@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,793 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import crypto from 'node:crypto';
5
+ import {fileURLToPath} from 'node:url';
6
+ import { Database } from './sqlite-compat.mjs';
7
+
8
+ export const sha256 = (v) => crypto.createHash('sha256').update(v).digest('hex');
9
+ // Opt-in diagnostics intentionally contain only stable error classes/codes, never paths,
10
+ // raw messages, credentials, or stdout (which would corrupt MCP JSON-RPC framing).
11
+ export function debugLog(scope,error){
12
+ if(process.env.A2A_DEBUG!=='1')return;
13
+ const label=String(scope).replace(/[^a-z0-9_-]/gi,'').slice(0,48);
14
+ const code=String(error?.code||error?.name||'unknown').replace(/[^a-z0-9_-]/gi,'').slice(0,48);
15
+ process.stderr.write('[A2A debug] '+label+': '+code+'\n');
16
+ }
17
+
18
+ // Bounded, descriptor-pinned metadata reader. Never follows a leaf symlink;
19
+ // checks user-owned parent components when reading trusted configuration.
20
+ export function readSafeBytesFile(filename,{maxBytes=128*1024,checkParentDir=false,requirePrivateMode=false}={}){
21
+ let fd=null;
22
+ try{
23
+ if(typeof filename!=='string'||!Number.isSafeInteger(maxBytes)||maxBytes<1)return {ok:false,reason:'invalid_path_or_limit'};
24
+ const target=path.resolve(filename);
25
+ if(checkParentDir){
26
+ const home=path.resolve(getHomeDir()),rel=path.relative(home,path.dirname(target));
27
+ if(rel==='..'||rel.startsWith('..'+path.sep)||path.isAbsolute(rel))return {ok:false,reason:'outside_home'};
28
+ let cursor=home;
29
+ for(const seg of rel.split(path.sep).filter(Boolean)){
30
+ cursor=path.join(cursor,seg);
31
+ const st=fs.lstatSync(cursor);
32
+ if(st.isSymbolicLink()||!st.isDirectory())return {ok:false,reason:'symlink_parent'};
33
+ }
34
+ }
35
+ const before=fs.lstatSync(target);
36
+ if(before.isSymbolicLink()||!before.isFile())return {ok:false,reason:'unsafe_type'};
37
+ if(before.size>maxBytes)return {ok:false,reason:'too_large'};
38
+ if(requirePrivateMode&&process.platform!=='win32'&&(before.mode&0o022)!==0)
39
+ return {ok:false,reason:'unsafe_mode'};
40
+ fd=fs.openSync(target,fs.constants.O_RDONLY|(fs.constants.O_NOFOLLOW||0));
41
+ const st=fs.fstatSync(fd);
42
+ if(!st.isFile()||st.size>maxBytes)return {ok:false,reason:'too_large_or_unsafe'};
43
+ if(st.dev!==before.dev||st.ino!==before.ino)return {ok:false,reason:'changed_during_read'};
44
+ if(requirePrivateMode&&process.platform!=='win32'&&(st.mode&0o022)!==0)
45
+ return {ok:false,reason:'unsafe_mode'};
46
+ // A same-user writer can grow a file after fstat. Never use unbounded
47
+ // readFileSync(fd): read at most maxBytes+1 even during concurrent writes.
48
+ const chunks=[];let total=0;
49
+ while(total<=maxBytes){
50
+ const chunk=Buffer.allocUnsafe(Math.min(64*1024,maxBytes+1-total));
51
+ const length=fs.readSync(fd,chunk,0,chunk.length,null);
52
+ if(length===0)break;
53
+ chunks.push(chunk.subarray(0,length));total+=length;
54
+ }
55
+ if(total>maxBytes)return {ok:false,reason:'too_large'};
56
+ const after=fs.fstatSync(fd);
57
+ if(after.size!==st.size||after.mtimeMs!==st.mtimeMs||after.ctimeMs!==st.ctimeMs)
58
+ return {ok:false,reason:'changed_during_read'};
59
+ return {ok:true,bytes:Buffer.concat(chunks,total)};
60
+ }catch(error){
61
+ return {ok:false,reason:error?.code==='ENOENT'?'missing':error?.code==='ELOOP'?'symlink':'unreadable'};
62
+ }finally{if(fd!==null)try{fs.closeSync(fd)}catch{}}
63
+ }
64
+ export function readSafeJsonFile(filename,options={}){
65
+ const read=readSafeBytesFile(filename,options);
66
+ if(!read.ok)return read;
67
+ try{
68
+ const value=JSON.parse(read.bytes.toString('utf8'));
69
+ if(!value||typeof value!=='object'||Array.isArray(value))
70
+ return {ok:false,reason:'invalid_json'};
71
+ return {ok:true,value,bytes:read.bytes};
72
+ }catch{return {ok:false,reason:'invalid_json'}}
73
+ }
74
+
75
+ export const MAX_INDEX_FILES = 9000;
76
+ export const MAX_SOURCE_BYTES = 160 * 1024;
77
+ const BLOCKED_PARTS = new Set(['.git','node_modules','vendor','.next','.nuxt','.svelte-kit','.turbo','.parcel-cache','.dart_tool','.gradle','target','dist','build','coverage','.venv','venv','__pycache__','.pytest_cache','.mypy_cache','.ruff_cache','.idea','.vscode','.verifykit','.a2a','.cache','.terraform','.pnpm-store','.gitlab','.ssh','.aws','.kube','.gnupg','.docker','.azure','.gcloud','.config','.gemini','.claude','.cursor']);
78
+ const SENSITIVE = /(^|\/)(\.env(?:\..*)?|\.npmrc|\.pypirc|\.netrc|id_rsa|id_ed25519|id_ecdsa|id_dsa|\.htpasswd|\.pgpass|\.my\.cnf|\.vault-token|\.git-credentials|.*service[-_]account.*\.json|.*\.jks|.*\.keystore|.*\.kdbx|.*\.pem|.*\.key|.*\.p12|.*\.pfx|secrets?(?:\..*)?|credentials?(?:\..*)?|.*\.sqlite(?:-wal|-shm)?|.*\.db|package-lock\.json|pnpm-lock\.yaml|yarn\.lock|bun\.lockb?|composer\.lock|Cargo\.lock|poetry\.lock|Gemfile\.lock|npm-shrinkwrap\.json)$/i;
79
+ const IGNORED_SUBPATHS = /(^|\/)storage\/logs(\/|$)/i;
80
+ export const isSafeRelative = (rel) => typeof rel === 'string' && rel.length > 0 && rel.length <= 500 && !rel.includes('\0') && !path.isAbsolute(rel) && !rel.split(/[\\/]/).some(p=>p==='..') && !rel.startsWith('~');
81
+ export const shouldIgnore = (rel) => {
82
+ const norm = String(rel || '').replaceAll('\\', '/');
83
+ return norm.split('/').some(p => BLOCKED_PARTS.has(p))
84
+ || SENSITIVE.test(norm)
85
+ || IGNORED_SUBPATHS.test(norm)
86
+ || /\.(?:min\.(?:js|css)|map|lock|tsbuildinfo|png|jpe?g|gif|webp|pdf|zip|tar|gz|mp4|mp3|woff2?|ttf|exe|dll|so|dylib)$/i.test(norm);
87
+ };
88
+ export function getHomeDir() {
89
+ if (process.env.HOME && process.env.HOME.trim()) return process.env.HOME;
90
+ if (process.env.USERPROFILE && process.env.USERPROFILE.trim()) return process.env.USERPROFILE;
91
+ return os.homedir();
92
+ }
93
+ export const dataDir = () => {
94
+ if (process.env.A2A_DATA_DIR || process.env.VERIFYKIT_DATA_DIR || process.env.PLUGIN_DATA) {
95
+ return path.resolve(process.env.A2A_DATA_DIR || process.env.VERIFYKIT_DATA_DIR || process.env.PLUGIN_DATA);
96
+ }
97
+ const home = getHomeDir();
98
+ const pluginData = path.join(home, '.gemini', 'antigravity', 'plugin_data', 'a2a');
99
+ if (fs.existsSync(pluginData)) return pluginData;
100
+ const a2aDir = path.join(home, '.config', 'a2a', 'data');
101
+ if (fs.existsSync(a2aDir)) return a2aDir;
102
+ const legacyDir = path.join(home, '.config', 'verifykit', 'data');
103
+ if (fs.existsSync(legacyDir)) return legacyDir;
104
+ return a2aDir;
105
+ };
106
+ export const allowlistPath = () => {
107
+ const home = getHomeDir();
108
+ const p = path.join(home, '.config', 'a2a', 'allowed-workspaces.json');
109
+ const legacy = path.join(home, '.config', 'verifykit', 'allowed-workspaces.json');
110
+ if (fs.existsSync(legacy) && !fs.existsSync(p)) return legacy;
111
+ return p;
112
+ };
113
+ export const settingsPath = () => {
114
+ const home = getHomeDir();
115
+ const p = path.join(home, '.config', 'a2a', 'settings.json');
116
+ const legacy = path.join(home, '.config', 'verifykit', 'settings.json');
117
+ if (fs.existsSync(p)) return p;
118
+ if (fs.existsSync(legacy)) return legacy;
119
+ return p;
120
+ };
121
+
122
+ function readSettings() {
123
+ const read=readSafeJsonFile(settingsPath(),{maxBytes:64*1024,checkParentDir:true});
124
+ if(!read.ok){if(read.reason!=='missing')debugLog('settings_read',read.reason);return {}}
125
+ return read.value;
126
+ }
127
+
128
+ function writeSettings(patch) {
129
+ const target = path.join(getHomeDir(), '.config', 'a2a', 'settings.json');
130
+ const parent = path.dirname(target);
131
+ fs.mkdirSync(parent, { recursive: true, mode: 0o700 });
132
+ const data = { ...readSettings(), ...patch, updatedAt: new Date().toISOString() };
133
+ // Atomic replacement, unlike O_TRUNC, keeps a complete previous settings
134
+ // file if a process is interrupted midway through a write.
135
+ const temp=target+'.'+process.pid+'.'+crypto.randomUUID()+'.tmp';
136
+ const flags=fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL|(fs.constants.O_NOFOLLOW||0);
137
+ let fd=null;
138
+ try{
139
+ fd=fs.openSync(temp,flags,0o600);
140
+ fs.writeFileSync(fd,JSON.stringify(data,null,2)+'\n');
141
+ fs.closeSync(fd);fd=null;
142
+ fs.renameSync(temp,target);
143
+ }finally{
144
+ if(fd!==null)fs.closeSync(fd);
145
+ try{fs.unlinkSync(temp)}catch{}
146
+ }
147
+ return data;
148
+ }
149
+
150
+ export function getVerifyKitMode() {
151
+ const data = readSettings();
152
+ if (data.mode === 'always-on' || data.mode === 'on-demand') return data.mode;
153
+ // Opt-in to proactive analysis; avoid extra model/tool turns for ordinary tasks.
154
+ return 'on-demand';
155
+ }
156
+ export const getA2AMode = getVerifyKitMode;
157
+
158
+ export function getCompactMode() {
159
+ const data = readSettings();
160
+ if (typeof data.compact === 'boolean') return data.compact;
161
+ if (data.compact === 'on' || data.compact === 'enabled' || data.compact === 'true') return true;
162
+ // New installs default to bounded responses. Explicit compact off is honored.
163
+ return true;
164
+ }
165
+
166
+ // Full-content Antigravity brain artifact retention is sensitive: default OFF.
167
+ // Manual snapshot_artifact calls remain explicit and unaffected.
168
+ export function getArtifactAutoSnapshotMode(){
169
+ return readSettings().artifact_auto_snapshot===true;
170
+ }
171
+ export function setArtifactAutoSnapshotMode(value){
172
+ if(value!==true&&value!==false&&value!=='on'&&value!=='off')throw new Error('Expected auto-snapshot on or off');
173
+ const enabled=value===true||value==='on';
174
+ writeSettings({artifact_auto_snapshot:enabled});
175
+ return enabled;
176
+ }
177
+
178
+ export function setCompactMode(val) {
179
+ let boolVal;
180
+ if (val === 'toggle') {
181
+ boolVal = !getCompactMode();
182
+ } else if (val === true || val === 'on' || val === 'enable' || val === 'enabled' || val === 'true') {
183
+ boolVal = true;
184
+ } else if (val === false || val === 'off' || val === 'disable' || val === 'disabled' || val === 'false') {
185
+ boolVal = false;
186
+ } else {
187
+ throw new Error('Invalid compact setting. Expected "on", "off", or "toggle"');
188
+ }
189
+ writeSettings({ compact: boolVal });
190
+ return boolVal;
191
+ }
192
+
193
+ export function setVerifyKitMode(mode) {
194
+ if (mode !== 'always-on' && mode !== 'on-demand') {
195
+ throw new Error('Invalid mode. Expected "always-on" or "on-demand"');
196
+ }
197
+ writeSettings({ mode });
198
+ return mode;
199
+ }
200
+ export const setA2AMode = setVerifyKitMode;
201
+
202
+ const VALID_AUTO_TRUST = new Set(['antigravity-trust', 'active-only', 'project-markers', 'off']);
203
+ export function getAutoTrustMode() {
204
+ const data = readSettings();
205
+ if (VALID_AUTO_TRUST.has(data.autoTrust)) return data.autoTrust;
206
+ return 'antigravity-trust';
207
+ }
208
+ export function setAutoTrustMode(mode) {
209
+ if (!VALID_AUTO_TRUST.has(mode)) {
210
+ throw new Error('Invalid autoTrust mode. Expected "antigravity-trust", "active-only", "project-markers", or "off"');
211
+ }
212
+ writeSettings({ autoTrust: mode });
213
+ invalidateWorkspaceCache();
214
+ return mode;
215
+ }
216
+
217
+ export const normalizeWorkspace = input => {
218
+ if (!input || typeof input !== 'string') throw new Error('workspace must be an absolute directory path');
219
+ const full = path.resolve(input);
220
+ if (!path.isAbsolute(input)) throw new Error('workspace must be an absolute directory path');
221
+ if (!fs.existsSync(full) || !fs.statSync(full).isDirectory()) throw new Error('workspace does not exist');
222
+ return fs.realpathSync(full);
223
+ };
224
+
225
+ export function realpathIfExists(p) {
226
+ try {
227
+ if (fs.existsSync(p)) return fs.realpathSync(p);
228
+ } catch {}
229
+ return path.resolve(p);
230
+ }
231
+
232
+ export function getProtectedRoots() {
233
+ const homeRaw = getHomeDir();
234
+ const home = realpathIfExists(homeRaw);
235
+ const tmpRaw = os.tmpdir();
236
+ const tmp = realpathIfExists(tmpRaw);
237
+ const candidates = [
238
+ path.parse(home).root,
239
+ home,
240
+ path.join(home, 'Documents'),
241
+ path.join(home, 'Downloads'),
242
+ path.join(home, 'Desktop'),
243
+ path.join(home, 'Music'),
244
+ path.join(home, 'Pictures'),
245
+ path.join(home, 'Videos'),
246
+ path.join(home, '.config'),
247
+ path.join(home, '.gemini'),
248
+ path.join(home, '.gemini', 'config'),
249
+ path.join(home, '.gemini', 'antigravity'),
250
+ path.join(home, '.ssh'),
251
+ path.join(home, '.aws'),
252
+ path.join(home, '.gnupg'),
253
+ path.resolve(tmpRaw),
254
+ tmp,
255
+ ];
256
+ const roots = new Set();
257
+ for (const c of candidates) {
258
+ roots.add(path.resolve(c));
259
+ roots.add(realpathIfExists(c));
260
+ }
261
+ return roots;
262
+ }
263
+
264
+ export function isProtectedRoot(ws) {
265
+ if (!ws || typeof ws !== 'string') return true;
266
+ const canonical = realpathIfExists(ws);
267
+ const home = realpathIfExists(getHomeDir());
268
+ if (canonical === path.parse(canonical).root) return true;
269
+ if (process.platform === 'win32') {
270
+ const cLower = canonical.toLowerCase();
271
+ const hLower = home.toLowerCase();
272
+ if (cLower === path.parse(cLower).root.toLowerCase()) return true;
273
+ if (cLower === hLower || hLower.startsWith(cLower.endsWith(path.sep) ? cLower : cLower + path.sep)) return true;
274
+ } else {
275
+ if (canonical === home || home.startsWith(canonical.endsWith(path.sep) ? canonical : canonical + path.sep)) return true;
276
+ }
277
+ // Deny descendants of credential/application state directories, not just
278
+ // the directory itself. Ordinary projects in Documents remain permitted.
279
+ for (const sensitive of ['.ssh','.aws','.gnupg','.config','.gemini','.docker','.azure','.gcloud']) {
280
+ const target=realpathIfExists(path.join(home,sensitive));
281
+ if (isSameOrDescendantPath(target,canonical)) return true;
282
+ }
283
+ const protRoots = getProtectedRoots();
284
+ if (protRoots.has(canonical)) return true;
285
+ if (process.platform === 'win32' || process.platform === 'darwin') {
286
+ const cLower = canonical.toLowerCase();
287
+ for (const pr of protRoots) {
288
+ if (pr.toLowerCase() === cLower) return true;
289
+ }
290
+ }
291
+ return false;
292
+ }
293
+
294
+ const PROJECT_MARKERS = [
295
+ '.git', 'package.json', 'composer.json', 'pyproject.toml', 'go.mod', 'Cargo.toml',
296
+ 'pubspec.yaml', 'pom.xml', 'build.gradle', 'build.gradle.kts', 'Package.swift',
297
+ 'project.godot', 'CMakeLists.txt', 'Makefile'
298
+ ];
299
+
300
+ function hasProjectMarker(dir) {
301
+ try {
302
+ for (const m of PROJECT_MARKERS) {
303
+ if (fs.existsSync(path.join(dir, m))) return true;
304
+ }
305
+ const entries = fs.readdirSync(dir);
306
+ return entries.some(e => /\.(?:sln|csproj)$/i.test(e));
307
+ } catch {
308
+ return false;
309
+ }
310
+ }
311
+
312
+ function parseJsonc(raw) {
313
+ try { return JSON.parse(raw); } catch {}
314
+ let out = '', i = 0, inStr = false, esc = false;
315
+ while (i < raw.length) {
316
+ const ch = raw[i];
317
+ if (inStr) {
318
+ out += ch;
319
+ if (esc) esc = false;
320
+ else if (ch === '\\') esc = true;
321
+ else if (ch === '"') inStr = false;
322
+ i++;
323
+ continue;
324
+ }
325
+ if (ch === '"') { inStr = true; out += ch; i++; continue; }
326
+ if (ch === '/' && raw[i + 1] === '/') {
327
+ while (i < raw.length && raw[i] !== '\n') i++;
328
+ continue;
329
+ }
330
+ if (ch === '/' && raw[i + 1] === '*') {
331
+ i += 2;
332
+ while (i < raw.length && !(raw[i] === '*' && raw[i + 1] === '/')) i++;
333
+ i += 2;
334
+ continue;
335
+ }
336
+ out += ch;
337
+ i++;
338
+ }
339
+ out = out.replace(/,\s*([}\]])/g, '$1');
340
+ return JSON.parse(out);
341
+ }
342
+
343
+ function extractWorkspaceFolderPaths(wsFilePath) {
344
+ const results = [];
345
+ try {
346
+ const bytes=readSafeBytesFile(wsFilePath,{maxBytes:128*1024});
347
+ if(!bytes.ok)return results;
348
+ const data = parseJsonc(bytes.bytes.toString('utf8'));
349
+ const folders = Array.isArray(data?.folders) ? data.folders : [];
350
+ const baseDir = path.dirname(wsFilePath);
351
+ for (const f of folders) {
352
+ if (!f || typeof f !== 'object') continue;
353
+ if (typeof f.uri === 'string' && f.uri.startsWith('file://')) {
354
+ try { results.push(fileURLToPath(f.uri)); } catch {}
355
+ } else if (typeof f.path === 'string' && f.path.trim()) {
356
+ results.push(path.resolve(baseDir, f.path));
357
+ }
358
+ }
359
+ } catch {}
360
+ return results;
361
+ }
362
+
363
+ const WORKSPACE_CACHE_TTL_MS = 10_000;
364
+ let workspaceCache = null;
365
+
366
+ export function invalidateWorkspaceCache() {
367
+ workspaceCache = null;
368
+ }
369
+
370
+ export function loadAntigravityWorkspaces({ bypassCache = false } = {}) {
371
+ const autoTrust = getAutoTrustMode();
372
+ if (autoTrust === 'off') return [];
373
+
374
+ const home = getHomeDir();
375
+ // The active SessionStart record is a cache input in active-only mode.
376
+ // A workspace switch must invalidate permissions without waiting for TTL.
377
+ let activeVersion='';
378
+ if(autoTrust==='active-only'){
379
+ try{
380
+ const stat=fs.lstatSync(path.join(dataDir(),'active-session.json'));
381
+ activeVersion=stat.isFile()&&!stat.isSymbolicLink()?`${stat.mtimeMs}:${stat.size}`:'unsafe';
382
+ }catch{activeVersion='missing'}
383
+ }
384
+ const cacheKey = `${home}|${autoTrust}|${settingsPath()}|${activeVersion}`;
385
+ const now = Date.now();
386
+ if (!bypassCache && workspaceCache && workspaceCache.key === cacheKey && (now - workspaceCache.ts) < WORKSPACE_CACHE_TTL_MS) {
387
+ return workspaceCache.dirs;
388
+ }
389
+
390
+ const dirs = new Set();
391
+ const visitedWorkspaces=new Set();
392
+ const addPath = (rawPath, { requireMarker = true, depth = 0 } = {}) => {
393
+ if(depth>1)return;
394
+ if (!rawPath || typeof rawPath !== 'string') return;
395
+ if (rawPath.endsWith('.code-workspace') || path.basename(rawPath) === 'workspace.json') {
396
+ const absolute=path.resolve(rawPath);
397
+ if(visitedWorkspaces.has(absolute))return;
398
+ visitedWorkspaces.add(absolute);
399
+ for(const folder of extractWorkspaceFolderPaths(absolute)){
400
+ addPath(folder,{requireMarker,depth:depth+1});
401
+ }
402
+ return;
403
+ }
404
+ try {
405
+ if (!fs.existsSync(rawPath) || !fs.statSync(rawPath).isDirectory()) return;
406
+ const real = fs.realpathSync(rawPath);
407
+ if (isProtectedRoot(real)) return;
408
+ if (requireMarker && !hasProjectMarker(real)) return;
409
+ dirs.add(real);
410
+ } catch {}
411
+ };
412
+
413
+ // 1. Antigravity IDE built-in Workspace Trust (globalStorage/state.vscdb -> content.trust.model.key)
414
+ try {
415
+ const stateCandidates = [
416
+ path.join(home, '.config', 'Antigravity IDE', 'User', 'globalStorage', 'state.vscdb'),
417
+ path.join(home, 'Library', 'Application Support', 'Antigravity IDE', 'User', 'globalStorage', 'state.vscdb'),
418
+ ...(process.env.APPDATA ? [path.join(process.env.APPDATA, 'Antigravity IDE', 'User', 'globalStorage', 'state.vscdb')] : []),
419
+ ];
420
+ for (const dbFile of stateCandidates) {
421
+ // SQLite takes a pathname, so conservatively refuse symlinked/oversized
422
+ // trust stores and user-controlled symlinked parent directories.
423
+ let safeDb=false;
424
+ try{
425
+ const leaf=fs.lstatSync(dbFile);
426
+ if(leaf.isFile()&&!leaf.isSymbolicLink()&&leaf.size<=64*1024*1024){
427
+ const rel=path.relative(path.resolve(home),path.dirname(path.resolve(dbFile)));
428
+ if(rel!=='.'&&rel!==''&&(rel==='..'||rel.startsWith('..'+path.sep)||path.isAbsolute(rel)))continue;
429
+ let dir=path.resolve(home);safeDb=true;
430
+ for(const seg of rel.split(path.sep).filter(Boolean)){
431
+ dir=path.join(dir,seg);
432
+ const st=fs.lstatSync(dir);
433
+ if(!st.isDirectory()||st.isSymbolicLink()){safeDb=false;break}
434
+ }
435
+ }
436
+ }catch{}
437
+ if(!safeDb)continue;
438
+ let db;
439
+ try {
440
+ db = new Database(dbFile, { readOnly: true });
441
+ const row = db.prepare("SELECT value FROM ItemTable WHERE key='content.trust.model.key'").get();
442
+ if (row?.value) {
443
+ const parsed = JSON.parse(row.value);
444
+ const entries = Array.isArray(parsed?.uriTrustInfo) ? parsed.uriTrustInfo : [];
445
+ for (const entry of entries) {
446
+ if (!entry || entry.trusted !== true || !entry.uri) continue;
447
+ let raw = entry.uri.fsPath || entry.uri.path || null;
448
+ if (!raw && typeof entry.uri.external === 'string' && entry.uri.external.startsWith('file://')) {
449
+ try { raw = fileURLToPath(entry.uri.external); } catch {}
450
+ }
451
+ if (raw) addPath(raw, { requireMarker: false });
452
+ }
453
+ }
454
+ } catch(error) {debugLog('ide_trust_database',error)} finally {
455
+ try { db?.close(); } catch(error) {debugLog('ide_trust_close',error)}
456
+ }
457
+ }
458
+ } catch {}
459
+
460
+ // 2. Antigravity CLI & App settings.json (explicit trustedWorkspaces)
461
+ try {
462
+ for (const appDir of ['antigravity-cli', 'antigravity', 'antigravity-ide']) {
463
+ const cliSettings = path.join(home, '.gemini', appDir, 'settings.json');
464
+ const config=readSafeJsonFile(cliSettings,{maxBytes:128*1024,checkParentDir:true});
465
+ if(!config.ok)continue;
466
+ try {
467
+ const trusted = Array.isArray(config.value?.trustedWorkspaces) ? config.value.trustedWorkspaces : [];
468
+ for (const p of trusted) {
469
+ addPath(p, { requireMarker: false });
470
+ }
471
+ } catch {}
472
+ }
473
+ } catch {}
474
+
475
+ // Never grant workspace authorization from /proc command-line text.
476
+ // A separate, unrelated user process can spoof "agy --add-dir=<victim>"
477
+ // in its argv. Only IDE/CLI trust state, user allowlist, and narrowly
478
+ // reviewed project records are eligible authorization sources.
479
+
480
+ if (autoTrust === 'project-markers') {
481
+ // 4. ~/.gemini/config/projects/*.json (historical projects — require project marker)
482
+ try {
483
+ const projDir = path.join(home, '.gemini', 'config', 'projects');
484
+ if (fs.existsSync(projDir)) {
485
+ for (const f of fs.readdirSync(projDir)) {
486
+ if (!f.endsWith('.json')) continue;
487
+ try {
488
+ const read=readSafeJsonFile(path.join(projDir,f),{maxBytes:128*1024,checkParentDir:true});
489
+ if(!read.ok)continue;
490
+ const resources = read.value?.projectResources?.resources || [];
491
+ for (const res of resources) {
492
+ if (res.folderUri && typeof res.folderUri === 'string' && res.folderUri.startsWith('file://')) {
493
+ try {
494
+ addPath(fileURLToPath(res.folderUri), { requireMarker: true });
495
+ } catch {}
496
+ }
497
+ }
498
+ } catch {}
499
+ }
500
+ }
501
+ } catch {}
502
+
503
+ // 4. ~/.gemini/projects.json (historical projects — require project marker)
504
+ try {
505
+ const pJson = path.join(home, '.gemini', 'projects.json');
506
+ const read=readSafeJsonFile(pJson,{maxBytes:128*1024,checkParentDir:true});
507
+ if(read.ok){
508
+ const content=read.value;
509
+ if (content?.projects && typeof content.projects === 'object') {
510
+ for (const p of Object.keys(content.projects)) {
511
+ addPath(p, { requireMarker: true });
512
+ }
513
+ }
514
+ }
515
+ } catch {}
516
+
517
+ // 5. ~/.config/Antigravity IDE/User/workspaceStorage/*/workspace.json (historical IDE storage — require project marker)
518
+ try {
519
+ const wsStorage = path.join(home, '.config', 'Antigravity IDE', 'User', 'workspaceStorage');
520
+ if (fs.existsSync(wsStorage)) {
521
+ for (const d of fs.readdirSync(wsStorage)) {
522
+ const wsFile = path.join(wsStorage, d, 'workspace.json');
523
+ if (fs.existsSync(wsFile)) {
524
+ try {
525
+ const data = JSON.parse(fs.readFileSync(wsFile, 'utf8'));
526
+ const uri = data.folder || data.workspace;
527
+ if (uri && typeof uri === 'string' && uri.startsWith('file://')) {
528
+ try {
529
+ addPath(fileURLToPath(uri), { requireMarker: true });
530
+ } catch {}
531
+ }
532
+ } catch {}
533
+ }
534
+ }
535
+ }
536
+ } catch {}
537
+ }
538
+
539
+ if(autoTrust==='active-only'){
540
+ // Active-only is an intersection of two independent local records:
541
+ // (1) an explicitly trusted Antigravity workspace and
542
+ // (2) the last bounded SessionStart workspace. A hook record by itself
543
+ // can NEVER authorize a new workspace.
544
+ const active=[];
545
+ try{
546
+ const sessionFile=path.join(dataDir(),'active-session.json');
547
+ const metadata=readSafeJsonFile(sessionFile,{maxBytes:128*1024});
548
+ if(metadata.ok){
549
+ const latest=metadata.value.latest;
550
+ const candidates=[...(Array.isArray(latest?.workspacePaths)?latest.workspacePaths.slice(0,32):[]),latest?.cwd];
551
+ for(const candidate of candidates){
552
+ if(typeof candidate!=='string'||!path.isAbsolute(candidate))continue;
553
+ const real=realpathIfExists(candidate);
554
+ if(!fs.existsSync(real)||!fs.statSync(real).isDirectory()||isProtectedRoot(real))continue;
555
+ if([...dirs].some(trusted=>isSameOrDescendantPath(trusted,real)))active.push(real);
556
+ }
557
+ }
558
+ }catch{}
559
+ dirs.clear();
560
+ for(const activeRoot of active)dirs.add(activeRoot);
561
+ }
562
+ const sorted = [...dirs].sort();
563
+ workspaceCache = { key: cacheKey, ts: now, dirs: sorted };
564
+ return sorted;
565
+ }
566
+
567
+ function readWorkspaceGrants(){
568
+ const file=allowlistPath();
569
+ try{
570
+ const read=readSafeJsonFile(file,{maxBytes:128*1024,checkParentDir:true});
571
+ if(!read.ok){
572
+ if(read.reason==='missing')return {allowed:[],revoked:[],valid:true};
573
+ throw Error('Unsafe workspace grants file');
574
+ }
575
+ const data=read.value;
576
+ if(!data||!Array.isArray(data.allowed)||!Array.isArray(data.revoked??[]))throw Error('Malformed workspace grants');
577
+ const validList=xs=>xs.every(x=>typeof x==='string'&&x.length<=1024&&path.isAbsolute(x));
578
+ const revoked=data.revoked??[];
579
+ if(!validList(data.allowed)||!validList(revoked))throw Error('Invalid workspace grants');
580
+ return {allowed:data.allowed,revoked,valid:true};
581
+ }catch(e){
582
+ if(e.code==='ENOENT')return {allowed:[],revoked:[],valid:true};
583
+ // A damaged grants file must never silently reactivate auto-trusted paths.
584
+ return {allowed:[],revoked:[],valid:false};
585
+ }
586
+ }
587
+ export function loadAllowlist(){return readWorkspaceGrants().allowed}
588
+ export function loadRevokedWorkspaces(){return readWorkspaceGrants().revoked}
589
+
590
+ // Normalize only documented macOS /private aliases (never arbitrary paths)
591
+ // and the default case-insensitive OS families before comparing boundaries.
592
+ function normalizedComparablePath(input){
593
+ let resolved=path.resolve(input);
594
+ if(process.platform==='darwin')
595
+ resolved=resolved.replace(/^\/private(?=\/(?:var|tmp|etc)(?:\/|$))/,'');
596
+ return process.platform==='win32'||process.platform==='darwin'?resolved.toLowerCase():resolved;
597
+ }
598
+ export function isSamePath(a,b){
599
+ return typeof a==='string'&&a.length>0&&typeof b==='string'&&b.length>0&&
600
+ normalizedComparablePath(a)===normalizedComparablePath(b);
601
+ }
602
+ export function isSameOrDescendantPath(parent, child) {
603
+ if(typeof parent!=='string'||!parent||typeof child!=='string'||!child)return false;
604
+ const p=normalizedComparablePath(parent),c=normalizedComparablePath(child);
605
+ return c===p||c.startsWith(p.endsWith(path.sep)?p:p+path.sep);
606
+ }
607
+
608
+ export function isWorkspaceAuthorized(ws){
609
+ if (isProtectedRoot(ws)) return false;
610
+ const canonical = realpathIfExists(ws);
611
+ const grants=readWorkspaceGrants();
612
+ if(!grants.valid)return false;
613
+ if(grants.revoked.some(p=>isSameOrDescendantPath(p,canonical)||isSameOrDescendantPath(p,ws)))return false;
614
+ const allowed = grants.allowed;
615
+ for (const a of allowed) {
616
+ if (isProtectedRoot(a)) continue;
617
+ if (isSameOrDescendantPath(a, canonical) || isSameOrDescendantPath(a, ws)) {
618
+ return true;
619
+ }
620
+ }
621
+ // Authorization is a security decision: bypass the UI discovery TTL so an
622
+ // IDE Workspace Trust revocation takes effect on the next A2A request.
623
+ const agWorkspaces = loadAntigravityWorkspaces({bypassCache:true});
624
+ for (const a of agWorkspaces) {
625
+ if (isProtectedRoot(a)) continue;
626
+ if (isSameOrDescendantPath(a, canonical) || isSameOrDescendantPath(a, ws)) {
627
+ return true;
628
+ }
629
+ }
630
+ return false;
631
+ }
632
+
633
+ export function requireAuthorizedWorkspace(input){
634
+ const ws=normalizeWorkspace(input);
635
+ if (isProtectedRoot(ws)) throw new Error('Protected workspace denied; select an ordinary trusted project');
636
+ if (!isWorkspaceAuthorized(ws)) throw new Error('Workspace is not authorized. Run: node scripts/a2a.mjs allow "'+ws+'" (local user approval).');
637
+ return ws;
638
+ }
639
+ function writeAllowlist(allowed,revoked=[]){
640
+ const target=path.join(getHomeDir(), '.config', 'a2a', 'allowed-workspaces.json');
641
+ const parent=path.dirname(target);fs.mkdirSync(parent,{recursive:true,mode:0o700});
642
+ // A replace prevents partial/truncated grant files on interruption and never
643
+ // follows a symlink at the target pathname.
644
+ const temp=target+'.'+process.pid+'.'+crypto.randomUUID()+'.tmp';
645
+ const flags=fs.constants.O_WRONLY|fs.constants.O_CREAT|fs.constants.O_EXCL|(fs.constants.O_NOFOLLOW||0);
646
+ let fd=null;
647
+ try{
648
+ fd=fs.openSync(temp,flags,0o600);
649
+ fs.writeFileSync(fd,JSON.stringify({version:1,allowed,revoked},null,2)+'\n');
650
+ fs.closeSync(fd);fd=null;
651
+ fs.renameSync(temp,target);
652
+ }finally{
653
+ if(fd!==null)fs.closeSync(fd);
654
+ try{fs.unlinkSync(temp)}catch{}
655
+ }
656
+ }
657
+ export function authorizeWorkspace(input) {
658
+ const ws=normalizeWorkspace(input);
659
+ if(isProtectedRoot(ws)) throw new Error('Refusing to authorize a protected root or system directory');
660
+ const current=readWorkspaceGrants();
661
+ if(!current.valid)throw new Error('Workspace grants file is invalid; repair it before allowing access');
662
+ const allowed=[...new Set([...current.allowed,ws])].sort();
663
+ const revoked=current.revoked.filter(x=>x!==ws);
664
+ writeAllowlist(allowed,revoked);
665
+ return ws;
666
+ }
667
+ export function revokeWorkspace(input){
668
+ const ws=normalizeWorkspace(input);
669
+ const current=readWorkspaceGrants();
670
+ if(!current.valid)throw new Error('Workspace grants file is invalid; cannot safely revoke access');
671
+ const allowed=current.allowed.filter(x=>x!==ws);
672
+ const revoked=[...new Set([...current.revoked,ws])].sort();
673
+ writeAllowlist(allowed,revoked);
674
+ return allowed;
675
+ }
676
+ export function safeFile(root,rel,{mustExist=true}={}) {
677
+ if (!isSafeRelative(rel) || shouldIgnore(rel)) throw new Error('Blocked unsafe or sensitive file path');
678
+ const full=path.resolve(root,rel);
679
+ if (full === root || !full.startsWith(root+path.sep)) throw new Error('Path escapes workspace');
680
+ if (mustExist){
681
+ const segments=path.relative(root,full).split(path.sep);let cursor=root;
682
+ for(const segment of segments){cursor=path.join(cursor,segment);const st=fs.lstatSync(cursor);if(st.isSymbolicLink()) throw new Error('Symlink access denied');}
683
+ if(!fs.statSync(full).isFile())throw new Error('Not a regular file');
684
+ }
685
+ return full;
686
+ }
687
+
688
+ export const MAX_ARTIFACT_BYTES = 500 * 1024;
689
+
690
+ export function safeArtifactPath(workspaceRoot, conversationId, targetPath, { mustExist = true } = {}) {
691
+ if (!targetPath || typeof targetPath !== 'string' || targetPath.includes('\0')) {
692
+ throw new Error('Invalid artifact path');
693
+ }
694
+ const resolved = path.resolve(targetPath);
695
+
696
+ let authorizedBoundary = null;
697
+ let trustedBrainArtifact=false;
698
+ if (workspaceRoot) {
699
+ try {
700
+ const authWs = requireAuthorizedWorkspace(workspaceRoot);
701
+ if (isSameOrDescendantPath(authWs, resolved) || isSameOrDescendantPath(workspaceRoot, resolved)) {
702
+ authorizedBoundary = authWs;
703
+ }
704
+ } catch {}
705
+ }
706
+ if (!authorizedBoundary && conversationId && /^[a-zA-Z0-9_\-.]{4,64}$/.test(conversationId)) {
707
+ const brainDir = path.resolve(getHomeDir(), '.gemini', 'antigravity', 'brain', conversationId);
708
+ // Only top-level Markdown artifacts can be read from a conversation brain.
709
+ // Never allow .system_generated or nested internal conversation content.
710
+ if (isSamePath(path.dirname(resolved),brainDir) && path.extname(resolved).toLowerCase()==='.md'
711
+ && !path.basename(resolved).startsWith('.')) {
712
+ // The special brain exception does not rely on workspace approval.
713
+ // Every directory segment below HOME must therefore be a real directory,
714
+ // never a symlink that redirects private reads elsewhere.
715
+ let safeBrain=true;
716
+ let segment=getHomeDir();
717
+ for (const part of ['.gemini','antigravity','brain',conversationId]) {
718
+ segment=path.join(segment,part);
719
+ try {
720
+ const st=fs.lstatSync(segment);
721
+ if(st.isSymbolicLink()||!st.isDirectory()){safeBrain=false;break}
722
+ } catch {safeBrain=false;break}
723
+ }
724
+ if (!safeBrain)throw new Error('Symlink access denied for brain artifact');
725
+ authorizedBoundary = brainDir;
726
+ trustedBrainArtifact=true;
727
+ }
728
+ }
729
+ // No global allowlist fallback: authorization is bound to the *requested* workspace.
730
+ // For hook-driven snapshots (no workspaceRoot), only the session's brain directory is valid.
731
+ if (!authorizedBoundary) {
732
+ throw new Error('Path escapes authorized workspace or brain boundary');
733
+ }
734
+
735
+ if (isProtectedRoot(resolved) && !trustedBrainArtifact) {
736
+ throw new Error('Access to protected root denied');
737
+ }
738
+
739
+ const base = path.basename(resolved);
740
+ const relativeInsideBoundary=trustedBrainArtifact?path.basename(resolved):path.relative(authorizedBoundary,resolved);
741
+ if (shouldIgnore(relativeInsideBoundary) || /(?:^\.env|\.pem$|\.key$|\.sqlite|\.git$)/i.test(base)) {
742
+ throw new Error('Access to sensitive file denied');
743
+ }
744
+
745
+ if (mustExist) {
746
+ if (!fs.existsSync(resolved)) {
747
+ throw new Error('Artifact file does not exist');
748
+ }
749
+
750
+ let boundaryForSegments = authorizedBoundary;
751
+ if (process.platform === 'darwin') {
752
+ if (resolved.startsWith('/private/') && !boundaryForSegments.startsWith('/private/')) {
753
+ boundaryForSegments = '/private' + boundaryForSegments;
754
+ } else if (!resolved.startsWith('/private/') && boundaryForSegments.startsWith('/private/')) {
755
+ boundaryForSegments = boundaryForSegments.slice('/private'.length);
756
+ }
757
+ }
758
+
759
+ const relFromBoundary = path.relative(boundaryForSegments, resolved);
760
+ const segments = relFromBoundary.split(path.sep);
761
+ let cursor = boundaryForSegments;
762
+ for (const seg of segments) {
763
+ if (!seg || seg === '.') continue;
764
+ cursor = path.join(cursor, seg);
765
+ const st = fs.lstatSync(cursor);
766
+ if (st.isSymbolicLink()) {
767
+ throw new Error('Symlink access denied');
768
+ }
769
+ }
770
+ const stat = fs.statSync(resolved);
771
+ if (!stat.isFile()) {
772
+ throw new Error('Not a regular file');
773
+ }
774
+ if (stat.size > MAX_ARTIFACT_BYTES) {
775
+ throw new Error(`Artifact file exceeds maximum allowed size (${MAX_ARTIFACT_BYTES / 1024} KB)`);
776
+ }
777
+ }
778
+
779
+ return resolved;
780
+ }
781
+ export function cleanError(error) {return String(error?.message||error).replace(/[\r\n\t]/g,' ').slice(0,400)}
782
+
783
+ /**
784
+ * The refresh RPC carries an Antigravity CSRF token. Never send it to a
785
+ * non-loopback endpoint supplied through process environment variables.
786
+ */
787
+ export function localAntigravityRpcUrl(address){
788
+ if(typeof address!=='string'||address.length>100)throw new Error('Invalid local language server address');
789
+ const match=/^(127\.0\.0\.1|localhost|\[::1\]):([0-9]{1,5})$/i.exec(address);
790
+ const port=match?Number(match[2]):0;
791
+ if(!match||port<1||port>65535)throw new Error('Language server must use a loopback host and valid port');
792
+ return 'http://'+match[1]+':'+port+'/exa.language_server_pb.LanguageServerService/RefreshMcpServers';
793
+ }