@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.
Files changed (39) hide show
  1. package/bin/maestro.mjs +10 -1
  2. package/docs/guides/billing-console-keys.md +16 -3
  3. package/lib/assurance/first-reply.mjs +31 -2
  4. package/lib/assurance/operator-plane-store.mjs +164 -0
  5. package/lib/assurance/operator-plane.mjs +689 -0
  6. package/lib/budget-guard.mjs +93 -3
  7. package/lib/cli/attention.mjs +300 -0
  8. package/lib/cli/seat-auth.mjs +86 -6
  9. package/lib/comms/receipts.mjs +15 -3
  10. package/lib/comms/send-gate.mjs +329 -2
  11. package/lib/org/awareness.mjs +15 -2
  12. package/lib/org/clause-match.mjs +470 -0
  13. package/lib/org/client.mjs +27 -1
  14. package/lib/org/escalation-chain.mjs +134 -0
  15. package/lib/org/first-run.mjs +263 -0
  16. package/lib/org/genesis-contract.mjs +271 -0
  17. package/lib/org/governance-runtime.mjs +409 -0
  18. package/lib/org/governance-store.mjs +238 -0
  19. package/lib/org/governance.mjs +326 -0
  20. package/lib/org/mesh.mjs +135 -0
  21. package/lib/org/protocol.checksum +1 -1
  22. package/lib/org/protocol.mjs +6 -0
  23. package/lib/org/registry.mjs +7 -1
  24. package/lib/org/tool-surface.mjs +28 -0
  25. package/lib/setup/enroll-from-cohort.mjs +11 -0
  26. package/lib/telemetry/alerts.mjs +86 -1
  27. package/lib/telemetry/collect.mjs +237 -1
  28. package/package.json +1 -1
  29. package/scripts/daemon/agent-daemon.mjs +41 -2
  30. package/scripts/daemon/assurance.mjs +482 -55
  31. package/scripts/daemon/cadence-consumer.mjs +17 -0
  32. package/scripts/daemon/context-compiler.mjs +25 -0
  33. package/scripts/daemon/deliver.mjs +71 -5
  34. package/scripts/fleet/closing-sweep.mjs +266 -0
  35. package/scripts/healthcheck.sh +35 -0
  36. package/scripts/local-triggers/autoupdate.sh +61 -5
  37. package/scripts/maintenance/check-stamp-freshness.mjs +314 -0
  38. package/scripts/org/send-orgmail.mjs +112 -25
  39. package/scripts/session/supervisor.mjs +14 -0
@@ -0,0 +1,314 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * check-stamp-freshness.mjs
4
+ *
5
+ * Fails when a maintenance artefact's typed `generated:` stamp LEADS the file's
6
+ * own mtime — i.e. the record claims it was written at a time that had not yet
7
+ * happened — and, under --strict, when a stamp cannot witness same-day
8
+ * freshness at all (date-only, null or unparseable).
9
+ *
10
+ * Why this exists: an evening wrap once stamped six artefacts with a generation
11
+ * time it estimated from the volume of work done rather than read from the
12
+ * clock. Every stamp was in the future relative to its own write and the drift
13
+ * grew monotonically through the run (+8 min on the first index, +66 min on the
14
+ * last brief). The timezone conversion was correct in every row, so this was not
15
+ * a timezone bug. Because the error was self-consistent across all six files, no
16
+ * cross-artefact check could catch it. The only independent witness is the
17
+ * filesystem mtime — which nothing was comparing against.
18
+ *
19
+ * The asymmetry is deliberate: leading the mtime is always an error (a file
20
+ * cannot be authored after it was written), while lagging it is normal and
21
+ * expected — later edits touch mtime without regenerating content. So this
22
+ * checker is strict above the line and silent below it.
23
+ *
24
+ * Every target is named in exactly one bucket, and the classified total is
25
+ * asserted against the file total, so a bucket that fails to add up is a hard
26
+ * error rather than a quiet gap. The buckets:
27
+ *
28
+ * - OK precise stamp, at or behind its mtime.
29
+ * - LEAD stamp ahead of its mtime by more than the tolerance. Always FAIL.
30
+ * - COARSE date-only stamp (`generated: '2026-09-02'`). Parses to midnight
31
+ * UTC and therefore sits hours BEHIND its own mtime by construction,
32
+ * so it cannot witness the intra-day forward-dating this checker
33
+ * exists to catch. Not literally unfailable (a future DAY still
34
+ * trips) but blind to same-day errors. WEAK.
35
+ * - NULL the literal `generated: null` / `~` / empty. Scaffold writers seed
36
+ * this when they first create a file, so it means THE GENERATOR HAS
37
+ * NEVER RUN — a real finding, not "nothing to check". WEAK.
38
+ * - UNPARSEABLE present but not a date. WEAK.
39
+ * - ABSENT no `generated:` key at all (e.g. a file that uses `updated:`,
40
+ * machine-written every cycle). INFO only.
41
+ * - ALLOWED a NULL/ABSENT target the operator has declared a design state
42
+ * via --allow-null (a capability deliberately not run on this seat).
43
+ * Printed, never counted weak. The allowance is SELF-INVALIDATING:
44
+ * if a stamp ever appears, something is generating the file after
45
+ * all and it falls through to ordinary checking.
46
+ *
47
+ * Default mode gates LEAD only (exit 1) and reports WEAK as OK-WEAK (exit 0).
48
+ * --strict also gates the WEAK buckets: a stamp that cannot prove same-day
49
+ * freshness must not pass silently.
50
+ *
51
+ * A second class of typed stamp is detectable by SHAPE rather than by lead: every
52
+ * deterministic writer emits sub-second precision (12:00:28.851Z); a hand-typed
53
+ * time lands on a round minute with zero milliseconds. That shape survives any
54
+ * later write, whereas the mtime witness does not — once any tick rewrites the
55
+ * file its mtime moves past the stamp and a forward-dated value drops silently out
56
+ * of LEAD. Typed-shape stamps are REPORTED, NEVER GATED, in either mode: the shape
57
+ * proves the stamp was typed, not that it is stale, and failing a build on a proof
58
+ * gap rather than a staleness signal is the wrong trade.
59
+ *
60
+ * A queue-row pass applies the same mtime witness to `last_updated:` / `opened:` /
61
+ * `created:` / `resolved:` / `closed:` stamps inside state/queues/*.yaml, by regex
62
+ * over the raw text (no YAML dependency, stays fast over multi-MB files). Leads
63
+ * there FAIL in both modes; typed-shape rows are reported, never gated.
64
+ *
65
+ * OUT OF SCOPE, deliberately: stamps written inside JSON note fields. Those need a
66
+ * different reader and that tree may be under concurrent edit.
67
+ *
68
+ * Usage: node scripts/maintenance/check-stamp-freshness.mjs
69
+ * [--strict] [--tolerance-sec N] [--allow-null PATH]... [paths...]
70
+ * Exit: 0 all clear (or OK-WEAK in default mode),
71
+ * 1 a stamp leads its mtime, or --strict and a weak stamp,
72
+ * 2 usage/read error, or the classification did not account for every file.
73
+ */
74
+
75
+ import { readFileSync, statSync, existsSync } from 'node:fs';
76
+ import { readdirSync } from 'node:fs';
77
+
78
+ // Node 20 has no fs.globSync (it arrived in 22), and package.json engines says
79
+ // >=20, so expand the one pattern shape this file uses by hand: a literal
80
+ // directory, then a single '*' segment with an optional literal suffix.
81
+ function globSync(pattern) {
82
+ const slash = pattern.lastIndexOf('/');
83
+ const dir = slash === -1 ? '.' : pattern.slice(0, slash);
84
+ const leaf = pattern.slice(slash + 1);
85
+ const star = leaf.indexOf('*');
86
+ if (star === -1 || dir.includes('*')) throw new Error(`unsupported pattern ${pattern}`);
87
+ const prefix = leaf.slice(0, star), suffix = leaf.slice(star + 1);
88
+ let names;
89
+ try { names = readdirSync(dir); } catch { return []; }
90
+ return names
91
+ .filter((n) => n.startsWith(prefix) && n.endsWith(suffix) && n.length >= prefix.length + suffix.length)
92
+ .map((n) => (dir === '.' ? n : `${dir}/${n}`));
93
+ }
94
+
95
+ // tmp/ is excluded on purpose: those are pre-edit backups whose mtime is the COPY
96
+ // time, so their stamps legitimately lag by hours and would be pure noise.
97
+ const DEFAULT_TARGETS = [
98
+ 'state/dashboards/*.yaml',
99
+ 'state/indexes/*.yaml',
100
+ 'state/registers/*.yaml',
101
+ 'state/backlog/*.yaml',
102
+ 'memory/indexes/*.yaml',
103
+ 'knowledge/decisions/index.yaml',
104
+ ];
105
+
106
+ // A write takes a few seconds; allow for it. Anything beyond this is a typed guess.
107
+ const DEFAULT_TOLERANCE_SEC = 120;
108
+
109
+ const USAGE =
110
+ 'usage: check-stamp-freshness.mjs [--strict] [--tolerance-sec N] [--allow-null PATH]... [paths...]';
111
+
112
+ function parseArgs(argv) {
113
+ const out = { tolerance: DEFAULT_TOLERANCE_SEC, strict: false, targets: [], allowNull: new Set() };
114
+ for (let i = 0; i < argv.length; i++) {
115
+ const a = argv[i];
116
+ if (a === '--help' || a === '-h') { console.log(USAGE); process.exit(0); }
117
+ if (a === '--tolerance-sec') {
118
+ out.tolerance = Number(argv[++i]);
119
+ if (!Number.isFinite(out.tolerance) || out.tolerance < 0) { console.error(USAGE); process.exit(2); }
120
+ continue;
121
+ }
122
+ if (a === '--strict') { out.strict = true; continue; }
123
+ if (a === '--allow-null') {
124
+ const p = argv[++i];
125
+ if (!p) { console.error(USAGE); process.exit(2); }
126
+ out.allowNull.add(p);
127
+ continue;
128
+ }
129
+ if (a.startsWith('--')) { console.error(`unknown option ${a}\n${USAGE}`); process.exit(2); }
130
+ out.targets.push(a);
131
+ }
132
+ if (!out.targets.length) out.targets = DEFAULT_TARGETS;
133
+ return out;
134
+ }
135
+
136
+ /**
137
+ * Classify the `generated:` scalar without a YAML parse — these files must stay
138
+ * checkable even when malformed. Returns a KIND rather than a bare value, so the
139
+ * caller can tell "absent", "null", "garbage" and "imprecise" apart.
140
+ */
141
+ function readStamp(text) {
142
+ const m = text.match(/^generated: *(.*?) *$/m);
143
+ if (!m) return { kind: 'ABSENT' };
144
+
145
+ const raw = m[1].replace(/^['"]|['"]$/g, '').trim();
146
+ if (raw === '' || raw === 'null' || raw === '~') return { kind: 'NULL', raw: m[1].trim() };
147
+
148
+ const d = new Date(raw);
149
+ if (Number.isNaN(d.getTime())) return { kind: 'UNPARSEABLE', raw };
150
+
151
+ // No time-of-day component: parses to midnight UTC, so it cannot witness
152
+ // same-day forward-dating even though it is a valid date.
153
+ if (/^\d{4}-\d{2}-\d{2}$/.test(raw)) return { kind: 'COARSE', raw, date: d };
154
+
155
+ return { kind: 'PRECISE', raw, date: d };
156
+ }
157
+
158
+ const { tolerance, strict, targets, allowNull } = parseArgs(process.argv.slice(2));
159
+
160
+ let files = [];
161
+ for (const t of targets) {
162
+ try {
163
+ files.push(...(t.includes('*') ? globSync(t) : existsSync(t) ? [t] : []));
164
+ } catch (e) {
165
+ console.error(`cannot expand ${t}: ${e.message}`);
166
+ process.exit(2);
167
+ }
168
+ }
169
+ files = [...new Set(files)].sort();
170
+
171
+ if (!files.length) {
172
+ console.error('no files matched');
173
+ process.exit(2);
174
+ }
175
+
176
+ const buckets = { OK: [], LEAD: [], NULL: [], UNPARSEABLE: [], COARSE: [], ABSENT: [], ALLOWED: [] };
177
+
178
+ for (const f of files) {
179
+ let text, st;
180
+ try { text = readFileSync(f, 'utf8'); st = statSync(f); }
181
+ catch (e) { console.error(`cannot read ${f}: ${e.message}`); process.exit(2); }
182
+
183
+ const stamp = readStamp(text);
184
+
185
+ if (allowNull.has(f) && (stamp.kind === 'NULL' || stamp.kind === 'ABSENT')) {
186
+ buckets.ALLOWED.push({ file: f, raw: stamp.raw ?? '(no key)' });
187
+ continue;
188
+ }
189
+
190
+ if (stamp.kind === 'ABSENT' || stamp.kind === 'NULL' || stamp.kind === 'UNPARSEABLE') {
191
+ buckets[stamp.kind].push({ file: f, raw: stamp.raw });
192
+ continue;
193
+ }
194
+
195
+ const leadSec = (stamp.date.getTime() - st.mtime.getTime()) / 1000;
196
+ const row = {
197
+ file: f, stamp: stamp.raw, mtime: st.mtime.toISOString(),
198
+ leadMin: (leadSec / 60).toFixed(1),
199
+ };
200
+
201
+ // A lead is an error regardless of precision — a date-only stamp naming a future
202
+ // day is still a stamp ahead of its own write.
203
+ if (leadSec > tolerance) buckets.LEAD.push(row);
204
+ else if (stamp.kind === 'COARSE') buckets.COARSE.push(row);
205
+ else buckets.OK.push(row);
206
+ }
207
+
208
+ // Assert the classification adds up, so a bucket that swallows a file is a hard
209
+ // error rather than a quiet gap.
210
+ const classified = Object.values(buckets).reduce((n, b) => n + b.length, 0);
211
+ if (classified !== files.length) {
212
+ console.error(`INTERNAL: classified ${classified} of ${files.length} files — a bucket is dropping rows`);
213
+ process.exit(2);
214
+ }
215
+
216
+ for (const x of buckets.LEAD) {
217
+ console.error(`FAIL ${x.file}`);
218
+ console.error(` generated: ${x.stamp} leads mtime ${x.mtime} by ${x.leadMin} min`);
219
+ }
220
+ for (const x of buckets.NULL) {
221
+ console.error(`WEAK ${x.file}`);
222
+ console.error(` generated: ${x.raw} — generator has never run; stamp is an unfilled scaffold seed`);
223
+ }
224
+ for (const x of buckets.UNPARSEABLE) {
225
+ console.error(`WEAK ${x.file}`);
226
+ console.error(` generated: ${x.raw} — present but not a date; cannot be checked`);
227
+ }
228
+ for (const x of buckets.COARSE) {
229
+ console.error(`WEAK ${x.file}`);
230
+ console.error(` generated: ${x.stamp} — date-only, parses to midnight UTC and sits ${Math.abs(x.leadMin)} min behind mtime; cannot witness same-day freshness`);
231
+ }
232
+ for (const x of buckets.ALLOWED) {
233
+ console.error(`INFO ${x.file} — generated: ${x.raw}, NOT COUNTED WEAK: allowed by --allow-null (generator deliberately not run here)`);
234
+ }
235
+ for (const x of buckets.ABSENT) {
236
+ console.error(`INFO ${x.file} — no generated: key`);
237
+ }
238
+
239
+ // Typed-shape stamps: round minute, zero milliseconds. Reported, never gated.
240
+ const TYPED_SHAPE = /T\d{2}:\d{2}:00\.000Z$/;
241
+ const typed = [...buckets.LEAD, ...buckets.COARSE, ...buckets.OK].filter((x) => TYPED_SHAPE.test(x.stamp));
242
+ for (const x of typed) {
243
+ console.error(
244
+ `INFO ${x.file} — generated: ${x.stamp} is a round minute with zero ms (typed, not clock-read)` +
245
+ (buckets.LEAD.includes(x)
246
+ ? '; witnessed above as a lead'
247
+ : '; mtime has moved since, so no lead can be proven either way')
248
+ );
249
+ }
250
+
251
+ // ---------------------------------------------------------------------------
252
+ // QUEUE-ROW PASS. A queue row cannot legitimately claim to have been updated after
253
+ // the file that contains it was last written, so file mtime is the same witness
254
+ // used above. Note the typed shape here covers both `T08:45:00Z` (no millisecond
255
+ // field) and `T08:45:00.000Z`.
256
+ const QUEUE_GLOB = 'state/queues/*.yaml';
257
+ const QUEUE_STAMP_KEY = /^\s+(last_updated|opened|created|resolved|closed): *(.+?) *$/;
258
+ const QUEUE_ROW_ID = /^\s*- id: *(.+?) *$/;
259
+ const QUEUE_TYPED_SHAPE = /T\d{2}:\d{2}:00(\.000)?Z$/;
260
+ const queueLeads = [];
261
+ const queueTyped = [];
262
+ let queueRowsChecked = 0;
263
+ let queueFilesChecked = 0;
264
+ for (const qp of globSync(QUEUE_GLOB).sort()) {
265
+ let text;
266
+ try { text = readFileSync(qp, 'utf8'); } catch { continue; }
267
+ const mtime = statSync(qp).mtime.getTime();
268
+ queueFilesChecked++;
269
+ let currentId = '(before first row)';
270
+ for (const line of text.split('\n')) {
271
+ const idm = line.match(QUEUE_ROW_ID);
272
+ if (idm) { currentId = idm[1]; continue; }
273
+ const m = line.match(QUEUE_STAMP_KEY);
274
+ if (!m) continue;
275
+ const raw = m[2].replace(/^['"]|['"]$/g, '').trim();
276
+ // Date-only values carry no intra-day information; skip rather than guess.
277
+ if (!/T\d{2}:\d{2}/.test(raw)) continue;
278
+ const t = Date.parse(raw);
279
+ if (Number.isNaN(t)) continue;
280
+ queueRowsChecked++;
281
+ const leadSec = (t - mtime) / 1000;
282
+ if (leadSec > tolerance) queueLeads.push({ file: qp, id: currentId, key: m[1], stamp: raw, leadSec });
283
+ if (QUEUE_TYPED_SHAPE.test(raw)) queueTyped.push({ file: qp, id: currentId, key: m[1], stamp: raw });
284
+ }
285
+ }
286
+ for (const x of queueLeads) {
287
+ console.error(
288
+ `LEAD ${x.file} :: ${x.id} — ${x.key}: ${x.stamp} is ` +
289
+ `${(x.leadSec / 60).toFixed(1)} min AHEAD of that file's own mtime`
290
+ );
291
+ }
292
+ if (queueTyped.length) {
293
+ console.error(
294
+ `INFO ${queueTyped.length} queue row stamp(s) carry the typed shape (round minute, zero or absent ms) — ` +
295
+ 'reported, not gated in either mode'
296
+ );
297
+ }
298
+
299
+ const weak = buckets.NULL.length + buckets.UNPARSEABLE.length + buckets.COARSE.length;
300
+ const leads = buckets.LEAD.length + queueLeads.length;
301
+ const failed = leads + (strict ? weak : 0);
302
+ const verdict = leads ? 'FAIL' : weak && strict ? 'FAIL' : weak ? 'OK-WEAK' : 'OK';
303
+
304
+ console.log(
305
+ `${verdict}: ${files.length} target(s) — ${buckets.OK.length} checkable and clean, ` +
306
+ `${buckets.LEAD.length} ahead of their own mtime, ${buckets.COARSE.length} date-only (cannot witness same-day freshness), ` +
307
+ `${buckets.NULL.length} never generated, ${buckets.UNPARSEABLE.length} unparseable, ${buckets.ABSENT.length} unstamped, ` +
308
+ `${buckets.ALLOWED.length} allowed null(s) excluded from weak, ` +
309
+ `${typed.length} typed-shape (round-minute .000Z, not gated) ` +
310
+ `| queue rows: ${queueRowsChecked} stamp(s) over ${queueFilesChecked} file(s), ` +
311
+ `${queueLeads.length} ahead of their own mtime, ${queueTyped.length} typed-shape ` +
312
+ `(tolerance ${tolerance}s${strict ? ', strict' : ''})`
313
+ );
314
+ process.exit(failed ? 1 : 0);
@@ -50,10 +50,6 @@ import { call, approvalWait } from "../../lib/org/client.mjs";
50
50
  import { resolveOrgToolConfig } from "../../lib/org/tool-surface.mjs";
51
51
  import { applyBrandEnvCompat } from "../../lib/env-compat.mjs";
52
52
 
53
- // Fleet back-compat FIRST: bridge NEOLITH_* ⇄ COHORT_* env names before the
54
- // env-first credential resolution (COHORT_API_TOKEN et al.) kicks in.
55
- applyBrandEnvCompat();
56
-
57
53
  function parseArgs(argv) {
58
54
  const flags = { to: [], cc: [], bcc: [] };
59
55
  for (let i = 0; i < argv.length; i += 1) {
@@ -88,7 +84,30 @@ function usage() {
88
84
  }
89
85
 
90
86
  /**
91
- * Belt-and-braces local screen; the server guardrails stay authoritative.
87
+ * The local screen — the same send-gate every other outbound lane runs, and
88
+ * FAIL-CLOSED. The server guardrails stay authoritative for what they cover;
89
+ * they do not cover what this gate covers (persona leaks, machine internals,
90
+ * scaffold markers, the retired register), so this is not belt-and-braces.
91
+ *
92
+ * ── WHY A GATE THAT CANNOT LOAD IS A REFUSAL ────────────────────────────────
93
+ *
94
+ * This used to `catch { return text; }` around the whole screen: a send-gate
95
+ * that failed to import, or threw, meant the body went out unscreened on "the
96
+ * server guardrails still apply". That made this CLI the one outbound lane a
97
+ * direct invocation could take past the gate — `lib/org/messaging.mjs` fails
98
+ * closed on a gate fault ("never send what we could not screen"), and so does
99
+ * `deliver()`. A send this lane cannot screen is now a send it does not make,
100
+ * with the reason on stderr and a no-send row on this seat's ledger.
101
+ *
102
+ * RESULTS, NOT THROWS. Returns `{ok:true, text}` or `{ok:false, code, reason}`
103
+ * with `code` one of:
104
+ * BLOCKED the gate refused the body (its reason names the rule and
105
+ * the span — rewrite and send again)
106
+ * GATE_UNAVAILABLE the gate module would not load, or exports no screen
107
+ * GATE_ERROR the screen itself threw
108
+ * so the caller decides the exit and the test drives every branch without a
109
+ * process exit. `deps.loadGate` is the test seam for the import; production
110
+ * never passes it.
92
111
  *
93
112
  * `firstContact` MUST be passed. `screenOutbound` defaults it to TRUE, and under
94
113
  * the `disclose-always` posture that limb is an outright block for any body that
@@ -104,27 +123,82 @@ function usage() {
104
123
  * (`--reply-to-message`) is by construction NOT first contact. A bare `--to` is,
105
124
  * and still blocks — that limb is left exactly as it was.
106
125
  */
107
- async function screenLocally(text, recipients, agentRoot, firstContact) {
126
+ export async function screenLocally(text, recipients, agentRoot, firstContact, deps = {}) {
127
+ const errText = (err) => (err && err.message ? err.message : String(err));
128
+ let screenOutbound;
108
129
  try {
109
- const { screenOutbound } = await import("../../lib/comms/send-gate.mjs");
110
- const verdict = await screenOutbound({
130
+ const load = typeof deps.loadGate === "function" ? deps.loadGate : () => import("../../lib/comms/send-gate.mjs");
131
+ ({ screenOutbound } = await load());
132
+ } catch (err) {
133
+ return { ok: false, code: "GATE_UNAVAILABLE", reason: `the outbound send-gate could not be loaded (${errText(err)}) — nothing was sent: this lane does not send what it cannot screen` };
134
+ }
135
+ if (typeof screenOutbound !== "function") {
136
+ return { ok: false, code: "GATE_UNAVAILABLE", reason: "the outbound send-gate module exports no screenOutbound — nothing was sent: this lane does not send what it cannot screen" };
137
+ }
138
+ let verdict;
139
+ try {
140
+ verdict = await screenOutbound({
111
141
  channel: "orgmail",
112
142
  recipient: recipients.join(",") || "(thread)",
113
143
  text,
114
144
  agentRoot,
115
145
  firstContact,
116
146
  });
117
- if (verdict && verdict.allow === false) {
118
- console.error(`send-orgmail: BLOCKED by the outbound send-gate — ${verdict.reason || "policy"}`);
119
- process.exit(1);
120
- }
121
- return typeof verdict?.redactedText === "string" ? verdict.redactedText : text;
122
- } catch {
123
- return text; // gate unavailable → server guardrails still apply
147
+ } catch (err) {
148
+ return { ok: false, code: "GATE_ERROR", reason: `the outbound send-gate failed while screening (${errText(err)}) — nothing was sent` };
124
149
  }
150
+ // `allow !== true`, not `allow === false`: a verdict that does not say "allow"
151
+ // has not allowed anything.
152
+ if (!verdict || verdict.allow !== true) {
153
+ return {
154
+ ok: false,
155
+ code: "BLOCKED",
156
+ reason: (verdict && verdict.reason) || "policy",
157
+ ...(verdict && verdict.rule ? { rule: verdict.rule, match: verdict.match } : {}),
158
+ };
159
+ }
160
+ return { ok: true, text: typeof verdict.redactedText === "string" ? verdict.redactedText : text };
161
+ }
162
+
163
+ /**
164
+ * A refusal from `screenLocally`, made loud and durable: the reason on stderr,
165
+ * and a no-send row on THIS seat's ledger (the seat whose body was refused),
166
+ * keyed the way `tool-surface.executeOrgTool` keys its own refusals, so the
167
+ * daemon that spawned the session records "the send was refused" rather than
168
+ * an unexplained silence. Never throws; the bookkeeping cannot change the exit.
169
+ *
170
+ * @param {{code:string, reason:string}} refusal
171
+ * @param {{channel:string, agentRoot:string}} where
172
+ */
173
+ async function reportRefusal(refusal, where) {
174
+ console.error(`send-orgmail: BLOCKED (${refusal.code}) — ${refusal.reason}`);
175
+ if (refusal.code === "BLOCKED") {
176
+ console.error("send-orgmail: nothing was sent and nothing was edited. Rewrite the body to clear the stated rule and run this again.");
177
+ }
178
+ try {
179
+ const { recordNoSend } = await import("../../lib/comms/receipts.mjs");
180
+ recordNoSend({
181
+ decision: "refused",
182
+ service: "orgmail",
183
+ channel: where.channel,
184
+ code: refusal.code === "BLOCKED" ? "CONTENT_POLICY" : refusal.code,
185
+ reason: refusal.reason,
186
+ surface: "session",
187
+ // A content verdict clears on a rewrite and an unloadable gate on a fix,
188
+ // so neither is final — calling it permanent is how a fixable refusal
189
+ // becomes a final apology.
190
+ permanent: false,
191
+ agentRoot: where.agentRoot,
192
+ });
193
+ } catch { /* bookkeeping must never change a refusal into anything else */ }
125
194
  }
126
195
 
127
196
  async function main() {
197
+ // Fleet back-compat FIRST: bridge NEOLITH_* ⇄ COHORT_* env names before the
198
+ // env-first credential resolution (COHORT_API_TOKEN et al.) kicks in. Inside
199
+ // main, not at module scope, so a test can import `screenLocally` without
200
+ // this mutating its environment.
201
+ applyBrandEnvCompat();
128
202
  const flags = parseArgs(process.argv.slice(2));
129
203
  if (flags.help) { usage(); process.exit(0); }
130
204
 
@@ -141,20 +215,29 @@ async function main() {
141
215
  }
142
216
 
143
217
  const cfg = resolveOrgToolConfig({});
144
- if (!cfg.token || !cfg.base) {
145
- console.error("send-orgmail: no org credential — set COHORT_API_TOKEN or run `cohort setup --only org`");
146
- process.exit(1);
147
- }
148
- const o = { base: cfg.base, token: cfg.token, orgId: cfg.orgId };
149
218
 
219
+ // THE SCREEN RUNS BEFORE THE CREDENTIAL CHECK, as in `lib/org/messaging.mjs`:
220
+ // a body the gate refuses is refused on every seat, enrolled or not, and the
221
+ // sender hears the rule rather than an unrelated configuration error.
150
222
  // Not first contact when we are replying into an existing thread or message.
151
223
  const isFirstContact = !flags.thread && !flags.replyToMessageId;
152
- const text = await screenLocally(
224
+ const screened = await screenLocally(
153
225
  String(body),
154
226
  [...flags.to, ...flags.cc, ...flags.bcc],
155
227
  cfg.agentRoot,
156
228
  isFirstContact,
157
229
  );
230
+ if (!screened.ok) {
231
+ await reportRefusal(screened, { channel: flags.thread || flags.to[0] || flags.replyToMessageId, agentRoot: cfg.agentRoot });
232
+ process.exit(1);
233
+ }
234
+ const text = screened.text;
235
+
236
+ if (!cfg.token || !cfg.base) {
237
+ console.error("send-orgmail: no org credential — set COHORT_API_TOKEN or run `cohort setup --only org`");
238
+ process.exit(1);
239
+ }
240
+ const o = { base: cfg.base, token: cfg.token, orgId: cfg.orgId };
158
241
 
159
242
  // ONE business id per invocation; hq dedups on (mailbox, idempotencyId).
160
243
  const idempotencyId = randomUUID();
@@ -261,7 +344,11 @@ async function main() {
261
344
  process.exit(1);
262
345
  }
263
346
 
264
- main().catch((err) => {
265
- console.error(`send-orgmail: ${err && err.message ? err.message : err}`);
266
- process.exit(1);
267
- });
347
+ // Run as a CLI only when invoked directly, so a test can import `screenLocally`
348
+ // (the same guard `send-cohort-message.mjs` uses).
349
+ if (process.argv[1] && process.argv[1].endsWith("send-orgmail.mjs")) {
350
+ main().catch((err) => {
351
+ console.error(`send-orgmail: ${err && err.message ? err.message : err}`);
352
+ process.exit(1);
353
+ });
354
+ }
@@ -453,6 +453,20 @@ export async function runSupervisor(deps = {}) {
453
453
  }
454
454
  }
455
455
  }
456
+ // 4d. A restart requested via `maestro session restart` is honoured by
457
+ // THIS launch: whatever process the directive reached has already
458
+ // exited (or the job was bounced outright), and this launch is the
459
+ // relaunch it asked for. Retire the marker, so `maestro session
460
+ // status` stops reporting "restart requested" for a restart that has
461
+ // already happened — left in place, it never clears on its own.
462
+ {
463
+ let restartRequested = false;
464
+ try { d.readFileSync(paths.restartRequestedFile, "utf8"); restartRequested = true; } catch { restartRequested = false; }
465
+ if (restartRequested) {
466
+ try { d.unlinkSync(paths.restartRequestedFile); d.log("restart requested honoured by this launch; marker retired"); }
467
+ catch (e) { d.log(`restart requested honoured but not retired: ${e && e.message ? e.message : e}`); }
468
+ }
469
+ }
456
470
  const launched = recordLaunch(record, { now: d.now });
457
471
  const saved = saveMainSession(agentRoot, launched, fsDeps);
458
472
  if (!saved.ok) d.log(`main-session.json not saved: ${saved.error}`);