@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,98 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @typedef {object} WorkflowState
|
|
3
|
-
* @property {1} schemaVersion
|
|
4
|
-
* @property {string} workflowId
|
|
5
|
-
* @property {number} revision
|
|
6
|
-
* @property {object} versions
|
|
7
|
-
* @property {object} target
|
|
8
|
-
* @property {Array<object>} tasks
|
|
9
|
-
* @property {Array<object>} assignments
|
|
10
|
-
* @property {Array<object>} identities
|
|
11
|
-
* @property {Array<object>} leases
|
|
12
|
-
* @typedef {object} NormalizedRequest
|
|
13
|
-
* @property {string} requestId
|
|
14
|
-
* @property {'codex'|'claude'} platform
|
|
15
|
-
* @property {string} operation
|
|
16
|
-
* @property {string} actorRef
|
|
17
|
-
* @property {string} taskId
|
|
18
|
-
* @property {string} cwd
|
|
19
|
-
* @property {string} toolName
|
|
20
|
-
* @property {object} arguments
|
|
21
|
-
* @property {string[]} paths
|
|
22
|
-
* @property {object} descriptor
|
|
23
|
-
* @typedef {object} EvidenceBundle
|
|
24
|
-
* @property {Array<object>} provenance Provider-observed references, never raw tool arguments.
|
|
25
|
-
* @property {Array<object>} [facts] Provider-confirmed facts tied to state and source references.
|
|
26
|
-
*/
|
|
27
|
-
import path from 'node:path';
|
|
28
|
-
import {ROLES, OPERATIONS} from './operations.mjs';
|
|
29
|
-
const fail = message => {throw new Error(`Runtime schema: ${message}`);};
|
|
30
|
-
export const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
31
|
-
export const text = value => typeof value === 'string' && value.length > 0;
|
|
32
|
-
const hash = value => typeof value === 'string' && /^sha256:[a-f0-9]{64}$/.test(value);
|
|
33
|
-
const strings = value => Array.isArray(value) && value.every(text) && new Set(value).size === value.length;
|
|
34
|
-
const absolute = value => text(value) && path.isAbsolute(value) && path.normalize(value) === value;
|
|
35
|
-
const unique = (items,key) => items.every(x=>object(x)&&text(x[key])) && new Set(items.map(x=>x[key])).size===items.length;
|
|
36
|
-
function approval(a){return object(a)&&text(a.id)&&['user-message','human-confirmation'].includes(a.source)&&text(a.messageRef)&&hash(a.contentHash)&&object(a.scope)&&text(a.scope.taskId)&&absolute(a.scope.target)&&strings(a.scope.operations)&&a.scope.operations.every(op=>OPERATIONS.includes(op))&&strings(a.scope.paths)&&a.scope.paths.every(absolute);}
|
|
37
|
-
/** Validate stored workflow data. Observed provenance must still be checked by evaluate. */
|
|
38
|
-
export function validateWorkflowState(s){
|
|
39
|
-
if(object(s)&&s.workflowKind!==undefined)fail('provider state cannot use cooperative contract');
|
|
40
|
-
if(!object(s)||s.schemaVersion!==1||!text(s.workflowId)||!Number.isSafeInteger(s.revision)||s.revision<0)fail('version or identity');
|
|
41
|
-
if(!object(s.versions)||['policy','runtime','adapter','policyHash','runtimeHash','adapterHash'].some(k=>!text(s.versions[k])))fail('versions');
|
|
42
|
-
if(['policyHash','runtimeHash','adapterHash'].some(k=>!hash(s.versions[k])))fail('hash algorithm');
|
|
43
|
-
if(!object(s.target)||!absolute(s.target.realpath)||['repository','worktree','baseHead','head'].some(k=>!text(s.target[k]))||!(s.target.branch===null||text(s.target.branch)))fail('target');
|
|
44
|
-
if(!['plan','small-task','no-plan'].includes(s.mode))fail('mode');
|
|
45
|
-
for(const k of ['documents','approvals','tasks','assignments','identities','leases','checks','findings','acceptances','commits','audit','capabilities','requests'])if(!Array.isArray(s[k]))fail(k);
|
|
46
|
-
if(!unique(s.tasks,'id')||s.tasks.some(t=>!['pending','assigned','rework','verification','accepted','committed'].includes(t.status)||!strings(t.paths)||t.paths.some(p=>!absolute(p))||!strings(t.dependencies)||!text(t.baseCommit)||!strings(t.criteria)||!strings(t.requiredChecks)))fail('tasks');
|
|
47
|
-
if(!unique(s.approvals,'id')||s.approvals.some(a=>!approval(a)))fail('approval provenance');
|
|
48
|
-
if(!unique(s.identities,'actorRef')||s.identities.some(i=>!ROLES.includes(i.role)||!text(i.taskId)||!text(i.observationRef)))fail('identity');
|
|
49
|
-
if(!unique(s.leases,'actorRef')||s.leases.some(l=>!text(l.taskId)||!['active','suspended','retired'].includes(l.status)))fail('lease');
|
|
50
|
-
if(s.assignments.some(a=>!object(a)||!((a.status==='pending'&&a.actorRef===null&&text(a.assignmentId)&&text(a.correlationRef)&&text(a.requestId)&&text(a.requestedBy)&&['codex','claude'].includes(a.platform))||text(a.actorRef))||!text(a.taskId)||!ROLES.includes(a.role)||!strings(a.paths)||a.paths.some(p=>!absolute(p))||!strings(a.operations)||a.operations.some(op=>!OPERATIONS.includes(op))||!text(a.approvalRef)))fail('assignment');
|
|
51
|
-
for(const a of s.assignments){
|
|
52
|
-
if(a.checks!==undefined&&(!Array.isArray(a.checks)||a.checks.some(c=>!object(c)||!absolute(c.executable)||!Array.isArray(c.args)||!c.args.every(x=>typeof x==='string')||!absolute(c.cwd)||!object(c.env)||!strings(c.outputs)||c.outputs.some(p=>!absolute(p)))))fail('check descriptor');
|
|
53
|
-
if(a.temporary!==undefined&&(!object(a.temporary)||!strings(a.temporary.paths)||a.temporary.paths.some(p=>!absolute(p))||!text(a.temporary.cleanupOwner)||!Number.isFinite(Date.parse(a.temporary.expiresAt))))fail('temporary assignment');
|
|
54
|
-
}
|
|
55
|
-
if(new Set(s.assignments.map(a=>a.status==='pending'?'pending:'+a.assignmentId:'actor:'+a.actorRef)).size!==s.assignments.length)fail('ambiguous assignment');
|
|
56
|
-
if(s.documents.some(d=>!object(d)||!['spec','plan'].includes(d.kind)||!absolute(d.path)||!text(d.gitPath)||path.isAbsolute(d.gitPath)||d.gitPath.split('/').includes('..')||!hash(d.contentHash)||!text(d.approvalRef)))fail('document');
|
|
57
|
-
if(s.checks.some(c=>!object(c)||!text(c.id)||!text(c.taskId)||!['passed','failed','pending','unknown'].includes(c.status)||!text(c.fingerprint)||!text(c.actorRef)||!text(c.resultRef)))fail('checks');
|
|
58
|
-
if(s.findings.some(f=>!object(f)||!text(f.id)||!text(f.taskId)))fail('findings');
|
|
59
|
-
if(s.acceptances.some(a=>!object(a)||!text(a.taskId)||!text(a.actorRef)||!text(a.fingerprint)||!strings(a.criteria)||!strings(a.checkIds)||!strings(a.findingIds)))fail('acceptances');
|
|
60
|
-
if(s.commits.some(c=>!object(c)||!text(c.purpose)||!text(c.taskId)||!text(c.expectedParent)||!text(c.expectedTree)))fail('commits');
|
|
61
|
-
if(s.requests.some(r=>!object(r)||!text(r.requestId)||!hash(r.requestFingerprint)||!object(r.decision))||new Set(s.requests.map(r=>r.requestId)).size!==s.requests.length)fail('request replay');
|
|
62
|
-
if(s.plannerLedger!==undefined){validatePlannerLedger(s.plannerLedger);if(s.plannerLedger.stages.some(stage=>stage.workflowId!==s.workflowId))fail('Planner workflow binding');}
|
|
63
|
-
return s;
|
|
64
|
-
}
|
|
65
|
-
export function validateRequest(r){
|
|
66
|
-
if(!object(r)||['requestId','actorRef','taskId','toolName'].some(k=>!text(r[k]))||!['codex','claude'].includes(r.platform)||!OPERATIONS.includes(r.operation)||!absolute(r.cwd)||!object(r.arguments)||!object(r.descriptor)||!strings(r.paths)||r.paths.some(p=>!absolute(p)))fail('request');
|
|
67
|
-
return r;
|
|
68
|
-
}
|
|
69
|
-
export function validateEvidence(e){
|
|
70
|
-
if(!object(e)||!Array.isArray(e.provenance)||!unique(e.provenance,'id'))fail('evidence');
|
|
71
|
-
if(e.resolvedPaths!==undefined&&(!Array.isArray(e.resolvedPaths)||e.resolvedPaths.some(p=>!object(p)||!absolute(p.path)||!absolute(p.realpath))))fail('resolved paths');
|
|
72
|
-
if(e.facts!==undefined&&(!Array.isArray(e.facts)||e.facts.some(f=>!object(f)||!text(f.kind)||!text(f.workflowId)||!Number.isSafeInteger(f.revision)||!object(f.target)||!hash(f.policyHash)||!text(f.sourceRef)||!object(f.data))))fail('facts');
|
|
73
|
-
for(const p of e.provenance){
|
|
74
|
-
if(!['platform-event','user-message','human-confirmation'].includes(p.source))fail('provenance source');
|
|
75
|
-
if(p.source==='platform-event'&&(!text(p.eventRef)||!text(p.actorRef)||!['codex','claude'].includes(p.platform)))fail('platform provenance');
|
|
76
|
-
if(p.source!=='platform-event'&&(!text(p.messageRef)||!hash(p.contentHash)))fail('approval provenance');
|
|
77
|
-
if(!object(p.verification)||p.verification.status!=='verified'||!text(p.verification.verifierRef)||!text(p.verification.sourceRef))fail('unverified provenance');
|
|
78
|
-
}
|
|
79
|
-
return e;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
/** Shared stage shape. Missing ledgers remain valid legacy state, never fresh history. */
|
|
83
|
-
export function validatePlannerStage(stage){
|
|
84
|
-
if(stage?.ready!==undefined&&typeof stage.ready!=='boolean')fail('Planner readiness type');
|
|
85
|
-
if(!object(stage)||!text(stage.id)||!text(stage.workflowId)||!object(stage.document)||!absolute(stage.document.path)||!['spec','plan'].includes(stage.document.kind)||!text(stage.document.phase)||!text(stage.approvalRef)||!Number.isSafeInteger(stage.inputVersion)||stage.inputVersion<1||!Number.isSafeInteger(stage.scopeVersion)||stage.scopeVersion<0||!Number.isSafeInteger(stage.criteriaVersion)||stage.criteriaVersion<1)fail('Planner stage identity');
|
|
86
|
-
if(!Array.isArray(stage.criteria)||!stage.criteria.length||!unique(stage.criteria,'id')||stage.criteria.some(c=>!['open','resolved'].includes(c.status)||!text(c.judgmentRef)))fail('Planner criteria');
|
|
87
|
-
if(!Array.isArray(stage.calls)||!unique(stage.calls,'requestId')||stage.calls.some(c=>!['initial','correction','further'].includes(c.kind)||!['reserved','unknown','succeeded','failed'].includes(c.status)||!Array.isArray(c.evidenceHashes)||c.evidenceHashes.some(h=>!hash(h)))||stage.calls.filter(c=>c.kind==='initial').length>1||stage.calls.filter(c=>c.kind==='correction').length>1)fail('Planner call history');
|
|
88
|
-
if(stage.pending!==null&&(!text(stage.pending)||!stage.calls.some(c=>c.requestId===stage.pending&&['reserved','unknown'].includes(c.status))))fail('Planner pending call');
|
|
89
|
-
const pending=stage.calls.filter(c=>['reserved','unknown'].includes(c.status));if(pending.length>1||pending.length!==(stage.pending===null?0:1))fail('Planner orphan reservation');
|
|
90
|
-
if(stage.artifacts!==undefined&&(!Array.isArray(stage.artifacts)||!unique(stage.artifacts,'ref')||stage.artifacts.some(a=>!absolute(a.path)||!hash(a.hash)||!Array.isArray(a.criterionIds)||!['draft','self-review','input','progress','finding'].includes(a.purpose)||a.verification?.status!=='verified'||a.verification.source!=='local-bytes'||a.semantic&&a.semantic.source!=='operator-attested')))fail('Planner artifact evidence');
|
|
91
|
-
if(stage.ready===true&&(stage.pending!==null||stage.criteria.some(c=>c.status!=='resolved')||stage.result?.status!=='succeeded'||stage.review?.complete!==true||stage.review?.full!==true||stage.review?.resultRef!==stage.result.ref||!stage.artifacts?.some(a=>a.ref===stage.result.artifactRef&&a.purpose==='draft')||!stage.artifacts?.some(a=>a.ref===stage.result.selfReviewRef&&a.purpose==='self-review')))fail('Planner incomplete readiness');
|
|
92
|
-
return stage;
|
|
93
|
-
}
|
|
94
|
-
export function validatePlannerLedger(ledger){
|
|
95
|
-
if(!object(ledger)||ledger.version!==1||!Array.isArray(ledger.stages)||!unique(ledger.stages,'id'))fail('Planner ledger');
|
|
96
|
-
for(const stage of ledger.stages)validatePlannerStage(stage);
|
|
97
|
-
return ledger;
|
|
98
|
-
}
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs/promises';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import {spawnSync} from 'node:child_process';
|
|
4
|
-
export const absolute=value=>typeof value==='string'&&path.isAbsolute(value)&&path.normalize(value)===value;
|
|
5
|
-
export const within=(base,file)=>absolute(file)&&!path.relative(base,file).split(path.sep).includes('..')&&!path.isAbsolute(path.relative(base,file));
|
|
6
|
-
/** Inspect every component, including ancestors outside the ARC namespace. */
|
|
7
|
-
export async function inspectPath(filename,{missing=false,directory=false}={}){
|
|
8
|
-
if(!absolute(filename))throw Error('Unsafe absolute path');
|
|
9
|
-
let cursor=path.parse(filename).root;
|
|
10
|
-
const parts=filename.slice(cursor.length).split(path.sep).filter(Boolean);
|
|
11
|
-
for(let i=0;i<parts.length;i++){
|
|
12
|
-
cursor=path.join(cursor,parts[i]);let stat;
|
|
13
|
-
try{stat=await fs.lstat(cursor);}catch(error){if(missing&&error.code==='ENOENT')return;throw error;}
|
|
14
|
-
if(stat.isSymbolicLink())throw Error('Unsafe symlink path');
|
|
15
|
-
if(i<parts.length-1||directory){if(!stat.isDirectory())throw Error('Unsafe directory type');}
|
|
16
|
-
else if(!stat.isFile())throw Error('State must be a regular file');
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
export function validateWorkflowId(id){if(typeof id!=='string'||!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(id))throw Error('Invalid workflow ID');return id;}
|
|
20
|
-
/** Shell-free, read-only observation; inherited Git target/config overrides are removed. */
|
|
21
|
-
export async function observeCooperativeTarget(cwd){
|
|
22
|
-
if(!absolute(cwd))throw Error('Absolute workspace required');await inspectPath(cwd,{directory:true});
|
|
23
|
-
const env=Object.fromEntries(Object.entries(process.env).filter(([key])=>!key.toUpperCase().startsWith('GIT_')));
|
|
24
|
-
Object.assign(env,{GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:process.platform==='win32'?'NUL':'/dev/null',GIT_OPTIONAL_LOCKS:'0',GIT_NO_REPLACE_OBJECTS:'1',GIT_NO_LAZY_FETCH:'1',GIT_TERMINAL_PROMPT:'0'});
|
|
25
|
-
const query=(args,detached=false)=>{const r=spawnSync('git',['--no-pager','-c','core.fsmonitor=false',...args],{cwd,env,encoding:'utf8',timeout:10000,maxBuffer:1024*1024});if(detached&&r.status===1&&!r.error)return null;if(r.status!==0||r.error||!r.stdout.endsWith('\n')||r.stdout.slice(0,-1).includes('\n'))throw Error('Git target observation failed');return r.stdout.slice(0,-1);};
|
|
26
|
-
const target={realpath:query(['rev-parse','--show-toplevel']),gitCommonDir:query(['rev-parse','--path-format=absolute','--git-common-dir']),gitDir:query(['rev-parse','--absolute-git-dir']),head:query(['rev-parse','HEAD']),branch:query(['symbolic-ref','--quiet','--short','HEAD'],true)};
|
|
27
|
-
await validateObservedTarget(cwd,target);return target;
|
|
28
|
-
}
|
|
29
|
-
export async function validateObservedTarget(cwd,target){
|
|
30
|
-
if(!absolute(cwd)||!target||target.realpath!==cwd||!absolute(target.gitCommonDir)||!absolute(target.gitDir)||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(target.head)||!(target.branch===null||typeof target.branch==='string'&&target.branch))throw Error('Invalid observed target');
|
|
31
|
-
await inspectPath(cwd,{directory:true});await inspectPath(target.gitCommonDir,{directory:true});
|
|
32
|
-
return target;
|
|
33
|
-
}
|
|
34
|
-
export async function workflowStatePath(target,workflowId){
|
|
35
|
-
validateWorkflowId(workflowId);const statePath=path.join(target.gitCommonDir,'arc','workflows',workflowId,'state.json');await inspectPath(statePath,{missing:true});return statePath;
|
|
36
|
-
}
|
|
@@ -1,94 +0,0 @@
|
|
|
1
|
-
import {verifiedCooperativeReconciliation} from './acceptance.mjs';
|
|
2
|
-
import {verifiedReconciliation} from './gate.mjs';
|
|
3
|
-
import {applyTargetPreparationTransition} from './target-preparation.mjs';
|
|
4
|
-
import fs from 'node:fs/promises';
|
|
5
|
-
import path from 'node:path';
|
|
6
|
-
import crypto from 'node:crypto';
|
|
7
|
-
import {validateWorkflowState, validateRequest} from './schema.mjs';
|
|
8
|
-
/** Hash complete normalized decision inputs at the trusted caller boundary, never a tool-supplied hash. */
|
|
9
|
-
export function fingerprintRequest(input){
|
|
10
|
-
const canonical=value=>{
|
|
11
|
-
if(value===null||typeof value==='string'||typeof value==='boolean')return value;
|
|
12
|
-
if(typeof value==='number'&&Number.isFinite(value))return value;
|
|
13
|
-
if(Array.isArray(value))return value.map(canonical);
|
|
14
|
-
if(value&&Object.getPrototypeOf(value)===Object.prototype)return Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])]));
|
|
15
|
-
throw Error('Request fingerprint requires complete JSON inputs');
|
|
16
|
-
};
|
|
17
|
-
return 'sha256:'+crypto.createHash('sha256').update(JSON.stringify(canonical(input))).digest('hex');
|
|
18
|
-
}
|
|
19
|
-
/** A failed/interrupted transaction retains the original state. Locks are never silently recovered. */
|
|
20
|
-
export async function transactWorkflow({statePath,expectedRevision,requestId,request,requestFingerprint,decide}){
|
|
21
|
-
if(!path.isAbsolute(statePath)||!Number.isSafeInteger(expectedRevision)||expectedRevision<0||typeof requestId!=='string'||!requestId||typeof decide!=='function')throw Error('Invalid transaction');
|
|
22
|
-
if(typeof requestFingerprint!=='string'||!/^sha256:[a-f0-9]{64}$/.test(requestFingerprint))throw Error('Valid request fingerprint required');
|
|
23
|
-
const normalized=validateRequest(structuredClone(request));
|
|
24
|
-
if(normalized.requestId!==requestId||fingerprintRequest(normalized)!==requestFingerprint)throw Error('Request fingerprint conflict with normalized input');
|
|
25
|
-
const parent=await fs.realpath(path.dirname(statePath));statePath=path.join(parent,path.basename(statePath));
|
|
26
|
-
const lockPath=statePath+'.lock';let lock;let temporary;
|
|
27
|
-
try{
|
|
28
|
-
lock=await fs.open(lockPath,'wx',0o600);
|
|
29
|
-
const stat=await fs.lstat(statePath);if(!stat.isFile()||stat.isSymbolicLink())throw Error('State must be regular file');
|
|
30
|
-
const state=validateWorkflowState(JSON.parse(await fs.readFile(statePath,'utf8')));
|
|
31
|
-
const prior=state.requests.find(r=>r.requestId===requestId);
|
|
32
|
-
let decision;
|
|
33
|
-
if(prior){
|
|
34
|
-
if(prior.requestFingerprint!==requestFingerprint)throw Error('Request fingerprint conflict');
|
|
35
|
-
const current=await decide(structuredClone(state));
|
|
36
|
-
if(!current||!['allow','deny','hold'].includes(current.decision))throw Error('Invalid replay decision');
|
|
37
|
-
const completing=normalized.operation==='commit'&&prior.decision.decision==='allow'&&prior.decision.expectedCommit&¤t.decision==='allow'&¤t.proposedTransition&&verifiedReconciliation(current,state,current.proposedTransition,prior.decision.expectedCommit)&&!state.commits.some(c=>c.requestId===requestId);
|
|
38
|
-
if(completing)decision=current;
|
|
39
|
-
else{
|
|
40
|
-
const replay={...current,proposedTransition:null};
|
|
41
|
-
if(current.decision==='allow'&&(current.proposedTransition||!['read','draft','review'].includes(normalized.operation))){replay.decision='hold';replay.reason='Replay cannot authorize repeated state or external effects';}
|
|
42
|
-
return {state,decision:replay,replayed:true};
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
if(state.revision!==expectedRevision)throw Error('Stale revision');
|
|
46
|
-
decision??=await decide(structuredClone(state));
|
|
47
|
-
if(!decision||!['allow','deny','hold'].includes(decision.decision))throw Error('Invalid decision');
|
|
48
|
-
const next=decision.proposedTransition?structuredClone(decision.proposedTransition):structuredClone(state);
|
|
49
|
-
if(decision.decision!=='allow'&&decision.proposedTransition)throw Error('Denied transition');
|
|
50
|
-
if(next.workflowId!==state.workflowId||(JSON.stringify(next.target)!==JSON.stringify(state.target)&&!verifiedReconciliation(decision,state,next)))throw Error('Transaction target mismatch');
|
|
51
|
-
for(const old of state.identities){const current=next.identities.find(i=>i.actorRef===old.actorRef);if(!current||current.taskId!==old.taskId||current.role!==old.role)throw Error('Identity rebind forbidden');}
|
|
52
|
-
for(const old of state.leases){const current=next.leases.find(l=>l.actorRef===old.actorRef);if(old.status==='retired'&&(!current||current.status!=='retired'||current.taskId!==old.taskId))throw Error('Retired lease revival forbidden');}
|
|
53
|
-
next.revision=state.revision+1;next.requests=prior?state.requests.map(r=>r.requestId===requestId?{requestId,requestFingerprint,decision}:r):[...state.requests,{requestId,requestFingerprint,decision}];
|
|
54
|
-
next.audit=[...state.audit,{requestId,revision:next.revision,decision:decision.decision,ruleIds:decision.ruleIds??[],result:'pending'}];
|
|
55
|
-
validateWorkflowState(next);
|
|
56
|
-
await saveDurableState({statePath,state:next});
|
|
57
|
-
return {state:next,decision,replayed:false};
|
|
58
|
-
}finally{
|
|
59
|
-
if(temporary)await fs.unlink(temporary).catch(()=>{});
|
|
60
|
-
if(lock){await lock.close();await fs.unlink(lockPath);}
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
/** Shared durability primitive. A post-rename sync error is reported as failure;
|
|
65
|
-
* the caller must re-read rather than assume rollback or repeat an effect. */
|
|
66
|
-
export async function saveDurableState({statePath,state,create=false,storage={}}){
|
|
67
|
-
const parent=path.dirname(statePath),temporary=path.join(parent,`.${path.basename(statePath)}.${crypto.randomUUID()}.tmp`);
|
|
68
|
-
let exists=false;
|
|
69
|
-
try{
|
|
70
|
-
const handle=await fs.open(temporary,'wx',0o600);exists=true;
|
|
71
|
-
try{await handle.writeFile(JSON.stringify(state,null,2)+'\n');await handle.sync();}finally{await handle.close();}
|
|
72
|
-
if(create){await (storage.link??fs.link)(temporary,statePath);await fs.unlink(temporary);}else await (storage.rename??fs.rename)(temporary,statePath);
|
|
73
|
-
exists=false;
|
|
74
|
-
const directory=await fs.open(parent,'r');try{await directory.sync();}finally{await directory.close();}
|
|
75
|
-
}finally{if(exists)await fs.unlink(temporary).catch(()=>{});}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** Only a locally verified cooperative commit may advance the stored target. */
|
|
79
|
-
export function applyCooperativeCommitTransition({state,decision}){
|
|
80
|
-
if(decision?.decision!=='allow'||!verifiedCooperativeReconciliation(decision,state)||!decision.proposedTransition?.commit)throw Error('Verified cooperative reconciliation required');
|
|
81
|
-
const next=structuredClone(state),transition=decision.proposedTransition;
|
|
82
|
-
next.targetHistory.push({target:structuredClone(state.target),revision:state.revision+1,source:'local-observation',kind:'verified-commit-parent'});
|
|
83
|
-
next.target=structuredClone(transition.target);next.commits.push(structuredClone(transition.commit));next.tasks.find(t=>t.id===transition.commit.taskId).status='committed';
|
|
84
|
-
return next;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
/** Target preparation changes identity only after re-evaluating its captured observation. */
|
|
88
|
-
export function applyCooperativeTargetTransition({state,decision,messageRef}){
|
|
89
|
-
const next=applyTargetPreparationTransition({state,decision});
|
|
90
|
-
if(next.targetVersion!==state.targetVersion+1)throw Error('Verified target preparation transition required');
|
|
91
|
-
next.targetHistory.push({target:structuredClone(state.target),revision:state.revision+1,source:'local-observation',kind:'target-preparation-source'});
|
|
92
|
-
next.targetTransitions.at(-1).messageRef=messageRef;
|
|
93
|
-
return next;
|
|
94
|
-
}
|
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|
2
|
-
const text=value=>typeof value==='string'&&value.length>0;
|
|
3
|
-
const relative=value=>text(value)&&!/[\\\x00\r\n:]/.test(value)&&!value.startsWith('/')&&!value.split('/').some(part=>!part||part==='.'||part==='..');
|
|
4
|
-
|
|
5
|
-
export async function readTargetPreparationEvidence({state,targetIntent,destination,observe=observeCooperativeTarget,readChanges=readCooperativeChanges,gitRunner}={}){
|
|
6
|
-
const sourceTarget=await observe(state.target.realpath);
|
|
7
|
-
const snapshot=await readChanges({state:{...state,target:sourceTarget},...(gitRunner?{gitRunner}:{})});
|
|
8
|
-
const stage=state.plannerLedger?.stages?.find(s=>s.id===targetIntent?.firstStageId);
|
|
9
|
-
const source={target:sourceTarget,fingerprint:snapshot.final,snapshot:snapshot.transitionSnapshot,preserved:!!targetIntent?.sourceSnapshot&&same(snapshot.transitionSnapshot,targetIntent.sourceSnapshot),inputVersion:stage?.inputVersion,candidate:targetIntent?.candidate,base:targetIntent?.base};
|
|
10
|
-
if(!destination)return {source};
|
|
11
|
-
const target=await observe(destination.realpath),tasks=state.tasks.map(task=>({...task,paths:task.paths.map(p=>{if(!within(state.target.realpath,p))throw Error('Task path escapes source');return path.join(target.realpath,path.relative(state.target.realpath,p));})})),destinationSnapshot=await readChanges({state:{...state,target,tasks},...(gitRunner?{gitRunner}:{})}),result={target,snapshot:destinationSnapshot.transitionSnapshot};
|
|
12
|
-
source.preserved=source.preserved&&same(destinationSnapshot.transitionSnapshot,targetIntent.sourceSnapshot);
|
|
13
|
-
if(target.realpath!==state.target.realpath){
|
|
14
|
-
const query=await (gitRunner??defaultRunner)({cwd:sourceTarget.realpath,args:['worktree','list','--porcelain','-z']});
|
|
15
|
-
if(query?.status!==0||query.error||!Buffer.isBuffer(query.stdout))throw Error('Worktree registration query failed');
|
|
16
|
-
const raw=new TextDecoder('utf-8',{fatal:true}).decode(query.stdout);if(raw&&!raw.endsWith('\0\0'))throw Error('Incomplete worktree registration');
|
|
17
|
-
const entries=raw?raw.slice(0,-2).split('\0\0').map(entry=>entry.split('\0')):[];
|
|
18
|
-
result.registered=entries.some(entry=>entry.includes('worktree '+target.realpath)&&entry.includes('HEAD '+target.head)&&entry.includes('branch refs/heads/'+target.branch));
|
|
19
|
-
const attachment=state.records?.find(r=>r.kind==='note'&&r.messageRef===destination.attachmentRef&&r.targetVersion===state.targetVersion&&r.source==='operator-attested'&&r.data?.type==='worktree-attachment'&&r.data.realpath===target.realpath&&r.data.gitDir===target.gitDir&&r.data.gitCommonDir===target.gitCommonDir);
|
|
20
|
-
if(attachment)result.attachmentRef=attachment.messageRef;
|
|
21
|
-
}
|
|
22
|
-
if(destination.path!==undefined){
|
|
23
|
-
if(!relative(destination.path))throw Error('Invalid destination path');
|
|
24
|
-
const filename=path.join(target.realpath,...destination.path.split('/'));
|
|
25
|
-
if(!within(target.realpath,filename))throw Error('Destination path escapes workspace');
|
|
26
|
-
await inspectPath(filename);const handle=await fs.open(filename,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);
|
|
27
|
-
let bytes,after;
|
|
28
|
-
try{const before=await handle.stat();if(!before.isFile())throw Error('Destination must be a regular file');bytes=await handle.readFile();after=await handle.stat();const named=await fs.lstat(filename);if(before.dev!==after.dev||before.ino!==after.ino||before.size!==after.size||before.mtimeMs!==after.mtimeMs||before.mode!==after.mode||after.dev!==named.dev||after.ino!==named.ino)throw Error('Destination changed while reading');}finally{await handle.close();}
|
|
29
|
-
await inspectPath(filename);if(!within(target.realpath,await fs.realpath(filename)))throw Error('Destination path escapes workspace');
|
|
30
|
-
result.document={path:destination.path,hash:'sha256:'+createHash('sha256').update(bytes).digest('hex'),mode:0o100000|(after.mode&0o777),verification:{status:'verified',source:'local-bytes'}};
|
|
31
|
-
}
|
|
32
|
-
return {source,destination:result};
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export function validateTargetPreparationRecord(kind,data){
|
|
36
|
-
if(!data||data.type!==kind||!['intent','checkpoint','transition','destination'].includes(kind))throw Error('Invalid target preparation type');
|
|
37
|
-
if(kind==='intent'&&(!text(data.id)||!text(data.workflowId)||!data.sourceTarget||!Number.isSafeInteger(data.sourceTargetVersion)||!text(data.selectionRef)||!['current','branch','worktree'].includes(data.kind)||!text(data.candidate)||!text(data.base)||!text(data.firstStageId)||!Array.isArray(data.documents)||!data.documents.length||data.documents.some(d=>!['spec','plan'].includes(d.kind)||!relative(d.path))||new Set(data.documents.map(d=>d.kind)).size!==data.documents.length))throw Error('Invalid target preparation intent');
|
|
38
|
-
if(kind==='intent'&&(!Number.isSafeInteger(data.sourceTargetVersion)||data.sourceTargetVersion<1||!['realpath','gitCommonDir','gitDir'].every(k=>typeof data.sourceTarget[k]==='string'&&path.isAbsolute(data.sourceTarget[k])&&path.normalize(data.sourceTarget[k])===data.sourceTarget[k])||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(data.sourceTarget.head)||!(data.sourceTarget.branch===null||text(data.sourceTarget.branch))||!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(data.base)||new Set(data.documents.map(d=>d.path)).size!==data.documents.length))throw Error('Invalid target preparation intent identity');
|
|
39
|
-
if(kind==='checkpoint'&&(!text(data.intentId)||!text(data.stageId)||!text(data.resultRef)||!text(data.selfReviewRef)))throw Error('Invalid target preparation checkpoint');
|
|
40
|
-
if(kind==='transition'&&(!text(data.intentId)||!text(data.checkpointRef)||!Number.isSafeInteger(data.expectedRevision)||data.expectedRevision<0))throw Error('Invalid target preparation transition');
|
|
41
|
-
if(kind==='destination'&&(!text(data.intentId)||!text(data.transitionRef)||!text(data.stageId)||!text(data.resultRef)||!text(data.selfReviewRef)||!relative(data.path)||!/^sha256:[a-f0-9]{64}$/.test(data.hash)||![0o100644,0o100755].includes(data.mode)||!text(data.reviewRef)||!text(data.approvalRef)||!Number.isSafeInteger(data.targetVersion)||data.targetVersion<1))throw Error('Invalid target preparation destination');
|
|
42
|
-
return data;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export function evaluateTargetPreparation({state,request,evidence}={}){
|
|
46
|
-
const hold=reason=>({decision:'hold',ruleIds:['cooperative.target-preparation'],reason});
|
|
47
|
-
try{validateTargetPreparationRecord(request?.type,request);}catch{return hold('Invalid target preparation record');}
|
|
48
|
-
if(request.type==='intent'){
|
|
49
|
-
if(state.targetIntents?.some(intent=>!state.targetTransitions?.some(transition=>transition.intentId===intent.id)))return hold('Existing target preparation intent is still active');
|
|
50
|
-
const approval=state.records?.find(r=>r.kind==='approval'&&r.messageRef===request.approvalRef&&r.source==='operator-attested'&&r.actor?.role==='orchestrator'&&r.targetVersion===state.targetVersion&&r.scopeVersion===state.scopeVersion);
|
|
51
|
-
const approved=approval?.data?.targetPreparation;
|
|
52
|
-
if(!['Bounded','Architectural'].includes(request.depth)||(request.depth==='Architectural'&&(!request.documents.some(d=>d.kind==='spec')||!request.documents.some(d=>d.kind==='plan'))))return hold('Approved depth requires its complete document set');
|
|
53
|
-
if(!text(request.approvalRef)||!text(request.depth)||['depth','selectionRef','kind','candidate','base','workflowId','firstStageId','sourceTargetVersion'].some(k=>approved?.[k]!==request[k])||!same(approved?.sourceTarget,request.sourceTarget)||!same(approved?.documents,request.documents)||request.workflowId!==state.workflowId||request.sourceTargetVersion!==state.targetVersion||!same(request.sourceTarget,state.target)||!same(evidence?.source?.target,state.target)||!text(evidence?.source?.fingerprint)||!state.selections?.some(s=>s.messageRef===request.selectionRef&&s.targetVersion===state.targetVersion)||state.targetIntents?.some(i=>i.id===request.id)||request.base!==state.target.head)return hold('Current approval, document set, source, explicit choice and preservation snapshot required');
|
|
54
|
-
return {decision:'allow',ruleIds:['cooperative.target-preparation'],proposedTransition:{intent:{...structuredClone(request),scopeVersion:state.scopeVersion,sourceFingerprint:evidence.source.fingerprint,...(evidence.source.snapshot?{sourceSnapshot:structuredClone(evidence.source.snapshot)}:{}),source:'operator-attested'}}};
|
|
55
|
-
}
|
|
56
|
-
if(request.type==='transition'){
|
|
57
|
-
const intent=state?.targetIntents?.find(i=>i.id===request.intentId),checkpoint=state?.targetCheckpoints?.find(c=>c.intentId===request.intentId&&c.messageRef===request.checkpointRef);
|
|
58
|
-
const source=evidence?.source,destination=evidence?.destination?.target;
|
|
59
|
-
if(state.plannerLedger?.stages?.some(s=>s.pending||s.calls?.some(c=>['reserved','unknown'].includes(c.status))))return hold('Pending or unknown Planner execution');
|
|
60
|
-
const stage=state.plannerLedger?.stages?.find(s=>s.id===intent?.firstStageId),result=stage?.result,chat=result?.chatDraft;
|
|
61
|
-
if(!intent||intent.scopeVersion!==state.scopeVersion||stage?.scopeVersion!==state.scopeVersion||stage.targetVersion!==state.targetVersion||!state.records?.some(r=>r.kind==='approval'&&r.messageRef===intent.approvalRef&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion&&r.actor?.role==='orchestrator'&&r.source==='operator-attested'))return hold('Current scope approval and source stage required');
|
|
62
|
-
if(!stage||stage.targetIntentId!==intent.id||checkpoint?.stageId!==stage.id||checkpoint.resultRef!==result?.ref||checkpoint.selfReviewRef!==chat?.selfReviewRef||checkpoint.candidate!==intent.candidate||checkpoint.base!==intent.base||checkpoint.inputVersion!==stage.inputVersion||result.status!=='succeeded'||chat?.intentId!==intent.id||chat.complete!==true||!text(chat.draftRef)||!stage.calls?.some(c=>c.requestId===result.requestId&&c.status==='succeeded'))return hold('Checkpoint source result changed');
|
|
63
|
-
if(!intent||!checkpoint||state.targetTransitions?.some(t=>t.intentId===intent.id)||request.expectedRevision!==state.revision||intent.sourceTargetVersion!==state.targetVersion||!same(intent.sourceTarget,state.target)||!same(evidence?.versions,state.versions)||!source?.preserved||!destination||source.target?.realpath!==state.target.realpath||source.target?.gitCommonDir!==state.target.gitCommonDir||source.target?.gitDir!==state.target.gitDir||destination.gitCommonDir!==state.target.gitCommonDir||state.unresolved?.some(u=>!u.resolvedBy)||state.assignments?.some(a=>a.status==='active')||state.intents?.some(i=>['prepared','unknown','mismatch'].includes(i.status)))return hold('Current checkpoint, preservation and independent target evidence required');
|
|
64
|
-
if(intent.kind==='branch'&&!(destination.realpath===state.target.realpath&&destination.gitDir===state.target.gitDir&&destination.branch===intent.candidate&&destination.head===intent.base&&source.target.branch===intent.candidate&&source.target.head===intent.base))return hold('Branch target differs from intent');
|
|
65
|
-
if(intent.kind==='current'&&(!same(destination,state.target)||destination.branch!==intent.candidate||destination.head!==intent.base))return hold('Current target changed');
|
|
66
|
-
if(intent.kind==='worktree'&&state.tasks?.some(task=>task.paths?.length))return hold('Worktree transition with source-bound task paths is unsupported');
|
|
67
|
-
if(intent.kind==='worktree'&&!(same(source.target,state.target)&&destination.realpath!==state.target.realpath&&destination.gitDir!==state.target.gitDir&&destination.branch===intent.candidate&&destination.head===intent.base&&evidence.destination.registered===true&&text(evidence.destination.attachmentRef)&&state.records?.some(r=>r.kind==='note'&&r.messageRef===evidence.destination.attachmentRef&&r.targetVersion===state.targetVersion&&r.source==='operator-attested'&&r.data?.type==='worktree-attachment'&&r.data.realpath===destination.realpath&&r.data.gitDir===destination.gitDir&&r.data.gitCommonDir===destination.gitCommonDir)))return hold('Worktree registration and attachment required');
|
|
68
|
-
return {decision:'allow',ruleIds:['cooperative.target-preparation'],proposedTransition:{target:structuredClone(destination),intentId:intent.id,checkpointRef:request.checkpointRef,sourceTargetVersion:state.targetVersion,expectedRevision:state.revision,validation:{request:structuredClone(request),evidence:structuredClone(evidence)}}};
|
|
69
|
-
}
|
|
70
|
-
if(request.type==='destination'){
|
|
71
|
-
const intent=state.targetIntents?.find(i=>i.id===request.intentId),document=intent?.documents?.find(d=>d.path===request.path),transition=state.targetTransitions?.find(t=>t.intentId===request.intentId&&t.messageRef===request.transitionRef&&t.targetVersion===state.targetVersion),checkpoint=state.targetCheckpoints?.find(c=>c.intentId===request.intentId&&c.messageRef===transition?.checkpointRef),stage=state.plannerLedger?.stages?.find(s=>s.id===request.stageId),chat=stage?.result?.chatDraft,observed=evidence?.destination?.document;
|
|
72
|
-
const review=state.records?.find(r=>r.kind==='planner-review'&&r.messageRef===request.reviewRef&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion&&r.source==='operator-attested'),approval=state.records?.find(r=>r.kind==='approval'&&r.messageRef===request.approvalRef&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion&&r.source==='operator-attested');
|
|
73
|
-
if(!intent||!document||intent.firstStageId!==request.stageId||!transition||!same(transition.target,state.target)||request.targetVersion!==state.targetVersion||!checkpoint||checkpoint.stageId!==request.stageId||checkpoint.resultRef!==request.resultRef||checkpoint.selfReviewRef!==request.selfReviewRef||stage?.targetIntentId!==intent.id||stage.result?.ref!==request.resultRef||stage.result.status!=='succeeded'||chat?.intentId!==intent.id||chat.complete!==true||chat.selfReviewRef!==request.selfReviewRef||!same(evidence?.destination?.target,state.target)||observed?.verification?.status!=='verified'||observed.verification.source!=='local-bytes'||observed.path!==request.path||observed.hash!==request.hash||observed.mode!==request.mode)return hold('Current transition, source attestation and observed destination bytes required');
|
|
74
|
-
if(stage.scopeVersion!==state.scopeVersion||review?.data?.resultRef!==request.resultRef||review.data.full!==true||review.data.complete!==true||review.data.hash!==request.hash||!Array.isArray(stage.criteria)||!Array.isArray(review.data.criteria)||review.data.criteria.length!==stage.criteria.length||new Set(review.data.criteria.map(c=>c.id)).size!==stage.criteria.length||review.data.criteria.some(c=>!stage.criteria.some(s=>s.id===c.id)||c.status!=='resolved'||!text(c.judgmentRef))||approval?.data?.kind!==document.kind||approval.data.contentHash!==request.hash||![request.path,path.join(state.target.realpath,request.path)].includes(approval.data.path))return hold('Current full review and document approval required');
|
|
75
|
-
return {decision:'allow',ruleIds:['cooperative.target-preparation'],proposedTransition:{destination:{...structuredClone(request),scopeVersion:state.scopeVersion,sourceLink:'operator-attested',verification:{status:'verified',source:'local-bytes'}}}};
|
|
76
|
-
}
|
|
77
|
-
if(request?.type!=='checkpoint')return hold('Unsupported target preparation request');
|
|
78
|
-
const intent=state?.targetIntents?.find(i=>i.id===request.intentId);
|
|
79
|
-
const stage=state?.plannerLedger?.stages?.find(s=>s.id===request.stageId);
|
|
80
|
-
const source=evidence?.source,result=stage?.result,chat=result?.chatDraft;
|
|
81
|
-
if(!intent||intent.scopeVersion!==state.scopeVersion||stage?.scopeVersion!==state.scopeVersion||stage.targetVersion!==state.targetVersion||!state.records?.some(r=>r.kind==='approval'&&r.messageRef===intent.approvalRef&&r.scopeVersion===state.scopeVersion&&r.targetVersion===state.targetVersion&&r.actor?.role==='orchestrator'&&r.source==='operator-attested'))return hold('Current scope approval and source stage required');
|
|
82
|
-
if(!intent||!stage||intent.firstStageId!==stage.id||stage.targetIntentId!==intent.id||intent.sourceTargetVersion!==state.targetVersion||!same(intent.sourceTarget,state.target)||!same(source?.target,state.target)||source.preserved!==true||source.inputVersion!==stage.inputVersion||source.candidate!==intent.candidate||source.base!==intent.base)return hold('Current source and intent evidence required');
|
|
83
|
-
if(stage.pending||result?.ref!==request.resultRef||result?.status!=='succeeded'||!stage.calls?.some(c=>c.requestId===result.requestId&&c.status==='succeeded')||stage.calls.some(c=>['reserved','unknown'].includes(c.status))||chat?.intentId!==intent.id||!chat.draftRef||!chat.selfReviewRef||chat.selfReviewRef!==request.selfReviewRef||chat.complete!==true)return hold('Complete confirmed chat draft and self-review required');
|
|
84
|
-
return {decision:'allow',ruleIds:['cooperative.target-preparation'],reason:'Chat checkpoint attested',proposedTransition:{checkpoint:{intentId:intent.id,stageId:stage.id,resultRef:result.ref,selfReviewRef:chat.selfReviewRef,candidate:intent.candidate,base:intent.base,inputVersion:stage.inputVersion}}};
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
export function applyTargetPreparationTransition({state,decision}={}){
|
|
88
|
-
const next=structuredClone(state),transition=decision?.proposedTransition;
|
|
89
|
-
if(decision?.decision!=='allow'||!transition?.target||transition.sourceTargetVersion!==state.targetVersion||transition.expectedRevision!==state.revision||state.targetTransitions?.some(t=>t.intentId===transition.intentId))return next;
|
|
90
|
-
if(!transition.validation)return next;
|
|
91
|
-
const checked=evaluateTargetPreparation({state,...transition.validation});
|
|
92
|
-
if(checked.decision!=='allow'||!same(checked.proposedTransition,transition))return next;
|
|
93
|
-
const intent=state.targetIntents?.find(i=>i.id===transition.intentId),checkpoint=state.targetCheckpoints?.find(c=>c.intentId===transition.intentId&&c.messageRef===transition.checkpointRef);
|
|
94
|
-
if(!intent||!checkpoint||intent.sourceTargetVersion!==state.targetVersion||!same(intent.sourceTarget,state.target))return next;
|
|
95
|
-
next.target=structuredClone(transition.target);next.targetVersion++;
|
|
96
|
-
(next.targetTransitions??=[]).push({...structuredClone(transition),targetVersion:next.targetVersion});
|
|
97
|
-
return next;
|
|
98
|
-
}
|
|
99
|
-
import fs from 'node:fs/promises';
|
|
100
|
-
import {constants} from 'node:fs';
|
|
101
|
-
import path from 'node:path';
|
|
102
|
-
import {createHash} from 'node:crypto';
|
|
103
|
-
import {inspectPath,within,observeCooperativeTarget} from './scope.mjs';
|
|
104
|
-
import {readCooperativeChanges} from './verification.mjs';
|
|
105
|
-
import {spawnSync} from 'node:child_process';
|
|
106
|
-
function defaultRunner({cwd,args}){
|
|
107
|
-
const env=Object.fromEntries(Object.entries(process.env).filter(([key])=>!key.toUpperCase().startsWith('GIT_')));
|
|
108
|
-
Object.assign(env,{GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:process.platform==='win32'?'NUL':'/dev/null',GIT_OPTIONAL_LOCKS:'0',GIT_NO_REPLACE_OBJECTS:'1',GIT_NO_LAZY_FETCH:'1',GIT_TERMINAL_PROMPT:'0'});
|
|
109
|
-
return spawnSync('git',['--no-pager','-c','core.fsmonitor=false',...args],{cwd,env,encoding:'buffer',timeout:10000,maxBuffer:1024*1024});
|
|
110
|
-
}
|
|
@@ -1,125 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs/promises';
|
|
2
|
-
import {constants} from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import {createHash} from 'node:crypto';
|
|
5
|
-
import {spawnSync} from 'node:child_process';
|
|
6
|
-
import {fingerprintRequest} from './store.mjs';
|
|
7
|
-
import {absolute,within,inspectPath} from './scope.mjs';
|
|
8
|
-
const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|
9
|
-
const text=v=>typeof v==='string'&&v.length>0;
|
|
10
|
-
const hash=v=>typeof v==='string'&&/^sha256:[a-f0-9]{64}$/.test(v);
|
|
11
|
-
const list=v=>Array.isArray(v)&&v.every(text)&&new Set(v).size===v.length;
|
|
12
|
-
const fields=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).every(k=>keys.includes(k));
|
|
13
|
-
const base=state=>({expectedRevision:state?.revision??0,coverage:{enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false},requiredEvidence:[],nextActions:[],proposedTransition:null});
|
|
14
|
-
const hold=(state,id,reason)=>({...base(state),decision:'hold',ruleIds:['cooperative.'+id],reason});
|
|
15
|
-
const allow=(state,transition)=>({...base(state),decision:'allow',ruleIds:['cooperative.verification'],proposedTransition:transition});
|
|
16
|
-
const current=(state,scope,taskId,changes)=>scope==='final'?changes?.final:changes?.tasks?.[taskId];
|
|
17
|
-
const approval=(state,taskId)=>state.records.filter(r=>r.kind==='approval'&&(!r.data.affectedTaskIds||r.data.affectedTaskIds.includes(taskId))).at(-1);
|
|
18
|
-
function authorized(state,task){
|
|
19
|
-
const a=approval(state,task?.id);
|
|
20
|
-
return task&&!task.invalidated&&a&&a.source==='operator-attested'&&a.targetVersion===state.targetVersion&&task.scopeVersion===a.scopeVersion&&task.targetVersion===state.targetVersion&&task.approvalRef===a.messageRef&&task.approvalVersion===a.data.approvalVersion&&task.documentVersion===a.data.documentVersion;
|
|
21
|
-
}
|
|
22
|
-
function descriptorValid(state,d,operation){
|
|
23
|
-
if(operation==='review')return fields(d,['kind','paths'])&&d.kind==='source-review'&&list(d.paths)&&d.paths.length>0&&d.paths.every(p=>absolute(p)&&within(state.target.realpath,p));
|
|
24
|
-
return fields(d,['executable','args','cwd','env','outputs'])&&absolute(d.executable)&&Array.isArray(d.args)&&d.args.every(v=>typeof v==='string')&&absolute(d.cwd)&&within(state.target.realpath,d.cwd)&&fields(d.env,Object.keys(d.env??{}))&&Object.values(d.env).every(v=>typeof v==='string')&&Array.isArray(d.outputs)&&d.outputs.every(p=>absolute(p)&&within(state.target.realpath,p));
|
|
25
|
-
}
|
|
26
|
-
const assignedImplementer=(state,id,taskId)=>state.assignments.some(a=>a.agentId===id&&a.taskId===taskId&&a.status==='active');
|
|
27
|
-
function independent(state,actor,taskId){
|
|
28
|
-
if(!fields(actor,['id','role'])||!text(actor.id))return false;
|
|
29
|
-
if(state.assignments.some(a=>a.agentId===actor.id))return false;
|
|
30
|
-
return !(state.intents??[]).some(i=>i.verificationActor?.id===actor.id&&(i.verificationActor.role!==actor.role||actor.role==='qa'&&i.taskId!==taskId))&&!(state.checks??[]).some(c=>c.verificationActor?.id===actor.id&&(c.verificationActor.role!==actor.role||actor.role==='qa'&&c.taskId!==taskId));
|
|
31
|
-
}
|
|
32
|
-
/** Invalidate only the affected dependency closure; preserve all historical evidence. */
|
|
33
|
-
export function invalidateAffectedEvidence({state,changedVersions={},affectedTaskIds}={}){
|
|
34
|
-
const next=structuredClone(state),ids=new Set(affectedTaskIds??next.tasks.map(t=>t.id));
|
|
35
|
-
let changed=true;while(changed){changed=false;for(const t of next.tasks)if(!ids.has(t.id)&&t.dependencies?.some(id=>ids.has(id))){ids.add(t.id);changed=true;}}
|
|
36
|
-
for(const t of next.tasks)if(ids.has(t.id)){t.invalidated=true;t.status='held';t.invalidatedBy=structuredClone(changedVersions);t.invalidatedAt=state.revision+1;}
|
|
37
|
-
for(const key of ['checks','acceptances'])for(const entry of next[key]??[])if(entry.scope==='final'||ids.has(entry.taskId)){entry.stale=true;entry.invalidatedBy=structuredClone(changedVersions);}
|
|
38
|
-
for(const intent of next.intents??[])if(['check','review'].includes(intent.operation)&&(intent.scope==='final'||ids.has(intent.taskId)))intent.stale=true;
|
|
39
|
-
// Old approval statements remain immutable; no change creates renewed authority.
|
|
40
|
-
if(Number.isSafeInteger(changedVersions.scopeVersion))next.scopeVersion=changedVersions.scopeVersion;
|
|
41
|
-
return next;
|
|
42
|
-
}
|
|
43
|
-
function record({state,request,evidence}){
|
|
44
|
-
const entry=request.evidence,d=entry?.data;
|
|
45
|
-
if(!entry||!text(entry.messageRef)||!d)return hold(state,'verification-record','Structured evidence required');
|
|
46
|
-
if(entry.kind==='acceptance-evidence'&&d.kind==='task'){
|
|
47
|
-
const t=d.task,previous=state.tasks.find(task=>task.id===t?.id),a=approval(state,t?.id);
|
|
48
|
-
if(previous?.invalidated&&(!a||!Number.isSafeInteger(a.revision)||a.revision<previous.invalidatedAt||a.scopeVersion!==state.scopeVersion))return hold(state,'task-approval-stale','Invalidated task requires a renewed approval statement');
|
|
49
|
-
if(!fields(t,['id','paths','criteria','requiredChecks','dependencies','approvalRef','approvalVersion','documentVersion','scopeVersion','targetVersion','status'])||!text(t.id)||!list(t.paths)||!t.paths.length||!t.paths.every(p=>absolute(p)&&within(state.target.realpath,p))||!list(t.criteria)||!t.criteria.length||!list(t.dependencies)||t.dependencies.includes(t.id)||t.dependencies.some(id=>!state.tasks.some(task=>task.id===id))||!Array.isArray(t.requiredChecks)||!t.requiredChecks.length||!t.requiredChecks.every(c=>descriptorValid(state,c,'check'))||!['pending',undefined].includes(t.status)||state.tasks.some(task=>task.id===t.id&&['accepted','committed'].includes(task.status))||!authorized(state,t))return hold(state,'task-contract','Current approval and explicit pending task contract required');
|
|
50
|
-
return allow(state,{task:{...structuredClone(t),status:'pending',source:'operator-attested',messageRef:entry.messageRef}});
|
|
51
|
-
}
|
|
52
|
-
if(entry.kind!=='finding')return hold(state,'unsupported','Check and review outcomes require durable intent/result');
|
|
53
|
-
if(d.action==='open'){
|
|
54
|
-
const check=state.checks.find(c=>c.id===d.checkId&&!c.stale);
|
|
55
|
-
if(!fields(d,['action','id','checkId','message'])||!text(d.id)||!text(d.message)||state.findings.some(f=>f.id===d.id)||!check)return hold(state,'finding','Finding must link an existing check or review');
|
|
56
|
-
return allow(state,{finding:{id:d.id,checkId:check.id,scope:check.scope,taskId:check.taskId,origin:check.scope==='final'&&check.operation==='review'?'final-review':'check',status:'open',message:d.message,messageRef:entry.messageRef,source:'operator-attested'}});
|
|
57
|
-
}
|
|
58
|
-
const finding=state.findings.find(f=>f.id===d.id);
|
|
59
|
-
const affected=finding?.scope==='final'?state.tasks.map(t=>t.id):[finding?.taskId];
|
|
60
|
-
if(!fields(d,['action','id','actor','changeFingerprint'])||d.action!=='resolve'||!finding||finding.status==='closed'||!fields(d.actor,['id','role'])||d.actor.role!=='implementer'||!affected.some(id=>assignedImplementer(state,d.actor.id,id))||!hash(d.changeFingerprint)||d.changeFingerprint!==current(state,finding.scope,finding.taskId,evidence?.changes))return hold(state,'finding-resolution','Assigned Implementer correction at the current fingerprint required');
|
|
61
|
-
return allow(state,{finding:{...finding,status:'resolved',resolutionRef:entry.messageRef,resolutionActor:structuredClone(d.actor),changeFingerprint:d.changeFingerprint}});
|
|
62
|
-
}
|
|
63
|
-
/** Pure cooperative gate: verifies recorded consistency, never identity or semantic sufficiency. */
|
|
64
|
-
export function evaluateCooperativeVerification({state,request,evidence}={}){
|
|
65
|
-
if(state?.mode!=='plan')return hold(state,'unsupported','Only the complete spec and plan path is supported');
|
|
66
|
-
if(!request||request.expectedRevision!==state.revision)return hold(state,'revision','Stale verification request');
|
|
67
|
-
if(request.actor?.role!=='orchestrator')return hold(state,'verification-actor','Orchestrator statement required');
|
|
68
|
-
if(request.operation==='verification-record')return record({state,request,evidence});
|
|
69
|
-
if(request.operation==='verification-result')return outcome({state,request,evidence});
|
|
70
|
-
if(!['check','review'].includes(request.operation))return hold(state,'unsupported','Unsupported verification operation');
|
|
71
|
-
const a=request.arguments,t=state.tasks.find(t=>t.id===request.taskId);
|
|
72
|
-
if(!fields(a,['scope','actor','descriptor','changeFingerprint','findingIds'])||!['task','final'].includes(a.scope)||!hash(a.changeFingerprint)||a.changeFingerprint!==current(state,a.scope,request.taskId,evidence?.changes)||!descriptorValid(state,a.descriptor,request.operation))return hold(state,'verification-fingerprint','Exact scope descriptor and current fingerprint required');
|
|
73
|
-
if(a.scope==='task'&&(!authorized(state,t)||t.status==='held'||request.operation==='review'||!t.requiredChecks.some(d=>same(d,a.descriptor))))return hold(state,'verification-task','Current task approval and exact assigned check required; Reviewer is final only');
|
|
74
|
-
if(a.scope==='final'&&(request.taskId!==undefined||request.operation!=='review'||!state.tasks.length||state.tasks.some(t=>!authorized(state,t)||!['accepted','committed'].includes(t.status))))return hold(state,'verification-final','Final review follows accepted tasks and required task checks');
|
|
75
|
-
const finalCorrection=a.scope==='final'&&state.findings.some(f=>f.origin==='final-review'&&f.status==='resolved'&&a.findingIds?.includes(f.id));
|
|
76
|
-
if(a.scope==='final'&&!finalCorrection&&state.tasks.some(task=>task.requiredChecks.some(descriptor=>!state.checks.some(c=>c.scope==='task'&&c.taskId===task.id&&c.operation==='check'&&!c.stale&&c.status==='passed'&&c.verdict==='proven'&&text(c.resultRef)&&c.verificationActor?.role==='qa'&&same(c.descriptor,descriptor)&&(c.changeFingerprint===evidence.changes?.tasks?.[task.id]||task.status==='committed'&&state.commits?.some(commit=>commit.taskId===task.id&&commit.observationSource==='local-git'&&commit.fingerprint===c.changeFingerprint&&commit.postCommitFingerprint===evidence.changes?.tasks?.[task.id]))))))return hold(state,'verification-final-checks','Initial final review requires current task QA evidence');
|
|
77
|
-
if(a.actor?.role!==(request.operation==='review'?'reviewer':'qa')||a.actor.id===request.actor.id||!independent(state,a.actor,request.taskId))return hold(state,'verification-independence','Independent actor statement and fresh task QA required');
|
|
78
|
-
const findings=state.findings.filter(f=>f.status!=='closed'&&(a.scope==='final'||f.scope==='task'&&f.taskId===request.taskId));
|
|
79
|
-
if(a.findingIds!==undefined&&(!list(a.findingIds)||a.findingIds.some(id=>!findings.some(f=>f.id===id))))return hold(state,'finding-recheck','Unknown finding recheck');
|
|
80
|
-
if(findings.some(f=>f.status!=='resolved'||!text(f.resolutionRef)||f.resolutionActor?.role!=='implementer'||f.changeFingerprint!==a.changeFingerprint||!a.findingIds?.includes(f.id)||f.origin==='final-review'&&request.operation!=='review'||f.origin!=='final-review'&&request.operation!=='check'))return hold(state,'finding-recheck','Implementer resolution and the required QA or final Reviewer recheck required');
|
|
81
|
-
if(state.intents.some(i=>['check','review'].includes(i.operation)&&['prepared','unknown','mismatch'].includes(i.status)&&i.scope===a.scope&&i.taskId===request.taskId&&same(i.descriptor,a.descriptor)&&!i.stale))return hold(state,'verification-active','Reconcile the existing verification intent');
|
|
82
|
-
const intent={requestId:request.requestId,operation:request.operation,status:'prepared',scope:a.scope,taskId:request.taskId,verificationActor:structuredClone(a.actor),descriptor:structuredClone(a.descriptor),changeFingerprint:a.changeFingerprint,findingIds:[...(a.findingIds??[])],scopeVersion:state.scopeVersion,targetVersion:state.targetVersion,versions:structuredClone(state.versions),target:structuredClone(state.target),approval:structuredClone(approval(state,request.taskId)),taskFingerprint:fingerprintRequest(a.scope==='final'?state.tasks:t),fingerprint:fingerprintRequest(request),source:'operator-attested'};
|
|
83
|
-
return allow(state,{intent});
|
|
84
|
-
}
|
|
85
|
-
function outcome({state,request,evidence}){
|
|
86
|
-
const intent=state.intents.find(i=>i.requestId===request.intentId),r=request.result,d=r?.data;
|
|
87
|
-
if(!intent||!['check','review'].includes(intent.operation)||!['prepared','unknown','mismatch'].includes(intent.status))return hold(state,'verification-intent','Matching unresolved verification intent required');
|
|
88
|
-
const valid=r&&['succeeded','failed','unknown','mismatch'].includes(r.status)&&text(r.messageRef)&&fields(d,['actor','descriptor','scope','taskId','changeFingerprint','verdict'])&&['proven','unmet','unverified'].includes(d.verdict)&&same(d.actor,intent.verificationActor)&&same(d.descriptor,intent.descriptor)&&d.scope===intent.scope&&d.taskId===intent.taskId&&d.changeFingerprint===intent.changeFingerprint;
|
|
89
|
-
const fresh=!intent.stale&&intent.changeFingerprint===current(state,intent.scope,intent.taskId,evidence?.changes)&&(intent.scope==='task'||intent.scopeVersion===state.scopeVersion)&&intent.targetVersion===state.targetVersion&&same(intent.target,state.target)&&same(intent.versions,state.versions)&&independent(state,intent.verificationActor,intent.taskId)&&same(intent.approval,approval(state,intent.taskId))&&intent.taskFingerprint===fingerprintRequest(intent.scope==='final'?state.tasks:state.tasks.find(t=>t.id===intent.taskId));
|
|
90
|
-
const status=!valid?'mismatch':r.status;
|
|
91
|
-
const check={id:intent.requestId,operation:intent.operation,scope:intent.scope,taskId:intent.taskId,descriptor:structuredClone(intent.descriptor),verificationActor:structuredClone(intent.verificationActor),changeFingerprint:intent.changeFingerprint,resultRef:r?.messageRef,verdict:valid?d.verdict:'unverified',status:fresh&&status==='succeeded'&&d.verdict==='proven'?'passed':status==='failed'||d?.verdict==='unmet'?'failed':'unverified',stale:!fresh,source:'operator-attested'};
|
|
92
|
-
const findings=[];
|
|
93
|
-
if(check.status==='failed')findings.push({id:intent.requestId+':failure',checkId:check.id,scope:intent.scope,taskId:intent.taskId,origin:intent.operation==='review'?'final-review':'check',status:'open',source:'operator-attested',messageRef:r.messageRef});
|
|
94
|
-
if(check.status==='passed')for(const id of intent.findingIds){const f=state.findings.find(f=>f.id===id);if(!f||f.status!=='resolved'||f.changeFingerprint!==intent.changeFingerprint)return hold(state,'finding-recheck','Finding changed after prepare');findings.push({...f,status:'closed',recheckRef:r.messageRef,recheckActor:structuredClone(d.actor)});}
|
|
95
|
-
const transition={result:{...structuredClone(r),status,source:'operator-attested'},check,findings};
|
|
96
|
-
return check.status==='passed'?allow(state,transition):{...hold(state,'verification-'+status,'Recorded outcome does not establish passing current evidence'),proposedTransition:transition};
|
|
97
|
-
}
|
|
98
|
-
function defaultRunner({cwd,args}){
|
|
99
|
-
const env=Object.fromEntries(Object.entries(process.env).filter(([k])=>!k.toUpperCase().startsWith('GIT_')));
|
|
100
|
-
Object.assign(env,{GIT_OPTIONAL_LOCKS:'0',GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:process.platform==='win32'?'NUL':'/dev/null',GIT_NO_REPLACE_OBJECTS:'1',GIT_NO_LAZY_FETCH:'1',GIT_TERMINAL_PROMPT:'0'});
|
|
101
|
-
return spawnSync('git',['--no-pager','--literal-pathspecs','-c','core.fsmonitor=false',...args],{cwd,env,encoding:'buffer',timeout:10000,maxBuffer:16*1024*1024});
|
|
102
|
-
}
|
|
103
|
-
/** Read tracked/untracked regular bytes, deletions and modes without staging or execution.
|
|
104
|
-
* The snapshot is cooperative evidence at observation time, not an atomic execution sandbox. */
|
|
105
|
-
export async function readCooperativeChanges({state,gitRunner=defaultRunner}){
|
|
106
|
-
const inventory=await gitRunner({cwd:state.target.realpath,args:['ls-files','--cached','--others','--exclude-standard','-z']});
|
|
107
|
-
if(inventory?.status!==0||inventory.error||!Buffer.isBuffer(inventory.stdout))throw Error('Verification inventory query failed');
|
|
108
|
-
const raw=new TextDecoder('utf-8',{fatal:true}).decode(inventory.stdout);
|
|
109
|
-
if(raw&&!raw.endsWith('\0'))throw Error('Incomplete verification inventory');
|
|
110
|
-
const index=await gitRunner({cwd:state.target.realpath,args:['ls-files','--stage','-z']});
|
|
111
|
-
if(index?.status!==0||index.error||!Buffer.isBuffer(index.stdout))throw Error('Verification index query failed');
|
|
112
|
-
const indexText=new TextDecoder('utf-8',{fatal:true}).decode(index.stdout),indexRows=[],transitionIndex=[];
|
|
113
|
-
if(indexText&&!indexText.endsWith('\0'))throw Error('Incomplete verification index');
|
|
114
|
-
for(const entry of indexText?indexText.slice(0,-1).split('\0'):[]){const match=/^(100644|100755) ([a-f0-9]{40}|[a-f0-9]{64}) 0\t([\s\S]+)$/.exec(entry);if(!match||!match[3]||/[\\\x00\r\n:]/.test(match[3])||match[3].startsWith('/')||match[3].split('/').some(p=>!p||p==='.'||p==='..'))throw Error('Verification requires regular stage-0 index entries');indexRows.push({path:path.join(state.target.realpath,match[3]),entry});transitionIndex.push({path:match[3],mode:match[1],blob:match[2],stage:0});}
|
|
115
|
-
const names=[...new Set(raw?raw.slice(0,-1).split('\0'):[])].sort(),rows=[];
|
|
116
|
-
for(const name of names){
|
|
117
|
-
if(!name||name.includes('\\')||name.includes('\n')||name.includes('\r')||path.isAbsolute(name)||name.split('/').some(p=>!p||p==='.'||p==='..'))throw Error('Invalid verification path');
|
|
118
|
-
const file=path.join(state.target.realpath,...name.split('/'));
|
|
119
|
-
try{await inspectPath(file);const handle=await fs.open(file,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);let stat,bytes;try{stat=await handle.stat();if(!stat.isFile())throw Error('Verification requires regular files');bytes=await handle.readFile();const after=await handle.stat(),named=await fs.lstat(file);if(stat.dev!==after.dev||stat.ino!==after.ino||stat.size!==after.size||stat.mtimeMs!==after.mtimeMs||stat.mode!==after.mode||after.dev!==named.dev||after.ino!==named.ino)throw Error('Verification file changed while reading');}finally{await handle.close();}await inspectPath(file);rows.push({path:file,mode:stat.mode&0o777,hash:'sha256:'+createHash('sha256').update(bytes).digest('hex')});}
|
|
120
|
-
catch(error){if(error.code!=='ENOENT')throw error;rows.push({path:file,deleted:true});}
|
|
121
|
-
}
|
|
122
|
-
const tasks={},taskSnapshots={};for(const task of state.tasks){if(!list(task.paths)||!task.paths.every(p=>absolute(p)&&within(state.target.realpath,p)))throw Error('Invalid task paths');taskSnapshots[task.id]={scope:'task',taskId:task.id,target:Object.fromEntries(Object.entries(state.target).filter(([key])=>key!=='head')),paths:task.paths,index:indexRows.filter(row=>task.paths.some(p=>within(p,row.path))),rows:rows.filter(row=>task.paths.some(p=>within(p,row.path)))};tasks[task.id]=fingerprintRequest(taskSnapshots[task.id]);}
|
|
123
|
-
const transitionSnapshot={index:transitionIndex.sort((a,b)=>a.path.localeCompare(b.path)),files:rows.map(row=>({...row,path:path.relative(state.target.realpath,row.path).split(path.sep).join('/')}))};
|
|
124
|
-
return {tasks,taskSnapshots,final:fingerprintRequest({scope:'final',target:state.target,index:indexRows,rows}),transitionSnapshot};
|
|
125
|
-
}
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|