1
0

rescope-vendor.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. /**
  2. * Rescope the vendored Cordis packages into the `@deepseek-ai` scope, and undo
  3. * that rescope with `--reverse`. Every harness package declares `cordis` as a
  4. * peer dependency, so publication carries this framework layer too; publishing
  5. * it under the upstream names would squat them on the registry
  6. * ([rationale](../.agents/notes/implemented/process/2026-08-10-vendor-package-rescope.md),
  7. * [name mapping](../docs/rescope.md)).
  8. *
  9. * The generic pass rewrites ONLY delimited, complete package-name tokens:
  10. * `'old'` / `"old"` / `` `old` `` / `'old/subpath'`, plus a YAML `name: old`
  11. * scalar. A match needs a quote (or `name: `) immediately left and the matching
  12. * quote — optionally after a `/subpath` — immediately right, which excludes
  13. * `cordis.yml`, the Loader's `cordis:` builtin prefix, `cordis-config-entry`,
  14. * `@deepseek-ai/dsh-tool-cordis`, and `cordiverse/cordis`, and makes the
  15. * rewrite idempotent because the scoped name's `cordis` is preceded by `/`.
  16. * Markdown follows the rename inside every fence, and in `docs/` prose too:
  17. * a tutorial that teaches an unresolvable name is wrong, while prose elsewhere
  18. * records what was true when it was written.
  19. *
  20. * Sites the token rule cannot express (dot-notation access, unquoted object
  21. * keys, regex literals, the vendored-manifest table) are listed in
  22. * {@link EXACT_EDITS} with an exact hit count, so an upstream change to one of
  23. * them fails loudly instead of being silently skipped.
  24. *
  25. * Usage: `pnpm run rescope-vendor [--apply|--check] [--reverse]`. Without a
  26. * mode it reports what would change. `--check` asserts the post-state: no
  27. * residue, every exact edit landed, every postcondition holds, and a second
  28. * `--apply` would be a no-op.
  29. */
  30. import { execFileSync } from 'node:child_process'
  31. import { existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'
  32. import { resolve } from 'node:path'
  33. import { fileURLToPath } from 'node:url'
  34. const root = resolve(import.meta.dirname, '..')
  35. /** One vendored package's directory, upstream npm name, and rescoped name. */
  36. interface Rename {
  37. readonly directory: string
  38. readonly upstream: string
  39. readonly scoped: string
  40. }
  41. /** The mapping this codemod applies; `vendor/README.md` carries the same table. */
  42. const RENAMES: readonly Rename[] = [
  43. { directory: 'cordis', upstream: 'cordis', scoped: '@deepseek-ai/cordis' },
  44. { directory: 'cosmokit', upstream: 'cosmokit', scoped: '@deepseek-ai/cosmokit' },
  45. { directory: 'schemastery', upstream: 'schemastery', scoped: '@deepseek-ai/schemastery' },
  46. { directory: 'loader', upstream: '@cordisjs/plugin-loader', scoped: '@deepseek-ai/cordis-plugin-loader' },
  47. { directory: 'include', upstream: '@cordisjs/plugin-include', scoped: '@deepseek-ai/cordis-plugin-include' },
  48. { directory: 'group', upstream: '@cordisjs/plugin-group', scoped: '@deepseek-ai/cordis-plugin-group' },
  49. { directory: 'timer', upstream: '@cordisjs/plugin-timer', scoped: '@deepseek-ai/cordis-plugin-timer' },
  50. { directory: 'hmr', upstream: '@cordisjs/plugin-hmr', scoped: '@deepseek-ai/cordis-plugin-hmr' },
  51. { directory: 'logger-console', upstream: '@cordisjs/plugin-logger-console', scoped: '@deepseek-ai/cordis-plugin-logger-console' },
  52. ]
  53. const EXTENSIONS = ['.ts', '.tsx', '.js', '.mjs', '.cjs', '.tpl', '.json', '.yml', '.yaml', '.md'] as const
  54. /** An exact-string edit the token rule cannot express, with its required hit count. */
  55. interface ExactEdit {
  56. readonly id: string
  57. readonly file: string
  58. readonly find: string
  59. readonly replace: string
  60. readonly expect: number
  61. }
  62. /**
  63. * A file where an upstream name also appears as a vendor DIRECTORY name or an
  64. * upstream runtime identifier: the generic pass is disabled for the listed
  65. * names and {@link EXACT_EDITS} renames the real package-name occurrences.
  66. */
  67. interface GenericSkip {
  68. readonly file: string
  69. readonly upstream: readonly string[]
  70. }
  71. const GENERIC_SKIPS: readonly GenericSkip[] = [
  72. // `vendorPackages` lists vendor/ directory names, joined with 'vendor' below it.
  73. { file: 'packages/examples/acp-demo/tests/built-bin.e2e.ts', upstream: ['cordis', 'cosmokit', 'schemastery'] },
  74. // `Symbol.for('schemastery')` and the `vendor:` metadata field are upstream identifiers.
  75. { file: 'vendor/schemastery/src/index.ts', upstream: ['schemastery'] },
  76. // Asserts the vendored-manifest table, which gains an upstream-name column.
  77. { file: 'scripts/gen-third-party-notices.spec.ts', upstream: RENAMES.map(rename => rename.upstream) },
  78. // `cordis` is also an agent-preset id — the directory name under
  79. // apps/cli/config/agent-presets/ — so in these files the bare name is
  80. // product data, not a package reference. Renaming it changed which preset
  81. // the creator flow stages and which id the roster reports.
  82. { file: 'packages/client/ui-agent-preset/src/client/AgentPresetSection.tsx', upstream: ['cordis'] },
  83. { file: 'packages/client/ui-agent-preset/src/client/index.ts', upstream: ['cordis'] },
  84. { file: 'packages/client/ui-agent-preset/tests/apply.spec.ts', upstream: ['cordis'] },
  85. { file: 'packages/client/ui-agent-preset/tests/locales.spec.ts', upstream: ['cordis'] },
  86. { file: 'packages/client/ui-agent-preset/tests/section.spec.tsx', upstream: ['cordis'] },
  87. { file: 'apps/cli/tests/web-agent-presets.e2e.ts', upstream: ['cordis'] },
  88. { file: 'apps/web/tests/agent-preset-authoring.e2e.ts', upstream: ['cordis'] },
  89. { file: 'packages/preset/agent-presets/tests/session.spec.ts', upstream: ['cordis'] },
  90. // The preset's own composition: its header comment and its system prompt name
  91. // the preset a model mounts, so the scoped name would send the model after an
  92. // id no roster reports.
  93. { file: 'apps/cli/config/agent-presets/cordis/agent.cordis.yml', upstream: ['cordis'] },
  94. // GROUP_ORDER holds `packages/<group>/` directory names, not package names.
  95. { file: 'scripts/gen-module-graph.ts', upstream: ['cordis'] },
  96. { file: 'scripts/gen-doc-graphs.ts', upstream: ['cordis'] },
  97. ]
  98. /** A string that must appear exactly `count` times once the rescope has run. */
  99. interface PostCondition {
  100. readonly file: string
  101. readonly text: string
  102. readonly count: number
  103. }
  104. const POSTCONDITIONS: readonly PostCondition[] = [
  105. { file: 'vendor/cordis/package.json', text: '"name": "@deepseek-ai/cordis"', count: 1 },
  106. { file: 'vendor/hmr/package.json', text: '"name": "@deepseek-ai/cordis-plugin-hmr"', count: 1 },
  107. { file: 'scripts/cordis-walk.ts', text: '@deepseek-ai\\/cordis', count: 1 },
  108. { file: 'scripts/cordis-walk.ts', text: '!== \'@deepseek-ai/cordis\'', count: 1 },
  109. { file: 'scripts/gen-scoped-events.ts', text: '=== \'@deepseek-ai/cordis\'', count: 1 },
  110. { file: 'packages/typert/generator/src/analyzer.ts', text: '!== \'@deepseek-ai/cordis\'', count: 2 },
  111. { file: 'scripts/check-workspace-constraints.ts', text: '?.[\'@deepseek-ai/cordis\']', count: 2 },
  112. { file: 'packages/boot/app-boot/tsdown.config.ts', text: '[\'@deepseek-ai/cordis-plugin-include\']', count: 1 },
  113. { file: 'tsconfig.base.json', text: '"@deepseek-ai/cordis-plugin-loader": ["./vendor/loader/src"]', count: 1 },
  114. // One insertion, once: a duplicated log entry is what a non-idempotent apply produced.
  115. { file: 'vendor/README.md', text: '17. **`@deepseek-ai` rescope**', count: 1 },
  116. { file: 'knip.json', text: '@cordisjs', count: 0 },
  117. { file: 'pnpm-workspace.yaml', text: 'cordis@4.0.0-rc.7', count: 0 },
  118. // The preset ids in this table are product data, not package names.
  119. { file: 'packages/client/ui-agent-preset/tests/locales.spec.ts', text: '[\'cordis\', \'presetCordisName\'', count: 1 },
  120. // The preset id the shipped composition documents to its own model.
  121. { file: 'apps/cli/config/agent-presets/cordis/agent.cordis.yml', text: 'The `cordis` agent preset', count: 1 },
  122. { file: 'apps/cli/config/agent-presets/cordis/agent.cordis.yml', text: 'corrupting the `cordis` preset', count: 1 },
  123. { file: 'packages/examples/acp-demo/tests/built-bin.e2e.ts', text: '\'cordis\', \'loader\', \'include\', \'timer\', \'hmr\', \'logger-console\',', count: 1 },
  124. ]
  125. /**
  126. * Every exact edit, in application order. Each `find` is written against the
  127. * PRE-rename text because these run before the generic pass, so no `find` may
  128. * quote a neighbouring line the generic pass would rewrite.
  129. */
  130. const EXACT_EDITS: readonly ExactEdit[] = [
  131. {
  132. id: 'cordis-walk-merge-head',
  133. file: 'scripts/cordis-walk.ts',
  134. find: 'const MERGE_HEAD = /declare module [\'"](?:cordis|\\.\\/context\\.ts)[\'"]/',
  135. replace: 'const MERGE_HEAD = /declare module [\'"](?:@deepseek-ai\\/cordis|\\.\\/context\\.ts)[\'"]/',
  136. expect: 1,
  137. },
  138. {
  139. id: 'constraints-manifest-lookup',
  140. file: 'scripts/check-workspace-constraints.ts',
  141. find: ` const peer = manifest.peerDependencies?.cordis
  142. const dev = manifest.devDependencies?.cordis
  143. if (!peer) errors.push(\`\${label}: cordis must be a peerDependency\`)
  144. if (!dev) errors.push(\`\${label}: cordis must also be a devDependency\`)
  145. if (peer && dev && peer !== dev) {
  146. errors.push(\`\${label}: cordis peer (\${peer}) and dev (\${dev}) ranges must match\`)`,
  147. replace: ` const peer = manifest.peerDependencies?.['@deepseek-ai/cordis']
  148. const dev = manifest.devDependencies?.['@deepseek-ai/cordis']
  149. if (!peer) errors.push(\`\${label}: @deepseek-ai/cordis must be a peerDependency\`)
  150. if (!dev) errors.push(\`\${label}: @deepseek-ai/cordis must also be a devDependency\`)
  151. if (peer && dev && peer !== dev) {
  152. errors.push(\`\${label}: @deepseek-ai/cordis peer (\${peer}) and dev (\${dev}) ranges must match\`)`,
  153. expect: 1,
  154. },
  155. {
  156. // The rescoped name is already covered by the `@deepseek-ai/.+` pattern beside it.
  157. id: 'knip-logger-console',
  158. file: 'knip.json',
  159. find: ` "ignoreDependencies": [
  160. "@cordisjs/plugin-logger-console",
  161. "@deepseek-ai/.+"
  162. ]
  163. },
  164. "packages/util/home": {`,
  165. replace: ` "ignoreDependencies": [
  166. "@deepseek-ai/.+"
  167. ]
  168. },
  169. "packages/util/home": {`,
  170. expect: 1,
  171. },
  172. {
  173. id: 'knip-bundle-base',
  174. file: 'knip.json',
  175. find: ` "packages/bundle/base": {
  176. "ignoreDependencies": [
  177. "@deepseek-ai/.+",
  178. "@cordisjs/.+"
  179. ]`,
  180. replace: ` "packages/bundle/base": {
  181. "ignoreDependencies": [
  182. "@deepseek-ai/.+"
  183. ]`,
  184. expect: 1,
  185. },
  186. {
  187. // Rescoped packages are never fetched from a registry, so the exclusion is dead config.
  188. id: 'pnpm-release-age',
  189. file: 'pnpm-workspace.yaml',
  190. find: `minimumReleaseAgeExclude:
  191. # Cordis release candidates are source-vendored and pinned in vendor/README.md
  192. # during the same-day sync that updates package manifests and the lockfile.
  193. - '@cordisjs/plugin-loader@1.0.0-rc.5'
  194. - cordis@4.0.0-rc.7
  195. `,
  196. replace: 'minimumReleaseAgeExclude:\n',
  197. expect: 1,
  198. },
  199. {
  200. id: 'publication-set-scope-assertion',
  201. file: 'scripts/publish-npm-baseline.ts',
  202. find: ' if (!isVendored && !name.startsWith(\'@deepseek-ai/\')) {',
  203. replace: ` // Vendored packages are rescoped too (vendor/README.md), so publication
  204. // never carries an upstream name that would squat it on the registry.
  205. if (!name.startsWith('@deepseek-ai/')) {`,
  206. expect: 1,
  207. },
  208. {
  209. id: 'vendor-readme-preamble',
  210. file: 'vendor/README.md',
  211. find: 'All vendored packages keep their **original npm names** and are marked `private: true` — they are never published from this repo. `pnpm-workspace.yaml#linkWorkspacePackages` makes matching upstream semver ranges resolve these pinned workspaces, including imports from built `lib/`; disabling it substitutes npm copies behind the same names.',
  212. replace: 'All vendored packages are **renamed into the `@deepseek-ai` scope** (`cordis` → `@deepseek-ai/cordis`, `@cordisjs/plugin-<x>` → `@deepseek-ai/cordis-plugin-<x>`): every harness package declares `cordis` as a peer dependency, so publishing the harness publishes this framework layer too, and a publication under the upstream names would squat them on the registry. Directory names and upstream version numbers are deliberately unchanged, so the manifest below still reads as an upstream snapshot. `pnpm-workspace.yaml#linkWorkspacePackages` makes those preserved semver ranges resolve these pinned workspaces, including imports from built `lib/`.',
  213. expect: 1,
  214. },
  215. {
  216. id: 'vendor-readme-schemastery-note',
  217. file: 'vendor/README.md',
  218. find: 'whose lazy `require(\'cosmokit\')` can race',
  219. replace: 'whose lazy `require(\'@deepseek-ai/cosmokit\')` can race',
  220. expect: 1,
  221. },
  222. {
  223. id: 'vendor-readme-table-head',
  224. file: 'vendor/README.md',
  225. find: '| Directory | npm name | Version | Upstream repo | Commit |\n|---|---|---|---|---|',
  226. replace: '| Directory | npm name | Upstream name | Version | Upstream repo | Commit |\n|---|---|---|---|---|---|',
  227. expect: 1,
  228. },
  229. {
  230. id: 'vendor-readme-local-modification-log',
  231. file: 'vendor/README.md',
  232. find: '\n16. **`cordis/package.json` publishes `src`**',
  233. replace: '\n16. **`cordis/package.json` publishes `src`**: added `src` to the `files` list, joining the other eight vendored packages. Cordis declares `"./src/*": "./src/*"` in its exports, so a tarball without `src` publishes an export map pointing at absent files; the release change judgement also reads `files` to decide whether a diff reaches the payload, and a package whose only published paths are build output has no tracked path to match.\n17. **`@deepseek-ai` rescope**: every vendored manifest `name`, every internal dependency entry among the vendored set, and every module specifier that reaches them use the scoped names in the manifest table\'s `npm name` column. Directory names, version numbers, and dependency ranges are unchanged, and no upstream runtime identifier is renamed — `Symbol.for(\'schemastery\')` and Schemastery\'s `vendor:` metadata field keep their upstream values. Re-apply with `pnpm run rescope-vendor --apply` after a sync; the table\'s two name columns are the mapping, restated for consumers in [docs/rescope.md](../docs/rescope.md).',
  234. expect: 1,
  235. },
  236. {
  237. // A plain fence listing the bundle's mounted tree: a bare token, no quotes.
  238. id: 'agent-spine-demo-mounted-tree',
  239. file: 'packages/examples/agent-spine-demo/README.md',
  240. find: '@cordisjs/plugin-timer timer service',
  241. replace: '@deepseek-ai/cordis-plugin-timer timer service',
  242. expect: 1,
  243. },
  244. {
  245. id: 'agent-spine-demo-mounted-tree-zh',
  246. file: 'packages/examples/agent-spine-demo/README.zh.md',
  247. find: '@cordisjs/plugin-timer timer service',
  248. replace: '@deepseek-ai/cordis-plugin-timer timer service',
  249. expect: 1,
  250. },
  251. {
  252. // The root contract claimed vendored packages keep their upstream names.
  253. id: 'root-agents-vendored-name-contract',
  254. file: 'AGENTS.md',
  255. find: 'vendored packages keep upstream names and are `private: true`. `cordis` is a peerDependency (+ dev) of every harness package.',
  256. replace: 'vendored packages are rescoped ([mapping](docs/rescope.md)) and `private: true`. `@deepseek-ai/cordis` is a peerDependency (+ dev) of every harness package.',
  257. expect: 1,
  258. },
  259. {
  260. // The client purity gate reads `@deepseek-ai/` as "another plugin package".
  261. // The rescope moves the vendored framework and its libraries into that
  262. // namespace, where the gate would reject the library imports client
  263. // bundles have always inlined, so it needs their names.
  264. id: 'client-purity-vendored-libraries',
  265. file: 'packages/client/tsdown.client.ts',
  266. find: '/** Generated descriptor/codec contribution with no shared runtime identity. */',
  267. replace: `/**
  268. * Vendored framework libraries: rescoped into @deepseek-ai, so the gate below
  269. * would read them as plugin packages. They carry no cross-plugin runtime
  270. * identity to share — the framework itself is a platform module (external),
  271. * while these are ordinary libraries a browser bundle inlines.
  272. */
  273. const VENDORED_LIBRARY = /^@deepseek-ai\\/(cosmokit|schemastery)(\\/|$)/
  274. /** Generated descriptor/codec contribution with no shared runtime identity. */`,
  275. expect: 1,
  276. },
  277. {
  278. id: 'client-purity-vendored-libraries-predicate',
  279. file: 'packages/client/tsdown.client.ts',
  280. find: ' if (INLINE_SAFE.test(source) || GENERATED_REMOTE.test(source)) return null // wire contribution: inline is the point',
  281. replace: ` if (VENDORED_LIBRARY.test(source)) return null // vendored library: inline, no shared identity
  282. if (INLINE_SAFE.test(source) || GENERATED_REMOTE.test(source)) return null // wire contribution: inline is the point`,
  283. expect: 1,
  284. },
  285. {
  286. // The step-1 file tree told the reader to keep the upstream name, one
  287. // paragraph above the invariant that says to rescope it.
  288. id: 'vendoring-cookbook-tree-comment',
  289. file: 'docs/cookbook/adding-a-vendored-package.md',
  290. find: ' package.json # from upstream; set "private": true, keep name/exports/type',
  291. replace: ' package.json # from upstream; set "private": true, rescope the name, keep exports/type',
  292. expect: 1,
  293. },
  294. {
  295. id: 'vendoring-cookbook-tree-comment-zh',
  296. file: 'docs/cookbook/adding-a-vendored-package.zh.md',
  297. find: ' package.json # from upstream; set "private": true, keep name/exports/type',
  298. replace: ' package.json # from upstream; set "private": true, rescope the name, keep exports/type',
  299. expect: 1,
  300. },
  301. {
  302. // The checklist told the next vendoring to keep upstream's name.
  303. id: 'vendoring-cookbook-name-invariant',
  304. file: 'docs/cookbook/adding-a-vendored-package.md',
  305. find: "keep upstream's `name`/`version`/`exports`/`type`",
  306. replace: "rescope the `name` ([mapping](../rescope.md)) while keeping upstream's `version`/`exports`/`type`",
  307. expect: 1,
  308. },
  309. {
  310. id: 'vendoring-cookbook-name-invariant-zh',
  311. file: 'docs/cookbook/adding-a-vendored-package.zh.md',
  312. find: '保留上游的 `name`/`version`/`exports`/`type`',
  313. replace: '改写 `name` 的 scope([映射](../rescope.md)),保留上游的 `version`/`exports`/`type`',
  314. expect: 1,
  315. },
  316. {
  317. // The real package references in files whose other `cordis` strings are preset ids.
  318. id: 'agent-preset-spec-framework-import',
  319. file: 'packages/client/ui-agent-preset/tests/apply.spec.ts',
  320. find: "import { Context } from 'cordis'",
  321. replace: "import { Context } from '@deepseek-ai/cordis'",
  322. expect: 1,
  323. },
  324. {
  325. id: 'web-agent-presets-e2e-framework-import',
  326. file: 'apps/cli/tests/web-agent-presets.e2e.ts',
  327. find: "import { Context } from 'cordis'",
  328. replace: "import { Context } from '@deepseek-ai/cordis'",
  329. expect: 1,
  330. },
  331. {
  332. id: 'notices-vendored-row-type',
  333. file: 'scripts/gen-third-party-notices.ts',
  334. find: `export interface VendoredRow {
  335. npmName: string
  336. upstream: string
  337. }`,
  338. replace: `export interface VendoredRow {
  339. npmName: string
  340. /** The name this package carries upstream; MIT attribution names the fork's origin, not our scope. */
  341. upstreamName: string
  342. upstream: string
  343. }`,
  344. expect: 1,
  345. },
  346. {
  347. id: 'notices-vendored-row-parse',
  348. file: 'scripts/gen-third-party-notices.ts',
  349. find: ` const match = /^\\| \\x60\\S+\\/\\x60 \\| \\x60([^\\x60]+)\\x60 \\| \\S+ \\| (https:\\/\\/\\S+?)(?: \\([^)]*\\))? \\| \\x60[0-9a-f]+\\x60 \\|$/.exec(line)
  350. if (match === null) continue
  351. const [, npmName, upstream] = match
  352. if (npmName === undefined || upstream === undefined) continue
  353. rows.push({ npmName, upstream })`,
  354. replace: ` const match = new RegExp(String.raw\`^\\| \\x60\\S+\\/\\x60 \\| \\x60([^\\x60]+)\\x60 \\| \\x60([^\\x60]+)\\x60 \\| \\S+ \\| \`
  355. + String.raw\`(https:\\/\\/\\S+?)(?: \\([^)]*\\))? \\| \\x60[0-9a-f]+\\x60 \\|$\`).exec(line)
  356. if (match === null) continue
  357. const [, npmName, upstreamName, upstream] = match
  358. if (npmName === undefined || upstreamName === undefined || upstream === undefined) continue
  359. rows.push({ npmName, upstreamName, upstream })`,
  360. expect: 1,
  361. },
  362. {
  363. id: 'notices-vendored-section',
  364. file: 'scripts/gen-third-party-notices.ts',
  365. find: 'The Cordis framework and its foundation libraries are source-vendored into this repository rather than consumed from npm. All are MIT-licensed',
  366. replace: 'The Cordis framework and its foundation libraries are source-vendored into this repository rather than consumed from npm, and republished under the \\`@deepseek-ai\\` scope. All are MIT-licensed',
  367. expect: 1,
  368. },
  369. {
  370. id: 'notices-vendored-table',
  371. file: 'scripts/gen-third-party-notices.ts',
  372. find: `| Package | Upstream | License |
  373. | --- | --- | --- |
  374. \${vendored.map(row => \`| \\\`\${row.npmName}\\\` | [\${row.upstream.replace('https://', '')}](\${row.upstream}) | MIT |\`).join('\\n')}`,
  375. replace: `| Package | Upstream name | Upstream | License |
  376. | --- | --- | --- | --- |
  377. \${vendored.map(row => \`| \\\`\${row.npmName}\\\` | \\\`\${row.upstreamName}\\\` | [\${row.upstream.replace('https://', '')}](\${row.upstream}) | MIT |\`).join('\\n')}`,
  378. expect: 1,
  379. },
  380. {
  381. id: 'notices-spec-row-fixture',
  382. file: 'scripts/gen-third-party-notices.spec.ts',
  383. find: ' expect(rows).toContainEqual({ npmName: \'cordis\', upstream: \'https://github.com/cordiverse/cordis\' })',
  384. replace: ` expect(rows).toContainEqual({
  385. npmName: '@deepseek-ai/cordis',
  386. upstreamName: 'cordis',
  387. upstream: 'https://github.com/cordiverse/cordis',
  388. })`,
  389. expect: 1,
  390. },
  391. {
  392. id: 'notices-spec-shape-fixture',
  393. file: 'scripts/gen-third-party-notices.spec.ts',
  394. find: 'parseVendoredRows(\'| `cordis/` | cordis | 4.0.0 | https://example.com | `abc123` |\\n\')',
  395. replace: 'parseVendoredRows(\'| `cordis/` | `@deepseek-ai/cordis` | cordis | 4.0.0 | https://example.com | `abc123` |\\n\')',
  396. expect: 1,
  397. },
  398. {
  399. // The framework peer is no longer a registry name, so the rehearsal must install this
  400. // repository's vendored copies; cosmokit comes along as cordis's own dependency.
  401. id: 'packed-install-vendored-peer',
  402. file: 'packages/sandbox/sandbox-local/tests/packed-install.e2e.ts',
  403. find: ` 'packages/support/invariants',
  404. ]`,
  405. replace: ` 'packages/support/invariants',
  406. // The framework and the vendored packages the closure declares outright:
  407. // rescoped into @deepseek-ai, so the consumer installs this repository's
  408. // copies. Schemastery is a hard dependency of three members above, not a
  409. // peer, so npm resolves it while installing them.
  410. 'vendor/cordis',
  411. 'vendor/cosmokit',
  412. 'vendor/schemastery',
  413. ]`,
  414. expect: 1,
  415. },
  416. {
  417. id: 'packed-install-registry-spec',
  418. file: 'packages/sandbox/sandbox-local/tests/packed-install.e2e.ts',
  419. find: ` // Peer ranges resolve to the tarballs; Cordis is pinned to their peer range. Do not omit optional
  420. // dependencies because the launcher selects its OS/CPU package through one.
  421. writeFileSync(join(consumerDir, 'package.json'), JSON.stringify({ name: 'dsh-packed-consumer', private: true, type: 'module' }))
  422. const install = spawnSync('npm', ['install', '--no-audit', '--no-fund', ...tarballs, 'cordis@4.0.0-rc.7'], {`,
  423. replace: ` // Peer ranges resolve to the tarballs, the framework peer included. Do not omit optional
  424. // dependencies because the launcher selects its OS/CPU package through one.
  425. writeFileSync(join(consumerDir, 'package.json'), JSON.stringify({ name: 'dsh-packed-consumer', private: true, type: 'module' }))
  426. const install = spawnSync('npm', ['install', '--no-audit', '--no-fund', ...tarballs], {`,
  427. expect: 1,
  428. },
  429. {
  430. id: 'packed-install-module-doc',
  431. file: 'packages/sandbox/sandbox-local/tests/packed-install.e2e.ts',
  432. find: ` * Keyless publish-path rehearsal. It packs the provider, its workspace peers, and the current
  433. * repository's Landlock entry/platform packages, then installs those exact tarballs in an external
  434. * plain-Node consumer. The host launcher comes from the exact local tarballs, so no registry copy,
  435. * tsx, path mapping, or workspace resolution can hide missing files, dependency errors, or lost
  436. * executable modes.`,
  437. replace: ` * Keyless publish-path rehearsal. It packs the provider, its workspace peers, the vendored framework
  438. * peer, and the current repository's Landlock entry/platform packages, then installs those exact
  439. * tarballs in an external plain-Node consumer. The host launcher comes from the exact local tarballs,
  440. * so no registry copy, tsx, path mapping, or workspace resolution can hide missing files, dependency
  441. * errors, or lost executable modes.`,
  442. expect: 1,
  443. },
  444. // The manifest table's name column plus the new upstream-name column, one edit per row.
  445. ...RENAMES.map(rename => ({
  446. id: `vendor-readme-row-${rename.directory}`,
  447. file: 'vendor/README.md',
  448. find: `| \`${rename.directory}/\` | \`${rename.upstream}\` | `,
  449. replace: `| \`${rename.directory}/\` | \`${rename.scoped}\` | \`${rename.upstream}\` | `,
  450. expect: 1,
  451. })),
  452. ]
  453. /** Files the rescope must never rewrite. */
  454. function excluded(file: string): boolean {
  455. if (file === 'scripts/rescope-vendor.ts') return true // the mapping itself
  456. if (file.startsWith('.agents/notes/')) return true // notes record what was true when written
  457. // Recorded model payloads quote documentation verbatim, so they must mirror the
  458. // sources on disk — including the notes this rescope leaves alone.
  459. if (file.startsWith('scripts/snapshots/')) return true
  460. // The mapping documents state both names on purpose.
  461. if (file === 'docs/rescope.md' || file === 'docs/rescope.zh.md') return true
  462. if (file.endsWith('.i18n.yaml')) return true // blob-hash records, re-recorded by the pairing gate
  463. if (file === 'pnpm-lock.yaml') return true // regenerated by pnpm install
  464. if (/^vendor\/[^/]+\/(README\.md|LICENSE)$/.test(file)) return true // upstream files kept verbatim
  465. return !EXTENSIONS.some(extension => file.endsWith(extension))
  466. }
  467. function escapeRegExp(value: string): string {
  468. return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
  469. }
  470. /** One name's rewrite, precompiled for both delimited forms. */
  471. interface Pattern {
  472. readonly upstream: string
  473. readonly from: string
  474. readonly to: string
  475. readonly token: RegExp
  476. readonly yamlName: RegExp
  477. }
  478. function patterns(reverse: boolean): Pattern[] {
  479. return RENAMES
  480. .map(rename => ({
  481. upstream: rename.upstream,
  482. from: reverse ? rename.scoped : rename.upstream,
  483. to: reverse ? rename.upstream : rename.scoped,
  484. }))
  485. .sort((left, right) => right.from.length - left.from.length)
  486. .map(rename => ({
  487. ...rename,
  488. token: new RegExp(`(['"\`])${escapeRegExp(rename.from)}((?:/[^'"\`\\s]*)?)\\1`, 'g'),
  489. yamlName: new RegExp(`^(\\s*(?:-\\s*)?name:[ \\t]+)${escapeRegExp(rename.from)}([ \\t]*(?:#.*)?)$`, 'gm'),
  490. }))
  491. }
  492. function skipped(file: string, pattern: Pattern): boolean {
  493. return GENERIC_SKIPS.some(skip => skip.file === file && skip.upstream.includes(pattern.upstream))
  494. }
  495. function rewriteLine(line: string, file: string, all: readonly Pattern[]): string {
  496. let out = line
  497. for (const pattern of all) {
  498. if (skipped(file, pattern)) continue
  499. out = out.replace(pattern.token, (_match, quote: string, subpath: string) => `${quote}${pattern.to}${subpath}${quote}`)
  500. out = out.replace(pattern.yamlName, (_match, prefix: string, suffix: string) => `${prefix}${pattern.to}${suffix}`)
  501. }
  502. return out
  503. }
  504. /**
  505. * Rewrite a file's eligible lines.
  506. *
  507. * Markdown splits in two. Every fence is code a reader copies or a
  508. * configuration they mount, so every fence follows the rename regardless of its
  509. * info string. Prose follows it only under `docs/`, where a sentence quoting
  510. * `` `cordis` `` teaches a name this repository no longer resolves; elsewhere
  511. * prose is a record of what was true when it was written, and the same spelling
  512. * can mean something else entirely — the Python SDK's `cordis` option, or the
  513. * unvendored `@cordisjs/plugin-http`.
  514. */
  515. function rewrite(text: string, file: string, all: readonly Pattern[]): { text: string; lines: number } {
  516. const markdown = file.endsWith('.md')
  517. const prose = markdown && file.startsWith('docs/')
  518. let insideFence = false
  519. let lines = 0
  520. const out = text.split('\n').map((line) => {
  521. if (markdown) {
  522. if (/^\s*```/.test(line)) {
  523. insideFence = !insideFence
  524. return line
  525. }
  526. if (!insideFence && !prose) return line
  527. }
  528. const next = rewriteLine(line, file, all)
  529. if (next !== line) lines += 1
  530. return next
  531. })
  532. return { text: out.join('\n'), lines }
  533. }
  534. function classify(file: string): string {
  535. if (/^vendor\/[^/]+\/package\.json$/.test(file)) return 'vendor manifest name'
  536. if (file.endsWith('package.json')) return 'package.json dependencies'
  537. if (/\.(ts|tsx|js|mjs|cjs|tpl)$/.test(file)) return 'code specifiers'
  538. if (/\.(yml|yaml)$/.test(file)) return 'YAML plugin names'
  539. if (file.endsWith('.json')) return 'JSON configuration'
  540. return 'Markdown fences and docs prose'
  541. }
  542. /**
  543. * One exact edit's state in the text it targets. `pending` means the source
  544. * form is present and the target form absent; `applied` means the reverse;
  545. * anything else — a partial application, a moved site, or a DUPLICATED
  546. * insertion — is `invalid`, so it fails the run instead of being applied again.
  547. */
  548. export type ExactEditState = 'pending' | 'applied' | 'invalid'
  549. /**
  550. * Classify one exact edit against its target text.
  551. *
  552. * An insertion keeps its anchor (`replace` contains `find`) and a deletion
  553. * keeps its remainder (`find` contains `replace`), so neither can be judged by
  554. * the source form alone: the surviving side counts the target form instead.
  555. * @param text - the complete current text of the edited file.
  556. * @param find - the source form, already oriented for the running direction.
  557. * @param replace - the target form, already oriented for the running direction.
  558. * @param expect - how many occurrences one complete application produces.
  559. * @returns Whether the edit is pending, already applied, or invalid.
  560. */
  561. export function exactEditState(text: string, find: string, replace: string, expect: number): ExactEditState {
  562. const hits = text.split(find).length - 1
  563. const landed = text.split(replace).length - 1
  564. if (replace.includes(find)) {
  565. if (landed === expect) return 'applied'
  566. return landed === 0 && hits === expect ? 'pending' : 'invalid'
  567. }
  568. if (find.includes(replace)) {
  569. if (hits === 0) return landed === expect ? 'applied' : 'invalid'
  570. return hits === expect ? 'pending' : 'invalid'
  571. }
  572. if (hits === 0 && landed === expect) return 'applied'
  573. return hits === expect && landed === 0 ? 'pending' : 'invalid'
  574. }
  575. function main(): void {
  576. const args = process.argv.slice(2)
  577. const mode = args.includes('--apply') ? 'apply' : args.includes('--check') ? 'check' : 'dry'
  578. const reverse = args.includes('--reverse')
  579. const all = patterns(reverse)
  580. const files = execFileSync('git', ['ls-files', '-z'], { cwd: root, encoding: 'utf8' })
  581. .split('\0')
  582. .filter(file => file !== '' && !excluded(file))
  583. const counts = new Map<string, { files: number; lines: number }>()
  584. const failures: string[] = []
  585. const outstanding: string[] = []
  586. // Classify every exact edit before writing anything: a single invalid site
  587. // means the mapping and the tree disagree, and a half-applied tree is worse
  588. // than an untouched one.
  589. const planned: { edit: ExactEdit; path: string; find: string; replace: string }[] = []
  590. for (const edit of EXACT_EDITS) {
  591. const path = resolve(root, edit.file)
  592. const before = readFileSync(path, 'utf8')
  593. const find = reverse ? edit.replace : edit.find
  594. const replace = reverse ? edit.find : edit.replace
  595. const state = exactEditState(before, find, replace, edit.expect)
  596. if (state === 'invalid') {
  597. failures.push(`exact edit ${edit.id}: ${edit.file} is neither pending nor cleanly applied (duplicated, partial, or moved)`)
  598. continue
  599. }
  600. if (mode === 'check') {
  601. if (state !== 'applied') failures.push(`exact edit ${edit.id} did not land in ${edit.file}`)
  602. continue
  603. }
  604. if (state === 'pending') planned.push({ edit, path, find, replace })
  605. }
  606. if (failures.length > 0) {
  607. for (const failure of failures) console.error(`rescope-vendor: ${failure}`)
  608. console.error(`rescope-vendor: ${String(failures.length)} problem(s); nothing was written.`)
  609. process.exitCode = 1
  610. return
  611. }
  612. if (mode === 'apply') {
  613. // Re-read per edit: two edits can target one file, and a stale snapshot
  614. // would let the second write discard the first.
  615. for (const { path, find, replace } of planned) {
  616. writeFileSync(path, readFileSync(path, 'utf8').split(find).join(replace))
  617. }
  618. }
  619. for (const file of files) {
  620. const path = resolve(root, file)
  621. const before = readFileSync(path, 'utf8')
  622. const { text: after, lines } = rewrite(before, file, all)
  623. if (after === before) continue
  624. outstanding.push(file)
  625. const kind = classify(file)
  626. const current = counts.get(kind) ?? { files: 0, lines: 0 }
  627. counts.set(kind, { files: current.files + 1, lines: current.lines + lines })
  628. if (mode === 'apply') writeFileSync(path, after)
  629. }
  630. console.log(`rescope-vendor: ${mode}${reverse ? ' --reverse' : ''} over ${String(files.length)} tracked files`)
  631. for (const kind of [...counts.keys()].sort()) {
  632. const { files: count, lines } = counts.get(kind) ?? { files: 0, lines: 0 }
  633. console.log(` ${kind.padEnd(24)} ${String(count).padStart(4)} file(s), ${String(lines)} line(s)`)
  634. }
  635. if (mode !== 'dry') {
  636. for (const check of POSTCONDITIONS) {
  637. if (reverse) break
  638. const path = resolve(root, check.file)
  639. const hits = existsSync(path) ? readFileSync(path, 'utf8').split(check.text).length - 1 : -1
  640. if (hits !== check.count) {
  641. failures.push(`postcondition: ${check.file} has ${String(hits)} occurrence(s) of ${JSON.stringify(check.text)}, expected ${String(check.count)}`)
  642. }
  643. }
  644. // The generic pass above already told us which files would still change,
  645. // which in check mode is exactly the residue-and-idempotency signal.
  646. if (mode === 'check') {
  647. for (const file of outstanding) failures.push(`residue: ${file} still carries a pre-rescope name token`)
  648. }
  649. }
  650. if (failures.length > 0) {
  651. for (const failure of failures) console.error(`rescope-vendor: ${failure}`)
  652. console.error(`rescope-vendor: ${String(failures.length)} problem(s); the mapping or an upstream site moved.`)
  653. process.exitCode = 1
  654. } else if (mode === 'check') {
  655. console.log('rescope-vendor: post-state verified — no residue, every exact edit landed, idempotent.')
  656. } else if (mode === 'apply') {
  657. console.log('rescope-vendor: applied. Run `pnpm install`, `pnpm run gen-third-party-notices`, and re-record the touched bilingual pairs.')
  658. }
  659. }
  660. // Importing this module for its exported classifier must not run the codemod.
  661. if (process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) {
  662. main()
  663. }