From dd06371929dcdd1d3e644680fdd28a8889e07eb1 Mon Sep 17 00:00:00 2001 From: Ruilin Geng Date: Thu, 5 Nov 2026 19:11:05 +0800 Subject: [PATCH] =?UTF-8?q?feat(gates):=20=E7=A6=81=E6=AD=A2=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E5=85=A5=E5=8F=A3=E6=96=B0=E5=A2=9E=E5=80=BC=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=20(#7860)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(gates): reject value exports on function plugin entries A function plugin entry may export only the Loader fields (name, inject, Config, apply), types, and classes whose instances extend Cordis Service or Error, as docs/defensive-patterns/package-surface.md requires. The new verify-plugin-entry-exports gate reads every packages/*/*/src/index.ts that exports a value apply through the Host and then the Client compiler face, and rejects any other value export, including a default export beside apply, values that arrive through export *, and exports that do not resolve. Exports that predate the gate are listed per package in scripts/plugin-entry-existing-exports.ts. A listed export passes; a line fails when its package has no function plugin entry, its list is empty or repeats a name, or it names an export the entry no longer reports. * docs(gates): mark new existing-export lines as rule exceptions A line added to scripts/plugin-entry-existing-exports.ts after the gate's introduction is an exception under the plugin entry rule in docs/defensive-patterns/package-surface.md, which requires the domain owner's confirmation. * fix(gates): report a default export beside apply even when it is a class The class allowance also covered the default export, so a function plugin entry that default-exported a class extending Cordis Service or Error beside apply passed the gate. The Loader then loads that default export instead of the module namespace, which is the mixed plugin form the rule forbids. A default export beside apply is now reported whatever it holds. * fix(gates): judge plugin entry exports by their run-time export paths The gate read TypeScript's export table, which differs from what the entry exports at run time in two forms. An `export type { x }` hid a value that `export *` brings in under the same name, although the type-only export is erased and the value stays. A name that a nested `export type *` reaches was reported as a value, although nothing reaches the entry at run time. The gate now walks the emitted export forms: type-only exports and declare declarations emit nothing, a re-export emits only a run-time export of its target, and `export *` brings in every run-time name of its target except default and the names the module exports itself. An `export *` whose module does not resolve is reported as `*`. * feat(gates): check service plugin entries for value exports The plugin entry rule in docs/defensive-patterns/package-surface.md covers both entry forms: a function plugin exports the Loader fields, a service plugin default-exports its plugin class, and beyond those a Host entry may export only Service Definition classes and error types. The gate checked only function plugins, so a value on a service plugin entry, which another package imports past the Loader row just the same, went unreported, and an entry could escape the gate by default-exporting a class. An entry without apply whose default export is a class the Loader can construct is now a service plugin. Its default class passes under any name, as do types and classes extending Cordis Service or Error; name, inject, Config, and every other value are reported. Libraries, a default export that is not a class, and an abstract default class, which defines a capability seam, stay unchecked. The corpus guard now requires both forms. The existing-export list is regenerated to cover the service plugin entries' current value exports. * fix(gates): admit the plugin entry export list as a plugin record name The plugin entry export list now records the session service entry's existing value exports, appendPluginRecord among them. Like the published dependency policy, the list names the function without calling it, so the plugin record caller gate admits it. * chore(gates): list the plugin entry exports that landed on master Master gained value exports on the plugin-manager, llm, and subagent service entries and renamed office-to-pdf to office-kit before the gate lands. They predate the gate, so the existing-export list records them. --- ...11-04-plugin-entry-value-exports.i18n.yaml | 22 + .../2026-11-04-plugin-entry-value-exports.md | 48 ++ ...026-11-04-plugin-entry-value-exports.zh.md | 48 ++ package.json | 1 + scripts/plugin-entry-existing-exports.ts | 266 ++++++++++ scripts/run-gates.spec.ts | 2 +- scripts/run-gates.ts | 1 + scripts/verify-plugin-entry-exports.spec.ts | 346 +++++++++++++ scripts/verify-plugin-entry-exports.ts | 485 ++++++++++++++++++ scripts/verify-plugin-record-callers.spec.ts | 4 +- scripts/verify-plugin-record-callers.ts | 13 +- 11 files changed, 1230 insertions(+), 6 deletions(-) create mode 100644 .agents/notes/implemented/process/2026-11-04-plugin-entry-value-exports.i18n.yaml create mode 100644 .agents/notes/implemented/process/2026-11-04-plugin-entry-value-exports.md create mode 100644 .agents/notes/implemented/process/2026-11-04-plugin-entry-value-exports.zh.md create mode 100644 scripts/plugin-entry-existing-exports.ts create mode 100644 scripts/verify-plugin-entry-exports.spec.ts create mode 100644 scripts/verify-plugin-entry-exports.ts diff --git a/.agents/notes/implemented/process/2026-11-04-plugin-entry-value-exports.i18n.yaml b/.agents/notes/implemented/process/2026-11-04-plugin-entry-value-exports.i18n.yaml new file mode 100644 index 0000000000..46d3ffa74e --- /dev/null +++ b/.agents/notes/implemented/process/2026-11-04-plugin-entry-value-exports.i18n.yaml @@ -0,0 +1,22 @@ +# Bilingual-pair consistency record for 2026-11-04-plugin-entry-value-exports.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-04-plugin-entry-value-exports.md +/agent-note-plugin-entries-must-not-add-value-exports: + en: 7fa97c44ef2ea43c + zh: 40b94e6a814ff3be +/agent-note-plugin-entries-must-not-add-value-exports/problem: + en: 430b0f35a1358a2f + zh: 83b10ec03fab2477 +/agent-note-plugin-entries-must-not-add-value-exports/decision: + en: af431ecc09ef6646 + zh: 3231ab74de70dffa +/agent-note-plugin-entries-must-not-add-value-exports/alternatives-considered: + en: eba451c0ac372a95 + zh: 906cfc30c66680de +/agent-note-plugin-entries-must-not-add-value-exports/consequences: + en: aef0c3a9efa2e76a + zh: d490227953a5f397 +/agent-note-plugin-entries-must-not-add-value-exports/testing: + en: 50085a461a070e5c + zh: 4d9935def73c5b6a diff --git a/.agents/notes/implemented/process/2026-11-04-plugin-entry-value-exports.md b/.agents/notes/implemented/process/2026-11-04-plugin-entry-value-exports.md new file mode 100644 index 0000000000..be29538301 --- /dev/null +++ b/.agents/notes/implemented/process/2026-11-04-plugin-entry-value-exports.md @@ -0,0 +1,48 @@ +# Agent Note: Plugin entries must not add value exports + +Status: implemented + +English | [中文](2026-11-04-plugin-entry-value-exports.zh.md) + +## Problem + +[The package surface rules](../../../../docs/defensive-patterns/package-surface.md) limit a plugin entry to what the Cordis Loader loads: a function plugin's entry exports `name`, `inject`, `Config`, and `apply`, a service plugin's entry default-exports its plugin class, and beyond those a Host entry may export only the Service Definition classes and error types that other packages extend or throw. No gate checked the rule, and value exports beyond it accumulated on many plugin entries; `dsh-mcp-client`'s entry, for example, gained `probeServer`, `ReconnectSchema`, and four other values that `dsh-mcp-manager` imports. + +The Cordis Loader imports a plugin entry when its row activates and reads only what the plugin form provides: the Loader fields from a function plugin's module namespace, or a service plugin's default-exported class. Any other value on the entry is API that another package can import statically, and that import evaluates the entry module and its dependencies when the importer loads, without the row's activation or `inject` wait. + +## Decision + +The gate [verify-plugin-entry-exports](../../../../scripts/verify-plugin-entry-exports.ts) enforces the rule for both plugin forms: + +- **Scope**: every `packages///src/index.ts` that is a plugin entry. An entry that exports a value named `apply` is a function plugin. An entry without `apply` whose default export is a class the Loader can construct is a service plugin. Libraries, a default export that is not a class, and an abstract default class are not checked; an abstract class defines a capability seam that providers extend, and the Loader cannot construct it. +- **Compiler faces**: the gate reads each entry through the Host compiler face and then the Client face, and the first face that compiles an entry classifies it. An entry that neither face compiles fails the gate, and so does a corpus without a function plugin entry or without a service plugin entry. +- **Rule**: a function plugin entry may export `name`, `inject`, `Config`, and `apply`, and a service plugin entry may export its default class under any name. Either may also export types and values whose every construct signature builds an instance whose base types reach Cordis `Service` or the global `Error`. Class declarations, class expressions, and mixin results pass on the same terms. Every other value fails, including a value that arrives through `export *`, an export whose target does not resolve, and an `export *` whose module does not resolve, which is reported as `*`. A service plugin entry's `name`, `inject`, and `Config` fail like other values, because the Loader reads them from the class. A default export beside `apply` fails whatever it holds, even an allowed class, because the Loader then loads the default export instead of the module namespace. +- **Value or type**: decided by the names the entry exports at run time, with module targets and local bindings resolved against the bound Program because `verbatimModuleSyntax` is off, as in [verify-optional-dependency-imports](../../../../scripts/verify-optional-dependency-imports.ts). Type-only exports and declarations emit nothing, a re-export emits only a run-time export of its target, and `export *` brings in every run-time name of its target except `default` and the names the module exports itself. An `export type` therefore does not hide a value that `export *` provides under the same name, and a name that only `export type *` reaches, at any depth, is a type. +- **Existing exports**: [plugin-entry-existing-exports.ts](../../../../scripts/plugin-entry-existing-exports.ts) lists, by package, the value exports that entries had when the gate arrived. A line records debt, not an approved exception. A listed export passes. A line fails when its package has no entry or its entry is not a plugin entry, when its export list is empty or repeats a name, and when it names an export the entry no longer reports, so removing an export removes its line in the same change. No document or test records the number of listed exports; the gate prints the number it matched. +- **Registration**: a shared hygiene gate in [run-gates](../../../../scripts/run-gates.ts), so it runs in the CI static lane, in master CI, in the local `hygiene` and `check-all` aggregates, and in the Windows observational lane. + +## Alternatives considered + +**Compare the list with the pull request base in CI.** CI already passes the base commit to the [frozen-archive gate](2026-07-26-frozen-agent-note-archive.md), so a gate could reject every line a change adds. The comparison also rejects legitimate changes: renaming a package moves its lines to a new key, and reverting an export removal restores a line. Additions stay a review decision, as they are for the other allowance lists in this repository. + +**Generate a baseline and prune it with a command.** The [unknown-cast gate](2026-09-19-no-unknown-casts.md) keeps a generated JSON baseline with a `--prune` command. A hand-edited TypeScript list keeps one readable entry per package in the diff, and the gate's validation names the line to delete. + +**Check only function plugin entries.** The rule's judged condition names a function plugin's `src/index.ts`, but its first paragraph describes both entry forms and allows a Host entry only the Service Definition classes and error types beyond what the Loader loads. A value that another package imports from a service plugin entry bypasses the row in the same way, and a gate limited to function plugins would let an entry escape it by default-exporting a class. + +**Check Loader rows that name a package subpath.** A Loader row can name a module other than the package root. Finding those modules requires reading every profile, bundle, and preset composition, which this gate does not do, so review still owns them. + +**Remove every existing export in the same change.** Removing the listed exports needs test and consumer changes in dozens of packages. The list lets the gate block new exports immediately while each package removes its own. + +**Judge classes by declaration syntax.** Allowing only `class` declarations that extend `Service` or `Error` rejects class expressions and mixin results that construct the same instances. The gate judges what an export constructs. + +## Consequences + +A new value export on a plugin entry fails CI with the file, line, package, and export name, and the message names the rule and the way out. Existing exports keep working until their packages remove them, and each removal shortens the list. + +The gate builds the Host Program and then the Client Program, and releases the first before building the second, so its peak memory stays near that of the Host Program, like verify-optional-dependency-imports. + +Loader rows that name a subpath, default exports that are not classes, deep imports through `./src/*`, and consumers that import a listed export stay outside the gate, and review still owns them. `/client` entries follow [the Client package rules](../../../../packages/client/AGENTS.md), and the Client build already rejects cross-plugin value imports. The list accepts an added line like any other file, so an addition depends on review. + +## Testing + +[verify-plugin-entry-exports.spec.ts](../../../../scripts/verify-plugin-entry-exports.spec.ts) compiles a fixture with its own Host and Client configs and a stand-in Cordis `Service`. It pins each reported and passing export form, including the run-time paths through `export type` and nested `export type *` and base classes that only share a root's name, the three ways an entry exports `apply`, an `apply` that only a type-only path reaches, service plugin entries whose default class extends `Service` or no class, the entries that are not plugins (a library, an abstract default class, and a default-exported function), an entry only the Client face compiles, an entry neither face compiles, every list validation, a corpus without either plugin form, and a manifest without a name. [run-gates.spec.ts](../../../../scripts/run-gates.spec.ts) pins the gate's registration. Adding a value export to a real function plugin or service plugin entry and removing a listed export makes the gate report both. diff --git a/.agents/notes/implemented/process/2026-11-04-plugin-entry-value-exports.zh.md b/.agents/notes/implemented/process/2026-11-04-plugin-entry-value-exports.zh.md new file mode 100644 index 0000000000..f4d45ca60d --- /dev/null +++ b/.agents/notes/implemented/process/2026-11-04-plugin-entry-value-exports.zh.md @@ -0,0 +1,48 @@ +# Agent Note: 插件入口不得新增值导出 + +Status: implemented + +[English](2026-11-04-plugin-entry-value-exports.md) | 中文 + +## 问题 + +[包表面规则](../../../../docs/defensive-patterns/package-surface.zh.md)把插件入口限定为 Cordis Loader 加载的内容:函数插件的入口导出 `name`、`inject`、`Config`、`apply`,服务插件的入口默认导出它的插件类;除此之外,Host 入口只可再导出供其他包 `extends` 或 `throw` 的 Service Definition 类与错误类型。此前没有门禁检查这条规则,超出规则的值导出在许多插件入口上累积;例如 `dsh-mcp-client` 的入口新增了 `probeServer`、`ReconnectSchema` 以及另外四个由 `dsh-mcp-manager` 导入的值。 + +Cordis Loader 在插件条目激活时才导入它的入口,并且只读取插件形态提供的内容:函数插件模块命名空间里的 Loader 字段,或服务插件默认导出的类。入口上的其他值都是其他包可以静态导入的 API;这种导入会在导入方加载时执行该入口模块及其依赖,不经过该条目的激活,也不等待 `inject`。 + +## 决策 + +门禁 [verify-plugin-entry-exports](../../../../scripts/verify-plugin-entry-exports.ts) 对两种插件形态执行这条规则: + +- **范围**:每个作为插件入口的 `packages///src/index.ts`。导出了名为 `apply` 的值的入口是函数插件;没有 `apply`、而默认导出 Loader 能构造的类的入口是服务插件。库、默认导出不是类的入口,以及默认导出抽象类的入口都不检查;抽象类定义的是供提供方继承的能力接缝,Loader 无法构造它。 +- **compiler face**:门禁先用 Host compiler face、再用 Client face 读取每个入口,由第一个编译它的 face 判定。两个 face 都不编译的入口会让门禁失败;找不到任何函数插件入口或任何服务插件入口时也失败。 +- **判定**:函数插件入口可以导出 `name`、`inject`、`Config`、`apply`,服务插件入口可以用任意名字导出它的默认类。两者都还可以导出类型,以及每个构造签名构造出的实例其基类型都能追溯到 Cordis `Service` 或全局 `Error` 的值。类声明、类表达式和 mixin 结果按同样的条件放行。其他值都会失败,包括经 `export *` 带出的值、目标无法解析的导出,以及模块无法解析的 `export *`(以 `*` 报告)。服务插件入口上的 `name`、`inject`、`Config` 和其他值一样会失败,因为 Loader 从类上读取它们。`apply` 旁边的默认导出无论是什么都会失败,即使是放行的类,因为 Loader 此时会加载默认导出,而不是模块命名空间。 +- **值还是类型**:按入口在运行时导出的名字判定;因为 `verbatimModuleSyntax` 是关闭的,模块目标和本地绑定和 [verify-optional-dependency-imports](../../../../scripts/verify-optional-dependency-imports.ts) 一样基于绑定后的 Program 解析。仅类型的导出和声明不产生任何输出,再导出只在目标是运行时导出时才产生输出,`export *` 带出目标的全部运行时名字,但不包括 `default` 和本模块自己导出的名字。因此 `export type` 不会遮住 `export *` 以同名带出的值,而只能经 `export type *` 到达的名字,无论经过几层,都算类型。 +- **存量导出**:[plugin-entry-existing-exports.ts](../../../../scripts/plugin-entry-existing-exports.ts) 按包列出门禁引入时各入口已有的值导出。每一行记录的是存量欠账,不是批准的例外。列出的导出可以通过。以下情况该行失败:包没有入口或入口不是插件入口;导出列表为空或有重复的名字;列出的导出已不再被入口报告。因此删除一个导出时要在同一改动中删掉它在清单里的行。任何文档或测试都不记录清单条目的数量;门禁只打印它匹配到的数量。 +- **注册**:[run-gates](../../../../scripts/run-gates.ts) 的共享卫生门禁,因此在 CI static lane、master CI、本地 `hygiene` 和 `check-all` 聚合以及 Windows observational lane 中运行。 + +## 考虑过的替代方案 + +**在 CI 中把清单与 PR 的 base 比较。** CI 已经把 base 提交传给[冻结归档门禁](2026-07-26-frozen-agent-note-archive.zh.md),因此门禁可以拒绝改动新增的每一行。但这种比较也会拒绝正当的改动:包改名会把它的行移到新的键下,回滚一次导出删除会恢复一行。新增条目仍由 review 决定,和仓库里其他放行清单一样。 + +**生成基线并用命令裁剪。** [unknown-cast 门禁](2026-09-19-no-unknown-casts.zh.md)维护一份生成的 JSON 基线和 `--prune` 命令。手工编辑的 TypeScript 清单在 diff 中每个包一条,便于阅读,门禁的校验会指出要删的行。 + +**只检查函数插件入口。** 规则的判定条件写的是函数插件的 `src/index.ts`,但规则第一段同时描述了两种入口形态,并且规定 Host 入口在 Loader 加载的内容之外只能导出 Service Definition 类与错误类型。其他包从服务插件入口导入的值同样绕过了插件条目;只检查函数插件的门禁,会让入口改成默认导出类就避开检查。 + +**检查指向包子路径的 Loader 条目。** Loader 条目可以指向包根以外的模块。找出这些模块需要读取所有 profile、bundle 和 preset 组合,本门禁不做这件事,因此仍由 review 负责。 + +**在同一改动中删除所有存量导出。** 删除清单里的导出需要改动几十个包的测试和使用方。有了清单,门禁可以立即拦住新增导出,各包再自行删除存量。 + +**按声明语法判断类。** 只放行继承 `Service` 或 `Error` 的 `class` 声明,会拒绝构造出同样实例的类表达式和 mixin 结果。门禁按导出构造出的实例判断。 + +## 后果 + +插件入口新增值导出时,CI 失败并给出文件、行号、包名和导出名,消息中写明规则和改法。存量导出在所属包删除前继续可用,每次删除都会让清单变短。 + +门禁先构建 Host Program,再构建 Client Program,并在构建第二个之前释放第一个,因此峰值内存接近 Host Program 本身,与 verify-optional-dependency-imports 相当。 + +指向子路径的 Loader 条目、默认导出不是类的入口、经 `./src/*` 的深导入,以及导入清单中导出的使用方都不在门禁范围内,仍由 review 负责。`/client` 入口遵循 [Client 包规则](../../../../packages/client/AGENTS.md),Client 构建已经拒绝跨插件的值导入。清单和其他文件一样可以新增行,因此新增条目依赖 review。 + +## 测试 + +[verify-plugin-entry-exports.spec.ts](../../../../scripts/verify-plugin-entry-exports.spec.ts) 编译一个 fixture,它有自己的 Host、Client 配置和一个替身 Cordis `Service`。它锁定每种被报告和被放行的导出写法(包括经 `export type` 与多层 `export type *` 的运行时路径,以及只是与根类同名的基类)、入口导出 `apply` 的三种方式、只经仅类型路径到达的 `apply`、默认类继承 `Service` 或不继承任何类的服务插件入口、不是插件的入口(库、默认导出抽象类、默认导出函数)、只有 Client face 编译的入口、两个 face 都不编译的入口、每项清单校验、缺少任一插件形态的语料,以及没有名字的 manifest。[run-gates.spec.ts](../../../../scripts/run-gates.spec.ts) 锁定门禁的注册。在真实的函数插件或服务插件入口上新增一个值导出并删除一个已列出的导出,门禁会同时报告这两处。 diff --git a/package.json b/package.json index 358900fad0..37b86b60d5 100644 --- a/package.json +++ b/package.json @@ -155,6 +155,7 @@ "verify-no-bare-dispatcher": "tsx scripts/verify-no-bare-dispatcher.ts", "verify-no-top-level-await": "tsx scripts/verify-no-top-level-await.ts", "verify-plugin-record-callers": "tsx scripts/verify-plugin-record-callers.ts", + "verify-plugin-entry-exports": "tsx scripts/verify-plugin-entry-exports.ts", "verify-cordis-config": "tsx scripts/verify-cordis-config.ts", "rescope-vendor": "tsx scripts/rescope-vendor.ts", "rescope-vendor:check": "tsx scripts/rescope-vendor.ts --check", diff --git a/scripts/plugin-entry-existing-exports.ts b/scripts/plugin-entry-existing-exports.ts new file mode 100644 index 0000000000..98b8552466 --- /dev/null +++ b/scripts/plugin-entry-existing-exports.ts @@ -0,0 +1,266 @@ +/** + * Value exports that plugin entries already had when verify-plugin-entry-exports started enforcing the plugin entry + * rule in docs/defensive-patterns/package-surface.md. Each line records existing debt, not an approved exception. The + * gate passes a listed export and fails a line when its package has no plugin entry, when its export list is empty or + * repeats a name, or when it names an export the entry no longer reports, so removing an export removes its line in + * the same change. A line added after the gate's introduction is an exception under the rule, and the rule requires + * the domain owner's confirmation for it. + */ +export const EXISTING_PLUGIN_ENTRY_EXPORTS = { + '@deepseek-ai/dsh-acp-app': ['ACP_APP_STARTUP_SERVICE'], + '@deepseek-ai/dsh-action-cards': ['Config', 'isPluginStopping'], + '@deepseek-ai/dsh-agent': [ + 'AgentModel', 'agentCarrier', 'agentEvents', 'assembleContextFor', 'emitAgentEvent', 'foldConsumedWork', + 'installModelSelection', 'modelSelectionProjectionDefinition', + ], + '@deepseek-ai/dsh-agent-instructions': [ + 'discoverBaselineInstructionFiles', 'loadBaselineInstructions', 'renderAgentInstructions', + ], + '@deepseek-ai/dsh-agent-loop': ['CONFIGURED_AGENT_IDENTITIES_KEY', 'DEFAULT_MAX_PARALLEL_TOOL_CALLS'], + '@deepseek-ai/dsh-agent-preset-registry': [ + 'agentPresetProjectionDefinition', 'auditRows', 'entryListProblem', 'leakedServices', + ], + '@deepseek-ai/dsh-agent-team': ['TeamId', 'TeamMessageId', 'TeamTaskId'], + '@deepseek-ai/dsh-api-remote-access': ['REMOTE_ACCESS_SNAPSHOT_KEY'], + '@deepseek-ai/dsh-api-remotes': ['API_REMOTE_FORWARDED_EVENTS'], + '@deepseek-ai/dsh-attachment-local': [ + 'DEFAULT_IMAGE_COMPRESSION_CONCURRENCY', 'DEFAULT_MAX_IMAGES_PER_MESSAGE', 'DEFAULT_MAX_IMAGE_BYTES', + 'DEFAULT_MAX_IMAGE_DIMENSION', 'DEFAULT_MAX_IMAGE_PIXELS', 'DEFAULT_MAX_MESSAGE_IMAGE_BYTES', + 'DEFAULT_NORMALIZED_IMAGE_MAX_BYTES', 'DEFAULT_NORMALIZED_IMAGE_MAX_DIMENSION', + 'DEFAULT_NORMALIZED_IMAGE_MAX_PIXELS', 'MAX_IMAGE_COMPRESSION_CONCURRENCY', 'canPassThroughNormalization', + 'commitPreparedImageFile', 'normalizeImage', 'prepareImageFile', 'readImageFile', 'readRequestImageFile', + 'requestImageVariantId', 'saveImageFile', 'validateImageFile', + ], + '@deepseek-ai/dsh-bash-local': ['ENV_OVERRIDES', 'assertServiceableBashConfig'], + '@deepseek-ai/dsh-client-connection': [ + 'API_PATH', 'CONNECT_PATH', 'Peer', 'RpcId', 'clientRequestSchema', 'rpcErrorSchema', 'rpcIdSchema', + 'rpcMessageSchema', 'rpcResultSchema', 'serverResponseSchema', 'transportError', + ], + '@deepseek-ai/dsh-client-hmr': ['EVENTS_ENDPOINT'], + '@deepseek-ai/dsh-client-locale': ['LOCALE_IDS', 'LOCALE_PREFERENCE_FIELD', 'LOCALE_SETTINGS_NAMESPACE'], + '@deepseek-ai/dsh-client-modules': ['bootInjections', 'orderByModuleGraph', 'stripClientSuffix'], + '@deepseek-ai/dsh-client-ui-chat': [ + 'CHAT_SETTINGS_NAMESPACE', 'DEFAULT_TRANSCRIPT_VIEW_MODE', 'LEGACY_EXPANDED_TRANSCRIPT_VIEW_MODE', + 'LEGACY_TRANSCRIPT_VIEW_MODE', 'TRANSCRIPT_VIEW_FIELD', 'TRANSCRIPT_VIEW_MODES', + ], + '@deepseek-ai/dsh-client-ui-conversation': [ + 'BUSY_ENTER_BEHAVIORS', 'BUSY_ENTER_FIELD', 'CONVERSATION_SETTINGS_NAMESPACE', 'DEFAULT_BUSY_ENTER_BEHAVIOR', + ], + '@deepseek-ai/dsh-client-ui-theme': [ + 'DEFAULT_FONT_SIZE', 'DEFAULT_PREFERENCE', 'FONT_SIZE_FIELD', 'FONT_SIZE_MAX', 'FONT_SIZE_MIN', 'THEME_PREFERENCES', + 'THEME_PREFERENCE_FIELD', 'THEME_SETTINGS_NAMESPACE', + ], + '@deepseek-ai/dsh-command-feedback': ['FEEDBACK_CATEGORIES', 'recordFeedback'], + '@deepseek-ai/dsh-commands': ['CommandDefinitionId', 'CommandId', 'name', 'parseCommand'], + '@deepseek-ai/dsh-compaction-tool-result-pruner': ['DEFAULTS', 'PRUNE_MARKER', 'codePointLength', 'resolveConfig'], + '@deepseek-ai/dsh-cordis-host-runner': [ + 'ApprovalRequestId', 'CordisDynamicPackageId', 'CordisDynamicPluginId', 'CordisDynamicPluginRunId', + ], + '@deepseek-ai/dsh-credentials-local': [ + 'CREDENTIALS_FILENAME', 'DOCUMENT_VERSION', 'parseCredentialsDocument', 'renderFlatLayoutMigration', 'resolveSpec', + ], + '@deepseek-ai/dsh-cua': ['CuaConfig', 'installCua'], + '@deepseek-ai/dsh-deepseek-account-platform': ['Config'], + '@deepseek-ai/dsh-experimental-claude-code-mods': [ + 'DEFAULT_TOOL_ALIASES', 'KNOWN_EVENTS', 'MODS_API_VERSION', 'SERVED_EVENTS', 'defineMod', + ], + '@deepseek-ai/dsh-experimental-cua-macos': ['GUIDANCE'], + '@deepseek-ai/dsh-experimental-forge': ['changeRequestKey'], + '@deepseek-ai/dsh-experimental-inspector': ['resolveInspectorOptions', 'startInspector'], + '@deepseek-ai/dsh-experimental-ptc-runtime-python': [ + 'checkDoneValue', 'detachResidual', 'encodeJsonPlain', 'hasNonLosslessNumber', 'hasUnsafeIntegerToken', + 'hostFrameParseCeiling', 'logTruncationMarker', 'readProcessStart', 'resolvePythonBin', 'validateChildFrame', + ], + '@deepseek-ai/dsh-experimental-worktree': ['generatedWorktreeName'], + '@deepseek-ai/dsh-file-reference-local': [ + 'DEFAULT_FILE_SEARCH_EXCLUDED_DIRECTORIES', 'DEFAULT_FILE_SEARCH_MAX_ENTRIES', 'DEFAULT_FILE_SEARCH_MAX_RESULTS', + 'FILE_REFERENCE_PROMPT', 'WorkspaceFileSearch', 'activeAtToken', 'formatFileMention', + ], + '@deepseek-ai/dsh-goal': [ + 'GOAL_CHANGE_VERSION', 'GoalId', 'applyGoalProjection', 'decodeGoalChange', 'foldGoal', 'goalChangeRef', + 'goalProjectionDefinition', + ], + '@deepseek-ai/dsh-goal-round-driver': ['renderGoalRoundPrompt'], + '@deepseek-ai/dsh-host-directory-picker-auto': [ + 'BACKEND_PACKAGES', 'SURFACE_PACKAGES', 'canExecute', 'hasLinuxChooserBinary', 'resolveDirectoryPickerBackend', + ], + '@deepseek-ai/dsh-host-directory-picker-browse': ['boundedInsert', 'fullyQualified', 'raceAbort'], + '@deepseek-ai/dsh-host-directory-picker-native': ['pickNativeDirectory'], + '@deepseek-ai/dsh-host-plugin-inventory': ['pluginEntryId', 'readPluginInventory'], + '@deepseek-ai/dsh-host-product-telemetry-otel': ['Config'], + '@deepseek-ai/dsh-host-webserver': [ + 'bindUrlHost', 'isLoopbackHost', 'isWildcardHost', 'normalizeBindAddress', 'renderIndexInjections', + ], + '@deepseek-ai/dsh-jobs-local': ['TASK_WAIT_TIMEOUT'], + '@deepseek-ai/dsh-llm': [ + 'ACCOUNT_QUOTA_EXCEEDED_CODE', 'APP_IDENTITY', 'AssistantStreamAccumulator', 'BlockAssembler', + 'CONTEXT_SUMMARY_MAX_CHARS', 'CONTEXT_WINDOW_EXCEEDED_CODE', 'EMPTY_RESPONSE_CODE', 'IMAGE_OFFLOAD_REQUIRED_CODE', + 'INVALID_CREDENTIAL_CODE', 'LLM_FAILURE_CODES', 'LlmAdapter', 'LlmAttemptId', 'MessageId', 'ProviderRequestId', + 'QUOTA_EXCEEDED_CODE', 'RETRY_CODE_CHOICES', 'ReasoningEffortId', 'RetryPolicySchema', 'ToolCallId', + 'assembleAssistantStream', 'assertUsableApiKey', 'assistantStreamChunks', 'assistantStreamFirstTokenTime', + 'assistantStreamHasVisibleContent', 'assistantStreamHasVisibleText', 'attributionHeaders', 'boundContextSummary', + 'callConfigEquals', 'chunkHasVisibleText', 'contentHasFile', 'contentHasImage', 'createAssistantMessage', + 'createDeveloperMessage', 'createMessage', 'createSystemMessage', 'createToolResultMessage', 'createUserMessage', + 'errorChain', 'expandAssistantStream', 'fileHandleText', 'freezeMessage', 'isAgentLoopRequest', + 'isContextWindowExceededError', 'isHarnessError', 'isQuotaExceededError', 'isTokenDelta', 'isVisibleChunk', + 'joinAssistantStreamText', 'lastAssistantStreamChunk', 'markAgentLoopRequest', 'normalizeApiKey', + 'offloadedImageText', 'projectFilesToText', 'projectImagesForTextModel', 'projectOffloadedImages', + 'projectToolUpdates', 'requestImageHandleText', 'requiredImageOffload', 'resolveImageAttachmentAccess', + 'resolveRetryPolicy', 'runFirstTokenTime', 'runFirstVisibleTime', 'textOnlyImageText', 'userAgent', + ], + '@deepseek-ai/dsh-llm-deepseek-account': ['plainAccountOptions', 'resolveAccountOptions'], + '@deepseek-ai/dsh-llm-deepseek-api-key': ['plainOptions', 'resolveAdapterOptions'], + '@deepseek-ai/dsh-llm-pi-ai': ['PiAiAdapter', 'recordKeyFor', 'supportedProtocols'], + '@deepseek-ai/dsh-llm-replay': [ + 'deriveReplayScript', 'installLlmReplay', 'loadReplayScript', 'loadSessionScripts', 'parseSessionHeader', + 'parseSessionLog', 'prepareSessionSnapshotFixtureForComparison', 'resolveScriptedEntry', + ], + '@deepseek-ai/dsh-llm-retry': ['RetryId'], + '@deepseek-ai/dsh-lsp': ['LspProviderId', 'finalExtension'], + '@deepseek-ai/dsh-lsp-stdio': [ + 'LspConnection', 'LspInstance', 'MessageDecoder', 'canonicalizeWorkspace', 'encodeMessage', + 'negotiatePositionEncoding', 'normalizeHover', 'normalizeLocations', 'readHostSource', 'requestMethod', + 'supportsOperation', 'supportsTransientOpen', + ], + '@deepseek-ai/dsh-mcp-client': [ + 'ReconnectSchema', 'SERVER_NAME_PATTERN', 'assertTemplateSyntax', 'connectionStatusOf', 'createMcpToolDefinition', + 'probeServer', 'resolveReconnectPolicy', + ], + '@deepseek-ai/dsh-office-kit': ['Config', 'OfficeKitGeneration', 'OfficeKitKey', 'OfficeSourceKey'], + '@deepseek-ai/dsh-permission-presets': ['AUTO_PRESET', 'CUSTOM_PRESET'], + '@deepseek-ai/dsh-persona': ['PERSONA_PREFIX_SECTION', 'PERSONA_SUFFIX_SECTION'], + '@deepseek-ai/dsh-plan-mode': ['EXIT_PLAN_MODE', 'planProjectionDefinition', 'resolveConfig'], + '@deepseek-ai/dsh-plugin-manager': ['classifyInstallFailure', 'parseInstallSpec', 'pinnedGitOrigin'], + '@deepseek-ai/dsh-pwsh-local': [ + 'ENCODING_PREAMBLE', 'ENV_OVERRIDES', 'assertServiceablePwshConfig', 'candidatePwshPaths', 'resolvePwshPath', + ], + '@deepseek-ai/dsh-sandbox-policy': ['SANDBOX_MODES', 'setSandboxMode'], + '@deepseek-ai/dsh-schedule': [ + 'DEFAULT_LIST_LIMIT', 'MAX_LIST_LIMIT', 'MAX_TITLE_LENGTH', 'MIN_EVERY_INTERVAL_SECONDS', 'REQUIRED_TITLE_MESSAGE', + 'ScheduleId', 'canonicalizeCronExpression', 'createAfterScheduleRecord', 'createAtScheduleRecord', + 'createCronScheduleRecord', 'createDailyScheduleRecord', 'createEveryScheduleRecord', 'createWeeklyScheduleRecord', + 'decodeScheduleRecord', 'formatScheduleLocalTime', 'isRecurringScheduleRecord', 'normalizeWeekdays', + 'parseCronInput', 'parseWeeklyInput', 'renderRecurringReminderBatchFraming', 'renderReminderFraming', + 'resolveCronOccurrence', 'resolveDailyOccurrence', 'resolveEveryOccurrence', 'resolveRecurringOccurrence', + 'resolveWeeklyOccurrence', 'scheduleDomain', 'scheduleTitle', 'weeklyTime', + ], + '@deepseek-ai/dsh-sdk-app': ['SDK_APP_STARTUP_SERVICE'], + '@deepseek-ai/dsh-sdk-jsonrpc-server': ['HarnessSdkJsonRpcServer'], + '@deepseek-ai/dsh-session': [ + 'KNOWN_SESSION_EVENT_TYPES', 'SESSION_FORMAT_VERSION', 'Session', 'SessionId', 'SessionLogOffset', + 'SessionPreparation', 'SessionSeq', 'TOOL_NOT_STARTED', 'TOOL_OUTCOME_UNKNOWN', 'ToolCallRecovery', + 'adoptSessionEvent', 'appendPluginRecord', 'buildForkSeed', 'canonicalHeader', 'decodeSeqRanges', + 'deriveEventMessage', 'encodeSeqRanges', 'foldRequestHeader', 'foldSurface', 'headerEquals', + 'interruptedTurnClosers', 'isAppendSurfaceEvent', 'isReplacementSurfaceEvent', 'isSurfaceEligibleType', + 'isSurfaceEvent', 'pluginRecordOf', 'snapshotSessionEvent', + ], + '@deepseek-ai/dsh-session-log-deepseek': ['acceptedThrough'], + '@deepseek-ai/dsh-session-log-export': [ + 'DEFAULT_SESSION_LOG_COMPRESSION_LEVEL', 'SESSION_LOG_EXPORT_PATH', 'SESSION_LOG_FILENAME', 'flushLiveSessionLog', + 'formatSessionMarkdown', 'readSessionLogText', 'serializeSessionLog', 'sessionLogExportDeps', + 'sessionLogZipEntries', 'sessionLogZipFilename', 'streamSessionLogZip', + ], + '@deepseek-ai/dsh-session-persistence-jsonl': ['JsonlCompressionSchema'], + '@deepseek-ai/dsh-session-projection-cache': [ + 'Config', 'checkpointIdentity', 'checkpointRecord', 'checkpointRow', 'projectionCacheDomainSpec', + ], + '@deepseek-ai/dsh-session-query-sqlite': [ + 'SESSION_QUERY_SQLITE_APPLICATION_ID', 'SESSION_QUERY_SQLITE_DEFAULT_LIMIT', 'SESSION_QUERY_SQLITE_MAX_LIMIT', + 'SESSION_QUERY_SQLITE_PATH_KEY', 'SESSION_QUERY_SQLITE_SCHEMA_VERSION', 'SESSION_QUERY_SQLITE_SNIPPET_CHARS', + ], + '@deepseek-ai/dsh-session-reference': [ + 'DEFAULT_CANDIDATE_LIMIT', 'DEFAULT_MAX_REFERENCE_BYTES', 'MAX_REFERENCES', 'SESSION_REFERENCE_SCHEME', + 'decodeSessionReferenceUri', 'encodeSessionReferenceUri', 'formatSessionReferenceMention', + 'parseSessionReferenceText', + ], + '@deepseek-ai/dsh-session-telemetry-otel': [ + 'Config', 'DEFAULT_SHUTDOWN_TIMEOUT_MILLIS', 'DEFAULT_TELEMETRY_MODE', 'SessionTelemetryMode', + ], + '@deepseek-ai/dsh-session-title': [ + 'SessionTitleProviderId', 'fallbackSessionTitle', 'foldSessionTitle', 'normalizeSessionTitle', + 'titleProjectionDefinition', 'truncateTitleUtf8', + ], + '@deepseek-ai/dsh-settings': ['redactSecrets'], + '@deepseek-ai/dsh-skill': [ + 'BUNDLED_SKILL_RANK', 'escapeText', 'isModelInvocable', 'isSkillName', 'isUserInvocable', 'renderSkillContent', + ], + '@deepseek-ai/dsh-skill-filesystem': ['FileSystemSkillProvider'], + '@deepseek-ai/dsh-spill-local': [ + 'DEFAULT_ROOT_PREFIX', 'discoverDefaultRoots', 'encodeSegment', 'isErrno', 'privateRoot', 'saveTextFile', + 'sessionDir', 'sweepSpillRoots', + ], + '@deepseek-ai/dsh-storage': ['BackendRegistry', 'UNIT_NAME_RE', 'storageBackendServiceKey'], + '@deepseek-ai/dsh-storage-domain': ['DomainFacility', 'defineDomain', 'descriptorOf', 'domainTable'], + '@deepseek-ai/dsh-storage-json': ['JsonStorageBackend'], + '@deepseek-ai/dsh-storage-sqlite': ['STORAGE_SQLITE_SCHEMA_VERSION', 'SqliteStorageBackend'], + '@deepseek-ai/dsh-subagent': [ + 'AssistantOutputFold', 'NO_START_CAPABILITIES', 'ROOT_AGENT_NAME', 'STRUCTURED_OUTPUT_TOOL', + 'SUBAGENT_DESCRIPTOR_VERSION', 'SubagentRunId', 'appendDelegatedPolicyOverrides', 'applyChildComposition', + 'assertPositiveFinite', 'assertSubagentMaxDepth', 'assertUsableCwd', 'captureDelegatedPolicyOverrides', + 'childSessionMeta', 'delegationDepthOf', 'finalAssistantOutput', 'foldSubagentDescriptor', + 'parentAgentOptionsForDelegation', 'resolveChildAgentOptions', 'resolveChildDepth', 'settleRunResult', + 'snapshotSubagentDescriptor', 'subprocessRunHandle', + ], + '@deepseek-ai/dsh-system-prompt': [ + 'PERSONA_PREFIX_SECTION', 'PERSONA_SUFFIX_SECTION', 'TOOL_ORDER_REST', 'joinContextSections', + 'renderContextSections', 'renderContextSnapshot', 'renderPrompt', + ], + '@deepseek-ai/dsh-terminal': ['TerminalSessionId'], + '@deepseek-ai/dsh-terminal-bash': ['BashTerminalBackend', 'PWSH_PROMPT_SETUP'], + '@deepseek-ai/dsh-tool-call-timeout-policy': ['TOOL_TIMEOUT'], + '@deepseek-ai/dsh-tool-executor-native': ['NativeToolExecutor'], + '@deepseek-ai/dsh-tool-executor-ptc': [ + 'PtcExecutor', 'jsonSchemaToPy', 'jsonSchemaToTs', 'renderToolsSdk', 'renderToolsSdkPy', + ], + '@deepseek-ai/dsh-tool-fs-search': [ + 'GLOB_MAX_RESULTS', 'GLOB_VCS_EXCLUDES', 'GREP_MAX_LINE_BYTES', 'GREP_MAX_MATCHES', 'RAW_OUTPUT_MAX_BYTES', + 'SEARCH_GRACE_MS', 'SEARCH_META_MAX_BYTES', 'SEARCH_STDERR_MAX_BYTES', 'SEARCH_TIMEOUT_MS', 'applyGlobTool', + 'applyGrepTool', 'buildGlobCommand', 'buildGrepCommand', 'formatGlobOutput', 'formatGrepMatches', + 'formatGrepOutput', 'parseGlobArgs', 'parseGrepArgs', 'parseGrepMatches', 'presentGlobCall', 'presentGlobResult', + 'presentGrepCall', 'presentGrepResult', 'previewLine', 'resolveRgPath', 'runRipgrep', 'sampleAcrossTopLevel', + 'toWorkdirRelative', 'trySaveFormattedResult', + ], + '@deepseek-ai/dsh-tool-lsp': [ + 'DEFAULT_LSP_TOOL_TIMEOUT_MS', 'DEFAULT_MAX_LOCATIONS', 'DEFAULT_MAX_RESULT_CHARS', 'LSP_OPERATIONS', + 'LSP_PROMPT_TEXT', 'formatHover', 'formatLocations', 'parseLspArgs', 'presentLspCall', 'renderUri', + ], + '@deepseek-ai/dsh-tool-session-query': ['DEFAULT_MAX_SEARCH_RESULTS', 'DEFAULT_SEARCH_TIMEOUT_MS'], + '@deepseek-ai/dsh-tool-terminal': ['DEFAULT_MAX_RESULT_BYTES', 'MIN_MAX_RESULT_BYTES'], + '@deepseek-ai/dsh-tool-web': [ + 'DEFAULT_FETCH_MAX_OUTPUT_CHARS', 'DEFAULT_WEB_TOOL_TIMEOUT_MS', 'WEB_SEARCH_MAX_QUERIES', 'WEB_SEARCH_MAX_RESULTS', + 'applyWebFetchTool', 'applyWebSearchTool', 'fetchMetaFromResult', 'fetchMetaFromValue', 'formatFetchOutput', + 'formatSearchOutput', 'parseFetchArgs', 'presentFetchCall', 'presentFetchResult', 'presentSearchCall', + 'presentSearchResult', 'searchMetaFromResult', 'searchMetaFromValue', + ], + '@deepseek-ai/dsh-tool-workspace-dependencies': [ + 'copyPrimaryRuntime', 'installPrimaryRuntime', 'parsePrimaryRuntime', 'primaryRuntimePythonAliases', + 'readPrimaryRuntime', 'resolvePrimaryRuntime', 'workspaceDependencyPaths', + ], + '@deepseek-ai/dsh-tools': [ + 'RUN_CODE_NAME', 'TOOL_ABORTED', 'TOOL_ABORTED_BEFORE_DISPATCH', 'assertObjectJsonSchema', + 'assertSupportedJsonSchema', 'defineTool', 'isJsonSchemaRecord', 'isPlainJsonArray', 'isPlainJsonRecord', + 'parameterSchemaSpecToJsonSchema', 'projectToolSchema', 'validateArgs', 'validateJsonSchemaValue', + 'valueSchemaSpecToJsonSchema', + ], + '@deepseek-ai/dsh-typert-loader': ['TYPERT_HOST_EXPORT', 'validateTypertManifest'], + '@deepseek-ai/dsh-typert-registry': ['typertEndpoint', 'typertKey', 'typertPackageKey'], + '@deepseek-ai/dsh-user-approval': ['APPROVAL_POLICIES', 'ApprovalRequestId', 'setApprovalPolicy'], + '@deepseek-ai/dsh-user-questions': ['TIMED_WAIT_PARAMETER', 'isTimedAskUserQuestionSchema'], + '@deepseek-ai/dsh-web-app': ['internals'], + '@deepseek-ai/dsh-web-deepseek-api': [ + 'DEEPSEEK_DEFAULT_COUNT', 'DEEPSEEK_FETCH_API_PROVIDER_ID', 'DEEPSEEK_SEARCH_API_PROVIDER_ID', + 'DEEPSEEK_SEARCH_REQUESTS_PER_SECOND', 'DEEPSEEK_WEB_API_BASE_URL', 'DeepSeekFetchApiProvider', + 'DeepSeekSearchApiProvider', 'mapSearchResponse', + ], + '@deepseek-ai/dsh-web-fetch-http': ['DEFAULT_USER_AGENT', 'HttpFetchProvider', 'LOCAL_FETCH_PROVIDER_ID'], + '@deepseek-ai/dsh-web-search-deepseek': [ + 'DEEPSEEK_DEFAULT_API_VERSION', 'DEEPSEEK_DEFAULT_BASE_URL', 'DEEPSEEK_DEFAULT_MAX_TOKENS', + 'DEEPSEEK_DEFAULT_MAX_USES', 'DEEPSEEK_DEFAULT_MODEL', 'DEEPSEEK_PROVIDER_ID', 'DeepSeekSearchProvider', + 'WEB_SEARCH_DEEPSEEK_SETTINGS_NAMESPACE', + ], + '@deepseek-ai/dsh-webhook': ['WebhookDeliveryId', 'WebhookRuleId', 'WebhookSourceId'], + '@deepseek-ai/dsh-workflow-ptc': ['materializeFromRealm', 'validateMeta'], + '@deepseek-ai/dsh-workspace': [ + 'WorkspaceId', 'realpathNormalize', 'workspaceDomainSpec', 'workspaceDomainState', 'workspaceRecord', + ], +} as const satisfies Readonly> diff --git a/scripts/run-gates.spec.ts b/scripts/run-gates.spec.ts index 3c37aa5142..dd6d7cf536 100644 --- a/scripts/run-gates.spec.ts +++ b/scripts/run-gates.spec.ts @@ -380,7 +380,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', 'no-top-level-await', + 'plugin-record-callers', 'no-unknown-casts', 'no-top-level-await', 'plugin-entry-exports', 'cordis-config', 'runtime-closure', ]) }) diff --git a/scripts/run-gates.ts b/scripts/run-gates.ts index a8cd867c34..6caa503c79 100644 --- a/scripts/run-gates.ts +++ b/scripts/run-gates.ts @@ -421,6 +421,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('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' }), ] } diff --git a/scripts/verify-plugin-entry-exports.spec.ts b/scripts/verify-plugin-entry-exports.spec.ts new file mode 100644 index 0000000000..3dd1c6221d --- /dev/null +++ b/scripts/verify-plugin-entry-exports.spec.ts @@ -0,0 +1,346 @@ +/** + * Tests for the plugin entry export gate: which entries it checks, which export forms it reports, how the + * existing-export list is validated, and how it fails when an entry goes unchecked. + * + * The fixture compiles its own `tsconfig.host.json` and `tsconfig.client.json`, with a stand-in Cordis `Service` at + * the path the repository maps `@deepseek-ai/cordis` to. + */ + +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterAll, describe, expect, it } from 'vitest' +import { + ENTRY_GLOB, + EXISTING_EXPORTS_FILE, + discoverEntries, + scanFailures, + scanRepository, +} from './verify-plugin-entry-exports.ts' + +const compilerOptions = { + target: 'es2022', + module: 'esnext', + moduleResolution: 'bundler', + noEmit: true, + skipLibCheck: true, + types: [], + paths: { '@deepseek-ai/cordis': ['./vendor/cordis/src/index.ts'] }, +} + +const manifest = (name: string): string => JSON.stringify({ name, version: '0.0.1' }) + +const PLUGIN_ENTRY = [ + "import { Service } from '@deepseek-ai/cordis'", + '', + // The Loader fields, with Config as both an interface and a value. + "export const name = 'plugin'", + "export const inject = ['tools']", + 'export interface Config { limit: number }', + 'export const Config = (config: Config): Config => config', + 'export function apply(): void {}', + // Types, in every form the compiler erases. + 'export interface Shape { a: number }', + 'export type Alias = string', + "export type { Remote as RemoteAlias } from './types.ts'", + "export { type Remote } from './types.ts'", + "export { Remote as RemoteAgain } from './types.ts'", + "export type * from './type-star.ts'", + // Classes judged by what they construct. + 'export class DirectError extends Error {}', + 'export class IndirectError extends DirectError {}', + 'class Detailed extends Error { declare readonly detail?: T }', + 'export class GenericError extends Detailed {}', + 'export class DirectService extends Service {}', + 'export class GenericService extends Service {}', + 'export const ExpressionError = class extends Error {}', + 'function Tagged object>(base: Base) {', + " return class extends base { readonly tag = 'tagged' }", + '}', + 'export class MixedError extends Tagged(Error) {}', + // Values the rule does not allow. + 'export function helper(): void {}', + 'export const LIMIT = 3', + 'export const PATTERN = /x/u', + 'export enum Mode { A }', + 'export namespace Space { export const inner = 1 }', + 'export class Plain {}', + 'export const PlainExpression = class {}', + 'export class MixedPlain extends Tagged(class {}) {}', + "export type Id = string & { readonly brand: 'Id' }", + 'export function Id(value: string): Id { return value as Id }', + "export * from './values.ts'", + "export * as namespaced from './values.ts'", + "export { helperImpl as renamed } from './values.ts'", + "export { missing } from './missing.ts'", + "export * from './gone.ts'", + '', +].join('\n') + +const FIXTURE: Record = { + 'tsconfig.host.json': JSON.stringify({ + compilerOptions, + include: ['vendor/**/*.ts', 'packages/**/*.ts'], + exclude: ['packages/f/client-only/**', 'packages/f/orphan/**'], + }), + 'tsconfig.client.json': JSON.stringify({ compilerOptions, include: ['packages/f/client-only/**/*.ts'] }), + 'vendor/cordis/src/index.ts': 'export abstract class Service { declare readonly value?: T }\n', + + 'packages/f/plugin/package.json': manifest('@f/plugin'), + 'packages/f/plugin/src/index.ts': PLUGIN_ENTRY, + 'packages/f/plugin/src/types.ts': 'export interface Remote { b: string }\n', + 'packages/f/plugin/src/type-star.ts': 'export interface StarShape { c: number }\nexport const hiddenByTypeStar = 1\n', + 'packages/f/plugin/src/values.ts': [ + 'export const starred = 1', + 'export interface StarredShape { d: number }', + 'export function helperImpl(): void {}', + '', + ].join('\n'), + + // A value `apply` makes an entry a function plugin, in each form an entry can export it. + 'packages/f/const-apply/package.json': manifest('@f/const-apply'), + 'packages/f/const-apply/src/index.ts': 'export const apply = (): void => {}\nexport const extra = 1\n', + 'packages/f/reexport-apply/package.json': manifest('@f/reexport-apply'), + 'packages/f/reexport-apply/src/index.ts': "export { apply } from './apply.ts'\nexport const extra = 1\n", + 'packages/f/reexport-apply/src/apply.ts': 'export function apply(): void {}\n', + 'packages/f/with-default/package.json': manifest('@f/with-default'), + 'packages/f/with-default/src/index.ts': 'export function apply(): void {}\nexport default apply\n', + // A Service class as the default export beside apply: the Loader loads it instead of the namespace. + 'packages/f/default-service/package.json': manifest('@f/default-service'), + 'packages/f/default-service/src/index.ts': [ + "import { Service } from '@deepseek-ai/cordis'", + 'export function apply(): void {}', + 'export default class Mixed extends Service {}', + '', + ].join('\n'), + + // Run-time export paths: an erased `export type` does not hide the value `export *` brings in under its name, and a + // name that only a nested `export type *` reaches is a type, including an `apply` that reaches the entry that way. + 'packages/f/type-shadow/package.json': manifest('@f/type-shadow'), + 'packages/f/type-shadow/src/index.ts': [ + 'export function apply(): void {}', + "export type { hidden } from './value.ts'", + "export * from './value.ts'", + '', + ].join('\n'), + 'packages/f/type-shadow/src/value.ts': 'export const hidden = 1\n', + 'packages/f/type-barrel/package.json': manifest('@f/type-barrel'), + 'packages/f/type-barrel/src/index.ts': "export function apply(): void {}\nexport * from './barrel.ts'\n", + 'packages/f/type-barrel/src/barrel.ts': "export type * from './value.ts'\n", + 'packages/f/type-barrel/src/value.ts': 'export const hidden = 1\n', + 'packages/f/type-apply/package.json': manifest('@f/type-apply'), + 'packages/f/type-apply/src/index.ts': "export * from './barrel.ts'\n", + 'packages/f/type-apply/src/barrel.ts': "export type * from './impl.ts'\n", + 'packages/f/type-apply/src/impl.ts': 'export function apply(): void {}\nexport const extra = 1\n', + + // Base classes that only share a name with Error and Service are not the allowed roots. + 'packages/f/fake-base/package.json': manifest('@f/fake-base'), + 'packages/f/fake-base/src/index.ts': [ + 'export function apply(): void {}', + 'class Error {}', + 'class Service {}', + 'export class FakeError extends Error {}', + 'export class FakeService extends Service {}', + '', + ].join('\n'), + + // A service plugin entry default-exports a class the Loader constructs. Beside it pass other names for the same class, + // types, and Service or Error classes; `Config` and other values are reported, because the Loader reads the class. + 'packages/f/service/package.json': manifest('@f/service'), + 'packages/f/service/src/index.ts': [ + "import { Service } from '@deepseek-ai/cordis'", + 'export default class Store extends Service {}', + 'export { Store as NamedStore }', + 'export class StoreError extends Error {}', + 'export interface StoreShape { a: number }', + 'export const helper = 1', + 'export const Config = { limit: 1 }', + '', + ].join('\n'), + 'packages/f/plain-class/package.json': manifest('@f/plain-class'), + 'packages/f/plain-class/src/index.ts': [ + 'export default class Plain {}', + 'export { Plain }', + 'export function plainHelper(): void {}', + '', + ].join('\n'), + + // Entries the Loader cannot load as a plugin are not checked: a library, an abstract default class that defines a + // capability seam, and a default export that is not a class. + 'packages/f/library/package.json': manifest('@f/library'), + 'packages/f/library/src/index.ts': 'export const util = 1\n', + 'packages/f/seam/package.json': manifest('@f/seam'), + 'packages/f/seam/src/index.ts': [ + "import { Service } from '@deepseek-ai/cordis'", + 'export default abstract class Definition extends Service {}', + 'export const seamHelper = 1', + '', + ].join('\n'), + 'packages/f/default-function/package.json': manifest('@f/default-function'), + 'packages/f/default-function/src/index.ts': 'export default function plugin(): void {}\nexport const fnHelper = 1\n', + + // Only the Client face compiles this entry; no face compiles the orphan. + 'packages/f/client-only/package.json': manifest('@f/client-only'), + 'packages/f/client-only/src/index.ts': 'export function apply(): void {}\nexport const clientValue = 1\n', + 'packages/f/orphan/package.json': manifest('@f/orphan'), + 'packages/f/orphan/src/index.ts': 'export function apply(): void {}\n', + + 'packages/f/listed/package.json': manifest('@f/listed'), + 'packages/f/listed/src/index.ts': [ + 'export function apply(): void {}', + 'export const kept = 1', + 'export const alsoKept = 2', + 'export interface Typed { a: number }', + 'export class ListedError extends Error {}', + '', + ].join('\n'), +} + +const EXISTING = { + '@f/listed': ['kept', 'alsoKept', 'kept', 'gone', 'Typed', 'ListedError'], + '@f/library': ['util'], + '@f/unknown': ['value'], + '@f/const-apply': [], + '@f/orphan': ['anything'], +} + +function writeFixture(files: Record, prefix: string): string { + const fixtureRoot = mkdtempSync(join(tmpdir(), prefix)) + for (const [rel, content] of Object.entries(files)) { + mkdirSync(dirname(join(fixtureRoot, rel)), { recursive: true }) + writeFileSync(join(fixtureRoot, rel), content) + } + return fixtureRoot +} + +function lineOf(text: string, line: string): number { + return text.split('\n').indexOf(line) + 1 +} + +const root = writeFixture(FIXTURE, 'plugin-entry-exports-') +const emptyRoot = writeFixture({ + 'tsconfig.host.json': JSON.stringify({ compilerOptions, include: ['packages/**/*.ts'] }), + 'packages/f/library/package.json': manifest('@f/library'), + 'packages/f/library/src/index.ts': 'export const util = 1\n', +}, 'plugin-entry-exports-empty-') +const namelessRoot = writeFixture({ + 'packages/f/nameless/package.json': JSON.stringify({ version: '0.0.1' }), + 'packages/f/nameless/src/index.ts': 'export function apply(): void {}\n', +}, 'plugin-entry-exports-nameless-') +const result = scanRepository(root, EXISTING) + +afterAll(() => { + for (const fixtureRoot of [root, emptyRoot, namelessRoot]) rmSync(fixtureRoot, { recursive: true, force: true }) +}) + +describe('function plugin entry exports', () => { + it('reports every value beyond the Loader fields, types, and Service or Error classes', () => { + expect(result.violations.map(value => `${value.packageName} ${value.exportName}`)).toEqual([ + '@f/client-only clientValue', + '@f/const-apply extra', + '@f/default-service default', + '@f/fake-base FakeError', + '@f/fake-base FakeService', + '@f/plain-class plainHelper', + '@f/plugin helper', + '@f/plugin LIMIT', + '@f/plugin PATTERN', + '@f/plugin Mode', + '@f/plugin Space', + '@f/plugin Plain', + '@f/plugin PlainExpression', + '@f/plugin MixedPlain', + '@f/plugin Id', + '@f/plugin helperImpl', + '@f/plugin starred', + '@f/plugin namespaced', + '@f/plugin renamed', + '@f/plugin missing', + '@f/plugin *', + '@f/reexport-apply extra', + '@f/service helper', + '@f/service Config', + '@f/type-shadow hidden', + '@f/with-default default', + ]) + }) + + it('follows run-time export paths through type-only exports', () => { + const shadow = result.violations.find(value => value.packageName === '@f/type-shadow') + expect(shadow).toMatchObject({ exportName: 'hidden', line: 3, unresolved: false }) + expect(result.violations.some(value => value.packageName === '@f/type-barrel' || value.packageName === '@f/type-apply')) + .toBe(false) + }) + + it('reports a default export beside apply even when it is a Service class', () => { + expect(result.violations.filter(value => value.exportName === 'default').map(value => value.packageName)) + .toEqual(['@f/default-service', '@f/with-default']) + }) + + it('checks entries that export a value apply or default-export a class the Loader constructs', () => { + expect(result.checkedEntries).toEqual({ function: 10, service: 2 }) + const unchecked = new Set(['@f/library', '@f/seam', '@f/default-function', '@f/type-apply']) + expect(result.violations.some(value => unchecked.has(value.packageName))).toBe(false) + }) + + it('locates a star re-export at its statement and a renamed re-export at its specifier', () => { + const lines = Object.fromEntries(result.violations + .filter(value => value.packageName === '@f/plugin') + .map(value => [value.exportName, value.line])) + expect(lines.starred).toBe(lineOf(PLUGIN_ENTRY, "export * from './values.ts'")) + expect(lines.helperImpl).toBe(lineOf(PLUGIN_ENTRY, "export * from './values.ts'")) + expect(lines.renamed).toBe(lineOf(PLUGIN_ENTRY, "export { helperImpl as renamed } from './values.ts'")) + expect(lines.Id).toBe(lineOf(PLUGIN_ENTRY, 'export function Id(value: string): Id { return value as Id }')) + }) + + it('names the file, line, package, and export, and marks an export whose target does not resolve', () => { + const failures = scanFailures(result) + expect(failures).toContain('packages/f/const-apply/src/index.ts:2 @f/const-apply exports extra') + expect(failures).toContain(`packages/f/plugin/src/index.ts:${String(lineOf(PLUGIN_ENTRY, "export { missing } from './missing.ts'"))}` + + ' @f/plugin exports missing, whose target does not resolve') + expect(failures).toContain(`packages/f/plugin/src/index.ts:${String(lineOf(PLUGIN_ENTRY, "export * from './gone.ts'"))}` + + ' @f/plugin exports *, whose target does not resolve') + }) + + it('reads the Client face and fails an entry that no face compiles', () => { + expect(result.unloadedEntries).toEqual(['packages/f/orphan/src/index.ts']) + expect(scanFailures(result)).toContain('packages/f/orphan/src/index.ts is compiled by neither' + + ' tsconfig.host.json nor tsconfig.client.json, so its exports go unchecked') + }) +}) + +describe('existing-export list', () => { + it('passes a listed export', () => { + expect(result.violations.some(value => value.packageName === '@f/listed')).toBe(false) + expect(result.listedExports).toBe(2) + }) + + it('fails unknown packages, entries that are not plugins, empty lists, repeats, and exports no longer reported', () => { + const entry = 'packages/f/listed/src/index.ts' + expect(result.listProblems).toEqual([ + '@f/listed lists kept more than once; keep one', + `@f/listed lists gone, which ${entry} no longer exports beyond the rule; remove it`, + `@f/listed lists Typed, which ${entry} no longer exports beyond the rule; remove it`, + `@f/listed lists ListedError, which ${entry} no longer exports beyond the rule; remove it`, + '@f/library: packages/f/library/src/index.ts is not a plugin entry; remove its line', + `@f/unknown has no ${ENTRY_GLOB} entry; remove its line`, + '@f/const-apply lists no exports; remove its line', + ]) + expect(scanFailures(result)).toContain(`${EXISTING_EXPORTS_FILE}: @f/const-apply lists no exports; remove its line`) + }) +}) + +describe('entry corpus', () => { + it('fails when no function plugin entry or no service plugin entry is found', () => { + const empty = scanRepository(emptyRoot, {}, ['host']) + expect(empty.checkedEntries).toEqual({ function: 0, service: 0 }) + expect(scanFailures(empty)).toEqual([ + `no function plugin entry matches ${ENTRY_GLOB}; entry discovery or classification is broken`, + `no service plugin entry matches ${ENTRY_GLOB}; entry discovery or classification is broken`, + ]) + }) + + it('rejects an entry whose package manifest has no name', () => { + expect(() => discoverEntries(namelessRoot)).toThrow('packages/f/nameless/package.json has no string name') + }) +}) diff --git a/scripts/verify-plugin-entry-exports.ts b/scripts/verify-plugin-entry-exports.ts new file mode 100644 index 0000000000..ba2f4b06ab --- /dev/null +++ b/scripts/verify-plugin-entry-exports.ts @@ -0,0 +1,485 @@ +/** + * Reject a value that a plugin entry exports beyond what the Cordis Loader loads. + * + * The rule lives in docs/defensive-patterns/package-surface.md ("A plugin package exports what the Loader loads"): + * a function plugin's entry exports `name`, `inject`, `Config`, and `apply`, a service plugin's entry default-exports + * its plugin class, and either may add the Service Definition classes and error types that other packages extend or + * throw. The Loader imports the entry when its row activates and reads only what the plugin form provides; any other + * value on the entry is API that another package can import statically, which evaluates the entry module without its + * Loader row. + * + * The corpus is every `packages///src/index.ts`. An entry that exports a value named `apply` is a + * function plugin. A default export beside `apply` is always reported, even a class allowed below, because the Loader + * then loads the default export instead of the module namespace. An entry without `apply` whose default export is a + * class the Loader can construct is a service plugin: its default export and other names for the same class pass, and + * `name`, `inject`, and `Config` are reported like any other value because the Loader reads them from the class. Other + * entries are not checked: libraries, a default export that is not a class, and an abstract default class, which + * defines a capability seam that providers extend. Each entry is read through the Host compiler face and then the + * Client face; the first face that compiles it classifies it. An entry that neither face compiles fails the gate, + * because it would otherwise go unchecked, and so does a corpus without a function plugin or without a service plugin. + * + * Value-vs-type follows the names each entry exports at run time, resolved against a bound Program because + * `verbatimModuleSyntax` is off: type-only exports and declarations emit nothing, a re-export emits only a run-time + * export of its target, and `export *` brings in every run-time name of its target except `default` and the names the + * module exports itself. A type-only export therefore does not hide a value that `export *` provides under the same + * name, and a name that only `export type *` reaches, at any depth, is a type. A value passes as a class when every + * construct signature builds an instance whose base types reach Cordis `Service` or the global `Error`; class + * declarations, class expressions, and mixin results are judged by what they construct. An export whose target does + * not resolve is reported, and so is an `export *` whose module does not resolve, under the name `*`. + * + * Exports that predate the gate are listed in scripts/plugin-entry-existing-exports.ts. A listed export passes. A list + * line fails when its package has no entry or its entry is not a plugin, when its export list is empty or repeats a + * name, and when it names an export the entry no longer reports, so removing an export also removes its line. + */ + +import { globSync, readFileSync } from 'node:fs' +import { join, posix, resolve } from 'node:path' +import ts from 'typescript' +import { EXISTING_PLUGIN_ENTRY_EXPORTS } from './plugin-entry-existing-exports.ts' +import { TypeScriptProject, type CompilerFace } from './ts-project.ts' + +const GATE = 'verify-plugin-entry-exports' +const root = resolve(import.meta.dirname, '..') + +/** The corpus glob for the root entry of every workspace package. */ +export const ENTRY_GLOB = 'packages/*/*/src/index.ts' + +/** Repository-relative path of the list of exports that predate the gate. */ +export const EXISTING_EXPORTS_FILE = 'scripts/plugin-entry-existing-exports.ts' + +/** The rule this gate enforces, named in its diagnostics. */ +const RULE = 'docs/defensive-patterns/package-surface.md#a-plugin-package-exports-what-the-loader-loads' + +/** Values the Loader reads from a function plugin's module namespace. */ +const LOADER_FIELDS: ReadonlySet = new Set(['name', 'inject', 'Config', 'apply']) + +/** The plugin forms the rule names: `apply` on the module namespace, or a default-exported plugin class. */ +export type PluginForm = 'function' | 'service' + +/** Every plugin form, in report order. */ +const PLUGIN_FORMS: readonly PluginForm[] = ['function', 'service'] + +/** Package name to the value exports its plugin entry may keep while they still exist. */ +export type ExistingEntryExports = Readonly> + +/** One package root entry that the corpus glob found. */ +export interface PluginEntry { + /** Repository-relative POSIX path of the entry. */ + readonly file: string + /** The `name` field of the package manifest that owns the entry. */ + readonly packageName: string +} + +/** One value a plugin entry exports beyond what its form allows. */ +export interface EntryValueExport { + /** Repository-relative POSIX path of the entry. */ + readonly file: string + /** One-based line of the declaration, re-export specifier, or `export *` statement in the entry. */ + readonly line: number + readonly packageName: string + readonly exportName: string + /** True when the export's target does not resolve, so the value cannot be classified. */ + readonly unresolved: boolean +} + +/** What one repository scan checked and found. */ +export interface ScanResult { + /** Number of entries checked, per plugin form. */ + readonly checkedEntries: Readonly> + /** Reported exports that the existing-export list does not name, sorted by file, line, and name. */ + readonly violations: readonly EntryValueExport[] + /** Defects in the existing-export list. */ + readonly listProblems: readonly string[] + /** Entries that no compiler face compiles. */ + readonly unloadedEntries: readonly string[] + /** Number of reported exports that the existing-export list names. */ + readonly listedExports: number +} + +/** How one compiler face classified one entry. */ +interface EntryFacts { + /** Undefined for an entry the Loader cannot load as a plugin. */ + readonly form: PluginForm | undefined + readonly valueExports: readonly EntryValueExport[] +} + +function lineOf(node: ts.Node, sourceFile: ts.SourceFile): number { + return sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line + 1 +} + +function resolveAlias(symbol: ts.Symbol, checker: ts.TypeChecker): ts.Symbol { + return (symbol.flags & ts.SymbolFlags.Alias) === 0 ? symbol : checker.getAliasedSymbol(symbol) +} + +/** + * Find every package root entry and the package that owns it. + * @param repositoryRoot - absolute repository root. + * @returns entries sorted by path. + * @throws when an owning manifest has no string `name`. + */ +export function discoverEntries(repositoryRoot: string): PluginEntry[] { + return globSync(ENTRY_GLOB, { cwd: repositoryRoot }) + .map(file => file.replaceAll('\\', '/')) + .sort() + .map((file) => { + const manifest = posix.join(posix.dirname(posix.dirname(file)), 'package.json') + const parsed: unknown = JSON.parse(readFileSync(join(repositoryRoot, manifest), 'utf8')) + const name = typeof parsed === 'object' && parsed !== null && 'name' in parsed ? parsed.name : undefined + if (typeof name !== 'string') throw new Error(`${GATE}: ${manifest} has no string name`) + return { file, packageName: name } + }) +} + +/** The Cordis `Service` class as this program resolves it, or undefined when the program does not load Cordis. */ +function cordisService(project: TypeScriptProject): ts.Symbol | undefined { + const { checker, program } = project + const resolved = ts.resolveModuleName( + '@deepseek-ai/cordis', join(project.projectRoot, 'package.json'), program.getCompilerOptions(), ts.sys, + ).resolvedModule + const sourceFile = resolved === undefined ? undefined : program.getSourceFile(resolved.resolvedFileName) + const moduleSymbol = sourceFile === undefined ? undefined : checker.getSymbolAtLocation(sourceFile) + if (moduleSymbol === undefined) return undefined + const service = checker.getExportsOfModule(moduleSymbol).find(symbol => ts.symbolName(symbol) === 'Service') + return service === undefined ? undefined : resolveAlias(service, checker) +} + +/** Whether any hop of an export's alias chain is a type-only import or export. */ +function isTypeOnlyAlias(symbol: ts.Symbol, checker: ts.TypeChecker): boolean { + const seen = new Set() + for (let current: ts.Symbol | undefined = symbol; current !== undefined && !seen.has(current);) { + seen.add(current) + if (current.declarations?.some(declaration => ts.isTypeOnlyImportOrExportDeclaration(declaration)) === true) { + return true + } + if ((current.flags & ts.SymbolFlags.Alias) === 0) return false + current = checker.getImmediateAliasedSymbol(current) + } + return false +} + +/** One name a module exports at run time: the node that introduces it there, and the value it carries. */ +interface RuntimeExport { + /** Undefined for a name a declaration file provides, which has no emit to locate. */ + readonly node: ts.Node | undefined + /** Undefined when the export's target does not resolve. */ + readonly symbol: ts.Symbol | undefined +} + +/** Run-time exports per module, shared by every entry that one Program classifies. */ +type RuntimeExportCache = Map> + +function hasModifier(node: ts.Node, kind: ts.SyntaxKind): boolean { + return ts.canHaveModifiers(node) && (ts.getModifiers(node)?.some(modifier => modifier.kind === kind) ?? false) +} + +function bindingNames(name: ts.BindingName): string[] { + if (ts.isIdentifier(name)) return [name.text] + return name.elements.flatMap(element => ts.isOmittedExpression(element) ? [] : bindingNames(element.name)) +} + +/** The symbol an alias resolves to, or undefined when it reaches no declaration. */ +function resolvedTarget(symbol: ts.Symbol, checker: ts.TypeChecker): ts.Symbol | undefined { + const target = resolveAlias(symbol, checker) + return (target.declarations ?? []).length === 0 ? undefined : target +} + +/** Run-time exports of the module a specifier names, or undefined when the specifier does not resolve. */ +function moduleRuntimeExports( + specifier: ts.Expression, checker: ts.TypeChecker, cache: RuntimeExportCache, +): ReadonlyMap | undefined { + const moduleSymbol = checker.getSymbolAtLocation(specifier) + return moduleSymbol === undefined ? undefined : runtimeExports(moduleSymbol, checker, cache) +} + +/** Run-time exports of a declaration file or ambient module: its values that no type-only alias reaches. */ +function declaredRuntimeExports(moduleSymbol: ts.Symbol, checker: ts.TypeChecker, result: Map): void { + for (const exported of checker.getExportsOfModule(moduleSymbol)) { + if (isTypeOnlyAlias(exported, checker)) continue + const target = resolvedTarget(exported, checker) + if (target === undefined || (target.flags & ts.SymbolFlags.Value) !== 0) { + result.set(ts.symbolName(exported), { node: undefined, symbol: target }) + } + } +} + +/** + * Names a module exports at run time with `verbatimModuleSyntax` off, each with the node that introduces it in the + * module: type-only exports and `declare` declarations emit nothing, a re-export emits only a run-time export of its + * target, and `export *` brings every run-time name of its target except `default` and the names the module exports + * itself. + */ +function runtimeExports( + moduleSymbol: ts.Symbol, checker: ts.TypeChecker, cache: RuntimeExportCache, +): ReadonlyMap { + const cached = cache.get(moduleSymbol) + if (cached !== undefined) return cached + const result = new Map() + // An `export *` cycle that reaches this module again sees the names collected so far. + cache.set(moduleSymbol, result) + const file = moduleSymbol.valueDeclaration + if (file === undefined || !ts.isSourceFile(file) || file.isDeclarationFile) { + declaredRuntimeExports(moduleSymbol, checker, result) + return result + } + const table = new Map(checker.getExportsOfModule(moduleSymbol).map(symbol => [ts.symbolName(symbol), symbol])) + const own = (name: string): ts.Symbol | undefined => { + const symbol = table.get(name) + return symbol === undefined ? undefined : resolvedTarget(symbol, checker) + } + const add = (name: string, node: ts.Node, symbol: ts.Symbol | undefined): void => { + if (!result.has(name)) result.set(name, { node, symbol }) + } + const stars: ts.ExportDeclaration[] = [] + for (const statement of file.statements) { + if (ts.isExportDeclaration(statement)) { + if (statement.isTypeOnly) continue + const clause = statement.exportClause + const specifier = statement.moduleSpecifier + if (clause === undefined) { + stars.push(statement) + } else if (ts.isNamespaceExport(clause)) { + add(clause.name.text, clause, specifier === undefined ? undefined : checker.getSymbolAtLocation(specifier)) + } else { + for (const element of clause.elements) { + if (element.isTypeOnly) continue + if (specifier === undefined) { + const local = checker.getExportSpecifierLocalTargetSymbol(element) + if (local !== undefined && isTypeOnlyAlias(local, checker)) continue + const target = local === undefined ? undefined : resolvedTarget(local, checker) + if (target === undefined || (target.flags & ts.SymbolFlags.Value) !== 0) add(element.name.text, element, target) + } else { + const source = moduleRuntimeExports(specifier, checker, cache) + const reexported = source?.get((element.propertyName ?? element.name).text) + if (source === undefined || reexported !== undefined) add(element.name.text, element, reexported?.symbol) + } + } + } + } else if (ts.isExportAssignment(statement)) { + if (statement.isExportEquals !== true) add('default', statement, own('default')) + } else if (hasModifier(statement, ts.SyntaxKind.ExportKeyword) && !hasModifier(statement, ts.SyntaxKind.DeclareKeyword)) { + const asDefault = hasModifier(statement, ts.SyntaxKind.DefaultKeyword) ? 'default' : undefined + if (ts.isFunctionDeclaration(statement) || ts.isClassDeclaration(statement)) { + const name = asDefault ?? statement.name?.text + if (name !== undefined) add(name, statement, own(name)) + } else if (ts.isVariableStatement(statement)) { + for (const declaration of statement.declarationList.declarations) { + for (const name of bindingNames(declaration.name)) add(name, declaration, own(name)) + } + } else if (ts.isEnumDeclaration(statement)) { + if (!hasModifier(statement, ts.SyntaxKind.ConstKeyword)) add(statement.name.text, statement, own(statement.name.text)) + } else if (ts.isModuleDeclaration(statement) && ts.isIdentifier(statement.name)) { + const namespace = own(statement.name.text) + if (namespace !== undefined && (namespace.flags & ts.SymbolFlags.ValueModule) !== 0) { + add(statement.name.text, statement, namespace) + } + } + } + } + const explicit = new Set(result.keys()) + for (const star of stars) { + const source = star.moduleSpecifier === undefined ? undefined : moduleRuntimeExports(star.moduleSpecifier, checker, cache) + if (source === undefined) { + add('*', star, undefined) + continue + } + for (const [name, { symbol }] of source) { + if (name !== 'default' && !explicit.has(name)) add(name, star, symbol) + } + } + return result +} + +function isTypeReference(type: ts.Type): type is ts.TypeReference { + return (type.flags & ts.TypeFlags.Object) !== 0 + && ((type as ts.ObjectType).objectFlags & ts.ObjectFlags.Reference) !== 0 +} + +/** Whether an instance type or one of its base types, through generic and mixin bases, is a root class. */ +function reachesRoot( + type: ts.Type, checker: ts.TypeChecker, isRoot: (symbol: ts.Symbol) => boolean, seen: Set, +): boolean { + if (seen.has(type)) return false + seen.add(type) + if (type.isIntersection()) return type.types.some(part => reachesRoot(part, checker, isRoot, seen)) + const declared = isTypeReference(type) ? type.target : type + const symbol = declared.getSymbol() + if (symbol !== undefined && isRoot(symbol)) return true + return declared.isClassOrInterface() + && checker.getBaseTypes(declared).some(base => reachesRoot(base, checker, isRoot, seen)) +} + +/** Whether a value is a class the Loader can construct: it has construct signatures and no abstract declaration. */ +function isConstructibleClass(symbol: ts.Symbol, checker: ts.TypeChecker): boolean { + return checker.getTypeOfSymbol(symbol).getConstructSignatures().length > 0 + && !(symbol.declarations ?? []).some(declaration => + ts.isClassDeclaration(declaration) && hasModifier(declaration, ts.SyntaxKind.AbstractKeyword)) +} + +/** The plugin form of an entry from its run-time exports, or undefined when the Loader cannot load it as a plugin. */ +function pluginForm(exports: ReadonlyMap, checker: ts.TypeChecker): PluginForm | undefined { + if (exports.get('apply')?.symbol !== undefined) return 'function' + const pluginClass = exports.get('default')?.symbol + return pluginClass !== undefined && isConstructibleClass(pluginClass, checker) ? 'service' : undefined +} + +/** Classify one entry's exports in the face whose program compiled it. */ +function classifyEntry( + project: TypeScriptProject, entry: PluginEntry, sourceFile: ts.SourceFile, service: ts.Symbol | undefined, + cache: RuntimeExportCache, +): EntryFacts { + const { checker, program } = project + const moduleSymbol = checker.getSymbolAtLocation(sourceFile) + if (moduleSymbol === undefined) return { form: undefined, valueExports: [] } + const exports = runtimeExports(moduleSymbol, checker, cache) + const form = pluginForm(exports, checker) + if (form === undefined) return { form, valueExports: [] } + const pluginClass = form === 'service' ? exports.get('default')?.symbol : undefined + const isRoot = (symbol: ts.Symbol): boolean => symbol === service + || (ts.symbolName(symbol) === 'Error' + && (symbol.declarations ?? []).some(declaration => program.isSourceFileDefaultLibrary(declaration.getSourceFile()))) + const constructsRootClass = (target: ts.Symbol): boolean => { + const signatures = checker.getTypeOfSymbol(target).getConstructSignatures() + return signatures.length > 0 + && signatures.every(signature => reachesRoot(signature.getReturnType(), checker, isRoot, new Set())) + } + + const valueExports: EntryValueExport[] = [] + for (const [exportName, { node, symbol }] of exports) { + if (form === 'function' ? LOADER_FIELDS.has(exportName) : symbol === pluginClass) continue + // The Loader loads a default export instead of a function plugin's namespace, so the class allowance never covers it. + if (exportName !== 'default' && symbol !== undefined && constructsRootClass(symbol)) continue + valueExports.push({ + file: entry.file, + line: lineOf(node ?? sourceFile, sourceFile), + packageName: entry.packageName, + exportName, + unresolved: symbol === undefined, + }) + } + return { form, valueExports } +} + +function duplicates(names: readonly string[]): string[] { + const seen = new Set() + return [...new Set(names.filter(name => seen.has(name) || !seen.add(name)))] +} + +/** Problems of the existing-export list against what the scan classified. */ +function existingListProblems( + existing: ExistingEntryExports, entries: readonly PluginEntry[], facts: ReadonlyMap, +): string[] { + const problems: string[] = [] + const entriesByPackage = new Map(entries.map(entry => [entry.packageName, entry])) + for (const [packageName, exportNames] of Object.entries(existing)) { + const entry = entriesByPackage.get(packageName) + if (entry === undefined) { + problems.push(`${packageName} has no ${ENTRY_GLOB} entry; remove its line`) + continue + } + const entryFacts = facts.get(entry.file) + // An entry that no face compiles is reported on its own; its exports are unknown. + if (entryFacts === undefined) continue + if (entryFacts.form === undefined) { + problems.push(`${packageName}: ${entry.file} is not a plugin entry; remove its line`) + continue + } + if (exportNames.length === 0) problems.push(`${packageName} lists no exports; remove its line`) + for (const name of duplicates(exportNames)) problems.push(`${packageName} lists ${name} more than once; keep one`) + const reported = new Set(entryFacts.valueExports.map(value => value.exportName)) + for (const name of new Set(exportNames)) { + if (!reported.has(name)) { + problems.push(`${packageName} lists ${name}, which ${entry.file} no longer exports beyond the rule; remove it`) + } + } + } + return problems +} + +/** + * Classify the entries one compiler face compiles and that no earlier face classified. The face's Program stays local + * to this call, so it is collectable before the next face builds its own. + */ +function classifyFace( + repositoryRoot: string, face: CompilerFace, entries: readonly PluginEntry[], facts: Map, +): void { + const project = new TypeScriptProject(repositoryRoot, face) + const service = cordisService(project) + const cache: RuntimeExportCache = new Map() + for (const entry of entries) { + if (facts.has(entry.file)) continue + const sourceFile = project.program.getSourceFile(resolve(repositoryRoot, entry.file)) + if (sourceFile !== undefined) facts.set(entry.file, classifyEntry(project, entry, sourceFile, service, cache)) + } +} + +/** + * Check every plugin entry against the rule and the existing-export list. + * @param repositoryRoot - absolute root holding `packages/` and the `tsconfig..json` aggregates. + * @param existing - package name to the value exports that may remain. + * @param faces - compiler faces to load in order; the first face that compiles an entry classifies it. + * @returns the checked counts, the unlisted exports, the list problems, and the uncompiled entries. + */ +export function scanRepository( + repositoryRoot: string = root, + existing: ExistingEntryExports = EXISTING_PLUGIN_ENTRY_EXPORTS, + faces: readonly CompilerFace[] = ['host', 'client'], +): ScanResult { + const entries = discoverEntries(repositoryRoot) + const facts = new Map() + for (const face of faces) classifyFace(repositoryRoot, face, entries, facts) + const reported = entries.flatMap(entry => facts.get(entry.file)?.valueExports ?? []) + const violations = reported + .filter(value => existing[value.packageName]?.includes(value.exportName) !== true) + .sort((left, right) => left.file.localeCompare(right.file) || left.line - right.line + || left.exportName.localeCompare(right.exportName)) + const checked = (form: PluginForm): number => entries.filter(entry => facts.get(entry.file)?.form === form).length + return { + checkedEntries: { function: checked('function'), service: checked('service') }, + violations, + listProblems: existingListProblems(existing, entries, facts), + unloadedEntries: entries.filter(entry => !facts.has(entry.file)).map(entry => entry.file), + listedExports: reported.length - violations.length, + } +} + +/** + * Render a scan as failure lines. + * @param result - one repository scan. + * @returns one line per failure, empty when the tree passes. + */ +export function scanFailures(result: ScanResult): string[] { + return [ + ...PLUGIN_FORMS.filter(form => result.checkedEntries[form] === 0) + .map(form => `no ${form} plugin entry matches ${ENTRY_GLOB}; entry discovery or classification is broken`), + ...result.unloadedEntries.map(file => + `${file} is compiled by neither tsconfig.host.json nor tsconfig.client.json, so its exports go unchecked`), + ...result.violations.map(value => `${value.file}:${String(value.line)} ${value.packageName} exports ` + + `${value.exportName}${value.unresolved ? ', whose target does not resolve' : ''}`), + ...result.listProblems.map(problem => `${EXISTING_EXPORTS_FILE}: ${problem}`), + ] +} + +/** CLI entry: report every failure and exit 1, or confirm the invariant holds. */ +function main(): void { + const result = scanRepository() + const failures = scanFailures(result) + if (failures.length === 0) { + console.log(`${GATE}: ${String(result.checkedEntries.function)} function plugin and` + + ` ${String(result.checkedEntries.service)} service plugin entries export only what the Loader loads, types,` + + ` and Service or Error classes, apart from ${String(result.listedExports)} export(s) listed in` + + ` ${EXISTING_EXPORTS_FILE}.`) + return + } + console.error(`${GATE}: ${String(failures.length)} problem(s):`) + for (const failure of failures) console.error(` ${failure}`) + if (result.violations.length > 0) { + console.error('\nA function plugin entry exports name, inject, Config, and apply, and a service plugin entry' + + ' default-exports its plugin class; either may also export types and classes extending Cordis Service or' + + ` Error (${RULE}).`) + console.error('Keep any other value in an internal module: same-package tests import that module, and other' + + ' packages reach the behavior through a ctx service.') + } + process.exitCode = 1 +} + +if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) main() diff --git a/scripts/verify-plugin-record-callers.spec.ts b/scripts/verify-plugin-record-callers.spec.ts index 70b45a4963..ba8ae3d6ec 100644 --- a/scripts/verify-plugin-record-callers.spec.ts +++ b/scripts/verify-plugin-record-callers.spec.ts @@ -7,6 +7,7 @@ import { checkDeclaredPluginRecordWrites, checkPluginRecordCallers, DEPENDENCY_POLICY_FILE, + ENTRY_EXPORT_LIST_FILE, findPluginRecordReferences, isAdmittedCaller, OWNER_FILE, @@ -133,11 +134,12 @@ describe('verify-plugin-record-callers', () => { expect(checkPluginRecordCallers(corpus(source))).toEqual([]) }) - it('admits experimental source, the owner, tests, this gate, and the dependency policy', () => { + it('admits experimental source, the owner, tests, this gate, the dependency policy, and the entry export list', () => { for (const file of [ EXPERIMENTAL, OWNER_FILE, DEPENDENCY_POLICY_FILE, + ENTRY_EXPORT_LIST_FILE, 'packages/session/session-persistence/tests/live-write-contract.ts', 'apps/web/tests/session.e2e.ts', 'examples/demo/tests/demo.spec.ts', diff --git a/scripts/verify-plugin-record-callers.ts b/scripts/verify-plugin-record-callers.ts index e1a1b55e39..b41b8c325c 100644 --- a/scripts/verify-plugin-record-callers.ts +++ b/scripts/verify-plugin-record-callers.ts @@ -4,8 +4,9 @@ * `appendPluginRecord` in `@deepseek-ai/dsh-session` appends an ignorable `plugin:` record that the * experimental persistence catalogue lists and that a Session format migration keeps only on a best-effort * basis. Experimental packages may rely on that; a release package must declare its events instead. - * The owning module and test files, which exercise the operation, are exempt, as is the published - * dependency policy, which names the function to classify the export without calling it. + * The owning module and test files, which exercise the operation, are exempt, as are the published + * dependency policy and the plugin entry export list, which name the function to classify or record its + * export without calling it. * * Discovery is syntax-aware: every identifier spelled `appendPluginRecord` counts — an import, a * named re-export, a call, a namespace member, a destructured binding, or an alias source — and so @@ -46,6 +47,9 @@ const GATE_FILES: ReadonlySet = new Set([ /** The published dependency policy names the restricted function to classify the export's package edge. */ export const DEPENDENCY_POLICY_FILE = 'scripts/package-dependency-policy.ts' +/** The plugin entry export list names the restricted function to record the session entry's existing export. */ +export const ENTRY_EXPORT_LIST_FILE = 'scripts/plugin-entry-existing-exports.ts' + const SOURCE_EXTENSION = /\.(?:[cm]?[jt]s|[jt]sx)$/u /** A line continuation, which a string or template literal drops from its value. */ @@ -103,11 +107,12 @@ export function isTestFile(file: string): boolean { /** * Whether a file may reference the restricted function. * @param file - repository-relative path, in POSIX separators. - * @returns whether the file is experimental source, the owner, a test, this gate, or the dependency policy. + * @returns whether the file is experimental source, the owner, a test, this gate, the dependency policy, or the plugin + * entry export list. */ export function isAdmittedCaller(file: string): boolean { return file.startsWith(EXPERIMENTAL_PREFIX) || file === OWNER_FILE || isTestFile(file) || GATE_FILES.has(file) - || file === DEPENDENCY_POLICY_FILE + || file === DEPENDENCY_POLICY_FILE || file === ENTRY_EXPORT_LIST_FILE } function scriptKind(file: string): ts.ScriptKind {