@yunhozz/arc 0.3.3 → 0.3.5

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 (126) hide show
  1. package/MANIFEST.sha256 +80 -122
  2. package/README.md +3 -3
  3. package/claude/skill/SKILL.md +1 -0
  4. package/claude/skill/references/coordination.md +5 -3
  5. package/claude/skill/references/git-recovery.md +5 -0
  6. package/claude/skill/references/handoff-prep.md +6 -8
  7. package/claude/skill/references/handoff.md +4 -4
  8. package/claude/skill/references/planning.md +5 -0
  9. package/claude/skill/references/worktree-creation.md +14 -0
  10. package/codex/skill/references/coordination.md +5 -3
  11. package/codex/skill/references/git-recovery.md +1 -5
  12. package/codex/skill/references/worktree-creation.md +20 -0
  13. package/lib/installer/manifest.mjs +10 -9
  14. package/lib/installer/package-references.mjs +2 -2
  15. package/lib/installer/plan.mjs +3 -1
  16. package/lib/installer/skill-sources.mjs +23 -0
  17. package/lib/installer/superpowers.mjs +5 -5
  18. package/lib/runtime/bootstrap.mjs +1 -1
  19. package/lib/runtime/local-cli.mjs +10 -20
  20. package/lib/runtime/role-bridge.mjs +2 -4
  21. package/lib/runtime/role-dispatch-policy.mjs +4 -9
  22. package/lib/runtime/role-routing.mjs +1 -2
  23. package/lib/watch/dispatch.mjs +10 -2
  24. package/lib/watch/git.mjs +4 -2
  25. package/lib/watch/index.mjs +16 -8
  26. package/lib/watch/model.mjs +8 -4
  27. package/lib/watch/normalize-claude.mjs +83 -6
  28. package/lib/watch/normalize-codex.mjs +15 -11
  29. package/lib/watch/render.mjs +73 -19
  30. package/lib/watch/scope.mjs +5 -5
  31. package/lib/watch/watcher.mjs +110 -10
  32. package/package.json +2 -1
  33. package/scripts/check-installer-parity.mjs +3 -1
  34. package/scripts/update-manifest.mjs +1 -1
  35. package/scripts/update-runtime-assets.mjs +1 -1
  36. package/{codex → shared}/skill/references/handoff-worktree.md +17 -16
  37. package/{codex → shared}/skill/runtime/bootstrap.mjs +1 -1
  38. package/{codex → shared}/skill/runtime/local-cli.mjs +10 -20
  39. package/{codex → shared}/skill/runtime/role-bridge.mjs +2 -4
  40. package/{claude → shared}/skill/runtime/role-dispatch-policy.mjs +4 -9
  41. package/{claude → shared}/skill/runtime/role-routing.mjs +1 -2
  42. package/claude/skill/runtime/bootstrap.mjs +0 -38
  43. package/claude/skill/runtime/local-cli.mjs +0 -248
  44. package/claude/skill/runtime/role-bridge.mjs +0 -227
  45. package/codex/skill/references/brainstorming.md +0 -316
  46. package/codex/skill/references/builder-check-prompt.md +0 -23
  47. package/codex/skill/references/scripts/frame-template.html +0 -213
  48. package/codex/skill/references/scripts/helper.js +0 -167
  49. package/codex/skill/references/scripts/server.cjs +0 -723
  50. package/codex/skill/references/scripts/start-server.sh +0 -216
  51. package/codex/skill/references/scripts/stop-server.sh +0 -120
  52. package/codex/skill/references/superpowers-LICENSE +0 -21
  53. package/codex/skill/references/superpowers-provenance.json +0 -26
  54. package/codex/skill/references/test-driven-development.md +0 -330
  55. package/codex/skill/references/visual-companion.md +0 -299
  56. package/codex/skill/references/writing-good-tests.md +0 -198
  57. package/codex/skill/references/writing-plans.md +0 -204
  58. package/codex/skill/runtime/acceptance.mjs +0 -68
  59. package/codex/skill/runtime/adapters/claude.mjs +0 -86
  60. package/codex/skill/runtime/adapters/codex.mjs +0 -65
  61. package/codex/skill/runtime/assignment.mjs +0 -42
  62. package/codex/skill/runtime/capabilities.mjs +0 -44
  63. package/codex/skill/runtime/cli.mjs +0 -8
  64. package/codex/skill/runtime/command.mjs +0 -38
  65. package/codex/skill/runtime/cooperative-schema.mjs +0 -87
  66. package/codex/skill/runtime/cooperative.mjs +0 -239
  67. package/codex/skill/runtime/evaluate.mjs +0 -331
  68. package/codex/skill/runtime/external.mjs +0 -51
  69. package/codex/skill/runtime/gate.mjs +0 -71
  70. package/codex/skill/runtime/git-evidence.mjs +0 -258
  71. package/codex/skill/runtime/git-query.mjs +0 -88
  72. package/codex/skill/runtime/identity.mjs +0 -49
  73. package/codex/skill/runtime/operations.mjs +0 -6
  74. package/codex/skill/runtime/role-bridge-args.mjs +0 -148
  75. package/codex/skill/runtime/role-dispatch-policy.mjs +0 -110
  76. package/codex/skill/runtime/role-dispatch-store.mjs +0 -134
  77. package/codex/skill/runtime/role-observe.mjs +0 -299
  78. package/codex/skill/runtime/role-policy.json +0 -654
  79. package/codex/skill/runtime/role-routing-config.mjs +0 -19
  80. package/codex/skill/runtime/role-routing.mjs +0 -233
  81. package/codex/skill/runtime/role-supervisor.mjs +0 -356
  82. package/codex/skill/runtime/schema.mjs +0 -98
  83. package/codex/skill/runtime/scope.mjs +0 -36
  84. package/codex/skill/runtime/store.mjs +0 -94
  85. package/codex/skill/runtime/target-preparation.mjs +0 -110
  86. package/codex/skill/runtime/verification.mjs +0 -125
  87. /package/{claude → shared}/skill/references/brainstorming.md +0 -0
  88. /package/{claude → shared}/skill/references/builder-check-prompt.md +0 -0
  89. /package/{claude → shared}/skill/references/scripts/frame-template.html +0 -0
  90. /package/{claude → shared}/skill/references/scripts/helper.js +0 -0
  91. /package/{claude → shared}/skill/references/scripts/server.cjs +0 -0
  92. /package/{claude → shared}/skill/references/scripts/start-server.sh +0 -0
  93. /package/{claude → shared}/skill/references/scripts/stop-server.sh +0 -0
  94. /package/{claude → shared}/skill/references/superpowers-LICENSE +0 -0
  95. /package/{claude → shared}/skill/references/superpowers-provenance.json +0 -0
  96. /package/{claude → shared}/skill/references/test-driven-development.md +0 -0
  97. /package/{claude → shared}/skill/references/visual-companion.md +0 -0
  98. /package/{claude → shared}/skill/references/writing-good-tests.md +0 -0
  99. /package/{claude → shared}/skill/references/writing-plans.md +0 -0
  100. /package/{claude → shared}/skill/runtime/acceptance.mjs +0 -0
  101. /package/{claude → shared}/skill/runtime/adapters/claude.mjs +0 -0
  102. /package/{claude → shared}/skill/runtime/adapters/codex.mjs +0 -0
  103. /package/{claude → shared}/skill/runtime/assignment.mjs +0 -0
  104. /package/{claude → shared}/skill/runtime/capabilities.mjs +0 -0
  105. /package/{claude → shared}/skill/runtime/cli.mjs +0 -0
  106. /package/{claude → shared}/skill/runtime/command.mjs +0 -0
  107. /package/{claude → shared}/skill/runtime/cooperative-schema.mjs +0 -0
  108. /package/{claude → shared}/skill/runtime/cooperative.mjs +0 -0
  109. /package/{claude → shared}/skill/runtime/evaluate.mjs +0 -0
  110. /package/{claude → shared}/skill/runtime/external.mjs +0 -0
  111. /package/{claude → shared}/skill/runtime/gate.mjs +0 -0
  112. /package/{claude → shared}/skill/runtime/git-evidence.mjs +0 -0
  113. /package/{claude → shared}/skill/runtime/git-query.mjs +0 -0
  114. /package/{claude → shared}/skill/runtime/identity.mjs +0 -0
  115. /package/{claude → shared}/skill/runtime/operations.mjs +0 -0
  116. /package/{claude → shared}/skill/runtime/role-bridge-args.mjs +0 -0
  117. /package/{claude → shared}/skill/runtime/role-dispatch-store.mjs +0 -0
  118. /package/{claude → shared}/skill/runtime/role-observe.mjs +0 -0
  119. /package/{claude → shared}/skill/runtime/role-policy.json +0 -0
  120. /package/{claude → shared}/skill/runtime/role-routing-config.mjs +0 -0
  121. /package/{claude → shared}/skill/runtime/role-supervisor.mjs +0 -0
  122. /package/{claude → shared}/skill/runtime/schema.mjs +0 -0
  123. /package/{claude → shared}/skill/runtime/scope.mjs +0 -0
  124. /package/{claude → shared}/skill/runtime/store.mjs +0 -0
  125. /package/{claude → shared}/skill/runtime/target-preparation.mjs +0 -0
  126. /package/{claude → shared}/skill/runtime/verification.mjs +0 -0
@@ -1,13 +1,14 @@
1
1
  import {validateAgentTemplates} from '../prompts/render.mjs';
2
2
  import {COOPERATIVE_RUNTIME_MODULES} from '../runtime/bootstrap.mjs';
3
3
  import {RUNTIME_MODULE_PATHS} from './runtime-assets.mjs';
4
+ import {composeSkillSources} from './skill-sources.mjs';
4
5
  import {POLICY_TARGETS,buildPolicyOutputs} from '../policy/render.mjs';
5
- import {validateFlatReferenceFiles,REFERENCE_PATH_MAP} from './superpowers.mjs';
6
+ import {validateFlatReferenceFiles} from './superpowers.mjs';
6
7
  import path from 'node:path';import crypto from 'node:crypto';import{loadModelConfig,resolveModelSettings,renderProfiles}from '../models/index.mjs';import{readCheckedFile,typeOf,sameIdentity,metadataOf}from './targets.mjs';
7
8
  export class PayloadValidationError extends Error{constructor(message,options){super(message,options);this.name='PayloadValidationError';this.code='ARC_PAYLOAD_VALIDATION';}}
8
9
  const MUTABLE=new Set(['codex/skill/models.toml','claude/skill/models.toml']);
9
10
  export const LOCAL_UPDATER_PATH='scripts/update-superpowers-local.sh';
10
- const ROOTS=['bin','lib','scripts','vendor','prebuilds','codex/skill','codex/agents','claude/skill','claude/agents'];
11
+ const ROOTS=['bin','lib','scripts','vendor','prebuilds','shared/skill','codex/skill','codex/agents','claude/skill','claude/agents'];
11
12
  const FIXED=['README.md','install.command','package.json','native/binding.c','native/binding.gyp'];
12
13
  function safeName(name){return typeof name==='string'&&name.length>0&&!name.includes('\\')&&!name.includes('\0')&&!name.startsWith('/')&&name.split('/').every(p=>p&&p!=='.'&&p!=='..')&&path.posix.normalize(name)===name;}
13
14
  function allowed(name){return FIXED.includes(name)||ROOTS.some(root=>name.startsWith(root+'/'));}
@@ -27,7 +28,7 @@ export function verifyPayload({packageRoot,safeFs,payloadMode='auto'}){
27
28
  let root;try{
28
29
  root=safeFs.openRoot(packageRoot);const source=sourcePayload(root,payloadMode),manifest=readCheckedFile(root,'MANIFEST.sha256').bytes;let text;try{text=new TextDecoder('utf-8',{fatal:true}).decode(manifest);}catch{throw Error('Manifest is not UTF-8');}
29
30
  const listed=new Map();for(const line of text.split(/\r?\n/)){if(!line)continue;const m=/^([a-fA-F0-9]{64}) (.+)$/.exec(line);if(!m||!safeName(m[2]))throw Error('Malformed or escaping manifest path');const name=m[2];if(MUTABLE.has(name)||name===LOCAL_UPDATER_PATH||!allowed(name)||name.split('/').includes('.DS_Store')||listed.has(name))throw Error(`Duplicate, mutable or unexpected manifest entry: ${name}`);listed.set(name,m[1].toLowerCase());}
30
- const files=new Map(),snapshot=new Map(),referenceTrees={};
31
+ const files=new Map(),snapshot=new Map();
31
32
  function walk(directory,prefix){const before=directory.stat();for(const name of directory.readDir()){
32
33
  const relative=prefix?prefix+'/'+name:name;const stat=directory.lstat(name),type=typeOf(stat);
33
34
  if(relative===LOCAL_UPDATER_PATH){if(!source)throw Error('Local updater wrapper is forbidden in package payload');if(type!==0o100000||!sameIdentity(stat,directory.lstat(name)))throw Error('Local updater wrapper must be a stable regular file');continue;}
@@ -38,14 +39,14 @@ export function verifyPayload({packageRoot,safeFs,payloadMode='auto'}){
38
39
  }if(!sameIdentity(before,directory.stat()))throw Error('Payload directory changed while reading');}
39
40
  function select(relative,isTree){const parts=relative.split('/');let parent=root;const opened=[];try{for(const component of parts.slice(0,-1)){let st;try{st=parent.lstat(component);}catch(e){if(e.code==='ENOENT')return;throw e;}if(typeOf(st)!==0o040000)throw Error('Unsafe payload parent');const next=parent.openDir(component);if(!sameIdentity(st,next.stat())){next.close();throw Error('Payload parent changed');}opened.push(next);parent=next;}const name=parts.at(-1);let st;try{st=parent.lstat(name);}catch(e){if(e.code==='ENOENT')return;throw e;}if(isTree){if(typeOf(st)!==0o040000)throw Error('Payload root is not a directory');const sub=parent.openDir(name);try{if(!sameIdentity(st,sub.stat()))throw Error('Payload root changed');snapshot.set(relative,{...metadataOf(st),type:'directory'});walk(sub,relative);}finally{sub.close();}}else{if(typeOf(st)!==0o100000)throw Error('Payload file is not regular');const item=readCheckedFile(parent,name,st);if(!listed.has(relative)||crypto.createHash('sha256').update(item.bytes).digest('hex')!==listed.get(relative))throw Error(`Missing entry or hash mismatch: ${relative}`);files.set(relative,item.bytes);snapshot.set(relative,item.metadata);}}finally{for(const h of opened.reverse())h.close();}}
40
41
  for(const item of FIXED)select(item,false);for(const item of ROOTS)select(item,true);
41
- for(const platform of ['codex','claude'])referenceTrees[platform]=validateFlatReferenceFiles(files,platform);
42
- for(const{destination}of REFERENCE_PATH_MAP)if(!referenceTrees.codex.entries.get(destination).bytes.equals(referenceTrees.claude.entries.get(destination).bytes))throw Error('Imported platform parity mismatch: '+destination);
42
+ for(const platform of ['codex','claude'])composeSkillSources(files,platform);
43
+ const referenceTree=validateFlatReferenceFiles(files);
43
44
  for(const name of listed.keys())if(!files.has(name))throw Error(`Manifest entry is missing: ${name}`);
44
45
  const required=['lib/prompts/agent-fragments.json','lib/prompts/render.mjs','lib/policy/role-policy.json','lib/policy/render.mjs','scripts/update-role-policy.mjs','lib/limits.mjs','lib/installer/limits.mjs','lib/installer/runtime-config.mjs','README.md','install.command','package.json','bin/arc.mjs','lib/cli/root.mjs','lib/tui/app.mjs','lib/tui/terminal.mjs','lib/tui/render.mjs','lib/tui/setup.mjs','lib/management/operations.mjs','lib/management/status.mjs','lib/management/update.mjs','lib/management/workflow.mjs','lib/cli/postinstall.mjs','scripts/postinstall.mjs','lib/cli/upgrade.mjs','bin/arc-upgrade.mjs','lib/installer/shell-completion.mjs','lib/installer/manifest.mjs','lib/installer/targets.mjs','lib/installer/global-config.mjs','lib/installer/plan.mjs','lib/safe-fs/index.mjs','lib/safe-fs/native.mjs','lib/models/index.mjs','lib/models/config.mjs','lib/models/profiles.mjs','vendor/toml/LICENSE','vendor/toml/package.json','vendor/toml/provenance.json','vendor/toml/dist/index.js','prebuilds/index.json'];
45
- required.push('lib/installer/runtime-assets.mjs',...RUNTIME_MODULE_PATHS);
46
- for(const platform of ['codex','claude'])required.push(`${platform}/skill/runtime/role-policy.json`,...RUNTIME_MODULE_PATHS.map(name=>`${platform}/skill/runtime/${name.slice('lib/runtime/'.length)}`));
46
+ required.push('lib/installer/skill-sources.mjs','lib/installer/runtime-assets.mjs',...RUNTIME_MODULE_PATHS);
47
+ required.push('shared/skill/runtime/role-policy.json',...RUNTIME_MODULE_PATHS.map(name=>`shared/skill/runtime/${name.slice('lib/runtime/'.length)}`));
47
48
  for(const tuple of ['darwin-arm64','darwin-x64','linux-arm64-gnu','linux-x64-gnu'])required.push(`prebuilds/${tuple}/arc_safe_fs.node`);
48
- for(const platform of ['codex','claude'])for(const name of [...COOPERATIVE_RUNTIME_MODULES,'role-policy.json'])required.push(`${platform}/skill/runtime/${name}`);
49
+ for(const name of [...COOPERATIVE_RUNTIME_MODULES,'role-policy.json'])required.push(`shared/skill/runtime/${name}`);
49
50
  const modelInputs={};for(const platform of ['codex','claude']){const base=`${platform}/skill`;required.push(`${base}/SKILL.md`,`${base}/models.toml`,`${base}/references/limits.md`);const profiles=new Map();for(const role of ['scouter','planner','implementer','qa','reviewer']){const name=`arc-${role}.${platform==='codex'?'toml':'md'}`,key=`${platform}/agents/${name}`;required.push(key);profiles.set(name,files.get(key));}modelInputs[platform]={models:files.get(`${base}/models.toml`),profiles};}
50
51
  for(const name of required)if(!files.has(name))throw Error(`Required runtime asset is missing: ${name}`);
51
52
  const agentRegistry=JSON.parse(files.get('lib/prompts/agent-fragments.json').toString('utf8'));
@@ -56,6 +57,6 @@ export function verifyPayload({packageRoot,safeFs,payloadMode='auto'}){
56
57
  for(const [name,bytes] of policyOutputs)if(!bytes.equals(files.get(name)))throw Error(`Stale role policy output: ${name}`);
57
58
  const vendor=JSON.parse(files.get('vendor/toml/provenance.json'));for(const name of Object.keys(vendor.files??{}))if(!safeName(name)||!files.has('vendor/toml/'+name))throw Error('Vendored runtime asset is missing');
58
59
  for(const platform of ['codex','claude']){const input=modelInputs[platform];const config=loadModelConfig(input.models,platform);renderProfiles(input.profiles,resolveModelSettings(config));modelInputs[platform]={models:Buffer.from(input.models),profiles:new Map([...input.profiles].map(([k,v])=>[k,Buffer.from(v)]))};}
59
- return{packageRoot,files,modelInputs,agentRegistry,snapshot,referenceTrees};
60
+ return{packageRoot,files,modelInputs,agentRegistry,snapshot,referenceTree};
60
61
  }catch(cause){throw new PayloadValidationError(`Payload verification failed: ${cause.message}`,{cause});}finally{root?.close();}
61
62
  }
@@ -11,7 +11,7 @@ import {applyTransaction} from './transaction.mjs';
11
11
 
12
12
  export async function refreshPackageReferences({packageRoot,safeFs,acquisition,signal,hooks={}}){
13
13
  if(!safeFs){const native=loadNative({root:packageRoot});safeFs={openRoot:p=>openRoot(p,{native})};}
14
- const payload=verifyPayload({packageRoot,safeFs,payloadMode:'source'}),paths=['codex','claude'].flatMap(platform=>REFERENCE_PATH_MAP.map(({destination})=>path.join(packageRoot,platform,'skill/references',destination)));
14
+ const payload=verifyPayload({packageRoot,safeFs,payloadMode:'source'}),paths=REFERENCE_PATH_MAP.map(({destination})=>path.join(packageRoot,'shared/skill/references',destination));
15
15
  paths.push(path.join(packageRoot,'MANIFEST.sha256'));
16
16
  const snapshot=new Map([...payload.snapshot].map(([name,item])=>[path.join(packageRoot,name),item]));
17
17
  for(const name of ['MANIFEST.sha256','package-lock.json'])inspectPath(safeFs,path.join(packageRoot,name),{kind:'file',snapshot});
@@ -24,7 +24,7 @@ export async function refreshPackageReferences({packageRoot,safeFs,acquisition,s
24
24
  const dispose=acquired.dispose;acquired.dispose=async()=>{await dispose();fs.rmdirSync(work);};
25
25
  }
26
26
  const flat=flattenReferenceBundle(acquired.references),candidate=new Map(payload.files),specs=[];
27
- for(const platform of ['codex','claude'])for(const[destination,entry]of flat){const name=platform+'/skill/references/'+destination;candidate.set(name,entry.bytes);specs.push({path:path.join(packageRoot,name),bytes:entry.bytes});}
27
+ for(const[destination,entry]of flat){const name='shared/skill/references/'+destination;candidate.set(name,entry.bytes);specs.push({path:path.join(packageRoot,name),bytes:entry.bytes});}
28
28
  specs.push({path:path.join(packageRoot,'MANIFEST.sha256'),bytes:renderManifest(candidate)});
29
29
  const plan={target:{home:packageRoot},managedPaths:paths,externalPaths:[],snapshot};
30
30
  const result=applyTransaction(plan,{safeFs,signal,hooks,specs});
@@ -1,6 +1,7 @@
1
1
  import {inspectStandaloneProfile} from './install-mode.mjs';
2
2
  import {renderAgentProfile} from '../prompts/render.mjs';
3
3
  import {PayloadValidationError} from './manifest.mjs';
4
+ import {composeSkillSources} from './skill-sources.mjs';
4
5
  import{parseLanguage,serializeLanguage,renderLanguagePolicy,validateLanguage}from'./language.mjs';
5
6
  import{resolveLimits}from'../limits.mjs';import{parseLimits,serializeLimits}from'./limits.mjs';import{readRuntimeConcurrency,renderCodexConcurrency,renderClaudeConcurrency}from'./runtime-config.mjs';import{assertPlanSnapshot}from'./transaction.mjs';
6
7
  import{validateModelConfig}from'../models/config.mjs';
@@ -29,7 +30,8 @@ function renderModelAssets({payload,target,roles,modelConfig,language,verifiedCa
29
30
  }
30
31
  export function renderStandaloneProfiles({payload,target,modelConfig,language}){return renderModelAssets({payload,target,modelConfig,language}).profiles;}
31
32
  function renderSkillPayload({payload,target,language,modelBytes,limits}){
32
- const skill=new Map();for(const[name,bytes]of payload.files)if(name.startsWith(target.payloadPrefix+'/skill/'))skill.set(name.slice((target.payloadPrefix+'/skill/').length),Buffer.from(bytes));skill.set('SKILL.md',renderLanguagePolicy(skill.get('SKILL.md'),language));skill.set('settings.toml',serializeLanguage(language));skill.set('models.toml',modelBytes);skill.set('limits.toml',serializeLimits(limits));
33
+ let skill;try{skill=composeSkillSources(payload.files,target.platform);}catch(cause){throw new PayloadValidationError(`Payload skill composition failed: ${cause.message}`,{cause});}
34
+ skill.set('SKILL.md',renderLanguagePolicy(skill.get('SKILL.md'),language));skill.set('settings.toml',serializeLanguage(language));skill.set('models.toml',modelBytes);skill.set('limits.toml',serializeLimits(limits));
33
35
  return skill;
34
36
  }
35
37
  function renderNativeChanges({target,safeFs,snapshot,skipGlobal,preview,concurrentExplicit,limits,summary,language}){
@@ -0,0 +1,23 @@
1
+ export const SHARED_SKILL_PREFIX='shared/skill/';
2
+ export const GENERATED_SKILL_FILES=Object.freeze(['SKILL.md','models.toml','settings.toml','limits.toml']);
3
+
4
+ export function composeSkillSources(files,platform){
5
+ if(!(files instanceof Map))throw Error('Invalid skill source files');
6
+ if(!['codex','claude'].includes(platform))throw Error(`Invalid skill source platform: ${platform}`);
7
+ const shared=new Map(),selected=new Map(),prefix=platform+'/skill/';
8
+ for(const [name,bytes]of files){
9
+ if(name.startsWith(SHARED_SKILL_PREFIX))shared.set(name.slice(SHARED_SKILL_PREFIX.length),bytes);
10
+ else if(name.startsWith(prefix))selected.set(name.slice(prefix.length),bytes);
11
+ }
12
+ const compare=(a,b)=>a<b?-1:a>b?1:0,sharedNames=[...shared.keys()].sort(compare);
13
+ for(const name of sharedNames)if(selected.has(name))throw Error(`Skill source conflict (C1 same path): ${name}`);
14
+ for(const name of sharedNames)if(GENERATED_SKILL_FILES.some(generated=>name===generated||name.startsWith(generated+'/')))throw Error(`Skill source conflict (C2 generated file): ${name}`);
15
+ const union=new Map([...shared,...selected]),names=[...union.keys()].sort(compare);
16
+ for(const name of names){
17
+ const parts=name.split('/');for(let i=1;i<parts.length;i++){
18
+ const parent=parts.slice(0,i).join('/');
19
+ if(union.has(parent)&&(shared.has(parent)||shared.has(name)))throw Error(`Skill source conflict (C3 file/directory prefix): ${parent} vs ${name}`);
20
+ }
21
+ }
22
+ return new Map(names.map(name=>[name,Buffer.from(union.get(name))]));
23
+ }
@@ -8,7 +8,7 @@ export const REQUIRED=Object.freeze({
8
8
  });
9
9
  export const SKILLS=Object.freeze(Object.keys(REQUIRED));
10
10
  export const REPOSITORY='https://github.com/obra/superpowers';
11
- export const DYNAMIC_ROOTS=Object.freeze(['codex','claude'].map(platform=>`${platform}/skill/references/superpowers`));
11
+ export const DYNAMIC_ROOTS=Object.freeze(['codex','claude','shared'].map(platform=>`${platform}/skill/references/superpowers`));
12
12
  export const isDynamicReferencePath=name=>DYNAMIC_ROOTS.some(root=>name===root||name.startsWith(root+'/'));
13
13
  export const REFERENCE_PATH_MAP=Object.freeze([
14
14
  ['brainstorming/SKILL.md','brainstorming.md'],['writing-plans/SKILL.md','writing-plans.md'],['test-driven-development/SKILL.md','test-driven-development.md'],
@@ -123,10 +123,10 @@ export function flattenReferenceBundle(bundle){
123
123
  for(const[name,entry]of bundle.entries){if(entry.type==='symlink')failure('Unsupported reference link in flat payload');if(entry.type==='file'&&!allowedFiles.has(name)||entry.type==='directory'&&!allowedDirectories.has(name))failure('Unsupported reference file in flat payload');}
124
124
  return new Map(REFERENCE_PATH_MAP.map(({source,destination})=>{const entry=bundle.entries.get(source);if(entry?.type!=='file')failure('Required flat reference is missing or not regular');return[destination,{...entry,bytes:Buffer.from(entry.bytes)}];}));
125
125
  }
126
- export function validateFlatReferenceFiles(files,platform){
127
- if(!(files instanceof Map)||!['codex','claude'].includes(platform))failure('Invalid flat reference input');
128
- const prefix=platform+'/skill/references/',entries=new Map();
129
- for(const name of files.keys())if(name.startsWith(prefix+'superpowers/'))failure('Unexpected nested reference payload');
126
+ export function validateFlatReferenceFiles(files){
127
+ if(!(files instanceof Map))failure('Invalid flat reference input');
128
+ const prefix='shared/skill/references/',entries=new Map();
129
+ for(const name of files.keys())if(DYNAMIC_ROOTS.some(root=>name.startsWith(root+'/')))failure('Unexpected nested reference payload');
130
130
  for(const{source,destination}of REFERENCE_PATH_MAP){const bytes=files.get(prefix+destination);if(!Buffer.isBuffer(bytes))failure('Required flat reference file is missing: '+prefix+destination);const parts=source.split('/');for(let i=1;i<parts.length;i++)entries.set(parts.slice(0,i).join('/'),{type:'directory',mode:0o755n});entries.set(source,{type:'file',bytes,mode:0o644n});}
131
131
  let provenance;try{provenance=JSON.parse(entries.get('provenance.json').bytes);}catch{failure('Malformed flat reference provenance');}
132
132
  const bundle=validateReferenceBundle({entries,provenance});return{provenance,entries:flattenReferenceBundle(bundle)};
@@ -18,7 +18,7 @@ export async function cooperativeVersions(){
18
18
  const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
19
19
  let policy;try{policy=await fs.readFile(new URL('../policy/role-policy.json',import.meta.url));}catch(error){if(error.code!=='ENOENT')throw error;policy=await fs.readFile(new URL('./role-policy.json',import.meta.url));}
20
20
  const runtime=await Promise.all(COOPERATIVE_RUNTIME_MODULES.map(file=>fs.readFile(new URL(file,import.meta.url))));
21
- return {policy:'1',runtime:'cooperative-8',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
21
+ return {policy:'1',runtime:'cooperative-9',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
22
22
  }
23
23
  export async function initializeCooperativeWorkflow({cwd,workflowId,input,observe=observeCooperativeTarget,storage={}}){
24
24
  validateWorkflowId(workflowId);validateCooperativeCommand({command:'init',input});
@@ -2,7 +2,6 @@ import path from 'node:path';
2
2
  import fs from 'node:fs';
3
3
  import { StringDecoder } from 'node:string_decoder';
4
4
  import { spawn } from 'node:child_process';
5
- import { DEFAULT_POLICY } from './role-dispatch-policy.mjs';
6
5
 
7
6
  const environments = new WeakMap();
8
7
  export function resolveConfigHome(platform, { userHome, env = {}, cwd } = {}) {
@@ -215,34 +214,25 @@ export async function probePlatformAuth(context, { signal, timeoutMs = 10000 } =
215
214
  if (signal?.aborted) abort();
216
215
  });
217
216
  }
218
- export function compareVersions(a, b) {
219
- const left = String(a).split('.').map(Number), right = String(b).split('.').map(Number);
220
- for (let i = 0; i < Math.max(left.length, right.length); i += 1) { const x = left[i] ?? 0, y = right[i] ?? 0; if (x !== y) return x < y ? -1 : 1; }
221
- return 0;
222
- }
223
- /** Runs `<cli> --version`; keeps only the parsed version, never the raw output. */
224
- export async function probeCliVersion(context, { signal, timeoutMs = 10000, policy = DEFAULT_POLICY } = {}) {
225
- const platform = context?.platform;
226
- const result = (version, supported, reason) => ({ version, supported, ...(reason ? { reason } : {}) });
227
- if (!environments.has(context) || signal?.aborted) return result(null, false, 'cli_execution_error');
217
+ /** Runs `<cli> --version` for reporting only; keeps only the parsed version, never the raw output. */
218
+ export async function probeCliVersion(context, { signal, timeoutMs = 10000 } = {}) {
219
+ const result = (version, reason) => ({ version, ...(reason ? { reason } : {}) });
220
+ if (!environments.has(context) || signal?.aborted) return result(null, 'cli_execution_error');
228
221
  return new Promise(resolve => {
229
222
  let child, output = '', overflow = false, done = false;
230
223
  const finish = value => { if (done) return; done = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); resolve(value); };
231
- const abort = () => { child?.kill(); finish(result(null, false, 'cli_execution_error')); };
232
- const timer = setTimeout(() => { child?.kill(); finish(result(null, false, 'timeout')); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
224
+ const abort = () => { child?.kill(); finish(result(null, 'cli_execution_error')); };
225
+ const timer = setTimeout(() => { child?.kill(); finish(result(null, 'timeout')); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
233
226
  signal?.addEventListener('abort', abort, { once: true });
234
227
  try { child = spawn(context.executable, ['--version'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
235
- catch { finish(result(null, false, 'cli_execution_error')); return; }
228
+ catch { finish(result(null, 'cli_execution_error')); return; }
236
229
  child.stdout.on('data', chunk => { if (output.length + chunk.length > 65536) overflow = true; else if (!overflow) output += chunk.toString(); });
237
230
  child.stderr.on('data', chunk => { if (chunk.length > 65536) overflow = true; });
238
- child.on('error', () => finish(result(null, false, 'cli_execution_error')));
231
+ child.on('error', () => finish(result(null, 'cli_execution_error')));
239
232
  child.on('close', (code, exitSignal) => {
240
- if (exitSignal || code !== 0 || overflow) return finish(result(null, false, 'cli_execution_error'));
233
+ if (exitSignal || code !== 0 || overflow) return finish(result(null, 'cli_execution_error'));
241
234
  const version = /\d+\.\d+\.\d+/.exec(output)?.[0] ?? null;
242
- if (!version) return finish(result(null, false, 'version_unparsed'));
243
- const range = policy?.supportedVersions?.[platform];
244
- const supported = Boolean(range) && compareVersions(version, range.min) >= 0 && compareVersions(version, range.below) < 0;
245
- finish(supported ? result(version, true) : result(version, false, 'version_unsupported'));
235
+ finish(version ? result(version) : result(null, 'version_unparsed'));
246
236
  });
247
237
  });
248
238
  }
@@ -4,7 +4,7 @@ import fsp from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import {DEFAULT_POLICY, reason, profileName, bridgeGateReasons, environmentReasons} from './role-dispatch-policy.mjs';
6
6
  import {readLease, writeLease, listLeases, readHostLimits, NON_TERMINAL_STATES, readHeartbeat, requestCancel, clearCancel, TERMINAL_STATES} from './role-dispatch-store.mjs';
7
- import {withRoutingLock, readActivation, readRevision, authenticate, versionOf} from './role-routing.mjs';
7
+ import {withRoutingLock, readActivation, readRevision, authenticate} from './role-routing.mjs';
8
8
  import {resolveConfigHome} from './local-cli.mjs';
9
9
  import {startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation} from './role-supervisor.mjs';
10
10
 
@@ -134,10 +134,8 @@ export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(
134
134
  result=blank(context,dispatchId,'hold',active!==null&&active!==lease.revision?'revision_changed':'activation_unverified');return;
135
135
  }
136
136
  const requested=config.roles[lease.role],platform=requested.platform,codes=new Set();
137
- const {cli,authentication}=await authenticate(platform,context,policy);
137
+ const {authentication}=await authenticate(platform,context,policy);
138
138
  if(authentication.status!=='Available')codes.add(authentication.status);
139
- const version=await versionOf(cli,policy);
140
- if(cli&&!version.supported)codes.add('permission_scope_unverified');
141
139
  for(const code of environmentReasons(context.executionEnvironment,policy))codes.add(code);
142
140
  for(const code of bridgeGateReasons({platform,role:lease.role,hostPlatform:context.hostPlatform,policy}))codes.add(code);
143
141
  // The dispatch itself is terminal here, so only other non-terminal bridge leases occupy slots. The workflow total is not increased by a follow-up segment.
@@ -1,9 +1,5 @@
1
- // Fixed policy values for composite role dispatch. Gate results mirror the recorded G1-G8 outcomes.
2
- export const SUPPORTED_CLI_VERSIONS = Object.freeze({
3
- claude: Object.freeze({min: '2.1.322', below: '2.2.0'}),
4
- codex: Object.freeze({min: '0.167.0', below: '0.168.0'})
5
- });
6
- export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'fail', G2: 'fail', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: 'pass'});
1
+ // Fixed policy values for composite role dispatch. G2 'escalation' means the bridge runs only with per-call user escalation approval on a Codex host; it is not a verified pass.
2
+ export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'fail', G2: 'escalation', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: 'pass'});
7
3
  // No sandbox settings JSON has been recorded: G1 failed, so there is nothing to apply.
8
4
  const RECORDED_CLAUDE_SANDBOX_SETTINGS = null;
9
5
  const isRecordedObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
@@ -26,7 +22,6 @@ export const LEASE_RETENTION_MS = 2592000000;
26
22
  export const PROBE_TIMEOUT_MS = 10000;
27
23
 
28
24
  export const DEFAULT_POLICY = Object.freeze({
29
- supportedVersions: SUPPORTED_CLI_VERSIONS,
30
25
  gates: BRIDGE_GATE_RESULTS,
31
26
  claudeSandboxSettings: CLAUDE_SANDBOX_SETTINGS,
32
27
  codexDelegationCallNames: CODEX_DELEGATION_CALL_NAMES,
@@ -48,10 +43,10 @@ export const RELEASE_CONDITIONS = Object.freeze({
48
43
  'Not Available': 'Install the target platform CLI so that it is found on PATH.',
49
44
  Unauthorized: 'Authenticate the target platform CLI.',
50
45
  Incomplete: 'Make the target platform CLI authentication status check complete successfully.',
51
- environment_unverified: 'Desktop hosts are held in this release; use a CLI host or a later ARC update that changes the support status.',
46
+ environment_unverified: 'Desktop hosts are held in this release. If this session is not running inside a Desktop app (for example a terminal or IDE terminal session), declare codex-cli or claude-cli instead; otherwise use a CLI host or a later ARC update that changes the support status.',
52
47
  host_sandbox_blocked: 'Allow the host to write the Codex home and keep a detached supervisor alive, with explicit user approval.',
53
48
  capacity_exhausted: 'Finish or release active bridge executions, or raise the host limits.',
54
- permission_scope_unverified: 'Use a supported CLI version or update ARC, and verify enforcement of the role permissions and approved scope before starting.',
49
+ permission_scope_unverified: 'Update ARC and verify enforcement of the role permissions and approved scope before starting.',
55
50
  native_profile_reload_unverified: 'Verify that the host session loaded the requested profile revision.',
56
51
  revision_changed: 'Re-run routing-status and prepare a new dispatch under the current revision.',
57
52
  duplicate_dispatch: 'Use a new requestId, or finish the existing dispatch for the same workflow, task and role.',
@@ -136,7 +136,7 @@ export async function authenticate(platform,context,policy){
136
136
  const auth=await (platform==='codex'?probeCodexAuthStatus:probePlatformAuth)(cli,{timeoutMs:policy.probeTimeoutMs});
137
137
  return {cli,authentication:{status:auth.authStatus==='authenticated'?'Available':auth.authStatus==='unauthorized'?'Unauthorized':'Incomplete',...(auth.reason?{reason:auth.reason}:{})}};
138
138
  }
139
- export const versionOf=(cli,policy)=>cli?probeCliVersion(cli,{timeoutMs:policy.probeTimeoutMs,policy}):{version:null,supported:false,reason:'cli_not_found'};
139
+ export const versionOf=(cli,policy)=>cli?probeCliVersion(cli,{timeoutMs:policy.probeTimeoutMs}):{version:null,reason:'cli_not_found'};
140
140
  export async function readRevision(homes){
141
141
  const bytes=await readStable(path.join(homes.codex,'arc-role-platform-routing.json'),[]);
142
142
  return parseRoleRoutingConfig(bytes.toString('utf8')).revision;
@@ -194,7 +194,6 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
194
194
  if(authentication.status!=='Available')codes.add(authentication.status);
195
195
  if(route==='bridge'){
196
196
  result.cliVersion=await versionOf(cli,policy);
197
- if(cli&&!result.cliVersion.supported)codes.add('permission_scope_unverified');
198
197
  }
199
198
  for(const code of environmentReasons(environment,policy))codes.add(code);
200
199
  const leases=await listLeases(homes.codex);
@@ -85,6 +85,13 @@ export function createDispatchIndex({codexHome}) {
85
85
  const workflows = path.join(gcd, 'arc', 'workflows');
86
86
  for (const workflow of await entries(workflows)) {
87
87
  if (!workflow.isDirectory()) continue;
88
+ let cwd = null;
89
+ try {
90
+ const state = JSON.parse(await fsp.readFile(path.join(workflows,workflow.name,'state.json'),'utf8'));
91
+ if (typeof state?.target?.realpath === 'string' && path.isAbsolute(state.target.realpath)) cwd = state.target.realpath;
92
+ } catch (error) {
93
+ if (!(error instanceof SyntaxError) && !['ENOENT','ENOTDIR','EACCES'].includes(error.code)) throw error;
94
+ }
88
95
  const dispatches = path.join(workflows, workflow.name, 'dispatches');
89
96
  for (const dispatch of await entries(dispatches)) {
90
97
  if (!dispatch.isDirectory()) continue;
@@ -98,7 +105,7 @@ export function createDispatchIndex({codexHome}) {
98
105
  record = await readRecord(segmentDir) ?? record;
99
106
  await readEvents(segmentDir, ref);
100
107
  }
101
- artifacts.set(dispatch.name, {dir, workflowId:workflow.name, record});
108
+ artifacts.set(dispatch.name, {dir, workflowId:workflow.name, record, cwd});
102
109
  }
103
110
  }
104
111
  }
@@ -108,6 +115,7 @@ export function createDispatchIndex({codexHome}) {
108
115
  const artifact = artifacts.get(id), lease = currentLeases.get(id), value = lease ?? artifact?.record;
109
116
  ref.inScope = Boolean(artifact || (includeAllLeases && lease));
110
117
  ref.artifactDir = artifact?.dir ?? null;
118
+ ref.cwd = artifact?.cwd ?? null;
111
119
  if (!lease && !artifact) continue;
112
120
  for (const key of ['workflowId', 'rawRole', 'route', 'hostPlatform', 'state', 'updatedAt']) delete ref[key];
113
121
  if (artifact) ref.workflowId = artifact.workflowId;
@@ -120,7 +128,7 @@ export function createDispatchIndex({codexHome}) {
120
128
  }
121
129
  ref.role = roleFromName(ref.rawRole);
122
130
  ref.reasons = value?.reasons ?? [];
123
- const signature = JSON.stringify([ref.state, ref.reasons]), first = !signatures.has(id);
131
+ const signature = JSON.stringify([ref.state, ref.reasons, ref.cwd]), first = !signatures.has(id);
124
132
  if (first || signatures.get(id) !== signature) updates.push({ref, first});
125
133
  signatures.set(id, signature);
126
134
  }
package/lib/watch/git.mjs CHANGED
@@ -7,9 +7,10 @@ export const GIT_ALLOWED = Object.freeze([
7
7
  Object.freeze(['rev-parse','--show-toplevel']),
8
8
  Object.freeze(['rev-parse','--path-format=absolute','--git-common-dir']),
9
9
  Object.freeze(['worktree','list','--porcelain','-z']),
10
+ Object.freeze(['ls-files','-z','--cached','--others','--exclude-standard']),
10
11
  ]);
11
12
 
12
- export function createGitRunner({env = process.env, timeoutMs = WATCH_LIMITS.gitTimeoutMs} = {}) {
13
+ export function createGitRunner({env = process.env, timeoutMs = WATCH_LIMITS.gitTimeoutMs, maxBuffer = WATCH_LIMITS.gitMaxBufferBytes} = {}) {
13
14
  const cleanEnv = Object.fromEntries(Object.entries(env).filter(([key]) => !key.toUpperCase().startsWith('GIT_')));
14
15
  Object.assign(cleanEnv, {
15
16
  GIT_CONFIG_NOSYSTEM:'1', GIT_CONFIG_GLOBAL:process.platform === 'win32' ? 'NUL' : '/dev/null',
@@ -21,7 +22,8 @@ export function createGitRunner({env = process.env, timeoutMs = WATCH_LIMITS.git
21
22
  }
22
23
  try {
23
24
  const {stdout} = await execFileAsync('git', ['--no-pager','-c','core.fsmonitor=false',...args], {
24
- cwd, env:cleanEnv, shell:false, encoding:'utf8', timeout:timeoutMs,
25
+ cwd, env:cleanEnv, shell:false, encoding:'utf8', maxBuffer,
26
+ timeout:args[0] === 'ls-files' ? WATCH_LIMITS.shellScanTimeoutMs : timeoutMs,
25
27
  });
26
28
  return stdout;
27
29
  } catch { return null; }
@@ -13,8 +13,8 @@ export const WATCH_HELP = `Usage: arc watch [options]
13
13
 
14
14
  Follow Claude Code and Codex session activity in one read-only stream.
15
15
 
16
- Scope (default: every worktree of the current Git repository, or the current directory):
17
- --cwd <dir> Watch the repository or directory at <dir>
16
+ Scope (default: the current Git worktree, or the current directory):
17
+ --cwd <dir> Watch the worktree or directory at <dir>
18
18
  --all Watch sessions from every directory
19
19
  --session <id> Follow one session or ARC dispatch and its subagents
20
20
  --platform <name> codex or claude (default: both)
@@ -23,14 +23,14 @@ Output:
23
23
  --tail <n> First show the last <n> events from recently active sessions (default 20, 0 = new only)
24
24
  --verbose Also show reasoning, settings, turn starts and diagnostics
25
25
  --json Write one JSON object per line
26
- --width <n> Maximum width of one-line events (default: terminal width, or 200)
26
+ --width <n> Maximum line width; one-line events are clipped, messages and file lists wrap (default: terminal width, or 200)
27
27
  --help Show this help
28
28
 
29
- User and agent messages are shown in full; other events use one line.
29
+ User and agent messages and file paths are shown in full; other events use one line.
30
30
  Tool and command outputs are never shown; common secret patterns are masked.
31
31
  A spinner on the last line shows while a turn is in progress (TTY only).
32
32
  Codex Desktop sessions are not included.
33
- Bridge roles on a Codex host are currently held (host_sandbox_blocked) and appear once they run.
33
+ Claude bridge Scouter, Planner and Reviewer on a Codex host need per-call escalation approval (otherwise host_sandbox_blocked) and appear once they run; Claude bridge Implementer and QA stay held.
34
34
  Press Ctrl-L to clear the screen (TTY only) and Ctrl-C to stop.`;
35
35
 
36
36
  export async function runWatch(argv, io = {}) {
@@ -58,6 +58,7 @@ export async function runWatch(argv, io = {}) {
58
58
  const now = io.now ?? Date.now, git = io.git ?? createGitRunner({env});
59
59
  const proc = io.process ?? process, schedule = io.setInterval ?? setInterval, unschedule = io.clearInterval ?? clearInterval;
60
60
  let width, watcher, timer, stopped = false, active;
61
+ const wrap = Boolean(!options.json && (output.isTTY || options.width != null));
61
62
  const color = Boolean(output.isTTY && !options.json && !env.NO_COLOR);
62
63
  const spinnerEnabled = Boolean(output.isTTY && !options.json);
63
64
  const keysEnabled = Boolean(input.isTTY && output.isTTY && !options.json && typeof input.setRawMode === 'function');
@@ -122,7 +123,7 @@ export async function runWatch(argv, io = {}) {
122
123
  eraseSpinner();
123
124
  for (const event of events) {
124
125
  if (stopped) break;
125
- output.write((options.json ? renderJson(event) : renderHuman(event,{width,color,verbose:options.verbose})) + '\n');
126
+ output.write((options.json ? renderJson(event) : renderHuman(event,{width,color,verbose:options.verbose,wrap})) + '\n');
126
127
  }
127
128
  drawSpinner();
128
129
  };
@@ -130,7 +131,7 @@ export async function runWatch(argv, io = {}) {
130
131
  output.on('error', onError);
131
132
  output.on('resize', resize);
132
133
  io.signal?.addEventListener('abort', onSignal, {once:true});
133
- let ticking = false;
134
+ let ticking = false, nextPollAt;
134
135
  active = (async () => {
135
136
  if (keysEnabled) {
136
137
  rawModeEnabled = true;
@@ -147,13 +148,20 @@ export async function runWatch(argv, io = {}) {
147
148
  }
148
149
  write(await watcher.start());
149
150
  if (stopped) return;
151
+ nextPollAt = now() + L.filePollMs;
150
152
  timer = schedule(() => {
151
153
  if (stopped || ticking) return;
154
+ if (now() < nextPollAt) {
155
+ eraseSpinner();
156
+ drawSpinner();
157
+ return;
158
+ }
159
+ nextPollAt = now() + L.filePollMs;
152
160
  ticking = true;
153
161
  active = (async () => { try { write(await watcher.tick()); } finally { ticking = false; } })();
154
162
  active.catch(onError);
155
163
  return active;
156
- }, L.filePollMs);
164
+ }, spinnerEnabled ? 100 : L.filePollMs);
157
165
  })();
158
166
  active.catch(onError);
159
167
  });
@@ -1,4 +1,4 @@
1
- export const WATCH_KINDS = Object.freeze(['session','settings','turn_start','turn_end','turn_failed','user','agent','reasoning','command','tool','tool_failed','file_change','file_create','spawn','approval','dispatch','error','other','notice']);
1
+ export const WATCH_KINDS = Object.freeze(['session','settings','turn_start','turn_end','turn_failed','user','agent','reasoning','command','tool','tool_failed','file_change','file_create','file_delete','spawn','approval','dispatch','error','other','notice']);
2
2
  export const MESSAGE_KINDS = Object.freeze(['user','agent']);
3
3
  export const VERBOSE_KINDS = Object.freeze(['settings','turn_start','reasoning','other']);
4
4
  export const ROLE_NAMES = Object.freeze(['scouter','planner','implementer','qa','reviewer']);
@@ -9,9 +9,12 @@ export const WATCH_LIMITS = Object.freeze({
9
9
  idleDetachMs:1800000, maxFollowed:64, maxReadBytesPerTick:1048576,
10
10
  maxLineBytes:4194304, historyBytes:262144, maxRepos:32, claudeHeadBytes:1048576,
11
11
  claudeCwdWaitMs:10000, codexMetaBytes:4194304, lookbackDays:7,
12
- jsonTextMax:1000, agentNameMax:20, pathsMax:20, toolCacheMax:512, defaultTail:20,
12
+ jsonTextMax:1000, wrapMinBody:20, toolCacheMax:512, defaultTail:20,
13
13
  maxTail:1000, widthMin:40, widthMax:2000, ttyWidthMin:60, nonTtyWidth:200,
14
14
  gitTimeoutMs:10000, spinnerIdleMs:300000,
15
+ shellScanDelayMs:1000, shellScanMinIntervalMs:3000, shellScansPerTick:2,
16
+ shellScanMaxFiles:20000, shellScanTimeoutMs:5000, shellScanFailureMax:3,
17
+ shellLstatBatch:256, shellClaimTtlMs:120000, gitMaxBufferBytes:16777216,
15
18
  });
16
19
 
17
20
  /**
@@ -31,12 +34,13 @@ export const WATCH_LIMITS = Object.freeze({
31
34
  * @property {'scouter'|'planner'|'implementer'|'qa'|'reviewer'|'orchestrator'} [role]
32
35
  * @property {string} [dispatchId]
33
36
  * @property {string} [workflowId]
34
- * @property {'session'|'settings'|'turn_start'|'turn_end'|'turn_failed'|'user'|'agent'|'reasoning'|'command'|'tool'|'tool_failed'|'file_change'|'file_create'|'spawn'|'approval'|'dispatch'|'error'|'other'|'notice'} kind
37
+ * @property {'session'|'settings'|'turn_start'|'turn_end'|'turn_failed'|'user'|'agent'|'reasoning'|'command'|'tool'|'tool_failed'|'file_change'|'file_create'|'file_delete'|'spawn'|'approval'|'dispatch'|'error'|'other'|'notice'} kind
35
38
  * @property {string} [text] Sanitized, masked text; user/agent preserve newlines without a length cap. Other JSON text is capped at 1000 code points.
36
39
  * @property {boolean} [truncated]
37
40
  * @property {number} [exitCode]
38
41
  * @property {string} [tool]
39
- * @property {string[]} [paths] At most 20 paths.
42
+ * @property {string[]} [paths] All reported paths, deduplicated; no fixed cap.
43
+ * @property {boolean} [inferred] True for file events inferred from a Git file-list and lstat comparison.
40
44
  * @property {string} [model]
41
45
  * @property {string} [effort]
42
46
  * @property {string} [approval]
@@ -1,10 +1,11 @@
1
+ import path from 'node:path';
1
2
  import {WATCH_LIMITS} from './model.mjs';
2
3
 
3
4
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
4
5
  const string = value => typeof value === 'string';
5
6
 
6
7
  export function createClaudeState() {
7
- return {modelSeen:false, tools:new Map(), writes:new Map()};
8
+ return {modelSeen:false, tools:new Map(), writes:new Map(), deletes:new Map()};
8
9
  }
9
10
 
10
11
  export function parseClaudeHead(obj) {
@@ -31,12 +32,75 @@ function userText(content) {
31
32
  return text.replace(/<(system-reminder|command-[\w-]+|local-command-[\w-]+|task-notification|bash-input|bash-stdout|bash-stderr)\b[^>]*>[\s\S]*?(?:<\/\1\s*>|$)/gi, '');
32
33
  }
33
34
 
34
- /** State contains the first-model flag and bounded tool-name and pending-Write caches. */
35
+ // Parse only literal shell words. Expansions, pipelines and other shell syntax
36
+ // stay command events because their deletion targets cannot be inferred safely.
37
+ function literalCommands(command) {
38
+ if (!string(command) || /[\r\n]/.test(command)) return null;
39
+ const commands = [[]];
40
+ let word = '', started = false, quote = '';
41
+ const flush = () => {
42
+ if (started) commands.at(-1).push(word);
43
+ word = ''; started = false;
44
+ };
45
+ for (let i=0;i<command.length;i++) {
46
+ const c = command[i];
47
+ if (quote === "'") {
48
+ if (c === quote) quote = ''; else word += c;
49
+ } else if (quote === '"') {
50
+ if (c === quote) quote = '';
51
+ else if (c === '$' || c === '`') return null;
52
+ else if (c === '\\' && /["\\$`]/.test(command[i+1] ?? '')) word += command[++i];
53
+ else word += c;
54
+ } else if (c === "'" || c === '"') {
55
+ quote = c; started = true;
56
+ } else if (c === '\\') {
57
+ if (++i >= command.length) return null;
58
+ word += command[i]; started = true;
59
+ } else if (/[ \t]/.test(c)) flush();
60
+ else if (c === '&' && command[i+1] === '&') {
61
+ flush(); commands.push([]); i++;
62
+ } else if (/[;|&<>$`*?\[\]{}()]/.test(c) || (!started && (c === '~' || c === '#'))) return null;
63
+ else { word += c; started = true; }
64
+ }
65
+ if (quote) return null;
66
+ flush();
67
+ return commands.every(words => words.length) ? commands : null;
68
+ }
69
+
70
+ function deletionPaths(command, cwd) {
71
+ const commands = literalCommands(command);
72
+ if (!commands || commands.length > 2) return [];
73
+ let base = string(cwd) && path.isAbsolute(cwd) ? cwd : undefined;
74
+ if (commands.length === 2) {
75
+ const [name,...args] = commands.shift();
76
+ if (args[0] === '--') args.shift();
77
+ if (name !== 'cd' || args.length !== 1 || !args[0] || args[0].startsWith('-')) return [];
78
+ if (!path.isAbsolute(args[0]) && !base) return [];
79
+ base = path.resolve(base ?? '/',args[0]);
80
+ }
81
+ const [name,...args] = commands[0];
82
+ if (!['rm','/bin/rm','/usr/bin/rm'].includes(name)) return [];
83
+ const paths = [];
84
+ let options = true;
85
+ for (const arg of args) {
86
+ if (options && arg === '--') { options = false; continue; }
87
+ if (options && arg.startsWith('-') && arg !== '-') {
88
+ if (!/^-[fRrvd]+$/.test(arg) && !['--force','--recursive','--verbose','--dir'].includes(arg)) return [];
89
+ continue;
90
+ }
91
+ if (!arg) return [];
92
+ paths.push(base ? path.resolve(base,arg) : arg);
93
+ }
94
+ return [...new Set(paths)];
95
+ }
96
+
97
+ /** State contains bounded tool-name, pending-Write and pending-deletion caches. */
35
98
  export function normalizeClaudeLine(obj, state) {
36
99
  try {
37
100
  if (!object(obj) || !['user','assistant'].includes(obj.type) || !object(obj.message)) return [];
38
101
  if (!object(state) || !(state.tools instanceof Map)) return [];
39
102
  if (!(state.writes instanceof Map)) state.writes = new Map();
103
+ if (!(state.deletes instanceof Map)) state.deletes = new Map();
40
104
  const events = [];
41
105
  const emit = (kind, fields={}) => {
42
106
  const event = {kind, ...fields};
@@ -57,12 +121,16 @@ export function normalizeClaudeLine(obj, state) {
57
121
  if (block?.type !== 'tool_result') continue;
58
122
  const id = block.tool_use_id, pending = state.writes.has(id), path = state.writes.get(id);
59
123
  state.writes.delete(id);
124
+ const deleted = state.deletes.get(id);
125
+ state.deletes.delete(id);
60
126
  if (block.is_error === true) {
61
127
  const tool = state.tools.get(id);
62
128
  emit('tool_failed', string(tool) ? {tool} : {});
129
+ } else if (deleted && obj.toolUseResult?.interrupted !== true && !obj.toolUseResult?.backgroundTaskId) {
130
+ emit('file_delete', {paths:deleted});
63
131
  } else if (pending) {
64
132
  const result = obj.toolUseResult;
65
- const paths = [...new Set([string(result?.filePath) ? result.filePath : path].filter(string))].slice(0,WATCH_LIMITS.pathsMax);
133
+ const paths = [...new Set([string(result?.filePath) ? result.filePath : path].filter(string))];
66
134
  emit(result?.type === 'create' ? 'file_create' : 'file_change', {paths});
67
135
  }
68
136
  }
@@ -90,15 +158,22 @@ export function normalizeClaudeLine(obj, state) {
90
158
  while (state.tools.size > WATCH_LIMITS.toolCacheMax) state.tools.delete(state.tools.keys().next().value);
91
159
  }
92
160
  const input = object(block.input) ? block.input : {};
93
- if (name === 'Bash') emit('command', string(input.command) ? {text:input.command} : {});
94
- else if (name === 'Write') {
161
+ if (name === 'Bash') {
162
+ emit('command', string(input.command) ? {text:input.command} : {});
163
+ if (string(block.id)) {
164
+ state.deletes.delete(block.id);
165
+ const paths = input.run_in_background === true ? [] : deletionPaths(input.command,obj.cwd);
166
+ if (paths.length) state.deletes.set(block.id, paths);
167
+ while (state.deletes.size > WATCH_LIMITS.toolCacheMax) state.deletes.delete(state.deletes.keys().next().value);
168
+ }
169
+ } else if (name === 'Write') {
95
170
  if (string(block.id)) {
96
171
  state.writes.delete(block.id);
97
172
  state.writes.set(block.id, string(input.file_path) ? input.file_path : undefined);
98
173
  while (state.writes.size > WATCH_LIMITS.toolCacheMax) state.writes.delete(state.writes.keys().next().value);
99
174
  }
100
175
  } else if (['Edit','MultiEdit','NotebookEdit'].includes(name)) {
101
- emit('file_change', {paths:[...new Set([input.file_path,input.notebook_path].filter(string))].slice(0,WATCH_LIMITS.pathsMax)});
176
+ emit('file_change', {paths:[...new Set([input.file_path,input.notebook_path].filter(string))]});
102
177
  } else if (['Agent','Task'].includes(name)) {
103
178
  const agent = string(input.subagent_type) ? input.subagent_type : '';
104
179
  const description = string(input.description) ? input.description : '';
@@ -106,6 +181,8 @@ export function normalizeClaudeLine(obj, state) {
106
181
  } else if (['Read','Grep','Glob','WebFetch','WebSearch'].includes(name)) {
107
182
  const target = [input.file_path,input.pattern,input.path,input.url,input.query].find(string);
108
183
  emit('tool', {tool:name, ...(target === undefined ? {} : {text:target})});
184
+ } else if (name === 'SubagentHandback' && string(input.message) && input.message) {
185
+ emit('agent', {text:input.message});
109
186
  } else emit('tool', {tool:name});
110
187
  if (name === 'SubagentHandback' && !turnEnded) {
111
188
  emit('turn_end');