@adamchanadam/agent-handoff-kit 0.3.67 → 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,
@@ -6709,7 +6772,7 @@ async function exists(filePath) {
6709
6772
  }
6710
6773
 
6711
6774
  function printHelp(version) {
6712
- printCard(version, "continuity ready", "o.o");
6775
+ printCard(version, "command help", "o.o");
6713
6776
  console.log(`Agent Handoff Kit
6714
6777
 
6715
6778
  Usage:
@@ -6717,19 +6780,28 @@ Usage:
6717
6780
  agent-handoff-kit upgrade [--dry-run] [--yes] [--root <path>]
6718
6781
  agent-handoff-kit doctor [--root <path>]
6719
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]
6720
6785
  agent-handoff-kit closeout-status [--root <path>]
6786
+ agent-handoff-kit handoff-read [--root <path>] [--max-chars <64..8192>] [--offset <n> --sha256 <digest>]
6721
6787
 
6722
6788
  Commands:
6723
6789
  init Plan or install missing core files and rule packs.
6724
6790
  upgrade Preserve existing files; merge safe core updates or report conflicts.
6725
6791
  doctor Check required installed files.
6726
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.
6727
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.
6728
6799
 
6729
6800
  中文速讀:
6730
6801
  ✅ 第一次用:先在項目資料夾執行 init。
6731
6802
  🔄 已裝過:執行 upgrade;若想先預覽,才加 --dry-run。
6732
6803
  🩺 不確定狀態:用 doctor 檢查;doctor 只檢查,不會改檔。
6804
+ 📖 想看全局:用 progress 開啟專案速覽;紀錄寫入後自動更新。
6733
6805
 
6734
6806
  安裝之後:
6735
6807
  不要把顯示出來的 Start Agent Handoff 或 "Work in ..." 文字輸入終端機。
@@ -6750,6 +6822,7 @@ Commands:
6750
6822
  npx --yes @adamchanadam/agent-handoff-kit@latest upgrade
6751
6823
  npx --yes @adamchanadam/agent-handoff-kit@latest doctor
6752
6824
  npx --yes @adamchanadam/agent-handoff-kit@latest workspace-health
6825
+ npx --yes @adamchanadam/agent-handoff-kit@latest progress
6753
6826
 
6754
6827
  升級前如想先看會改甚麼,才用預演:
6755
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
+ }