gen-persistence-catalog.ts 20 KB

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