@adamchanadam/agent-handoff-kit 0.3.66 → 0.4.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.
@@ -10,6 +10,7 @@ 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 { readHandoffChunk, formatHandoffChunk } from "./handoff-read.mjs";
13
14
  import { freshInstallMappings, installedFileContract, installedMappings, requiredInstalledTargets, upgradeStateMappings, upgradeStateTargets } from "./installed-file-contract.mjs";
14
15
  import { getArtifactBoundManagedSegment, getOfficialBaseline, identifyOfficialOrigin, loadOfficialOriginCatalog } from "./official-origin-catalog.mjs";
15
16
  import {
@@ -569,14 +570,26 @@ async function main() {
569
570
  const version = await readPackageVersion();
570
571
  // `doctor` renders version alignment itself. Let that single health run own
571
572
  // 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);
573
+ if (!new Set(["closeout-status", "doctor", "workspace-health", "progress", "commands", "handoff-read"]).has(command)) await maybePrintUpdateNotice(version);
573
574
  if (!command || options.help) {
575
+ if (command === "handoff-read") {
576
+ 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.");
577
+ return;
578
+ }
574
579
  printHelp(version);
575
580
  return;
576
581
  }
577
582
 
578
583
  const root = path.resolve(options.root ?? process.cwd());
579
584
 
585
+ if (command === "handoff-read") {
586
+ if (["dryRun", "yes", "manifest"].some(key => Object.hasOwn(options, key))) throw new Error("handoff-read accepts only --root, --offset, --max-chars and --sha256");
587
+ output.write(formatHandoffChunk(readHandoffChunk(root, options)));
588
+ return;
589
+ }
590
+
591
+ if (["offset", "maxChars", "sha256"].some(key => options[key] !== undefined)) throw new Error("chunk options require handoff-read");
592
+
580
593
  if (command === "init" || command === "upgrade") {
581
594
  await runInstall(command, root, options, version);
582
595
  return;
@@ -592,6 +605,31 @@ async function main() {
592
605
  return;
593
606
  }
594
607
 
608
+ if (command === "commands") {
609
+ const { installCommands } = await import("./commands.mjs");
610
+ const result = installCommands({ root, agent: options.agent ?? "all", yes: options.yes, dryRun: options.dryRun });
611
+ console.log("Agent Handoff Kit — Shortcuts / 快捷入口: " + result.status);
612
+ for (const item of result.plan) console.log(item.action + " " + item.file);
613
+ if (result.status === "conflict") { console.error("Existing command differs; no files written. Review the named conflict. / 同名入口有差異,未寫入任何檔案。"); process.exitCode = 1; }
614
+ else if (result.status === "preview") console.log("Preview only. Add --yes to enable. / 只作預覽,加 --yes 才啟用。");
615
+ else console.log("Ready. Reload your agent if needed. / 已啟用,必要時重新載入 AI。Claude / Gemini / Antigravity: /handoff-kit-help · Codex: $handoff-kit-help or /skills");
616
+ return;
617
+ }
618
+
619
+ if (command === "progress") {
620
+ if (options.background) {
621
+ const { openProgress } = await import("./progress/open.mjs");
622
+ const result = await openProgress({ root, port: options.port ?? 0, openBrowser: !options.noOpen, version });
623
+ console.log("Agent Handoff Kit — Project overview / 專案速覽\n" + result.url + "\n" + (result.reused ? "Reused local service. / 已重用服務。" : "Started local service. / 已啟動服務。"));
624
+ return;
625
+ }
626
+ const { startProgress, PROGRESS_IDLE_MS } = await import("./progress/server.mjs");
627
+ await startProgress({ root, port: options.port ?? 0, openBrowser: !options.noOpen, version, onReady: ({ url }) => {
628
+ 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 可立即停止。`);
629
+ } });
630
+ return;
631
+ }
632
+
595
633
  if (command === "workspace-health") {
596
634
  runWorkspaceHealth(root);
597
635
  return;
@@ -706,7 +744,7 @@ function assessHandoffSufficiency(text) {
706
744
  const match = new RegExp(`^(?:[-*]\\s+)?${escapeRegExp(label)}:\\s*(.*)$`, "iu").exec(line);
707
745
  return match ? [match[1].trim()] : [];
708
746
  });
709
- const affirmative = (value) => /^yes(?:$|[\s.;:—–-])/iu.test(value);
747
+ const affirmative = (value) => /^yes(?:$|[\s,.;:—–-])/iu.test(value);
710
748
  const answers = fields("Answer");
711
749
  const evidence = fields("Reconstruction evidence");
712
750
  const findings = [];
@@ -1055,7 +1093,7 @@ function assessHandoffWorkspaceIdentity(handoffText, health) {
1055
1093
 
1056
1094
  const gitRootValue = workspaceFieldValue(section, "Git root");
1057
1095
  if (hasSubstantiveWorkspaceValue(gitRootValue)
1058
- && !workspaceValueMeansNoGit(gitRootValue)
1096
+ && !workspaceRootMeansNoGit(gitRootValue)
1059
1097
  && !workspaceTextIncludesPath(gitRootValue, health.gitRoot)) {
1060
1098
  findings.push(`Workspace: handoff Git root does not match live Git root ${health.gitRoot}`);
1061
1099
  }
@@ -1114,18 +1152,24 @@ function workspaceValueMeansNoGit(value) {
1114
1152
  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
1153
  }
1116
1154
 
1155
+ function workspaceRootMeansNoGit(value) {
1156
+ // Absence labels apply to the repository root, never to a branch/commit name.
1157
+ return /^\s*(?:none|not_applicable|n\/a)(?:$|\s*[;(—–])/iu.test(value ?? "") || workspaceValueMeansNoGit(value);
1158
+ }
1159
+
1117
1160
  function workspaceSectionClaimsNoGit(section) {
1118
- return workspaceValueMeansNoGit(workspaceFieldValue(section, "Git root"))
1161
+ return workspaceRootMeansNoGit(workspaceFieldValue(section, "Git root"))
1119
1162
  || workspaceValueMeansNoGit(section);
1120
1163
  }
1121
1164
 
1122
1165
  function workspaceSectionClaimsGitRepository(section) {
1166
+ const gitRoot = workspaceFieldValue(section, "Git root");
1123
1167
  const values = [
1124
- workspaceFieldValue(section, "Git root"),
1125
1168
  workspaceFieldValue(section, "Branch"),
1126
1169
  workspaceFieldValue(section, "Commit")
1127
1170
  ];
1128
- return values.some((value) => hasSubstantiveWorkspaceValue(value) && !workspaceValueMeansNoGit(value));
1171
+ return (hasSubstantiveWorkspaceValue(gitRoot) && !workspaceRootMeansNoGit(gitRoot))
1172
+ || values.some((value) => hasSubstantiveWorkspaceValue(value) && !workspaceValueMeansNoGit(value));
1129
1173
  }
1130
1174
 
1131
1175
  function workspaceSectionClaimsVerifiedState(section) {
@@ -1173,7 +1217,7 @@ function printCloseoutStatusCard(version, result) {
1173
1217
  console.log("status: complete");
1174
1218
  console.log("✅ Done: required closeout state is complete");
1175
1219
  console.log("🔎 QC: fresh doctor and opening-message mirror passed");
1176
- console.log("📌 Handoff: opening message ready");
1220
+ console.log("📌 Handoff: opening message ready; next-session reception and recovery still required");
1177
1221
  console.log("⚠️ Boundary: none");
1178
1222
  return;
1179
1223
  }
@@ -1201,7 +1245,26 @@ function parseArgs(args) {
1201
1245
  else if (arg === "--yes" || arg === "-y") options.yes = true;
1202
1246
  else if (arg === "--manifest") options.manifest = args[++i];
1203
1247
  else if (arg === "--help" || arg === "-h") options.help = true;
1204
- else if (arg === "--root") options.root = args[++i];
1248
+ else if (arg === "--root") {
1249
+ if (options.root !== undefined || !args[i + 1] || args[i + 1].startsWith("--")) throw new Error("missing or duplicate value for --root");
1250
+ options.root = args[++i];
1251
+ }
1252
+ else if (["--offset", "--max-chars", "--sha256"].includes(arg)) {
1253
+ const key = { "--offset": "offset", "--max-chars": "maxChars", "--sha256": "sha256" }[arg];
1254
+ if (options[key] !== undefined || args[i + 1] === undefined || args[i + 1].startsWith("--")) throw new Error(`missing or duplicate value for ${arg}`);
1255
+ options[key] = args[++i];
1256
+ }
1257
+ else if (command === "commands" && arg === "--agent") {
1258
+ options.agent = args[++i];
1259
+ if (!options.agent || options.agent.startsWith("--")) throw new Error("--agent requires all, claude, gemini, codex or antigravity");
1260
+ }
1261
+ else if (command === "progress" && arg === "--background") options.background = true;
1262
+ else if (command === "progress" && arg === "--no-open") options.noOpen = true;
1263
+ else if (command === "progress" && arg === "--port") {
1264
+ const value = args[++i];
1265
+ if (!/^\d{1,5}$/.test(value ?? "") || Number(value) > 65535) throw new Error("progress --port must be 0–65535");
1266
+ options.port = Number(value);
1267
+ }
1205
1268
  else throw new Error(`unknown option "${arg}"`);
1206
1269
  }
1207
1270
 
@@ -1284,7 +1347,7 @@ async function runInstall(command, root, options, version) {
1284
1347
  || hasNoTransactionOutputs
1285
1348
  )) {
1286
1349
  const noOpHealth = await assessUpgradeNoopHealth(root, version);
1287
- if (noOpHealth.ok) printCard(version, "continuity ready", "o.o");
1350
+ if (noOpHealth.ok) printCard(version, "installation verified", "o.o");
1288
1351
  console.log(`command: ${command}`);
1289
1352
  console.log(`current directory: ${process.cwd()}`);
1290
1353
  console.log(`selected root: ${root}`);
@@ -1445,7 +1508,7 @@ async function executeInstallTransaction(command, root, mode, plan, version, can
1445
1508
 
1446
1509
  const created = outputs.filter((item) => !item.before).map((item) => item.targetRel);
1447
1510
  const merged = outputs.filter((item) => item.before).map((item) => item.reason ? `${item.targetRel} - ${item.reason}` : item.targetRel);
1448
- printCard(version, command === "upgrade" ? "upgrade verified" : "continuity ready", "o.o");
1511
+ printCard(version, command === "upgrade" ? "upgrade verified" : "installation verified", "o.o");
1449
1512
  printInstallSummary(version, command, mode, root, {
1450
1513
  created: created.length,
1451
1514
  merged: merged.length,
@@ -1527,7 +1590,7 @@ async function executeDirectNoClobberCreateInstall(command, root, mode, plan, ve
1527
1590
  }
1528
1591
 
1529
1592
  const created = outputs.map((item) => item.targetRel);
1530
- printCard(version, "continuity ready", "o.o");
1593
+ printCard(version, "installation verified", "o.o");
1531
1594
  printInstallSummary(version, command, mode, root, {
1532
1595
  created: created.length,
1533
1596
  merged: 0,
@@ -3494,7 +3557,7 @@ async function checkHandoffTemperatureBoundary(root) {
3494
3557
  return { ok: findings.length === 0, checked: 1, findings };
3495
3558
  }
3496
3559
 
3497
- const rootMismatchGuard = "If this root does not match the expected project root";
3560
+ const rootMismatchGuard = "If the root does not match the handoff";
3498
3561
 
3499
3562
  function currentStateEvidenceRules() {
3500
3563
  return [
@@ -3790,52 +3853,47 @@ function isOwnedOpeningLifecycleBoilerplate(line) {
3790
3853
  || /^Upgrade never resets consumed \/ not_applicable first-use state back to eligible\./i.test(line);
3791
3854
  }
3792
3855
 
3793
- function stripResolvedNegatedActionClauses(line) {
3794
- return line.split(/(?<=[.;;。])\s*/).filter((clause) => {
3795
- const negated = /\b(?:no|not|never|without|did not|has not|have not)\b/i.test(clause);
3796
- const action = /\b(?:commit|push|tag|release|publish|deploy|deployment|sync|write|upgrade)\b/i.test(clause);
3797
- return !(negated && action);
3798
- }).join(" ");
3799
- }
3800
-
3801
3856
  const ignoredLifecycleEnglish = new Set([
3802
- "completed", "complete", "finish", "finished", "continue", "incomplete", "passed", "verified", "pending", "blocked", "follow", "scope",
3803
- "monitor", "only", "reopened", "recommended", "next", "step", "session", "current", "work", "task", "with",
3804
- "from", "that", "this", "handoff", "lifecycle", "migration", "regression", "agent", "reason", "condition",
3805
- "the", "and", "for", "into", "still", "remains"
3857
+ "completed", "complete", "finish", "finished", "continue", "resume", "incomplete", "passed", "pass", "verified", "verify",
3858
+ "pending", "blocked", "limited", "failed", "done", "resolved", "unresolved", "successful", "successfully", "success", "run",
3859
+ "the", "and", "is", "are", "was", "were", "has", "have", "been", "not", "no", "yet", "still", "remains", "remain"
3806
3860
  ]);
3807
3861
 
3808
- function lifecycleEnglishTokens(line, stripNegated = false) {
3809
- const source = stripNegated ? stripResolvedNegatedActionClauses(line) : line;
3810
- return (source.toLowerCase().match(/[a-z0-9][a-z0-9_-]{2,}/g) ?? [])
3811
- .filter((token) => !ignoredLifecycleEnglish.has(token));
3862
+ function lifecycleAssertionClauses(line) {
3863
+ // A status belongs to its clause, not every topic in a Completed/QC paragraph.
3864
+ // Keep file extensions and dotted versions intact; separate contrast clauses.
3865
+ return line.split(/[;;](?!\s*(?:condition|trigger|missing evidence|reason|條件|觸發條件|缺少證據|原因)\s*[::])|[。!?!?]+|\.(?=\s|$)|\b(?:but|however|whereas|while)\b|(?:但|不過|然而)/i)
3866
+ .map((clause) => clause.trim().replace(/^[,,\s]+|[,,\s]+$/g, ""))
3867
+ .filter(Boolean);
3812
3868
  }
3813
3869
 
3814
- function lifecycleTopicWindows(line, stripNegated = false) {
3815
- const source = stripNegated ? stripResolvedNegatedActionClauses(line) : line;
3816
- const englishTokens = lifecycleEnglishTokens(source);
3817
- const english = Array.from({ length: Math.max(0, englishTokens.length - 2) }, (_, index) => englishTokens.slice(index, index + 3).join(" "));
3818
- const chineseRuns = source.match(/[\u3400-\u9fff]{6,}/g) ?? [];
3819
- const chinese = chineseRuns.flatMap((run) => Array.from({ length: Math.max(0, run.length - 5) }, (_, index) => run.slice(index, index + 6)));
3820
- return new Set([...english, ...chinese]);
3870
+ function isAffirmativeLifecycleAssertion(clause) {
3871
+ // Word boundaries matter: incomplete, unverified and unsuccessful are not
3872
+ // positive results. Recording a limitation is not completing that work.
3873
+ const assertion = clause.replace(/\b(?:without|no)\s+(?:errors?|failures?|issues?|blockers?)\b/gi, "");
3874
+ if (/\b(?:not|never|without|incomplete|unverified|unsuccessful|unresolved|pending|blocked|limited|failed|missing)\b|(?:尚未|未曾|未完成|未通過|未驗證|未核對|不代表|不涵蓋|沒有|仍需|待驗|受限|受阻)/i.test(assertion)) return false;
3875
+ return /\b(?:completed?|finished|pass(?:ed)?|verified|done|resolved|success(?:ful)?)\b|(?:已完成|完成|通過|已驗證|已核對|已解決)/i.test(assertion);
3821
3876
  }
3822
3877
 
3823
- function lifecycleShortChineseCore(line, stripNegated = false) {
3824
- const rawSource = stripNegated ? stripResolvedNegatedActionClauses(line) : line;
3825
- const source = rawSource.split(/(?:\s+[—–-]\s*)?(?:reason|condition)\s*[::]|(?:原因|條件)\s*[::]/i)[0];
3826
- const ignored = /(後續追蹤|只監察|尚未完成|已經完成|重新開啟|完成|已驗證|繼續|下一步|待辦|尚未|未完成|通過|風險|受阻|重開|監察|追蹤|修復|修補|修正)/g;
3827
- const core = (source.match(/[\u3400-\u9fff]+/g) ?? []).join("").replace(ignored, "");
3828
- return core.length >= 2 && core.length <= 5 ? core : null;
3878
+ function lifecycleAssertionCore(clause) {
3879
+ const source = openingLifecycleDirectiveText(clause)
3880
+ .replace(/^checks run this session\s*[::]\s*/i, "")
3881
+ .replace(/^(?:non[- ]?blocking|risk|非阻擋|非阻塞|風險)\s*[::—-]\s*/i, "")
3882
+ .replace(/\b(?:without|no)\s+(?:errors?|failures?|issues?|blockers?)\b/gi, "")
3883
+ .replace(/\s+(?:in\s+the\s+)?next\s+(?:session|round)\s*$/i, "")
3884
+ .split(/(?:\b(?:reason|condition|evidence)|原因|條件|證據)\s*[::]/i)[0]
3885
+ .replace(/(?:尚未完成|已經完成|已完成|未完成|已驗證|未驗證|已核對|未核對|已通過|未通過|尚未|仍然|仍|完成|通過|繼續|待辦|受阻)/g, "");
3886
+ const tokens = (source.toLowerCase().match(/[a-z0-9][a-z0-9_-]*|[\u3400-\u9fff]+/g) ?? [])
3887
+ .filter((token) => !ignoredLifecycleEnglish.has(token));
3888
+ return tokens.join(" ");
3829
3889
  }
3830
3890
 
3831
- function lifecycleTopicsOverlap(left, right) {
3832
- const leftWindows = lifecycleTopicWindows(left, true);
3833
- if ([...lifecycleTopicWindows(right)].some((window) => leftWindows.has(window))) return true;
3834
- const leftEnglish = lifecycleEnglishTokens(left, true);
3835
- const rightEnglish = lifecycleEnglishTokens(right);
3836
- if (leftEnglish.length === 2 && rightEnglish.length === 2 && leftEnglish.join(" ") === rightEnglish.join(" ")) return true;
3837
- const leftChinese = lifecycleShortChineseCore(left, true);
3838
- return Boolean(leftChinese && leftChinese === lifecycleShortChineseCore(right));
3891
+ function lifecycleAssertionsMatch(left, right) {
3892
+ // Shared product names / paths / three-word windows are not proof of the
3893
+ // same acceptance scope. Only a complete normalized assertion core matches.
3894
+ // This is a conservative mechanical guard, not natural-language adjudication.
3895
+ const core = lifecycleAssertionCore(left);
3896
+ return core.length >= 2 && core === lifecycleAssertionCore(right);
3839
3897
  }
3840
3898
 
3841
3899
  function isExplicitLifecycleReclassification(line) {
@@ -3892,23 +3950,29 @@ function findHandoffLifecycleContradictions(text) {
3892
3950
  ...handoffStateLines(text, "completed-this-session", "Completed This Session")
3893
3951
  .map((line) => ({ section: "Completed This Session", line })),
3894
3952
  ...handoffStateLines(text, "validation-qc", "Validation / QC")
3895
- .filter((line) => /(pass|passed|verified|complete|success|通過|完成|已驗證|已核對)/i.test(line))
3896
3953
  .map((line) => ({ section: "Validation / QC", line }))
3897
- ];
3954
+ ].flatMap((entry) => lifecycleAssertionClauses(entry.line)
3955
+ .filter(isAffirmativeLifecycleAssertion)
3956
+ .map((assertion) => ({ ...entry, assertion })));
3898
3957
  const carryForward = [
3899
3958
  ...handoffStateLines(text, "next-priorities", "Next Priorities")
3900
3959
  .map((line) => ({ section: "Next Priorities", line })),
3901
3960
  ...handoffStateLines(text, "risks-blockers", "Risks / Blockers")
3902
3961
  .map((line) => ({ section: "Risks / Blockers", line })),
3903
3962
  ...handoffStateLines(text, "next-session-opening-message", "Next Session Opening Message")
3904
- .filter((line) => isOpeningLifecycleCarryForwardLine(line))
3905
3963
  .map((line) => ({ section: "Next Session Opening Message", line }))
3906
3964
  ];
3907
3965
  const findings = [];
3908
3966
  for (const pending of carryForward) {
3909
- if (isResolvedCarryForwardStatement(pending.line) || isExplicitLifecycleReclassification(pending.line)) continue;
3910
- for (const done of resolved) {
3911
- if (lifecycleTopicsOverlap(done.line, pending.line)) findings.push({ resolved: done, carryForward: pending });
3967
+ for (const assertion of lifecycleAssertionClauses(pending.line)) {
3968
+ if (pending.section === "Next Session Opening Message" && !isOpeningLifecycleCarryForwardLine(assertion)) continue;
3969
+ // Risks may repeat a completed local fact to explain an unrelated limit.
3970
+ // Next Priorities still rejects completed work listed as a next action.
3971
+ if (pending.section === "Risks / Blockers" && isAffirmativeLifecycleAssertion(assertion)) continue;
3972
+ if (isResolvedCarryForwardStatement(assertion) || isExplicitLifecycleReclassification(assertion)) continue;
3973
+ for (const done of resolved) {
3974
+ if (lifecycleAssertionsMatch(done.assertion, assertion)) findings.push({ resolved: done, carryForward: pending });
3975
+ }
3912
3976
  }
3913
3977
  }
3914
3978
  return findings;
@@ -5565,15 +5629,82 @@ function migrateSessionHandoff(targetText, sourceText, context = {}) {
5565
5629
  const targetPrompt = targetSection.match(/```text\s*\r?\n([\s\S]*?)\r?\n```/);
5566
5630
  const sourcePrompt = sourceSection.match(/```text\s*\r?\n([\s\S]*?)\r?\n```/);
5567
5631
  if (!targetPrompt || !sourcePrompt) return null;
5568
- const existingRoot = targetPrompt[1].match(/^Work in (.+?)\. Read AGENTS\.md,/m)?.[1] ?? "<absolute project root>";
5569
- const currentPrompt = sourcePrompt[1].replace("<absolute project root>", existingRoot);
5570
- const updatedSection = targetSection.replace(targetPrompt[0], `\`\`\`text\n${currentPrompt}\n\`\`\``);
5632
+ // The opening message carries user state. Upgrade must never regenerate it
5633
+ // from a blank template. A historical official opening may be a whole
5634
+ // multi-line block (and its first line materializes the local root), so
5635
+ // replace only a catalog-proven official prefix. Any remaining paragraph is
5636
+ // user-owned and survives byte-for-content through the migration.
5637
+ const sourceInstruction = sourcePrompt[1].split(/\r?\n/).find((line) => line.startsWith("Resume the current objective. A plain "));
5638
+ const officialOpeningPrefixes = new Set();
5639
+ const officialInstructions = new Set();
5640
+ for (const [version, release] of Object.entries(context.officialCatalog?.releases ?? {})) {
5641
+ if (!release.source?.npm?.integrity || compareSemver(version, context.currentVersion) > 0) continue;
5642
+ const baseline = getOfficialBaseline({ version, targetRel: "dev/SESSION_HANDOFF.md", catalog: context.officialCatalog });
5643
+ const opening = baseline?.state === "present" ? extractOpeningMessage(baseline.text) : null;
5644
+ if (opening) officialOpeningPrefixes.add(normalizeOfficialOpeningPrefix(opening));
5645
+ for (const line of opening?.split(/\r?\n/) ?? []) {
5646
+ if (line.startsWith("Resume the current objective. A plain ")) officialInstructions.add(line);
5647
+ }
5648
+ }
5649
+ let currentPrompt = replaceOfficialOpeningPrefix(
5650
+ targetPrompt[1],
5651
+ sourcePrompt[1],
5652
+ officialOpeningPrefixes
5653
+ ) ?? targetPrompt[1].split(/(\r?\n)/).map((line) => (
5654
+ sourceInstruction && officialInstructions.has(line) ? sourceInstruction : line
5655
+ )).join("");
5656
+ currentPrompt = restoreMissingCurrentOpeningLines(currentPrompt, sourcePrompt[1]);
5657
+ const updatedSection = targetSection.replace(targetPrompt[1], () => currentPrompt);
5571
5658
  merged = `${merged.slice(0, targetBounds.start)}${updatedSection}${merged.slice(targetBounds.end)}`;
5572
5659
 
5573
5660
  const temperatureRepair = repairHandoffCurrentStateEvidenceBoundary(merged);
5574
5661
  return temperatureRepair.text;
5575
5662
  }
5576
5663
 
5664
+ function normalizeOfficialOpeningPrefix(text) {
5665
+ return text
5666
+ .replace(/\r\n?/g, "\n")
5667
+ .replace(/^(Work in )[^\n]+?(\.(?: Read AGENTS\.md, then dev\/SESSION_HANDOFF\.md\.)?)$/m, "$1<ROOT>$2");
5668
+ }
5669
+
5670
+ function replaceOfficialOpeningPrefix(targetPrompt, sourcePrompt, officialPrefixes) {
5671
+ const targetLines = targetPrompt.replace(/\r\n?/g, "\n").split("\n");
5672
+ for (const prefix of [...officialPrefixes].sort((left, right) => right.length - left.length)) {
5673
+ const prefixLines = prefix.split("\n");
5674
+ if (targetLines.length < prefixLines.length) continue;
5675
+ if (normalizeOfficialOpeningPrefix(targetLines.slice(0, prefixLines.length).join("\n")) !== prefix) continue;
5676
+ const userOwnedSuffix = targetLines.slice(prefixLines.length).join("\n");
5677
+ return userOwnedSuffix ? `${sourcePrompt}\n${userOwnedSuffix}` : sourcePrompt;
5678
+ }
5679
+ return null;
5680
+ }
5681
+
5682
+ function restoreMissingCurrentOpeningLines(targetPrompt, sourcePrompt) {
5683
+ const sourceLines = sourcePrompt.replace(/\r\n?/g, "\n").split("\n");
5684
+ const targetLines = targetPrompt.replace(/\r\n?/g, "\n").split("\n");
5685
+ const sourceKeys = sourceLines.map(normalizeOfficialOpeningPrefix);
5686
+ const countKey = (lines, key) => lines.filter((line) => normalizeOfficialOpeningPrefix(line) === key).length;
5687
+
5688
+ for (let sourceIndex = 0; sourceIndex < sourceLines.length; sourceIndex += 1) {
5689
+ const sourceLine = sourceLines[sourceIndex];
5690
+ const sourceKey = sourceKeys[sourceIndex];
5691
+ if (!sourceLine.trim() || countKey(sourceLines, sourceKey) !== 1 || countKey(targetLines, sourceKey) !== 0) continue;
5692
+
5693
+ const previousKey = sourceKeys.slice(0, sourceIndex).reverse().find((key, offset) => (
5694
+ sourceLines[sourceIndex - offset - 1].trim() && countKey(sourceLines, key) === 1 && countKey(targetLines, key) === 1
5695
+ ));
5696
+ const nextKey = sourceKeys.slice(sourceIndex + 1).find((key, offset) => (
5697
+ sourceLines[sourceIndex + offset + 1].trim() && countKey(sourceLines, key) === 1 && countKey(targetLines, key) === 1
5698
+ ));
5699
+ if (!previousKey || !nextKey) continue;
5700
+ const previousIndex = targetLines.findIndex((line) => normalizeOfficialOpeningPrefix(line) === previousKey);
5701
+ const nextIndex = targetLines.findIndex((line) => normalizeOfficialOpeningPrefix(line) === nextKey);
5702
+ if (previousIndex < 0 || nextIndex < 0 || previousIndex >= nextIndex) continue;
5703
+ targetLines.splice(previousIndex + 1, 0, sourceLine);
5704
+ }
5705
+ return targetLines.join("\n");
5706
+ }
5707
+
5577
5708
  function migrateSessionLog(targetText, sourceText) {
5578
5709
  let merged = mergeSessionLogTemplateContract(targetText, sourceText);
5579
5710
  if (!merged) return null;
@@ -6641,7 +6772,7 @@ async function exists(filePath) {
6641
6772
  }
6642
6773
 
6643
6774
  function printHelp(version) {
6644
- printCard(version, "continuity ready", "o.o");
6775
+ printCard(version, "command help", "o.o");
6645
6776
  console.log(`Agent Handoff Kit
6646
6777
 
6647
6778
  Usage:
@@ -6649,19 +6780,28 @@ Usage:
6649
6780
  agent-handoff-kit upgrade [--dry-run] [--yes] [--root <path>]
6650
6781
  agent-handoff-kit doctor [--root <path>]
6651
6782
  agent-handoff-kit workspace-health [--root <path>]
6783
+ agent-handoff-kit commands [--agent all|claude|gemini|codex|antigravity] [--root <path>] [--dry-run] [--yes]
6784
+ agent-handoff-kit progress [--root <path>] [--background] [--port <0-65535>] [--no-open]
6652
6785
  agent-handoff-kit closeout-status [--root <path>]
6786
+ agent-handoff-kit handoff-read [--root <path>] [--max-chars <64..8192>] [--offset <n> --sha256 <digest>]
6653
6787
 
6654
6788
  Commands:
6655
6789
  init Plan or install missing core files and rule packs.
6656
6790
  upgrade Preserve existing files; merge safe core updates or report conflicts.
6657
6791
  doctor Check required installed files.
6658
6792
  workspace-health Read live root / Git / worktree state without writing files.
6793
+ commands Preview or enable project-local shortcuts; existing different files are preserved.
6794
+ progress Open the local bilingual overview; --background starts or reuses a service and returns.
6659
6795
  closeout-status Render the state-bound closeout card after a full closeout.
6796
+ handoff-read Return one bounded handoff chunk with snapshot/range metadata; no writes or network.
6797
+ Offset counts Unicode code points. Continue with the returned nextOffset and sha256.
6798
+ Ranges show content served, not reception, understanding or permission to act.
6660
6799
 
6661
6800
  中文速讀:
6662
6801
  ✅ 第一次用:先在項目資料夾執行 init。
6663
6802
  🔄 已裝過:執行 upgrade;若想先預覽,才加 --dry-run。
6664
6803
  🩺 不確定狀態:用 doctor 檢查;doctor 只檢查,不會改檔。
6804
+ 📖 想看全局:用 progress 開啟專案速覽;紀錄寫入後自動更新。
6665
6805
 
6666
6806
  安裝之後:
6667
6807
  不要把顯示出來的 Start Agent Handoff 或 "Work in ..." 文字輸入終端機。
@@ -6682,6 +6822,7 @@ Commands:
6682
6822
  npx --yes @adamchanadam/agent-handoff-kit@latest upgrade
6683
6823
  npx --yes @adamchanadam/agent-handoff-kit@latest doctor
6684
6824
  npx --yes @adamchanadam/agent-handoff-kit@latest workspace-health
6825
+ npx --yes @adamchanadam/agent-handoff-kit@latest progress
6685
6826
 
6686
6827
  升級前如想先看會改甚麼,才用預演:
6687
6828
  npx --yes @adamchanadam/agent-handoff-kit@latest upgrade --dry-run
@@ -0,0 +1,86 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+
5
+ // One content owner; platform adapters are generated from these entries.
6
+ export const commands = Object.freeze([
7
+ {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.'},
8
+ {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.'},
9
+ {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 npx --yes @adamchanadam/agent-handoff-kit@latest progress --background --root <project-root>. Quote the root as one argument using the active shell. This may fetch the CLI into the npm cache; it does not run project init or upgrade. Use an explicitly selected local candidate executable during unreleased development. If tool acquisition fails, report that failure without changing Kit state. The command reuses or starts the local service and opens the browser. If the host has an integrated browser tool, --no-open may be used and the returned loopback URL opened there. 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.'},
10
+ {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.'},
11
+ {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.'},
12
+ {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.'},
13
+ {name:'handoff-kit-check',label:'檢查 Kit / 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.'},
14
+ {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.'}
15
+ ]);
16
+ const menu=commands.map(c=>`${c.name}: ${c.label}`).join('\n');
17
+ 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':''}`;}
18
+ export function commandFiles(agent='all'){
19
+ if(!['all','claude','gemini','codex','antigravity'].includes(agent))throw Error('Unknown agent; use all, claude, gemini, codex or antigravity.');
20
+ const files=[];
21
+ for(const command of commands){const body=bodyFor(command),skill=`---\nname: ${command.name}\ndescription: ${JSON.stringify(command.description)}\n---\n\n${body}`;
22
+ if(['all','claude'].includes(agent))files.push({file:`.claude/skills/${command.name}/SKILL.md`,text:skill});
23
+ if(['all','codex','antigravity'].includes(agent))files.push({file:`.agents/skills/${command.name}/SKILL.md`,text:skill});
24
+ if(['all','gemini'].includes(agent))files.push({file:`.gemini/commands/${command.name}.toml`,text:`description = ${JSON.stringify(command.label)}\nprompt = ${JSON.stringify(body)}\n`});
25
+ }
26
+ return files;
27
+ }
28
+ function stat(file){try{return fs.lstatSync(file);}catch(e){if(e.code==='ENOENT')return null;throw e;}}
29
+ function safePath(root,relative,{directory=false}={}){
30
+ const segments=relative.split('/');let at=root;
31
+ 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}`);}
32
+ return at;
33
+ }
34
+ // Resolve existing ancestors too: a relocated global directory may itself be a link.
35
+ function scopePath(file){
36
+ let at=path.resolve(file);const tail=[];
37
+ 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;}}
38
+ }
39
+ function within(base,file){const relative=path.relative(base,file);return relative===''||(!path.isAbsolute(relative)&&relative!=='..'&&!relative.startsWith('..'+path.sep));}
40
+ function assertProjectScope(root,files){
41
+ 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;};
42
+ const homes=[os.homedir(),process.env.HOME,process.env.USERPROFILE].filter(Boolean).map(scopePath);
43
+ // Environment overrides do not erase the operating system's actual home boundary.
44
+ try{homes.push(scopePath(os.userInfo().homedir));}catch(e){if(e.code!=='ERR_SYSTEM_ERROR')throw e;}
45
+ const selected=scopePath(root);
46
+ if(path.relative(path.parse(selected).root,selected)===''||homes.some(home=>path.relative(home,selected)===''))refuse();
47
+ const shared=[];
48
+ 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});}
49
+ if(process.env.CLAUDE_CONFIG_DIR)shared.push({dir:process.env.CLAUDE_CONFIG_DIR});
50
+ if(process.env.CODEX_HOME)shared.push({dir:process.env.CODEX_HOME,worktrees:true});
51
+ 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')});}
52
+ if(process.platform==='win32'){
53
+ 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)});
54
+ }else{
55
+ for(const dir of ['/etc/codex','/etc/claude-code','/etc/gemini-cli','/Library/Application Support/ClaudeCode','/Library/Application Support/GeminiCli'])shared.push({dir});
56
+ }
57
+ const locations=[selected,...files.map(file=>scopePath(path.join(root,file.file)))];
58
+ for(const entry of shared){const base=scopePath(entry.dir),worktrees=path.join(base,'worktrees');
59
+ for(const location of locations){
60
+ if(!within(base,location))continue;
61
+ // Codex-managed checkouts remain project-scoped; the worktree container is not a project.
62
+ if(entry.worktrees&&within(worktrees,selected)&&path.relative(worktrees,selected)!=='')continue;
63
+ refuse();
64
+ }
65
+ }
66
+ }
67
+ function assertRoot(root,files){assertProjectScope(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.');
68
+ safePath(root,'dev', {directory:true});
69
+ if(stat(path.join(root,'dev/governance_migrations/.upgrade.lock')))throw Error('Upgrade lock exists; recover the Kit upgrade before installing commands.');
70
+ 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.');
71
+ }
72
+ export function installCommands({root,agent='all',yes=false,dryRun=false}){
73
+ root=path.resolve(root);const files=commandFiles(agent);assertRoot(root,files);
74
+ const plan=files.map(item=>{const target=safePath(root,item.file),s=stat(target);return{...item,target,action:!s?'create':fs.readFileSync(target,'utf8')===item.text?'keep':'conflict'};});
75
+ if(plan.some(p=>p.action==='conflict'))return{status:'conflict',written:[],plan:plan.map(({file,action})=>({file,action}))};
76
+ if(dryRun||!yes)return{status:'preview',written:[],plan:plan.map(({file,action})=>({file,action}))};
77
+ const written=[];
78
+ try{for(const item of plan){assertRoot(root,files);safePath(root,item.file);if(item.action==='keep')continue;
79
+ // Create-only: even a concurrent writer cannot be overwritten by this command.
80
+ fs.mkdirSync(path.dirname(item.target),{recursive:true});safePath(root,item.file);
81
+ 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;}
82
+ }
83
+ for(const item of plan){safePath(root,item.file);if(fs.readFileSync(item.target,'utf8')!==item.text)throw Error('Readback changed: '+item.file);}
84
+ }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;}
85
+ return{status:'ready',written,plan:plan.map(({file,action})=>({file,action}))};
86
+ }
@@ -0,0 +1,88 @@
1
+ // Read-only transport for a handoff. Returned ranges are not proof that an AI
2
+ // received, understood, or is authorized to act on the document.
3
+ import { constants, closeSync, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from "node:fs";
4
+ import { createHash } from "node:crypto";
5
+ import path from "node:path";
6
+
7
+ export function readHandoffChunk(selectedRoot, options = {}) {
8
+ const offset = unsignedInteger(options.offset ?? "0", "offset");
9
+ const maxChars = unsignedInteger(options.maxChars ?? "4000", "max-chars");
10
+ if (maxChars < 64 || maxChars > 8192) throw new Error("max-chars must be between 64 and 8192");
11
+ const expected = options.sha256;
12
+ if (expected !== undefined && !/^[a-f0-9]{64}$/.test(expected)) throw new Error("sha256 must be a lowercase SHA-256 digest");
13
+ if (offset > 0 && expected === undefined) throw new Error("continuation requires --sha256 from the first chunk");
14
+
15
+ // Root aliases are supported (for example /tmp on macOS). Expose both paths
16
+ // so the caller can verify the canonical root against the intended workspace.
17
+ // Links below that root are rejected, not followed into another workspace.
18
+ const requestedRoot = path.resolve(selectedRoot);
19
+ const root = realpathSync(requestedRoot);
20
+ assertSafeRoot(root);
21
+ const target = path.join(root, "dev", "SESSION_HANDOFF.md");
22
+ const before = lstatSync(target, { bigint: true });
23
+ if (!before.isFile() || before.isSymbolicLink()) throw new Error("handoff must be a regular file, not a link");
24
+ const descriptor = openSync(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
25
+ let bytes;
26
+ try {
27
+ const opened = fstatSync(descriptor, { bigint: true });
28
+ if (!sameIdentity(before, opened)) throw new Error("handoff changed before reading; restart at offset 0");
29
+ bytes = readFileSync(descriptor);
30
+ const after = fstatSync(descriptor, { bigint: true });
31
+ assertSafeRoot(root);
32
+ const current = lstatSync(target, { bigint: true });
33
+ if (!sameIdentity(before, after) || !sameIdentity(before, current) || BigInt(bytes.length) !== after.size) {
34
+ throw new Error("handoff changed while reading; restart at offset 0");
35
+ }
36
+ } finally {
37
+ closeSync(descriptor);
38
+ }
39
+
40
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
41
+ if (expected !== undefined && expected !== sha256) throw new Error("handoff snapshot changed; discard mixed coverage and restart at offset 0");
42
+ let decoded;
43
+ try { decoded = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes); }
44
+ catch { throw new Error("handoff is not valid UTF-8; no content returned"); }
45
+ const characters = Array.from(decoded);
46
+ const total = characters.length;
47
+ if (offset > total || (offset === total && total > 0)) throw new Error("offset must identify content within the handoff");
48
+ const end = Math.min(total, offset + maxChars);
49
+ return Object.freeze({
50
+ requestedRoot, root, file: "dev/SESSION_HANDOFF.md", sha256, offset, end, total,
51
+ nextOffset: end < total ? end : null,
52
+ text: characters.slice(offset, end).join("")
53
+ });
54
+ }
55
+
56
+ export function formatHandoffChunk(chunk) {
57
+ const metadata = JSON.stringify({ requestedRoot: chunk.requestedRoot, root: chunk.root, file: chunk.file, sha256: chunk.sha256, offset: chunk.offset, end: chunk.end, total: chunk.total, unit: "Unicode code points", nextOffset: chunk.nextOffset });
58
+ return `AHK_HANDOFF_BEGIN ${metadata}\n${chunk.text}\nAHK_HANDOFF_END ${chunk.sha256} ${chunk.offset}:${chunk.end}/${chunk.total}\n`;
59
+ }
60
+
61
+ function unsignedInteger(value, name) {
62
+ const text = String(value);
63
+ if (!/^(0|[1-9][0-9]*)$/.test(text) || !Number.isSafeInteger(Number(text))) throw new Error(`${name} must be a non-negative safe integer`);
64
+ return Number(text);
65
+ }
66
+
67
+ function inspect(target) {
68
+ try { return lstatSync(target); }
69
+ catch (error) { if (error.code === "ENOENT") return null; throw error; }
70
+ }
71
+
72
+ function assertSafeRoot(root) {
73
+ if (!lstatSync(root).isDirectory()) throw new Error("root must be an existing directory");
74
+ const dev = inspect(path.join(root, "dev"));
75
+ if (!dev?.isDirectory() || dev.isSymbolicLink()) throw new Error("dev must be an existing directory inside root, not a link");
76
+ const migrations = inspect(path.join(root, "dev", "governance_migrations"));
77
+ if (migrations && (!migrations.isDirectory() || migrations.isSymbolicLink())) throw new Error("governance_migrations must not be a link or non-directory");
78
+ if (inspect(path.join(root, "dev", "governance_migrations", ".upgrade.lock"))) {
79
+ throw new Error("upgrade lock exists; do not read handoff; resume the authorized upgrade recovery first");
80
+ }
81
+ }
82
+
83
+ function sameIdentity(left, right) {
84
+ // Windows path metadata may report dev=0 while the open handle reports its
85
+ // volume ID. Compare a device ID only when both probes expose one.
86
+ const sameDevice = left.dev === 0n || right.dev === 0n || left.dev === right.dev;
87
+ return sameDevice && right.isFile() && !right.isSymbolicLink() && ["ino", "size", "mtimeNs", "ctimeNs"].every(key => left[key] === right[key]);
88
+ }