dsh-harness-kit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +321 -2
- package/README.zh-CN.md +278 -0
- package/client.js +1272 -0
- package/cordis.patch.yml +4 -0
- package/docs/DETAIL.en.md +97 -0
- package/docs/DETAIL.md +73 -0
- package/docs/assets/ui-new-task.png +0 -0
- package/docs/assets/ui-onboarding.png +0 -0
- package/docs/assets/ui-war-room.png +0 -0
- package/icon.svg +7 -0
- package/index.js +49 -0
- package/kernel/advance.js +96 -0
- package/kernel/bindings.js +24 -0
- package/kernel/commands.js +927 -0
- package/kernel/env.js +64 -0
- package/kernel/exec.js +41 -0
- package/kernel/flows.js +89 -0
- package/kernel/guards.js +79 -0
- package/kernel/miniyaml.js +133 -0
- package/kernel/models.js +104 -0
- package/kernel/panel.js +1103 -0
- package/kernel/paths.js +53 -0
- package/kernel/roles.js +67 -0
- package/kernel/setup.js +644 -0
- package/kernel/state.js +59 -0
- package/kernel/steer.js +27 -0
- package/kernel/sync.js +140 -0
- package/kernel/te.js +122 -0
- package/kernel/worktree.js +868 -0
- package/locale/en.json +14 -0
- package/locale/zh.json +14 -0
- package/package.json +63 -4
- package/packs/ai-coding/agents/business-analyst.md +90 -0
- package/packs/ai-coding/agents/code-reviewer.md +156 -0
- package/packs/ai-coding/agents/developer.md +147 -0
- package/packs/ai-coding/agents/project-manager.md +190 -0
- package/packs/ai-coding/agents/readiness-reviewer.md +123 -0
- package/packs/ai-coding/agents/solution-architect.md +122 -0
- package/packs/ai-coding/agents/test-engineer.md +230 -0
- package/packs/ai-coding/assets/scripts/check_codegraph.py +215 -0
- package/packs/ai-coding/assets/scripts/codebase_guide_init.py +330 -0
- package/packs/ai-coding/assets/scripts/env_auto.py +612 -0
- package/packs/ai-coding/assets/scripts/harness.py +38 -0
- package/packs/ai-coding/assets/scripts/harness_init.py +193 -0
- package/packs/ai-coding/assets/scripts/lib.py +1011 -0
- package/packs/ai-coding/assets/scripts/run_field.py +295 -0
- package/packs/ai-coding/assets/scripts/spec_lint.py +247 -0
- package/packs/ai-coding/assets/scripts/update_board.py +524 -0
- package/packs/ai-coding/assets/scripts/verify.py +184 -0
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/CODE_STANDARDS.tmpl +44 -0
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/app-CLAUDE.tmpl +34 -0
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/build.tmpl +8 -0
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/module-CLAUDE.tmpl +42 -0
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/root-CLAUDE.tmpl +41 -0
- package/packs/ai-coding/assets/templates/java/maven/CODE_STANDARDS.tmpl +44 -0
- package/packs/ai-coding/assets/templates/java/maven/build.tmpl +9 -0
- package/packs/ai-coding/assets/templates/java/maven/root-CLAUDE.tmpl +38 -0
- package/packs/ai-coding/assets/templates/java/maven-multimodule/CODE_STANDARDS.tmpl +44 -0
- package/packs/ai-coding/assets/templates/java/maven-multimodule/build.tmpl +9 -0
- package/packs/ai-coding/assets/templates/java/maven-multimodule/module-CLAUDE.tmpl +40 -0
- package/packs/ai-coding/assets/templates/java/maven-multimodule/root-CLAUDE.tmpl +38 -0
- package/packs/ai-coding/assets/templates/javascript/mobile-app/CODE_STANDARDS.tmpl +51 -0
- package/packs/ai-coding/assets/templates/javascript/mobile-app/build.tmpl +8 -0
- package/packs/ai-coding/assets/templates/javascript/mobile-app/root-CLAUDE.tmpl +36 -0
- package/packs/ai-coding/assets/templates/javascript/uniapp/CODE_STANDARDS.tmpl +69 -0
- package/packs/ai-coding/assets/templates/javascript/uniapp/build.tmpl +8 -0
- package/packs/ai-coding/assets/templates/javascript/uniapp/root-CLAUDE.tmpl +56 -0
- package/packs/ai-coding/assets/templates/javascript/vue-multimodule/CODE_STANDARDS.tmpl +51 -0
- package/packs/ai-coding/assets/templates/javascript/vue-multimodule/app-CLAUDE.tmpl +36 -0
- package/packs/ai-coding/assets/templates/javascript/vue-multimodule/build.tmpl +8 -0
- package/packs/ai-coding/assets/templates/javascript/vue-multimodule/root-CLAUDE.tmpl +34 -0
- package/packs/ai-coding/flows/_router.yml +14 -0
- package/packs/ai-coding/flows/bugfix.yml +37 -0
- package/packs/ai-coding/flows/fix.yml +44 -0
- package/packs/ai-coding/flows/init.yml +83 -0
- package/packs/ai-coding/flows/new.yml +29 -0
- package/packs/ai-coding/flows/quick.yml +40 -0
- package/packs/ai-coding/flows/refactor.yml +50 -0
- package/packs/ai-coding/flows/standard.yml +49 -0
- package/packs/ai-coding/rules/code-standards.md +30 -0
- package/packs/ai-coding/rules/core.md +83 -0
- package/packs/ai-coding/templates/bugfix.md +29 -0
- package/packs/ai-coding/templates/memory-entry.md +46 -0
- package/packs/ai-coding/templates/proposal.md +47 -0
- package/packs/ai-coding/templates/spec-template.md +34 -0
- package/screenshots.json +5 -0
|
@@ -0,0 +1,868 @@
|
|
|
1
|
+
// 任务级并行开发:池化 git worktree 工作区管理(v2)。
|
|
2
|
+
//
|
|
3
|
+
// 设计(2026-11-14 与人定稿):
|
|
4
|
+
// - 单任务场景:保持原模式——直接在主工作树(services/<仓>)上开发,零迁移成本;
|
|
5
|
+
// - 多任务场景:主工作树被占用(checkout 着别的任务的开发分支)时,分配池化 slot
|
|
6
|
+
// `.worktrees/<仓>/slot-N/`(长期复用的通用工作区,不带任务名);
|
|
7
|
+
// - N 只有在第 N+1 个任务并发时才创建(2 并发 → slot-1,3 并发 → slot-2,依此);
|
|
8
|
+
// - 任务结束(归档)不删 worktree:slot 停在基线提交即「释放」,构建/依赖缓存保持热态;
|
|
9
|
+
// - 台账是本机状态不进资产 git(.gitignore 排除 + 摘除追踪):分配落点属于本机资源,
|
|
10
|
+
// 别人的任务占的是他自己机器的主工作树,不应出现在我的台账里挡我的路(2026-11-14 定);
|
|
11
|
+
// - 主树脏基线不是静默拒绝而是决策点:提示处理改动,或用户明确选 --slot 隔离开发。
|
|
12
|
+
// - 分配粒度是「每仓」:backend 忙只影响 backend,frontend 空闲的新任务直接用主工作树;
|
|
13
|
+
// - 卫生纪律:分配给新任务前 slot 必须干净(git status 空),脏 slot 拒绝分配并给清理指引
|
|
14
|
+
// (不自动 stash——残留可能是有价值的工作,由人裁决)。
|
|
15
|
+
//
|
|
16
|
+
// 台账 .harness/tasks/worktrees.json(v2):
|
|
17
|
+
// {
|
|
18
|
+
// "version": 2,
|
|
19
|
+
// "slots": { "<repo>": { "slot-1": { "task": "…", "branch": "…", "since": "ISO", "state": "bound" | "stale-unmerged" } } },
|
|
20
|
+
// "tasks": { "<task>": { "assignedAt": "ISO", "repos": { "<repo>": { "placement": "main" | "slot-N", "branch": "…", "base": "…" } } } }
|
|
21
|
+
// }
|
|
22
|
+
// v1(per-task worktree)台账无 version 字段,读取时自然落入容错分支视为空——
|
|
23
|
+
// M1 刚上线即改为池化,野外无 v1 数据需要迁移。
|
|
24
|
+
import fs from 'node:fs';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
import { harnessDir } from './paths.js';
|
|
27
|
+
import { runGit } from './exec.js';
|
|
28
|
+
|
|
29
|
+
const ledgerPath = (ws) => path.join(harnessDir(ws), 'tasks', 'worktrees.json');
|
|
30
|
+
const worktreeRoot = (ws, repo) => path.join(ws, '.worktrees', repo);
|
|
31
|
+
|
|
32
|
+
// --------------------------------------------------------------- 台账读写
|
|
33
|
+
|
|
34
|
+
/** 读台账(v2;坏文件/v1 一律容错为空)。 */
|
|
35
|
+
export function readWorkspaces(ws) {
|
|
36
|
+
try {
|
|
37
|
+
const data = JSON.parse(fs.readFileSync(ledgerPath(ws), 'utf8'));
|
|
38
|
+
if (data?.version !== 2 || typeof data !== 'object') return { slots: {}, tasks: {} };
|
|
39
|
+
return { slots: data.slots ?? {}, tasks: data.tasks ?? {} };
|
|
40
|
+
} catch { return { slots: {}, tasks: {} }; }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function writeWorkspaces(ws, { slots, tasks }) {
|
|
44
|
+
fs.mkdirSync(path.dirname(ledgerPath(ws)), { recursive: true });
|
|
45
|
+
fs.writeFileSync(ledgerPath(ws), `${JSON.stringify({ version: 2, slots, tasks }, null, 2)}\n`, 'utf8');
|
|
46
|
+
keepLedgerLocal(ws);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** 台账本地化:.gitignore 排除 + 已追踪的旧文件摘除追踪(保留本地文件)。失败容忍。 */
|
|
50
|
+
export function keepLedgerLocal(ws, entry = 'tasks/worktrees.json') {
|
|
51
|
+
try {
|
|
52
|
+
const hd = harnessDir(ws);
|
|
53
|
+
const gi = path.join(hd, '.gitignore');
|
|
54
|
+
const cur = fs.existsSync(gi) ? fs.readFileSync(gi, 'utf8') : '';
|
|
55
|
+
if (!cur.split('\n').some((l) => l.trim() === entry)) {
|
|
56
|
+
fs.appendFileSync(gi, `${cur.endsWith('\n') || cur === '' ? '' : '\n'}# 本机工作区/环境台账(机器本地状态,不共享、勿提交)\n${entry}\n`, 'utf8');
|
|
57
|
+
}
|
|
58
|
+
if (fs.existsSync(path.join(hd, '.git'))) {
|
|
59
|
+
runGit(['rm', '--cached', '--quiet', '--ignore-unmatch', entry], { cwd: hd });
|
|
60
|
+
}
|
|
61
|
+
} catch { /* 容忍:最坏结果是台账被同步,跨用户挡路问题复现 */ }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 兼容旧测试与外部引用
|
|
65
|
+
export const readWorktrees = readWorkspaces;
|
|
66
|
+
|
|
67
|
+
// --------------------------------------------------------------- git 小工具
|
|
68
|
+
|
|
69
|
+
/** 根仓本地排除 .worktrees/(不动共享 .gitignore,不进提交)。幂等。 */
|
|
70
|
+
function excludeFromRootRepo(ws) {
|
|
71
|
+
const exclude = path.join(ws, '.git', 'info', 'exclude');
|
|
72
|
+
try {
|
|
73
|
+
if (!fs.existsSync(path.join(ws, '.git'))) return;
|
|
74
|
+
fs.mkdirSync(path.dirname(exclude), { recursive: true });
|
|
75
|
+
const cur = fs.existsSync(exclude) ? fs.readFileSync(exclude, 'utf8') : '';
|
|
76
|
+
if (!cur.split('\n').some((l) => l.trim() === '.worktrees/')) {
|
|
77
|
+
fs.appendFileSync(exclude, `${cur.endsWith('\n') || cur === '' ? '' : '\n'}.worktrees/\n`, 'utf8');
|
|
78
|
+
}
|
|
79
|
+
} catch { /* 排除失败不阻断主流程,仅表现为根仓 untracked 噪音 */ }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 某仓是否为可用 git 仓(submodule/普通仓均可)。 */
|
|
83
|
+
async function isGitRepo(repoDir) {
|
|
84
|
+
return (await runGit(['rev-parse', '--git-dir'], { cwd: repoDir })).code === 0;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 解析基线分支:kit.json source.branch → 本地 dev → 当前 HEAD。 */
|
|
88
|
+
async function resolveBase(repoDir, source) {
|
|
89
|
+
const wanted = source.branch ?? 'dev';
|
|
90
|
+
if ((await runGit(['rev-parse', '--verify', `refs/heads/${wanted}`], { cwd: repoDir })).code === 0) return wanted;
|
|
91
|
+
if ((await runGit(['rev-parse', '--verify', 'refs/heads/dev'], { cwd: repoDir })).code === 0) return 'dev';
|
|
92
|
+
if ((await runGit(['rev-parse', '--verify', 'HEAD'], { cwd: repoDir })).code === 0) return 'HEAD';
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 解析任务创建时指定的基线(--base,analysis-base.json 落盘):
|
|
98
|
+
* 该值同时是开发分支基点与归档合入目标(2026-11-17 定:目标基线=创建时指定,不是默认基线)。
|
|
99
|
+
* 返回可用的 ref 名(本地分支或 origin/<分支>),不可用返回 null。
|
|
100
|
+
*/
|
|
101
|
+
async function resolveTaskBase(repoDir, branch) {
|
|
102
|
+
if (!branch) return null;
|
|
103
|
+
if ((await runGit(['rev-parse', '--verify', `refs/heads/${branch}`], { cwd: repoDir })).code === 0) return branch;
|
|
104
|
+
if ((await runGit(['rev-parse', '--verify', `refs/remotes/origin/${branch}`], { cwd: repoDir })).code === 0) return `origin/${branch}`;
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 读任务创建时指定的分析/开发基线(.harness/deliverables/<任务>/analysis-base.json)。 */
|
|
109
|
+
export function readTaskBaseSpec(ws, task) {
|
|
110
|
+
try {
|
|
111
|
+
const spec = JSON.parse(fs.readFileSync(path.join(harnessDir(ws), 'deliverables', task, 'analysis-base.json'), 'utf8'));
|
|
112
|
+
return spec && typeof spec === 'object' ? spec : {};
|
|
113
|
+
} catch { return {}; }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
async function currentBranch(repoDir) {
|
|
117
|
+
const r = await runGit(['branch', '--show-current'], { cwd: repoDir });
|
|
118
|
+
return r.code === 0 ? r.stdout.trim() : '';
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
async function isDirty(dir) {
|
|
122
|
+
const r = await runGit(['status', '--porcelain'], { cwd: dir });
|
|
123
|
+
return r.code !== 0 || r.stdout.trim() !== '';
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 本地合入判定。 */
|
|
127
|
+
async function mergedLocally(repoDir, branch, base) {
|
|
128
|
+
const r = await runGit(['branch', '--merged', base, '--list', branch], { cwd: repoDir });
|
|
129
|
+
return r.code === 0 && r.stdout.includes(branch);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 合入判定(归档释放用):先看本地基线;未合入则 fetch 远端基线再判一次
|
|
134
|
+
* (iot-harness 的合入发生在 GitLab MR,本地 dev 常滞后——不 fetch 会把
|
|
135
|
+
* 几乎所有归档都判成"未合入",主工作树/slot 永远无法释放)。
|
|
136
|
+
* fetch 失败按未合入处理(不报错)。
|
|
137
|
+
*/
|
|
138
|
+
async function mergedStatus(repoDir, branch, base) {
|
|
139
|
+
if (await mergedLocally(repoDir, branch, base)) return true;
|
|
140
|
+
if (base === 'HEAD') return false;
|
|
141
|
+
// base 可能是远端 ref(--base 指定的分支只有远端时 resolveTaskBase 返回 origin/<x>)
|
|
142
|
+
const remoteBase = base.startsWith('origin/') ? base.slice('origin/'.length) : base;
|
|
143
|
+
await runGit(['fetch', 'origin', remoteBase], { cwd: repoDir, timeoutMs: 30_000 });
|
|
144
|
+
const target = base.startsWith('origin/') ? base : `origin/${remoteBase}`;
|
|
145
|
+
return mergedLocally(repoDir, branch, target);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// --------------------------------------------------------------- 决策点(需人裁决的结构性阻塞)
|
|
149
|
+
|
|
150
|
+
const decisionsPath = (ws) => path.join(harnessDir(ws), 'tasks', 'decisions.json');
|
|
151
|
+
|
|
152
|
+
/** 待裁决决策点(本机状态):{ <task>: { code, text, options, at } }。 */
|
|
153
|
+
export function readDecisions(ws) {
|
|
154
|
+
try {
|
|
155
|
+
const data = JSON.parse(fs.readFileSync(decisionsPath(ws), 'utf8'));
|
|
156
|
+
return data && typeof data === 'object' ? data : {};
|
|
157
|
+
} catch { return {}; }
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function writeDecisions(ws, decisions) {
|
|
161
|
+
fs.mkdirSync(path.dirname(decisionsPath(ws)), { recursive: true });
|
|
162
|
+
fs.writeFileSync(decisionsPath(ws), `${JSON.stringify(decisions, null, 2)}\n`, 'utf8');
|
|
163
|
+
keepLedgerLocal(ws, 'tasks/decisions.json');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 记录决策点(工作区分配拒绝等);重复记录覆盖(保持最新文本)。 */
|
|
167
|
+
export function recordDecision(ws, task, entry) {
|
|
168
|
+
const decisions = readDecisions(ws);
|
|
169
|
+
decisions[task] = { ...entry, at: new Date().toISOString() };
|
|
170
|
+
writeDecisions(ws, decisions);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** 清除决策点(用户已裁决重跑成功 / 任务归档 / 同名重建)。 */
|
|
174
|
+
export function clearDecision(ws, task) {
|
|
175
|
+
const decisions = readDecisions(ws);
|
|
176
|
+
if (!(task in decisions)) return;
|
|
177
|
+
delete decisions[task];
|
|
178
|
+
writeDecisions(ws, decisions);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** 主工作树现场详情(决策点报错的信息增强:分支 + git status,帮助人裁决)。 */
|
|
182
|
+
export async function describeMainWorktree(ws, source, { maxLines = 10 } = {}) {
|
|
183
|
+
const repoDir = path.join(ws, source.path);
|
|
184
|
+
if (!fs.existsSync(repoDir) || !(await isGitRepo(repoDir))) return `${source.name}:仓不可用`;
|
|
185
|
+
const branch = await currentBranch(repoDir);
|
|
186
|
+
const st = await runGit(['status', '--short'], { cwd: repoDir });
|
|
187
|
+
const lines = st.code === 0 ? st.stdout.trim().split('\n').filter(Boolean) : [];
|
|
188
|
+
return [
|
|
189
|
+
`${source.name}(\`${repoDir}\`)`,
|
|
190
|
+
` 当前分支:\`${branch || '(detached)'}\``,
|
|
191
|
+
lines.length === 0 ? ' 工作区干净' : ` 未提交改动(前 ${Math.min(lines.length, maxLines)} 行/共 ${lines.length}):\n${lines.slice(0, maxLines).map((l) => ` ${l}`).join('\n')}`,
|
|
192
|
+
].join('\n');
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 本地合入任务分支到目标基线(B 方案,2026-11-17 定):不推送,推送仍归人。
|
|
197
|
+
* 人通过 /hk-archive <任务> --merge(可带 repo:branch 覆盖)显式确认目标分支——
|
|
198
|
+
* 确认即触发本次调用。合并提交留在目标分支上;冲突则中止并报告,不污染基线。
|
|
199
|
+
*
|
|
200
|
+
* 合并位置:目标分支若被某工作树 checkout 且干净 → 就地合并;否则建临时工作树
|
|
201
|
+
* (.worktrees/<仓>/_merge)合并后删除。主工作树脏 → 拒绝该仓。
|
|
202
|
+
* 返回 { merged: [{repo,target,commit}], conflicts: [{repo,target,files}], refused: [{repo,reason}] }。
|
|
203
|
+
*/
|
|
204
|
+
export async function mergeTaskBranches(ws, kit, task, overrides = {}) {
|
|
205
|
+
const out = { merged: [], conflicts: [], refused: [] };
|
|
206
|
+
const ledger = readWorkspaces(ws);
|
|
207
|
+
const entry = ledger.tasks?.[task];
|
|
208
|
+
if (!entry) { out.refused.push({ repo: '-', reason: `台账无任务 ${task} 的工作区记录` }); return out; }
|
|
209
|
+
|
|
210
|
+
for (const [name, info] of Object.entries(entry.repos ?? {})) {
|
|
211
|
+
if (!info || !info.branch) continue; // 无分支记录(非 git 仓)跳过;main/slot 两种放置都可合入
|
|
212
|
+
const source = (kit?.sources ?? []).find((s) => s.name === name);
|
|
213
|
+
const repoDir = source ? path.join(ws, source.path) : null;
|
|
214
|
+
if (!repoDir || !fs.existsSync(repoDir) || !(await isGitRepo(repoDir))) {
|
|
215
|
+
out.refused.push({ repo: name, reason: '仓不可用' });
|
|
216
|
+
continue;
|
|
217
|
+
}
|
|
218
|
+
// 目标分支:人显式覆盖优先,否则台账记录的创建时基线
|
|
219
|
+
let target = (overrides?.[name] ?? info.base ?? '').trim();
|
|
220
|
+
if (!target) { out.refused.push({ repo: name, reason: '无目标基线记录' }); continue; }
|
|
221
|
+
// 远端 ref → 先落成本地分支(合并必须发生在本地分支上)
|
|
222
|
+
if (target.startsWith('origin/')) {
|
|
223
|
+
const local = target.slice('origin/'.length);
|
|
224
|
+
if ((await runGit(['rev-parse', '--verify', `refs/heads/${local}`], { cwd: repoDir })).code !== 0) {
|
|
225
|
+
const cb = await runGit(['branch', local, target], { cwd: repoDir });
|
|
226
|
+
if (cb.code !== 0) { out.refused.push({ repo: name, reason: `目标 ${target} 无法建立本地分支` }); continue; }
|
|
227
|
+
}
|
|
228
|
+
target = local;
|
|
229
|
+
}
|
|
230
|
+
if ((await runGit(['rev-parse', '--verify', `refs/heads/${target}`], { cwd: repoDir })).code !== 0) {
|
|
231
|
+
out.refused.push({ repo: name, reason: `目标分支 ${target} 不存在` });
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
const branch = info.branch;
|
|
235
|
+
if ((await runGit(['rev-parse', '--verify', `refs/heads/${branch}`], { cwd: repoDir })).code !== 0) {
|
|
236
|
+
out.refused.push({ repo: name, reason: `任务分支 ${branch} 已不存在` });
|
|
237
|
+
continue;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// 目标分支被哪个工作树 checkout?
|
|
241
|
+
const holder = await worktreeOnBranch(repoDir, target);
|
|
242
|
+
let mergeCwd = null;
|
|
243
|
+
let tempDir = null;
|
|
244
|
+
if (holder) {
|
|
245
|
+
if (await isDirty(holder)) { out.refused.push({ repo: name, reason: `目标分支 ${target} 所在工作树有未提交改动,请先处理:${holder}` }); continue; }
|
|
246
|
+
mergeCwd = holder;
|
|
247
|
+
} else {
|
|
248
|
+
tempDir = path.join(worktreeRoot(ws, name), '_merge');
|
|
249
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
250
|
+
fs.mkdirSync(path.dirname(tempDir), { recursive: true });
|
|
251
|
+
const add = await runGit(['worktree', 'add', tempDir, target], { cwd: repoDir });
|
|
252
|
+
if (add.code !== 0) { out.refused.push({ repo: name, reason: `临时工作树创建失败:${(add.stderr || '').trim().split('\n')[0]}` }); continue; }
|
|
253
|
+
mergeCwd = tempDir;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// --no-ff 合并:即使可快进也留合并提交,记录"某任务合入"
|
|
257
|
+
const mg = await runGit(['merge', '--no-ff', '-m', `harness: 合入 ${branch}(${task})`, branch], { cwd: mergeCwd });
|
|
258
|
+
if (mg.code !== 0) {
|
|
259
|
+
const files = (await runGit(['diff', '--name-only', '--diff-filter=U'], { cwd: mergeCwd })).stdout.trim().split('\n').filter(Boolean);
|
|
260
|
+
await runGit(['merge', '--abort'], { cwd: mergeCwd });
|
|
261
|
+
if (tempDir) { await runGit(['worktree', 'remove', '--force', tempDir], { cwd: repoDir }); fs.rmSync(tempDir, { recursive: true, force: true }); }
|
|
262
|
+
out.conflicts.push({ repo: name, target, files });
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
const commit = (await runGit(['rev-parse', '--short', 'HEAD'], { cwd: mergeCwd })).stdout.trim();
|
|
266
|
+
if (tempDir) {
|
|
267
|
+
await runGit(['worktree', 'remove', '--force', tempDir], { cwd: repoDir });
|
|
268
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
269
|
+
}
|
|
270
|
+
out.merged.push({ repo: name, target, commit });
|
|
271
|
+
}
|
|
272
|
+
return out;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** 哪个工作树 checkout 着某分支(返回路径;无则 null)。 */
|
|
276
|
+
async function worktreeOnBranch(repoDir, branch) {
|
|
277
|
+
const r = await runGit(['worktree', 'list', '--porcelain'], { cwd: repoDir });
|
|
278
|
+
if (r.code !== 0) return null;
|
|
279
|
+
let cur = null;
|
|
280
|
+
for (const line of r.stdout.split('\n')) {
|
|
281
|
+
if (line.startsWith('worktree ')) cur = line.slice('worktree '.length).trim();
|
|
282
|
+
else if (line.startsWith('branch ') && line.slice('branch '.length).trim() === `refs/heads/${branch}`) return cur;
|
|
283
|
+
}
|
|
284
|
+
return null;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* 主工作树状态:occupied = 不能再分配新任务。
|
|
289
|
+
* 占用判定(唯一标准,2026-11-14 定):checkout 着非基线分支(正在分支开发中),
|
|
290
|
+
* 或基线上有未提交改动(保守——防止新任务在脏基线上开工)。
|
|
291
|
+
*/
|
|
292
|
+
async function mainWorktreeState(repoDir, base) { const branch = await currentBranch(repoDir);
|
|
293
|
+
const dirty = await isDirty(repoDir);
|
|
294
|
+
const occupied = branch !== base || dirty;
|
|
295
|
+
let reason = '';
|
|
296
|
+
if (branch !== base) reason = `主工作树正在分支 \`${branch}\` 上开发`;
|
|
297
|
+
else if (dirty) reason = '主工作树基线上有未提交改动';
|
|
298
|
+
return { branch, dirty, occupied, reason };
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// --------------------------------------------------------------- 冲突前置检测
|
|
302
|
+
|
|
303
|
+
/** 极简看板行扫描(任务名+状态):供占用者回填核对用,不做全量契约校验(parseBoard 在 panel.js,避免环依赖)。 */
|
|
304
|
+
function boardRowsFor(ws) {
|
|
305
|
+
try {
|
|
306
|
+
const text = fs.readFileSync(path.join(harnessDir(ws), 'tasks', 'board.md'), 'utf8');
|
|
307
|
+
return text.split('\n')
|
|
308
|
+
.filter((l) => l.startsWith('|'))
|
|
309
|
+
.map((l) => {
|
|
310
|
+
const c = l.split('|').map((x) => x.trim());
|
|
311
|
+
return { task: c[1] ?? '', status: c[2] ?? '' };
|
|
312
|
+
})
|
|
313
|
+
.filter((r) => r.task && r.task !== '任务名' && !/^[-: ]+$/.test(r.task));
|
|
314
|
+
} catch { return []; }
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** 与在途任务(台账内其他任务)的分支改动文件集重叠。 */
|
|
318
|
+
async function overlapWithInflight(ws, kit, task) {
|
|
319
|
+
const { tasks } = readWorkspaces(ws);
|
|
320
|
+
const out = [];
|
|
321
|
+
for (const [other, entry] of Object.entries(tasks)) {
|
|
322
|
+
if (other === task || !entry?.repos) continue;
|
|
323
|
+
for (const source of kit.sources ?? []) {
|
|
324
|
+
const info = entry.repos[source.name];
|
|
325
|
+
if (!info?.branch || !info?.base) continue;
|
|
326
|
+
const repoDir = path.join(ws, source.path);
|
|
327
|
+
if (!fs.existsSync(repoDir) || !(await isGitRepo(repoDir))) continue;
|
|
328
|
+
const r = await runGit(['diff', '--name-only', `${info.base}...${info.branch}`], { cwd: repoDir });
|
|
329
|
+
if (r.code === 0 && r.stdout.trim()) {
|
|
330
|
+
out.push({ task: other, source: source.name, files: r.stdout.trim().split('\n') });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
return out;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// --------------------------------------------------------------- slot 分配与释放
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* 在仓上找空闲 slot 或新建一个,并切到任务分支。
|
|
341
|
+
* 返回 { placement, path };不可用时返回 { error }。
|
|
342
|
+
*/
|
|
343
|
+
async function acquireSlot(ws, repoDir, repoName, task, branch, base, slots) {
|
|
344
|
+
const root = worktreeRoot(ws, repoName);
|
|
345
|
+
const repoSlots = slots[repoName] ?? {};
|
|
346
|
+
const notes = [];
|
|
347
|
+
const boundToOther = (s) => {
|
|
348
|
+
const b = repoSlots[s];
|
|
349
|
+
return b && b.task !== task && b.state !== 'stale-unmerged' ? b : null;
|
|
350
|
+
};
|
|
351
|
+
const stale = (s) => repoSlots[s]?.state === 'stale-unmerged';
|
|
352
|
+
|
|
353
|
+
// 已绑定本任务的 slot → 复用(幂等)
|
|
354
|
+
for (const [name, binding] of Object.entries(repoSlots)) {
|
|
355
|
+
if (binding.task === task && fs.existsSync(path.join(root, name))) {
|
|
356
|
+
if (await currentBranch(path.join(root, name)) !== binding.branch) {
|
|
357
|
+
await runGit(['checkout', binding.branch], { cwd: path.join(root, name) });
|
|
358
|
+
}
|
|
359
|
+
return { placement: name, path: path.join(root, name), notes };
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// 找现成 slot 目录:无绑定或绑定的任务已不在台账 → 候选
|
|
364
|
+
const dirs = fs.existsSync(root) ? fs.readdirSync(root).filter((d) => /^slot-\d+$/.test(d) && fs.statSync(path.join(root, d)).isDirectory()) : [];
|
|
365
|
+
dirs.sort((a, b) => Number(a.slice(5)) - Number(b.slice(5)));
|
|
366
|
+
for (const name of dirs) {
|
|
367
|
+
if (boundToOther(name) || stale(name)) continue;
|
|
368
|
+
const dir = path.join(root, name);
|
|
369
|
+
if (await isDirty(dir)) {
|
|
370
|
+
// 卫生纪律:脏 slot 跳过并提示人工清理(不自动 stash——残留可能是有价值的工作);
|
|
371
|
+
// 后面还有干净 slot 就用,没有就新建,脏 slot 不阻塞任务
|
|
372
|
+
const bindingHint = repoSlots[name]?.task ? `(上一任任务 ${repoSlots[name].task} 的残留)` : '';
|
|
373
|
+
notes.push(`slot ${name} 有未提交改动${bindingHint},已跳过:请人工处理(提交/丢弃/移走)后它才能再被使用`);
|
|
374
|
+
continue;
|
|
375
|
+
}
|
|
376
|
+
// 干净 slot:切到任务分支(已存在则直接切,否则从基线拉)
|
|
377
|
+
const branchExists = (await runGit(['rev-parse', '--verify', `refs/heads/${branch}`], { cwd: repoDir })).code === 0;
|
|
378
|
+
const r = branchExists
|
|
379
|
+
? await runGit(['checkout', branch], { cwd: dir })
|
|
380
|
+
: await runGit(['checkout', '-b', branch, base], { cwd: dir });
|
|
381
|
+
if (r.code !== 0) return { error: `slot ${name} 切分支失败:${(r.stderr || '').trim().split('\n')[0]}` };
|
|
382
|
+
return { placement: name, path: dir, notes };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// 没有可用 slot → 新建下一个序号(池化:只有并发数超出现有 slot 数才新建)
|
|
386
|
+
const nums = [...dirs, ...Object.keys(repoSlots)];
|
|
387
|
+
const next = nums.reduce((m, n) => Math.max(m, Number(String(n).replace(/\D/g, '')) || 0), 0) + 1;
|
|
388
|
+
const name = `slot-${next}`;
|
|
389
|
+
const dir = path.join(root, name);
|
|
390
|
+
fs.mkdirSync(root, { recursive: true });
|
|
391
|
+
const r = await runGit(['worktree', 'add', '-b', branch, dir, base], { cwd: repoDir });
|
|
392
|
+
if (r.code !== 0) return { error: `新建 slot ${name} 失败:${(r.stderr || '').trim().split('\n')[0]}` };
|
|
393
|
+
return { placement: name, path: dir, notes };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** 释放 slot:分支已合入 → 切回基线、删分支、解绑(目录保留);未合入 → 标 stale。 */
|
|
397
|
+
async function releaseSlot(repoDir, dir, binding, base, slots, repoName, candidates = null) {
|
|
398
|
+
const branch = binding.branch;
|
|
399
|
+
if (!fs.existsSync(dir)) { delete slots[repoName][binding.slot]; return { released: true }; }
|
|
400
|
+
// 合入判定:台账基线(任务创建时指定)与当前 kit 基线任一命中都算已合入——
|
|
401
|
+
// 人可能在开发期间改基线(如 phm 合入 feat_phm_261022,2026-11-17 真实事故)
|
|
402
|
+
const targets = [...new Set((candidates && candidates.length ? candidates : [base]).filter(Boolean))];
|
|
403
|
+
let hit = null;
|
|
404
|
+
for (const t of targets) {
|
|
405
|
+
if (await mergedStatus(repoDir, branch, t)) { hit = t; break; }
|
|
406
|
+
}
|
|
407
|
+
if (hit) {
|
|
408
|
+
if (await isDirty(dir)) {
|
|
409
|
+
return { released: false, reason: `slot ${binding.slot} 有未提交改动,请人工处理后再释放` };
|
|
410
|
+
}
|
|
411
|
+
// 注意:基线分支在主工作树 checkout 着,git 不允许第二个 worktree 再 checkout 它——
|
|
412
|
+
// 释放用 detached HEAD 停在基线提交上(复用时从 detached 直接拉新分支,零冲突)
|
|
413
|
+
const co = await runGit(['checkout', '--detach', hit], { cwd: dir });
|
|
414
|
+
if (co.code !== 0) return { released: false, reason: `slot ${binding.slot} 切回基线失败:${(co.stderr || '').trim().split('\n')[0]}` };
|
|
415
|
+
await runGit(['branch', '-d', branch], { cwd: repoDir });
|
|
416
|
+
delete slots[repoName][binding.slot];
|
|
417
|
+
return { released: true, matchedBase: hit };
|
|
418
|
+
}
|
|
419
|
+
slots[repoName][binding.slot] = { ...binding, state: 'stale-unmerged' };
|
|
420
|
+
return { released: false, reason: `分支 ${branch} 未合入 ${targets.join(' / ')}:slot ${binding.slot} 保留并标记 stale(后续任务不会使用);人确认合入后重跑 /hk-archive 释放` };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// --------------------------------------------------------------- 主入口
|
|
424
|
+
|
|
425
|
+
/**
|
|
426
|
+
* 为任务分配各仓工作区(幂等)。
|
|
427
|
+
* 返回 { assigned: [{source, placement, path?, branch, base, reused}], refused: [{source, reason}], overlaps }。
|
|
428
|
+
* placement: 'main' = 主工作树;'slot-N' = 池化 worktree。
|
|
429
|
+
*/
|
|
430
|
+
export async function ensureTaskWorkspaces(ws, kit, task, { branchPrefix = 'feat', forceSlot = false } = {}) {
|
|
431
|
+
const result = { assigned: [], refused: [], notes: [], overlaps: [] };
|
|
432
|
+
const sources = kit?.sources ?? [];
|
|
433
|
+
if (sources.length === 0) return result;
|
|
434
|
+
excludeFromRootRepo(ws);
|
|
435
|
+
const ledger = readWorkspaces(ws);
|
|
436
|
+
const tEntry = ledger.tasks[task] ?? { assignedAt: new Date().toISOString(), repos: {} };
|
|
437
|
+
|
|
438
|
+
for (const source of sources) {
|
|
439
|
+
const repoDir = path.join(ws, source.path);
|
|
440
|
+
if (!fs.existsSync(repoDir)) continue; // 仓目录缺失:与本任务无关,跳过
|
|
441
|
+
if (!(await isGitRepo(repoDir))) {
|
|
442
|
+
// 非 git 仓(或伪 .git):退回原模式,不做任何 git 管理
|
|
443
|
+
const prev = tEntry.repos[source.name];
|
|
444
|
+
if (!prev) {
|
|
445
|
+
tEntry.repos[source.name] = { placement: 'main', branch: null, base: null };
|
|
446
|
+
result.assigned.push({ source: source.name, placement: 'main', path: repoDir, branch: null, base: null, reused: false });
|
|
447
|
+
} else {
|
|
448
|
+
result.assigned.push({ source: source.name, placement: 'main', path: repoDir, branch: prev.branch, base: prev.base, reused: true });
|
|
449
|
+
}
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
// 开发分支基点:任务创建时指定的基线(--base)优先,否则 kit.json 基线(2026-11-17 定)
|
|
453
|
+
const taskSpec = readTaskBaseSpec(ws, task);
|
|
454
|
+
let base = await resolveBase(repoDir, source) ?? 'HEAD';
|
|
455
|
+
if (taskSpec[source.name]) {
|
|
456
|
+
const resolved = await resolveTaskBase(repoDir, taskSpec[source.name]);
|
|
457
|
+
if (resolved) {
|
|
458
|
+
base = resolved;
|
|
459
|
+
} else {
|
|
460
|
+
result.notes.push(`${source.name}:创建时指定的基线 ${taskSpec[source.name]} 不存在(本地/远端均无),已回退默认基线 ${base}`);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
const branch = `${branchPrefix}/harness-${task}`;
|
|
464
|
+
|
|
465
|
+
// 幂等:本任务已有有效分配 → 复用
|
|
466
|
+
const existing = tEntry.repos[source.name];
|
|
467
|
+
if (existing) {
|
|
468
|
+
if (existing.placement === 'main') {
|
|
469
|
+
result.assigned.push({ source: source.name, placement: 'main', path: repoDir, branch, base, reused: true });
|
|
470
|
+
} else {
|
|
471
|
+
const dir = path.join(worktreeRoot(ws, source.name), existing.placement);
|
|
472
|
+
if (fs.existsSync(dir)) {
|
|
473
|
+
result.assigned.push({ source: source.name, placement: existing.placement, path: dir, branch, base, reused: true });
|
|
474
|
+
} else {
|
|
475
|
+
delete tEntry.repos[source.name]; // slot 目录没了,重新分配
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
if (tEntry.repos[source.name]) continue;
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// 主工作树空闲?→ 原模式。
|
|
482
|
+
// 注意:判定「占用」以台账为准而非仅 git 状态——分配给主工作树只写台账、
|
|
483
|
+
// 分支由 agent 稍后创建;若只看 git 状态,两个任务在分支创建前会同时抢到主工作树。
|
|
484
|
+
// 台账已本地化(keepLedgerLocal),里面的占用者必然是本机自己的任务。
|
|
485
|
+
const main = forceSlot ? { occupied: true, branch, dirty: false, reason: '--slot 强制隔离' } : await mainWorktreeState(repoDir, base);
|
|
486
|
+
const owner = Object.entries(ledger.tasks).find(([t, e]) => t !== task && e?.repos?.[source.name]?.placement === 'main');
|
|
487
|
+
if (!main.occupied && !owner) {
|
|
488
|
+
tEntry.repos[source.name] = { placement: 'main', branch, base };
|
|
489
|
+
ledger.slots[source.name] ??= {};
|
|
490
|
+
result.assigned.push({ source: source.name, placement: 'main', path: repoDir, branch, base, reused: false });
|
|
491
|
+
continue;
|
|
492
|
+
}
|
|
493
|
+
if (!owner && !forceSlot) {
|
|
494
|
+
// 占用分支是 harness 任务分支(feat/harness-* / fix/harness-*)但台账无记录:
|
|
495
|
+
// 典型是台账机制之前的在途任务——分支语义明确,无需人裁决,自动落 slot;
|
|
496
|
+
// 且回填台账,让该任务归档时主树能被正确释放(2026-11-16 iot-harness 真实场景)。
|
|
497
|
+
const hm = main.branch.match(/^(?:feat|fix)\/harness-(.+)$/);
|
|
498
|
+
if (hm) {
|
|
499
|
+
const rows = boardRowsFor(ws);
|
|
500
|
+
const row = rows.find((r) => r.task === hm[1]) ?? rows.find((r) => r.task === hm[1].replace(/-r\d+$/, ''));
|
|
501
|
+
if (row) {
|
|
502
|
+
ledger.tasks[row.task] ??= { assignedAt: new Date().toISOString(), repos: {} };
|
|
503
|
+
if (!ledger.tasks[row.task].repos[source.name]) {
|
|
504
|
+
ledger.tasks[row.task].repos[source.name] = { placement: 'main', branch: main.branch, base };
|
|
505
|
+
result.notes.push(`主工作树被 harness 任务 ${row.task} 占用(台账无记录,已回填);本任务自动分配 slot`);
|
|
506
|
+
}
|
|
507
|
+
} else {
|
|
508
|
+
result.notes.push(`主工作树被 harness 分支 ${main.branch} 占用(对应任务不在看板,未回填台账);本任务自动分配 slot`);
|
|
509
|
+
}
|
|
510
|
+
// 落入下方 slot 分配
|
|
511
|
+
} else {
|
|
512
|
+
// 真正的外来分支/脏基线 → 决策点:不静默选 slot,提示用户处理或明确加 --slot(用户裁决后再执行)
|
|
513
|
+
const dirtyOnBase = main.branch === base;
|
|
514
|
+
result.refused.push({
|
|
515
|
+
source: source.name,
|
|
516
|
+
reason: dirtyOnBase
|
|
517
|
+
? '主工作树基线上有未提交改动(可能是手工修改):请先提交/暂存/丢弃后重跑(主工作树模式);或确认要在隔离 slot 开发:重跑时加 `--slot`'
|
|
518
|
+
: `${main.reason},且非本工作区台账任务(可能是手工操作残留):请先人工处理;或确认要在隔离 slot 开发:重跑时加 \`--slot\``,
|
|
519
|
+
});
|
|
520
|
+
continue;
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
// 主工作树被本机其他台账任务占用(或其分配已落台账)→ slot
|
|
524
|
+
ledger.slots[source.name] ??= {};
|
|
525
|
+
const acq = await acquireSlot(ws, repoDir, source.name, task, branch, base, ledger.slots);
|
|
526
|
+
if (acq.error) {
|
|
527
|
+
result.refused.push({ source: source.name, reason: acq.error });
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
530
|
+
result.notes.push(...(acq.notes ?? []));
|
|
531
|
+
ledger.slots[source.name][acq.placement] = { task, branch, since: new Date().toISOString(), state: 'bound' };
|
|
532
|
+
tEntry.repos[source.name] = { placement: acq.placement, branch, base };
|
|
533
|
+
result.assigned.push({ source: source.name, placement: acq.placement, path: acq.path, branch, base, reused: false });
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
ledger.tasks[task] = tEntry;
|
|
537
|
+
writeWorkspaces(ws, ledger);
|
|
538
|
+
result.overlaps = await overlapWithInflight(ws, kit, task);
|
|
539
|
+
return result;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/**
|
|
543
|
+
* 归档释放:main 不动(合入确认归人);slot 已合入 → 切回基线释放;
|
|
544
|
+
* 未合入 → stale 标记保留。返回 { released, stale: [{source, reason}], missing }。
|
|
545
|
+
*/
|
|
546
|
+
export async function releaseTaskWorkspaces(ws, kit, task) {
|
|
547
|
+
const out = { released: [], stale: [], missing: false };
|
|
548
|
+
const ledger = readWorkspaces(ws);
|
|
549
|
+
const entry = ledger.tasks[task];
|
|
550
|
+
if (!entry) { out.missing = true; return out; }
|
|
551
|
+
const remaining = {};
|
|
552
|
+
for (const [name, info] of Object.entries(entry.repos ?? {})) {
|
|
553
|
+
const source = (kit?.sources ?? []).find((s) => s.name === name);
|
|
554
|
+
const repoDir = source ? path.join(ws, source.path) : null;
|
|
555
|
+
if (info.placement === 'main') {
|
|
556
|
+
// 已合入 → 把主工作树切回基线、删分支(回到干净空闲态,下个任务可直接用);
|
|
557
|
+
// 未合入 → 保持占用(保护性:代码未合入时不让新任务踩主工作树)
|
|
558
|
+
if (repoDir && fs.existsSync(repoDir) && await isGitRepo(repoDir) && info.branch) {
|
|
559
|
+
const cur = await currentBranch(repoDir);
|
|
560
|
+
if (cur === info.branch) {
|
|
561
|
+
if (await mergedStatus(repoDir, info.branch, info.base ?? 'dev')) {
|
|
562
|
+
if (!(await isDirty(repoDir))) {
|
|
563
|
+
await runGit(['checkout', info.base ?? 'dev'], { cwd: repoDir });
|
|
564
|
+
await runGit(['branch', '-d', info.branch], { cwd: repoDir });
|
|
565
|
+
out.released.push({ source: name, placement: 'main', note: '主工作树已切回基线并删已合入分支' });
|
|
566
|
+
} else {
|
|
567
|
+
out.stale.push({ source: name, reason: `主工作树分支 ${info.branch} 已合入但有未提交改动,未切回基线(请人工处理)` });
|
|
568
|
+
remaining[name] = info;
|
|
569
|
+
}
|
|
570
|
+
} else {
|
|
571
|
+
out.stale.push({ source: name, reason: `分支 ${info.branch} 未合入 ${info.base}:主工作树保持占用(保护性),人确认合入后重跑 /hk-archive 释放` });
|
|
572
|
+
remaining[name] = info;
|
|
573
|
+
}
|
|
574
|
+
continue;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
out.released.push({ source: name, placement: 'main', note: '主工作树(无内核动作)' });
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
const dir = path.join(worktreeRoot(ws, name), info.placement);
|
|
581
|
+
ledger.slots[name] ??= {};
|
|
582
|
+
if (!repoDir || !fs.existsSync(repoDir) || !(await isGitRepo(repoDir))) {
|
|
583
|
+
ledger.slots[name][info.placement] = { task, branch: info.branch, since: entry.assignedAt, state: 'stale-unmerged', slot: info.placement };
|
|
584
|
+
out.stale.push({ source: name, reason: '仓不可用,slot 标记 stale' });
|
|
585
|
+
remaining[name] = info;
|
|
586
|
+
continue;
|
|
587
|
+
}
|
|
588
|
+
// 候选基线:台账记录的创建时基线 + 当前 kit 基线(人可能中途改基线,见 2026-11-17 phm 事故)
|
|
589
|
+
const kitBase = source?.branch ?? null;
|
|
590
|
+
const r = await releaseSlot(repoDir, dir, { slot: info.placement, task, branch: info.branch }, info.base, ledger.slots, name, [info.base, kitBase]);
|
|
591
|
+
if (r.released) {
|
|
592
|
+
const via = r.matchedBase && r.matchedBase !== info.base ? `(按当前基线 ${r.matchedBase} 判定已合入)` : '';
|
|
593
|
+
out.released.push({ source: name, placement: info.placement, note: `slot 已切回基线并释放(目录保留复用)${via}` });
|
|
594
|
+
} else {
|
|
595
|
+
out.stale.push({ source: name, reason: r.reason });
|
|
596
|
+
remaining[name] = info;
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
if (Object.keys(remaining).length === 0) delete ledger.tasks[task];
|
|
600
|
+
else ledger.tasks[task] = { ...entry, repos: remaining };
|
|
601
|
+
writeWorkspaces(ws, ledger);
|
|
602
|
+
return out;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* 清任务残留(/hk-new、/hk-fix 重建同名任务前调用)。
|
|
607
|
+
* 不问合入状态:干净 slot → 切回基线、解绑、已合入的分支顺手删;脏 slot → 保持绑定并提示。
|
|
608
|
+
*/
|
|
609
|
+
export async function clearTaskWorkspaces(ws, kit, task) {
|
|
610
|
+
const ledger = readWorkspaces(ws);
|
|
611
|
+
const entry = ledger.tasks[task];
|
|
612
|
+
if (!entry) return { cleared: 0, notes: [] };
|
|
613
|
+
const notes = [];
|
|
614
|
+
let cleared = 0;
|
|
615
|
+
for (const [name, info] of Object.entries(entry.repos ?? {})) {
|
|
616
|
+
if (info.placement === 'main') continue; // 主工作树不做任何动作
|
|
617
|
+
const dir = path.join(worktreeRoot(ws, name), info.placement);
|
|
618
|
+
const source = (kit?.sources ?? []).find((s) => s.name === name);
|
|
619
|
+
const repoDir = source ? path.join(ws, source.path) : null;
|
|
620
|
+
ledger.slots[name] ??= {};
|
|
621
|
+
if (!fs.existsSync(dir) || !repoDir || !(await isGitRepo(repoDir))) {
|
|
622
|
+
delete ledger.slots[name]?.[info.placement];
|
|
623
|
+
cleared += 1;
|
|
624
|
+
continue;
|
|
625
|
+
}
|
|
626
|
+
if (await isDirty(dir)) {
|
|
627
|
+
notes.push(`slot ${info.placement}(${name})有未提交改动,保持绑定请人工处理`);
|
|
628
|
+
ledger.slots[name][info.placement] = { task, branch: info.branch, since: entry.assignedAt, state: 'bound', slot: info.placement };
|
|
629
|
+
continue;
|
|
630
|
+
}
|
|
631
|
+
await runGit(['checkout', '--detach', info.base], { cwd: dir });
|
|
632
|
+
if (await mergedStatus(repoDir, info.branch, info.base)) {
|
|
633
|
+
await runGit(['branch', '-d', info.branch], { cwd: repoDir });
|
|
634
|
+
}
|
|
635
|
+
delete ledger.slots[name][info.placement];
|
|
636
|
+
cleared += 1;
|
|
637
|
+
}
|
|
638
|
+
delete ledger.tasks[task];
|
|
639
|
+
writeWorkspaces(ws, ledger);
|
|
640
|
+
return { cleared, notes };
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* 基线分析镜像(设计期源码阅读,2026-11-16 真实场景驱动):
|
|
645
|
+
* BA/SA/RR 与 fix 质量门需要基于基线分支读源码,但主工作树常被在途任务占用、
|
|
646
|
+
* slot 是任务开发资源——分析是只读且基于确定性基线分支的,不值得占 slot。
|
|
647
|
+
* 为每仓维护常驻镜像 `.worktrees/<repo>/_baseline`(detached 停在基线分支 HEAD,
|
|
648
|
+
* 固定名不参与 slot-N 轮换),多任务分析共享同一镜像,零分配逻辑。
|
|
649
|
+
*
|
|
650
|
+
* 返回 { created, reused, updated, notes, mirrors: [{source, path, base, sha}] }。
|
|
651
|
+
*/
|
|
652
|
+
export async function ensureBaselineMirrors(ws, kit) {
|
|
653
|
+
const result = { created: [], reused: [], updated: [], notes: [], mirrors: [] };
|
|
654
|
+
for (const source of kit?.sources ?? []) {
|
|
655
|
+
const repoDir = path.join(ws, source.path);
|
|
656
|
+
if (!fs.existsSync(repoDir) || !(await isGitRepo(repoDir))) {
|
|
657
|
+
result.notes.push(`${source.name}:仓不可用,无分析镜像(设计期源码分析受限)`);
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
const base = await resolveBase(repoDir, source) ?? 'HEAD';
|
|
661
|
+
const baseSha = (await runGit(['rev-parse', '--short', base], { cwd: repoDir })).stdout.trim();
|
|
662
|
+
const dir = path.join(worktreeRoot(ws, source.name), '_baseline');
|
|
663
|
+
if (!fs.existsSync(dir)) {
|
|
664
|
+
excludeFromRootRepo(ws);
|
|
665
|
+
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
|
666
|
+
const r = await runGit(['worktree', 'add', '--detach', dir, base], { cwd: repoDir });
|
|
667
|
+
if (r.code !== 0) {
|
|
668
|
+
result.notes.push(`${source.name}:分析镜像创建失败:${(r.stderr || '').trim().split('\n')[0]}`);
|
|
669
|
+
continue;
|
|
670
|
+
}
|
|
671
|
+
result.created.push({ source: source.name, path: dir });
|
|
672
|
+
} else if (await isDirty(dir)) {
|
|
673
|
+
// 镜像被弄脏:不切换不更新,提示人工恢复(分析镜像是共享只读资源)
|
|
674
|
+
result.notes.push(`${source.name}:分析镜像有未提交改动(共享只读资源被污染),请人工处理:${dir}`);
|
|
675
|
+
} else {
|
|
676
|
+
const head = (await runGit(['rev-parse', base], { cwd: repoDir })).stdout.trim();
|
|
677
|
+
const cur = (await runGit(['rev-parse', 'HEAD'], { cwd: dir })).stdout.trim();
|
|
678
|
+
if (head !== cur) {
|
|
679
|
+
// 基线前进(主树 pull 过)→ 镜像跟随到最新基线提交
|
|
680
|
+
const co = await runGit(['checkout', '--detach', base], { cwd: dir });
|
|
681
|
+
if (co.code === 0) result.updated.push({ source: source.name, path: dir });
|
|
682
|
+
else result.notes.push(`${source.name}:分析镜像跟随基线失败:${(co.stderr || '').trim().split('\n')[0]}`);
|
|
683
|
+
} else {
|
|
684
|
+
result.reused.push({ source: source.name, path: dir });
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
const sha = (await runGit(['rev-parse', '--short', 'HEAD'], { cwd: dir })).stdout.trim();
|
|
688
|
+
result.mirrors.push({ source: source.name, path: dir, base, sha: sha || baseSha });
|
|
689
|
+
}
|
|
690
|
+
return result;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/** 「源码分析基线(只读镜像)」剧本节(注入 propose/fix 剧本;无镜像时返回空串不打扰)。 */
|
|
694
|
+
/**
|
|
695
|
+
* 任务专属分析基点(--base 按仓指定分支,2026-11-16 真实需求):
|
|
696
|
+
* "这个任务基于 backend 的 release/1.2、frontend 的 dev 分析"。
|
|
697
|
+
* 不切换共享镜像(镜像多任务共享,切换需长期锁定会把分析管线串行化)——
|
|
698
|
+
* 改为给该任务建专属只读工作区 `.worktrees/<仓>/_task-<任务>/`(detached 停在指定分支),
|
|
699
|
+
* 任务独占无锁、随任务归档回收。spec 落盘 .harness/deliverables/<任务>/analysis-base.json,
|
|
700
|
+
* 重跑 propose 不传 --base 时按已落盘 spec 幂等重建。
|
|
701
|
+
*/
|
|
702
|
+
const taskAnalysisDir = (ws, repo, task) => path.join(worktreeRoot(ws, repo), `_task-${task}`);
|
|
703
|
+
const taskAnalysisSpecPath = (ws, task) => path.join(harnessDir(ws), 'deliverables', task, 'analysis-base.json');
|
|
704
|
+
|
|
705
|
+
/** 列某仓可选分支(面板新建任务的分析基点下拉):本地 + origin 远端(去重、去 HEAD、上限 100)。 */
|
|
706
|
+
export async function listGitBranches(ws, source) {
|
|
707
|
+
const repoDir = path.join(ws, source.path);
|
|
708
|
+
if (!fs.existsSync(repoDir) || !(await isGitRepo(repoDir))) return [];
|
|
709
|
+
const out = new Set();
|
|
710
|
+
const local = await runGit(['branch', '--format=%(refname:short)'], { cwd: repoDir });
|
|
711
|
+
if (local.code === 0) for (const b of local.stdout.split('\n')) if (b.trim()) out.add(b.trim());
|
|
712
|
+
const remote = await runGit(['branch', '-r', '--format=%(refname:short)'], { cwd: repoDir });
|
|
713
|
+
if (remote.code === 0) {
|
|
714
|
+
for (const b of remote.stdout.split('\n')) {
|
|
715
|
+
const name = b.trim();
|
|
716
|
+
if (!name || name.endsWith('/HEAD')) continue;
|
|
717
|
+
out.add(name.replace(/^origin\//, ''));
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
return [...out].slice(0, 100);
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/** 列全部 source 仓的分支清单:{ <repo>: [branch…] }(面板新建任务模态框用)。 */
|
|
724
|
+
export async function listAllGitBranches(ws, kit) {
|
|
725
|
+
const out = {};
|
|
726
|
+
for (const source of kit?.sources ?? []) {
|
|
727
|
+
try { out[source.name] = await listGitBranches(ws, source); } catch { out[source.name] = []; }
|
|
728
|
+
}
|
|
729
|
+
return out;
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/** 解析 --base 旗标值:"backend:release/1.2,frontend:dev" → {backend:'release/1.2',...};坏段忽略。 */
|
|
733
|
+
export function parseBaseSpec(raw) {
|
|
734
|
+
const out = {};
|
|
735
|
+
if (typeof raw !== 'string') return out;
|
|
736
|
+
for (const pair of raw.split(',')) {
|
|
737
|
+
const idx = pair.indexOf(':');
|
|
738
|
+
if (idx <= 0) continue;
|
|
739
|
+
const name = pair.slice(0, idx).trim();
|
|
740
|
+
const branch = pair.slice(idx + 1).trim();
|
|
741
|
+
if (name && branch) out[name] = branch;
|
|
742
|
+
}
|
|
743
|
+
return out;
|
|
744
|
+
}
|
|
745
|
+
|
|
746
|
+
/** 建/切任务专属分析工作区。overrides 为空时读已落盘 spec。返回 {created,reused,switched,notes,worktrees}。 */
|
|
747
|
+
export async function ensureTaskAnalysisWorktrees(ws, kit, task, overrides = null) {
|
|
748
|
+
const result = { created: [], reused: [], switched: [], notes: [], worktrees: [] };
|
|
749
|
+
let spec = overrides && Object.keys(overrides).length > 0 ? overrides : null;
|
|
750
|
+
if (!spec) {
|
|
751
|
+
try { spec = JSON.parse(fs.readFileSync(taskAnalysisSpecPath(ws, task), 'utf8')); }
|
|
752
|
+
catch { return result; }
|
|
753
|
+
if (!spec || typeof spec !== 'object') return result;
|
|
754
|
+
}
|
|
755
|
+
// 落盘 spec(重跑 propose 不传 --base 也能幂等重建;任务归档时随活目录一起清掉)
|
|
756
|
+
fs.mkdirSync(path.dirname(taskAnalysisSpecPath(ws, task)), { recursive: true });
|
|
757
|
+
fs.writeFileSync(taskAnalysisSpecPath(ws, task), `${JSON.stringify(spec, null, 2)}\n`, 'utf8');
|
|
758
|
+
|
|
759
|
+
for (const [repoName, branch] of Object.entries(spec)) {
|
|
760
|
+
const source = (kit?.sources ?? []).find((s) => s.name === repoName);
|
|
761
|
+
const repoDir = source ? path.join(ws, source.path) : null;
|
|
762
|
+
if (!repoDir || !fs.existsSync(repoDir) || !(await isGitRepo(repoDir))) {
|
|
763
|
+
result.notes.push(`${repoName}:仓不可用,--base 分析工作区未建`);
|
|
764
|
+
continue;
|
|
765
|
+
}
|
|
766
|
+
// 分支解析:本地分支 → 远端 origin/<分支>;都没有 → 提示
|
|
767
|
+
let target = branch;
|
|
768
|
+
if ((await runGit(['rev-parse', '--verify', `refs/heads/${branch}`], { cwd: repoDir })).code !== 0) {
|
|
769
|
+
if ((await runGit(['rev-parse', '--verify', `refs/remotes/origin/${branch}`], { cwd: repoDir })).code === 0) {
|
|
770
|
+
target = `origin/${branch}`;
|
|
771
|
+
} else {
|
|
772
|
+
result.notes.push(`${repoName}:--base 分支 ${branch} 不存在(本地与 origin 均无)`);
|
|
773
|
+
continue;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
const dir = taskAnalysisDir(ws, repoName, task);
|
|
777
|
+
if (fs.existsSync(dir)) {
|
|
778
|
+
if (await isDirty(dir)) {
|
|
779
|
+
result.notes.push(`${repoName}:本任务分析工作区有未提交改动,请人工处理:${dir}`);
|
|
780
|
+
} else if ((await runGit(['rev-parse', 'HEAD'], { cwd: dir })).stdout.trim()
|
|
781
|
+
=== (await runGit(['rev-parse', target], { cwd: repoDir })).stdout.trim()) {
|
|
782
|
+
result.reused.push({ source: repoName, path: dir });
|
|
783
|
+
} else {
|
|
784
|
+
const co = await runGit(['checkout', '--detach', target], { cwd: dir });
|
|
785
|
+
if (co.code === 0) result.switched.push({ source: repoName, path: dir, branch });
|
|
786
|
+
else result.notes.push(`${repoName}:分析工作区切分支失败:${(co.stderr || '').trim().split('\n')[0]}`);
|
|
787
|
+
}
|
|
788
|
+
} else {
|
|
789
|
+
excludeFromRootRepo(ws);
|
|
790
|
+
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
|
791
|
+
const r = await runGit(['worktree', 'add', '--detach', dir, target], { cwd: repoDir });
|
|
792
|
+
if (r.code !== 0) {
|
|
793
|
+
result.notes.push(`${repoName}:分析工作区创建失败:${(r.stderr || '').trim().split('\n')[0]}`);
|
|
794
|
+
continue;
|
|
795
|
+
}
|
|
796
|
+
result.created.push({ source: repoName, path: dir, branch });
|
|
797
|
+
}
|
|
798
|
+
result.worktrees.push({
|
|
799
|
+
source: repoName, path: dir, branch,
|
|
800
|
+
sha: (await runGit(['rev-parse', '--short', 'HEAD'], { cwd: dir })).stdout.trim(),
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
return result;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/** 回收任务专属分析工作区(归档/重建清理;任务独占无合入问题,干净即删,脏则留给人)。 */
|
|
807
|
+
export async function removeTaskAnalysisWorktrees(ws, kit, task) {
|
|
808
|
+
const out = { removed: 0, notes: [] };
|
|
809
|
+
for (const source of kit?.sources ?? []) {
|
|
810
|
+
const dir = taskAnalysisDir(ws, source.name, task);
|
|
811
|
+
const repoDir = path.join(ws, source.path);
|
|
812
|
+
if (!fs.existsSync(dir)) continue;
|
|
813
|
+
if (!(await isGitRepo(repoDir))) { fs.rmSync(dir, { recursive: true, force: true }); out.removed += 1; continue; }
|
|
814
|
+
if (await isDirty(dir)) {
|
|
815
|
+
out.notes.push(`${source.name}:任务分析工作区有未提交改动,保留待人工处理:${dir}`);
|
|
816
|
+
continue;
|
|
817
|
+
}
|
|
818
|
+
await runGit(['worktree', 'remove', '--force', dir], { cwd: repoDir });
|
|
819
|
+
out.removed += 1;
|
|
820
|
+
}
|
|
821
|
+
return out;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
export function renderAnalysisNotice(res, taskRes = null) {
|
|
825
|
+
if ((!res || (res.mirrors?.length ?? 0) === 0) && (taskRes?.worktrees?.length ?? 0) === 0) return '';
|
|
826
|
+
const lines = ['### 源码分析基线(只读,设计期专用)'];
|
|
827
|
+
if (res && (res.mirrors?.length ?? 0) > 0) {
|
|
828
|
+
lines.push('- BA/SA/RR 与质量门评估**只读**以下镜像(常驻检出基线分支,多任务共享):',
|
|
829
|
+
...res.mirrors.map((m) => ` - ${m.source} → \`${m.path}\`(基线 \`${m.base}\` @ ${m.sha})`));
|
|
830
|
+
}
|
|
831
|
+
if ((taskRes?.worktrees?.length ?? 0) > 0) {
|
|
832
|
+
lines.push('- 本任务**专属**分析工作区(--base 指定,任务独占,勿改勿切分支):',
|
|
833
|
+
...taskRes.worktrees.map((w) => ` - ${w.source} → \`${w.path}\`(\`${w.branch}\` @ ${w.sha})`));
|
|
834
|
+
}
|
|
835
|
+
lines.push('- 禁止修改/切换上述目录;也不要读 \`services/\` 主工作树与其他任务 slot 的未提交改动——那些不属于本任务的分析上下文。',
|
|
836
|
+
'- 若需调整共享镜像的分析基点:让人在面板设置页调整该仓基线分支后重跑 /hk-propose(镜像自动跟随新基线)。');
|
|
837
|
+
for (const n of [...(res?.notes ?? []), ...(taskRes?.notes ?? [])]) lines.push(`- ⚠️ ${n}`);
|
|
838
|
+
return lines.join('\n');
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/**
|
|
842
|
+
* 生成「并行工作区」剧本节(纯函数):告知 PM/Worker 各仓工作区在哪、红线是什么。
|
|
843
|
+
* 无分配(无 sources)时返回空串。
|
|
844
|
+
*/
|
|
845
|
+
export function renderWorkspaceNotice(res, task) {
|
|
846
|
+
const lines = [];
|
|
847
|
+
const assigned = res?.assigned ?? [];
|
|
848
|
+
if (assigned.length === 0 && (res?.refused ?? []).length === 0) return '';
|
|
849
|
+
lines.push('### 并行工作区(源码红线)');
|
|
850
|
+
lines.push('- 各仓工作区分配:**developer 写源码只进分配给自己的目录,其余目录(主工作树/其他 slot/其他仓)一律只读**:');
|
|
851
|
+
for (const w of assigned) {
|
|
852
|
+
const where = w.placement === 'main'
|
|
853
|
+
? (w.branch ? `主工作树 \`${w.path}\`(当前只有本任务在该仓开发;开工前从基线 \`${w.base}\` 新建分支 \`${w.branch}\`)` : `主工作树 \`${w.path}\`(非 git 仓,直接工作)`)
|
|
854
|
+
: `池化 worktree \`${w.path}\`(分支 \`${w.branch}\`,内核已切好;slot 常驻复用,不要删目录)`;
|
|
855
|
+
lines.push(` - ${w.source} → ${where}`);
|
|
856
|
+
}
|
|
857
|
+
lines.push('- worktree slot 由内核在归档时切回基线释放(不删目录,依赖/构建缓存保持热态);不要手工删 slot 目录、不要在里面放与工作无关的私货。');
|
|
858
|
+
for (const o of res?.overlaps ?? []) {
|
|
859
|
+
lines.push(`- ⚠️ 与在途任务 **${o.task}** 在 ${o.source} 上已改文件重叠(${o.files.slice(0, 5).join('、')}${o.files.length > 5 ? ' 等' : ''}):两任务同文件并发修改必冲突,开工前先向人确认裁决顺序。`);
|
|
860
|
+
}
|
|
861
|
+
for (const n of res?.notes ?? []) {
|
|
862
|
+
lines.push(`- ⚠️ ${n}`);
|
|
863
|
+
}
|
|
864
|
+
for (const f of res?.refused ?? []) {
|
|
865
|
+
lines.push(`- ⛔ ${f.source}:${f.reason}`);
|
|
866
|
+
}
|
|
867
|
+
return lines.join('\n');
|
|
868
|
+
}
|