dsh-harness-kit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +321 -2
  3. package/README.zh-CN.md +278 -0
  4. package/client.js +1272 -0
  5. package/cordis.patch.yml +4 -0
  6. package/docs/DETAIL.en.md +97 -0
  7. package/docs/DETAIL.md +73 -0
  8. package/docs/assets/ui-new-task.png +0 -0
  9. package/docs/assets/ui-onboarding.png +0 -0
  10. package/docs/assets/ui-war-room.png +0 -0
  11. package/icon.svg +7 -0
  12. package/index.js +49 -0
  13. package/kernel/advance.js +96 -0
  14. package/kernel/bindings.js +24 -0
  15. package/kernel/commands.js +927 -0
  16. package/kernel/env.js +64 -0
  17. package/kernel/exec.js +41 -0
  18. package/kernel/flows.js +89 -0
  19. package/kernel/guards.js +79 -0
  20. package/kernel/miniyaml.js +133 -0
  21. package/kernel/models.js +104 -0
  22. package/kernel/panel.js +1103 -0
  23. package/kernel/paths.js +53 -0
  24. package/kernel/roles.js +67 -0
  25. package/kernel/setup.js +644 -0
  26. package/kernel/state.js +59 -0
  27. package/kernel/steer.js +27 -0
  28. package/kernel/sync.js +140 -0
  29. package/kernel/te.js +122 -0
  30. package/kernel/worktree.js +868 -0
  31. package/locale/en.json +14 -0
  32. package/locale/zh.json +14 -0
  33. package/package.json +63 -4
  34. package/packs/ai-coding/agents/business-analyst.md +90 -0
  35. package/packs/ai-coding/agents/code-reviewer.md +156 -0
  36. package/packs/ai-coding/agents/developer.md +147 -0
  37. package/packs/ai-coding/agents/project-manager.md +190 -0
  38. package/packs/ai-coding/agents/readiness-reviewer.md +123 -0
  39. package/packs/ai-coding/agents/solution-architect.md +122 -0
  40. package/packs/ai-coding/agents/test-engineer.md +230 -0
  41. package/packs/ai-coding/assets/scripts/check_codegraph.py +215 -0
  42. package/packs/ai-coding/assets/scripts/codebase_guide_init.py +330 -0
  43. package/packs/ai-coding/assets/scripts/env_auto.py +612 -0
  44. package/packs/ai-coding/assets/scripts/harness.py +38 -0
  45. package/packs/ai-coding/assets/scripts/harness_init.py +193 -0
  46. package/packs/ai-coding/assets/scripts/lib.py +1011 -0
  47. package/packs/ai-coding/assets/scripts/run_field.py +295 -0
  48. package/packs/ai-coding/assets/scripts/spec_lint.py +247 -0
  49. package/packs/ai-coding/assets/scripts/update_board.py +524 -0
  50. package/packs/ai-coding/assets/scripts/verify.py +184 -0
  51. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/CODE_STANDARDS.tmpl +44 -0
  52. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/app-CLAUDE.tmpl +34 -0
  53. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/build.tmpl +8 -0
  54. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/module-CLAUDE.tmpl +42 -0
  55. package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/root-CLAUDE.tmpl +41 -0
  56. package/packs/ai-coding/assets/templates/java/maven/CODE_STANDARDS.tmpl +44 -0
  57. package/packs/ai-coding/assets/templates/java/maven/build.tmpl +9 -0
  58. package/packs/ai-coding/assets/templates/java/maven/root-CLAUDE.tmpl +38 -0
  59. package/packs/ai-coding/assets/templates/java/maven-multimodule/CODE_STANDARDS.tmpl +44 -0
  60. package/packs/ai-coding/assets/templates/java/maven-multimodule/build.tmpl +9 -0
  61. package/packs/ai-coding/assets/templates/java/maven-multimodule/module-CLAUDE.tmpl +40 -0
  62. package/packs/ai-coding/assets/templates/java/maven-multimodule/root-CLAUDE.tmpl +38 -0
  63. package/packs/ai-coding/assets/templates/javascript/mobile-app/CODE_STANDARDS.tmpl +51 -0
  64. package/packs/ai-coding/assets/templates/javascript/mobile-app/build.tmpl +8 -0
  65. package/packs/ai-coding/assets/templates/javascript/mobile-app/root-CLAUDE.tmpl +36 -0
  66. package/packs/ai-coding/assets/templates/javascript/uniapp/CODE_STANDARDS.tmpl +69 -0
  67. package/packs/ai-coding/assets/templates/javascript/uniapp/build.tmpl +8 -0
  68. package/packs/ai-coding/assets/templates/javascript/uniapp/root-CLAUDE.tmpl +56 -0
  69. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/CODE_STANDARDS.tmpl +51 -0
  70. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/app-CLAUDE.tmpl +36 -0
  71. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/build.tmpl +8 -0
  72. package/packs/ai-coding/assets/templates/javascript/vue-multimodule/root-CLAUDE.tmpl +34 -0
  73. package/packs/ai-coding/flows/_router.yml +14 -0
  74. package/packs/ai-coding/flows/bugfix.yml +37 -0
  75. package/packs/ai-coding/flows/fix.yml +44 -0
  76. package/packs/ai-coding/flows/init.yml +83 -0
  77. package/packs/ai-coding/flows/new.yml +29 -0
  78. package/packs/ai-coding/flows/quick.yml +40 -0
  79. package/packs/ai-coding/flows/refactor.yml +50 -0
  80. package/packs/ai-coding/flows/standard.yml +49 -0
  81. package/packs/ai-coding/rules/code-standards.md +30 -0
  82. package/packs/ai-coding/rules/core.md +83 -0
  83. package/packs/ai-coding/templates/bugfix.md +29 -0
  84. package/packs/ai-coding/templates/memory-entry.md +46 -0
  85. package/packs/ai-coding/templates/proposal.md +47 -0
  86. package/packs/ai-coding/templates/spec-template.md +34 -0
  87. package/screenshots.json +5 -0
@@ -0,0 +1,59 @@
1
+ // Task/gate state derived from the workspace: the guard reads these facts
2
+ // instead of a session state machine, so reloads and forks stay consistent.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { harnessDir, protectedSourcePaths } from './paths.js';
6
+
7
+ // NOTE: no \b — CJK chars are non-word in JS regex, so \b after 轻量 never matches.
8
+ // Tolerates markdown bold between 裁决 and colon: "**人裁决**:`轻量`" (legacy format).
9
+ // Horizontal whitespace only — a colon at line end must not match a keyword on the next line.
10
+ const VERDICT = /裁决[**]*[::][ \t]*`?(轻量|light|--full|full)(?![\w-])/i;
11
+ // Full-flow unlock: human approval 1 recorded by PM at the end of proposal.md
12
+ // (see flows/*.yml 审批 1 stage). "审批 1:通过" / "审批1: PASS" both match.
13
+ const APPROVAL1 = /审批\s*1[^0-9\n]{0,20}(通过|PASS)/i;
14
+ // M2: fix直通 unlocks on bugfix.md quality-gate verdict; full flow (any task
15
+ // with proposal.md, including profile=bugfix) unlocks on recorded approval 1.
16
+ // A full-flow bugfix.md (BA-written, "## 结论" PASS) has no verdict line, so
17
+ // the two docs must not be checked interchangeably.
18
+ const VERDICT_DOC = { file: 'bugfix.md', unlock: VERDICT };
19
+ const PROPOSAL_DOC = { file: 'proposal.md', unlock: APPROVAL1 };
20
+
21
+ /** Active task dirs under .harness/deliverables (excluding _archive, _template, dotfiles). */
22
+ export function activeTasks(ws) {
23
+ const dir = path.join(harnessDir(ws), 'deliverables');
24
+ if (!fs.existsSync(dir)) return [];
25
+ return fs
26
+ .readdirSync(dir, { withFileTypes: true })
27
+ .filter((e) => e.isDirectory() && !e.name.startsWith('_') && !e.name.startsWith('.'))
28
+ .map((e) => e.name);
29
+ }
30
+
31
+ /**
32
+ * A task is "planning" while its planning doc exists without the recorded
33
+ * human gate. Full flow (proposal.md present) → approval 1; fix直通 → verdict.
34
+ * proposal.md takes precedence: a full-flow bugfix profile writes both docs,
35
+ * and only the proposal approval gate applies.
36
+ */
37
+ export function taskIsPlanning(ws, task) {
38
+ const dir = path.join(harnessDir(ws), 'deliverables', task);
39
+ const hasProposal = fs.existsSync(path.join(dir, PROPOSAL_DOC.file));
40
+ const doc = hasProposal ? PROPOSAL_DOC : VERDICT_DOC;
41
+ const file = path.join(dir, doc.file);
42
+ if (!fs.existsSync(file)) return false;
43
+ let text = '';
44
+ try {
45
+ text = fs.readFileSync(file, 'utf8');
46
+ } catch {
47
+ return true; // unreadable planning doc → stay locked
48
+ }
49
+ return !doc.unlock.test(text);
50
+ }
51
+
52
+ /**
53
+ * Source paths currently locked by the Bootstrap red line: non-empty while
54
+ * any active task is still in planning (no recorded human gate).
55
+ */
56
+ export function lockedSourcePaths(ws, kit) {
57
+ const planning = activeTasks(ws).filter((t) => taskIsPlanning(ws, t));
58
+ return planning.length > 0 ? protectedSourcePaths(kit) : [];
59
+ }
@@ -0,0 +1,27 @@
1
+ // Build a user-role message and submit it to the receiving agent.
2
+ // Mirrors @deepseek-ai/dsh-llm createUserMessage() at runtime
3
+ // ({ id, role, content, source }, deep-frozen; brands are compile-time only),
4
+ // so the bundle needs no imports from shipped dsh packages.
5
+ import { randomUUID } from 'node:crypto';
6
+
7
+ function deepFreeze(value) {
8
+ if (value !== null && typeof value === 'object') {
9
+ for (const key of Object.keys(value)) deepFreeze(value[key]);
10
+ Object.freeze(value);
11
+ }
12
+ return value;
13
+ }
14
+
15
+ export function userText(text, source = { kind: 'user' }) {
16
+ return deepFreeze({
17
+ id: randomUUID(),
18
+ role: 'user',
19
+ content: [{ type: 'text', text }],
20
+ source,
21
+ });
22
+ }
23
+
24
+ /** Submit a model-visible user message to the agent (plan-mode precedent). */
25
+ export function steer(agent, text) {
26
+ agent.steer(userText(text));
27
+ }
package/kernel/sync.js ADDED
@@ -0,0 +1,140 @@
1
+ // /hk-sync:资产仓库 git 同步 —— 自动提交本地变更 → pull --rebase →
2
+ // 纯追加文件三路自动合并 → push。非纯追加冲突中止 rebase 回滚、转人工。
3
+ // 说明:git 由插件 handler 直接 spawn(不经 bash 工具审批链),/hk-sync 本身是
4
+ // 显式用户命令即授权;归档后自动触发需 kit.json assets.autoSync=true 显式开启,
5
+ // 且所有 git 操作与结果都写入命令返回文本。
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { runGit } from './exec.js';
9
+
10
+ const APPEND_ONLY_FILES = new Set(['memory/index.md', 'specs/_index.md', 'tasks/board.md', 'tasks/claims.json']);
11
+ const APPEND_ONLY_RE = /^deliverables\/_archive\/[^/]+\/rounds\.md$/;
12
+
13
+ export function isAppendOnly(rel) {
14
+ return APPEND_ONLY_FILES.has(rel) || APPEND_ONLY_RE.test(rel);
15
+ }
16
+
17
+ const ok = (text) => ({ kind: 'success', text });
18
+ const fail = (text) => ({ kind: 'error', text });
19
+
20
+ /**
21
+ * 资产布局探测(.harness 的 git 归属):
22
+ * - 'repo' :.harness 自带 .git(独立资产仓库,/hk-sync 作用对象)
23
+ * - 'embedded' :.harness 无独立 .git,但被工作区某级父 git 仓库跟踪(随根仓库共享,
24
+ * 同步走根仓库的 commit/push,/hk-sync 不适用)
25
+ * - 'plain' :纯本地,无任何 git 管理
26
+ * @returns {Promise<{layout:'repo'|'embedded'|'plain', repoRoot?:string, rel?:string}>}
27
+ * repoRoot = 跟踪 .harness 的仓库根;rel = .harness 相对该根的路径(多为 '.harness')
28
+ */
29
+ export async function assetsLayout(ws) {
30
+ const hd = path.join(ws, '.harness');
31
+ if (fs.existsSync(path.join(hd, '.git'))) return { layout: 'repo' };
32
+ if (!fs.existsSync(hd)) return { layout: 'plain' };
33
+ const top = await runGit(['rev-parse', '--show-toplevel'], { cwd: hd, timeoutMs: 15_000 });
34
+ if (top.code !== 0 || !top.stdout.trim()) return { layout: 'plain' };
35
+ // macOS /var→/private/var 等符号链接:git 返回 realpath,两侧统一后再求相对路径
36
+ const repoRoot = fs.realpathSync(top.stdout.trim());
37
+ const rel = path.relative(repoRoot, fs.realpathSync(hd));
38
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) return { layout: 'plain' };
39
+ // 物理嵌套不等于被跟踪:父仓库必须真的管理 .harness 下的文件
40
+ const tracked = await runGit(['ls-files', '--', rel], { cwd: repoRoot, timeoutMs: 15_000 });
41
+ if (tracked.code !== 0 || !tracked.stdout.trim()) return { layout: 'plain' };
42
+ return { layout: 'embedded', repoRoot, rel };
43
+ }
44
+
45
+ export async function syncAssets(ws, kit) {
46
+ const hd = path.join(ws, '.harness');
47
+ const g = (args) => runGit(args, { cwd: hd, timeoutMs: 300_000 });
48
+
49
+ if (!fs.existsSync(path.join(hd, '.git'))) {
50
+ const lay = await assetsLayout(ws);
51
+ if (lay.layout === 'embedded') {
52
+ return fail(
53
+ `资产目录 \`.harness/\` 无独立 git,已随工作区根仓库(\`${lay.repoRoot}\`)管理:资产变更直接在根仓库 commit/push 即共享,\`/hk-sync\` 不适用。` +
54
+ '如需拆分为独立资产仓库:建空远端后 `cd .harness && git init && git remote add origin <url>`,重跑 `/hk-init` 自动接管首推,再把根仓库里的 `.harness/` 移出跟踪(`git rm -r --cached .harness` + .gitignore)。',
55
+ );
56
+ }
57
+ return fail(
58
+ '资产目录 `.harness/` 未绑定 git(当前为本地模式)。绑定方式:新工作区用 `/hk-init --assets <url|init>`;' +
59
+ '既有目录可手工 `cd .harness && git init && git remote add origin <url>` 后重跑 `/hk-init` 自动回填 kit.json,再执行 `/hk-sync`。',
60
+ );
61
+ }
62
+ const remotes = (await g(['remote'])).stdout
63
+ .split('\n')
64
+ .map((s) => s.trim())
65
+ .filter(Boolean);
66
+ if (remotes.length === 0) {
67
+ return fail('资产仓库尚无远端:`cd .harness && git remote add origin <团队资产仓库 URL>` 后重试 `/hk-sync`。');
68
+ }
69
+ const remote = remotes.includes('origin') ? 'origin' : remotes[0];
70
+ const branch = kit?.assets?.branch || (await g(['branch', '--show-current'])).stdout.trim() || 'master';
71
+
72
+ const steps = [];
73
+
74
+ // 1. 自动提交本地变更(资产仓库为 harness 专有,提交信息显式标注)
75
+ if ((await g(['status', '--porcelain'])).stdout.trim()) {
76
+ await g(['add', '-A']);
77
+ const msg = `harness: sync ${new Date().toISOString().slice(0, 16).replace('T', ' ')}`;
78
+ const c = await g(['commit', '-m', msg]);
79
+ if (c.code !== 0) return fail(`自动提交失败:\n${c.stderr || c.stdout}`);
80
+ steps.push(`自动提交本地变更(\`${msg}\`)`);
81
+ }
82
+
83
+ // 2. pull --rebase
84
+ const pull = await g(['pull', '--rebase', remote, branch]);
85
+ if (pull.code !== 0) {
86
+ const out = pull.stderr || pull.stdout;
87
+ if (/couldn't find remote ref|does not appear to be/i.test(out)) {
88
+ steps.push(`远端暂无 \`${branch}\` 分支(首次同步)`);
89
+ } else {
90
+ const conflicts = (await g(['diff', '--name-only', '--diff-filter=U'])).stdout
91
+ .trim()
92
+ .split('\n')
93
+ .filter(Boolean);
94
+ if (conflicts.length > 0 && conflicts.every(isAppendOnly)) {
95
+ // 纯追加自动三路合并:ours = base+A、theirs = base+B ⇒ base+A+B
96
+ const merged = [];
97
+ for (const f of conflicts) {
98
+ const base = (await g(['show', `:1:${f}`])).stdout;
99
+ const ours = (await g(['show', `:2:${f}`])).stdout;
100
+ const theirs = (await g(['show', `:3:${f}`])).stdout;
101
+ if (!ours.startsWith(base) || !theirs.startsWith(base)) {
102
+ await g(['rebase', '--abort']);
103
+ return fail(
104
+ `\`${f}\` 虽在纯追加白名单,但实际改动含改写/删除(非 base 前缀追加),已中止 rebase 回滚到同步前状态,请人工处理:\`cd .harness && git pull --rebase ${remote} ${branch}\``,
105
+ );
106
+ }
107
+ fs.writeFileSync(path.join(hd, f), ours + theirs.slice(base.length), 'utf8');
108
+ await g(['add', f]);
109
+ merged.push(f);
110
+ }
111
+ const cont = await g(['-c', 'core.editor=true', 'rebase', '--continue']);
112
+ if (cont.code !== 0) {
113
+ await g(['rebase', '--abort']);
114
+ return fail(`自动合并后 \`rebase --continue\` 失败,已回滚到同步前状态:\n${cont.stderr || cont.stdout}`);
115
+ }
116
+ steps.push(`纯追加冲突自动三路合并:${merged.map((f) => `\`${f}\``).join('、')}`);
117
+ } else if (conflicts.length > 0) {
118
+ await g(['rebase', '--abort']);
119
+ return fail(
120
+ `以下文件冲突,超出纯追加自动合并范围,已中止 rebase 回滚到同步前状态,转人工处理:\n${conflicts.map((f) => `- \`${f}\``).join('\n')}\n\n手工步骤:\`cd .harness && git pull --rebase ${remote} ${branch}\`,解冲突后 \`git rebase --continue && git push ${remote} ${branch}\`,或修复后重跑 \`/hk-sync\`。`,
121
+ );
122
+ } else {
123
+ return fail(`git pull --rebase 失败(无冲突标记,疑似网络/认证问题):\n${out}`);
124
+ }
125
+ }
126
+ } else {
127
+ steps.push(/already up[ -]to[ -]date/i.test(pull.stdout + pull.stderr) ? '远端无新提交' : '已 rebase 远端新提交');
128
+ }
129
+
130
+ // 3. push
131
+ const push = await g(['push', remote, `HEAD:${branch}`]);
132
+ if (push.code !== 0) {
133
+ return fail(
134
+ `push 失败(本地 rebase 结果已保留,未丢失;请检查权限/远端后重试 \`/hk-sync\`):\n${push.stderr || push.stdout}`,
135
+ );
136
+ }
137
+ steps.push('已 push 到远端');
138
+
139
+ return ok(`资产同步完成(\`${remote}/${branch}\`):\n${steps.map((s) => `- ${s}`).join('\n')}`);
140
+ }
package/kernel/te.js ADDED
@@ -0,0 +1,122 @@
1
+ // TE 环境串行排队(M3 一期,2026-11-15 定):测试环境全局只有一个
2
+ // (起服务/连 TDengine/jmeter 不可多任务并发),TE 阶段按租约串行:
3
+ //
4
+ // - 租约台账 .harness/tasks/test-env.json(本机状态,不进资产 git):
5
+ // { "holder": "task-x", "since": "ISO", "queue": ["task-y"] }
6
+ // - PM 派发 TE Worker 前必须先 `/hk-te acquire <任务>`:
7
+ // 空闲 → 授权;自己持有 → 已持有;别人持有 → 排队并暂停 TE 阶段(内核不可抢占运行中的 Worker,门在派发前)
8
+ // - 释放:holder 的看板链 TE 标 ✅/—(或任务归档/消失)→ 轮询器自动释放并晋升队列头部,
9
+ // 向该任务绑定的会话注入「轮到你了」;排队任务自己越过 TE 阶段 → 自动出队
10
+ // - grace:holder 已授权但看板链还没标 TE▶(PM 先 acquire 后写板的时序窗口)不释放
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { harnessDir } from './paths.js';
14
+ import { keepLedgerLocal } from './worktree.js';
15
+
16
+ const envPath = (ws) => path.join(harnessDir(ws), 'tasks', 'test-env.json');
17
+
18
+ export function readTestEnv(ws) {
19
+ try {
20
+ const data = JSON.parse(fs.readFileSync(envPath(ws), 'utf8'));
21
+ return {
22
+ holder: typeof data?.holder === 'string' ? data.holder : null,
23
+ since: data?.since ?? null,
24
+ queue: Array.isArray(data?.queue) ? data.queue.filter((t) => typeof t === 'string') : [],
25
+ };
26
+ } catch { return { holder: null, since: null, queue: [] }; }
27
+ }
28
+
29
+ function writeTestEnv(ws, env) {
30
+ fs.mkdirSync(path.dirname(envPath(ws)), { recursive: true });
31
+ fs.writeFileSync(envPath(ws), `${JSON.stringify(env, null, 2)}\n`, 'utf8');
32
+ keepLedgerLocal(ws, 'tasks/test-env.json');
33
+ }
34
+
35
+ /** 看板链中 TE 阶段的标记(✅ 完成 / — 跳过 → 不再需要环境;▶/…/⛔/缺 → 仍可能需要)。 */
36
+ function teMark(applyText) {
37
+ if (!applyText) return null;
38
+ const m = applyText.match(/TE\s*(✅|▶|…|⛔|—)/);
39
+ return m ? m[1] : null;
40
+ }
41
+
42
+ /** 任务是否需要 TE 环境(链上 TE 未✅/未— 即视为需要,含 PM 先 acquire 后写板的宽限)。 */
43
+ function needsTe(applyText) {
44
+ const mark = teMark(applyText);
45
+ return mark !== '✅' && mark !== '—';
46
+ }
47
+
48
+ /**
49
+ * 对账(轮询器每 7s 调用,也可命令内调用):
50
+ * - holder 的任务已越过 TE(✅/—)、已归档/不在看板 → 释放
51
+ * - queue 里已越过 TE 或已不在看板的任务 → 出队
52
+ * - 空闲且有排队 → 晋升队首
53
+ * 返回 { released, promoted, env }。
54
+ */
55
+ export function reconcileTestEnv(ws, boardRows) {
56
+ const env = readTestEnv(ws);
57
+ const released = [];
58
+ const rowOf = (t) => (boardRows ?? []).find((r) => r.task === t);
59
+ const active = (t) => {
60
+ const row = rowOf(t);
61
+ return !!row && row.status !== 'DONE' && row.status !== 'AWAITING_ARCHIVE' && needsTe(row.apply);
62
+ };
63
+ if (env.holder && !active(env.holder)) {
64
+ released.push(env.holder);
65
+ env.holder = null;
66
+ env.since = null;
67
+ }
68
+ env.queue = env.queue.filter((t) => t !== env.holder && active(t));
69
+ let promoted = null;
70
+ if (!env.holder && env.queue.length > 0) {
71
+ promoted = env.queue.shift();
72
+ env.holder = promoted;
73
+ env.since = new Date().toISOString();
74
+ }
75
+ writeTestEnv(ws, env);
76
+ return { released, promoted, env };
77
+ }
78
+
79
+ /**
80
+ * 获取租约:空闲 → 授权;自持 → 提示已持有;他持 → 入队(去重)并返回排队位次。
81
+ * 返回 { granted, queued, position, holder, text }。
82
+ */
83
+ export function acquireTestEnv(ws, task) {
84
+ const env = readTestEnv(ws);
85
+ if (env.holder === task) {
86
+ return { granted: true, queued: false, position: 0, holder: task, text: `TE 环境已由本任务持有(${task}),继续 TE 阶段` };
87
+ }
88
+ if (env.holder) {
89
+ if (!env.queue.includes(task)) env.queue.push(task);
90
+ writeTestEnv(ws, env);
91
+ return {
92
+ granted: false, queued: true, position: env.queue.length, holder: env.holder,
93
+ text: `TE 环境被 **${env.holder}** 占用:本任务已排队(第 ${env.queue.length} 位)。暂停 TE 阶段、不要派发 TE Worker、不要起服务/连测试库; holder 完成 TE 后内核自动释放并通知你`,
94
+ };
95
+ }
96
+ writeTestEnv(ws, { holder: task, since: new Date().toISOString(), queue: env.queue });
97
+ return { granted: true, queued: false, position: 0, holder: task, text: `TE 环境已授权给 **${task}**(TE 标 ✅ 后自动释放)` };
98
+ }
99
+
100
+ /** 手工释放(holder 或排队任务都可调用;排队任务调用=退出排队)。 */
101
+ export function releaseTestEnv(ws, task) {
102
+ const env = readTestEnv(ws);
103
+ if (env.holder === task) {
104
+ env.holder = null;
105
+ env.since = null;
106
+ writeTestEnv(ws, env);
107
+ return { released: true, text: `TE 环境已释放${env.queue.length > 0 ? `(排队:${env.queue.join('、')},轮询器将自动晋升队首)` : ''}` };
108
+ }
109
+ const before = env.queue.length;
110
+ env.queue = env.queue.filter((t) => t !== task);
111
+ writeTestEnv(ws, env);
112
+ return env.queue.length < before
113
+ ? { released: false, text: `已退出 TE 排队` }
114
+ : { released: false, text: `本任务未持有 TE 环境也不在排队中` };
115
+ }
116
+
117
+ /** 状态文本(/hk-te status 与面板用)。 */
118
+ export function describeTestEnv(ws) {
119
+ const env = readTestEnv(ws);
120
+ if (!env.holder && env.queue.length === 0) return 'TE 环境空闲';
121
+ return `TE 环境持有:${env.holder ?? '(无)'}${env.since ? `(${env.since.slice(0, 19).replace('T', ' ')} 起)` : ''}${env.queue.length > 0 ? `;排队:${env.queue.join(' → ')}` : ''}`;
122
+ }