gen-persistence-catalog.ts 21 KB

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