@aliip/pilah 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/BUILD_STATUS.md +23 -0
  2. package/LICENSE +21 -0
  3. package/README.md +108 -2
  4. package/assets/logo.svg +5 -0
  5. package/docs/ACCEPTANCE_GATE.md +41 -0
  6. package/docs/ADAPTIVE_RCA_WORKFLOW.md +93 -0
  7. package/docs/AGENT_DECISION_REVIEW.md +17 -0
  8. package/docs/ALWAYS_ON_5_WHYS.md +75 -0
  9. package/docs/ARCHITECTURE.md +43 -0
  10. package/docs/BEHAVIORAL_5_WHYS_V2_0_1.md +117 -0
  11. package/docs/CHECKPOINT_RECOVERY.md +86 -0
  12. package/docs/CI_EFFICIENCY.md +63 -0
  13. package/docs/COMPATIBILITY.md +84 -0
  14. package/docs/CONTRACTS.md +177 -0
  15. package/docs/CONVERSATION_USAGE.md +52 -0
  16. package/docs/ENGINEERING_METHOD.md +68 -0
  17. package/docs/HOST_VALIDATION.md +35 -0
  18. package/docs/INDEPENDENT_ACCEPTANCE_RUNBOOK.md +72 -0
  19. package/docs/INTERVENTION_LEDGER.md +25 -0
  20. package/docs/MAIN_VALIDATION_BACKLOG.md +19 -0
  21. package/docs/NATIVE_FIRST_WORKFLOW.md +27 -0
  22. package/docs/OPEN_SOURCE_ENGINEERING_STANDARDS.md +62 -0
  23. package/docs/ORCHESTRATION_ADVISOR.md +36 -0
  24. package/docs/PRE_VNEXT_INTEGRATION.md +27 -0
  25. package/docs/README.md +54 -0
  26. package/docs/RELEASE.md +33 -0
  27. package/docs/RELEASE_AUTHORIZATION.md +33 -0
  28. package/docs/RISK_GUIDANCE.md +18 -0
  29. package/docs/SECURITY.md +76 -0
  30. package/docs/SECURITY_RELIABILITY_AUDIT_V2_0_1.md +55 -0
  31. package/docs/SEMANTIC_EVIDENCE.md +27 -0
  32. package/docs/SOURCES.md +13 -0
  33. package/docs/TOKEN_EFFICIENCY.md +71 -0
  34. package/docs/TOKEN_PROVENANCE.md +15 -0
  35. package/docs/V2_0_1_TRACEABILITY.md +66 -0
  36. package/hooks.json +45 -0
  37. package/mcp_config.json +16 -0
  38. package/package.json +31 -4
  39. package/plugin.json +27 -0
  40. package/rules/AGENTS.md +2 -0
  41. package/schemas/database.sql +84 -0
  42. package/schemas/mcp-tools.json +552 -0
  43. package/scripts/a2a.mjs +344 -0
  44. package/scripts/check-release.mjs +42 -0
  45. package/scripts/check-syntax.mjs +30 -0
  46. package/scripts/checkpoint.mjs +50 -0
  47. package/scripts/compare-agent-traces.mjs +53 -0
  48. package/scripts/context-guardian.mjs +132 -0
  49. package/scripts/evaluate-acceptance.mjs +110 -0
  50. package/scripts/export-benchmark.mjs +31 -0
  51. package/scripts/generate-contracts.mjs +6 -0
  52. package/scripts/hook.mjs +406 -0
  53. package/scripts/host-check.mjs +40 -0
  54. package/scripts/intervention-ledger.mjs +94 -0
  55. package/scripts/pilah.mjs +3 -0
  56. package/scripts/release-authorization.mjs +137 -0
  57. package/scripts/review-agent-decisions.mjs +34 -0
  58. package/scripts/semantic-evidence.mjs +15 -0
  59. package/scripts/verifykit.mjs +3 -0
  60. package/skills/pilah/SKILL.md +24 -0
  61. package/src/acceptance-matrix.mjs +84 -0
  62. package/src/browser-evidence.mjs +40 -0
  63. package/src/context-health.mjs +14 -0
  64. package/src/conversations.mjs +302 -0
  65. package/src/engine.mjs +494 -0
  66. package/src/graph.mjs +169 -0
  67. package/src/mcp-diagnostics.mjs +53 -0
  68. package/src/mcp.mjs +151 -0
  69. package/src/model-recovery.mjs +108 -0
  70. package/src/native-tool-recovery.mjs +45 -0
  71. package/src/node-runtime.mjs +13 -0
  72. package/src/orchestration-advisor.mjs +24 -0
  73. package/src/rca.mjs +174 -0
  74. package/src/risk-guidance.mjs +95 -0
  75. package/src/scanner.mjs +303 -0
  76. package/src/security.mjs +793 -0
  77. package/src/semantic-evidence.mjs +144 -0
  78. package/src/skill-discovery.mjs +23 -0
  79. package/src/sqlite-compat.mjs +11 -0
  80. package/src/storage.mjs +455 -0
  81. package/src/tokens.mjs +627 -0
  82. package/src/tools.mjs +164 -0
  83. package/src/verification.mjs +567 -0
  84. package/src/workflow-router.mjs +34 -0
@@ -0,0 +1,567 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import {safeFile,sha256,readSafeBytesFile,readSafeJsonFile} from './security.mjs';
5
+ import {uniqueId} from './storage.mjs';
6
+ import {discoverTestCommands,gitChanges} from './scanner.mjs';
7
+
8
+ import {proposeRiskTests} from './risk-guidance.mjs';
9
+ import {normalizeAcceptanceCriterion,acceptanceCompletion,localEvidencePolicy} from './acceptance-matrix.mjs';
10
+
11
+ // Bounded structural guard: regex case extraction must never count cases outside
12
+ // a complete JUnit document as passing assertions. Unsupported XML fails closed.
13
+ function validJUnitStructure(xml){
14
+ const source=xml.replace(/^\s*<\?xml\s+[^?]*\?>/i,'').trim();
15
+ const stack=[];let rootSeen=false,completed=false,cursor=0;
16
+ const tags=/<(\/?)([A-Za-z][A-Za-z0-9:_.-]*)([^<>]*?)>/g;
17
+ let match;
18
+ while((match=tags.exec(source))!==null){
19
+ const between=source.slice(cursor,match.index);
20
+ if(completed||between.includes('<')||(!stack.length&&between.trim()))return false;
21
+ const closing=match[1]==='/',name=match[2].toLowerCase();
22
+ const selfClosing=!closing&&/\/\s*$/.test(match[3]);
23
+ if(closing){
24
+ if(stack.pop()!==name)return false;
25
+ if(!stack.length)completed=true;
26
+ }else{
27
+ if(!stack.length){if(rootSeen||!['testsuite','testsuites'].includes(name))return false;rootSeen=true;}
28
+ if(name==='testcase'&&stack.at(-1)!=='testsuite')return false;
29
+ if(name==='testsuite'&&stack.length&&!['testsuite','testsuites'].includes(stack.at(-1)))return false;
30
+ if(name==='testsuites'&&stack.length)return false;
31
+ if(['failure','error','skipped'].includes(name)&&stack.at(-1)!=='testcase')return false;
32
+ if(!selfClosing)stack.push(name);
33
+ else if(!stack.length)completed=true;
34
+ }
35
+ cursor=tags.lastIndex;
36
+ }
37
+ const tail=source.slice(cursor);
38
+ return rootSeen&&completed&&!stack.length&&!tail.includes('<')&&!tail.trim();
39
+ }
40
+
41
+ export function parseArtifact(text, filename){
42
+ const ext=filename.toLowerCase().split('.').at(-1), sample=text.slice(0,1200000);
43
+ if(ext==='xml' && /<(?:testsuite|testsuites)\b/.test(sample)){
44
+ // A test report is untrusted local content. Fail closed on XML constructs
45
+ // outside the narrow JUnit schema, and strip non-structural log content
46
+ // BEFORE searching for testcase/failure tags.
47
+ if(/<!DOCTYPE\b|<!ENTITY\b/i.test(sample))return {status:'inconclusive',reason:'Unsupported XML entity or DTD',assertions:0,cases:[]};
48
+ const clean=sample
49
+ .replace(/<!--[\s\S]*?-->/g,'')
50
+ .replace(/<(?:system-out|system-err)\b[^>]*>[\s\S]*?<\/(?:system-out|system-err)\s*>/gi,'')
51
+ .replace(/<!\[CDATA\[[\s\S]*?\]\]>/g,'');
52
+ if(/<!--|<!\[CDATA\[|<(?:system-out|system-err)\b/i.test(clean))
53
+ return {status:'inconclusive',reason:'Incomplete XML comment or log content',assertions:0,cases:[]};
54
+ if(!validJUnitStructure(clean)||!/<\/testsuite\s*>/.test(clean)||/<testcase\b/i.test(clean)===false)
55
+ return {status:'inconclusive',reason:'Incomplete JUnit XML',assertions:0,cases:[]};
56
+ const attrs=text=>Object.fromEntries([...text.matchAll(/([A-Za-z][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)]
57
+ .map(m=>[m[1],m[2]??m[3]]));
58
+ const tags=[...clean.matchAll(/<testcase\b([^>]*)>/g)];
59
+ const cases=[];let cursor=0;
60
+ for(const item of tags){
61
+ const tag=item[0],at=item.index;
62
+ if(at<cursor)return {status:'inconclusive',reason:'Overlapping or malformed JUnit testcases',assertions:cases.length,cases};
63
+ const attr=attrs(item[1]);
64
+ if(!attr.name)return {status:'inconclusive',reason:'JUnit testcase name absent',assertions:cases.length,cases};
65
+ const selfClosing=/\/\s*>$/.test(tag);
66
+ const close=selfClosing?at+tag.length:clean.indexOf('</testcase>',at+tag.length);
67
+ const next=clean.indexOf('<testcase',at+tag.length);
68
+ if(close<0||(!selfClosing&&next>=0&&next<close))
69
+ return {status:'inconclusive',reason:'Unclosed or nested JUnit testcase',assertions:cases.length,cases};
70
+ const body=selfClosing?'':clean.slice(at+tag.length,close);
71
+ cursor=selfClosing?at+tag.length:close+'</testcase>'.length;
72
+ const state=/<(?:failure|error)\b/i.test(body)?'failed':/<skipped\b/i.test(body)?'skipped':'passed';
73
+ cases.push({name:attr.name,state});
74
+ }
75
+ if(/<testcase\b/i.test(clean.slice(cursor))||/<!\[CDATA\[|<!--/.test(clean.slice(cursor)))
76
+ return {status:'inconclusive',reason:'Unparsed JUnit testcase',assertions:cases.length,cases};
77
+ const rootMatch=clean.match(/<testsuites\b([^>]*)>/);
78
+ const rootAttrs=rootMatch?attrs(rootMatch[1]):{};
79
+ const suites=[...clean.matchAll(/<testsuite\b([^>]*)>/g)];
80
+ let expected=NaN,declaredFailed=0,declaredSkipped=0;
81
+ if(rootAttrs.tests!==undefined){
82
+ expected=Number(rootAttrs.tests);
83
+ declaredFailed=Number(rootAttrs.failures||0)+Number(rootAttrs.errors||0);
84
+ declaredSkipped=Number(rootAttrs.skipped||0);
85
+ }else if(suites.length){
86
+ let sum=0,found=false;
87
+ for(const suite of suites){
88
+ const a=attrs(suite[1]);
89
+ if(a.tests!==undefined){found=true;sum+=Number(a.tests)}
90
+ declaredFailed+=Number(a.failures||0)+Number(a.errors||0);
91
+ declaredSkipped+=Number(a.skipped||0);
92
+ }
93
+ expected=found?sum:NaN;
94
+ }
95
+ const failed=cases.filter(c=>c.state==='failed').length,skipped=cases.filter(c=>c.state==='skipped').length;
96
+ if(!cases.length||!Number.isSafeInteger(expected)||expected!==cases.length)
97
+ return {status:'inconclusive',reason:'JUnit count mismatch or missing',assertions:cases.length,cases};
98
+ if(!Number.isSafeInteger(declaredFailed)||!Number.isSafeInteger(declaredSkipped)
99
+ ||declaredFailed!==failed||declaredSkipped!==skipped)
100
+ return {status:'inconclusive',reason:'JUnit declared outcomes disagree with actual cases',assertions:cases.length,cases};
101
+ return {status:failed?'failed':skipped===cases.length?'inconclusive':'passed',
102
+ assertions:cases.length,failed,skipped,format:'junit-xml',cases};
103
+ }
104
+ if(/(?:^|\n)TAP version\s+\d+/.test(sample)||/^(?:ok|not ok)\s+\d+/m.test(sample)){
105
+ const matches=[...sample.matchAll(/^(not ok|ok)\s+(\d+)\b(?:\s*-\s*([^\n#]*))?([^\n]*)$/gm)];
106
+ const cases=matches.map(m=>({
107
+ name:(m[3]||'').trim(),
108
+ number:Number(m[2]),
109
+ state:m[1]==='not ok'?'failed':/#\s*(?:SKIP|TODO)\b/i.test(m[4]||'')?'skipped':'passed'
110
+ }));
111
+ if(/^\s*Bail out!\b/im.test(sample))
112
+ return {status:'failed',reason:'TAP bailout: run aborted',assertions:cases.length,cases};
113
+ const plans=[...sample.matchAll(/^(\d+)\.\.(\d+)\s*(?:#.*)?$/gm)];
114
+ if(plans.length!==1||Number(plans[0][1])!==1||Number(plans[0][2])<1)
115
+ return {status:'inconclusive',reason:'TAP plan missing or invalid',assertions:cases.length,cases};
116
+ const expected=Number(plans[0][2]);
117
+ if(!cases.length||!Number.isSafeInteger(expected)||expected!==cases.length
118
+ ||cases.some((c,i)=>c.number!==i+1))
119
+ return {status:'inconclusive',reason:'TAP assertions are missing, duplicated or out of order',assertions:cases.length,cases};
120
+ const failed=cases.filter(c=>c.state==='failed').length,skipped=cases.filter(c=>c.state==='skipped').length;
121
+ return {status:failed?'failed':skipped===cases.length?'inconclusive':'passed',
122
+ assertions:cases.length,failed,skipped,format:'tap',cases};
123
+ }
124
+ if(ext==='json'){
125
+ try {
126
+ const obj=JSON.parse(sample);
127
+ const validFormats=new Set(['a2a-test-report-v1','verifykit-test-report-v1']);
128
+ if(!validFormats.has(obj?.format)||!Array.isArray(obj.cases)||obj.cases.length<1||obj.cases.length>10000||obj.completed!==true)return {status:'inconclusive',assertions:0,reason:'Unsupported or incomplete report schema',cases:[]};
129
+ const cases=obj.cases.map(c=>({name:String(c.name||'').slice(0,160),state:['passed','failed','skipped'].includes(c.state)?c.state:'unknown'}));
130
+ if(cases.some(c=>!c.name||c.state==='unknown'))return {status:'inconclusive',assertions:cases.length,reason:'Invalid test cases',cases};
131
+ const failed=cases.filter(c=>c.state==='failed').length,skipped=cases.filter(c=>c.state==='skipped').length;
132
+ return {status:failed?'failed':skipped===cases.length?'inconclusive':'passed',assertions:cases.length,failed,skipped,format:obj.format,cases};
133
+ }catch{}
134
+ }
135
+ return {status:'inconclusive',assertions:0,reason:'Unsupported artifact type; require JUnit, TAP, or a2a-test-report-v1',cases:[]};
136
+ }
137
+
138
+ export function planVerification({index,impact,criteria=[],compact=false}){
139
+ if(!Array.isArray(criteria)||criteria.length>40)throw new Error('criteria must be an array of at most 40 items');
140
+ const seen=new Set();const plan=criteria.map(c=>{
141
+ const item=normalizeAcceptanceCriterion(c);
142
+ if(seen.has(item.id))throw new Error('Duplicate criterion');
143
+ seen.add(item.id);
144
+ return item;
145
+ });
146
+ const checks=discoverTestCommands(index);
147
+ const riskGuidance=proposeRiskTests({paths:impact?.changed??[],criteria:plan.map(x=>[x.description,x.given,x.when,x.then].filter(Boolean).join(' ')),compact});
148
+ const highRisk=impact?.risk==='high'||riskGuidance.findings.some(x=>x.priority==='critical');
149
+ // Maintainer discipline is a bounded NOT-REVIEWED checklist, never a quality verdict.
150
+ // It costs no extra tool call and is omitted for unrelated/trivial tasks.
151
+ const maintainerReview=highRisk?{
152
+ status:'not-reviewed',
153
+ required_checks:[
154
+ 'Reproduce defect; failing regression before fix, passing after',
155
+ 'Minimal diff; preserve local conventions and public API compatibility',
156
+ 'Test observable behavior and adversarial boundary, not test names',
157
+ 'Review maintenance/performance cost; no unapproved dependencies'
158
+ ],
159
+ proof:'native-test-and-human-review-required'
160
+ }:null;
161
+ return {criteria:plan,impact:impact?{risk:impact.risk,related_tests:impact.related_tests,unknowns:impact.uncertainty}:null,risk_guidance:riskGuidance,...(maintainerReview?{maintainer_review:maintainerReview}:{}),checks,completion:acceptanceCompletion(plan,[],{planning:true}),execution:'Use existing Antigravity native terminal/browser with its permissions. A2A does not execute commands.',state:'not_run'};
162
+ }
163
+ function aggregate(results){if(results.some(r=>r.status==='failed'))return 'failed';if(results.some(r=>r.status==='blocked'))return 'blocked';if(results.length&&results.every(r=>r.status==='passed'))return 'passed';return 'inconclusive'}
164
+ export function assessVerification(store,wsId,root,rev,criteria,{planId=null}={}){
165
+ // Either the entire verification run and its evidence records are committed,
166
+ // or none are. Invalid later criteria must never leave orphaned passed evidence.
167
+ return store.transaction(()=>{
168
+ if(!Array.isArray(criteria)||criteria.length>40||(!planId&&criteria.length===0))
169
+ throw new Error('Provide 1–40 criteria, or a persisted plan_id with optional evidence bindings');
170
+ let boundRevision=null,requested=criteria;
171
+ if(planId!==null){
172
+ if(typeof planId!=='string'||!/^apl-[A-Za-z0-9-]{8,100}$/.test(planId))throw new Error('Invalid plan_id');
173
+ const saved=store.get('SELECT * FROM acceptance_plans WHERE workspace_id=? AND id=?',wsId,planId);
174
+ if(!saved)throw new Error('Unknown or unauthorized acceptance plan');
175
+ if(sha256(saved.criteria_json)!==saved.manifest_sha)throw new Error('Acceptance plan integrity mismatch');
176
+ const authoritative=JSON.parse(saved.criteria_json);
177
+ if(!Array.isArray(authoritative)||authoritative.length===0||authoritative.length>40)throw new Error('Invalid persisted acceptance plan');
178
+ boundRevision=saved.revision_id;
179
+ const indexed=new Map();
180
+ for(const item of criteria){
181
+ if(!item||typeof item!=='object'||Array.isArray(item)||typeof item.id!=='string'||indexed.has(item.id))throw new Error('Invalid or duplicate plan evidence binding');
182
+ indexed.set(item.id,item);
183
+ }
184
+ const expected=new Set(authoritative.map(c=>c.id));
185
+ if([...indexed.keys()].some(id=>!expected.has(id)))throw new Error('Assessment criterion is not part of the persisted plan');
186
+ requested=authoritative.map(original=>{
187
+ const binding=indexed.get(original.id)||{};
188
+ // The persisted plan controls the meaning of acceptance. Caller may
189
+ // attach evidence but may not silently change its expected behavior.
190
+ for(const key of ['description','given','when','then','evidence_type','viewport','ui_state','reference','source_revision','negative']){
191
+ if(Object.hasOwn(binding,key)&&JSON.stringify(binding[key])!==JSON.stringify(original[key]))
192
+ throw new Error('Acceptance contract changed: '+key);
193
+ }
194
+ return {...original,...(typeof binding.artifact==='string'?{artifact:binding.artifact}:{}),
195
+ ...(typeof binding.test_name==='string'?{test_name:binding.test_name}:{}),
196
+ ...(binding.blocked===true?{blocked:true}:{})};
197
+ });
198
+ }
199
+ const ids=new Set(),results=[],plan=[];
200
+ for(const c of requested){
201
+ if(typeof c==='string')throw new Error('Assessment criteria require an explicit id and named test evidence');
202
+ const criterion=normalizeAcceptanceCriterion(c);
203
+ if(ids.has(criterion.id))throw new Error('Invalid or duplicate criterion ID');
204
+ ids.add(criterion.id);plan.push(criterion);
205
+ let result={id:criterion.id,status:criterion.contract==='acceptance-v1'?'not_tested':'inconclusive',reason:'No evidence artifact'};
206
+ if(typeof c.artifact==='string'){
207
+ const full=safeFile(root,c.artifact);const stat=fs.statSync(full);if(stat.size>1200000)throw new Error('Evidence report exceeds 1.2 MB');
208
+ const bytes=fs.readFileSync(full),hash=sha256(bytes), parsed=parseArtifact(bytes.toString('utf8'),c.artifact);
209
+ // An explicit test name prevents an arbitrary passing suite from proving an unrelated criterion.
210
+ const matchName=typeof c.test_name==='string'?c.test_name.trim():'';
211
+ let derivedStatus=parsed.status, reason=parsed.reason||null;
212
+ if(!matchName){derivedStatus='inconclusive';reason='test_name is required to bind the criterion to actual test cases; use * only for legacy whole-suite checks';}
213
+ else if(criterion.contract==='acceptance-v1'&&matchName==='*'){derivedStatus='inconclusive';reason='Structured acceptance requires an exact named test case';}
214
+ else if(matchName!=='*'){
215
+ const selected=parsed.cases.filter(t=>t.name===matchName);
216
+ if(!selected.length){derivedStatus='inconclusive';reason='Named test case was not found in report';}
217
+ else if(selected.some(t=>t.state==='failed')){derivedStatus='failed';reason='Named test case failed';}
218
+ else if(selected.some(t=>t.state==='skipped')){derivedStatus='inconclusive';reason='Named test case was skipped';}
219
+ else if(parsed.status==='inconclusive'){derivedStatus='inconclusive';reason=parsed.reason||'Report incomplete';}
220
+ else if(parsed.status==='failed'){derivedStatus='failed';reason='The same test suite contains failures';}
221
+ else {derivedStatus='passed';reason=null;}
222
+ }
223
+ if((criterion.source_revision&&criterion.source_revision!==rev)||(boundRevision&&boundRevision!==rev)){
224
+ derivedStatus='stale';reason='Acceptance plan or explicit source revision differs from current workspace revision';
225
+ }
226
+ if(derivedStatus==='passed'&&!localEvidencePolicy(criterion).locally_attestable){
227
+ derivedStatus='inconclusive';reason=localEvidencePolicy(criterion).reason;
228
+ }
229
+ const evidenceId=uniqueId('ev');
230
+ store.run('INSERT INTO evidence VALUES(?,?,?,?,?,?,?,?,?,?)',evidenceId,wsId,rev,criterion.id,derivedStatus==='stale'?'inconclusive':derivedStatus,parsed.format||'unknown',c.artifact,hash,JSON.stringify({assertions:parsed.assertions||0,failed:parsed.failed||0,skipped:parsed.skipped||0,reason,test_name:matchName,requested_evidence_type:criterion.evidence_type||'unspecified',trust:'local-report-not-cryptographically-attested'}),new Date().toISOString());
231
+ result={id:criterion.id,status:derivedStatus,evidence_id:evidenceId,assertions:parsed.assertions||0,...(reason?{reason}:{})};
232
+ }else if(c.blocked===true){result={id:criterion.id,status:'blocked',reason:'Required environment unavailable; no runnable evidence supplied'}}
233
+ if(boundRevision&&boundRevision!==rev){result={id:criterion.id,status:'stale',reason:'Persisted acceptance plan revision differs from current workspace source'};}
234
+ results.push(result);
235
+ }
236
+ const verdict=aggregate(results),runId=uniqueId('run');store.run('INSERT INTO runs VALUES(?,?,?,?,?,?)',runId,wsId,rev,verdict,JSON.stringify(results),new Date().toISOString());
237
+ return {run_id:runId,revision:rev,verdict,criteria:results,plan_id:planId||null,scope_bound:Boolean(planId),scope_source_revision:boundRevision,completion:acceptanceCompletion(plan,results),proof_scope:'named-machine-test-assertions-only',release_ready:false,semantic_requirements_proven:false,limits:['A passing JUnit/TAP/JSON suite is NOT a release-readiness or semantic concurrency/offline/security verdict.','Only independently signed acceptance evidence via assess_release can report release eligibility.','Report parsing does not attest origin or test execution authenticity.',...(!planId?['Acceptance scope is unbound: omitted planned scenarios cannot be detected without plan_id.']:[])]};
238
+ });
239
+ }
240
+ export function listEvidence(store,wsId,root,currentRevision,{limit=20,id}={}){
241
+ const check=x=>{let artifact_intact=false;try{const p=safeFile(root,x.artifact_path),bytes=readSafeBytesFile(p,{maxBytes:4*1024*1024});artifact_intact=bytes.ok&&sha256(bytes.bytes)===x.artifact_sha}catch{};return {fresh:x.revision_id===currentRevision&&artifact_intact,artifact_intact}};
242
+ if(id){const e=store.get('SELECT * FROM evidence WHERE workspace_id=? AND id=?',wsId,id);if(!e)return {found:false};return {...e,...check(e),metadata:JSON.parse(e.metadata_json),metadata_json:undefined}}
243
+ const n=Math.max(1,Math.min(50,Number(limit)||20));
244
+ return {items:store.all('SELECT id,criterion_id,status,artifact_path,artifact_sha,revision_id,created_at FROM evidence WHERE workspace_id=? ORDER BY created_at DESC LIMIT ?',wsId,n).map(x=>{const state=check(x);return {id:x.id,criterion_id:x.criterion_id,status:x.status,artifact_path:x.artifact_path,revision_id:x.revision_id,created_at:x.created_at,...state}})};
245
+ }
246
+ export function freshness(store,wsId,root,revision){const items=store.all('SELECT id,revision_id,criterion_id,status,artifact_path,artifact_sha FROM evidence WHERE workspace_id=? ORDER BY created_at DESC LIMIT 30',wsId);return items.map(x=>{let artifact_intact=false;try{const bytes=readSafeBytesFile(safeFile(root,x.artifact_path),{maxBytes:4*1024*1024});artifact_intact=bytes.ok&&sha256(bytes.bytes)===x.artifact_sha}catch{};return {id:x.id,revision_id:x.revision_id,criterion_id:x.criterion_id,status:x.status,artifact_intact,fresh:x.revision_id===revision&&artifact_intact}})}
247
+
248
+ export const CANDIDATE_ARTIFACTS = [
249
+ 'report.xml',
250
+ 'junit.xml',
251
+ 'test-results.xml',
252
+ 'test-report.xml',
253
+ 'junit-report.xml',
254
+ 'tests.tap',
255
+ 'test.tap',
256
+ 'report.tap',
257
+ 'test-results.json',
258
+ 'a2a-test-report.json',
259
+ 'test-results/junit.xml',
260
+ 'test-results/test-results.xml',
261
+ 'coverage/junit.xml',
262
+ 'reports/junit.xml',
263
+ 'reports/test-results.xml',
264
+ 'build/test-results/test/TESTS-TestSuites.xml'
265
+ ];
266
+
267
+ export function computeSourceFingerprint(root, changedFiles = []) {
268
+ const fileHashes = [];
269
+ for (const rel of changedFiles) {
270
+ try {
271
+ const full = safeFile(root, rel);
272
+ fileHashes.push(`${rel}:${sha256(fs.readFileSync(full))}`);
273
+ } catch {}
274
+ }
275
+ fileHashes.sort();
276
+ return sha256(fileHashes.join('\n'));
277
+ }
278
+
279
+ export function nativeRunProvenance(store,root,changedFiles,relReport,reportHash,currentRevision){
280
+ // This is a local hook-derived record, not a cryptographic attestation.
281
+ if(!changedFiles.length || !store?.base)return {matched:false,reason:'No changed source files were bound to the native run'};
282
+ try{
283
+ const sameWorkspace=(a,b)=>a&&b&&fs.realpathSync(a)===fs.realpathSync(b);
284
+ const recordFile=readSafeJsonFile(path.join(store.base,'last-test-run.json'),{maxBytes:128*1024});
285
+ const activeFile=readSafeJsonFile(path.join(store.base,'active-session.json'),{maxBytes:128*1024});
286
+ if(!recordFile.ok||!activeFile.ok)return {matched:false,reason:'Native run metadata is missing or unsafe'};
287
+ const record=recordFile.value;
288
+ const active=activeFile.value.latest;
289
+ if(!active?.conversationId || active.conversationId!==record.conversationId
290
+ || !Array.isArray(active.workspacePaths)
291
+ || !active.workspacePaths.some(w=>{try{return sameWorkspace(w,root)}catch{return false}})){
292
+ return {matched:false,reason:'Native-run record is not bound to the active workspace session'};
293
+ }
294
+ if(record.kind!=='native-test-tool-completed'||record.succeeded!==true||!sameWorkspace(record.workspace,root)){
295
+ return {matched:false,reason:'No successful native test run recorded for this workspace'};
296
+ }
297
+ const age=Date.now()-Date.parse(record.updatedAt||'');
298
+ if(!Number.isFinite(age)||age< -2000||age>15*60*1000)return {matched:false,reason:'Native run is outside freshness window'};
299
+ if(!record.source_revision||record.source_revision!==currentRevision)return {matched:false,reason:'Native test run is not bound to the current complete source revision'};
300
+ if(record.report_bindings?.[relReport]!==true)return {matched:false,reason:'Report was not explicitly bound to the native test command'};
301
+ if(record.report_hashes?.[relReport]!==reportHash)return {matched:false,reason:'Report hash differs from the last native test run'};
302
+ for(const rel of changedFiles){
303
+ const expected=record.source_hashes?.[rel];
304
+ if(!expected || expected!==sha256(fs.readFileSync(safeFile(root,rel)))){
305
+ return {matched:false,reason:'Changed source does not match the native test run'};
306
+ }
307
+ }
308
+ return {matched:true,reason:null};
309
+ }catch{return {matched:false,reason:'Native run provenance cannot be read'}}
310
+ }
311
+
312
+ // Outcome describes the handoff, not independently proven user acceptance.
313
+ export function handoffOutcome(status,{verified=false,testsPassed=false}={}){
314
+ if(status==='stale')return 'stale';
315
+ if(status==='failed')return 'failed';
316
+ if(verified)return 'completed';
317
+ if(testsPassed||status==='blocked')return 'partial';
318
+ return 'unknown';
319
+ }
320
+ export function verifyHandoff(store,wsId,root,rev,{
321
+ worker_name=null,
322
+ changed=[],
323
+ artifact=null,
324
+ criteria=[],
325
+ allow_stale=false
326
+ }={}){
327
+ let detectedChanged=Array.isArray(changed)&&changed.length>0?changed:gitChanges(root);
328
+ if(!Array.isArray(detectedChanged)) detectedChanged=[];
329
+ detectedChanged=detectedChanged.map(p=>String(p).replaceAll('\\','/'));
330
+
331
+ let maxSourceMtimeMs=0;
332
+ for(const rel of detectedChanged){
333
+ try{
334
+ const full=safeFile(root,rel);
335
+ const st=fs.statSync(full);
336
+ if(st.mtimeMs>maxSourceMtimeMs) maxSourceMtimeMs=st.mtimeMs;
337
+ }catch{}
338
+ }
339
+
340
+ let relArtifact=artifact;
341
+ if(!relArtifact){
342
+ let newestTime=0;
343
+ for(const cand of CANDIDATE_ARTIFACTS){
344
+ try{
345
+ const full=safeFile(root,cand);
346
+ const st=fs.statSync(full);
347
+ if(st.isFile()&&st.mtimeMs>newestTime){
348
+ newestTime=st.mtimeMs;
349
+ relArtifact=cand;
350
+ }
351
+ }catch{}
352
+ }
353
+ }
354
+
355
+ if(!relArtifact){
356
+ return {
357
+ operation:'verify_handoff',
358
+ verified:false,
359
+ status:'missing_evidence',
360
+ handoff_outcome:'unknown',
361
+ source_freshness:'unknown',
362
+ worker:worker_name||null,
363
+ revision:rev,
364
+ changed_files:detectedChanged,
365
+ reason:'No machine-readable test report artifact found (JUnit XML, TAP, or JSON). Subagents must run tests with a machine reporter before reporting completion.',
366
+ actionable_fix:'Run native tests with a reporter flag: npm test -- --reporter=tap, pytest --junitxml=report.xml, go test -v ./... > tests.tap, or php artisan test --log-junit=report.xml'
367
+ };
368
+ }
369
+
370
+ const full=safeFile(root,relArtifact);
371
+ const stat=fs.statSync(full);
372
+ if(stat.size>1200000)throw new Error('Evidence report exceeds 1.2 MB');
373
+
374
+ const isFresh=maxSourceMtimeMs===0||(stat.mtimeMs>=maxSourceMtimeMs-1500); // allow_stale never authorizes a PASS
375
+ if(!isFresh){
376
+ return {
377
+ operation:'verify_handoff',
378
+ verified:false,
379
+ status:'stale',
380
+ handoff_outcome:'stale',
381
+ source_freshness:'stale',
382
+ worker:worker_name||null,
383
+ revision:rev,
384
+ artifact:relArtifact,
385
+ fresh:false,
386
+ changed_files:detectedChanged,
387
+ reason:'Test evidence artifact is stale: source files were modified after the test report was generated.',
388
+ actionable_fix:'Re-run native test suite to generate a fresh report matching the latest code changes.'
389
+ };
390
+ }
391
+
392
+ const bytes=fs.readFileSync(full);
393
+ const hash=sha256(bytes);
394
+ const parsed=parseArtifact(bytes.toString('utf8'),path.basename(relArtifact));
395
+
396
+ let derivedStatus=parsed.status;
397
+ let reason=parsed.reason||null;
398
+ let failedCases=[];
399
+
400
+ if(parsed.status==='failed'){
401
+ derivedStatus='failed';
402
+ failedCases=parsed.cases.filter(c=>c.state==='failed').slice(0,10).map(c=>c.name);
403
+ reason=`Test report contains ${parsed.failed} failing test case(s).`;
404
+ }else if(parsed.status==='inconclusive'){
405
+ derivedStatus='inconclusive';
406
+ reason=parsed.reason||'Test report incomplete or contains 0 assertions.';
407
+ }else if((parsed.assertions||0)===0){
408
+ derivedStatus='inconclusive';
409
+ reason='No test assertions found in report.';
410
+ }
411
+
412
+ let criteriaResults=[];
413
+ const hasExplicitCriteria = Array.isArray(criteria) && criteria.length > 0;
414
+ const criteriaSeen=new Set();
415
+ if(hasExplicitCriteria){
416
+ if(criteria.length>40)throw new Error('Too many handoff criteria');
417
+ for(const c of criteria){
418
+ if(typeof c!=='string' && (!c||typeof c!=='object'||Array.isArray(c)))throw new Error('Invalid handoff criterion');
419
+ const typed=typeof c==='string'?null:normalizeAcceptanceCriterion(c);
420
+ const cid=typed?.id??c.trim();
421
+ if(!cid||criteriaSeen.has(cid))throw new Error('Invalid or duplicate handoff criterion ID');
422
+ criteriaSeen.add(cid);
423
+ const testName=typeof c==='object'&&typeof c.test_name==='string'?c.test_name.trim():(typeof c==='string'?c.trim():'*');
424
+ let cStatus='passed';
425
+ let cReason=null;
426
+ if(testName==='*'){
427
+ cStatus='inconclusive';
428
+ cReason='Handoff verification requires an exact named testcase, not a wildcard';
429
+ }else{
430
+ const matching=parsed.cases.filter(tc=>tc.name===testName); // exact-case binding prevents ambiguous PASS
431
+ if(!matching.length){
432
+ cStatus='inconclusive';
433
+ cReason=`Test case "${testName}" not found in report`;
434
+ }else if(matching.some(tc=>tc.state==='failed')){
435
+ cStatus='failed';
436
+ cReason=`Test case "${testName}" failed`;
437
+ }else if(matching.some(tc=>tc.state==='skipped')){
438
+ cStatus='inconclusive';
439
+ cReason=`Test case "${testName}" was skipped`;
440
+ }
441
+ }
442
+ if(typed?.source_revision&&typed.source_revision!==rev){
443
+ cStatus='inconclusive';cReason='Handoff criterion source revision is stale';
444
+ }
445
+ if(cStatus==='passed'&&!localEvidencePolicy(typed).locally_attestable){
446
+ cStatus='inconclusive';cReason=localEvidencePolicy(typed).reason;
447
+ }
448
+ criteriaResults.push({id:cid,status:cStatus,...(typed?.evidence_type?{evidence_type:typed.evidence_type}:{}),...(cReason?{reason:cReason}:{})});
449
+ }
450
+ if(criteriaResults.some(r=>r.status==='failed')){
451
+ derivedStatus='failed';
452
+ reason='One or more required criteria failed.';
453
+ }else if(criteriaResults.some(r=>r.status==='inconclusive')){
454
+ derivedStatus='inconclusive';
455
+ reason='One or more required criteria could not be verified.';
456
+ }
457
+ }
458
+
459
+ const sourceFingerprint=computeSourceFingerprint(root,detectedChanged);
460
+
461
+ const testsPassed=parsed.status==='passed'&&parsed.failed===0&&(parsed.assertions||0)>0;
462
+ const provenance=nativeRunProvenance(store,root,detectedChanged,relArtifact,hash,rev);
463
+
464
+ let deliverableVerified=false;
465
+ if(!hasExplicitCriteria){
466
+ deliverableVerified=false;
467
+ if(testsPassed){
468
+ derivedStatus='unverified_deliverable';
469
+ reason='Test suite passed, but no acceptance criteria were mapped to test cases proving the deliverable.';
470
+ }
471
+ }else{
472
+ deliverableVerified=testsPassed&&isFresh&&derivedStatus==='passed'&&provenance.matched;
473
+ if(testsPassed&&isFresh&&derivedStatus==='passed'&&!provenance.matched){
474
+ derivedStatus='unattested_report';
475
+ reason='Report passed named criteria, but evidence is not bound to a recent native test execution: '+provenance.reason;
476
+ }
477
+ }
478
+
479
+ const verified=deliverableVerified;
480
+
481
+ const dbStatus=(derivedStatus==='passed')?'passed':(derivedStatus==='failed')?'failed':(derivedStatus==='blocked')?'blocked':'inconclusive';
482
+
483
+ const evidenceId=uniqueId('ev');
484
+ store.run('INSERT INTO evidence VALUES(?,?,?,?,?,?,?,?,?,?)',
485
+ evidenceId,
486
+ wsId,
487
+ rev,
488
+ worker_name?`teamwork:${worker_name}`:'teamwork_handoff',
489
+ dbStatus,
490
+ parsed.format||'unknown',
491
+ relArtifact,
492
+ hash,
493
+ JSON.stringify({
494
+ worker_name:worker_name||'worker',
495
+ changed_files:detectedChanged,
496
+ source_fingerprint:sourceFingerprint,
497
+ assertions:parsed.assertions||0,
498
+ failed:parsed.failed||0,
499
+ skipped:parsed.skipped||0,
500
+ fresh:isFresh,
501
+ tests_passed:testsPassed,
502
+ deliverable_verified:deliverableVerified,
503
+ verified,
504
+ trust:provenance.matched?'native-hook-local-evidence':'unattested-local-report',
505
+ provenance_matched:provenance.matched,
506
+ provenance_reason:provenance.reason,
507
+ allow_stale_requested:allow_stale===true,
508
+ evidence_limit:'Local run metadata is not cryptographically attested'
509
+ }),
510
+ new Date().toISOString()
511
+ );
512
+
513
+ const runId=uniqueId('run');
514
+ store.run('INSERT INTO runs VALUES(?,?,?,?,?,?)',
515
+ runId,
516
+ wsId,
517
+ rev,
518
+ dbStatus,
519
+ JSON.stringify([{
520
+ operation:'verify_handoff',
521
+ worker:worker_name,
522
+ artifact:relArtifact,
523
+ source_fingerprint:sourceFingerprint,
524
+ assertions:parsed.assertions||0,
525
+ failed:parsed.failed||0,
526
+ tests_passed:testsPassed,
527
+ deliverable_verified:deliverableVerified,
528
+ verified,
529
+ criteria:criteriaResults
530
+ }]),
531
+ new Date().toISOString()
532
+ );
533
+
534
+ return {
535
+ operation:'verify_handoff',
536
+ verified,
537
+ verified_scope:verified?'local-named-machine-assertions-only':'none',
538
+ independently_attested:false,
539
+ tests_passed:testsPassed,
540
+ deliverable_verified:deliverableVerified,
541
+ status:derivedStatus,
542
+ handoff_outcome:handoffOutcome(derivedStatus,{verified,testsPassed}),
543
+ source_freshness:isFresh?'current-by-mtime-only':'stale',
544
+ worker:worker_name||null,
545
+ revision:rev,
546
+ source_fingerprint:sourceFingerprint,
547
+ artifact:relArtifact,
548
+ artifact_sha:hash,
549
+ assertions:parsed.assertions||0,
550
+ failed:parsed.failed||0,
551
+ skipped:parsed.skipped||0,
552
+ format:parsed.format,
553
+ fresh:isFresh,
554
+ changed_files:detectedChanged,
555
+ run_id:runId,
556
+ evidence_id:evidenceId,
557
+ summary:deliverableVerified
558
+ ?`Worker ${worker_name||'task'} local named test assertions verified (${parsed.assertions} passed, ${parsed.skipped||0} skipped). This is not independent deliverable or runtime acceptance.`
559
+ :testsPassed
560
+ ?`Worker ${worker_name||'task'} tests passed (${parsed.assertions} assertions), but deliverable is unverified: acceptance criteria must be mapped to test cases.`
561
+ :`Worker ${worker_name||'task'} handoff unverified (${derivedStatus}): ${reason||'Test requirements not satisfied.'}`,
562
+ ...(reason?{reason}:{}),
563
+ ...(failedCases.length?{failed_cases:failedCases}:{}),
564
+ ...(criteriaResults.length?{criteria:criteriaResults}:{}),
565
+ ...(!deliverableVerified?{actionable_fix:hasExplicitCriteria?'Ensure all criteria map to passing test cases and tests are rerun after final edits.':'Specify acceptance criteria to verify that test cases prove the intended deliverable.'}:{})
566
+ };
567
+ }
@@ -0,0 +1,34 @@
1
+ // Explicit, deterministic workflow advice. No model calls, tools, or settings writes.
2
+ const PROFILES=new Set(['economy','balanced','deep-review']);
3
+ const TASKS=new Set(['simple','cross-file','change-impact','verification','recovery']);
4
+ const RISKS=new Set(['low','medium','high','critical']);
5
+ export function routeWorkflow({profile='balanced',task='simple',risk='low',uncertainty=false,scopeKnown=true,hasNamedEvidence=false}={}){
6
+ if(!PROFILES.has(profile)||!TASKS.has(task)||!RISKS.has(risk)||
7
+ typeof uncertainty!=='boolean'||typeof scopeKnown!=='boolean'||typeof hasNamedEvidence!=='boolean')
8
+ throw new Error('Invalid workflow route request');
9
+ const baseline={profile,task,risk,mode:'native-first',automatic_tool_calls:0,
10
+ requires_user_approval:false,model_switch:false,estimated_token_savings:null,provider_usage:null,
11
+ selection_basis:'Caller-declared task, risk and uncertainty; not independently verified or an instruction to auto-call MCP.'};
12
+ let operation=null,reason='Native context is sufficient or this task does not require PILAH.';
13
+ if(task!=='simple'&&uncertainty&&(task==='cross-file'||!scopeKnown)){
14
+ operation='pilah_context';reason='Targeted code graph query may reduce uncertainty across files.';
15
+ } else if(task==='change-impact'&&(uncertainty||(risk!=='low'&&profile!=='economy'))){
16
+ operation='pilah_impact';reason=uncertainty
17
+ ?'Scoped change impact may expose dependent files and tests.'
18
+ :'A risk-aware impact summary is potentially useful for the scoped change.';
19
+ } else if(task==='verification'&&['high','critical'].includes(risk)&&profile==='deep-review'){
20
+ operation='pilah_verify';reason='A high-risk acceptance plan is warranted; no local test is counted as release proof.';
21
+ } else if(task==='recovery'&&['high','critical'].includes(risk)&&profile==='deep-review'){
22
+ operation='pilah_evidence';reason='Opt-in model recovery may be helpful after a verified failure; no automatic retries.';
23
+ }
24
+ if(task==='simple'){operation=null;reason='Simple tasks remain native-only regardless of declared uncertainty.';}
25
+ if(operation&&(!scopeKnown||task==='cross-file')&&operation!=='pilah_context'){
26
+ operation='pilah_context';reason='Determine the scope before considering other PILAH operations.';
27
+ }
28
+ // Deep review may suggest more verification, but cannot authorize a second call.
29
+ return {...baseline,proposal:operation??'native-only',max_initial_a2a_calls:operation?1:0,
30
+ reason,needs_workspace_permission:!!operation,needs_named_test_evidence:false,
31
+ named_evidence_required_for_assessment:operation==='pilah_verify',
32
+ additional_calls:'Only after a new, explicit uncertainty; never automatically chained.',
33
+ caveat:'A routing recommendation is not measured token or quality improvement.'};
34
+ }