@cohortapp/agent-sdk 2.18.25 → 2.18.28

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.
@@ -55,7 +55,7 @@ import { appendFileSync, mkdirSync, readdirSync, readFileSync, renameSync, unlin
55
55
  import { spawn } from "child_process";
56
56
  import { join } from "path";
57
57
  import { deliver, deliverWithRetry, replyTargetOf, canDeliverTo, canReactTo, deliverReaction } from "./deliver.mjs";
58
- import { spokeFor, spokeSince, NON_ANSWER_KINDS } from "../../lib/comms/receipts.mjs";
58
+ import { spokeFor, spokeSince, noSendFor, NON_ANSWER_KINDS } from "../../lib/comms/receipts.mjs";
59
59
  import { resultTextFromStdout } from "./session-outcomes.mjs";
60
60
  // The ack generator funnels through `claude --print` like every other daemon
61
61
  // model call (CEO directive 2026-04-27: no direct Anthropic API from the
@@ -98,7 +98,7 @@ import {
98
98
  noticeRejection,
99
99
  fallbackNotice,
100
100
  } from "../../lib/assurance/notice-voice.mjs";
101
- import { isRetiredFirstReply, firstReplyShape, REACTIONS, isAlreadyAnsweredElsewhere } from "../../lib/assurance/first-reply.mjs";
101
+ import { isRetiredFirstReply, firstReplyShape, REACTIONS, statesNoReplyOwed } from "../../lib/assurance/first-reply.mjs";
102
102
  // The unit of acknowledgement is the CONVERSATION, not the message: four
103
103
  // messages in a row earn ONE first response that was written with all four in
104
104
  // front of it. `groupIntoBatches` + `batchVerdict` decide WHEN and WHICH;
@@ -592,9 +592,21 @@ export function narratorPatterns() {
592
592
  composeInterrupted(), // "Heads up — my session on this was interrupted …"
593
593
  composeSilentSuccess({}, {}), // terminal notice, no result text
594
594
  composeSilentSuccess({}, { finalText: CAUSE }), // terminal notice + excerpt
595
+ // composeRefusedSend, all four shapes. It is a NARRATOR message like the
596
+ // rest — if this gate cannot recognise it, a peer's refusal notice arrives
597
+ // as an ordinary ask, earns an ack and spawns a session behind it, which is
598
+ // the loop that produced 142 of 188 notices on 2026-09-30.
599
+ composeRefusedSend({}, { why: { code: CAUSE, permanent: true } }),
600
+ composeRefusedSend({}, { why: { code: CAUSE, permanent: false } }),
601
+ composeRefusedSend({}, { why: { code: CAUSE, permanent: true }, finalText: CAUSE }),
602
+ composeRefusedSend({}, { why: { code: CAUSE, permanent: false }, finalText: CAUSE }),
595
603
  ];
604
+ // GLOBAL, not first-occurrence. `String.prototype.replace` with a string
605
+ // pattern substitutes once, so a template carrying the sentinel twice — a
606
+ // cause AND an excerpt, which composeRefusedSend does — kept a literal
607
+ // "@@CAUSE@@" in its second slot and could then never match real output.
596
608
  _narratorPatterns = templates.map((t) =>
597
- new RegExp(`^${esc(t).replace(/\d+/g, "\\d+").replace(esc(CAUSE), "[\\s\\S]+?")}$`),
609
+ new RegExp(`^${esc(t).replace(/\d+/g, "\\d+").split(esc(CAUSE)).join("[\\s\\S]+?")}$`),
598
610
  );
599
611
  return _narratorPatterns;
600
612
  }
@@ -1302,6 +1314,60 @@ export function composeSilentSuccess(rec, o = {}) {
1302
1314
  return `${head} I don't have a clean result to show you, though. Want me to run it again?`;
1303
1315
  }
1304
1316
 
1317
+ /**
1318
+ * The case `composeSilentSuccess` was apologising for by mistake: a send that
1319
+ * WAS attempted and was STOPPED, with a recorded cause.
1320
+ *
1321
+ * ── WHY A SEPARATE COMPOSER RATHER THAN A BETTER SENTENCE ────────────────────
1322
+ *
1323
+ * "Finished this but didn't get a reply out to you — my fault" was the only
1324
+ * thing this module could say about `heard === false`, because the absence of a
1325
+ * delivery receipt was the only evidence it had. That absence has three causes
1326
+ * and they want three different sentences:
1327
+ *
1328
+ * refused something tried to send and was blocked — the outbound gate, an
1329
+ * ACL, a transport error, a pre-tool hook with no fallback lane.
1330
+ * The work is done, the human has nothing, and the CAUSE is the
1331
+ * one fact worth saying. This composer.
1332
+ * declined nothing tried, because nothing was owed. Say nothing at all;
1333
+ * `settleSession` closes quietly and never reaches a composer.
1334
+ * unexplained no row on file. `composeSilentSuccess` — and only here is "my
1335
+ * fault" the honest word, because we genuinely do not know.
1336
+ *
1337
+ * The cause is quoted from the no-send row, which `recordNoSend` bounds to 300
1338
+ * characters and which is documented never to carry the message body. The head
1339
+ * is a FROZEN LITERAL in `first-reply.STATUS_NOTICE_PATTERNS`: a notice this
1340
+ * seat emits that a receiving seat cannot recognise gets dispatched to that seat
1341
+ * as an ordinary ask, and on 2026-09-30 that loop produced 142 of one day's 188
1342
+ * notices. Emitter and recogniser are edited together or not at all.
1343
+ *
1344
+ * @param {object} rec
1345
+ * @param {object} [o] `{why, finalText}` — `why` is a `noSendFor` verdict
1346
+ * @returns {string}
1347
+ */
1348
+ export function composeRefusedSend(rec, o = {}) {
1349
+ const why = o.why || {};
1350
+ const code = why.code ? String(why.code).trim() : "";
1351
+ const reason = why.reason ? String(why.reason).trim() : "";
1352
+ // The code alone is machine noise to a human, and the reason alone loses the
1353
+ // handle an operator greps for. Both when both exist, whichever when one does.
1354
+ const cause = code && reason && !reason.startsWith(code) ? `${code}: ${reason}` : reason || code;
1355
+ const head = `Couldn't get this out to you — the send was blocked${cause ? ` (${cause})` : ""}.`;
1356
+ // Never promise a retry this path does not perform. The silent-success branch
1357
+ // has no retry loop — that lives in the failure branch — so a permanent cause
1358
+ // says so and a transient one offers, rather than asserting, another attempt.
1359
+ const next = why.permanent
1360
+ ? ` That won't clear on its own.`
1361
+ : ` Say the word and I'll try again.`;
1362
+ const tail = (o.finalText || "").trim();
1363
+ if (!tail) return `${head}${next}`;
1364
+ const excerpt =
1365
+ tail.length > SILENT_SUCCESS_EXCERPT_LIMIT
1366
+ ? `${tail.slice(0, SILENT_SUCCESS_EXCERPT_LIMIT).trimEnd()}…\n\n(That's the first ${SILENT_SUCCESS_EXCERPT_LIMIT} of ${tail.length} characters — the rest is in my session log; say the word and I'll resend the full tail.)`
1367
+ : tail;
1368
+ return `${head}${next} Here's what I have:\n\n${excerpt}`;
1369
+ }
1370
+
1305
1371
  /**
1306
1372
  * Is this obligation's surface AMBIENT rather than a 1:1 the requester waits on?
1307
1373
  *
@@ -1959,6 +2025,73 @@ export async function settleSession(a = {}) {
1959
2025
  }
1960
2026
 
1961
2027
  if (a.ok && !heard) {
2028
+ // ── WHY NOTHING WENT OUT, WHEN ANYONE BOTHERED TO SAY ────────────────────
2029
+ //
2030
+ // This is the branch that produced 188 recovery notices into the org in one
2031
+ // day (2026-09-30). `heard === false` was read as one thing — "the session
2032
+ // finished and its reply never sent, apologise and dump the result into the
2033
+ // room" — and it is three things. The absence of a delivery receipt cannot
2034
+ // tell them apart and no cleverness here will make it; so whoever decides
2035
+ // now RECORDS the decision (`recordNoSend`, from the session plane via
2036
+ // `tool-surface`/`record-no-send.sh` and from this plane via `deliver`), and
2037
+ // this is the reader:
2038
+ //
2039
+ // declined a turn decided no reply was owed. Close quietly, say
2040
+ // NOTHING. Measured on 2026-09-30: of the 46 seed notices that
2041
+ // day, 32 carried the session's own words saying exactly this
2042
+ // ("Logged and archived — no response needed"). Every one of
2043
+ // those 32 was an apology for the design working.
2044
+ // refused something tried to send and was blocked, with a cause on
2045
+ // file. Name the cause — that is the only fact that lets
2046
+ // anyone fix it. Four notices in the 09-29/30 window named
2047
+ // their own blocked lane in prose because they had no other
2048
+ // way to report it.
2049
+ // no row genuinely unexplained. This is the only case "my fault" was
2050
+ // ever the honest word, and it keeps the old behaviour
2051
+ // unchanged — including for every seat that has not upgraded,
2052
+ // which writes no rows at all.
2053
+ //
2054
+ // FAILS OPEN TO THE OLD BEHAVIOUR. A null verdict, a thrown reader, a
2055
+ // corrupt ledger line: all of them land on `composeSilentSuccess`, because
2056
+ // one redundant notice beats a silently dropped answer. That is the same
2057
+ // bias `spokeFor` carries and the reason this module exists.
2058
+ const noSeen = (a.deps && a.deps.noSendForImpl) || noSendFor;
2059
+ let why = null;
2060
+ try {
2061
+ why = noSeen({ obligation: rec, now, agentRoot: AGENT_REPO_DIR });
2062
+ } catch { why = null; }
2063
+ if (why && why.decision === "declined") {
2064
+ closeObligation(a.key, {
2065
+ outcome: "answered",
2066
+ now,
2067
+ note: `session exited 0 and recorded a deliberate decline${why.reason ? `: ${why.reason}` : ""}`,
2068
+ });
2069
+ counters.bump("assurance.no_send_declined", { service: rec.service });
2070
+ return { spoke: false, text: null, verdict: "declined-no-reply-owed", willRetry: false, noSend: why };
2071
+ }
2072
+ if (why && why.decision === "refused") {
2073
+ // A refusal is a FAULT and it is told even on an ambient surface: the
2074
+ // ambient guard below exists to stop result text being NARRATED into a
2075
+ // shared room when nobody asked, and this is not narration — it is the
2076
+ // one line that says a message this seat owed was stopped, plus its cause.
2077
+ // Withholding it is how a blocked send lane stays invisible for days.
2078
+ const finalText = safeResultText(a.stdout);
2079
+ const text = composeRefusedSend(rec, { why, finalText });
2080
+ const res = await send(item, text, {
2081
+ kind: "reply",
2082
+ idempotencySuffix: `refused-${rec.attempts || 0}`,
2083
+ obligationKey: rec.key,
2084
+ sessionId: rec.sessionId,
2085
+ });
2086
+ closeObligation(a.key, {
2087
+ outcome: res && res.sent ? "answered" : "undeliverable",
2088
+ now,
2089
+ note: `send refused (${why.code || "no code"}${why.surface ? ` on ${why.surface}` : ""}); ${res && res.sent ? "cause reported to the room" : `cause also undeliverable: ${res && res.error}`}`,
2090
+ });
2091
+ counters.bump("assurance.no_send_refused", { service: rec.service, code: why.code || "none" });
2092
+ return { spoke: !!(res && res.sent), text, verdict: "send-refused", willRetry: false, noSend: why };
2093
+ }
2094
+
1962
2095
  // A CLEAN SILENT EXIT OUTSIDE A DM CLOSES QUIETLY, LIKE A DOC COMMENT.
1963
2096
  // The rescue message exists to hand a waiting requester the result their
1964
2097
  // session produced but never sent. On an ambient/membership-proved surface
@@ -1983,7 +2116,8 @@ export async function settleSession(a = {}) {
1983
2116
  //
1984
2117
  // This rescue reads "exited 0 having sent nothing" as one state — the
1985
2118
  // answer got stuck on the way out. There are two, and the second is a
1986
- // session that recognised the item as one it had ALREADY replied to.
2119
+ // session that judged nothing was owed in reply and said so. 40 such posts
2120
+ // across seven seats in the 48h to 2026-10-01.
1987
2121
  // Publishing that one posts the seat's own reasoning into a room, addressed
1988
2122
  // to nobody. Measured on 2026-09-30 18:21:49Z, one seat into a shared
1989
2123
  // engineering channel: "Archived — this is a duplicate delivery of the same
@@ -1996,18 +2130,26 @@ export async function settleSession(a = {}) {
1996
2130
  // discharged, not abandoned; only the narration is withheld. Same shape as
1997
2131
  // the ambient-surface branch above, and a distinct note + counter so the
1998
2132
  // difference stays visible to an operator sweeping outcomes.
1999
- if (isAlreadyAnsweredElsewhere(finalText)) {
2133
+ if (statesNoReplyOwed(finalText)) {
2000
2134
  closeObligation(a.key, {
2001
2135
  outcome: "answered",
2002
2136
  now,
2003
- note: "session exited 0 stating it had already answered this item; second narration withheld",
2137
+ note: "session exited 0 stating no reply was owed; narration withheld",
2004
2138
  });
2005
- counters.bump("assurance.silent_success_already_answered", { service: rec.service });
2139
+ counters.bump("assurance.silent_success_no_reply_owed", { service: rec.service });
2006
2140
  return { spoke: false, text: null, verdict: "silent-success", willRetry: false };
2007
2141
  }
2008
2142
 
2009
2143
  const text = composeSilentSuccess(rec, { finalText });
2010
- const res = await send(item, text, { kind: "reply", idempotencySuffix: `rescue-${rec.attempts || 0}` });
2144
+ const res = await send(item, text, {
2145
+ kind: "reply",
2146
+ idempotencySuffix: `rescue-${rec.attempts || 0}`,
2147
+ // So a refusal of the RESCUE itself lands attributed. `deliver.noteNoSend`
2148
+ // cannot sniff this from the environment — the dispatcher stamps
2149
+ // MAESTRO_OBLIGATION_KEY on the spawned child, not on this daemon.
2150
+ obligationKey: rec.key,
2151
+ sessionId: rec.sessionId,
2152
+ });
2011
2153
  closeObligation(a.key, {
2012
2154
  outcome: res && res.sent ? "answered" : "undeliverable",
2013
2155
  now,
@@ -2783,6 +2925,7 @@ export default {
2783
2925
  noticeGenEnabled,
2784
2926
  _buildAckUserPromptForTest: buildAckUserPrompt,
2785
2927
  composeSilentSuccess,
2928
+ composeRefusedSend,
2786
2929
  composeInterrupted,
2787
2930
  looksLikePeerOutcomeNotice,
2788
2931
  classifyFailure,
@@ -30,12 +30,12 @@ import { mkdirSync, writeFileSync } from "fs";
30
30
  import { join } from "path";
31
31
  import { screenOutbound } from "../../lib/comms/send-gate.mjs";
32
32
  import { getHookBus } from "../../lib/hooks/bus.mjs";
33
- import { recordOutbound } from "../../lib/comms/receipts.mjs";
33
+ import { recordNoSend, recordOutbound } from "../../lib/comms/receipts.mjs";
34
34
  // Pure data (a frozen table, no imports of its own) — the surface vocabulary the
35
35
  // inbound projection stamps into `raw_ref`. Imported rather than re-listed so a
36
36
  // new surface cannot be added upstream without this file's switch noticing.
37
37
  import { ROOM_SURFACES, SURFACE_NAMES } from "../../lib/org/inbound/surfaces.mjs";
38
- import { isRetiredFirstReply } from "../../lib/assurance/first-reply.mjs";
38
+ import { isAgentStatusNotice, isRetiredFirstReply } from "../../lib/assurance/first-reply.mjs";
39
39
 
40
40
  const AGENT_REPO_DIR = process.env.AGENT_DIR || join(new URL(".", import.meta.url).pathname, "../..");
41
41
 
@@ -770,6 +770,42 @@ const REPLY_FILLER_OPENERS = [
770
770
  */
771
771
  export function stripReplyFiller(text) {
772
772
  if (typeof text !== "string") return text;
773
+ // ── THE DAEMON'S OWN NOTICES ARE EXEMPT, AND THIS IS NOT A COURTESY ───────
774
+ // FIX 2 was written for SESSION-authored answers that happened to open with a
775
+ // flush apology: filler in front of a real answer, where deleting the opener
776
+ // leaves the answer intact and better. A notice this daemon COMPOSED is the
777
+ // opposite case — its opener is not in front of the content, it IS the
778
+ // content's identity, and stripping it silently broke the one invariant every
779
+ // downstream recogniser depends on: that the bytes on the wire are the bytes
780
+ // the composer produced.
781
+ //
782
+ // Measured, production, 2026-09-30. `assurance.composeSilentSuccess` emits
783
+ // "Finished this but didn't get a reply out to you — my fault. Here's where
784
+ // I got to:\n\n<result>"
785
+ // and REPLY_FILLER_OPENERS[0] matches that whole first sentence, so what
786
+ // actually landed in the org was "Here's where I got to:\n\n<result>" — 188
787
+ // of them in one day, byte-for-byte confirmed in the ledger. The receiving
788
+ // seat's dispatch gate recognises a peer's notice with
789
+ // `assurance.isOwnNarratorText`, whose regexes are DERIVED from these very
790
+ // composers and anchored `^…$` precisely so they cannot drift from the
791
+ // emitter. A strip applied after composition defeats that by construction:
792
+ // the gate was comparing against a string nothing sends any more.
793
+ //
794
+ // The gate therefore missed, the notice was dispatched as an ordinary ask,
795
+ // the receiving session read it, correctly decided nothing was owed, exited 0
796
+ // having said nothing — and ITS silent-success rescue fired, landing on the
797
+ // first seat. 142 of the 188 notices that day were triggered by another
798
+ // notice: a two-seat DM ran one every ~60s for twenty minutes.
799
+ //
800
+ // So: never strip from our own status-notice family. That family is named
801
+ // once, in `lib/assurance/first-reply.isAgentStatusNotice`, shared with the
802
+ // board-row guard — one definition, so the emitter, the sender and the
803
+ // receiver cannot disagree about what a notice looks like.
804
+ // Head paragraph only, not the whole body: FIX 2's target is a filler opener,
805
+ // so the question here is "does this text OPEN as one of our notices" — the
806
+ // same thing every recogniser anchors on. A session-authored answer that
807
+ // merely contains a notice-shaped line further down keeps its strip.
808
+ if (isAgentStatusNotice(String(text).split(/\n\s*\n/, 1)[0])) return text;
773
809
  for (const re of REPLY_FILLER_OPENERS) {
774
810
  const m = text.match(re);
775
811
  if (m) {
@@ -869,6 +905,64 @@ export async function deliverReaction(item, emoji, o = {}) {
869
905
  }
870
906
  }
871
907
 
908
+ /**
909
+ * Record a send that did not happen, and hand the frame back unchanged.
910
+ *
911
+ * ── WHY EVERY REFUSAL IN THIS FUNCTION GOES THROUGH HERE ─────────────────────
912
+ *
913
+ * A refused send is returned to the caller and then, in practice, forgotten:
914
+ * `settleSession` writes the reason into an obligation note and closes the debt
915
+ * `undeliverable`. Nothing that later decides what the human is TOLD can see
916
+ * it. So the recovery notice says "Finished this but didn't get a reply out to
917
+ * you — my fault" for a send the gate refused for a stated reason, and the one
918
+ * fact worth saying — WHY — is the one fact it cannot reach.
919
+ *
920
+ * `recordNoSend` puts the reason in the same append-only ledger the delivery
921
+ * receipts live in, keyed to the obligation, so it crosses the process boundary
922
+ * the same way a receipt does and is readable by whatever speaks next.
923
+ *
924
+ * Fail-open by construction: `recordNoSend` never throws and its return value
925
+ * is ignored. Bookkeeping must not be able to turn a refusal into a crash.
926
+ *
927
+ * ── ATTRIBUTION IS PASSED IN, NOT SNIFFED FROM THE ENVIRONMENT ───────────────
928
+ *
929
+ * `recordNoSend` falls back to `MAESTRO_OBLIGATION_KEY` / `MAESTRO_SESSION_ID`
930
+ * when the caller names neither. Those are stamped by the dispatcher on the
931
+ * CHILD it spawns (`dispatcher.mjs`), so they are present in a spawned session
932
+ * and absent in the daemon — which is where this function runs. A row written
933
+ * here without an explicit key therefore carries `obligationKey:null,
934
+ * sessionId:null`, and `noSendFor`'s attribution ladder can never match it:
935
+ * every downstream reader sees nothing, and the whole recording is inert in
936
+ * exactly the plane it was written for. (The first cut of this code had that
937
+ * bug, and its test hid it by setting the env var by hand.)
938
+ *
939
+ * So the obligation rides in on `o` from the caller that owns it — `assurance`
940
+ * passes `rec.key` and `rec.sessionId` — and the env fallback is left for the
941
+ * session plane where it is actually correct.
942
+ *
943
+ * @param {object} item
944
+ * @param {object} o the deliver options: `{obligationKey, sessionId}`
945
+ * @param {object} frame the `{sent:false, …}` result being returned
946
+ * @returns {object} `frame`
947
+ */
948
+ function noteNoSend(item, o, frame) {
949
+ recordNoSend({
950
+ decision: "refused",
951
+ service: (item && item.service) || "unknown",
952
+ channel: (frame && frame.channel) || replyTargetOf(item) || (item && item.channel_id),
953
+ code: frame && frame.code,
954
+ // The CAUSE, never the body. `frame.error` is composed by this file and by
955
+ // the transports; none of them interpolates the message text.
956
+ reason: frame && frame.error,
957
+ surface: "daemon",
958
+ permanent: !!(frame && frame.permanent),
959
+ obligationKey: (o && o.obligationKey) || undefined,
960
+ sessionId: (o && o.sessionId) || undefined,
961
+ agentRoot: AGENT_REPO_DIR,
962
+ });
963
+ return frame;
964
+ }
965
+
872
966
  export async function deliver(item, text, o = {}) {
873
967
  const kind = o.kind || "reply";
874
968
  // FIX 2 (DM-LATENCY, 2026-09-27): strip a leading seat-flush / recovery filler
@@ -921,13 +1015,13 @@ export async function deliver(item, text, o = {}) {
921
1015
  // crosses this function.
922
1016
  if (isRetiredFirstReply(text)) {
923
1017
  try { console.error(`[deliver] refused: retired placeholder reply in outbound body ${JSON.stringify(String(text).slice(0, 120))} — this is a stale composer, not a message (permanent, not retrying)`); } catch { /* */ }
924
- return { sent: false, via: null, permanent: true, channel: item && item.channel_id, code: "FORBIDDEN_SCOPE", error: "FORBIDDEN_SCOPE: retired placeholder reply — the first line must be generated from the actual thread, or nothing" };
1018
+ return noteNoSend(item, o, { sent: false, via: null, permanent: true, channel: item && item.channel_id, code: "FORBIDDEN_SCOPE", error: "FORBIDDEN_SCOPE: retired placeholder reply — the first line must be generated from the actual thread, or nothing" });
925
1019
  }
926
1020
  const leak = scaffoldMarkerLeak(text);
927
1021
  if (leak) {
928
1022
  const surface = (item && item.channel_id) ? "room" : "unknown";
929
1023
  try { console.error(`[deliver] refused: raw scaffold marker ${JSON.stringify(leak)} in outbound body (permanent, not retrying)`); } catch { /* */ }
930
- return { sent: false, via: null, permanent: true, channel: item && item.channel_id, surface, code: "FORBIDDEN_SCOPE", error: `FORBIDDEN_SCOPE: raw scaffold marker ${leak} in outbound body — strip the marker; never send reasoning or transcript wrappers` };
1024
+ return noteNoSend(item, o, { sent: false, via: null, permanent: true, channel: item && item.channel_id, surface, code: "FORBIDDEN_SCOPE", error: `FORBIDDEN_SCOPE: raw scaffold marker ${leak} in outbound body — strip the marker; never send reasoning or transcript wrappers` });
931
1025
  }
932
1026
  // FIX 2 (DM-LATENCY, 2026-09-27): a reply in the seat's voice must never carry a
933
1027
  // machine-local path — no one off this box can open it, and CLAUDE.md forbids
@@ -937,7 +1031,7 @@ export async function deliver(item, text, o = {}) {
937
1031
  if (pathLeak) {
938
1032
  const surface = (item && item.channel_id) ? "room" : "unknown";
939
1033
  try { console.error(`[deliver] refused: machine-local path ${JSON.stringify(pathLeak)} in outbound body (permanent, not retrying)`); } catch { /* */ }
940
- return { sent: false, via: null, permanent: true, channel: item && item.channel_id, surface, code: "FORBIDDEN_SCOPE", error: `FORBIDDEN_SCOPE: machine-local path ${pathLeak} in outbound body — no one off this machine can open it; a reply must not carry a local path` };
1034
+ return noteNoSend(item, o, { sent: false, via: null, permanent: true, channel: item && item.channel_id, surface, code: "FORBIDDEN_SCOPE", error: `FORBIDDEN_SCOPE: machine-local path ${pathLeak} in outbound body — no one off this machine can open it; a reply must not carry a local path` });
941
1035
  }
942
1036
  // `permanent` says retrying changes nothing. A caller that cannot tell the
943
1037
  // difference between "hq blipped" and "there is no transport for telegram"
@@ -973,8 +1067,9 @@ export async function deliver(item, text, o = {}) {
973
1067
  chars: String(text).length,
974
1068
  agentRoot: AGENT_REPO_DIR,
975
1069
  });
1070
+ return result;
976
1071
  }
977
- return result;
1072
+ return noteNoSend(item, o, result);
978
1073
  }
979
1074
 
980
1075
  /**
@@ -593,7 +593,20 @@ Why split read vs write: MCP tools are ideal for reading because they have full
593
593
  - Match the tone and urgency of the sender
594
594
  - If the sender is CEO, prioritise speed and directness
595
595
  - If you need to share documents, upload to Google Drive or send as PDF — NEVER reference local file paths
596
- - Verify the send succeeded by checking the script's exit code and stdout before considering the task complete`,
596
+ - Verify the send succeeded by checking the script's exit code and stdout before considering the task complete
597
+
598
+ THE ORG MESSAGING LANE (the MCP send tools are hook-blocked; this is the sanctioned door):
599
+ \`node scripts/org/send-cohort-message.mjs --channel "<channel_id>" --body-file <path>\` (or \`--dm <member_id>\`, \`--thread-root <message_id>\`, \`--mention <member_id>\`)
600
+ - Exit 0 = sent, and the receipt is written for you. Exit 1 = refused or failed, with the cause on stderr. Exit 2 = your flags were wrong.
601
+ - On \`FORBIDDEN_SCOPE\` the outbound send-gate refused THIS BODY, not the send: reword to clear the stated rule and run it again.
602
+ - For Slack use \`scripts/slack-send.sh\`; for workspace email \`node scripts/org/send-orgmail.mjs\`.
603
+
604
+ IF NOTHING GOES OUT, SAY WHY — one command, and it matters more than it looks:
605
+ \`./scripts/record-no-send.sh <declined|refused> "<service>" "<channel_id>" "<short reason>" ["<code>"]\`
606
+ - \`declined\` — you decided no reply was owed (the thread is closed, nothing was asked, you archived it). Run this and then just stop.
607
+ - \`refused\` — you TRIED to send and something stopped you: a blocked lane, a non-zero exit, an error frame. Run this with the cause, then retry if the cause could pass on a second attempt.
608
+ - CHECK THE EXIT CODE. 0 = recorded and attributable. 3 = recorded but NOTHING CAN READ IT (this session has no MAESTRO_OBLIGATION_KEY / MAESTRO_SESSION_ID — report that, it is a dispatcher bug). 4 = the recorder could not run. 64 = your arguments were wrong and nothing was written.
609
+ Why: a successful send leaves a receipt automatically, and the absence of one is all anyone downstream can see. Read alone it means "the reply failed", so a turn that correctly stayed quiet gets apologised for and its working notes pasted into the room — 188 of those landed in the org on 2026-09-30, and 32 of the 46 seed notices said in their own text that the session had chosen not to reply. This is the only way your reason crosses back out of this session.`,
597
610
 
598
611
  draft: `ACTION: Draft a response or document — do NOT send it yet.
599
612
  - Read the message and understand what is being requested
@@ -5,11 +5,20 @@
5
5
  # interactive Claude sessions. READS are welcome; the outbound WRITES
6
6
  # (messaging_send, email_send, email_draft_send) and the org_rpc escape hatch
7
7
  # must go through the
8
- # sanctioned CLI lane instead — scripts/slack-send.sh / scripts/org/send-orgmail.mjs
9
- # — which carries the full dedup + reply-storm + governance perimeter that the
10
- # MCP tool's content screen alone does not. Same pattern as
11
- # block-mcp-slack-send.sh (CEO directive si-010).
8
+ # sanctioned CLI lane instead — which carries the full dedup + reply-storm +
9
+ # governance perimeter that the MCP tool's content screen alone does not. Same
10
+ # pattern as block-mcp-slack-send.sh (CEO directive si-010).
11
+ #
12
+ # THE LANE FOR ORG MESSAGING IS scripts/org/send-cohort-message.mjs, and until
13
+ # 2026-09-30 it did not exist. This rejection named one for Slack and one for
14
+ # workspace email and, for org messaging, only "the daemon's messaging path" —
15
+ # which a spawned session cannot invoke. So a session with an answer to give had
16
+ # no door at all, and said so in the room instead: two production notices on
17
+ # 09-29/30 report this block verbatim, and four in that window name a blocked
18
+ # send lane. A refusal that names no alternative is not a policy, it is a dead
19
+ # end. Every rule this hook protects still holds on the new lane — it calls the
20
+ # same executeOrgTool, which runs the same send-gate before dispatch.
12
21
  #
13
22
  # Exit 2 = blocked (message shown to Claude as rejection)
14
- echo "BLOCKED: org-MCP outbound writes are session-blocked. Reply via the sanctioned CLI lane instead: org messaging → the daemon's messaging path / scripts/slack-send.sh for Slack; workspace email → node scripts/org/send-orgmail.mjs --thread \"<thread_id>\" --body-file <path>. Read/board/decision org tools remain available." >&2
23
+ echo "BLOCKED: org-MCP outbound writes are session-blocked. Use the sanctioned CLI lane instead: org messaging → node scripts/org/send-cohort-message.mjs --channel \"<channel_id>\" --body-file <path> (or --dm <member_id>); Slack → scripts/slack-send.sh; workspace email → node scripts/org/send-orgmail.mjs --thread \"<thread_id>\" --body-file <path>. If you decide NOT to reply, record it: ./scripts/record-no-send.sh declined <service> <channel> \"<reason>\" — otherwise the absence of a reply is read as a failed send. Read/board/decision org tools remain available." >&2
15
24
  exit 2
@@ -0,0 +1,190 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * send-cohort-message.mjs — the sanctioned CLI lane for ORG MESSAGING sends.
4
+ *
5
+ * ── WHY THIS FILE EXISTS ─────────────────────────────────────────────────────
6
+ *
7
+ * It is the lane that was missing, and its absence is a MEASURED cause of
8
+ * replies that never sent — not an inferred one.
9
+ *
10
+ * `scripts/hooks/block-mcp-cohort-send.sh` and the `pre-send-audit.sh`
11
+ * PreToolUse hook both stop a session calling `mcp__cohort__messaging_send`
12
+ * directly, and both point at "the sanctioned CLI lane instead". For Slack that
13
+ * lane is `scripts/slack-send.sh`; for workspace email it is
14
+ * `scripts/org/send-orgmail.mjs`; for ORG MESSAGING the rejection text named
15
+ * only "the daemon's messaging path", which a spawned session cannot invoke.
16
+ * There was no door.
17
+ *
18
+ * Two production notices in the 2026-09-29/30 window say exactly that, in their
19
+ * own words, because narrating it into a room was the only reporting channel
20
+ * they had left:
21
+ *
22
+ * cmun731th2fvpm9013jihfgob (09-29T11:39:52Z)
23
+ * "There's no sanctioned way to send a Cohort DM reply in this session —
24
+ * MCP send is hook-blocked, and unlike Slack/Gmail/orgmail there's no CLI
25
+ * script for Cohort sends"
26
+ * cmunr4biu4djim901asuqb1i7 (09-30T06:55Z)
27
+ * "Couldn't get an answer directly into Layla's DM — the Cohort send lane
28
+ * from this seat is still hook-blocked, there's no CLI equivalent for
29
+ * Cohort messaging"
30
+ *
31
+ * Four notices in that window name a blocked send lane; the earliest is
32
+ * 09-29T11:39:52Z and the latest 09-30T16:04:35Z. A companion change makes the
33
+ * hook RECORD its refusals (`send-gate.runPreSendHook`), so a block is visible
34
+ * to the daemon instead of only to the session. That fixes the reporting. This
35
+ * fixes the send.
36
+ *
37
+ * ── THIS IS NOT A POLICY BYPASS, AND THAT IS THE POINT ───────────────────────
38
+ *
39
+ * Every send here goes through `executeOrgTool("messaging_send", …)`, which is
40
+ * the same in-process path the MCP tool uses and which:
41
+ *
42
+ * 1. screens the body through `lib/comms/send-gate.screenOutbound` BEFORE
43
+ * dispatch (`screenOrgOutbound`) — the identical module the PreToolUse hook
44
+ * runs, so a banned phrase, a persona leak or a scaffold marker is refused
45
+ * here too, with the same reason string;
46
+ * 2. lets hq's server-side ACLs, pairing and dedup stay authoritative;
47
+ * 3. writes the delivery RECEIPT on success, so the daemon that spawned this
48
+ * session does not read a delivered reply as silence and apologise for it;
49
+ * 4. writes a NO-SEND row on failure, so a refusal crosses the process
50
+ * boundary with its cause instead of dying in this process's stderr.
51
+ *
52
+ * So the hook's rule is preserved — screened, audited, recorded — and the only
53
+ * thing that changes is that a session which has something to say can say it.
54
+ *
55
+ * Usage:
56
+ * node scripts/org/send-cohort-message.mjs --channel <channelId> --body "text"
57
+ * node scripts/org/send-cohort-message.mjs --channel <id> --body-file reply.md
58
+ * node scripts/org/send-cohort-message.mjs --dm <memberId> --body "text"
59
+ * … --thread-root <messageId> reply under a thread root
60
+ * … --mention <memberId> repeatable; tag only people who must ACT
61
+ *
62
+ * Exit codes:
63
+ * 0 sent (the messageId is printed)
64
+ * 1 refused or failed — the cause is on stderr AND in the no-send ledger
65
+ * 2 usage error; nothing was attempted
66
+ */
67
+
68
+ "use strict";
69
+
70
+ import { readFileSync } from "node:fs";
71
+ import { executeOrgTool, resolveOrgToolConfig } from "../../lib/org/tool-surface.mjs";
72
+ import { applyBrandEnvCompat } from "../../lib/env-compat.mjs";
73
+
74
+ // Fleet back-compat FIRST: bridge NEOLITH_* ⇄ COHORT_* env names before any
75
+ // env-first credential resolution. See lib/env-compat.mjs.
76
+ applyBrandEnvCompat();
77
+
78
+ export function parseArgs(argv) {
79
+ const flags = { mentions: [] };
80
+ for (let i = 0; i < argv.length; i += 1) {
81
+ const a = argv[i];
82
+ const next = () => { i += 1; return argv[i]; };
83
+ switch (a) {
84
+ case "--channel": case "--channel-id": flags.channel = next(); break;
85
+ case "--dm": flags.dm = next(); break;
86
+ case "--body": flags.body = next(); break;
87
+ case "--body-file": flags.bodyFile = next(); break;
88
+ case "--thread-root": flags.threadRootId = next(); break;
89
+ case "--mention": flags.mentions.push(String(next()).trim()); break;
90
+ case "--help": case "-h": flags.help = true; break;
91
+ default: return { error: `unknown flag ${a}` };
92
+ }
93
+ }
94
+ flags.mentions = flags.mentions.filter(Boolean);
95
+ return flags;
96
+ }
97
+
98
+ function usageInto(lines) {
99
+ lines.push('Usage: node scripts/org/send-cohort-message.mjs --channel <channelId> --body "text"');
100
+ lines.push(" node scripts/org/send-cohort-message.mjs --dm <memberId> --body-file <path>");
101
+ lines.push(" [--thread-root <messageId>] [--mention <memberId> …]");
102
+ }
103
+
104
+ /**
105
+ * The whole lane as a PURE-ISH function over injected effects, so it is testable
106
+ * without a network, a credential or a process exit.
107
+ *
108
+ * Returns rather than exits, and reports rather than throws, for the reason the
109
+ * whole lane exists: a send that fails silently is the defect. Every path below
110
+ * produces a code AND a line saying why.
111
+ *
112
+ * @param {object} o
113
+ * @param {string[]} o.argv
114
+ * @param {(name:string, input:object, opts:object)=>Promise<object>} [o.executeImpl]
115
+ * @param {(o:object)=>object} [o.resolveConfigImpl]
116
+ * @param {(p:string, enc:string)=>string} [o.readFileImpl]
117
+ * @returns {Promise<{code:number, out:string[], err:string[]}>}
118
+ */
119
+ export async function sendCohortMessage(o = {}) {
120
+ const out = [];
121
+ const err = [];
122
+ const readFile = o.readFileImpl || readFileSync;
123
+ const execute = o.executeImpl || executeOrgTool;
124
+ const resolveConfig = o.resolveConfigImpl || resolveOrgToolConfig;
125
+ const fail = (code, msg) => { err.push(`send-cohort-message: ${msg}`); return { code, out, err }; };
126
+
127
+ const flags = parseArgs(o.argv || []);
128
+ if (flags.error) { err.push(`send-cohort-message: ${flags.error}`); usageInto(out); return { code: 2, out, err }; }
129
+ if (flags.help) { usageInto(out); return { code: 0, out, err }; }
130
+
131
+ let body = flags.body;
132
+ if (!body && flags.bodyFile) {
133
+ try { body = readFile(flags.bodyFile, "utf8"); }
134
+ catch (e) { return fail(2, `cannot read --body-file ${flags.bodyFile}: ${e && e.message ? e.message : e}`); }
135
+ }
136
+ if (!body || !String(body).trim()) { usageInto(out); return fail(2, "--body or --body-file required"); }
137
+ if (!flags.channel && !flags.dm) { usageInto(out); return fail(2, "--channel or --dm required"); }
138
+
139
+ const cfg = resolveConfig({});
140
+ if (!cfg.token || !cfg.base) {
141
+ return fail(1, "no org credential — set COHORT_API_TOKEN or run `cohort setup --only org`");
142
+ }
143
+ const opts = { agentRoot: cfg.agentRoot };
144
+
145
+ let channelId = flags.channel;
146
+ if (!channelId) {
147
+ // `--dm <memberId>` is the common case for answering a person, and resolving
148
+ // it here is what stops a session shelling out twice and carrying an id
149
+ // between the two calls.
150
+ const open = await execute("messaging_open_dm", { memberId: flags.dm }, opts);
151
+ if (!open || !open.ok) {
152
+ return fail(1, `cannot open a DM with ${flags.dm} — ${open?.error?.code || "ERROR"}: ${open?.error?.message || "messaging.openDm failed"}`);
153
+ }
154
+ channelId = open.result?.channelId || open.result?.id;
155
+ if (!channelId) return fail(1, `messaging_open_dm returned no channel id — ${JSON.stringify(open.result || {})}`);
156
+ }
157
+
158
+ const input = { channelId, body: String(body) };
159
+ if (flags.threadRootId) input.threadRootId = flags.threadRootId;
160
+ if (flags.mentions.length) input.mentions = flags.mentions;
161
+
162
+ // The receipt on success and the no-send row on refusal are both written INSIDE
163
+ // executeOrgTool — see its trailer. Nothing to do here but report.
164
+ const frame = await execute("messaging_send", input, opts);
165
+ if (!frame || !frame.ok) {
166
+ const code = frame?.error?.code || "ERROR";
167
+ err.push(`send-cohort-message: ${code} — ${frame?.error?.message || "messaging.send failed"}`);
168
+ if (code === "FORBIDDEN_SCOPE") {
169
+ err.push("send-cohort-message: that is the outbound send-gate, not the server. Rewrite the body to clear the stated rule and run this again — the refusal is already on the no-send ledger, so nobody downstream will apologise for a silence you did not choose.");
170
+ }
171
+ return { code: 1, out, err };
172
+ }
173
+ const id = frame.result?.messageId || frame.result?.id || "(no id)";
174
+ out.push(`send-cohort-message: sent — channel ${channelId} message ${id}`);
175
+ return { code: 0, out, err };
176
+ }
177
+
178
+ async function main() {
179
+ const r = await sendCohortMessage({ argv: process.argv.slice(2) });
180
+ for (const l of r.out) console.log(l);
181
+ for (const l of r.err) console.error(l);
182
+ process.exit(r.code);
183
+ }
184
+
185
+ if (process.argv[1] && process.argv[1].endsWith("send-cohort-message.mjs")) {
186
+ main().catch((e) => {
187
+ console.error(`send-cohort-message: ${e && e.message ? e.message : e}`);
188
+ process.exit(1);
189
+ });
190
+ }