@adamchanadam/agent-handoff-kit 0.3.67 → 0.4.1
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.en.md +44 -180
- package/README.md +45 -187
- package/bin/agent-handoff-kit.mjs +149 -36
- package/bin/commands.mjs +134 -0
- package/bin/handoff-read.mjs +88 -0
- package/bin/installed-file-contract.mjs +79 -63
- package/bin/migration-baselines/official-origin-catalog.json +433 -1
- package/bin/official-origin-catalog.mjs +267 -257
- package/bin/progress/ICON-LICENSE.txt +21 -0
- package/bin/progress/agent-handoff-kit-logo2-256.png +0 -0
- package/bin/progress/assets.mjs +6 -0
- package/bin/progress/dashboard-hero.png +0 -0
- package/bin/progress/dashboard.mjs +134 -0
- package/bin/progress/icons.svg +36 -0
- package/bin/progress/index.html +31 -0
- package/bin/progress/launch.mjs +40 -0
- package/bin/progress/open.mjs +43 -0
- package/bin/progress/project-version.mjs +121 -0
- package/bin/progress/projection.mjs +144 -0
- package/bin/progress/renderer.js +152 -0
- package/bin/progress/server.mjs +78 -0
- package/bin/progress/styles.css +31 -0
- package/bin/upgrade-inventory.mjs +153 -273
- package/docs/commands.md +61 -0
- package/docs/progress.md +73 -0
- package/package.json +3 -1
- package/packs/closeout.md +71 -66
- package/runtime-core/AGENTS.core.md +112 -101
- package/runtime-core/PROJECT_INDEX.md +8 -1
- package/runtime-core/SESSION_HANDOFF.md +157 -147
- package/runtime-core/SESSION_LOG.md +2 -0
|
@@ -10,7 +10,10 @@ import { hostname } from "node:os";
|
|
|
10
10
|
import path from "node:path";
|
|
11
11
|
import { fileURLToPath } from "node:url";
|
|
12
12
|
import { assessPromptMirrorRoot, assessPromptMirrorTexts, extractOpeningMessage } from "./prompt-mirror-core.mjs";
|
|
13
|
-
import {
|
|
13
|
+
import { readHandoffChunk, formatHandoffChunk } from "./handoff-read.mjs";
|
|
14
|
+
import { freshInstallMappings, installedFileContract, installedMappings, requiredInstalledTargets, upgradeStateMappings, upgradeStateTargets, requiredShortcutTargets, SHORTCUT_INSTALL_CONTRACT } from "./installed-file-contract.mjs";
|
|
15
|
+
import { commands, commandFiles, planCommands, assertCommandPaths } from "./commands.mjs";
|
|
16
|
+
const legacyShortcutRecoveryPermit = Symbol("legacy shortcut recovery only");
|
|
14
17
|
import { getArtifactBoundManagedSegment, getOfficialBaseline, identifyOfficialOrigin, loadOfficialOriginCatalog } from "./official-origin-catalog.mjs";
|
|
15
18
|
import {
|
|
16
19
|
markdownVisibleLinesOutsideHiddenBlocks,
|
|
@@ -569,19 +572,50 @@ async function main() {
|
|
|
569
572
|
const version = await readPackageVersion();
|
|
570
573
|
// `doctor` renders version alignment itself. Let that single health run own
|
|
571
574
|
// the lookup instead of checking once here and once again inside doctor.
|
|
572
|
-
if (!new Set(["closeout-status", "doctor", "workspace-health"]).has(command)) await maybePrintUpdateNotice(version);
|
|
575
|
+
if (!new Set(["closeout-status", "doctor", "workspace-health", "progress", "commands", "handoff-read", "update"]).has(command)) await maybePrintUpdateNotice(version);
|
|
573
576
|
if (!command || options.help) {
|
|
577
|
+
if (command === "handoff-read") {
|
|
578
|
+
console.log("Usage: agent-handoff-kit handoff-read [--root <path>] [--max-chars <64..8192>] [--offset <n> --sha256 <digest>]\nRead-only, offline. Offsets count Unicode code points. Continue using nextOffset and the same sha256.\nContent served is not proof of reception, understanding or permission to act.");
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
574
581
|
printHelp(version);
|
|
575
582
|
return;
|
|
576
583
|
}
|
|
577
584
|
|
|
578
585
|
const root = path.resolve(options.root ?? process.cwd());
|
|
579
586
|
|
|
587
|
+
if (command === "handoff-read") {
|
|
588
|
+
if (["dryRun", "yes", "manifest"].some(key => Object.hasOwn(options, key))) throw new Error("handoff-read accepts only --root, --offset, --max-chars and --sha256");
|
|
589
|
+
output.write(formatHandoffChunk(readHandoffChunk(root, options)));
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
if (["offset", "maxChars", "sha256"].some(key => options[key] !== undefined)) throw new Error("chunk options require handoff-read");
|
|
594
|
+
|
|
580
595
|
if (command === "init" || command === "upgrade") {
|
|
581
596
|
await runInstall(command, root, options, version);
|
|
582
597
|
return;
|
|
583
598
|
}
|
|
584
599
|
|
|
600
|
+
if (command === "update") {
|
|
601
|
+
assertCommandPaths(root);
|
|
602
|
+
await validateTransactionRoot(root, [], { createMissingRoot: false });
|
|
603
|
+
const installed = await readProjectIndexTemplateVersion(root);
|
|
604
|
+
if (!installed) throw new Error('Project version is unverified; check the existing Kit installation before updating. / 無法確認專案版本,未升級。');
|
|
605
|
+
const latest = await fetchLatestVersion();
|
|
606
|
+
if (!latest || !isStableSemver(latest)) throw new Error('npm latest could not be verified; no upgrade performed. / 未能確認 npm 最新版,未升級。');
|
|
607
|
+
console.log('Installed / 已安裝: ' + installed + '; npm latest / 最新版: ' + latest);
|
|
608
|
+
if (compareSemver(installed, latest) > 0) throw new Error('Project is newer than npm latest; refusing downgrade. / 專案版本較新,不會降級。');
|
|
609
|
+
if (version !== latest) throw new Error('Acquire the verified public CLI and retry: npx --yes @adamchanadam/agent-handoff-kit@' + latest + ' update --root <project-root> (quote the verified root as one argument in your active shell)');
|
|
610
|
+
if (installed === latest && !await exists(path.join(root, 'dev/governance_migrations/.upgrade.lock'))) {
|
|
611
|
+
console.log('Already current; checking installation without writing. / 已是最新版,唯讀核對安裝。');
|
|
612
|
+
await runDoctor(root, version);
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
await runInstall('upgrade', root, { ...options, yes: true }, version);
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
|
|
585
619
|
if (command === "doctor") {
|
|
586
620
|
await runDoctor(root, version);
|
|
587
621
|
return;
|
|
@@ -592,6 +626,32 @@ async function main() {
|
|
|
592
626
|
return;
|
|
593
627
|
}
|
|
594
628
|
|
|
629
|
+
if (command === "commands") {
|
|
630
|
+
const { installCommands } = await import("./commands.mjs");
|
|
631
|
+
const result = installCommands({ root, agent: options.agent ?? "all", yes: options.yes, dryRun: options.dryRun });
|
|
632
|
+
console.log("Agent Handoff Kit — Shortcuts / 快捷入口: " + result.status);
|
|
633
|
+
for (const item of result.plan) console.log(item.action + " " + item.file);
|
|
634
|
+
if (result.status === "upgrade-required") { console.error('Official entries need a transactional update. Run upgrade --dry-run, then upgrade --yes. / 官方入口需要安全升級,請用 Kit 升級流程。'); process.exitCode = 1; }
|
|
635
|
+
else if (result.status === "conflict") { console.error("Existing command differs; no files written. Review the named conflict. / 同名入口有差異,未寫入任何檔案。"); process.exitCode = 1; }
|
|
636
|
+
else if (result.status === "preview") console.log("Preview only. Add --yes to enable. / 只作預覽,加 --yes 才啟用。");
|
|
637
|
+
else console.log("Ready. Reload your agent if needed. / 已啟用,必要時重新載入 AI。Claude / Gemini / Antigravity: /handoff-kit-help · Codex: $handoff-kit-help or /skills");
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
if (command === "progress") {
|
|
642
|
+
if (options.background) {
|
|
643
|
+
const { openProgress } = await import("./progress/open.mjs");
|
|
644
|
+
const result = await openProgress({ root, port: options.port ?? 0, openBrowser: !options.noOpen, version });
|
|
645
|
+
console.log("Agent Handoff Kit — Project overview / 專案速覽\n" + result.url + "\n" + (result.reused ? "Reused local service. / 已重用服務。" : "Started local service. / 已啟動服務。"));
|
|
646
|
+
return;
|
|
647
|
+
}
|
|
648
|
+
const { startProgress, PROGRESS_IDLE_MS } = await import("./progress/server.mjs");
|
|
649
|
+
await startProgress({ root, port: options.port ?? 0, openBrowser: !options.noOpen, version, onReady: ({ url }) => {
|
|
650
|
+
console.log(`Agent Handoff Kit — Project overview / 專案速覽\n${url}\nRead-only live view. Kept available for ${PROGRESS_IDLE_MS / 3600000} hours without connected pages; no file polling while idle. Ctrl+C stops now.\n唯讀自動更新。全部頁面斷線後保留 ${PROGRESS_IDLE_MS / 3600000} 小時,閒置時暫停讀檔;按 Ctrl+C 可立即停止。`);
|
|
651
|
+
} });
|
|
652
|
+
return;
|
|
653
|
+
}
|
|
654
|
+
|
|
595
655
|
if (command === "workspace-health") {
|
|
596
656
|
runWorkspaceHealth(root);
|
|
597
657
|
return;
|
|
@@ -706,7 +766,7 @@ function assessHandoffSufficiency(text) {
|
|
|
706
766
|
const match = new RegExp(`^(?:[-*]\\s+)?${escapeRegExp(label)}:\\s*(.*)$`, "iu").exec(line);
|
|
707
767
|
return match ? [match[1].trim()] : [];
|
|
708
768
|
});
|
|
709
|
-
const affirmative = (value) => /^yes(?:$|[\s
|
|
769
|
+
const affirmative = (value) => /^yes(?:$|[\s,.;:—–-])/iu.test(value);
|
|
710
770
|
const answers = fields("Answer");
|
|
711
771
|
const evidence = fields("Reconstruction evidence");
|
|
712
772
|
const findings = [];
|
|
@@ -1055,7 +1115,7 @@ function assessHandoffWorkspaceIdentity(handoffText, health) {
|
|
|
1055
1115
|
|
|
1056
1116
|
const gitRootValue = workspaceFieldValue(section, "Git root");
|
|
1057
1117
|
if (hasSubstantiveWorkspaceValue(gitRootValue)
|
|
1058
|
-
&& !
|
|
1118
|
+
&& !workspaceRootMeansNoGit(gitRootValue)
|
|
1059
1119
|
&& !workspaceTextIncludesPath(gitRootValue, health.gitRoot)) {
|
|
1060
1120
|
findings.push(`Workspace: handoff Git root does not match live Git root ${health.gitRoot}`);
|
|
1061
1121
|
}
|
|
@@ -1114,18 +1174,24 @@ function workspaceValueMeansNoGit(value) {
|
|
|
1114
1174
|
return /\b(no git|non-git|not a git repository|not_git)\b|\bgit:\s*no(?=$|[\s,;.])|(?:沒有|無|不是).{0,12}\bGit\b/iu.test(value ?? "");
|
|
1115
1175
|
}
|
|
1116
1176
|
|
|
1177
|
+
function workspaceRootMeansNoGit(value) {
|
|
1178
|
+
// Absence labels apply to the repository root, never to a branch/commit name.
|
|
1179
|
+
return /^\s*(?:none|not_applicable|n\/a)(?:$|\s*[;(—–])/iu.test(value ?? "") || workspaceValueMeansNoGit(value);
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1117
1182
|
function workspaceSectionClaimsNoGit(section) {
|
|
1118
|
-
return
|
|
1183
|
+
return workspaceRootMeansNoGit(workspaceFieldValue(section, "Git root"))
|
|
1119
1184
|
|| workspaceValueMeansNoGit(section);
|
|
1120
1185
|
}
|
|
1121
1186
|
|
|
1122
1187
|
function workspaceSectionClaimsGitRepository(section) {
|
|
1188
|
+
const gitRoot = workspaceFieldValue(section, "Git root");
|
|
1123
1189
|
const values = [
|
|
1124
|
-
workspaceFieldValue(section, "Git root"),
|
|
1125
1190
|
workspaceFieldValue(section, "Branch"),
|
|
1126
1191
|
workspaceFieldValue(section, "Commit")
|
|
1127
1192
|
];
|
|
1128
|
-
return
|
|
1193
|
+
return (hasSubstantiveWorkspaceValue(gitRoot) && !workspaceRootMeansNoGit(gitRoot))
|
|
1194
|
+
|| values.some((value) => hasSubstantiveWorkspaceValue(value) && !workspaceValueMeansNoGit(value));
|
|
1129
1195
|
}
|
|
1130
1196
|
|
|
1131
1197
|
function workspaceSectionClaimsVerifiedState(section) {
|
|
@@ -1173,7 +1239,7 @@ function printCloseoutStatusCard(version, result) {
|
|
|
1173
1239
|
console.log("status: complete");
|
|
1174
1240
|
console.log("✅ Done: required closeout state is complete");
|
|
1175
1241
|
console.log("🔎 QC: fresh doctor and opening-message mirror passed");
|
|
1176
|
-
console.log("📌 Handoff: opening message ready");
|
|
1242
|
+
console.log("📌 Handoff: opening message ready; next-session reception and recovery still required");
|
|
1177
1243
|
console.log("⚠️ Boundary: none");
|
|
1178
1244
|
return;
|
|
1179
1245
|
}
|
|
@@ -1201,7 +1267,26 @@ function parseArgs(args) {
|
|
|
1201
1267
|
else if (arg === "--yes" || arg === "-y") options.yes = true;
|
|
1202
1268
|
else if (arg === "--manifest") options.manifest = args[++i];
|
|
1203
1269
|
else if (arg === "--help" || arg === "-h") options.help = true;
|
|
1204
|
-
else if (arg === "--root")
|
|
1270
|
+
else if (arg === "--root") {
|
|
1271
|
+
if (options.root !== undefined || !args[i + 1] || args[i + 1].startsWith("--")) throw new Error("missing or duplicate value for --root");
|
|
1272
|
+
options.root = args[++i];
|
|
1273
|
+
}
|
|
1274
|
+
else if (["--offset", "--max-chars", "--sha256"].includes(arg)) {
|
|
1275
|
+
const key = { "--offset": "offset", "--max-chars": "maxChars", "--sha256": "sha256" }[arg];
|
|
1276
|
+
if (options[key] !== undefined || args[i + 1] === undefined || args[i + 1].startsWith("--")) throw new Error(`missing or duplicate value for ${arg}`);
|
|
1277
|
+
options[key] = args[++i];
|
|
1278
|
+
}
|
|
1279
|
+
else if (command === "commands" && arg === "--agent") {
|
|
1280
|
+
options.agent = args[++i];
|
|
1281
|
+
if (!options.agent || options.agent.startsWith("--")) throw new Error("--agent requires all, claude, gemini, codex or antigravity");
|
|
1282
|
+
}
|
|
1283
|
+
else if (command === "progress" && arg === "--background") options.background = true;
|
|
1284
|
+
else if (command === "progress" && arg === "--no-open") options.noOpen = true;
|
|
1285
|
+
else if (command === "progress" && arg === "--port") {
|
|
1286
|
+
const value = args[++i];
|
|
1287
|
+
if (!/^\d{1,5}$/.test(value ?? "") || Number(value) > 65535) throw new Error("progress --port must be 0–65535");
|
|
1288
|
+
options.port = Number(value);
|
|
1289
|
+
}
|
|
1205
1290
|
else throw new Error(`unknown option "${arg}"`);
|
|
1206
1291
|
}
|
|
1207
1292
|
|
|
@@ -1217,6 +1302,7 @@ async function needsProjectIndexVersionInject(root, command, version) {
|
|
|
1217
1302
|
}
|
|
1218
1303
|
|
|
1219
1304
|
async function runInstall(command, root, options, version) {
|
|
1305
|
+
assertCommandPaths(root); // Before recovery: recovery itself can write.
|
|
1220
1306
|
// Guard the selected root before reading or recovering any persisted
|
|
1221
1307
|
// transaction. Recovery is a write path and must not run through a junction.
|
|
1222
1308
|
await validateTransactionRoot(root, [], { createMissingRoot: false });
|
|
@@ -1284,7 +1370,7 @@ async function runInstall(command, root, options, version) {
|
|
|
1284
1370
|
|| hasNoTransactionOutputs
|
|
1285
1371
|
)) {
|
|
1286
1372
|
const noOpHealth = await assessUpgradeNoopHealth(root, version);
|
|
1287
|
-
if (noOpHealth.ok) printCard(version, "
|
|
1373
|
+
if (noOpHealth.ok) printCard(version, "installation verified", "o.o");
|
|
1288
1374
|
console.log(`command: ${command}`);
|
|
1289
1375
|
console.log(`current directory: ${process.cwd()}`);
|
|
1290
1376
|
console.log(`selected root: ${root}`);
|
|
@@ -1445,7 +1531,7 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
|
|
|
1445
1531
|
|
|
1446
1532
|
const created = outputs.filter((item) => !item.before).map((item) => item.targetRel);
|
|
1447
1533
|
const merged = outputs.filter((item) => item.before).map((item) => item.reason ? `${item.targetRel} - ${item.reason}` : item.targetRel);
|
|
1448
|
-
printCard(version, command === "upgrade" ? "upgrade verified" : "
|
|
1534
|
+
printCard(version, command === "upgrade" ? "upgrade verified" : "installation verified", "o.o");
|
|
1449
1535
|
printInstallSummary(version, command, mode, root, {
|
|
1450
1536
|
created: created.length,
|
|
1451
1537
|
merged: merged.length,
|
|
@@ -1509,7 +1595,9 @@ async function executeDirectNoClobberCreateInstall(command, root, mode, plan, ve
|
|
|
1509
1595
|
}
|
|
1510
1596
|
|
|
1511
1597
|
for (const output of outputs) {
|
|
1598
|
+
await validateTransactionRoot(root, plan, { createMissingRoot: false });
|
|
1512
1599
|
await mkdir(path.dirname(output.targetAbs), { recursive: true });
|
|
1600
|
+
assertCommandPaths(root);
|
|
1513
1601
|
await writeFile(output.targetAbs, output.after, { mode: 0o600, flag: "wx" });
|
|
1514
1602
|
const written = await readOptionalBuffer(output.targetAbs);
|
|
1515
1603
|
if (!written || sha256(written) !== output.afterHash) {
|
|
@@ -1527,7 +1615,7 @@ async function executeDirectNoClobberCreateInstall(command, root, mode, plan, ve
|
|
|
1527
1615
|
}
|
|
1528
1616
|
|
|
1529
1617
|
const created = outputs.map((item) => item.targetRel);
|
|
1530
|
-
printCard(version, "
|
|
1618
|
+
printCard(version, "installation verified", "o.o");
|
|
1531
1619
|
printInstallSummary(version, command, mode, root, {
|
|
1532
1620
|
created: created.length,
|
|
1533
1621
|
merged: 0,
|
|
@@ -1654,6 +1742,7 @@ async function buildTransactionOutputs(command, root, plan, version, options = {
|
|
|
1654
1742
|
for (const item of plan) {
|
|
1655
1743
|
if (item.action !== "create" && item.action !== "merge" && item.action !== "preserve") continue;
|
|
1656
1744
|
const before = await readOptionalBuffer(item.targetAbs);
|
|
1745
|
+
if (item.generatedText != null && item.action === "create" && before) throw new Error(`${item.targetRel}: target appeared after shortcut planning; restart the read-only plan`);
|
|
1657
1746
|
if (item.plannedInputHash && (!before || sha256(before) !== item.plannedInputHash)) {
|
|
1658
1747
|
throw new Error(`${item.targetRel}: input changed after official-region proof; restart the read-only plan`);
|
|
1659
1748
|
}
|
|
@@ -1674,7 +1763,7 @@ async function buildTransactionOutputs(command, root, plan, version, options = {
|
|
|
1674
1763
|
after = Buffer.from(before);
|
|
1675
1764
|
}
|
|
1676
1765
|
} else if (item.action === "create") {
|
|
1677
|
-
const sourceText = await readTemplateSource(command, item.sourceRel, item.targetRel, item.sourceAbs);
|
|
1766
|
+
const sourceText = item.generatedText ?? await readTemplateSource(command, item.sourceRel, item.targetRel, item.sourceAbs);
|
|
1678
1767
|
afterText = item.targetRel === "AGENTS.md" ? mergeManagedBlock("", sourceText) : sourceText;
|
|
1679
1768
|
} else if (item.action === "merge" && item.targetRel === "dev/PROJECT_INDEX.md" && item.metadataTransition === projectIndexTemplateVersionMetadataTransition) {
|
|
1680
1769
|
if (!before) throw new Error(`${item.targetRel}: template-version metadata transition disappeared before preparation`);
|
|
@@ -1722,6 +1811,9 @@ async function buildTransactionOutputs(command, root, plan, version, options = {
|
|
|
1722
1811
|
if (materializedText !== indexOutput.afterText) {
|
|
1723
1812
|
indexOutput.after = Buffer.from(materializedText, "utf8");
|
|
1724
1813
|
indexOutput.afterText = null;
|
|
1814
|
+
} else if (indexOutput.before && decodeUtf8(indexOutput.before, indexRel).text === materializedText) {
|
|
1815
|
+
indexOutput.after = Buffer.from(indexOutput.before);
|
|
1816
|
+
indexOutput.afterText = null; // Preserve mixed line endings when only shortcuts need repair.
|
|
1725
1817
|
} else {
|
|
1726
1818
|
indexOutput.afterText = materializedText;
|
|
1727
1819
|
}
|
|
@@ -1913,6 +2005,7 @@ async function prepareTransaction(root, command, version, outputs, mode, plan, a
|
|
|
1913
2005
|
command,
|
|
1914
2006
|
mode,
|
|
1915
2007
|
attemptedVersion: version,
|
|
2008
|
+
shortcutInstallContract: SHORTCUT_INSTALL_CONTRACT,
|
|
1916
2009
|
committedVersion: null,
|
|
1917
2010
|
plannedSkips: plan.filter((item) => item.action === "skip").length,
|
|
1918
2011
|
host: hostname(),
|
|
@@ -2206,6 +2299,7 @@ async function pathExists(filePath) {
|
|
|
2206
2299
|
}
|
|
2207
2300
|
|
|
2208
2301
|
async function validateTransactionRoot(root, plan, { createMissingRoot = true } = {}) {
|
|
2302
|
+
assertCommandPaths(root);
|
|
2209
2303
|
let rootStats;
|
|
2210
2304
|
try {
|
|
2211
2305
|
rootStats = await lstat(root);
|
|
@@ -2253,6 +2347,7 @@ async function validateTransactionOverlay(root, outputs) {
|
|
|
2253
2347
|
.map((item) => [item.targetRel, decodeUtf8(item.after, item.targetRel).text]));
|
|
2254
2348
|
const finalText = async (relative) => outputMap.get(relative) ?? await readOptionalText(path.join(root, relative));
|
|
2255
2349
|
const failures = [];
|
|
2350
|
+
for (const item of commandFiles()) if ((await finalText(item.file)) !== item.text) failures.push(`${item.file}: required shortcut missing or different after transaction`);
|
|
2256
2351
|
for (const target of requiredTargets) if ((await finalText(target)) == null) failures.push(`${target}: missing after transaction`);
|
|
2257
2352
|
for (const rule of requiredAnchors) {
|
|
2258
2353
|
if (preservedRuntimeTargets.has(rule.target)) continue;
|
|
@@ -2323,6 +2418,7 @@ function bridgeTextFailure(targetRel, text) {
|
|
|
2323
2418
|
}
|
|
2324
2419
|
|
|
2325
2420
|
async function atomicReplaceFromBuffer(root, targetAbs, buffer, id, expectedHash, options = {}) {
|
|
2421
|
+
assertCommandPaths(root);
|
|
2326
2422
|
const targetRel = options.targetRel ?? path.relative(root, targetAbs);
|
|
2327
2423
|
const phase = options.phase ?? "forward";
|
|
2328
2424
|
const escrowDir = options.escrowDir;
|
|
@@ -2474,6 +2570,7 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
|
|
|
2474
2570
|
}
|
|
2475
2571
|
if (!Array.isArray(journal.entries) || journal.entries.length === 0) throw new Error("upgrade journal has no valid entries; no recovery writes attempted");
|
|
2476
2572
|
if (!isStableSemver(journal.attemptedVersion ?? "")) throw new Error("upgrade journal attempted version is invalid; no recovery writes attempted");
|
|
2573
|
+
if (journal.shortcutInstallContract !== undefined && journal.shortcutInstallContract !== SHORTCUT_INSTALL_CONTRACT) throw new Error("unknown shortcut install contract; no recovery writes attempted");
|
|
2477
2574
|
const allowedStates = new Set(["prepared", "committing", "rollback-needed", "manual-recovery-required", "committed", "rolled-back"]);
|
|
2478
2575
|
if (!allowedStates.has(journal.state)) throw new Error("upgrade journal state is invalid; no recovery writes attempted");
|
|
2479
2576
|
|
|
@@ -2531,6 +2628,7 @@ async function validateRecoveryJournal(root, journal, journalPath, lockId = null
|
|
|
2531
2628
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) throw new Error("upgrade journal entry schema is invalid; no recovery writes attempted");
|
|
2532
2629
|
const allowedTarget = requiredTargets.includes(entry.targetRel)
|
|
2533
2630
|
|| upgradeStateTargets.includes(entry.targetRel)
|
|
2631
|
+
|| (journal.shortcutInstallContract === SHORTCUT_INSTALL_CONTRACT && requiredShortcutTargets.includes(entry.targetRel))
|
|
2534
2632
|
|| formalWitness?.contentPaths.has(entry.targetRel);
|
|
2535
2633
|
if (!allowedTarget || seen.has(entry.targetRel)) throw new Error("upgrade journal target is unknown or duplicated; no recovery writes attempted");
|
|
2536
2634
|
seen.add(entry.targetRel);
|
|
@@ -2774,6 +2872,7 @@ async function recoverInterruptedTransaction(root, options = {}) {
|
|
|
2774
2872
|
const doctorStatus = await runDoctor(root, journal.committedVersion, {
|
|
2775
2873
|
silentCard: true,
|
|
2776
2874
|
context: "recovered-committed-transaction-health",
|
|
2875
|
+
legacyShortcutRecovery: journal.shortcutInstallContract === undefined ? legacyShortcutRecoveryPermit : null,
|
|
2777
2876
|
skipVersionRegistryLookup: true,
|
|
2778
2877
|
allowActiveTransaction: true,
|
|
2779
2878
|
captureFormalUserRules: (state) => { formalRuntimeState = state; }
|
|
@@ -3066,6 +3165,22 @@ async function runDoctor(root, version, options = {}) {
|
|
|
3066
3165
|
return "failed";
|
|
3067
3166
|
}
|
|
3068
3167
|
|
|
3168
|
+
if (options.legacyShortcutRecovery !== legacyShortcutRecoveryPermit) {
|
|
3169
|
+
let shortcutFailures;
|
|
3170
|
+
try { shortcutFailures = planCommands(root).filter(item => item.action !== "keep").map(item => item.file); }
|
|
3171
|
+
catch (error) { shortcutFailures = [safeErrorLabel(error)]; }
|
|
3172
|
+
console.log(`\nproject shortcut checks: 1 (${commands.length} entries / ${requiredShortcutTargets.length} files)`);
|
|
3173
|
+
console.log(shortcutFailures.length ? "missing or different project shortcuts" : "ok project shortcuts ready");
|
|
3174
|
+
rows.push({target: "project shortcuts", ok: shortcutFailures.length === 0});
|
|
3175
|
+
if (shortcutFailures.length) {
|
|
3176
|
+
for (const failure of shortcutFailures) console.log(' ' + failure);
|
|
3177
|
+
printDoctorSummary(version, root, "needs-fix", {checked: rows.length, failedKind: "project shortcuts", failedCount: shortcutFailures.length,
|
|
3178
|
+
nextStep: "Kit 安裝未齊備。請執行 upgrade --dry-run;缺少的入口會一併補齊,同名差異需先處理。"});
|
|
3179
|
+
process.exitCode = 1;
|
|
3180
|
+
return "failed";
|
|
3181
|
+
}
|
|
3182
|
+
} else console.log("legacy transaction recovery: shortcut acceptance deferred to the current install plan");
|
|
3183
|
+
|
|
3069
3184
|
const archiveCasing = await checkSessionLogArchiveCasing(root);
|
|
3070
3185
|
console.log(`\nSESSION_LOG archive casing checks: 1`);
|
|
3071
3186
|
console.log(`${archiveCasing.ok ? "ok" : "missing"} dev/SESSION_LOG_archive canonical path`);
|
|
@@ -4192,6 +4307,12 @@ async function buildPlan(root, command, version = null) {
|
|
|
4192
4307
|
...(reason ? { reason } : {})
|
|
4193
4308
|
});
|
|
4194
4309
|
}
|
|
4310
|
+
for (const item of planCommands(root)) plan.push({
|
|
4311
|
+
targetRel: item.file, targetAbs: item.target, generatedText: item.text,
|
|
4312
|
+
action: item.action === 'keep' ? 'skip' : item.action,
|
|
4313
|
+
...(item.action === 'merge' ? { mergedText: item.text, plannedInputHash: item.plannedInputHash } : {}),
|
|
4314
|
+
reason: item.action === 'conflict' ? 'project shortcut differs; preserve it and resolve before installation' : item.action === 'merge' ? `verified official v${item.officialVersion} shortcut update` : 'required project shortcut'
|
|
4315
|
+
});
|
|
4195
4316
|
return plan;
|
|
4196
4317
|
}
|
|
4197
4318
|
|
|
@@ -6560,29 +6681,9 @@ function printCard(version, status, eyes) {
|
|
|
6560
6681
|
function printInstallNextSteps(root, conflictCount, mode = "first-install", skippedCount = 0, options = {}) {
|
|
6561
6682
|
console.log("");
|
|
6562
6683
|
console.log("============================================================");
|
|
6563
|
-
|
|
6564
|
-
|
|
6565
|
-
console.log("⚠️ 已補齊缺少檔案,但仍要檢查入口連接");
|
|
6566
|
-
} else {
|
|
6567
|
-
console.log("✅ 安裝完成:下一步請在 AI 對話中操作");
|
|
6568
|
-
}
|
|
6684
|
+
console.log("✅ 安裝完成:下一步請在 AI 對話中操作");
|
|
6685
|
+
console.log("✅ 專案快捷入口已就緒;進度頁可直接由 handoff-kit-progress 開啟。");
|
|
6569
6686
|
console.log("============================================================");
|
|
6570
|
-
if (conflictCount > 0) {
|
|
6571
|
-
console.log("⚠️ 狀態:有既有檔案未能證明可安全合併。");
|
|
6572
|
-
console.log("⚠️ 這不是檔案壞掉;工具已停手,沒有覆寫 conflict 檔案。");
|
|
6573
|
-
console.log(conflictRepairNextStepLine());
|
|
6574
|
-
console.log("");
|
|
6575
|
-
}
|
|
6576
|
-
if (needsPartialRepairStep) {
|
|
6577
|
-
console.log("你原本已有部分 AI 記憶檔,工具已保留它們,沒有覆寫。");
|
|
6578
|
-
console.log("下一步先不要開始新任務;請在終端機執行以下預演,讓工具檢查能否安全補入口連接:");
|
|
6579
|
-
console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run");
|
|
6580
|
-
console.log("");
|
|
6581
|
-
console.log("如預演顯示沒有 conflict,再執行:");
|
|
6582
|
-
console.log(" npx --yes @adamchanadam/agent-handoff-kit@latest upgrade");
|
|
6583
|
-
console.log("============================================================");
|
|
6584
|
-
return;
|
|
6585
|
-
}
|
|
6586
6687
|
console.log("------------------------------------------------------------");
|
|
6587
6688
|
console.log("⚠️ 下面這句不是終端機指令。");
|
|
6588
6689
|
console.log("📋 不用再留在終端機;請打開能讀寫此資料夾的 AI agent。若 AI 已在此資料夾內,新增對話後輸入:");
|
|
@@ -6618,6 +6719,7 @@ function printUpgradeNextSteps(root, conflictCount) {
|
|
|
6618
6719
|
console.log("============================================================");
|
|
6619
6720
|
return;
|
|
6620
6721
|
}
|
|
6722
|
+
console.log("✅ 專案快捷入口已就緒;進度頁可直接由 handoff-kit-progress 開啟。");
|
|
6621
6723
|
console.log("🛠️ Kit migration 已通過離線遷移驗收;已由正式 doctor 的同輪讀回確認提交與健康使用同一狀態");
|
|
6622
6724
|
console.log("============================================================");
|
|
6623
6725
|
console.log("📋 如你正在進行中的工作對話已熟悉 Agent Handoff Kit,繼續使用原本的開工方式即可,無需重新做新手引導。");
|
|
@@ -6709,7 +6811,7 @@ async function exists(filePath) {
|
|
|
6709
6811
|
}
|
|
6710
6812
|
|
|
6711
6813
|
function printHelp(version) {
|
|
6712
|
-
printCard(version, "
|
|
6814
|
+
printCard(version, "command help", "o.o");
|
|
6713
6815
|
console.log(`Agent Handoff Kit
|
|
6714
6816
|
|
|
6715
6817
|
Usage:
|
|
@@ -6717,19 +6819,29 @@ Usage:
|
|
|
6717
6819
|
agent-handoff-kit upgrade [--dry-run] [--yes] [--root <path>]
|
|
6718
6820
|
agent-handoff-kit doctor [--root <path>]
|
|
6719
6821
|
agent-handoff-kit workspace-health [--root <path>]
|
|
6822
|
+
agent-handoff-kit commands [--agent all|claude|gemini|codex|antigravity] [--root <path>] [--dry-run] [--yes]
|
|
6823
|
+
agent-handoff-kit progress [--root <path>] [--background] [--port <0-65535>] [--no-open]
|
|
6720
6824
|
agent-handoff-kit closeout-status [--root <path>]
|
|
6825
|
+
agent-handoff-kit handoff-read [--root <path>] [--max-chars <64..8192>] [--offset <n> --sha256 <digest>]
|
|
6721
6826
|
|
|
6722
6827
|
Commands:
|
|
6723
6828
|
init Plan or install missing core files and rule packs.
|
|
6829
|
+
update Check npm latest; safely upgrade this project if newer.
|
|
6724
6830
|
upgrade Preserve existing files; merge safe core updates or report conflicts.
|
|
6725
6831
|
doctor Check required installed files.
|
|
6726
6832
|
workspace-health Read live root / Git / worktree state without writing files.
|
|
6833
|
+
commands Preview or enable project-local shortcuts; existing different files are preserved.
|
|
6834
|
+
progress Open the local bilingual overview; --background starts or reuses a service and returns.
|
|
6727
6835
|
closeout-status Render the state-bound closeout card after a full closeout.
|
|
6836
|
+
handoff-read Return one bounded handoff chunk with snapshot/range metadata; no writes or network.
|
|
6837
|
+
Offset counts Unicode code points. Continue with the returned nextOffset and sha256.
|
|
6838
|
+
Ranges show content served, not reception, understanding or permission to act.
|
|
6728
6839
|
|
|
6729
6840
|
中文速讀:
|
|
6730
6841
|
✅ 第一次用:先在項目資料夾執行 init。
|
|
6731
6842
|
🔄 已裝過:執行 upgrade;若想先預覽,才加 --dry-run。
|
|
6732
6843
|
🩺 不確定狀態:用 doctor 檢查;doctor 只檢查,不會改檔。
|
|
6844
|
+
📖 想看全局:用 progress 開啟專案速覽;紀錄寫入後自動更新。
|
|
6733
6845
|
|
|
6734
6846
|
安裝之後:
|
|
6735
6847
|
不要把顯示出來的 Start Agent Handoff 或 "Work in ..." 文字輸入終端機。
|
|
@@ -6750,6 +6862,7 @@ Commands:
|
|
|
6750
6862
|
npx --yes @adamchanadam/agent-handoff-kit@latest upgrade
|
|
6751
6863
|
npx --yes @adamchanadam/agent-handoff-kit@latest doctor
|
|
6752
6864
|
npx --yes @adamchanadam/agent-handoff-kit@latest workspace-health
|
|
6865
|
+
npx --yes @adamchanadam/agent-handoff-kit@latest progress
|
|
6753
6866
|
|
|
6754
6867
|
升級前如想先看會改甚麼,才用預演:
|
|
6755
6868
|
npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run
|
package/bin/commands.mjs
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import {createHash} from 'node:crypto';
|
|
5
|
+
import {validateOfficialOriginCatalog} from './official-origin-catalog.mjs';
|
|
6
|
+
import {assetBytes,assetNames,runtimeVersion} from './progress/assets.mjs';
|
|
7
|
+
|
|
8
|
+
// One content owner; platform adapters are generated from these entries.
|
|
9
|
+
export const commands = Object.freeze([
|
|
10
|
+
{name:'handoff-kit-start',label:'開工 / Start',description:'Resume Agent Handoff Kit state when the user asks to start or resume a session.',intent:'Start Agent Handoff',body:'Follow the project AGENTS.md startup contract. This is bare continuity startup unless the user explicitly adds a task or long-run instruction. Receive the required handoff content; truncated output is incomplete and requires bounded follow-up reads before a loaded claim. Show the startup result and stop at the applicable startup boundary. Do not open the progress page, load the log, or begin the saved objective merely because this shortcut was invoked.'},
|
|
11
|
+
{name:'handoff-kit-close',label:'收工 / Wrap up',description:'Save and verify the Agent Handoff Kit handoff when the user ends the session.',intent:'Wrap up Agent Handoff',body:'Follow AGENTS.md and the closeout route in dev/RULE_PACKS.md through its complete workflow. Save and reconcile the actual handoff, log and opening mirror, then run the required closeout checks and report their actual result. Running closeout-status alone is not closeout. This shortcut grants no additional Git commit, push, release or external-write permission.'},
|
|
12
|
+
{name:'handoff-kit-progress',label:'進度頁 / Progress',description:'Open the existing Agent Handoff Kit project overview without generating a report.',intent:'Open the project progress page',body:'In the verified project root, run node dev/handoff-kit/launch.mjs --root <project-root>, quoting the root as one argument in the active shell. The normal installer supplies this local program and its assets; opening progress does not use npm, download tools or require registry access. For an integrated browser, add --no-open and open the returned loopback URL there. Verify the returned page is reachable before reporting success. If the local program is missing or damaged, identify incomplete installation rather than silently acquiring @latest or overwriting files. A platform permission failure requires the runtime’s supported approval mechanism; do not change global caches, credentials, ACLs or sandbox settings or ask the user to repair npm. Give one short result. Do not read or summarize the log for the model, generate HTML, write progress data, or change the normal record-saving schedule.'},
|
|
13
|
+
{name:'handoff-kit-align',label:'對齊治理 / Align',description:'Check a named document or scan for important documents not connected to Agent Handoff Kit.',intent:'Bridge governance / scan for unbridged governance documents',body:'Use the governance-bridge route in dev/RULE_PACKS.md and its existing owner. With a named target, review that target and its source/index/sync relationships. Without a target, perform the bounded candidate scan described by that workflow. Report gaps and proposed changes; a scan alone never authorizes edits, renames, deletes or authority merges. Apply a concrete fix only when the user has authorized its scope. This is not a Kit upgrade or a blanket rule rewrite.'},
|
|
14
|
+
{name:'handoff-kit-onboard',label:'新手引導 / Onboard',description:'Guide a user who explicitly asks to learn or start using Agent Handoff Kit.',intent:'Teach me to use Agent Handoff Kit',body:'Use the onboarding route in dev/RULE_PACKS.md. Explain in the user’s language, use their existing goal when provided, and ask only for missing information that matters. Do not reset first-use state, reinstall the Kit, or mark project work complete. Follow the existing onboarding procedure rather than inventing another questionnaire.'},
|
|
15
|
+
{name:'handoff-kit-remember',label:'保存工作規則 / Remember',description:'Route an explicitly requested future working rule into Agent Handoff Kit governance.',intent:'Connect this future working rule to Agent Handoff Kit',body:'Use the long-term governance route in dev/RULE_PACKS.md. If no rule or identifiable preceding instruction was provided, ask one short question. Locate the existing owner and writable project supplement, then merge only the authorized rule and verify its consumer route. Preserve official core/pack bodies. Do not save secrets or treat a session-log note as the durable rule owner.'},
|
|
16
|
+
{name:'handoff-kit-check',label:'檢查安裝 / Check',description:'Check the selected project’s Agent Handoff Kit installation without repairing or upgrading it.',intent:'Check Agent Handoff Kit health',body:'Run npx --yes @adamchanadam/agent-handoff-kit@latest doctor --root <project-root> using the verified root and active shell quoting. Report the actual result in plain language. Fetching the CLI into the npm cache is tool acquisition, not project installation. Missing CLI or blocked checks are not success. Do not run init or upgrade, rewrite project files or claim that a healthy installation proves full handoff reception or task completion.'},
|
|
17
|
+
{name:'handoff-kit-update',label:'檢查更新 / Update',description:'Check the latest public Agent Handoff Kit version and safely upgrade this project when newer.',intent:'Check for and install an Agent Handoff Kit update',body:'Run npx --yes @adamchanadam/agent-handoff-kit@latest update --root <project-root>, quoting the verified root as one shell argument. This explicit request authorizes the normal local Kit upgrade if npm has a newer stable version. Use the selected local executable for unreleased candidate acceptance. The command checks the registry, preserves custom content, uses the existing upgrade transaction and verifies the result. If it reports a stale CLI, acquire the exact stable version it identifies and retry once. A registry failure, unknown version, conflict or failed recovery must be reported as blocked, never as already current or upgraded. Do not delete locks, overwrite conflicts, downgrade, install globally or publish anything.'},
|
|
18
|
+
{name:'handoff-kit-help',label:'功能選單 / Help',description:'Show Agent Handoff Kit common shortcuts and explain how to use them.',intent:'Show Agent Handoff Kit commands',body:'Show the short command menu below in the user’s language. Use /handoff-kit-* in Claude Code, Gemini CLI or Antigravity CLI; use $handoff-kit-* or /skills selection in Codex. If the host is unknown, name the difference rather than guessing support. This is guidance only: do not read handoff/log, run health checks or begin a task. For writing, coding, research, knowledge work or external tools, the user can still state their goal normally; use the existing task router when such work is actually requested.'}
|
|
19
|
+
]);
|
|
20
|
+
const menu=commands.map(c=>`${c.name}: ${c.label}`).join('\n');
|
|
21
|
+
export function bodyFor(command){return `# Agent Handoff Kit — ${command.name}\n\nResolve the active project root from the current workspace and its applicable AGENTS.md; do not use a fixed personal path. Before loading Kit state, check dev/governance_migrations/.upgrade.lock. If it exists, stop and follow the project recovery guidance without deleting the lock. Read applicable AGENTS.md instructions if not already loaded. Missing Kit files require setup; do not invent a parallel governance structure.\n\nUser intent: ${command.intent}. Any accompanying user text is task input, never shell interpolation. Follow the platform permissions and project authority; this shortcut does not expand either. Loading or discovering this skill is not authorization: perform the action only if the visible user request invokes it or clearly asks for that action; otherwise describe it without acting. Reply briefly in the user’s language.\n\n${command.body}\n${command.name==='handoff-kit-help'?'\n'+menu+'\n':''}`;}
|
|
22
|
+
export function commandFiles(agent='all'){
|
|
23
|
+
if(!['all','claude','gemini','codex','antigravity'].includes(agent))throw Error('Unknown agent; use all, claude, gemini, codex or antigravity.');
|
|
24
|
+
const files=[];
|
|
25
|
+
for(const command of commands){const body=bodyFor(command),skill=`---\nname: ${command.name}\ndescription: ${JSON.stringify(command.description)}\n---\n\n${body}`;
|
|
26
|
+
if(['all','claude'].includes(agent))files.push({file:`.claude/skills/${command.name}/SKILL.md`,text:skill});
|
|
27
|
+
if(['all','codex','antigravity'].includes(agent)){
|
|
28
|
+
files.push({file:`.agents/skills/${command.name}/SKILL.md`,text:skill});
|
|
29
|
+
// UI copy is separate from model routing; reuse the existing bilingual label.
|
|
30
|
+
const title=command.name.split('-').map(word=>word[0].toUpperCase()+word.slice(1)).join(' ');
|
|
31
|
+
files.push({file:`.agents/skills/${command.name}/agents/openai.yaml`,text:`interface:\n display_name: ${JSON.stringify(title)}\n short_description: ${JSON.stringify(command.label)}\n`});
|
|
32
|
+
}
|
|
33
|
+
if(['all','gemini'].includes(agent))files.push({file:`.gemini/commands/${command.name}.toml`,text:`description = ${JSON.stringify(command.label)}\nprompt = ${JSON.stringify(body)}\n`});
|
|
34
|
+
}
|
|
35
|
+
return [...files,...progressFiles()];
|
|
36
|
+
}
|
|
37
|
+
function stat(file){try{return fs.lstatSync(file);}catch(e){if(e.code==='ENOENT')return null;throw e;}}
|
|
38
|
+
function safePath(root,relative,{directory=false}={}){
|
|
39
|
+
const segments=relative.split('/');let at=root;
|
|
40
|
+
for(let i=0;i<segments.length;i++){at=path.join(at,segments[i]);const s=stat(at);if(!s)continue;if(s.isSymbolicLink()||!((i<segments.length-1||directory)?s.isDirectory():s.isFile()))throw Error(`Unsafe path: ${relative}`);}
|
|
41
|
+
return at;
|
|
42
|
+
}
|
|
43
|
+
// Resolve existing ancestors too: a relocated global directory may itself be a link.
|
|
44
|
+
function scopePath(file){
|
|
45
|
+
let at=path.resolve(file);const tail=[];
|
|
46
|
+
while(true){try{return path.join(fs.realpathSync(at),...tail);}catch(e){if(e.code!=='ENOENT')throw e;const parent=path.dirname(at);if(parent===at)throw e;tail.unshift(path.basename(at));at=parent;}}
|
|
47
|
+
}
|
|
48
|
+
function within(base,file){const relative=path.relative(base,file);return relative===''||(!path.isAbsolute(relative)&&relative!=='..'&&!relative.startsWith('..'+path.sep));}
|
|
49
|
+
function assertProjectScope(root,files){
|
|
50
|
+
const refuse=()=>{const error=Error('Global location refused: Kit shortcuts belong in an installed project folder, not a home, drive root or shared AI configuration directory. / 快捷入口只可安裝在專案目錄,請勿選擇使用者主目錄、磁碟根目錄或 AI 全域設定位置。');error.code='ERR_COMMAND_SCOPE';throw error;};
|
|
51
|
+
const homes=[os.homedir(),process.env.HOME,process.env.USERPROFILE].filter(Boolean).map(scopePath);
|
|
52
|
+
// Environment overrides do not erase the operating system's actual home boundary.
|
|
53
|
+
try{homes.push(scopePath(os.userInfo().homedir));}catch(e){if(e.code!=='ERR_SYSTEM_ERROR')throw e;}
|
|
54
|
+
const selected=scopePath(root);
|
|
55
|
+
if(path.relative(path.parse(selected).root,selected)===''||homes.some(home=>path.relative(home,selected)===''))refuse();
|
|
56
|
+
const shared=[];
|
|
57
|
+
for(const home of homes){for(const name of ['.claude','.gemini','.agents'])shared.push({dir:path.join(home,name)});shared.push({dir:path.join(home,'.codex'),worktrees:true});}
|
|
58
|
+
if(process.env.CLAUDE_CONFIG_DIR)shared.push({dir:process.env.CLAUDE_CONFIG_DIR});
|
|
59
|
+
if(process.env.CODEX_HOME)shared.push({dir:process.env.CODEX_HOME,worktrees:true});
|
|
60
|
+
if(process.env.GEMINI_CLI_HOME){const home=scopePath(process.env.GEMINI_CLI_HOME);if(path.relative(home,selected)==='')refuse();shared.push({dir:path.join(home,'.gemini')});}
|
|
61
|
+
if(process.platform==='win32'){
|
|
62
|
+
for(const base of [process.env.ProgramFiles,process.env.PROGRAMDATA].filter(Boolean))for(const name of ['ClaudeCode','GeminiCli','gemini-cli','codex'])shared.push({dir:path.join(base,name)});
|
|
63
|
+
}else{
|
|
64
|
+
for(const dir of ['/etc/codex','/etc/claude-code','/etc/gemini-cli','/Library/Application Support/ClaudeCode','/Library/Application Support/GeminiCli'])shared.push({dir});
|
|
65
|
+
}
|
|
66
|
+
const locations=[selected,...files.map(file=>scopePath(path.join(root,file.file)))];
|
|
67
|
+
for(const entry of shared){const base=scopePath(entry.dir),worktrees=path.join(base,'worktrees');
|
|
68
|
+
for(const location of locations){
|
|
69
|
+
if(!within(base,location))continue;
|
|
70
|
+
// Codex-managed checkouts remain project-scoped; the worktree container is not a project.
|
|
71
|
+
if(entry.worktrees&&within(worktrees,selected)&&path.relative(worktrees,selected)!=='')continue;
|
|
72
|
+
refuse();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
// Shared, read-only installer boundary. Missing project roots are allowed here;
|
|
77
|
+
// the standalone commands route still requires an installed, unlocked Kit.
|
|
78
|
+
export function assertCommandPaths(root,files=commandFiles()){
|
|
79
|
+
root=path.resolve(root);assertProjectScope(root,files);
|
|
80
|
+
const s=stat(root);if(s&&(!s.isDirectory()||s.isSymbolicLink()))throw Error('Select a non-linked project root; a symbolic link or junction is not supported.');
|
|
81
|
+
if(path.relative(scopePath(root),root)!=='')throw Error('Linked project root is not supported.');
|
|
82
|
+
for(const item of files)safePath(root,item.file);
|
|
83
|
+
}
|
|
84
|
+
let shortcutCatalog;
|
|
85
|
+
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
86
|
+
function officialShortcutVersion(file, bytes){
|
|
87
|
+
if(!shortcutCatalog){const c=JSON.parse(fs.readFileSync(new URL('./migration-baselines/official-origin-catalog.json',import.meta.url),'utf8'));validateOfficialOriginCatalog(c);shortcutCatalog=c;}
|
|
88
|
+
const sha=digest(bytes);
|
|
89
|
+
return Object.entries(shortcutCatalog.generatedShortcuts??{}).find(([,entry])=>entry.files[file]===sha)?.[0]??null;
|
|
90
|
+
}
|
|
91
|
+
export function planCommands(root,agent='all'){
|
|
92
|
+
root=path.resolve(root);const files=commandFiles(agent);assertCommandPaths(root,files);
|
|
93
|
+
return files.map(item=>{
|
|
94
|
+
const target=safePath(root,item.file),s=stat(target);
|
|
95
|
+
if(!s)return{...item,target,action:'create'};
|
|
96
|
+
const bytes=fs.readFileSync(target);
|
|
97
|
+
if(bytes.equals(Buffer.from(item.text)))return{...item,target,action:'keep'};
|
|
98
|
+
const officialVersion=officialShortcutVersion(item.file,bytes);
|
|
99
|
+
return{...item,target,action:officialVersion?'merge':'conflict',...(officialVersion?{officialVersion,plannedInputHash:digest(bytes)}:{})};
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
function assertRoot(root,files){assertCommandPaths(root,files);const s=stat(root);if(!s?.isDirectory()||s.isSymbolicLink())throw Error('Select an existing, non-linked project root.');const canonical=fs.realpathSync(root);if(path.relative(canonical,root)!=='')throw Error('Linked project root is not supported.');
|
|
103
|
+
safePath(root,'dev', {directory:true});
|
|
104
|
+
if(stat(path.join(root,'dev/governance_migrations/.upgrade.lock')))throw Error('Upgrade lock exists; recover the Kit upgrade before installing commands.');
|
|
105
|
+
for(const f of ['AGENTS.md','dev/SESSION_HANDOFF.md'])if(!stat(safePath(root,f)))throw Error('Select an installed Kit project before enabling commands.');
|
|
106
|
+
}
|
|
107
|
+
export function installCommands({root,agent='all',yes=false,dryRun=false}){
|
|
108
|
+
root=path.resolve(root);const files=commandFiles(agent);assertRoot(root,files);
|
|
109
|
+
const plan=planCommands(root,agent);
|
|
110
|
+
if(plan.some(p=>p.action==='merge'))return{status:'upgrade-required',written:[],plan:plan.map(({file,action})=>({file,action}))};
|
|
111
|
+
if(plan.some(p=>p.action==='conflict'))return{status:'conflict',written:[],plan:plan.map(({file,action})=>({file,action}))};
|
|
112
|
+
if(dryRun||!yes)return{status:'preview',written:[],plan:plan.map(({file,action})=>({file,action}))};
|
|
113
|
+
const written=[];
|
|
114
|
+
try{for(const item of plan){assertRoot(root,files);safePath(root,item.file);if(item.action==='keep')continue;
|
|
115
|
+
// Create-only: even a concurrent writer cannot be overwritten by this command.
|
|
116
|
+
fs.mkdirSync(path.dirname(item.target),{recursive:true});safePath(root,item.file);
|
|
117
|
+
try{fs.writeFileSync(item.target,item.text,{encoding:'utf8',flag:'wx'});written.push(item.file);}catch(e){if(e.code==='EEXIST'&&stat(item.target)?.isFile()&&!stat(item.target)?.isSymbolicLink()&&fs.readFileSync(item.target,'utf8')===item.text)continue;throw e;}
|
|
118
|
+
}
|
|
119
|
+
for(const item of plan){safePath(root,item.file);if(fs.readFileSync(item.target,'utf8')!==item.text)throw Error('Readback changed: '+item.file);}
|
|
120
|
+
}catch(e){const error=new Error(`Command setup interrupted after ${written.length} files; existing files preserved. Rerun preview to inspect remaining paths. ${e.message}`);error.written=written;throw error;}
|
|
121
|
+
return{status:'ready',written,plan:plan.map(({file,action})=>({file,action}))};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Generated support files use the same exact-byte ownership and transaction as entries.
|
|
125
|
+
let cachedProgressFiles;
|
|
126
|
+
export function progressFiles(){
|
|
127
|
+
if(!cachedProgressFiles){
|
|
128
|
+
const names=['launch','open','server','projection','dashboard','project-version'];
|
|
129
|
+
const data=Object.fromEntries(assetNames.map(name=>[name,assetBytes(name).toString('base64')]));
|
|
130
|
+
const assets=`// Generated from the shipped Dashboard. Do not edit.\nexport const installed=true;\nexport const runtimeVersion=${JSON.stringify(runtimeVersion)};\nconst data=${JSON.stringify(data)};\nexport const assetNames=Object.freeze(Object.keys(data));\nexport function assetBytes(name){if(!Object.hasOwn(data,name))throw Error('Unknown progress asset');return Buffer.from(data[name],'base64');}\n`;
|
|
131
|
+
cachedProgressFiles=[...names.map(name=>({file:`dev/handoff-kit/${name}.mjs`,text:fs.readFileSync(new URL(`./progress/${name}.mjs`,import.meta.url),'utf8')})),{file:'dev/handoff-kit/assets.mjs',text:assets}];
|
|
132
|
+
}
|
|
133
|
+
return cachedProgressFiles.map(item=>({...item}));
|
|
134
|
+
}
|