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.
Files changed (240) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +149 -0
  4. package/LICENSE +27 -0
  5. package/README.md +330 -3
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +145 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1474 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +114 -0
  25. package/config/modelCatalog.json +620 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +262 -0
  28. package/hooks/handlers/hookIo.mjs +255 -0
  29. package/hooks/handlers/hookIpcClient.mjs +83 -0
  30. package/hooks/handlers/post-tool-use.mjs +265 -0
  31. package/hooks/handlers/pre-model-switch.mjs +249 -0
  32. package/hooks/handlers/pre-tool-use.mjs +365 -0
  33. package/hooks/handlers/stop-gate.mjs +240 -0
  34. package/hooks/handlers/user-prompt-submit.mjs +143 -0
  35. package/hooks/hooks.json +81 -0
  36. package/hooks/post_invocation.mjs +13 -0
  37. package/hooks/post_tool_use.mjs +17 -0
  38. package/hooks/pre_invocation.mjs +14 -0
  39. package/hooks/pre_tool_use.mjs +97 -0
  40. package/hooks/register.js +687 -0
  41. package/hooks/session_start.mjs +14 -0
  42. package/hooks/stop.mjs +13 -0
  43. package/hooks.json +56 -0
  44. package/package.json +103 -4
  45. package/packages/antigravity/package.json +14 -0
  46. package/packages/antigravity/src/index.mjs +1 -0
  47. package/packages/claude-code/package.json +14 -0
  48. package/packages/claude-code/src/index.mjs +2 -0
  49. package/packages/core/package.json +14 -0
  50. package/packages/core/src/index.mjs +1 -0
  51. package/packages/engine-node/package.json +14 -0
  52. package/packages/engine-node/src/index.mjs +1 -0
  53. package/packages/mcp/package.json +17 -0
  54. package/packages/mcp/src/server.mjs +396 -0
  55. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  56. package/packages/pro/README-SIGNING.md +30 -0
  57. package/packages/pro/package.json +16 -0
  58. package/packages/pro/src/index.mjs +3 -0
  59. package/packages/pro/src/team_finops_pack.mjs +241 -0
  60. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  61. package/plugin.json +36 -0
  62. package/rules/AGENTS.md +10 -0
  63. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  64. package/sidecars/horizon-daemon/server.mjs +2002 -0
  65. package/sidecars/horizon-daemon/sidecar.json +19 -0
  66. package/skills/cost-radar/SKILL.md +21 -0
  67. package/skills/evolve/SKILL.md +21 -0
  68. package/skills/handoff/SKILL.md +42 -0
  69. package/skills/horizon/SKILL.md +17 -0
  70. package/skills/inspect/SKILL.md +18 -0
  71. package/skills/precheck/SKILL.md +44 -0
  72. package/src/adapters/antigravity/index.mjs +79 -0
  73. package/src/adapters/claude-code/index.mjs +155 -0
  74. package/src/cli/cost_radar.mjs +70 -0
  75. package/src/cli/doctor.mjs +351 -0
  76. package/src/cli/horizon_hud.mjs +686 -0
  77. package/src/cli/init.mjs +425 -0
  78. package/src/cli/postmortem.mjs +515 -0
  79. package/src/coach/cacheGravityRouter.mjs +12 -0
  80. package/src/config/modelCatalog.json +620 -0
  81. package/src/config/platformQuirks.json +19 -0
  82. package/src/core/action_queue.mjs +264 -0
  83. package/src/core/ag_bridge.mjs +346 -0
  84. package/src/core/atomic_io.mjs +124 -0
  85. package/src/core/baseline.mjs +607 -0
  86. package/src/core/blindspot_sensors.mjs +399 -0
  87. package/src/core/classifier.mjs +1757 -0
  88. package/src/core/coach/circuit_breakers.mjs +650 -0
  89. package/src/core/coach/contradiction_auditor.mjs +239 -0
  90. package/src/core/coach/effort_advisor.mjs +143 -0
  91. package/src/core/coach/handoff_hydrator.mjs +483 -0
  92. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  93. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  94. package/src/core/coach/reflector_queue.mjs +505 -0
  95. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  96. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  97. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  98. package/src/core/coach/task_quota_router.mjs +955 -0
  99. package/src/core/coach/turn_zero_gate.mjs +574 -0
  100. package/src/core/compaction_coach.mjs +1126 -0
  101. package/src/core/config.mjs +214 -0
  102. package/src/core/constants.mjs +1800 -0
  103. package/src/core/detectors_det01_to_16.mjs +1474 -0
  104. package/src/core/episodic_memory.mjs +135 -0
  105. package/src/core/fts5_output_compressor.mjs +359 -0
  106. package/src/core/git_ledger.mjs +189 -0
  107. package/src/core/handoff_audit.mjs +558 -0
  108. package/src/core/history.mjs +221 -0
  109. package/src/core/hook_diagnostics.mjs +158 -0
  110. package/src/core/horizon_classifier.mjs +326 -0
  111. package/src/core/horizon_config.mjs +802 -0
  112. package/src/core/host_watchdog.mjs +200 -0
  113. package/src/core/layer5_hygiene.mjs +966 -0
  114. package/src/core/log_resolver.mjs +231 -0
  115. package/src/core/mcp_auditor.mjs +138 -0
  116. package/src/core/micro_skills_store.mjs +91 -0
  117. package/src/core/offenders.mjs +161 -0
  118. package/src/core/parser.mjs +1996 -0
  119. package/src/core/path_canonicalizer.mjs +73 -0
  120. package/src/core/paths.mjs +310 -0
  121. package/src/core/prefix_cache_shield.mjs +386 -0
  122. package/src/core/pro_license.mjs +385 -0
  123. package/src/core/prompt_rubric.mjs +518 -0
  124. package/src/core/pruner.mjs +433 -0
  125. package/src/core/quota.mjs +1860 -0
  126. package/src/core/rsi_instinct_engine.mjs +1197 -0
  127. package/src/core/sanitizer.mjs +121 -0
  128. package/src/core/session_forensics.mjs +303 -0
  129. package/src/core/session_timeline.mjs +358 -0
  130. package/src/core/settings.mjs +99 -0
  131. package/src/core/shared/detectors.mjs +1342 -0
  132. package/src/core/shared/fnv1a64.mjs +85 -0
  133. package/src/core/shared/handoff_schema.mjs +123 -0
  134. package/src/core/shared/index.mjs +5 -0
  135. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  136. package/src/core/shared/micro_skills.mjs +1 -0
  137. package/src/core/shared/plugin_validator.mjs +202 -0
  138. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  139. package/src/core/sidecar_store.mjs +302 -0
  140. package/src/core/sprint_metrics.mjs +366 -0
  141. package/src/core/sqlite_client.mjs +283 -0
  142. package/src/core/storage_doctor.mjs +358 -0
  143. package/src/core/subagents.mjs +609 -0
  144. package/src/core/swarm_topology.mjs +360 -0
  145. package/src/core/task_quota_router.mjs +1656 -0
  146. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  147. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  148. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  149. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  150. package/src/core/timeline_svg.mjs +236 -0
  151. package/src/core/tool_surgeon.mjs +305 -0
  152. package/src/core/trajectory_stitcher.mjs +645 -0
  153. package/src/core/u_shaped_optimizer.mjs +789 -0
  154. package/src/core/wal_hygiene.mjs +233 -0
  155. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  156. package/src/core-isomorphic/catalog/index.mjs +1 -0
  157. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
  158. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  159. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  160. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  161. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  162. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  163. package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
  164. package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
  165. package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
  166. package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
  167. package/src/core-isomorphic/control/callTree.mjs +338 -0
  168. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  169. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  170. package/src/core-isomorphic/control/index.mjs +49 -0
  171. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  172. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  173. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  174. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  175. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  176. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
  177. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  178. package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
  179. package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
  180. package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
  181. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  182. package/src/core-isomorphic/economics/index.mjs +47 -0
  183. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  184. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  185. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
  186. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
  187. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
  188. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
  189. package/src/core-isomorphic/index.js +26 -0
  190. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  191. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  192. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  193. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  194. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
  195. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  196. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  197. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  198. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
  199. package/src/core-isomorphic/ui/modViews.mjs +1478 -0
  200. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  201. package/src/core-isomorphic/ustf/index.mjs +7 -0
  202. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  203. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  204. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  205. package/src/demo/synthetic_states.mjs +661 -0
  206. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  207. package/src/diagnostics/doctorEngine.mjs +203 -0
  208. package/src/engine-node/db/index.mjs +58 -0
  209. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  210. package/src/engine-node/db/probe.mjs +110 -0
  211. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  212. package/src/engine-node/index.mjs +9 -0
  213. package/src/engine-node/ipc/client.mjs +447 -0
  214. package/src/engine-node/ipc/index.mjs +22 -0
  215. package/src/engine-node/ipc/protocol.mjs +177 -0
  216. package/src/engine-node/ipc/server.mjs +445 -0
  217. package/src/engine-node/offloader/index.mjs +6 -0
  218. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  219. package/src/engine-node/sensors/blindspots.mjs +369 -0
  220. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  221. package/src/engine-node/sensors/index.mjs +7 -0
  222. package/src/hooks/portfolio_runtime.mjs +858 -0
  223. package/src/hooks/post_invocation.mjs +419 -0
  224. package/src/hooks/pre_invocation.mjs +1015 -0
  225. package/src/hooks/session_start.mjs +161 -0
  226. package/src/shims/agy_cli_compressor.mjs +705 -0
  227. package/src/shims/agy_git_guard.mjs +749 -0
  228. package/src/shims/ah_log_query.mjs +39 -0
  229. package/src/ui/costRadarSvg.mjs +6 -0
  230. package/src/ui/horizonGrid.mjs +1 -0
  231. package/src/ui/horizonPanelHtml.mjs +1 -0
  232. package/src/ui/horizon_panel.css +167 -0
  233. package/src/ui/horizon_panel.js +212 -0
  234. package/src/ui/modViews.mjs +1 -0
  235. package/src/utils/nodeIo.mjs +59 -0
  236. package/src/utils/runtime.mjs +1 -0
  237. package/src/webview/advanced_view.html +1808 -0
  238. package/src/webview/horizon_panel.html +11389 -0
  239. package/src/webview/registry.mjs +80 -0
  240. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,110 @@
1
+ /**
2
+ * @file src/engine-node/db/probe.mjs
3
+ * Dynamic runtime probe for node:sqlite builtin module.
4
+ *
5
+ * Enables full read-only SQLite & FTS5 on Node >= 22.5, with automatic fallback
6
+ * to JSONL parsing on Node 20 LTS with zero --no-warnings flags.
7
+ */
8
+
9
+ let warningSuppressed = false;
10
+
11
+ /**
12
+ * Suppresses experimental SQLite warning from process.emitWarning.
13
+ * Allows Node >= 22.5 to load node:sqlite with 0 stderr noise and zero --no-warnings CLI flags.
14
+ */
15
+ export function suppressSqliteWarning({ force = false } = {}) {
16
+ if ((warningSuppressed && !force) || typeof process === 'undefined') return;
17
+ warningSuppressed = true;
18
+ if (typeof process.emitWarning === 'function') {
19
+ const orig = process.emitWarning.bind(process);
20
+ process.emitWarning = function (warning, ...args) {
21
+ const msg = typeof warning === 'string' ? warning : (warning && warning.message) || '';
22
+ const type = typeof args[0] === 'string' ? args[0] : (args[0] && args[0].type) || (warning && warning.name) || '';
23
+ if ((type === 'ExperimentalWarning' && /SQLite/i.test(msg)) || /SQLite is an experimental feature/i.test(msg)) {
24
+ return;
25
+ }
26
+ return orig(warning, ...args);
27
+ };
28
+ }
29
+ }
30
+
31
+ let probedModule = undefined;
32
+
33
+ /**
34
+ * Probes for built-in node:sqlite module via process.getBuiltinModule.
35
+ *
36
+ * @param {object} [options={}]
37
+ * @param {boolean} [options.forceFallback=false]
38
+ * @param {Function|null} [options.getBuiltinModuleOverride=null]
39
+ * @returns {object|null}
40
+ */
41
+ export function probeSqliteBuiltin({ forceFallback = false, getBuiltinModuleOverride = null } = {}) {
42
+ if (
43
+ forceFallback ||
44
+ (typeof process !== 'undefined' && process.env?.CTXTOP_FORCE_NO_SQLITE === '1')
45
+ ) {
46
+ return null;
47
+ }
48
+ if (probedModule !== undefined && !getBuiltinModuleOverride) return probedModule;
49
+
50
+ suppressSqliteWarning();
51
+
52
+ const getBuiltin = getBuiltinModuleOverride ||
53
+ (typeof process !== 'undefined' && typeof process.getBuiltinModule === 'function'
54
+ ? process.getBuiltinModule.bind(process)
55
+ : null);
56
+
57
+ if (!getBuiltin) {
58
+ if (!getBuiltinModuleOverride) probedModule = null;
59
+ return null;
60
+ }
61
+
62
+ try {
63
+ const mod = getBuiltin('node:sqlite');
64
+ if (mod && typeof mod.DatabaseSync === 'function') {
65
+ if (!getBuiltinModuleOverride) probedModule = mod;
66
+ return mod;
67
+ }
68
+ } catch {
69
+ // Fail-open: probe never throws
70
+ }
71
+
72
+ if (!getBuiltinModuleOverride) probedModule = null;
73
+ return null;
74
+ }
75
+
76
+ /**
77
+ * Returns true if built-in node:sqlite with DatabaseSync is available in this runtime.
78
+ *
79
+ * @param {object} [options={}]
80
+ * @returns {boolean}
81
+ */
82
+ export function isNodeSqliteAvailable(options = {}) {
83
+ return Boolean(probeSqliteBuiltin(options));
84
+ }
85
+
86
+ /**
87
+ * Returns the DatabaseSync constructor if available, or null.
88
+ *
89
+ * @param {object} [options={}]
90
+ * @returns {Function|null}
91
+ */
92
+ export function getDatabaseSyncClass(options = {}) {
93
+ const mod = probeSqliteBuiltin(options);
94
+ return mod?.DatabaseSync || null;
95
+ }
96
+
97
+ /**
98
+ * Resets probe cache for testing environments.
99
+ */
100
+ export function resetProbeCacheForTesting() {
101
+ probedModule = undefined;
102
+ }
103
+
104
+ export default {
105
+ suppressSqliteWarning,
106
+ probeSqliteBuiltin,
107
+ isNodeSqliteAvailable,
108
+ getDatabaseSyncClass,
109
+ resetProbeCacheForTesting
110
+ };
@@ -0,0 +1,122 @@
1
+ /**
2
+ * @file src/engine-node/db/sqlite_wrapper.mjs
3
+ * Read-only wrapper around node:sqlite DatabaseSync.
4
+ *
5
+ * Strictly enforces { readOnly: true } invariant and rejects any mutating SQL.
6
+ */
7
+
8
+ import path from 'node:path';
9
+ import { getDatabaseSyncClass } from './probe.mjs';
10
+
11
+ const MUTATION_SQL_RE = /^\s*(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|REPLACE|ATTACH|DETACH|VACUUM|REINDEX)\b/i;
12
+
13
+ export class SqliteDatabaseSyncWrapper {
14
+ /**
15
+ * @param {string} dbPath
16
+ * @param {object} options
17
+ * @param {boolean} options.readOnly - Must strictly be true
18
+ * @param {Function} [options.DatabaseSync] - Optional constructor override
19
+ */
20
+ constructor(dbPath, options = {}) {
21
+ if (!options || options.readOnly !== true) {
22
+ throw new Error('[Zero-Trust SQLite Guard] SqliteDatabaseSyncWrapper strictly requires { readOnly: true }');
23
+ }
24
+ if (!dbPath || typeof dbPath !== 'string') {
25
+ throw new TypeError('SqliteDatabaseSyncWrapper requires a non-empty dbPath string');
26
+ }
27
+
28
+ this.dbPath = (dbPath === ':memory:' || dbPath.startsWith('file:')) ? dbPath : path.resolve(dbPath);
29
+ this.readOnly = true;
30
+ this.isOpen = true;
31
+
32
+ const DbCtor = options.DatabaseSync || getDatabaseSyncClass(options);
33
+ if (!DbCtor) {
34
+ throw new Error('DatabaseSync constructor is unavailable in this runtime');
35
+ }
36
+
37
+ this.db = new DbCtor(this.dbPath, { readOnly: true, readonly: true });
38
+ try {
39
+ if (typeof this.db.exec === 'function') {
40
+ this.db.exec('PRAGMA busy_timeout = 3000;');
41
+ }
42
+ } catch {
43
+ // Ignore pragma rejection on immutable/locked handles
44
+ }
45
+ }
46
+
47
+ _assertNotMutating(sql) {
48
+ if (!sql || typeof sql !== 'string') return;
49
+ const stripped = sql
50
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
51
+ .replace(/--.*$/gm, ' ')
52
+ .trim();
53
+
54
+ const statements = stripped.split(';').map(s => s.trim()).filter(Boolean);
55
+ for (const stmt of statements) {
56
+ if (MUTATION_SQL_RE.test(stmt)) {
57
+ throw new Error(`[Zero-Trust SQLite Guard] Mutation query not permitted on read-only database: ${sql}`);
58
+ }
59
+ if (/^\s*WITH\b/i.test(stmt) && /\b(DELETE|INSERT|UPDATE|DROP|ALTER|REPLACE)\b/i.test(stmt)) {
60
+ throw new Error(`[Zero-Trust SQLite Guard] Mutation query not permitted on read-only database: ${sql}`);
61
+ }
62
+ }
63
+ }
64
+
65
+ get(sql, params = []) {
66
+ if (!this.isOpen) throw new Error('Database handle is closed');
67
+ this._assertNotMutating(sql);
68
+ const stmt = this.db.prepare(sql);
69
+ if (Array.isArray(params)) return stmt.get(...params);
70
+ if (params !== undefined && params !== null) return stmt.get(params);
71
+ return stmt.get();
72
+ }
73
+
74
+ all(sql, params = []) {
75
+ if (!this.isOpen) throw new Error('Database handle is closed');
76
+ this._assertNotMutating(sql);
77
+ const stmt = this.db.prepare(sql);
78
+ if (Array.isArray(params)) return stmt.all(...params);
79
+ if (params !== undefined && params !== null) return stmt.all(params);
80
+ return stmt.all();
81
+ }
82
+
83
+ searchFts(query, limit = 10, { table = null } = {}) {
84
+ if (!this.isOpen) throw new Error('Database handle is closed');
85
+ if (!query || typeof query !== 'string') return [];
86
+
87
+ let targetTable = table;
88
+ if (!targetTable) {
89
+ try {
90
+ const tables = this.all("SELECT name FROM sqlite_master WHERE type='table' AND sql LIKE '%fts5%'");
91
+ if (tables.length > 0) targetTable = tables[0].name;
92
+ } catch {
93
+ // Fall back to null
94
+ }
95
+ }
96
+
97
+ if (!targetTable) return [];
98
+
99
+ try {
100
+ const sanitized = query.replace(/['"*]/g, ' ').trim();
101
+ if (!sanitized) return [];
102
+ const sql = `SELECT *, snippet(${targetTable}, -1, '[', ']', '...', 16) AS snippet, bm25(${targetTable}) AS score ` +
103
+ `FROM ${targetTable} WHERE ${targetTable} MATCH ? ORDER BY score LIMIT ?`;
104
+ return this.all(sql, [sanitized, limit]);
105
+ } catch {
106
+ return [];
107
+ }
108
+ }
109
+
110
+ close() {
111
+ if (this.isOpen) {
112
+ this.isOpen = false;
113
+ try {
114
+ if (typeof this.db.close === 'function') this.db.close();
115
+ } catch {
116
+ // Safe close
117
+ }
118
+ }
119
+ }
120
+ }
121
+
122
+ export default SqliteDatabaseSyncWrapper;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @file src/engine-node/index.mjs
3
+ * Highbeam Node.js runtime engines barrel.
4
+ */
5
+
6
+ export * from './db/index.mjs';
7
+ export * from './sensors/index.mjs';
8
+ export * from './offloader/index.mjs';
9
+ export * from './ipc/index.mjs';
@@ -0,0 +1,447 @@
1
+ /**
2
+ * @file src/engine-node/ipc/client.mjs
3
+ * Highbeam Micro-IPC Client.
4
+ *
5
+ * Implements high-performance (<0.8ms SLA, p95 ~0.13ms) local IPC communication
6
+ * with persistent warm socket reuse, message demultiplexing, and 15ms failover
7
+ * to local in-process fallback execution when daemon is offline.
8
+ * Strictly 0 npm dependencies (uses only standard node:* built-ins).
9
+ */
10
+
11
+ import net from 'node:net';
12
+ import {
13
+ resolveIpcPath,
14
+ formatJsonRpcRequest,
15
+ JsonRpcStreamParser,
16
+ IPC_LIMITS
17
+ } from './protocol.mjs';
18
+
19
+ export class MicroIpcClient {
20
+ /**
21
+ * @param {object} [options]
22
+ * @param {string} [options.ipcPath]
23
+ * @param {number} [options.connectTimeoutMs=15]
24
+ * @param {number} [options.requestTimeoutMs=500]
25
+ * @param {boolean} [options.persistent=true]
26
+ */
27
+ constructor(options = {}) {
28
+ this.ipcPath = resolveIpcPath(options);
29
+ this.connectTimeoutMs = options.connectTimeoutMs ?? IPC_LIMITS.DEFAULT_CONNECT_TIMEOUT_MS;
30
+ this.requestTimeoutMs = options.requestTimeoutMs ?? IPC_LIMITS.DEFAULT_REQUEST_TIMEOUT_MS;
31
+ this.persistent = options.persistent ?? true;
32
+
33
+ // Warm socket management
34
+ this.activeSocket = null;
35
+ this.streamParser = null;
36
+ this.connectingPromise = null;
37
+
38
+ // In-flight pending requests: Map<reqId, { resolve, reject, timer, method }>
39
+ this.pendingRequests = new Map();
40
+ this.isClosed = false;
41
+ }
42
+
43
+ /**
44
+ * Returns the warm active socket if connected and writable, or initiates
45
+ * a new connection if none exists or the previous socket was closed.
46
+ *
47
+ * @param {number} connectTimeoutMs
48
+ * @returns {Promise<import('node:net').Socket>}
49
+ * @private
50
+ */
51
+ async _ensureConnected(connectTimeoutMs) {
52
+ if (this.isClosed) {
53
+ this.isClosed = false;
54
+ }
55
+
56
+ if (
57
+ this.activeSocket &&
58
+ !this.activeSocket.destroyed &&
59
+ !this.activeSocket.connecting &&
60
+ this.activeSocket.writable
61
+ ) {
62
+ return this.activeSocket;
63
+ }
64
+
65
+ if (this.connectingPromise) {
66
+ return this.connectingPromise;
67
+ }
68
+
69
+ this.connectingPromise = this._connect(connectTimeoutMs);
70
+ try {
71
+ return await this.connectingPromise;
72
+ } finally {
73
+ this.connectingPromise = null;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Establishes a new connection to the IPC socket / pipe.
79
+ *
80
+ * @param {number} connectTimeoutMs
81
+ * @returns {Promise<import('node:net').Socket>}
82
+ * @private
83
+ */
84
+ _connect(connectTimeoutMs) {
85
+ return new Promise((resolve, reject) => {
86
+ let settled = false;
87
+ let connectTimer = null;
88
+ let socket = null;
89
+
90
+ const cleanupTimer = () => {
91
+ if (connectTimer) {
92
+ clearTimeout(connectTimer);
93
+ connectTimer = null;
94
+ }
95
+ };
96
+
97
+ try {
98
+ socket = net.connect(this.ipcPath);
99
+ } catch (err) {
100
+ return reject(err);
101
+ }
102
+
103
+ // Fast connection timeout guard (default 15ms)
104
+ connectTimer = setTimeout(() => {
105
+ if (!settled) {
106
+ settled = true;
107
+ cleanupTimer();
108
+ try {
109
+ socket.destroy();
110
+ } catch (_err) {
111
+ void _err;
112
+ }
113
+ reject(new Error(`[MicroIPC] Connection timeout (${connectTimeoutMs}ms) to ${this.ipcPath}`));
114
+ }
115
+ }, connectTimeoutMs);
116
+
117
+ // Create stream parser attached to this socket
118
+ const parser = new JsonRpcStreamParser(
119
+ (msg) => this._onMessage(msg),
120
+ (parseErr) => this._onParseError(parseErr, socket)
121
+ );
122
+
123
+ socket.on('connect', () => {
124
+ if (settled) return;
125
+ settled = true;
126
+ cleanupTimer();
127
+
128
+ // Unref warm idle socket so it does not keep Node.js event loop alive unnecessarily
129
+ socket.unref();
130
+
131
+ this.activeSocket = socket;
132
+ this.streamParser = parser;
133
+ resolve(socket);
134
+ });
135
+
136
+ socket.on('data', (chunk) => {
137
+ parser.feed(chunk);
138
+ });
139
+
140
+ socket.on('error', (err) => {
141
+ if (!settled) {
142
+ settled = true;
143
+ cleanupTimer();
144
+ reject(err);
145
+ }
146
+ this._handleSocketError(socket, err);
147
+ });
148
+
149
+ socket.on('close', () => {
150
+ if (!settled) {
151
+ settled = true;
152
+ cleanupTimer();
153
+ reject(new Error('[MicroIPC] Socket closed during connection'));
154
+ }
155
+ this._handleSocketClose(socket);
156
+ });
157
+ });
158
+ }
159
+
160
+ /**
161
+ * Handles unexpected socket errors, cleans up active state, and rejects in-flight requests.
162
+ *
163
+ * @param {import('node:net').Socket} socket
164
+ * @param {Error} err
165
+ * @private
166
+ */
167
+ _handleSocketError(socket, err) {
168
+ if (this.activeSocket === socket) {
169
+ this.activeSocket = null;
170
+ this.streamParser = null;
171
+ }
172
+ const errorMsg = err?.message || 'Unknown socket error';
173
+ this._rejectAllPending(new Error(`[MicroIPC] Socket error: ${errorMsg}`));
174
+ }
175
+
176
+ /**
177
+ * Handles socket close / disconnect events, cleans up active state, and rejects in-flight requests.
178
+ *
179
+ * @param {import('node:net').Socket} socket
180
+ * @private
181
+ */
182
+ _handleSocketClose(socket) {
183
+ if (this.activeSocket === socket) {
184
+ this.activeSocket = null;
185
+ this.streamParser = null;
186
+ }
187
+ this._rejectAllPending(new Error('[MicroIPC] Socket closed before receiving response'));
188
+ }
189
+
190
+ /**
191
+ * Handles JSON-RPC stream parser errors (e.g. buffer overrun).
192
+ *
193
+ * @param {Error} parseErr
194
+ * @param {import('node:net').Socket} socket
195
+ * @private
196
+ */
197
+ _onParseError(parseErr, socket) {
198
+ if (this.activeSocket === socket) {
199
+ this.activeSocket = null;
200
+ this.streamParser = null;
201
+ try {
202
+ socket.destroy();
203
+ } catch (_err) {
204
+ void _err;
205
+ }
206
+ }
207
+ this._rejectAllPending(parseErr);
208
+ }
209
+
210
+ /**
211
+ * Rejects all currently pending in-flight requests with the given error.
212
+ *
213
+ * @param {Error} error
214
+ * @private
215
+ */
216
+ _rejectAllPending(error) {
217
+ const entries = Array.from(this.pendingRequests.entries());
218
+ this.pendingRequests.clear();
219
+ for (const [id, pending] of entries) {
220
+ if (pending.timer) {
221
+ clearTimeout(pending.timer);
222
+ pending.timer = null;
223
+ }
224
+ try {
225
+ pending.reject(error);
226
+ } catch (_err) {
227
+ void _err;
228
+ }
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Dispatches incoming parsed JSON-RPC responses to their matching pending request.
234
+ *
235
+ * @param {object} msg
236
+ * @private
237
+ */
238
+ _onMessage(msg) {
239
+ if (!msg || typeof msg !== 'object') return;
240
+ const id = msg.id;
241
+ if (id === null || id === undefined) return;
242
+
243
+ const pending = this.pendingRequests.get(id);
244
+ if (!pending) return;
245
+
246
+ this.pendingRequests.delete(id);
247
+ if (pending.timer) {
248
+ clearTimeout(pending.timer);
249
+ pending.timer = null;
250
+ }
251
+
252
+ if (msg.error) {
253
+ const errMsg = typeof msg.error === 'string'
254
+ ? msg.error
255
+ : (msg.error.message || 'JSON-RPC Error');
256
+ const err = new Error(errMsg);
257
+ if (typeof msg.error === 'object' && msg.error.code !== undefined) {
258
+ err.code = msg.error.code;
259
+ }
260
+ if (typeof msg.error === 'object' && msg.error.data !== undefined) {
261
+ err.data = msg.error.data;
262
+ }
263
+ pending.reject(err);
264
+ } else {
265
+ pending.resolve(msg.result);
266
+ }
267
+ }
268
+
269
+ /**
270
+ * Executes a remote JSON-RPC 2.0 method over the warm local IPC socket/pipe.
271
+ *
272
+ * @param {string} method
273
+ * @param {*} [params={}]
274
+ * @param {object} [options={}]
275
+ * @param {number} [options.connectTimeoutMs]
276
+ * @param {number} [options.requestTimeoutMs]
277
+ * @param {boolean} [options.persistent]
278
+ * @returns {Promise<*>} Result payload
279
+ */
280
+ async call(method, params = {}, options = {}) {
281
+ const connectTimeout = options.connectTimeoutMs ?? this.connectTimeoutMs;
282
+ const requestTimeout = options.requestTimeoutMs ?? this.requestTimeoutMs;
283
+ const isPersistent = options.persistent ?? this.persistent;
284
+ const id = Date.now() + Math.random().toString(36).slice(2, 8);
285
+
286
+ const socket = await this._ensureConnected(connectTimeout);
287
+
288
+ return new Promise((resolve, reject) => {
289
+ let requestTimer = null;
290
+
291
+ requestTimer = setTimeout(() => {
292
+ if (this.pendingRequests.has(id)) {
293
+ this.pendingRequests.delete(id);
294
+ // When a request times out, destroy the socket to cleanly cancel remote work
295
+ // and trigger server-side suspension cleanup without leaks.
296
+ if (this.activeSocket === socket) {
297
+ this.activeSocket = null;
298
+ this.streamParser = null;
299
+ try {
300
+ socket.destroy();
301
+ } catch (_err) {
302
+ void _err;
303
+ }
304
+ }
305
+ reject(new Error(`[MicroIPC] Request timeout (${requestTimeout}ms) for method ${method}`));
306
+ }
307
+ }, requestTimeout);
308
+
309
+ this.pendingRequests.set(id, {
310
+ resolve: (result) => {
311
+ if (!isPersistent) {
312
+ this.close();
313
+ }
314
+ resolve(result);
315
+ },
316
+ reject: (err) => {
317
+ if (!isPersistent) {
318
+ this.close();
319
+ }
320
+ reject(err);
321
+ },
322
+ timer: requestTimer,
323
+ method
324
+ });
325
+
326
+ try {
327
+ const payload = formatJsonRpcRequest(method, params, id);
328
+ socket.write(payload, (writeErr) => {
329
+ if (writeErr) {
330
+ if (this.pendingRequests.has(id)) {
331
+ this.pendingRequests.delete(id);
332
+ if (requestTimer) {
333
+ clearTimeout(requestTimer);
334
+ requestTimer = null;
335
+ }
336
+ if (this.activeSocket === socket) {
337
+ this.activeSocket = null;
338
+ this.streamParser = null;
339
+ try {
340
+ socket.destroy();
341
+ } catch (_e) {
342
+ void _e;
343
+ }
344
+ }
345
+ reject(writeErr);
346
+ }
347
+ }
348
+ });
349
+ } catch (err) {
350
+ if (this.pendingRequests.has(id)) {
351
+ this.pendingRequests.delete(id);
352
+ if (requestTimer) {
353
+ clearTimeout(requestTimer);
354
+ requestTimer = null;
355
+ }
356
+ }
357
+ if (this.activeSocket === socket) {
358
+ this.activeSocket = null;
359
+ this.streamParser = null;
360
+ try {
361
+ socket.destroy();
362
+ } catch (_e) {
363
+ void _e;
364
+ }
365
+ }
366
+ reject(err);
367
+ }
368
+ });
369
+ }
370
+
371
+ /**
372
+ * Calls a remote method, seamlessly falling back to local evaluation if the IPC
373
+ * daemon is unreachable, delayed >15ms, or errors.
374
+ *
375
+ * @param {string} method
376
+ * @param {*} params
377
+ * @param {Function} fallbackFn
378
+ * @param {object} [options]
379
+ * @returns {Promise<{ source: 'ipc' | 'fallback', result: *, fallbackReason?: string }>}
380
+ */
381
+ async callWithFallback(method, params, fallbackFn, options = {}) {
382
+ try {
383
+ const result = await this.call(method, params, options);
384
+ return { source: 'ipc', result };
385
+ } catch (err) {
386
+ try {
387
+ const fallbackResult = await fallbackFn(params, err);
388
+ return {
389
+ source: 'fallback',
390
+ result: fallbackResult,
391
+ fallbackReason: err.message
392
+ };
393
+ } catch (fallbackErr) {
394
+ throw fallbackErr;
395
+ }
396
+ }
397
+ }
398
+
399
+ /**
400
+ * Pings the IPC daemon. Returns true if responsive within timeout, false otherwise.
401
+ * Defaults to this.requestTimeoutMs or 500ms instead of hardcoded 15ms.
402
+ *
403
+ * @param {number} [timeoutMs]
404
+ * @returns {Promise<boolean>}
405
+ */
406
+ async ping(timeoutMs = this.requestTimeoutMs ?? 500) {
407
+ const effectiveTimeout = timeoutMs ?? this.requestTimeoutMs ?? 500;
408
+ try {
409
+ await this.call('daemon.ping', {}, { connectTimeoutMs: effectiveTimeout, requestTimeoutMs: effectiveTimeout });
410
+ return true;
411
+ } catch (_err) {
412
+ return false;
413
+ }
414
+ }
415
+
416
+ /**
417
+ * Closes the active socket connection and cleans up pending requests.
418
+ *
419
+ * @returns {Promise<void>}
420
+ */
421
+ async close() {
422
+ if (this.isClosed) return;
423
+ this.isClosed = true;
424
+ const sock = this.activeSocket;
425
+ this.activeSocket = null;
426
+ this.streamParser = null;
427
+ this.connectingPromise = null;
428
+
429
+ if (sock && !sock.destroyed) {
430
+ try {
431
+ sock.end();
432
+ sock.destroy();
433
+ } catch (_err) {
434
+ void _err;
435
+ }
436
+ }
437
+
438
+ this._rejectAllPending(new Error('[MicroIPC] Client closed'));
439
+ }
440
+
441
+ /**
442
+ * Alias for close() for stream/socket lifecycle compatibility.
443
+ */
444
+ destroy() {
445
+ this.close();
446
+ }
447
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * @file src/engine-node/ipc/index.mjs
3
+ * Highbeam Micro-IPC Bridge Barrel.
4
+ */
5
+
6
+ export {
7
+ resolveIpcPath,
8
+ formatJsonRpcRequest,
9
+ formatJsonRpcResponse,
10
+ formatJsonRpcError,
11
+ JsonRpcStreamParser,
12
+ JSON_RPC_ERRORS,
13
+ IPC_LIMITS
14
+ } from './protocol.mjs';
15
+
16
+ export {
17
+ MicroIpcClient
18
+ } from './client.mjs';
19
+
20
+ export {
21
+ MicroIpcServer
22
+ } from './server.mjs';