@adamchanadam/agent-handoff-kit 0.4.1 → 0.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +21 -21
  2. package/README.en.md +1 -1
  3. package/README.md +1 -1
  4. package/bin/agent-handoff-kit.mjs +7107 -6887
  5. package/bin/commands.mjs +134 -134
  6. package/bin/handoff-read.mjs +88 -88
  7. package/bin/installed-file-contract.mjs +154 -90
  8. package/bin/migration-baselines/official-origin-catalog.json +514 -1
  9. package/bin/official-origin-catalog.mjs +294 -267
  10. package/bin/progress/ICON-LICENSE.txt +21 -21
  11. package/bin/progress/assets.mjs +6 -6
  12. package/bin/progress/dashboard.mjs +134 -134
  13. package/bin/progress/icons.svg +36 -36
  14. package/bin/progress/index.html +31 -31
  15. package/bin/progress/launch.mjs +40 -40
  16. package/bin/progress/open.mjs +43 -43
  17. package/bin/progress/project-version.mjs +121 -121
  18. package/bin/progress/projection.mjs +144 -144
  19. package/bin/progress/renderer.js +152 -152
  20. package/bin/progress/server.mjs +78 -78
  21. package/bin/progress/styles.css +31 -31
  22. package/bin/prompt-mirror-core.mjs +84 -84
  23. package/bin/upgrade-inventory.mjs +243 -243
  24. package/bin/user-rules-router.mjs +4 -4
  25. package/docs/commands.md +2 -2
  26. package/docs/progress.md +73 -73
  27. package/package.json +22 -22
  28. package/packs/agent-governance.md +120 -120
  29. package/packs/closeout.md +91 -91
  30. package/packs/coding.md +28 -28
  31. package/packs/integrations.md +20 -20
  32. package/packs/knowledge.md +3 -3
  33. package/packs/onboarding.md +43 -39
  34. package/packs/research.md +30 -30
  35. package/packs/safety.md +2 -2
  36. package/runtime-core/AGENTS.core.md +161 -147
  37. package/runtime-core/CLAUDE.md +13 -13
  38. package/runtime-core/DOC_SYNC_REGISTRY.md +24 -24
  39. package/runtime-core/GEMINI.md +17 -17
  40. package/runtime-core/PROJECT_DECISIONS.md +43 -43
  41. package/runtime-core/PROJECT_INDEX.md +16 -16
  42. package/runtime-core/RULE_PACKS.md +1 -1
  43. package/runtime-core/SESSION_HANDOFF.md +180 -180
  44. package/runtime-core/SESSION_LOG.md +37 -37
  45. package/runtime-core/START_NEXT_SESSION_PROMPT.txt +1 -1
  46. package/runtime-core/USER_RULES_ENTRY.md +2 -0
package/bin/commands.mjs CHANGED
@@ -1,134 +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
- }
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. Give one short result that includes the exact returned loopback URL. 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. 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. Keep each durable rule in one authoritative location; resolve conflicts there using the project\'s existing authority order, without duplicating the rule or creating a compromise rule. 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. For unreleased-candidate acceptance, pass the controlled general registry on the same `npx --registry <loopback> ...` invocation, so the CLI launched by npx inherits it for the update lookup. A project `.npmrc` config readback is setup metadata, not inheritance evidence, and a direct Node run is insufficient. 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. Read applicable AGENTS.md instructions if not already loaded, then follow its \`Upgrade lock guard\` before loading Kit state. 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
+ }
@@ -1,88 +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
- }
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
+ }