synabun 2.4.4 → 2.4.6

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 (129) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +1 -1
  3. package/docs/browser-extension-bridge.md +5 -4
  4. package/docs/whatsapp.md +19 -3
  5. package/hooks/claude-code/session-start.mjs +21 -18
  6. package/lib/claude-global-config.js +214 -0
  7. package/lib/client-config-repair.js +17 -3
  8. package/mcp-server/dist/index.d.ts.map +1 -1
  9. package/mcp-server/dist/index.js +6 -1
  10. package/mcp-server/dist/index.js.map +1 -1
  11. package/mcp-server/dist/services/neural-interface.d.ts +1 -0
  12. package/mcp-server/dist/services/neural-interface.d.ts.map +1 -1
  13. package/mcp-server/dist/services/neural-interface.js +1 -0
  14. package/mcp-server/dist/services/neural-interface.js.map +1 -1
  15. package/mcp-server/dist/services/tool-catalog.js +1 -1
  16. package/mcp-server/dist/services/tool-catalog.js.map +1 -1
  17. package/mcp-server/dist/tools/agents.d.ts +18 -3
  18. package/mcp-server/dist/tools/agents.d.ts.map +1 -1
  19. package/mcp-server/dist/tools/agents.js +85 -16
  20. package/mcp-server/dist/tools/agents.js.map +1 -1
  21. package/mcp-server/dist/tools/skill-tools.d.ts +24 -5
  22. package/mcp-server/dist/tools/skill-tools.d.ts.map +1 -1
  23. package/mcp-server/dist/tools/skill-tools.js +88 -8
  24. package/mcp-server/dist/tools/skill-tools.js.map +1 -1
  25. package/mcp-server/dist/tools/tool-groups.d.ts.map +1 -1
  26. package/mcp-server/dist/tools/tool-groups.js +19 -4
  27. package/mcp-server/dist/tools/tool-groups.js.map +1 -1
  28. package/mcp-server/package-lock.json +2 -2
  29. package/mcp-server/package.json +1 -1
  30. package/mcp-server/src/index.ts +6 -1
  31. package/mcp-server/src/services/neural-interface.ts +2 -1
  32. package/mcp-server/src/services/tool-catalog.ts +1 -1
  33. package/mcp-server/src/tools/agents.ts +78 -16
  34. package/mcp-server/src/tools/skill-tools.ts +82 -9
  35. package/mcp-server/src/tools/tool-groups.ts +19 -4
  36. package/neural-interface/i18n/en.json +484 -19
  37. package/neural-interface/i18n/pt-BR.json +484 -19
  38. package/neural-interface/lib/agents-studio-api.js +7 -2
  39. package/neural-interface/lib/antigravity/home.js +43 -8
  40. package/neural-interface/lib/antigravity/panel-bridge.js +7 -3
  41. package/neural-interface/lib/antigravity/tool-call.js +14 -0
  42. package/neural-interface/lib/assistant-brains/antigravity.js +4 -2
  43. package/neural-interface/lib/assistant-dispatch.js +15 -1
  44. package/neural-interface/lib/assistant-persona.js +8 -3
  45. package/neural-interface/lib/assistant-route-gate.js +11 -2
  46. package/neural-interface/lib/assistant-runtime.js +95 -13
  47. package/neural-interface/lib/assistant-spilled-output.js +53 -0
  48. package/neural-interface/lib/assistant-user-context.js +7 -3
  49. package/neural-interface/lib/browser-default.js +22 -2
  50. package/neural-interface/lib/browser-extension-bridge.js +50 -3
  51. package/neural-interface/lib/browser-extension-pin.json +7 -7
  52. package/neural-interface/lib/browser-extension-protocol.js +30 -1
  53. package/neural-interface/lib/browser-extension-setup.js +204 -36
  54. package/neural-interface/lib/claude-agent-bridge.js +13 -2
  55. package/neural-interface/lib/codex-thread-history.js +144 -7
  56. package/neural-interface/lib/codex-worker-app-server.js +84 -30
  57. package/neural-interface/lib/db.js +26 -0
  58. package/neural-interface/lib/greeting/sources.js +7 -3
  59. package/neural-interface/lib/jsonl-lines.js +10 -11
  60. package/neural-interface/lib/line-buffer.js +88 -0
  61. package/neural-interface/lib/loop-stall.js +15 -1
  62. package/neural-interface/lib/memory-list-read.js +105 -0
  63. package/neural-interface/lib/memory-timers.js +4 -1
  64. package/neural-interface/lib/native-loop-runtime.js +7 -3
  65. package/neural-interface/lib/provider-panel-api-key-auth.js +33 -6
  66. package/neural-interface/lib/remote-policy.js +24 -7
  67. package/neural-interface/lib/skills/api-v2.js +18 -3
  68. package/neural-interface/lib/skills/bundle.js +2 -2
  69. package/neural-interface/lib/skills/deploy.js +169 -34
  70. package/neural-interface/lib/skills/digest.js +57 -3
  71. package/neural-interface/lib/skills/health.js +55 -1
  72. package/neural-interface/lib/skills/known-bridge-digests.json +12 -0
  73. package/neural-interface/lib/skills/runtime-checks.js +7 -4
  74. package/neural-interface/lib/skills/scan-shell.js +56 -7
  75. package/neural-interface/lib/skills/scan.js +13 -12
  76. package/neural-interface/lib/skills/service.js +7 -2
  77. package/neural-interface/lib/skills/telemetry.js +2 -2
  78. package/neural-interface/lib/teams/README.md +34 -6
  79. package/neural-interface/lib/teams/api.js +94 -10
  80. package/neural-interface/lib/teams/index.js +4 -0
  81. package/neural-interface/lib/teams/landing.js +195 -75
  82. package/neural-interface/lib/teams/recovery.js +68 -0
  83. package/neural-interface/lib/teams/scheduler.js +380 -61
  84. package/neural-interface/lib/teams/worktrees.js +123 -30
  85. package/neural-interface/lib/terminal-token-redaction.js +228 -58
  86. package/neural-interface/lib/terminal-tokens.js +18 -0
  87. package/neural-interface/lib/whatsapp/brain.js +21 -0
  88. package/neural-interface/lib/whatsapp/bridge.js +40 -4
  89. package/neural-interface/package-lock.json +2 -2
  90. package/neural-interface/package.json +1 -1
  91. package/neural-interface/public/extension-setup.html +6 -2
  92. package/neural-interface/public/index.html +117 -37
  93. package/neural-interface/public/shared/agents/studio/ax-api.js +27 -0
  94. package/neural-interface/public/shared/agents/studio/ax-create-view.js +1 -1
  95. package/neural-interface/public/shared/agents/studio/ax-icons.js +1 -0
  96. package/neural-interface/public/shared/agents/studio/ax-library-view.js +3 -2
  97. package/neural-interface/public/shared/agents/studio/ax-main.js +127 -41
  98. package/neural-interface/public/shared/agents/studio/ax-review-view.js +3 -2
  99. package/neural-interface/public/shared/agents/studio/ax-teams-view.js +436 -33
  100. package/neural-interface/public/shared/agents/studio/ax-teams.js +357 -10
  101. package/neural-interface/public/shared/agents/studio/ax-ui.js +31 -0
  102. package/neural-interface/public/shared/agents/studio/ax-views.js +67 -69
  103. package/neural-interface/public/shared/agents/studio/ax-work-answer.js +86 -0
  104. package/neural-interface/public/shared/agents/studio/ax-work-view.js +305 -0
  105. package/neural-interface/public/shared/agents/studio/ax-work.css +74 -0
  106. package/neural-interface/public/shared/agents/studio/ax-work.js +300 -0
  107. package/neural-interface/public/shared/browser-extension-updates.js +3 -1
  108. package/neural-interface/public/shared/cdx/cdx-deferred.js +90 -0
  109. package/neural-interface/public/shared/cdx/cdx-render.js +18 -7
  110. package/neural-interface/public/shared/cdx/cdx-tabs.js +2 -1
  111. package/neural-interface/public/shared/extension-setup/es-page.js +23 -4
  112. package/neural-interface/public/shared/extension-setup/es-view.js +51 -11
  113. package/neural-interface/public/shared/extension-update-view.js +1 -1
  114. package/neural-interface/public/shared/loading-diagnostic-entry.js +16 -1
  115. package/neural-interface/public/shared/settings/settings-ai-browser.js +23 -3
  116. package/neural-interface/public/shared/settings/settings-browser-extension.js +575 -197
  117. package/neural-interface/public/shared/settings/settings-extension-diagrams.js +116 -0
  118. package/neural-interface/public/shared/settings/settings-extension-guide.js +222 -0
  119. package/neural-interface/public/shared/settings/settings-ia.js +2 -2
  120. package/neural-interface/public/shared/settings/settings-shell.js +5 -0
  121. package/neural-interface/public/shared/skills/studio/sx-operations-view.js +5 -0
  122. package/neural-interface/public/shared/skills/studio/sx-plan.js +42 -3
  123. package/neural-interface/public/shared/skills/studio/sx-publish-view.js +20 -4
  124. package/neural-interface/public/shared/styles.css +196 -13
  125. package/neural-interface/public/shared/ui-settings.js +48 -11
  126. package/neural-interface/server.js +336 -253
  127. package/npm-shrinkwrap.json +2 -2
  128. package/package.json +2 -1
  129. package/skills/skill-forge/SKILL.md +7 -3
@@ -11,12 +11,22 @@
11
11
  // when a fast-forward would do), and the target is moved to it. The merge is computed without a
12
12
  // checkout (`git merge-tree`); one that conflicts is refused, never resolved.
13
13
  //
14
+ // The target is the branch the caller names, or the team's recorded base branch (the branch the project was on when
15
+ // the team was created): never the branch that happens to be checked out when somebody lands.
16
+ //
14
17
  // A landing changes nothing and answers with a report when:
15
- // NOT_FAST_FORWARD mode 'ff' and the target has commits the integration branch lacks
16
- // MERGE_CONFLICT mode 'merge' and the two do not merge cleanly
18
+ // LANDING_PREVIEW_STALE the caller said where the two branches were when the landing was confirmed
19
+ // (`expectedTargetHead`, `expectedIntegrationHead`) and one of them is elsewhere now; the
20
+ // answer carries the landing as it stands (`preview`)
21
+ // OWNER_BRANCH_MOVED `unmovedOnly` (the scheduler asks it of an Assistant's landing) and the target is not at
22
+ // the commit the team was cut from
23
+ // TEAM_NOT_READY a slice is not joined yet (`allowPartial` lands what is joined)
24
+ // TARGET_NOT_FOUND the target is not a branch of this project
25
+ // NOTHING_TO_LAND the target already has everything on the integration branch (asked before the tests)
17
26
  // TESTS_NOT_PASSED the test command has not passed on the integration branch's head (`allowUntested` lands
18
27
  // a team that has no test command, or whose head was not tested, on the caller's word)
19
- // TEAM_NOT_READY a slice is not joined yet (`allowPartial` lands what is joined)
28
+ // NOT_FAST_FORWARD mode 'ff' and the target has commits the integration branch lacks
29
+ // MERGE_CONFLICT mode 'merge' and the two do not merge cleanly
20
30
  // DIRTY_FILES_AFFECTED the landing would change a file that has uncommitted changes in the checkout that has
21
31
  // the target branch (or would write over a file that is there and untracked or ignored)
22
32
  // CHECKOUT_BUSY that checkout is in the middle of a merge, a rebase, a cherry-pick, a revert or a bisect
@@ -24,6 +34,9 @@
24
34
  // TARGET_MOVED the target moved while the landing was prepared
25
35
  // and the report says what the user can run themselves (`userShouldRun`).
26
36
  //
37
+ // `preview(teamId)` answers what a landing sent now would be told, without moving anything. Both run the same
38
+ // checks (`admit`, then `decide`), so what the preview says and what the landing does cannot differ.
39
+ //
27
40
  // Where the target is checked out (the user's own checkout, usually), the branch, the index and the files are
28
41
  // updated together by a fast-forward of that checkout to the commit prepared above. git carries every uncommitted
29
42
  // change of a file the landing does not touch across unchanged, staged or not, and refuses before it changes
@@ -43,6 +56,12 @@ const exists = (path) => existsSync(path);
43
56
 
44
57
  export const LANDING_MODES = Object.freeze(['ff', 'merge']);
45
58
 
59
+ /** A head the caller expects (a full commit id), or null when it names none. */
60
+ const headGiven = (value) => (value === undefined || value === null || value === '' ? null : String(value).trim().toLowerCase());
61
+ /** The first sentence of a refusal's message: the reason a preview gives. */
62
+ const firstSentence = (text) => { const said = String(text || '').trim(); return (/^.*?[.!?](?=\s+[A-Z]|$)/s.exec(said) || [said])[0]; };
63
+ const short = (commit) => (commit ? String(commit).slice(0, 12) : 'no commit (it is not there)');
64
+
46
65
  /** Do two project-relative paths name the same file, or is one inside the other? */
47
66
  function touches(a, b) {
48
67
  const x = a.replace(/\/+$/, '');
@@ -62,97 +81,198 @@ function touches(a, b) {
62
81
  export function createTeamLanding({ state, git, locks, claims, identity = null, now = Date.now } = {}) {
63
82
  const isAncestor = async (cwd, older, newer) => (await git(['merge-base', '--is-ancestor', older, newer], { cwd })).ok;
64
83
 
84
+ /** The branch a landing goes to: the one the caller names, or the one the team was cut from. Never the branch checked out now. */
85
+ const targetOf = (record, targetBranch) => (typeof targetBranch === 'string' && targetBranch.trim() ? targetBranch.trim() : record?.baseBranch || null);
86
+
65
87
  /**
66
- * Bring a team's integration branch into a branch of the user's.
67
- *
68
- * @param {string} teamId
69
- * @param {object} [options]
70
- * @param {string} [options.targetBranch] default: the branch the project was on when the team was created
71
- * @param {'ff'|'merge'} [options.mode] default 'ff'
72
- * @param {boolean} [options.allowUntested] land although the tests have not passed on the integration head
73
- * @param {boolean} [options.allowPartial] land although some slices are not joined
74
- * @returns {Promise<{ ok: true, landed: object, changed: object[] } | { ok: false, code: string, message: string, report?: object }>}
88
+ * What a landing checks before it asks git where the two branches are: the team, the mode and the target's name.
89
+ * → a refusal, or `{ ok: true, target, cwd, source }`.
75
90
  */
76
- async function land(teamId, { targetBranch = null, mode = 'ff', allowUntested = false, allowPartial = false } = {}) {
77
- const record = isTeamSlug(teamId) ? await state.record(teamId) : null;
91
+ async function admit(teamId, record, { targetBranch = null, mode = 'ff' } = {}) {
78
92
  if (!record) return refuse('TEAM_NOT_FOUND', `No team named "${teamId}" is recorded.`);
79
93
  if (record.plan.readOnly) return refuse('TEAM_READ_ONLY', 'Read-only teams never commit, integrate or land.');
80
94
  if (!LANDING_MODES.includes(mode)) return refuse('INVALID_MODE', 'mode is "ff" (move the branch forward) or "merge" (make a merge commit).');
81
95
  if (record.state === 'merged') return refuse('ALREADY_LANDED', `Team "${teamId}" has landed already (${record.landed?.targetBranch || 'its target'}).`, { landed: record.landed || null });
82
96
  if (['creating', 'integrating', 'landing'].includes(record.state)) return refuse('TEAM_NEEDS_RECOVERY', `Team "${teamId}" is recorded as ${record.state}: run recover() first.`, { state: record.state });
83
97
  if (['failed', 'cancelled'].includes(record.state) || record.removed) return refuse('TEAM_NOT_ACTIVE', `Team "${teamId}" is ${record.removed ? 'removed' : record.state}: there is nothing to land.`, { state: record.state });
84
- const target = typeof targetBranch === 'string' && targetBranch.trim() ? targetBranch.trim() : record.baseBranch;
98
+ const target = targetOf(record, targetBranch);
85
99
  if (!target) return refuse('TARGET_REQUIRED', 'The project was on no branch when the team was created: name the branch to land on (targetBranch).');
86
100
  if (parseBranchName(target)) return refuse('TARGET_IS_TEAM_BRANCH', `${target} is a team's own branch: a landing goes to a branch of yours.`);
87
101
  const cwd = record.projectPath;
88
102
  if (!isDirectory(cwd)) return refuse('PROJECT_NOT_FOUND', `${cwd} is not a folder.`);
89
103
  if (!(await git(['check-ref-format', '--branch', target], { cwd })).ok) return refuse('TARGET_NOT_FOUND', `"${target.slice(0, 120)}" is not a branch name.`);
90
- const source = integrationBranchName(teamId);
104
+ return { ok: true, target, cwd, source: integrationBranchName(teamId) };
105
+ }
91
106
 
92
- return locks.run(repoLockKey(cwd), () => locks.run(`team:${teamId}`, async () => {
93
- const head = await commitOf(git, cwd, `refs/heads/${source}`);
94
- if (!head) return refuse('INTEGRATION_BRANCH_MISSING', `${source} is not there. Run recover() first.`);
95
- if (head !== record.integration.head) return refuse('INTEGRATION_MOVED', `${source} is at ${head}, not at the commit SynaBun left it on (${record.integration.head}): somebody moved it.`, { head, recorded: record.integration.head });
96
-
97
- const open = record.plan.slices.map((slice) => ({ id: slice.id, state: sliceState(record, slice.id) })).filter((slice) => !['integrated', 'cancelled'].includes(slice.state));
98
- if (open.length && !allowPartial) return refuse('TEAM_NOT_READY', `Team "${teamId}" is not finished: ${open.map((slice) => `${slice.id} is ${slice.state}`).join(', ')}.`, { report: { teamId, slices: open } });
99
-
100
- const tests = record.integration.tests;
101
- const tested = !!tests && tests.ok === true && tests.commit === head;
102
- if (!tested && !allowUntested) {
103
- const why = !record.testCommand && !tests ? 'the team has no test command' : !tests || tests.commit !== head ? 'the tests have not been run on this commit' : 'the tests failed on this commit';
104
- return refuse('TESTS_NOT_PASSED', `${source} (${head.slice(0, 12)}) has not passed its tests: ${why}. Nothing was landed.`, { report: { teamId, integrationHead: head, tests: tests || null, testCommand: record.testCommand } });
105
- }
107
+ /** Where the integration branch and the target branch are now, as git has them (null: not there). */
108
+ const headsOf = async ({ cwd, source, target }) => ({
109
+ head: await commitOf(git, cwd, `refs/heads/${source}`),
110
+ targetHead: await commitOf(git, cwd, `refs/heads/${target}`),
111
+ });
106
112
 
107
- const targetHead = await commitOf(git, cwd, `refs/heads/${target}`);
108
- if (!targetHead) return refuse('TARGET_NOT_FOUND', `There is no branch named ${target} in this project.`);
109
- if (head === targetHead || await isAncestor(cwd, head, targetHead)) return refuse('NOTHING_TO_LAND', `${target} already has everything on ${source}.`, { report: { teamId, targetBranch: target, targetHead, integrationHead: head } });
113
+ /**
114
+ * Everything a landing checks once it knows where the two branches are, in the order it answers. It moves
115
+ * nothing (mode 'merge' writes the merge commit the target would be moved to: an object no branch has yet).
116
+ * → a refusal, or the landing as it would be done: `{ ok: true, head, targetHead, to, mergeCommit, changed,
117
+ * checkout, open, tested, byHand }`.
118
+ */
119
+ async function decide(teamId, record, { target, cwd, source }, { head, targetHead }, { mode = 'ff', allowUntested = false, allowPartial = false, unmovedOnly = false } = {}) {
120
+ // `unmovedOnly`: the caller lands only what the owner would wave through, so the target must be where the team
121
+ // was cut from. Moved since: the owner decides (a merge would mix their newer commits with the team's).
122
+ const cutFrom = record.baseCommit || null;
123
+ if (unmovedOnly && targetHead && cutFrom && targetHead !== cutFrom) {
124
+ return refuse('OWNER_BRANCH_MOVED', `${target} has moved since the team was cut from ${String(cutFrom).slice(0, 10)} (it is at ${targetHead.slice(0, 10)} now). Landing is the owner's to decide: ask them, do not land.`, {
125
+ status: 409, report: { targetBranch: target, cutFrom, head: targetHead, integrationBranch: source, userShouldRun: [`git checkout ${target}`, `git merge ${source}`] },
126
+ });
127
+ }
128
+ if (!head) return refuse('INTEGRATION_BRANCH_MISSING', `${source} is not there. Run recover() first.`);
129
+ const recorded = record.integration?.head || null;
130
+ if (head !== recorded) return refuse('INTEGRATION_MOVED', `${source} is at ${head}, not at the commit SynaBun left it on (${recorded}): somebody moved it.`, { head, recorded });
110
131
 
111
- const byHand = (how) => [`git checkout ${target}`, how === 'ff' ? `git merge --ff-only ${source}` : `git merge --no-ff ${source}`];
112
- const fastForward = await isAncestor(cwd, targetHead, head);
113
- if (mode === 'ff' && !fastForward) {
114
- const counts = /^(\d+)\s+(\d+)/.exec((await git(['rev-list', '--left-right', '--count', `${targetHead}...${head}`], { cwd })).stdout || '');
115
- return refuse('NOT_FAST_FORWARD', `${target} has moved since the team started: it has ${counts ? counts[1] : 'some'} commit(s) that ${source} does not have, so it cannot be moved forward to it. Land with mode "merge", or merge it yourself.`, {
116
- report: { teamId, targetBranch: target, targetHead, integrationHead: head, baseCommit: record.baseCommit, targetOnly: counts ? Number(counts[1]) : null, integrationOnly: counts ? Number(counts[2]) : null, userShouldRun: byHand('merge') },
117
- });
118
- }
132
+ const open = record.plan.slices.map((slice) => ({ id: slice.id, state: sliceState(record, slice.id) })).filter((slice) => !['integrated', 'cancelled'].includes(slice.state));
133
+ if (open.length && !allowPartial) return refuse('TEAM_NOT_READY', `Team "${teamId}" is not finished: ${open.map((slice) => `${slice.id} is ${slice.state}`).join(', ')}.`, { report: { teamId, slices: open } });
134
+
135
+ // Is there anything to land at all? Asked before the tests: joins that changed nothing leave nothing to test.
136
+ if (!targetHead) return refuse('TARGET_NOT_FOUND', `There is no branch named ${target} in this project.`);
137
+ if (head === targetHead || await isAncestor(cwd, head, targetHead)) return refuse('NOTHING_TO_LAND', `${target} already has everything on ${source}.`, { report: { teamId, targetBranch: target, targetHead, integrationHead: head } });
138
+
139
+ const tests = record.integration.tests;
140
+ const tested = !!tests && tests.ok === true && tests.commit === head;
141
+ if (!tested && !allowUntested) {
142
+ const why = !record.testCommand && !tests ? 'the team has no test command' : !tests || tests.commit !== head ? 'the tests have not been run on this commit' : 'the tests failed on this commit';
143
+ return refuse('TESTS_NOT_PASSED', `${source} (${head.slice(0, 12)}) has not passed its tests: ${why}. Nothing was landed.`, { report: { teamId, integrationHead: head, tests: tests || null, testCommand: record.testCommand } });
144
+ }
119
145
 
120
- // The commit the target is moved to: the integration head, or a merge commit made without a checkout.
121
- let to = head;
122
- let mergeCommit = null;
123
- if (mode === 'merge') {
124
- const merged = await git(['merge-tree', '--write-tree', '--name-only', '--no-messages', '-z', targetHead, head], { cwd });
125
- const parts = nulList(merged.stdout);
126
- if (merged.status === 1) return refuse('MERGE_CONFLICT', `${source} does not merge cleanly into ${target}: ${parts.slice(1, 6).join(', ')}${parts.length > 6 ? '…' : ''}. Nothing was landed and nothing was resolved.`, { report: { teamId, targetBranch: target, targetHead, integrationHead: head, files: parts.slice(1), userShouldRun: byHand('merge') } });
127
- if (!merged.ok || !/^[0-9a-f]{40,64}$/.test(parts[0] || '')) return refuse('MERGE_UNAVAILABLE', `git could not work the merge out without a checkout (${gitSaid(merged)}); it needs git 2.38 or newer. Nothing was landed.`, { report: { userShouldRun: byHand('merge') } });
128
- const made = await git(['commit-tree', parts[0], '-p', targetHead, '-p', head, '-m', `Merge team ${teamId} (${source}) into ${target}\n\nSynaBun-Team: ${teamId}`], { cwd, env: await identityEnv(git, cwd, identity) });
129
- mergeCommit = line(made);
130
- if (!made.ok || !mergeCommit) return refuse('MERGE_UNAVAILABLE', `The merge commit could not be made: ${gitSaid(made)}. Nothing was landed.`, { report: { userShouldRun: byHand('merge') } });
131
- to = mergeCommit;
146
+ const byHand = (how) => [`git checkout ${target}`, how === 'ff' ? `git merge --ff-only ${source}` : `git merge --no-ff ${source}`];
147
+ const fastForward = await isAncestor(cwd, targetHead, head);
148
+ if (mode === 'ff' && !fastForward) {
149
+ const counts = /^(\d+)\s+(\d+)/.exec((await git(['rev-list', '--left-right', '--count', `${targetHead}...${head}`], { cwd })).stdout || '');
150
+ return refuse('NOT_FAST_FORWARD', `${target} has moved since the team started: it has ${counts ? counts[1] : 'some'} commit(s) that ${source} does not have, so it cannot be moved forward to it. Land with mode "merge", or merge it yourself.`, {
151
+ report: { teamId, targetBranch: target, targetHead, integrationHead: head, baseCommit: record.baseCommit, targetOnly: counts ? Number(counts[1]) : null, integrationOnly: counts ? Number(counts[2]) : null, userShouldRun: byHand('merge') },
152
+ });
153
+ }
154
+
155
+ // The commit the target is moved to: the integration head, or a merge commit made without a checkout.
156
+ let to = head;
157
+ let mergeCommit = null;
158
+ if (mode === 'merge') {
159
+ const merged = await git(['merge-tree', '--write-tree', '--name-only', '--no-messages', '-z', targetHead, head], { cwd });
160
+ const parts = nulList(merged.stdout);
161
+ if (merged.status === 1) return refuse('MERGE_CONFLICT', `${source} does not merge cleanly into ${target}: ${parts.slice(1, 6).join(', ')}${parts.length > 6 ? '…' : ''}. Nothing was landed and nothing was resolved.`, { report: { teamId, targetBranch: target, targetHead, integrationHead: head, files: parts.slice(1), userShouldRun: byHand('merge') } });
162
+ if (!merged.ok || !/^[0-9a-f]{40,64}$/.test(parts[0] || '')) return refuse('MERGE_UNAVAILABLE', `git could not work the merge out without a checkout (${gitSaid(merged)}); it needs git 2.38 or newer. Nothing was landed.`, { report: { userShouldRun: byHand('merge') } });
163
+ const made = await git(['commit-tree', parts[0], '-p', targetHead, '-p', head, '-m', `Merge team ${teamId} (${source}) into ${target}\n\nSynaBun-Team: ${teamId}`], { cwd, env: await identityEnv(git, cwd, identity) });
164
+ mergeCommit = line(made);
165
+ if (!made.ok || !mergeCommit) return refuse('MERGE_UNAVAILABLE', `The merge commit could not be made: ${gitSaid(made)}. Nothing was landed.`, { report: { userShouldRun: byHand('merge') } });
166
+ to = mergeCommit;
167
+ }
168
+ const changed = parseNameStatus((await git(['diff', '--name-status', '-z', '--no-renames', targetHead, to], { cwd })).stdout);
169
+
170
+ // The checkout that has the target branch, if any: the landing must not disturb what is uncommitted there.
171
+ const checkout = (await listWorktrees(git, cwd)).find((entry) => entry.branch === target) || null;
172
+ if (checkout) {
173
+ const place = checkout.path;
174
+ if (!isDirectory(place)) return refuse('CHECKOUT_REFUSED', `${target} is registered as checked out in ${place}, which is not there. Run "git worktree prune", then land again.`, { report: { checkout: place, userShouldRun: ['git worktree prune'] } });
175
+ const busy = await operationsUnderWay(git, place, { exists });
176
+ if (busy.any) {
177
+ const what = busy.merge ? 'merge' : busy.rebase ? 'rebase' : busy.cherryPick ? 'cherry-pick' : busy.revert ? 'revert' : 'bisect';
178
+ return refuse('CHECKOUT_BUSY', `${place} is in the middle of a ${what}: a landing there cannot be guaranteed to leave it as it is. Finish or abort the ${what}, then land again or merge it yourself.`, { report: { checkout: place, operation: what, userShouldRun: byHand(mode) } });
179
+ }
180
+ const changes = await changesOf(git, place);
181
+ if (changes === null) return refuse('CHECKOUT_REFUSED', `The uncommitted changes of ${place} could not be read, so the landing cannot be guaranteed to leave them alone.`, { report: { checkout: place, userShouldRun: byHand(mode) } });
182
+ const dirty = [...new Set(changes.flatMap((change) => [change.path, change.from].filter(Boolean)))];
183
+ const affected = changed.filter((entry) => dirty.some((path) => touches(entry.path, path))).map((entry) => ({ path: entry.path, status: entry.status, why: 'uncommitted changes' }));
184
+ // A file the landing adds where one already is (untracked files are in `dirty`; an ignored one is not).
185
+ const covered = changed.filter((entry) => entry.status === 'A' && !affected.some((each) => each.path === entry.path) && present(join(place, entry.path))).map((entry) => ({ path: entry.path, status: entry.status, why: 'a file that is not tracked is already there' }));
186
+ if (affected.length || covered.length) {
187
+ const files = [...affected, ...covered];
188
+ return refuse('DIRTY_FILES_AFFECTED', `The landing would change ${files.length} file(s) that have uncommitted changes in ${place}: ${files.slice(0, 5).map((file) => file.path).join(', ')}${files.length > 5 ? '…' : ''}. Nothing was landed. Commit or put those changes aside yourself, then land again.`, { report: { teamId, checkout: place, targetBranch: target, files, userShouldRun: byHand(mode) } });
132
189
  }
133
- const changed = parseNameStatus((await git(['diff', '--name-status', '-z', '--no-renames', targetHead, to], { cwd })).stdout);
190
+ }
191
+ return { ok: true, head, targetHead, to, mergeCommit, changed, checkout, open, tested, byHand };
192
+ }
134
193
 
135
- // The checkout that has the target branch, if any: the landing must not disturb what is uncommitted there.
136
- const checkout = (await listWorktrees(git, cwd)).find((entry) => entry.branch === target) || null;
137
- if (checkout) {
138
- const place = checkout.path;
139
- if (!isDirectory(place)) return refuse('CHECKOUT_REFUSED', `${target} is registered as checked out in ${place}, which is not there. Run "git worktree prune", then land again.`, { report: { checkout: place, userShouldRun: ['git worktree prune'] } });
140
- const busy = await operationsUnderWay(git, place, { exists });
141
- if (busy.any) {
142
- const what = busy.merge ? 'merge' : busy.rebase ? 'rebase' : busy.cherryPick ? 'cherry-pick' : busy.revert ? 'revert' : 'bisect';
143
- return refuse('CHECKOUT_BUSY', `${place} is in the middle of a ${what}: a landing there cannot be guaranteed to leave it as it is. Finish or abort the ${what}, then land again or merge it yourself.`, { report: { checkout: place, operation: what, userShouldRun: byHand(mode) } });
144
- }
145
- const changes = await changesOf(git, place);
146
- if (changes === null) return refuse('CHECKOUT_REFUSED', `The uncommitted changes of ${place} could not be read, so the landing cannot be guaranteed to leave them alone.`, { report: { checkout: place, userShouldRun: byHand(mode) } });
147
- const dirty = [...new Set(changes.flatMap((change) => [change.path, change.from].filter(Boolean)))];
148
- const affected = changed.filter((entry) => dirty.some((path) => touches(entry.path, path))).map((entry) => ({ path: entry.path, status: entry.status, why: 'uncommitted changes' }));
149
- // A file the landing adds where one already is (untracked files are in `dirty`; an ignored one is not).
150
- const covered = changed.filter((entry) => entry.status === 'A' && !affected.some((each) => each.path === entry.path) && present(join(place, entry.path))).map((entry) => ({ path: entry.path, status: entry.status, why: 'a file that is not tracked is already there' }));
151
- if (affected.length || covered.length) {
152
- const files = [...affected, ...covered];
153
- return refuse('DIRTY_FILES_AFFECTED', `The landing would change ${files.length} file(s) that have uncommitted changes in ${place}: ${files.slice(0, 5).map((file) => file.path).join(', ')}${files.length > 5 ? '…' : ''}. Nothing was landed. Commit or put those changes aside yourself, then land again.`, { report: { teamId, checkout: place, targetBranch: target, files, userShouldRun: byHand(mode) } });
154
- }
194
+ /**
195
+ * The landing as it stands: what a landing sent now, with no override, would be told. `known`: the two heads,
196
+ * when the caller has read them already (the landing itself, under its lock).
197
+ * → `{ targetBranch, targetHead, integrationHead, testCommand, testsPassedOnHead, canLand, code, reason }`
198
+ */
199
+ async function previewOf(teamId, record, { targetBranch = null, mode = 'ff', unmovedOnly = false } = {}, known = null) {
200
+ const admitted = await admit(teamId, record, { targetBranch, mode });
201
+ const target = admitted.ok ? admitted.target : targetOf(record, targetBranch);
202
+ let heads = known;
203
+ if (!heads) {
204
+ // A landing that is refused early still says where the branches are, when they can be asked for at all.
205
+ const cwd = record?.projectPath || null;
206
+ const askable = !!cwd && isDirectory(cwd);
207
+ const named = askable && !!target && (admitted.ok || (await git(['check-ref-format', '--branch', target], { cwd })).ok);
208
+ heads = {
209
+ head: askable ? await commitOf(git, cwd, `refs/heads/${integrationBranchName(teamId)}`) : null,
210
+ targetHead: named ? await commitOf(git, cwd, `refs/heads/${target}`) : null,
211
+ };
212
+ }
213
+ const said = admitted.ok ? await decide(teamId, record, admitted, heads, { mode, unmovedOnly }) : admitted;
214
+ const tests = record?.integration?.tests || null;
215
+ return {
216
+ targetBranch: target, targetHead: heads.targetHead || null, integrationHead: heads.head || null,
217
+ testCommand: record?.testCommand || null,
218
+ testsPassedOnHead: !!tests && tests.ok === true && !!heads.head && tests.commit === heads.head,
219
+ canLand: said.ok === true, code: said.ok ? null : said.code, reason: said.ok ? null : firstSentence(said.message),
220
+ };
221
+ }
222
+
223
+ /**
224
+ * What a landing of this team would be told now, without moving anything: the same checks as `land`, with no
225
+ * override (`allowUntested`, `allowPartial`) and no lock taken.
226
+ *
227
+ * @param {string} teamId
228
+ * @param {object} [options]
229
+ * @param {string} [options.targetBranch] default: the team's recorded base branch
230
+ * @param {'ff'|'merge'} [options.mode] default 'ff' (a preview of 'merge' writes the merge commit object)
231
+ * @param {boolean} [options.unmovedOnly] as for `land`
232
+ * @returns {Promise<{ targetBranch: string|null, targetHead: string|null, integrationHead: string|null, testCommand: string|null, testsPassedOnHead: boolean, canLand: boolean, code: string|null, reason: string|null }>}
233
+ */
234
+ async function preview(teamId, { targetBranch = null, mode = 'ff', unmovedOnly = false } = {}) {
235
+ const record = isTeamSlug(teamId) ? await state.record(teamId) : null;
236
+ return previewOf(teamId, record, { targetBranch, mode, unmovedOnly });
237
+ }
238
+
239
+ /**
240
+ * Bring a team's integration branch into a branch of the user's.
241
+ *
242
+ * @param {string} teamId
243
+ * @param {object} [options]
244
+ * @param {string} [options.targetBranch] default: the branch the project was on when the team was created
245
+ * @param {'ff'|'merge'} [options.mode] default 'ff'
246
+ * @param {boolean} [options.allowUntested] land although the tests have not passed on the integration head
247
+ * @param {boolean} [options.allowPartial] land although some slices are not joined
248
+ * @param {boolean} [options.unmovedOnly] land only while the target is at the commit the team was cut from
249
+ * @param {string} [options.expectedTargetHead] the target's tip when the landing was confirmed (full commit id)
250
+ * @param {string} [options.expectedIntegrationHead] the integration head when the landing was confirmed
251
+ * @returns {Promise<{ ok: true, landed: object, changed: object[] } | { ok: false, code: string, message: string, report?: object, preview?: object }>}
252
+ */
253
+ async function land(teamId, { targetBranch = null, mode = 'ff', allowUntested = false, allowPartial = false, unmovedOnly = false, expectedTargetHead = null, expectedIntegrationHead = null } = {}) {
254
+ const record = isTeamSlug(teamId) ? await state.record(teamId) : null;
255
+ const admitted = await admit(teamId, record, { targetBranch, mode });
256
+ if (!admitted.ok) return admitted;
257
+ const { target, cwd, source } = admitted;
258
+ const expected = { target: headGiven(expectedTargetHead), integration: headGiven(expectedIntegrationHead) };
259
+
260
+ return locks.run(repoLockKey(cwd), () => locks.run(`team:${teamId}`, async () => {
261
+ const heads = await headsOf(admitted);
262
+ // What was confirmed must be what is there: asked first, under the lock, of git itself.
263
+ const elsewhere = [
264
+ expected.target && expected.target !== heads.targetHead ? `${target} is at ${short(heads.targetHead)}, not at ${short(expected.target)}` : null,
265
+ expected.integration && expected.integration !== heads.head ? `${source} is at ${short(heads.head)}, not at ${short(expected.integration)}` : null,
266
+ ].filter(Boolean);
267
+ if (elsewhere.length) {
268
+ return refuse('LANDING_PREVIEW_STALE', `What was confirmed is not what is there any more: ${elsewhere.join('; ')}. Nothing was landed. Read the landing again and confirm it.`, {
269
+ preview: await previewOf(teamId, record, { targetBranch: target, mode, unmovedOnly }, heads),
270
+ report: { teamId, targetBranch: target, expectedTargetHead: expected.target, targetHead: heads.targetHead || null, expectedIntegrationHead: expected.integration, integrationHead: heads.head || null },
271
+ });
155
272
  }
273
+ const decided = await decide(teamId, record, admitted, heads, { mode, allowUntested, allowPartial, unmovedOnly });
274
+ if (!decided.ok) return decided;
275
+ const { head, targetHead, to, mergeCommit, changed, checkout, open, tested, byHand } = decided;
156
276
 
157
277
  const previous = record.state;
158
278
  const landing = { targetBranch: target, mode, from: targetHead, to, integrationHead: head, mergeCommit, checkout: checkout?.path || null, startedAt: now() };
@@ -180,5 +300,5 @@ export function createTeamLanding({ state, git, locks, claims, identity = null,
180
300
  }));
181
301
  }
182
302
 
183
- return { land };
303
+ return { land, preview };
184
304
  }
@@ -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);