gen-persistence-catalog.ts 23 KB

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