@cohortapp/agent-sdk 2.18.37 → 2.19.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 +10 -1
- package/docs/guides/billing-console-keys.md +16 -3
- package/lib/assurance/first-reply.mjs +31 -2
- package/lib/assurance/operator-plane-store.mjs +164 -0
- package/lib/assurance/operator-plane.mjs +689 -0
- package/lib/budget-guard.mjs +93 -3
- package/lib/cli/attention.mjs +300 -0
- package/lib/cli/seat-auth.mjs +86 -6
- package/lib/comms/receipts.mjs +15 -3
- package/lib/comms/send-gate.mjs +329 -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/registry.mjs +7 -1
- package/lib/org/tool-surface.mjs +28 -0
- package/lib/setup/enroll-from-cohort.mjs +11 -0
- package/lib/telemetry/alerts.mjs +86 -1
- package/lib/telemetry/collect.mjs +237 -1
- package/package.json +1 -1
- package/scripts/daemon/agent-daemon.mjs +41 -2
- package/scripts/daemon/assurance.mjs +482 -55
- package/scripts/daemon/cadence-consumer.mjs +17 -0
- package/scripts/daemon/context-compiler.mjs +25 -0
- package/scripts/daemon/deliver.mjs +71 -5
- package/scripts/fleet/closing-sweep.mjs +266 -0
- package/scripts/healthcheck.sh +35 -0
- package/scripts/local-triggers/autoupdate.sh +61 -5
- package/scripts/maintenance/check-stamp-freshness.mjs +314 -0
- package/scripts/org/send-orgmail.mjs +112 -25
- package/scripts/session/supervisor.mjs +14 -0
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/org/governance.mjs — the pure rules the Genesis governance fields drive
|
|
3
|
+
* at runtime (WS6, M2). No I/O, no clock, no env: every input is a parameter.
|
|
4
|
+
*
|
|
5
|
+
* The server (Cohort) computes the hard parts — the EFFECTIVE approval mode
|
|
6
|
+
* (override + day-7 relaxation), Forbidden with the workspace nevers merged in —
|
|
7
|
+
* and ships them on whoami/members. This module decides what one tool call may
|
|
8
|
+
* do given those fields. The effectful halves (filing the approval, pausing,
|
|
9
|
+
* notifying) live in `governance-runtime.mjs`.
|
|
10
|
+
*
|
|
11
|
+
* ── OLD SERVER = TODAY'S BEHAVIOUR, EXACTLY ─────────────────────────────────
|
|
12
|
+
* `present:false` (no governance field on the wire) returns `allow` before any
|
|
13
|
+
* rule runs. `approvalMode:null` (a server that sends rights but no mode) gates
|
|
14
|
+
* nothing on mode. Nothing here invents a mode, a cap or a clause.
|
|
15
|
+
*
|
|
16
|
+
* @module lib/org/governance
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
"use strict";
|
|
20
|
+
|
|
21
|
+
import { describeCall, matchClauses, statedAmountMicros } from "./clause-match.mjs";
|
|
22
|
+
import { effectiveForbidden } from "./genesis-contract.mjs";
|
|
23
|
+
|
|
24
|
+
// ── Action classes ───────────────────────────────────────────────────────────
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The governance action classes of a tool call.
|
|
28
|
+
* read no side effect. Never gated (the onboarding pass is reads).
|
|
29
|
+
* plumbing governance's own machinery and work visibility — gating
|
|
30
|
+
* approval_request on an approval is a deadlock.
|
|
31
|
+
* conversation speaking inside the workspace. NOT gated by approval mode:
|
|
32
|
+
* in `all_first_week` the agent must still be able to reply
|
|
33
|
+
* to, and ask, the very human who approves — an approval to
|
|
34
|
+
* say "I need an approval" never resolves. Forbidden and
|
|
35
|
+
* escalates clauses still apply to it.
|
|
36
|
+
* internal_write a write that stays inside the workspace.
|
|
37
|
+
* external leaves the workspace (email out, invites/shares to outside
|
|
38
|
+
* addresses, third-party integration writes).
|
|
39
|
+
* financial moves or commits money (pays a bill, sends an invoice).
|
|
40
|
+
*/
|
|
41
|
+
export const ACTION_CLASSES = Object.freeze(["read", "plumbing", "conversation", "internal_write", "external", "financial"]);
|
|
42
|
+
|
|
43
|
+
/** Tools that are governance's own machinery or pure visibility. */
|
|
44
|
+
export const PLUMBING_TOOLS = Object.freeze(new Set([
|
|
45
|
+
"approval_request", "approval_wait", "escalation_raise", "board_track", "work_track",
|
|
46
|
+
"messaging_react", "messaging_bookmark", "messaging_mark_unread_from", "email_mark_read",
|
|
47
|
+
"memory_author", "preference_remember", "knowledge_append", "board_claim", "board_complete",
|
|
48
|
+
"org_describe", "session_status", "org_whoami",
|
|
49
|
+
]));
|
|
50
|
+
|
|
51
|
+
/** In-workspace speech. */
|
|
52
|
+
export const CONVERSATION_TOOLS = Object.freeze(new Set([
|
|
53
|
+
"messaging_send", "messaging_send_voice_note", "messaging_open_dm", "messaging_open_group",
|
|
54
|
+
"task_comment", "decision_comment", "engage_colleagues",
|
|
55
|
+
]));
|
|
56
|
+
|
|
57
|
+
/** Money moves. */
|
|
58
|
+
export const FINANCIAL_TOOLS = Object.freeze(new Set(["books_bill_approve", "books_invoice_send"]));
|
|
59
|
+
|
|
60
|
+
/** Always leave the workspace. */
|
|
61
|
+
export const EXTERNAL_TOOLS = Object.freeze(new Set(["email_send", "email_draft_send"]));
|
|
62
|
+
|
|
63
|
+
/** RPC methods (for `org_rpc`) in the same classes. */
|
|
64
|
+
const FINANCIAL_METHODS = new Set(["books.billApprove", "books.invoiceSend"]);
|
|
65
|
+
const EXTERNAL_METHODS = new Set(["email.send", "email.draftSend"]);
|
|
66
|
+
const PLUMBING_METHODS = new Set(["approval.request", "approval.wait", "approval.get", "escalation.ask", "board.track", "presence.beat", "cost.report"]);
|
|
67
|
+
const CONVERSATION_METHODS = new Set(["messaging.send", "messaging.typing", "channel.resolveOrCreateDm"]);
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Classify one tool call. Pure.
|
|
71
|
+
*
|
|
72
|
+
* @param {string} name tool name
|
|
73
|
+
* @param {object} input
|
|
74
|
+
* @param {object|null} def the tool descriptor (`access`, `integration`, `binding`)
|
|
75
|
+
* @param {{workspaceDomain?: string|null, methodSideEffecting?: (m:string)=>boolean}} [o]
|
|
76
|
+
* @returns {string} one of ACTION_CLASSES
|
|
77
|
+
*/
|
|
78
|
+
export function actionClassFor(name, input = {}, def = null, o = {}) {
|
|
79
|
+
const i = input && typeof input === "object" ? input : {};
|
|
80
|
+
if (name === "org_rpc") {
|
|
81
|
+
const m = typeof i.method === "string" ? i.method : "";
|
|
82
|
+
if (PLUMBING_METHODS.has(m)) return "plumbing";
|
|
83
|
+
if (FINANCIAL_METHODS.has(m)) return "financial";
|
|
84
|
+
if (EXTERNAL_METHODS.has(m)) return "external";
|
|
85
|
+
if (CONVERSATION_METHODS.has(m)) return "conversation";
|
|
86
|
+
const se = typeof o.methodSideEffecting === "function" ? o.methodSideEffecting(m) : true;
|
|
87
|
+
return se ? "internal_write" : "read";
|
|
88
|
+
}
|
|
89
|
+
if (PLUMBING_TOOLS.has(name)) return "plumbing";
|
|
90
|
+
if (FINANCIAL_TOOLS.has(name)) return "financial";
|
|
91
|
+
if (EXTERNAL_TOOLS.has(name)) return "external";
|
|
92
|
+
const access = def && def.access ? String(def.access) : "write";
|
|
93
|
+
if (access === "read") return "read";
|
|
94
|
+
// A granted integration tool writes into somebody else's system.
|
|
95
|
+
if (def && def.integration) return "external";
|
|
96
|
+
if (CONVERSATION_TOOLS.has(name)) return "conversation";
|
|
97
|
+
// Invites and shares that reach an outside address leave the workspace.
|
|
98
|
+
const call = describeCall(name, i, { workspaceDomain: o.workspaceDomain || null });
|
|
99
|
+
if (call.audience === "external") return "external";
|
|
100
|
+
return "internal_write";
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Does the approval mode require a human approval before this class runs?
|
|
105
|
+
* all_first_week → every write (internal, external, financial)
|
|
106
|
+
* external_only → external + financial (money leaving the org is outbound)
|
|
107
|
+
* none / null → nothing (null = an old server: today's behaviour)
|
|
108
|
+
* @param {string|null} mode
|
|
109
|
+
* @param {string} actionClass
|
|
110
|
+
*/
|
|
111
|
+
export function modeRequiresApproval(mode, actionClass) {
|
|
112
|
+
if (actionClass === "read" || actionClass === "plumbing" || actionClass === "conversation") return false;
|
|
113
|
+
if (mode === "all_first_week") return true;
|
|
114
|
+
if (mode === "external_only") return actionClass === "external" || actionClass === "financial";
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** The approvals.kind/actionClass hq files the request under. */
|
|
119
|
+
export function approvalKindFor(actionClass) {
|
|
120
|
+
if (actionClass === "financial") return "spend";
|
|
121
|
+
if (actionClass === "external") return "external_comms";
|
|
122
|
+
return "exec";
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ── Team mode ────────────────────────────────────────────────────────────────
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* What teamMode allows the seat to INITIATE.
|
|
129
|
+
* off → nothing proactive (it still answers when addressed)
|
|
130
|
+
* assist → drafts for humans; proactive writes become drafts, not sends
|
|
131
|
+
* run → acts within its decision rights
|
|
132
|
+
* null → old server / no team: today's behaviour (= run)
|
|
133
|
+
* @param {string|null} teamMode
|
|
134
|
+
* @returns {{proactive: boolean, draftsOnly: boolean}}
|
|
135
|
+
*/
|
|
136
|
+
export function teamModePosture(teamMode) {
|
|
137
|
+
if (teamMode === "off") return { proactive: false, draftsOnly: false };
|
|
138
|
+
if (teamMode === "assist") return { proactive: true, draftsOnly: true };
|
|
139
|
+
return { proactive: true, draftsOnly: false };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ── The tool-call decision ───────────────────────────────────────────────────
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* @typedef {object} GateDecision
|
|
146
|
+
* @property {"allow"|"block"|"approve"|"escalate"|"over_cap"|"paused"} verdict
|
|
147
|
+
* @property {string} reason a stable code
|
|
148
|
+
* @property {string} why one plain sentence for the model and the log
|
|
149
|
+
* @property {string} actionClass
|
|
150
|
+
* @property {string|null} clause the clause that decided it, if any
|
|
151
|
+
* @property {string[]} notes weak matches surfaced, never enforced
|
|
152
|
+
* @property {number|null} amountMicros
|
|
153
|
+
*/
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Decide one tool call. Pure. Order: forbidden → single-action cap → paused →
|
|
157
|
+
* escalates → forbidden-with-approval → approval mode → allow.
|
|
158
|
+
*
|
|
159
|
+
* @param {object} o
|
|
160
|
+
* @param {string} o.name
|
|
161
|
+
* @param {object} [o.input]
|
|
162
|
+
* @param {object|null} [o.def]
|
|
163
|
+
* @param {import("./genesis-contract.mjs").AgentGovernance} [o.governance]
|
|
164
|
+
* @param {boolean} [o.present] the server sent governance fields at all
|
|
165
|
+
* @param {boolean} [o.approved] a verified, payload-bound approval accompanies the call
|
|
166
|
+
* @param {{reason:string}|null} [o.pause] the local pause in force, if any
|
|
167
|
+
* @param {string|null} [o.workspaceDomain]
|
|
168
|
+
* @param {(m:string)=>boolean} [o.methodSideEffecting]
|
|
169
|
+
* @returns {GateDecision}
|
|
170
|
+
*/
|
|
171
|
+
export function decideToolCall(o = {}) {
|
|
172
|
+
const name = String(o.name || "");
|
|
173
|
+
const input = o.input && typeof o.input === "object" ? o.input : {};
|
|
174
|
+
const g = o.governance || null;
|
|
175
|
+
const amountMicros = statedAmountMicros(input);
|
|
176
|
+
const actionClass = actionClassFor(name, input, o.def || null, {
|
|
177
|
+
workspaceDomain: o.workspaceDomain || null,
|
|
178
|
+
methodSideEffecting: o.methodSideEffecting,
|
|
179
|
+
});
|
|
180
|
+
const base = { actionClass, clause: null, notes: [], amountMicros };
|
|
181
|
+
const out = (verdict, reason, why, extra = {}) => ({ ...base, verdict, reason, why, ...extra });
|
|
182
|
+
|
|
183
|
+
if (!o.present || !g) return out("allow", "no_governance", "the server sent no governance fields (old server) — nothing to enforce");
|
|
184
|
+
if (actionClass === "read" || actionClass === "plumbing") return out("allow", actionClass, `${actionClass} calls are never gated`);
|
|
185
|
+
|
|
186
|
+
const call = describeCall(name, input, { workspaceDomain: o.workspaceDomain || null });
|
|
187
|
+
const forbidden = effectiveForbidden(g.decisionRights.forbidden, g.workspaceNevers);
|
|
188
|
+
const fMatches = matchClauses(forbidden, call);
|
|
189
|
+
const notes = [];
|
|
190
|
+
|
|
191
|
+
// 1. Forbidden, unqualified, clear → hard block. Approval cannot lift it.
|
|
192
|
+
const hard = fMatches.find((m) => m.strength === "clear" && !m.approvalWay);
|
|
193
|
+
if (hard) {
|
|
194
|
+
return out("block", "forbidden", `forbidden by "${hard.clause}" — ${hard.why}`, { clause: hard.clause });
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// 2. Single-action cap, checked against the call's stated cost.
|
|
198
|
+
const capMicros = g.spendCaps && g.spendCaps.singleActionMicros;
|
|
199
|
+
if (capMicros != null && amountMicros != null && amountMicros > capMicros) {
|
|
200
|
+
return out(
|
|
201
|
+
"over_cap",
|
|
202
|
+
"single_action_cap",
|
|
203
|
+
`this action states $${(amountMicros / 1e6).toFixed(2)}, over the $${(capMicros / 1e6).toFixed(2)} single-action cap`,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// 3. A spend pause refuses anything that states a cost; everything else runs
|
|
208
|
+
// (proactive initiation is stopped upstream, at the cadence consumer and
|
|
209
|
+
// the ladder — answering is not).
|
|
210
|
+
if (o.pause && amountMicros != null && amountMicros > 0) {
|
|
211
|
+
return out("paused", "paused", `spending is paused (${o.pause.reason || "cap reached"}) and this action states a cost`);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
for (const m of fMatches) if (m.strength === "weak" && !m.approvalWay) notes.push(`Forbidden "${m.clause}" may apply: ${m.why}`);
|
|
215
|
+
|
|
216
|
+
// 4. Escalates: a clear match goes to a human, whatever the mode.
|
|
217
|
+
const eMatches = matchClauses(g.decisionRights.escalates, call);
|
|
218
|
+
const esc = eMatches.find((m) => m.strength === "clear");
|
|
219
|
+
for (const m of eMatches) if (m.strength === "weak") notes.push(`Escalates "${m.clause}" may apply: ${m.why}`);
|
|
220
|
+
if (esc && !o.approved) {
|
|
221
|
+
return out("escalate", "escalates", `"${esc.clause}" escalates — ${esc.why}`, { clause: esc.clause, notes });
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// 5. Forbidden "…without approval": the clause names its own way through.
|
|
225
|
+
// Weak matches qualify too — the cost of a false positive is one click.
|
|
226
|
+
const qualified = fMatches.find((m) => m.approvalWay);
|
|
227
|
+
if (qualified && !o.approved) {
|
|
228
|
+
return out("approve", "forbidden_without_approval", `"${qualified.clause}" needs an approval — ${qualified.why}`, { clause: qualified.clause, notes });
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// 6. The approval mode.
|
|
232
|
+
if (modeRequiresApproval(g.approvalMode, actionClass) && !o.approved) {
|
|
233
|
+
return out("approve", `approval_mode:${g.approvalMode}`, `approval mode ${g.approvalMode} requires an approval for ${actionClass.replace("_", " ")} actions`, { notes });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// 7. Team on assist: the seat drafts, a human sends. Anything that leaves
|
|
237
|
+
// the workspace or moves money goes through a human even when the
|
|
238
|
+
// approval mode alone would let it run.
|
|
239
|
+
if (teamModePosture(g.teamMode).draftsOnly && (actionClass === "external" || actionClass === "financial") && !o.approved) {
|
|
240
|
+
return out("approve", "team_mode:assist", "the team has this seat on assist — a human sends what leaves the workspace", { notes });
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return out("allow", o.approved ? "approved" : "within_rights", o.approved ? "approved by a human" : "within decision rights", { notes });
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// ── Spend caps ───────────────────────────────────────────────────────────────
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Is the monthly cap reached? Pure.
|
|
250
|
+
* @param {{spentMicros: number, monthlyMicros: number|null}} o
|
|
251
|
+
* @returns {{reached: boolean, pct: number|null}}
|
|
252
|
+
*/
|
|
253
|
+
export function monthlyCapStatus({ spentMicros, monthlyMicros }) {
|
|
254
|
+
if (monthlyMicros == null || !Number.isFinite(spentMicros)) return { reached: false, pct: null };
|
|
255
|
+
if (monthlyMicros <= 0) return { reached: true, pct: null };
|
|
256
|
+
const pct = +((spentMicros / monthlyMicros) * 100).toFixed(2);
|
|
257
|
+
return { reached: spentMicros >= monthlyMicros, pct };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
// ── The prompt line ──────────────────────────────────────────────────────────
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* The decision-rights block for the compiled context. Every clause the matcher
|
|
264
|
+
* cannot enforce still reaches the model here, which is where they all lived
|
|
265
|
+
* before this module. Empty string when there is nothing to say.
|
|
266
|
+
* @param {import("./genesis-contract.mjs").AgentGovernance|null} g
|
|
267
|
+
* @param {{pause?: {reason:string}|null}} [o]
|
|
268
|
+
* @returns {string}
|
|
269
|
+
*/
|
|
270
|
+
export function governancePromptBlock(g, o = {}) {
|
|
271
|
+
if (!g) return "";
|
|
272
|
+
const lines = [];
|
|
273
|
+
const forbidden = effectiveForbidden(g.decisionRights.forbidden, g.workspaceNevers);
|
|
274
|
+
if (g.decisionRights.autonomous.length) lines.push(`You may, without asking: ${g.decisionRights.autonomous.join("; ")}.`);
|
|
275
|
+
if (g.decisionRights.escalates.length) lines.push(`Take to a human first: ${g.decisionRights.escalates.join("; ")}.`);
|
|
276
|
+
if (forbidden.length) lines.push(`Forbidden: ${forbidden.join("; ")}.`);
|
|
277
|
+
if (g.approvalMode === "all_first_week") lines.push("Every action other than talking to colleagues needs an approval this week.");
|
|
278
|
+
else if (g.approvalMode === "external_only") lines.push("Anything that leaves the workspace or moves money needs an approval.");
|
|
279
|
+
if (g.teamMode === "off") lines.push("Your team has not switched you on: answer when asked, start nothing.");
|
|
280
|
+
else if (g.teamMode === "assist") lines.push("Your team has you on assist: draft for people to send, do not send for them.");
|
|
281
|
+
if (o.pause) lines.push(`Spending is paused (${o.pause.reason}). Do not start anything that costs money.`);
|
|
282
|
+
return lines.join("\n");
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// ── The execution ladder ─────────────────────────────────────────────────────
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* What governance adds to the execution ladder's inputs (lib/execution/
|
|
289
|
+
* disposition.mjs reads `runtime.directive`, `runtime.dailyCapExhausted` and
|
|
290
|
+
* `facts.escalateTo`; until WS6 the daemon fed it only `emergencyStop`). Pure.
|
|
291
|
+
*
|
|
292
|
+
* Returns EMPTY objects for an old server and for a seat with nothing in
|
|
293
|
+
* force, so `{...runtime, ...ladder.runtime}` changes nothing.
|
|
294
|
+
*
|
|
295
|
+
* @param {object} o
|
|
296
|
+
* @param {boolean} o.present
|
|
297
|
+
* @param {object|null} o.governance
|
|
298
|
+
* @param {{source:string}|null} [o.pause]
|
|
299
|
+
* @param {string|null} [o.firstHuman]
|
|
300
|
+
* @returns {{runtime: object, facts: object}}
|
|
301
|
+
*/
|
|
302
|
+
export function ladderInputs({ present, governance, pause = null, firstHuman = null }) {
|
|
303
|
+
const runtime = {};
|
|
304
|
+
const facts = {};
|
|
305
|
+
// A pause from the directive or a cap, and a team that has the seat OFF,
|
|
306
|
+
// read as `pause_schedules`: stop initiating, keep answering.
|
|
307
|
+
if (pause) runtime.directive = "pause_schedules";
|
|
308
|
+
if (pause && pause.source === "monthly_cap") runtime.dailyCapExhausted = true;
|
|
309
|
+
if (present && governance && !teamModePosture(governance.teamMode).proactive) runtime.directive = "pause_schedules";
|
|
310
|
+
if (present && firstHuman) facts.escalateTo = firstHuman;
|
|
311
|
+
return { runtime, facts };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Must the ladder's approval for these action classes go to a HUMAN, even on a
|
|
316
|
+
* surface whose policy grants the seat self-approval? Pure.
|
|
317
|
+
* `classes` are the ladder's (irreversible / external / financial).
|
|
318
|
+
* @param {string|null} approvalMode
|
|
319
|
+
* @param {readonly string[]} classes
|
|
320
|
+
*/
|
|
321
|
+
export function ladderNeedsHumanApproval(approvalMode, classes) {
|
|
322
|
+
const cs = Array.isArray(classes) ? classes : [];
|
|
323
|
+
if (approvalMode === "all_first_week") return cs.length > 0;
|
|
324
|
+
if (approvalMode === "external_only") return cs.includes("external") || cs.includes("financial");
|
|
325
|
+
return false;
|
|
326
|
+
}
|
package/lib/org/mesh.mjs
CHANGED
|
@@ -86,6 +86,10 @@ const KNOWN_DIRECTIVES = new Set([
|
|
|
86
86
|
"toolset_changed",
|
|
87
87
|
"restart",
|
|
88
88
|
"session.restart",
|
|
89
|
+
// Mandate-spine directives (protocol DIRECTIVES, 2026-08) — handled since WS6.
|
|
90
|
+
"pause_schedules",
|
|
91
|
+
"plan_stale",
|
|
92
|
+
"revoke_scope",
|
|
89
93
|
]);
|
|
90
94
|
|
|
91
95
|
/** Where the session runtime looks for a restart request (relative to the agent root). */
|
|
@@ -354,6 +358,113 @@ async function refreshIntegrationTools(ctx) {
|
|
|
354
358
|
}
|
|
355
359
|
}
|
|
356
360
|
|
|
361
|
+
/** The org credential in the shape governance-runtime takes. */
|
|
362
|
+
function connOf(ctx) {
|
|
363
|
+
const n = (ctx.cfg && ctx.cfg.org && ctx.cfg.org.cohort) || {};
|
|
364
|
+
return {
|
|
365
|
+
base: ctx.base,
|
|
366
|
+
token: ctx.token,
|
|
367
|
+
orgId: ctx.orgId,
|
|
368
|
+
agentId: n.agentId || process.env.COHORT_AGENT_ID || undefined,
|
|
369
|
+
fetchImpl: ctx.fetchImpl,
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/** `plan_stale`: refetch the mandate (lib/mandate/refresh). Fail-open. */
|
|
374
|
+
async function refreshMandateFromDirective(ctx) {
|
|
375
|
+
try {
|
|
376
|
+
const { refreshMandate } = await import("../mandate/refresh.mjs");
|
|
377
|
+
const r = await refreshMandate(ctx.agentRoot, {
|
|
378
|
+
base: ctx.base,
|
|
379
|
+
token: ctx.token,
|
|
380
|
+
orgId: ctx.orgId,
|
|
381
|
+
memberId: ctx.agentMemberId || undefined,
|
|
382
|
+
fetchImpl: ctx.fetchImpl,
|
|
383
|
+
log: (level, msg) => (level === "error" || level === "warn" ? logWarn(msg) : logInfo(msg)),
|
|
384
|
+
});
|
|
385
|
+
logInfo(`plan_stale directive — mandate refreshed (${r && r.source ? r.source : "unknown"}${r && r.changed ? ", changed" : ""})`);
|
|
386
|
+
} catch (err) {
|
|
387
|
+
logWarn(`plan_stale directive — mandate refresh failed (${err && err.message}) — running on the cached mandate`);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* The Genesis governance step of a beat (WS6): re-read whoami on a 15-minute
|
|
393
|
+
* throttle (or at once after plan_stale / revoke_scope), re-walk the
|
|
394
|
+
* reports-to chain when it changed, check the monthly spend cap on a 5-minute
|
|
395
|
+
* throttle, and run any first-run step that is due.
|
|
396
|
+
*
|
|
397
|
+
* Only runs with a client that can read the profile, so an injected test
|
|
398
|
+
* client without `fetchSelfProfile` keeps the beat exactly as it was. And
|
|
399
|
+
* every step after the refresh is a no-op for a seat whose server sends no
|
|
400
|
+
* governance fields (an old server). Fail-open throughout.
|
|
401
|
+
*/
|
|
402
|
+
async function governanceBeat(ctx) {
|
|
403
|
+
if (!ctx.client || typeof ctx.client.fetchSelfProfile !== "function") return;
|
|
404
|
+
let rt;
|
|
405
|
+
try { rt = await import("./governance-runtime.mjs"); } catch (err) {
|
|
406
|
+
logWarn(`governance module failed to load (${err && err.message}) — governance is not refreshed`);
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
const now = ctx.now();
|
|
410
|
+
const conn = connOf(ctx);
|
|
411
|
+
try {
|
|
412
|
+
const r = await rt.refreshGovernance({
|
|
413
|
+
agentRoot: ctx.agentRoot,
|
|
414
|
+
conn,
|
|
415
|
+
now,
|
|
416
|
+
lastAt: ctx.governanceAt,
|
|
417
|
+
force: ctx.governanceForce === true,
|
|
418
|
+
fetchSelfProfileImpl: ctx.client.fetchSelfProfile,
|
|
419
|
+
fetchImpl: ctx.fetchImpl,
|
|
420
|
+
});
|
|
421
|
+
if (r.ran) { ctx.governanceAt = now; ctx.governanceForce = false; }
|
|
422
|
+
if (!r.ok) logWarn(`governance refresh failed (${r.error}) — enforcing the last-good copy`);
|
|
423
|
+
if (r.ok && r.ran && r.record && r.record.present && (r.changed || !ctx.chainResolved)) {
|
|
424
|
+
const chain = await rt.resolveEscalation({
|
|
425
|
+
agentRoot: ctx.agentRoot,
|
|
426
|
+
conn,
|
|
427
|
+
governance: r.record.governance,
|
|
428
|
+
selfId: r.record.memberId || undefined,
|
|
429
|
+
now,
|
|
430
|
+
fetchSelfProfileImpl: ctx.client.fetchSelfProfile,
|
|
431
|
+
fetchImpl: ctx.fetchImpl,
|
|
432
|
+
});
|
|
433
|
+
ctx.chainResolved = true;
|
|
434
|
+
if (r.changed) logInfo(`governance refreshed (${r.record.fields.join(", ")}); escalations reach ${chain.firstHuman || `no human (${chain.reason})`}`);
|
|
435
|
+
}
|
|
436
|
+
} catch (err) {
|
|
437
|
+
logWarn(`governance refresh threw (${err && err.message}) — enforcing the last-good copy`);
|
|
438
|
+
}
|
|
439
|
+
if (!Number.isFinite(ctx.capCheckAt) || now - ctx.capCheckAt >= rt.CAP_CHECK_MS) {
|
|
440
|
+
ctx.capCheckAt = now;
|
|
441
|
+
try { await rt.enforceSpendCaps({ agentRoot: ctx.agentRoot, conn, now }); }
|
|
442
|
+
catch (err) { logWarn(`spend-cap check threw (${err && err.message})`); }
|
|
443
|
+
}
|
|
444
|
+
try {
|
|
445
|
+
const { runFirstRun } = await import("./first-run.mjs");
|
|
446
|
+
const { loadGovernance, readAgentJson } = await import("./governance-store.mjs");
|
|
447
|
+
const record = loadGovernance(ctx.agentRoot);
|
|
448
|
+
if (record.present) {
|
|
449
|
+
const agent = readAgentJson(ctx.agentRoot);
|
|
450
|
+
const fr = await runFirstRun({
|
|
451
|
+
agentRoot: ctx.agentRoot,
|
|
452
|
+
record,
|
|
453
|
+
conn,
|
|
454
|
+
slug: record.slug || conn.agentId || null,
|
|
455
|
+
leadMemberId: rt.cachedFirstHuman(ctx.agentRoot),
|
|
456
|
+
tz: typeof agent.timezone === "string" && agent.timezone ? agent.timezone : "UTC",
|
|
457
|
+
now,
|
|
458
|
+
});
|
|
459
|
+
if (fr.action !== "none" && fr.action !== "wait") {
|
|
460
|
+
(fr.ok ? logInfo : logWarn)(`first run: ${fr.action} (${fr.reason})${fr.error ? ` — ${fr.error}` : ""}`);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
} catch (err) {
|
|
464
|
+
logWarn(`first-run step threw (${err && err.message}) — retrying on the next beat`);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
357
468
|
/**
|
|
358
469
|
* Act on one directive. Pure dispatch; each handler is independently fail-open.
|
|
359
470
|
* @param {string} directive one of KNOWN_DIRECTIVES
|
|
@@ -389,6 +500,27 @@ async function handleDirective(directive, ctx) {
|
|
|
389
500
|
case "session.restart":
|
|
390
501
|
requestSessionRestart(ctx.agentRoot, ctx.now);
|
|
391
502
|
return;
|
|
503
|
+
case "pause_schedules": {
|
|
504
|
+
// Stop INITIATING, keep answering (protocol DIRECTIVES). The pause is
|
|
505
|
+
// durable: the beat delivers a queued directive ONCE, so a pause held
|
|
506
|
+
// only in memory would be lost on the next restart.
|
|
507
|
+
const { pauseFromDirective } = await import("./governance-runtime.mjs");
|
|
508
|
+
const r = await pauseFromDirective({ agentRoot: ctx.agentRoot, conn: connOf(ctx), now: ctx.now() });
|
|
509
|
+
logWarn(`pause_schedules directive — proactive work paused${r && r.already ? " (already paused)" : ""}`);
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
case "plan_stale":
|
|
513
|
+
// The mandate moved: refetch it, and re-read governance with it (a plan
|
|
514
|
+
// tier or a cap can move in the same change).
|
|
515
|
+
await refreshMandateFromDirective(ctx);
|
|
516
|
+
ctx.governanceForce = true;
|
|
517
|
+
return;
|
|
518
|
+
case "revoke_scope":
|
|
519
|
+
// A scope was withdrawn: re-probe what this seat may call (the granted
|
|
520
|
+
// tool set) and re-read governance on this same beat.
|
|
521
|
+
ctx.governanceForce = true;
|
|
522
|
+
await refreshIntegrationTools(ctx);
|
|
523
|
+
return;
|
|
392
524
|
default:
|
|
393
525
|
return; // forward-compatible: ignore unknown directives
|
|
394
526
|
}
|
|
@@ -484,6 +616,7 @@ async function beatOnce(ctx) {
|
|
|
484
616
|
// refresh never affects the beat's returned directives. A `toolset_changed`
|
|
485
617
|
// directive above already forced this ahead of the poll when hq pushes one.
|
|
486
618
|
if (!ctx.stopped) await refreshIntegrationTools(ctx);
|
|
619
|
+
if (!ctx.stopped) await governanceBeat(ctx);
|
|
487
620
|
return directives;
|
|
488
621
|
}
|
|
489
622
|
|
|
@@ -615,6 +748,8 @@ export const _internals = {
|
|
|
615
748
|
resyncDirectory,
|
|
616
749
|
refreshPolicy,
|
|
617
750
|
refreshIntegrationTools,
|
|
751
|
+
governanceBeat,
|
|
752
|
+
refreshMandateFromDirective,
|
|
618
753
|
collectBeatStatus,
|
|
619
754
|
escalateCriticalAlerts,
|
|
620
755
|
KNOWN_DIRECTIVES,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
289887e9e8d2257bc47ce9b2c04f4db41450ceb225d31f6f31a9370b74d5cd2f
|
package/lib/org/protocol.mjs
CHANGED
|
@@ -480,6 +480,12 @@ export const METHODS = Object.freeze({
|
|
|
480
480
|
// the asker, the same law as `Approval.requester ≠ approver`.
|
|
481
481
|
"escalation.ask": { family: "escalation", scope: "org.write", sideEffecting: true },
|
|
482
482
|
"escalation.answer": { family: "escalation", scope: "org.write", sideEffecting: true },
|
|
483
|
+
// The `OpenQuestion` READER, split from `escalation.list` on purpose: that
|
|
484
|
+
// method lists the `Escalation` model and its callers read that shape, so
|
|
485
|
+
// widening it to two entities would break them. `ask` wrote OpenQuestions with
|
|
486
|
+
// no way to read them back on the RPC surface (only `queries/board.ts`, a
|
|
487
|
+
// board-UI query, ever did) — this is the missing read leg. org.read.
|
|
488
|
+
"escalation.openQuestions": { family: "escalation", scope: "org.read", sideEffecting: false },
|
|
483
489
|
// --- annotation ---
|
|
484
490
|
"annotation.create": { family: "annotation", scope: "org.write", sideEffecting: true, idempotent: true },
|
|
485
491
|
"annotation.comment": { family: "annotation", scope: "org.write", sideEffecting: true },
|
package/lib/org/registry.mjs
CHANGED
|
@@ -99,6 +99,12 @@ export function buildSelfEntry(o = {}) {
|
|
|
99
99
|
* @param {object} [opts] - { limit=5, queues=["action-stack","backlog"], items? }
|
|
100
100
|
* @returns {Promise<object[]>}
|
|
101
101
|
*/
|
|
102
|
+
// An allow list, not a deny list: a deny list publishes every terminal status
|
|
103
|
+
// it forgot to name (resolved, superseded …) as fleet focus — one resolved row
|
|
104
|
+
// was a seat's top focus eight days after it closed. Unknown statuses are
|
|
105
|
+
// omitted; a missing status still reads as open.
|
|
106
|
+
const LIVE_FOCUS_STATUSES = new Set(["open", "in_progress", "blocked"]);
|
|
107
|
+
|
|
102
108
|
export async function currentFocus(agentRoot, opts = {}) {
|
|
103
109
|
const limit = Number.isFinite(opts.limit) ? opts.limit : 5;
|
|
104
110
|
if (Array.isArray(opts.items)) return opts.items.slice(0, limit);
|
|
@@ -115,7 +121,7 @@ export async function currentFocus(agentRoot, opts = {}) {
|
|
|
115
121
|
for (const it of items) {
|
|
116
122
|
if (!it || typeof it !== "object") continue;
|
|
117
123
|
const status = String(it.status || "open").toLowerCase();
|
|
118
|
-
if (status
|
|
124
|
+
if (!LIVE_FOCUS_STATUSES.has(status)) continue;
|
|
119
125
|
out.push({ title: String(it.title || it.next_action || "").slice(0, 140), queue: q, priority: it.priority || "normal" });
|
|
120
126
|
if (out.length >= limit) return out;
|
|
121
127
|
}
|
package/lib/org/tool-surface.mjs
CHANGED
|
@@ -3516,6 +3516,34 @@ async function executeOrgToolInner(name, input = {}, o = {}) {
|
|
|
3516
3516
|
|
|
3517
3517
|
const callOpts = { base: cfg.base, token: cfg.token, orgId: cfg.orgId, fetchImpl: o.fetchImpl };
|
|
3518
3518
|
|
|
3519
|
+
// Genesis governance gate (WS6, M2) — BOTH planes, before dispatch and
|
|
3520
|
+
// before the send-gate. Decision rights, inherited nevers, the approval
|
|
3521
|
+
// mode, team mode and the spend caps the server ships on whoami. A seat
|
|
3522
|
+
// whose server sends none of those fields (an old server) passes straight
|
|
3523
|
+
// through: `gateToolCall` returns no frame and the input unchanged. The
|
|
3524
|
+
// gate strips its own `governanceApprovalId` key, so a re-invocation after
|
|
3525
|
+
// an approval dispatches exactly the payload the human approved.
|
|
3526
|
+
if (o.governance !== false) {
|
|
3527
|
+
const { gateToolCall } = await import("./governance-runtime.mjs");
|
|
3528
|
+
const gated = await gateToolCall(
|
|
3529
|
+
{
|
|
3530
|
+
name,
|
|
3531
|
+
input,
|
|
3532
|
+
def,
|
|
3533
|
+
cfg,
|
|
3534
|
+
governanceOverride: o.governance || undefined,
|
|
3535
|
+
errFrame,
|
|
3536
|
+
methodSideEffecting: (m) => {
|
|
3537
|
+
const md = methodDef(m);
|
|
3538
|
+
return !md || md.sideEffecting !== false;
|
|
3539
|
+
},
|
|
3540
|
+
},
|
|
3541
|
+
{ fetchImpl: o.fetchImpl, ...(o.governanceDeps || {}) },
|
|
3542
|
+
);
|
|
3543
|
+
if (gated.frame) return gated.frame;
|
|
3544
|
+
input = gated.input;
|
|
3545
|
+
}
|
|
3546
|
+
|
|
3519
3547
|
// Send-gate screen for outbound-content tools (BOTH planes, before dispatch).
|
|
3520
3548
|
if (def.outbound) {
|
|
3521
3549
|
const method = def.binding && def.binding.method;
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
|
|
37
37
|
import { readAgentJson } from "./sot.mjs";
|
|
38
38
|
import { isPlaceholder } from "./completeness.mjs";
|
|
39
|
+
import { GOVERNANCE_FIELDS } from "../org/governance-store.mjs";
|
|
39
40
|
|
|
40
41
|
// Archetype axes the identity section also offers. Keep these in sync with
|
|
41
42
|
// lib/setup/sections/identity.mjs FUNCTIONS/ALTITUDES — a derived value MUST be
|
|
@@ -280,6 +281,16 @@ function mapOrgProfile(p) {
|
|
|
280
281
|
if (reports.length) out.reports = reports;
|
|
281
282
|
const governance = Array.isArray(p.governance) ? p.governance.filter((g) => g && typeof g === "object") : [];
|
|
282
283
|
if (governance.length) out.governance = governance;
|
|
284
|
+
// Genesis governance (WS6, M1): planTier, reportsTo, approvalMode (effective),
|
|
285
|
+
// decisionRights, workspaceNevers, spendCaps, teamMode, firstAction. Persisted
|
|
286
|
+
// under `agentGovernance` — `governance` above is the relationship-edge LIST
|
|
287
|
+
// and keeps its type. Only the fields the server actually sent are kept, raw,
|
|
288
|
+
// so the reader (lib/org/governance-store#loadGovernance) can tell an old
|
|
289
|
+
// server (none sent) from a new one, and normalises them through the WS0
|
|
290
|
+
// contract reader on the way out.
|
|
291
|
+
const agentGovernance = {};
|
|
292
|
+
for (const k of GOVERNANCE_FIELDS) if (p[k] !== undefined) agentGovernance[k] = p[k];
|
|
293
|
+
if (Object.keys(agentGovernance).length) out.agentGovernance = agentGovernance;
|
|
283
294
|
return Object.keys(out).length ? out : null;
|
|
284
295
|
}
|
|
285
296
|
|