@sema-agent/server 7.5.0 → 7.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +18 -3
  3. package/README.zh-CN.md +14 -3
  4. package/USAGE.md +37 -1
  5. package/dist/approval-reconciler.d.ts +1 -1
  6. package/dist/approval-reconciler.js +6 -5
  7. package/dist/boot/config-center.js +15 -2
  8. package/dist/boot/execution-env.js +1 -1
  9. package/dist/boot/parked-revive-gate.d.ts +78 -0
  10. package/dist/boot/parked-revive-gate.js +114 -0
  11. package/dist/boot/resolve-spec.d.ts +3 -20
  12. package/dist/boot/resolve-spec.js +25 -119
  13. package/dist/budget.d.ts +1 -1
  14. package/dist/budget.js +1 -1
  15. package/dist/capabilities/repo-tools.d.ts +1 -1
  16. package/dist/capabilities/repo-tools.js +8 -2
  17. package/dist/config-provider.d.ts +1 -0
  18. package/dist/config-provider.js +23 -3
  19. package/dist/config-types.d.ts +5 -3
  20. package/dist/config.js +5 -4
  21. package/dist/deployment-governance.d.ts +168 -0
  22. package/dist/deployment-governance.js +206 -0
  23. package/dist/fleet/fleet-bus.d.ts +11 -1
  24. package/dist/fleet/fleet-bus.js +43 -0
  25. package/dist/fleet/fleet-terminal-window.d.ts +98 -0
  26. package/dist/fleet/fleet-terminal-window.js +316 -0
  27. package/dist/http/routes/approvals-assistant.js +6 -7
  28. package/dist/http/routes/fleet.js +160 -14
  29. package/dist/http/routes/runs.js +5 -1
  30. package/dist/http/routes/trace-usage.js +3 -4
  31. package/dist/http/send.d.ts +23 -0
  32. package/dist/http/send.js +23 -0
  33. package/dist/http/server.d.ts +4 -0
  34. package/dist/http/server.js +5 -2
  35. package/dist/http/sse-log.js +3 -4
  36. package/dist/leader/diffout.d.ts +10 -0
  37. package/dist/leader/diffout.js +14 -2
  38. package/dist/leader/diffup.js +3 -2
  39. package/dist/leader/planner.js +7 -0
  40. package/dist/main.js +22 -26
  41. package/dist/observability/fail-open.d.ts +4 -0
  42. package/dist/observability/fail-open.js +4 -0
  43. package/dist/orchestration/workflow-notify-journal.d.ts +1 -1
  44. package/dist/orchestration/workflow-notify-journal.js +14 -34
  45. package/dist/plugins/approval-ask-store-sql.d.ts +33 -0
  46. package/dist/plugins/approval-ask-store-sql.js +66 -33
  47. package/dist/plugins/background-agent-store-sql.js +16 -16
  48. package/dist/plugins/breaker-state-sql.js +2 -2
  49. package/dist/plugins/checkpoint-store-sql.d.ts +5 -2
  50. package/dist/plugins/checkpoint-store-sql.js +5 -2
  51. package/dist/plugins/image-bake-store-sql.d.ts +1 -1
  52. package/dist/plugins/image-bake-store-sql.js +27 -27
  53. package/dist/plugins/image-index-sql.js +15 -15
  54. package/dist/plugins/mailbox-store-sql.js +3 -3
  55. package/dist/plugins/memory-engine-pg.js +9 -9
  56. package/dist/plugins/memory-engine-tidb.js +7 -7
  57. package/dist/plugins/memory-sync-store-pg.js +13 -13
  58. package/dist/plugins/memory-sync-store-tidb.js +5 -5
  59. package/dist/plugins/outcome-ledger-sql.js +7 -7
  60. package/dist/plugins/pg-cost-quota.js +3 -3
  61. package/dist/plugins/pg-pool.js +84 -75
  62. package/dist/plugins/pg-rate-limiter.js +3 -3
  63. package/dist/plugins/pg-session-storage.d.ts +1 -1
  64. package/dist/plugins/pg-session-storage.js +12 -13
  65. package/dist/plugins/remote-env-host.js +3 -1
  66. package/dist/plugins/remote-env-local-docker.js +6 -3
  67. package/dist/plugins/remote-env-ssh.d.ts +13 -1
  68. package/dist/plugins/roster-store-sql.js +8 -8
  69. package/dist/plugins/store-contracts.d.ts +19 -0
  70. package/dist/plugins/store-contracts.js +42 -0
  71. package/dist/plugins/task-attachment-store.js +5 -5
  72. package/dist/plugins/task-list-store-sql.js +1 -1
  73. package/dist/plugins/tidb-cost-quota.js +1 -1
  74. package/dist/plugins/tidb-pool.js +83 -60
  75. package/dist/plugins/tidb-rate-limiter.js +1 -1
  76. package/dist/plugins/tidb-session-store.js +2 -5
  77. package/dist/plugins/tool-result-store-sql.js +2 -2
  78. package/dist/plugins/usage-window-store-sql.js +13 -13
  79. package/dist/plugins/write-behind-counter.d.ts +10 -2
  80. package/dist/plugins/write-behind-counter.js +13 -3
  81. package/dist/resource-suspend.d.ts +3 -1
  82. package/dist/resource-suspend.js +3 -1
  83. package/dist/run-local.d.ts +73 -1
  84. package/dist/run-local.js +146 -5
  85. package/dist/runs.d.ts +3 -1
  86. package/dist/runs.js +3 -1
  87. package/dist/security.d.ts +12 -0
  88. package/dist/security.js +12 -0
  89. package/dist/session-sync-kernel.d.ts +13 -0
  90. package/dist/session-sync-kernel.js +13 -0
  91. package/dist/trace/core-keyset-guard.d.ts +1 -1
  92. package/dist/trace/project.d.ts +10 -1
  93. package/dist/trace/project.js +31 -0
  94. package/package.json +3 -3
@@ -0,0 +1,316 @@
1
+ /**
2
+ * #189 修方向 1(黑板 [3112] 定谳)—— `/v1/fleet/stream` 连接时快照要并入的**近期终态 workflow 行窗**。
3
+ *
4
+ * ## 它修什么
5
+ * 引擎重启后 boot 扫描判死前世 `running` run,`publishWorkflow`(终帧)与 `removeWorkflow` 在**同一同步
6
+ * 调用栈内**背靠背执行;fleet bus 是纯内存 EventEmitter、无重放,`snapshot()` 只读活跃 Map ⇒ **重启之后
7
+ * 才连上的客户端连增量带快照都结构性看不见那一行**(cli 七轮正控实证)。durable 真源一直是对的
8
+ * (`GET /v1/workflows` 可达),缺的只是把它接到面板这一路上——所以这里是 **pull**:读同一份 durable
9
+ * store,**不碰 bus 的活跃 Map**(活行的单写者不变量、增量帧语义逐字不动)。
10
+ *
11
+ * ## 五条界(任何一条失手都只是少几行历史 ⇒ 整体 F 类 fail-open,登记 tag,不静默)
12
+ * · 窗长 {@link FLEET_SNAPSHOT_TERMINAL_WINDOW_MS} · 行数 {@link FLEET_SNAPSHOT_TERMINAL_MAX_ROWS}
13
+ * · 扫描面 {@link FLEET_SNAPSHOT_TERMINAL_SCAN_LIMIT} · 读预算 {@link FLEET_SNAPSHOT_TERMINAL_READ_BUDGET_MS}
14
+ * · 熔断冷却 {@link FLEET_SNAPSHOT_TERMINAL_COOLDOWN_MS}
15
+ *
16
+ * ## 为什么本模块有进程级可变状态(路由域刻意保持零状态,故不放在 `routes/fleet.ts`)
17
+ * 三件都长在同一个事实上——**`WorkflowRunStore` 契约没有取消面**,`Promise.race` 只结束等待、撤不回
18
+ * 已发出的查询:合流(重连风暴不按连接数放大,R1-H2)、合流窗有限(不把陈旧结果发给后来者、也不让
19
+ * 一条永不 settle 的读把后续连接全钉死,R2-H1/R3-M2)、熔断冷却(挂死的后端不被每周期继续加压,
20
+ * R3-H1)。真解是店侧查询超时/取消 —— 要动契约与四个后端,已作移交项。
21
+ *
22
+ * ## scope
23
+ * `WorkflowRunStore` 契约**没有跨 scope 枚举**(见 `orchestration/workflow-notify-journal.ts` 头注),
24
+ * 所以窗恒按**调用者自己的 principal scope** 读:fleet-wide 观察者看到的是「全租户活行 + 自己 scope 的
25
+ * 终态窗」。这是诚实的不对称(读不到的东西不编),方向安全(绝不多给);真行的租户/会话可见性仍由
26
+ * 路由的 `visW` 统一执法,本模块不自行放行。
27
+ */
28
+ import { isTerminalWorkflowStatus } from "@sema-agent/core";
29
+ import { recordFailOpen } from "../observability/fail-open.js";
30
+ import { buildFleetWorkflowRow } from "./fleet-bus.js";
31
+ /**
32
+ * 窗长 —— 10 分钟,**不做旋钮**。
33
+ *
34
+ * 它覆盖的是一段具体的人机时长:「引擎重启 → 客户端重连 → 人看一眼面板上刚才那条 workflow 怎么了」。
35
+ * 比它短会漏掉重连慢一步的壳(即本 issue 的病灶);比它长就变成「拿 SSE 快照当历史列表」——而历史面
36
+ * 本来就有真源(`GET /v1/workflows`:durable、可分页、带 scope/session 过滤),不该在这里长出第二个。
37
+ * 两侧边界都由语义定死,旋钮只会让部署方去调一个没有正确取值的数;fleet 面现有零旋钮,从之。
38
+ */
39
+ export const FLEET_SNAPSHOT_TERMINAL_WINDOW_MS = 10 * 60_000;
40
+ /** 同一快照里终态行的行数上限(窗长之外的第二道界)。快照是面板首屏,不是历史列表——超出的部分归
41
+ * `GET /v1/workflows`。 */
42
+ export const FLEET_SNAPSHOT_TERMINAL_MAX_ROWS = 20;
43
+ /**
44
+ * 每个终态**扫描面**的行数(店侧下推的 limit)。它比 {@link FLEET_SNAPSHOT_TERMINAL_MAX_ROWS} 大是有
45
+ * 具体病灶的(codex R1-M3,红先复现):店侧分页按 `createdAt DESC` 排(core 契约 + 两个 SQL 实现皆然),
46
+ * 而本窗的判据是**结束时刻**——一条跑了三天、刚刚才结束的 workflow(正是用户此刻要看的那条)会被 20 条
47
+ * 更晚创建的行挤出首页。留这段余量是在现有契约内能给的最好答案;彻底解法是店侧加一个 `ended_at DESC`
48
+ * 的窄查询(要过真双库门,已作移交项记在发车说明里)。
49
+ *
50
+ * 残余(如实记档):同 scope 同一终态下,若有超过本值条**更晚创建**的行,那条"早创建、刚结束"的行仍会
51
+ * 被挤掉。此时用户仍可从 `GET /v1/workflows` 看到真相——丢的只是面板首屏的一行。
52
+ */
53
+ export const FLEET_SNAPSHOT_TERMINAL_SCAN_LIMIT = 100;
54
+ /** durable 读的时间预算。超时=**放弃这段增益**(记 F 类 fail-open),绝不让一次慢查询把整条 SSE 握手
55
+ * 拖住——面板少一条历史行是难看,连不上流是坏掉。 */
56
+ export const FLEET_SNAPSHOT_TERMINAL_READ_BUDGET_MS = 2_000;
57
+ /**
58
+ * (原 `FLEET_SNAPSHOT_TERMINAL_COALESCE_MS` 已删)⚖️ 「同时只有一支探针」与「结果别太陈旧」的取舍
59
+ * —— codex R3-M2 与 R4-H1 是两轮方向相反的 finding,这里成文定案。
60
+ *
61
+ * 后来者**加入**在飞的那支读,只要它还在自己的预算之内({@link FLEET_SNAPSHOT_TERMINAL_READ_BUDGET_MS})。
62
+ * · 曾短暂改成 250ms 的窄窗(想压小"采到"与"交付"的时差):实测判据下更坏 —— 慢而健康的店(比如
63
+ * 1.9s)配错峰重连,会变成每 250ms 起一批新读(2 次 list + ≤20 点读),而熔断要等某个调用方 2s
64
+ * 超时才开;单飞的意义被自己抵消(R4-H1)。
65
+ * · 保留的代价:刚好在探针尾巴上加入的调用方,可能拿到一份最多约"两倍预算"之前采到的行集(R3-M2)
66
+ * —— 后果是这条连接首屏少一条**刚刚**结束的行(且只有跨副本翻转才补不上帧),与本模块整体的 F 类
67
+ * 姿态同级;而 R4-H1 的后果是给一个已经很慢的库继续加压。取小害。
68
+ * 过了预算的在飞读 = 已被放弃的一代(等待方全走光了),不再加入:那一代由熔断收尾,新调用方在冷却期
69
+ * 外开新一代。
70
+ */
71
+ /**
72
+ * 熔断冷却期:一次读失败/超预算之后,同 (store, scope) 在这段时间内**不再发起新读**(直接放弃这段增益,
73
+ * 记 F 类 fail-open)。
74
+ *
75
+ * 为什么必须有(codex R3-H1,红先复现 4→2):`WorkflowRunStore` 契约没有取消面 —— 发出去的查询撤不回。
76
+ * 后端挂死时,只按"复用窗过期就再起一次"办,等于每个周期给那个已经挂死的后端再加两笔永不回来的活,
77
+ * 连接不断则永远堆下去(池/内存/驱动队列迟早耗尽),这正是"故障期被自己的重试放大"那一族。冷却期把
78
+ * 新增速率钉在「每 scope 每 10s 至多一次探针」,并且**自愈**:冷却一过,下一条连接就是一次真实探测。
79
+ * 残余(如实记档):挂死那几笔仍在后端占着;真解=店侧查询超时/取消(要动契约与四个后端,移交项)。
80
+ */
81
+ export const FLEET_SNAPSHOT_TERMINAL_COOLDOWN_MS = 10_000;
82
+ /** 终态词表:从 {@link WorkflowRunStatus} 闭集**穷举**(缺一个键或多一个键都是编译期错误)后按 core 的
83
+ * {@link isTerminalWorkflowStatus} 判定——集合的闭合由类型执法、终态的**语义**仍是 core 单源。core 若
84
+ * 加一个状态,这里编译期就红,而不是悄悄漏进/漏出终态窗。 */
85
+ const TERMINAL_WORKFLOW_STATUSES = (() => {
86
+ const all = { running: true, completed: true, failed: true };
87
+ return Object.keys(all).filter((s) => isTerminalWorkflowStatus(s));
88
+ })();
89
+ /** fleet 行上的 `status` 是自由字符串(wire 面容忍未知词),而"是不是终态"必须与上面那张**同一张**
90
+ * 闭集表说同一句话 —— 供路由判断一条 workflow 行帧是否终态(不做裸 cast:词表就是判据)。 */
91
+ export function isTerminalWorkflowRowStatus(status) {
92
+ return TERMINAL_WORKFLOW_STATUSES.some((s) => s === status);
93
+ }
94
+ const stateByStore = new WeakMap();
95
+ function scopeState(store, scope) {
96
+ let byScope = stateByStore.get(store);
97
+ if (!byScope) {
98
+ byScope = new Map();
99
+ stateByStore.set(store, byScope);
100
+ }
101
+ let st = byScope.get(scope);
102
+ if (!st) {
103
+ st = {};
104
+ byScope.set(scope, st);
105
+ }
106
+ return st;
107
+ }
108
+ /** 开熔断,并挂一个 unref 的到期回调自清 + 销号 —— 否则「读超时 2.0s、查询 2.1s 才落地」这条常见路径会
109
+ * 留下一条永久驻留的 scope 记录(冷却记号没人清、`evictIfIdle` 又因为冷却未过而不动手,codex R5-M2)。
110
+ * 代际校验(`coolingUntil === until`)保证到期回调只清自己开的那一次。 */
111
+ function openCooldown(store, scope, st) {
112
+ // codex R6-M:同一支探针失败的 N 个等待者各自到点都会走到这里——冷却语义是 per-probe-failure,不是
113
+ // per-waiter,首开者赢:已在冷却期内就不续期、不再铸第二支定时器(风暴+挂库时 O(连接数) 定时器与
114
+ // 闭包正好压在依赖已经退化的时刻)。
115
+ if (st.coolingUntil !== undefined && st.coolingUntil > Date.now())
116
+ return;
117
+ const until = Date.now() + FLEET_SNAPSHOT_TERMINAL_COOLDOWN_MS;
118
+ st.coolingUntil = until;
119
+ const t = setTimeout(() => {
120
+ if (st.coolingUntil !== until)
121
+ return; // 期间又开过新的一次冷却:那次自己管自己
122
+ st.coolingUntil = undefined;
123
+ evictIfIdle(store, scope, st);
124
+ }, FLEET_SNAPSHOT_TERMINAL_COOLDOWN_MS);
125
+ if (typeof t.unref === "function")
126
+ t.unref(); // 观测性的收尾绝不该拖住进程退出
127
+ }
128
+ /** 无事可记的 scope 就地销号(codex R4-M2):否则每一个**曾经**开过流的 principal 都会在这张强引用表里
129
+ * 永久留一条——多租户长跑进程下,租户流动/高基数身份会把它变成一条只增不减的内存线。 */
130
+ function evictIfIdle(store, scope, st) {
131
+ if (st.inFlight !== undefined)
132
+ return;
133
+ if (st.coolingUntil !== undefined && Date.now() < st.coolingUntil)
134
+ return;
135
+ const byScope = stateByStore.get(store);
136
+ if (byScope?.get(scope) === st)
137
+ byScope.delete(scope);
138
+ }
139
+ /**
140
+ * 取该 scope 的近期终态行窗。**永不抛**:任何失败/超预算都收成"少几行历史"并记 F 类 fail-open。
141
+ *
142
+ * ⚠️ 调用方仍须对每一行施加与活行**同一套**可见性判据(`visW`:scope + `?session=`)——本函数按 scope
143
+ * 读,但会话轴刻意留给调用方,好与活行"无 sessionId 的行 fail-open 可见"的既有语义逐字一致。
144
+ */
145
+ /** [3156] 轮2 真红的修:进程内终态行 seed 缓存 —— **写路径顺手喂**(publishFleet 的 terminal 臂),
146
+ * 读侧零库查询零时序竞态。存在理由:durable pull 的查询键是 caller 的 scope,而 fleetWide 连接
147
+ * (无 auth 部署恒是)的可见性判据放行**全部** scope —— 查询键与可见性判据不同源,引擎铸行的
148
+ * scope("anon:shell-live")永远不等于 caller 侧的 "default",pull 恒 miss。seed 缓存按「发生过什么」
149
+ * 记(与订阅方无关),读侧再过各连接自己的 visW。不是活跃集:bus 的 Map 零触碰,单写者不变量原样。
150
+ * 有界:行数 ≤ MAX_ROWS×2、窗长同 WINDOW_MS,超界丢最旧。 */
151
+ const seededTerminalRows = [];
152
+ export function seedTerminalWorkflowRow(row) {
153
+ const now = Date.now();
154
+ seededTerminalRows.push({ row, at: now });
155
+ // 双界修剪:窗长 + 行数(常数级,每次 seed 顺手)
156
+ while (seededTerminalRows.length > 0 && (now - seededTerminalRows[0].at > FLEET_SNAPSHOT_TERMINAL_WINDOW_MS || seededTerminalRows.length > FLEET_SNAPSHOT_TERMINAL_MAX_ROWS * 2)) {
157
+ seededTerminalRows.shift();
158
+ }
159
+ }
160
+ /** 测试缝:清 seed 缓存(与 clearTerminalWindowCooldownForTest 同姿势,生产零调用)。 */
161
+ export function clearSeededTerminalRowsForTest() {
162
+ seededTerminalRows.length = 0;
163
+ }
164
+ /** 窗内 seed 行(同 id 取最新一条;窗外的顺手剪掉)。 */
165
+ function seededRowsInWindow() {
166
+ const now = Date.now();
167
+ const byId = new Map();
168
+ for (const e of seededTerminalRows) {
169
+ if (now - e.at <= FLEET_SNAPSHOT_TERMINAL_WINDOW_MS)
170
+ byId.set(e.row.id, e.row);
171
+ }
172
+ return [...byId.values()];
173
+ }
174
+ export async function recentTerminalWorkflowRows(store, scope, pullScope) {
175
+ // [3156]:seed 缓存 = 本进程生命周期内全部终态(含 boot recover 判死)的同源可达径——fleetWide 连接
176
+ // (scope=null,可见性判据放行全 scope)取 seed **全量**,并以 `pullScope`(caller principal,尽力形)
177
+ // 做 durable pull 兜底:pull 的查询键与引擎铸行 scope 可能不同源(cli 轮2 实测 "default" vs
178
+ // "anon:shell-live" 恒 miss),中了是增益、中不了还有 seed——两径并集,谁都不当唯一真源。
179
+ // scoped 连接:seed 按本 scope 滤 + durable pull 本 scope(跨进程兜底)。
180
+ // [3193] 病理3:seed 侧不再按 caller scope 预滤——那是第二份可见性判据(F1 病族),与引擎铸行
181
+ // scope("anon:shell-live" vs caller "default")恒 miss。本函数只产**候选集**;可见/擦除由路由的
182
+ // visW/stripW 同一套判据裁(与快照活行、增量帧同源),窗与 MAX_ROWS 双界仍在。
183
+ const seeded = seededRowsInWindow();
184
+ const effectiveScope = scope ?? pullScope;
185
+ if (effectiveScope === undefined)
186
+ return seeded;
187
+ const scopeForPull = effectiveScope;
188
+ if (!store)
189
+ return seeded; // 无 durable store 的部署(memory 后端/未开自编排):seed 缓存仍工作
190
+ const cooling = scopeState(store, scopeForPull);
191
+ if (cooling.coolingUntil !== undefined && Date.now() < cooling.coolingUntil) {
192
+ // 熔断中:上一代读超预算(后端卡住),这段时间内连探都不探(见 FLEET_SNAPSHOT_TERMINAL_COOLDOWN_MS)。
193
+ recordFailOpen("server.fleet.snapshot-terminal-window-unavailable", "cooling down after an over-budget read");
194
+ return seeded; // 熔断只熔 durable 读;seed 是进程内的,照常(scope=null 的 fleetWide 形=全量,勿再按 null 过滤)
195
+ }
196
+ cooling.coolingUntil = undefined; // 冷却已到期:销掉这个记号,好让空闲 scope 能被回收
197
+ evictIfIdle(store, scopeForPull, cooling);
198
+ let timer;
199
+ const probe = sharedRead(store, scopeForPull);
200
+ try {
201
+ const budget = new Promise((_resolve, reject) => {
202
+ timer = setTimeout(() => reject(new Error(`terminal-window read exceeded ${FLEET_SNAPSHOT_TERMINAL_READ_BUDGET_MS}ms`)), FLEET_SNAPSHOT_TERMINAL_READ_BUDGET_MS);
203
+ if (typeof timer.unref === "function")
204
+ timer.unref();
205
+ });
206
+ const pulled = await Promise.race([probe.rows, budget]);
207
+ // scoped 腿 = durable pull ∪ seed(同 id durable 优先 —— 库行是 CAS 后真源,seed 是投影快照)
208
+ const pulledIds = new Set(pulled.map((r) => r.id));
209
+ return [...pulled, ...seeded.filter((r) => !pulledIds.has(r.id))];
210
+ }
211
+ catch (err) {
212
+ // 熔断**只由自己这一代开**(codex R4-H1):判据是「我等的那一代到现在还挂在飞」——那才是"后端卡住、
213
+ // 再发就是加压"。两个反例都被这条判据排除:① 我等的那代其实已经完成/失败并销号(快失败的店不累积
214
+ // 在飞的活,没有加压问题,不该罚 10 秒);② 我超时时表上挂的已经是**别人**开的新一代(我这代早settle
215
+ // 了),拿它当证据会让一个已经健康的 scope 被上一代的迟到超时按住。
216
+ const st = scopeState(store, scopeForPull);
217
+ if (st.inFlight === probe)
218
+ openCooldown(store, scopeForPull, st);
219
+ // detail 用 `err.message` 而不是 `String(err)`:后者会调用抛出值自己的 toString,而那本身可能再抛
220
+ // (逃出本兜底,把降级变成故障)。非 Error 抛出值就如实说"不是 Error",不去问它任何问题。
221
+ recordFailOpen("server.fleet.snapshot-terminal-window-unavailable", err instanceof Error ? err.message : "terminal-window read threw a non-Error value");
222
+ return seeded; // durable 读失败只失去跨进程兜底;本进程 seed 照常(读它不碰后端)
223
+ }
224
+ finally {
225
+ if (timer !== undefined)
226
+ clearTimeout(timer);
227
+ }
228
+ }
229
+ /**
230
+ * test-only:把熔断冷却**提前**到现在(等价于"冷却期已过"),**不动**在飞读的登记。
231
+ *
232
+ * 为什么只清冷却:冷却期是墙钟(10s),测试不该真等;而"在飞读的复用是否会把毒 promise 传给后来者"
233
+ * 恰恰是要被测的行为,清掉它就等于把待测对象删了。生产路径不引用本函数(与
234
+ * `resetFailOpenRecorderForTest` 同一姿势:测试面显式,不给生产留旁路)。
235
+ */
236
+ export function clearTerminalWindowCooldownForTest(store, scope) {
237
+ scopeState(store, scope).coolingUntil = undefined;
238
+ }
239
+ /** test-only:这个 store 目前还记着几个 scope(codex R4-M2 的空闲销号有没有真的销)。 */
240
+ export function trackedTerminalWindowScopesForTest(store) {
241
+ return stateByStore.get(store)?.size ?? 0;
242
+ }
243
+ /** 合流层:同 (store, scope) 上**同时只有一代**在飞的读;后来者加入仍在预算内的那一代,settle 即销号。 */
244
+ function sharedRead(store, scope) {
245
+ const st = scopeState(store, scope);
246
+ const existing = st.inFlight;
247
+ // 加入仍在预算内的那一代(见上方取舍段);更老的那代已被放弃,不加入。
248
+ if (existing && Date.now() - existing.startedAt < FLEET_SNAPSHOT_TERMINAL_READ_BUDGET_MS)
249
+ return existing;
250
+ const entry = {
251
+ startedAt: Date.now(),
252
+ rows: readRecentTerminalWorkflowRows(store, scope).finally(() => {
253
+ // 只销自己那一号:一次慢读期间可能已经开始了下一代(本次先 settle 的竞态下,清空会误删新号)。
254
+ if (st.inFlight === entry) {
255
+ st.inFlight = undefined;
256
+ evictIfIdle(store, scope, st);
257
+ }
258
+ }),
259
+ };
260
+ // 所有等待方都可能因为超预算先走(race),没有 catch 的 promise 会变成 unhandledRejection 把进程带下去。
261
+ entry.rows.catch(() => undefined);
262
+ st.inFlight = entry;
263
+ return entry;
264
+ }
265
+ /**
266
+ * `Promise.all` 的**等齐**版:等**每一支**都落地,再决定成败(有失败就抛第一个失败原因)。
267
+ *
268
+ * 为什么不能用 `Promise.all`(codex R5-H1):它在**第一支**失败时立刻 reject,而兄弟支还挂在后端上。
269
+ * 于是这一代探针提前销号,超时的调用方看到"我这代已经不在表上了"就不开熔断(那条判据本意是排除
270
+ * 快失败),下一条连接照样再发一批 —— 正是这套机制要防的放大。等齐之后,"探针还在飞"与"后端还有
271
+ * 我发出去的活"这两件事重新同义,代际熔断的判据才成立。
272
+ */
273
+ async function allOrFirstFailureAfterAllSettled(work) {
274
+ const settled = await Promise.allSettled(work);
275
+ const values = [];
276
+ for (const r of settled) {
277
+ if (r.status === "rejected")
278
+ throw r.reason; // 第一支失败的原因原样上抛(调用方统一收成 fail-open)
279
+ values.push(r.value);
280
+ }
281
+ return values;
282
+ }
283
+ /** 读本体(抛错/超时由 {@link recentTerminalWorkflowRows} 统一收成 fail-open)。 */
284
+ async function readRecentTerminalWorkflowRows(store, scope) {
285
+ const cutoff = Date.now() - FLEET_SNAPSHOT_TERMINAL_WINDOW_MS;
286
+ /** 窗判据的时间轴 = 「这一行最后变成现在这样是什么时候」:终态行恒有 `endedAt`,回落 `createdAt`
287
+ * (与 core `reap` 的 `endedAt ?? createdAt` 同一口径——两处对「这行多老」必须给同一个答案)。 */
288
+ const settledAt = (r) => r.endedAt ?? r.createdAt;
289
+ // 每个终态各扫一页(店侧下推 status + limit),再按结束时刻归并。不用"一次不带 status 的取页":那会被
290
+ // 同 scope 里更新的 running 行挤掉真正要找的终态行。
291
+ const pages = await allOrFirstFailureAfterAllSettled(TERMINAL_WORKFLOW_STATUSES.map((status) => store.listByScope(scope, { status, limit: FLEET_SNAPSHOT_TERMINAL_SCAN_LIMIT })));
292
+ const windowed = pages
293
+ .flat()
294
+ .filter((s) => s.scope === scope && settledAt(s) >= cutoff)
295
+ .sort((a, b) => settledAt(b) - settledAt(a) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) // 同刻结束按 id 定序:快照不许随机
296
+ .slice(0, FLEET_SNAPSHOT_TERMINAL_MAX_ROWS);
297
+ // summary 不带 doneCount/startedCount(core `WorkflowRunSummary` 没有这两位),而面板行的其余供数都在
298
+ // 它上面——与其在这里另写一份"近似"投影(两份投影必漂,本仓在 startedCount 口径上已吃过一次),不如
299
+ // 取回整行走**同一个** {@link buildFleetWorkflowRow}。代价=每行一次主键点读,受行数上限硬界(≤20),
300
+ // 且只发生在开流那一拍、同 scope 并发还会合流。
301
+ const runs = await allOrFirstFailureAfterAllSettled(windowed.map((s) => store.get(s.id)));
302
+ const rows = [];
303
+ for (const [i, run] of runs.entries()) {
304
+ if (!run)
305
+ continue; // list 与 get 之间被 reap 掉:诚实跳过,不为一个不存在的 run 造行
306
+ // `store.get` 是**无 scope 门**的裸读(带门的是 core 的 `getWorkflowRun`)——id 虽然来自本 scope 的
307
+ // 列表,仍按真行的 scope 复核一次:租户轴上宁可多判一次,也不靠"来源可信"。
308
+ if (run.scope !== scope)
309
+ continue;
310
+ if (!isTerminalWorkflowStatus(run.status) || settledAt(run) < cutoff)
311
+ continue; // 读回时已不在窗内/已不是终态
312
+ rows.push(buildFleetWorkflowRow(windowed[i].id, run));
313
+ }
314
+ return rows;
315
+ }
316
+ //# sourceMappingURL=fleet-terminal-window.js.map
@@ -1,10 +1,10 @@
1
- import { principalFrom, decodeCheckpointScope } from "../../security.js";
1
+ import { principalFrom, decodeCheckpointScope, PRINCIPAL_TOKEN_HEADER, APPROVAL_MAC_HEADER, APPROVAL_MAC_KID_HEADER } from "../../security.js";
2
2
  import { verifyDirectDoorProof } from "../../principal-jwt.js";
3
3
  import { MAX_APPROVAL_REASON_CHARS } from "../../approval-hmac.js";
4
4
  import { redactedPreview } from "../../trace/redact.js";
5
5
  import { fleetRunLabels } from "../../fleet/fleet-bus.js"; // [2069]④ §3 行展示名与 fleet 行同源(见用处的注)
6
6
  import { sleep } from "../sse-log.js";
7
- import { sendJson, sendError, sseHeaders } from "../send.js";
7
+ import { sendJson, sendError, sseHeaders, SSE_MAX_STREAM_MS, SSE_HEARTBEAT_IDLE_MS } from "../send.js";
8
8
  import { gatedPrincipal, explicitOperatorOk, isOperator } from "../principal-gate.js";
9
9
  // design/80 seam #2 (assistant-scheduler): graceful preempt (durable yield) + resource_limit resume of one task.
10
10
  export const ASSISTANT_PREEMPT_RE = /^\/v1\/assistant\/tasks\/([^/]+)\/preempt$/;
@@ -427,7 +427,7 @@ async function handleApprovalsAssistantBody(req, res, url, ctx, miss) {
427
427
  let deciderPrincipal = principal;
428
428
  if (deps.config.directDoorActive) {
429
429
  const hdr = (n) => { const h = req.headers[n]; return Array.isArray(h) ? h[0] : h; };
430
- const proof = verifyDirectDoorProof({ jwt: hdr("x-approval-principal-token"), mac: hdr("x-approval-mac"), kid: hdr("x-approval-mac-kid") },
430
+ const proof = verifyDirectDoorProof({ jwt: hdr(PRINCIPAL_TOKEN_HEADER), mac: hdr(APPROVAL_MAC_HEADER), kid: hdr(APPROVAL_MAC_KID_HEADER) },
431
431
  // reason 入签:同一条规则也适用于身份绑定腿(两个绑定位为 null,第五位照常参与)。
432
432
  { sessionId: run.sessionId, decision, reason: typeof body.reason === "string" ? body.reason : null }, deps.config, { actionBinding: false });
433
433
  if (!proof.ok) {
@@ -569,7 +569,7 @@ async function handleApprovalsAssistantBody(req, res, url, ctx, miss) {
569
569
  const h = req.headers[n];
570
570
  return Array.isArray(h) ? h[0] : h;
571
571
  };
572
- const proof = verifyDirectDoorProof({ jwt: hdr("x-approval-principal-token"), mac: hdr("x-approval-mac"), kid: hdr("x-approval-mac-kid") },
572
+ const proof = verifyDirectDoorProof({ jwt: hdr(PRINCIPAL_TOKEN_HEADER), mac: hdr(APPROVAL_MAC_HEADER), kid: hdr(APPROVAL_MAC_KID_HEADER) },
573
573
  // reason 入签(三方裁 (a) + clay 干净切):落账理由属于决定内容,与 decision 同受完整性保护。
574
574
  { sessionId, boundCallId: binding.boundCallId, boundInputHash: binding.boundInputHash, decision, reason: typeof body.reason === "string" ? body.reason : null }, deps.config);
575
575
  if (!proof.ok) {
@@ -682,7 +682,6 @@ export async function streamApprovals(req, res, cs, scope, pollMs = APPROVALS_ST
682
682
  let closed = false;
683
683
  req.on("close", () => { closed = true; });
684
684
  const start = Date.now();
685
- const MAX_MS = 15 * 60 * 1000;
686
685
  let lastBeat = Date.now();
687
686
  let prev = new Map();
688
687
  let first = true;
@@ -715,11 +714,11 @@ export async function streamApprovals(req, res, cs, scope, pollMs = APPROVALS_ST
715
714
  res.write(`event: resolved\ndata: ${JSON.stringify({ type: "resolved", sessionId: p.sessionId, toolCallId: p.toolCallId })}\n\n`); // decided/expired/gone
716
715
  }
717
716
  prev = cur;
718
- if (Date.now() - start > MAX_MS) {
717
+ if (Date.now() - start > SSE_MAX_STREAM_MS) {
719
718
  res.write(`event: error\ndata: ${JSON.stringify({ type: "error", errorCode: "STREAM_MAX_DURATION", message: "approvals stream reached its 15-minute cap — reconnect to continue" })}\n\n`);
720
719
  break;
721
720
  }
722
- if (Date.now() - lastBeat > 15_000) {
721
+ if (Date.now() - lastBeat > SSE_HEARTBEAT_IDLE_MS) {
723
722
  res.write(`event: heartbeat\ndata: ${JSON.stringify({ type: "heartbeat" })}\n\n`);
724
723
  lastBeat = Date.now();
725
724
  }
@@ -1,3 +1,4 @@
1
+ import { FLEET_SNAPSHOT_TERMINAL_MAX_ROWS, isTerminalWorkflowRowStatus, recentTerminalWorkflowRows } from "../../fleet/fleet-terminal-window.js";
1
2
  import { taskNotificationFoldKey } from "../../orchestration/workflow-completion-inbox.js";
2
3
  import { sendJson, sendError, sseHeaders } from "../send.js";
3
4
  import { gatedPrincipal } from "../principal-gate.js";
@@ -44,7 +45,12 @@ async function handleFleetBody(req, res, url, ctx, miss) {
44
45
  // (a non-shell observer following one session). Default (absent) keeps the frame-即-投递 semantics —
45
46
  // today's only session-bound consumer IS the model-injecting shell.
46
47
  const observeOnly = fleetParams.get("observe") === "1";
47
- await streamFleet(req, res, deps.fleetBus, fleetWide ? null : (principal ?? "default"), callerSession || null, observeOnly ? undefined : deps.workflowCompletionInbox);
48
+ // #189:终态行窗的 durable 读交给 streamFleet 在**订阅注册之后**做(见那里的缓冲段)——放在这里
49
+ // (开流之前)会让"帧已扇出而本连接尚未订阅"的窗口凭空多出一个读的时长,codex R1-H1 红先复现过。
50
+ // [3156] 轮2 真红修:终态窗的查询键必须与可见性判据**同源**——fleetWide 连接(callerScope=null,
51
+ // visW 放行全 scope)此前窗却按 caller principal("default")查,而行的 scope 是引擎铸的
52
+ // ("anon:shell-live")⇒ durable pull 恒 miss。fleetWide ⇒ null(窗走进程内 seed 缓存,全 scope)。
53
+ await streamFleet(req, res, deps.fleetBus, fleetWide ? null : (principal ?? "default"), callerSession || null, observeOnly ? undefined : deps.workflowCompletionInbox, { store: deps.workflowRunStore, scope: fleetWide ? null : (principal ?? "default"), pullScope: principal ?? "default", ready: deps.fleetRecoveryDone });
48
54
  return;
49
55
  }
50
56
  miss.fell = true;
@@ -54,7 +60,7 @@ async function handleFleetBody(req, res, url, ctx, miss) {
54
60
  * else owner-scoped (only rows whose `scope` matches). The tenant-internal `scope` field is STRIPPED from every
55
61
  * emitted row (it's a gate input, never rendered). A removal is forwarded ONLY for a row this connection actually
56
62
  * saw (no id-existence oracle for an unseen tenant's run). Heartbeat + dual-close cleanup unsubscribe the bus. */
57
- function streamFleet(req, res, bus, callerScope, callerSession = null, completionInbox) {
63
+ function streamFleet(req, res, bus, callerScope, callerSession = null, completionInbox, terminal) {
58
64
  return new Promise((resolve) => {
59
65
  sseHeaders(res);
60
66
  // [1508] 1.247 `bgNotifyFailClosed` — the GENERATION marker cli asked for ([1500]📌/[1502] F2): declares
@@ -81,19 +87,68 @@ function streamFleet(req, res, bus, callerScope, callerSession = null, completio
81
87
  // subscriber gets a content-scrubbed projection (ids/status/progress/timing kept); a fleet-wide observer
82
88
  // (trace/dashboard, callerSession === null) keeps the full row. Rows tagged with the caller's own session
83
89
  // pass sessionOk and are never scrubbed (r.sessionId present ⇒ it equals callerSession here).
90
+ // codex R6:FleetTaskRow 逐键处置表——`satisfies Record<keyof FleetTaskRow,…>` 使**任何**行新键先在
91
+ // 编译期红(TS2741),强迫对跨会话可见性表态;"keep" 键必须同步进下方白名单构造,配套钉在
92
+ // test/fleet-bg-child.test.ts(R6 格:kept 键集 ⊆ 表内 keep∪rewrite 集)。
93
+ const SCOPED_TASK_KEY_DISPOSITION = {
94
+ id: "keep", parentId: "keep", parentToolCallId: "keep", workflowRunId: "keep", status: "keep",
95
+ startedAt: "keep", elapsedMs: "keep", tokens: "keep", queuedCount: "keep",
96
+ awaitingPlanApproval: "keep", toolUses: "keep", usage: "keep", resumable: "keep", sourceLane: "keep",
97
+ name: "rewrite", scope: "strip", sessionId: "strip",
98
+ description: "scrub", agentType: "scrub", agentName: "scrub", currentAction: "scrub",
99
+ currentTool: "scrub", transcriptId: "scrub", stoppedBy: "scrub", editedFiles: "scrub",
100
+ };
101
+ void SCOPED_TASK_KEY_DISPOSITION;
84
102
  const stripT = (r) => {
85
103
  const { scope: _s, sessionId: _sid, ...rest } = r;
86
104
  if (callerSession !== null && r.sessionId === undefined) {
87
- const { description: _d, agentType: _at, agentName: _an, currentAction: _ca, ...keep } = rest;
88
- return { ...keep, name: "(unattributed)" };
105
+ // [3136]②→codex R6(确认轮):黑名单形被两次击穿(currentTool、editedFiles)——同一信任边界的键
106
+ // 靠逐个想起来列,漏一个就是跨会话内容泄漏。改**白名单构造**:kept 对象逐键显式拼,未列键默认
107
+ // 不过;新键先过上方处置表的编译期门。
108
+ return {
109
+ id: rest.id,
110
+ status: rest.status,
111
+ name: "(unattributed)",
112
+ ...(rest.parentId !== undefined ? { parentId: rest.parentId } : {}),
113
+ ...(rest.parentToolCallId !== undefined ? { parentToolCallId: rest.parentToolCallId } : {}),
114
+ ...(rest.workflowRunId !== undefined ? { workflowRunId: rest.workflowRunId } : {}),
115
+ ...(rest.startedAt !== undefined ? { startedAt: rest.startedAt } : {}),
116
+ ...(rest.elapsedMs !== undefined ? { elapsedMs: rest.elapsedMs } : {}),
117
+ ...(rest.tokens !== undefined ? { tokens: rest.tokens } : {}),
118
+ ...(rest.queuedCount !== undefined ? { queuedCount: rest.queuedCount } : {}),
119
+ ...(rest.awaitingPlanApproval !== undefined ? { awaitingPlanApproval: rest.awaitingPlanApproval } : {}),
120
+ ...(rest.toolUses !== undefined ? { toolUses: rest.toolUses } : {}),
121
+ ...(rest.usage !== undefined ? { usage: rest.usage } : {}),
122
+ ...(rest.resumable !== undefined ? { resumable: rest.resumable } : {}),
123
+ ...(rest.sourceLane !== undefined ? { sourceLane: rest.sourceLane } : {}),
124
+ };
89
125
  }
90
126
  return rest;
91
127
  };
128
+ // A-002.5(#194 病族 F2):workflow 行与 task 行同一条降权跨会话边界——stripT 的黑名单三次被
129
+ // 击穿后改了白名单,stripW 当时漏改(同函数体孪生)。处置表同姿势:行加新键先编译红强迫表态。
130
+ const SCOPED_WORKFLOW_KEY_DISPOSITION = {
131
+ id: "keep", status: "keep", doneCount: "keep", totalCount: "keep", failedCount: "keep",
132
+ startedCount: "keep", elapsedMs: "keep", tokens: "keep",
133
+ name: "rewrite", scope: "strip", sessionId: "strip",
134
+ description: "scrub",
135
+ };
136
+ void SCOPED_WORKFLOW_KEY_DISPOSITION;
92
137
  const stripW = (r) => {
93
138
  const { scope: _s, sessionId: _sid, ...rest } = r;
94
139
  if (callerSession !== null && r.sessionId === undefined) {
95
- const { description: _d, ...keep } = rest;
96
- return { ...keep, name: "(unattributed)" };
140
+ // 白名单构造:kept 逐键显式拼,未列键默认不过(与 stripT 同形;"keep" 键必须同步进处置表)。
141
+ return {
142
+ id: rest.id,
143
+ status: rest.status,
144
+ name: "(unattributed)",
145
+ ...(rest.doneCount !== undefined ? { doneCount: rest.doneCount } : {}),
146
+ ...(rest.totalCount !== undefined ? { totalCount: rest.totalCount } : {}),
147
+ ...(rest.failedCount !== undefined ? { failedCount: rest.failedCount } : {}),
148
+ ...(rest.startedCount !== undefined ? { startedCount: rest.startedCount } : {}),
149
+ ...(rest.elapsedMs !== undefined ? { elapsedMs: rest.elapsedMs } : {}),
150
+ ...(rest.tokens !== undefined ? { tokens: rest.tokens } : {}),
151
+ };
97
152
  }
98
153
  return rest;
99
154
  };
@@ -102,14 +157,18 @@ function streamFleet(req, res, bus, callerScope, callerSession = null, completio
102
157
  // 单点注入:调用方已带 type 的帧(hook_notice/bg_notification)保持原值。
103
158
  const send = (event, data) => { if (!res.writableEnded)
104
159
  res.write(`event: ${event}\ndata: ${JSON.stringify({ type: event, ...data })}\n\n`); };
105
- // connect-time snapshot (filtered + scope-stripped) — the visible rows become this connection's "seen" set.
106
- const snap = bus.snapshot();
107
- const tasks = snap.tasks.filter(visT);
108
- const workflows = snap.workflows.filter(visW);
109
- tasks.forEach((r) => seenTasks.add(r.id));
110
- workflows.forEach((r) => seenWf.add(r.id));
111
- send("snapshot", { tasks: tasks.map(stripT), workflows: workflows.map(stripW), ts: snap.ts });
112
- const unsubscribe = bus.subscribe((frame) => {
160
+ /** #189:快照里那些**按窗保留**的 workflow 行 id(来自 durable 终态窗,或握手期间才翻终态的行)
161
+ * —— workflow / workflow_remove 两臂。 */
162
+ const retainedTerminalWf = new Set();
163
+ /** 现在是否正在重放握手期缓冲(只在这段里,终态行帧才升级为"保留行")。 */
164
+ let replayingBuffer = false;
165
+ /** [3193] codex R4:首见即终态的历史行保留**预算**(每连接)。retainedTerminalWf 本身不积累
166
+ * (每个 id 的撤行帧即刻消费),真正会无界的是「被豁免撤行、留在面板与 seenWf 里的历史行数」。
167
+ * 预算=终态窗容量同阶(×2);耗尽后退回旧「终帧→撤行」契约(行瞬态可见)——有界降级,不吞帧。
168
+ * 快照径的保留行不占预算(已由窗的行数+窗龄双界)。 */
169
+ let retainedHistoryBudget = FLEET_SNAPSHOT_TERMINAL_MAX_ROWS * 2;
170
+ /** 一条增量帧的处理(**先注册订阅、后组装快照**,故与快照解耦成具名函数——见下方缓冲段)。 */
171
+ const handleFrame = (frame) => {
113
172
  switch (frame.type) {
114
173
  case "task":
115
174
  if (visT(frame.row)) {
@@ -119,6 +178,19 @@ function streamFleet(req, res, bus, callerScope, callerSession = null, completio
119
178
  break;
120
179
  case "workflow":
121
180
  if (visW(frame.row)) {
181
+ // #189 / codex R4-M3 → [3193] ①a 泛化:**本连接首见即终态**的行(重放期或活径皆然)与终态窗
182
+ // 里的行是同一件事——它对这条连接从来不是"活跃集成员",是历史;它的撤行帧描述的活跃集离场
183
+ // 对本连接无意义,照发只会让"看不看得见刚结束的 workflow"取决于 recover 落在握手窗哪一侧
184
+ // (cli [3193] 插桩实证:落在重放窗内=保留可见,落在重放窗后=终帧+撤行背靠背、行瞬现即消)。
185
+ // ⇒ 判据=「重放期 ∪ 首见即终态」并集(#189 原判据的严格超集):重放期臂保住"快照见过
186
+ // running、缓冲里才翻终态"的行(R4-M3);首见臂保住活径上 recover 晚到的行(①a)。见过
187
+ // running 的行在活径仍按既有契约走(终帧→撤行),在线消费端语义不变。豁免仍一次性,集合有界如旧。
188
+ // [3193] codex R5:已在保留集里的 id(快照径收的)不重复扣预算——否则握手重放把同一批行
189
+ // 按"快照+重放"记两次账,40 预算被快照行白耗光,其后真正的首见历史行立刻失去豁免。
190
+ if ((replayingBuffer || !seenWf.has(frame.row.id)) && isTerminalWorkflowRowStatus(frame.row.status) && !retainedTerminalWf.has(frame.row.id) && retainedHistoryBudget > 0) {
191
+ retainedTerminalWf.add(frame.row.id);
192
+ retainedHistoryBudget--;
193
+ }
122
194
  seenWf.add(frame.row.id);
123
195
  send("workflow", { row: stripW(frame.row), ts: frame.ts });
124
196
  }
@@ -128,6 +200,17 @@ function streamFleet(req, res, bus, callerScope, callerSession = null, completio
128
200
  send("task_remove", { id: frame.id, ts: frame.ts });
129
201
  break;
130
202
  case "workflow_remove":
203
+ // 🔴 #189 / codex R2-M1:按窗**刻意保留**的历史行不受本连接的撤行帧影响。行在 durable 读
204
+ // 期间翻终态时,活写路径的「终帧 + 撤行」会落进缓冲,重放到这里就会把快照刚保住的那一行
205
+ // 又撤掉 —— 于是「看不看得见刚结束的 workflow」重新取决于连接时机(晚 1ms 连上的人看得见,
206
+ // 撞上这一拍的人看不见),正是本 issue 要消灭的竞态。撤行帧描述的是**活跃集**离场,而这些
207
+ // 行进快照时就已经是终态历史,不在活跃集语义里。id 不复用(runId 每次新铸,终态不回滚),
208
+ // 故这层豁免既有界又不会误伤后来的真活行。
209
+ // 豁免**一次性**:配对的那一帧撤行到达即消费(codex R5-M3)。否则这个 id 被永久噤声——
210
+ // 同 id 若之后又出现活行(帧乱序/未来的行复用),它的撤行帧也会被吞,面板留一条撤不掉的死行;
211
+ // 顺带,每条长连接的保留集不再随握手期完成数无界增长。
212
+ if (retainedTerminalWf.delete(frame.id))
213
+ break;
131
214
  if (seenWf.delete(frame.id))
132
215
  send("workflow_remove", { id: frame.id, ts: frame.ts });
133
216
  break;
@@ -217,6 +300,21 @@ function streamFleet(req, res, bus, callerScope, callerSession = null, completio
217
300
  default:
218
301
  break; // snapshot frames are connect-time only, never fanned out
219
302
  }
303
+ };
304
+ // 🔴 #189 / codex R1-H1:订阅**先于**快照注册,快照组装期间到达的帧先进缓冲、发完快照再按序重放。
305
+ // 快照第一次有了一段 await(durable 终态窗读),而 fleet bus 只扇给**当前**订阅者、不重放 —— 先读后
306
+ // 订阅就等于开了一个"这段时间的帧对本连接不存在"的窗口(bg_notification 是模型注入面,丢一帧=这次
307
+ // 完成回执要等到下次开流才由 durable inbox 补;task_remove/hook_notice 同理)。
308
+ // 顺序安全:`bus.snapshot()` 取在**读之后**,缓冲里的行帧描述的都是快照那一刻或更早的状态,重放
309
+ // 只会把同一状态再叠一次(upsert 幂等);撤行帧仍按 seen 集判(没见过的行不发撤除)。
310
+ // 缓冲无显式上限:窗口被读预算硬界在 2s,且缓冲存的是**帧对象引用**(不复制行);设一个会丢帧的
311
+ // 上限反而正好丢掉这段代码要保住的东西。
312
+ let buffered = [];
313
+ const unsubscribe = bus.subscribe((frame) => {
314
+ if (buffered !== null)
315
+ buffered.push(frame);
316
+ else
317
+ handleFrame(frame);
220
318
  });
221
319
  // Real frame (not an SSE comment) — a per-frame-parsing BFF drops comments (zero-frame window downstream)
222
320
  const hb = setInterval(() => { if (!res.writableEnded)
@@ -234,8 +332,56 @@ function streamFleet(req, res, bus, callerScope, callerSession = null, completio
234
332
  res.end();
235
333
  resolve();
236
334
  };
335
+ // 关闭钩子在 await **之前**挂上:快照还在组装时对端就断了,也照常收摊(不然那段时间的断连没人处理)。
237
336
  req.on("close", shutdown);
238
337
  res.on("close", shutdown);
338
+ void (async () => {
339
+ // [3193] 病理1:boot recover(判死前世 running 行)与快照组装赛跑——SIGKILL 后壳重连常抢在
340
+ // recover 之前,此刻 seed/durable 两径皆空,快照永远缺那一行。屏障=recovery 完成 promise
341
+ // (main.ts 铸,memory 后端/无 gate 部署=已 resolve),**有界**等待(帧订阅已挂上,等待期帧全
342
+ // 进缓冲不丢):超时=recover 真挂了,按旧行为出快照(可用性路径,行还有 first-sight-terminal
343
+ // 豁免与下次重连兜底),不无限拖住连接。
344
+ if (terminal?.ready !== undefined) {
345
+ await Promise.race([terminal.ready, new Promise((r) => { const t = setTimeout(r, 3000); if (typeof t.unref === "function")
346
+ t.unref(); })]);
347
+ if (done || res.writableEnded)
348
+ return;
349
+ }
350
+ // #189:durable 近期终态行窗(有界 + 永不抛;详见 fleet-terminal-window.ts)。
351
+ const terminalWindow = terminal === undefined ? [] : await recentTerminalWorkflowRows(terminal.store, terminal.scope, terminal.pullScope);
352
+ if (done || res.writableEnded)
353
+ return; // 组装期间断连:shutdown 已 unsubscribe,不再发任何东西
354
+ // connect-time snapshot (filtered + scope-stripped) — the visible rows become this connection's "seen" set.
355
+ const snap = bus.snapshot();
356
+ const tasks = snap.tasks.filter(visT);
357
+ const live = snap.workflows.filter(visW);
358
+ // #189:活行(bus 的活跃集)+ durable 终态窗。
359
+ // · 一行一 id:同 id 两侧都有(行刚翻转的那一拍)时 **活行优先** —— 活行是唯一写者写的当前态,
360
+ // 终态窗是读时快照,后者覆盖前者会让面板倒退。
361
+ // · 并入行同样过 `visW`(scope + `?session=`),与活行**同一套判据**:终态行泄跨租户是事故。
362
+ // · bus 的 Map **不被触碰** —— 单写者不变量原样:活跃集里永远没有终态行,增量帧语义逐字不变。
363
+ const liveIds = new Set(live.map((r) => r.id));
364
+ const retained = terminalWindow.filter((r) => !liveIds.has(r.id) && visW(r));
365
+ retained.forEach((r) => retainedTerminalWf.add(r.id));
366
+ const workflows = [...live, ...retained];
367
+ tasks.forEach((r) => seenTasks.add(r.id));
368
+ workflows.forEach((r) => seenWf.add(r.id));
369
+ send("snapshot", { tasks: tasks.map(stripT), workflows: workflows.map(stripW), ts: snap.ts });
370
+ const pending = buffered ?? [];
371
+ buffered = null; // 自此直投(先置空再重放:重放期间新到的帧走直投,不会插到旧帧前面)
372
+ replayingBuffer = true;
373
+ try {
374
+ for (const frame of pending)
375
+ handleFrame(frame);
376
+ }
377
+ finally {
378
+ replayingBuffer = false; // 重放一结束立刻恢复常态语义(哪怕上面抛了)
379
+ }
380
+ })().catch(() => shutdown());
381
+ // ⚠️ 上面这个 catch 不是"静默降级":快照组装本身抛错(写向已销毁的 socket 那一族)时**没有**可以继续
382
+ // 的语义——这条连接已经没救了,干净收摊即正解。它真正防的是把原先同步执行器里的抛错(会直接 reject
383
+ // 出去)变成一条 **unhandled rejection**(Node 默认带走整个进程)。订阅回调自身的抛错另有隔离层
384
+ // (fleet bus 的 subscribe,记 fail-open),不经这里。
239
385
  });
240
386
  }
241
387
  //# sourceMappingURL=fleet.js.map
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { uuidv7, mintCheckpointToken, CheckpointError, validatePendingSteer } from "@sema-agent/core";
3
+ import { isTerminalRunStatus } from "../../plugins/store-contracts.js";
3
4
  import { redactSecrets } from "../../trace/redact.js";
4
5
  import { HttpError, verifiedPrincipal, isUuidV7, encodeCheckpointScope } from "../../security.js";
5
6
  import { runInBackground } from "../../runs.js";
@@ -575,7 +576,10 @@ async function handleRunsBody(req, res, url, ctx, miss) {
575
576
  // 并发腿可能先终态化(如 approval.expired),我方写打空却仍答 "cancelled" 就是响应与账本不一致。
576
577
  // 写后复读,照实际行应答(锁一样释放了;谁先写赢谁的 errorCode)。
577
578
  const finalRow = await rs.getRun(taskId).catch(() => undefined);
578
- if (finalRow && finalRow.errorCode !== "cancelled" && (finalRow.status === "failed" || finalRow.status === "completed" || finalRow.status === "blocked")) {
579
+ // 终局判据取自词表属主 `store-contracts.ts` 的穷举 `isTerminalRunStatus`(原地手抄的三连 `===`
580
+ // 对 core **增**一个终局态是静默的:新态会被判成「还没终局」⇒ 这里改答 "cancelled",与账本不一致,
581
+ // 正是本段注释要防的那件事)。
582
+ if (finalRow && finalRow.errorCode !== "cancelled" && isTerminalRunStatus(finalRow.status)) {
579
583
  sendJson(res, 202, { taskId, status: finalRow.status, errorCode: finalRow.errorCode ?? null, note: `session unlocked; the run was terminalized concurrently (${finalRow.errorCode ?? finalRow.status}) before this cancel's write — reporting the actual ledger state` });
580
584
  return;
581
585
  }