@yunhozz/arc 0.3.5 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/MANIFEST.sha256 +133 -94
  2. package/README.md +56 -21
  3. package/claude/skill/SKILL.md +1 -1
  4. package/claude/skill/references/commit.md +10 -8
  5. package/claude/skill/references/coordination.md +6 -4
  6. package/claude/skill/references/handoff-prep.md +12 -12
  7. package/claude/skill/references/handoff.md +2 -0
  8. package/claude/skill/references/planning.md +8 -8
  9. package/claude/skill/references/verification.md +6 -6
  10. package/codex/skill/SKILL.md +1 -1
  11. package/codex/skill/references/commit.md +10 -8
  12. package/codex/skill/references/coordination.md +6 -4
  13. package/codex/skill/references/handoff-prep.md +12 -12
  14. package/codex/skill/references/handoff.md +2 -0
  15. package/codex/skill/references/planning.md +8 -8
  16. package/codex/skill/references/verification.md +6 -6
  17. package/gemini/GEMINI.md +8 -0
  18. package/gemini/agents/arc-implementer.md +37 -0
  19. package/gemini/agents/arc-planner.md +47 -0
  20. package/gemini/agents/arc-qa.md +37 -0
  21. package/gemini/agents/arc-reviewer.md +39 -0
  22. package/gemini/agents/arc-scouter.md +38 -0
  23. package/gemini/instructions.md +4 -0
  24. package/gemini/skill/SKILL.md +78 -0
  25. package/gemini/skill/models.toml +23 -0
  26. package/gemini/skill/references/arc-visual-companion.md +28 -0
  27. package/gemini/skill/references/commit.md +55 -0
  28. package/gemini/skill/references/coordination.md +149 -0
  29. package/gemini/skill/references/git-recovery.md +34 -0
  30. package/gemini/skill/references/handoff-prep.md +110 -0
  31. package/gemini/skill/references/handoff.md +227 -0
  32. package/gemini/skill/references/limits.md +31 -0
  33. package/gemini/skill/references/planning.md +168 -0
  34. package/gemini/skill/references/verification.md +155 -0
  35. package/gemini/skill/references/worktree-creation.md +8 -0
  36. package/lib/color/palette.mjs +6 -0
  37. package/lib/installer/acquisition.mjs +7 -5
  38. package/lib/installer/install-mode.mjs +49 -26
  39. package/lib/installer/install.mjs +3 -2
  40. package/lib/installer/manifest.mjs +20 -14
  41. package/lib/installer/plan.mjs +24 -21
  42. package/lib/installer/preset.mjs +9 -8
  43. package/lib/installer/role-routing.mjs +160 -81
  44. package/lib/installer/runtime-assets.mjs +2 -0
  45. package/lib/installer/runtime-config.mjs +3 -0
  46. package/lib/installer/skill-sources.mjs +4 -3
  47. package/lib/installer/superpowers.mjs +2 -1
  48. package/lib/installer/target-errors.mjs +1 -0
  49. package/lib/installer/targets.mjs +14 -6
  50. package/lib/installer/uninstall.mjs +5 -4
  51. package/lib/installer/upgrade-state.mjs +14 -10
  52. package/lib/installer/upgrade.mjs +9 -5
  53. package/lib/management/operations.mjs +96 -48
  54. package/lib/management/status.mjs +10 -8
  55. package/lib/management/update.mjs +8 -7
  56. package/lib/models/catalog-gemini.mjs +48 -0
  57. package/lib/models/catalog.mjs +27 -12
  58. package/lib/models/config.mjs +23 -22
  59. package/lib/models/gemini-models.json +12 -0
  60. package/lib/models/profiles.mjs +7 -5
  61. package/lib/models/static-catalog.mjs +13 -14
  62. package/lib/npm/upgrade.mjs +2 -2
  63. package/lib/platforms/availability.mjs +98 -0
  64. package/lib/platforms/claude.mjs +14 -0
  65. package/lib/platforms/codex.mjs +16 -0
  66. package/lib/platforms/formats/gemini-markdown.mjs +48 -0
  67. package/lib/platforms/formats/markdown.mjs +39 -0
  68. package/lib/platforms/formats/toml.mjs +39 -0
  69. package/lib/platforms/gemini.mjs +14 -0
  70. package/lib/platforms/index.mjs +27 -0
  71. package/lib/policy/placement.mjs +4 -4
  72. package/lib/policy/render.mjs +13 -8
  73. package/lib/policy/role-policy.json +40 -21
  74. package/lib/prompts/agent-fragments.json +71 -1
  75. package/lib/prompts/render.mjs +32 -11
  76. package/lib/runtime/bootstrap.mjs +1 -1
  77. package/lib/runtime/cooperative-schema.mjs +0 -23
  78. package/lib/runtime/cooperative.mjs +13 -34
  79. package/lib/runtime/evaluate.mjs +3 -69
  80. package/lib/runtime/gemini-stream.mjs +32 -0
  81. package/lib/runtime/git-evidence.mjs +0 -98
  82. package/lib/runtime/identity.mjs +2 -1
  83. package/lib/runtime/local-cli.mjs +14 -24
  84. package/lib/runtime/operations.mjs +2 -2
  85. package/lib/runtime/platform-registry.mjs +130 -0
  86. package/lib/runtime/role-bridge-args.mjs +57 -2
  87. package/lib/runtime/role-bridge.mjs +86 -65
  88. package/lib/runtime/role-dispatch-policy.mjs +17 -7
  89. package/lib/runtime/role-dispatch-store.mjs +20 -14
  90. package/lib/runtime/role-observe.mjs +1 -0
  91. package/lib/runtime/role-routing-config.mjs +36 -9
  92. package/lib/runtime/role-routing.mjs +62 -29
  93. package/lib/runtime/role-supervisor.mjs +114 -49
  94. package/lib/runtime/schema.mjs +5 -4
  95. package/lib/tui/app.mjs +84 -35
  96. package/lib/tui/custom-preset.mjs +114 -68
  97. package/lib/tui/derive-install-plan.mjs +19 -0
  98. package/lib/tui/diagram.mjs +68 -0
  99. package/lib/tui/mode.mjs +77 -0
  100. package/lib/tui/render.mjs +47 -16
  101. package/lib/tui/setup.mjs +168 -100
  102. package/lib/tui/terminal.mjs +9 -6
  103. package/lib/watch/anchor-store.mjs +44 -0
  104. package/lib/watch/dispatch.mjs +3 -3
  105. package/lib/watch/index.mjs +37 -24
  106. package/lib/watch/model.mjs +1 -0
  107. package/lib/watch/normalize-claude.mjs +50 -10
  108. package/lib/watch/normalize-codex.mjs +79 -5
  109. package/lib/watch/render.mjs +30 -13
  110. package/lib/watch/scope.mjs +2 -1
  111. package/lib/watch/status-line.mjs +51 -0
  112. package/lib/watch/tail.mjs +27 -0
  113. package/lib/watch/watcher.mjs +193 -53
  114. package/package.json +2 -1
  115. package/scripts/update-manifest.mjs +2 -2
  116. package/shared/skill/runtime/bootstrap.mjs +1 -1
  117. package/shared/skill/runtime/cooperative-schema.mjs +0 -23
  118. package/shared/skill/runtime/cooperative.mjs +13 -34
  119. package/shared/skill/runtime/evaluate.mjs +3 -69
  120. package/shared/skill/runtime/gemini-stream.mjs +32 -0
  121. package/shared/skill/runtime/git-evidence.mjs +0 -98
  122. package/shared/skill/runtime/identity.mjs +2 -1
  123. package/shared/skill/runtime/local-cli.mjs +14 -24
  124. package/shared/skill/runtime/operations.mjs +2 -2
  125. package/shared/skill/runtime/platform-registry.mjs +130 -0
  126. package/shared/skill/runtime/role-bridge-args.mjs +57 -2
  127. package/shared/skill/runtime/role-bridge.mjs +86 -65
  128. package/shared/skill/runtime/role-dispatch-policy.mjs +17 -7
  129. package/shared/skill/runtime/role-dispatch-store.mjs +20 -14
  130. package/shared/skill/runtime/role-observe.mjs +1 -0
  131. package/shared/skill/runtime/role-policy.json +40 -21
  132. package/shared/skill/runtime/role-routing-config.mjs +36 -9
  133. package/shared/skill/runtime/role-routing.mjs +62 -29
  134. package/shared/skill/runtime/role-supervisor.mjs +114 -49
  135. package/shared/skill/runtime/schema.mjs +5 -4
@@ -1,175 +1,254 @@
1
+ import {installerRegistryOf,sortByAnchor} from '../platforms/index.mjs';
1
2
  import {renderStandaloneProfiles} from './plan.mjs';
3
+ import {verifyPayload} from './manifest.mjs';
2
4
  import {loadModelConfig} from '../models/index.mjs';
3
5
  import {parseLanguage} from './language.mjs';
4
- import {inspectStandaloneProfile,assertVerifiedInstallMode} from './install-mode.mjs';
6
+ import {inspectStandaloneProfile,assertVerifiedInstallMode,readInstallMode} from './install-mode.mjs';
7
+ import {runtimeRegistryOf,createPlatformRegistry,routingProfileFile,standaloneProfileFile} from '../runtime/platform-registry.mjs';
5
8
  import path from 'node:path';
6
9
  import crypto from 'node:crypto';
7
- import {inspectPath,TargetConfigurationError} from './targets.mjs';
10
+ import {inspectPath,typeOf,sameObjectIdentity,TargetConfigurationError} from './targets.mjs';
8
11
  import {assertPlanSnapshot,applyTransaction} from './transaction.mjs';
9
12
  import {renderProfiles,resolveModelSettings} from '../models/index.mjs';
10
13
  import {COOPERATIVE_RUNTIME_MODULES,cooperativeVersions} from '../runtime/bootstrap.mjs';
11
14
  import {acquireRoleRoutingLock} from '../runtime/role-routing.mjs';
12
- import {NON_TERMINAL_STATES,listLeases} from '../runtime/role-dispatch-store.mjs';
13
- import {revisionTag} from '../runtime/role-dispatch-policy.mjs';
15
+ import {NON_TERMINAL_STATES,listLeases,readLease,writeLease} from '../runtime/role-dispatch-store.mjs';
14
16
  import {ROUTING_ROLES,parseRoleRoutingConfig,serializeRoleRoutingConfig,validateRoleRoutingConfig} from '../runtime/role-routing-config.mjs';
15
17
 
16
18
  const digest=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
17
19
  const validHash=value=>typeof value==='string'&&/^sha256:[a-f0-9]{64}$/.test(value);
18
20
  const exact=(value,keys)=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
19
21
  const fail=message=>{throw new TargetConfigurationError(message);};
20
- const profilePath=(target,role)=>path.join(target.home,'agents',`arc-routing-${role.slice(4)}.${target.platform==='codex'?'toml':'md'}`);
22
+ const profilePath=(target,role,runtimePlatforms)=>path.join(target.home,'agents',routingProfileFile(runtimeRegistryOf({runtimePlatforms}).getPlatform(target.platform),role));
21
23
  const markerPath=target=>path.join(target.home,'arc-role-platform-routing.prepared.json');
22
- const activePath=targets=>path.join(targets.codex.home,'arc-role-platform-routing.json');
24
+ const activePath=(targets,anchor)=>path.join(targets[anchor].home,'arc-role-platform-routing.json');
23
25
  const read=(safeFs,filename,snapshot)=>inspectPath(safeFs,filename,{kind:'file',read:true,snapshot});
24
26
 
25
- export function renameCompositeProfile(bytes,platform,role,revision){
26
- if(typeof revision!=='string'||!/^[A-Za-z0-9._-]{1,128}$/.test(revision))fail('Composite revision cannot be tagged');
27
- const suffix=role.slice(4),old=platform==='codex'?`arc_${suffix}`:`arc-${suffix}`,next=platform==='codex'?`arc_routing_${suffix}`:`arc-routing-${suffix}`;
28
- const text=bytes.toString('utf8'),pattern=platform==='codex'?new RegExp(`^name[ \\t]*=[ \\t]*["']${old}["']([ \\t]*(?:#[^\\r\\n]*)?)(\\r?)$`,'m'):new RegExp(`^name: ${old}(\\r?)$`,'m');
29
- const matches=[...text.matchAll(new RegExp(pattern.source,'gm'))];if(matches.length!==1)fail('Cannot identify the managed composite profile name');
30
- const renamed=platform==='codex'?text.replace(pattern,(_match,comment,cr)=>`name = "${next}"${comment}${cr}`):text.replace(pattern,(_match,cr)=>`name: ${next}${cr}`);
31
- return Buffer.from(tagDescription(renamed,platform,revision));
27
+ export const legacyAnchorPlatform = 'codex';
28
+ // Only installers read the historical v1 order. Runtime activation stays strict.
29
+ export function parseInstalledRoutingConfig(text,{runtimePlatforms}={}){
30
+ const registry=runtimeRegistryOf({runtimePlatforms});let config;
31
+ try{config=parseRoleRoutingConfig(text,{runtimePlatforms:registry});}catch(cause){
32
+ if(JSON.parse(text)?.version!==1)throw cause;
33
+ const historical=createPlatformRegistry([...registry.byAnchorOrder()].sort((a,b)=>Number(b.id===legacyAnchorPlatform)-Number(a.id===legacyAnchorPlatform)).map((descriptor,anchorOrder)=>({...descriptor,anchorOrder})));
34
+ config=parseRoleRoutingConfig(text,{runtimePlatforms:historical});
35
+ }
36
+ return validateRoleRoutingConfig({...config,version:2,platforms:[...config.platforms].sort((a,b)=>registry.getPlatform(a).anchorOrder-registry.getPlatform(b).anchorOrder)},{runtimePlatforms:registry});
32
37
  }
33
38
 
34
- /** Only the header (before developer_instructions or the closing frontmatter fence) is searched, so instruction text cannot be mistaken for a description. */
35
- function tagDescription(text,platform,revision){
36
- const tag=revisionTag(revision),lines=text.split('\n'),codex=platform==='codex',end=lines.findIndex((line,index)=>codex?/^developer_instructions[ \t]*=/.test(line):index>0&&line.replace(/\r$/,'')==='---'),limit=end<0?lines.length:end;
37
- const pattern=codex?/^(description[ \t]*=[ \t]*"(?:[^"\\]|\\.)*)("[ \t]*(?:#[^\r\n]*)?\r?)$/:/^(description: .*?)(\r?)$/,hits=[];
38
- for(let i=0;i<limit;i++)if(/^description[ \t]*[=:]/.test(lines[i]))hits.push(i);
39
- const match=hits.length===1?pattern.exec(lines[hits[0]]):null;if(!match)fail('Composite revision cannot be tagged');
40
- lines[hits[0]]=`${match[1]} ${tag}${match[2]}`;
41
- return lines.join('\n');
39
+ export function renameCompositeProfile(bytes,platform,role,revision,context={}){
40
+ return installerRegistryOf(context).getPlatform(platform).profiles.renameForRouting(bytes,role,revision);
42
41
  }
43
42
 
43
+ const defaultCompositePlatforms=context=>installerRegistryOf(context).byAnchorOrder().filter(descriptor=>descriptor.runtime.capabilities.compositeHost.state==='verified').map(descriptor=>descriptor.runtime.id);
44
+
44
45
  /** Inspect only ARC-owned composite paths; existing unknown files are never replaced. */
45
- export function prepareCompositeFiles({context,targets,config,profileInputs,modelConfigs}){
46
- assertVerifiedInstallMode({safeFs:context.safeFs,targets});
47
- config=validateRoleRoutingConfig(config);const bytes=Buffer.from(serializeRoleRoutingConfig(config)),snapshot=new Map(),active=activePath(targets),activeFile=read(context.safeFs,active,snapshot);
48
- let previous=null;if(activeFile.exists)try{previous=parseRoleRoutingConfig(activeFile.bytes.toString('utf8'));}catch{fail('Existing composite configuration cannot be verified');}
49
- if(previous?.revision===config.revision&&!activeFile.bytes.equals(bytes))fail('A published revision cannot be reused with different content');
46
+ export function prepareCompositeFiles({context,targets,config,platforms=config.platforms??defaultCompositePlatforms(context),anchor=sortByAnchor(platforms,installerRegistryOf(context))[0],profileInputs,modelConfigs,previous}){
47
+ const mode=assertVerifiedInstallMode({safeFs:context.safeFs,targets,platforms:context.platforms});
48
+ previous??=mode.mode==='composite'?{platforms:mode.platforms,anchor:mode.anchor}:undefined;
49
+ const {runtimePlatforms}=context;
50
+ config=validateRoleRoutingConfig(config,{runtimePlatforms});
51
+ const bytes=Buffer.from(serializeRoleRoutingConfig(config)),snapshot=new Map(),active=activePath(targets,anchor),activeFile=read(context.safeFs,active,snapshot);
52
+ const previousActive=activePath(targets,previous?.anchor??anchor),previousFile=previousActive===active?activeFile:read(context.safeFs,previousActive,snapshot);
53
+ let previousConfig=null;if(previousFile.exists)try{previousConfig=parseInstalledRoutingConfig(previousFile.bytes.toString('utf8'),{runtimePlatforms});}catch{fail('Existing composite configuration cannot be verified');}
54
+ if(previousConfig?.revision===config.revision&&!previousFile.bytes.equals(bytes))fail('A published revision cannot be reused with different content');
50
55
  const markers={},existingProfiles={},desired={};
51
- for(const platform of ['codex','claude']){
56
+ for(const platform of platforms){
52
57
  const target=targets[platform],found=read(context.safeFs,markerPath(target),snapshot);let marker=null;
53
58
  if(found.exists)try{marker=JSON.parse(found.bytes.toString('utf8'));}catch{fail('Existing composite marker cannot be verified');}
54
59
  const oldRoles=marker&&marker.profiles&&typeof marker.profiles==='object'&&!Array.isArray(marker.profiles)?Object.keys(marker.profiles):[];
55
- if(marker&&(!exact(marker,['version','revision','platform','targetHome','activeConfigPath','configHash','runtime','profiles'])||marker.version!==1||typeof marker.revision!=='string'||!marker.revision||marker.platform!==platform||marker.targetHome!==target.home||marker.activeConfigPath!==active||!validHash(marker.configHash)||!exact(marker.runtime,['version','hash','policyHash'])||typeof marker.runtime.version!=='string'||!marker.runtime.version||!validHash(marker.runtime.hash)||!validHash(marker.runtime.policyHash)||oldRoles.some(role=>!ROUTING_ROLES.includes(role))||previous&&(marker.revision!==previous.revision||marker.configHash!==digest(activeFile.bytes)||!exact(marker.profiles,ROUTING_ROLES.filter(role=>previous.roles[role].platform===platform)))))fail('Existing composite marker does not match configuration');
60
+ if(marker&&(!exact(marker,['version','revision','platform','targetHome','activeConfigPath','configHash','runtime','profiles'])||marker.version!==1||typeof marker.revision!=='string'||!marker.revision||marker.platform!==platform||marker.targetHome!==target.home||marker.activeConfigPath!==previousActive||!validHash(marker.configHash)||!exact(marker.runtime,['version','hash','policyHash'])||typeof marker.runtime.version!=='string'||!marker.runtime.version||!validHash(marker.runtime.hash)||!validHash(marker.runtime.policyHash)||oldRoles.some(role=>!ROUTING_ROLES.includes(role))||previousConfig&&(marker.revision!==previousConfig.revision||marker.configHash!==digest(previousFile.bytes)||!exact(marker.profiles,ROUTING_ROLES.filter(role=>previousConfig.roles[role].platform===platform)))))fail('Existing composite marker does not match configuration');
56
61
  markers[platform]=marker;existingProfiles[platform]={};
57
62
  for(const role of ROUTING_ROLES){
58
- const filename=profilePath(target,role),file=read(context.safeFs,filename,snapshot),old=marker?.profiles?.[role];
63
+ const filename=profilePath(target,role,runtimePlatforms),file=read(context.safeFs,filename,snapshot),old=marker?.profiles?.[role];
59
64
  if(old&&(!exact(old,['path','hash'])||old.path!==path.relative(target.home,filename).split(path.sep).join('/')||!file.exists||old.hash!==digest(file.bytes)))fail('Existing composite profile does not match its marker');
60
65
  if(file.exists&&!old)fail('Unmanaged composite profile already exists');
61
66
  existingProfiles[platform][role]=Boolean(old);
62
67
  }
63
- const settings=resolveModelSettings(modelConfigs[platform]),field=platform==='codex'?'model_reasoning_effort':'effort';
64
- for(const role of ROUTING_ROLES)if(config.roles[role].platform===platform)settings.roles[role]={model:config.roles[role].model,[field]:config.roles[role].effort};
65
- const rendered=renderProfiles(profileInputs[platform],settings);desired[platform]={};
66
- for(const role of ROUTING_ROLES.filter(role=>config.roles[role].platform===platform)){
67
- const original=`${role.replace('_','-')}.${platform==='codex'?'toml':'md'}`,value=rendered.get(original);if(!value)fail('Composite profile source is unavailable');
68
- desired[platform][role]=renameCompositeProfile(value,platform,role,config.revision);
68
+ const roles=ROUTING_ROLES.filter(role=>config.roles[role].platform===platform);if(!roles.length)continue;
69
+ const descriptor=installerRegistryOf(context).getPlatform(platform),settings=resolveModelSettings(modelConfigs[platform],{runtimePlatforms}),field=descriptor.models.effortField;
70
+ for(const role of roles)settings.roles[role]={model:config.roles[role].model,[field]:config.roles[role].effort};
71
+ const rendered=renderProfiles(profileInputs[platform],settings,{runtimePlatforms,renderProfile:descriptor.profiles.render});desired[platform]={};
72
+ for(const role of roles){
73
+ const original=standaloneProfileFile(descriptor.runtime,role),value=rendered.get(original);if(!value)fail('Composite profile source is unavailable');
74
+ desired[platform][role]=renameCompositeProfile(value,platform,role,config.revision,context);
69
75
  }
70
76
  }
71
- if(previous&&!Object.values(markers).some(Boolean))fail('Existing composite configuration has no ownership marker');
77
+ if(previousConfig&&!Object.values(markers).some(Boolean)&&!previous?.platforms.some(platform=>!platforms.includes(platform)))fail('Existing composite configuration has no ownership marker');
72
78
  const standaloneRemovals=[],residualPaths=[];
73
- for(const platform of ['codex','claude'])for(const role of ROUTING_ROLES){const found=inspectStandaloneProfile({safeFs:context.safeFs,target:targets[platform],role,snapshot});if(found.owned)standaloneRemovals.push(found.path);else if(found.exists)residualPaths.push(found.path);}
74
- const managedPaths=[...standaloneRemovals,active,...['codex','claude'].flatMap(platform=>[markerPath(targets[platform]),...ROUTING_ROLES.map(role=>profilePath(targets[platform],role))])];
75
- return {target:targets.codex,targets,config,bytes,snapshot,managedPaths,externalPaths:[],desired,existingProfiles,standaloneRemovals,residualPaths};
79
+ for(const platform of platforms)for(const role of ROUTING_ROLES){const found=inspectStandaloneProfile({safeFs:context.safeFs,target:targets[platform],role,snapshot,platforms:context.platforms});if(found.owned)standaloneRemovals.push(found.path);else if(found.exists)residualPaths.push(found.path);}
80
+ const transitionRemovals=[],standaloneWrites=[],externalPaths=[],removed=(previous?.platforms??[]).filter(platform=>!platforms.includes(platform));
81
+ const payload=removed.length?verifyPayload(context):null;
82
+ for(const platform of removed){
83
+ const target=targets[platform],owned=inspectCompositeRemoval({target,safeFs:context.safeFs,activeConfigPath:previousActive,snapshot,runtimePlatforms});
84
+ transitionRemovals.push(...owned.removals);residualPaths.push(...owned.residualPaths);
85
+ const restored=restoreStandaloneSpecs({context,target,payload,snapshot});standaloneWrites.push(...restored.writes);externalPaths.push(...restored.externalPaths);residualPaths.push(...restored.residualPaths);
86
+ }
87
+ if(previous&&previous.anchor!==anchor)transitionRemovals.push(previousActive);
88
+ const managedPaths=[...new Set([...standaloneRemovals,active,...platforms.flatMap(platform=>[markerPath(targets[platform]),...ROUTING_ROLES.map(role=>profilePath(targets[platform],role,runtimePlatforms))]),...transitionRemovals,...standaloneWrites.map(spec=>spec.path)])];
89
+ return {target:targets[anchor],targets,platforms,anchor,previous,config,bytes,snapshot,managedPaths,externalPaths,desired,existingProfiles,standaloneRemovals,transitionRemovals:[...new Set(transitionRemovals)],standaloneWrites,residualPaths};
76
90
  }
77
91
 
78
92
  export function readCompositeRoutingConfig(context,targets){
79
- const snapshot=new Map(),found=read(context.safeFs,activePath(targets),snapshot);if(!found.exists)return null;
80
- return parseRoleRoutingConfig(found.bytes.toString('utf8'));
93
+ const {anchor}=readInstallMode({safeFs:context.safeFs,targets,platforms:context.platforms});if(!anchor)return null;
94
+ const snapshot=new Map(),found=read(context.safeFs,activePath(targets,anchor),snapshot);if(!found.exists)return null;
95
+ return parseInstalledRoutingConfig(found.bytes.toString('utf8'),{runtimePlatforms:context.runtimePlatforms});
81
96
  }
82
97
 
83
98
  /** Return only composite paths whose current bytes match the active marker. */
84
- export function inspectCompositeRemoval({target,safeFs,activeConfigPath,snapshot}){
99
+ export function inspectCompositeRemoval({target,safeFs,activeConfigPath,snapshot,runtimePlatforms}){
85
100
  const markerFile=read(safeFs,markerPath(target),snapshot),activeFile=activeConfigPath?read(safeFs,activeConfigPath,snapshot):{exists:false},files={};
86
- for(const role of ROUTING_ROLES)files[role]=read(safeFs,profilePath(target,role),snapshot);
87
- const existing=[...(markerFile.exists?[markerPath(target)]:[]),...ROUTING_ROLES.filter(role=>files[role].exists).map(role=>profilePath(target,role)),...(target.platform==='codex'&&activeFile.exists?[activeConfigPath]:[])];
101
+ for(const role of ROUTING_ROLES)files[role]=read(safeFs,profilePath(target,role,runtimePlatforms),snapshot);
102
+ const existing=[...(markerFile.exists?[markerPath(target)]:[]),...ROUTING_ROLES.filter(role=>files[role].exists).map(role=>profilePath(target,role,runtimePlatforms)),...(activeFile.exists&&target.home===path.dirname(activeConfigPath)?[activeConfigPath]:[])];
88
103
  if(!existing.length)return {removals:[],residualPaths:[]};
89
104
  try{
90
105
  if(!activeFile.exists||!markerFile.exists)throw Error('Incomplete composite ownership');
91
- const config=parseRoleRoutingConfig(activeFile.bytes.toString('utf8')),marker=JSON.parse(markerFile.bytes.toString('utf8')),roles=ROUTING_ROLES.filter(role=>config.roles[role].platform===target.platform);
106
+ const config=parseInstalledRoutingConfig(activeFile.bytes.toString('utf8'),{runtimePlatforms}),marker=JSON.parse(markerFile.bytes.toString('utf8')),roles=ROUTING_ROLES.filter(role=>config.roles[role].platform===target.platform);
92
107
  if(!exact(marker,['version','revision','platform','targetHome','activeConfigPath','configHash','runtime','profiles'])||marker.version!==1||marker.revision!==config.revision||marker.platform!==target.platform||marker.targetHome!==target.home||marker.activeConfigPath!==activeConfigPath||marker.configHash!==digest(activeFile.bytes)||!exact(marker.profiles,roles))throw Error('Marker mismatch');
93
- for(const role of ROUTING_ROLES){const entry=marker.profiles[role],file=files[role],relative=path.relative(target.home,profilePath(target,role)).split(path.sep).join('/');if(entry&&(!exact(entry,['path','hash'])||entry.path!==relative||!file.exists||entry.hash!==digest(file.bytes))||file.exists&&!entry)throw Error('Profile ownership mismatch');}
108
+ for(const role of ROUTING_ROLES){const entry=marker.profiles[role],file=files[role],relative=path.relative(target.home,profilePath(target,role,runtimePlatforms)).split(path.sep).join('/');if(entry&&(!exact(entry,['path','hash'])||entry.path!==relative||!file.exists||entry.hash!==digest(file.bytes))||file.exists&&!entry)throw Error('Profile ownership mismatch');}
94
109
  return {removals:existing,residualPaths:[]};
95
110
  }catch{return {removals:[],residualPaths:existing};}
96
111
  }
97
112
 
98
- /** A non-terminal bridge lease still owns a running or unverified child, so composite settings cannot change under it. Native leases never block. */
99
- async function assertNoActiveBridgeDispatch(codexHome){
113
+ const forceFinishableLease=lease=>lease.route==='native'&&NON_TERMINAL_STATES.includes(lease.state)||lease.route==='bridge'&&lease.state==='reserved';
114
+ const blockingDispatch=(home,lease)=>({home,dispatchId:lease.dispatchId,role:lease.role,workflowId:lease.workflowId,route:lease.route,state:lease.state,hostPlatform:lease.hostPlatform,updatedAt:lease.updatedAt,forceFinishable:forceFinishableLease(lease)});
115
+
116
+ /** Non-terminal bridge leases block composite changes; native leases only block anchor moves. */
117
+ async function assertNoActiveBridgeDispatch(codexHome,runtimePlatforms){
100
118
  let leases;
101
- try{leases=await listLeases(codexHome);}
119
+ try{leases=await listLeases(codexHome,{runtimePlatforms});}
102
120
  catch(cause){const error=new TargetConfigurationError('Dispatch leases cannot be read; composite settings are not published',{cause});error.activation='held';error.activeDispatches=null;throw error;}
103
- const active=leases.filter(lease=>lease.route==='bridge'&&NON_TERMINAL_STATES.includes(lease.state)).map(lease=>lease.dispatchId);
104
- if(active.length){const error=new TargetConfigurationError('Active bridge dispatches block composite publication; finish or cancel them first');error.activation='held';error.activeDispatches=active;throw error;}
121
+ const blocking=leases.filter(lease=>lease.route==='bridge'&&NON_TERMINAL_STATES.includes(lease.state)).map(lease=>blockingDispatch(codexHome,lease));
122
+ if(blocking.length){const error=new TargetConfigurationError('Active bridge dispatches block composite publication; finish or cancel them first');error.activation='held';error.activeDispatches=[...new Set(blocking.map(entry=>entry.dispatchId))];error.blockingDispatches=blocking;throw error;}
123
+ }
124
+ async function assertNoActiveMovingDispatches(homes,runtimePlatforms){
125
+ let blocking;
126
+ try{blocking=(await Promise.all(homes.map(async home=>(await listLeases(home,{runtimePlatforms})).filter(lease=>NON_TERMINAL_STATES.includes(lease.state)).map(lease=>blockingDispatch(home,lease))))).flat();}
127
+ catch(cause){const error=new TargetConfigurationError('Dispatch leases cannot be read; composite settings are not published',{cause});error.activation='held';error.activeDispatches=null;throw error;}
128
+ const active=[...new Set(blocking.map(entry=>entry.dispatchId))];
129
+ if(active.length){const error=new TargetConfigurationError('Active dispatches block moving mixed routing; finish or cancel them first');error.activation='held';error.activeDispatches=active;error.blockingDispatches=blocking;throw error;}
130
+ }
131
+
132
+ export async function forceFinishDispatches({context,entries,now=Date.now(),acquireLock=acquireRoleRoutingLock}){
133
+ const homes=new Map(),releases=[],finished=[],skipped=[],residualPaths=[],{runtimePlatforms}=context;
134
+ let failure,failed=false;
135
+ for(const entry of entries){if(!homes.has(entry.home))homes.set(entry.home,[]);homes.get(entry.home).push(entry);}
136
+ try{
137
+ for(const home of homes.keys())releases.push({home,release:await acquireLock(home)});
138
+ for(const [home,entries]of homes)for(const entry of entries){
139
+ const lease=await readLease(home,entry.dispatchId,{runtimePlatforms});
140
+ if(!lease||!NON_TERMINAL_STATES.includes(lease.state)||lease.state!==entry.state||lease.updatedAt!==entry.updatedAt){skipped.push({dispatchId:entry.dispatchId,reason:'changed'});continue;}
141
+ if(!forceFinishableLease(lease)){skipped.push({dispatchId:entry.dispatchId,reason:'not_eligible'});continue;}
142
+ await writeLease(home,{...lease,state:'cancelled',claims:{...(lease.claims??{}),terminal:{level:'operator-attested',source:'installer-force-finish',observed:'cancelled'}},reasons:[]},{now,runtimePlatforms});
143
+ finished.push(entry.dispatchId);
144
+ }
145
+ }catch(error){failure=error;failed=true;}
146
+ for(const {home,release}of releases.reverse()){let released=false;try{released=await release();}catch{}if(!released)residualPaths.push(path.join(home,'arc-role-platform-routing.lock'));}
147
+ if(failed||residualPaths.length){
148
+ if(!failed)failure=new TargetConfigurationError('Dispatch lock ownership could not be verified');
149
+ else if(!failure||typeof failure!=='object')failure=new Error('Force finish failed',{cause:failure});
150
+ if(residualPaths.length){failure.residualPaths=[...new Set([...(Array.isArray(failure.residualPaths)?failure.residualPaths:[]),...residualPaths])];failure.lockReleaseFailed=true;}
151
+ failure.forceFinish={finished,skipped};throw failure;
152
+ }
153
+ return {finished,skipped,residualPaths};
154
+ }
155
+ // A joining anchor may not have an installation yet. Retain descriptors so a
156
+ // refused move can remove only the empty directories created for its locks.
157
+ function prepareLockHome({safeFs,home,created,handles}){
158
+ let directory=safeFs.openRoot('/'),filename='';handles.push(directory);
159
+ for(const name of home.split('/').filter(Boolean)){
160
+ filename+='/'+name;let stat;
161
+ try{stat=directory.lstat(name);}catch(error){if(error.code!=='ENOENT')throw error;directory.mkdir(name,0o700);stat=directory.lstat(name);created.push({parent:directory,name,path:filename,identity:stat});}
162
+ if(typeOf(stat)!==0o040000)fail(`Expected destination directory: ${filename}`);
163
+ const next=directory.openDir(name);handles.push(next);if(!sameObjectIdentity(stat,next.stat()))fail('Anchor home changed while preparing routing lock');directory=next;
164
+ }
105
165
  }
106
166
  /** Publication is serialized with T2's preflight; all execution paths remain held. */
107
- export async function publishCompositeFiles({context,prepared}){
108
- let release,published=false,publication,failure,failed=false;const {targets,config,bytes}=prepared;
167
+ export async function publishCompositeFiles({context,prepared,beforePublish}){
168
+ let published=false,publication,failure,failed=false,installing=false;const releases=[],created=[],handles=[],{targets,config,platforms=config.platforms??defaultCompositePlatforms(context),anchor=sortByAnchor(platforms,installerRegistryOf(context))[0],bytes}=prepared,{runtimePlatforms}=context;
169
+ const moving=prepared.previous&&prepared.previous.anchor!==anchor,anchors=moving?sortByAnchor([prepared.previous.anchor,anchor],installerRegistryOf(context)):[anchor];
170
+ // Larger composites lock every participating home in anchor order; preserve pair publication behavior.
171
+ const lockPlatforms=sortByAnchor([...new Set([...anchors,...(platforms.length>2?platforms:[])])],installerRegistryOf(context));
109
172
  try{
110
- release=await acquireRoleRoutingLock(targets.codex.home);
111
- await assertNoActiveBridgeDispatch(targets.codex.home);
173
+ if(moving)for(const id of lockPlatforms)prepareLockHome({safeFs:context.safeFs,home:targets[id].home,created,handles});
174
+ for(const id of lockPlatforms)releases.push({home:targets[id].home,release:await acquireRoleRoutingLock(targets[id].home)});
175
+ if(moving)await assertNoActiveMovingDispatches(anchors.map(id=>targets[id].home),runtimePlatforms);else await assertNoActiveBridgeDispatch(targets[anchor].home,runtimePlatforms);
176
+ // Management installs must run after the move guard and under both locks.
177
+ if(beforePublish){installing=true;await beforePublish({createdHomes:created.map(item=>item.path)});}
112
178
  assertPlanSnapshot(prepared,{safeFs:context.safeFs});
113
179
  const versions=await cooperativeVersions(),runtimeSnapshot=new Map(),markers={};
114
- for(const platform of ['codex','claude']){
180
+ for(const platform of platforms){
115
181
  const target=targets[platform],dir=path.join(target.home,'skills','arc','runtime'),modules=[];
116
182
  for(const name of COOPERATIVE_RUNTIME_MODULES){const file=read(context.safeFs,path.join(dir,name),runtimeSnapshot);if(!file.exists)fail('Installed cooperative runtime is incomplete');modules.push(file.bytes);}
117
183
  const policy=read(context.safeFs,path.join(dir,'role-policy.json'),runtimeSnapshot);if(!policy.exists)fail('Installed role policy is missing');
118
184
  const runtimeHash=digest(Buffer.concat(modules)),policyHash=digest(policy.bytes);
119
185
  if(runtimeHash!==versions.runtimeHash||policyHash!==versions.policyHash)fail('Installed runtime or policy differs from the current package');
120
- const profiles={};for(const [role,content] of Object.entries(prepared.desired[platform]))profiles[role]={path:path.relative(target.home,profilePath(target,role)).split(path.sep).join('/'),hash:digest(content)};
121
- markers[platform]={version:1,revision:config.revision,platform,targetHome:target.home,activeConfigPath:activePath(targets),configHash:digest(bytes),runtime:{version:versions.runtime,hash:runtimeHash,policyHash},profiles};
186
+ const profiles={};for(const [role,content] of Object.entries(prepared.desired[platform]??{}))profiles[role]={path:path.relative(target.home,profilePath(target,role,runtimePlatforms)).split(path.sep).join('/'),hash:digest(content)};
187
+ markers[platform]={version:1,revision:config.revision,platform,targetHome:target.home,activeConfigPath:activePath(targets,anchor),configHash:digest(bytes),runtime:{version:versions.runtime,hash:runtimeHash,policyHash},profiles};
122
188
  }
123
189
  assertPlanSnapshot({snapshot:runtimeSnapshot},{safeFs:context.safeFs});
124
- const specs=[...(prepared.modelWrites??[]),...(prepared.standaloneRemovals??[]).map(path=>({path,remove:true}))];
125
- for(const platform of ['codex','claude'])for(const role of ROUTING_ROLES){const filename=profilePath(targets[platform],role),content=prepared.desired[platform][role];if(content)specs.push({path:filename,bytes:content});else if(prepared.existingProfiles[platform][role])specs.push({path:filename,remove:true});}
126
- for(const platform of ['codex','claude'])specs.push({path:markerPath(targets[platform]),bytes:Buffer.from(JSON.stringify(markers[platform],null,2)+'\n')});
127
- specs.push({path:activePath(targets),bytes});
128
- const hooks={...context.hooks,fault:event=>{if(event.phase==='before-publish'&&event.path===activePath(targets))assertPlanSnapshot({snapshot:runtimeSnapshot},{safeFs:context.safeFs});context.hooks?.fault?.(event);}};
190
+ const specs=[...(prepared.modelWrites??[]),...(prepared.standaloneRemovals??[]).map(path=>({path,remove:true})),...(prepared.transitionRemovals??[]).map(path=>({path,remove:true})),...(prepared.standaloneWrites??[])];
191
+ for(const platform of platforms)for(const role of ROUTING_ROLES){const filename=profilePath(targets[platform],role,runtimePlatforms),content=prepared.desired[platform]?.[role];if(content)specs.push({path:filename,bytes:content});else if(prepared.existingProfiles[platform][role])specs.push({path:filename,remove:true});}
192
+ for(const platform of platforms)specs.push({path:markerPath(targets[platform]),bytes:Buffer.from(JSON.stringify(markers[platform],null,2)+'\n')});
193
+ specs.push({path:activePath(targets,anchor),bytes});
194
+ const hooks={...context.hooks,fault:event=>{if(event.phase==='before-publish'&&event.path===activePath(targets,anchor))assertPlanSnapshot({snapshot:runtimeSnapshot},{safeFs:context.safeFs});context.hooks?.fault?.(event);}};
129
195
  let result;try{result=applyTransaction(prepared,{safeFs:context.safeFs,signal:context.signal,hooks,specs});}catch(error){error.activation=error.rollback==='restored'?'held':'unknown';throw error;}
130
196
  published=true;publication={published:true,revision:config.revision,residualPaths:[...(prepared.residualPaths??[]),...result.residualPaths],cleanupError:result.cleanupError};
131
197
  }catch(error){failure=error;failed=true;}
132
- let released=true;if(release)try{released=await release();}catch{released=false;}
133
- if(!released){
134
- const lockPath=path.join(targets.codex.home,'arc-role-platform-routing.lock');
198
+ const failedLocks=[];
199
+ for(const {home,release}of releases.reverse()){let released=false;try{released=await release();}catch{}if(!released)failedLocks.push(path.join(home,'arc-role-platform-routing.lock'));}
200
+ if(failedLocks.length){
135
201
  if(failed){
136
202
  if(!failure||typeof failure!=='object')failure=new Error('Composite publication failed',{cause:failure});
137
- failure.residualPaths=[...new Set([...(Array.isArray(failure.residualPaths)?failure.residualPaths:[]),lockPath])];failure.lockReleaseFailed=true;
203
+ failure.residualPaths=[...new Set([...(Array.isArray(failure.residualPaths)?failure.residualPaths:[]),...failedLocks])];failure.lockReleaseFailed=true;
204
+ if(moving)failure.activation??=published?'unknown':'held';
138
205
  failure.message=(typeof failure.message==='string'?failure.message:'Composite publication failed')+'; Composite publication lock ownership could not be verified';
139
206
  }else{
140
207
  failure=new TargetConfigurationError('Composite publication lock ownership could not be verified',publication?.cleanupError?{cause:publication.cleanupError}:undefined);
141
208
  failure.activation=published?'unknown':'held';failure.lockReleaseFailed=true;
142
- failure.residualPaths=[...new Set([...(Array.isArray(publication?.residualPaths)?publication.residualPaths:[]),...(Array.isArray(publication?.cleanupError?.residualPaths)?publication.cleanupError.residualPaths:[]),lockPath])];
209
+ failure.residualPaths=[...new Set([...(Array.isArray(publication?.residualPaths)?publication.residualPaths:[]),...(Array.isArray(publication?.cleanupError?.residualPaths)?publication.cleanupError.residualPaths:[]),...failedLocks])];
143
210
  if(publication?.cleanupError)failure.cleanupError=publication.cleanupError;
144
211
  failed=true;
145
212
  }
146
213
  }
214
+ if(!installing&&!published)for(const item of created.reverse())try{
215
+ if(!sameObjectIdentity(item.identity,item.parent.lstat(item.name)))throw Error('Created anchor directory identity changed');
216
+ item.parent.rmdir(item.name);
217
+ }catch{
218
+ failure??=new TargetConfigurationError('Anchor lock directory cleanup could not be verified');failure.activation??='held';failure.residualPaths=[...new Set([...(failure.residualPaths??[]),item.path])];failed=true;
219
+ }
220
+ for(const handle of handles.reverse())handle.close();
147
221
  if(failed)throw failure;
148
222
  return publication;
149
223
  }
150
224
 
225
+ function restoreStandaloneSpecs({context,target,payload,snapshot}){
226
+ const writes=[],residualPaths=[],externalPaths=[],platform=target.platform;
227
+ const arc=path.join(target.home,'skills/arc');if(!inspectPath(context.safeFs,arc,{kind:'directory',snapshot}).exists)return{writes,residualPaths,externalPaths};
228
+ const inputs={};for(const name of ['models.toml','settings.toml']){const filename=path.join(arc,name),found=read(context.safeFs,filename,snapshot);if(!found.exists)fail(`Installed settings missing: ${filename}`);inputs[name]=found.bytes;externalPaths.push(filename);}
229
+ const profiles=renderStandaloneProfiles({payload,target,modelConfig:loadModelConfig(inputs['models.toml'],platform,{runtimePlatforms:context.runtimePlatforms}),language:parseLanguage(inputs['settings.toml']).language,platforms:context.platforms,runtimePlatforms:context.runtimePlatforms});
230
+ for(const role of ROUTING_ROLES){const found=inspectStandaloneProfile({safeFs:context.safeFs,target,role,snapshot,platforms:context.platforms});if(found.exists&&!found.owned){residualPaths.push(found.path);continue;}writes.push({path:found.path,bytes:profiles.get(path.basename(found.path))});}
231
+ return{writes,residualPaths,externalPaths};
232
+ }
151
233
  /** Restore standalone profiles and remove verified routing files in one transaction. */
152
- export function prepareCompositeDeactivation({context,targets,payload}){
153
- const snapshot=new Map();assertVerifiedInstallMode({safeFs:context.safeFs,targets,snapshot});
234
+ export function prepareCompositeDeactivation({context,targets,payload,platforms=assertVerifiedInstallMode({safeFs:context.safeFs,targets,platforms:context.platforms}).platforms,anchor=sortByAnchor(platforms,installerRegistryOf(context))[0]}){
235
+ const snapshot=new Map();assertVerifiedInstallMode({safeFs:context.safeFs,targets,snapshot,platforms:context.platforms});
154
236
  const removals=[],writes=[],residualPaths=[],externalPaths=[];
155
- for(const platform of ['codex','claude']){
156
- const target=targets[platform],owned=inspectCompositeRemoval({target,safeFs:context.safeFs,activeConfigPath:activePath(targets),snapshot});removals.push(...owned.removals);
157
- const arc=path.join(target.home,'skills/arc');if(!inspectPath(context.safeFs,arc,{kind:'directory',snapshot}).exists)continue;
158
- const inputs={};for(const name of ['models.toml','settings.toml']){const filename=path.join(arc,name),found=read(context.safeFs,filename,snapshot);if(!found.exists)fail(`Installed settings missing: ${filename}`);inputs[name]=found.bytes;externalPaths.push(filename);}
159
- const profiles=renderStandaloneProfiles({payload,target,modelConfig:loadModelConfig(inputs['models.toml'],platform),language:parseLanguage(inputs['settings.toml']).language});
160
- for(const role of ROUTING_ROLES){const found=inspectStandaloneProfile({safeFs:context.safeFs,target,role,snapshot});if(found.exists&&!found.owned){residualPaths.push(found.path);continue;}writes.push({path:found.path,bytes:profiles.get(path.basename(found.path))});}
237
+ for(const platform of platforms){
238
+ const target=targets[platform],owned=inspectCompositeRemoval({target,safeFs:context.safeFs,activeConfigPath:activePath(targets,anchor),snapshot,runtimePlatforms:context.runtimePlatforms});removals.push(...owned.removals);
239
+ const restored=restoreStandaloneSpecs({context,target,payload,snapshot});writes.push(...restored.writes);residualPaths.push(...restored.residualPaths);externalPaths.push(...restored.externalPaths);
161
240
  }
162
- return{target:targets.codex,targets,snapshot,managedPaths:[...new Set([...removals,...writes.map(item=>item.path)])],externalPaths,removals:[...new Set(removals)],writes,residualPaths};
241
+ return{target:targets[anchor],targets,platforms,anchor,snapshot,managedPaths:[...new Set([...removals,...writes.map(item=>item.path)])],externalPaths,removals:[...new Set(removals)],writes,residualPaths};
163
242
  }
164
243
  export async function publishCompositeDeactivation({context,prepared}){
165
- let release,result,failure;
244
+ let release,result,failure;const {anchor=sortByAnchor(prepared.platforms??installerRegistryOf(context).byAnchorOrder().map(descriptor=>descriptor.runtime.id),installerRegistryOf(context))[0]}=prepared;
166
245
  try{
167
- release=await acquireRoleRoutingLock(prepared.targets.codex.home);await assertNoActiveBridgeDispatch(prepared.targets.codex.home);
168
- assertPlanSnapshot(prepared,{safeFs:context.safeFs});assertVerifiedInstallMode({safeFs:context.safeFs,targets:prepared.targets});
246
+ release=await acquireRoleRoutingLock(prepared.targets[anchor].home);await assertNoActiveBridgeDispatch(prepared.targets[anchor].home,context.runtimePlatforms);
247
+ assertPlanSnapshot(prepared,{safeFs:context.safeFs});assertVerifiedInstallMode({safeFs:context.safeFs,targets:prepared.targets,platforms:context.platforms});
169
248
  const applied=applyTransaction(prepared,{safeFs:context.safeFs,signal:context.signal,hooks:context.hooks,specs:[...prepared.removals.map(path=>({path,remove:true})),...prepared.writes]});
170
249
  result={residualPaths:[...prepared.residualPaths,...applied.residualPaths],cleanupError:applied.cleanupError};
171
250
  }catch(error){failure=error;}
172
251
  let released=true;if(release)try{released=await release();}catch{released=false;}
173
- if(!released){const lockPath=path.join(prepared.targets.codex.home,'arc-role-platform-routing.lock');failure??=new TargetConfigurationError('Composite publication lock ownership could not be verified');failure.lockReleaseFailed=true;failure.residualPaths=[...new Set([...(failure.residualPaths??[]),...(result?.residualPaths??[]),lockPath])];if(result?.cleanupError)failure.cleanupError=result.cleanupError;}
252
+ if(!released){const lockPath=path.join(prepared.targets[anchor].home,'arc-role-platform-routing.lock');failure??=new TargetConfigurationError('Composite publication lock ownership could not be verified');failure.lockReleaseFailed=true;failure.residualPaths=[...new Set([...(failure.residualPaths??[]),...(result?.residualPaths??[]),lockPath])];if(result?.cleanupError)failure.cleanupError=result.cleanupError;}
174
253
  if(failure)throw failure;return result;
175
254
  }
@@ -14,11 +14,13 @@ export const RUNTIME_MODULE_PATHS = Object.freeze([
14
14
  'lib/runtime/evaluate.mjs',
15
15
  'lib/runtime/external.mjs',
16
16
  'lib/runtime/gate.mjs',
17
+ 'lib/runtime/gemini-stream.mjs',
17
18
  'lib/runtime/git-evidence.mjs',
18
19
  'lib/runtime/git-query.mjs',
19
20
  'lib/runtime/identity.mjs',
20
21
  'lib/runtime/local-cli.mjs',
21
22
  'lib/runtime/operations.mjs',
23
+ 'lib/runtime/platform-registry.mjs',
22
24
  'lib/runtime/role-bridge-args.mjs',
23
25
  'lib/runtime/role-bridge.mjs',
24
26
  'lib/runtime/role-dispatch-policy.mjs',
@@ -83,3 +83,6 @@ export function renderClaudeConcurrency(original,value) {
83
83
  if(!isDeepStrictEqual(JSON.parse(content),data))fail('Cannot verify safe Claude concurrency edit');
84
84
  return {content,action:'set Claude concurrency'};
85
85
  }
86
+
87
+ export const readCodexConcurrency = original => readRuntimeConcurrency('codex', original);
88
+ export const readClaudeConcurrency = original => readRuntimeConcurrency('claude', original);
@@ -1,10 +1,10 @@
1
1
  export const SHARED_SKILL_PREFIX='shared/skill/';
2
2
  export const GENERATED_SKILL_FILES=Object.freeze(['SKILL.md','models.toml','settings.toml','limits.toml']);
3
3
 
4
- export function composeSkillSources(files,platform){
4
+ export function composeSkillSources(files,platform,context={}){
5
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/';
6
+ const descriptor=installerRegistryOf(context).getPlatform(platform);if(!descriptor)throw Error(`Invalid skill source platform: ${platform}`);
7
+ const shared=new Map(),selected=new Map(),prefix=descriptor.payloadPrefix+'/skill/';
8
8
  for(const [name,bytes]of files){
9
9
  if(name.startsWith(SHARED_SKILL_PREFIX))shared.set(name.slice(SHARED_SKILL_PREFIX.length),bytes);
10
10
  else if(name.startsWith(prefix))selected.set(name.slice(prefix.length),bytes);
@@ -21,3 +21,4 @@ export function composeSkillSources(files,platform){
21
21
  }
22
22
  return new Map(names.map(name=>[name,Buffer.from(union.get(name))]));
23
23
  }
24
+ import {installerRegistryOf} from '../platforms/index.mjs';
@@ -1,4 +1,5 @@
1
1
  import path from 'node:path';
2
+ import {DEFAULT_INSTALLER_REGISTRY} from '../platforms/index.mjs';
2
3
  import {createHash} from 'node:crypto';
3
4
  import {readCheckedFile,sameIdentity,typeOf,metadataOf} from './targets.mjs';
4
5
  export const REQUIRED=Object.freeze({
@@ -8,7 +9,7 @@ export const REQUIRED=Object.freeze({
8
9
  });
9
10
  export const SKILLS=Object.freeze(Object.keys(REQUIRED));
10
11
  export const REPOSITORY='https://github.com/obra/superpowers';
11
- export const DYNAMIC_ROOTS=Object.freeze(['codex','claude','shared'].map(platform=>`${platform}/skill/references/superpowers`));
12
+ export const DYNAMIC_ROOTS=Object.freeze([...DEFAULT_INSTALLER_REGISTRY.platformIds(),'shared'].map(platform=>`${platform}/skill/references/superpowers`));
12
13
  export const isDynamicReferencePath=name=>DYNAMIC_ROOTS.some(root=>name===root||name.startsWith(root+'/'));
13
14
  export const REFERENCE_PATH_MAP=Object.freeze([
14
15
  ['brainstorming/SKILL.md','brainstorming.md'],['writing-plans/SKILL.md','writing-plans.md'],['test-driven-development/SKILL.md','test-driven-development.md'],
@@ -0,0 +1 @@
1
+ export class TargetConfigurationError extends Error{constructor(message,options){super(message,options);this.name='TargetConfigurationError';this.code='ARC_TARGET_CONFIGURATION';}}
@@ -1,11 +1,19 @@
1
- import {resolveConfigHome} from '../runtime/local-cli.mjs';
1
+ import {installerRegistryOf} from '../platforms/index.mjs';
2
+ import {standaloneProfileFile} from '../runtime/platform-registry.mjs';
2
3
  import path from 'node:path';import crypto from 'node:crypto';
3
- export class TargetConfigurationError extends Error{constructor(message,options){super(message,options);this.name='TargetConfigurationError';this.code='ARC_TARGET_CONFIGURATION';}}
4
+ import {TargetConfigurationError} from './target-errors.mjs';
5
+ export {TargetConfigurationError} from './target-errors.mjs';
4
6
  const fail=message=>{throw new TargetConfigurationError(message);};
5
- export function resolveTarget(platform,{userHome,env={},cwd}={}){
6
- let home;try{home=resolveConfigHome(platform,{userHome,env,cwd});}catch(error){fail(error.message);}
7
- const profileNames=['scouter','planner','implementer','qa','reviewer'].map(role=>`arc-${role}.${platform==='codex'?'toml':'md'}`);
8
- return Object.freeze({platform,home,userHome:path.resolve(userHome),payloadPrefix:platform,profileNames:Object.freeze(profileNames),instructionPath:path.join(home,platform==='codex'?'AGENTS.md':'CLAUDE.md'),runtimeConfigPath:path.join(home,platform==='codex'?'config.toml':'settings.json'),globalPaths:Object.freeze(platform==='codex'?[path.join(home,'AGENTS.md'),path.join(home,'config.toml')]:[path.join(home,'CLAUDE.md'),path.join(home,'settings.json')])});
7
+ export function resolveTarget(platform,{userHome,env={},cwd,platforms}={}){
8
+ const descriptor=installerRegistryOf({platforms}).getPlatform(platform);if(!descriptor)fail('Target must be codex or claude');
9
+ let home;try{home=descriptor.runtime.home.resolve({userHome,env,cwd});}catch(error){fail(error.message);}
10
+ const profileNames=['scouter','planner','implementer','qa','reviewer'].map(role=>standaloneProfileFile(descriptor.runtime,`arc_${role}`));
11
+ return Object.freeze({platform,home,userHome:path.resolve(userHome),payloadPrefix:descriptor.payloadPrefix,profileNames:Object.freeze(profileNames),instructionPath:path.join(home,descriptor.instructionFile),runtimeConfigPath:path.join(home,descriptor.runtimeConfigFile),globalPaths:Object.freeze(descriptor.globalPaths.map(name=>path.join(home,name)))});
12
+ }
13
+ export function resolveTargets(context={}){
14
+ const targets={},unresolved=[];
15
+ for(const {runtime:{id}}of installerRegistryOf(context).byAnchorOrder())try{targets[id]=resolveTarget(id,context);}catch(error){unresolved.push({platform:id,error});}
16
+ return{targets,unresolved};
9
17
  }
10
18
  export function typeOf(metadata){return Number(metadata.mode&0o170000n);}
11
19
  export function sameObjectIdentity(a,b){return ['dev','ino','mode'].every(key=>a[key]===b[key]);}
@@ -1,4 +1,5 @@
1
1
  import {inspectStandaloneProfile} from './install-mode.mjs';
2
+ import {installerRegistryOf} from '../platforms/index.mjs';
2
3
  import path from 'node:path';
3
4
  import {inspectPath,sameIdentity,TargetConfigurationError} from './targets.mjs';
4
5
  import {SKILLS,snapshotSkill} from './superpowers.mjs';
@@ -6,10 +7,10 @@ import {validatePlanSet} from './plan.mjs';
6
7
  import {removeManagedBlock} from './global-config.mjs';
7
8
  import {attachShellCompletionCleanup} from './shell-completion.mjs';
8
9
  import {inspectCompositeRemoval} from './role-routing.mjs';
9
- export function buildUninstallPlan({target,safeFs,skipGlobal=false,removeCompletion=true,compositeActivePath}){
10
+ export function buildUninstallPlan({target,safeFs,skipGlobal=false,removeCompletion=true,compositeActivePath,platforms,runtimePlatforms}){
10
11
  const snapshot=new Map(),removals=[],managedPaths=[path.join(target.home,'skills/arc'),...target.profileNames.map(name=>path.join(target.home,'agents',name))],globalChanges=[];
11
12
  const standaloneResidual=[];
12
- for(const filename of managedPaths){if(filename===managedPaths[0]){const found=inspectPath(safeFs,filename,{kind:'directory',tree:true,allowLinks:true,snapshot});if(found.exists)removals.push(filename);}else{const found=inspectStandaloneProfile({safeFs,target,role:path.basename(filename).split('.')[0].replace('-','_'),snapshot});if(found.owned)removals.push(filename);else if(found.exists)standaloneResidual.push(filename);}}
13
+ for(const filename of managedPaths){if(filename===managedPaths[0]){const found=inspectPath(safeFs,filename,{kind:'directory',tree:true,allowLinks:true,snapshot});if(found.exists)removals.push(filename);}else{const found=inspectStandaloneProfile({safeFs,target,role:path.basename(filename).split('.')[0].replace('-','_'),snapshot,platforms});if(found.owned)removals.push(filename);else if(found.exists)standaloneResidual.push(filename);}}
13
14
  const linkedSkills=new Set(),arc=managedPaths[0];
14
15
  for(const[filename,entry]of snapshot){if(entry?.type!=='symlink'||!filename.startsWith(arc+'/'))continue;
15
16
  const relative=path.relative(arc,filename),parts=relative.split('/'),skill=parts[2];
@@ -18,9 +19,9 @@ export function buildUninstallPlan({target,safeFs,skipGlobal=false,removeComplet
18
19
  }
19
20
  for(const skill of linkedSkills){const root=arc+'/references/superpowers/'+skill,directory=safeFs.openRoot(root);try{if(!sameIdentity(snapshot.get(root),directory.stat()))throw new TargetConfigurationError('Removal reference root changed');snapshotSkill(directory,root,[]);}finally{directory.close();}}
20
21
  if(!skipGlobal){const filename=target.instructionPath??target.globalPaths[0],found=inspectPath(safeFs,filename,{kind:'file',read:true,snapshot});managedPaths.push(filename);if(found.exists){const removed=removeManagedBlock(found.bytes);if(removed.changed)globalChanges.push({path:filename,content:removed.content});}}
21
- const composite=inspectCompositeRemoval({target,safeFs,activeConfigPath:compositeActivePath,snapshot});
22
+ const composite=inspectCompositeRemoval({target,safeFs,activeConfigPath:compositeActivePath,snapshot,runtimePlatforms});
22
23
  removals.push(...composite.removals);managedPaths.push(...composite.removals);
23
- const plan={target,skipGlobal,snapshot,removals,managedPaths,externalPaths:[],globalChanges,compositeOwned:composite.removals.length>0,compositeResidual:[...standaloneResidual,...composite.residualPaths],summary:[target.platform==='codex'?'Codex config.toml wait settings and native concurrency key are preserved.':'Claude settings.json native concurrency key is preserved.']};
24
+ const plan={target,skipGlobal,snapshot,removals,managedPaths,externalPaths:[],globalChanges,compositeOwned:composite.removals.length>0,compositeResidual:[...standaloneResidual,...composite.residualPaths],summary:[installerRegistryOf({platforms}).getPlatform(target.platform).uninstallSummary]};
24
25
  if(removeCompletion)attachShellCompletionCleanup([plan],{safeFs});return plan;
25
26
  }
26
27
  import {assertPlanSnapshot,applyUninstallTransaction} from './transaction.mjs';
@@ -1,32 +1,36 @@
1
1
  import {readInstallMode,inspectStandaloneProfile} from './install-mode.mjs';
2
+ import {installerRegistryOf} from '../platforms/index.mjs';
2
3
  import path from 'node:path';
3
4
  import {createHash} from 'node:crypto';
4
- import {resolveTarget,inspectPath,TargetConfigurationError} from './targets.mjs';
5
+ import {resolveTargets,inspectPath,TargetConfigurationError} from './targets.mjs';
5
6
  import {loadModelConfig} from '../models/index.mjs';
6
7
  import {parseLanguage} from './language.mjs';
7
8
  import {parseLimits} from './limits.mjs';
8
9
  import {removeManagedBlock} from './global-config.mjs';
9
10
  import {removeShellCompletion} from './shell-completion.mjs';
10
- import {readRuntimeConcurrency} from './runtime-config.mjs';
11
11
  const fail=message=>{throw new TargetConfigurationError(message);};
12
- export function collectInstalledState({safeFs,userHome,env={},cwd}){
12
+ export function collectInstalledState({safeFs,userHome,env={},cwd,platforms,runtimePlatforms}){
13
13
  if(env.CODEX_HOME!==undefined&&!path.isAbsolute(env.CODEX_HOME)&&env.CODEX_HOME!=='~'&&!env.CODEX_HOME.startsWith('~/')&&(!cwd||!path.isAbsolute(cwd)))fail('A verified invocation cwd is required for relative CODEX_HOME');
14
- const modeSnapshot=new Map(),mode=readInstallMode({safeFs,targets:Object.fromEntries(['codex','claude'].map(p=>[p,resolveTarget(p,{userHome,env,cwd})])),snapshot:modeSnapshot}).mode,targets=[],residualPaths=[];
15
- for(const platform of ['codex','claude']){
16
- const target=resolveTarget(platform,{userHome,env,cwd}),snapshot=new Map(),arc=path.join(target.home,'skills/arc');
14
+ const registry=installerRegistryOf({platforms}),ids=registry.byAnchorOrder().map(descriptor=>descriptor.runtime.id);
15
+ const resolved=resolveTargets({userHome,env,cwd,platforms}),modeSnapshot=new Map(),installation=readInstallMode({safeFs,...resolved,snapshot:modeSnapshot,platforms}),mode=installation.mode,targets=[],residualPaths=[];
16
+ if(resolved.unresolved.some(({platform})=>installation.platforms.includes(platform)))fail('Mixed routing configuration cannot be verified.');
17
+ for(const platform of ids){
18
+ const target=resolved.targets[platform];if(!target)continue;
19
+ const snapshot=new Map(),arc=path.join(target.home,'skills/arc');
17
20
  const skill=inspectPath(safeFs,arc,{kind:'directory',tree:true,allowLinks:true,snapshot});
18
- const profiles=mode==='composite'?[]:target.profileNames.map(name=>inspectStandaloneProfile({safeFs,target,role:name.split('.')[0].replace('-','_'),snapshot}));
21
+ const profiles=mode==='composite'&&installation.platforms.includes(platform)?[]:target.profileNames.map(name=>inspectStandaloneProfile({safeFs,target,role:name.split('.')[0].replace('-','_'),snapshot,platforms}));
19
22
  const instruction=inspectPath(safeFs,target.instructionPath,{kind:'file',read:true,snapshot}),managed=instruction.exists?removeManagedBlock(instruction.bytes):{changed:false};
20
23
  if(!skill.exists){if(profiles.some(item=>item.exists&&item.owned)||managed.changed)fail(`Incomplete ARC installation: ${target.home}`);residualPaths.push(...profiles.filter(item=>item.exists&&!item.owned).map(item=>item.path));continue;}
21
24
  function mandatory(name){const found=inspectPath(safeFs,path.join(arc,name),{kind:'file',read:true,snapshot});if(!found.exists||!found.bytes.length)fail(`Incomplete ARC installation: missing ${name} at ${target.home}`);return found.bytes;}
22
25
  mandatory('SKILL.md');if(profiles.some(item=>!item.exists))fail(`Incomplete ARC installation: missing profile at ${target.home}`);
23
- let language,modelConfig,limits;try{language=parseLanguage(mandatory('settings.toml')).language;modelConfig=loadModelConfig(mandatory('models.toml'),platform);limits=parseLimits(mandatory('limits.toml'));}catch(cause){throw new TargetConfigurationError(`Invalid installed ARC settings at ${target.home}: ${cause.message}`,{cause});}
24
- const native=inspectPath(safeFs,target.runtimeConfigPath,{kind:'file',read:true,snapshot});if(native.exists)try{readRuntimeConcurrency(platform,native.bytes);}catch(cause){throw new TargetConfigurationError(`Invalid native configuration at ${target.runtimeConfigPath}: ${cause.message}`,{cause});}
26
+ let language,modelConfig,limits;try{language=parseLanguage(mandatory('settings.toml')).language;modelConfig=loadModelConfig(mandatory('models.toml'),platform,{runtimePlatforms});limits=parseLimits(mandatory('limits.toml'));}catch(cause){throw new TargetConfigurationError(`Invalid installed ARC settings at ${target.home}: ${cause.message}`,{cause});}
27
+ const runtimeConfig=registry.getPlatform(platform).runtimeConfig;
28
+ if(typeof runtimeConfig.readConcurrency==='function'){const native=inspectPath(safeFs,target.runtimeConfigPath,{kind:'file',read:true,snapshot});if(native.exists)try{runtimeConfig.readConcurrency(native.bytes);}catch(cause){throw new TargetConfigurationError(`Invalid native configuration at ${target.runtimeConfigPath}: ${cause.message}`,{cause});}}
25
29
  const shell=inspectPath(safeFs,path.join(userHome,'.zshrc'),{kind:'file',read:true,snapshot});if(shell.exists)removeShellCompletion(shell.bytes);
26
30
  if(mode==='composite')for(const [filename,value]of modeSnapshot)if(value)snapshot.set(filename,value);
27
31
  for(const [filename,value]of snapshot)if(!value)snapshot.delete(filename);
28
32
  targets.push({target,language,modelConfig,limits,snapshot,residualPaths:profiles.filter(item=>item.exists&&!item.owned).map(item=>item.path)});
29
33
  }
30
34
  const hash=createHash('sha256');for(const entry of targets){hash.update(entry.target.platform+'\0'+entry.target.home+'\0');for(const [name,value]of [...entry.snapshot].sort(([a],[b])=>a.localeCompare(b)))hash.update(JSON.stringify([name,value],(key,value)=>key==='atimeNs'?undefined:typeof value==='bigint'?value.toString():value));}
31
- return{targets,mode,residualPaths,stateToken:hash.digest('hex')};
35
+ return{targets,mode,platforms:installation.platforms,registry,residualPaths,stateToken:hash.digest('hex')};
32
36
  }
@@ -5,11 +5,14 @@ import {renderManagedBlock,removeManagedBlock,agentsBlockBody} from './global-co
5
5
  import {attachShellCompletionCleanup} from './shell-completion.mjs';
6
6
  import {verifyPayload} from './manifest.mjs';
7
7
  import {installTargets} from './install.mjs';
8
- export function buildUpgradePlans({payload,state,safeFs}){
8
+ import {installerRegistryOf} from '../platforms/index.mjs';
9
+ import {createPlatformRegistry} from '../runtime/platform-registry.mjs';
10
+ export function buildUpgradePlans({payload,state,safeFs,registry=state.registry}){
11
+ const platforms=installerRegistryOf({platforms:registry}),runtimePlatforms=createPlatformRegistry(platforms.byAnchorOrder().map(descriptor=>descriptor.runtime));
9
12
  for(const entry of state.targets)assertPlanSnapshot(entry,{safeFs});
10
13
  const plans=state.targets.map(entry=>{
11
14
  const {target,language,modelConfig,limits}=entry;
12
- const plan=buildInstallPlan({payload,target,profiles:state.mode==='composite'?'omit':'write',language,modelConfig,limits,skipGlobal:true,safeFs});
15
+ const plan=buildInstallPlan({payload,target,profiles:state.mode==='composite'&&state.platforms.includes(target.platform)?'omit':'write',language,modelConfig,limits,skipGlobal:true,safeFs,platforms,runtimePlatforms});
13
16
  for(const [name,value]of entry.snapshot)plan.snapshot.set(name,value);
14
17
  const current=inspectPath(safeFs,target.instructionPath,{kind:'file',read:true,snapshot:plan.snapshot});
15
18
  if(current.exists&&removeManagedBlock(current.bytes).changed){const rendered=renderManagedBlock(current.bytes,agentsBlockBody(target.home,target.userHome,language,target.platform));plan.managedPaths.push(target.instructionPath);if(!rendered.content.equals(current.bytes))plan.globalChanges.push({path:target.instructionPath,original:current.bytes,...rendered});}
@@ -18,7 +21,8 @@ export function buildUpgradePlans({payload,state,safeFs}){
18
21
  attachShellCompletionCleanup(plans,{safeFs});
19
22
  validatePlanSet(plans);return plans;
20
23
  }
21
- export async function upgradeInstalledTargets({packageRoot,state,safeFs,signal}){
22
- const payload=verifyPayload({packageRoot,safeFs}),version=JSON.parse(payload.files.get('package.json').toString('utf8')).version,plans=buildUpgradePlans({payload,state,safeFs});
23
- return{version,residualPaths:state.residualPaths??[],...await installTargets(plans,{safeFs,signal})};
24
+ export async function upgradeInstalledTargets({packageRoot,state,safeFs,signal,registry=state.registry}){
25
+ const platforms=installerRegistryOf({platforms:registry}),runtimePlatforms=createPlatformRegistry(platforms.byAnchorOrder().map(descriptor=>descriptor.runtime));
26
+ const payload=verifyPayload({packageRoot,safeFs,platforms,runtimePlatforms}),version=JSON.parse(payload.files.get('package.json').toString('utf8')).version,plans=buildUpgradePlans({payload,state,safeFs,registry:platforms});
27
+ return{version,residualPaths:state.residualPaths??[],...await installTargets(plans,{safeFs,signal,platforms})};
24
28
  }