doukui 0.0.0-stage → 0.3.1
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.en.md +42 -0
- package/README.md +147 -2
- package/bin/commands/build.js +178 -0
- package/bin/commands/config.js +88 -0
- package/bin/commands/help.js +83 -0
- package/bin/commands/init.js +194 -0
- package/bin/commands/install.js +202 -0
- package/bin/commands/interactive.js +352 -0
- package/bin/commands/list.js +108 -0
- package/bin/commands/loop-server.js +357 -0
- package/bin/commands/loop.js +1443 -0
- package/bin/commands/migrate.js +120 -0
- package/bin/commands/setup-global.js +81 -0
- package/bin/commands/status.js +140 -0
- package/bin/commands/team-cleanup.js +190 -0
- package/bin/commands/validate-config.js +35 -0
- package/bin/commands/validate.js +21 -0
- package/bin/commands/version.js +22 -0
- package/bin/context.js +143 -0
- package/bin/doukui.js +216 -0
- package/package.json +47 -4
- package/plugins/contracts/capabilities.js +268 -0
- package/plugins/contracts/checkresult-schema.json +75 -0
- package/plugins/contracts/config-schema.json +179 -0
- package/plugins/contracts/plugin-interface.js +262 -0
- package/plugins/contracts/plugin-schema.json +104 -0
- package/plugins/core/hook-session-start/index.js +281 -0
- package/plugins/core/hook-session-start/plugin.json +7 -0
- package/plugins/core/hook-skill-gate/index.js +661 -0
- package/plugins/core/hook-skill-gate/plugin.json +12 -0
- package/plugins/core/provider-loop-engine/index.js +1411 -0
- package/plugins/core/provider-loop-engine/plugin.json +15 -0
- package/plugins/core/provider-memory-store/index.js +510 -0
- package/plugins/core/provider-memory-store/plugin.json +9 -0
- package/plugins/core/provider-role-registry/index.js +376 -0
- package/plugins/core/provider-role-registry/plugin.json +9 -0
- package/plugins/core/provider-state-store/index.js +244 -0
- package/plugins/core/provider-state-store/plugin.json +9 -0
- package/plugins/core/provider-watchdog/assets/daemon-config.template.json +32 -0
- package/plugins/core/provider-watchdog/assets/lib/watchdog-multi-window.js +676 -0
- package/plugins/core/provider-watchdog/assets/watchdog.js +754 -0
- package/plugins/core/provider-watchdog/index.js +151 -0
- package/plugins/core/provider-watchdog/plugin.json +13 -0
- package/plugins/core/skill-agent-dispatcher/cleanup-reference.md +214 -0
- package/plugins/core/skill-agent-dispatcher/daemon-helpers-reference.md +249 -0
- package/plugins/core/skill-agent-dispatcher/plugin.json +13 -0
- package/plugins/core/skill-agent-dispatcher/roles-reference.md +253 -0
- package/plugins/core/skill-agent-dispatcher/skill.md +1291 -0
- package/plugins/core/skill-agentic-loop/plugin.json +20 -0
- package/plugins/core/skill-agentic-loop/skill.md +588 -0
- package/plugins/core/skill-batch-task-creator/plugin.json +15 -0
- package/plugins/core/skill-batch-task-creator/skill.md +620 -0
- package/plugins/core/skill-checklist/plugin.json +10 -0
- package/plugins/core/skill-checklist/skill.md +171 -0
- package/plugins/core/skill-completion-report/plugin.json +10 -0
- package/plugins/core/skill-completion-report/skill.md +331 -0
- package/plugins/core/skill-doukui-plan/plugin.json +15 -0
- package/plugins/core/skill-doukui-plan/skill.md +233 -0
- package/plugins/core/skill-doukui-sync/plugin.json +10 -0
- package/plugins/core/skill-doukui-sync/skill.md +76 -0
- package/plugins/core/skill-experience-logger/plugin.json +10 -0
- package/plugins/core/skill-experience-logger/skill.md +235 -0
- package/plugins/core/skill-human-checkpoint/plugin.json +10 -0
- package/plugins/core/skill-human-checkpoint/skill.md +194 -0
- package/plugins/core/skill-progress-tracker/plugin.json +10 -0
- package/plugins/core/skill-progress-tracker/skill.md +228 -0
- package/plugins/core/skill-role-manager/plugin.json +10 -0
- package/plugins/core/skill-role-manager/skill.md +252 -0
- package/plugins/core/skill-split-work-package/plugin.json +15 -0
- package/plugins/core/skill-split-work-package/skill.md +441 -0
- package/plugins/core/skill-task-archive/plugin.json +10 -0
- package/plugins/core/skill-task-archive/skill.md +116 -0
- package/plugins/core/skill-task-creator/plugin.json +15 -0
- package/plugins/core/skill-task-creator/skill.md +886 -0
- package/plugins/core/skill-team-cleanup/plugin.json +10 -0
- package/plugins/core/skill-team-cleanup/skill.md +266 -0
- package/plugins/core/skill-watchdog-manager/plugin.json +10 -0
- package/plugins/core/skill-watchdog-manager/skill.md +143 -0
- package/plugins/core/skill-workflow-orchestrator/plugin.json +13 -0
- package/plugins/core/skill-workflow-orchestrator/skill.md +273 -0
- package/plugins/core/validator-doc-sync/index.js +248 -0
- package/plugins/core/validator-doc-sync/plugin.json +12 -0
- package/plugins/core/validator-work-package/index.js +300 -0
- package/plugins/core/validator-work-package/plugin.json +12 -0
- package/plugins/plugin-registry.json +186 -0
- package/plugins/runtime/agent-def-generator.js +150 -0
- package/plugins/runtime/audit-logger.js +311 -0
- package/plugins/runtime/build-cli.js +89 -0
- package/plugins/runtime/checkresult-validator.js +131 -0
- package/plugins/runtime/claude-md-injector.js +159 -0
- package/plugins/runtime/cleanup-utils.js +293 -0
- package/plugins/runtime/config-manager.js +317 -0
- package/plugins/runtime/config-validator.js +320 -0
- package/plugins/runtime/context-window.js +81 -0
- package/plugins/runtime/event-bus.js +207 -0
- package/plugins/runtime/executor-claude.js +828 -0
- package/plugins/runtime/executor-default.js +448 -0
- package/plugins/runtime/executor-local.js +178 -0
- package/plugins/runtime/executor-sdk.js +415 -0
- package/plugins/runtime/harness-build.js +1037 -0
- package/plugins/runtime/hook-dispatcher.js +315 -0
- package/plugins/runtime/logger.js +192 -0
- package/plugins/runtime/loop-actuator.js +292 -0
- package/plugins/runtime/loop-coordinator.js +347 -0
- package/plugins/runtime/loop-defaults.js +29 -0
- package/plugins/runtime/loop-dispatch-batch.js +247 -0
- package/plugins/runtime/loop-executor.js +120 -0
- package/plugins/runtime/loop-report.js +327 -0
- package/plugins/runtime/loop-server-core.js +750 -0
- package/plugins/runtime/loop-snapshot.js +581 -0
- package/plugins/runtime/loop-trace.js +242 -0
- package/plugins/runtime/loop-worktree.js +404 -0
- package/plugins/runtime/manifest-resolver.js +457 -0
- package/plugins/runtime/multi-window-coordinator.js +560 -0
- package/plugins/runtime/objective-verifier.js +136 -0
- package/plugins/runtime/plan-lint.js +100 -0
- package/plugins/runtime/plan-reader.js +763 -0
- package/plugins/runtime/plugin-loader.js +798 -0
- package/plugins/runtime/plugin-trust.js +182 -0
- package/plugins/runtime/plugin-validator.js +491 -0
- package/plugins/runtime/provider-failover.js +114 -0
- package/plugins/runtime/provider-resolver.js +342 -0
- package/plugins/runtime/reflection-evaluator.js +545 -0
- package/plugins/runtime/resolve-plugin-path.js +297 -0
- package/plugins/runtime/safe-path.js +119 -0
- package/plugins/runtime/sandbox-context.js +235 -0
- package/plugins/runtime/sandbox-manager.js +609 -0
- package/plugins/runtime/sandbox-worker.js +215 -0
- package/plugins/runtime/self-rescue-ladder.js +38 -0
- package/plugins/runtime/settings-merger.js +172 -0
- package/plugins/runtime/state-store.js +527 -0
- package/plugins/runtime/team-cleanup.js +497 -0
- package/plugins/runtime/text-tokenize.js +25 -0
- package/plugins/runtime/validator-pipeline.js +475 -0
- package/plugins/runtime/yaml-parser.js +692 -0
- package/templates/harness-config.yaml +394 -0
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loop Trace — Agentic Loop per-round 阶段级可观测性聚合落盘(WP-196-1-impl)
|
|
3
|
+
*
|
|
4
|
+
* @module loop-trace
|
|
5
|
+
*
|
|
6
|
+
* 职责(单一职责:per-round trace 聚合 + JSONL 落盘):
|
|
7
|
+
* - 把 engine step() 返回的 phaseTimings + executor.run() 的 _executorTrace + 本轮 verdict
|
|
8
|
+
* 聚合成一个 round record。
|
|
9
|
+
* - 以 JSON Lines(每行一个 JSON 对象)追加到 `.doukui/loop-{loopId}/trace.jsonl`,
|
|
10
|
+
* 崩溃后可逐行回放(修复 WP-194 根因⑥:运行时数据目录不存在)。
|
|
11
|
+
* - 渲染一行式阶段摘要供 driver stdout 输出(回应「感觉不是五段式」)。
|
|
12
|
+
*
|
|
13
|
+
* 与 loop-report.js 的边界(落点选择 = 方式 A,单一职责):
|
|
14
|
+
* loop-report.js 是纯函数式终态报告(无 IO、无副作用,注释明示),负责 loop 触顶时的
|
|
15
|
+
* 「总结报告内容」。本模块负责「每轮增量 trace 落盘 + 一行摘要」,有 IO 副作用,二者解耦。
|
|
16
|
+
*
|
|
17
|
+
* 回退安全(承袭 WP-191 心跳 fs.utimesSync 失败降级纪律):
|
|
18
|
+
* 所有落盘/渲染均 try/catch 降级。appendTrace 写入失败只返回 false + 不抛,
|
|
19
|
+
* 调用方(driver)据此决定是否记 warning,loop 主流程照常推进。
|
|
20
|
+
*
|
|
21
|
+
* 数据来源:
|
|
22
|
+
* - engine step() 返回值 .phaseTimings(observe/think/act/reflect/decide 各 {phase, startMs, endMs, elapsedMs, summary})
|
|
23
|
+
* - executor.run() 返回的 CheckResult._executorTrace({spawnMs, exitCode, timedOut, rateLimited, tokenUsage, endpointMs})
|
|
24
|
+
* - step() 返回值 .verdict / .iteration
|
|
25
|
+
*
|
|
26
|
+
* 设计依据:docs/wp/WP-196.md、docs/wp/WP-196-1-impl.md
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
'use strict';
|
|
30
|
+
|
|
31
|
+
var fs = require('fs');
|
|
32
|
+
var path = require('path');
|
|
33
|
+
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
// 路径解析
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 解析 trace.jsonl 落盘路径。
|
|
40
|
+
* 根目录探测:优先 projectRoot(driver 传入),回退从 cwd 向上找 .doukui / package.json / task.md,
|
|
41
|
+
* 最终兜底 cwd。
|
|
42
|
+
* @param {string} loopId
|
|
43
|
+
* @param {string} [projectRoot] 项目根覆盖
|
|
44
|
+
* @returns {string} 绝对路径 .doukui/loop-{loopId}/trace.jsonl
|
|
45
|
+
*/
|
|
46
|
+
function resolveTracePath(loopId, projectRoot) {
|
|
47
|
+
var root = projectRoot || _detectProjectRoot();
|
|
48
|
+
return path.join(root, '.doukui', 'loop-' + loopId, 'trace.jsonl');
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function _detectProjectRoot() {
|
|
52
|
+
var dir = process.cwd();
|
|
53
|
+
for (var i = 0; i < 10; i++) {
|
|
54
|
+
if (fs.existsSync(path.join(dir, '.doukui'))) return dir;
|
|
55
|
+
if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
|
|
56
|
+
if (fs.existsSync(path.join(dir, 'task.md'))) return dir;
|
|
57
|
+
var parent = path.dirname(dir);
|
|
58
|
+
if (parent === dir) break;
|
|
59
|
+
dir = parent;
|
|
60
|
+
}
|
|
61
|
+
return process.cwd();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// ---------------------------------------------------------------------------
|
|
65
|
+
// round record 聚合
|
|
66
|
+
// ---------------------------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* 聚合一个 round record(纯函数,无 IO)。
|
|
70
|
+
* 容错:任一输入缺失时对应字段降级(executor 缺失→null,phaseTimings 缺失→[]),不抛。
|
|
71
|
+
*
|
|
72
|
+
* @param {object} opts
|
|
73
|
+
* @param {string} opts.loopId
|
|
74
|
+
* @param {number} opts.iteration
|
|
75
|
+
* @param {Array<{phase:string, startMs?:number, endMs?:number, elapsedMs?:number, summary?:object}>} [opts.phaseTimings]
|
|
76
|
+
* @param {object} [opts.executorTrace] { spawnMs, exitCode, timedOut, rateLimited, tokenUsage, endpointMs }
|
|
77
|
+
* @param {string} [opts.verdict]
|
|
78
|
+
* @param {string} [opts.dispatchedWp] 本轮 dispatch 的 WP(driver 从 pendingAction 取)
|
|
79
|
+
* @returns {object} round record
|
|
80
|
+
*/
|
|
81
|
+
function buildRoundRecord(opts) {
|
|
82
|
+
opts = opts || {};
|
|
83
|
+
return {
|
|
84
|
+
loopId: opts.loopId || '',
|
|
85
|
+
iteration: (typeof opts.iteration === 'number') ? opts.iteration : 0,
|
|
86
|
+
phases: Array.isArray(opts.phaseTimings) ? opts.phaseTimings.slice() : [],
|
|
87
|
+
executor: opts.executorTrace || null,
|
|
88
|
+
dispatchedWp: opts.dispatchedWp || null,
|
|
89
|
+
verdict: opts.verdict || null,
|
|
90
|
+
timestamp: new Date().toISOString(),
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ---------------------------------------------------------------------------
|
|
95
|
+
// 一行式阶段摘要(driver stdout 用)
|
|
96
|
+
// ---------------------------------------------------------------------------
|
|
97
|
+
|
|
98
|
+
var PHASE_LABEL = {
|
|
99
|
+
observe: 'Observe',
|
|
100
|
+
think: 'Think',
|
|
101
|
+
act: 'Act',
|
|
102
|
+
reflect: 'Reflect',
|
|
103
|
+
decide: 'Decide',
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
// 五段式固定顺序(即便 phaseTimings 缺某段也按序占位,让用户「看见五段式在跑」)
|
|
107
|
+
var PHASE_ORDER = ['observe', 'think', 'act', 'reflect', 'decide'];
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 渲染一行式阶段摘要:`[iter 3] Observe 12ms · Think 1ms · Act 48023ms · Reflect 3ms · Decide 1ms → dispatch WP-XXX`
|
|
111
|
+
*
|
|
112
|
+
* Act 段耗时合并(WP-196 后续修复):engine step() 的 `timePhase('act')` 只包裹
|
|
113
|
+
* `factoryApi.act()`(产生 dispatch 决策,毫秒级),真正的 `executor.run()`(spawn
|
|
114
|
+
* claude/glm,单轮可达数十秒~数分钟)由 driver 在 step() 返回**之后**调用(loop.js:808),
|
|
115
|
+
* 不在 engine act timePhase 计时内。若只渲染 act.elapsedMs,stdout 会打出 `Act 4ms`
|
|
116
|
+
* 这种掩盖单轮 90%+ 真实 spawn 开销的误导性假象——这正是用户「感觉不是五段式」的真因之一:
|
|
117
|
+
* 五段计时漏掉了唯一真正耗时的 Act 内部 spawn(实测一轮 act.elapsedMs=4ms 但
|
|
118
|
+
* executor.spawnMs=90754ms,99.87% 耗时隐形)。
|
|
119
|
+
*
|
|
120
|
+
* 故当 roundRecord.executor.spawnMs 为 number 时,把它并入 Act 显示
|
|
121
|
+
* (engine act 决策 + driver executor 执行 = 真实 Act 总耗时);executor 缺失
|
|
122
|
+
* (noop 轮 / local executor)或 spawnMs 非 number 时,保持原行为仅显示 act.elapsedMs。
|
|
123
|
+
*
|
|
124
|
+
* 缺失阶段显示 `-`;verdict/dispatchedWp 缺失时省略后缀。
|
|
125
|
+
* @param {object} roundRecord(buildRoundRecord 产出)
|
|
126
|
+
* @returns {string}
|
|
127
|
+
*/
|
|
128
|
+
function renderOneLine(roundRecord) {
|
|
129
|
+
roundRecord = roundRecord || {};
|
|
130
|
+
var iter = (typeof roundRecord.iteration === 'number') ? roundRecord.iteration : '?';
|
|
131
|
+
// 按 phase 名建索引取 elapsedMs
|
|
132
|
+
var byName = {};
|
|
133
|
+
var phases = Array.isArray(roundRecord.phases) ? roundRecord.phases : [];
|
|
134
|
+
for (var i = 0; i < phases.length; i++) {
|
|
135
|
+
var p = phases[i];
|
|
136
|
+
if (p && p.phase) byName[p.phase] = p;
|
|
137
|
+
}
|
|
138
|
+
// executor spawn 耗时(driver 层 executor.run 产生,不在 engine act timePhase 内)。
|
|
139
|
+
// 存在时并入 Act 段,避免 stdout 的 Act 只反映毫秒级决策、掩盖数十秒的真实 spawn。
|
|
140
|
+
var execSpawnMs = (roundRecord.executor && typeof roundRecord.executor.spawnMs === 'number')
|
|
141
|
+
? roundRecord.executor.spawnMs : null;
|
|
142
|
+
var parts = [];
|
|
143
|
+
for (var j = 0; j < PHASE_ORDER.length; j++) {
|
|
144
|
+
var name = PHASE_ORDER[j];
|
|
145
|
+
var label = PHASE_LABEL[name] || name;
|
|
146
|
+
var entry = byName[name];
|
|
147
|
+
var ms = (entry && typeof entry.elapsedMs === 'number') ? entry.elapsedMs : null;
|
|
148
|
+
// Act 段:engine act 决策耗时(ms) + driver executor spawn 耗时(execSpawnMs) = 真实 Act 总耗时
|
|
149
|
+
if (name === 'act' && execSpawnMs !== null) {
|
|
150
|
+
var combined = (ms !== null ? ms : 0) + execSpawnMs;
|
|
151
|
+
parts.push(label + ' ' + combined + 'ms');
|
|
152
|
+
} else {
|
|
153
|
+
parts.push(label + ' ' + (ms !== null ? ms + 'ms' : '-'));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
var line = '[iter ' + iter + '] ' + parts.join(' · ');
|
|
157
|
+
// token-usage:五段后追加紧凑端点元数据后缀(仅当 executor 提取到时显示,缺失不显示,
|
|
158
|
+
// 保持五段式视觉焦点)。承袭 WP-196 纪律——纯观测叠加,try/catch 降级不影响渲染。
|
|
159
|
+
try {
|
|
160
|
+
var exec = roundRecord.executor || {};
|
|
161
|
+
var ep = exec.endpointMs || {};
|
|
162
|
+
var tu = exec.tokenUsage || {};
|
|
163
|
+
var suffixParts = [];
|
|
164
|
+
if (typeof ep.ttft === 'number') suffixParts.push('TTFT ' + ep.ttft + 'ms');
|
|
165
|
+
if (typeof tu.input === 'number' || typeof tu.output === 'number') {
|
|
166
|
+
var inTok = (typeof tu.input === 'number') ? tu.input : '?';
|
|
167
|
+
var outTok = (typeof tu.output === 'number') ? tu.output : '?';
|
|
168
|
+
suffixParts.push('tok ' + inTok + '→' + outTok);
|
|
169
|
+
}
|
|
170
|
+
if (suffixParts.length) line += ' · ' + suffixParts.join(' · ');
|
|
171
|
+
} catch (_se) { /* 后缀降级:忽略 */ }
|
|
172
|
+
if (roundRecord.dispatchedWp) {
|
|
173
|
+
line += ' → dispatch ' + roundRecord.dispatchedWp;
|
|
174
|
+
} else if (roundRecord.verdict && roundRecord.verdict !== 'continue') {
|
|
175
|
+
line += ' → ' + roundRecord.verdict;
|
|
176
|
+
}
|
|
177
|
+
return line;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
// ---------------------------------------------------------------------------
|
|
181
|
+
// JSONL 落盘(IO,全 try/catch 降级)
|
|
182
|
+
// ---------------------------------------------------------------------------
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* 追加一个 round record 到 trace.jsonl(JSON Lines,每行一个 JSON)。
|
|
186
|
+
* 目录不存在则递归创建;写入失败 try/catch 降级返回 false,不抛异常。
|
|
187
|
+
*
|
|
188
|
+
* @param {string} tracePath trace.jsonl 绝对路径(resolveTracePath 产出)
|
|
189
|
+
* @param {object} roundRecord buildRoundRecord 产出
|
|
190
|
+
* @returns {boolean} true=写入成功,false=降级(写入失败)
|
|
191
|
+
*/
|
|
192
|
+
function appendTrace(tracePath, roundRecord) {
|
|
193
|
+
try {
|
|
194
|
+
var dir = path.dirname(tracePath);
|
|
195
|
+
try {
|
|
196
|
+
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
197
|
+
} catch (_me) { /* 目录创建失败降级 */ }
|
|
198
|
+
var line = JSON.stringify(roundRecord) + '\n';
|
|
199
|
+
fs.appendFileSync(tracePath, line, { encoding: 'utf8' });
|
|
200
|
+
return true;
|
|
201
|
+
} catch (e) {
|
|
202
|
+
// 降级:观测落盘失败绝不阻断 loop 主流程(承袭 WP-191 心跳降级纪律)
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* 读取并解析 trace.jsonl(供 verify/回放测试用)。
|
|
209
|
+
* 损坏行跳过(不抛),返回有效 record 数组。
|
|
210
|
+
* @param {string} tracePath
|
|
211
|
+
* @returns {Array<object>}
|
|
212
|
+
*/
|
|
213
|
+
function readTrace(tracePath) {
|
|
214
|
+
try {
|
|
215
|
+
if (!fs.existsSync(tracePath)) return [];
|
|
216
|
+
var content = fs.readFileSync(tracePath, { encoding: 'utf8' });
|
|
217
|
+
var lines = content.split('\n');
|
|
218
|
+
var out = [];
|
|
219
|
+
for (var i = 0; i < lines.length; i++) {
|
|
220
|
+
var line = lines[i];
|
|
221
|
+
if (!line || !line.trim()) continue;
|
|
222
|
+
try {
|
|
223
|
+
out.push(JSON.parse(line));
|
|
224
|
+
} catch (_pe) { /* 跳过损坏行 */ }
|
|
225
|
+
}
|
|
226
|
+
return out;
|
|
227
|
+
} catch (_e) {
|
|
228
|
+
return [];
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
module.exports = {
|
|
233
|
+
resolveTracePath: resolveTracePath,
|
|
234
|
+
buildRoundRecord: buildRoundRecord,
|
|
235
|
+
renderOneLine: renderOneLine,
|
|
236
|
+
appendTrace: appendTrace,
|
|
237
|
+
readTrace: readTrace,
|
|
238
|
+
// 暴露内部工具便于单元测试
|
|
239
|
+
_detectProjectRoot: _detectProjectRoot,
|
|
240
|
+
_PHASE_ORDER: PHASE_ORDER,
|
|
241
|
+
_PHASE_LABEL: PHASE_LABEL,
|
|
242
|
+
};
|
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loop Worktree — per-WP git worktree 隔离管理器(concurrent-dispatch Step 2)
|
|
3
|
+
*
|
|
4
|
+
* @module loop-worktree
|
|
5
|
+
*
|
|
6
|
+
* 背景(docs/reports/2026-07-01_step2-follow-up-worktree-isolation.md):
|
|
7
|
+
* v0.4.0 的 --concurrency=N(N>1)并发批调度存在已知限制:executor.run 内的
|
|
8
|
+
* readWorktreeDirty 共用单一 config.projectRoot,批内 N 个 spawn 并发改同一工作树,
|
|
9
|
+
* dirtyBefore/dirtyAfter 互相污染 → noProgress 信号在批模式失真(退化为批级而非 per-WP)。
|
|
10
|
+
* 本模块为每个并发 dispatch 的 WP 创建独立 git worktree,executor.run 在各自 cwd 跑,
|
|
11
|
+
* 使脏度检测 per-WP 准确、互不串扰。
|
|
12
|
+
*
|
|
13
|
+
* 合并策略(用户选定,文档 §5.3 问题1 = 策略 A):
|
|
14
|
+
* 每 WP 独立分支(doukui/{loopId}/{wpId})→ 批后逐个 cherry-pick 回主分支。
|
|
15
|
+
* 冲突时 git cherry-pick --abort、记 conflict(交 driver 报失败项,engine retry/resplit 兜底),
|
|
16
|
+
* 不阻断 loop 主流程。
|
|
17
|
+
*
|
|
18
|
+
* 生命周期(driver 调用约定):
|
|
19
|
+
* 批前:每 WP createWorktreeForWp() → 拿到独立 wtPath
|
|
20
|
+
* dispatchBatch:executor.run 的 pendingAction.projectRoot = wtPath(per-call override)
|
|
21
|
+
* 批后串行回填:每 WP mergeWorktreeBranch()(含冲突检测)→ removeWorktree()
|
|
22
|
+
*
|
|
23
|
+
* 容错纪律(承袭 WP-191/196):
|
|
24
|
+
* - 非 git 仓库 / git 不可用 / wpId 非法 / worktree add 失败 → 降级返回 { degraded:true, wtPath:null },
|
|
25
|
+
* driver 不注入 override(executor 退回 config.projectRoot = 批级 noProgress,等同 v0.4.0 行为)
|
|
26
|
+
* - 任何 git 调用失败绝不抛出阻断 loop;全程 try/catch 降级
|
|
27
|
+
*
|
|
28
|
+
* 可测性(codebase DI-over-mocking 哲学,见 executor-claude / loop-dispatch-batch):
|
|
29
|
+
* - git 操作通过注入的 execFn(默认 child_process.execFileSync)执行,测试传 fake 不真跑 git
|
|
30
|
+
* - 真实 git worktree 端到端单测走临时 repo(test/runtime/test-loop-worktree.js)
|
|
31
|
+
*
|
|
32
|
+
* 路径安全(复用 safe-path):
|
|
33
|
+
* - wpId / loopId 经 safePath.validateSafeName 消毒,防路径注入(拼进 .doukui/wt-{loopId}-{wpId})
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
'use strict';
|
|
37
|
+
|
|
38
|
+
var path = require('path');
|
|
39
|
+
var fs = require('fs');
|
|
40
|
+
var safePath = require('./safe-path');
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 默认 worktree 落盘根(相对 repoRoot;已被 .gitignore 覆盖)。
|
|
44
|
+
* 落盘到 .doukui/ 子树不入 git diff 视野(.gitignore line 11),符合文档 §5.2 提议。
|
|
45
|
+
*/
|
|
46
|
+
var DEFAULT_WORKTREES_DIRNAME = '.doukui';
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* worktree 分支名前缀(doukui/{loopId}/{wpId})。
|
|
50
|
+
* 前缀 `doukui/` 命名空间隔离,避免与用户既有分支冲突。
|
|
51
|
+
*/
|
|
52
|
+
var BRANCH_PREFIX = 'doukui';
|
|
53
|
+
|
|
54
|
+
// ---------------------------------------------------------------------------
|
|
55
|
+
// 内部工具
|
|
56
|
+
// ---------------------------------------------------------------------------
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* 同步执行 git 子命令的封装(统一异常归一化)。
|
|
60
|
+
* @param {Function} execFn (cmd, args, opts) => string;注入用,默认 execFileSync
|
|
61
|
+
* @param {string} cwd 工作目录
|
|
62
|
+
* @param {string[]} args git 参数(不含 'git' 前缀)
|
|
63
|
+
* @returns {{ok:true,out:string}|{ok:false,err:Error}}
|
|
64
|
+
*/
|
|
65
|
+
function git(execFn, cwd, args) {
|
|
66
|
+
try {
|
|
67
|
+
var out = execFn('git', args, {
|
|
68
|
+
cwd: cwd,
|
|
69
|
+
encoding: 'utf8',
|
|
70
|
+
timeout: 10000, // worktree 操作放宽到 10s(add/merge 可能较慢)
|
|
71
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
72
|
+
});
|
|
73
|
+
return { ok: true, out: String(out || '') };
|
|
74
|
+
} catch (e) {
|
|
75
|
+
return { ok: false, err: e };
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* 校验 repoRoot 是否恰为某 git 仓库的 toplevel(不是其子目录、不是普通目录)。
|
|
81
|
+
* 设计意图(必须保留):git rev-parse 会向上递归找父级 .git,若 repoRoot 落在某个上层
|
|
82
|
+
* git 仓库内(如 os.tmpdir() 在用户家目录 git 仓库内),仅判"git 是否能跑"会误判为仓库。
|
|
83
|
+
* 须进一步确认 repoRoot 自身就是 toplevel,而非父仓库的子目录。
|
|
84
|
+
*
|
|
85
|
+
* 实现关键(CI Windows 根因修复,WP follow-up):
|
|
86
|
+
* 旧实现用 path.relative(realpathSync(top), realpathSync(repoRoot)) === '' 做字符串比对。
|
|
87
|
+
* 但 CI Windows runner 的 os.tmpdir() 返回 8.3 短名(C:\Users\RUNNER~1\...,长名 runneradmin),
|
|
88
|
+
* mkdtempSync 产生的 repoRoot 含 RUNNER~1,而 git rev-parse --show-toplevel 返回长名 runneradmin。
|
|
89
|
+
* node 18/20 的 fs.realpathSync(JS 实现)在 Windows 上**不解析 8.3 短名**,两路 realpathSync
|
|
90
|
+
* 仍分别带 RUNNER~1 / runneradmin → path.relative 非空 → 误判 false(macos/ubuntu 无此问题)。
|
|
91
|
+
*
|
|
92
|
+
* 新方案彻底绕开 node 路径规范化与字符串比对,改由 git 自身作答:
|
|
93
|
+
* git rev-parse --show-toplevel --show-cdup
|
|
94
|
+
* 一次调用得两行输出(均相对同一 cwd,无跨字符串比较):
|
|
95
|
+
* - toplevel 非空:确为某 git 仓库的工作树(普通目录外 → git 退出码 128 → !r.ok → false);
|
|
96
|
+
* - cdup === ''(空串):cwd 距 toplevel 的相对路径为空 → cwd 即 toplevel(恰在仓库根);
|
|
97
|
+
* cdup 形如 '../' / '../../' 表示 cwd 在 toplevel 子目录内 → 父级仓库误判防护命中 → false。
|
|
98
|
+
* git 内部对 cwd 的解析与对 toplevel 的解析口径一致,不引入 node realpathSync 的短名盲区,
|
|
99
|
+
* 且天然兼容 worktree(.git 为文件)/ 大小写不敏感 FS / 符号链接(git 自行 resolve,不经 node)。
|
|
100
|
+
* @param {Function} execFn
|
|
101
|
+
* @param {string} repoRoot
|
|
102
|
+
* @returns {boolean}
|
|
103
|
+
*/
|
|
104
|
+
function isGitRepo(execFn, repoRoot) {
|
|
105
|
+
// 单次 git 调用同取 toplevel + cdup(相对同一 cwd,规避跨字符串路径比较的短名陷阱)
|
|
106
|
+
var r = git(execFn, repoRoot, ['rev-parse', '--show-toplevel', '--show-cdup']);
|
|
107
|
+
if (!r.ok) return false; // 非 git 仓库 / git 不可用 / 不在工作树内
|
|
108
|
+
var lines = r.out.split(/\r?\n/);
|
|
109
|
+
var top = lines[0] ? lines[0].trim() : '';
|
|
110
|
+
var cdup = lines[1] ? lines[1].trim() : '';
|
|
111
|
+
if (!top) return false; // 无 toplevel → 非工作树(如 bare repo / 异常)
|
|
112
|
+
// 防御:toplevel 须形似绝对路径(含路径分隔符),杜绝退化输入(裸 cdup 行如 '../')被当 toplevel。
|
|
113
|
+
// 正常 git exit-0 路径下 toplevel 必为非空绝对路径,此断言永不误杀;异常输出时 fail-safe 返 false。
|
|
114
|
+
if (top.indexOf('/') === -1 && top.indexOf('\\') === -1) return false;
|
|
115
|
+
// cdup 空串 ⇔ cwd 即 toplevel;非空('../' 等)⇔ repoRoot 落在父仓库子目录内 → 误判防护
|
|
116
|
+
return cdup === '';
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* 读取 repoRoot 当前 HEAD 提交 sha(cherry-pick base 用)。
|
|
121
|
+
* @param {Function} execFn
|
|
122
|
+
* @param {string} repoRoot
|
|
123
|
+
* @returns {string|null} sha;失败 null
|
|
124
|
+
*/
|
|
125
|
+
function readHeadSha(execFn, repoRoot) {
|
|
126
|
+
var r = git(execFn, repoRoot, ['rev-parse', 'HEAD']);
|
|
127
|
+
if (!r.ok) return null;
|
|
128
|
+
var sha = r.out.trim();
|
|
129
|
+
return sha.length > 0 ? sha : null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 读取 repoRoot 当前分支名(worktree base 用)。
|
|
134
|
+
* 处于 detached HEAD 时返回 HEAD sha(作为 base 仍有效)。
|
|
135
|
+
* @param {Function} execFn
|
|
136
|
+
* @param {string} repoRoot
|
|
137
|
+
* @returns {string|null}
|
|
138
|
+
*/
|
|
139
|
+
function readCurrentBranch(execFn, repoRoot) {
|
|
140
|
+
var r = git(execFn, repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
141
|
+
if (!r.ok) return null;
|
|
142
|
+
var branch = r.out.trim();
|
|
143
|
+
if (!branch || branch === 'HEAD') {
|
|
144
|
+
// detached HEAD:用 sha 作 base
|
|
145
|
+
return readHeadSha(execFn, repoRoot);
|
|
146
|
+
}
|
|
147
|
+
return branch;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// ---------------------------------------------------------------------------
|
|
151
|
+
// 公开 API
|
|
152
|
+
// ---------------------------------------------------------------------------
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* 为单个 WP 创建独立 git worktree(策略 A:每 WP 独立分支)。
|
|
156
|
+
*
|
|
157
|
+
* 执行:`git worktree add <wtPath> -b doukui/{loopId}/{wpId} [<baseBranch>]`
|
|
158
|
+
* 落盘:wtPath = path.join(worktreesDir, 'wt-{loopId}-{wpId}')
|
|
159
|
+
*
|
|
160
|
+
* 降级条件(任一 → 返回 {degraded:true, wtPath:null},driver 不注入 override):
|
|
161
|
+
* - repoRoot 非 git 仓库 / git 不可用
|
|
162
|
+
* - loopId 或 wpId 非法(safe-path 校验失败)
|
|
163
|
+
* - worktree add 失败(如分支已存在、磁盘满)
|
|
164
|
+
*
|
|
165
|
+
* @param {object} opts
|
|
166
|
+
* @param {string} opts.repoRoot 真实 git 仓库根(loop.js:533 chdir 前解析的 projectRoot)
|
|
167
|
+
* @param {string} opts.loopId loop 标识
|
|
168
|
+
* @param {string} opts.wpId WP 标识
|
|
169
|
+
* @param {string} [opts.baseBranch] worktree 起点;缺省用 repo 当前分支/HEAD
|
|
170
|
+
* @param {string} [opts.worktreesDir] worktree 落盘根;缺省 path.join(repoRoot, '.doukui')
|
|
171
|
+
* @param {Function} [opts.execFn] git 执行函数注入(测试用);默认 execFileSync
|
|
172
|
+
* @returns {{wtPath:string, branch:string, degraded:false} |
|
|
173
|
+
* {wtPath:null, branch:null, degraded:true, reason:string}}
|
|
174
|
+
*/
|
|
175
|
+
function createWorktreeForWp(opts) {
|
|
176
|
+
opts = opts || {};
|
|
177
|
+
var repoRoot = opts.repoRoot;
|
|
178
|
+
var loopId = opts.loopId;
|
|
179
|
+
var wpId = opts.wpId;
|
|
180
|
+
var execFn = typeof opts.execFn === 'function'
|
|
181
|
+
? opts.execFn
|
|
182
|
+
: function () { var cp = require('child_process'); return cp.execFileSync.apply(cp, arguments); };
|
|
183
|
+
|
|
184
|
+
// 参数校验(路径安全:loopId/wpId 拼进文件路径与分支名,必须消毒)
|
|
185
|
+
if (!repoRoot || typeof repoRoot !== 'string') {
|
|
186
|
+
return { wtPath: null, branch: null, degraded: true, reason: 'invalid_repoRoot' };
|
|
187
|
+
}
|
|
188
|
+
var loopIdCheck = safePath.validateSafeName(loopId);
|
|
189
|
+
if (!loopIdCheck.ok) {
|
|
190
|
+
return { wtPath: null, branch: null, degraded: true, reason: 'invalid_loopId:' + loopIdCheck.reason };
|
|
191
|
+
}
|
|
192
|
+
var wpIdCheck = safePath.validateSafeName(wpId);
|
|
193
|
+
if (!wpIdCheck.ok) {
|
|
194
|
+
return { wtPath: null, branch: null, degraded: true, reason: 'invalid_wpId:' + wpIdCheck.reason };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// 非 git 仓库降级
|
|
198
|
+
if (!isGitRepo(execFn, repoRoot)) {
|
|
199
|
+
return { wtPath: null, branch: null, degraded: true, reason: 'not_a_git_repo' };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// 解析 base 分支(缺省用当前分支 / detached HEAD 的 sha)
|
|
203
|
+
var baseBranch = opts.baseBranch;
|
|
204
|
+
if (!baseBranch) {
|
|
205
|
+
baseBranch = readCurrentBranch(execFn, repoRoot);
|
|
206
|
+
if (!baseBranch) {
|
|
207
|
+
return { wtPath: null, branch: null, degraded: true, reason: 'cannot_resolve_base' };
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// 落盘路径与分支名
|
|
212
|
+
var worktreesDir = opts.worktreesDir || path.join(repoRoot, DEFAULT_WORKTREES_DIRNAME);
|
|
213
|
+
var wtPath = path.join(worktreesDir, 'wt-' + loopId + '-' + wpId);
|
|
214
|
+
var branch = BRANCH_PREFIX + '/' + loopId + '/' + wpId;
|
|
215
|
+
|
|
216
|
+
// 确保 worktreesDir 存在(git worktree add 不自动建父目录到任意深度)
|
|
217
|
+
try {
|
|
218
|
+
if (!fs.existsSync(worktreesDir)) fs.mkdirSync(worktreesDir, { recursive: true });
|
|
219
|
+
} catch (_e) {
|
|
220
|
+
return { wtPath: null, branch: null, degraded: true, reason: 'cannot_mkdir_worktreesDir' };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// 已存在同名 worktree/分支:先清理残留(幂等,承袭 appendProgressLine 幂等思路)。
|
|
224
|
+
// 顺序关键:必须**先 worktree remove 再 branch -D**——分支若被某 worktree 检出,
|
|
225
|
+
// git branch -D 会失败("branch is checked out")。worktree remove 释放检出后才能删分支。
|
|
226
|
+
// 已存在 wtPath 目录:清理(防上次异常残留)
|
|
227
|
+
try {
|
|
228
|
+
if (fs.existsSync(wtPath)) {
|
|
229
|
+
// 先尝试 git worktree remove(登记表清理 + 释放分支检出),失败再物理删
|
|
230
|
+
git(execFn, repoRoot, ['worktree', 'remove', '--force', wtPath]);
|
|
231
|
+
if (fs.existsSync(wtPath)) fs.rmSync(wtPath, { recursive: true, force: true });
|
|
232
|
+
}
|
|
233
|
+
} catch (_e) { /* best-effort */ }
|
|
234
|
+
// 分支已存在 → -b 会失败;worktree 已 remove 后再删分支(best-effort)
|
|
235
|
+
var existingBranch = git(execFn, repoRoot, ['rev-parse', '--verify', branch]);
|
|
236
|
+
if (existingBranch.ok) {
|
|
237
|
+
git(execFn, repoRoot, ['branch', '-D', branch]); // best-effort,失败由 add 报错兜底
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// 创建 worktree + 分支
|
|
241
|
+
var addArgs = ['worktree', 'add', wtPath, '-b', branch];
|
|
242
|
+
if (baseBranch) addArgs.push(baseBranch);
|
|
243
|
+
var addRes = git(execFn, repoRoot, addArgs);
|
|
244
|
+
if (!addRes.ok) {
|
|
245
|
+
return { wtPath: null, branch: null, degraded: true, reason: 'worktree_add_failed' };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// 防御性校验:wtPath 确实生成
|
|
249
|
+
if (!fs.existsSync(wtPath)) {
|
|
250
|
+
return { wtPath: null, branch: null, degraded: true, reason: 'wtPath_not_created' };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return { wtPath: wtPath, branch: branch, degraded: false };
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* 把 WP worktree 分支的改动 cherry-pick 回主分支(策略 A 合并)。
|
|
258
|
+
*
|
|
259
|
+
* 在 repoRoot(主工作树)执行:`git cherry-pick <branch>`。
|
|
260
|
+
* 冲突 → `git cherry-pick --abort`,返回 {conflict:true}(driver 记失败项,不阻断 loop)。
|
|
261
|
+
* 分支无新提交(WP 未改代码或未 commit)→ 视为无改动,{merged:false, conflict:false}。
|
|
262
|
+
*
|
|
263
|
+
* 注意:本函数假设 WP 在 worktree 内的改动已 commit 到其分支。
|
|
264
|
+
* claude 子进程只改工作树不自动 commit;driver 在调用本函数前需先在 wtPath 内
|
|
265
|
+
* `git add -A && git commit`(见 driver 接线),否则 cherry-pick 无提交可拾取。
|
|
266
|
+
* 若 WP 未 commit,本函数的"无新提交"分支返回 merged:false,driver 据此判 noProgress。
|
|
267
|
+
*
|
|
268
|
+
* @param {object} opts
|
|
269
|
+
* @param {string} opts.repoRoot 真实 git 仓库根(主工作树)
|
|
270
|
+
* @param {string} opts.branch 要合并的 WP 分支(doukui/{loopId}/{wpId})
|
|
271
|
+
* @param {string} [opts.wpId] 仅日志/诊断用
|
|
272
|
+
* @param {Function} [opts.execFn] git 执行函数注入(测试用)
|
|
273
|
+
* @returns {{merged:boolean, conflict:boolean, degraded:boolean, reason?:string}}
|
|
274
|
+
*/
|
|
275
|
+
function mergeWorktreeBranch(opts) {
|
|
276
|
+
opts = opts || {};
|
|
277
|
+
var repoRoot = opts.repoRoot;
|
|
278
|
+
var branch = opts.branch;
|
|
279
|
+
var execFn = typeof opts.execFn === 'function'
|
|
280
|
+
? opts.execFn
|
|
281
|
+
: function () { var cp = require('child_process'); return cp.execFileSync.apply(cp, arguments); };
|
|
282
|
+
|
|
283
|
+
if (!repoRoot || typeof repoRoot !== 'string' || !branch || typeof branch !== 'string') {
|
|
284
|
+
return { merged: false, conflict: false, degraded: true, reason: 'invalid_args' };
|
|
285
|
+
}
|
|
286
|
+
if (!isGitRepo(execFn, repoRoot)) {
|
|
287
|
+
return { merged: false, conflict: false, degraded: true, reason: 'not_a_git_repo' };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// 主工作树须 clean 才能 cherry-pick(git 强制要求);dirty 则先 stash 保护(best-effort)
|
|
291
|
+
// 注:批内串行回填阶段,主工作树理论 clean(改动在各 worktree),但防御性 stash 兜底。
|
|
292
|
+
var dirtyCheck = git(execFn, repoRoot, ['status', '--porcelain']);
|
|
293
|
+
var stashed = false;
|
|
294
|
+
if (dirtyCheck.ok && dirtyCheck.out.trim().length > 0) {
|
|
295
|
+
var stashRes = git(execFn, repoRoot, ['stash', 'push', '--include-untracked']);
|
|
296
|
+
stashed = stashRes.ok;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
try {
|
|
300
|
+
// 分支是否有新提交(相对 HEAD):无则跳过 cherry-pick(WP 未改/未 commit)
|
|
301
|
+
var logRes = git(execFn, repoRoot, ['rev-list', '--count', 'HEAD..' + branch]);
|
|
302
|
+
if (logRes.ok) {
|
|
303
|
+
var count = parseInt(logRes.out.trim(), 10);
|
|
304
|
+
if (isNaN(count) || count === 0) {
|
|
305
|
+
// 无新提交:WP 未产出代码改动(与 noProgress 信号一致),不合并
|
|
306
|
+
return { merged: false, conflict: false, degraded: false };
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
// 分支不存在(已被删/降级路径):跳过
|
|
310
|
+
var verifyRes = git(execFn, repoRoot, ['rev-parse', '--verify', branch]);
|
|
311
|
+
if (!verifyRes.ok) {
|
|
312
|
+
return { merged: false, conflict: false, degraded: true, reason: 'branch_not_found' };
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// cherry-pick:冲突时退出码非 0 + stderr 含 conflict 标记
|
|
316
|
+
var pickRes = git(execFn, repoRoot, ['cherry-pick', branch]);
|
|
317
|
+
if (pickRes.ok) {
|
|
318
|
+
return { merged: true, conflict: false, degraded: false };
|
|
319
|
+
}
|
|
320
|
+
// 失败:判定是否冲突(cherry-pick 冲突会留下未完成状态,必须 abort)
|
|
321
|
+
var conflictRes = git(execFn, repoRoot, ['diff', '--name-only', '--diff-filter=U']);
|
|
322
|
+
var isConflict = conflictRes.ok && conflictRes.out.trim().length > 0;
|
|
323
|
+
// 无论是否冲突,cherry-pick 失败都 abort 回到 clean 状态(防遗留 sequencer 状态卡住后续)
|
|
324
|
+
git(execFn, repoRoot, ['cherry-pick', '--abort']); // best-effort
|
|
325
|
+
return {
|
|
326
|
+
merged: false,
|
|
327
|
+
conflict: isConflict,
|
|
328
|
+
degraded: !isConflict, // 非冲突的失败算降级(如锁文件、权限)
|
|
329
|
+
reason: isConflict ? 'merge_conflict' : 'cherry_pick_failed',
|
|
330
|
+
};
|
|
331
|
+
} finally {
|
|
332
|
+
// 还原 stash(仅当之前 stash 过)
|
|
333
|
+
if (stashed) {
|
|
334
|
+
git(execFn, repoRoot, ['stash', 'pop']); // best-effort,pop 冲突由用户后续处理
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* 清理 WP worktree + 分支(批后收尾,best-effort)。
|
|
341
|
+
*
|
|
342
|
+
* 执行:`git worktree remove --force <wtPath>` + `git branch -D <branch>`。
|
|
343
|
+
* 全程 try/catch:清理失败绝不阻断 loop(残留 worktree 在 .doukui/ 已 gitignored,
|
|
344
|
+
* 不污染 repo,下次 createWorktreeForWp 的幂等清理会兜底)。
|
|
345
|
+
*
|
|
346
|
+
* @param {object} opts
|
|
347
|
+
* @param {string} opts.repoRoot
|
|
348
|
+
* @param {string} [opts.wtPath] worktree 路径(可能 null,降级路径)
|
|
349
|
+
* @param {string} [opts.branch] 分支名(可能 null)
|
|
350
|
+
* @param {Function} [opts.execFn] git 执行函数注入(测试用)
|
|
351
|
+
* @returns {{cleaned:boolean}} 至少一项成功即 cleaned:true
|
|
352
|
+
*/
|
|
353
|
+
function removeWorktree(opts) {
|
|
354
|
+
opts = opts || {};
|
|
355
|
+
var repoRoot = opts.repoRoot;
|
|
356
|
+
var wtPath = opts.wtPath;
|
|
357
|
+
var branch = opts.branch;
|
|
358
|
+
var execFn = typeof opts.execFn === 'function'
|
|
359
|
+
? opts.execFn
|
|
360
|
+
: function () { var cp = require('child_process'); return cp.execFileSync.apply(cp, arguments); };
|
|
361
|
+
|
|
362
|
+
var cleaned = false;
|
|
363
|
+
|
|
364
|
+
if (!repoRoot || typeof repoRoot !== 'string') {
|
|
365
|
+
return { cleaned: false };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
// 1. worktree remove(git 登记表清理)
|
|
369
|
+
if (wtPath && isGitRepo(execFn, repoRoot)) {
|
|
370
|
+
var rmRes = git(execFn, repoRoot, ['worktree', 'remove', '--force', wtPath]);
|
|
371
|
+
if (rmRes.ok) cleaned = true;
|
|
372
|
+
}
|
|
373
|
+
// 1b. worktree remove 失败/降级:物理删 wtPath 目录(防残留)
|
|
374
|
+
if (wtPath) {
|
|
375
|
+
try {
|
|
376
|
+
if (fs.existsSync(wtPath)) fs.rmSync(wtPath, { recursive: true, force: true });
|
|
377
|
+
} catch (_e) { /* best-effort */ }
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// 2. branch -D(分支清理)
|
|
381
|
+
if (branch && isGitRepo(execFn, repoRoot)) {
|
|
382
|
+
var brRes = git(execFn, repoRoot, ['branch', '-D', branch]);
|
|
383
|
+
if (brRes.ok) cleaned = true;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// 3. git worktree prune(清理已删目录的过期登记,防 git worktree list 累积)
|
|
387
|
+
if (isGitRepo(execFn, repoRoot)) {
|
|
388
|
+
git(execFn, repoRoot, ['worktree', 'prune']); // best-effort
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
return { cleaned: cleaned };
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
module.exports = {
|
|
395
|
+
createWorktreeForWp: createWorktreeForWp,
|
|
396
|
+
mergeWorktreeBranch: mergeWorktreeBranch,
|
|
397
|
+
removeWorktree: removeWorktree,
|
|
398
|
+
// 暴露内部工具便于单元测试
|
|
399
|
+
_isGitRepo: isGitRepo,
|
|
400
|
+
_readHeadSha: readHeadSha,
|
|
401
|
+
_readCurrentBranch: readCurrentBranch,
|
|
402
|
+
_DEFAULT_WORKTREES_DIRNAME: DEFAULT_WORKTREES_DIRNAME,
|
|
403
|
+
_BRANCH_PREFIX: BRANCH_PREFIX,
|
|
404
|
+
};
|