forked from cflmy/deepseek-harness
feat(infra): reject new Cordis root reads
This commit is contained in:
1 parent
39163dd30f
commit
a29dafde97
9 files changed
+552
-1
No files matched your search
@@ -0,0 +1,19 @@
|
||||
# Bilingual-pair consistency record for 2026-11-13-no-new-cordis-root-reads.md (docs/i18n/README.md): per heading
|
||||
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
|
||||
# After editing either side, bring the other along and re-record with:
|
||||
# pnpm run verify-translation-pairing --write .agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.md
|
||||
/agent-note-prohibit-new-reads-of-the-cordis-root-context:
|
||||
en: b46331d0804f9d45
|
||||
zh: d8b3d8a47541c838
|
||||
/agent-note-prohibit-new-reads-of-the-cordis-root-context/problem:
|
||||
en: c6935cb7ef54f299
|
||||
zh: 214ed828b3201539
|
||||
/agent-note-prohibit-new-reads-of-the-cordis-root-context/decision:
|
||||
en: 9b3238a642603e28
|
||||
zh: a4b5601157f621b7
|
||||
/agent-note-prohibit-new-reads-of-the-cordis-root-context/alternatives-considered:
|
||||
en: 81d959fa34f3e682
|
||||
zh: 861f22528134e255
|
||||
/agent-note-prohibit-new-reads-of-the-cordis-root-context/consequences:
|
||||
en: d85154ce0a279c1f
|
||||
zh: 7672ff57971ef221
|
||||
@@ -0,0 +1,31 @@
|
||||
# Agent Note: Prohibit new reads of the Cordis root context
|
||||
|
||||
Status: implemented
|
||||
|
||||
English | [中文](2026-11-13-no-new-cordis-root-reads.zh.md)
|
||||
|
||||
## Problem
|
||||
|
||||
`ctx[Context.root]` returns the application's root context. A property read through it skips the `inject` check, because the root fiber has no runtime; a listener registered on it skips scope filtering; and it reads the root realm instead of the caller's isolate realm. DSH code uses it to read undeclared services, to listen to every Agent's events, to key per-application state, and to call boot APIs that require the root context. Each of these uses has, or needs, a declared replacement: an `inject` entry, `{ global: true }` on a listener, or a service that owns the root-level operation.
|
||||
|
||||
The repository contains such reads across boot, host, preset, protocol, experimental, and test owners. Replacing all of them in one change would combine the enforcement decision with several service designs.
|
||||
|
||||
## Decision
|
||||
|
||||
New reads of the Cordis root context are prohibited in first-party JavaScript and TypeScript, including tests, fixtures, and scripts. The [checker](../../../../scripts/verify-cordis-root.ts), exposed as `pnpm run verify-cordis-root`, uses the TypeScript syntax tree. A read is `Context.root`, `Context['root']`, or a destructured `root` on a value binding of `Context` imported from `@deepseek-ai/cordis`, including renamed and namespace imports, and any string literal whose value is exactly `cordis.root`, the key behind `Symbol.for('cordis.root')`. Type positions, comments, other strings, and source text embedded in a template are not reads.
|
||||
|
||||
Existing reads have an exact baseline in `scripts/cordis-root.baseline.json`, kept by [the shared inventory module](../../../../scripts/baseline-inventory.ts) under the rules of the [unknown-cast inventory](2026-09-19-no-unknown-casts.md): baseline edits only delete entries or decrease counts, `--prune` removes retired entries and refuses to write while new reads exist, and no command adds an allowance. A read's fingerprint covers the tokens of the element access whose key is the root symbol, so a recorded read moved to another receiver is a new finding.
|
||||
|
||||
Files that exercise the root contract itself are listed with a reason in `CORDIS_ROOT_EXEMPTIONS` inside the checker and are not scanned: the Cordis rc.12 specification and the checker. An exemption whose file no longer reads the root fails the gate. Vendored sources and frozen archived Agent Notes keep their inventory exclusions. The checker runs in CI static and primary modes and the local `hygiene` and `check-all` profiles in [the gate runner](../../../../scripts/run-gates.ts).
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
**Replace every existing read before enforcing the rule.** Rejected because several replacements need new services, such as a profile-composition service for the boot APIs and an application-lifecycle signal; enforcing first stops new reads while those designs are reviewed separately.
|
||||
|
||||
**Use the `no-restricted-properties` lint rule.** Rejected because it matches the identifier `Context` by name, so a renamed import such as `CordisContext` passes, and it cannot match `Symbol.for('cordis.root')`.
|
||||
|
||||
**Record the exempt files in the baseline.** Rejected because the baseline only shrinks, while the exempt files are expected to keep their reads; keeping them apart lets the baseline reach empty.
|
||||
|
||||
## Consequences
|
||||
|
||||
Owners must remove a recorded read before changing its receiver or moving it into an unlisted file, and prune its entry after removal. Passing the check establishes that no unlisted syntactic root read exists. It does not detect a root context obtained through another value, such as a stored reference, a service that returns it, or code assembled from strings at runtime.
|
||||
@@ -0,0 +1,31 @@
|
||||
# Agent Note: 禁止新增对 Cordis 根上下文的读取
|
||||
|
||||
Status: implemented
|
||||
|
||||
[English](2026-11-13-no-new-cordis-root-reads.md) | 中文
|
||||
|
||||
## 问题
|
||||
|
||||
`ctx[Context.root]` 返回应用的根上下文。通过它读取属性会跳过 `inject` 检查,因为根 fiber 没有 runtime;在它上面注册的监听器会跳过 scope 过滤;它读取的是根 realm,而不是调用方所在的 isolate realm。DSH 代码用它读取未声明的服务、监听所有 Agent 的事件、作为应用级状态的键,以及调用要求根上下文的启动 API。这些用法都已有或需要一个显式声明的替代方式:`inject` 条目、监听器上的 `{ global: true }`,或负责根级操作的服务。
|
||||
|
||||
仓库中的此类读取分布在 boot、host、preset、protocol、experimental 和测试等多个所有者中。在一次变更中全部替换,会把执行规则的决定与多个服务设计混在一起。
|
||||
|
||||
## 决定
|
||||
|
||||
第一方 JavaScript 和 TypeScript(包括测试、fixture 和脚本)禁止新增对 Cordis 根上下文的读取。[检查器](../../../../scripts/verify-cordis-root.ts)通过 `pnpm run verify-cordis-root` 运行,使用 TypeScript 语法树。读取指:对从 `@deepseek-ai/cordis` 导入的 `Context` 值绑定(包括重命名导入和命名空间导入)的 `Context.root`、`Context['root']` 或解构出的 `root`,以及值恰为 `cordis.root` 的任何字符串字面量,即 `Symbol.for('cordis.root')` 背后的键。类型位置、注释、其他字符串以及嵌入模板中的源码文本不算读取。
|
||||
|
||||
现有读取使用 `scripts/cordis-root.baseline.json` 中的精确基线记录,由[共享清单模块](../../../../scripts/baseline-inventory.ts)按 [unknown 类型断言清单](2026-09-19-no-unknown-casts.zh.md)的规则维护:基线修改只能删除条目或减少次数,`--prune` 删除已失效的条目并在存在新读取时拒绝写入,且没有任何命令可以添加放行。读取的指纹覆盖以根符号为键的元素访问的 token,因此把已记录的读取换到另一个接收者上会产生新的检查发现。
|
||||
|
||||
测试根上下文约定本身的文件在检查器内的 `CORDIS_ROOT_EXEMPTIONS` 中逐个列出并注明原因,不参与扫描:Cordis rc.12 规范测试和检查器本身。若豁免文件不再读取根上下文,门禁失败。vendored 源码和已冻结的归档 Agent Notes 保留清单的排除规则。检查器参与[门禁运行器](../../../../scripts/run-gates.ts)中的 CI static 和 primary 模式以及本地 `hygiene` 和 `check-all` 配置。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**在执行规则前替换所有现有读取。** 已否决,因为部分替换需要新的服务,例如供启动 API 使用的 profile 组合服务和应用生命周期信号;先执行规则可以阻止新增读取,同时单独评审这些设计。
|
||||
|
||||
**使用 `no-restricted-properties` lint 规则。** 已否决,因为它按名称匹配标识符 `Context`,重命名导入(如 `CordisContext`)可以绕过,而且无法匹配 `Symbol.for('cordis.root')`。
|
||||
|
||||
**把豁免文件记入基线。** 已否决,因为基线只会缩小,而豁免文件预期会保留其读取;分开维护可以让基线最终清空。
|
||||
|
||||
## 影响
|
||||
|
||||
所有者在更换已记录读取的接收者或将其移入未登记的文件之前,必须先移除该读取,并在移除后裁剪其条目。通过此检查表明不存在未登记的语法层面的根读取。它无法检测通过其他值获得的根上下文,例如保存的引用、返回根上下文的服务,或运行时由字符串拼装的代码。
|
||||
@@ -112,6 +112,7 @@
|
||||
"verify-concrete-terms": "tsx scripts/verify-concrete-terms.ts",
|
||||
"verify-no-unknown-casts": "tsx scripts/verify-no-unknown-casts.ts",
|
||||
"verify-empty-catch": "tsx scripts/verify-empty-catch.ts",
|
||||
"verify-cordis-root": "tsx scripts/verify-cordis-root.ts",
|
||||
"verify-doc-refs": "tsx scripts/verify-doc-refs.ts",
|
||||
"verify-subsystem-pages": "tsx scripts/verify-subsystem-pages.ts",
|
||||
"verify-package-paths": "tsx scripts/verify-package-paths.ts",
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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) => {
|
||||
|
||||
@@ -425,6 +425,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' }),
|
||||
]
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
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],
|
||||
])('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`],
|
||||
])('ignores %s', (_name, text) => {
|
||||
expect(findCordisRootReads('input.ts', text)).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)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* Reject new reads of the Cordis root context, retiring the recorded existing reads.
|
||||
*
|
||||
* A read is `Context.root`, `Context['root']`, or a destructured `root` on a value binding of
|
||||
* `Context` imported from `@deepseek-ai/cordis`, including a renamed or namespace import, and any
|
||||
* string literal whose value is exactly `cordis.root`, the global symbol key behind
|
||||
* `Symbol.for('cordis.root')`. Type positions such as `typeof Context.root` are not reads.
|
||||
*
|
||||
* 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, '..')
|
||||
|
||||
/** Module that exports the Cordis `Context` class. */
|
||||
const CORDIS_MODULE = '@deepseek-ai/cordis'
|
||||
|
||||
/** Global symbol key of `Context.root`. */
|
||||
const ROOT_SYMBOL_KEY = 'cordis.root'
|
||||
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
|
||||
/** Local names that refer to the Cordis `Context` value or to the Cordis module namespace. */
|
||||
interface CordisBindings {
|
||||
context: Set<string>
|
||||
namespace: Set<string>
|
||||
}
|
||||
|
||||
function cordisBindings(source: ts.SourceFile): CordisBindings {
|
||||
const bindings: CordisBindings = { context: new Set(), namespace: new Set() }
|
||||
for (const statement of source.statements) {
|
||||
if (!ts.isImportDeclaration(statement) || statement.importClause === undefined) continue
|
||||
if (!ts.isStringLiteral(statement.moduleSpecifier) || statement.moduleSpecifier.text !== CORDIS_MODULE) continue
|
||||
const clause = statement.importClause
|
||||
if (clause.phaseModifier === ts.SyntaxKind.TypeKeyword || clause.namedBindings === undefined) continue
|
||||
if (ts.isNamespaceImport(clause.namedBindings)) {
|
||||
bindings.namespace.add(clause.namedBindings.name.text)
|
||||
continue
|
||||
}
|
||||
for (const element of clause.namedBindings.elements) {
|
||||
if (!element.isTypeOnly && (element.propertyName ?? element.name).text === 'Context') {
|
||||
bindings.context.add(element.name.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
return bindings
|
||||
}
|
||||
|
||||
function isContextValue(node: ts.Expression, bindings: CordisBindings): boolean {
|
||||
if (ts.isParenthesizedExpression(node)) return isContextValue(node.expression, bindings)
|
||||
if (ts.isIdentifier(node)) return bindings.context.has(node.text)
|
||||
return ts.isPropertyAccessExpression(node) && node.name.text === 'Context'
|
||||
&& ts.isIdentifier(node.expression) && bindings.namespace.has(node.expression.text)
|
||||
}
|
||||
|
||||
function isRootKey(node: ts.Expression): boolean {
|
||||
return ts.isStringLiteralLike(node) && node.text === 'root'
|
||||
}
|
||||
|
||||
function bindsRoot(pattern: ts.ObjectBindingPattern): boolean {
|
||||
return pattern.elements.some((element) => {
|
||||
const name = element.propertyName ?? element.name
|
||||
if (ts.isIdentifier(name) || ts.isStringLiteralLike(name)) return name.text === 'root'
|
||||
return ts.isComputedPropertyName(name) && isRootKey(name.expression)
|
||||
})
|
||||
}
|
||||
|
||||
function readsRoot(node: ts.Node, bindings: CordisBindings): boolean {
|
||||
if (ts.isPropertyAccessExpression(node)) return node.name.text === 'root' && isContextValue(node.expression, bindings)
|
||||
if (ts.isElementAccessExpression(node)) return isRootKey(node.argumentExpression) && isContextValue(node.expression, bindings)
|
||||
if (ts.isVariableDeclaration(node)) {
|
||||
return node.initializer !== undefined && ts.isObjectBindingPattern(node.name) && bindsRoot(node.name)
|
||||
&& isContextValue(node.initializer, bindings)
|
||||
}
|
||||
return ts.isStringLiteralLike(node) && node.text === ROOT_SYMBOL_KEY && !ts.isLiteralTypeNode(node.parent)
|
||||
}
|
||||
|
||||
/** 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, type positions, 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 => {
|
||||
const access = accessOf(node)
|
||||
reads.push({
|
||||
file: normalized,
|
||||
line: source.getLineAndCharacterOfPosition(node.getStart(source)).line + 1,
|
||||
fingerprint: syntaxFingerprint(access, source),
|
||||
})
|
||||
}
|
||||
const visit = (node: ts.Node): void => {
|
||||
if (readsRoot(node, bindings)) record(node)
|
||||
// A type query names `Context.root` without reading it.
|
||||
if (ts.isTypeQueryNode(node)) return
|
||||
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.',
|
||||
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)
|
||||
}
|
||||
Reference in new issue
Block a user