@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,344 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {Engine} from '../src/engine.mjs';
5
+ import {sqliteApiName} from '../src/sqlite-compat.mjs';
6
+ import {nodeVersionManagerAdvisory} from '../src/node-runtime.mjs';
7
+ import pkg from '../package.json' with {type:'json'};
8
+ import {
9
+ allowlistPath,settingsPath,getA2AMode,setA2AMode,getCompactMode,setCompactMode,
10
+ getAutoTrustMode,setAutoTrustMode,getArtifactAutoSnapshotMode,setArtifactAutoSnapshotMode,loadAllowlist,loadAntigravityWorkspaces,
11
+ authorizeWorkspace,revokeWorkspace,dataDir,getHomeDir,requireAuthorizedWorkspace,isProtectedRoot,localAntigravityRpcUrl
12
+ } from '../src/security.mjs';
13
+ import {readOfficialAgyUsageFile} from '../src/tokens.mjs';
14
+ import {diagnoseSkillDiscovery} from '../src/skill-discovery.mjs';
15
+ import {scanConversationHistory,attachReportSize,formatConversationReport} from '../src/conversations.mjs';
16
+ import {assessContextHealth} from '../src/context-health.mjs';
17
+ import {routeWorkflow} from '../src/workflow-router.mjs';
18
+ import {checkHost} from './host-check.mjs';
19
+
20
+ // Treat active session metadata as untrusted local input: no symlinks,
21
+ // oversized data or non-object payloads. This may describe a *different*
22
+ // workspace and is never a substitute for workspace authorization.
23
+ function readActiveSession(base){
24
+ try{
25
+ const file=path.join(base,'active-session.json');
26
+ const st=fs.lstatSync(file);
27
+ if(!st.isFile()||st.isSymbolicLink()||st.size>128*1024)return null;
28
+ const data=JSON.parse(fs.readFileSync(file,'utf8'));
29
+ return data&&typeof data==='object'&&!Array.isArray(data)?data.latest||null:null;
30
+ }catch{return null}
31
+ }
32
+ const [cmd,...argv]=process.argv.slice(2);
33
+ function print(obj){process.stdout.write(JSON.stringify(obj,null,2)+'\n')}
34
+ if(!cmd||['help','--help','-h'].includes(cmd)){
35
+ console.log(`PILAH CLI - Project Intelligence, Logic, Analysis & Handoffs\n
36
+ Commands:\n doctor [--public] inspect runtime, workspace trust and mode (redacted sharing option)
37
+ host-check explicitly validate CLI and plugin listing; NOT live IDE acceptance
38
+ mode [always-on|on-demand] get or set active PILAH mode (default: on-demand)
39
+ toggle switch between always-on and on-demand
40
+ compact [on|off|toggle|status] get, set, or toggle PILAH Compact mode
41
+ autotrust [antigravity-trust|active-only|project-markers|off] get or set Antigravity workspace auto-trust policy
42
+ allow <absolute-workspace> authorize one project manually
43
+ revoke <absolute-workspace> revoke one project
44
+ inspect <workspace> index project & show code graph coverage
45
+ tokens [--json] [--limit 10] [--conversation ID] [--include-subagents] [--usage-file output.json] read all Antigravity conversation usage locally
46
+ context-health --conversation ID [--milestone-complete] read-only milestone advice (no recurring hook)
47
+ route --profile economy|balanced|deep-review --task simple|cross-file|change-impact|verification|recovery [--risk low|medium|high|critical] [--uncertain] [--unknown-scope] non-executing native-first recommendation
48
+ skeleton <workspace> <file...> strip comments via lexer and estimate preview size reduction
49
+ context <workspace> <query> query symbols and feature relations
50
+ impact <workspace> [paths...] analyze impact & calculate tokens affected
51
+ plan <workspace> [criterion ...] suggest native checks
52
+ assess <workspace> <criterion_id> <relative-report-file> <test-name|*> validate test report
53
+ verify-handoff <workspace> [--artifact <file>] [--worker <name>] [--allow-stale] verify subagent/teamwork test evidence
54
+ evidence <workspace> list verified evidence and regression history
55
+ side-questions [workspace] [--conv <id>] [--parent <id>] list recorded Antigravity side questions (/btw)
56
+ artifacts [list|diff|show|snapshot] [file] [--conv <id>] [--v1 N] [--v2 M] version & diff brain artifacts
57
+ artifact-autosnapshot [status|on|off] explicit opt-in for retaining full brain Markdown on edit events
58
+ privacy status <workspace> inspect local workspace-scoped SQLite retention
59
+ privacy purge <workspace> --confirm-purge delete only stored rows for that trusted workspace
60
+ refresh [serverName] hot-reload PILAH MCP server via Antigravity Language Server RPC
61
+ stats view install metrics, clone traffic & unique users from GitHub
62
+ mcp start PILAH stdio server via src/mcp.mjs`);process.exit(0);
63
+ }
64
+ try{
65
+ if(cmd==='host-check'){
66
+ if(argv.length)throw Error('Usage: pilah host-check');
67
+ const result=checkHost();print(result);
68
+ if(result.status==='blocked'||result.status==='partial')process.exitCode=2;
69
+ else if(result.status==='failed')process.exitCode=1;
70
+ }
71
+ else if(cmd==='doctor'){
72
+ if(argv.length>1||(argv[0]!==undefined&&argv[0]!=='--public'))throw Error('Usage: doctor [--public]');
73
+ const shared=argv[0]==='--public';
74
+ const allowed=loadAllowlist().filter(ws=>!isProtectedRoot(ws));
75
+ const ide=loadAntigravityWorkspaces();
76
+ print({public_redacted:shared,
77
+ name:'pilah',
78
+ title:'PILAH',
79
+ version:pkg.version,
80
+ node:process.versions.node,
81
+ node_requirement:'>=22.13.0',
82
+ sqlite:'node:sqlite',
83
+ sqlite_api:sqliteApiName,
84
+ sqlite_version:process.versions.sqlite||null,
85
+ ...(shared?{}:{node_binary:process.execPath,...nodeVersionManagerAdvisory(process.execPath)}),
86
+ mode:getA2AMode(),
87
+ compact_mode:getCompactMode()?'enabled':'disabled',
88
+ artifact_auto_snapshot:getArtifactAutoSnapshotMode()?'enabled':'disabled',
89
+ auto_trust:getAutoTrustMode(),
90
+ ...(shared?{allowed_workspace_count:allowed.length,antigravity_workspace_count:ide.length}:{settings:settingsPath(),data_dir:dataDir(),allowlist:allowlistPath(),allowed_workspaces:allowed,antigravity_workspaces:ide}),
91
+ ignored_protected_grants:loadAllowlist().filter(isProtectedRoot).length,
92
+ host_validation:{status:'not_checked',next_step:'Run node scripts/pilah.mjs host-check for an explicit native CLI preflight.'},
93
+ skill_discovery:diagnoseSkillDiscovery(),
94
+ session_usage:{status:'not_collected',reason:'Doctor does not read internal conversation transcripts.'},
95
+ network:'no outbound requests',
96
+ shell_execution:'disabled',
97
+ });
98
+ }
99
+ else if(cmd==='mode'){
100
+ const target=argv[0];
101
+ if(!target||target==='status'){print({mode:getA2AMode()});}
102
+ else {print({mode:setA2AMode(target)});}
103
+ }
104
+ else if(cmd==='toggle'){
105
+ const current=getA2AMode();
106
+ const next=current==='always-on'?'on-demand':'always-on';
107
+ print({previous:current,mode:setA2AMode(next)});
108
+ }
109
+ else if(cmd==='compact'){
110
+ const target=argv[0];
111
+ if(!target||target==='status'){print({compact:getCompactMode()?'enabled':'disabled'});}
112
+ else if(target==='toggle'){print({compact:setCompactMode('toggle')?'enabled':'disabled'});}
113
+ else {print({compact:setCompactMode(target)?'enabled':'disabled'});}
114
+ }
115
+ else if(cmd==='artifact-autosnapshot'){
116
+ const setting=argv[0]||'status';
117
+ if(setting==='status')print({artifact_auto_snapshot:getArtifactAutoSnapshotMode()?'enabled':'disabled',note:'Automatic full-content brain Markdown retention is opt-in; default off.'});
118
+ else print({artifact_auto_snapshot:setArtifactAutoSnapshotMode(setting)?'enabled':'disabled',note:'Stored snapshots are private local content; existing history is not deleted when disabled.'});
119
+ }
120
+ else if(cmd==='autotrust'){
121
+ const target=argv[0];
122
+ if(!target||target==='status'){print({auto_trust:getAutoTrustMode()});}
123
+ else {print({auto_trust:setAutoTrustMode(target)});}
124
+ }
125
+ else if(cmd==='privacy'){
126
+ const [action,workspace,flag]=argv;
127
+ if(!['status','purge'].includes(action)||!workspace)throw Error('Usage: privacy status <trusted-workspace> | privacy purge <trusted-workspace> --confirm-purge');
128
+ if(action==='status'&&flag!==undefined)throw Error('Unexpected privacy argument');
129
+ if(action==='purge'&&flag!=='--confirm-purge')throw Error('Explicit --confirm-purge is required to erase workspace-scoped records');
130
+ const root=requireAuthorizedWorkspace(workspace),e=new Engine();
131
+ try{
132
+ print(action==='status'?e.store.workspaceDataCounts(root):e.store.purgeWorkspaceData(root,{confirmed:true}));
133
+ }finally{e.close()}
134
+ }
135
+ else if(cmd==='allow'){print({authorized:authorizeWorkspace(argv[0])})}
136
+ else if(cmd==='revoke'){print({remaining:revokeWorkspace(argv[0])})}
137
+ else if(cmd==='refresh'){
138
+ const addr=process.env.ANTIGRAVITY_LS_ADDRESS;
139
+ const csrf=process.env.ANTIGRAVITY_CSRF_TOKEN;
140
+ const serverName=(argv[0]&&/^[A-Za-z0-9_-]{1,64}$/.test(argv[0]))?argv[0]:'pilah_pilah';
141
+ if(!addr||!csrf){
142
+ print({status:'skipped',serverName,reason:'ANTIGRAVITY_LS_ADDRESS or ANTIGRAVITY_CSRF_TOKEN not set'});
143
+ }else{
144
+ const url=localAntigravityRpcUrl(addr);
145
+ const res=await fetch(url,{
146
+ method:'POST',
147
+ headers:{'Content-Type':'application/json','x-codeium-csrf-token':csrf},
148
+ body:JSON.stringify({serverName}),
149
+ signal:AbortSignal.timeout(5000),
150
+ });
151
+ const body=await res.text();
152
+ if(!res.ok) throw new Error(`RefreshMcpServers failed (${res.status}); inspect Antigravity local diagnostics`);
153
+ let parsed=null;try{parsed=body?JSON.parse(body):{}}catch{parsed=body}
154
+ print({status:'refreshed',serverName,response:parsed});
155
+ }
156
+ }
157
+ else if(cmd==='stats'){
158
+ const {execFileSync}=await import('node:child_process');
159
+ try{
160
+ const repoName=process.env.PILAH_REPO||'alifakbxr/pilah';
161
+ const clonesRaw=execFileSync('gh',['api',`/repos/${repoName}/traffic/clones`],{encoding:'utf8',timeout:6000});
162
+ const viewsRaw=execFileSync('gh',['api',`/repos/${repoName}/traffic/views`],{encoding:'utf8',timeout:6000});
163
+ const repoRaw=execFileSync('gh',['api',`/repos/${repoName}`],{encoding:'utf8',timeout:6000});
164
+ const clones=JSON.parse(clonesRaw);
165
+ const views=JSON.parse(viewsRaw);
166
+ const repo=JSON.parse(repoRaw);
167
+ print({
168
+ repository:repoName,
169
+ install_metrics:{
170
+ total_clones_last_14d: clones.count||0,
171
+ unique_installers_last_14d: clones.uniques||0,
172
+ active_clone_days: (clones.clones||[]).filter(c=>c.count>0),
173
+ },
174
+ traffic_metrics:{
175
+ total_views_last_14d: views.count||0,
176
+ unique_visitors_last_14d: views.uniques||0,
177
+ },
178
+ community:{
179
+ stars: repo.stargazers_count||0,
180
+ forks: repo.forks_count||0,
181
+ watchers: repo.subscribers_count||0,
182
+ }
183
+ });
184
+ }catch(err){
185
+ print({error:'Failed to fetch GitHub traffic stats',details:err.message});
186
+ }
187
+ }
188
+ else if(cmd==='route'){
189
+ const q={};
190
+ for(let i=0;i<argv.length;i++){
191
+ const arg=argv[i];
192
+ if(arg==='--profile'||arg==='--task'||arg==='--risk'){
193
+ if(!argv[i+1])throw new Error('Missing route value: '+arg);
194
+ q[arg.slice(2)]=argv[++i];
195
+ }else if(arg==='--uncertain')q.uncertainty=true;
196
+ else if(arg==='--unknown-scope')q.scopeKnown=false;
197
+ else if(arg==='--named-evidence')q.hasNamedEvidence=true;
198
+ else throw new Error('Unknown route option: '+arg);
199
+ }
200
+ print(routeWorkflow(q));
201
+ }
202
+ else if(cmd==='context-health'){
203
+ let conversationId=null,milestoneComplete=false;
204
+ for(let i=0;i<argv.length;i++){
205
+ const arg=argv[i];
206
+ if(arg==='--conversation')conversationId=argv[++i];
207
+ else if(arg.startsWith('--conversation='))conversationId=arg.slice(15);
208
+ else if(arg==='--milestone-complete')milestoneComplete=true;
209
+ else throw new Error('Invalid context-health argument. Use --conversation ID [--milestone-complete]');
210
+ }
211
+ if(!conversationId||!/^[a-zA-Z0-9._-]{4,128}$/.test(conversationId))throw new Error('Provide an explicit valid --conversation ID');
212
+ const report=scanConversationHistory({dataDirPath:dataDir(),conversationId,limit:1,includeSubagents:true});
213
+ const entry=report.recent_conversations.find(x=>x.conversation_id===conversationId);
214
+ print(entry?assessContextHealth({steps:entry.steps,complete:entry.complete,milestoneComplete}):
215
+ {status:'insufficient_evidence',automatic_compaction:false,active_context_tokens:null,measured_token_savings:null,
216
+ recommendation:'No complete local transcript found for the explicit conversation ID.'});
217
+ }
218
+ else if(cmd==='tokens'){
219
+ let format='text',limit=10,conversationId=null,includeSubagents=false;
220
+ const usageFiles=[];
221
+ for(let i=0;i<argv.length;i++){
222
+ const item=argv[i];
223
+ if(item==='--json'){format='json';}
224
+ else if(item==='--include-subagents'){includeSubagents=true;}
225
+ else if(item==='--current'){limit=1;}
226
+ else if(item==='--limit'){
227
+ const n=Number(argv[++i]);
228
+ if(!Number.isInteger(n)||n<1||n>30)throw new Error('--limit must be a number from 1 to 30');
229
+ limit=n;
230
+ }else if(item.startsWith('--limit=')){
231
+ const n=Number(item.slice(8));
232
+ if(!Number.isInteger(n)||n<1||n>30)throw new Error('--limit must be a number from 1 to 30');
233
+ limit=n;
234
+ }else if(item==='--conversation'){conversationId=argv[++i];}
235
+ else if(item.startsWith('--conversation=')){conversationId=item.slice(15);}
236
+ else if(item==='--usage-file'){usageFiles.push(argv[++i]);}
237
+ else if(item.startsWith('--usage-file=')){usageFiles.push(item.slice(13));}
238
+ else if(item.startsWith('--'))throw new Error('Unknown tokens option: '+item);
239
+ else if(item!=='.'&&!path.isAbsolute(item))throw new Error('Unexpected tokens argument: '+item);
240
+ // Positional workspace retained for backwards compatibility; global history is intentional.
241
+ }
242
+ if(conversationId&&!/^[a-zA-Z0-9._-]{4,128}$/.test(conversationId))throw new Error('Invalid conversation ID');
243
+ const officialRuns=usageFiles.map(file=>readOfficialAgyUsageFile(file));
244
+ const report=scanConversationHistory({dataDirPath:dataDir(),limit,conversationId,includeSubagents,officialRuns});
245
+ attachReportSize(report,{format});
246
+ if(format==='json')print(report);
247
+ else process.stdout.write(formatConversationReport(report)+'\n');
248
+ }
249
+ else if(cmd==='mcp'){await import('../src/mcp.mjs')}
250
+ else {
251
+ const engine=new Engine();let result;
252
+ try{
253
+ if(cmd==='inspect'){result=engine.context({workspace:argv[0]});}
254
+
255
+ else if(cmd==='skeleton'){
256
+ const workspace=argv[0];
257
+ const files=argv.slice(1);
258
+ result=engine.context({workspace,action:'skeleton',files});
259
+ }
260
+ else if(cmd==='context')result=engine.context({workspace:argv[0],action:'query',query:argv.slice(1).join(' ')});
261
+ else if(cmd==='impact')result=engine.impact({workspace:argv[0],changed:argv.slice(1)});
262
+ else if(cmd==='plan')result=engine.verify({workspace:argv[0],operation:'plan',criteria:argv.slice(1)});
263
+ else if(cmd==='assess')result=engine.verify({workspace:argv[0],operation:'assess',criteria:[{id:argv[1],artifact:argv[2],test_name:argv[3]}]});
264
+ else if(cmd==='verify-handoff'||cmd==='verify_handoff'){
265
+ let ws=null;let artifact=null;let workerName=null;let allowStale=false;
266
+ for(let i=0;i<argv.length;i++){
267
+ if(argv[i]==='--artifact'&&argv[i+1]){artifact=argv[++i];}
268
+ else if(argv[i].startsWith('--artifact=')){artifact=argv[i].slice(11);}
269
+ else if(argv[i]==='--worker'&&argv[i+1]){workerName=argv[++i];}
270
+ else if(argv[i].startsWith('--worker=')){workerName=argv[i].slice(9);}
271
+ else if(argv[i]==='--allow-stale'){allowStale=true;}
272
+ else if(!ws&&!argv[i].startsWith('-')){ws=argv[i];}
273
+ }
274
+ result=engine.verify({
275
+ workspace:ws||process.cwd(),
276
+ operation:'verify_handoff',
277
+ artifact,
278
+ worker_name:workerName,
279
+ allow_stale:allowStale
280
+ });
281
+ }
282
+ else if(cmd==='evidence')result=engine.evidence({workspace:argv[0]});
283
+ else if(cmd==='side-questions'||cmd==='side_questions'){
284
+ let ws=null;let convId=null;let parentId=null;
285
+ for(let i=0;i<argv.length;i++){
286
+ if(argv[i]==='--conv'&&argv[i+1]){convId=argv[++i];}
287
+ else if(argv[i].startsWith('--conv=')){convId=argv[i].slice(7);}
288
+ else if(argv[i]==='--parent'&&argv[i+1]){parentId=argv[++i];}
289
+ else if(argv[i].startsWith('--parent=')){parentId=argv[i].slice(9);}
290
+ else if(!ws&&!argv[i].startsWith('-')){ws=argv[i];}
291
+ }
292
+ const root=requireAuthorizedWorkspace(ws||process.cwd());
293
+ const wsId=engine.store.register(root);
294
+ const items=engine.store.listSideQuestions({workspaceId:wsId,conversationId:convId,parentConversationId:parentId});
295
+ result={count:items.length,side_questions:items};
296
+ }
297
+ else if(cmd==='artifacts'){
298
+ const sub=argv[0]||'list';
299
+ let artifactName=null;
300
+ let convId=null;
301
+ let workspaceArg=null;
302
+ let v1=null;
303
+ let v2=null;
304
+ const subIsCmd=['list','diff','show','snapshot'].includes(sub);
305
+ const action=subIsCmd?sub:'list';
306
+ const restArgs=subIsCmd?argv.slice(1):argv;
307
+ for(let i=0;i<restArgs.length;i++){
308
+ if(restArgs[i]==='--workspace'&&restArgs[i+1]){workspaceArg=restArgs[++i];}
309
+ else if(restArgs[i].startsWith('--workspace=')){workspaceArg=restArgs[i].slice(12);}
310
+ else if(restArgs[i]==='--conv'&&restArgs[i+1]){convId=restArgs[++i];}
311
+ else if(restArgs[i].startsWith('--conv=')){convId=restArgs[i].slice(7);}
312
+ else if(restArgs[i]==='--v1'&&restArgs[i+1]){v1=Number(restArgs[++i]);}
313
+ else if(restArgs[i].startsWith('--v1=')){v1=Number(restArgs[i].slice(5));}
314
+ else if(restArgs[i]==='--v2'&&restArgs[i+1]){v2=Number(restArgs[++i]);}
315
+ else if(restArgs[i].startsWith('--v2=')){v2=Number(restArgs[i].slice(5));}
316
+ else if(!artifactName&&!restArgs[i].startsWith('-')){artifactName=restArgs[i];}
317
+ }
318
+ const active=readActiveSession(engine.store.base);
319
+ if(!convId)convId=active?.conversationId||process.env.ANTIGRAVITY_CONVERSATION_ID||'default';
320
+ const activeWorkspace=Array.isArray(active?.workspacePaths)?active.workspacePaths[0]:null;
321
+ const root=requireAuthorizedWorkspace(workspaceArg||activeWorkspace||process.cwd());
322
+ const wsId=engine.store.register(root);
323
+ if(action==='list'){
324
+ const items=engine.store.listArtifactVersions({workspaceId:wsId,conversationId:convId,artifactName});
325
+ result={conversation_id:convId,artifact_name:artifactName||null,count:items.length,versions:items};
326
+ }else if(action==='diff'){
327
+ if(!artifactName)throw new Error('artifact name required for diff (e.g. a2a artifacts diff walkthrough.md)');
328
+ const diffRes=engine.store.getArtifactDiff({workspaceId:wsId,conversationId:convId,artifactName,v1,v2});
329
+ result={conversation_id:convId,...(diffRes||{artifact_name:artifactName,v1,v2,diff:''})};
330
+ }else if(action==='show'){
331
+ if(!artifactName)throw new Error('artifact name required for show');
332
+ const row=engine.store.getArtifactVersion({workspaceId:wsId,conversationId:convId,artifactName,versionNumber:v1||v2});
333
+ result=row||{status:'not_found'};
334
+ }else if(action==='snapshot'){
335
+ if(!artifactName)throw new Error('artifact name or path required for snapshot');
336
+ const targetPath=path.isAbsolute(artifactName)?artifactName:path.join(getHomeDir(),'.gemini/antigravity/brain',convId,artifactName);
337
+ result=engine.evidence({workspace:root,operation:'snapshot_artifact',conversation_id:convId,artifact_path:targetPath});
338
+ }
339
+ }
340
+ else throw new Error('Unknown command '+cmd);
341
+ }finally{engine.close();}
342
+ print(result);
343
+ }
344
+ }catch(e){process.stderr.write('A2A: '+String(e.message||e)+'\n');process.exitCode=1}
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {fileURLToPath} from 'node:url';
5
+ import assert from 'node:assert/strict';
6
+ import {TOOLS} from '../src/tools.mjs';
7
+
8
+ const root=fileURLToPath(new URL('../',import.meta.url));
9
+ const read=file=>JSON.parse(fs.readFileSync(path.join(root,file),'utf8'));
10
+
11
+ const manifest=read('plugin.json');
12
+ const pkg=read('package.json');
13
+ assert.equal(pkg.version,manifest.version,'Package and plugin version must match');
14
+ assert.match(fs.readFileSync(path.join(root,'.npmignore'),'utf8'),/(?:^|\n)benchmarks\/[^\n]*\n?/,'Benchmark evaluator is intentionally source-checkout-only');
15
+ assert.match(manifest.name,/^[a-z0-9]+(?:-[a-z0-9]+)*$/);
16
+ assert.match(manifest.version,/^\d+\.\d+\.\d+$/);
17
+ assert.ok(manifest.displayName&&manifest.description&&manifest.license&&manifest.author);
18
+
19
+ const mcpCfg=read('mcp_config.json');
20
+ assert.equal(mcpCfg.mcpServers.pilah.command,'node');
21
+ assert.ok(fs.existsSync(path.join(root,manifest.logo)));
22
+
23
+ const hooksFile=path.join(root,'hooks.json');
24
+ assert.ok(fs.existsSync(hooksFile),'hooks.json must exist');
25
+ const hooksCfg=read('hooks.json');
26
+ assert.ok(hooksCfg && typeof hooksCfg==='object' && Object.keys(hooksCfg).length>0,'hooks.json must define at least one hook');
27
+
28
+ const rulesFile=path.join(root,'rules','AGENTS.md');
29
+ assert.ok(fs.existsSync(rulesFile),'rules/AGENTS.md must exist');
30
+
31
+ assert.deepEqual(read('schemas/mcp-tools.json').tools,TOOLS,'Generated MCP schemas are out of sync');
32
+ assert.equal(TOOLS.length,4);
33
+
34
+ for(const file of ['src/mcp.mjs','scripts/a2a.mjs','scripts/hook.mjs','schemas/database.sql','README.md','docs/ARCHITECTURE.md','docs/COMPATIBILITY.md','docs/CONTRACTS.md','docs/SECURITY.md','docs/RELEASE.md']){
35
+ assert.ok(fs.existsSync(path.join(root,file)),'Missing required file: '+file);
36
+ }
37
+
38
+ console.log(JSON.stringify({
39
+ status:'passed',
40
+ checks:['manifest-shape','mcp-transport','hooks-present','rules-present','schema-drift','documentation-presence'],
41
+ warning:'Not a replacement for agy plugin validate --strict or a live Antigravity install.'
42
+ },null,2));
@@ -0,0 +1,30 @@
1
+ #!/usr/bin/env node
2
+ // Check every shipped ESM module and CLI script, not an easily stale hand-written list.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {spawnSync} from 'node:child_process';
6
+ import {fileURLToPath} from 'node:url';
7
+
8
+ const root=fileURLToPath(new URL('../',import.meta.url));
9
+ const sources=[];
10
+ function collect(dir){
11
+ for(const entry of fs.readdirSync(path.join(root,dir),{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){
12
+ const relative=path.join(dir,entry.name);
13
+ if(entry.isDirectory())collect(relative);
14
+ else if(entry.isFile()&&entry.name.endsWith('.mjs'))sources.push(relative);
15
+ }
16
+ }
17
+ for(const directory of ['src','scripts'])collect(directory);
18
+ if(!sources.length)throw new Error('No source or CLI modules discovered');
19
+ let failures=0;
20
+ for(const relative of sources){
21
+ const run=spawnSync(process.execPath,['--check',path.join(root,relative)],{stdio:'inherit'});
22
+ if(run.error)throw run.error;
23
+ if(run.status!==0)failures++;
24
+ }
25
+ if(failures){
26
+ process.stderr.write(`Syntax validation failed in ${failures}/${sources.length} ESM files.\n`);
27
+ process.exitCode=1;
28
+ }else{
29
+ process.stdout.write(`Syntax validated: ${sources.length} src/scripts ESM files.\n`);
30
+ }
@@ -0,0 +1,50 @@
1
+ #!/usr/bin/env node
2
+ // Local-only, explicit checkpoint generation. Does not run or resume any agent.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import {fileURLToPath} from 'node:url';
6
+ const MAX=8*1024*1024;
7
+ const states=new Set(['passed','failed','blocked','partial','not-tested','running','stale']);
8
+ const validId=s=>typeof s==='string'&&/^[a-zA-Z0-9][a-zA-Z0-9._-]{3,127}$/.test(s);
9
+ const check=(ok,message)=>{if(!ok)throw new Error(message)};
10
+ const count=(arr,s)=>arr.filter(x=>x.status===s).length;
11
+ export function checkpointFromStream(events,scenarioRecord){
12
+ check(Array.isArray(events)&&events.length<=40000,'Expected bounded events array');
13
+ check(scenarioRecord&&Array.isArray(scenarioRecord.scenarios)&&scenarioRecord.scenarios.length<=150,'Expected bounded scenarios');
14
+ const seen=new Set(),scenarios=[];
15
+ for(const s of scenarioRecord.scenarios){
16
+ check(s&&typeof s.id==='string'&&/^[a-zA-Z0-9_.:-]{1,100}$/.test(s.id)&&!seen.has(s.id)&&states.has(s.status),'Invalid or duplicate scenario');
17
+ seen.add(s.id);
18
+ scenarios.push({id:s.id,status:s.status,evidence_trust:'self-reported',...(typeof s.evidence_ref==='string'&&/^(?:ci|test|run|evidence)[/-][a-zA-Z0-9_.-]{1,100}$/.test(s.evidence_ref)&&!s.evidence_ref.includes('..')?{evidence_ref:s.evidence_ref}:{}),...((s.status==='failed'||s.status==='blocked')&&typeof s.reason_code==='string'&&/^[a-z][a-z0-9_-]{1,59}$/.test(s.reason_code)?{reason_code:s.reason_code}:{})});
19
+ }
20
+ let lastResult=null,active=new Set(),closed=new Set(),lastId=null,completed=0;
21
+ for(const event of events){
22
+ if(event?.event==='init'&&validId(event.conversation_id))lastId=event.conversation_id;
23
+ if(event?.event==='result'&&event.result&&typeof event.result==='object'){
24
+ lastResult=event.result;
25
+ if(validId(lastResult.conversation_id))lastId=lastResult.conversation_id;
26
+ }
27
+ const s=event?.step_update;
28
+ if(event?.event!=='step_update'||!s||!Number.isSafeInteger(s.step_index))continue;
29
+ if(s.state==='ACTIVE')active.add(s.step_index);
30
+ if(s.state==='DONE'){active.delete(s.step_index);if(!closed.has(s.step_index)){closed.add(s.step_index);completed++}}
31
+ }
32
+ const status=['SUCCESS','ERROR','CANCELED','INTERRUPTED','INVALID','WAITING','RUNNING'].includes(lastResult?.status)?lastResult.status:(active.size?'INTERRUPTED_OR_INCOMPLETE':'UNKNOWN');
33
+ const usage=lastResult?.usage;
34
+ const official=usage&&Number.isSafeInteger(usage.input_tokens)&&Number.isSafeInteger(usage.output_tokens)&&Number.isSafeInteger(usage.total_tokens)&&usage.total_tokens===usage.input_tokens+usage.output_tokens?usage.total_tokens:null;
35
+ const classified=status==='SUCCESS'?'completed':status==='ERROR'?'provider-or-agent-error':status==='INTERRUPTED'?'interrupted':status==='CANCELED'?'cancelled':status==='WAITING'?'awaiting-input':status==='UNKNOWN'?'no-terminal-state':'other';
36
+ const sourceVersion=typeof scenarioRecord.revision==='string'&&/^[a-zA-Z0-9._:-]{4,160}$/.test(scenarioRecord.revision)?scenarioRecord.revision:null;
37
+ const servedVersion=typeof scenarioRecord.served_build_revision==='string'&&/^[a-zA-Z0-9._:-]{4,160}$/.test(scenarioRecord.served_build_revision)?scenarioRecord.served_build_revision:null;
38
+ const mismatch=sourceVersion&&servedVersion&&sourceVersion!==servedVersion;
39
+ return {schema:'a2a-checkpoint-v1',conversation_id:lastId,run_state:status,category:classified,reported_revision:sourceVersion,reported_served_build_revision:servedVersion,reported_build_mismatch:!!mismatch,revision_authenticated:false,completed_steps:completed,unfinished_step_count:active.size,official_total_tokens:official,scenarios,summary:{reported_passed:count(scenarios,'passed'),verified_passed:0,failed:count(scenarios,'failed'),partial:count(scenarios,'partial'),blocked:count(scenarios,'blocked'),not_tested:count(scenarios,'not-tested'),running:count(scenarios,'running')},resume_suggestion:validId(lastId)?{manual_command:'agy --conversation '+lastId,requires_user_approval:true,auto_executed:false}:{manual_command:'Use Antigravity /resume to select the session after verifying it still exists.',requires_user_approval:true,auto_executed:false},limitations:['Scenario evidence is supplied externally and is NOT independently verified; reported passed is not accepted for release','No raw prompts, stdout, tokens, or browser session secrets are stored','A lack of terminal result cannot prove a particular quota or provider failure']};
40
+ }
41
+ export function checkpointFromFiles(streamFile,scenarioFile){
42
+ const read=(p,limit)=>{const s=fs.statSync(p);check(s.isFile()&&s.size<=limit,'File exceeds allowed size');return fs.readFileSync(p,'utf8')};
43
+ const stream=read(streamFile,MAX),scenario=JSON.parse(read(scenarioFile,1024*1024));
44
+ const events=stream.split(/\r?\n/).filter(Boolean).map(line=>JSON.parse(line));
45
+ return checkpointFromStream(events,scenario);
46
+ }
47
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
48
+ try{check(process.argv.length===4,'Usage: node scripts/checkpoint.mjs stream.jsonl scenarios.json');process.stdout.write(JSON.stringify(checkpointFromFiles(process.argv[2],process.argv[3]),null,2)+'\n')}
49
+ catch(e){process.stderr.write('Checkpoint unavailable: '+e.message+'\n');process.exitCode=1}
50
+ }
@@ -0,0 +1,53 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import {fileURLToPath} from 'node:url';
5
+ // Metadata-only; never returns prompts, thinking, arguments or tool outputs.
6
+ const check=(x,m)=>{if(!x)throw new Error(m)};
7
+ export function classifyTool(call){
8
+ const n=String(call?.name||'').toLowerCase();
9
+ if(n.startsWith('a2a_')||n.includes('mcp'))return 'mcp';
10
+ if(/browser|playwright|puppeteer|chrome|devtools/.test(n))return 'browser';
11
+ if(/write|create_file|replace|edit|patch/.test(n))return 'write';
12
+ if(/read|search|grep|list|find/.test(n))return 'read';
13
+ if(/run_command|terminal|shell|exec/.test(n))return 'shell';
14
+ return 'other';
15
+ }
16
+ export function analyzeAgentTrace(records){
17
+ check(Array.isArray(records)&&records.length<=250000,'Invalid or oversized transcript');
18
+ const byStep=new Map(),counts={read:0,write:0,shell:0,browser:0,mcp:0,other:0},names=new Map();
19
+ let first=null,last=null,errors=0,toolErrors=0,capacityHints=0,users=0,malformed=0;
20
+ for(const e of records){
21
+ if(!e||typeof e!=='object'||Array.isArray(e)){malformed++;continue}
22
+ const timestamp=Date.parse(e.created_at||'');
23
+ if(Number.isFinite(timestamp)){first=Math.min(first??timestamp,timestamp);last=Math.max(last??timestamp,timestamp)}
24
+ if(e.type==='USER_INPUT')users++;
25
+ if(e.type==='ERROR_MESSAGE'){errors++;if(/(?:\b503\b|capacity|overloaded)/i.test(String(e.content||'').slice(0,300)))capacityHints++}
26
+ if(e.type==='GENERIC'&&e.status==='ERROR')toolErrors++;
27
+ if(e.type==='PLANNER_RESPONSE'&&Number.isSafeInteger(e.step_index)){
28
+ const old=byStep.get(e.step_index);
29
+ if(!old||Date.parse(e.created_at||'')>=Date.parse(old.created_at||''))byStep.set(e.step_index,e);
30
+ }
31
+ }
32
+ let toolCalls=0,consecutive=0,previous=null;
33
+ for(const e of [...byStep.values()].sort((a,b)=>a.step_index-b.step_index)){
34
+ for(const c of Array.isArray(e.tool_calls)?e.tool_calls:[]){
35
+ toolCalls++;counts[classifyTool(c)]++;
36
+ const candidate=String(c.name||'unknown');
37
+ const known=new Set(['run_command','call_mcp_tool','read_file','write_to_file','edit_file','replace_file','apply_patch','search_files','grep_search','list_dir','find_files','browser','write_file','a2a_context','a2a_impact','a2a_verify','a2a_evidence']);
38
+ const safe=known.has(candidate)?candidate:'other-tool';
39
+ names.set(safe,(names.get(safe)||0)+1);
40
+ if(safe===previous)consecutive++;previous=safe;
41
+ }
42
+ }
43
+ return {schema:'a2a-observable-trace-v1',model_response_steps:byStep.size,user_turn_records:users,tool_calls:toolCalls,tool_categories:counts,most_used_tools:[...names].sort((a,b)=>b[1]-a[1]).slice(0,15).map(([name,calls])=>({name,calls})),observed_elapsed_seconds:first===null?null:Math.round((last-first)/1000),error_records:errors,tool_result_errors:toolErrors,provider_capacity_hints:capacityHints,consecutive_same_tool_name_count:consecutive,malformed_records:malformed,caveats:['Observed elapsed time is not model compute time','Consecutive same-tool calls do not prove retry loops','Provider capacity hints do not prove quota exhaustion','Counts do not establish reasoning quality or application correctness']};
44
+ }
45
+ export function compareAgentTraces(a,b){
46
+ const native=analyzeAgentTrace(a),a2a=analyzeAgentTrace(b);
47
+ return {schema:'a2a-observable-comparison-v1',native,a2a,delta:{model_response_steps:a2a.model_response_steps-native.model_response_steps,tool_calls:a2a.tool_calls-native.tool_calls,observed_elapsed_seconds:native.observed_elapsed_seconds===null||a2a.observed_elapsed_seconds===null?null:a2a.observed_elapsed_seconds-native.observed_elapsed_seconds},conclusion:'Descriptive only: independent acceptance and provider usage needed for causal or efficiency claims.'};
48
+ }
49
+ function read(file){const stat=fs.statSync(file);check(stat.isFile()&&stat.size<=128*1024*1024,'Expected transcript file <=128 MiB');return fs.readFileSync(file,'utf8').split(/\r?\n/).filter(Boolean).map(l=>JSON.parse(l))}
50
+ if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
51
+ try{check(process.argv.length===4,'Usage: node scripts/compare-agent-traces.mjs native.jsonl a2a.jsonl');console.log(JSON.stringify(compareAgentTraces(read(process.argv[2]),read(process.argv[3])),null,2))}
52
+ catch(e){console.error('Trace analysis error: '+e.message);process.exitCode=1}
53
+ }