@aliip/pilah 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/BUILD_STATUS.md +23 -0
  2. package/LICENSE +21 -0
  3. package/README.md +108 -2
  4. package/assets/logo.svg +5 -0
  5. package/docs/ACCEPTANCE_GATE.md +41 -0
  6. package/docs/ADAPTIVE_RCA_WORKFLOW.md +93 -0
  7. package/docs/AGENT_DECISION_REVIEW.md +17 -0
  8. package/docs/ALWAYS_ON_5_WHYS.md +75 -0
  9. package/docs/ARCHITECTURE.md +43 -0
  10. package/docs/BEHAVIORAL_5_WHYS_V2_0_1.md +117 -0
  11. package/docs/CHECKPOINT_RECOVERY.md +86 -0
  12. package/docs/CI_EFFICIENCY.md +63 -0
  13. package/docs/COMPATIBILITY.md +84 -0
  14. package/docs/CONTRACTS.md +177 -0
  15. package/docs/CONVERSATION_USAGE.md +52 -0
  16. package/docs/ENGINEERING_METHOD.md +68 -0
  17. package/docs/HOST_VALIDATION.md +35 -0
  18. package/docs/INDEPENDENT_ACCEPTANCE_RUNBOOK.md +72 -0
  19. package/docs/INTERVENTION_LEDGER.md +25 -0
  20. package/docs/MAIN_VALIDATION_BACKLOG.md +19 -0
  21. package/docs/NATIVE_FIRST_WORKFLOW.md +27 -0
  22. package/docs/OPEN_SOURCE_ENGINEERING_STANDARDS.md +62 -0
  23. package/docs/ORCHESTRATION_ADVISOR.md +36 -0
  24. package/docs/PRE_VNEXT_INTEGRATION.md +27 -0
  25. package/docs/README.md +54 -0
  26. package/docs/RELEASE.md +33 -0
  27. package/docs/RELEASE_AUTHORIZATION.md +33 -0
  28. package/docs/RISK_GUIDANCE.md +18 -0
  29. package/docs/SECURITY.md +76 -0
  30. package/docs/SECURITY_RELIABILITY_AUDIT_V2_0_1.md +55 -0
  31. package/docs/SEMANTIC_EVIDENCE.md +27 -0
  32. package/docs/SOURCES.md +13 -0
  33. package/docs/TOKEN_EFFICIENCY.md +71 -0
  34. package/docs/TOKEN_PROVENANCE.md +15 -0
  35. package/docs/V2_0_1_TRACEABILITY.md +66 -0
  36. package/hooks.json +45 -0
  37. package/mcp_config.json +16 -0
  38. package/package.json +31 -4
  39. package/plugin.json +27 -0
  40. package/rules/AGENTS.md +2 -0
  41. package/schemas/database.sql +84 -0
  42. package/schemas/mcp-tools.json +552 -0
  43. package/scripts/a2a.mjs +344 -0
  44. package/scripts/check-release.mjs +42 -0
  45. package/scripts/check-syntax.mjs +30 -0
  46. package/scripts/checkpoint.mjs +50 -0
  47. package/scripts/compare-agent-traces.mjs +53 -0
  48. package/scripts/context-guardian.mjs +132 -0
  49. package/scripts/evaluate-acceptance.mjs +110 -0
  50. package/scripts/export-benchmark.mjs +31 -0
  51. package/scripts/generate-contracts.mjs +6 -0
  52. package/scripts/hook.mjs +406 -0
  53. package/scripts/host-check.mjs +40 -0
  54. package/scripts/intervention-ledger.mjs +94 -0
  55. package/scripts/pilah.mjs +3 -0
  56. package/scripts/release-authorization.mjs +137 -0
  57. package/scripts/review-agent-decisions.mjs +34 -0
  58. package/scripts/semantic-evidence.mjs +15 -0
  59. package/scripts/verifykit.mjs +3 -0
  60. package/skills/pilah/SKILL.md +24 -0
  61. package/src/acceptance-matrix.mjs +84 -0
  62. package/src/browser-evidence.mjs +40 -0
  63. package/src/context-health.mjs +14 -0
  64. package/src/conversations.mjs +302 -0
  65. package/src/engine.mjs +494 -0
  66. package/src/graph.mjs +169 -0
  67. package/src/mcp-diagnostics.mjs +53 -0
  68. package/src/mcp.mjs +151 -0
  69. package/src/model-recovery.mjs +108 -0
  70. package/src/native-tool-recovery.mjs +45 -0
  71. package/src/node-runtime.mjs +13 -0
  72. package/src/orchestration-advisor.mjs +24 -0
  73. package/src/rca.mjs +174 -0
  74. package/src/risk-guidance.mjs +95 -0
  75. package/src/scanner.mjs +303 -0
  76. package/src/security.mjs +793 -0
  77. package/src/semantic-evidence.mjs +144 -0
  78. package/src/skill-discovery.mjs +23 -0
  79. package/src/sqlite-compat.mjs +11 -0
  80. package/src/storage.mjs +455 -0
  81. package/src/tokens.mjs +627 -0
  82. package/src/tools.mjs +164 -0
  83. package/src/verification.mjs +567 -0
  84. package/src/workflow-router.mjs +34 -0
@@ -0,0 +1,406 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {pathToFileURL} from 'node:url';
5
+ import { dataDir, getA2AMode, getArtifactAutoSnapshotMode, getHomeDir, requireAuthorizedWorkspace } from '../src/security.mjs';
6
+ import { sanitizeConversationId, vettedTranscript } from '../src/tokens.mjs';
7
+ import { Store } from '../src/storage.mjs';
8
+ import {gitChanges} from '../src/scanner.mjs';
9
+ import {Engine} from '../src/engine.mjs';
10
+ import {CANDIDATE_ARTIFACTS} from '../src/verification.mjs';
11
+ import {safeFile,sha256,debugLog} from '../src/security.mjs';
12
+
13
+ function writeJsonSecure(filePath, obj) {
14
+ const dir = path.dirname(filePath);
15
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
16
+ // Atomic replacement avoids a torn active-session record after interruption.
17
+ const temp=filePath+'.'+process.pid+'.'+globalThis.crypto.randomUUID()+'.tmp';
18
+ const flags=fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL|(fs.constants.O_NOFOLLOW||0);
19
+ let fd=null;
20
+ try{
21
+ fd=fs.openSync(temp,flags,0o600);
22
+ fs.writeFileSync(fd,JSON.stringify(obj,null,2)+'\n');
23
+ fs.closeSync(fd);fd=null;
24
+ fs.renameSync(temp,filePath);
25
+ }finally{
26
+ if(fd!==null)fs.closeSync(fd);
27
+ try{fs.unlinkSync(temp)}catch{}
28
+ }
29
+ }
30
+
31
+ function safeLocalJson(file,maxBytes=128*1024){
32
+ try{
33
+ const stat=fs.lstatSync(file);
34
+ if(!stat.isFile()||stat.isSymbolicLink()||stat.size>maxBytes)return null;
35
+ const value=JSON.parse(fs.readFileSync(file,'utf8'));
36
+ return value&&typeof value==='object'&&!Array.isArray(value)?value:null;
37
+ }catch(error){debugLog('hook_metadata',error);return null}
38
+ }
39
+ function hookArgs(payload){
40
+ const input=payload?.toolCall?.args||payload?.toolArgs||payload?.toolInput||payload?.arguments;
41
+ return input&&typeof input==='object'&&!Array.isArray(input)?input:{};
42
+ }
43
+ export function isDirectTestCommand(value){
44
+ if(typeof value!=='string'||!value.trim()||value.length>2000)return false;
45
+ let cmd=value.trim();
46
+ // Refuse shell chaining, masked exit status, command substitution, pipes,
47
+ // redirections, comments and multiline invocations. Only an optional cd
48
+ // prefix is allowed before one direct test runner.
49
+ if(/[\r\n;|<>\x60]/.test(cmd)||/\$\s*\(|\$\{/.test(cmd)||/\s#/.test(cmd))return false;
50
+ if(cmd.includes('&&')){
51
+ const match=cmd.match(/^cd\s+[A-Za-z0-9./_~-]+\s*&&\s*(.+)$/i);
52
+ if(!match||match[1].includes('&&'))return false;
53
+ cmd=match[1].trim();
54
+ }
55
+ if(/[&]/.test(cmd))return false;
56
+ cmd=cmd.replace(/^(?:(?:[A-Za-z_][A-Za-z0-9_]*)=[A-Za-z0-9._:/=-]+\s+){0,8}/,'');
57
+ cmd=cmd.replace(/^(?:npx|bunx|uv\s+run|poetry\s+run)\s+/i,'');
58
+ const runner=/^(?:npm\s+(?:run\s+)?test(?:\b|:)|pnpm\s+(?:(?:run|exec)\s+)?(?:test|vitest|jest)(?:\b|:)|yarn\s+(?:(?:run)\s+)?(?:test|vitest|jest)(?:\b|:)|bun\s+(?:(?:run)\s+)?test\b|node\s+--test\b|python3?\s+-m\s+(?:pytest|unittest)\b|pytest\b|phpunit\b|pest\b|vitest\b|jest\b|mocha\b|cargo\s+test\b|go\s+test\b|dotnet\s+test\b|flutter\s+test\b|dart\s+test\b|swift\s+test\b|mvn\s+test\b|(?:\.\/)?gradlew\s+test\b|php\s+artisan\s+test\b)/i;
59
+ return runner.test(cmd);
60
+ }
61
+
62
+ export function detectSideQuestionInfo(payload, transcriptPath) {
63
+ let isSideQuestion = Boolean(payload?.isSideQuestion || payload?.sideQuestion);
64
+ let parentConversationId = payload?.parentConversationId || null;
65
+ let initialQuestion = null;
66
+ const currentConvId = sanitizeConversationId(payload?.conversationId);
67
+
68
+ // Internal transcripts are diagnostic only; never read arbitrarily large logs in a hook.
69
+ const vetted=vettedTranscript(transcriptPath,currentConvId);
70
+ if (vetted && fs.statSync(vetted.logFile).size <= 64 * 1024) {
71
+ try {
72
+ const stream = fs.readFileSync(vetted.logFile, 'utf8');
73
+ if (stream.includes('<side_question>') || stream.includes('side question (/btw)')) {
74
+ isSideQuestion = true;
75
+ }
76
+ if (!parentConversationId) {
77
+ const matches = [...stream.matchAll(/brain\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/gi)];
78
+ for (const m of matches) {
79
+ if (m[1] && m[1] !== currentConvId) {
80
+ parentConversationId = m[1];
81
+ break;
82
+ }
83
+ }
84
+ }
85
+ const lines = stream.split('\n');
86
+ for (const line of lines) {
87
+ if (!line.trim()) continue;
88
+ try {
89
+ const row = JSON.parse(line);
90
+ if (row.type === 'USER_INPUT' && row.content) {
91
+ const cleanText = row.content
92
+ .replace(/<USER_REQUEST>|<\/USER_REQUEST>/g, '')
93
+ .replace(/<ADDITIONAL_METADATA>[\s\S]*?<\/ADDITIONAL_METADATA>/g, '')
94
+ .replace(/<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/g, '')
95
+ .trim();
96
+ if (cleanText) {
97
+ initialQuestion = cleanText.slice(0, 1000);
98
+ break;
99
+ }
100
+ }
101
+ } catch {}
102
+ }
103
+ } catch {}
104
+ }
105
+
106
+ if (!isSideQuestion && currentConvId) {
107
+ try {
108
+ const metaCache = path.join(getHomeDir(),'.gemini','antigravity-cli','cache','conversation_metadata.json');
109
+ const data=safeLocalJson(metaCache,64*1024);
110
+ if(data?.conversations?.[currentConvId]?.is_internal)isSideQuestion=true;
111
+ } catch {}
112
+ }
113
+
114
+ return { isSideQuestion, parentConversationId, initialQuestion };
115
+ }
116
+
117
+ function recordActiveSession(payload, baseDir) {
118
+ const convId = sanitizeConversationId(payload?.conversationId);
119
+ const transcriptPath = vettedTranscript(payload?.transcriptPath,convId)?.logFile||null;
120
+ const workspacePaths = Array.isArray(payload?.workspacePaths)
121
+ ? payload.workspacePaths.filter(w => typeof w === 'string' && w.length<=1024 && path.isAbsolute(w)).slice(0,32)
122
+ : [];
123
+ const cwd = typeof payload?.cwd === 'string' && payload.cwd.length<=1024 && path.isAbsolute(payload.cwd) ? payload.cwd : null;
124
+ if (!convId) return;
125
+
126
+ const sessionFile = path.join(baseDir, 'active-session.json');
127
+ const existing=safeLocalJson(sessionFile)||{};
128
+
129
+ const prev = existing.latest || {};
130
+ const prevWs = Array.isArray(prev.workspacePaths) ? prev.workspacePaths.join('|') : '';
131
+ const nextWs = workspacePaths.join('|');
132
+ if (prev.conversationId === convId && prev.transcriptPath === transcriptPath && prevWs === nextWs && prev.cwd === cwd) {
133
+ return;
134
+ }
135
+
136
+ const sideQ = process.env.A2A_TRACK_SIDE_QUESTIONS==='1'
137
+ ? detectSideQuestionInfo(payload, transcriptPath)
138
+ : {isSideQuestion:false,parentConversationId:null,initialQuestion:null};
139
+ const now = new Date().toISOString();
140
+ const entry = {
141
+ conversationId: convId,
142
+ transcriptPath,
143
+ workspacePaths,
144
+ cwd,
145
+ modelName: typeof payload?.modelName === 'string' ? payload.modelName.slice(0,100) : null,
146
+ updatedAt: now,
147
+ ...(sideQ.isSideQuestion ? {
148
+ sideQuestion: {
149
+ isSideQuestion: true,
150
+ parentConversationId: sideQ.parentConversationId,
151
+ question: sideQ.initialQuestion,
152
+ }
153
+ } : {}),
154
+ };
155
+
156
+ if (sideQ.isSideQuestion && convId) {
157
+ try {
158
+ const store = new Store(baseDir);
159
+ try {
160
+ let wsId = null;
161
+ if (workspacePaths.length > 0) {
162
+ try { wsId = store.register(requireAuthorizedWorkspace(workspacePaths[0])); } catch {}
163
+ }
164
+ if(wsId) store.recordSideQuestion({
165
+ workspaceId: wsId,
166
+ conversationId: convId,
167
+ parentConversationId: sideQ.parentConversationId,
168
+ question: sideQ.initialQuestion || 'Side Question',
169
+ transcriptPath,
170
+ status: 'active'
171
+ });
172
+ } finally {
173
+ store.close();
174
+ }
175
+ } catch {}
176
+ }
177
+
178
+ const byWorkspace = (existing.byWorkspace && typeof existing.byWorkspace === 'object') ? { ...existing.byWorkspace } : {};
179
+ for (const ws of workspacePaths) {
180
+ byWorkspace[ws] = { conversationId: convId, transcriptPath, updatedAt: now };
181
+ }
182
+ if (cwd && !byWorkspace[cwd]) {
183
+ byWorkspace[cwd] = { conversationId: convId, transcriptPath, updatedAt: now };
184
+ }
185
+
186
+ // Cap retained workspace metadata; the current session is stored separately.
187
+ const recent=Object.entries(byWorkspace).sort((a,b)=>Date.parse(b[1]?.updatedAt||0)-Date.parse(a[1]?.updatedAt||0)).slice(0,100);
188
+ writeJsonSecure(sessionFile, { updatedAt: now, latest: entry, byWorkspace:Object.fromEntries(recent) });
189
+
190
+ // Do not bulk-copy conversation artifacts when a session starts. Only snapshot
191
+ // explicit edit events or direct user requests; avoids needless I/O and retention.
192
+ }
193
+
194
+ function handleArtifactModification(payload, baseDir) {
195
+ // Full-content brain Markdown history is opt-in; session metadata remains
196
+ // independent and does not itself grant content-retention consent.
197
+ if(!getArtifactAutoSnapshotMode() || payload?.error) return;
198
+ const toolName = payload?.toolCall?.name || payload?.toolName || '';
199
+ if (!['write_to_file','replace_file_content','multi_replace_file_content','write_file','edit_file'].includes(toolName)) return;
200
+ const args=hookArgs(payload);
201
+ const filePath = args?.TargetFile || args?.Path || args?.path;
202
+ const convId = sanitizeConversationId(payload?.conversationId);
203
+ if (!convId || typeof filePath !== 'string' || !filePath.endsWith('.md')) return;
204
+ // Accept Windows separators for matching, but let safeArtifactPath validate the
205
+ // actual OS path and session-specific boundary (including symlinks).
206
+ const normalized = filePath.replaceAll('\\','/');
207
+ if (!normalized.includes('/brain/'+convId+'/')) return;
208
+ const workspaces = Array.isArray(payload?.workspacePaths) ? payload.workspacePaths : [];
209
+ const candidates = [...workspaces, payload?.cwd].filter(p=>typeof p==='string');
210
+ let root=null;
211
+ for(const candidate of candidates){
212
+ try{root=requireAuthorizedWorkspace(candidate);break}catch{}
213
+ }
214
+ if(!root) return;
215
+ try{
216
+ const store=new Store(baseDir);
217
+ try{
218
+ const wsId=store.register(root);
219
+ store.snapshotArtifact({workspaceId:wsId,workspaceRoot:root,conversationId:convId,artifactPath:filePath});
220
+ }finally{store.close()}
221
+ }catch{}
222
+ }
223
+
224
+ // A completed tool call is not proof of a successful test process. Accept
225
+ // explicit numeric exit statuses only; missing/conflicting signals fail closed.
226
+ // Antigravity versions can expose different nested response objects.
227
+ export function nativeProcessExitStatus(payload){
228
+ const sources=[payload,payload?.toolCallResult,payload?.toolResponse,payload?.response,payload?.result,payload?.toolResult];
229
+ const codes=[];
230
+ for(const source of sources){
231
+ if(!source||typeof source!=='object'||Array.isArray(source))continue;
232
+ for(const key of ['exitCode','exit_code','commandExitCode','processExitCode']){
233
+ if(Object.hasOwn(source,key) && source[key]!==null && source[key]!==undefined){
234
+ const code=source[key];
235
+ if(!Number.isSafeInteger(code))return {status:'unknown',exit_code:null,reason:'Invalid exit status representation'};
236
+ codes.push(code);
237
+ }
238
+ }
239
+ }
240
+ if(payload?.error || payload?.toolResponse?.error || payload?.toolCallResult?.error)return {status:'failed',exit_code:codes[0]??null,reason:'Native tool reported an error'};
241
+ if(!codes.length)return {status:'unknown',exit_code:null,reason:'No explicit process exit status available'};
242
+ if(codes.some(x=>x!==codes[0]))return {status:'unknown',exit_code:null,reason:'Conflicting native process exit statuses'};
243
+ return {status:codes[0]===0?'passed':'failed',exit_code:codes[0],reason:null};
244
+ }
245
+
246
+
247
+ function pendingTestFile(baseDir,payload){
248
+ const conv=sanitizeConversationId(payload?.conversationId),idx=payload?.stepIdx;
249
+ if(!conv||!Number.isSafeInteger(idx)||idx<0)return null;
250
+ return path.join(baseDir,'pending-tests',sha256(conv+':'+idx).slice(0,32)+'.json');
251
+ }
252
+ function reporterSnapshot(root,rel){
253
+ try{
254
+ const file=safeFile(root,rel),st=fs.statSync(file);
255
+ if(!st.isFile()||st.size>1200000)return null;
256
+ return {exists:true,hash:sha256(fs.readFileSync(file))};
257
+ }catch{return {exists:false}}
258
+ }
259
+ function recordPreTestRun(payload,baseDir){
260
+ const args=hookArgs(payload),cmd=args.CommandLine||args.commandLine||args.command;
261
+ if(!isDirectTestCommand(cmd))return;
262
+ const file=pendingTestFile(baseDir,payload);
263
+ if(!file)return;
264
+ const candidates=[args.Cwd||args.cwd,payload?.cwd,...(payload?.workspacePaths||[])].filter(v=>typeof v==='string');
265
+ let root=null;
266
+ for(const candidate of candidates){try{root=requireAuthorizedWorkspace(candidate);break}catch{}}
267
+ if(!root)return;
268
+ const reports={};
269
+ const cmdPath=cmd.replaceAll('\\','/');
270
+ for(const rel of CANDIDATE_ARTIFACTS){
271
+ if(cmdPath.includes(rel)||cmdPath.includes(path.posix.basename(rel)))
272
+ reports[rel]=reporterSnapshot(root,rel);
273
+ }
274
+ writeJsonSecure(file,{
275
+ kind:'native-test-preflight-v1',conversationId:sanitizeConversationId(payload.conversationId),
276
+ stepIdx:payload.stepIdx,workspace:root,command_hash:sha256(cmd),started_at:Date.now(),reports
277
+ });
278
+ }
279
+ function consumeTestPreflight(payload,baseDir,cmd,workspace){
280
+ const file=pendingTestFile(baseDir,payload);if(!file)return null;
281
+ const prior=safeLocalJson(file,32*1024);
282
+ try{fs.unlinkSync(file)}catch{}
283
+ if(prior?.kind!=='native-test-preflight-v1'
284
+ ||prior.conversationId!==sanitizeConversationId(payload?.conversationId)
285
+ ||prior.stepIdx!==payload.stepIdx||prior.workspace!==workspace
286
+ ||prior.command_hash!==sha256(cmd))return null;
287
+ const elapsed=Date.now()-prior.started_at;
288
+ if(!Number.isFinite(elapsed)||elapsed<0||elapsed>15*60*1000)return null;
289
+ return prior;
290
+ }
291
+
292
+ function recordCommandRun(payload, baseDir) {
293
+ handleArtifactModification(payload, baseDir);
294
+ const args=hookArgs(payload);
295
+ const cmd=args.CommandLine||args.commandLine||args.command;
296
+ if(typeof cmd!=='string'||!cmd.trim())return;
297
+ const direct=isDirectTestCommand(cmd);
298
+ const suspicious=!direct&&/\b(?:npm\s+(?:run\s+)?test|node\s+--test|pytest|phpunit|pest|vitest|jest|mocha|cargo\s+test|go\s+test|dotnet\s+test|flutter\s+test|swift\s+test|mvn\s+test|gradlew\s+test|php\s+artisan\s+test)\b/i.test(cmd);
299
+ if(!direct&&!suspicious)return;
300
+ const candidates=[args.Cwd||args.cwd,payload?.cwd,...(payload?.workspacePaths||[])].filter(p=>typeof p==='string');
301
+ let root=null;
302
+ for(const p of candidates){try{root=requireAuthorizedWorkspace(p);break}catch{}}
303
+ if(!root)return;
304
+ const exit=direct?nativeProcessExitStatus(payload):{status:'unknown',exit_code:null};
305
+ // Failed/unknown processes need no expensive workspace/report hashing.
306
+ const sourceHashes={};
307
+ const changed=exit.status==='passed'
308
+ ? gitChanges(root).filter(p=>/\.(?:js|ts|jsx|tsx|mjs|cjs|php|py|go|rs|kt|java|dart|gd|swift|cs|rb|vue|svelte|sql)$/i.test(p))
309
+ : [];
310
+ for(const rel of changed.slice(0,200)){
311
+ try{sourceHashes[rel]=sha256(fs.readFileSync(safeFile(root,rel)))}catch{}
312
+ }
313
+ // A successful command is not proof it generated an unrelated existing report.
314
+ // Only explicitly named, recently written reporter output is eligible for
315
+ // bounded local correlation; no independent execution attestation is implied.
316
+ let sourceRevision=null;
317
+ if(exit.status==='passed'){
318
+ let engine;
319
+ try{engine=new Engine();const state=engine.sync(root,{verifyIntegrity:true});if(state.source_integrity_complete)sourceRevision=state.revision;}
320
+ catch(error){debugLog('hook_source_revision',error)}finally{try{engine?.close()}catch{}}
321
+ }
322
+ const reportHashes={},reportBindings={};
323
+ const preflight=consumeTestPreflight(payload,baseDir,cmd,root);
324
+ const reportArg=cmd.replaceAll('\\\\','/');const finishedAt=Date.now();
325
+ for(const rel of exit.status==='passed'&&sourceRevision?CANDIDATE_ARTIFACTS:[]){
326
+ try{
327
+ const file=safeFile(root,rel);
328
+ const stat=fs.statSync(file);
329
+ const before=preflight?.reports?.[rel];
330
+ if(stat.size<=1200000&&stat.isFile()&&before&&
331
+ (reportArg.includes(rel)||reportArg.includes(path.posix.basename(rel)))&&
332
+ stat.mtimeMs>=preflight.started_at-2000&&stat.mtimeMs<=finishedAt+2000){
333
+ const currentHash=sha256(fs.readFileSync(file));
334
+ if(before.exists===false||(before.exists===true&&before.hash!==currentHash)){
335
+ reportHashes[rel]=currentHash;reportBindings[rel]=true;
336
+ }
337
+ }
338
+ }catch{}
339
+ }
340
+ // Clear positive provenance after unsuccessful or ambiguous runs. A pre-existing
341
+ // passing report must not be re-attested by a failed/unknown native command.
342
+ const reportFile=path.join(baseDir,'last-test-run.json');
343
+ writeJsonSecure(reportFile,{
344
+ updatedAt:new Date().toISOString(),
345
+ conversationId:sanitizeConversationId(payload?.conversationId),
346
+ workspace:root,
347
+ kind:'native-test-tool-completed',
348
+ succeeded:exit.status==='passed',
349
+ exit_status:exit.status,
350
+ exit_code:exit.exit_code,
351
+ source_hashes:exit.status==='passed'?sourceHashes:{},
352
+ report_hashes:exit.status==='passed'?reportHashes:{},
353
+ report_bindings:exit.status==='passed'?reportBindings:{},
354
+ source_revision:exit.status==='passed'?sourceRevision:null,
355
+ });
356
+ }
357
+
358
+ export const ALWAYS_ON_POLICY = 'PILAH Always-On (opt-in): Native first; zero calls for clear tasks. Before coding, reuse existing code or platform primitives. If cross-file uncertainty remains, use eager PILAH context once (pilah_context, workspace=<trusted project>, limit=5). Other tools lazy: discover their schema. No chains without new evidence. Local PASS is not E2E.';
359
+
360
+ export function handleHookEvent(payload, { baseDir = dataDir() } = {}) {
361
+ if (!payload || typeof payload !== 'object') return {};
362
+ const event = payload.hookEventName || payload.hook_event_name || '';
363
+
364
+ if (event === 'SessionStart') {
365
+ recordActiveSession(payload, baseDir);
366
+ } else if (event === 'PreToolUse') {
367
+ recordPreTestRun(payload, baseDir);
368
+ return {decision:'allow'}; // Defer to native Antigravity permission policy.
369
+ } else if (event === 'PostToolUse') {
370
+ recordCommandRun(payload, baseDir);
371
+ return {};
372
+ }
373
+
374
+ if (event === 'SessionStart') {
375
+ // In on-demand mode do not inject instructions into every Antigravity session.
376
+ if (getA2AMode() !== 'always-on') return {};
377
+ return {
378
+ injectSteps: [{systemMessage:{systemMessage:ALWAYS_ON_POLICY}}],
379
+ };
380
+ }
381
+
382
+ return {};
383
+ }
384
+
385
+ const isEntry = process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href;
386
+ if (isEntry) {
387
+ let raw = '';
388
+ try {
389
+ // Hooks are best-effort metadata handlers, never unbounded stdin consumers.
390
+ const chunks=[],buffer=Buffer.alloc(32768);let bytes=0;
391
+ for(;;){
392
+ const count=fs.readSync(0,buffer,0,buffer.length,null);
393
+ if(!count)break;
394
+ bytes+=count;
395
+ if(bytes>256*1024)throw Error('Hook payload exceeds safe limit');
396
+ chunks.push(Buffer.from(buffer.subarray(0,count)));
397
+ }
398
+ raw = Buffer.concat(chunks).toString('utf8');
399
+ const payload = raw.trim() ? JSON.parse(raw) : {};
400
+ const out = handleHookEvent(payload);
401
+ process.stdout.write(JSON.stringify(out) + '\n');
402
+ } catch {
403
+ process.stdout.write('{}\n');
404
+ }
405
+ process.exit(0);
406
+ }
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ // Explicit, read-only host preflight. No plugin install, model call or background daemon.
3
+ import path from 'node:path';
4
+ import {fileURLToPath} from 'node:url';
5
+ import {spawnSync} from 'node:child_process';
6
+
7
+ const root=path.resolve(fileURLToPath(new URL('..',import.meta.url)));
8
+ const base={live_agent_adoption:'not_tested',independent_e2e:'not_tested',
9
+ model_token_savings:'not_measured',
10
+ note:'Host CLI validation is not evidence that Antigravity selected PILAH appropriately during an IDE coding session.'};
11
+
12
+ export function checkHost({command='agy',cwd=root,exec=spawnSync}={}){
13
+ const run=(args)=>{try{return exec(command,args,{cwd,encoding:'utf8',windowsHide:true,timeout:20000,maxBuffer:128*1024})}
14
+ catch{return {status:null,error:{code:'EUNKNOWN'}}}};
15
+ const version=run(['--version']);
16
+ if(version.error||version.status!==0)return {...base,status:'blocked',
17
+ cli:'not_available',validation:'not_run',installed:'unknown',
18
+ next_step:'Install or expose the official Antigravity CLI on PATH, then rerun node scripts/pilah.mjs host-check.'};
19
+ const validated=run(['plugin','validate','--strict','.']);
20
+ if(validated.error||validated.status!==0)return {...base,status:'failed',
21
+ cli:'available',validation:'failed',installed:'unknown',
22
+ next_step:'Run agy plugin validate --strict . locally and review its private diagnostics; do not bypass strict validation.'};
23
+ const listed=run(['plugin','list']);
24
+ if(listed.error||listed.status!==0)return {...base,status:'partial',
25
+ cli:'available',validation:'passed',installed:'unknown',
26
+ next_step:'Inspect agy plugin list and the active Antigravity plugin manager; test real tool discovery separately.'};
27
+ const found=/(^|[^a-z0-9_-])pilah([^a-z0-9_-]|$)/i.test(String(listed.stdout||''));
28
+ return {...base,status:found?'local-preflight-passed':'partial',
29
+ cli:'available',validation:'passed',installed:found?'listed':'not_listed',
30
+ next_step:found
31
+ ?'In the actual Antigravity host, verify 4 PILAH tools, skill activation, one useful cross-file call, one trivial zero-call task and denied-workspace negatives.'
32
+ :'Enable/register PILAH in the Antigravity plugin manager and verify plugin list before claiming installation.'};
33
+ }
34
+
35
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
36
+ const report=checkHost();
37
+ process.stdout.write(JSON.stringify(report,null,2)+'\n');
38
+ if(report.status==='blocked'||report.status==='partial')process.exitCode=2;
39
+ if(report.status==='failed')process.exitCode=1;
40
+ }
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ // Local transcript analysis; outcome attribution is observational, never causal.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ const check=(v,m)=>{if(!v)throw new Error(m)};
7
+ function plain(v){return String(v||'').replace(/^["']|["']$/g,'').slice(0,120)}
8
+ const KNOWN=new Set(['pilah_context','pilah_impact','pilah_verify','pilah_evidence','a2a_context','a2a_impact','a2a_verify','a2a_evidence','verifykit_context','verifykit_impact','verifykit_verify','verifykit_evidence']);
9
+ export function isA2AInvocation(call){
10
+ const name=plain(call?.name);
11
+ const explicitServer=plain(call?.args?.ServerName??call?.args?.server_name??call?.serverName??call?.server_name);
12
+ if(KNOWN.has(name))return !explicitServer||['pilah','pilah_pilah','a2a','a2a_a2a','verifykit','verifykit_verifykit'].includes(explicitServer)?name:null;
13
+ // Match exact known tool names before parsing server prefixes: pilah + pilah_context
14
+ // would otherwise be misread as pilah_pilah + context.
15
+ for(const server of ['pilah','pilah_pilah','a2a','a2a_a2a','verifykit','verifykit_verifykit']){
16
+ for(const tool of KNOWN){
17
+ if(name===`mcp_${server}_${tool}`||name===`mcp__${server}__${tool}`||
18
+ name===`${server}/${tool}`||name===`${server}.${tool}`||name===`${server}:${tool}`)return tool;
19
+ }
20
+ }
21
+ // Antigravity surfaces MCP calls as both a nested call_mcp_tool event and
22
+ // namespaced direct invocation strings. Normalize only known A2A namespaces.
23
+ const scoped=name.match(/^(?:pilah_pilah|pilah|a2a_a2a|a2a|verifykit_verifykit|verifykit)[/.:]([a-z0-9_]+)$/);
24
+ const encoded=name.match(/^mcp__(?:pilah_pilah|pilah|a2a_a2a|a2a|verifykit_verifykit|verifykit)__([a-z0-9_]+)$/);
25
+ const eager=name.match(/^mcp_(?:pilah_pilah|pilah|a2a_a2a|a2a|verifykit_verifykit|verifykit)_([a-z0-9_]+)$/);
26
+ if(scoped||encoded||eager){
27
+ const tool=(scoped||encoded||eager)[1];
28
+ return KNOWN.has(tool)?tool:'unknown-a2a-tool';
29
+ }
30
+ if(name.startsWith('pilah_')||name.startsWith('a2a_')||name.startsWith('verifykit_'))return 'unknown-a2a-tool';
31
+ if(name!=='call_mcp_tool')return null;
32
+ const tool=plain(call?.args?.ToolName??call?.args?.tool_name),server=plain(call?.args?.ServerName??call?.args?.server_name);
33
+ if(!['pilah','pilah_pilah','a2a','a2a_a2a','verifykit','verifykit_verifykit'].includes(server))return null;
34
+ return KNOWN.has(tool)?tool:'unknown-a2a-tool';
35
+ }
36
+ function resultOf(e){
37
+ if(!e)return 'no-result';
38
+ // A successful JSON-RPC transport can carry a *failed* MCP tool result.
39
+ // Bound parsing and never export the original response or local paths.
40
+ const excerpt=String(e.content||'').slice(0,4000);
41
+ let parsed=null;
42
+ try{parsed=JSON.parse(excerpt)}catch{}
43
+ if(parsed?.content?.[0]?.text&&typeof parsed.content[0].text==='string'){
44
+ try{parsed=JSON.parse(parsed.content[0].text.slice(0,4000))}catch{}
45
+ }
46
+ const code=String(parsed?.code??parsed?.error?.code??'');
47
+ const isError=e.status==='ERROR'||parsed?.isError===true||
48
+ parsed?.status==='error'||parsed?.error!==undefined;
49
+ if(isError){
50
+ if(/invalid[_ -]?(?:tool[_ -]?)?arguments?|invalid_args|^[-]32602$/i.test(code)||
51
+ /unknown argument|invalid (type|value|integer)|missing [a-z_]+/i.test(excerpt))return 'invalid-arguments';
52
+ if(/workspace[_ -]?(?:authorization|required|access|denied)|permission|protected/i.test(code)||
53
+ /not authorized|authorization required|permission denied|protected workspace/i.test(excerpt))return 'authorization-denied';
54
+ return 'tool-error';
55
+ }
56
+ if(e.status==='DONE')return 'succeeded';
57
+ return 'incomplete';
58
+ }
59
+ export function buildInterventionLedger(records){
60
+ check(Array.isArray(records)&&records.length<=250000,'Invalid or oversized transcript');
61
+ const newestPlanner=new Map();
62
+ for(const e of records)if(e?.type==='PLANNER_RESPONSE'&&Number.isSafeInteger(e.step_index))newestPlanner.set(e.step_index,e);
63
+ const events=records.filter(e=>e&&typeof e==='object'&&Number.isSafeInteger(e.step_index)&&(e.type!=='PLANNER_RESPONSE'||newestPlanner.get(e.step_index)===e)).sort((a,b)=>a.step_index-b.step_index);
64
+ // Precompute the next event of each type once rather than searching the tail for every call.
65
+ const nextPlannerIndex=new Array(events.length),nextGenericIndex=new Array(events.length);
66
+ let nextPlanner=-1,nextGeneric=-1;
67
+ for(let i=events.length-1;i>=0;i--){
68
+ nextPlannerIndex[i]=nextPlanner;nextGenericIndex[i]=nextGeneric;
69
+ if(events[i].type==='PLANNER_RESPONSE')nextPlanner=i;
70
+ if(events[i].type==='GENERIC')nextGeneric=i;
71
+ }
72
+ const ledger=[],counts={succeeded:0,'invalid-arguments':0,'authorization-denied':0,'tool-error':0,'no-result':0,incomplete:0};
73
+ for(let i=0;i<events.length;i++){
74
+ const e=events[i];if(e.type!=='PLANNER_RESPONSE')continue;
75
+ const calls=Array.isArray(e.tool_calls)?e.tool_calls:[];
76
+ for(const call of calls){
77
+ const name=isA2AInvocation(call);if(!name)continue;
78
+ // A single planner turn can call multiple tools. Without a call ID, matching is ambiguous.
79
+ const resultIndex=nextGenericIndex[i],plannerIndex=nextPlannerIndex[i];
80
+ const generic=resultIndex!==-1&&resultIndex<=i+5&&(plannerIndex===-1||resultIndex<plannerIndex)?events[resultIndex]:null;
81
+ const outcome=calls.length===1?resultOf(generic):'incomplete';
82
+ counts[outcome]++;
83
+ const nextPlanner=plannerIndex===-1?null:events[plannerIndex];
84
+ const ts=Date.parse(e.created_at||'');
85
+ ledger.push({step_index:e.step_index,tool:name,outcome,result_step_index:generic?.step_index??null,next_model_step_index:nextPlanner?.step_index??null,timestamp:Number.isFinite(ts)?new Date(ts).toISOString():null,observable_result_bytes:generic?.content?Buffer.byteLength(String(generic.content),'utf8'):null,attributed_model_tokens:null,attributed_token_savings:null,caused_quality_improvement:null});
86
+ }
87
+ }
88
+ return {schema:'a2a-intervention-ledger-v1',total_invocations:ledger.length,counts,interventions:ledger,caveats:['A completed tool invocation does not prove a downstream quality improvement','Result association is heuristic if more than one tool was used in a planner step','No raw prompts, commands, arguments, paths, thinking or result bodies are exported','Model tokens caused by plugin calls are not separately attributable from these records']};
89
+ }
90
+ function read(file){const st=fs.statSync(file);check(st.isFile()&&st.size<=128*1024*1024,'Expected JSONL transcript <=128 MiB');return fs.readFileSync(file,'utf8').split(/\r?\n/).filter(Boolean).map(l=>JSON.parse(l))}
91
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
92
+ try{check(process.argv.length===3,'Usage: node scripts/intervention-ledger.mjs transcript.jsonl');console.log(JSON.stringify(buildInterventionLedger(read(process.argv[2])),null,2))}
93
+ catch(e){console.error('Ledger failed: '+e.message);process.exitCode=1}
94
+ }
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ // Public CLI path; compatibility behavior stays in the existing implementation.
3
+ import './a2a.mjs';