@orkestrel/scaffold 0.0.125 → 0.0.127

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/bin/main.js +50 -14
  2. package/dist/bin/main.js.map +1 -1
  3. package/dist/host/AGENTS.md +1 -1
  4. package/dist/host/agents/orchestration.md +5 -4
  5. package/dist/host/agents/skills/orkestrel-falsify/SKILL.md +1 -1
  6. package/dist/host/agents/skills/orkestrel-harden/references/methods.md +2 -2
  7. package/dist/host/agents/skills/orkestrel-journey/SKILL.md +18 -19
  8. package/dist/host/agents/skills/orkestrel-parallel/references/codex.md +2 -1
  9. package/dist/host/claude/AGENTS.md +2 -2
  10. package/dist/host/claude/agents/orkestrel.md +18 -18
  11. package/dist/host/claude/agents/planner.md +2 -2
  12. package/dist/host/claude/rules/quality.md +3 -0
  13. package/dist/host/claude/rules/tests.md +3 -0
  14. package/dist/host/claude/rules/workspace.md +11 -5
  15. package/dist/host/codex/agents/planner.toml +2 -2
  16. package/dist/host/guides/agent.md +285 -161
  17. package/dist/host/guides/capture.md +123 -123
  18. package/dist/host/guides/database.md +18 -7
  19. package/dist/host/guides/ndjson.md +4 -3
  20. package/dist/host/guides/ollama.md +2 -2
  21. package/dist/host/guides/program.md +3 -3
  22. package/dist/host/guides/qualifier.md +1 -1
  23. package/dist/host/guides/relation.md +71 -31
  24. package/dist/host/guides/scaffold.md +101 -64
  25. package/dist/host/guides/study.md +22 -12
  26. package/dist/host/guides/toolbox.md +9 -2
  27. package/dist/host/manifest.json +26 -26
  28. package/dist/host/tests/config.test.ts +24 -6
  29. package/dist/src/core/index.cjs +134 -79
  30. package/dist/src/core/index.cjs.map +1 -1
  31. package/dist/src/core/index.d.cts +30 -7
  32. package/dist/src/core/index.d.ts +30 -7
  33. package/dist/src/core/index.js +134 -80
  34. package/dist/src/core/index.js.map +1 -1
  35. package/package.json +4 -4
@@ -18,6 +18,8 @@ The loop and its tool handlers execute in the host that constructs them. See [Pl
18
18
 
19
19
  ## Surface
20
20
 
21
+ The `Conversation.add` method refuses a malformed `MessageInput` value before storing it and carries its structural faults in the error context.
22
+
21
23
  `Conversation.add` stores each tool call with only its `id`, `name`, and `arguments`. It refuses
22
24
  non-JSON arguments with `ConversationError` code `'MESSAGE'` before storing any member of a batch.
23
25
  Hydration still admits non-JSON call arguments in an in-memory snapshot; a durable snapshot must
@@ -206,6 +208,8 @@ agent.context.messages.add({ role: 'user', content: 'Delete record 42.' })
206
208
 
207
209
  Every call passes the gate in one order: scope, then `evaluate`, then the `consequential` floor, then the approver, and a call that `allow` cleared is checked once more against the tool instance the turn advertised before it dispatches. The floor reads the advertised definition, so a tool annotated `consequential` asks with or without rules, and with no approver that ask is denied as unanswered. `ask: () => true` is the visible relaxation of the floor: it answers yes to every asked call.
208
210
 
211
+ For a batch, the loop decides every call synchronously before entering an approver. It asks in call order, waiting for each answer before asking the next, and dispatches only after that pass unless the run is cancelled. A batch with no asked call adds no approval wait.
212
+
209
213
  Keep the two guard seams apart. An `ask` handler is a call guard: it reads the full `call`, so an approver must see that call before it answers, and it runs in the loop's own process, where a run `timeout` cancels it. An `execute` wrapper is a content guard: it reads what the handler returns and can refuse or rewrite it before the model reads it. The gate reads no model text, so rewording an injected instruction leaves its outcome unchanged, and it doesn't stop the model from choosing a tool that carries no annotation and no rule.
210
214
 
211
215
  An allowlist is a `fallback` that denies, with one rule per listed tool. To stop a run at its first denial, call `agent.abort` from a `deny` listener, so the denied call stores nothing and no further turn runs. The following fence does both:
@@ -549,6 +553,8 @@ Selection usage is charged in full to the cost `budget` and folded into `AgentRe
549
553
 
550
554
  ### Judgments on the conversation
551
555
 
556
+ Judgment writes and judge-result ingestion check the answer form, probability bounds, choice keys, and score length against the question. A judgment request must contain questions; a non-aborted result that neither answers nor refuses a requested question is an error.
557
+
552
558
  A conversation's `judgments` store records what a judge answered about its messages. Each record is keyed by the caller's question id, and adding an existing key replaces the record in place, last write wins, at its original insertion position, and the `add` method stamps the `time` member. A record carries the question, the answer or the refusal, the judge's configured `model`, the ordered `sources` ids, and the rendered `state`, and it carries `usage` only when its request asked that one question.
553
559
 
554
560
  The `resolve(judge, request, sources, signal)` method reuses every recorded judgment that matches and asks the judge once for the rest, recording what returns. A match compares the question as a JSON value, the sources in order, the rendered state, and the judge's configured `model` rather than the name a server reports, so a question whose keys arrive in another order, from a store that returns keys sorted or a host that builds it in another order, matches, and a changed criterion, a changed state, or a changed source order asks again. Criteria order reaches the prompt and a small model reads options by position, so a reused answer keeps the reading its first order earned; call `remove(id)` to ask again after reordering. A cancel keeps the records of the questions that completed and rethrows the abort.
@@ -601,20 +607,21 @@ Write criteria for a judge that reads literally (see [Jev 1.13 jaggedness](https
601
607
 
602
608
  ### Serving a conversation through a ledger
603
609
 
604
- A ledger serves one conversation as event-sourced records with one record per owner. The `createLedger(provider, options)` factory returns a `LedgerInterface` value that owns the conversation, the agent that answers it, and that agent's tools, and its `respond` method appends a request as a user message and serves it through to the reply. The conversation is the event log. Each request reads the system message, which holds the `system` option and whatever instructions and skills the `agent` option supplies, then the context message when the `agent` option supplies memos or an active workspace, then a tail of the seed history (the messages added before the first request), then a copy of the request turn: the records the ledger projects from what a judge filed about every message, a `## Request` heading, and the request. The stored request keeps its own content. An earlier request and its reply don't re-enter a planned prompt; what its lookups returned reaches a later request through the records and the `recall` tool. When the selection faults, the run rejects under the default `strict`, and under `strict: false` the agent builds the prompt from the whole conversation view instead, earlier requests and replies included, with no records.
610
+ A ledger serves one conversation as event-sourced records with one record per owner. The `createLedger(provider, options)` factory returns a `LedgerInterface` value that owns the conversation, the agent that answers it, and that agent's tools, and its `respond` method appends a request as a user message and serves it through to the reply. The conversation is the event log. Each request reads the system message, which holds the `system` option and whatever instructions and skills the `agent` option supplies, then the context message when the `agent` option supplies memos or an active workspace, then a tail of the seed history (the messages added before the first request), then each completed exchange in the window as it was sent, then a copy of the request turn: the record lines the window doesn't hold, which the ledger projects from what a judge filed about every message, a `## Request` heading, and the request. The stored request keeps its own content. The window follows the seed without changing its selection. A request or a reply the window no longer holds re-enters a planned prompt through a labeled word match from the `recall` tool, and what a request's lookups returned reaches a later request through the records and the `recall` tool. When the selection faults, the run rejects under the default `strict`, and under `strict: false` the agent builds the prompt from the whole conversation view instead, earlier requests and replies included, with no records.
605
611
 
606
612
  Run the ledger's agent only through the `respond` method: the ledger's agent serves only the ledger's `conversation`. An active `respond` call owns a run on that conversation whose request, the newest message, is that call's request or one of the ledger's notes. A run that no active `respond` call owns, such as a direct call to the agent's `generate` method or a run on another conversation, gets a faulted selection when its newest message is a user message: the selection's `fault` is a `LedgerError` with code `'REQUEST'`, so under the default `strict` the run rejects with that error before it reaches the provider, and under `strict: false` the agent emits `fault` and builds the prompt from the whole view of the run's conversation with no records. Either way the ledger asks its judge nothing for that run. When its newest message isn't a user message, the run gets no selection and builds from the whole view. Calibration admits no run, so a run during the `calibrate` method, or during the calibration that opens a `respond` call, is one that no active `respond` call owns.
607
613
 
608
614
  The method has the following pieces, each named by its export:
609
615
 
610
- - **The filing.** The `Classifier` class files each message through the judge the `judge` option injects. The ledger files a tool result, its own notes, an assistant call, and an assistant reply after the first request by their shape, and asks the judge about the rest: the `LEDGER_QUESTIONS` category question about each remaining non-request message, and the topic question, for each desk topic, about each non-quiet statement and each request unless that topic has `requested: false`; and the `amends` question about a later user message whose `correction` probability reaches the `correction` cutoff and an earlier message that isn't quiet and shares an id, an owner, or a desk topic with it, followed by the `supersedes` question about the same pair when the `amends` answer reaches its cutoff. The `narrow` member of the `correction` option keeps only the eligible earlier messages that also share a registry entity with the correction or an id or a number in their content, so a desk topic alone admits no pair, and a correction with no id, owner, or desk topic still asks no pair. On a scripted support-desk conversation recorded on 2026-11-03 with the Mica v0.1 4B judge on Ollama 0.40.14, `narrow` took 24 judge calls and 45 s against 68 and 136 s at a correction in 199 messages of 285889 characters (median 577, 95th percentile 5111, maximum 10059), and 26 judge calls and 45 s against 109 and 196 s at a correction in 290 messages of 539538 characters (median 583, 95th percentile 5906, maximum 32883). Those calls include the category and topic questions `narrow` leaves in place. Filings were equal at those two corrections, on 5 pairs and 1 supersession. A third correction, forecast from recorded answers and not run, lost 0 of 8 pairs. The 173 pairs `narrow` drops across the three, 196 questions, filed 0 on recorded answers, on text whose corrections repeat a literal by construction, and the registry-entity path admitted no pair on this recording. A true supersession outside that set is never asked, and no run on any model measures how often one occurs. Set `narrow` when a correction's wait costs more than a missed supersession and your corrections repeat the id, number, or looked-up entity they correct. Leave it off for a host with no lookups or with free-text values. Every answer lands in the conversation's `judgments` store, so a later request asks only what no earlier one asked. Under the default `strict`, a judge failure rejects the `respond` call it belongs to, after the `fault` event, and holds nothing, so the next request asks the judge again about every question still unanswered. A failure that repeats rejects that request too, so a question the judge always refuses stops each request until you remove its message or set `strict: false`. Under `strict: false`, a judge failure leaves its question unanswered, and the next request asks it again, except for two failures that hold the question so that no later request asks it: a refused question, which the judge reports as a `JudgeError` with code `'QUESTION'`, and the deterministic logprob failure the `DETERMINISTIC_JUDGE_ERROR` constant matches. The `LedgerClassification` value reads the filing back at the cutoffs: an `amends` answer at its cutoff marks a pair amended only when the two messages share an id or a number, and a `supersedes` answer at its cutoff marks the pair superseded and amended whatever they share. Each `classify` call also returns one `ClassifierAttempt` value per logical filing question it attempted, in asking order, and observes the filing without changing it. An attempt names the question's key and its `ClassifierPhase` value, and its `ClassifierOutcome` value says whether the conversation already held the judgment (`cached`), the classifier held the question after a deterministic failure or because a message it names left the conversation (`skipped`), or the judgment manager's `resolve` call fulfilled (`resolved`), rejected under a live signal (`failed`), or was cut short by an abort (`aborted`). A `resolved`, `failed`, or `aborted` attempt carries the monotonic milliseconds the classifier waited on that call as `duration`, and a `cached` or `skipped` attempt carries none. A question that a caller abort preceded has no attempt, because it never began. The attempts count logical questions and resolve requests, never the physical wire calls a judge makes for them, and they record no join of pending requests. The `attempts` member of the `LedgerResult` value holds the attempts of the filing selections of that `respond` call alone; the `Selection` values the ledger emits carry none. A page passes `agent: { scheduler: createBrowserScheduler() }` from `@orkestrel/workflow/browser`, so the classifier hands the host a turn each time the `LEDGER_SLICE` constant's milliseconds have run while it files, and the plan after the filing still runs as one task; a page that omits the option also runs each stretch of cached filing as one task, and the host gets a turn only while the classifier waits on the judge. A direct `agent.context.select` for the same request during a paced filing's yield rejects with `AgentError` `'CONCURRENCY'`, and one for a message the call does not own returns a selection whose `fault` is `LedgerError` `'REQUEST'`. A `classify` call reads each message's quiet flag and near set at most once while it pairs corrections, so a judgment or message written during a pair-phase await reads at the next `classify` call, and `LedgerLookup.read` runs one time per tool message for each plan, each `recall` call, and each filing pass. The **What a cancel waits for.** bullet under [Production behaviors of automatic compaction](#production-behaviors-of-automatic-compaction) applies to this filing: what it names holds the run, and on a ledger its held scan, until it returns.
611
- - **The records.** The `buildRecords` helper projects the filing into one `LedgerRecord` value per owner a lookup result names, plus one rules record for the rules and corrections no owner claims. Each line is a sentence of a live message, verbatim except that a sentence that opens with a pronoun opens with its party and a colon. A message filed quiet or superseded isn't live. Accepted message-level amendments preserve every original indexed sentence of live earlier sources; the projection lists distinct direct edges in its `amendments` member. Sentence scope remains unresolved. The `recall` tool and the answer note keep the stored content of each message they carry. The seed tail keeps stored content except for lookup results, which the plan replaces with stubs.
612
- - **Amendment scope.** The first retained occurrence of an amended source opens with its `[N]` reference and a note on its later changes. Distinct retained sources receive decimal references starting at 1 in first-occurrence emission order, after deduplication. References are local to one rendering of the records and are recomputed after each trim; omitted sources do not shift them. Repeated occurrences share one reference. Recall and storage retain original source IDs. Authored content is unchanged. A fully included later source opens with its own [M] reference, and the earlier source's note reads “Changed later by [M].” If any effective correction is absent, partial, or superseded, the note reads “A later change is not shown.” The omission note exposes no omitted identity, text, owner, or count. Completeness uses every original sentence identity after source deduplication and each trim; annotations count against the existing room. Effective superseded amenders retain provenance without restoring their text. No transitive amendment edge is inferred. Earlier text can conflict with its correction; downstream correction application and semantic sentence withdrawal remain unproved.
613
- - **The plan.** For each request, the ledger selects the records the request names through the `selectRecords` helper and fits the built head (the system message and the context message), the tail, and the copy of the request turn that carries the records inside a token budget: the `capacity` option less the `predict` option, times the `prompt` share, less the overhead cost of the gauge and held back by the `LEDGER_SCALE_DRIFT` constant, of which the tail takes at most the `tail` share. Owner records with the same member ids in the same order render once, under their titles joined with `; `; before trimming, the view keeps the first requested record's key, members, and lines. The projection, held sources, and recall stay unchanged. The budget bounds only the records and the tail of a request's first call: the plan prices the built head, the tail, and the copy of the request turn with the records and images it carries. The request, each lookup result, the pass's own assistant turns with their calls and replayed thinking, the answer note and the `cue` note, and the whole view a faulted selection builds from enter the prompt unbounded, so any of them can carry a prompt past the budget. The plan prices each lookup stub in the tail at the longer of its `shown` and `hidden` forms, so a tail that fits the plan still fits after the records decide which results they show. The `share` option sets both shares, and the `DEFAULT_LEDGER_SHARE` constant holds the defaults. Until the records fit, the ledger drops the rules off the request's topics, then the sources outside the selected records, then the rules on its topics, then the owner lines. Inside an owner record, it drops the lines whose source isn't a rule or a correction first, oldest first, then the lines of rules and corrections, oldest first. The `Gauge` class prices the prompt; without the `gauge` option, the ledger calibrates before its first pass, and the `calibrate` method measures the price on demand. A lookup in the tail reaches the model as the stub the `renderStub` helper writes, which says whether the records show its result. The plan reaches the agent as a `Selection` value whose `messages` member is the tail, then the copy of the request turn that the `buildRequestMessage` helper writes: the records, a blank line, a `## Request` heading, and the request. When no records render, the copy is the request itself. The answer pass carries the same copy, and the stored request keeps its own content.
614
- - **The `recall` tool.** The ledger registers a `recall` tool beside the application's lookups. It lists the earlier messages and lookup findings that match a topic (an owner name, an id, or a topic) with their stored content, newest first, each source followed by the amenders the topic doesn't match itself; an amender the topic matches lists as its own newer item. The tool cuts the list by whole items to the room the gauge leaves for the reply, naming how many older items it left out. A request can call it as many times as the `limit` member of the `recall` option allows, the `DEFAULT_RECALL_LIMIT` constant by default; after that, or when the capacity left less the `predict` option falls under twice the reply's reserve, it returns the `closure` note.
615
- - **The repeat stop.** A lookup or `recall` call that repeats an earlier call of the same request, compared by tool name and canonical arguments, returns the `repeat` note as its failure, and the ledger aborts the pass. For a lookup, the repeat stop's identity compares string arguments as written. The projection's lookup identity, which the `identifyLookup` helper writes, trims and uppercases each top-level string argument and decides which finding replaces an earlier one. So `lookup_order` calls for `bw-5512` and `BW-5512` both run in one request, and the second finding replaces the first in the records.
616
- - **The answer pass.** When the first pass ends partial or without final text and the caller didn't abort, the ledger adds an answer note when the pass's lookups or recalls returned anything, carrying what they returned without their call text, then the `cue` note, and runs one answer pass that advertises no tools and always turns thinking off. The `passes` member of the `LedgerResult` value holds both passes, and its `content` member is the last pass's. A rejected first pass counts as unfinished. When the answer pass rejects as well, the `respond` method rejects with that pass's error, and the ledger stays free for a later request.
617
- - **The thinking budget.** The `predict` option reserves the generation room that thinking and the reply share, taking it out of the plan budget, the recall room, and the close rule. The gauge counts only the thinking the next request carries: under the provider's default `replay` of `'none'`, it leaves a call's thinking out of the capacity that call used, and the `computeThinking` helper apportions that thinking from the completion by character share. Under every policy, the reply reserve reads the reply without its thinking. The `think` option requests or suppresses thinking for the first pass, and omission leaves the provider's default; the answer pass always runs with thinking off. With replay `'none'`, a ledger at a `capacity` of `W + P` with a `predict` of `P`, where `W` is a context window and `P` a generation cap, budgets like a ledger at `W` without thinking.
616
+ - **The filing.** The `Classifier` class files each message through the judge the `judge` option injects. A user message carrying an id or a number, as read by `extractLiterals`, stays non-quiet regardless of its recorded weights. If its winning category is quiet, `category` returns `undefined`; this floor supplies no fact, rule, or correction judgment. Shape assignments keep their categories. Hydrating recorded judgments applies the same floor, and the next filing asks the topic questions those messages previously skipped. The ledger files a tool result, its own notes, an assistant call, and an assistant reply after the first request by their shape, and asks the judge about the rest: the `LEDGER_QUESTIONS` category question about each remaining non-request message, and the topic question, for each desk topic, about each non-quiet statement and each request unless that topic has `requested: false`; and the `amends` question about a later user message whose `correction` probability reaches the `correction` cutoff and an earlier message that isn't quiet and shares an id, an owner, or a desk topic with it, followed by the `supersedes` question about the same pair when the `amends` answer reaches its cutoff. The `narrow` member of the `correction` option keeps only the eligible earlier messages that also share a registry entity with the correction or an id or a number in their content, so a desk topic alone admits no pair, and a correction with no id, owner, or desk topic still asks no pair. On a scripted support-desk conversation recorded on 2026-11-03 with the Mica v0.1 4B judge on Ollama 0.40.14, `narrow` took 24 judge calls and 45 s against 68 and 136 s at a correction in 199 messages of 285889 characters (median 577, 95th percentile 5111, maximum 10059), and 26 judge calls and 45 s against 109 and 196 s at a correction in 290 messages of 539538 characters (median 583, 95th percentile 5906, maximum 32883). Those calls include the category and topic questions `narrow` leaves in place. Filings were equal at those two corrections, on 5 pairs and 1 supersession. A third correction, forecast from recorded answers and not run, lost 0 of 8 pairs. The 173 pairs `narrow` drops across the three, 196 questions, filed 0 on recorded answers, on text whose corrections repeat a literal by construction, and the registry-entity path admitted no pair on this recording. A true supersession outside that set is never asked, and no run on any model measures how often one occurs. Set `narrow` when a correction's wait costs more than a missed supersession and your corrections repeat the id, number, or looked-up entity they correct. Leave it off for a host with no lookups or with free-text values. Every answer lands in the conversation's `judgments` store, so a later request asks only what no earlier one asked. Under the default `strict`, a judge failure rejects the `respond` call it belongs to, after the `fault` event, and holds nothing, so the next request asks the judge again about every question still unanswered. A failure that repeats rejects that request too, so a question the judge always refuses stops each request until you remove its message or set `strict: false`. Under `strict: false`, a judge failure leaves its question unanswered, and the next request asks it again, except for two failures that hold the question so that no later request asks it: a refused question, which the judge reports as a `JudgeError` with code `'QUESTION'`, and the deterministic logprob failure the `DETERMINISTIC_JUDGE_ERROR` constant matches. The `LedgerClassification` value ignores amendment and supersession marks whose later message is quiet and reads the remaining filing back at the cutoffs: an `amends` answer at its cutoff marks a pair amended only when the two messages share an id or a number, and a `supersedes` answer at its cutoff marks the pair superseded and amended whatever they share. Each `classify` call also returns one `ClassifierAttempt` value per logical filing question it attempted, in asking order, and observes the filing without changing it. An attempt names the question's key and its `ClassifierPhase` value, and its `ClassifierOutcome` value says whether the conversation already held the judgment (`cached`), the classifier held the question after a deterministic failure or because a message it names left the conversation (`skipped`), or the judgment manager's `resolve` call fulfilled (`resolved`), rejected under a live signal (`failed`), or was cut short by an abort (`aborted`). A `resolved`, `failed`, or `aborted` attempt carries the monotonic milliseconds the classifier waited on that call as `duration`, and a `cached` or `skipped` attempt carries none. A question that a caller abort preceded has no attempt, because it never began. The attempts count logical questions and resolve requests, never the physical wire calls a judge makes for them, and they record no join of pending requests. The `attempts` member of the `LedgerResult` value holds the attempts of the filing selections of that `respond` call alone; the `Selection` values the ledger emits carry none. A page passes `agent: { scheduler: createBrowserScheduler() }` from `@orkestrel/workflow/browser`, so the classifier hands the host a turn each time the `LEDGER_SLICE` constant's milliseconds have run while it files, and the plan after the filing still runs as one task; a page that omits the option also runs each stretch of cached filing as one task, and the host gets a turn only while the classifier waits on the judge. A direct `agent.context.select` for the same request during a paced filing's yield rejects with `AgentError` `'CONCURRENCY'`, and one for a message the call does not own returns a selection whose `fault` is `LedgerError` `'REQUEST'`. A `classify` call reads each message's quiet flag and near set at most once while it pairs corrections, so a judgment or message written during a pair-phase await reads at the next `classify` call, and `LedgerLookup.read` runs one time per tool message for each plan, each `recall` call, and each filing pass. The **What a cancel waits for.** bullet under [Production behaviors of automatic compaction](#production-behaviors-of-automatic-compaction) applies to this filing: what it names holds the run, and on a ledger its held scan, until it returns.
617
+ - **The records.** The `buildRecords` helper projects the filing into one `LedgerRecord` value per owner a lookup result names, plus one rules record for the rules and corrections no owner claims. Each line is a sentence of a live message, verbatim except that a sentence that opens with a pronoun opens with its party and a colon. A message filed quiet or superseded isn't live. Accepted message-level amendments preserve every original indexed sentence of live earlier sources; the projection lists distinct accepted edges in its `amendments` member. Sentence scope remains unresolved. The `recall` tool and the answer note keep the stored content of each message they carry. The seed tail keeps stored content except for lookup results, which the plan replaces with stubs.
618
+ - **Amendment scope.** The first retained occurrence of an amended source opens with its `[N]` reference and a note on its later changes. Distinct retained sources receive decimal references starting at 1 in first-occurrence emission order, after deduplication. References are local to one rendering of the records and are recomputed after each trim; omitted sources do not shift them. A copy that follows a window numbers its sources after the ones the window holds, so one reference names one source across the window and that copy. Repeated occurrences share one reference. Recall and storage retain original source IDs. Authored content is unchanged. A fully included later source opens with its own [M] reference, and the earlier source's note reads “Changed later by [M].” If any effective correction is absent or partial, the note reads “A later change is not shown.” The omission note exposes no omitted identity, text, owner, or count. Completeness uses every original sentence identity after source deduplication and each trim; annotations count against the existing room. An edge whose amender a newer message superseded points at that amender's newest live successor, followed through accepted supersessions alone, so a change fully received by the records is not called not shown. With no live successor, the edge keeps its endpoint, which reads as absent. Neither restores the superseded text. An amendment of an amender infers no edge to the earlier message. Earlier text can conflict with its correction; downstream correction application and semantic sentence withdrawal remain unproved.
619
+ - **The plan.** For each request, the ledger selects the records the request names through the `selectRecords` helper and fits the built head (the system message and the context message), the tail, and the copy of the request turn that carries the records inside a token budget: the `capacity` option less the `predict` option, times the `prompt` share, less the overhead cost of the gauge and held back by the `LEDGER_SCALE_DRIFT` constant, of which the seed tail takes at most the `tail` share. The `tail` share bounds only the seed. Owner records with the same member ids in the same order render once, under their titles joined with `; `; before trimming, the view keeps the first requested record's key, members, and lines. The projection and held sources stay unchanged. The plan budget bounds the records, the tail, and the window of a request's first call: it prices the built head, the tail, the window, and the copy with its records and images. Runtime recall and recovery fit their result groups separately. A request, a lookup result, or a faulted selection's whole view can still exceed the budget. The plan prices each lookup stub in the tail at the longer of its `shown` and `hidden` forms, so a tail that fits the plan still fits after the window and the copy decide which results they show. The `share` option sets both shares, and the `DEFAULT_LEDGER_SHARE` constant holds the defaults. Until the records fit, the ledger drops the rules off the request's topics, then the sources outside the selected records, then the rules on its topics, then the owner lines. Inside an owner record, it drops the lines whose source isn't a rule or a correction first, oldest first, then the lines of rules and corrections, oldest first. The `Gauge` class prices the prompt; without the `gauge` option, the ledger calibrates before its first pass, and the `calibrate` method measures the price on demand. A lookup in the tail reaches the model as the stub the `renderStub` helper writes, which reads `shown` when the window and the copy together hold its whole result or the whole result of a finding with the same canonical lookup identity and text. The plan reaches the agent as a `Selection` value whose `messages` member is the tail, then each exchange in the window, then the copy of the request turn that the `buildRequestMessage` helper writes: the record lines the window doesn't hold, a blank line, a `## Request` heading, and the request. A copy with no line to add is the request itself. The answer pass carries the same copy, and the stored request keeps its own content.
620
+ - **The window.** The ledger holds one `LedgerExchange` value per completed exchange: the request as it was sent, its final reply, and the record lines that copy rendered. Each prompt sends those exchanges in order, so a prompt extends the one before it, within the limits the **A follow-up can read the reply again.** bullet names. A copy holds only the record lines the window doesn't hold, matched by identity and never by text, so identical words under another source render with their own attribution. A titled record's line is held by record, source, and sentence, so a source under another owner's record renders again for its attribution. A line of a source outside the selected records, which renders under no title, is held by source and sentence under any placement, so it doesn't repeat what an earlier copy printed under a title. A line the window holds stays held whether or not a later request selects its record. The seed and the records are planned without the window, so the window spends only the spare room of the plan's total and never displaces a record line or a seed message. The plan prices the following rungs in order and sends the first whose prompt fits the total and, if that rung offers `recall`, leaves an open recall open: the whole window with a copy of the lines it doesn't hold, then the newest exchange with its request plain and a copy of every selected line, then no exchange and a copy of every selected line. When no rung meets both tests, the plan sends no exchange. A recall already closed with no exchange at all doesn't prevent admission. A fall to a lower rung is silent, with no note, and an answered request leaves the window as what it sent plus its own exchange, so the exchanges a fall left out don't return. An admitted window can reduce recall listing room without closing recall. Admission retains its reserve forecast. Runtime recall reads reported usage when available, including completion and replayed thinking, and fits its result without that reserve veto. The window empties when a message it holds changes or leaves the conversation, when a source it holds leaves the records, when the accepted amendments touching a message it holds change, when a request no longer pairs with the reply held for it, or when this request's lines would change an amendment note or reference an earlier copy printed. A source missing from this request's selected records empties nothing. An empty window derives the newest request and its final reply from the conversation, with the request plain, or nothing when the newest request holds no valid reply. A window a change empties keeps its last exchange, with the request plain, when the derive gives nothing because a later request failed and that exchange's reply still stands, so a stopped request doesn't lose the reply a person read. It never carries a removed reply, and it never falls back to an exchange older than that. A derived pair seats before the request is sent. A request that rejects or ends with no reply leaves the window as it stands, a seated derived pair included, so the next prompt holds the last good exchange. A request answered through the whole view under `strict: false` joins with its stored request plain and no lines. Tool calls, tool results, and ledger notes never enter the window, so a request that called a tool joins as its copy and its final reply.
621
+ - **The `recall` tool.** The tool requires a nonempty topic string; an empty topic fails argument admission. The ledger registers a `recall` tool beside the application's lookups and offers it only on a request with something to find: a user statement, including a quiet one, a lookup finding with a result, an earlier request, or a nonblank call-free reply that the seed tail, the window, and the copy together don't hold whole. A lookup stub doesn't hold its result, but a fully received finding with the same canonical lookup identity and text holds an identical finding's result too. A partly shown message counts as hidden, and a finding with no result never opens the offer. A ledger note and the current request's own turns never open the offer. The `collectRecallMessages` and `hasHiddenRecall` helpers read this per request from the conversation, so a hydrated ledger offers what the uninterrupted one offers. When nothing is hidden, the ledger narrows the agent's scope to the other tools for that request, keeping a host's allow-lists and selector, and the `respond` method restores the host's own scope when it settles, a rejection or an abort included, only while the plan's scope is still active. A scope the host applied in the meantime stays active. The tool's description reads that it finds something said earlier that isn't in the messages the model can see. It lists matching statements and lookup findings first, newest first, each source followed by the amenders the topic doesn't match itself; an amender the topic matches lists as its own newer item. It then lists earlier requests and call-free, non-empty assistant replies, newest first, under `Earlier request:` and `Earlier reply:`. A conversation match contains every word of at least one part of the topic, including when that part also names an owner. This conversation route excludes the current request and its turns, ledger notes, and messages already listed. It keeps the stored text, with each run of line breaks written as a line break and two spaces so that only a label opens a line, and it admits a partial reply the conversation stored before an abort. A hidden quiet statement can open the offer by itself, and a word match can list it. A cut landing mid-stream stores no reply and carries nothing. On the statement and lookup route, only lines opening with `Earlier request:` or `Earlier reply:` gain the same two-space indent; every other byte, including stored line breaks, stays unchanged. A label names the message's role, so a host-added assistant message in the seed reads as a reply too. These listings do not promote replies or requests into records. A search that finds nothing returns `nothing earlier on "TOPIC"; answer from the messages you can see`, where `TOPIC` is the searched topic, and that result enters no answer note. A blank topic still returns its guidance as a failure. The route reads the conversation and not the prompt, so it can list a request or a reply the window already carries. The tool fits whole items, including each source's amenders, into what the measured request leaves below capacity less predict, and names how many items it left out. An oversized item is omitted, and a later fitting item can still be returned. The result and its omission line share the allowance, with tool-message framing counted. When no item fits, the line reads `N older items didn't fit in this request; answer from the messages you can see`, using `item` for one and `more` for conversation matches. A partial listing keeps `N older items not shown; name a narrower topic to narrow the recall`. A gauged direct run fits its listing to the same allowance; with no gauge, the first whole item remains unconditional. The cut line uses `more` when an omitted item precedes a kept one in listing order, or when conversation matches are listed; otherwise it uses `older`. This rule applies to both omission forms. Statements and lookup findings take priority over conversation matches. A request can call it as many times as the `limit` member of the `recall` option allows, the `DEFAULT_RECALL_LIMIT` constant by default; after that it returns the `closure` note. Lack of room never closes recall: a distinct later call is fitted independently. The prefix uses the last call's reported prompt and completion, adjusted for replay by `Gauge.remainder`; missing usage uses an estimate. Additions use the larger of `Gauge.rate` and the latest reported call's prompt less known overhead divided by its estimate, with `LEDGER_SCALE_DRIFT` headroom. As in `Gauge.observe`, a partly spared call keeps the marginal rate instead of guessing an overhead share. Calls without reported usage use the marginal rate alone. Sibling recall results share the room. A listing within the `LEDGER_SCALE_DRIFT` margin of the room can be left out, with the omission line stating that it did not fit this request.
622
+ - **The repeat stop.** A lookup or `recall` call that repeats an earlier call of the same request, compared by tool name and canonical arguments, returns the `repeat` note as its failure, and the ledger aborts the pass. For a lookup, the repeat stop's identity compares string arguments as written. The projection's lookup identity, which the `identifyLookup` helper writes, trims and uppercases each top-level string argument and decides which finding replaces an earlier one. So `lookup_order` calls for `bw-5512` and `BW-5512` both run in one request, and the second finding replaces the first in the records when its text differs. A finding with different text or an empty result replaces the earlier one, a finding with the same text replaces nothing, so the first unsuperseded finding of the final same-text run stays live, and a thrown call files no finding, leaving the earlier result live.
623
+ - **The answer pass.** When the first pass ends partial or without final text and the caller didn't abort, the ledger adds an answer note when the pass's lookups or recalls returned anything, carrying what they returned without their call text, then the `cue` note, and runs one answer pass that advertises no tools and always turns thinking off. Before that pass, the ledger prices the rebuilt prompt at the same request-local rate. If it exceeds capacity less predict, it leaves a call-free partial assistant reply out of the prompt while keeping it stored, then fits the union of result groups to the remaining room. Source and amendment groups stay whole. Only the omission line the ledger appended is excluded from the digest; a literal line inside an accepted source group is preserved, even when its text matches an omission line; groups already represented by earlier groups enter no second copy. The `passes` member of the `LedgerResult` value holds both passes, and its `content` member is the last pass's. A rejected first pass counts as unfinished. When the answer pass rejects as well, the `respond` method rejects with that pass's error, and the ledger stays free for a later request.
624
+ - **The thinking budget.** The `predict` option reserves the generation room that thinking and the reply share, taking it out of the plan budget, the runtime recall room, and the answer prompt allowance. The plan's reserve-based admission rule stays unchanged. The gauge counts only the thinking the next request carries: under the provider's default `replay` of `'none'`, it leaves a call's thinking out of the capacity that call used, and the `computeThinking` helper apportions that thinking from the completion by character share. Under every policy, the reply reserve reads the reply without its thinking. The `think` option requests or suppresses thinking for the first pass, and omission leaves the provider's default; the answer pass always runs with thinking off. With replay `'none'`, a ledger at a `capacity` of `W + P` with a `predict` of `P`, where `W` is a context window and `P` a generation cap, budgets like a ledger at `W` without thinking.
618
625
 
619
626
  Display references identify sources within the rendered records while the line keeps the stored identity:
620
627
 
@@ -643,7 +650,7 @@ The application supplies the following through `LedgerOptions`:
643
650
  - the capacity, through the `capacity` option, the model's context window in tokens;
644
651
  - the generation cap, through the `predict` option, in tokens with thinking included, 0 by default and less than `capacity`;
645
652
  - the thinking of the first pass, through the boolean `think` option; the answer pass always runs with thinking off;
646
- - the state to hydrate from, through the `snapshot` option, which takes what a ledger's `snapshot` method returned: the conversation with its judgments, the marked request, note, and failed tool result ids, and the gauge, which a `gauge` option overrides.
653
+ - the state to hydrate from, through the `snapshot` option, which takes what a ledger's `snapshot` method returned: the conversation with its judgments, the marked request, note, and failed tool result ids, the gauge, which a `gauge` option overrides, and the window while it holds an exchange.
647
654
 
648
655
  The method has the following documented limits:
649
656
 
@@ -651,23 +658,31 @@ The method has the following documented limits:
651
658
  - **A desk-wide correction stays in one owner's record.** A message that names an owner joins that owner's record and not the rules record, so a correction to a desk-wide rule stated inside one owner's message isn't among the rules a request about another owner reads.
652
659
  - **Recall identity is the topic alone.** The repeat stop compares two `recall` calls by their trimmed `topic` argument, so a second call with the same topic is a repeat whatever other arguments it carries.
653
660
  - **A change during a selection rejects the request.** A selection reads the conversation it was asked about, so a host append or removal while a `respond` call's selection runs faults it with a `changed during selection` error. Under the default `strict`, `respond` rejects with that error before it reaches the provider, and the ledger stays free for a later call. Under `strict: false`, the agent emits `fault` and builds the prompt from the whole view.
654
- - **A direct run beside a request is refused.** A direct run on the ledger's conversation while a `respond` call's pass runs is refused with `AgentError` `'CONCURRENCY'`. Under the default `strict`, any other run no active `respond` call owns whose newest message is a user message rejects with `LedgerError` `'REQUEST'` before it reaches the provider: a direct run between requests, one during the calibration that opens a call, and a run on another conversation during a call. Under `strict: false` that run emits `fault` and goes on over the whole view with no ledger selection; a run on another conversation then adds its turns and usage to that call's gauge readings, shares its repeat stop, and can reach the `recall` and lookup tools, which the ledger's agent advertises to every run and which read the ledger's `conversation`.
661
+ - **A direct run beside a request is refused.** A direct run on the ledger's conversation while a `respond` call's pass runs is refused with `AgentError` `'CONCURRENCY'`. Under the default `strict`, any other run no active `respond` call owns whose newest message is a user message rejects with `LedgerError` `'REQUEST'` before it reaches the provider: a direct run between requests, one during the calibration that opens a call, and a run on another conversation during a call. Under `strict: false` that run emits `fault` and goes on over the whole view with no ledger selection; a run on another conversation then adds its turns and usage to that call's gauge readings, shares its repeat stop, and can reach the lookup tools, and the `recall` tool when that call's request offers it, because the ledger's agent shares its scope across runs, and those tools read the ledger's `conversation`.
655
662
  - **A run no call owns keeps no request state.** The ledger holds a request's state in a `LedgerRequest` value from the start of its `respond` call until the call settles. A run that no `respond` call owns, including a run during calibration, reads no request's state: its lookup and `recall` calls run with no repeat stop, recall limit, or close rule, and none of its turns reach a gauge reading.
656
663
  - **A seed tool message counts as successful.** A tool message the application adds to the conversation has no recorded result, so the ledger reads it as a successful lookup and files it as a fact, and its reading handler decides what the result names.
657
664
  - **An abort during calibration rejects.** When the caller's signal aborts while the ledger calibrates, the `respond` method rejects with the abort reason instead of resolving a partial result; after calibration, an abort ends the request partial and skips the answer pass.
658
665
  - **A foreign signal rejects before anything is appended.** A `signal` that isn't a native `AbortSignal` rejects the `respond` method with a `ContractError` before the request is appended, and the ledger stays free for a later request.
659
- - **Only the seed forms the tail.** Only the messages added before the first request form the seed tail, so an application message added after the first request reaches a planned prompt only through the records or the `recall` tool.
660
- - **Records don't retire.** No age or request count retires a message: it leaves the records only when a later message supersedes it, a later finding of the same lookup replaces it, or a later answer files it quiet. Only the plan decides which of its lines a request copy shows.
661
- - **The ledger refuses no over-window prompt.** A request, a lookup result, the pass's own turns, the answer note, or the whole view a faulted selection builds from reaches the provider whole when it's larger than the room the `capacity` option leaves, and the provider's own context limit decides what happens to it. A provider that refuses an over-long prompt fails the pass, so lower `capacity`, or set `AgentOptions.window` on an agent you drive yourself, to fold the conversation first.
662
- - **A memo written between passes enters unpriced.** A memo written during a request's first pass, by a lookup or a host tool, enters the answer pass's context message unpriced: the plan prices the head the first pass sends, and the answer pass rebuilds the context message from the managers as they read then, so the system, tail, and request positions stay byte-identical and the context message can change.
666
+ - **The seed selection stays fixed.** Only the messages added before the first request form the seed tail. Each completed exchange follows it in the window: a request as it was sent and its last call-free assistant reply, excluding notes, calls, and tool messages. A blank or missing last call-free reply carries nothing. A committed partial reply means one the conversation stored; it remains eligible after an abort, but a cut landing mid-stream stores no reply and carries nothing. A host statement reaches the prompt through records or recall, and neither that statement nor a host lookup after the reply erases the exchange. Two non-empty call-free assistants without a ledger note between them make the pairing ambiguous, so it carries nothing; answer-pass notes establish the separation between a partial first reply and the final answer. A host that removes a request must remove every turn of it too, because nothing stored links a reply to its request: a surviving reply can read as the earlier request's when that request has no reply of its own, or when the removed request's answer pass left its note behind. The seed messages and the selected record lines stay the same on every rung of the window, and only a seed stub's `shown` or `hidden` state follows the rung.
667
+ - **Records don't retire.** No age or request count retires a message: it leaves the records only when a later message supersedes it, a later finding of the same lookup with different text or an empty result replaces it, or a later answer files it quiet. Only the plan decides which of its lines a request copy shows, and a line an earlier copy showed stays in the prompt until the window empties or falls past that copy.
668
+ - **The ledger refuses no over-window prompt.** A request, a lookup result, or the whole view a faulted selection builds from can exceed the room the `capacity` option leaves. Recall results and recovery digests are fitted, but unbounded mandatory content can still reach the provider, and the provider's own context limit decides what happens to it. A provider that refuses an over-long prompt fails the pass, so lower `capacity`, or set `AgentOptions.window` on an agent you drive yourself, to fold the conversation first.
669
+ - **A host edit after fitting enters unpriced.** A memo written during a request's first pass enters the rebuilt answer context and consumes its fitting allowance. A later host edit, after fitting, remains unpriced. The context can change while the selected seed and request stay the same.
663
670
  - **A heading inside a record line reads as one.** A record line and the request copy render a message's or a lookup's text verbatim, so text holding a `## Rules` or `## Request` heading reads as one inside the user turn's copy; it changes no filing and never reaches `system`, and no delimiter marks such text.
664
671
  - **A lookup is a read.** A ledger lookup is a read; a tool whose call has a consequence is not a lookup, and a ledger refuses a `consequential` lookup at every call. `LedgerAgentOptions` carries no `authority`: the ledger passes its own, which allows the names it advertises (`recall` and each lookup) and denies every other name, so a `consequential` lookup meets the floor with no approver and is denied as unanswered, and a tool a host adds later reads `the ledger advertises no such tool`.
665
- - **A snapshot's judgments are frozen records.** `LedgerInterface.snapshot().conversation` carries the stored deep-frozen judgments, so a write to one throws `TypeError` in strict-mode code, and a host copies a record through `copyJSON` before it migrates or redacts it.
666
- - **A snapshot carries no gauge observations.** The `gauge` member of a snapshot holds the scale and the overhead cost alone. A hydrated ledger has observed no reply and no earlier request, so until it completes a request of its own, the `recall` tool sizes its room and applies its close rule as a ledger that has served nothing does, and a `recall` call can list a different number of items than the same call on the ledger that took the snapshot.
672
+ - **A snapshot's judgments are frozen records.** `LedgerInterface.snapshot().conversation` carries the stored deep-frozen judgments, so a write to one throws `TypeError` in strict-mode code, and a host copies a record through `copyJSON` before it migrates or redacts it. A host that migrates or redacts a snapshot can delete its `window` member as the clean path, because the stored copies repeat conversation text: the hydrated ledger derives the newest pair plain, and no stored copy keeps the old text in the snapshot's bytes or can send it.
673
+ - **A snapshot carries no gauge observations.** The `gauge` member of a snapshot holds the scale and the overhead cost alone. A hydrated ledger has observed no reply and no earlier request, so its window admission starts with the longest stored reply as its reserve forecast. Runtime recall uses the current request's measurements; lost marginal-rate history can still change the fit, so live and hydrated calls can list different numbers of items. The window's rungs retain their reserve rule. A hydrated ledger sends what the uninterrupted one would when the live and hydrated reserves admit the same rung. A rung that lies between the two reserves can differ, which moves the prefix and never the record coverage.
667
674
  - **A hydrated ledger asks a held question again.** A snapshot doesn't carry the questions a `strict: false` classifier held after a refused question or a deterministic judge failure, so a ledger hydrated from it asks each of them again in its next request.
675
+ - **A snapshot carries the window.** The `window` member of a `LedgerSnapshot` value is optional and present only while the window holds an exchange, so the snapshot of an empty window reads as one with no such member. A 0.0.36 snapshot holds none, reads as it did, and derives the newest pair plain. The `snapshot` method omits a window its conversation can't support, as after a host removes a held message, so a removal doesn't leave a snapshot that hydrating refuses. The `isLedgerSnapshot` guard reads a stored window's exact shape alone, so it refuses a malformed window or one with no `digest` member, and construction refuses that snapshot with `LedgerError` code `'SNAPSHOT'`. It reads no reference or sentence range, so a well-shaped window that names a removed message or sentence passes the guard, and hydrating discards it, because its digest disagrees or can't be computed.
676
+ - **A stored window carries a digest.** The `window` member of a snapshot holds a required `digest` member, a checksum the `digestLedgerWindow` helper computes over the canonical form of its held messages, each request, reply, and record line's source, every lookup result and every message holding a call, because an owner heading can print a lookup no line holds, its stored copies, and its sentence receipts. An edit to any of those, by a host migrating or redacting, makes the digest disagree: hydrating discards the whole window and the ledger derives the newest pair from the edited conversation, so old held text doesn't reach a provider. A digest that can't be computed discards the window the same way. The digest detects an edit, can collide, and makes no security claim. The canonical form sorts keys, so a store that reorders them doesn't make the digest disagree. A held message the canonical form can't render, such as one with an `undefined` tool argument, makes the `snapshot` method omit the window. A held lookup's call arguments count too, through the assistant message that made the call.
677
+ - **A follow-up can read the reply again.** A model server that keeps a prompt cache reuses a prompt that extends the last. On a model whose generation prefix differs from how it renders a reply in history, the server reads the reply itself again, so a follow-up costs the reply plus the text the last prompt didn't hold: small with short replies, and larger with long ones. After a request that called a tool, the prompt shares its prefix only through that request's copy, because tool calls and results stay out of the window, so that reply is read again on any model. Anything ahead of the window moves the prefix too: a system or instruction edit, a memo or workspace change in the context message, a seed stub whose `shown` or `hidden` state flips, and a seed exchange whose cut moves when the gauge rescales. So do an emptied window, a fall to a lower rung, a workspace image, which attaches to the last user message, and a reply whose thinking the `replay` policy leaves out.
678
+ - **A changed lookup empties the window.** A later finding of the same lookup with different text or an empty result retires the source the window holds, and that empties the window. That prompt holds the derived newest pair and a copy of every selected line, so it doesn't extend the prompt before it. A lookup repeated with the same text retires nothing, so the prompt extends the one before it.
679
+ - **A cut stream stores nothing.** A stream cut before its reply is stored leaves the window standing, so a follow-up that refers to the cut text reads against the last completed reply.
680
+ - **Recall fitting depends on its measured price.** Runtime recall and recovery allow the `LEDGER_SCALE_DRIFT` margin over the larger of the gauge's marginal rate and this request's measured rate. A provider whose new text costs more than that bound is outside the capacity guarantee. Missing usage remains estimated; no exact tokenizer preflight is available. A long earlier reply still affects window admission, but never vetoes a runtime recall that fits.
681
+ - **A replaced seed lookup keeps its stub.** When a later finding of the same lookup with different text replaces a seed lookup, the seed stub reads `result not shown` while a later copy can print the replacing result, unless the window and the copy fully receive a finding with the same canonical lookup identity and text as the seed finding. That full receipt makes a duplicate stub read `shown`, even when its own source is retired.
682
+ - **A change can sit beside its not-shown note.** When an amender was superseded with no live successor, or when a later message amends the amender and files no edge of its own to the earliest message, the earliest message's note reads “A later change is not shown.” beside a change the copy prints, because no other edge is inferred. The note can also read this way when the change sits raw in the seed tail, because the record's amendment rendering doesn't read that tail.
668
683
  - **A snapshot survives a store that sorts keys.** A judgment matches by JSON value, so a `DatabaseConversationStore` column that returns keys in another order, a binary JSON column included, keeps every memoized judgment. A structured `state` compares by its JSON text, key order included, so pass the same key order on each resolve or render it to a string first. A restored answer keeps the probability order its store returned, so `measureAnswer` can name another winner on an exact tie; the `category` method of the `Classifier` class walks `LEDGER_CATEGORIES`, so a ledger's filing doesn't depend on that order. A restored lookup call's arguments render in the order the column returns them, so a records line, an item the `recall` tool lists, a lookup stub in the tail, and the provider request can differ in bytes from the ones the original run sent, and a stub's `hidden` form can tell the model to recall with another string argument, because it names the first string in that order. A restored message object keeps the member order its column returned, so a provider whose encode passes `request.messages` through by spread sends those members in that order; the relay projection and the judge requests fix their member order. `matchesJSON` is bounded to JSON data and promises nothing for a cycle, a `toJSON` object, `NaN`, an infinity, or an `undefined`, function, symbol, or hole inside a list.
669
- - **The `narrow` member can hide a supersession.** The ledger never compares an earlier message that shares only a desk topic with the correction, so a supersession on a pair sharing no registry entity and no id or number is never filed. For example, "the refund limit is 500" then "no, the refund limit is 600" shares no literal, so with no shared registry entity `narrow` never asks about that pair, where the unset rule does.
670
- - **Nothing caps a correction's pair questions.** A correction's pair questions grow with its eligible earlier messages. At the 290-message correction of the recording under **The filing.**, one correction asked 98 pair questions over 93 earlier messages, inside 109 judge calls and 196 s on the Mica v0.1 4B judge. The `narrow` member lowers them, and the caller's abort signal ends them.
684
+ - **The `narrow` member can hide a supersession.** The ledger never compares an earlier message that shares only a desk topic with the correction, so a supersession on a pair sharing no registry entity and no id or number is never filed. For example, "the refund limit is 500" then "no, the refund limit is 600" shares no literal, so with no shared registry entity `narrow` never asks about that pair, where the unset rule does. In the reading of 2026-11-06, of 12 corrections two blind readers agreed on, across ABCD and Taskmaster-1, 8 carry no id or number and 4 carry only the new value, and none repeats the old one. Read those messages alone, because their dialogs weren't at hand, so only a shared registry entity could admit their pairs.
685
+ - **Nothing caps a correction's pair questions.** A correction's pair questions grow with its eligible earlier messages. At the 290-message correction recorded on 2026-11-03 under **The filing.**, one correction asked 98 pair questions over 93 earlier messages, inside 109 judge calls and 196 s on the Mica v0.1 4B judge. The `narrow` member lowers them, and the caller's abort signal ends them.
671
686
 
672
687
  ### Customizing the format (the cascade)
673
688
 
@@ -755,7 +770,7 @@ The provider's `replay` member decides which recorded thinking goes back to the
755
770
 
756
771
  Choose `'turn'` for a backend that reads thinking inside a tool loop. Some chat formats keep the thinking of the turn in progress and drop older thinking, such as the Qwen3 template (see [the Qwen3 model card](https://huggingface.co/Qwen/Qwen3-235B-A22B)), and some APIs refuse a tool turn that leaves out its thinking, such as DeepSeek's (see [DeepSeek thinking mode](https://api-docs.deepseek.com/guides/thinking_mode)). The `thinking` member is a plain string, so it can't carry a signature that an API requires beside the text, such as Anthropic's (see [Anthropic extended thinking](https://platform.claude.com/docs/en/build-with-claude/thinking)).
757
772
 
758
- The agent loop, a relay server, and a ledger apply the policy before calling the provider. A direct `generate` or `stream` call sends messages as given. The agent applies the policy through `stripThinking` before every provider call and before every compaction estimate, and a provider without a `replay` member counts as `'none'`. `estimateRequest` counts a message's `thinking`, so the `window` budget counts the thinking the request carries and no other. A ledger applies the same policy to the tail it plans and each call it measures, and calibration applies the policy at the next user boundary, as if a user message followed the conversation view. Calibration prices the whole view; a planned request carries only the selected tail, so the retained messages can differ.
773
+ The agent loop, a relay server, and a ledger apply the policy before calling the provider. A direct `generate` or `stream` call sends messages as given. The agent applies the policy through `stripThinking` before every provider call and before every compaction estimate, and a provider without a `replay` member counts as `'none'`. `estimateRequest` counts a message's `thinking`, so the `window` budget counts the thinking the request carries and no other. A ledger applies the same policy to the tail and the window it plans and each call it measures, and calibration applies the policy at the next user boundary, as if a user message followed the conversation view. Calibration prices the whole view; a planned request carries only the selected tail, so the retained messages can differ.
759
774
 
760
775
  A relay applies both policies. The agent in the browser strips the request by the policy of its `RelayProvider`, the request carries each remaining `thinking` member, and `RelayStream` strips it again by the upstream provider's policy, so the upstream call carries only the thinking that both policies keep.
761
776
 
@@ -796,7 +811,7 @@ The `JudgeInterface` contract is the decision boundary beside `ProviderInterface
796
811
 
797
812
  The `AgentJudge` class is the engine behind that boundary, as the `AgentProvider` class is the engine behind `ProviderInterface`. It owns each call's deadline, the transport, the `headers` hook, the validation before inference, the bounded error read, and the merge of every call's result, and it leaves the wire open: a subclass supplies `name`, `encode(request)`, which projects one call's `JudgeRequest` onto the protocol's request shape, and `read(value, request)`, which decodes one call's parsed response into a `JudgeResult`. A one-shot JSON response has no framing state and no buffered tail, so the engine has no `frame` or `finish` seam. In place of the `split` and `strict` switches it takes one `batch` switch: `true`, the default, sends every question in one call, and `false` sends one call per question in key order.
798
813
 
799
- The `SystemOneJudge` class is the wire this package ships on that engine, and the `createSystemOneJudge` factory returns it behind `JudgeInterface`. It speaks the System One decision protocol at `SYSTEM_ONE_PATH` and sends every question in one call. See [Asking a System One server a choice, a noul, and a score](#asking-a-system-one-server-a-choice-a-noul-and-a-score) for the servers it serves and a whole request; see [Writing a judge wire](#writing-a-judge-wire) for a wire of your own.
814
+ The `SystemOneJudge` class is the wire this package ships on that engine, and the `createSystemOneJudge` factory returns it behind `JudgeInterface`. It speaks the System One decision protocol at `SYSTEM_ONE_PATH` and sends every question in one call. Wire keys are zero-based positions in the request's question entry order. It maps answers back to the caller's ids, and a missing or invalid answer names the caller's id in its `PROTOCOL` error. Changing only the caller's ids preserves the request bytes. See [Asking a System One server a choice, a noul, and a score](#asking-a-system-one-server-a-choice-a-noul-and-a-score) for the servers it serves and a whole request; see [Writing a judge wire](#writing-a-judge-wire) for a wire of your own.
800
815
 
801
816
  The engine's failures arrive as one error class. A `JudgeError` carries a machine-readable `code` and, for an HTTP failure alone, the response `status`; the `isJudgeError` function narrows a caught value so a caller can branch on the code:
802
817
 
@@ -1565,53 +1580,63 @@ The `ledgers` module serves a conversation through event-sourced records: the `L
1565
1580
 
1566
1581
  The following table lists the types the ledger declares, each with its shape:
1567
1582
 
1568
- | Name | Kind | Signature | Summary |
1569
- | ------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1570
- | `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]` | Names the category the ledger files a message under, one of `LEDGER_CATEGORIES`. |
1571
- | `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }` | Carries the wording of every question the ledger asks its judge. |
1572
- | `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }` | Carries the probability cutoff of each reading the ledger takes from its judge. |
1573
- | `LedgerTopic` | interface | `{ name, criterion, requested? }` | Carries one desk topic: the subject the ledger asks its judge about for statements and, when enabled, requests. |
1574
- | `LedgerShare` | interface | `{ prompt, tail }` | Carries the share of the context capacity the prompt can take and the share of that budget the tail can take. |
1575
- | `LedgerNote` | interface | `{ cue, results, repeat, closure }` | Carries the text of each note the ledger writes into its conversation or returns to the model. |
1576
- | `LedgerRecallOptions` | interface | `{ limit? }` | Configures the ledger's `recall` tool. |
1577
- | `LedgerCorrectionOptions` | interface | `{ narrow? }` | Narrows the pair questions the ledger asks about each correction. |
1578
- | `LedgerOwner` | interface | `{ id, names }` | Carries one owner a lookup result names: its id and the names it goes by. |
1579
- | `LedgerLookupResult` | interface | `{ ids, owners }` | Carries what a lookup handler read from one lookup result: the ids it names and the owners among them. |
1580
- | `LedgerLookupHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerLookupResult \| undefined` | Reads one successful lookup result into the ids and owners it names. |
1581
- | `LedgerLookup` | interface | `{ tool, read }` | Carries one application lookup: the tool the model calls and the handler that reads its results. |
1582
- | `LedgerLookupFinding` | interface | `{ id, name, arguments, text, result }` | Carries one successful lookup result as the ledger read it. |
1583
- | `LedgerLookupState` | type | `'failed' \| 'empty' \| 'shown' \| 'hidden'` | Names what became of a lookup of an earlier request, as the tail stub of its result reports it. |
1584
- | `LedgerRegistry` | interface | `{ ids, owners }` | Carries the ids the ledger's lookups named and the owners among them. |
1585
- | `LedgerIndex` | interface | `{ ids, aliases, carriers, names, words, keys, ranks }` | Carries a registry prepared for matching: its ids, each owner name's owners, and the compiled needles. |
1586
- | `LedgerGauge` | interface | `{ scale, overhead }` | Carries the price of a prompt in tokens, measured against the model the ledger serves. |
1587
- | `LedgerAgentOptions` | type | `Pick<AgentOptions, 'limit' \| 'timeout' \| 'on' \| 'scheduler' \| 'instructions' \| 'skills' \| 'memos' \| 'workspaces' \| 'strict'>` | Selects the agent bounds, hooks, scheduler, and context libraries a ledger passes through to the agent it builds. |
1588
- | `LedgerOptions` | interface | `{ judge, system, topics, questions, thresholds, capacity, predict?, think?, gauge?, lookups?, share?, recall?, correction?, agent?, snapshot? }` | Configures a ledger: its judge and the wording and cutoffs it files with, the desk topics, the context capacity, and the optional first-pass thinking, lookups, gauge, shares, snapshot, recall limit, correction filter, and agent options. |
1589
- | `LedgerSnapshot` | interface | `{ conversation, requests, notes, failures, gauge? }` | Holds the JSON-serializable state a ledger hydrates from: its conversation and the message ids it marked. |
1590
- | `LedgerResult` | interface | `{ passes, attempts }` | Carries the outcome of one request a ledger served: the agent result of its reply and every pass it took. |
1591
- | `LedgerInterface` | interface | `{ agent, conversation, gauge, respond(), calibrate(), snapshot() }` | Serves the requests of one conversation through an agent whose prompt the ledger projects from what the judge filed. |
1592
- | `LedgerRequestInterface` | interface | `{ fault(), faulted(), message, plan, selection, boundary, usage, calls, attempts, enter(), open(), adopt(), observe(), spend(), think(), file(), admit(), recall(), close(), list(), lines() }` | Holds what one `respond` call of a ledger keeps while it serves its request: the request message, the filing attempts and the plan its selections produced, the gauge calls of its passes, and its repeat and recall stops. |
1593
- | `LedgerWordSet` | interface | `{ words, names }` | Carries the lowercase words and non-opening capitalized names of a message. |
1594
- | `LedgerClassification` | interface | `{ quiet, categories, topics, amendments, supersessions }` | Carries the ledger's filing of its conversation's messages, keyed by message id. |
1595
- | `LedgerLine` | interface | `{ text, source, sentence, party?, topics, role }` | Carries one record line: a sentence of a live message, verbatim except that a sentence that opens with a pronoun opens with its party and a colon. |
1596
- | `LedgerRecord` | interface | `{ key, title, members, lines }` | Carries one record: the live messages placed on one owner or on the rules, as lines. |
1597
- | `LedgerAmendment` | interface | `{ earlier, later }` | Identifies an accepted direct message amendment whose sentence scope remains unresolved. |
1598
- | `LedgerRenderContext` | interface | `{ amendments, complete, first, references }` | Supplies accepted amendments and completely included sources for one rendering of the records. |
1599
- | `LedgerProjection` | interface | `{ records, amendments, orphans }` | Carries the records projected from a conversation, accepted amendments, and the live messages no record placed. |
1600
- | `LedgerProjectionInput` | interface | `{ system, exclusions, owners, messages, findings, entities, classification }` | Carries what a projection reads. |
1601
- | `LedgerProjectionRequest` | interface | `{ owners, topics }` | Carries the owners and the desk topics one request names, which select its records. |
1602
- | `LedgerCategoryHandler` | type | `(message: Message) => LedgerCategory \| undefined` | Reads a message's category from its shape, or returns undefined to leave it to the judge. |
1603
- | `LedgerEntityHandler` | type | `(text: string, partial: boolean) => ReadonlySet<string>` | Lists the registry ids and owner ids a text names. |
1604
- | `ClassifierOptions` | interface | `{ strict?, conversation, judge, questions, topics, thresholds, assign, entities, correction?, scheduler? }` | Configures a classifier: the conversation it files, the judge and the wording it asks with, the desk topics, the cutoffs, the ledger's handlers, and the optional correction filter and scheduler. |
1605
- | `ClassifierPhase` | type | `'category' \| 'topic' \| 'amends' \| 'supersedes'` | Names the filing question a classifier asked: a message's category, a message's topic, or an earlier and later message's amendment or supersession. |
1606
- | `ClassifierOutcome` | type | `'cached' \| 'skipped' \| 'resolved' \| 'failed' \| 'aborted'` | Names what became of one filing question. |
1607
- | `ClassifierAttempt` | interface | `{ key, phase, outcome, duration? }` | Carries what became of one filing question: its judgment key, its phase, its outcome, and the time spent resolving it. |
1608
- | `ClassifierResult` | interface | `{ judgments, usage?, attempts, fault?, failure? }` | Carries the judgment keys one classification rests on and the judge usage it spent. |
1609
- | `ClassifierInterface` | interface | `{ classify(), category(), quiet(), decisive(), topics(), classification() }` | Files a conversation's messages through a judge and reads the filing. |
1610
- | `GaugeCall` | interface | `{ estimate, prompt?, completion?, thinking?, tools }` | Carries one agent call as the gauge reads it. |
1611
- | `GaugeOptions` | interface | `{ capacity, predict?, replay? }` | Configures a gauge: its starting price of a prompt and the context capacity it measures against. |
1612
- | `GaugeInterface` | interface | `{ rate(), remainder(), reserve(), room(), observe() }` | Prices prompts in tokens and measures the room a request has left. |
1613
- | `LedgerPlanGroup` | type | `1 \| 2 \| 3` | Names the planning group of a source the records render: a topic match, an off-topic rule or correction, or a name match. |
1614
- | `LedgerErrorCode` | type | `'REQUEST' \| 'THRESHOLD' \| 'SHARE' \| 'CAPACITY' \| 'LIMIT' \| 'TOPIC' \| 'LOOKUP' \| 'GAUGE' \| 'REFERENCE' \| 'SNAPSHOT' \| 'QUESTION'` | Names the machine-readable conditions a `LedgerError` error reports. |
1583
+ | Name | Kind | Signature | Summary |
1584
+ | ------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1585
+ | `LedgerCategory` | type | `(typeof LEDGER_CATEGORIES)[number]` | Names the category the ledger files a message under, one of `LEDGER_CATEGORIES`. |
1586
+ | `LedgerQuestion` | interface | `{ category, topic, amends, supersedes }` | Carries the wording of every question the ledger asks its judge. |
1587
+ | `LedgerThreshold` | interface | `{ category, topic, amends, supersedes, correction }` | Carries the probability cutoff of each reading the ledger takes from its judge. |
1588
+ | `LedgerTopic` | interface | `{ name, criterion, requested? }` | Carries one desk topic: the subject the ledger asks its judge about for statements and, when enabled, requests. |
1589
+ | `LedgerShare` | interface | `{ prompt, tail }` | Carries the share of the context capacity the prompt can take and the share of that budget the tail can take. |
1590
+ | `LedgerNote` | interface | `{ cue, results, repeat, closure }` | Carries the text of each note the ledger writes into its conversation or returns to the model. |
1591
+ | `LedgerRecallOptions` | interface | `{ limit? }` | Configures the ledger's `recall` tool. |
1592
+ | `LedgerCorrectionOptions` | interface | `{ narrow? }` | Narrows the pair questions the ledger asks about each correction. |
1593
+ | `LedgerOwner` | interface | `{ id, names }` | Carries one owner a lookup result names: its id and the names it goes by. |
1594
+ | `LedgerLookupResult` | interface | `{ ids, owners }` | Carries what a lookup handler read from one lookup result: the ids it names and the owners among them. |
1595
+ | `LedgerLookupHandler` | type | `(args: Readonly<Record<string, unknown>>, text: string) => LedgerLookupResult \| undefined` | Reads one successful lookup result into the ids and owners it names. |
1596
+ | `LedgerLookup` | interface | `{ tool, read }` | Carries one application lookup: the tool the model calls and the handler that reads its results. |
1597
+ | `LedgerLookupFinding` | interface | `{ id, name, arguments, text, result }` | Carries one successful lookup result as the ledger read it. |
1598
+ | `LedgerLookupState` | type | `'failed' \| 'empty' \| 'shown' \| 'hidden'` | Names what became of a lookup of an earlier request, as the tail stub of its result reports it. |
1599
+ | `LedgerRegistry` | interface | `{ ids, owners }` | Carries the ids the ledger's lookups named and the owners among them. |
1600
+ | `LedgerIndex` | interface | `{ ids, aliases, carriers, names, words, keys, ranks }` | Carries a registry prepared for matching: its ids, each owner name's owners, and the compiled needles. |
1601
+ | `LedgerGauge` | interface | `{ scale, overhead }` | Carries the price of a prompt in tokens, measured against the model the ledger serves. |
1602
+ | `LedgerAgentOptions` | type | `Pick<AgentOptions, 'limit' \| 'timeout' \| 'on' \| 'scheduler' \| 'instructions' \| 'skills' \| 'memos' \| 'workspaces' \| 'strict'>` | Selects the agent bounds, hooks, scheduler, and context libraries a ledger passes through to the agent it builds. |
1603
+ | `LedgerOptions` | interface | `{ judge, system, topics, questions, thresholds, capacity, predict?, think?, gauge?, lookups?, share?, recall?, correction?, agent?, snapshot? }` | Configures a ledger: its judge and the wording and cutoffs it files with, the desk topics, the context capacity, and the optional first-pass thinking, lookups, gauge, shares, snapshot, recall limit, correction filter, and agent options. |
1604
+ | `LedgerSnapshot` | interface | `{ conversation, requests, notes, failures, gauge?, window? }` | Holds the JSON-serializable state a ledger hydrates from: its conversation and the message ids it marked. |
1605
+ | `LedgerExchangeSnapshot` | interface | `{ request, copy?, reply, lines }` | Carries the sent request text, stored pair ids, and sentence placements of one exchange. |
1606
+ | `LedgerWindowSnapshot` | interface | `{ digest, exchanges, amendments }` | Carries a nonempty exchange window, its message, copy, and receipt checksum, and its accepted edges. |
1607
+ | `LedgerResult` | interface | `{ passes, attempts }` | Carries the outcome of one request a ledger served: the agent result of its reply and every pass it took. |
1608
+ | `LedgerInterface` | interface | `{ agent, conversation, gauge, respond(), calibrate(), snapshot() }` | Serves the requests of one conversation through an agent whose prompt the ledger projects from what the judge filed. |
1609
+ | `LedgerListing` | interface | `{ result, lines, groups, turn }` | Carries a recall result, its accepted whole groups, lookup line translations, and provider-turn position. |
1610
+ | `LedgerRecovery` | interface | `{ digest, omitted }` | Carries the answer note and the partial messages omitted from its prompt. |
1611
+ | `LedgerRequestInterface` | interface | `{ scope, apply(), sent, fault(), faulted(), message, plan, selection, boundary, usage, calls, attempts, enter(), open(), adopt(), observe(), spend(), think(), file(), admit(), recall(), close(), list(), listings, lines() }` | Holds what one `respond` call of a ledger keeps while it serves its request: the request message, the filing attempts and the plan its selections produced, the gauge calls of its passes, and its repeat and recall stops. |
1612
+ | `LedgerWordSet` | interface | `{ words, names }` | Carries the lowercase words and non-opening capitalized names of a message. |
1613
+ | `LedgerClassification` | interface | `{ quiet, categories, topics, amendments, supersessions }` | Carries the ledger's filing of its conversation's messages, keyed by message id. |
1614
+ | `LedgerLine` | interface | `{ text, source, sentence, party?, topics, role }` | Carries one record line: a sentence of a live message, verbatim except that a sentence that opens with a pronoun opens with its party and a colon. |
1615
+ | `LedgerReceipt` | interface | `{ key, title, source, sentence }` | Identifies an original sentence at one record placement. |
1616
+ | `LedgerOccurrence` | interface | `{}` | Carries a rendered sentence with its record placement. |
1617
+ | `LedgerExchange` | interface | `{ request, reply, lines }` | Carries a completed request copy, its stored reply, and the sentences the copy rendered. |
1618
+ | `LedgerDraft` | interface | `{ copy, lines, evidence, window }` | Carries a planned copy and its validity evidence to request settlement. |
1619
+ | `LedgerEvidence` | interface | `{ messages, amendments }` | Captures held message identities and the accepted edges used to validate their copies. |
1620
+ | `LedgerRenderResult` | interface | `{ text, lines }` | Carries rendered record text and its sentences in emission order. |
1621
+ | `LedgerRecord` | interface | `{ key, title, members, lines }` | Carries one record: the live messages placed on one owner or on the rules, as lines. |
1622
+ | `LedgerAmendment` | interface | `{ earlier, later }` | Identifies an accepted direct message amendment whose sentence scope remains unresolved. |
1623
+ | `LedgerRenderContext` | interface | `{ amendments, complete, first, references }` | Supplies accepted amendments and completely included sources for one rendering of the records. |
1624
+ | `LedgerProjection` | interface | `{ records, amendments, orphans }` | Carries the records projected from a conversation, accepted amendments, and the live messages no record placed. |
1625
+ | `LedgerProjectionInput` | interface | `{ system, exclusions, owners, messages, findings, entities, classification }` | Carries what a projection reads. |
1626
+ | `LedgerProjectionRequest` | interface | `{ owners, topics }` | Carries the owners and the desk topics one request names, which select its records. |
1627
+ | `LedgerCategoryHandler` | type | `(message: Message) => LedgerCategory \| undefined` | Reads a message's category from its shape, or returns undefined to leave it to the judge. |
1628
+ | `LedgerEntityHandler` | type | `(text: string, partial: boolean) => ReadonlySet<string>` | Lists the registry ids and owner ids a text names. |
1629
+ | `ClassifierOptions` | interface | `{ strict?, conversation, judge, questions, topics, thresholds, assign, entities, correction?, scheduler? }` | Configures a classifier: the conversation it files, the judge and the wording it asks with, the desk topics, the cutoffs, the ledger's handlers, and the optional correction filter and scheduler. |
1630
+ | `ClassifierPhase` | type | `'category' \| 'topic' \| 'amends' \| 'supersedes'` | Names the filing question a classifier asked: a message's category, a message's topic, or an earlier and later message's amendment or supersession. |
1631
+ | `ClassifierOutcome` | type | `'cached' \| 'skipped' \| 'resolved' \| 'failed' \| 'aborted'` | Names what became of one filing question. |
1632
+ | `ClassifierAttempt` | interface | `{ key, phase, outcome, duration? }` | Carries what became of one filing question: its judgment key, its phase, its outcome, and the time spent resolving it. |
1633
+ | `ClassifierResult` | interface | `{ judgments, usage?, attempts, fault?, failure? }` | Carries the judgment keys one classification rests on and the judge usage it spent. |
1634
+ | `ClassifierInterface` | interface | `{ classify(), category(), quiet(), decisive(), topics(), classification() }` | Files a conversation's messages through a judge and reads the filing. |
1635
+ | `GaugeCall` | interface | `{ estimate, spared?, prompt?, completion?, thinking?, tools }` | Carries one agent call as the gauge reads it. |
1636
+ | `GaugeOptions` | interface | `{ capacity, predict?, replay? }` | Configures a gauge: its starting price of a prompt and the context capacity it measures against. |
1637
+ | `GaugeInterface` | interface | `{ rate(), remainder(), reserve(), room(), observe() }` | Prices prompts in tokens and measures the room a request has left. |
1638
+ | `LedgerPlanGroup` | type | `1 \| 2 \| 3` | Names the planning group of a source the records render: a topic match, an off-topic rule or correction, or a name match. |
1639
+ | `LedgerErrorCode` | type | `'REQUEST' \| 'THRESHOLD' \| 'SHARE' \| 'CAPACITY' \| 'LIMIT' \| 'TOPIC' \| 'LOOKUP' \| 'GAUGE' \| 'REFERENCE' \| 'SNAPSHOT' \| 'QUESTION'` | Names the machine-readable conditions a `LedgerError` error reports. |
1615
1640
 
1616
1641
  #### Constants
1617
1642
 
@@ -1625,6 +1650,7 @@ The following table lists the constants that hold the ledger's categories, recor
1625
1650
  | `PLACED_CATEGORIES` | const | `readonly LedgerCategory[]` | Lists the categories that place a message no owner claims on the rules record. |
1626
1651
  | `LEDGER_RULES_KEY` | const | `"rules"` | Names the key of the record that holds the rules no owner claims. |
1627
1652
  | `LEDGER_OWNER_PREFIX` | const | `"owner:"` | Prefixes the key of an owner's record, which the owner's id follows. |
1653
+ | `LEDGER_RECALL_LABELS` | const | `Readonly<{ request: "Earlier request:"; reply: "Earlier reply:"; }>` | Labels recalled conversation text by its origin. |
1628
1654
  | `LEDGER_QUESTIONS` | const | `LedgerQuestion` | Supplies the wording of every question the ledger asks its judge. |
1629
1655
  | `LEDGER_NOTES` | const | `LedgerNote` | Supplies the text of each ledger note, worded for a model that answers in its final message. |
1630
1656
  | `DEFAULT_LEDGER_SHARE` | const | `LedgerShare` | Supplies the default prompt and tail shares. |
@@ -1667,61 +1693,72 @@ The following table lists the classes that serve, file, and price a conversation
1667
1693
 
1668
1694
  The following guards validate ledger fractions, capacity, and snapshots:
1669
1695
 
1670
- | Name | Kind | Signature | Summary |
1671
- | ------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1672
- | `isFraction` | function | `(value: unknown) => value is number` | Checks whether a value is finite and lies in the interval (0, 1\]. |
1673
- | `isLedgerQuestion` | function | `(value: unknown) => value is LedgerQuestion` | Checks whether a value holds the wording a ledger files with: a choice `category` question whose criteria describe every category, a non-empty `topic` string, and noul `amends` and `supersedes` questions. |
1674
- | `ledgerSnapshotShape` | const | `import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; sections: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; summary: import("@orkestrel/contract").StringShape; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; judgments: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; answer: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; probabilities: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; probabilities: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; noul: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>]>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; refusal: import("@orkestrel/contract").ObjectShape<{ missing: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>; }, boolean \| ContractShape>]>>>; }, boolean \| ContractShape>; requests: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; notes: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; failures: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; gauge: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ scale: import("@orkestrel/contract").NumberShape; overhead: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a ledger snapshot exactly: an unknown key refuses, so a key a later version adds never reads as absent. |
1675
- | `ledgerSnapshotContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ conversation: Readonly<{ id: string; sections: readonly Readonly<{ id: string; summary: string; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & {}>[]; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & { judgments?: readonly (Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; answer: Readonly<{ form: "choice"; probabilities: { readonly [k: string]: number; }; } & {}> \| Readonly<{ form: "score"; probabilities: readonly number[]; } & {}> \| Readonly<{ form: "noul"; noul: number; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }> \| Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; refusal: Readonly<{ missing: readonly string[]; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }>)[]; }>; requests: readonly string[]; notes: readonly string[]; failures: readonly string[]; } & { gauge?: Readonly<{ scale: number; overhead: number; } & {}>; }>>` | Reads the faults of a refused ledger snapshot. |
1676
- | `isPositiveSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a positive safe integer. |
1677
- | `isLedgerSnapshot` | function | `(value: unknown) => value is LedgerSnapshot` | Checks whether a value is a ledger snapshot whose marked ids name messages of its own conversation. |
1696
+ | Name | Kind | Signature | Summary |
1697
+ | ------------------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1698
+ | `isFraction` | function | `(value: unknown) => value is number` | Checks whether a value is finite and lies in the interval (0, 1\]. |
1699
+ | `isLedgerQuestion` | function | `(value: unknown) => value is LedgerQuestion` | Checks whether a value holds the wording a ledger files with: a choice `category` question whose criteria describe every category, a non-empty `topic` string, and noul `amends` and `supersedes` questions. |
1700
+ | `ledgerWindowShape` | const | `import("@orkestrel/contract").ObjectShape<{ digest: import("@orkestrel/contract").StringShape; exchanges: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ request: import("@orkestrel/contract").StringShape; copy: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; reply: import("@orkestrel/contract").StringShape; lines: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ key: import("@orkestrel/contract").StringShape; title: import("@orkestrel/contract").StringShape; source: import("@orkestrel/contract").StringShape; sentence: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; amendments: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ earlier: import("@orkestrel/contract").StringShape; later: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes the minimal serialized evidence of a nonempty exchange window. |
1701
+ | `ledgerWindowContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ digest: string; exchanges: readonly Readonly<{ request: string; reply: string; lines: readonly Readonly<{ key: string; title: string; source: string; sentence: number; } & {}>[]; } & { copy?: string; }>[]; amendments: readonly Readonly<{ earlier: string; later: string; } & {}>[]; } & {}>>` | Reads structural faults of a serialized exchange window. |
1702
+ | `ledgerSnapshotShape` | const | `import("@orkestrel/contract").ObjectShape<{ conversation: import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; sections: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; summary: import("@orkestrel/contract").StringShape; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; messages: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; role: import("@orkestrel/contract").LiteralShape<readonly ["system", "user", "assistant", "tool"]>; content: import("@orkestrel/contract").StringShape; calls: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; name: import("@orkestrel/contract").StringShape; arguments: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>; }, boolean \| ContractShape>>>; call: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; images: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>>; thinking: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>>; judgments: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; answer: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; probabilities: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; probabilities: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NumberShape>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; noul: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>]>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ id: import("@orkestrel/contract").StringShape; question: import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["choice"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["score"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").NullableShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>>; }, boolean \| ContractShape>, import("@orkestrel/contract").ObjectShape<{ form: import("@orkestrel/contract").LiteralShape<readonly ["noul"]>; instructions: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; criteria: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ true: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; false: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").UnionShape<readonly [import("@orkestrel/contract").StringShape, import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").JSONShape>, import("@orkestrel/contract").ObjectShape<Record<never, never>, import("@orkestrel/contract").JSONShape>]>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>]>; model: import("@orkestrel/contract").StringShape; sources: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; state: import("@orkestrel/contract").StringShape; time: import("@orkestrel/contract").NumberShape; usage: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ prompt: import("@orkestrel/contract").NumberShape; completion: import("@orkestrel/contract").NumberShape; total: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; refusal: import("@orkestrel/contract").ObjectShape<{ missing: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; }, boolean \| ContractShape>; }, boolean \| ContractShape>]>>>; }, boolean \| ContractShape>; requests: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; notes: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; failures: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").StringShape>; gauge: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ scale: import("@orkestrel/contract").NumberShape; overhead: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; window: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").ObjectShape<{ digest: import("@orkestrel/contract").StringShape; exchanges: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ request: import("@orkestrel/contract").StringShape; copy: import("@orkestrel/contract").OptionalShape<import("@orkestrel/contract").StringShape>; reply: import("@orkestrel/contract").StringShape; lines: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ key: import("@orkestrel/contract").StringShape; title: import("@orkestrel/contract").StringShape; source: import("@orkestrel/contract").StringShape; sentence: import("@orkestrel/contract").NumberShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; amendments: import("@orkestrel/contract").ArrayShape<import("@orkestrel/contract").ObjectShape<{ earlier: import("@orkestrel/contract").StringShape; later: import("@orkestrel/contract").StringShape; }, boolean \| ContractShape>>; }, boolean \| ContractShape>>; }, boolean \| ContractShape>` | Describes a ledger snapshot exactly: an unknown key refuses, so a key a later version adds never reads as absent. |
1703
+ | `ledgerSnapshotContract` | const | `import("@orkestrel/contract").ContractInterface<Readonly<{ conversation: Readonly<{ id: string; sections: readonly Readonly<{ id: string; summary: string; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & {}>[]; messages: readonly Readonly<{ id: string; role: "assistant" \| "system" \| "tool" \| "user"; content: string; } & { calls?: readonly Readonly<{ id: string; name: string; arguments: { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; } & {}>[]; call?: string; images?: readonly string[]; thinking?: string; }>[]; } & { judgments?: readonly (Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; answer: Readonly<{ form: "choice"; probabilities: { readonly [k: string]: number; }; } & {}> \| Readonly<{ form: "score"; probabilities: readonly number[]; } & {}> \| Readonly<{ form: "noul"; noul: number; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }> \| Readonly<{ id: string; question: Readonly<{ form: "choice"; criteria: { readonly [k: string]: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null; }; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "score"; criteria: readonly (string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; } \| null)[]; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }> \| Readonly<{ form: "noul"; } & { instructions?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; criteria?: Readonly<{} & { true?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; false?: string \| readonly import("@orkestrel/contract").JSONValue[] \| { readonly [k: string]: import("@orkestrel/contract").JSONValue; }; }>; }>; model: string; sources: readonly string[]; state: string; time: number; refusal: Readonly<{ missing: readonly string[]; } & {}>; } & { usage?: Readonly<{ prompt: number; completion: number; total: number; } & {}>; }>)[]; }>; requests: readonly string[]; notes: readonly string[]; failures: readonly string[]; } & { gauge?: Readonly<{ scale: number; overhead: number; } & {}>; window?: Readonly<{ digest: string; exchanges: readonly Readonly<{ request: string; reply: string; lines: readonly Readonly<{ key: string; title: string; source: string; sentence: number; } & {}>[]; } & { copy?: string; }>[]; amendments: readonly Readonly<{ earlier: string; later: string; } & {}>[]; } & {}>; }>>` | Reads structural faults of a ledger snapshot, including its optional held exchange window. |
1704
+ | `isPositiveSafeInteger` | function | `(value: unknown) => value is number` | Checks whether a value is a positive safe integer. |
1705
+ | `isLedgerWindowSnapshot` | function | `(value: unknown) => value is LedgerWindowSnapshot` | Checks whether a value has the exact shape of a nonempty exchange window. |
1706
+ | `isLedgerSnapshot` | function | `(value: unknown) => value is LedgerSnapshot` | Checks whether a value is a ledger snapshot whose marked ids name messages of its own conversation. |
1678
1707
 
1679
1708
  #### Helpers
1680
1709
 
1681
- The following table lists the pure helpers that read text, project and select records, render the records, and fit a price:
1682
-
1683
- | Name | Kind | Signature | Summary |
1684
- | -------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
1685
- | `splitSentences` | function | `(text: string) => readonly string[]` | Splits a message into its sentences. |
1686
- | `collectNames` | function | `(text: string) => readonly string[]` | Collects the capitalized name runs of a text, leaving out the run that opens each sentence. |
1687
- | `identifyLookup` | function | `(name: string, args: Readonly<Record<string, unknown>>) => string \| undefined` | Identifies a lookup finding for projection by its tool name and normalized arguments. |
1688
- | `linkOwners` | function | `(findings: readonly LedgerLookupFinding[], owners: ReadonlyMap<string, readonly string[]>) => ReadonlyMap<string, string>` | Links each id-shaped lookup argument to its owner. |
1689
- | `collectRegistry` | function | `(findings: readonly LedgerLookupFinding[]) => LedgerRegistry` | Collects the ids and the owner names the lookup findings named. |
1690
- | `buildLedgerIndex` | function | `(registry: LedgerRegistry) => LedgerIndex` | Builds a registry's matching index: each name's owners, each word's carriers, the needles, keys, and ranks. |
1691
- | `matchEntities` | function | `(index: LedgerIndex, text: string, partial: boolean) => ReadonlySet<string>` | Matches the registry ids and owners a text names. |
1692
- | `normalizeWord` | function | `(word: string) => string` | Normalizes a run of letters and digits to the one form each of its cases folds to. |
1693
- | `buildRecords` | function | `(input: LedgerProjectionInput) => LedgerProjection` | Projects the owner records and the rules record from a conversation's messages. |
1694
- | `selectRecords` | function | `(projection: LedgerProjection, request: LedgerProjectionRequest) => readonly LedgerRecord[]` | Selects a request's records, collapsing owners with equal ordered member ids under titles joined with `; `. |
1695
- | `findLedgerCall` | function | `(group: readonly Message[], message: Message) => ToolCall \| undefined` | Finds the call that owns a tool message within a collected tool group. |
1696
- | `collectProjectionIds` | function | `(projection: LedgerProjection) => ReadonlySet<string>` | Collects the live message ids placed in records or left without a record. |
1697
- | `scanAmendments` | function | `(amendments: ReadonlyMap<string, readonly string[]>, start: string, admit: (id: string) => boolean) => readonly string[]` | Scans admitted amendments in breadth-first order without revisiting a message. |
1698
- | `buildRecallMessage` | function | `(topic: string) => Message` | Builds the placeholder assistant recall call used to price recall framing. |
1699
- | `buildRequestMessage` | function | `(request: Message, records: string) => Message` | Builds the copy of a request turn that carries the rendered records ahead of the request. |
1700
- | `renderTopicNames` | function | `(topics: readonly LedgerTopic[]) => string` | Renders topic names as a comma-separated list in their supplied order. |
1701
- | `renderCauseChain` | function | `(error: unknown) => string` | Renders an error and its causes, stopping after 4 entries. |
1702
- | `extractWords` | function | `(message: Message) => LedgerWordSet` | Extracts lowercase words and capitalized names that do not open a sentence. |
1703
- | `splitWords` | function | `(part: string) => readonly string[]` | Splits a topic part into lowercase words with surrounding punctuation removed. |
1704
- | `rankLedgerCut` | function | `(group: LedgerPlanGroup, unsettled: boolean, category: LedgerCategory \| undefined) => number` | Ranks a source the records render for removal before the next prompt. |
1705
- | `findLedgerCut` | function | `<T>(low: number, high: number, probe: (cut: number) => T \| undefined, found?: T) => T \| undefined` | Finds the first cut in a range whose probe returns a value, by bisection. |
1706
- | `buildLedgerCut` | function | `(steps: ReadonlyArray<LedgerLine \| string>, records: readonly LedgerRecord[], included: ReadonlySet<string>) => { readonly records: readonly LedgerRecord[]; readonly included: ReadonlySet<string>; }` | Builds the cut the given steps leave: each step drops the line it is, by identity, or the source it names. |
1707
- | `renderLedgerRecord` | function | `(record: Pick<LedgerRecord, 'title' \| 'lines'>, context?: LedgerRenderContext) => string` | Renders one record as a heading and one list item per line. |
1708
- | `renderLedgerPinned` | function | `(record: Pick<LedgerRecord, 'title' \| 'lines'>, context?: LedgerRenderContext) => string` | Renders one owner record under a `###` heading, which the records nest under their one `## Records` heading. |
1709
- | `splitTopic` | function | `(topic: string) => readonly string[]` | Splits a recall topic at its joints. |
1710
- | `cutListing` | function | `(entries: readonly string[], room: number) => string` | Cuts entries to a room and names how many it left out. |
1711
- | `matchesCutLine` | function | `(line: string) => boolean` | Checks whether a line is the cut line `cutListing` writes. |
1712
- | `normalizeArgument` | function | `(value: string) => string` | Normalizes a lookup argument string to the spelling that lookup identity and owner linking compare. |
1713
- | `splitResultLines` | function | `(text: string) => readonly string[]` | Splits a tool result into its lines at each line feed, with or without a carriage return before it. |
1714
- | `renderLookupCall` | function | `(name: string, args: Readonly<Record<string, unknown>>) => string` | Renders a lookup call as its tool name and its JSON arguments. |
1715
- | `renderStub` | function | `(name: string, args: Readonly<Record<string, unknown>>, state: LedgerLookupState) => string` | Renders the tail stub of a lookup result from an earlier request. |
1716
- | `computeThinking` | function | `(message: Pick<Message, 'thinking' \| 'content' \| 'calls'>, completion: number) => number` | Computes the completion tokens attributable to a message's thinking. |
1717
- | `resolvePredict` | function | `(predict: number \| undefined, capacity: number) => number` | Resolves the generation cap and checks it against the context capacity. |
1718
- | `fitSlope` | function | `(groups: ReadonlyArray<readonly GaugeCall[]>) => number \| undefined` | Fits the marginal tokens one estimate unit adds within a request. |
1719
- | `collectLive` | function | `(input: LedgerProjectionInput) => readonly string[]` | Collects the ids of the live messages in conversation order. |
1720
- | `placeMember` | function | `(input: LedgerProjectionInput, links: ReadonlyMap<string, string>, amended: ReadonlyMap<string, readonly string[]>, id: string, seen: ReadonlySet<string>, settled?: Map<string, ReadonlySet<string>>) => ReadonlySet<string>` | Places a message on the record keys it joins. |
1721
- | `buildLedgerRenderContext` | function | `(messages: readonly Message[], lines: readonly LedgerLine[], amendments: readonly LedgerAmendment[]) => LedgerRenderContext` | Derives complete source identities, first occurrences, and local references from the actual lines of the records. |
1722
- | `renderLedgerAnnotation` | function | `(line: LedgerLine, context: LedgerRenderContext) => string` | Renders a source's reference and its later changes at the source's first retained line. |
1723
- | `collectAmendments` | function | `(input: LedgerProjectionInput, byId: ReadonlyMap<string, Message>, live: readonly string[]) => readonly LedgerAmendment[]` | Collects accepted direct amendments of live messages. |
1724
- | `buildLines` | function | `(input: LedgerProjectionInput, byId: ReadonlyMap<string, Message>, id: string, holders: readonly string[], system: readonly string[]) => readonly LedgerLine[]` | Builds the record lines of one message. |
1710
+ The following table lists the pure helpers that read text, project and select records, render the records, fit a price, and hold the window:
1711
+
1712
+ | Name | Kind | Signature | Summary |
1713
+ | -------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1714
+ | `splitSentences` | function | `(text: string) => readonly string[]` | Splits a message into its sentences. |
1715
+ | `collectNames` | function | `(text: string) => readonly string[]` | Collects the capitalized name runs of a text, leaving out the run that opens each sentence. |
1716
+ | `identifyLookup` | function | `(name: string, args: Readonly<Record<string, unknown>>) => string \| undefined` | Identifies a lookup finding for projection by its tool name and normalized arguments. |
1717
+ | `linkOwners` | function | `(findings: readonly LedgerLookupFinding[], owners: ReadonlyMap<string, readonly string[]>) => ReadonlyMap<string, string>` | Links each id-shaped lookup argument to its owner. |
1718
+ | `collectRegistry` | function | `(findings: readonly LedgerLookupFinding[]) => LedgerRegistry` | Collects the ids and the owner names the lookup findings named. |
1719
+ | `buildLedgerIndex` | function | `(registry: LedgerRegistry) => LedgerIndex` | Builds a registry's matching index: each name's owners, each word's carriers, the needles, keys, and ranks. |
1720
+ | `matchEntities` | function | `(index: LedgerIndex, text: string, partial: boolean) => ReadonlySet<string>` | Matches the registry ids and owners a text names. |
1721
+ | `normalizeWord` | function | `(word: string) => string` | Normalizes a run of letters and digits to the one form each of its cases folds to. |
1722
+ | `buildRecords` | function | `(input: LedgerProjectionInput) => LedgerProjection` | Projects the owner records and the rules record from a conversation's messages. |
1723
+ | `selectRecords` | function | `(projection: LedgerProjection, request: LedgerProjectionRequest) => readonly LedgerRecord[]` | Selects a request's records, collapsing owners with equal ordered member ids under titles joined with `; `. |
1724
+ | `findLedgerCall` | function | `(group: readonly Message[], message: Message) => ToolCall \| undefined` | Finds the call that owns a tool message within a collected tool group. |
1725
+ | `collectProjectionIds` | function | `(projection: LedgerProjection) => ReadonlySet<string>` | Collects the live message ids placed in records or left without a record. |
1726
+ | `scanAmendments` | function | `(amendments: ReadonlyMap<string, readonly string[]>, start: string, admit: (id: string) => boolean) => readonly string[]` | Scans admitted amendments in breadth-first order without revisiting a message. |
1727
+ | `buildRecallMessage` | function | `(topic: string) => Message` | Builds the placeholder assistant recall call used to price recall framing. |
1728
+ | `buildRequestMessage` | function | `(request: Message, records: string) => Message` | Builds the copy of a request turn that carries the rendered records ahead of the request. |
1729
+ | `renderTopicNames` | function | `(topics: readonly LedgerTopic[]) => string` | Renders topic names as a comma-separated list in their supplied order. |
1730
+ | `renderCauseChain` | function | `(error: unknown) => string` | Renders an error and its causes, stopping after 4 entries. |
1731
+ | `extractWords` | function | `(message: Message) => LedgerWordSet` | Extracts lowercase words and capitalized names that do not open a sentence. |
1732
+ | `splitWords` | function | `(part: string) => readonly string[]` | Splits a topic part into lowercase words with surrounding punctuation removed. |
1733
+ | `rankLedgerCut` | function | `(group: LedgerPlanGroup, unsettled: boolean, category: LedgerCategory \| undefined) => number` | Ranks a source the records render for removal before the next prompt. |
1734
+ | `findLedgerCut` | function | `<T>(low: number, high: number, probe: (cut: number) => T \| undefined, found?: T) => T \| undefined` | Finds the first cut in a range whose probe returns a value, by bisection. |
1735
+ | `buildLedgerCut` | function | `(steps: ReadonlyArray<LedgerLine \| string>, records: readonly LedgerRecord[], included: ReadonlySet<string>) => { readonly records: readonly LedgerRecord[]; readonly included: ReadonlySet<string>; }` | Builds the cut the given steps leave: each step drops the line it is, by identity, or the source it names. |
1736
+ | `renderLedgerRecord` | function | `(record: Pick<LedgerRecord, 'title' \| 'lines'>, context?: LedgerRenderContext) => string` | Renders one record as a heading and one list item per line. |
1737
+ | `renderLedgerPinned` | function | `(record: Pick<LedgerRecord, 'title' \| 'lines'>, context?: LedgerRenderContext) => string` | Renders one owner record under a `###` heading, which the records nest under their one `## Records` heading. |
1738
+ | `splitTopic` | function | `(topic: string) => readonly string[]` | Splits a recall topic at its joints. |
1739
+ | `cutListing` | function | `(entries: readonly string[], room: number, kind?: 'older' \| 'more', first?: boolean) => string` | Cuts entries to a room and names how many it left out. |
1740
+ | `matchesCutLine` | function | `(line: string) => boolean` | Checks whether a line is the cut line `cutListing` writes. |
1741
+ | `normalizeArgument` | function | `(value: string) => string` | Normalizes a lookup argument string to the spelling that lookup identity and owner linking compare. |
1742
+ | `splitResultLines` | function | `(text: string) => readonly string[]` | Splits a tool result into its lines at each line feed, with or without a carriage return before it. |
1743
+ | `renderLookupCall` | function | `(name: string, args: Readonly<Record<string, unknown>>) => string` | Renders a lookup call as its tool name and its JSON arguments. |
1744
+ | `renderStub` | function | `(name: string, args: Readonly<Record<string, unknown>>, state: LedgerLookupState) => string` | Renders the tail stub of a lookup result from an earlier request. |
1745
+ | `computeThinking` | function | `(message: Pick<Message, 'thinking' \| 'content' \| 'calls'>, completion: number) => number` | Computes the completion tokens attributable to a message's thinking. |
1746
+ | `resolvePredict` | function | `(predict: number \| undefined, capacity: number) => number` | Resolves the generation cap and checks it against the context capacity. |
1747
+ | `fitSlope` | function | `(groups: ReadonlyArray<readonly GaugeCall[]>) => number \| undefined` | Fits the marginal tokens one estimate unit adds within a request. |
1748
+ | `collectLive` | function | `(input: LedgerProjectionInput) => readonly string[]` | Collects the ids of the live messages in conversation order. |
1749
+ | `placeMember` | function | `(input: LedgerProjectionInput, links: ReadonlyMap<string, string>, amended: ReadonlyMap<string, readonly string[]>, id: string, seen: ReadonlySet<string>, settled?: Map<string, ReadonlySet<string>>) => ReadonlySet<string>` | Places a message on the record keys it joins. |
1750
+ | `buildLedgerRenderContext` | function | `(messages: readonly Message[], lines: readonly LedgerLine[], amendments: readonly LedgerAmendment[]) => LedgerRenderContext` | Derives complete source identities, first occurrences, and local references from the actual lines of the records. |
1751
+ | `renderLedgerAnnotation` | function | `(line: LedgerLine, context: LedgerRenderContext) => string` | Renders a source's reference and its later changes at the source's first retained line. |
1752
+ | `collectAmendments` | function | `(input: LedgerProjectionInput, byId: ReadonlyMap<string, Message>, live: readonly string[]) => readonly LedgerAmendment[]` | Collects accepted amendments of live messages, following superseded amenders to live successors. |
1753
+ | `buildLines` | function | `(input: LedgerProjectionInput, byId: ReadonlyMap<string, Message>, id: string, holders: readonly string[], system: readonly string[]) => readonly LedgerLine[]` | Builds the record lines of one message. |
1754
+ | `collectRecallMessages` | function | `(input: LedgerProjectionInput, requests: ReadonlySet<string>, notes: ReadonlySet<string>) => readonly Message[]` | Collects stored messages eligible to open the recall offer. |
1755
+ | `hasHiddenRecall` | function | `(input: LedgerProjectionInput, request: string, requests: ReadonlySet<string>, notes: ReadonlySet<string>, messages: readonly Message[], lines: readonly LedgerReceipt[]) => boolean` | Checks whether an eligible earlier message is absent from the prompt or incompletely covered. A successful finding is held when a finding with the same canonical identity and text is fully received. |
1756
+ | `matchesLookup` | function | `(left: LedgerLookupFinding, right: LedgerLookupFinding) => boolean` | Checks whether two successful findings carry the same text for the same canonical lookup. |
1757
+ | `digestLedgerWindow` | function | `(exchanges: readonly LedgerExchangeSnapshot[], messages: readonly Message[]) => string \| undefined` | Digests held messages, lookup call context, stored copies, and sentence receipts using canonical text. This non-cryptographic checksum detects host edits and makes no security claim. |
1758
+ | `buildLedgerLineKey` | function | `(line: Pick<LedgerOccurrence, 'key' \| 'title' \| 'source' \| 'sentence'>) => string` | Encodes a sentence's record placement without comparing rendered text. |
1759
+ | `collectLedgerLines` | function | `(record: LedgerRecord, held: ReadonlySet<string>) => readonly LedgerOccurrence[]` | Collects the record's sentence receipts not already held by a window. |
1760
+ | `collectLedgerReplies` | function | `(messages: readonly Message[], requests: ReadonlySet<string>, notes: ReadonlySet<string>) => ReadonlyMap<string, Message>` | Selects each marked request's unambiguous final call-free reply. |
1761
+ | `collectLedgerEvidence` | function | `(messages: readonly Message[], sources: ReadonlySet<string>, amendments: readonly LedgerAmendment[]) => LedgerEvidence` | Captures source bytes and direct amendment edges for a held window. |
1725
1762
 
1726
1763
  The `Classifier` and `Gauge` classes the ledger composes are public, so a harness can file a conversation or price a prompt without a ledger. The following classifier files one rule, and the following gauge prices the calls of one request:
1727
1764
 
@@ -1833,10 +1870,10 @@ The seams a judge wire fills, beneath the boundary method it inherits. `AgentJud
1833
1870
 
1834
1871
  The System One wire over `AgentJudge`: it fills both seams and inherits `ask` from the engine, so a caller drives it through `JudgeInterface` like any judge. Its `name` reports `'systemone'` and stays a data member.
1835
1872
 
1836
- | Method | Returns | Summary |
1837
- | -------- | ------------------ | --------------------------------------------------------------------------------------- |
1838
- | `encode` | `SystemOneRequest` | Projects the state and questions onto the System One request with the configured model. |
1839
- | `read` | `JudgeResult` | Decodes requested System One answers and reports the server model and available usage. |
1873
+ | Method | Returns | Summary |
1874
+ | -------- | ------------------ | ----------------------------------------------------------------------------------------------------------- |
1875
+ | `encode` | `SystemOneRequest` | Projects the state and questions onto the System One request with the configured model and positional keys. |
1876
+ | `read` | `JudgeResult` | Decodes positional System One answers under caller ids and reports the server model and available usage. |
1840
1877
 
1841
1878
  #### `ThinkSplitterInterface`
1842
1879
 
@@ -2004,6 +2041,8 @@ The unbounded async channel. A producer writes with `push` and ends it with `clo
2004
2041
 
2005
2042
  Concurrent `drain` readers share one buffer: each value goes to exactly one reader, and `close` or `fail` ends every reader. A `push` after `close` or `fail` is buffered rather than refused, so a later `drain` yields it before reporting the end.
2006
2043
 
2044
+ A channel retains at most its newest consumed value until the next push. A paused reader holds only the value it took, not the remaining queue. Unread values remain buffered without a bound.
2045
+
2007
2046
  Buffered values are always delivered before the end is reported, so a `close` or `fail` arriving alongside the last values still hands them over first:
2008
2047
 
2009
2048
  ```ts
@@ -2155,12 +2194,13 @@ The conversation ledger. The `respond` method serves one request through to its
2155
2194
 
2156
2195
  #### `LedgerRequestInterface`
2157
2196
 
2158
- The state of one `respond` call. The ledger creates one request per call and drops it when the call settles, so no request state reaches a later call or a run no call owns. Each agent run the call makes is a pass: the `open` method starts one, and the `selection`, `boundary`, and `usage` data members read the current pass. The `message`, `plan`, `selection`, `boundary`, `usage`, `calls`, and `attempts` data members stay Surface rows.
2197
+ The state of one `respond` call. The ledger creates one request per call and drops it when the call settles, so no request state reaches a later call or a run no call owns. Each agent run the call makes is a pass: the `open` method starts one, and the `selection`, `boundary`, and `usage` data members read the current pass. The `scope`, `sent`, `message`, `plan`, `selection`, `boundary`, `usage`, `calls`, and `attempts` data members stay Surface rows. The `apply(scope)` method records the scope applied by the plan for conditional restoration when the call settles.
2159
2198
 
2160
2199
  | Method | Returns | Summary |
2161
2200
  | --------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
2162
2201
  | `enter` | `Message` | Appends the request's content to a conversation as a user message, once, and holds it as `message`. |
2163
2202
  | `open` | `void` | Opens a pass, which becomes the current pass. |
2203
+ | `apply` | `void` | Records the scope applied by the ledger's plan for conditional restoration at settle. |
2164
2204
  | `fault` | `void` | Records an error the request's run reported through its `fault` event. |
2165
2205
  | `faulted` | `boolean` | Reports whether the request's run reported this error through its `fault` event. |
2166
2206
  | `adopt` | `void` | Records the selection the current pass's run adopted and adds the usage it spent. |
@@ -2216,18 +2256,18 @@ request.lines('Refunds over $100 need a manager.') // undefined — no recall re
2216
2256
 
2217
2257
  The ledger's filing engine. The `classify` method asks the judge what the conversation's recorded judgments lack, and the readers derive every answer from those judgments and the cutoffs. It carries no data members.
2218
2258
 
2219
- | Method | Returns | Summary |
2220
- | ---------------- | ----------------------------- | ------------------------------------------------------------------------------------------------ |
2221
- | `classify` | `Promise<ClassifierResult>` | Asks every filing question the conversation's judgments lack an answer for. |
2222
- | `category` | `LedgerCategory \| undefined` | Returns the category a message is filed under, or undefined when no category reaches its cutoff. |
2223
- | `quiet` | `boolean` | Returns true if the message is filed as quiet; false otherwise. |
2224
- | `decisive` | `boolean` | Returns true if the message is filed as decisive; false otherwise. |
2225
- | `topics` | `ReadonlySet<string>` | Returns the desk topics the message is filed under. |
2226
- | `classification` | `LedgerClassification` | Returns the filing of every message in the conversation. |
2259
+ | Method | Returns | Summary |
2260
+ | ---------------- | ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
2261
+ | `classify` | `Promise<ClassifierResult>` | Asks every filing question the conversation's judgments lack an answer for. |
2262
+ | `category` | `LedgerCategory \| undefined` | Returns the assigned or recorded category, or undefined when no category reaches its cutoff or the user literal floor suppresses a quiet winner. |
2263
+ | `quiet` | `boolean` | Returns true for a quiet assignment or a recorded quiet weight at the cutoff, except for a user message carrying an id or number; false otherwise. |
2264
+ | `decisive` | `boolean` | Returns true if the message is filed as decisive; false otherwise. |
2265
+ | `topics` | `ReadonlySet<string>` | Returns the desk topics the message is filed under. |
2266
+ | `classification` | `LedgerClassification` | Returns the filing of every message in the conversation. |
2227
2267
 
2228
2268
  #### `GaugeInterface`
2229
2269
 
2230
- The prompt price. The `rate`, `remainder`, `reserve`, and `room` methods read the calls of the request in progress, and the `observe` method folds a finished request in. The `scale` and `overhead` data members stay Surface rows. The `scale` member holds the price from the last observation; the `overhead` member holds the construction price.
2270
+ The prompt price. The `rate`, `remainder`, `reserve`, and `room` methods read the calls of the request in progress, and the `observe` method folds a finished request in. The `scale` and `overhead` data members stay Surface rows. The `scale` member holds the last learned price; the `overhead` member holds the construction price. A call's optional `spared` member defaults to zero. Observation rescales only when the first call held exactly all overhead (`spared` absent or zero) or none (`spared` at or above overhead), subtracting `max(0, overhead - spared)` from reported prompt usage. A partially spared first call keeps the existing scale. Estimated use adds that reduced overhead to `scale * estimate`. When no tool is advertised, the ledger spares all overhead and can rescale exactly. When some tools remain, it spares the estimated price of the JSON array of every omitted definition, capped at overhead; a partial share is not learned from, so the calibrated scale remains until a first call with exact overhead can update it.
2231
2271
 
2232
2272
  | Method | Returns | Summary |
2233
2273
  | ----------- | -------- | ---------------------------------------------------------------------------------------------------- |
@@ -2267,7 +2307,7 @@ These invariants hold across `src/core` ↔ `agent.md`:
2267
2307
  - **Automatic compaction (the context `window` budget).** With `AgentOptions.window` set and a summarizable run conversation, the loop measures each request it will send, with its messages after the `replay` policy, its advertised tools, and its per-call `options`, against the window before the first provider request and between turns, and compacts and rebuilds when the window is exhausted. A summarizer throw emits `fault` and the run continues over-window unless `strict` is set, and a fold that compacts nothing between turns while over the window stops auto-compaction for the rest of the run. A run whose signal aborted by the end of tool dispatch folds nothing before it settles. When no selection handler runs, and either `window` is absent or the run's conversation has no summarizer, the loop adds no `await` before the first provider request.
2268
2308
  - **Active workspace rendering by carrier.** `build()` reads only the active workspace, filters its files through `scope.files`, renders text files under `WORKSPACE_SECTION_HEADER` through `renderFencedFile` into one `user` context message with a minted id, which is never stored, and attaches the base64 data of binary `image/` files to a copy of the last user message of the conversation. With no active workspace, or no text file, the context message holds the memos index alone, and with no memos index either, no context message renders.
2269
2309
  - **The durable `ConversationStore` + the manager's `open` / `save` seam.** A `ConversationSnapshot` is the JSON payload `{ id, sections, messages, judgments? }`, created by `snapshot()` and restored through `ConversationInput.snapshot` without emitting events. `MemoryConversationStore` keeps snapshots in a map and `DatabaseConversationStore` in one opaque JSON column narrowed by `isConversationSnapshot`, both through `get`, `set`, and `delete`. `open(id)` activates a registry hit or hydrates a store hit, keeps a conversation registered under `id` during the store read, and throws `ConversationError` `'SNAPSHOT'` on a snapshot whose `id` is not `id`; `DatabaseConversationStore.get` throws the same code on such a row and on a row that fails the guard, and `set` refuses what `get` would. `add` throws `ConversationError` `'ID'` on an id already live. A stored snapshot that holds a `system` role rejects `open` with `ConversationError` `'ROLE'`, the registry and `active` unchanged. `save(id)` returns `false` when no store or conversation exists. `MemoStoreInterface` is the memo twin: `MemoryMemoStore` and `DatabaseMemoStore` persist a `MemoSnapshot` by its memo set id through `get`, `set`, and `delete`, and the host authors what it stores, because a memo can be model-written and a stored memo set hydrates as written after `isMemoSnapshot` accepts it.
2270
- - **Limit exhaustion, the three failure layers, and per-run options.** A run that exhausts `limit` while its last turn still requested tools settles `partial: true` and emits `exhaust` instead of `abort`. The loop charges the `allowance` mid-stream from the `estimateTokens` estimate of each turn's content, and charges the cost `budget` the reported usage after each call, net of the estimate only when the `allowance` is the `budget`, or the estimate when the call reported none, a call that failed with a genuine provider error included; it never charges twice. `AgentResult.stop` names the one layer, `meter`, `budget`, or `model`, that stopped the final provider call first. `AgentRunOptions` members override their construction defaults for one run, `conversation` and `prompt` have no construction default, a per-run `signal` composes with the constructed one, and `think` and `schema` reach the provider in one options object, omitted when both are absent. A construction or per-run `limit` that is not a nonnegative safe integer throws `AgentError` with code `LIMIT`.
2310
+ - **Limit exhaustion, the three failure layers, and per-run options.** A run that exhausts `limit` while its last turn still requested tools settles `partial: true` and emits `exhaust` instead of `abort`. The loop charges the `allowance` mid-stream from the `estimateTokens` estimate of each turn's content, and charges the cost `budget` the reported usage after each call, net of the estimate only when the `allowance` is the `budget`, or the estimate when the call reported none, a call that failed with a genuine provider error included; it never charges twice. `AgentResult.stop` names the one layer, `meter`, `budget`, or `model`, that stopped the final provider call first. `AgentRunOptions` members override their construction defaults for one run, `conversation` and `prompt` have no construction default, a per-run `signal` composes with the constructed one, and `think` and `schema` reach the provider in one options object, omitted when both are absent. A construction or per-run `limit` that is not a positive safe integer throws `AgentError` with code `LIMIT`.
2271
2311
  - **Construction-time context wiring.** `AgentOptions.instructions`, `skills`, `memos`, `workspaces`, `scope`, `conversations`, and `select` forward into the `AgentContext` the constructor builds.
2272
2312
  - **`strict` — fault escalation.** `AgentOptions.strict` defaults to `true`: an automatic-compaction summarizer failure and each selection fault emit `fault` and then settle the run `error`, and with `strict: false` the run continues. A strict run also refuses a final answer that misses the run's `schema` with `AgentError` `'SCHEMA'`, and a request still over the window with `AgentError` `'WINDOW'`, whose message reads `the request measures <consumed> against a window of <max> and this run folds no further`. A cancel at a select site wins over `strict`, and a manual `conversation.compact()` always propagates its own error.
2273
2313
  - **Bounded `sections`.** A `sections` cap, set per conversation, as a manager default, or per `compact()` call, bounds `Conversation.sections` to at most `sections` entries after a successful merge; when a fold exceeds it, the oldest sections merge into one through a summarizer call and `collapse` fires. A cap that is not a positive safe integer throws `ConversationError` with code `SECTIONS`, and a `keep` that is not a nonnegative safe integer throws it with code `KEEP`. A digest that is not a string or whose trimmed text is empty refuses the fold it would commit with `'SUMMARY'`; such a digest for a capped merge refuses the merge and keeps the fold already committed, one section over the cap, which the next sound merge collapses.
@@ -2276,11 +2316,11 @@ These invariants hold across `src/core` ↔ `agent.md`:
2276
2316
 
2277
2317
  With `strict`, the default, that request throws `AgentError` `'WINDOW'`. With `strict: false`, no error and no agent event marks that point: the loop sends the over-window request, and no reading covers the provider's behavior past its window, so read the `consumed` and `exhausted` members of your `window` `Budget`, which hold the last request the loop measured, after a run.
2278
2318
 
2279
- From that stop, `compact({ keep: 0 })` frees one request: with a scripted summarizer and the same text, under a gauge overhead of 352, the next request measured 10358 tokens with 9 recaps, the new recap being the recorded 2385 characters. A conversation at `keep: 0` from goal 35, whose fold at goal 36 takes 4 messages and leaves 8 recaps, measured 9750 under that recap and 11139 under a recap of 7942 characters. The sections stay, so each later fold adds a recap against the same window. Only a `sections` cap or `cumulative` lowers that smallest request, and each needs a fold with an eligible slice. At that stop under `keep: 2` the live tail is a user, an assistant, and a user message, so `compact()` folds nothing and a strict retry refuses again; the sections merge at `compact({ keep: 0 })` or at the admission of a later run whose new prompt leaves an eligible slice. The two can't combine. `cumulative` has no per-call form, so it needs a conversation rebuilt from `snapshot()` with `ConversationInput.cumulative`. A host that reserves less output can set a larger `max` on the same model.
2319
+ In the from-stop reading of 2026-11-03, `compact({ keep: 0 })` frees one request: with a scripted summarizer and the same text, under a gauge overhead of 352, the next request measured 10358 tokens with 9 recaps, the new recap being the recorded 2385 characters. In the separate fixture reading of 2026-11-03, a conversation at `keep: 0` from goal 35, whose fold at goal 36 takes 4 messages and leaves 8 recaps, measured 9750 under that recap and 11139 under a recap of 7942 characters. The sections stay, so each later fold adds a recap against the same window. Only a `sections` cap or `cumulative` lowers that smallest request, and each needs a fold with an eligible slice. At that stop under `keep: 2` the live tail is a user, an assistant, and a user message, so `compact()` folds nothing and a strict retry refuses again; the sections merge at `compact({ keep: 0 })` or at the admission of a later run whose new prompt leaves an eligible slice. The two can't combine. `cumulative` has no per-call form, so it needs a conversation rebuilt from `snapshot()` with `ConversationInput.cumulative`. A host that reserves less output can set a larger `max` on the same model.
2280
2320
 
2281
- Beside that stop, `cumulative` has a reading and no recommendation. Seeded from that run's goal 32 on Ollama 0.40.14, it sealed goals 33 to 48 with three folds, each into one section, and the first prompts after those folds read 2958 to 3192 tokens, where the first prompts after the first seven folds of the run without it read 2733 to 11176. Its recaps kept fewer literals by `extractLiterals`: at goal 48, 11 of 170 ids and 14 of 112 numbers of 147 folded messages (254018 characters, median 577, 95th percentile 6716, maximum 6911) in a recap of 3456 characters; at goal 34, 14 of 138 ids and 15 of 96 numbers of 116 folded messages (177397 characters, median 580, 95th percentile 4824, maximum 5030) in a recap of 4844 characters. The run without it kept 57 of 138 ids and 41 of 96 numbers over the same 116 messages at goal 34, in 6 recaps of 31077 characters, and 48 of 122 ids and 41 of 87 numbers over 104 messages of 158238 characters at goal 32, in 5 recaps of 23135 characters. The originals stay on the section, and `search` and `rehydrate` read them back; they reach the model only through a tool the host registers, and Agent ships none. This is one arm, one seed, and one recording on two Ollama versions, so the figures state no cause, and no quality label reads these recaps. No reading on this model compares a `sections` cap with `cumulative`.
2321
+ Beside that stop, `cumulative` has a reading and no recommendation. In the cumulative reading of 2026-11-03, seeded from that run's goal 32 on Ollama 0.40.14, it sealed goals 33 to 48 with three folds, each into one section, and the first prompts after those folds read 2958 to 3192 tokens, where the first prompts after the first seven folds of the 2026-11-02 and 2026-11-03 recording without it read 2733 to 11176. Its recaps kept fewer literals by `extractLiterals`: at goal 48, 11 of 170 ids and 14 of 112 numbers of 147 folded messages (254018 characters, median 577, 95th percentile 6716, maximum 6911) in a recap of 3456 characters; at goal 34, 14 of 138 ids and 15 of 96 numbers of 116 folded messages (177397 characters, median 580, 95th percentile 4824, maximum 5030) in a recap of 4844 characters. The 2026-11-02 and 2026-11-03 recording without it kept 57 of 138 ids and 41 of 96 numbers over the same 116 messages at goal 34, in 6 recaps of 31077 characters, and 48 of 122 ids and 41 of 87 numbers over 104 messages of 158238 characters at goal 32, in 5 recaps of 23135 characters. The originals stay on the section, and `search` and `rehydrate` read them back; they reach the model only through a tool the host registers, and Agent ships none. This is one arm, one seed, and one recording on two Ollama versions, so the figures state no cause, and no quality label reads these recaps. No reading on this model compares a `sections` cap with `cumulative`.
2282
2322
 
2283
- - **`sanitizeUsage`.** `sanitizeToken` turns a non-finite or non-positive count into `0` and floors a positive fraction, and `sanitizeUsage` applies it to each field. The loop sanitizes a provider's usage and an abort partial's usage before charging or folding it.
2323
+ - **`sanitizeUsage`.** `sanitizeToken` turns a non-finite or non-positive count into `0` and floors a positive fraction, and `sanitizeUsage` applies it to each field. A settled provider result crosses the provider-result guard before charging or folding its usage; malformed present usage refuses the result. The loop sanitizes an abort partial's usage, and absent usage retains the estimate.
2284
2324
  - **`AgentError` — the concurrency guard.** `stream()` throws `AgentError` with code `CONCURRENCY` and `context: { agent }` synchronously when a run is in flight and the agent carries a `window`, or when the run's effective `budget` or `allowance` is an instance a live run holds; after those checks it throws one with `context: { agent, conversation }`, naming the conversation's id, when a live run is bound to the run's conversation. Runs holding distinct instances on distinct conversations with no `window` overlap. The refused run never starts either bound, so the live run stays bound to it. The guard compares conversation instances: two `Conversation` values opened from one stored snapshot are distinct to it and run at once on an agent with no `window` and distinct budgets, so a host opens each thread once and keys its thread registry by principal and thread. A `prompt` that is not an exact `AgentPrompt`, a `budget` or `allowance` that does not implement `BudgetInterface`, or a `conversation` that does not implement `ConversationInterface` throws `ContractError` with code `placement` before either bound starts, and a refused run appends no `prompt`. `isAgentError` narrows a caught value, and a `REGISTRY` error's `context` names the `category` and `name`.
2285
2325
  - **`agentResultToJSON` — the portable `AgentResult` projection.** The helper accepts `unknown`, never throws, reads each structural field once, and returns a fresh exact `{ content, thinking?, usage?, partial, stop? }` `JSONValue`, or `undefined` for invalid input; a malformed `stop` refuses the whole value. Finite negative and fractional usage counts are preserved, and extra fields are dropped.
2286
2326
  - **The provider engine's request and stream.** The engine posts `JSON.stringify(encode(request))` to `url + (path ?? '')` with a JSON content type the `headers` hook can extend, decodes the body through `readChunks`, and feeds every framed record and the `finish` tail through `read`. A record whose `read` returns a `result` ends the call with that result, and under the default `strict` a stream that ends with neither a settled result nor a `done` record throws `ProviderError` with code `PROTOCOL`. A non-OK body is read through `readBodyText` to at most `MAX_ERROR_BODY_LENGTH` bytes and its remainder cancelled, and each reader releases its lock on every exit.
@@ -2475,13 +2515,13 @@ That judge answers through `ask` like any other. With `batch: false` the engine
2475
2515
 
2476
2516
  Every configuration sends one request layout, position by position. The following table lists what fills each position under each strategy:
2477
2517
 
2478
- | Position | Plain agent | Automatic compaction | Ledger, first pass of a request |
2479
- | ---------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
2480
- | `system` | the `system` option, then `## Instructions`, then `## Skills`; absent when all are empty | the same | the `system` option, then `## Instructions` and `## Skills` from the `agent` option |
2481
- | `user` context message | `## Memos`, then `## Workspace`; absent when both are empty; a minted id, never stored and never folded | the same | the same, from the `agent` option |
2482
- | Tail | `view()` | one `assistant` recap per section, opening with `CONVERSATION_RECAP_PREFIX`, then the live tail | the seed tail, with each lookup result as its stub |
2483
- | Request | the last stored `user` message; images attach here | the same | a built copy of the `user` turn: `## Records`, `## Rules`, and `## Request` before the prompt, or the prompt alone when nothing renders; images attach here |
2484
- | Run turns | each `assistant` message with its calls, then one `tool` message per call | the same | the same |
2518
+ | Position | Plain agent | Automatic compaction | Ledger, first pass of a request |
2519
+ | ---------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2520
+ | `system` | the `system` option, then `## Instructions`, then `## Skills`; absent when all are empty | the same | the `system` option, then `## Instructions` and `## Skills` from the `agent` option |
2521
+ | `user` context message | `## Memos`, then `## Workspace`; absent when both are empty; a minted id, never stored and never folded | the same | the same, from the `agent` option |
2522
+ | Tail | `view()` | one `assistant` recap per section, opening with `CONVERSATION_RECAP_PREFIX`, then the live tail | the seed tail, with each lookup result as its stub, then each completed exchange in the window as it was sent, within the room the records leave and without closing an open recall |
2523
+ | Request | the last stored `user` message; images attach here | the same | a built copy of the `user` turn: the `## Records` and `## Rules` lines the window doesn't hold and `## Request` before the prompt, or the prompt alone when it has no line to add; images attach here |
2524
+ | Run turns | each `assistant` message with its calls, then one `tool` message per call | the same | the same |
2485
2525
 
2486
2526
  A host writes the `system` message through the `system` option, `instructions.add`, a skill load, and the skill index, and nothing else reaches it. A stored message plays `user`, `assistant`, or `tool`: `add`, a snapshot, a job seed, and a selection each refuse a `system` role with `ConversationError` `'ROLE'`. `Conversation.reference()` returns text for a `user` message or a workspace file, and it never belongs in the `system` message. Because an instruction never folds, a rule in an instruction survives every round of compaction, and a host scope with an explicit `instructions` allow-list filters a loaded `skill:<name>` instruction. The skills index stays inert until a host registers a loading tool, as the `SkillManager` paragraph states.
2487
2527
 
@@ -3250,15 +3290,15 @@ const result = await agent.generate() // { content: 'Refunds need a manager.', p
3250
3290
 
3251
3291
  The ledger is the records strategy: it keeps every message and serves each request through records, where automatic compaction folds older turns into recaps. The following table compares the strategies. It recommends no form and changes no default, and the **compaction floor** clause under [Contract](#contract) holds the one reading behind its compaction rows.
3252
3292
 
3253
- | Strategy | Set it through | What the next request holds | What keeps the originals | What stops it |
3254
- | -------------------------------- | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
3255
- | Plain agent | `createAgent(provider)` with no `window` | the whole `view()` | the conversation's live tail | nothing folds, so the provider's own limit decides |
3256
- | Automatic compaction | `AgentOptions.window` and a summarizable conversation | one recap per section, then the live tail | each section's `messages`, read through `search` and `rehydrate` | every recap stays, so a request can reach the window with nothing left to fold |
3257
- | Compaction with a `sections` cap | the `sections` option, per conversation, as a manager default, or per `compact()` call | at most the cap's recaps after a merge, then the live tail | the same | a merge needs a fold with an eligible slice, and it can't combine with `cumulative` |
3258
- | Compaction with `cumulative` | `ConversationOptions.cumulative` or `ConversationInput.cumulative` | one recap, then the live tail | the same | a fold needs an eligible slice, and its summarizer reads recaps and not the originals behind them |
3259
- | Ledger | `createLedger(provider, options)` | the built head, the seed tail, and a copy of the request turn with its records | the conversation, read through the `recall` tool | a judge and fitted cutoffs are required, and the ledger refuses no over-window prompt |
3293
+ | Strategy | Set it through | What the next request holds | What keeps the originals | What stops it |
3294
+ | -------------------------------- | -------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
3295
+ | Plain agent | `createAgent(provider)` with no `window` | the whole `view()` | the conversation's live tail | nothing folds, so the provider's own limit decides |
3296
+ | Automatic compaction | `AgentOptions.window` and a summarizable conversation | one recap per section, then the live tail | each section's `messages`, read through `search` and `rehydrate` | every recap stays, so a request can reach the window with nothing left to fold |
3297
+ | Compaction with a `sections` cap | the `sections` option, per conversation, as a manager default, or per `compact()` call | at most the cap's recaps after a merge, then the live tail | the same | a merge needs a fold with an eligible slice, and it can't combine with `cumulative` |
3298
+ | Compaction with `cumulative` | `ConversationOptions.cumulative` or `ConversationInput.cumulative` | one recap, then the live tail | the same | a fold needs an eligible slice, and its summarizer reads recaps and not the originals behind them |
3299
+ | Ledger | `createLedger(provider, options)` | the built head, the seed tail, each completed exchange in the window as it was sent, within the room the records leave and without closing an open recall, and a copy of the request turn with the record lines the window doesn't hold | the conversation, read through the `recall` tool | a judge and fitted cutoffs are required, and the ledger refuses no over-window prompt |
3260
3300
 
3261
- Build a ledger from a provider, a judge, the lookups, and the measured questions, add the seed history to its conversation, and send each request through the `respond` method. Read the last message of each `select` event's selection, the copy of the request turn, to see the records the ledger wrote ahead of the request. The following ledger serves two requests; a scripted provider stands in for the model and a scripted judge for Mica:
3301
+ Build a ledger from a provider, a judge, the lookups, and the measured questions, add the seed history to its conversation, and send each request through the `respond` method. Read the last message of each `select` event's selection, the copy of the request turn, to see the record lines the ledger added for that request; the exchanges before it in the selection hold the lines earlier copies showed. The following ledger serves two requests; a scripted provider stands in for the model and a scripted judge for Mica:
3262
3302
 
3263
3303
  ```ts
3264
3304
  import type {
@@ -3357,12 +3397,12 @@ second.content // 'Yes. Refunds over $100 need a manager.'
3357
3397
  copies[0]
3358
3398
  // '## Rules\n- Refunds over $100 need a manager.\n\n## Request\nCan Brightwater Studio get a refund on order BW-5512?' — no lookup has named an owner yet
3359
3399
  copies[1]
3360
- // '## Records\n### Brightwater Studio (BW-20931)\n- Order BW-5512 for account BW-20931: Brightwater Studio.\n- Refund due $148.50.\n\n## Rules\n- Refunds over $100 need a manager.\n\n## Request\nDoes the Brightwater Studio refund need a manager?'
3400
+ // '## Records\n### Brightwater Studio (BW-20931)\n- Order BW-5512 for account BW-20931: Brightwater Studio.\n- Refund due $148.50.\n\n## Request\nDoes the Brightwater Studio refund need a manager?' — the first copy still holds the rule
3361
3401
  ```
3362
3402
 
3363
- The second request names Brightwater Studio, so its records carry that owner's record, built from the first request's lookup result, while neither the first request nor its reply reaches the second prompt, and the system message holds the `system` option alone. The executed transcription runs this fence with its own cutoffs and reads the prompts the provider received; see [the `tests/guides.test.ts` parity test](../tests/guides.test.ts).
3403
+ The second request names Brightwater Studio, so its copy carries that owner's record, built from the first request's lookup result. It leaves out the rule, because the first request's copy, which follows the seed tail in the window with its final reply, holds it. The system message holds the `system` option alone. The executed transcription runs this fence with its own cutoffs and reads the prompts the provider received; see [the `tests/guides.test.ts` parity test](../tests/guides.test.ts).
3364
3404
 
3365
- To carry a ledger across a restart, store what its `snapshot` method returns and pass it back as the `snapshot` option of a later `createLedger` call. The snapshot is plain JSON: the conversation with its judgments, the ids of the requests, notes, and failed tool results the ledger marked, and the gauge. Narrow a parsed snapshot with the `isLedgerSnapshot` guard first, because construction refuses a snapshot the guard refuses with `LedgerError` code `'SNAPSHOT'`. The hydrated ledger makes no calibration call when the snapshot or the options carry a gauge, and it asks its judge no question the stored judgments answer. The following example continues the preceding ledger in a second ledger, and the second ledger writes the records the first would write for the same request:
3405
+ To carry a ledger across a restart, store what its `snapshot` method returns and pass it back as the `snapshot` option of a later `createLedger` call. The snapshot is plain JSON: the conversation with its judgments, the ids of the requests, notes, and failed tool results the ledger marked, the gauge, and the window while it holds an exchange. Narrow a parsed snapshot with the `isLedgerSnapshot` guard first, because construction refuses a snapshot the guard refuses with `LedgerError` code `'SNAPSHOT'`. The hydrated ledger makes no calibration call when the snapshot or the options carry a gauge, and it asks its judge no question the stored judgments answer. The following example continues the preceding ledger in a second ledger, and the second ledger sends the prompt the first would send for the same request. The window holds every line this request selects, so its copy is the request itself:
3366
3406
 
3367
3407
  ```ts
3368
3408
  import type { LedgerInterface, LedgerOptions, ProviderInterface } from '@orkestrel/agent'
@@ -3383,11 +3423,95 @@ restored.agent.emitter.on('select', (selection) => copies.push(selection.message
3383
3423
  const third = await restored.respond('Is the Brightwater Studio refund approved yet?')
3384
3424
  third.content // 'Not yet. A manager must approve it.'
3385
3425
  copies[0]
3386
- // '## Records\n### Brightwater Studio (BW-20931)\n- Order BW-5512 for account BW-20931: Brightwater Studio.\n- Refund due $148.50.\n\n## Rules\n- Refunds over $100 need a manager.\n\n## Request\nIs the Brightwater Studio refund approved yet?' — what the first ledger writes for the same request
3426
+ // 'Is the Brightwater Studio refund approved yet?' — what the first ledger writes for the same request
3387
3427
  ```
3388
3428
 
3389
3429
  To serve a thinking model, pass its context window as the `capacity` option and its generation cap, thinking included, as the `predict` option, and set the boolean `think` option to request or suppress thinking for the first pass. The answer pass always runs with thinking off. The plan then budgets what the window leaves after the cap, the recall room keeps the cap free, and the gauge counts only the thinking the next request carries; see [Serving a conversation through a ledger](#serving-a-conversation-through-a-ledger) for the budget.
3390
3430
 
3431
+ #### Composing a records desk for a small local GPU
3432
+
3433
+ A records desk on a small local GPU runs two models by role: the agent's provider writes the replies, and the ledger's judge files the messages. Pass the provider as the first argument of the `createLedger` function and the judge as its `judge` option. The window and the `recall` offer are the ledger's own behavior and need no configuration.
3434
+
3435
+ When the two models don't fit on one GPU, run the judge on the CPU through its provider options, so that neither model evicts the other between requests. The `createOllamaJudge` function of `@orkestrel/ollama` forwards `options: { num_gpu: 0 }` to the daemon for this.
3436
+
3437
+ A judge can also be two judges. The `ask` method of `JudgeInterface` takes every question of one request, so a host can compose a two-step judge on it: a fast first judge takes each choice question, the host keeps the answers it trusts, and a second judge takes the rest. The following fence composes one and names models only as examples:
3438
+
3439
+ ```ts
3440
+ import type {
3441
+ JudgeInterface,
3442
+ JudgeRequest,
3443
+ JudgeResult,
3444
+ LedgerThreshold,
3445
+ ProviderInterface,
3446
+ } from '@orkestrel/agent'
3447
+ import { buildJudgeResult, createLedger, LEDGER_QUESTIONS, measureAnswer } from '@orkestrel/agent'
3448
+
3449
+ declare const provider: ProviderInterface // the agent's model on the GPU, for example `createOllama({ model: 'qwen3.5:4b-q4_K_M' })`
3450
+ declare const fast: JudgeInterface // a first judge, for example `createSystemOneJudge({ url, model: 'tev1:0.8b' })`
3451
+ declare const slow: JudgeInterface // a second judge on the CPU, for example `createOllamaJudge({ model, system, options: { num_gpu: 0 } })`
3452
+ declare const thresholds: LedgerThreshold // fitted on LEDGER_QUESTIONS and your judges
3453
+ declare const cutoff: number // the winning probability this host trusts from the first judge, fitted on its own rows
3454
+
3455
+ class TwoStepJudge implements JudgeInterface {
3456
+ readonly id = 'two-step'
3457
+ readonly name = 'two-step'
3458
+ readonly model: string
3459
+ readonly #first: JudgeInterface
3460
+ readonly #second: JudgeInterface
3461
+ readonly #keep: number
3462
+
3463
+ constructor(first: JudgeInterface, second: JudgeInterface, keep: number) {
3464
+ this.#first = first
3465
+ this.#second = second
3466
+ this.#keep = keep
3467
+ // A stored judgment is reused only under one identity, so all that changes an answer joins it.
3468
+ this.model = JSON.stringify({ first: first.model, second: second.model, keep })
3469
+ }
3470
+
3471
+ async ask(request: JudgeRequest, signal: AbortSignal): Promise<JudgeResult> {
3472
+ const entries = Object.entries(request.questions)
3473
+ const choices = entries.filter(([, question]) => question.form === 'choice')
3474
+ const asked: JudgeResult =
3475
+ choices.length === 0
3476
+ ? { model: this.model, answers: {} }
3477
+ : await this.#first.ask({ ...request, questions: Object.fromEntries(choices) }, signal)
3478
+ const kept = Object.entries(asked.answers).filter(([, answer]) => {
3479
+ const { winner, probability } = measureAnswer(answer)
3480
+ return probability >= this.#keep && winner !== 'correction'
3481
+ })
3482
+ const answered: JudgeResult = {
3483
+ model: this.model,
3484
+ answers: Object.fromEntries(kept),
3485
+ ...(asked.usage === undefined ? {} : { usage: asked.usage }),
3486
+ }
3487
+ const rest = entries.filter(([id]) => !Object.hasOwn(answered.answers, id))
3488
+ return rest.length === 0
3489
+ ? answered
3490
+ : buildJudgeResult(this.model, [
3491
+ answered,
3492
+ await this.#second.ask({ ...request, questions: Object.fromEntries(rest) }, signal),
3493
+ ])
3494
+ }
3495
+ }
3496
+
3497
+ const ledger = createLedger(provider, {
3498
+ judge: new TwoStepJudge(fast, slow, cutoff),
3499
+ system: 'You staff the Larkspur support desk.',
3500
+ topics: [{ name: 'refunds', criterion: 'refund amounts and approvals' }],
3501
+ questions: LEDGER_QUESTIONS,
3502
+ thresholds,
3503
+ capacity: 32_768, // the agent model's context window
3504
+ predict: 8_192, // its generation cap, thinking included
3505
+ })
3506
+ await ledger.respond('Does the Brightwater Studio refund need a manager?')
3507
+ ```
3508
+
3509
+ The `model` member holds both judges' identities and the cutoff, so changing any of them asks each question again. This class rejects when its first judge rejects. For a fuller worked example that refers a first judge's fault to the second and checks each distribution, read `studies/memory/StudyMemoryJudge.ts` in this repository and adapt it: it holds one study's policy, and no published entry exports it. The executed transcription runs the preceding class with a scripted provider and recording judges; see [the `tests/guides.test.ts` parity test](../tests/guides.test.ts).
3510
+
3511
+ The application decides which models to run, which thresholds to keep, and whether to run two judges at all. The package ships the mechanism and none of that policy.
3512
+
3513
+ The same line holds for what a request carries beyond its messages. To have a judge choose the tools, instructions, memos, or skills of a request, ask the judge before the request and apply the answer through the `narrow` method of the active scope. Narrowing only tightens, so an answer can't admit a tool the scope excludes. A tool list or system text that changes between requests costs the reuse of the prompt, and a wrong answer withholds that tool for the request.
3514
+
3391
3515
  ### Upgrade data written before 0.0.35
3392
3516
 
3393
3517
  Stored data written before 0.0.35 meets the checks of 0.0.35 at its next read. A snapshot that carries a member its shape doesn't declare, the conversation `summary` a 0.0.29 snapshot can hold included, refuses at its next read as well: the stores throw `'SNAPSHOT'` naming the key, because a refused row read as absent would let `open` overwrite it. Read that row through your own table and rewrite it without the key, or delete it with `store.delete`. A stored snapshot that holds a `system` row rejects with `ConversationError` `'ROLE'` and the message `a conversation snapshot holds a system message; a snapshot written before 0.0.35 can hold a system row; remove it before loading`. A queued `AgentJobInput` seed that holds a `system` message fails at `AgentRegistry.build` through `add`, with `ConversationError` `'ROLE'` and the message `a stored message role must be one of "user", "assistant", "tool"; received "system"; host text goes in the system option or an instruction`, and the job's `system` member carries that text.
@@ -3567,13 +3691,13 @@ The following test files back this guide:
3567
3691
  - [`tests/src/core/agents/contracts.test.ts`](../tests/src/core/agents/contracts.test.ts) — the frame, prompt, and answer contracts over every frame arm and every refused wire row, a throwing `Proxy`, and seeded values that agree with `parse`.
3568
3692
  - [`tests/src/core/agents/validators.test.ts`](../tests/src/core/agents/validators.test.ts) — `isAuthorityDecision` over each verdict with and without `reason`, and its refusal of a `{ zone, allowed }` decision, an unknown verdict, a non-string `zone` or `reason`, a non-object, a throwing getter, a revoked `Proxy`, and a `Proxy` whose `get` trap throws.
3569
3693
  - [`tests/src/core/agents/AgentFanout.test.ts`](../tests/src/core/agents/AgentFanout.test.ts) — `AgentFanout` through a real runner: one fan-out per unit across a retried attempt, every distinct unit's children, and the partial policy.
3570
- - [`tests/src/core/ledgers/Ledger.test.ts`](../tests/src/core/ledgers/Ledger.test.ts) — the ledger over a scripted provider: owner records, seed stubs paired with their calls by call id and priced at their longer form, and the seed tail, the `'REQUEST'` fault of a run no active `respond` call owns, a run on another conversation, and the refused direct run during a request, the runs that stay on the ledger's conversation under a switch, the repeat stop, the answer pass and the abort that skips it, calibration with its replay at the next user boundary and its refusals, the filing of notes and failed lookups, the `recall` tool's listing, limit, and room, the answer note's lines, the generation cap and thinking per pass, and retained amended sentences with unresolved scope while `recall`, the answer note, and the seed tail keep stored content, and the snapshot and hydrate: selections and judge keys equal to the uninterrupted ledger's with each emptied mark list as a control, the JSON round trip, the `'CONCURRENCY'` refusal, the flush before capture, judgments kept across a judge abort, the `'SNAPSHOT'` refusals, the `'ROLE'` refusal of a hydrated `system` message, the gauge precedence, the fork, a recorded correction fixture replayed through a hydrated ledger, the replay from a sorted snapshot, each lookup result read once per selection, a message removed during a judge await kept out of that selection's plan, the forwarding of the `narrow` member to the classifier, head pricing and the built-head calibration, and the host turns: each entry refused during one, another thread's refused run and its recall, an append and a removal that fault the selection with no question about a gone message, a judgment removed during one asked again, an abort and a scheduler fault that leave the ledger free, the same bytes when paced, and the agent's turn between its own turns.
3571
- - [`tests/src/core/ledgers/LedgerRequest.test.ts`](../tests/src/core/ledgers/LedgerRequest.test.ts) — the request's recall-limit refusal, its single `enter`, its passes with their selections, usage, calls, and thinking, its filing attempts and plan, the repeat stop, the recall limit and `close`, and the listings of a recall result.
3694
+ - [`tests/src/core/ledgers/Ledger.test.ts`](../tests/src/core/ledgers/Ledger.test.ts) — the ledger over a scripted provider: owner records, seed stubs paired with their calls by call id and priced at their longer form, and the seed tail, the `'REQUEST'` fault of a run no active `respond` call owns, a run on another conversation, and the refused direct run during a request, the runs that stay on the ledger's conversation under a switch, the repeat stop, the answer pass and the abort that skips it, calibration with its replay at the next user boundary and its refusals, the filing of notes and failed lookups, the `recall` tool's listing, limit, room, and per-request offer with a host's scope kept and restored, the answer note's lines, the generation cap and thinking per pass, and retained amended sentences with unresolved scope while `recall`, the answer note, and the seed tail keep stored content, the window's extending copies, rungs, emptying, derived pair, rejected request, answered fallback, and stub state, and the snapshot and hydrate: selections and judge keys equal to the uninterrupted ledger's with each emptied mark list as a control, provider prompts equal through five JSON round trips, the `window` member's omission, refusals, and digest checked at hydrate, the JSON round trip, the `'CONCURRENCY'` refusal, the flush before capture, judgments kept across a judge abort, the `'SNAPSHOT'` refusals, the `'ROLE'` refusal of a hydrated `system` message, the gauge precedence, the fork, a recorded correction fixture replayed through a hydrated ledger, the replay from a sorted snapshot, each lookup result read once per selection, a message removed during a judge await kept out of that selection's plan, the forwarding of the `narrow` member to the classifier, head pricing and the built-head calibration, and the host turns: each entry refused during one, another thread's refused run and its recall, an append and a removal that fault the selection with no question about a gone message, a judgment removed during one asked again, an abort and a scheduler fault that leave the ledger free, the same bytes when paced, and the agent's turn between its own turns.
3695
+ - [`tests/src/core/ledgers/LedgerRequest.test.ts`](../tests/src/core/ledgers/LedgerRequest.test.ts) — the request's recall-limit refusal, its single `enter`, its passes with their selections, usage, calls, and thinking, its filing attempts and plan, the draft its last provider turn adopted as the `sent` member, the repeat stop, the recall limit and `close`, and the listings of a recall result.
3572
3696
  - [`tests/src/core/ledgers/Classifier.test.ts`](../tests/src/core/ledgers/Classifier.test.ts) — the measured question bytes and asking order, judgment reuse and usage, exact cutoffs, the category tie in `LEDGER_CATEGORIES` order, pair questions, deterministic and transient judge failures, abort faults that keep the completed judgments, the cached, skipped, resolved, failed, and aborted attempts each of those paths records, each message's quiet flag and near set read once per classification, with a change to the conversation or the judge's model read at the next call, the pairs of every eligible earlier message asked in conversation order and the narrower set of the `narrow` member, and the host turns: a yield after a slice elapses on a recording and a real scheduler, none in a live slice or with no scheduler, the same questions when paced, the asks a removed source skips, an abort during a turn, and a scheduler fault.
3573
3697
  - [`tests/src/core/ledgers/Gauge.test.ts`](../tests/src/core/ledgers/Gauge.test.ts) — the gauge's construction refusals and its `observe`, `rate`, `remainder`, `reserve`, and `room` methods, under the generation cap and each replay policy.
3574
3698
  - [`tests/src/core/ledgers/factories.test.ts`](../tests/src/core/ledgers/factories.test.ts) — `createLedger` and its `LedgerError` refusals for thresholds, shares, capacity, limits, topics, lookups, and a supplied gauge, the keys of the `LedgerAgentOptions` type, and the barrel exports of the ledger module.
3575
- - [`tests/src/core/ledgers/helpers.test.ts`](../tests/src/core/ledgers/helpers.test.ts) — the projection helpers from `splitSentences` through `buildRecords` and `selectRecords`, the `normalizeWord` fold, the alias index the `buildLedgerIndex` function builds for the `matchEntities` function, the record renderers, `findLedgerCall`, `rankLedgerCut`, `findLedgerCut`, `buildLedgerCut`, `splitTopic`, `cutListing` and `matchesCutLine`, `renderStub`, `buildRequestMessage`, `normalizeArgument`, `splitResultLines`, `renderLookupCall`, `computeThinking`, `resolvePredict`, and `fitSlope`.
3576
- - [`tests/src/core/ledgers/validators.test.ts`](../tests/src/core/ledgers/validators.test.ts) — `isFraction`, `isPositiveSafeInteger`, and `isLedgerSnapshot`, which refuses every malformed snapshot, an unknown or mis-roled id, a throwing getter, and a revoked proxy, and accepts a snapshot a ledger returned.
3699
+ - [`tests/src/core/ledgers/helpers.test.ts`](../tests/src/core/ledgers/helpers.test.ts) — the projection helpers from `splitSentences` through `buildRecords` and `selectRecords`, the `normalizeWord` fold, the alias index the `buildLedgerIndex` function builds for the `matchEntities` function, the record renderers, `findLedgerCall`, `rankLedgerCut`, `findLedgerCut`, `buildLedgerCut`, `splitTopic`, `cutListing` and `matchesCutLine`, `renderStub`, `buildRequestMessage`, `normalizeArgument`, `splitResultLines`, `renderLookupCall`, `computeThinking`, `resolvePredict`, `fitSlope`, `digestLedgerWindow`, `collectRecallMessages`, `hasHiddenRecall`, `buildLedgerLineKey`, `collectLedgerLines`, `collectLedgerReplies`, and `collectLedgerEvidence`.
3700
+ - [`tests/src/core/ledgers/validators.test.ts`](../tests/src/core/ledgers/validators.test.ts) — `isFraction`, `isPositiveSafeInteger`, `isLedgerSnapshot`, which refuses every malformed snapshot, an unknown or mis-roled id, a throwing getter, and a revoked proxy, and accepts a snapshot a ledger returned, and `isLedgerWindowSnapshot`, which agrees with the `ledgerWindowContract` constant on a valid window and its malformed neighbors.
3577
3701
 
3578
3702
  ### Placement proofs
3579
3703