dsh-punky-swarm 0.3.6

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 (101) hide show
  1. package/CHANGELOG.md +120 -0
  2. package/LICENSE +661 -0
  3. package/README.en.md +281 -0
  4. package/README.md +281 -0
  5. package/cordis.patch.yml +59 -0
  6. package/lib/acps/certs.js +310 -0
  7. package/lib/acps/discovery-client.js +283 -0
  8. package/lib/acps/registry-client.js +527 -0
  9. package/lib/acps/server.js +302 -0
  10. package/lib/aip/agent-descriptor.js +170 -0
  11. package/lib/aip/identity.js +469 -0
  12. package/lib/aip/tool-descriptor.js +93 -0
  13. package/lib/api.js +266 -0
  14. package/lib/artifact-types.js +48 -0
  15. package/lib/assembly/audit-blind-review.js +170 -0
  16. package/lib/assembly/schema.js +253 -0
  17. package/lib/assembly.js +41 -0
  18. package/lib/assets.js +103 -0
  19. package/lib/bridge/trajectory.js +202 -0
  20. package/lib/client.js +704 -0
  21. package/lib/comms/acps-bridge.js +219 -0
  22. package/lib/comms/aip-format.js +141 -0
  23. package/lib/comms/budget.js +124 -0
  24. package/lib/comms/mailbox.js +221 -0
  25. package/lib/comms/topic-runtime.js +76 -0
  26. package/lib/comms/topic.js +115 -0
  27. package/lib/discovery/filter.js +199 -0
  28. package/lib/discovery/schema.js +157 -0
  29. package/lib/discovery/service.js +251 -0
  30. package/lib/hot/config-watch.js +252 -0
  31. package/lib/index.js +433 -0
  32. package/lib/lock.js +69 -0
  33. package/lib/panel/batch-detail.js +163 -0
  34. package/lib/panel/batch-list.js +84 -0
  35. package/lib/panel/locales.js +93 -0
  36. package/lib/panel/main.js +270 -0
  37. package/lib/panel/stream.js +348 -0
  38. package/lib/panel/theme.js +103 -0
  39. package/lib/panel/widgets.js +63 -0
  40. package/lib/schema.d.ts +192 -0
  41. package/lib/schema.js +259 -0
  42. package/lib/schema.ts +398 -0
  43. package/lib/state/archive.js +174 -0
  44. package/lib/state/command-exec.js +148 -0
  45. package/lib/state/constants.js +37 -0
  46. package/lib/state/corrupt-registry.js +103 -0
  47. package/lib/state/event-types.js +65 -0
  48. package/lib/state/gates.d.ts +226 -0
  49. package/lib/state/gates.js +428 -0
  50. package/lib/state/gates.ts +348 -0
  51. package/lib/state/machine-rules.d.ts +14 -0
  52. package/lib/state/machine-rules.js +76 -0
  53. package/lib/state/machine-rules.ts +88 -0
  54. package/lib/state/machine.js +68 -0
  55. package/lib/state/resume.js +201 -0
  56. package/lib/state/schema-v3.d.ts +10 -0
  57. package/lib/state/schema-v3.js +57 -0
  58. package/lib/state/schema-v3.ts +80 -0
  59. package/lib/state/store.js +607 -0
  60. package/lib/state/task-utils.js +40 -0
  61. package/lib/tools/core.js +323 -0
  62. package/lib/tools/git-utils.js +44 -0
  63. package/lib/tools/lane-tools.js +455 -0
  64. package/lib/tools/log-tools.js +173 -0
  65. package/lib/tools/mailbox-tools.js +121 -0
  66. package/lib/tools/merge-agent.js +127 -0
  67. package/lib/tools/register.js +85 -0
  68. package/lib/tools/shared.js +32 -0
  69. package/lib/types/contracts.d.ts +277 -0
  70. package/lib/types/contracts.js +17 -0
  71. package/lib/types/contracts.ts +279 -0
  72. package/lib/verify/evidence.js +249 -0
  73. package/lib/verify/gate.js +161 -0
  74. package/lib/verify/mount.js +48 -0
  75. package/lib/verify/selector.js +101 -0
  76. package/lib/watch/lane-heartbeat.js +333 -0
  77. package/lib/wave-plan.d.ts +48 -0
  78. package/lib/wave-plan.js +473 -0
  79. package/lib/wave-plan.ts +465 -0
  80. package/package.json +71 -0
  81. package/presets/jiufeng/NOTICE +5 -0
  82. package/presets/jiufeng/agent.cordis.yml +275 -0
  83. package/presets/jiufeng/preset.yml +3 -0
  84. package/skills/jiufeng-team/SKILL.md +214 -0
  85. package/skills/jiufeng-team/references/constitution.md +62 -0
  86. package/skills/jiufeng-team/references/roles/coder.md +17 -0
  87. package/skills/jiufeng-team/references/roles/coordinator.md +13 -0
  88. package/skills/jiufeng-team/references/roles/designer.md +14 -0
  89. package/skills/jiufeng-team/references/roles/doc-manager.md +13 -0
  90. package/skills/jiufeng-team/references/roles/manager.md +22 -0
  91. package/skills/jiufeng-team/references/roles/reviewer.md +19 -0
  92. package/skills/jiufeng-team/references/roles/supervisor.md +13 -0
  93. package/skills/jiufeng-team/references/roles/tester.md +13 -0
  94. package/skills/jiufeng-team/references/templates/call-chain-matrix-template.md +121 -0
  95. package/skills/jiufeng-team/references/templates/endpoint-behavior-template.md +60 -0
  96. package/skills/jiufeng-team/references/templates/gap-list.json +33 -0
  97. package/skills/jiufeng-team/references/templates/leader-decision-pack.md +92 -0
  98. package/skills/jiufeng-team/references/templates/plan-template.md +61 -0
  99. package/skills/jiufeng-team/references/templates/success-pattern-seeds.md +126 -0
  100. package/skills/jiufeng-team/references/workflow.md +98 -0
  101. package/skills/jiufeng-team/scripts/check-v3-density.mjs +98 -0
@@ -0,0 +1,428 @@
1
+ /*
2
+ Copyright (C) 2025-2026 Punky
3
+
4
+ This program is free software: you can redistribute it and/or modify
5
+ it under the terms of the GNU Affero General Public License as
6
+ published by the Free Software Foundation, either version 3 of the
7
+ License, or (at your option) any later version.
8
+
9
+ This program is distributed in the hope that it will be useful,
10
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
11
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
+ GNU Affero General Public License for more details.
13
+
14
+ You should have received a copy of the GNU Affero General Public License
15
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
16
+ */
17
+ // Gates:Tier3 层间门禁(设计 §3.3/§四/§五/§15)——entry(consume 前置)/ exit(outputs/produce 前置 + Plan 契约 checkPlanContract)/ complete(audit 验收前置)
18
+ // 纯函数闭包工厂:createGates(root) 注入 root;门禁函数签名 (sessionId, batchId, batch, lane)——batch 对象显式传入,不持有状态
19
+ // Phase 2 类型化:wavePlan 任务属性访问经 taskOf 单点断言(findTask 保持 JS,返回 object|null → WavePlanTask,
20
+ // 断言依据:findTask 语义即"按 id 定位 buildWavePlan 持久形态任务");Batch/批事件判别联合收窄(零断言消解 TS2339);
21
+ // gate 函数返回类型沿用结构推断(消费方 store.js 等为 JS,无类型约束)——运行期语义零变更(断言纯类型层)。
22
+ import fs from 'node:fs';
23
+ import path from 'node:path';
24
+ import * as schema from '../schema.js';
25
+ import { runCommand } from './command-exec.js';
26
+ // P1-07 单点收敛:SESSION_RE/isAbsPath 定义迁至 constants.js;isAbsPath 保持导出
27
+ // (store.js:24 等既有消费方 import { isAbsPath } from './gates.js' 不受影响)。
28
+ import { SESSION_RE, isAbsPath } from './constants.js';
29
+ // P1-04 单点:findTask 收敛至 task-utils.js(原 :108 本地定义删除,调用点不变)
30
+ import { findTask } from './task-utils.js';
31
+ // R-07 读端收敛:e.type 比较改引 EVT 常量单点(member.settled 读端 :117)
32
+ import * as EVT from './event-types.js';
33
+ export { isAbsPath };
34
+ // 局部类型化包装:findTask(task-utils.js,保持 JS)返回 object|null → 属性访问全报"属性不存在"。
35
+ // taskOf 为唯一断言点:findTask 遍历 batch.wavePlan[].tasks 按 t.id === lane 返回 buildWavePlan 持久形态任务
36
+ // → WavePlanTask 类型成立(运行期零变化,断言纯类型层)。
37
+ function taskOf(batch, lane) {
38
+ return findTask(batch, lane);
39
+ }
40
+ // targets 门禁(O2)marker 逃生声明标记:目标文件含独立行 `targets-claimed: true` 即视为已变更(跳过 mtime 比对)。
41
+ // 行首锚定独立行正则(仿 needHuman 独立行模式)——内嵌/注释/非行首不误判(NFR3)。
42
+ export const TARGETS_CLAIMED_RE = /^targets-claimed:\s*true$/m;
43
+ // needHuman:audit 产物人工裁决声明检测(纯函数,与 checkExitGate 同源文件解析)——
44
+ // 产物含独立行 `needHuman: true`(正则 /^needHuman:\s*true$/m)即声明人工裁决需求;
45
+ // 缺失/空文件/目录跳过(零感知:缺产物由 exit gate 既有语义拒,本函数不补刀)
46
+ export function detectNeedHuman(artifactsDir, producePaths) {
47
+ if (!Array.isArray(producePaths) || producePaths.length === 0)
48
+ return { declared: false, path: null };
49
+ for (const p of producePaths) {
50
+ const abs = isAbsPath(p) ? p : path.join(artifactsDir, p);
51
+ let content;
52
+ try {
53
+ const st = fs.statSync(abs);
54
+ if (st.isDirectory() || st.size === 0)
55
+ continue;
56
+ content = fs.readFileSync(abs, 'utf8');
57
+ }
58
+ catch {
59
+ continue;
60
+ }
61
+ if (/^needHuman:\s*true$/m.test(content))
62
+ return { declared: true, path: p };
63
+ }
64
+ return { declared: false, path: null };
65
+ }
66
+ // 命令 gate(V1):产物独立行声明 `gate: <命令>`(行首锚定正则,与 needHuman 独立行模式同源)
67
+ // 内嵌/注释/非行首不误判;`gate: false` 视为显式禁用声明不计入(spec G1);空命令(gate: 后无内容)不计入(spec G8)
68
+ export const GATE_LINE_RE = /^gate:\s*(.+)$/gm;
69
+ // 声明解析纯函数(同 detectNeedHuman 模式:缺失/空/目录跳过、零感知):
70
+ // 遍历 produce/outputs 并集 → 收集所有命中行命令(保序)→ { declared, commands, path }
71
+ // 全部命中行为空/禁用 → declared=false(零感知,C2/G8)
72
+ export function detectGate(artifactsDir, paths) {
73
+ if (!Array.isArray(paths) || paths.length === 0)
74
+ return { declared: false, commands: [], path: null };
75
+ const commands = [];
76
+ let declaredPath = null;
77
+ for (const p of paths) {
78
+ const abs = isAbsPath(p) ? p : path.join(artifactsDir, p);
79
+ let content;
80
+ try {
81
+ const st = fs.statSync(abs);
82
+ if (st.isDirectory() || st.size === 0)
83
+ continue;
84
+ content = fs.readFileSync(abs, 'utf8');
85
+ }
86
+ catch {
87
+ continue;
88
+ }
89
+ GATE_LINE_RE.lastIndex = 0; // /g 正则复用防 lastIndex 泄漏
90
+ let m;
91
+ while ((m = GATE_LINE_RE.exec(content)) !== null) {
92
+ const cmd = m[1].trim();
93
+ if (cmd.length === 0 || cmd === 'false')
94
+ continue; // 空命令 / gate: false(禁用声明)不计入
95
+ commands.push(cmd);
96
+ if (!declaredPath)
97
+ declaredPath = p;
98
+ }
99
+ }
100
+ return { declared: commands.length > 0, commands, path: declaredPath };
101
+ }
102
+ export function createGates(root) {
103
+ const sessionsDir = path.join(root, 'sessions');
104
+ function sessionDir(sessionId) {
105
+ if (!SESSION_RE.test(sessionId))
106
+ throw new Error('invalid sessionId: ' + sessionId);
107
+ return path.join(sessionsDir, sessionId);
108
+ }
109
+ function artifactsDirOf(sessionId, batchId) {
110
+ return path.join(sessionDir(sessionId), 'artifacts', batchId);
111
+ }
112
+ function batchFile(sessionId, batchId) {
113
+ if (!SESSION_RE.test(batchId))
114
+ throw new Error('invalid batchId');
115
+ return path.join(sessionDir(sessionId), 'batches', batchId + '.json');
116
+ }
117
+ function readBatch(sessionId, batchId) {
118
+ const file = batchFile(sessionId, batchId);
119
+ if (!fs.existsSync(file))
120
+ return null;
121
+ try {
122
+ // 单点断言:批次 JSON 由 store.createBatch 写入(Batch 契约同源形态),JSON.parse 产物断言为 Batch
123
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
124
+ }
125
+ catch {
126
+ // 损坏批次隔离(v2-node-robustness ②,AC-1 读路径不 throw):损坏 → null(登记在 store 旁路清单,本文件不重复)
127
+ return null;
128
+ }
129
+ }
130
+ // ---- Tier3 门禁辅助 ----
131
+ // lane 启动时间(O2 targets 门禁基准):events 末尾向前反查最近一条 `member.settled` 且 lane 匹配且
132
+ // to==='running' 的事件 ts(ISO)——返工(review→running)会 push 新的 running 结算事件 → 基准重置(重新计时);
133
+ // 无 → 回退 batch.createdAt(防御;正常 merged 必有 running 事件)。遍历模式仿 store.js lastActiveAtOf。
134
+ // e.type === EVT 常量值('member.settled')在 BatchEvent 判别联合下收窄;兜底分支字段 unknown 与 === 比较不受影响
135
+ function laneStartedAt(batch, lane) {
136
+ const evs = batch.events ?? [];
137
+ for (let i = evs.length - 1; i >= 0; i--) {
138
+ const e = evs[i];
139
+ if (e && e.type === EVT.EVT_MEMBER_SETTLED && e.lane === lane && e.to === 'running' && e.ts)
140
+ return e.ts;
141
+ }
142
+ return batch.createdAt;
143
+ }
144
+ function resolveArtifact(sessionId, batchId, rel) {
145
+ return isAbsPath(rel) ? rel : path.join(artifactsDirOf(sessionId, batchId), rel);
146
+ }
147
+ function fileExistsNonEmpty(p) {
148
+ try {
149
+ const st = fs.statSync(p);
150
+ return st.isDirectory() || st.size > 0;
151
+ }
152
+ catch {
153
+ return false;
154
+ }
155
+ }
156
+ // Entry Gate(设计 §四):exec 与 audit lane 派发前 consume 必须全部存在且非空
157
+ // P2-03:条件覆盖 audit 层(原仅 exec——audit lane 声明 consume 时缺产物同样应拒派 GATE_ENTRY_MISSING)
158
+ function checkEntryGate(sessionId, batchId, batch, lane) {
159
+ const t = taskOf(batch, lane);
160
+ if (!t || (t.layer !== 'exec' && t.layer !== 'audit') || !Array.isArray(t.consume) || t.consume.length === 0)
161
+ return { ok: true };
162
+ const missing = t.consume.filter((p) => !fileExistsNonEmpty(resolveArtifact(sessionId, batchId, p)));
163
+ return missing.length ? { ok: false, code: 'GATE_ENTRY_MISSING', missing } : { ok: true };
164
+ }
165
+ // Plan 契约产物结构校验:仅 plan 产物——spec 必填章节 + task-tree JSON 可解析
166
+ function checkPlanContract(sessionId, batchId, batch, lane) {
167
+ const t = taskOf(batch, lane);
168
+ if (!t || t.layer !== 'plan' || !Array.isArray(t.produce))
169
+ return { ok: true };
170
+ const problems = [];
171
+ for (const p of t.produce) {
172
+ const abs = resolveArtifact(sessionId, batchId, p);
173
+ if (!fileExistsNonEmpty(abs)) {
174
+ problems.push(p + ' missing');
175
+ continue;
176
+ }
177
+ const content = fs.readFileSync(abs, 'utf8');
178
+ if (p.endsWith('spec.md')) {
179
+ if (!content.includes('## 验收标准'))
180
+ problems.push(p + ' lacks "## 验收标准"');
181
+ if (!content.includes('## 约束'))
182
+ problems.push(p + ' lacks "## 约束"');
183
+ }
184
+ else if (p.endsWith('.json')) {
185
+ try {
186
+ JSON.parse(content);
187
+ }
188
+ catch {
189
+ problems.push(p + ' invalid JSON');
190
+ }
191
+ }
192
+ }
193
+ return problems.length ? { ok: false, code: 'GATE_PLAN_CONTRACT', problems } : { ok: true };
194
+ }
195
+ // Exit Gate(设计 §五):exec→outputs 存在;audit→produce 存在;plan→Plan 契约
196
+ function checkExitGate(sessionId, batchId, batch, lane) {
197
+ const t = taskOf(batch, lane);
198
+ if (!t || !t.layer)
199
+ return { ok: true };
200
+ if (t.layer === 'plan')
201
+ return checkPlanContract(sessionId, batchId, batch, lane);
202
+ const field = t.layer === 'exec' ? 'outputs' : (t.layer === 'audit' ? 'produce' : null);
203
+ if (!field || !Array.isArray(t[field]) || t[field].length === 0)
204
+ return { ok: true };
205
+ const missing = t[field].filter((p) => !fileExistsNonEmpty(resolveArtifact(sessionId, batchId, p)));
206
+ return missing.length ? { ok: false, code: 'GATE_EXIT_MISSING_' + t.layer.toUpperCase(), missing } : { ok: true };
207
+ }
208
+ // needHuman Gate(复用 review 态挂起):audit lane 产物声明 needHuman →
209
+ // review→merged 前置人工裁决证据(note 契约 `human:<裁决人>:<时间>:<结论>`,如 human:user@2026-08-21:accept)
210
+ // 缺证据 → GATE_NEEDHUMAN_PENDING;conflict 驳回不强制(评审驳回/人工否决语义);
211
+ // 未声明/非 audit lane → 零感知({ ok: true, declared: false })
212
+ function checkNeedHumanGate(sessionId, batchId, batch, lane, note) {
213
+ const t = taskOf(batch, lane);
214
+ if (!t || t.layer !== 'audit' || !Array.isArray(t.produce) || t.produce.length === 0) {
215
+ return { ok: true, declared: false, path: null };
216
+ }
217
+ const det = detectNeedHuman(artifactsDirOf(sessionId, batchId), t.produce);
218
+ if (!det.declared)
219
+ return { ok: true, declared: false, path: null };
220
+ const evidence = typeof note === 'string' ? (note.match(/^human:.+/m) ?? [null])[0] : null;
221
+ if (evidence)
222
+ return { ok: true, declared: true, path: det.path, evidence };
223
+ return {
224
+ ok: false, code: 'GATE_NEEDHUMAN_PENDING', declared: true, path: det.path,
225
+ message: 'audit lane 声明 needHuman,须 Manager 转达人工裁决(merged 需 note 含 human: 证据 / conflict 驳回)',
226
+ };
227
+ }
228
+ // 命令 gate(V1,设计 §组件 2 / spec G2-G10、C5-C7):exec 层产物声明行 `gate: <命令>` → merged 前置确定性执行 → 退出码判定
229
+ // 签名与既有门禁一致(batch 显式传入,不持有状态);执行器经 deps.runCommand 注入(DI,默认真实执行器,测试可注入 mock)
230
+ // cwd 契约(C7):lane worktree 根(若已建)→ GATE_REPO_ROOT(批次 repo 根配置,V1 env 注入)→ artifacts 根兜底
231
+ function commandCwd(sessionId, batchId, lane) {
232
+ const wt = path.join(sessionDir(sessionId), 'worktrees', batchId, lane);
233
+ try {
234
+ if (fs.statSync(wt).isDirectory())
235
+ return wt;
236
+ }
237
+ catch { /* 未建 worktree,继续 */ }
238
+ const repoRoot = process.env.GATE_REPO_ROOT;
239
+ if (repoRoot) {
240
+ try {
241
+ if (fs.statSync(repoRoot).isDirectory())
242
+ return repoRoot;
243
+ }
244
+ catch { /* 无效则跳过 */ }
245
+ }
246
+ return artifactsDirOf(sessionId, batchId);
247
+ }
248
+ function checkCommandGate(sessionId, batchId, batch, lane, deps = {}) {
249
+ // 总开关(GATE_ENABLED=false → 全部零感知,应急逃生阀)
250
+ if (String(process.env.GATE_ENABLED).toLowerCase() === 'false')
251
+ return { ok: true, declared: false };
252
+ const t = taskOf(batch, lane);
253
+ if (!t || t.layer !== 'exec')
254
+ return { ok: true, declared: false }; // 仅约束 exec 层验证声明(D-005)
255
+ // produce ∪ outputs 并集(去重保序)
256
+ const fields = [...new Set([...(t.produce ?? []), ...(t.outputs ?? [])])];
257
+ const det = detectGate(artifactsDirOf(sessionId, batchId), fields);
258
+ if (!det.declared)
259
+ return { ok: true, declared: false }; // 未声明 gate → 零感知(C2/G10)
260
+ if (det.commands.length === 0) {
261
+ return { ok: false, code: 'GATE_EXIT_NO_COMMAND', command: null, exitCode: null, declared: true, needHumanEscalation: false, detail: 'gate 行命中但命令解析为空(防空命令假通过)' };
262
+ }
263
+ const run = deps.runCommand ?? runCommand;
264
+ const results = [];
265
+ let failed = null;
266
+ let outputTruncated = false;
267
+ for (const command of det.commands) {
268
+ const r = run({ command, cwd: commandCwd(sessionId, batchId, lane) });
269
+ if (r.truncated)
270
+ outputTruncated = true;
271
+ const res = { command, exitCode: r.exitCode ?? null, durationMs: r.durationMs ?? 0 };
272
+ results.push(res);
273
+ if (r.forbidden) {
274
+ failed = { code: 'GATE_EXIT_FORBIDDEN', command, exitCode: null, detail: '黑名单命中(只读守卫,不执行)' };
275
+ break;
276
+ }
277
+ if (r.timedOut) {
278
+ failed = { code: 'GATE_EXIT_TIMEOUT', command, exitCode: res.exitCode, detail: '命令超时(重试后仍超时)' };
279
+ break;
280
+ }
281
+ if (r.error && r.error.startsWith('GATE_EXIT_SPAWN_FAIL')) {
282
+ failed = { code: 'GATE_EXIT_SPAWN_FAIL', command, exitCode: null, detail: r.error };
283
+ break;
284
+ }
285
+ if (r.error === 'GATE_EXIT_NO_COMMAND') {
286
+ failed = { code: 'GATE_EXIT_NO_COMMAND', command, exitCode: null, detail: r.error };
287
+ break;
288
+ }
289
+ if (!r.ok) {
290
+ failed = { code: 'GATE_EXIT_NONZERO', command, exitCode: res.exitCode, detail: '退出码 ' + res.exitCode + '(非 0,重试后仍失败)' };
291
+ break;
292
+ }
293
+ }
294
+ if (failed) {
295
+ // C5/G9:失败且产物同时声明 needHuman → 转人工闸(不抛错,store 接线转 checkNeedHumanGate 语义)
296
+ const nh = detectNeedHuman(artifactsDirOf(sessionId, batchId), fields);
297
+ return { ok: false, ...failed, declared: true, needHumanEscalation: nh.declared, path: det.path };
298
+ }
299
+ return { ok: true, declared: true, commands: det.commands, results, outputTruncated, path: det.path };
300
+ }
301
+ // targets 门禁(O2,设计 §1.2):exec 层 lane 声明 targets(批次产物根外目标文件绝对路径)→ merged 前置校验
302
+ // 每个 target:①存在性(statSync 为文件;缺失/目录 → missing);②变更性——mtime 晚于 lane 启动时间
303
+ // (默认 mtime 路径),或 marker 逃生(任务级 targetsMarker 非空 或 env GATE_TARGETS_MODE==='marker' →
304
+ // 目标文件内容含独立行 `targets-claimed: true` 即视为已变更,跳过 mtime 比对,两模式不叠加);
305
+ // 未声明 targets / 非 exec 层 / GATE_ENABLED=false → 零感知({ ok: true, declared: false },与 checkCommandGate D-005 对称)。
306
+ // 判定:missing 非空 → { ok:false, code:'GATE_TARGET_MISSING', missing };unchanged 非空 →
307
+ // { ok:false, code:'GATE_TARGET_UNCHANGED', unchanged };全过 → { ok:true, declared:true, mode:'mtime'|'marker' }。
308
+ // 诚实披露:mtime/marker 均为低成本实证(非密码学证据),防「口头声称零成本通过」;恶意伪造归 O5 人审。
309
+ function checkTargetsGate(sessionId, batchId, batch, lane) {
310
+ // 总开关(GATE_ENABLED=false → 全批零感知,应急逃生阀,与 checkCommandGate 同源)
311
+ if (String(process.env.GATE_ENABLED).toLowerCase() === 'false')
312
+ return { ok: true, declared: false };
313
+ const t = taskOf(batch, lane);
314
+ if (!t || t.layer !== 'exec' || !Array.isArray(t.targets) || t.targets.length === 0) {
315
+ return { ok: true, declared: false }; // 未声明 / 非 exec 层 → 零感知
316
+ }
317
+ const startAt = laneStartedAt(batch, lane);
318
+ const startMs = Date.parse(startAt);
319
+ const markerMode = (typeof t.targetsMarker === 'string' && t.targetsMarker.length > 0)
320
+ || String(process.env.GATE_TARGETS_MODE).toLowerCase() === 'marker';
321
+ const missing = [];
322
+ const unchanged = [];
323
+ for (const target of t.targets) {
324
+ let st;
325
+ try {
326
+ st = fs.statSync(target);
327
+ }
328
+ catch {
329
+ missing.push(target);
330
+ continue;
331
+ }
332
+ if (!st.isFile()) {
333
+ missing.push(target);
334
+ continue;
335
+ } // 目录/非文件视同缺失(与 detectNeedHuman 文件判定同源)
336
+ if (markerMode) {
337
+ let claimed = false;
338
+ try {
339
+ claimed = TARGETS_CLAIMED_RE.test(fs.readFileSync(target, 'utf8'));
340
+ }
341
+ catch { /* 读失败 → 视为未声明(fail-closed,落到 unchanged) */ }
342
+ if (claimed)
343
+ continue; // 标记命中 → 视为已变更(跳过 mtime 比对)
344
+ unchanged.push(target);
345
+ continue;
346
+ }
347
+ // mtime 主路径(默认):目标文件 mtime 必须晚于 lane 最近 running 启动时间
348
+ const mtimeMs = new Date(st.mtime).getTime();
349
+ if (!(Number.isFinite(mtimeMs) && Number.isFinite(startMs) && mtimeMs > startMs))
350
+ unchanged.push(target);
351
+ }
352
+ if (missing.length > 0) {
353
+ return { ok: false, declared: true, code: 'GATE_TARGET_MISSING', missing, unchanged: [], mode: markerMode ? 'marker' : 'mtime', targets: [...t.targets] };
354
+ }
355
+ if (unchanged.length > 0) {
356
+ return { ok: false, declared: true, code: 'GATE_TARGET_UNCHANGED', missing: [], unchanged, mode: markerMode ? 'marker' : 'mtime', targets: [...t.targets] };
357
+ }
358
+ return { ok: true, declared: true, missing: [], unchanged: [], mode: markerMode ? 'marker' : 'mtime', targets: [...t.targets] };
359
+ }
360
+ // Complete Gate(设计 §5.2):audit 层必须存在且全部 settled 且无 failed/conflict;exec 层全部 settled
361
+ function checkCompleteGate(batch) {
362
+ const layers = { plan: [], exec: [], audit: [] };
363
+ for (const w of batch.wavePlan ?? []) {
364
+ for (const t of w.tasks)
365
+ if (t.layer && layers[t.layer])
366
+ layers[t.layer].push(t.id);
367
+ }
368
+ if (layers.exec.length === 0 && layers.audit.length === 0)
369
+ return { ok: true }; // generic 批次
370
+ const laneState = (id) => batch.lanes[id];
371
+ const allTerminal = (ids) => ids.every((id) => schema.isMemberTerminal(laneState(id)));
372
+ if (layers.audit.length === 0)
373
+ return { ok: false, code: 'GATE_COMPLETE_NO_AUDIT' };
374
+ if (!allTerminal(layers.audit))
375
+ return { ok: false, code: 'GATE_EXIT_PENDING_AUDIT', pending: layers.audit.filter((id) => !schema.isMemberTerminal(laneState(id))) };
376
+ if (layers.audit.some((id) => ['failed', 'conflict'].includes(laneState(id))))
377
+ return { ok: false, code: 'GATE_COMPLETE_AUDIT_FAILED' };
378
+ if (layers.exec.length && !allTerminal(layers.exec))
379
+ return { ok: false, code: 'GATE_COMPLETE_EXEC_PENDING', pending: layers.exec.filter((id) => !schema.isMemberTerminal(laneState(id))) };
380
+ return { ok: true };
381
+ }
382
+ // 门禁状态查询(gate_status 工具用,设计 §8 M1):lane 的 layer/契约字段/缺失清单/plan 契约问题
383
+ function gateStatus(sessionId, batchId, lane) {
384
+ const batch = readBatch(sessionId, batchId);
385
+ if (!batch) {
386
+ // 损坏批次(文件存在但解析失败)→ 返回 corrupt 视图不 throw(AC-1 读路径不 throw);不存在 → throw
387
+ if (fs.existsSync(batchFile(sessionId, batchId))) {
388
+ return { lane, layer: null, state: null, team: null, corrupt: true, consume: [], produce: [], outputs: [], consumeMissing: [], outputsMissing: [], produceMissing: [], contractProblems: null, targets: [], targetsMissing: [], targetsUnchanged: [] };
389
+ }
390
+ throw new Error('batch not found: ' + batchId);
391
+ }
392
+ const t = taskOf(batch, lane);
393
+ if (!t)
394
+ return { lane, layer: null, state: batch.lanes[lane], gates: 'generic', team: batch.team };
395
+ const missing = (field) => (Array.isArray(t[field]) ? t[field] : []).filter((p) => !fileExistsNonEmpty(resolveArtifact(sessionId, batchId, p)));
396
+ const contract = t.layer === 'plan' ? checkPlanContract(sessionId, batchId, batch, lane) : null;
397
+ // targets 探测(O2,设计 §1.5):声明清单 + 缺失清单 + 未变更清单——仅 stat(存在性 + mtime 路径),
398
+ // 不读文件正文(marker 命中判定留给门禁执行时,避免 gate_status 读文件成本,见 design Open Question 3)
399
+ const targets = Array.isArray(t.targets) ? [...t.targets] : [];
400
+ const startAt = laneStartedAt(batch, lane);
401
+ const startMs = Date.parse(startAt);
402
+ const statFile = (p) => { try {
403
+ const st = fs.statSync(p);
404
+ return st.isFile() ? st : null;
405
+ }
406
+ catch {
407
+ return null;
408
+ } };
409
+ const targetsMissing = targets.filter((p) => statFile(p) === null);
410
+ const targetsUnchanged = targets.filter((p) => {
411
+ if (targetsMissing.includes(p))
412
+ return false;
413
+ const st = statFile(p);
414
+ if (!st)
415
+ return true; // 探测竞态:stat 失败视同未变更(保守)
416
+ const mtimeMs = new Date(st.mtime).getTime();
417
+ return !(Number.isFinite(mtimeMs) && Number.isFinite(startMs) && mtimeMs > startMs);
418
+ });
419
+ return {
420
+ lane, layer: t.layer ?? null, state: batch.lanes[lane], team: batch.team,
421
+ consume: t.consume ?? [], produce: t.produce ?? [], outputs: t.outputs ?? [],
422
+ consumeMissing: missing('consume'), outputsMissing: missing('outputs'), produceMissing: missing('produce'),
423
+ contractProblems: contract && !contract.ok ? contract.problems : null,
424
+ targets, targetsMissing, targetsUnchanged,
425
+ };
426
+ }
427
+ return { checkEntryGate, checkPlanContract, checkExitGate, checkNeedHumanGate, checkCommandGate, checkTargetsGate, checkCompleteGate, gateStatus };
428
+ }