dsh-harness-kit 0.1.6 → 0.2.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 (31) hide show
  1. package/README.md +27 -13
  2. package/README.zh-CN.md +26 -16
  3. package/client.js +108 -11
  4. package/docs/DETAIL.en.md +29 -9
  5. package/docs/DETAIL.md +14 -4
  6. package/kernel/advance.js +3 -3
  7. package/kernel/bindings.js +11 -6
  8. package/kernel/commands.js +150 -23
  9. package/kernel/local-files.js +5 -5
  10. package/kernel/metrics.js +280 -0
  11. package/kernel/panel.js +140 -6
  12. package/kernel/paths.js +62 -1
  13. package/kernel/setup.js +5 -4
  14. package/kernel/te.js +4 -4
  15. package/kernel/worktree.js +162 -20
  16. package/package.json +1 -1
  17. package/packs/ai-coding/assets/scripts/codebase_guide_init.py +1 -1
  18. package/packs/ai-coding/assets/scripts/harness_init.py +15 -6
  19. package/packs/ai-coding/assets/scripts/te_lease.py +6 -1
  20. package/packs/ai-coding/assets/scripts/update_board.py +30 -0
  21. package/packs/ai-coding/flows/init.yml +2 -2
  22. /package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/{app-CLAUDE.tmpl → app-AGENTS.tmpl} +0 -0
  23. /package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/{module-CLAUDE.tmpl → module-AGENTS.tmpl} +0 -0
  24. /package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +0 -0
  25. /package/packs/ai-coding/assets/templates/java/maven/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +0 -0
  26. /package/packs/ai-coding/assets/templates/java/maven-multimodule/{module-CLAUDE.tmpl → module-AGENTS.tmpl} +0 -0
  27. /package/packs/ai-coding/assets/templates/java/maven-multimodule/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +0 -0
  28. /package/packs/ai-coding/assets/templates/javascript/mobile-app/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +0 -0
  29. /package/packs/ai-coding/assets/templates/javascript/uniapp/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +0 -0
  30. /package/packs/ai-coding/assets/templates/javascript/vue-multimodule/{app-CLAUDE.tmpl → app-AGENTS.tmpl} +0 -0
  31. /package/packs/ai-coding/assets/templates/javascript/vue-multimodule/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +0 -0
package/kernel/panel.js CHANGED
@@ -28,6 +28,8 @@ import { readWorkspaces } from './worktree.js';
28
28
  import { listAllGitBranches } from './worktree.js';
29
29
  import { reconcileTestEnv, readTestEnv } from './te.js';
30
30
  import { readDecisions } from './worktree.js';
31
+ import { discoverSource, readLocalFiles, writeLocalFiles, provisionAllSlots } from './local-files.js';
32
+ import { collectTaskMetrics, readLatestTaskMetrics } from './metrics.js';
31
33
 
32
34
  /** 解析看板 markdown 表(7 列契约,见 commands.js boardTemplate)。
33
35
  * 容错与 commands.js parseBoardRow 同源:超列溢出并入「续接提示」,不足补 —。 */
@@ -198,7 +200,7 @@ export function claimTask(ws, task, by) {
198
200
  }
199
201
 
200
202
  // ---------------------------------------------------------- 任务 ↔ 会话绑定
201
- // .harness/tasks/sessions.json:{ tasks: { <任务名>: { sessionId, at } } }
203
+ // .harness/local/sessions.json:{ tasks: { <任务名>: { sessionId, at, sessions } } }
202
204
  // 实现已下沉 kernel/bindings.js(kernel 命令 handler 与自动续接引擎共用),此处转出口径不变。
203
205
  export { readTaskSessions, recordTaskSession } from './bindings.js';
204
206
 
@@ -208,19 +210,30 @@ export { readTaskSessions, recordTaskSession } from './bindings.js';
208
210
  * (PM 流程)生成 —— 有缺口时面板给出「运行初始化编排」入口而不是让用户
209
211
  * 对着「初始化成功」却缺文件的工程发懵。
210
212
  */
211
- export function initGaps(ws, kit) {
213
+ export function initGapItems(ws, kit) {
212
214
  const gaps = [];
213
- if (!fs.existsSync(path.join(ws, 'AGENTS.md')) && !fs.existsSync(path.join(ws, 'CLAUDE.md'))) gaps.push('根 AGENTS.md/CLAUDE.md');
215
+ if (!fs.existsSync(path.join(ws, 'AGENTS.md')) && !fs.existsSync(path.join(ws, 'CLAUDE.md'))) {
216
+ gaps.push({ kind: 'root-entry', repo: null, label: '根 AGENTS.md/CLAUDE.md', path: 'AGENTS.md', action: 'orchestrate' });
217
+ }
214
218
  for (const s of kit?.sources ?? []) {
215
219
  if (!s?.path) continue;
216
220
  const sp = path.join(ws, s.path);
217
221
  if (!fs.existsSync(sp)) continue;
218
- if (!fs.existsSync(path.join(sp, '.harness', 'build.json'))) gaps.push(`${s.name} 的 build.json`);
219
- if (!fs.existsSync(path.join(sp, 'AGENTS.md')) && !fs.existsSync(path.join(sp, 'CLAUDE.md'))) gaps.push(`${s.name} 的 AGENTS.md/CLAUDE.md`);
222
+ if (!fs.existsSync(path.join(sp, '.harness', 'build.json'))) {
223
+ gaps.push({ kind: 'build-json', repo: s.name, label: `${s.name} 的 build.json`, path: `${s.path}/.harness/build.json`, action: 'orchestrate' });
224
+ }
225
+ if (!fs.existsSync(path.join(sp, 'AGENTS.md')) && !fs.existsSync(path.join(sp, 'CLAUDE.md'))) {
226
+ gaps.push({ kind: 'subproject-entry', repo: s.name, label: `${s.name} 的 AGENTS.md/CLAUDE.md`, path: `${s.path}/AGENTS.md`, action: 'orchestrate' });
227
+ }
220
228
  }
221
229
  return gaps;
222
230
  }
223
231
 
232
+ /** 兼容旧调用:只返回人类可读标签。 */
233
+ export function initGaps(ws, kit) {
234
+ return initGapItems(ws, kit).map((g) => g.label);
235
+ }
236
+
224
237
  /**
225
238
  * 「需要你」注意力项(M4b):审批/待归档/同步阻塞·落后/初始化缺口。
226
239
  * 返回 [{level: block|warn, kind, task?, text, line?, jump?}],block 在前。
@@ -323,6 +336,18 @@ export function updateKit(ws, patch) {
323
336
  target.branch = s.branch.trim();
324
337
  }
325
338
  }
339
+ if (patch.worktree !== undefined) {
340
+ if (patch.worktree == null || typeof patch.worktree !== 'object' || Array.isArray(patch.worktree)) {
341
+ return { error: 'worktree 必须是对象' };
342
+ }
343
+ if (patch.worktree.autoClose !== undefined && typeof patch.worktree.autoClose !== 'boolean') {
344
+ return { error: 'worktree.autoClose 必须是布尔值' };
345
+ }
346
+ if (patch.worktree.targetSync !== undefined && !['safe', 'ff-only', 'off'].includes(patch.worktree.targetSync)) {
347
+ return { error: "worktree.targetSync 必须是 'safe' / 'ff-only' / 'off'" };
348
+ }
349
+ kit.worktree = { ...(kit.worktree ?? {}), ...patch.worktree };
350
+ }
326
351
  if (patch.autoSync !== undefined) {
327
352
  if (typeof patch.autoSync !== 'boolean') return { error: 'autoSync 必须是布尔值' };
328
353
  kit.assets = kit.assets ?? { mode: 'local' };
@@ -396,6 +421,7 @@ export function workspaceState(ws, { sync = null } = {}) {
396
421
  const slots = Object.fromEntries(Object.entries(ledger.slots).map(([repo, m]) => [repo,
397
422
  Object.entries(m).map(([slot, b]) => ({ slot, task: b.task, branch: b.branch, state: b.state ?? 'bound' }))]));
398
423
  const staleSlots = Object.entries(slots).flatMap(([repo, arr]) => arr.filter((s) => s.state === 'stale-unmerged').map((s) => ({ repo, ...s })));
424
+ const gapItems = initGapItems(ws, kit);
399
425
  // 已归档任务仍占着主工作树台账(典型:归档后才合入并切分支;没有后续归档触发释放)
400
426
  const archivedLedger = Object.entries(ledger.tasks ?? {})
401
427
  .filter(([task]) => !fs.existsSync(path.join(harnessDir(ws), 'deliverables', task)))
@@ -408,8 +434,9 @@ export function workspaceState(ws, { sync = null } = {}) {
408
434
  sync,
409
435
  slots,
410
436
  te: ledgerTe,
437
+ initGaps: gapItems,
411
438
  attention: (() => {
412
- const items = attentionItems(tasks, sync, initGaps(ws, kit), staleSlots, ledgerTe, readDecisions(ws), archivedLedger);
439
+ const items = attentionItems(tasks, sync, gapItems.map((g) => g.label), staleSlots, ledgerTe, readDecisions(ws), archivedLedger);
413
440
  // 初始化失败 → block 级常驻提示(页面重开仍可见;成功后自动消失)
414
441
  const initJob = initProgress.get(ws);
415
442
  if (initJob?.done && initJob.error) {
@@ -804,6 +831,7 @@ export function registerPanelApi(ctx) {
804
831
  sources: kit.sources ?? [],
805
832
  models: kit.models ?? {},
806
833
  assets: kit.assets ?? { mode: 'local' },
834
+ worktree: kit.worktree ?? {},
807
835
  // 流程配置(原 .harness/config.json,2026-11-18 迁入 kit.json)
808
836
  applyMode: kit.applyMode ?? 'auto',
809
837
  legacyConfig: readLegacyConfig(ws.path),
@@ -835,6 +863,112 @@ export function registerPanelApi(ctx) {
835
863
  },
836
864
  });
837
865
 
866
+ // 任务运行统计:按任务会话树汇总 model/effort/token/耗时;只读元数据。
867
+ const insightCache = new Map();
868
+ mount({
869
+ kind: 'exact',
870
+ path: '/harness-kit/task-insight',
871
+ async handler(req, res) {
872
+ if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
873
+ const url = new URL(req.url, 'http://x');
874
+ const ws = findWs(registry, url.searchParams.get('workspace'));
875
+ if (!ws) return sendJson(res, 404, { ok: false, error: '未知工作区' });
876
+ const task = url.searchParams.get('task');
877
+ if (!task) return sendJson(res, 400, { ok: false, error: '缺少 task' });
878
+ const kit = readKit(ws.path);
879
+ if (!kit) return sendJson(res, 404, { ok: false, error: '尚未初始化' });
880
+ const key = `${ws.path}::${task}`;
881
+ const hit = insightCache.get(key);
882
+ if (hit && Date.now() - hit.at < 10_000) return sendJson(res, 200, { ok: true, metrics: hit.metrics });
883
+ try {
884
+ let metrics = await collectTaskMetrics(ws.path, kit, task, {
885
+ sessionQuery: ctx.get('sessionQuery'),
886
+ tokenMeter: ctx.get('tokenMeter'),
887
+ sessions: ctx.get('sessions'),
888
+ });
889
+ if (metrics.coverage === 'unavailable') {
890
+ const archived = readLatestTaskMetrics(ws.path, task);
891
+ if (archived) metrics = { ...archived, source: 'archive' };
892
+ }
893
+ const payload = { ...metrics, task };
894
+ insightCache.set(key, { at: Date.now(), metrics: payload });
895
+ sendJson(res, 200, { ok: true, metrics: payload });
896
+ } catch (cause) {
897
+ sendJson(res, 500, { ok: false, error: cause.message });
898
+ }
899
+ },
900
+ });
901
+
902
+ // 本机配置(git-ignored)发现/确认:面板化 /hk-local;确认后只为已绑定 slot 补齐。
903
+ mount({
904
+ kind: 'exact',
905
+ path: '/harness-kit/local',
906
+ async handler(req, res) {
907
+ const ref = new URL(req.url, 'http://x').searchParams.get('workspace');
908
+ const ws = findWs(registry, ref);
909
+ if (!ws) return sendJson(res, 404, { ok: false, error: '未知工作区' });
910
+ const kit = readKit(ws.path);
911
+ if (!kit) return sendJson(res, 404, { ok: false, error: '尚未初始化' });
912
+ if (req.method === 'GET') {
913
+ try {
914
+ const manifest = readLocalFiles(ws.path);
915
+ const sources = [];
916
+ for (const source of kit.sources ?? []) {
917
+ if (!source?.path) continue;
918
+ const candidates = await discoverSource(ws.path, source);
919
+ const entry = manifest.sources?.[source.name] ?? {};
920
+ const approved = [...new Set([...(Array.isArray(source.localFiles) ? source.localFiles : []), ...(Array.isArray(entry.approved) ? entry.approved : [])])];
921
+ const skipped = Array.isArray(entry.skipped) ? entry.skipped : [];
922
+ sources.push({
923
+ name: source.name,
924
+ path: source.path,
925
+ mode: entry.mode === 'symlink' ? 'symlink' : 'copy',
926
+ approved,
927
+ skipped,
928
+ candidates: candidates.map((c) => ({ path: c.path, kind: c.kind, reason: c.reason, size: c.size, pending: !approved.includes(c.path) && !skipped.includes(c.path) })),
929
+ });
930
+ }
931
+ sendJson(res, 200, { ok: true, sources });
932
+ } catch (cause) {
933
+ sendJson(res, 500, { ok: false, error: cause.message });
934
+ }
935
+ return;
936
+ }
937
+ if (req.method === 'POST') {
938
+ try {
939
+ const { workspace, repo, action, paths } = JSON.parse(await readBody(req) || '{}');
940
+ const targetWs = findWs(registry, workspace);
941
+ if (!targetWs) return sendJson(res, 404, { ok: false, error: '未知工作区' });
942
+ if (!['approve', 'skip'].includes(action)) return sendJson(res, 400, { ok: false, error: "action 必须是 'approve' 或 'skip'" });
943
+ const targetKit = readKit(targetWs.path);
944
+ const source = (targetKit?.sources ?? []).find((s) => s.name === repo);
945
+ if (!source) return sendJson(res, 404, { ok: false, error: `未知子工程:${repo ?? '?'}` });
946
+ const candidates = await discoverSource(targetWs.path, source);
947
+ const valid = new Set(candidates.map((c) => c.path));
948
+ const manifest = readLocalFiles(targetWs.path);
949
+ const entry = manifest.sources?.[repo] ?? {};
950
+ const approved = new Set(Array.isArray(entry.approved) ? entry.approved : []);
951
+ const skipped = new Set(Array.isArray(entry.skipped) ? entry.skipped : []);
952
+ const requested = Array.isArray(paths) && paths.length > 0 ? paths : candidates.map((c) => c.path);
953
+ const chosen = [...new Set(requested)].filter((p) => valid.has(p));
954
+ if (chosen.length === 0) return sendJson(res, 400, { ok: false, error: '没有有效的候选路径' });
955
+ for (const p of chosen) {
956
+ if (action === 'approve') { approved.add(p); skipped.delete(p); }
957
+ else { skipped.add(p); approved.delete(p); }
958
+ }
959
+ manifest.sources[repo] = { ...entry, approved: [...approved], skipped: [...skipped], updatedAt: new Date().toISOString() };
960
+ writeLocalFiles(targetWs.path, manifest);
961
+ const notes = action === 'approve' ? await provisionAllSlots(targetWs.path, [source]) : [];
962
+ sendJson(res, 200, { ok: true, notes });
963
+ } catch (cause) {
964
+ sendJson(res, 500, { ok: false, error: cause.message });
965
+ }
966
+ return;
967
+ }
968
+ sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
969
+ },
970
+ });
971
+
838
972
  // 新建任务「浏览…」:工作区内目录列举(仅供选文件;拒绝越界/符号链接逃逸;过滤 .git 与 node_modules)
839
973
  mount({
840
974
  kind: 'exact',
package/kernel/paths.js CHANGED
@@ -42,8 +42,69 @@ export function writeKit(ws, kit) {
42
42
  fs.writeFileSync(p, JSON.stringify(kit, null, 2) + '\n', 'utf8');
43
43
  }
44
44
 
45
+ /** 本机状态目录:.harness/local/(会话绑定/工作区台账/决策点/租约/本机配置)。 */
46
+ export function localDir(ws) {
47
+ return path.join(harnessDir(ws), 'local');
48
+ }
49
+
50
+ /** 旧本机状态 → .harness/local/ 的迁移表(只迁移,不删除非空新文件)。 */
51
+ const LEGACY_LOCAL = [
52
+ ['tasks/sessions.json', 'sessions.json'],
53
+ ['tasks/auto-advance.json', 'auto-advance.json'],
54
+ ['tasks/worktrees.json', 'worktrees.json'],
55
+ ['tasks/decisions.json', 'decisions.json'],
56
+ ['tasks/test-env.json', 'test-env.json'],
57
+ ['tasks/local-files.json', 'local-files.json'],
58
+ ];
59
+
60
+ /** 确保 .gitignore 排除 local/(旧工作区迁移时也必须补上,否则本机状态会被提交)。 */
61
+ function ensureLocalIgnored(ws) {
62
+ try {
63
+ const gi = path.join(harnessDir(ws), '.gitignore');
64
+ const cur = fs.existsSync(gi) ? fs.readFileSync(gi, 'utf8') : '';
65
+ if (!cur.split('\n').some((l) => l.trim() === 'local/')) {
66
+ fs.appendFileSync(gi, `${cur.endsWith('\n') || cur === '' ? '' : '\n'}# 本机状态(机器本地,不共享、勿提交)\nlocal/\n`, 'utf8');
67
+ }
68
+ } catch { /* 忽略失败不阻断 */ }
69
+ }
70
+
71
+ /** 把旧位置的本机状态搬到 .harness/local/;幂等,失败不阻断。 */
72
+ export function migrateLegacyLocalState(ws) {
73
+ const dir = localDir(ws);
74
+ fs.mkdirSync(dir, { recursive: true });
75
+ ensureLocalIgnored(ws);
76
+ for (const [oldRel, name] of LEGACY_LOCAL) {
77
+ const oldPath = path.join(harnessDir(ws), oldRel);
78
+ const newPath = path.join(dir, name);
79
+ if (!fs.existsSync(oldPath) || fs.existsSync(newPath)) continue;
80
+ try { fs.renameSync(oldPath, newPath); } catch {
81
+ try { fs.copyFileSync(oldPath, newPath); fs.rmSync(oldPath, { force: true }); } catch { /* 下一次读取再试 */ }
82
+ }
83
+ }
84
+ }
85
+
86
+ /**
87
+ * 本机状态文件路径:默认 .harness/local/<name>;旧路径存在且新路径不存在时先迁移。
88
+ * legacyRel 用于兼容 0.2.0 以前的 tasks/*.json 布局。
89
+ */
90
+ export function localStatePath(ws, name, legacyRel = null) {
91
+ const dir = localDir(ws);
92
+ fs.mkdirSync(dir, { recursive: true });
93
+ ensureLocalIgnored(ws);
94
+ const file = path.join(dir, name);
95
+ if (legacyRel && !fs.existsSync(file)) {
96
+ const oldPath = path.join(harnessDir(ws), legacyRel);
97
+ if (fs.existsSync(oldPath)) {
98
+ try { fs.renameSync(oldPath, file); } catch {
99
+ try { fs.copyFileSync(oldPath, file); fs.rmSync(oldPath, { force: true }); } catch { /* 继续读旧路径 */ }
100
+ }
101
+ }
102
+ }
103
+ return file;
104
+ }
105
+
45
106
  export function defaultKit() {
46
- return { version: 1, pack: DEFAULT_PACK, hosts: ['dsh'], sources: [], models: {} };
107
+ return { version: 1, pack: DEFAULT_PACK, hosts: ['dsh'], sources: [], models: {}, worktree: { autoClose: true, targetSync: 'safe' } };
47
108
  }
48
109
 
49
110
  /** kit.json sources plus the always-protected e2e/ zone. */
package/kernel/setup.js CHANGED
@@ -3,7 +3,7 @@
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { runGit } from './exec.js';
6
- import { readKit, writeKit, defaultKit, harnessDir, packDir, kitPath } from './paths.js';
6
+ import { readKit, writeKit, defaultKit, harnessDir, packDir, kitPath, migrateLegacyLocalState } from './paths.js';
7
7
 
8
8
  export function guessRole(name) {
9
9
  if (/front|web|ui/i.test(name)) return 'frontend';
@@ -356,7 +356,7 @@ export async function runInit(ws, { assets, branch, sources = [], onProgress } =
356
356
  '',
357
357
  ].join('\n')],
358
358
  // transient logs + pack 管理运行时 stay out of the assets repo (independent-repo layout)
359
- ['.gitignore', '.logs/**/*\n!.logs/**/\n!.logs/**/.gitkeep\n# pack 管理运行时(/hk-init 每次刷新,勿手改、勿提交)\nscripts/\n# 本机状态(各机独立,勿提交:会话绑定/续接点火/工作区分配/决策点/环境租约)\ntasks/sessions.json\ntasks/auto-advance.json\ntasks/worktrees.json\ntasks/decisions.json\ntasks/test-env.json\ntasks/local-files.json\n'],
359
+ ['.gitignore', '.logs/**/*\n!.logs/**/\n!.logs/**/.gitkeep\n# pack 管理运行时(/hk-init 每次刷新,勿手改、勿提交)\nscripts/\n# 本机状态(机器本地,不共享、勿提交)\nlocal/\n'],
360
360
  ]) {
361
361
  const abs = path.join(hd, file);
362
362
  if (!fs.existsSync(abs)) {
@@ -390,8 +390,9 @@ export async function runInit(ws, { assets, branch, sources = [], onProgress } =
390
390
  }
391
391
  }
392
392
 
393
- // 存量迁移:本机状态文件(会话绑定/续接点火/工作区分配/决策点/环境租约)不入资产库
394
- const LOCAL_STATE = ['tasks/sessions.json', 'tasks/auto-advance.json', 'tasks/worktrees.json', 'tasks/decisions.json', 'tasks/test-env.json'];
393
+ // 存量迁移:本机状态统一到 .harness/local/(旧 tasks/*.json 自动搬移),整目录不进资产库
394
+ migrateLegacyLocalState(ws);
395
+ const LOCAL_STATE = ['local/'];
395
396
  if (fs.existsSync(giPath)) {
396
397
  const cur = fs.readFileSync(giPath, 'utf8');
397
398
  const missing = LOCAL_STATE.filter((e) => !cur.split('\n').some((l) => l.trim() === e));
package/kernel/te.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // TE 环境串行排队(M3 一期,2026-11-15 定):测试环境全局只有一个
2
2
  // (起服务/连 TDengine/jmeter 不可多任务并发),TE 阶段按租约串行:
3
3
  //
4
- // - 租约台账 .harness/tasks/test-env.json(本机状态,不进资产 git):
4
+ // - 租约台账 .harness/local/test-env.json(本机状态,不进资产 git):
5
5
  // { "holder": "task-x", "since": "ISO", "queue": ["task-y"] }
6
6
  // - PM 派发 TE Worker 前必须先 `/hk-te acquire <任务>`:
7
7
  // 空闲 → 授权;自己持有 → 已持有;别人持有 → 排队并暂停 TE 阶段(内核不可抢占运行中的 Worker,门在派发前)
@@ -10,10 +10,10 @@
10
10
  // - grace:holder 已授权但看板链还没标 TE▶(PM 先 acquire 后写板的时序窗口)不释放
11
11
  import fs from 'node:fs';
12
12
  import path from 'node:path';
13
- import { harnessDir } from './paths.js';
13
+ import { localStatePath } from './paths.js';
14
14
  import { keepLedgerLocal } from './worktree.js';
15
15
 
16
- const envPath = (ws) => path.join(harnessDir(ws), 'tasks', 'test-env.json');
16
+ const envPath = (ws) => localStatePath(ws, 'test-env.json', 'tasks/test-env.json');
17
17
 
18
18
  export function readTestEnv(ws) {
19
19
  try {
@@ -29,7 +29,7 @@ export function readTestEnv(ws) {
29
29
  function writeTestEnv(ws, env) {
30
30
  fs.mkdirSync(path.dirname(envPath(ws)), { recursive: true });
31
31
  fs.writeFileSync(envPath(ws), `${JSON.stringify(env, null, 2)}\n`, 'utf8');
32
- keepLedgerLocal(ws, 'tasks/test-env.json');
32
+ keepLedgerLocal(ws);
33
33
  }
34
34
 
35
35
  /** 看板链中 TE 阶段的标记(✅ 完成 / — 跳过 → 不再需要环境;▶/…/⛔/缺 → 仍可能需要)。 */
@@ -13,7 +13,7 @@
13
13
  // - 卫生纪律:分配给新任务前 slot 必须干净(git status 空),脏 slot 拒绝分配并给清理指引
14
14
  // (不自动 stash——残留可能是有价值的工作,由人裁决)。
15
15
  //
16
- // 台账 .harness/tasks/worktrees.json(v2):
16
+ // 台账 .harness/local/worktrees.json(v2):
17
17
  // {
18
18
  // "version": 2,
19
19
  // "slots": { "<repo>": { "slot-1": { "task": "…", "branch": "…", "since": "ISO", "state": "bound" | "stale-unmerged" } } },
@@ -23,11 +23,11 @@
23
23
  // M1 刚上线即改为池化,野外无 v1 数据需要迁移。
24
24
  import fs from 'node:fs';
25
25
  import path from 'node:path';
26
- import { harnessDir } from './paths.js';
26
+ import { harnessDir, localStatePath } from './paths.js';
27
27
  import { runGit } from './exec.js';
28
28
  import { provisionLocalFiles } from './local-files.js';
29
29
 
30
- const ledgerPath = (ws) => path.join(harnessDir(ws), 'tasks', 'worktrees.json');
30
+ const ledgerPath = (ws) => localStatePath(ws, 'worktrees.json', 'tasks/worktrees.json');
31
31
  const worktreeRoot = (ws, repo) => path.join(ws, '.worktrees', repo);
32
32
 
33
33
  // --------------------------------------------------------------- 台账读写
@@ -47,19 +47,19 @@ function writeWorkspaces(ws, { slots, tasks }) {
47
47
  keepLedgerLocal(ws);
48
48
  }
49
49
 
50
- /** 台账本地化:.gitignore 排除 + 已追踪的旧文件摘除追踪(保留本地文件)。失败容忍。 */
51
- export function keepLedgerLocal(ws, entry = 'tasks/worktrees.json') {
50
+ /** 本机状态本地化:.gitignore 排除整个 .harness/local/;旧 tasks/*.json 行保留不影响。 */
51
+ export function keepLedgerLocal(ws, _entry = null) {
52
52
  try {
53
53
  const hd = harnessDir(ws);
54
54
  const gi = path.join(hd, '.gitignore');
55
55
  const cur = fs.existsSync(gi) ? fs.readFileSync(gi, 'utf8') : '';
56
- if (!cur.split('\n').some((l) => l.trim() === entry)) {
57
- fs.appendFileSync(gi, `${cur.endsWith('\n') || cur === '' ? '' : '\n'}# 本机工作区/环境台账(机器本地状态,不共享、勿提交)\n${entry}\n`, 'utf8');
56
+ if (!cur.split('\n').some((l) => l.trim() === 'local/')) {
57
+ fs.appendFileSync(gi, `${cur.endsWith('\n') || cur === '' ? '' : '\n'}# 本机状态(机器本地,不共享、勿提交)\nlocal/\n`, 'utf8');
58
58
  }
59
59
  if (fs.existsSync(path.join(hd, '.git'))) {
60
- runGit(['rm', '--cached', '--quiet', '--ignore-unmatch', entry], { cwd: hd });
60
+ runGit(['rm', '-r', '--cached', '--quiet', '--ignore-unmatch', 'local'], { cwd: hd });
61
61
  }
62
- } catch { /* 容忍:最坏结果是台账被同步,跨用户挡路问题复现 */ }
62
+ } catch { /* 容忍:最坏结果是本机状态被同步 */ }
63
63
  }
64
64
 
65
65
  // 兼容旧测试与外部引用
@@ -212,7 +212,7 @@ async function mergedStatus(repoDir, branch, base) {
212
212
 
213
213
  // --------------------------------------------------------------- 决策点(需人裁决的结构性阻塞)
214
214
 
215
- const decisionsPath = (ws) => path.join(harnessDir(ws), 'tasks', 'decisions.json');
215
+ const decisionsPath = (ws) => localStatePath(ws, 'decisions.json', 'tasks/decisions.json');
216
216
 
217
217
  /** 待裁决决策点(本机状态):{ <task>: { code, text, options, at } }。 */
218
218
  export function readDecisions(ws) {
@@ -225,7 +225,7 @@ export function readDecisions(ws) {
225
225
  function writeDecisions(ws, decisions) {
226
226
  fs.mkdirSync(path.dirname(decisionsPath(ws)), { recursive: true });
227
227
  fs.writeFileSync(decisionsPath(ws), `${JSON.stringify(decisions, null, 2)}\n`, 'utf8');
228
- keepLedgerLocal(ws, 'tasks/decisions.json');
228
+ keepLedgerLocal(ws);
229
229
  }
230
230
 
231
231
  /** 记录决策点(工作区分配拒绝等);重复记录覆盖(保持最新文本)。 */
@@ -257,20 +257,144 @@ export async function describeMainWorktree(ws, source, { maxLines = 10 } = {}) {
257
257
  ].join('\n');
258
258
  }
259
259
 
260
+ /** 判断 ancestor 是否为 descendant 的祖先(git 退出码 0 = 是)。 */
261
+ async function isAncestor(repoDir, ancestor, descendant) {
262
+ return (await runGit(['merge-base', '--is-ancestor', ancestor, descendant], { cwd: repoDir })).code === 0;
263
+ }
264
+
265
+ /** 把目标本地分支的上游设为 origin/<target>(远端分支存在时;失败不阻断)。 */
266
+ async function setTargetUpstream(repoDir, target) {
267
+ const remote = await runGit(['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${target}`], { cwd: repoDir });
268
+ if (remote.code !== 0) return;
269
+ await runGit(['branch', '--set-upstream-to', `origin/${target}`, target], { cwd: repoDir });
270
+ }
271
+
272
+ /** 把 origin/<target> 干净地并入本地目标(仅本地,不推送);冲突中止回滚。 */
273
+ async function mergeRemoteIntoTarget(ws, repoDir, name, target, remoteRev, out) {
274
+ const localRev = (await runGit(['rev-parse', 'refs/heads/' + target], { cwd: repoDir })).stdout.trim();
275
+ const holder = await worktreeOnBranch(repoDir, target);
276
+ let cwd = holder;
277
+ let tempDir = null;
278
+ if (!cwd) {
279
+ tempDir = path.join(worktreeRoot(ws, name), '_sync');
280
+ fs.rmSync(tempDir, { recursive: true, force: true });
281
+ fs.mkdirSync(path.dirname(tempDir), { recursive: true });
282
+ const add = await runGit(['worktree', 'add', tempDir, target], { cwd: repoDir });
283
+ if (add.code !== 0) {
284
+ out.refused.push({ repo: name, reason: `目标 ${target} 同步工作树创建失败:${(add.stderr || '').trim().split('\n')[0]}` });
285
+ return false;
286
+ }
287
+ cwd = tempDir;
288
+ }
289
+ if (await isDirty(cwd)) {
290
+ if (tempDir) await runGit(['worktree', 'remove', '--force', tempDir], { cwd: repoDir });
291
+ out.refused.push({ repo: name, reason: `目标分支 ${target} 所在工作树有未提交改动,无法并入远端:${cwd}` });
292
+ return false;
293
+ }
294
+ const mg = await runGit(['merge', '--no-edit', `origin/${target}`], { cwd });
295
+ if (mg.code !== 0) {
296
+ const files = (await runGit(['diff', '--name-only', '--diff-filter=U'], { cwd })).stdout.trim().split('\n').filter(Boolean);
297
+ await runGit(['merge', '--abort'], { cwd });
298
+ if (tempDir) { await runGit(['worktree', 'remove', '--force', tempDir], { cwd: repoDir }); fs.rmSync(tempDir, { recursive: true, force: true }); }
299
+ out.refused.push({ repo: name, reason: `目标 ${target} 与 origin/${target} 分叉且自动并入冲突(已回滚):${files.slice(0, 6).join('、') || '见 git status'}` });
300
+ return false;
301
+ }
302
+ if (tempDir) { await runGit(['worktree', 'remove', '--force', tempDir], { cwd: repoDir }); fs.rmSync(tempDir, { recursive: true, force: true }); }
303
+ await setTargetUpstream(repoDir, target);
304
+ out.synced.push({ repo: name, target, from: localRev.slice(0, 12), to: remoteRev.slice(0, 12), merged: true });
305
+ return true;
306
+ }
307
+
308
+ /**
309
+ * 合并前把本地目标与 origin/<target> 对齐。
310
+ * - safe(默认):落后 → 快进;领先 → 保留;分叉 → 干净地并入 origin(冲突回滚)。
311
+ * - ff-only:落后 → 快进;领先/分叉 → 停止。
312
+ * - off:不同步。
313
+ * 返回 true = 可以继续;false = 已写入 out.refused。
314
+ * 不做 rebase、不强制更新、不推送。
315
+ */
316
+ async function syncTargetBranch(ws, repoDir, name, target, out, mode = 'safe') {
317
+ const hasOrigin = (await runGit(['remote', 'get-url', 'origin'], { cwd: repoDir })).code === 0;
318
+ if (!hasOrigin) return true;
319
+ const remoteRef = `refs/remotes/origin/${target}`;
320
+ const hadRemoteRef = (await runGit(['rev-parse', '--verify', '--quiet', remoteRef], { cwd: repoDir })).code === 0;
321
+ // fetch 是只读远端操作;失败时若有已知远端分支则停止,避免在旧目标上合入。
322
+ const fetched = await runGit(['fetch', 'origin', target], { cwd: repoDir, timeoutMs: 30_000 });
323
+ if (fetched.code !== 0) {
324
+ if (hadRemoteRef) {
325
+ out.refused.push({
326
+ repo: name,
327
+ reason: `目标 ${target} 远端拉取失败(${(fetched.stderr || '').trim().split('\n')[0] || '网络/权限'});修复后重试,或加 --no-merge 仅归档`,
328
+ });
329
+ return false;
330
+ }
331
+ // 远端还没有同名分支:按纯本地目标处理。
332
+ return true;
333
+ }
334
+ const remoteRev = (await runGit(['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${target}`], { cwd: repoDir })).stdout.trim();
335
+ if (!remoteRev) return true;
336
+ const localRev = (await runGit(['rev-parse', '--verify', '--quiet', `refs/heads/${target}`], { cwd: repoDir })).stdout.trim();
337
+ if (!localRev) return true;
338
+ if (localRev === remoteRev) {
339
+ await setTargetUpstream(repoDir, target);
340
+ return true;
341
+ }
342
+ if (await isAncestor(repoDir, localRev, remoteRev)) {
343
+ // 本地目标落后远端:优先在 checkout 它的干净工作树里快进;否则直接更新 ref。
344
+ const holder = await worktreeOnBranch(repoDir, target);
345
+ if (holder) {
346
+ if (await isDirty(holder)) {
347
+ out.refused.push({ repo: name, reason: `目标分支 ${target} 所在工作树有未提交改动,无法快进:${holder}` });
348
+ return false;
349
+ }
350
+ const ff = await runGit(['merge', '--ff-only', `origin/${target}`], { cwd: holder });
351
+ if (ff.code !== 0) {
352
+ out.refused.push({ repo: name, reason: `目标 ${target} 快进失败:${(ff.stderr || '').trim().split('\n')[0]}` });
353
+ return false;
354
+ }
355
+ } else {
356
+ const ur = await runGit(['update-ref', `refs/heads/${target}`, remoteRev], { cwd: repoDir });
357
+ if (ur.code !== 0) {
358
+ out.refused.push({ repo: name, reason: `目标 ${target} 本地 ref 快进失败` });
359
+ return false;
360
+ }
361
+ }
362
+ await setTargetUpstream(repoDir, target);
363
+ out.synced.push({ repo: name, target, from: localRev.slice(0, 12), to: remoteRev.slice(0, 12) });
364
+ return true;
365
+ }
366
+ if (await isAncestor(repoDir, remoteRev, localRev)) {
367
+ // 本地目标领先远端:这是 autoClose 未推送合并提交后的常态,safe 模式不应阻止下一次收尾。
368
+ if (mode === 'ff-only') {
369
+ out.refused.push({ repo: name, reason: `目标 ${target} 有未推送的本地提交(领先 origin/${target});ff-only 模式停止,改用 safe 或先推送` });
370
+ return false;
371
+ }
372
+ await setTargetUpstream(repoDir, target);
373
+ return true;
374
+ }
375
+ if (mode !== 'safe') {
376
+ out.refused.push({ repo: name, reason: `目标 ${target} 与 origin/${target} 已分叉;ff-only 模式停止,改用 safe 或先人工合并` });
377
+ return false;
378
+ }
379
+ return mergeRemoteIntoTarget(ws, repoDir, name, target, remoteRev, out);
380
+ }
381
+
260
382
  /**
261
383
  * 本地合入任务分支到目标基线(B 方案,2026-11-17 定):不推送,推送仍归人。
262
- * 人通过 /hk-archive <任务> --merge(可带 repo:branch 覆盖)显式确认目标分支——
263
- * 确认即触发本次调用。合并提交留在目标分支上;冲突则中止并报告,不污染基线。
264
384
  *
385
+ * 2026-11-22(0.2.0):合并前先把本地目标快进到 origin/<target>(只 ff),
386
+ * 已合入(本地或远端)不再重复 merge;冲突/目标脏/目标分叉全部在归档前停止。
265
387
  * 合并位置:目标分支若被某工作树 checkout 且干净 → 就地合并;否则建临时工作树
266
388
  * (.worktrees/<仓>/_merge)合并后删除。主工作树脏 → 拒绝该仓。
267
- * 返回 { merged: [{repo,target,commit}], conflicts: [{repo,target,files}], refused: [{repo,reason}] }。
389
+ *
390
+ * 返回 { merged, conflicts, refused, alreadyMerged, synced, planned, dryRun }。
268
391
  */
269
- export async function mergeTaskBranches(ws, kit, task, overrides = {}) {
270
- const out = { merged: [], conflicts: [], refused: [] };
392
+ export async function mergeTaskBranches(ws, kit, task, overrides = {}, { syncTarget = 'safe', dryRun = false } = {}) {
393
+ const out = { merged: [], conflicts: [], refused: [], alreadyMerged: [], synced: [], planned: [], dryRun: dryRun === true };
271
394
  const ledger = readWorkspaces(ws);
272
395
  const entry = ledger.tasks?.[task];
273
- if (!entry) { out.refused.push({ repo: '-', reason: `台账无任务 ${task} 的工作区记录` }); return out; }
396
+ // 无台账 = 本任务没有分配过代码工作区(纯文档任务),不是错误;直接跳过合入。
397
+ if (!entry) { out.noWorkspace = true; return out; }
274
398
 
275
399
  for (const [name, info] of Object.entries(entry.repos ?? {})) {
276
400
  if (!info || !info.branch) continue; // 无分支记录(非 git 仓)跳过;main/slot 两种放置都可合入
@@ -290,6 +414,7 @@ export async function mergeTaskBranches(ws, kit, task, overrides = {}) {
290
414
  const cb = await runGit(['branch', local, target], { cwd: repoDir });
291
415
  if (cb.code !== 0) { out.refused.push({ repo: name, reason: `目标 ${target} 无法建立本地分支` }); continue; }
292
416
  }
417
+ await setTargetUpstream(repoDir, local);
293
418
  target = local;
294
419
  }
295
420
  if ((await runGit(['rev-parse', '--verify', `refs/heads/${target}`], { cwd: repoDir })).code !== 0) {
@@ -302,6 +427,21 @@ export async function mergeTaskBranches(ws, kit, task, overrides = {}) {
302
427
  continue;
303
428
  }
304
429
 
430
+ // 已合入本地目标:无需同步/合并,直接释放。远端 MR 合入的情况在 sync 后再判一次。
431
+ if (await mergedLocally(repoDir, branch, target)) {
432
+ out.alreadyMerged.push({ repo: name, target });
433
+ continue;
434
+ }
435
+ if (dryRun) {
436
+ out.planned.push({ repo: name, target, branch });
437
+ continue;
438
+ }
439
+ if (syncTarget !== 'off' && !(await syncTargetBranch(ws, repoDir, name, target, out, syncTarget))) continue;
440
+ if (await mergedLocally(repoDir, branch, target)) {
441
+ out.alreadyMerged.push({ repo: name, target });
442
+ continue;
443
+ }
444
+
305
445
  // 目标分支被哪个工作树 checkout?
306
446
  const holder = await worktreeOnBranch(repoDir, target);
307
447
  let mergeCwd = null;
@@ -681,12 +821,14 @@ async function releaseEntry(ws, kit, task, entry, ledger) {
681
821
  await runGit(['branch', '-d', info.branch], { cwd: repoDir });
682
822
  out.released.push({ source: name, placement: 'main', note: `主工作树已切回 ${mergedBase} 并删已合入分支` });
683
823
  } else {
684
- // 当前在别的分支:只释放台账,不改用户当前分支,也不删分支——
685
- // 分支清理交给人在确认后处理,避免自动对账产生额外副作用。
824
+ // 当前在别的分支:不改用户当前分支,但已确认合入的任务分支可以安全删除(-d 会拒绝未合入)。
825
+ const del = await runGit(['branch', '-d', info.branch], { cwd: repoDir });
686
826
  out.released.push({
687
827
  source: name,
688
828
  placement: 'main',
689
- note: `主工作树当前在 ${cur || '(detached)'};任务分支已合入 ${mergedBase},仅释放台账`,
829
+ note: del.code === 0
830
+ ? `主工作树当前在 ${cur || '(detached)'};任务分支已合入 ${mergedBase},已删除任务分支`
831
+ : `主工作树当前在 ${cur || '(detached)'};任务分支已合入 ${mergedBase},但分支仍被其他工作树使用,保留`,
690
832
  });
691
833
  }
692
834
  continue;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-harness-kit",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "description": "Multi-agent engineering workflow for DeepSeek Harness: roles, flows, guards and workspace assets.",
5
5
  "private": false,
6
6
  "license": "MIT",
@@ -22,7 +22,7 @@ def instruction_target(path: Path) -> Path:
22
22
  return path / "AGENTS.md"
23
23
 
24
24
  # 模块 / App 级 AGENTS.md 的**机器可读元信息行**:行内加粗键值 `- **键**:值`,**不是** `### 标题`。
25
- # 这是 `.harness/templates/*/{module,app}-CLAUDE.tmpl`(内容按 AGENTS.md 生成)与本检查器之间的**唯一契约**:
25
+ # 这是 `.harness/templates/*/{module,app}-AGENTS.tmpl`(内容按 AGENTS.md 生成)与本检查器之间的**唯一契约**:
26
26
  # 检查器按这些键做子串匹配,模板必须原样产出对应行 —— 模板若教标题形态,
27
27
  # 「严格照模板生成」的文档必然报 WARN(历史上前端 41 个 App 全中)。
28
28
  # `tests/harness/test_codebase_guide_init.py` 把两边钉死,改这里必须同步改模板。