gen-persistence-catalog.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. /**
  2. * Generate `docs/persistence-catalog.md` from every `SessionEventMap` merge and
  3. * the owning `SurfaceEventType` union. This is the durable-record vocabulary,
  4. * not 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 } 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 payload blocks (skipped by
  15. * doc-typecheck, since a bare payload fragment is 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. /** Primary core-data-structures page for linked payload types. */
  20. const LINK_MAP: Record<string, string> = {
  21. CallId: 'core.md',
  22. ContentBlock: 'core.md',
  23. MessageSource: 'core.md',
  24. StreamChunk: 'llm-streaming.md',
  25. TokenUsage: 'llm-streaming.md',
  26. TodoItem: 'session.md',
  27. TurnTrigger: 'session.md',
  28. TurnEndReason: 'session.md',
  29. }
  30. /** One log event, extracted from a `SessionEventMap` declaration. */
  31. export interface LogEventEntry {
  32. /** Scoped name, e.g. `turn/start`. */
  33. name: string
  34. /** The scope prefix, e.g. `turn` (everything before the first `/`). */
  35. scope: string
  36. /** Payload type text (the member's type annotation, whitespace-collapsed). */
  37. payload: string
  38. /** Description prose (the member's JSDoc), one line per paragraph. */
  39. doc: string
  40. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  41. source: string
  42. }
  43. /** A {@link LogEventEntry} plus its surface-eligibility badge. */
  44. export interface AnnotatedLogEventEntry extends LogEventEntry {
  45. /** Whether the type is a `SurfaceEventType` member (may carry `surfaceOp`). */
  46. surface: boolean
  47. }
  48. const printer = ts.createPrinter({ removeComments: true })
  49. /**
  50. * Render a member type on one line through the TypeScript printer, which adds
  51. * semicolon separators. Drop its trailing semicolon before `}` to match the
  52. * repository's inline-literal style.
  53. */
  54. function payloadText(type: ts.TypeNode, sf: ts.SourceFile): string {
  55. return printer.printNode(ts.EmitHint.Unspecified, type, sf)
  56. .replace(/\s+/g, ' ')
  57. .replace(/;\s*\}/g, ' }')
  58. .trim()
  59. }
  60. /**
  61. * Every `interface SessionEventMap` declaration in a source file: the owning
  62. * top-level declaration (in `@deepseek-ai/dsh-session`) and any declaration
  63. * merge inside a `declare module '@deepseek-ai/dsh-session'` block. Both forms
  64. * declare members of the SAME merged interface, so both are catalogued
  65. * uniformly. `topLevel` distinguishes the owning form so the caller can verify
  66. * it actually lives in the owning package — an unrelated local interface that
  67. * happens to share the name must not be catalogued as the on-disk vocabulary.
  68. */
  69. function sessionEventMapDecls(sf: ts.SourceFile): { decl: ts.InterfaceDeclaration; topLevel: boolean }[] {
  70. const decls: { decl: ts.InterfaceDeclaration; topLevel: boolean }[] = []
  71. for (const stmt of sf.statements) {
  72. if (ts.isInterfaceDeclaration(stmt) && stmt.name.text === 'SessionEventMap') decls.push({ decl: stmt, topLevel: true })
  73. if (ts.isModuleDeclaration(stmt) && ts.isStringLiteral(stmt.name) && stmt.name.text === SESSION_MODULE
  74. && stmt.body && ts.isModuleBlock(stmt.body)) {
  75. for (const inner of stmt.body.statements) {
  76. if (ts.isInterfaceDeclaration(inner) && inner.name.text === 'SessionEventMap') decls.push({ decl: inner, topLevel: false })
  77. }
  78. }
  79. }
  80. return decls
  81. }
  82. /**
  83. * The npm package name owning a `packages/<group>/<pkg>/…` source file, read
  84. * from that package's manifest — or null when the manifest is missing or
  85. * unparseable (the caller treats null as "ownership unverifiable").
  86. */
  87. function packageNameFor(rel: string, scanRoot: string): string | null {
  88. const dir = rel.split('/').slice(0, 3).join('/')
  89. try {
  90. const manifest = JSON.parse(readFileSync(resolve(scanRoot, dir, 'package.json'), 'utf8')) as { name?: string }
  91. return typeof manifest.name === 'string' ? manifest.name : null
  92. } catch {
  93. // Missing or malformed package.json — every real workspace package has one,
  94. // so this only arises in stripped-down fixture trees; either way ownership
  95. // cannot be verified and the caller reports the declaration.
  96. return null
  97. }
  98. }
  99. /**
  100. * Collect every `SessionEventMap` merge, rejecting inherited, non-literal,
  101. * untyped, undocumented, duplicate, or incorrectly owned members in one report.
  102. */
  103. export function collectLogEvents(scanRoot: string = root): LogEventEntry[] {
  104. const entries: LogEventEntry[] = []
  105. const violations: string[] = []
  106. const seen = new Map<string, string>()
  107. let owningDecl: string | null = null
  108. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).sort()) {
  109. const abs = resolve(scanRoot, rel)
  110. const text = readFileSync(abs, 'utf8')
  111. if (!text.includes('SessionEventMap')) continue
  112. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  113. for (const { decl, topLevel } of sessionEventMapDecls(sf)) {
  114. const declSrc = pointer(rel, sf, decl)
  115. if (topLevel) {
  116. // The top-level form has one home: the single exported declaration in
  117. // the owning package. Same-named interfaces elsewhere are different
  118. // types and must not enter the on-disk catalog.
  119. const pkg = packageNameFor(rel, scanRoot)
  120. if (pkg !== SESSION_MODULE) {
  121. 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}'.`)
  122. continue
  123. }
  124. const exported = decl.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false
  125. if (!exported) {
  126. violations.push(`top-level interface SessionEventMap (${declSrc}) is not exported; the owning vocabulary is the single exported declaration — rename a local helper interface.`)
  127. continue
  128. }
  129. if (owningDecl) {
  130. violations.push(`top-level interface SessionEventMap (${declSrc}) is already declared at ${owningDecl}; the owning vocabulary has exactly one home.`)
  131. continue
  132. }
  133. owningDecl = declSrc
  134. }
  135. if (decl.heritageClauses?.length) {
  136. violations.push(`SessionEventMap declaration (${declSrc}) uses extends; inherited keys would join keyof SessionEventMap without a catalog row — declare event members directly.`)
  137. }
  138. for (const member of decl.members) {
  139. const src = pointer(rel, sf, member)
  140. if (!ts.isPropertySignature(member) || !member.type) {
  141. // A method-form or type-less member still joins `keyof SessionEventMap`,
  142. // so skipping it silently would be exactly the undocumented-event hole
  143. // this catalog exists to close.
  144. const label = (member as { name?: ts.Node }).name?.getText(sf) ?? member.getText(sf).replace(/\s+/g, ' ')
  145. violations.push(`SessionEventMap member ${label} (${src}) is not a property signature with an explicit payload type; declare every log event as 'scope/name': <payload>.`)
  146. continue
  147. }
  148. if (!ts.isStringLiteral(member.name)) {
  149. violations.push(`log event at ${src} has a non-literal name; the catalog needs string-literal event names.`)
  150. continue
  151. }
  152. const name = member.name.text
  153. const where = `log event '${name}' (${src})`
  154. const prior = seen.get(name)
  155. if (prior) {
  156. violations.push(`${where} is already declared at ${prior}; an event type has exactly one declaration.`)
  157. continue
  158. }
  159. seen.set(name, src)
  160. const payload = payloadText(member.type, sf)
  161. const { doc, hasMode } = parseJsDoc(rawJsDoc(text, member))
  162. if (hasMode) {
  163. 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.`)
  164. }
  165. if (!doc) {
  166. violations.push(`${where} has no description prose. Say what the event records and what its payload means — the JSDoc becomes the catalog entry.`)
  167. }
  168. entries.push({ name, scope: name.split('/')[0] ?? name, payload, doc, source: src })
  169. }
  170. }
  171. }
  172. reportViolations('gen-persistence-catalog', violations)
  173. return entries
  174. }
  175. /**
  176. * Parse the `SurfaceEventType` union — the surface-eligible subset of event
  177. * types — from source. Hard-errors when the alias is missing, declared more
  178. * than once, or contains a non-string-literal member: the badge derivation
  179. * relies on the union being a closed set of literal event names.
  180. * `scanRoot` defaults to the repo root; tests pass a fixture dir.
  181. */
  182. export function collectSurfaceEventTypes(scanRoot: string = root): string[] {
  183. const found: { names: string[]; source: string }[] = []
  184. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).sort()) {
  185. const abs = resolve(scanRoot, rel)
  186. const text = readFileSync(abs, 'utf8')
  187. if (!text.includes('SurfaceEventType')) continue
  188. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  189. for (const stmt of sf.statements) {
  190. if (!ts.isTypeAliasDeclaration(stmt) || stmt.name.text !== 'SurfaceEventType') continue
  191. const src = pointer(rel, sf, stmt)
  192. const members = ts.isUnionTypeNode(stmt.type) ? [...stmt.type.types] : [stmt.type]
  193. const names: string[] = []
  194. for (const m of members) {
  195. if (ts.isLiteralTypeNode(m) && ts.isStringLiteral(m.literal)) names.push(m.literal.text)
  196. else throw new Error(`gen-persistence-catalog: SurfaceEventType (${src}) has a non-string-literal member; the badge derivation needs a closed literal union.`)
  197. }
  198. found.push({ names, source: src })
  199. }
  200. }
  201. const only = found[0]
  202. if (!only) throw new Error('gen-persistence-catalog: no SurfaceEventType union found under packages/*/*/src.')
  203. 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.`)
  204. return only.names
  205. }
  206. /**
  207. * Attach the surface/log-only badge to each event. Hard-errors when a
  208. * `SurfaceEventType` union member names no collected event — a stale union
  209. * member would otherwise silently badge nothing.
  210. */
  211. export function annotateSurface(events: LogEventEntry[], surfaceTypes: string[]): AnnotatedLogEventEntry[] {
  212. const names = new Set(events.map(e => e.name))
  213. const stale = surfaceTypes.filter(t => !names.has(t))
  214. if (stale.length > 0) {
  215. throw new Error(`gen-persistence-catalog: SurfaceEventType member(s) ${stale.map(t => `'${t}'`).join(', ')} name no declared log event (stale union member?).`)
  216. }
  217. const surface = new Set(surfaceTypes)
  218. return events.map(e => ({ ...e, surface: surface.has(e.name) }))
  219. }
  220. /** Render the cross-link "Types:" line for a payload, or '' if none apply. */
  221. function typeLinks(payload: string): string {
  222. const seen = new Set<string>()
  223. for (const name of Object.keys(LINK_MAP)) {
  224. if (new RegExp(`\\b${name}\\b`).test(payload)) seen.add(name)
  225. }
  226. if (seen.size === 0) return ''
  227. const links = [...seen].sort().map(n => `[${n}](core-data-structures/${LINK_MAP[n]})`)
  228. return `Types: ${links.join(' · ')}`
  229. }
  230. /** Render one log event entry. */
  231. function renderEvent(e: AnnotatedLogEventEntry): string[] {
  232. const out = [`#### \`${e.name}\` — ${e.surface ? 'surface' : 'log-only'}`, '']
  233. if (e.doc) out.push(e.doc, '')
  234. out.push('```' + FENCE, `'${e.name}': ${e.payload}`, '```', '')
  235. const links = typeLinks(e.payload)
  236. if (links) out.push(links, '')
  237. out.push(`Source: [\`${e.source}\`](../${e.source.split(':')[0]})`, '')
  238. return out
  239. }
  240. /** Render the full catalog (pure, deterministic given the collected inputs). */
  241. export function render(events: AnnotatedLogEventEntry[]): string {
  242. const lines: string[] = [
  243. '<!-- Generated by scripts/gen-persistence-catalog.ts — do not edit by hand.',
  244. ' Run `pnpm run gen-persistence-catalog` to regenerate. -->',
  245. '',
  246. '# Persistence Log Event Catalog',
  247. '',
  248. '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).',
  249. '',
  250. '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).',
  251. '',
  252. '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.',
  253. '',
  254. '## Events',
  255. '',
  256. ]
  257. const scopes = [...new Set(events.map(e => e.scope))].sort()
  258. for (const scope of scopes) {
  259. lines.push(`### \`${scope}/*\``, '')
  260. for (const e of events.filter(x => x.scope === scope).sort((a, b) => a.name.localeCompare(b.name))) {
  261. lines.push(...renderEvent(e))
  262. }
  263. }
  264. return lines.join('\n')
  265. }
  266. /** CLI entry: default writes the catalog, `--check` fails if the committed copy
  267. * is stale. Guarded behind an entry-point check so importing this module for
  268. * tests neither regenerates the committed file nor calls process.exit. */
  269. function main(): void {
  270. const content = render(annotateSurface(collectLogEvents(), collectSurfaceEventTypes()))
  271. if (process.argv.includes('--check')) {
  272. let committed: string | null = null
  273. try {
  274. committed = readFileSync(resolve(root, OUT), 'utf8')
  275. } catch {
  276. // Only ENOENT (not yet generated) is expected; a present-but-unreadable
  277. // file is not a state this repo produces. Either way the remedy is the
  278. // same — regenerate — so treat a read failure as "stale".
  279. committed = null
  280. }
  281. if (committed === content) {
  282. console.log(`gen-persistence-catalog: ${OUT} is up to date.`)
  283. process.exit(0)
  284. }
  285. console.error(`gen-persistence-catalog: ${OUT} is stale. Run \`pnpm run gen-persistence-catalog\` and commit ${OUT}.`)
  286. process.exit(1)
  287. }
  288. writeFileSync(resolve(root, OUT), content)
  289. console.log(`gen-persistence-catalog: wrote ${OUT}.`)
  290. }
  291. // Run only when invoked as a script, not when imported by a test.
  292. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  293. main()
  294. }