synabun 2.4.2 → 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 (220) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +83 -34
  4. package/lib/release-npm-ci.mjs +23 -1
  5. package/mcp-server/dist/http.d.ts.map +1 -1
  6. package/mcp-server/dist/http.js +8 -1
  7. package/mcp-server/dist/http.js.map +1 -1
  8. package/mcp-server/dist/services/identity.d.ts +2 -0
  9. package/mcp-server/dist/services/identity.d.ts.map +1 -1
  10. package/mcp-server/dist/services/identity.js +4 -0
  11. package/mcp-server/dist/services/identity.js.map +1 -1
  12. package/mcp-server/dist/services/memory-client.d.ts +5 -0
  13. package/mcp-server/dist/services/memory-client.d.ts.map +1 -1
  14. package/mcp-server/dist/services/memory-client.js +21 -2
  15. package/mcp-server/dist/services/memory-client.js.map +1 -1
  16. package/mcp-server/dist/services/memory-writer.d.ts +3 -0
  17. package/mcp-server/dist/services/memory-writer.d.ts.map +1 -1
  18. package/mcp-server/dist/services/memory-writer.js +7 -1
  19. package/mcp-server/dist/services/memory-writer.js.map +1 -1
  20. package/mcp-server/dist/services/neural-interface.d.ts +11 -1
  21. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  22. package/mcp-server/dist/services/neural-interface.js +68 -18
  23. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  24. package/mcp-server/dist/services/typesafe-config.d.ts +38 -2
  25. package/mcp-server/dist/services/typesafe-config.d.ts.map +1 -1
  26. package/mcp-server/dist/services/typesafe-config.js +260 -8
  27. package/mcp-server/dist/services/typesafe-config.js.map +1 -1
  28. package/mcp-server/dist/tools/agent-definition.d.ts +2 -2
  29. package/mcp-server/dist/tools/agents.d.ts +3 -1
  30. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/agents.js +11 -6
  32. package/mcp-server/dist/tools/agents.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-extension-setup.d.ts.map +1 -1
  34. package/mcp-server/dist/tools/browser-extension-setup.js +8 -2
  35. package/mcp-server/dist/tools/browser-extension-setup.js.map +1 -1
  36. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  37. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  38. package/mcp-server/dist/tools/browser-observe.js +113 -27
  39. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  40. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  41. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  42. package/mcp-server/dist/tools/browser-readers.js +17 -0
  43. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  44. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  45. package/mcp-server/dist/tools/remember.js +6 -2
  46. package/mcp-server/dist/tools/remember.js.map +1 -1
  47. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  48. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  49. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  50. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  51. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  52. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  53. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  54. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  55. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  56. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  57. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  58. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  59. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  60. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  61. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  62. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  63. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  64. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  65. package/mcp-server/package-lock.json +5 -5
  66. package/mcp-server/package.json +1 -1
  67. package/mcp-server/src/http.ts +8 -1
  68. package/mcp-server/src/services/identity.ts +5 -0
  69. package/mcp-server/src/services/memory-client.ts +32 -12
  70. package/mcp-server/src/services/memory-writer.ts +5 -2
  71. package/mcp-server/src/services/neural-interface.ts +66 -19
  72. package/mcp-server/src/services/typesafe-config.ts +268 -7
  73. package/mcp-server/src/tools/agents.ts +12 -6
  74. package/mcp-server/src/tools/browser-extension-setup.ts +8 -2
  75. package/mcp-server/src/tools/browser-observe.ts +117 -28
  76. package/mcp-server/src/tools/browser-readers.ts +19 -0
  77. package/mcp-server/src/tools/remember.ts +6 -1
  78. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  79. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  80. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  81. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  82. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  83. package/neural-interface/i18n/en.json +189 -1
  84. package/neural-interface/i18n/pt-BR.json +196 -8
  85. package/neural-interface/lib/assistant-api.js +123 -0
  86. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  87. package/neural-interface/lib/assistant-brains/opencode.js +121 -7
  88. package/neural-interface/lib/assistant-dispatch.js +302 -44
  89. package/neural-interface/lib/assistant-envelope.js +40 -0
  90. package/neural-interface/lib/assistant-memory.js +3 -1
  91. package/neural-interface/lib/assistant-persona.js +6 -0
  92. package/neural-interface/lib/assistant-router.js +18 -8
  93. package/neural-interface/lib/assistant-runtime.js +182 -11
  94. package/neural-interface/lib/assistant-task-prompt.js +15 -2
  95. package/neural-interface/lib/browser-connection-state.js +20 -0
  96. package/neural-interface/lib/browser-extension-adapter.js +221 -17
  97. package/neural-interface/lib/browser-extension-archive.js +149 -0
  98. package/neural-interface/lib/browser-extension-bridge.js +46 -10
  99. package/neural-interface/lib/browser-extension-folder.js +635 -76
  100. package/neural-interface/lib/browser-extension-package.js +201 -0
  101. package/neural-interface/lib/browser-extension-pin.js +84 -0
  102. package/neural-interface/lib/browser-extension-pin.json +35 -0
  103. package/{browser-extension/protocol.js → neural-interface/lib/browser-extension-protocol.js} +111 -13
  104. package/neural-interface/lib/browser-extension-setup.js +108 -19
  105. package/neural-interface/lib/browser-extension-update.js +104 -0
  106. package/neural-interface/lib/browser-extraction.js +38 -14
  107. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  108. package/neural-interface/lib/claude-history.js +12 -1
  109. package/neural-interface/lib/cli-install.js +23 -3
  110. package/neural-interface/lib/cli-update-planner.js +67 -4
  111. package/neural-interface/lib/confined-fs.js +25 -0
  112. package/neural-interface/lib/coordination/operations.js +2 -0
  113. package/neural-interface/lib/db.js +39 -16
  114. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  115. package/neural-interface/lib/git-bash/manager.js +28 -3
  116. package/neural-interface/lib/git-status-runner.js +31 -3
  117. package/neural-interface/lib/loop-inventory.js +162 -0
  118. package/neural-interface/lib/loop-stall.js +74 -4
  119. package/neural-interface/lib/memory-session-capture.js +157 -66
  120. package/neural-interface/lib/native-loop-providers.js +82 -13
  121. package/neural-interface/lib/native-loop-runtime.js +23 -2
  122. package/neural-interface/lib/opencode-protocol.js +4 -2
  123. package/neural-interface/lib/opencode-shell-read.js +107 -0
  124. package/neural-interface/lib/opencode-stop-failures.js +40 -0
  125. package/neural-interface/lib/opencode-turn-release.js +173 -0
  126. package/neural-interface/lib/opencode-v2-client.js +4 -1
  127. package/neural-interface/lib/opencode-v2-ws-requests.js +34 -0
  128. package/neural-interface/lib/opencode2-client.js +341 -6
  129. package/neural-interface/lib/opencode2-translate.js +161 -4
  130. package/neural-interface/lib/peer-identity.js +62 -16
  131. package/neural-interface/lib/session-cache-builder.js +66 -18
  132. package/neural-interface/lib/session-capture-gate.js +42 -0
  133. package/neural-interface/lib/session-indexer.js +28 -20
  134. package/neural-interface/lib/teams/scheduler.js +3 -2
  135. package/neural-interface/lib/terminal-token-redaction.js +83 -0
  136. package/neural-interface/lib/ui-blob-api.js +14 -5
  137. package/neural-interface/lib/ui-blob-store.js +302 -39
  138. package/neural-interface/lib/whatsapp/bridge.js +52 -6
  139. package/neural-interface/package-lock.json +5 -5
  140. package/neural-interface/package.json +1 -1
  141. package/neural-interface/public/extension-setup.html +6 -2
  142. package/neural-interface/public/shared/agy/agy-panel.js +38 -10
  143. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  144. package/neural-interface/public/shared/assistant/asst-api.js +67 -0
  145. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  146. package/neural-interface/public/shared/assistant/asst-panel.js +354 -11
  147. package/neural-interface/public/shared/assistant/asst-rack-styles.js +23 -0
  148. package/neural-interface/public/shared/assistant/asst-render.js +343 -10
  149. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  150. package/neural-interface/public/shared/assistant/asst-shell-logic.js +200 -0
  151. package/neural-interface/public/shared/assistant/asst-shell.js +111 -0
  152. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  153. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  154. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  155. package/neural-interface/public/shared/assistant/asst-styles.js +21 -0
  156. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  157. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  158. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  159. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  160. package/neural-interface/public/shared/browser-extension-updates.js +88 -0
  161. package/neural-interface/public/shared/cdx/cdx-tabs.js +25 -0
  162. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  163. package/neural-interface/public/shared/extension-setup/es-page.js +25 -12
  164. package/neural-interface/public/shared/extension-setup/es-view.js +25 -10
  165. package/neural-interface/public/shared/extension-update-view.js +34 -0
  166. package/neural-interface/public/shared/mtc/mtc-panel.js +17 -2
  167. package/neural-interface/public/shared/ocp-v2/ocp-v2-events.js +5 -0
  168. package/neural-interface/public/shared/ocp-v2/ocp-v2-manager.js +1 -0
  169. package/neural-interface/public/shared/ocp-v2/ocp-v2-panel.js +34 -2
  170. package/neural-interface/public/shared/ocp-v2/ocp-v2-rehydrate.js +7 -1
  171. package/neural-interface/public/shared/ocp-v2/ocp-v2-render.js +26 -1
  172. package/neural-interface/public/shared/ocp-v2/ocp-v2-send.js +39 -6
  173. package/neural-interface/public/shared/ocp-v2/ocp-v2-session-actions.js +20 -1
  174. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-block.js +165 -0
  175. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +350 -0
  176. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell.js +108 -0
  177. package/neural-interface/public/shared/ocp-v2/ocp-v2-state.js +49 -3
  178. package/neural-interface/public/shared/ocp-v2/ocp-v2-styles.js +40 -0
  179. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools-logic.js +20 -5
  180. package/neural-interface/public/shared/ocp-v2/ocp-v2-tools.js +7 -1
  181. package/neural-interface/public/shared/ocp-v2/ocp-v2-ws.js +7 -2
  182. package/neural-interface/public/shared/settings/settings-browser-extension.js +61 -13
  183. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  184. package/neural-interface/public/shared/shell-stop-view.js +83 -0
  185. package/neural-interface/public/shared/styles.css +4 -0
  186. package/neural-interface/public/shared/tour/tour-actor.js +14 -3
  187. package/neural-interface/public/shared/tray-auto-close.js +36 -6
  188. package/neural-interface/public/shared/ui-claude-panel.js +130 -1
  189. package/neural-interface/public/shared/ui-native-loop-router.js +45 -3
  190. package/neural-interface/public/shared/ui-notifications.js +23 -4
  191. package/neural-interface/public/shared/ui-scroll-follow.js +4 -0
  192. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  193. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  194. package/neural-interface/public/shared/worker-end.js +18 -0
  195. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  196. package/neural-interface/scripts/rebuild-pty.js +10 -0
  197. package/neural-interface/server.js +725 -308
  198. package/npm-shrinkwrap.json +5 -5
  199. package/package.json +1 -2
  200. package/browser-extension/content.js +0 -231
  201. package/browser-extension/engine.js +0 -658
  202. package/browser-extension/icons/icon-128.png +0 -0
  203. package/browser-extension/icons/icon-16.png +0 -0
  204. package/browser-extension/icons/icon-32.png +0 -0
  205. package/browser-extension/icons/icon-48.png +0 -0
  206. package/browser-extension/icons/status-off-16.png +0 -0
  207. package/browser-extension/icons/status-off-32.png +0 -0
  208. package/browser-extension/icons/status-off-48.png +0 -0
  209. package/browser-extension/icons/status-on-16.png +0 -0
  210. package/browser-extension/icons/status-on-32.png +0 -0
  211. package/browser-extension/icons/status-on-48.png +0 -0
  212. package/browser-extension/manifest.json +0 -58
  213. package/browser-extension/popup-strings.js +0 -250
  214. package/browser-extension/popup-view.js +0 -151
  215. package/browser-extension/popup.css +0 -166
  216. package/browser-extension/popup.html +0 -108
  217. package/browser-extension/popup.js +0 -359
  218. package/browser-extension/service-worker.js +0 -283
  219. package/browser-extension/setup-content.js +0 -36
  220. package/browser-extension/tokens.css +0 -326
@@ -249,6 +249,11 @@ async function writeAll(handle, buffer) {
249
249
  /**
250
250
  * Download `url` into `destination` (a new file), HTTPS only and only through
251
251
  * hosts `allow` accepts. Checks the size and, when given, the SHA-256.
252
+ * `identityOnly`: an answer with any Content-Encoding but identity is refused
253
+ * before its body is read, so `maxBytes` bounds the bytes on the wire and no
254
+ * decoding work is done (fetch would otherwise decode gzip or br by itself and
255
+ * count the decoded bytes). Every answer that is refused, and every transfer
256
+ * that fails, ends its request: the body is cancelled and the request aborted.
252
257
  * Resolves { sha256, size, url } (the address the file came from).
253
258
  */
254
259
  export async function downloadFile({
@@ -263,6 +268,7 @@ export async function downloadFile({
263
268
  onProgress = () => {},
264
269
  stallMs = 60_000,
265
270
  accept = 'application/octet-stream',
271
+ identityOnly = false,
266
272
  }) {
267
273
  let current;
268
274
  try { current = new URL(url); } catch { throw new CliInstallError('internal', `Not an address: ${url}`); }
@@ -280,26 +286,33 @@ export async function downloadFile({
280
286
  let made = false;
281
287
  let answered = false;
282
288
  let received = 0;
289
+ // The body still open (an answer being looked at, then the reader): cancelled whenever the download is given up.
290
+ let release = null;
283
291
  const hash = createHash('sha256');
284
292
  try {
285
293
  alive();
286
294
  let response = null;
287
295
  for (let hop = 0; ; hop++) {
288
296
  response = await fetchImpl(current, { redirect: 'manual', signal: stop.signal, headers: { accept, 'accept-encoding': 'identity', 'user-agent': 'synabun' } });
297
+ const answer = response;
298
+ release = () => answer.body?.cancel();
289
299
  if (response.status < 300 || response.status >= 400) break;
290
300
  const next = nextHop(response, current, allow);
291
301
  try { await response.body?.cancel(); } catch { /* nothing to drain */ }
302
+ release = null;
292
303
  if (hop >= MAX_REDIRECTS) throw new CliInstallError('http', 'The download server redirected too many times.');
293
304
  current = next;
294
305
  alive();
295
306
  }
296
307
  if (response.status !== 200 || !response.body) {
297
- try { await response.body?.cancel(); } catch { /* nothing to drain */ }
298
308
  throw new CliInstallError('http', `${current.hostname} answered ${response.status} instead of the file.`, { detail: String(response.status) });
299
309
  }
310
+ const encoding = String(response.headers.get('content-encoding') || '').trim().toLowerCase();
311
+ if (identityOnly && encoding && encoding !== 'identity') {
312
+ throw new CliInstallError('http', `${current.hostname} sent the file encoded (${encoding.slice(0, 20)}) although it was asked for the file as it is. It was not downloaded.`, { detail: 'content-encoding' });
313
+ }
300
314
  const announced = Number(response.headers.get('content-length'));
301
315
  if (Number.isFinite(announced) && announced > 0 && ((expectedSize && announced !== expectedSize) || announced > maxBytes)) {
302
- try { await response.body.cancel(); } catch { /* nothing to drain */ }
303
316
  throw new CliInstallError('checksum', `${current.hostname} offered ${announced} bytes${expectedSize ? `; the published file has ${expectedSize}` : ''}. It was not downloaded.`);
304
317
  }
305
318
  answered = true;
@@ -310,6 +323,7 @@ export async function downloadFile({
310
323
  // Read through a reader of our own, cancelled on a stall or a stop: the transfer ends then whatever the
311
324
  // transport does with the signal.
312
325
  const reader = response.body.getReader();
326
+ release = () => reader.cancel();
313
327
  const onStop = () => { reader.cancel(stop.signal.reason).catch(() => {}); };
314
328
  stop.signal.addEventListener('abort', onStop, { once: true });
315
329
  try {
@@ -336,12 +350,18 @@ export async function downloadFile({
336
350
  await handle.sync();
337
351
  await handle.close();
338
352
  handle = null;
353
+ release = null;
339
354
  return { sha256: digest, size: received, url: current.href };
340
355
  } catch (error) {
356
+ const stoppedFor = stop.signal.aborted && stop.signal.reason instanceof CliInstallError ? stop.signal.reason : null;
357
+ // Whatever ended it, the request ends here too: nothing more arrives, is decoded or is read.
358
+ if (!stop.signal.aborted) stop.abort(new CliInstallError('cancelled', 'The download was given up.'));
359
+ try { await release?.(); } catch { /* cancelled already */ }
360
+ release = null;
341
361
  try { await handle?.close(); } catch { /* closed */ }
342
362
  handle = null;
343
363
  if (made) rmSync(destination, { force: true });
344
- if (stop.signal.aborted && stop.signal.reason instanceof CliInstallError) throw stop.signal.reason;
364
+ if (stoppedFor) throw stoppedFor;
345
365
  if (error instanceof CliInstallError) throw error;
346
366
  if (DISK_CODES.has(errorCode(error))) throw asInstallError(error, 'disk', `The download could not be saved (${errorCode(error)}).`);
347
367
  if (answered) throw new CliInstallError('interrupted', `The download from ${current.hostname} ended after ${received} bytes.`, { cause: error, detail: errorCode(error) || error?.message });
@@ -82,6 +82,19 @@ export const OPENCODE_UPDATE_SOURCES = Object.freeze({
82
82
  brewToken: 'opencode-v2',
83
83
  });
84
84
 
85
+ /**
86
+ * OpenCode 2 in WinGet (checked 2026-11-23): the package id, and the arguments OpenCode's own updater asks WinGet
87
+ * with to find the version it can install (`winget search …`). WinGet is the yardstick of a WinGet install, not
88
+ * OpenCode's update API: a release reaches WinGet's repository days after it is published, and some never do (on
89
+ * 2026-11-23 the API said 2.4.1 while WinGet's newest was 2.3.2, after 2.2.7 with nothing between). `opencode
90
+ * upgrade --method winget` installs what WinGet has, so a badge measured against the API stays lit after an update
91
+ * that did all it could.
92
+ */
93
+ export const OPENCODE_WINGET_ID = 'Anomaly.OpenCode';
94
+ export const OPENCODE_WINGET_SEARCH_ARGS = Object.freeze([
95
+ 'search', '--id', OPENCODE_WINGET_ID, '--exact', '--source', 'winget', '--accept-source-agreements', '--disable-interactivity',
96
+ ]);
97
+
85
98
  const PLAIN_VERSION_RE = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
86
99
  const plainVersion = (value) => {
87
100
  const text = typeof value === 'string' ? value.trim().replace(/^v(?=\d)/i, '') : '';
@@ -104,6 +117,24 @@ export function parseFormulaVersion(text) {
104
117
  return match ? plainVersion(match[1]) : null;
105
118
  }
106
119
 
120
+ /**
121
+ * The version `winget search --id <id> --exact` lists for a package, or null. Read as OpenCode's own updater reads
122
+ * it: on any line, the word after the package id (the table's columns are Name, Id, Version, Source; a progress
123
+ * spinner may share the first line, separated by carriage returns).
124
+ */
125
+ export function parseWingetSearchVersion(output, id = OPENCODE_WINGET_ID) {
126
+ const wanted = String(id || '').toLowerCase();
127
+ if (!wanted) return null;
128
+ for (const line of String(output ?? '').split(/\r?\n|\r/)) {
129
+ const words = line.trim().split(/\s+/);
130
+ const at = words.findIndex((word) => word.toLowerCase() === wanted);
131
+ if (at === -1) continue;
132
+ const version = plainVersion(words[at + 1]);
133
+ if (version) return version;
134
+ }
135
+ return null;
136
+ }
137
+
107
138
  /**
108
139
  * Where a tool's newest version is read from when it has no npm package:
109
140
  * `{ url, channel, read(text) }`, or null (an npm tool, a tool with no such
@@ -295,14 +326,32 @@ export function quoteCommandPath(file, platform = process.platform) {
295
326
  * upgrade` refreshes by itself only once in a while (HOMEBREW_AUTO_UPDATE_SECS,
296
327
  * a day by default) and would answer "already installed", leaving the badge
297
328
  * lit: the command refreshes first.
329
+ *
330
+ * `gitBash`: a Git Bash this PC has (lib/git-bash resolver: bash.exe), for OpenCode 2's own installer on Windows.
331
+ * `opencode upgrade --method curl` runs that installer, a bash script, with Git Bash, which it looks for through
332
+ * `git --exec-path`: a PC whose git is not on PATH (Git's "Git Bash only" setup, or SynaBun's own copy of Git) has
333
+ * one all the same, and is told where it is (OPENCODE_GIT_BASH_PATH, for that one command).
334
+ *
335
+ * `installedVersion`: the version found, when the caller knows it. An OpenCode in %USERPROFILE%\.opencode\bin that
336
+ * is not OpenCode 2 (the release archive an older SynaBun put there was OpenCode 1) gets no command, as before: its
337
+ * own upgrade is not the one meant here, and SynaBun's panel already says how to get OpenCode 2.
298
338
  */
299
- export function buildUpdateCommand(toolKey, installSource, { brewToken = null, binPath = null, platform = null, refreshBrew = false } = {}) {
339
+ export function buildUpdateCommand(toolKey, installSource, { brewToken = null, binPath = null, platform = null, refreshBrew = false, gitBash = null, installedVersion = null } = {}) {
340
+ if (toolKey === 'opencode' && installSource === 'standalone' && platform === 'win32' && installedVersion != null && !/^v?2\./.test(String(installedVersion).trim())) return null;
300
341
  const planned = planUpdateCommand(toolKey, installSource, { brewToken, platform });
301
342
  const command = planned && refreshBrew && isBrewSource(installSource) ? `brew update && ${planned}` : planned;
302
343
  const name = TOOL_COMMANDS[toolKey];
303
344
  if (!command || !binPath || !name) return command;
304
345
  if (command !== name && !command.startsWith(`${name} `)) return command;
305
- return `${quoteCommandPath(binPath, platform || process.platform)}${command.slice(name.length)}`;
346
+ const started = `${quoteCommandPath(binPath, platform || process.platform)}${command.slice(name.length)}`;
347
+ const bash = toolKey === 'opencode' && platform === 'win32' && installSource === 'standalone' ? cmdSetValue(gitBash) : null;
348
+ return bash ? `set "OPENCODE_GIT_BASH_PATH=${bash}" && ${started}` : started;
349
+ }
350
+
351
+ /** A value cmd.exe takes unchanged inside `set "NAME=value"`, or null (a quote, a variable or an escape in it). */
352
+ function cmdSetValue(value) {
353
+ const text = typeof value === 'string' ? value.trim() : '';
354
+ return text && !/["%!^\r\n]/.test(text) ? text : null;
306
355
  }
307
356
 
308
357
  function planUpdateCommand(toolKey, installSource, { brewToken = null, platform = null } = {}) {
@@ -326,8 +375,10 @@ function planUpdateCommand(toolKey, installSource, { brewToken = null, platform
326
375
 
327
376
  // OpenCode 2 updates itself through the channel it came from (brew is handled above).
328
377
  if (toolKey === 'opencode') {
329
- // Its installer script is bash: a copy in %USERPROFILE%\.opencode\bin on Windows is no OpenCode 2 install.
330
- if (installSource === 'standalone' && platform === 'win32') return null;
378
+ // %USERPROFILE%\.opencode\bin\opencode.exe is an install of OpenCode 2's own script on Windows too (the script
379
+ // runs in Git Bash and names the file opencode.exe), and OpenCode 2 updates it there with `--method curl`
380
+ // through Git Bash (read in the Windows builds of 2.2.7 and 2.4.1, 2026-11-23). It used to get no command here,
381
+ // so its badge could only say "update via the official installer".
331
382
  if (OPENCODE_METHODS[installSource]) return `opencode upgrade --method ${OPENCODE_METHODS[installSource]}`;
332
383
  if (['volta', 'scoop', 'choco'].includes(installSource)) return null; // not an OpenCode 2 channel: the caller shows a hint
333
384
  return selfUpdate;
@@ -408,6 +459,13 @@ export function parseBrewOutdated(raw) {
408
459
  * tool's formula as its tap publishes it (OpenCode's tap only): what Homebrew
409
460
  * installs once the tap is refreshed, so it counts when it is newer than the
410
461
  * install and `brew outdated` has not heard of it yet.
462
+ *
463
+ * `winget`: what WinGet was asked about a WinGet install (OpenCode 2 only):
464
+ * `{ version }`, the version WinGet lists, or null when it could not be
465
+ * asked. WinGet is then the yardstick, as Homebrew is for a Homebrew install:
466
+ * its version when that is newer than the install, else the install itself (no
467
+ * badge), and the install itself when WinGet could not be asked (fail closed:
468
+ * the update API's version is one WinGet may not have).
411
469
  */
412
470
  export function resolveLatest({
413
471
  installSource,
@@ -416,7 +474,12 @@ export function resolveLatest({
416
474
  npmLatest = null,
417
475
  brewUpstream = null,
418
476
  installed = null,
477
+ winget = undefined,
419
478
  } = {}) {
479
+ if (installSource === 'winget' && winget !== undefined) {
480
+ if (!installed) return null;
481
+ return winget?.version && semverNewer(installed, winget.version) ? winget.version : installed;
482
+ }
420
483
  if (!isBrewSource(installSource)) return npmLatest;
421
484
  if (!installed) return null;
422
485
  if (!brewOutdated) return installed;
@@ -99,6 +99,31 @@ export function readConfinedFileWithMetadata(base, path, { maxBytes = MAX_FILE_B
99
99
  } finally { try { closeSync(fd); } catch {} }
100
100
  }
101
101
 
102
+ /**
103
+ * At most `length` bytes of one regular file inside `base`, from byte `start`, with the file's size at the time
104
+ * of the read: opened and verified the same way (a link out of `base`, a FIFO or a folder is refused). For files
105
+ * read in pages while another process writes them (a background command's output).
106
+ * @returns {{ bytes: Buffer, size: number }}
107
+ */
108
+ export function readConfinedRange(base, path, { start = 0, length = 0 } = {}) {
109
+ const real = canonicalInside(base, path);
110
+ const fd = openExisting(real, constants.O_RDONLY);
111
+ try {
112
+ const st = verifyOpened(fd, real);
113
+ if (!st.isFile()) throw new PathConfineError(400, 'Not a regular file.');
114
+ const from = Math.max(0, Math.floor(Number(start) || 0));
115
+ const want = Math.max(0, Math.min(Math.floor(Number(length) || 0), MAX_FILE_BYTES, Math.max(0, st.size - from)));
116
+ const buf = Buffer.allocUnsafe(want);
117
+ let got = 0;
118
+ while (got < want) {
119
+ const n = readSync(fd, buf, got, want - got, from + got);
120
+ if (n <= 0) break;
121
+ got += n;
122
+ }
123
+ return { bytes: got === want ? buf : buf.subarray(0, got), size: st.size };
124
+ } finally { try { closeSync(fd); } catch {} }
125
+ }
126
+
102
127
  /**
103
128
  * A read stream of one regular file inside `base`, opened and verified the
104
129
  * same way (for files too large to read at once: transcripts).
@@ -63,6 +63,8 @@ export const RUN_EVENT_REASONS = Object.freeze({
63
63
  stopped: { kind: K.RUN_STOPPED, mailbox: true },
64
64
  completed: { kind: K.RUN_COMPLETED, mailbox: false },
65
65
  user_intervened: { kind: K.RUN_NOTICE, mailbox: true },
66
+ // A steer (assistant-dispatch.js steerRun): logged as a notice; the brain hears the user's own steer as user_intervened.
67
+ steered: { kind: K.RUN_NOTICE, mailbox: false },
66
68
  queue_started: { kind: K.RUN_PROGRESS, mailbox: true },
67
69
  suspended: { kind: K.RUN_PROGRESS, mailbox: true },
68
70
  resumed: { kind: K.RUN_PROGRESS, mailbox: true },
@@ -42,22 +42,42 @@ export function getDbPath() {
42
42
  return envPath;
43
43
  }
44
44
 
45
+ function ensureSessionCacheSchema(d) {
46
+ d.exec(SESSION_CACHE_SQL);
47
+ const columns = () => new Set(d.prepare('PRAGMA table_info(session_cache)').all().map(c => c.name));
48
+ const required = ['account_id', 'file_identity', 'content_fingerprint'];
49
+ const existing = columns();
50
+ for (const name of required) {
51
+ if (existing.has(name)) continue;
52
+ // Another connection may finish the same additive migration first.
53
+ try { d.exec(`ALTER TABLE session_cache ADD COLUMN ${name} TEXT`); }
54
+ catch (err) { if (!columns().has(name)) throw err; }
55
+ }
56
+ const verified = columns();
57
+ if (!required.every(name => verified.has(name))) throw new Error('Incomplete session_cache schema');
58
+ d.exec(SESSION_FTS_SQL);
59
+ }
60
+
45
61
  export function getDb() {
46
- if (!db) {
47
- const dbPath = getDbPath();
48
- const dir = dirname(dbPath);
49
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
62
+ if (db) return db;
63
+ const dir = dirname(getDbPath());
64
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
50
65
 
51
- db = sharedDb();
52
- try { db.exec(SESSION_CACHE_SQL); } catch { /* session_cache migration */ }
66
+ const opened = sharedDb();
67
+ const { timeout } = opened.prepare('PRAGMA busy_timeout').get();
68
+ // A retry of these synchronous ALTERs must not stack two 5-second busy waits.
69
+ try {
70
+ opened.exec(`PRAGMA busy_timeout = ${Math.min(timeout, 50)}`);
53
71
  try {
54
- const sessionCacheColumns = new Set(
55
- db.prepare('PRAGMA table_info(session_cache)').all().map((column) => String(column?.name || '')),
56
- );
57
- if (!sessionCacheColumns.has('account_id')) db.exec('ALTER TABLE session_cache ADD COLUMN account_id TEXT');
58
- } catch { /* additive session_cache migration */ }
59
- try { db.exec(SESSION_FTS_SQL); } catch { /* FTS5 may already exist */ }
72
+ ensureSessionCacheSchema(opened);
73
+ } catch (err) {
74
+ if (![5, 6].includes(err.errcode & 0xff)) throw err; // SQLITE_BUSY / SQLITE_LOCKED
75
+ ensureSessionCacheSchema(opened);
76
+ }
77
+ } finally {
78
+ opened.exec(`PRAGMA busy_timeout = ${timeout}`);
60
79
  }
80
+ db = opened;
61
81
  return db;
62
82
  }
63
83
 
@@ -75,6 +95,8 @@ CREATE TABLE IF NOT EXISTS session_cache (
75
95
  file_path TEXT,
76
96
  file_size INTEGER,
77
97
  file_mtime TEXT,
98
+ file_identity TEXT,
99
+ content_fingerprint TEXT,
78
100
  body_size INTEGER,
79
101
  deleted INTEGER DEFAULT 0,
80
102
  account_id TEXT,
@@ -817,13 +839,14 @@ export function upsertSessionCache(entry) {
817
839
  const d = getDb();
818
840
  d.prepare(`INSERT OR REPLACE INTO session_cache
819
841
  (session_id, provider, project, project_path, git_branch, first_prompt, message_count,
820
- created, modified, file_path, file_size, file_mtime, body_size, deleted, account_id)
821
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
842
+ created, modified, file_path, file_size, file_mtime, file_identity, content_fingerprint, body_size, deleted, account_id)
843
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(
822
844
  entry.session_id, entry.provider, entry.project || null, entry.project_path || null,
823
845
  entry.git_branch || null, entry.first_prompt || null, entry.message_count || 0,
824
846
  entry.created || null, entry.modified || null, entry.file_path || null,
825
- entry.file_size || null, entry.file_mtime || null, entry.body_size || 0,
826
- entry.deleted ? 1 : 0, entry.account_id || null,
847
+ entry.file_size || null, entry.file_mtime || null,
848
+ entry.file_identity || null, entry.content_fingerprint || null,
849
+ entry.body_size || 0, entry.deleted ? 1 : 0, entry.account_id || null,
827
850
  );
828
851
  }
829
852
 
@@ -309,8 +309,8 @@ export function createOpencodeCompletionEngine({
309
309
  // An OpenCode SynaBun does not drive (OpenCode 1, an OpenCode 2 older than the minimum) never starts; a version
310
310
  // not known here (a command line in Settings) is told by what answers.
311
311
  const detected = await detectOpencode();
312
- if (detected && typeof detected === 'object' && detected.supported === false && detected.major != null) {
313
- throw new Error(detected.reason || `OpenCode ${detected.major} is not supported`);
312
+ if (detected && typeof detected === 'object' && detected.supported === false && (detected.major != null || (!detected.path && !detected.commandLine))) {
313
+ throw new Error(detected.reason || (detected.major != null ? `OpenCode ${detected.major} is not supported` : 'OpenCode is not installed.'));
314
314
  }
315
315
  if (mine !== epoch) throw new Error('The completion server was stopped while it was starting');
316
316
  const password = passwordFrom === 'stdout' ? null : newPassword();
@@ -151,6 +151,20 @@ export function createGitBashManager({
151
151
  return out;
152
152
  }
153
153
 
154
+ // Prime the managed selection at manager creation. Requests keep using the
155
+ // cached result while an expired resolution waits for the next event-loop turn.
156
+ let managed = off || platform !== 'win32' ? null : copies().find(copy => copy.ok)?.git ?? null;
157
+ let managedCheckedAt = now();
158
+ let refreshTimer = null;
159
+ function scheduleRefresh() {
160
+ if (refreshTimer) return;
161
+ refreshTimer = setImmediate(() => {
162
+ refreshTimer = null;
163
+ try { refresh(); } catch (err) { log(`[git-bash] Refresh failed: ${err.message}`); }
164
+ });
165
+ refreshTimer.unref();
166
+ }
167
+
154
168
  function refresh() {
155
169
  let next;
156
170
  // macOS, Linux, the kill switch: nothing to look at (no settings read, no PATH walked).
@@ -160,7 +174,10 @@ export function createGitBashManager({
160
174
  try { settingsBash = settingsValue(); } catch { settingsBash = null; }
161
175
  let searchPath = '';
162
176
  try { searchPath = pathValue(); } catch { searchPath = pathEnvValue(env); }
163
- next = resolveGitBash({ platform, env, settingsValue: settingsBash, pathValue: searchPath, copies: copies(), ownRoots, ...(isFile ? { isFile } : {}) });
177
+ const checked = copies();
178
+ managed = checked.find(copy => copy.ok)?.git ?? null;
179
+ managedCheckedAt = now();
180
+ next = resolveGitBash({ platform, env, settingsValue: settingsBash, pathValue: searchPath, copies: checked, ownRoots, ...(isFile ? { isFile } : {}) });
164
181
  }
165
182
  const changed = !same(current, next);
166
183
  current = next;
@@ -256,9 +273,16 @@ export function createGitBashManager({
256
273
  return gitBashChildEnv(base, r, { platform });
257
274
  }
258
275
 
259
- function gitExecutable() {
276
+ function managedGitExecutable() {
277
+ if (off || platform !== 'win32') return null;
278
+ if (now() - managedCheckedAt > maxAgeMs) scheduleRefresh();
279
+ return managed;
280
+ }
281
+
282
+ function gitExecutable({ includeSystem = false } = {}) {
260
283
  const r = resolution();
261
- return r.passToClaude && r.git ? r.git : null;
284
+ if (!r.git) return null;
285
+ return (includeSystem || r.passToClaude) ? r.git : null;
262
286
  }
263
287
 
264
288
  function status() {
@@ -297,6 +321,7 @@ export function createGitBashManager({
297
321
  resolution,
298
322
  refresh,
299
323
  childEnv,
324
+ managedGitExecutable,
300
325
  gitExecutable,
301
326
  ensure,
302
327
  whenReady,
@@ -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
+ }