@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
package/src/graph.mjs ADDED
@@ -0,0 +1,169 @@
1
+ import {sha256,isSafeRelative,shouldIgnore} from './security.mjs';
2
+ import {gitChanges} from './scanner.mjs';
3
+
4
+ const uniq=xs=>[...new Set(xs)];
5
+ const isSensitiveFeature=s=>/(auth|login|session|payment|checkout|security|permission|access|transaction|migration|database|crypto|billing|order|credential)/i.test(s);
6
+ export const normalizeRelPath=rel=>String(rel||'').replaceAll('\\','/').replace(/^(?:\.\/)+/,'');
7
+
8
+ function batchedSelect(store,sqlPrefix,wsId,ids,sqlSuffix=''){
9
+ const out=[];
10
+ for(let i=0;i<ids.length;i+=100){
11
+ const chunk=ids.slice(i,i+100);
12
+ if(!chunk.length)continue;
13
+ const placeholders=chunk.map(()=>'?').join(',');
14
+ out.push(...store.all(`${sqlPrefix}(${placeholders})${sqlSuffix}`,wsId,...chunk));
15
+ }
16
+ return out;
17
+ }
18
+
19
+ export function contextQuery(store,wsId,{query='',limit=12}={}){
20
+ const q=String(query).trim().slice(0,160).toLowerCase();
21
+ const n=Math.max(1,Math.min(40,Number(limit)||12));
22
+ // instr() treats % and _ literally, unlike LIKE's wildcard semantics.
23
+ const nodes=q
24
+ ?store.all(`SELECT * FROM nodes WHERE workspace_id=?
25
+ AND (instr(LOWER(label),?)>0 OR instr(LOWER(file_path),?)>0)
26
+ ORDER BY CASE
27
+ WHEN LOWER(label)=? THEN 0
28
+ WHEN substr(LOWER(label),1,length(?))=? THEN 1
29
+ WHEN LOWER(file_path)=? THEN 2
30
+ WHEN instr(LOWER(label),?)>0 THEN 3
31
+ ELSE 4 END,kind,label LIMIT ?`,
32
+ wsId,q,q,q,q,q,q,q,n)
33
+ :store.all("SELECT * FROM nodes WHERE workspace_id=? AND kind IN ('feature','test') ORDER BY kind,label LIMIT ?",wsId,n);
34
+ const queryIds=nodes.slice(0,15).map(x=>x.id);
35
+ const relationships=[];
36
+ if(queryIds.length){
37
+ const ph=queryIds.map(()=>'?').join(',');
38
+ const edges=store.all(`SELECT source,target,kind,basis,state FROM edges WHERE workspace_id=? AND (source IN (${ph}) OR target IN (${ph})) ORDER BY CASE kind WHEN 'IMPORTS' THEN 0 WHEN 'MAY_TEST' THEN 1 WHEN 'CONTRIBUTES_TO' THEN 2 ELSE 3 END LIMIT 120`,wsId,...queryIds,...queryIds);
39
+ relationships.push(...edges);
40
+ }
41
+ return {nodes:nodes.map(({id,kind,label,file_path,line,basis})=>({id,kind,label,file:file_path,line,basis})),
42
+ relations:[...new Map(relationships.map(e=>[e.source+'|'+e.target+'|'+e.kind,e])).values()].slice(0,80),
43
+ uncertainty:['Static discovery is not full behavioral or runtime dependency coverage.']};
44
+ }
45
+ // A changed entry point often reaches services through dynamic framework dispatch.
46
+ // This is a review trigger, never proof of route coverage or authorization.
47
+ export function inferEntryPointRisks(changed=[]){
48
+ const paths=Array.isArray(changed)?changed:[];
49
+ const groups=[
50
+ ['routes',/^(?:routes\/|app\/Http\/routes\/)/i],
51
+ ['middleware',/(?:Middleware\/|Policy\.php$|Policies\/|Guard\.php$)/i],
52
+ ['http-controller',/(?:Controllers?\/|Http\/Requests?\/)/i],
53
+ ['service',/(?:Services?\/|Actions?\/|Repositories?\/)/i],
54
+ ['background',/(?:Jobs?\/|Listeners?\/|Commands?\/|Queue\/)/i],
55
+ ['offline-sync',/(?:offline|sync|replay|service[-_]?worker|\bsw\.js\b)/i],
56
+ ['financial',/(?:checkout|payment|refund|price|discount|tax|ledger|invoice|poscontroller)/i],
57
+ ['tenant-relationship',/(?:tenant|organization|organisation|store|supplier|membership|inventory|productvariant)/i]
58
+ ];
59
+ const entry_points=groups.filter(([,re])=>paths.some(x=>re.test(x))).map(([name])=>name);
60
+ return {entry_points,requires_role_matrix:entry_points.some(x=>['routes','middleware','http-controller','background','offline-sync','tenant-relationship'].includes(x)),
61
+ requires_domain_invariant_tests:entry_points.some(x=>['financial','offline-sync','tenant-relationship'].includes(x)),
62
+ verified_coverage:false,
63
+ warning:'Framework route/middleware dispatch and foreign-key ownership are not established by static file references. Test each entry point independently.'};
64
+ }
65
+
66
+ // Suggestions only: filename proximity does not prove that a test exercises a path.
67
+ export function rankFallbackTests(changed,available,limit=5){
68
+ const stems=changed.map(p=>p.split('/').at(-1).replace(/\.[^.]+$/,'').replace(/(?:Service|Controller|Repository|Request|Model)$/,'').toLowerCase()).filter(Boolean);
69
+ return [...new Set(available)].map(file=>{
70
+ const name=file.split('/').at(-1).replace(/\.[^.]+$/,'').toLowerCase();
71
+ let score=0;
72
+ for(const stem of stems)if(stem.length>=3&&(name.includes(stem)||stem.includes(name.replace(/test|spec/g,''))))score=Math.max(score,stem===name?3:2);
73
+ return {file,score};
74
+ }).filter(x=>x.score>0).sort((a,b)=>b.score-a.score||a.file.localeCompare(b.file)).slice(0,limit).map(x=>x.file);
75
+ }
76
+
77
+ export function analyzeImpact(store,wsId,workspace,{changed=[],depth=3}={}){
78
+ const rawPaths=(changed.length?changed:gitChanges(workspace)).slice(0,200);
79
+ const paths=[];
80
+ for(const raw of rawPaths){
81
+ if(!isSafeRelative(raw)||shouldIgnore(raw))throw new Error('Unsafe changed path');
82
+ const rel=normalizeRelPath(raw);
83
+ if(!isSafeRelative(rel)||shouldIgnore(rel))throw new Error('Unsafe changed path');
84
+ paths.push(rel);
85
+ }
86
+ const uniquePaths=uniq(paths),changedIds=new Set(uniquePaths.map(p=>'file:'+p));
87
+ const cappedDepth=Math.min(4,Math.max(1,Number(depth)||3));
88
+ const queue=uniquePaths.map(p=>({id:'file:'+p,depth:0}));
89
+ const visited=new Map(),foundEdges=[],directDependencies=new Set(),observedConsumers=new Set(),heuristicTests=new Set();
90
+ let head=0,queueLimited=false,edgeLimited=false;
91
+ for(const id of changedIds){
92
+ const direct=store.all("SELECT target FROM edges WHERE workspace_id=? AND source=? AND kind='IMPORTS' LIMIT 100",wsId,id);
93
+ for(const e of direct)if(e.target.startsWith('file:'))directDependencies.add(e.target.slice(5));
94
+ if(direct.length===100)edgeLimited=true;
95
+ }
96
+ while(head<queue.length&&visited.size<350){
97
+ const cur=queue[head++];
98
+ if(visited.has(cur.id)&&visited.get(cur.id)<=cur.depth)continue;
99
+ visited.set(cur.id,cur.depth);
100
+ if(cur.depth>=cappedDepth)continue;
101
+ // Only reverse dependencies can be impacted by a changed provider. Direct
102
+ // imports from a changed consumer are dependencies, not affected callers.
103
+ const rels=store.all(
104
+ "SELECT source,target,kind,basis,state FROM edges WHERE workspace_id=? AND target=? AND kind IN ('IMPORTS','MAY_TEST') ORDER BY CASE kind WHEN 'IMPORTS' THEN 0 ELSE 1 END LIMIT 250",
105
+ wsId,cur.id
106
+ );
107
+ if(rels.length===250)edgeLimited=true;
108
+ for(const e of rels){
109
+ if(!e.source.startsWith('file:')||!e.target.startsWith('file:'))continue;
110
+ foundEdges.push(e);
111
+ if(e.kind==='IMPORTS')observedConsumers.add(e.source.slice(5));
112
+ if(e.kind==='MAY_TEST')heuristicTests.add(e.source.slice(5));
113
+ // Test candidates are terminal: a heuristic MAY_TEST must never be
114
+ // promoted into another source dependency during traversal.
115
+ if(e.kind==='MAY_TEST'){
116
+ if(!visited.has(e.source))visited.set(e.source,cur.depth+1);
117
+ continue;
118
+ }
119
+ if(!visited.has(e.source)&&queue.length<1000)queue.push({id:e.source,depth:cur.depth+1});
120
+ else if(queue.length>=1000)queueLimited=true;
121
+ }
122
+ }
123
+ const traversalTruncated=head<queue.length||queueLimited||edgeLimited;
124
+ const ids=[...visited.keys()];
125
+ const rows=batchedSelect(store,'SELECT id,kind,label,file_path,basis FROM nodes WHERE workspace_id=? AND id IN ',wsId,ids);
126
+ const nodes=rows.map(n=>({id:n.id,kind:n.kind,label:n.label,path:n.file_path,basis:n.basis}));
127
+ const candidates=nodes.filter(n=>!changedIds.has(n.id));
128
+ const relatedTests=candidates.filter(n=>n.kind==='test').map(n=>n.path);
129
+ const allTests=store.all("SELECT file_path FROM nodes WHERE workspace_id=? AND kind='test' LIMIT 150",wsId).map(x=>x.file_path);
130
+ const missingChanged=uniquePaths.filter(p=>!store.get('SELECT 1 AS present FROM files WHERE workspace_id=? AND path=?',wsId,p));
131
+ const fallback=rankFallbackTests(uniquePaths,allTests);
132
+ const risks=[];
133
+ if(uniquePaths.some(p=>isSensitiveFeature(p))||nodes.some(n=>isSensitiveFeature(n.label)))risks.push('security-or-state-sensitive');
134
+ if(uniquePaths.some(p=>/schema|migration|lock|config|middleware/i.test(p)))risks.push('cross-module-configuration');
135
+ if(heuristicTests.size||nodes.some(n=>n.basis==='derived'))risks.push('heuristic-relations');
136
+ if(!relatedTests.length)risks.push('no-mapped-tests');
137
+ const entryReview=inferEntryPointRisks(uniquePaths);
138
+ if(entryReview.requires_role_matrix||entryReview.requires_domain_invariant_tests)risks.push('unverified-runtime-authorization-or-domain-constraints');
139
+ const risk=risks.includes('security-or-state-sensitive')?'high':risks.length>=2?'medium':uniquePaths.length?'low':'unknown';
140
+ const affected=candidates.filter(n=>n.kind!=='symbol'&&n.kind!=='feature');
141
+ const uniqueTests=uniq(relatedTests);
142
+ return {
143
+ changed:uniquePaths,affected:affected.slice(0,25),affected_total:affected.length,
144
+ related_tests:uniqueTests.slice(0,10),related_tests_total:uniqueTests.length,
145
+ fallback_test_candidates:relatedTests.length?[]:fallback,risk,signals:risks,
146
+ direct_dependencies:[...directDependencies].slice(0,20),direct_dependencies_total:directDependencies.size,
147
+ observed_consumers:[...observedConsumers].filter(p=>!uniquePaths.includes(p)).slice(0,25),
148
+ heuristic_test_candidates:[...heuristicTests].slice(0,10),
149
+ entry_point_review:entryReview,
150
+ coverage:{graph_nodes_visited:visited.size,traversal_depth:cappedDepth,static_only:true,
151
+ dependency_direction:'reverse-imports-for-affected;forward-imports-for-dependencies',
152
+ result_truncated:affected.length>25||uniqueTests.length>10||directDependencies.size>20,
153
+ graph_visit_limit_reached:traversalTruncated,indexed_changed_files:uniquePaths.length-missingChanged.length,
154
+ unindexed_changed_files:missingChanged.length,unindexed_changed_paths:missingChanged.slice(0,10),
155
+ mapped_test_evidence:uniqueTests.length?'static_graph_only':'none',
156
+ fallback_test_confidence:fallback.length?'filename_heuristic_only':'none',
157
+ analysis_complete:false},
158
+ uncertainty:['Static references and naming heuristics cannot prove complete runtime impact.',
159
+ ...(missingChanged.length?['Some changed files are not in the index: results may miss dependencies or tests.']:[]),
160
+ ...(!uniqueTests.length?['No tests mapped by static graph; suggested filenames are not verified test coverage.']:[]),
161
+ ...(traversalTruncated?['Graph traversal or per-node fan-out was capped. Results are incomplete.']:[]),
162
+ ...(heuristicTests.size?['Heuristic test mappings are candidates, not execution evidence.']:[]),
163
+ ...(entryReview.requires_role_matrix?['Role matrix, route middleware and background operation access have not been dynamically tested.']:[]),
164
+ ...(entryReview.requires_domain_invariant_tests?['Financial and tenant/store relationships require independent integration assertions; static edges are insufficient.']:[]),
165
+ ...(uniquePaths.length?[]:['No changed paths detected. Provide changed paths explicitly or modify the working tree.'])]
166
+ };
167
+ }
168
+ export function validateChangedPaths(paths){if(!Array.isArray(paths)||paths.length>200)throw new Error('changed must be an array with at most 200 paths');for(const p of paths)if(!isSafeRelative(p)||shouldIgnore(p))throw new Error('Invalid changed file path')}
169
+ export function shortGraphSummary(store,wsId){return {files:store.get('SELECT COUNT(*) as n FROM files WHERE workspace_id=?',wsId)?.n||0,nodes:store.get('SELECT COUNT(*) as n FROM nodes WHERE workspace_id=?',wsId)?.n||0,relations:store.get('SELECT COUNT(*) as n FROM edges WHERE workspace_id=?',wsId)?.n||0,tests:store.get("SELECT COUNT(*) as n FROM nodes WHERE workspace_id=? AND kind='test'",wsId)?.n||0}}
@@ -0,0 +1,53 @@
1
+ import {ALL_TOOLS} from './tools.mjs';
2
+ // Never copy untrusted exception text into a model response. Paths, credentials and
3
+ // tool arguments can appear in exceptions from external helpers and adapters.
4
+ export function classifyMcpFailure(toolName,error){
5
+ const msg=String(error?.message||error||'').slice(0,2000);
6
+ const spec=ALL_TOOLS.find(x=>x.name===toolName);
7
+ if(/Unknown argument:|Missing (?!resource uri)|Invalid (type|value|integer|array|object|item):|Arguments must be|Value too long:/i.test(msg)){
8
+ return {status:'error',code:'invalid_tool_arguments',message:'The tool request does not match the allowed input contract.',
9
+ accepted_parameters:spec?Object.keys(spec.inputSchema.properties):[],
10
+ required_parameters:spec?.inputSchema.required??[],
11
+ next_step:'Inspect tools/list and retry with the documented parameter names and types. Do not guess aliases.'};
12
+ }
13
+ if(/Protected workspace denied/i.test(msg)){
14
+ return {status:'error',code:'workspace_access_denied',
15
+ message:'Protected application configuration paths cannot be used as PILAH project workspaces.',
16
+ next_step:'Choose an already trusted ordinary project. Do not run allow or retry this protected path.'};
17
+ }
18
+ if(/Workspace is not authorized/i.test(msg)){
19
+ return {status:'error',code:'workspace_authorization_required',
20
+ message:'Workspace is not authorized for PILAH.',
21
+ next_step:'Ask the user to trust the ordinary project in Antigravity, or use node <PLUGIN_ROOT>/scripts/pilah.mjs allow <workspace> from the installed plugin. Never bypass protected roots.'};
22
+ }
23
+ if(/protected root|system directory|Symlink access denied|sensitive file denied|escapes authorized|Path escapes|outside workspace|Permission denied/i.test(msg)){
24
+ return {status:'error',code:'workspace_access_denied',
25
+ message:'PILAH denied workspace or file access under its safety policy.',
26
+ next_step:'Choose an authorized project and permitted project file. Do not change protected-root checks.'};
27
+ }
28
+ if(/ENOENT|no such file|does not exist|not found|cannot find (?:the )?(?:file|path)|unknown workspace|invalid workspace/i.test(msg)){
29
+ return {status:'error',code:'workspace_not_found',message:'Requested workspace does not exist or is not accessible.',next_step:'Provide an existing authorized project path; no permissions are automatically changed.'};
30
+ }
31
+ if(/Source integrity incomplete|Source revision differs|source.*stale|Acceptance plan.*different source_revision|Report.*stale/i.test(msg)){
32
+ return {status:'error',code:'source_freshness_unconfirmed',
33
+ message:'PILAH cannot verify that source and test evidence refer to the same revision.',
34
+ next_step:'Re-index the authorized workspace, rerun the affected native tests, and provide a new revision-bound report. Do not reuse prior PASS.'};
35
+ }
36
+ if(/No machine-readable test report|Required relative evidence artifact|No evidence artifact|Named test case.*not found/i.test(msg)){
37
+ return {status:'error',code:'evidence_missing',
38
+ message:'PILAH needs a bounded, named machine-readable test report.',
39
+ next_step:'Run the relevant native test with JUnit, TAP or supported JSON output, then provide the report path and exact test case.'};
40
+ }
41
+ if(/response exceeds 64 KiB|Evidence report exceeds|Evidence artifact exceeds|index_byte_budget_exceeded/i.test(msg)){
42
+ return {status:'error',code:'resource_limit',
43
+ message:'The requested analysis exceeds a bounded input or output limit.',
44
+ next_step:'Narrow the query, files, graph depth or evidence scope; do not disable input limits.'};
45
+ }
46
+ if(/Unknown tool/i.test(msg)){
47
+ return {status:'error',code:'unknown_tool',message:'Tool is not available.',
48
+ available_tools:ALL_TOOLS.filter(x=>x.name.startsWith('pilah_')).map(x=>x.name),
49
+ next_step:'Inspect tools/list for exact tool names.'};
50
+ }
51
+ return {status:'error',code:'tool_execution_error',message:'PILAH tool execution failed. Technical details were withheld to protect local data.',
52
+ next_step:'Check private local diagnostics and validated arguments; do not retry indefinitely.'};
53
+ }
package/src/mcp.mjs ADDED
@@ -0,0 +1,151 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import pkg from '../package.json' with {type:'json'};
4
+ import path from 'node:path';
5
+ import readline from 'node:readline';
6
+ import {Engine} from './engine.mjs';
7
+ import {getListedTools,validateArgs} from './tools.mjs';
8
+ import {dataDir,getA2AMode,getCompactMode,getAutoTrustMode,loadAllowlist,loadAntigravityWorkspaces,requireAuthorizedWorkspace} from './security.mjs';
9
+ import {getSessionTokenUsage} from './tokens.mjs';
10
+ import {classifyMcpFailure} from './mcp-diagnostics.mjs';
11
+
12
+ const server={name:'pilah',version:pkg.version}, engine=new Engine();
13
+ // Stdio currently implements the 2025-03-26 handshake contract only.
14
+ const MCP_PROTOCOL='2025-03-26';
15
+ const io=readline.createInterface({input:process.stdin,crlfDelay:Infinity,terminal:false});
16
+ const answer=(id,result,error)=>{
17
+ const message={jsonrpc:'2.0',id,...(error?{error:{code:error.code||-32603,message:String(error.message||error).slice(0,300),...(error.data?{data:error.data}:{})}}:{result})};
18
+ process.stdout.write(JSON.stringify(message)+'\n');
19
+ };
20
+
21
+ const RESOURCES = [
22
+ {uri:'pilah://status',name:'PILAH Status',description:'Current PILAH modes and redacted workspace counts; no local paths.',mimeType:'application/json'},
23
+ {uri:'pilah://tokens/session',name:'PILAH Session Diagnostics',description:'Local session event counts only; model token totals require official Antigravity CLI JSON output.',mimeType:'application/json'},
24
+ {uri:'pilah://workspace/summary',name:'PILAH Workspace Summary',description:'Active workspace graph coverage and estimated source inventory; not model token usage.',mimeType:'application/json'},
25
+ {uri:'pilah://side-questions',name:'PILAH Side Questions',description:'Recorded Antigravity side questions (/btw) and exploration notes.',mimeType:'application/json'},
26
+ ];
27
+
28
+ function getActiveSession(){
29
+ try{
30
+ const file=path.join(engine.store.base,'active-session.json');
31
+ const stat=fs.lstatSync(file);
32
+ if(!stat.isFile()||stat.size>128*1024)return null;
33
+ const data=JSON.parse(fs.readFileSync(file,'utf8'));
34
+ // This stdio server is shared across sessions. Never infer a calling client's
35
+ // session when recent parent/subagent or other project IDs coexist.
36
+ const identities=new Set(Object.values(data?.byWorkspace||{}).map(x=>x?.conversationId).filter(Boolean));
37
+ if(identities.size>1)return null;
38
+ const active=data?.latest;
39
+ const workspace=active?.workspacePaths?.[0] || active?.cwd;
40
+ return active?.conversationId && workspace ? {conversationId:active.conversationId,workspace} : null;
41
+ }catch{return null}
42
+ }
43
+ function readResource(uri){
44
+ if(uri.replace(/^a2a:\/\//,'pilah://')==='pilah://status'){
45
+ return {
46
+ name:'pilah',
47
+ version:server.version,
48
+ mode:getA2AMode(),
49
+ compact_mode:getCompactMode(),
50
+ auto_trust:getAutoTrustMode(),
51
+ data_dir_configured:fs.existsSync(dataDir()),
52
+ authorized_workspace_count:loadAllowlist().length,
53
+ antigravity_workspace_count:loadAntigravityWorkspaces().length,
54
+ active_workspace_authorized:(()=>{
55
+ const active=getActiveSession();
56
+ if(!active)return false;
57
+ try{requireAuthorizedWorkspace(active.workspace);return true}catch{return false}
58
+ })(),
59
+ };
60
+ }
61
+ if(uri.replace(/^a2a:\/\//,'pilah://')==='pilah://tokens/session'){
62
+ const active=getActiveSession();
63
+ if(!active)return {status:'unavailable',reason:'No active session found'};
64
+ requireAuthorizedWorkspace(active.workspace);
65
+ return getSessionTokenUsage(active.conversationId,{workspace:active.workspace,dataDirPath:engine.store.base})||{status:'unavailable',reason:'No session transcript found'};
66
+ }
67
+ if(uri.replace(/^a2a:\/\//,'pilah://')==='pilah://side-questions'){
68
+ const active=getActiveSession();
69
+ if(!active?.conversationId || !active?.workspace) return {status:'no_active_session',side_questions:[]};
70
+ const root=requireAuthorizedWorkspace(active.workspace);
71
+ const wsId=engine.store.register(root);
72
+ return {side_questions:engine.store.listSideQuestions({workspaceId:wsId,conversationId:active.conversationId,limit:20})};
73
+ }
74
+ if(uri.replace(/^a2a:\/\//,'pilah://')==='pilah://workspace/summary'){
75
+ const activeWs=getActiveSession()?.workspace;
76
+ if(!activeWs)return {status:'no_active_workspace',reason:'Open an authorized workspace in a session first.'};
77
+ return engine.context({workspace:activeWs,action:'inspect'});
78
+ }
79
+ throw Object.assign(new Error('Resource not found'),{code:-32002});
80
+ }
81
+
82
+ function route(req){
83
+ if(req?.jsonrpc!=='2.0'||typeof req.method!=='string')throw Object.assign(new Error('Invalid JSON-RPC request'),{code:-32600});
84
+ switch(req.method){
85
+ case 'initialize':{
86
+ const requested=req.params?.protocolVersion??MCP_PROTOCOL;
87
+ if(requested!==MCP_PROTOCOL)throw Object.assign(new Error('Unsupported MCP protocol version; supported: '+MCP_PROTOCOL),{code:-32602,data:{requested:typeof requested==='string'?requested.slice(0,40):null,supported:[MCP_PROTOCOL]}});
88
+ return {protocolVersion:MCP_PROTOCOL,capabilities:{tools:{listChanged:false},resources:{subscribe:false,listChanged:false}},serverInfo:server};
89
+ }
90
+ case 'ping':return {};
91
+ case 'tools/list':return {tools:getListedTools()};
92
+ case 'tools/call':{
93
+ const {name,arguments:args={}}=req.params||{};validateArgs(name,args);
94
+ let result;
95
+ switch(name){
96
+ case 'pilah_context':
97
+ case 'a2a_context':
98
+ case 'verifykit_context':result=engine.context(args);break;
99
+ case 'pilah_impact':
100
+ case 'a2a_impact':
101
+ case 'verifykit_impact':result=engine.impact(args);break;
102
+ case 'pilah_verify':
103
+ case 'a2a_verify':
104
+ case 'verifykit_verify':result=engine.verify(args);break;
105
+ case 'pilah_evidence':
106
+ case 'a2a_evidence':
107
+ case 'verifykit_evidence':result=engine.evidence(args);break;
108
+ default:throw new Error('Unknown tool: '+name);
109
+ }
110
+ const text=JSON.stringify(result);
111
+ if(!text)throw new Error('Empty tool response');
112
+ if(Buffer.byteLength(text,'utf8')>64*1024)throw new Error('MCP response exceeds 64 KiB. Narrow the file list, query, or diff range.');
113
+ return {content:[{type:'text',text}],isError:false};
114
+ }
115
+ case 'resources/list':return {resources:RESOURCES};
116
+ case 'resources/read':{
117
+ const uri=req.params?.uri;
118
+ if(typeof uri!=='string'||!uri)throw Object.assign(new Error('Missing resource uri'),{code:-32602});
119
+ const payload=readResource(uri);
120
+ const content=JSON.stringify(payload);
121
+ if(Buffer.byteLength(content,'utf8')>64*1024)throw new Error('MCP resource response exceeds 64 KiB');
122
+ return {contents:[{uri,mimeType:'application/json',text:content}]};
123
+ }
124
+ case 'prompts/list':return {prompts:[]};
125
+ default:throw Object.assign(new Error('Method not found'),{code:-32601});
126
+ }
127
+ }
128
+ io.on('line',(line)=>{
129
+ if(!line.trim())return;
130
+ if(line.length>180000){answer(null,null,{code:-32600,message:'Request too large'});return}
131
+ let req;
132
+ try{req=JSON.parse(line)}catch{answer(null,null,{code:-32700,message:'Parse error'});return}
133
+ if(!req || typeof req!=='object' || Array.isArray(req)){answer(null,null,{code:-32600,message:'Invalid JSON-RPC request'});return}
134
+ if(req.id!==undefined && req.id!==null && typeof req.id!=='string' && typeof req.id!=='number'){
135
+ answer(null,null,{code:-32600,message:'Invalid JSON-RPC id'});return;
136
+ }
137
+ // JSON-RPC notifications have no response and MUST NOT run data-changing tool handlers.
138
+ if(req.id===undefined)return;
139
+ try{answer(req.id,route(req))}catch(e){
140
+ if(req.method==='tools/call'){answer(req.id,{content:[{type:'text',text:JSON.stringify(classifyMcpFailure(req.params?.name,e))}],isError:true});return}
141
+ if(req.method==='resources/read' && e?.code!==-32002 && e?.code!==-32602){
142
+ const safe=classifyMcpFailure('resources/read',e);
143
+ answer(req.id,null,{code:-32000,message:safe.code+': '+safe.message});return;
144
+ }
145
+ answer(req.id,null,e);
146
+ }
147
+ });
148
+ const shutdown=()=>{try{engine.close()}catch{}process.exit(0)};
149
+ process.on('SIGINT',shutdown);
150
+ process.on('SIGTERM',shutdown);
151
+ io.on('close',()=>{try{engine.close()}catch{}});
@@ -0,0 +1,108 @@
1
+ // Local conservative assisted recovery: no quota APIs, model switching or retries.
2
+ import {sha256} from './security.mjs';
3
+
4
+ const CONV=/^[A-Za-z0-9._-]{4,128}$/;
5
+ export const validConversationId=id=>typeof id==='string'&&CONV.test(id)&&id!=='.'&&id!=='..';
6
+ export const cleanModelName=name=>typeof name==='string'&&/^[A-Za-z0-9][A-Za-z0-9 ._()/-]{0,99}$/.test(name)?name:null;
7
+ export function classifyModelFailure(error){
8
+ if(typeof error!=='string'||!error.trim())return {category:'unknown',confidence:'low'};
9
+ const e=error.slice(0,4096);
10
+ let category='unknown',confidence='low';
11
+ if(/quota (?:exhausted|exceeded|depleted)|(?:weekly|daily|five.hour|5.hour) (?:quota|limit) (?:reached|exhausted|exceeded)|insufficient (?:ai )?credits|credit balance exhausted|model quota exhausted/i.test(e))category='quota_exhausted';
12
+ else if(/\b(?:429|rate.limit(?:ed)?|too many requests|resource_exhausted)\b/i.test(e))category='rate_limited';
13
+ else if(/\b(?:503|high traffic|capacity exhausted|service unavailable|backend overload|server (?:is )?(?:overloaded|busy))\b/i.test(e))category='capacity';
14
+ else if(/\b(?:502|504|bad gateway|gateway timeout|internal server error|500)\b/i.test(e))category='service_error';
15
+ else if(/\b(?:401|403|unauthorized|unauthenticated|permission denied|invalid credentials|invalid api key)\b/i.test(e))category='authentication';
16
+ else if(/\b(?:context window|context length|maximum context|input (?:is )?too long|token limit exceeded)\b/i.test(e))category='context_limit';
17
+ else if(/\b(?:econnreset|econnrefused|etimedout|network unreachable|connection (?:reset|timed out)|tls handshake)\b/i.test(e))category='network';
18
+ if(category!=='unknown')confidence='medium';
19
+ return {category,confidence};
20
+ }
21
+ export function modelRecoveryAdvice(category){
22
+ const base={automatic_switch:false,model_availability:'not_checked',quota:'not_checked',
23
+ selection:'Use the native model selector or /model; PILAH cannot switch the active model.'};
24
+ switch(category){
25
+ case 'quota_exhausted':return {...base,action:'check_quota_and_choose',message:'Open /usage and inspect remaining quota by model group. If an eligible group has capacity, select a model manually with /model. Availability is not verified.'};
26
+ case 'rate_limited':return {...base,action:'respect_native_retry',message:'Rate limiting is not proof the weekly quota is exhausted. Respect native retry/backoff and check /usage; do not retry endlessly or rotate accounts.'};
27
+ case 'capacity':case 'service_error':return {...base,action:'native_retry_then_choose',message:'Let Antigravity native retries finish. If errors persist, check /usage and select an eligible model manually with /model.'};
28
+ case 'network':return {...base,action:'check_connection',message:'Check the network and Antigravity status. Changing model might not solve connectivity errors.'};
29
+ case 'authentication':return {...base,action:'check_sign_in',message:'Check your native Antigravity sign-in and permissions; do not rotate accounts automatically.'};
30
+ case 'context_limit':return {...base,action:'compact_or_resume',message:'Use an explicit concise checkpoint and revalidate source and tests. Switching models does not guarantee more context.'};
31
+ default:return {...base,action:'inspect_native_error',message:'Cause is unconfirmed. Inspect Antigravity errors and /usage before deciding how to recover.'};
32
+ }
33
+ }
34
+ export function saveRecoveryCheckpoint(store,wsId,{conversationId,revision,taskSummary,completed=[],nextSteps=[],decisions=[],pendingTests=[]}){
35
+ if(!validConversationId(conversationId))throw Error('Valid conversation_id required');
36
+ if(typeof taskSummary!=='string'||!taskSummary.trim()||taskSummary.length>500)throw Error('task_summary must be 1-500 characters');
37
+ for(const [name,items] of [['completed',completed],['next_steps',nextSteps],['decisions',decisions],['pending_tests',pendingTests]]){
38
+ if(!Array.isArray(items)||items.length>8||items.some(x=>typeof x!=='string'||!x.trim()||x.length>200))throw Error(name+' must have up to 8 short statements');
39
+ }
40
+ // Never persist common credential or bearer-token assignments in plaintext
41
+ // as part of a model-recovery handoff, even when supplied explicitly.
42
+ const notes=[taskSummary,...completed,...nextSteps,...decisions,...pendingTests];
43
+ if(notes.some(x=>/(?:password|passwd|api[ _-]?key|(?:access[_-]?|refresh[_-]?)?token|cookie|authorization|private[_-]?key|secret)\s*[:=]|\bBearer\s+[A-Za-z0-9._~-]{8,}/i.test(x) || /(?:\bgh[pousr]_[A-Za-z0-9]{10,}|\bsk-[A-Za-z0-9_-]{12,}|\bAKIA[0-9A-Z]{16}\b|\bnpm_[A-Za-z0-9]{10,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)/i.test(x))){
44
+ throw new Error('Checkpoint contains a possible credential; remove secrets before saving');
45
+ }
46
+ const now=new Date().toISOString();
47
+ store.run('INSERT INTO recovery_checkpoints(workspace_id,conversation_id,revision_id,task_summary,completed_json,next_steps_json,decisions_json,pending_tests_json,created_at,updated_at) VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(workspace_id,conversation_id) DO UPDATE SET revision_id=excluded.revision_id,task_summary=excluded.task_summary,completed_json=excluded.completed_json,next_steps_json=excluded.next_steps_json,decisions_json=excluded.decisions_json,pending_tests_json=excluded.pending_tests_json,updated_at=excluded.updated_at',
48
+ wsId,conversationId,revision||null,taskSummary.trim(),JSON.stringify(completed),JSON.stringify(nextSteps),JSON.stringify(decisions),JSON.stringify(pendingTests),now,now);
49
+ store.run('DELETE FROM recovery_checkpoints WHERE workspace_id=? AND conversation_id NOT IN (SELECT conversation_id FROM recovery_checkpoints WHERE workspace_id=? ORDER BY updated_at DESC LIMIT 30)',wsId,wsId);
50
+ return {status:'saved',task_outcome:pendingTests.length||nextSteps.length?'partial':'unknown',
51
+ conversation_id:conversationId,revision:revision||null,verified:false,
52
+ content_origin:'explicit_notes',updated_at:now};
53
+ }
54
+ export function recordModelStop(store,wsId,{conversationId,modelName,error,terminationReason}){
55
+ if(!validConversationId(conversationId)||terminationReason!=='error')return {recorded:false};
56
+ const model=cleanModelName(modelName),classified=classifyModelFailure(error),now=new Date().toISOString();
57
+ // Persist only category, not raw provider messages, prompts or secrets.
58
+ store.run('INSERT INTO model_recovery_state(workspace_id,conversation_id,model_name,incident_category,incident_confidence,incident_at,updated_at) VALUES(?,?,?,?,?,?,?) ON CONFLICT(workspace_id,conversation_id) DO UPDATE SET model_name=COALESCE(excluded.model_name,model_recovery_state.model_name),incident_category=excluded.incident_category,incident_confidence=excluded.incident_confidence,incident_at=excluded.incident_at,updated_at=excluded.updated_at',
59
+ wsId,conversationId,model,classified.category,classified.confidence,now,now);
60
+ store.run('DELETE FROM model_recovery_state WHERE workspace_id=? AND conversation_id NOT IN (SELECT conversation_id FROM model_recovery_state WHERE workspace_id=? ORDER BY updated_at DESC LIMIT 60)',wsId,wsId);
61
+ return {recorded:true,category:classified.category,confidence:classified.confidence,error_body_persisted:false};
62
+ }
63
+ export function observeModelInvocation(store,wsId,{conversationId,modelName}){
64
+ if(!validConversationId(conversationId))return {notice:null};
65
+ const model=cleanModelName(modelName);if(!model)return {notice:null};
66
+ return store.transaction(()=>{
67
+ const prev=store.get('SELECT * FROM model_recovery_state WHERE workspace_id=? AND conversation_id=?',wsId,conversationId);
68
+ const changed=Boolean(prev?.model_name&&prev.model_name!==model);
69
+ const age=prev?.incident_at?Date.now()-Date.parse(prev.incident_at):Infinity;
70
+ const incident=age>=0&&age<6*60*60*1000?prev?.incident_category:null;
71
+ const key=sha256(JSON.stringify([prev?.model_name||'',model,incident||'',prev?.incident_at||'']));
72
+ const notify=(changed||incident)&&prev?.notice_signature!==key;
73
+ const now=new Date().toISOString();
74
+ store.run('INSERT INTO model_recovery_state(workspace_id,conversation_id,model_name,notice_signature,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(workspace_id,conversation_id) DO UPDATE SET model_name=excluded.model_name,notice_signature=COALESCE(excluded.notice_signature,model_recovery_state.notice_signature),updated_at=excluded.updated_at',
75
+ wsId,conversationId,model,notify?key:null,now);
76
+ if(!notify)return {notice:null,model_changed:changed};
77
+ const checkpoint=store.get('SELECT conversation_id FROM recovery_checkpoints WHERE workspace_id=? AND conversation_id=?',wsId,conversationId);
78
+ // No untrusted free-text task notes embedded as high-priority instructions.
79
+ const notice='PILAH assisted recovery: '+(changed?'The user-selected model changed. ':'A model invocation previously failed. ')+
80
+ (incident?'Observed error category: '+incident+' (heuristic, not verified quota). ':'')+
81
+ (checkpoint?'Explicit task checkpoint available via pilah_evidence(operation="model_recovery"). ':'')+
82
+ 'Verify current files and test state. Never claim the last task completed, auto-switch models or retry blindly.';
83
+ return {notice,model_changed:changed,checkpoint_available:Boolean(checkpoint)};
84
+ });
85
+ }
86
+ export function recoveryStatus(store,wsId,{conversationId=null,currentRevision=null}={}){
87
+ if(conversationId!==null&&!validConversationId(conversationId))throw Error('Invalid conversation_id');
88
+ const state=conversationId?
89
+ store.get('SELECT conversation_id,model_name,incident_category,incident_confidence,incident_at FROM model_recovery_state WHERE workspace_id=? AND conversation_id=?',wsId,conversationId):
90
+ store.get('SELECT conversation_id,model_name,incident_category,incident_confidence,incident_at FROM model_recovery_state WHERE workspace_id=? ORDER BY updated_at DESC LIMIT 1',wsId);
91
+ const row=conversationId?
92
+ store.get('SELECT * FROM recovery_checkpoints WHERE workspace_id=? AND conversation_id=?',wsId,conversationId):
93
+ store.get('SELECT * FROM recovery_checkpoints WHERE workspace_id=? ORDER BY updated_at DESC LIMIT 1',wsId);
94
+ const age=row?Date.now()-Date.parse(row.updated_at):Infinity;
95
+ const checkpoint=age>=0&&age<=7*24*60*60*1000?{
96
+ conversation_id:row.conversation_id,task_summary:row.task_summary,
97
+ completed:JSON.parse(row.completed_json),next_steps:JSON.parse(row.next_steps_json),
98
+ decisions:JSON.parse(row.decisions_json||'[]'),pending_tests:JSON.parse(row.pending_tests_json||'[]'),
99
+ source_revision:row.revision_id,source_revision_matches:typeof currentRevision==='string'?row.revision_id===currentRevision:null,
100
+ source_freshness:typeof currentRevision!=='string'?'unknown':row.revision_id===currentRevision?'current':'stale',
101
+ task_outcome:typeof currentRevision==='string'&&row.revision_id!==currentRevision?'stale':
102
+ (JSON.parse(row.pending_tests_json||'[]').length||JSON.parse(row.next_steps_json||'[]').length?'partial':'unknown'),
103
+ updated_at:row.updated_at,verified:false,
104
+ warning:'Explicit notes are not proof of completion. Recheck code, permissions and tests.'}:null;
105
+ return {status:'assisted_only',automatic_switch:false,
106
+ observation:state?{...state}:null,advice:modelRecoveryAdvice(state?.incident_category||'unknown'),checkpoint,
107
+ limitations:['No quota API queried','Error categories are heuristic','No automatic model switch or retry executed']};
108
+ }
@@ -0,0 +1,45 @@
1
+ // Native Antigravity failure triage only. A2A does not call or intercept native tools.
2
+ // Never include raw error text, paths, screenshots, commands or credentials in output.
3
+ const CATEGORIES=new Set(['invalid_arguments','context_lost','timeout','permission_denied','missing_file','edit_conflict','unknown']);
4
+ const ADVICE={
5
+ invalid_arguments:{next_step:'Inspect the current native tool schema and required parameter names; obtain a fresh pageId when applicable.',safe_retry:'Only after corrected parameters.'},
6
+ context_lost:{next_step:'List active browser pages, select a current page and re-evaluate selectors after navigation.',safe_retry:'Only after refreshing browser state.'},
7
+ timeout:{next_step:'Check whether the prior action completed before retrying. Respect native backoff and user approvals.',safe_retry:'Only after observing the current state.'},
8
+ permission_denied:{next_step:'Stop and request the user-approved workspace or tool permission. Never bypass native safeguards.',safe_retry:'Only after explicit authorization.'},
9
+ missing_file:{next_step:'Inspect the current project tree and resolve the existing authorized file path.',safe_retry:'Only after confirming the file exists.'},
10
+ edit_conflict:{next_step:'Read the current file version, recompute the minimal patch and re-run affected tests.',safe_retry:'Only after refreshing the expected source state.'},
11
+ unknown:{next_step:'Inspect native diagnostics and last observable tool state. Do not assume cause or retry blindly.',safe_retry:'Only after determining a changed condition.'}
12
+ };
13
+ export function classifyNativeToolFailure({error_class,error_hint='',tool_family='other',retry_count=0}={}){
14
+ if(typeof error_hint!=='string'||error_hint.length>400)throw Error('Invalid bounded error hint');
15
+ if(!['mcp','browser','filesystem','terminal','other'].includes(tool_family))throw Error('Invalid tool family');
16
+ if(!Number.isSafeInteger(retry_count)||retry_count<0||retry_count>20)throw Error('Invalid retry count');
17
+ if(error_class!==undefined&&!CATEGORIES.has(error_class))throw Error('Unknown error class');
18
+ const e=error_hint;
19
+ // Authorization failures are safety critical: an argument/pageId substring or
20
+ // a caller-provided lower-severity class must never downgrade them.
21
+ const denial=/(?:permission denied|forbidden|eacces|unauthori[sz]ed|\b403\b|access denied)/i.test(e);
22
+ const detected=
23
+ denial?'permission_denied':
24
+ /(?:-32602|invalid (?:arguments?|parameter)|missing (?:required|parameter)|invalid pageid)/i.test(e)?'invalid_arguments':
25
+ /(?:execution context (?:was )?destroyed|context lost|stale element|no such page|target closed)/i.test(e)?'context_lost':
26
+ /(?:timeout|timed out|deadline exceeded|etimedout)/i.test(e)?'timeout':
27
+ /(?:enoent|file not found|no such file|path does not exist)/i.test(e)?'missing_file':
28
+ /(?:edit conflict|patch failed|expected text not found|old string not found|does not match)/i.test(e)?'edit_conflict':'unknown';
29
+ const category=error_class==='permission_denied'?'permission_denied':(detected==='unknown'?(error_class||'unknown'):detected);
30
+ const advice=ADVICE[category];
31
+ return {
32
+ status:'guidance_only',category,
33
+ confidence:detected!=='unknown'?'heuristic':'user_classified_or_unknown',
34
+ native_tool_family:tool_family,
35
+ retry_same_input:false,
36
+ retry_count,
37
+ escalation:retry_count>=2?'Stop identical retries; inspect the tool contract/state or request user guidance.':null,
38
+ next_step:advice.next_step,
39
+ safe_retry:advice.safe_retry,
40
+ requires_user_approval:category==='permission_denied',
41
+ automatic_execution:false,
42
+ raw_error_stored:false,
43
+ limitations:['A2A cannot intercept or modify native Antigravity tool calls','Error classifications are heuristics, not verified root causes']
44
+ };
45
+ }
@@ -0,0 +1,13 @@
1
+ import path from 'node:path';
2
+
3
+ // Advisory only: never probe shells, execute commands or modify IDE configuration.
4
+ export function nodeVersionManagerAdvisory(binary=process.execPath){
5
+ const normalized=typeof binary==='string'?path.normalize(binary).replaceAll('\\','/').toLowerCase():'';
6
+ const managed=/(?:^|\/)(?:\.nvm\/versions\/node\/[^/]+\/bin|\.fnm\/node-versions\/[^/]+\/installation\/bin|\.fnm\/[^/]+\/bin|\.volta\/(?:tools\/image\/node\/[^/]+\/bin|bin)|\.asdf\/(?:installs\/nodejs\/[^/]+\/bin|shims)|\.nodenv\/(?:versions\/[^/]+\/bin|shims))(?:\/node(?:\.exe)?)?$/.test(normalized);
7
+ return {
8
+ node_version_manager_path:managed,
9
+ path_advisory:managed
10
+ ? 'Node is under a shell-managed version manager. A desktop-launched Antigravity process may not inherit its PATH. Confirm node availability in the IDE environment; no configuration changes were made.'
11
+ : null
12
+ };
13
+ }
@@ -0,0 +1,24 @@
1
+ // Opt-in, non-executing advisor for Antigravity's native agent modes.
2
+ const ALLOWED=new Set(['/swarm','/teamwork','/boost','@subagent']);
3
+ const isArr=v=>Array.isArray(v)&&v.length<=30&&v.every(x=>typeof x==='string'&&x.length<=120);
4
+ export function adviseOrchestration(task={}){
5
+ if(!task||typeof task!=='object'||Array.isArray(task))throw new Error('Provide a task description object');
6
+ const work=task.workstreams??[];
7
+ if(!isArr(work))throw new Error('workstreams must be <=30 strings');
8
+ const listed=task.available_commands??[];
9
+ if(!isArr(listed)||listed.some(x=>!ALLOWED.has(x)))throw new Error('Invalid available_commands');
10
+ const tier=['free','pro','ultra','paid-other','unknown'].includes(task.tier)?task.tier:'unknown';
11
+ const supported=new Set(listed);
12
+ const paid=tier==='pro'||tier==='ultra'||tier==='paid-other';
13
+ const pro=tier==='pro'||tier==='ultra';
14
+ const can=x=>supported.has(x)&&(x==='@subagent'||paid&&(x!=='/swarm'||pro));
15
+ const ownership=['independent','shared','unknown'].includes(task.file_ownership)?task.file_ownership:'unknown';
16
+ const independent=work.length>=2&&task.dependencies==='low'&&ownership==='independent';
17
+ const long=Number.isInteger(task.milestones)&&task.milestones>=2&&task.long_horizon===true;
18
+ let suggested='single-agent',why='A single agent avoids parallel coordination overhead for uncertain or tightly coupled work';
19
+ if(long&&independent&&can('/teamwork')){suggested='/teamwork';why='Multiple milestones benefit from dedicated roles and independent audit gates'}
20
+ else if(independent&&can('/swarm')){suggested='/swarm';why='Independent workstreams can be divided among named workers and a verifier'}
21
+ else if(task.hard_reasoning===true&&can('/boost')){suggested='/boost';why='A hard tightly coupled problem may benefit from iterative challenger verification'}
22
+ else if(independent&&can('@subagent')){suggested='@subagent';why='Delegate one scoped workstream for focused help, keeping primary agent in control'}
23
+ return {status:'recommendation-only',recommended:suggested,rationale:why,task_summary:{workstreams:work.length,dependencies:task.dependencies||'unknown',file_ownership:ownership,milestones:Number.isInteger(task.milestones)?task.milestones:null},plan_tier:tier,explicit_capabilities:[...supported],user_approval_required:true,automatic_worker_launch:false,cautions:['File ownership and low coupling are user-declared, not independently verified','Do not launch multiple workers on overlapping files without a conflict-resolution plan','Every worker handoff requires named evidence before integration','Only commands explicitly reported available are considered','Free Tier does not imply paid /boost, /swarm or /teamwork access','Parallel workers can consume more tokens and quota than a single agent','MCP access may differ for Swarm workers; validate tools and permissions separately','A2A does not replace native Antigravity coordination or worker evidence gates']};
24
+ }