gen-persistence-catalog.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. const root = resolve(import.meta.dirname, '..')
  48. const OUT = 'docs/persistence-catalog.md'
  49. /** The fenced-block info string for generated payload blocks (skipped by
  50. * doc-typecheck, since a bare payload fragment is not standalone-compilable). */
  51. const FENCE = 'ts persistence-catalog'
  52. /** The package whose module id plugin merges augment (`declare module '…'`). */
  53. const SESSION_MODULE = '@deepseek-ai/dsh-session'
  54. /**
  55. * Cross-link map: a type name that appears in a payload → the
  56. * core-data-structures page that documents it (path relative to OUT's folder).
  57. * Hand-curated and catalog-owned, same policy as the cordis catalog's map: each
  58. * name resolves to exactly one PRIMARY page. A payload type with no
  59. * core-data-structures home (e.g. `HookDialect`, documented in its package)
  60. * simply gets no link.
  61. */
  62. const LINK_MAP: Record<string, string> = {
  63. CallId: 'core.md',
  64. ContentBlock: 'core.md',
  65. MessageSource: 'core.md',
  66. StreamChunk: 'llm-streaming.md',
  67. TokenUsage: 'llm-streaming.md',
  68. TodoItem: 'session.md',
  69. TurnTrigger: 'session.md',
  70. TurnEndReason: 'session.md',
  71. }
  72. /** One log event, extracted from a `SessionEventMap` declaration. */
  73. export interface LogEventEntry {
  74. /** Scoped name, e.g. `turn/start`. */
  75. name: string
  76. /** The scope prefix, e.g. `turn` (everything before the first `/`). */
  77. scope: string
  78. /** Payload type text (the member's type annotation, whitespace-collapsed). */
  79. payload: string
  80. /** Description prose (the member's JSDoc), one line per paragraph. */
  81. doc: string
  82. /** Source pointer `packages/…/file.ts:line` of the declaration. */
  83. source: string
  84. }
  85. /** A {@link LogEventEntry} plus its surface-eligibility badge. */
  86. export interface AnnotatedLogEventEntry extends LogEventEntry {
  87. /** Whether the type is a `SurfaceEventType` member (may carry `surfaceOp`). */
  88. surface: boolean
  89. }
  90. /** Repo-relative source pointer `file:line` for a node's first character. */
  91. function pointer(rel: string, sf: ts.SourceFile, node: ts.Node): string {
  92. const { line } = sf.getLineAndCharacterOfPosition(node.getStart(sf))
  93. return `${rel}:${line + 1}`
  94. }
  95. const printer = ts.createPrinter({ removeComments: true })
  96. /**
  97. * One-line payload text for a member's type annotation. Printed through the
  98. * TypeScript printer (not sliced from source text): the printer emits `;`
  99. * member separators regardless of how the source separated them, so a
  100. * multi-line newline-separated type literal still collapses to a VALID
  101. * single-line fragment. The trailing `;` the printer puts before every `}` is
  102. * dropped to match the repo's inline-literal style.
  103. */
  104. function payloadText(type: ts.TypeNode, sf: ts.SourceFile): string {
  105. return printer.printNode(ts.EmitHint.Unspecified, type, sf)
  106. .replace(/\s+/g, ' ')
  107. .replace(/;\s*\}/g, ' }')
  108. .trim()
  109. }
  110. /** The raw `/** … *​/` JSDoc block immediately preceding a node, or '' if none. */
  111. function rawJsDoc(text: string, node: ts.Node): string {
  112. const ranges = ts.getLeadingCommentRanges(text, node.getFullStart()) ?? []
  113. const jsdoc = ranges.filter(r => text.slice(r.pos, r.pos + 3) === '/**').at(-1)
  114. return jsdoc ? text.slice(jsdoc.pos, jsdoc.end) : ''
  115. }
  116. /**
  117. * Parse a raw JSDoc block into description prose, flagging whether any `@mode`
  118. * tag is present (forbidden on log events). Output obeys the repo's markdown
  119. * conventions so the generated file passes verify-md-wrap: each prose paragraph
  120. * collapses to ONE physical line, and a `-` bullet list is preserved with each
  121. * item on its own single line (continuation lines folded in). `{@link Foo}`
  122. * unwraps to `Foo`. Description prose ends at the FIRST block tag (standard
  123. * JSDoc semantics): tag lines and their continuation lines are never prose.
  124. */
  125. function parseJsDoc(raw: string): { doc: string; hasMode: boolean } {
  126. const inner = raw
  127. .replace(/^\/\*\*/, '')
  128. .replace(/\*\/$/, '')
  129. .split('\n')
  130. .map(l => l.replace(/^\s*\*?\s?/, '').replace(/\s+$/, ''))
  131. let hasMode = false
  132. let inTags = false
  133. const blocks: string[] = []
  134. let para: string[] = []
  135. let list: string[] = []
  136. let item: string[] = []
  137. const join = (parts: string[]): string => parts.join(' ').replace(/\s+/g, ' ').trim()
  138. const flushItem = (): void => {
  139. if (item.length) list.push(join(item))
  140. item = []
  141. }
  142. const flushList = (): void => {
  143. flushItem()
  144. if (list.length) blocks.push(list.join('\n')) // one block, items on own lines
  145. list = []
  146. }
  147. const flushPara = (): void => {
  148. flushList()
  149. if (para.length) blocks.push(join(para))
  150. para = []
  151. }
  152. for (const line of inner) {
  153. // Tag detection runs on the trimmed line: the normalization above strips at
  154. // most one post-`*` space, so an extra-indented `* @mode` still reaches
  155. // here with leading whitespace and must not leak into prose.
  156. const tagLine = line.trimStart()
  157. if (/^@mode\b/.test(tagLine)) { hasMode = true; flushPara(); inTags = true; continue }
  158. if (tagLine.startsWith('@')) { flushPara(); inTags = true; continue }
  159. if (inTags) continue // block-tag territory: continuations are never prose
  160. if (line.trim() === '') { flushPara(); continue }
  161. if (/^-\s+/.test(line)) {
  162. // A list item starts: a pending paragraph (e.g. an intro line directly
  163. // above the list, no blank between) flushes FIRST so it renders above.
  164. flushItem()
  165. if (para.length) { blocks.push(join(para)); para = [] }
  166. item.push(line)
  167. continue
  168. }
  169. if (item.length) { item.push(line); continue } // continuation of current item
  170. para.push(line)
  171. }
  172. flushPara()
  173. const doc = blocks.join('\n\n').replace(/\{@link\s+([^}]+)\}/g, '$1').trim()
  174. return { doc, hasMode }
  175. }
  176. /**
  177. * Throw one aggregate error for every completeness violation a walk collected.
  178. * Aggregation is deliberate: a remediation pass sees the whole list at once
  179. * instead of replaying the gate once per offender.
  180. */
  181. function reportViolations(violations: string[]): void {
  182. if (violations.length === 0) return
  183. throw new Error(
  184. `gen-persistence-catalog: ${violations.length} JSDoc completeness violation(s):\n`
  185. + violations.map(v => ` ${v}`).join('\n'),
  186. )
  187. }
  188. /**
  189. * Every `interface SessionEventMap` declaration in a source file: the owning
  190. * top-level declaration (in `@deepseek-ai/dsh-session`) and any declaration
  191. * merge inside a `declare module '@deepseek-ai/dsh-session'` block. Both forms
  192. * declare members of the SAME merged interface, so both are catalogued
  193. * uniformly. `topLevel` distinguishes the owning form so the caller can verify
  194. * it actually lives in the owning package — an unrelated local interface that
  195. * happens to share the name must not be catalogued as the on-disk vocabulary.
  196. */
  197. function sessionEventMapDecls(sf: ts.SourceFile): { decl: ts.InterfaceDeclaration; topLevel: boolean }[] {
  198. const decls: { decl: ts.InterfaceDeclaration; topLevel: boolean }[] = []
  199. for (const stmt of sf.statements) {
  200. if (ts.isInterfaceDeclaration(stmt) && stmt.name.text === 'SessionEventMap') decls.push({ decl: stmt, topLevel: true })
  201. if (ts.isModuleDeclaration(stmt) && ts.isStringLiteral(stmt.name) && stmt.name.text === SESSION_MODULE
  202. && stmt.body && ts.isModuleBlock(stmt.body)) {
  203. for (const inner of stmt.body.statements) {
  204. if (ts.isInterfaceDeclaration(inner) && inner.name.text === 'SessionEventMap') decls.push({ decl: inner, topLevel: false })
  205. }
  206. }
  207. }
  208. return decls
  209. }
  210. /**
  211. * The npm package name owning a `packages/<group>/<pkg>/…` source file, read
  212. * from that package's manifest — or null when the manifest is missing or
  213. * unparseable (the caller treats null as "ownership unverifiable").
  214. */
  215. function packageNameFor(rel: string, scanRoot: string): string | null {
  216. const dir = rel.split('/').slice(0, 3).join('/')
  217. try {
  218. const manifest = JSON.parse(readFileSync(resolve(scanRoot, dir, 'package.json'), 'utf8')) as { name?: string }
  219. return typeof manifest.name === 'string' ? manifest.name : null
  220. } catch {
  221. // Missing or malformed package.json — every real workspace package has one,
  222. // so this only arises in stripped-down fixture trees; either way ownership
  223. // cannot be verified and the caller reports the declaration.
  224. return null
  225. }
  226. }
  227. /**
  228. * Walk every `SessionEventMap` declaration (the owning interface plus every
  229. * plugin declaration merge) and extract its events, hard-erroring (aggregated)
  230. * on any completeness violation: a member without description prose, an
  231. * `@mode` tag (a category error — log events have no dispatch mode), a member
  232. * that is not a property signature with an explicit payload type, a
  233. * non-literal member name, an `extends` clause (inherited keys would join
  234. * `keyof SessionEventMap` without a catalog row), a top-level declaration that
  235. * is not the single exported one in the owning package, or the same event
  236. * declared twice.
  237. * `scanRoot` defaults to the repo root; tests pass a fixture dir.
  238. */
  239. export function collectLogEvents(scanRoot: string = root): LogEventEntry[] {
  240. const entries: LogEventEntry[] = []
  241. const violations: string[] = []
  242. const seen = new Map<string, string>()
  243. let owningDecl: string | null = null
  244. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).sort()) {
  245. const abs = resolve(scanRoot, rel)
  246. const text = readFileSync(abs, 'utf8')
  247. if (!text.includes('SessionEventMap')) continue
  248. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  249. for (const { decl, topLevel } of sessionEventMapDecls(sf)) {
  250. const declSrc = pointer(rel, sf, decl)
  251. if (topLevel) {
  252. // The top-level form is the OWNING vocabulary, and it has exactly one
  253. // home: the single EXPORTED declaration in the owning package. A
  254. // same-named interface anywhere else — another package, a non-exported
  255. // local, a second exported copy — is a different type that must not be
  256. // catalogued as on-disk events.
  257. const pkg = packageNameFor(rel, scanRoot)
  258. if (pkg !== SESSION_MODULE) {
  259. 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}'.`)
  260. continue
  261. }
  262. const exported = decl.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false
  263. if (!exported) {
  264. violations.push(`top-level interface SessionEventMap (${declSrc}) is not exported; the owning vocabulary is the single exported declaration — rename a local helper interface.`)
  265. continue
  266. }
  267. if (owningDecl) {
  268. violations.push(`top-level interface SessionEventMap (${declSrc}) is already declared at ${owningDecl}; the owning vocabulary has exactly one home.`)
  269. continue
  270. }
  271. owningDecl = declSrc
  272. }
  273. if (decl.heritageClauses?.length) {
  274. violations.push(`SessionEventMap declaration (${declSrc}) uses extends; inherited keys would join keyof SessionEventMap without a catalog row — declare event members directly.`)
  275. }
  276. for (const member of decl.members) {
  277. const src = pointer(rel, sf, member)
  278. if (!ts.isPropertySignature(member) || !member.type) {
  279. // A method-form or type-less member still joins `keyof SessionEventMap`,
  280. // so skipping it silently would be exactly the undocumented-event hole
  281. // this catalog exists to close.
  282. const label = (member as { name?: ts.Node }).name?.getText(sf) ?? member.getText(sf).replace(/\s+/g, ' ')
  283. violations.push(`SessionEventMap member ${label} (${src}) is not a property signature with an explicit payload type; declare every log event as 'scope/name': <payload>.`)
  284. continue
  285. }
  286. if (!ts.isStringLiteral(member.name)) {
  287. violations.push(`log event at ${src} has a non-literal name; the catalog needs string-literal event names.`)
  288. continue
  289. }
  290. const name = member.name.text
  291. const where = `log event '${name}' (${src})`
  292. const prior = seen.get(name)
  293. if (prior) {
  294. violations.push(`${where} is already declared at ${prior}; an event type has exactly one declaration.`)
  295. continue
  296. }
  297. seen.set(name, src)
  298. const payload = payloadText(member.type, sf)
  299. const { doc, hasMode } = parseJsDoc(rawJsDoc(text, member))
  300. if (hasMode) {
  301. 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.`)
  302. }
  303. if (!doc) {
  304. violations.push(`${where} has no description prose. Say what the event records and what its payload means — the JSDoc becomes the catalog entry.`)
  305. }
  306. entries.push({ name, scope: name.split('/')[0] ?? name, payload, doc, source: src })
  307. }
  308. }
  309. }
  310. reportViolations(violations)
  311. return entries
  312. }
  313. /**
  314. * Parse the `SurfaceEventType` union — the surface-eligible subset of event
  315. * types — from source. Hard-errors when the alias is missing, declared more
  316. * than once, or contains a non-string-literal member: the badge derivation
  317. * relies on the union being a closed set of literal event names.
  318. * `scanRoot` defaults to the repo root; tests pass a fixture dir.
  319. */
  320. export function collectSurfaceEventTypes(scanRoot: string = root): string[] {
  321. const found: { names: string[]; source: string }[] = []
  322. for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).sort()) {
  323. const abs = resolve(scanRoot, rel)
  324. const text = readFileSync(abs, 'utf8')
  325. if (!text.includes('SurfaceEventType')) continue
  326. const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true)
  327. for (const stmt of sf.statements) {
  328. if (!ts.isTypeAliasDeclaration(stmt) || stmt.name.text !== 'SurfaceEventType') continue
  329. const src = pointer(rel, sf, stmt)
  330. const members = ts.isUnionTypeNode(stmt.type) ? [...stmt.type.types] : [stmt.type]
  331. const names: string[] = []
  332. for (const m of members) {
  333. if (ts.isLiteralTypeNode(m) && ts.isStringLiteral(m.literal)) names.push(m.literal.text)
  334. else throw new Error(`gen-persistence-catalog: SurfaceEventType (${src}) has a non-string-literal member; the badge derivation needs a closed literal union.`)
  335. }
  336. found.push({ names, source: src })
  337. }
  338. }
  339. const only = found[0]
  340. if (!only) throw new Error('gen-persistence-catalog: no SurfaceEventType union found under packages/*/*/src.')
  341. 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.`)
  342. return only.names
  343. }
  344. /**
  345. * Attach the surface/log-only badge to each event. Hard-errors when a
  346. * `SurfaceEventType` union member names no collected event — a stale union
  347. * member would otherwise silently badge nothing.
  348. */
  349. export function annotateSurface(events: LogEventEntry[], surfaceTypes: string[]): AnnotatedLogEventEntry[] {
  350. const names = new Set(events.map(e => e.name))
  351. const stale = surfaceTypes.filter(t => !names.has(t))
  352. if (stale.length > 0) {
  353. throw new Error(`gen-persistence-catalog: SurfaceEventType member(s) ${stale.map(t => `'${t}'`).join(', ')} name no declared log event (stale union member?).`)
  354. }
  355. const surface = new Set(surfaceTypes)
  356. return events.map(e => ({ ...e, surface: surface.has(e.name) }))
  357. }
  358. /** Render the cross-link "Types:" line for a payload, or '' if none apply. */
  359. function typeLinks(payload: string): string {
  360. const seen = new Set<string>()
  361. for (const name of Object.keys(LINK_MAP)) {
  362. if (new RegExp(`\\b${name}\\b`).test(payload)) seen.add(name)
  363. }
  364. if (seen.size === 0) return ''
  365. const links = [...seen].sort().map(n => `[${n}](core-data-structures/${LINK_MAP[n]})`)
  366. return `Types: ${links.join(' · ')}`
  367. }
  368. /** Render one log event entry. */
  369. function renderEvent(e: AnnotatedLogEventEntry): string[] {
  370. const out = [`#### \`${e.name}\` — ${e.surface ? 'surface' : 'log-only'}`, '']
  371. if (e.doc) out.push(e.doc, '')
  372. out.push('```' + FENCE, `'${e.name}': ${e.payload}`, '```', '')
  373. const links = typeLinks(e.payload)
  374. if (links) out.push(links, '')
  375. out.push(`Source: [\`${e.source}\`](../${e.source.split(':')[0]})`, '')
  376. return out
  377. }
  378. /** Render the full catalog (pure, deterministic given the collected inputs). */
  379. export function render(events: AnnotatedLogEventEntry[]): string {
  380. const lines: string[] = [
  381. '<!-- Generated by scripts/gen-persistence-catalog.ts — do not edit by hand.',
  382. ' Run `pnpm run gen-persistence-catalog` to regenerate. -->',
  383. '',
  384. '# Persistence Log Event Catalog',
  385. '',
  386. '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).',
  387. '',
  388. '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).',
  389. '',
  390. '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.',
  391. '',
  392. '## Events',
  393. '',
  394. ]
  395. const scopes = [...new Set(events.map(e => e.scope))].sort()
  396. for (const scope of scopes) {
  397. lines.push(`### \`${scope}/*\``, '')
  398. for (const e of events.filter(x => x.scope === scope).sort((a, b) => a.name.localeCompare(b.name))) {
  399. lines.push(...renderEvent(e))
  400. }
  401. }
  402. return lines.join('\n')
  403. }
  404. /** CLI entry: default writes the catalog, `--check` fails if the committed copy
  405. * is stale. Guarded behind an entry-point check so importing this module for
  406. * tests neither regenerates the committed file nor calls process.exit. */
  407. function main(): void {
  408. const content = render(annotateSurface(collectLogEvents(), collectSurfaceEventTypes()))
  409. if (process.argv.includes('--check')) {
  410. let committed: string | null = null
  411. try {
  412. committed = readFileSync(resolve(root, 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. if (committed === content) {
  420. console.log(`gen-persistence-catalog: ${OUT} is up to date.`)
  421. process.exit(0)
  422. }
  423. console.error(`gen-persistence-catalog: ${OUT} is stale. Run \`pnpm run gen-persistence-catalog\` and commit ${OUT}.`)
  424. process.exit(1)
  425. }
  426. writeFileSync(resolve(root, OUT), content)
  427. console.log(`gen-persistence-catalog: wrote ${OUT}.`)
  428. }
  429. // Run only when invoked as a script, not when imported by a test.
  430. if (process.argv[1] && import.meta.filename === resolve(process.argv[1])) {
  431. main()
  432. }