Merge pull request #8436 from deepseek-harness/chore/cordis-root-gate
feat(infra): reject new Cordis root reads
This commit is contained in:
commit
ce7bc84b10
12 files changed
+759
-2
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: 458cdad9fce26157
|
||||
zh: 6ac3b9d7404b4996
|
||||
/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: 6067864f7a2ff1c8
|
||||
zh: df4c9af26a1abd5d
|
||||
@@ -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 and a type checker over each file alone. A read names the root symbol through a Cordis value binding of `Context` or `symbols`: `.root`, `['root']`, or `root` destructured 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, default, namespace, and `import =` forms, or through a destructured or namespace `import()` or `require()` result; a local that shadows the import is not a binding. Any string literal whose value is exactly `cordis.root`, the key behind `Symbol.for('cordis.root')`, is also a read. Type positions, interfaces, type aliases, ambient declarations, 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). The [defensive pattern](../../../../docs/defensive-patterns/general.md#plugins-do-not-read-the-cordis-root-context) states the rule and its replacements for authors, and the gate's rejection message links it.
|
||||
|
||||
## 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, an alias of `Context`, 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 语法树,并对每个文件单独建立类型检查器。读取指通过 `Context` 或 `symbols` 的 Cordis 值绑定访问根符号:`.root`、`['root']`,或在声明、参数默认值或赋值中解构出的 `root`。绑定来自 `@deepseek-ai/cordis` 或其子路径,可以是静态导入(包括重命名、默认、命名空间和 `import =` 形式),也可以是解构或整体接收的 `import()` 或 `require()` 结果;遮蔽导入的局部变量不是绑定。值恰为 `cordis.root` 的任何字符串字面量也算读取,即 `Symbol.for('cordis.root')` 背后的键。类型位置、接口、类型别名、ambient 声明、注释、其他字符串以及嵌入模板中的源码文本不算读取。
|
||||
|
||||
现有读取使用 `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` 配置。[防御性模式](../../../../docs/defensive-patterns/general.zh.md#plugins-do-not-read-the-cordis-root-context)为作者写明该规则及替代方式,门禁的拒绝信息链接到这一节。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**在执行规则前替换所有现有读取。** 已否决,因为部分替换需要新的服务,例如供启动 API 使用的 profile 组合服务和应用生命周期信号;先执行规则可以阻止新增读取,同时单独评审这些设计。
|
||||
|
||||
**使用 `no-restricted-properties` lint 规则。** 已否决,因为它按名称匹配标识符 `Context`,重命名导入(如 `CordisContext`)可以绕过,而且无法匹配 `Symbol.for('cordis.root')`。
|
||||
|
||||
**把豁免文件记入基线。** 已否决,因为基线只会缩小,而豁免文件预期会保留其读取;分开维护可以让基线最终清空。
|
||||
|
||||
## 影响
|
||||
|
||||
所有者在更换已记录读取的接收者或将其移入未登记的文件之前,必须先移除该读取,并在移除后裁剪其条目。通过此检查表明不存在未登记的语法层面的根读取。它无法检测通过其他值获得的根上下文,例如保存的引用、`Context` 的别名、返回根上下文的服务,或运行时由字符串拼装的代码。
|
||||
@@ -28,7 +28,10 @@
|
||||
zh: bb6db31a63bcf383
|
||||
/defensive-patterns/shared-state-has-one-owner:
|
||||
en: 053e2c485eec2613
|
||||
zh: 2817da00572c789f
|
||||
zh: 637cb8ed0e6bf664
|
||||
/defensive-patterns/plugins-do-not-read-the-cordis-root-context:
|
||||
en: 88f70e265c218094
|
||||
zh: 975eebb43cbdf4f1
|
||||
/defensive-patterns/a-business-capability-owns-itself:
|
||||
en: f74f2467e507455f
|
||||
zh: fe1bae04be5ad63a
|
||||
|
||||
@@ -121,6 +121,35 @@ globalThis.__dshCache = new Map() // shared across instances, reclaimed never
|
||||
|
||||
The wrong form lets instances overwrite each other, makes reclamation timing unknowable, and leaks state between tests.
|
||||
|
||||
## Plugins do not read the Cordis root context
|
||||
|
||||
A plugin reaches services, listeners, and registrations through its own context, never through the root context that `ctx[Context.root]` returns. A read through the root skips the `inject` check, because the root fiber has no runtime; a listener on the root skips scope filtering; the root resolves services in the root isolate realm instead of the plugin's; and a listener or accessor registered there is not removed when the plugin is disposed.
|
||||
|
||||
The judged condition: name the declared mechanism each use replaces. A service read is an `inject` entry; a listener that must observe every scope passes `{ global: true }`; a per-application key or a root-level boot operation is a service that owns it. The boundary is first-party JavaScript and TypeScript, including tests and fixtures, and covers `Context.root`, `symbols.root`, and `Symbol.for('cordis.root')`, which name the same symbol. [verify-cordis-root.ts](../../scripts/verify-cordis-root.ts), run as `pnpm run verify-cordis-root` and by `scripts/run-gates.ts` as the `cordis-root` gate, rejects new reads. Exception: the files listed in its `CORDIS_ROOT_EXEMPTIONS`, which pin the root contract itself. The reads recorded in `scripts/cordis-root.baseline.json` are remediation work owned by their packages, not a precedent for new code; the [decision record](../../.agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.md) states the rationale.
|
||||
|
||||
```ts
|
||||
// Services come from inject; a listener that observes every scope says so.
|
||||
interface Loader { await(): Promise<void> }
|
||||
interface Context {
|
||||
readonly loader: Loader
|
||||
on(name: string, listener: () => void, options?: { global?: boolean }): () => void
|
||||
}
|
||||
|
||||
export const inject = ['loader']
|
||||
|
||||
export function apply(ctx: Context, listener: () => void): void {
|
||||
void ctx.loader.await()
|
||||
ctx.on('agent/inbox/inserted', listener, { global: true })
|
||||
}
|
||||
```
|
||||
|
||||
```ts ignore-check
|
||||
void ctx[Context.root].loader.await() // no inject entry, no wait
|
||||
ctx[Context.root].on('agent/inbox/inserted', listener) // escapes scope filtering and plugin disposal
|
||||
```
|
||||
|
||||
The wrong form starts a plugin before its dependency exists, lets it observe and change state outside its scope and realm, and leaves registrations behind after the plugin is disposed.
|
||||
|
||||
## A business capability owns itself
|
||||
|
||||
A business capability lives in its own package and attaches through a registration surface — a registry, `slots.inject`, a waterfall, or an event subscription. A runtime, controller, manager, or gateway carries generic orchestration: it may hold the registry structure and the disposal lifecycle, while the entries are written by the packages that own them, and it never hardcodes a central table of business rows.
|
||||
|
||||
@@ -137,6 +137,37 @@ globalThis.__dshCache = new Map() // shared across instances, reclaimed never
|
||||
|
||||
反例让实例之间互相覆盖、回收时机不可控,并让状态在测试之间泄漏。
|
||||
|
||||
<a id="plugins-do-not-read-the-cordis-root-context"></a>
|
||||
|
||||
## 插件不读取 Cordis 根上下文
|
||||
|
||||
插件通过自己的上下文获取服务、监听事件和注册内容,绝不经由 `ctx[Context.root]` 返回的根上下文。经由根上下文读取会跳过 `inject` 检查,因为根 fiber 没有 runtime;在根上下文上注册的监听器会跳过 scope 过滤;根上下文在根 isolate realm 中解析服务,而不是插件所在的 realm;在根上下文上注册的监听器或 accessor 不会随插件释放而移除。
|
||||
|
||||
判定条件:为每处用法说出它替代的显式声明机制。读取服务对应一条 `inject` 条目;必须观察所有 scope 的监听器传入 `{ global: true }`;应用级的键或根级启动操作由拥有它的服务提供。边界是第一方 JavaScript 和 TypeScript(包括测试和 fixture),覆盖 `Context.root`、`symbols.root` 和 `Symbol.for('cordis.root')`,三者指向同一个符号。[verify-cordis-root.ts](../../scripts/verify-cordis-root.ts) 通过 `pnpm run verify-cordis-root` 运行,并由 `scripts/run-gates.ts` 作为 `cordis-root` 门禁运行,拒绝新增读取。例外:其 `CORDIS_ROOT_EXEMPTIONS` 中列出的文件,它们测试根上下文约定本身。`scripts/cordis-root.baseline.json` 中记录的读取是各包所有者待清理的工作,不是新代码的先例;理由见[决策记录](../../.agents/notes/implemented/process/2026-11-13-no-new-cordis-root-reads.zh.md)。
|
||||
|
||||
```ts
|
||||
// Services come from inject; a listener that observes every scope says so.
|
||||
interface Loader { await(): Promise<void> }
|
||||
interface Context {
|
||||
readonly loader: Loader
|
||||
on(name: string, listener: () => void, options?: { global?: boolean }): () => void
|
||||
}
|
||||
|
||||
export const inject = ['loader']
|
||||
|
||||
export function apply(ctx: Context, listener: () => void): void {
|
||||
void ctx.loader.await()
|
||||
ctx.on('agent/inbox/inserted', listener, { global: true })
|
||||
}
|
||||
```
|
||||
|
||||
```ts ignore-check
|
||||
void ctx[Context.root].loader.await() // no inject entry, no wait
|
||||
ctx[Context.root].on('agent/inbox/inserted', listener) // escapes scope filtering and plugin disposal
|
||||
```
|
||||
|
||||
反例让插件在依赖存在之前启动,让它观察和修改自身 scope 与 realm 之外的状态,并在插件释放后留下注册内容。
|
||||
|
||||
<a id="a-business-capability-owns-itself"></a>
|
||||
|
||||
## 业务能力自己拥有自己
|
||||
|
||||
@@ -113,6 +113,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) => {
|
||||
|
||||
@@ -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' }),
|
||||
]
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
}
|
||||
Reference in new issue
Block a user