verify-cordis-config.ts 18 KB

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