@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/engine.mjs
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import {Store,uniqueId} from './storage.mjs';
|
|
5
|
+
import {requireAuthorizedWorkspace,sha256,cleanError,safeFile,getCompactMode,getHomeDir,isSamePath,isSameOrDescendantPath,readSafeJsonFile} from './security.mjs';
|
|
6
|
+
import {discover,createGraph,snapshotOf,gitHead,discoverTestCommands} from './scanner.mjs';
|
|
7
|
+
import {contextQuery,analyzeImpact,shortGraphSummary,validateChangedPaths} from './graph.mjs';
|
|
8
|
+
import {planVerification,assessVerification,listEvidence,freshness,verifyHandoff} from './verification.mjs';
|
|
9
|
+
import {estimateTokens,getSessionTokenUsage,analyzeWorkspaceTokens,skeletonizeCode} from './tokens.mjs';
|
|
10
|
+
import {scanConversationHistory,attachReportSize} from './conversations.mjs';
|
|
11
|
+
import {evaluateSemanticClaims} from './semantic-evidence.mjs';
|
|
12
|
+
import {assessBrowserEvidence} from './browser-evidence.mjs';
|
|
13
|
+
|
|
14
|
+
import {assessRelease} from '../scripts/evaluate-acceptance.mjs';
|
|
15
|
+
|
|
16
|
+
import {adviseOrchestration} from './orchestration-advisor.mjs';
|
|
17
|
+
import {saveRecoveryCheckpoint,recoveryStatus} from './model-recovery.mjs';
|
|
18
|
+
import {classifyNativeToolFailure} from './native-tool-recovery.mjs';
|
|
19
|
+
import {recordRcaIncident,addRcaHypothesis,assessRcaHypothesis,listRcaIncidents,listRcaHypotheses,deleteRcaIncident} from './rca.mjs';
|
|
20
|
+
|
|
21
|
+
export class Engine {
|
|
22
|
+
constructor({store}={}) {this.store=store||new Store();this.owned=!store;}
|
|
23
|
+
close(){if(this.owned)this.store.close()}
|
|
24
|
+
sync(workspace,{verifyIntegrity=false}={}){
|
|
25
|
+
const root=requireAuthorizedWorkspace(workspace),wsId=this.store.register(root);
|
|
26
|
+
const cachedFiles=new Map(this.store.all('SELECT path,content_sha AS hash,language,bytes,mtime_ms FROM files WHERE workspace_id=?',wsId).map(r=>[r.path,r]));
|
|
27
|
+
const index=discover(root,{cachedFiles:verifyIntegrity?null:cachedFiles}), git=gitHead(root);
|
|
28
|
+
const snapshot=sha256((git||'no-git')+'|'+snapshotOf(index));const current=this.store.latest(wsId);
|
|
29
|
+
const revision=this.store.insertRevision(wsId,snapshot,git,{os:os.platform(),arch:os.arch(),node:process.versions.node});
|
|
30
|
+
if(!current||current.id!==revision||cachedFiles.size!==index.files.length){
|
|
31
|
+
for(const f of index.files){
|
|
32
|
+
if(f.text===null){
|
|
33
|
+
try{f.text=fs.readFileSync(safeFile(root,f.path),'utf8')}catch{f.text=''}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
const graph=createGraph(index);
|
|
37
|
+
this.store.persistIndex(wsId,revision,index.files.map(({text,...rest})=>rest),graph.nodes,graph.edges);
|
|
38
|
+
}
|
|
39
|
+
return {root,wsId,revision,index,git,snapshot,skipped:index.skipped,scan_stats:index.scan_stats,source_integrity_complete:index.integrityComplete!==false};
|
|
40
|
+
}
|
|
41
|
+
resolveMeta(workspace){
|
|
42
|
+
const root=requireAuthorizedWorkspace(workspace),wsId=this.store.register(root);
|
|
43
|
+
const current=this.store.latest(wsId);
|
|
44
|
+
if(!current) return this.sync(workspace);
|
|
45
|
+
return {root,wsId,revision:current.id,git:current.git_head};
|
|
46
|
+
}
|
|
47
|
+
context({workspace,action='inspect',query='',limit=12,history_scope='current',history_limit=10,file=null,files=[],task={},path:targetPath=null}={}){
|
|
48
|
+
const compact=getCompactMode();
|
|
49
|
+
if(action==='orchestration'){requireAuthorizedWorkspace(workspace);return adviseOrchestration(task)}
|
|
50
|
+
if(action==='tokens'&&history_scope==='all'){
|
|
51
|
+
// This must be an explicit tokens action. Do not walk private transcripts
|
|
52
|
+
// as a side effect of ordinary inspect/impact calls.
|
|
53
|
+
requireAuthorizedWorkspace(workspace);
|
|
54
|
+
const output=scanConversationHistory({
|
|
55
|
+
dataDirPath:this.store.base,
|
|
56
|
+
limit:Math.min(10,history_limit||10),
|
|
57
|
+
});
|
|
58
|
+
attachReportSize(output,{format:'json'});
|
|
59
|
+
return {action:'tokens',history:output,note:'Historical token counters are not equivalent to provider-reported usage.'};
|
|
60
|
+
}
|
|
61
|
+
if(action==='skeleton'){
|
|
62
|
+
// The preview must be labeled with the revision of the bytes actually read.
|
|
63
|
+
const s=this.sync(workspace,{verifyIntegrity:true});
|
|
64
|
+
const singleTarget=file||targetPath;
|
|
65
|
+
const targets=[...(typeof singleTarget==='string'&&singleTarget.trim()?[singleTarget.trim()]:[]),...(Array.isArray(files)?files:[])].filter(Boolean);
|
|
66
|
+
const uniqueTargets=[...new Set(targets)].slice(0,20);
|
|
67
|
+
if(!uniqueTargets.length) throw new Error('Provide file or files for action="skeleton"');
|
|
68
|
+
let totalRaw=0, totalSkel=0;
|
|
69
|
+
const outputCharBudget=compact?4800:32000;
|
|
70
|
+
const perFileCharBudget=compact?1600:6000;
|
|
71
|
+
let remainingOutputChars=outputCharBudget;
|
|
72
|
+
let omittedFiles=0;
|
|
73
|
+
const items=[];
|
|
74
|
+
for(const [index,rel] of uniqueTargets.entries()){
|
|
75
|
+
if(compact&&index>=6){
|
|
76
|
+
omittedFiles++;
|
|
77
|
+
items.push({file:rel,skipped:true,reason:'compact_file_budget'});
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
const full=safeFile(s.root,rel);
|
|
81
|
+
const stat=fs.statSync(full);
|
|
82
|
+
if(stat.size>160*1024 || remainingOutputChars<100){
|
|
83
|
+
omittedFiles++;
|
|
84
|
+
items.push({file:rel,skipped:true,reason:stat.size>160*1024?'source_too_large':'response_budget_exhausted'});
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
const raw=fs.readFileSync(full,'utf8');
|
|
88
|
+
const wholeSkeleton=skeletonizeCode(raw,path.extname(rel));
|
|
89
|
+
const cap=Math.min(perFileCharBudget,remainingOutputChars);
|
|
90
|
+
const skeleton=wholeSkeleton.length>cap?wholeSkeleton.slice(0,cap):wholeSkeleton;
|
|
91
|
+
const truncated=skeleton.length<wholeSkeleton.length;
|
|
92
|
+
remainingOutputChars-=skeleton.length;
|
|
93
|
+
const rawTokens=estimateTokens(raw);
|
|
94
|
+
const skelTokens=estimateTokens(skeleton);
|
|
95
|
+
totalRaw+=rawTokens;totalSkel+=skelTokens;
|
|
96
|
+
items.push({
|
|
97
|
+
file:rel,
|
|
98
|
+
...(compact?{}:{estimated_source_tokens:rawTokens,estimated_preview_tokens:skelTokens}),
|
|
99
|
+
skeleton,
|
|
100
|
+
truncated,
|
|
101
|
+
...(truncated?{warning:'Preview truncated. Do not infer complete code behavior from this excerpt.'}:{}),
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
const payload={
|
|
105
|
+
workspace_id:s.wsId,
|
|
106
|
+
revision:s.revision,
|
|
107
|
+
action:'skeleton',
|
|
108
|
+
files:items,
|
|
109
|
+
summary:{
|
|
110
|
+
estimated_source_tokens:totalRaw,
|
|
111
|
+
estimated_preview_tokens:totalSkel,
|
|
112
|
+
estimated_preview_only:true,
|
|
113
|
+
preview_char_budget:outputCharBudget,
|
|
114
|
+
omitted_files:omittedFiles,
|
|
115
|
+
truncated_files:items.filter(x=>x.truncated).length,
|
|
116
|
+
note:compact?'Payload estimates only; no billed savings proven.':'These are relative payload-size estimates; no model usage or net savings were measured.',
|
|
117
|
+
},
|
|
118
|
+
...(compact?{compact:true}:{}),
|
|
119
|
+
};
|
|
120
|
+
this.store.recordTelemetry(s.wsId,{toolName:'pilah_context',action:'skeleton',rawScopeTokens:totalRaw,responseTokens:estimateTokens(JSON.stringify(payload))});
|
|
121
|
+
return payload;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const s=this.sync(workspace,{verifyIntegrity:action==='freshness'||action==='query'||action==='inspect'});
|
|
125
|
+
const base={
|
|
126
|
+
workspace_id:s.wsId,
|
|
127
|
+
revision:s.revision,
|
|
128
|
+
git_head:s.git,
|
|
129
|
+
coverage:{
|
|
130
|
+
...shortGraphSummary(this.store,s.wsId),
|
|
131
|
+
skipped_files:s.skipped.length,
|
|
132
|
+
incomplete:s.skipped.length>0,
|
|
133
|
+
source_integrity_complete:s.source_integrity_complete,
|
|
134
|
+
},
|
|
135
|
+
read_only:true,
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
if(action==='query'){
|
|
139
|
+
const qRes=contextQuery(this.store,s.wsId,{query,limit});
|
|
140
|
+
if(compact){
|
|
141
|
+
// Keep full uncertainty statements: compact output cannot change
|
|
142
|
+
// the meaning of coverage/safety limits.
|
|
143
|
+
const originalEdges=qRes.relations.length;
|
|
144
|
+
if(originalEdges>12){
|
|
145
|
+
qRes.relations=qRes.relations.slice(0,12);
|
|
146
|
+
qRes.relations_truncated=true;
|
|
147
|
+
qRes.relations_before_compaction=originalEdges;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const payload={...base,...qRes,...(compact?{compact:true}:{})};
|
|
151
|
+
const fileBytes=new Map(s.index.files.map(f=>[f.path,f.bytes]));
|
|
152
|
+
const matchedFiles=new Set(qRes.nodes.map(n=>n.file).filter(Boolean));
|
|
153
|
+
let rawBytes=0;
|
|
154
|
+
for(const fp of matchedFiles) rawBytes+=fileBytes.get(fp)||0;
|
|
155
|
+
this.store.recordTelemetry(s.wsId,{toolName:'pilah_context',action:'query',rawScopeTokens:estimateTokens(rawBytes),responseTokens:estimateTokens(JSON.stringify(payload))});
|
|
156
|
+
return payload;
|
|
157
|
+
}
|
|
158
|
+
if(action==='freshness'){
|
|
159
|
+
return {...base,evidence:freshness(this.store,s.wsId,s.root,s.revision),...(compact?{compact:true}:{})};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if(action==='inspect'){
|
|
163
|
+
const cmdInfo=discoverTestCommands(s.index,s.root);
|
|
164
|
+
return {
|
|
165
|
+
...base,
|
|
166
|
+
index_scan_stats:s.scan_stats,
|
|
167
|
+
ecosystems:cmdInfo.suggestions.map(x=>x.ecosystem),
|
|
168
|
+
test_candidates:cmdInfo.testFiles.slice(0,25),
|
|
169
|
+
limitations:compact?['Static heuristic analysis']:['Language analysis is heuristic and static; relationships may be incomplete.'],
|
|
170
|
+
...(compact?{compact:true}:{}),
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
if(action==='tokens'){
|
|
174
|
+
// Explicit-only telemetry: do not spend computation or context space on every inspect.
|
|
175
|
+
const telemetrySummary=this.store.getTelemetrySummary(s.wsId);
|
|
176
|
+
const wsTokens=analyzeWorkspaceTokens(s.index,[],telemetrySummary);
|
|
177
|
+
base.coverage.estimated_workspace_source_tokens=wsTokens.total_estimated_tokens;
|
|
178
|
+
base.coverage.source_token_estimate_only=true;
|
|
179
|
+
const trimmedWsTokens=compact?{...wsTokens,top_consumers:wsTokens.top_consumers.slice(0,5)}:wsTokens;
|
|
180
|
+
// Current conversation is selected from A2A's SessionStart hook when
|
|
181
|
+
// present. This still works for conversations created before installing A2A.
|
|
182
|
+
const latest=scanConversationHistory({
|
|
183
|
+
dataDirPath:this.store.base,limit:1,onlyLatest:true
|
|
184
|
+
});
|
|
185
|
+
attachReportSize(latest,{format:'json'});
|
|
186
|
+
// The workspace index cannot measure Gemini usage; never auto-read private
|
|
187
|
+
// Antigravity transcripts or report fabricated percentages.
|
|
188
|
+
return {
|
|
189
|
+
...base,
|
|
190
|
+
workspace_tokens:trimmedWsTokens,
|
|
191
|
+
conversation_history:latest,
|
|
192
|
+
session_usage:{
|
|
193
|
+
status:'not_available',
|
|
194
|
+
source:null,
|
|
195
|
+
usage:null,
|
|
196
|
+
reason:'No provider-reported Antigravity CLI usage supplied. Use pilah tokens --usage-file <official agy JSON output>.',
|
|
197
|
+
},
|
|
198
|
+
...(compact?{compact:true}:{}),
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
throw new Error('Unknown context action');
|
|
202
|
+
}
|
|
203
|
+
impact({workspace,changed=[],depth=3,summary=false}={}){
|
|
204
|
+
validateChangedPaths(changed);
|
|
205
|
+
const compact=getCompactMode();
|
|
206
|
+
const s=this.sync(workspace,{verifyIntegrity:true});
|
|
207
|
+
const res=analyzeImpact(this.store,s.wsId,s.root,{changed,depth});
|
|
208
|
+
// Always-On uses this one-call triage response for risky or multi-module work.
|
|
209
|
+
// Preserve risk, uncertainty, source freshness, and total counts. Never imply
|
|
210
|
+
// this bounded preview is complete coverage.
|
|
211
|
+
if(summary){
|
|
212
|
+
return {
|
|
213
|
+
revision:s.revision,
|
|
214
|
+
changed:res.changed,
|
|
215
|
+
risk:res.risk,
|
|
216
|
+
signals:res.signals,
|
|
217
|
+
affected:res.affected.slice(0,8).map(({kind,path,label})=>({kind,path,label})),
|
|
218
|
+
affected_total:res.affected_total,
|
|
219
|
+
related_tests:res.related_tests.slice(0,5),
|
|
220
|
+
related_tests_total:res.related_tests_total,
|
|
221
|
+
fallback_test_candidates:res.fallback_test_candidates.slice(0,3),
|
|
222
|
+
coverage:{...res.coverage,output_bounded:true},
|
|
223
|
+
uncertainty:res.uncertainty,
|
|
224
|
+
incomplete_index:s.skipped.length>0,
|
|
225
|
+
summary:true,
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
const impactTokens=analyzeWorkspaceTokens(s.index,res.changed);
|
|
229
|
+
const affectedPaths=new Set([...res.changed,...res.affected.map(a=>a.path).filter(Boolean)]);
|
|
230
|
+
const fileBytes=new Map(s.index.files.map(f=>[f.path,f.bytes]));
|
|
231
|
+
let rawScopeBytes=0;
|
|
232
|
+
for(const p of affectedPaths) rawScopeBytes+=fileBytes.get(p)||0;
|
|
233
|
+
if(compact){
|
|
234
|
+
// Never shorten risk/uncertainty language to a misleading ellipsis.
|
|
235
|
+
if(res.coverage){
|
|
236
|
+
delete res.coverage.graph_nodes_visited;
|
|
237
|
+
delete res.coverage.traversal_depth;
|
|
238
|
+
}
|
|
239
|
+
if(res.signals&&res.signals.length>2) res.signals=res.signals.slice(0,2);
|
|
240
|
+
if(res.fallback_test_candidates&&res.related_tests.length>0) delete res.fallback_test_candidates;
|
|
241
|
+
}
|
|
242
|
+
const isLargeScope=(res.affected_total>=6||(res.changed.length+res.affected_total)>=8);
|
|
243
|
+
const payload={
|
|
244
|
+
revision:s.revision,
|
|
245
|
+
...res,
|
|
246
|
+
estimated_source_tokens_affected:impactTokens.changed_files_tokens,
|
|
247
|
+
source_token_estimate_only:true,
|
|
248
|
+
incomplete_index:s.skipped.some(x=>x==='index_limit_exceeded'||x==='index_byte_budget_exceeded'),
|
|
249
|
+
...(isLargeScope?{
|
|
250
|
+
teamwork_advisory:{
|
|
251
|
+
large_scope:true,
|
|
252
|
+
recommendation:'Consider native parallel assistance only if available and approved by the user. Do not assume /teamwork, /swarm, /boost or @subagent is enabled.',
|
|
253
|
+
capability_confirmed:false,
|
|
254
|
+
user_approval_required:true,
|
|
255
|
+
automatic_worker_launch:false,
|
|
256
|
+
affected_count:res.affected.length,
|
|
257
|
+
risk:res.risk,
|
|
258
|
+
}
|
|
259
|
+
}:{}),
|
|
260
|
+
...(compact?{compact:true}:{}),
|
|
261
|
+
};
|
|
262
|
+
this.store.recordTelemetry(s.wsId,{toolName:'pilah_impact',action:'impact',rawScopeTokens:estimateTokens(rawScopeBytes),responseTokens:estimateTokens(JSON.stringify(payload))});
|
|
263
|
+
return payload;
|
|
264
|
+
}
|
|
265
|
+
verify({workspace,operation='plan',criteria=[],changed=[],worker_name,artifact,allow_stale,persist_plan=false,plan_id=null}={}){
|
|
266
|
+
const compact=getCompactMode();
|
|
267
|
+
const s=this.sync(workspace,{verifyIntegrity:true});
|
|
268
|
+
if(!s.source_integrity_complete&&operation!=='plan')throw new Error('Source integrity incomplete; verification cannot make a freshness claim');
|
|
269
|
+
if(operation==='plan'){
|
|
270
|
+
validateChangedPaths(changed);
|
|
271
|
+
let plannedCriteria=criteria;
|
|
272
|
+
if(plan_id!==null){
|
|
273
|
+
if(persist_plan!==true||!Array.isArray(criteria)||criteria.length!==0)throw new Error('Reissue plan requires persist_plan=true and no replacement criteria');
|
|
274
|
+
const saved=this.store.get('SELECT * FROM acceptance_plans WHERE workspace_id=? AND id=?',s.wsId,plan_id);
|
|
275
|
+
if(!saved||sha256(saved.criteria_json)!==saved.manifest_sha)throw new Error('Unknown or invalid prior acceptance plan');
|
|
276
|
+
plannedCriteria=JSON.parse(saved.criteria_json);
|
|
277
|
+
if(!Array.isArray(plannedCriteria)||plannedCriteria.length===0||plannedCriteria.length>40)throw new Error('Invalid prior plan');
|
|
278
|
+
if(plannedCriteria.some(c=>c.source_revision && c.source_revision!==s.revision))
|
|
279
|
+
throw new Error('The prior plan pins a different source_revision; create a new reviewed plan with an explicit updated revision');
|
|
280
|
+
}
|
|
281
|
+
const plan=planVerification({index:s.index,impact:analyzeImpact(this.store,s.wsId,s.root,{changed}),criteria:plannedCriteria,compact});
|
|
282
|
+
if(plan_id!==null){
|
|
283
|
+
plan.reissued_from=plan_id;
|
|
284
|
+
plan.warning='A reissued plan retains the prior required scenarios but does not prove they were executed on current code. Rerun native tests and review new evidence.';
|
|
285
|
+
}
|
|
286
|
+
if(compact){
|
|
287
|
+
// Preserve named unknowns and required checks; drop only verbose notes.
|
|
288
|
+
if(plan.checks) delete plan.checks.note;
|
|
289
|
+
}
|
|
290
|
+
// Persist acceptance scope only on explicit opt-in; plans may contain
|
|
291
|
+
// user-authored requirements and are therefore private local content.
|
|
292
|
+
if(persist_plan===true){
|
|
293
|
+
if(plan.criteria.length===0)throw new Error('Cannot persist an empty acceptance plan');
|
|
294
|
+
const id=uniqueId('apl');
|
|
295
|
+
const manifest=JSON.stringify(plan.criteria);
|
|
296
|
+
this.store.run('INSERT INTO acceptance_plans(id,workspace_id,revision_id,manifest_sha,criteria_json,created_at) VALUES(?,?,?,?,?,?)',
|
|
297
|
+
id,s.wsId,s.revision,sha256(manifest),manifest,new Date().toISOString());
|
|
298
|
+
this.store.run('DELETE FROM acceptance_plans WHERE workspace_id=? AND id NOT IN (SELECT id FROM acceptance_plans WHERE workspace_id=? ORDER BY created_at DESC LIMIT 30)',s.wsId,s.wsId);
|
|
299
|
+
plan.plan_id=id;plan.scope_bound=true;plan.scope_persisted=true;
|
|
300
|
+
}else{plan.plan_id=null;plan.scope_bound=false;plan.scope_persisted=false;}
|
|
301
|
+
return {revision:s.revision,...plan,...(compact?{compact:true}:{})};
|
|
302
|
+
}
|
|
303
|
+
if(operation==='assess'){
|
|
304
|
+
const res=assessVerification(this.store,s.wsId,s.root,s.revision,criteria,{planId:plan_id});
|
|
305
|
+
if(compact){
|
|
306
|
+
if(res.limits){
|
|
307
|
+
res.limits=['Report origin unverified','No independent release evidence','Untested behaviors out of scope',
|
|
308
|
+
...(!res.scope_bound?['Acceptance scope is unbound; omitted planned scenarios cannot be detected']:[])];
|
|
309
|
+
}
|
|
310
|
+
res.compact=true;
|
|
311
|
+
}
|
|
312
|
+
return res;
|
|
313
|
+
}
|
|
314
|
+
if(operation==='assess_semantic'||operation==='assess_browser'){
|
|
315
|
+
if(typeof artifact!=='string'||!artifact)throw Error('Required relative evidence artifact path');
|
|
316
|
+
const full=safeFile(s.root,artifact),stat=fs.statSync(full);
|
|
317
|
+
if(!stat.isFile()||stat.size>1024*1024)throw Error('Evidence artifact exceeds 1 MiB');
|
|
318
|
+
const bytes=fs.readFileSync(full);
|
|
319
|
+
let report;
|
|
320
|
+
try{report=JSON.parse(bytes.toString('utf8'))}catch{throw Error('Invalid semantic/browser evidence JSON')}
|
|
321
|
+
let result;
|
|
322
|
+
if(operation==='assess_semantic'){
|
|
323
|
+
result=evaluateSemanticClaims(report);
|
|
324
|
+
if(result.revision!==s.revision)result={...result,report_status:'stale',release_verified:false};
|
|
325
|
+
}else{
|
|
326
|
+
const checkList=[];
|
|
327
|
+
for(const a of Array.isArray(report?.artifacts)?report.artifacts.slice(0,40):[]){
|
|
328
|
+
if(typeof a?.path!=='string'||!a.path)continue;
|
|
329
|
+
try{
|
|
330
|
+
const source=safeFile(s.root,a.path),info=fs.statSync(source);
|
|
331
|
+
if(!info.isFile()||info.size>4*1024*1024)continue;
|
|
332
|
+
checkList.push({reference:a.reference,sha256:sha256(fs.readFileSync(source)),intact:true});
|
|
333
|
+
}catch{}
|
|
334
|
+
}
|
|
335
|
+
result=assessBrowserEvidence(report,{expectedRevision:s.revision,artifactChecks:checkList});
|
|
336
|
+
}
|
|
337
|
+
// Local semantic/browser reports are never independent proof of execution.
|
|
338
|
+
const recordStatus='inconclusive';
|
|
339
|
+
const evidenceId=uniqueId('ev');
|
|
340
|
+
this.store.run('INSERT INTO evidence VALUES(?,?,?,?,?,?,?,?,?,?)',
|
|
341
|
+
evidenceId,s.wsId,s.revision,report?.scenario_id||'semantic-review',recordStatus,operation,artifact,sha256(bytes),
|
|
342
|
+
JSON.stringify({trust:'unattested-local-report',release_verified:false,summary:result.report_status||result.status,artifact_sha256:sha256(bytes)}),
|
|
343
|
+
new Date().toISOString());
|
|
344
|
+
return {revision:s.revision,evidence_id:evidenceId,...result,current_revision:s.revision,verification_verdict:'inconclusive',
|
|
345
|
+
note:'The evidence artifact is parsed and hashed locally; reported execution is not independently authenticated.'};
|
|
346
|
+
}
|
|
347
|
+
if(operation==='assess_release'){
|
|
348
|
+
if(typeof artifact!=='string'||!artifact)throw Error('Required relative release manifest');
|
|
349
|
+
const source=safeFile(s.root,artifact);
|
|
350
|
+
const manifestData=readSafeJsonFile(source,{maxBytes:1024*1024});
|
|
351
|
+
if(!manifestData.ok)throw Error('Invalid or unsafe release manifest: '+manifestData.reason);
|
|
352
|
+
const document=manifestData.value;
|
|
353
|
+
const diagnostics=[];
|
|
354
|
+
const describe=(kind,read)=>{
|
|
355
|
+
if(read.ok||read.reason==='missing')return;
|
|
356
|
+
const help=read.reason==='unsafe_mode'?'group/world writable; apply chmod 600':
|
|
357
|
+
read.reason==='symlink_parent'||read.reason==='symlink'||read.reason==='unsafe_type'?'symlink or unsafe file':
|
|
358
|
+
read.reason==='too_large'?'exceeds 64 KiB':
|
|
359
|
+
read.reason==='invalid_json'?'invalid JSON':'unreadable or invalid';
|
|
360
|
+
diagnostics.push('Local '+kind+' config rejected ('+help+').');
|
|
361
|
+
};
|
|
362
|
+
const trustFile=path.join(getHomeDir(),'.config','a2a','trusted-evaluators.json');
|
|
363
|
+
const trustRead=readSafeJsonFile(trustFile,{maxBytes:65536,checkParentDir:true,requirePrivateMode:true});
|
|
364
|
+
describe('trusted-evaluators',trustRead);
|
|
365
|
+
const trustKeys=trustRead.ok?trustRead.value:{};
|
|
366
|
+
// Frozen user-controlled scope; never read acceptance definitions from generated app.
|
|
367
|
+
const scopeFile=path.join(getHomeDir(),'.config','a2a','acceptance-registry.json');
|
|
368
|
+
const scopeRead=readSafeJsonFile(scopeFile,{maxBytes:65536,checkParentDir:true,requirePrivateMode:true});
|
|
369
|
+
describe('acceptance-registry',scopeRead);
|
|
370
|
+
const pinned=scopeRead.ok?scopeRead.value:null;
|
|
371
|
+
const requiredScenarios=pinned?.schema==='a2a-acceptance-registry-v1'&&Array.isArray(pinned.scenarios)?pinned.scenarios:null;
|
|
372
|
+
if(scopeRead.ok&&!requiredScenarios)diagnostics.push('Local acceptance-registry config rejected (invalid schema).');
|
|
373
|
+
const evaluation=assessRelease(document,{trustKeys,requiredScenarios});
|
|
374
|
+
if(diagnostics.length)evaluation.limits.push(...diagnostics);
|
|
375
|
+
if(document.revision!==s.revision){
|
|
376
|
+
evaluation.verdict='blocked';evaluation.release_ready=false;
|
|
377
|
+
evaluation.blockers.push({reason:'Current workspace snapshot differs from submitted release manifest'});
|
|
378
|
+
}
|
|
379
|
+
const evidenceId=uniqueId('ev'),bytes=manifestData.bytes;
|
|
380
|
+
this.store.run('INSERT INTO evidence VALUES(?,?,?,?,?,?,?,?,?,?)',evidenceId,s.wsId,s.revision,'release-readiness',
|
|
381
|
+
evaluation.release_ready?'passed':'inconclusive','signed-release-evaluation',artifact,sha256(bytes),
|
|
382
|
+
JSON.stringify({trust:'public-key-verified-issuer-claim',release_ready:evaluation.release_ready,signature_evidence:evaluation.scenarios.results.reduce((n,x)=>n+x.signature_verified_evidence,0)}),new Date().toISOString());
|
|
383
|
+
return {revision:s.revision,evidence_id:evidenceId,...evaluation,
|
|
384
|
+
limitations:[...evaluation.limits,'User-pinned public key is read only from local A2A config; the plugin does not create or trust keys from project source']};
|
|
385
|
+
}
|
|
386
|
+
if(operation==='verify_handoff'||operation==='handoff'){
|
|
387
|
+
validateChangedPaths(changed);
|
|
388
|
+
const res=verifyHandoff(this.store,s.wsId,s.root,s.revision,{worker_name,changed,artifact,criteria,allow_stale});
|
|
389
|
+
if(compact) res.compact=true;
|
|
390
|
+
return res;
|
|
391
|
+
}
|
|
392
|
+
throw new Error('Unknown verify operation');
|
|
393
|
+
}
|
|
394
|
+
#resolveActiveConversationId(){
|
|
395
|
+
try{
|
|
396
|
+
const sf=path.join(this.store.base,'active-session.json');
|
|
397
|
+
const d=readSafeJsonFile(sf,{maxBytes:128*1024});
|
|
398
|
+
if(d.ok&&d.value.latest?.conversationId)return d.value.latest.conversationId;
|
|
399
|
+
}catch{}
|
|
400
|
+
return process.env.ANTIGRAVITY_CONVERSATION_ID||'default';
|
|
401
|
+
}
|
|
402
|
+
evidence({workspace,operation='list',id,limit=20,title,root_cause='',paths=[],criteria=[],evidence_ids=[],hypothesis,experiment,incident_id,conversation_id,parent_conversation_id,question,summary,status,artifact_name,artifact_path,v1,v2,task_summary,completed=[],next_steps=[],decisions=[],pending_tests=[],tool_family='other',error_hint='',error_class,retry_count=0,persist_rca=false,confirm_deletion=false,hypothesis_id,parent_hypothesis_id=null,predicted_observation,disconfirming_test,expected_criterion_id,plan_id=null,experiment_outcome,observation}={}){
|
|
403
|
+
const compact=getCompactMode();
|
|
404
|
+
const isReadOnly=operation==='tool_recovery'||operation==='model_recovery'||operation==='list'||operation==='runs'||operation==='incidents'||operation==='hypotheses'||operation==='side_questions'||operation==='side-questions'||operation==='artifact_versions'||operation==='artifact-versions'||operation==='artifact_diff'||operation==='artifact-diff';
|
|
405
|
+
// Freshness is a security-relevant claim: never reuse cached revision metadata
|
|
406
|
+
// when presenting test evidence or historical run freshness.
|
|
407
|
+
const needsLiveRevision=['list','runs','model_recovery','save_checkpoint','incidents','record_incident','add_hypothesis','assess_hypothesis','hypotheses'].includes(operation);
|
|
408
|
+
const s=needsLiveRevision?this.sync(workspace,{verifyIntegrity:true}):(isReadOnly?this.resolveMeta(workspace):this.sync(workspace));
|
|
409
|
+
if(needsLiveRevision&&s.source_integrity_complete===false)throw new Error('Source integrity incomplete; evidence freshness cannot be verified');
|
|
410
|
+
const wsId=s.wsId;
|
|
411
|
+
if(operation==='tool_recovery')return classifyNativeToolFailure({error_class,error_hint,tool_family,retry_count});
|
|
412
|
+
if(operation==='save_checkpoint'){
|
|
413
|
+
if(!conversation_id)throw new Error('Explicit conversation_id is required to avoid cross-session checkpoint attribution');
|
|
414
|
+
const conv=conversation_id;
|
|
415
|
+
const saved=saveRecoveryCheckpoint(this.store,wsId,{
|
|
416
|
+
conversationId:conv,revision:s.revision,taskSummary:task_summary,
|
|
417
|
+
completed,nextSteps:next_steps,decisions,pendingTests:pending_tests
|
|
418
|
+
});
|
|
419
|
+
return {...saved,warning:'Notes are locally stored, not verified task completion; do not put secrets in checkpoints.'};
|
|
420
|
+
}
|
|
421
|
+
if(operation==='model_recovery'){
|
|
422
|
+
return {...recoveryStatus(this.store,wsId,{
|
|
423
|
+
conversationId:conversation_id||null,currentRevision:s.revision
|
|
424
|
+
}),current_revision:s.revision};
|
|
425
|
+
}
|
|
426
|
+
if(operation==='list')return {revision:s.revision,...listEvidence(this.store,wsId,s.root,s.revision,{limit,id}),...(compact?{compact:true}:{})};
|
|
427
|
+
if(operation==='runs')return {revision:s.revision,runs:this.store.all('SELECT id,revision_id,verdict,criteria_json,created_at FROM runs WHERE workspace_id=? ORDER BY created_at DESC LIMIT ?',wsId,Math.max(1,Math.min(50,Number(limit)||20))).map(x=>({...x,fresh:x.revision_id===s.revision,criteria:JSON.parse(x.criteria_json),criteria_json:undefined})),...(compact?{compact:true}:{})};
|
|
428
|
+
if(operation==='incidents')return {...listRcaIncidents(this.store,wsId,s.revision,compact?Math.min(8,Number(limit)||20):limit),...(compact?{compact:true}:{})};
|
|
429
|
+
if(operation==='record_incident')return {...recordRcaIncident(this.store,wsId,s.root,s.revision,{title,root_cause,paths,criteria,evidence_ids,persist_rca}),...(compact?{compact:true}:{})};
|
|
430
|
+
if(operation==='add_hypothesis')return {...addRcaHypothesis(this.store,wsId,s.revision,{
|
|
431
|
+
hypothesis,experiment,incident_id,parent_hypothesis_id,predicted_observation,disconfirming_test,expected_criterion_id,plan_id,persist_rca
|
|
432
|
+
}),...(compact?{compact:true}:{})};
|
|
433
|
+
if(operation==='assess_hypothesis')return {...assessRcaHypothesis(this.store,wsId,s.root,s.revision,{
|
|
434
|
+
hypothesis_id,experiment_outcome,observation,evidence_ids,persist_rca
|
|
435
|
+
}),...(compact?{compact:true}:{})};
|
|
436
|
+
if(operation==='hypotheses')return {...listRcaHypotheses(this.store,wsId,s.root,s.revision,compact?Math.min(8,Number(limit)||20):limit,incident_id||null),...(compact?{compact:true}:{})};
|
|
437
|
+
if(operation==='delete_incident')return deleteRcaIncident(this.store,wsId,{incident_id,persist_rca,confirm_deletion});
|
|
438
|
+
if(operation==='side_questions'||operation==='side-questions'){
|
|
439
|
+
const items=this.store.listSideQuestions({workspaceId:wsId,parentConversationId:parent_conversation_id,conversationId:conversation_id||id,limit});
|
|
440
|
+
return {workspace:s.root,count:items.length,items,...(compact?{compact:true}:{})};
|
|
441
|
+
}
|
|
442
|
+
if(operation==='record_side_question'||operation==='record-side-question'){
|
|
443
|
+
const cid=conversation_id||id;
|
|
444
|
+
const qText=question||title;
|
|
445
|
+
if(!cid||!qText)throw new Error('conversation_id (or id) and question (or title) are required to record a side question');
|
|
446
|
+
const record=this.store.recordSideQuestion({
|
|
447
|
+
workspaceId:wsId,
|
|
448
|
+
conversationId:cid,
|
|
449
|
+
parentConversationId:parent_conversation_id||null,
|
|
450
|
+
title:title||null,
|
|
451
|
+
question:qText,
|
|
452
|
+
summary:summary||null,
|
|
453
|
+
status:status||'resolved'
|
|
454
|
+
});
|
|
455
|
+
return {status:'recorded',side_question:record,...(compact?{compact:true}:{})};
|
|
456
|
+
}
|
|
457
|
+
if(operation==='artifact_versions'||operation==='artifact-versions'){
|
|
458
|
+
const convId=conversation_id||id||this.#resolveActiveConversationId();
|
|
459
|
+
const items=this.store.listArtifactVersions({workspaceId:wsId,conversationId:convId,artifactName:artifact_name,limit});
|
|
460
|
+
return {conversation_id:convId,artifact_name:artifact_name||null,count:items.length,versions:items,...(compact?{compact:true}:{})};
|
|
461
|
+
}
|
|
462
|
+
if(operation==='artifact_diff'||operation==='artifact-diff'){
|
|
463
|
+
const convId=conversation_id||id||this.#resolveActiveConversationId();
|
|
464
|
+
if(!artifact_name)throw new Error('artifact_name is required for artifact_diff');
|
|
465
|
+
const diffRes=this.store.getArtifactDiff({workspaceId:wsId,conversationId:convId,artifactName:artifact_name,v1,v2});
|
|
466
|
+
return {conversation_id:convId,...(diffRes||{artifact_name,v1,v2,diff:''}),...(compact?{compact:true}:{})};
|
|
467
|
+
}
|
|
468
|
+
if(operation==='snapshot_artifact'||operation==='snapshot-artifact'){
|
|
469
|
+
const convId=conversation_id||id;
|
|
470
|
+
if(!convId)throw new Error('Explicit conversation_id is required for an artifact snapshot');
|
|
471
|
+
if(!artifact_path&&!artifact_name)throw new Error('artifact_path or artifact_name is required');
|
|
472
|
+
const targetPath=artifact_path
|
|
473
|
+
? (path.isAbsolute(artifact_path)?artifact_path:path.resolve(s.root,artifact_path))
|
|
474
|
+
: path.join(getHomeDir(),'.gemini','antigravity','brain',convId,artifact_name);
|
|
475
|
+
// Absolute path identity, including macOS /private aliases and case normalization,
|
|
476
|
+
// must be verified against this authorized workspace rather than process.cwd().
|
|
477
|
+
const absolute=path.resolve(targetPath);
|
|
478
|
+
const inWorkspace=isSameOrDescendantPath(s.root,absolute)&&!isSamePath(s.root,absolute);
|
|
479
|
+
if(!inWorkspace){
|
|
480
|
+
const sessionFile=path.join(this.store.base,'active-session.json');
|
|
481
|
+
let latest=null;
|
|
482
|
+
try{const d=readSafeJsonFile(sessionFile,{maxBytes:128*1024});latest=d.ok?d.value.latest:null}catch{}
|
|
483
|
+
if(latest?.conversationId!==convId || !Array.isArray(latest.workspacePaths)
|
|
484
|
+
|| !latest.workspacePaths.some(w=>{try{return requireAuthorizedWorkspace(w)===s.root}catch{return false}})){
|
|
485
|
+
throw new Error('Brain artifact does not belong to the active authorized workspace/session');
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
const snap=this.store.snapshotArtifact({workspaceId:wsId,conversationId:convId,artifactPath:targetPath,workspaceRoot:s.root});
|
|
489
|
+
return {status:'snapshotted',snapshot:snap,...(compact?{compact:true}:{})};
|
|
490
|
+
}
|
|
491
|
+
throw new Error('Unknown evidence operation');
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
export function guardedCall(fn,args){try{return fn(args||{})}catch(e){return {status:'error',message:cleanError(e),retryable:false}}}
|