project.spec.ts 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. import { chmod, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
  2. import { tmpdir } from 'node:os'
  3. import { join } from 'node:path'
  4. import { fileURLToPath } from 'node:url'
  5. import { afterEach, describe, expect, it } from 'vitest'
  6. import {
  7. FeatureOption,
  8. ExclusiveOptionFeature,
  9. MultiOptionFeature,
  10. FixedFeature,
  11. type FeatureProjectView,
  12. } from '../src/features/feature.ts'
  13. import { createBuiltinRegistry } from '../src/features/builtin/index.ts'
  14. import {
  15. npmCordisConfigEntry,
  16. cordisConfigEntry,
  17. environment as environmentResource,
  18. optionalString,
  19. ownedTextFile,
  20. requiredString,
  21. stringArray,
  22. } from '../src/features/builtin/helpers.ts'
  23. import { defineFeatures, defineFeature } from '../src/features/define-feature.ts'
  24. import { FeatureRegistry } from '../src/features/registry.ts'
  25. import { ProjectContribution } from '../src/features/resources.ts'
  26. import type { CordisConfigEntryResource, ProjectResource } from '../src/features/resources.ts'
  27. import type { CordisConfigEntry } from '../src/documents/cordis-yaml-file.ts'
  28. import { PackageJsonFile } from '../src/documents/package-json-file.ts'
  29. import { TextProjectFile } from '../src/documents/project-file.ts'
  30. import { featureId, resourceKey } from '../src/ids.ts'
  31. import { NpmPackageManager } from '../src/package-managers/package-manager.ts'
  32. import { LocalPluginBlueprint } from '../src/plugins/local-plugin-blueprint.ts'
  33. import { SdkProject } from '../src/project/sdk-project.ts'
  34. import type {
  35. FeatureSelection,
  36. ProjectCreationRequest,
  37. ProjectProfile,
  38. } from '../src/project/types.ts'
  39. const temporary: string[] = []
  40. const repoRoot = fileURLToPath(new URL('../../../../', import.meta.url))
  41. afterEach(async () => {
  42. await Promise.all(temporary.splice(0).map(path => rm(path, { recursive: true, force: true })))
  43. })
  44. function selection(id: string, options: readonly string[], secrets?: Record<string, string>): FeatureSelection {
  45. return { id: featureId(id), options, ...secrets ? { secrets } : {} }
  46. }
  47. function request(
  48. extra: readonly FeatureSelection[] = [],
  49. plugins: readonly LocalPluginBlueprint[] = [],
  50. app: 'acp' | 'embed' = 'embed',
  51. bash: 'local' | 'sandbox' = 'local',
  52. ): ProjectCreationRequest {
  53. return {
  54. name: 'test-agent',
  55. description: 'test project',
  56. runtime: { model: 'deepseek-v4-flash' },
  57. packageManager: new NpmPackageManager('10.0.0'),
  58. releaseVersion: '0.0.1',
  59. features: [
  60. selection('provider', ['deepseek-official'], { apiKey: 'test-key' }),
  61. selection('bash', [bash]),
  62. selection('app', [app]),
  63. selection('persistence', ['jsonl']),
  64. ...extra,
  65. ],
  66. localPlugins: plugins,
  67. }
  68. }
  69. async function createCommitted(
  70. extra: readonly FeatureSelection[] = [],
  71. plugins: readonly LocalPluginBlueprint[] = [],
  72. ): Promise<SdkProject> {
  73. const root = await mkdtemp(join(tmpdir(), 'dsh-project-domain-'))
  74. temporary.push(root)
  75. const creation = request(extra, plugins)
  76. const project = SdkProject.create(root, creation)
  77. const registry = createBuiltinRegistry(project.profile)
  78. const edit = project.edit(registry)
  79. for (const item of creation.features) edit.installFeature(registry.get(item.id), item)
  80. for (const plugin of plugins) edit.addPlugin(plugin)
  81. return (await edit.commit()).project
  82. }
  83. describe('SdkProject and ProjectEditSession', () => {
  84. it('derives existing-project profiles and tolerates malformed optional documents', async () => {
  85. const make = async (
  86. name: string,
  87. manifest: Record<string, unknown>,
  88. cordis: string,
  89. extras: Record<string, string> = {},
  90. ): Promise<SdkProject> => {
  91. const root = await mkdtemp(join(tmpdir(), `${name}-`))
  92. temporary.push(root)
  93. await writeFile(join(root, 'package.json'), JSON.stringify(manifest))
  94. await writeFile(join(root, 'cordis.yml'), cordis)
  95. for (const [path, text] of Object.entries(extras)) await writeFile(join(root, path), text)
  96. return SdkProject.open(root)
  97. }
  98. const acp = await make('dsh-open-acp', {
  99. name: 'acp', description: 'ACP', packageManager: 'pnpm@10.1.0',
  100. dependencies: { '@deepseek-ai/dsh-scripts': '^1.2.3' },
  101. }, `- id: acp
  102. name: '@deepseek-ai/dsh-acp'
  103. config: { model: app-model }
  104. `, { '.env': 'KEY=value\n', 'tsconfig.json': '{bad', 'pnpm-workspace.yaml': 'bad' })
  105. expect(acp.profile).toMatchObject({
  106. runInterface: 'acp', runtime: { model: 'app-model' }, releaseVersion: '1.2.3', description: 'ACP',
  107. })
  108. expect(acp.profile.packageManager.name).toBe('pnpm')
  109. expect(acp.readEnvironment('.env', 'KEY')).toBe('value')
  110. expect(() => acp.readEnvironment('.env.example', 'KEY')).not.toThrow()
  111. expect(acp.document('tsconfig.json')).toBeInstanceOf(TextProjectFile)
  112. await expect(make('dsh-open-tui', {}, `- id: provider
  113. name: '@deepseek-ai/dsh-llm-deepseek'
  114. config: { models: [provider-model] }
  115. - id: tui
  116. name: '@deepseek-ai/dsh-tui'
  117. `)).rejects.toThrow('unsupported run interface: @deepseek-ai/dsh-tui has been removed')
  118. await expect(make('dsh-open-tui-subpath', {}, `- id: tui-prompt
  119. name: '@deepseek-ai/dsh-tui/prompt'
  120. `)).rejects.toThrow('unsupported run interface: @deepseek-ai/dsh-tui has been removed')
  121. const embedded = await make('dsh-open-embed', {}, `- id: provider
  122. name: '@deepseek-ai/dsh-llm-deepseek'
  123. config: { models: [provider-model] }
  124. `, { 'yarn.lock': '' })
  125. expect(embedded.profile.runInterface).toBe('embed')
  126. expect(embedded.profile.runtime.model).toBe('provider-model')
  127. expect(embedded.profile.packageManager.name).toBe('yarn')
  128. expect(embedded.profile.name).toBe(embedded.root.split('/').at(-1))
  129. const pnpm = await make('dsh-open-pnpm', { name: 'pnpm' }, '[]\n', { 'pnpm-lock.yaml': '' })
  130. expect(pnpm.profile.packageManager.name).toBe('pnpm')
  131. const defaults = await make('dsh-open-default', { name: 'default', packageManager: 'npm@10.0.0' }, '[]\n')
  132. expect(defaults.profile).toMatchObject({
  133. runInterface: 'embed', runtime: { model: 'deepseek-v4-flash' }, releaseVersion: '0.0.1',
  134. })
  135. expect(() => SdkProject.create(defaults.root, { ...request(), features: [] })).toThrow('requires one app')
  136. await expect(make('dsh-open-invalid-manager', { name: 'bad', packageManager: 'bad' }, '[]\n'))
  137. .rejects.toThrow('invalid packageManager field')
  138. const providerFallback = await make('dsh-open-provider-fallback', { name: 'fallback' }, `- id: provider
  139. name: '@deepseek-ai/dsh-llm-deepseek'
  140. config: { models: [fallback-model] }
  141. `)
  142. expect(providerFallback.profile.runtime.model).toBe('fallback-model')
  143. const pnpmRequest = { ...request(), packageManager: new (await import('../src/package-managers/package-manager.ts')).PnpmPackageManager('10.0.0') }
  144. expect(SdkProject.create(join(defaults.root, 'pnpm'), pnpmRequest).hasDocument('pnpm-workspace.yaml')).toBe(true)
  145. })
  146. it('commits a complete blueprint and round-trips every installed feature', async () => {
  147. const project = await createCommitted([
  148. selection('hmr', ['default']),
  149. selection('fs', ['local']),
  150. selection('todo', ['default']),
  151. selection('web', ['exa'], { apiKey: 'exa-key' }),
  152. selection('subagent', ['fork']),
  153. selection('workflow', ['workerthread']),
  154. selection('hooks', ['claude', 'codex']),
  155. ], [new LocalPluginBlueprint('sample', 'plugin'), new LocalPluginBlueprint('lookup', 'tool')])
  156. const registry = createBuiltinRegistry(project.profile)
  157. const inspections = registry.inspect(project)
  158. expect(inspections.filter(item => item.state === 'enabled').map(item => item.id)).toEqual([
  159. 'provider', 'spine', 'bash', 'app', 'persistence', 'hmr', 'fs', 'todo', 'web', 'subagent', 'workflow', 'hooks',
  160. ])
  161. expect(inspections.find(item => item.id === 'subagent')?.options).toEqual(['spawn', 'fork'])
  162. expect(project.cordisConfigEntries().map(entry => entry.id)).toContain('lookup')
  163. const index = await readFile(join(project.root, 'index.ts'), 'utf8')
  164. expect(index).toContain('SdkBootContext')
  165. expect(index).toContain('agents.create')
  166. expect(index).not.toContain('boot.args.resume')
  167. expect(index).not.toContain('AgentId')
  168. expect(index).toContain('SessionId(`main-session-${randomUUID()}`)')
  169. expect(project.packageManifest().scripts).toEqual({
  170. dev: 'dsh-sdk dev index.ts',
  171. build: 'dsh-sdk build',
  172. typecheck: 'tsc -b',
  173. start: 'dsh-sdk start index.js',
  174. config: 'dsh-sdk config',
  175. })
  176. expect(await readFile(join(project.root, '.env.example'), 'utf8')).toContain('EXA_API_KEY=')
  177. expect(project.cordis.entry('agent-loop')?.config).toEqual({ agents: [] })
  178. expect(project.cordis.entry('session-invariant')?.name).toBe('@deepseek-ai/dsh-session/invariant')
  179. expect(project.cordis.entry('agent-invariant')?.name).toBe('@deepseek-ai/dsh-agent/invariant')
  180. expect(project.cordis.entry('scope-invariant')?.name).toBe('@deepseek-ai/dsh-scope/invariant')
  181. expect(project.cordis.entry('agent-loop-invariant')?.name).toBe('@deepseek-ai/dsh-agent-loop/invariant')
  182. expect(project.cordis.entry('system-prompt')?.config?.persona).toContain('{{cwd}}')
  183. expect(project.packageManifest().dependencies?.['@cordisjs/plugin-timer']).toBe('^1.1.2')
  184. expect(project.packageManifest().dependencies?.['@cordisjs/plugin-hmr']).toBe('^1.0.15')
  185. expect(project.packageManifest().dependencies?.['@deepseek-ai/dsh-scope']).toBe('^0.0.1')
  186. expect(project.packageManifest().dependencies).not.toHaveProperty('@deepseek-ai/dsh-scope/invariant')
  187. expect(project.packageManifest().dependencies).not.toHaveProperty('node-addon-require-builtin')
  188. expect(project.cordis.entry('hmr')).toMatchObject({ name: '@cordisjs/plugin-hmr' })
  189. expect(project.cordis.entry('llm-deepseek')?.config).not.toHaveProperty('baseURL')
  190. expect(project.cordis.entry('llm-deepseek')?.config).not.toHaveProperty('models')
  191. })
  192. it.each(['spawn', 'fork'] as const)('mounts Task controls for %s subagents', async (option) => {
  193. const project = await createCommitted([selection('subagent', [option])])
  194. expect(project.cordis.entry('tasks')?.name).toBe('@deepseek-ai/dsh-tasks-local')
  195. expect(project.cordis.entry('tool-tasks')?.name).toBe('@deepseek-ai/dsh-tool-tasks')
  196. expect(project.packageManifest().dependencies).toMatchObject({
  197. '@deepseek-ai/dsh-tasks-local': '^0.0.1',
  198. '@deepseek-ai/dsh-tool-tasks': '^0.0.1',
  199. })
  200. expect(project.packageManifest().dependencies).not.toHaveProperty('@deepseek-ai/dsh-tasks')
  201. })
  202. it('round-trips embed app projects without a front-door Cordis config entry', async () => {
  203. const root = await mkdtemp(join(tmpdir(), 'dsh-embed-app-'))
  204. temporary.push(root)
  205. const creation = request([], [], 'embed')
  206. const project = SdkProject.create(root, creation)
  207. const registry = createBuiltinRegistry(project.profile)
  208. const edit = project.edit(registry)
  209. for (const item of creation.features) edit.installFeature(registry.get(item.id), item)
  210. const committed = (await edit.commit()).project
  211. const app = createBuiltinRegistry(committed.profile).get(featureId('app')).inspect(committed)
  212. expect(app).toMatchObject({ state: 'enabled', options: ['embed'] })
  213. expect(app.selection).toEqual(selection('app', ['embed']))
  214. expect(committed.cordis.entry('agent-loop')?.config).toEqual({ agents: [] })
  215. expect(committed.cordis.entry('acp')).toBeUndefined()
  216. })
  217. it('emits the sandbox workspace-write example as inactive Cordis config', async () => {
  218. const root = await mkdtemp(join(tmpdir(), 'dsh-sandbox-bash-'))
  219. temporary.push(root)
  220. const creation = request([], [], 'embed', 'sandbox')
  221. const project = SdkProject.create(root, creation)
  222. const registry = createBuiltinRegistry(project.profile)
  223. const edit = project.edit(registry)
  224. for (const item of creation.features) edit.installFeature(registry.get(item.id), item)
  225. await edit.commit()
  226. const cordis = await readFile(join(root, 'cordis.yml'), 'utf8')
  227. expect(cordis).toContain(`- id: bash
  228. name: "@deepseek-ai/dsh-bash-sandbox"
  229. # Uncomment to allow writes under the project workspace.
  230. # config:
  231. # mode: workspace-write
  232. # workspaceRoot: !!js process.cwd()`)
  233. })
  234. it('round-trips the custom pi-ai provider with explicit endpoint and default model', async () => {
  235. const root = await mkdtemp(join(tmpdir(), 'dsh-custom-provider-'))
  236. temporary.push(root)
  237. const base = request()
  238. const creation: ProjectCreationRequest = {
  239. ...base,
  240. features: [
  241. {
  242. id: featureId('provider'),
  243. options: ['custom'],
  244. values: { baseURL: 'https://custom.example/v1' },
  245. secrets: { apiKey: 'custom-key' },
  246. },
  247. ...base.features.filter(item => item.id !== 'provider'),
  248. ],
  249. }
  250. const project = SdkProject.create(root, creation)
  251. const registry = createBuiltinRegistry(project.profile)
  252. const edit = project.edit(registry)
  253. for (const item of creation.features) edit.installFeature(registry.get(item.id), item)
  254. const committed = (await edit.commit()).project
  255. expect(committed.cordis.entry('llm-pi-ai')).toMatchObject({
  256. name: '@deepseek-ai/dsh-llm-pi-ai',
  257. config: { baseURL: 'https://custom.example/v1' },
  258. })
  259. expect(committed.cordis.entry('llm-pi-ai')?.config).not.toHaveProperty('models')
  260. expect(createBuiltinRegistry(committed.profile).get(featureId('provider')).inspect(committed)).toMatchObject({
  261. state: 'enabled', options: ['custom'],
  262. })
  263. })
  264. it('switches exclusive options and refuses disabling a required feature', async () => {
  265. const project = await createCommitted([selection('subagent', ['spawn']), selection('workflow', ['workerthread'])])
  266. const registry = createBuiltinRegistry(project.profile)
  267. const edit = project.edit(registry)
  268. const persistence = registry.get(featureId('persistence'))
  269. edit.configureFeature(persistence, selection('persistence', ['sqlite']))
  270. expect(() => { edit.disableFeature(registry.get(featureId('subagent'))) }).toThrow('required by workflow')
  271. expect(() => { edit.disableFeature(registry.get(featureId('app'))) }).toThrow('required feature')
  272. const committed = await edit.commit()
  273. expect(committed.project.cordis.entry('session-persistence')?.name).toContain('sqlite')
  274. expect(committed.changes.npmDependenciesChanged).toBe(true)
  275. })
  276. it('switches app-owned files and scripts while protecting user edits', async () => {
  277. const project = await createCommitted()
  278. const registry = createBuiltinRegistry(project.profile)
  279. const edit = project.edit(registry)
  280. edit.configureFeature(registry.get(featureId('app')), selection('app', ['acp']))
  281. const acp = (await edit.commit()).project
  282. expect(acp.profile.runInterface).toBe('acp')
  283. expect(acp.cordis.entry('commands')).toBeUndefined()
  284. expect(acp.cordis.entry('user-interaction')).toBeUndefined()
  285. expect(acp.packageManifest().scripts).toMatchObject({
  286. dev: 'dsh-sdk dev index.ts',
  287. start: 'dsh-sdk start index.js',
  288. })
  289. expect(await readFile(join(acp.root, 'README.md'), 'utf8')).toContain('Run as an ACP automation server')
  290. expect(await readFile(join(acp.root, 'index.ts'), 'utf8')).not.toContain('agents.create')
  291. const acpRegistry = createBuiltinRegistry(acp.profile)
  292. const embedEdit = acp.edit(acpRegistry)
  293. embedEdit.configureFeature(acpRegistry.get(featureId('app')), selection('app', ['embed']))
  294. const embed = (await embedEdit.commit()).project
  295. expect(embed.profile.runInterface).toBe('embed')
  296. expect(await readFile(join(embed.root, 'README.md'), 'utf8')).toContain('Embed the harness')
  297. const embedIndex = await readFile(join(embed.root, 'index.ts'), 'utf8')
  298. expect(embedIndex).toContain('agents.create')
  299. expect(embedIndex).toContain("import { SessionId } from '@deepseek-ai/dsh-session'")
  300. expect(embedIndex).not.toContain('AgentId')
  301. await writeFile(join(embed.root, 'README.md'), '# Custom README\n')
  302. const modified = await SdkProject.open(embed.root)
  303. const modifiedRegistry = createBuiltinRegistry(modified.profile)
  304. expect(() => { modified.edit(modifiedRegistry).configureFeature(
  305. modifiedRegistry.get(featureId('app')),
  306. selection('app', ['acp']),
  307. ) }).toThrow('feature-owned file was modified: README.md')
  308. const manifest = PackageJsonFile.parse(await readFile(join(embed.root, 'package.json'), 'utf8'))
  309. manifest.removeScript('dev')
  310. await writeFile(join(embed.root, 'package.json'), manifest.serialize())
  311. const incomplete = await SdkProject.open(embed.root)
  312. expect(createBuiltinRegistry(incomplete.profile).get(featureId('app')).inspect(incomplete).diagnostics)
  313. .toContain('missing package.json script dev')
  314. })
  315. it('supports disabled feature reconfiguration and rejects invalid state operations', async () => {
  316. const project = await createCommitted([selection('todo', ['default'])])
  317. const registry = createBuiltinRegistry(project.profile)
  318. const edit = project.edit(registry)
  319. expect(edit.inspections()).not.toHaveLength(0)
  320. const todo = registry.get(featureId('todo'))
  321. edit.configureFeature(registry.get(featureId('web')), selection('web', ['deepseek-official']))
  322. edit.disableFeature(todo)
  323. edit.configureFeature(todo, selection('todo', ['default']))
  324. edit.enableFeature(todo)
  325. expect(() => { edit.enableFeature(registry.get(featureId('workflow'))) }).toThrow('not installed')
  326. expect(() => { edit.disableFeature(registry.get(featureId('workflow'))) }).toThrow('not installed')
  327. expect(() => { edit.setCustomPluginDisabled('missing', true) }).toThrow('does not exist')
  328. const committed = await edit.commit()
  329. expect(committed.changes.enabledFeatures).toContain('todo')
  330. expect(() => { edit.enableFeature(todo) }).toThrow('already committed')
  331. })
  332. it('preserves custom entries and toggles only their Loader disabled state', async () => {
  333. const project = await createCommitted([], [new LocalPluginBlueprint('sample', 'plugin')])
  334. const registry = createBuiltinRegistry(project.profile)
  335. const edit = project.edit(registry)
  336. edit.setCustomPluginDisabled('sample', true)
  337. expect(edit.cordisConfigEntries().find(entry => entry.id === 'sample')?.disabled).toBe(true)
  338. expect(() => { edit.setCustomPluginDisabled('agent-loop', true) }).toThrow('builtin feature')
  339. const next = (await edit.commit()).project
  340. const enable = next.edit(createBuiltinRegistry(next.profile))
  341. enable.setCustomPluginDisabled('sample', false)
  342. expect((await enable.commit()).project.cordis.entry('sample')?.disabled).toBeUndefined()
  343. })
  344. it('rejects local plugin collisions and invalid optional document shapes', async () => {
  345. const project = await createCommitted([], [new LocalPluginBlueprint('sample', 'plugin')])
  346. const registry = createBuiltinRegistry(project.profile)
  347. const npmDependencyConflict = project.edit(registry)
  348. expect(() => { npmDependencyConflict.addPlugin(new LocalPluginBlueprint('sample', 'plugin')) })
  349. .toThrow('NPM dependency already exists')
  350. await writeFile(join(project.root, 'tsconfig.json'), 'not-json\n')
  351. const malformed = await SdkProject.open(project.root)
  352. expect(() => { malformed.edit(createBuiltinRegistry(malformed.profile)).addPlugin(
  353. new LocalPluginBlueprint('other', 'plugin'),
  354. ) }).toThrow('requires a valid tsconfig')
  355. const entryProject = await createCommitted()
  356. const entryEdit = entryProject.edit(createBuiltinRegistry(entryProject.profile))
  357. ;(entryEdit as unknown as { cordis(): { addEntry(entry: CordisConfigEntry): void } }).cordis()
  358. .addEntry({ id: 'sample', name: 'manual' })
  359. expect(() => { entryEdit.addPlugin(new LocalPluginBlueprint('sample', 'plugin')) }).toThrow('entry already exists')
  360. const fileEdit = entryProject.edit(createBuiltinRegistry(entryProject.profile))
  361. ;(fileEdit as unknown as { documents: Map<string, TextProjectFile> }).documents
  362. .set('plugins/other/package.json', new TextProjectFile('plugins/other/package.json', '{}'))
  363. expect(() => { fileEdit.addPlugin(new LocalPluginBlueprint('other', 'plugin')) }).toThrow('file already exists')
  364. })
  365. it('reinstalls existing/disabled features and detects requirement cycles', async () => {
  366. const project = await createCommitted([selection('todo', ['default']), selection('subagent', ['spawn'])])
  367. const registry = createBuiltinRegistry(project.profile)
  368. const edit = project.edit(registry)
  369. const todo = registry.get(featureId('todo'))
  370. edit.installFeature(todo, selection('todo', ['default']))
  371. edit.disableFeature(todo)
  372. edit.installFeature(todo, selection('todo', ['default']))
  373. const subagent = registry.get(featureId('subagent'))
  374. edit.disableFeature(subagent)
  375. edit.installFeature(registry.get(featureId('workflow')), selection('workflow', ['workerthread']))
  376. expect(edit.cordisConfigEntries().find(entry => entry.id === 'subagent-spawn')?.disabled).toBeUndefined()
  377. class Cyclic extends FixedFeature {
  378. override readonly summary = 'cyclic'
  379. override readonly options = [new (class extends FeatureOption {
  380. override readonly id = 'one'
  381. override readonly label = 'One'
  382. override contribution(): ProjectContribution { return new ProjectContribution([]) }
  383. })()]
  384. override readonly id
  385. override readonly requires
  386. constructor(id: string, required: string) {
  387. super()
  388. this.id = featureId(id)
  389. this.requires = [featureId(required)]
  390. }
  391. }
  392. const one = new Cyclic('cycle-one', 'cycle-two')
  393. const two = new Cyclic('cycle-two', 'cycle-one')
  394. const cycleRegistry = new FeatureRegistry([one, two], project.profile)
  395. expect(() => { project.edit(cycleRegistry).installFeature(one, selection('cycle-one', ['one'])) })
  396. .toThrow('cyclic feature requirement')
  397. })
  398. it('removes clean owned files and detects files disappearing before commit', async () => {
  399. const project = await createCommitted([selection('hooks', ['claude', 'codex']), selection('todo', ['default'])])
  400. const registry = createBuiltinRegistry(project.profile)
  401. const remove = project.edit(registry)
  402. remove.configureFeature(registry.get(featureId('hooks')), selection('hooks', ['codex']))
  403. const committed = await remove.commit()
  404. expect(committed.changes.changedFiles).toContain('hooks.json')
  405. const edit = committed.project.edit(createBuiltinRegistry(committed.project.profile))
  406. edit.disableFeature(createBuiltinRegistry(committed.project.profile).get(featureId('todo')))
  407. await rm(join(committed.project.root, 'cordis.yml'))
  408. await expect(edit.commit()).rejects.toThrow('cannot verify project file cordis.yml')
  409. })
  410. it('guards internal resource collisions and malformed aggregate documents', async () => {
  411. const project = await createCommitted()
  412. const registry = createBuiltinRegistry(project.profile)
  413. const edit = project.edit(registry)
  414. type Internals = {
  415. documents: Map<string, TextProjectFile>
  416. states: Map<ReturnType<typeof featureId>, unknown>
  417. applyResource(resource: ProjectResource, previous: ProjectResource | undefined): void
  418. removeResource(resource: ProjectResource): void
  419. replaceContribution(previous: ProjectContribution | undefined, next: ProjectContribution): void
  420. finalProfile(): ProjectProfile
  421. manifest(): unknown
  422. cordis(): unknown
  423. environment(path: '.env' | '.env.example'): unknown
  424. state(feature: FixedFeature): unknown
  425. }
  426. const internals = edit as unknown as Internals
  427. const collidingEntry: ProjectResource = {
  428. kind: 'cordis-config-entry', key: resourceKey('cordis-config-entry:agent-loop'),
  429. entry: { id: 'agent-loop', name: 'other-package' }, ownedConfigKeys: [],
  430. }
  431. expect(() => { internals.applyResource(collidingEntry, undefined) }).toThrow('is owned by')
  432. const existingFile: ProjectResource = {
  433. kind: 'owned-file', key: resourceKey('file:tsconfig.json'),
  434. document: new TextProjectFile('tsconfig.json', 'replacement'), removeOnlyWhenUnchanged: true,
  435. }
  436. expect(() => { internals.applyResource(existingFile, undefined) }).toThrow('already exists')
  437. internals.documents.set('owned.txt', new TextProjectFile('owned.txt', 'old'))
  438. const previousFile: ProjectResource = {
  439. ...existingFile, key: resourceKey('file:owned.txt'), document: new TextProjectFile('owned.txt', 'old'),
  440. }
  441. const nextFile: ProjectResource = {
  442. ...existingFile, key: resourceKey('file:owned.txt'), document: new TextProjectFile('owned.txt', 'replacement'),
  443. }
  444. internals.applyResource(nextFile, previousFile)
  445. expect(internals.documents.get('owned.txt')?.serialize()).toBe('replacement\n')
  446. internals.documents.set('owned.txt', new TextProjectFile('owned.txt', 'user edit'))
  447. expect(() => { internals.applyResource(nextFile, previousFile) }).toThrow('was modified')
  448. const existingScript: ProjectResource = {
  449. kind: 'package-script', key: resourceKey('package-script:build'),
  450. name: 'build', command: 'other build', removeOnlyWhenUnchanged: true,
  451. }
  452. expect(() => { internals.applyResource(existingScript, undefined) }).toThrow('script already exists')
  453. const transientScript: ProjectResource = {
  454. kind: 'package-script', key: resourceKey('package-script:transient'),
  455. name: 'transient', command: 'first', removeOnlyWhenUnchanged: true,
  456. }
  457. internals.applyResource(transientScript, undefined)
  458. const nextScript: ProjectResource = { ...transientScript, command: 'second' }
  459. internals.applyResource(nextScript, transientScript)
  460. internals.applyResource(nextScript, transientScript)
  461. ;(internals.manifest() as PackageJsonFile).setScript('transient', 'user edit')
  462. expect(() => { internals.applyResource(transientScript, nextScript) }).toThrow('script was modified')
  463. expect(() => { internals.removeResource(nextScript) }).toThrow('script was modified')
  464. ;(internals.manifest() as PackageJsonFile).setScript('transient', 'second')
  465. internals.removeResource(nextScript)
  466. expect(() => { internals.removeResource(nextScript) }).toThrow('script is missing')
  467. expect(() => { internals.removeResource({
  468. ...existingFile, key: resourceKey('file:missing.txt'), document: new TextProjectFile('missing.txt', 'missing'),
  469. }) }).toThrow('owned file is missing')
  470. expect(() => { internals.removeResource({
  471. kind: 'cordis-config-entry', key: resourceKey('cordis-config-entry:missing'),
  472. entry: { id: 'missing', name: 'missing' }, ownedConfigKeys: [],
  473. }) }).toThrow('cannot confirm old Cordis resource')
  474. const transient: ProjectResource = {
  475. kind: 'owned-file', key: resourceKey('file:transient.txt'),
  476. document: new TextProjectFile('transient.txt', 'transient'), removeOnlyWhenUnchanged: true,
  477. }
  478. internals.applyResource(transient, undefined)
  479. internals.removeResource(transient)
  480. internals.replaceContribution(
  481. new ProjectContribution([{ kind: 'npm-dependency', key: resourceKey('shared'), name: 'cordis', section: 'dependencies' }]),
  482. new ProjectContribution([{
  483. kind: 'cordis-config-entry', key: resourceKey('shared'), entry: { id: 'new', name: 'new' }, ownedConfigKeys: [],
  484. }]),
  485. )
  486. internals.replaceContribution(
  487. new ProjectContribution([{
  488. kind: 'environment', key: resourceKey('environment:SAME'), name: 'SAME', value: 'old', exampleValue: '',
  489. }]),
  490. new ProjectContribution([{
  491. kind: 'environment', key: resourceKey('environment:SAME'), name: 'SAME', value: 'new', exampleValue: '',
  492. }]),
  493. )
  494. internals.documents.set('.env', new TextProjectFile('.env', 'bad'))
  495. expect(() => edit.readEnvironment('.env', 'KEY')).toThrow('not an environment document')
  496. expect(() => { internals.environment('.env') }).toThrow('not an environment document')
  497. internals.documents.delete('package.json')
  498. expect(() => { internals.manifest() }).toThrow('package.json is missing')
  499. internals.documents.delete('cordis.yml')
  500. expect(() => { internals.cordis() }).toThrow('cordis.yml is missing')
  501. class Foreign extends FixedFeature {
  502. override readonly id = featureId('foreign')
  503. override readonly summary = 'foreign'
  504. override readonly options = []
  505. }
  506. expect(() => { internals.state(new Foreign()) }).toThrow('not applicable')
  507. internals.states.delete(featureId('app'))
  508. expect(internals.finalProfile()).toBe(project.profile)
  509. const sourceDocuments = (project as unknown as { documents: Map<string, TextProjectFile> }).documents
  510. sourceDocuments.set('.env', new TextProjectFile('.env', 'bad'))
  511. expect(() => project.readEnvironment('.env', 'KEY')).toThrow('not an environment document')
  512. sourceDocuments.delete('package.json')
  513. expect(() => project.packageJson).toThrow('package.json is missing or invalid')
  514. sourceDocuments.delete('cordis.yml')
  515. expect(() => project.cordis).toThrow('cordis.yml is missing or invalid')
  516. })
  517. it('rejects external edits before writing any affected file', async () => {
  518. const project = await createCommitted([selection('todo', ['default'])])
  519. const registry = createBuiltinRegistry(project.profile)
  520. const edit = project.edit(registry)
  521. edit.disableFeature(registry.get(featureId('todo')))
  522. const manifestBefore = await readFile(join(project.root, 'package.json'), 'utf8')
  523. await writeFile(join(project.root, 'cordis.yml'), '# external\n[]\n')
  524. await expect(edit.commit()).rejects.toThrow('changed outside this edit session')
  525. expect(await readFile(join(project.root, 'package.json'), 'utf8')).toBe(manifestBefore)
  526. })
  527. it('rejects a create target file that appeared after the edit session opened', async () => {
  528. const root = await mkdtemp(join(tmpdir(), 'dsh-create-conflict-'))
  529. temporary.push(root)
  530. const creation = request()
  531. const project = SdkProject.create(root, creation)
  532. const registry = createBuiltinRegistry(project.profile)
  533. const edit = project.edit(registry)
  534. for (const item of creation.features) edit.installFeature(registry.get(item.id), item)
  535. await writeFile(join(root, 'README.md'), 'external\n')
  536. await expect(edit.commit()).rejects.toThrow('changed outside this edit session: README.md')
  537. })
  538. it('uses Cordis config entries as the installation anchor and rejects partial resources', async () => {
  539. const root = await mkdtemp(join(tmpdir(), 'dsh-inconsistent-'))
  540. temporary.push(root)
  541. await writeFile(join(root, 'package.json'), JSON.stringify({
  542. name: 'partial', dependencies: { '@deepseek-ai/dsh-llm-deepseek': '^0.0.1' },
  543. }))
  544. await writeFile(join(root, 'cordis.yml'), '[]\n')
  545. const project = await SdkProject.open(root)
  546. const registry = createBuiltinRegistry(project.profile)
  547. expect(registry.get(featureId('provider')).inspect(project)).toMatchObject({
  548. state: 'absent', diagnostics: [],
  549. })
  550. const partialRoot = await mkdtemp(join(tmpdir(), 'dsh-entry-partial-'))
  551. temporary.push(partialRoot)
  552. await writeFile(join(partialRoot, 'package.json'), JSON.stringify({ name: 'partial-entry' }))
  553. await writeFile(join(partialRoot, 'cordis.yml'), `- id: llm-deepseek
  554. name: '@deepseek-ai/dsh-llm-deepseek'
  555. config:
  556. apiKey: test
  557. `)
  558. const partial = await SdkProject.open(partialRoot)
  559. const installation = createBuiltinRegistry(partial.profile)
  560. .get(featureId('provider')).inspect(partial)
  561. expect(installation.state).toBe('inconsistent')
  562. expect(installation.diagnostics).toContain('missing package.json dependencies entry @deepseek-ai/dsh-llm-deepseek')
  563. const partialEdit = partial.edit(createBuiltinRegistry(partial.profile))
  564. const provider = createBuiltinRegistry(partial.profile).get(featureId('provider'))
  565. expect(() => { partialEdit.configureFeature(provider, selection('provider', ['deepseek-official'])) }).toThrow('inconsistent')
  566. expect(() => { partialEdit.enableFeature(provider) }).toThrow('inconsistent')
  567. expect(() => { partialEdit.disableFeature(provider) }).toThrow('required feature')
  568. })
  569. it('rejects inconsistent optional features and incompatible requirement options', async () => {
  570. const root = await mkdtemp(join(tmpdir(), 'dsh-optional-inconsistent-'))
  571. temporary.push(root)
  572. await writeFile(join(root, 'package.json'), '{"name":"partial"}')
  573. await writeFile(join(root, 'cordis.yml'), `- id: web-search-exa
  574. name: '@deepseek-ai/dsh-web-search-exa'
  575. `)
  576. const project = await SdkProject.open(root)
  577. const builtin = createBuiltinRegistry(project.profile)
  578. const edit = project.edit(builtin)
  579. const web = builtin.get(featureId('web'))
  580. expect(() => { edit.disableFeature(web) }).toThrow('inconsistent')
  581. expect(() => { edit.installFeature(web, selection('web', ['deepseek-official'])) }).toThrow('inconsistent')
  582. class RequiresWeb extends FixedFeature {
  583. override readonly id = featureId('requires-web')
  584. override readonly summary = 'requires web'
  585. override readonly requires = [featureId('web')]
  586. override readonly options = [new (class extends FeatureOption {
  587. override readonly id = 'one'
  588. override readonly label = 'One'
  589. override contribution(): ProjectContribution { return new ProjectContribution([]) }
  590. })()]
  591. }
  592. const requiresWeb = new RequiresWeb()
  593. const webRegistry = new FeatureRegistry([web, requiresWeb], project.profile)
  594. expect(() => { project.edit(webRegistry).installFeature(requiresWeb, selection('requires-web', ['one'])) })
  595. .toThrow('required feature web is inconsistent')
  596. class RequiresAcp extends FixedFeature {
  597. override readonly id = featureId('requires-acp')
  598. override readonly summary = 'requires acp'
  599. override readonly options = [new (class extends FeatureOption {
  600. override readonly id = 'one'
  601. override readonly label = 'One'
  602. override contribution(): ProjectContribution { return new ProjectContribution([]) }
  603. })()]
  604. override requirements(): readonly [{ id: ReturnType<typeof featureId>; options: readonly string[] }] {
  605. return [{ id: featureId('app'), options: ['acp'] }]
  606. }
  607. }
  608. const requiring = new RequiresAcp()
  609. const complete = await createCommitted()
  610. const app = createBuiltinRegistry(complete.profile).get(featureId('app'))
  611. const registry = new FeatureRegistry([app, requiring], complete.profile)
  612. expect(() => { complete.edit(registry).installFeature(requiring, selection('requires-acp', ['one'])) })
  613. .toThrow('does not satisfy the option requirement')
  614. })
  615. it('removes obsolete environment resources when switching options', async () => {
  616. const project = await createCommitted([selection('web', ['exa'], { apiKey: 'exa' })])
  617. const registry = createBuiltinRegistry(project.profile)
  618. const edit = project.edit(registry)
  619. edit.configureFeature(registry.get(featureId('web')), selection('web', ['deepseek-official']))
  620. expect(edit.readEnvironment('.env.example', 'EXA_API_KEY')).toBeUndefined()
  621. })
  622. it('preserves duplicate and existing .env values while appending differently named secrets', async () => {
  623. const project = await createCommitted()
  624. if (process.platform !== 'win32') {
  625. expect((await stat(join(project.root, '.env'))).mode & 0o777).toBe(0o600)
  626. }
  627. const original = '# keep\nDEEPSEEK_API_KEY=first\nDEEPSEEK_API_KEY=second\n'
  628. await writeFile(join(project.root, '.env'), original)
  629. if (process.platform !== 'win32') await chmod(join(project.root, '.env'), 0o640)
  630. const reopened = await SdkProject.open(project.root)
  631. const registry = createBuiltinRegistry(reopened.profile)
  632. expect(registry.get(featureId('provider')).inspect(reopened)).toMatchObject({
  633. state: 'enabled', selection: { secrets: { apiKey: 'second' } },
  634. })
  635. const edit = reopened.edit(registry)
  636. edit.configureFeature(
  637. registry.get(featureId('provider')),
  638. selection('provider', ['deepseek-official'], { apiKey: 'replacement' }),
  639. )
  640. edit.installFeature(registry.get(featureId('web')), selection('web', ['exa'], { apiKey: 'exa-key' }))
  641. const withExa = (await edit.commit()).project
  642. expect(await readFile(join(withExa.root, '.env'), 'utf8')).toBe(`${original}EXA_API_KEY=exa-key\n`)
  643. if (process.platform !== 'win32') {
  644. expect((await stat(join(withExa.root, '.env'))).mode & 0o777).toBe(0o640)
  645. }
  646. const nextRegistry = createBuiltinRegistry(withExa.profile)
  647. const remove = withExa.edit(nextRegistry)
  648. remove.configureFeature(nextRegistry.get(featureId('web')), selection('web', ['deepseek-official']))
  649. await remove.commit()
  650. expect(await readFile(join(withExa.root, '.env'), 'utf8')).toBe(`${original}EXA_API_KEY=exa-key\n`)
  651. })
  652. it('refuses to remove a feature-owned file after user edits', async () => {
  653. const project = await createCommitted([selection('hooks', ['claude', 'codex'])])
  654. await writeFile(join(project.root, 'hooks.json'), '{"hooks":{}}\n')
  655. const reopened = await SdkProject.open(project.root)
  656. const registry = createBuiltinRegistry(reopened.profile)
  657. const edit = reopened.edit(registry)
  658. expect(() => { edit.configureFeature(
  659. registry.get(featureId('hooks')),
  660. selection('hooks', ['codex']),
  661. ) }).toThrow('owned file was modified: hooks.json')
  662. })
  663. it('does not mistake a linked NPM dependency closure for an installed feature', async () => {
  664. const root = await mkdtemp(join(tmpdir(), 'dsh-link-closure-inspection-'))
  665. temporary.push(root)
  666. const base = request([selection('hooks', ['claude'])])
  667. const creation: ProjectCreationRequest = { ...base, linkWorkspaceRoot: repoRoot }
  668. const project = SdkProject.create(root, creation)
  669. const registry = createBuiltinRegistry(project.profile)
  670. const edit = project.edit(registry)
  671. for (const item of creation.features) edit.installFeature(registry.get(item.id), item)
  672. const committed = (await edit.commit()).project
  673. expect(committed.packageManifest().dependencies?.['@deepseek-ai/dsh-subagent']).toMatch(/^file:/)
  674. expect(createBuiltinRegistry(committed.profile).get(featureId('subagent')).inspect(committed).state).toBe('absent')
  675. })
  676. it('mounts an external plugin dependency and rejects missing deps or duplicate entries', async () => {
  677. const root = await mkdtemp(join(tmpdir(), 'dsh-external-plugin-'))
  678. temporary.push(root)
  679. const creation = request()
  680. const project = SdkProject.create(root, creation)
  681. const registry = createBuiltinRegistry(project.profile)
  682. const edit = project.edit(registry)
  683. for (const item of creation.features) edit.installFeature(registry.get(item.id), item)
  684. await edit.commit()
  685. const manifestPath = join(root, 'package.json')
  686. const manifest = JSON.parse(await readFile(manifestPath, 'utf8')) as { dependencies?: Record<string, string> }
  687. manifest.dependencies = { ...manifest.dependencies, 'ext-plugin': 'github:o/r#sha' }
  688. await writeFile(manifestPath, JSON.stringify(manifest, null, 2))
  689. const reopened = await SdkProject.open(root)
  690. const edit2 = reopened.edit(createBuiltinRegistry(reopened.profile))
  691. edit2.addExternalPlugin('ext-plugin', 'ext-plugin')
  692. expect(() => { edit2.addExternalPlugin('ext-plugin', 'ext-plugin') }).toThrow('already exists')
  693. expect(() => { edit2.addExternalPlugin('missing', 'not-a-dep') }).toThrow('not installed')
  694. const commit = await edit2.commit()
  695. expect(commit.project.cordis.entry('ext-plugin')?.name).toBe('ext-plugin')
  696. })
  697. })
  698. describe('extension points', () => {
  699. const profile: ProjectProfile = {
  700. name: 'test', description: 'test', runtime: { model: 'm' }, runInterface: 'embed',
  701. packageManager: new NpmPackageManager('10.0.0'), releaseVersion: '0.0.1',
  702. }
  703. it('rejects cross-feature resource ownership conflicts at registry construction', () => {
  704. class TestOption extends FeatureOption {
  705. override readonly id = 'default'
  706. override readonly label = 'Default'
  707. override contribution(): ProjectContribution {
  708. return new ProjectContribution([{
  709. kind: 'npm-dependency', key: resourceKey('npm-dependency:shared'), name: 'shared', section: 'dependencies',
  710. }])
  711. }
  712. }
  713. class TestFeature extends FixedFeature {
  714. override readonly id
  715. override readonly summary = 'test'
  716. override readonly options = [new TestOption()]
  717. constructor(id: string) {
  718. super()
  719. this.id = featureId(id)
  720. }
  721. }
  722. expect(() => new FeatureRegistry([
  723. new TestFeature('one'), new TestFeature('two'),
  724. ], profile)).toThrow('declared by both one and two')
  725. expect(new TestFeature('one').defaultOptions()).toEqual(['default'])
  726. expect(() => new FeatureRegistry([
  727. new TestFeature('one'), new TestFeature('one'),
  728. ], profile)).toThrow('duplicate feature id')
  729. })
  730. it('validates selection modes and declarative feature definitions', () => {
  731. const option = { id: 'one', label: 'One', default: true, resources: [] } as const
  732. expect(() => defineFeature({ id: 'bad-single', summary: 'bad', mode: 'single', options: [] }))
  733. .toThrow('requires one default option')
  734. expect(() => defineFeature({
  735. id: 'bad-exclusive', summary: 'bad', mode: 'exclusive', options: [{ ...option, default: false }],
  736. })).toThrow('exactly one default option')
  737. expect(() => defineFeature({
  738. id: 'bad-multiple', summary: 'bad', mode: 'multiple', options: [{ ...option, default: false }],
  739. })).toThrow('at least one default option')
  740. const exclusive = defineFeature({
  741. id: 'defined', summary: 'Defined', mode: 'exclusive', supportedInterfaces: ['embed'],
  742. requires: [{ id: 'base' }], suggests: ['suggested'],
  743. baseResources: [{ kind: 'npm-dependency', name: 'base', section: 'devDependencies' }],
  744. options: [
  745. {
  746. id: 'one', label: 'One', default: true,
  747. requires: [{ id: 'option', options: ['required'] }],
  748. secrets: [{ id: 'token', environment: 'TOKEN', message: 'Token', required: true }],
  749. resources: [
  750. {
  751. kind: 'npm-cordis-config-entry', id: 'one', package: 'one-package',
  752. config: { nested: { value: 1 }, list: ['x'], nullable: null },
  753. },
  754. { kind: 'owned-file', path: 'one.txt', text: 'one', removeOnlyWhenUnchanged: false },
  755. ],
  756. },
  757. {
  758. id: 'two', label: 'Two', resources: [
  759. { kind: 'file-cordis-config-entry', id: 'two', path: './two.ts' },
  760. ],
  761. },
  762. ],
  763. })
  764. expect(exclusive.defaultOptions(profile)).toEqual(['one'])
  765. expect(exclusive.isApplicable(profile)).toBe(true)
  766. expect(exclusive.isApplicable({ ...profile, runInterface: 'acp' })).toBe(false)
  767. expect(exclusive.requirements(selection('defined', ['one']))).toEqual([
  768. { id: 'base' }, { id: 'option', options: ['required'] },
  769. ])
  770. const contribution = exclusive.contribution({
  771. id: featureId('defined'), options: ['one'], secrets: { token: 'secret' },
  772. }, profile)
  773. expect(contribution.resources.map(resource => resource.kind)).toEqual([
  774. 'npm-dependency', 'npm-dependency', 'cordis-config-entry', 'owned-file', 'environment',
  775. ])
  776. const entry = contribution.resources.find(resource => resource.kind === 'cordis-config-entry')
  777. expect(entry?.validateConfig?.({ nested: { value: 2 }, list: ['a', 'b'], nullable: null })).toEqual([])
  778. expect(entry?.validateConfig?.({ nested: [], list: 'bad' })).toHaveLength(3)
  779. expect(() => exclusive.normalizeSelection(selection('other', ['one']), profile)).toThrow('does not belong')
  780. expect(() => exclusive.normalizeSelection(selection('defined', ['one']), { ...profile, runInterface: 'acp' }))
  781. .toThrow('not available')
  782. expect(() => exclusive.normalizeSelection(selection('defined', ['missing']), profile)).toThrow('unknown')
  783. expect(() => exclusive.normalizeSelection(selection('defined', ['one', 'two']), profile)).toThrow('exactly one')
  784. expect(defineFeatures([exclusive, {
  785. id: 'fixed', summary: 'Fixed', mode: 'single', options: [option],
  786. }])).toHaveLength(2)
  787. expect(() => new FeatureRegistry([], profile).get(featureId('missing'))).toThrow('unknown feature')
  788. expect(new FeatureRegistry([exclusive], profile).ownerOfPackage('one-package', { ...profile, runInterface: 'acp' }))
  789. .toBeUndefined()
  790. class Unsupported extends FixedFeature {
  791. override readonly id = featureId('unsupported')
  792. override readonly summary = 'unsupported'
  793. override readonly options = [new (class extends FeatureOption {
  794. override readonly id = 'one'
  795. override readonly label = 'One'
  796. override contribution(): ProjectContribution { return new ProjectContribution([]) }
  797. })()]
  798. override readonly supportedInterfaces = []
  799. }
  800. expect(() => new FeatureRegistry([new Unsupported()], profile)).toThrow('supports no run interface')
  801. })
  802. it('covers feature base classes and resource conflict checks', () => {
  803. class EmptySimple extends FixedFeature {
  804. override readonly id = featureId('empty')
  805. override readonly summary = 'empty'
  806. override readonly options = []
  807. }
  808. expect(() => new EmptySimple().defaultOptions()).toThrow('has no option')
  809. class BadSimple extends FixedFeature {
  810. override readonly id = featureId('bad-simple')
  811. override readonly summary = 'bad'
  812. override readonly options = [new (class extends FeatureOption {
  813. override readonly id = 'one'
  814. override readonly label = 'One'
  815. override contribution(): ProjectContribution { return new ProjectContribution([]) }
  816. })(), new (class extends FeatureOption {
  817. override readonly id = 'two'
  818. override readonly label = 'Two'
  819. override contribution(): ProjectContribution { return new ProjectContribution([]) }
  820. })()]
  821. }
  822. expect(() => new BadSimple().normalizeSelection(selection('bad-simple', ['one']), profile)).toThrow('one fixed option')
  823. class EmptyMulti extends MultiOptionFeature {
  824. override readonly id = featureId('multi')
  825. override readonly summary = 'multi'
  826. override readonly options = []
  827. override defaultOptions(): readonly string[] { return [] }
  828. }
  829. expect(() => new EmptyMulti().normalizeSelection(selection('multi', []), profile)).toThrow('at least one')
  830. class EmptyExclusive extends ExclusiveOptionFeature {
  831. override readonly id = featureId('exclusive')
  832. override readonly summary = 'exclusive'
  833. override readonly options = []
  834. override defaultOptions(): readonly string[] { return [] }
  835. }
  836. expect(() => new EmptyExclusive().normalizeSelection(selection('exclusive', []), profile)).toThrow('exactly one')
  837. const resource = {
  838. kind: 'npm-dependency' as const, key: resourceKey('same'), name: 'one', section: 'dependencies' as const,
  839. }
  840. expect(() => new ProjectContribution([resource, resource])).toThrow('duplicate contribution')
  841. expect(() => ProjectContribution.merge(
  842. new ProjectContribution([resource]),
  843. new ProjectContribution([{ ...resource, name: 'two' }]),
  844. )).toThrow('conflicting definitions')
  845. expect(ProjectContribution.merge(new ProjectContribution([resource]), new ProjectContribution([resource])).byKey().size)
  846. .toBe(1)
  847. expect(ownedTextFile('owner', 'file.txt', 'text').document).toBeInstanceOf(TextProjectFile)
  848. expect(optionalString({ value: 1 }, 'value')).toHaveLength(1)
  849. expect(optionalString({}, 'value')).toEqual([])
  850. expect(requiredString({ value: 'x' }, 'value')).toEqual([])
  851. expect(stringArray({ value: ['a'] }, 'value')).toEqual([])
  852. expect(stringArray({ value: [1] }, 'value')).toHaveLength(1)
  853. expect(cordisConfigEntry('owner', { id: 'entry', name: 'pkg' }).ownedConfigKeys).toEqual([])
  854. expect(npmCordisConfigEntry('owner', { id: 'entry', name: 'pkg' })[1].ownedConfigKeys).toEqual([])
  855. expect(npmCordisConfigEntry('owner', { id: 'entry', name: '@scope/pkg/subpath' })[0].name).toBe('@scope/pkg')
  856. expect(npmCordisConfigEntry('owner', { id: 'entry', name: 'pkg/subpath' })[0].name).toBe('pkg')
  857. for (const invalid of ['', '@scope', '@scope/']) {
  858. expect(() => npmCordisConfigEntry('owner', { id: 'entry', name: invalid })).toThrow('invalid bare package specifier')
  859. }
  860. expect(environmentResource('owner', 'EMPTY', undefined)).not.toHaveProperty('value')
  861. const builtins = createBuiltinRegistry(profile)
  862. expect(builtins.get(featureId('app')).defaultOptions(profile)).toEqual(['embed'])
  863. expect(builtins.get(featureId('hmr')).defaultOptions(profile)).toEqual(['default'])
  864. const app = builtins.get(featureId('app'))
  865. const acpEntry = builtins.get(featureId('app')).contribution(selection('app', ['acp']), profile).resources
  866. .find((resource): resource is CordisConfigEntryResource =>
  867. resource.kind === 'cordis-config-entry' && resource.entry.id === 'acp')
  868. expect(acpEntry?.entry.id).toBe('acp')
  869. expect(acpEntry?.validateConfig?.({ model: '' })).toHaveLength(1)
  870. const embedOption = app.options.find(option => option.id === 'embed')
  871. expect(embedOption?.markerConfigEntries(profile)).toEqual([])
  872. expect(embedOption?.contribution(profile, {}).resources.map(resource => resource.kind)).toEqual([
  873. 'owned-file', 'owned-file', 'package-script', 'package-script',
  874. ])
  875. expect(embedOption?.matchesConfigEntries([
  876. { id: 'agent-loop', name: '@deepseek-ai/dsh-agent-loop' },
  877. { id: 'acp', name: '@deepseek-ai/dsh-acp' },
  878. ], profile)).toBe(false)
  879. const spineAgentLoop = builtins.get(featureId('spine')).contribution(selection('spine', ['default']), profile).resources
  880. .find((resource): resource is CordisConfigEntryResource =>
  881. resource.kind === 'cordis-config-entry' && resource.entry.id === 'agent-loop')
  882. expect(spineAgentLoop?.validateConfig?.({ agents: 'main' })).toEqual(['agents must be an array'])
  883. expect(spineAgentLoop?.validateConfig?.({ agents: ['main'] })).toEqual(['agents must be empty'])
  884. expect(spineAgentLoop?.validateConfig?.({ agents: [] })).toEqual([])
  885. expect(builtins.get(featureId('provider')).defaultOptions(profile)).toEqual(['deepseek-official'])
  886. expect(() => builtins.get(featureId('provider')).contribution({
  887. id: featureId('provider'), options: ['custom'], values: { baseURL: 1 },
  888. }, profile)).toThrow('baseURL must be a string')
  889. const alternateModel = builtins.get(featureId('provider')).contribution({
  890. id: featureId('provider'), options: ['deepseek-official'],
  891. }, { ...profile, runtime: { model: 'other' } }).resources
  892. .find(resource => resource.kind === 'cordis-config-entry')
  893. expect(alternateModel?.entry.config?.models).toEqual(['other'])
  894. class RequiringSimple extends BadSimple {
  895. override readonly requires = [featureId('npm-dependency')]
  896. }
  897. expect(new RequiringSimple().requirements(selection('bad-simple', ['one']))).toEqual([{ id: 'npm-dependency' }])
  898. expect(builtins.get(featureId('bash')).defaultOptions(profile)).toEqual(['local'])
  899. })
  900. it('reports every inconsistent feature resource shape', () => {
  901. const feature = defineFeature({
  902. id: 'inspectable', summary: 'Inspectable', mode: 'single',
  903. baseResources: [{ kind: 'file-cordis-config-entry', id: 'base', path: 'pkg' }],
  904. options: [{
  905. id: 'one', label: 'One', default: true,
  906. secrets: [{ id: 'token', environment: 'TOKEN', message: 'Token', required: true }],
  907. resources: [
  908. { kind: 'file-cordis-config-entry', id: 'one', path: 'pkg', config: { value: 'x' } },
  909. { kind: 'npm-dependency', name: 'dep' },
  910. { kind: 'owned-file', path: 'owned.txt', text: 'owned' },
  911. ],
  912. }],
  913. })
  914. const view = (entries: readonly CordisConfigEntry[]): FeatureProjectView => ({
  915. profile,
  916. cordisConfigEntries: () => entries,
  917. packageManifest: () => ({}),
  918. hasDocument: () => false,
  919. readEnvironment: (path) => {
  920. if (path === '.env.example') throw new Error('bad env')
  921. return 'secret'
  922. },
  923. })
  924. expect(feature.inspect(view([])).state).toBe('absent')
  925. const inconsistent = feature.inspect(view([
  926. { id: 'one', name: 'pkg', config: { value: 1 } },
  927. { id: 'extra', name: 'pkg', disabled: true },
  928. ]))
  929. expect(inconsistent.state).toBe('inconsistent')
  930. expect(inconsistent.diagnostics.join('\n')).toContain('missing Cordis config entry base')
  931. expect(inconsistent.diagnostics.join('\n')).toContain('unexpected owned Cordis config entry extra')
  932. expect(inconsistent.diagnostics.join('\n')).toContain('missing package.json dependencies entry dep')
  933. expect(inconsistent.diagnostics.join('\n')).toContain('missing owned file owned.txt')
  934. expect(inconsistent.diagnostics.join('\n')).toContain('bad env')
  935. expect(inconsistent.diagnostics.join('\n')).toContain('mixed enabled states')
  936. expect(feature.inspect(view([{ id: 'unknown', name: 'pkg' }])).state).toBe('inconsistent')
  937. const ambiguous = defineFeature({
  938. id: 'ambiguous', summary: 'Ambiguous', mode: 'exclusive',
  939. options: [
  940. { id: 'one', label: 'One', default: true, resources: [], markers: [{ id: 'one', name: 'pkg' }] },
  941. { id: 'two', label: 'Two', resources: [], markers: [{ id: 'two', name: 'pkg' }] },
  942. ],
  943. })
  944. expect(ambiguous.inspect(view([{ id: 'one', name: 'pkg' }, { id: 'two', name: 'pkg' }])).state)
  945. .toBe('inconsistent')
  946. const noValidator = defineFeature({
  947. id: 'no-validator', summary: 'No validator', mode: 'single',
  948. options: [{
  949. id: 'one', label: 'One', default: true,
  950. resources: [{ kind: 'file-cordis-config-entry', id: 'plain', path: 'plain-package' }],
  951. }],
  952. })
  953. expect(noValidator.inspect(view([{ id: 'plain', name: 'plain-package' }])).state).toBe('enabled')
  954. const app = createBuiltinRegistry(profile).get(featureId('app'))
  955. expect(app.inspect(view([{ id: 'acp', name: '@deepseek-ai/dsh-acp' }])).state)
  956. .toBe('inconsistent')
  957. })
  958. })