gen-persistence-catalog.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. /**
  2. * Generate (and verify) the persistence log event catalog in
  3. * docs/persistence-catalog.md.
  4. *
  5. * The catalog is the ON-DISK-vocabulary reference: every event type that can
  6. * appear in a session's durable event log — every member of the
  7. * merge-extensible `SessionEventMap`, across the owning declaration in
  8. * `@deepseek-ai/dsh-session` and every plugin declaration merge. It complements
  9. * the cordis events/services catalog (the live bus wiring — a log event is NOT
  10. * a cordis event; it reaches listeners via the single `session/event` emit) and
  11. * the core-data-structures session page (the `SessionEvent` envelope and
  12. * derivation semantics): this page is the RECORDS a persisted log can contain.
  13. *
  14. * `tsx scripts/gen-persistence-catalog.ts` → write the catalog
  15. * `tsx scripts/gen-persistence-catalog.ts --check` → exit 1 if the committed
  16. * file is stale (CI /
  17. * pre-push gate)
  18. *
  19. * Like its AST sibling `gen-cordis-catalog.ts` (and unlike the boot-based
  20. * `gen-tool-catalog.ts`), this is a pure source pass: every log event is a
  21. * string-literal-named property with a static type annotation, so the AST is
  22. * the whole truth and a brand-new event (core or merged) appears in the next
  23. * regenerate — an un-regenerated file fails `--check`. The walk enforces JSDoc
  24. * COMPLETENESS on the whole vocabulary: every member carries description prose
  25. * (it becomes the catalog entry), and an `@mode` tag on a member is a hard
  26. * error — dispatch modes belong to cordis bus events, and a log event has none
  27. * (see docs/rfc/implemented/process/2026-07-04-persistence-log-catalog.md).
  28. * Structural holes are hard errors for the same reason: a member that is not a
  29. * property signature with an explicit payload type, an `extends` clause on a
  30. * declaration, a top-level `interface SessionEventMap` that is not the single
  31. * exported declaration in the owning package, and a duplicate declaration of
  32. * one event would each let something join (or impersonate)
  33. * `keyof SessionEventMap` without a truthful catalog row. Violations aggregate
  34. * into ONE error listing every offender.
  35. *
  36. * The surface/log-only badge is parsed from the `SurfaceEventType` union in the
  37. * owning package (never hand-listed here), and every union member must name a
  38. * collected event — a stale union member is a hard error.
  39. *
  40. * Payload fences use the ` ```ts persistence-catalog ` info string:
  41. * doc-typecheck recognizes it and skips compilation (a bare payload fragment is
  42. * not standalone-compilable), excluded from the opt-out ratio.
  43. */
  44. import { globSync, readFileSync, writeFileSync } from 'node:fs'
  45. import { resolve } from 'node:path'
  46. import ts from 'typescript'
  47. import { parseJsDoc, pointer, rawJsDoc, reportViolations } from './jsdoc.ts'
  48. const root = resolve(import.meta.dirname, '..')
  49. const OUT = 'docs/persistence-catalog.md'
  50. /** The fenced-block info string for generated payload blocks (skipped by
  51. * doc-typecheck, since a bare payload fragment is not standalone-compilable). */
  52. const FENCE = 'ts persistence-catalog'
  53. /** The package whose module id plugin merges augment (`declare module '…'`). */
  54. const SESSION_MODULE = '@deepseek-ai/dsh-session'
  55. /**
  56. * Cross-link map: a type name that appears in a payload → the
  57. * core-data-structures page that documents it (path relative to OUT's folder).
  58. * Hand-curated and catalog-owned, same policy as the cordis catalog's map: each
  59. * name resolves to exactly one PRIMARY page. A payload type with no
  60. * core-data-structures home (e.g. `HookDialect`, documented in its package)
  61. * simply gets no link.
  62. */
  63. const LINK_MAP: Record<string, string> = {
  64. CallId: 'core.md',
  65. ContentBlock: 'core.md',
  66. MessageSource: 'core.md',
  67. StreamChunk: 'llm-streaming.md',
  68. TokenUsage: 'llm-streaming.md',
  69. TodoItem: 'session.md',
  70. TurnTrigger: 'session.md',
  71. TurnEndReason: 'session.md',
  72. }
  73. /** One log event, extracted from a `SessionEventMap` declaration. */
  74. export interface LogEventEntry {
  75. /** Scoped name, e.g. `turn/start`. */
  76. name: string
  77. /** The scope prefix, e.g. `turn` (everything before the first `/`). */
  78. scope: string
  79. /** Payload type text (the member's type annotation, whitespace-collapsed). */
  80. payload: string
  81. /** Description prose (the member's JSDoc), one line per paragraph. */
  82. doc: string
  83. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  84. source: string
  85. }
  86. /** A {@link LogEventEntry} plus its surface-eligibility badge. */
  87. export interface AnnotatedLogEventEntry extends LogEventEntry {
  88. /** Whether the type is a `SurfaceEventType` member (may carry `surfaceOp`). */
  89. surface: boolean
  90. }
  91. const printer = ts.createPrinter({ removeComments: true })
  92. /**
  93. * One-line payload text for a member's type annotation. Printed through the
  94. * TypeScript printer (not sliced from source text): the printer emits `;`
  95. * member separators regardless of how the source separated them, so a
  96. * multi-line newline-separated type literal still collapses to a VALID
  97. * single-line fragment. The trailing `;` the printer puts before every `}` is
  98. * dropped to match the repo's inline-literal style.
  99. */
  100. function payloadText(type: ts.TypeNode, sf: ts.SourceFile): string {
  101. return printer.printNode(ts.EmitHint.Unspecified, type, sf)
  102. .replace(/\s+/g, ' ')
  103. .replace(/;\s*\}/g, ' }')
  104. .trim()
  105. }
  106. /**
  107. * Every `interface SessionEventMap` declaration in a source file: the owning
  108. * top-level declaration (in `@deepseek-ai/dsh-session`) and any declaration
  109. * merge inside a `declare module '@deepseek-ai/dsh-session'` block. Both forms
  110. * declare members of the SAME merged interface, so both are catalogued
  111. * uniformly. `topLevel` distinguishes the owning form so the caller can verify
  112. * it actually lives in the owning package — an unrelated local interface that
  113. * happens to share the name must not be catalogued as the on-disk vocabulary.
  114. */
  115. function sessionEventMapDecls(sf: ts.SourceFile): { decl: ts.InterfaceDeclaration; topLevel: boolean }[] {
  116. const decls: { decl: ts.InterfaceDeclaration; topLevel: boolean }[] = []
  117. for (const stmt of sf.statements) {
  118. if (ts.isInterfaceDeclaration(stmt) && stmt.name.text === 'SessionEventMap') decls.push({ decl: stmt, topLevel: true })
  119. if (ts.isModuleDeclaration(stmt) && ts.isStringLiteral(stmt.name) && stmt.name.text === SESSION_MODULE
  120. && stmt.body && ts.isModuleBlock(stmt.body)) {
  121. for (const inner of stmt.body.statements) {
  122. if (ts.isInterfaceDeclaration(inner) && inner.name.text === 'SessionEventMap') decls.push({ decl: inner, topLevel: false })
  123. }
  124. }
  125. }
  126. return decls
  127. }
  128. /**
  129. * The npm package name owning a `packages/<group>/<pkg>/…` source file, read
  130. * from that package's manifest — or null when the manifest is missing or
  131. * unparseable (the caller treats null as "ownership unverifiable").
  132. */
  133. function packageNameFor(rel: string, scanRoot: string): string | null {
  134. const dir = rel.split('/').slice(0, 3).join('/')
  135. try {
  136. const manifest = JSON.parse(readFileSync(resolve(scanRoot, dir, 'package.json'), 'utf8')) as { name?: string }
  137. return typeof manifest.name === 'string' ? manifest.name : null
  138. } catch {
  139. // Missing or malformed package.json — every real workspace package has one,
  140. // so this only arises in stripped-down fixture trees; either way ownership
  141. // cannot be verified and the caller reports the declaration.
  142. return null
  143. }
  144. }
  145. /**
  146. * Walk every `SessionEventMap` declaration (the owning interface plus every
  147. * plugin declaration merge) and extract its events, hard-erroring (aggregated)
  148. * on any completeness violation: a member without description prose, an
  149. * `@mode` tag (a category error — log events have no dispatch mode), a member
  150. * that is not a property signature with an explicit payload type, a
  151. * non-literal member name, an `extends` clause (inherited keys would join
  152. * `keyof SessionEventMap` without a catalog row), a top-level declaration that
  153. * is not the single exported one in the owning package, or the same event
  154. * declared twice.
  155. * `scanRoot` defaults to the repo root; tests pass a fixture dir.
  156. */
  157. export function collectLogEvents(scanRoot: string = root): LogEventEntry[] {
  158. const entries: LogEventEntry[] = []
  159. const violations: string[] = []
  160. const seen = new Map<string, string>()
  161. let owningDecl: string | null = null
  162. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).sort()) {
  163. const abs = resolve(scanRoot, rel)
  164. const text = readFileSync(abs, 'utf8')
  165. if (!text.includes('SessionEventMap')) continue
  166. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  167. for (const { decl, topLevel } of sessionEventMapDecls(sf)) {
  168. const declSrc = pointer(rel, sf, decl)
  169. if (topLevel) {
  170. // The top-level form is the OWNING vocabulary, and it has exactly one
  171. // home: the single EXPORTED declaration in the owning package. A
  172. // same-named interface anywhere else — another package, a non-exported
  173. // local, a second exported copy — is a different type that must not be
  174. // catalogued as on-disk events.
  175. const pkg = packageNameFor(rel, scanRoot)
  176. if (pkg !== SESSION_MODULE) {
  177. 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}'.`)
  178. continue
  179. }
  180. const exported = decl.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false
  181. if (!exported) {
  182. violations.push(`top-level interface SessionEventMap (${declSrc}) is not exported; the owning vocabulary is the single exported declaration — rename a local helper interface.`)
  183. continue
  184. }
  185. if (owningDecl) {
  186. violations.push(`top-level interface SessionEventMap (${declSrc}) is already declared at ${owningDecl}; the owning vocabulary has exactly one home.`)
  187. continue
  188. }
  189. owningDecl = declSrc
  190. }
  191. if (decl.heritageClauses?.length) {
  192. violations.push(`SessionEventMap declaration (${declSrc}) uses extends; inherited keys would join keyof SessionEventMap without a catalog row — declare event members directly.`)
  193. }
  194. for (const member of decl.members) {
  195. const src = pointer(rel, sf, member)
  196. if (!ts.isPropertySignature(member) || !member.type) {
  197. // A method-form or type-less member still joins `keyof SessionEventMap`,
  198. // so skipping it silently would be exactly the undocumented-event hole
  199. // this catalog exists to close.
  200. const label = (member as { name?: ts.Node }).name?.getText(sf) ?? member.getText(sf).replace(/\s+/g, ' ')
  201. violations.push(`SessionEventMap member ${label} (${src}) is not a property signature with an explicit payload type; declare every log event as 'scope/name': <payload>.`)
  202. continue
  203. }
  204. if (!ts.isStringLiteral(member.name)) {
  205. violations.push(`log event at ${src} has a non-literal name; the catalog needs string-literal event names.`)
  206. continue
  207. }
  208. const name = member.name.text
  209. const where = `log event '${name}' (${src})`
  210. const prior = seen.get(name)
  211. if (prior) {
  212. violations.push(`${where} is already declared at ${prior}; an event type has exactly one declaration.`)
  213. continue
  214. }
  215. seen.set(name, src)
  216. const payload = payloadText(member.type, sf)
  217. const { doc, hasMode } = parseJsDoc(rawJsDoc(text, member))
  218. if (hasMode) {
  219. 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.`)
  220. }
  221. if (!doc) {
  222. violations.push(`${where} has no description prose. Say what the event records and what its payload means — the JSDoc becomes the catalog entry.`)
  223. }
  224. entries.push({ name, scope: name.split('/')[0] ?? name, payload, doc, source: src })
  225. }
  226. }
  227. }
  228. reportViolations('gen-persistence-catalog', violations)
  229. return entries
  230. }
  231. /**
  232. * Parse the `SurfaceEventType` union — the surface-eligible subset of event
  233. * types — from source. Hard-errors when the alias is missing, declared more
  234. * than once, or contains a non-string-literal member: the badge derivation
  235. * relies on the union being a closed set of literal event names.
  236. * `scanRoot` defaults to the repo root; tests pass a fixture dir.
  237. */
  238. export function collectSurfaceEventTypes(scanRoot: string = root): string[] {
  239. const found: { names: string[]; source: string }[] = []
  240. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).sort()) {
  241. const abs = resolve(scanRoot, rel)
  242. const text = readFileSync(abs, 'utf8')
  243. if (!text.includes('SurfaceEventType')) continue
  244. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  245. for (const stmt of sf.statements) {
  246. if (!ts.isTypeAliasDeclaration(stmt) || stmt.name.text !== 'SurfaceEventType') continue
  247. const src = pointer(rel, sf, stmt)
  248. const members = ts.isUnionTypeNode(stmt.type) ? [...stmt.type.types] : [stmt.type]
  249. const names: string[] = []
  250. for (const m of members) {
  251. if (ts.isLiteralTypeNode(m) && ts.isStringLiteral(m.literal)) names.push(m.literal.text)
  252. else throw new Error(`gen-persistence-catalog: SurfaceEventType (${src}) has a non-string-literal member; the badge derivation needs a closed literal union.`)
  253. }
  254. found.push({ names, source: src })
  255. }
  256. }
  257. const only = found[0]
  258. if (!only) throw new Error('gen-persistence-catalog: no SurfaceEventType union found under packages/*/*/src.')
  259. 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.`)
  260. return only.names
  261. }
  262. /**
  263. * Attach the surface/log-only badge to each event. Hard-errors when a
  264. * `SurfaceEventType` union member names no collected event — a stale union
  265. * member would otherwise silently badge nothing.
  266. */
  267. export function annotateSurface(events: LogEventEntry[], surfaceTypes: string[]): AnnotatedLogEventEntry[] {
  268. const names = new Set(events.map(e => e.name))
  269. const stale = surfaceTypes.filter(t => !names.has(t))
  270. if (stale.length > 0) {
  271. throw new Error(`gen-persistence-catalog: SurfaceEventType member(s) ${stale.map(t => `'${t}'`).join(', ')} name no declared log event (stale union member?).`)
  272. }
  273. const surface = new Set(surfaceTypes)
  274. return events.map(e => ({ ...e, surface: surface.has(e.name) }))
  275. }
  276. /** Render the cross-link "Types:" line for a payload, or '' if none apply. */
  277. function typeLinks(payload: string): string {
  278. const seen = new Set<string>()
  279. for (const name of Object.keys(LINK_MAP)) {
  280. if (new RegExp(`\\b${name}\\b`).test(payload)) seen.add(name)
  281. }
  282. if (seen.size === 0) return ''
  283. const links = [...seen].sort().map(n => `[${n}](core-data-structures/${LINK_MAP[n]})`)
  284. return `Types: ${links.join(' · ')}`
  285. }
  286. /** Render one log event entry. */
  287. function renderEvent(e: AnnotatedLogEventEntry): string[] {
  288. const out = [`#### \`${e.name}\` — ${e.surface ? 'surface' : 'log-only'}`, '']
  289. if (e.doc) out.push(e.doc, '')
  290. out.push('```' + FENCE, `'${e.name}': ${e.payload}`, '```', '')
  291. const links = typeLinks(e.payload)
  292. if (links) out.push(links, '')
  293. out.push(`Source: [\`${e.source}\`](../${e.source.split(':')[0]})`, '')
  294. return out
  295. }
  296. /** Render the full catalog (pure, deterministic given the collected inputs). */
  297. export function render(events: AnnotatedLogEventEntry[]): string {
  298. const lines: string[] = [
  299. '<!-- Generated by scripts/gen-persistence-catalog.ts — do not edit by hand.',
  300. ' Run `pnpm run gen-persistence-catalog` to regenerate. -->',
  301. '',
  302. '# Persistence Log Event Catalog',
  303. '',
  304. 'Every event type that can appear in a session\'s durable event log: each member of the merge-extensible `SessionEventMap` — the owning vocabulary in `@deepseek-ai/dsh-session` plus every plugin declaration merge in this repo — with the payload it carries, its surface badge, and the declaration it comes from. It complements [session.md](core-data-structures/session.md) (the `SessionEvent` envelope, surface list, and `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).',
  305. '',
  306. '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. Payload blocks use a `ts persistence-catalog` fence (skipped by doc-typecheck, since a bare payload fragment is not standalone-compilable). Type names in a payload link to the page that documents them. See [the persistence-log-catalog RFC](rfc/implemented/process/2026-07-04-persistence-log-catalog.md).',
  307. '',
  308. 'The on-disk envelope around every payload is `SessionEvent` — `type`, monotonic `seq`, epoch-ms `time`, the `data` documented here, plus `surfaceOp`/`sourceEventSeqs` on **surface** events only ([envelope](core-data-structures/session.md#sessioneventt--one-log-entry)). **surface** marks a `SurfaceEventType` member: it produces an LLM message and declares how it joins the surface list. **log-only** marks everything else: 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.',
  309. '',
  310. '## Events',
  311. '',
  312. ]
  313. const scopes = [...new Set(events.map(e => e.scope))].sort()
  314. for (const scope of scopes) {
  315. lines.push(`### \`${scope}/*\``, '')
  316. for (const e of events.filter(x => x.scope === scope).sort((a, b) => a.name.localeCompare(b.name))) {
  317. lines.push(...renderEvent(e))
  318. }
  319. }
  320. return lines.join('\n')
  321. }
  322. /** CLI entry: default writes the catalog, `--check` fails if the committed copy
  323. * is stale. Guarded behind an entry-point check so importing this module for
  324. * tests neither regenerates the committed file nor calls process.exit. */
  325. function main(): void {
  326. const content = render(annotateSurface(collectLogEvents(), collectSurfaceEventTypes()))
  327. if (process.argv.includes('--check')) {
  328. let committed: string | null = null
  329. try {
  330. committed = readFileSync(resolve(root, OUT), 'utf8')
  331. } catch {
  332. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  333. // file is not a state this repo produces. Either way the remedy is the
  334. // same — regenerate — so treat a read failure as "stale".
  335. committed = null
  336. }
  337. if (committed === content) {
  338. console.log(`gen-persistence-catalog: ${OUT} is up to date.`)
  339. process.exit(0)
  340. }
  341. console.error(`gen-persistence-catalog: ${OUT} is stale. Run \`pnpm run gen-persistence-catalog\` and commit ${OUT}.`)
  342. process.exit(1)
  343. }
  344. writeFileSync(resolve(root, OUT), content)
  345. console.log(`gen-persistence-catalog: wrote ${OUT}.`)
  346. }
  347. // Run only when invoked as a script, not when imported by a test.
  348. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  349. main()
  350. }