dsh-subagent-dispatch-control 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +183 -2
- package/client.js +9781 -0
- package/cordis.patch.yml +13 -0
- package/docs/BOOST-EVIDENCE.md +259 -0
- package/docs/CONFORMANCE.md +236 -0
- package/docs/FACTS-CONTRACT.md +368 -0
- package/docs/FLOW-COVERAGE.md +215 -0
- package/docs/PACKAGE-README.md +858 -0
- package/docs/RANGE-PLAN.md +357 -0
- package/docs/SECURITY-NOTES.md +110 -0
- package/docs/SPLIT-PLAN.md +604 -0
- package/docs/STAGE3-CONTRACT.md +287 -0
- package/docs/TIER-ROUTING.md +275 -0
- package/docs/badge/CONFORMANCE.md +246 -0
- package/docs/badge/DETAIL.md +319 -0
- package/docs/badge/PROJECTIONS.md +264 -0
- package/docs/badge/TEST-PLAN.md +252 -0
- package/docs/images/badge-menu.png +0 -0
- package/docs/images/dispatch.png +0 -0
- package/docs/images/header.png +0 -0
- package/docs/images/pair-header.png +0 -0
- package/docs/images/pair-panel.png +0 -0
- package/docs/images/panel.png +0 -0
- package/docs/wiki/Home.md +43 -0
- package/docs/wiki//344/275/277/347/224/250/346/214/207/345/215/227.md +97 -0
- package/docs/wiki//345/256/211/350/243/205/344/270/216/345/215/207/347/272/247.md +87 -0
- package/docs/wiki//346/225/205/351/232/234/346/216/222/346/237/245.md +94 -0
- package/icon.svg +12 -0
- package/lib/badge-policy.mjs +502 -0
- package/lib/badge-sync.mjs +385 -0
- package/lib/command.mjs +490 -0
- package/lib/completion.mjs +288 -0
- package/lib/concurrency.mjs +2555 -0
- package/lib/dispatch-command.mjs +181 -0
- package/lib/dispatch-gate.mjs +924 -0
- package/lib/facts-store.mjs +183 -0
- package/lib/gate-state.mjs +465 -0
- package/lib/gate.mjs +886 -0
- package/lib/index.js +309 -0
- package/lib/inject.mjs +195 -0
- package/lib/interrupt.mjs +376 -0
- package/lib/ledger.mjs +948 -0
- package/lib/lifecycle.mjs +274 -0
- package/lib/messages.mjs +532 -0
- package/lib/notice.mjs +769 -0
- package/lib/plan-gate.mjs +385 -0
- package/lib/projection.mjs +978 -0
- package/lib/report.mjs +290 -0
- package/lib/route.mjs +346 -0
- package/lib/run-registry.mjs +402 -0
- package/lib/services.mjs +293 -0
- package/lib/stuck.mjs +567 -0
- package/lib/tier-config.mjs +212 -0
- package/lib/tier-policy.mjs +167 -0
- package/lib/tier-state.mjs +137 -0
- package/lib/todo-gate.mjs +1672 -0
- package/lib/tools.mjs +2912 -0
- package/locale/en.json +9 -0
- package/locale/zh.json +9 -0
- package/package.json +83 -4
- package/vendor/node_modules/@deepseek-ai/cosmokit/LICENSE +21 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/README.md +30 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/lib/index.js +418 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/package.json +32 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/array.ts +42 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/index.ts +12 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/misc.ts +78 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/string.ts +113 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/time.ts +92 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/types.ts +168 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/volatile.ts +86 -0
- package/vendor/node_modules/@deepseek-ai/schemastery/LICENSE +21 -0
- package/vendor/node_modules/@deepseek-ai/schemastery/README.md +393 -0
- package/vendor/node_modules/@deepseek-ai/schemastery/lib/index.cjs +635 -0
- package/vendor/node_modules/@deepseek-ai/schemastery/lib/index.mjs +635 -0
- package/vendor/node_modules/@deepseek-ai/schemastery/package.json +39 -0
- package/vendor/node_modules/@deepseek-ai/schemastery/src/index.ts +962 -0
- package/vendor/node_modules/@standard-schema/spec/LICENSE +21 -0
- package/vendor/node_modules/@standard-schema/spec/README.md +198 -0
- package/vendor/node_modules/@standard-schema/spec/dist/index.cjs +18 -0
- package/vendor/node_modules/@standard-schema/spec/dist/index.js +0 -0
- package/vendor/node_modules/@standard-schema/spec/package.json +39 -0
package/lib/gate.mjs
ADDED
|
@@ -0,0 +1,886 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 并发派发确认闸(round-7 新增;round-7c 改为真实生命周期计数;round-9 v4 runId 集合 + 轮次作用域)。
|
|
3
|
+
* **当前主功能摘要见文件头 v13 块(v1–v12 均为历史,仅供防回退参考)。**
|
|
4
|
+
*
|
|
5
|
+
* 背景(用户实测反馈 + 第五轮审计):
|
|
6
|
+
* 插件原本只有 systemPrompt 里的一句软提示("并发前先调用 suggest_concurrency")。
|
|
7
|
+
* 实测该约束形同虚设——模型完全可以直接派发多个子代理,用户从未被问过并发数。
|
|
8
|
+
*
|
|
9
|
+
* ── 版本迭代的教训(v1–v13;每一版都被审计打回,记录在此防止回退)──
|
|
10
|
+
*
|
|
11
|
+
* v1(在途计数,按 tools/execute 调用期):
|
|
12
|
+
* ✗ R1-01:官方 `subagent` 的 execute 是**启动后立即返回**(startLocal 文档写明
|
|
13
|
+
* "resolve at initial inbox acceptance"),子代理在后台继续跑。于是
|
|
14
|
+
* ① 同批快速返回时第 2 路看不到"在途"
|
|
15
|
+
* ② 被拦的 2..N 路可在 1 路返回后逐条重发 → 全部放行
|
|
16
|
+
* 实测 5 个子代理全部启动、用户 0 次确认。
|
|
17
|
+
*
|
|
18
|
+
* v2(时间窗口,放行后 10 分钟内都算在途):
|
|
19
|
+
* ✓ 堵住了 v1 的逐条重发绕过
|
|
20
|
+
* ✗ R2-01:**误伤串行派发**。用户"派一个、等完、再派一个"是最常见的正常用法,
|
|
21
|
+
* 但窗口内第 2 路也被拦。闸已无法区分"同批并发"与"先后串行"。
|
|
22
|
+
*
|
|
23
|
+
* v3(真实生命周期事件,round-7c):
|
|
24
|
+
* ✓ 订阅宿主 `subagent/start` 与 `subagent/end`(dsh-subagent 的 emitLifecycle),
|
|
25
|
+
* 按 `parentSessionId` 维护"当前真正在跑的子代理数"。
|
|
26
|
+
* ✓ 串行派发:前一个 end 之后才 start 下一个 → 在跑数归零 → 不拦。
|
|
27
|
+
* ✓ 同批并发:第 2 路进入时第 1 路仍在跑(尚未 end)→ 在跑数 ≥1 → 拦。
|
|
28
|
+
* ✗ A-01(round-8):计数**跨轮存活**。上一轮的子代理还没 end 时,新一轮的
|
|
29
|
+
* **单路**派发也被拦——而文案还写着"单路不受影响"。
|
|
30
|
+
* ✗ A-02 / C3-01:孤儿 start(崩溃 / 取消 / 宿主 rollbackUnpublished 路径不发 end)
|
|
31
|
+
* 让计数永久 +1 → 该 session **所有**派发永久被拦,无 TTL、无自愈。
|
|
32
|
+
* ✗ C3-02:只按 parentSessionId 做 ±1,**零引用 runId**。同一 run 发两次 end
|
|
33
|
+
* 会把另一个仍在跑的 run 抵消掉(下溢)→ 漏拦。
|
|
34
|
+
*
|
|
35
|
+
* v4(round-9 修复;历史,非当前):
|
|
36
|
+
* ① 计数容器换成 `Map<parentSessionId, Map<runKey, { startedAt, gen }>>`。
|
|
37
|
+
* start 以 runId 为键写入,end 按 runId 删除 → **重复 end 天然幂等**(C3-02 修复),
|
|
38
|
+
* 且每个 run 可枚举、可超时回收(A-02/C3-01 的兜底前提)。
|
|
39
|
+
* ② 「本轮并发」= 同一个 turn 内 start 的 run。订阅 `session/event` 的 `turn/start`,
|
|
40
|
+
* 把该 session 的轮次代数 +1,并把**上一代及更早**的 run 全部出清
|
|
41
|
+
* (上一轮遗留的子代理不再参与本轮判定)→ A-01 修复。
|
|
42
|
+
* 这也是 A-02 的根治点:孤儿 start 最多锁死它自己那一轮,下一轮开始即自愈。
|
|
43
|
+
* ③ 兜底三层:轮次边界(正常宿主)→ run 存活上限 staleRunMs(宿主不发 turn/start 时)
|
|
44
|
+
* → 计数异常逃生阀 sanityCap(end 大面积丢失时降级放行并告警)。
|
|
45
|
+
* 三层都只会让闸**少拦**(fail-open),绝不会把用户永久锁死。
|
|
46
|
+
* ④ D-01 自检:`agent.id !== agent.session?.id` 时 warn 一次。宿主 runInfo 的
|
|
47
|
+
* `parentSessionId` 取的是 `activation.ancestors.at(-1)`(creator 的 **agent id**),
|
|
48
|
+
* 而本闸按 `agent.session.id` 归组;两者不同时计数可能与派发会话对不上
|
|
49
|
+
* (方向是 fail-open)。这里不擅自改键(R1-06 的防串号约束仍在),但让它在日志可见。
|
|
50
|
+
*
|
|
51
|
+
* v5(B1-P0-1 / B1-P1-2 修复;历史,非当前):
|
|
52
|
+
* ① B1-P0-1(P0 竞态):v4 只按 subagent/start 计数,但官方 batch 调度器对
|
|
53
|
+
* `isConcurrencySafe: () => true` 的 subagent **并发启动**同批调用,而
|
|
54
|
+
* subagent/start 要等子代理工具体内 resolveDirectory → materialize →
|
|
55
|
+
* agents.create 多层 await 之后才 emit(宿主 manager.startActivation 的
|
|
56
|
+
* 最后一个 rollback-protected 步)。于是第 2 路判定时第 1 路尚未计数 →
|
|
57
|
+
* 两路一起放行。C2 实测:工具体 emit 前 await=0 时拦得住,await≥1 时全部放行
|
|
58
|
+
* (结构性必然,不是时序巧合)。
|
|
59
|
+
* 现在:判定通过后**先占位再进工具体**(beginCall / finally 释放),
|
|
60
|
+
* 判定用「生命周期在跑数 + 在途派发数」,把 pre-emit 窗口整个覆盖掉。
|
|
61
|
+
* ② B1-P1-2:旧回滚按「不在本调用进入时的快照里」删除,会把同批兄弟在本调用
|
|
62
|
+
* 执行期间刚起的合法 run 一起删掉(C2 实测:A 仍在跑,B 失败回滚后
|
|
63
|
+
* inFlightCount = 0 → 后续 fail-open)。现在每次派发带唯一 token,并用
|
|
64
|
+
* AsyncLocalStorage 记录「该次调用自己的异步上下文」:start 在谁的上下文里
|
|
65
|
+
* emit 就归谁(owner),回滚只删 owner 是自己的 run。
|
|
66
|
+
* 无上下文的 start(孤儿 / 宿主改为延迟 emit)一律不归因 → 绝不误删兄弟的 run,
|
|
67
|
+
* 留给 turn/start 或 staleRunMs 兜底(与 A-02 同一套,方向 fail-open)。
|
|
68
|
+
*
|
|
69
|
+
* v6(R1 修复:第二轮三层审计 P1 + M1 + P2;历史,非当前):
|
|
70
|
+
* ① P1(took tools.mjs):确认卡的**任意**选项都写 confirmed: true,于是
|
|
71
|
+
* 「按建议执行:不派发」「改为串行」「不派发」、自定义输入都被当成用户授权;
|
|
72
|
+
* tools.mjs 拿到 confirmed 就 markConcurrencyConfirmed → 本会话**永久**放行并发。
|
|
73
|
+
* 现在解锁要同时满足 confirmed 与 concurrencyApproved,后者由选项语义表
|
|
74
|
+
* (用户选择 vs 建议 mode 的结构化比较)得出 —— 本模块只消费结果,判据不变。
|
|
75
|
+
* ② M1(unavailable 永久粘滞):标记写入后从不清除,一次环境性失败就把该
|
|
76
|
+
* session 的闸永久关掉(turn/start 不自愈,单会话 reset 也漏清)。
|
|
77
|
+
* 现在 turn/start 与单会话 reset 都会清掉它;降级语义保留(下次派发所在轮
|
|
78
|
+
* 若仍问不了,调用 suggest_concurrency 会重新探测并重新标记;单路派发不拦)。
|
|
79
|
+
* ③ P2(卸载不摘监听器):dispose 只清状态、丢弃 ctx.on 的返回值,卸载后闸
|
|
80
|
+
* 仍拦(L1-B P2-2 探针 off=0)。现在收集所有 ctx.on 返回的 off 并在 dispose
|
|
81
|
+
* 里逐个调用,与 todo-gate.mjs / stuck.mjs 同款。
|
|
82
|
+
*
|
|
83
|
+
* v7(本轮 M2b 修复:02 三闸审计 F5 + t3「会话级单向阀门」):
|
|
84
|
+
* ① 确认按轮生效(t3 问题4):confirmedSessions 由「Set<sessionKey> 永久集合」改为
|
|
85
|
+
* 「Map<sessionKey, { turn, at }>」,记录授权时所在轮次代数;isConcurrencyConfirmed
|
|
86
|
+
* 仅在 record.turn === currentGen(key) 时返回 true,recordTurnStart 在换轮时删除旧记录。
|
|
87
|
+
* 语义:用户点过一次「并发 N 路」只对本轮有效,下一轮 turn/start 自动失效、需重新确认
|
|
88
|
+
* —— 既保留「确认后同轮放行」的既有行为,又消除「一次授权、本会话永久免确认、无法撤销」
|
|
89
|
+
* 的单向阀门。确认发生在 suggest_concurrency 工具执行内、与随后派发同一轮,正常流程不受影响。
|
|
90
|
+
* ② 跨轮逐条派发的语义边界明示(F5/P2):见下方语义边界第 10 条。
|
|
91
|
+
*
|
|
92
|
+
* v8(本轮 M2r 返修:授权粒度按 N + 与「只派 1 路」选项合并,V2 残留 #2 / t3 问题4):
|
|
93
|
+
* ① 授权粒度:confirmedSessions 的值由 { turn, at } 扩展为 { turn, at, concurrency },
|
|
94
|
+
* markConcurrencyConfirmed(agent, concurrency) 记录用户确认的**路数上限 N**;
|
|
95
|
+
* 放行判据由「本轮确认过就放行」收紧为「本轮确认过、且本轮在跑+在途路数 < N 才放行」。
|
|
96
|
+
* 未传 N(legacy 调用 / 测试直调)时 N 记为 Infinity,等价旧「本轮确认即放行」,语义不回退。
|
|
97
|
+
* ② 与「只派 1 路」选项合并(V2 残留 #1/#2 合并设计):确认卡的「只派 1 路子代理(不并发)」
|
|
98
|
+
* 选项旗标 false(不解锁)—— 落闸后本轮只放行第 1 路、第 2 路仍被拦,行为上与「确认 N=1」
|
|
99
|
+
* 一致;而「按建议执行:并发 N 路」确认后放行上限为 N。二者共用同一套「按轮 + 按 N」判据。
|
|
100
|
+
*
|
|
101
|
+
* v9(M13 修复:用户实测 2026-11-25 12:1x「串行点选不清空」):
|
|
102
|
+
* v6 起轮次展示纪元(confirmationEpochs)由 markConcurrencyConfirmed 顺带推进,
|
|
103
|
+
* 而该函数只在 confirmed && concurrencyApproved 时被调用 —— 于是「按建议执行:串行」
|
|
104
|
+
* 「改为串行」「不派发」等**真实决策**不写纪元 → 面板不清空(旧轮 agent 全部留着)。
|
|
105
|
+
* 现在把「闸放行」与「轮纪元」彻底拆成两个职责:闸放行维持现条件;轮纪元由新增的
|
|
106
|
+
* recordDecisionEpoch(任何 answered === true 调用)推进,二者共用 recordConfirmationEpoch
|
|
107
|
+
* 单调逻辑 / 同一张 confirmationEpochs 表。串行点选:纪元写、面板清、闸**不**解锁。
|
|
108
|
+
*
|
|
109
|
+
* v10(本轮 N3 / SEC-B-01·ARB-P3-05 修复:同轮「最近答复」撤销既有授权):
|
|
110
|
+
* ① 仲裁 ARB-P3-05(P3 增强):同轮先确认并发 N 路后,用户在**同一轮**的确认卡上改选到
|
|
111
|
+
* 任何不构成并发同意的答复(改为串行 / 不派发 / 只派 1 路 / 自定义输入)时,本轮既有
|
|
112
|
+
* 授权仍在 —— 闸按旧 N 继续放行第 2 路(探针 13/13 行为级坐实;跨轮撤销已由 v7 闭合,
|
|
113
|
+
* 这是同轮缺口)。现在 tools.mjs 在 answered && !concurrencyApproved 分支调用本模块
|
|
114
|
+
* 新增的 revokeConcurrencyConfirmation 撤销 confirmedSessions 条目。
|
|
115
|
+
* ② 为什么不直接调 resetConcurrencyConfirmation:reset(agent) 还会清 confirmationEpochs
|
|
116
|
+
* (M13 决策纪元)与 runsByParent / callsByParent(本轮在跑 / 在途计数)。清纪元会让
|
|
117
|
+
* 同 tick 的 recordDecisionEpoch 写入被抹掉或 seq 从 1 重计(破坏「跨刻 seq 单调 +1」
|
|
118
|
+
* 与客户端 resolveConfirmEpoch 同刻取大 seq 的合并规则);清在跑计数会让本轮已启动、
|
|
119
|
+
* 尚未结束的子代理从闸的账上消失(fail-open 方向的闸完整性破口)。撤销授权只需要
|
|
120
|
+
* 「本轮不再放行并发」这一件事,故 revoke 只删 confirmedSessions。
|
|
121
|
+
* ③ 与 M13 的职责并存(都写,同 tick 顺序固定):tools.mjs 对 answered === true 先
|
|
122
|
+
* recordDecisionEpoch(决策纪元,面板清旧轮),再按 approved 分叉——approved →
|
|
123
|
+
* markConcurrencyConfirmed(解锁 + 同刻纪元沿用);!approved →
|
|
124
|
+
* revokeConcurrencyConfirmation(只撤授权,纪元保留)。两职责互不覆盖。
|
|
125
|
+
*
|
|
126
|
+
* v11(本轮 P2 修复:磁盘事实源 + 台账重档,2026-11-25 任务-52):
|
|
127
|
+
* ① 根因:纪元/派发事实只活在进程内存(confirmationEpochs / runsByParent),
|
|
128
|
+
* 宿主重启即失;主会话投影断链(ctx.inject 晚绑定未生效)时浏览器拿不到
|
|
129
|
+
* 任何事实 → 面板显示旧轮(用户实测「面板不刷新」)。记录体系遵循同一取向:
|
|
130
|
+
* 数据层全在磁盘,UI 只读磁盘,不依赖运行时投影单点。
|
|
131
|
+
* ② 落盘形态(按主会话分目录,追加式 JSONL):
|
|
132
|
+
* <home>/.dsh/team-preflight/sessions/<encodeURIComponent(sessionKey)>/
|
|
133
|
+
* ├── epochs.jsonl 纪元历史:{kind:'confirm'|'decision'|'revoke'|'reset', epochTime, seq, at, sessionKey}
|
|
134
|
+
* └── ledger.jsonl 派发台账:{kind:'start'|'end'|'error', agentId, runId, name,
|
|
135
|
+
* createdAt/endedAt, stopReason, sessionKey};start 行增补可选
|
|
136
|
+
* tier/model(档位记账 2026-11-27;无档位 → 键级缺席,旧格式行为逐字不变)
|
|
137
|
+
* epoch 落盘挂在 recordConfirmationEpoch 单一漏斗(markConcurrencyConfirmed /
|
|
138
|
+
* recordDecisionEpoch / revokeConcurrencyConfirmation 三个公开入口共用);
|
|
139
|
+
* ledger 落盘挂在既有 subagent/start、subagent/end 监听器内——不新增 ctx.on,
|
|
140
|
+
* dispose 纪律不变(见 v6 P2)。
|
|
141
|
+
* ③ 写侧纪律:全部 try/catch 静默降级(磁盘失败绝不影响闸判定/确认主流程);
|
|
142
|
+
* mkdirSync 目录懒建去重;appendFileSync 追加不覆盖。
|
|
143
|
+
* ④ 读侧纪律(脏读防御):逐行独立 JSON.parse,坏行跳过;文件不存在/读失败视为空;
|
|
144
|
+
* 磁盘值按 (mtimeMs, size) 缓存,文件未变时返回同一冻结引用(V11 R1 引用稳定契约);
|
|
145
|
+
* readConfirmationEpochFromDisk 内存命中优先、未命中才读磁盘(投影 view 的磁盘兜底层);
|
|
146
|
+
* 确认纪元推进只认 confirm|decision 行(revoke 只记事实,v10:撤销不清纪元)。
|
|
147
|
+
* ⑤ 重定向接缝(与 tools.mjs DSH_SUBROUTE_HOME 同款先例,N3):DSH_TP_HOME 环境变量
|
|
148
|
+
* 优先——测试把它指向临时目录,绝不写真实 ~/.dsh;测试进程(argv[1] 命中
|
|
149
|
+
* test*.mjs / test*.js)且未设置 DSH_TP_HOME → 落盘/读盘整体禁用(纵深防御:
|
|
150
|
+
* 即使套件漏配重定向也不会污染真实目录;生产宿主 argv 是 DSH 主程序,不受影响)。
|
|
151
|
+
* ⑥ 与 M8 localStorage 的分工:磁盘 = 宿主侧权威历史(跨重启、跨浏览器);
|
|
152
|
+
* localStorage = 浏览器侧最后兜底(投影完全断链时仍有 M8 旧值)。
|
|
153
|
+
*
|
|
154
|
+
* v12(批次1/W3 磁盘台账第一批,2026-11-25;仲裁定谳报告 A-03/A-04/A-05/A-09/A-11/A-19):
|
|
155
|
+
* 只动「写盘 / 读盘」三函数与落盘根解析,业务判据(闸放行、纪元单调、语义边界 1-11)一字不改。
|
|
156
|
+
* ① A-03 断链自愈:append 失败即撤销 tpDirsCreated 缓存 → 重建目录 → **重试一次**;
|
|
157
|
+
* 重试成功 / 最终失败各 warnOnce 一次(旧实现完全静默,用户与审计都无法察觉)。
|
|
158
|
+
* ② A-04 半行防粘连:本进程首次写某 JSONL(或上次写失败后)先校验末字节,非换行则先补
|
|
159
|
+
* 换行 —— 崩溃残留的半行不再把紧随其后的 1 条正常记录粘成坏行。常态路径零额外 syscall。
|
|
160
|
+
* ③ A-05 缓存一致性:ledgerDiskHydrated 由「每进程每 key 一次」改为按 mtime+size 增量水合
|
|
161
|
+
* (外部追加可见);ledgerSnapshotCache 加磁盘签名复验(有事实的快照按
|
|
162
|
+
* DISK_REVALIDATE_MS 复验,空快照零 syscall);epochDiskState 的 miss 结果也缓存
|
|
163
|
+
* (旧实现每次投影折叠付一次 statSync,R3 实测 136x 成本税)。
|
|
164
|
+
* ④ A-09 落盘根校验:DSH_TP_HOME 设了就必须 trim 后非空且为绝对路径,否则**禁用落盘**
|
|
165
|
+
* (旧实现把空白值当根 → cwd 下建怪名目录;相对路径静默按 cwd 解析)。
|
|
166
|
+
* ⑤ A-11 路径段校验:encodeURIComponent 不转义点号 → '.' / '..' 这两个 key 会逃出 sessions/
|
|
167
|
+
* 一层,现直接拒绝(返回 null,落盘/读盘整体 no-op)。
|
|
168
|
+
* ⑥ A-19 磁盘纪元语义:读侧由「取最大 epochTime」改为**最后一条有效行胜出**(append-only
|
|
169
|
+
* 的自然语义,与内存侧「最后一次写入」一致)—— 时钟回拨后写的新决策不再被回拨前的
|
|
170
|
+
* 旧纪元压过(R3 C2b 实证)。
|
|
171
|
+
*
|
|
172
|
+
* v13(本轮:agent/error 捕获 —— 台账 error 行 + 面板「报错」确切化):
|
|
173
|
+
* ① 背景:宿主 dsh-agent 有 agent/error 事件(payload { agent, turn, step, error },
|
|
174
|
+
* runtime-types.d.ts:411),表示某 step/turn 报错。此前插件只记 subagent/start、
|
|
175
|
+
* subagent/end 的 stopReason —— agent/error 之后若没有 subagent/end(宿主重启 /
|
|
176
|
+
* 事件丢失),面板只能显示「疑似中断」,无法显示确切的「报错」。
|
|
177
|
+
* ② 写侧:新增模块级 childRunBySession(childSessionId -> { key, runId })反查表,
|
|
178
|
+
* 在 onStart 的 try 内登记(与台账落盘同一段)、onEnd 清理;agent/error 经反查
|
|
179
|
+
* 定位所属派发,ledgerRecordError 追加 kind:'error' 行
|
|
180
|
+
* { kind, agentId, runId, at, message(截断 200 字符), sessionKey };失败静默。
|
|
181
|
+
* ③ 读侧:applyLedgerEvent 认 kind:'error' —— 按 runId(agentId 校验)找 run:
|
|
182
|
+
* errorAt=parsed.at(缺失忽略该行)、stopReason='error'、errorMessage(缺失 null);
|
|
183
|
+
* **不设置 endedAt**(报错 ≠ 收场,run 是否结束仍只由 end 行决定)。
|
|
184
|
+
* ④ 快照:内存行增 errorAt/errorMessage(null 起步);buildLedgerSnapshot 行增可选
|
|
185
|
+
* errorAt(null 不挂键);status = endedAt===null ? (errorAt!==null?'error':'running')
|
|
186
|
+
* : (completed | 'error' | 'ended')。旧 ledger 行无 errorAt → 行为逐字不变。
|
|
187
|
+
* ⑤ 纪律:agent/error 走既有 listen()(disposers 统一摘除,v6 P2 同款);记账失败
|
|
188
|
+
* 静默(try/catch);DSH_TP_HOME 重定向同款;enabled:false 只关闸不关账。
|
|
189
|
+
*
|
|
190
|
+
* 语义边界(与实现逐条对齐,文案不得超出这里):
|
|
191
|
+
* 1. **只拦"本轮的并发"**:本轮(同一 turn)已有 run 在跑或已在途派发,且本会话未确认 → 拦。
|
|
192
|
+
* 2. **单路放行**:本轮没有任何在跑 run / 在途派发时派 1 路 → 放行;
|
|
193
|
+
* 上一轮的遗留 run 不算本轮。
|
|
194
|
+
* 3. **串行放行**:等前一个 end 之后再派下一个(同一轮内)→ 放行。
|
|
195
|
+
* 4. **逐条重发不放行**:第 1 路仍在跑(或仍在启动)时,本轮内重复派发 → 拦(R1-01 回归)。
|
|
196
|
+
* 5. **已确认放行(按轮 + 按 N 双约束)**:本轮确认过、且本轮在跑+在途路数 < 确认的 N 时才放行;
|
|
197
|
+
* 确认随 turn/start 失效(见 v7① / v8①)。N=1 即「只派 1 路」,本轮恰好放行 1 路、第 2 路仍拦;
|
|
198
|
+
* 未传 N 的 legacy 调用按不限路数(Infinity)放行,即旧「本轮确认即放行」行为(不回退)。
|
|
199
|
+
* 6. **环境缺失一律放行**:拿不到 agent / session / 服务 → 放行(并 warn 一次)。
|
|
200
|
+
* 7. **可关闭**:`enabled: false`(连计数都不做)。
|
|
201
|
+
* 8. **ask:false 不解锁**(R3-01):必须真正拿到用户答复。
|
|
202
|
+
* 9. **在途派发也算**(B1-P0-1):已进入 tools/execute、尚未返回的委派同样算本轮并发;
|
|
203
|
+
* 否则真实时序下第 2 路看不到第 1 路(它的 start 还没 emit)。
|
|
204
|
+
* 10. **跨轮逐条派发不算并发(刻意语义边界,F5/P2)**:每收到一次 turn/start 就清零本轮的
|
|
205
|
+
* run 与在途派发(这是 A-01/A-02 的根治点)。因此「派 1 路 → 按官方指引结束当前轮次 →
|
|
206
|
+
* 子代理结果回投触发新 turn/start → 再派 1 路」的序列不会被本闸累计成并发:每路之间隔一个
|
|
207
|
+
* 完整子代理生命周期,实际并发度低、接近串行,不属本闸拦截的「同轮并发」范围。这是明确的
|
|
208
|
+
* 边界声明,**当前不收紧**(收紧需宿主事件区分「由子代理结算开启的新轮」,可行性未核实;
|
|
209
|
+
* 贸然拦截会误伤合法的单路串行用法)。
|
|
210
|
+
* 11. **同轮改选即撤销(v10 / SEC-B-01·ARB-P3-05)**:本轮已确认 N 路后,用户在同一轮的
|
|
211
|
+
* 确认卡上改选到任何「不构成并发同意」的答复(answered === true 且
|
|
212
|
+
* concurrencyApproved !== true,含改为串行 / 不派发 / 只派 1 路 / 自定义输入)→
|
|
213
|
+
* revokeConcurrencyConfirmation 立即删除 confirmedSessions 条目,本轮回到「未确认」
|
|
214
|
+
* 状态:第 2 路起重新被拦,新派发需重新弹卡确认。只清授权、不清纪元(决策仍写面板、
|
|
215
|
+
* seq 保持单调)、不清在跑计数(已启动的子代理照常统计)。
|
|
216
|
+
*/
|
|
217
|
+
|
|
218
|
+
/* ══════════════════════════════════════════════════════════════════════════
|
|
219
|
+
* 结构重构(62-结构重构 / P1 W2-F-06/07/08):本文件是**装配与转发层**。
|
|
220
|
+
* 状态表/确认逻辑 → gate-state.mjs;台账/epoch → ledger.mjs;中断 → interrupt.mjs;
|
|
221
|
+
* run 计数/记录 → run-registry.mjs(三闸共用);数据生命周期 → lifecycle.mjs。
|
|
222
|
+
* 依赖方向:gate.mjs → 上述五模块(新模块之间仅 ledger/interrupt → run-registry 的纯 helper;无环)。
|
|
223
|
+
* 导出面:本文件保留全部旧导出名(re-export / 薄转发),test 与其它 lib 的 import 路径与签名不变。
|
|
224
|
+
* 每个 ?query 实例创建自己的一套状态实例,与原「模块级状态」的测试隔离语义一致。
|
|
225
|
+
* ══════════════════════════════════════════════════════════════════════════ */
|
|
226
|
+
|
|
227
|
+
import { realpathSync } from 'node:fs'
|
|
228
|
+
import { dirname, resolve, sep } from 'node:path'
|
|
229
|
+
import { DEFAULT_DISK_REVALIDATE_MS } from './ledger.mjs'
|
|
230
|
+
// W4-27:台账实例与事实读取搬到 lib/facts-store.mjs(最底层基础设施,不依赖任何业务模块)。
|
|
231
|
+
import { factsStore, createFactsStore } from './facts-store.mjs'
|
|
232
|
+
|
|
233
|
+
// 档位路由显式化(第二波):确认档位的磁盘事实由 tier-state.mjs 持有(另一 lane 的模块)。
|
|
234
|
+
// 防御性加载:模块缺失 / 加载失败 → readTierFactOf 恒 null(台账照记,只是不带档位字段)。
|
|
235
|
+
// 必须在 gate.mjs 顶层 import(?tier-bare 测试钩子按 parentURL 识别本实例并换成空模块)。
|
|
236
|
+
let tierStateMod = null
|
|
237
|
+
try { tierStateMod = await import('./tier-state.mjs') } catch { tierStateMod = null }
|
|
238
|
+
|
|
239
|
+
import { createGateState } from './gate-state.mjs'
|
|
240
|
+
import { createInterrupts } from './interrupt.mjs'
|
|
241
|
+
import { createRunRegistry, finiteNumberOf, isDelegationName, nonEmptyStringOf, parentKeyOf, runIdOf, sessionEventKeyOf, sessionKeyOf } from './run-registry.mjs'
|
|
242
|
+
import {
|
|
243
|
+
isLifecycleSegmentSafe as lifecycleSegmentSafe,
|
|
244
|
+
installLifecycleSweep as lifecycleInstallSweep,
|
|
245
|
+
purgeStaleSessions as lifecyclePurgeStaleSessions,
|
|
246
|
+
sweepLifecycle as lifecycleSweep,
|
|
247
|
+
} from './lifecycle.mjs'
|
|
248
|
+
|
|
249
|
+
/** 单个 run 的存活上限(毫秒)。超过即视为 end 丢失的孤儿并回收(A-02 兜底)。 */
|
|
250
|
+
const DEFAULT_STALE_RUN_MS = 30 * 60 * 1000
|
|
251
|
+
/** 本轮在跑数超过此值即判为"end 大面积丢失"的异常残留,降级放行并告警(逃生阀)。 */
|
|
252
|
+
const DEFAULT_SANITY_CAP = 32
|
|
253
|
+
/** 告警去重集合的上限(超过就整体清空,避免无界增长)。 */
|
|
254
|
+
const MAX_WARN_KEYS = 64
|
|
255
|
+
/** 中断标志 TTL(10 分钟,设计文档 V-INT-4)。 */
|
|
256
|
+
const DEFAULT_INTERRUPT_FLAG_TTL_MS = 10 * 60 * 1000
|
|
257
|
+
/** 数据生命周期清理日志缺省文件名(D3;具体路径由 lifecycle.mjs 拼)。 */
|
|
258
|
+
const CLEANUP_LOG_FILE = 'cleanup-log.jsonl'
|
|
259
|
+
|
|
260
|
+
/** 由 installConcurrencyGate 覆盖:单 run 存活上限。 */
|
|
261
|
+
let staleRunMs = DEFAULT_STALE_RUN_MS
|
|
262
|
+
/** 由 installConcurrencyGate 覆盖:在跑数逃生阀阈值。 */
|
|
263
|
+
let sanityCap = DEFAULT_SANITY_CAP
|
|
264
|
+
/** 由 installConcurrencyGate 覆盖:时钟(测试可注入)。 */
|
|
265
|
+
let clock = () => Date.now()
|
|
266
|
+
/** 由 installConcurrencyGate 覆盖:快照复验节流(0 = 每次复验)。 */
|
|
267
|
+
let diskRevalidateMs = DEFAULT_DISK_REVALIDATE_MS
|
|
268
|
+
/** 由 installConcurrencyGate 覆盖:中断标志 TTL(测试可注入小值)。 */
|
|
269
|
+
let interruptFlagTtlMs = DEFAULT_INTERRUPT_FLAG_TTL_MS
|
|
270
|
+
/** 当前安装实例的 ctx(A-03 磁盘告警用)。未安装时为 null。 */
|
|
271
|
+
let installedCtx = null
|
|
272
|
+
|
|
273
|
+
/** 告警去重:同一类问题只 warn 一次。 */
|
|
274
|
+
let warnedKeys = new Set()
|
|
275
|
+
|
|
276
|
+
/** 去重告警。logger 不可用(或被禁用)时静默跳过,绝不影响主流程。 */
|
|
277
|
+
function warnOnce(ctx, tag, message) {
|
|
278
|
+
try {
|
|
279
|
+
if (warnedKeys.has(tag)) return
|
|
280
|
+
if (warnedKeys.size >= MAX_WARN_KEYS) warnedKeys = new Set()
|
|
281
|
+
warnedKeys.add(tag)
|
|
282
|
+
ctx?.logger?.warn?.('[team-preflight] ' + message)
|
|
283
|
+
} catch { /* logger 不可用也不影响放行 */ }
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// 先取台账(W4-27:台账实例由 lib/facts-store.mjs 持有),再建状态 / 中断 / run 注册表。
|
|
287
|
+
// 每个模块实例(含 ?query 测试实例)各自持有一套状态,互不共享 —— 隔离语义保持原样:
|
|
288
|
+
// · 无 query 的默认实例复用 facts-store 的默认台账(= projection.mjs 读的同一份,
|
|
289
|
+
// 与旧实现「projection 直接 import 默认 gate 模块」逐字等价);
|
|
290
|
+
// · 带 ?query 的测试实例现建一套(与旧实现「每个 gate.mjs?query 各一个 ledger」等价)。
|
|
291
|
+
let gateState = null
|
|
292
|
+
const facts = import.meta.url.includes('?') ? createFactsStore() : factsStore
|
|
293
|
+
const ledger = facts.ledger
|
|
294
|
+
// 迟绑定配置:告警通道 / 磁盘告警用的 ctx / 档位事实模块(?tier-bare 钩子仍生效)。
|
|
295
|
+
facts.configure({
|
|
296
|
+
warnOnce,
|
|
297
|
+
getCtx: () => installedCtx,
|
|
298
|
+
tierStateMod,
|
|
299
|
+
})
|
|
300
|
+
const registry = createRunRegistry({
|
|
301
|
+
clock: () => clock(),
|
|
302
|
+
staleRunMs: () => staleRunMs,
|
|
303
|
+
turnMode: 'gen',
|
|
304
|
+
turnCap: 512,
|
|
305
|
+
turnTouch: true,
|
|
306
|
+
entryTurnField: 'gen',
|
|
307
|
+
entryOf: ({ startedAt, turn, owner }) => ({ startedAt, gen: turn, owner }),
|
|
308
|
+
ttlRequiresPositive: false,
|
|
309
|
+
invalidStartedAtExpired: false,
|
|
310
|
+
})
|
|
311
|
+
gateState = createGateState({
|
|
312
|
+
clock: () => clock(),
|
|
313
|
+
currentGen: (key) => registry.currentTurn(key),
|
|
314
|
+
ledger,
|
|
315
|
+
})
|
|
316
|
+
const interrupts = createInterrupts({
|
|
317
|
+
clock: () => clock(),
|
|
318
|
+
currentGen: (key) => registry.currentTurn(key),
|
|
319
|
+
ledger,
|
|
320
|
+
})
|
|
321
|
+
ledger.setMemoryEpochReader(gateState.readConfirmationEpochByKey)
|
|
322
|
+
|
|
323
|
+
/** 派发调用的异步归属上下文(B1-P1-2;底层 AsyncLocalStorage 由 run-registry 实例持有)。 */
|
|
324
|
+
const callContext = { run: (call, fn) => registry.runInContext(call, fn) }
|
|
325
|
+
|
|
326
|
+
/** 读某 session 当前轮次代数(从未收到 turn/start 时为 0)。 */
|
|
327
|
+
function currentGen(key) { return registry.currentTurn(key) }
|
|
328
|
+
|
|
329
|
+
// ── run 注册表薄转发(保留既有内部名;变异锚 M16 依赖 sweepExpired 函数壳)──
|
|
330
|
+
function sweepExpired(key) { return registry.sweepExpired(key) }
|
|
331
|
+
function sweepExpiredCalls(key) { return registry.sweepExpiredCalls(key) }
|
|
332
|
+
function countActive(key) { return registry.countActive(key) }
|
|
333
|
+
function countDispatching(key) { return registry.countDispatching(key) }
|
|
334
|
+
function beginCall(key) { return registry.beginCall(key) }
|
|
335
|
+
function endCall(key, token) { return registry.endCall(key, token) }
|
|
336
|
+
function rollbackCallSpawns(key, token) { return registry.rollbackCallSpawns(key, token) }
|
|
337
|
+
function recordStart(key, info) { return registry.recordStart(key, info) }
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* 记录一次 end(gate 侧保留精确删除快路径:变异锚 M15 依赖 runs.delete('r:' + runId);
|
|
341
|
+
* 共享 run 表/轮次/占位由 run-registry 维护,删除规则与 run-registry.deleteRunFromBucket 同构)。
|
|
342
|
+
*/
|
|
343
|
+
function recordEnd(key, info) {
|
|
344
|
+
sweepExpired(key)
|
|
345
|
+
const runs = registry.bucketOf(key)
|
|
346
|
+
if (runs === undefined) return
|
|
347
|
+
const runId = runIdOf(info)
|
|
348
|
+
if (runId !== undefined) {
|
|
349
|
+
runs.delete('r:' + runId)
|
|
350
|
+
} else {
|
|
351
|
+
const id = info?.id
|
|
352
|
+
const matched = typeof id === 'string' && id !== '' && runs.delete('i:' + id)
|
|
353
|
+
if (!matched) {
|
|
354
|
+
let oldestKey
|
|
355
|
+
let oldestAt = Number.POSITIVE_INFINITY
|
|
356
|
+
for (const [candidateKey, run] of runs) {
|
|
357
|
+
if (run.startedAt < oldestAt) { oldestAt = run.startedAt; oldestKey = candidateKey }
|
|
358
|
+
}
|
|
359
|
+
if (oldestKey !== undefined) runs.delete(oldestKey)
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
registry.dropBucketIfEmpty(key)
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** 处理 turn/start:轮次 +1、出清上一代 run / 在途占位,并清 unavailable / confirmed。 */
|
|
366
|
+
function recordTurnStart(key) {
|
|
367
|
+
const discarded = registry.beginNewTurn(key)
|
|
368
|
+
gateState.clearTurnState(key)
|
|
369
|
+
return discarded
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// ── 导出面:确认状态(转发 gate-state.mjs)──
|
|
373
|
+
export function markConcurrencyConfirmed(agent, concurrency) { return gateState.markConcurrencyConfirmed(agent, concurrency) }
|
|
374
|
+
export function revokeConcurrencyConfirmation(agent) { return gateState.revokeConcurrencyConfirmation(agent) }
|
|
375
|
+
export function downscaleConcurrencyConfirmation(agent, limit = 1) { return gateState.downscaleConcurrencyConfirmation(agent, limit) }
|
|
376
|
+
export function recordDecisionEpoch(agent) { return gateState.recordDecisionEpoch(agent) }
|
|
377
|
+
export function readConfirmationEpochByKey(key) { return gateState.readConfirmationEpochByKey(key) }
|
|
378
|
+
export function readConfirmationEpoch(agent) { return gateState.readConfirmationEpoch(agent) }
|
|
379
|
+
export function isConcurrencyConfirmed(agent) { return gateState.isConcurrencyConfirmed(agent) }
|
|
380
|
+
export function confirmedConcurrencyLimit(agent) { return gateState.confirmedConcurrencyLimit(agent) }
|
|
381
|
+
export function markConcurrencyUnavailable(agent) { return gateState.markConcurrencyUnavailable(agent) }
|
|
382
|
+
export function isConcurrencyUnavailable(agent) { return gateState.isConcurrencyUnavailable(agent) }
|
|
383
|
+
|
|
384
|
+
// ── 导出面:台账(转发 ledger.mjs)──
|
|
385
|
+
export function ledgerRootOf() { return ledger.ledgerRootOf() }
|
|
386
|
+
export function readConfirmationEpochFromDisk(key) { return ledger.readConfirmationEpochFromDisk(key) }
|
|
387
|
+
export function readLedgerSnapshotByKey(key) { return ledger.readLedgerSnapshotByKey(key) }
|
|
388
|
+
|
|
389
|
+
// ── 导出面:中断阀门(转发 interrupt.mjs)──
|
|
390
|
+
export function setInterruptFlag(agentName, options = {}) { return interrupts.setInterruptFlag(agentName, options) }
|
|
391
|
+
export function getInterruptFlag(target) { return interrupts.getInterruptFlag(target) }
|
|
392
|
+
export function clearInterruptFlag(target) { return interrupts.clearInterruptFlag(target) }
|
|
393
|
+
export function checkInterrupt(target) { return interrupts.checkInterrupt(target) }
|
|
394
|
+
export function interruptFlagState() { return interrupts.interruptFlagState() }
|
|
395
|
+
|
|
396
|
+
// ── 导出面:run 计数(测试与诊断)──
|
|
397
|
+
export function inFlightCount(target) {
|
|
398
|
+
const key = typeof target === 'string' ? target : sessionKeyOf(target)
|
|
399
|
+
if (key === undefined) return 0
|
|
400
|
+
sweepExpired(key)
|
|
401
|
+
return countActive(key)
|
|
402
|
+
}
|
|
403
|
+
export function pendingDispatchCount(target) {
|
|
404
|
+
const key = typeof target === 'string' ? target : sessionKeyOf(target)
|
|
405
|
+
if (key === undefined) return 0
|
|
406
|
+
sweepExpiredCalls(key)
|
|
407
|
+
return countDispatching(key)
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** 解析 install 选项(原 installConcurrencyGate 头部逐字搬迁)。 */
|
|
411
|
+
function applyConcurrencyGateOptions(ctx, options) {
|
|
412
|
+
const enabled = options?.enabled !== false
|
|
413
|
+
staleRunMs = Number.isFinite(options?.staleRunMs) && options.staleRunMs > 0 ? options.staleRunMs : DEFAULT_STALE_RUN_MS
|
|
414
|
+
sanityCap = Number.isFinite(options?.sanityCap) && options.sanityCap >= 1 ? options.sanityCap : DEFAULT_SANITY_CAP
|
|
415
|
+
clock = typeof options?.now === 'function' ? options.now : () => Date.now()
|
|
416
|
+
// A-03:磁盘告警需要一个 ctx(三个写入点里有两个不在 ctx 作用域内)。
|
|
417
|
+
installedCtx = ctx ?? null
|
|
418
|
+
// A-05:快照复验节流(0 = 每次复验;非法值回落默认)。
|
|
419
|
+
diskRevalidateMs = Number.isFinite(options?.diskRevalidateMs) && options.diskRevalidateMs >= 0
|
|
420
|
+
? options.diskRevalidateMs
|
|
421
|
+
: DEFAULT_DISK_REVALIDATE_MS
|
|
422
|
+
ledger.setDiskRevalidateMs(diskRevalidateMs)
|
|
423
|
+
// V-INT:中断标志 TTL(非法值回落默认,绝不把 TTL 配成「永不过期」)。
|
|
424
|
+
interruptFlagTtlMs = Number.isFinite(options?.interruptFlagTtlMs) && options.interruptFlagTtlMs > 0
|
|
425
|
+
? options.interruptFlagTtlMs
|
|
426
|
+
: DEFAULT_INTERRUPT_FLAG_TTL_MS
|
|
427
|
+
interrupts.setTtl(interruptFlagTtlMs)
|
|
428
|
+
return enabled
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/** 监听器卸载句柄收集器(R1/P2:卸载必须真的摘掉监听器)。 */
|
|
432
|
+
function createDisposerBag(ctx) {
|
|
433
|
+
const disposers = []
|
|
434
|
+
const listen = (event, listener) => {
|
|
435
|
+
const off = ctx.on(event, listener)
|
|
436
|
+
if (typeof off === 'function') disposers.push(off)
|
|
437
|
+
}
|
|
438
|
+
return { disposers, listen }
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
function makeSubagentStartHandler(ctx, enabled) {
|
|
442
|
+
return (info) => {
|
|
443
|
+
// v11 台账落盘:挂在既有监听器内(不新增 ctx.on);与闸 enablement 解耦——
|
|
444
|
+
// 台账是记录设施不是闸,enabled:false 只关闸不关账。失败静默(try/catch)。
|
|
445
|
+
try {
|
|
446
|
+
const ledgerKey = parentKeyOf(info)
|
|
447
|
+
if (ledgerKey !== undefined) ledger.ledgerRecordStart(ledgerKey, info, clock(), { ctx })
|
|
448
|
+
} catch { /* 台账落盘失败不影响主流程 */ }
|
|
449
|
+
// v13:登记「子代理会话 → 所属派发」反查(agent/error 只带 childSessionId,
|
|
450
|
+
// 台账目录与 run 行要靠它定位)。与台账同一段、同一纪律:失败静默、与 enablement 解耦。
|
|
451
|
+
try {
|
|
452
|
+
const childSessionId = nonEmptyStringOf(info?.id)
|
|
453
|
+
const ledgerKey = parentKeyOf(info)
|
|
454
|
+
const runId = runIdOf(info) ?? nonEmptyStringOf(info?.id)
|
|
455
|
+
if (childSessionId !== null && ledgerKey !== undefined && runId !== null) {
|
|
456
|
+
ledger.rememberChildRun(childSessionId, { key: ledgerKey, runId })
|
|
457
|
+
}
|
|
458
|
+
} catch { /* 反查表登记失败不影响主流程(agent/error 记账退化) */ }
|
|
459
|
+
// V-INT:登记「子代理名 ↔ 子代理会话」反查(同一挂点、同一纪律——记录设施,
|
|
460
|
+
// 与 enabled 解耦:关闸不等于关闭中断通道,否则叫停会在配置降级时静默失效)。
|
|
461
|
+
try { interrupts.rememberInterruptTarget(info) } catch { /* 反查表维护失败不影响主流程 */ }
|
|
462
|
+
if (!enabled) return
|
|
463
|
+
try {
|
|
464
|
+
const key = parentKeyOf(info)
|
|
465
|
+
if (key === undefined) return
|
|
466
|
+
const { expired } = recordStart(key, info)
|
|
467
|
+
if (expired > 0) {
|
|
468
|
+
warnOnce(ctx, 'expired:' + key,
|
|
469
|
+
'concurrency gate: 回收了 ' + expired + ' 个超时未 end 的子代理记录(end 丢失兜底,A-02)')
|
|
470
|
+
}
|
|
471
|
+
} catch { /* 生命周期统计失败不影响主流程 */ }
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
function makeSubagentEndHandler(ctx, enabled) {
|
|
476
|
+
return (info) => {
|
|
477
|
+
// v11 台账落盘(同上;stopReason 一并记录,供面板重建「completed/error」状态)
|
|
478
|
+
try {
|
|
479
|
+
const ledgerKey = parentKeyOf(info)
|
|
480
|
+
if (ledgerKey !== undefined) ledger.ledgerRecordEnd(ledgerKey, info, clock(), { ctx })
|
|
481
|
+
} catch { /* 台账落盘失败不影响主流程 */ }
|
|
482
|
+
// V-INT:子代理收尾即自动清标志(设计文档 V-INT-4「子代理收尾完成即自动清」)。
|
|
483
|
+
// 不清的话:同一名字被重新派发(新 run 同 session)时会立刻继承旧标志 → 误杀新任务。
|
|
484
|
+
try {
|
|
485
|
+
const targetSession = nonEmptyStringOf(info?.id)
|
|
486
|
+
const targetName = nonEmptyStringOf(info?.name)
|
|
487
|
+
if (targetSession !== null) interrupts.clearInterruptFlag('s:' + targetSession)
|
|
488
|
+
if (targetName !== null) interrupts.clearInterruptFlag('n:' + targetName)
|
|
489
|
+
} catch { /* 清标志失败不影响主流程(TTL / 执行代对账仍是后手) */ }
|
|
490
|
+
// v13:收尾即清反查表项(end 之后的迟到 agent/error 不再记账——收场行已有
|
|
491
|
+
// stopReason,报错行落点消失是预期行为,不猜归属)。
|
|
492
|
+
try {
|
|
493
|
+
const targetSession = nonEmptyStringOf(info?.id)
|
|
494
|
+
if (targetSession !== null) ledger.forgetChildRun(targetSession)
|
|
495
|
+
} catch { /* 清理失败不影响主流程 */ }
|
|
496
|
+
if (!enabled) return
|
|
497
|
+
try {
|
|
498
|
+
const key = parentKeyOf(info)
|
|
499
|
+
if (key === undefined) return
|
|
500
|
+
recordEnd(key, info)
|
|
501
|
+
} catch { /* 同上 */ }
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function makeTurnStartHandler(ctx, enabled) {
|
|
506
|
+
return (session, event) => {
|
|
507
|
+
if (!enabled) return
|
|
508
|
+
try {
|
|
509
|
+
if (event?.type !== 'turn/start') return
|
|
510
|
+
const key = sessionEventKeyOf(session)
|
|
511
|
+
if (key === undefined) return
|
|
512
|
+
const discarded = recordTurnStart(key)
|
|
513
|
+
if (discarded > 0) {
|
|
514
|
+
try {
|
|
515
|
+
ctx.logger?.debug?.(
|
|
516
|
+
'[team-preflight] concurrency gate: 新一轮开始,出清 ' + discarded
|
|
517
|
+
+ ' 个上一轮遗留的 run 记录(跨轮不累计,A-01)',
|
|
518
|
+
)
|
|
519
|
+
} catch { /* debug 不可用忽略 */ }
|
|
520
|
+
}
|
|
521
|
+
} catch { /* 轮次跟踪失败不影响主流程 */ }
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function makeAgentErrorHandler(ctx) {
|
|
526
|
+
return (payload) => {
|
|
527
|
+
try {
|
|
528
|
+
const childId = nonEmptyStringOf(payload?.agent?.session?.id)
|
|
529
|
+
if (!childId) return
|
|
530
|
+
const rec = ledger.childRunOf(childId)
|
|
531
|
+
if (!rec) return
|
|
532
|
+
ledger.ledgerRecordError(rec.key, { runId: rec.runId, agentId: childId }, Date.now(), payload?.error, { ctx })
|
|
533
|
+
} catch { /* 记账失败不影响宿主错误通道 */ }
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function makeConcurrencyDelegationGuard(ctx, enabled) {
|
|
538
|
+
return async (exec, next) => {
|
|
539
|
+
if (!enabled) return next()
|
|
540
|
+
if (!isDelegationName(exec?.name)) return next()
|
|
541
|
+
|
|
542
|
+
const agent = exec?.agent
|
|
543
|
+
if (agent === null || typeof agent !== 'object') return next()
|
|
544
|
+
|
|
545
|
+
let verdict
|
|
546
|
+
let key
|
|
547
|
+
try {
|
|
548
|
+
key = sessionKeyOf(agent)
|
|
549
|
+
if (key === undefined) {
|
|
550
|
+
// C3-04:拿不到 session 标识时一律放行,但必须留下痕迹(原先静默)。
|
|
551
|
+
warnOnce(ctx, 'no-session-key',
|
|
552
|
+
'concurrency gate: 拿不到 agent.session.id,本次委派放行(本闸对该次派发失效)')
|
|
553
|
+
verdict = { block: false }
|
|
554
|
+
} else if (isConcurrencyConfirmed(agent)) {
|
|
555
|
+
// v8(t3 问题4 授权粒度):确认按 N 路放行 —— 本轮在跑+在途路数 < N 才放行,第 N+1 路拦。
|
|
556
|
+
// 未传 N 的 legacy 确认 = Infinity(恒 < Infinity)→ 等价旧「本轮确认即放行」,不回退。
|
|
557
|
+
const limit = confirmedConcurrencyLimit(agent) ?? Infinity
|
|
558
|
+
const expired = sweepExpired(key)
|
|
559
|
+
if (expired > 0) {
|
|
560
|
+
warnOnce(ctx, 'expired:' + key,
|
|
561
|
+
'concurrency gate: 回收了 ' + expired + ' 个超时未 end 的子代理记录(end 丢失兜底,A-02)')
|
|
562
|
+
}
|
|
563
|
+
const expiredCalls = sweepExpiredCalls(key)
|
|
564
|
+
if (expiredCalls > 0) {
|
|
565
|
+
warnOnce(ctx, 'expired-call:' + key,
|
|
566
|
+
'concurrency gate: 回收了 ' + expiredCalls
|
|
567
|
+
+ ' 个超时未返回的派发占位(工具挂死兜底)')
|
|
568
|
+
}
|
|
569
|
+
const running = countActive(key) + countDispatching(key)
|
|
570
|
+
if (running > sanityCap) {
|
|
571
|
+
// 逃生阀:与未确认分支同款 fail-open。
|
|
572
|
+
warnOnce(ctx, 'sanity:' + key,
|
|
573
|
+
'concurrency gate: 本轮在跑数 ' + running + ' 超过上限 ' + sanityCap
|
|
574
|
+
+ ',判为 end 丢失残留,本次降级放行(C3-01 逃生阀)')
|
|
575
|
+
verdict = { block: false }
|
|
576
|
+
} else {
|
|
577
|
+
// 未达上限放行;达到 / 超过已确认的路数上限 → 拦(携带 limit 以输出专用文案)
|
|
578
|
+
verdict = running < limit ? { block: false } : { block: true, running, limit }
|
|
579
|
+
}
|
|
580
|
+
} else if (isConcurrencyUnavailable(agent)) {
|
|
581
|
+
// H1-04:本环境无法获得用户确认(无 userQuestions / 子代理 / 提问抛错)。
|
|
582
|
+
// 坚持拦会把并发功能锁死 —— 降级放行并 warn 一次。
|
|
583
|
+
warnOnce(ctx, 'unavailable:' + key,
|
|
584
|
+
'concurrency gate: 本会话环境无法获得用户确认(无 userQuestions 服务或提问失败),'
|
|
585
|
+
+ '并发确认机制在本环境不可用,本次派发降级放行')
|
|
586
|
+
verdict = { block: false }
|
|
587
|
+
} else {
|
|
588
|
+
// D-01 自检:宿主 runInfo 的 parentSessionId 是 creator 的 **agent id**
|
|
589
|
+
// (manager.js: ancestors.at(-1)),本闸按 agent.session.id 归组。
|
|
590
|
+
// 两者不同时计数可能与派发会话对不上(方向是 fail-open),至少让日志可见。
|
|
591
|
+
const agentId = agent?.id
|
|
592
|
+
if (typeof agentId === 'string' && agentId !== '' && agentId !== key) {
|
|
593
|
+
warnOnce(ctx, 'id-mismatch:' + agentId + ':' + key,
|
|
594
|
+
'concurrency gate: agent.id (' + agentId + ') !== agent.session.id (' + key
|
|
595
|
+
+ '),宿主 parentSessionId 取的是 agent id,计数可能与派发会话对不上(放行优先)')
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
const expired = sweepExpired(key)
|
|
599
|
+
if (expired > 0) {
|
|
600
|
+
warnOnce(ctx, 'expired:' + key,
|
|
601
|
+
'concurrency gate: 回收了 ' + expired + ' 个超时未 end 的子代理记录(end 丢失兜底,A-02)')
|
|
602
|
+
}
|
|
603
|
+
// B1-P0-1:在途派发(已进入 tools/execute、start 还没 emit)必须算进来,
|
|
604
|
+
// 否则真实时序下第 2 路看不到第 1 路(它的 subagent/start 还在多层 await 之后)。
|
|
605
|
+
// 变量名沿用 running:判据 = 本轮生命周期在跑数 + 本轮在途派发数。
|
|
606
|
+
const expiredCalls = sweepExpiredCalls(key)
|
|
607
|
+
if (expiredCalls > 0) {
|
|
608
|
+
warnOnce(ctx, 'expired-call:' + key,
|
|
609
|
+
'concurrency gate: 回收了 ' + expiredCalls
|
|
610
|
+
+ ' 个超时未返回的派发占位(工具挂死兜底)')
|
|
611
|
+
}
|
|
612
|
+
const running = countActive(key) + countDispatching(key)
|
|
613
|
+
if (running > sanityCap) {
|
|
614
|
+
// 逃生阀:一轮内不可能真有这么多并发,判为 end 大面积丢失的残留。
|
|
615
|
+
warnOnce(ctx, 'sanity:' + key,
|
|
616
|
+
'concurrency gate: 本轮在跑数 ' + running + ' 超过上限 ' + sanityCap
|
|
617
|
+
+ ',判为 end 丢失残留,本次降级放行(C3-01 逃生阀)')
|
|
618
|
+
verdict = { block: false }
|
|
619
|
+
} else {
|
|
620
|
+
verdict = running >= 1
|
|
621
|
+
? { block: true, running }
|
|
622
|
+
: { block: false }
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
} catch (error) {
|
|
626
|
+
try {
|
|
627
|
+
ctx.logger?.warn?.('[team-preflight] concurrency gate check failed:', error?.message ?? error)
|
|
628
|
+
} catch { /* logger 不可用也不影响放行 */ }
|
|
629
|
+
verdict = { block: false }
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
if (verdict.block && verdict.limit !== undefined) {
|
|
633
|
+
// v8:已确认 N 路、但本轮已派发到上限 —— 文案必须说清「已达上限」而非「尚未确认」。
|
|
634
|
+
throw new Error(
|
|
635
|
+
'并发派发被拦下:本轮已确认的并发上限是 ' + verdict.limit + ' 路。'
|
|
636
|
+
+ `检测到本会话本轮已有 ${verdict.running} 路派发在进行中(已启动的子代理 + 正在启动的派发),`
|
|
637
|
+
+ '本次派发会让本轮并发数超过已确认的上限。\n'
|
|
638
|
+
+ '若需更多并发,请重新调用 suggest_concurrency 与用户确认更高的并发路数;'
|
|
639
|
+
+ '串行派发(等前一个结束再派下一个)或上一轮的遗留子代理不受影响。\n'
|
|
640
|
+
+ '(本工具确认只对**本轮**有效:下一轮 turn/start 后需重新确认。)',
|
|
641
|
+
)
|
|
642
|
+
}
|
|
643
|
+
if (verdict.block) {
|
|
644
|
+
throw new Error(
|
|
645
|
+
'并发派发被拦下:本会话本轮尚未确认并发方案。'
|
|
646
|
+
+ `检测到本会话本轮已有 ${verdict.running} 路派发在进行中(已启动的子代理 + 正在启动的派发),本次派发会让本轮并发数增加。\n`
|
|
647
|
+
+ '请先调用 suggest_concurrency 把并发方案(几路 / 分几批 / 模型档)交给用户确认。\n'
|
|
648
|
+
+ '注意:subagent 启动后立即返回,但子代理仍在后台运行——'
|
|
649
|
+
+ '本轮内逐条重发同样会被本闸拦下;串行派发(等前一个结束再派下一个)不受影响。\n'
|
|
650
|
+
+ '本闸只统计本轮(同一轮 turn 内 start 或正在启动)的并发:上一轮的遗留子代理不计入本轮,'
|
|
651
|
+
+ '所以新一轮的单路派发不会被拦;单个 run 超时(end 丢失)后会被自动回收,无需重启。',
|
|
652
|
+
)
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// ── 3b. 放行后:先占位(B1-P0-1),再进工具体;失败时只回滚自己起的 run(B1-P1-2)──
|
|
656
|
+
//
|
|
657
|
+
// 占位必须在 await next() 之前**同步**完成,且在这里之后不能再有 await:
|
|
658
|
+
// 判定 → 占位之间一旦插入 await,同批两路就可能都先判定、后占位,P0 竞态原地复活。
|
|
659
|
+
if (key === undefined) return next()
|
|
660
|
+
const call = beginCall(key)
|
|
661
|
+
try {
|
|
662
|
+
// B1-P1-2:把工具体(含它 emit 的 subagent/start)跑在本次调用自己的
|
|
663
|
+
// 异步上下文里 → start 监听器据此精确归因 owner,兄弟的 run 不可能被误删。
|
|
664
|
+
return await callContext.run(call, () => next())
|
|
665
|
+
} catch (error) {
|
|
666
|
+
// 宿主 rollbackUnpublished 路径会 emit start 但不补发 end(最常见孤儿来源):
|
|
667
|
+
// 本次调用 emit 过的 run 随失败一起留下 → 立刻撤销,精确到 owner。
|
|
668
|
+
try {
|
|
669
|
+
const rolledBack = rollbackCallSpawns(key, call.token)
|
|
670
|
+
if (rolledBack > 0) {
|
|
671
|
+
warnOnce(ctx, 'rollback:' + key,
|
|
672
|
+
'concurrency gate: 本次派发失败,撤销了本次调用自己起的 ' + rolledBack
|
|
673
|
+
+ ' 个 run 记录(宿主 rollbackUnpublished 不补发 end,C3-01)')
|
|
674
|
+
}
|
|
675
|
+
} catch { /* 兜底失败不改变原始错误 */ }
|
|
676
|
+
throw error
|
|
677
|
+
} finally {
|
|
678
|
+
// 成功 / 抛错 / 被拒都要释放占位,否则一次失败会把本会话永久锁死。
|
|
679
|
+
endCall(key, call.token)
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
/** 卸载清理:先摘监听器,再清状态与注入选项(R1/P2;R2 callSeq 不归零)。 */
|
|
685
|
+
function makeConcurrencyDispose(disposers) {
|
|
686
|
+
return () => {
|
|
687
|
+
for (const off of disposers.splice(0)) {
|
|
688
|
+
try { off() } catch { /* 监听器已随 ctx 销毁时忽略 */ }
|
|
689
|
+
}
|
|
690
|
+
gateState.clearAll()
|
|
691
|
+
interrupts.resetAll()
|
|
692
|
+
ledger.resetChildRuns()
|
|
693
|
+
registry.resetAll(true)
|
|
694
|
+
warnedKeys = new Set()
|
|
695
|
+
// v11:磁盘事实缓存随卸载清理(下次安装重新从磁盘水合;文件保留为历史事实)
|
|
696
|
+
// A-03:目录缓存与末字节校验缓存也随卸载清理(下次安装重新懒建 / 重新校验)
|
|
697
|
+
ledger.resetAllCaches(true)
|
|
698
|
+
installedCtx = null
|
|
699
|
+
// 注入的选项随本次 install 一起失效(测试互相污染防护)
|
|
700
|
+
staleRunMs = DEFAULT_STALE_RUN_MS
|
|
701
|
+
sanityCap = DEFAULT_SANITY_CAP
|
|
702
|
+
clock = () => Date.now()
|
|
703
|
+
diskRevalidateMs = DEFAULT_DISK_REVALIDATE_MS
|
|
704
|
+
interruptFlagTtlMs = DEFAULT_INTERRUPT_FLAG_TTL_MS
|
|
705
|
+
ledger.setDiskRevalidateMs(DEFAULT_DISK_REVALIDATE_MS)
|
|
706
|
+
interrupts.resetTtl()
|
|
707
|
+
// R2:callSeq 不归零(见 run-registry.mjs 定义处注释)——dispose 后旧调用可能仍在飞。
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* 安装并发确认闸(装配层:选项 → 5 个监听器 → dispose;各监听器职责见下方 make* 工厂)。
|
|
712
|
+
*/
|
|
713
|
+
export function installConcurrencyGate(ctx, options = {}) {
|
|
714
|
+
const enabled = applyConcurrencyGateOptions(ctx, options)
|
|
715
|
+
const { disposers, listen } = createDisposerBag(ctx)
|
|
716
|
+
|
|
717
|
+
// ── 1. 子代理生命周期("本轮在跑数"的唯一真相来源 + v11 台账 / v13 反查 / V-INT 反查)──
|
|
718
|
+
listen('subagent/start', makeSubagentStartHandler(ctx, enabled))
|
|
719
|
+
listen('subagent/end', makeSubagentEndHandler(ctx, enabled))
|
|
720
|
+
// ── 2. 轮次边界:turn/start 时把「本轮并发」重置(A-01/A-02 根治点)──
|
|
721
|
+
listen('session/event', makeTurnStartHandler(ctx, enabled))
|
|
722
|
+
// ── 2b. v13:agent/error 捕获(子代理 step/turn 报错 → 台账 error 行)──
|
|
723
|
+
listen('agent/error', makeAgentErrorHandler(ctx))
|
|
724
|
+
// ── 3. 派发前的确认检查(判定 / 文案 / 占位 / 回滚,见 makeConcurrencyDelegationGuard)──
|
|
725
|
+
listen('tools/execute', makeConcurrencyDelegationGuard(ctx, enabled))
|
|
726
|
+
|
|
727
|
+
// ── 4. 卸载清理 ──
|
|
728
|
+
return makeConcurrencyDispose(disposers)
|
|
729
|
+
}
|
|
730
|
+
export const __test = {
|
|
731
|
+
/**
|
|
732
|
+
* 直接折叠一批台账事件(模块私有 applyLedgerEvent 的透传包装)。
|
|
733
|
+
* 传 runs(Map):折叠进给定表(复用同一防御实现);省略:新建独立表。
|
|
734
|
+
* @param {Map<string, object>} [runs]
|
|
735
|
+
* @param {object} parsed
|
|
736
|
+
* @returns {Map<string, object>} 折叠所用的表(start/end/error 后的行)
|
|
737
|
+
*/
|
|
738
|
+
applyLedgerEvent(runs, parsed) {
|
|
739
|
+
if (runs instanceof Map) { ledger.foldLedgerEvent(runs, parsed); return runs }
|
|
740
|
+
const fresh = new Map()
|
|
741
|
+
ledger.foldLedgerEvent(fresh, parsed)
|
|
742
|
+
return fresh
|
|
743
|
+
},
|
|
744
|
+
}
|
|
745
|
+
/* ══════════════════════════════════════════════════════════════════════════
|
|
746
|
+
* 【变更 2026-11-28 启动恢复检查】未完成子代理判定(纯函数,零 I/O)。
|
|
747
|
+
*
|
|
748
|
+
* 背景(用户发现 a/b):① 被手动中止的 agent(send_interrupt → 宿主硬停 →
|
|
749
|
+
* subagent/end stopReason='aborted' + 中断记账 kind:'interrupt')在面板上与
|
|
750
|
+
* 「正常完成」混淆;② 新会话 / 宿主重启后,主模型没有统一的「上次未完成子代理」
|
|
751
|
+
* 视角,无法在开工前向用户确认是否继续。
|
|
752
|
+
*
|
|
753
|
+
* 本函数是 check_subagent_selection 报告「未完成子代理」段的**唯一判据**:
|
|
754
|
+
* 输入 readLedgerSnapshotByKey 的返回值({epoch, agents} 或 null),输出未完成清单。
|
|
755
|
+
* 「未完成」= 三类(宁可多报,绝不漏报——恢复检查是提醒不是闸):
|
|
756
|
+
* · status==='running'(start 后无 end:宿主崩溃 / 事件丢失);
|
|
757
|
+
* · status==='error'(agent/error 后无 end:报了错且没收场);
|
|
758
|
+
* · status==='ended' 且 stopReason 为 'aborted' / 'error'(被手动中止 / 异常收场)。
|
|
759
|
+
* completed 与普通 ended(stopReason 为其它值 / 缺失)不算未完成 —— 正常收工。
|
|
760
|
+
*
|
|
761
|
+
* 【变更 2026-11-28 死亡语义】(58 号报告 G1):ended 判词的 stopReason 集合
|
|
762
|
+
* {aborted,error} 扩为 {aborted,error,max-tokens,refusal}——「打到 token 上限」
|
|
763
|
+
* 与「已拒接」同样是**没把任务做完**的收场,恢复检查必须同样提醒。未知
|
|
764
|
+
* stopReason 不报(「宁可多报」只覆盖**已知**的未完成判词,不覆盖不认识的:
|
|
765
|
+
* 未知判词按普通收场处理,与既有「completed / 普通 ended 不算」一致)。
|
|
766
|
+
* ══════════════════════════════════════════════════════════════════════════ */
|
|
767
|
+
/**
|
|
768
|
+
* 从台账快照提取「未完成」的子代理行(纯函数,脏值不抛、不透传)。
|
|
769
|
+
*
|
|
770
|
+
* @param {unknown} snapshot readLedgerSnapshotByKey 的返回值:{epoch, agents:[...]} 或 null
|
|
771
|
+
* @returns {Array<{id: string, name: string, status: string,
|
|
772
|
+
* stopReason: string|null, interruptAt: number|null, createdAt: number|null, endedAt: number|null}>}
|
|
773
|
+
* 按 createdAt 升序(脏行丢弃:id 非非空字符串 / createdAt 非有限数字的行不参与)。
|
|
774
|
+
*/
|
|
775
|
+
export function unfinishedAgentsOfSnapshot(snapshot) {
|
|
776
|
+
if (snapshot === null || snapshot === undefined || typeof snapshot !== 'object' || Array.isArray(snapshot)) return []
|
|
777
|
+
const rows = Array.isArray(snapshot.agents) ? snapshot.agents : []
|
|
778
|
+
const out = []
|
|
779
|
+
for (const row of rows) {
|
|
780
|
+
if (row === null || typeof row !== 'object' || Array.isArray(row)) continue
|
|
781
|
+
const id = nonEmptyStringOf(row.id)
|
|
782
|
+
if (id === null) continue
|
|
783
|
+
const status = nonEmptyStringOf(row.status)
|
|
784
|
+
if (status === null) continue
|
|
785
|
+
const stopReason = nonEmptyStringOf(row.stopReason)
|
|
786
|
+
// 【变更 2026-11-28 死亡语义】ended 判词集合 {aborted,error} →
|
|
787
|
+
// {aborted,error,max-tokens,refusal};未知 stopReason 不报(按普通收场)。
|
|
788
|
+
const unfinished = status === 'running'
|
|
789
|
+
|| status === 'error'
|
|
790
|
+
|| (status === 'ended'
|
|
791
|
+
&& (stopReason === 'aborted' || stopReason === 'error'
|
|
792
|
+
|| stopReason === 'max-tokens' || stopReason === 'refusal'))
|
|
793
|
+
if (unfinished !== true) continue
|
|
794
|
+
const interruptAt = finiteNumberOf(row.interruptAt)
|
|
795
|
+
out.push({
|
|
796
|
+
id,
|
|
797
|
+
name: nonEmptyStringOf(row.name) ?? id,
|
|
798
|
+
status,
|
|
799
|
+
stopReason,
|
|
800
|
+
// interruptAt 只认有限数字(脏值当没有);「手动中止」= aborted + 有中断记账。
|
|
801
|
+
interruptAt,
|
|
802
|
+
createdAt: finiteNumberOf(row.createdAt),
|
|
803
|
+
endedAt: finiteNumberOf(row.endedAt),
|
|
804
|
+
})
|
|
805
|
+
}
|
|
806
|
+
out.sort((a, b) => {
|
|
807
|
+
const ca = a.createdAt === null ? Number.POSITIVE_INFINITY : a.createdAt
|
|
808
|
+
const cb = b.createdAt === null ? Number.POSITIVE_INFINITY : b.createdAt
|
|
809
|
+
return ca - cb
|
|
810
|
+
})
|
|
811
|
+
return out
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
/* ══════════════════════════════════════════════════════════════════════════
|
|
815
|
+
* 数据生命周期(D1–D6)转发层:实现见 lib/lifecycle.mjs。
|
|
816
|
+
* 保留三个旧导出名与签名(test.mjs [69] D1 源码护栏依赖);TOCTOU 前缀校验
|
|
817
|
+
* isWithinSessionsRoot 留在本文件(作为注入给 lifecycle 的安全钩子,D4 护栏)。
|
|
818
|
+
* ══════════════════════════════════════════════════════════════════════════ */
|
|
819
|
+
|
|
820
|
+
/** 删前再次确认:dir 必须是 sessionsRoot 的**直接**子目录,且 realpath 仍在 sessionsRoot 内。 */
|
|
821
|
+
function isWithinSessionsRoot(dir, sessionsRoot, sessionsReal) {
|
|
822
|
+
try {
|
|
823
|
+
const resolvedDir = resolve(dir)
|
|
824
|
+
const resolvedRoot = resolve(sessionsRoot)
|
|
825
|
+
if (dirname(resolvedDir) !== resolvedRoot) return false
|
|
826
|
+
if (sessionsReal !== null) {
|
|
827
|
+
const realDir = realpathSync(resolvedDir)
|
|
828
|
+
if (realDir !== resolvedDir) {
|
|
829
|
+
// realpath 与字面不同(含符号链接):必须仍在真实根内
|
|
830
|
+
if (!realDir.startsWith(sessionsReal + sep)) return false
|
|
831
|
+
}
|
|
832
|
+
// 字面路径已由上面的 dirname 校验保证是直接子级;无符号链接时无需再比对。
|
|
833
|
+
}
|
|
834
|
+
return true
|
|
835
|
+
} catch { return false }
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
/** 生命周期清理钩子依赖包:落盘根 / TOCTOU 校验 / 缺省日志名(lifecycle.mjs 不 import gate)。 */
|
|
839
|
+
const lifecycleDeps = {
|
|
840
|
+
rootOf: () => ledger.ledgerRootOf(),
|
|
841
|
+
withinRoot: isWithinSessionsRoot,
|
|
842
|
+
defaultLogFileName: CLEANUP_LOG_FILE,
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/** 纯规划:返回应删清单(不删任何东西)。实现见 lib/lifecycle.mjs。 */
|
|
846
|
+
export function purgeStaleSessions(root, now = Date.now(), opts = {}) { return lifecyclePurgeStaleSessions(root, now, opts) }
|
|
847
|
+
|
|
848
|
+
/** 执行层:扫 + 判活跃 + 删 + 写清理日志。实现见 lib/lifecycle.mjs。 */
|
|
849
|
+
export function sweepLifecycle(rootArg, now = Date.now(), opts = {}) { return lifecycleSweep(rootArg, now, opts, lifecycleDeps) }
|
|
850
|
+
|
|
851
|
+
/** 会话目录段名安全校验(D5)。实现见 lib/lifecycle.mjs。 */
|
|
852
|
+
export function isLifecycleSegmentSafe(name) { return lifecycleSegmentSafe(name) }
|
|
853
|
+
|
|
854
|
+
/** D4 触发钩子:启动后台扫 + 24h 周期 + dispose。实现见 lib/lifecycle.mjs。 */
|
|
855
|
+
export function installLifecycleSweep(ctx, config = {}) { return lifecycleInstallSweep(ctx, config, lifecycleDeps) }
|
|
856
|
+
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
* 清空确认状态(测试与卸载用)。
|
|
860
|
+
* 不传参数 → 清空全部状态;传 agent → 只清该 session 的确认与在跑集合(轮次代数保留)。
|
|
861
|
+
*/
|
|
862
|
+
export function resetConcurrencyConfirmation(agent) {
|
|
863
|
+
if (agent === undefined) {
|
|
864
|
+
// W7-001:整体 reset 同时作废「磁盘续写基线」——本进程后续确认从 seq=1 起算。
|
|
865
|
+
gateState.resetAll()
|
|
866
|
+
interrupts.resetAll()
|
|
867
|
+
ledger.resetChildRuns()
|
|
868
|
+
registry.resetAll(false)
|
|
869
|
+
warnedKeys = new Set()
|
|
870
|
+
// v11:磁盘事实缓存一并清理(下次读盘重新水合;磁盘文件本身是历史事实,不删)。
|
|
871
|
+
ledger.resetAllCaches(false)
|
|
872
|
+
// R2:callSeq 不归零(见 run-registry.mjs 定义处注释)。
|
|
873
|
+
return
|
|
874
|
+
}
|
|
875
|
+
const key = sessionKeyOf(agent)
|
|
876
|
+
if (key !== undefined) {
|
|
877
|
+
gateState.resetForSession(key)
|
|
878
|
+
// V-INT:该会话作为**目标**的中断标志一并清。
|
|
879
|
+
interrupts.clearInterruptFlag('s:' + key)
|
|
880
|
+
// v13:该会话名下的 agent/error 反查项一并清。
|
|
881
|
+
ledger.clearChildRunsForSession(key)
|
|
882
|
+
// v11:单会话的磁盘事实缓存一并失效。
|
|
883
|
+
ledger.clearKeyCaches(key)
|
|
884
|
+
registry.resetKey(key)
|
|
885
|
+
}
|
|
886
|
+
}
|