@cohortapp/agent-sdk 2.18.36 → 2.19.0

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 (39) hide show
  1. package/bin/maestro.mjs +3 -0
  2. package/docs/guides/billing-console-keys.md +16 -3
  3. package/docs/runbooks/cadence-requeue-storm-recovery.md +186 -0
  4. package/lib/assurance/first-reply.mjs +47 -2
  5. package/lib/assurance/notice-plane.mjs +218 -0
  6. package/lib/assurance/notice-voice.mjs +35 -2
  7. package/lib/assurance/operator-plane-store.mjs +164 -0
  8. package/lib/assurance/operator-plane.mjs +689 -0
  9. package/lib/budget-escalate.mjs +42 -4
  10. package/lib/budget-guard.mjs +24 -1
  11. package/lib/cadence-bus.mjs +359 -46
  12. package/lib/cli/attention.mjs +300 -0
  13. package/lib/cli/seat-auth.mjs +86 -6
  14. package/lib/comms/machine-status.mjs +377 -0
  15. package/lib/comms/send-gate.mjs +309 -2
  16. package/lib/org/awareness.mjs +15 -2
  17. package/lib/org/clause-match.mjs +470 -0
  18. package/lib/org/client.mjs +27 -1
  19. package/lib/org/escalation-chain.mjs +134 -0
  20. package/lib/org/first-run.mjs +263 -0
  21. package/lib/org/genesis-contract.mjs +271 -0
  22. package/lib/org/governance-runtime.mjs +409 -0
  23. package/lib/org/governance-store.mjs +238 -0
  24. package/lib/org/governance.mjs +326 -0
  25. package/lib/org/mesh.mjs +135 -0
  26. package/lib/org/protocol.checksum +1 -1
  27. package/lib/org/protocol.mjs +6 -0
  28. package/lib/org/tool-surface.mjs +28 -0
  29. package/lib/setup/enroll-from-cohort.mjs +11 -0
  30. package/lib/telemetry/alerts.mjs +12 -0
  31. package/lib/telemetry/collect.mjs +237 -1
  32. package/package.json +1 -1
  33. package/scripts/ci/check-durable-write-seam.mjs +3 -3
  34. package/scripts/daemon/agent-daemon.mjs +41 -2
  35. package/scripts/daemon/assurance.mjs +852 -49
  36. package/scripts/daemon/cadence-consumer.mjs +182 -9
  37. package/scripts/daemon/context-compiler.mjs +25 -0
  38. package/scripts/daemon/deliver.mjs +172 -2
  39. package/scripts/fleet/closing-sweep.mjs +266 -0
@@ -0,0 +1,266 @@
1
+ #!/usr/bin/env node
2
+ // scripts/fleet/closing-sweep.mjs
3
+ //
4
+ // Per-seat closing-condition sweep for the #90 assurance-leak rollout.
5
+ //
6
+ // Encodes the settled closing condition (Isla + Jacob + Hannah, 2026-10-13):
7
+ // a seat is CLOSED for #90 only when, after it takes the fix and its daemon
8
+ // restarts onto the new module:
9
+ // (1) every guard #90 touches is green;
10
+ // (2) no guard is NEWLY broken — we compare the broken-guard SET (not a
11
+ // count) at a pinned pre-upgrade instant vs a pinned post-restart
12
+ // instant. A set regression fails the seat regardless of count, which
13
+ // is what a count can't see (fixed-two-broke-two reads as unchanged);
14
+ // (3) every guard still broken after the upgrade has a named owner + date;
15
+ // (4) install-on-absent-checker: a seat with no invariant checker wired is
16
+ // a FINDING, not a pass — nothing ran, so "clean" means unmeasured.
17
+ //
18
+ // This script IS the portable checker clause (4) calls for. It reads
19
+ // config/local-invariants.yaml and runs each invariant's own `verify`, so a
20
+ // seat whose only record is a passive checklist still gets measured. It does
21
+ // NOT modify seat state — it verifies.
22
+ //
23
+ // Usage:
24
+ // node scripts/fleet/closing-sweep.mjs capture [--out <file.json>]
25
+ // node scripts/fleet/closing-sweep.mjs diff <before.json> <after.json> [--touches id1,id2]
26
+ //
27
+ // `--touches` names the invariant ids #90's fix is accountable for (clause 1
28
+ // target = zero broken among these). Everything else broken rides clause 3
29
+ // (named owner + date), never a count.
30
+
31
+ import { execSync } from 'node:child_process';
32
+ import { readFileSync, writeFileSync, existsSync, readdirSync } from 'node:fs';
33
+ import { resolve, basename } from 'node:path';
34
+ import { homedir } from 'node:os';
35
+ import yaml from 'js-yaml';
36
+
37
+ const AGENT_ROOT = resolve(process.cwd());
38
+ const INVARIANTS_FILE = resolve(AGENT_ROOT, 'config/local-invariants.yaml');
39
+ const HEALTHCHECK_FILE = resolve(AGENT_ROOT, 'scripts/healthcheck.sh');
40
+ // The checker is seat-owned and may live under scripts/local/ or scripts/ci/
41
+ // (both outside the SDK overwrite path). Detect any present candidate rather
42
+ // than hardcoding one path — a seat whose checker sits elsewhere must not read
43
+ // as absent (Hannah, 2026-10-13).
44
+ const CHECKER_CANDIDATES = [
45
+ 'scripts/local/check-local-invariants.mjs',
46
+ 'scripts/ci/check-local-invariants.mjs',
47
+ 'scripts/local/invariant-watch.sh',
48
+ ].map((p) => resolve(AGENT_ROOT, p));
49
+ // The checker writes this stamp (ISO timestamp) each time it actually runs.
50
+ // "ran" is evidenced here, not by a loaded plist — a scheduled job can fail
51
+ // before it reaches the checker.
52
+ const STAMP_FILE = resolve(AGENT_ROOT, 'state/local/invariant-check.stamp');
53
+ // Freshness window for the stamp; default 25h (a daily checker + slack).
54
+ // Override with --window-hours on capture.
55
+ const DEFAULT_WINDOW_HOURS = 25;
56
+
57
+ function seatName() {
58
+ try {
59
+ const cfg = JSON.parse(readFileSync(resolve(AGENT_ROOT, 'config/agent.json'), 'utf8'));
60
+ return cfg?.agent?.seat || cfg?.seat || cfg?.agent?.repoSlug || basename(AGENT_ROOT);
61
+ } catch {
62
+ return basename(AGENT_ROOT);
63
+ }
64
+ }
65
+
66
+ // "Wired" is FOUR states, not a boolean (Isla/Jacob/Candace/Hannah 2026-10-13).
67
+ // The property we close on is that the checker EXECUTED recently — not that a
68
+ // call-site string exists (Jacob's seat) and not that a plist is loaded
69
+ // (Hannah's point: a loaded job can fail before reaching the checker). Both are
70
+ // presence checks on an adjacent property.
71
+ // absent — no checker and no call site
72
+ // present-unscheduled — checker/call-site exist, nothing runs them
73
+ // scheduled-not-run-in-window — a scheduler is configured, but no fresh run stamp
74
+ // ran — checker wrote a stamp dated inside its window
75
+ // Only 'ran' closes a seat.
76
+ function detectCheckerState(windowHours) {
77
+ const hasChecker = CHECKER_CANDIDATES.some((p) => existsSync(p));
78
+ let hasCallSite = false;
79
+ try {
80
+ hasCallSite = /invariant|local-invariants|check-local-invariants/i.test(readFileSync(HEALTHCHECK_FILE, 'utf8'));
81
+ } catch {}
82
+ if (!hasChecker && !hasCallSite) return { state: 'absent', runners: [], stamp: null };
83
+
84
+ // Does anything actually schedule it? launchd agents on this host, crontab,
85
+ // or a cadence obligation that invokes healthcheck.sh / the checker.
86
+ const runners = [];
87
+ try {
88
+ const laDir = resolve(homedir(), 'Library/LaunchAgents');
89
+ for (const f of readdirSync(laDir)) {
90
+ if (!f.endsWith('.plist')) continue;
91
+ if (/healthcheck\.sh|check-local-invariants/.test(readFileSync(resolve(laDir, f), 'utf8'))) runners.push(`launchd:${f}`);
92
+ }
93
+ } catch {}
94
+ try {
95
+ if (/healthcheck\.sh|check-local-invariants/.test(execSync('crontab -l', { stdio: 'pipe' }).toString())) runners.push('crontab');
96
+ } catch {}
97
+ try {
98
+ if (/healthcheck|check-local-invariants/.test(readFileSync(resolve(AGENT_ROOT, '.cadence-registry.json'), 'utf8'))) runners.push('cadence');
99
+ } catch {}
100
+
101
+ if (!runners.length) return { state: 'present-unscheduled', runners: [], stamp: null };
102
+
103
+ // Scheduled — but did it actually run inside its window? Evidence is the stamp.
104
+ let stamp = null;
105
+ try {
106
+ stamp = readFileSync(STAMP_FILE, 'utf8').trim();
107
+ } catch {}
108
+ const fresh = stamp && (Date.now() - Date.parse(stamp)) <= windowHours * 3600 * 1000;
109
+ return { state: fresh ? 'ran' : 'scheduled-not-run-in-window', runners, stamp };
110
+ }
111
+
112
+ // A verify that only greps for a string measures the property ADJACENT to the
113
+ // one we care about ("string present"), not behaviour — it can stay green over
114
+ // a dead path (Candace). Flag those structural rather than accepting the green.
115
+ function classifyMeasure(verify) {
116
+ if (!verify) return 'none';
117
+ const v = verify.trim();
118
+ if (/\bnode\b|\bnpm\b|--test\b/.test(v)) return 'behavioural';
119
+ if (/\bgrep\b/.test(v)) return 'presence-only';
120
+ return 'unknown';
121
+ }
122
+
123
+ function loadInvariants() {
124
+ const doc = yaml.load(readFileSync(INVARIANTS_FILE, 'utf8'));
125
+ return Array.isArray(doc?.invariants) ? doc.invariants : [];
126
+ }
127
+
128
+ // Run an invariant's own `verify`. Exit 0 => OK, anything else => BROKEN.
129
+ // grep verifies exit 1 on no-match; node --test verifies exit non-zero on
130
+ // a reverted export/import or a failed assertion. Both map cleanly.
131
+ function runVerify(inv) {
132
+ if (!inv.verify) return { status: 'UNVERIFIABLE', detail: 'no verify command declared' };
133
+ try {
134
+ execSync(inv.verify, { cwd: AGENT_ROOT, stdio: 'pipe', timeout: 120000 });
135
+ return { status: 'OK' };
136
+ } catch (err) {
137
+ const out = `${err.stdout || ''}${err.stderr || ''}`.trim();
138
+ const firstLine = out.split('\n').find((l) => /error|not provide an export|No such|not a function|undefined/i.test(l));
139
+ return { status: 'BROKEN', detail: firstLine || `verify exited ${err.status ?? 'non-zero'}` };
140
+ }
141
+ }
142
+
143
+ function capture(windowHours) {
144
+ const instant = new Date().toISOString();
145
+ const invariants = loadInvariants().map((inv) => {
146
+ const r = runVerify(inv);
147
+ return {
148
+ id: inv.id,
149
+ file: inv.file,
150
+ anchor: inv.anchor,
151
+ fixed: inv.fixed,
152
+ status: r.status,
153
+ detail: r.detail,
154
+ measures: classifyMeasure(inv.verify),
155
+ owner: inv.owner,
156
+ date: inv.date,
157
+ };
158
+ });
159
+ const brokenSet = invariants.filter((i) => i.status === 'BROKEN').map((i) => i.id);
160
+ const unverifiable = invariants.filter((i) => i.status === 'UNVERIFIABLE').map((i) => i.id);
161
+ // Structural: green is on an adjacent property, not behaviour — don't bank it.
162
+ const structural = invariants.filter((i) => i.measures === 'presence-only').map((i) => i.id);
163
+ return {
164
+ seat: seatName(),
165
+ instant,
166
+ windowHours,
167
+ checker: detectCheckerState(windowHours),
168
+ invariants,
169
+ brokenSet,
170
+ unverifiable,
171
+ structural,
172
+ };
173
+ }
174
+
175
+ // Apply the four-clause verdict to a before/after pair.
176
+ function diff(before, after, touches) {
177
+ const beforeBroken = new Set(before.brokenSet);
178
+ const afterBroken = new Set(after.brokenSet);
179
+ const newlyBroken = [...afterBroken].filter((id) => !beforeBroken.has(id)); // clause 2
180
+ const touchedBroken = touches.filter((id) => afterBroken.has(id)); // clause 1
181
+ const stillBroken = [...afterBroken]; // clause 3 — each needs owner + date
182
+
183
+ const checkerState = after.checker?.state;
184
+ // Clause 3: a still-broken guard is accountable only if the record carries a
185
+ // named owner AND a date for it (Hannah/Jacob 2026-10-13). Accountable breaks
186
+ // do NOT block closure; unaccounted ones do. A NEW break (clause 2) blocks
187
+ // regardless of owner — a regression is a regression.
188
+ const od = Object.fromEntries((after.invariants || []).map((i) => [i.id, i]));
189
+ const accountable = (id) => Boolean(od[id] && od[id].owner && od[id].date);
190
+ const unaccounted = stillBroken.filter((id) => !accountable(id));
191
+ const accounted = stillBroken.filter(accountable);
192
+ // Clause 4-adjacent: an invariant with no runnable verify measured NOTHING.
193
+ // That is a finding, not a pass — the same "zero means unmeasured" failure one
194
+ // level down (Hannah). It must block closure, never be silently dropped.
195
+ const unverifiable = after.unverifiable || [];
196
+
197
+ const findings = [];
198
+ if (checkerState !== 'ran') {
199
+ const why = {
200
+ absent: 'no checker and no call site — seat produces no signal when guards break',
201
+ 'present-unscheduled': 'checker/call-site exist but nothing runs them — never fires on its own',
202
+ 'scheduled-not-run-in-window': 'a scheduler is configured but no fresh run stamp — a loaded job can fail before reaching the checker',
203
+ }[checkerState] || 'checker never ran';
204
+ findings.push(`CLAUSE 4: checker state is "${checkerState}" (${why}). Only "ran" closes. Rollout must install the checker + a call site OUTSIDE the overwrite path AND prove it executed (a dated run stamp), not merely that a plist is loaded.`);
205
+ }
206
+ if (touchedBroken.length) {
207
+ findings.push(`CLAUSE 1: guard(s) #90 is accountable for still broken: ${touchedBroken.join(', ')}`);
208
+ }
209
+ if (newlyBroken.length) {
210
+ findings.push(`CLAUSE 2: set regression — guard(s) newly broken by taking the fix: ${newlyBroken.join(', ')}`);
211
+ }
212
+ if (unaccounted.length) {
213
+ findings.push(`CLAUSE 3: still broken WITHOUT a named owner + date in the record (blocks closure): ${unaccounted.join(', ')}`);
214
+ }
215
+ if (unverifiable.length) {
216
+ findings.push(`UNVERIFIABLE: measured nothing (no runnable verify) — a finding, not a pass: ${unverifiable.join(', ')}`);
217
+ }
218
+ // Structural: greens that measure an adjacent property, not behaviour.
219
+ if (after.structural?.length) {
220
+ findings.push(`STRUCTURAL: these invariants measure an adjacent property (string presence), not behaviour, so their green doesn't prove the guard: ${after.structural.join(', ')}`);
221
+ }
222
+
223
+ const closed =
224
+ checkerState === 'ran' &&
225
+ !touchedBroken.length &&
226
+ !newlyBroken.length &&
227
+ !unaccounted.length &&
228
+ !unverifiable.length;
229
+ return {
230
+ seat: after.seat,
231
+ beforeInstant: before.instant,
232
+ afterInstant: after.instant,
233
+ checkerState,
234
+ newlyBroken,
235
+ touchedBroken,
236
+ stillBroken,
237
+ accounted, // still broken but owned + dated — non-blocking under clause 3
238
+ unaccounted,
239
+ unverifiable,
240
+ structural: after.structural || [],
241
+ verdict: closed ? 'CLOSED' : 'NOT-CLOSED',
242
+ findings,
243
+ };
244
+ }
245
+
246
+ const [, , mode, ...rest] = process.argv;
247
+
248
+ if (mode === 'capture') {
249
+ const outIdx = rest.indexOf('--out');
250
+ const whIdx = rest.indexOf('--window-hours');
251
+ const windowHours = whIdx !== -1 && rest[whIdx + 1] ? Number(rest[whIdx + 1]) : DEFAULT_WINDOW_HOURS;
252
+ const snap = capture(windowHours);
253
+ const json = JSON.stringify(snap, null, 2);
254
+ if (outIdx !== -1 && rest[outIdx + 1]) writeFileSync(rest[outIdx + 1], json);
255
+ console.log(json);
256
+ } else if (mode === 'diff') {
257
+ const [beforeFile, afterFile] = rest.filter((a) => !a.startsWith('--'));
258
+ const tIdx = rest.indexOf('--touches');
259
+ const touches = tIdx !== -1 && rest[tIdx + 1] ? rest[tIdx + 1].split(',') : [];
260
+ const before = JSON.parse(readFileSync(beforeFile, 'utf8'));
261
+ const after = JSON.parse(readFileSync(afterFile, 'utf8'));
262
+ console.log(JSON.stringify(diff(before, after, touches), null, 2));
263
+ } else {
264
+ console.error('usage: closing-sweep.mjs capture [--out f] | diff <before> <after> [--touches ids]');
265
+ process.exit(2);
266
+ }