synabun 2.4.3 → 2.4.4

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 (153) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +61 -32
  4. package/mcp-server/dist/http.d.ts.map +1 -1
  5. package/mcp-server/dist/http.js +8 -1
  6. package/mcp-server/dist/http.js.map +1 -1
  7. package/mcp-server/dist/services/identity.d.ts +2 -0
  8. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  9. package/mcp-server/dist/services/identity.js +4 -0
  10. package/mcp-server/dist/services/identity.js.map +1 -1
  11. package/mcp-server/dist/services/memory-client.d.ts +5 -0
  12. package/mcp-server/dist/services/memory-client.d.ts.map +1 -1
  13. package/mcp-server/dist/services/memory-client.js +21 -2
  14. package/mcp-server/dist/services/memory-client.js.map +1 -1
  15. package/mcp-server/dist/services/memory-writer.d.ts +3 -0
  16. package/mcp-server/dist/services/memory-writer.d.ts.map +1 -1
  17. package/mcp-server/dist/services/memory-writer.js +7 -1
  18. package/mcp-server/dist/services/memory-writer.js.map +1 -1
  19. package/mcp-server/dist/services/neural-interface.d.ts +11 -1
  20. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  21. package/mcp-server/dist/services/neural-interface.js +67 -17
  22. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  23. package/mcp-server/dist/services/typesafe-config.d.ts +38 -2
  24. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  25. package/mcp-server/dist/services/typesafe-config.js +260 -8
  26. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  27. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  28. package/mcp-server/dist/tools/agents.d.ts +3 -1
  29. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  30. package/mcp-server/dist/tools/agents.js +11 -6
  31. package/mcp-server/dist/tools/agents.js.map +1 -1
  32. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  33. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  34. package/mcp-server/dist/tools/browser-observe.js +113 -27
  35. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  36. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  37. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  38. package/mcp-server/dist/tools/browser-readers.js +17 -0
  39. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  40. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  41. package/mcp-server/dist/tools/remember.js +6 -2
  42. package/mcp-server/dist/tools/remember.js.map +1 -1
  43. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  44. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  45. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  46. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  47. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  48. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  49. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  50. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  51. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  52. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  53. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  54. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  55. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  56. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  57. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  58. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  59. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  60. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  61. package/mcp-server/package-lock.json +2 -2
  62. package/mcp-server/package.json +1 -1
  63. package/mcp-server/src/http.ts +8 -1
  64. package/mcp-server/src/services/identity.ts +5 -0
  65. package/mcp-server/src/services/memory-client.ts +32 -12
  66. package/mcp-server/src/services/memory-writer.ts +5 -2
  67. package/mcp-server/src/services/neural-interface.ts +65 -18
  68. package/mcp-server/src/services/typesafe-config.ts +268 -7
  69. package/mcp-server/src/tools/agents.ts +12 -6
  70. package/mcp-server/src/tools/browser-observe.ts +117 -28
  71. package/mcp-server/src/tools/browser-readers.ts +19 -0
  72. package/mcp-server/src/tools/remember.ts +6 -1
  73. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  74. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  75. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  76. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  77. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  78. package/neural-interface/i18n/en.json +139 -0
  79. package/neural-interface/i18n/pt-BR.json +139 -0
  80. package/neural-interface/lib/assistant-api.js +90 -0
  81. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  82. package/neural-interface/lib/assistant-dispatch.js +276 -42
  83. package/neural-interface/lib/assistant-memory.js +3 -1
  84. package/neural-interface/lib/assistant-persona.js +6 -0
  85. package/neural-interface/lib/assistant-router.js +18 -8
  86. package/neural-interface/lib/assistant-runtime.js +87 -1
  87. package/neural-interface/lib/assistant-task-prompt.js +15 -2
  88. package/neural-interface/lib/browser-connection-state.js +20 -0
  89. package/neural-interface/lib/browser-extension-adapter.js +221 -15
  90. package/neural-interface/lib/browser-extension-bridge.js +40 -7
  91. package/neural-interface/lib/browser-extension-folder.js +50 -11
  92. package/neural-interface/lib/browser-extension-package.js +6 -5
  93. package/neural-interface/lib/browser-extension-pin.json +15 -13
  94. package/neural-interface/lib/browser-extension-protocol.js +111 -13
  95. package/neural-interface/lib/browser-extension-setup.js +7 -5
  96. package/neural-interface/lib/browser-extension-update.js +104 -0
  97. package/neural-interface/lib/browser-extraction.js +38 -14
  98. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  99. package/neural-interface/lib/claude-history.js +12 -1
  100. package/neural-interface/lib/confined-fs.js +25 -0
  101. package/neural-interface/lib/coordination/operations.js +2 -0
  102. package/neural-interface/lib/db.js +39 -16
  103. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  104. package/neural-interface/lib/git-bash/manager.js +28 -3
  105. package/neural-interface/lib/git-status-runner.js +31 -3
  106. package/neural-interface/lib/loop-inventory.js +162 -0
  107. package/neural-interface/lib/loop-stall.js +74 -4
  108. package/neural-interface/lib/memory-session-capture.js +157 -66
  109. package/neural-interface/lib/native-loop-providers.js +73 -13
  110. package/neural-interface/lib/native-loop-runtime.js +3 -0
  111. package/neural-interface/lib/opencode-protocol.js +4 -2
  112. package/neural-interface/lib/peer-identity.js +62 -16
  113. package/neural-interface/lib/session-cache-builder.js +66 -18
  114. package/neural-interface/lib/session-capture-gate.js +42 -0
  115. package/neural-interface/lib/session-indexer.js +28 -20
  116. package/neural-interface/lib/teams/scheduler.js +3 -2
  117. package/neural-interface/lib/ui-blob-api.js +14 -5
  118. package/neural-interface/lib/ui-blob-store.js +302 -39
  119. package/neural-interface/package-lock.json +2 -2
  120. package/neural-interface/package.json +1 -1
  121. package/neural-interface/public/extension-setup.html +1 -0
  122. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  123. package/neural-interface/public/shared/assistant/asst-api.js +42 -0
  124. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  125. package/neural-interface/public/shared/assistant/asst-panel.js +285 -10
  126. package/neural-interface/public/shared/assistant/asst-render.js +205 -4
  127. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  128. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  129. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  130. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  131. package/neural-interface/public/shared/assistant/asst-styles.js +20 -0
  132. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  133. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  134. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  135. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  136. package/neural-interface/public/shared/browser-extension-updates.js +88 -0
  137. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  138. package/neural-interface/public/shared/extension-setup/es-page.js +18 -11
  139. package/neural-interface/public/shared/extension-update-view.js +34 -0
  140. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +8 -4
  141. package/neural-interface/public/shared/settings/settings-browser-extension.js +10 -4
  142. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  143. package/neural-interface/public/shared/styles.css +4 -0
  144. package/neural-interface/public/shared/ui-claude-panel.js +110 -1
  145. package/neural-interface/public/shared/ui-notifications.js +23 -4
  146. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  147. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  148. package/neural-interface/public/shared/worker-end.js +18 -0
  149. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  150. package/neural-interface/scripts/rebuild-pty.js +10 -0
  151. package/neural-interface/server.js +483 -280
  152. package/npm-shrinkwrap.json +2 -2
  153. package/package.json +1 -1
@@ -77,14 +77,27 @@ export function createGitStatusRunner({
77
77
  timeoutMs = 15000, debounceMs = 150, minIntervalMs = 2000, cacheMs = 30000, maxConcurrent = 2, maxRepos = 64,
78
78
  backoffMs = 30000, maxBackoffMs = 300000, uncoveredCacheMs = 2000, killGraceMs = 1500, taskkillMs = 1000,
79
79
  watch = true, watchFactory = createTreeWatcher, watchdog = spawnImpl === spawn, now = Date.now,
80
+ binaryResolver = null,
80
81
  } = {}) {
81
82
  const binaries = new Map();
83
+ let defaultBinaryResolver = typeof binaryResolver === 'function' ? binaryResolver : null;
82
84
  const entries = new Map(), monitors = createMonitorMemo(), queue = [], children = new Set();
83
85
  let active = 0, closed = false, guard = null, guardReady = null;
84
86
  const nullDevice = platform === 'win32' ? String.raw`\\.\nul` : devNull;
85
87
  const keyOf = root => platform === 'win32' ? root.toLowerCase() : root;
86
88
  const directKill = child => { if (children.has(child) && live(child)) try { child.kill('SIGKILL'); } catch { /* already gone */ } };
87
89
 
90
+ async function resolveBinary(binary) {
91
+ if (binary && binary !== 'git') return binary;
92
+ if (typeof defaultBinaryResolver === 'function') {
93
+ try {
94
+ const resolved = await defaultBinaryResolver();
95
+ if (resolved) return resolved;
96
+ } catch { /* fall back to 'git' */ }
97
+ }
98
+ return binary || 'git';
99
+ }
100
+
88
101
  function killTree(child, sync = false) {
89
102
  if (!children.has(child) || !live(child)) return Promise.resolve();
90
103
  if (platform !== 'win32') {
@@ -226,6 +239,7 @@ export function createGitStatusRunner({
226
239
  });
227
240
  }
228
241
  async function run(args, { cwd, binary = 'git', env = process.env, ...options } = {}) {
242
+ const resolvedBin = await resolveBinary(binary);
229
243
  const clean = { ...env };
230
244
  for (const name of REDIRECTING) delete clean[name];
231
245
  const safeEnv = gitReadEnv(clean);
@@ -233,11 +247,15 @@ export function createGitStatusRunner({
233
247
  if (readsIndex(args)) {
234
248
  monitor = monitors.get(cwd);
235
249
  if (monitor === undefined) {
236
- const probe = await execute(binary, ['--no-pager', '-c', `core.hooksPath=${nullDevice}`, 'config', '--type=bool', '--get', 'core.fsmonitor'], { ...options, timeoutMs: 3000, cwd, env: safeEnv });
250
+ const probe = await execute(resolvedBin, ['--no-pager', '-c', `core.hooksPath=${nullDevice}`, 'config', '--type=bool', '--get', 'core.fsmonitor'], { ...options, timeoutMs: 3000, cwd, env: safeEnv });
237
251
  monitor = monitors.set(cwd, probe.ok && String(probe.stdout).trim() === 'true');
238
252
  }
239
253
  }
240
- return execute(binary, gitReadArgs(args, { monitor, nullDevice }), { ...options, cwd, env: safeEnv });
254
+ return execute(resolvedBin, gitReadArgs(args, { monitor, nullDevice }), { ...options, cwd, env: safeEnv });
255
+ }
256
+ async function runRaw(args, options = {}) {
257
+ const resolvedBin = await resolveBinary(options.binary);
258
+ return execute(resolvedBin, args, { ...options, env: withGitFallback(options.env) });
241
259
  }
242
260
  function drop(key, entry) {
243
261
  entry.controller?.abort(); entry.watcher?.close(); entries.delete(key);
@@ -371,7 +389,17 @@ export function createGitStatusRunner({
371
389
  for (const child of children) void killTree(child, sync);
372
390
  if (guard?.connected) guard.disconnect();
373
391
  }
374
- return { read, run, runRaw: (args, options = {}) => execute(options.binary || 'git', args, { ...options, env: withGitFallback(options.env) }), ignored, invalidate, release, shutdown, stats: () => ({ active, queued: queue.length, children: children.size, repos: entries.size }) };
392
+ return {
393
+ read,
394
+ run,
395
+ runRaw,
396
+ setBinaryResolver: (fn) => { defaultBinaryResolver = typeof fn === 'function' ? fn : null; binaries.clear(); },
397
+ ignored,
398
+ invalidate,
399
+ release,
400
+ shutdown,
401
+ stats: () => ({ active, queued: queue.length, children: children.size, repos: entries.size }),
402
+ };
375
403
  }
376
404
 
377
405
  export function projectStatus(result, cwd, platform = process.platform) {
@@ -0,0 +1,162 @@
1
+ // ═══════════════════════════════════════════
2
+ // SynaBun Neural Interface — Async Loop Inventory Scanner
3
+ // ═══════════════════════════════════════════
4
+ // Scans LOOP_DIR (*.json) asynchronously using fs.promises and caches parsed
5
+ // loop files keyed by (mtimeMs, ctimeMs, ino, size) so unchanged files are
6
+ // neither re-read nor re-parsed on every periodic poll, while atomic
7
+ // same-name replacements with equal size and mtime still invalidate the cache.
8
+ // Dynamic fields (elapsedMinutes, stalledMinutes, stalledMs, terminalAlive,
9
+ // state) are recomputed live from the cached JSON on every scan.
10
+
11
+ import * as fsp from 'node:fs/promises';
12
+ import { resolve } from 'node:path';
13
+
14
+ export function isInventoryLoopFile(name) {
15
+ return typeof name === 'string'
16
+ && name.endsWith('.json')
17
+ && name !== '.gitkeep'
18
+ && !name.startsWith('pending-')
19
+ && name !== 'active-pointer.json';
20
+ }
21
+
22
+ /**
23
+ * Create an asynchronous, stat-identity-cached loop inventory scanner.
24
+ *
25
+ * @param {object} options
26
+ * @param {string | (() => string)} options.loopDir
27
+ * @param {(data: object) => boolean} [options.isLoopRuntimeAlive]
28
+ * @param {{ readdir: Function, stat: Function, readFile: Function }} [options.fsPromises]
29
+ * @param {() => number} [options.now]
30
+ */
31
+ export function createLoopInventoryScanner({
32
+ loopDir,
33
+ isLoopRuntimeAlive = () => false,
34
+ fsPromises = fsp,
35
+ now = Date.now,
36
+ } = {}) {
37
+ const fileCache = new Map(); // filename -> { mtimeMs, ctimeMs, ino, size, data }
38
+ let reads = 0;
39
+ let cacheHits = 0;
40
+
41
+ async function scan({ includeExtraFields = false, includeRaw = false } = {}) {
42
+ const result = includeRaw
43
+ ? { loops: [], staleCount: 0, rawEntries: [] }
44
+ : { loops: [], staleCount: 0 };
45
+ const dir = typeof loopDir === 'function' ? loopDir() : loopDir;
46
+ if (!dir) {
47
+ fileCache.clear();
48
+ return result;
49
+ }
50
+
51
+ let entries;
52
+ try {
53
+ entries = await fsPromises.readdir(dir);
54
+ } catch (err) {
55
+ if (err?.code === 'ENOENT') {
56
+ fileCache.clear();
57
+ return result;
58
+ }
59
+ throw err;
60
+ }
61
+
62
+ const files = entries.filter(isInventoryLoopFile);
63
+ const seen = new Set(files);
64
+ for (const key of fileCache.keys()) {
65
+ if (!seen.has(key)) fileCache.delete(key);
66
+ }
67
+
68
+ const currentMs = now();
69
+ for (const f of files) {
70
+ const filePath = resolve(dir, f);
71
+ let stat;
72
+ try {
73
+ stat = await fsPromises.stat(filePath);
74
+ } catch {
75
+ fileCache.delete(f);
76
+ continue;
77
+ }
78
+
79
+ const ctimeMs = stat.ctimeMs ?? null;
80
+ const ino = stat.ino ?? null;
81
+ let data;
82
+ const cached = fileCache.get(f);
83
+ if (
84
+ cached
85
+ && cached.mtimeMs === stat.mtimeMs
86
+ && cached.ctimeMs === ctimeMs
87
+ && cached.ino === ino
88
+ && cached.size === stat.size
89
+ ) {
90
+ data = cached.data;
91
+ cacheHits++;
92
+ } else {
93
+ try {
94
+ const raw = await fsPromises.readFile(filePath, 'utf-8');
95
+ data = JSON.parse(raw);
96
+ fileCache.set(f, { mtimeMs: stat.mtimeMs, ctimeMs, ino, size: stat.size, data });
97
+ reads++;
98
+ } catch {
99
+ fileCache.delete(f);
100
+ continue;
101
+ }
102
+ }
103
+
104
+ if (!data || typeof data !== 'object') continue;
105
+ const sessionId = f.replace('.json', '');
106
+ if (includeRaw) {
107
+ result.rawEntries.push({ file: f, filePath, sessionId, mtimeMs: stat.mtimeMs, stat, data });
108
+ }
109
+ const startedAtMs = data.startedAt ? new Date(data.startedAt).getTime() : 0;
110
+ const lastIterAtMs = data.lastIterationAt ? new Date(data.lastIterationAt).getTime() : startedAtMs;
111
+ const elapsedMs = startedAtMs ? currentMs - startedAtMs : 0;
112
+ const stalledMs = lastIterAtMs ? currentMs - lastIterAtMs : 0;
113
+ const terminalAlive = !!isLoopRuntimeAlive(data);
114
+ const iterDone = (data.currentIteration || 0) >= (data.totalIterations || 0) && (data.totalIterations || 0) > 0;
115
+ let state;
116
+ if (data.active === false) {
117
+ state = 'stale-inactive';
118
+ result.staleCount++;
119
+ } else if (data.terminalSessionId && !terminalAlive) {
120
+ state = data.runtimeType === 'native' ? 'orphaned-native' : 'orphaned-pty';
121
+ } else if (iterDone) {
122
+ state = 'finished';
123
+ } else {
124
+ state = 'active';
125
+ }
126
+
127
+ const item = {
128
+ sessionId,
129
+ terminalSessionId: data.terminalSessionId || null,
130
+ terminalAlive,
131
+ ...(includeExtraFields ? {
132
+ runId: data.runId || null,
133
+ profile: data.profile || null,
134
+ runtimeType: data.runtimeType || 'pty',
135
+ surface: data.surface || 'terminal',
136
+ } : {}),
137
+ task: typeof data.task === 'string' ? data.task.slice(0, 200) : '',
138
+ currentIteration: data.currentIteration || 0,
139
+ totalIterations: data.totalIterations || 0,
140
+ startedAt: data.startedAt || null,
141
+ lastIterationAt: data.lastIterationAt || null,
142
+ elapsedMinutes: Math.round(elapsedMs / 60000),
143
+ stalledMinutes: Math.round(stalledMs / 60000),
144
+ stalledMs,
145
+ state,
146
+ browserSessionId: data.browserSessionId || null,
147
+ browserTabId: data.browserTabId || null,
148
+ usesBrowser: !!data.usesBrowser,
149
+ };
150
+ result.loops.push(item);
151
+ }
152
+
153
+ result.loops.sort((a, b) => (b.startedAt || '').localeCompare(a.startedAt || ''));
154
+ return result;
155
+ }
156
+
157
+ return {
158
+ scan,
159
+ clearCache() { fileCache.clear(); },
160
+ stats() { return { reads, cacheHits, cachedFiles: fileCache.size }; },
161
+ };
162
+ }
@@ -6,10 +6,13 @@ let activeMonitor;
6
6
  // `last` alone named whatever marked most recently, and the 2 s capture and maintenance timers mark every second:
7
7
  // a multi-second recall or write wait that started before them was reported under their names
8
8
  // (docs/startup-freeze-and-agents-audit.md → Third pass). A stall line now also says what was still in flight
9
- // (beginActivity) and the slowest synchronous SQLite statement of the stalled interval (instrumentSqlite).
9
+ // (beginActivity) and the slowest synchronous work of the stalled interval (instrumentSqlite, timeBlockingWork,
10
+ // beginBlockingWork, noteBlockingWork). `markActivity` labels are kept strictly as context (`last:`), never
11
+ // timed via nextTick, so unrelated callbacks sharing a turn are never misattributed.
10
12
  const open = new Map();
11
13
  let openSeq = 0;
12
14
  let slowest = null;
15
+ const activeSyncSpans = []; // stack of open beginBlockingWork/timeBlockingWork spans on this thread
13
16
 
14
17
  export function markActivity(label) {
15
18
  activeMonitor?.mark(label);
@@ -33,16 +36,52 @@ export function noteBlockingWork(label, ms) {
33
36
  if (!slowest || ms > slowest.ms) slowest = { label, ms };
34
37
  }
35
38
 
39
+ /**
40
+ * Time a non-SQL synchronous section on this thread. Returns an `end()` callback that records its duration
41
+ * via `noteBlockingWork` when at or over `thresholdMs`. Also keeps the span visible while still running so
42
+ * a stall detected mid-section attributes it immediately.
43
+ */
44
+ export function beginBlockingWork(label, { thresholdMs = 50, mark = true } = {}) {
45
+ if (mark) markActivity(label);
46
+ const span = { label, started: performance.now(), thresholdMs, ended: false };
47
+ activeSyncSpans.push(span);
48
+ if (activeSyncSpans.length > 64) activeSyncSpans.shift();
49
+ return () => {
50
+ if (span.ended) return 0;
51
+ span.ended = true;
52
+ const idx = activeSyncSpans.lastIndexOf(span);
53
+ if (idx >= 0) activeSyncSpans.splice(idx, 1);
54
+ const ms = performance.now() - span.started;
55
+ if (ms >= thresholdMs) noteBlockingWork(label, ms);
56
+ return ms;
57
+ };
58
+ }
59
+
60
+ /** Run synchronous function `fn` under a named blocking-work timer (attributed on any stall line). */
61
+ export function timeBlockingWork(label, fn, options) {
62
+ const end = beginBlockingWork(label, options);
63
+ try { return fn(); } finally { end(); }
64
+ }
65
+
36
66
  function inFlight(now) {
37
67
  const list = [];
38
68
  for (const { label, at } of open.values()) { list.push(`${label} ${((now - at) / 1000).toFixed(1)} s`); if (list.length === 3) break; }
39
69
  return list.length ? `; in flight: ${list.join(', ')}${open.size > 3 ? ` +${open.size - 3}` : ''}` : '';
40
70
  }
41
71
 
72
+ function longestActiveSpan(now) {
73
+ let best = null;
74
+ for (const span of activeSyncSpans) {
75
+ const ms = now - span.started;
76
+ if (!best || ms > best.ms) best = { label: span.label, ms };
77
+ }
78
+ return best;
79
+ }
80
+
42
81
  let sqliteInstrumented = false;
43
82
  /**
44
- * Time every synchronous SQLite call on this thread (node:sqlite statements and exec) and keep the slowest of each
45
- * monitor interval at or over `thresholdMs`, with the start of its SQL. A few tens of nanoseconds per call.
83
+ * Time every synchronous SQLite call on this thread (node:sqlite statements, prepare and exec) and keep the slowest
84
+ * of each monitor interval at or over `thresholdMs`, with the start of its SQL. A few tens of nanoseconds per call.
46
85
  * Off with SYNABUN_LOOP_STALL_SQL=off. Only for the thread that runs the monitor: workers have their own classes.
47
86
  */
48
87
  export function instrumentSqlite({ thresholdMs = 50 } = {}) {
@@ -60,6 +99,16 @@ export function instrumentSqlite({ thresholdMs = 50 } = {}) {
60
99
  }
61
100
  };
62
101
  }
102
+ const prepare = DatabaseSync.prototype.prepare;
103
+ if (typeof prepare === 'function') {
104
+ DatabaseSync.prototype.prepare = function timedPrepare(sql, ...rest) {
105
+ const started = performance.now();
106
+ try { return prepare.call(this, sql, ...rest); } finally {
107
+ const ms = performance.now() - started;
108
+ if (ms >= thresholdMs) noteBlockingWork(`sql prepare ${describe(sql)}`, ms);
109
+ }
110
+ };
111
+ }
63
112
  const exec = DatabaseSync.prototype.exec;
64
113
  DatabaseSync.prototype.exec = function timedExec(sql) {
65
114
  const started = performance.now();
@@ -81,6 +130,7 @@ export function instrumentSqlite({ thresholdMs = 50 } = {}) {
81
130
  // line ends with what the limit kept back since the line before it: how many stalls, their sum and the worst.
82
131
  export function startLoopStallMonitor({
83
132
  thresholdMs = 500, intervalMs = 100, resolution = 20, rateLimitMs = 30_000, longMs = 3000,
133
+ unattributedMs = 10_000,
84
134
  log = console.warn,
85
135
  } = {}) {
86
136
  if (activeMonitor) return activeMonitor;
@@ -93,6 +143,24 @@ export function startLoopStallMonitor({
93
143
  // One stall is seen twice (by the mark that follows it and by the delayed tick): `seenUntil` counts it once.
94
144
  let seenUntil = -Infinity;
95
145
 
146
+ function pickAttribution(now, blocked) {
147
+ const activeSpan = longestActiveSpan(now);
148
+ const specific = !slowest ? activeSpan
149
+ : !activeSpan ? slowest
150
+ : activeSpan.ms > slowest.ms ? activeSpan : slowest;
151
+ const minReport = Math.min(blocked / 4, 100);
152
+ if (specific && specific.ms >= minReport) {
153
+ return `; longest sync: ${specific.label} ${Math.round(specific.ms)} ms`;
154
+ }
155
+ // Never leave a >10 s stall completely unattributed: report whatever timed section ran, or explicitly
156
+ // state it was unattributed (e.g., V8 GC pause, OS sleep, or untagged native/JS work) after `activity`.
157
+ if (blocked >= unattributedMs) {
158
+ if (specific && specific.ms > 0) return `; longest sync: ${specific.label} ${Math.round(specific.ms)} ms`;
159
+ return `; longest sync: unattributed (after ${activity})`;
160
+ }
161
+ return '';
162
+ }
163
+
96
164
  function check(now, histogram = 0) {
97
165
  const blocked = Math.max(now - lastTick - intervalMs, histogram);
98
166
  if (blocked < thresholdMs) return;
@@ -107,7 +175,7 @@ export function startLoopStallMonitor({
107
175
  if (limited && now - blocked < seenUntil) return; // this long stall already has its line
108
176
  lastReport = now;
109
177
  seenUntil = now;
110
- const work = slowest && slowest.ms >= Math.min(blocked / 4, 100) ? `; longest sync: ${slowest.label} ${Math.round(slowest.ms)} ms` : '';
178
+ const work = pickAttribution(now, blocked);
111
179
  slowest = null;
112
180
  const more = held.count
113
181
  ? `; ${held.count} more ${held.count === 1 ? 'stall' : 'stalls'} since the last line, ${Math.round(held.ms)} ms in all, worst ${Math.round(held.worst)} ms`
@@ -132,6 +200,8 @@ export function startLoopStallMonitor({
132
200
  stop() {
133
201
  clearInterval(timer);
134
202
  delay.disable();
203
+ slowest = null;
204
+ activeSyncSpans.length = 0;
135
205
  if (activeMonitor === this) activeMonitor = undefined;
136
206
  },
137
207
  };
@@ -1,4 +1,6 @@
1
1
  import { runSessionJob } from './session-cache-worker.js';
2
+ import { captureStartOffset, fileIdentityOf, mtimeIsoOf } from './session-capture-gate.js';
3
+ import { statSync } from 'node:fs';
2
4
  import { open } from 'node:fs/promises';
3
5
  import { getDb } from '../../mcp-server/dist/services/sqlite.js';
4
6
  import { detectProject } from '../../mcp-server/dist/config.js';
@@ -6,40 +8,109 @@ import { normalizeMemoryEvents, ingestMemoryEvents, CAPTURE_TRANSACTION_MS, CAPT
6
8
  import { maintenancePaused } from './memory-timers.js';
7
9
 
8
10
  /** The hosts whose transcripts are captured from a file (OpenCode's rows are taken in session-cache-builder.js). */
9
- export const CAPTURE_HOSTS=Object.freeze(['claude-code','codex','antigravity']);
11
+ export const CAPTURE_HOSTS = Object.freeze(['claude-code', 'codex', 'antigravity']);
10
12
 
11
- /**
12
- * `size`: the transcript's size now, when the caller knows it. A file already read to that size is left as it is
13
- * (a pass over every Antigravity conversation would otherwise mark each one pending again).
14
- */
15
- export function queueMemoryCapture({host,sessionId,filePath,project,cwd,size=null}) {
16
- if(!filePath || !sessionId || !CAPTURE_HOSTS.includes(host))return;
17
- if(size!=null) {
18
- const row=getDb().prepare('SELECT file_path,byte_offset,status,cwd FROM memory_capture_files WHERE host=? AND session_id=?').get(host,sessionId);
19
- if(row && row.status==='complete' && row.file_path===filePath && Number(row.byte_offset)===Number(size) && (row.cwd || null)===(cwd || null))return;
13
+ const migratedDbs = new WeakSet();
14
+ const CAPTURE_EXTRA_COLUMNS = Object.freeze([
15
+ ['file_size', 'INTEGER'],
16
+ ['file_mtime', 'TEXT'],
17
+ ['file_identity', 'TEXT'],
18
+ ]);
19
+
20
+ function ensureCaptureMetadataColumns(d) {
21
+ if (migratedDbs.has(d)) return;
22
+ for (const [name, type] of CAPTURE_EXTRA_COLUMNS) {
23
+ const hasColumn = () => d.prepare('PRAGMA table_info(memory_capture_files)').all().some(c => c.name === name);
24
+ if (!hasColumn()) {
25
+ try { d.exec(`ALTER TABLE memory_capture_files ADD COLUMN ${name} ${type}`); }
26
+ catch (err) { if (!hasColumn()) throw err; }
27
+ }
20
28
  }
21
- // An Antigravity conversation whose folder agy named only later is read again from its start: its events take the
22
- // project (each step keeps its source id, so nothing is stored twice).
23
- getDb().prepare(`INSERT INTO memory_capture_files(host,session_id,file_path,project,cwd) VALUES(?,?,?,?,?)
24
- ON CONFLICT(host,session_id) DO UPDATE SET file_path=excluded.file_path,project=excluded.project,cwd=excluded.cwd,status='pending',error=NULL,
25
- byte_offset=CASE WHEN excluded.host='antigravity' AND memory_capture_files.cwd IS NOT excluded.cwd THEN 0 ELSE memory_capture_files.byte_offset END`)
26
- .run(host,sessionId,filePath,cwd ? detectProject(cwd) : project || 'global',cwd || null);
29
+ migratedDbs.add(d);
27
30
  }
28
31
 
29
- let running=false;
30
- let timer=null;
32
+ function readStatBestEffort(filePath, providedStat) {
33
+ if (providedStat && providedStat.size != null && (providedStat.dev != null || providedStat.ino != null || providedStat.mtimeNs != null)) {
34
+ return providedStat;
35
+ }
36
+ try {
37
+ return statSync(filePath, { bigint: true });
38
+ } catch {
39
+ return providedStat || null;
40
+ }
41
+ }
42
+
43
+ // Compare the actual checkpoint in SQL on every transition: a scan or worker
44
+ // that yielded to another capture cannot overwrite its newer offset or status.
45
+ const checkpointWhere = `host = ? AND session_id = ? AND status = ? AND byte_offset = ?
46
+ AND file_path = ? AND cwd IS ? AND file_size IS ? AND file_mtime IS ? AND file_identity IS ?`;
47
+ function checkpointKey(row) {
48
+ return [row.host, row.session_id, row.status, row.byte_offset, row.file_path, row.cwd,
49
+ row.file_size, row.file_mtime, row.file_identity];
50
+ }
51
+
52
+ export function queueMemoryCapture({ host, sessionId, filePath, project, cwd, size = null, stat = null,
53
+ fileMtime = null, fileIdentity = null }) {
54
+ if (!filePath || !sessionId || !CAPTURE_HOSTS.includes(host)) return;
55
+ const d = getDb();
56
+ ensureCaptureMetadataColumns(d);
57
+ const read = d.prepare('SELECT * FROM memory_capture_files WHERE host = ? AND session_id = ?');
58
+ const projectName = () => cwd ? detectProject(cwd) : project || 'global';
59
+ // A worker can finish between the read and the update. Re-evaluate that checkpoint.
60
+ for (;;) {
61
+ const row = read.get(host, sessionId);
62
+ const st = readStatBestEffort(filePath, stat);
63
+ const currentSize = st ? Number(st.size) : size;
64
+ const mtime = mtimeIsoOf(st) ?? fileMtime;
65
+ const identity = fileIdentityOf(st) ?? fileIdentity;
66
+ if (!row) {
67
+ const added = d.prepare(`INSERT INTO memory_capture_files
68
+ (host, session_id, file_path, project, cwd, byte_offset, status, file_size, file_mtime, file_identity)
69
+ VALUES (?, ?, ?, ?, ?, 0, 'pending', ?, ?, ?) ON CONFLICT(host, session_id) DO NOTHING`)
70
+ .run(host, sessionId, filePath, projectName(), cwd || null, currentSize, mtime, identity);
71
+ if (added.changes) return;
72
+ stat = null;
73
+ continue;
74
+ }
75
+
76
+ const sameCwd = (host !== 'antigravity' && !cwd) || row.cwd === (cwd || null);
77
+ const sameSource = row.file_path === filePath && (host !== 'antigravity' || sameCwd);
78
+ const offset = sameSource ? captureStartOffset(row, currentSize, identity, mtime) : 0;
79
+ const complete = row.status === 'complete' && sameSource && sameCwd && offset === currentSize;
80
+ const status = complete ? 'complete' : 'pending';
81
+ // If the stat failed, preserve the known checkpoint for the worker's next open.
82
+ const nextSize = currentSize ?? (sameSource ? row.file_size : null);
83
+ const nextMtime = mtime ?? (sameSource ? row.file_mtime : null);
84
+ const nextIdentity = identity ?? (sameSource ? row.file_identity : null);
85
+ const nextCwd = sameCwd && sameSource ? row.cwd : cwd || null;
86
+ if (sameSource && sameCwd && status === row.status && offset === row.byte_offset
87
+ && row.file_size === nextSize && row.file_mtime === nextMtime && row.file_identity === nextIdentity
88
+ && (complete || row.project === projectName())) return;
89
+
90
+ const changed = d.prepare(`UPDATE memory_capture_files SET file_path = ?, project = ?, cwd = ?,
91
+ status = ?, error = NULL, byte_offset = ?, file_size = ?, file_mtime = ?, file_identity = ?
92
+ WHERE ${checkpointWhere}`).run(filePath, complete ? row.project : projectName(), nextCwd,
93
+ status, offset, nextSize, nextMtime, nextIdentity, ...checkpointKey(row));
94
+ if (changed.changes) return;
95
+ stat = null; // Resample if a worker committed a newer checkpoint.
96
+ }
97
+ }
98
+
99
+ let running = false;
100
+ let timer = null;
31
101
  export async function captureMemoryFileBatch(target, { reportProgress = false } = {}) {
32
- if(running)return {busy:true};
33
- running=true;
102
+ if (running) return { busy: true };
103
+ running = true;
34
104
  try {
35
105
  return await runSessionJob('capture', { target, reportProgress });
36
106
  } finally {
37
- running=false;
107
+ running = false;
38
108
  }
39
109
  }
40
110
 
41
111
  export async function capturePendingFile(target, { reportProgress, warmLookup } = {}) {
42
112
  const d = getDb();
113
+ ensureCaptureMetadataColumns(d);
43
114
  if (maintenancePaused(d)) return { paused: true };
44
115
  const select = target
45
116
  ? d.prepare('SELECT * FROM memory_capture_files WHERE host=? AND session_id=?')
@@ -62,66 +133,86 @@ export async function capturePendingFile(target, { reportProgress, warmLookup }
62
133
  async function readCaptureFile(d, job) {
63
134
  let file;
64
135
  try {
65
- file=await open(job.file_path,'r');
66
- const stat=await file.stat();
67
- const offset=stat.size<job.byte_offset ? 0 : job.byte_offset;
136
+ file = await open(job.file_path, 'r');
137
+ const stat = await file.stat({ bigint: true });
138
+ const fileSize = Number(stat.size);
139
+ const identity = fileIdentityOf(stat);
140
+ const mtime = mtimeIsoOf(stat);
141
+ const offset = captureStartOffset(job, fileSize, identity, mtime);
142
+ const saveCheckpoint = (end) => d.prepare(`
143
+ UPDATE memory_capture_files SET byte_offset = ?, status = ?, error = NULL,
144
+ file_size = ?, file_mtime = ?, file_identity = ? WHERE ${checkpointWhere}
145
+ `).run(end, end >= fileSize ? 'complete' : 'pending', fileSize, mtime, identity, ...checkpointKey(job));
146
+
68
147
  // Bounded file reads keep large transcripts off the UI request path.
69
- let buffer=Buffer.alloc(256*1024);
70
- let {bytesRead}=await file.read(buffer,0,buffer.length,offset);
71
- if(!bytesRead){d.prepare("UPDATE memory_capture_files SET status='complete' WHERE host=? AND session_id=?").run(job.host,job.session_id);return;}
72
- while(buffer.subarray(0,bytesRead).lastIndexOf(10)<0 && bytesRead===buffer.length && buffer.length<8*1024*1024) {
73
- buffer=Buffer.alloc(buffer.length*2);
74
- ({bytesRead}=await file.read(buffer,0,buffer.length,offset));
148
+ let buffer = Buffer.alloc(256 * 1024);
149
+ let { bytesRead } = await file.read(buffer, 0, buffer.length, offset);
150
+ if (!bytesRead) {
151
+ saveCheckpoint(offset);
152
+ return;
153
+ }
154
+ while (buffer.subarray(0, bytesRead).lastIndexOf(10) < 0 && bytesRead === buffer.length && buffer.length < 8 * 1024 * 1024) {
155
+ buffer = Buffer.alloc(buffer.length * 2);
156
+ ({ bytesRead } = await file.read(buffer, 0, buffer.length, offset));
75
157
  }
76
- const bytes=buffer.subarray(0,bytesRead);
77
- const newline=bytes.lastIndexOf(10);
78
- let consumed=newline+1;
79
- if(newline<0) {
80
- if(bytesRead===buffer.length)throw new Error('Transcript record exceeds 8 MiB; original source retained.');
158
+ const bytes = buffer.subarray(0, bytesRead);
159
+ const newline = bytes.lastIndexOf(10);
160
+ let consumed = newline + 1;
161
+ if (newline < 0) {
162
+ if (bytesRead === buffer.length) throw new Error('Transcript record exceeds 8 MiB; original source retained.');
81
163
  // A valid final JSON record need not end in a newline. Incomplete tails
82
164
  // remain pending until the writer finishes them.
83
- try{JSON.parse(bytes.toString('utf8'));consumed=bytesRead;}catch{return;}
165
+ try { JSON.parse(bytes.toString('utf8')); consumed = bytesRead; } catch { return; }
84
166
  }
85
- const records=[];
86
- let position=offset;
87
- for(const line of bytes.subarray(0,consumed).toString('utf8').split('\n')) {
88
- if(line.trim()) {try {const record=JSON.parse(line);records.push({...record,id:record.id || record.uuid || `byte:${position}`});}catch{}}
89
- position+=Buffer.byteLength(line)+1;
167
+ const records = [];
168
+ let position = offset;
169
+ for (const line of bytes.subarray(0, consumed).toString('utf8').split('\n')) {
170
+ if (line.trim()) {
171
+ try {
172
+ const record = JSON.parse(line);
173
+ records.push({ ...record, id: record.id || record.uuid || `byte:${position}` });
174
+ } catch {}
175
+ }
176
+ position += Buffer.byteLength(line) + 1;
90
177
  }
91
- const sourceCwd=job.cwd || records.find(r=>r.cwd)?.cwd || records.find(r=>r.type==='session_meta')?.payload?.cwd;
92
- const project=sourceCwd ? detectProject(sourceCwd) : job.project;
93
- const events=normalizeMemoryEvents(job.host,records,{session_id:job.session_id,project,cwd:sourceCwd});
94
- if(maintenancePaused())return;
178
+ const sourceCwd = job.cwd || records.find(r => r.cwd)?.cwd || records.find(r => r.type === 'session_meta')?.payload?.cwd;
179
+ const project = sourceCwd ? detectProject(sourceCwd) : job.project;
180
+ const events = normalizeMemoryEvents(job.host, records, { session_id: job.session_id, project, cwd: sourceCwd });
181
+ if (maintenancePaused()) return;
95
182
  // Short transactions with the write lock left free between them (memory-sessions.ts CAPTURE_*): the server's
96
183
  // own writes wait for this lock on its event loop.
97
- for (let offset = 0; offset < events.length;) {
184
+ for (let i = 0; i < events.length;) {
98
185
  if (maintenancePaused()) return; // replay from the previous checkpoint on resume
99
- const batch = ingestMemoryEvents(events.slice(offset, offset + 25), { maxTransactionMs: CAPTURE_TRANSACTION_MS });
100
- offset += Math.max(1, batch.consumed);
101
- if (batch.indexed && offset < events.length) await new Promise(done => setTimeout(done, CAPTURE_PAUSE_MS));
186
+ const batch = ingestMemoryEvents(events.slice(i, i + 25), { maxTransactionMs: CAPTURE_TRANSACTION_MS });
187
+ i += Math.max(1, batch.consumed);
188
+ if (batch.indexed && i < events.length) await new Promise(done => setTimeout(done, CAPTURE_PAUSE_MS));
102
189
  }
103
190
  // Replaying after a crash between intake and checkpoint is idempotent.
104
- d.prepare("UPDATE memory_capture_files SET byte_offset=?,status=?,error=NULL WHERE host=? AND session_id=?")
105
- .run(offset+consumed,offset+consumed>=stat.size ? 'complete':'pending',job.host,job.session_id);
106
- }catch(error){d.prepare("UPDATE memory_capture_files SET status='failed',error=? WHERE host=? AND session_id=?").run(error.message,job.host,job.session_id);}
107
- finally{await file?.close();}
191
+ saveCheckpoint(offset + consumed);
192
+ } catch (error) {
193
+ d.prepare(`UPDATE memory_capture_files SET status='failed', error=? WHERE ${checkpointWhere}`)
194
+ .run(error.message, ...checkpointKey(job));
195
+ } finally {
196
+ await file?.close();
197
+ }
108
198
  }
109
- let startTimer=null;
199
+
200
+ let startTimer = null;
110
201
  // offsetMs keeps this tick out of phase with the 2 s maintenance timer so the
111
202
  // two never stack on the same event-loop turn.
112
- export function startMemoryCapture({offsetMs=1000,intervalMs=2000}={}) {
113
- if(timer||startTimer)return;
114
- const tick=()=>captureMemoryFileBatch().catch(error=>console.error('[memory capture]',error.message));
115
- startTimer=setTimeout(()=>{
116
- startTimer=null;
117
- timer=setInterval(tick,intervalMs);
203
+ export function startMemoryCapture({ offsetMs = 1000, intervalMs = 2000 } = {}) {
204
+ if (timer || startTimer) return;
205
+ const tick = () => captureMemoryFileBatch().catch(error => console.error('[memory capture]', error.message));
206
+ startTimer = setTimeout(() => {
207
+ startTimer = null;
208
+ timer = setInterval(tick, intervalMs);
118
209
  timer.unref();
119
- },offsetMs);
210
+ }, offsetMs);
120
211
  startTimer.unref();
121
212
  }
122
- export function stopMemoryCapture(){
123
- if(startTimer)clearTimeout(startTimer);
124
- if(timer)clearInterval(timer);
125
- startTimer=null;
126
- timer=null;
213
+ export function stopMemoryCapture() {
214
+ if (startTimer) clearTimeout(startTimer);
215
+ if (timer) clearInterval(timer);
216
+ startTimer = null;
217
+ timer = null;
127
218
  }