dsh-harness-kit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +321 -2
  3. package/README.zh-CN.md +278 -0
  4. package/client.js +1272 -0
  5. package/cordis.patch.yml +4 -0
  6. package/docs/DETAIL.en.md +97 -0
  7. package/docs/DETAIL.md +73 -0
  8. package/docs/assets/ui-new-task.png +0 -0
  9. package/docs/assets/ui-onboarding.png +0 -0
  10. package/docs/assets/ui-war-room.png +0 -0
  11. package/icon.svg +7 -0
  12. package/index.js +49 -0
  13. package/kernel/advance.js +96 -0
  14. package/kernel/bindings.js +24 -0
  15. package/kernel/commands.js +927 -0
  16. package/kernel/env.js +64 -0
  17. package/kernel/exec.js +41 -0
  18. package/kernel/flows.js +89 -0
  19. package/kernel/guards.js +79 -0
  20. package/kernel/miniyaml.js +133 -0
  21. package/kernel/models.js +104 -0
  22. package/kernel/panel.js +1103 -0
  23. package/kernel/paths.js +53 -0
  24. package/kernel/roles.js +67 -0
  25. package/kernel/setup.js +644 -0
  26. package/kernel/state.js +59 -0
  27. package/kernel/steer.js +27 -0
  28. package/kernel/sync.js +140 -0
  29. package/kernel/te.js +122 -0
  30. package/kernel/worktree.js +868 -0
  31. package/locale/en.json +14 -0
  32. package/locale/zh.json +14 -0
  33. package/package.json +63 -4
  34. package/packs/ai-coding/agents/business-analyst.md +90 -0
  35. package/packs/ai-coding/agents/code-reviewer.md +156 -0
  36. package/packs/ai-coding/agents/developer.md +147 -0
  37. package/packs/ai-coding/agents/project-manager.md +190 -0
  38. package/packs/ai-coding/agents/readiness-reviewer.md +123 -0
  39. package/packs/ai-coding/agents/solution-architect.md +122 -0
  40. package/packs/ai-coding/agents/test-engineer.md +230 -0
  41. package/packs/ai-coding/assets/scripts/check_codegraph.py +215 -0
  42. package/packs/ai-coding/assets/scripts/codebase_guide_init.py +330 -0
  43. package/packs/ai-coding/assets/scripts/env_auto.py +612 -0
  44. package/packs/ai-coding/assets/scripts/harness.py +38 -0
  45. package/packs/ai-coding/assets/scripts/harness_init.py +193 -0
  46. package/packs/ai-coding/assets/scripts/lib.py +1011 -0
  47. package/packs/ai-coding/assets/scripts/run_field.py +295 -0
  48. package/packs/ai-coding/assets/scripts/spec_lint.py +247 -0
  49. package/packs/ai-coding/assets/scripts/update_board.py +524 -0
  50. package/packs/ai-coding/assets/scripts/verify.py +184 -0
  51. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/CODE_STANDARDS.tmpl +44 -0
  52. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/app-CLAUDE.tmpl +34 -0
  53. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/build.tmpl +8 -0
  54. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/module-CLAUDE.tmpl +42 -0
  55. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/root-CLAUDE.tmpl +41 -0
  56. package/packs/ai-coding/assets/templates/java/maven/CODE_STANDARDS.tmpl +44 -0
  57. package/packs/ai-coding/assets/templates/java/maven/build.tmpl +9 -0
  58. package/packs/ai-coding/assets/templates/java/maven/root-CLAUDE.tmpl +38 -0
  59. package/packs/ai-coding/assets/templates/java/maven-multimodule/CODE_STANDARDS.tmpl +44 -0
  60. package/packs/ai-coding/assets/templates/java/maven-multimodule/build.tmpl +9 -0
  61. package/packs/ai-coding/assets/templates/java/maven-multimodule/module-CLAUDE.tmpl +40 -0
  62. package/packs/ai-coding/assets/templates/java/maven-multimodule/root-CLAUDE.tmpl +38 -0
  63. package/packs/ai-coding/assets/templates/javascript/mobile-app/CODE_STANDARDS.tmpl +51 -0
  64. package/packs/ai-coding/assets/templates/javascript/mobile-app/build.tmpl +8 -0
  65. package/packs/ai-coding/assets/templates/javascript/mobile-app/root-CLAUDE.tmpl +36 -0
  66. package/packs/ai-coding/assets/templates/javascript/uniapp/CODE_STANDARDS.tmpl +69 -0
  67. package/packs/ai-coding/assets/templates/javascript/uniapp/build.tmpl +8 -0
  68. package/packs/ai-coding/assets/templates/javascript/uniapp/root-CLAUDE.tmpl +56 -0
  69. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/CODE_STANDARDS.tmpl +51 -0
  70. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/app-CLAUDE.tmpl +36 -0
  71. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/build.tmpl +8 -0
  72. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/root-CLAUDE.tmpl +34 -0
  73. package/packs/ai-coding/flows/_router.yml +14 -0
  74. package/packs/ai-coding/flows/bugfix.yml +37 -0
  75. package/packs/ai-coding/flows/fix.yml +44 -0
  76. package/packs/ai-coding/flows/init.yml +83 -0
  77. package/packs/ai-coding/flows/new.yml +29 -0
  78. package/packs/ai-coding/flows/quick.yml +40 -0
  79. package/packs/ai-coding/flows/refactor.yml +50 -0
  80. package/packs/ai-coding/flows/standard.yml +49 -0
  81. package/packs/ai-coding/rules/code-standards.md +30 -0
  82. package/packs/ai-coding/rules/core.md +83 -0
  83. package/packs/ai-coding/templates/bugfix.md +29 -0
  84. package/packs/ai-coding/templates/memory-entry.md +46 -0
  85. package/packs/ai-coding/templates/proposal.md +47 -0
  86. package/packs/ai-coding/templates/spec-template.md +34 -0
  87. package/screenshots.json +5 -0
package/kernel/env.js ADDED
@@ -0,0 +1,64 @@
1
+ // 向导环境预检:git / Python 3 是 Harness Kit 的硬依赖,缺失时在面板里直接给出
2
+ // 对应平台的安装命令,避免用户提交初始化后才发现失败。
3
+ // 纯逻辑 + 注入式执行器:sim 套件可在不 spawn 进程的情况下覆盖三平台提示。
4
+ import { run } from './exec.js';
5
+
6
+ /** 受检工具及其安装指引(命令只做展示,不自动执行)。 */
7
+ export const ENV_TOOLS = [
8
+ {
9
+ id: 'git',
10
+ name: 'git',
11
+ command: 'git',
12
+ args: ['--version'],
13
+ purpose: '克隆代码/资产仓库、团队资产同步、任务并行 worktree',
14
+ install: {
15
+ darwin: { command: 'xcode-select --install', url: 'https://git-scm.com/download/mac' },
16
+ win32: { command: 'winget install --id Git.Git -e --source winget', url: 'https://git-scm.com/download/win' },
17
+ linux: { command: 'sudo apt install git # Debian/Ubuntu;Fedora: sudo dnf install git', url: 'https://git-scm.com/download/linux' },
18
+ default: { command: 'https://git-scm.com/downloads', url: 'https://git-scm.com/downloads' },
19
+ },
20
+ },
21
+ {
22
+ id: 'python3',
23
+ name: 'Python 3',
24
+ command: 'python3',
25
+ args: ['--version'],
26
+ purpose: '初始化脚本、看板写入、规格校验、体检与验证',
27
+ install: {
28
+ darwin: { command: 'brew install python', url: 'https://www.python.org/downloads/mac-osx/' },
29
+ win32: {
30
+ command: 'winget install --id Python.Python.3.12 -e --source winget',
31
+ url: 'https://www.python.org/downloads/windows/',
32
+ },
33
+ linux: { command: 'sudo apt install python3 # Debian/Ubuntu;Fedora: sudo dnf install python3', url: 'https://www.python.org/downloads/source/' },
34
+ default: { command: 'https://www.python.org/downloads/', url: 'https://www.python.org/downloads/' },
35
+ },
36
+ },
37
+ ];
38
+
39
+ function firstLine(text) {
40
+ return String(text ?? '').trim().split('\n')[0]?.trim() ?? '';
41
+ }
42
+
43
+ /**
44
+ * 检查每个工具的 `--version`。失败不是异常:返回 missing 项与安装指引。
45
+ * @param {{ platform?: NodeJS.Platform, runCommand?: typeof run }} options
46
+ * @returns {Promise<{ allOk: boolean, platform: string, tools: Array<object> }>}
47
+ */
48
+ export async function checkEnvironment({ platform = process.platform, runCommand = run } = {}) {
49
+ const tools = [];
50
+ for (const tool of ENV_TOOLS) {
51
+ const result = await runCommand(tool.command, tool.args, { timeoutMs: 10_000 });
52
+ const found = result.code === 0;
53
+ const install = tool.install[platform] ?? tool.install.default;
54
+ tools.push({
55
+ id: tool.id,
56
+ name: tool.name,
57
+ purpose: tool.purpose,
58
+ ok: found,
59
+ version: found ? firstLine(result.stdout) || firstLine(result.stderr) || undefined : undefined,
60
+ ...(found ? {} : { install, error: firstLine(result.stderr) || `exit ${result.code}` }),
61
+ });
62
+ }
63
+ return { allOk: tools.every((tool) => tool.ok), platform, tools };
64
+ }
package/kernel/exec.js ADDED
@@ -0,0 +1,41 @@
1
+ // Promisified child_process runner for git/script invocations owned by
2
+ // command handlers. Runs unsandboxed like Claude Code hooks; every call site
3
+ // reports the command and outcome in the command result text.
4
+ import { spawn } from 'node:child_process';
5
+
6
+ export function run(cmd, args, { cwd, timeoutMs = 120_000 } = {}) {
7
+ return new Promise((resolve) => {
8
+ const child = spawn(cmd, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
9
+ let stdout = '';
10
+ let stderr = '';
11
+ let settled = false;
12
+ const timer = setTimeout(() => {
13
+ if (settled) return;
14
+ settled = true;
15
+ child.kill('SIGKILL');
16
+ resolve({ code: -1, stdout, stderr: stderr + `\n[harness-kit] 超时(${timeoutMs}ms),进程已终止` });
17
+ }, timeoutMs);
18
+ child.stdout.on('data', (d) => {
19
+ stdout += d;
20
+ });
21
+ child.stderr.on('data', (d) => {
22
+ stderr += d;
23
+ });
24
+ child.on('error', (err) => {
25
+ if (settled) return;
26
+ settled = true;
27
+ clearTimeout(timer);
28
+ resolve({ code: -1, stdout, stderr: stderr + `\n[harness-kit] 启动失败:${err.message}` });
29
+ });
30
+ child.on('close', (code) => {
31
+ if (settled) return;
32
+ settled = true;
33
+ clearTimeout(timer);
34
+ resolve({ code: code ?? -1, stdout, stderr });
35
+ });
36
+ });
37
+ }
38
+
39
+ export function runGit(args, opts) {
40
+ return run('git', args, opts);
41
+ }
@@ -0,0 +1,89 @@
1
+ // Flow loading + compilation of a flow definition into a Lead orchestration
2
+ // prompt (ruling 2: prompt orchestration first, no hard state machine).
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { packDir, harnessDir } from './paths.js';
6
+ import { parseYaml } from './miniyaml.js';
7
+
8
+ /** Load flows/<name>.yml; workspace override .harness/flows/ wins. */
9
+ export function loadFlow(ws, kit, name) {
10
+ const candidates = [
11
+ path.join(harnessDir(ws), 'flows', `${name}.yml`),
12
+ path.join(packDir(kit), 'flows', `${name}.yml`),
13
+ ];
14
+ for (const file of candidates) {
15
+ if (fs.existsSync(file)) {
16
+ try {
17
+ return { flow: parseYaml(fs.readFileSync(file, 'utf8')), file };
18
+ } catch (cause) {
19
+ throw new Error(`流程定义 ${file} 解析失败:${cause.message}`);
20
+ }
21
+ }
22
+ }
23
+ return null;
24
+ }
25
+
26
+ function stageLines(flow, context) {
27
+ const lines = [];
28
+ // phase filter: stages without `phase` belong to every phase (fix/init flows);
29
+ // full-flow stages carry phase: propose|apply and are filtered by the command.
30
+ const stages = (flow.stages ?? []).filter(
31
+ (s) => !context.phase || !s.phase || s.phase === context.phase,
32
+ );
33
+ for (const [i, stage] of stages.entries()) {
34
+ const head = `### 阶段 ${i + 1}:${stage.name}`;
35
+ const body = [];
36
+ if (stage.actor) body.push(`- 执行者:${stage.actor}`);
37
+ if (stage.worker) body.push(`- Worker 角色:${stage.worker}(用 subagent 工具派发,prompt 中内嵌角色定义全文)`);
38
+ if (stage.model) body.push(`- 派发模型:${stage.model}`);
39
+ if (Array.isArray(stage.do)) for (const item of stage.do) body.push(`- ${item}`);
40
+ if (stage.gate) body.push(`- ⛔ 人工质量门:${stage.gate} —— 用 ask_user_question 工具交人裁决,禁止自行决定`);
41
+ if (stage.approval) body.push(`- ⛔ 审批点:${stage.approval} —— 用 ask_user_question 交人审批后方可继续`);
42
+ lines.push([head, ...body].join('\n'));
43
+ }
44
+ return lines.join('\n\n');
45
+ }
46
+
47
+ /**
48
+ * Compile the flow into a Lead orchestration prompt.
49
+ * context: { task, desc, roleSections, rules, artifacts, phase?, dispatchSection? }
50
+ * phase='propose'|'apply' filters full-flow stages; dispatchSection overrides the
51
+ * default dispatch appendix (used by M2 commands to embed model routing).
52
+ */
53
+ export function compileFlowPrompt(flow, context) {
54
+ const parts = [
55
+ `# Harness Kit 任务调度指令(${flow.name ?? 'flow'})`,
56
+ '',
57
+ `你现在以 **PM(项目负责人)** 身份编排本任务。以下是流程定义(${context.flowFile})编译出的执行剧本,严格按阶段顺序推进;标注 ⛔ 处必须停下来交人裁决/审批。`,
58
+ '',
59
+ `## 任务`,
60
+ `- 任务名:${context.task}`,
61
+ `- 需求描述:${context.desc}`,
62
+ `- 活目录:${context.artifacts}`,
63
+ '',
64
+ `## 流程阶段`,
65
+ stageLines(flow, context),
66
+ ];
67
+ if (flow.after?.length) {
68
+ parts.push('', '## 收尾', ...flow.after.map((s) => `- ${s}`));
69
+ }
70
+ if (context.roleSections) {
71
+ parts.push('', '## 角色定义', context.roleSections);
72
+ }
73
+ if (context.rules) {
74
+ parts.push('', '## 运行时纪律(必须遵守)', context.rules);
75
+ }
76
+ if (context.dispatchSection) {
77
+ parts.push('', context.dispatchSection);
78
+ } else {
79
+ parts.push(
80
+ '',
81
+ '## 派发方式',
82
+ '- 你自己承担 PM 职责:拆解、派发、汇总、向人汇报。',
83
+ '- Worker/subagent 一律用 subagent 工具派发:prompt 自包含(任务背景 + 产出路径 + 写范围约束;阶段指定 Worker 角色时另需先读角色文件并内嵌定义全文),等待其返回结果后再进下一阶段。',
84
+ '- Worker 产物写入上述活目录对应文件;Worker 只能写其 write_scopes 声明的范围。',
85
+ '- 任何时候信息不足或口径模糊:先向人反问,不要自行补全。',
86
+ );
87
+ }
88
+ return parts.join('\n');
89
+ }
@@ -0,0 +1,79 @@
1
+ // ToolGuard set. M1 scope:
2
+ // - unconditional: destructive git operations (reset --hard / clean -f / push --force)
3
+ // - phase-conditional (Bootstrap red line): writes to kit.json sources paths
4
+ // and e2e/ while any active task lacks a recorded human quality-gate verdict
5
+ // (see kernel/state.js — the verdict recorded in bugfix.md unlocks Dev).
6
+ import path from 'node:path';
7
+ import { wsRoot, readKit } from './paths.js';
8
+ import { lockedSourcePaths } from './state.js';
9
+
10
+ const DESTRUCTIVE = /\bgit\s+reset\s+--hard\b|\bgit\s+clean\s+-[a-zA-Z]*f|\bgit\s+push\b[^|&;]*--force|\bgit\s+push\s+-f\b/;
11
+ const BASH_WRITE = />>?|\bsed\s+-i\b|\btee\b|\b(mv|cp|rm|touch|mkdir|install|rsync|patch)\b|\bgit\s+(apply|restore|checkout\s+--|commit|add)\b/;
12
+
13
+ function normalizeTarget(ws, filePath) {
14
+ if (typeof filePath !== 'string' || filePath === '') return null;
15
+ const abs = path.isAbsolute(filePath) ? filePath : path.resolve(ws, filePath);
16
+ return abs;
17
+ }
18
+
19
+ function pathHits(abs, ws, relPaths) {
20
+ return relPaths.find((rel) => {
21
+ const base = path.resolve(ws, rel);
22
+ return abs === base || abs.startsWith(base + path.sep);
23
+ });
24
+ }
25
+
26
+ function bashHitsProtected(command, locked) {
27
+ if (!BASH_WRITE.test(command)) return null;
28
+ // cheap token scan: any protected relative path appearing as a token
29
+ return locked.find((rel) => {
30
+ const token = rel.replace(/\/$/, '');
31
+ return new RegExp(`(^|[\\s'"|;&>])${token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(/|\\s|'|"|:|$)`).test(command);
32
+ });
33
+ }
34
+
35
+ export function installGuards(ctx, logger) {
36
+ const dispose = ctx.tools.guard((execution) => {
37
+ const name = execution.name;
38
+ const args = execution.arguments ?? {};
39
+
40
+ if (name === 'bash' && typeof args.command === 'string' && DESTRUCTIVE.test(args.command)) {
41
+ return 'Harness Kit 红线:禁止破坏性 git 操作(reset --hard / clean -f / push --force)。';
42
+ }
43
+
44
+ const agent = execution.agent;
45
+ if (!agent) return undefined;
46
+ let ws;
47
+ try {
48
+ ws = wsRoot(agent);
49
+ } catch {
50
+ return undefined; // no workspace context → not our call
51
+ }
52
+ let kit;
53
+ try {
54
+ kit = readKit(ws);
55
+ } catch (cause) {
56
+ logger?.warn?.('harness-kit guard: kit.json 读取失败,跳过红线检查: %o', cause);
57
+ return undefined;
58
+ }
59
+ if (!kit) return undefined;
60
+ const locked = lockedSourcePaths(ws, kit);
61
+ if (locked.length === 0) return undefined;
62
+
63
+ if ((name === 'edit' || name === 'write') && typeof args.file_path === 'string') {
64
+ const abs = normalizeTarget(ws, args.file_path);
65
+ const hit = abs && pathHits(abs, ws, locked);
66
+ if (hit) {
67
+ return `Harness Bootstrap 红线:规划阶段(质量门未裁决)禁止修改源码区 ${hit}。请先完成 bugfix.md 并交人裁决质量门。`;
68
+ }
69
+ }
70
+ if (name === 'bash' && typeof args.command === 'string') {
71
+ const hit = bashHitsProtected(args.command, locked);
72
+ if (hit) {
73
+ return `Harness Bootstrap 红线:规划阶段(质量门未裁决)禁止通过 shell 写源码区 ${hit}。请先完成规划文档并交人裁决质量门。`;
74
+ }
75
+ }
76
+ return undefined;
77
+ });
78
+ return dispose;
79
+ }
@@ -0,0 +1,133 @@
1
+ // Minimal YAML subset parser/dumper for flow definitions.
2
+ // Supported: nested maps by 2-space indent, `- item` and `- key: value` lists,
3
+ // scalars (string/number/boolean/null), `#` comments, single- and
4
+ // double-quoted strings. Anything else (anchors, flow style, block scalars)
5
+ // throws — flow files authored for the kernel stay inside this subset.
6
+
7
+ class YamlSubsetError extends Error {}
8
+
9
+ function scalar(raw) {
10
+ const s = raw.trim();
11
+ if (s === '' || s === '~' || s === 'null') return null;
12
+ if (s === 'true') return true;
13
+ if (s === 'false') return false;
14
+ if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
15
+ if (s.startsWith('"') && s.endsWith('"')) return s.slice(1, -1).replace(/\\(["\\n])/g, (_, c) => (c === 'n' ? '\n' : c));
16
+ if (s.startsWith("'") && s.endsWith("'")) return s.slice(1, -1).replace(/''/g, "'");
17
+ return s;
18
+ }
19
+
20
+ function tokenize(text) {
21
+ const lines = [];
22
+ for (const rawLine of text.split(/\r?\n/)) {
23
+ const noComment = rawLine.replace(/(^|\s)#.*$/, '');
24
+ if (noComment.trim() === '') continue;
25
+ const indent = /^ */.exec(noComment)[0].length;
26
+ if (indent % 2 !== 0) throw new YamlSubsetError(`奇数缩进不受支持: ${rawLine}`);
27
+ lines.push({ indent, text: noComment.trim() });
28
+ }
29
+ return lines;
30
+ }
31
+
32
+ export function parseYaml(text) {
33
+ const lines = tokenize(text);
34
+ let pos = 0;
35
+
36
+ function parseBlock(indent) {
37
+ if (pos >= lines.length) return null;
38
+ if (lines[pos].indent !== indent) throw new YamlSubsetError(`缩进错位(期望 ${indent}): ${lines[pos].text}`);
39
+ const isList = lines[pos].text.startsWith('- ') || lines[pos].text === '-';
40
+ return isList ? parseList(indent) : parseMap(indent);
41
+ }
42
+
43
+ function parseMap(indent) {
44
+ const out = {};
45
+ while (pos < lines.length && lines[pos].indent === indent && !lines[pos].text.startsWith('-')) {
46
+ const m = /^([A-Za-z0-9_][A-Za-z0-9_.-]*):(?:\s+(.*))?$/.exec(lines[pos].text);
47
+ if (!m) throw new YamlSubsetError(`无法解析的行: ${lines[pos].text}`);
48
+ const [, key, rest] = m;
49
+ pos += 1;
50
+ if (rest !== undefined && rest !== '') {
51
+ out[key] = scalar(rest);
52
+ } else if (pos < lines.length && lines[pos].indent > indent) {
53
+ out[key] = parseBlock(lines[pos].indent);
54
+ } else {
55
+ out[key] = null;
56
+ }
57
+ }
58
+ return out;
59
+ }
60
+
61
+ function parseList(indent) {
62
+ const out = [];
63
+ while (pos < lines.length && lines[pos].indent === indent && (lines[pos].text.startsWith('- ') || lines[pos].text === '-')) {
64
+ const itemText = lines[pos].text === '-' ? '' : lines[pos].text.slice(2);
65
+ const m = /^([A-Za-z0-9_][A-Za-z0-9_.-]*):(?:\s+(.*))?$/.exec(itemText);
66
+ if (m) {
67
+ // List item opening a map; subsequent keys indent past the dash.
68
+ const itemIndent = indent + 2;
69
+ const obj = {};
70
+ const [, key, rest] = m;
71
+ pos += 1;
72
+ obj[key] = rest !== undefined && rest !== '' ? scalar(rest) : pos < lines.length && lines[pos].indent > itemIndent - 2 ? parseBlock(lines[pos].indent) : null;
73
+ while (pos < lines.length && lines[pos].indent === itemIndent && !lines[pos].text.startsWith('-')) {
74
+ const km = /^([A-Za-z0-9_][A-Za-z0-9_.-]*):(?:\s+(.*))?$/.exec(lines[pos].text);
75
+ if (!km) throw new YamlSubsetError(`无法解析的行: ${lines[pos].text}`);
76
+ const [, k2, r2] = km;
77
+ pos += 1;
78
+ obj[k2] = r2 !== undefined && r2 !== '' ? scalar(r2) : pos < lines.length && lines[pos].indent > itemIndent ? parseBlock(lines[pos].indent) : null;
79
+ }
80
+ out.push(obj);
81
+ } else {
82
+ out.push(scalar(itemText));
83
+ pos += 1;
84
+ }
85
+ }
86
+ return out;
87
+ }
88
+
89
+ const result = lines.length === 0 ? null : parseBlock(lines[0].indent);
90
+ if (pos < lines.length) throw new YamlSubsetError(`解析在以下行处停滞: ${lines[pos].text}`);
91
+ return result;
92
+ }
93
+
94
+ function dumpValue(value, indent) {
95
+ const pad = ' '.repeat(indent);
96
+ if (value === null || value === undefined) return 'null';
97
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
98
+ if (typeof value === 'string') {
99
+ return /[:#\n]|^[\s"'-]|^\s*$|^(true|false|null|~)$|^-?\d/.test(value) ? JSON.stringify(value) : value;
100
+ }
101
+ if (Array.isArray(value)) {
102
+ if (value.length === 0) return '[]';
103
+ return value
104
+ .map((item) => {
105
+ if (typeof item === 'object' && item !== null && !Array.isArray(item)) {
106
+ const entries = Object.entries(item);
107
+ if (entries.length === 0) return `${pad}- {}`;
108
+ const [k0, v0] = entries[0];
109
+ const head = typeof v0 === 'object' && v0 !== null && Object.keys(v0).length > 0
110
+ ? `${pad}- ${k0}:\n${dumpValue(v0, indent + 4)}`
111
+ : `${pad}- ${k0}: ${dumpValue(v0, 0)}`;
112
+ const rest = dumpValue(Object.fromEntries(entries.slice(1)), indent + 2);
113
+ return entries.length > 1 ? `${head}\n${rest}` : head;
114
+ }
115
+ return `${pad}- ${dumpValue(item, 0)}`;
116
+ })
117
+ .join('\n');
118
+ }
119
+ const entries = Object.entries(value);
120
+ if (entries.length === 0) return '{}';
121
+ return entries
122
+ .map(([k, v]) => {
123
+ if (typeof v === 'object' && v !== null && !(Array.isArray(v) && v.length === 0) && Object.keys(v).length > 0) {
124
+ return `${pad}${k}:\n${dumpValue(v, indent + 2)}`;
125
+ }
126
+ return `${pad}${k}: ${dumpValue(v, 0)}`;
127
+ })
128
+ .join('\n');
129
+ }
130
+
131
+ export function dumpYaml(value) {
132
+ return dumpValue(value, 0) + '\n';
133
+ }
@@ -0,0 +1,104 @@
1
+ // Model routing: content packs name logical models (reasoning/coding/fast) in
2
+ // role frontmatter and flow stages; kit.json `models` maps them to concrete
3
+ // provider/model. Missing mapping degrades to the session default model.
4
+ // Availability is validated by the Lead at dispatch time (list_subagent_models),
5
+ // so this module only resolves the mapping deterministically.
6
+
7
+ /** Resolve a logical model name to { provider?, model, reasoning_effort? } or null. */
8
+ export function resolveModel(kit, logical) {
9
+ if (!logical || typeof logical !== 'string') return null;
10
+ const entry = kit?.models?.[logical];
11
+ if (!entry || typeof entry !== 'object' || !entry.model) return null;
12
+ return {
13
+ ...(entry.provider ? { provider: entry.provider } : {}),
14
+ model: entry.model,
15
+ ...(entry.reasoning_effort ? { reasoning_effort: entry.reasoning_effort } : {}),
16
+ };
17
+ }
18
+
19
+ /** Human-readable dispatch description for prompts/status output. */
20
+ export function describeModel(kit, logical) {
21
+ if (!logical) return '会话默认(角色未声明逻辑模型)';
22
+ const r = resolveModel(kit, logical);
23
+ if (!r) return `${logical}(kit.json models 未映射 → 会话默认)`;
24
+ const eff = r.reasoning_effort ? `, reasoning_effort=${r.reasoning_effort}` : '';
25
+ return `${logical} → provider=${r.provider ?? '(会话默认 provider)'}, model=${r.model}${eff}`;
26
+ }
27
+
28
+ /**
29
+ * 角色级模型映射:kit.json models 允许用「角色名」(business-analyst 等)做键,
30
+ * 优先级高于逻辑模型名(fast/coding/reasoning)。返回 {entry, via}:
31
+ * via='role' 命中角色映射;via='logical' 命中逻辑名映射;null 都未映射。
32
+ */
33
+ export function resolveWorkerModel(kit, role, logical) {
34
+ const byRole = resolveModel(kit, role);
35
+ if (byRole) return { entry: byRole, via: 'role' };
36
+ const byLogical = resolveModel(kit, logical);
37
+ if (byLogical) return { entry: byLogical, via: 'logical' };
38
+ return null;
39
+ }
40
+
41
+ /**
42
+ * 从 kit.json models 映射收集子智能体路由授权(去重)。
43
+ * DSH 默认子模型限父会话当前模型且宿主无 GUI 开关(subagentModelSelection 出厂关)——
44
+ * HarnessKit 按工作区映射自动授权:映射了的路由就是人想用的(2026-11-16 iot-harness RR 降级事故)。
45
+ */
46
+ export function collectModelRoutes(kit) {
47
+ const seen = new Map();
48
+ for (const m of Object.values(kit?.models ?? {})) {
49
+ if (m && typeof m.provider === 'string' && m.provider && typeof m.model === 'string' && m.model) {
50
+ seen.set(`${m.provider}/${m.model}`, { provider: m.provider, model: m.model });
51
+ }
52
+ }
53
+ return [...seen.values()];
54
+ }
55
+
56
+ /** 派发描述:角色级优先,标注命中来源,便于人核对为什么用了这个模型。 */
57
+ export function describeWorkerModel(kit, role, logical) {
58
+ const r = resolveWorkerModel(kit, role, logical);
59
+ if (!r) {
60
+ if (!logical) return '会话默认(角色未声明逻辑模型)';
61
+ return `${logical}(kit.json models 未映射 → 会话默认)`;
62
+ }
63
+ const { provider, model, reasoning_effort } = r.entry;
64
+ const via = r.via === 'role' ? `角色映射 ${role}` : `逻辑模型 ${logical}`;
65
+ // subagent 工具要求 provider/model 必须成对(缺一即报错);映射缺 provider 时无法成对传递,
66
+ // 视为会话默认派发——不显式传任何模型参数(2026-11-16 iot-harness 真实踩坑:PM 只传 model 触发校验报错)
67
+ if (!provider) {
68
+ return `${via} 只配了 model 未配 provider:无法成对传递,按会话默认派发(不传任何模型参数)`;
69
+ }
70
+ const eff = reasoning_effort ? `, reasoning_effort=${reasoning_effort}` : '';
71
+ return `${via} → provider=${provider}, model=${model}${eff}`;
72
+ }
73
+
74
+ /**
75
+ * Render the "## 派发方式" appendix with per-worker model routing.
76
+ * workers: [{ role, logical }] — logical from role frontmatter / stage override.
77
+ */
78
+ export function dispatchSection(kit, workers) {
79
+ const lines = [
80
+ '## 派发方式',
81
+ '- 你自己承担 PM 职责:拆解、派发、汇总、向人汇报。',
82
+ '- Worker/subagent 一律用 subagent 工具派发:prompt 自包含(任务背景 + 产出路径 + 写范围约束;阶段指定 Worker 角色时另需先读角色文件并内嵌定义全文),等待其返回结果后再进下一阶段。',
83
+ '- Worker 产物写入活目录对应文件;Worker 只能写其 write_scopes 声明的范围。',
84
+ '- 任何时候信息不足或口径模糊:先向人反问,不要自行补全。',
85
+ '',
86
+ '### 模型路由(派发时必须执行)',
87
+ '- kit.json models 支持两级键:角色名(business-analyst 等)优先,其次逻辑模型名(fast/coding/reasoning);下方每行已标注命中来源。',
88
+ ];
89
+ if (workers.length === 0) {
90
+ lines.push('- 本流程无 Worker 阶段,全部 PM 自行执行。');
91
+ } else {
92
+ for (const w of workers) {
93
+ lines.push(`- **${w.role}** → ${describeWorkerModel(kit, w.role, w.logical)}`);
94
+ }
95
+ }
96
+ lines.push(
97
+ '- 派发带模型的 Worker 前,先用 list_subagent_models 校验 provider/model 可用;',
98
+ ' 可用 → subagent 调用传 provider/model(及 reasoning_effort,如有):**provider 与 model 必须成对,缺一即报错**;',
99
+ ' 不可用或报错 → **不带 provider/model 任何参数**重新派发(= 会话默认),并在汇报中告知人「模型映射失效,已降级」;',
100
+ '- 未映射的逻辑模型、或映射缺 provider(无法成对)→ 直接按会话默认派发,不必校验、不传任何模型参数。',
101
+ '- 可用性是会话级作用域:子模型路由默认限父会话当前模型;其他 provider 需人在 DSH 会话的模型选择里显式授权子智能体路由。',
102
+ );
103
+ return lines.join('\n');
104
+ }