@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.
- package/BUILD_STATUS.md +23 -0
- package/LICENSE +21 -0
- package/README.md +108 -2
- package/assets/logo.svg +5 -0
- package/docs/AB_EVALUATION.md +62 -0
- package/docs/ACCEPTANCE_GATE.md +41 -0
- package/docs/ADAPTIVE_RCA_WORKFLOW.md +93 -0
- package/docs/AGENT_DECISION_REVIEW.md +17 -0
- package/docs/AGENT_TRACE_BENCHMARK.md +17 -0
- package/docs/ALWAYS_ON_5_WHYS.md +75 -0
- package/docs/ARCHITECTURE.md +43 -0
- package/docs/BEHAVIORAL_5_WHYS_V2_0_1.md +117 -0
- package/docs/CHECKPOINT_RECOVERY.md +86 -0
- package/docs/CI_EFFICIENCY.md +63 -0
- package/docs/COMPATIBILITY.md +84 -0
- package/docs/CONTRACTS.md +177 -0
- package/docs/CONVERSATION_USAGE.md +52 -0
- package/docs/ENGINEERING_METHOD.md +68 -0
- package/docs/HOST_VALIDATION.md +35 -0
- package/docs/INDEPENDENT_ACCEPTANCE_RUNBOOK.md +72 -0
- package/docs/INTERVENTION_LEDGER.md +25 -0
- package/docs/MAIN_VALIDATION_BACKLOG.md +19 -0
- package/docs/NATIVE_FIRST_WORKFLOW.md +27 -0
- package/docs/OPEN_SOURCE_ENGINEERING_STANDARDS.md +62 -0
- package/docs/ORCHESTRATION_ADVISOR.md +36 -0
- package/docs/PRE_VNEXT_INTEGRATION.md +27 -0
- package/docs/PRIVATE_BENCHMARK_EXPORT.md +14 -0
- package/docs/README.md +58 -0
- package/docs/RELEASE.md +33 -0
- package/docs/RELEASE_AUTHORIZATION.md +33 -0
- package/docs/RISK_GUIDANCE.md +18 -0
- package/docs/SECURITY.md +76 -0
- package/docs/SECURITY_RELIABILITY_AUDIT_V2_0_1.md +55 -0
- package/docs/SEMANTIC_EVIDENCE.md +27 -0
- package/docs/SOURCES.md +13 -0
- package/docs/STOCKROOM_BENCHMARK_RECHECK_2026_11_18.md +53 -0
- package/docs/TOKEN_EFFICIENCY.md +71 -0
- package/docs/TOKEN_PROVENANCE.md +15 -0
- package/docs/V2_0_1_TRACEABILITY.md +66 -0
- package/hooks.json +45 -0
- package/mcp_config.json +16 -0
- package/package.json +31 -4
- package/plugin.json +27 -0
- package/rules/AGENTS.md +2 -0
- package/schemas/database.sql +84 -0
- package/schemas/mcp-tools.json +552 -0
- package/scripts/a2a.mjs +343 -0
- package/scripts/check-release.mjs +42 -0
- package/scripts/check-syntax.mjs +30 -0
- package/scripts/checkpoint.mjs +50 -0
- package/scripts/compare-agent-traces.mjs +53 -0
- package/scripts/context-guardian.mjs +132 -0
- package/scripts/evaluate-acceptance.mjs +110 -0
- package/scripts/export-benchmark.mjs +31 -0
- package/scripts/generate-contracts.mjs +6 -0
- package/scripts/hook.mjs +406 -0
- package/scripts/host-check.mjs +40 -0
- package/scripts/intervention-ledger.mjs +94 -0
- package/scripts/pilah.mjs +3 -0
- package/scripts/release-authorization.mjs +137 -0
- package/scripts/review-agent-decisions.mjs +34 -0
- package/scripts/semantic-evidence.mjs +15 -0
- package/scripts/verifykit.mjs +3 -0
- package/skills/pilah/SKILL.md +24 -0
- package/src/acceptance-matrix.mjs +84 -0
- package/src/browser-evidence.mjs +40 -0
- package/src/context-health.mjs +14 -0
- package/src/conversations.mjs +302 -0
- package/src/engine.mjs +494 -0
- package/src/graph.mjs +169 -0
- package/src/mcp-diagnostics.mjs +53 -0
- package/src/mcp.mjs +151 -0
- package/src/model-recovery.mjs +108 -0
- package/src/native-tool-recovery.mjs +45 -0
- package/src/node-runtime.mjs +13 -0
- package/src/orchestration-advisor.mjs +24 -0
- package/src/rca.mjs +174 -0
- package/src/risk-guidance.mjs +95 -0
- package/src/scanner.mjs +303 -0
- package/src/security.mjs +793 -0
- package/src/semantic-evidence.mjs +144 -0
- package/src/skill-discovery.mjs +23 -0
- package/src/sqlite-compat.mjs +11 -0
- package/src/storage.mjs +455 -0
- package/src/tokens.mjs +627 -0
- package/src/tools.mjs +164 -0
- package/src/verification.mjs +567 -0
- package/src/workflow-router.mjs +34 -0
package/src/rca.mjs
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
// A2A RCA is opt-in: named machine assertions support an experiment, not causality.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import {safeFile,sha256} from './security.mjs';
|
|
4
|
+
import {uniqueId} from './storage.mjs';
|
|
5
|
+
import {validateChangedPaths} from './graph.mjs';
|
|
6
|
+
|
|
7
|
+
export const RCA_WARNING='Local named tests do not independently prove a root cause. Review competing explanations, source freshness and external behavior.';
|
|
8
|
+
const SECRET=/(?:password|passwd|api[ _-]?key|(?:access[_ -]?|refresh[_ -]?)?token|cookie|authorization|private[_ -]?key|secret)\s*[:=]|\bBearer\s+[A-Za-z0-9._~-]{8,}/i;
|
|
9
|
+
const validate=(text,label,min,max)=>{
|
|
10
|
+
if(typeof text!=='string'||text.trim().length<min||text.length>max)throw Error('Invalid '+label+' (expected '+min+'-'+max+' characters)');
|
|
11
|
+
if(SECRET.test(text))throw Error('Possible credential in RCA notes; remove secrets before saving');
|
|
12
|
+
return text.trim();
|
|
13
|
+
};
|
|
14
|
+
const optional=(text,label,max)=>text===undefined||text===null||text===''?null:validate(text,label,1,max);
|
|
15
|
+
const consent=flag=>{if(flag!==true)throw Error('Explicit persist_rca=true required before storing private RCA notes')};
|
|
16
|
+
const signature=(title,paths)=>sha256(JSON.stringify([title.toLowerCase().replace(/\s+/g,' ').trim(),[...new Set(paths)].sort().slice(0,8)]));
|
|
17
|
+
function checkEvidence(store,ws,root,revision,id,criterion=null,strict=false){
|
|
18
|
+
const e=store.get('SELECT * FROM evidence WHERE workspace_id=? AND id=?',ws,id);
|
|
19
|
+
if(!e)throw Error('Unknown RCA evidence ID or unauthorized workspace');
|
|
20
|
+
if(e.revision_id!==revision)throw Error('RCA evidence is stale for current source revision');
|
|
21
|
+
let intact=false;
|
|
22
|
+
try{intact=sha256(fs.readFileSync(safeFile(root,e.artifact_path)))===e.artifact_sha}catch{}
|
|
23
|
+
if(!intact)throw Error('RCA evidence hash/path does not match a current permitted artifact');
|
|
24
|
+
if(criterion!==null&&e.criterion_id!==criterion)throw Error('RCA evidence belongs to an unrelated acceptance criterion');
|
|
25
|
+
const meta=JSON.parse(e.metadata_json||'{}');
|
|
26
|
+
if(strict && (e.status!=='passed' || !['unit','integration'].includes(meta.requested_evidence_type)
|
|
27
|
+
|| !meta.test_name || meta.test_name==='*' || !(meta.assertions>=1)))
|
|
28
|
+
throw Error('RCA requires a passing exact named unit/integration assertion; build, UI and hardware are insufficient');
|
|
29
|
+
return {id:e.id,criterion_id:e.criterion_id,test_name:meta.test_name||null,
|
|
30
|
+
evidence_type:meta.requested_evidence_type||'unspecified',fresh:true,
|
|
31
|
+
trust:'local-machine-assertion-only'};
|
|
32
|
+
}
|
|
33
|
+
export function recordRcaIncident(store,ws,root,revision,args){
|
|
34
|
+
consent(args.persist_rca);
|
|
35
|
+
const title=validate(args.title,'incident title',5,240);
|
|
36
|
+
const candidate=optional(args.root_cause,'candidate cause',1400)||'';
|
|
37
|
+
const paths=args.paths||[],criteria=args.criteria||[],evidenceIds=args.evidence_ids||[];
|
|
38
|
+
if(!Array.isArray(paths)||paths.length>80||paths.some(x=>typeof x!=='string'||x.length>500))throw Error('Invalid RCA paths');
|
|
39
|
+
validateChangedPaths(paths);
|
|
40
|
+
if(!Array.isArray(criteria)||criteria.length>40)throw Error('Invalid RCA criteria');
|
|
41
|
+
const cleanCriteria=criteria.map(x=>validate(x,'criterion',1,160));
|
|
42
|
+
if(!Array.isArray(evidenceIds)||evidenceIds.length>20||new Set(evidenceIds).size!==evidenceIds.length)throw Error('Invalid RCA evidence IDs');
|
|
43
|
+
const checked=evidenceIds.map(id=>checkEvidence(store,ws,root,revision,id));
|
|
44
|
+
const sig=signature(title,paths);
|
|
45
|
+
const related=store.all('SELECT id FROM incidents WHERE workspace_id=? AND signature_sha=? ORDER BY created_at DESC LIMIT 3',ws,sig).map(x=>x.id);
|
|
46
|
+
const id=uniqueId('inc');
|
|
47
|
+
store.run('INSERT INTO incidents(id,workspace_id,title,root_cause,state,revision_id,related_paths_json,criteria_json,evidence_ids_json,created_at,signature_sha) VALUES(?,?,?,?,?,?,?,?,?,?,?)',
|
|
48
|
+
id,ws,title,candidate,'investigating',revision,JSON.stringify(paths),JSON.stringify(cleanCriteria),
|
|
49
|
+
JSON.stringify(checked.map(x=>x.id)),new Date().toISOString(),sig);
|
|
50
|
+
return {id,state:'investigating',revision,candidate_cause:candidate||null,
|
|
51
|
+
root_cause_verified:false,linked_evidence_count:checked.length,
|
|
52
|
+
related_incident_ids:related,recurrence_is_hypothesis:true,warning:RCA_WARNING};
|
|
53
|
+
}
|
|
54
|
+
export function addRcaHypothesis(store,ws,revision,args){
|
|
55
|
+
consent(args.persist_rca);
|
|
56
|
+
const description=validate(args.hypothesis,'hypothesis',8,1000);
|
|
57
|
+
const experiment=validate(args.experiment,'experiment',8,1000);
|
|
58
|
+
const prediction=validate(args.predicted_observation,'predicted_observation',8,300);
|
|
59
|
+
const falsifier=validate(args.disconfirming_test,'disconfirming_test',8,300);
|
|
60
|
+
const criterion=validate(args.expected_criterion_id,'expected_criterion_id',1,160);
|
|
61
|
+
if(!args.incident_id||!store.get('SELECT id FROM incidents WHERE id=? AND workspace_id=?',args.incident_id,ws))
|
|
62
|
+
throw Error('RCA incident must exist in authorized workspace');
|
|
63
|
+
let depth=1;
|
|
64
|
+
const parentId=args.parent_hypothesis_id||null;
|
|
65
|
+
if(parentId){
|
|
66
|
+
const parent=store.get('SELECT incident_id,why_depth FROM hypotheses WHERE id=? AND workspace_id=?',parentId,ws);
|
|
67
|
+
if(!parent||parent.incident_id!==args.incident_id)throw Error('Parent hypothesis must belong to same incident');
|
|
68
|
+
depth=(parent.why_depth||1)+1;
|
|
69
|
+
}
|
|
70
|
+
if(depth>8)throw Error('Maximum RCA why depth reached; branch or summarize');
|
|
71
|
+
const planId=args.plan_id||null;
|
|
72
|
+
if(planId){
|
|
73
|
+
const plan=store.get('SELECT revision_id,manifest_sha,criteria_json FROM acceptance_plans WHERE workspace_id=? AND id=?',ws,planId);
|
|
74
|
+
if(!plan||plan.revision_id!==revision||sha256(plan.criteria_json)!==plan.manifest_sha
|
|
75
|
+
||!JSON.parse(plan.criteria_json).some(x=>x.id===criterion))
|
|
76
|
+
throw Error('RCA criterion must exist in a fresh, intact, authorized acceptance plan');
|
|
77
|
+
}
|
|
78
|
+
const id=uniqueId('hyp'),now=new Date().toISOString();
|
|
79
|
+
const sql='INSERT INTO hypotheses(id,workspace_id,incident_id,description,status,experiment,evidence_ids_json,created_at,revision_id,parent_hypothesis_id,why_depth,predicted_observation,disconfirming_test,expected_criterion_id,plan_id,assessment_json,assessed_revision_id,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
|
|
80
|
+
store.run(sql,id,ws,args.incident_id,description,'untested',experiment,'[]',now,
|
|
81
|
+
revision,parentId,depth,prediction,falsifier,criterion,planId,'{}',null,now);
|
|
82
|
+
return {id,incident_id:args.incident_id,status:'untested',why_depth:depth,parent_hypothesis_id:parentId,
|
|
83
|
+
source_revision:revision,root_cause_verified:false,warning:'Hypothesis saved but not tested; evidence remains required.'};
|
|
84
|
+
}
|
|
85
|
+
export function assessRcaHypothesis(store,ws,root,revision,args){
|
|
86
|
+
consent(args.persist_rca);
|
|
87
|
+
if(!['supports','refutes','inconclusive'].includes(args.experiment_outcome))
|
|
88
|
+
throw Error('experiment_outcome must be supports, refutes or inconclusive');
|
|
89
|
+
const observation=validate(args.observation,'observation',8,400);
|
|
90
|
+
const h=store.get('SELECT * FROM hypotheses WHERE workspace_id=? AND id=?',ws,args.hypothesis_id);
|
|
91
|
+
if(!h)throw Error('Unknown RCA hypothesis or unauthorized workspace');
|
|
92
|
+
if(!h.revision_id||h.revision_id!==revision)throw Error('RCA hypothesis is stale; create a new reviewed hypothesis');
|
|
93
|
+
if(!h.predicted_observation||!h.disconfirming_test||!h.expected_criterion_id)
|
|
94
|
+
throw Error('Falsifiable prediction, counter-test and named criterion required');
|
|
95
|
+
const ids=args.evidence_ids||[];
|
|
96
|
+
if(!Array.isArray(ids)||ids.length>20||new Set(ids).size!==ids.length)throw Error('Invalid RCA evidence IDs');
|
|
97
|
+
if(args.experiment_outcome!=='inconclusive'&&ids.length===0)throw Error('Causal outcome needs fresh named experimental evidence');
|
|
98
|
+
const evidence=ids.map(id=>checkEvidence(store,ws,root,revision,id,h.expected_criterion_id,args.experiment_outcome!=='inconclusive'));
|
|
99
|
+
const status=args.experiment_outcome==='supports'?'locally_supported':
|
|
100
|
+
args.experiment_outcome==='refutes'?'refuted':'inconclusive';
|
|
101
|
+
const now=new Date().toISOString();
|
|
102
|
+
const assessment={outcome:args.experiment_outcome,observation,evidence_ids:evidence.map(x=>x.id),
|
|
103
|
+
criterion_id:h.expected_criterion_id,plan_id:h.plan_id||null,source_revision:revision,
|
|
104
|
+
independent_causal_proof:false,updated_at:now};
|
|
105
|
+
store.transaction(()=>{
|
|
106
|
+
store.run('INSERT INTO rca_experiments(id,workspace_id,hypothesis_id,revision_id,outcome,observation,criterion_id,evidence_ids_json,created_at) VALUES(?,?,?,?,?,?,?,?,?)',
|
|
107
|
+
uniqueId('rex'),ws,h.id,revision,args.experiment_outcome,observation,h.expected_criterion_id,
|
|
108
|
+
JSON.stringify(assessment.evidence_ids),now);
|
|
109
|
+
store.run('UPDATE hypotheses SET status=?,evidence_ids_json=?,assessment_json=?,assessed_revision_id=?,updated_at=? WHERE workspace_id=? AND id=?',
|
|
110
|
+
status,JSON.stringify(assessment.evidence_ids),JSON.stringify(assessment),revision,now,ws,h.id);
|
|
111
|
+
});
|
|
112
|
+
return {id:h.id,incident_id:h.incident_id,status,why_depth:h.why_depth,source_freshness:'current',
|
|
113
|
+
linked_local_evidence:evidence,independently_attested:false,root_cause_verified:false,warning:RCA_WARNING};
|
|
114
|
+
}
|
|
115
|
+
export function listRcaHypotheses(store,ws,root,revision,limit=20,incidentId=null){
|
|
116
|
+
const n=Math.max(1,Math.min(50,Number(limit)||20));
|
|
117
|
+
const rows=incidentId?
|
|
118
|
+
store.all('SELECT * FROM hypotheses WHERE workspace_id=? AND incident_id=? ORDER BY created_at DESC LIMIT ?',ws,incidentId,n):
|
|
119
|
+
store.all('SELECT * FROM hypotheses WHERE workspace_id=? ORDER BY created_at DESC LIMIT ?',ws,n);
|
|
120
|
+
const total=incidentId?
|
|
121
|
+
store.get('SELECT count(*) AS n FROM hypotheses WHERE workspace_id=? AND incident_id=?',ws,incidentId).n:
|
|
122
|
+
store.get('SELECT count(*) AS n FROM hypotheses WHERE workspace_id=?',ws).n;
|
|
123
|
+
return {revision,total,more_available:total>rows.length,items:rows.map(h=>{
|
|
124
|
+
const fresh=Boolean(h.revision_id&&h.revision_id===revision);
|
|
125
|
+
const assessedFresh=Boolean(h.assessed_revision_id&&h.assessed_revision_id===revision);
|
|
126
|
+
let evidenceIntact=true;
|
|
127
|
+
if(h.status==='locally_supported'||h.status==='refuted'){
|
|
128
|
+
try{
|
|
129
|
+
const ids=JSON.parse(h.evidence_ids_json||'[]');
|
|
130
|
+
if(!ids.length)throw Error('No linked evidence');
|
|
131
|
+
for(const id of ids)checkEvidence(store,ws,root,revision,id,h.expected_criterion_id,true);
|
|
132
|
+
}catch{evidenceIntact=false}
|
|
133
|
+
}
|
|
134
|
+
const status=!fresh||(h.status!=='untested'&&!assessedFresh)||!evidenceIntact?'stale':h.status;
|
|
135
|
+
const history=store.all('SELECT outcome,revision_id,criterion_id,created_at FROM rca_experiments WHERE workspace_id=? AND hypothesis_id=? ORDER BY created_at DESC LIMIT 3',ws,h.id);
|
|
136
|
+
const assessmentCount=store.get('SELECT count(*) AS n FROM rca_experiments WHERE workspace_id=? AND hypothesis_id=?',ws,h.id).n;
|
|
137
|
+
return {id:h.id,incident_id:h.incident_id,description:h.description,status,
|
|
138
|
+
recent_experiments:history,experiments_total:assessmentCount,more_experiments_available:assessmentCount>history.length,
|
|
139
|
+
recorded_status:h.status,source_freshness:fresh?'current':'stale_or_unbound',
|
|
140
|
+
linked_evidence_intact:evidenceIntact,
|
|
141
|
+
experiment:h.experiment,parent_hypothesis_id:h.parent_hypothesis_id||null,
|
|
142
|
+
why_depth:h.why_depth||1,predicted_observation:h.predicted_observation||null,
|
|
143
|
+
disconfirming_test:h.disconfirming_test||null,expected_criterion_id:h.expected_criterion_id||null,
|
|
144
|
+
plan_id:h.plan_id||null,evidence_ids:JSON.parse(h.evidence_ids_json||'[]'),
|
|
145
|
+
assessment:JSON.parse(h.assessment_json||'{}'),
|
|
146
|
+
root_cause_verified:false,independently_attested:false};
|
|
147
|
+
}),warning:RCA_WARNING};
|
|
148
|
+
}
|
|
149
|
+
export function listRcaIncidents(store,ws,revision,limit=20){
|
|
150
|
+
const rows=store.all('SELECT * FROM incidents WHERE workspace_id=? ORDER BY created_at DESC LIMIT ?',ws,Math.max(1,Math.min(50,Number(limit)||20)));
|
|
151
|
+
const total=store.get('SELECT count(*) AS n FROM incidents WHERE workspace_id=?',ws).n;
|
|
152
|
+
return {revision,total,more_available:total>rows.length,items:rows.map(x=>({id:x.id,title:x.title,root_cause:x.root_cause,
|
|
153
|
+
candidate_cause:x.root_cause||null,root_cause_verified:false,
|
|
154
|
+
state:x.state==='evidence-linked'?'historical-evidence-linked-unverified':x.state,
|
|
155
|
+
source_freshness:x.revision_id===revision?'current':'stale',
|
|
156
|
+
paths:JSON.parse(x.related_paths_json),criteria:JSON.parse(x.criteria_json),
|
|
157
|
+
evidence_ids:JSON.parse(x.evidence_ids_json),created_at:x.created_at})),warning:RCA_WARNING};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function deleteRcaIncident(store,ws,{incident_id,persist_rca,confirm_deletion}){
|
|
161
|
+
consent(persist_rca);
|
|
162
|
+
if(confirm_deletion!==true)throw Error('Explicit confirm_deletion=true required to delete RCA history');
|
|
163
|
+
if(typeof incident_id!=='string'||!incident_id)throw Error('incident_id is required');
|
|
164
|
+
return store.transaction(()=>{
|
|
165
|
+
const exists=store.get('SELECT id FROM incidents WHERE workspace_id=? AND id=?',ws,incident_id);
|
|
166
|
+
if(!exists)throw Error('RCA incident not found in authorized workspace');
|
|
167
|
+
const count=store.get('SELECT count(*) AS n FROM hypotheses WHERE workspace_id=? AND incident_id=?',ws,incident_id).n;
|
|
168
|
+
store.run('DELETE FROM rca_experiments WHERE workspace_id=? AND hypothesis_id IN (SELECT id FROM hypotheses WHERE workspace_id=? AND incident_id=?)',ws,ws,incident_id);
|
|
169
|
+
store.run('DELETE FROM hypotheses WHERE workspace_id=? AND incident_id=?',ws,incident_id);
|
|
170
|
+
store.run('DELETE FROM incidents WHERE workspace_id=? AND id=?',ws,incident_id);
|
|
171
|
+
return {deleted:true,incident_id,hypotheses_deleted:count,other_evidence_preserved:true,
|
|
172
|
+
warning:'RCA rows removed logically. SQLite WAL, backups or filesystem remnants may retain older bytes; this is not cryptographic erasure.'};
|
|
173
|
+
});
|
|
174
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Domain-specific verification requests, not a vulnerability scanner or test runner.
|
|
2
|
+
// The safest possible result is a list of NOT-RUN checks, never a passing verdict.
|
|
3
|
+
const CASES={
|
|
4
|
+
'authorization-and-tenant-isolation':[
|
|
5
|
+
['auth-route-role','Role matrix rejects forbidden mutations and leaves the database unchanged'],
|
|
6
|
+
['auth-store-link','Store, supplier, category and variant IDs must belong to the authorized tenant and store'],
|
|
7
|
+
['auth-entry-points','Authorization is enforced independently for web, API, offline sync, replay and background handlers'],
|
|
8
|
+
['auth-cost-projection','Cashier and other non-finance roles cannot receive restricted cost-price data']
|
|
9
|
+
],
|
|
10
|
+
'financial-integrity':[
|
|
11
|
+
['finance-server-prices','Sale prices, discount and tax policy derive from trusted server sources or audited authorized overrides'],
|
|
12
|
+
['finance-line-reconcile','Sum of item totals, discounts, taxes and rounding equals order totals in integer minor units'],
|
|
13
|
+
['finance-paid-reconcile','Completed/paid status requires reconciled payment totals, including split payments and tendered change'],
|
|
14
|
+
['finance-zero-payment','A paid order cannot be created with zero or underpaid settlement']
|
|
15
|
+
],
|
|
16
|
+
'refund-and-inventory-invariants':[
|
|
17
|
+
['refund-duplicate-lines','Duplicate item IDs within a single refund request cannot increase refunded quantity or restock'],
|
|
18
|
+
['refund-amount-only','A partial monetary-only refund does not restock all units without an explicit return decision'],
|
|
19
|
+
['stock-negative','Stock cannot go negative and all inventory mutations reconcile to an append-only movement ledger'],
|
|
20
|
+
['transfer-race','Concurrent receive/cancel attempts yield one final transfer state and one stock adjustment']
|
|
21
|
+
],
|
|
22
|
+
'concurrency-and-idempotency':[
|
|
23
|
+
['concurrent-last-stock','Two independent DB connections race for the last item with exactly one success'],
|
|
24
|
+
['idem-response-loss','Response loss after committed checkout and retry with same ID causes exactly one order and ledger effect'],
|
|
25
|
+
['idem-payload-conflict','Same operation ID with different normalized payload returns conflict without new side effects']
|
|
26
|
+
],
|
|
27
|
+
'offline-security-and-recovery':[
|
|
28
|
+
['offline-authorize','Offline sync and replay enforce the same tenant and store checks as online checkout'],
|
|
29
|
+
['offline-process-restart','The persisted queue survives full browser process restart, then syncs exactly once'],
|
|
30
|
+
['offline-user-switch','Sign-out/account switch does not expose cached HTML or IndexedDB data from prior user'],
|
|
31
|
+
['offline-failed-retry','Failed and conflicted operations have bounded retry/reconciliation and visible terminal outcomes']
|
|
32
|
+
],
|
|
33
|
+
'identity-and-production-safety':[
|
|
34
|
+
['auth-rate-limit','Login and registration are rate-limited under repeated invalid attempts'],
|
|
35
|
+
['auth-invitation','Membership invitations have valid acceptance, expiry, organization and store authorization'],
|
|
36
|
+
['error-sanitization','Public API errors do not include private exceptions, SQL traces or credentials'],
|
|
37
|
+
['production-demo','Production pages do not expose working seeded demo credentials or test-only hooks']
|
|
38
|
+
],
|
|
39
|
+
'web-usability-and-operations':[
|
|
40
|
+
['ui-accessibility','Interactive flows support keyboard, visible focus, labels and contrast at target viewports'],
|
|
41
|
+
['ui-mobile','Critical flows avoid clipping/overflow on supported screen sizes'],
|
|
42
|
+
['production-health','Operational readiness includes error observability and resource/performance evidence']
|
|
43
|
+
]
|
|
44
|
+
};
|
|
45
|
+
const SCOPE=[
|
|
46
|
+
['authorization-and-tenant-isolation',/(?:\b(auth|role|permission|middleware|tenant|organisation|organization|membership|access|policy|guard)\b|routes\/(?:web|api)\.php|controllers?\/|\bstore[_ -]?id\b|\bsupplier[_ -]?id\b)/i],
|
|
47
|
+
['financial-integrity',/(?:checkout|poscontroller|poscheckout|payment|invoice|discount|tax|price|ledger|settlement|paid|billing)/i],
|
|
48
|
+
['refund-and-inventory-invariants',/(?:refund|stock|inventory|transfer|receiv|restock|adjustment)/i],
|
|
49
|
+
['concurrency-and-idempotency',/(?:checkout|poscontroller|poscheckout|refund|transfer|inventory|operation[_ -]?id|idempoten|concurren|stock)/i],
|
|
50
|
+
['offline-security-and-recovery',/(?:offline|service[-_]?worker|\bsw\.js\b|indexeddb|sync|queue|pwa|replay|cache)/i],
|
|
51
|
+
['identity-and-production-safety',/(?:\b(login|register|auth|invite|invitation|seeder|seeders|exception|errorhandler|authcontroller)\b|routes\/(?:web|api)\.php)/i],
|
|
52
|
+
['web-usability-and-operations',/(?:\.(?:vue|tsx|jsx|css|scss)\b|pages\/|components\/|accessib|performance|responsive)/i]
|
|
53
|
+
];
|
|
54
|
+
const safe=(a,max)=>Array.isArray(a)?a.filter(x=>typeof x==='string'&&x.length<1000).slice(0,max):[];
|
|
55
|
+
export const RISK_DOMAINS=Object.freeze(Object.keys(CASES));
|
|
56
|
+
export function proposeRiskTests({paths=[],criteria=[],compact=false}={}){
|
|
57
|
+
const sources=[...safe(paths,80),...safe(criteria,40)];
|
|
58
|
+
const q=sources.join(' ').slice(0,12000);
|
|
59
|
+
const riskDomains=SCOPE.filter(([,re])=>re.test(q)).map(([name])=>name);
|
|
60
|
+
const all=riskDomains.flatMap(domain=>CASES[domain].map(([id,requirement],order)=>({
|
|
61
|
+
domain,priority:domain==='web-usability-and-operations'?'medium':'critical',
|
|
62
|
+
id,requirement,order
|
|
63
|
+
})));
|
|
64
|
+
// Rank by specific symptoms/criterion words instead of returning every
|
|
65
|
+
// generic test template. Existing full output can still be requested by
|
|
66
|
+
// turning Compact off; none of these suggestions are mandatory acceptance.
|
|
67
|
+
const words=new Set(q.toLowerCase().match(/[a-z][a-z0-9_-]{3,}/g)||[]);
|
|
68
|
+
const ranked=all.map(x=>{
|
|
69
|
+
const terms=(x.id+' '+x.requirement).toLowerCase().match(/[a-z][a-z0-9_-]{3,}/g)||[];
|
|
70
|
+
return {...x,match_score:terms.filter(t=>words.has(t)).length};
|
|
71
|
+
}).sort((a,b)=>b.match_score-a.match_score||(a.priority==='critical'?-1:1)-(b.priority==='critical'?-1:1)||a.order-b.order);
|
|
72
|
+
const selected=new Set((compact?ranked.slice(0,3):ranked).map(x=>x.id));
|
|
73
|
+
const findings=riskDomains.map(domain=>{
|
|
74
|
+
const scenarios=CASES[domain].filter(([id])=>selected.has(id)).map(([id,requirement])=>({
|
|
75
|
+
id,requirement,status:'not-run',evidence_required:true,
|
|
76
|
+
minimum_evidence:domain==='web-usability-and-operations'?'browser-or-accessibility-report':'named-machine-assertion-plus-domain-invariant'
|
|
77
|
+
}));
|
|
78
|
+
return {domain,priority:domain==='web-usability-and-operations'?'medium':'critical',
|
|
79
|
+
negative_test_scenarios:scenarios,suggested_total:CASES[domain].length,
|
|
80
|
+
suggestions_omitted:CASES[domain].length-scenarios.length};
|
|
81
|
+
});
|
|
82
|
+
const suggestedIds=findings.flatMap(x=>x.negative_test_scenarios.map(y=>y.id));
|
|
83
|
+
return {status:findings.length?'suggestions-only':'no-domain-signals-detected',
|
|
84
|
+
findings,
|
|
85
|
+
// Historical required_test_ids was a misleading label: suggestions are not
|
|
86
|
+
// acceptance requirements until explicitly adopted in a verification plan.
|
|
87
|
+
required_test_ids:[],suggested_test_ids:suggestedIds,
|
|
88
|
+
suggested_total:all.length,suggested_visible:suggestedIds.length,
|
|
89
|
+
more_available:suggestedIds.length<all.length,
|
|
90
|
+
coverage_assurance:'none',adopted_as_mandatory:false,
|
|
91
|
+
limitations:['Static paths/criteria only suggest risks; they are not discovered vulnerabilities',
|
|
92
|
+
'No suggested scenario was run or added to mandatory acceptance criteria',
|
|
93
|
+
'No domain match does not mean the application is secure or that route/service coverage is complete',
|
|
94
|
+
'Use a user-reviewed a2a_verify plan and independent evidence for release claims']};
|
|
95
|
+
}
|
package/src/scanner.mjs
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {spawnSync} from 'node:child_process';
|
|
5
|
+
import {sha256, MAX_INDEX_FILES, MAX_SOURCE_BYTES,shouldIgnore,safeFile} from './security.mjs';
|
|
6
|
+
import {stripCommentsLex} from './tokens.mjs';
|
|
7
|
+
|
|
8
|
+
const langMap={'.js':'javascript','.mjs':'javascript','.cjs':'javascript','.jsx':'javascript','.ts':'typescript','.tsx':'typescript','.mts':'typescript','.cts':'typescript','.php':'php','.py':'python','.go':'go','.rs':'rust','.java':'java','.kt':'kotlin','.kts':'kotlin','.dart':'dart','.swift':'swift','.cs':'csharp','.gd':'gdscript','.c':'c','.h':'c','.cpp':'cpp','.hpp':'cpp','.cc':'cpp','.rb':'ruby','.ex':'elixir','.exs':'elixir','.vue':'vue','.svelte':'svelte','.html':'html','.css':'css','.scss':'scss','.sql':'sql','.json':'json','.yaml':'yaml','.yml':'yaml','.toml':'toml','.xml':'xml','.sh':'shell'};
|
|
9
|
+
const manifestName=/^(package\.json|composer\.json|pyproject\.toml|requirements[^/]*\.txt|go\.mod|Cargo\.toml|pom\.xml|build\.gradle(?:\.kts)?|settings\.gradle(?:\.kts)?|pubspec\.yaml|project\.godot|CMakeLists\.txt|Makefile|[^/]+\.csproj|[^/]+\.sln|Package\.swift|Gemfile|mix\.exs)$/;
|
|
10
|
+
const textName=/\.(?:js|jsx|ts|tsx|mts|cts|mjs|cjs|php|py|go|rs|java|kt|kts|dart|swift|cs|gd|c|h|cpp|hpp|cc|rb|ex|exs|vue|svelte|html|css|scss|sql|json|yaml|yml|toml|xml|sh)$/i;
|
|
11
|
+
const testFile=/(?:^|\/)(?:tests?|specs?|__tests__)(?:\/|$)|(?:\.test\.|\.spec\.|_test\.|_spec\.|Test\.(?:java|kt|cs|php)$)/i;
|
|
12
|
+
export const detectLanguage=rel=>langMap[path.extname(rel).toLowerCase()]||(manifestName.test(path.basename(rel))?'config':'unknown');
|
|
13
|
+
export const isTestFile=rel=>testFile.test(rel);
|
|
14
|
+
// Generated A2A reports are evidence, not application source. Restrict this
|
|
15
|
+
// exclusion to report directories AND recognized report shapes; ordinary JSON,
|
|
16
|
+
// including application configuration, must still affect the source revision.
|
|
17
|
+
export function isGeneratedA2AReport(rel,content){
|
|
18
|
+
if(!/(^|\/)(?:reports?|test-results)\/[^/]+\.json$/i.test(String(rel||'').replaceAll('\\','/')))return false;
|
|
19
|
+
try{
|
|
20
|
+
const x=JSON.parse(String(content));
|
|
21
|
+
if(!x||typeof x!=='object'||Array.isArray(x))return false;
|
|
22
|
+
if(x.schema==='a2a-browser-evidence-v1'&&typeof x.source?.revision==='string')return true;
|
|
23
|
+
if(typeof x.revision==='string'&&Array.isArray(x.claims)&&x.claims.length>0)return true;
|
|
24
|
+
if(typeof x.revision==='string'&&x.evaluator&&Array.isArray(x.scenarios))return true;
|
|
25
|
+
return x.format==='a2a-test-report-v1'&&Array.isArray(x.cases)&&x.completed===true;
|
|
26
|
+
}catch{return false}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function gitHead(root){const p=spawnSync('git',['rev-parse','HEAD'],{cwd:root,timeout:1500,encoding:'utf8',windowsHide:true});return p.status===0?p.stdout.trim():null}
|
|
30
|
+
export function gitChanges(root){
|
|
31
|
+
// git status may execute a repository-configured fsmonitor hook unless explicitly disabled.
|
|
32
|
+
// A2A only inspects source; repository trust must never imply permission to run hooks.
|
|
33
|
+
const p=spawnSync('git',['-c','core.fsmonitor=false','status','--porcelain=v1','-z','--untracked-files=normal'],{cwd:root,timeout:4000,encoding:'utf8',windowsHide:true});
|
|
34
|
+
if(p.status!==0) return [];
|
|
35
|
+
const parts=p.stdout.split('\0'),out=[];
|
|
36
|
+
for(let i=0;i<parts.length;i++){
|
|
37
|
+
const s=parts[i];
|
|
38
|
+
if(!s||s.length<4)continue;
|
|
39
|
+
const status=s.slice(0,2);
|
|
40
|
+
const rel=s.slice(3);
|
|
41
|
+
if(/[RC]/.test(status)) i++;
|
|
42
|
+
if(rel && !shouldIgnore(rel))out.push(rel.replaceAll('\\','/'));
|
|
43
|
+
}
|
|
44
|
+
return [...new Set(out)].sort().slice(0,500);
|
|
45
|
+
}
|
|
46
|
+
// Hash moderately oversized first-party files without parsing them. Larger or
|
|
47
|
+
// unreadable sources make verification explicitly incomplete instead of stale-PASS.
|
|
48
|
+
function fingerprintOversizedSource(full,size){
|
|
49
|
+
if(size>32*1024*1024)return null;
|
|
50
|
+
const fd=fs.openSync(full,'r'),buffer=Buffer.allocUnsafe(65536),hash=crypto.createHash('sha256');
|
|
51
|
+
try{
|
|
52
|
+
let position=0;
|
|
53
|
+
while(position<size){
|
|
54
|
+
const n=fs.readSync(fd,buffer,0,Math.min(buffer.length,size-position),position);
|
|
55
|
+
if(n<=0)return null;
|
|
56
|
+
hash.update(buffer.subarray(0,n));position+=n;
|
|
57
|
+
}
|
|
58
|
+
if(fs.fstatSync(fd).size!==size)return null;
|
|
59
|
+
return hash.digest('hex');
|
|
60
|
+
}finally{fs.closeSync(fd)}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function discover(root,{limit=MAX_INDEX_FILES,cachedFiles=null}={}){
|
|
64
|
+
const paths=[],skip=[],skippedHashes=[],stack=[''];let scanned=0,totalBytes=0,integrityComplete=true,readFiles=0,readBytes=0,reusedFiles=0,oversizedHashedBytes=0;const now=Date.now();
|
|
65
|
+
while(stack.length){const dir=stack.pop();let entries;try{entries=fs.readdirSync(path.join(root,dir),{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))}catch{continue}
|
|
66
|
+
for(const ent of entries){const rel=(dir?dir+'/':'')+ent.name;
|
|
67
|
+
if(shouldIgnore(rel)||ent.isSymbolicLink())continue;
|
|
68
|
+
if(ent.isDirectory()){stack.push(rel);continue}
|
|
69
|
+
if(!ent.isFile() || !(textName.test(rel)||manifestName.test(ent.name)))continue;
|
|
70
|
+
scanned++;if(scanned>limit){skip.push('index_limit_exceeded');integrityComplete=false;stack.length=0;break}
|
|
71
|
+
try{const full=safeFile(root,rel);const st=fs.statSync(full);if(st.size>MAX_SOURCE_BYTES){
|
|
72
|
+
skip.push('large:'+rel);
|
|
73
|
+
const digest=fingerprintOversizedSource(full,st.size);
|
|
74
|
+
if(digest){skippedHashes.push(rel+':'+digest);oversizedHashedBytes+=st.size;}else integrityComplete=false;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if(totalBytes+st.size>32*1024*1024){skip.push('index_byte_budget_exceeded');integrityComplete=false;stack.length=0;break}
|
|
78
|
+
const cached=cachedFiles?.get(rel);
|
|
79
|
+
if(cached && ent.name!=='package.json' && !/(^|\/)(?:reports?|test-results)\/[^/]+\.json$/i.test(rel) && cached.mtime_ms!=null && cached.mtime_ms===st.mtimeMs && cached.bytes===st.size && (now-st.mtimeMs)>1500){
|
|
80
|
+
totalBytes+=st.size;reusedFiles++;
|
|
81
|
+
paths.push({path:rel,hash:cached.hash,language:cached.language||detectLanguage(rel),bytes:st.size,mtime_ms:st.mtimeMs,text:null});
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
const buf=fs.readFileSync(full);readFiles++;readBytes+=buf.length;totalBytes+=st.size;if(buf.includes(0)){skip.push('binary:'+rel);skippedHashes.push(rel+':'+sha256(buf));continue}
|
|
85
|
+
if(isGeneratedA2AReport(rel,buf))continue;
|
|
86
|
+
paths.push({path:rel,hash:sha256(buf),language:detectLanguage(rel),bytes:st.size,mtime_ms:st.mtimeMs,text:buf.toString('utf8')});
|
|
87
|
+
}catch{skip.push('unreadable:'+rel);integrityComplete=false}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
paths.sort((a,b)=>a.path.localeCompare(b.path));return {files:paths,skipped:skip,skippedHashes,integrityComplete,scan_stats:{read_files:readFiles,read_bytes:readBytes,reused_files:reusedFiles,oversized_hashed_bytes:oversizedHashedBytes,scanned_candidates:scanned}};
|
|
91
|
+
}
|
|
92
|
+
function buildLineStarts(text){
|
|
93
|
+
const starts=[0];
|
|
94
|
+
for(let i=0;i<text.length;i++)if(text.charCodeAt(i)===10)starts.push(i+1);
|
|
95
|
+
return starts;
|
|
96
|
+
}
|
|
97
|
+
function lineAt(starts,offset){
|
|
98
|
+
let lo=0,hi=starts.length-1;
|
|
99
|
+
while(lo<=hi){
|
|
100
|
+
const mid=(lo+hi)>>>1;
|
|
101
|
+
if(starts[mid]<=offset)lo=mid+1;else hi=mid-1;
|
|
102
|
+
}
|
|
103
|
+
return hi+1;
|
|
104
|
+
}
|
|
105
|
+
const symbolPatterns=[
|
|
106
|
+
/\b(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function\*?|class|interface|enum|type|trait|struct|mod)\s+([A-Za-z_$][\w$]*)/g,
|
|
107
|
+
/\b(?:def|class)\s+([A-Za-z_][\w]*)/g,
|
|
108
|
+
/\b(?:pub(?:\([^)]*\))?\s+)?(?:async\s+)?(?:fn|struct|trait|enum)\s+([A-Za-z_][\w]*)/g,
|
|
109
|
+
/\bfunc\s+(?:\([^)]+\)\s*)?([A-Za-z_][\w]*)\s*\(/g,
|
|
110
|
+
/\btype\s+([A-Za-z_][\w]*)\s+(?:struct|interface)\b/g,
|
|
111
|
+
/\b(?:public|private|protected|internal|open|override|static|final|suspend|async)?\s*(?:fun|func|class|interface|record|struct|enum|protocol)\s+([A-Za-z_][\w]*)/g
|
|
112
|
+
];
|
|
113
|
+
export function extractSymbols(text,ext=''){
|
|
114
|
+
if(!text)return [];
|
|
115
|
+
const cleaned=stripCommentsLex(text,ext,{preserveLines:true});
|
|
116
|
+
const starts=buildLineStarts(cleaned);
|
|
117
|
+
const results=[];
|
|
118
|
+
for(const re of symbolPatterns){
|
|
119
|
+
re.lastIndex=0;
|
|
120
|
+
let m,count=0;
|
|
121
|
+
while((m=re.exec(cleaned))!==null && count<60){
|
|
122
|
+
results.push({name:m[1],line:lineAt(starts,m.index)});
|
|
123
|
+
count++;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return [...new Map(results.map(s=>[s.name+'@'+s.line,s])).values()].sort((a,b)=>a.line-b.line).slice(0,150);
|
|
127
|
+
}
|
|
128
|
+
function importsFrom(text,language,ext=''){
|
|
129
|
+
if(!text)return [];
|
|
130
|
+
const cleaned=stripCommentsLex(text,ext,{preserveLines:true});
|
|
131
|
+
let matches=[];
|
|
132
|
+
const patterns=[
|
|
133
|
+
/\b(?:import\s+(?:[^'"\n]+?\s+from\s+)?|export\s+[^'"\n]*?from\s+|require\s*\(\s*|import\s*\(\s*)['"]([^'"\n]+)['"]/g,
|
|
134
|
+
/\b(?:include|include_once|require|require_once)\s*\(?\s*['"]([^'"\n]+)['"]/g,
|
|
135
|
+
/\b(?:include|import|preload)\s*\(?\s*['"](res:\/\/[^'"\n]+)['"]/g,
|
|
136
|
+
/\b(?:mod|use)\s+([A-Za-z_][\w:]*)/g,
|
|
137
|
+
/#include\s+["<]([^">]+)[">]/g
|
|
138
|
+
];
|
|
139
|
+
for(const re of patterns){let m;re.lastIndex=0;while((m=re.exec(cleaned))!==null && matches.length<120)matches.push(m[1]);}
|
|
140
|
+
if(language==='python'){
|
|
141
|
+
const re=/^\s*from\s+(\.*[A-Za-z_][\w.]*)\s+import\s+/gm;let m;while((m=re.exec(cleaned))!==null)matches.push(m[1]);
|
|
142
|
+
const direct=/^\s*import\s+([A-Za-z_][\w.]*)/gm;while((m=direct.exec(cleaned))!==null)matches.push(m[1]);
|
|
143
|
+
}
|
|
144
|
+
if(language==='php'){
|
|
145
|
+
// Explicit, static imports only. Runtime container resolution and Laravel
|
|
146
|
+
// facades are intentionally out of scope.
|
|
147
|
+
const re=/^\s*use\s+(?!function\b|const\b)([A-Za-z_][\w\\]*)(?:\s+as\s+\w+)?\s*;/gm;
|
|
148
|
+
let m;while((m=re.exec(cleaned))!==null && matches.length<120)matches.push(m[1]);
|
|
149
|
+
}
|
|
150
|
+
return [...new Set(matches)];
|
|
151
|
+
}
|
|
152
|
+
function localConfigAliases(files){
|
|
153
|
+
const php=[],js=[];
|
|
154
|
+
const resolveDir=(folder,dir)=>{
|
|
155
|
+
if(typeof dir!=='string'||dir.startsWith('/')||dir.includes('\\')||dir.split('/').includes('..'))return null;
|
|
156
|
+
const combined=path.posix.normalize(path.posix.join(folder,dir));
|
|
157
|
+
return combined==='..'||combined.startsWith('../')||combined.startsWith('/')?null:combined;
|
|
158
|
+
};
|
|
159
|
+
for(const f of files){
|
|
160
|
+
if(!f.text||!/(^|\/)(?:composer|tsconfig|jsconfig)\.json$/.test(f.path))continue;
|
|
161
|
+
let data;try{data=JSON.parse(f.text)}catch{continue}
|
|
162
|
+
const folder=path.posix.dirname(f.path)==='.'?'':path.posix.dirname(f.path);
|
|
163
|
+
if(path.posix.basename(f.path)==='composer.json'){
|
|
164
|
+
for(const mapping of [data?.autoload?.['psr-4'],data?.['autoload-dev']?.['psr-4']]){
|
|
165
|
+
if(!mapping||typeof mapping!=='object'||Array.isArray(mapping))continue;
|
|
166
|
+
for(const [prefix,dirs] of Object.entries(mapping).slice(0,100)){
|
|
167
|
+
if(!prefix.endsWith('\\')||prefix.length>100)continue;
|
|
168
|
+
for(const dir of (Array.isArray(dirs)?dirs:[dirs]).slice(0,8)){
|
|
169
|
+
const target=resolveDir(folder,dir);
|
|
170
|
+
if(target!==null)php.push({prefix,target});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}else{
|
|
175
|
+
const compiler=data?.compilerOptions;
|
|
176
|
+
if(!compiler||typeof compiler!=='object'||Array.isArray(compiler))continue;
|
|
177
|
+
const base=resolveDir(folder,typeof compiler.baseUrl==='string'?compiler.baseUrl:'.');
|
|
178
|
+
if(base===null)continue;
|
|
179
|
+
const entries=compiler.paths;
|
|
180
|
+
if(!entries||typeof entries!=='object'||Array.isArray(entries))continue;
|
|
181
|
+
for(const [prefix,targets] of Object.entries(entries).slice(0,100)){
|
|
182
|
+
if(!prefix.endsWith('/*')||prefix.length>80||!Array.isArray(targets))continue;
|
|
183
|
+
for(const target of targets.slice(0,8)){
|
|
184
|
+
if(typeof target!=='string'||!target.endsWith('/*'))continue;
|
|
185
|
+
const dir=resolveDir(base,target.slice(0,-2));
|
|
186
|
+
if(dir!==null)js.push({prefix:prefix.slice(0,-1),target:dir});
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
php.sort((a,b)=>b.prefix.length-a.prefix.length);
|
|
192
|
+
js.sort((a,b)=>b.prefix.length-a.prefix.length);
|
|
193
|
+
return {php,js};
|
|
194
|
+
}
|
|
195
|
+
function resolveImport(rel,imp,known,language,aliases){
|
|
196
|
+
|
|
197
|
+
if(language==='python'){
|
|
198
|
+
const dots=imp.match(/^\.+/);
|
|
199
|
+
if(dots){
|
|
200
|
+
let dir=path.posix.dirname(rel);
|
|
201
|
+
for(let n=1;n<dots[0].length;n++)dir=path.posix.dirname(dir);
|
|
202
|
+
const member=imp.slice(dots[0].length).replaceAll('.','/');
|
|
203
|
+
imp=path.posix.normalize(path.posix.join(dir,member));
|
|
204
|
+
}else imp=imp.replaceAll('.','/');
|
|
205
|
+
if(!imp||imp==='.'||imp.startsWith('..')||imp.startsWith('/'))return null;
|
|
206
|
+
}
|
|
207
|
+
else if(language==='php' && imp.includes('\\')){
|
|
208
|
+
let mapped=null;
|
|
209
|
+
for(const rule of aliases.php){
|
|
210
|
+
if(!imp.startsWith(rule.prefix))continue;
|
|
211
|
+
const remainder=imp.slice(rule.prefix.length).replaceAll('\\','/');
|
|
212
|
+
if(!remainder||remainder.split('/').some(x=>!x||x==='..'||x==='.'))continue;
|
|
213
|
+
mapped=path.posix.join(rule.target,remainder+'.php');
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
if(!mapped)return null;
|
|
217
|
+
imp=mapped;
|
|
218
|
+
}
|
|
219
|
+
else if(['javascript','typescript','vue','svelte'].includes(language)&&!imp.startsWith('.')&&!imp.startsWith('res://')){
|
|
220
|
+
let mapped=null;
|
|
221
|
+
for(const rule of aliases.js){
|
|
222
|
+
if(!imp.startsWith(rule.prefix))continue;
|
|
223
|
+
const remainder=imp.slice(rule.prefix.length);
|
|
224
|
+
if(!remainder||remainder.split('/').some(x=>!x||x==='..'||x==='.'))continue;
|
|
225
|
+
mapped=path.posix.join(rule.target,remainder);
|
|
226
|
+
break;
|
|
227
|
+
}
|
|
228
|
+
if(!mapped)return null;
|
|
229
|
+
imp=mapped;
|
|
230
|
+
}
|
|
231
|
+
else if(imp.startsWith('res://'))imp=imp.slice(6);
|
|
232
|
+
else if(imp.startsWith('.'))imp=path.posix.normalize(path.posix.join(path.posix.dirname(rel),imp));
|
|
233
|
+
else return null;
|
|
234
|
+
if(imp.startsWith('..')||imp.startsWith('/')||imp==='.')return null;
|
|
235
|
+
const candidates=[imp];
|
|
236
|
+
if(!known.has(imp)){
|
|
237
|
+
if(imp.endsWith('.js'))candidates.push(imp.slice(0,-3)+'.ts',imp.slice(0,-3)+'.tsx',imp.slice(0,-3)+'.mts');
|
|
238
|
+
else if(imp.endsWith('.jsx'))candidates.push(imp.slice(0,-4)+'.tsx');
|
|
239
|
+
else if(imp.endsWith('.mjs'))candidates.push(imp.slice(0,-4)+'.mts');
|
|
240
|
+
else if(imp.endsWith('.cjs'))candidates.push(imp.slice(0,-4)+'.cts');
|
|
241
|
+
}
|
|
242
|
+
// Python src-layout packages (e.g. src/pkg/mod.py) are resolved only
|
|
243
|
+
// when the exact indexed file exists; never synthesize external dependencies.
|
|
244
|
+
if(language==='python' && !imp.startsWith('src/')){
|
|
245
|
+
candidates.push('src/'+imp+'.py','src/'+imp+'/__init__.py');
|
|
246
|
+
}
|
|
247
|
+
candidates.push(
|
|
248
|
+
...['.ts','.tsx','.mts','.cts','.js','.jsx','.mjs','.cjs','.py','.php','.gd','.json','.vue','.svelte','.h','.hpp','.rs'].map(s=>imp+s),
|
|
249
|
+
...['index.ts','index.tsx','index.mts','index.js','index.mjs','__init__.py','mod.rs'].map(s=>imp+'/'+s)
|
|
250
|
+
);
|
|
251
|
+
return candidates.find(s=>known.has(s))||null;
|
|
252
|
+
}
|
|
253
|
+
function featureOf(rel){let n=path.basename(rel).replace(/\.(test|spec|unit|integration)\b/ig,'').replace(/(_test|_spec|Test)\b/g,'').replace(/\.[^.]+$/,'');return n.toLowerCase().replace(/(controller|service|component|handler|model|repository|screen|page|view|store|routes|route)$/,'').replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')||'root'}
|
|
254
|
+
export function createGraph(index){
|
|
255
|
+
let files=index.files,nodes=[],edges=[],byPath=new Map(files.map(f=>[f.path,f])),featIds=new Map();const known=new Set(byPath.keys());
|
|
256
|
+
const nonTestByFeature=new Map(),configured=localConfigAliases(files);
|
|
257
|
+
const addEdge=(from,to,kind,basis='source',state='observed',file=null)=>{const id=sha256(from+'|'+to+'|'+kind).slice(0,36);edges.push({id,from,to,kind,basis,state,file})};
|
|
258
|
+
for(const f of files){const fid='file:'+f.path;const isTest=isTestFile(f.path);nodes.push({id:fid,kind:isTest?'test':'file',label:f.path,path:f.path,basis:'source'});
|
|
259
|
+
if(manifestName.test(path.basename(f.path)))continue;
|
|
260
|
+
const feature=featureOf(f.path);let ftid='feature:'+feature;
|
|
261
|
+
if(!featIds.has(ftid)){featIds.set(ftid,true);nodes.push({id:ftid,kind:'feature',label:feature,basis:'derived'})}
|
|
262
|
+
addEdge(fid,ftid,'CONTRIBUTES_TO','filename-derived','derived',f.path);
|
|
263
|
+
if(!isTest){
|
|
264
|
+
if(!nonTestByFeature.has(feature))nonTestByFeature.set(feature,[]);
|
|
265
|
+
nonTestByFeature.get(feature).push(f);
|
|
266
|
+
}
|
|
267
|
+
const ext=path.extname(f.path);
|
|
268
|
+
for(const sym of extractSymbols(f.text,ext)){const sid='symbol:'+f.path+':'+sym.name+':'+sym.line;nodes.push({id:sid,kind:'symbol',label:sym.name,path:f.path,line:sym.line,basis:'source'});addEdge(fid,sid,'DECLARES','source','observed',f.path)}
|
|
269
|
+
for(const imp of importsFrom(f.text,f.language,ext)){const target=resolveImport(f.path,imp,known,f.language,configured);if(target)addEdge(fid,'file:'+target,'IMPORTS','static-import','observed',f.path)}
|
|
270
|
+
}
|
|
271
|
+
for(const f of files){
|
|
272
|
+
if(!isTestFile(f.path))continue;
|
|
273
|
+
const targets=nonTestByFeature.get(featureOf(f.path))||[];
|
|
274
|
+
for(const target of targets.slice(0,12))addEdge('file:'+f.path,'file:'+target.path,'MAY_TEST','naming-heuristic','derived',f.path);
|
|
275
|
+
}
|
|
276
|
+
return {nodes,edges:[...new Map(edges.map(x=>[x.id,x])).values()]};
|
|
277
|
+
}
|
|
278
|
+
const knownScripts=[
|
|
279
|
+
{files:['package.json'],match:/"(?:test|lint|typecheck|check|build)"\s*:/,ecosystem:'node',runners:['npm run test','npm run lint','npm run build']},
|
|
280
|
+
{files:['composer.json'],ecosystem:'php',runners:['vendor/bin/phpunit','vendor/bin/pest']},
|
|
281
|
+
{files:['pyproject.toml','pytest.ini'],ecosystem:'python',runners:['python -m pytest']},
|
|
282
|
+
{files:['go.mod'],ecosystem:'go',runners:['go test ./...']},
|
|
283
|
+
{files:['Cargo.toml'],ecosystem:'rust',runners:['cargo test']},
|
|
284
|
+
{files:['pubspec.yaml'],ecosystem:'dart',runners:['flutter test','dart test']},
|
|
285
|
+
{files:['project.godot'],ecosystem:'godot',runners:['godot --headless --path . --quit']},
|
|
286
|
+
{files:['pom.xml'],ecosystem:'java',runners:['mvn test']},
|
|
287
|
+
{files:['build.gradle','build.gradle.kts'],ecosystem:'gradle',runners:['./gradlew test']},
|
|
288
|
+
{files:['Package.swift'],ecosystem:'swift',runners:['swift test']},
|
|
289
|
+
{files:['App.csproj','App.sln'],ecosystem:'dotnet',runners:['dotnet test']},
|
|
290
|
+
{files:['CMakeLists.txt'],ecosystem:'cmake',runners:['ctest --output-on-failure']},
|
|
291
|
+
];
|
|
292
|
+
export function discoverTestCommands(index,root=null){const names=new Set(index.files.map(f=>path.basename(f.path)));const suggestions=[];
|
|
293
|
+
for(const k of knownScripts){if(!k.files.some(x=>names.has(x)) && !(k.ecosystem==='dotnet' && [...names].some(n=>/\.(csproj|sln)$/.test(n))))continue;
|
|
294
|
+
const cmds=(k.ecosystem==='node')?(()=>{try{const pkg=index.files.find(f=>f.path==='package.json');if(!pkg)return [];const raw=pkg.text??(root?fs.readFileSync(safeFile(root,'package.json'),'utf8'):null);if(!raw)return [];const parsed=JSON.parse(raw);return ['test','lint','typecheck','check','build'].filter(c=>typeof parsed.scripts?.[c]==='string').map(c=>'npm run '+c)}catch{return []}})():k.runners;
|
|
295
|
+
suggestions.push({ecosystem:k.ecosystem,candidates:cmds,execution:'native-antigravity-only',confirmed:false});
|
|
296
|
+
}
|
|
297
|
+
const testFiles=index.files.filter(f=>isTestFile(f.path)).map(f=>f.path).slice(0,100);
|
|
298
|
+
return {suggestions,testFiles,note:'Commands are candidates, not audited safe. Run only with Antigravity native permissions, after inspecting scripts.'};
|
|
299
|
+
}
|
|
300
|
+
// Bump whenever scanner/graph semantics change: a stable source revision alone
|
|
301
|
+
// must not reuse relation rows from a previous installed PILAH algorithm.
|
|
302
|
+
export const GRAPH_INDEX_VERSION='pilah-graph-v2';
|
|
303
|
+
export function snapshotOf(index){return sha256([GRAPH_INDEX_VERSION,...index.files.map(f=>f.path+':'+f.hash),...(index.skippedHashes||[]),index.integrityComplete===false?'source-integrity-incomplete':'source-integrity-complete'].sort().join('\n'))}
|