@aliip/pilah 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) 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/AB_EVALUATION.md +62 -0
  6. package/docs/ACCEPTANCE_GATE.md +41 -0
  7. package/docs/ADAPTIVE_RCA_WORKFLOW.md +93 -0
  8. package/docs/AGENT_DECISION_REVIEW.md +17 -0
  9. package/docs/AGENT_TRACE_BENCHMARK.md +17 -0
  10. package/docs/ALWAYS_ON_5_WHYS.md +75 -0
  11. package/docs/ARCHITECTURE.md +43 -0
  12. package/docs/BEHAVIORAL_5_WHYS_V2_0_1.md +117 -0
  13. package/docs/CHECKPOINT_RECOVERY.md +86 -0
  14. package/docs/CI_EFFICIENCY.md +63 -0
  15. package/docs/COMPATIBILITY.md +84 -0
  16. package/docs/CONTRACTS.md +177 -0
  17. package/docs/CONVERSATION_USAGE.md +52 -0
  18. package/docs/ENGINEERING_METHOD.md +68 -0
  19. package/docs/HOST_VALIDATION.md +35 -0
  20. package/docs/INDEPENDENT_ACCEPTANCE_RUNBOOK.md +72 -0
  21. package/docs/INTERVENTION_LEDGER.md +25 -0
  22. package/docs/MAIN_VALIDATION_BACKLOG.md +19 -0
  23. package/docs/NATIVE_FIRST_WORKFLOW.md +27 -0
  24. package/docs/OPEN_SOURCE_ENGINEERING_STANDARDS.md +62 -0
  25. package/docs/ORCHESTRATION_ADVISOR.md +36 -0
  26. package/docs/PRE_VNEXT_INTEGRATION.md +27 -0
  27. package/docs/PRIVATE_BENCHMARK_EXPORT.md +14 -0
  28. package/docs/README.md +58 -0
  29. package/docs/RELEASE.md +33 -0
  30. package/docs/RELEASE_AUTHORIZATION.md +33 -0
  31. package/docs/RISK_GUIDANCE.md +18 -0
  32. package/docs/SECURITY.md +76 -0
  33. package/docs/SECURITY_RELIABILITY_AUDIT_V2_0_1.md +55 -0
  34. package/docs/SEMANTIC_EVIDENCE.md +27 -0
  35. package/docs/SOURCES.md +13 -0
  36. package/docs/STOCKROOM_BENCHMARK_RECHECK_2026_11_18.md +53 -0
  37. package/docs/TOKEN_EFFICIENCY.md +71 -0
  38. package/docs/TOKEN_PROVENANCE.md +15 -0
  39. package/docs/V2_0_1_TRACEABILITY.md +66 -0
  40. package/hooks.json +45 -0
  41. package/mcp_config.json +16 -0
  42. package/package.json +31 -4
  43. package/plugin.json +27 -0
  44. package/rules/AGENTS.md +2 -0
  45. package/schemas/database.sql +84 -0
  46. package/schemas/mcp-tools.json +552 -0
  47. package/scripts/a2a.mjs +343 -0
  48. package/scripts/check-release.mjs +42 -0
  49. package/scripts/check-syntax.mjs +30 -0
  50. package/scripts/checkpoint.mjs +50 -0
  51. package/scripts/compare-agent-traces.mjs +53 -0
  52. package/scripts/context-guardian.mjs +132 -0
  53. package/scripts/evaluate-acceptance.mjs +110 -0
  54. package/scripts/export-benchmark.mjs +31 -0
  55. package/scripts/generate-contracts.mjs +6 -0
  56. package/scripts/hook.mjs +406 -0
  57. package/scripts/host-check.mjs +40 -0
  58. package/scripts/intervention-ledger.mjs +94 -0
  59. package/scripts/pilah.mjs +3 -0
  60. package/scripts/release-authorization.mjs +137 -0
  61. package/scripts/review-agent-decisions.mjs +34 -0
  62. package/scripts/semantic-evidence.mjs +15 -0
  63. package/scripts/verifykit.mjs +3 -0
  64. package/skills/pilah/SKILL.md +24 -0
  65. package/src/acceptance-matrix.mjs +84 -0
  66. package/src/browser-evidence.mjs +40 -0
  67. package/src/context-health.mjs +14 -0
  68. package/src/conversations.mjs +302 -0
  69. package/src/engine.mjs +494 -0
  70. package/src/graph.mjs +169 -0
  71. package/src/mcp-diagnostics.mjs +53 -0
  72. package/src/mcp.mjs +151 -0
  73. package/src/model-recovery.mjs +108 -0
  74. package/src/native-tool-recovery.mjs +45 -0
  75. package/src/node-runtime.mjs +13 -0
  76. package/src/orchestration-advisor.mjs +24 -0
  77. package/src/rca.mjs +174 -0
  78. package/src/risk-guidance.mjs +95 -0
  79. package/src/scanner.mjs +303 -0
  80. package/src/security.mjs +793 -0
  81. package/src/semantic-evidence.mjs +144 -0
  82. package/src/skill-discovery.mjs +23 -0
  83. package/src/sqlite-compat.mjs +11 -0
  84. package/src/storage.mjs +455 -0
  85. package/src/tokens.mjs +627 -0
  86. package/src/tools.mjs +164 -0
  87. package/src/verification.mjs +567 -0
  88. package/src/workflow-router.mjs +34 -0
@@ -0,0 +1,137 @@
1
+ #!/usr/bin/env node
2
+ // Fail-closed publishing gate. External acceptance material is supplied by an
3
+ // independently controlled CI environment, not read from repository sources.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import crypto from 'node:crypto';
7
+ import {execFileSync} from 'node:child_process';
8
+ import {fileURLToPath} from 'node:url';
9
+ import {assessRelease} from './evaluate-acceptance.mjs';
10
+
11
+ const SHA=/^[a-f0-9]{40}$/;
12
+ const digest=x=>typeof x==='string'&&/^[a-f0-9]{64}$/i.test(x);
13
+ const check=(ok,msg)=>{if(!ok)throw new Error(msg)};
14
+ const isObject=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
15
+ const CANONICAL_REPOS=['alifakbxr/pilah','alifakbxr/a2a'];
16
+ const REQUIRED_SCENARIOS=Array.from({length:18},(_,i)=>'F'+String(i+1).padStart(2,'0'));
17
+
18
+ // Canonicalize the complete unsigned manifest, not only commit metadata.
19
+ export function releaseManifestDigest(manifest){
20
+ const canonical=value=>Array.isArray(value)?value.map(canonical):
21
+ value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value;
22
+ const {release_approval,...unsigned}=manifest;
23
+ return crypto.createHash('sha256').update(JSON.stringify(canonical(unsigned))).digest('hex');
24
+ }
25
+ export function releaseApprovalPayload({release_target,revision,approved_at,manifest_sha256}){
26
+ return JSON.stringify({
27
+ schema:'a2a-release-approval-v1',
28
+ repository:release_target.repository,commit_sha:release_target.commit_sha,
29
+ version:release_target.version,revision,manifest_sha256,
30
+ acceptance_registry_sha256:release_target.acceptance_registry_sha256,
31
+ real_antigravity_validation:release_target.real_antigravity_validation,
32
+ privacy_reviewed:release_target.privacy_reviewed,
33
+ repeated_benchmark_verified:release_target.repeated_benchmark_verified,
34
+ approved_at
35
+ });
36
+ }
37
+ function validReleaseApproval(manifest,trustKeys){
38
+ const approval=manifest.release_approval,keys=trustKeys;
39
+ if(!isObject(approval)||typeof approval.key_id!=='string'||
40
+ typeof approval.signature!=='string'||!/^[a-zA-Z0-9+/]{85,86}==$/.test(approval.signature)||
41
+ typeof approval.approved_at!=='string'||!Number.isFinite(Date.parse(approval.approved_at)))return false;
42
+ const key=Object.hasOwn(keys,approval.key_id)?keys[approval.key_id]:null;
43
+ if(typeof key!=='string')return false;
44
+ const digest=releaseManifestDigest(manifest);
45
+ if(approval.manifest_sha256!==digest)return false;
46
+ const approvedAt=Date.parse(approval.approved_at);
47
+ if(approvedAt>Date.now()+5*60_000||approvedAt<Date.now()-90*24*60*60_000)return false;
48
+ try{
49
+ const publicKey=crypto.createPublicKey(key);
50
+ if(publicKey.asymmetricKeyType!=='ed25519')return false;
51
+ const signature=Buffer.from(approval.signature,'base64');
52
+ return signature.length===64&&crypto.verify(
53
+ null,Buffer.from(releaseApprovalPayload({
54
+ release_target:manifest.release_target,revision:manifest.revision,
55
+ approved_at:approval.approved_at,manifest_sha256:digest
56
+ })),publicKey,signature);
57
+ }catch{return false}
58
+ }
59
+
60
+ export function assertPublishAuthorized({
61
+ repository,eventName,ref,checkoutSha,mainSha,approvedSha,packageVersion,
62
+ manifest,trustKeys,registry
63
+ }={}){
64
+ check(CANONICAL_REPOS.includes(repository),'Publishing permitted only from the canonical repository');
65
+ check(SHA.test(checkoutSha||'')&&SHA.test(mainSha||'')&&checkoutSha===mainSha,'Release must exactly match the current main HEAD');
66
+ check(SHA.test(approvedSha||'')&&approvedSha===checkoutSha,'Independent maintainer-approved release commit is missing or differs');
67
+ check(typeof packageVersion==='string'&&/^\d+\.\d+\.\d+$/.test(packageVersion),'Invalid package version');
68
+ if(eventName==='push'||eventName==='release'){
69
+ check(ref==='refs/tags/v'+packageVersion,'Published tag must exactly match the package version');
70
+ }else{
71
+ check(eventName==='workflow_dispatch'&&ref==='refs/heads/main','Manual publishing is permitted only from main');
72
+ }
73
+ check(isObject(manifest)&&isObject(manifest.release_target),'Externally supplied release evidence is required');
74
+ check(manifest.release_target.repository===repository&&
75
+ manifest.release_target.commit_sha===checkoutSha&&
76
+ manifest.release_target.version===packageVersion,'Release evidence does not bind to the exact commit and version');
77
+ check(isObject(registry)&&registry.schema==='a2a-acceptance-registry-v1'&&
78
+ Array.isArray(registry.scenarios),'Independent frozen acceptance registry missing');
79
+ const ids=registry.scenarios.map(x=>x?.id);
80
+ check(ids.length>=REQUIRED_SCENARIOS.length&&REQUIRED_SCENARIOS.every(x=>ids.includes(x)),
81
+ 'External acceptance registry must include all 18 required STOCKROOM scenarios');
82
+ check(isObject(trustKeys)&&Object.keys(trustKeys).length>0,'External evaluator trust keys required');
83
+ check(digest(manifest.release_target.acceptance_registry_sha256),
84
+ 'Acceptance registry digest must be pinned to release evidence');
85
+ const registryDigest=crypto.createHash('sha256').update(JSON.stringify(registry)).digest('hex');
86
+ check(manifest.release_target.acceptance_registry_sha256===registryDigest,
87
+ 'External registry differs from the release evidence binding');
88
+ const assessment=assessRelease(manifest,{trustKeys,requiredScenarios:registry.scenarios});
89
+ check(assessment.release_ready===true&&assessment.scope_verified===true,
90
+ 'Independent machine-evidence assessment is not release eligible');
91
+ check(assessment.scenarios.total>=REQUIRED_SCENARIOS.length,'Missing required acceptance cases');
92
+ check(manifest.release_target.real_antigravity_validation===true &&
93
+ manifest.release_target.privacy_reviewed===true &&
94
+ manifest.release_target.repeated_benchmark_verified===true,
95
+ 'Release lacks externally approved Antigravity, privacy or repeated benchmark gates');
96
+ check(validReleaseApproval(manifest,trustKeys),
97
+ 'Missing, expired or invalid independent Ed25519 release approval for this exact candidate');
98
+ return {status:'authorized',release_commit:checkoutSha,package_version:packageVersion,
99
+ verified_scenarios:assessment.scenarios.passed,registry_sha256:registryDigest,
100
+ note:'This verifies externally supplied attestations, not the honesty of test execution.'};
101
+ }
102
+
103
+ function readExternalJson(name,{maxBytes=64*1024}={}){
104
+ const encoded=process.env[name];
105
+ check(typeof encoded==='string'&&encoded.length>0&&encoded.length<=maxBytes*2,
106
+ 'Missing or oversized external secret: '+name);
107
+ check(/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)&&encoded.length%4===0,
108
+ 'Invalid base64 secret: '+name);
109
+ const raw=Buffer.from(encoded,'base64');
110
+ check(raw.length<=maxBytes,'External JSON secret too large: '+name);
111
+ try{return JSON.parse(raw.toString('utf8'))}
112
+ catch{throw new Error('Malformed external JSON secret: '+name)}
113
+ }
114
+
115
+ export function authorizeFromEnvironment(){
116
+ const repository=process.env.GITHUB_REPOSITORY,eventName=process.env.GITHUB_EVENT_NAME,
117
+ ref=process.env.GITHUB_REF,approvedSha=process.env.A2A_RELEASE_APPROVED_SHA;
118
+ const checkoutSha=execFileSync('git',['rev-parse','HEAD'],{encoding:'utf8',timeout:5000}).trim();
119
+ const mainSha=execFileSync('git',['rev-parse','origin/main'],{encoding:'utf8',timeout:5000}).trim();
120
+ const pkg=JSON.parse(fs.readFileSync(new URL('../package.json',import.meta.url),'utf8'));
121
+ return assertPublishAuthorized({repository,eventName,ref,checkoutSha,mainSha,approvedSha,
122
+ packageVersion:pkg.version,
123
+ manifest:readExternalJson('A2A_RELEASE_EVIDENCE_B64',{maxBytes:128*1024}),
124
+ trustKeys:readExternalJson('A2A_RELEASE_TRUST_KEYS_B64'),
125
+ registry:readExternalJson('A2A_RELEASE_REGISTRY_B64')});
126
+ }
127
+
128
+ if(process.argv[1]&&fileURLToPath(import.meta.url)===path.resolve(process.argv[1])){
129
+ try{
130
+ const result=authorizeFromEnvironment();
131
+ process.stdout.write(JSON.stringify(result)+'\n');
132
+ }catch(error){
133
+ // Never print supplied secrets, source reports or raw crypto exceptions to CI logs.
134
+ process.stderr.write('Release authorization DENIED: '+String(error.message).slice(0,160)+'\n');
135
+ process.exitCode=1;
136
+ }
137
+ }
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+ // Explicit independent review annotations; no hidden thinking inspection or weighted ranking.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ const areas=new Set(['planning','diagnosis','tool-selection','verification','error-recovery','handoff']);
7
+ const grades=new Set(['supported','incomplete','contradicted','not-observable']);
8
+ const validRef=x=>typeof x==='string'&&/^(?:ci|trace|review|test)[-:][a-zA-Z0-9_.-]{1,80}$/.test(x)&&!x.includes('..');
9
+ const check=(ok,m)=>{if(!ok)throw new Error(m)};
10
+ export function assessReviewedDecisions(transcript,review){
11
+ check(Array.isArray(transcript)&&transcript.length<=250000,'Invalid transcript');
12
+ check(review&&review.reviewer?.role==='independent'&&Array.isArray(review.annotations)&&review.annotations.length<=200,'Independent reviewer and <=200 annotations required');
13
+ const steps=new Set(transcript.filter(x=>x?.type==='PLANNER_RESPONSE'&&Number.isSafeInteger(x.step_index)).map(x=>x.step_index));
14
+ const counts=Object.fromEntries([...areas].map(k=>[k,{supported:0,incomplete:0,contradicted:0,'not-observable':0}]));
15
+ const seen=new Set(),items=[];
16
+ for(const a of review.annotations){
17
+ check(a&&Number.isSafeInteger(a.step_index)&&areas.has(a.area)&&grades.has(a.grade)&&validRef(a.evidence_ref),'Invalid or unsafe review annotation');
18
+ const key=a.step_index+':'+a.area;check(!seen.has(key),'Duplicate reviewed step and area');seen.add(key);
19
+ const tracePresent=steps.has(a.step_index);
20
+ const status=tracePresent?a.grade:'not-observable';
21
+ counts[a.area][status]++;
22
+ items.push({step_index:a.step_index,area:a.area,assessment:status,evidence_ref:a.evidence_ref,...(!tracePresent?{reason:'Referenced planner step not present in input transcript'}:{})});
23
+ }
24
+ return {schema:'a2a-independent-decision-review-v1',annotated_decisions:items.length,areas:counts,annotations:items,limits:['Independent reviewer role is declared by the file; identity and evidence are not cryptographically attested','Only observable decisions are reviewable; hidden chain-of-thought is not accessed','No scalar reasoning score or causal claims are generated','Reviews require examining original local evidence privately']};
25
+ }
26
+ function readJson(p,limit){const stat=fs.statSync(p);check(stat.isFile()&&stat.size<=limit,'Input exceeds size limit');return fs.readFileSync(p,'utf8')}
27
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
28
+ try{
29
+ check(process.argv.length===4,'Usage: node scripts/review-agent-decisions.mjs transcript.jsonl review.json');
30
+ const log=readJson(process.argv[2],128*1024*1024).split(/\r?\n/).filter(Boolean).map(JSON.parse);
31
+ const review=JSON.parse(readJson(process.argv[3],1024*1024));
32
+ console.log(JSON.stringify(assessReviewedDecisions(log,review),null,2));
33
+ }catch(e){console.error('Review validation failed: '+e.message);process.exitCode=1}
34
+ }
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ // Standalone entrypoint for the same conservative engine offered via a2a_verify.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ import {evaluateSemanticClaims} from '../src/semantic-evidence.mjs';
7
+ export {evaluateSemanticClaims,inspectScenarioFacts} from '../src/semantic-evidence.mjs';
8
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
9
+ try{
10
+ if(process.argv.length!==3)throw Error('Usage: node scripts/semantic-evidence.mjs <scenario-evidence.json>');
11
+ const stat=fs.statSync(process.argv[2]);
12
+ if(!stat.isFile()||stat.size>1024*1024)throw Error('Evidence artifact must be a regular JSON file <=1 MiB');
13
+ process.stdout.write(JSON.stringify(evaluateSemanticClaims(JSON.parse(fs.readFileSync(process.argv[2],'utf8'))),null,2)+'\n');
14
+ }catch(e){process.stderr.write('Semantic evidence invalid: '+e.message+'\n');process.exitCode=1}
15
+ }
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ // Backward-compatible wrapper for A2A
3
+ import './a2a.mjs';
@@ -0,0 +1,24 @@
1
+ ---
2
+ name: pilah
3
+ description: Native-first engineering assistance for scoped code changes, cross-file impact, root cause investigation and verifiable results. Use for risky or unclear coding tasks, not routine edits.
4
+ ---
5
+
6
+ # PILAH — Project Intelligence, Logic, Analysis & Handoffs
7
+
8
+ Antigravity is the executor. PILAH is a small, read-first assistant, not a substitute agent or automatic test runner.
9
+
10
+ ## 0 calls → 1 precise call → more only if new evidence
11
+
12
+ 1. **0 calls:** clear tasks, isolated changes, known bug, trivial UI text. Use the existing project code and native tools.
13
+ 2. **Before coding:** define the complete scope (callers, tests, config, security boundaries). Ask in order: is it necessary? already implemented? available through the platform/standard library? existing dependency? otherwise the smallest readable change.
14
+ 3. **1 call when uncertainty matters:** eager `pilah_context(workspace="<trusted project>",action="query",query="<specific symbol>",limit=5)`; for an identified risky change, discover lazy `pilah_impact` schema and use a scoped file list. Never run both reflexively.
15
+ 4. **Debugging:** reproduce the symptom, identify a falsifiable root-cause hypothesis, make the smallest correcting change. Use adaptive 5 Whys only for repeated, high-risk or unclear failures. No mandatory five-question ceremony for simple bugs.
16
+ 5. **Evidence:** if correctness is nontrivial, use native tests, realistic negative cases and exact named reports. `pilah_verify(operation="plan")` can outline acceptance; assessment requires real evidence. Second call only after new evidence. Persist acceptance scope only via `persist_plan:true`; full Markdown auto-snapshots are **off** by default. Source changes invalidate stale evidence. Local tests are not independent proof of visual, browser, security or hardware acceptance.
17
+ 6. **Simplify after tests:** remove redundant code or glue; preserve validation, permissions, behavior, error handling and accessibility. Prefer readable code over cryptic one-liners.
18
+ 7. **Handoff:** explicitly state changed, tests run, failures, outstanding tests, and risks. Use `pilah_evidence` only for real recovery/RCA needs; persistent storage requires opt-in.
19
+
20
+ Native teamwork/subagents only when independent workstreams benefit and the user opts in. Never spawn teams or change model modes automatically. No extra plugins, background transcript scans, forced compaction, or unverified token-saving claims.
21
+
22
+ For repetitive native operations, prefer a short, reviewable script with bounded, redacted output over repeated reads/calls. Check effects and permissions first; never bypass approval or sandboxing. Model routing, background sidecars and automatic prompt mutation are not PILAH features.
23
+
24
+ **Compatibility:** Older tool calls and existing configuration/data paths remain supported in code. Default public tool discovery exposes only the four PILAH operations.
@@ -0,0 +1,84 @@
1
+ // A2A acceptance matrix: scope and evidence requirements are explicit, never inferred.
2
+ // Local reports cannot independently attest browser state, visual parity or hardware.
3
+ import {sha256} from './security.mjs';
4
+
5
+ const TYPES=new Set(['build','unit','integration','browser','visual','hardware','security','independent']);
6
+ const UI=new Set(['browser','visual']);
7
+ const text=(value,max=160)=>typeof value==='string'&&value.trim().length>0&&value.length<=max;
8
+ const clean=(value,max=160)=>text(value,max)?value.trim():null;
9
+
10
+ export function normalizeAcceptanceCriterion(input){
11
+ if(typeof input==='string'){
12
+ if(!text(input))throw new Error('Invalid criterion');
13
+ return {id:sha256(input.trim().toLowerCase()).slice(0,20),description:input.trim(),status:'not_run',evidence_required:true,contract:'legacy'};
14
+ }
15
+ if(!input||typeof input!=='object'||Array.isArray(input)||!text(input.id,160))throw new Error('Invalid acceptance criterion id');
16
+ const id=input.id.trim();
17
+ const typed=input.evidence_type!==undefined;
18
+ if(!typed){
19
+ if(input.description!==undefined&&!text(input.description))throw new Error('Invalid criterion description');
20
+ return {id,description:clean(input.description)||id,status:'not_tested',evidence_required:true,contract:'legacy'};
21
+ }
22
+ if(!TYPES.has(input.evidence_type))throw new Error('Unknown acceptance evidence_type');
23
+ for(const field of ['given','when','then']){
24
+ if(!text(input[field],200))throw new Error('Acceptance requires explicit '+field);
25
+ }
26
+ if(UI.has(input.evidence_type)){
27
+ for(const field of ['viewport','ui_state','reference']){
28
+ if(!text(input[field],160))throw new Error('UI acceptance requires '+field);
29
+ }
30
+ }
31
+ if(input.source_revision!==undefined&&!text(input.source_revision,160))throw new Error('Invalid source_revision');
32
+ if(input.negative!==undefined&&typeof input.negative!=='boolean')throw new Error('Invalid negative control flag');
33
+ return {
34
+ id,description:clean(input.description)||id,
35
+ given:input.given.trim(),when:input.when.trim(),then:input.then.trim(),
36
+ evidence_type:input.evidence_type,
37
+ ...(UI.has(input.evidence_type)?{
38
+ viewport:input.viewport.trim(),ui_state:input.ui_state.trim(),reference:input.reference.trim()
39
+ }:{}),
40
+ ...(input.source_revision?{source_revision:input.source_revision}:{}),
41
+ negative:input.negative===true,
42
+ status:'not_tested',evidence_required:true,
43
+ contract:'acceptance-v1'
44
+ };
45
+ }
46
+
47
+
48
+ const LOCAL_ATTESTATION_EXCLUDED=new Set(['browser','visual','hardware','security','independent']);
49
+ // A2A machine reports are inspectable local assertions, not independent
50
+ // execution/visual/hardware witnesses. Shared by assess and verify_handoff.
51
+ export function localEvidencePolicy(criterion){
52
+ const kind=criterion?.evidence_type||'unspecified';
53
+ if(LOCAL_ATTESTATION_EXCLUDED.has(kind))return {
54
+ locally_attestable:false,
55
+ reason:'Local named tests and native hook metadata cannot independently attest '+kind+' acceptance'
56
+ };
57
+ return {locally_attestable:true,reason:null};
58
+ }
59
+
60
+ export function acceptanceCompletion(plan,results,{planning=false}={}){
61
+ const byId=new Map(results.map(r=>[r.id,r]));
62
+ const counts={passed:0,failed:0,blocked:0,not_tested:0,stale:0,inconclusive:0};
63
+ const missing=[];
64
+ for(const criterion of plan){
65
+ const result=byId.get(criterion.id);
66
+ let status=planning?'not_tested':(result?.status||'not_tested');
67
+ if(status==='not_run'||!Object.hasOwn(counts,status))status='not_tested';
68
+ counts[status]++;
69
+ if(status!=='passed'&&missing.length<20)missing.push({id:criterion.id,status});
70
+ }
71
+ const localPasses=counts.passed;
72
+ return {
73
+ status:planning?'not_tested':'not_independently_verified',
74
+ fully_verified:false,
75
+ scope:'explicit-acceptance-criteria',
76
+ total:plan.length,
77
+ counts,
78
+ local_report_passes:localPasses,
79
+ independently_attested:0,
80
+ missing_or_unproven:missing,
81
+ missing_truncated:plan.length-localPasses>missing.length,
82
+ note:'Named local machine tests prove only their assertions. Build success is not browser, visual, financial, hardware, or independent acceptance. Use signed assess_release evidence for release eligibility.'
83
+ };
84
+ }
@@ -0,0 +1,40 @@
1
+ // Browser Evidence v1 contract: read-only and conservative.
2
+ import {isDeepStrictEqual} from 'node:util';
3
+ // A local artifact hash verifies unchanged bytes, NOT browser execution authenticity.
4
+ const object=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
5
+ const bounded=x=>typeof x==='string'&&x.length>0&&x.length<=160;
6
+ const id=x=>bounded(x)&&/^[a-zA-Z0-9_.:-]+$/.test(x);
7
+ const sha=x=>typeof x==='string'&&/^[a-f0-9]{64}$/i.test(x);
8
+ export function assessBrowserEvidence(report,{expectedRevision,artifactChecks=[]}={}){
9
+ if(!object(report)||report.schema!=='a2a-browser-evidence-v1')throw Error('Unsupported browser evidence schema');
10
+ if(!id(report.scenario_id)||!object(report.source)||!object(report.build)||!object(report.environment)||!Array.isArray(report.assertions)||report.assertions.length>100)throw Error('Incomplete browser evidence');
11
+ if(!bounded(expectedRevision))throw Error('Expected trusted source revision required');
12
+ const problems=[];
13
+ if(report.source.revision!==expectedRevision)problems.push('source-revision-mismatch');
14
+ if(!sha(report.build.artifact_sha256)||!sha(report.build.served_sha256)||report.build.artifact_sha256!==report.build.served_sha256)problems.push('served-build-not-matched');
15
+ if(report.build.source_revision!==expectedRevision)problems.push('build-source-unbound');
16
+ if(!bounded(report.environment.browser)||!bounded(report.environment.version))problems.push('browser-environment-incomplete');
17
+ if(!bounded(report.runner?.name)||!bounded(report.runner?.version))problems.push('runner-missing');
18
+ if(!report.started_at||!report.finished_at||!Number.isFinite(Date.parse(report.started_at))||!Number.isFinite(Date.parse(report.finished_at))||Date.parse(report.started_at)>Date.parse(report.finished_at))problems.push('timing-invalid');
19
+ const cases=[],seenAssertions=new Set();
20
+ for(const a of report.assertions){
21
+ if(!object(a)||!id(a.id)||!['passed','failed','skipped','not-run'].includes(a.status)){problems.push('invalid-assertion');continue}
22
+ if(seenAssertions.has(a.id)){problems.push('duplicate-assertion');continue}
23
+ seenAssertions.add(a.id);
24
+ const outcome=a.status==='passed'&&a.executed===true&&a.observed!==undefined&&a.expected!==undefined&&isDeepStrictEqual(a.observed,a.expected)?'reported-passed':a.status==='failed'?'reported-failed':'insufficient';
25
+ cases.push({id:a.id,outcome});
26
+ }
27
+ if(!cases.length)problems.push('no-machine-assertions');
28
+ if(cases.some(c=>c.outcome==='reported-failed'))problems.push('assertion-failed');
29
+ if(cases.some(c=>c.outcome==='insufficient'))problems.push('assertions-not-verified');
30
+ const artifacts=Array.isArray(report.artifacts)?report.artifacts:[];
31
+ if(artifacts.length>40)problems.push('too-many-artifacts');
32
+ const byRef=new Map(artifactChecks.map(x=>[x.reference,x]));
33
+ for(const art of artifacts){
34
+ if(!object(art)||!id(art.reference)||!sha(art.sha256)){problems.push('unsafe-artifact-reference');continue}
35
+ const observed=byRef.get(art.reference);
36
+ if(!observed||observed.sha256!==art.sha256||observed.intact!==true)problems.push('artifact-not-intact');
37
+ }
38
+ const stale=problems.includes('source-revision-mismatch')||problems.includes('build-source-unbound');
39
+ return {schema:'a2a-browser-assessment-v1',scenario_id:report.scenario_id,revision:expectedRevision,status:stale?'stale':problems.length?'inconclusive':'evidence-present-unattested',independently_verified:false,artifact_count:artifacts.length,assertions:cases,problem_codes:[...new Set(problems)],trust:'unattested-browser-report',limits:['Metadata and assertions originate from the supplied report; reporter identity is not authenticated','Same build digest in two report fields does not prove browser loaded the expected build','Only trusted external browser/backend harness execution can establish scenario correctness']};
40
+ }
@@ -0,0 +1,14 @@
1
+ // Read-only on-demand context milestone advice: never automatic compaction.
2
+ export const CONTEXT_HEALTH_LIMITS=Object.freeze({reviewSteps:80,handoffSteps:140});
3
+ export function assessContextHealth({steps,complete=true,milestoneComplete=false}={}){
4
+ if(!Number.isSafeInteger(steps)||steps<0)throw new Error('Invalid planner step count');
5
+ if(typeof complete!=='boolean'||typeof milestoneComplete!=='boolean')throw new Error('Invalid context state');
6
+ const common={planner_steps_since_conversation_start:steps,step_count_is_heuristic:true,active_context_tokens:null,
7
+ measured_token_savings:null,automatic_compaction:false,user_action_required:true,
8
+ note:'Local planner steps are not context-window occupancy, quota or official token usage.'};
9
+ if(!complete)return {...common,status:'insufficient_evidence',recommendation:'Transcript is incomplete; verify the native session before considering compaction.'};
10
+ if(steps<CONTEXT_HEALTH_LIMITS.reviewSteps)return {...common,status:'normal',recommendation:'No context action suggested by step heuristic.'};
11
+ if(!milestoneComplete)return {...common,status:'defer_until_milestone',recommendation:'Finish active edits and tests; this command cannot detect unfinished work.'};
12
+ if(steps>=CONTEXT_HEALTH_LIMITS.handoffSteps)return {...common,status:'handoff_review',recommendation:'At a user-confirmed completed milestone, consider a new session with verified files, tests and next steps. Never auto-clear or auto-compact.'};
13
+ return {...common,status:'compact_review',recommendation:'At a user-confirmed completed milestone, consider native /compact only after checking verified state. Never auto-compact.'};
14
+ }