@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.
- package/bin/maestro.mjs +3 -0
- package/docs/guides/billing-console-keys.md +16 -3
- package/docs/runbooks/cadence-requeue-storm-recovery.md +186 -0
- package/lib/assurance/first-reply.mjs +47 -2
- package/lib/assurance/notice-plane.mjs +218 -0
- package/lib/assurance/notice-voice.mjs +35 -2
- package/lib/assurance/operator-plane-store.mjs +164 -0
- package/lib/assurance/operator-plane.mjs +689 -0
- package/lib/budget-escalate.mjs +42 -4
- package/lib/budget-guard.mjs +24 -1
- package/lib/cadence-bus.mjs +359 -46
- package/lib/cli/attention.mjs +300 -0
- package/lib/cli/seat-auth.mjs +86 -6
- package/lib/comms/machine-status.mjs +377 -0
- package/lib/comms/send-gate.mjs +309 -2
- package/lib/org/awareness.mjs +15 -2
- package/lib/org/clause-match.mjs +470 -0
- package/lib/org/client.mjs +27 -1
- package/lib/org/escalation-chain.mjs +134 -0
- package/lib/org/first-run.mjs +263 -0
- package/lib/org/genesis-contract.mjs +271 -0
- package/lib/org/governance-runtime.mjs +409 -0
- package/lib/org/governance-store.mjs +238 -0
- package/lib/org/governance.mjs +326 -0
- package/lib/org/mesh.mjs +135 -0
- package/lib/org/protocol.checksum +1 -1
- package/lib/org/protocol.mjs +6 -0
- package/lib/org/tool-surface.mjs +28 -0
- package/lib/setup/enroll-from-cohort.mjs +11 -0
- package/lib/telemetry/alerts.mjs +12 -0
- package/lib/telemetry/collect.mjs +237 -1
- package/package.json +1 -1
- package/scripts/ci/check-durable-write-seam.mjs +3 -3
- package/scripts/daemon/agent-daemon.mjs +41 -2
- package/scripts/daemon/assurance.mjs +852 -49
- package/scripts/daemon/cadence-consumer.mjs +182 -9
- package/scripts/daemon/context-compiler.mjs +25 -0
- package/scripts/daemon/deliver.mjs +172 -2
- package/scripts/fleet/closing-sweep.mjs +266 -0
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/org/governance-runtime.mjs — the effectful half of Genesis governance
|
|
3
|
+
* enforcement (WS6, M2–M3). The rules are pure, in `governance.mjs`; this file
|
|
4
|
+
* is the edge: it reads the disk, calls the org, files approvals, pauses the
|
|
5
|
+
* seat, emits the diagnostic event and DMs the human.
|
|
6
|
+
*
|
|
7
|
+
* refreshGovernance whoami → state/org/governance.json (throttled; the beat)
|
|
8
|
+
* resolveEscalation walk reports-to up to a human → state/org/escalation-chain.json
|
|
9
|
+
* gateToolCall the executeOrgToolInner chokepoint
|
|
10
|
+
* enforceSpendCaps monthly cap → pause + event + guardian DM (the beat)
|
|
11
|
+
* pauseFromDirective the `pause_schedules` beat directive
|
|
12
|
+
*
|
|
13
|
+
* Every function returns a value and never throws. A failure on any network
|
|
14
|
+
* leg fails toward TODAY'S behaviour (no new gate), except where a gate has
|
|
15
|
+
* already decided — a decided block is never undone by a transport fault.
|
|
16
|
+
*
|
|
17
|
+
* @module lib/org/governance-runtime
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
"use strict";
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
loadGovernance,
|
|
24
|
+
persistGovernance,
|
|
25
|
+
governanceRecord,
|
|
26
|
+
readPause,
|
|
27
|
+
writePause,
|
|
28
|
+
clearPause,
|
|
29
|
+
capsFingerprint,
|
|
30
|
+
workspaceDomain,
|
|
31
|
+
} from "./governance-store.mjs";
|
|
32
|
+
import { decideToolCall, approvalKindFor, monthlyCapStatus } from "./governance.mjs";
|
|
33
|
+
import { walkToFirstHuman, memberLookup, persistChain, loadChain } from "./escalation-chain.mjs";
|
|
34
|
+
|
|
35
|
+
/** How often the beat may re-read whoami. The beat itself runs every 30 s. */
|
|
36
|
+
export const GOVERNANCE_REFRESH_MS = 15 * 60_000;
|
|
37
|
+
|
|
38
|
+
/** How often the beat may re-measure month-to-date spend against the cap. */
|
|
39
|
+
export const CAP_CHECK_MS = 5 * 60_000;
|
|
40
|
+
|
|
41
|
+
/** The input key a re-invocation carries its approval under. Stripped before dispatch. */
|
|
42
|
+
export const APPROVAL_INPUT_KEY = "governanceApprovalId";
|
|
43
|
+
|
|
44
|
+
function warn(msg) {
|
|
45
|
+
try { console.warn(`[governance] ${msg}`); } catch { /* logging must never throw into a gate */ }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// ── Refresh ──────────────────────────────────────────────────────────────────
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Re-read whoami and persist the governance fields when they are due.
|
|
52
|
+
*
|
|
53
|
+
* @param {object} o
|
|
54
|
+
* @param {string} o.agentRoot
|
|
55
|
+
* @param {{base:string, token:string, orgId:string, agentId?:string}} o.conn
|
|
56
|
+
* @param {number} [o.now]
|
|
57
|
+
* @param {number} [o.lastAt] when the previous refresh ran (the caller's memory)
|
|
58
|
+
* @param {boolean} [o.force]
|
|
59
|
+
* @param {Function} [o.fetchSelfProfileImpl]
|
|
60
|
+
* @param {Function} [o.fetchImpl]
|
|
61
|
+
* @returns {Promise<{ok:true, ran:boolean, changed:boolean, record?:object}|{ok:false, ran:true, error:string}>}
|
|
62
|
+
*/
|
|
63
|
+
export async function refreshGovernance(o = {}) {
|
|
64
|
+
const now = Number.isFinite(o.now) ? o.now : Date.now();
|
|
65
|
+
if (!o.force && Number.isFinite(o.lastAt) && now - o.lastAt < GOVERNANCE_REFRESH_MS) {
|
|
66
|
+
return { ok: true, ran: false, changed: false };
|
|
67
|
+
}
|
|
68
|
+
const conn = o.conn || {};
|
|
69
|
+
if (!conn.base || !conn.token || !conn.orgId) return { ok: false, ran: true, error: "no org credential" };
|
|
70
|
+
const fetchSelf = o.fetchSelfProfileImpl || (await import("./client.mjs")).fetchSelfProfile;
|
|
71
|
+
let frame;
|
|
72
|
+
try {
|
|
73
|
+
frame = await fetchSelf({ base: conn.base, apiKey: conn.token, orgId: conn.orgId, agentId: conn.agentId || undefined, fetchImpl: o.fetchImpl });
|
|
74
|
+
} catch (err) {
|
|
75
|
+
return { ok: false, ran: true, error: `whoami threw: ${err && err.message ? err.message : err}` };
|
|
76
|
+
}
|
|
77
|
+
if (!frame || !frame.ok) return { ok: false, ran: true, error: `whoami failed: ${(frame && frame.error && frame.error.code) || "unknown"}` };
|
|
78
|
+
const record = governanceRecord(frame.result, now);
|
|
79
|
+
const prev = loadGovernance(o.agentRoot);
|
|
80
|
+
const changed =
|
|
81
|
+
prev.source !== "state" ||
|
|
82
|
+
JSON.stringify({ f: prev.fields, g: prev.governance }) !== JSON.stringify({ f: record.fields, g: record.present ? record.governance : null });
|
|
83
|
+
const w = persistGovernance(o.agentRoot, record);
|
|
84
|
+
if (!w.ok) return { ok: false, ran: true, error: w.error };
|
|
85
|
+
return { ok: true, ran: true, changed, record };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ── The escalation target ────────────────────────────────────────────────────
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Resolve (and cache) the first human up the seat's reports-to chain.
|
|
92
|
+
* @param {object} o - { agentRoot, conn, governance?, selfId?, now?, lookup?, fetchSelfProfileImpl?, fetchImpl? }
|
|
93
|
+
* @returns {Promise<import("./escalation-chain.mjs").ChainResult>}
|
|
94
|
+
*/
|
|
95
|
+
export async function resolveEscalation(o = {}) {
|
|
96
|
+
const g = o.governance || loadGovernance(o.agentRoot).governance;
|
|
97
|
+
const reportsTo = g ? g.reportsTo : null;
|
|
98
|
+
const selfId = o.selfId || loadGovernance(o.agentRoot).memberId || "self";
|
|
99
|
+
const lookup = o.lookup || memberLookup(o.conn || {}, { fetchSelfProfileImpl: o.fetchSelfProfileImpl, fetchImpl: o.fetchImpl });
|
|
100
|
+
const result = await walkToFirstHuman({ selfId, reportsTo, lookup });
|
|
101
|
+
if (o.agentRoot && reportsTo) persistChain(o.agentRoot, result, Number.isFinite(o.now) ? o.now : Date.now());
|
|
102
|
+
return result;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The cached first human, or null. Never touches the network. */
|
|
106
|
+
export function cachedFirstHuman(agentRoot) {
|
|
107
|
+
const c = loadChain(agentRoot);
|
|
108
|
+
return c && c.firstHuman ? String(c.firstHuman) : null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ── Delivery: one DM to one member ───────────────────────────────────────────
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* DM a member over the existing Cohort lane (channel.resolveOrCreateDm +
|
|
115
|
+
* messaging.send — the same two methods lib/budget-escalate.mjs uses).
|
|
116
|
+
* @param {object} o - { conn, memberId, body, idempotencyId }
|
|
117
|
+
* @param {object} [deps] - { callImpl }
|
|
118
|
+
* @returns {Promise<{ok:true, channelId:string}|{ok:false, error:string}>}
|
|
119
|
+
*/
|
|
120
|
+
export async function notifyMember(o = {}, deps = {}) {
|
|
121
|
+
const conn = o.conn || {};
|
|
122
|
+
if (!o.memberId) return { ok: false, error: "no recipient" };
|
|
123
|
+
if (!conn.base || !conn.token) return { ok: false, error: "no org credential" };
|
|
124
|
+
const call = deps.callImpl || (await import("./client.mjs")).call;
|
|
125
|
+
try {
|
|
126
|
+
const dm = await call("channel.resolveOrCreateDm", { memberId: o.memberId }, conn);
|
|
127
|
+
const r = dm && dm.ok ? dm.result || {} : null;
|
|
128
|
+
const channelId = r && (r.channelId || r.id || (r.channel && r.channel.id));
|
|
129
|
+
if (!channelId) return { ok: false, error: `dm-resolve-failed:${(dm && dm.error && dm.error.code) || "unknown"}` };
|
|
130
|
+
const sent = await call("messaging.send", { channelId, body: String(o.body || ""), idempotencyId: o.idempotencyId }, { ...conn, idempotencyKey: o.idempotencyId });
|
|
131
|
+
if (!sent || !sent.ok) return { ok: false, error: `send-failed:${(sent && sent.error && sent.error.code) || "unknown"}` };
|
|
132
|
+
return { ok: true, channelId };
|
|
133
|
+
} catch (err) {
|
|
134
|
+
return { ok: false, error: `notify threw: ${err && err.message ? err.message : err}` };
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ── Diagnostics ──────────────────────────────────────────────────────────────
|
|
139
|
+
|
|
140
|
+
async function emitGuard(agentRoot, attrs, deps = {}) {
|
|
141
|
+
try {
|
|
142
|
+
const emit = deps.emitEvent || (await import("../diagnostics/events.mjs")).emitEvent;
|
|
143
|
+
emit({ type: "guard_fail", attrs: { gate: "governance", ...attrs } }, { agentRoot, now: deps.nowFn });
|
|
144
|
+
} catch { /* diagnostics must never take down the gate they observe */ }
|
|
145
|
+
try {
|
|
146
|
+
const bump = deps.bump || (await import("../diagnostics/counters.mjs")).bump;
|
|
147
|
+
bump(`governance.${attrs.verdict || attrs.kind || "event"}`, { reason: attrs.reason || null }, { agentRoot });
|
|
148
|
+
} catch { /* a counter must never crash the path it observes */ }
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ── Pausing ──────────────────────────────────────────────────────────────────
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Pause the seat: write the pause, emit the event, DM the guardian. Idempotent
|
|
155
|
+
* per `key` (a repeat while already paused for the same key does nothing).
|
|
156
|
+
* @param {object} o - { agentRoot, conn, source, reason, month?, governance?, key, now? }
|
|
157
|
+
* @param {object} [deps] - { callImpl, emitEvent, bump, lookup }
|
|
158
|
+
*/
|
|
159
|
+
export async function pauseSeat(o = {}, deps = {}) {
|
|
160
|
+
const now = Number.isFinite(o.now) ? o.now : Date.now();
|
|
161
|
+
const existing = readPause(o.agentRoot);
|
|
162
|
+
if (existing && existing.key === o.key) return { ok: true, paused: true, already: true, notified: false };
|
|
163
|
+
const state = {
|
|
164
|
+
source: o.source,
|
|
165
|
+
reason: o.reason,
|
|
166
|
+
since: new Date(now).toISOString(),
|
|
167
|
+
month: o.month || null,
|
|
168
|
+
capsFingerprint: capsFingerprint(o.governance || null),
|
|
169
|
+
key: o.key,
|
|
170
|
+
};
|
|
171
|
+
const w = writePause(o.agentRoot, state);
|
|
172
|
+
if (!w.ok) warn(w.error);
|
|
173
|
+
await emitGuard(o.agentRoot, { kind: "pause", verdict: "paused", source: o.source, reason: o.reason }, deps);
|
|
174
|
+
warn(`seat PAUSED (${o.source}): ${o.reason}`);
|
|
175
|
+
const guardian = (o.governance && o.governance.guardianMemberId) || cachedFirstHuman(o.agentRoot) || (o.governance && o.governance.reportsTo && o.governance.reportsTo.kind === "human" ? o.governance.reportsTo.memberId : null);
|
|
176
|
+
let notified = false;
|
|
177
|
+
if (guardian) {
|
|
178
|
+
const r = await notifyMember(
|
|
179
|
+
{
|
|
180
|
+
conn: o.conn,
|
|
181
|
+
memberId: guardian,
|
|
182
|
+
body: `Paused new work for this seat: ${o.reason}. It still answers when asked. Raise the cap on its charter to resume.`,
|
|
183
|
+
idempotencyId: `governance-pause-${o.key}`.slice(0, 64),
|
|
184
|
+
},
|
|
185
|
+
deps,
|
|
186
|
+
);
|
|
187
|
+
notified = r.ok;
|
|
188
|
+
if (!r.ok) warn(`the guardian could not be told about the pause (${r.error}) — the pause stands`);
|
|
189
|
+
} else {
|
|
190
|
+
warn("no human up the reports-to chain to tell about the pause — the pause stands; resolve the seat's reporting line");
|
|
191
|
+
}
|
|
192
|
+
return { ok: w.ok, paused: true, already: false, notified, guardian };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** The `pause_schedules` directive. A directive pause has no automatic lift. */
|
|
196
|
+
export async function pauseFromDirective(o = {}, deps = {}) {
|
|
197
|
+
const now = Number.isFinite(o.now) ? o.now : Date.now();
|
|
198
|
+
return pauseSeat(
|
|
199
|
+
{
|
|
200
|
+
...o,
|
|
201
|
+
source: "directive",
|
|
202
|
+
reason: "the workspace paused this seat's schedules",
|
|
203
|
+
key: `directive-${new Date(now).toISOString().slice(0, 10)}`,
|
|
204
|
+
governance: loadGovernance(o.agentRoot).governance,
|
|
205
|
+
now,
|
|
206
|
+
},
|
|
207
|
+
deps,
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* The beat's cap check. Monthly: pause when month-to-date spend reaches the cap,
|
|
213
|
+
* lift when the month rolls over or the cap moves. Single-action pause: lift
|
|
214
|
+
* when the caps move (the guardian raised it). Never touches a directive pause.
|
|
215
|
+
*
|
|
216
|
+
* @param {object} o - { agentRoot, conn, now?, governance?, spentMicros? }
|
|
217
|
+
* @param {object} [deps] - { monthToDate, callImpl, emitEvent, bump }
|
|
218
|
+
*/
|
|
219
|
+
export async function enforceSpendCaps(o = {}, deps = {}) {
|
|
220
|
+
const now = Number.isFinite(o.now) ? o.now : Date.now();
|
|
221
|
+
const loaded = o.governance ? { present: true, governance: o.governance } : loadGovernance(o.agentRoot);
|
|
222
|
+
if (!loaded.present || !loaded.governance) return { ok: true, checked: false, reason: "no_governance" };
|
|
223
|
+
const g = loaded.governance;
|
|
224
|
+
const pause = readPause(o.agentRoot);
|
|
225
|
+
const month = new Date(now).toISOString().slice(0, 7);
|
|
226
|
+
|
|
227
|
+
if (pause && pause.source === "single_action_cap" && pause.capsFingerprint !== capsFingerprint(g)) {
|
|
228
|
+
clearPause(o.agentRoot, { now, why: "the caps changed" });
|
|
229
|
+
warn("single-action-cap pause lifted: the charter's caps changed");
|
|
230
|
+
}
|
|
231
|
+
const monthly = g.spendCaps.monthlyMicros;
|
|
232
|
+
if (monthly == null) {
|
|
233
|
+
if (pause && pause.source === "monthly_cap") clearPause(o.agentRoot, { now, why: "the monthly cap was removed" });
|
|
234
|
+
return { ok: true, checked: false, reason: "no_monthly_cap" };
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
let spentMicros = o.spentMicros;
|
|
238
|
+
if (!Number.isFinite(spentMicros)) {
|
|
239
|
+
try {
|
|
240
|
+
const mtd = deps.monthToDate || (await import("../budget-guard.mjs")).monthToDate;
|
|
241
|
+
spentMicros = Math.round(mtd({ agentRoot: o.agentRoot, now: () => now }).spentUSD * 1e6);
|
|
242
|
+
} catch (err) {
|
|
243
|
+
return { ok: false, checked: false, error: `could not read month-to-date spend: ${err && err.message ? err.message : err}` };
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const st = monthlyCapStatus({ spentMicros, monthlyMicros: monthly });
|
|
247
|
+
if (st.reached) {
|
|
248
|
+
const r = await pauseSeat(
|
|
249
|
+
{
|
|
250
|
+
agentRoot: o.agentRoot,
|
|
251
|
+
conn: o.conn,
|
|
252
|
+
source: "monthly_cap",
|
|
253
|
+
reason: `month-to-date spend $${(spentMicros / 1e6).toFixed(2)} reached the $${(monthly / 1e6).toFixed(2)} monthly cap`,
|
|
254
|
+
month,
|
|
255
|
+
governance: g,
|
|
256
|
+
key: `monthly-${month}-${monthly}`,
|
|
257
|
+
now,
|
|
258
|
+
},
|
|
259
|
+
deps,
|
|
260
|
+
);
|
|
261
|
+
return { ok: true, checked: true, reached: true, pct: st.pct, ...r };
|
|
262
|
+
}
|
|
263
|
+
if (pause && pause.source === "monthly_cap" && (pause.month !== month || pause.capsFingerprint !== capsFingerprint(g))) {
|
|
264
|
+
clearPause(o.agentRoot, { now, why: pause.month !== month ? "a new month" : "the cap moved" });
|
|
265
|
+
warn("monthly-cap pause lifted");
|
|
266
|
+
}
|
|
267
|
+
return { ok: true, checked: true, reached: false, pct: st.pct };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// ── The tool chokepoint ──────────────────────────────────────────────────────
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Is `approvalId` an APPROVED approval bound to exactly this payload?
|
|
274
|
+
* @returns {Promise<boolean>}
|
|
275
|
+
*/
|
|
276
|
+
async function approvalHolds({ approvalId, payloadHash, conn, approvalGetImpl, fetchImpl }) {
|
|
277
|
+
if (!approvalId || !conn.base || !conn.token) return false;
|
|
278
|
+
try {
|
|
279
|
+
const get = approvalGetImpl || (await import("./client.mjs")).approvalGet;
|
|
280
|
+
const f = await get({ id: String(approvalId) }, { base: conn.base, token: conn.token, fetchImpl });
|
|
281
|
+
const a = f && f.ok ? f.result || {} : null;
|
|
282
|
+
if (!a) return false;
|
|
283
|
+
const status = String(a.status || a.state || "").toLowerCase();
|
|
284
|
+
const hash = a.payloadHash || a.payload_hash || null;
|
|
285
|
+
return status === "approved" && hash === payloadHash;
|
|
286
|
+
} catch {
|
|
287
|
+
// Unverifiable is unapproved: the call is held, which is the safe side.
|
|
288
|
+
return false;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Gate one org tool call. Returns `null` to let it dispatch (with `input`
|
|
294
|
+
* possibly stripped of the approval key), or an error FRAME to return instead.
|
|
295
|
+
*
|
|
296
|
+
* @param {object} o
|
|
297
|
+
* @param {string} o.name
|
|
298
|
+
* @param {object} o.input
|
|
299
|
+
* @param {object|null} o.def
|
|
300
|
+
* @param {{agentRoot:string, base:string, token:string, orgId:string}} o.cfg
|
|
301
|
+
* @param {object} [o.governanceOverride] {present, governance} (tests)
|
|
302
|
+
* @param {Function} [o.errFrame]
|
|
303
|
+
* @param {Function} [o.methodSideEffecting]
|
|
304
|
+
* @param {object} [deps] - { approvalGetImpl, requestApprovalImpl, callImpl, emitEvent, bump, fetchImpl, now }
|
|
305
|
+
* @returns {Promise<{frame: object|null, input: object, decision: object}>}
|
|
306
|
+
*/
|
|
307
|
+
export async function gateToolCall(o = {}, deps = {}) {
|
|
308
|
+
const input = o.input && typeof o.input === "object" ? { ...o.input } : {};
|
|
309
|
+
const approvalId = input[APPROVAL_INPUT_KEY] ? String(input[APPROVAL_INPUT_KEY]) : null;
|
|
310
|
+
delete input[APPROVAL_INPUT_KEY];
|
|
311
|
+
const cfg = o.cfg || {};
|
|
312
|
+
const loaded = o.governanceOverride || loadGovernance(cfg.agentRoot);
|
|
313
|
+
if (!loaded.present) return { frame: null, input, decision: { verdict: "allow", reason: "no_governance" } };
|
|
314
|
+
|
|
315
|
+
const { hashPayload } = await import("./approvals.mjs");
|
|
316
|
+
const payloadHash = hashPayload({ tool: o.name, input });
|
|
317
|
+
const conn = { base: cfg.base, token: cfg.token, orgId: cfg.orgId, fetchImpl: deps.fetchImpl };
|
|
318
|
+
const approved = approvalId
|
|
319
|
+
? await approvalHolds({ approvalId, payloadHash, conn, approvalGetImpl: deps.approvalGetImpl, fetchImpl: deps.fetchImpl })
|
|
320
|
+
: false;
|
|
321
|
+
const pause = readPause(cfg.agentRoot);
|
|
322
|
+
const decision = decideToolCall({
|
|
323
|
+
name: o.name,
|
|
324
|
+
input,
|
|
325
|
+
def: o.def || null,
|
|
326
|
+
governance: loaded.governance,
|
|
327
|
+
present: loaded.present,
|
|
328
|
+
approved,
|
|
329
|
+
pause,
|
|
330
|
+
workspaceDomain: workspaceDomain(cfg.agentRoot),
|
|
331
|
+
methodSideEffecting: o.methodSideEffecting,
|
|
332
|
+
});
|
|
333
|
+
for (const n of decision.notes || []) warn(`${o.name}: ${n} (not enforced — weak match)`);
|
|
334
|
+
const errFrame = o.errFrame;
|
|
335
|
+
const mk = (code, message, extra) => {
|
|
336
|
+
const f = errFrame(code, message);
|
|
337
|
+
f.error.governance = { verdict: decision.verdict, reason: decision.reason, actionClass: decision.actionClass, clause: decision.clause, ...extra };
|
|
338
|
+
return f;
|
|
339
|
+
};
|
|
340
|
+
|
|
341
|
+
if (decision.verdict === "allow") return { frame: null, input, decision };
|
|
342
|
+
|
|
343
|
+
await emitGuard(cfg.agentRoot, { tool: o.name, verdict: decision.verdict, reason: decision.reason, clause: decision.clause, actionClass: decision.actionClass }, deps);
|
|
344
|
+
|
|
345
|
+
if (decision.verdict === "block") {
|
|
346
|
+
return { frame: mk("FORBIDDEN_SCOPE", `${o.name} blocked: ${decision.why}. This cannot be approved past; tell the person who asked.`), input, decision };
|
|
347
|
+
}
|
|
348
|
+
if (decision.verdict === "paused") {
|
|
349
|
+
return { frame: mk("GOVERNANCE_NOT_READY", `${o.name} held: ${decision.why}.`), input, decision };
|
|
350
|
+
}
|
|
351
|
+
if (decision.verdict === "over_cap") {
|
|
352
|
+
const g = loaded.governance;
|
|
353
|
+
await pauseSeat(
|
|
354
|
+
{
|
|
355
|
+
agentRoot: cfg.agentRoot,
|
|
356
|
+
conn,
|
|
357
|
+
source: "single_action_cap",
|
|
358
|
+
reason: `${o.name} would have cost $${(decision.amountMicros / 1e6).toFixed(2)}, over the single-action cap`,
|
|
359
|
+
governance: g,
|
|
360
|
+
key: `single-${capsFingerprint(g)}-${payloadHash.slice(0, 12)}`,
|
|
361
|
+
now: deps.now,
|
|
362
|
+
},
|
|
363
|
+
deps,
|
|
364
|
+
);
|
|
365
|
+
return { frame: mk("GOVERNANCE_NOT_READY", `${o.name} refused: ${decision.why}. The seat is paused for spending and its guardian has been told.`), input, decision };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// approve | escalate → file the approval, bound to this exact payload.
|
|
369
|
+
const escalate = decision.verdict === "escalate";
|
|
370
|
+
const target = escalate ? cachedFirstHuman(cfg.agentRoot) : null;
|
|
371
|
+
const request = deps.requestApprovalImpl || (await import("./approvals.mjs")).requestApproval;
|
|
372
|
+
const actionClass = approvalKindFor(decision.actionClass);
|
|
373
|
+
let filed = null;
|
|
374
|
+
try {
|
|
375
|
+
filed = await request({
|
|
376
|
+
cfg: { org: { cohort: { enabled: true, base: cfg.base, token: cfg.token, orgId: cfg.orgId } } },
|
|
377
|
+
agentRoot: cfg.agentRoot,
|
|
378
|
+
action: o.name,
|
|
379
|
+
payload: { tool: o.name, input },
|
|
380
|
+
// A gated class so requestApproval never short-circuits as "not gated".
|
|
381
|
+
classification: [decision.actionClass === "financial" ? "financial" : decision.actionClass === "external" ? "external" : "irreversible"],
|
|
382
|
+
kind: actionClass,
|
|
383
|
+
subject: `${o.name}: ${decision.why}`,
|
|
384
|
+
approver: target ? { memberId: target } : undefined,
|
|
385
|
+
deliverFn: target
|
|
386
|
+
? async ({ text }) => notifyMember({ conn, memberId: target, body: text, idempotencyId: `gov-${payloadHash.slice(0, 40)}` }, deps)
|
|
387
|
+
: undefined,
|
|
388
|
+
fetchImpl: deps.fetchImpl,
|
|
389
|
+
});
|
|
390
|
+
} catch (err) {
|
|
391
|
+
warn(`approval request threw (${err && err.message ? err.message : err}) — the call stays held`);
|
|
392
|
+
}
|
|
393
|
+
const serverId = filed && filed.frame && filed.frame.ok && filed.frame.result && filed.frame.result.id ? String(filed.frame.result.id) : null;
|
|
394
|
+
const filedOk = !!(filed && filed.requested);
|
|
395
|
+
const next = filedOk
|
|
396
|
+
? `approval_wait approvalId=${serverId || filed.id}; when approved, call ${o.name} again with the SAME input plus ${APPROVAL_INPUT_KEY}="${serverId || filed.id}".`
|
|
397
|
+
: "the approval could not be filed — tell the person who asked that this needs a human's approval.";
|
|
398
|
+
return {
|
|
399
|
+
frame: mk(
|
|
400
|
+
"GOVERNANCE_NOT_READY",
|
|
401
|
+
`${o.name} held for approval: ${decision.why}. ${next}`,
|
|
402
|
+
{ approvalId: serverId || (filed && filed.id) || null, payloadHash, filed: filedOk, escalatedTo: target },
|
|
403
|
+
),
|
|
404
|
+
input,
|
|
405
|
+
decision,
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
export const _internals = { approvalHolds, emitGuard };
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/org/governance-store.mjs — where the seat's Genesis governance fields
|
|
3
|
+
* live on disk, and the one reader every enforcement point uses (WS6, M1).
|
|
4
|
+
*
|
|
5
|
+
* Two copies, one reader:
|
|
6
|
+
* config/agent.json orgProfile.agentGovernance written by enrollment /
|
|
7
|
+
* `maestro setup` sync (enroll-from-cohort#mapOrgProfile)
|
|
8
|
+
* state/org/governance.json written by the presence
|
|
9
|
+
* beat's throttled whoami refresh, so a day-7 relaxation, a
|
|
10
|
+
* plan change or a new cap is seen without a re-setup.
|
|
11
|
+
* The state file wins when both exist: it is the fresher of the two by
|
|
12
|
+
* construction (the beat refreshes it; agent.json moves only on setup).
|
|
13
|
+
*
|
|
14
|
+
* WHY `agentGovernance` AND NOT `governance`: `orgProfile.governance` already
|
|
15
|
+
* exists and is the member's GovernanceRelationship edge list (an array). Re-
|
|
16
|
+
* using the key would change its type under every reader of it.
|
|
17
|
+
*
|
|
18
|
+
* Read-only module (the writes use lib/fs-atomic). No network. Never throws:
|
|
19
|
+
* a missing or corrupt file reads as "no governance", which is the old-server
|
|
20
|
+
* reading — today's behaviour.
|
|
21
|
+
*
|
|
22
|
+
* Imported by lib/budget-guard.mjs, so it must not import anything that imports
|
|
23
|
+
* the guard back.
|
|
24
|
+
*
|
|
25
|
+
* @module lib/org/governance-store
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
"use strict";
|
|
29
|
+
|
|
30
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
31
|
+
import { join } from "node:path";
|
|
32
|
+
|
|
33
|
+
import { writeJsonAtomic } from "../fs-atomic.mjs";
|
|
34
|
+
import { readAgentGovernance } from "./genesis-contract.mjs";
|
|
35
|
+
|
|
36
|
+
export const GOVERNANCE_STATE_REL = join("state", "org", "governance.json");
|
|
37
|
+
export const PAUSE_STATE_REL = join("state", "org", "governance-pause.json");
|
|
38
|
+
|
|
39
|
+
/** The DTO keys whose presence marks a post-redesign server. */
|
|
40
|
+
export const GOVERNANCE_FIELDS = Object.freeze([
|
|
41
|
+
"planTier", "reportsTo", "approvalMode", "decisionRights", "workspaceNevers", "spendCaps", "teamMode", "firstAction",
|
|
42
|
+
]);
|
|
43
|
+
|
|
44
|
+
/** @param {unknown} v */
|
|
45
|
+
const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Unwrap a whoami/member response to the member DTO (bare, or under
|
|
49
|
+
* member/profile/result/data — the wrappers client.mjs#unwrapProfile accepts).
|
|
50
|
+
* @param {unknown} input
|
|
51
|
+
* @returns {Record<string, unknown>}
|
|
52
|
+
*/
|
|
53
|
+
export function memberDto(input) {
|
|
54
|
+
if (!isObj(input)) return {};
|
|
55
|
+
if ("slug" in input || GOVERNANCE_FIELDS.some((k) => k in input)) return input;
|
|
56
|
+
for (const key of ["member", "profile", "result", "data"]) {
|
|
57
|
+
if (isObj(input[key])) return input[key];
|
|
58
|
+
}
|
|
59
|
+
return input;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Which governance fields the server actually sent. An empty list is an old
|
|
64
|
+
* server (or a human member, for whom hq sends none).
|
|
65
|
+
* @param {unknown} input
|
|
66
|
+
* @returns {string[]}
|
|
67
|
+
*/
|
|
68
|
+
export function governanceFieldsPresent(input) {
|
|
69
|
+
const m = memberDto(input);
|
|
70
|
+
return GOVERNANCE_FIELDS.filter((k) => m[k] !== undefined);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The persisted projection: the fields as `readAgentGovernance` reads them,
|
|
75
|
+
* plus which ones were really on the wire. Pure.
|
|
76
|
+
* @param {unknown} dto
|
|
77
|
+
* @param {number} [now] epoch ms
|
|
78
|
+
* @returns {{present: boolean, fields: string[], governance: object, memberId: string|null, slug: string|null, fetchedAt: string}}
|
|
79
|
+
*/
|
|
80
|
+
export function governanceRecord(dto, now = Date.now()) {
|
|
81
|
+
const m = memberDto(dto);
|
|
82
|
+
const fields = governanceFieldsPresent(m);
|
|
83
|
+
return {
|
|
84
|
+
present: fields.length > 0,
|
|
85
|
+
fields,
|
|
86
|
+
governance: readAgentGovernance(m),
|
|
87
|
+
memberId: typeof m.memberId === "string" ? m.memberId : null,
|
|
88
|
+
slug: typeof m.slug === "string" ? m.slug : null,
|
|
89
|
+
fetchedAt: new Date(now).toISOString(),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** @param {string} path */
|
|
94
|
+
function readJson(path) {
|
|
95
|
+
try {
|
|
96
|
+
if (!existsSync(path)) return null;
|
|
97
|
+
const v = JSON.parse(readFileSync(path, "utf8"));
|
|
98
|
+
return isObj(v) ? v : null;
|
|
99
|
+
} catch {
|
|
100
|
+
// Corrupt or unreadable reads as absent: absent governance is the old-server
|
|
101
|
+
// reading, which is today's behaviour — the safe direction to fail.
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Read config/agent.json, fail-open. */
|
|
107
|
+
export function readAgentJson(agentRoot) {
|
|
108
|
+
return readJson(join(agentRoot || ".", "config", "agent.json")) || {};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* The seat's governance, from the freshest copy on disk.
|
|
113
|
+
*
|
|
114
|
+
* @param {string} agentRoot
|
|
115
|
+
* @returns {{present: boolean, fields: string[], governance: object|null, memberId: string|null, slug: string|null, fetchedAt: string|null, source: "state"|"agent.json"|"none"}}
|
|
116
|
+
*/
|
|
117
|
+
export function loadGovernance(agentRoot) {
|
|
118
|
+
const none = { present: false, fields: [], governance: null, memberId: null, slug: null, fetchedAt: null, source: "none" };
|
|
119
|
+
if (!agentRoot) return none;
|
|
120
|
+
const state = readJson(join(agentRoot, GOVERNANCE_STATE_REL));
|
|
121
|
+
if (state && Array.isArray(state.fields)) {
|
|
122
|
+
const present = state.fields.length > 0;
|
|
123
|
+
return {
|
|
124
|
+
present,
|
|
125
|
+
fields: state.fields.filter((f) => typeof f === "string"),
|
|
126
|
+
// Re-read through the contract reader: a hand-edited or older-shaped file
|
|
127
|
+
// can never hand the gate a malformed value.
|
|
128
|
+
governance: present ? readAgentGovernance(state.governance || {}) : null,
|
|
129
|
+
memberId: typeof state.memberId === "string" ? state.memberId : null,
|
|
130
|
+
slug: typeof state.slug === "string" ? state.slug : null,
|
|
131
|
+
fetchedAt: typeof state.fetchedAt === "string" ? state.fetchedAt : null,
|
|
132
|
+
source: "state",
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
const agent = readAgentJson(agentRoot);
|
|
136
|
+
const ag = agent.orgProfile && isObj(agent.orgProfile.agentGovernance) ? agent.orgProfile.agentGovernance : null;
|
|
137
|
+
if (!ag) return none;
|
|
138
|
+
const fields = governanceFieldsPresent(ag);
|
|
139
|
+
if (!fields.length) return none;
|
|
140
|
+
return {
|
|
141
|
+
present: true,
|
|
142
|
+
fields,
|
|
143
|
+
governance: readAgentGovernance(ag),
|
|
144
|
+
memberId: typeof agent.memberId === "string" ? agent.memberId : null,
|
|
145
|
+
slug: null,
|
|
146
|
+
fetchedAt: null,
|
|
147
|
+
source: "agent.json",
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Persist a governance record (the beat's refresh). Atomic.
|
|
153
|
+
* @param {string} agentRoot
|
|
154
|
+
* @param {object} record a governanceRecord()
|
|
155
|
+
* @returns {{ok: true, path: string} | {ok: false, error: string}}
|
|
156
|
+
*/
|
|
157
|
+
export function persistGovernance(agentRoot, record) {
|
|
158
|
+
const path = join(agentRoot, GOVERNANCE_STATE_REL);
|
|
159
|
+
try {
|
|
160
|
+
writeJsonAtomic(path, record);
|
|
161
|
+
return { ok: true, path };
|
|
162
|
+
} catch (err) {
|
|
163
|
+
return { ok: false, error: `could not write ${GOVERNANCE_STATE_REL}: ${err && err.message ? err.message : err}` };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The workspace email domain (lower-case), from the seat's own address — what
|
|
169
|
+
* "internal" means for a recipient. Null when the seat has no address.
|
|
170
|
+
* @param {string} agentRoot
|
|
171
|
+
* @returns {string|null}
|
|
172
|
+
*/
|
|
173
|
+
export function workspaceDomain(agentRoot) {
|
|
174
|
+
const a = readAgentJson(agentRoot);
|
|
175
|
+
const email = [a.email, a.agentEmail, a.identity && a.identity.email].find((e) => typeof e === "string" && e.includes("@"));
|
|
176
|
+
return email ? email.split("@").pop().toLowerCase() : null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ── The local pause ──────────────────────────────────────────────────────────
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* @typedef {object} PauseState
|
|
183
|
+
* @property {string} source "monthly_cap" | "single_action_cap" | "directive"
|
|
184
|
+
* @property {string} reason one plain sentence
|
|
185
|
+
* @property {string} since ISO
|
|
186
|
+
* @property {string|null} month YYYY-MM for a monthly-cap pause
|
|
187
|
+
* @property {string|null} capsFingerprint the caps in force when it paused
|
|
188
|
+
*/
|
|
189
|
+
|
|
190
|
+
/** @param {string} agentRoot @returns {PauseState|null} */
|
|
191
|
+
export function readPause(agentRoot) {
|
|
192
|
+
if (!agentRoot) return null;
|
|
193
|
+
const p = readJson(join(agentRoot, PAUSE_STATE_REL));
|
|
194
|
+
return p && typeof p.source === "string" ? /** @type {PauseState} */ (p) : null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** @param {string} agentRoot @param {PauseState} state */
|
|
198
|
+
export function writePause(agentRoot, state) {
|
|
199
|
+
try {
|
|
200
|
+
writeJsonAtomic(join(agentRoot, PAUSE_STATE_REL), state);
|
|
201
|
+
return { ok: true };
|
|
202
|
+
} catch (err) {
|
|
203
|
+
return { ok: false, error: `could not write ${PAUSE_STATE_REL}: ${err && err.message ? err.message : err}` };
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Lift the pause. The state is kept, marked lifted, so the history survives. */
|
|
208
|
+
export function clearPause(agentRoot, { now = Date.now(), why = "lifted" } = {}) {
|
|
209
|
+
const p = readPause(agentRoot);
|
|
210
|
+
if (!p) return { ok: true, cleared: false };
|
|
211
|
+
try {
|
|
212
|
+
writeJsonAtomic(join(agentRoot, PAUSE_STATE_REL + ".lifted"), { ...p, liftedAt: new Date(now).toISOString(), why });
|
|
213
|
+
} catch { /* the lifted record is history only; failing to keep it must not keep the seat paused */ }
|
|
214
|
+
try {
|
|
215
|
+
writeJsonAtomic(join(agentRoot, PAUSE_STATE_REL), { lifted: true, at: new Date(now).toISOString(), why });
|
|
216
|
+
return { ok: true, cleared: true };
|
|
217
|
+
} catch (err) {
|
|
218
|
+
return { ok: false, error: `could not lift the pause: ${err && err.message ? err.message : err}` };
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** The caps, as a string that changes when either cap changes. */
|
|
223
|
+
export function capsFingerprint(governance) {
|
|
224
|
+
const c = (governance && governance.spendCaps) || {};
|
|
225
|
+
return `${c.monthlyMicros ?? "none"}:${c.singleActionMicros ?? "none"}`;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* The charter's monthly cap in cents, for budget-guard. Null when the server
|
|
230
|
+
* sent none (or no governance at all).
|
|
231
|
+
* @param {string} agentRoot
|
|
232
|
+
* @returns {number|null}
|
|
233
|
+
*/
|
|
234
|
+
export function charterMonthlyCapCents(agentRoot) {
|
|
235
|
+
const g = loadGovernance(agentRoot);
|
|
236
|
+
const m = g.present && g.governance ? g.governance.spendCaps.monthlyMicros : null;
|
|
237
|
+
return m == null ? null : Math.floor(m / 10_000);
|
|
238
|
+
}
|