dsh-harness-kit 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +321 -2
- package/README.zh-CN.md +278 -0
- package/client.js +1272 -0
- package/cordis.patch.yml +4 -0
- package/docs/DETAIL.en.md +97 -0
- package/docs/DETAIL.md +73 -0
- package/docs/assets/ui-new-task.png +0 -0
- package/docs/assets/ui-onboarding.png +0 -0
- package/docs/assets/ui-war-room.png +0 -0
- package/icon.svg +7 -0
- package/index.js +49 -0
- package/kernel/advance.js +96 -0
- package/kernel/bindings.js +24 -0
- package/kernel/commands.js +927 -0
- package/kernel/env.js +64 -0
- package/kernel/exec.js +41 -0
- package/kernel/flows.js +89 -0
- package/kernel/guards.js +79 -0
- package/kernel/miniyaml.js +133 -0
- package/kernel/models.js +104 -0
- package/kernel/panel.js +1103 -0
- package/kernel/paths.js +53 -0
- package/kernel/roles.js +67 -0
- package/kernel/setup.js +644 -0
- package/kernel/state.js +59 -0
- package/kernel/steer.js +27 -0
- package/kernel/sync.js +140 -0
- package/kernel/te.js +122 -0
- package/kernel/worktree.js +868 -0
- package/locale/en.json +14 -0
- package/locale/zh.json +14 -0
- package/package.json +63 -4
- package/packs/ai-coding/agents/business-analyst.md +90 -0
- package/packs/ai-coding/agents/code-reviewer.md +156 -0
- package/packs/ai-coding/agents/developer.md +147 -0
- package/packs/ai-coding/agents/project-manager.md +190 -0
- package/packs/ai-coding/agents/readiness-reviewer.md +123 -0
- package/packs/ai-coding/agents/solution-architect.md +122 -0
- package/packs/ai-coding/agents/test-engineer.md +230 -0
- package/packs/ai-coding/assets/scripts/check_codegraph.py +215 -0
- package/packs/ai-coding/assets/scripts/codebase_guide_init.py +330 -0
- package/packs/ai-coding/assets/scripts/env_auto.py +612 -0
- package/packs/ai-coding/assets/scripts/harness.py +38 -0
- package/packs/ai-coding/assets/scripts/harness_init.py +193 -0
- package/packs/ai-coding/assets/scripts/lib.py +1011 -0
- package/packs/ai-coding/assets/scripts/run_field.py +295 -0
- package/packs/ai-coding/assets/scripts/spec_lint.py +247 -0
- package/packs/ai-coding/assets/scripts/update_board.py +524 -0
- package/packs/ai-coding/assets/scripts/verify.py +184 -0
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/CODE_STANDARDS.tmpl +44 -0
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/app-CLAUDE.tmpl +34 -0
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/build.tmpl +8 -0
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/module-CLAUDE.tmpl +42 -0
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/root-CLAUDE.tmpl +41 -0
- package/packs/ai-coding/assets/templates/java/maven/CODE_STANDARDS.tmpl +44 -0
- package/packs/ai-coding/assets/templates/java/maven/build.tmpl +9 -0
- package/packs/ai-coding/assets/templates/java/maven/root-CLAUDE.tmpl +38 -0
- package/packs/ai-coding/assets/templates/java/maven-multimodule/CODE_STANDARDS.tmpl +44 -0
- package/packs/ai-coding/assets/templates/java/maven-multimodule/build.tmpl +9 -0
- package/packs/ai-coding/assets/templates/java/maven-multimodule/module-CLAUDE.tmpl +40 -0
- package/packs/ai-coding/assets/templates/java/maven-multimodule/root-CLAUDE.tmpl +38 -0
- package/packs/ai-coding/assets/templates/javascript/mobile-app/CODE_STANDARDS.tmpl +51 -0
- package/packs/ai-coding/assets/templates/javascript/mobile-app/build.tmpl +8 -0
- package/packs/ai-coding/assets/templates/javascript/mobile-app/root-CLAUDE.tmpl +36 -0
- package/packs/ai-coding/assets/templates/javascript/uniapp/CODE_STANDARDS.tmpl +69 -0
- package/packs/ai-coding/assets/templates/javascript/uniapp/build.tmpl +8 -0
- package/packs/ai-coding/assets/templates/javascript/uniapp/root-CLAUDE.tmpl +56 -0
- package/packs/ai-coding/assets/templates/javascript/vue-multimodule/CODE_STANDARDS.tmpl +51 -0
- package/packs/ai-coding/assets/templates/javascript/vue-multimodule/app-CLAUDE.tmpl +36 -0
- package/packs/ai-coding/assets/templates/javascript/vue-multimodule/build.tmpl +8 -0
- package/packs/ai-coding/assets/templates/javascript/vue-multimodule/root-CLAUDE.tmpl +34 -0
- package/packs/ai-coding/flows/_router.yml +14 -0
- package/packs/ai-coding/flows/bugfix.yml +37 -0
- package/packs/ai-coding/flows/fix.yml +44 -0
- package/packs/ai-coding/flows/init.yml +83 -0
- package/packs/ai-coding/flows/new.yml +29 -0
- package/packs/ai-coding/flows/quick.yml +40 -0
- package/packs/ai-coding/flows/refactor.yml +50 -0
- package/packs/ai-coding/flows/standard.yml +49 -0
- package/packs/ai-coding/rules/code-standards.md +30 -0
- package/packs/ai-coding/rules/core.md +83 -0
- package/packs/ai-coding/templates/bugfix.md +29 -0
- package/packs/ai-coding/templates/memory-entry.md +46 -0
- package/packs/ai-coding/templates/proposal.md +47 -0
- package/packs/ai-coding/templates/spec-template.md +34 -0
- package/screenshots.json +5 -0
package/kernel/panel.js
ADDED
|
@@ -0,0 +1,1103 @@
|
|
|
1
|
+
// M4/M4b 面板数据通道:webServer 路由向 Client 面板暴露状态、配置与命令转发。
|
|
2
|
+
// - GET /harness-kit/state 工作区看板 + 流程进度 + 认领 + 同步健康 + 注意力项
|
|
3
|
+
// - GET /harness-kit/config kit.json 配置视图(?workspace=)
|
|
4
|
+
// - POST /harness-kit/config {workspace, patch} 更新 kit.json(基线分支/autoSync/models)
|
|
5
|
+
// - GET /harness-kit/activity 资产仓库团队动态(git log,?workspace=)
|
|
6
|
+
// - POST /harness-kit/sync {workspace} 立即同步(Host 直跑,不占会话)
|
|
7
|
+
// - POST /harness-kit/command {workspace, line} 把 /hk-* 命令转发给该工作区的活动会话(成功自动登记任务↔会话)
|
|
8
|
+
// - POST /harness-kit/bind-session {workspace, task, sessionId} 登记任务↔会话绑定(客户端新开会话后回调)
|
|
9
|
+
// - POST /harness-kit/workspace/inspect {path} 目录预检(新建/打开向导共用)
|
|
10
|
+
// - POST /harness-kit/workspace/create {path, title?} 注册任意已存在目录为 DSH 工作区
|
|
11
|
+
// - POST /harness-kit/workspace/open {path, title?} 打开已有 Harness 工作区(须含 .harness/kit.json)
|
|
12
|
+
// - POST /harness-kit/workspace/init {workspace, assets?, sources?} 面板初始化向导(/hk-init + /hk-setup --add 等价,幂等)
|
|
13
|
+
// - GET /harness-kit/env 向导环境预检(git / Python 3 + 对应平台安装指引,不自动安装)
|
|
14
|
+
// 纯函数(parseBoard / taskProgress / nextAction / laneOf / parseClaims /
|
|
15
|
+
// attentionItems / parseGitLog / updateKit)与 HTTP 接线分离,供 sim 测试。
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { harnessDir, readKit, writeKit, defaultKit } from './paths.js';
|
|
19
|
+
import { loadFlow } from './flows.js';
|
|
20
|
+
import { runGit } from './exec.js';
|
|
21
|
+
import { checkEnvironment } from './env.js';
|
|
22
|
+
import { assetsLayout, syncAssets } from './sync.js';
|
|
23
|
+
import { runInit, formatInitReport, inspectDir } from './setup.js';
|
|
24
|
+
import { readTaskSessions, recordTaskSession } from './bindings.js';
|
|
25
|
+
import { scanAutoAdvance, markAdvanceFired } from './advance.js';
|
|
26
|
+
import { listRoles } from './roles.js';
|
|
27
|
+
import { readWorkspaces } from './worktree.js';
|
|
28
|
+
import { listAllGitBranches } from './worktree.js';
|
|
29
|
+
import { reconcileTestEnv, readTestEnv } from './te.js';
|
|
30
|
+
import { readDecisions } from './worktree.js';
|
|
31
|
+
|
|
32
|
+
/** 解析看板 markdown 表(7 列契约,见 commands.js boardTemplate)。
|
|
33
|
+
* 容错与 commands.js parseBoardRow 同源:超列溢出并入「续接提示」,不足补 —。 */
|
|
34
|
+
export function parseBoard(text) {
|
|
35
|
+
const table = text.split('\n').filter((l) => l.startsWith('|'));
|
|
36
|
+
if (table.length < 2) return { headers: [], rows: [] };
|
|
37
|
+
const cells = (line) => {
|
|
38
|
+
const c = line.trim().replace(/^\||\|$/g, '').split('|').map((x) => x.trim());
|
|
39
|
+
if (c.length > 7) return [...c.slice(0, 6), c.slice(6).join(' / ')];
|
|
40
|
+
while (c.length < 7) c.push('—');
|
|
41
|
+
return c;
|
|
42
|
+
};
|
|
43
|
+
const headers = cells(table[0]);
|
|
44
|
+
const rows = table.slice(2).map((line) => {
|
|
45
|
+
const c = cells(line);
|
|
46
|
+
return { task: c[0], status: c[1], profile: c[2], apply: c[3], branch: c[4], updated: c[5], hint: c[6] };
|
|
47
|
+
});
|
|
48
|
+
return { headers, rows };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 从 stage.do 行提取产物文件名(「产出 xxx.md」)。 */
|
|
52
|
+
function evidenceFiles(stage) {
|
|
53
|
+
const out = [];
|
|
54
|
+
for (const item of stage.do ?? []) {
|
|
55
|
+
const re = /产出\s*`?([\w.-]+\.md)/g;
|
|
56
|
+
let m;
|
|
57
|
+
while ((m = re.exec(item)) !== null) out.push(m[1]);
|
|
58
|
+
}
|
|
59
|
+
return [...new Set(out)];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 审批标记:proposal.md / bugfix.md 中出现「<阶段名>:通过」。 */
|
|
63
|
+
function approvalPassed(dir, name) {
|
|
64
|
+
for (const doc of ['proposal.md', 'bugfix.md']) {
|
|
65
|
+
const file = path.join(dir, doc);
|
|
66
|
+
if (!fs.existsSync(file)) continue;
|
|
67
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
68
|
+
if (new RegExp(`${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[::]\\s*通过`).test(text)) return true;
|
|
69
|
+
}
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 解析看板 Apply进度 链:`R<n>:Dev✅ 验证▶` → { round, chain: [{name, mark}] };不合规/—/已归档返回 null。 */
|
|
74
|
+
export function parseApplyChain(text) {
|
|
75
|
+
const m = /^R(\d+)[::]\s*(.+)$/.exec(String(text ?? '').trim());
|
|
76
|
+
if (!m) return null;
|
|
77
|
+
const chain = [];
|
|
78
|
+
for (const tok of m[2].trim().split(/\s+/)) {
|
|
79
|
+
const sm = /^(.+?)(✅|▶|…|⛔|—)$/.exec(tok);
|
|
80
|
+
if (!sm) return null; // 任一 token 不合规 → 放弃链驱动,回退证据驱动
|
|
81
|
+
chain.push({ name: sm[1], mark: sm[2] });
|
|
82
|
+
}
|
|
83
|
+
return chain.length ? { round: Number(m[1]), chain } : null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** 看板链阶段 → 面板阶段对象(与 flow yml 派生的结构同构)。 */
|
|
87
|
+
function chainStages(chain) {
|
|
88
|
+
return chain.map(({ name, mark }) => ({
|
|
89
|
+
name,
|
|
90
|
+
kind: /^审批/.test(name) ? 'approval' : 'worker',
|
|
91
|
+
phase: ['影响面', 'propose', '审批1'].includes(name) ? 'propose' : 'apply',
|
|
92
|
+
done: mark === '✅',
|
|
93
|
+
skipped: mark === '—',
|
|
94
|
+
blocked: mark === '⛔',
|
|
95
|
+
evidence: [],
|
|
96
|
+
}));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* 推导单任务流程进度。
|
|
101
|
+
* 返回 { flow, stages: [{name, phase, kind, done, evidence}], pendingApproval, current }
|
|
102
|
+
* kind: worker|approval|plain;current = 首个未完成阶段下标(-1 表示全部完成)。
|
|
103
|
+
*/
|
|
104
|
+
export function taskProgress(ws, kit, task, profile, status, applyText = null) {
|
|
105
|
+
const dir = path.join(harnessDir(ws), 'deliverables', task);
|
|
106
|
+
const files = fs.existsSync(dir)
|
|
107
|
+
? fs.readdirSync(dir).filter((f) => f.endsWith('.md'))
|
|
108
|
+
: [];
|
|
109
|
+
let flowName = profile && profile !== '—' ? profile : null;
|
|
110
|
+
// v4.1 三态:bugfix=全流程;fix-full/fix-light=直通;裸 fix=直通裁决未定(兼容旧板:
|
|
111
|
+
// 旧短名 fix 曾覆盖 bugfix 全流程,无链回退时仍按 proposal.md 消解)
|
|
112
|
+
if (flowName === 'fix-full' || flowName === 'fix-light') flowName = 'fix';
|
|
113
|
+
else if (flowName === 'fix') flowName = files.includes('proposal.md') ? 'bugfix' : 'fix';
|
|
114
|
+
if (!flowName) flowName = files.includes('bugfix.md') ? 'fix' : 'standard';
|
|
115
|
+
|
|
116
|
+
// 看板 Apply进度 链是 PM 维护的权威进度(v3 语法):有链则以链驱动圆点,与看板文本严格一致;
|
|
117
|
+
// 无链(—)才回退证据文件推导(老数据/新立项未写链)。
|
|
118
|
+
const parsed = parseApplyChain(applyText);
|
|
119
|
+
if (parsed) {
|
|
120
|
+
const stages = chainStages(parsed.chain);
|
|
121
|
+
if (status === 'DONE') for (const s of stages) { s.done = true; s.blocked = false; }
|
|
122
|
+
let current = parsed.chain.findIndex((c) => c.mark === '▶');
|
|
123
|
+
if (current < 0) current = stages.findIndex((s) => !s.done && !s.skipped);
|
|
124
|
+
const pending = stages.find((s, i) => s.kind === 'approval' && !s.done && !s.skipped
|
|
125
|
+
&& stages.slice(0, i).every((p) => p.done || p.skipped));
|
|
126
|
+
// 越序检测:▶ 之前存在未完成(非 ✅/—)阶段 = 写板不规范,面板应浮出水面
|
|
127
|
+
const outOfOrder = current > 0 && parsed.chain.slice(0, current).some((c) => c.mark !== '✅' && c.mark !== '—');
|
|
128
|
+
return { flow: flowName, stages, pendingApproval: pending?.name ?? null, current, deliverables: files, round: parsed.round, outOfOrder };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const loaded = loadFlow(ws, kit ?? defaultKit(), flowName);
|
|
132
|
+
if (!loaded) return { flow: flowName, stages: [], pendingApproval: null, current: -1, deliverables: files };
|
|
133
|
+
const stages = (loaded.flow.stages ?? []).map((s) => {
|
|
134
|
+
const kind = s.approval ? 'approval' : s.worker ? 'worker' : 'plain';
|
|
135
|
+
let done;
|
|
136
|
+
let evidence = [];
|
|
137
|
+
if (kind === 'approval') {
|
|
138
|
+
done = approvalPassed(dir, s.name);
|
|
139
|
+
} else {
|
|
140
|
+
evidence = evidenceFiles(s);
|
|
141
|
+
done = evidence.length > 0 && evidence.every((f) => files.includes(f));
|
|
142
|
+
}
|
|
143
|
+
return { name: s.name, phase: s.phase ?? null, kind, done, evidence };
|
|
144
|
+
});
|
|
145
|
+
let current = stages.findIndex((s) => !s.done);
|
|
146
|
+
if (status === 'DONE') {
|
|
147
|
+
// 已归档任务活目录已清空,证据文件不在——按状态视作全程完成
|
|
148
|
+
for (const s of stages) s.done = true;
|
|
149
|
+
current = -1;
|
|
150
|
+
}
|
|
151
|
+
const pending = stages.find((s, i) => s.kind === 'approval' && !s.done && stages.slice(0, i).every((p) => p.done));
|
|
152
|
+
return { flow: flowName, stages, pendingApproval: pending?.name ?? null, current, deliverables: files };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 单任务面板动作:{kind: reopen|archive|wait|apply|propose, line?, approval?}。 */
|
|
156
|
+
export function nextAction(row, progress) {
|
|
157
|
+
const { task, status } = row;
|
|
158
|
+
if (status === 'DONE') return { kind: 'reopen', line: `/hk-apply ${task}` };
|
|
159
|
+
if (status === 'AWAITING_ARCHIVE') return { kind: 'archive', line: `/hk-archive ${task}` };
|
|
160
|
+
if (progress.pendingApproval) return { kind: 'wait', approval: progress.pendingApproval };
|
|
161
|
+
const cur = progress.current >= 0 ? progress.stages[progress.current] : null;
|
|
162
|
+
if (cur && cur.phase === 'apply') return { kind: 'apply', line: `/hk-apply ${task}` };
|
|
163
|
+
return { kind: 'propose', line: `/hk-propose ${task}` };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 泳道分派:plan=规划中 / build=实施中 / archive=待归档 / done=已归档(M4b)。 */
|
|
167
|
+
export function laneOf(row, progress) {
|
|
168
|
+
if (row.status === 'DONE') return 'done';
|
|
169
|
+
if (row.status === 'AWAITING_ARCHIVE') return 'archive';
|
|
170
|
+
// 未启动(PENDING)一律归「规划中」,不看链阶段——否则全 … 的 fix 任务会因
|
|
171
|
+
// 质量门 phase=apply 落进「实施中」
|
|
172
|
+
if (row.status === 'PENDING') return 'plan';
|
|
173
|
+
const cur = progress.current >= 0 ? progress.stages[progress.current] : null;
|
|
174
|
+
return cur?.phase === 'apply' ? 'build' : 'plan';
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** 解析 claims.json(追加式 JSONL,每行 {task, by, ts};by=null 表示释放,后者覆盖前者)。 */
|
|
178
|
+
export function parseClaims(text) {
|
|
179
|
+
const claims = {};
|
|
180
|
+
for (const line of text.split('\n')) {
|
|
181
|
+
const t = line.trim();
|
|
182
|
+
if (!t) continue;
|
|
183
|
+
try {
|
|
184
|
+
const j = JSON.parse(t);
|
|
185
|
+
if (typeof j.task !== 'string' || !j.task) continue;
|
|
186
|
+
if (j.by == null) delete claims[j.task];
|
|
187
|
+
else claims[j.task] = { by: String(j.by), ts: typeof j.ts === 'string' ? j.ts : null };
|
|
188
|
+
} catch { /* 容忍坏行 */ }
|
|
189
|
+
}
|
|
190
|
+
return claims;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** 追加一条认领记录(由 /hk-propose 自动调用;文件纳入 sync 纯追加白名单)。 */
|
|
194
|
+
export function claimTask(ws, task, by) {
|
|
195
|
+
const file = path.join(harnessDir(ws), 'tasks', 'claims.json');
|
|
196
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
197
|
+
fs.appendFileSync(file, `${JSON.stringify({ task, by, ts: new Date().toISOString() })}\n`, 'utf8');
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// ---------------------------------------------------------- 任务 ↔ 会话绑定
|
|
201
|
+
// .harness/tasks/sessions.json:{ tasks: { <任务名>: { sessionId, at } } }
|
|
202
|
+
// 实现已下沉 kernel/bindings.js(kernel 命令 handler 与自动续接引擎共用),此处转出口径不变。
|
|
203
|
+
export { readTaskSessions, recordTaskSession } from './bindings.js';
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* 初始化完整性缺口:根 AGENTS.md 与各子工程的 build.json / CLAUDE.md。
|
|
207
|
+
* 确定性物化(面板「重跑初始化」)只铺骨架与脚本,子工程文档由初始化编排
|
|
208
|
+
* (PM 流程)生成 —— 有缺口时面板给出「运行初始化编排」入口而不是让用户
|
|
209
|
+
* 对着「初始化成功」却缺文件的工程发懵。
|
|
210
|
+
*/
|
|
211
|
+
export function initGaps(ws, kit) {
|
|
212
|
+
const gaps = [];
|
|
213
|
+
if (!fs.existsSync(path.join(ws, 'AGENTS.md'))) gaps.push('根 AGENTS.md');
|
|
214
|
+
for (const s of kit?.sources ?? []) {
|
|
215
|
+
if (!s?.path) continue;
|
|
216
|
+
const sp = path.join(ws, s.path);
|
|
217
|
+
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`);
|
|
220
|
+
}
|
|
221
|
+
return gaps;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* 「需要你」注意力项(M4b):审批/待归档/同步阻塞·落后/初始化缺口。
|
|
226
|
+
* 返回 [{level: block|warn, kind, task?, text, line?, jump?}],block 在前。
|
|
227
|
+
*/
|
|
228
|
+
export function attentionItems(tasks, sync, gaps = [], staleSlots = [], teEnv = null, decisions = {}) {
|
|
229
|
+
const items = [];
|
|
230
|
+
for (const t of tasks) {
|
|
231
|
+
if (t.status === 'DONE') continue;
|
|
232
|
+
if (t.progress?.pendingApproval) {
|
|
233
|
+
items.push({ level: 'block', kind: 'approval', task: t.task, text: `${t.task} · ${t.progress.pendingApproval} 等待人工审批`, jump: true });
|
|
234
|
+
}
|
|
235
|
+
const blocked = t.progress?.stages?.find((s) => s.blocked);
|
|
236
|
+
if (blocked) {
|
|
237
|
+
items.push({ level: 'block', kind: 'stage-blocked', task: t.task, text: `${t.task} · ${blocked.name} 阻塞,待人工裁决`, jump: true });
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (sync?.state === 'blocked') {
|
|
241
|
+
// embedded:rebase 中途发生在工作区根仓库,面板不能替用户动代码仓库,只指路不挂动作
|
|
242
|
+
items.push(sync.layout === 'embedded'
|
|
243
|
+
? { level: 'block', kind: 'sync-blocked', text: `根仓库 rebase 中途(上次冲突未处理完),需人工在 ${sync.repoRoot ?? '根仓库'} 解冲突后 git rebase --continue` }
|
|
244
|
+
: { level: 'block', kind: 'sync-blocked', text: '资产同步冲突已中止回滚,需要人工合并(.harness 仓库)', sync: true });
|
|
245
|
+
}
|
|
246
|
+
for (const t of tasks) {
|
|
247
|
+
if (t.status === 'AWAITING_ARCHIVE') {
|
|
248
|
+
items.push({ level: 'warn', kind: 'archive', task: t.task, text: `${t.task} · 已完成待归档`, line: `/hk-archive ${t.task}` });
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
for (const t of tasks) {
|
|
252
|
+
if (t.status !== 'DONE' && t.progress?.outOfOrder) {
|
|
253
|
+
items.push({ level: 'warn', kind: 'chain-out-of-order', task: t.task, text: `${t.task} · 看板链越序:当前阶段之前还有未完成阶段(应补 ✅ 或 —)`, jump: true });
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (gaps.length > 0) {
|
|
257
|
+
items.push({ level: 'warn', kind: 'init-incomplete', text: `初始化不完整:缺 ${gaps.join('、')}(由初始化编排生成,重跑骨架物化不产生这些文件)`, init: true });
|
|
258
|
+
}
|
|
259
|
+
if (sync?.state === 'behind' || sync?.state === 'diverged') {
|
|
260
|
+
// embedded:落后的是工作区根仓库,资产随根仓库 commit/push 共享,/hk-sync 不适用——
|
|
261
|
+
// 只提示不挂「立即同步」动作(挂了只会得到"不适用"报错,2026-11-13 用户踩中)
|
|
262
|
+
items.push(sync.layout === 'embedded'
|
|
263
|
+
? { level: 'warn', kind: 'sync-behind', text: `工作区根仓库落后远端 ${sync.behind} 个提交${sync.dirty ? ',.harness 有未提交变更' : ''}(资产随根仓库管理,在根仓库 git pull/push 即共享)` }
|
|
264
|
+
: { level: 'warn', kind: 'sync-behind', text: `资产仓库落后远端 ${sync.behind} 个提交${sync.dirty ? ',且有未提交变更' : ''}`, sync: true });
|
|
265
|
+
}
|
|
266
|
+
// M2:stale slot(任务已归档但分支未合入,槽位被保留占用)→ 提醒人确认合入后重跑归档释放
|
|
267
|
+
for (const s of staleSlots) {
|
|
268
|
+
items.push({ level: 'warn', kind: 'workspace-stale', task: s.task, text: `${s.repo} 的 ${s.slot} 保留未释放:任务 ${s.task} 分支 ${s.branch} 未合入基线(远端 MR 合入后重跑 /hk-archive ${s.task} 释放槽位)`, jump: true });
|
|
269
|
+
}
|
|
270
|
+
// TE 串行:有人在排队时提示当前持有者与等待者
|
|
271
|
+
if (teEnv?.holder && (teEnv.queue?.length ?? 0) > 0) {
|
|
272
|
+
items.push({ level: 'warn', kind: 'te-queued', task: teEnv.holder, text: `TE 环境被 ${teEnv.holder} 占用,排队等待:${teEnv.queue.join(' → ')}(TE 完成后自动释放,无需人工)` });
|
|
273
|
+
}
|
|
274
|
+
// 待裁决决策点(外来分支占用等):block 级常驻,options 由面板渲染为可点按钮
|
|
275
|
+
for (const [task, d] of Object.entries(decisions ?? {})) {
|
|
276
|
+
items.push({
|
|
277
|
+
level: 'block', kind: 'workspace-decision', task,
|
|
278
|
+
text: d.text || `任务 ${task} 有待裁决决策点(${d.code})`,
|
|
279
|
+
options: Array.isArray(d.options) ? d.options : [], jump: true,
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
return items;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** 解析 git log 行(%h%x1f%an%x1f%ad%x1f%s)。 */
|
|
286
|
+
export function parseGitLog(text) {
|
|
287
|
+
return text.split('\n')
|
|
288
|
+
.map((line) => line.trim())
|
|
289
|
+
.filter(Boolean)
|
|
290
|
+
.map((line) => {
|
|
291
|
+
const [hash, author, at, ...rest] = line.split('\x1f');
|
|
292
|
+
return { hash, author, at, subject: rest.join('\x1f') };
|
|
293
|
+
})
|
|
294
|
+
.filter((e) => e.hash && e.subject);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* 受控更新 kit.json(M4b 配置视图第 2 层)。
|
|
299
|
+
* patch: { sources?: [{name, branch}], autoSync?: boolean, models?: {logical: {provider?, model}} }
|
|
300
|
+
* 返回 { ok: true, kit } 或 { error }。
|
|
301
|
+
*/
|
|
302
|
+
export function updateKit(ws, patch) {
|
|
303
|
+
const kit = readKit(ws);
|
|
304
|
+
if (!kit) return { error: '尚未初始化:请先运行 /hk-init' };
|
|
305
|
+
if (patch == null || typeof patch !== 'object') return { error: 'patch 必须是对象' };
|
|
306
|
+
|
|
307
|
+
if (patch.sources !== undefined) {
|
|
308
|
+
if (!Array.isArray(patch.sources)) return { error: 'sources 必须是数组' };
|
|
309
|
+
for (const s of patch.sources) {
|
|
310
|
+
if (typeof s?.name !== 'string' || typeof s?.branch !== 'string' || !s.branch.trim()) {
|
|
311
|
+
return { error: 'sources 每项需含 name 与非空 branch' };
|
|
312
|
+
}
|
|
313
|
+
const target = kit.sources.find((k) => k.name === s.name);
|
|
314
|
+
if (!target) return { error: `未知子工程:${s.name}` };
|
|
315
|
+
target.branch = s.branch.trim();
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
if (patch.autoSync !== undefined) {
|
|
319
|
+
if (typeof patch.autoSync !== 'boolean') return { error: 'autoSync 必须是布尔值' };
|
|
320
|
+
kit.assets = kit.assets ?? { mode: 'local' };
|
|
321
|
+
kit.assets.autoSync = patch.autoSync;
|
|
322
|
+
}
|
|
323
|
+
if (patch.models !== undefined) {
|
|
324
|
+
if (typeof patch.models !== 'object' || patch.models === null || Array.isArray(patch.models)) {
|
|
325
|
+
return { error: 'models 必须是对象' };
|
|
326
|
+
}
|
|
327
|
+
for (const [k, v] of Object.entries(patch.models)) {
|
|
328
|
+
if (v == null) continue; // null = 删除映射
|
|
329
|
+
if (typeof v !== 'object' || typeof v.model !== 'string' || !v.model.trim()) {
|
|
330
|
+
return { error: `models.${k} 需为 {provider?, model}` };
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
kit.models = kit.models ?? {};
|
|
334
|
+
for (const [k, v] of Object.entries(patch.models)) {
|
|
335
|
+
if (v == null) delete kit.models[k];
|
|
336
|
+
else kit.models[k] = { ...(v.provider ? { provider: v.provider } : {}), model: v.model.trim() };
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
writeKit(ws, kit);
|
|
340
|
+
return { ok: true, kit };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** 汇总一个工作区的面板状态;无 .harness 返回 null。 */
|
|
344
|
+
export function workspaceState(ws, { sync = null } = {}) {
|
|
345
|
+
if (!fs.existsSync(harnessDir(ws))) return null;
|
|
346
|
+
const boardFile = path.join(harnessDir(ws), 'tasks', 'board.md');
|
|
347
|
+
const board = fs.existsSync(boardFile) ? parseBoard(fs.readFileSync(boardFile, 'utf8')) : { headers: [], rows: [] };
|
|
348
|
+
let kit = null;
|
|
349
|
+
try { kit = readKit(ws) ?? defaultKit(); } catch { kit = defaultKit(); }
|
|
350
|
+
const claimsFile = path.join(harnessDir(ws), 'tasks', 'claims.json');
|
|
351
|
+
const claims = fs.existsSync(claimsFile) ? parseClaims(fs.readFileSync(claimsFile, 'utf8')) : {};
|
|
352
|
+
const taskSessions = readTaskSessions(ws);
|
|
353
|
+
const ledger = readWorkspaces(ws);
|
|
354
|
+
const ledgerTe = readTestEnv(ws);
|
|
355
|
+
const tasks = board.rows.map((row) => {
|
|
356
|
+
const progress = taskProgress(ws, kit, row.task, row.profile, row.status, row.apply);
|
|
357
|
+
return {
|
|
358
|
+
...row,
|
|
359
|
+
progress,
|
|
360
|
+
action: nextAction(row, progress),
|
|
361
|
+
lane: laneOf(row, progress),
|
|
362
|
+
claimer: claims[row.task]?.by ?? null,
|
|
363
|
+
sessionId: taskSessions[row.task]?.sessionId ?? null,
|
|
364
|
+
// M2 工作区分配(本机台账):{ <repo>: { placement: 'main'|'slot-N', branch, base } } | null
|
|
365
|
+
workspace: ledger.tasks[row.task]?.repos ?? null,
|
|
366
|
+
// TE 环境持有者标记(串行租约)
|
|
367
|
+
teHolder: ledgerTe.holder === row.task,
|
|
368
|
+
};
|
|
369
|
+
});
|
|
370
|
+
// M2 slot 池概览 + stale 清单(未合入保留的槽位,需人确认后重跑归档释放)
|
|
371
|
+
const slots = Object.fromEntries(Object.entries(ledger.slots).map(([repo, m]) => [repo,
|
|
372
|
+
Object.entries(m).map(([slot, b]) => ({ slot, task: b.task, branch: b.branch, state: b.state ?? 'bound' }))]));
|
|
373
|
+
const staleSlots = Object.entries(slots).flatMap(([repo, arr]) => arr.filter((s) => s.state === 'stale-unmerged').map((s) => ({ repo, ...s })));
|
|
374
|
+
return {
|
|
375
|
+
path: ws,
|
|
376
|
+
board,
|
|
377
|
+
tasks,
|
|
378
|
+
claims,
|
|
379
|
+
sync,
|
|
380
|
+
slots,
|
|
381
|
+
te: ledgerTe,
|
|
382
|
+
attention: (() => {
|
|
383
|
+
const items = attentionItems(tasks, sync, initGaps(ws, kit), staleSlots, ledgerTe, readDecisions(ws));
|
|
384
|
+
// 初始化失败 → block 级常驻提示(页面重开仍可见;成功后自动消失)
|
|
385
|
+
const initJob = initProgress.get(ws);
|
|
386
|
+
if (initJob?.done && initJob.error) {
|
|
387
|
+
items.push({ level: 'block', kind: 'init-failed', text: `初始化失败:${String(initJob.error).replace(/\s+/g, ' ').slice(0, 240)}(到「配置」页重跑初始化)`, init: true });
|
|
388
|
+
}
|
|
389
|
+
return items;
|
|
390
|
+
})(),
|
|
391
|
+
assets: kit.assets
|
|
392
|
+
? { mode: kit.assets.mode ?? 'local', url: kit.assets.url ?? null, branch: kit.assets.branch ?? null, autoSync: kit.assets.autoSync === true }
|
|
393
|
+
: { mode: 'local', url: null, branch: null, autoSync: false },
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// ---------------------------------------------------------- 初始化进度(向导动态提示)
|
|
398
|
+
// wsPath → { stage, detail, startedAt, done, error };仅内存态,进程重启即清空
|
|
399
|
+
const initProgress = new Map();
|
|
400
|
+
|
|
401
|
+
// ---------------------------------------------------------- 同步健康(缓存)
|
|
402
|
+
const SYNC_TTL_MS = 5 * 60 * 1000;
|
|
403
|
+
const syncCache = new Map(); // ws → { at, data, inflight }
|
|
404
|
+
|
|
405
|
+
/** 拉取宿主 LLM 注册的 provider/模型清单,供设置页模型映射下拉。失败容忍为 []。 */
|
|
406
|
+
export async function listModelCatalog(llm) {
|
|
407
|
+
try {
|
|
408
|
+
if (!llm || typeof llm.listProviders !== 'function') return [];
|
|
409
|
+
const providers = llm.listProviders();
|
|
410
|
+
const out = [];
|
|
411
|
+
for (const p of providers) {
|
|
412
|
+
let models = [];
|
|
413
|
+
try { models = (await llm.listModels?.(p.id)) ?? []; } catch { /* 单 provider 失败不拖垮整体 */ }
|
|
414
|
+
out.push({ provider: p.id, name: p.name ?? p.id, models: models.map((m) => ({ id: m.id, name: m.name ?? m.id })) });
|
|
415
|
+
}
|
|
416
|
+
return out;
|
|
417
|
+
} catch { return []; }
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** 模型下拉建议:kit.json models 已映射的逻辑名 + catalog 里的全部模型 id(provider 过滤)。 */
|
|
421
|
+
export function modelSuggest(models, provider) {
|
|
422
|
+
return (models ?? []).filter((mo) => !provider || mo.provider === provider).flatMap((mo) => mo.models ?? []).map((m) => m.id);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** 设置页角色名下拉数据源:kit.json models 已映射的逻辑名(角色名的既有用法)。 */
|
|
426
|
+
function logicalModelNames(kit) {
|
|
427
|
+
try { return Object.keys(kit?.models ?? {}).map((name) => ({ name })); } catch { return []; }
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async function computeSyncHealth(ws) {
|
|
431
|
+
const hd = harnessDir(ws);
|
|
432
|
+
const g = (args, timeoutMs = 30_000) => runGit(args, { cwd: hd, timeoutMs });
|
|
433
|
+
const at = new Date().toISOString();
|
|
434
|
+
if (!fs.existsSync(path.join(hd, '.git'))) {
|
|
435
|
+
// .harness 无独立 git:可能随工作区根仓库管理(embedded)——健康从父仓库取,
|
|
436
|
+
// dirty 只看 .harness 路径范围,ahead/behind 随根仓库分支(push 会一并携带资产)。
|
|
437
|
+
const lay = await assetsLayout(ws);
|
|
438
|
+
if (lay.layout !== 'embedded') {
|
|
439
|
+
return { state: 'local', ahead: 0, behind: 0, dirty: false, checkedAt: at };
|
|
440
|
+
}
|
|
441
|
+
try {
|
|
442
|
+
const root = lay.repoRoot;
|
|
443
|
+
const g2 = (args, timeoutMs = 30_000) => runGit(args, { cwd: root, timeoutMs });
|
|
444
|
+
const gitDirOut = (await g2(['rev-parse', '--git-dir'])).stdout.trim();
|
|
445
|
+
const gd = path.isAbsolute(gitDirOut) ? gitDirOut : path.join(root, gitDirOut || '.git');
|
|
446
|
+
if (fs.existsSync(path.join(gd, 'rebase-merge')) || fs.existsSync(path.join(gd, 'rebase-apply'))) {
|
|
447
|
+
return { state: 'blocked', layout: 'embedded', repoRoot: root, ahead: 0, behind: 0, dirty: true, checkedAt: at };
|
|
448
|
+
}
|
|
449
|
+
const dirty = !!(await g2(['status', '--porcelain', '--', lay.rel])).stdout.trim();
|
|
450
|
+
const remotes = (await g2(['remote'])).stdout.split('\n').map((s) => s.trim()).filter(Boolean);
|
|
451
|
+
if (remotes.length === 0) {
|
|
452
|
+
return { state: 'embedded', layout: 'embedded', repoRoot: root, ahead: 0, behind: 0, dirty, checkedAt: at };
|
|
453
|
+
}
|
|
454
|
+
const remote = remotes.includes('origin') ? 'origin' : remotes[0];
|
|
455
|
+
const branch = (await g2(['branch', '--show-current'])).stdout.trim() || 'master';
|
|
456
|
+
const fetch = await g2(['fetch', remote, branch], 60_000);
|
|
457
|
+
if (fetch.code !== 0) {
|
|
458
|
+
return { state: 'offline', layout: 'embedded', repoRoot: root, ahead: 0, behind: 0, dirty, checkedAt: at, error: (fetch.stderr || fetch.stdout).trim().slice(0, 300) };
|
|
459
|
+
}
|
|
460
|
+
const counts = (await g2(['rev-list', '--left-right', '--count', `HEAD...${remote}/${branch}`])).stdout.trim().split(/\s+/);
|
|
461
|
+
const ahead = Number(counts[0]) || 0;
|
|
462
|
+
const behind = Number(counts[1]) || 0;
|
|
463
|
+
const state = ahead > 0 && behind > 0 ? 'diverged' : behind > 0 ? 'behind' : ahead > 0 ? 'ahead' : 'clean';
|
|
464
|
+
return { state, layout: 'embedded', repoRoot: root, ahead, behind, dirty, checkedAt: at };
|
|
465
|
+
} catch (cause) {
|
|
466
|
+
return { state: 'unknown', layout: 'embedded', ahead: 0, behind: 0, dirty: false, checkedAt: at, error: cause.message };
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
try {
|
|
470
|
+
// rebase 中途 = 上次冲突中止未处理完
|
|
471
|
+
if (fs.existsSync(path.join(hd, '.git', 'rebase-merge')) || fs.existsSync(path.join(hd, '.git', 'rebase-apply'))) {
|
|
472
|
+
return { state: 'blocked', ahead: 0, behind: 0, dirty: true, checkedAt: at };
|
|
473
|
+
}
|
|
474
|
+
const remotes = (await g(['remote'])).stdout.split('\n').map((s) => s.trim()).filter(Boolean);
|
|
475
|
+
if (remotes.length === 0) {
|
|
476
|
+
return { state: 'no-remote', ahead: 0, behind: 0, dirty: false, checkedAt: at };
|
|
477
|
+
}
|
|
478
|
+
const remote = remotes.includes('origin') ? 'origin' : remotes[0];
|
|
479
|
+
const branch = readKit(ws)?.assets?.branch
|
|
480
|
+
|| (await g(['branch', '--show-current'])).stdout.trim() || 'master';
|
|
481
|
+
const dirty = !!(await g(['status', '--porcelain'])).stdout.trim();
|
|
482
|
+
const fetch = await g(['fetch', remote, branch], 60_000);
|
|
483
|
+
if (fetch.code !== 0) {
|
|
484
|
+
return { state: 'offline', ahead: 0, behind: 0, dirty, checkedAt: at, error: (fetch.stderr || fetch.stdout).trim().slice(0, 300) };
|
|
485
|
+
}
|
|
486
|
+
const upstream = `${remote}/${branch}`;
|
|
487
|
+
const counts = (await g(['rev-list', '--left-right', '--count', `HEAD...${upstream}`])).stdout.trim().split(/\s+/);
|
|
488
|
+
const ahead = Number(counts[0]) || 0;
|
|
489
|
+
const behind = Number(counts[1]) || 0;
|
|
490
|
+
const state = ahead > 0 && behind > 0 ? 'diverged' : behind > 0 ? 'behind' : ahead > 0 ? 'ahead' : 'clean';
|
|
491
|
+
return { state, ahead, behind, dirty, checkedAt: at };
|
|
492
|
+
} catch (cause) {
|
|
493
|
+
return { state: 'unknown', ahead: 0, behind: 0, dirty: false, checkedAt: at, error: cause.message };
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** 低频缓存的同步健康(同步返回,后台刷新);force=true 强制后台重检。 */
|
|
498
|
+
/** 工作区内目录列举(新建任务「浏览…」):拒绝越界/符号链接逃逸,过滤 .git 与 node_modules,目录优先排序。 */
|
|
499
|
+
export function browseDir(wsPath, rel = '') {
|
|
500
|
+
const rootReal = fs.realpathSync(wsPath);
|
|
501
|
+
const abs = path.resolve(wsPath, String(rel).replace(/^\/+|\/+$/g, '') || '.');
|
|
502
|
+
if (!fs.existsSync(abs)) return { error: '目录不存在' };
|
|
503
|
+
const absReal = fs.realpathSync(abs);
|
|
504
|
+
if (absReal !== rootReal && !absReal.startsWith(rootReal + path.sep)) return { error: '目录越界' };
|
|
505
|
+
if (!fs.statSync(absReal).isDirectory()) return { error: '不是目录' };
|
|
506
|
+
const SKIP = new Set(['.git', 'node_modules']);
|
|
507
|
+
const entries = fs.readdirSync(absReal, { withFileTypes: true })
|
|
508
|
+
.filter((e) => !SKIP.has(e.name))
|
|
509
|
+
.map((e) => ({ name: e.name, kind: e.isDirectory() ? 'dir' : (e.isFile() ? 'file' : 'other') }))
|
|
510
|
+
.filter((e) => e.kind !== 'other')
|
|
511
|
+
.sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === 'dir' ? -1 : 1))
|
|
512
|
+
.slice(0, 500);
|
|
513
|
+
const dir = path.relative(rootReal, absReal).split(path.sep).filter(Boolean).join('/');
|
|
514
|
+
return { ok: true, dir, parent: dir ? (path.posix.dirname(dir) === '.' ? '' : path.posix.dirname(dir)) : null, entries };
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
export function syncHealth(ws, { force = false } = {}) {
|
|
518
|
+
const cached = syncCache.get(ws);
|
|
519
|
+
if (force || !cached || (!cached.inflight && Date.now() - cached.at >= SYNC_TTL_MS)) {
|
|
520
|
+
if (!cached?.inflight) {
|
|
521
|
+
const inflight = computeSyncHealth(ws).then((data) => {
|
|
522
|
+
syncCache.set(ws, { at: Date.now(), data, inflight: null });
|
|
523
|
+
return data;
|
|
524
|
+
}).catch(() => cached?.data ?? null);
|
|
525
|
+
syncCache.set(ws, { at: Date.now(), data: cached?.data ?? null, inflight });
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
return syncCache.get(ws)?.data ?? { state: 'checking', ahead: 0, behind: 0, dirty: false };
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
/** 团队动态(git log,缓存 5 分钟)。 */
|
|
532
|
+
const activityCache = new Map();
|
|
533
|
+
export function teamActivity(ws, { force = false } = {}) {
|
|
534
|
+
const cached = activityCache.get(ws);
|
|
535
|
+
if (!force && cached && Date.now() - cached.at < SYNC_TTL_MS) return Promise.resolve(cached.data);
|
|
536
|
+
const hd = harnessDir(ws);
|
|
537
|
+
if (!fs.existsSync(path.join(hd, '.git'))) return Promise.resolve([]);
|
|
538
|
+
return runGit(['log', '-n', '50', '--pretty=format:%h%x1f%an%x1f%ad%x1f%s', '--date=format:%Y-%m-%d %H:%M'], { cwd: hd, timeoutMs: 15_000 })
|
|
539
|
+
.then((r) => {
|
|
540
|
+
const entries = r.code === 0 ? parseGitLog(r.stdout) : [];
|
|
541
|
+
activityCache.set(ws, { at: Date.now(), data: entries });
|
|
542
|
+
return entries;
|
|
543
|
+
})
|
|
544
|
+
.catch(() => cached?.data ?? []);
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
// --------------------------------------------------------------- HTTP 接线
|
|
548
|
+
function sendJson(res, code, data) {
|
|
549
|
+
const body = JSON.stringify(data);
|
|
550
|
+
res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
551
|
+
res.end(body);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
function readBody(req) {
|
|
555
|
+
return new Promise((resolve, reject) => {
|
|
556
|
+
const chunks = [];
|
|
557
|
+
req.on('data', (c) => chunks.push(c));
|
|
558
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
559
|
+
req.on('error', reject);
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
const findWs = (registry, ref) => registry.list().find((w) => w.id === ref || w.path === ref);
|
|
564
|
+
|
|
565
|
+
/**
|
|
566
|
+
* 注册面板 HTTP 端点。全部服务按可选读取(非 web 组成下静默跳过)。
|
|
567
|
+
* 返回 disposer 列表(调用方负责挂 ctx.effect)。
|
|
568
|
+
*/
|
|
569
|
+
export function registerPanelApi(ctx) {
|
|
570
|
+
const webServer = ctx.get('webServer');
|
|
571
|
+
const registry = ctx.get('workspaceRegistry');
|
|
572
|
+
if (!webServer || !registry) return [];
|
|
573
|
+
const agents = ctx.get('agents');
|
|
574
|
+
const commands = ctx.get('commands');
|
|
575
|
+
const sessionTitle = ctx.get('sessionTitle');
|
|
576
|
+
const llm = ctx.get('llm');
|
|
577
|
+
const logger = ctx.get('logger');
|
|
578
|
+
|
|
579
|
+
const disposers = [];
|
|
580
|
+
const mount = (route) => {
|
|
581
|
+
try {
|
|
582
|
+
const rawDispose = webServer.register(route);
|
|
583
|
+
// webServer 的 disposer 按 key 删除(table.delete(path)):旧 fiber 的处置
|
|
584
|
+
// 若晚于新 fiber 注册执行,会误删新注册。挂 identity 守卫——仅当表中
|
|
585
|
+
// 当前条目确为本 fiber 注册的 route 对象时才真正摘除。
|
|
586
|
+
const table = route.kind === 'exact' ? webServer.exact : webServer.prefixes;
|
|
587
|
+
disposers.push(() => {
|
|
588
|
+
if (table?.get?.(route.path) === route) rawDispose();
|
|
589
|
+
});
|
|
590
|
+
} catch (cause) {
|
|
591
|
+
// 热重载残留的史前注册无法在进程内摘除;容忍复用,重启 Host 后由新代码接管。
|
|
592
|
+
if (/duplicate/.test(cause.message)) {
|
|
593
|
+
logger?.warn?.(`harness-kit: route ${route.path} 已被旧实例占用,沿用旧处理器(重启 Host 后刷新)`);
|
|
594
|
+
} else throw cause;
|
|
595
|
+
}
|
|
596
|
+
};
|
|
597
|
+
|
|
598
|
+
// ---- 自动续接引擎:人裁决(定稿 approved / 审批 1:通过)落盘后自动接力下一条命令,
|
|
599
|
+
// 不再要求人手动敲 /hk-propose、/hk-apply。7s 轮询全部含 .harness 的工作区;
|
|
600
|
+
// 触发需同时满足:看板闸门(PENDING/IN_PROGRESS)+ 一次性标记未落盘 +
|
|
601
|
+
// 任务有会话绑定且该会话 agent 在线。失败按 5 分钟退避重试,成功才落标记。
|
|
602
|
+
// kit.json 里 autoAdvance=false 可整区关闭。审批/归档本身始终是人裁决。
|
|
603
|
+
const advanceBackoff = new Map(); // `${wsPath}|${task}|${hop}` → 上次尝试 ts
|
|
604
|
+
let advanceRunning = false;
|
|
605
|
+
const autoAdvanceTick = async () => {
|
|
606
|
+
if (advanceRunning || !agents || !commands) return;
|
|
607
|
+
advanceRunning = true;
|
|
608
|
+
try {
|
|
609
|
+
for (const w of registry.list()) {
|
|
610
|
+
const ws = w.path;
|
|
611
|
+
if (!fs.existsSync(harnessDir(ws))) continue;
|
|
612
|
+
let kit = null;
|
|
613
|
+
try { kit = readKit(ws); } catch { continue; }
|
|
614
|
+
if (kit?.autoAdvance === false) continue;
|
|
615
|
+
let hops;
|
|
616
|
+
try { hops = scanAutoAdvance(ws); } catch { continue; }
|
|
617
|
+
const decisions = readDecisions(ws);
|
|
618
|
+
for (const hop of hops) {
|
|
619
|
+
// 有待裁决决策点的任务:引擎不自动重试(重试无意义且刷日志),等人在面板/会话裁决后清决策点
|
|
620
|
+
if (decisions[hop.task]) continue;
|
|
621
|
+
const key = `${ws}|${hop.task}|${hop.hop}`;
|
|
622
|
+
if (Date.now() - (advanceBackoff.get(key) ?? 0) < 5 * 60 * 1000) continue;
|
|
623
|
+
const sessionId = readTaskSessions(ws)[hop.task]?.sessionId;
|
|
624
|
+
if (!sessionId) continue;
|
|
625
|
+
const agent = agents.get(sessionId);
|
|
626
|
+
if (!agent) continue;
|
|
627
|
+
advanceBackoff.set(key, Date.now());
|
|
628
|
+
try {
|
|
629
|
+
const exec = await commands.execute(agent, hop.line, [], new AbortController().signal);
|
|
630
|
+
if (exec?.result?.kind === 'error') {
|
|
631
|
+
logger?.warn?.(`harness-kit 自动续接失败:${hop.line} → ${exec.result.text}`);
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
634
|
+
markAdvanceFired(ws, hop.task, hop.hop);
|
|
635
|
+
advanceBackoff.delete(key);
|
|
636
|
+
logger?.info?.(`harness-kit 自动续接:${hop.task} ${hop.hop === 'propose' ? '定稿→propose' : hop.hop === 'archive' ? '审批2→archive' : '审批1→apply'}(${hop.line} → ${sessionId})`);
|
|
637
|
+
} catch (cause) {
|
|
638
|
+
logger?.warn?.(`harness-kit 自动续接异常:${hop.line} → ${cause.message}`);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
// TE 环境对账:holder 越过 TE(链标 ✅/—/归档)→ 自动释放并晋升队首,
|
|
642
|
+
// 向被晋升任务绑定的会话注入「轮到你了」。排队任务自己越过 TE → 自动出队。
|
|
643
|
+
try {
|
|
644
|
+
const board = parseBoard(fs.readFileSync(path.join(harnessDir(ws), 'tasks', 'board.md'), 'utf8')).rows;
|
|
645
|
+
const { promoted } = reconcileTestEnv(ws, board);
|
|
646
|
+
if (promoted) {
|
|
647
|
+
const sessionId = readTaskSessions(ws)[promoted]?.sessionId;
|
|
648
|
+
const agent = sessionId && agents.get(sessionId);
|
|
649
|
+
if (agent) {
|
|
650
|
+
try {
|
|
651
|
+
await commands.execute(agent, `TE 环境已释放,已授权给本任务:请继续 TE 阶段(环境独占,直接派发 Test Engineer 即可,无需再 acquire)。`, [], new AbortController().signal);
|
|
652
|
+
logger?.info?.(`harness-kit TE 环境晋升:${promoted}(→ ${sessionId})`);
|
|
653
|
+
} catch (cause) {
|
|
654
|
+
logger?.warn?.(`harness-kit TE 晋升注入失败:${promoted} → ${cause.message}`);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
} catch { /* 对账失败下轮重试 */ }
|
|
659
|
+
}
|
|
660
|
+
} finally {
|
|
661
|
+
advanceRunning = false;
|
|
662
|
+
}
|
|
663
|
+
};
|
|
664
|
+
const advanceTimer = setInterval(() => { void autoAdvanceTick(); }, 7000);
|
|
665
|
+
if (typeof advanceTimer.unref === 'function') advanceTimer.unref();
|
|
666
|
+
disposers.push(() => clearInterval(advanceTimer));
|
|
667
|
+
|
|
668
|
+
mount({
|
|
669
|
+
kind: 'exact',
|
|
670
|
+
path: '/harness-kit/state',
|
|
671
|
+
async handler(req, res) {
|
|
672
|
+
if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
|
|
673
|
+
try {
|
|
674
|
+
const workspaces = [];
|
|
675
|
+
for (const w of registry.list()) {
|
|
676
|
+
if (!fs.existsSync(harnessDir(w.path))) continue;
|
|
677
|
+
// 同步健康走缓存:命中立即返回,未命中后台刷新本轮先给旧值/空
|
|
678
|
+
const sync = syncHealth(w.path);
|
|
679
|
+
const state = workspaceState(w.path, { sync });
|
|
680
|
+
if (!state) continue;
|
|
681
|
+
const archivedSet = new Set(registry.archivedSessionIds ?? []);
|
|
682
|
+
const sessions = w.sessionIds.map((id) => ({ id, live: !!agents?.get(id), archived: archivedSet.has(id) }));
|
|
683
|
+
// 新建任务模态框的分析基点下拉:各仓可选分支清单
|
|
684
|
+
let gitBranches = {};
|
|
685
|
+
try { gitBranches = await listAllGitBranches(w.path, readKit(w.path) ?? {}); } catch { gitBranches = {}; }
|
|
686
|
+
// init:初始化任务进行状态(页面关掉后重开也能看到,防止无感知重复初始化)
|
|
687
|
+
workspaces.push({ id: w.id, title: w.title, ...state, sessions, gitBranches, init: initProgress.get(w.path) ?? null });
|
|
688
|
+
}
|
|
689
|
+
sendJson(res, 200, { ok: true, workspaces });
|
|
690
|
+
} catch (cause) {
|
|
691
|
+
logger?.warn?.(`harness-kit panel state failed: ${cause.message}`);
|
|
692
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
693
|
+
}
|
|
694
|
+
},
|
|
695
|
+
});
|
|
696
|
+
|
|
697
|
+
mount({
|
|
698
|
+
kind: 'exact',
|
|
699
|
+
path: '/harness-kit/config',
|
|
700
|
+
async handler(req, res) {
|
|
701
|
+
const ref = new URL(req.url, 'http://x').searchParams.get('workspace');
|
|
702
|
+
if (req.method === 'GET') {
|
|
703
|
+
try {
|
|
704
|
+
const ws = findWs(registry, ref);
|
|
705
|
+
if (!ws) return sendJson(res, 404, { ok: false, error: '未知工作区' });
|
|
706
|
+
const kit = readKit(ws.path);
|
|
707
|
+
if (!kit) return sendJson(res, 404, { ok: false, error: '尚未初始化' });
|
|
708
|
+
sendJson(res, 200, {
|
|
709
|
+
ok: true,
|
|
710
|
+
kit: { pack: kit.pack ?? 'ai-coding', hosts: kit.hosts ?? [], sources: kit.sources ?? [], models: kit.models ?? {}, assets: kit.assets ?? { mode: 'local' } },
|
|
711
|
+
sync: syncHealth(ws.path),
|
|
712
|
+
catalog: await listModelCatalog(llm),
|
|
713
|
+
presetModels: logicalModelNames(kit),
|
|
714
|
+
roles: listRoles(ws.path, kit).map((r) => ({ role: r.role, name: r.meta?.name ?? r.role, logical: r.meta?.model ?? null, origin: r.origin })),
|
|
715
|
+
});
|
|
716
|
+
} catch (cause) {
|
|
717
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
718
|
+
}
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
if (req.method === 'POST') {
|
|
722
|
+
try {
|
|
723
|
+
const { workspace, patch } = JSON.parse(await readBody(req) || '{}');
|
|
724
|
+
const ws = findWs(registry, workspace);
|
|
725
|
+
if (!ws) return sendJson(res, 404, { ok: false, error: '未知工作区' });
|
|
726
|
+
const r = updateKit(ws.path, patch);
|
|
727
|
+
if (r.error) return sendJson(res, 400, { ok: false, error: r.error });
|
|
728
|
+
sendJson(res, 200, { ok: true });
|
|
729
|
+
} catch (cause) {
|
|
730
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
731
|
+
}
|
|
732
|
+
return;
|
|
733
|
+
}
|
|
734
|
+
sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
|
|
735
|
+
},
|
|
736
|
+
});
|
|
737
|
+
|
|
738
|
+
// 新建任务「浏览…」:工作区内目录列举(仅供选文件;拒绝越界/符号链接逃逸;过滤 .git 与 node_modules)
|
|
739
|
+
mount({
|
|
740
|
+
kind: 'exact',
|
|
741
|
+
path: '/harness-kit/browse',
|
|
742
|
+
async handler(req, res) {
|
|
743
|
+
if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
|
|
744
|
+
try {
|
|
745
|
+
const q = new URL(req.url, 'http://x').searchParams;
|
|
746
|
+
const ws = findWs(registry, q.get('workspace'));
|
|
747
|
+
if (!ws) return sendJson(res, 404, { ok: false, error: '未知工作区' });
|
|
748
|
+
const r = browseDir(ws.path, q.get('dir') ?? '');
|
|
749
|
+
if (r.error) return sendJson(res, 400, { ok: false, error: r.error });
|
|
750
|
+
sendJson(res, 200, r);
|
|
751
|
+
} catch (cause) {
|
|
752
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
753
|
+
}
|
|
754
|
+
},
|
|
755
|
+
});
|
|
756
|
+
|
|
757
|
+
// 环境预检:向导打开时检查 git / Python 3,缺失项返回对应平台的安装命令。
|
|
758
|
+
mount({
|
|
759
|
+
kind: 'exact',
|
|
760
|
+
path: '/harness-kit/env',
|
|
761
|
+
async handler(req, res) {
|
|
762
|
+
if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
|
|
763
|
+
try {
|
|
764
|
+
sendJson(res, 200, { ok: true, ...(await checkEnvironment()) });
|
|
765
|
+
} catch (cause) {
|
|
766
|
+
logger?.warn?.(`harness-kit env check failed: ${cause.message}`);
|
|
767
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
768
|
+
}
|
|
769
|
+
},
|
|
770
|
+
});
|
|
771
|
+
|
|
772
|
+
mount({
|
|
773
|
+
kind: 'exact',
|
|
774
|
+
path: '/harness-kit/activity',
|
|
775
|
+
async handler(req, res) {
|
|
776
|
+
if (req.method !== 'GET') return sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
|
|
777
|
+
try {
|
|
778
|
+
const ref = new URL(req.url, 'http://x').searchParams.get('workspace');
|
|
779
|
+
const ws = findWs(registry, ref);
|
|
780
|
+
if (!ws) return sendJson(res, 404, { ok: false, error: '未知工作区' });
|
|
781
|
+
sendJson(res, 200, { ok: true, entries: await teamActivity(ws.path) });
|
|
782
|
+
} catch (cause) {
|
|
783
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
784
|
+
}
|
|
785
|
+
},
|
|
786
|
+
});
|
|
787
|
+
|
|
788
|
+
mount({
|
|
789
|
+
kind: 'exact',
|
|
790
|
+
path: '/harness-kit/sync',
|
|
791
|
+
async handler(req, res) {
|
|
792
|
+
if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
|
|
793
|
+
try {
|
|
794
|
+
const { workspace } = JSON.parse(await readBody(req) || '{}');
|
|
795
|
+
const ws = findWs(registry, workspace);
|
|
796
|
+
if (!ws) return sendJson(res, 404, { ok: false, error: '未知工作区' });
|
|
797
|
+
const kit = readKit(ws.path);
|
|
798
|
+
if (!kit) return sendJson(res, 404, { ok: false, error: '尚未初始化' });
|
|
799
|
+
const r = await syncAssets(ws.path, kit);
|
|
800
|
+
syncCache.delete(ws.path); // 同步后强制下次重检
|
|
801
|
+
sendJson(res, r.kind === 'success' ? 200 : 409, { ok: r.kind === 'success', text: r.text });
|
|
802
|
+
} catch (cause) {
|
|
803
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
804
|
+
}
|
|
805
|
+
},
|
|
806
|
+
});
|
|
807
|
+
|
|
808
|
+
// 临时排障(2026-11-13,「继续推进跳转异常」):命令路由关键步骤落盘,事后可回放点击链路。
|
|
809
|
+
const dbg = (obj) => {
|
|
810
|
+
try {
|
|
811
|
+
fs.appendFileSync('/tmp/hk-command-debug.log',
|
|
812
|
+
JSON.stringify({ ts: new Date().toISOString(), ...obj }) + '\n');
|
|
813
|
+
} catch { /* 排障日志失败不阻断 */ }
|
|
814
|
+
};
|
|
815
|
+
|
|
816
|
+
mount({
|
|
817
|
+
kind: 'exact',
|
|
818
|
+
path: '/harness-kit/command',
|
|
819
|
+
async handler(req, res) {
|
|
820
|
+
if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
|
|
821
|
+
try {
|
|
822
|
+
const { workspace, line, sessionId } = JSON.parse(await readBody(req) || '{}');
|
|
823
|
+
dbg({ ev: 'recv', workspace, line, sessionId: sessionId ?? null });
|
|
824
|
+
if (typeof line !== 'string' || !line.startsWith('/hk-')) {
|
|
825
|
+
return sendJson(res, 400, { ok: false, error: '仅允许 /hk-* 命令' });
|
|
826
|
+
}
|
|
827
|
+
const ws = findWs(registry, workspace);
|
|
828
|
+
if (!ws) return sendJson(res, 404, { ok: false, error: '未知工作区' });
|
|
829
|
+
let found;
|
|
830
|
+
if (typeof sessionId === 'string' && sessionId) {
|
|
831
|
+
// 定向注入(立项专属会话):新建会话的 agent 注册有延迟,轮询等待就绪(≤15s)
|
|
832
|
+
const deadline = Date.now() + 15000;
|
|
833
|
+
let agent = agents?.get(sessionId);
|
|
834
|
+
while (!agent && Date.now() < deadline) {
|
|
835
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
836
|
+
agent = agents?.get(sessionId);
|
|
837
|
+
}
|
|
838
|
+
if (agent) found = { id: sessionId, agent };
|
|
839
|
+
} else {
|
|
840
|
+
// 优先有活 agent 的会话(最近注册优先)
|
|
841
|
+
found = [...ws.sessionIds].reverse().map((id) => ({ id, agent: agents?.get(id) })).find((x) => x.agent);
|
|
842
|
+
}
|
|
843
|
+
if (!found) {
|
|
844
|
+
dbg({ ev: 'no-agent', directed: !!sessionId, wsSessions: [...ws.sessionIds] });
|
|
845
|
+
return sendJson(res, 409, {
|
|
846
|
+
ok: false,
|
|
847
|
+
error: sessionId ? '目标会话尚未就绪,请稍后重试' : '该工作区没有活动会话,请先打开一个会话再操作',
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
dbg({ ev: 'pick', directed: !!sessionId, picked: found.id });
|
|
851
|
+
// execute 返回 CommandExecution|undefined(语法/名称未解析时 undefined,且不落任何日志);
|
|
852
|
+
// 必须检查 result.kind——handler 失败(如任务撞名)时把真实错误透传给面板,
|
|
853
|
+
// 否则用户只看到「已发送」而会话里什么都没发生。
|
|
854
|
+
const exec = await commands.execute(found.agent, line, [], new AbortController().signal);
|
|
855
|
+
dbg({ ev: 'exec', sessionId: found.id, execUndefined: !exec, resultKind: exec?.result?.kind ?? null });
|
|
856
|
+
if (!exec) {
|
|
857
|
+
return sendJson(res, 400, { ok: false, error: `命令未注册或无法解析:${line}`, sessionId: found.id });
|
|
858
|
+
}
|
|
859
|
+
if (exec.result?.kind === 'error') {
|
|
860
|
+
return sendJson(res, 200, { ok: false, error: exec.result.text || '命令执行失败', sessionId: found.id });
|
|
861
|
+
}
|
|
862
|
+
if (exec.result?.kind === 'decision') {
|
|
863
|
+
// 结构化决策点:面板渲染可点选项(不登记绑定——命令未成功执行)
|
|
864
|
+
return sendJson(res, 200, {
|
|
865
|
+
ok: false, decision: true, code: exec.result.code,
|
|
866
|
+
text: exec.result.text, options: exec.result.options, sessionId: found.id,
|
|
867
|
+
});
|
|
868
|
+
}
|
|
869
|
+
// 任务↔会话绑定:命令成功才登记;命令行可解析出 ASCII 任务名即登记(--auto 自动命名场景由后续 hk-propose/apply 补绑)
|
|
870
|
+
const boundTask = line.match(/^\/hk-(?:new|fix|propose|apply|archive)\s+([A-Za-z0-9][A-Za-z0-9_-]*)/)?.[1];
|
|
871
|
+
if (boundTask) {
|
|
872
|
+
try { recordTaskSession(ws.path, boundTask, found.id); } catch { /* 绑定失败不阻断命令 */ }
|
|
873
|
+
}
|
|
874
|
+
// 立项会话命名:hk-new/hk-fix 成功后把会话标题固定为任务名(user 源,后续自动标题生成不再覆盖)。
|
|
875
|
+
// --auto 场景命令行没有任务名,从成功文本的 **task** 提取。
|
|
876
|
+
if (/^\/hk-(?:new|fix)\s/.test(line)) {
|
|
877
|
+
const named = boundTask || exec.result?.text?.match(/\*\*([A-Za-z0-9][A-Za-z0-9_-]*)\*\*/)?.[1];
|
|
878
|
+
if (named && found.agent?.session) {
|
|
879
|
+
try { sessionTitle?.rename(found.agent.session, named); } catch { /* 命名失败不阻断命令 */ }
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
sendJson(res, 200, { ok: true, line, sessionId: found.id, text: exec.result?.text });
|
|
883
|
+
// 归档兜底(2026-11-13 定位):绑定会话被归档后,客户端 openSession 选中它会被
|
|
884
|
+
// 导航效应立刻清回空白「新会话」视图(归档会话在侧栏隐藏),表现为「跳到一个空白
|
|
885
|
+
// 新对话窗」。命令成功即视为用户关注该会话,这里幂等取消归档;放在响应之后,
|
|
886
|
+
// 不影响时延,失败只记日志。
|
|
887
|
+
if (registry.archivedSessionIds?.includes?.(found.id)) {
|
|
888
|
+
registry.unarchiveSession(found.id).catch((e) => logger?.warn?.(`harness-kit unarchive failed: ${e.message}`));
|
|
889
|
+
}
|
|
890
|
+
} catch (cause) {
|
|
891
|
+
logger?.warn?.(`harness-kit panel command failed: ${cause.message}`);
|
|
892
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
893
|
+
}
|
|
894
|
+
},
|
|
895
|
+
});
|
|
896
|
+
|
|
897
|
+
// 临时排障端点:客户端把跳转步骤(hasLiveSession/openSession 结果)回报到同一日志文件。
|
|
898
|
+
mount({
|
|
899
|
+
kind: 'exact',
|
|
900
|
+
path: '/harness-kit/debug-log',
|
|
901
|
+
async handler(req, res) {
|
|
902
|
+
if (req.method !== 'POST') return sendJson(res, 405, { ok: false });
|
|
903
|
+
try {
|
|
904
|
+
const body = JSON.parse(await readBody(req) || '{}');
|
|
905
|
+
dbg({ ev: 'client', ...body });
|
|
906
|
+
} catch { /* 忽略坏包 */ }
|
|
907
|
+
sendJson(res, 200, { ok: true });
|
|
908
|
+
},
|
|
909
|
+
});
|
|
910
|
+
|
|
911
|
+
mount({
|
|
912
|
+
kind: 'exact',
|
|
913
|
+
path: '/harness-kit/bind-session',
|
|
914
|
+
async handler(req, res) {
|
|
915
|
+
if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
|
|
916
|
+
try {
|
|
917
|
+
const { workspace, task, sessionId } = JSON.parse(await readBody(req) || '{}');
|
|
918
|
+
const ws = findWs(registry, workspace);
|
|
919
|
+
if (!ws) return sendJson(res, 404, { ok: false, error: '未知工作区' });
|
|
920
|
+
if (typeof task !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(task)) {
|
|
921
|
+
return sendJson(res, 400, { ok: false, error: '任务名非法' });
|
|
922
|
+
}
|
|
923
|
+
if (typeof sessionId !== 'string' || !sessionId) {
|
|
924
|
+
return sendJson(res, 400, { ok: false, error: 'sessionId 缺失' });
|
|
925
|
+
}
|
|
926
|
+
recordTaskSession(ws.path, task, sessionId);
|
|
927
|
+
sendJson(res, 200, { ok: true });
|
|
928
|
+
} catch (cause) {
|
|
929
|
+
logger?.warn?.(`harness-kit bind-session failed: ${cause.message}`);
|
|
930
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
931
|
+
}
|
|
932
|
+
},
|
|
933
|
+
});
|
|
934
|
+
|
|
935
|
+
// ------------------------------------------------------- 工作区开通/初始化(面板向导)
|
|
936
|
+
// inspect:目录预检(打开/新建向导共用,返回是否 Harness 工作区与注册状态)
|
|
937
|
+
mount({
|
|
938
|
+
kind: 'exact',
|
|
939
|
+
path: '/harness-kit/workspace/inspect',
|
|
940
|
+
async handler(req, res) {
|
|
941
|
+
if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
|
|
942
|
+
try {
|
|
943
|
+
const body = JSON.parse(await readBody(req) || '{}');
|
|
944
|
+
const info = inspectDir(body.path);
|
|
945
|
+
const registered = info.path ? findWs(registry, info.path) : undefined;
|
|
946
|
+
sendJson(res, 200, {
|
|
947
|
+
ok: true,
|
|
948
|
+
inspect: info,
|
|
949
|
+
registered: registered ? { id: registered.id, title: registered.title, path: registered.path } : null,
|
|
950
|
+
});
|
|
951
|
+
} catch (cause) {
|
|
952
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
953
|
+
}
|
|
954
|
+
},
|
|
955
|
+
});
|
|
956
|
+
|
|
957
|
+
// create:把任意已存在目录注册为 DSH 工作区(新建向导第一步;不建目录、不写资产)
|
|
958
|
+
mount({
|
|
959
|
+
kind: 'exact',
|
|
960
|
+
path: '/harness-kit/workspace/create',
|
|
961
|
+
async handler(req, res) {
|
|
962
|
+
if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
|
|
963
|
+
try {
|
|
964
|
+
const body = JSON.parse(await readBody(req) || '{}');
|
|
965
|
+
const wsPath = typeof body.path === 'string' ? body.path.trim() : '';
|
|
966
|
+
if (!wsPath || !path.isAbsolute(wsPath)) return sendJson(res, 400, { ok: false, error: 'path 必须是绝对路径' });
|
|
967
|
+
const info = inspectDir(wsPath);
|
|
968
|
+
if (!info.exists) return sendJson(res, 400, { ok: false, error: `目录不存在:${wsPath}` });
|
|
969
|
+
if (!info.isDir) return sendJson(res, 400, { ok: false, error: `不是目录:${wsPath}` });
|
|
970
|
+
const title = typeof body.title === 'string' && body.title.trim() ? body.title.trim() : undefined;
|
|
971
|
+
const w = await registry.create(wsPath, title);
|
|
972
|
+
sendJson(res, 200, { ok: true, workspace: { id: w.id, title: w.title, path: w.path }, inspect: inspectDir(w.path) });
|
|
973
|
+
} catch (cause) {
|
|
974
|
+
logger?.warn?.(`harness-kit workspace create failed: ${cause.message}`);
|
|
975
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
976
|
+
}
|
|
977
|
+
},
|
|
978
|
+
});
|
|
979
|
+
|
|
980
|
+
// open:打开已有 Harness 工作区——必须含可解析的 .harness/kit.json,否则 409
|
|
981
|
+
mount({
|
|
982
|
+
kind: 'exact',
|
|
983
|
+
path: '/harness-kit/workspace/open',
|
|
984
|
+
async handler(req, res) {
|
|
985
|
+
if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
|
|
986
|
+
try {
|
|
987
|
+
const body = JSON.parse(await readBody(req) || '{}');
|
|
988
|
+
const wsPath = typeof body.path === 'string' ? body.path.trim() : '';
|
|
989
|
+
if (!wsPath || !path.isAbsolute(wsPath)) return sendJson(res, 400, { ok: false, error: 'path 必须是绝对路径' });
|
|
990
|
+
const info = inspectDir(wsPath);
|
|
991
|
+
if (!info.exists) return sendJson(res, 400, { ok: false, error: `目录不存在:${wsPath}` });
|
|
992
|
+
if (!info.isDir) return sendJson(res, 400, { ok: false, error: `不是目录:${wsPath}` });
|
|
993
|
+
if (!info.hasKit) {
|
|
994
|
+
return sendJson(res, 409, { ok: false, code: 'not-harness', error: '该目录不是 Harness 工作区:缺少 .harness/kit.json(可改用「新建工作区」并在此目录初始化)', inspect: info });
|
|
995
|
+
}
|
|
996
|
+
if (info.kitError) {
|
|
997
|
+
return sendJson(res, 409, { ok: false, code: 'kit-corrupt', error: `.harness/kit.json 解析失败:${info.kitError}`, inspect: info });
|
|
998
|
+
}
|
|
999
|
+
const title = typeof body.title === 'string' && body.title.trim() ? body.title.trim() : undefined;
|
|
1000
|
+
const w = await registry.create(wsPath, title);
|
|
1001
|
+
sendJson(res, 200, { ok: true, workspace: { id: w.id, title: w.title, path: w.path }, inspect: info });
|
|
1002
|
+
} catch (cause) {
|
|
1003
|
+
logger?.warn?.(`harness-kit workspace open failed: ${cause.message}`);
|
|
1004
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
1005
|
+
}
|
|
1006
|
+
},
|
|
1007
|
+
});
|
|
1008
|
+
|
|
1009
|
+
// init:在已注册工作区上执行 /hk-init 等价物化(幂等),可附带登记子工程(/hk-setup --add 等价)。
|
|
1010
|
+
// body: {workspace, assets?: {mode:'local'|'init'|'url', url?, branch?}, sources?: [{url, name?, path?, role?, branch?}]}
|
|
1011
|
+
mount({
|
|
1012
|
+
kind: 'exact',
|
|
1013
|
+
path: '/harness-kit/workspace/init',
|
|
1014
|
+
async handler(req, res) {
|
|
1015
|
+
if (req.method !== 'POST') return sendJson(res, 405, { ok: false, error: 'method-not-allowed' });
|
|
1016
|
+
try {
|
|
1017
|
+
const body = JSON.parse(await readBody(req) || '{}');
|
|
1018
|
+
const ws = findWs(registry, body.workspace);
|
|
1019
|
+
if (!ws) return sendJson(res, 404, { ok: false, error: '未知工作区(请先在 DSH 注册该目录)' });
|
|
1020
|
+
let assets;
|
|
1021
|
+
let branch;
|
|
1022
|
+
if (body.assets != null) {
|
|
1023
|
+
const a = body.assets;
|
|
1024
|
+
if (!a || typeof a !== 'object' || !['local', 'init', 'url'].includes(a.mode)) {
|
|
1025
|
+
return sendJson(res, 400, { ok: false, error: 'assets.mode 必须是 local/init/url' });
|
|
1026
|
+
}
|
|
1027
|
+
if (a.mode === 'url') {
|
|
1028
|
+
const url = typeof a.url === 'string' ? a.url.trim() : '';
|
|
1029
|
+
if (!url) return sendJson(res, 400, { ok: false, error: 'assets.mode=url 时必须提供 assets.url' });
|
|
1030
|
+
assets = url;
|
|
1031
|
+
} else {
|
|
1032
|
+
assets = a.mode;
|
|
1033
|
+
}
|
|
1034
|
+
branch = typeof a.branch === 'string' && a.branch.trim() ? a.branch.trim() : undefined;
|
|
1035
|
+
}
|
|
1036
|
+
const sources = [];
|
|
1037
|
+
if (body.sources != null) {
|
|
1038
|
+
if (!Array.isArray(body.sources)) return sendJson(res, 400, { ok: false, error: 'sources 必须是数组' });
|
|
1039
|
+
for (const s of body.sources) {
|
|
1040
|
+
if (!s || typeof s !== 'object') return sendJson(res, 400, { ok: false, error: 'sources 元素必须是对象' });
|
|
1041
|
+
const url = typeof s.url === 'string' ? s.url.trim() : '';
|
|
1042
|
+
if (!url) return sendJson(res, 400, { ok: false, error: '每个子工程必须提供 url' });
|
|
1043
|
+
const spec = { url };
|
|
1044
|
+
for (const k of ['name', 'path', 'role', 'branch']) {
|
|
1045
|
+
if (typeof s[k] === 'string' && s[k].trim()) spec[k] = s[k].trim();
|
|
1046
|
+
}
|
|
1047
|
+
if (spec.path) {
|
|
1048
|
+
const abs = path.resolve(ws.path, spec.path);
|
|
1049
|
+
if (abs !== ws.path && !abs.startsWith(ws.path + path.sep)) {
|
|
1050
|
+
return sendJson(res, 400, { ok: false, error: `子工程路径越界:${spec.path}` });
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
sources.push(spec);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
// 异步任务化(2026-11-17):初始化可能持续十几分钟(大仓克隆),不能挂在单个
|
|
1057
|
+
// HTTP 请求上——页面刷新/重载会掐断请求,前端只看到 "Failed to fetch" 而任务其实在跑。
|
|
1058
|
+
// 改为:POST 立即返回 started,后台执行 + 进度端点轮询;刷新页面不影响任务完成。
|
|
1059
|
+
const prevJob = initProgress.get(ws.path);
|
|
1060
|
+
if (prevJob && !prevJob.done) {
|
|
1061
|
+
return sendJson(res, 409, { ok: false, error: '该工作区初始化已在进行中,请等待完成(可刷新页面,任务不受影响)' });
|
|
1062
|
+
}
|
|
1063
|
+
initProgress.set(ws.path, { stage: '准备', detail: '校验参数', startedAt: Date.now(), done: false, error: null, result: null });
|
|
1064
|
+
void (async () => {
|
|
1065
|
+
const setP = (patch) => {
|
|
1066
|
+
initProgress.set(ws.path, { ...(initProgress.get(ws.path) ?? {}), ...patch });
|
|
1067
|
+
};
|
|
1068
|
+
try {
|
|
1069
|
+
const r = await runInit(ws.path, {
|
|
1070
|
+
assets, branch, sources,
|
|
1071
|
+
onProgress: (p) => setP({ stage: p.stage, detail: p.detail, done: false, error: null }),
|
|
1072
|
+
});
|
|
1073
|
+
if (!r.ok) {
|
|
1074
|
+
setP({ stage: '失败', detail: '', done: true, error: r.error });
|
|
1075
|
+
return;
|
|
1076
|
+
}
|
|
1077
|
+
setP({
|
|
1078
|
+
stage: '完成', detail: '', done: true, error: null, finishedAt: Date.now(),
|
|
1079
|
+
result: {
|
|
1080
|
+
report: formatInitReport(r),
|
|
1081
|
+
created: r.created,
|
|
1082
|
+
kept: r.kept,
|
|
1083
|
+
scanned: r.scanned,
|
|
1084
|
+
warnings: r.warnings,
|
|
1085
|
+
sources: r.kit.sources,
|
|
1086
|
+
sourceErrors: r.sourceReports.filter((x) => !x.ok).map((x) => x.error),
|
|
1087
|
+
},
|
|
1088
|
+
});
|
|
1089
|
+
} catch (cause) {
|
|
1090
|
+
setP({ stage: '失败', detail: '', done: true, error: String(cause?.message ?? cause) });
|
|
1091
|
+
}
|
|
1092
|
+
})();
|
|
1093
|
+
return sendJson(res, 200, { ok: true, started: true, workspace: ws.id });
|
|
1094
|
+
} catch (cause) {
|
|
1095
|
+
logger?.warn?.(`harness-kit workspace init failed: ${cause.message}`);
|
|
1096
|
+
sendJson(res, 500, { ok: false, error: cause.message });
|
|
1097
|
+
}
|
|
1098
|
+
},
|
|
1099
|
+
});
|
|
1100
|
+
|
|
1101
|
+
logger?.info?.('harness-kit: M4b panel API mounted (state/config/activity/sync/command/bind-session/workspace-inspect/create/open/init)');
|
|
1102
|
+
return disposers;
|
|
1103
|
+
}
|