@yunhozz/arc 0.2.7 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MANIFEST.sha256 +115 -68
- package/README.md +21 -5
- package/claude/agents/arc-implementer.md +3 -3
- package/claude/agents/arc-planner.md +3 -3
- package/claude/agents/arc-qa.md +3 -3
- package/claude/agents/arc-reviewer.md +3 -3
- package/claude/agents/arc-scouter.md +3 -3
- package/claude/skill/SKILL.md +5 -5
- package/claude/skill/models.toml +7 -48
- package/claude/skill/references/commit.md +7 -7
- package/claude/skill/references/coordination.md +39 -3
- package/claude/skill/references/git-recovery.md +1 -1
- package/claude/skill/references/handoff-prep.md +6 -6
- package/claude/skill/references/handoff.md +8 -3
- package/claude/skill/references/limits.md +2 -0
- package/claude/skill/references/planning.md +8 -8
- package/claude/skill/references/verification.md +9 -9
- package/claude/skill/runtime/adapters/claude.mjs +4 -0
- package/claude/skill/runtime/adapters/codex.mjs +3 -0
- package/claude/skill/runtime/bootstrap.mjs +4 -2
- package/claude/skill/runtime/command.mjs +21 -4
- package/claude/skill/runtime/local-cli.mjs +248 -0
- package/claude/skill/runtime/role-bridge-args.mjs +148 -0
- package/claude/skill/runtime/role-bridge.mjs +227 -0
- package/claude/skill/runtime/role-dispatch-policy.mjs +110 -0
- package/claude/skill/runtime/role-dispatch-store.mjs +134 -0
- package/claude/skill/runtime/role-observe.mjs +299 -0
- package/claude/skill/runtime/role-policy.json +12 -10
- package/claude/skill/runtime/role-routing-config.mjs +19 -0
- package/claude/skill/runtime/role-routing.mjs +233 -0
- package/claude/skill/runtime/role-supervisor.mjs +356 -0
- package/claude/skill/scripts/model_config.py +23 -5
- package/codex/agents/arc-implementer.toml +3 -3
- package/codex/agents/arc-planner.toml +3 -3
- package/codex/agents/arc-qa.toml +3 -3
- package/codex/agents/arc-reviewer.toml +3 -3
- package/codex/agents/arc-scouter.toml +3 -3
- package/codex/skill/SKILL.md +5 -5
- package/codex/skill/models.toml +7 -48
- package/codex/skill/references/commit.md +7 -7
- package/codex/skill/references/coordination.md +38 -2
- package/codex/skill/references/handoff-prep.md +6 -6
- package/codex/skill/references/handoff-worktree.md +3 -3
- package/codex/skill/references/handoff.md +8 -3
- package/codex/skill/references/limits.md +2 -0
- package/codex/skill/references/planning.md +8 -8
- package/codex/skill/references/verification.md +9 -9
- package/codex/skill/runtime/adapters/claude.mjs +4 -0
- package/codex/skill/runtime/adapters/codex.mjs +3 -0
- package/codex/skill/runtime/bootstrap.mjs +4 -2
- package/codex/skill/runtime/command.mjs +21 -4
- package/codex/skill/runtime/local-cli.mjs +248 -0
- package/codex/skill/runtime/role-bridge-args.mjs +148 -0
- package/codex/skill/runtime/role-bridge.mjs +227 -0
- package/codex/skill/runtime/role-dispatch-policy.mjs +110 -0
- package/codex/skill/runtime/role-dispatch-store.mjs +134 -0
- package/codex/skill/runtime/role-observe.mjs +299 -0
- package/codex/skill/runtime/role-policy.json +12 -10
- package/codex/skill/runtime/role-routing-config.mjs +19 -0
- package/codex/skill/runtime/role-routing.mjs +233 -0
- package/codex/skill/runtime/role-supervisor.mjs +356 -0
- package/codex/skill/scripts/model_config.py +17 -22
- package/lib/cli/root.mjs +3 -2
- package/lib/installer/install-mode.mjs +34 -0
- package/lib/installer/install.mjs +1 -1
- package/lib/installer/plan.mjs +16 -7
- package/lib/installer/preset.mjs +18 -11
- package/lib/installer/role-routing.mjs +175 -0
- package/lib/installer/runtime-assets.mjs +9 -0
- package/lib/installer/targets.mjs +2 -7
- package/lib/installer/transaction.mjs +1 -1
- package/lib/installer/uninstall.mjs +10 -5
- package/lib/installer/upgrade-state.mjs +9 -6
- package/lib/installer/upgrade.mjs +2 -2
- package/lib/management/operations.mjs +94 -5
- package/lib/management/status.mjs +12 -6
- package/lib/management/update.mjs +3 -1
- package/lib/models/catalog.mjs +3 -3
- package/lib/models/claude-models.json +297 -0
- package/lib/models/codex-catalog.mjs +9 -6
- package/lib/models/codex-models.json +189 -0
- package/lib/models/config.mjs +25 -20
- package/lib/models/index.mjs +1 -1
- package/lib/models/static-catalog.mjs +42 -0
- package/lib/policy/role-policy.json +12 -10
- package/lib/runtime/adapters/claude.mjs +4 -0
- package/lib/runtime/adapters/codex.mjs +3 -0
- package/lib/runtime/bootstrap.mjs +4 -2
- package/lib/runtime/command.mjs +21 -4
- package/lib/runtime/local-cli.mjs +248 -0
- package/lib/runtime/role-bridge-args.mjs +148 -0
- package/lib/runtime/role-bridge.mjs +227 -0
- package/lib/runtime/role-dispatch-policy.mjs +110 -0
- package/lib/runtime/role-dispatch-store.mjs +134 -0
- package/lib/runtime/role-observe.mjs +299 -0
- package/lib/runtime/role-routing-config.mjs +19 -0
- package/lib/runtime/role-routing.mjs +233 -0
- package/lib/runtime/role-supervisor.mjs +356 -0
- package/lib/tui/app.mjs +32 -23
- package/lib/tui/custom-preset.mjs +138 -66
- package/lib/tui/render.mjs +4 -3
- package/lib/tui/setup.mjs +96 -51
- package/lib/watch/args.mjs +43 -0
- package/lib/watch/discover-claude.mjs +63 -0
- package/lib/watch/discover-codex.mjs +45 -0
- package/lib/watch/dispatch.mjs +133 -0
- package/lib/watch/git.mjs +29 -0
- package/lib/watch/index.mjs +112 -0
- package/lib/watch/labels.mjs +24 -0
- package/lib/watch/model.mjs +48 -0
- package/lib/watch/normalize-claude.mjs +99 -0
- package/lib/watch/normalize-codex.mjs +96 -0
- package/lib/watch/policy.mjs +52 -0
- package/lib/watch/render.mjs +86 -0
- package/lib/watch/scope.mjs +64 -0
- package/lib/watch/tail.mjs +75 -0
- package/lib/watch/watcher.mjs +337 -0
- package/package.json +2 -2
|
@@ -74,23 +74,27 @@ def _parse_file(path: Path, label: str) -> tuple[bytes, str, dict]:
|
|
|
74
74
|
return content, text, parsed
|
|
75
75
|
|
|
76
76
|
|
|
77
|
-
|
|
77
|
+
_LEGACY_PRESETS = ("economy", "balanced", "smart")
|
|
78
78
|
|
|
79
79
|
|
|
80
80
|
def validate_config(config: dict, path: Path) -> dict:
|
|
81
|
+
if isinstance(config, dict) and type(config.get("version")) is int and config["version"] == 3:
|
|
82
|
+
if set(config) != {"version", "roles"} or not isinstance(config["roles"], dict) or set(config["roles"]) != set(ROLE_FILES):
|
|
83
|
+
raise _error(path, "settings", "update to version 3 role settings; requires exactly the five ARC roles")
|
|
84
|
+
return {"version": 3, "roles": {role: _settings_for_profile(values, role, path) for role, values in config["roles"].items()}}
|
|
81
85
|
if not isinstance(config, dict) or type(config.get("version")) is not int or config["version"] not in (1, 2):
|
|
82
|
-
raise _error(path, "settings", "update to version
|
|
86
|
+
raise _error(path, "settings", "update to version 3 role settings; reinstall ARC or edit models.toml")
|
|
83
87
|
has_custom = "custom" in config
|
|
84
88
|
allowed = {"version", "preset", "roles"} | ({"custom"} if config["version"] == 2 and has_custom else set())
|
|
85
89
|
if set(config) != allowed:
|
|
86
|
-
raise _error(path, "settings", "update to version
|
|
87
|
-
if not isinstance(config["preset"], str) or config["preset"] not in (*
|
|
90
|
+
raise _error(path, "settings", "update to version 3 role settings; reinstall ARC or edit models.toml")
|
|
91
|
+
if not isinstance(config["preset"], str) or config["preset"] not in (*_LEGACY_PRESETS, "custom") or (config["preset"] == "custom" and not has_custom):
|
|
88
92
|
raise _error(path, "preset", "must select an available preset")
|
|
89
93
|
roles = config["roles"]
|
|
90
94
|
if not isinstance(roles, dict) or set(roles) != set(ROLE_FILES):
|
|
91
95
|
raise _error(path, "roles", "must define exactly the five ARC roles")
|
|
92
96
|
for role, variants in roles.items():
|
|
93
|
-
if not isinstance(variants, dict) or set(variants) != set(
|
|
97
|
+
if not isinstance(variants, dict) or set(variants) != set(_LEGACY_PRESETS):
|
|
94
98
|
raise _error(path, f"roles.{role}", "must contain exactly economy, balanced and smart")
|
|
95
99
|
for preset, values in variants.items():
|
|
96
100
|
_settings_for_profile(values, f"{role}.{preset}", path)
|
|
@@ -100,32 +104,23 @@ def validate_config(config: dict, path: Path) -> dict:
|
|
|
100
104
|
raise _error(path, "custom", "must define exactly the five ARC roles")
|
|
101
105
|
for role, values in custom.items():
|
|
102
106
|
_settings_for_profile(values, f"custom.{role}", path)
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
return result
|
|
107
|
+
active = config["custom"] if config["preset"] == "custom" else {role: variants[config["preset"]] for role, variants in roles.items()}
|
|
108
|
+
return {"version": 3, "roles": copy.deepcopy(active)}
|
|
106
109
|
|
|
107
110
|
|
|
108
111
|
def load_settings(config_path: Path) -> dict[str, RoleSettings]:
|
|
109
|
-
"""Validate
|
|
112
|
+
"""Validate v1/v2/v3 and return the active role settings."""
|
|
110
113
|
_, _, config = _parse_file(config_path, "settings")
|
|
111
|
-
|
|
112
|
-
if config["preset"] == "custom":
|
|
113
|
-
return config["custom"]
|
|
114
|
-
return {role: dict(variants[config["preset"]]) for role, variants in config["roles"].items()}
|
|
114
|
+
return validate_config(config, config_path)["roles"]
|
|
115
115
|
|
|
116
116
|
|
|
117
117
|
def serialize_settings(config: dict) -> bytes:
|
|
118
|
-
"""Serialize
|
|
118
|
+
"""Serialize active roles using schema v3."""
|
|
119
119
|
config = validate_config(config, Path("models.toml"))
|
|
120
|
-
lines = ["version =
|
|
120
|
+
lines = ["version = 3"]
|
|
121
121
|
for role in ROLE_FILES:
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
lines.extend(f"{key} = {json.dumps(config['roles'][role][preset][key], ensure_ascii=False)}" for key in _MODEL_FIELDS)
|
|
125
|
-
if "custom" in config:
|
|
126
|
-
for role in ROLE_FILES:
|
|
127
|
-
lines.extend(["", f"[custom.{role}]"])
|
|
128
|
-
lines.extend(f"{key} = {json.dumps(config['custom'][role][key], ensure_ascii=False)}" for key in _MODEL_FIELDS)
|
|
122
|
+
lines.extend(["", f"[roles.{role}]"])
|
|
123
|
+
lines.extend(f"{key} = {json.dumps(config['roles'][role][key], ensure_ascii=False)}" for key in _MODEL_FIELDS)
|
|
129
124
|
return ("\n".join(lines) + "\n").encode("utf-8")
|
|
130
125
|
|
|
131
126
|
|
package/lib/cli/root.mjs
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import fs from 'node:fs';
|
|
2
|
-
const usage='Usage: arc\n arc --help\n arc --version';
|
|
2
|
+
const usage='Usage: arc\n arc watch [options]\n arc --help\n arc --version';
|
|
3
3
|
export async function runRoot(args=process.argv.slice(2),io={}){
|
|
4
4
|
const input=io.input??process.stdin,output=io.output??process.stdout,error=io.error??process.stderr;
|
|
5
|
-
if(args.length===1&&args[0]==='--help'){output.write(usage+'\n\nOpen ARC Management in an interactive terminal to install or manage the harness.\n');return 0;}
|
|
5
|
+
if(args.length===1&&args[0]==='--help'){output.write(usage+'\n\nOpen ARC Management in an interactive terminal to install or manage the harness.\nRun arc watch to follow Claude Code and Codex session activity.\n');return 0;}
|
|
6
6
|
if(args.length===1&&args[0]==='--version'){output.write(JSON.parse(fs.readFileSync(new URL('../../package.json',import.meta.url))).version+'\n');return 0;}
|
|
7
|
+
if(args[0]==='watch'){const {runWatch}=await import('../watch/index.mjs');return runWatch(args.slice(1),io);}
|
|
7
8
|
if(args.length){error.write('Error: Unsupported arguments. Open arc to manage the harness.\n'+usage+'\n');return 2;}
|
|
8
9
|
if(!input.isTTY||!output.isTTY){error.write('Error: arc requires an interactive terminal. Run arc directly in a terminal.\n');return 2;}
|
|
9
10
|
const {runTui}=await import('../tui/app.mjs');
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import {inspectPath,TargetConfigurationError} from './targets.mjs';
|
|
3
|
+
import {inspectCompositeRemoval} from './role-routing.mjs';
|
|
4
|
+
import {parseRoleRoutingConfig} from '../runtime/role-routing-config.mjs';
|
|
5
|
+
export function isOwnedStandaloneProfile(bytes,platform,role){
|
|
6
|
+
if(!/^arc_(scouter|planner|implementer|qa|reviewer)$/.test(role))return false;
|
|
7
|
+
const text=bytes.toString('utf8'),suffix=role.slice(4);
|
|
8
|
+
if(!/^\[ARC role policy: contract begin\]\r?$/m.test(text))return false;
|
|
9
|
+
if(platform==='claude'){
|
|
10
|
+
const front=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);if(!front)return false;
|
|
11
|
+
const names=front[1].match(/^name: .*\r?$/gm)??[];return names.length===1&&new RegExp(`^name: arc-${suffix}\\r?$`).test(names[0]);
|
|
12
|
+
}
|
|
13
|
+
if(platform!=='codex')return false;
|
|
14
|
+
const names=text.match(/^name[ \t]*=.*\r?$/gm)??[];
|
|
15
|
+
return names.length===1&&new RegExp(`^name[ \\t]*=[ \\t]*"arc_${suffix}"[ \\t]*(#.*)?\\r?$`).test(names[0]);
|
|
16
|
+
}
|
|
17
|
+
export function inspectStandaloneProfile({safeFs,target,role,snapshot=new Map()}){
|
|
18
|
+
const filename=path.join(target.home,'agents',`${role.replace('_','-')}.${target.platform==='codex'?'toml':'md'}`),file=inspectPath(safeFs,filename,{kind:'file',read:true,allowLeafLink:true,snapshot});
|
|
19
|
+
return{path:filename,exists:file.exists,owned:file.exists&&snapshot.get(filename)?.type==='file'&&isOwnedStandaloneProfile(file.bytes,target.platform,role)};
|
|
20
|
+
}
|
|
21
|
+
export function readInstallMode({safeFs,targets,snapshot=new Map()}){
|
|
22
|
+
const active=path.join(targets.codex.home,'arc-role-platform-routing.json'),homes={},residualPaths=[];
|
|
23
|
+
for(const platform of ['codex','claude']){
|
|
24
|
+
const result=inspectCompositeRemoval({target:targets[platform],safeFs,activeConfigPath:active,snapshot});
|
|
25
|
+
homes[platform]=result.residualPaths.length?'unverified':result.removals.length?'composite':'standalone';residualPaths.push(...result.residualPaths);
|
|
26
|
+
}
|
|
27
|
+
const mode=homes.codex===homes.claude?homes.codex:'unverified';
|
|
28
|
+
if(mode==='unverified')for(const [filename,value]of snapshot)if(value&&(/arc-role-platform-routing|arc-routing-/.test(filename)))residualPaths.push(filename);
|
|
29
|
+
let config=null;if(mode==='composite')config=parseRoleRoutingConfig(inspectPath(safeFs,active,{kind:'file',read:true,snapshot}).bytes.toString('utf8'));
|
|
30
|
+
return{mode,homes,config,residualPaths:[...new Set(residualPaths)]};
|
|
31
|
+
}
|
|
32
|
+
export function assertVerifiedInstallMode(options){
|
|
33
|
+
const state=readInstallMode(options);if(state.mode==='unverified'){const error=new TargetConfigurationError('Claude & Codex configuration cannot be verified.');error.residualPaths=state.residualPaths;throw error;}return state;
|
|
34
|
+
}
|
|
@@ -18,7 +18,7 @@ export async function installTargets(plans,{safeFs,signal,hooks={}}){
|
|
|
18
18
|
try{
|
|
19
19
|
assertPlanSnapshot(plan,{safeFs});
|
|
20
20
|
const installed=applyTransaction(plan,{safeFs,signal,hooks});
|
|
21
|
-
results[index]={...results[index],status:'installed',error:installed.cleanupError??null,residualPaths:[...results[index].residualPaths,...(installed.residualPaths??[])]};if(installed.cleanupError)failed=true;
|
|
21
|
+
results[index]={...results[index],status:'installed',error:installed.cleanupError??null,residualPaths:[...results[index].residualPaths,...(plan.residualPaths??[]),...(installed.residualPaths??[])]};if(installed.cleanupError)failed=true;
|
|
22
22
|
}catch(error){const cancelled=signal?.aborted||error.code==='ARC_INSTALL_CANCELLED';interrupted=Boolean(cancelled);results[index]={...results[index],status:'failed',rollback:error.rollback??'not-needed',residualPaths:[...results[index].residualPaths,...(error.residualPaths??[])],error};failed=true;}
|
|
23
23
|
if(failed)break;
|
|
24
24
|
}
|
package/lib/installer/plan.mjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
+
import {inspectStandaloneProfile} from './install-mode.mjs';
|
|
1
2
|
import {renderAgentProfile} from '../prompts/render.mjs';
|
|
2
3
|
import {PayloadValidationError} from './manifest.mjs';
|
|
3
4
|
import{parseLanguage,serializeLanguage,renderLanguagePolicy,validateLanguage}from'./language.mjs';
|
|
4
5
|
import{resolveLimits}from'../limits.mjs';import{parseLimits,serializeLimits}from'./limits.mjs';import{readRuntimeConcurrency,renderCodexConcurrency,renderClaudeConcurrency}from'./runtime-config.mjs';import{assertPlanSnapshot}from'./transaction.mjs';
|
|
5
6
|
import{validateModelConfig}from'../models/config.mjs';
|
|
6
7
|
import{assertCatalogRoles}from'../models/catalog.mjs';
|
|
7
|
-
import path from'node:path';import{loadModelConfig,
|
|
8
|
+
import path from'node:path';import{loadModelConfig,withRoles,serializeModelConfig,renderProfiles,resolveModelSettings}from'../models/index.mjs';import{inspectPath,TargetConfigurationError}from'./targets.mjs';import{renderManagedBlock,renderWaitSettings,agentsBlockBody}from'./global-config.mjs';
|
|
8
9
|
function fail(message){throw new TargetConfigurationError(message);}
|
|
9
10
|
export function previewLimits({target,safeFs}){
|
|
10
11
|
const snapshot=new Map(),filename=path.join(target.home,'skills/arc/limits.toml');
|
|
@@ -18,11 +19,15 @@ export function previewLanguage({target,safeFs}){
|
|
|
18
19
|
let existing=null;try{if(current.exists)existing=parseLanguage(current.bytes).language;}catch(cause){fail(`Invalid ARC language settings: ${cause.message}`);}
|
|
19
20
|
return{existing,snapshot};
|
|
20
21
|
}
|
|
21
|
-
function renderModelAssets({payload,target,
|
|
22
|
+
function renderModelAssets({payload,target,roles,modelConfig,language,verifiedCatalog}){
|
|
22
23
|
const input=payload.modelInputs[target.platform];if(!input)fail('Selected payload platform is unavailable');
|
|
23
|
-
|
|
24
|
+
const base=modelConfig!==undefined?validateModelConfig(modelConfig):loadModelConfig(input.models,target.platform);
|
|
25
|
+
if(roles!==undefined)assertCatalogRoles({platform:target.platform,roles,catalog:verifiedCatalog});
|
|
26
|
+
const config=roles!==undefined?withRoles(base,roles):base;
|
|
27
|
+
if(config.platform!==target.platform)fail('Model config platform does not match target');const settings=resolveModelSettings(config),profiles=renderProfiles(input.profiles,settings);try{for(const[name,bytes]of profiles){const expanded=renderAgentProfile(`${target.platform}/agents/${name}`,bytes,payload.agentRegistry);const final=renderLanguagePolicy(expanded,language);if(final.toString('utf8').includes('ARC_AGENT_FRAGMENT'))throw Error('Unresolved fragment marker');profiles.set(name,final);}const checked=renderProfiles(profiles,settings);if(checked.size!==profiles.size||[...profiles].some(([name,bytes],i)=>{const entry=[...checked][i];return !entry||entry[0]!==name||!entry[1].equals(bytes);}))throw Error('Final profile model settings changed');}catch(cause){throw new PayloadValidationError(`Payload profile rendering failed: ${cause.message}`,{cause});}const modelBytes=Buffer.from(serializeModelConfig(config));
|
|
24
28
|
return{profiles,modelBytes};
|
|
25
29
|
}
|
|
30
|
+
export function renderStandaloneProfiles({payload,target,modelConfig,language}){return renderModelAssets({payload,target,modelConfig,language}).profiles;}
|
|
26
31
|
function renderSkillPayload({payload,target,language,modelBytes,limits}){
|
|
27
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));
|
|
28
33
|
return skill;
|
|
@@ -48,19 +53,22 @@ function renderNativeChanges({target,safeFs,snapshot,skipGlobal,preview,concurre
|
|
|
48
53
|
}
|
|
49
54
|
return globalChanges;
|
|
50
55
|
}
|
|
51
|
-
export function buildInstallPlan({payload,target,
|
|
56
|
+
export function buildInstallPlan({payload,target,roles,profiles:profileMode='write',skipGlobal=false,safeFs,limits,concurrentExplicit=false,limitsPreview,language='en',languagePreview,modelConfig,verifiedCatalog}){
|
|
52
57
|
validateLanguage(language);
|
|
53
58
|
if(languagePreview)assertPlanSnapshot({snapshot:languagePreview.snapshot},{safeFs});
|
|
54
59
|
const languageState=languagePreview??previewLanguage({target,safeFs});
|
|
55
60
|
if(limitsPreview)assertPlanSnapshot({snapshot:limitsPreview.snapshot},{safeFs});
|
|
56
61
|
const preview=limitsPreview??previewLimits({target,safeFs});
|
|
57
62
|
limits=resolveLimits({existing:preview.existing,overrides:limits??{}});
|
|
58
|
-
const
|
|
63
|
+
const modelSnapshot=new Map();
|
|
64
|
+
if(modelConfig===undefined&&roles===undefined){const installed=inspectPath(safeFs,path.join(target.home,'skills/arc/models.toml'),{kind:'file',read:true,snapshot:modelSnapshot});if(installed.exists)modelConfig=loadModelConfig(installed.bytes,target.platform);}
|
|
65
|
+
const {profiles,modelBytes}=renderModelAssets({payload,target,roles,modelConfig,language,verifiedCatalog});
|
|
59
66
|
const skill=renderSkillPayload({payload,target,language,modelBytes,limits});
|
|
60
67
|
const snapshot=new Map(),home=target.home;const skills=path.join(home,'skills'),agents=path.join(home,'agents'),arc=path.join(skills,'arc');
|
|
61
68
|
for(const name of [home,skills,agents])inspectPath(safeFs,name,{kind:'directory',snapshot});
|
|
62
69
|
inspectPath(safeFs,arc,{kind:'directory',tree:true,allowLinks:true,snapshot});
|
|
63
|
-
const profilePaths=
|
|
70
|
+
const profilePaths=[],profileWrites=new Map(),residualPaths=[];
|
|
71
|
+
if(profileMode!=='omit')for(const [name,bytes]of profiles){const found=inspectStandaloneProfile({safeFs,target,role:name.split('.')[0].replace('-','_'),snapshot});if(found.exists&&!found.owned){residualPaths.push(found.path);continue;}profilePaths.push(found.path);profileWrites.set(name,bytes);}
|
|
64
72
|
const externalPaths=[],summary=['Verified packaged Superpowers references will be installed inside ARC'];
|
|
65
73
|
summary.push(`ARC limits: total ${limits.max_total_subagents}; concurrent ${limits.max_concurrent_subagents} (policy: ${arc}/limits.toml)`);
|
|
66
74
|
const globalChanges=renderNativeChanges({target,safeFs,snapshot,skipGlobal,preview,concurrentExplicit,limits,summary,language});
|
|
@@ -68,7 +76,8 @@ export function buildInstallPlan({payload,target,preset,skipGlobal=false,safeFs,
|
|
|
68
76
|
for(const [filename,metadata]of preview.snapshot)snapshot.set(filename,metadata);
|
|
69
77
|
for(const [filename,metadata]of languageState.snapshot)snapshot.set(filename,metadata);
|
|
70
78
|
summary.push(`ARC output language: ${language}`);
|
|
71
|
-
const
|
|
79
|
+
for(const item of modelSnapshot)snapshot.set(...item);
|
|
80
|
+
const plan={target,language,roles,skipGlobal,limits,concurrentExplicit,profileWrites,residualPaths,generated:{models:modelBytes,profiles,skill},globalChanges,managedPaths,externalPaths,snapshot,summary};validatePlanSet([plan]);return plan;
|
|
72
81
|
}
|
|
73
82
|
function overlaps(a,b){return a===b||a.startsWith(b+'/')||b.startsWith(a+'/');}
|
|
74
83
|
export function validatePlanSet(plans){
|
package/lib/installer/preset.mjs
CHANGED
|
@@ -1,19 +1,26 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
|
+
import {inspectStandaloneProfile} from './install-mode.mjs';
|
|
2
3
|
import {inspectPath,TargetConfigurationError} from './targets.mjs';
|
|
3
|
-
import {loadModelConfig,
|
|
4
|
+
import {loadModelConfig,withRoles,serializeModelConfig,resolveModelSettings,renderProfiles} from '../models/index.mjs';
|
|
4
5
|
import {assertPlanSnapshot,applyTransaction} from './transaction.mjs';
|
|
6
|
+
import {readModelFileVersion} from '../models/config.mjs';
|
|
7
|
+
import {isDeepStrictEqual} from 'node:util';
|
|
5
8
|
import {assertCatalogRoles} from '../models/catalog.mjs';
|
|
6
|
-
import {validatePlanSet} from './plan.mjs';
|
|
7
|
-
|
|
8
|
-
|
|
9
|
+
import {validatePlanSet,renderStandaloneProfiles} from './plan.mjs';
|
|
10
|
+
import {parseLanguage} from './language.mjs';
|
|
11
|
+
export function buildPresetPlan({target,roles,safeFs,verifiedCatalog,payload,loadPayload}){
|
|
12
|
+
const snapshot=new Map(),modelsPath=path.join(target.home,'skills/arc/models.toml'),managedPaths=[modelsPath],residualPaths=[];
|
|
9
13
|
const read=filename=>{const found=inspectPath(safeFs,filename,{kind:'file',read:true,snapshot});if(!found.exists)throw new TargetConfigurationError(`Installed ARC file missing: ${filename}`);return found.bytes;};
|
|
10
14
|
const originalModels=read(modelsPath),config=loadModelConfig(originalModels,target.platform);
|
|
11
|
-
if(
|
|
12
|
-
const next=
|
|
13
|
-
const
|
|
14
|
-
|
|
15
|
-
for(const
|
|
16
|
-
|
|
15
|
+
if(roles!==undefined)assertCatalogRoles({platform:target.platform,roles,catalog:verifiedCatalog});
|
|
16
|
+
const next=roles!==undefined?withRoles(config,roles):config,originalProfiles=new Map();
|
|
17
|
+
for(const name of target.profileNames){const found=inspectStandaloneProfile({safeFs,target,role:name.split('.')[0].replace('-','_'),snapshot});if(!found.exists)throw new TargetConfigurationError(`Installed ARC file missing: ${found.path}`);if(!found.owned){residualPaths.push(found.path);continue;}originalProfiles.set(name,read(found.path));managedPaths.push(found.path);}
|
|
18
|
+
const profileInputs=residualPaths.length?renderStandaloneProfiles({payload:payload??loadPayload(),target,modelConfig:next,language:parseLanguage(read(path.join(target.home,'skills/arc/settings.toml'))).language}):new Map();
|
|
19
|
+
for(const entry of originalProfiles)profileInputs.set(...entry);
|
|
20
|
+
const profiles=renderProfiles(profileInputs,resolveModelSettings(next)),specs=[];
|
|
21
|
+
if(readModelFileVersion(originalModels)<3||!isDeepStrictEqual(config.roles,next.roles))specs.push({path:modelsPath,bytes:Buffer.from(serializeModelConfig(next))});
|
|
22
|
+
for(const[name,bytes]of profiles)if(originalProfiles.has(name)&&!bytes.equals(originalProfiles.get(name)))specs.push({path:path.join(target.home,'agents',name),bytes});
|
|
23
|
+
return{target,roles:next.roles,snapshot,managedPaths,residualPaths,externalPaths:[],specs};
|
|
17
24
|
}
|
|
18
25
|
export async function switchPresetTargets(plans,{safeFs,signal,hooks={}}){
|
|
19
26
|
const results=plans.map(plan=>({platform:plan.target.platform,status:'not-started',rollback:'not-needed',residualPaths:[],error:null}));
|
|
@@ -22,7 +29,7 @@ export async function switchPresetTargets(plans,{safeFs,signal,hooks={}}){
|
|
|
22
29
|
if(invalid)return{results,interrupted:false};
|
|
23
30
|
for(let i=0;i<plans.length;i++){
|
|
24
31
|
if(signal?.aborted)return{results,interrupted:true};const plan=plans[i];
|
|
25
|
-
try{assertPlanSnapshot(plan,{safeFs});const applied=plan.specs.length?applyTransaction(plan,{safeFs,signal,hooks,specs:plan.specs}):{residualPaths:[],cleanupError:null};results[i]={...results[i],status:plan.specs.length?'updated':'unchanged',residualPaths:applied.residualPaths,error:applied.cleanupError};if(applied.cleanupError)break;}
|
|
32
|
+
try{assertPlanSnapshot(plan,{safeFs});const applied=plan.specs.length?applyTransaction(plan,{safeFs,signal,hooks,specs:plan.specs}):{residualPaths:[],cleanupError:null};results[i]={...results[i],status:plan.specs.length?'updated':'unchanged',residualPaths:[...new Set([...(plan.residualPaths??[]),...applied.residualPaths])],error:applied.cleanupError};if(applied.cleanupError)break;}
|
|
26
33
|
catch(error){results[i]={...results[i],status:'failed',rollback:error.rollback??'not-needed',residualPaths:error.residualPaths??[],error};return{results,interrupted:Boolean(signal?.aborted)};}
|
|
27
34
|
}
|
|
28
35
|
return{results,interrupted:false};
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import {renderStandaloneProfiles} from './plan.mjs';
|
|
2
|
+
import {loadModelConfig} from '../models/index.mjs';
|
|
3
|
+
import {parseLanguage} from './language.mjs';
|
|
4
|
+
import {inspectStandaloneProfile,assertVerifiedInstallMode} from './install-mode.mjs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import {inspectPath,TargetConfigurationError} from './targets.mjs';
|
|
8
|
+
import {assertPlanSnapshot,applyTransaction} from './transaction.mjs';
|
|
9
|
+
import {renderProfiles,resolveModelSettings} from '../models/index.mjs';
|
|
10
|
+
import {COOPERATIVE_RUNTIME_MODULES,cooperativeVersions} from '../runtime/bootstrap.mjs';
|
|
11
|
+
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';
|
|
14
|
+
import {ROUTING_ROLES,parseRoleRoutingConfig,serializeRoleRoutingConfig,validateRoleRoutingConfig} from '../runtime/role-routing-config.mjs';
|
|
15
|
+
|
|
16
|
+
const digest=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
|
|
17
|
+
const validHash=value=>typeof value==='string'&&/^sha256:[a-f0-9]{64}$/.test(value);
|
|
18
|
+
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
|
+
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'}`);
|
|
21
|
+
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');
|
|
23
|
+
const read=(safeFs,filename,snapshot)=>inspectPath(safeFs,filename,{kind:'file',read:true,snapshot});
|
|
24
|
+
|
|
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));
|
|
32
|
+
}
|
|
33
|
+
|
|
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');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 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');
|
|
50
|
+
const markers={},existingProfiles={},desired={};
|
|
51
|
+
for(const platform of ['codex','claude']){
|
|
52
|
+
const target=targets[platform],found=read(context.safeFs,markerPath(target),snapshot);let marker=null;
|
|
53
|
+
if(found.exists)try{marker=JSON.parse(found.bytes.toString('utf8'));}catch{fail('Existing composite marker cannot be verified');}
|
|
54
|
+
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');
|
|
56
|
+
markers[platform]=marker;existingProfiles[platform]={};
|
|
57
|
+
for(const role of ROUTING_ROLES){
|
|
58
|
+
const filename=profilePath(target,role),file=read(context.safeFs,filename,snapshot),old=marker?.profiles?.[role];
|
|
59
|
+
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
|
+
if(file.exists&&!old)fail('Unmanaged composite profile already exists');
|
|
61
|
+
existingProfiles[platform][role]=Boolean(old);
|
|
62
|
+
}
|
|
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);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if(previous&&!Object.values(markers).some(Boolean))fail('Existing composite configuration has no ownership marker');
|
|
72
|
+
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};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
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'));
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Return only composite paths whose current bytes match the active marker. */
|
|
84
|
+
export function inspectCompositeRemoval({target,safeFs,activeConfigPath,snapshot}){
|
|
85
|
+
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]:[])];
|
|
88
|
+
if(!existing.length)return {removals:[],residualPaths:[]};
|
|
89
|
+
try{
|
|
90
|
+
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);
|
|
92
|
+
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');}
|
|
94
|
+
return {removals:existing,residualPaths:[]};
|
|
95
|
+
}catch{return {removals:[],residualPaths:existing};}
|
|
96
|
+
}
|
|
97
|
+
|
|
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){
|
|
100
|
+
let leases;
|
|
101
|
+
try{leases=await listLeases(codexHome);}
|
|
102
|
+
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;}
|
|
105
|
+
}
|
|
106
|
+
/** 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;
|
|
109
|
+
try{
|
|
110
|
+
release=await acquireRoleRoutingLock(targets.codex.home);
|
|
111
|
+
await assertNoActiveBridgeDispatch(targets.codex.home);
|
|
112
|
+
assertPlanSnapshot(prepared,{safeFs:context.safeFs});
|
|
113
|
+
const versions=await cooperativeVersions(),runtimeSnapshot=new Map(),markers={};
|
|
114
|
+
for(const platform of ['codex','claude']){
|
|
115
|
+
const target=targets[platform],dir=path.join(target.home,'skills','arc','runtime'),modules=[];
|
|
116
|
+
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
|
+
const policy=read(context.safeFs,path.join(dir,'role-policy.json'),runtimeSnapshot);if(!policy.exists)fail('Installed role policy is missing');
|
|
118
|
+
const runtimeHash=digest(Buffer.concat(modules)),policyHash=digest(policy.bytes);
|
|
119
|
+
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};
|
|
122
|
+
}
|
|
123
|
+
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);}};
|
|
129
|
+
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
|
+
published=true;publication={published:true,revision:config.revision,residualPaths:[...(prepared.residualPaths??[]),...result.residualPaths],cleanupError:result.cleanupError};
|
|
131
|
+
}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');
|
|
135
|
+
if(failed){
|
|
136
|
+
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;
|
|
138
|
+
failure.message=(typeof failure.message==='string'?failure.message:'Composite publication failed')+'; Composite publication lock ownership could not be verified';
|
|
139
|
+
}else{
|
|
140
|
+
failure=new TargetConfigurationError('Composite publication lock ownership could not be verified',publication?.cleanupError?{cause:publication.cleanupError}:undefined);
|
|
141
|
+
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])];
|
|
143
|
+
if(publication?.cleanupError)failure.cleanupError=publication.cleanupError;
|
|
144
|
+
failed=true;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if(failed)throw failure;
|
|
148
|
+
return publication;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 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});
|
|
154
|
+
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))});}
|
|
161
|
+
}
|
|
162
|
+
return{target:targets.codex,targets,snapshot,managedPaths:[...new Set([...removals,...writes.map(item=>item.path)])],externalPaths,removals:[...new Set(removals)],writes,residualPaths};
|
|
163
|
+
}
|
|
164
|
+
export async function publishCompositeDeactivation({context,prepared}){
|
|
165
|
+
let release,result,failure;
|
|
166
|
+
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});
|
|
169
|
+
const applied=applyTransaction(prepared,{safeFs:context.safeFs,signal:context.signal,hooks:context.hooks,specs:[...prepared.removals.map(path=>({path,remove:true})),...prepared.writes]});
|
|
170
|
+
result={residualPaths:[...prepared.residualPaths,...applied.residualPaths],cleanupError:applied.cleanupError};
|
|
171
|
+
}catch(error){failure=error;}
|
|
172
|
+
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;}
|
|
174
|
+
if(failure)throw failure;return result;
|
|
175
|
+
}
|
|
@@ -17,7 +17,16 @@ export const RUNTIME_MODULE_PATHS = Object.freeze([
|
|
|
17
17
|
'lib/runtime/git-evidence.mjs',
|
|
18
18
|
'lib/runtime/git-query.mjs',
|
|
19
19
|
'lib/runtime/identity.mjs',
|
|
20
|
+
'lib/runtime/local-cli.mjs',
|
|
20
21
|
'lib/runtime/operations.mjs',
|
|
22
|
+
'lib/runtime/role-bridge-args.mjs',
|
|
23
|
+
'lib/runtime/role-bridge.mjs',
|
|
24
|
+
'lib/runtime/role-dispatch-policy.mjs',
|
|
25
|
+
'lib/runtime/role-dispatch-store.mjs',
|
|
26
|
+
'lib/runtime/role-observe.mjs',
|
|
27
|
+
'lib/runtime/role-routing-config.mjs',
|
|
28
|
+
'lib/runtime/role-routing.mjs',
|
|
29
|
+
'lib/runtime/role-supervisor.mjs',
|
|
21
30
|
'lib/runtime/schema.mjs',
|
|
22
31
|
'lib/runtime/scope.mjs',
|
|
23
32
|
'lib/runtime/store.mjs',
|
|
@@ -1,14 +1,9 @@
|
|
|
1
|
+
import {resolveConfigHome} from '../runtime/local-cli.mjs';
|
|
1
2
|
import path from 'node:path';import crypto from 'node:crypto';
|
|
2
3
|
export class TargetConfigurationError extends Error{constructor(message,options){super(message,options);this.name='TargetConfigurationError';this.code='ARC_TARGET_CONFIGURATION';}}
|
|
3
4
|
const fail=message=>{throw new TargetConfigurationError(message);};
|
|
4
5
|
export function resolveTarget(platform,{userHome,env={},cwd}={}){
|
|
5
|
-
|
|
6
|
-
if(typeof userHome!=='string'||!path.isAbsolute(userHome)||!userHome.trim())fail('userHome must be an absolute user directory');
|
|
7
|
-
userHome=path.resolve(userHome);if(!env||typeof env!=='object')fail('env must be an environment object');
|
|
8
|
-
const expand=value=>value==='~'?userHome:value.startsWith('~/')?path.join(userHome,value.slice(2)):value;
|
|
9
|
-
let home;if(platform==='codex'){const raw=env.CODEX_HOME;if(raw!==undefined&&(typeof raw!=='string'||!raw.trim()))fail('CODEX_HOME is empty or invalid');const expanded=expand(raw??path.join(userHome,'.codex'));if(path.isAbsolute(expanded))home=path.resolve(expanded);else{const base=cwd??process.cwd();if(typeof base!=='string'||!path.isAbsolute(base))fail('cwd must be absolute for relative CODEX_HOME');home=path.resolve(base,expanded);}}
|
|
10
|
-
else{home=path.join(userHome,'.claude');const raw=env.CLAUDE_CONFIG_DIR;if(raw!==undefined&&(typeof raw!=='string'||!raw.trim()||!path.isAbsolute(expand(raw))||path.resolve(expand(raw))!==home))fail('CLAUDE_CONFIG_DIR must select the default ~/.claude directory');}
|
|
11
|
-
if(home==='/'||home===path.resolve(userHome))fail('Target home must not be the filesystem or user-home root');
|
|
6
|
+
let home;try{home=resolveConfigHome(platform,{userHome,env,cwd});}catch(error){fail(error.message);}
|
|
12
7
|
const profileNames=['scouter','planner','implementer','qa','reviewer'].map(role=>`arc-${role}.${platform==='codex'?'toml':'md'}`);
|
|
13
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')])});
|
|
14
9
|
}
|
|
@@ -59,7 +59,7 @@ export function applyTransaction(plan,{safeFs,signal,hooks={},specs:explicitSpec
|
|
|
59
59
|
const event=(phase,details={})=>{actionLog.push({phase,...details});if(signal?.aborted)throw new InstallError('Install interrupted','ARC_INSTALL_CANCELLED');hooks.fault?.({phase,...details,plan});};
|
|
60
60
|
try{
|
|
61
61
|
event('before-prepare');
|
|
62
|
-
const specs=explicitSpecs??plan.uninstallSpecs??[{path:plan.target.home+'/skills/arc',tree:composeStaticArcSkillTree(plan.generated.skill)},...[...plan.generated.profiles].map(([name,bytes])=>({path:plan.target.home+'/agents/'+name,bytes})),...plan.globalChanges.map(change=>({path:change.path,bytes:change.content}))];
|
|
62
|
+
const specs=explicitSpecs??plan.uninstallSpecs??[{path:plan.target.home+'/skills/arc',tree:composeStaticArcSkillTree(plan.generated.skill)},...[...(plan.profileWrites??plan.generated.profiles)].map(([name,bytes])=>({path:plan.target.home+'/agents/'+name,bytes})),...plan.globalChanges.map(change=>({path:change.path,bytes:change.content}))];
|
|
63
63
|
for(const spec of specs){if(!spec.remove&&!spec.tree&&!Buffer.isBuffer(spec.bytes))fail('Missing verified staged data');const parent=openParent(safeFs,spec.path,created);parents.push(parent);const name=path.basename(spec.path);event('before-stage',{path:spec.path});let area=byParent.get(path.dirname(spec.path));if(area&&!sameObjectIdentity(parent.stat(),area.parent.stat()))fail('Reused staging parent identity changed','ARC_INSTALL_DRIFT');if(!area){const stageName='.arc-stage-'+randomUUID();parent.mkdir(stageName,0o700);const stage=parent.openDir(stageName);area={parent,stage,name:stageName,path:path.dirname(spec.path)+'/'+stageName,identity:stage.stat(),expected:new Map()};areas.push(area);byParent.set(path.dirname(spec.path),area);}const stage=area.stage,preparedName='prepared-'+actions.length,previousName='previous-'+actions.length,rollbackName='rollback-installed-'+actions.length;
|
|
64
64
|
if(spec.remove){}
|
|
65
65
|
else if(spec.tree){stage.mkdir(preparedName,0o700);const dir=stage.openDir(preparedName);try{writeTree(dir,spec.tree);if(spec.rootMetadata)finishDirectory(dir,spec.rootMetadata.mode,spec.rootMetadata);else dir.sync();}finally{dir.close();}}
|
|
@@ -1,26 +1,31 @@
|
|
|
1
|
+
import {inspectStandaloneProfile} from './install-mode.mjs';
|
|
1
2
|
import path from 'node:path';
|
|
2
3
|
import {inspectPath,sameIdentity,TargetConfigurationError} from './targets.mjs';
|
|
3
4
|
import {SKILLS,snapshotSkill} from './superpowers.mjs';
|
|
4
5
|
import {validatePlanSet} from './plan.mjs';
|
|
5
6
|
import {removeManagedBlock} from './global-config.mjs';
|
|
6
7
|
import {attachShellCompletionCleanup} from './shell-completion.mjs';
|
|
7
|
-
|
|
8
|
+
import {inspectCompositeRemoval} from './role-routing.mjs';
|
|
9
|
+
export function buildUninstallPlan({target,safeFs,skipGlobal=false,removeCompletion=true,compositeActivePath}){
|
|
8
10
|
const snapshot=new Map(),removals=[],managedPaths=[path.join(target.home,'skills/arc'),...target.profileNames.map(name=>path.join(target.home,'agents',name))],globalChanges=[];
|
|
9
|
-
|
|
11
|
+
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);}}
|
|
10
13
|
const linkedSkills=new Set(),arc=managedPaths[0];
|
|
11
|
-
for(const[filename,entry]of snapshot){if(entry?.type!=='symlink')continue;
|
|
14
|
+
for(const[filename,entry]of snapshot){if(entry?.type!=='symlink'||!filename.startsWith(arc+'/'))continue;
|
|
12
15
|
const relative=path.relative(arc,filename),parts=relative.split('/'),skill=parts[2];
|
|
13
16
|
if(parts[0]!=='references'||parts[1]!=='superpowers'||!SKILLS.includes(skill)||parts.length<4||!entry.link||path.isAbsolute(entry.link)||entry.link.includes('\\')||entry.link.includes('\0'))throw new TargetConfigurationError('Unsafe ARC removal link');
|
|
14
17
|
linkedSkills.add(skill);
|
|
15
18
|
}
|
|
16
19
|
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();}}
|
|
17
20
|
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});}}
|
|
18
|
-
const
|
|
21
|
+
const composite=inspectCompositeRemoval({target,safeFs,activeConfigPath:compositeActivePath,snapshot});
|
|
22
|
+
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.']};
|
|
19
24
|
if(removeCompletion)attachShellCompletionCleanup([plan],{safeFs});return plan;
|
|
20
25
|
}
|
|
21
26
|
import {assertPlanSnapshot,applyUninstallTransaction} from './transaction.mjs';
|
|
22
27
|
export async function uninstallTargets(plans,{safeFs,signal,hooks={}}){
|
|
23
|
-
const results=plans.map(plan=>({platform:plan.target.platform,status:'not-started',rollback:'not-needed',residualPaths:[],error:null}));let invalid=false;
|
|
28
|
+
const results=plans.map(plan=>({platform:plan.target.platform,status:'not-started',rollback:'not-needed',residualPaths:[...(plan.compositeResidual??[])],error:null}));let invalid=false;
|
|
24
29
|
// Each standalone preview retains its snapshot; only the first plan owns the shared shell write.
|
|
25
30
|
for(const plan of plans.slice(1)){const filename=path.join(plans[0].target.userHome,'.zshrc');plan.managedPaths=plan.managedPaths.filter(name=>name!==filename);plan.globalChanges=plan.globalChanges.filter(change=>change.path!==filename);plan.snapshot.delete(filename);}
|
|
26
31
|
try{validatePlanSet(plans);}catch(error){return{results:results.map(item=>({...item,status:'failed',error})),interrupted:false};}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {readInstallMode,inspectStandaloneProfile} from './install-mode.mjs';
|
|
1
2
|
import path from 'node:path';
|
|
2
3
|
import {createHash} from 'node:crypto';
|
|
3
4
|
import {resolveTarget,inspectPath,TargetConfigurationError} from './targets.mjs';
|
|
@@ -10,20 +11,22 @@ import {readRuntimeConcurrency} from './runtime-config.mjs';
|
|
|
10
11
|
const fail=message=>{throw new TargetConfigurationError(message);};
|
|
11
12
|
export function collectInstalledState({safeFs,userHome,env={},cwd}){
|
|
12
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');
|
|
13
|
-
const targets=[];
|
|
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=[];
|
|
14
15
|
for(const platform of ['codex','claude']){
|
|
15
16
|
const target=resolveTarget(platform,{userHome,env,cwd}),snapshot=new Map(),arc=path.join(target.home,'skills/arc');
|
|
16
17
|
const skill=inspectPath(safeFs,arc,{kind:'directory',tree:true,allowLinks:true,snapshot});
|
|
17
|
-
const profiles=target.profileNames.map(name=>
|
|
18
|
+
const profiles=mode==='composite'?[]:target.profileNames.map(name=>inspectStandaloneProfile({safeFs,target,role:name.split('.')[0].replace('-','_'),snapshot}));
|
|
18
19
|
const instruction=inspectPath(safeFs,target.instructionPath,{kind:'file',read:true,snapshot}),managed=instruction.exists?removeManagedBlock(instruction.bytes):{changed:false};
|
|
19
|
-
if(!skill.exists){if(profiles.some(item=>item.exists)||managed.changed)fail(`Incomplete ARC installation: ${target.home}`);continue;}
|
|
20
|
+
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;}
|
|
20
21
|
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;}
|
|
21
|
-
mandatory('SKILL.md');if(profiles.some(item=>!item.exists
|
|
22
|
+
mandatory('SKILL.md');if(profiles.some(item=>!item.exists))fail(`Incomplete ARC installation: missing profile at ${target.home}`);
|
|
22
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});}
|
|
23
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});}
|
|
24
25
|
const shell=inspectPath(safeFs,path.join(userHome,'.zshrc'),{kind:'file',read:true,snapshot});if(shell.exists)removeShellCompletion(shell.bytes);
|
|
25
|
-
|
|
26
|
+
if(mode==='composite')for(const [filename,value]of modeSnapshot)if(value)snapshot.set(filename,value);
|
|
27
|
+
for(const [filename,value]of snapshot)if(!value)snapshot.delete(filename);
|
|
28
|
+
targets.push({target,language,modelConfig,limits,snapshot,residualPaths:profiles.filter(item=>item.exists&&!item.owned).map(item=>item.path)});
|
|
26
29
|
}
|
|
27
30
|
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));}
|
|
28
|
-
return{targets,stateToken:hash.digest('hex')};
|
|
31
|
+
return{targets,mode,residualPaths,stateToken:hash.digest('hex')};
|
|
29
32
|
}
|
|
@@ -9,7 +9,7 @@ export function buildUpgradePlans({payload,state,safeFs}){
|
|
|
9
9
|
for(const entry of state.targets)assertPlanSnapshot(entry,{safeFs});
|
|
10
10
|
const plans=state.targets.map(entry=>{
|
|
11
11
|
const {target,language,modelConfig,limits}=entry;
|
|
12
|
-
const plan=buildInstallPlan({payload,target,language,modelConfig,
|
|
12
|
+
const plan=buildInstallPlan({payload,target,profiles:state.mode==='composite'?'omit':'write',language,modelConfig,limits,skipGlobal:true,safeFs});
|
|
13
13
|
for(const [name,value]of entry.snapshot)plan.snapshot.set(name,value);
|
|
14
14
|
const current=inspectPath(safeFs,target.instructionPath,{kind:'file',read:true,snapshot:plan.snapshot});
|
|
15
15
|
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});}
|
|
@@ -20,5 +20,5 @@ export function buildUpgradePlans({payload,state,safeFs}){
|
|
|
20
20
|
}
|
|
21
21
|
export async function upgradeInstalledTargets({packageRoot,state,safeFs,signal}){
|
|
22
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,...await installTargets(plans,{safeFs,signal})};
|
|
23
|
+
return{version,residualPaths:state.residualPaths??[],...await installTargets(plans,{safeFs,signal})};
|
|
24
24
|
}
|