synabun 2.4.3 → 2.4.5

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 (177) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +66 -36
  4. package/docs/whatsapp.md +3 -3
  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 +12 -1
  21. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  22. package/mcp-server/dist/services/neural-interface.js +68 -17
  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 +19 -4
  30. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  31. package/mcp-server/dist/tools/agents.js +85 -17
  32. package/mcp-server/dist/tools/agents.js.map +1 -1
  33. package/mcp-server/dist/tools/browser-observe.d.ts +11 -0
  34. package/mcp-server/dist/tools/browser-observe.d.ts.map +1 -1
  35. package/mcp-server/dist/tools/browser-observe.js +113 -27
  36. package/mcp-server/dist/tools/browser-observe.js.map +1 -1
  37. package/mcp-server/dist/tools/browser-readers.d.ts +6 -0
  38. package/mcp-server/dist/tools/browser-readers.d.ts.map +1 -0
  39. package/mcp-server/dist/tools/browser-readers.js +17 -0
  40. package/mcp-server/dist/tools/browser-readers.js.map +1 -0
  41. package/mcp-server/dist/tools/remember.d.ts.map +1 -1
  42. package/mcp-server/dist/tools/remember.js +6 -2
  43. package/mcp-server/dist/tools/remember.js.map +1 -1
  44. package/mcp-server/dist/tools/youtube/analytics.d.ts +4 -0
  45. package/mcp-server/dist/tools/youtube/analytics.d.ts.map +1 -1
  46. package/mcp-server/dist/tools/youtube/analytics.js +25 -20
  47. package/mcp-server/dist/tools/youtube/analytics.js.map +1 -1
  48. package/mcp-server/dist/tools/youtube/helpers.d.ts +5 -1
  49. package/mcp-server/dist/tools/youtube/helpers.d.ts.map +1 -1
  50. package/mcp-server/dist/tools/youtube/helpers.js +7 -3
  51. package/mcp-server/dist/tools/youtube/helpers.js.map +1 -1
  52. package/mcp-server/dist/tools/youtube/navigate.d.ts +2 -0
  53. package/mcp-server/dist/tools/youtube/navigate.d.ts.map +1 -1
  54. package/mcp-server/dist/tools/youtube/navigate.js +5 -3
  55. package/mcp-server/dist/tools/youtube/navigate.js.map +1 -1
  56. package/mcp-server/dist/tools/youtube/playlist.js +2 -2
  57. package/mcp-server/dist/tools/youtube/playlist.js.map +1 -1
  58. package/mcp-server/dist/tools/youtube/readers.d.ts +4 -0
  59. package/mcp-server/dist/tools/youtube/readers.d.ts.map +1 -0
  60. package/mcp-server/dist/tools/youtube/readers.js +15 -0
  61. package/mcp-server/dist/tools/youtube/readers.js.map +1 -0
  62. package/mcp-server/package-lock.json +2 -2
  63. package/mcp-server/package.json +1 -1
  64. package/mcp-server/src/http.ts +8 -1
  65. package/mcp-server/src/services/identity.ts +5 -0
  66. package/mcp-server/src/services/memory-client.ts +32 -12
  67. package/mcp-server/src/services/memory-writer.ts +5 -2
  68. package/mcp-server/src/services/neural-interface.ts +67 -19
  69. package/mcp-server/src/services/typesafe-config.ts +268 -7
  70. package/mcp-server/src/tools/agents.ts +79 -17
  71. package/mcp-server/src/tools/browser-observe.ts +117 -28
  72. package/mcp-server/src/tools/browser-readers.ts +19 -0
  73. package/mcp-server/src/tools/remember.ts +6 -1
  74. package/mcp-server/src/tools/youtube/analytics.ts +26 -28
  75. package/mcp-server/src/tools/youtube/helpers.ts +8 -2
  76. package/mcp-server/src/tools/youtube/navigate.ts +6 -7
  77. package/mcp-server/src/tools/youtube/playlist.ts +2 -2
  78. package/mcp-server/src/tools/youtube/readers.ts +15 -0
  79. package/neural-interface/i18n/en.json +487 -8
  80. package/neural-interface/i18n/pt-BR.json +487 -8
  81. package/neural-interface/lib/agents-studio-api.js +7 -2
  82. package/neural-interface/lib/antigravity/home.js +43 -8
  83. package/neural-interface/lib/antigravity/tool-call.js +14 -0
  84. package/neural-interface/lib/assistant-api.js +90 -0
  85. package/neural-interface/lib/assistant-brains/antigravity.js +4 -2
  86. package/neural-interface/lib/assistant-brains/claude.js +10 -0
  87. package/neural-interface/lib/assistant-dispatch.js +276 -42
  88. package/neural-interface/lib/assistant-memory.js +3 -1
  89. package/neural-interface/lib/assistant-persona.js +14 -3
  90. package/neural-interface/lib/assistant-route-gate.js +11 -2
  91. package/neural-interface/lib/assistant-router.js +18 -8
  92. package/neural-interface/lib/assistant-runtime.js +103 -6
  93. package/neural-interface/lib/assistant-spilled-output.js +53 -0
  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-default.js +22 -2
  97. package/neural-interface/lib/browser-extension-adapter.js +221 -15
  98. package/neural-interface/lib/browser-extension-bridge.js +89 -9
  99. package/neural-interface/lib/browser-extension-folder.js +50 -11
  100. package/neural-interface/lib/browser-extension-package.js +6 -5
  101. package/neural-interface/lib/browser-extension-pin.json +15 -13
  102. package/neural-interface/lib/browser-extension-protocol.js +141 -14
  103. package/neural-interface/lib/browser-extension-setup.js +210 -40
  104. package/neural-interface/lib/browser-extension-update.js +104 -0
  105. package/neural-interface/lib/browser-extraction.js +38 -14
  106. package/neural-interface/lib/claude-bg-tasks.js +183 -0
  107. package/neural-interface/lib/claude-history.js +12 -1
  108. package/neural-interface/lib/confined-fs.js +25 -0
  109. package/neural-interface/lib/coordination/operations.js +2 -0
  110. package/neural-interface/lib/db.js +39 -16
  111. package/neural-interface/lib/editor-completion-opencode.js +2 -2
  112. package/neural-interface/lib/git-bash/manager.js +28 -3
  113. package/neural-interface/lib/git-status-runner.js +31 -3
  114. package/neural-interface/lib/loop-inventory.js +162 -0
  115. package/neural-interface/lib/loop-stall.js +74 -4
  116. package/neural-interface/lib/memory-session-capture.js +157 -66
  117. package/neural-interface/lib/native-loop-providers.js +73 -13
  118. package/neural-interface/lib/native-loop-runtime.js +3 -0
  119. package/neural-interface/lib/opencode-protocol.js +4 -2
  120. package/neural-interface/lib/peer-identity.js +62 -16
  121. package/neural-interface/lib/remote-policy.js +24 -7
  122. package/neural-interface/lib/session-cache-builder.js +66 -18
  123. package/neural-interface/lib/session-capture-gate.js +42 -0
  124. package/neural-interface/lib/session-indexer.js +28 -20
  125. package/neural-interface/lib/teams/README.md +22 -1
  126. package/neural-interface/lib/teams/api.js +79 -6
  127. package/neural-interface/lib/teams/index.js +2 -0
  128. package/neural-interface/lib/teams/recovery.js +68 -0
  129. package/neural-interface/lib/teams/scheduler.js +352 -31
  130. package/neural-interface/lib/teams/worktrees.js +123 -30
  131. package/neural-interface/lib/ui-blob-api.js +14 -5
  132. package/neural-interface/lib/ui-blob-store.js +302 -39
  133. package/neural-interface/package-lock.json +2 -2
  134. package/neural-interface/package.json +1 -1
  135. package/neural-interface/public/extension-setup.html +7 -2
  136. package/neural-interface/public/shared/agents/studio/ax-api.js +16 -0
  137. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +318 -13
  138. package/neural-interface/public/shared/agents/studio/ax-teams.js +141 -9
  139. package/neural-interface/public/shared/assistant/asst-agents-dock.js +4 -0
  140. package/neural-interface/public/shared/assistant/asst-api.js +42 -0
  141. package/neural-interface/public/shared/assistant/asst-composer.js +85 -12
  142. package/neural-interface/public/shared/assistant/asst-panel.js +285 -10
  143. package/neural-interface/public/shared/assistant/asst-render.js +205 -4
  144. package/neural-interface/public/shared/assistant/asst-scenes.js +12 -0
  145. package/neural-interface/public/shared/assistant/asst-sidepanel.js +18 -1
  146. package/neural-interface/public/shared/assistant/asst-state.js +241 -2
  147. package/neural-interface/public/shared/assistant/asst-steer.js +294 -0
  148. package/neural-interface/public/shared/assistant/asst-styles.js +20 -0
  149. package/neural-interface/public/shared/bg-tasks/bg-tasks-claude.js +147 -0
  150. package/neural-interface/public/shared/bg-tasks/bg-tasks-model.js +527 -0
  151. package/neural-interface/public/shared/bg-tasks/bg-tasks-panel.js +161 -0
  152. package/neural-interface/public/shared/bg-tasks/bg-tasks-view.js +508 -0
  153. package/neural-interface/public/shared/browser-extension-updates.js +90 -0
  154. package/neural-interface/public/shared/cp/cp-bg-tasks.js +130 -0
  155. package/neural-interface/public/shared/extension-setup/es-page.js +41 -15
  156. package/neural-interface/public/shared/extension-setup/es-view.js +51 -11
  157. package/neural-interface/public/shared/extension-update-view.js +34 -0
  158. package/neural-interface/public/shared/ocp-v2/ocp-v2-shell-logic.js +8 -4
  159. package/neural-interface/public/shared/settings/settings-ai-browser.js +23 -3
  160. package/neural-interface/public/shared/settings/settings-browser-extension.js +581 -197
  161. package/neural-interface/public/shared/settings/settings-extension-diagrams.js +116 -0
  162. package/neural-interface/public/shared/settings/settings-extension-guide.js +222 -0
  163. package/neural-interface/public/shared/settings/settings-extension-update.js +114 -0
  164. package/neural-interface/public/shared/settings/settings-ia.js +2 -2
  165. package/neural-interface/public/shared/settings/settings-shell.js +5 -0
  166. package/neural-interface/public/shared/styles.css +200 -13
  167. package/neural-interface/public/shared/ui-claude-panel.js +110 -1
  168. package/neural-interface/public/shared/ui-notifications.js +23 -4
  169. package/neural-interface/public/shared/ui-settings-entry.js +6 -0
  170. package/neural-interface/public/shared/ui-settings.js +48 -11
  171. package/neural-interface/public/shared/ui-tray-columns.js +9 -2
  172. package/neural-interface/public/shared/worker-end.js +18 -0
  173. package/neural-interface/scripts/patch-node-pty.mjs +151 -0
  174. package/neural-interface/scripts/rebuild-pty.js +10 -0
  175. package/neural-interface/server.js +503 -281
  176. package/npm-shrinkwrap.json +2 -2
  177. package/package.json +1 -1
@@ -548,16 +548,111 @@ export function createTeamWorktrees({ state, git, locks, setup: defaultSetup = n
548
548
  });
549
549
  }
550
550
 
551
+ /**
552
+ * The checks of a guarded removal, read only: every worktree is a linked worktree of its own on its branch, clean
553
+ * (nothing uncommitted, untracked files included), and every branch is merged into `target` (mergedInto), with
554
+ * `git branch -d`'s own criterion met for the ancestors it deletes. The same checks answer "could this go now"
555
+ * for a list (`onTarget`) and run again, under the repository's lock, right before anything is removed.
556
+ * → { items: [{ sliceId, path, branch, head, via }], checks: [{ name: 'clean'|'merged', ok, detail, sliceId, … }] }
557
+ */
558
+ async function guardedChecks(record, target) {
559
+ const teamId = record.teamId;
560
+ const checks = [];
561
+ const items = piecesOf(record.plan).map(sliceId => ({ sliceId, path: worktreePath(record.projectPath, teamId, sliceId), branch: sliceId === INTEGRATION_SLICE_ID ? integrationBranchName(teamId) : branchName(teamId, sliceId) }));
562
+ const registered = await listWorktrees(git, record.projectPath);
563
+ for (const item of items) {
564
+ let linked = false;
565
+ try { linked = lstatSync(join(item.path, '.git')).isFile() && !lstatSync(item.path).isSymbolicLink(); } catch {}
566
+ const valid = linked && await branchAt(git, item.path) === item.branch && registered.some(w => realOf(w.path) === realOf(item.path) && w.branch === item.branch && !w.locked) && registered.every(w => w.branch !== item.branch || realOf(w.path) === realOf(item.path));
567
+ checks.push({ name: 'clean', ok: !!valid, detail: `${item.path}: ${valid ? 'linked worktree verified' : 'not an unlocked linked worktree on its expected branch'}`, sliceId: item.sliceId, path: item.path, kind: 'worktree' });
568
+ if (valid) {
569
+ const changes = await changesOf(git, item.path);
570
+ checks.push({ name: 'clean', ok: changes !== null && changes.length === 0, detail: `${item.path}: ${changes === null ? 'status unavailable' : changes.map(c => c.path).join(', ') || 'clean'}`, sliceId: item.sliceId, path: item.path, kind: 'changes', files: (changes || []).map(c => c.path).slice(0, 50) });
571
+ }
572
+ // Merged: an ancestor of the target, or every commit beyond the base patch-equivalent to one in it
573
+ // (mergedInto). The head it checked is the one the deletion compares against.
574
+ const merged = await mergedInto(git, record.projectPath, item.branch, target, record.baseCommit);
575
+ item.head = merged.head;
576
+ item.via = merged.via;
577
+ checks.push({ name: 'merged', ok: merged.ok, detail: merged.detail, branch: item.branch, head: merged.head, via: merged.via, commits: merged.commits, sliceId: item.sliceId });
578
+ }
579
+ // branch -d checks the configured upstream, or HEAD when none exists.
580
+ // Verify that criterion too for the ancestors it deletes, so a different target checkout cannot cause
581
+ // partial removal. A patch-equivalent branch is deleted by compare-and-swap, which asks neither.
582
+ for (const item of items.filter((each) => each.via === 'ancestor')) {
583
+ const upstream = line(await git(['rev-parse', '--abbrev-ref', `${item.branch}@{upstream}`], { cwd: record.projectPath })) || 'HEAD';
584
+ const safe = (await git(['merge-base', '--is-ancestor', item.head, upstream], { cwd: record.projectPath })).ok;
585
+ checks.push({ name: 'merged', ok: safe, detail: `${item.branch}: safe branch -d against ${upstream}`, branch: item.branch, sliceId: item.sliceId });
586
+ }
587
+ return { items, checks };
588
+ }
589
+
590
+ /**
591
+ * Is everything a `ready` team joined on its base branch already: the commit SynaBun recorded as the integration
592
+ * head, and the integration branch as it is now (when somebody moved it)? Asked of git, never of the records.
593
+ * → { ok, detail, target, targetHead, head, live }
594
+ */
595
+ async function onTargetCheck(record) {
596
+ const cwd = record.projectPath;
597
+ const target = record.baseBranch;
598
+ const branch = integrationBranchName(record.teamId);
599
+ const no = (detail, extra = {}) => ({ ok: false, detail, target: target || null, ...extra });
600
+ if (!target) return no('The project was on no branch when the team was created, so there is no base branch to compare with.');
601
+ const targetHead = await commitOf(git, cwd, `refs/heads/${target}`);
602
+ if (!targetHead) return no(`The base branch ${target} is not there.`);
603
+ const head = record.integration?.head || null;
604
+ const live = await commitOf(git, cwd, `refs/heads/${branch}`);
605
+ if (!head) return no('No integration head is recorded for this team.', { targetHead });
606
+ if (!live) return no(`${branch} is not there.`, { targetHead, head });
607
+ const on = async (commit) => commit === targetHead || (await git(['merge-base', '--is-ancestor', commit, targetHead], { cwd })).ok;
608
+ if (!(await on(head))) return no(`${target} does not have the team's integration head ${head.slice(0, 12)}: it has not landed.`, { targetHead, head, live });
609
+ if (live !== head && !(await on(live))) return no(`${branch} moved to ${live.slice(0, 12)}, which ${target} does not have.`, { targetHead, head, live });
610
+ return { ok: true, detail: `${target} has ${branch} (${head.slice(0, 12)}).`, target, targetHead, head, live };
611
+ }
612
+
613
+ /**
614
+ * A `ready` code team whose joined work is on its base branch already (merged outside `land`, its worktrees and
615
+ * branches still there): where, and whether its worktrees and branches could go now with nothing lost (`clean`:
616
+ * every guarded check passes). Read only and without a lock: a list asks it. Null for any other team, and when git
617
+ * does not show the work on the base branch. Never removes anything: `remove(teamId, { guarded: true,
618
+ * mergedOutside: true })` asks it all again, under the lock, before it does.
619
+ *
620
+ * @returns {Promise<null | { branch: string, head: string, targetHead: string, live: string, moved: boolean,
621
+ * clean: boolean, dirty: { sliceId: string, path: string, files: string[] }[],
622
+ * unmerged: { sliceId: string, branch: string, commits: string[] }[], other: string[] }>}
623
+ */
624
+ async function onTarget(teamId) {
625
+ const record = await get(teamId);
626
+ if (!record || record.plan.readOnly || record.removed || record.state !== 'ready' || !isDirectory(record.projectPath)) return null;
627
+ const on = await onTargetCheck(record);
628
+ if (!on.ok) return null;
629
+ const { checks } = await guardedChecks(record, on.target);
630
+ const failed = checks.filter((check) => !check.ok);
631
+ // Uncommitted files git listed; commits the base branch lacks; anything else (a status git could not read, a
632
+ // worktree that is not where SynaBun left it, a branch that is gone) as git's own words.
633
+ const isDirty = (check) => check.kind === 'changes' && Array.isArray(check.files) && check.files.length > 0;
634
+ const isUnmerged = (check) => check.name === 'merged' && Array.isArray(check.commits) && check.commits.length > 0;
635
+ const dirty = failed.filter(isDirty).map((check) => ({ sliceId: check.sliceId, path: check.path, files: check.files }));
636
+ const unmerged = failed.filter(isUnmerged).map((check) => ({ sliceId: check.sliceId, branch: check.branch, commits: check.commits.slice(0, 20) }));
637
+ const other = failed.filter((check) => !isDirty(check) && !isUnmerged(check)).map((check) => check.detail).slice(0, 10);
638
+ return { branch: on.target, head: on.head, targetHead: on.targetHead, live: on.live, moved: on.live !== on.head, clean: failed.length === 0, dirty, unmerged, other };
639
+ }
640
+
551
641
  /**
552
642
  * Remove a team's worktrees and branches. Only after a landing, or with `discard: true`. A worktree with
553
643
  * uncommitted changes and a branch whose commits are nowhere else are kept and reported, unless `force: true`.
644
+ * `guarded: true` removes all or nothing, after every check passed (guardedChecks); with `mergedOutside: true` it
645
+ * takes a `ready` team whose work is on its base branch already, records that landing (`landed.external`) and
646
+ * removes its worktrees and branches the same way.
554
647
  *
555
648
  * @returns {Promise<{ ok: true, complete: boolean, removed: object[], kept: object[] } | { ok: false, code: string }>}
556
649
  */
557
- async function remove(teamId, { discard = false, force = false, guarded = false, checkOnly = false } = {}) {
650
+ async function remove(teamId, { discard = false, force = false, guarded = false, checkOnly = false, mergedOutside = false } = {}) {
558
651
  const record = await get(teamId);
559
652
  if (!record) return refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is recorded.`);
560
653
  if (guarded && record.plan.readOnly) return refuse('TEAM_NOT_LANDED', 'Read-only teams cannot land.', { checks: [{ name: 'landed', ok: false, detail: 'Read-only team' }] });
654
+ if (mergedOutside && !guarded) return refuse('INVALID_OPTIONS', 'mergedOutside is a guarded removal.');
655
+ if (mergedOutside && (record.state !== 'ready' || record.removed)) return refuse('TEAM_NOT_READY', `Team "${teamId}" is ${record.removed ? 'removed' : record.state}: only a ready team whose work is on its base branch already is cleaned up this way.`, { state: record.state, checks: [{ name: 'on-target', ok: false, detail: `Team state: ${record.state}` }] });
561
656
  if (record.plan.readOnly) {
562
657
  const removed = [], kept = [];
563
658
  for (const slice of record.plan.slices) {
@@ -570,42 +665,40 @@ export function createTeamWorktrees({ state, git, locks, setup: defaultSetup = n
570
665
  }
571
666
  if (record.state === 'integrating' || record.state === 'landing' || record.state === 'creating') return refuse('TEAM_NEEDS_RECOVERY', `Team "${teamId}" is recorded as ${record.state}: run recover() before removing it.`, { state: record.state });
572
667
  const landed = record.state === 'merged';
573
- if (!landed && !discard && !record.plan.readOnly && !checkOnly) return refuse('TEAM_NOT_LANDED', `Team "${teamId}" has not landed: its result is on ${integrationBranchName(teamId)}. Land it first, or pass discard: true to give its work up.`, { state: record.state });
668
+ if (!landed && !discard && !record.plan.readOnly && !checkOnly && !mergedOutside) return refuse('TEAM_NOT_LANDED', `Team "${teamId}" has not landed: its result is on ${integrationBranchName(teamId)}. Land it first, or pass discard: true to give its work up.`, { state: record.state });
574
669
  if (!isDirectory(record.projectPath)) return refuse('PROJECT_NOT_FOUND', `${record.projectPath} is not a folder.`);
575
670
 
576
671
  return locks.run(repoKey(record.projectPath), async () => {
577
672
  if (guarded) {
673
+ // Merged outside `land`: what the integration branch has must be on the base branch already (asked again
674
+ // here, under the lock), and the base branch is the target every other check measures against.
675
+ // The record as it is now, under the lock: what is checked and what is recorded are the same team.
676
+ const subject = mergedOutside ? await get(teamId) : record;
677
+ if (mergedOutside && (subject?.state !== 'ready' || subject.removed)) return refuse('TEAM_NOT_READY', `Team "${teamId}" is ${subject?.removed ? 'removed' : subject?.state || 'gone'} now: nothing was removed.`, { state: subject?.state || null, checks: [{ name: 'on-target', ok: false, detail: `Team state: ${subject?.state || 'gone'}` }] });
678
+ const target = mergedOutside ? subject.baseBranch : record.landed?.targetBranch;
578
679
  const checks = [];
579
- const items = piecesOf(record.plan).map(sliceId => ({ sliceId, path: worktreePath(record.projectPath, teamId, sliceId), branch: sliceId === INTEGRATION_SLICE_ID ? integrationBranchName(teamId) : branchName(teamId, sliceId) }));
580
- const registered = await listWorktrees(git, record.projectPath);
581
- const target = record.landed?.targetBranch;
582
- for (const item of items) {
583
- let linked = false;
584
- try { linked = lstatSync(join(item.path, '.git')).isFile() && !lstatSync(item.path).isSymbolicLink(); } catch {}
585
- const valid = linked && await branchAt(git, item.path) === item.branch && registered.some(w => realOf(w.path) === realOf(item.path) && w.branch === item.branch && !w.locked) && registered.every(w => w.branch !== item.branch || realOf(w.path) === realOf(item.path));
586
- checks.push({ name: 'clean', ok: !!valid, detail: `${item.path}: ${valid ? 'linked worktree verified' : 'not an unlocked linked worktree on its expected branch'}` });
587
- if (valid) {
588
- const changes = await changesOf(git, item.path);
589
- checks.push({ name: 'clean', ok: changes !== null && changes.length === 0, detail: `${item.path}: ${changes === null ? 'status unavailable' : changes.map(c => c.path).join(', ') || 'clean'}` });
590
- }
591
- // Merged: an ancestor of the target, or every commit beyond the base patch-equivalent to one in it
592
- // (mergedInto). The head it checked is the one the deletion compares against.
593
- const merged = await mergedInto(git, record.projectPath, item.branch, target, record.baseCommit);
594
- item.head = merged.head;
595
- item.via = merged.via;
596
- checks.push({ name: 'merged', ok: merged.ok, detail: merged.detail, branch: item.branch, head: merged.head, via: merged.via, commits: merged.commits });
597
- }
598
- // branch -d checks the configured upstream, or HEAD when none exists.
599
- // Verify that criterion too for the ancestors it deletes, so a different target checkout cannot cause
600
- // partial removal. A patch-equivalent branch is deleted by compare-and-swap, which asks neither.
601
- for (const item of items.filter((each) => each.via === 'ancestor')) {
602
- const upstream = line(await git(['rev-parse', '--abbrev-ref', `${item.branch}@{upstream}`], { cwd: record.projectPath })) || 'HEAD';
603
- const safe = (await git(['merge-base', '--is-ancestor', item.head, upstream], { cwd: record.projectPath })).ok;
604
- checks.push({ name: 'merged', ok: safe, detail: `${item.branch}: safe branch -d against ${upstream}` });
680
+ if (mergedOutside) {
681
+ const on = await onTargetCheck(subject);
682
+ checks.push({ name: 'on-target', ok: on.ok, detail: on.detail });
683
+ if (!on.ok) return refuse('NOT_ON_TARGET', on.detail, { checks });
605
684
  }
685
+ const { items, checks: guardedList } = await guardedChecks(subject, target);
686
+ checks.push(...guardedList);
606
687
  const failed = checks.find(c => !c.ok);
607
688
  if (failed) return refuse(failed.name === 'merged' ? 'BRANCH_NOT_MERGED' : 'WORKTREE_DIRTY', failed.detail, { checks });
608
689
  if (checkOnly) return { ok: true, checks };
690
+ // The team's work is on its base branch: that is a landing, made by somebody else. It is written before
691
+ // anything is removed, so a stop half-way leaves a team that says where its work is.
692
+ let landedOutside = null;
693
+ if (mergedOutside) {
694
+ const tests = subject.integration.tests;
695
+ const head = subject.integration.head;
696
+ landedOutside = {
697
+ targetBranch: target, mode: null, from: null, to: head, integrationHead: head, mergeCommit: null, checkout: null,
698
+ files: null, at: now(), partial: false, tested: !!tests && tests.ok === true && tests.commit === head, external: true,
699
+ };
700
+ await state.writeTeam(teamId, 'merged', { landing: null, landed: landedOutside });
701
+ }
609
702
  // All checks precede all mutations. The branches are settled first, in one atomic ref transaction: every
610
703
  // ancestor is verified at the head that was checked, and every patch-equivalent branch is deleted only if it
611
704
  // is still at that head (`git branch -d` refuses those, and `-D` is never used). Such a branch is checked
@@ -660,7 +753,7 @@ export function createTeamWorktrees({ state, git, locks, setup: defaultSetup = n
660
753
  if (!pruned.ok) throw new Error(`Cleanup prune failed: ${gitSaid(pruned)}`);
661
754
  try { rmdirSync(join(worktreesRoot(record.projectPath), teamId)); } catch (error) { if (error.code !== 'ENOENT' && error.code !== 'ENOTEMPTY') throw error; }
662
755
  await state.writeTeam(teamId, 'merged', { removed: true, removal: { at: now(), force: false, removed, kept: [] } });
663
- return { ok: true, complete: true, removed, checks };
756
+ return { ok: true, complete: true, removed, checks, ...(landedOutside ? { landed: landedOutside } : {}) };
664
757
  }
665
758
  const registered = await listWorktrees(git, record.projectPath);
666
759
  const integration = record.plan.readOnly ? {} : await pieceInfo(record, INTEGRATION_SLICE_ID, registered);
@@ -745,7 +838,7 @@ export function createTeamWorktrees({ state, git, locks, setup: defaultSetup = n
745
838
  });
746
839
  }
747
840
 
748
- return { create, get, list, inspect, startSlice, finishReadOnlySlice, remove, prune, materialize, unmake, pieceInfo, placeOf, collisions };
841
+ return { create, get, list, inspect, onTarget, startSlice, finishReadOnlySlice, remove, prune, materialize, unmake, pieceInfo, placeOf, collisions };
749
842
  }
750
843
 
751
844
  /** A test command as it is stored: text, a list of arguments, or null. `false` for anything else. */
@@ -53,11 +53,19 @@ export function createUiBlobRouter({ namespaces, store, ownerNamespace = null, o
53
53
  return ns;
54
54
  }
55
55
 
56
- router.get('/api/ui-blobs/:ns', (req, res) => {
56
+ router.get('/api/ui-blobs/:ns', async (req, res) => {
57
57
  const ns = namespaceOf(req, res);
58
58
  if (!ns) return;
59
- try { res.json(store.getNamespace(ns)); }
60
- catch (err) { res.status(500).json({ error: err.message }); }
59
+ try {
60
+ if (typeof store.getNamespaceJsonAsync === 'function') {
61
+ const json = await store.getNamespaceJsonAsync(ns);
62
+ res.type('application/json').send(json);
63
+ } else if (typeof store.getNamespaceAsync === 'function') {
64
+ res.json(await store.getNamespaceAsync(ns));
65
+ } else {
66
+ res.json(store.getNamespace(ns));
67
+ }
68
+ } catch (err) { res.status(500).json({ error: err.message }); }
61
69
  });
62
70
 
63
71
  router.get('/api/ui-blobs/:ns/:id', (req, res) => {
@@ -83,8 +91,9 @@ export function createUiBlobRouter({ namespaces, store, ownerNamespace = null, o
83
91
  order.applied(ns, req.params.id, revision);
84
92
  const maxEntries = parseInt(req.query.maxEntries, 10) || 0;
85
93
  const maxChars = parseInt(req.query.maxChars, 10) || 0;
86
- let evicted = [];
87
- if (maxEntries || maxChars) evicted = store.prune(ns, { maxEntries, maxTotalChars: maxChars });
94
+ const evicted = maxEntries > 0 || maxChars > 0
95
+ ? store.prune(ns, { maxEntries, maxTotalChars: maxChars })
96
+ : [];
88
97
  res.json({ ok: true, evicted });
89
98
  } catch (err) { res.status(500).json({ error: err.message }); }
90
99
  }
@@ -12,13 +12,101 @@
12
12
  // HTML churn would bloat its WAL and backups for no benefit.
13
13
 
14
14
  import { DatabaseSync } from 'node:sqlite';
15
+ import { Worker, isMainThread, parentPort, workerData } from 'node:worker_threads';
16
+ import { setTimeout, clearTimeout } from 'node:timers';
15
17
  import { dirname } from 'path';
16
18
  import { existsSync, mkdirSync } from 'fs';
17
19
 
20
+ const MAX_TRIM_ROWS = 128;
21
+ const DELETE_BATCH = 32;
22
+ const DEFAULT_BACKFILL_BATCH = 16;
23
+ const NAMESPACE_READ_PAGE = 25;
24
+ const WORKER_IDLE_MS = 5000;
25
+
18
26
  let db = null;
19
27
  let dbPath = null;
28
+ let backfillTimer = null;
29
+ let recountThrough = 0;
30
+ let readerState = null;
31
+ let readerJobSeq = 0;
32
+
33
+ function terminateReaderWorker(reason = 'ui-blob-store closed') {
34
+ const current = readerState;
35
+ if (!current) return;
36
+ readerState = null;
37
+ if (current.idleTimer) { clearTimeout(current.idleTimer); current.idleTimer = null; }
38
+ if (current.jobs.size) {
39
+ const err = new Error(reason);
40
+ for (const job of current.jobs.values()) job.reject(err);
41
+ current.jobs.clear();
42
+ }
43
+ try { void current.worker.terminate(); } catch {}
44
+ }
45
+
46
+ function ensureSchema(d) {
47
+ d.exec(`
48
+ CREATE TABLE IF NOT EXISTS ui_blobs (
49
+ ns TEXT NOT NULL, id TEXT NOT NULL, value TEXT NOT NULL,
50
+ value_chars INTEGER, updated_at INTEGER NOT NULL, PRIMARY KEY (ns, id)
51
+ );
52
+ CREATE TABLE IF NOT EXISTS ui_blob_meta (k TEXT PRIMARY KEY, v INTEGER NOT NULL);
53
+ `);
54
+ if (!d.prepare('PRAGMA table_info(ui_blobs)').all().some(col => col.name === 'value_chars')) {
55
+ d.exec('ALTER TABLE ui_blobs ADD COLUMN value_chars INTEGER');
56
+ }
57
+ d.exec(`
58
+ DROP TRIGGER IF EXISTS trg_ui_blobs_ai_chars;
59
+ DROP TRIGGER IF EXISTS trg_ui_blobs_au_chars;
60
+ DROP TRIGGER IF EXISTS trg_ui_blobs_au_rev;
61
+ DROP INDEX IF EXISTS idx_ui_blobs_ns_updated;
62
+ DROP INDEX IF EXISTS idx_ui_blobs_null_chars;
63
+ CREATE INDEX IF NOT EXISTS idx_ui_blobs_trim ON ui_blobs(ns, updated_at DESC, id DESC, value_chars);
64
+ INSERT OR IGNORE INTO ui_blob_meta (k, v)
65
+ SELECT 'recount_through', COALESCE(MAX(rowid), 0) FROM ui_blobs;
66
+ `);
67
+ return d.prepare("SELECT v FROM ui_blob_meta WHERE k = 'recount_through'").get().v;
68
+ }
69
+
70
+ // Recount pre-upgrade rows (both NULL and old UTF-16 counts). The rowid keyset and
71
+ // its checkpoint commit together. New writes already use SQLite LENGTH().
72
+ export function backfillBlobValueCharsBatch(limit = DEFAULT_BACKFILL_BATCH) {
73
+ if (!db || !recountThrough) return 0;
74
+ const batch = Math.max(1, Math.min(DEFAULT_BACKFILL_BATCH, Math.trunc(limit) || DEFAULT_BACKFILL_BATCH));
75
+ const rows = db.prepare('SELECT rowid FROM ui_blobs WHERE rowid <= ? ORDER BY rowid DESC LIMIT ?')
76
+ .all(recountThrough, batch);
77
+ const next = rows.length === batch ? Math.max(0, rows.at(-1).rowid - 1) : 0;
78
+ db.exec('BEGIN');
79
+ try {
80
+ if (rows.length) {
81
+ db.prepare('UPDATE ui_blobs SET value_chars = LENGTH(value) WHERE rowid BETWEEN ? AND ?')
82
+ .run(rows.at(-1).rowid, rows[0].rowid);
83
+ }
84
+ db.prepare("UPDATE ui_blob_meta SET v = ? WHERE k = 'recount_through'").run(next);
85
+ db.exec('COMMIT');
86
+ recountThrough = next;
87
+ return rows.length;
88
+ } catch (err) {
89
+ db.exec('ROLLBACK');
90
+ throw err;
91
+ }
92
+ }
93
+
94
+ function scheduleBackfill() {
95
+ if (!recountThrough) return;
96
+ backfillTimer = setTimeout(() => {
97
+ try {
98
+ backfillBlobValueCharsBatch();
99
+ } catch (err) {
100
+ console.warn('[ui-blobs] Character recount paused until next open:', err.message);
101
+ return;
102
+ }
103
+ scheduleBackfill();
104
+ }, 25);
105
+ backfillTimer.unref();
106
+ }
20
107
 
21
108
  export function initBlobStore(path) {
109
+ if (db && dbPath !== path) closeBlobStore();
22
110
  dbPath = path;
23
111
  return getBlobDb();
24
112
  }
@@ -26,19 +114,24 @@ export function initBlobStore(path) {
26
114
  function getBlobDb() {
27
115
  if (!db) {
28
116
  if (!dbPath) throw new Error('ui-blob-store: initBlobStore(path) not called');
29
- const dir = dirname(dbPath);
30
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
31
- db = new DatabaseSync(dbPath);
32
- db.exec('PRAGMA journal_mode = WAL');
33
- db.exec('PRAGMA busy_timeout = 5000');
34
- db.exec(`
35
- CREATE TABLE IF NOT EXISTS ui_blobs (
36
- ns TEXT NOT NULL,
37
- id TEXT NOT NULL,
38
- value TEXT NOT NULL,
39
- updated_at INTEGER NOT NULL,
40
- PRIMARY KEY (ns, id)
41
- );`);
117
+ if (dbPath !== ':memory:') {
118
+ const dir = dirname(dbPath);
119
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
120
+ }
121
+ const opened = new DatabaseSync(dbPath);
122
+ try {
123
+ if (dbPath !== ':memory:') opened.exec('PRAGMA journal_mode = WAL');
124
+ opened.exec('PRAGMA busy_timeout = 5000');
125
+ opened.exec('BEGIN');
126
+ recountThrough = ensureSchema(opened);
127
+ opened.exec('COMMIT');
128
+ } catch (err) {
129
+ try { opened.close(); } catch {}
130
+ throw err;
131
+ }
132
+ // Publish the connection only after PRAGMAs and ensureSchema() succeed.
133
+ db = opened;
134
+ scheduleBackfill();
42
135
  }
43
136
  return db;
44
137
  }
@@ -53,6 +146,106 @@ export function blobGetNamespace(ns) {
53
146
  return out;
54
147
  }
55
148
 
149
+ function buildNamespaceJsonSync(d, ns, pageSize = NAMESPACE_READ_PAGE) {
150
+ const firstStmt = d.prepare('SELECT id, value FROM ui_blobs WHERE ns = ? ORDER BY id ASC LIMIT ?');
151
+ const nextStmt = d.prepare('SELECT id, value FROM ui_blobs WHERE ns = ? AND id > ? ORDER BY id ASC LIMIT ?');
152
+ let lastId = null;
153
+ const parts = ['{'];
154
+ let first = true;
155
+ for (;;) {
156
+ const rows = lastId === null ? firstStmt.all(ns, pageSize) : nextStmt.all(ns, lastId, pageSize);
157
+ if (!rows.length) break;
158
+ for (const row of rows) {
159
+ lastId = row.id;
160
+ try {
161
+ const parsed = JSON.parse(row.value);
162
+ const encoded = JSON.stringify(parsed);
163
+ if (encoded === undefined) continue;
164
+ parts.push(`${first ? '' : ','}${JSON.stringify(row.id)}:${encoded}`);
165
+ first = false;
166
+ } catch { /* skip corrupt row */ }
167
+ }
168
+ if (rows.length < pageSize) break;
169
+ }
170
+ parts.push('}');
171
+ return parts.join('');
172
+ }
173
+
174
+ function getOrCreateReaderWorker(targetPath) {
175
+ if (readerState && readerState.path !== targetPath) {
176
+ terminateReaderWorker('ui-blob-store path changed');
177
+ }
178
+ if (!readerState) {
179
+ const worker = new Worker(new URL(import.meta.url), {
180
+ workerData: { uiBlobReader: true },
181
+ execArgv: process.execArgv.filter((arg) => arg === '--experimental-sqlite'),
182
+ });
183
+ const state = { worker, path: targetPath, jobs: new Map(), idleTimer: null };
184
+ readerState = state;
185
+ worker.on('message', (msg) => {
186
+ const job = state.jobs.get(msg.id);
187
+ if (!job) return;
188
+ state.jobs.delete(msg.id);
189
+ if (state.jobs.size === 0 && readerState === state) {
190
+ worker.unref();
191
+ if (state.idleTimer) clearTimeout(state.idleTimer);
192
+ state.idleTimer = setTimeout(() => {
193
+ state.idleTimer = null;
194
+ if (readerState === state && state.jobs.size === 0) {
195
+ terminateReaderWorker('idle');
196
+ }
197
+ }, WORKER_IDLE_MS);
198
+ state.idleTimer.unref?.();
199
+ }
200
+ if (msg.error) job.reject(new Error(msg.error));
201
+ else job.resolve(Buffer.from(msg.bytes.buffer, msg.bytes.byteOffset, msg.bytes.byteLength));
202
+ });
203
+ const onWorkerEnd = (err) => {
204
+ if (state.idleTimer) { clearTimeout(state.idleTimer); state.idleTimer = null; }
205
+ if (readerState === state) readerState = null;
206
+ if (state.jobs.size) {
207
+ const error = err || new Error('ui-blob reader worker exited before replying');
208
+ for (const job of state.jobs.values()) job.reject(error);
209
+ state.jobs.clear();
210
+ }
211
+ };
212
+ worker.once('error', onWorkerEnd);
213
+ worker.once('exit', () => onWorkerEnd());
214
+ }
215
+ return readerState;
216
+ }
217
+
218
+ /**
219
+ * Read and serialize an entire namespace as a UTF-8 JSON Buffer off the event loop
220
+ * (in a short-lived worker thread for file-backed DBs).
221
+ * Preserves the exact `{ [id]: value }` response contract for GET /api/ui-blobs/:ns.
222
+ */
223
+ export async function blobGetNamespaceJsonAsync(ns) {
224
+ const d = getBlobDb();
225
+ if (!dbPath || dbPath === ':memory:') {
226
+ return Buffer.from(buildNamespaceJsonSync(d, ns));
227
+ }
228
+ const targetPath = dbPath;
229
+ const state = getOrCreateReaderWorker(targetPath);
230
+ if (state.idleTimer) { clearTimeout(state.idleTimer); state.idleTimer = null; }
231
+ state.worker.ref();
232
+ const id = ++readerJobSeq;
233
+ return new Promise((resolve, reject) => {
234
+ state.jobs.set(id, { resolve, reject });
235
+ try {
236
+ state.worker.postMessage({ id, dbPath: targetPath, ns });
237
+ } catch (err) {
238
+ state.jobs.delete(id);
239
+ reject(err);
240
+ }
241
+ });
242
+ }
243
+
244
+ export async function blobGetNamespaceAsync(ns) {
245
+ const buf = await blobGetNamespaceJsonAsync(ns);
246
+ return JSON.parse(buf.toString('utf8'));
247
+ }
248
+
56
249
  export function blobGet(ns, id) {
57
250
  const d = getBlobDb();
58
251
  const row = d.prepare('SELECT value FROM ui_blobs WHERE ns = ? AND id = ?').get(ns, id);
@@ -62,15 +255,20 @@ export function blobGet(ns, id) {
62
255
 
63
256
  export function blobPut(ns, id, value) {
64
257
  const d = getBlobDb();
258
+ const serialized = JSON.stringify(value);
259
+ // Keep the last write newest through millisecond ties and backwards clock steps.
65
260
  d.prepare(`
66
- INSERT INTO ui_blobs (ns, id, value, updated_at) VALUES (?, ?, ?, ?)
67
- ON CONFLICT(ns, id) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at
68
- `).run(ns, id, JSON.stringify(value), Date.now());
261
+ INSERT INTO ui_blobs (ns, id, value, value_chars, updated_at)
262
+ VALUES (?, ?, ?, LENGTH(?), MAX(?, COALESCE((
263
+ SELECT updated_at + 1 FROM ui_blobs WHERE ns = ? ORDER BY updated_at DESC LIMIT 1
264
+ ), 0)))
265
+ ON CONFLICT(ns, id) DO UPDATE SET
266
+ value = excluded.value, value_chars = excluded.value_chars, updated_at = excluded.updated_at
267
+ `).run(ns, id, serialized, serialized, Date.now(), ns);
69
268
  }
70
269
 
71
270
  export function blobDelete(ns, id) {
72
- const d = getBlobDb();
73
- d.prepare('DELETE FROM ui_blobs WHERE ns = ? AND id = ?').run(ns, id);
271
+ getBlobDb().prepare('DELETE FROM ui_blobs WHERE ns = ? AND id = ?').run(ns, id);
74
272
  }
75
273
 
76
274
  // ── Which of a page's requests for one entry is the newer ──
@@ -142,33 +340,98 @@ export function createBlobOrder({ now = Date.now, ttlMs = BLOB_ORDER_TTL_MS, max
142
340
  }
143
341
 
144
342
  export function blobClearNamespace(ns) {
145
- const d = getBlobDb();
146
- const result = d.prepare('DELETE FROM ui_blobs WHERE ns = ?').run(ns);
147
- return Number(result?.changes || 0);
343
+ return getBlobDb().prepare('DELETE FROM ui_blobs WHERE ns = ?').run(ns).changes;
148
344
  }
149
345
 
150
- // Evict oldest entries beyond maxEntries and/or beyond maxTotalChars of
151
- // cumulative value length (newest kept). Returns the evicted ids.
346
+ // Keep the newest entry even if it alone exceeds the character budget.
152
347
  export function blobPrune(ns, { maxEntries = 0, maxTotalChars = 0 } = {}) {
348
+ if (!(maxEntries > 0 || maxTotalChars > 0)) return [];
153
349
  const d = getBlobDb();
154
- const rows = d.prepare(
155
- 'SELECT id, LENGTH(value) AS len FROM ui_blobs WHERE ns = ? ORDER BY updated_at DESC'
156
- ).all(ns);
157
- const evicted = [];
158
- let totalChars = 0;
159
- rows.forEach((row, i) => {
160
- totalChars += row.len;
161
- const overCount = maxEntries > 0 && i >= maxEntries;
162
- const overChars = maxTotalChars > 0 && totalChars > maxTotalChars && i > 0;
163
- if (overCount || overChars) evicted.push(row.id);
164
- });
165
- if (evicted.length) {
166
- const del = d.prepare('DELETE FROM ui_blobs WHERE ns = ? AND id = ?');
167
- for (const id of evicted) del.run(ns, id);
350
+ let cutoff;
351
+ if (maxTotalChars > 0) {
352
+ // Only an uncounted legacy value needs a table lookup. Normal writes trim
353
+ // straight from the covering index and stop as soon as either cap is reached.
354
+ const rows = d.prepare(`
355
+ SELECT id, updated_at, CASE WHEN rowid <= ? OR value_chars IS NULL
356
+ THEN (SELECT LENGTH(legacy.value) FROM ui_blobs AS legacy WHERE legacy.rowid = b.rowid)
357
+ ELSE value_chars END AS chars
358
+ FROM ui_blobs AS b WHERE ns = ? ORDER BY updated_at DESC, id DESC LIMIT ?
359
+ `).iterate(recountThrough, ns, MAX_TRIM_ROWS);
360
+ let total = 0;
361
+ let count = 0;
362
+ for (const row of rows) {
363
+ total += row.chars;
364
+ if (count && total > maxTotalChars) break;
365
+ cutoff = row;
366
+ count++;
367
+ if (total >= maxTotalChars || count === maxEntries) break;
368
+ if (count === MAX_TRIM_ROWS) {
369
+ console.debug('[ui-blobs] Character trim reached the row budget for', ns);
370
+ // No character cutoff proven in this scan. A separate count cap still applies.
371
+ cutoff = null;
372
+ }
373
+ }
374
+ }
375
+ if (!cutoff && maxEntries > 0) {
376
+ cutoff = d.prepare(`
377
+ SELECT updated_at, id FROM ui_blobs WHERE ns = ?
378
+ ORDER BY updated_at DESC, id DESC LIMIT 1 OFFSET ?
379
+ `).get(ns, Math.min(Number.MAX_SAFE_INTEGER, maxEntries) - 1);
380
+ }
381
+ if (!cutoff) return [];
382
+ const victims = d.prepare(`
383
+ SELECT id FROM ui_blobs WHERE ns = ? AND (updated_at, id) < (?, ?)
384
+ ORDER BY updated_at, id LIMIT ?
385
+ `).all(ns, cutoff.updated_at, cutoff.id, MAX_TRIM_ROWS + 1);
386
+ if (victims.length > MAX_TRIM_ROWS) {
387
+ victims.pop();
388
+ console.debug('[ui-blobs] Remaining evictions deferred to next write for', ns);
168
389
  }
169
- return evicted;
390
+ const ids = victims.map(row => row.id);
391
+ if (ids.length) {
392
+ d.exec('BEGIN');
393
+ try {
394
+ for (let i = 0; i < ids.length; i += DELETE_BATCH) {
395
+ const batch = ids.slice(i, i + DELETE_BATCH);
396
+ const params = batch.map(() => '?').join(',');
397
+ d.prepare(`DELETE FROM ui_blobs WHERE ns = ? AND id IN (${params})`).run(ns, ...batch);
398
+ }
399
+ d.exec('COMMIT');
400
+ } catch (err) {
401
+ d.exec('ROLLBACK');
402
+ throw err;
403
+ }
404
+ }
405
+ return ids;
170
406
  }
171
407
 
172
408
  export function closeBlobStore() {
173
- if (db) { try { db.close(); } catch {} db = null; }
409
+ clearTimeout(backfillTimer);
410
+ backfillTimer = null;
411
+ recountThrough = 0;
412
+ terminateReaderWorker('ui-blob-store closed');
413
+ if (db) { db.close(); db = null; }
414
+ }
415
+
416
+ // ── Worker thread entrypoint for off-event-loop namespace reads ──
417
+ if (!isMainThread && workerData?.uiBlobReader && parentPort) {
418
+ const encoder = new TextEncoder();
419
+ parentPort.on('message', ({ id, dbPath: targetPath, ns }) => {
420
+ let reader = null;
421
+ try {
422
+ reader = new DatabaseSync(targetPath);
423
+ reader.exec('PRAGMA query_only = ON');
424
+ reader.exec('PRAGMA busy_timeout = 5000; BEGIN');
425
+ const json = buildNamespaceJsonSync(reader, ns, NAMESPACE_READ_PAGE);
426
+ reader.exec('COMMIT');
427
+ // Close before replying so an idle worker never pins the DB file (critical on Windows).
428
+ reader.close();
429
+ reader = null;
430
+ const bytes = encoder.encode(json);
431
+ parentPort.postMessage({ id, bytes }, [bytes.buffer]);
432
+ } catch (err) {
433
+ if (reader) { try { reader.close(); } catch {} }
434
+ parentPort.postMessage({ id, error: err?.message || String(err) });
435
+ }
436
+ });
174
437
  }
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "neural-memory-interface",
3
- "version": "2.4.3",
3
+ "version": "2.4.5",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "neural-memory-interface",
9
- "version": "2.4.3",
9
+ "version": "2.4.5",
10
10
  "hasInstallScript": true,
11
11
  "license": "Apache-2.0",
12
12
  "dependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neural-memory-interface",
3
- "version": "2.4.3",
3
+ "version": "2.4.5",
4
4
  "private": true,
5
5
  "description": "Private local SynaBun interface for memory visualization and multi-agent workflows",
6
6
  "license": "Apache-2.0",