1
0

persistence-changes.spec.ts 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  1. /** Current-tree persistence history rejects uncovered and incorrectly acknowledged type changes. */
  2. import { spawnSync } from 'node:child_process'
  3. import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'
  4. import { tmpdir } from 'node:os'
  5. import { join, resolve } from 'node:path'
  6. import { afterEach, describe, expect, it } from 'vitest'
  7. import { canonicalizeSchema, schemaDigest } from './persistence-schema-model.ts'
  8. import type { PersistenceRoot, PersistenceSchemaInventory, SchemaNode, SchemaProperty } from './persistence-schema-model.ts'
  9. import { extractPersistenceSchema } from './persistence-schema.ts'
  10. import { persistenceCatalogArtifacts } from './gen-persistence-catalog.ts'
  11. import {
  12. classifyPersistenceChange,
  13. loadPersistenceHistory,
  14. parsePersistenceSnapshot,
  15. runPersistenceChanges as executePersistenceChanges,
  16. validatePersistenceHistory,
  17. verifyPersistenceChanges,
  18. } from './persistence-changes.ts'
  19. import type { PersistenceChangeRecord, PersistenceHistoryEntry } from './persistence-changes.ts'
  20. function runPersistenceChanges(
  21. args: readonly string[], root: string, extract: (root: string) => PersistenceSchemaInventory,
  22. ): string {
  23. return executePersistenceChanges(args, root, extract, (_root, current) => [{
  24. path: 'docs/persistence-schema.json', content: JSON.stringify(current, null, 2) + '\n',
  25. }])
  26. }
  27. function jsonResult(source: string): { ok: boolean; files: readonly string[] } {
  28. return JSON.parse(source) as { ok: boolean; files: readonly string[] }
  29. }
  30. const AUTHORED_PROSE = {
  31. en: { summary: 'Adds optional metadata.', compatibility: 'Readers may omit the metadata.', verification: 'The focused tests passed.' },
  32. zh: { summary: '添加可选元数据。', compatibility: '读取方可省略元数据。', verification: '定向测试通过。' },
  33. }
  34. function proseFile(root: string): string {
  35. const path = join(root, 'prose.json')
  36. writeFileSync(path, JSON.stringify(AUTHORED_PROSE))
  37. return path
  38. }
  39. const roots: string[] = []
  40. afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }) })
  41. function fixture(): string {
  42. const root = mkdtempSync(join(tmpdir(), 'dsh-persistence-changes-'))
  43. roots.push(root)
  44. mkdirSync(join(root, 'docs/persistence-changes'), { recursive: true })
  45. return root
  46. }
  47. type Shape = 'string' | 'number' | 'boolean' | { readonly [property: string]: Shape }
  48. function typeRoot(key: string, shape: Shape, version = 3): PersistenceRoot {
  49. const nodes: SchemaNode[] = []
  50. function add(shape: Shape): number {
  51. const index = nodes.length
  52. nodes.push({ kind: 'primitive', type: 'never' })
  53. nodes[index] = typeof shape === 'string' ? { kind: 'primitive', type: shape } : {
  54. kind: 'object', indices: [], properties: Object.entries(shape).map(([name, child]) => ({
  55. name: name.replace(/\?$/u, ''), optional: name.endsWith('?'), type: add(child),
  56. })),
  57. }
  58. return index
  59. }
  60. if (key === 'SessionHeader') {
  61. const index = add(shape)
  62. const node = nodes[index]!
  63. if (node.kind !== 'object') throw new Error('header fixture requires an object')
  64. nodes[index] = { ...node, properties: [...node.properties, { name: 'version', optional: false, type: nodes.length }] }
  65. nodes.push({ kind: 'literal', value: version })
  66. } else if (key.startsWith('event:')) {
  67. add({ data: shape, type: 'string' })
  68. const node = nodes[0]!
  69. if (node.kind !== 'object') throw new Error('event fixture requires an object')
  70. const type = node.properties.find(item => item.name === 'type')!.type
  71. nodes[type] = { kind: 'literal', value: key.slice(6) }
  72. } else add(shape)
  73. const schema = canonicalizeSchema(nodes, 0)
  74. return { key, kind: ['SessionHeader', 'JsonlHeaderLine'].includes(key) ? 'header' : key === 'SessionEventEnvelope' ? 'envelope' : 'event',
  75. ...(key.startsWith('event:') ? { event: key.slice(6), surface: false } : {}), schema, digest: schemaDigest(schema) }
  76. }
  77. function inventory(eventShape: Shape = { value: 'string' }, version = 3): PersistenceSchemaInventory {
  78. return { formatVersion: 1, types: [], roots: [typeRoot('SessionHeader', { id: 'string' }, version), typeRoot('SessionEventEnvelope', { type: 'string' }), typeRoot('event:example/value', eventShape), typeRoot('JsonlHeaderLine', { version: 'number' })] }
  79. }
  80. function entry(
  81. id: string, schema: PersistenceSchemaInventory, previous: string | null,
  82. baseline = false, decision: 'same-version' | 'version-bump' = 'same-version',
  83. ): PersistenceHistoryEntry {
  84. return {
  85. record: { schemaVersion: 1, id, baseline, changes: schema.roots.map(root => ({
  86. root: root.key, previous, after: root.digest, decision,
  87. })) },
  88. snapshot: schema,
  89. }
  90. }
  91. const BASE_ID = '2026-09-11-baseline'
  92. const NEXT_ID = '2026-09-11-change'
  93. function onlyEvent(schema: PersistenceSchemaInventory): PersistenceSchemaInventory {
  94. return { ...schema, roots: schema.roots.filter(root => root.kind === 'event') }
  95. }
  96. function finishDocuments(root: string, id: string): void {
  97. for (const suffix of ['.md', '.zh.md']) {
  98. const path = join(root, 'docs/persistence-changes', id + suffix)
  99. writeFileSync(path, readFileSync(path, 'utf8').replaceAll('TODO: explain this change.', 'Optional payload metadata preserves the recorded value.')
  100. .replaceAll('TODO: record validation evidence.', 'The focused persistence-history tests passed.'))
  101. }
  102. }
  103. function commitCurrent(root: string, schema: PersistenceSchemaInventory): void {
  104. writeFileSync(join(root, 'docs/persistence-schema.json'), JSON.stringify(schema, null, 2) + '\n')
  105. }
  106. function baseline(root: string, schema = inventory()): void {
  107. runPersistenceChanges(['--baseline', BASE_ID], root, () => schema)
  108. finishDocuments(root, BASE_ID)
  109. commitCurrent(root, schema)
  110. }
  111. function unionBody(arms: readonly (readonly SchemaProperty[])[]): PersistenceRoot {
  112. const nodes: SchemaNode[] = [
  113. { kind: 'object', indices: [], properties: [{ name: 'data', type: 1, optional: false }] },
  114. { kind: 'union', types: arms.map((_, index) => 5 + index) },
  115. { kind: 'primitive', type: 'string' },
  116. { kind: 'primitive', type: 'number' },
  117. { kind: 'primitive', type: 'boolean' },
  118. ...arms.map(properties => ({ kind: 'object' as const, indices: [], properties })),
  119. ]
  120. const schema = canonicalizeSchema(nodes, 0)
  121. return { ...typeRoot('event:example/value', {}), schema, digest: schemaDigest(schema) }
  122. }
  123. describe('persistence change classification', () => {
  124. it('treats a new optional payload subtree as one additive change even with required descendants', () => {
  125. const before = typeRoot('event:example/value', { value: 'string' })
  126. const after = typeRoot('event:example/value', { value: 'string', 'details?': { name: 'string', count: 'number' } })
  127. expect(classifyPersistenceChange(before, after)).toEqual([{ path: 'event:example/value.data.details', kind: 'optional-property-added', description: 'optional property added', requiresVersionBump: false }])
  128. })
  129. it('permits required-to-optional payload properties while rejecting opposite changes, type changes, and removals', () => {
  130. const required = typeRoot('event:example/value', { value: 'string' })
  131. const optional = typeRoot('event:example/value', { 'value?': 'string' })
  132. expect(classifyPersistenceChange(required, optional).every(change => !change.requiresVersionBump)).toBe(true)
  133. for (const after of [required, typeRoot('event:example/value', { 'value?': 'number' }), typeRoot('event:example/value', {})]) {
  134. expect(classifyPersistenceChange(optional, after).some(change => change.requiresVersionBump)).toBe(true)
  135. }
  136. })
  137. it('pairs multiple discriminated union arms when a shared payload gains an optional property', () => {
  138. function unionRoot(optional: boolean): PersistenceRoot {
  139. const nodes: SchemaNode[] = [
  140. { kind: 'object', indices: [], properties: [{ name: 'data', type: 1, optional: false }] },
  141. { kind: 'union', types: [2, 3] },
  142. { kind: 'object', indices: [], properties: [{ name: 'kind', type: 4, optional: false }, { name: 'payload', type: 6, optional: false }] },
  143. { kind: 'object', indices: [], properties: [{ name: 'kind', type: 5, optional: false }, { name: 'payload', type: 6, optional: false }] },
  144. { kind: 'literal', value: 'left' }, { kind: 'literal', value: 'right' },
  145. { kind: 'object', indices: [], properties: [{ name: 'value', type: 7, optional: false }, ...(optional ? [{ name: 'label', type: 7, optional: true }] : [])] },
  146. { kind: 'primitive', type: 'string' },
  147. ]
  148. const schema = canonicalizeSchema(nodes, 0)
  149. return { ...typeRoot('event:example/value', {}), schema, digest: schemaDigest(schema) }
  150. }
  151. const differences = classifyPersistenceChange(unionRoot(false), unionRoot(true))
  152. expect(differences.length).toBeGreaterThan(0)
  153. expect(differences.every(change => !change.requiresVersionBump)).toBe(true)
  154. })
  155. it('allows optional additions across undiscriminated union arms', () => {
  156. const first = [{ name: 'a', type: 2, optional: false }]
  157. const second = [{ name: 'b', type: 3, optional: false }]
  158. const extra = { name: 'x', type: 4, optional: true }
  159. const differences = classifyPersistenceChange(unionBody([first, second]), unionBody([[...first, extra], [...second, extra]]))
  160. expect(differences).toEqual([expect.objectContaining({ path: 'event:example/value.data.x', requiresVersionBump: false })])
  161. })
  162. it('allows required-to-optional fields across undiscriminated union arms', () => {
  163. const before = unionBody([[{ name: 'a', type: 2, optional: false }], [{ name: 'b', type: 3, optional: false }]])
  164. const after = unionBody([[{ name: 'a', type: 2, optional: true }], [{ name: 'b', type: 3, optional: true }]])
  165. const differences = classifyPersistenceChange(before, after)
  166. expect(differences.map(change => change.path).sort()).toEqual(['event:example/value.data.a', 'event:example/value.data.b'])
  167. expect(differences.every(change => change.kind === 'property-made-optional' && !change.requiresVersionBump)).toBe(true)
  168. })
  169. it('finds a complete matching when one union arm has multiple additive successors', () => {
  170. const required = [{ name: 'a', type: 2, optional: false }]
  171. const optional = [{ name: 'a', type: 2, optional: true }]
  172. const flexible = [{ name: '0', type: 4, optional: true }, ...optional]
  173. const constrained = [...required, { name: 'z', type: 4, optional: true }]
  174. const before = unionBody([required, optional])
  175. for (const after of [unionBody([flexible, constrained]), unionBody([constrained, flexible])]) {
  176. const differences = classifyPersistenceChange(before, after)
  177. expect(differences.length).toBeGreaterThan(0)
  178. expect(differences.every(change => !change.requiresVersionBump)).toBe(true)
  179. }
  180. const noCompleteMatching = unionBody([flexible, [{ name: 'different', type: 4, optional: true }]])
  181. expect(classifyPersistenceChange(before, noCompleteMatching).some(change => change.requiresVersionBump)).toBe(true)
  182. })
  183. it('keeps union cardinality, property removal, new required fields, and value types strict', () => {
  184. const first = [{ name: 'a', type: 2, optional: false }]
  185. const second = [{ name: 'b', type: 3, optional: false }]
  186. const third = [{ name: 'c', type: 4, optional: false }]
  187. const before = unionBody([first, second])
  188. const variants = [
  189. unionBody([first, second, third]),
  190. unionBody([first]),
  191. unionBody([first, third]),
  192. unionBody([[...first, { name: 'x', type: 4, optional: false }], [...second, { name: 'x', type: 4, optional: true }]]),
  193. unionBody([[{ name: 'a', type: 3, optional: true }], [{ name: 'b', type: 3, optional: true }]]),
  194. ]
  195. for (const after of variants) expect(classifyPersistenceChange(before, after).some(change => change.requiresVersionBump)).toBe(true)
  196. })
  197. it('checks all recursive union arms without retaining provisional successes between candidates', () => {
  198. const next = { name: 'next', type: 1, optional: true }
  199. const first = [{ name: 'a', type: 2, optional: false }, next]
  200. const second = [{ name: 'b', type: 3, optional: false }, next]
  201. const extra = { name: 'x', type: 4, optional: true }
  202. const before = unionBody([first, second])
  203. const additive = unionBody([[...first, extra], [...second, extra]])
  204. expect(classifyPersistenceChange(before, additive).every(change => !change.requiresVersionBump)).toBe(true)
  205. const invalid = unionBody([[...first, extra], [{ name: 'b', type: 2, optional: false }, next, extra]])
  206. expect(classifyPersistenceChange(before, invalid).some(change => change.requiresVersionBump)).toBe(true)
  207. expect(classifyPersistenceChange(invalid, before).some(change => change.requiresVersionBump)).toBe(true)
  208. })
  209. it('preserves body scope through arrays and tuples and rejects a simultaneous value-type change', () => {
  210. function wrapped(optional: boolean, primitive: 'string' | 'number' = 'string'): PersistenceRoot {
  211. const nodes: SchemaNode[] = [
  212. { kind: 'object', indices: [], properties: [{ name: 'data', type: 1, optional: false }] },
  213. { kind: 'tuple', elements: [{ type: 2, optional: false, rest: false }] },
  214. { kind: 'array', element: 3 },
  215. { kind: 'object', indices: [], properties: [{ name: 'value', type: 4, optional }] },
  216. { kind: 'primitive', type: primitive },
  217. ]
  218. const schema = canonicalizeSchema(nodes, 0)
  219. return { ...typeRoot('event:example/value', {}), schema, digest: schemaDigest(schema) }
  220. }
  221. expect(classifyPersistenceChange(wrapped(false), wrapped(true)).every(change => !change.requiresVersionBump)).toBe(true)
  222. expect(classifyPersistenceChange(wrapped(false), wrapped(true, 'number')).some(change => change.requiresVersionBump)).toBe(true)
  223. })
  224. it('keeps optional header/envelope properties and surface event additions strict', () => {
  225. for (const key of ['SessionHeader', 'JsonlHeaderLine', 'SessionEventEnvelope']) {
  226. expect(classifyPersistenceChange(typeRoot(key, {}), typeRoot(key, { 'metadata?': 'string' }))[0]?.requiresVersionBump).toBe(true)
  227. }
  228. const added = typeRoot('event:example/added', { value: 'string' })
  229. expect(classifyPersistenceChange(null, added)[0]?.requiresVersionBump).toBe(false)
  230. expect(classifyPersistenceChange(null, { ...added, surface: true })[0]?.requiresVersionBump).toBe(true)
  231. expect(classifyPersistenceChange(added, null)[0]?.requiresVersionBump).toBe(true)
  232. })
  233. })
  234. describe('persistence history verification', () => {
  235. it('accepts a baseline and a successive optional addition without comparing the historical schema to current', () => {
  236. const before = inventory()
  237. const after = inventory({ value: 'string', 'label?': 'string' })
  238. const history = validatePersistenceHistory([entry(BASE_ID, before, null, true), entry(NEXT_ID, onlyEvent(after), BASE_ID)])
  239. expect(history.tips.get('event:example/value')?.root?.digest).toBe(after.roots[2]?.digest)
  240. expect(history.tips.get('SessionHeader')?.id).toBe(BASE_ID)
  241. })
  242. it('rejects missing predecessors, forks, cycles, duplicates, and missing baseline', () => {
  243. const base = entry(BASE_ID, inventory(), null, true)
  244. const next = entry(NEXT_ID, onlyEvent(inventory({ value: 'string', 'label?': 'string' })), BASE_ID)
  245. expect(() => validatePersistenceHistory([next])).toThrow('exactly one baseline')
  246. expect(() => validatePersistenceHistory([base, entry(NEXT_ID, next.snapshot, '2026-09-11-missing')])).toThrow('missing predecessor')
  247. expect(() => validatePersistenceHistory([base, next, entry('2026-09-11-fork', next.snapshot, BASE_ID)])).toThrow('forked')
  248. expect(() => validatePersistenceHistory([base, base])).toThrow('exactly one baseline')
  249. const cycle = entry('2026-09-11-cycle', { ...next.snapshot, roots: [typeRoot('event:cycle/event', {})] }, '2026-09-11-cycle')
  250. expect(() => validatePersistenceHistory([base, cycle])).toThrow('cycle')
  251. })
  252. it('binds breaking decisions to the same record header version transition', () => {
  253. const base = entry(BASE_ID, inventory(), null, true)
  254. const breaking = inventory({ value: 'number' }, 4)
  255. expect(() => validatePersistenceHistory([base, entry(NEXT_ID, onlyEvent(breaking), BASE_ID)])).toThrow('requires a format version bump')
  256. expect(() => validatePersistenceHistory([base, entry(NEXT_ID, onlyEvent(breaking), BASE_ID, false, 'version-bump')])).toThrow("this record's own")
  257. const touched = { ...breaking, roots: breaking.roots.filter(root => root.key === 'SessionHeader' || root.kind === 'event') }
  258. expect(validatePersistenceHistory([base, entry(NEXT_ID, touched, BASE_ID, false, 'version-bump')]).tips.get('SessionHeader')?.id).toBe(NEXT_ID)
  259. const later = entry('2026-09-11-later', onlyEvent(inventory({ value: 'boolean' }, 4)), NEXT_ID, false, 'version-bump')
  260. expect(() => validatePersistenceHistory([base, entry(NEXT_ID, touched, BASE_ID, false, 'version-bump'), later])).toThrow("this record's own")
  261. })
  262. it('retains deletion tombstones and requires re-added roots to continue them', () => {
  263. const base = entry(BASE_ID, inventory(), null, true)
  264. const after = inventory({}, 4)
  265. const header = after.roots[0]!
  266. const record: PersistenceChangeRecord = { schemaVersion: 1, id: NEXT_ID, baseline: false, changes: [
  267. { root: 'SessionHeader', previous: BASE_ID, after: header.digest, decision: 'version-bump' },
  268. { root: 'event:example/value', previous: BASE_ID, after: null, decision: 'version-bump' },
  269. ] }
  270. const deletion = { record, snapshot: { ...after, roots: [header] } }
  271. expect(validatePersistenceHistory([base, deletion]).tips.get('event:example/value')?.root).toBeNull()
  272. const restored = entry('2026-09-11-restore', onlyEvent(inventory()), NEXT_ID)
  273. expect(validatePersistenceHistory([base, deletion, restored]).tips.get('event:example/value')?.id).toBe(restored.record.id)
  274. expect(() => validatePersistenceHistory([base, deletion, entry('2026-09-11-restore', restored.snapshot, null)])).toThrow('forked')
  275. })
  276. it('rejects malformed references, unknown schema variants, digest tampering, and extra snapshot roots', () => {
  277. const schema = inventory()
  278. const malformed = structuredClone(schema) as unknown as { roots: Array<{ schema: { nodes: unknown[] }; digest: string }> }
  279. malformed.roots[0]!.schema.nodes = [{ kind: 'array', element: 99 }]
  280. expect(() => parsePersistenceSnapshot(malformed)).toThrow('unknown schema node')
  281. malformed.roots[0]!.schema.nodes = [{ kind: 'future' }]
  282. expect(() => parsePersistenceSnapshot(malformed)).toThrow('unknown schema node kind')
  283. const tampered = structuredClone(schema)
  284. Object.assign(tampered.roots[0]!, { digest: '0'.repeat(64) })
  285. expect(() => parsePersistenceSnapshot(tampered)).toThrow('digest mismatch')
  286. expect(() => parsePersistenceSnapshot({ ...schema, formatVersion: 2 })).toThrow('normalization version')
  287. const next = entry(NEXT_ID, onlyEvent(inventory({ value: 'string', 'label?': 'string' })), BASE_ID)
  288. expect(() => validatePersistenceHistory([entry(BASE_ID, schema, null, true), { ...next, snapshot: inventory() }])).toThrow('snapshot roots')
  289. })
  290. })
  291. describe('persistence changes current-tree commands', () => {
  292. it('requires completed record prose, rejects stale generated output, and reports unacknowledged paths', () => {
  293. const root = fixture()
  294. const before = inventory()
  295. runPersistenceChanges(['--baseline', BASE_ID], root, () => before)
  296. expect(() => loadPersistenceHistory(root)).toThrow('complete compatibility')
  297. finishDocuments(root, BASE_ID)
  298. rmSync(join(root, 'docs/persistence-schema.json'))
  299. expect(() => verifyPersistenceChanges(root, before)).toThrow('is missing')
  300. commitCurrent(root, before)
  301. const after = inventory({ value: 'string', 'label?': 'string' })
  302. expect(() => verifyPersistenceChanges(root, after)).toThrow('is stale')
  303. commitCurrent(root, after)
  304. expect(() => verifyPersistenceChanges(root, after)).toThrow('event:example/value.data.label: optional property added (same-version allowed)')
  305. runPersistenceChanges(['--record', NEXT_ID, '--decision', 'same-version'], root, () => after)
  306. finishDocuments(root, NEXT_ID)
  307. expect(runPersistenceChanges([], root, () => after)).toContain('4 roots match 2 history records')
  308. expect(() => runPersistenceChanges(['--baseline', '2026-09-11-reset'], root, () => after)).toThrow('cannot reset history')
  309. expect(() => runPersistenceChanges(['--record', '2026-09-11-empty', '--decision', 'same-version'], root, () => after)).toThrow('no persistence type changes')
  310. })
  311. it('rejects changed bilingual machine declarations and unreferenced snapshots', () => {
  312. const root = fixture()
  313. baseline(root)
  314. const chinese = join(root, 'docs/persistence-changes', `${BASE_ID}.zh.md`)
  315. const original = readFileSync(chinese, 'utf8')
  316. writeFileSync(chinese, original.replace('baseline: true', 'baseline: false'))
  317. expect(() => loadPersistenceHistory(root)).toThrow('bilingual machine records differ')
  318. writeFileSync(chinese, original)
  319. writeFileSync(join(root, 'docs/persistence-changes/2026-09-11-orphan.schema.json'), '{}\n')
  320. expect(() => loadPersistenceHistory(root)).toThrow('unreferenced')
  321. })
  322. it.each([
  323. ['optional field', inventory({ value: 'string', 'label?': 'string' })],
  324. ['required-to-optional field', inventory({ 'value?': 'string' })],
  325. ['ordinary event addition', { ...inventory(), roots: [...inventory().roots, typeRoot('event:example/added', { count: 'number' })] }],
  326. ] as const)('infers same-version for %s', (_name, after) => {
  327. const root = fixture()
  328. baseline(root)
  329. runPersistenceChanges(['--record', NEXT_ID, '--prose', proseFile(root)], root, () => after)
  330. const changes = loadPersistenceHistory(root).entries.find(entry => entry.record.id === NEXT_ID)?.record.changes
  331. expect(changes?.length).toBeGreaterThan(0)
  332. expect(changes?.every(change => change.decision === 'same-version')).toBe(true)
  333. verifyPersistenceChanges(root, after)
  334. })
  335. it('infers a version bump when the source includes its own increasing header version', () => {
  336. const root = fixture()
  337. baseline(root)
  338. const after = inventory({ value: 'number' }, 4)
  339. runPersistenceChanges(['--record', NEXT_ID, '--prose', proseFile(root)], root, () => after)
  340. const changes = loadPersistenceHistory(root).entries.find(entry => entry.record.id === NEXT_ID)?.record.changes
  341. expect(changes?.map(change => change.root).sort()).toEqual(['SessionHeader', 'event:example/value'])
  342. expect(changes?.every(change => change.decision === 'version-bump')).toBe(true)
  343. verifyPersistenceChanges(root, after)
  344. })
  345. it('rejects inferred bumps without a header transition and explicit incorrect assertions before writing', () => {
  346. const root = fixture()
  347. baseline(root)
  348. const prose = proseFile(root)
  349. const directory = join(root, 'docs/persistence-changes')
  350. const files = readdirSync(directory).sort()
  351. const inventoryPath = join(root, 'docs/persistence-schema.json')
  352. const before = readFileSync(inventoryPath, 'utf8')
  353. for (const [args, code] of [
  354. [[], 'version-transition-required'],
  355. [['--decision', 'same-version'], 'version-bump-required'],
  356. ] as const) {
  357. const result = jsonResult(runPersistenceChanges(['--record', NEXT_ID, '--prose', prose, '--json', ...args], root,
  358. () => inventory({ value: 'number' })))
  359. expect(result).toMatchObject({ ok: false, code, files: [], changes: [expect.objectContaining({ requiresVersionBump: true })] })
  360. expect(readFileSync(inventoryPath, 'utf8')).toBe(before)
  361. expect(readdirSync(directory).sort()).toEqual(files)
  362. }
  363. })
  364. it('authors a complete pair from explicit prose and reports source changes even when generated artifacts are stale', () => {
  365. const root = fixture()
  366. baseline(root)
  367. const after = inventory({ value: 'string', 'label?': 'string' })
  368. const pending = jsonResult(runPersistenceChanges(['--check', '--json'], root, () => after))
  369. expect(pending).toMatchObject({ ok: false, operation: 'check', code: 'stale-artifacts',
  370. roots: [{ root: 'event:example/value', kind: 'event', before: inventory().roots[2]?.digest, after: after.roots[2]?.digest }], changes: [
  371. { root: 'event:example/value', path: 'event:example/value.data.label', kind: 'optional-property-added', requiresVersionBump: false },
  372. ] })
  373. const written = jsonResult(runPersistenceChanges(['--record', NEXT_ID, '--decision', 'same-version', '--prose', proseFile(root), '--json'], root, () => after))
  374. expect(written).toMatchObject({ ok: true, operation: 'record', recordId: NEXT_ID })
  375. expect(written.files).toEqual([
  376. 'docs/persistence-schema.json', `docs/persistence-changes/${NEXT_ID}.md`, `docs/persistence-changes/${NEXT_ID}.zh.md`,
  377. `docs/persistence-changes/${NEXT_ID}.i18n.yaml`, `docs/persistence-changes/${NEXT_ID}.schema.json`,
  378. ])
  379. expect(written).toMatchObject({ roots: [{ root: 'event:example/value', kind: 'event',
  380. before: inventory().roots[2]?.digest, after: after.roots[2]?.digest }] })
  381. expect(readFileSync(join(root, `docs/persistence-changes/${NEXT_ID}.md`), 'utf8')).toContain(AUTHORED_PROSE.en.compatibility)
  382. expect(jsonResult(runPersistenceChanges(['--check', '--json'], root, () => after)).ok).toBe(true)
  383. })
  384. it('refreshes only a terminal acknowledgement while preserving its authored prose and predecessor', () => {
  385. const root = fixture()
  386. baseline(root)
  387. const after = inventory({ value: 'string', 'label?': 'string' })
  388. const prose = proseFile(root)
  389. runPersistenceChanges(['--record', NEXT_ID, '--decision', 'same-version', '--prose', prose], root, () => after)
  390. const path = join(root, `docs/persistence-changes/${NEXT_ID}.md`)
  391. const beforeText = readFileSync(path, 'utf8')
  392. const refreshed = inventory({ value: 'string', 'label?': 'string', 'extra?': 'number' })
  393. runPersistenceChanges(['--update', NEXT_ID], root, () => refreshed)
  394. const stripRecord = (value: string): string => value.replace(/```yaml persistence-change[\s\S]*?```/u, '')
  395. expect(stripRecord(readFileSync(path, 'utf8'))).toBe(stripRecord(beforeText))
  396. expect(loadPersistenceHistory(root).tips.get('event:example/value')?.id).toBe(NEXT_ID)
  397. expect(loadPersistenceHistory(root).entries.find(entry => entry.record.id === NEXT_ID)?.record.changes[0]?.previous).toBe(BASE_ID)
  398. expect(jsonResult(runPersistenceChanges(['--check', '--json'], root, () => refreshed)).ok).toBe(true)
  399. const final = inventory({ value: 'string', 'label?': 'string', 'extra?': 'number', 'last?': 'boolean' })
  400. runPersistenceChanges(['--record', '2026-09-11-successor', '--decision', 'same-version', '--prose', prose], root, () => final)
  401. expect(() => runPersistenceChanges(['--update', NEXT_ID, '--decision', 'same-version'], root, () => final)).toThrow('with successors')
  402. expect(() => runPersistenceChanges(['--update', BASE_ID, '--decision', 'same-version'], root, () => final)).toThrow('cannot update the persistence baseline')
  403. })
  404. it('completes a scaffold through update and rejects invalid prose or decisions before changing files', () => {
  405. const root = fixture()
  406. baseline(root)
  407. const after = inventory({ value: 'string', 'label?': 'string' })
  408. runPersistenceChanges(['--record', NEXT_ID, '--decision', 'same-version'], root, () => after)
  409. const prose = proseFile(root)
  410. runPersistenceChanges(['--update', NEXT_ID, '--decision', 'same-version', '--prose', prose], root, () => after)
  411. expect(runPersistenceChanges(['--check'], root, () => after)).toContain('roots match')
  412. expect(readFileSync(join(root, `docs/persistence-changes/${NEXT_ID}.md`), 'utf8')).not.toContain('TODO:')
  413. const pairedPaths = ['.md', '.zh.md', '.i18n.yaml'].map(suffix => join(root, `docs/persistence-changes/${NEXT_ID}${suffix}`))
  414. const completed = pairedPaths.map(path => readFileSync(path, 'utf8'))
  415. runPersistenceChanges(['--update', NEXT_ID, '--decision', 'same-version', '--prose', prose], root, () => after)
  416. expect(pairedPaths.map(path => readFileSync(path, 'utf8'))).toEqual(completed)
  417. const path = join(root, `docs/persistence-changes/${NEXT_ID}.md`)
  418. const before = readFileSync(path, 'utf8')
  419. const invalid = inventory({ value: 'number' })
  420. const result = jsonResult(runPersistenceChanges(['--update', NEXT_ID, '--decision', 'same-version', '--json'], root, () => invalid))
  421. expect(result).toMatchObject({ ok: false, code: 'version-bump-required', changes: [expect.objectContaining({ kind: 'type-changed', requiresVersionBump: true })] })
  422. expect(readFileSync(path, 'utf8')).toBe(before)
  423. for (const value of [
  424. { ...AUTHORED_PROSE, extra: 'unsupported' },
  425. { ...AUTHORED_PROSE, en: { ...AUTHORED_PROSE.en, compatibility: ' ' } },
  426. { ...AUTHORED_PROSE, zh: { ...AUTHORED_PROSE.zh, verification: 'TODO: record validation evidence.' } },
  427. { ...AUTHORED_PROSE, zh: { ...AUTHORED_PROSE.zh, verification: '```text\nUnpaired code.\n```' } },
  428. ]) {
  429. writeFileSync(prose, JSON.stringify(value))
  430. expect(() => runPersistenceChanges(['--update', NEXT_ID, '--decision', 'same-version', '--prose', prose], root, () => after)).toThrow()
  431. expect(readFileSync(path, 'utf8')).toBe(before)
  432. }
  433. })
  434. it('executes the real CLI against a source-only temporary checkout without Git history', () => {
  435. const root = fixture()
  436. const physical = join(root, 'packages/session/session-persistence-jsonl/src')
  437. mkdirSync(physical, { recursive: true })
  438. writeFileSync(join(physical, 'format.ts'), "interface HeaderLine { type: 'session'; version: number; id: string; delegationDepth: number }; export {}\n")
  439. const session = join(root, 'packages/core/session/src')
  440. mkdirSync(session, { recursive: true })
  441. writeFileSync(join(session, '../package.json'), JSON.stringify({ name: '@deepseek-ai/dsh-session' }))
  442. writeFileSync(join(root, 'tsconfig.host.json'), JSON.stringify({ compilerOptions: {
  443. target: 'ESNext', module: 'ESNext', moduleResolution: 'Bundler', types: [], skipLibCheck: true,
  444. paths: { '@deepseek-ai/dsh-session/types': ['./packages/core/session/src/types.ts'] },
  445. } }))
  446. const source = [
  447. '/** Stored header. */', 'export interface SessionHeader { version: 3; id: string }',
  448. '/** Stored event payloads. */', 'export interface SessionEventMap {', '/** Saved value. */',
  449. "'example/value': { value: string }", '}', '/** Surface event names. */', "export type SurfaceEventType = 'example/value'",
  450. '/** Persisted event names. */', 'export type SessionEventType = keyof SessionEventMap',
  451. '/** Surface placement. */', "export type SurfaceOp = 'append'", '/** Persisted event. */',
  452. 'export type SessionEvent<K extends keyof SessionEventMap = keyof SessionEventMap> =',
  453. ' { [P in K]: { type: P; seq: number; data: SessionEventMap[P]; surfaceOp: SurfaceOp } }[K]', '',
  454. ].join('\n')
  455. writeFileSync(join(session, 'types.ts'), source)
  456. const script = resolve(import.meta.dirname, 'persistence-changes.ts')
  457. const cli = (...args: string[]): ReturnType<typeof spawnSync> => spawnSync(process.execPath, ['--import', import.meta.resolve('tsx/esm'), script, '--root', root, ...args], {
  458. cwd: root, encoding: 'utf8', timeout: 120_000,
  459. })
  460. const prose = proseFile(root)
  461. const initialized = cli('--baseline', BASE_ID, '--prose', prose)
  462. expect(initialized.error).toBeUndefined()
  463. expect(initialized.signal).toBeNull()
  464. expect(initialized.status, String(initialized.stderr)).toBe(0)
  465. const accepted = cli('--check')
  466. expect(accepted.error).toBeUndefined()
  467. expect(accepted.signal).toBeNull()
  468. expect(accepted.status, String(accepted.stderr)).toBe(0)
  469. const optional = source.replace('value: string', 'value: string; label?: string')
  470. writeFileSync(join(session, 'types.ts'), optional)
  471. const authored = cli('--record', NEXT_ID, '--prose', prose, '--json')
  472. expect(authored.error).toBeUndefined()
  473. expect(authored.signal).toBeNull()
  474. expect(authored.status, String(authored.stderr)).toBe(0)
  475. expect(JSON.parse(String(authored.stdout)) as unknown).toMatchObject({ ok: true, operation: 'record' })
  476. const beforeUpdate = readFileSync(join(root, `docs/persistence-changes/${NEXT_ID}.md`), 'utf8')
  477. writeFileSync(join(session, 'types.ts'), optional.replace('label?: string', 'label?: string; extra?: number'))
  478. const updated = cli('--update', NEXT_ID, '--json')
  479. expect(updated.error).toBeUndefined()
  480. expect(updated.signal).toBeNull()
  481. expect(updated.status, String(updated.stderr)).toBe(0)
  482. expect(JSON.parse(String(updated.stdout)) as unknown).toMatchObject({ ok: true, operation: 'update' })
  483. expect(readFileSync(join(root, `docs/persistence-changes/${NEXT_ID}.md`), 'utf8').replace(/```yaml persistence-change[\s\S]*?```/u, ''))
  484. .toBe(beforeUpdate.replace(/```yaml persistence-change[\s\S]*?```/u, ''))
  485. const generated = extractPersistenceSchema(root)
  486. for (const file of persistenceCatalogArtifacts(root, generated)) expect(readFileSync(join(root, file.path), 'utf8')).toBe(file.content)
  487. verifyPersistenceChanges(root, generated)
  488. writeFileSync(join(session, 'types.ts'), optional.replace('label?: string', 'label?: string; extra?: number').replace('value: string', 'value: number'))
  489. commitCurrent(root, extractPersistenceSchema(root))
  490. const rejected = cli('--check')
  491. expect(rejected.error).toBeUndefined()
  492. expect(rejected.signal).toBeNull()
  493. expect(rejected.status).toBe(1)
  494. expect(String(rejected.stderr)).toContain('version-bump required')
  495. const structured = cli('--check', '--json')
  496. expect(structured.error).toBeUndefined()
  497. expect(structured.signal).toBeNull()
  498. expect(structured.status).toBe(1)
  499. expect(JSON.parse(String(structured.stdout)) as unknown).toMatchObject({
  500. ok: false, code: 'unacknowledged-changes', changes: [expect.objectContaining({ kind: 'type-changed', requiresVersionBump: true })],
  501. })
  502. })
  503. })