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
@@ -87,6 +87,11 @@ export const LOOKUP_CAP_MS = 2500;
87
87
  /** How long a failed lookup is kept on its connection: a burst of requests is not looked up again each, an open tab
88
88
  * is soon. */
89
89
  export const NEGATIVE_TTL_MS = 2000;
90
+ /** The start probe's waits before it asks again after a failure that may pass (a timeout on a busy machine): only then
91
+ * is the server reported degraded. A denial (EPERM) is never asked again. */
92
+ export const PROBE_RETRY_DELAYS_MS = Object.freeze([250, 1000, 3000]);
93
+ /** While degraded by a failure that may pass, the probe runs again this often until it answers (or a denial follows). */
94
+ export const PROBE_RECHECK_MS = 5000;
90
95
  const PS_SNAPSHOT_TTL_MS = 2000;
91
96
  // A process's parents and command line do not change while it lives (a parent that exits leaves it to launchd, which
92
97
  // only ever takes an agent or a browser out of the chain, never puts one in): kept half an hour, checked against
@@ -647,6 +652,8 @@ function defaultRun(file, args, { timeout, stderr: withStderr = false }) {
647
652
  });
648
653
  }
649
654
 
655
+ const defaultSleep = (ms) => new Promise((resolve) => { const t = setTimeout(resolve, ms); t.unref?.(); });
656
+
650
657
  function thisMachineAddresses() {
651
658
  const out = new Set(['127.0.0.1', '::1']);
652
659
  try {
@@ -669,8 +676,11 @@ function thisMachineAddresses() {
669
676
  * @param {(path:string) => string} [o.realpath] fs.realpathSync (tests inject one).
670
677
  * @param {number} [o.lookupCapMs] the cap of one attempt (LOOKUP_CAP_MS; tests shorten it).
671
678
  * @param {number} [o.negativeTtlMs] how long a failed lookup is kept on its connection (NEGATIVE_TTL_MS).
679
+ * @param {number[]} [o.probeRetryDelaysMs] waits between start-probe attempts after a failure that may pass.
680
+ * @param {number} [o.probeRecheckMs] how often a retryable-degraded server probes again (0: never).
681
+ * @param {(ms:number) => Promise<void>} [o.sleep] waits (tests inject one).
672
682
  */
673
- export function createPeerIdentity({ platform = process.platform, selfPid = process.pid, run = defaultRun, localAddresses = null, log = () => {}, now = Date.now, disabled = false, synabunRoots = [], realpath = realpathSync, debugClient = null, lookupCapMs = LOOKUP_CAP_MS, negativeTtlMs = NEGATIVE_TTL_MS } = {}) {
683
+ export function createPeerIdentity({ platform = process.platform, selfPid = process.pid, run = defaultRun, localAddresses = null, log = () => {}, now = Date.now, disabled = false, synabunRoots = [], realpath = realpathSync, debugClient = null, lookupCapMs = LOOKUP_CAP_MS, negativeTtlMs = NEGATIVE_TTL_MS, probeRetryDelaysMs = PROBE_RETRY_DELAYS_MS, probeRecheckMs = PROBE_RECHECK_MS, sleep = defaultSleep } = {}) {
674
684
  const supported = platform === 'darwin' && !disabled;
675
685
  const capMs = Number.isFinite(lookupCapMs) && lookupCapMs > 0 ? lookupCapMs : LOOKUP_CAP_MS;
676
686
  const ttlMs = Number.isFinite(negativeTtlMs) && negativeTtlMs >= 0 ? negativeTtlMs : NEGATIVE_TTL_MS;
@@ -748,31 +758,67 @@ export function createPeerIdentity({ platform = process.platform, selfPid = proc
748
758
  function authorityState() {
749
759
  return { state: authority.state, reason: authority.reason, retryable: authority.retryable === true, since: authority.since };
750
760
  }
761
+ /** One sample of netstat and ps: `{ failures, retryable }` (retryable only when every failure may pass). */
762
+ async function probeOnce() {
763
+ const failures = [];
764
+ let transient = true;
765
+ try { await readNetstat(); } catch (error) {
766
+ failures.push(error?.netstatTable ? error.message : netstatFailure(error));
767
+ transient = transient && isTransientLookupError(error);
768
+ }
769
+ try {
770
+ const parents = parsePsParents(await run(PS, ['-Ao', 'pid=,ppid=,ucomm='], { timeout: PS_TIMEOUT_MS }));
771
+ if (!parents.size) { failures.push('ps listed no processes'); transient = false; }
772
+ else if (!parents.has(selfPid)) { failures.push('ps did not list this server'); transient = false; }
773
+ } catch (error) { failures.push(`ps: ${failureText(error)}`); transient = transient && isTransientLookupError(error); }
774
+ return { failures, retryable: failures.length > 0 && transient };
775
+ }
776
+ const retryDelays = (Array.isArray(probeRetryDelaysMs) ? probeRetryDelaysMs : PROBE_RETRY_DELAYS_MS).filter((ms) => Number.isFinite(ms) && ms >= 0);
777
+ const recheckMs = Number.isFinite(probeRecheckMs) && probeRecheckMs > 0 ? probeRecheckMs : 0;
778
+ let recheckTimer = null;
779
+ /** Probe again later while degraded by a failure that may pass; a later answer restores, a denial ends it. */
780
+ function scheduleRecheck() {
781
+ if (!recheckMs || recheckTimer) return;
782
+ recheckTimer = setTimeout(async () => {
783
+ recheckTimer = null;
784
+ if (authority.state !== 'degraded' || !authority.retryable) return;
785
+ let r;
786
+ try { r = await probeOnce(); } catch (error) { r = { failures: [`the probe failed (${error?.message || error})`], retryable: false }; }
787
+ if (authority.state !== 'degraded') return; // a lookup settled it meanwhile
788
+ if (!r.failures.length) restore('probe recheck');
789
+ else {
790
+ degrade(r.failures.join('; '), { retryable: r.retryable, source: 'probe recheck' });
791
+ if (authority.retryable) scheduleRecheck();
792
+ }
793
+ }, recheckMs);
794
+ recheckTimer.unref?.();
795
+ }
751
796
  /**
752
- * The start probe (server.js runs it once, at start): netstat and ps, as a lookup runs them. A failure is the
753
- * degraded state at once, with its reason in the log and in GET /api/health, before any owner's request meets it.
754
- * Off macOS (or off) there is nothing to probe. Never rejects; asked twice, it runs once.
797
+ * The start probe (server.js runs it once, at start): netstat and ps, as a lookup runs them. A failure that may pass
798
+ * (a timeout under load) is asked again after each of `probeRetryDelaysMs`; only a failure that lasts is the degraded
799
+ * state, with its reason in the log and in GET /api/health, before any owner's request meets it; while it may still
800
+ * pass, the probe runs again every `probeRecheckMs` until it answers. A denial (EPERM) degrades at once and is never
801
+ * retried: the server keeps failing closed. Off macOS (or off) there is nothing to probe. Never rejects; asked
802
+ * twice, it runs once.
755
803
  */
756
804
  function probe() {
757
805
  if (!supported) return Promise.resolve(authorityState());
758
806
  if (probed) return probed;
759
807
  probed = (async () => {
760
- const failures = [];
761
- let retryable = false;
762
- try { await readNetstat(); } catch (error) {
763
- failures.push(error?.netstatTable ? error.message : netstatFailure(error));
764
- retryable = retryable || isTransientLookupError(error);
808
+ let r = await probeOnce();
809
+ for (let i = 0; r.failures.length && r.retryable && i < retryDelays.length; i++) {
810
+ if (authority.state !== 'pending') break;
811
+ stats.retries++;
812
+ await sleep(retryDelays[i]);
813
+ r = await probeOnce();
765
814
  }
766
- try {
767
- const parents = parsePsParents(await run(PS, ['-Ao', 'pid=,ppid=,ucomm='], { timeout: PS_TIMEOUT_MS }));
768
- if (!parents.size) failures.push('ps listed no processes');
769
- else if (!parents.has(selfPid)) failures.push('ps did not list this server');
770
- } catch (error) { failures.push(`ps: ${failureText(error)}`); retryable = retryable || isTransientLookupError(error); }
771
815
  // A request can finish its full lookup while this boot-time sample is in flight.
772
816
  // Its observed outcome takes precedence over the preflight in either direction.
773
817
  if (authority.state !== 'pending') return authorityState();
774
- if (failures.length) degrade(failures.join('; '), { retryable, source: 'start probe' });
775
- else {
818
+ if (r.failures.length) {
819
+ degrade(r.failures.join('; '), { retryable: r.retryable, source: 'start probe' });
820
+ if (r.retryable) scheduleRecheck();
821
+ } else {
776
822
  say('[peer-identity] start probe: netstat and ps answer; the owner\'s authority is checked against the calling process');
777
823
  restore('start probe');
778
824
  }
@@ -10,9 +10,12 @@
10
10
  // refuse, user allow rules included; routing always asks (one
11
11
  // route card per task is the task's approval); workers get no
12
12
  // computer, no "user-authorized-full" and a registered cwd.
13
- // autonomous — the modes as configured. On WhatsApp it stays until the owner
14
- // lowers it in Settings; any other channel only until its
15
- // autonomousUntil, then ask.
13
+ // autonomous — never asks: routing is 'never' whatever the session's or the
14
+ // global route mode (saved routes bind, else the brain picks;
15
+ // also on a turn with untrusted content, whose tools are asked
16
+ // at Ask), and on WhatsApp the brain runs bypassPermissions.
17
+ // On WhatsApp it stays until the owner lowers it in Settings;
18
+ // any other channel only until its autonomousUntil, then ask.
16
19
  // Ask and Autonomous hold only on a Claude brain: its in-process PreToolUse
17
20
  // hook sees every call with its arguments. A Codex or OpenCode brain runs
18
21
  // ordinary commands inside its own sandbox / permissions without asking, so a
@@ -111,13 +114,18 @@ export function brainCapsLevel(policy, { provider = null, now = Date.now() } = {
111
114
  * The approval mode and plan flag a brain may run with. read-only forces plan
112
115
  * mode (`planApproved`: the desktop approved the plan, which may then run);
113
116
  * ask forces the approval mode to 'default' (every provider asks there);
114
- * autonomous keeps what was configured.
117
+ * autonomous keeps what was configured, except on WhatsApp, where it is
118
+ * 'bypassPermissions' whatever the panel last used: Autonomous acts without
119
+ * asking, so the phone is never asked to approve a tool (the brain's remote
120
+ * hook still refuses what isDeniedRemoteTool lists, and computer use keeps
121
+ * its own rule). The plan flag is kept either way.
115
122
  */
116
123
  export function clampBrainModes(policy, modes = {}, { untrusted = false, now = Date.now(), planApproved = false } = {}) {
117
124
  const permissionMode = modes.permissionMode && modes.permissionMode !== 'plan' ? String(modes.permissionMode) : 'default';
118
125
  const planMode = modes.planMode === true || modes.permissionMode === 'plan';
119
126
  const level = effectiveLevel(policy, { untrusted, now });
120
- if (!level || level === 'autonomous') return { permissionMode, planMode };
127
+ if (!level) return { permissionMode, planMode };
128
+ if (level === 'autonomous') return { permissionMode: policy.channel === 'whatsapp' ? 'bypassPermissions' : permissionMode, planMode };
121
129
  if (level === 'ask') return { permissionMode: 'default', planMode };
122
130
  return { permissionMode: 'default', planMode: planApproved ? planMode : true };
123
131
  }
@@ -181,10 +189,19 @@ export function remoteComputerDenial(reason = null) {
181
189
  return COMPUTER_OFF_TEXT[reason] || 'Computer use is not available from WhatsApp right now.';
182
190
  }
183
191
 
184
- /** The route mode a remote session runs: below autonomous every task is approved on its route card. */
192
+ /**
193
+ * The route mode a remote session runs. Autonomous never asks where a task runs, whatever the
194
+ * session's or the global route mode says ('never': the saved route for the class binds, else the
195
+ * brain's own pick runs), so the phone is never shown a model card. A turn that carries content the
196
+ * owner did not write (a picture, a forwarded or quoted message) is capped at Ask for its tools,
197
+ * not for its route: the owner configured Autonomous. Below Autonomous every task is approved on
198
+ * its route card ('always-ask').
199
+ */
185
200
  export function clampRouteMode(policy, mode, opts = {}) {
186
201
  const level = effectiveLevel(policy, opts);
187
- if (!level || level === 'autonomous') return mode;
202
+ if (!level) return mode;
203
+ if (level === 'autonomous') return 'never';
204
+ if (opts.untrusted === true && effectiveLevel(policy, { ...opts, untrusted: false }) === 'autonomous') return 'never';
188
205
  return 'always-ask';
189
206
  }
190
207
 
@@ -1,4 +1,5 @@
1
1
  import { queueMemoryCapture } from './memory-session-capture.js';
2
+ import { fileIdentityOf, isSessionFileUnchanged, mtimeIsoOf } from './session-capture-gate.js';
2
3
  import { normalizeMemoryEvents, ingestMemoryEvents, CAPTURE_TRANSACTION_MS, CAPTURE_PAUSE_MS } from '../../mcp-server/dist/services/memory-sessions.js';
3
4
  import { detectProject } from '../../mcp-server/dist/config.js';
4
5
  /**
@@ -200,20 +201,42 @@ function* scanClaudeCache({ project, onProgress }) {
200
201
  total++;
201
202
  const filePath = join(projDir.path, file);
202
203
  let stat;
203
- try { stat = statSync(filePath); } catch { continue; }
204
- if (stat.size > MAX_CLAUDE_FILE) continue;
205
-
204
+ try { stat = statSync(filePath, { bigint: true }); } catch { continue; }
205
+ const fileSize = Number(stat.size);
206
206
  const sessionId = file.replace('.jsonl', '');
207
- queueMemoryCapture({host:'claude-code',sessionId,filePath,project:projDir.name});
208
207
  const existing = getSessionCacheEntry(sessionId, 'claude-code');
209
- if (existing && existing.file_size === stat.size && existing.file_mtime === stat.mtime.toISOString()) {
210
- continue;
211
- }
208
+
209
+ // Decide memory capture from the capture checkpoint, independent of the search cache
210
+ // and its 50 MiB parser size limit.
211
+ queueMemoryCapture({
212
+ host: 'claude-code',
213
+ sessionId,
214
+ filePath,
215
+ cwd: existing?.project_path || undefined,
216
+ project: projDir.name,
217
+ size: fileSize,
218
+ stat,
219
+ });
220
+
221
+ if (fileSize > MAX_CLAUDE_FILE) continue;
222
+
223
+ if (isSessionFileUnchanged(existing, stat)) continue;
212
224
 
213
225
  const parsed = parseClaudeSession(filePath);
214
226
  if (!parsed) continue;
215
227
 
216
- queueMemoryCapture({host:'claude-code',sessionId:parsed.sessionId,filePath,cwd:parsed.cwd,project:projDir.name});
228
+ if (parsed.sessionId !== sessionId || (parsed.cwd && parsed.cwd !== existing?.project_path)) {
229
+ queueMemoryCapture({
230
+ host: 'claude-code',
231
+ sessionId: parsed.sessionId,
232
+ filePath,
233
+ cwd: parsed.cwd,
234
+ project: projDir.name,
235
+ size: fileSize,
236
+ stat,
237
+ });
238
+ }
239
+
217
240
  const entry = {
218
241
  session_id: parsed.sessionId,
219
242
  provider: 'claude-code',
@@ -223,10 +246,12 @@ function* scanClaudeCache({ project, onProgress }) {
223
246
  first_prompt: parsed.firstPrompt,
224
247
  message_count: parsed.messageCount,
225
248
  created: parsed.earliest,
226
- modified: parsed.latest || stat.mtime.toISOString(),
249
+ modified: parsed.latest || mtimeIsoOf(stat),
227
250
  file_path: filePath,
228
- file_size: stat.size,
229
- file_mtime: stat.mtime.toISOString(),
251
+ file_size: fileSize,
252
+ file_mtime: mtimeIsoOf(stat),
253
+ file_identity: fileIdentityOf(stat),
254
+
230
255
  body_size: parsed.body.length,
231
256
  deleted: 0,
232
257
  };
@@ -334,7 +359,7 @@ function* scanCodexCache({ project, projects, accounts, onProgress }) {
334
359
  const projLower = project ? String(project).toLowerCase() : null;
335
360
  const d = getDb();
336
361
  const probeStmt = d.prepare(
337
- 'SELECT session_id, file_size, file_mtime FROM session_cache WHERE file_path = ? AND provider = ?'
362
+ 'SELECT session_id, file_size, file_mtime, file_identity FROM session_cache WHERE file_path = ? AND provider = ?'
338
363
  );
339
364
 
340
365
  let total = 0;
@@ -347,14 +372,25 @@ function* scanCodexCache({ project, projects, accounts, onProgress }) {
347
372
  if (!filePath) continue;
348
373
  total++;
349
374
  let stat;
350
- try { stat = statSync(filePath); } catch { continue; }
375
+ try { stat = statSync(filePath, { bigint: true }); } catch { continue; }
376
+ const fileSize = Number(stat.size);
351
377
 
352
378
  if (projLower && session.cwd && !session.cwd.toLowerCase().includes(projLower)) continue;
353
379
  liveSessionIds.add(session.sessionId);
354
380
 
355
- queueMemoryCapture({host:'codex',sessionId:session.sessionId,filePath,cwd:session.cwd || session.projectPath});
381
+ // Decide memory capture from the capture checkpoint, independent of session_cache hits
382
+ // and the 50 MiB search-cache parser limit (parseCodexSession rejects >50 MiB rollouts).
383
+ queueMemoryCapture({
384
+ host: 'codex',
385
+ sessionId: session.sessionId,
386
+ filePath,
387
+ cwd: session.cwd || session.projectPath,
388
+ size: fileSize,
389
+ stat,
390
+ });
391
+
356
392
  const probe = probeStmt.get(filePath, 'codex');
357
- if (probe && probe.file_size === stat.size && probe.file_mtime === stat.mtime.toISOString()) {
393
+ if (isSessionFileUnchanged(probe, stat)) {
358
394
  const cached = getSessionCacheEntry(session.sessionId, 'codex');
359
395
  if (cached?.deleted || cached?.account_id !== session.accountId) {
360
396
  upsertSessionCache({
@@ -371,7 +407,17 @@ function* scanCodexCache({ project, projects, accounts, onProgress }) {
371
407
  const parsed = parseCodexSession(filePath);
372
408
  if (!parsed) continue;
373
409
 
374
- queueMemoryCapture({host:'codex',sessionId:parsed.sessionId,filePath,cwd:parsed.cwd || session.cwd});
410
+ if (parsed.sessionId !== session.sessionId || (parsed.cwd && parsed.cwd !== (session.cwd || session.projectPath))) {
411
+ queueMemoryCapture({
412
+ host: 'codex',
413
+ sessionId: parsed.sessionId,
414
+ filePath,
415
+ cwd: parsed.cwd || session.cwd || session.projectPath,
416
+ size: fileSize,
417
+ stat,
418
+ });
419
+ }
420
+
375
421
  const entry = {
376
422
  session_id: parsed.sessionId,
377
423
  provider: 'codex',
@@ -383,8 +429,10 @@ function* scanCodexCache({ project, projects, accounts, onProgress }) {
383
429
  created: session.created || parsed.created,
384
430
  modified: session.modified || parsed.modified,
385
431
  file_path: filePath,
386
- file_size: parsed.fileSize,
387
- file_mtime: parsed.modified,
432
+ file_size: fileSize,
433
+ file_mtime: mtimeIsoOf(stat),
434
+ file_identity: fileIdentityOf(stat),
435
+
388
436
  body_size: parsed.body.length,
389
437
  deleted: 0,
390
438
  account_id: session.accountId,
@@ -0,0 +1,42 @@
1
+ export function mtimeIsoOf(stat) {
2
+ if (!stat) return null;
3
+ if (typeof stat.mtimeIso === 'string' && stat.mtimeIso) return stat.mtimeIso;
4
+ if (typeof stat.mtime?.toISOString === 'function') return stat.mtime.toISOString();
5
+ if (stat.mtimeMs != null && Number.isFinite(Number(stat.mtimeMs))) {
6
+ return new Date(Number(stat.mtimeMs)).toISOString();
7
+ }
8
+ return null;
9
+ }
10
+
11
+ /**
12
+ * Deterministic persisted file identity combining device, inode, ctime, and mtime
13
+ * (nanosecond resolution when BigInt stats are used). Returns null for minimal
14
+ * stat mocks that only carry size + mtime.
15
+ */
16
+ export function fileIdentityOf(stat) {
17
+ if (stat?.dev == null || stat.ino == null) return null;
18
+ const ctime = stat.ctimeNs != null ? `ns:${stat.ctimeNs}` : (stat.ctimeMs != null ? `ms:${stat.ctimeMs}` : '');
19
+ const mtime = stat.mtimeNs != null ? `ns:${stat.mtimeNs}` : (stat.mtimeMs != null ? `ms:${stat.mtimeMs}` : '');
20
+ return `${stat.dev}:${stat.ino}:${ctime}:${mtime}`;
21
+ }
22
+
23
+ // Older checkpoints already encode dev:ino:ctime:mtime. The first two fields identify
24
+ // the file across appends. The complete stamp detects same-size edits, even if mtime is restored.
25
+ export function captureStartOffset(row, size, identity, mtime) {
26
+ const offset = Number(row.byte_offset);
27
+ const previousSize = row.file_size ?? offset;
28
+ if (size != null && (size < offset || size < previousSize)) return 0;
29
+ if (!row.file_identity || !identity) return offset;
30
+ if (size > previousSize) {
31
+ const fileKey = stamp => stamp.split(':', 2).join(':');
32
+ return fileKey(identity) === fileKey(row.file_identity) ? offset : 0;
33
+ }
34
+ if (identity !== row.file_identity
35
+ || (mtime && row.file_mtime && mtime !== row.file_mtime)) return 0;
36
+ return offset;
37
+ }
38
+
39
+ export function isSessionFileUnchanged(cached, stat) {
40
+ return !!cached?.file_identity && cached.file_identity === fileIdentityOf(stat)
41
+ && Number(cached.file_size) === Number(stat.size) && cached.file_mtime === mtimeIsoOf(stat);
42
+ }
@@ -1,6 +1,7 @@
1
1
  import { captureMemoryFileBatch } from './memory-session-capture.js';
2
2
  import { withMemoryWrite } from '../../mcp-server/dist/services/sqlite-write.js';
3
3
  import { runSessionJob } from './session-cache-worker.js';
4
+ import { fileIdentityOf, isSessionFileUnchanged, mtimeIsoOf } from './session-capture-gate.js';
4
5
  /**
5
6
  * Session Indexer — Pipeline orchestrator for indexing Claude Code session transcripts.
6
7
  * Queues local JSONL files through the shared, incremental memory event intake.
@@ -130,29 +131,28 @@ export async function startIndexing(options = {}) {
130
131
 
131
132
  if (options.sessionIds && !options.sessionIds.includes(sessionId)) continue;
132
133
 
134
+ let stat;
135
+ try {
136
+ stat = statSync(filePath, { bigint: true });
137
+ } catch { continue; }
138
+ const fileSize = Number(stat.size);
139
+ const fileMtime = mtimeIsoOf(stat);
140
+ const fileIdentity = fileIdentityOf(stat);
141
+
133
142
  if (!options.reindex && state.sessions[sessionId]) {
134
143
  const entry = state.sessions[sessionId];
135
- if (entry.status === 'complete') {
136
- try {
137
- const stat = statSync(filePath);
138
- if (stat.size === entry.file_size && stat.mtime.toISOString() === entry.file_mtime) {
139
- continue;
140
- }
141
- } catch { continue; }
142
- }
144
+ if (entry.status === 'complete' && isSessionFileUnchanged(entry, stat)) continue;
143
145
  }
144
146
 
145
- try {
146
- const stat = statSync(filePath);
147
- if (stat.size === 0) continue;
148
- sessionsToIndex.push({
149
- sessionId,
150
- filePath,
151
- fileSize: stat.size,
152
- fileMtime: stat.mtime.toISOString(),
153
- projectDir: projDir.name,
154
- });
155
- } catch { continue; }
147
+ if (fileSize === 0) continue;
148
+ sessionsToIndex.push({
149
+ sessionId,
150
+ filePath,
151
+ fileSize,
152
+ fileMtime,
153
+ fileIdentity,
154
+ projectDir: projDir.name,
155
+ });
156
156
  }
157
157
  }
158
158
 
@@ -179,7 +179,14 @@ export async function startIndexing(options = {}) {
179
179
  // Preserve this entry point and its UI progress events for Claude hooks.
180
180
  const target = { host: 'claude-code', sessionId: session.sessionId };
181
181
  const project = detectProjectFromDir(session.projectDir);
182
- await runSessionJob('queue-capture', { ...target, filePath: session.filePath, project });
182
+ await runSessionJob('queue-capture', {
183
+ ...target,
184
+ filePath: session.filePath,
185
+ project,
186
+ size: session.fileSize,
187
+ fileMtime: session.fileMtime,
188
+ fileIdentity: session.fileIdentity,
189
+ });
183
190
  let complete = false;
184
191
  while (!isCancelled?.()) {
185
192
  const outcome = await captureMemoryFileBatch(target, { reportProgress: true });
@@ -193,6 +200,7 @@ export async function startIndexing(options = {}) {
193
200
  const chunkIds = await runSessionJob('capture-chunks', target);
194
201
  totalChunks += chunkIds.length;
195
202
  state.sessions[session.sessionId]={session_id:session.sessionId,file_path:session.filePath,file_size:session.fileSize,file_mtime:session.fileMtime,
203
+ file_identity:session.fileIdentity,
196
204
  chunk_count:chunkIds.length,chunk_ids:chunkIds,indexed_at:new Date().toISOString(),project,
197
205
  status:complete ? 'complete' : 'partial',last_line_indexed:0};
198
206
  saveState(state);
@@ -256,6 +256,10 @@ Where it applies, `report.userShouldRun` is what the user can run themselves (`g
256
256
  | `landing` | the target branch at the landing's commit: `merged`. Where it was: the team is as before. Anywhere else: reported |
257
257
  | a worktree's folder gone | put back from its branch (what was uncommitted in the folder went with the folder) |
258
258
  | a slice's branch and folder gone | the slice is `failed` |
259
+ | the integration branch and folder gone, every slice ended or gone, the integration head on the base branch already | the team is `merged` (merged outside `land`: `landed.external: true`, `landed.recovered: true`); nothing is made again |
260
+ | the integration branch and folder gone, every slice ended or gone, nothing joined (no slice `integrated`, the head still the base commit) | the team is `failed`; no empty integration branch is made |
261
+
262
+ A team closed that way gives its claims back, and `removed: true` is written when no branch or folder of it is left; a slice branch that is still there stays, for `remove` (after the landing) or a discard. The integration branch is still made again from its recorded head when any slice is at work or its branch is still there with its folder gone, when the head has commits the base branch does not have, or when the base branch is not there to compare with. Each closing is the action `team_closed` (`state`, `reason: 'merged_outside_landing' | 'nothing_integrated'`, `targetBranch`, `head`, `removed`).
259
263
 
260
264
  It also takes the claims of every team under way again and registers every slice with the worker guard again (the guard's registry is in memory).
261
265
 
@@ -301,7 +305,7 @@ They ask git under the rules of a read and change nothing. The tool has no actio
301
305
  `createTeamScheduler({ teams, coordination, dispatcher, density, router, session, git, dataDir, broadcast, limits })` (`scheduler.js`). `docs/agents.md` → Teams says what it does for the Assistant and the workers; this is what a caller of the library needs to know about it.
302
306
 
303
307
  - **It is the only caller of the library in the server.** `server.js` shares it (`shareTeamScheduler`); the Assistant's API and the Agents Studio routes ask `sharedTeamScheduler()` when a request arrives. A test passes its own.
304
- - **Its own record** is one JSON file per team in `<dataDir>/teams/<teamId>.json` (the session, the route, the dispatch settings, each slice's runs and retry counts, its status). Everything about git is read from the journal through the library, never kept twice.
308
+ - **Its own record** is one JSON file per team in `<dataDir>/teams/<teamId>.json` (the session, the route, the dispatch settings, each slice's runs and retry counts, its status). Everything about git is read from the journal through the library, never kept twice. `remove(teamId)` deletes that file (and `teams/sandbox/<teamId>.sb`) for a closed team once git and the disk show nothing of it and no worker lives; the journal entry stays (a closed team's journal state is terminal, so `recover()` skips it, and its id is never made again), and a removed record is never saved again (`docs/agents.md` → Teams, Removing a closed team).
305
309
  - **A team's steps never overlap**: every step of one team runs after the one before it (`inTurn`), and none runs before the library's `recover()` has.
306
310
  - **The run id comes first.** `dispatchSlice` makes the run id, calls `startSlice(teamId, sliceId, { runId })` (or `resolveInSlice`), and only then dispatches with that id (`dispatcher.dispatch(spec, { team, runId })`): the claims are in the run's name before the worker exists. The dispatcher takes `team` and `runId` from the scheduler alone; no request body reaches them.
307
311
  - **What it decides that the library leaves open** (the list below this section, as it was written for this phase): workers run with capability `workspace`; `STRAY_CHANGES` is answered with `allowStray: true` (the files stay out, the event names them); a conflict goes to the slice's own worker through `resolveInSlice`; `land` is never called because a team became ready; the workers are stopped before `remove`; the tests run through `test-sandbox.js`; the setup step is `cloneNodeModules()`; a team id is `<title>-<6 hex>`.
@@ -380,3 +384,20 @@ lastOwnerTurnAt: (sessionId) => _assistantRuntime?.lastOwnerTurnAt?.(sessionId)
380
384
  With that dependency present, absent, equal or earlier timestamps refuse cleanup. Without it,
381
385
  confirmation timing is explicitly reported as unverified. Git failures during removal throw;
382
386
  external concurrent filesystem changes cannot be made transactional across Git commands.
387
+
388
+ ### A ready team merged outside `land`
389
+
390
+ Somebody may merge a ready team's integration branch into its base branch by hand, leaving its worktrees and
391
+ branches on disk. `onTarget(teamId)` (read only, no lock: a list asks it) answers `null` unless the journal says
392
+ `ready` and git says the recorded integration head, and the live integration branch, are ancestors of
393
+ `refs/heads/<baseBranch>`; then `{ branch, head, targetHead, live, moved, clean, dirty, unmerged, other }`, where
394
+ `clean` is every guarded check above passing against the base branch (`guardedChecks`, the same code the removal
395
+ runs), `dirty` the uncommitted files per worktree, `unmerged` the branches with commits the base branch lacks, and
396
+ `other` git's words for anything else. Live workers are the scheduler's to count (`liveRuns`), not the library's.
397
+
398
+ `remove(teamId, { guarded: true, mergedOutside: true })` reads the team again under the repository's lock, refuses
399
+ (`TEAM_NOT_READY`, `NOT_ON_TARGET`, then the guarded codes) with nothing changed, and otherwise journals the landing
400
+ somebody else made (`merged`, `landed.external: true`) before it removes anything, then removes exactly as a guarded
401
+ cleanup does. The scheduler's `cleanupMerged(teamId, { by: { kind: 'owner' }, userConfirmed: true })` adds the live
402
+ worker check, records the landing on the team, emits `team_cleaned` and removes the team's record. Nothing does this
403
+ at start-up: recovery closes such a team only when its integration branch and worktree are already gone.
@@ -11,8 +11,11 @@
11
11
  // /api/assistant/team/* a worker's `team` tool: context, post, read, wait, ack, claims, request. Only a
12
12
  // run that proves its pin (its terminal token) AND works a team slice now. The
13
13
  // team is the run's own, read from the scheduler: no request names one.
14
- // /api/agents-studio/v1/teams* Agents Studio (the page): the list, one team in full, and the owner's two
15
- // decisions, land and discard.
14
+ // /api/agents-studio/v1/teams* Agents Studio (the page): the list, one team in full, and the owner's
15
+ // decisions: land, discard (with `force`, also the work a discard kept; with
16
+ // `remove`, the record too once nothing is left), clean up a landed team's
17
+ // worktrees, clean up and remove a ready team whose work is on its base branch
18
+ // already (cleanup-merged), remove a closed team's record, clear finished.
16
19
  //
17
20
  // Every refusal of the library (lib/teams/README.md) and of the scheduler comes back as it is: `{ ok: false, code,
18
21
  // message, … }`, with the HTTP status that fits.
@@ -20,6 +23,7 @@
20
23
  import { AGENT_DENSITIES, AGENT_DENSITY_WORKERS } from '../agents/density.js';
21
24
  import { LANDING_MODES } from './landing.js';
22
25
  import { TEAM_MESSAGE_KINDS } from './brief.js';
26
+ import { CLOSED_TEAM_STATUSES } from './scheduler.js';
23
27
 
24
28
  /** Codes that are about the request itself (400), about who asks (403), about something missing (404). The rest is a conflict (409). */
25
29
  const STATUS_BY_CODE = Object.freeze({
@@ -210,11 +214,38 @@ export function registerAssistantTeamRoutes(router, { scheduler, orchestrationGu
210
214
  }));
211
215
  }
212
216
 
213
- /** A team as the Agents Studio list shows it: exactly these fields. */
217
+ /** `alreadyOnTarget` as a list row carries it: where the work is and whether the team could go now, or null. */
218
+ const onTargetRow = (value) => (value && typeof value === 'object' && typeof value.branch === 'string' && value.branch
219
+ ? { branch: value.branch, head: typeof value.head === 'string' ? value.head : null, clean: value.clean === true }
220
+ : null);
221
+ const count = (value) => (Number.isInteger(value) && value >= 0 ? value : null);
222
+
223
+ /**
224
+ * A team as the Agents Studio list shows it: exactly these fields. `removable`: a closed team whose record can go
225
+ * now (nothing of it left on disk or in git, no live run); false for every other team. For a team that waits on the
226
+ * owner (needs attention, ready): `liveRuns` (workers still alive), `left` (its worktrees and branches on disk and in
227
+ * git) and `alreadyOnTarget` (a ready team whose work is on its base branch already: `{ branch, head, clean }`);
228
+ * null when not asked or not known.
229
+ */
214
230
  export const teamListRow = (team) => ({
215
231
  id: team.id, project: team.project, title: team.title, status: team.status, density: team.density, slices: team.slices, createdAt: team.createdAt,
232
+ removable: team.removable === true,
233
+ alreadyOnTarget: onTargetRow(team.alreadyOnTarget),
234
+ liveRuns: count(team.liveRuns),
235
+ left: count(team.left),
216
236
  });
217
237
 
238
+ /** Run `fn` over `items`, at most `limit` at a time, the answers in the items' order. */
239
+ async function eachLimited(items, limit, fn) {
240
+ const out = new Array(items.length);
241
+ let next = 0;
242
+ const lane = async () => { while (next < items.length) { const at = next++; out[at] = await fn(items[at], at); } };
243
+ await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, lane));
244
+ return out;
245
+ }
246
+ /** How many teams the list asks git about at once. */
247
+ export const TEAM_LIST_CONCURRENCY = 4;
248
+
218
249
  /**
219
250
  * One team as Agents Studio reads it (GET /teams/:id): the plan, its slices, the claims, the integration branch and
220
251
  * its last test result, the landing, and the last 100 team events and messages.
@@ -223,7 +254,15 @@ export function teamDetail(answer) {
223
254
  const team = answer.team || {};
224
255
  return {
225
256
  ok: true,
226
- team: { ...teamListRow(team), state: team.state ?? null, attention: team.attention ?? null, sessionId: team.sessionId ?? null, workflowId: team.workflowId ?? null, baseCommit: team.baseCommit ?? null, baseBranch: team.baseBranch ?? null, cap: team.cap ?? null, updatedAt: team.updatedAt ?? null },
257
+ team: {
258
+ ...teamListRow({ ...team, removable: team.removal?.removable === true }), state: team.state ?? null, attention: team.attention ?? null, sessionId: team.sessionId ?? null, workflowId: team.workflowId ?? null,
259
+ baseCommit: team.baseCommit ?? null, baseBranch: team.baseBranch ?? null, cap: team.cap ?? null, updatedAt: team.updatedAt ?? null,
260
+ // A closed team: whether its record can go, and what is still on disk or in git when it cannot (null: open).
261
+ removal: team.removal ?? null,
262
+ // A ready team whose work is on its base branch already, in full: where, whether it is clean, and what is
263
+ // not (uncommitted files per worktree, branches with commits the base branch lacks, other blocks).
264
+ alreadyOnTarget: team.alreadyOnTarget ?? null,
265
+ },
227
266
  plan: answer.plan,
228
267
  slices: (answer.slices || []).map((slice) => ({
229
268
  id: slice.id, title: slice.title, status: slice.status, phase: slice.phase, runId: slice.runId, run: slice.run,
@@ -274,7 +313,18 @@ export function registerTeamStudioRoutes({ route, reader, owner, json, scheduler
274
313
 
275
314
  route('get', '/teams', reader, teamReader, run(async (req, res, teams) => {
276
315
  const q = req.query || {};
277
- res.json({ ok: true, teams: teams.list({ sessionId: sessionOf(req), projectPath: typeof q.project === 'string' && q.project ? q.project : null, open: q.open === '1' || q.open === 'true' }).map(teamListRow) });
316
+ const rows = teams.list({ sessionId: sessionOf(req), projectPath: typeof q.project === 'string' && q.project ? q.project : null, open: q.open === '1' || q.open === 'true' });
317
+ // A closed team, and one that waits on the owner, are asked of git and the disk, a few at a time (the page offers
318
+ // Remove, Clear finished and the cards' quick actions from it); a running team is not asked.
319
+ const out = await eachLimited(rows, TEAM_LIST_CONCURRENCY, async (row) => {
320
+ let facts = {};
321
+ try {
322
+ if (typeof teams.overview === 'function') facts = (await teams.overview(row.id)) || {};
323
+ else if (CLOSED_TEAM_STATUSES.includes(row.status) && typeof teams.removability === 'function') facts = { removable: (await teams.removability(row.id)).removable === true };
324
+ } catch { facts = {}; }
325
+ return teamListRow({ ...row, ...facts });
326
+ });
327
+ res.json({ ok: true, teams: out });
278
328
  }));
279
329
  route('get', '/teams/:id', reader, teamReader, idCheck, run(async (req, res, teams) => {
280
330
  const session = sessionOf(req);
@@ -291,6 +341,29 @@ export function registerTeamStudioRoutes({ route, reader, owner, json, scheduler
291
341
  }));
292
342
  route('post', '/teams/:id/discard', json, owner, idCheck, run(async (req, res, teams) => {
293
343
  const body = req.body || {};
294
- send(res, await teams.discard(req.params.id, { by: { kind: 'owner' }, force: body.force === true, reason: typeof body.reason === 'string' ? body.reason : '' }));
344
+ // `remove: true` (Discard & remove): the record goes too, in the same step, once the discard left nothing.
345
+ send(res, await teams.discard(req.params.id, { by: { kind: 'owner' }, force: body.force === true, remove: body.remove === true, reason: typeof body.reason === 'string' ? body.reason : '' }));
346
+ }));
347
+ // A ready team whose work is on its base branch already: its worktrees, branches and record, in one step, once
348
+ // git says again that nothing would be lost (the owner's page, `userConfirmed: true`).
349
+ route('post', '/teams/:id/cleanup-merged', json, owner, idCheck, run(async (req, res, teams) => {
350
+ if (typeof teams.cleanupMerged !== 'function') return unavailable(res);
351
+ const body = req.body || {};
352
+ send(res, await teams.cleanupMerged(req.params.id, { by: { kind: 'owner' }, userConfirmed: body.userConfirmed === true || body.user_confirmed === true }));
353
+ }));
354
+ // The owner cleans up a landed team's worktrees and branches. The owner's page is the confirmation (with
355
+ // `userConfirmed: true`), so no Assistant turn is asked for; every other check of the scheduler's stays.
356
+ route('post', '/teams/:id/cleanup', json, owner, idCheck, run(async (req, res, teams) => {
357
+ const body = req.body || {};
358
+ send(res, await teams.cleanup(req.params.id, { by: { kind: 'owner' }, userConfirmed: body.userConfirmed === true || body.user_confirmed === true }));
359
+ }));
360
+ // Every closed team that can go; the rest are listed as skipped, with why.
361
+ route('post', '/teams/clear-finished', json, owner, run(async (req, res, teams) => {
362
+ const body = req.body || {};
363
+ send(res, await teams.clearFinished({ by: { kind: 'owner' }, projectPath: typeof body.project === 'string' && body.project ? body.project : null }));
364
+ }));
365
+ // A closed team's record, once nothing of it is left on disk or in git.
366
+ route('delete', '/teams/:id', json, owner, idCheck, run(async (req, res, teams) => {
367
+ send(res, await teams.remove(req.params.id, { by: { kind: 'owner' } }));
295
368
  }));
296
369
  }
@@ -86,6 +86,8 @@ export function createTeams({ store, git = createGitRunner(), runTests = createT
86
86
  plan: async (teamId) => (await worktrees.get(teamId))?.plan || null,
87
87
  list: worktrees.list,
88
88
  inspect: worktrees.inspect,
89
+ /** A ready team whose work is on its base branch already (merged outside land): where, and whether it is clean. Read only. */
90
+ onTarget: worktrees.onTarget,
89
91
  startSlice,
90
92
  finishSlice: integration.finishSlice,
91
93
  finishReadOnlySlice: async (teamId, sliceId, options) => {