synabun 2.4.4 → 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 (59) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +5 -4
  4. package/docs/whatsapp.md +3 -3
  5. package/mcp-server/dist/services/neural-interface.d.ts +1 -0
  6. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  7. package/mcp-server/dist/services/neural-interface.js +1 -0
  8. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  9. package/mcp-server/dist/tools/agents.d.ts +16 -3
  10. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  11. package/mcp-server/dist/tools/agents.js +74 -11
  12. package/mcp-server/dist/tools/agents.js.map +1 -1
  13. package/mcp-server/package-lock.json +2 -2
  14. package/mcp-server/package.json +1 -1
  15. package/mcp-server/src/services/neural-interface.ts +2 -1
  16. package/mcp-server/src/tools/agents.ts +67 -11
  17. package/neural-interface/i18n/en.json +349 -9
  18. package/neural-interface/i18n/pt-BR.json +349 -9
  19. package/neural-interface/lib/agents-studio-api.js +7 -2
  20. package/neural-interface/lib/antigravity/home.js +43 -8
  21. package/neural-interface/lib/antigravity/tool-call.js +14 -0
  22. package/neural-interface/lib/assistant-brains/antigravity.js +4 -2
  23. package/neural-interface/lib/assistant-persona.js +8 -3
  24. package/neural-interface/lib/assistant-route-gate.js +11 -2
  25. package/neural-interface/lib/assistant-runtime.js +16 -5
  26. package/neural-interface/lib/assistant-spilled-output.js +53 -0
  27. package/neural-interface/lib/browser-default.js +22 -2
  28. package/neural-interface/lib/browser-extension-bridge.js +50 -3
  29. package/neural-interface/lib/browser-extension-pin.json +7 -7
  30. package/neural-interface/lib/browser-extension-protocol.js +30 -1
  31. package/neural-interface/lib/browser-extension-setup.js +204 -36
  32. package/neural-interface/lib/remote-policy.js +24 -7
  33. package/neural-interface/lib/teams/README.md +22 -1
  34. package/neural-interface/lib/teams/api.js +79 -6
  35. package/neural-interface/lib/teams/index.js +2 -0
  36. package/neural-interface/lib/teams/recovery.js +68 -0
  37. package/neural-interface/lib/teams/scheduler.js +349 -29
  38. package/neural-interface/lib/teams/worktrees.js +123 -30
  39. package/neural-interface/package-lock.json +2 -2
  40. package/neural-interface/package.json +1 -1
  41. package/neural-interface/public/extension-setup.html +6 -2
  42. package/neural-interface/public/shared/agents/studio/ax-api.js +16 -0
  43. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +318 -13
  44. package/neural-interface/public/shared/agents/studio/ax-teams.js +141 -9
  45. package/neural-interface/public/shared/browser-extension-updates.js +3 -1
  46. package/neural-interface/public/shared/extension-setup/es-page.js +23 -4
  47. package/neural-interface/public/shared/extension-setup/es-view.js +51 -11
  48. package/neural-interface/public/shared/extension-update-view.js +1 -1
  49. package/neural-interface/public/shared/settings/settings-ai-browser.js +23 -3
  50. package/neural-interface/public/shared/settings/settings-browser-extension.js +575 -197
  51. package/neural-interface/public/shared/settings/settings-extension-diagrams.js +116 -0
  52. package/neural-interface/public/shared/settings/settings-extension-guide.js +222 -0
  53. package/neural-interface/public/shared/settings/settings-ia.js +2 -2
  54. package/neural-interface/public/shared/settings/settings-shell.js +5 -0
  55. package/neural-interface/public/shared/styles.css +196 -13
  56. package/neural-interface/public/shared/ui-settings.js +48 -11
  57. package/neural-interface/server.js +20 -1
  58. package/npm-shrinkwrap.json +2 -2
  59. package/package.json +1 -1
@@ -16,6 +16,9 @@
16
16
  // `merged`; where it was, the team is as before; anywhere else, it is reported.
17
17
  // any other a worktree whose folder is gone is put back from its branch (the commits are there; what was
18
18
  // uncommitted in the folder went with the folder); a slice whose branch is gone too is `failed`.
19
+ // A team whose integration branch and worktree are both gone and none of whose slices is at work
20
+ // any more is over, and nothing of it is made again: `merged` when its integration head is on its
21
+ // base branch already (merged outside `land`), `failed` when it never joined anything.
19
22
  //
20
23
  // Recovery never deletes work: it removes only what a creation left half-made (no worker had started), and it moves
21
24
  // only the integration branch, back to a commit SynaBun itself recorded, when everything after that commit is a
@@ -164,10 +167,75 @@ export function createTeamRecovery({ state, git, locks, worktrees, claims, integ
164
167
  }
165
168
  }
166
169
 
170
+ /**
171
+ * A team whose integration branch and worktree are both gone, and none of whose slices is still at work, is over:
172
+ * what it joined is on its base branch already (merged outside `land`), or it never joined anything. Making the
173
+ * branch again would bring back a worktree nobody uses, at every start-up. It is closed instead: `merged` (its
174
+ * `landed` says so, `external: true`) or `failed`. A slice whose branch and folder are gone is `failed`, as below;
175
+ * nothing is removed but the team's folder when it is empty. Everything else is left to the steps below: a slice
176
+ * still at work or whose branch is still there, commits on the integration head its base branch does not have, a
177
+ * base branch that is not there.
178
+ * @returns {Promise<boolean>} true when the team was closed
179
+ */
180
+ async function closeIfOver(record, report) {
181
+ if (record.plan.readOnly || !['planned', 'running', 'ready'].includes(record.state)) return false;
182
+ const teamId = record.teamId;
183
+ const cwd = record.projectPath;
184
+ const there = async (sliceId) => {
185
+ const { path, branch } = worktrees.placeOf(record.plan, sliceId);
186
+ return present(path) || !!(await commitOf(git, cwd, `refs/heads/${branch}`));
187
+ };
188
+ if (await there(INTEGRATION_SLICE_ID)) return false;
189
+ const gone = [];
190
+ let left = false;
191
+ for (const slice of record.plan.slices) {
192
+ const settled = SETTLED_SLICE_STATES.includes(sliceState(record, slice.id));
193
+ if (!(await there(slice.id))) { if (!settled) gone.push(slice.id); continue; }
194
+ if (!settled) return false;
195
+ left = true;
196
+ }
197
+ const states = record.plan.slices.map((slice) => (gone.includes(slice.id) ? 'failed' : sliceState(record, slice.id)));
198
+ const head = record.integration.head;
199
+ let closed = null;
200
+ if (!states.includes('integrated') && head === record.baseCommit) closed = 'failed';
201
+ else if (record.baseBranch && head) {
202
+ const target = await commitOf(git, cwd, `refs/heads/${record.baseBranch}`);
203
+ if (target && (await git(['merge-base', '--is-ancestor', head, target], { cwd })).ok) closed = 'merged';
204
+ }
205
+ if (!closed) return false;
206
+ await git(['worktree', 'prune'], { cwd });
207
+ for (const sliceId of gone) {
208
+ await state.writeSlice(teamId, sliceId, 'failed', { reason: 'its branch and its worktree are gone', failedAt: now() });
209
+ report.actions.push({ action: 'slice_failed', sliceId, reason: 'missing' });
210
+ }
211
+ const removed = !left;
212
+ if (closed === 'merged') {
213
+ const tests = record.integration.tests;
214
+ await state.writeTeam(teamId, 'merged', {
215
+ landing: null, removed, recoveredAt: now(),
216
+ landed: {
217
+ targetBranch: record.baseBranch, mode: null, from: null, to: head, integrationHead: head, mergeCommit: null, checkout: null,
218
+ files: null, at: now(), partial: states.some((each) => !['integrated', 'cancelled'].includes(each)),
219
+ tested: !!tests && tests.ok === true && tests.commit === head, external: true, recovered: true,
220
+ },
221
+ });
222
+ } else {
223
+ await state.writeTeam(teamId, 'failed', {
224
+ error: 'Every slice ended and nothing was joined; the integration branch and its worktree were gone at the restart, so recovery closed the team instead of making an empty branch again.',
225
+ failedAt: now(), removed, recovered: true,
226
+ });
227
+ }
228
+ await claims.end(teamId);
229
+ try { rmdirSync(join(worktreesRoot(cwd), teamId)); } catch { /* not empty, or not there */ }
230
+ report.actions.push({ action: 'team_closed', state: closed, reason: closed === 'merged' ? 'merged_outside_landing' : 'nothing_integrated', targetBranch: record.baseBranch, head, removed });
231
+ return true;
232
+ }
233
+
167
234
  /** Worktrees whose folder is gone, slices left in the middle of a join. */
168
235
  async function recoverPieces(record, report) {
169
236
  const teamId = record.teamId;
170
237
  const cwd = record.projectPath;
238
+ if (await closeIfOver(record, report)) return;
171
239
  let registered = await listWorktrees(git, cwd);
172
240
  for (const sliceId of [...record.plan.slices.map((slice) => slice.id), ...(record.plan.readOnly ? [] : [INTEGRATION_SLICE_ID])]) {
173
241
  const current = sliceId === INTEGRATION_SLICE_ID ? null : sliceState(record, sliceId);
@@ -14,7 +14,13 @@
14
14
  // attention and the Assistant is told
15
15
  // land the integration branch into the owner's branch: the owner's step, or the Assistant's when the tests
16
16
  // passed, the owner's branch has not moved and no locally changed file is touched
17
- // discard stop the workers, give the work up
17
+ // cleanup after a landing, the team's worktrees and branches, once every one is merged and clean (the owner's
18
+ // word: from Agents Studio, or the Assistant after the owner said yes in its session)
19
+ // discard stop the workers, give the work up (what holds work is kept unless the owner says `force`); the
20
+ // owner's Discard & remove forgets the team in the same step when nothing of it is left
21
+ // remove forget a closed team (its record here), only once nothing of it is left on disk or in git
22
+ // cleanupMerged a ready team whose work somebody merged into its base branch outside `land`: checked again
23
+ // against git, its landing recorded, its worktrees, branches and record removed (the owner's)
18
24
  //
19
25
  // Agent density targets the selected worker count; fewer requires a reason. Solo starts no
20
26
  // team; workers never work in the owner's checkout or on the owner's branch; the owner's branch receives the work
@@ -30,8 +36,8 @@
30
36
 
31
37
  import { markActivity } from '../loop-stall.js';
32
38
  import { createHash, randomBytes } from 'node:crypto';
33
- import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
34
- import { join } from 'node:path';
39
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs';
40
+ import { dirname, join } from 'node:path';
35
41
  import { AGENT_DENSITY_LABELS, DEFAULT_AGENT_DENSITY, maxWorkers, normalizeAgentDensity } from '../agents/density.js';
36
42
  import { splitTitle } from '../agents/split.js';
37
43
  import { sessionRecipient } from '../coordination/store.js';
@@ -40,8 +46,9 @@ import {
40
46
  unresolvedFollowUp,
41
47
  } from './brief.js';
42
48
  import {
43
- worktreePath, branchName, integrationBranchName, isTeamSlug, normalizeRelPath, normalizeTeamPlan, pathOwner, validateTeamPlan,
49
+ BRANCH_PREFIX, INTEGRATION_SLICE_ID, worktreePath, branchName, integrationBranchName, isTeamSlug, normalizeRelPath, normalizeTeamPlan, pathOwner, validateTeamPlan,
44
50
  } from './schema.js';
51
+ import { TERMINAL_TEAM_STATES } from './state.js';
45
52
  import { TEAM_TEST_TIMEOUT_MS } from './test-runner.js';
46
53
  import { testCommandOf } from './worktrees.js';
47
54
 
@@ -72,6 +79,11 @@ export const TEAM_CHANGED = 'assistant:team-changed';
72
79
  /** A team as the scheduler sees it (its own status; the journal's state is finer). */
73
80
  export const TEAM_STATUSES = Object.freeze(['running', 'needs_attention', 'ready', 'completed', 'landed', 'discarded', 'failed']);
74
81
  const OPEN_STATUSES = new Set(['running', 'needs_attention', 'ready']);
82
+ /** A team that is over: nothing of it runs again. Only such a team can be removed. */
83
+ export const CLOSED_TEAM_STATUSES = Object.freeze(['landed', 'completed', 'discarded', 'failed']);
84
+ const CLOSED_STATUSES = new Set(CLOSED_TEAM_STATUSES);
85
+ /** The durable log's kind of a removal (not a TEAM_EVENTS entry: nobody's mailbox gets it, no page reads a removed team). */
86
+ export const TEAM_REMOVED_LOG_KIND = 'team.removed';
75
87
 
76
88
  export const TEAM_SCHEDULER_LIMITS = Object.freeze({
77
89
  /** How often a slice is sent back to its worker for one kind of trouble before the team needs attention. */
@@ -178,6 +190,9 @@ export function createTeamScheduler({
178
190
  const runIndex = new Map(); // runId → { teamId, sliceId } (every run a slice ever had)
179
191
  const chains = new Map(); // team or slice key → last scheduled operation
180
192
  const postTimes = new Map(); // runId → the times of its recent posts
193
+ // Teams removed while the server runs. A step that was handed a team's record before it was removed must never
194
+ // write that record back (save) or announce it (emit): its id is never made again (the journal keeps it).
195
+ const removedTeams = new Set();
181
196
  let unsubscribe = null;
182
197
  let watchdog = null;
183
198
  let watchdogPass = null;
@@ -200,6 +215,7 @@ export function createTeamScheduler({
200
215
  // ── the scheduler's own record ─────────────────────────────────────────────
201
216
  const fileOf = (teamId) => join(dir, `${teamId}.json`);
202
217
  function save(record) {
218
+ if (removedTeams.has(record.teamId)) return record;
203
219
  record.updatedAt = iso(now());
204
220
  records.set(record.teamId, record);
205
221
  try {
@@ -250,7 +266,9 @@ export function createTeamScheduler({
250
266
  const inTurn = (teamId, fn) => enqueue([teamId], fn);
251
267
  const inSlice = (record, sliceId, fn) => enqueue([`${record.teamId}/${sliceId}`], fn);
252
268
  const withAllSlices = (record, fn) => enqueue(Object.keys(record.slices).map(id => `${record.teamId}/${id}`), fn);
253
- const teamStep = (record, fn) => inTurn(record.teamId, () => withAllSlices(record, fn));
269
+ const gone = (teamId) => refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is known here (it was removed).`, { status: 404 });
270
+ // A step queued before the team was removed finds it gone and changes nothing.
271
+ const teamStep = (record, fn) => inTurn(record.teamId, () => withAllSlices(record, () => (removedTeams.has(record.teamId) ? gone(record.teamId) : fn())));
254
272
  /** Resolves once every team's queued steps have run (tests, shutdown). */
255
273
  async function settled() {
256
274
  while (chains.size) {
@@ -265,7 +283,7 @@ export function createTeamScheduler({
265
283
  */
266
284
  async function emit(record, name, detail = {}, { critical = false, mailbox = null, quiet = false } = {}) {
267
285
  const spec = TEAM_EVENTS[name];
268
- if (!spec) return null;
286
+ if (!spec || removedTeams.has(record.teamId)) return null;
269
287
  record.eventSeq = (Number(record.eventSeq) || 0) + 1;
270
288
  const told = (mailbox === null ? spec.mailbox : mailbox) && !!record.sessionId && !quiet;
271
289
  const payload = {
@@ -384,6 +402,10 @@ export function createTeamScheduler({
384
402
  });
385
403
  let claims = [];
386
404
  try { claims = (await store.claimsFor({ teamId: record.teamId })).map((claim) => ({ sliceId: claim.sliceId, runId: claim.runId || null, glob: claim.glob, claimedAt: claim.claimedAt || claim.createdAt || null })); } catch { claims = []; }
405
+ // A closed team: what is still on disk and in git, and whether its record can go (the page's Clean up / Remove).
406
+ const removal = CLOSED_STATUSES.has(record.status) ? removalView(await removalOf(record, journal)) : null;
407
+ // A ready team whose work is on its base branch already (merged outside land): where, and whether it is clean.
408
+ const alreadyOnTarget = await onTargetOf(record, { full: true });
387
409
  const tests = journal?.integration?.tests || null;
388
410
  const events = (await tailOfLog(record.teamId, TEAM_EVENT_LOG_KINDS, timeline)).map(eventView);
389
411
  const messages = (await tailOfLog(record.teamId, [TEAM_MESSAGE_LOG_KIND], timeline)).map(messageView);
@@ -394,6 +416,8 @@ export function createTeamScheduler({
394
416
  baseCommit: journal?.baseCommit || plan.baseCommit || null, baseBranch: journal?.baseBranch || null,
395
417
  route: record.routeId ? { routeId: record.routeId, taskClass: record.taskClass || null } : null,
396
418
  cap: maxWorkers(record.density),
419
+ removal,
420
+ alreadyOnTarget,
397
421
  },
398
422
  plan,
399
423
  slices,
@@ -1176,18 +1200,26 @@ export function createTeamScheduler({
1176
1200
  });
1177
1201
  }
1178
1202
 
1179
- function cleanup(teamId, { sessionId = null, userConfirmed = false } = {}) {
1203
+ /**
1204
+ * Remove a landed team's worktrees and branches, all or nothing: confirmed, landed, every run ended (the final
1205
+ * worker of each slice done), every branch merged into the target, every worktree clean. `by.kind` 'owner' is
1206
+ * the owner's own page (Agents Studio, whose route only the owner reaches): its confirmation is the owner's
1207
+ * word. Anybody else (the Assistant's agent_team) needs, besides `userConfirmed`, an owner UI turn in the team's
1208
+ * session after the landing, so a worktree is never deleted on the model's word alone.
1209
+ */
1210
+ function cleanup(teamId, { sessionId = null, userConfirmed = false, by = null } = {}) {
1180
1211
  const record = records.get(String(teamId || ''));
1181
1212
  if (!record) return Promise.resolve(refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is known here.`));
1182
1213
  return teamStep(record, async () => {
1183
1214
  if (sessionId && sessionId !== record.sessionId) return refuse('TEAM_FORBIDDEN', 'That team belongs to another Assistant session.');
1184
1215
  if (record.cleanedAt) return { ok: true, teamId: record.teamId, alreadyClean: true, removed: [] };
1185
- const verified = typeof lastOwnerTurnAt === 'function';
1216
+ const owner = by?.kind === 'owner';
1217
+ const verified = !owner && typeof lastOwnerTurnAt === 'function';
1186
1218
  let ownerAt = null;
1187
1219
  if (verified) { try { ownerAt = await lastOwnerTurnAt(record.sessionId); } catch {} }
1188
1220
  const timestamp = value => typeof value === 'number' ? value : Date.parse(value);
1189
- const confirmed = userConfirmed === true && (!verified || timestamp(ownerAt) > timestamp(record.landing?.at));
1190
- const checks = [{ name: 'confirmed', ok: confirmed, detail: verified ? 'Requires explicit confirmation and an owner UI turn after landing.' : 'Owner-turn timing unverified; explicit confirmation required.' },
1221
+ const confirmed = userConfirmed === true && (owner || !verified || timestamp(ownerAt) > timestamp(record.landing?.at));
1222
+ const checks = [{ name: 'confirmed', ok: confirmed, detail: owner ? 'Requires the owner\'s explicit confirmation from SynaBun\'s own page.' : verified ? 'Requires explicit confirmation and an owner UI turn after landing.' : 'Owner-turn timing unverified; explicit confirmation required.' },
1191
1223
  { name: 'landed', ok: record.status === 'landed', detail: `Team status: ${record.status}` }];
1192
1224
  const dispatcher = dispatcherOf();
1193
1225
  const finalIds = new Set();
@@ -1227,9 +1259,9 @@ export function createTeamScheduler({
1227
1259
  const out = await teams.remove(record.teamId, { guarded: true });
1228
1260
  if (!out.ok) return { ...out, checks: [...checks, ...(out.checks || [])] };
1229
1261
  record.cleanedAt = iso(now());
1230
- record.cleanup = { complete: true, removed: out.removed };
1231
- await emit(record, 'team_cleaned', { text: 'Confirmed cleanup removed the team worktrees and branches.' });
1232
- return { ok: true, teamId: record.teamId, removed: out.removed, ...(!verified ? { confirmation: 'unverified' } : {}) };
1262
+ record.cleanup = { complete: true, removed: out.removed, by: owner ? 'owner' : 'assistant' };
1263
+ await emit(record, 'team_cleaned', { text: owner ? 'The owner cleaned up the team\'s worktrees and branches from Agents Studio.' : 'Confirmed cleanup removed the team worktrees and branches.', by: owner ? 'owner' : 'assistant' });
1264
+ return { ok: true, teamId: record.teamId, removed: out.removed, ...(!owner && !verified ? { confirmation: 'unverified' } : {}) };
1233
1265
  });
1234
1266
  }
1235
1267
 
@@ -1241,28 +1273,305 @@ export function createTeamScheduler({
1241
1273
  try { return (await dispatcher.killAll({ workflowId: record.workflowId, reason })).stopped || []; } catch (error) { say('teams:stop-failed', { teamId: record.teamId, error: error?.message || String(error) }); return []; }
1242
1274
  }
1243
1275
 
1244
- /** Give a team up: its workers are stopped, its worktrees and branches removed (what holds work is kept unless `force`). */
1245
- function discard(teamId, { by = { kind: 'owner' }, force = false, reason = '' } = {}) {
1276
+ /**
1277
+ * Give a team up: its workers are stopped, its worktrees and branches removed (what holds work is kept unless the
1278
+ * owner says `force`). Asked again of a discarded team whose work was kept, with `force`, it deletes that work:
1279
+ * the owner's step that lets the team be removed afterwards.
1280
+ */
1281
+ function discard(teamId, { by = { kind: 'owner' }, force = false, reason = '', remove: andRemove = false } = {}) {
1246
1282
  const record = records.get(String(teamId || ''));
1247
1283
  if (!record) return Promise.resolve(refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is known here.`, { status: 404 }));
1248
1284
  return teamStep(record, async () => {
1285
+ const out = await discardNow(record, { by, force, reason });
1286
+ // Discard & remove (the owner's): the record goes too, in the same step, only once the discard left nothing on
1287
+ // disk or in git and no worker lives (removalOf). Otherwise the team stays, discarded, and the answer says why.
1288
+ if (!out.ok || andRemove !== true || by?.kind !== 'owner') return out;
1289
+ if (!out.complete) return { ...out, teamRemoved: false, removal: removalView(await removalOf(record)) };
1290
+ const check = await removalOf(record);
1291
+ if (!check.ok) return { ...out, teamRemoved: false, removal: removalView(check) };
1292
+ const gone = await removeNow(record, { by, check });
1293
+ return { ...out, teamRemoved: gone.ok === true, ...(gone.ok ? {} : { removal: { removable: false, code: gone.code, message: gone.message, next: null, left: [] } }) };
1294
+ });
1295
+ }
1296
+
1297
+ /** The discard itself, inside the team's step. */
1298
+ async function discardNow(record, { by = { kind: 'owner' }, force = false, reason = '' } = {}) {
1299
+ const teamId = record.teamId;
1300
+ const journal = await journalOf(record.teamId);
1301
+ if (journal?.state === 'merged') return refuse('ALREADY_LANDED', `Team "${teamId}" has landed: there is nothing to discard.`, { status: 409 });
1302
+ if (record.status === 'discarded' && journal?.removed) return { ok: true, already: true, complete: true, removed: [], kept: [], cleanup: record.cleanup };
1303
+ const assistant = by?.kind !== 'owner';
1304
+ const forced = !assistant && force === true;
1305
+ const again = record.status === 'discarded';
1306
+ const stopped = await stopRuns(record, 'team_discarded');
1307
+ const removed = await teams.remove(record.teamId, { discard: true, force: forced });
1308
+ if (!removed.ok) return removed; // the library's refusal, unchanged
1309
+ record.status = 'discarded';
1310
+ record.attention = null;
1311
+ record.cleanup = { complete: removed.complete === true, kept: (removed.kept || []).map((item) => ({ sliceId: item.sliceId, path: item.path, branch: item.branch, reason: item.reason, files: (item.files || []).slice(0, 20), commits: item.commits ?? null })), ...(forced ? { forced: true } : {}) };
1312
+ const kept = record.cleanup.kept.length;
1313
+ const outcome = removed.complete ? (again ? 'The work that was kept is deleted: worktrees and branches removed.' : 'Worktrees and branches removed.') : `${kept} worktree${kept === 1 ? '' : 's'} or branch${kept === 1 ? '' : 'es'} kept because work is in them.`;
1314
+ await emit(record, 'discarded', {
1315
+ text: `${again ? 'Discarded again' : 'Discarded'}${forced ? ' (force)' : ''}${reason ? `: ${clip(reason, 200)}` : ''}. ${outcome}`, by: by?.kind || 'owner',
1316
+ }, { quiet: assistant && by?.sessionId === record.sessionId });
1317
+ return { ok: true, stopped, complete: removed.complete === true, removed: removed.removed || [], kept: record.cleanup.kept };
1318
+ }
1319
+
1320
+ // ── removing a closed team ─────────────────────────────────────────────────
1321
+ /** The runs of a team that are still alive (working, waiting warm, queued, suspended, resuming). */
1322
+ function liveRunsOf(record) {
1323
+ const dispatcher = dispatcherOf();
1324
+ if (!dispatcher || typeof dispatcher.get !== 'function') return null;
1325
+ const ids = new Set();
1326
+ for (const slice of Object.values(record.slices || {})) {
1327
+ for (const id of slice.runIds || []) ids.add(id);
1328
+ if (slice.runId) ids.add(slice.runId);
1329
+ }
1330
+ let listed = null;
1331
+ try { listed = dispatcher.teamRuns?.(record.teamId, record.workflowId); } catch { listed = null; }
1332
+ if (Array.isArray(listed)) for (const run of listed) if (run?.runId) ids.add(run.runId);
1333
+ const live = [];
1334
+ for (const id of ids) {
1335
+ const run = runOf(id);
1336
+ if (run && (run.active === true || run.state === 'running' || run.state === 'queued')) live.push(`${id}: ${run.state || 'active'}`);
1337
+ }
1338
+ return live;
1339
+ }
1340
+
1341
+ const present = (path) => { try { lstatSync(path); return true; } catch { return false; } };
1342
+ const isFolder = (path) => { try { return lstatSync(path).isDirectory(); } catch { return false; } };
1343
+
1344
+ /**
1345
+ * What of a team is still on disk and in git, asked of git and the disk (never of what the records say): each
1346
+ * worktree's folder, each branch under the team's prefix, anything else in the team's folder of `.worktrees/`.
1347
+ * → { checked: true, left: [{ sliceId, path, branch, worktree, branchExists }] } or { checked: false, code, message }
1348
+ */
1349
+ async function leftoversOf(record, journal) {
1350
+ const cwd = record.projectPath;
1351
+ if (!cwd || !isFolder(cwd)) return { checked: false, code: 'PROJECT_NOT_FOUND', message: `The project folder ${cwd || '(none)'} is not there, so SynaBun cannot check that nothing of the team is left. Put the folder back (or mount its disk) and try again.` };
1352
+ if (typeof git !== 'function') return { checked: false, code: 'GIT_UNAVAILABLE', message: 'SynaBun cannot ask git about this team here.' };
1353
+ const prefix = `refs/heads/${BRANCH_PREFIX}/${record.teamId}/`;
1354
+ let refs;
1355
+ try { refs = await git(['for-each-ref', '--format=%(refname)', prefix], { cwd }); } catch { refs = null; }
1356
+ if (!refs?.ok) return { checked: false, code: 'NOT_A_REPOSITORY', message: `${cwd} could not be read as a git repository, so SynaBun cannot check that the team's branches are gone.` };
1357
+ const branches = new Set(String(refs.stdout || '').split('\n').map((line) => line.trim()).filter(Boolean).map((ref) => ref.slice('refs/heads/'.length)));
1358
+ const plan = journal?.plan || record.plan || { slices: [] };
1359
+ const pieces = [...(plan.slices || []).map((slice) => slice.id), ...(plan.readOnly ? [] : [INTEGRATION_SLICE_ID])];
1360
+ const left = [];
1361
+ const paths = new Set();
1362
+ for (const sliceId of pieces) {
1363
+ let path;
1364
+ try { path = worktreePath(cwd, record.teamId, sliceId); } catch { continue; }
1365
+ const branch = sliceId === INTEGRATION_SLICE_ID ? integrationBranchName(record.teamId) : branchName(record.teamId, sliceId);
1366
+ paths.add(path);
1367
+ const worktree = present(path);
1368
+ const branchExists = branches.delete(branch);
1369
+ if (worktree || branchExists) left.push({ sliceId, path, branch, worktree, branchExists });
1370
+ }
1371
+ // A branch under the team's prefix that is no slice of its plan is the team's too.
1372
+ for (const branch of branches) left.push({ sliceId: null, path: null, branch, worktree: false, branchExists: true });
1373
+ let folder = null;
1374
+ try { folder = dirname(worktreePath(cwd, record.teamId, INTEGRATION_SLICE_ID)); } catch { folder = null; }
1375
+ if (folder && isFolder(folder)) {
1376
+ let names = [];
1377
+ try { names = readdirSync(folder); } catch { names = []; }
1378
+ for (const name of names) {
1379
+ const path = join(folder, name);
1380
+ if (!paths.has(path)) left.push({ sliceId: null, path, branch: null, worktree: true, branchExists: false });
1381
+ }
1382
+ }
1383
+ return { checked: true, left, folder };
1384
+ }
1385
+
1386
+ /**
1387
+ * Can a team's record go? Only a closed team (landed, completed, discarded, failed) with no live run and nothing
1388
+ * left on disk or in git: a landed team that was not cleaned up, a discarded one whose work was kept, are refused,
1389
+ * so work is never left behind without a record that points at it.
1390
+ */
1391
+ async function removalOf(record, journal = undefined) {
1392
+ const known = journal === undefined ? await journalOf(record.teamId) : journal;
1393
+ if (!CLOSED_STATUSES.has(record.status)) return refuse('TEAM_OPEN', `Team "${record.teamId}" is ${record.status}: only a closed team (landed, completed, discarded or failed) can be removed. Land or discard it first.`, { status: 409 });
1394
+ // The journal must be over too: the library's recovery acts on a team that is not (it could make a worktree
1395
+ // again), and nothing would point at what it made once the record is gone. A team with no journal entry is over.
1396
+ if (known && !TERMINAL_TEAM_STATES.includes(known.state)) return refuse('TEAM_NEEDS_RECOVERY', `Team "${record.teamId}" is recorded as ${known.state} in the journal: restart SynaBun so its recovery runs before it is removed.`, { status: 409 });
1397
+ const live = liveRunsOf(record);
1398
+ if (live === null) return refuse('DISPATCH_UNAVAILABLE', 'The Assistant\'s dispatcher is not running, so SynaBun cannot check that no worker of the team is still alive.', { status: 503 });
1399
+ if (live.length) return refuse('TEAM_RUNS_ACTIVE', `A worker of team "${record.teamId}" is still alive (${live.join(', ')}): stop it before the team is removed.`, { status: 409, runs: live });
1400
+ const disk = await leftoversOf(record, known);
1401
+ if (!disk.checked) return refuse(disk.code, disk.message, { status: 409 });
1402
+ if (disk.left.length) {
1403
+ const readOnly = (known?.plan || record.plan)?.readOnly === true;
1404
+ const next = record.status === 'landed' && !readOnly ? 'cleanup' : (record.status === 'discarded' || record.status === 'failed') && !readOnly ? 'force_discard' : 'by_hand';
1405
+ const what = `${disk.left.length} worktree${disk.left.length === 1 ? '' : 's'} or branch${disk.left.length === 1 ? '' : 'es'} of it ${disk.left.length === 1 ? 'is' : 'are'} still there`;
1406
+ const how = next === 'cleanup' ? 'Clean up its worktrees first (they are removed only when every branch is merged and every worktree is clean).'
1407
+ : next === 'force_discard' ? 'They hold work that was not landed: delete the kept work first (discard with force), or land it another way.'
1408
+ : 'Remove them by hand (git worktree remove, git branch -d) once you no longer need them.';
1409
+ return refuse('TEAM_WORKTREES_LEFT', `Team "${record.teamId}" cannot be removed: ${what} (${disk.left.map((item) => item.path || item.branch).slice(0, 6).join(', ')}). ${how}`, { status: 409, next, left: disk.left });
1410
+ }
1411
+ return { ok: true, teamId: record.teamId, removable: true, left: [], folder: disk.folder };
1412
+ }
1413
+
1414
+ /** A removal answer as the page reads it. */
1415
+ const removalView = (out) => ({
1416
+ removable: out.ok === true, code: out.ok ? null : out.code || null, message: out.ok ? null : out.message || null,
1417
+ next: out.next || null, left: (out.left || []).map((item) => ({ sliceId: item.sliceId ?? null, path: item.path ?? null, branch: item.branch ?? null, worktree: item.worktree === true, branchExists: item.branchExists === true })),
1418
+ });
1419
+
1420
+ /** Whether a team's record can be removed now, and what is left of it when not (no change is made). */
1421
+ async function removability(teamId) {
1422
+ const record = records.get(String(teamId || ''));
1423
+ if (!record) return { removable: false, code: 'TEAM_NOT_FOUND', message: `No team named "${teamId}" is known here.`, next: null, left: [] };
1424
+ return removalView(await removalOf(record));
1425
+ }
1426
+
1427
+ /**
1428
+ * Forget a closed team: its record here (`<dataDir>/teams/<teamId>.json`) and its test sandbox profile go, and it
1429
+ * leaves the list. Nothing in git or on disk is touched (removalOf refuses while anything of it is there); the
1430
+ * journal and the durable log keep their entries, so the team's id is never made again. The record is written
1431
+ * nowhere after this: never through emit(), which saves the record again.
1432
+ */
1433
+ function remove(teamId, { by = { kind: 'owner' } } = {}) {
1434
+ const record = records.get(String(teamId || ''));
1435
+ if (!record) return Promise.resolve(refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is known here.`, { status: 404 }));
1436
+ return teamStep(record, async () => {
1437
+ const check = await removalOf(record);
1438
+ if (!check.ok) return check;
1439
+ return removeNow(record, { by, check });
1440
+ });
1441
+ }
1442
+
1443
+ /** The removal itself, inside the team's step, once removalOf said yes (`check`). */
1444
+ async function removeNow(record, { by = { kind: 'owner' }, check } = {}) {
1445
+ // The team's own empty folder of .worktrees/ (nothing is in it: removalOf looked).
1446
+ if (check?.folder) { try { rmdirSync(check.folder); } catch { /* not there */ } }
1447
+ try { unlinkSync(fileOf(record.teamId)); } catch (error) {
1448
+ if (error?.code !== 'ENOENT') return refuse('TEAM_REMOVE_FAILED', `The record of team "${record.teamId}" could not be deleted: ${error?.message || error}`, { status: 500 });
1449
+ }
1450
+ removedTeams.add(record.teamId);
1451
+ try { unlinkSync(join(dir, 'sandbox', `${record.teamId}.sb`)); } catch { /* none was written */ }
1452
+ records.delete(record.teamId);
1453
+ const runIds = [];
1454
+ for (const [runId, ref] of runIndex) if (ref.teamId === record.teamId) runIds.push(runId);
1455
+ for (const runId of runIds) { runIndex.delete(runId); postTimes.delete(runId); }
1456
+ try {
1457
+ await store.append({
1458
+ id: `team:${record.teamId}:removed`, kind: TEAM_REMOVED_LOG_KIND, priority: 'low', teamId: record.teamId, sessionId: record.sessionId || null, runId: null,
1459
+ payload: { kind: 'team_removed', teamId: record.teamId, title: record.title || null, status: record.status, by: by?.kind || 'owner' }, to: [],
1460
+ });
1461
+ } catch (error) { say('teams:event-failed', { teamId: record.teamId, event: 'team_removed', error: error?.message || String(error) }); }
1462
+ try { broadcast({ type: TEAM_CHANGED, teamId: record.teamId, event: 'removed', status: null, sliceId: null }); } catch { /* no page is listening */ }
1463
+ say('teams:removed', { teamId: record.teamId, status: record.status, by: by?.kind || 'owner' });
1464
+ // `closedAs`, never `status`: a route's answer takes `status` for the HTTP status (lib/teams/api.js).
1465
+ return { ok: true, teamId: record.teamId, removed: true, closedAs: record.status };
1466
+ }
1467
+
1468
+ // ── a team whose work is on its base branch already ────────────────────────
1469
+ /**
1470
+ * A `ready` code team whose joined work reached its base branch outside `land` (somebody merged the integration
1471
+ * branch by hand), its worktrees and branches still there: where, and whether they could go now (`clean`: every
1472
+ * worktree clean, every branch merged into the base branch, no worker alive). Asked of git (teams.onTarget), never
1473
+ * of the records; null for every other team. `full`: also what keeps it from being clean.
1474
+ */
1475
+ async function onTargetOf(record, { full = false } = {}) {
1476
+ if (record.status !== 'ready' || record.plan?.readOnly === true || typeof teams.onTarget !== 'function') return null;
1477
+ let found = null;
1478
+ try { found = await teams.onTarget(record.teamId); } catch (error) { say('teams:on-target-failed', { teamId: record.teamId, error: error?.message || String(error) }); return null; }
1479
+ if (!found) return null;
1480
+ const live = liveRunsOf(record);
1481
+ const runs = live === null ? null : live.length;
1482
+ const brief = { branch: found.branch, head: found.head, clean: found.clean === true && runs === 0 };
1483
+ if (!full) return brief;
1484
+ return { ...brief, targetHead: found.targetHead, live: found.live, moved: found.moved === true, runs, dirty: found.dirty || [], unmerged: found.unmerged || [], other: found.other || [] };
1485
+ }
1486
+
1487
+ /**
1488
+ * What the Agents Studio list says of a team beside its summary, asked of git, the disk and the dispatcher: a
1489
+ * closed team's `removable`; a team that waits on the owner (needs attention, ready) its live workers (`liveRuns`),
1490
+ * how much of it is on disk (`left`: worktrees and branches) and, ready, whether its work is on its base branch
1491
+ * already (`alreadyOnTarget`). A running team: nothing (the page offers it nothing from the list).
1492
+ */
1493
+ async function overview(teamId) {
1494
+ const record = records.get(String(teamId || ''));
1495
+ if (!record) return null;
1496
+ if (CLOSED_STATUSES.has(record.status)) return { removable: (await removability(record.teamId)).removable === true };
1497
+ if (record.status !== 'needs_attention' && record.status !== 'ready') return {};
1498
+ const live = liveRunsOf(record);
1499
+ const disk = await leftoversOf(record, await journalOf(record.teamId));
1500
+ return {
1501
+ liveRuns: live === null ? null : live.length,
1502
+ left: disk.checked ? disk.left.length : null,
1503
+ alreadyOnTarget: await onTargetOf(record),
1504
+ };
1505
+ }
1506
+
1507
+ /**
1508
+ * The owner's Clean up & remove of a team whose work is on its base branch already: everything is asked again of
1509
+ * git as it runs (on the base branch, every worktree clean, every branch merged, no worker alive); refused, nothing
1510
+ * is removed and the answer says why. Then the landing somebody else made is recorded (`landed.external`), the
1511
+ * worktrees and branches go, and the team's record with them. Only from the owner's page (`by.kind` 'owner',
1512
+ * `userConfirmed`).
1513
+ */
1514
+ function cleanupMerged(teamId, { by = null, userConfirmed = false } = {}) {
1515
+ const record = records.get(String(teamId || ''));
1516
+ if (!record) return Promise.resolve(refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is known here.`, { status: 404 }));
1517
+ return teamStep(record, async () => {
1518
+ if (by?.kind !== 'owner') return refuse('TEAM_FORBIDDEN', 'Cleaning up a team that is on its base branch already is the owner\'s, from Agents Studio.', { status: 403 });
1519
+ if (userConfirmed !== true) return refuse('CLEANUP_NOT_CONFIRMED', 'Requires the owner\'s explicit confirmation from SynaBun\'s own page.');
1520
+ if (record.plan.readOnly) return refuse('TEAM_READ_ONLY', 'Research and review teams have no integration branch.');
1521
+ if (record.status !== 'ready') return refuse('TEAM_NOT_READY', `Team "${record.teamId}" is ${record.status}: only a ready team whose work is on its base branch already is cleaned up this way.`);
1522
+ const live = liveRunsOf(record);
1523
+ if (live === null) return refuse('DISPATCH_UNAVAILABLE', 'The Assistant\'s dispatcher is not running, so SynaBun cannot check that no worker of the team is still alive.', { status: 503 });
1524
+ if (live.length) return refuse('TEAM_RUNS_ACTIVE', `A worker of team "${record.teamId}" is still alive (${live.join(', ')}): nothing was removed.`, { runs: live });
1525
+ let out;
1526
+ try {
1527
+ out = await teams.remove(record.teamId, { guarded: true, mergedOutside: true });
1528
+ } catch (error) {
1529
+ out = refuse('CLEANUP_INTERRUPTED', `${error?.message || String(error)}. Look at the team's worktrees before trying again.`, { status: 500 });
1530
+ }
1531
+ // The landing is recorded before anything is removed: whatever came of the removal, the journal may say so now.
1249
1532
  const journal = await journalOf(record.teamId);
1250
- if (journal?.state === 'merged') return refuse('ALREADY_LANDED', `Team "${teamId}" has landed: there is nothing to discard.`, { status: 409 });
1251
- if (record.status === 'discarded' && journal?.removed) return { ok: true, already: true, cleanup: record.cleanup };
1252
- const assistant = by?.kind !== 'owner';
1253
- const stopped = await stopRuns(record, 'team_discarded');
1254
- const removed = await teams.remove(record.teamId, { discard: true, force: !assistant && force === true });
1255
- if (!removed.ok) return removed; // the library's refusal, unchanged
1256
- record.status = 'discarded';
1257
- record.attention = null;
1258
- record.cleanup = { complete: removed.complete === true, kept: (removed.kept || []).map((item) => ({ sliceId: item.sliceId, path: item.path, branch: item.branch, reason: item.reason, files: (item.files || []).slice(0, 20), commits: item.commits ?? null })) };
1259
- await emit(record, 'discarded', {
1260
- text: `Discarded${reason ? `: ${clip(reason, 200)}` : ''}. ${removed.complete ? 'Worktrees and branches removed.' : `${record.cleanup.kept.length} worktree${record.cleanup.kept.length === 1 ? '' : 's'} or branch${record.cleanup.kept.length === 1 ? '' : 'es'} kept because work is in them.`}`, by: by?.kind || 'owner',
1261
- }, { quiet: assistant && by?.sessionId === record.sessionId });
1262
- return { ok: true, stopped, complete: removed.complete === true, removed: removed.removed || [], kept: record.cleanup.kept };
1533
+ const landed = journal?.state === 'merged' ? (out.landed || journal.landed || null) : null;
1534
+ if (landed) {
1535
+ record.status = 'landed';
1536
+ record.attention = null;
1537
+ record.landing = { landed, at: iso(now()), by: 'owner', external: true };
1538
+ }
1539
+ if (!out.ok) {
1540
+ if (landed) {
1541
+ record.cleanup = { available: true, next: 'The team\'s work is on its base branch; its worktrees and branches are kept until a clean-up can remove them.' };
1542
+ await emit(record, 'landed', { targetBranch: landed.targetBranch, mode: null, to: landed.to || null, text: `Found on ${landed.targetBranch} already (merged outside SynaBun); its worktrees and branches were kept: ${clip(out.message, 300)}`, by: 'owner' });
1543
+ }
1544
+ return out; // nothing was removed (the library's refusal, unchanged)
1545
+ }
1546
+ const branch = landed?.targetBranch || journal?.baseBranch || null;
1547
+ record.cleanedAt = iso(now());
1548
+ record.cleanup = { complete: true, removed: out.removed, by: 'owner', external: true };
1549
+ await emit(record, 'team_cleaned', { text: `Already on ${branch}: the owner cleaned up the team's worktrees and branches from Agents Studio and removed the team.`, by: 'owner', targetBranch: branch });
1550
+ const check = await removalOf(record, journal);
1551
+ if (!check.ok) return { ok: true, teamId: record.teamId, branch, removed: out.removed, teamRemoved: false, removal: removalView(check) };
1552
+ const gone = await removeNow(record, { by, check });
1553
+ return { ok: true, teamId: record.teamId, branch, removed: out.removed, teamRemoved: gone.ok === true, ...(gone.ok ? {} : { removal: { removable: false, code: gone.code, message: gone.message, next: null, left: [] } }) };
1263
1554
  });
1264
1555
  }
1265
1556
 
1557
+ /**
1558
+ * Remove every closed team that can go (the page's Clear finished). A team that cannot is never dropped quietly:
1559
+ * it is listed in `skipped` with why (`code`, `next`: cleanup, force_discard, by_hand).
1560
+ */
1561
+ async function clearFinished({ sessionId = null, projectPath = null, by = { kind: 'owner' } } = {}) {
1562
+ const removed = [];
1563
+ const skipped = [];
1564
+ const closedTeams = [...records.values()]
1565
+ .filter((record) => CLOSED_STATUSES.has(record.status) && (!sessionId || record.sessionId === String(sessionId)) && (!projectPath || record.projectPath === projectPath))
1566
+ .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
1567
+ for (const record of closedTeams) {
1568
+ const out = await remove(record.teamId, { by });
1569
+ if (out.ok) removed.push(record.teamId);
1570
+ else skipped.push({ teamId: record.teamId, title: record.title || record.teamId, status: record.status, code: out.code || null, message: out.message || null, next: out.next || null, left: (out.left || []).length });
1571
+ }
1572
+ return { ok: true, removed, skipped };
1573
+ }
1574
+
1266
1575
  // ── the channel (a worker's `team` tool) ───────────────────────────────────
1267
1576
  /** The team and slice a run works on now, or null: only the slice's current run, while it lives, is a member. */
1268
1577
  function member(runId) {
@@ -1489,7 +1798,14 @@ export function createTeamScheduler({
1489
1798
  await withAllSlices(record, async () => {
1490
1799
  const journal = await journalOf(record.teamId);
1491
1800
  if (!journal) { record.status = 'failed'; record.attention = { code: 'TEAM_RECORD_MISSING', sliceId: null, message: 'The team has no record in the journal any more.', at: iso(now()) }; save(record); return { teamId: record.teamId, status: record.status }; }
1492
- if (journal.state === 'merged') { record.status = 'landed'; save(record); return { teamId: record.teamId, status: record.status }; }
1801
+ if (journal.state === 'merged') {
1802
+ record.status = 'landed';
1803
+ // Closed by the library's recovery with no branch or worktree of it left (merged outside land and tidied
1804
+ // by hand): there is nothing for a confirmed cleanup to remove.
1805
+ if (journal.removed && !record.cleanedAt) { record.cleanedAt = iso(now()); record.cleanup = { complete: true, removed: [] }; }
1806
+ save(record);
1807
+ return { teamId: record.teamId, status: record.status };
1808
+ }
1493
1809
  if (journal.state === 'cancelled' || journal.state === 'failed') { record.status = journal.state === 'failed' ? 'failed' : 'discarded'; save(record); return { teamId: record.teamId, status: record.status }; }
1494
1810
  for (const slice of record.plan.slices) {
1495
1811
  const mine = record.slices[slice.id];
@@ -1556,6 +1872,10 @@ export function createTeamScheduler({
1556
1872
  return Object.freeze({
1557
1873
  limits,
1558
1874
  plan, start, status, list, get, ownedBy, assign, setTestCommand, integrate, land, cleanup, discard,
1875
+ // a closed team's record (the owner's, from Agents Studio)
1876
+ removability, remove, clearFinished,
1877
+ // what the Studio's list says beside a summary; a ready team whose work is on its base branch already
1878
+ overview, cleanupMerged,
1559
1879
  // the channel of a worker's `team` tool (the caller's proven run id decides the team)
1560
1880
  member, post, read, wait, ack, claims, request,
1561
1881
  recover: () => track(recover()), attach, shutdown, settled,