Merge pull request #8436 from deepseek-harness/chore/cordis-root-gate

feat(infra): reject new Cordis root reads
This commit is contained in:
Shigma authored and GitHub committed 2026-11-13 17:44:59 +08:00
commit ce7bc84b10
12 files changed
+759 -2

No files matched your search

+83
View File
@@ -0,0 +1,83 @@
{
"apps/cli/tests/profiles/headless/tests/fixtures/subagent-settlement-fence.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 2
},
"apps/web/tests/default-product-isolation.e2e.ts": {
"d0b9e422bcad4455b7450e6bef2d6fa774afc3f44cdc75bc1d480c11b9fd0214": 1
},
"packages/api/gateway/tests/browser-credentials.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/api/gateway/tests/gateway.host.spec.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/api/gateway/tests/operator-connect.host.spec.ts": {
"a024beae6117bcaeaded2d59d0be04db10eae40e0d4b8ade0eb88fee7dfb9973": 1
},
"packages/api/gateway/tests/peer.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 4
},
"packages/api/session-controller/tests/transport.host.spec.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/boot/app-boot/tests/config-reload.spec.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/boot/config-editor/src/index.ts": {
"2ef15140c5ddf0d1c87a5c80055760aaae1fd5ed86c986c69115c27cfa13ee51": 3
},
"packages/boot/hmr/src/index.ts": {
"2ef15140c5ddf0d1c87a5c80055760aaae1fd5ed86c986c69115c27cfa13ee51": 1
},
"packages/boot/hmr/tests/package-reload.spec.ts": {
"08185f8ef80468685cfa5affb086454f655c61ab83ecb9f8cde15c9a573bd1be": 1
},
"packages/bundle/web-app/src/index.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 3
},
"packages/bundle/web-app/tests/browser-open.host.spec.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/client/connection/tests/node-half.host.spec.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 2
},
"packages/experimental/auto-review/src/index.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/experimental/auto-review/tests/auto-review.spec.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 2
},
"packages/experimental/inspector/src/shared/cordis/observer.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/host/authentication-token/src/index.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/host/authentication-token/tests/loader.host.spec.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 2
},
"packages/host/authentication-token/tests/plugin.host.spec.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/host/frontend-static/tests/frontend-static.spec.ts": {
"e9ced37d23b7f2f7af77caaa3c4ace319974f275186f14c1d32093f0658f73af": 1
},
"packages/mcp/mcp-client/src/index.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/preset/agent-preset-registry/src/mount.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/sdk/server/src/index.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/settings/settings/src/index.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 1
},
"packages/test-support/session-snapshot/tests/fixtures/subagent-send-message-fence.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 4
},
"packages/typert/protocol/src/index.ts": {
"3755d2978651498c26c74bf7d3552cae5dd33d7f28e3c405cd282098e40a7c58": 2
}
}
+11 -1
View File
@@ -383,7 +383,7 @@ describe('gate graph validation', () => {
'rescope-vendor', 'publint', 'constraints', 'default-product-isolation', 'product-use', 'official-bundle-catalog', 'provider-data', 'package-dependencies', 'application-entrypoints',
'dsh-package-licenses', 'node-next-types',
'optional-dependency-imports', 'client-packages', 'installer-locales', 'locale-metadata', 'client-ui-i18n', 'client-route-resolution', 'no-bare-dispatcher',
'plugin-record-callers', 'no-unknown-casts', 'empty-catch', 'no-top-level-await', 'plugin-entry-exports',
'plugin-record-callers', 'no-unknown-casts', 'empty-catch', 'cordis-root', 'no-top-level-await', 'plugin-entry-exports',
'cordis-config', 'runtime-closure',
])
})
@@ -459,6 +459,16 @@ describe('gate graph validation', () => {
},
)
it.each(['ci-primary', 'ci-static', 'check-all', 'hygiene'] as const)(
'rejects new Cordis root reads in %s',
(mode) => {
const gate = withPnpmEntrypoint(() => gatesForMode(mode).find(subject => subject.id === 'cordis-root'))
expect(gate?.args).toContain('verify-cordis-root')
expect(gate?.allowFailure).not.toBe(true)
},
)
it.each(['ci-primary', 'ci-static', 'check-all', 'hygiene'] as const)(
'keeps package dependency enforcement in %s',
(mode) => {
+1
View File
@@ -427,6 +427,7 @@ function sharedHygieneGates(): Gate[] {
pnpmScript('plugin-record-callers', 'verify-plugin-record-callers', { label: 'plugin record callers' }),
pnpmScript('no-unknown-casts', 'verify-no-unknown-casts', { label: 'no new unknown casts' }),
pnpmScript('empty-catch', 'verify-empty-catch', { label: 'no new silent catches' }),
pnpmScript('cordis-root', 'verify-cordis-root', { label: 'no new Cordis root reads' }),
pnpmScript('no-top-level-await', 'verify-no-top-level-await', { label: 'no module-scope await' }),
pnpmScript('plugin-entry-exports', 'verify-plugin-entry-exports', { label: 'plugin entry exports' }),
]
+198
View File
@@ -0,0 +1,198 @@
import { readFileSync, unlinkSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { createInventoryRepo, gitFixture as git, removeInventoryRepos, writeFixture as write } from './baseline-inventory.fixture.ts'
import {
CORDIS_ROOT_EXEMPTIONS,
countCordisRootReads,
findCordisRootReads,
scanCordisRootReads,
verifyCordisRoot,
} from './verify-cordis-root.ts'
const baselinePath = 'scripts/cordis-root.baseline.json'
const sourcePath = 'packages/example/src/index.ts'
const header = "import { Context } from '@deepseek-ai/cordis'\n"
const read = `${header}export const root = (ctx: Context) => ctx[Context.root]\n`
const none = {}
afterEach(removeInventoryRepos)
function fixture(): string {
return createInventoryRepo(baselinePath, 'export {}\n')
}
function recordBaseline(root: string): string {
const text = `${JSON.stringify(countCordisRootReads(scanCordisRootReads(root, none)), null, 2)}\n`
write(root, baselinePath, text)
return text
}
describe('Cordis root read syntax', () => {
it.each([
['an element access', `${header}ctx[Context.root]`, 1],
['a property chain through the root', `${header}ctx[Context.root].loader.await()`, 1],
['a bare symbol read', `${header}const key = Context.root`, 1],
['a parenthesized class', `${header}ctx[(Context).root]`, 1],
['a string-keyed read', `${header}ctx[Context['root']]`, 1],
['a destructured read', `${header}const { root } = Context`, 1],
['a renamed destructured read', `${header}const { root: key } = Context`, 1],
['a renamed import', "import { Context as CordisContext } from '@deepseek-ai/cordis'\nctx[CordisContext.root]", 1],
['a namespace import', "import * as cordis from '@deepseek-ai/cordis'\nctx[cordis.Context.root]", 1],
['a global symbol key', "ctx[Symbol.for('cordis.root')]", 1],
['a template symbol key', 'ctx[Symbol.for(`cordis.root`)]', 1],
['a symbol key held in a constant', "const key = 'cordis.root'", 1],
['several reads', `${header}ctx[Context.root].on('a', f); ctx[Context.root].on('b', g)`, 2],
['a TSX expression', `${header}export const view = <View ctx={ctx[Context.root]} />`, 1],
['the symbols table', "import { symbols } from '@deepseek-ai/cordis'\nctx[symbols.root]", 1],
['a renamed symbols table', "import { symbols as cordisSymbols } from '@deepseek-ai/cordis'\nctx[cordisSymbols['root']]", 1],
['the symbols table of a namespace', "import * as cordis from '@deepseek-ai/cordis'\nctx[cordis.symbols.root]", 1],
['root destructured from the symbols table', "import { symbols } from '@deepseek-ai/cordis'\nconst { root } = symbols", 1],
['a subpath import', "import { Context } from '@deepseek-ai/cordis/src/index.ts'\nctx[Context.root]", 1],
['a default import', "import cordis from '@deepseek-ai/cordis'\nctx[cordis.Context.root]", 1],
['an import-equals namespace', "import cordis = require('@deepseek-ai/cordis')\nctx[cordis.Context.root]", 1],
['a destructured dynamic import', "const { Context } = await import('@deepseek-ai/cordis')\nctx[Context.root]", 1],
['a renamed destructured dynamic import', "const { Context: C } = await import('@deepseek-ai/cordis')\nctx[C.root]", 1],
['a namespace dynamic import', "const cordis = await import('@deepseek-ai/cordis')\nctx[cordis.Context.root]", 1],
['a destructured require', "const { Context } = require('@deepseek-ai/cordis')\nctx[Context.root]", 1],
['a destructuring assignment', `${header}let key; ({ root: key } = Context)`, 1],
['a shorthand destructuring assignment', `${header}let root; ({ root } = Context)`, 1],
['a parameter default', `${header}function f({ root } = Context) { return root }`, 1],
['a nested binding default', `${header}const { a: { root } = Context } = value`, 1],
['a computed class member', `${header}class Holder { [Context.root] = undefined }`, 1],
['a class extends clause', `${header}class Holder extends mixin(Context.root) {}`, 1],
])('finds %s', (_name, text, count) => {
expect(findCordisRootReads('input.tsx', text)).toHaveLength(count)
})
it.each([
['comments', `${header}// ctx[Context.root]\n/* Symbol.for('cordis.root') */`],
['strings that mention the root', `${header}const text = 'ctx[Context.root]'`],
['source text embedded in a template', "const code = `ctx[Symbol.for('cordis.root')]`"],
['a type query', `${header}type Root = typeof Context.root`],
['a literal type', "type Key = 'cordis.root'"],
['a type-only import', "import type { Context } from '@deepseek-ai/cordis'\nctx[Context.root]"],
['a type-only specifier', "import { type Context } from '@deepseek-ai/cordis'\nctx[Context.root]"],
['a Context from another module', "import { Context } from './context.ts'\nctx[Context.root]"],
['another static of Context', `${header}ctx[Context.isolate]`],
['a root member of another value', `${header}const dir = project.root`],
['a destructured root of another value', `${header}const { root } = project`],
['a parameter that shadows the import', `${header}function f(Context: { root: string }) { return Context.root }`],
['a local that shadows the import', `${header}{ const Context = project; Context.root }`],
['a parameter that shadows a namespace', "import * as cordis from '@deepseek-ai/cordis'\nfunction f(cordis: any) { return cordis.Context.root }"],
['an interface member', `${header}interface Holder { [Context.root]: Context }`],
['a type literal member', `${header}type Holder = { [Context.root]: Context }`],
['an ambient class member', `${header}declare class Holder { [Context.root]: Context }`],
['an ambient module member', `${header}declare module 'x' { const key: typeof Context.root; export const value = Context.root }`],
['an ambient class field', `${header}class Holder { declare [Context.root]: Context }`],
['an implements clause', `${header}class Holder implements Base<typeof Context.root> {}`],
['another member of the symbols table', "import { symbols } from '@deepseek-ai/cordis'\nctx[symbols.original]"],
['a dynamic import of another module', "const { Context } = await import('./context.ts')\nctx[Context.root]"],
['a destructuring assignment of another member', `${header}let isolate; ({ isolate } = Context)`],
])('ignores %s', (_name, text) => {
expect(findCordisRootReads('input.ts', text)).toEqual([])
})
it('resolves bindings in JavaScript modules', () => {
expect(findCordisRootReads('input.mjs', "const { Context } = await import('@deepseek-ai/cordis')\nctx[Context.root]")).toHaveLength(1)
expect(findCordisRootReads('input.cjs', "const { symbols } = require('@deepseek-ai/cordis')\nfunction f(symbols) { return symbols.root }")).toEqual([])
})
it('skips declaration files', () => {
expect(findCordisRootReads('input.d.ts', `${header}export declare const key: typeof Context.root\nexport const value = Context.root`)).toEqual([])
})
it('reports normalized paths and the read line', () => {
const [found] = findCordisRootReads('packages\\example\\index.ts', `${header}\nctx[Context.root]`)
expect(found).toMatchObject({ file: 'packages/example/index.ts', line: 3 })
expect(found?.fingerprint).toMatch(/^[a-f0-9]{64}$/u)
})
it('identifies a read by its receiver', () => {
const fingerprint = (text: string): string | undefined => findCordisRootReads('input.ts', `${header}${text}`)[0]?.fingerprint
expect(fingerprint('ctx[\n Context.root /* root */ ]')).toBe(fingerprint('ctx[Context.root]'))
expect(fingerprint('ctx[Context.root].loader')).toBe(fingerprint('ctx[Context.root].fiber'))
expect(fingerprint('other[Context.root]')).not.toBe(fingerprint('ctx[Context.root]'))
expect(findCordisRootReads('input.ts', "other[Symbol.for('cordis.root')]")[0]?.fingerprint)
.not.toBe(findCordisRootReads('input.ts', "ctx[Symbol.for('cordis.root')]")[0]?.fingerprint)
})
})
describe('Cordis root read inventory', () => {
it('accepts a recorded read after formatting without rewriting the baseline', () => {
const root = fixture()
write(root, sourcePath, read)
const baseline = recordBaseline(root)
write(root, sourcePath, `${header}export const root = (ctx: Context) => ctx[\n Context.root\n]\n`)
expect(verifyCordisRoot(root, false, none)).toBe(1)
expect(verifyCordisRoot(root, true, none)).toBe(1)
expect(readFileSync(join(root, baselinePath), 'utf8')).toBe(baseline)
})
it.each([
['another copy of a recorded read', `${read}export const again = (ctx: Context) => ctx[Context.root]\n`],
['a read through another receiver', `${header}export const root = (other: Context) => other[Context.root]\n`],
['a global symbol key read', "export const root = (ctx: object) => Reflect.get(ctx, Symbol.for('cordis.root'))\n"],
])('rejects %s without changing the baseline', (_name, text) => {
const root = fixture()
write(root, sourcePath, read)
const baseline = recordBaseline(root)
write(root, sourcePath, text)
expect(() => verifyCordisRoot(root, false, none)).toThrow(/verify-cordis-root: new reads of the Cordis root context/u)
expect(() => verifyCordisRoot(root, true, none)).toThrow(/verify-cordis-root: new reads of the Cordis root context/u)
expect(readFileSync(join(root, baselinePath), 'utf8')).toBe(baseline)
})
it('rejects a new read when the inventory is empty', () => {
const root = fixture()
write(root, sourcePath, read)
expect(() => verifyCordisRoot(root, false, none)).toThrow(`${sourcePath}:2`)
})
it('requires pruning a fixed read', () => {
const root = fixture()
write(root, sourcePath, read)
git(root, 'add', sourcePath)
recordBaseline(root)
write(root, sourcePath, 'export {}\n')
expect(() => verifyCordisRoot(root, false, none)).toThrow(/remove retired baseline entries/u)
expect(verifyCordisRoot(root, true, none)).toBe(0)
expect(readFileSync(join(root, baselinePath), 'utf8')).toBe('{}\n')
})
it('excludes vendored source', () => {
const root = fixture()
write(root, 'vendor/cordis/src/index.ts', read)
git(root, 'add', '.')
expect(verifyCordisRoot(root, false, none)).toBe(0)
})
})
describe('Cordis root read exemptions', () => {
const exemptPath = 'scripts/root-contract.spec.ts'
const exemptions = { [exemptPath]: 'pins the root contract' }
it('leaves an exempt file unscanned', () => {
const root = fixture()
write(root, exemptPath, read)
expect(scanCordisRootReads(root, exemptions)).toEqual([])
expect(verifyCordisRoot(root, false, exemptions)).toBe(0)
})
it.each([
['no longer reads the root', (root: string) => { write(root, exemptPath, 'export {}\n') }],
['is deleted', (root: string) => { write(root, exemptPath, read); unlinkSync(join(root, exemptPath)) }],
])('rejects an exemption whose file %s', (_name, change) => {
const root = fixture()
change(root)
expect(() => verifyCordisRoot(root, false, exemptions))
.toThrow(`verify-cordis-root: exempt file ${exemptPath} no longer reads the root context`)
})
it('names only files that read the root in this repository', () => {
const root = join(import.meta.dirname, '..')
for (const file of Object.keys(CORDIS_ROOT_EXEMPTIONS)) {
expect(findCordisRootReads(file, readFileSync(join(root, file), 'utf8')).length).toBeGreaterThan(0)
}
})
})
+320
View File
@@ -0,0 +1,320 @@
/**
* Reject new reads of the Cordis root context, retiring the recorded existing reads.
*
* A read names the root symbol through a Cordis value binding: `Context.root` or `symbols.root`,
* their `['root']` forms, or `root` destructured from either in a declaration, a parameter default,
* or an assignment. A binding comes from `@deepseek-ai/cordis` or one of its subpaths through a
* static import, including renamed and namespace imports, or through a destructured or namespace
* `import()` or `require()` result. References resolve through the file's own scopes, so a local
* that shadows the import is not a binding. Any string literal whose value is exactly `cordis.root`,
* the global symbol key behind `Symbol.for('cordis.root')`, is also a read. Type positions,
* interfaces, type aliases, and ambient declarations are erased and contain no reads.
*
* The check is syntactic: a root context reached through another value, such as a stored
* reference, an alias of `Context`, a service that returns it, or source text assembled at run
* time, is outside it.
*
* A finding's identity covers the syntax tokens of the access to the root: the element access whose
* key is the root symbol when one encloses it, otherwise the read itself. Existing reads are
* recorded in `scripts/cordis-root.baseline.json`; the files in {@link CORDIS_ROOT_EXEMPTIONS} pin
* the root contract itself and are not scanned.
*/
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import ts from 'typescript'
import {
countInventory,
listInventorySources,
runInventoryGate,
syntaxFingerprint,
verifyInventory,
type InventoryBaseline,
type InventoryGate,
} from './baseline-inventory.ts'
const root = resolve(import.meta.dirname, '..')
/** Package that exports the Cordis `Context` class and the `symbols` table. */
const CORDIS_MODULE = '@deepseek-ai/cordis'
/** Global symbol key of `Context.root`. */
const ROOT_SYMBOL_KEY = 'cordis.root'
/** Cordis exports that hold the root symbol as their `root` member. */
const ROOT_HOLDERS = new Set(['Context', 'symbols'])
/**
* Files that exercise the root context itself, keyed by repository path, with the reason each needs
* it. A key whose file no longer reads the root fails the gate.
*/
export const CORDIS_ROOT_EXEMPTIONS: Readonly<Record<string, string>> = {
'scripts/cordis-core-rc12.spec.ts': 'pins the vendored Cordis `Context.root` symbol and its `Symbol.for` key',
'scripts/verify-cordis-root.ts': 'names the root symbol key this gate detects',
}
/** Existing root-read counts, keyed by repository path and syntax fingerprint. */
export type CordisRootBaseline = InventoryBaseline
/** One read of the Cordis root context in authored source. */
export interface CordisRootRead {
/** Repository-relative path with forward slashes. */
file: string
/** One-based source line. */
line: number
/** SHA-256 of the access's syntax tokens, excluding comments and whitespace. */
fingerprint: string
}
/** Declared symbols that refer to a Cordis root holder or to the Cordis module namespace. */
interface CordisBindings {
checker: ts.TypeChecker
holders: Set<ts.Symbol>
namespaces: Set<ts.Symbol>
}
function isCordisSpecifier(node: ts.Node | undefined): boolean {
return node !== undefined && ts.isStringLiteralLike(node)
&& (node.text === CORDIS_MODULE || node.text.startsWith(`${CORDIS_MODULE}/`))
}
/** Whether an initializer evaluates to the Cordis module: `import()`, `await import()`, or `require()`. */
function loadsCordis(node: ts.Expression): boolean {
if (ts.isParenthesizedExpression(node) || ts.isAwaitExpression(node)) return loadsCordis(node.expression)
if (!ts.isCallExpression(node) || node.arguments.length === 0) return false
const callee = node.expression
const loader = callee.kind === ts.SyntaxKind.ImportKeyword || (ts.isIdentifier(callee) && callee.text === 'require')
return loader && isCordisSpecifier(node.arguments[0])
}
function propertyText(name: ts.PropertyName | ts.BindingName): string | undefined {
if (ts.isIdentifier(name) || ts.isStringLiteralLike(name)) return name.text
if (ts.isComputedPropertyName(name) && ts.isStringLiteralLike(name.expression)) return name.expression.text
return undefined
}
/** Type-check one file in isolation, so references resolve through its own scopes only. */
function isolatedChecker(source: ts.SourceFile): ts.TypeChecker {
const options: ts.CompilerOptions = { allowJs: true, noLib: true, noResolve: true, types: [] }
const host: ts.CompilerHost = {
getSourceFile: fileName => (fileName === source.fileName ? source : undefined),
getDefaultLibFileName: () => 'lib.d.ts',
writeFile: () => undefined,
getCurrentDirectory: () => '/',
getCanonicalFileName: fileName => fileName,
useCaseSensitiveFileNames: () => true,
getNewLine: () => '\n',
fileExists: fileName => fileName === source.fileName,
readFile: () => undefined,
}
return ts.createProgram({ rootNames: [source.fileName], options, host }).getTypeChecker()
}
function cordisBindings(source: ts.SourceFile): CordisBindings | undefined {
if (!source.text.includes(CORDIS_MODULE)) return undefined
const checker = isolatedChecker(source)
const bindings: CordisBindings = { checker, holders: new Set(), namespaces: new Set() }
const add = (set: Set<ts.Symbol>, name: ts.Identifier): void => {
const symbol = checker.getSymbolAtLocation(name)
if (symbol !== undefined) set.add(symbol)
}
const visit = (node: ts.Node): void => {
if (ts.isImportDeclaration(node) && isCordisSpecifier(node.moduleSpecifier)) {
const clause = node.importClause
if (clause === undefined || clause.phaseModifier === ts.SyntaxKind.TypeKeyword) return
if (clause.name !== undefined) add(bindings.namespaces, clause.name)
if (clause.namedBindings !== undefined && ts.isNamespaceImport(clause.namedBindings)) {
add(bindings.namespaces, clause.namedBindings.name)
} else {
for (const element of clause.namedBindings?.elements ?? []) {
if (!element.isTypeOnly && ROOT_HOLDERS.has((element.propertyName ?? element.name).text)) {
add(bindings.holders, element.name)
}
}
}
return
}
if (ts.isImportEqualsDeclaration(node) && !node.isTypeOnly && ts.isExternalModuleReference(node.moduleReference)
&& isCordisSpecifier(node.moduleReference.expression)) {
add(bindings.namespaces, node.name)
return
}
if (ts.isVariableDeclaration(node) && node.initializer !== undefined && loadsCordis(node.initializer)) {
if (ts.isIdentifier(node.name)) add(bindings.namespaces, node.name)
else if (ts.isObjectBindingPattern(node.name)) {
for (const element of node.name.elements) {
const exported = propertyText(element.propertyName ?? element.name)
if (exported !== undefined && ROOT_HOLDERS.has(exported) && ts.isIdentifier(element.name)) {
add(bindings.holders, element.name)
}
}
}
}
ts.forEachChild(node, visit)
}
visit(source)
return bindings.holders.size + bindings.namespaces.size === 0 ? undefined : bindings
}
function refersTo(node: ts.Identifier, set: Set<ts.Symbol>, bindings: CordisBindings): boolean {
const symbol = bindings.checker.getSymbolAtLocation(node)
return symbol !== undefined && set.has(symbol)
}
/** Whether an expression evaluates to `Context` or `symbols` from Cordis. */
function isRootHolder(node: ts.Expression, bindings: CordisBindings): boolean {
if (ts.isParenthesizedExpression(node)) return isRootHolder(node.expression, bindings)
if (ts.isIdentifier(node)) return refersTo(node, bindings.holders, bindings)
const member = ts.isPropertyAccessExpression(node) ? node.name.text
: ts.isElementAccessExpression(node) && ts.isStringLiteralLike(node.argumentExpression) ? node.argumentExpression.text
: undefined
if (member === undefined || !ROOT_HOLDERS.has(member)) return false
const namespace = (node as ts.PropertyAccessExpression | ts.ElementAccessExpression).expression
return ts.isIdentifier(namespace) && refersTo(namespace, bindings.namespaces, bindings)
}
function isRootKey(node: ts.Expression): boolean {
return ts.isStringLiteralLike(node) && node.text === 'root'
}
function bindsRoot(pattern: ts.ObjectBindingPattern): boolean {
return pattern.elements.some(element => propertyText(element.propertyName ?? element.name) === 'root')
}
function assignsRoot(pattern: ts.ObjectLiteralExpression): boolean {
return pattern.properties.some((property) => {
if (ts.isShorthandPropertyAssignment(property)) return property.name.text === 'root'
return ts.isPropertyAssignment(property) && propertyText(property.name) === 'root'
})
}
function readsRoot(node: ts.Node, bindings: CordisBindings | undefined): boolean {
if (ts.isStringLiteralLike(node)) return node.text === ROOT_SYMBOL_KEY
if (bindings === undefined) return false
if (ts.isPropertyAccessExpression(node)) return node.name.text === 'root' && isRootHolder(node.expression, bindings)
if (ts.isElementAccessExpression(node)) return isRootKey(node.argumentExpression) && isRootHolder(node.expression, bindings)
if (ts.isVariableDeclaration(node) || ts.isParameter(node) || ts.isBindingElement(node)) {
return node.initializer !== undefined && ts.isObjectBindingPattern(node.name) && bindsRoot(node.name)
&& isRootHolder(node.initializer, bindings)
}
return ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken
&& ts.isObjectLiteralExpression(node.left) && assignsRoot(node.left) && isRootHolder(node.right, bindings)
}
/** Whether a subtree is erased from the emitted program, so it contains no reads. */
function isErased(node: ts.Node): boolean {
if (ts.isSourceFile(node)) return node.isDeclarationFile
if (ts.canHaveModifiers(node) && ts.getModifiers(node)?.some(modifier => modifier.kind === ts.SyntaxKind.DeclareKeyword)) {
return true
}
if (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) return true
// A class `extends` clause evaluates its expression; every other type node is erased.
if (ts.isExpressionWithTypeArguments(node)) {
return !(ts.isHeritageClause(node.parent) && node.parent.token === ts.SyntaxKind.ExtendsKeyword
&& ts.isClassLike(node.parent.parent))
}
return ts.isTypeNode(node)
}
/** The expression whose tokens identify a read: an element access keyed by the root, or the read. */
function accessOf(node: ts.Node): ts.Node {
let current = node
while (ts.isParenthesizedExpression(current.parent) || (ts.isCallExpression(current.parent)
&& current.parent.arguments.length === 1 && current.parent.arguments[0] === current)) {
current = current.parent
}
const parent = current.parent
return ts.isElementAccessExpression(parent) && parent.argumentExpression === current ? parent : node
}
/**
* Find reads of the Cordis root context.
* @param file - repository-relative source path; its extension selects TS or TSX parsing.
* @param text - source contents.
* @returns reads in AST traversal order; comments, erased type syntax, shadowed names, and strings
* other than the exact root symbol key do not match.
*/
export function findCordisRootReads(file: string, text: string): CordisRootRead[] {
const normalized = file.replaceAll('\\', '/')
const source = ts.createSourceFile(`/${normalized}`, text, ts.ScriptTarget.Latest, true)
const bindings = cordisBindings(source)
const reads: CordisRootRead[] = []
const record = (node: ts.Node): void => {
reads.push({
file: normalized,
line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
fingerprint: syntaxFingerprint(accessOf(node), source),
})
}
const visit = (node: ts.Node): void => {
if (isErased(node)) return
if (readsRoot(node, bindings)) record(node)
ts.forEachChild(node, visit)
}
visit(source)
return reads
}
/**
* Scan tracked source and non-ignored new source, including tests and configuration files.
* @param repoRoot - repository root containing the Git index.
* @param exemptions - repository paths left unscanned, each of which must still read the root.
* @returns every root read outside the exempt files.
* @throws if discovery omits a required source area, an eligible path is a symlink, or an exempt
* file is missing or no longer reads the root.
*/
export function scanCordisRootReads(
repoRoot: string,
exemptions: Readonly<Record<string, string>> = CORDIS_ROOT_EXEMPTIONS,
): CordisRootRead[] {
const files = listInventorySources(repoRoot, 'verify-cordis-root')
const reads = files.flatMap(file => findCordisRootReads(file, readFileSync(resolve(repoRoot, file), 'utf8')))
for (const file of Object.keys(exemptions)) {
if (!reads.some(read => read.file === file)) {
throw new Error(`verify-cordis-root: exempt file ${file} no longer reads the root context; remove its exemption`)
}
}
return reads.filter(read => !Object.hasOwn(exemptions, read.file))
}
function createGate(exemptions: Readonly<Record<string, string>>): InventoryGate<CordisRootRead> {
return {
name: 'verify-cordis-root',
baselinePath: 'scripts/cordis-root.baseline.json',
scan: repoRoot => scanCordisRootReads(repoRoot, exemptions),
rejection: 'new reads of the Cordis root context are forbidden. Declare the service in `inject`,'
+ ' register through the plugin context, or use `{ global: true }` for an unscoped listener'
+ ' (see docs/defensive-patterns/general.md#plugins-do-not-read-the-cordis-root-context).',
describe: read => `${read.file}:${String(read.line)} (${read.fingerprint})`,
success: count => `verify-cordis-root: no new root reads; ${String(count)} recorded reads remain.`,
}
}
/**
* Count exact reads without granting a file-wide allowance.
* @param reads - observed root reads.
* @returns path and fingerprint counts in stable order for comparison and pruning.
*/
export function countCordisRootReads(reads: readonly CordisRootRead[]): CordisRootBaseline {
return countInventory(reads)
}
/**
* Enforce the recorded root-read inventory, optionally deleting retired allowances.
* @param repoRoot - repository root to scan.
* @param prune - remove stale entries only after establishing that no new read exists.
* @param exemptions - repository paths left unscanned, each of which must still read the root.
* @returns the number of recorded reads still present.
* @throws for new reads, malformed inventories, stale entries without pruning, or stale exemptions.
*/
export function verifyCordisRoot(
repoRoot: string,
prune = false,
exemptions: Readonly<Record<string, string>> = CORDIS_ROOT_EXEMPTIONS,
): number {
return verifyInventory(createGate(exemptions), repoRoot, prune)
}
if (import.meta.filename === resolve(process.argv[1] ?? '')) {
runInventoryGate(createGate(CORDIS_ROOT_EXEMPTIONS), root)
}