dsh-harness-kit 0.1.5 → 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 (36) hide show
  1. package/README.md +30 -15
  2. package/README.zh-CN.md +29 -18
  3. package/client.js +108 -11
  4. package/docs/DETAIL.en.md +30 -10
  5. package/docs/DETAIL.md +15 -5
  6. package/kernel/advance.js +3 -3
  7. package/kernel/bindings.js +11 -6
  8. package/kernel/commands.js +257 -20
  9. package/kernel/local-files.js +175 -0
  10. package/kernel/metrics.js +280 -0
  11. package/kernel/panel.js +141 -7
  12. package/kernel/paths.js +62 -1
  13. package/kernel/setup.js +20 -19
  14. package/kernel/te.js +4 -4
  15. package/kernel/worktree.js +164 -20
  16. package/package.json +1 -1
  17. package/packs/ai-coding/agents/business-analyst.md +4 -4
  18. package/packs/ai-coding/agents/code-reviewer.md +6 -6
  19. package/packs/ai-coding/agents/developer.md +5 -5
  20. package/packs/ai-coding/agents/solution-architect.md +2 -2
  21. package/packs/ai-coding/assets/scripts/codebase_guide_init.py +70 -48
  22. package/packs/ai-coding/assets/scripts/harness_init.py +30 -11
  23. package/packs/ai-coding/assets/scripts/te_lease.py +106 -0
  24. package/packs/ai-coding/assets/scripts/update_board.py +30 -0
  25. package/packs/ai-coding/assets/scripts/verify.py +3 -3
  26. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/{app-CLAUDE.tmpl → app-AGENTS.tmpl} +5 -5
  27. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/{module-CLAUDE.tmpl → module-AGENTS.tmpl} +5 -5
  28. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +3 -3
  29. package/packs/ai-coding/assets/templates/java/maven/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +3 -3
  30. package/packs/ai-coding/assets/templates/java/maven-multimodule/{module-CLAUDE.tmpl → module-AGENTS.tmpl} +5 -5
  31. package/packs/ai-coding/assets/templates/java/maven-multimodule/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +3 -3
  32. package/packs/ai-coding/assets/templates/javascript/mobile-app/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +3 -3
  33. package/packs/ai-coding/assets/templates/javascript/uniapp/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +3 -3
  34. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/{app-CLAUDE.tmpl → app-AGENTS.tmpl} +4 -4
  35. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +3 -3
  36. package/packs/ai-coding/flows/init.yml +7 -7
@@ -0,0 +1,280 @@
1
+ // 任务运行统计:从 DSH sessionQuery / sessions 读取会话树,汇总模型、token、耗时与失败。
2
+ // 只收元数据,不落 prompt / 消息正文 / 工具参数 / 原始 session id。
3
+ // 两个消费面共用同一采集函数:面板实时查看、归档时写 metrics/<R>.json。
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { harnessDir } from './paths.js';
7
+ import { readTaskSessions } from './bindings.js';
8
+
9
+ const USAGE_KEYS = ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'reasoningTokens'];
10
+
11
+ function emptyUsage() {
12
+ return Object.fromEntries(USAGE_KEYS.map((k) => [k, 0]));
13
+ }
14
+
15
+ function addUsage(target, usage) {
16
+ if (!usage || typeof usage !== 'object') return false;
17
+ let found = false;
18
+ for (const key of USAGE_KEYS) {
19
+ const value = Number(usage[key]);
20
+ if (Number.isFinite(value) && value >= 0) { target[key] += value; found = true; }
21
+ }
22
+ return found;
23
+ }
24
+
25
+ function sessionLabel(id, primaryId, catalog) {
26
+ if (id === primaryId) return 'PM';
27
+ return catalog.get(id) || '子会话';
28
+ }
29
+
30
+ function flattenTree(nodes, out) {
31
+ for (const node of nodes ?? []) {
32
+ if (node?.session?.header?.id) out.push(node.session.header.id);
33
+ flattenTree(node?.descendants, out);
34
+ }
35
+ }
36
+
37
+ function snapshotFromLive(session) {
38
+ if (!session) return null;
39
+ try {
40
+ const events = typeof session.snapshotEvents === 'function'
41
+ ? session.snapshotEvents()
42
+ : (typeof session.ownEvents === 'function' ? session.ownEvents() : []);
43
+ return { header: session.header ?? {}, events, inherited: Number(session.inheritedEventCount ?? 0) };
44
+ } catch { return null; }
45
+ }
46
+
47
+ /**
48
+ * 采集一个任务的运行统计。
49
+ * services: { sessionQuery?, tokenMeter?, sessions?, currentSession? }
50
+ * 返回 { schemaVersion, generatedAt, coverage, agents, totals, notes }。
51
+ */
52
+ export async function collectTaskMetrics(ws, kit, task, services = {}) {
53
+ const generatedAt = new Date().toISOString();
54
+ const notes = [];
55
+ const binding = readTaskSessions(ws)[task] ?? {};
56
+ const primaryId = typeof binding.sessionId === 'string' ? binding.sessionId : null;
57
+ const boundIds = [...new Set([
58
+ primaryId,
59
+ ...(Array.isArray(binding.sessions) ? binding.sessions.map((x) => x?.id) : []),
60
+ ].filter((x) => typeof x === 'string' && x))];
61
+
62
+ const ids = new Set(boundIds);
63
+ const { sessionQuery, tokenMeter, sessions, currentSession } = services;
64
+ const canTrace = !!sessionQuery && typeof sessionQuery.traceSession === 'function';
65
+ const canRead = !!sessionQuery && typeof sessionQuery.readSession === 'function';
66
+
67
+ if (canTrace) {
68
+ for (const id of boundIds) {
69
+ try {
70
+ const trace = await sessionQuery.traceSession(id);
71
+ const found = [];
72
+ if (trace?.target?.header?.id) found.push(trace.target.header.id);
73
+ flattenTree(trace?.descendants, found);
74
+ for (const x of found) ids.add(x);
75
+ } catch {
76
+ notes.push(`会话 ${id.slice(0, 8)} 的会话树不可读`);
77
+ }
78
+ }
79
+ }
80
+ let currentSnapshot = null;
81
+ if (ids.size === 0 && currentSession) {
82
+ currentSnapshot = snapshotFromLive(currentSession);
83
+ if (currentSnapshot) ids.add('__current__');
84
+ }
85
+
86
+ // currentSession 不在绑定表时的兜底:只统计当前会话,标记 partial。
87
+ const idList = [...ids];
88
+ if (idList.length === 0) {
89
+ return {
90
+ schemaVersion: 1, generatedAt, coverage: 'unavailable',
91
+ agents: [], totals: totalOf([]), notes: ['任务没有可读的会话绑定'],
92
+ };
93
+ }
94
+
95
+ const snapshots = new Map();
96
+ const liveSessions = new Map();
97
+ for (const id of idList) {
98
+ if (id === '__current__') { snapshots.set(id, currentSnapshot); continue; }
99
+ let snap = null;
100
+ if (canRead) {
101
+ try {
102
+ const s = await sessionQuery.readSession(id);
103
+ if (s?.events) snap = { header: s.session ?? s.header ?? {}, events: s.events, inherited: Number(s.inheritedEventCount ?? 0) };
104
+ } catch { notes.push(`会话 ${String(id).slice(0, 8)} 读取失败`); }
105
+ }
106
+ if (!snap && sessions && typeof sessions.get === 'function') {
107
+ const live = sessions.get(id);
108
+ if (live) { liveSessions.set(id, live); snap = snapshotFromLive(live); }
109
+ }
110
+ if (!snap && currentSession && primaryId && id === primaryId) snap = snapshotFromLive(currentSession);
111
+ if (snap) snapshots.set(id, snap);
112
+ }
113
+
114
+ // 子代理标签:subagent/catalog 事件(data.childId + label/name,兼容 children 数组)
115
+ const catalog = new Map();
116
+ for (const snap of snapshots.values()) {
117
+ for (const e of snap.events ?? []) {
118
+ if (e?.type !== 'subagent/catalog') continue;
119
+ const d = e.data ?? {};
120
+ const entries = Array.isArray(d.children) ? d.children : [d];
121
+ for (const c of entries) {
122
+ if (typeof c?.childId === 'string' && c.childId) {
123
+ const label = c.label || c.name || c.role;
124
+ if (typeof label === 'string' && label) catalog.set(c.childId, label);
125
+ }
126
+ }
127
+ }
128
+ }
129
+
130
+ const agents = [];
131
+ for (const [id, snap] of snapshots.entries()) {
132
+ // 子会话可能继承父会话事件;只统计自身的 seq,避免 token 重复计算。
133
+ const inherited = Number.isFinite(snap.inherited) ? snap.inherited : 0;
134
+ const events = (snap.events ?? []).filter((e) => !Number.isFinite(Number(e?.seq)) || Number(e.seq) >= inherited);
135
+ const usage = emptyUsage();
136
+ let hasUsage = false;
137
+ let provider = null;
138
+ let model = null;
139
+ let effort = null;
140
+ let turns = 0;
141
+ let steps = 0;
142
+ let toolCalls = 0;
143
+ let toolFailures = 0;
144
+ const turnStart = new Map();
145
+ let activeDurationMs = 0;
146
+ let firstTime = null;
147
+ let lastTime = null;
148
+ let contextPressure = null;
149
+
150
+ for (const e of events) {
151
+ const type = e?.type;
152
+ const time = Number(e?.time);
153
+ if (Number.isFinite(time)) {
154
+ if (firstTime == null || time < firstTime) firstTime = time;
155
+ if (lastTime == null || time > lastTime) lastTime = time;
156
+ }
157
+ if (type === 'request/header') {
158
+ const cfg = e?.data?.header?.config;
159
+ if (cfg?.provider) provider = cfg.provider;
160
+ if (cfg?.model) model = cfg.model;
161
+ if (cfg?.reasoningEffort) effort = cfg.reasoningEffort;
162
+ } else if (type === 'assistant/message') {
163
+ steps += 1;
164
+ const src = e?.data?.message?.source;
165
+ if (!provider && src?.provider) provider = src.provider;
166
+ if (!model && src?.model) model = src.model;
167
+ if (addUsage(usage, e?.data?.usage)) hasUsage = true;
168
+ } else if (type === 'turn/start') {
169
+ const turn = e?.data?.turn;
170
+ if (Number.isFinite(Number(turn)) && Number.isFinite(time)) turnStart.set(Number(turn), time);
171
+ } else if (type === 'turn/end') {
172
+ turns += 1;
173
+ const turn = Number(e?.data?.turn);
174
+ const start = turnStart.get(turn);
175
+ if (Number.isFinite(start) && Number.isFinite(time) && time >= start) activeDurationMs += time - start;
176
+ } else if (type === 'tool/call') {
177
+ toolCalls += 1;
178
+ } else if (type === 'tool/result') {
179
+ if (e?.data?.error || e?.data?.message?.isError) toolFailures += 1;
180
+ }
181
+ }
182
+ if (turns === 0 && steps > 0) turns = steps;
183
+ if (!hasUsage) notes.push(`${sessionLabel(id, primaryId, catalog)} 未返回 usage`);
184
+
185
+ const live = liveSessions.get(id);
186
+ if (tokenMeter && typeof tokenMeter.contextPressure === 'function') {
187
+ try {
188
+ const cp = live
189
+ ? tokenMeter.contextPressure(live)
190
+ : (sessionQuery && typeof sessionQuery.inspectSession === 'function'
191
+ ? await sessionQuery.inspectSession(id, (s) => tokenMeter.contextPressure(s))
192
+ : null);
193
+ const pressure = Number(cp?.pressureTokens);
194
+ const window = Number(cp?.contextWindow);
195
+ contextPressure = Number.isFinite(pressure) && Number.isFinite(window) && window > 0 ? pressure / window : null;
196
+ } catch { /* 上下文压力是可选项 */ }
197
+ }
198
+
199
+ agents.push({
200
+ label: sessionLabel(id, primaryId, catalog),
201
+ provider: provider || null,
202
+ model: model || null,
203
+ reasoningEffort: effort || null,
204
+ turns,
205
+ steps,
206
+ inputTokens: hasUsage ? usage.inputTokens : null,
207
+ outputTokens: hasUsage ? usage.outputTokens : null,
208
+ cacheReadTokens: hasUsage ? usage.cacheReadTokens : null,
209
+ cacheWriteTokens: hasUsage ? usage.cacheWriteTokens : null,
210
+ reasoningTokens: hasUsage ? usage.reasoningTokens : null,
211
+ totalTokens: hasUsage ? usage.inputTokens + usage.outputTokens : null,
212
+ toolCalls,
213
+ toolFailures,
214
+ activeDurationMs,
215
+ wallClockMs: firstTime != null && lastTime != null ? Math.max(0, lastTime - firstTime) : null,
216
+ contextPressure: typeof contextPressure === 'number' ? contextPressure : null,
217
+ });
218
+ }
219
+
220
+ agents.sort((a, b) => (a.label === 'PM' ? -1 : b.label === 'PM' ? 1 : a.label.localeCompare(b.label)));
221
+ const anyUsage = agents.some((a) => a.inputTokens != null);
222
+ const missing = idList.length - snapshots.size;
223
+ const coverage = snapshots.size === 0 ? 'unavailable' : (missing > 0 || notes.length > 0 || !anyUsage ? 'partial' : 'complete');
224
+ return {
225
+ schemaVersion: 1,
226
+ generatedAt,
227
+ coverage,
228
+ agents,
229
+ totals: totalOf(agents),
230
+ notes: [...new Set(notes)].slice(0, 12),
231
+ };
232
+ }
233
+
234
+ function totalOf(agents) {
235
+ const sum = (key) => agents.reduce((n, a) => n + (typeof a[key] === 'number' ? a[key] : 0), 0);
236
+ return {
237
+ agents: agents.length,
238
+ turns: sum('turns'),
239
+ steps: sum('steps'),
240
+ inputTokens: sum('inputTokens'),
241
+ outputTokens: sum('outputTokens'),
242
+ cacheReadTokens: sum('cacheReadTokens'),
243
+ cacheWriteTokens: sum('cacheWriteTokens'),
244
+ reasoningTokens: sum('reasoningTokens'),
245
+ totalTokens: sum('totalTokens'),
246
+ toolCalls: sum('toolCalls'),
247
+ toolFailures: sum('toolFailures'),
248
+ activeDurationMs: sum('activeDurationMs'),
249
+ wallClockMs: sum('wallClockMs'),
250
+ };
251
+ }
252
+
253
+ /** 读取任务最新一轮归档统计(历史任务在会话不可读时的兜底)。 */
254
+ export function readLatestTaskMetrics(ws, task) {
255
+ const dir = path.join(harnessDir(ws), 'deliverables', '_archive', task, 'metrics');
256
+ if (!fs.existsSync(dir)) return null;
257
+ const files = fs.readdirSync(dir)
258
+ .filter((f) => /^R\d+\.json$/.test(f))
259
+ .sort((a, b) => Number(b.match(/\d+/)[0]) - Number(a.match(/\d+/)[0]));
260
+ for (const name of files) {
261
+ try {
262
+ const data = JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8'));
263
+ if (data && typeof data === 'object') return data;
264
+ } catch { /* 跳过坏快照 */ }
265
+ }
266
+ return null;
267
+ }
268
+
269
+ /** 归档时写 metrics/<R>.json;已存在则保留(同一轮只写一次)。 */
270
+ export function writeTaskMetrics(ws, task, tag, metrics) {
271
+ const dir = path.join(harnessDir(ws), 'deliverables', '_archive', task, 'metrics');
272
+ fs.mkdirSync(dir, { recursive: true });
273
+ const file = path.join(dir, `${tag}.json`);
274
+ if (fs.existsSync(file)) return { file, skipped: true };
275
+ const payload = { ...metrics, task, round: tag };
276
+ const tmp = `${file}.tmp`;
277
+ fs.writeFileSync(tmp, `${JSON.stringify(payload, null, 2)}\n`, 'utf8');
278
+ fs.renameSync(tmp, file);
279
+ return { file, skipped: false };
280
+ }
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,29 +200,40 @@ 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
 
205
207
  /**
206
- * 初始化完整性缺口:根 AGENTS.md 与各子工程的 build.json / CLAUDE.md。
208
+ * 初始化完整性缺口:根 AGENTS.md/CLAUDE.md 与各子工程的 build.json / AGENTS.md(兼容 CLAUDE.md)。
207
209
  * 确定性物化(面板「重跑初始化」)只铺骨架与脚本,子工程文档由初始化编排
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'))) gaps.push('根 AGENTS.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, 'CLAUDE.md'))) gaps.push(`${s.name} 的 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';
@@ -268,7 +268,7 @@ export async function runInit(ws, { assets, branch, sources = [], onProgress } =
268
268
  '',
269
269
  '| 层 | 位置 | 性质 | 用途 |',
270
270
  '|---|---|---|---|---|',
271
- '| L1 入口 | `services/<子工程>/CLAUDE.md` | 人工编写 | 技术栈、框架模式、模块发现索引 |',
271
+ '| L1 入口 | `services/<子工程>/AGENTS.md`(优先)或 `CLAUDE.md`(兼容) | 人工编写 | 技术栈、框架模式、模块发现索引 |',
272
272
  '| L2 规范 | `services/<子工程>/docs/CODE_STANDARDS.md` | 人工编写 | 编码规范,团队持续打磨 |',
273
273
  '| L3 索引 | `services/<子工程>/.codegraph/` | CodeGraph 生成 | 类/方法/调用链,AI 通过 `codegraph explore` 查询 |',
274
274
  '',
@@ -277,9 +277,9 @@ export async function runInit(ws, { assets, branch, sources = [], onProgress } =
277
277
  '| 角色 | 必读 | 按需 |',
278
278
  '|---|---|---|',
279
279
  '| PM | overview.md、specs/_index.md、tasks/board.md | memory/index.md |',
280
- '| BA | overview.md、specs/_index.md、对应子工程 L1 CLAUDE.md | 相关模块 L1 CLAUDE.md |',
281
- '| SA | 对应子工程 L1 + L2、codegraph explore(L3) | 相关模块 L1 CLAUDE.md |',
282
- '| Dev | 对应子工程 L1 + L2、对应模块 L1 CLAUDE.md | codegraph explore(调用链) |',
280
+ '| BA | overview.md、specs/_index.md、对应子工程 L1 AGENTS.md/CLAUDE.md | 相关模块 L1 AGENTS.md/CLAUDE.md |',
281
+ '| SA | 对应子工程 L1 + L2、codegraph explore(L3) | 相关模块 L1 AGENTS.md/CLAUDE.md |',
282
+ '| Dev | 对应子工程 L1 + L2、对应模块 L1 AGENTS.md/CLAUDE.md | codegraph explore(调用链) |',
283
283
  '| CR | .harness/rules/code-standards.md、子工程 L2 | codegraph explore(影响范围) |',
284
284
  '| TE | 任务 deliverables(proposal/requirements/design) | 对应子工程 L1 |',
285
285
  '',
@@ -302,7 +302,7 @@ export async function runInit(ws, { assets, branch, sources = [], onProgress } =
302
302
  '',
303
303
  '| 端 | 技术 | 说明 |',
304
304
  '|---|---|---|',
305
- '<!-- TODO: 按各子工程 CLAUDE.md / build.json 据实补全 -->',
305
+ '<!-- TODO: 按各子工程 AGENTS.md 或 CLAUDE.md / build.json 据实补全 -->',
306
306
  '',
307
307
  '## 目录结构',
308
308
  '',
@@ -319,7 +319,7 @@ export async function runInit(ws, { assets, branch, sources = [], onProgress } =
319
319
  '',
320
320
  '| 想知道什么 | 去哪看 |',
321
321
  '|---|---|---|',
322
- '| 子工程技术细节、框架模式 | `services/<子工程>/CLAUDE.md` |',
322
+ '| 子工程技术细节、框架模式 | `services/<子工程>/AGENTS.md`(优先)或 `CLAUDE.md`(兼容) |',
323
323
  '| 编码规范 | `services/<子工程>/docs/CODE_STANDARDS.md` |',
324
324
  '| 构建/启动/测试命令 | `services/<子工程>/.harness/build.json` |',
325
325
  '| 已有系统能力 | `.harness/specs/_index.md` |',
@@ -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\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));
@@ -505,9 +506,13 @@ export async function runInit(ws, { assets, branch, sources = [], onProgress } =
505
506
  }
506
507
  }
507
508
 
508
- // 3. host instruction files: AGENTS.md canonical + CLAUDE.md pointer (never overwrite)
509
+ // 3. host instruction file: prefer AGENTS.md; if either AGENTS.md or legacy CLAUDE.md
510
+ // already exists, do not generate the missing one (never overwrite).
509
511
  const agentsMd = path.join(ws, 'AGENTS.md');
510
- if (!fs.existsSync(agentsMd)) {
512
+ const legacyClaudeMd = path.join(ws, 'CLAUDE.md');
513
+ const hasAgents = fs.existsSync(agentsMd);
514
+ const hasClaude = fs.existsSync(legacyClaudeMd);
515
+ if (!hasAgents && !hasClaude) {
511
516
  const sourceLines = kit.sources.map((s) => `| ${s.name} | \`${s.path}\` | ${s.role} | ${s.branch} |`).join('\n');
512
517
  fs.writeFileSync(
513
518
  agentsMd,
@@ -549,13 +554,9 @@ export async function runInit(ws, { assets, branch, sources = [], onProgress } =
549
554
  'utf8',
550
555
  );
551
556
  created.push('AGENTS.md');
552
- } else kept.push('AGENTS.md');
553
-
554
- const claudeMd = path.join(ws, 'CLAUDE.md');
555
- if (!fs.existsSync(claudeMd)) {
556
- fs.writeFileSync(claudeMd, 'See @AGENTS.md\n', 'utf8');
557
- created.push('CLAUDE.md(指针薄壳)');
558
- } else kept.push('CLAUDE.md(已存在,未改动)');
557
+ } else {
558
+ kept.push(hasAgents ? 'AGENTS.md' : 'CLAUDE.md(legacy,未改动)');
559
+ }
559
560
 
560
561
  // 4. materialize init assets from the pack — scripts 是 pack 管理运行时(不入库,每次刷新覆盖);
561
562
  // templates 是播种资产(项目可裁剪,create-only 不覆盖)