verify-cordis-config.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. /**
  2. * Validate Cordis Loader entry metadata and package resolution.
  3. *
  4. * The Loader interpolates only a plugin entry's `config`; expression objects in
  5. * fields such as `disabled` remain truthy data and silently change composition.
  6. * Example configs and the dsh Web composition resolve named plugins from their
  7. * owning workspace manifests. Local example packages must also be in the root
  8. * TypeScript project graph.
  9. */
  10. import { globSync, readFileSync } from 'node:fs'
  11. import { dirname, relative, resolve } from 'node:path'
  12. import * as yaml from 'js-yaml'
  13. import ts from 'typescript'
  14. import { cordisConfigFiles } from './cordis-config-files.ts'
  15. interface JsExpr {
  16. __jsExpr: string
  17. }
  18. interface PackageManifest {
  19. name?: string
  20. dependencies?: Record<string, string>
  21. }
  22. interface PluginReference {
  23. file: string
  24. name: string
  25. }
  26. const root = resolve(import.meta.dirname, '..')
  27. // These example files are overlays consumed by the built dsh app, so their bare
  28. // specifiers resolve from apps/cli rather than the examples workspace.
  29. const appOverlayFiles = new Set([
  30. 'examples/web-cordis/cordis.yml',
  31. 'examples/web-schedule/cordis.yml',
  32. ...globSync('examples/mcp-memory/*.cordis.yml', { cwd: root }),
  33. ])
  34. const metadataFields = ['id', 'name', 'group', 'disabled', 'inject', 'intercept', 'isolate'] as const
  35. /** The adaptive directory-picker chooser package (mounts a backend row at boot). */
  36. const CHOOSER_PACKAGE = '@deepseek-ai/dsh-host-directory-picker-auto'
  37. /**
  38. * The backends the chooser mounts by runtime string (mirror of its exported
  39. * `BACKEND_PACKAGES`), invisible to yml-row scanning: a composition mounting
  40. * the chooser must resolve both, or keyless Linux CI (which only ever
  41. * resolves `browse`) hides a dropped `-native` dependency until a macOS boot.
  42. */
  43. const CHOOSER_BACKEND_PACKAGES = [
  44. '@deepseek-ai/dsh-host-directory-picker-native',
  45. '@deepseek-ai/dsh-host-directory-picker-browse',
  46. ]
  47. const jsExprType = new yaml.Type('tag:yaml.org,2002:js', {
  48. kind: 'scalar',
  49. resolve: data => typeof data === 'string',
  50. construct: (data: unknown): JsExpr => {
  51. if (typeof data !== 'string') throw new TypeError('!!js requires a scalar string')
  52. return { __jsExpr: data }
  53. },
  54. })
  55. const schema = yaml.JSON_SCHEMA.extend(jsExprType)
  56. const files = cordisConfigFiles(root)
  57. const errors: string[] = []
  58. const pluginReferences: PluginReference[] = []
  59. for (const file of files) {
  60. const document: unknown = yaml.load(readFileSync(resolve(root, file), 'utf8'), { schema })
  61. if (!isUnknownArray(document)) {
  62. errors.push(`${file}: root must be a Loader entry array`)
  63. continue
  64. }
  65. for (let index = 0; index < document.length; index++) {
  66. validateEntry(document[index], file, `[${index}]`)
  67. }
  68. }
  69. errors.push(...validateExampleResolution())
  70. errors.push(...validateAppResolution())
  71. errors.push(...validateSourcePlaneResolution())
  72. errors.push(...validatePresetPlaneSeparation())
  73. errors.push(...validateClientHalvesDeclared())
  74. if (errors.length > 0) {
  75. console.error('verify-cordis-config: invalid Loader metadata or plugin package resolution:')
  76. for (const error of errors) console.error(`- ${error}`)
  77. process.exitCode = 1
  78. } else {
  79. console.log(`verify-cordis-config: ${files.length} config files passed.`)
  80. }
  81. /**
  82. * A browser plugin must declare the browser half it ships.
  83. *
  84. * The browser roster is discovered by scanning composed packages for a
  85. * `dsh.client` block, and the node half of a surface plugin is an empty
  86. * `apply`. A `packages/client` package that exports `./client` without that
  87. * block therefore composes, activates, and contributes nothing — its bundle is
  88. * never served and no error is raised anywhere. The mismatch is invisible in
  89. * the composition file, so it is checked against the manifests instead. Only
  90. * this group is checked: a Host package's `./client` export is the typed wire
  91. * face its browser consumers import, not a plugin the roster serves.
  92. * @returns one violation per client package whose `./client` export and
  93. * `dsh.client` declaration disagree.
  94. */
  95. function validateClientHalvesDeclared(): string[] {
  96. return globSync('packages/client/*/package.json', { cwd: root }).flatMap((manifestPath) => {
  97. const manifest = readManifest(manifestPath) as PackageManifest & {
  98. exports?: Record<string, unknown>
  99. dsh?: { client?: unknown }
  100. }
  101. const shipsClient = manifest.exports !== undefined && Object.hasOwn(manifest.exports, './client')
  102. const declaresClient = manifest.dsh?.client !== undefined
  103. if (shipsClient === declaresClient) return []
  104. return [shipsClient
  105. ? `${manifestPath}: exports "./client" but declares no dsh.client, so its browser half is never served`
  106. : `${manifestPath}: declares dsh.client but exports no "./client" entry to serve`]
  107. })
  108. }
  109. /**
  110. * No shipped agent preset may repeat a row the host composition still runs.
  111. *
  112. * A preset contributes what ONE session adds to the host's registries. A row
  113. * active on both planes is therefore mounted twice — once per process and once
  114. * per session — and what that costs depends on what the row does: a provider
  115. * behind an `isolate` realm shadows the host's for its own consumers, so a host
  116. * contributor to that service reaches nobody; a row that registers into a host
  117. * singleton registers once per live session, so the second one collides.
  118. *
  119. * Both have happened. `bash-env` in a preset realm left `DSH_WEB_URL` reaching
  120. * no shell, and `tool-subagent-report` handed every child `report` once per live
  121. * session until the second registration threw. Neither changes a tool catalog,
  122. * so no catalog assertion can see them — and the shipped presets are near-copies
  123. * of each other, so a fix applied to three of four is the normal failure.
  124. * @returns one diagnostic per preset row that is also active on the host plane.
  125. */
  126. function validatePresetPlaneSeparation(): string[] {
  127. const problems: string[] = []
  128. // The shipped Web surface is two bundle patch layers over an empty root.
  129. const hostFile = 'packages/bundle/base/cordis.patch.yml'
  130. const overlayFile = 'packages/bundle/web-app/cordis.patch.yml'
  131. const hostRows = rowIds(hostFile)
  132. const overlay = loadEntries(overlayFile)
  133. const disabled = new Set<string>()
  134. for (const entry of overlay) {
  135. if (!isRecord(entry)) continue
  136. if (entry.disabled === true && typeof entry.id === 'string') disabled.add(entry.id)
  137. }
  138. // The overlay's own inserts are host-plane too; its disables take them back out.
  139. const active = new Set([...hostRows, ...rowIds(overlayFile)].filter(id => !disabled.has(id)))
  140. for (const file of globSync('apps/cli/config/agent-presets/*/agent.cordis.yml', { cwd: root })) {
  141. for (const id of rowIds(file)) {
  142. if (!active.has(id)) continue
  143. problems.push(
  144. `${file}: row "${id}" is also active in the host composition; `
  145. + 'a row belongs to exactly one plane',
  146. )
  147. }
  148. }
  149. return problems
  150. }
  151. /** Every entry of one config file, or an empty list when it is not an entry array. */
  152. function loadEntries(file: string): unknown[] {
  153. const document: unknown = yaml.load(readFileSync(resolve(root, file), 'utf8'), { schema })
  154. return isUnknownArray(document) ? document : []
  155. }
  156. /**
  157. * Row ids declared anywhere in one config file, including inside group `config`
  158. * lists — a preset nests most of its rows in `isolate` groups.
  159. * @param file - repository-relative config path.
  160. * @returns the declared ids.
  161. */
  162. function rowIds(file: string): Set<string> {
  163. const ids = new Set<string>()
  164. const walk = (value: unknown): void => {
  165. if (isUnknownArray(value)) {
  166. for (const item of value) walk(item)
  167. return
  168. }
  169. if (!isRecord(value)) return
  170. if (typeof value.id === 'string' && typeof value.name === 'string') ids.add(value.id)
  171. for (const child of Object.values(value)) walk(child)
  172. }
  173. walk(loadEntries(file))
  174. return ids
  175. }
  176. function validateEntry(value: unknown, file: string, path: string): void {
  177. if (!isRecord(value)) {
  178. errors.push(`${file}${path}: entry must be an object`)
  179. return
  180. }
  181. recordPlugin(value, file)
  182. validateMetadata(value, file, path)
  183. if ((value.group === true || value.name === '@deepseek-ai/cordis-plugin-group') && isUnknownArray(value.config)) {
  184. for (let index = 0; index < value.config.length; index++) {
  185. validateEntry(value.config[index], file, `${path}.config[${index}]`)
  186. }
  187. }
  188. if (isUnknownArray(value.insert)) {
  189. for (let index = 0; index < value.insert.length; index++) {
  190. validateEntry(value.insert[index], file, `${path}.insert[${index}]`)
  191. }
  192. }
  193. if (value.name !== '@deepseek-ai/cordis-plugin-include') return
  194. const config = value.config
  195. if (!isRecord(config) || !isUnknownArray(config.patches)) return
  196. for (let index = 0; index < config.patches.length; index++) {
  197. const patch = config.patches[index]
  198. const patchPath = `${path}.config.patches[${index}]`
  199. if (!isRecord(patch)) continue
  200. recordPlugin(patch, file)
  201. validateMetadata(patch, file, patchPath)
  202. if (!isUnknownArray(patch.insert)) continue
  203. for (let insertIndex = 0; insertIndex < patch.insert.length; insertIndex++) {
  204. validateEntry(patch.insert[insertIndex], file, `${patchPath}.insert[${insertIndex}]`)
  205. }
  206. }
  207. }
  208. function recordPlugin(entry: Record<string, unknown>, file: string): void {
  209. if (typeof entry.name === 'string') pluginReferences.push({ file, name: entry.name })
  210. }
  211. function validateExampleResolution(): string[] {
  212. const violations: string[] = []
  213. const exampleManifest = readManifest('examples/package.json')
  214. const dependencies = exampleManifest.dependencies ?? {}
  215. const localPackages = localPackageDirectories()
  216. const rootReferences = rootProjectReferences()
  217. const exampleReferences = pluginReferences.filter(reference => reference.file.startsWith('examples/') && !appOverlayFiles.has(reference.file))
  218. violations.push(...missingPluginDependencies(exampleReferences, dependencies, 'examples/package.json'))
  219. const requiredPackages = new Set(exampleReferences.map(reference => packageNameFromSpecifier(reference.name)))
  220. const localExamplePackages = new Set([
  221. ...Object.keys(dependencies),
  222. ...[...requiredPackages].filter(packageName => packageName !== undefined),
  223. ])
  224. for (const packageName of localExamplePackages) {
  225. const packageDirectory = localPackages.get(packageName)
  226. if (packageDirectory === undefined || rootReferences.has(packageDirectory)) continue
  227. const repoPath = relative(root, packageDirectory).replaceAll('\\', '/')
  228. violations.push(`tsconfig.json: missing project reference for ${packageName} (${repoPath})`)
  229. }
  230. return violations
  231. }
  232. function validateAppResolution(): string[] {
  233. const violations: string[] = []
  234. // App overlays (and any config left under apps/cli/config) resolve from the
  235. // dsh app's own dependency surface — the profile module fallback mirrors it.
  236. const appDependencies = {
  237. ...readManifest('apps/cli/package.json').dependencies,
  238. // The fallback also links every bundle's own dependencies (healProfilesModuleFallback).
  239. ...Object.fromEntries(globSync('packages/bundle/*/package.json', { cwd: root })
  240. .flatMap(file => Object.entries(readManifest(file).dependencies ?? {}))),
  241. }
  242. const shipped = new Set(globSync('*.cordis.yml', { cwd: resolve(root, 'apps/cli/config') })
  243. .map(file => `apps/cli/config/${file}`))
  244. const appReferences = pluginReferences.filter(reference => shipped.has(reference.file) || appOverlayFiles.has(reference.file))
  245. violations.push(...missingPluginDependencies(appReferences, appDependencies, 'apps/cli/package.json or a bundle manifest'))
  246. // Each bundle's patch rows must resolve from that bundle's own dependencies:
  247. // per-layer resolution anchors on the bundle package directory.
  248. for (const manifestPath of globSync('packages/bundle/*/package.json', { cwd: root })) {
  249. const bundleDir = manifestPath.replace(/\/package\.json$/, '')
  250. const manifest = readManifest(manifestPath)
  251. const references = pluginReferences.filter(reference => reference.file.startsWith(`${bundleDir}/`))
  252. violations.push(...missingPluginDependencies(
  253. // A bundle may mount its own package (the web-app runtime row).
  254. references.filter(reference => packageNameFromSpecifier(reference.name) !== manifest.name),
  255. manifest.dependencies ?? {},
  256. manifestPath,
  257. ))
  258. }
  259. return violations
  260. }
  261. /**
  262. * Every configured specifier of a local workspace package must resolve through
  263. * the tsconfig `paths` facade to a `.ts`/`.tsx` source file. The `dsh` source
  264. * launch (tsx) and vitest resolve in the source plane; without a `paths` match
  265. * they fall back to package `exports`, which reach built `lib/` — present on a
  266. * built dev tree, absent on a clean one — so a missing mapping boots locally
  267. * yet breaks every clean checkout. Anything but a `.ts`/`.tsx` hit (a `.d.ts`
  268. * or `.js` under built `lib/`) is that artifact-plane fallback, not source.
  269. */
  270. function validateSourcePlaneResolution(): string[] {
  271. const violations: string[] = []
  272. const localPackages = localPackageDirectories()
  273. const config = ts.readConfigFile(resolve(root, 'tsconfig.base.json'), path => ts.sys.readFile(path))
  274. if (config.error !== undefined) {
  275. throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'))
  276. }
  277. const { options, errors: optionErrors } = ts.convertCompilerOptionsFromJson(
  278. (config.config as { compilerOptions?: unknown }).compilerOptions,
  279. root,
  280. 'tsconfig.base.json',
  281. )
  282. if (optionErrors.length > 0) {
  283. throw new Error(optionErrors.map(error => ts.flattenDiagnosticMessageText(error.messageText, '\n')).join('\n'))
  284. }
  285. // convertCompilerOptionsFromJson leaves `pathsBasePath` unset, so relative
  286. // `paths` targets resolve against the host's current directory; anchor it to
  287. // the repository root to keep the gate cwd-independent.
  288. const host: ts.ModuleResolutionHost = {
  289. fileExists: path => ts.sys.fileExists(path),
  290. readFile: path => ts.sys.readFile(path),
  291. directoryExists: path => ts.sys.directoryExists(path),
  292. getCurrentDirectory: () => root,
  293. }
  294. const sourceExtensions = new Set<string>([ts.Extension.Ts, ts.Extension.Tsx])
  295. const containingFile = resolve(root, 'scripts/verify-cordis-config.ts')
  296. const locationsBySpecifier = new Map<string, Set<string>>()
  297. for (const reference of pluginReferences) {
  298. const packageName = packageNameFromSpecifier(reference.name)
  299. if (packageName === undefined || !localPackages.has(packageName)) continue
  300. const locations = locationsBySpecifier.get(reference.name) ?? new Set<string>()
  301. locations.add(reference.file)
  302. locationsBySpecifier.set(reference.name, locations)
  303. }
  304. for (const [specifier, locations] of locationsBySpecifier) {
  305. const resolved = ts.resolveModuleName(specifier, containingFile, options, host).resolvedModule
  306. if (resolved !== undefined && sourceExtensions.has(resolved.extension)) continue
  307. violations.push(`${[...locations].join(', ')}: ${specifier} does not resolve to workspace source through tsconfig.base.json paths (add a mapping so the tsx source launch does not depend on built lib/)`)
  308. }
  309. return violations
  310. }
  311. function missingPluginDependencies(
  312. references: readonly PluginReference[],
  313. dependencies: Readonly<Record<string, string>>,
  314. manifestPath: string,
  315. ): string[] {
  316. const requiredPackages = new Map<string, Set<string>>()
  317. const require = (packageName: string, file: string): void => {
  318. const locations = requiredPackages.get(packageName) ?? new Set<string>()
  319. locations.add(file)
  320. requiredPackages.set(packageName, locations)
  321. }
  322. for (const reference of references) {
  323. const packageName = packageNameFromSpecifier(reference.name)
  324. if (packageName === undefined) continue
  325. require(packageName, reference.file)
  326. if (packageName === CHOOSER_PACKAGE) {
  327. for (const backend of CHOOSER_BACKEND_PACKAGES) require(backend, reference.file)
  328. }
  329. }
  330. return [...requiredPackages].flatMap(([packageName, locations]) => packageName in dependencies
  331. ? []
  332. : `${[...locations].join(', ')}: ${packageName} must be declared in ${manifestPath} dependencies`)
  333. }
  334. function readManifest(path: string): PackageManifest {
  335. return JSON.parse(readFileSync(resolve(root, path), 'utf8')) as PackageManifest
  336. }
  337. function localPackageDirectories(): Map<string, string> {
  338. const manifests = globSync(['packages/*/*/package.json', 'vendor/*/package.json'], { cwd: root })
  339. const packages = new Map<string, string>()
  340. for (const manifestPath of manifests) {
  341. const manifest = readManifest(manifestPath)
  342. if (manifest.name !== undefined) packages.set(manifest.name, resolve(root, dirname(manifestPath)))
  343. }
  344. return packages
  345. }
  346. function rootProjectReferences(): Set<string> {
  347. // The root solution references the host and client aggregates (the two
  348. // sides merge cordis Context under the same keys, so one program cannot see
  349. // both — but this BFS only collects reference paths, it never forms a
  350. // program). Seed the solution and follow nested aggregate references to
  351. // collect the covered leaf project set.
  352. const collected = new Set<string>()
  353. const queue = [resolve(root, 'tsconfig.json')]
  354. const seen = new Set<string>()
  355. for (let file = queue.pop(); file !== undefined; file = queue.pop()) {
  356. if (seen.has(file)) continue
  357. seen.add(file)
  358. const config = ts.readConfigFile(file, path => ts.sys.readFile(path))
  359. if (config.error !== undefined) {
  360. throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'))
  361. }
  362. const references = (config.config as { references?: Array<{ path?: unknown }> }).references ?? []
  363. for (const reference of references) {
  364. if (typeof reference.path !== 'string') continue
  365. const target = resolve(dirname(file), reference.path)
  366. if (target.endsWith('.json')) queue.push(target)
  367. else collected.add(target)
  368. }
  369. }
  370. return collected
  371. }
  372. function packageNameFromSpecifier(specifier: string): string | undefined {
  373. if (specifier.startsWith('.') || specifier.startsWith('/') || /^[a-z][a-z+.-]*:/i.test(specifier)) return undefined
  374. const segments = specifier.split('/')
  375. if (specifier.startsWith('@')) {
  376. return segments.length >= 2 ? `${segments[0]}/${segments[1]}` : undefined
  377. }
  378. return segments[0] || undefined
  379. }
  380. function validateMetadata(entry: Record<string, unknown>, file: string, path: string): void {
  381. for (const field of metadataFields) {
  382. if (!(field in entry)) continue
  383. const expressionPaths: string[] = []
  384. collectExpressionPaths(entry[field], `${path}.${field}`, expressionPaths)
  385. for (const expressionPath of expressionPaths) errors.push(`${file}${expressionPath}: !!js is not interpolated here`)
  386. }
  387. }
  388. function collectExpressionPaths(value: unknown, path: string, output: string[]): void {
  389. if (isJsExpr(value)) {
  390. output.push(path)
  391. return
  392. }
  393. if (isUnknownArray(value)) {
  394. for (let index = 0; index < value.length; index++) collectExpressionPaths(value[index], `${path}[${index}]`, output)
  395. return
  396. }
  397. if (!isRecord(value)) return
  398. for (const [key, child] of Object.entries(value)) collectExpressionPaths(child, `${path}.${key}`, output)
  399. }
  400. function isJsExpr(value: unknown): value is JsExpr {
  401. return isRecord(value) && typeof value.__jsExpr === 'string'
  402. }
  403. function isRecord(value: unknown): value is Record<string, unknown> {
  404. return value !== null && typeof value === 'object'
  405. }
  406. function isUnknownArray(value: unknown): value is unknown[] {
  407. return Array.isArray(value)
  408. }