@cohortapp/agent-sdk 2.5.1 → 2.6.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/bin/maestro.mjs +305 -89
- package/bin/maestro.test.mjs +357 -48
- package/docs/runbooks/backup-restore.md +65 -33
- package/framework-features.json +4 -4
- package/lib/backup/policy.mjs +710 -0
- package/lib/backup/policy.test.mjs +305 -0
- package/lib/budget-escalate.mjs +133 -0
- package/lib/budget-escalate.test.mjs +232 -0
- package/lib/budget-guard.envelope.test.mjs +476 -0
- package/lib/budget-guard.mjs +853 -75
- package/lib/budget-guard.test.mjs +91 -42
- package/lib/cadences.mjs +33 -0
- package/lib/channels/orgmail/adapter.mjs +88 -3
- package/lib/channels/orgmail/adapter.test.mjs +137 -0
- package/lib/channels/repeat-suppressor.mjs +198 -0
- package/lib/channels/repeat-suppressor.test.mjs +134 -0
- package/lib/comms/receipts.mjs +297 -0
- package/lib/cost/ledger-row.mjs +333 -0
- package/lib/cost/ledger-row.test.mjs +183 -0
- package/lib/execution/drive.mjs +28 -1
- package/lib/execution/effects.mjs +191 -12
- package/lib/execution/effects.test.mjs +50 -11
- package/lib/goals/admission.mjs +13 -1
- package/lib/goals/admission.test.mjs +26 -1
- package/lib/goals/loop.mjs +13 -0
- package/lib/kpi-sensors.test.mjs +3 -0
- package/lib/mandate/cache.mjs +13 -5
- package/lib/mandate/derive.mjs +146 -21
- package/lib/mandate/derive.test.mjs +50 -6
- package/lib/mandate/model.mjs +32 -4
- package/lib/mandate/refresh.test.mjs +16 -2
- package/lib/mcp/server.test.mjs +12 -3
- package/lib/model-router/economics.mjs +107 -76
- package/lib/model-router/economics.test.mjs +64 -46
- package/lib/model-router/integration-coverage.test.mjs +39 -37
- package/lib/model-router/ledger.mjs +75 -22
- package/lib/model-router/ledger.test.mjs +35 -2
- package/lib/org/client.mjs +14 -0
- package/lib/org/cost-sync.mjs +16 -2
- package/lib/org/doctor.mjs +62 -1
- package/lib/org/doctor.test.mjs +36 -3
- package/lib/org/email-remedy.mjs +49 -0
- package/lib/org/engagement-ledger.mjs +376 -0
- package/lib/org/engagement-ledger.test.mjs +112 -0
- package/lib/org/engagement.mjs +1056 -0
- package/lib/org/engagement.test.mjs +739 -0
- package/lib/org/messaging.mjs +230 -3
- package/lib/org/messaging.test.mjs +110 -1
- package/lib/org/param-contract.mjs +56 -2
- package/lib/org/param-contract.test.mjs +26 -0
- package/lib/org/protocol.checksum +1 -1
- package/lib/org/protocol.mjs +5 -0
- package/lib/org/protocol.test.mjs +7 -1
- package/lib/org/tool-surface.mjs +506 -10
- package/lib/org/tool-surface.test.mjs +191 -7
- package/lib/org/ui-parity.mjs +333 -6
- package/lib/org/ui-parity.test.mjs +96 -3
- package/lib/org/work-ledger.mjs +241 -0
- package/lib/org/work-ledger.test.mjs +237 -0
- package/lib/plan/adoption-e2e.test.mjs +366 -0
- package/lib/plan/budget-enforcement.test.mjs +400 -0
- package/lib/plan/budget-runtime.mjs +215 -0
- package/lib/plan/compile.mjs +201 -5
- package/lib/plan/compile.test.mjs +19 -5
- package/lib/plan/emit.mjs +8 -0
- package/lib/plan/emit.test.mjs +18 -0
- package/lib/resource-governor.mjs +58 -12
- package/lib/resource-governor.test.mjs +41 -1
- package/lib/security/audit-engine.mjs +45 -8
- package/lib/security/audit-engine.test.mjs +35 -0
- package/lib/setup/enroll-from-cohort.mjs +14 -1
- package/lib/setup/sections/mandate.mjs +48 -7
- package/lib/setup/sections/mandate.test.mjs +17 -2
- package/lib/setup/sections/orgmail.mjs +10 -2
- package/lib/setup/state.mjs +83 -2
- package/lib/telemetry/collect.mjs +360 -20
- package/lib/telemetry/collect.test.mjs +266 -0
- package/package.json +1 -1
- package/scripts/cost/track-claude-usage.mjs +207 -48
- package/scripts/cost/track-claude-usage.test.mjs +148 -0
- package/scripts/daemon/agent-daemon.mjs +315 -17
- package/scripts/daemon/assurance-e2e.test.mjs +421 -0
- package/scripts/daemon/assurance.mjs +944 -0
- package/scripts/daemon/assurance.test.mjs +668 -0
- package/scripts/daemon/cadence-consumer-governance.test.mjs +56 -0
- package/scripts/daemon/cadence-consumer.mjs +147 -9
- package/scripts/daemon/cadence-consumer.test.mjs +6 -0
- package/scripts/daemon/cadence-handlers.mjs +158 -0
- package/scripts/daemon/cadence-handlers.test.mjs +64 -0
- package/scripts/daemon/classifier.test.mjs +18 -9
- package/scripts/daemon/deliver.mjs +314 -0
- package/scripts/daemon/dispatcher-governance.test.mjs +10 -0
- package/scripts/daemon/dispatcher.mjs +64 -6
- package/scripts/daemon/responder-cost.test.mjs +68 -0
- package/scripts/daemon/responder.mjs +351 -298
- package/scripts/local-triggers/generate-plists.test.mjs +7 -4
- package/scripts/maintenance/backup-run.mjs +415 -0
- package/scripts/maintenance/backup-to-cloud.sh +16 -116
- package/scripts/org/send-orgmail.mjs +16 -0
- package/scripts/record-receipt.sh +63 -0
- package/scripts/restore-from-backup.sh +14 -3
- package/scripts/restore-from-backup.test.mjs +8 -5
- package/scripts/send-email-threaded.py +47 -0
- package/scripts/send-sms.sh +4 -0
- package/scripts/send-whatsapp.sh +4 -0
- package/scripts/setup/init-backup.mjs +93 -38
- package/scripts/slack-send.sh +12 -0
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* budget-enforcement.test.mjs — the ceiling, enforced.
|
|
3
|
+
*
|
|
4
|
+
* Covers the three places a breach actually bites:
|
|
5
|
+
* compile.applyBudgetPosture the plan-level suspension (125%)
|
|
6
|
+
* compile.obligationAllowedUnderPosture the per-tick form the daemon uses
|
|
7
|
+
* budget-runtime.reconcileBudgetPosture the I/O around them (drift, band edge)
|
|
8
|
+
*
|
|
9
|
+
* The invariant every one of these tests exists to protect: WE DEGRADE, WE NEVER
|
|
10
|
+
* BRICK. At every band, the inline cadences still run and the seat still answers
|
|
11
|
+
* its inbox.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { test } from "node:test";
|
|
15
|
+
import assert from "node:assert/strict";
|
|
16
|
+
import { promises as fsp } from "node:fs";
|
|
17
|
+
import { tmpdir } from "node:os";
|
|
18
|
+
import { join } from "node:path";
|
|
19
|
+
|
|
20
|
+
import { compilePlan, applyBudgetPosture, obligationAllowedUnderPosture } from "./compile.mjs";
|
|
21
|
+
import { reconcileBudgetPosture, readPosture } from "./budget-runtime.mjs";
|
|
22
|
+
import { postureForBand } from "../budget-guard.mjs";
|
|
23
|
+
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
// fixtures
|
|
26
|
+
// ---------------------------------------------------------------------------
|
|
27
|
+
|
|
28
|
+
const manifest = () => ({
|
|
29
|
+
schemaVersion: 1,
|
|
30
|
+
entries: [
|
|
31
|
+
{ id: "books_reports", plane: "protocol", kind: "method", reachable: true, blastRadius: "internal" },
|
|
32
|
+
{ id: "board_ready", plane: "protocol", kind: "method", reachable: true, blastRadius: "internal" },
|
|
33
|
+
{ id: "messaging_send", plane: "protocol", kind: "method", reachable: true, blastRadius: "external" },
|
|
34
|
+
],
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
/** An adopted, fully-admissible objective — the kind that compiles obligations. */
|
|
38
|
+
function objective(over = {}) {
|
|
39
|
+
return {
|
|
40
|
+
id: `obj-${over.key || "a"}`,
|
|
41
|
+
key: over.key || "a",
|
|
42
|
+
kind: "OBJECTIVE",
|
|
43
|
+
state: "active",
|
|
44
|
+
text: "an adopted objective",
|
|
45
|
+
memberId: "A016",
|
|
46
|
+
parentId: null,
|
|
47
|
+
parentKey: null,
|
|
48
|
+
charterSectionId: "sec-1",
|
|
49
|
+
metric: "gross_margin",
|
|
50
|
+
unit: "pct",
|
|
51
|
+
direction: "up",
|
|
52
|
+
baseline: 10,
|
|
53
|
+
target: 40,
|
|
54
|
+
value: 12,
|
|
55
|
+
tolerance: 1,
|
|
56
|
+
weight: 1,
|
|
57
|
+
cadence: "weekly",
|
|
58
|
+
sensor: { source: "method", capability: "books_reports", params: {} },
|
|
59
|
+
budgetCentsPerPeriod: null,
|
|
60
|
+
collaborators: [],
|
|
61
|
+
adoptedById: "HUMAN-1",
|
|
62
|
+
adoptedAt: "2026-06-01T00:00:00.000Z",
|
|
63
|
+
...over,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function mandate(over = {}) {
|
|
68
|
+
return {
|
|
69
|
+
contractVersion: 1,
|
|
70
|
+
memberId: "A016",
|
|
71
|
+
objectives: [],
|
|
72
|
+
proposed: [],
|
|
73
|
+
budgetCentsPerPeriod: null,
|
|
74
|
+
seatBudgetCents: null,
|
|
75
|
+
budgetPeriod: null,
|
|
76
|
+
budgetSource: "employee.payBasis.meteredBudget",
|
|
77
|
+
collaborators: [],
|
|
78
|
+
reactsTo: [],
|
|
79
|
+
degradations: [],
|
|
80
|
+
generatedAt: "2026-06-01T00:00:00.000Z",
|
|
81
|
+
...over,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const STANDARD = [
|
|
86
|
+
{ id: "cadence-bus-heartbeat", mode: "inline", interval: 300 },
|
|
87
|
+
{ id: "inbox-processor", mode: "guarded", calendar: { hour: 9 } },
|
|
88
|
+
];
|
|
89
|
+
|
|
90
|
+
function fundedPlan() {
|
|
91
|
+
return compilePlan({
|
|
92
|
+
mandate: mandate({
|
|
93
|
+
objectives: [objective({ key: "gross-margin", budgetCentsPerPeriod: 60_000 })],
|
|
94
|
+
seatBudgetCents: 60_000,
|
|
95
|
+
budgetPeriod: "monthly",
|
|
96
|
+
}),
|
|
97
|
+
manifest: manifest(),
|
|
98
|
+
standardCadences: STANDARD,
|
|
99
|
+
log: () => {},
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
// the funded envelope reaches the obligations (the PROOF this all rests on)
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
test("a funded envelope produces per-obligation budgets derived from it", () => {
|
|
108
|
+
const plan = compilePlan({
|
|
109
|
+
mandate: mandate({
|
|
110
|
+
objectives: [
|
|
111
|
+
objective({ key: "a", budgetCentsPerPeriod: 45_000, weight: 3 }),
|
|
112
|
+
objective({ key: "b", budgetCentsPerPeriod: 15_000, weight: 1 }),
|
|
113
|
+
],
|
|
114
|
+
seatBudgetCents: 60_000,
|
|
115
|
+
budgetPeriod: "monthly",
|
|
116
|
+
}),
|
|
117
|
+
manifest: manifest(),
|
|
118
|
+
standardCadences: STANDARD,
|
|
119
|
+
log: () => {},
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
const funded = plan.obligations.filter((o) => Number.isFinite(o.budget_cents_per_period));
|
|
123
|
+
assert.ok(funded.length >= 4, "each objective yields a measure SCHEDULE + an OUTCOME, both funded");
|
|
124
|
+
assert.equal(plan.obligations.find((o) => o.key === "outcome.a").budget_cents_per_period, 45_000);
|
|
125
|
+
assert.equal(plan.obligations.find((o) => o.key === "outcome.b").budget_cents_per_period, 15_000);
|
|
126
|
+
// The apportioned shares sum to the envelope — no cents invented, none leaked.
|
|
127
|
+
const outcomes = plan.obligations.filter((o) => o.kind === "OUTCOME");
|
|
128
|
+
assert.equal(outcomes.reduce((n, o) => n + o.budget_cents_per_period, 0), 60_000);
|
|
129
|
+
assert.equal(plan.contract.unmetered, false);
|
|
130
|
+
|
|
131
|
+
// And the obligations with NO objective behind them stay honestly unmetered
|
|
132
|
+
// rather than inheriting a fiction.
|
|
133
|
+
const standard = plan.obligations.find((o) => o.key === "schedule.inbox-processor");
|
|
134
|
+
assert.equal(standard.budget_cents_per_period, null);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test("an UNFUNDED seat compiles unmetered and says so — it does not invent 500c", () => {
|
|
138
|
+
const warnings = [];
|
|
139
|
+
const plan = compilePlan({
|
|
140
|
+
mandate: mandate({ objectives: [objective({ key: "a" })] }),
|
|
141
|
+
manifest: manifest(),
|
|
142
|
+
standardCadences: STANDARD,
|
|
143
|
+
log: (_l, m) => warnings.push(m),
|
|
144
|
+
});
|
|
145
|
+
assert.equal(plan.contract.unmetered, true);
|
|
146
|
+
assert.ok(plan.obligations.every((o) => o.budget_cents_per_period === null));
|
|
147
|
+
assert.ok(warnings.some((w) => /no seat envelope/.test(w) && /NOT enforced/.test(w)));
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
// ---------------------------------------------------------------------------
|
|
151
|
+
// applyBudgetPosture — the 125% rung
|
|
152
|
+
// ---------------------------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
test("below 125% nothing is suspended", () => {
|
|
155
|
+
const plan = fundedPlan();
|
|
156
|
+
for (const band of [0, 80, 100]) {
|
|
157
|
+
const r = applyBudgetPosture(plan, postureForBand(band));
|
|
158
|
+
assert.deepEqual(r.suspended, [], `band ${band} must not suspend obligations`);
|
|
159
|
+
assert.equal(r.drift.length, 0);
|
|
160
|
+
}
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test("at 125% the objective's obligations suspend — and NOTHING else does", () => {
|
|
164
|
+
const plan = fundedPlan();
|
|
165
|
+
const r = applyBudgetPosture(plan, postureForBand(125), { spentUSD: 41, capUSD: 30 });
|
|
166
|
+
|
|
167
|
+
assert.ok(r.suspended.includes("outcome.gross-margin"));
|
|
168
|
+
assert.ok(r.suspended.includes("schedule.measure.gross-margin"),
|
|
169
|
+
"the measure cadence spends on the same warrant as its OUTCOME");
|
|
170
|
+
|
|
171
|
+
// The seat's own life-support is untouched at every band.
|
|
172
|
+
const heartbeat = r.obligations.find((o) => o.key === "schedule.cadence-bus-heartbeat");
|
|
173
|
+
assert.equal(heartbeat.status, "active", "an inline cadence costs nothing and must never be suspended");
|
|
174
|
+
// The trap this asserts against: OUTCOME rows are `offline_safe:true`, so an
|
|
175
|
+
// exemption keyed on that flag suspends nothing at all.
|
|
176
|
+
assert.equal(r.obligations.find((o) => o.key === "outcome.gross-margin").offline_safe, true);
|
|
177
|
+
assert.equal(r.obligations.find((o) => o.key === "outcome.gross-margin").status, "suspended");
|
|
178
|
+
const inbox = r.obligations.find((o) => o.key === "schedule.inbox-processor");
|
|
179
|
+
assert.equal(inbox.status, "active", "the seat keeps answering its inbox — Invariant #1");
|
|
180
|
+
for (const react of r.obligations.filter((o) => o.kind === "REACT")) {
|
|
181
|
+
assert.equal(react.status, "active", "REACT obligations are how a human reaches this seat");
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// One drift row per suspended obligation, carrying the evidence.
|
|
185
|
+
assert.equal(r.drift.length, r.suspended.length);
|
|
186
|
+
for (const d of r.drift) {
|
|
187
|
+
assert.equal(d.kind, "budget_breach");
|
|
188
|
+
assert.equal(d.detail.band, 125);
|
|
189
|
+
assert.equal(d.detail.spentUSD, 41);
|
|
190
|
+
assert.equal(d.detail.capUSD, 30);
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test("applyBudgetPosture is idempotent and does not mutate its input", () => {
|
|
195
|
+
const plan = fundedPlan();
|
|
196
|
+
const before = JSON.stringify(plan.obligations);
|
|
197
|
+
const once = applyBudgetPosture(plan, postureForBand(125));
|
|
198
|
+
const twice = applyBudgetPosture({ obligations: once.obligations }, postureForBand(125));
|
|
199
|
+
assert.equal(JSON.stringify(plan.obligations), before, "the compiled plan is not mutated");
|
|
200
|
+
assert.deepEqual(twice.suspended, [], "an already-suspended obligation is not re-suspended, nor re-drifted");
|
|
201
|
+
assert.equal(twice.drift.length, 0);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
// ---------------------------------------------------------------------------
|
|
205
|
+
// obligationAllowedUnderPosture — the per-tick form the daemon uses
|
|
206
|
+
// ---------------------------------------------------------------------------
|
|
207
|
+
|
|
208
|
+
test("the daemon's per-tick gate agrees with the plan-level transition", () => {
|
|
209
|
+
const outcomeCadence = { kind: "SCHEDULE", scope: "mandate", objective_id: "obj-a", offline_safe: false, mode: "guarded" };
|
|
210
|
+
const heartbeat = { kind: "SCHEDULE", scope: "standard", objective_id: null, offline_safe: true, mode: "inline" };
|
|
211
|
+
const standard = { kind: "SCHEDULE", scope: "standard", objective_id: null, offline_safe: false, mode: "guarded" };
|
|
212
|
+
|
|
213
|
+
assert.equal(obligationAllowedUnderPosture(outcomeCadence, postureForBand(100)).allowed, true);
|
|
214
|
+
assert.equal(obligationAllowedUnderPosture(outcomeCadence, postureForBand(125)).allowed, false);
|
|
215
|
+
assert.match(obligationAllowedUnderPosture(outcomeCadence, postureForBand(125)).reason, /suspended/);
|
|
216
|
+
|
|
217
|
+
// Life support, at the worst band there is.
|
|
218
|
+
assert.equal(obligationAllowedUnderPosture(heartbeat, postureForBand(150)).allowed, true);
|
|
219
|
+
|
|
220
|
+
// >150%: a plain standard cadence is a spawn that is not a human reply.
|
|
221
|
+
assert.equal(obligationAllowedUnderPosture(standard, postureForBand(125)).allowed, true);
|
|
222
|
+
assert.equal(obligationAllowedUnderPosture(standard, postureForBand(150)).allowed, false);
|
|
223
|
+
assert.match(obligationAllowedUnderPosture(standard, postureForBand(150)).reason, /not a direct human reply/);
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
// ---------------------------------------------------------------------------
|
|
227
|
+
// reconcileBudgetPosture — drift on the band EDGE, plan file untouched
|
|
228
|
+
// ---------------------------------------------------------------------------
|
|
229
|
+
|
|
230
|
+
async function tmpRoot() {
|
|
231
|
+
const dir = join(tmpdir(), `budget-runtime-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`);
|
|
232
|
+
await fsp.mkdir(join(dir, "state", "plan"), { recursive: true });
|
|
233
|
+
return dir;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
test("reconcile records budget_breach drift once per band edge, not once per tick", async () => {
|
|
237
|
+
const root = await tmpRoot();
|
|
238
|
+
try {
|
|
239
|
+
const plan = fundedPlan();
|
|
240
|
+
const drift = [];
|
|
241
|
+
const deps = { plan, appendDrift: (row) => { drift.push(row); return true; }, log: () => {} };
|
|
242
|
+
|
|
243
|
+
const first = await reconcileBudgetPosture({ agentRoot: root, posture: postureForBand(125), status: { spentUSD: 41, capUSD: 30, pct: 137 } }, deps);
|
|
244
|
+
assert.ok(first.suspended.length >= 2);
|
|
245
|
+
assert.equal(first.recorded, first.suspended.length);
|
|
246
|
+
assert.equal(readPosture(root).band, 125, "the acted-on band is persisted");
|
|
247
|
+
|
|
248
|
+
const again = await reconcileBudgetPosture({ agentRoot: root, posture: postureForBand(125), status: {} }, deps);
|
|
249
|
+
assert.equal(again.recorded, 0, "same band, same tick-after-tick: no new rows");
|
|
250
|
+
assert.equal(drift.length, first.recorded);
|
|
251
|
+
|
|
252
|
+
// Coming back DOWN is an edge too — a human who saw the suspension needs the
|
|
253
|
+
// clearing edge as well.
|
|
254
|
+
const down = await reconcileBudgetPosture({ agentRoot: root, posture: postureForBand(0), status: {} }, deps);
|
|
255
|
+
assert.equal(down.suspended.length, 0);
|
|
256
|
+
assert.equal(readPosture(root).band, 0);
|
|
257
|
+
} finally { await fsp.rm(root, { recursive: true, force: true }); }
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
test("a breach is mirrored to hq, and the clearing edge resolves it there", async () => {
|
|
261
|
+
const root = await tmpRoot();
|
|
262
|
+
try {
|
|
263
|
+
const plan = fundedPlan();
|
|
264
|
+
const mirrored = [];
|
|
265
|
+
const deps = {
|
|
266
|
+
plan,
|
|
267
|
+
appendDrift: () => true,
|
|
268
|
+
log: () => {},
|
|
269
|
+
mirrorDrift: async (row) => { mirrored.push(row); return { ok: true }; },
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
const up = await reconcileBudgetPosture({ agentRoot: root, posture: postureForBand(125), status: { spentUSD: 41, capUSD: 30 } }, deps);
|
|
273
|
+
assert.equal(up.mirrored, up.drift.length);
|
|
274
|
+
assert.ok(mirrored.every((m) => m.kind === "budget_breach" && !m.resolve));
|
|
275
|
+
|
|
276
|
+
// Back under the ceiling: the open rows are RESOLVED at hq, or the org shows
|
|
277
|
+
// a permanently-breached seat that has in fact recovered.
|
|
278
|
+
mirrored.length = 0;
|
|
279
|
+
const down = await reconcileBudgetPosture({ agentRoot: root, posture: postureForBand(0), status: {} }, deps);
|
|
280
|
+
assert.equal(down.suspended.length, 0);
|
|
281
|
+
assert.ok(mirrored.length > 0, "the clearing edge is reported too");
|
|
282
|
+
assert.ok(mirrored.every((m) => m.resolve === true));
|
|
283
|
+
} finally { await fsp.rm(root, { recursive: true, force: true }); }
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
test("an hq that rejects or throws never blocks the LOCAL suspension", async () => {
|
|
287
|
+
const root = await tmpRoot();
|
|
288
|
+
try {
|
|
289
|
+
const plan = fundedPlan();
|
|
290
|
+
const logged = [];
|
|
291
|
+
const local = [];
|
|
292
|
+
const r = await reconcileBudgetPosture(
|
|
293
|
+
{ agentRoot: root, posture: postureForBand(125), status: {} },
|
|
294
|
+
{
|
|
295
|
+
plan,
|
|
296
|
+
appendDrift: (row) => { local.push(row); return true; },
|
|
297
|
+
log: (l, m) => logged.push(`${l}:${m}`),
|
|
298
|
+
mirrorDrift: async () => { throw new Error("hq unreachable"); },
|
|
299
|
+
}
|
|
300
|
+
);
|
|
301
|
+
assert.ok(r.suspended.length > 0, "the obligations are still suspended");
|
|
302
|
+
assert.equal(r.recorded, local.length, "and the local record is complete");
|
|
303
|
+
assert.equal(r.mirrored, 0);
|
|
304
|
+
assert.ok(logged.some((l) => /could not mirror/.test(l)), "the mirror failure is named, not swallowed");
|
|
305
|
+
} finally { await fsp.rm(root, { recursive: true, force: true }); }
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
test("a seat with no compiled plan reconciles cleanly instead of throwing", async () => {
|
|
309
|
+
const root = await tmpRoot();
|
|
310
|
+
try {
|
|
311
|
+
const logged = [];
|
|
312
|
+
const r = await reconcileBudgetPosture(
|
|
313
|
+
{ agentRoot: root, posture: postureForBand(150), status: {} },
|
|
314
|
+
{ log: (l, m) => logged.push(`${l}:${m}`) }
|
|
315
|
+
);
|
|
316
|
+
assert.equal(r.ok, true);
|
|
317
|
+
assert.deepEqual(r.suspended, []);
|
|
318
|
+
assert.match(r.reason, /config\/plan\.yaml is absent/);
|
|
319
|
+
assert.ok(logged.some((l) => /no plan to suspend/.test(l)), "and it says so rather than passing silently");
|
|
320
|
+
} finally { await fsp.rm(root, { recursive: true, force: true }); }
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
// ---------------------------------------------------------------------------
|
|
324
|
+
// BAND 150 MUST NOT SILENCE THE INBOX
|
|
325
|
+
// ---------------------------------------------------------------------------
|
|
326
|
+
|
|
327
|
+
test("band 150 defers discretionary cadences but NEVER the human lane", () => {
|
|
328
|
+
// The 150% rung was implemented as `kind !== "REACT"`, and every cadence the
|
|
329
|
+
// consumer evaluates is a SCHEDULE — so `inbox-processor` and
|
|
330
|
+
// `messaging-inbound` (the only puller of org DMs and @mentions) were deferred
|
|
331
|
+
// too. It only looked harmless because both guards default to
|
|
332
|
+
// `decision:"inline"` and return before the gate; set INBOX_CADENCE_ESCALATE=1
|
|
333
|
+
// or MESSAGING_INBOUND_ESCALATE=1 — the documented cadence-only mode — and the
|
|
334
|
+
// seat stopped reading its inbox at a budget breach. That is the bricking
|
|
335
|
+
// Invariant #1 forbids.
|
|
336
|
+
const posture = postureForBand(150);
|
|
337
|
+
assert.equal(posture.refuseNonHumanSpawn, true);
|
|
338
|
+
|
|
339
|
+
const inbox = { key: "schedule.inbox-processor", kind: "SCHEDULE", mode: "guarded", human_lane: true, status: "active" };
|
|
340
|
+
const inbound = { key: "schedule.messaging-inbound", kind: "SCHEDULE", mode: "guarded", human_lane: true, status: "active" };
|
|
341
|
+
const backlog = { key: "schedule.backlog-executor", kind: "SCHEDULE", mode: "guarded", human_lane: false, status: "active" };
|
|
342
|
+
const react = { key: "react.task.assigned", kind: "REACT", mode: "escalate", status: "active" };
|
|
343
|
+
|
|
344
|
+
assert.equal(obligationAllowedUnderPosture(inbox, posture).allowed, true, "the seat keeps reading its inbox");
|
|
345
|
+
assert.equal(obligationAllowedUnderPosture(inbound, posture).allowed, true, "and keeps PULLING messages into it");
|
|
346
|
+
assert.equal(obligationAllowedUnderPosture(react, posture).allowed, true);
|
|
347
|
+
assert.equal(obligationAllowedUnderPosture(backlog, posture).allowed, false, "discretionary work does defer");
|
|
348
|
+
assert.match(obligationAllowedUnderPosture(backlog, posture).reason, /not a direct human reply/);
|
|
349
|
+
});
|
|
350
|
+
|
|
351
|
+
test("the compiler STAMPS the human lane on the plan, so an operator can read it", () => {
|
|
352
|
+
// Inferring the lane at enforcement time would leave the plan on disk silent
|
|
353
|
+
// about which obligations a breach may never stop.
|
|
354
|
+
const plan = compilePlan({
|
|
355
|
+
mandate: {},
|
|
356
|
+
manifest: { entries: [] },
|
|
357
|
+
standardCadences: [
|
|
358
|
+
{ id: "inbox-processor", scope: "standard", mode: "guarded", interval: 300 },
|
|
359
|
+
{ id: "messaging-inbound", scope: "standard", mode: "guarded", interval: 45 },
|
|
360
|
+
{ id: "backlog-executor", scope: "standard", mode: "guarded", interval: 600 },
|
|
361
|
+
{ id: "dynamic-jobs", scope: "standard", mode: "guarded", interval: 60 },
|
|
362
|
+
],
|
|
363
|
+
log: () => {},
|
|
364
|
+
});
|
|
365
|
+
const laneOf = (id) => plan.obligations.find((o) => o.key === `schedule.${id}`).human_lane;
|
|
366
|
+
assert.equal(laneOf("inbox-processor"), true);
|
|
367
|
+
assert.equal(laneOf("messaging-inbound"), true);
|
|
368
|
+
assert.equal(laneOf("backlog-executor"), false);
|
|
369
|
+
assert.equal(laneOf("dynamic-jobs"), false, "the agent's own reminders are not somebody waiting on a reply");
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
test("STRUCTURAL: the drift return-leg runs on the MONEY clock, not the daily one", async () => {
|
|
373
|
+
// `reconcileBudgetPosture` had exactly one caller: `guardGoalSteward`, which
|
|
374
|
+
// `lib/cadences.mjs` schedules at 07:15 DAILY — while the band it reads resets
|
|
375
|
+
// at UTC midnight. A seat could hit 150% every afternoon for a month and hq
|
|
376
|
+
// would never see one `budget_breach` drift row, because by the next 07:15 the
|
|
377
|
+
// band it observed was 0 again. Local enforcement was fine (`governanceGate`
|
|
378
|
+
// re-reads per tick); it was the RECORD — the thing the person who funds the
|
|
379
|
+
// seat looks at — that never arrived.
|
|
380
|
+
const { readFileSync } = await import("node:fs");
|
|
381
|
+
const { fileURLToPath } = await import("node:url");
|
|
382
|
+
const root = fileURLToPath(new URL("../../", import.meta.url));
|
|
383
|
+
|
|
384
|
+
const consumer = readFileSync(`${root}scripts/daemon/cadence-consumer.mjs`, "utf-8");
|
|
385
|
+
assert.match(consumer, /reconcileBudgetPosture/, "the consumer reconciles the posture itself");
|
|
386
|
+
|
|
387
|
+
// It must live inside the escalation timer (the 5-minute one), not in a
|
|
388
|
+
// calendar-scheduled handler.
|
|
389
|
+
const timerAt = consumer.indexOf("const escalateTimer");
|
|
390
|
+
const reconcileAt = consumer.indexOf("reconcileBudgetPosture", timerAt);
|
|
391
|
+
const timerEndsAt = consumer.indexOf("}, budgetEscalateMs)", timerAt);
|
|
392
|
+
assert.ok(timerAt > 0 && reconcileAt > timerAt && reconcileAt < timerEndsAt,
|
|
393
|
+
"the reconcile is inside the budgetEscalateMs timer");
|
|
394
|
+
assert.match(consumer, /DEFAULT_BUDGET_ESCALATE_MS = 5 \* 60_000/, "and that timer is 5 minutes");
|
|
395
|
+
|
|
396
|
+
// The daily caller stays — it is idempotent and harmless — but it is no longer
|
|
397
|
+
// the only one.
|
|
398
|
+
const handlers = readFileSync(`${root}scripts/daemon/cadence-handlers.mjs`, "utf-8");
|
|
399
|
+
assert.match(handlers, /reconcileBudgetPosture/);
|
|
400
|
+
});
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/plan/budget-runtime.mjs — the 125 % rung, applied to the plan on disk.
|
|
3
|
+
*
|
|
4
|
+
* `compilePlan` suspends an objective whose apportioned share does not fit the
|
|
5
|
+
* seat envelope, but that is a PLAN-TIME judgement made once against the
|
|
6
|
+
* mandate's arithmetic. It cannot see what the seat has actually spent since.
|
|
7
|
+
* `applyBudgetPosture` (lib/plan/compile.mjs) is the same transition made at
|
|
8
|
+
* RUNTIME against the ledger — this module is the I/O around it:
|
|
9
|
+
*
|
|
10
|
+
* config/plan.yaml + lib/budget-guard.dailyStatus().posture
|
|
11
|
+
* → which obligations are suspended RIGHT NOW
|
|
12
|
+
* → one `budget_breach` drift row each, in state/plan/drift.jsonl
|
|
13
|
+
* → state/plan/budget-posture.json (the band we last acted on)
|
|
14
|
+
*
|
|
15
|
+
* WHY THE PLAN FILE IS NOT REWRITTEN. A breach is a transient fact about a
|
|
16
|
+
* ledger; the plan is a durable fact about a mandate. Emitting a suspended plan
|
|
17
|
+
* would drop the cadence from `config/cadences.yaml` and unload its launchd job,
|
|
18
|
+
* and the next recompile at a healthy band would have to put it back — a seat
|
|
19
|
+
* whose schedule flaps with its spend. So the compiled plan stays the plan, and
|
|
20
|
+
* the EFFECTIVE plan is `plan ⊕ posture`, computed on every read. The daemon
|
|
21
|
+
* enforces the same rule per-tick through
|
|
22
|
+
* `compile.obligationAllowedUnderPosture`, so the file and the daemon can never
|
|
23
|
+
* disagree about what is suspended.
|
|
24
|
+
*
|
|
25
|
+
* WHY DRIFT IS RECORDED ON BAND CHANGE ONLY. A drift row per obligation per tick
|
|
26
|
+
* would bury the signal in its own noise (the same reason `mandate.reportDrift`
|
|
27
|
+
* dedupes open rows server-side). We record when the band MOVES — including when
|
|
28
|
+
* it moves back down, which is the "resolved" edge a human needs to see.
|
|
29
|
+
*
|
|
30
|
+
* Never throws. Every degradation is returned AND logged: a governance step that
|
|
31
|
+
* fails quietly is the failure mode this whole subsystem exists to end.
|
|
32
|
+
*
|
|
33
|
+
* @module lib/plan/budget-runtime
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
"use strict";
|
|
37
|
+
|
|
38
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
39
|
+
import { join, resolve } from "node:path";
|
|
40
|
+
|
|
41
|
+
import { applyBudgetPosture } from "./compile.mjs";
|
|
42
|
+
import { writeJsonAtomic, appendJsonl } from "../fs-atomic.mjs";
|
|
43
|
+
|
|
44
|
+
/** Where the last-acted-on band is remembered (git-ignored runtime state). */
|
|
45
|
+
export const POSTURE_REL = join("state", "plan", "budget-posture.json");
|
|
46
|
+
/** The same drift log `lib/execution/effects.writeDrift` appends to. */
|
|
47
|
+
export const DRIFT_REL = join("state", "plan", "drift.jsonl");
|
|
48
|
+
const PLAN_REL = join("config", "plan.yaml");
|
|
49
|
+
|
|
50
|
+
function rootOf(agentRoot) {
|
|
51
|
+
return resolve(agentRoot || process.env.AGENT_ROOT || process.env.AGENT_DIR || process.cwd());
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Read the compiled plan. Never throws; a missing plan is a legitimate state. */
|
|
55
|
+
async function readPlan(agentRoot, deps = {}) {
|
|
56
|
+
if (deps.plan) return { plan: deps.plan, reason: null };
|
|
57
|
+
const p = join(rootOf(agentRoot), PLAN_REL);
|
|
58
|
+
if (!existsSync(p)) return { plan: null, reason: "config/plan.yaml is absent — nothing is compiled yet" };
|
|
59
|
+
let yaml = deps.yaml || null;
|
|
60
|
+
if (!yaml) {
|
|
61
|
+
try { yaml = (await import("js-yaml")).default; }
|
|
62
|
+
catch (err) { return { plan: null, reason: `js-yaml unavailable: ${err && err.message ? err.message : err}` }; }
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
const doc = yaml.load(readFileSync(p, "utf-8"));
|
|
66
|
+
if (!doc || typeof doc !== "object") return { plan: null, reason: "config/plan.yaml did not parse to an object" };
|
|
67
|
+
return { plan: doc, reason: null };
|
|
68
|
+
} catch (err) {
|
|
69
|
+
return { plan: null, reason: `config/plan.yaml is unreadable: ${err && err.message ? err.message : err}` };
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The band this seat last recorded drift for. Never throws. */
|
|
74
|
+
export function readPosture(agentRoot, deps = {}) {
|
|
75
|
+
const p = join(rootOf(agentRoot), POSTURE_REL);
|
|
76
|
+
if (deps.posturePath === null) return { band: null, at: null };
|
|
77
|
+
if (!existsSync(p)) return { band: null, at: null };
|
|
78
|
+
try {
|
|
79
|
+
const raw = JSON.parse(readFileSync(p, "utf-8"));
|
|
80
|
+
return { band: Number.isFinite(raw.band) ? raw.band : null, at: raw.at || null, suspended: raw.suspended || [] };
|
|
81
|
+
} catch {
|
|
82
|
+
return { band: null, at: null };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Reconcile the compiled plan against the live budget posture.
|
|
88
|
+
*
|
|
89
|
+
* @param {object} o
|
|
90
|
+
* @param {string} o.agentRoot
|
|
91
|
+
* @param {object} o.posture `lib/budget-guard.postureForBand()` output
|
|
92
|
+
* @param {object} [o.status] the full `dailyStatus()` (folded into drift detail)
|
|
93
|
+
* @param {object} [deps] { plan?, yaml?, now?, log?, write?, appendDrift?, mirrorDrift? }
|
|
94
|
+
* mirrorDrift — async ({kind,key,detail,resolve?}) => frame. Wired to
|
|
95
|
+
* `mandate.reportDrift` in production so the org sees the suspension; omit it
|
|
96
|
+
* and the record stays local (and says so).
|
|
97
|
+
* @returns {Promise<{ok:boolean, suspended:string[], drift:object[], recorded:number,
|
|
98
|
+
* mirrored:number, band:number, previousBand:number|null, reason:string|null}>}
|
|
99
|
+
*/
|
|
100
|
+
export async function reconcileBudgetPosture(o = {}, deps = {}) {
|
|
101
|
+
const agentRoot = rootOf(o.agentRoot);
|
|
102
|
+
const posture = o.posture || {};
|
|
103
|
+
const status = o.status || {};
|
|
104
|
+
const log = typeof deps.log === "function" ? deps.log : (level, msg) => {
|
|
105
|
+
(level === "error" ? console.error : console.warn)(`[budget-runtime] ${msg}`);
|
|
106
|
+
};
|
|
107
|
+
const nowMs = typeof deps.now === "function" ? deps.now() : Date.now();
|
|
108
|
+
const band = Number.isFinite(posture.band) ? posture.band : 0;
|
|
109
|
+
const previous = readPosture(agentRoot, deps);
|
|
110
|
+
const empty = { ok: true, suspended: [], drift: [], recorded: 0, mirrored: 0, band, previousBand: previous.band, reason: null };
|
|
111
|
+
|
|
112
|
+
const { plan, reason } = await readPlan(agentRoot, deps);
|
|
113
|
+
if (!plan) {
|
|
114
|
+
// Not an error: a seat with no adopted mandate legitimately has no plan.
|
|
115
|
+
if (band > 0) log("warn", `band ${band}% but no plan to suspend — ${reason}`);
|
|
116
|
+
return { ...empty, reason };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const applied = applyBudgetPosture(plan, posture, {
|
|
120
|
+
spentUSD: Number.isFinite(status.spentUSD) ? status.spentUSD : null,
|
|
121
|
+
capUSD: Number.isFinite(status.capUSD) ? status.capUSD : null,
|
|
122
|
+
pct: Number.isFinite(status.pct) ? status.pct : null,
|
|
123
|
+
capSource: status.capSource || null,
|
|
124
|
+
seatBudgetCents: (status.envelope && status.envelope.seatBudgetCents) ?? null,
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
// Nothing to say unless the band MOVED. Includes the downward edge: a human
|
|
128
|
+
// who saw "12 obligations suspended" needs to see them come back.
|
|
129
|
+
if (previous.band === band) {
|
|
130
|
+
return { ...empty, suspended: applied.suspended, drift: [] };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const append = deps.appendDrift || ((row) => appendJsonl(join(agentRoot, DRIFT_REL), row));
|
|
134
|
+
let recorded = 0;
|
|
135
|
+
for (const d of applied.drift) {
|
|
136
|
+
const ok = append({
|
|
137
|
+
at: new Date(nowMs).toISOString(),
|
|
138
|
+
kind: d.kind,
|
|
139
|
+
key: d.key,
|
|
140
|
+
detail: d.detail,
|
|
141
|
+
source: "budget-guard",
|
|
142
|
+
});
|
|
143
|
+
if (ok !== false) recorded += 1;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// MIRROR TO hq. A suspension that only exists in a jsonl file on one laptop is
|
|
147
|
+
// invisible to the person who funds the seat — and funding is the only thing
|
|
148
|
+
// that clears it. `mandate.reportDrift` dedupes an open row per
|
|
149
|
+
// (memberId, kind, key) server-side, so re-reporting is safe and the row stays
|
|
150
|
+
// current instead of going stale. Best-effort by construction: the local
|
|
151
|
+
// record is written FIRST, so an unreachable hq loses nothing.
|
|
152
|
+
let mirrored = 0;
|
|
153
|
+
if (typeof deps.mirrorDrift === "function") {
|
|
154
|
+
for (const d of applied.drift) {
|
|
155
|
+
try {
|
|
156
|
+
const res = await deps.mirrorDrift({ kind: d.kind, key: d.key, detail: d.detail });
|
|
157
|
+
if (res && res.ok === false) {
|
|
158
|
+
log("warn", `hq rejected the ${d.kind} drift for ${d.key}: ${(res.error && res.error.code) || "unknown"} — the local record stands`);
|
|
159
|
+
} else {
|
|
160
|
+
mirrored += 1;
|
|
161
|
+
}
|
|
162
|
+
} catch (err) {
|
|
163
|
+
log("warn", `could not mirror the ${d.kind} drift for ${d.key} to hq (${err && err.message ? err.message : err}) — the local record stands`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
// Clearing edge: the seat came back under the ceiling, so the open rows are
|
|
167
|
+
// resolved. Without this, hq shows a permanently-breached seat that has in
|
|
168
|
+
// fact recovered, and the drift list stops being worth reading.
|
|
169
|
+
if (applied.drift.length === 0 && (previous.suspended || []).length > 0) {
|
|
170
|
+
for (const key of previous.suspended) {
|
|
171
|
+
try { await deps.mirrorDrift({ kind: "budget_breach", key, detail: { band }, resolve: true }); }
|
|
172
|
+
catch (err) { log("warn", `could not resolve the budget_breach drift for ${key} at hq (${err && err.message ? err.message : err})`); }
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (applied.suspended.length > 0) {
|
|
178
|
+
log(
|
|
179
|
+
"warn",
|
|
180
|
+
`band ${previous.band ?? 0}% → ${band}%: SUSPENDING ${applied.suspended.length} obligation(s) ` +
|
|
181
|
+
`(${applied.suspended.slice(0, 5).join(", ")}${applied.suspended.length > 5 ? ", …" : ""}) — ` +
|
|
182
|
+
"inline + offline-safe cadences continue, and the seat keeps answering its inbox"
|
|
183
|
+
);
|
|
184
|
+
} else if ((previous.band ?? 0) >= 125 && band < 125) {
|
|
185
|
+
log("warn", `band ${previous.band}% → ${band}%: obligations are no longer suspended for budget`);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const write = deps.write || ((path, value) => writeJsonAtomic(path, value));
|
|
189
|
+
try {
|
|
190
|
+
write(join(agentRoot, POSTURE_REL), {
|
|
191
|
+
band,
|
|
192
|
+
mode: posture.mode || null,
|
|
193
|
+
at: new Date(nowMs).toISOString(),
|
|
194
|
+
suspended: applied.suspended,
|
|
195
|
+
spentUSD: status.spentUSD ?? null,
|
|
196
|
+
capUSD: status.capUSD ?? null,
|
|
197
|
+
capSource: status.capSource ?? null,
|
|
198
|
+
});
|
|
199
|
+
} catch (err) {
|
|
200
|
+
log("error", `could not persist the budget posture (${err && err.message ? err.message : err}) — the next tick will re-record this band's drift`);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
return {
|
|
204
|
+
ok: true,
|
|
205
|
+
suspended: applied.suspended,
|
|
206
|
+
drift: applied.drift,
|
|
207
|
+
recorded,
|
|
208
|
+
mirrored,
|
|
209
|
+
band,
|
|
210
|
+
previousBand: previous.band,
|
|
211
|
+
reason: null,
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export default { reconcileBudgetPosture, readPosture, POSTURE_REL, DRIFT_REL };
|