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.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +321 -2
  3. package/README.zh-CN.md +278 -0
  4. package/client.js +1272 -0
  5. package/cordis.patch.yml +4 -0
  6. package/docs/DETAIL.en.md +97 -0
  7. package/docs/DETAIL.md +73 -0
  8. package/docs/assets/ui-new-task.png +0 -0
  9. package/docs/assets/ui-onboarding.png +0 -0
  10. package/docs/assets/ui-war-room.png +0 -0
  11. package/icon.svg +7 -0
  12. package/index.js +49 -0
  13. package/kernel/advance.js +96 -0
  14. package/kernel/bindings.js +24 -0
  15. package/kernel/commands.js +927 -0
  16. package/kernel/env.js +64 -0
  17. package/kernel/exec.js +41 -0
  18. package/kernel/flows.js +89 -0
  19. package/kernel/guards.js +79 -0
  20. package/kernel/miniyaml.js +133 -0
  21. package/kernel/models.js +104 -0
  22. package/kernel/panel.js +1103 -0
  23. package/kernel/paths.js +53 -0
  24. package/kernel/roles.js +67 -0
  25. package/kernel/setup.js +644 -0
  26. package/kernel/state.js +59 -0
  27. package/kernel/steer.js +27 -0
  28. package/kernel/sync.js +140 -0
  29. package/kernel/te.js +122 -0
  30. package/kernel/worktree.js +868 -0
  31. package/locale/en.json +14 -0
  32. package/locale/zh.json +14 -0
  33. package/package.json +63 -4
  34. package/packs/ai-coding/agents/business-analyst.md +90 -0
  35. package/packs/ai-coding/agents/code-reviewer.md +156 -0
  36. package/packs/ai-coding/agents/developer.md +147 -0
  37. package/packs/ai-coding/agents/project-manager.md +190 -0
  38. package/packs/ai-coding/agents/readiness-reviewer.md +123 -0
  39. package/packs/ai-coding/agents/solution-architect.md +122 -0
  40. package/packs/ai-coding/agents/test-engineer.md +230 -0
  41. package/packs/ai-coding/assets/scripts/check_codegraph.py +215 -0
  42. package/packs/ai-coding/assets/scripts/codebase_guide_init.py +330 -0
  43. package/packs/ai-coding/assets/scripts/env_auto.py +612 -0
  44. package/packs/ai-coding/assets/scripts/harness.py +38 -0
  45. package/packs/ai-coding/assets/scripts/harness_init.py +193 -0
  46. package/packs/ai-coding/assets/scripts/lib.py +1011 -0
  47. package/packs/ai-coding/assets/scripts/run_field.py +295 -0
  48. package/packs/ai-coding/assets/scripts/spec_lint.py +247 -0
  49. package/packs/ai-coding/assets/scripts/update_board.py +524 -0
  50. package/packs/ai-coding/assets/scripts/verify.py +184 -0
  51. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/CODE_STANDARDS.tmpl +44 -0
  52. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/app-CLAUDE.tmpl +34 -0
  53. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/build.tmpl +8 -0
  54. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/module-CLAUDE.tmpl +42 -0
  55. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/root-CLAUDE.tmpl +41 -0
  56. package/packs/ai-coding/assets/templates/java/maven/CODE_STANDARDS.tmpl +44 -0
  57. package/packs/ai-coding/assets/templates/java/maven/build.tmpl +9 -0
  58. package/packs/ai-coding/assets/templates/java/maven/root-CLAUDE.tmpl +38 -0
  59. package/packs/ai-coding/assets/templates/java/maven-multimodule/CODE_STANDARDS.tmpl +44 -0
  60. package/packs/ai-coding/assets/templates/java/maven-multimodule/build.tmpl +9 -0
  61. package/packs/ai-coding/assets/templates/java/maven-multimodule/module-CLAUDE.tmpl +40 -0
  62. package/packs/ai-coding/assets/templates/java/maven-multimodule/root-CLAUDE.tmpl +38 -0
  63. package/packs/ai-coding/assets/templates/javascript/mobile-app/CODE_STANDARDS.tmpl +51 -0
  64. package/packs/ai-coding/assets/templates/javascript/mobile-app/build.tmpl +8 -0
  65. package/packs/ai-coding/assets/templates/javascript/mobile-app/root-CLAUDE.tmpl +36 -0
  66. package/packs/ai-coding/assets/templates/javascript/uniapp/CODE_STANDARDS.tmpl +69 -0
  67. package/packs/ai-coding/assets/templates/javascript/uniapp/build.tmpl +8 -0
  68. package/packs/ai-coding/assets/templates/javascript/uniapp/root-CLAUDE.tmpl +56 -0
  69. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/CODE_STANDARDS.tmpl +51 -0
  70. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/app-CLAUDE.tmpl +36 -0
  71. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/build.tmpl +8 -0
  72. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/root-CLAUDE.tmpl +34 -0
  73. package/packs/ai-coding/flows/_router.yml +14 -0
  74. package/packs/ai-coding/flows/bugfix.yml +37 -0
  75. package/packs/ai-coding/flows/fix.yml +44 -0
  76. package/packs/ai-coding/flows/init.yml +83 -0
  77. package/packs/ai-coding/flows/new.yml +29 -0
  78. package/packs/ai-coding/flows/quick.yml +40 -0
  79. package/packs/ai-coding/flows/refactor.yml +50 -0
  80. package/packs/ai-coding/flows/standard.yml +49 -0
  81. package/packs/ai-coding/rules/code-standards.md +30 -0
  82. package/packs/ai-coding/rules/core.md +83 -0
  83. package/packs/ai-coding/templates/bugfix.md +29 -0
  84. package/packs/ai-coding/templates/memory-entry.md +46 -0
  85. package/packs/ai-coding/templates/proposal.md +47 -0
  86. package/packs/ai-coding/templates/spec-template.md +34 -0
  87. package/screenshots.json +5 -0
@@ -0,0 +1,927 @@
1
+ // /hk-* command registrations. Commands follow the plan-mode precedent:
2
+ // handlers do deterministic file/git work themselves, then steer the
3
+ // receiving agent with a compiled orchestration prompt for the LLM part.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { wsRoot, readKit, writeKit, defaultKit, harnessDir, packDir, protectedSourcePaths } from './paths.js';
8
+ import { runGit, run } from './exec.js';
9
+ import { steer } from './steer.js';
10
+ import { resolveRole, listRoles, readCoreRules } from './roles.js';
11
+ import { loadFlow, compileFlowPrompt } from './flows.js';
12
+ import { activeTasks, taskIsPlanning } from './state.js';
13
+ import { assetsLayout, syncAssets } from './sync.js';
14
+ import { claimTask } from './panel.js';
15
+ import { clearAdvanceMarks } from './advance.js';
16
+ import { ensureTaskWorkspaces, releaseTaskWorkspaces, clearTaskWorkspaces, renderWorkspaceNotice, ensureBaselineMirrors, renderAnalysisNotice, ensureTaskAnalysisWorktrees, removeTaskAnalysisWorktrees, parseBaseSpec, describeMainWorktree, recordDecision, clearDecision, readWorkspaces, mergeTaskBranches } from './worktree.js';
17
+ import { acquireTestEnv, releaseTestEnv, describeTestEnv } from './te.js';
18
+ import { recordTaskSession } from './bindings.js';
19
+ import { addSource, runInit, formatInitReport, guessRole, boardTemplate } from './setup.js';
20
+ import { dispatchSection, describeWorkerModel } from './models.js';
21
+
22
+ const ok = (text) => ({ kind: 'success', text });
23
+ const err = (text) => ({ kind: 'error', text });
24
+ // 结构化决策点(B 方案):需要人裁决但选项明确的场景(如工作区外来占用)。
25
+ // 会话路由按 text 渲染;面板路由识别 kind 后渲染可点选项。options[].line 可直接重跑。
26
+ const decision = (text, code, options) => ({ kind: 'decision', text, code, options });
27
+
28
+ /** 把任务绑定到执行命令的当前会话(覆盖手敲命令等面板路由不在场的入口;取不到 id 则跳过)。 */
29
+ function bindCurrentSession(ws, task, agent) {
30
+ const sid = agent?.session?.id ?? agent?.id;
31
+ if (typeof sid !== 'string' || sid.length === 0) return;
32
+ try { recordTaskSession(ws, task, sid); } catch { /* 绑定失败不阻断命令 */ }
33
+ }
34
+
35
+ function parseArgs(raw) {
36
+ const tokens = raw.trim().split(/\s+/).filter(Boolean);
37
+ const flags = {};
38
+ const positional = [];
39
+ for (let i = 0; i < tokens.length; i += 1) {
40
+ const t = tokens[i];
41
+ if (t.startsWith('--')) {
42
+ const key = t.slice(2);
43
+ if (i + 1 < tokens.length && !tokens[i + 1].startsWith('--')) {
44
+ flags[key] = tokens[i + 1];
45
+ i += 1;
46
+ } else {
47
+ flags[key] = true;
48
+ }
49
+ } else {
50
+ positional.push(t);
51
+ }
52
+ }
53
+ return { flags, positional };
54
+ }
55
+
56
+ // ----------------------------------------------------------- M2 shared helpers
57
+ const PROFILES = ['standard', 'quick', 'bugfix', 'refactor'];
58
+ const APPROVAL1 = /审批\s*1[^0-9\n]{0,20}(通过|PASS)/i;
59
+ const STATUS_APPROVED = /状态[**]*[::][ \t]*`?approved(?![\w-])/im;
60
+ /** 任务名即活目录名:中英文/数字开头,可含 - 与 _。 */
61
+ const TASK_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/; // 英文/数字开头,可含 -_(中文名走 --auto 派生 slug)
62
+
63
+ /** --auto:从描述派生任务名(英文词 kebab;纯中文回退时间戳;撞名自动加序号)。 */
64
+ function autoTaskName(ws, desc) {
65
+ const words = (String(desc).match(/[A-Za-z][A-Za-z0-9]*/g) || []).slice(0, 4);
66
+ let base = words.join('-').toLowerCase().replace(/^-+|-+$/g, '');
67
+ if (!base) {
68
+ const d = new Date();
69
+ const p = (n) => String(n).padStart(2, '0');
70
+ base = `auto-${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`;
71
+ }
72
+ base = base.slice(0, 40);
73
+ let name = base;
74
+ for (let i = 2; fs.existsSync(path.join(harnessDir(ws), 'deliverables', name)); i++) name = `${base}-${i}`;
75
+ return name;
76
+ }
77
+
78
+ /** Extract the declared profile from proposal.md; template option lines ("A | B") are ignored. */
79
+ function readProfile(proposal) {
80
+ for (const line of proposal.split('\n')) {
81
+ const m = line.match(/profile[**]*[::][ \t]*`?\**\s*(standard|quick|bugfix|refactor)(?![\w-])/i);
82
+ if (m && !line.slice(line.indexOf(m[1]) + m[1].length).includes('|')) return m[1].toLowerCase();
83
+ }
84
+ return 'standard';
85
+ }
86
+
87
+ /**
88
+ * Verdict of the LAST conclusion section (`## 结论` / `### 结论` / `## 就绪自评`).
89
+ * Prefers an explicit 「结论:PASS/BLOCK」 line; falls back to the last PASS/BLOCK
90
+ * token in the section. Returns 'PASS' | 'BLOCK' | null.
91
+ */
92
+ function lastConclusion(text) {
93
+ const matches = [...text.matchAll(/^#{2,3}\s*\**\s*(结论|就绪自评)\s*\**\s*$/gm)];
94
+ if (matches.length === 0) return null;
95
+ const last = matches[matches.length - 1];
96
+ const rest = text.slice(last.index + last[0].length);
97
+ const next = rest.search(/^#{1,4}\s/m);
98
+ const section = next === -1 ? rest : rest.slice(0, next);
99
+ const explicit = [...section.matchAll(/结论[**]*[::][ \t]*`?\**\s*(PASS|BLOCK)(?![\w-])/gi)];
100
+ if (explicit.length > 0) return explicit[explicit.length - 1][1].toUpperCase();
101
+ const tokens = [...section.matchAll(/(PASS|BLOCK)(?![\w-])/g)];
102
+ return tokens.length > 0 ? tokens[tokens.length - 1][1].toUpperCase() : null;
103
+ }
104
+
105
+ /** Unique workers of a flow phase, in stage order: [{ role, stageModel }]. */
106
+ function flowWorkers(flow, phase) {
107
+ const seen = new Map();
108
+ for (const s of flow.stages ?? []) {
109
+ if (!s.worker) continue;
110
+ if (phase && s.phase && s.phase !== phase) continue;
111
+ if (!seen.has(s.worker)) seen.set(s.worker, { role: s.worker, stageModel: s.model ?? null });
112
+ }
113
+ return [...seen.values()];
114
+ }
115
+
116
+ /** Build worker file refs + model-routing rows for a flow phase. */
117
+ function buildWorkerContext(ws, kit, flow, phase) {
118
+ const refs = [];
119
+ const modelRows = [];
120
+ for (const w of flowWorkers(flow, phase)) {
121
+ const r = resolveRole(ws, kit, w.role);
122
+ const logical = w.stageModel ?? r?.meta?.model ?? null;
123
+ refs.push(
124
+ r
125
+ ? `- ${w.role}:派发前用 read 工具读 \`${r.file}\`(${r.origin === 'workspace' ? '工作区覆写' : '内容包默认'})全文,内嵌进 Worker prompt;模型:${describeWorkerModel(kit, w.role, logical)}`
126
+ : `- ⚠️ ${w.role}:角色定义缺失,按通用职责派发;模型:${describeWorkerModel(kit, w.role, logical)}`,
127
+ );
128
+ modelRows.push({ role: w.role, logical });
129
+ }
130
+ return { refs: refs.join('\n'), modelRows };
131
+ }
132
+
133
+ /**
134
+ * 看板行健壮解析(与 panel.js parseBoard、update_board.py parse_row 三方同源):
135
+ * 超列时溢出并入「续接提示」(管道符只可能从自由文本混入),不足 7 格补 —。
136
+ */
137
+ function parseBoardRow(line) {
138
+ const cells = line.trim().replace(/^\||\|$/g, '').split('|').map((c) => c.trim());
139
+ if (cells.length > 7) return [...cells.slice(0, 6), cells.slice(6).join(' / ')];
140
+ while (cells.length < 7) cells.push('—');
141
+ return cells;
142
+ }
143
+
144
+ /**
145
+ * Append/update one board row for the task(7 列契约)。
146
+ * 内核只机械更新 [1]状态 与 [5]上次活动;Profile/Apply进度/分支/续接提示由 PM/Worker 按剧本维护,
147
+ * 更新既有行时保留其余列。
148
+ */
149
+ export function updateBoard(ws, task, status, opts = {}) {
150
+ const boardDir = path.join(harnessDir(ws), 'tasks');
151
+ fs.mkdirSync(boardDir, { recursive: true });
152
+ const board = path.join(boardDir, 'board.md');
153
+ if (!fs.existsSync(board)) {
154
+ fs.writeFileSync(board, boardTemplate(), 'utf8');
155
+ }
156
+ const d = new Date();
157
+ const p2 = (n) => String(n).padStart(2, '0');
158
+ const date = `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())} ${p2(d.getHours())}:${p2(d.getMinutes())}`;
159
+ const text = fs.readFileSync(board, 'utf8');
160
+ const rowRe = new RegExp(`^\\| ${task} \\|.*$`, 'm');
161
+ if (rowRe.test(text)) {
162
+ const updated = text.replace(rowRe, (line) => {
163
+ const cells = parseBoardRow(line);
164
+ cells[1] = status;
165
+ cells[5] = date;
166
+ return `| ${cells.join(' | ')} |`;
167
+ });
168
+ fs.writeFileSync(board, updated, 'utf8');
169
+ } else {
170
+ // 新行:fix 直通三态可直接定档并写初始链(全 … 待做),其余 profile — 待 propose 定档。
171
+ // 必须插到表格末尾(最后一个表格行之后)而非盲 appendFileSync——文件尾部有
172
+ // 「续接提示编写规范」引用块,盲追加会把行落到表格外(2026-11-13 cluster-monitor 踩中)。
173
+ const newRow = `| ${task} | ${status} | ${opts.profile ?? '—'} | ${opts.apply ?? '—'} | — | ${date} | — |`;
174
+ const lines = text.split('\n');
175
+ let lastRow = -1;
176
+ for (let i = 0; i < lines.length; i++) if (/^\s*\|/.test(lines[i])) lastRow = i;
177
+ if (lastRow >= 0) {
178
+ lines.splice(lastRow + 1, 0, newRow);
179
+ fs.writeFileSync(board, lines.join('\n'), 'utf8');
180
+ } else {
181
+ fs.appendFileSync(board, `${newRow}\n`, 'utf8');
182
+ }
183
+ }
184
+ }
185
+
186
+ /** Infer the task name when omitted: exactly one active task wins. */
187
+ function inferTask(ws, positional, usage) {
188
+ if (positional[0]) return { task: positional[0] };
189
+ const act = activeTasks(ws);
190
+ if (act.length === 1) return { task: act[0] };
191
+ return { error: `${usage}${act.length ? `(当前活跃任务:${act.join('、')})` : ''}` };
192
+ }
193
+
194
+ // ---------------------------------------------------------------- /hk-setup
195
+ async function hkSetup({ agent, rawInput }) {
196
+ const ws = wsRoot(agent);
197
+ const { flags, positional } = parseArgs(rawInput);
198
+ let kit = readKit(ws) ?? defaultKit();
199
+
200
+ if (!flags.add) {
201
+ const lines = ['## Harness Kit 工作区仓库清单', ''];
202
+ if (kit.sources.length === 0) lines.push('(空)使用 `/hk-setup --add <git-url> [--name n] [--path p] [--branch b]` 登记或克隆代码仓库。');
203
+ for (const s of kit.sources) {
204
+ const exists = fs.existsSync(path.join(ws, s.path));
205
+ lines.push(`- **${s.name}** (${s.role ?? 'backend'}) → \`${s.path}\` ${exists ? '✅ 已存在' : '❌ 缺失'}${s.url ? ` — ${s.url}` : ''}${s.branch ? ` [${s.branch}]` : ''}`);
206
+ }
207
+ lines.push('', '路径已存在的仓库直接登记;不存在时会先 `git clone`(普通 clone)。之后运行 `/hk-init`。');
208
+ return ok(lines.join('\n'));
209
+ }
210
+
211
+ const r = await addSource(ws, { url: flags.add, name: flags.name, path: flags.path, role: flags.role, branch: flags.branch });
212
+ if (!r.ok) return err(r.error);
213
+ return ok(r.lines.join('\n'));
214
+ }
215
+
216
+ // ----------------------------------------------------------------- /hk-init
217
+ async function hkInit({ agent, rawInput }) {
218
+ const ws = wsRoot(agent);
219
+ const { flags } = parseArgs(rawInput);
220
+ const r = await runInit(ws, { assets: flags.assets, branch: flags.branch });
221
+ if (!r.ok) return err(r.error);
222
+ const { kit } = r;
223
+
224
+ // 5. steer the init orchestration prompt (original /harness-init Steps 1-7b)
225
+ let steered = false;
226
+ if (kit.sources.length > 0) {
227
+ const loaded = loadFlow(ws, kit, 'init');
228
+ if (loaded) {
229
+ const pm = resolveRole(ws, kit, 'project-manager');
230
+ const prompt = compileFlowPrompt(loaded.flow, {
231
+ task: '工程初始化',
232
+ desc: '探测 services/ 下子工程的技术栈与结构,按模板生成子工程文档(CLAUDE.md / build.json / CODE_STANDARDS.md / 模块级 CLAUDE.md);再与人协作补齐各端 build.json 的编译/启动命令并实跑一次编译+启动验证(成功后停掉服务);最后建 CodeGraph 代码索引 —— 原 /harness-init 流程',
233
+ flowFile: loaded.file,
234
+ artifacts: '各子工程(生成清单见 .harness/.logs/workflow/harness-init-plan.json)',
235
+ roleSections: pm ? `### PM 角色(你立即切换到此身份)\n\n${pm.body}` : undefined,
236
+ rules: readCoreRules(kit),
237
+ });
238
+ steer(agent, prompt);
239
+ steered = true;
240
+ }
241
+ }
242
+
243
+ return ok(formatInitReport(r, { steered }));
244
+ }
245
+
246
+ // ------------------------------------------------------------------ /hk-fix
247
+ async function hkFix({ agent, rawInput }) {
248
+ const ws = wsRoot(agent);
249
+ const kit = readKit(ws);
250
+ if (!kit) return err('尚未初始化:请先运行 `/hk-init`。');
251
+ const { flags, positional } = parseArgs(rawInput);
252
+ // parseArgs 会把 --auto 后首个词吞为旗标值;先还原完整词序再解构
253
+ const words = typeof flags.auto === 'string' ? [flags.auto, ...positional] : positional;
254
+ let [task, ...descParts] = words;
255
+ if (flags.auto) task = null;
256
+ const desc = (flags.auto ? words : descParts).join(' ') || '(未提供描述,PM 须先向人反问澄清)';
257
+ const autoNamed = !!flags.auto;
258
+ if (autoNamed) task = autoTaskName(ws, desc);
259
+ if (!task || !TASK_NAME_RE.test(task)) return err('用法:/hk-fix [任务名] <一句话描述> [--full|--light] [--auto](任务名限英文/数字/-_;留空或 --auto 按描述自动生成)');
260
+
261
+ const taskDir = path.join(harnessDir(ws), 'deliverables', task);
262
+ if (fs.existsSync(taskDir)) {
263
+ // 空目录(上次执行中断/手动清理后的残留)直接复用;有内容才判撞名
264
+ if (fs.readdirSync(taskDir).length > 0) return err(`任务 ${task} 的活目录已存在:换任务名,或先归档/清理。`);
265
+ } else {
266
+ fs.mkdirSync(taskDir, { recursive: true });
267
+ }
268
+
269
+ // scaffold bugfix.md from the pack template
270
+ const tplPath = path.join(packDir(kit), 'templates', 'bugfix.md');
271
+ const tpl = fs.existsSync(tplPath) ? fs.readFileSync(tplPath, 'utf8') : '# Bugfix:{{task}}\n\n## 问题描述\n{{desc}}\n\n## 质量门\n\n## R0\n- 质量门裁决:\n';
272
+ const date = new Date().toISOString().slice(0, 10);
273
+ let doc = tpl.replaceAll('{{task}}', task).replaceAll('{{desc}}', desc).replaceAll('{{date}}', date);
274
+ const preVerdict = flags.full ? '--full' : flags.light ? '轻量' : null;
275
+ if (preVerdict) doc = doc.replace(/质量门裁决:[^\n]*/, `质量门裁决:${preVerdict}(调用时预声明)`);
276
+ fs.writeFileSync(path.join(taskDir, 'bugfix.md'), doc, 'utf8');
277
+
278
+ // resolve roles: PM embedded; workers referenced by file for just-in-time read
279
+ const pm = resolveRole(ws, kit, 'project-manager');
280
+ const loaded = loadFlow(ws, kit, 'fix');
281
+ if (!loaded) return err('找不到 fix 流程定义(packs/ai-coding/flows/fix.yml 或 .harness/flows/fix.yml)。');
282
+ const wctx = buildWorkerContext(ws, kit, loaded.flow, null);
283
+ const workerRefs = wctx.refs || '- (Worker 角色定义缺失)';
284
+
285
+ // 并行开发:fix 也会改源码——清同名残留 + 分配工作区(fix/harness-<task>)
286
+ clearDecision(ws, task);
287
+ await clearTaskWorkspaces(ws, kit, task);
288
+ await removeTaskAnalysisWorktrees(ws, kit, task);
289
+ const wt = await ensureTaskWorkspaces(ws, kit, task, { branchPrefix: 'fix', forceSlot: flags.slot === true });
290
+ if (wt.refused.length > 0) {
291
+ const details = [];
292
+ for (const f of wt.refused) {
293
+ const source = (kit.sources ?? []).find((s) => s.name === f.source);
294
+ if (source) details.push(await describeMainWorktree(ws, source));
295
+ }
296
+ const text = `工作区分配需要人工裁决(不开发工):\n${wt.refused.map((f) => `- ${f.source}:${f.reason}`).join('\n')}` +
297
+ (details.length > 0 ? `\n\n主工作树现场:\n${details.join('\n\n')}` : '');
298
+ const options = [
299
+ { label: '在隔离 slot 开发', line: `/hk-fix ${task} --slot`, primary: true },
300
+ { label: '已处理主树,按原样重跑', line: `/hk-fix ${task}` },
301
+ ];
302
+ recordDecision(ws, task, { code: 'workspace-foreign', text, options });
303
+ return decision(text, 'workspace-foreign', options);
304
+ }
305
+ clearDecision(ws, task);
306
+ const wtNotice = renderWorkspaceNotice(wt, task);
307
+ // 质量门评估可能读源码:同样给只读基线镜像 + --base 任务专属分析区
308
+ const mirrors = await ensureBaselineMirrors(ws, kit);
309
+ const taskAnalysis = await ensureTaskAnalysisWorktrees(ws, kit, task, parseBaseSpec(flags.base));
310
+ const mirrorNotice = renderAnalysisNotice(mirrors, taskAnalysis);
311
+
312
+ const prompt = compileFlowPrompt(loaded.flow, {
313
+ task,
314
+ desc,
315
+ flowFile: loaded.file,
316
+ artifacts: `.harness/deliverables/${task}/`,
317
+ roleSections: [
318
+ pm ? `### PM 角色(你立即切换到此身份)\n\n${pm.body}` : '(缺 project-manager 角色定义,按通用 PM 职责执行)',
319
+ '',
320
+ '### Worker 角色(派发时逐个读取并内嵌)',
321
+ workerRefs,
322
+ ].join('\n'),
323
+ rules: [readCoreRules(kit), wtNotice, mirrorNotice, TE_NOTICE].filter(Boolean).join('\n\n'),
324
+ dispatchSection: dispatchSection(kit, wctx.modelRows),
325
+ });
326
+
327
+ steer(agent, prompt);
328
+ // fix 直通三态定档:--full → fix-full;--light → fix-light(CR/TE 直接标 —);未声明 → fix(直通·裁决未定,质量门裁决后 PM 改写)
329
+ const fixProfile = flags.full ? 'fix-full' : flags.light ? 'fix-light' : 'fix';
330
+ const initChain = flags.light ? 'R1:质量门▶ Dev… CR— TE— 验证…' : 'R1:质量门▶ Dev… CR… TE… 验证…';
331
+ updateBoard(ws, task, 'PENDING', { profile: fixProfile, apply: initChain });
332
+ clearAdvanceMarks(ws, task);
333
+ bindCurrentSession(ws, task, agent);
334
+ const wtSummary = wt.assigned.length > 0 ? `\n- 工作区分配:${wt.assigned.map((w) => `${w.source} → ${w.placement === 'main' ? '主工作树' : w.placement}${w.branch ? `(\`${w.branch}\` ← \`${w.base}\`)` : ''}`).join(';')}` : '';
335
+ return ok(`fix 任务 **${task}** 已启动:\n- 活目录 \`.harness/deliverables/${task}/bugfix.md\` 已生成${autoNamed ? '\n- 任务名由描述自动生成;如需更名请现在告诉我' : ''}\n- 看板已登记(PENDING,profile=${fixProfile})\n- 执行剧本已提交给 PM(本会话),从「分支准备」阶段开始${wtSummary}${preVerdict ? `\n- 质量门已预声明:${preVerdict}` : '\n- 质量门将由 PM 评估后交你裁决(裁决后 PM 须把看板 profile 改写为 fix-full / fix-light)'}`);
336
+ }
337
+
338
+ // ------------------------------------------------------------------ /hk-new
339
+ // Bootstrap: scaffold proposal.md + register board + steer clarification flow.
340
+ async function hkNew({ agent, rawInput }) {
341
+ const ws = wsRoot(agent);
342
+ const kit = readKit(ws);
343
+ if (!kit) return err('尚未初始化:请先运行 `/hk-init`。');
344
+ const { flags, positional } = parseArgs(rawInput);
345
+ // parseArgs 会把 --auto 后首个词吞为旗标值;先还原完整词序再解构
346
+ const words = typeof flags.auto === 'string' ? [flags.auto, ...positional] : positional;
347
+ let [task, ...descParts] = words;
348
+ if (flags.auto) task = null;
349
+ const desc = (flags.auto ? words : descParts).join(' ') || '(未提供描述,PM 须先向人反问澄清)';
350
+ const autoNamed = !!flags.auto;
351
+ if (autoNamed) task = autoTaskName(ws, desc);
352
+ if (!task || !TASK_NAME_RE.test(task)) {
353
+ return err('用法:/hk-new [任务名] <需求描述> [--file <需求文件>] [--auto](任务名限英文/数字/-_;留空或 --auto 按描述自动生成)');
354
+ }
355
+
356
+ const taskDir = path.join(harnessDir(ws), 'deliverables', task);
357
+ if (fs.existsSync(taskDir)) {
358
+ // 空目录(上次执行中断/手动清理后的残留)直接复用;有内容才判撞名
359
+ if (fs.readdirSync(taskDir).length > 0) return err(`任务 ${task} 的活目录已存在:换任务名,或先归档/清理。`);
360
+ } else {
361
+ fs.mkdirSync(taskDir, { recursive: true });
362
+ }
363
+ // 任务重建:先清上一化身的自动续接标记与同名工作区/分析区残留(须在 --base 建分析区之前,否则刚建的会被当残留回收)
364
+ clearAdvanceMarks(ws, task);
365
+ clearDecision(ws, task);
366
+ await clearTaskWorkspaces(ws, kit, task);
367
+ await removeTaskAnalysisWorktrees(ws, kit, task);
368
+
369
+ // optional requirement file: copy into the task dir for the bootstrap to read
370
+ let reqFile = '(无)';
371
+ if (typeof flags.file === 'string') {
372
+ const src = path.resolve(ws, flags.file);
373
+ if (!fs.existsSync(src) || !fs.statSync(src).isFile()) {
374
+ fs.rmSync(taskDir, { recursive: true, force: true });
375
+ return err(`需求文件不存在:${flags.file}`);
376
+ }
377
+ reqFile = path.basename(src);
378
+ fs.copyFileSync(src, path.join(taskDir, reqFile));
379
+ }
380
+
381
+ const tplPath = path.join(packDir(kit), 'templates', 'proposal.md');
382
+ const tpl = fs.existsSync(tplPath)
383
+ ? fs.readFileSync(tplPath, 'utf8')
384
+ : '# 提案:{{task}}\n\n> **状态**:draft\n\n## 输入\n\n- **来源**:{{source}}\n- **文件**:{{file}}\n- **描述**:{{desc}}\n';
385
+ const doc = tpl
386
+ .replaceAll('{{task}}', task)
387
+ .replaceAll('{{desc}}', desc)
388
+ .replaceAll('{{source}}', reqFile === '(无)' ? '描述' : '描述+文件')
389
+ .replaceAll('{{file}}', reqFile);
390
+ fs.writeFileSync(path.join(taskDir, 'proposal.md'), doc, 'utf8');
391
+ // --base 分析基点(面板新建任务的分支选择):落盘 spec + 立即建任务专属分析工作区(propose 时幂等复用)
392
+ let baseNote = '';
393
+ if (typeof flags.base === 'string') {
394
+ const spec = parseBaseSpec(flags.base);
395
+ if (Object.keys(spec).length > 0) {
396
+ const ta = await ensureTaskAnalysisWorktrees(ws, kit, task, spec);
397
+ const parts = [];
398
+ if (ta.created.length > 0) parts.push(`新建专属分析区:${ta.created.map((w) => `${w.source}@${w.branch}`).join('、')}`);
399
+ if (ta.reused.length + ta.switched.length > 0) parts.push(`复用/切换专属分析区:${[...ta.reused, ...ta.switched].map((w) => w.source).join('、')}`);
400
+ if (ta.worktrees.length > 0) parts.push(`分析基点:${ta.worktrees.map((w) => `${w.source}→${w.branch}(${w.sha})`).join(';')}`);
401
+ parts.push(...ta.notes);
402
+ baseNote = `\n- ${parts.join('\n- ')}`;
403
+ }
404
+ }
405
+ updateBoard(ws, task, 'PENDING');
406
+ bindCurrentSession(ws, task, agent);
407
+
408
+ const pm = resolveRole(ws, kit, 'project-manager');
409
+ const loaded = loadFlow(ws, kit, 'new');
410
+ if (!loaded) return err('找不到 bootstrap 流程定义(packs/ai-coding/flows/new.yml)。');
411
+ const router = loadFlow(ws, kit, '_router');
412
+ const prompt = compileFlowPrompt(loaded.flow, {
413
+ task,
414
+ desc,
415
+ flowFile: loaded.file,
416
+ artifacts: `.harness/deliverables/${task}/`,
417
+ roleSections: [
418
+ pm ? `### PM 角色(你立即切换到此身份)\n\n${pm.body}` : '(缺 project-manager 角色定义,按通用 PM 职责执行)',
419
+ '',
420
+ '### Profile 路由表(逐条对照 when 条件判定)',
421
+ router ? `\`\`\`yaml\n${fs.readFileSync(router.file, 'utf8').trim()}\n\`\`\`` : '(缺 flows/_router.yml:按默认 standard 处理,并在汇报中注明)',
422
+ ].join('\n'),
423
+ rules: readCoreRules(kit),
424
+ dispatchSection: dispatchSection(kit, []),
425
+ });
426
+
427
+ steer(agent, prompt);
428
+ return ok(
429
+ `新任务 **${task}** 已创建:\n- 提案草稿 \`.harness/deliverables/${task}/proposal.md\` 已生成(状态 draft)${autoNamed ? '\n- 任务名由描述自动生成;如需更名请现在告诉我' : ''}${reqFile === '(无)' ? '' : `\n- 需求文件已拷入:\`${reqFile}\``}\n- 看板已登记(PENDING)${baseNote}\n- Bootstrap 剧本已提交 PM:解读输入 → 起草 → Profile 判定 → ⛔模糊点反问 → ⛔定稿(approved)→ 交接\n\n红线生效:定稿+审批 1 前,源码区(${protectedSourcePaths(kit).join('、')})禁写。`,
430
+ );
431
+ }
432
+
433
+ // -------------------------------------------------------------- /hk-propose
434
+ async function hkPropose({ agent, rawInput }) {
435
+ const ws = wsRoot(agent);
436
+ const kit = readKit(ws);
437
+ if (!kit) return err('尚未初始化:请先运行 `/hk-init`。');
438
+ const { flags, positional } = parseArgs(rawInput);
439
+ const inferred = inferTask(ws, positional, '用法:/hk-propose [任务名] [--base <仓:分支,…>](省略任务名时要求唯一活跃任务;--base=按仓指定分析基点,如 backend:release/1.2)');
440
+ if (inferred.error) return err(inferred.error);
441
+ const task = inferred.task;
442
+ const taskDir = path.join(harnessDir(ws), 'deliverables', task);
443
+ const proposalPath = path.join(taskDir, 'proposal.md');
444
+ if (!fs.existsSync(proposalPath)) {
445
+ return err(`任务 ${task} 缺少 proposal.md:全流程任务由 /hk-new 创建;简单 bug 修复请用 /hk-fix。`);
446
+ }
447
+ const proposal = fs.readFileSync(proposalPath, 'utf8');
448
+ if (!STATUS_APPROVED.test(proposal)) {
449
+ return err(`proposal.md 未定稿(状态行需为「> **状态**:approved」):先完成 Bootstrap 消歧义与人工定稿,再运行 /hk-propose。`);
450
+ }
451
+
452
+ const profile = readProfile(proposal);
453
+ const loaded = loadFlow(ws, kit, profile);
454
+ if (!loaded) return err(`找不到 ${profile} 流程定义(packs/ai-coding/flows/${profile}.yml)。`);
455
+ const pm = resolveRole(ws, kit, 'project-manager');
456
+ const wctx = buildWorkerContext(ws, kit, loaded.flow, 'propose');
457
+ // 设计期源码分析:常驻只读基线镜像(主树被在途任务占用时 BA/SA/RR 仍有确定的分析基点)
458
+ const mirrors = await ensureBaselineMirrors(ws, kit);
459
+ // --base 按任务指定分析基点 → 任务专属分析工作区(不切换共享镜像,无需锁定)
460
+ const taskAnalysis = await ensureTaskAnalysisWorktrees(ws, kit, task, parseBaseSpec(flags.base));
461
+ const mirrorNotice = renderAnalysisNotice(mirrors, taskAnalysis);
462
+ const prompt = compileFlowPrompt(loaded.flow, {
463
+ task,
464
+ desc: `按已定稿的 proposal.md 执行 **propose 阶段**(profile=${profile})。先通读 proposal.md 全文,交叉验证 profile 与任务规模是否匹配,不匹配则停下交人裁决`,
465
+ flowFile: loaded.file,
466
+ artifacts: `.harness/deliverables/${task}/`,
467
+ phase: 'propose',
468
+ roleSections: [
469
+ pm ? `### PM 角色(你立即切换到此身份)\n\n${pm.body}` : '(缺 project-manager 角色定义,按通用 PM 职责执行)',
470
+ '',
471
+ '### Worker 角色(派发时逐个读取并内嵌)',
472
+ wctx.refs,
473
+ ].join('\n'),
474
+ rules: [readCoreRules(kit), mirrorNotice].filter(Boolean).join('\n\n'),
475
+ dispatchSection: dispatchSection(kit, wctx.modelRows),
476
+ });
477
+
478
+ updateBoard(ws, task, 'IN_PROGRESS');
479
+ bindCurrentSession(ws, task, agent);
480
+ // M4b 自动认领:追加式 claims.json(sync 白名单,随 /hk-sync 全队可见)
481
+ let claimHint = '';
482
+ try {
483
+ const who = (await runGit(['config', 'user.name'], { cwd: harnessDir(ws) })).stdout.trim()
484
+ || os.userInfo()?.username || 'unknown';
485
+ claimTask(ws, task, who);
486
+ claimHint = `\n- 已自动认领给 **${who}**(claims.json,随 /hk-sync 共享)`;
487
+ } catch { /* 认领失败不阻塞流程 */ }
488
+ steer(agent, prompt);
489
+ return ok(`propose 阶段已启动(任务 **${task}**,profile=${profile}):\n- 执行剧本已提交 PM:${flowWorkers(loaded.flow, 'propose').map((w) => w.role).join(' → ') || 'PM 自行执行'} → ⛔审批 1\n- 审批 1 通过后 PM 会把「审批 1:通过」写入 proposal.md(红线解锁),随后自动续接引擎会接力执行 \`/hk-apply ${task}\`(无需人再手动运行)${claimHint}`);
490
+ }
491
+
492
+ // ---------------------------------------------------------------- /hk-apply
493
+ async function hkApply({ agent, rawInput }) {
494
+ const ws = wsRoot(agent);
495
+ const kit = readKit(ws);
496
+ if (!kit) return err('尚未初始化:请先运行 `/hk-init`。');
497
+ const { flags, positional } = parseArgs(rawInput);
498
+ const inferred = inferTask(ws, positional, '用法:/hk-apply [任务名] [反馈] [--slot](省略任务名时要求唯一活跃任务;--slot=主树有未处理改动时强制隔离到 slot 开发)');
499
+ if (inferred.error) return err(inferred.error);
500
+ const task = inferred.task;
501
+ const feedback = positional.slice(1).join(' ');
502
+
503
+ const taskDir = path.join(harnessDir(ws), 'deliverables', task);
504
+ const proposalPath = path.join(taskDir, 'proposal.md');
505
+ if (!fs.existsSync(proposalPath)) {
506
+ return err(`任务 ${task} 缺少 proposal.md:/hk-apply 只服务全流程任务;fix 直通的质量门后直接继续,无需本命令。`);
507
+ }
508
+ const proposal = fs.readFileSync(proposalPath, 'utf8');
509
+ if (!APPROVAL1.test(proposal)) {
510
+ return err(`审批 1 未记录:propose 阶段的人审批通过后,PM 须把「审批 1:通过(日期)」写入 proposal.md 末尾。`);
511
+ }
512
+
513
+ const profile = readProfile(proposal);
514
+ // readiness preflight per profile (原 harness-apply 3a+ 规则)
515
+ const readyDoc = { standard: 'readiness-report.md', refactor: 'readiness-report.md', quick: 'design.md', bugfix: 'bugfix.md' }[profile];
516
+ const readyPath = path.join(taskDir, readyDoc);
517
+ if (!fs.existsSync(readyPath)) {
518
+ return err(`就绪预检 FAIL:缺 ${readyDoc}(propose 阶段未产出)。先运行 /hk-propose ${task} 完成方案阶段。`);
519
+ }
520
+ const verdict = lastConclusion(fs.readFileSync(readyPath, 'utf8'));
521
+ if (verdict !== 'PASS') {
522
+ return err(`就绪预检 FAIL:${readyDoc} 最后结论为 ${verdict ?? '缺失'},需 PASS 才能开工(propose 被打回时先回炉重做)。`);
523
+ }
524
+
525
+ const loaded = loadFlow(ws, kit, profile);
526
+ if (!loaded) return err(`找不到 ${profile} 流程定义(packs/ai-coding/flows/${profile}.yml)。`);
527
+ const pm = resolveRole(ws, kit, 'project-manager');
528
+ const wctx = buildWorkerContext(ws, kit, loaded.flow, 'apply');
529
+
530
+ // 并行开发:预检全过后分配工作区(主工作树 or 池化 slot);外来占用 → 结构化决策点(面板渲染可点选项)
531
+ const wt = await ensureTaskWorkspaces(ws, kit, task, { forceSlot: flags.slot === true });
532
+ if (wt.refused.length > 0) {
533
+ const details = [];
534
+ for (const f of wt.refused) {
535
+ const source = (kit.sources ?? []).find((s) => s.name === f.source);
536
+ if (source) details.push(await describeMainWorktree(ws, source));
537
+ }
538
+ const text = `工作区分配需要人工裁决(不开发工):\n${wt.refused.map((f) => `- ${f.source}:${f.reason}`).join('\n')}` +
539
+ (details.length > 0 ? `\n\n主工作树现场:\n${details.join('\n\n')}` : '');
540
+ const options = [
541
+ { label: '在隔离 slot 开发', line: `/hk-apply ${task}${feedback ? ` ${feedback}` : ''} --slot`, primary: true },
542
+ { label: '已处理主树,按原样重跑', line: `/hk-apply ${task}${feedback ? ` ${feedback}` : ''}` },
543
+ ];
544
+ recordDecision(ws, task, { code: 'workspace-foreign', text, options });
545
+ return decision(text, 'workspace-foreign', options);
546
+ }
547
+ clearDecision(ws, task);
548
+ const wtNotice = renderWorkspaceNotice(wt, task);
549
+
550
+ const prompt = compileFlowPrompt(loaded.flow, {
551
+ task,
552
+ desc: `按 proposal.md + 方案文档执行 **apply 阶段**(profile=${profile})。先通读 proposal/design 等既有产物;若 Dev/CR 产物已存在(续接场景),跳过已完成阶段从断点继续${feedback ? `\n\n续接反馈(人):${feedback}` : ''}`,
553
+ flowFile: loaded.file,
554
+ artifacts: `.harness/deliverables/${task}/`,
555
+ phase: 'apply',
556
+ roleSections: [
557
+ pm ? `### PM 角色(你立即切换到此身份)\n\n${pm.body}` : '(缺 project-manager 角色定义,按通用 PM 职责执行)',
558
+ '',
559
+ '### Worker 角色(派发时逐个读取并内嵌)',
560
+ wctx.refs,
561
+ ].join('\n'),
562
+ rules: [readCoreRules(kit), wtNotice, TE_NOTICE].filter(Boolean).join('\n\n'),
563
+ dispatchSection: dispatchSection(kit, wctx.modelRows),
564
+ });
565
+
566
+ steer(agent, prompt);
567
+ bindCurrentSession(ws, task, agent);
568
+ const wtSummary = wt.assigned.length > 0
569
+ ? `\n- 工作区分配:${wt.assigned.map((w) => `${w.source} → ${w.placement === 'main' ? '主工作树' : w.placement}${w.branch ? `(\`${w.branch}\` ← \`${w.base}\`)` : ''}`).join(';')}`
570
+ : '';
571
+ const wtOverlap = wt.overlaps.length > 0
572
+ ? `\n- ⚠️ 与在途任务文件重叠:${wt.overlaps.map((o) => `${o.task}(${o.source}:${o.files.slice(0, 3).join('、')}${o.files.length > 3 ? ' 等' : ''})`).join(';')}——同文件并发修改必冲突,已写入剧本提示 PM 先向你确认`
573
+ : '';
574
+ return ok(`apply 阶段已启动(任务 **${task}**,profile=${profile}):\n- 就绪预检 PASS(${readyDoc})\n- 执行剧本已提交 PM:${flowWorkers(loaded.flow, 'apply').map((w) => w.role).join(' → ')} → ⛔审批 2${feedback ? `\n- 已携带续接反馈` : ''}${wtSummary}${wtOverlap}\n- 审批 2 通过后,PM 把看板置 AWAITING_ARCHIVE 并记录审批 2 ✅,自动续接引擎会接力 \`/hk-archive ${task}\`(无需手动敲;关闭自动续接时由人运行)`);
575
+ }
576
+
577
+ // --------------------------------------------------------------- /hk-archive
578
+ async function hkArchive({ agent, rawInput }) {
579
+ const ws = wsRoot(agent);
580
+ const kit = readKit(ws);
581
+ if (!kit) return err('尚未初始化:请先运行 `/hk-init`。');
582
+ const { flags, positional } = parseArgs(rawInput);
583
+ const task = positional[0];
584
+ if (!task) return err('用法:/hk-archive <任务名> [--merge [仓:分支,…]]');
585
+ // 合入确认(B 方案,2026-11-17):--merge = 人显式确认要把任务分支本地合入目标基线;
586
+ // 可带 repo:branch 覆盖目标(不带则用任务创建时指定的基线)。合并只做本地提交,不推送。
587
+ const mergeAsked = flags.merge !== undefined;
588
+ const mergeOverrides = mergeAsked && typeof flags.merge === 'string' ? parseBaseSpec(flags.merge) : {};
589
+
590
+ const taskDir = path.join(harnessDir(ws), 'deliverables', task);
591
+ if (!fs.existsSync(taskDir)) {
592
+ // 已归档任务的残留收尾(2026-11-17 新增):文档已归档但工作区 slot 因分支未合入而保留
593
+ // (stale-unmerged),注意力条提示「远端 MR 合入后重跑 /hk-archive 释放槽位」——
594
+ // 此时活目录已清,正常预检必然失败;这里识别为「只做工作区释放」的收尾模式。
595
+ const wl = readWorkspaces(ws);
596
+ if (wl.tasks?.[task]) {
597
+ const mg = mergeAsked ? await mergeTaskBranches(ws, kit, task, mergeOverrides) : null;
598
+ const rel = await releaseTaskWorkspaces(ws, kit, task);
599
+ const ta = await removeTaskAnalysisWorktrees(ws, kit, task);
600
+ clearDecision(ws, task);
601
+ const lines = [
602
+ ...(mg ? mergeLines(mg) : []),
603
+ ...rel.released.map((r) => `${r.placement === 'main' ? '主工作树' : `slot ${r.placement}`} 已释放(${r.source})`),
604
+ ...rel.stale.map((s) => `⚠️ ${s.source}:${s.reason}`),
605
+ ...(ta.removed > 0 ? [`任务分析工作区已回收 ×${ta.removed}`] : []),
606
+ ...ta.notes,
607
+ ];
608
+ if (rel.stale.length > 0) {
609
+ const targets = [...new Set([...rel.stale.map((x) => x.source)])]
610
+ .map((src) => `${src}→${(wl.tasks?.[task]?.repos?.[src]?.base) ?? '?'}`).join('、');
611
+ return err(`任务 **${task}** 已归档,但工作区仍未释放:\n${lines.join('\n')}\n\n确认要本地合入目标基线(${targets})后运行:\n\`/hk-archive ${task} --merge\`(可用 \`--merge 仓:分支\` 覆盖目标;只做本地合并,推送仍由人执行)`);
612
+ }
613
+ return ok(`任务 **${task}** 已归档,残留工作区已收尾:\n${lines.join('\n') || '(无残留)'}`);
614
+ }
615
+ return err(`活目录 .harness/deliverables/${task}/ 不存在。`);
616
+ }
617
+
618
+ const isFullFlow = fs.existsSync(path.join(taskDir, 'proposal.md'));
619
+
620
+ // preflight 1: planning gate must be recorded
621
+ if (taskIsPlanning(ws, task)) {
622
+ return err(
623
+ isFullFlow
624
+ ? `归档预检 FAIL:${task} 的 proposal.md 缺少「审批 1:通过」记录(审批 1 通过后由 PM 写入)。`
625
+ : `归档预检 FAIL:${task} 的 bugfix.md 缺少质量门人裁决记录(需含「裁决:轻量」或「裁决:--full」)。`,
626
+ );
627
+ }
628
+
629
+ if (isFullFlow) {
630
+ // preflight 2 (full flow): test report must conclude PASS
631
+ const trPath = path.join(taskDir, 'test-report.md');
632
+ if (!fs.existsSync(trPath)) return err(`归档预检 FAIL:缺 test-report.md(apply 阶段未产出测试报告)。`);
633
+ const verdict = lastConclusion(fs.readFileSync(trPath, 'utf8'));
634
+ if (verdict !== 'PASS') {
635
+ return err(`归档预检 FAIL:test-report.md 最后结论为 ${verdict ?? '缺失'},需 PASS 才能归档(BUG→回开发,需求级→回 propose,环境阻塞→升级给人)。`);
636
+ }
637
+ } else {
638
+ // preflight 2 (fix flow): --full verdict requires real CR/TE docs
639
+ const fixText = fs.readFileSync(path.join(taskDir, 'bugfix.md'), 'utf8');
640
+ const m = fixText.match(/裁决[**]*[::][ \t]*`?(--full|full)(?![\w-])/i);
641
+ if (m) {
642
+ const missing = ['code-review.md', 'test-report.md'].filter((f) => !fs.existsSync(path.join(taskDir, f)));
643
+ if (missing.length > 0) {
644
+ return err(`归档预检 FAIL:质量门裁决为 --full,但缺 ${missing.join('、')}(--full 必须真实走 CR → TE)。`);
645
+ }
646
+ }
647
+ }
648
+
649
+ // preflight 3 (full flow): spec 编号门禁内核化——合并前的 specs 必须已 PASS(原仅 steer 提示,PM 可能漏跑)。
650
+ // 仅当 specs 已有实质 spec 文件时启用(首个任务尚无 spec 可合,lint 的「无 spec 文件」退出码不视为 FAIL)。
651
+ if (isFullFlow) {
652
+ const specsDir = path.join(harnessDir(ws), 'specs');
653
+ const hasSpecs = fs.existsSync(specsDir) && fs.readdirSync(specsDir).some((f) => f.endsWith('.md') && !f.startsWith('_') && f !== 'spec-template.md');
654
+ const lint = path.join(harnessDir(ws), 'scripts', 'spec_lint.py');
655
+ if (hasSpecs && fs.existsSync(lint)) {
656
+ const r = await run('python3', [lint], { cwd: ws, timeoutMs: 60_000 });
657
+ if (r.code !== 0) {
658
+ return err(`归档预检 FAIL:spec 编号门禁未通过——\n${(r.stdout || r.stderr).trim()}\n修复后重试(门禁:.harness/scripts/spec_lint.py)。`);
659
+ }
660
+ }
661
+ }
662
+
663
+ const archiveDir = path.join(harnessDir(ws), 'deliverables', '_archive', task);
664
+ fs.mkdirSync(archiveDir, { recursive: true });
665
+ const date = new Date().toISOString().slice(0, 10);
666
+
667
+ // round number: existing rounds in archive + 1... count previous archive files' R markers
668
+ let round = 0;
669
+ const marker = path.join(archiveDir, 'rounds.md');
670
+ if (fs.existsSync(marker)) {
671
+ const text = fs.readFileSync(marker, 'utf8');
672
+ const rounds = [...text.matchAll(/^\| R(\d+) /gm)];
673
+ round = rounds.length;
674
+ }
675
+ const tag = `R${round}`;
676
+
677
+ // append each active doc to its archive counterpart under an R<N> section
678
+ const appended = [];
679
+ for (const name of fs.readdirSync(taskDir)) {
680
+ if (!name.endsWith('.md')) continue;
681
+ const body = fs.readFileSync(path.join(taskDir, name), 'utf8');
682
+ const target = path.join(archiveDir, name);
683
+ const section = `\n\n---\n\n## ${tag}(${date} 归档)\n\n${body.trim()}\n`;
684
+ fs.appendFileSync(target, section, 'utf8');
685
+ appended.push(name);
686
+ }
687
+
688
+ // rounds.md summary line (append-only)
689
+ const summaryLine = `| ${tag} | ${date} | ${appended.join(', ') || '(无文档)'} |\n`;
690
+ if (!fs.existsSync(marker)) fs.writeFileSync(marker, `# ${task} 归档轮次\n\n| 轮次 | 日期 | 文档 |\n|---|---|---|\n`, 'utf8');
691
+ fs.appendFileSync(marker, summaryLine, 'utf8');
692
+
693
+ // clear the active dir
694
+ fs.rmSync(taskDir, { recursive: true, force: true });
695
+ updateBoard(ws, task, 'DONE');
696
+ clearAdvanceMarks(ws, task);
697
+ bindCurrentSession(ws, task, agent);
698
+
699
+ // worktree 收尾:slot 已合入基线的 → 切回基线释放(目录保留);未合入 → stale 保留提示
700
+ // 合入确认(B 方案):--merge 时先本地合入目标基线,再释放槽位
701
+ const mgNormal = mergeAsked ? await mergeTaskBranches(ws, kit, task, mergeOverrides) : null;
702
+ const wtResult = await releaseTaskWorkspaces(ws, kit, task);
703
+ clearDecision(ws, task);
704
+ const taCleanup = await removeTaskAnalysisWorktrees(ws, kit, task);
705
+ const staleLines = wtResult.stale.map((s) => `⚠️ ${s.source}:${s.reason}`);
706
+ const confirmHint = wtResult.stale.length > 0 && !mergeAsked
707
+ ? [`确认要本地合入目标基线后运行:\`/hk-archive ${task} --merge\`(可用 \`--merge 仓:分支\` 覆盖目标;只本地合并,推送由人执行)`]
708
+ : [];
709
+ const wtNote = wtResult.missing && taCleanup.removed === 0 && taCleanup.notes.length === 0 && !mgNormal
710
+ ? ''
711
+ : [
712
+ ...(mgNormal ? mergeLines(mgNormal) : []),
713
+ ...wtResult.released.map((r) => `${r.placement === 'main' ? '主工作树无需处理' : `slot ${r.placement} 已释放(切回基线,目录保留)`}(${r.source})`),
714
+ ...staleLines,
715
+ ...confirmHint,
716
+ ...(taCleanup.removed > 0 ? [`任务分析工作区已回收 ×${taCleanup.removed}`] : []),
717
+ ...taCleanup.notes,
718
+ ].join('\n');
719
+
720
+ // full flow: steer PM to do Spec Merge + Memory Merge from the archived R<N> docs
721
+ let mergeNote = '提示:Memory/Spec Merge 由 PM 在归档前完成;';
722
+ if (isFullFlow) {
723
+ const pm = resolveRole(ws, kit, 'project-manager');
724
+ const mergePrompt = [
725
+ `# Harness Kit 归档收尾(${task} ${tag})`,
726
+ '',
727
+ `${pm ? `你继续以 PM 身份执行收尾(角色定义见 ${pm.file},先读全文)。` : '你以 PM 身份执行收尾。'}本轮产物已追加归档到 \`.harness/deliverables/_archive/${task}/\` 的 ${tag} 段。按顺序完成两个合并:`,
728
+ '',
729
+ '## 1. Spec Merge',
730
+ `- 读 \`_archive/${task}/requirements.md\` ${tag} 段的「§7 Spec Delta」,把 ADDED/MODIFIED/REMOVED 条目并入 \`.harness/specs/\` 对应能力文档(id_max 编号不回收)`,
731
+ '- 全新能力建新文档:**格式必须遵循 \`.harness/specs/spec-template.md\`**(frontmatter:domain/summary/entities/api_prefixes/prefix/id_max_r/id_max_s/retired/last_updated;Requirement/Scenario 编号 \`<PREFIX>-R-<NNN>\` / \`<PREFIX>-S-<NNN>\`),并登记 \`specs/_index.md\` 业务域表',
732
+ '- 合并后运行 \`python3 .harness/scripts/spec_lint.py\`(存在时)做门禁校验,FAIL 必须修复',
733
+ '',
734
+ '## 2. Memory Merge',
735
+ `- 从 \`_archive/${task}/\` 本轮各文档(dev-log / test-report / code-review)提取可复用踩坑与经验,并入 \`.harness/memory/\``,
736
+ '- **每条新条目必须遵循 \`.harness/memory/templates/entry.md\`**:文件名 \`YYYY-MM-DD_<scope>_<slug>.md\`(scope 六选一:backend/frontend/mobile/tooling/infra/shared),frontmatter 含 id/date/scope/tags,正文含症状/根因/修复/防复发/复发检测;tooling/infra/shared 类必须含「流程优化排除」节',
737
+ '- 每条在 \`memory/index.md\` 条目索引表追加一行(只追加);命名约定与写/不写纪律见该文件头',
738
+ '- 流程优先决策门:若经验属于 tooling/infra/shared 级,应改 harness 资产本身(模板/角色/流程定义),而不是只写记忆',
739
+ '',
740
+ '完成后向人汇报两个合并的结果清单。',
741
+ ].join('\n');
742
+ steer(agent, mergePrompt);
743
+ mergeNote = 'Spec/Memory Merge 收尾剧本已提交 PM(基于归档段执行);';
744
+ }
745
+
746
+ let syncHint;
747
+ if (kit.assets?.autoSync === true && fs.existsSync(path.join(harnessDir(ws), '.git'))) {
748
+ const r = await syncAssets(ws, kit);
749
+ syncHint = r.kind === 'success' ? `资产已自动同步(assets.autoSync):${r.text}` : `资产自动同步失败(assets.autoSync):${r.text}`;
750
+ } else if (kit.assets && kit.assets.mode !== 'local') {
751
+ syncHint = `资产仓库已绑定${kit.assets.url ? `(${kit.assets.url})` : ''},请运行 \`/hk-sync\` 同步(或在 kit.json 设 \`assets.autoSync=true\` 让归档后自动同步)`;
752
+ } else {
753
+ const lay = await assetsLayout(ws);
754
+ syncHint =
755
+ lay.layout === 'embedded'
756
+ ? `资产随工作区根仓库管理(\`${lay.repoRoot}\`),随根仓库 commit/push 即共享,无需 \`/hk-sync\``
757
+ : '资产仓库为本地模式;如需团队共享,绑定远端后用 `/hk-sync` 同步';
758
+ }
759
+ return ok(`任务 **${task}** 已归档为 ${tag}:\n- 追加归档:${appended.map((f) => `\`_archive/${task}/${f}\``).join('、') || '(无)'}\n- 轮次摘要追加到 \`_archive/${task}/rounds.md\`\n- 活目录已清空${wtNote ? `\n- ${wtNote}` : ''}\n\n${mergeNote}${syncHint}。`);
760
+ }
761
+
762
+ // ---------------------------------------------------------------- /hk-te
763
+ // TE 环境串行租约(测试环境全局只有一个;排队细节见 kernel/te.js)。
764
+ function hkTe({ agent, rawInput }) {
765
+ const ws = wsRoot(agent);
766
+ if (!readKit(ws)) return err('尚未初始化:请先运行 `/hk-init`。');
767
+ const { positional } = parseArgs(rawInput);
768
+ const sub = positional[0] ?? 'status';
769
+ const task = positional[1];
770
+ if (sub === 'acquire') {
771
+ if (!task) return err('用法:/hk-te acquire <任务名>');
772
+ const r = acquireTestEnv(ws, task);
773
+ return ok(r.text);
774
+ }
775
+ if (sub === 'release') {
776
+ if (!task) return err('用法:/hk-te release <任务名>');
777
+ return ok(releaseTestEnv(ws, task).text);
778
+ }
779
+ if (sub === 'status') return ok(describeTestEnv(ws));
780
+ return err('用法:/hk-te [acquire|release <任务名> | status]');
781
+ }
782
+
783
+ /** 合入结果的行化输出(--merge 用)。 */
784
+ function mergeLines(mg) {
785
+ const lines = [];
786
+ for (const m of mg.merged) lines.push(`✅ ${m.repo} → ${m.target} 已本地合入(commit ${m.commit},未推送)`);
787
+ for (const c of mg.conflicts) lines.push(`⛔ ${c.repo} → ${c.target} 合并冲突(已中止回滚):${c.files.slice(0, 8).join('、') || '见 git status'}`);
788
+ for (const r of mg.refused) lines.push(`⚠️ ${r.repo}:${r.reason}`);
789
+ return lines;
790
+ }
791
+
792
+ /** TE 串行纪律节(注入 apply/fix 剧本;PM 派发 TE Worker 前的门)。 */
793
+ const TE_NOTICE = [
794
+ '### TE 环境(串行排队,必须遵守)',
795
+ '- 测试环境(起服务/连 TDengine/jmeter)全局只有一个,TE 阶段按租约串行。',
796
+ '- 派发 TE Worker **之前**先在本会话运行 `/hk-te acquire <任务名>`:',
797
+ ' 已获授权 → 正常派发;排队中 → **暂停 TE 阶段**,向人汇报「TE 环境被谁占用、本任务已排队」,**不要派发 TE Worker、不要起服务/连测试库**(内核无法抢占运行中的 Worker,门必须在派发前)。',
798
+ '- TE 完成(看板链 TE 标 ✅)后内核自动释放并通知下一个排队任务,无需手工 release。',
799
+ ].join('\n');
800
+
801
+ // ---------------------------------------------------------------- /hk-sync
802
+ async function hkSync({ agent }) {
803
+ const ws = wsRoot(agent);
804
+ const kit = readKit(ws);
805
+ if (!kit) return err('尚未初始化:请先运行 `/hk-init`。');
806
+ return syncAssets(ws, kit);
807
+ }
808
+
809
+ // ---------------------------------------------------------------- /hk-doctor
810
+ async function hkDoctor({ agent }) {
811
+ const ws = wsRoot(agent);
812
+ const lines = ['## Harness Kit 体检', ''];
813
+ lines.push(`- 工作区:\`${ws}\``);
814
+ lines.push(`- 内容包目录:\`${packDir(readKit(ws) ?? undefined)}\` ${fs.existsSync(packDir(readKit(ws) ?? undefined)) ? '✅' : '❌ 缺失'}`);
815
+
816
+ const kit = readKit(ws);
817
+ if (!kit) {
818
+ lines.push('- kit.json:❌ 不存在 → 运行 `/hk-init`');
819
+ return ok(lines.join('\n'));
820
+ }
821
+ lines.push(`- kit.json:✅(pack: ${kit.pack ?? 'ai-coding'},sources: ${kit.sources.length} 个)`);
822
+ for (const s of kit.sources) {
823
+ lines.push(` - ${s.name} → \`${s.path}\` ${fs.existsSync(path.join(ws, s.path)) ? '✅' : '❌ 路径缺失'}`);
824
+ }
825
+ const a = kit.assets;
826
+ const embedded = !a || a.mode === 'local' ? await assetsLayout(ws) : null;
827
+ lines.push(
828
+ `- 资产仓库:${
829
+ embedded?.layout === 'embedded'
830
+ ? `🔗 随工作区根仓库管理(\`${embedded.repoRoot}\`,embedded:资产随根仓库 commit/push 共享,\`/hk-sync\` 不适用)`
831
+ : !a || a.mode === 'local'
832
+ ? '📁 本地模式(`/hk-init --assets <url|init>` 可绑定)'
833
+ : a.mode === 'clone'
834
+ ? `🔗 clone 自 \`${a.url}\`(分支 \`${a.branch ?? '?'}\`)`
835
+ : `📦 本地 git(分支 \`${a.branch ?? '?'}\`${a.url ? `,远端 \`${a.url}\`` : ',无远端'})`
836
+ }${a?.autoSync === true ? ',归档后自动同步(autoSync)' : ''}`,
837
+ );
838
+
839
+ const roles = listRoles(ws, kit);
840
+ lines.push(`- 角色注册表:${roles.length} 个(${roles.map((r) => `${r.role}${r.origin === 'workspace' ? '·覆写' : ''}`).join('、') || '无'})`);
841
+ for (const r of roles.filter((x) => x.error)) lines.push(` - ⚠️ ${r.role}:${r.error}`);
842
+
843
+ const planning = activeTasks(ws).filter((t) => taskIsPlanning(ws, t));
844
+ const active = activeTasks(ws);
845
+ lines.push(`- 活跃任务:${active.length ? active.map((t) => `\`${t}\``).join('、') : '无'}`);
846
+ lines.push(`- Bootstrap 红线:${planning.length ? `🔒 锁定中(规划未裁决:${planning.join('、')}),写禁区 ${protectedSourcePaths(kit).join('、')}` : '🔓 未锁定'}`);
847
+
848
+ const flowNames = ['fix', 'new', 'standard', 'quick', 'bugfix', 'refactor', '_router', 'init'];
849
+ const flowStatus = flowNames.map((n) => {
850
+ const f = loadFlow(ws, kit, n);
851
+ return `${n} ${f ? '✅' : '❌'}`;
852
+ });
853
+ lines.push(`- 流程定义:${flowStatus.join('、')}`);
854
+
855
+ const models = kit.models && typeof kit.models === 'object' ? Object.entries(kit.models) : [];
856
+ lines.push(
857
+ `- 模型映射:${models.length === 0 ? '(空 → 全部走会话默认;在 kit.json models 中配置 logical→{provider,model})' : models.map(([k, v]) => `${k}→${v?.provider ? `${v.provider}/` : ''}${v?.model ?? '?'}`).join('、')}`,
858
+ );
859
+
860
+ // init assets materialization state:与 /hk-init 物化契约逐项对账(缺件 → 重跑 /hk-init create-only 补齐)
861
+ const assetChecks = [
862
+ 'scripts/harness_init.py', 'scripts/harness.py', 'scripts/lib.py',
863
+ 'scripts/verify.py', 'scripts/spec_lint.py', 'scripts/env_auto.py',
864
+ 'scripts/check_codegraph.py', 'scripts/run_field.py', 'scripts/codebase_guide_init.py',
865
+ 'scripts/update_board.py',
866
+ 'rules/code-standards.md', 'specs/spec-template.md', 'memory/templates/entry.md',
867
+ ];
868
+ const missing = assetChecks.filter((rel) => !fs.existsSync(path.join(harnessDir(ws), rel)));
869
+ const templatesOk = fs.existsSync(path.join(harnessDir(ws), 'templates')) && fs.readdirSync(path.join(harnessDir(ws), 'templates')).length > 0;
870
+ if (!templatesOk) missing.push('templates/(目录为空)');
871
+ lines.push(
872
+ `- 初始化资产:${missing.length === 0 ? `✅ ${assetChecks.length} 项脚本/规范/模板 + templates 齐全` : `❌ 缺 ${missing.length} 项:${missing.map((m) => `\`${m}\``).join('、')} → 重跑 \`/hk-init\` 补齐`}`,
873
+ );
874
+ // 看板 7 列契约(lib.py _board_rows 硬编码列序;4 列旧简表会使分支列读取落空)
875
+ const boardPath = path.join(harnessDir(ws), 'tasks', 'board.md');
876
+ if (fs.existsSync(boardPath)) {
877
+ const boardText = fs.readFileSync(boardPath, 'utf8');
878
+ lines.push(`- 看板契约:${boardText.includes('| 任务名 | 状态 | Profile |') ? '✅ 7 列契约' : '⚠️ 非 7 列格式(缺 Profile/分支/续接提示列,lib.py 将读取落空)→ 按 boardTemplate 7 列表头整改'}`);
879
+ // 看板内容体检(列格式契约,唯一写入门禁 update_board.py --check;脚本缺失则跳过,由上方资产检查报缺件)
880
+ const ub = path.join(harnessDir(ws), 'scripts', 'update_board.py');
881
+ if (fs.existsSync(ub)) {
882
+ const chk = await run('python3', [ub, '--check'], { cwd: ws, timeoutMs: 15_000 });
883
+ lines.push(`- 看板体检:${chk.code === 0 ? '✅ 全行合规' : `❌ 列格式违规 → python3 .harness/scripts/update_board.py --repair --write 修复\n${(chk.stdout || '').trim().split('\n').map((l) => ` ${l}`).join('\n')}`}`);
884
+ }
885
+ }
886
+ // pack 管理运行时漂移:scripts 内容与 pack 不一致 → 重跑 /hk-init 刷新(scripts 不入库,漂移只来自手改或 pack 升级后未刷新)
887
+ const packScripts = path.join(packDir(kit), 'assets', 'scripts');
888
+ const wsScripts = path.join(harnessDir(ws), 'scripts');
889
+ if (fs.existsSync(packScripts)) {
890
+ const drift = [];
891
+ for (const f of fs.readdirSync(packScripts)) {
892
+ if (!f.endsWith('.py')) continue;
893
+ const b = path.join(wsScripts, f);
894
+ if (!fs.existsSync(b)) drift.push(`${f}(缺失)`);
895
+ else if (fs.readFileSync(path.join(packScripts, f), 'utf8') !== fs.readFileSync(b, 'utf8')) drift.push(`${f}(不一致)`);
896
+ }
897
+ lines.push(`- 运行时脚本:${drift.length === 0 ? '✅ 与 pack 一致' : `⚠️ 与 pack 漂移:${drift.join('、')} → 重跑 \`/hk-init\` 刷新`}`);
898
+ }
899
+ const py = await run('python3', ['--version'], { timeoutMs: 10_000 });
900
+ lines.push(`- python3:${py.code === 0 ? `✅ ${py.stdout.trim()}` : '❌ 不可用(init 探测/校验脚本需要)'}`);
901
+ const cg = await run('codegraph', ['--version'], { timeoutMs: 15_000 });
902
+ lines.push(`- codegraph CLI:${cg.code === 0 ? `✅ ${cg.stdout.trim().split('\n')[0]}` : '⚠️ 未安装(init 的 CodeGraph 阶段会自动 npm install -g,需人批准)'}`);
903
+ return ok(lines.join('\n'));
904
+ }
905
+
906
+ export function registerCommands(ctx) {
907
+ const defs = [
908
+ { name: 'hk-setup', description: '收集代码仓库并登记 kit.json(--add <url> [--name n] [--path p] [--role r] [--branch b])', hint: '[--add <git-url> …]', handler: hkSetup },
909
+ { name: 'hk-init', description: '初始化 .harness 骨架/资产仓库绑定/脚本模板物化,并编排子工程文档与 CodeGraph 索引生成(幂等)', hint: '[--assets <url|init|local>] [--branch <分支>]', handler: hkInit },
910
+ { name: 'hk-fix', description: '启动轻量 fix 直通任务:脚手架 + PM 编排剧本', hint: '[任务名] <一句话描述> [--full|--light] [--auto]', handler: hkFix },
911
+ { name: 'hk-new', description: '启动全流程任务(Bootstrap):proposal 脚手架 + 需求澄清/profile 判定/定稿编排', hint: '[任务名] <需求描述> [--file <需求文件>] [--auto]', handler: hkNew },
912
+ { name: 'hk-propose', description: '执行 propose 方案阶段(BA→SA→RR→审批1,按 proposal profile)', hint: '[任务名]', handler: hkPropose },
913
+ { name: 'hk-apply', description: '执行 apply 实施阶段(Dev→CR→TE→审批2;含就绪预检与续接)', hint: '[任务名] [反馈]', handler: hkApply },
914
+ { name: 'hk-archive', description: '归档任务本轮产物到 _archive 并清空活目录(全流程附带 Spec/Memory Merge 收尾)', hint: '<任务名>', handler: hkArchive },
915
+ { name: 'hk-te', description: 'TE 环境串行租约(测试环境全局唯一):acquire 授权/排队、release 释放/退队、status 查看', hint: '[acquire|release <任务名> | status]', handler: hkTe },
916
+ { name: 'hk-sync', description: '资产仓库 git 同步:自动提交 → pull --rebase → 纯追加文件自动三路合并 → push(其余冲突中止回滚转人工)', handler: hkSync },
917
+ { name: 'hk-doctor', description: '检查 harness 工作区健康度(kit/角色/红线/流程)', hint: '', handler: hkDoctor },
918
+ ];
919
+ for (const def of defs) {
920
+ ctx.commands.register({
921
+ name: def.name,
922
+ description: def.description,
923
+ ...(def.hint ? { input: { hint: def.hint } } : {}),
924
+ handler: ({ agent, rawInput }) => def.handler({ agent, rawInput }),
925
+ });
926
+ }
927
+ }