diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 5484d0efe2..3bc15253a5 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -1,13 +1,85 @@ -# Persistence Log Event Catalog +# Session Persistence Event Catalog -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). +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 in this repo — with source JSDoc, full payload declaration, surface badge, and declaration site. It complements [session.md](core-data-structures/session.md) (surface ordering and the `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). -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). +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 RFC](rfc/implemented/process/2026-07-04-persistence-log-catalog.md). -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. +The envelope declarations below compose each event's `type`, monotonic `seq`, epoch-ms `time`, `data`, 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](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. + +## Event envelope + +```ts persistence-catalog +/** The appendable event-type keys of {@link SessionEventMap}, plugin-merged extensions included. */ +export type SessionEventType = keyof SessionEventMap + +/** + * The subset of {@link SessionEventType} values whose events produce LLM + * messages and are eligible to appear on the ordered surface. Only these + * event types may carry {@link SurfaceOp} and {@link SessionEvent.sourceEventSeqs}. + */ +export type SurfaceEventType = + | 'user/message' + | 'assistant/message' + | 'tool/result' + | 'context/message' + | 'steering/message' + +/** + * How a session event entered the ordered surface. Only valid on + * {@link SurfaceEventType} events. + * + * - `'append'`: added to the tail — normal path for user/assistant/tool/context + * messages. + * - `{ op: 'replace', start, end }`: replaces surface nodes from `start` + * (inclusive) through `end` (inclusive) with this node. Both must exist as + * surface nodes in the current surface. `start === end` replaces a single + * node. The node's {@link SessionEvent.sourceEventSeqs} must include every + * shadowed surface node. Used by compaction and possible other manipulations. + */ +export type SurfaceOp = + | 'append' + | { op: 'replace'; start: number; end: number } + +/** + * One immutable entry in the session log. + * + * A proper discriminated union over `type` (not independent `type`/`data` + * unions), so `switch (event.type)` narrows `event.data` without casts. + * + * The {@link sourceEventSeqs} and {@link surfaceOp} fields are conditional: + * they only exist on {@link SurfaceEventType} variants (`user/message`, + * `assistant/message`, `tool/result`, `context/message`, `steering/message`). + * Non-surface events (boundary markers, chunks, usage, errors) never carry + * surface metadata — the compiler enforces this at `Session.append()` + * call sites. + */ +export type SessionEvent = { + [K in SessionEventType]: { + type: K + /** Monotonic sequence number within the session. */ + seq: number + /** Unix epoch milliseconds. */ + time: number + data: SessionEventMap[K] + } & (K extends SurfaceEventType ? { + /** + * Seq numbers of events that are provenance sources of this event + * (e.g. the `assistant/chunk` seqs that built an `assistant/message`, + * or the surface nodes shadowed by a compaction replace node). An + * `assistant/message` may carry a present empty array for a known empty + * provider stream; omission means unrecorded provenance. + */ + sourceEventSeqs?: number[] + /** How this event entered the surface; absent for non-surface events. */ + surfaceOp?: SurfaceOp + } : object) +}[T] +``` + +Sources: [`packages/core/session/src/types.ts:255`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:262`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:292`](../packages/core/session/src/types.ts) · [`packages/core/session/src/types.ts:324`](../packages/core/session/src/types.ts) ## Events @@ -15,10 +87,21 @@ The on-disk envelope around every payload is `SessionEvent` — `type`, monotoni #### `approval/asked` — log-only -An approval question was put to the answerer chain — log-only audit (like `hook/*`; NOT a surface event, carries no `surfaceOp`). `id` pairs it with the `approval/decided` that always follows; `toolName` is the tool the question is about, `callId` the exact tool call when the asker had one, `reason` the asker's human-readable explanation (e.g. a hook's permission-decision reason). - ```ts persistence-catalog -'approval/asked': { id: ApprovalRequestId; toolName: string; callId?: CallId; reason?: string } +/** + * An approval question was put to the answerer chain — log-only audit + * (like `hook/*`; NOT a surface event, carries no `surfaceOp`). `id` pairs + * it with the `approval/decided` that always follows; `toolName` is the + * tool the question is about, `callId` the exact tool call when the asker + * had one, `reason` the asker's human-readable explanation (e.g. a hook's + * permission-decision reason). + */ +'approval/asked': { + id: ApprovalRequestId + toolName: string + callId?: CallId + reason?: string +} ``` Types: [CallId](core-data-structures/core.md) @@ -27,19 +110,31 @@ Source: [`packages/ui/user-approval/src/index.ts:45`](../packages/ui/user-approv #### `approval/decided` — log-only -The outcome of a prior `approval/asked` (same `id`) — log-only audit. Exactly one per ask, appended when the outcome is known: a decision, a cancellation, or the fail-closed `'unavailable'`. - ```ts persistence-catalog -'approval/decided': { id: ApprovalRequestId; outcome: ApprovalOutcome } +/** + * The outcome of a prior `approval/asked` (same `id`) — log-only audit. + * Exactly one per ask, appended when the outcome is known: a decision, a + * cancellation, or the fail-closed `'unavailable'`. + */ +'approval/decided': { + id: ApprovalRequestId + outcome: ApprovalOutcome +} ``` Source: [`packages/ui/user-approval/src/index.ts:56`](../packages/ui/user-approval/src/index.ts) #### `approval/policy` — log-only -The session's approval policy was switched — log-only, durable, replayable, never in the model transcript (the model learns the policy from the prompt section and the narrator's notices). The LAST such event is the session's override (effectiveApprovalPolicy); who asked for it is derivable from position (an event after the log's last `request/header` was a runtime switch by the user). - ```ts persistence-catalog +/** + * The session's approval policy was switched — log-only, durable, + * replayable, never in the model transcript (the model learns the policy + * from the prompt section and the narrator's notices). The LAST such + * event is the session's override ({@link effectiveApprovalPolicy}); + * who asked for it is derivable from position (an event after the log's + * last `request/header` was a runtime switch by the user). + */ 'approval/policy': { policy: ApprovalPolicy } ``` @@ -49,9 +144,8 @@ Source: [`packages/ui/user-approval/src/index.ts:68`](../packages/ui/user-approv #### `assistant/chunk` — log-only -Raw stream chunk — token-level replay fidelity. - ```ts persistence-catalog +/** Raw stream chunk — token-level replay fidelity. */ 'assistant/chunk': { turn: number; step: number; chunk: StreamChunk } ``` @@ -61,9 +155,13 @@ Source: [`packages/core/session/src/types.ts:219`](../packages/core/session/src/ #### `assistant/message` — surface -Assembled assistant message for one step (derived history uses this). Carries the step's `usage` when the adapter reported token accounting, so the model output and its accounting travel together (there is no separate usage record). `usage` is absent when the adapter reported none. - ```ts persistence-catalog +/** + * Assembled assistant message for one step (derived history uses this). + * Carries the step's `usage` when the adapter reported token accounting, so + * the model output and its accounting travel together (there is no separate + * usage record). `usage` is absent when the adapter reported none. + */ 'assistant/message': { turn: number; step: number; content: ContentBlock[]; provenance: AssistantProvenance; usage?: TokenUsage } ``` @@ -75,9 +173,12 @@ Source: [`packages/core/session/src/types.ts:226`](../packages/core/session/src/ #### `bash/sandbox-mode` — log-only -Durable log-only sandbox-mode override; never a surface event or model message. Execution and ACP option reporting fold the latest event through effectiveSandboxMode without adding a prompt notice. - ```ts persistence-catalog +/** + * Durable log-only sandbox-mode override; never a surface event or model + * message. Execution and ACP option reporting fold the latest event through + * {@link effectiveSandboxMode} without adding a prompt notice. + */ 'bash/sandbox-mode': { mode: SandboxMode } ``` @@ -87,9 +188,8 @@ Source: [`packages/bash/bash/src/session-mode.ts:20`](../packages/bash/bash/src/ #### `compact/end` — log-only -Marks the end of a compaction — log-only, releases the lock. `error` set if summarization failed. - ```ts persistence-catalog +/** Marks the end of a compaction — log-only, releases the lock. `error` set if summarization failed. */ 'compact/end': { turn: number; error?: string } ``` @@ -97,9 +197,8 @@ Source: [`packages/compact/compact/src/types.ts:40`](../packages/compact/compact #### `compact/start` — log-only -Marks the start of a compaction — log-only, holds the lock until `compact/end`. - ```ts persistence-catalog +/** Marks the start of a compaction — log-only, holds the lock until `compact/end`. */ 'compact/start': { turn: number } ``` @@ -107,10 +206,30 @@ Source: [`packages/compact/compact/src/types.ts:15`](../packages/compact/compact #### `compact/summary` — log-only -Provenance record of a completed summarization — log-only, no surfaceOp. The summary content is in `data.summary`; the actual surface replacement is performed by a subsequent `user/message` event that shadows the compacted range. - ```ts persistence-catalog -'compact/summary': { summary: ContentBlock[]; shadowedRange: { start: number; end: number }; shadowedSeqs: number[]; shadowedTokenCount: number; provider: string; model: string; maxTokens?: number } +/** + * Provenance record of a completed summarization — log-only, no surfaceOp. + * The summary content is in `data.summary`; the actual surface replacement + * is performed by a subsequent `user/message` event that shadows the + * compacted range. + */ +'compact/summary': { + summary: ContentBlock[] + shadowedRange: { start: number; end: number } + shadowedSeqs: number[] + shadowedTokenCount: number + /** The provider route that wrote the summary. */ + provider: string + /** + * The model that wrote the summary — the summarize call's envelope, + * reported by the backend that made the call, logged so the one-shot + * request is reconstructable from log + code and "which model wrote + * this summary" has a durable answer (the reconstructability RFC). + */ + model: string + /** The generation cap the summarize call sent, when one applied. */ + maxTokens?: number +} ``` Types: [ContentBlock](core-data-structures/core.md) @@ -121,10 +240,20 @@ Source: [`packages/compact/compact/src/types.ts:22`](../packages/compact/compact #### `context/message` — surface -In-session context injection (file-change notices, subdir AGENTS.md, skill content, cron notifications, …). Rendered into the derived history as synthetic context — NOT a user prompt. `envelope: 'raw'` lets a caller own the complete model-facing frame; `meta` is durable JSON state omitted from the model projection. - ```ts persistence-catalog -'context/message': { content: ContentBlock[]; source: MessageSource; envelope?: ContextEnvelope; meta?: JsonValue } +/** + * In-session context injection (file-change notices, subdir AGENTS.md, + * skill content, cron notifications, …). Rendered into the derived history + * as synthetic context — NOT a user prompt. `envelope: 'raw'` lets a caller + * own the complete model-facing frame; `meta` is durable JSON state omitted + * from the model projection. + */ +'context/message': { + content: ContentBlock[] + source: MessageSource + envelope?: ContextEnvelope + meta?: JsonValue +} ``` Types: [ContentBlock](core-data-structures/core.md) · [MessageSource](core-data-structures/core.md) @@ -135,20 +264,44 @@ Source: [`packages/core/session/src/types.ts:212`](../packages/core/session/src/ #### `hook/invoked` — log-only -A hook command was invoked at a hook point — log-only provenance (like `compact/*`; NOT a SurfaceEventType, carries no `surfaceOp`). `dialect` is the bridge that ran it (`claude`/`codex`), `point` the hook point (`PreToolUse`, `Stop`, …), `matcher` the matcher-group pattern that selected it (absent for match-all), `handlerId` a stable id for the command (so an invoked/result pair correlates). `turn` is the open turn the invocation lives inside. - ```ts persistence-catalog -'hook/invoked': { turn: number; point: string; dialect: HookDialect; matcher?: string; handlerId: string } +/** + * A hook command was invoked at a hook point — log-only provenance (like + * `compact/*`; NOT a {@link SurfaceEventType}, carries no `surfaceOp`). + * `dialect` is the bridge that ran it (`claude`/`codex`), `point` + * the hook point (`PreToolUse`, `Stop`, …), `matcher` the matcher-group + * pattern that selected it (absent for match-all), `handlerId` a stable id + * for the command (so an invoked/result pair correlates). `turn` is the open + * turn the invocation lives inside. + */ +'hook/invoked': { + turn: number + point: string + dialect: HookDialect + matcher?: string + handlerId: string +} ``` Source: [`packages/hooks/hook-protocol/src/types.ts:19`](../packages/hooks/hook-protocol/src/types.ts) #### `hook/result` — log-only -Log-only outcome paired to `hook/invoked` by `handlerId`. Decision is the parsed permission result, `stop` for `continue:false`, or `pass`; exit code may be absent, stderr is bounded, and duration is wall-clock runtime. - ```ts persistence-catalog -'hook/result': { turn: number; point: string; handlerId: string; decision: string; exitCode?: number; stderrSummary?: string; durationMs: number } +/** + * Log-only outcome paired to `hook/invoked` by `handlerId`. Decision is the + * parsed permission result, `stop` for `continue:false`, or `pass`; exit code + * may be absent, stderr is bounded, and duration is wall-clock runtime. + */ +'hook/result': { + turn: number + point: string + handlerId: string + decision: string + exitCode?: number + stderrSummary?: string + durationMs: number +} ``` Source: [`packages/hooks/hook-protocol/src/types.ts:31`](../packages/hooks/hook-protocol/src/types.ts) @@ -157,9 +310,13 @@ Source: [`packages/hooks/hook-protocol/src/types.ts:31`](../packages/hooks/hook- #### `permission/preset` — log-only -Records the selected preset as durable, log-only user intent. The knob events follow in the same turn and control execution; this event stays out of the model transcript and lets effectivePermissionPreset preserve a selection when bundles match. - ```ts persistence-catalog +/** + * Records the selected preset as durable, log-only user intent. The knob + * events follow in the same turn and control execution; this event stays + * out of the model transcript and lets {@link effectivePermissionPreset} + * preserve a selection when bundles match. + */ 'permission/preset': { preset: string } ``` @@ -169,9 +326,11 @@ Source: [`packages/ui/permission/src/index.ts:33`](../packages/ui/permission/src #### `prompt/blocked` — log-only -Durable record of a prompt veto and its reason. It is log-only: the blocked prompt never enters the model-visible surface, including in a mixed batch. - ```ts persistence-catalog +/** + * Durable record of a prompt veto and its reason. It is log-only: the blocked + * prompt never enters the model-visible surface, including in a mixed batch. + */ 'prompt/blocked': { content: ContentBlock[]; source: MessageSource; reason: string } ``` @@ -183,9 +342,11 @@ Source: [`packages/core/session/src/types.ts:204`](../packages/core/session/src/ #### `request/header` — log-only -Full header for the next request, appended inside its step before dispatch. It is log-only; the latest snapshot reconstructs the request header. - ```ts persistence-catalog +/** + * Full header for the next request, appended inside its step before dispatch. + * It is log-only; the latest snapshot reconstructs the request header. + */ 'request/header': { header: EpochHeader; reason: RequestHeaderReason } ``` @@ -195,9 +356,8 @@ Source: [`packages/core/session/src/types.ts:251`](../packages/core/session/src/ #### `steering/message` — surface -Steering content injected between steps of a running turn. - ```ts persistence-catalog +/** Steering content injected between steps of a running turn. */ 'steering/message': { turn: number; content: ContentBlock[]; source: MessageSource } ``` @@ -209,9 +369,8 @@ Source: [`packages/core/session/src/types.ts:244`](../packages/core/session/src/ #### `step/end` — log-only -Closes step `step` of turn `turn`. - ```ts persistence-catalog +/** Closes step `step` of turn `turn`. */ 'step/end': { turn: number; step: number } ``` @@ -219,9 +378,8 @@ Source: [`packages/core/session/src/types.ts:197`](../packages/core/session/src/ #### `step/start` — log-only -Opens step `step` of turn `turn` — one model call plus the tool executions it requested. - ```ts persistence-catalog +/** Opens step `step` of turn `turn` — one model call plus the tool executions it requested. */ 'step/start': { turn: number; step: number } ``` @@ -231,9 +389,8 @@ Source: [`packages/core/session/src/types.ts:195`](../packages/core/session/src/ #### `todo/write` — log-only -Whole-list snapshot; latest write wins on replay. Log-only UI state; never derived history. - ```ts persistence-catalog +/** Whole-list snapshot; latest write wins on replay. Log-only UI state; never derived history. */ 'todo/write': { todos: TodoItem[] } ``` @@ -245,9 +402,12 @@ Source: [`packages/core/session/src/types.ts:246`](../packages/core/session/src/ #### `tool/call` — log-only -The model requested one tool invocation: `name` with the raw `arguments` JSON string exactly as the model produced it (unparsed). `callId` pairs the call with its `tool/result`. - ```ts persistence-catalog +/** + * The model requested one tool invocation: `name` with the raw `arguments` + * JSON string exactly as the model produced it (unparsed). `callId` pairs the + * call with its `tool/result`. + */ 'tool/call': { turn: number; step: number; callId: CallId; name: string; arguments: string } ``` @@ -257,9 +417,22 @@ Source: [`packages/core/session/src/types.ts:232`](../packages/core/session/src/ #### `tool/code-dispatch` — log-only -One bridged sub-dispatch from a `run_code` program: the parent `run_code` call id, the deterministic sub-call id (`:code:`), the tool `name` with its JSON-normalized `arguments` — the exact value dispatched, normalized BEFORE dispatch, so this append can never fail on payload shape — whether the sub-call errored, and a bounded `resultSummary` of its model-facing text. Before bounding, occurrences of a non-root session workspace path are normalized to `.` so host-specific absolute path lengths cannot change the summary. Log-only: `deriveMessages()` ignores it, so sub-calls never re-enter model context; persistence and UIs get every call. Appended inside the parent `run_code`'s execution (the bridge drains its queue before returning), so the turn-enclosure invariant holds by construction. - ```ts persistence-catalog +/** + * One bridged sub-dispatch from a `run_code` program: the parent + * `run_code` call id, the deterministic sub-call id + * (`:code:`), the tool `name` with its JSON-normalized + * `arguments` — the exact value dispatched, normalized BEFORE dispatch, + * so this append can never fail on payload shape — whether the sub-call + * errored, and a bounded `resultSummary` of its model-facing text. Before + * bounding, occurrences of a non-root session workspace path are + * normalized to `.` so host-specific absolute path lengths cannot change + * the summary. + * Log-only: `deriveMessages()` ignores it, so sub-calls never re-enter + * model context; persistence and UIs get every call. Appended inside the + * parent `run_code`'s execution (the bridge drains its queue before + * returning), so the turn-enclosure invariant holds by construction. + */ 'tool/code-dispatch': { parentCallId: CallId; subCallId: CallId; name: string; arguments: unknown; isError: boolean; resultSummary: string } ``` @@ -269,9 +442,16 @@ Source: [`packages/core/tools/src/code-mode.ts:34`](../packages/core/tools/src/c #### `tool/result` — surface -A completed tool call's model-facing result, plus an optional tool-private `meta` presentation payload. `meta` is opaque to the core (`unknown` — the producing tool owns its shape and reads it back in `presentResult`) but MUST be JSON-serializable: `Session.append` runtime-validates all event data with `isJsonValue`, so a non-serializable `meta` is rejected at the source, and the durable log reproduces the identical card on replay. Absent unless the tool attaches one (e.g. `dsh-tool-fs` carries its result-time contextual diff here). - ```ts persistence-catalog +/** + * A completed tool call's model-facing result, plus an optional tool-private + * `meta` presentation payload. `meta` is opaque to the core (`unknown` — the + * producing tool owns its shape and reads it back in `presentResult`) but MUST + * be JSON-serializable: `Session.append` runtime-validates all event data with + * `isJsonValue`, so a non-serializable `meta` is rejected at the source, and the + * durable log reproduces the identical card on replay. Absent unless the tool + * attaches one (e.g. `dsh-tool-fs` carries its result-time contextual diff here). + */ 'tool/result': { turn: number; step: number; callId: CallId; content: ContentBlock[]; isError: boolean; error?: { name: string; code: string }; meta?: unknown } ``` @@ -283,9 +463,12 @@ Source: [`packages/core/session/src/types.ts:242`](../packages/core/session/src/ #### `turn/end` — log-only -Closes turn `turn` with the TurnEndReason that ended it. The loop fires the awaited `session/flush` checkpoint at every turn end, so the turn boundary is also the durable-commit boundary. - ```ts persistence-catalog +/** + * Closes turn `turn` with the {@link TurnEndReason} that ended it. The loop + * fires the awaited `session/flush` checkpoint at every turn end, so the turn + * boundary is also the durable-commit boundary. + */ 'turn/end': { turn: number; reason: TurnEndReason } ``` @@ -295,9 +478,13 @@ Source: [`packages/core/session/src/types.ts:193`](../packages/core/session/src/ #### `turn/start` — log-only -Opens turn `turn`. `trigger` records what started it — a drained message batch or an idle-time injection. The turn is the durability/replay boundary: every event sits between a `turn/start` and its matching `turn/end` (the turn-enclosure invariant). - ```ts persistence-catalog +/** + * Opens turn `turn`. `trigger` records what started it — a drained message + * batch or an idle-time injection. The turn is the durability/replay + * boundary: every event sits between a `turn/start` and its matching + * `turn/end` (the turn-enclosure invariant). + */ 'turn/start': { turn: number; trigger: TurnTrigger } ``` @@ -309,9 +496,8 @@ Source: [`packages/core/session/src/types.ts:187`](../packages/core/session/src/ #### `user/message` — surface -A user-visible prompt (queued message drained at turn start). - ```ts persistence-catalog +/** A user-visible prompt (queued message drained at turn start). */ 'user/message': { content: ContentBlock[]; source: MessageSource } ``` diff --git a/docs/rfc/implemented/process/2026-07-04-persistence-log-catalog.md b/docs/rfc/implemented/process/2026-07-04-persistence-log-catalog.md index 0de6255322..70a6d60c1a 100644 --- a/docs/rfc/implemented/process/2026-07-04-persistence-log-catalog.md +++ b/docs/rfc/implemented/process/2026-07-04-persistence-log-catalog.md @@ -4,19 +4,19 @@ Status: implemented ## Problem -`SessionEventMap` is the on-disk vocabulary, but its declarations are split across the owning session package and declaration merges. The generated persistence catalog is the single reference for every event and payload; hand-maintained tables drift and are removed. These records are not Cordis events—observers receive them through the single `session/event` bus event—so the Cordis catalog cannot cover them. The generator discovers all declarations and the doc-sync freshness gate rejects omissions or stale output. +`SessionEventMap` is the on-disk vocabulary, but its declarations are split across the owning session package and declaration merges. The generated persistence catalog is the single reference for every event, its complete payload declaration and source JSDoc, and the shared `SessionEvent` envelope; hand-maintained tables drift and are removed. These records are not Cordis events—observers receive them through the single `session/event` bus event—so the Cordis catalog cannot cover them. The generator discovers all declarations and the doc-sync freshness gate rejects omissions or stale output. ## Decision Generate `docs/persistence-catalog.md` from source, with a freshness gate, as the fourth reference surface: the *records* a persisted session log can contain, complementing the cordis catalog (wiring), core-data-structures (vocabulary), and the tool catalog (tools). -`gen-persistence-catalog.ts` scans every owning and declaration-merged `SessionEventMap` with the TypeScript AST. It renders source JSDoc, payload type, derived surface badge, reference links, and source location. The doc-sync freshness check rejects a vocabulary change whose catalog was not regenerated. +`gen-persistence-catalog.ts` scans every owning and declaration-merged `SessionEventMap` with the TypeScript AST. It renders each member from its leading JSDoc through the complete payload type, retaining nested property comments and removing only its containing indentation, and also pastes the owning `SessionEventType`, `SurfaceEventType`, `SurfaceOp`, and `SessionEvent` declarations that compose the persisted envelope. Derived surface badges, reference links, and source locations remain outside the declaration blocks. The doc-sync freshness check rejects a vocabulary or envelope change whose catalog was not regenerated. Specific choices: -- **JSDoc completeness, enforced.** Every member must carry description prose — the JSDoc becomes the catalog entry, the same forcing function the cordis catalog applies to bus events. An `@mode` tag on a member is a hard error: dispatch modes belong to cordis bus events, and a log event has none — the tag would misread as "this fires on the bus with mode X". Violations aggregate into one error listing every offender. +- **JSDoc completeness, enforced.** Every member and rendered envelope type must carry description prose, and the full source JSDoc stays attached to its declaration in the catalog. An `@mode` tag is a hard error: dispatch modes belong to cordis bus events, and persisted records have none. Violations aggregate into one error listing every offender. - **The surface badge is derived, not hand-listed.** `SurfaceEventType` — the subset that produces LLM messages and may carry `surfaceOp` — is parsed from its union declaration in the owning package; a union member naming no declared event is a hard error (a stale union member would otherwise silently badge nothing). Everything else renders **log-only**. -- **A dedicated fence.** Payload blocks use a ` ```ts persistence-catalog ` info string that `doc-typecheck` recognizes and skips, excluded from the opt-out ratio — the same treatment as `ts cordis-catalog` (a bare payload fragment is not standalone-compilable). +- **A dedicated fence.** Declaration blocks use a ` ```ts persistence-catalog ` info string that `doc-typecheck` recognizes and skips, excluded from the opt-out ratio — the same treatment as `ts cordis-catalog` (the declarations reference types from their owning modules and are not standalone-compilable). - **Repo scope.** The catalog enumerates the packages in this repo, matching the siblings' packages-only scope; a downstream plugin can merge further event types, which are outside the catalog by construction. The walk defends its own assumptions with hard errors: the owning top-level `interface SessionEventMap` must be the single exported declaration in `@deepseek-ai/dsh-session` (an unrelated, local, or duplicate same-named interface cannot be catalogued as the on-disk vocabulary), no declaration may carry `extends` (inherited keys would join `keyof SessionEventMap` without a catalog row), every member must be a property signature with an explicit payload type (a method-form member would join `keyof` yet slip past a silent walk), and a duplicate member across declarations fails. This supersedes the hand-copies: the session.md `hook/*` table, the compact README's event table, the hook-protocol README's payload bullets, and the session README's name-list now link the catalog instead of restating payloads (the surrounding semantics prose stays where it was). The two stray `@mode emit` tags on the hook-protocol merge members are removed — the new gate rejects them as the category error they were. @@ -28,7 +28,7 @@ This supersedes the hand-copies: the session.md `hook/*` table, the compact READ ## Consequences -- The catalog cannot drift: a vocabulary change the committed file doesn't reflect fails `verify-persistence-catalog` in the pre-push hook and CI, and a new merged event with no JSDoc fails the generator outright — a plugin can no longer add an undocumented on-disk record type. -- Event prose has a single home, the JSDoc at the declaration; thin JSDoc yields a thin catalog entry, pressuring authors to document at the source. +- The catalog cannot drift: a vocabulary or envelope change the committed file doesn't reflect fails `verify-persistence-catalog` in the pre-push hook and CI, and a new merged event with no JSDoc fails the generator outright — a plugin can no longer add an undocumented on-disk record type. +- Event prose has a single home, the JSDoc at the declaration; the catalog preserves that JSDoc and any nested field comments without flattening or paraphrasing them. - The `SurfaceEventType` union is now structurally load-bearing for docs: renaming an event without updating the union (or vice versa) fails the generator, not just the compiler. - The badge derivation assumes the union stays a closed set of string literals with exactly one owner; a refactor away from that shape must update the generator in the same change. diff --git a/packages/core/session/tests/gen-persistence-catalog.spec.ts b/packages/core/session/tests/gen-persistence-catalog.spec.ts index cca9cbfa61..9f18e75bbe 100644 --- a/packages/core/session/tests/gen-persistence-catalog.spec.ts +++ b/packages/core/session/tests/gen-persistence-catalog.spec.ts @@ -9,6 +9,7 @@ import { join } from 'node:path' import { afterEach, describe, expect, it } from 'vitest' import { annotateSurface, + collectEventEnvelopeTypes, collectLogEvents, collectSurfaceEventTypes, render, @@ -56,6 +57,7 @@ describe('gen-persistence-catalog collectLogEvents', () => { scope: 'fix', doc: 'A thing was recorded.', payload: '{ turn: number }', + declaration: '/** A thing was recorded. */\n\'fix/happened\': { turn: number }', source: 'packages/core/fix/src/types.ts:3', }) }) @@ -102,10 +104,13 @@ describe('gen-persistence-catalog collectLogEvents', () => { it('collapses a newline-separated multi-line payload to a valid one-line fragment', () => { const events = collectLogEvents(make({ 'packages/group/fix/src/types.ts': merge( - ' /** Wide payload. */\n \'fix/wide\': {\n alpha: string[]\n range: { start: number; end: number }\n count: number\n }', + ' /** Wide payload. */\n \'fix/wide\': {\n /** Alpha values. */\n alpha: string[]\n range: { start: number; end: number }\n count: number\n }', ), })) expect(events[0]?.payload).toBe('{ alpha: string[]; range: { start: number; end: number }; count: number }') + expect(events[0]?.declaration).toBe( + '/** Wide payload. */\n\'fix/wide\': {\n /** Alpha values. */\n alpha: string[]\n range: { start: number; end: number }\n count: number\n}', + ) }) it('hard-errors on a member with no description prose', () => { @@ -158,6 +163,59 @@ describe('gen-persistence-catalog collectLogEvents', () => { }) }) +describe('gen-persistence-catalog collectEventEnvelopeTypes', () => { + const declarations = `/** Event keys. */ +export type SessionEventType = keyof SessionEventMap +/** Surface-producing event keys. */ +export type SurfaceEventType = 'fix/message' +/** Surface placement. */ +export type SurfaceOp = 'append' +/** One persisted event. */ +export type SessionEvent = { type: T } +` + + it('extracts the envelope declarations with their complete JSDoc in canonical order', () => { + const entries = collectEventEnvelopeTypes(make({ + 'packages/core/fix/package.json': OWNER_MANIFEST, + 'packages/core/fix/src/types.ts': declarations, + })) + expect(entries.map(entry => entry.name)).toEqual([ + 'SessionEventType', + 'SurfaceEventType', + 'SurfaceOp', + 'SessionEvent', + ]) + expect(entries[3]).toMatchObject({ + declaration: '/** One persisted event. */\nexport type SessionEvent = { type: T }', + source: 'packages/core/fix/src/types.ts:8', + }) + }) + + it('hard-errors when an envelope declaration is missing', () => { + expect(() => collectEventEnvelopeTypes(make({ + 'packages/core/fix/package.json': OWNER_MANIFEST, + 'packages/core/fix/src/types.ts': declarations.replace('/** Surface placement. */\nexport type SurfaceOp = \'append\'\n', ''), + }))).toThrow(/missing event-envelope declaration\(s\): SurfaceOp/) + }) + + it('hard-errors on duplicate, unexported, undocumented, or mistagged envelope declarations', () => { + const violations = new RegExp([ + '4 JSDoc completeness violation\\(s\\)', + '[\\s\\S]*not exported', + '[\\s\\S]*@mode tag', + '[\\s\\S]*SurfaceOp.*no description prose', + '[\\s\\S]*SessionEvent.*already declared', + ].join('')) + expect(() => collectEventEnvelopeTypes(make({ + 'packages/core/fix/package.json': OWNER_MANIFEST, + 'packages/core/fix/src/types.ts': declarations + .replace('/** Event keys. */\nexport type SessionEventType', '/** Event keys.\n * @mode emit\n */\ntype SessionEventType') + .replace('/** Surface placement. */\n', '') + + '/** Duplicate event. */\nexport type SessionEvent = { type: never }\n', + }))).toThrow(violations) + }) +}) + describe('gen-persistence-catalog collectSurfaceEventTypes', () => { it('parses the literal union', () => { const types = collectSurfaceEventTypes(make({ @@ -192,9 +250,21 @@ describe('gen-persistence-catalog annotateSurface + render', () => { scope: name.split('/')[0] ?? name, payload: '{ turn: number }', doc: `Records ${name}.`, + declaration: `/** Records ${name}. */\n'${name}': { turn: number }`, source: 'packages/core/fix/src/types.ts:3', }) + const envelopeTypes = [ + 'SessionEventType', + 'SurfaceEventType', + 'SurfaceOp', + 'SessionEvent', + ].map(name => ({ + name: name as 'SessionEventType' | 'SurfaceEventType' | 'SurfaceOp' | 'SessionEvent', + declaration: `/** ${name}. */\nexport type ${name} = never`, + source: 'packages/core/fix/src/types.ts:1', + })) + it('badges union members surface and everything else log-only', () => { const annotated = annotateSurface([entry('fix/message'), entry('fix/marker')], ['fix/message']) expect(annotated.map(e => [e.name, e.surface])).toEqual([['fix/message', true], ['fix/marker', false]]) @@ -205,11 +275,13 @@ describe('gen-persistence-catalog annotateSurface + render', () => { .toThrow(/'fix\/ghost' name no declared log event/) }) - it('renders badges, payload fences, and the generated-file header', () => { - const out = render(annotateSurface([entry('fix/message'), entry('fix/marker')], ['fix/message'])) + it('renders badges, declaration fences, and the generated-file header', () => { + const out = render(annotateSurface([entry('fix/message'), entry('fix/marker')], ['fix/message']), envelopeTypes) expect(out).toContain('Generated by scripts/gen-persistence-catalog.ts') + expect(out).toContain('# Session Persistence Event Catalog') + expect(out).toContain('```ts persistence-catalog\n/** SessionEventType. */\nexport type SessionEventType = never') expect(out).toContain('#### `fix/message` — surface') expect(out).toContain('#### `fix/marker` — log-only') - expect(out).toContain('```ts persistence-catalog\n\'fix/marker\': { turn: number }\n```') + expect(out).toContain('```ts persistence-catalog\n/** Records fix/marker. */\n\'fix/marker\': { turn: number }\n```') }) }) diff --git a/scripts/gen-persistence-catalog.ts b/scripts/gen-persistence-catalog.ts index 9469081607..8762b8529e 100644 --- a/scripts/gen-persistence-catalog.ts +++ b/scripts/gen-persistence-catalog.ts @@ -1,7 +1,7 @@ /** * Generate `docs/persistence-catalog.md` from every `SessionEventMap` merge and - * the owning `SurfaceEventType` union. This is the durable-record vocabulary, - * not the live Cordis bus. Event declarations must be unique, explicitly typed, + * the owning event-envelope types. This is the durable-record vocabulary, not + * the live Cordis bus. Event declarations must be unique, explicitly typed, * documented, inheritance-free, and free of Cordis-only `@mode` tags; every * surface-union member must resolve to one. `--check` verifies the artifact. */ @@ -14,13 +14,23 @@ import { parseJsDoc, pointer, rawJsDoc, reportViolations } from './jsdoc.ts' const root = resolve(import.meta.dirname, '..') const OUT = 'docs/persistence-catalog.md' -/** The fenced-block info string for generated payload blocks (skipped by - * doc-typecheck, since a bare payload fragment is not standalone-compilable). */ +/** The fenced-block info string for generated declaration blocks (skipped by + * doc-typecheck, since their imported types are not standalone-compilable). */ const FENCE = 'ts persistence-catalog' /** The package whose module id plugin merges augment (`declare module '…'`). */ const SESSION_MODULE = '@deepseek-ai/dsh-session' +/** Event-envelope declarations rendered before the per-event vocabulary. */ +const EVENT_ENVELOPE_TYPE_NAMES = [ + 'SessionEventType', + 'SurfaceEventType', + 'SurfaceOp', + 'SessionEvent', +] as const + +type EventEnvelopeTypeName = typeof EVENT_ENVELOPE_TYPE_NAMES[number] + /** Primary core-data-structures page for linked payload types. */ const LINK_MAP: Record = { CallId: 'core.md', @@ -41,6 +51,8 @@ export interface LogEventEntry { scope: string /** Payload type text (the member's type annotation, whitespace-collapsed). */ payload: string + /** Source member declaration and complete JSDoc, dedented from its container. */ + declaration: string /** Description prose (the member's JSDoc), one line per paragraph. */ doc: string /** Source pointer `packages/…/file.ts:line` of the declaration. */ @@ -53,6 +65,16 @@ export interface AnnotatedLogEventEntry extends LogEventEntry { surface: boolean } +/** One owning event-envelope declaration pasted into the generated catalog. */ +export interface EventEnvelopeTypeEntry { + /** Exported declaration name. */ + name: EventEnvelopeTypeName + /** Verbatim type declaration, including its complete leading JSDoc. */ + declaration: string + /** Source pointer `packages/…/file.ts:line` of the declaration. */ + source: string +} + const printer = ts.createPrinter({ removeComments: true }) /** @@ -67,6 +89,24 @@ function payloadText(type: ts.TypeNode, sf: ts.SourceFile): string { .trim() } +/** + * Copy a declaration from its leading JSDoc through its closing token while + * removing only the indentation imposed by its containing interface/module. + */ +function declarationText(text: string, sf: ts.SourceFile, node: ts.Node): string { + const raw = rawJsDoc(text, node) + const nodeStart = node.getStart(sf) + const start = raw ? text.lastIndexOf(raw, nodeStart) : nodeStart + const { line } = sf.getLineAndCharacterOfPosition(start) + const lineStart = sf.getPositionOfLineAndCharacter(line, 0) + const indent = text.slice(lineStart, start) + return text.slice(lineStart, node.end) + .split('\n') + .map(lineText => lineText.startsWith(indent) ? lineText.slice(indent.length) : lineText) + .join('\n') + .trimEnd() +} + /** * Every `interface SessionEventMap` declaration in a source file: the owning * top-level declaration (in `@deepseek-ai/dsh-session`) and any declaration @@ -177,7 +217,8 @@ export function collectLogEvents(scanRoot: string = root): LogEventEntry[] { if (!doc) { violations.push(`${where} has no description prose. Say what the event records and what its payload means — the JSDoc becomes the catalog entry.`) } - entries.push({ name, scope: name.split('/')[0] ?? name, payload, doc, source: src }) + const declaration = declarationText(text, sf, member) + entries.push({ name, scope: name.split('/')[0] ?? name, payload, declaration, doc, source: src }) } } } @@ -185,6 +226,51 @@ export function collectLogEvents(scanRoot: string = root): LogEventEntry[] { return entries } +/** + * Collect the exported declarations that compose the persisted event envelope, + * preserving their source JSDoc and declaration text. + */ +export function collectEventEnvelopeTypes(scanRoot: string = root): EventEnvelopeTypeEntry[] { + const found = new Map() + const violations: string[] = [] + const wanted = new Set(EVENT_ENVELOPE_TYPE_NAMES) + for (const rel of globSync('packages/*/*/src/**/*.ts', { cwd: scanRoot }).map(s => s.split(sep).join('/')).sort()) { + const abs = resolve(scanRoot, rel) + const text = readFileSync(abs, 'utf8') + if (!EVENT_ENVELOPE_TYPE_NAMES.some(name => text.includes(name))) continue + if (packageNameFor(rel, scanRoot) !== SESSION_MODULE) continue + const sf = ts.createSourceFile(abs, text, ts.ScriptTarget.Latest, true) + for (const stmt of sf.statements) { + if (!ts.isTypeAliasDeclaration(stmt) || !wanted.has(stmt.name.text)) continue + const name = stmt.name.text as EventEnvelopeTypeName + const src = pointer(rel, sf, stmt) + const where = `event-envelope type '${name}' (${src})` + const prior = found.get(name) + if (prior) { + violations.push(`${where} is already declared at ${prior.source}; the persisted envelope type has exactly one owner.`) + continue + } + if (!(stmt.modifiers?.some(m => m.kind === ts.SyntaxKind.ExportKeyword) ?? false)) { + violations.push(`${where} is not exported.`) + } + const { doc, hasMode } = parseJsDoc(rawJsDoc(text, stmt)) + if (hasMode) violations.push(`${where} carries an @mode tag, but a persisted type has no dispatch mode.`) + if (!doc) violations.push(`${where} has no description prose. The full JSDoc is part of the generated catalog.`) + found.set(name, { name, declaration: declarationText(text, sf, stmt), source: src }) + } + } + const missing = EVENT_ENVELOPE_TYPE_NAMES.filter(name => !found.has(name)) + if (missing.length > 0) { + violations.push(`missing event-envelope declaration(s): ${missing.join(', ')}.`) + } + reportViolations('gen-persistence-catalog', violations) + return EVENT_ENVELOPE_TYPE_NAMES.map((name) => { + const entry = found.get(name) + if (!entry) throw new Error(`gen-persistence-catalog: missing checked event-envelope declaration '${name}'.`) + return entry + }) +} + /** * Parse the `SurfaceEventType` union — the surface-eligible subset of event * types — from source. Hard-errors when the alias is missing, declared more @@ -246,8 +332,7 @@ function typeLinks(payload: string): string { /** Render one log event entry. */ function renderEvent(e: AnnotatedLogEventEntry): string[] { const out = [`#### \`${e.name}\` — ${e.surface ? 'surface' : 'log-only'}`, ''] - if (e.doc) out.push(e.doc, '') - out.push('```' + FENCE, `'${e.name}': ${e.payload}`, '```', '') + out.push('```' + FENCE, e.declaration, '```', '') const links = typeLinks(e.payload) if (links) out.push(links, '') out.push(`Source: [\`${e.source}\`](../${e.source.split(':')[0]})`, '') @@ -255,18 +340,26 @@ function renderEvent(e: AnnotatedLogEventEntry): string[] { } /** Render the full catalog (pure, deterministic given the collected inputs). */ -export function render(events: AnnotatedLogEventEntry[]): string { +export function render(events: AnnotatedLogEventEntry[], envelopeTypes: EventEnvelopeTypeEntry[]): string { const lines: string[] = [ '', '', - '# Persistence Log Event Catalog', + '# Session Persistence Event Catalog', '', - '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).', + '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 in this repo — with source JSDoc, full payload declaration, surface badge, and declaration site. It complements [session.md](core-data-structures/session.md) (surface ordering and the `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).', '', - '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).', + '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 RFC](rfc/implemented/process/2026-07-04-persistence-log-catalog.md).', '', - '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.', + 'The envelope declarations below compose each event\'s `type`, monotonic `seq`, epoch-ms `time`, `data`, 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](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.', + '', + '## Event envelope', + '', + '```' + FENCE, + envelopeTypes.map(entry => entry.declaration).join('\n\n'), + '```', + '', + `Sources: ${envelopeTypes.map(entry => `[\`${entry.source}\`](../${entry.source.split(':')[0]})`).join(' · ')}`, '', '## Events', '', @@ -285,7 +378,7 @@ export function render(events: AnnotatedLogEventEntry[]): string { * is stale. Guarded behind an entry-point check so importing this module for * tests neither regenerates the committed file nor calls process.exit. */ function main(): void { - const content = render(annotateSurface(collectLogEvents(), collectSurfaceEventTypes())) + const content = render(annotateSurface(collectLogEvents(), collectSurfaceEventTypes()), collectEventEnvelopeTypes()) if (process.argv.includes('--check')) { let committed: string | null = null try {