dsh-harness-kit 0.1.5 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -15
- package/README.zh-CN.md +29 -18
- package/client.js +108 -11
- package/docs/DETAIL.en.md +30 -10
- package/docs/DETAIL.md +15 -5
- package/kernel/advance.js +3 -3
- package/kernel/bindings.js +11 -6
- package/kernel/commands.js +257 -20
- package/kernel/local-files.js +175 -0
- package/kernel/metrics.js +280 -0
- package/kernel/panel.js +141 -7
- package/kernel/paths.js +62 -1
- package/kernel/setup.js +20 -19
- package/kernel/te.js +4 -4
- package/kernel/worktree.js +164 -20
- package/package.json +1 -1
- package/packs/ai-coding/agents/business-analyst.md +4 -4
- package/packs/ai-coding/agents/code-reviewer.md +6 -6
- package/packs/ai-coding/agents/developer.md +5 -5
- package/packs/ai-coding/agents/solution-architect.md +2 -2
- package/packs/ai-coding/assets/scripts/codebase_guide_init.py +70 -48
- package/packs/ai-coding/assets/scripts/harness_init.py +30 -11
- package/packs/ai-coding/assets/scripts/te_lease.py +106 -0
- package/packs/ai-coding/assets/scripts/update_board.py +30 -0
- package/packs/ai-coding/assets/scripts/verify.py +3 -3
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/{app-CLAUDE.tmpl → app-AGENTS.tmpl} +5 -5
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/{module-CLAUDE.tmpl → module-AGENTS.tmpl} +5 -5
- package/packs/ai-coding/assets/templates/dotnet/dotnet-multimodule/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +3 -3
- package/packs/ai-coding/assets/templates/java/maven/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +3 -3
- package/packs/ai-coding/assets/templates/java/maven-multimodule/{module-CLAUDE.tmpl → module-AGENTS.tmpl} +5 -5
- package/packs/ai-coding/assets/templates/java/maven-multimodule/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +3 -3
- package/packs/ai-coding/assets/templates/javascript/mobile-app/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +3 -3
- package/packs/ai-coding/assets/templates/javascript/uniapp/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +3 -3
- package/packs/ai-coding/assets/templates/javascript/vue-multimodule/{app-CLAUDE.tmpl → app-AGENTS.tmpl} +4 -4
- package/packs/ai-coding/assets/templates/javascript/vue-multimodule/{root-CLAUDE.tmpl → root-AGENTS.tmpl} +3 -3
- package/packs/ai-coding/flows/init.yml +7 -7
package/kernel/bindings.js
CHANGED
|
@@ -1,24 +1,29 @@
|
|
|
1
|
-
// 任务 ↔ 会话绑定表(.harness/tasks/sessions.json
|
|
1
|
+
// 任务 ↔ 会话绑定表(.harness/local/sessions.json;旧 tasks/sessions.json 自动迁移)。
|
|
2
2
|
// 记录点:面板 /harness-kit/command 成功执行、kernel 命令 handler(hk-new/hk-fix 内直接登记,
|
|
3
3
|
// 覆盖「在会话里手敲命令」的场景)、客户端新开会话后 POST /harness-kit/bind-session。
|
|
4
4
|
// 用途:面板「重开/继续实施/转到会话」跳转;自动续接引擎据此找到任务所属会话。
|
|
5
5
|
import fs from 'node:fs';
|
|
6
6
|
import path from 'node:path';
|
|
7
|
-
import {
|
|
7
|
+
import { localStatePath } from './paths.js';
|
|
8
8
|
|
|
9
9
|
/** 读任务→会话绑定表(坏文件容忍为 {})。 */
|
|
10
10
|
export function readTaskSessions(ws) {
|
|
11
11
|
try {
|
|
12
|
-
const data = JSON.parse(fs.readFileSync(
|
|
12
|
+
const data = JSON.parse(fs.readFileSync(localStatePath(ws, 'sessions.json', 'tasks/sessions.json'), 'utf8'));
|
|
13
13
|
return data && typeof data === 'object' && data.tasks && typeof data.tasks === 'object' ? data.tasks : {};
|
|
14
14
|
} catch { return {}; }
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
/**
|
|
17
|
+
/** 登记/覆盖任务→会话绑定,并保留历史会话(统计归档用;同一会话去重)。 */
|
|
18
18
|
export function recordTaskSession(ws, task, sessionId) {
|
|
19
|
-
const file =
|
|
19
|
+
const file = localStatePath(ws, 'sessions.json', 'tasks/sessions.json');
|
|
20
20
|
const tasks = readTaskSessions(ws);
|
|
21
|
-
|
|
21
|
+
const now = new Date().toISOString();
|
|
22
|
+
const prev = tasks[task] && typeof tasks[task] === 'object' ? tasks[task] : {};
|
|
23
|
+
const history = Array.isArray(prev.sessions) ? prev.sessions.filter((x) => x && typeof x.id === 'string') : [];
|
|
24
|
+
if (prev.sessionId && !history.some((x) => x.id === prev.sessionId)) history.push({ id: prev.sessionId, at: prev.at ?? now });
|
|
25
|
+
if (!history.some((x) => x.id === sessionId)) history.push({ id: sessionId, at: now });
|
|
26
|
+
tasks[task] = { sessionId, at: now, sessions: history };
|
|
22
27
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
23
28
|
fs.writeFileSync(file, `${JSON.stringify({ tasks }, null, 2)}\n`, 'utf8');
|
|
24
29
|
}
|
package/kernel/commands.js
CHANGED
|
@@ -15,9 +15,11 @@ import { claimTask } from './panel.js';
|
|
|
15
15
|
import { clearAdvanceMarks } from './advance.js';
|
|
16
16
|
import { ensureTaskWorkspaces, releaseTaskWorkspaces, clearTaskWorkspaces, renderWorkspaceNotice, ensureBaselineMirrors, renderAnalysisNotice, ensureTaskAnalysisWorktrees, removeTaskAnalysisWorktrees, parseBaseSpec, describeMainWorktree, recordDecision, clearDecision, readWorkspaces, mergeTaskBranches, reconcileArchivedWorktrees } from './worktree.js';
|
|
17
17
|
import { acquireTestEnv, releaseTestEnv, describeTestEnv } from './te.js';
|
|
18
|
+
import { discoverAll, discoverSource, readLocalFiles, writeLocalFiles, provisionAllSlots } from './local-files.js';
|
|
18
19
|
import { recordTaskSession } from './bindings.js';
|
|
19
20
|
import { addSource, runInit, formatInitReport, guessRole, boardTemplate } from './setup.js';
|
|
20
21
|
import { dispatchSection, describeWorkerModel } from './models.js';
|
|
22
|
+
import { collectTaskMetrics, writeTaskMetrics } from './metrics.js';
|
|
21
23
|
|
|
22
24
|
const ok = (text) => ({ kind: 'success', text });
|
|
23
25
|
const err = (text) => ({ kind: 'error', text });
|
|
@@ -234,7 +236,7 @@ async function hkInit({ agent, rawInput }) {
|
|
|
234
236
|
const pm = resolveRole(ws, kit, 'project-manager');
|
|
235
237
|
const prompt = compileFlowPrompt(loaded.flow, {
|
|
236
238
|
task: '工程初始化',
|
|
237
|
-
desc: '探测 services/ 下子工程的技术栈与结构,按模板生成子工程文档(CLAUDE.md
|
|
239
|
+
desc: '探测 services/ 下子工程的技术栈与结构,按模板生成子工程文档(AGENTS.md(已有 CLAUDE.md 则跳过)/ build.json / CODE_STANDARDS.md / 模块级 AGENTS.md);再与人协作补齐各端 build.json 的编译/启动命令并实跑一次编译+启动验证(成功后停掉服务);最后建 CodeGraph 代码索引 —— 原 /harness-init 流程',
|
|
238
240
|
flowFile: loaded.file,
|
|
239
241
|
artifacts: '各子工程(生成清单见 .harness/.logs/workflow/harness-init-plan.json)',
|
|
240
242
|
roleSections: pm ? `### PM 角色(你立即切换到此身份)\n\n${pm.body}` : undefined,
|
|
@@ -593,17 +595,25 @@ async function hkApply({ agent, rawInput }) {
|
|
|
593
595
|
}
|
|
594
596
|
|
|
595
597
|
// --------------------------------------------------------------- /hk-archive
|
|
596
|
-
async function hkArchive({ agent, rawInput }) {
|
|
598
|
+
async function hkArchive({ agent, rawInput, ctx }) {
|
|
597
599
|
const ws = wsRoot(agent);
|
|
598
600
|
const kit = readKit(ws);
|
|
599
601
|
if (!kit) return err('尚未初始化:请先运行 `/hk-init`。');
|
|
600
602
|
const { flags, positional } = parseArgs(rawInput);
|
|
601
603
|
const task = positional[0];
|
|
602
|
-
if (!task) return err('用法:/hk-archive <任务名> [--merge [仓:分支,…]]');
|
|
604
|
+
if (!task) return err('用法:/hk-archive <任务名> [--merge [仓:分支,…]] [--no-merge] [--dry-run]');
|
|
603
605
|
// 合入确认(B 方案,2026-11-17):--merge = 人显式确认要把任务分支本地合入目标基线;
|
|
604
606
|
// 可带 repo:branch 覆盖目标(不带则用任务创建时指定的基线)。合并只做本地提交,不推送。
|
|
605
607
|
const mergeAsked = flags.merge !== undefined;
|
|
608
|
+
const noMerge = flags['no-merge'] === true;
|
|
609
|
+
const dryRun = flags['dry-run'] === true;
|
|
610
|
+
if (mergeAsked && noMerge) return err('`--merge` 与 `--no-merge` 不能同时使用。');
|
|
606
611
|
const mergeOverrides = mergeAsked && typeof flags.merge === 'string' ? parseBaseSpec(flags.merge) : {};
|
|
612
|
+
// 0.2.0:autoClose 取代 autoMergeClean(旧键兼容);只做本地合并,不推送。
|
|
613
|
+
const autoClose = kit.worktree?.autoClose === true || kit.worktree?.autoMergeClean === true;
|
|
614
|
+
const targetSync = ['off', 'ff-only', 'safe'].includes(kit.worktree?.targetSync) ? kit.worktree.targetSync : 'safe';
|
|
615
|
+
const shouldMerge = !noMerge && (mergeAsked || autoClose);
|
|
616
|
+
const mergeOpts = { syncTarget: targetSync, dryRun };
|
|
607
617
|
|
|
608
618
|
const taskDir = path.join(harnessDir(ws), 'deliverables', task);
|
|
609
619
|
// 活跃任务归档前先清理其他已归档残留;残留收尾(taskDir 不存在)不能先清理,
|
|
@@ -615,7 +625,10 @@ async function hkArchive({ agent, rawInput }) {
|
|
|
615
625
|
// 此时活目录已清,正常预检必然失败;这里识别为「只做工作区释放」的收尾模式。
|
|
616
626
|
const wl = readWorkspaces(ws);
|
|
617
627
|
if (wl.tasks?.[task]) {
|
|
618
|
-
const mg =
|
|
628
|
+
const mg = shouldMerge ? await mergeTaskBranches(ws, kit, task, mergeOverrides, mergeOpts) : null;
|
|
629
|
+
if (dryRun) {
|
|
630
|
+
return ok(`/hk-archive ${task} 收尾预演(dry-run,未改动任何 ref):\n${(mg ? mergeLines(mg) : ['(未启用自动收尾)']).join('\n')}`);
|
|
631
|
+
}
|
|
619
632
|
const rel = await releaseTaskWorkspaces(ws, kit, task);
|
|
620
633
|
const ta = await removeTaskAnalysisWorktrees(ws, kit, task);
|
|
621
634
|
clearDecision(ws, task);
|
|
@@ -626,10 +639,18 @@ async function hkArchive({ agent, rawInput }) {
|
|
|
626
639
|
...(ta.removed > 0 ? [`任务分析工作区已回收 ×${ta.removed}`] : []),
|
|
627
640
|
...ta.notes,
|
|
628
641
|
];
|
|
642
|
+
const mgFailed = mg && (mg.conflicts.length > 0 || mg.refused.length > 0);
|
|
643
|
+
if (mgFailed) {
|
|
644
|
+
return err(`任务 **${task}** 已归档,但工作区收尾被阻断:\n${lines.join('\n')}\n\n任务文档已在归档区;修复上述问题后重跑 \`/hk-archive ${task}\`(只做本地合并,推送仍由人执行)。`);
|
|
645
|
+
}
|
|
629
646
|
if (rel.stale.length > 0) {
|
|
630
647
|
const targets = [...new Set([...rel.stale.map((x) => x.source)])]
|
|
631
648
|
.map((src) => `${src}→${(wl.tasks?.[task]?.repos?.[src]?.base) ?? '?'}`).join('、');
|
|
632
|
-
|
|
649
|
+
const hint = noMerge
|
|
650
|
+
? `已按 \`--no-merge\` 跳过代码收尾;确认合入目标基线(${targets})后重跑不带该旗标:`
|
|
651
|
+
: `确认要本地合入目标基线(${targets})后运行:`;
|
|
652
|
+
const command = noMerge ? `/hk-archive ${task}` : `/hk-archive ${task} --merge`;
|
|
653
|
+
return err(`任务 **${task}** 已归档,但工作区仍未释放:\n${lines.join('\n')}\n\n${hint}\n\`${command}\`(只做本地合并,推送仍由人执行)`);
|
|
633
654
|
}
|
|
634
655
|
return ok(`任务 **${task}** 已归档,残留工作区已收尾:\n${lines.join('\n') || '(无残留)'}`);
|
|
635
656
|
}
|
|
@@ -681,6 +702,21 @@ async function hkArchive({ agent, rawInput }) {
|
|
|
681
702
|
}
|
|
682
703
|
}
|
|
683
704
|
|
|
705
|
+
// 0.2.0:收尾前置。干净可合入时先同步目标并合入;失败则任务保持活跃、文档不归档,
|
|
706
|
+
// 避免出现「已归档但 slot 还 stale」的中间态。--no-merge 保留旧行为(只归档文档)。
|
|
707
|
+
if (dryRun) {
|
|
708
|
+
const mgPlan = shouldMerge ? await mergeTaskBranches(ws, kit, task, mergeOverrides, mergeOpts) : null;
|
|
709
|
+
const planLines = mgPlan ? mergeLines(mgPlan) : ['(未启用自动收尾,将只归档文档)'];
|
|
710
|
+
return ok(`/hk-archive ${task} 预演(dry-run,未改动任何文件/ref):\n${planLines.join('\n')}\n\n门禁已通过;去掉 --dry-run 即执行。`);
|
|
711
|
+
}
|
|
712
|
+
let mgBefore = null;
|
|
713
|
+
if (shouldMerge) {
|
|
714
|
+
mgBefore = await mergeTaskBranches(ws, kit, task, mergeOverrides, mergeOpts);
|
|
715
|
+
if (mgBefore.conflicts.length > 0 || mgBefore.refused.length > 0) {
|
|
716
|
+
return err(`归档未执行:工作区收尾被阻断,任务 **${task}** 仍保持活跃,文档未归档。\n${mergeLines(mgBefore).join('\n')}\n\n修复后重跑 \`/hk-archive ${task}\`;若只想先归档文档,加 \`--no-merge\`。`);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
|
|
684
720
|
const archiveDir = path.join(harnessDir(ws), 'deliverables', '_archive', task);
|
|
685
721
|
fs.mkdirSync(archiveDir, { recursive: true });
|
|
686
722
|
const date = new Date().toISOString().slice(0, 10);
|
|
@@ -695,6 +731,21 @@ async function hkArchive({ agent, rawInput }) {
|
|
|
695
731
|
}
|
|
696
732
|
const tag = `R${round}`;
|
|
697
733
|
|
|
734
|
+
// 运行统计快照:与面板 task-insight 共用采集函数;失败不阻塞归档,写 unavailable stub。
|
|
735
|
+
let metricsNote = '';
|
|
736
|
+
try {
|
|
737
|
+
const metrics = await collectTaskMetrics(ws, kit, task, {
|
|
738
|
+
sessionQuery: ctx?.get?.('sessionQuery'),
|
|
739
|
+
tokenMeter: ctx?.get?.('tokenMeter'),
|
|
740
|
+
sessions: ctx?.get?.('sessions'),
|
|
741
|
+
currentSession: agent?.session,
|
|
742
|
+
});
|
|
743
|
+
const written = writeTaskMetrics(ws, task, tag, metrics);
|
|
744
|
+
metricsNote = `\n- 运行统计:\`_archive/${task}/metrics/${tag}.json\`(${metrics.coverage}${written.skipped ? ',已存在' : ''})`;
|
|
745
|
+
} catch (cause) {
|
|
746
|
+
metricsNote = `\n- ⚠️ 运行统计写入失败:${String(cause?.message || cause).replace(/\s+/g, ' ').slice(0, 160)}`;
|
|
747
|
+
}
|
|
748
|
+
|
|
698
749
|
// append each active doc to its archive counterpart under an R<N> section
|
|
699
750
|
const appended = [];
|
|
700
751
|
for (const name of fs.readdirSync(taskDir)) {
|
|
@@ -717,20 +768,20 @@ async function hkArchive({ agent, rawInput }) {
|
|
|
717
768
|
clearAdvanceMarks(ws, task);
|
|
718
769
|
bindCurrentSession(ws, task, agent);
|
|
719
770
|
|
|
720
|
-
// worktree
|
|
721
|
-
// 合入确认(B 方案):--merge 时先本地合入目标基线,再释放槽位
|
|
722
|
-
const mgNormal = mergeAsked ? await mergeTaskBranches(ws, kit, task, mergeOverrides) : null;
|
|
771
|
+
// worktree 收尾:合入已在前置阶段完成;这里只释放槽位/切回基线并删除已合入分支。
|
|
723
772
|
const wtResult = await releaseTaskWorkspaces(ws, kit, task);
|
|
724
773
|
clearDecision(ws, task);
|
|
725
774
|
const taCleanup = await removeTaskAnalysisWorktrees(ws, kit, task);
|
|
726
775
|
const staleLines = wtResult.stale.map((s) => `⚠️ ${s.source}:${s.reason}`);
|
|
727
|
-
const confirmHint = wtResult.stale.length > 0
|
|
728
|
-
? [
|
|
776
|
+
const confirmHint = wtResult.stale.length > 0
|
|
777
|
+
? [noMerge
|
|
778
|
+
? `已按 \`--no-merge\` 跳过代码收尾;确认合入目标基线后重跑不带该旗标:\`/hk-archive ${task}\``
|
|
779
|
+
: `收尾后仍有槽位未释放;确认合入目标基线后运行:\`/hk-archive ${task} --merge\`(可用 \`--merge 仓:分支\` 覆盖目标;只本地合并,推送由人执行)`]
|
|
729
780
|
: [];
|
|
730
|
-
const wtNote = wtResult.missing && taCleanup.removed === 0 && taCleanup.notes.length === 0 && !
|
|
781
|
+
const wtNote = wtResult.missing && taCleanup.removed === 0 && taCleanup.notes.length === 0 && !mgBefore
|
|
731
782
|
? ''
|
|
732
783
|
: [
|
|
733
|
-
...(
|
|
784
|
+
...(mgBefore ? mergeLines(mgBefore) : []),
|
|
734
785
|
...wtResult.released.map((r) => `${r.placement === 'main' ? '主工作树无需处理' : `slot ${r.placement} 已释放(切回基线,目录保留)`}(${r.source})`),
|
|
735
786
|
...staleLines,
|
|
736
787
|
...confirmHint,
|
|
@@ -779,7 +830,7 @@ async function hkArchive({ agent, rawInput }) {
|
|
|
779
830
|
? `资产随工作区根仓库管理(\`${lay.repoRoot}\`),随根仓库 commit/push 即共享,无需 \`/hk-sync\``
|
|
780
831
|
: '资产仓库为本地模式;如需团队共享,绑定远端后用 `/hk-sync` 同步';
|
|
781
832
|
}
|
|
782
|
-
return ok(`任务 **${task}** 已归档为 ${tag}:\n- 追加归档:${appended.map((f) => `\`_archive/${task}/${f}\``).join('、') || '(无)'}\n- 轮次摘要追加到 \`_archive/${task}/rounds.md\`\n- 活目录已清空${wtNote ? `\n- ${wtNote}` : ''}\n\n${mergeNote}${syncHint}。`);
|
|
833
|
+
return ok(`任务 **${task}** 已归档为 ${tag}:\n- 追加归档:${appended.map((f) => `\`_archive/${task}/${f}\``).join('、') || '(无)'}\n- 轮次摘要追加到 \`_archive/${task}/rounds.md\`\n- 活目录已清空${wtNote ? `\n- ${wtNote}` : ''}${metricsNote}\n\n${mergeNote}${syncHint}。`);
|
|
783
834
|
}
|
|
784
835
|
|
|
785
836
|
// ---------------------------------------------------------------- /hk-te
|
|
@@ -803,10 +854,17 @@ function hkTe({ agent, rawInput }) {
|
|
|
803
854
|
return err('用法:/hk-te [acquire|release <任务名> | status]');
|
|
804
855
|
}
|
|
805
856
|
|
|
806
|
-
/** 合入结果的行化输出(--merge 用)。 */
|
|
857
|
+
/** 合入结果的行化输出(--merge / autoClose 用)。 */
|
|
807
858
|
function mergeLines(mg) {
|
|
808
859
|
const lines = [];
|
|
860
|
+
for (const s of mg.synced ?? []) {
|
|
861
|
+
lines.push(s.merged
|
|
862
|
+
? `🔄 ${s.repo} → ${s.target} 已并入 origin/${s.target} ${s.from}..${s.to}(本地合并,未推送)`
|
|
863
|
+
: `🔄 ${s.repo} → ${s.target} 已快进 ${s.from}..${s.to}(origin,未推送)`);
|
|
864
|
+
}
|
|
865
|
+
for (const a of mg.alreadyMerged ?? []) lines.push(`✅ ${a.repo} → ${a.target} 已包含任务分支(跳过重复合并)`);
|
|
809
866
|
for (const m of mg.merged) lines.push(`✅ ${m.repo} → ${m.target} 已本地合入(commit ${m.commit},未推送)`);
|
|
867
|
+
for (const p of mg.planned ?? []) lines.push(`📝 [dry-run] ${p.repo}:将先快进 ${p.target},再合入 ${p.branch}`);
|
|
810
868
|
for (const c of mg.conflicts) lines.push(`⛔ ${c.repo} → ${c.target} 合并冲突(已中止回滚):${c.files.slice(0, 8).join('、') || '见 git status'}`);
|
|
811
869
|
for (const r of mg.refused) lines.push(`⚠️ ${r.repo}:${r.reason}`);
|
|
812
870
|
return lines;
|
|
@@ -816,8 +874,11 @@ function mergeLines(mg) {
|
|
|
816
874
|
const TE_NOTICE = [
|
|
817
875
|
'### TE 环境(串行排队,必须遵守)',
|
|
818
876
|
'- 测试环境(起服务/连 TDengine/jmeter)全局只有一个,TE 阶段按租约串行。',
|
|
819
|
-
'- 派发 TE Worker
|
|
820
|
-
'
|
|
877
|
+
'- 派发 TE Worker **之前**必须先获取租约:',
|
|
878
|
+
' - 人可运行 `/hk-te acquire <任务名>`;',
|
|
879
|
+
' - PM/自动流程可直接运行 `python3 .harness/scripts/te_lease.py acquire <任务名>`(与 `/hk-te` 共用同一 `local/test-env.json`,不需要人代跑 slash command)。',
|
|
880
|
+
' - 已获授权 → 正常派发;排队中 → **暂停 TE 阶段**,向人汇报「TE 环境被谁占用、本任务已排队」,**不要派发 TE Worker、不要起服务/连测试库**(内核无法抢占运行中的 Worker,门必须在派发前)。',
|
|
881
|
+
'- 租约只是串行锁,不是人工审批;获取后仍按 TE 门禁执行。',
|
|
821
882
|
'- TE 完成(看板链 TE 标 ✅)后内核自动释放并通知下一个排队任务,无需手工 release。',
|
|
822
883
|
].join('\n');
|
|
823
884
|
|
|
@@ -830,9 +891,109 @@ async function hkSync({ agent }) {
|
|
|
830
891
|
return syncAssets(ws, kit);
|
|
831
892
|
}
|
|
832
893
|
|
|
894
|
+
// ---------------------------------------------------------------- /hk-local
|
|
895
|
+
// 本地配置(git-ignored)发现/确认/复制:确认一次写本机 manifest,后续 slot 自动补。
|
|
896
|
+
function localEntry(manifest, name) {
|
|
897
|
+
const entry = manifest.sources?.[name];
|
|
898
|
+
return entry && typeof entry === 'object' ? entry : {};
|
|
899
|
+
}
|
|
900
|
+
function localUpdate(ws, name, patch) {
|
|
901
|
+
const manifest = readLocalFiles(ws);
|
|
902
|
+
const prev = localEntry(manifest, name);
|
|
903
|
+
manifest.sources[name] = {
|
|
904
|
+
...prev,
|
|
905
|
+
...patch,
|
|
906
|
+
updatedAt: new Date().toISOString(),
|
|
907
|
+
};
|
|
908
|
+
writeLocalFiles(ws, manifest);
|
|
909
|
+
return manifest.sources[name];
|
|
910
|
+
}
|
|
911
|
+
function localSources(ws, kit, repo) {
|
|
912
|
+
const sources = Array.isArray(kit?.sources) ? kit.sources : [];
|
|
913
|
+
return repo ? sources.filter((s) => s.name === repo) : sources;
|
|
914
|
+
}
|
|
915
|
+
function fmtSize(n) {
|
|
916
|
+
if (n < 1024) return `${n} B`;
|
|
917
|
+
return `${(n / 1024).toFixed(1)} KB`;
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
async function hkLocal({ agent, rawInput }) {
|
|
921
|
+
const ws = wsRoot(agent);
|
|
922
|
+
const kit = readKit(ws);
|
|
923
|
+
if (!kit) return err('尚未初始化:请先运行 `/hk-init`。');
|
|
924
|
+
const { flags, positional } = parseArgs(rawInput);
|
|
925
|
+
const sub = positional[0] ?? 'scan';
|
|
926
|
+
const sources = localSources(ws, kit, flags.repo);
|
|
927
|
+
if (sources.length === 0) return err(`未找到仓库${flags.repo ? `:${flags.repo}` : ''}。`);
|
|
928
|
+
|
|
929
|
+
if (sub === 'scan' || sub === 'status') {
|
|
930
|
+
const lines = [`## 本地配置(${sources.map((s) => s.name).join('、')})`, ''];
|
|
931
|
+
for (const source of sources) {
|
|
932
|
+
const manifest = readLocalFiles(ws);
|
|
933
|
+
const entry = localEntry(manifest, source.name);
|
|
934
|
+
const baseline = Array.isArray(source.localFiles) ? source.localFiles : [];
|
|
935
|
+
const approved = [...new Set([...baseline, ...(Array.isArray(entry.approved) ? entry.approved : [])])];
|
|
936
|
+
const skipped = new Set(Array.isArray(entry.skipped) ? entry.skipped : []);
|
|
937
|
+
const candidates = await discoverSource(ws, source);
|
|
938
|
+
const pending = candidates.filter((c) => !approved.includes(c.path) && !skipped.has(c.path));
|
|
939
|
+
lines.push(`### ${source.name}(${source.path})`);
|
|
940
|
+
lines.push(`- 模式:${entry.mode === 'symlink' ? 'symlink' : 'copy'};已确认 ${approved.length} 个;候选 ${pending.length} 个`);
|
|
941
|
+
if (pending.length > 0) {
|
|
942
|
+
lines.push('', '| 置信 | 来源 | 大小 | 路径 |', '|---|---|---:|---|');
|
|
943
|
+
for (const c of pending) lines.push(`| ${c.reason === 'high' ? '高' : '配置'} | ${c.kind} | ${fmtSize(c.size)} | \`${c.path}\` |`);
|
|
944
|
+
lines.push('', `确认:\`/hk-local approve all --repo ${source.name}\`,或按路径:\`/hk-local approve <path> --repo ${source.name}\``);
|
|
945
|
+
} else {
|
|
946
|
+
lines.push('- 没有未确认候选。');
|
|
947
|
+
}
|
|
948
|
+
lines.push('');
|
|
949
|
+
}
|
|
950
|
+
return ok(lines.join('\n'));
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
if (sub === 'approve' || sub === 'skip') {
|
|
954
|
+
const target = positional[1];
|
|
955
|
+
if (!target) return err(`用法:/hk-local ${sub} all|path... --repo <仓库>`);
|
|
956
|
+
const out = [];
|
|
957
|
+
for (const source of sources) {
|
|
958
|
+
const candidates = await discoverSource(ws, source);
|
|
959
|
+
const paths = target === 'all' ? candidates.map((c) => c.path) : positional.slice(1);
|
|
960
|
+
if (paths.length === 0) {
|
|
961
|
+
out.push(`${source.name}:没有候选`);
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
const manifest = readLocalFiles(ws);
|
|
965
|
+
const entry = localEntry(manifest, source.name);
|
|
966
|
+
const approved = new Set([...(Array.isArray(entry.approved) ? entry.approved : []), ...(sub === 'approve' ? paths : [])]);
|
|
967
|
+
const skipped = new Set(Array.isArray(entry.skipped) ? entry.skipped : []);
|
|
968
|
+
for (const p of paths) {
|
|
969
|
+
if (sub === 'approve') { skipped.delete(p); } else { skipped.add(p); approved.delete(p); }
|
|
970
|
+
}
|
|
971
|
+
localUpdate(ws, source.name, { approved: [...approved], skipped: [...skipped] });
|
|
972
|
+
out.push(`${source.name}:${sub === 'approve' ? '确认' : '跳过'} ${paths.length} 个`);
|
|
973
|
+
}
|
|
974
|
+
out.push('', '运行 `/hk-local apply` 补齐当前已绑定的 slot。');
|
|
975
|
+
return ok(out.join('\n'));
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
if (sub === 'mode') {
|
|
979
|
+
const mode = flags.mode ?? positional[1];
|
|
980
|
+
if (!['copy', 'symlink'].includes(mode)) return err('用法:/hk-local mode copy|symlink --repo <仓库>');
|
|
981
|
+
for (const source of sources) localUpdate(ws, source.name, { mode });
|
|
982
|
+
return ok(`已设置 ${sources.map((s) => s.name).join('、')} 为 ${mode}。`);
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
if (sub === 'apply') {
|
|
986
|
+
const notes = await provisionAllSlots(ws, sources);
|
|
987
|
+
return ok(notes.length ? notes.join('\n') : '没有需要补齐的已绑定 slot。');
|
|
988
|
+
}
|
|
989
|
+
|
|
990
|
+
return err('用法:/hk-local [scan|status|approve all|path... | skip path... | mode copy|symlink | apply] [--repo <仓库>]');
|
|
991
|
+
}
|
|
992
|
+
|
|
833
993
|
// ---------------------------------------------------------------- /hk-doctor
|
|
834
|
-
async function hkDoctor({ agent }) {
|
|
994
|
+
async function hkDoctor({ agent, rawInput }) {
|
|
835
995
|
const ws = wsRoot(agent);
|
|
996
|
+
const { flags } = parseArgs(rawInput ?? '');
|
|
836
997
|
const lines = ['## Harness Kit 体检', ''];
|
|
837
998
|
lines.push(`- 工作区:\`${ws}\``);
|
|
838
999
|
lines.push(`- 内容包目录:\`${packDir(readKit(ws) ?? undefined)}\` ${fs.existsSync(packDir(readKit(ws) ?? undefined)) ? '✅' : '❌ 缺失'}`);
|
|
@@ -842,6 +1003,48 @@ async function hkDoctor({ agent }) {
|
|
|
842
1003
|
lines.push('- kit.json:❌ 不存在 → 运行 `/hk-init`');
|
|
843
1004
|
return ok(lines.join('\n'));
|
|
844
1005
|
}
|
|
1006
|
+
if (flags.fix === true) {
|
|
1007
|
+
const fixed = [];
|
|
1008
|
+
try {
|
|
1009
|
+
const r = await runInit(ws, {});
|
|
1010
|
+
if (!r.ok) {
|
|
1011
|
+
lines.push(`- 修复:❌ 初始化物化失败:${r.error}`);
|
|
1012
|
+
} else {
|
|
1013
|
+
fixed.push(...r.created.map((x) => `物化 \`${x}\``));
|
|
1014
|
+
for (const w of r.warnings) fixed.push(`⚠️ ${w}`);
|
|
1015
|
+
}
|
|
1016
|
+
} catch (cause) {
|
|
1017
|
+
lines.push(`- 修复:❌ 初始化物化异常:${cause.message}`);
|
|
1018
|
+
}
|
|
1019
|
+
// 看板 7 列修复(唯一写入门禁)
|
|
1020
|
+
const ub = path.join(harnessDir(ws), 'scripts', 'update_board.py');
|
|
1021
|
+
if (fs.existsSync(ub)) {
|
|
1022
|
+
const chk = await run('python3', [ub, '--check'], { cwd: ws, timeoutMs: 15_000 });
|
|
1023
|
+
if (chk.code !== 0) {
|
|
1024
|
+
const rep = await run('python3', [ub, '--repair', '--write'], { cwd: ws, timeoutMs: 30_000 });
|
|
1025
|
+
fixed.push(rep.code === 0 ? '看板已按 7 列契约修复' : `看板修复失败:${(rep.stdout || rep.stderr).trim()}`);
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
// 记忆 hot/cold 索引(存在 entries 但索引缺失时重建)
|
|
1029
|
+
const mem = path.join(harnessDir(ws), 'scripts', 'memory_index.py');
|
|
1030
|
+
if (fs.existsSync(mem) && (!fs.existsSync(path.join(harnessDir(ws), 'memory', 'index.md')) || !fs.existsSync(path.join(harnessDir(ws), 'memory', 'cold.md')))) {
|
|
1031
|
+
const sync = await run('python3', [mem, 'sync'], { cwd: ws, timeoutMs: 60_000 });
|
|
1032
|
+
fixed.push(sync.code === 0 ? '记忆 hot/cold 索引已重建' : `记忆索引重建失败:${(sync.stdout || sync.stderr).trim()}`);
|
|
1033
|
+
}
|
|
1034
|
+
// 旧模板命名:只提示,不删可能被项目裁剪过的文件
|
|
1035
|
+
const legacyTemplates = [];
|
|
1036
|
+
const walk = (dir) => {
|
|
1037
|
+
if (!fs.existsSync(dir)) return;
|
|
1038
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
1039
|
+
const abs = path.join(dir, e.name);
|
|
1040
|
+
if (e.isDirectory()) walk(abs);
|
|
1041
|
+
else if (e.name.endsWith('-CLAUDE.tmpl')) legacyTemplates.push(path.relative(ws, abs));
|
|
1042
|
+
}
|
|
1043
|
+
};
|
|
1044
|
+
walk(path.join(harnessDir(ws), 'templates'));
|
|
1045
|
+
if (legacyTemplates.length > 0) fixed.push(`旧模板 ${legacyTemplates.length} 个(可人工删除,插件不覆盖):${legacyTemplates.slice(0, 4).join('、')}${legacyTemplates.length > 4 ? ' 等' : ''}`);
|
|
1046
|
+
lines.push(`- 自动修复:${fixed.length ? fixed.join(';') : '无确定性修复项'}`);
|
|
1047
|
+
}
|
|
845
1048
|
const reconcile = await reconcileArchivedQuiet(ws, kit);
|
|
846
1049
|
if (reconcile) {
|
|
847
1050
|
const released = reconcile.released.length;
|
|
@@ -900,7 +1103,7 @@ async function hkDoctor({ agent }) {
|
|
|
900
1103
|
'scripts/harness_init.py', 'scripts/harness.py', 'scripts/lib.py',
|
|
901
1104
|
'scripts/verify.py', 'scripts/spec_lint.py', 'scripts/env_auto.py',
|
|
902
1105
|
'scripts/check_codegraph.py', 'scripts/run_field.py', 'scripts/codebase_guide_init.py',
|
|
903
|
-
'scripts/update_board.py', 'scripts/memory_index.py',
|
|
1106
|
+
'scripts/update_board.py', 'scripts/memory_index.py', 'scripts/te_lease.py',
|
|
904
1107
|
'rules/code-standards.md', 'specs/spec-template.md', 'memory/templates/entry.md',
|
|
905
1108
|
'memory/README.md', 'memory/cold.md',
|
|
906
1109
|
];
|
|
@@ -953,8 +1156,41 @@ async function hkDoctor({ agent }) {
|
|
|
953
1156
|
return ok(lines.join('\n'));
|
|
954
1157
|
}
|
|
955
1158
|
|
|
1159
|
+
/**
|
|
1160
|
+
* 统一入口(0.3.0 概念收敛):/hk init|task|close|doctor。
|
|
1161
|
+
* 旧 /hk-* 命令继续作为别名,内部转发到同一 handler。
|
|
1162
|
+
*/
|
|
1163
|
+
async function hkUmbrella({ agent, rawInput, ctx }) {
|
|
1164
|
+
const text = String(rawInput ?? '').trim();
|
|
1165
|
+
const [sub, ...restParts] = text.split(/\s+/).filter(Boolean);
|
|
1166
|
+
const rest = restParts.join(' ');
|
|
1167
|
+
if (!sub || sub === 'help' || sub === '-h' || sub === '--help') {
|
|
1168
|
+
return ok([
|
|
1169
|
+
'## /hk 入口',
|
|
1170
|
+
'',
|
|
1171
|
+
'- `/hk init [--assets …]`:初始化 / 修复工作区骨架与资产绑定',
|
|
1172
|
+
'- `/hk task <描述> [--file …]`:立项;加 `--fix` 走快速修复',
|
|
1173
|
+
'- `/hk close <任务> [--merge|--no-merge] [--dry-run]`:归档并收尾',
|
|
1174
|
+
'- `/hk doctor [--fix]`:体检;`--fix` 修复确定性缺件',
|
|
1175
|
+
'',
|
|
1176
|
+
'高级命令仍可用:/hk-setup、/hk-propose、/hk-apply、/hk-archive、/hk-fix、/hk-te、/hk-local、/hk-sync。',
|
|
1177
|
+
].join('\n'));
|
|
1178
|
+
}
|
|
1179
|
+
if (sub === 'init') return hkInit({ agent, rawInput: rest, ctx });
|
|
1180
|
+
if (sub === 'close') return hkArchive({ agent, rawInput: rest, ctx });
|
|
1181
|
+
if (sub === 'doctor') return hkDoctor({ agent, rawInput: rest, ctx });
|
|
1182
|
+
if (sub === 'task') {
|
|
1183
|
+
const tokens = restParts.filter((t) => t !== '--fix');
|
|
1184
|
+
const line = tokens.join(' ');
|
|
1185
|
+
if (restParts.includes('--fix')) return hkFix({ agent, rawInput: line, ctx });
|
|
1186
|
+
return hkNew({ agent, rawInput: line, ctx });
|
|
1187
|
+
}
|
|
1188
|
+
return err(`未知 /hk 子命令:${sub}。可用:init / task / close / doctor。`);
|
|
1189
|
+
}
|
|
1190
|
+
|
|
956
1191
|
export function registerCommands(ctx) {
|
|
957
1192
|
const defs = [
|
|
1193
|
+
{ name: 'hk', description: 'Harness Kit 统一入口:init / task / close / doctor', hint: '[init|task|close|doctor] …', handler: hkUmbrella },
|
|
958
1194
|
{ name: 'hk-setup', description: '收集代码仓库并登记 kit.json(--add <url> [--name n] [--path p] [--role r] [--branch b])', hint: '[--add <git-url> …]', handler: hkSetup },
|
|
959
1195
|
{ name: 'hk-init', description: '初始化 .harness 骨架/资产仓库绑定/脚本模板物化,并编排子工程文档与 CodeGraph 索引生成(幂等)', hint: '[--assets <url|init|local>] [--branch <分支>]', handler: hkInit },
|
|
960
1196
|
{ name: 'hk-fix', description: '启动轻量 fix 直通任务:脚手架 + PM 编排剧本', hint: '[任务名] <一句话描述> [--full|--light] [--auto]', handler: hkFix },
|
|
@@ -963,15 +1199,16 @@ export function registerCommands(ctx) {
|
|
|
963
1199
|
{ name: 'hk-apply', description: '执行 apply 实施阶段(Dev→CR→TE→审批2;含就绪预检与续接)', hint: '[任务名] [反馈]', handler: hkApply },
|
|
964
1200
|
{ name: 'hk-archive', description: '归档任务本轮产物到 _archive 并清空活目录(全流程附带 Spec/Memory Merge 收尾)', hint: '<任务名>', handler: hkArchive },
|
|
965
1201
|
{ name: 'hk-te', description: 'TE 环境串行租约(测试环境全局唯一):acquire 授权/排队、release 释放/退队、status 查看', hint: '[acquire|release <任务名> | status]', handler: hkTe },
|
|
1202
|
+
{ name: 'hk-local', description: '本地配置(git-ignored)发现/确认/复制:首次确认后新 slot 自动补齐', hint: '[scan|status|approve all|path... | skip path... | mode copy|symlink | apply] [--repo <仓库>]', handler: hkLocal },
|
|
966
1203
|
{ name: 'hk-sync', description: '资产仓库 git 同步:自动提交 → pull --rebase → 纯追加文件自动三路合并 → push(其余冲突中止回滚转人工)', handler: hkSync },
|
|
967
|
-
{ name: 'hk-doctor', description: '检查 harness 工作区健康度(kit
|
|
1204
|
+
{ name: 'hk-doctor', description: '检查 harness 工作区健康度(kit/角色/红线/流程);--fix 修复确定性缺件', hint: '[--fix]', handler: hkDoctor },
|
|
968
1205
|
];
|
|
969
1206
|
for (const def of defs) {
|
|
970
1207
|
ctx.commands.register({
|
|
971
1208
|
name: def.name,
|
|
972
1209
|
description: def.description,
|
|
973
1210
|
...(def.hint ? { input: { hint: def.hint } } : {}),
|
|
974
|
-
handler: ({ agent, rawInput }) => def.handler({ agent, rawInput }),
|
|
1211
|
+
handler: ({ agent, rawInput }) => def.handler({ agent, rawInput, ctx }),
|
|
975
1212
|
});
|
|
976
1213
|
}
|
|
977
1214
|
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// 本地文件(git-ignored 配置)在 worktree slot 间的发现/确认/复制。
|
|
2
|
+
//
|
|
3
|
+
// 设计(2026-11-20 与人定稿):
|
|
4
|
+
// - 不从插件硬编码文件名;候选由主工作树的 ignored/untracked 文件推断;
|
|
5
|
+
// - 首次确认后写入本机 manifest(.harness/local/local-files.json,不入资产 git);
|
|
6
|
+
// - 新 slot 只复制已确认项;新候选只提示,不自动复制;
|
|
7
|
+
// - 支持 copy / symlink 两种模式,目标已存在时不覆盖。
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { harnessDir, localStatePath } from './paths.js';
|
|
11
|
+
import { runGit } from './exec.js';
|
|
12
|
+
|
|
13
|
+
const MANIFEST = 'local-files.json';
|
|
14
|
+
const CONFIG_EXT = new Set(['.properties', '.yml', '.yaml', '.conf', '.ini', '.toml', '.json', '.xml', '.env']);
|
|
15
|
+
const EXCLUDE_DIRS = new Set([
|
|
16
|
+
'.git', 'target', 'build', 'dist', 'out', 'bin', 'obj', 'node_modules', '.idea', '.vscode',
|
|
17
|
+
'.gradle', '.mvn', '.next', 'coverage', 'logs', '.cache', 'tmp', '.tmp', '.DS_Store',
|
|
18
|
+
]);
|
|
19
|
+
const EXCLUDE_EXT = new Set([
|
|
20
|
+
'.class', '.jar', '.war', '.zip', '.gz', '.tar', '.png', '.jpg', '.jpeg', '.gif', '.ico',
|
|
21
|
+
'.pdf', '.log', '.lock', '.map', '.min.js', '.min.css', '.woff', '.woff2', '.ttf', '.eot',
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
export const localFilesPath = (ws) => localStatePath(ws, MANIFEST, 'tasks/local-files.json');
|
|
25
|
+
|
|
26
|
+
export function readLocalFiles(ws) {
|
|
27
|
+
try {
|
|
28
|
+
const data = JSON.parse(fs.readFileSync(localFilesPath(ws), 'utf8'));
|
|
29
|
+
return {
|
|
30
|
+
version: 1,
|
|
31
|
+
sources: data && typeof data.sources === 'object' && data.sources ? data.sources : {},
|
|
32
|
+
};
|
|
33
|
+
} catch {
|
|
34
|
+
return { version: 1, sources: {} };
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function writeLocalFiles(ws, data) {
|
|
39
|
+
const file = localFilesPath(ws);
|
|
40
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
41
|
+
fs.writeFileSync(file, `${JSON.stringify({ version: 1, sources: data.sources ?? {} }, null, 2)}\n`, 'utf8');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function sourceEntry(manifest, name) {
|
|
45
|
+
const entry = manifest.sources?.[name];
|
|
46
|
+
return entry && typeof entry === 'object' ? entry : {};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function approvedOf(manifest, source) {
|
|
50
|
+
const entry = sourceEntry(manifest, source.name);
|
|
51
|
+
const baseline = Array.isArray(source.localFiles) ? source.localFiles : [];
|
|
52
|
+
const extra = Array.isArray(entry.approved) ? entry.approved : [];
|
|
53
|
+
return [...new Set([...baseline, ...extra])];
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function skippedOf(manifest, source) {
|
|
57
|
+
return new Set(Array.isArray(sourceEntry(manifest, source.name).skipped) ? sourceEntry(manifest, source.name).skipped : []);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function excluded(rel) {
|
|
61
|
+
const lower = rel.toLowerCase();
|
|
62
|
+
const parts = lower.split('/');
|
|
63
|
+
if (parts.some((p) => EXCLUDE_DIRS.has(p))) return true;
|
|
64
|
+
if (EXCLUDE_EXT.has(path.extname(lower))) return true;
|
|
65
|
+
if (/(^|\/)(package-lock\.json|pnpm-lock\.yaml|yarn\.lock|composer\.lock)$/.test(lower)) return true;
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function candidateReason(rel) {
|
|
70
|
+
const base = path.basename(rel).toLowerCase();
|
|
71
|
+
if (base.startsWith('.env') || /(local|secret|credential|application-|dbcp)/.test(base)) return 'high';
|
|
72
|
+
if (CONFIG_EXT.has(path.extname(base))) return 'config';
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function gitList(repo, args) {
|
|
77
|
+
const r = await runGit(['ls-files', ...args], { cwd: repo });
|
|
78
|
+
if (r.code !== 0) return [];
|
|
79
|
+
return r.stdout.split('\0').filter(Boolean);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 从主工作树推断候选;只读。 */
|
|
83
|
+
export async function discoverSource(ws, source) {
|
|
84
|
+
const repo = path.resolve(ws, source.path);
|
|
85
|
+
if (!fs.existsSync(repo)) return [];
|
|
86
|
+
const check = await runGit(['rev-parse', '--is-inside-work-tree'], { cwd: repo });
|
|
87
|
+
if (check.code !== 0 || check.stdout.trim() !== 'true') return [];
|
|
88
|
+
const untracked = await gitList(repo, ['--others', '--exclude-standard', '-z']);
|
|
89
|
+
const ignored = await gitList(repo, ['--others', '--ignored', '--exclude-standard', '-z']);
|
|
90
|
+
const status = new Map();
|
|
91
|
+
for (const p of untracked) status.set(p, 'untracked');
|
|
92
|
+
for (const p of ignored) status.set(p, 'ignored');
|
|
93
|
+
const rows = [];
|
|
94
|
+
for (const [rel, kind] of status) {
|
|
95
|
+
if (!rel || excluded(rel)) continue;
|
|
96
|
+
const reason = candidateReason(rel);
|
|
97
|
+
if (!reason) continue;
|
|
98
|
+
const abs = path.join(repo, rel);
|
|
99
|
+
let stat;
|
|
100
|
+
try { stat = fs.statSync(abs); } catch { continue; }
|
|
101
|
+
if (!stat.isFile() || stat.size > 256 * 1024) continue;
|
|
102
|
+
rows.push({ path: rel.replaceAll('\\', '/'), source: source.name, kind, reason, size: stat.size });
|
|
103
|
+
}
|
|
104
|
+
rows.sort((a, b) => (a.reason === b.reason ? a.path.localeCompare(b.path) : a.reason === 'high' ? -1 : 1));
|
|
105
|
+
return rows;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export async function discoverAll(ws, sources) {
|
|
109
|
+
const out = [];
|
|
110
|
+
for (const source of sources ?? []) {
|
|
111
|
+
for (const row of await discoverSource(ws, source)) out.push(row);
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function provisionOne(srcRoot, dstRoot, rel, mode, notes) {
|
|
117
|
+
const from = path.resolve(srcRoot, rel);
|
|
118
|
+
const to = path.resolve(dstRoot, rel);
|
|
119
|
+
const srcRel = path.relative(srcRoot, from);
|
|
120
|
+
const dstRel = path.relative(dstRoot, to);
|
|
121
|
+
if (srcRel.startsWith('..') || dstRel.startsWith('..') || path.isAbsolute(srcRel) || path.isAbsolute(dstRel)) {
|
|
122
|
+
notes.push(`本地配置路径越界,已跳过:${rel}`);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (!fs.existsSync(from) || !fs.statSync(from).isFile()) {
|
|
126
|
+
notes.push(`本地配置不存在,未复制:${rel}`);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (fs.existsSync(to)) return;
|
|
130
|
+
fs.mkdirSync(path.dirname(to), { recursive: true });
|
|
131
|
+
if (mode === 'symlink') {
|
|
132
|
+
try {
|
|
133
|
+
fs.symlinkSync(path.relative(path.dirname(to), from), to);
|
|
134
|
+
notes.push(`已软链本地配置:${rel}`);
|
|
135
|
+
return;
|
|
136
|
+
} catch {
|
|
137
|
+
// Windows/受限文件系统回退 copy
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
fs.copyFileSync(from, to);
|
|
141
|
+
notes.push(`已复制本地配置:${rel}`);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 为某个 slot 补齐已确认的本地配置;不覆盖已有文件。 */
|
|
145
|
+
export async function provisionLocalFiles(ws, source, slotDir) {
|
|
146
|
+
const manifest = readLocalFiles(ws);
|
|
147
|
+
const approved = approvedOf(manifest, source);
|
|
148
|
+
const mode = sourceEntry(manifest, source.name).mode === 'symlink' ? 'symlink' : 'copy';
|
|
149
|
+
const notes = [];
|
|
150
|
+
for (const rel of approved) provisionOne(path.resolve(ws, source.path), slotDir, rel, mode, notes);
|
|
151
|
+
const candidates = await discoverSource(ws, source);
|
|
152
|
+
const skipped = skippedOf(manifest, source);
|
|
153
|
+
const pending = candidates.filter((c) => !approved.includes(c.path) && !skipped.has(c.path));
|
|
154
|
+
if (pending.length > 0) {
|
|
155
|
+
notes.push(`发现 ${pending.length} 个未确认的本地配置候选:运行 \`/hk-local scan\` 查看,\`/hk-local approve all --repo ${source.name}\` 确认`);
|
|
156
|
+
}
|
|
157
|
+
return notes;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 把已确认配置补到所有已绑定 slot(/hk-local apply)。 */
|
|
161
|
+
export async function provisionAllSlots(ws, sources) {
|
|
162
|
+
let ledger = {};
|
|
163
|
+
try { ledger = JSON.parse(fs.readFileSync(localStatePath(ws, 'worktrees.json', 'tasks/worktrees.json'), 'utf8')); } catch { /* no ledger */ }
|
|
164
|
+
const notes = [];
|
|
165
|
+
for (const source of sources ?? []) {
|
|
166
|
+
const slots = ledger.slots?.[source.name] ?? {};
|
|
167
|
+
for (const [placement, info] of Object.entries(slots)) {
|
|
168
|
+
if (!info || info.state !== 'bound') continue;
|
|
169
|
+
const dir = path.join(ws, '.worktrees', source.name, placement);
|
|
170
|
+
if (!fs.existsSync(dir)) continue;
|
|
171
|
+
notes.push(...(await provisionLocalFiles(ws, source, dir)));
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return notes;
|
|
175
|
+
}
|