gen-persistence-catalog.ts 24 KB

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