@cohortapp/agent-sdk 2.18.36 → 2.18.37

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.
@@ -43,6 +43,9 @@
43
43
  * pollMs drain interval (default 2_000).
44
44
  * heartbeatMs health.json refresh interval (default 15_000).
45
45
  * recoveryMs stale-claim sweep interval (default 5 * 60_000).
46
+ * deferHoldMs how long a tick deferred by an upstream gate is held off
47
+ * the claim path before the gate is re-tested
48
+ * (default 30_000). Never affects attempt accounting.
46
49
  * budgetEscalateMs how often to check whether a budget-band notice is due
47
50
  * for the SUPERVISOR (default 5 * 60_000; 0 disables).
48
51
  * spawnSession injected spawner for tests; defaults to a real
@@ -75,6 +78,8 @@ import {
75
78
  completeTick,
76
79
  failTick,
77
80
  requeueTick,
81
+ MAX_DEFER_HOLD_MS,
82
+ DEDUPE_LANE_HANDOFF_TIMEOUT,
78
83
  enqueueTick,
79
84
  recoverStaleClaims,
80
85
  sweepRetention,
@@ -156,6 +161,12 @@ const MAX_CONCURRENT_SUB_SESSIONS = 1;
156
161
  // the burn. 2 retries with exponential back-off is the right balance.
157
162
  const DEFAULT_MAX_ATTEMPTS = 2;
158
163
  const BACKOFF_SCHEDULE_MS = [0, 30_000, 120_000]; // 1st retry +30s, 2nd retry +2m
164
+ // How long a tick deferred by an upstream gate is held off the claim path
165
+ // before the gate is re-tested (W19). Attempt-count-neutral: see deferTick.
166
+ // 30 s matches the first non-zero backoff rung, so a gate that clears quickly
167
+ // costs at most one wasted interval and a gate that stays shut costs 2 polls'
168
+ // worth of work per minute instead of 30.
169
+ const DEFER_HOLD_MS = 30_000;
159
170
 
160
171
  // Circuit breaker — when 3 same-cadence failures land in a row, stop
161
172
  // spawning that cadence for 30 minutes. Prevents launchd-rate runaway.
@@ -703,6 +714,9 @@ export function startConsumer(opts = {}) {
703
714
  const backoffSchedule = opts.backoffSchedule || BACKOFF_SCHEDULE_MS;
704
715
  const circuitThreshold = opts.circuitThreshold ?? CIRCUIT_OPEN_THRESHOLD;
705
716
  const circuitDurationMs = opts.circuitDurationMs ?? CIRCUIT_OPEN_DURATION_MS;
717
+ // Overridable like `backoffSchedule`, so a test can drive the deferral path
718
+ // hard without waiting out a real hold.
719
+ const deferHoldMs = Number.isFinite(opts.deferHoldMs) ? opts.deferHoldMs : DEFER_HOLD_MS;
706
720
  const maxAttempts = opts.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
707
721
  // WS4 governance modules (injectable for hermetic tests).
708
722
  const governor = opts.governor || resourceGovernor;
@@ -976,6 +990,41 @@ export function startConsumer(opts = {}) {
976
990
  // cadence are the duplicate this guards against.
977
991
  const inFlightCadences = new Set();
978
992
 
993
+ // PER-CADENCE DEFERRAL HOLDS (W19 rework) — cadence → epoch-ms deadline.
994
+ //
995
+ // WHY NOT PER TICK. The first cut stamped the hold on the deferred TICK only.
996
+ // That makes the requeue rate linear in queue depth: with `depth` pending
997
+ // copies, `depth` independent deadlines expire inside one hold window and the
998
+ // drain claims and re-defers every one of them. MEASURED on this branch over
999
+ // 15 min of 2 s polls behind a gate that never opens (30 s hold): depth 1 →
1000
+ // 8.0/s to 0.03/s, but depth 87 (the live inbox) → 8.0/s to only 2.9/s, and
1001
+ // depth 240 and 1000 → 8.0/s BEFORE AND AFTER. The incident's own queue was
1002
+ // 15,674 deep, so the per-tick hold alone would have delivered nothing.
1003
+ //
1004
+ // A gate is shut for a CADENCE, not for a file. One hold therefore covers
1005
+ // every pending tick of that cadence, and the rate stops depending on how
1006
+ // many there are: 120 deferrals/hour at any depth.
1007
+ //
1008
+ // In memory, deliberately. The durable half is already on disk (each
1009
+ // deferred tick carries `metadata.notBefore`), so a restart loses only the
1010
+ // grouping — the first poll after a restart re-establishes one hold per shut
1011
+ // cadence at a cost of one deferral each.
1012
+ const cadenceHoldUntil = new Map();
1013
+
1014
+ /** Set (never shorten) the hold on a cadence. */
1015
+ function holdCadence(cadence, until) {
1016
+ if (!cadence || !Number.isFinite(until)) return;
1017
+ const prior = cadenceHoldUntil.get(cadence);
1018
+ if (!Number.isFinite(prior) || until > prior) cadenceHoldUntil.set(cadence, until);
1019
+ }
1020
+
1021
+ /** Drop holds that have expired, so the map stays the size of the shut set. */
1022
+ function pruneCadenceHolds(now) {
1023
+ for (const [cadence, until] of cadenceHoldUntil) {
1024
+ if (!(until > now)) cadenceHoldUntil.delete(cadence);
1025
+ }
1026
+ }
1027
+
979
1028
  // Injectable clock so tests can drive the stale window deterministically.
980
1029
  const nowMs = typeof opts.now === "function" ? opts.now : Date.now;
981
1030
 
@@ -990,19 +1039,57 @@ export function startConsumer(opts = {}) {
990
1039
 
991
1040
  /**
992
1041
  * Re-queue a tick that cannot run YET (an upstream gate, never a per-event
993
- * failure) to the TAIL under a new id (audit F8). Attempts untouched.
1042
+ * failure) to the TAIL under a new id (audit F8), HELD until it is worth
1043
+ * re-testing the gate. Attempts untouched.
1044
+ *
994
1045
  * `count:false` (the circuit/backoff skip) re-keys without touching the
995
1046
  * retry/deferral counters or last_decision — a held-back cadence was never
996
1047
  * attempted, and the skip is already logged and counted as skipped_*; a
997
1048
  * 30 s poll inside a 60 min circuit window must not read as 120 retries.
1049
+ *
1050
+ * THE HOT LOOP THIS CLOSES (W19, measured on this seat 2026-10-01).
1051
+ * Re-keying alone left the tick immediately claimable, so every poll
1052
+ * re-claimed it, re-tested the shut gate and wrote it back: 1,186,383
1053
+ * deferrals in 68 h (8/s, the 16-per-drain batch cap over a 2 s poll), one
1054
+ * event at 40,150 deferrals, 443 MB/day of audit log. The incident note
1055
+ * blamed the CONCURRENCY call site; the log says otherwise — the live
1056
+ * reasons were `cadence-in-flight:sub-session` (35,043/day),
1057
+ * `cadence-in-flight:handoff` (12,035), `skipped_circuit_open` (14,307) and
1058
+ * the governance gate, with concurrency not in the top twenty. Every one of
1059
+ * them lands HERE, so the hold belongs here and not at any one call site —
1060
+ * fixing only the concurrency path would have changed nothing measurable.
1061
+ *
1062
+ * ATTEMPT-COUNT-NEUTRAL, BY CONSTRUCTION AND BY TEST. The hold is a
1063
+ * timestamp on the requeued copy; `attempts` is written only by `failTick`
1064
+ * (audit M5), which is not called on this path. A gate closure therefore
1065
+ * cannot spend retry budget or move a tick toward dlq/, however long it
1066
+ * stays shut. That is the expensive mistake to make here: reusing the retry
1067
+ * machinery for the delay would dead-letter a perfectly healthy cadence for
1068
+ * the crime of being deferred often, turning a delay into a lost task.
1069
+ * `defer-hold.test.mjs` pins it.
1070
+ *
1071
+ * @param {number} [opts.holdMs] override the hold (e.g. a gate that knows
1072
+ * its own `retry_at`). 0 means "claimable now".
998
1073
  */
999
- function deferTick(event, reason, extra = {}, { count = true } = {}) {
1000
- const r = requeueTick(agentRoot, event, { defer: true });
1074
+ function deferTick(event, reason, extra = {}, { count = true, holdMs = deferHoldMs } = {}) {
1075
+ // Clamped here as well as in requeueTick: the number that reaches the
1076
+ // per-cadence map must be the same one that reaches the tick's own stamp,
1077
+ // or claimNextTick's two holds would disagree about when this is due.
1078
+ const hold = Number.isFinite(holdMs) ? Math.min(Math.max(holdMs, 0), MAX_DEFER_HOLD_MS) : 0;
1079
+ const r = requeueTick(agentRoot, event, { defer: true, now: new Date(nowMs()), holdMs: hold });
1080
+ // THE DEPTH-INDEPENDENT HALF. Hold the CADENCE, not just this tick — see
1081
+ // `cadenceHoldUntil`. Every pending copy of this cadence is now skipped
1082
+ // without being claimed until the hold expires, so a shut gate costs one
1083
+ // deferral per hold window however deep the queue is.
1084
+ if (hold > 0) holdCadence(event.cadence, nowMs() + hold);
1001
1085
  if (count) {
1002
- stats.retries += 1;
1086
+ // NOT stats.retries. A deferral is not a retry, and conflating them made
1087
+ // the health file read `retries: 1186419` against 36 real retries — an
1088
+ // operator seeing a million retries reasonably concludes the DLQ is
1089
+ // about to fill. `stats.deferred` is the honest counter.
1003
1090
  stats.deferred += 1;
1004
1091
  stats.last_decision = "deferred";
1005
- log({ level: "info", stage: "escalate_deferred", reason, id: event.id, requeued_as: r && r.id, cadence: event.cadence, ...extra });
1092
+ log({ level: "info", stage: "escalate_deferred", reason, id: event.id, requeued_as: r && r.id, cadence: event.cadence, hold_ms: hold, ...extra });
1006
1093
  }
1007
1094
  return { ok: false, decision: "deferred", reason };
1008
1095
  }
@@ -1124,9 +1211,28 @@ export function startConsumer(opts = {}) {
1124
1211
  const r = enqueueTick({
1125
1212
  cadence: h.cadence,
1126
1213
  source: "handoff-timeout",
1214
+ // THE MAJORITY LANE OF THE LIVE DEPTH (W19 rework). This sweep has
1215
+ // no time gate of any kind: every expired handoff enqueues, and on
1216
+ // 2026-10-01 that was 47 of the live seat's 88 pending ticks, all
1217
+ // of them `meeting-action-capture` — 47 copies of "the session
1218
+ // never acked it, run it again", which cannot each do distinct
1219
+ // work. Its own lane, so a pending periodic tick never suppresses
1220
+ // it and it never suppresses one.
1221
+ dedupeLane: DEDUPE_LANE_HANDOFF_TIMEOUT,
1127
1222
  agentRoot,
1128
1223
  metadata: { ...meta, handoffTimedOut: true, handoffTickId: h.tickId, reason: `handoff to session timed out (${h.deadlineAt || "no deadline"})` },
1129
1224
  });
1225
+ // A SUPPRESSED DUPLICATE IS A SUCCESS, AND GETTING THIS WRONG MAKES A
1226
+ // SECOND HOT LOOP. The work is already pending, so this handoff is
1227
+ // done and must be retired — if it threw instead, the handoff would
1228
+ // stay open, `cadenceInFlight` would report "handoff" forever, and
1229
+ // this sweep (which runs on EVERY poll, ahead of the drain) would
1230
+ // re-enqueue, re-suppress and write two log rows every 2 s.
1231
+ if (r && r.skipped === "pending-duplicate") {
1232
+ log({ level: "info", stage: "handoff_timed_out_duplicate", id: h.tickId, cadence: h.cadence, pending_id: r.pendingId || null, note: "a handoff-timeout tick for this cadence is already pending; handoff retired" });
1233
+ stats.handoff_timeouts += 1;
1234
+ return true;
1235
+ }
1130
1236
  // enqueueTick swallows an unwritable inbox (fallbackOnly, audit row
1131
1237
  // only) — that is NOT back on the bus: keep the handoff open.
1132
1238
  if (!r || !r.path) throw new Error(`tick not enqueued (${r && r.fallbackOnly ? "inbox unwritable" : "no path"})`);
@@ -1312,9 +1418,31 @@ export function startConsumer(opts = {}) {
1312
1418
  }
1313
1419
  }
1314
1420
 
1421
+ /**
1422
+ * How many cadences are held right now, and until when.
1423
+ *
1424
+ * `held` makes a deferral hold OBSERVABLE. Without it an operator cannot tell
1425
+ * "this tick is waiting 30 s for a shut gate" from "this tick is stuck",
1426
+ * because claimNextTick skips a held tick silently and nothing else in the
1427
+ * health file mentions it. Reported in both the heartbeat and getStats so the
1428
+ * two never disagree.
1429
+ */
1430
+ function heldSnapshot() {
1431
+ const now = nowMs();
1432
+ let held = 0;
1433
+ let furthest = 0;
1434
+ for (const until of cadenceHoldUntil.values()) {
1435
+ if (until > now) {
1436
+ held += 1;
1437
+ if (until > furthest) furthest = until;
1438
+ }
1439
+ }
1440
+ return { held, held_until: furthest ? new Date(furthest).toISOString() : null };
1441
+ }
1442
+
1315
1443
  function heartbeat() {
1316
1444
  writeHealth(agentRoot, {
1317
- stats: { ...stats, depth: busDepth(agentRoot) },
1445
+ stats: { ...stats, depth: busDepth(agentRoot), ...heldSnapshot() },
1318
1446
  active_subsessions: activeSubSessions,
1319
1447
  stopping,
1320
1448
  });
@@ -1338,7 +1466,28 @@ export function startConsumer(opts = {}) {
1338
1466
  // Put the event back — to the TAIL (F8). Attempt accounting is
1339
1467
  // single-sourced in failTick (audit M5), so we never touch it here: a
1340
1468
  // held-back-by-circuit re-queue is not a failed attempt, nor a retry.
1341
- deferTick(event, gate.reason, { retry_at: new Date(gate.retry_at).toISOString() }, { count: false });
1469
+ // This gate knows its own deadline, so hold to exactly that rather than
1470
+ // the generic interval: a 30 min open circuit should cost ONE requeue,
1471
+ // not sixty. Floored at the generic hold so a retry_at already in the
1472
+ // past (clock skew, a just-expired window) cannot re-open the hot loop.
1473
+ deferTick(
1474
+ event,
1475
+ gate.reason,
1476
+ { retry_at: new Date(gate.retry_at).toISOString() },
1477
+ // Hold to this gate's own deadline, so a 30 min open circuit costs ONE
1478
+ // requeue not sixty. FLOORED at the generic hold so a retry_at already
1479
+ // in the past cannot re-open the hot loop, and CEILINGED at
1480
+ // MAX_DEFER_HOLD_MS so a retry_at from a provider Retry-After, a
1481
+ // forward clock jump or a corrupted number cannot park the tick out of
1482
+ // sight for days (claimNextTick skips a held tick silently).
1483
+ {
1484
+ count: false,
1485
+ holdMs: Math.min(
1486
+ MAX_DEFER_HOLD_MS,
1487
+ Math.max(deferHoldMs, gate.retry_at - nowMs()),
1488
+ ),
1489
+ },
1490
+ );
1342
1491
  return { ok: false, decision: gate.reason };
1343
1492
  }
1344
1493
 
@@ -1710,6 +1859,7 @@ export function startConsumer(opts = {}) {
1710
1859
 
1711
1860
  let processed = 0;
1712
1861
  let spawnedThisTick = 0;
1862
+ pruneCadenceHolds(nowMs());
1713
1863
  // Head-of-line (F8): a deferred tick is re-keyed to the tail, so the loop
1714
1864
  // KEEPS SCANNING past it to the next cadence instead of breaking. This set
1715
1865
  // (keyed by the tick's original id, which a re-key preserves) is how the
@@ -1718,7 +1868,10 @@ export function startConsumer(opts = {}) {
1718
1868
  // holding only un-runnable ticks costs one visit per tick, not sixteen.
1719
1869
  const seenThisTick = new Set();
1720
1870
  while (!stopping) {
1721
- const claim = claimNextTick(agentRoot);
1871
+ // Due-aware (W19): a tick still inside its deferral hold is skipped
1872
+ // without being claimed, so a shut gate costs a cached read rather than
1873
+ // a claim + requeue + audit row.
1874
+ const claim = claimNextTick(agentRoot, { now: nowMs(), heldCadences: cadenceHoldUntil });
1722
1875
  if (!claim) break;
1723
1876
  const event = claim.event;
1724
1877
  const key = (event.metadata && event.metadata.originalId) || event.id;
@@ -1876,7 +2029,7 @@ export function startConsumer(opts = {}) {
1876
2029
  }
1877
2030
 
1878
2031
  function getStats() {
1879
- return { ...stats, depth: busDepth(agentRoot), agent_root: agentRoot };
2032
+ return { ...stats, depth: busDepth(agentRoot), ...heldSnapshot(), agent_root: agentRoot };
1880
2033
  }
1881
2034
 
1882
2035
  return {
@@ -1891,6 +2044,9 @@ export function startConsumer(opts = {}) {
1891
2044
  _clearInFlight: (id) => inFlightClaimIds.delete(id),
1892
2045
  // Front door: the open handoffs this consumer has written for the session.
1893
2046
  _handoffs: () => listHandoffs(agentRoot),
2047
+ // Write the health file on demand, so a test can read `held` without
2048
+ // waiting on the heartbeat timer.
2049
+ _heartbeat: heartbeat,
1894
2050
  };
1895
2051
  }
1896
2052
 
@@ -36,6 +36,13 @@ import { recordNoSend, recordOutbound } from "../../lib/comms/receipts.mjs";
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
38
  import { isAgentStatusNotice, isRetiredFirstReply } from "../../lib/assurance/first-reply.mjs";
39
+ // THE TWO HALVES OF THE MACHINE-STATUS REFUSAL. `isMachineStatusDeliveryKind`
40
+ // is the ORIGIN test (what composed this) and `machineStatusNarration` is the
41
+ // SHAPE test (what it reads like). Both are pure data + pure predicates, imported
42
+ // rather than restated, so the decision in `notice-plane.mjs` and the enforcement
43
+ // here cannot drift. See the refusal block in `deliver` below.
44
+ import { isMachineStatusDeliveryKind } from "../../lib/assurance/notice-plane.mjs";
45
+ import { machineStatusNarration } from "../../lib/comms/machine-status.mjs";
39
46
 
40
47
  const AGENT_REPO_DIR = process.env.AGENT_DIR || join(new URL(".", import.meta.url).pathname, "../..");
41
48
 
@@ -945,6 +952,33 @@ export async function deliverReaction(item, emoji, o = {}) {
945
952
  * @param {object} frame the `{sent:false, …}` result being returned
946
953
  * @returns {object} `frame`
947
954
  */
955
+ /**
956
+ * Is this body one of this daemon's OWN status templates, carrying no answer?
957
+ *
958
+ * One paragraph (so the composers' excerpt paragraph is absent) AND an exact
959
+ * whole-body match against `assurance.narratorPatterns`, which is derived from
960
+ * the composers rather than written out — so rewording a template keeps it
961
+ * recognised here, and a real reply that merely opens with a familiar phrase is
962
+ * not matched, because the match spans the whole body.
963
+ *
964
+ * FAILS OPEN. A dynamic import that throws, or an assurance module mid-edit, must
965
+ * never be able to hold up a real reply.
966
+ *
967
+ * @param {unknown} text
968
+ * @returns {Promise<string|null>} a short excerpt of the matched body, or null
969
+ */
970
+ async function answerlessOwnTemplate(text) {
971
+ const raw = String(text == null ? "" : text).trim();
972
+ if (!raw) return null;
973
+ const paragraphs = raw.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
974
+ if (paragraphs.length !== 1) return null;
975
+ try {
976
+ const { isOwnNarratorText } = await import("./assurance.mjs");
977
+ if (typeof isOwnNarratorText !== "function") return null;
978
+ return isOwnNarratorText(raw) ? raw.slice(0, 90) : null;
979
+ } catch { return null; }
980
+ }
981
+
948
982
  function noteNoSend(item, o, frame) {
949
983
  recordNoSend({
950
984
  decision: "refused",
@@ -1017,6 +1051,76 @@ export async function deliver(item, text, o = {}) {
1017
1051
  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 { /* */ }
1018
1052
  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" });
1019
1053
  }
1054
+ // ── MACHINE STATUS NEVER REACHES A PERSON ────────────────────────────────
1055
+ //
1056
+ // The register above is a list of sentences that HAVE shipped. It cannot
1057
+ // refuse the next one, and the history says the next one is what gets sent:
1058
+ // three fixes, three registrations, three new variants, and on 2026-10-01 the
1059
+ // owner received the current variant twice, the second time eleven minutes
1060
+ // after complaining about the first. `lib/assurance/notice-plane.mjs` carries
1061
+ // the decision and the argument; this is where it is enforced on bytes.
1062
+ //
1063
+ // TWO TESTS, BECAUSE THEY FAIL DIFFERENTLY.
1064
+ //
1065
+ // ORIGIN — `kind` is "failure" or "notice", i.e. the caller has declared
1066
+ // that a machine composed this about its own apparatus. No
1067
+ // sentence can get around this one, which is the property every
1068
+ // previous fix lacked. `sayOutcomeNotice` no longer reaches this
1069
+ // function at all (it routes to the operator sink), so a refusal
1070
+ // here means a NEW caller has been wired to the human transport —
1071
+ // exactly the regression this is here to catch.
1072
+ // SHAPE — an apparatus subject plus a status predicate, in a body carrying
1073
+ // nothing else. This is what catches a sentence the codebase has
1074
+ // never contained, including one declared as a `reply` by an author
1075
+ // who routed around the origin test. Narrow by construction: a real
1076
+ // answer that reports the WORK failing has no apparatus subject,
1077
+ // and anything carrying a link, a fence, a list or real length is
1078
+ // exonerated outright. See `lib/comms/machine-status.mjs`.
1079
+ //
1080
+ // Permanent, like the other two refusals here: retrying re-runs a
1081
+ // deterministic screen and gets the same answer. The obligation is not lost —
1082
+ // `noteNoSend` writes the receipt and the assurance sweep's `escalate` has
1083
+ // already written the `needs-attention` row an operator sweeps.
1084
+ if (isMachineStatusDeliveryKind(kind)) {
1085
+ try { console.error(`[deliver] refused: machine-status delivery kind ${JSON.stringify(kind)} — status about this machine's own work goes to the operator plane (needs-attention, counters, logs), never to a conversation (permanent, not retrying)`); } catch { /* */ }
1086
+ return noteNoSend(item, o, { sent: false, via: null, permanent: true, channel: item && item.channel_id, code: "FORBIDDEN_SCOPE", error: `FORBIDDEN_SCOPE: machine-status kind "${kind}" may not be delivered to a conversation — route it to the operator plane` });
1087
+ }
1088
+ const narration = machineStatusNarration(text);
1089
+ if (narration) {
1090
+ try { console.error(`[deliver] refused: outbound body narrates this machine's own apparatus (${JSON.stringify(narration)}) — a person is owed the answer or nothing, not a status line (permanent, not retrying)`); } catch { /* */ }
1091
+ return noteNoSend(item, o, { sent: false, via: null, permanent: true, channel: item && item.channel_id, code: "FORBIDDEN_SCOPE", error: `FORBIDDEN_SCOPE: machine-status narration in outbound body (${narration}) — this belongs in the operator plane, not in a conversation` });
1092
+ }
1093
+ // ── THE THIRD SHAPE: ONE OF THIS DAEMON'S OWN TEMPLATES, WITH NO ANSWER ───
1094
+ //
1095
+ // Found by an adversarial pass on 2026-10-02, which got one through both gates
1096
+ // above. `composeSilentSuccess` with no result text —
1097
+ //
1098
+ // Finished this but didn't get a reply out to you — my fault. I don't have a
1099
+ // clean result to show you, though. Want me to run it again?
1100
+ //
1101
+ // — is machine status wearing a reply's `kind`: the ORIGIN test never sees it,
1102
+ // and the SHAPE test finds no apparatus noun in it. `composeRefusedSend` with
1103
+ // no result text is the same. Both are now routed to the operator plane at the
1104
+ // emitter; this is the backstop, because the emitter decision is one `if` and
1105
+ // this subsystem's guards have been accidentally undone three times.
1106
+ //
1107
+ // EXACT, DERIVED, AND IT CANNOT EAT AN ANSWER. `isOwnNarratorText` matches a
1108
+ // body against patterns DERIVED FROM THE COMPOSERS THEMSELVES (so a reworded
1109
+ // template is still recognised, which a literal register could not do), anchored
1110
+ // `^…$` over the whole body. The one-paragraph condition is what separates the
1111
+ // two shapes of those composers: both of them put the session's result text in
1112
+ // a SECOND paragraph, so a body with no second paragraph is the template alone.
1113
+ // A real reply that happens to open with a familiar phrase cannot match, because
1114
+ // the match is the entire body, not a prefix.
1115
+ //
1116
+ // Lazily imported: `assurance.mjs` imports this module, and the patterns are
1117
+ // derived from composers that live there. Fails OPEN — an import error must
1118
+ // never hold up a real reply.
1119
+ const answerless = await answerlessOwnTemplate(text);
1120
+ if (answerless) {
1121
+ try { console.error(`[deliver] refused: outbound body is this daemon's own status template with no answer in it — ${JSON.stringify(answerless)} (permanent, not retrying)`); } catch { /* */ }
1122
+ return noteNoSend(item, o, { sent: false, via: null, permanent: true, channel: item && item.channel_id, code: "FORBIDDEN_SCOPE", error: `FORBIDDEN_SCOPE: machine-status template with no work product in it — route it to the operator plane, not to a conversation` });
1123
+ }
1020
1124
  const leak = scaffoldMarkerLeak(text);
1021
1125
  if (leak) {
1022
1126
  const surface = (item && item.channel_id) ? "room" : "unknown";