ctxtop 0.0.0-stage → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +149 -0
- package/LICENSE +27 -0
- package/README.md +330 -3
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +145 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1474 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +114 -0
- package/config/modelCatalog.json +620 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +262 -0
- package/hooks/handlers/hookIo.mjs +255 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-tool-use.mjs +265 -0
- package/hooks/handlers/pre-model-switch.mjs +249 -0
- package/hooks/handlers/pre-tool-use.mjs +365 -0
- package/hooks/handlers/stop-gate.mjs +240 -0
- package/hooks/handlers/user-prompt-submit.mjs +143 -0
- package/hooks/hooks.json +81 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +17 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +687 -0
- package/hooks/session_start.mjs +14 -0
- package/hooks/stop.mjs +13 -0
- package/hooks.json +56 -0
- package/package.json +103 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2002 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +42 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +79 -0
- package/src/adapters/claude-code/index.mjs +155 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +686 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +620 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1800 -0
- package/src/core/detectors_det01_to_16.mjs +1474 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +966 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1996 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +310 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
- package/src/core-isomorphic/index.js +26 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
- package/src/core-isomorphic/ui/modViews.mjs +1478 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/doctorEngine.mjs +203 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +110 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +9 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +369 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +419 -0
- package/src/hooks/pre_invocation.mjs +1015 -0
- package/src/hooks/session_start.mjs +161 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +11389 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { getDatabaseSyncClass } from '../engine-node/db/probe.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Pure-JS JSONL/JSON fallback database adapter for Node 20 LTS runtimes (where built-in
|
|
7
|
+
* `node:sqlite` is absent) or when `CTXTOP_FORCE_NO_SQLITE=1` is set.
|
|
8
|
+
* Supports `.exec()`, `.prepare().run()/.get()/.all()`, and `.close()` for plugin-owned
|
|
9
|
+
* Horizon databases (`tool_logs_fts5.db`, `episodic_memory.db`, `instincts.db`, etc.).
|
|
10
|
+
*/
|
|
11
|
+
export class JsonlFallbackDatabaseSync {
|
|
12
|
+
constructor(dbPath = ':memory:', options = {}) {
|
|
13
|
+
this.dbPath = dbPath;
|
|
14
|
+
this.readOnly = Boolean(options.readOnly || options.readonly);
|
|
15
|
+
this.isMemory = !dbPath || dbPath === ':memory:' || String(dbPath).startsWith('file:');
|
|
16
|
+
this.tables = {};
|
|
17
|
+
this._load();
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
_load() {
|
|
21
|
+
if (this.isMemory || !fs.existsSync(this.dbPath)) return;
|
|
22
|
+
try {
|
|
23
|
+
const raw = fs.readFileSync(this.dbPath, 'utf8').trim();
|
|
24
|
+
if (raw.startsWith('{')) {
|
|
25
|
+
const parsed = JSON.parse(raw);
|
|
26
|
+
if (parsed && typeof parsed.tables === 'object') {
|
|
27
|
+
this.tables = parsed.tables;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
} catch {
|
|
31
|
+
// Binary SQLite file or unreadable file in read-only fallback mode -> empty in-memory view
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
_flush() {
|
|
36
|
+
if (this.isMemory || this.readOnly) return;
|
|
37
|
+
try {
|
|
38
|
+
fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
|
|
39
|
+
fs.writeFileSync(this.dbPath, JSON.stringify({ fallbackFormat: 'json-v1', tables: this.tables }), 'utf8');
|
|
40
|
+
} catch {}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
exec(sql = '') {
|
|
44
|
+
const createMatches = String(sql || '').matchAll(
|
|
45
|
+
/CREATE\s+(?:VIRTUAL\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([A-Za-z0-9_]+)/gi
|
|
46
|
+
);
|
|
47
|
+
let mutated = false;
|
|
48
|
+
for (const m of createMatches) {
|
|
49
|
+
const tbl = m[1];
|
|
50
|
+
if (tbl && !Array.isArray(this.tables[tbl])) {
|
|
51
|
+
this.tables[tbl] = [];
|
|
52
|
+
mutated = true;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (mutated) this._flush();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
prepare(sql = '') {
|
|
59
|
+
const self = this;
|
|
60
|
+
const normSql = String(sql || '').replace(/\s+/g, ' ').trim();
|
|
61
|
+
|
|
62
|
+
return {
|
|
63
|
+
run(...args) {
|
|
64
|
+
if (self.readOnly) {
|
|
65
|
+
throw new Error('attempt to write a readonly database');
|
|
66
|
+
}
|
|
67
|
+
const insMatch = normSql.match(
|
|
68
|
+
/^INSERT\s+(?:OR\s+REPLACE\s+)?INTO\s+([A-Za-z0-9_]+)\s*(?:\(([^)]+)\))?\s*VALUES\s*\(([^)]+)\)/i
|
|
69
|
+
);
|
|
70
|
+
if (insMatch) {
|
|
71
|
+
const table = insMatch[1];
|
|
72
|
+
const cols = insMatch[2]
|
|
73
|
+
? insMatch[2].split(',').map((c) => c.trim())
|
|
74
|
+
: ['session_id', 'turn_id', 'command', 'exit_code', 'raw_output', 'created_at'];
|
|
75
|
+
if (!Array.isArray(self.tables[table])) self.tables[table] = [];
|
|
76
|
+
const row = {};
|
|
77
|
+
cols.forEach((c, idx) => {
|
|
78
|
+
row[c] = args[idx] ?? null;
|
|
79
|
+
});
|
|
80
|
+
const pkCol = cols[0];
|
|
81
|
+
if (/OR\s+REPLACE/i.test(normSql) && pkCol) {
|
|
82
|
+
self.tables[table] = self.tables[table].filter((r) => r[pkCol] !== row[pkCol]);
|
|
83
|
+
}
|
|
84
|
+
self.tables[table].push(row);
|
|
85
|
+
self._flush();
|
|
86
|
+
return { changes: 1, lastInsertRowid: self.tables[table].length };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const delMatch = normSql.match(
|
|
90
|
+
/^DELETE\s+FROM\s+([A-Za-z0-9_]+)(?:\s+WHERE\s+([A-Za-z0-9_]+)\s*=\s*\?)?/i
|
|
91
|
+
);
|
|
92
|
+
if (delMatch) {
|
|
93
|
+
const table = delMatch[1];
|
|
94
|
+
const whereCol = delMatch[2];
|
|
95
|
+
if (Array.isArray(self.tables[table])) {
|
|
96
|
+
const before = self.tables[table].length;
|
|
97
|
+
self.tables[table] = whereCol
|
|
98
|
+
? self.tables[table].filter((r) => r[whereCol] !== args[0])
|
|
99
|
+
: [];
|
|
100
|
+
self._flush();
|
|
101
|
+
return { changes: before - self.tables[table].length };
|
|
102
|
+
}
|
|
103
|
+
return { changes: 0 };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
self._flush();
|
|
107
|
+
return { changes: 1 };
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
get(...args) {
|
|
111
|
+
if (/^PRAGMA\s+journal_mode/i.test(normSql)) {
|
|
112
|
+
return { journal_mode: 'wal' };
|
|
113
|
+
}
|
|
114
|
+
if (/^PRAGMA\s+wal_checkpoint/i.test(normSql)) {
|
|
115
|
+
return { busy: 0, log: 0, checkpointed: 0 };
|
|
116
|
+
}
|
|
117
|
+
const rows = this.all(...args);
|
|
118
|
+
return rows[0] ?? undefined;
|
|
119
|
+
},
|
|
120
|
+
|
|
121
|
+
all(...args) {
|
|
122
|
+
if (/^PRAGMA\s+journal_mode/i.test(normSql)) {
|
|
123
|
+
return [{ journal_mode: 'wal' }];
|
|
124
|
+
}
|
|
125
|
+
if (/^PRAGMA\s+wal_checkpoint/i.test(normSql)) {
|
|
126
|
+
return [{ busy: 0, log: 0, checkpointed: 0 }];
|
|
127
|
+
}
|
|
128
|
+
const fromMatch = normSql.match(/\bFROM\s+([A-Za-z0-9_]+)/i);
|
|
129
|
+
if (!fromMatch) return [];
|
|
130
|
+
const table = fromMatch[1];
|
|
131
|
+
const sourceRows = Array.isArray(self.tables[table]) ? [...self.tables[table]] : [];
|
|
132
|
+
|
|
133
|
+
let filtered = sourceRows;
|
|
134
|
+
let argIdx = 0;
|
|
135
|
+
|
|
136
|
+
if (/\bWHERE\b/i.test(normSql)) {
|
|
137
|
+
const eqMatches = [...normSql.matchAll(/\b([A-Za-z0-9_]+)\s*=\s*\?/g)];
|
|
138
|
+
for (const m of eqMatches) {
|
|
139
|
+
const col = m[1];
|
|
140
|
+
const val = args[argIdx++];
|
|
141
|
+
filtered = filtered.filter((r) => String(r[col] ?? '') === String(val ?? ''));
|
|
142
|
+
}
|
|
143
|
+
if (/\bMATCH\s+\?/i.test(normSql)) {
|
|
144
|
+
const matchVal = String(args[argIdx++] || '');
|
|
145
|
+
const terms = matchVal
|
|
146
|
+
.replace(/\b(OR|AND)\b/gi, ' ')
|
|
147
|
+
.replace(/[^A-Za-z0-9_.\s-]/g, ' ')
|
|
148
|
+
.toLowerCase()
|
|
149
|
+
.split(/\s+/)
|
|
150
|
+
.filter(Boolean);
|
|
151
|
+
if (terms.length > 0) {
|
|
152
|
+
filtered = filtered.filter((r) => {
|
|
153
|
+
const hay = Object.values(r).join(' ').toLowerCase();
|
|
154
|
+
return terms.some((t) => hay.includes(t));
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (/SELECT\s+count\(\*\)\s+as\s+count/i.test(normSql)) {
|
|
161
|
+
const totalBytes = filtered.reduce(
|
|
162
|
+
(sum, r) => sum + Buffer.byteLength(String(r.raw_output || r.rawOutput || ''), 'utf8'),
|
|
163
|
+
0
|
|
164
|
+
);
|
|
165
|
+
return [{ count: filtered.length, totalBytes }];
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (/\bLIMIT\s+\?/i.test(normSql) && argIdx < args.length) {
|
|
169
|
+
const lim = Math.max(1, Number(args[argIdx++]) || 10);
|
|
170
|
+
filtered = filtered.slice(0, lim);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return filtered.map((r) => ({
|
|
174
|
+
...r,
|
|
175
|
+
...(r.session_id !== undefined && r.sessionId === undefined ? { sessionId: r.session_id } : {}),
|
|
176
|
+
...(r.workspace_path !== undefined && r.workspacePath === undefined ? { workspacePath: r.workspace_path } : {}),
|
|
177
|
+
...(r.modified_files !== undefined && r.modifiedFiles === undefined ? { modifiedFiles: r.modified_files } : {}),
|
|
178
|
+
...(r.turn_id !== undefined && r.turnId === undefined ? { turnId: r.turn_id } : {}),
|
|
179
|
+
...(r.exit_code !== undefined && r.exitCode === undefined ? { exitCode: r.exit_code } : {}),
|
|
180
|
+
...(r.raw_output !== undefined && r.rawOutput === undefined ? { rawOutput: r.raw_output } : {}),
|
|
181
|
+
...(r.created_at !== undefined && r.createdAt === undefined ? { createdAt: r.created_at } : {}),
|
|
182
|
+
rank: r.rank ?? 0.0
|
|
183
|
+
}));
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
close() {
|
|
189
|
+
this._flush();
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function resolveDatabaseSync(overrideCtor = null) {
|
|
194
|
+
if (overrideCtor) return overrideCtor;
|
|
195
|
+
const Ctor = getDatabaseSyncClass();
|
|
196
|
+
if (Ctor) return Ctor;
|
|
197
|
+
return JsonlFallbackDatabaseSync;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Returns true when `dbPath` points to a host-owned Antigravity or Cursor SQLite database
|
|
202
|
+
* (`conversations/*.db`, `conversation_summaries.db`, or `state.vscdb`), which MUST NEVER
|
|
203
|
+
* be opened in read-write mode (`AGENTS.md` Invariant 4).
|
|
204
|
+
*/
|
|
205
|
+
export function isHostProtectedSqlitePath(dbPath = '') {
|
|
206
|
+
let norm = String(dbPath || '').replace(/\\/g, '/').toLowerCase().trim();
|
|
207
|
+
if (!norm) return false;
|
|
208
|
+
norm = norm.replace(/\?.*$/, '');
|
|
209
|
+
norm = norm.replace(/^file:\/{0,3}/, '/');
|
|
210
|
+
const base = path.posix.basename(norm);
|
|
211
|
+
if (base === 'state.vscdb' || base.startsWith('state.vscdb.')) return true;
|
|
212
|
+
if (base === 'conversation_summaries.db' || base.startsWith('conversation_summaries.db.')) return true;
|
|
213
|
+
const isSqliteExt = /\.(db|sqlite|sqlite3|db3)(\.|$)/i.test(base);
|
|
214
|
+
if (norm.includes('/conversations/') && isSqliteExt) return true;
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Opens a plugin-owned Horizon SQLite database with strict WAL + `busy_timeout = 3000`
|
|
220
|
+
* (or `{ readOnly: true, readonly: true }` for read-only queries).
|
|
221
|
+
* Falls back cleanly to `JsonlFallbackDatabaseSync` on Node 20 LTS when `node:sqlite` is absent.
|
|
222
|
+
*/
|
|
223
|
+
export function openLocalHorizonDb(dbPath, { readOnly = false, readonly = false, busyTimeoutMs = 3000, DatabaseSync = null } = {}) {
|
|
224
|
+
if (!dbPath || typeof dbPath !== 'string') {
|
|
225
|
+
throw new TypeError('openLocalHorizonDb requires a non-empty dbPath string');
|
|
226
|
+
}
|
|
227
|
+
const isMemory = dbPath === ':memory:' || dbPath.startsWith('file:');
|
|
228
|
+
const resolvedPath = isMemory ? dbPath : path.resolve(dbPath);
|
|
229
|
+
const isReadOnly = readOnly === true || readonly === true;
|
|
230
|
+
|
|
231
|
+
if (!isReadOnly && isHostProtectedSqlitePath(resolvedPath)) {
|
|
232
|
+
throw new Error(
|
|
233
|
+
`[Zero-Trust SQLite Guard] Refusing read-write open on protected host database: ${resolvedPath}`
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const DbCtor = resolveDatabaseSync(DatabaseSync);
|
|
238
|
+
const timeoutVal = Math.max(100, Number(busyTimeoutMs) || 3000);
|
|
239
|
+
|
|
240
|
+
if (isReadOnly) {
|
|
241
|
+
const db = new DbCtor(resolvedPath, { readOnly: true, readonly: true });
|
|
242
|
+
try {
|
|
243
|
+
if (typeof db.exec === 'function') {
|
|
244
|
+
db.exec(`PRAGMA busy_timeout = ${timeoutVal};`);
|
|
245
|
+
}
|
|
246
|
+
} catch {
|
|
247
|
+
// Read-only handles on locked/immutable files may reject pragma mutations; ignore safely.
|
|
248
|
+
}
|
|
249
|
+
return db;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
fs.mkdirSync(path.dirname(resolvedPath), { recursive: true });
|
|
253
|
+
const db = new DbCtor(resolvedPath);
|
|
254
|
+
try {
|
|
255
|
+
if (typeof db.exec === 'function') {
|
|
256
|
+
db.exec(`
|
|
257
|
+
PRAGMA journal_mode = WAL;
|
|
258
|
+
PRAGMA synchronous = NORMAL;
|
|
259
|
+
PRAGMA busy_timeout = ${timeoutVal};
|
|
260
|
+
`);
|
|
261
|
+
}
|
|
262
|
+
return db;
|
|
263
|
+
} catch (err) {
|
|
264
|
+
try {
|
|
265
|
+
if (typeof db.close === 'function') db.close();
|
|
266
|
+
} catch {}
|
|
267
|
+
throw err;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Strictly opens host Antigravity / IDE SQLite databases with `{ readOnly: true, readonly: true }`.
|
|
273
|
+
*/
|
|
274
|
+
export function openHostReadOnlyDb(dbPath, options = {}) {
|
|
275
|
+
return openLocalHorizonDb(dbPath, { ...options, readOnly: true, readonly: true });
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export default {
|
|
279
|
+
JsonlFallbackDatabaseSync,
|
|
280
|
+
isHostProtectedSqlitePath,
|
|
281
|
+
openLocalHorizonDb,
|
|
282
|
+
openHostReadOnlyDb
|
|
283
|
+
};
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import {
|
|
5
|
+
isHostProtectedSqlitePath,
|
|
6
|
+
openLocalHorizonDb,
|
|
7
|
+
openHostReadOnlyDb
|
|
8
|
+
} from './sqlite_client.mjs';
|
|
9
|
+
|
|
10
|
+
const RETRYABLE_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);
|
|
11
|
+
|
|
12
|
+
function renameSqliteWithRetrySync(srcPath, dstPath, maxAttempts = 5) {
|
|
13
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
14
|
+
try {
|
|
15
|
+
fs.renameSync(srcPath, dstPath);
|
|
16
|
+
return;
|
|
17
|
+
} catch (err) {
|
|
18
|
+
if (RETRYABLE_RENAME_CODES.has(err?.code) && attempt < maxAttempts) {
|
|
19
|
+
try {
|
|
20
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 15 * attempt);
|
|
21
|
+
} catch {}
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
throw err;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Returns true strictly for plugin-owned `.agents/` SQLite databases (never host
|
|
31
|
+
* `state.vscdb`, `conversations/*.db`, or `conversation_summaries.db`).
|
|
32
|
+
*/
|
|
33
|
+
export function isPluginOwnedAgentsSqlitePath(dbPath = '') {
|
|
34
|
+
if (!dbPath || typeof dbPath !== 'string') return false;
|
|
35
|
+
if (isHostProtectedSqlitePath(dbPath)) return false;
|
|
36
|
+
const resolved = path.resolve(dbPath).replace(/\\/g, '/').toLowerCase();
|
|
37
|
+
return /(^|\/)\.agents(\/|$)/.test(resolved);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Local Storage Doctor — Read-only host orphan auditing, `.agents/` SQLite streaming GC,
|
|
42
|
+
* and Antigravity 2.6+ `brain/` recovery.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
export async function auditCursorVscdbOrphans(vscdbPath, options = {}) {
|
|
46
|
+
const breakdown = {
|
|
47
|
+
bubbleId: 0,
|
|
48
|
+
checkpointId: 0,
|
|
49
|
+
messageRequestContext: 0,
|
|
50
|
+
agentKv: 0
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
let rows = Array.isArray(options.mockRows) ? options.mockRows : null;
|
|
54
|
+
if (!rows && vscdbPath && fs.existsSync(vscdbPath)) {
|
|
55
|
+
let db = null;
|
|
56
|
+
try {
|
|
57
|
+
db = openHostReadOnlyDb(vscdbPath, { DatabaseSync: options.DatabaseSync });
|
|
58
|
+
rows = db.prepare('SELECT key, value FROM cursorDiskKV').all();
|
|
59
|
+
} catch {
|
|
60
|
+
rows = [];
|
|
61
|
+
} finally {
|
|
62
|
+
try { if (db && typeof db.close === 'function') db.close(); } catch {}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const list = rows || [];
|
|
67
|
+
const activeComposerIds = new Set();
|
|
68
|
+
const referencedBlobIds = new Set();
|
|
69
|
+
|
|
70
|
+
for (const r of list) {
|
|
71
|
+
const key = String(r.key || '');
|
|
72
|
+
const rawVal = typeof r.value === 'string'
|
|
73
|
+
? r.value
|
|
74
|
+
: (Buffer.isBuffer(r.value) ? r.value.toString('utf8') : String(r.value || ''));
|
|
75
|
+
|
|
76
|
+
if (key.startsWith('composerData:')) {
|
|
77
|
+
const cid = key.slice('composerData:'.length).trim();
|
|
78
|
+
if (cid) activeComposerIds.add(cid);
|
|
79
|
+
const blobMatches = rawVal.match(/agentKv:blob:[A-Za-z0-9_-]+/g) || [];
|
|
80
|
+
for (const bm of blobMatches) referencedBlobIds.add(bm);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// Second pass: collect blob references from live bubbles
|
|
85
|
+
for (const r of list) {
|
|
86
|
+
const key = String(r.key || '');
|
|
87
|
+
if (key.startsWith('bubbleId:')) {
|
|
88
|
+
const parts = key.split(':');
|
|
89
|
+
const cid = parts[1] || '';
|
|
90
|
+
if (activeComposerIds.has(cid)) {
|
|
91
|
+
const rawVal = typeof r.value === 'string'
|
|
92
|
+
? r.value
|
|
93
|
+
: (Buffer.isBuffer(r.value) ? r.value.toString('utf8') : String(r.value || ''));
|
|
94
|
+
const blobMatches = rawVal.match(/agentKv:blob:[A-Za-z0-9_-]+/g) || [];
|
|
95
|
+
for (const bm of blobMatches) referencedBlobIds.add(bm);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
let orphanRowCount = 0;
|
|
101
|
+
let orphanBytes = 0;
|
|
102
|
+
|
|
103
|
+
for (const r of list) {
|
|
104
|
+
const key = String(r.key || '');
|
|
105
|
+
const valBytes = Buffer.isBuffer(r.value)
|
|
106
|
+
? r.value.length
|
|
107
|
+
: Buffer.byteLength(String(r.value || ''), 'utf8');
|
|
108
|
+
const rowBytes = Buffer.byteLength(key, 'utf8') + valBytes;
|
|
109
|
+
|
|
110
|
+
let isOrphan = false;
|
|
111
|
+
if (key.startsWith('bubbleId:')) {
|
|
112
|
+
const cid = key.split(':')[1] || '';
|
|
113
|
+
if (!activeComposerIds.has(cid)) {
|
|
114
|
+
isOrphan = true;
|
|
115
|
+
breakdown.bubbleId += 1;
|
|
116
|
+
}
|
|
117
|
+
} else if (key.startsWith('checkpointId:')) {
|
|
118
|
+
const cid = key.split(':')[1] || '';
|
|
119
|
+
if (!activeComposerIds.has(cid)) {
|
|
120
|
+
isOrphan = true;
|
|
121
|
+
breakdown.checkpointId += 1;
|
|
122
|
+
}
|
|
123
|
+
} else if (key.startsWith('messageRequestContext:')) {
|
|
124
|
+
const cid = key.split(':')[1] || '';
|
|
125
|
+
if (!activeComposerIds.has(cid)) {
|
|
126
|
+
isOrphan = true;
|
|
127
|
+
breakdown.messageRequestContext += 1;
|
|
128
|
+
}
|
|
129
|
+
} else if (key.startsWith('agentKv:blob:')) {
|
|
130
|
+
if (!referencedBlobIds.has(key) && activeComposerIds.size > 0) {
|
|
131
|
+
isOrphan = true;
|
|
132
|
+
breakdown.agentKv += 1;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (isOrphan) {
|
|
137
|
+
orphanRowCount += 1;
|
|
138
|
+
orphanBytes += rowBytes;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return {
|
|
143
|
+
vscdbPath: vscdbPath || '',
|
|
144
|
+
totalRows: list.length,
|
|
145
|
+
activeComposerIds: Array.from(activeComposerIds),
|
|
146
|
+
referencedBlobIds: Array.from(referencedBlobIds),
|
|
147
|
+
orphanRowCount,
|
|
148
|
+
orphanBytes,
|
|
149
|
+
orphanBreakdown: breakdown
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function compactCursorVscdbStreaming(vscdbPath, options = {}) {
|
|
154
|
+
const dryRun = Boolean(options.dryRun);
|
|
155
|
+
const audit = await auditCursorVscdbOrphans(vscdbPath, options);
|
|
156
|
+
|
|
157
|
+
if (dryRun) {
|
|
158
|
+
return {
|
|
159
|
+
success: true,
|
|
160
|
+
dryRun: true,
|
|
161
|
+
exportedLiveRows: Math.max(0, audit.totalRows - audit.orphanRowCount),
|
|
162
|
+
removedOrphanRows: audit.orphanRowCount,
|
|
163
|
+
reclaimedBytes: audit.orphanBytes,
|
|
164
|
+
backupPath: null
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
if (!isPluginOwnedAgentsSqlitePath(vscdbPath)) {
|
|
169
|
+
return {
|
|
170
|
+
success: false,
|
|
171
|
+
dryRun: false,
|
|
172
|
+
blockedHostWrite: true,
|
|
173
|
+
reason: 'HOST_DB_READONLY_GUARD',
|
|
174
|
+
exportedLiveRows: 0,
|
|
175
|
+
removedOrphanRows: 0,
|
|
176
|
+
reclaimedBytes: 0,
|
|
177
|
+
backupPath: null,
|
|
178
|
+
error: 'Compaction is restricted strictly to plugin-owned .agents/ SQLite databases; host state.vscdb and session DBs are read-only.'
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const resolvedPath = path.resolve(vscdbPath);
|
|
183
|
+
if (!fs.existsSync(resolvedPath)) {
|
|
184
|
+
return {
|
|
185
|
+
success: false,
|
|
186
|
+
dryRun: false,
|
|
187
|
+
exportedLiveRows: 0,
|
|
188
|
+
removedOrphanRows: 0,
|
|
189
|
+
reclaimedBytes: 0,
|
|
190
|
+
backupPath: null,
|
|
191
|
+
error: 'vscdbPath does not exist'
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const activeSet = new Set(audit.activeComposerIds);
|
|
196
|
+
const referencedBlobSet = new Set(audit.referencedBlobIds || []);
|
|
197
|
+
const rand = Math.random().toString(36).slice(2, 8);
|
|
198
|
+
const tmpExportPath = `${resolvedPath}.compact.${process.pid}.${Date.now()}.${rand}.sqlite`;
|
|
199
|
+
|
|
200
|
+
let srcDb = null;
|
|
201
|
+
let dstDb = null;
|
|
202
|
+
let exportedLiveRows = 0;
|
|
203
|
+
|
|
204
|
+
try {
|
|
205
|
+
srcDb = openLocalHorizonDb(resolvedPath, {
|
|
206
|
+
readOnly: true,
|
|
207
|
+
DatabaseSync: options.DatabaseSync
|
|
208
|
+
});
|
|
209
|
+
dstDb = openLocalHorizonDb(tmpExportPath, {
|
|
210
|
+
readOnly: false,
|
|
211
|
+
DatabaseSync: options.DatabaseSync
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
dstDb.exec('CREATE TABLE IF NOT EXISTS ItemTable (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB);');
|
|
215
|
+
dstDb.exec('CREATE TABLE IF NOT EXISTS cursorDiskKV (key TEXT UNIQUE ON CONFLICT REPLACE, value BLOB);');
|
|
216
|
+
|
|
217
|
+
try {
|
|
218
|
+
const items = srcDb.prepare('SELECT key, value FROM ItemTable').all();
|
|
219
|
+
const insItem = dstDb.prepare('INSERT OR REPLACE INTO ItemTable (key, value) VALUES (?, ?)');
|
|
220
|
+
for (const it of items) {
|
|
221
|
+
insItem.run(it.key, it.value);
|
|
222
|
+
}
|
|
223
|
+
} catch {}
|
|
224
|
+
|
|
225
|
+
const kvRows = srcDb.prepare('SELECT key, value FROM cursorDiskKV').all();
|
|
226
|
+
const insKv = dstDb.prepare('INSERT OR REPLACE INTO cursorDiskKV (key, value) VALUES (?, ?)');
|
|
227
|
+
|
|
228
|
+
for (const r of kvRows) {
|
|
229
|
+
const key = String(r.key || '');
|
|
230
|
+
let isOrphan = false;
|
|
231
|
+
if (key.startsWith('bubbleId:') || key.startsWith('checkpointId:') || key.startsWith('messageRequestContext:')) {
|
|
232
|
+
const cid = key.split(':')[1] || '';
|
|
233
|
+
if (!activeSet.has(cid)) isOrphan = true;
|
|
234
|
+
} else if (key.startsWith('agentKv:blob:')) {
|
|
235
|
+
if (!referencedBlobSet.has(key) && activeSet.size > 0) isOrphan = true;
|
|
236
|
+
}
|
|
237
|
+
if (!isOrphan) {
|
|
238
|
+
insKv.run(r.key, r.value);
|
|
239
|
+
exportedLiveRows += 1;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
try {
|
|
244
|
+
dstDb.exec('PRAGMA wal_checkpoint(TRUNCATE); PRAGMA journal_mode = DELETE;');
|
|
245
|
+
} catch {}
|
|
246
|
+
} catch (err) {
|
|
247
|
+
try { if (srcDb) srcDb.close(); } catch {}
|
|
248
|
+
try { if (dstDb) dstDb.close(); } catch {}
|
|
249
|
+
srcDb = null;
|
|
250
|
+
dstDb = null;
|
|
251
|
+
for (const cleanupPath of [tmpExportPath, `${tmpExportPath}-wal`, `${tmpExportPath}-shm`]) {
|
|
252
|
+
try { if (fs.existsSync(cleanupPath)) fs.unlinkSync(cleanupPath); } catch {}
|
|
253
|
+
}
|
|
254
|
+
throw err;
|
|
255
|
+
} finally {
|
|
256
|
+
try { if (srcDb) srcDb.close(); } catch {}
|
|
257
|
+
try { if (dstDb) dstDb.close(); } catch {}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const backupPath = `${resolvedPath}.pre_gc.${Date.now()}.bak`;
|
|
261
|
+
fs.copyFileSync(resolvedPath, backupPath);
|
|
262
|
+
|
|
263
|
+
for (const sidecarPath of [`${tmpExportPath}-wal`, `${tmpExportPath}-shm`, `${resolvedPath}-wal`, `${resolvedPath}-shm`]) {
|
|
264
|
+
try {
|
|
265
|
+
if (fs.existsSync(sidecarPath)) fs.unlinkSync(sidecarPath);
|
|
266
|
+
} catch {}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
renameSqliteWithRetrySync(tmpExportPath, resolvedPath);
|
|
270
|
+
|
|
271
|
+
return {
|
|
272
|
+
success: true,
|
|
273
|
+
dryRun: false,
|
|
274
|
+
exportedLiveRows,
|
|
275
|
+
removedOrphanRows: audit.orphanRowCount,
|
|
276
|
+
reclaimedBytes: audit.orphanBytes,
|
|
277
|
+
backupPath
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
export function recoverAntigravityBrainMigration(homeDir = os.homedir(), options = {}) {
|
|
282
|
+
const dryRun = Boolean(options.dryRun);
|
|
283
|
+
const geminiRoot = path.join(homeDir, '.gemini');
|
|
284
|
+
const surfaces = ['antigravity', 'antigravity-cli', 'antigravity-ide'];
|
|
285
|
+
|
|
286
|
+
const dbSessionIds = new Set();
|
|
287
|
+
const brainDirsBySurface = new Map();
|
|
288
|
+
|
|
289
|
+
for (const surf of surfaces) {
|
|
290
|
+
const convDir = path.join(geminiRoot, surf, 'conversations');
|
|
291
|
+
if (fs.existsSync(convDir)) {
|
|
292
|
+
try {
|
|
293
|
+
for (const f of fs.readdirSync(convDir)) {
|
|
294
|
+
if (f.endsWith('.db')) {
|
|
295
|
+
dbSessionIds.add(path.basename(f, '.db'));
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
} catch {}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const brainDir = path.join(geminiRoot, surf, 'brain');
|
|
302
|
+
if (fs.existsSync(brainDir)) {
|
|
303
|
+
try {
|
|
304
|
+
for (const entry of fs.readdirSync(brainDir, { withFileTypes: true })) {
|
|
305
|
+
if (entry.isDirectory()) {
|
|
306
|
+
const full = path.join(brainDir, entry.name);
|
|
307
|
+
if (!brainDirsBySurface.has(entry.name)) brainDirsBySurface.set(entry.name, []);
|
|
308
|
+
brainDirsBySurface.get(entry.name).push({ surface: surf, dir: full });
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
} catch {}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
const recoveredLinks = [];
|
|
316
|
+
let orphanedBrainCount = 0;
|
|
317
|
+
|
|
318
|
+
for (const [sid, locations] of brainDirsBySurface.entries()) {
|
|
319
|
+
const primaryBrain = path.join(geminiRoot, 'antigravity', 'brain', sid);
|
|
320
|
+
const hasPrimaryTask = fs.existsSync(path.join(primaryBrain, 'task.md')) || fs.existsSync(path.join(primaryBrain, 'task.md.resolved'));
|
|
321
|
+
|
|
322
|
+
if (!hasPrimaryTask) {
|
|
323
|
+
const donor = locations.find(loc =>
|
|
324
|
+
fs.existsSync(path.join(loc.dir, 'task.md')) ||
|
|
325
|
+
fs.existsSync(path.join(loc.dir, 'task.md.resolved')) ||
|
|
326
|
+
fs.existsSync(path.join(loc.dir, '.system_generated', 'logs', 'transcript_full.jsonl'))
|
|
327
|
+
);
|
|
328
|
+
if (donor && donor.dir !== primaryBrain) {
|
|
329
|
+
orphanedBrainCount += 1;
|
|
330
|
+
const filesCopied = [];
|
|
331
|
+
const candidates = ['task.md', 'task.md.resolved', 'implementation_plan.md', 'walkthrough.md'];
|
|
332
|
+
for (const cFile of candidates) {
|
|
333
|
+
const srcFile = path.join(donor.dir, cFile);
|
|
334
|
+
const dstFile = path.join(primaryBrain, cFile);
|
|
335
|
+
if (fs.existsSync(srcFile) && !fs.existsSync(dstFile)) {
|
|
336
|
+
if (!dryRun) {
|
|
337
|
+
fs.mkdirSync(primaryBrain, { recursive: true });
|
|
338
|
+
fs.copyFileSync(srcFile, dstFile);
|
|
339
|
+
}
|
|
340
|
+
filesCopied.push(cFile);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
recoveredLinks.push({
|
|
344
|
+
sessionId: sid,
|
|
345
|
+
fromBrainDir: donor.dir,
|
|
346
|
+
toBrainDir: primaryBrain,
|
|
347
|
+
filesCopied
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
return {
|
|
354
|
+
scannedDbCount: dbSessionIds.size,
|
|
355
|
+
orphanedBrainCount,
|
|
356
|
+
recoveredLinks
|
|
357
|
+
};
|
|
358
|
+
}
|