gen-persistence-catalog.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /**
  2. * Generate `docs/persistence-catalog.md` from every `SessionEventMap` merge and
  3. * the owning event-envelope types. This is the durable-record vocabulary, not
  4. * the live Cordis bus. Event declarations must be unique, explicitly typed,
  5. * documented, inheritance-free, and free of Cordis-only `@mode` tags; every
  6. * surface-union member must resolve to one. `--check` verifies the artifact.
  7. */
  8. import { globSync, readFileSync, writeFileSync } from 'node:fs'
  9. import { resolve, sep } from 'node:path'
  10. import ts from 'typescript'
  11. import { parseJsDoc, pointer, rawJsDoc, reportViolations } from './jsdoc.ts'
  12. const root = resolve(import.meta.dirname, '..')
  13. const OUT = 'docs/persistence-catalog.md'
  14. /** The fenced-block info string for generated declaration blocks (skipped by
  15. * doc-typecheck, since their imported types are not standalone-compilable). */
  16. const FENCE = 'ts persistence-catalog'
  17. /** The package whose module id plugin merges augment (`declare module '…'`). */
  18. const SESSION_MODULE = '@deepseek-ai/dsh-session'
  19. /** Event-envelope declarations rendered before the per-event vocabulary. */
  20. const EVENT_ENVELOPE_TYPE_NAMES = [
  21. 'SessionEventType',
  22. 'SurfaceEventType',
  23. 'SurfaceOp',
  24. 'SessionEvent',
  25. ] as const
  26. type EventEnvelopeTypeName = typeof EVENT_ENVELOPE_TYPE_NAMES[number]
  27. /** Primary core-data-structures page for linked payload types. */
  28. const LINK_MAP: Record<string, string> = {
  29. CallId: 'core.md',
  30. ContentBlock: 'core.md',
  31. MessageSource: 'core.md',
  32. StreamChunk: 'llm-streaming.md',
  33. TokenUsage: 'llm-streaming.md',
  34. TodoItem: 'session.md',
  35. TurnTrigger: 'session.md',
  36. TurnEndReason: 'session.md',
  37. SessionTitleEventData: 'session-title.md',
  38. SessionTitleLlmRequestEventData: 'session-title.md',
  39. SessionTitleModelProvenance: 'session-title.md',
  40. SessionTitleProviderId: 'session-title.md',
  41. SessionTitleSource: 'session-title.md',
  42. }
  43. /** One log event, extracted from a `SessionEventMap` declaration. */
  44. export interface LogEventEntry {
  45. /** Scoped name, e.g. `turn/start`. */
  46. name: string
  47. /** The scope prefix, e.g. `turn` (everything before the first `/`). */
  48. scope: string
  49. /** Payload type text (the member's type annotation, whitespace-collapsed). */
  50. payload: string
  51. /** Source member declaration and complete JSDoc, dedented from its container. */
  52. declaration: string
  53. /** Description prose (the member's JSDoc), one line per paragraph. */
  54. doc: string
  55. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  56. source: string
  57. }
  58. /** A {@link LogEventEntry} plus its surface-eligibility badge. */
  59. export interface AnnotatedLogEventEntry extends LogEventEntry {
  60. /** Whether the type is a `SurfaceEventType` member (may carry `surfaceOp`). */
  61. surface: boolean
  62. }
  63. /** One owning event-envelope declaration pasted into the generated catalog. */
  64. export interface EventEnvelopeTypeEntry {
  65. /** Exported declaration name. */
  66. name: EventEnvelopeTypeName
  67. /** Verbatim type declaration, including its complete leading JSDoc. */
  68. declaration: string
  69. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  70. source: string
  71. }
  72. const printer = ts.createPrinter({ removeComments: true })
  73. /**
  74. * Render a member type on one line through the TypeScript printer, which adds
  75. * semicolon separators. Drop its trailing semicolon before `}` to match the
  76. * repository's inline-literal style.
  77. */
  78. function payloadText(type: ts.TypeNode, sf: ts.SourceFile): string {
  79. return printer.printNode(ts.EmitHint.Unspecified, type, sf)
  80. .replace(/\s+/g, ' ')
  81. .replace(/;\s*\}/g, ' }')
  82. .trim()
  83. }
  84. /**
  85. * Copy a declaration from its leading JSDoc through its closing token while
  86. * removing only the indentation imposed by its containing interface/module.
  87. */
  88. function declarationText(text: string, sf: ts.SourceFile, node: ts.Node): string {
  89. const raw = rawJsDoc(text, node)
  90. const nodeStart = node.getStart(sf)
  91. const start = raw ? text.lastIndexOf(raw, nodeStart) : nodeStart
  92. const { line } = sf.getLineAndCharacterOfPosition(start)
  93. const lineStart = sf.getPositionOfLineAndCharacter(line, 0)
  94. const indent = text.slice(lineStart, start)
  95. return text.slice(lineStart, node.end)
  96. .split('\n')
  97. .map(lineText => lineText.startsWith(indent) ? lineText.slice(indent.length) : lineText)
  98. .join('\n')
  99. .trimEnd()
  100. }
  101. /**
  102. * Every `interface SessionEventMap` declaration in a source file: the owning
  103. * top-level declaration (in `@deepseek-ai/dsh-session`) and any declaration
  104. * merge inside a `declare module '@deepseek-ai/dsh-session'` block. Both forms
  105. * declare members of the SAME merged interface, so both are catalogued
  106. * uniformly. `topLevel` distinguishes the owning form so the caller can verify
  107. * it actually lives in the owning package — an unrelated local interface that
  108. * happens to share the name must not be catalogued as the on-disk vocabulary.
  109. */
  110. function sessionEventMapDecls(sf: ts.SourceFile): { decl: ts.InterfaceDeclaration; topLevel: boolean }[] {
  111. const decls: { decl: ts.InterfaceDeclaration; topLevel: boolean }[] = []
  112. for (const stmt of sf.statements) {
  113. if (ts.isInterfaceDeclaration(stmt) && stmt.name.text === 'SessionEventMap') decls.push({ decl: stmt, topLevel: true })
  114. if (ts.isModuleDeclaration(stmt) && ts.isStringLiteral(stmt.name) && stmt.name.text === SESSION_MODULE
  115. && stmt.body && ts.isModuleBlock(stmt.body)) {
  116. for (const inner of stmt.body.statements) {
  117. if (ts.isInterfaceDeclaration(inner) && inner.name.text === 'SessionEventMap') decls.push({ decl: inner, topLevel: false })
  118. }
  119. }
  120. }
  121. return decls
  122. }
  123. /**
  124. * The npm package name owning a `packages/<group>/<pkg>/…` source file, read
  125. * from that package's manifest — or null when the manifest is missing or
  126. * unparseable (the caller treats null as "ownership unverifiable").
  127. */
  128. function packageNameFor(rel: string, scanRoot: string): string | null {
  129. const dir = rel.split('/').slice(0, 3).join('/')
  130. try {
  131. const manifest = JSON.parse(readFileSync(resolve(scanRoot, dir, 'package.json'), 'utf8')) as { name?: string }
  132. return typeof manifest.name === 'string' ? manifest.name : null
  133. } catch {
  134. // Missing or malformed package.json — every real workspace package has one,
  135. // so this only arises in stripped-down fixture trees; either way ownership
  136. // cannot be verified and the caller reports the declaration.
  137. return null
  138. }
  139. }
  140. /**
  141. * Collect every `SessionEventMap` merge, rejecting inherited, non-literal,
  142. * untyped, undocumented, duplicate, or incorrectly owned members in one report.
  143. */
  144. export function collectLogEvents(scanRoot: string = root): LogEventEntry[] {
  145. const entries: LogEventEntry[] = []
  146. const violations: string[] = []
  147. const seen = new Map<string, string>()
  148. let owningDecl: string | null = null
  149. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  150. const abs = resolve(scanRoot, rel)
  151. const text = readFileSync(abs, 'utf8')
  152. if (!text.includes('SessionEventMap')) continue
  153. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  154. for (const { decl, topLevel } of sessionEventMapDecls(sf)) {
  155. const declSrc = pointer(rel, sf, decl)
  156. if (topLevel) {
  157. // The top-level form has one home: the single exported declaration in
  158. // the owning package. Same-named interfaces elsewhere are different
  159. // types and must not enter the on-disk catalog.
  160. const pkg = packageNameFor(rel, scanRoot)
  161. if (pkg !== SESSION_MODULE) {
  162. violations.push(`top-level interface SessionEventMap (${declSrc}) is outside ${SESSION_MODULE} (package ${pkg ?? 'unknown'}). Rename the interface, or contribute events via declare module '${SESSION_MODULE}'.`)
  163. continue
  164. }
  165. const exported = decl.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false
  166. if (!exported) {
  167. violations.push(`top-level interface SessionEventMap (${declSrc}) is not exported; the owning vocabulary is the single exported declaration — rename a local helper interface.`)
  168. continue
  169. }
  170. if (owningDecl) {
  171. violations.push(`top-level interface SessionEventMap (${declSrc}) is already declared at ${owningDecl}; the owning vocabulary has exactly one home.`)
  172. continue
  173. }
  174. owningDecl = declSrc
  175. }
  176. if (decl.heritageClauses?.length) {
  177. violations.push(`SessionEventMap declaration (${declSrc}) uses extends; inherited keys would join keyof SessionEventMap without a catalog row — declare event members directly.`)
  178. }
  179. for (const member of decl.members) {
  180. const src = pointer(rel, sf, member)
  181. if (!ts.isPropertySignature(member) || !member.type) {
  182. // A method-form or type-less member still joins `keyof SessionEventMap`,
  183. // so skipping it silently would be exactly the undocumented-event hole
  184. // this catalog exists to close.
  185. const label = (member as { name?: ts.Node }).name?.getText(sf) ?? member.getText(sf).replace(/\s+/g, ' ')
  186. violations.push(`SessionEventMap member ${label} (${src}) is not a property signature with an explicit payload type; declare every log event as 'scope/name': <payload>.`)
  187. continue
  188. }
  189. if (!ts.isStringLiteral(member.name)) {
  190. violations.push(`log event at ${src} has a non-literal name; the catalog needs string-literal event names.`)
  191. continue
  192. }
  193. const name = member.name.text
  194. const where = `log event '${name}' (${src})`
  195. const prior = seen.get(name)
  196. if (prior) {
  197. violations.push(`${where} is already declared at ${prior}; an event type has exactly one declaration.`)
  198. continue
  199. }
  200. seen.set(name, src)
  201. const payload = payloadText(member.type, sf)
  202. const { doc, hasMode } = parseJsDoc(rawJsDoc(text, member))
  203. if (hasMode) {
  204. violations.push(`${where} carries an @mode tag, but a log event has no dispatch mode (it is not a cordis bus event — it rides the 'session/event' emit). Remove the tag.`)
  205. }
  206. if (!doc) {
  207. violations.push(`${where} has no description prose. Say what the event records and what its payload means — the JSDoc becomes the catalog entry.`)
  208. }
  209. const declaration = declarationText(text, sf, member)
  210. entries.push({ name, scope: name.split('/')[0] ?? name, payload, declaration, doc, source: src })
  211. }
  212. }
  213. }
  214. reportViolations('gen-persistence-catalog', violations)
  215. return entries
  216. }
  217. /**
  218. * Collect the exported declarations that compose the persisted event envelope,
  219. * preserving their source JSDoc and declaration text.
  220. */
  221. export function collectEventEnvelopeTypes(scanRoot: string = root): EventEnvelopeTypeEntry[] {
  222. const found = new Map<EventEnvelopeTypeName, EventEnvelopeTypeEntry>()
  223. const violations: string[] = []
  224. const wanted = new Set<string>(EVENT_ENVELOPE_TYPE_NAMES)
  225. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  226. const abs = resolve(scanRoot, rel)
  227. const text = readFileSync(abs, 'utf8')
  228. if (!EVENT_ENVELOPE_TYPE_NAMES.some(name => text.includes(name))) continue
  229. if (packageNameFor(rel, scanRoot) !== SESSION_MODULE) continue
  230. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  231. for (const stmt of sf.statements) {
  232. if (!ts.isTypeAliasDeclaration(stmt) || !wanted.has(stmt.name.text)) continue
  233. const name = stmt.name.text as EventEnvelopeTypeName
  234. const src = pointer(rel, sf, stmt)
  235. const where = `event-envelope type '${name}' (${src})`
  236. const prior = found.get(name)
  237. if (prior) {
  238. violations.push(`${where} is already declared at ${prior.source}; the persisted envelope type has exactly one owner.`)
  239. continue
  240. }
  241. if (!(stmt.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)) {
  242. violations.push(`${where} is not exported.`)
  243. }
  244. const { doc, hasMode } = parseJsDoc(rawJsDoc(text, stmt))
  245. if (hasMode) violations.push(`${where} carries an @mode tag, but a persisted type has no dispatch mode.`)
  246. if (!doc) violations.push(`${where} has no description prose. The full JSDoc is part of the generated catalog.`)
  247. found.set(name, { name, declaration: declarationText(text, sf, stmt), source: src })
  248. }
  249. }
  250. const missing = EVENT_ENVELOPE_TYPE_NAMES.filter(name => !found.has(name))
  251. if (missing.length > 0) {
  252. violations.push(`missing event-envelope declaration(s): ${missing.join(', ')}.`)
  253. }
  254. reportViolations('gen-persistence-catalog', violations)
  255. return EVENT_ENVELOPE_TYPE_NAMES.map((name) => {
  256. const entry = found.get(name)
  257. if (!entry) throw new Error(`gen-persistence-catalog: missing checked event-envelope declaration '${name}'.`)
  258. return entry
  259. })
  260. }
  261. /**
  262. * Parse the `SurfaceEventType` union — the surface-eligible subset of event
  263. * types — from source. Hard-errors when the alias is missing, declared more
  264. * than once, or contains a non-string-literal member: the badge derivation
  265. * relies on the union being a closed set of literal event names.
  266. * `scanRoot` defaults to the repo root; tests pass a fixture dir.
  267. */
  268. export function collectSurfaceEventTypes(scanRoot: string = root): string[] {
  269. const found: { names: string[]; source: string }[] = []
  270. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) {
  271. const abs = resolve(scanRoot, rel)
  272. const text = readFileSync(abs, 'utf8')
  273. if (!text.includes('SurfaceEventType')) continue
  274. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  275. for (const stmt of sf.statements) {
  276. if (!ts.isTypeAliasDeclaration(stmt) || stmt.name.text !== 'SurfaceEventType') continue
  277. const src = pointer(rel, sf, stmt)
  278. const members = ts.isUnionTypeNode(stmt.type) ? [...stmt.type.types] : [stmt.type]
  279. const names: string[] = []
  280. for (const m of members) {
  281. if (ts.isLiteralTypeNode(m) && ts.isStringLiteral(m.literal)) names.push(m.literal.text)
  282. else throw new Error(`gen-persistence-catalog: SurfaceEventType (${src}) has a non-string-literal member; the badge derivation needs a closed literal union.`)
  283. }
  284. found.push({ names, source: src })
  285. }
  286. }
  287. const only = found[0]
  288. if (!only) throw new Error('gen-persistence-catalog: no SurfaceEventType union found under packages/*/*/src.')
  289. if (found.length > 1) throw new Error(`gen-persistence-catalog: SurfaceEventType is declared more than once (${found.map(f => f.source).join(', ')}); the surface subset has exactly one owner.`)
  290. return only.names
  291. }
  292. /**
  293. * Attach the surface/log-only badge to each event. Hard-errors when a
  294. * `SurfaceEventType` union member names no collected event — a stale union
  295. * member would otherwise silently badge nothing.
  296. */
  297. export function annotateSurface(events: LogEventEntry[], surfaceTypes: string[]): AnnotatedLogEventEntry[] {
  298. const names = new Set(events.map(e => e.name))
  299. const stale = surfaceTypes.filter(t => !names.has(t))
  300. if (stale.length > 0) {
  301. throw new Error(`gen-persistence-catalog: SurfaceEventType member(s) ${stale.map(t => `'${t}'`).join(', ')} name no declared log event (stale union member?).`)
  302. }
  303. const surface = new Set(surfaceTypes)
  304. return events.map(e => ({ ...e, surface: surface.has(e.name) }))
  305. }
  306. /** Render the cross-link "Types:" line for a payload, or '' if none apply. */
  307. function typeLinks(payload: string): string {
  308. const seen = new Set<string>()
  309. for (const name of Object.keys(LINK_MAP)) {
  310. if (new RegExp(`\\b${name}\\b`).test(payload)) seen.add(name)
  311. }
  312. if (seen.size === 0) return ''
  313. const links = [...seen].sort().map(n => `[${n}](core-data-structures/${LINK_MAP[n]})`)
  314. return `Types: ${links.join(' · ')}`
  315. }
  316. /** Render one log event entry. */
  317. function renderEvent(e: AnnotatedLogEventEntry): string[] {
  318. const out = [`#### \`${e.name}\` — ${e.surface ? 'surface' : 'log-only'}`, '']
  319. out.push('```' + FENCE, e.declaration, '```', '')
  320. const links = typeLinks(e.payload)
  321. if (links) out.push(links, '')
  322. out.push(`Source: [\`${e.source}\`](../${e.source.split(':')[0]})`, '')
  323. return out
  324. }
  325. /** Render the full catalog (pure, deterministic given the collected inputs). */
  326. export function render(events: AnnotatedLogEventEntry[], envelopeTypes: EventEnvelopeTypeEntry[]): string {
  327. const lines: string[] = [
  328. '<!-- Generated by scripts/gen-persistence-catalog.ts — do not edit by hand.',
  329. ' Run `pnpm run gen-persistence-catalog` to regenerate. -->',
  330. '',
  331. '# Session Persistence Event Catalog',
  332. '',
  333. 'Every event type that can appear in a session\'s durable event log: the complete persisted `SessionEvent` envelope and each member of the merge-extensible `SessionEventMap` — the owning vocabulary in `@deepseek-ai/dsh-session` plus every plugin declaration merge in this repo — with source JSDoc, full payload declaration, surface badge, and declaration site. It complements [session.md](core-data-structures/session.md) (surface ordering and the `deriveMessages()` projection), [persistence.md](core-data-structures/persistence.md) (how the log is made durable), and the [cordis events catalog](cordis-catalog/events.md) (the live bus wiring — a log event is NOT a cordis event; it reaches listeners via the single `session/event` emit).',
  334. '',
  335. 'This file is GENERATED from source (`scripts/gen-persistence-catalog.ts`) and verified fresh by `pnpm run verify-persistence-catalog` (part of `doc-sync`) — do not edit it by hand. Declaration blocks retain the source declaration and nested property JSDoc, removing only the indentation imposed by a containing interface/module, and use a `ts persistence-catalog` fence (skipped by doc-typecheck because declarations reference types from their owning modules). Type names in a payload link to the page that documents them. See [the persistence-log-catalog Agent Note](../.agents/notes/archived/process/2026-07-04-persistence-log-catalog.md).',
  336. '',
  337. 'The envelope declarations below compose each event\'s `type`, monotonic `seq`, epoch-ms `time`, `data`, and the conditional `surfaceOp`/`sourceEventSeqs` fields. **surface** marks a `SurfaceEventType` member: it produces an LLM message and declares how it joins the surface list. **log-only** marks everything else: a durable, replayable record with no derived-history contribution. Every payload is JSON-serializable (enforced at `Session.append`), and the whole format is pinned at `SESSION_FORMAT_VERSION = 0` — pre-release, no compatibility implied ([the version stance](core-data-structures/persistence.md)). Scope: the packages in this repo; a downstream plugin can merge further event types, which are outside this catalog by construction.',
  338. '',
  339. '## Event envelope',
  340. '',
  341. '```' + FENCE,
  342. envelopeTypes.map(entry => entry.declaration).join('\n\n'),
  343. '```',
  344. '',
  345. `Sources: ${envelopeTypes.map(entry => `[\`${entry.source}\`](../${entry.source.split(':')[0]})`).join(' · ')}`,
  346. '',
  347. '## Events',
  348. '',
  349. ]
  350. const scopes = [...new Set(events.map(e => e.scope))].sort()
  351. for (const scope of scopes) {
  352. lines.push(`### \`${scope}/*\``, '')
  353. for (const e of events.filter(x => x.scope === scope).sort((a, b) => a.name.localeCompare(b.name))) {
  354. lines.push(...renderEvent(e))
  355. }
  356. }
  357. return lines.join('\n')
  358. }
  359. /** CLI entry: default writes the catalog, `--check` fails if the committed copy
  360. * is stale. Guarded behind an entry-point check so importing this module for
  361. * tests neither regenerates the committed file nor calls process.exit. */
  362. function main(): void {
  363. const content = render(annotateSurface(collectLogEvents(), collectSurfaceEventTypes()), collectEventEnvelopeTypes())
  364. if (process.argv.includes('--check')) {
  365. let committed: string | null = null
  366. try {
  367. committed = readFileSync(resolve(root, OUT), 'utf8')
  368. } catch {
  369. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  370. // file is not a state this repo produces. Either way the remedy is the
  371. // same — regenerate — so treat a read failure as "stale".
  372. committed = null
  373. }
  374. if (committed === content) {
  375. console.log(`gen-persistence-catalog: ${OUT} is up to date.`)
  376. process.exit(0)
  377. }
  378. console.error(`gen-persistence-catalog: ${OUT} is stale. Run \`pnpm run gen-persistence-catalog\` and commit ${OUT}.`)
  379. process.exit(1)
  380. }
  381. writeFileSync(resolve(root, OUT), content)
  382. console.log(`gen-persistence-catalog: wrote ${OUT}.`)
  383. }
  384. // Run only when invoked as a script, not when imported by a test.
  385. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  386. main()
  387. }