switchroom 0.19.22 → 0.19.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-scheduler/index.js +5 -2
- package/dist/auth-broker/index.js +95 -2
- package/dist/cli/notion-write-pretool.mjs +5 -2
- package/dist/cli/switchroom.js +749 -357
- package/dist/host-control/main.js +96 -3
- package/dist/vault/approvals/kernel-server.js +98 -5
- package/dist/vault/broker/server.js +98 -5
- package/package.json +5 -4
- package/profiles/_base/start.sh.hbs +101 -0
- package/profiles/_shared/agent-self-service.md.hbs +64 -109
- package/profiles/_shared/delegation-golden-rule.md.hbs +5 -5
- package/profiles/_shared/dev-protocol.md.hbs +12 -42
- package/profiles/_shared/execution-discipline.md.hbs +7 -14
- package/profiles/coding/CLAUDE.md.hbs +0 -6
- package/profiles/default/CLAUDE.md.hbs +21 -50
- package/skills/dev-protocol/SKILL.md +97 -107
- package/skills/switchroom-release/SKILL.md +2 -1
- package/telegram-plugin/bunfig.toml +10 -0
- package/telegram-plugin/dist/gateway/gateway.js +267 -52
- package/telegram-plugin/gateway/backstop-delivery.ts +97 -16
- package/telegram-plugin/gateway/captured-answer-resume.ts +46 -17
- package/telegram-plugin/gateway/gateway.ts +43 -42
- package/telegram-plugin/gateway/latest-turn-lookup.ts +60 -0
- package/telegram-plugin/gateway/outbound-send-path.ts +61 -22
- package/telegram-plugin/gateway/stream-render.ts +6 -0
- package/telegram-plugin/gateway/subagent-handback-marker.ts +1 -1
- package/telegram-plugin/gateway/turn-end.ts +1 -1
- package/telegram-plugin/gateway/turn-record-status.ts +19 -0
- package/telegram-plugin/gateway/turns-jsonl-rotate.ts +65 -0
- package/telegram-plugin/reply-owner-resolve.ts +110 -9
- package/telegram-plugin/send-gate-degraded.test.ts +45 -16
- package/telegram-plugin/send-gate.ts +185 -24
- package/telegram-plugin/tests/activity-card-send-gate.test.ts +9 -9
- package/telegram-plugin/tests/agent-state-dir-preload.test.ts +33 -0
- package/telegram-plugin/tests/backstop-delivery.test.ts +204 -7
- package/telegram-plugin/tests/backstop-readback-probe.test.ts +12 -0
- package/telegram-plugin/tests/captured-answer-resume.test.ts +104 -0
- package/telegram-plugin/tests/latest-turn-lookup.test.ts +77 -0
- package/telegram-plugin/tests/narrative-lane-golden.test.ts +23 -1
- package/telegram-plugin/tests/reply-owner-resolve.test.ts +531 -0
- package/telegram-plugin/tests/send-reply-golden.test.ts +296 -28
- package/telegram-plugin/tests/stream-controller-send-gate.test.ts +134 -28
- package/telegram-plugin/tests/stream-render-golden.test.ts +25 -3
- package/telegram-plugin/tests/turns-jsonl-rotate.test.ts +92 -1
- package/vendor/hindsight-memory/scripts/drain_pending.py +113 -11
- package/vendor/hindsight-memory/scripts/lib/pending.py +802 -65
- package/vendor/hindsight-memory/scripts/lib/retain_split.py +54 -7
- package/vendor/hindsight-memory/scripts/tests/test_pending_drops.py +1445 -11
- package/vendor/hindsight-memory/scripts/tests/test_retain_split.py +78 -6
- package/vendor/hindsight-memory/tests/test_drain_pending.py +17 -2
- package/vendor/hindsight-memory/tests/test_pending.py +12 -4
|
@@ -62,7 +62,12 @@ import {
|
|
|
62
62
|
DEFAULT_SUPERSEDE_TTL_MS,
|
|
63
63
|
type FlushedTurnSupersedeRegistry,
|
|
64
64
|
} from '../flushed-turn-supersede.js'
|
|
65
|
-
import {
|
|
65
|
+
import {
|
|
66
|
+
decideAnswerLatchSuppression,
|
|
67
|
+
decideContentGateBypass,
|
|
68
|
+
type ReplyOwnerTier,
|
|
69
|
+
type ReplyOwnerCandidates,
|
|
70
|
+
} from '../reply-owner-resolve.js'
|
|
66
71
|
import { deriveTelegraphTitle } from '../telegraph.js'
|
|
67
72
|
import {
|
|
68
73
|
mayInjectListenButton,
|
|
@@ -611,7 +616,14 @@ export function createBackstopReadBack(
|
|
|
611
616
|
}
|
|
612
617
|
try {
|
|
613
618
|
const r = await w.gate(() => w.editMessageText(messageId, body, editApiOpts), gateOpts)
|
|
614
|
-
|
|
619
|
+
// A shed resolves the SEND_GATE_SHED sentinel; a gate no-op drop (the
|
|
620
|
+
// identical payload is already the last one sent for this message id) or
|
|
621
|
+
// an expired queue entry resolves `undefined`. In BOTH cases the edit
|
|
622
|
+
// never reached Telegram, so there is no evidence of existence —
|
|
623
|
+
// `ambiguous`, never a fabricated `exists`. Only a real API result
|
|
624
|
+
// (grammy resolves `true` or the edited Message) proves presence.
|
|
625
|
+
if (w.isShed(r) || r === undefined) return 'ambiguous'
|
|
626
|
+
return 'exists'
|
|
615
627
|
} catch (err) {
|
|
616
628
|
return classifyReadBackError(err)
|
|
617
629
|
}
|
|
@@ -719,7 +731,13 @@ export interface SendReplyGatewayDeps {
|
|
|
719
731
|
assertSendable(f: string): void
|
|
720
732
|
statusKey(chatId: string, threadId?: number | null): string
|
|
721
733
|
streamKey(chatId: string, threadId?: number | null): string
|
|
722
|
-
|
|
734
|
+
/** Resolves the owner turn AND returns the CANDIDATE SET it was derived from.
|
|
735
|
+
* The candidates are load-bearing, not diagnostics: `decideContentGateBypass`
|
|
736
|
+
* corroborates a model-steerable `origin`/`quoted` attribution against the
|
|
737
|
+
* framework-derived `latestEndedTurnId` inside them before allowing a
|
|
738
|
+
* content-gate bypass — an anchor that is an ENDED turn within the supersede
|
|
739
|
+
* TTL, never one still running (#3725). */
|
|
740
|
+
resolveReplyOwnerTurn(liveTurn: CurrentTurn | null, chatId: string, args: Record<string, unknown>): { turn: CurrentTurn | null; tier: ReplyOwnerTier; candidates: ReplyOwnerCandidates }
|
|
723
741
|
findTurnByOriginId(originTurnId: string | null | undefined): CurrentTurn | null
|
|
724
742
|
findTurnByQuotedMessageId(chatId: string, replyTo: unknown): CurrentTurn | null
|
|
725
743
|
resolveAnswerThreadWithLog(
|
|
@@ -939,7 +957,11 @@ export async function sendReply(
|
|
|
939
957
|
// double-send). The quoted / latest-ended recoveries are precisely what the
|
|
940
958
|
// router already did for the same reply, so unifying here makes the two
|
|
941
959
|
// resolvers agree and the late-reply supersede fires by identity.
|
|
942
|
-
const {
|
|
960
|
+
const {
|
|
961
|
+
turn: ownerTurn,
|
|
962
|
+
tier: ownerTier,
|
|
963
|
+
candidates: ownerCandidates,
|
|
964
|
+
} = resolveReplyOwnerTurn(turn, chat_id, args)
|
|
943
965
|
const resolvedTurnId = ownerTurn?.turnId ?? null
|
|
944
966
|
// #3429 — pass the (normalized) reply text so the registry CAN apply the
|
|
945
967
|
// new-content gate: identity match + TTL alone also fits a background
|
|
@@ -991,7 +1013,7 @@ export async function sendReply(
|
|
|
991
1013
|
// owner turn resolved (no record to clobber on the collapse path).
|
|
992
1014
|
const gateThreadId = ownerTurn?.sessionThreadId ?? replyThreadId
|
|
993
1015
|
// MUST-FIX 2 (dup-audit / Fable) — the content-gate READ is CHAT-WIDE, not
|
|
994
|
-
// lane-specific: `
|
|
1016
|
+
// lane-specific: `findLatestTurnForChat` resolves owners chat-wide, so a
|
|
995
1017
|
// handback in topic A can supersede topic B's ended turn; a thread-keyed gate
|
|
996
1018
|
// read (the F2 regression) let a reply dodge that handback by carrying a
|
|
997
1019
|
// different `message_thread_id`. Chat-wide makes the gate un-steerable — any
|
|
@@ -1007,23 +1029,35 @@ export async function sendReply(
|
|
|
1007
1029
|
ownerEndedAt != null &&
|
|
1008
1030
|
handbackAt > ownerEndedAt &&
|
|
1009
1031
|
now - handbackAt <= DEFAULT_SUPERSEDE_TTL_MS
|
|
1010
|
-
// MUST-FIX 1 (silent-data-loss, PROVEN by Fable 2026-07-21)
|
|
1011
|
-
//
|
|
1012
|
-
//
|
|
1013
|
-
//
|
|
1014
|
-
//
|
|
1032
|
+
// MUST-FIX 1 (silent-data-loss, PROVEN by Fable 2026-07-21) + the 2026-07-27
|
|
1033
|
+
// corroboration widening — decided by the pure `decideContentGateBypass` so
|
|
1034
|
+
// the gateway runs the exact code the unit tests exercise. The rule, in
|
|
1035
|
+
// brief (full rationale on that function):
|
|
1036
|
+
// - `live` — framework-owned live `currentTurn`; bypasses unconditionally
|
|
1037
|
+
// (`decideSupersede`'s same-turnId check already bars it from
|
|
1038
|
+
// a DIFFERENT ended turn's record).
|
|
1015
1039
|
// - `latest-ended` — the ambiguous DM/late-reply fallback the marko fix
|
|
1016
|
-
//
|
|
1017
|
-
//
|
|
1018
|
-
//
|
|
1019
|
-
//
|
|
1020
|
-
//
|
|
1021
|
-
//
|
|
1022
|
-
//
|
|
1023
|
-
//
|
|
1024
|
-
//
|
|
1025
|
-
|
|
1026
|
-
|
|
1040
|
+
// needs; bypass ONLY when no decoupled completion is in the
|
|
1041
|
+
// window (marker-absence ⇒ own answer).
|
|
1042
|
+
// - `origin` / `quoted` — MODEL-SUPPLIED attributions, so they bypass ONLY
|
|
1043
|
+
// when CORROBORATED: the turn they resolve must be the same
|
|
1044
|
+
// turn the framework-derived, TTL-bounded `latestEndedTurnId`
|
|
1045
|
+
// resolves (#3725 — that anchor is a genuinely ENDED turn
|
|
1046
|
+
// within the TTL; a turn still RUNNING in this chat is not a
|
|
1047
|
+
// candidate and corroborates nothing), and no handback may be
|
|
1048
|
+
// in the window. A reply that
|
|
1049
|
+
// steers itself onto a DIFFERENT ended turn fails
|
|
1050
|
+
// corroboration and keeps the content gate, so the Fable
|
|
1051
|
+
// silent-edit-over stays closed; a reply that merely echoes
|
|
1052
|
+
// its OWN turn no longer loses the collapse it would have got
|
|
1053
|
+
// by omitting the echo entirely (the observed 2026-07-27
|
|
1054
|
+
// `via=origin` duplicate).
|
|
1055
|
+
const replyIsOwnAnswer = decideContentGateBypass({
|
|
1056
|
+
tier: ownerTier,
|
|
1057
|
+
resolvedTurnId,
|
|
1058
|
+
candidates: ownerCandidates,
|
|
1059
|
+
handbackCouldOwnReply,
|
|
1060
|
+
})
|
|
1027
1061
|
const decision = flushedTurnSupersede.take(
|
|
1028
1062
|
chat_id,
|
|
1029
1063
|
gateThreadId,
|
|
@@ -1107,7 +1141,12 @@ export async function sendReply(
|
|
|
1107
1141
|
if (decision.reason === 'new-content') {
|
|
1108
1142
|
process.stderr.write(
|
|
1109
1143
|
`telegram gateway: reply: flush supersede declined — new content (#3429) ` +
|
|
1110
|
-
`chatId=${chat_id} ownerTurnId=${JSON.stringify(resolvedTurnId)}
|
|
1144
|
+
`chatId=${chat_id} ownerTurnId=${JSON.stringify(resolvedTurnId)} ` +
|
|
1145
|
+
// WHY the bypass didn't apply — without these two fields the
|
|
1146
|
+
// 2026-07-27 duplicate looked like a pure text-matcher failure and
|
|
1147
|
+
// took a log-archive dig to attribute to the tier restriction.
|
|
1148
|
+
`tier=${ownerTier} latestEnded=${JSON.stringify(ownerCandidates.latestEndedTurnId)} ` +
|
|
1149
|
+
`handbackInWindow=${handbackCouldOwnReply}; sending fresh\n`,
|
|
1111
1150
|
)
|
|
1112
1151
|
}
|
|
1113
1152
|
if (suppressByLatch) {
|
|
@@ -1856,6 +1856,12 @@ export function handleSessionEvent(deps: StreamRenderDeps, ev: SessionEvent): vo
|
|
|
1856
1856
|
sentIds = delivery.sentIds
|
|
1857
1857
|
chunkCount = delivery.chunkCount
|
|
1858
1858
|
delivered = delivery.delivered
|
|
1859
|
+
// #3702 — how many landed ids the read-back never corroborated.
|
|
1860
|
+
// Stamped on the turn so `emitTurnRecord` writes `landed_unconfirmed`
|
|
1861
|
+
// (omitted when 0): the fleet-visible counter for deliveries we call
|
|
1862
|
+
// `complete` on the Bot API's ack alone, because the probe is
|
|
1863
|
+
// inconclusive. Observational only — it never changes the status.
|
|
1864
|
+
turn.landedUnconfirmed = delivery.landedUnconfirmed
|
|
1859
1865
|
|
|
1860
1866
|
// #546 dedup: record what turn-flush just sent so a late-arriving
|
|
1861
1867
|
// reply / stream_reply with the same content gets suppressed.
|
|
@@ -201,7 +201,7 @@ export class SubagentHandbackMarker {
|
|
|
201
201
|
* Wall-clock ms of the most recent handback enqueue ANYWHERE in `chatId`
|
|
202
202
|
* (across every topic lane), or null. This is what the content-gate read uses
|
|
203
203
|
* (dup-audit MUST-FIX 2, Fable 2026-07-21): the owner-resolution latest-ended
|
|
204
|
-
* tier is CHAT-WIDE (`
|
|
204
|
+
* tier is CHAT-WIDE (`findLatestTurnForChat` ignores thread), so a
|
|
205
205
|
* background handback in topic A can resolve — and supersede — topic B's
|
|
206
206
|
* ended turn. A thread-SPECIFIC gate read (the F2 regression) let a reply
|
|
207
207
|
* dodge that handback by carrying a different `message_thread_id`, silently
|
|
@@ -436,7 +436,7 @@ function endCurrentTurnAtomic(
|
|
|
436
436
|
// live feed never opened because its sends failed (the resume-400 signature).
|
|
437
437
|
const turnEndedAt = Date.now()
|
|
438
438
|
// 2026-07 double-reply-on-DM fix (F2) — stamp the turn's end time so the
|
|
439
|
-
// `
|
|
439
|
+
// `latest-ended` supersede tier can be recency-bounded to the
|
|
440
440
|
// supersede TTL (a stale latest-ended turn must not inherit deletion
|
|
441
441
|
// authority over a newer turn's flush record). Set once; idempotent on the
|
|
442
442
|
// deferRecord flush path (which calls this synchronously before its send).
|
|
@@ -148,6 +148,20 @@ export interface TurnRecordRow {
|
|
|
148
148
|
tools: number
|
|
149
149
|
status: TurnStatus
|
|
150
150
|
turn_id: string
|
|
151
|
+
/**
|
|
152
|
+
* How many landed message ids of this turn's backstop delivery the read-back
|
|
153
|
+
* probe never corroborated (`sentIds` minus the confirmed subset). OMITTED
|
|
154
|
+
* when zero, so an ordinary row is byte-identical to before.
|
|
155
|
+
*
|
|
156
|
+
* This is the measurable counterpart of the delivery verdict: since an
|
|
157
|
+
* inconclusive probe counts as delivered, a `complete` row carrying
|
|
158
|
+
* `landed_unconfirmed > 0` is a turn we called delivered on the Bot API's
|
|
159
|
+
* ack alone. Counting those is how the fleet can tell whether that optimism
|
|
160
|
+
* is ever wrong (a `landed_unconfirmed` turn followed by a "you never
|
|
161
|
+
* answered me" is the falsifying observation). It is NOT a failure signal and
|
|
162
|
+
* nothing escalates on it.
|
|
163
|
+
*/
|
|
164
|
+
landed_unconfirmed?: number
|
|
151
165
|
}
|
|
152
166
|
|
|
153
167
|
/**
|
|
@@ -165,6 +179,7 @@ export function buildTurnRecord(
|
|
|
165
179
|
turnId: string
|
|
166
180
|
finalAnswerDelivered: boolean
|
|
167
181
|
deliveryOutcome?: DeliveryOutcome
|
|
182
|
+
landedUnconfirmed?: number
|
|
168
183
|
},
|
|
169
184
|
endedAt: number,
|
|
170
185
|
): TurnRecordRow {
|
|
@@ -175,5 +190,9 @@ export function buildTurnRecord(
|
|
|
175
190
|
tools: turn.toolCallCount ?? 0,
|
|
176
191
|
status: computeTurnStatus(turn),
|
|
177
192
|
turn_id: turn.turnId,
|
|
193
|
+
// Emitted ONLY when non-zero (see `TurnRecordRow.landed_unconfirmed`).
|
|
194
|
+
...(turn.landedUnconfirmed != null && turn.landedUnconfirmed > 0
|
|
195
|
+
? { landed_unconfirmed: turn.landedUnconfirmed }
|
|
196
|
+
: {}),
|
|
178
197
|
}
|
|
179
198
|
}
|
|
@@ -13,6 +13,71 @@
|
|
|
13
13
|
*/
|
|
14
14
|
export const TURNS_JSONL_MAX_BYTES = 5 * 1024 * 1024 // 5 MiB
|
|
15
15
|
|
|
16
|
+
/** The agent state dir inside a switchroom agent container (bind-mounted to
|
|
17
|
+
* `~/.switchroom/agents/<name>/` on the host). */
|
|
18
|
+
export const DEFAULT_AGENT_STATE_DIR = '/state/agent'
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Resolve the agent state dir from the environment — the ONE reader for
|
|
22
|
+
* `SWITCHROOM_AGENT_STATE_DIR` that every writer into that dir must use.
|
|
23
|
+
*
|
|
24
|
+
* Normalisation is the point. The gateway had two writers into this dir a few
|
|
25
|
+
* lines apart (the context-occupancy snapshot and the turn record) reading the
|
|
26
|
+
* env var with two different expressions: a bare
|
|
27
|
+
* `process.env.SWITCHROOM_AGENT_STATE_DIR ?? '/state/agent'` and this one. For
|
|
28
|
+
* a value like `"/x/ "` or `"/x/"` those resolve to DIFFERENT directories, so
|
|
29
|
+
* the two artifacts of the same turn would land in two places — exactly the
|
|
30
|
+
* kind of split-brain state that made the turn-record leak hard to see. Both
|
|
31
|
+
* call sites now share this function.
|
|
32
|
+
*
|
|
33
|
+
* Blank/whitespace-only is treated as unset (a compose file that renders an
|
|
34
|
+
* empty value must not send state to `/turns.jsonl` at the filesystem root),
|
|
35
|
+
* and a trailing slash is stripped so joins never double it.
|
|
36
|
+
*/
|
|
37
|
+
export function resolveAgentStateDir(
|
|
38
|
+
env: Record<string, string | undefined> = process.env,
|
|
39
|
+
): string {
|
|
40
|
+
const dir = env.SWITCHROOM_AGENT_STATE_DIR?.trim()
|
|
41
|
+
return dir != null && dir !== '' ? dir.replace(/\/+$/, '') : DEFAULT_AGENT_STATE_DIR
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Resolve the turn-record path from the environment.
|
|
46
|
+
*
|
|
47
|
+
* `emitTurnRecord` used to hard-code `/state/agent/turns.jsonl`, ignoring
|
|
48
|
+
* `SWITCHROOM_AGENT_STATE_DIR` — which the sibling context-occupancy writer a
|
|
49
|
+
* few lines above it in `gateway.ts` already honours. Inside an agent container
|
|
50
|
+
* that path is the bind-mounted PRODUCTION `~/.switchroom/agents/<name>/
|
|
51
|
+
* turns.jsonl`, so any test that drove the real turn-end funnel while running
|
|
52
|
+
* in an agent container appended its synthetic rows straight into that agent's
|
|
53
|
+
* production turn record — even when the test had pointed every state-dir env
|
|
54
|
+
* var at a tmpdir. Those rows are then read back by the fleet-health L0 sensor
|
|
55
|
+
* (`src/fleet-health/scan.ts`) as that agent's real production turns.
|
|
56
|
+
*
|
|
57
|
+
* Honouring the env var is the root-cause fix: production containers do not set
|
|
58
|
+
* it (default unchanged), and a test that isolates its state dir now isolates
|
|
59
|
+
* its turn records with it.
|
|
60
|
+
*
|
|
61
|
+
* ── Operator coupling: setting this var RELOCATES the fleet-health input ──
|
|
62
|
+
*
|
|
63
|
+
* `agent.env` in `switchroom.yaml` is propagated verbatim into the container
|
|
64
|
+
* (`src/agents/compose.ts` `userEnv`), so an operator CAN set
|
|
65
|
+
* `SWITCHROOM_AGENT_STATE_DIR` on an agent. If they point it anywhere other
|
|
66
|
+
* than the bind-mounted `/state/agent`, this file moves with it — but the
|
|
67
|
+
* fleet-health L0 sensor reads `~/.switchroom/agents/<name>/turns.jsonl` at a
|
|
68
|
+
* FIXED host path (`src/fleet-health/scan.ts`). That agent then presents no
|
|
69
|
+
* turns artifact, lands in the scan's `skipped[]`, and goes quiet on the health
|
|
70
|
+
* board: no findings, no ledger entries, indistinguishable from a healthy
|
|
71
|
+
* agent. Do not set this var in production `agent.env`; it exists so tests (and
|
|
72
|
+
* the vitest `agent-state-dir-guard` setup file) can isolate agent state into a
|
|
73
|
+
* tmpdir.
|
|
74
|
+
*/
|
|
75
|
+
export function resolveTurnsJsonlPath(
|
|
76
|
+
env: Record<string, string | undefined> = process.env,
|
|
77
|
+
): string {
|
|
78
|
+
return `${resolveAgentStateDir(env)}/turns.jsonl`
|
|
79
|
+
}
|
|
80
|
+
|
|
16
81
|
export interface RotateFs {
|
|
17
82
|
statSize: (path: string) => number | undefined // undefined ⇒ file absent
|
|
18
83
|
rename: (from: string, to: string) => void
|
|
@@ -25,8 +25,8 @@
|
|
|
25
25
|
*
|
|
26
26
|
* The DECISIVE divergence: the gateway's *thread-routing* path DID recover the
|
|
27
27
|
* owner turn for the same late reply — via `findTurnByQuotedMessageId` (the
|
|
28
|
-
* framework-owned default quote target) and `
|
|
29
|
-
* chat's most
|
|
28
|
+
* framework-owned default quote target) and `findLatestTurnForChat` (the
|
|
29
|
+
* chat's most recent turn). The supersede resolver chain omitted BOTH
|
|
30
30
|
* recoveries, so the two resolvers disagreed on who owned the reply. This module
|
|
31
31
|
* unifies them onto ONE precedence so they can never diverge again.
|
|
32
32
|
*
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
* `decideCapturedProseDelivery` — is to extract the decision core into a pure,
|
|
38
38
|
* unit-testable function and have the gateway run the EXACT code the regression
|
|
39
39
|
* tests exercise. The gateway performs the four turn lookups (currentTurn,
|
|
40
|
-
* findTurnByOriginId, findTurnByQuotedMessageId,
|
|
40
|
+
* findTurnByOriginId, findTurnByQuotedMessageId, findLatestTurnForChat) and
|
|
41
41
|
* feeds their resolved turnIds here; the precedence lives in one place.
|
|
42
42
|
*/
|
|
43
43
|
|
|
@@ -56,16 +56,25 @@ export interface ReplyOwnerCandidates {
|
|
|
56
56
|
/** `findTurnByQuotedMessageId(chat_id, reply_to)` — the framework-owned
|
|
57
57
|
* quoted message id, resolved with NO model thread assertion. */
|
|
58
58
|
quotedTurnId: string | null
|
|
59
|
-
/** `
|
|
60
|
-
* turn. The deterministic late-reply fallback (the DM
|
|
59
|
+
/** `findLatestTurnForChat(chat_id, {endedOnly:true})` — the chat's
|
|
60
|
+
* most-recently-ENDED turn. The deterministic late-reply fallback (the DM
|
|
61
|
+
* path's recovery). #3725: the gateway lookup skips turns that have not
|
|
62
|
+
* ended, so this is never a still-running turn. */
|
|
61
63
|
latestEndedTurnId: string | null
|
|
62
64
|
/** Age (ms) of the latest-ended turn — `now - turn.endedAt`. The latest-ended
|
|
63
65
|
* tier carries DESTRUCTIVE authority (it drives supersede deletion), so it is
|
|
64
66
|
* honoured ONLY when the turn ended within `latestEndedTtlMs` (the supersede
|
|
65
67
|
* TTL). Without the bound, a late reply belonging to an OLDER turn could
|
|
66
68
|
* resolve its owner to a NEWER turn now sitting at the registry tail and
|
|
67
|
-
* delete THAT turn's legit answer.
|
|
68
|
-
*
|
|
69
|
+
* delete THAT turn's legit answer.
|
|
70
|
+
*
|
|
71
|
+
* Two distinct absences (#3725):
|
|
72
|
+
* - `undefined` (property omitted) ⇒ unbounded, the pre-F2 back-compat
|
|
73
|
+
* escape for callers that don't supply an age at all;
|
|
74
|
+
* - explicit `null` ⇒ the caller COMPUTED no age, i.e. its candidate turn
|
|
75
|
+
* has no `endedAt` and has NOT ended. That cannot be TTL-bounded, so it
|
|
76
|
+
* fails CLOSED (not accepted) rather than granting unbounded authority
|
|
77
|
+
* to a turn that is still running. */
|
|
69
78
|
latestEndedAgeMs?: number | null
|
|
70
79
|
/** The supersede TTL bound applied to `latestEndedAgeMs`. Undefined ⇒
|
|
71
80
|
* unbounded. */
|
|
@@ -74,13 +83,17 @@ export interface ReplyOwnerCandidates {
|
|
|
74
83
|
|
|
75
84
|
/**
|
|
76
85
|
* Whether the latest-ended candidate is fresh enough to carry supersede
|
|
77
|
-
* (deletion) authority.
|
|
86
|
+
* (deletion) authority. An OMITTED age or TTL means unbounded (the pre-F2
|
|
87
|
+
* back-compat escape); an EXPLICIT null age fails closed (#3725 — the caller
|
|
88
|
+
* computed no age because its candidate turn has not ended, and an un-ended turn
|
|
89
|
+
* must be resolved by the `live` tier, never by this destructive fallback).
|
|
78
90
|
*/
|
|
79
91
|
function latestEndedAccepted(candidates: ReplyOwnerCandidates): boolean {
|
|
80
92
|
if (candidates.latestEndedTurnId == null) return false
|
|
81
93
|
const age = candidates.latestEndedAgeMs
|
|
82
94
|
const ttl = candidates.latestEndedTtlMs
|
|
83
|
-
if (age
|
|
95
|
+
if (age === null) return false
|
|
96
|
+
if (age === undefined || ttl == null) return true
|
|
84
97
|
return age <= ttl
|
|
85
98
|
}
|
|
86
99
|
|
|
@@ -143,6 +156,94 @@ export function resolveReplyOwnerTurnId(candidates: ReplyOwnerCandidates): strin
|
|
|
143
156
|
}
|
|
144
157
|
}
|
|
145
158
|
|
|
159
|
+
/**
|
|
160
|
+
* Whether the supersede path may BYPASS the #3429 content gate — i.e. treat the
|
|
161
|
+
* landing reply as this flushed turn's OWN answer and collapse the provisional
|
|
162
|
+
* flush REGARDLESS of the model having reworded it.
|
|
163
|
+
*
|
|
164
|
+
* ## Why this is not simply "the tier is positive"
|
|
165
|
+
*
|
|
166
|
+
* The pre-existing rule was `tier === 'live' || (tier === 'latest-ended' &&
|
|
167
|
+
* !handbackCouldOwnReply)`. `origin` and `quoted` were excluded WHOLESALE
|
|
168
|
+
* because both derive from MODEL-SUPPLIED args (`args.origin_turn_id` /
|
|
169
|
+
* `args.reply_to`): a reply can STEER its own attribution onto a DIFFERENT
|
|
170
|
+
* ended turn and, with the gate bypassed, silently edit over that turn's
|
|
171
|
+
* delivered answer (the #3429 double-loss, executed by Fable 2026-07-21).
|
|
172
|
+
*
|
|
173
|
+
* That wholesale exclusion over-fires. Observed 2026-07-27 on a DM agent (two
|
|
174
|
+
* answers delivered twice): the answer-ready quiescence flush posted the turn's
|
|
175
|
+
* composed prose as message A, the model then fired `reply` with a REWORDED
|
|
176
|
+
* version of the SAME answer, and — because it had echoed `origin_turn_id` back
|
|
177
|
+
* pointing at its OWN turn — the tier resolved `origin` rather than
|
|
178
|
+
* `latest-ended`, so no bypass applied and the content gate declined on the
|
|
179
|
+
* rewording (`reply: flush supersede declined — new content (#3429)`). Message B
|
|
180
|
+
* shipped as a visible duplicate. Had the model simply OMITTED the echo, the
|
|
181
|
+
* identical reply would have resolved `latest-ended` and collapsed to ONE
|
|
182
|
+
* message. The exclusion punished the model for supplying MORE information.
|
|
183
|
+
*
|
|
184
|
+
* ## The rule: corroborate the steerable tier, don't blanket-ban it
|
|
185
|
+
*
|
|
186
|
+
* A model-supplied attribution is dangerous only when it points somewhere the
|
|
187
|
+
* FRAMEWORK would not have gone on its own. So `origin`/`quoted` bypass the
|
|
188
|
+
* content gate IFF the turn they resolve is the SAME turn the framework-derived,
|
|
189
|
+
* TTL-bounded `latest-ended` candidate resolves — a candidate computed from
|
|
190
|
+
* `findLatestTurnForChat(chat_id, {endedOnly:true})` with no model input at all.
|
|
191
|
+
* "TTL-bounded" is enforced, not assumed (#3725): `latestEndedAccepted` demands
|
|
192
|
+
* an age within `latestEndedTtlMs`, and an anchor turn that has NOT ended (age
|
|
193
|
+
* explicitly null) is rejected outright rather than treated as unbounded — so a
|
|
194
|
+
* turn still running in another topic of the same chat can corroborate nothing.
|
|
195
|
+
*
|
|
196
|
+
* This grants ZERO new capability, which is the safety argument: any reply that
|
|
197
|
+
* reaches the bypass via a corroborated `origin`/`quoted` attribution could
|
|
198
|
+
* already have reached it by omitting `origin_turn_id`/`reply_to` entirely and
|
|
199
|
+
* landing on `latest-ended` with the same turn and the same outcome. Steering to
|
|
200
|
+
* a DIFFERENT ended turn breaks corroboration (`origin` id ≠ latest-ended id),
|
|
201
|
+
* so the gate holds and the #3429/Fable silent-edit-over defence is untouched.
|
|
202
|
+
*
|
|
203
|
+
* `latest-ended` corroborates itself trivially (its resolved id IS the
|
|
204
|
+
* latest-ended candidate), so the rule below SUBSUMES the previous behaviour on
|
|
205
|
+
* that tier rather than changing it.
|
|
206
|
+
*
|
|
207
|
+
* `live` keeps its unconditional bypass: `currentTurn` is framework-owned, and
|
|
208
|
+
* `decideSupersede`'s same-turnId requirement already bars it from reaching a
|
|
209
|
+
* DIFFERENT ended turn's record. `none` never bypasses (nothing to attribute).
|
|
210
|
+
*/
|
|
211
|
+
export function decideContentGateBypass(input: {
|
|
212
|
+
/** The winning owner tier (`resolveReplyOwnerTier`). */
|
|
213
|
+
tier: ReplyOwnerTier
|
|
214
|
+
/** The owner turnId the supersede will act on (`resolveReplyOwnerTurnId`). */
|
|
215
|
+
resolvedTurnId: string | null
|
|
216
|
+
/** The SAME candidate set both of the above were derived from — supplies the
|
|
217
|
+
* framework-derived `latestEndedTurnId` plus its freshness bound, so the
|
|
218
|
+
* corroboration reuses the EXACT rule `resolveReplyOwnerTier` applies
|
|
219
|
+
* (`latestEndedAccepted`) instead of duplicating it: within the TTL, and —
|
|
220
|
+
* since #3725 — not a turn that is still running. */
|
|
221
|
+
candidates: ReplyOwnerCandidates
|
|
222
|
+
/** True when a decoupled-completion inbound (`subagent_handback`) was enqueued
|
|
223
|
+
* in this chat AFTER the owner turn ended and within the supersede TTL — the
|
|
224
|
+
* ambiguous window where the late reply might BE that handback rather than
|
|
225
|
+
* the turn's own answer. Keeps the content gate on every non-`live` tier. */
|
|
226
|
+
handbackCouldOwnReply: boolean
|
|
227
|
+
}): boolean {
|
|
228
|
+
if (input.tier === 'live') return true
|
|
229
|
+
if (input.tier === 'none') return false
|
|
230
|
+
if (input.handbackCouldOwnReply) return false
|
|
231
|
+
// Total over degenerate input (#3726). TypeScript makes `candidates` mandatory
|
|
232
|
+
// and the one production caller (`resolveReplyOwnerTurn`) always builds it, so
|
|
233
|
+
// this cannot fire today — but this module is exported precisely so the
|
|
234
|
+
// decision can be exercised OUTSIDE the gateway's construction discipline.
|
|
235
|
+
// Every other defensive branch here fails CLOSED (keep the #3429 content
|
|
236
|
+
// gate); without this guard the missing-input case instead fails by THROWING
|
|
237
|
+
// out of the supersede path — a fail-open-by-crash. Matches the module's own
|
|
238
|
+
// precedent: `latestEndedAccepted` is total over null age/ttl/turnId.
|
|
239
|
+
if (input.candidates == null) return false
|
|
240
|
+
if (!latestEndedAccepted(input.candidates)) return false
|
|
241
|
+
return (
|
|
242
|
+
input.resolvedTurnId != null &&
|
|
243
|
+
input.resolvedTurnId === input.candidates.latestEndedTurnId
|
|
244
|
+
)
|
|
245
|
+
}
|
|
246
|
+
|
|
146
247
|
/**
|
|
147
248
|
* The answer-delivered latch value — SOURCE-TAGGED (#3426).
|
|
148
249
|
*
|
|
@@ -113,7 +113,7 @@ describe('send-gate PR2: cosmetic shedding', () => {
|
|
|
113
113
|
expect(gate.stats().global.sent).toBe(1)
|
|
114
114
|
})
|
|
115
115
|
|
|
116
|
-
it('
|
|
116
|
+
it('COALESCES a cosmetic EDIT through an open message-edit window instead of shedding it (#3716)', async () => {
|
|
117
117
|
const clock = new FakeClock()
|
|
118
118
|
const { calls, fn } = recorder(clock)
|
|
119
119
|
const gate = createSendGate({
|
|
@@ -122,17 +122,35 @@ describe('send-gate PR2: cosmetic shedding', () => {
|
|
|
122
122
|
// H1: msg-edit scope is keyed `${chat_id}:${messageId}`.
|
|
123
123
|
initialWindows: [{ scopeKey: 'msg-edit:5:42', untilTs: HOUR }],
|
|
124
124
|
})
|
|
125
|
+
const opts = { chat_id: '5', messageId: 42, priorityClass: 'cosmetic' as const }
|
|
125
126
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
})
|
|
127
|
+
// A burst of cosmetic edits arrives while the window is wide open. The old
|
|
128
|
+
// behaviour dropped every one of them (SEND_GATE_SHED), which stranded the
|
|
129
|
+
// card on whatever body happened to be on screen when the window opened.
|
|
130
|
+
const p1 = gate.gate(fn('v1'), { ...opts, editPayload: 'v1' })
|
|
131
|
+
await flush()
|
|
132
|
+
const p2 = gate.gate(fn('v2'), { ...opts, editPayload: 'v2' })
|
|
133
|
+
await flush()
|
|
134
|
+
const p3 = gate.gate(fn('v3'), { ...opts, editPayload: 'v3' })
|
|
135
|
+
await flush()
|
|
132
136
|
|
|
133
|
-
|
|
137
|
+
// Nothing has hit the API yet — the window still suppresses the send, which
|
|
138
|
+
// is the flood protection doing its job.
|
|
134
139
|
expect(calls).toHaveLength(0)
|
|
135
|
-
|
|
140
|
+
// ...but nothing was DISCARDED either.
|
|
141
|
+
expect(gate.stats().global.shed).toBe(0)
|
|
142
|
+
|
|
143
|
+
// Walk past the window. Exactly ONE send lands, carrying the NEWEST payload:
|
|
144
|
+
// the burst was aggregated, not dropped, and not replayed edit-by-edit.
|
|
145
|
+
await clock.advance(HOUR + 1000)
|
|
146
|
+
await flush()
|
|
147
|
+
await Promise.allSettled([p1, p2, p3])
|
|
148
|
+
|
|
149
|
+
expect(calls.map((c) => c.label)).toEqual(['v3'])
|
|
150
|
+
expect(gate.stats().global.sent).toBe(1)
|
|
151
|
+
expect(gate.stats().global.shed).toBe(0)
|
|
152
|
+
// v1 and v2 were superseded in the pending slot (last-write-wins).
|
|
153
|
+
expect(gate.stats().global.coalesced).toBeGreaterThan(0)
|
|
136
154
|
})
|
|
137
155
|
})
|
|
138
156
|
|
|
@@ -343,7 +361,7 @@ describe('send-gate PR2: H1 cross-chat message_id isolation', () => {
|
|
|
343
361
|
expect(calls.every((c) => c.at === 0)).toBe(true)
|
|
344
362
|
})
|
|
345
363
|
|
|
346
|
-
it('a 429 on chat A message 100 does NOT
|
|
364
|
+
it('a 429 on chat A message 100 does NOT delay chat B message 100 cosmetic edits', async () => {
|
|
347
365
|
const clock = new FakeClock()
|
|
348
366
|
const { calls, fn } = recorder(clock)
|
|
349
367
|
const gate = createSendGate({
|
|
@@ -353,14 +371,17 @@ describe('send-gate PR2: H1 cross-chat message_id isolation', () => {
|
|
|
353
371
|
initialWindows: [{ scopeKey: 'msg-edit:A:100', untilTs: HOUR }],
|
|
354
372
|
})
|
|
355
373
|
|
|
356
|
-
// Chat A cosmetic edit →
|
|
357
|
-
|
|
374
|
+
// Chat A cosmetic edit → deferred, its scope window is open (#3716: deferred,
|
|
375
|
+
// NOT shed — the edit is held and lands with its state once the window ends).
|
|
376
|
+
const pA = gate.gate(fn('A-edit'), {
|
|
358
377
|
chat_id: 'A',
|
|
359
378
|
messageId: 100,
|
|
360
379
|
editPayload: 'A-edit',
|
|
361
380
|
priorityClass: 'cosmetic',
|
|
362
381
|
})
|
|
363
|
-
|
|
382
|
+
await flush()
|
|
383
|
+
// Chat B cosmetic edit to the SAME message_id → must be unaffected (different
|
|
384
|
+
// scope). This is the H1 isolation the test exists to guard.
|
|
364
385
|
const rB = await gate.gate(fn('B-edit'), {
|
|
365
386
|
chat_id: 'B',
|
|
366
387
|
messageId: 100,
|
|
@@ -368,10 +389,18 @@ describe('send-gate PR2: H1 cross-chat message_id isolation', () => {
|
|
|
368
389
|
priorityClass: 'cosmetic',
|
|
369
390
|
})
|
|
370
391
|
|
|
371
|
-
expect(
|
|
372
|
-
expect(rB).toBe('B-edit') // B sent
|
|
392
|
+
expect(rB).toBe('B-edit') // B sent immediately, unblocked by A's window
|
|
373
393
|
expect(calls.map((c) => c.label)).toEqual(['B-edit'])
|
|
374
|
-
|
|
394
|
+
// A is still pending, not discarded.
|
|
395
|
+
expect(gate.stats().global.shed).toBe(0)
|
|
396
|
+
|
|
397
|
+
// Once A's window closes, A's edit lands too — nothing was lost.
|
|
398
|
+
await clock.advance(HOUR + 1000)
|
|
399
|
+
await flush()
|
|
400
|
+
await Promise.allSettled([pA])
|
|
401
|
+
|
|
402
|
+
expect(calls.map((c) => c.label).sort()).toEqual(['A-edit', 'B-edit'])
|
|
403
|
+
expect(gate.stats().global.shed).toBe(0)
|
|
375
404
|
})
|
|
376
405
|
})
|
|
377
406
|
|