project.spec.ts 53 KB

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