@yunhozz/arc 0.3.2 → 0.3.4
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 +105 -147
- package/README.md +3 -3
- package/claude/agents/arc-implementer.md +4 -4
- package/claude/agents/arc-planner.md +5 -5
- package/claude/agents/arc-qa.md +4 -4
- package/claude/agents/arc-reviewer.md +4 -4
- package/claude/agents/arc-scouter.md +5 -5
- package/claude/skill/SKILL.md +13 -8
- package/claude/skill/references/arc-visual-companion.md +5 -5
- package/claude/skill/references/commit.md +8 -8
- package/claude/skill/references/coordination.md +23 -21
- package/claude/skill/references/git-recovery.md +9 -4
- package/claude/skill/references/handoff-prep.md +13 -15
- package/claude/skill/references/handoff.md +22 -22
- package/claude/skill/references/limits.md +2 -2
- package/claude/skill/references/planning.md +20 -15
- package/claude/skill/references/verification.md +9 -9
- package/claude/skill/references/worktree-creation.md +14 -0
- package/codex/agents/arc-implementer.toml +4 -4
- package/codex/agents/arc-planner.toml +4 -4
- package/codex/agents/arc-qa.toml +4 -4
- package/codex/agents/arc-reviewer.toml +4 -4
- package/codex/agents/arc-scouter.toml +4 -4
- package/codex/skill/SKILL.md +12 -8
- package/codex/skill/references/arc-visual-companion.md +2 -2
- package/codex/skill/references/commit.md +8 -8
- package/codex/skill/references/coordination.md +22 -20
- package/codex/skill/references/git-recovery.md +5 -9
- package/codex/skill/references/handoff-prep.md +9 -9
- package/codex/skill/references/handoff.md +20 -20
- package/codex/skill/references/limits.md +2 -2
- package/codex/skill/references/planning.md +15 -15
- package/codex/skill/references/verification.md +10 -10
- package/codex/skill/references/worktree-creation.md +20 -0
- package/lib/installer/global-config.mjs +2 -2
- package/lib/installer/manifest.mjs +10 -9
- package/lib/installer/package-references.mjs +2 -2
- package/lib/installer/plan.mjs +3 -1
- package/lib/installer/skill-sources.mjs +23 -0
- package/lib/installer/superpowers.mjs +5 -5
- package/lib/policy/role-policy.json +10 -10
- package/lib/prompts/agent-fragments.json +16 -16
- package/lib/runtime/bootstrap.mjs +1 -1
- package/lib/runtime/local-cli.mjs +10 -20
- package/lib/runtime/role-bridge.mjs +2 -4
- package/lib/runtime/role-dispatch-policy.mjs +4 -9
- package/lib/runtime/role-routing.mjs +1 -2
- package/lib/watch/dispatch.mjs +10 -2
- package/lib/watch/git.mjs +4 -2
- package/lib/watch/index.mjs +16 -8
- package/lib/watch/model.mjs +8 -4
- package/lib/watch/normalize-claude.mjs +89 -7
- package/lib/watch/normalize-codex.mjs +15 -11
- package/lib/watch/render.mjs +73 -19
- package/lib/watch/scope.mjs +5 -5
- package/lib/watch/watcher.mjs +110 -10
- package/package.json +2 -1
- package/scripts/check-installer-parity.mjs +3 -1
- package/scripts/update-manifest.mjs +1 -1
- package/scripts/update-runtime-assets.mjs +1 -1
- package/{codex → shared}/skill/references/handoff-worktree.md +21 -20
- package/{codex → shared}/skill/runtime/bootstrap.mjs +1 -1
- package/{codex → shared}/skill/runtime/local-cli.mjs +10 -20
- package/{codex → shared}/skill/runtime/role-bridge.mjs +2 -4
- package/{claude → shared}/skill/runtime/role-dispatch-policy.mjs +4 -9
- package/{claude → shared}/skill/runtime/role-policy.json +10 -10
- package/{claude → shared}/skill/runtime/role-routing.mjs +1 -2
- package/claude/skill/runtime/bootstrap.mjs +0 -38
- package/claude/skill/runtime/local-cli.mjs +0 -248
- package/claude/skill/runtime/role-bridge.mjs +0 -227
- package/codex/skill/references/brainstorming.md +0 -316
- package/codex/skill/references/builder-check-prompt.md +0 -23
- package/codex/skill/references/scripts/frame-template.html +0 -213
- package/codex/skill/references/scripts/helper.js +0 -167
- package/codex/skill/references/scripts/server.cjs +0 -723
- package/codex/skill/references/scripts/start-server.sh +0 -216
- package/codex/skill/references/scripts/stop-server.sh +0 -120
- package/codex/skill/references/superpowers-LICENSE +0 -21
- package/codex/skill/references/superpowers-provenance.json +0 -26
- package/codex/skill/references/test-driven-development.md +0 -330
- package/codex/skill/references/visual-companion.md +0 -299
- package/codex/skill/references/writing-good-tests.md +0 -198
- package/codex/skill/references/writing-plans.md +0 -204
- package/codex/skill/runtime/acceptance.mjs +0 -68
- package/codex/skill/runtime/adapters/claude.mjs +0 -86
- package/codex/skill/runtime/adapters/codex.mjs +0 -65
- package/codex/skill/runtime/assignment.mjs +0 -42
- package/codex/skill/runtime/capabilities.mjs +0 -44
- package/codex/skill/runtime/cli.mjs +0 -8
- package/codex/skill/runtime/command.mjs +0 -38
- package/codex/skill/runtime/cooperative-schema.mjs +0 -87
- package/codex/skill/runtime/cooperative.mjs +0 -239
- package/codex/skill/runtime/evaluate.mjs +0 -331
- package/codex/skill/runtime/external.mjs +0 -51
- package/codex/skill/runtime/gate.mjs +0 -71
- package/codex/skill/runtime/git-evidence.mjs +0 -258
- package/codex/skill/runtime/git-query.mjs +0 -88
- package/codex/skill/runtime/identity.mjs +0 -49
- package/codex/skill/runtime/operations.mjs +0 -6
- package/codex/skill/runtime/role-bridge-args.mjs +0 -148
- package/codex/skill/runtime/role-dispatch-policy.mjs +0 -110
- package/codex/skill/runtime/role-dispatch-store.mjs +0 -134
- package/codex/skill/runtime/role-observe.mjs +0 -299
- package/codex/skill/runtime/role-policy.json +0 -654
- package/codex/skill/runtime/role-routing-config.mjs +0 -19
- package/codex/skill/runtime/role-routing.mjs +0 -233
- package/codex/skill/runtime/role-supervisor.mjs +0 -356
- package/codex/skill/runtime/schema.mjs +0 -98
- package/codex/skill/runtime/scope.mjs +0 -36
- package/codex/skill/runtime/store.mjs +0 -94
- package/codex/skill/runtime/target-preparation.mjs +0 -110
- package/codex/skill/runtime/verification.mjs +0 -125
- /package/{claude → shared}/skill/references/brainstorming.md +0 -0
- /package/{claude → shared}/skill/references/builder-check-prompt.md +0 -0
- /package/{claude → shared}/skill/references/scripts/frame-template.html +0 -0
- /package/{claude → shared}/skill/references/scripts/helper.js +0 -0
- /package/{claude → shared}/skill/references/scripts/server.cjs +0 -0
- /package/{claude → shared}/skill/references/scripts/start-server.sh +0 -0
- /package/{claude → shared}/skill/references/scripts/stop-server.sh +0 -0
- /package/{claude → shared}/skill/references/superpowers-LICENSE +0 -0
- /package/{claude → shared}/skill/references/superpowers-provenance.json +0 -0
- /package/{claude → shared}/skill/references/test-driven-development.md +0 -0
- /package/{claude → shared}/skill/references/visual-companion.md +0 -0
- /package/{claude → shared}/skill/references/writing-good-tests.md +0 -0
- /package/{claude → shared}/skill/references/writing-plans.md +0 -0
- /package/{claude → shared}/skill/runtime/acceptance.mjs +0 -0
- /package/{claude → shared}/skill/runtime/adapters/claude.mjs +0 -0
- /package/{claude → shared}/skill/runtime/adapters/codex.mjs +0 -0
- /package/{claude → shared}/skill/runtime/assignment.mjs +0 -0
- /package/{claude → shared}/skill/runtime/capabilities.mjs +0 -0
- /package/{claude → shared}/skill/runtime/cli.mjs +0 -0
- /package/{claude → shared}/skill/runtime/command.mjs +0 -0
- /package/{claude → shared}/skill/runtime/cooperative-schema.mjs +0 -0
- /package/{claude → shared}/skill/runtime/cooperative.mjs +0 -0
- /package/{claude → shared}/skill/runtime/evaluate.mjs +0 -0
- /package/{claude → shared}/skill/runtime/external.mjs +0 -0
- /package/{claude → shared}/skill/runtime/gate.mjs +0 -0
- /package/{claude → shared}/skill/runtime/git-evidence.mjs +0 -0
- /package/{claude → shared}/skill/runtime/git-query.mjs +0 -0
- /package/{claude → shared}/skill/runtime/identity.mjs +0 -0
- /package/{claude → shared}/skill/runtime/operations.mjs +0 -0
- /package/{claude → shared}/skill/runtime/role-bridge-args.mjs +0 -0
- /package/{claude → shared}/skill/runtime/role-dispatch-store.mjs +0 -0
- /package/{claude → shared}/skill/runtime/role-observe.mjs +0 -0
- /package/{claude → shared}/skill/runtime/role-routing-config.mjs +0 -0
- /package/{claude → shared}/skill/runtime/role-supervisor.mjs +0 -0
- /package/{claude → shared}/skill/runtime/schema.mjs +0 -0
- /package/{claude → shared}/skill/runtime/scope.mjs +0 -0
- /package/{claude → shared}/skill/runtime/store.mjs +0 -0
- /package/{claude → shared}/skill/runtime/target-preparation.mjs +0 -0
- /package/{claude → shared}/skill/runtime/verification.mjs +0 -0
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import {fingerprintRequest} from './store.mjs';
|
|
2
|
-
import {absolute,within} from './scope.mjs';
|
|
3
|
-
const completed=(state,id)=>state.tasks?.some(t=>t.id===id&&t.status==='committed'&&!t.invalidated)&&state.commits?.some(c=>c.taskId===id&&c.observationSource==='local-git'&&state.intents.some(i=>i.operation==='commit'&&i.requestId===c.requestId&&i.taskId===id&&i.status==='succeeded'));
|
|
4
|
-
const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|
5
|
-
const text=value=>typeof value==='string'&&value.length>0;
|
|
6
|
-
const version=value=>Number.isSafeInteger(value)&&value>0;
|
|
7
|
-
const setEqual=(a,b)=>Array.isArray(a)&&Array.isArray(b)&&new Set(a).size===a.length&&new Set(b).size===b.length&&same([...a].sort(),[...b].sort());
|
|
8
|
-
const base=state=>({expectedRevision:state?.revision??0,coverage:{enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false},requiredEvidence:[],nextActions:[],proposedTransition:null});
|
|
9
|
-
const hold=(state,id,reason)=>({...base(state),decision:'hold',ruleIds:['cooperative.'+id],reason});
|
|
10
|
-
/** Pure gate. observations are supplied by trusted local readers, never JSON input. */
|
|
11
|
-
export function prepareCooperativeAssignment({policy,state,request,observations}={}){
|
|
12
|
-
if(policy!==undefined&&policy.workflowKind!=='cooperative')return hold(state,'contract','Explicit cooperative contract required');
|
|
13
|
-
const args=request?.arguments;
|
|
14
|
-
if(state?.mode!=='plan'||request?.operation!=='assign-agent'||!args)return hold(state,'unsupported','Only explicit plan assignment is supported');
|
|
15
|
-
const allowed=['role','paths','operations','documents','approvalRef','approvalVersion','documentVersion','correlation'];
|
|
16
|
-
if(Object.keys(args).some(k=>!allowed.includes(k))||args.role!=='implementer'||!text(request.taskId)||!text(request.requestId)||!text(args.correlation)||!text(args.approvalRef)||!version(args.approvalVersion)||!version(args.documentVersion)||!Array.isArray(args.paths)||!args.paths.length||new Set(args.paths).size!==args.paths.length||args.paths.some(p=>!absolute(p)||!within(state.target.realpath,p))||!Array.isArray(args.operations)||!args.operations.length||args.operations.some(o=>o!=='edit'))return hold(state,'assignment','Invalid assignment or unsupported historical agent import');
|
|
17
|
-
if(!same(observations?.target,state.target)||!same(observations?.git?.target,state.target))return hold(state,'target','Re-observe target and renew approval after drift');
|
|
18
|
-
if(request.expectedRevision!==state.revision)return hold(state,'revision','Stale assignment request');
|
|
19
|
-
if(state.records.some(r=>r.data?.priorExecution===true)||state.assignments.some(a=>a.source!=='operator-attested'))return hold(state,'history','Earlier execution remains unverified; a late commit cannot authorize it');
|
|
20
|
-
if(state.intents.some(i=>i.operation==='assign-agent'&&['prepared','unknown','mismatch','succeeded'].includes(i.status)&&(i.taskId===request.taskId||i.correlation===args.correlation||!(i.status==='succeeded'&&completed(state,i.taskId))&&i.paths?.some(p=>args.paths.some(q=>within(p,q)||within(q,p))))))return hold(state,'assignment-active','Resolve the existing dispatch before preparing another');
|
|
21
|
-
const task=state.tasks?.find(t=>t.id===request.taskId);
|
|
22
|
-
if(task&&(task.invalidated||task.status==='held'||task.dependencies?.some(id=>{const predecessor=state.tasks.find(t=>t.id===id);return !predecessor||predecessor.invalidated||!['accepted','committed'].includes(predecessor.status);})))return hold(state,'task-stale','Affected task or predecessor requires renewed readiness and approval');
|
|
23
|
-
const scope=state.scopes?.findLast(s=>s.scopeVersion===state.scopeVersion&&(!s.data.affectedTaskIds||s.data.affectedTaskIds.includes(request.taskId)));
|
|
24
|
-
if(!task||!task.paths?.length||args.paths.some(p=>!task.paths.some(base=>within(base,p)))||scope&&args.paths.some(p=>!scope.data.paths?.some(base=>within(base,p))))return hold(state,'assignment-scope','Assignment must stay inside approved task and recorded scope');
|
|
25
|
-
const documents=args.documents,git=observations.git;
|
|
26
|
-
if(!Array.isArray(documents)||documents.length!==2||!setEqual(documents.map(d=>d.kind),['spec','plan'])||!git.docsCommit||!setEqual(git.docsCommit.paths,documents.map(d=>d.gitPath))||!same(git.docsCommit.documents,documents)||documents.some(d=>d.commit!==git.docsCommit.commit)||!Array.isArray(git.documents)||git.documents.length!==2||documents.some(d=>!git.documents.some(o=>o.path===d.path&&o.gitPath===d.gitPath&&o.kind===d.kind&&o.observedHash===d.contentHash&&o.currentHash===d.contentHash)))return hold(state,'documents','Exact committed spec and plan plus current bytes must match approval');
|
|
27
|
-
const approval=state.records.filter(r=>r.kind==='approval'&&(!r.data.affectedTaskIds||r.data.affectedTaskIds.includes(request.taskId))).at(-1);
|
|
28
|
-
if(task.approvalRef!==args.approvalRef||task.approvalVersion!==args.approvalVersion||task.documentVersion!==args.documentVersion||task.scopeVersion!==state.scopeVersion||task.targetVersion!==state.targetVersion||!approval||approval.source!=='operator-attested'||approval.messageRef!==args.approvalRef||approval.targetVersion!==state.targetVersion||approval.scopeVersion!==state.scopeVersion||approval.data.approvalVersion!==args.approvalVersion||approval.data.documentVersion!==args.documentVersion||!same(approval.data.documents,documents)||documents.some(d=>d.approvalRef!==args.approvalRef))return hold(state,'approval','Current document and approval versions must match');
|
|
29
|
-
const intent={requestId:request.requestId,taskId:request.taskId,operation:request.operation,status:'prepared',role:args.role,paths:[...args.paths],operations:[...args.operations],correlation:args.correlation,documents:structuredClone(documents),docsCommit:git.docsCommit.commit,approvalRef:args.approvalRef,approvalVersion:args.approvalVersion,documentVersion:args.documentVersion,target:structuredClone(state.target),targetVersion:state.targetVersion,scopeVersion:state.scopeVersion,revision:state.revision+1,fingerprint:fingerprintRequest(request),source:'operator-attested'};
|
|
30
|
-
return {...base(state),decision:'allow',ruleIds:['cooperative.assignment-prepared'],proposedTransition:{intent}};
|
|
31
|
-
}
|
|
32
|
-
/** A native response is an operator statement, not authenticated identity or compliance. */
|
|
33
|
-
export function recordCooperativeAssignmentResult({state,intent,result,observations}={}){
|
|
34
|
-
if(!intent||intent.operation!=='assign-agent')return hold(state,'intent','No matching assignment intent');
|
|
35
|
-
if(!['prepared','unknown','mismatch'].includes(intent.status))return hold(state,'assignment-terminal','Preserve the prior terminal native response');
|
|
36
|
-
if(!result||!['succeeded','failed','unknown','mismatch'].includes(result.status)||!text(result.messageRef)||!result.data)return hold(state,'assignment-result','Invalid native result statement');
|
|
37
|
-
if(result.status==='succeeded'&&(state.assignments.some(a=>a.agentId===result.data.agentId&&a.taskId!==intent.taskId)||state.intents?.some(i=>i.verificationActor?.id===result.data.agentId)||state.checks?.some(c=>c.verificationActor?.id===result.data.agentId)))return hold(state,'assignment-freshness','Implementer actor statements cannot cross tasks');
|
|
38
|
-
let status=result.status;
|
|
39
|
-
if(!same(intent.target,observations?.target)||result.data.correlation!==intent.correlation||result.data.taskId!==intent.taskId||status==='succeeded'&&!text(result.data.agentId))status='mismatch';
|
|
40
|
-
const entry={...structuredClone(result),status,requestId:intent.requestId,source:'operator-attested'};
|
|
41
|
-
return {...base(state),decision:['succeeded','failed'].includes(status)?'allow':'hold',ruleIds:['cooperative.assignment-'+status],proposedTransition:{result:entry}};
|
|
42
|
-
}
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
// Declarations describe documented hooks, never proof that this installation ran them.
|
|
2
|
-
const contracts = {
|
|
3
|
-
codex: {spawn_agent:'Agent', followup_task:null, SubagentStart:null},
|
|
4
|
-
claude: {Agent:'Agent', SubagentStart:null},
|
|
5
|
-
};
|
|
6
|
-
function operationOf(receipt, platform) {
|
|
7
|
-
const matcher = contracts[platform]?.[receipt.operation];
|
|
8
|
-
return matcher && receipt.toolPath === matcher ? receipt.operation : null;
|
|
9
|
-
}
|
|
10
|
-
export function summarizeProbe(receipts, {platform, sessionRef, platformVersion, attemptRef} = {}) {
|
|
11
|
-
const candidates = Array.isArray(receipts) ? receipts.filter(r => r && r.source === 'native' &&
|
|
12
|
-
r.platform === platform && operationOf(r,platform) &&
|
|
13
|
-
typeof sessionRef === 'string' && sessionRef.length > 0 && r.sessionRef === sessionRef &&
|
|
14
|
-
typeof platformVersion === 'string' && platformVersion.length > 0 && r.platformVersion === platformVersion &&
|
|
15
|
-
typeof attemptRef === 'string' && attemptRef.length > 0 && r.attemptRef === attemptRef &&
|
|
16
|
-
r.event === 'PreToolUse' && ['host-result','hook-decision'].includes(r.kind) &&
|
|
17
|
-
r.decision === 'deny' && (r.kind !== 'host-result' || (r.toolExecuted === false && r.success === true))) : [];
|
|
18
|
-
// JSON is unauthenticated. No native host verifier is available here, so even
|
|
19
|
-
// a structurally valid current receipt is only an unverified observation.
|
|
20
|
-
return {platform,sessionRef,platformVersion,attemptRef,verifiedDeny:false,status:'unknown',source:'unverified',
|
|
21
|
-
toolPaths:[...new Set(candidates.map(r=>operationOf(r,platform)))]};
|
|
22
|
-
}
|
|
23
|
-
export function evaluateCapability({platform,toolPath,sessionRef,platformVersion,attemptRef,receipts=[]} = {}) {
|
|
24
|
-
const known=Object.hasOwn(contracts[platform] ?? {},toolPath);
|
|
25
|
-
const observationOnly=known && toolPath === 'SubagentStart';
|
|
26
|
-
const observed=summarizeProbe(receipts,{platform,sessionRef,platformVersion,attemptRef});
|
|
27
|
-
return {platform,toolPath,sessionRef,platformVersion,attemptRef,observationOnly,
|
|
28
|
-
declared:{source:'documentation',matcher:contracts[platform]?.[toolPath] ?? null},
|
|
29
|
-
status:!known || observationOnly ? 'unsupported':'unknown',verifiedDeny:false,
|
|
30
|
-
source:!known || observationOnly ? 'documentation':'unverified',
|
|
31
|
-
observation:observationOnly?'documented':toolPath==='followup_task'?'unknown':'not-verified',enforcement:observationOnly?'observation-only':'unverified',
|
|
32
|
-
observedPaths:observed.toolPaths.filter(p=>p === toolPath)};
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** Raw event fields identify an invocation, not its approved role or semantics. */
|
|
36
|
-
export function plannerHookContextStatus({platform,input,context={}}={}){
|
|
37
|
-
const text=v=>typeof v==='string'&&v.length>0,object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
|
|
38
|
-
const fields={
|
|
39
|
-
'hook.hook_event_name':input?.hook_event_name==='PreToolUse','hook.session_id':text(input?.session_id),'hook.tool_use_id':text(input?.tool_use_id),'hook.tool_name':text(input?.tool_name),'hook.tool_input':object(input?.tool_input),'hook.cwd':text(input?.cwd),
|
|
40
|
-
'context.sessionRef':text(context.sessionRef),'context.actorRef':text(context.actorRef),'context.taskId':text(context.taskId),'context.requestId':text(context.requestId),'context.toolUseId':text(context.toolUseId),'context.statePath':text(context.statePath),'context.state':object(context.state),'context.policy':object(context.policy),'context.evidence':object(context.evidence),'context.describeTool':typeof context.describeTool==='function',
|
|
41
|
-
};
|
|
42
|
-
const missing=Object.keys(fields).filter(k=>!fields[k]);
|
|
43
|
-
return {platform,available:Object.keys(fields).filter(k=>fields[k]),missing,enforcement:missing.length?'unavailable':'hook-response-only',nativeVerified:false,source:'context-validation'};
|
|
44
|
-
}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import {fileURLToPath} from 'node:url';
|
|
3
|
-
import {runWorkflowCommand} from './command.mjs';
|
|
4
|
-
export {runWorkflowCommand};
|
|
5
|
-
// Importing the installed entry is safe for callers that own their own IO.
|
|
6
|
-
if(process.argv[1]&&fs.realpathSync(process.argv[1])===fileURLToPath(import.meta.url)){
|
|
7
|
-
process.exitCode=await runWorkflowCommand(process.argv.slice(2));
|
|
8
|
-
}
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import os from 'node:os';
|
|
4
|
-
import {initializeCooperativeWorkflow,commandResult} from './bootstrap.mjs';
|
|
5
|
-
import {runCooperativeCommand} from './cooperative.mjs';
|
|
6
|
-
import {validateWorkflowId} from './scope.mjs';
|
|
7
|
-
import {prepareRoleDispatch,routingStatus,invalidRoutingRequest} from './role-routing.mjs';
|
|
8
|
-
import {runBridgeDispatch,recordRoleObservation,resumeRoleDispatch,cancelRoleDispatch,heldRoutingResult} from './role-bridge.mjs';
|
|
9
|
-
export async function runWorkflowCommand(args,io={}){
|
|
10
|
-
const output=io.output??process.stdout;let workflowId=null,isRouting=false;
|
|
11
|
-
try{
|
|
12
|
-
const [command,...rest]=args,options={};
|
|
13
|
-
isRouting=['routing-status','prepare-dispatch','run-dispatch','observe','resume','cancel'].includes(command);
|
|
14
|
-
if(!['init','record','status','reconcile','prepare','result'].includes(command)&&!isRouting)throw Error('Expected workflow command');
|
|
15
|
-
// A bridge child must not drive routing itself: the supervisor sets ARC_BRIDGE_CHILD for the child CLI process tree.
|
|
16
|
-
if(isRouting&&(io.env??process.env).ARC_BRIDGE_CHILD){output.write(JSON.stringify({workflowId:null,...invalidRoutingRequest({}),message:'Routing commands are not available inside a bridge child.'})+'\n');return 2;}
|
|
17
|
-
for(let i=0;i<rest.length;i+=2){const key=rest[i];if(!['--cwd','--workflow','--input'].includes(key)||options[key]!==undefined||typeof rest[i+1]!=='string')throw Error('Invalid workflow option');options[key]=rest[i+1];}
|
|
18
|
-
const cwd=options['--cwd'];workflowId=options['--workflow'];validateWorkflowId(workflowId);
|
|
19
|
-
if(typeof cwd!=='string'||!path.isAbsolute(cwd)||path.normalize(cwd)!==cwd)throw Error('Absolute workspace required');
|
|
20
|
-
if(command==='status'?options['--input']!==undefined:options['--input']!=='-')throw Error('Mutations require --input -; status takes no input');
|
|
21
|
-
// Check/review, commit and external intents are recorded for the operator.
|
|
22
|
-
// Actual Git mutations remain Orchestrator actions; reconciliation observes their results.
|
|
23
|
-
const input=command==='status'?undefined:JSON.parse(io.input??fs.readFileSync(0,'utf8'));
|
|
24
|
-
let result;
|
|
25
|
-
if(isRouting){
|
|
26
|
-
if(!input||typeof input!=='object'||Array.isArray(input))throw Error('Invalid routing input');
|
|
27
|
-
const context={cwd,userHome:os.homedir(),env:process.env,workflowId,hostPlatform:input.hostPlatform,executionEnvironment:input.executionEnvironment};
|
|
28
|
-
const keys=Object.keys(input),allowed={'routing-status':[['hostPlatform','executionEnvironment'],[]],'prepare-dispatch':[['hostPlatform','executionEnvironment','role','expectedRevision','requestId','taskId'],['allowedPaths']],'run-dispatch':[['hostPlatform','executionEnvironment','dispatchId','brief'],[]],observe:[['hostPlatform','executionEnvironment','dispatchId'],['waitMs','event','nativeAgentId']],resume:[['hostPlatform','executionEnvironment','dispatchId','brief'],[]],cancel:[['hostPlatform','executionEnvironment','dispatchId'],[]]}[command];
|
|
29
|
-
if(allowed&&(allowed[0].some(key=>!Object.hasOwn(input,key))||keys.some(key=>!allowed[0].includes(key)&&!allowed[1].includes(key))))result=invalidRoutingRequest(context);
|
|
30
|
-
else result=command==='routing-status'?await routingStatus({context}):command==='prepare-dispatch'?await prepareRoleDispatch({context,assignment:{role:input.role,requestId:input.requestId,taskId:input.taskId,...(Object.hasOwn(input,'allowedPaths')?{allowedPaths:input.allowedPaths}:{})},expectedRevision:input.expectedRevision}):command==='run-dispatch'?await runBridgeDispatch({context,dispatchId:input.dispatchId,brief:input.brief}):command==='observe'?await recordRoleObservation({context,dispatchId:input.dispatchId,...(Object.hasOwn(input,'waitMs')?{waitMs:input.waitMs}:{}),...(Object.hasOwn(input,'event')?{event:input.event}:{}),...(Object.hasOwn(input,'nativeAgentId')?{nativeAgentId:input.nativeAgentId}:{})}):command==='resume'?await resumeRoleDispatch({context,dispatchId:input.dispatchId,brief:input.brief}):await cancelRoleDispatch({context,dispatchId:input.dispatchId});
|
|
31
|
-
result={workflowId,...result};
|
|
32
|
-
}else result=await(command==='init'?initializeCooperativeWorkflow({cwd,workflowId,input}):runCooperativeCommand({cwd,workflowId,command,input}));
|
|
33
|
-
output.write(JSON.stringify(result)+'\n');return result.decision==='deny'?2:result.decision==='hold'?3:0;
|
|
34
|
-
}catch(error){
|
|
35
|
-
const result=isRouting?{workflowId:null,...heldRoutingResult('activation_unverified','Provide a valid routing request and verify the active configuration and installed markers.')}:commandResult({workflowId,decision:'hold',ruleId:'cooperative.error',error:error.message});
|
|
36
|
-
output.write(JSON.stringify(result)+'\n');return 1;
|
|
37
|
-
}
|
|
38
|
-
}
|
|
@@ -1,87 +0,0 @@
|
|
|
1
|
-
import {ROLES} from './operations.mjs';
|
|
2
|
-
import {assertSecretFree} from './external.mjs';
|
|
3
|
-
import {object,text,validatePlannerLedger} from './schema.mjs';
|
|
4
|
-
import {absolute,validateWorkflowId} from './scope.mjs';
|
|
5
|
-
import path from 'node:path';
|
|
6
|
-
import {validateTargetPreparationRecord} from './target-preparation.mjs';
|
|
7
|
-
const fail=message=>{throw Error('Cooperative schema: '+message);};
|
|
8
|
-
const hash=value=>typeof value==='string'&&/^sha256:[a-f0-9]{64}$/.test(value);
|
|
9
|
-
const revision=value=>Number.isSafeInteger(value)&&value>=0;
|
|
10
|
-
const actor=value=>object(value)&&text(value.id)&&Object.keys(value).every(k=>['id','role'].includes(k))&&(value.role===undefined||ROLES.includes(value.role));
|
|
11
|
-
const statement=value=>object(value)&&text(value.messageRef)&&object(value.data);
|
|
12
|
-
function fields(value,allowed){if(!object(value)||Object.keys(value).some(k=>!allowed.includes(k)))fail('unexpected input field');}
|
|
13
|
-
function json(value){try{const encoded=JSON.stringify(value);if(encoded===undefined)fail('JSON input');}catch{fail('JSON input');}}
|
|
14
|
-
const exact=(value,keys)=>object(value)&&Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
|
|
15
|
-
const oid=value=>typeof value==='string'&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(value);
|
|
16
|
-
const time=value=>typeof value==='string'&&Number.isFinite(Date.parse(value))&&/(?:Z|[+-]\d\d:\d\d)$/.test(value);
|
|
17
|
-
const unique=value=>Array.isArray(value)&&new Set(value).size===value.length;
|
|
18
|
-
const gitPath=value=>text(value)&&!/[\\\x00\r\n:]/.test(value)&&!value.startsWith('/')&&!value.split('/').some(part=>!part||part==='.'||part==='..');
|
|
19
|
-
const ref=value=>text(value)&&/^refs\/[A-Za-z0-9][A-Za-z0-9._\/-]*$/.test(value)&&!value.includes('..')&&!value.includes('//')&&!value.endsWith('/')&&!value.endsWith('.')&&!value.endsWith('.lock');
|
|
20
|
-
const approval=value=>exact(value,['ref','version','hash','approvedAt'])&&text(value.ref)&&Number.isSafeInteger(value.version)&&value.version>0&&hash(value.hash)&&time(value.approvedAt);
|
|
21
|
-
const document=value=>exact(value,['version','hash','content'])&&Number.isSafeInteger(value.version)&&value.version>0&&hash(value.hash)&&typeof value.content==='string'&&Buffer.byteLength(value.content)<=1024*1024;
|
|
22
|
-
export function validatePlanAmendArguments(a){
|
|
23
|
-
if(!exact(a,['classification','reason','changedAt','affectedTaskIds','plan','history','approvals','writers','ownership','publication','remotes','recovery'])||!['contract','mechanical'].includes(a.classification)||!text(a.reason)||!time(a.changedAt)||!unique(a.affectedTaskIds)||!a.affectedTaskIds.length||!a.affectedTaskIds.every(text))fail('plan-amend request');
|
|
24
|
-
if(!exact(a.plan,['path','gitPath','old','new'])||!absolute(a.plan.path)||!gitPath(a.plan.gitPath)||!document(a.plan.old)||!document(a.plan.new)||a.plan.new.version<=a.plan.old.version)fail('plan-amend document');
|
|
25
|
-
if(!exact(a.history,['base','planCommit','head','branch'])||![a.history.base,a.history.planCommit,a.history.head].every(oid)||!text(a.history.branch)||/[\x00\r\n]/.test(a.history.branch))fail('plan-amend history');
|
|
26
|
-
if(!exact(a.approvals,['original','amendment'])||!approval(a.approvals.original)||!(a.classification==='mechanical'&&a.approvals.amendment===null||approval(a.approvals.amendment)))fail('plan-amend approvals');
|
|
27
|
-
if(!Array.isArray(a.writers)||!a.writers.length||a.writers.some(w=>!exact(w,['assignmentId','stoppedAt','evidenceRef'])||!text(w.assignmentId)||!time(w.stoppedAt)||!text(w.evidenceRef))||!unique(a.writers.map(w=>w.assignmentId)))fail('plan-amend writers');
|
|
28
|
-
if(!['exclusive','shared','unknown'].includes(a.ownership)||!['unpublished','published','unknown'].includes(a.publication)||!Array.isArray(a.remotes)||a.remotes.some(r=>!exact(r,['name','identity','complete','refs','observedAt','evidenceRef'])||!text(r.name)||!hash(r.identity)||r.complete!==true||!time(r.observedAt)||!text(r.evidenceRef)||!Array.isArray(r.refs)||r.refs.some(x=>!exact(x,['name','oid'])||!ref(x.name)||!oid(x.oid))||!unique(r.refs.map(x=>x.name)))||!unique(a.remotes.map(r=>r.name)))fail('plan-amend remote snapshot');
|
|
29
|
-
if(!exact(a.recovery,['ref','oid'])||!ref(a.recovery.ref)||!a.recovery.ref.startsWith('refs/arc/recovery/')||!oid(a.recovery.oid)||path.normalize(a.plan.path)!==a.plan.path)fail('plan-amend recovery');
|
|
30
|
-
return a;
|
|
31
|
-
}
|
|
32
|
-
export function validateCooperativeCommand(command){
|
|
33
|
-
assertSecretFree(command);fields(command,['command','input']);const {input,command:name}=command;
|
|
34
|
-
if(!['init','record','status','reconcile','prepare','result'].includes(name))fail('command');
|
|
35
|
-
if(name==='status'){if(input!==undefined)fail('status takes no input');return command;}
|
|
36
|
-
const resultStatement=name==='reconcile'||name==='result'&&input?.operation===undefined;
|
|
37
|
-
const allowed=name==='init'?['mode','actor','selection']:name==='record'?['requestId','expectedRevision','actor','evidence']:resultStatement?['requestId','expectedRevision','actor','intentId','result']:['requestId','expectedRevision','actor','operation','taskId','arguments'];
|
|
38
|
-
fields(input,allowed);json(input);
|
|
39
|
-
if(!actor(input.actor))fail('actor attestation');
|
|
40
|
-
if(name==='init'){
|
|
41
|
-
if(!['plan','no-plan','small-task'].includes(input.mode)||!object(input.selection)||!text(input.selection.messageRef)||!hash(input.selection.contentHash)||Object.keys(input.selection).some(k=>!['messageRef','contentHash'].includes(k)))fail('target selection');
|
|
42
|
-
return command;
|
|
43
|
-
}
|
|
44
|
-
if(!text(input.requestId)||input.requestId.length>128||!revision(input.expectedRevision))fail('request identity or revision');
|
|
45
|
-
if(name==='record'){
|
|
46
|
-
fields(input.evidence,['kind','messageRef','data']);
|
|
47
|
-
if(input.evidence?.data?.affectedTaskIds!==undefined&&(!Array.isArray(input.evidence.data.affectedTaskIds)||!input.evidence.data.affectedTaskIds.every(text)||new Set(input.evidence.data.affectedTaskIds).size!==input.evidence.data.affectedTaskIds.length))fail('affected task IDs');
|
|
48
|
-
if(!statement(input.evidence)||!['note','approval','external-approval','document','scope','check','finding','review','acceptance-evidence','planner-stage','planner-evidence','planner-result','planner-review','target-preparation'].includes(input.evidence.kind))fail('evidence');
|
|
49
|
-
}
|
|
50
|
-
if(resultStatement){
|
|
51
|
-
fields(input.result,['status','messageRef','data','notExecutedEvidence']);
|
|
52
|
-
if(!text(input.intentId)||!statement(input.result)||!['succeeded','failed','unknown','mismatch','cancelled'].includes(input.result.status))fail('result evidence');
|
|
53
|
-
if(input.result.status==='cancelled'&&(!object(input.result.notExecutedEvidence)||!text(input.result.notExecutedEvidence.messageRef)))fail('cancel requires not-executed evidence');
|
|
54
|
-
}
|
|
55
|
-
if((name==='prepare'||name==='result'&&!resultStatement)&&!text(input.operation))fail('operation');
|
|
56
|
-
if(name==='prepare'&&input.operation==='plan-amend')validatePlanAmendArguments(input.arguments);
|
|
57
|
-
return command;
|
|
58
|
-
}
|
|
59
|
-
export function validateCooperativeState(state){
|
|
60
|
-
if(!object(state)||state.workflowKind!=='cooperative'||state.contractVersion!==1||state.schemaVersion!==1||!revision(state.revision)||state.mode!=='plan')fail('explicit cooperative contract');
|
|
61
|
-
validateWorkflowId(state.workflowId);
|
|
62
|
-
if(!object(state.target)||!absolute(state.target.realpath)||!absolute(state.target.gitCommonDir)||!absolute(state.target.gitDir)||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(state.target.head)||!(state.target.branch===null||text(state.target.branch)))fail('target');
|
|
63
|
-
if(!object(state.versions)||!text(state.versions.policy)||!text(state.versions.runtime)||!hash(state.versions.policyHash)||!hash(state.versions.runtimeHash))fail('versions');
|
|
64
|
-
if(!object(state.coverage)||state.coverage.provenance!=='operator-attested'||state.coverage.nativeVerified!==false||state.coverage.enforcement!=='cooperative')fail('coverage');
|
|
65
|
-
for(const key of ['actors','selections','assignments','identities','leases','scopes','approvals','documents','tasks','requests','intents','results','checks','findings','acceptances','commits','audit','unresolved','records','targetHistory'])if(!Array.isArray(state[key]))fail(key);
|
|
66
|
-
if(state.tasks.some(t=>!object(t)||!text(t.id)||!Array.isArray(t.paths)||!Array.isArray(t.criteria)||!Array.isArray(t.requiredChecks)||!Array.isArray(t.dependencies))||new Set(state.tasks.map(t=>t.id)).size!==state.tasks.length)fail('task contracts');
|
|
67
|
-
if(state.commitObservations!==undefined&&(!Array.isArray(state.commitObservations)||state.commitObservations.some(o=>!object(o)||o.source!=='local-git'||!text(o.intentId)||!revision(o.revision))))fail('commit observations');
|
|
68
|
-
if(state.planAmendObservations!==undefined&&(!Array.isArray(state.planAmendObservations)||state.planAmendObservations.some(o=>!object(o)||o.source!=='local-git'||!text(o.intentId)||!revision(o.revision))))fail('plan-amend observations');
|
|
69
|
-
if(state.planAmendments!==undefined&&(!Array.isArray(state.planAmendments)||state.planAmendments.some(a=>!object(a)||a.source!=='operator-attested'||a.observationSource!=='local-git'||!text(a.intentId)||!absolute(a.path)||!hash(a.oldHash)||!hash(a.newHash)||!oid(a.oldCommit)||!oid(a.newCommit)||!Array.isArray(a.mapping)||!a.mapping.length)))fail('plan-amend connections');
|
|
70
|
-
if(!revision(state.scopeVersion)||!revision(state.targetVersion))fail('scope/target version');
|
|
71
|
-
if(state.actors.some(a=>!actor(a.actor)||a.source!=='operator-attested')||state.selections.some(s=>s.source!=='operator-attested'||!text(s.messageRef)))fail('attestations');
|
|
72
|
-
for(const key of ['scopes','approvals','documents','checks','findings','acceptances','commits'])if(state[key].some(entry=>!object(entry)||entry.source!=='operator-attested'))fail('attestation source');
|
|
73
|
-
if(state.records.some(r=>!actor(r.actor)||r.source!=='operator-attested'||!text(r.kind)||!statement(r)))fail('records');
|
|
74
|
-
if(state.requests.some(r=>!text(r.requestId)||!hash(r.requestFingerprint)||!object(r.decision))||new Set(state.requests.map(r=>r.requestId)).size!==state.requests.length)fail('request replay');
|
|
75
|
-
if(state.intents.some(i=>!text(i.requestId)||!['prepared','succeeded','failed','unknown','mismatch','cancelled'].includes(i.status)||!hash(i.fingerprint))||new Set(state.intents.map(i=>i.requestId)).size!==state.intents.length)fail('intents');
|
|
76
|
-
for(const intent of state.intents.filter(i=>i.operation==='plan-amend')){validatePlanAmendArguments(intent.arguments);if(!object(intent.target)||!object(intent.versions)||!object(intent.observation)||intent.source!=='operator-attested'||intent.checkpoint!==undefined&&!object(intent.checkpoint))fail('plan-amend intent');}
|
|
77
|
-
if(state.results.some(r=>!text(r.requestId)||!['succeeded','failed','unknown','mismatch','cancelled'].includes(r.status)||r.source!=='operator-attested'||!object(r.data)))fail('results');
|
|
78
|
-
if(state.plannerLedger!==undefined){validatePlannerLedger(state.plannerLedger);if(state.plannerLedger.stages.some(stage=>stage.workflowId!==state.workflowId||!Array.isArray(stage.artifacts)))fail('Planner workflow binding or artifacts');}
|
|
79
|
-
for(const key of ['targetIntents','targetCheckpoints','targetTransitions','targetDocuments'])if(state[key]!==undefined&&!Array.isArray(state[key]))fail(key);
|
|
80
|
-
const preparationIntents=state.targetIntents??[],checkpoints=state.targetCheckpoints??[],transitions=state.targetTransitions??[],documents=state.targetDocuments??[];
|
|
81
|
-
if(new Set(preparationIntents.map(i=>i.id)).size!==preparationIntents.length)fail('target intent identity');
|
|
82
|
-
for(const intent of preparationIntents){try{validateTargetPreparationRecord('intent',intent);}catch{fail('target intent');}const approved=state.records.find(r=>r.kind==='approval'&&r.messageRef===intent.approvalRef&&r.source==='operator-attested'&&r.actor?.role==='orchestrator'&&r.scopeVersion===intent.scopeVersion&&r.targetVersion===intent.sourceTargetVersion)?.data?.targetPreparation;if(intent.source!=='operator-attested'||intent.workflowId!==state.workflowId||!revision(intent.scopeVersion)||!hash(intent.sourceFingerprint)||!object(intent.sourceSnapshot)||!approved||['depth','selectionRef','kind','candidate','base','workflowId','firstStageId','sourceTargetVersion'].some(k=>approved[k]!==intent[k])||JSON.stringify(approved.sourceTarget)!==JSON.stringify(intent.sourceTarget)||JSON.stringify(approved.documents)!==JSON.stringify(intent.documents))fail('target intent provenance');}
|
|
83
|
-
for(const checkpoint of checkpoints){try{validateTargetPreparationRecord('checkpoint',{type:'checkpoint',...checkpoint});}catch{fail('target checkpoint');}if(checkpoint.source!=='operator-attested'||!text(checkpoint.messageRef)||!preparationIntents.some(i=>i.id===checkpoint.intentId&&i.firstStageId===checkpoint.stageId)||!state.records.some(r=>r.kind==='target-preparation'&&r.messageRef===checkpoint.messageRef&&r.source==='operator-attested'))fail('target checkpoint provenance');}
|
|
84
|
-
for(const transition of transitions){const request=transition.validation?.request;try{validateTargetPreparationRecord('transition',request);}catch{fail('target transition');}if(!object(transition.target)||!text(transition.messageRef)||!Number.isSafeInteger(transition.targetVersion)||transition.targetVersion!==transition.sourceTargetVersion+1||request.intentId!==transition.intentId||request.checkpointRef!==transition.checkpointRef||!preparationIntents.some(i=>i.id===transition.intentId)||!checkpoints.some(c=>c.intentId===transition.intentId&&c.messageRef===transition.checkpointRef)||!state.records.some(r=>r.kind==='target-preparation'&&r.messageRef===transition.messageRef&&r.source==='operator-attested'))fail('target transition provenance');}
|
|
85
|
-
for(const document of documents){try{validateTargetPreparationRecord('destination',document);}catch{fail('target document');}if(document.sourceLink!=='operator-attested'||document.verification?.status!=='verified'||document.verification?.source!=='local-bytes'||!text(document.messageRef)||!transitions.some(t=>t.intentId===document.intentId&&t.messageRef===document.transitionRef&&t.targetVersion===document.targetVersion)||!state.records.some(r=>r.kind==='target-preparation'&&r.messageRef===document.messageRef&&r.source==='operator-attested'))fail('target document provenance');}
|
|
86
|
-
assertSecretFree(state);json(state);return state;
|
|
87
|
-
}
|
|
@@ -1,239 +0,0 @@
|
|
|
1
|
-
import {EXTERNAL_ACTIONS,reconcileCooperativeExternal,cooperativeSupport} from './external.mjs';
|
|
2
|
-
import {reconcileCooperativeCommit} from './acceptance.mjs';
|
|
3
|
-
import {evaluateCooperativeVerification,invalidateAffectedEvidence,readCooperativeChanges} from './verification.mjs';
|
|
4
|
-
import {readAssignmentGitEvidence,readCooperativeCommitGitEvidence,readPlanAmendGitEvidence} from './git-evidence.mjs';
|
|
5
|
-
import {recordCooperativeAssignmentResult} from './assignment.mjs';
|
|
6
|
-
import fs from 'node:fs/promises';
|
|
7
|
-
import {constants} from 'node:fs';
|
|
8
|
-
import path from 'node:path';
|
|
9
|
-
import {createHash} from 'node:crypto';
|
|
10
|
-
import {validateCooperativeCommand,validateCooperativeState} from './cooperative-schema.mjs';
|
|
11
|
-
import {observeCooperativeTarget,validateObservedTarget,validateWorkflowId,workflowStatePath,inspectPath,absolute,within} from './scope.mjs';
|
|
12
|
-
import {fingerprintRequest,saveDurableState,applyCooperativeCommitTransition,applyCooperativeTargetTransition} from './store.mjs';
|
|
13
|
-
import {commandResult,cooperativeVersions} from './bootstrap.mjs';
|
|
14
|
-
import {evaluateCooperative,reconcileCooperativeResult,reconcileCooperativePlanAmend} from './evaluate.mjs';
|
|
15
|
-
import {evaluateTargetPreparation,readTargetPreparationEvidence} from './target-preparation.mjs';
|
|
16
|
-
const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|
17
|
-
const sameCheckout=(a,b)=>['realpath','gitCommonDir','gitDir'].every(k=>a[k]===b[k]);
|
|
18
|
-
/** Only trusted code may inject observation/storage. CLI JSON cannot set either. */
|
|
19
|
-
export async function runCooperativeCommand({cwd,workflowId,command,input,observe=observeCooperativeTarget,storage={},readGit=readAssignmentGitEvidence,readChanges=readCooperativeChanges,readCommitGit=readCooperativeCommitGitEvidence,readPlanAmendGit=readPlanAmendGitEvidence,clock=Date.now}){
|
|
20
|
-
validateWorkflowId(workflowId);validateCooperativeCommand({command,input});
|
|
21
|
-
if(command==='init')throw Error('Use initializeCooperativeWorkflow for init');
|
|
22
|
-
const target=await validateObservedTarget(cwd,await observe(cwd)),statePath=await workflowStatePath(target,workflowId);
|
|
23
|
-
const read=async()=>{await inspectPath(statePath);const state=validateCooperativeState(JSON.parse(await fs.readFile(statePath,'utf8')));if(state.workflowId!==workflowId)throw Error('Workflow identity mismatch');return state;};
|
|
24
|
-
const result=(state,decision,extra={})=>commandResult({workflowId,state,input,...decision,...extra});
|
|
25
|
-
if(command==='status'){
|
|
26
|
-
const state=await read();
|
|
27
|
-
if(!sameCheckout(state.target,target))return result(undefined,{decision:'hold',ruleIds:['cooperative.target']});
|
|
28
|
-
const changes=state.tasks.length?await readChanges({state}):undefined;
|
|
29
|
-
const evaluation=evaluateCooperative({state,request:{command,input},evidence:{target,versions:await cooperativeVersions(),changes}});
|
|
30
|
-
const unresolved=state.plannerLedger?.stages.some(s=>s.pending)||state.unresolved.some(entry=>!entry.resolvedBy)||state.intents.some(i=>(['prepared','unknown','mismatch'].includes(i.status)||i.operation==='plan-amend'&&i.status==='failed')&&!(['check','review'].includes(i.operation)&&i.stale));
|
|
31
|
-
return {...result(state,evaluation.decision==='allow'&&unresolved?{decision:'hold',ruleIds:['cooperative.unresolved']}:evaluation,{persisted:true}),state,support:cooperativeSupport(),...(changes?{changeFingerprints:changes}:{})};
|
|
32
|
-
}
|
|
33
|
-
let lock,plannerLock;
|
|
34
|
-
try{
|
|
35
|
-
lock=await fs.open(statePath+'.lock','wx',0o600);let state=await read();
|
|
36
|
-
const plannerWork=command==='prepare'&&input.operation==='planner-call'||command==='record'&&input.evidence.kind.startsWith('planner-');
|
|
37
|
-
if(plannerWork)plannerLock=await fs.open(path.join(target.gitCommonDir,'arc','planner.lock'),'wx',0o600);
|
|
38
|
-
if(!sameCheckout(state.target,target))return result(state,{decision:'hold',ruleIds:['cooperative.target']});
|
|
39
|
-
const requestFingerprint=fingerprintRequest({command,input});const prior=state.requests.find(r=>r.requestId===input.requestId);
|
|
40
|
-
if(prior){if(prior.requestFingerprint!==requestFingerprint)throw Error('Request fingerprint conflict');return result(state,{decision:'hold',ruleIds:['cooperative.replay']},{replayed:true});}
|
|
41
|
-
if(!['reconcile','result'].includes(command)&&input.expectedRevision!==state.revision)return result(state,{decision:'hold',ruleIds:[['prepare','result'].includes(command)?'cooperative.unsupported':'cooperative.revision']});
|
|
42
|
-
const currentTarget=await validateObservedTarget(cwd,await observe(cwd));
|
|
43
|
-
if(!sameCheckout(state.target,currentTarget))return result(state,{decision:'hold',ruleIds:['cooperative.target']});
|
|
44
|
-
const versions=await cooperativeVersions();
|
|
45
|
-
let git,gitError;
|
|
46
|
-
if(command==='prepare'&&input.operation==='assign-agent'&&input.arguments&&same(currentTarget,state.target)){
|
|
47
|
-
try{git=await readGit({target:currentTarget,documents:input.arguments?.documents??[]});}catch(error){gitError=error.message;}
|
|
48
|
-
}
|
|
49
|
-
const commitIntent=['result','reconcile'].includes(command)?state.intents.find(i=>i.requestId===input.intentId&&i.operation==='commit'):undefined;
|
|
50
|
-
if(command==='prepare'&&['accept','commit'].includes(input.operation)||commitIntent){
|
|
51
|
-
try{git=await readCommitGit({target:currentTarget,...(commitIntent&&input.result?.data?.commit?{commit:input.result.data.commit}:{})});}catch(error){gitError=error.message;}
|
|
52
|
-
}
|
|
53
|
-
const planIntent=state.intents.find(i=>i.operation==='plan-amend'&&i.requestId===((command==='record'&&input.evidence.kind==='note'&&input.evidence.data?.type==='plan-amend-checkpoint')?input.evidence.data.intentId:['result','reconcile'].includes(command)?input.intentId:null));
|
|
54
|
-
const planArguments=command==='prepare'&&input.operation==='plan-amend'?input.arguments:planIntent?.arguments;
|
|
55
|
-
let now;
|
|
56
|
-
if(planArguments){
|
|
57
|
-
try{git=await readPlanAmendGit({target:currentTarget,arguments:planArguments,mapping:command==='reconcile'&&input.result?.status==='succeeded'?input.result.data?.mapping??[]:[]});}catch(error){gitError=error.message;}
|
|
58
|
-
}
|
|
59
|
-
const changes=state.tasks.length?await readChanges({state}):undefined;
|
|
60
|
-
const plannerArtifacts=plannerWork?await readPlannerArtifacts(state,command==='record'&&input.evidence.kind==='planner-evidence'?input.evidence:undefined):undefined;
|
|
61
|
-
const plannerHistory=command==='record'&&input.evidence.kind==='planner-stage'?await readPlannerHistory(state,statePath,input.evidence.data.document?.path):{};
|
|
62
|
-
if(planArguments&&!gitError){try{now=clock();if(!Number.isFinite(now))throw Error('Invalid observation clock');}catch(error){gitError=error.message;}}
|
|
63
|
-
let destinationReview=false;
|
|
64
|
-
let decision=evaluateCooperative({state,request:{command,input},evidence:{target:currentTarget,versions,git,changes,requestFingerprint,plannerArtifacts,now,...plannerHistory}});
|
|
65
|
-
if(command==='record'&&input.evidence.kind==='planner-review'){
|
|
66
|
-
const data=input.evidence.data,stage=state.plannerLedger?.stages.find(s=>s.id===data.stageId),intent=state.targetIntents?.find(i=>i.id===stage?.targetIntentId),transition=state.targetTransitions?.find(t=>t.intentId===intent?.id&&t.targetVersion===state.targetVersion),document=intent?.documents.find(d=>d.kind===stage?.document.kind);
|
|
67
|
-
if(transition&&document){
|
|
68
|
-
let observed;try{observed=await readTargetPreparationEvidence({state,targetIntent:intent,destination:{realpath:state.target.realpath,path:document.path},observe,readChanges});}catch{}
|
|
69
|
-
const valid=input.actor.role==='orchestrator'&&stage.scopeVersion===state.scopeVersion&&same(versions,state.versions)&&same(currentTarget,state.target)&&!stage.pending&&stage.result?.status==='succeeded'&&stage.result.ref===data.resultRef&&stage.result.chatDraft?.complete===true&&data.full===true&&data.complete===true&&observed?.destination?.document?.hash===data.hash&&Array.isArray(data.criteria)&&data.criteria.length===stage.criteria.length&&new Set(data.criteria.map(c=>c.id)).size===stage.criteria.length&&data.criteria.every(c=>stage.criteria.some(s=>s.id===c.id)&&c.status==='resolved'&&typeof c.judgmentRef==='string'&&c.judgmentRef);
|
|
70
|
-
destinationReview=!!valid;
|
|
71
|
-
decision=valid?{decision:'allow',ruleIds:['cooperative.target-preparation']}:{decision:'hold',ruleIds:['cooperative.target-preparation'],reason:'Current destination bytes and complete source-bound review required'};
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
if(command==='record'&&['document','approval'].includes(input.evidence.kind)&&state.targetIntents?.some(intent=>!state.targetTransitions?.some(t=>t.intentId===intent.id)&&intent.documents.some(doc=>doc.kind===input.evidence.data.kind&&(input.evidence.data.path===doc.path||input.evidence.data.path===path.join(intent.sourceTarget.realpath,doc.path)))))decision={decision:'hold',ruleIds:['cooperative.target-preparation'],reason:'Prepared target transition required before document records'};
|
|
75
|
-
if(command==='record'&&input.evidence.kind==='approval'){
|
|
76
|
-
const data=input.evidence.data,intent=state.targetIntents?.find(i=>state.targetTransitions?.some(t=>t.intentId===i.id&&t.targetVersion===state.targetVersion)&&i.documents.some(d=>d.kind===data.kind));
|
|
77
|
-
if(intent){
|
|
78
|
-
const document=intent.documents.find(d=>d.kind===data.kind),firstStage=state.plannerLedger?.stages.find(s=>s.id===intent.firstStageId);
|
|
79
|
-
const stage=firstStage?.document.kind===data.kind?firstStage:state.plannerLedger?.stages.find(s=>s.document.kind===data.kind&&s.document.path===path.join(state.target.realpath,document.path)&&s.targetVersion===state.targetVersion);
|
|
80
|
-
const review=state.records.findLast(r=>r.kind==='planner-review'&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion&&r.data?.stageId===stage?.id&&r.data?.resultRef===stage?.result?.ref&&r.data?.full===true&&r.data?.complete===true&&r.data?.hash===data.contentHash);
|
|
81
|
-
let observed;try{observed=await readTargetPreparationEvidence({state,targetIntent:intent,destination:{realpath:state.target.realpath,path:document.path},observe,readChanges});}catch{}
|
|
82
|
-
if(stage?.scopeVersion!==state.scopeVersion||![document.path,path.join(state.target.realpath,document.path)].includes(data.path)||!review||observed?.destination?.document?.hash!==data.contentHash||!same(currentTarget,state.target)||!same(versions,state.versions)||input.actor.role!=='orchestrator')decision={decision:'hold',ruleIds:['cooperative.target-preparation'],reason:'Current reviewed destination bytes required for approval'};
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
if(command==='record'&&input.evidence.kind==='target-preparation'){
|
|
86
|
-
let observed;
|
|
87
|
-
try{const intent=state.targetIntents?.find(i=>i.id===input.evidence.data.intentId);observed=await readTargetPreparationEvidence({state,targetIntent:intent,destination:input.evidence.data.destination,observe,readChanges});}catch{}
|
|
88
|
-
decision=input.actor.role==='orchestrator'&&same(versions,state.versions)?evaluateTargetPreparation({state,request:input.evidence.data,evidence:{...observed,versions}}):{decision:'hold',ruleIds:['cooperative.target-preparation']};
|
|
89
|
-
}
|
|
90
|
-
if(gitError)decision={decision:'hold',ruleIds:[input.operation==='assign-agent'?'cooperative.documents':'cooperative.git-evidence'],reason:gitError};
|
|
91
|
-
if(command==='prepare'&&decision.decision==='allow'){
|
|
92
|
-
if(decision.proposedTransition?.plannerLedger)state.plannerLedger=decision.proposedTransition.plannerLedger;
|
|
93
|
-
if(decision.proposedTransition?.intent)state.intents.push(decision.proposedTransition.intent);
|
|
94
|
-
if(decision.proposedTransition?.acceptance){state.acceptances.push(decision.proposedTransition.acceptance);state.tasks.find(t=>t.id===input.taskId).status='accepted';}
|
|
95
|
-
}
|
|
96
|
-
if(['reconcile','result'].includes(command)&&input.result){
|
|
97
|
-
if(input.expectedRevision!==state.revision)state.unresolved.push({kind:'stale-result',requestId:input.requestId,intentId:input.intentId,expectedRevision:input.expectedRevision,revision:state.revision+1});
|
|
98
|
-
let intent=state.intents.find(i=>i.requestId===input.intentId);
|
|
99
|
-
decision=EXTERNAL_ACTIONS.includes(intent?.operation)?reconcileCooperativeExternal({state,intent,result:input.result,observations:{target:currentTarget}}):intent?.operation==='commit'?reconcileCooperativeCommit({state,intent,result:input.result,gitEvidence:git}):intent?.operation==='plan-amend'?reconcileCooperativePlanAmend({state,intent,result:input.result,observations:{target:currentTarget,git},now}):['check','review'].includes(intent?.operation)?evaluateCooperativeVerification({state,request:{...input,operation:'verification-result'},evidence:{changes}}):intent?.operation==='assign-agent'?recordCooperativeAssignmentResult({state,intent,result:input.result,observations:{target:currentTarget}}):reconcileCooperativeResult({state,intent,result:input.result,observations:{target:currentTarget}});
|
|
100
|
-
if(['assign-agent','check','review','commit','plan-amend',...EXTERNAL_ACTIONS].includes(intent?.operation)&&!same(versions,state.versions))decision={...decision,decision:'hold',ruleIds:['cooperative.versions']};
|
|
101
|
-
if(input.expectedRevision!==state.revision)decision={...decision,decision:'hold',ruleIds:['cooperative.revision']};
|
|
102
|
-
if((['commit','plan-amend'].includes(intent?.operation)||EXTERNAL_ACTIONS.includes(intent?.operation))&&input.actor.role!=='orchestrator')decision={...decision,decision:'hold',ruleIds:['cooperative.acceptance-actor']};
|
|
103
|
-
if(['check','review'].includes(intent?.operation)&&!same(currentTarget,state.target))decision={...decision,decision:'hold',ruleIds:['cooperative.target']};
|
|
104
|
-
if(intent?.operation==='commit'){
|
|
105
|
-
const verified=decision.proposedTransition;
|
|
106
|
-
// Failed reconciliation records what actually happened without changing target.
|
|
107
|
-
const observation={intentId:input.intentId,revision:state.revision+1,observation:verified?.observation??git??null,source:'local-git',...(gitError?{error:gitError}:{})};
|
|
108
|
-
if(decision.decision==='allow'){
|
|
109
|
-
state=applyCooperativeCommitTransition({state,decision});
|
|
110
|
-
intent=state.intents.find(i=>i.requestId===input.intentId);
|
|
111
|
-
const committedChanges=await readChanges({state}),commit=state.commits.at(-1);commit.postCommitFingerprint=committedChanges.tasks[intent.taskId];
|
|
112
|
-
if(committedChanges.taskSnapshots){
|
|
113
|
-
commit.snapshot=structuredClone(committedChanges.taskSnapshots[intent.taskId]);
|
|
114
|
-
const changedPaths=commit.paths.map(p=>state.target.realpath+'/'+p);
|
|
115
|
-
for(const prior of state.commits.slice(0,-1)){
|
|
116
|
-
const snapshot=prior.snapshotConnections?.at(-1)?.snapshot??prior.snapshot,current=committedChanges.taskSnapshots[prior.taskId];
|
|
117
|
-
if(!snapshot||!current||!changedPaths.some(p=>snapshot.paths.some(base=>within(base,p))))continue;
|
|
118
|
-
const projected=structuredClone(snapshot);for(const key of ['index','rows'])projected[key]=[...snapshot[key].filter(row=>!changedPaths.includes(row.path)),...current[key].filter(row=>changedPaths.includes(row.path))].sort((a,b)=>a.path<b.path?-1:a.path>b.path?1:0);
|
|
119
|
-
prior.snapshotConnections??=[];prior.snapshotConnections.push({commit:commit.commit,requestId:input.requestId,snapshot:projected,fingerprint:fingerprintRequest(projected)});prior.postCommitFingerprint=fingerprintRequest(projected);
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
for(const entry of state.unresolved)if(entry.kind==='target-changed'&&entry.intentId===input.intentId)entry.resolvedBy=input.requestId;
|
|
123
|
-
}
|
|
124
|
-
state.commitObservations??=[];state.commitObservations.push(observation);
|
|
125
|
-
if(decision.decision!=='allow'&&verified?.result?.status==='succeeded')verified.result.status='mismatch';
|
|
126
|
-
}
|
|
127
|
-
if(intent?.operation==='plan-amend'){
|
|
128
|
-
if(command!=='reconcile'||gitError||state.unresolved.some(u=>!u.resolvedBy&&!(u.intentId===input.intentId&&['target-changed','stale-result'].includes(u.kind))))decision={...decision,decision:'hold',ruleIds:['cooperative.plan-amend']};
|
|
129
|
-
if(decision.decision!=='allow'&&decision.proposedTransition?.result?.status==='succeeded')decision.proposedTransition.result.status='mismatch';
|
|
130
|
-
const observed={intentId:input.intentId,revision:state.revision+1,source:'local-git',target:currentTarget,observation:git??null,...(gitError?{error:gitError}:{})};
|
|
131
|
-
if(decision.decision==='allow'){
|
|
132
|
-
const previous=structuredClone(state.target),nextVersion=state.targetVersion+1,a=intent.arguments,transition=decision.proposedTransition;
|
|
133
|
-
state=invalidateAffectedEvidence({state,changedVersions:{targetVersion:nextVersion,documentVersion:a.plan.new.version},affectedTaskIds:a.affectedTaskIds});
|
|
134
|
-
state.targetHistory.push({target:previous,revision:state.revision+1,source:'local-observation',kind:'verified-plan-amend-parent',intentId:input.intentId});state.target=structuredClone(transition.target);state.targetVersion=nextVersion;
|
|
135
|
-
state.planAmendments??=[];state.planAmendments.push({intentId:input.intentId,path:a.plan.path,oldVersion:a.plan.old.version,newVersion:a.plan.new.version,oldHash:a.plan.old.hash,newHash:a.plan.new.hash,oldCommit:a.history.planCommit,newCommit:transition.mapping[0].new,mapping:structuredClone(transition.mapping),approvalRefs:structuredClone(a.approvals),source:'operator-attested',observationSource:'local-git'});
|
|
136
|
-
for(const u of state.unresolved)if(!u.resolvedBy&&u.intentId===input.intentId&&u.kind==='target-changed')u.resolvedBy=input.requestId;
|
|
137
|
-
intent=state.intents.find(i=>i.requestId===input.intentId);
|
|
138
|
-
}
|
|
139
|
-
state.planAmendObservations??=[];state.planAmendObservations.push(observed);
|
|
140
|
-
}
|
|
141
|
-
const verification=decision.proposedTransition;
|
|
142
|
-
if(verification?.check){
|
|
143
|
-
if(decision.decision!=='allow'&&verification.check.status==='passed'){verification.check.status='unverified';verification.check.stale=true;verification.findings=[];verification.result.status='mismatch';}
|
|
144
|
-
state.checks.push(verification.check);for(const finding of verification.findings){const index=state.findings.findIndex(f=>f.id===finding.id);if(index<0)state.findings.push(finding);else state.findings[index]=finding;}
|
|
145
|
-
}
|
|
146
|
-
if(intent?.operation==='assign-agent'&&decision.decision!=='allow'&&decision.proposedTransition?.result&&['succeeded','failed'].includes(decision.proposedTransition.result.status))decision.proposedTransition.result.status='mismatch';
|
|
147
|
-
if(EXTERNAL_ACTIONS.includes(intent?.operation)&&decision.decision!=='allow'&&decision.proposedTransition?.result&&(decision.proposedTransition.result.status==='succeeded'||decision.ruleIds[0]!=='cooperative.external'))decision.proposedTransition.result.status='mismatch';
|
|
148
|
-
if(decision.decision==='allow'&&input.expectedRevision===state.revision&&['succeeded','failed','cancelled'].includes(decision.proposedTransition?.result?.status))for(const entry of state.unresolved)if(entry.kind==='stale-result'&&entry.intentId===input.intentId&&!entry.resolvedBy){entry.resolvedBy=input.requestId;entry.resolutionEvidence={intentId:input.intentId,resultRef:input.result.messageRef,revision:state.revision};}
|
|
149
|
-
const actualResult=decision.proposedTransition?.result??input.result;
|
|
150
|
-
// Preserve actual statements even when runtime/HEAD changed, without rebinding target.
|
|
151
|
-
if(!same(currentTarget,state.target)){state.targetHistory.push({target:currentTarget,revision:state.revision+1,source:'local-observation'});state.unresolved.push({kind:'target-changed',...(['commit','plan-amend'].includes(intent?.operation)?{intentId:input.intentId}:{}),revision:state.revision+1});}
|
|
152
|
-
if(!same(versions,state.versions))state.unresolved.push({kind:'versions-changed',revision:state.revision+1});
|
|
153
|
-
state.results.push({...actualResult,requestId:input.intentId,recordRequestId:input.requestId,actor:input.actor,source:'operator-attested'});
|
|
154
|
-
if(intent&&(['assign-agent','check','review','commit','plan-amend',...EXTERNAL_ACTIONS].includes(intent.operation)?decision.proposedTransition?.result&&['prepared','unknown','mismatch'].includes(intent.status):true)){
|
|
155
|
-
intent.status=actualResult.status;
|
|
156
|
-
if(decision.decision==='allow'&&actualResult.status==='succeeded'&&intent.operation==='assign-agent')state.assignments.push({intentId:intent.requestId,taskId:intent.taskId,agentId:actualResult.data.agentId,status:'active',source:'operator-attested',identityVerified:false});
|
|
157
|
-
}
|
|
158
|
-
else state.unresolved.push({kind:'unmatched-result',requestId:input.intentId,revision:state.revision+1});
|
|
159
|
-
}else if(command==='record'&&input.evidence.kind.startsWith('planner-')){
|
|
160
|
-
if(destinationReview||decision.proposedTransition?.plannerLedger&&(decision.decision==='allow'||decision.proposedTransition.recordUncertainty)){
|
|
161
|
-
if(!destinationReview)state.plannerLedger=decision.proposedTransition.plannerLedger;
|
|
162
|
-
state.records.push({...input.evidence,actor:input.actor,source:'operator-attested',requestId:input.requestId,revision:state.revision+1,scopeVersion:state.scopeVersion,targetVersion:state.targetVersion});
|
|
163
|
-
if(input.evidence.kind==='planner-result'){
|
|
164
|
-
const intent=state.intents.find(i=>i.operation==='planner-call'&&i.requestId===input.evidence.data.callRequestId);
|
|
165
|
-
if(intent)intent.status=input.evidence.data.status;
|
|
166
|
-
}
|
|
167
|
-
}
|
|
168
|
-
}else if(command==='record'&&decision.decision==='allow'){
|
|
169
|
-
if(input.evidence.kind==='target-preparation'&&input.evidence.data.type==='transition')state=applyCooperativeTargetTransition({state,decision,messageRef:input.evidence.messageRef});
|
|
170
|
-
if(input.evidence.kind==='target-preparation'&&decision.proposedTransition?.intent){state.targetIntents??=[];state.targetIntents.push(decision.proposedTransition.intent);}
|
|
171
|
-
if(input.evidence.kind==='target-preparation'&&decision.proposedTransition?.checkpoint){state.targetCheckpoints??=[];state.targetCheckpoints.push({...decision.proposedTransition.checkpoint,messageRef:input.evidence.messageRef,source:'operator-attested'});}
|
|
172
|
-
if(input.evidence.kind==='target-preparation'&&decision.proposedTransition?.destination){state.targetDocuments??=[];state.targetDocuments.push({...decision.proposedTransition.destination,messageRef:input.evidence.messageRef});}
|
|
173
|
-
const entry={...input.evidence,actor:input.actor,source:'operator-attested',requestId:input.requestId,revision:state.revision+1,scopeVersion:state.scopeVersion,targetVersion:state.targetVersion};
|
|
174
|
-
if(entry.kind==='note'&&decision.proposedTransition?.checkpoint){const intent=state.intents.find(i=>i.operation==='plan-amend'&&i.requestId===decision.proposedTransition.checkpoint.intentId);if(!intent)throw Error('Checkpoint intent unavailable');intent.checkpoint=structuredClone(decision.proposedTransition.checkpoint);}
|
|
175
|
-
if(entry.kind==='scope'){
|
|
176
|
-
if(!Array.isArray(entry.data.paths)||entry.data.paths.some(p=>!absolute(p)||!within(state.target.realpath,p)))throw Error('Scope paths must stay inside workspace');
|
|
177
|
-
state=invalidateAffectedEvidence({state,changedVersions:{scopeVersion:state.scopeVersion+1},affectedTaskIds:entry.data.affectedTaskIds});entry.scopeVersion=state.scopeVersion;state.scopes.push(entry);
|
|
178
|
-
state.unresolved.push({kind:'scope-changed',revision:state.revision+1,scopeVersion:state.scopeVersion,affectedTaskIds:state.tasks.filter(t=>t.invalidatedBy?.scopeVersion===state.scopeVersion).map(t=>t.id)});
|
|
179
|
-
}
|
|
180
|
-
if(['document','approval'].includes(entry.kind)&&state.tasks.length)state=invalidateAffectedEvidence({state,changedVersions:{[entry.kind+'Version']:entry.revision},affectedTaskIds:entry.data.affectedTaskIds});
|
|
181
|
-
if(decision.proposedTransition?.task){const task=decision.proposedTransition.task,index=state.tasks.findIndex(t=>t.id===task.id);if(index>=0){state=invalidateAffectedEvidence({state,changedVersions:{taskVersion:entry.revision},affectedTaskIds:[task.id]});state.tasks[index]=task;}else state.tasks.push(task);}
|
|
182
|
-
if(decision.proposedTransition?.finding){const finding=decision.proposedTransition.finding,index=state.findings.findIndex(f=>f.id===finding.id);if(index<0)state.findings.push(finding);else state.findings[index]=finding;}
|
|
183
|
-
state.records.push(entry);
|
|
184
|
-
if(decision.proposedTransition?.task)for(const marker of state.unresolved.filter(u=>u.kind==='scope-changed'&&!u.resolvedBy&&u.scopeVersion<=state.scopeVersion)){
|
|
185
|
-
const ids=marker.affectedTaskIds?.length?marker.affectedTaskIds:state.tasks.map(t=>t.id),proof=[];let ready=ids.length>0;
|
|
186
|
-
for(const id of ids){
|
|
187
|
-
const task=state.tasks.find(t=>t.id===id),approval=state.records.findLast(r=>r.kind==='approval'&&(!r.data.affectedTaskIds||r.data.affectedTaskIds.includes(id)));
|
|
188
|
-
if(!task||task.invalidated||task.scopeVersion!==state.scopeVersion||!approval||approval.revision<=marker.revision||approval.scopeVersion!==state.scopeVersion||approval.targetVersion!==state.targetVersion||task.approvalRef!==approval.messageRef||task.approvalVersion!==approval.data.approvalVersion||task.documentVersion!==approval.data.documentVersion){ready=false;break;}
|
|
189
|
-
const documents=approval.data.documents;
|
|
190
|
-
if(!Array.isArray(documents)||documents.length!==2||!['spec','plan'].every(kind=>documents.some(d=>d.kind===kind))){ready=false;break;}
|
|
191
|
-
try{const observed=await readGit({target:currentTarget,documents});if(!same(observed.target,currentTarget)||!observed.docsCommit||!same(observed.docsCommit.documents,documents)||documents.some(d=>d.commit!==observed.docsCommit.commit||d.approvalRef!==approval.messageRef||!observed.documents?.some(o=>o.path===d.path&&o.gitPath===d.gitPath&&o.observedHash===d.contentHash&&o.currentHash===d.contentHash))){ready=false;break;}}
|
|
192
|
-
catch{ready=false;break;}
|
|
193
|
-
const scope=state.scopes.find(s=>s.scopeVersion===state.scopeVersion);if(!scope||task.paths.some(p=>!scope.data.paths.some(base=>within(base,p)))){ready=false;break;}
|
|
194
|
-
proof.push({taskId:id,taskRef:task.messageRef,approvalRef:approval.messageRef,documents:structuredClone(documents)});
|
|
195
|
-
}
|
|
196
|
-
if(ready){marker.resolvedBy=input.requestId;marker.resolutionEvidence={taskIds:ids,contracts:proof,scopeVersion:state.scopeVersion};}
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
// The observed identifiers contain no URLs and do not verify remote state.
|
|
200
|
-
if(planArguments&&Array.isArray(git?.configuredRemotes)&&git.configuredRemotes.every(r=>r&&typeof r.name==='string'&&/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(r.name)&&/^sha256:[a-f0-9]{64}$/.test(r.identity??'')))decision={...decision,observedRemoteIdentities:{source:'local-git',remotes:git.configuredRemotes.map(r=>({name:r.name,identity:r.identity}))}};
|
|
201
|
-
// A held request is durable audit, never an executable intent.
|
|
202
|
-
state.revision++;
|
|
203
|
-
const output=result(state,decision,{persisted:true});
|
|
204
|
-
state.requests.push({requestId:input.requestId,requestFingerprint,request:structuredClone({command,input}),decision:output});
|
|
205
|
-
state.audit.push({command,requestId:input.requestId,revision:state.revision,decision:output.decision,ruleIds:output.ruleIds,source:'operator-attested',actor:input.actor,...(input.intentId?{intentId:input.intentId,resolution:state.results.at(-1)?.status}:{}),...(input.operation?{operation:input.operation}:{})});
|
|
206
|
-
validateCooperativeState(state);await inspectPath(statePath);await saveDurableState({statePath,state,storage});return output;
|
|
207
|
-
}finally{if(plannerLock){await plannerLock.close();await fs.unlink(path.join(target.gitCommonDir,'arc','planner.lock'));}if(lock){await lock.close();await fs.unlink(statePath+'.lock');}}
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
async function readPlannerArtifacts(state,newRecord){
|
|
211
|
-
const entries=(state.plannerLedger?.stages??[]).flatMap(s=>(s.artifacts??[]).map(a=>({...a,stageId:s.id})));
|
|
212
|
-
if(newRecord)entries.push({...newRecord.data,ref:newRecord.messageRef});
|
|
213
|
-
return Promise.all(entries.map(async artifact=>{
|
|
214
|
-
try{
|
|
215
|
-
if(!absolute(artifact.path)||!within(state.target.realpath,artifact.path))throw Error('Artifact path escapes workspace');
|
|
216
|
-
await inspectPath(artifact.path);const handle=await fs.open(artifact.path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);let bytes;
|
|
217
|
-
try{const before=await handle.stat();if(!before.isFile())throw Error('Artifact must be a regular file');bytes=await handle.readFile();const after=await handle.stat(),named=await fs.lstat(artifact.path);if(before.dev!==after.dev||before.ino!==after.ino||before.size!==after.size||before.mtimeMs!==after.mtimeMs||after.dev!==named.dev||after.ino!==named.ino)throw Error('Artifact changed while reading');}finally{await handle.close();}
|
|
218
|
-
await inspectPath(artifact.path);if(!within(state.target.realpath,await fs.realpath(artifact.path)))throw Error('Artifact realpath escapes workspace');
|
|
219
|
-
const hash='sha256:'+createHash('sha256').update(bytes).digest('hex');
|
|
220
|
-
if(artifact.hash&&artifact.hash!==hash||artifact.contentHash&&artifact.contentHash!==hash)throw Error('Artifact hash mismatch');
|
|
221
|
-
return {...artifact,hash,verification:{status:'verified',source:'local-bytes'}};
|
|
222
|
-
}catch(error){return {...artifact,verification:{status:'unverified',source:'local-bytes'},error:error.message};}
|
|
223
|
-
}));
|
|
224
|
-
}
|
|
225
|
-
async function readPlannerHistory(state,statePath,documentPath){
|
|
226
|
-
const plannerHistory=[];
|
|
227
|
-
try{
|
|
228
|
-
const root=path.dirname(path.dirname(statePath));await inspectPath(root,{directory:true});
|
|
229
|
-
for(const entry of await fs.readdir(root,{withFileTypes:true})){
|
|
230
|
-
if(entry.name===state.workflowId)continue;
|
|
231
|
-
if(!entry.isDirectory()||entry.isSymbolicLink())throw Error('Unsafe workflow history path');
|
|
232
|
-
const filename=path.join(root,entry.name,'state.json');await inspectPath(filename);const other=validateCooperativeState(JSON.parse(await fs.readFile(filename,'utf8')));
|
|
233
|
-
if(!sameCheckout(state.target,other.target))continue;
|
|
234
|
-
if(!other.plannerLedger&&other.documents.some(d=>d.path===documentPath||d.data?.path===documentPath))throw Error('Existing document history has no Planner ledger');
|
|
235
|
-
for(const stage of other.plannerLedger?.stages??[])plannerHistory.push({workflowId:other.workflowId,stage});
|
|
236
|
-
}
|
|
237
|
-
return {plannerHistory};
|
|
238
|
-
}catch(error){return {plannerHistory,plannerHistoryError:error.message};}
|
|
239
|
-
}
|