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.
- package/CHANGELOG.md +120 -0
- package/LICENSE +661 -0
- package/README.en.md +281 -0
- package/README.md +281 -0
- package/cordis.patch.yml +59 -0
- package/lib/acps/certs.js +310 -0
- package/lib/acps/discovery-client.js +283 -0
- package/lib/acps/registry-client.js +527 -0
- package/lib/acps/server.js +302 -0
- package/lib/aip/agent-descriptor.js +170 -0
- package/lib/aip/identity.js +469 -0
- package/lib/aip/tool-descriptor.js +93 -0
- package/lib/api.js +266 -0
- package/lib/artifact-types.js +48 -0
- package/lib/assembly/audit-blind-review.js +170 -0
- package/lib/assembly/schema.js +253 -0
- package/lib/assembly.js +41 -0
- package/lib/assets.js +103 -0
- package/lib/bridge/trajectory.js +202 -0
- package/lib/client.js +704 -0
- package/lib/comms/acps-bridge.js +219 -0
- package/lib/comms/aip-format.js +141 -0
- package/lib/comms/budget.js +124 -0
- package/lib/comms/mailbox.js +221 -0
- package/lib/comms/topic-runtime.js +76 -0
- package/lib/comms/topic.js +115 -0
- package/lib/discovery/filter.js +199 -0
- package/lib/discovery/schema.js +157 -0
- package/lib/discovery/service.js +251 -0
- package/lib/hot/config-watch.js +252 -0
- package/lib/index.js +433 -0
- package/lib/lock.js +69 -0
- package/lib/panel/batch-detail.js +163 -0
- package/lib/panel/batch-list.js +84 -0
- package/lib/panel/locales.js +93 -0
- package/lib/panel/main.js +270 -0
- package/lib/panel/stream.js +348 -0
- package/lib/panel/theme.js +103 -0
- package/lib/panel/widgets.js +63 -0
- package/lib/schema.d.ts +192 -0
- package/lib/schema.js +259 -0
- package/lib/schema.ts +398 -0
- package/lib/state/archive.js +174 -0
- package/lib/state/command-exec.js +148 -0
- package/lib/state/constants.js +37 -0
- package/lib/state/corrupt-registry.js +103 -0
- package/lib/state/event-types.js +65 -0
- package/lib/state/gates.d.ts +226 -0
- package/lib/state/gates.js +428 -0
- package/lib/state/gates.ts +348 -0
- package/lib/state/machine-rules.d.ts +14 -0
- package/lib/state/machine-rules.js +76 -0
- package/lib/state/machine-rules.ts +88 -0
- package/lib/state/machine.js +68 -0
- package/lib/state/resume.js +201 -0
- package/lib/state/schema-v3.d.ts +10 -0
- package/lib/state/schema-v3.js +57 -0
- package/lib/state/schema-v3.ts +80 -0
- package/lib/state/store.js +607 -0
- package/lib/state/task-utils.js +40 -0
- package/lib/tools/core.js +323 -0
- package/lib/tools/git-utils.js +44 -0
- package/lib/tools/lane-tools.js +455 -0
- package/lib/tools/log-tools.js +173 -0
- package/lib/tools/mailbox-tools.js +121 -0
- package/lib/tools/merge-agent.js +127 -0
- package/lib/tools/register.js +85 -0
- package/lib/tools/shared.js +32 -0
- package/lib/types/contracts.d.ts +277 -0
- package/lib/types/contracts.js +17 -0
- package/lib/types/contracts.ts +279 -0
- package/lib/verify/evidence.js +249 -0
- package/lib/verify/gate.js +161 -0
- package/lib/verify/mount.js +48 -0
- package/lib/verify/selector.js +101 -0
- package/lib/watch/lane-heartbeat.js +333 -0
- package/lib/wave-plan.d.ts +48 -0
- package/lib/wave-plan.js +473 -0
- package/lib/wave-plan.ts +465 -0
- package/package.json +71 -0
- package/presets/jiufeng/NOTICE +5 -0
- package/presets/jiufeng/agent.cordis.yml +275 -0
- package/presets/jiufeng/preset.yml +3 -0
- package/skills/jiufeng-team/SKILL.md +214 -0
- package/skills/jiufeng-team/references/constitution.md +62 -0
- package/skills/jiufeng-team/references/roles/coder.md +17 -0
- package/skills/jiufeng-team/references/roles/coordinator.md +13 -0
- package/skills/jiufeng-team/references/roles/designer.md +14 -0
- package/skills/jiufeng-team/references/roles/doc-manager.md +13 -0
- package/skills/jiufeng-team/references/roles/manager.md +22 -0
- package/skills/jiufeng-team/references/roles/reviewer.md +19 -0
- package/skills/jiufeng-team/references/roles/supervisor.md +13 -0
- package/skills/jiufeng-team/references/roles/tester.md +13 -0
- package/skills/jiufeng-team/references/templates/call-chain-matrix-template.md +121 -0
- package/skills/jiufeng-team/references/templates/endpoint-behavior-template.md +60 -0
- package/skills/jiufeng-team/references/templates/gap-list.json +33 -0
- package/skills/jiufeng-team/references/templates/leader-decision-pack.md +92 -0
- package/skills/jiufeng-team/references/templates/plan-template.md +61 -0
- package/skills/jiufeng-team/references/templates/success-pattern-seeds.md +126 -0
- package/skills/jiufeng-team/references/workflow.md +98 -0
- package/skills/jiufeng-team/scripts/check-v3-density.mjs +98 -0
|
@@ -0,0 +1,455 @@
|
|
|
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
|
+
|
|
18
|
+
// 蟛蜞模式 lane 工具(worktree 物理隔离 + checkpoint 提交)
|
|
19
|
+
// -----------------------------------------------------------------------------
|
|
20
|
+
// 原骨架仅导出签名,本文件补齐 3 个 worktree 治理工具。实现契约要点:
|
|
21
|
+
// - lane_worktree_create : git worktree 建 lane 隔离工作树(幂等;集成分支 punky/orch 常驻,
|
|
22
|
+
// lane 分支 punky/<laneId> 从 orch HEAD 基线;残留先清理)
|
|
23
|
+
// - lane_worktree_merge : 串行 merge lane 分支进 orch(merge 队列锁 = serializedMerge 纪律;
|
|
24
|
+
// 成功清理 worktree+分支;失败保留现场 + 冲突文件清单,不自动处置)
|
|
25
|
+
// - lane_checkpoint : lane 内 git add -A + commit(无变更 no-op);这是续跑增强恢复
|
|
26
|
+
// 的物理保全地基——崩溃后 checkpoint 保住产物、
|
|
27
|
+
// 人工可抢救(git log 可查),不触发任何自动恢复(守「不做续跑」红线)
|
|
28
|
+
// - lane_checkpoint_status: 只读查询该 lane checkpoint 历史与 latest 进度(读事件流不调 git;
|
|
29
|
+
// resume 契约唯一查询入口——新 worker 查 checkpoint 跳过已完成步骤)
|
|
30
|
+
// lane_heartbeat 工具由 lib/watch/lane-heartbeat.js 注入组装(enabled 门控由该模块自持;
|
|
31
|
+
// 守卫式加载:既有 lane 未合入时静默降级,本模块照常注册 worktree 四工具,互不阻塞。
|
|
32
|
+
//
|
|
33
|
+
// 装配开关:经 readCapability(config,'worktree') 合并注册表 default(P1-01 缺省默认开,显式 enabled:false 可关);
|
|
34
|
+
// lane_checkpoint 可选 progress={step,total}(commit message + 事件 step/total + laneProgress 断点指针写)+ 只读 lane_checkpoint_status。
|
|
35
|
+
//
|
|
36
|
+
// 与 lane_claim 逻辑锁的互补关系:
|
|
37
|
+
// - lane_claim(既有):同一 lane 的【逻辑写】锁——批次/成员状态文件、产物落盘路径并发防写;
|
|
38
|
+
// 管「写谁的」(治理状态层),维持现状是正确性底线。
|
|
39
|
+
// - 本组工具(新增):不同 lane 在【同一 git 仓库】的【物理写】——工作目录/分支/文件树;
|
|
40
|
+
// 管「写到哪」(工作区层),仅当 C 类批次多 lane 作用于同一 git 仓库时启用(Manager 在 exec
|
|
41
|
+
// 派发前先 lane_worktree_create 并把路径注入 worker 任务包作 cwd 契约)。
|
|
42
|
+
// 两者不能互相替代(worktree 不管状态文件并发;lane_claim 不管文件系统冲突),叠加才完整。
|
|
43
|
+
// -----------------------------------------------------------------------------
|
|
44
|
+
import fs from 'node:fs';
|
|
45
|
+
import path from 'node:path';
|
|
46
|
+
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
47
|
+
import { TEXT_OUTPUT, sessionOf } from './shared.js'; // P2-01:共享辅助直引零依赖 shared.js(不再经 core.js)
|
|
48
|
+
import * as lock from '../lock.js';
|
|
49
|
+
import { resolveMergeConflict } from './merge-agent.js'; // merge 冲突可选 LLM 化解(默认关)
|
|
50
|
+
import { overBudgetOf, hasOverBudgetEvent, laneProgressWrite } from '../state/resume.js'; // B 步数预算:超限判定纯函数(判定层,接线在本文件);laneProgressWrite:P1-02 断点指针写(checkpoint progress 接线)
|
|
51
|
+
import { SAFE_ID } from '../state/constants.js'; // P1-07 单点(原 :64 定义迁出)
|
|
52
|
+
import { readCapability } from '../assembly/schema.js'; // P1-01 装配开关缺省合并读取(注册表 default 同源口径)
|
|
53
|
+
// R-01/R-07 收敛:worktree.*/lane.over-budget 事件字面量(发端 :278/:338/:346/:441 + 读端 :393)改引 EVT 常量单点
|
|
54
|
+
import * as EVT from '../state/event-types.js';
|
|
55
|
+
// R-06 runGit 下沉:git 调用单点迁至 git-utils.js(本文件与 merge-agent.js 均改引,消除双向 import 环)
|
|
56
|
+
import { runGit } from './git-utils.js';
|
|
57
|
+
|
|
58
|
+
// ---- 依赖注入(守卫式加载)----
|
|
59
|
+
let createHeartbeatTools = null;
|
|
60
|
+
try {
|
|
61
|
+
const m = await import('../watch/lane-heartbeat.js');
|
|
62
|
+
createHeartbeatTools = (typeof m?.createHeartbeatTools === 'function') ? m.createHeartbeatTools : null;
|
|
63
|
+
} catch {
|
|
64
|
+
createHeartbeatTools = null; // 模块异常 → lane_heartbeat 留待集成
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// ---- 常量 ----
|
|
68
|
+
const RESERVED_LANE = new Set(['_repo', 'orch']); // 与引擎目录布局冲突的 laneId 保留字
|
|
69
|
+
const ORCH_BRANCH = 'punky/orch';
|
|
70
|
+
const MERGE_WAIT_MS = 60_000; // 同批次 merge 串行化等待上限(serializedMerge 纪律)
|
|
71
|
+
|
|
72
|
+
// git 可用性探测(工具调用前置;git 不可用 → 返回清晰错误并提示安装,验收 T5)
|
|
73
|
+
function gitProbe() {
|
|
74
|
+
const r = runGit('.', ['--version']);
|
|
75
|
+
return r.ok ? { ok: true, version: r.stdout } : { ok: false, error: r.stderr };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ---- 引擎状态根内布局(worktree 根 = <root>/sessions/<sessionId>/worktrees/<batchId>/<laneId>)----
|
|
79
|
+
function batchWtRoot(root, sessionId, batchId) { return path.join(root, 'sessions', sessionId, 'worktrees', batchId); }
|
|
80
|
+
function mainRepoDir(root, sessionId, batchId) { return path.join(batchWtRoot(root, sessionId, batchId), '_repo'); }
|
|
81
|
+
function orchDirOf(root, sessionId, batchId) { return path.join(batchWtRoot(root, sessionId, batchId), 'orch'); }
|
|
82
|
+
function laneDirOf(root, sessionId, batchId, laneId) { return path.join(batchWtRoot(root, sessionId, batchId), laneId); }
|
|
83
|
+
function mergeLockFile(root, sessionId, batchId) { return path.join(batchWtRoot(root, sessionId, batchId), '.merge.lock'); }
|
|
84
|
+
const laneBranch = (laneId) => 'punky/' + laneId;
|
|
85
|
+
// 路径归一化(Windows):git worktree porcelain 输出长路径名,而 os.tmpdir()/TEMP 可能是 8.3 短名
|
|
86
|
+
// (如 ADMINI~1)——realpathSync.native 展开短名到规范长路径,保证注册 worktree 匹配可靠
|
|
87
|
+
function normPath(p) {
|
|
88
|
+
let abs = path.resolve(p);
|
|
89
|
+
try { abs = fs.realpathSync.native(abs); } catch { /* 路径不存在等 → 保持原样 */ }
|
|
90
|
+
return abs.replace(/\\/g, '/').replace(/\/+$/, '');
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function validateIds(sessionId, batchId, laneId) {
|
|
94
|
+
if (!SAFE_ID.test(String(sessionId))) throw new Error('invalid sessionId: ' + sessionId);
|
|
95
|
+
if (!SAFE_ID.test(String(batchId))) throw new Error('invalid batchId: ' + batchId);
|
|
96
|
+
if (!SAFE_ID.test(String(laneId))) throw new Error('invalid laneId: ' + laneId);
|
|
97
|
+
if (RESERVED_LANE.has(laneId)) throw new Error('laneId conflicts with engine layout: ' + laneId);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// git 身份兜底:全局/本地均无身份时回退 punky/punky@localhost
|
|
101
|
+
function ensureGitIdentity(repo) {
|
|
102
|
+
const name = runGit(repo, ['config', 'user.name']);
|
|
103
|
+
const email = runGit(repo, ['config', 'user.email']);
|
|
104
|
+
if (!name.ok || !name.stdout) runGit(repo, ['config', 'user.name', 'punky']);
|
|
105
|
+
if (!email.ok || !email.stdout) runGit(repo, ['config', 'user.email', 'punky@localhost']);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// 主仓库初始化(幂等):git init + 种子提交(worktree add 需要已存在的 HEAD 提交)
|
|
109
|
+
function ensureRepo(root, sessionId, batchId) {
|
|
110
|
+
const repo = mainRepoDir(root, sessionId, batchId);
|
|
111
|
+
if (!fs.existsSync(path.join(repo, 'HEAD'))) {
|
|
112
|
+
fs.mkdirSync(repo, { recursive: true });
|
|
113
|
+
const init = runGit(repo, ['init', '-b', 'punky/main']);
|
|
114
|
+
if (!init.ok) throw new Error('git init failed: ' + init.stderr);
|
|
115
|
+
}
|
|
116
|
+
ensureGitIdentity(repo);
|
|
117
|
+
if (!runGit(repo, ['rev-parse', '--verify', 'HEAD']).ok) {
|
|
118
|
+
const seed = runGit(repo, ['commit', '--allow-empty', '-m', 'punky orch seed']);
|
|
119
|
+
if (!seed.ok) throw new Error('seed commit failed: ' + seed.stderr);
|
|
120
|
+
}
|
|
121
|
+
return repo;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function listWorktrees(repo) {
|
|
125
|
+
const r = runGit(repo, ['worktree', 'list', '--porcelain']);
|
|
126
|
+
if (!r.ok) return [];
|
|
127
|
+
const paths = [];
|
|
128
|
+
for (const line of r.stdout.split('\n')) {
|
|
129
|
+
if (line.startsWith('worktree ')) paths.push(normPath(line.slice('worktree '.length)));
|
|
130
|
+
}
|
|
131
|
+
return paths;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// 清理残留 worktree 目录:已注册 → worktree remove --force;孤儿目录 → rm -rf;再 prune
|
|
135
|
+
function removeWorktreeDir(repo, dir) {
|
|
136
|
+
if (listWorktrees(repo).includes(normPath(dir))) {
|
|
137
|
+
runGit(repo, ['worktree', 'remove', '--force', dir]); // 失败(锁定等)不抛,下面 rm 兜底
|
|
138
|
+
}
|
|
139
|
+
if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
|
|
140
|
+
runGit(repo, ['worktree', 'prune']);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// 集成分支 worktree(幂等):已注册 → 复用(保留已合并产物);残留 → 清理重建
|
|
144
|
+
// 分支已存在(崩溃残留)→ 挂载既有分支(保全已合并历史),不存在 → -B 新建
|
|
145
|
+
function ensureOrch(root, sessionId, batchId) {
|
|
146
|
+
const repo = mainRepoDir(root, sessionId, batchId);
|
|
147
|
+
const orch = orchDirOf(root, sessionId, batchId);
|
|
148
|
+
if (listWorktrees(repo).includes(normPath(orch))) return { repo, orch };
|
|
149
|
+
removeWorktreeDir(repo, orch);
|
|
150
|
+
const hasBranch = runGit(repo, ['show-ref', '--verify', '--quiet', 'refs/heads/' + ORCH_BRANCH]).ok;
|
|
151
|
+
const args = hasBranch ? ['worktree', 'add', orch, ORCH_BRANCH] : ['worktree', 'add', '-B', ORCH_BRANCH, orch];
|
|
152
|
+
const add = runGit(repo, args);
|
|
153
|
+
if (!add.ok) throw new Error('worktree add (orch) failed: ' + add.stderr);
|
|
154
|
+
return { repo, orch };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// lane worktree 创建(幂等):已注册 → 复用;残留 → 清理重建
|
|
158
|
+
// 分支已存在(上次崩溃/未合并残留)→ 挂载既有分支(checkpoint 保全优先,验收 T6);
|
|
159
|
+
// 全新 → 从 orch HEAD 基线建分支(验收 T1:基线 = orch HEAD)
|
|
160
|
+
function createLaneWorktree(root, sessionId, batchId, laneId) {
|
|
161
|
+
const repo = mainRepoDir(root, sessionId, batchId);
|
|
162
|
+
const dir = laneDirOf(root, sessionId, batchId, laneId);
|
|
163
|
+
const branch = laneBranch(laneId);
|
|
164
|
+
if (listWorktrees(repo).includes(normPath(dir))) return { repo, dir, branch, reused: true };
|
|
165
|
+
removeWorktreeDir(repo, dir);
|
|
166
|
+
const hasBranch = runGit(repo, ['show-ref', '--verify', '--quiet', 'refs/heads/' + branch]).ok;
|
|
167
|
+
const args = hasBranch
|
|
168
|
+
? ['worktree', 'add', dir, branch]
|
|
169
|
+
: ['worktree', 'add', '-b', branch, dir, ORCH_BRANCH];
|
|
170
|
+
const add = runGit(repo, args);
|
|
171
|
+
if (!add.ok) throw new Error('worktree add (lane ' + laneId + ') failed: ' + add.stderr);
|
|
172
|
+
return { repo, dir, branch, reused: false };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// checkpoint:git add -A && git commit -m "<batchId>/<laneId>: <message>";无变更 no-op
|
|
176
|
+
// (checkpoint 保全引用):可选 progress={step,total}——提供时 commit message 内嵌
|
|
177
|
+
// "step <step>/<total> — <message>"(git log 可直接审计进度,对齐 taskswarm STATUS 语义);
|
|
178
|
+
// 不传 progress 保持现状格式(向后兼容,参数语义不变)。
|
|
179
|
+
function doCheckpoint(root, sessionId, batchId, laneId, message, progress) {
|
|
180
|
+
const dir = laneDirOf(root, sessionId, batchId, laneId);
|
|
181
|
+
if (!fs.existsSync(dir) || !fs.existsSync(path.join(dir, '.git'))) {
|
|
182
|
+
return { ok: false, reason: 'lane worktree not found — run lane_worktree_create first', worktree: dir };
|
|
183
|
+
}
|
|
184
|
+
const status = runGit(dir, ['status', '--porcelain']);
|
|
185
|
+
if (!status.ok) throw new Error('git status failed: ' + status.stderr);
|
|
186
|
+
if (!status.stdout) return { ok: true, committed: false, reason: 'no changes (no-op)', worktree: dir };
|
|
187
|
+
const msg = progress
|
|
188
|
+
? batchId + '/' + laneId + ': step ' + progress.step + '/' + progress.total + ' — ' + message
|
|
189
|
+
: batchId + '/' + laneId + ': ' + message;
|
|
190
|
+
const add = runGit(dir, ['add', '-A']);
|
|
191
|
+
if (!add.ok) throw new Error('git add failed: ' + add.stderr);
|
|
192
|
+
const commit = runGit(dir, ['commit', '-m', msg]);
|
|
193
|
+
if (!commit.ok) throw new Error('git commit failed: ' + commit.stderr);
|
|
194
|
+
const head = runGit(dir, ['rev-parse', 'HEAD']);
|
|
195
|
+
return { ok: true, committed: true, commit: head.ok ? head.stdout : null, worktree: dir, message: msg };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// merge lane 分支进 orch:串行(merge 队列锁);成功 → 清理;冲突 → 保留现场 + 文件清单
|
|
199
|
+
async function doMerge(root, sessionId, batchId, laneId) {
|
|
200
|
+
const { repo, orch } = ensureOrch(root, sessionId, batchId);
|
|
201
|
+
const branch = laneBranch(laneId);
|
|
202
|
+
if (!runGit(repo, ['show-ref', '--verify', '--quiet', 'refs/heads/' + branch]).ok) {
|
|
203
|
+
throw new Error('lane branch not found: ' + branch + '(请先 lane_worktree_create)');
|
|
204
|
+
}
|
|
205
|
+
const lane = laneDirOf(root, sessionId, batchId, laneId);
|
|
206
|
+
const lockPath = mergeLockFile(root, sessionId, batchId);
|
|
207
|
+
const acquired = await lock.acquire(lockPath, { waitMs: MERGE_WAIT_MS });
|
|
208
|
+
if (!acquired.ok) return { ok: false, error: 'merge queue busy(同批次 merge 串行化,等待超时)' };
|
|
209
|
+
try {
|
|
210
|
+
// 物理单写者:git merge 在 orch worktree 内执行(git 锁即物理单写者,serializedMerge 纪律)
|
|
211
|
+
const m = runGit(orch, ['merge', '--no-edit', branch]);
|
|
212
|
+
if (!m.ok) {
|
|
213
|
+
// 失败保留现场:worktree/分支/在途 merge 状态全保留(不自动处置),返回冲突文件清单
|
|
214
|
+
const unmerged = runGit(orch, ['diff', '--name-only', '--diff-filter=U']);
|
|
215
|
+
return {
|
|
216
|
+
ok: false, conflict: true,
|
|
217
|
+
files: unmerged.ok ? unmerged.stdout.split('\n').filter(Boolean) : [],
|
|
218
|
+
stderr: m.stderr,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
// 成功:清理 worktree + 分支(branch -d 在 orch HEAD 上下文判断已合并)
|
|
222
|
+
if (fs.existsSync(path.join(lane, '.git'))) runGit(repo, ['worktree', 'remove', '--force', lane]);
|
|
223
|
+
runGit(repo, ['worktree', 'prune']);
|
|
224
|
+
const del = runGit(orch, ['branch', '-d', branch]);
|
|
225
|
+
return { ok: true, worktreeCleaned: true, branchDeleted: del.ok, note: del.ok ? '' : 'branch -d: ' + del.stderr };
|
|
226
|
+
} finally {
|
|
227
|
+
lock.release(lockPath, acquired.token);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// ---- 工具定义 ----
|
|
232
|
+
function worktreeToolCreate(ctx, deps) {
|
|
233
|
+
const { store, root } = deps;
|
|
234
|
+
return defineTool({
|
|
235
|
+
name: 'lane_worktree_create',
|
|
236
|
+
description: 'git worktree 物理隔离:为 lane 建独立工作树——集成分支 punky/orch 常驻(主工作树从不 checkout 它)+ lane 分支 punky/<laneId>(从 orch HEAD 基线)。幂等:已注册 worktree 复用;残留目录先 worktree remove --force + prune;git 身份缺失时本地兜底 punky/punky@localhost。worktree 根 = <root>/sessions/<sessionId>/worktrees/<batchId>/<laneId>(引擎状态根内,不落工作区)。与 lane_claim 互补:lane_claim 管逻辑写(批次状态/产物并发),本工具管物理写(git 文件树/分支);仅当 C 类批次多 lane 作用于同一 git 仓库时由 Manager 在 exec 派发前调用,返回路径注入 worker 任务包作 cwd 契约。',
|
|
237
|
+
parameters: {
|
|
238
|
+
batchId: { type: 'string', required: true, description: '批次 ID' },
|
|
239
|
+
laneId: { type: 'string', required: true, description: 'lane 任务 ID(wave_plan task id)' },
|
|
240
|
+
session: { type: 'string', description: '批次归属会话(缺省=当前执行会话,cli 兜底)' },
|
|
241
|
+
},
|
|
242
|
+
output: {
|
|
243
|
+
schema: { type: 'object', additionalProperties: false, properties: {
|
|
244
|
+
ok: { type: 'boolean', required: true }, worktree: { type: 'string' }, branch: { type: 'string' },
|
|
245
|
+
orchBranch: { type: 'string' }, reused: { type: 'boolean' }, base: { type: 'string' }, sessionId: { type: 'string' },
|
|
246
|
+
error: { type: 'string' }, // 执行路径 git 不可用返回 {ok:false,error}(schema 与实现对齐)
|
|
247
|
+
} },
|
|
248
|
+
render: (_args, v) => TEXT_OUTPUT('worktree: ' + v.worktree + ' @' + v.branch + (v.reused ? ' (reused)' : '')),
|
|
249
|
+
},
|
|
250
|
+
async execute(args, exec) {
|
|
251
|
+
const probe = gitProbe();
|
|
252
|
+
if (!probe.ok) return { ok: false, error: 'git 不可用:' + probe.error + '(lane_worktree_create 需要 git;请安装并加入 PATH,或设 DSH_GIT_BIN)' };
|
|
253
|
+
const sessionId = sessionOf(args, exec);
|
|
254
|
+
validateIds(sessionId, args.batchId, args.laneId);
|
|
255
|
+
const batch = store.readBatch(sessionId, args.batchId);
|
|
256
|
+
if (!batch) throw new Error('batch not found: ' + args.batchId + ' @' + sessionId);
|
|
257
|
+
if (!(args.laneId in batch.lanes)) throw new Error('unknown lane: ' + args.laneId + ' @' + args.batchId);
|
|
258
|
+
ensureRepo(root, sessionId, args.batchId);
|
|
259
|
+
const { orch } = ensureOrch(root, sessionId, args.batchId);
|
|
260
|
+
const { dir, branch, reused } = createLaneWorktree(root, sessionId, args.batchId, args.laneId);
|
|
261
|
+
const base = runGit(orch, ['rev-parse', 'HEAD']);
|
|
262
|
+
store.appendEvent(sessionId, args.batchId, EVT.EVT_WORKTREE_CREATED, {
|
|
263
|
+
lane: args.laneId, worktree: dir, branch, orchBranch: ORCH_BRANCH, reused, base: base.ok ? base.stdout : null,
|
|
264
|
+
});
|
|
265
|
+
return { ok: true, worktree: dir, branch, orchBranch: ORCH_BRANCH, reused, base: base.ok ? base.stdout : null, sessionId };
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function worktreeToolCheckpoint(ctx, deps) {
|
|
271
|
+
const { store, root } = deps;
|
|
272
|
+
return defineTool({
|
|
273
|
+
name: 'lane_checkpoint',
|
|
274
|
+
description: 'lane checkpoint 提交:在 lane worktree 内 git add -A && git commit -m "<batchId>/<laneId>: <message>";无变更(status --porcelain 空)no-op(不产生空提交)。这是续跑增强恢复的物理保全地基:崩溃后 checkpoint 提交保住产物、人工可抢救(git log 可查),不触发任何自动恢复(守「不做续跑」红线)。worker 纪律:每完成一个子步骤即 checkpoint,禁止攒批。可选 progress={step,total}(步骤进度 STATUS,step 1-based)——提供时 commit message 内嵌 "step N/total" 且 worktree.checkpoint 事件携带 step/total(git log 可直接审计进度);不传 progress 保持现状(向后兼容)。',
|
|
275
|
+
parameters: {
|
|
276
|
+
batchId: { type: 'string', required: true, description: '批次 ID' },
|
|
277
|
+
laneId: { type: 'string', required: true, description: 'lane 任务 ID' },
|
|
278
|
+
message: { type: 'string', required: true, description: 'checkpoint 提交说明' },
|
|
279
|
+
progress: {
|
|
280
|
+
type: 'object',
|
|
281
|
+
additionalProperties: false,
|
|
282
|
+
properties: {
|
|
283
|
+
step: { type: 'integer', description: '当前步骤(1-based)' },
|
|
284
|
+
total: { type: 'integer', description: '总步数' },
|
|
285
|
+
},
|
|
286
|
+
description: '步骤进度 STATUS(可选):{ step, total }——step 1-based,total=总步数;提供时 commit message 内嵌 "step N/total" 且事件携带 step/total。校验:step/total 正整数且 step ≤ total。',
|
|
287
|
+
},
|
|
288
|
+
session: { type: 'string', description: '批次归属会话(缺省=当前执行会话,cli 兜底)' },
|
|
289
|
+
},
|
|
290
|
+
output: {
|
|
291
|
+
schema: { type: 'object', additionalProperties: false, properties: {
|
|
292
|
+
ok: { type: 'boolean', required: true }, committed: { type: 'boolean' }, commit: { type: 'string' },
|
|
293
|
+
reason: { type: 'string' }, worktree: { type: 'string' }, message: { type: 'string' },
|
|
294
|
+
error: { type: 'string' },
|
|
295
|
+
} },
|
|
296
|
+
render: (_args, v) => TEXT_OUTPUT(v.committed ? 'checkpoint: ' + v.commit : 'checkpoint: no-op (' + (v.reason ?? '') + ')'),
|
|
297
|
+
},
|
|
298
|
+
async execute(args, exec) {
|
|
299
|
+
const probe = gitProbe();
|
|
300
|
+
if (!probe.ok) return { ok: false, error: 'git 不可用:' + probe.error + '(lane_checkpoint 需要 git;请安装并加入 PATH,或设 DSH_GIT_BIN)' };
|
|
301
|
+
if (typeof args.message !== 'string' || !args.message.trim()) throw new Error('message required');
|
|
302
|
+
// progress 校验(fail-closed:step/total 正整数且 step ≤ total;不传 = null = 现状)
|
|
303
|
+
let progress = null;
|
|
304
|
+
if (args.progress != null) {
|
|
305
|
+
const step = args.progress.step;
|
|
306
|
+
const total = args.progress.total;
|
|
307
|
+
if (!Number.isInteger(step) || !Number.isInteger(total) || step < 1 || total < 1 || step > total) {
|
|
308
|
+
throw new Error('invalid progress: expected { step, total } with 1 <= step <= total (positive integers), got ' + JSON.stringify(args.progress));
|
|
309
|
+
}
|
|
310
|
+
progress = { step, total };
|
|
311
|
+
}
|
|
312
|
+
const sessionId = sessionOf(args, exec);
|
|
313
|
+
validateIds(sessionId, args.batchId, args.laneId);
|
|
314
|
+
const batch = store.readBatch(sessionId, args.batchId);
|
|
315
|
+
if (!batch) throw new Error('batch not found: ' + args.batchId + ' @' + sessionId);
|
|
316
|
+
if (!(args.laneId in batch.lanes)) throw new Error('unknown lane: ' + args.laneId + ' @' + args.batchId);
|
|
317
|
+
const r = doCheckpoint(root, sessionId, args.batchId, args.laneId, args.message.trim(), progress);
|
|
318
|
+
if (!r.ok) return r; // worktree 未建 → 提示先 create
|
|
319
|
+
if (r.committed) {
|
|
320
|
+
const evt = { lane: args.laneId, commit: r.commit, message: r.message };
|
|
321
|
+
if (progress) { evt.step = progress.step; evt.total = progress.total; } // 事件携带 step/total(不传则无,向后兼容)
|
|
322
|
+
store.appendEvent(sessionId, args.batchId, EVT.EVT_WORKTREE_CHECKPOINT, evt);
|
|
323
|
+
}
|
|
324
|
+
// P1-02 断点指针:checkpoint 携带 progress 经 laneProgressWrite 写 laneProgress(每子步骤完成即写,失败不阻断)+ B 步数预算超限判定
|
|
325
|
+
if (progress) {
|
|
326
|
+
try { store.updateLaneProgress(sessionId, args.batchId, args.laneId, { ...progress, status: 'running' }); }
|
|
327
|
+
catch (e) { ctx.logger?.warn?.('[lane-checkpoint] laneProgress write failed: ' + String(e?.message ?? e)); }
|
|
328
|
+
const b = overBudgetOf(batch, args.laneId, progress);
|
|
329
|
+
if (b.over && !hasOverBudgetEvent(batch, args.laneId)) {
|
|
330
|
+
store.appendEvent(sessionId, args.batchId, EVT.EVT_LANE_OVER_BUDGET, { lane: args.laneId, step: progress.step, total: progress.total, budget: b.budget });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return r;
|
|
334
|
+
},
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function worktreeToolCheckpointStatus(ctx, deps) {
|
|
339
|
+
const { store, root } = deps;
|
|
340
|
+
return defineTool({
|
|
341
|
+
name: 'lane_checkpoint_status',
|
|
342
|
+
description: 'lane checkpoint 状态查询(只读):读取批次事件流中该 lane 的 worktree.checkpoint 事件序列(ts/step/total 已在事件内),返回 checkpoint 历史与 latest 进度——不依赖 git 调用(零副作用、只读),供新 worker 续跑前查询 checkpoint 以跳过已完成步骤(resume 契约唯一查询入口)。',
|
|
343
|
+
parameters: {
|
|
344
|
+
batchId: { type: 'string', required: true, description: '批次 ID' },
|
|
345
|
+
laneId: { type: 'string', required: true, description: 'lane 任务 ID' },
|
|
346
|
+
session: { type: 'string', description: '批次归属会话(缺省=当前执行会话,cli 兜底)' },
|
|
347
|
+
},
|
|
348
|
+
output: {
|
|
349
|
+
schema: { type: 'object', additionalProperties: false, properties: {
|
|
350
|
+
ok: { type: 'boolean', required: true },
|
|
351
|
+
lane: { type: 'string', required: true },
|
|
352
|
+
branch: { type: 'string', required: true },
|
|
353
|
+
worktree: { type: 'string' },
|
|
354
|
+
checkpoints: {
|
|
355
|
+
type: 'array', required: true,
|
|
356
|
+
items: { type: 'object', additionalProperties: false, properties: {
|
|
357
|
+
commit: { type: 'string' }, ts: { type: 'string' }, message: { type: 'string' },
|
|
358
|
+
step: { type: 'integer' }, total: { type: 'integer' },
|
|
359
|
+
} },
|
|
360
|
+
},
|
|
361
|
+
latest: {
|
|
362
|
+
oneOf: [
|
|
363
|
+
{ type: 'object', additionalProperties: false, properties: { step: { type: 'integer' }, total: { type: 'integer' } } },
|
|
364
|
+
{ type: 'null' },
|
|
365
|
+
],
|
|
366
|
+
},
|
|
367
|
+
} },
|
|
368
|
+
render: (_args, v) => TEXT_OUTPUT('lane ' + v.lane + ': ' + v.checkpoints.length + ' checkpoint(s), latest=' + (v.latest ? v.latest.step + '/' + v.latest.total : 'none')),
|
|
369
|
+
},
|
|
370
|
+
async execute(args, exec) {
|
|
371
|
+
const sessionId = sessionOf(args, exec);
|
|
372
|
+
validateIds(sessionId, args.batchId, args.laneId);
|
|
373
|
+
const batch = store.readBatch(sessionId, args.batchId);
|
|
374
|
+
if (!batch) throw new Error('batch not found: ' + args.batchId + ' @' + sessionId);
|
|
375
|
+
if (!(args.laneId in batch.lanes)) throw new Error('unknown lane: ' + args.laneId + ' @' + args.batchId);
|
|
376
|
+
// 只读:事件流过滤(不调 git);latest = 最近一次携带 progress 的 checkpoint(倒序取首个有 step/total 的)
|
|
377
|
+
const events = (batch.events ?? []).filter((e) => e.type === EVT.EVT_WORKTREE_CHECKPOINT && e.lane === args.laneId);
|
|
378
|
+
const checkpoints = events.map((e) => {
|
|
379
|
+
const c = { commit: typeof e.commit === 'string' ? e.commit : '', ts: e.ts, message: e.message ?? '' };
|
|
380
|
+
if (Number.isInteger(e.step) && Number.isInteger(e.total)) { c.step = e.step; c.total = e.total; }
|
|
381
|
+
return c;
|
|
382
|
+
});
|
|
383
|
+
let latest = null;
|
|
384
|
+
for (let i = checkpoints.length - 1; i >= 0; i--) {
|
|
385
|
+
if (checkpoints[i].step != null && checkpoints[i].total != null) { latest = { step: checkpoints[i].step, total: checkpoints[i].total }; break; }
|
|
386
|
+
}
|
|
387
|
+
const out = { ok: true, lane: args.laneId, branch: laneBranch(args.laneId), checkpoints, latest };
|
|
388
|
+
const dir = laneDirOf(root, sessionId, args.batchId, args.laneId);
|
|
389
|
+
if (fs.existsSync(dir)) out.worktree = dir; // worktree 目录存在性探测(只读)
|
|
390
|
+
return out;
|
|
391
|
+
},
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
function worktreeToolMerge(ctx, deps) {
|
|
396
|
+
const { store, root } = deps;
|
|
397
|
+
return defineTool({
|
|
398
|
+
name: 'lane_worktree_merge',
|
|
399
|
+
description: 'merge lane 分支进 orch:串行执行(merge 队列锁,同批次 merge 串行化——git 锁即物理单写者,借鉴 taskswarm serializedMerge)。成功 → lane 产物并入 punky/orch,清理 lane worktree + 删除分支;失败(冲突)→ 保留现场(worktree/分支/在途 merge 状态全保留)并返回冲突文件清单,不自动处置(conflict 语义由 Manager/Leader 裁决,失败 lane 终态、重做=重开新批次)。与 lane_claim 互补并存:本工具管物理合并,lane_claim 仍管批次状态写。',
|
|
400
|
+
parameters: {
|
|
401
|
+
batchId: { type: 'string', required: true, description: '批次 ID' },
|
|
402
|
+
laneId: { type: 'string', required: true, description: 'lane 任务 ID' },
|
|
403
|
+
session: { type: 'string', description: '批次归属会话(缺省=当前执行会话,cli 兜底)' },
|
|
404
|
+
},
|
|
405
|
+
output: {
|
|
406
|
+
schema: { type: 'object', additionalProperties: false, properties: {
|
|
407
|
+
ok: { type: 'boolean', required: true }, conflict: { type: 'boolean' }, files: { type: 'array', items: { type: 'string' } },
|
|
408
|
+
stderr: { type: 'string' }, worktreeCleaned: { type: 'boolean' }, branchDeleted: { type: 'boolean' },
|
|
409
|
+
note: { type: 'string' }, error: { type: 'string' },
|
|
410
|
+
} },
|
|
411
|
+
render: (_args, v) => v.ok
|
|
412
|
+
? TEXT_OUTPUT('merged: worktree cleaned=' + v.worktreeCleaned + ' branch deleted=' + v.branchDeleted)
|
|
413
|
+
: TEXT_OUTPUT(v.conflict ? 'merge conflict (' + (v.files ?? []).length + ' file(s))' : 'merge failed: ' + (v.error ?? v.stderr ?? '')),
|
|
414
|
+
},
|
|
415
|
+
async execute(args, exec) {
|
|
416
|
+
const probe = gitProbe();
|
|
417
|
+
if (!probe.ok) return { ok: false, error: 'git 不可用:' + probe.error + '(lane_worktree_merge 需要 git;请安装并加入 PATH,或设 DSH_GIT_BIN)' };
|
|
418
|
+
const sessionId = sessionOf(args, exec);
|
|
419
|
+
validateIds(sessionId, args.batchId, args.laneId);
|
|
420
|
+
const batch = store.readBatch(sessionId, args.batchId);
|
|
421
|
+
if (!batch) throw new Error('batch not found: ' + args.batchId + ' @' + sessionId);
|
|
422
|
+
if (!(args.laneId in batch.lanes)) throw new Error('unknown lane: ' + args.laneId + ' @' + args.batchId);
|
|
423
|
+
const r = await doMerge(root, sessionId, args.batchId, args.laneId);
|
|
424
|
+
if (r.ok) {
|
|
425
|
+
store.appendEvent(sessionId, args.batchId, EVT.EVT_WORKTREE_MERGED, { lane: args.laneId, branch: laneBranch(args.laneId), branchDeleted: r.branchDeleted });
|
|
426
|
+
} else if (r.conflict) {
|
|
427
|
+
// 冲突可选 LLM merge agent 化解(默认关 → 现状逐字一致;全量逻辑在 merge-agent.js)
|
|
428
|
+
return await resolveMergeConflict(deps, {
|
|
429
|
+
root, store, sessionId, batchId: args.batchId, laneId: args.laneId,
|
|
430
|
+
orchDir: orchDirOf(root, sessionId, args.batchId), branch: laneBranch(args.laneId),
|
|
431
|
+
conflictFiles: r.files ?? [], conflict: r,
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
return r;
|
|
435
|
+
},
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// ---- 组装:lane_heartbeat(enabled 门控由该模块自持)+ worktree 四工具 ----
|
|
440
|
+
export function createLaneTools(ctx, deps) {
|
|
441
|
+
const config = deps?.config ?? {};
|
|
442
|
+
const tools = [];
|
|
443
|
+
// 注入的 lane_heartbeat;守卫式加载,模块未合入时留待集成(功能独立,互不阻塞)
|
|
444
|
+
if (createHeartbeatTools) tools.push(...createHeartbeatTools(ctx, deps));
|
|
445
|
+
// worktree 四工具(create/merge/checkpoint/checkpoint_status):P1-01 缺省默认开(readCapability 合并注册表 default,显式 enabled:false 可关)
|
|
446
|
+
if (readCapability(config, 'worktree')?.enabled === true) {
|
|
447
|
+
tools.push(
|
|
448
|
+
worktreeToolCreate(ctx, deps),
|
|
449
|
+
worktreeToolMerge(ctx, deps),
|
|
450
|
+
worktreeToolCheckpoint(ctx, deps),
|
|
451
|
+
worktreeToolCheckpointStatus(ctx, deps),
|
|
452
|
+
);
|
|
453
|
+
}
|
|
454
|
+
return tools;
|
|
455
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
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
|
+
|
|
18
|
+
// 蟛蜞模式日志导出工具(1 个):log_export
|
|
19
|
+
// -----------------------------------------------------------------------------
|
|
20
|
+
// 模型可调用、只读、可审计的事件日志导出。
|
|
21
|
+
// 现状事件流已完备(store.appendEvent 全量落 batch.events,含 member.settled / gate.* /
|
|
22
|
+
// worktree.* / budget.* / system.* / asset.* 等),但缺模型可调用的导出工具——本工具为
|
|
23
|
+
// store.readBatch 的纯读投影,零副作用(不 appendEvent、不改状态文件、不碰 mailbox、
|
|
24
|
+
// 不写工作区;唯一写路径是显式 writeTo 落盘到引擎产物根,属可审计产物)。
|
|
25
|
+
// 装配开关:经 readCapability(config,'logs') 合并注册表 default(P1-01——logs 键注册表默认关:
|
|
26
|
+
// 缺省不注册 → 工具总数不含 log_export;显式 capabilities.logs.enabled:true(如 cordis.patch.yml)
|
|
27
|
+
// 或 enabled:false 控制注册)。
|
|
28
|
+
import fs from 'node:fs';
|
|
29
|
+
import path from 'node:path';
|
|
30
|
+
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
31
|
+
import { TEXT_OUTPUT, sessionOf } from './shared.js'; // P2-01:共享辅助直引零依赖 shared.js(不再经 core.js)
|
|
32
|
+
import { SAFE_ID, TERMINAL } from '../state/constants.js'; // P1-07 单点(原 :32-33 定义迁出)
|
|
33
|
+
import { readCapability } from '../assembly/schema.js'; // P1-01:装配开关经注册表 default 缺省合并
|
|
34
|
+
// R-07 读端收敛:summaryOf 完整字面量比较改引 EVT 常量单点(member.settled/lane.skipped/lane.needhuman/batch.phase/budget.rejected)
|
|
35
|
+
import * as EVT from '../state/event-types.js';
|
|
36
|
+
|
|
37
|
+
function artifactsDirOf(root, sessionId, batchId) {
|
|
38
|
+
return path.join(root, 'sessions', sessionId, 'artifacts', batchId);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// 路径防逃逸(同 store.claimAsset 语义):批次内相对路径,拒绝绝对路径/盘符前缀/../空段
|
|
42
|
+
function assertSafeRelative(p) {
|
|
43
|
+
if (typeof p !== 'string' || !p.length) throw new Error('invalid writeTo path: ' + p + ' (must be batch-relative)');
|
|
44
|
+
if (path.isAbsolute(p) || /^[A-Za-z]:/.test(p)) throw new Error('invalid writeTo path: ' + p + ' (must be batch-relative, no absolute path)');
|
|
45
|
+
const segs = p.split(/[\\/]+/);
|
|
46
|
+
if (segs.some((s) => s === '' || s === '.' || s === '..')) throw new Error('invalid writeTo path: ' + p + ' (no .. or empty segment)');
|
|
47
|
+
return segs;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// 事件关键字段摘要(markdown 时间线表用;未知事件回退 JSON 截断)
|
|
51
|
+
function summaryOf(e) {
|
|
52
|
+
if (e.type === EVT.EVT_MEMBER_SETTLED) return (e.from ?? '') + ' -> ' + (e.to ?? '') + (e.note ? ' | ' + e.note : '');
|
|
53
|
+
if (e.type === EVT.EVT_LANE_SKIPPED || e.type === EVT.EVT_LANE_NEEDHUMAN) return e.note ?? '';
|
|
54
|
+
if (e.type === EVT.EVT_BATCH_PHASE) return (e.from ?? '') + ' -> ' + (e.to ?? '');
|
|
55
|
+
if (e.type.startsWith('gate.') || e.type.startsWith('worktree.') || e.type === EVT.EVT_BUDGET_REJECTED) {
|
|
56
|
+
const keys = ['lane', 'code', 'missing', 'detail', 'step', 'total', 'chainId', 'gate'];
|
|
57
|
+
const parts = keys.filter((k) => e[k] !== undefined).map((k) => k + '=' + (Array.isArray(e[k]) ? e[k].join(',') : String(e[k])));
|
|
58
|
+
return parts.join(' | ');
|
|
59
|
+
}
|
|
60
|
+
if (e.type.startsWith('asset.') || e.type.startsWith('archive.')) {
|
|
61
|
+
const keys = ['lane', 'target', 'source', 'reason'];
|
|
62
|
+
const parts = keys.filter((k) => e[k] !== undefined).map((k) => k + '=' + String(e[k]));
|
|
63
|
+
return parts.join(' | ');
|
|
64
|
+
}
|
|
65
|
+
const extra = { ...e };
|
|
66
|
+
delete extra.ts; delete extra.type; delete extra.lane;
|
|
67
|
+
const s = JSON.stringify(extra);
|
|
68
|
+
return s.length > 60 ? s.slice(0, 57) + '...' : s;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function matchEvent(e, args) {
|
|
72
|
+
if (args.lane && e.lane !== args.lane) return false;
|
|
73
|
+
if (args.type && !String(e.type ?? '').startsWith(args.type)) return false;
|
|
74
|
+
if (args.since && Date.parse(e.ts) < Date.parse(args.since)) return false;
|
|
75
|
+
return true;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function filterDesc(args) {
|
|
79
|
+
const conds = [];
|
|
80
|
+
if (args.lane) conds.push('lane=' + args.lane);
|
|
81
|
+
if (args.type) conds.push('type~' + args.type);
|
|
82
|
+
if (args.since) conds.push('since=' + args.since);
|
|
83
|
+
return conds.length ? conds.join('; ') : '无';
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// markdown 可审计报告:批次头 + 时间线表 + 尾部汇总(终态计数/门禁清单/资产归档清单)
|
|
87
|
+
function buildReport(batch, sessionId, filtered, args) {
|
|
88
|
+
const lines = [];
|
|
89
|
+
lines.push('# 事件日志导出报告');
|
|
90
|
+
lines.push('');
|
|
91
|
+
lines.push('- 批次: ' + batch.batchId);
|
|
92
|
+
lines.push('- 会话: ' + sessionId);
|
|
93
|
+
lines.push('- phase: ' + batch.phase);
|
|
94
|
+
lines.push('- 事件总数: ' + (batch.events ?? []).length);
|
|
95
|
+
lines.push('- 过滤条件: ' + filterDesc(args));
|
|
96
|
+
lines.push('- 导出时间: ' + new Date().toISOString());
|
|
97
|
+
lines.push('');
|
|
98
|
+
lines.push('## 时间线');
|
|
99
|
+
lines.push('');
|
|
100
|
+
lines.push('| ts | type | lane | 关键字段 |');
|
|
101
|
+
lines.push('|---|---|---|---|');
|
|
102
|
+
for (const e of filtered) {
|
|
103
|
+
lines.push('| ' + e.ts + ' | ' + e.type + ' | ' + (e.lane ?? '-') + ' | ' + summaryOf(e).replace(/\|/g, '\\|') + ' |');
|
|
104
|
+
}
|
|
105
|
+
lines.push('');
|
|
106
|
+
lines.push('## 尾部汇总');
|
|
107
|
+
lines.push('');
|
|
108
|
+
lines.push('### 各 lane 终态计数');
|
|
109
|
+
lines.push('');
|
|
110
|
+
lines.push('| 终态 | 计数 |');
|
|
111
|
+
lines.push('|---|---|');
|
|
112
|
+
for (const st of TERMINAL) {
|
|
113
|
+
const n = Object.values(batch.lanes ?? {}).filter((v) => v === st).length;
|
|
114
|
+
lines.push('| ' + st + ' | ' + n + ' |');
|
|
115
|
+
}
|
|
116
|
+
const gateEvents = filtered.filter((e) => String(e.type).startsWith('gate.'));
|
|
117
|
+
lines.push('');
|
|
118
|
+
lines.push('### 门禁事件清单 (' + gateEvents.length + ')');
|
|
119
|
+
lines.push('');
|
|
120
|
+
for (const e of gateEvents) lines.push('- `' + e.type + '` ' + summaryOf(e));
|
|
121
|
+
const assetEvents = filtered.filter((e) => String(e.type).startsWith('asset.') || String(e.type).startsWith('archive.'));
|
|
122
|
+
lines.push('');
|
|
123
|
+
lines.push('### 资产/归档事件清单 (' + assetEvents.length + ')');
|
|
124
|
+
lines.push('');
|
|
125
|
+
for (const e of assetEvents) lines.push('- `' + e.type + '` ' + summaryOf(e));
|
|
126
|
+
return lines.join('\n');
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function createLogTools(ctx, deps) {
|
|
130
|
+
const config = deps?.config ?? {};
|
|
131
|
+
// logs 注册表默认关(P1-01):readCapability 合并 default {enabled:false}——未配置/disabled → 零注册;
|
|
132
|
+
// 显式 logs.enabled=true(patch 全开)→ 注册 log_export。
|
|
133
|
+
if (readCapability(config, 'logs')?.enabled !== true) return [];
|
|
134
|
+
const { root, store } = deps;
|
|
135
|
+
|
|
136
|
+
return [
|
|
137
|
+
defineTool({
|
|
138
|
+
name: "log_export",
|
|
139
|
+
description: "导出批次事件日志(只读投影,零副作用):按 lane/type(前缀)/since 过滤;format=json 返回结构化事件数组(ts/type 保序),format=markdown 返回可审计报告(批次头+时间线表+尾部汇总);writeTo 可选落盘到引擎产物根(批次内相对路径,防逃逸)。",
|
|
140
|
+
parameters: {"batchId":{"type":"string","required":true,"description":"批次 ID"},"session":{"type":"string","description":"批次归属会话(缺省=当前执行会话,cli 兜底)"},"lane":{"type":"string","description":"按 lane 过滤"},"type":{"type":"string","description":"按事件 type 过滤(支持前缀匹配)"},"since":{"type":"string","description":"ISO 时间戳,仅返回该时刻之后的事件"},"format":{"type":"string","enum":["json","markdown"],"description":"json 默认 / markdown 可审计报告"},"writeTo":{"type":"string","description":"可选:相对批次产物根的落盘路径(如 audit/event-log.md),仅落引擎产物根"}},
|
|
141
|
+
output: {
|
|
142
|
+
schema: {"type":"object","additionalProperties":false,"properties":{"ok":{"type":"boolean","required":true},"batchId":{"type":"string","required":true},"session":{"type":"string","required":true},"phase":{"type":"string","required":true},"eventCount":{"type":"integer","required":true},"exported":{"type":"integer","required":true},"items":{"type":"array","items":{"type":"object","additionalProperties":true}},"report":{"type":"string"},"writtenTo":{"type":"string"}}},
|
|
143
|
+
render: (_args, value) => TEXT_OUTPUT('log_export: ' + value.exported + '/' + value.eventCount + ' events' + (value.writtenTo ? ' -> ' + value.writtenTo : '')),
|
|
144
|
+
},
|
|
145
|
+
async execute(args, exec) {
|
|
146
|
+
const sessionId = sessionOf(args, exec);
|
|
147
|
+
if (!SAFE_ID.test(sessionId)) throw new Error('invalid session: ' + sessionId);
|
|
148
|
+
if (!SAFE_ID.test(args.batchId)) throw new Error('invalid batchId: ' + args.batchId);
|
|
149
|
+
if (args.since != null && !Number.isFinite(Date.parse(args.since))) throw new Error('invalid since: ' + args.since + ' (must be ISO timestamp)');
|
|
150
|
+
const batch = store.readBatch(sessionId, args.batchId);
|
|
151
|
+
if (!batch) throw new Error('batch not found: ' + args.batchId);
|
|
152
|
+
const events = batch.events ?? [];
|
|
153
|
+
const filtered = events.filter((e) => matchEvent(e, args));
|
|
154
|
+
const out = { ok: true, batchId: args.batchId, session: sessionId, phase: batch.phase, eventCount: events.length, exported: filtered.length };
|
|
155
|
+
if ((args.format ?? 'json') === 'markdown') {
|
|
156
|
+
out.report = buildReport(batch, sessionId, filtered, args);
|
|
157
|
+
if (args.writeTo) {
|
|
158
|
+
const segs = assertSafeRelative(args.writeTo);
|
|
159
|
+
const artifactsDir = artifactsDirOf(root, sessionId, args.batchId);
|
|
160
|
+
const dest = path.join(artifactsDir, ...segs);
|
|
161
|
+
if (!path.resolve(dest).startsWith(path.resolve(artifactsDir) + path.sep)) throw new Error('writeTo escapes artifacts dir: ' + args.writeTo);
|
|
162
|
+
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
|
163
|
+
fs.writeFileSync(dest, out.report, 'utf8');
|
|
164
|
+
out.writtenTo = args.writeTo;
|
|
165
|
+
}
|
|
166
|
+
} else {
|
|
167
|
+
out.items = filtered;
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
},
|
|
171
|
+
}),
|
|
172
|
+
];
|
|
173
|
+
}
|