@dsh-cc/input-budget 0.0.0-stage → 0.9.6-rc.1

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.
package/lib/core.d.ts ADDED
@@ -0,0 +1,136 @@
1
+ /**
2
+ * The pure core of the per-step input budget governor — plan doc
3
+ * `docs/plans/2026-11-12-per-step-input-budget-governor.md` §"Budget model",
4
+ * §"Defer queue" and §"Observe mode".
5
+ *
6
+ * Everything here is a function of its arguments: messages + settings + defer
7
+ * queue + the `gateSeq` clock in, a decision batch + row fields + the new queue
8
+ * + the next `gateSeq` out. There is no cordis context, no module state and no
9
+ * clock read, so the whole algorithm is unit-testable without a runtime. The
10
+ * `agent/pre-step` listener that owns the per-session `gateSeq` and the queue
11
+ * lives in the slice-5 wiring, not here; the `enabled` setting is that
12
+ * listener's short-circuit, not a knob of this core.
13
+ *
14
+ * Budget arithmetic mirrors the Lean model
15
+ * `specs/lean/input-admission-arithmetic/Model.lean` exactly:
16
+ * `available(budget, used) = budget - used` (saturating), `fits` admits when
17
+ * `bytes <= available`, `oversize` when `budget < bytes`. Protected classes are
18
+ * never charged and never trimmed — the arithmetic face of "never touched".
19
+ *
20
+ * @module @dsh-cc/input-budget/core
21
+ */
22
+ import type { GovernorTrim } from '@dsh-cc/input-ledger';
23
+ import { type InputClass } from './classes.ts';
24
+ /** The governor knobs this core reads, as resolved by the settings surface. */
25
+ export interface GovernorSettings {
26
+ /** `'observe'` records decisions only; `'enforce'` acts on them. */
27
+ mode: 'observe' | 'enforce';
28
+ 'enter-budget-bytes': number;
29
+ 'advisory-budget-bytes': number;
30
+ 'memory-budget-bytes': number;
31
+ 'defer-ttl-steps': number;
32
+ }
33
+ /** Structural face of one content block (only `type: 'text'` blocks carry bytes). */
34
+ export interface GovernedContentBlock {
35
+ readonly type?: string;
36
+ readonly text?: string;
37
+ }
38
+ /**
39
+ * Structural face of one enter-batch message. Deliberately minimal: the
40
+ * governor reads a source kind and text-block bytes, nothing else, so a
41
+ * harness `UserMessage` satisfies it without importing harness types.
42
+ */
43
+ export interface GovernedMessage {
44
+ readonly role?: string;
45
+ readonly content?: unknown;
46
+ readonly source?: {
47
+ readonly kind?: string;
48
+ };
49
+ }
50
+ /** One trimmed message waiting in the defer backlog, stamped with `gateSeq`s. */
51
+ export interface DeferredEntry<T extends GovernedMessage = GovernedMessage> {
52
+ readonly message: T;
53
+ /** The `gateSeq` of the invocation that trimmed (enqueued) this entry. */
54
+ readonly enqueuedAtSeq: number;
55
+ /** The `gateSeq` of the last invocation that evaluated this entry. */
56
+ readonly lastOfferedSeq: number;
57
+ }
58
+ /** The batch-level inputs of one gate invocation. */
59
+ export interface GovernInput<T extends GovernedMessage = GovernedMessage> {
60
+ /** The claimed enter batch for this step, in arrival order. */
61
+ messages: readonly T[];
62
+ /** Resolved governor settings (hot-read by the listener). */
63
+ settings: GovernorSettings;
64
+ /** This session's defer backlog; absent on a fresh session or in observe mode. */
65
+ backlog?: readonly DeferredEntry<T>[];
66
+ /** The last `gateSeq` this session consumed; absent/0 before the first gate call. */
67
+ gateSeq?: number;
68
+ }
69
+ /** The `GovernorRow` fields this package owns (doc 3 owns the row schema). */
70
+ export interface GovernorDecision {
71
+ mode: 'observe' | 'enforce';
72
+ /** UTF-8 bytes per class of the decision batch (all five keys, always). */
73
+ bytesByClass: Record<string, number>;
74
+ /** Trim decisions in the order the algorithm took them. */
75
+ trimmed: GovernorTrim[];
76
+ /** Backlog entries offered to admission this invocation (0 in observe mode). */
77
+ offeredBacklog: number;
78
+ /** The enter budget could not be met within trimmable classes. */
79
+ hardOver: boolean;
80
+ }
81
+ /** One gate invocation's outcome. */
82
+ export interface GovernResult<T extends GovernedMessage = GovernedMessage> {
83
+ /** The decision batch: admitted backlog entries, then surviving fresh messages. */
84
+ messages: T[];
85
+ decision: GovernorDecision;
86
+ /** The defer backlog this invocation leaves behind (empty in observe mode). */
87
+ backlog: DeferredEntry<T>[];
88
+ /** The next `gateSeq` to hand to the following invocation. */
89
+ gateSeq: number;
90
+ }
91
+ /**
92
+ * The class budget a message of `cls` is judged against, or undefined when the
93
+ * class is never trimmed. Memory and advisory each carry their own budget: a
94
+ * 12 KiB memory entry is judged against `memory-budget-bytes`, never against
95
+ * the advisory limit.
96
+ */
97
+ export declare function classBudgetOf(cls: InputClass, settings: GovernorSettings): number | undefined;
98
+ /** Remaining room in one class budget (saturating, matching Lean's `Nat` subtraction). */
99
+ export declare function available(budget: number, used: number): number;
100
+ /** Lean `Formal.fits`: the message fits when it is within the room left after `used`. */
101
+ export declare function fits(budget: number, used: number, bytes: number): boolean;
102
+ /** Lean `Formal.oversize`: a message bigger than its whole class budget never fits. */
103
+ export declare function oversize(budget: number, bytes: number): boolean;
104
+ /**
105
+ * Lean `Formal.charged`: only budgeted classes (memory/advisory) are charged;
106
+ * governance/task/passthrough contribute zero bytes to any class budget —
107
+ * the arithmetic face of "never touched".
108
+ */
109
+ export declare function charged(cls: InputClass, bytes: number): number;
110
+ /**
111
+ * UTF-8 byte size of one message: text blocks only, the same measurement the
112
+ * input ledger records, so a governor row and a ledger row agree byte for byte.
113
+ * Non-text blocks and a non-array `content` contribute nothing.
114
+ */
115
+ export declare function messageBytes(message: GovernedMessage | undefined): number;
116
+ /** Source kind of one message; empty when the producer declared none. */
117
+ export declare function sourceKindOf(message: GovernedMessage | undefined): string;
118
+ /**
119
+ * Run one gate invocation.
120
+ *
121
+ * Order of operations (plan doc §"Defer queue"): age the backlog, admit the
122
+ * backlog FIFO against per-class budgets, then classify and trim the fresh
123
+ * batch — memory class first (its own budget), then advisory, then the enter
124
+ * budget as a last resort that only ever trims advisory and then memory. If the
125
+ * enter budget cannot be met within the trimmable classes, nothing further is
126
+ * trimmed, protected classes are untouched, and `hardOver` records the
127
+ * overflow.
128
+ *
129
+ * Observe mode runs the identical fresh-batch computation and records the same
130
+ * rows, but keeps no defer queue, simulates no backlog, emits no
131
+ * `drop-expired`, and returns the incoming batch untouched. Because its
132
+ * returned backlog is empty, an observe→enforce flip starts with an empty
133
+ * queue — the flip boundary of the plan doc, enforced by construction.
134
+ */
135
+ export declare function govern<T extends GovernedMessage>(input: GovernInput<T>): GovernResult<T>;
136
+ //# sourceMappingURL=core.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAc,MAAM,sBAAsB,CAAA;AACpE,OAAO,EAAiD,KAAK,UAAU,EAAE,MAAM,cAAc,CAAA;AAE7F,+EAA+E;AAC/E,MAAM,WAAW,gBAAgB;IAC/B,oEAAoE;IACpE,IAAI,EAAE,SAAS,GAAG,SAAS,CAAA;IAC3B,oBAAoB,EAAE,MAAM,CAAA;IAC5B,uBAAuB,EAAE,MAAM,CAAA;IAC/B,qBAAqB,EAAE,MAAM,CAAA;IAC7B,iBAAiB,EAAE,MAAM,CAAA;CAC1B;AAED,qFAAqF;AACrF,MAAM,WAAW,oBAAoB;IACnC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CACvB;AAED;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAA;IAC1B,QAAQ,CAAC,MAAM,CAAC,EAAE;QAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAC7C;AAED,iFAAiF;AACjF,MAAM,WAAW,aAAa,CAAC,CAAC,SAAS,eAAe,GAAG,eAAe;IACxE,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAA;IACnB,0EAA0E;IAC1E,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAA;IAC9B,sEAAsE;IACtE,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAA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K,EAAE,MAAM,GAAG,OAAO,CAEzE;AAED,uFAAuF;AACvF,wBAAgB,QAAQ,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAE/D;AAED;;;;GAIG;AACH,wBAAgB,OAAO,CAAC,GAAG,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAE9D;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,eAAe,GAAG,SAAS,GAAG,MAAM,CAUzE;AAED,yEAAyE;AACzE,wBAAgB,YAAY,CAAC,OAAO,EAAE,eAAe,GAAG,SAAS,GAAG,MAAM,CAGzE;AAkID;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,MAAM,CAAC,CAAC,SAAS,eAAe,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,GAAG,YAAY,CAAC,CAAC,CAAC,CAuGxF"}
package/lib/core.js ADDED
@@ -0,0 +1,307 @@
1
+ /**
2
+ * The pure core of the per-step input budget governor — plan doc
3
+ * `docs/plans/2026-11-12-per-step-input-budget-governor.md` §"Budget model",
4
+ * §"Defer queue" and §"Observe mode".
5
+ *
6
+ * Everything here is a function of its arguments: messages + settings + defer
7
+ * queue + the `gateSeq` clock in, a decision batch + row fields + the new queue
8
+ * + the next `gateSeq` out. There is no cordis context, no module state and no
9
+ * clock read, so the whole algorithm is unit-testable without a runtime. The
10
+ * `agent/pre-step` listener that owns the per-session `gateSeq` and the queue
11
+ * lives in the slice-5 wiring, not here; the `enabled` setting is that
12
+ * listener's short-circuit, not a knob of this core.
13
+ *
14
+ * Budget arithmetic mirrors the Lean model
15
+ * `specs/lean/input-admission-arithmetic/Model.lean` exactly:
16
+ * `available(budget, used) = budget - used` (saturating), `fits` admits when
17
+ * `bytes <= available`, `oversize` when `budget < bytes`. Protected classes are
18
+ * never charged and never trimmed — the arithmetic face of "never touched".
19
+ *
20
+ * @module @dsh-cc/input-budget/core
21
+ */
22
+ import { BUDGETED_CLASSES, INPUT_CLASSES, classifyKind } from "./classes.js";
23
+ /**
24
+ * The class budget a message of `cls` is judged against, or undefined when the
25
+ * class is never trimmed. Memory and advisory each carry their own budget: a
26
+ * 12 KiB memory entry is judged against `memory-budget-bytes`, never against
27
+ * the advisory limit.
28
+ */
29
+ export function classBudgetOf(cls, settings) {
30
+ if (cls === 'memory')
31
+ return settings['memory-budget-bytes'];
32
+ if (cls === 'advisory')
33
+ return settings['advisory-budget-bytes'];
34
+ return undefined;
35
+ }
36
+ /** Remaining room in one class budget (saturating, matching Lean's `Nat` subtraction). */
37
+ export function available(budget, used) {
38
+ return Math.max(0, budget - used);
39
+ }
40
+ /** Lean `Formal.fits`: the message fits when it is within the room left after `used`. */
41
+ export function fits(budget, used, bytes) {
42
+ return bytes <= available(budget, used);
43
+ }
44
+ /** Lean `Formal.oversize`: a message bigger than its whole class budget never fits. */
45
+ export function oversize(budget, bytes) {
46
+ return budget < bytes;
47
+ }
48
+ /**
49
+ * Lean `Formal.charged`: only budgeted classes (memory/advisory) are charged;
50
+ * governance/task/passthrough contribute zero bytes to any class budget —
51
+ * the arithmetic face of "never touched".
52
+ */
53
+ export function charged(cls, bytes) {
54
+ return BUDGETED_CLASSES.includes(cls) ? bytes : 0;
55
+ }
56
+ /**
57
+ * UTF-8 byte size of one message: text blocks only, the same measurement the
58
+ * input ledger records, so a governor row and a ledger row agree byte for byte.
59
+ * Non-text blocks and a non-array `content` contribute nothing.
60
+ */
61
+ export function messageBytes(message) {
62
+ const content = message?.content;
63
+ if (!Array.isArray(content))
64
+ return 0;
65
+ let bytes = 0;
66
+ for (const block of content) {
67
+ if (block?.type === 'text' && typeof block.text === 'string') {
68
+ bytes += Buffer.byteLength(block.text, 'utf8');
69
+ }
70
+ }
71
+ return bytes;
72
+ }
73
+ /** Source kind of one message; empty when the producer declared none. */
74
+ export function sourceKindOf(message) {
75
+ const kind = message?.source?.kind;
76
+ return typeof kind === 'string' ? kind : '';
77
+ }
78
+ /** Classify one message: class plus its byte size. */
79
+ function classify(message) {
80
+ return {
81
+ message,
82
+ class: classifyKind(sourceKindOf(message)),
83
+ bytes: messageBytes(message),
84
+ disposition: 'admit',
85
+ };
86
+ }
87
+ /**
88
+ * One `GovernorRow.trimmed` element; kind strings are label-capped like the ledger's.
89
+ * Local replica of the ledger's `clampLabel` (`input-ledger/src/rows.ts`, same
90
+ * 64-char privacy cap): the pure core must stay free of RUNTIME imports beyond
91
+ * its own files — the formal-design conformance adapter executes `core.ts`
92
+ * under Node type-stripping on a fresh CI checkout, where no workspace
93
+ * `lib/` (nor the sibling-harness `lib/` its bare imports would resolve to)
94
+ * has been built yet. Type-only imports are erased, so the schema dependency
95
+ * on `@dsh-cc/input-ledger` survives this constraint.
96
+ */
97
+ const MAX_LABEL_CHARS = 64;
98
+ function clampLabel(label) {
99
+ return label.length <= MAX_LABEL_CHARS ? label : label.slice(0, MAX_LABEL_CHARS);
100
+ }
101
+ function trimRow(message, bytes, action) {
102
+ const kind = sourceKindOf(message);
103
+ return { kind: clampLabel(kind.length > 0 ? kind : 'unlabelled'), bytes, action };
104
+ }
105
+ /** Normalize the clock: an absent or malformed `gateSeq` restarts at 0. */
106
+ function seqOf(gateSeq) {
107
+ return typeof gateSeq === 'number' && Number.isFinite(gateSeq) ? Math.max(0, Math.trunc(gateSeq)) : 0;
108
+ }
109
+ /** Add `bytes` to one class's running total. */
110
+ function bump(usage, cls, bytes) {
111
+ usage.set(cls, (usage.get(cls) ?? 0) + bytes);
112
+ }
113
+ /**
114
+ * Step 1 of the defer algorithm: age the backlog. An entry older than
115
+ * `defer-ttl-steps` gate invocations (strictly greater, so a TTL of 3 keeps an
116
+ * entry across invocations `seq`, `seq+1`, `seq+2`) is dropped `drop-expired`.
117
+ */
118
+ function ageBacklog(queue, seq, ttl, rows) {
119
+ const kept = [];
120
+ for (const entry of queue) {
121
+ if (seq - entry.enqueuedAtSeq > ttl) {
122
+ rows.push(trimRow(entry.message, messageBytes(entry.message), 'drop-expired'));
123
+ continue;
124
+ }
125
+ kept.push(entry);
126
+ }
127
+ return kept;
128
+ }
129
+ /**
130
+ * Step 2 of the defer algorithm: admit the backlog FIFO while the HEAD's own
131
+ * class budget has room. Each entry is judged against its own class budget
132
+ * (memory against `memory-budget-bytes`, advisory against
133
+ * `advisory-budget-bytes`), with this invocation's admitted bytes as `used`.
134
+ *
135
+ * An entry whose bytes alone exceed its class budget can never fit — possible
136
+ * only when the hot-read budgets shrank after enqueue — so it is dropped
137
+ * `drop-oversize` instead of blocking the queue forever. Every surviving entry
138
+ * is offered to this invocation, so its `lastOfferedSeq` advances to `seq`.
139
+ */
140
+ function admitBacklog(queue, seq, settings, rows) {
141
+ const admitted = [];
142
+ const used = new Map();
143
+ let index = 0;
144
+ for (; index < queue.length; index += 1) {
145
+ const entry = queue[index];
146
+ if (entry === undefined)
147
+ break;
148
+ const item = classify(entry.message);
149
+ const budget = classBudgetOf(item.class, settings);
150
+ if (budget === undefined) {
151
+ // Defensive: only budgeted classes are ever enqueued. Protected content is
152
+ // admitted rather than dropped, because losing it is the worse failure.
153
+ admitted.push(item);
154
+ continue;
155
+ }
156
+ if (oversize(budget, item.bytes)) {
157
+ rows.push(trimRow(item.message, item.bytes, 'drop-oversize'));
158
+ continue;
159
+ }
160
+ if (!fits(budget, used.get(item.class) ?? 0, item.bytes))
161
+ break;
162
+ admitted.push(item);
163
+ bump(used, item.class, item.bytes);
164
+ }
165
+ const queued = queue
166
+ .slice(index)
167
+ .map((entry) => ({ message: entry.message, enqueuedAtSeq: entry.enqueuedAtSeq, lastOfferedSeq: seq }));
168
+ return { admitted, queued, used };
169
+ }
170
+ /**
171
+ * Record one fresh trim: the row it emits and the disposition it takes.
172
+ * A message whose bytes alone exceed its own class budget is dropped
173
+ * `drop-oversize` and never enqueued — defer-then-drop would record a
174
+ * deferral that could never succeed.
175
+ */
176
+ function trimFresh(item, budget, rows) {
177
+ if (oversize(budget, item.bytes)) {
178
+ item.disposition = 'drop-oversize';
179
+ rows.push(trimRow(item.message, item.bytes, 'drop-oversize'));
180
+ return;
181
+ }
182
+ item.disposition = 'defer';
183
+ rows.push(trimRow(item.message, item.bytes, 'defer'));
184
+ }
185
+ /**
186
+ * Run one gate invocation.
187
+ *
188
+ * Order of operations (plan doc §"Defer queue"): age the backlog, admit the
189
+ * backlog FIFO against per-class budgets, then classify and trim the fresh
190
+ * batch — memory class first (its own budget), then advisory, then the enter
191
+ * budget as a last resort that only ever trims advisory and then memory. If the
192
+ * enter budget cannot be met within the trimmable classes, nothing further is
193
+ * trimmed, protected classes are untouched, and `hardOver` records the
194
+ * overflow.
195
+ *
196
+ * Observe mode runs the identical fresh-batch computation and records the same
197
+ * rows, but keeps no defer queue, simulates no backlog, emits no
198
+ * `drop-expired`, and returns the incoming batch untouched. Because its
199
+ * returned backlog is empty, an observe→enforce flip starts with an empty
200
+ * queue — the flip boundary of the plan doc, enforced by construction.
201
+ */
202
+ export function govern(input) {
203
+ const seq = seqOf(input.gateSeq) + 1;
204
+ const settings = input.settings;
205
+ const enforce = settings.mode === 'enforce';
206
+ const rows = [];
207
+ const offeredBacklog = enforce ? (input.backlog ?? []).length : 0;
208
+ const survivors = enforce
209
+ ? ageBacklog(input.backlog ?? [], seq, settings['defer-ttl-steps'], rows)
210
+ : [];
211
+ const admission = enforce
212
+ ? admitBacklog(survivors, seq, settings, rows)
213
+ : { admitted: [], queued: [], used: new Map() };
214
+ const fresh = input.messages.map(classify);
215
+ const usage = new Map(admission.used);
216
+ let total = 0;
217
+ for (const item of admission.admitted) {
218
+ total += item.bytes;
219
+ }
220
+ for (const item of fresh) {
221
+ bump(usage, item.class, item.bytes);
222
+ total += item.bytes;
223
+ }
224
+ // Budget model steps 3–4: per-class budgets, memory first then advisory,
225
+ // trimming the oldest message of the class until the class is within budget.
226
+ for (const cls of BUDGETED_CLASSES) {
227
+ const budget = classBudgetOf(cls, settings);
228
+ if (budget === undefined)
229
+ continue;
230
+ for (const item of fresh) {
231
+ if ((usage.get(cls) ?? 0) <= budget)
232
+ break;
233
+ if (item.class !== cls || item.disposition !== 'admit')
234
+ continue;
235
+ usage.set(cls, (usage.get(cls) ?? 0) - item.bytes);
236
+ total -= item.bytes;
237
+ trimFresh(item, budget, rows);
238
+ }
239
+ }
240
+ // Budget model step 5: the enter budget trims advisory, then memory, further.
241
+ // Trimmable classes are exhausted first; when even an empty trimmable set
242
+ // cannot reach the budget, nothing further is trimmed and the overflow is
243
+ // recorded (`hardOver`) instead of silently dropping protected content.
244
+ if (total > settings['enter-budget-bytes']) {
245
+ const candidates = [];
246
+ for (const cls of ['advisory', 'memory']) {
247
+ for (const item of fresh) {
248
+ if (item.class === cls && item.disposition === 'admit')
249
+ candidates.push(item);
250
+ }
251
+ }
252
+ let projected = total;
253
+ const removable = [];
254
+ for (const item of candidates) {
255
+ if (projected <= settings['enter-budget-bytes'])
256
+ break;
257
+ projected -= item.bytes;
258
+ removable.push(item);
259
+ }
260
+ if (projected <= settings['enter-budget-bytes']) {
261
+ for (const item of removable) {
262
+ total -= item.bytes;
263
+ trimFresh(item, classBudgetOf(item.class, settings) ?? item.bytes, rows);
264
+ }
265
+ }
266
+ }
267
+ const hardOver = total > settings['enter-budget-bytes'];
268
+ // Admitted backlog entries lead the batch (they are older), then the
269
+ // surviving fresh messages in arrival order — no other reordering.
270
+ const decisionMessages = [];
271
+ for (const item of admission.admitted)
272
+ decisionMessages.push(item.message);
273
+ for (const item of fresh) {
274
+ if (item.disposition === 'admit')
275
+ decisionMessages.push(item.message);
276
+ }
277
+ const bytesByClass = {};
278
+ for (const cls of INPUT_CLASSES)
279
+ bytesByClass[cls] = 0;
280
+ for (const message of decisionMessages) {
281
+ const cls = classifyKind(sourceKindOf(message));
282
+ bytesByClass[cls] = (bytesByClass[cls] ?? 0) + messageBytes(message);
283
+ }
284
+ const backlog = [];
285
+ if (enforce) {
286
+ for (const entry of admission.queued)
287
+ backlog.push(entry);
288
+ for (const item of fresh) {
289
+ if (item.disposition !== 'defer')
290
+ continue;
291
+ backlog.push({ message: item.message, enqueuedAtSeq: seq, lastOfferedSeq: seq });
292
+ }
293
+ }
294
+ return {
295
+ messages: enforce ? decisionMessages : [...input.messages],
296
+ decision: {
297
+ mode: settings.mode,
298
+ bytesByClass,
299
+ trimmed: rows,
300
+ offeredBacklog,
301
+ hardOver,
302
+ },
303
+ backlog,
304
+ gateSeq: seq,
305
+ };
306
+ }
307
+ //# sourceMappingURL=core.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,YAAY,EAAmB,MAAM,cAAc,CAAA;AAyF7F;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,GAAe,EAAE,QAA0B;IACvE,IAAI,GAAG,KAAK,QAAQ;QAAE,OAAO,QAAQ,CAAC,qBAAqB,CAAC,CAAA;IAC5D,IAAI,GAAG,KAAK,UAAU;QAAE,OAAO,QAAQ,CAAC,uBAAuB,CAAC,CAAA;IAChE,OAAO,SAAS,CAAA;AAClB,CAAC;AAED,0FAA0F;AAC1F,MAAM,UAAU,SAAS,CAAC,MAAc,EAAE,IAAY;IACpD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC,CAAA;AACnC,CAAC;AAED,yFAAyF;AACzF,MAAM,UAAU,IAAI,CAAC,MAAc,EAAE,IAAY,EAAE,KAAa;IAC9D,OAAO,KAAK,IAAI,SAAS,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;AACzC,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,QAAQ,CAAC,MAAc,EAAE,KAAa;IACpD,OAAO,MAAM,GAAG,KAAK,CAAA;AACvB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,OAAO,CAAC,GAAe,EAAE,KAAa;IACpD,OAAO,gBAAgB,CAAC,QAAQ,CAAC,GAAG,CA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AC,IAAI,CAAC,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,aAAa,EAAE,GAAG,EAAE,cAAc,EAAE,GAAG,EAAE,CAAC,CAAA;QAClF,CAAC;IACH,CAAC;IAED,OAAO;QACL,QAAQ,EAAE,OAAO,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,QAAQ,CAAC;QAC1D,QAAQ,EAAE;YACR,IAAI,EAAE,QAAQ,CAAC,IAAI;YACnB,YAAY;YACZ,OAAO,EAAE,IAAI;YACb,cAAc;YACd,QAAQ;SACT;QACD,OAAO;QACP,OAAO,EAAE,GAAG;KACb,CAAA;AACH,CAAC"}
package/lib/index.d.ts ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Per-step input budget governor — the class map, the pure governor core, the
3
+ * pipeline seam, the settings surface and the `agent/pre-step` listener for the
4
+ * context-engineering input-governance program (plan doc
5
+ * `docs/plans/2026-11-12-per-step-input-budget-governor.md`).
6
+ *
7
+ * One gate over the final per-step enter batch, arbitrating producer content by
8
+ * class: `governance`/`task`/`passthrough` are never trimmed and never
9
+ * deferred, `memory` and `advisory` are trimmed FIFO against their own byte
10
+ * budgets, and trimmed messages wait in a deterministic defer backlog aged by a
11
+ * monotonic per-session gate invocation counter. Ships observe-first: in
12
+ * observe mode the batch is returned untouched and only the decisions are
13
+ * recorded, on the same row fields enforce mode uses.
14
+ *
15
+ * The core is a pure function of its arguments (`govern`), so it is testable
16
+ * without cordis; {@linkcode apply} mounts the listener a preset row runs,
17
+ * {@linkcode buildGovernorRow} is the seam the ledger emission plugs into, and
18
+ * {@linkcode createGovernorLedgerSink} is that emission: the row goes to the
19
+ * `@dsh-cc/input-ledger` append sink under `<dshHome>/input-ledger/`, counted
20
+ * and debug-logged when the ledger is absent, disabled or failing.
21
+ *
22
+ * @module @dsh-cc/input-budget
23
+ */
24
+ export * from './classes.ts';
25
+ export * from './core.ts';
26
+ export * from './ledger.ts';
27
+ export * from './listener.ts';
28
+ export * from './pipeline.ts';
29
+ export { apply, name } from './plugin.ts';
30
+ export * from './row.ts';
31
+ export * from './settings.ts';
32
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,cAAc,cAAc,CAAA;AAC5B,cAAc,WAAW,CAAA;AACzB,cAAc,aAAa,CAAA;AAC3B,cAAc,eAAe,CAAA;AAC7B,cAAc,eAAe,CAAA;AAC7B,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AACzC,cAAc,UAAU,CAAA;AACxB,cAAc,eAAe,CAAA"}
package/lib/index.js ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Per-step input budget governor — the class map, the pure governor core, the
3
+ * pipeline seam, the settings surface and the `agent/pre-step` listener for the
4
+ * context-engineering input-governance program (plan doc
5
+ * `docs/plans/2026-11-12-per-step-input-budget-governor.md`).
6
+ *
7
+ * One gate over the final per-step enter batch, arbitrating producer content by
8
+ * class: `governance`/`task`/`passthrough` are never trimmed and never
9
+ * deferred, `memory` and `advisory` are trimmed FIFO against their own byte
10
+ * budgets, and trimmed messages wait in a deterministic defer backlog aged by a
11
+ * monotonic per-session gate invocation counter. Ships observe-first: in
12
+ * observe mode the batch is returned untouched and only the decisions are
13
+ * recorded, on the same row fields enforce mode uses.
14
+ *
15
+ * The core is a pure function of its arguments (`govern`), so it is testable
16
+ * without cordis; {@linkcode apply} mounts the listener a preset row runs,
17
+ * {@linkcode buildGovernorRow} is the seam the ledger emission plugs into, and
18
+ * {@linkcode createGovernorLedgerSink} is that emission: the row goes to the
19
+ * `@dsh-cc/input-ledger` append sink under `<dshHome>/input-ledger/`, counted
20
+ * and debug-logged when the ledger is absent, disabled or failing.
21
+ *
22
+ * @module @dsh-cc/input-budget
23
+ */
24
+ export * from "./classes.js";
25
+ export * from "./core.js";
26
+ export * from "./ledger.js";
27
+ export * from "./listener.js";
28
+ export * from "./pipeline.js";
29
+ export { apply, name } from "./plugin.js";
30
+ export * from "./row.js";
31
+ export * from "./settings.js";
32
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,cAAc,cAAc,CAAA;AAC5B,cAAc,WAAW,CAAA;AACzB,cAAc,aAAa,CAAA;AAC3B,cAAc,eAAe,CAAA;AAC7B,cAAc,eAAe,CAAA;AAC7B,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,aAAa,CAAA;AACzC,cAAc,UAAU,CAAA;AACxB,cAAc,eAAe,CAAA"}
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The ledger emission wiring — plan doc
3
+ * `docs/plans/2026-11-12-per-step-input-budget-governor.md` §"GovernorRow":
4
+ * `@dsh-cc/input-ledger` owns the row schema and the append sink, this package
5
+ * owns the row fields, and this module is the one place the two meet.
6
+ *
7
+ * The dependency is SOFT by design ("when the ledger package is absent/disabled,
8
+ * the governor still runs; rows are simply not persisted"):
9
+ *
10
+ * - no dsh-home on the host (a bare test host) — nothing to write to;
11
+ * - no cwd on the session header — no project bucket, so no file path exists
12
+ * (the ledger's own observers skip the same rows by convention);
13
+ * - `cc-input-ledger.enabled: false` — the ledger's own kill switch, hot-read
14
+ * per row exactly like the ledger's observers read it.
15
+ *
16
+ * Every one of those is a silent skip; every actual failure (a thrown path
17
+ * build, a failed append reported through `onError`) counts into
18
+ * {@linkcode getGovernorLedgerHealth}'s `droppedRows` and is debug-logged.
19
+ * Nothing here is ever thrown into the `agent/pre-step` waterfall and nothing
20
+ * here is awaited on the hot path: the append is detached and serialized by the
21
+ * ledger's own per-file write chain.
22
+ *
23
+ * @module @dsh-cc/input-budget/ledger
24
+ */
25
+ import { type GovernorRow, type InputLedgerSettings } from '@dsh-cc/input-ledger';
26
+ /**
27
+ * In-process emission health: governor rows that never reached the ledger.
28
+ * A fresh object each call, so callers cannot mutate the counter. Mirrors the
29
+ * ledger's own `getLedgerHealth()`; the sink counts here even when the ledger's
30
+ * counter also saw the failure, because this is the governor's view.
31
+ */
32
+ export declare function getGovernorLedgerHealth(): {
33
+ droppedRows: number;
34
+ };
35
+ /**
36
+ * Project bucket of one cwd: the first 16 hex chars of `sha256(realpath(cwd))`
37
+ * — the `cwdProjectKey` convention (handoff-store `cwdProjectKey`, sidecar-io
38
+ * `projectKeyOf`). A local replica, byte-identical to the one in
39
+ * `@dsh-cc/input-ledger` `src/observe.ts` (`projectKeyOfAgent`): that package
40
+ * keeps it private, and importing `@dsh-cc/sidecar-io` here would add a
41
+ * runtime dependency this soft wiring must not have.
42
+ */
43
+ export declare function projectKeyForCwd(cwd: string): string;
44
+ /**
45
+ * The project bucket of one `agent/pre-step` payload's agent, or `undefined`
46
+ * when the session header carries no cwd (the row is then skipped, as the
47
+ * ledger's observers skip theirs).
48
+ *
49
+ * @param agent - the payload's agent, of unknown shape.
50
+ */
51
+ export declare function cwdProjectKeyOf(agent: unknown): string | undefined;
52
+ /** Collaborators of the emission sink; the listener wires them to the runtime. */
53
+ export interface GovernorLedgerDeps {
54
+ /** dsh-home root; `undefined` means no persistence (a bare host). */
55
+ home: string | undefined;
56
+ /**
57
+ * Hot read of the LEDGER's settings (its `enabled` kill switch and row cap).
58
+ * Defaults to the raw user-layer file, re-read per row like the ledger's own
59
+ * observers, so a hot toggle applies on the next step without a restart.
60
+ */
61
+ readSettings?(): InputLedgerSettings;
62
+ /** Debug sink for swallowed failures (must not throw). */
63
+ debug(message: string): void;
64
+ }
65
+ /** One row sink: the listener's `emit` seam, project bucket included. */
66
+ export type GovernorRowSink = (row: GovernorRow, projectKey?: string | undefined) => void;
67
+ /**
68
+ * Build the sink that persists governor rows through the input ledger.
69
+ *
70
+ * @param deps - dsh-home root, the ledger settings read and the debug sink.
71
+ * @returns a synchronous, never-throwing row sink.
72
+ */
73
+ export declare function createGovernorLedgerSink(deps: GovernorLedgerDeps): GovernorRowSink;
74
+ //# sourceMappingURL=ledger.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ledger.d.ts","sourceRoot":"","sources":["../src/ledger.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAIH,OAAO,EAKL,KAAK,WAAW,EAChB,KAAK,mBAAmB,EACzB,MAAM,sBAAsB,CAAA;AAQ7B;;;;;GAKG;AACH,wBAAgB,uBAAuB,IAAI;IAAE,WAAW,EAAE,MAAM,CAAA;CAAE,CAEjE;AAgBD;;;;;;;GAOG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEpD;AASD;;;;;;GAMG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAGlE;AAED,kFAAkF;AAClF,MAAM,WAAW,kBAAkB;IACjC,qEAAqE;IACrE,IAAI,EAAE,MAAM,GAAG,SAAS,CAAA;IACxB;;;;OAIG;IACH,YAAY,CAAC,IAAI,mBAAmB,CAAA;IACpC,0DAA0D;IAC1D,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAA;CAC7B;AAED,yEAAyE;AACzE,MAAM,MAAM,eAAe,GAAG,CAAC,GAAG,EAAE,WAAW,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,KAAK,IAAI,CAAA;AAOzF;;;;;GAKG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,kBAAkB,GAAG,eAAe,CAqClF"}