dsh-boost 0.1.0 → 0.1.2

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 (54) hide show
  1. package/README.en.md +184 -70
  2. package/README.md +148 -59
  3. package/dist/gate/decide.js +33 -2
  4. package/dist/gate/decide.js.map +1 -1
  5. package/dist/hooks/llm-stream.js +242 -89
  6. package/dist/hooks/llm-stream.js.map +1 -1
  7. package/dist/hooks/post-execute.js +282 -25
  8. package/dist/hooks/post-execute.js.map +1 -1
  9. package/dist/hooks/session-state.js +18 -8
  10. package/dist/hooks/session-state.js.map +1 -1
  11. package/dist/host/root.js +22 -1
  12. package/dist/host/root.js.map +1 -1
  13. package/dist/index.js +494 -72
  14. package/dist/index.js.map +1 -1
  15. package/dist/scope/doc.js.map +1 -1
  16. package/dist/scope/store.js +24 -9
  17. package/dist/scope/store.js.map +1 -1
  18. package/dist/tools/boost.js +37 -4
  19. package/dist/tools/boost.js.map +1 -1
  20. package/dist/types.d.ts +18 -1
  21. package/dist/types.js.map +1 -1
  22. package/package.json +10 -6
  23. package/dist/admission/fixed-cost.d.ts +0 -23
  24. package/dist/admission/ledger.d.ts +0 -113
  25. package/dist/admission/retrieval.d.ts +0 -65
  26. package/dist/admission/usage.d.ts +0 -75
  27. package/dist/config.d.ts +0 -43
  28. package/dist/gate/binding.d.ts +0 -113
  29. package/dist/gate/decide.d.ts +0 -82
  30. package/dist/gate/guard.d.ts +0 -69
  31. package/dist/gate/invalidate.d.ts +0 -112
  32. package/dist/gate/plan.d.ts +0 -86
  33. package/dist/hooks/clock.d.ts +0 -68
  34. package/dist/hooks/execute.d.ts +0 -79
  35. package/dist/hooks/llm-stream.d.ts +0 -276
  36. package/dist/hooks/pending.d.ts +0 -89
  37. package/dist/hooks/post-execute.d.ts +0 -247
  38. package/dist/hooks/session-state.d.ts +0 -158
  39. package/dist/hooks/synthesize.d.ts +0 -74
  40. package/dist/host/loader.d.ts +0 -23
  41. package/dist/host/platform.d.ts +0 -18
  42. package/dist/host/root.d.ts +0 -18
  43. package/dist/projection/apply.d.ts +0 -174
  44. package/dist/projection/canonicalise.d.ts +0 -43
  45. package/dist/projection/counters.d.ts +0 -65
  46. package/dist/projection/truncate.d.ts +0 -47
  47. package/dist/prompt/protocol.d.ts +0 -45
  48. package/dist/receipts/store.d.ts +0 -198
  49. package/dist/scope/doc.d.ts +0 -117
  50. package/dist/scope/resolve.d.ts +0 -91
  51. package/dist/scope/store.d.ts +0 -135
  52. package/dist/selector/jev.d.ts +0 -93
  53. package/dist/tools/boost.d.ts +0 -367
  54. package/dist/tools/family.d.ts +0 -26
@@ -1,174 +0,0 @@
1
- /**
2
- * Projection execution: the shadow accounting and the real replacement.
3
- *
4
- * `projectShadow` is the half of projection that never changes what the model
5
- * sees: it decides whether a receipt *would* be cut, composes the replacement
6
- * string `projectApply` would produce, and prices both sides in tokens through
7
- * the caller's `estimate`. It writes nothing and reads no host service, so the
8
- * caller alone decides which mode to invoke (design §5.4).
9
- *
10
- * `projectApply` is the half that replaces, and it only replaces what is still
11
- * recoverable: the canonical receipt is persisted through the injected spill
12
- * backend first, then head line, head, spill footer and tail are composed. All
13
- * guards run before the write, a failed write or footer is a skip rather than
14
- * an exception, and a footer that would grow the receipt sends the original
15
- * back unchanged — a projection that grows a receipt defeats the plugin's
16
- * premise.
17
- *
18
- * The projected size is composed here, not read off `Truncation.after`:
19
- * `after` is the head line plus the two windows *without* the omission note, so
20
- * it is only a lower bound on the final replacement. Shadow mode prices
21
- * `renderHeadLine + head + omission note + tail`; the note's locator part is
22
- * unknown before the spill write, so only the standardized omission clause is
23
- * included.
24
- *
25
- * Skip reasons are stable codes, never prose: `error-receipt` (an error receipt
26
- * is evidence and is never projected), `family-not-configured` (the family has
27
- * no window), `not-worth-it` (`truncate`'s guard said no, or the footer left no
28
- * net gain), `empty` (shadow's empty receipt), and on the apply half
29
- * `no-spill`, `no-owner`, `projection-skipped:no-footer`, `spill-failed`, and
30
- * `footer-failed`.
31
- *
32
- * @module dsh-boost/projection/apply
33
- */
34
- import type { BoostConfig, ToolFamily } from '../types.js';
35
- /** Which projection behaviour the caller is running. */
36
- export type ProjectionMode = 'off' | 'shadow' | 'on';
37
- /** What projection did, or would have done, to one receipt. */
38
- export interface ProjectionOutcome {
39
- kind: 'skipped' | 'shadow' | 'applied';
40
- /** Stable skip code; present only when `kind === 'skipped'`. */
41
- reason?: string;
42
- /**
43
- * Tokens in the original receipt.
44
- *
45
- * Present only when `kind === 'shadow'` and the estimator priced both
46
- * sides; absent (with `estimate: 'unknown'` on the receipt) when it did not.
47
- */
48
- before?: number;
49
- /** Tokens in the replacement shadow mode would have produced. */
50
- after?: number;
51
- /** `before - after`. */
52
- saved?: number;
53
- /**
54
- * UTF-8 bytes the replacement omits; present only when `kind === 'applied'`.
55
- *
56
- * Apply mode has no token estimator: the caller (T23b) prices both texts
57
- * itself, and these two fields are the projection's own accounting.
58
- */
59
- omittedBytes?: number;
60
- /** Unicode code points the replacement omits; applied outcomes only. */
61
- omittedCodePoints?: number;
62
- /**
63
- * The persisted artifact's locator; applied outcomes only.
64
- *
65
- * It is the path the footer tells the model to read, and the retrieval ledger
66
- * matches later `read`/`grep` arguments against it (Task 25).
67
- */
68
- locator?: string;
69
- }
70
- /** A persisted spill artifact's model-facing handle. */
71
- export interface SpillHandle {
72
- /** Opaque locator the model can `read` or `grep`; never parsed here. */
73
- locator: string;
74
- /** How to retrieve the artifact, as guidance for the model. */
75
- retrievalHint: string;
76
- }
77
- /**
78
- * The host spill store, narrowed to the one method projection needs.
79
- *
80
- * `callId` and `label` are required because the host's `SaveTextSpill` requires
81
- * them; `projectApply` fills them in before calling. `saveText` rejects on a
82
- * real storage failure, and that rejection is handled as a skip.
83
- */
84
- export interface SpillBackend {
85
- saveText(input: {
86
- owner: {
87
- sessionId: string;
88
- };
89
- source: {
90
- kind: 'tool';
91
- toolName: string;
92
- callId: string;
93
- label: string;
94
- };
95
- suggestedName: string;
96
- content: string;
97
- }): Promise<SpillHandle>;
98
- }
99
- /**
100
- * Render the footer that names what was omitted and where the original lives.
101
- *
102
- * Injected by the caller, which dynamically imports the host's
103
- * `formatSpillNotice`; this module must never statically import
104
- * `@deepseek-ai/dsh-spill-policy` — it is not declared as a dependency, and a static import
105
- * would make the degradation path unreachable (design §5.4).
106
- */
107
- export type FormatFooter = (omitted: {
108
- kind: 'exact';
109
- count: number;
110
- }, ref: SpillHandle) => string;
111
- /** Everything one apply decision reads; every host service arrives pre-bound. */
112
- export interface ProjectApplyInput {
113
- /** Canonical receipt text, byte for byte as it would enter history. */
114
- text: string;
115
- /** Whether the host marked the receipt as an error. */
116
- isError: boolean;
117
- /** Projection family, which selects the window from `cfg`. */
118
- family: ToolFamily;
119
- /** Resolved plugin configuration. */
120
- cfg: BoostConfig;
121
- /** Owning session; without one the spill has no owner and projection stops. */
122
- sessionId: string | undefined;
123
- /** Tool name, recorded on the spill source and used for its file name. */
124
- toolName: string;
125
- /** Model-issued call id; defaults to `toolName`. */
126
- callId?: string;
127
- /** Human label for the artifact; defaults to `family`. */
128
- label?: string;
129
- /** Spill backend, absent when the host has none (projection then stops). */
130
- spill: SpillBackend | undefined;
131
- /** Footer renderer, absent when the host spill policy package is not installed. */
132
- formatFooter: FormatFooter | undefined;
133
- }
134
- /**
135
- * Report what projection would save, without touching the receipt.
136
- *
137
- * Guards run in a fixed order: an error receipt is skipped before anything
138
- * else, so even an empty or oversized error keeps its evidence (design §5.4
139
- * contract 4); then empty text; then a family with no configured window; then
140
- * `truncate`'s own decision (trigger, 256 KiB cap, net-gain guard).
141
- */
142
- export declare function projectShadow(input: {
143
- /** Canonical receipt text, byte for byte as it would enter history. */
144
- text: string;
145
- /** Whether the host marked the receipt as an error. */
146
- isError: boolean;
147
- /** Projection family, which selects the window from `cfg`. */
148
- family: ToolFamily;
149
- /** Resolved plugin configuration. */
150
- cfg: BoostConfig;
151
- /** Token estimator injected by the caller (never imported from the host). */
152
- estimate: (s: string) => number;
153
- }): Promise<ProjectionOutcome>;
154
- /**
155
- * Replace an oversized receipt with its head, tail, and a way back to the rest.
156
- *
157
- * The canonical original is spilled *before* anything is replaced — never the
158
- * projection, which would make the footer point at an artifact that does not
159
- * contain what it promises. The footer sits on its own line between the two
160
- * windows, and the composed replacement is re-checked against the original:
161
- * at the trigger boundary a long locator can make the "projection" longer than
162
- * the receipt it replaces, and a projection that grows a receipt is worse than
163
- * none.
164
- *
165
- * A spill or footer failure is swallowed and reported as `spill-failed` /
166
- * `footer-failed`; the caller's `post-execute` hook must never see an exception
167
- * from here. The footer must be guarded too: the host turns a throwing
168
- * `post-execute` listener into an `isError` result, which would lose the very
169
- * output this module exists to preserve.
170
- */
171
- export declare function projectApply(input: ProjectApplyInput): Promise<{
172
- content: string;
173
- outcome: ProjectionOutcome;
174
- }>;
@@ -1,43 +0,0 @@
1
- /**
2
- * Receipt canonicalisation.
3
- *
4
- * The host hands a tool result's content to the plugin as an array of content
5
- * blocks; every later stage (binding, guards, projection, hashing) reasons
6
- * about one string. This module is the only place that array becomes that
7
- * string.
8
- *
9
- * Only `type === 'text'` blocks contribute, in input order, byte-faithfully:
10
- * no trim, no line-ending normalisation, no reordering, no separator. Text
11
- * blocks without a `text` value contribute nothing and are not counted in
12
- * `textBlocks`; other block kinds (image, file, …) are skipped entirely.
13
- *
14
- * The block array is untrusted at this boundary even though the host declares
15
- * `ContentBlock[]`: the host validates lossless JSON, not block shape, so a
16
- * third-party tool's renderer can hand over `null` or a non-object. Such a
17
- * block is skipped, never dereferenced, and a content value that is not an
18
- * array is an empty receipt. Throwing here would make the host replace the
19
- * tool's real output with a tool error — the exact evidence loss this module
20
- * exists to prevent.
21
- *
22
- * `empty` means "no text content" — it is true for an empty array and for
23
- * text blocks whose concatenation is the empty string, and it is independent
24
- * of `isError`.
25
- *
26
- * @module dsh-boost/projection/canonicalise
27
- */
28
- /** The single string later stages consume, plus the facts they branch on. */
29
- export interface CanonicalReceipt {
30
- /** Text blocks concatenated in order, byte-for-byte as received. */
31
- text: string;
32
- /** Whether the host marked the tool result as an error. */
33
- isError: boolean;
34
- /** `text.length === 0`; means "no text content", not "no blocks". */
35
- empty: boolean;
36
- /** Number of text blocks that contributed to `text`, not `blocks.length`. */
37
- textBlocks: number;
38
- }
39
- /** Project a tool result's content blocks onto one canonical string. */
40
- export declare function canonicalise(blocks: ReadonlyArray<{
41
- type: string;
42
- text?: string;
43
- }>, isError: boolean): CanonicalReceipt;
@@ -1,65 +0,0 @@
1
- /**
2
- * Projection skip observability.
3
- *
4
- * A tool with no configured family returns its receipt unchanged, which is the
5
- * correct policy for `web_fetch`/`edit` and a silent mapping failure for a
6
- * decorated tool such as a new `mcp__ssh__*`. Both used to look identical from
7
- * `boost status` ("nothing projected"), so the operator could not tell "not
8
- * worth it" from "your tool is invisible to the mapper".
9
- *
10
- * The counter is deliberately cheap and bounded: two integers plus at most
11
- * {@link MAX_TRACKED_TOOLS} names. It counts calls that reached the projection
12
- * stage with a text receipt and no family; it is not a per-tool ledger. The
13
- * prompt-suppression count is the same shape, for the same reason: assembly
14
- * runs on every request, so only a number may be kept.
15
- *
16
- * @module dsh-boost/projection/counters
17
- */
18
- /** Process-wide projection counters, owned by `apply` and read by `status`. */
19
- export declare class ProjectionCounters {
20
- private unknownFamilyCount;
21
- private readonly unknownTools;
22
- private suppressedAssemblies;
23
- private missingProtocols;
24
- /**
25
- * Count one **decorated** call (`mcp__*`) whose family is not configured.
26
- *
27
- * Only decorated names are counted. An undecorated non-family tool (`edit`,
28
- * `web_fetch`, `todo_write`, or this plugin's own `boost`) is a by-design
29
- * pass, not a mapper gap, and counting it would bury the gap that matters in
30
- * noise the operator cannot separate out.
31
- *
32
- * `name` is optional because `exec.name` can be absent; the count still
33
- * increments, and only a present name is retained for the tool list.
34
- */
35
- unknownFamily(name: string | undefined): void;
36
- /** Calls skipped because no projection family matched. */
37
- unknownFamilies(): number;
38
- /** The retained unmapped tool names and their call counts (a copy). */
39
- unknownToolCounts(): Record<string, number>;
40
- /**
41
- * Count one prompt assembly whose protocol section was suppressed.
42
- *
43
- * `systemPrompt` assembly runs on every request, so design §5.5:378 requires
44
- * a count and forbids a per-assembly receipt. Without the count, `status`
45
- * cannot distinguish the shipped `selected + []` (correctly inert) from an
46
- * assembly whose section failed to inject — the exact "inert looks identical
47
- * to broken" failure the operator has no other signal for.
48
- */
49
- protocolSuppressed(): void;
50
- /** Prompt assemblies suppressed since load; read live by `boost status`. */
51
- protocolSuppressions(): number;
52
- /**
53
- * Count one model request whose final system prompt lost the protocol
54
- * section to a `complete: true` section.
55
- *
56
- * Distinct from {@link protocolSuppressed}: that counter includes correctly
57
- * invisible workspaces, while this one means the plugin judged the workspace
58
- * visible and still could not teach the model the plan grammar. It is the
59
- * operator's only signal that the prompt belongs to another plugin (review
60
- * row 12), and it drives the stable `ERR_HOST_COMPLETE_SECTION` code.
61
- */
62
- protocolMissing(): void;
63
- /** Model requests that lost the protocol section since load. */
64
- protocolMissings(): number;
65
- }
@@ -1,47 +0,0 @@
1
- /**
2
- * Receipt truncation: whether to cut, the two windows, and the head line.
3
- *
4
- * Lengths are counted in Unicode code points, never UTF-16 code units (design
5
- * §5.4): a CJK or emoji receipt must be cut at the same visual length as an
6
- * ASCII one, and slicing the code-point array is the only way never to split a
7
- * surrogate pair. `text.length` appears only as a cheap pre-filter — it is an
8
- * upper bound on the code-point count, so `text.length <= triggerChars` proves
9
- * that no cut is due.
10
- *
11
- * `truncate` returns `null` when a cut is not worth it: when the receipt does
12
- * not exceed the trigger, when its UTF-8 size exceeds the projection cap, or
13
- * when the rendered replacement would not be shorter than the original. Every
14
- * non-null result therefore satisfies `after.length < before.length`, which
15
- * the shadow-mode accounting relies on.
16
- *
17
- * @module dsh-boost/projection/truncate
18
- */
19
- import type { ProjectionParams } from '../types.js';
20
- /** The two windows plus the facts later stages report and account for. */
21
- export interface Truncation {
22
- /** The original receipt text, byte for byte. */
23
- before: string;
24
- /** The rendered replacement: head line, then head, then tail. */
25
- after: string;
26
- /** First `headChars` code points of `before`. */
27
- head: string;
28
- /** Last `tailChars` code points of `before`. */
29
- tail: string;
30
- /** UTF-8 bytes of `before` that neither window carries. */
31
- omittedBytes: number;
32
- /** `before` code points minus the two window sizes. */
33
- omittedCodePoints: number;
34
- }
35
- /** Render the head line of a truncation, with `en-US` thousands separators. */
36
- export declare function renderHeadLine(truncation: Truncation): string;
37
- /**
38
- * Whether `truncate` would cut `text`.
39
- *
40
- * Delegates instead of re-deriving the decision, so the two entry points can
41
- * never disagree at the edges (the exact cut, the net-gain guard, the byte
42
- * cap). The cheap pre-filters inside `truncate` keep the common "not worth
43
- * cutting" path free of code-point allocation.
44
- */
45
- export declare function shouldTruncate(text: string, params: ProjectionParams): boolean;
46
- /** Cut `text` down to its head and tail windows, or `null` when that is not worth it. */
47
- export declare function truncate(text: string, params: ProjectionParams): Truncation | null;
@@ -1,45 +0,0 @@
1
- /**
2
- * The plan-protocol system prompt section.
3
- *
4
- * This module owns the literal text that teaches the model to write a
5
- * `<CHISEL_PLAN>` block: the block shape, the candidate-id rule, the `args`
6
- * restrictions, the `$public` template, the guard vocabulary and the tools
7
- * substitution covers. Nothing here parses or validates a plan —
8
- * `src/gate/plan.ts`, `src/gate/binding.ts`, `src/gate/guard.ts` and
9
- * `src/gate/decide.ts` are the authority, and the text agrees with them.
10
- *
11
- * The referent is the most load-bearing claim: `decide` evaluates every
12
- * candidate's guards against `receipts.get(stepId)` — the receipt that just
13
- * arrived — not against the candidate's own not-yet-existing result. With no
14
- * such receipt nothing is viable, and several candidates whose guards pass on
15
- * that one receipt are alternatives for the selector, not a queue. The text
16
- * states this before the example because a guard aimed at the candidate's own
17
- * output fails every time.
18
- *
19
- * `after:"root"` is taught because T23b keys the just-arrived receipt as
20
- * `root`; an earlier executed candidate's receipt is keyed by its id. `$scalar`
21
- * needs the whole receipt to be one token (a one-path glob); an identifier
22
- * needs un-numbered output (a line-start `X: "value"`), which read/grep do not
23
- * provide; a multi-line value must be typed literally. `$single` is accepted
24
- * by binding but has no producer among the read/grep/glob receipts, so it is
25
- * deliberately not taught.
26
- *
27
- * The section is registered with `interpolate: false`; the text is still kept
28
- * free of `{{` so a later relaxation of that flag cannot rewrite it. The budget
29
- * is 1500 characters; the test pins it because this text is a permanent cost.
30
- *
31
- * @module dsh-boost/prompt/protocol
32
- */
33
- /** Section name the protocol is registered under (design §5.3). */
34
- export declare const PROTOCOL_NAME = "dsh-boost";
35
- /** Section order: alongside the other tool-contract sections. */
36
- export declare const PROTOCOL_ORDER = 100;
37
- /**
38
- * The protocol section's body, injected verbatim.
39
- *
40
- * Order is what the model needs first: where the block goes and which one
41
- * counts, what the guards read, the example and the sentence that repeats its
42
- * operand, the literal `args` rules, the guard vocabulary, the substituted
43
- * tools, and finally `$public` with its two binding sources and its limits.
44
- */
45
- export declare const PROTOCOL_TEXT = "Plan one <CHISEL_PLAN> block in visible text, not reasoning;only the first counts. It describes your next call, so guards test the receipt that just arrived, not that call's own result. No receipt, no substitution. Several steps passing on one receipt are alternatives;one is chosen. Omit when unsure;any failure runs the call normally.\n<CHISEL_PLAN>\n{\"goal\":\"g\",\"steps\":[{\"id\":\"A\",\"tool\":\"read\",\"args\":{\"file_path\":\"/repo/b.ts\"},\"guards\":[{\"text_contains\":\"2 matches\"}]}]}\n</CHISEL_PLAN>\nThe guard reads the incoming receipt, which says \"2 matches\".\nid:one capital A-Z, unique,max 26 steps.\nargs:object,not $public itself,depth<=64,no prototype keys,no $-key except $public.\nguards:>=1 other than {\"ok\":true};each guard object has exactly one form key.\n{\"ok\":true}:no error. {\"text_contains\":\"s\"}:s expected present. {\"text_not_contains\":\"s\"}:s expected absent, such as an error footer. Both case-sensitive,s non-empty,never guessed. {\"json_equals\":{\"pointer\":\"/a/b\",\"value\":\"v\"}}:the whole receipt must be JSON.\nSubstituted:read, grep, glob;others run normally.\n$public copies a value instead of retyping it:{\"$public\":{\"after\":\"root\",\"field\":\"$scalar\"}}. after:\"root\"=the incoming receipt,or a step that already ran. field:\"$scalar\"=the whole receipt is one token (a one-path glob);or X=exactly one line-start X:\"value\" or X=\"value\" (double-quoted, non-empty), which needs un-numbered output,so not read or grep. A multi-line value cannot be projected;type it literally. Else that step is skipped.";
@@ -1,198 +0,0 @@
1
- /** Why a receipt exists. `substitute-settled` is its own line because the store is append-only. */
2
- export type ReceiptKind = 'substitute' | 'substitute-settled' | 'shadow' | 'projection' | 'skip' | 'reset';
3
- /** Fields every receipt carries, before the store fills the derived ones. */
4
- type ReceiptCore = {
5
- ts: string;
6
- sessionId: string;
7
- turn: number;
8
- stepId?: string;
9
- kind: ReceiptKind;
10
- code: string;
11
- tool?: string;
12
- [k: string]: unknown;
13
- };
14
- /**
15
- * One line of the audit log.
16
- *
17
- * Invariant (plan line 581): a receipt with `kind === 'projection'` always
18
- * carries `unit: 'raw'` as a literal — T19/T26 filter on it, so a projection
19
- * receipt without it would be invisible to the counters. The plan keeps
20
- * `Receipt` an interface, which cannot pair `kind` with `unit`, so `buildReceipt`
21
- * enforces the invariant by construction: it overwrites `unit` with `'raw'` on
22
- * every projection receipt, ignoring any caller-supplied value, because the
23
- * literal is the invariant rather than a parameter. A projection receipt is
24
- * never rejected for shape; it must remain auditable.
25
- */
26
- export interface Receipt extends ReceiptCore {
27
- version: 1;
28
- receipt_hash: string;
29
- preview: string;
30
- }
31
- /** What callers hand to `append`; the store fills `version`, `receipt_hash` and `preview`. */
32
- type ReceiptInput = ReceiptCore & {
33
- version?: 1;
34
- preview?: string;
35
- };
36
- /** Tuning knobs; the defaults are the design's (§5.3). */
37
- interface ReceiptStoreOptions {
38
- fsyncEveryLines?: number;
39
- maxBytes?: number;
40
- maxLines?: number;
41
- }
42
- /**
43
- * `sha256(stable JSON)` of the fields that identify a call, first 16 hex chars.
44
- *
45
- * `args` is part of the payload on purpose: without it, two different calls of
46
- * the same tool in one turn would collide. A missing `args` hashes like `{}`,
47
- * and object keys are sorted recursively so insertion order cannot change the
48
- * hash. An own `__proto__` key is an ordinary key, not the prototype setter.
49
- *
50
- * Args deeper than {@link MAX_RECEIPT_ARGS_DEPTH} are cut with a marker before
51
- * hashing, exactly as they are before storing: otherwise the recursive walk or
52
- * `JSON.stringify` would throw and the receipt (the audit evidence) would be
53
- * lost. Two trees that differ only below the bound therefore hash alike; the
54
- * plan parser refuses such trees, and a call whose args are deeper did not come
55
- * from a plan.
56
- */
57
- export declare function receiptHash(r: {
58
- sessionId: string;
59
- turn: number;
60
- stepId?: string;
61
- tool?: string;
62
- args?: unknown;
63
- }): string;
64
- /**
65
- * Append-only, crash-safe, bounded store of receipts per session.
66
- *
67
- * See the module docs for the write and read paths. Concurrent method calls on
68
- * one instance are safe: writes are serialised through an internal promise
69
- * chain. The store is single-writer per root by design — rotation counters are
70
- * per instance, so two instances (or processes) writing one root can exceed the
71
- * shard caps and lose receipts. The plugin owns exactly one store per root.
72
- */
73
- export declare class ReceiptStore {
74
- private readonly root;
75
- private readonly fsyncEveryLines;
76
- private readonly maxBytes;
77
- private readonly maxLines;
78
- /** *Consecutive* write failures; reset by any successful append. */
79
- private failureCount;
80
- /**
81
- * Shard reads skipped by whole-store scans since the last scan that read
82
- * every shard (EACCES, EISDIR, …). A fully readable scan resets it to zero,
83
- * so a repaired shard drops `ERR_RECEIPTS_UNREADABLE` instead of pinning it
84
- * for the life of the process. Named scans neither count here nor reset it:
85
- * they do not cover the shard set status reports.
86
- */
87
- private readFailureCount;
88
- /** Whether the most recent whole-store scan hit {@link MAX_SCAN_SHARDS}. */
89
- private scanCapHit;
90
- private linesSinceSync;
91
- private readonly pending;
92
- private readonly states;
93
- private readonly dirty;
94
- private readonly disposed;
95
- private readonly disposedOrder;
96
- private dirReady;
97
- /** Writes run one at a time so rotation and buffer replay cannot interleave. */
98
- private chain;
99
- constructor(root: string, opts?: ReceiptStoreOptions);
100
- /**
101
- * Append one receipt. Never rejects: a serialisation or write failure is
102
- * counted and buffered. The session id is encoded only for the shard name;
103
- * the stored receipt keeps the original id.
104
- */
105
- append(receipt: ReceiptInput): Promise<void>;
106
- /** Force the buffered lines and the current shards to disk (called at turn end). */
107
- flush(): Promise<void>;
108
- /** Number of receipts readable for `sessionId` (`.1` plus current). */
109
- count(sessionId: string): Promise<number>;
110
- /**
111
- * Shard reads that the most recent whole-store scan skipped.
112
- *
113
- * A single unreadable shard (EACCES, a directory named `x.jsonl`, …) must
114
- * not abort the whole scan: `boost status` would turn that into
115
- * `ERR_BOOST_INTERNAL` for the entire ledger. Scans skip the shard and count
116
- * it here so status can report a stable degraded code.
117
- *
118
- * The count describes the skipped reads **since the last whole-store scan
119
- * that read every shard**, not the process lifetime: a fully readable scan
120
- * resets it, so repairing the shard and re-running `status` drops the code,
121
- * as the README instructs. A named `scan(sessionId)`/`count(sessionId)`
122
- * neither contributes to nor clears it, because it does not cover the shard
123
- * set the status total claims.
124
- */
125
- readErrors(): number;
126
- /**
127
- * Whether the most recent whole-store scan stopped at {@link MAX_SCAN_SHARDS}.
128
- *
129
- * `status` reports a total over the shards it read, so a capped scan is a
130
- * lower bound, not a total. The flag is per scan (false on the next full
131
- * scan that fits), which lets the operator see the condition clear; the
132
- * numeric totals stay unchanged and under-count, the safe direction.
133
- */
134
- scanTruncated(): boolean;
135
- /**
136
- * Yield readable receipts, oldest first: `.1` before the current shard.
137
- *
138
- * The optional `sessionId` is encoded to its shard name; the receipts keep
139
- * their original `sessionId`. With no argument, every shard under `receipts/`
140
- * is visited (encoded shard names sorted for determinism, capped at
141
- * {@link MAX_SCAN_SHARDS}), and each receipt supplies its own id from its
142
- * body. Unparseable middle lines are skipped; an unfinished trailing line is
143
- * ignored by the read and only the next write repairs it.
144
- *
145
- * A whole-store scan also maintains the two status readings: a shard it
146
- * cannot read increments {@link readErrors} (a fully readable scan resets
147
- * it), and more shards than the cap sets {@link scanTruncated}. Named scans
148
- * touch neither, because they are not the population `status` totals.
149
- */
150
- scan(sessionId?: string): AsyncIterable<Receipt>;
151
- /**
152
- * Forget one session's shard state and silence later receipts for it.
153
- *
154
- * Called from the plugin's `session/disposed` handler after `flush()`. It
155
- * evicts the cached counters, forgets any buffered lines for that session
156
- * **only when no write failure is outstanding**, and remembers the id
157
- * (bounded FIFO) so a hook that lands after disposal records nothing instead
158
- * of recreating state nothing will ever clear.
159
- *
160
- * The conditional drop is the "flush before eviction" promise: a successful
161
- * flush has already drained `pending`, so the loop is a no-op; a failed one
162
- * leaves the session's lines there, and they are the only copy of that
163
- * evidence. They stay queued for the next flush — the buffer is bounded by
164
- * {@link MAX_PENDING_LINES} and is emptied once {@link stopped} is reached,
165
- * so retaining them cannot grow without limit.
166
- */
167
- disposeSession(sessionId: string): void;
168
- /** Consecutive write failures; a successful append resets it to zero. */
169
- failures(): number;
170
- /** Fail-closed gate: true after {@link STOPPED_AFTER_FAILURES} consecutive write failures. */
171
- stopped(): boolean;
172
- private appendNow;
173
- /** The serialised body of {@link flush}; a failure is counted, never thrown. */
174
- private flushNow;
175
- /**
176
- * Count one write failure and enforce the buffer bound.
177
- *
178
- * Once the store is `stopped()` (three consecutive failures) it is
179
- * fail-closed: appends are still attempted so a recovered disk can reset the
180
- * count, but the replay buffer is dropped instead of growing for as long as
181
- * the outage lasts. Before that point `MAX_PENDING_LINES` is the hard cap.
182
- */
183
- private recordFailure;
184
- /** Replay buffered lines in order; the head stays queued until its write succeeds. */
185
- private drainPending;
186
- private writeLine;
187
- private ensureDir;
188
- /** Cached line/byte counters, loaded (and repaired) from disk on first use. */
189
- private stateFor;
190
- private rotateIfFull;
191
- private syncIfDue;
192
- private syncDirty;
193
- private syncSession;
194
- private shardPath;
195
- /** Encoded shard base names present under `receipts/`, sorted. */
196
- private listShardNames;
197
- }
198
- export {};