pi-odd-worktree 2.1.0 → 3.0.1

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 (160) hide show
  1. package/README.md +54 -319
  2. package/extensions/odd-worktree-tools.ts +4182 -2539
  3. package/lib/bash-activity.js +1166 -0
  4. package/lib/bash-design.js +684 -0
  5. package/lib/bash-destructive.js +559 -0
  6. package/lib/bash-frame.js +205 -0
  7. package/lib/card-content.js +23 -0
  8. package/lib/card-style.js +175 -0
  9. package/lib/checkout-facts.js +30 -70
  10. package/lib/codegraph-card-preview.js +628 -0
  11. package/lib/codegraph-card.js +515 -0
  12. package/lib/codegraph-compaction.js +76 -0
  13. package/lib/codegraph-daemon.js +246 -0
  14. package/lib/codegraph-edit-sync.js +182 -0
  15. package/lib/codegraph-guard-target.js +337 -0
  16. package/lib/codegraph-guard.js +211 -0
  17. package/lib/codegraph-index.js +1020 -0
  18. package/lib/codegraph-lock.js +607 -0
  19. package/lib/codegraph-mcp-config.js +134 -0
  20. package/lib/codegraph-mcp.js +123 -0
  21. package/lib/codegraph-paths.js +69 -0
  22. package/lib/codegraph-prompt/explore.md +11 -0
  23. package/lib/codegraph-prompt/fix.md +6 -0
  24. package/lib/codegraph-prompt/generic.md +8 -0
  25. package/lib/codegraph-prompt/judge.md +9 -0
  26. package/lib/codegraph-prompt/orchestrator.md +17 -0
  27. package/lib/codegraph-prompt/verify.md +10 -0
  28. package/lib/codegraph-prompt/worker.md +7 -0
  29. package/lib/codegraph-role.js +55 -0
  30. package/lib/codegraph-rules.js +146 -0
  31. package/lib/codegraph-session.js +303 -383
  32. package/lib/codegraph-warmup.js +139 -0
  33. package/lib/file-card-markdown.js +141 -0
  34. package/lib/file-card-resolver.js +245 -0
  35. package/lib/file-card.js +659 -0
  36. package/lib/files-index.js +387 -0
  37. package/lib/files-insert.js +81 -0
  38. package/lib/files-orders.js +326 -0
  39. package/lib/files-picker-view.js +1421 -0
  40. package/lib/files-preview.js +338 -0
  41. package/lib/files-scope-detail.js +171 -0
  42. package/lib/files-scope-view.js +507 -0
  43. package/lib/gh-issues.js +323 -15
  44. package/lib/issue-preview.js +26 -7
  45. package/lib/issues-bash-mutation.js +206 -0
  46. package/lib/issues-cache-store.js +261 -0
  47. package/lib/issues-section.js +710 -0
  48. package/lib/issues-view.js +649 -52
  49. package/lib/odd-prompt/odd-worktrees.md +21 -0
  50. package/lib/odd-worktrees-prompt.js +10 -28
  51. package/lib/related-issues-cache.js +210 -0
  52. package/lib/shell-card.js +825 -0
  53. package/lib/skill-odd-card.js +183 -0
  54. package/lib/tui-paint.js +4 -5
  55. package/lib/warp-create-panel.js +538 -250
  56. package/lib/warp-create-picker.js +56 -9
  57. package/lib/warp-delete-confirm.js +19 -28
  58. package/lib/warp-selector-view.js +160 -82
  59. package/lib/which-command.js +90 -0
  60. package/lib/worktree-card.js +267 -897
  61. package/lib/worktree-cards.js +383 -0
  62. package/lib/worktree-create.js +287 -0
  63. package/lib/worktree-git.js +3 -3
  64. package/lib/worktree-guard.js +548 -0
  65. package/lib/worktree-hooks.js +421 -712
  66. package/lib/worktree-list.js +120 -0
  67. package/lib/worktree-registry.js +162 -879
  68. package/lib/{worktree-close-herdr.js → worktree-remove.js} +9 -11
  69. package/lib/worktree-setup-runner.js +376 -0
  70. package/lib/worktree-setup.js +140 -0
  71. package/lib/worktree-warp-busy.js +462 -85
  72. package/lib/worktree-warp-sessions.js +1 -2
  73. package/package.json +2 -2
  74. package/tools/bash-activity.test.js +1420 -0
  75. package/tools/bash-design.test.js +1093 -0
  76. package/tools/bash-destructive.test.js +139 -0
  77. package/tools/card-content.test.js +44 -0
  78. package/tools/card-style.test.js +298 -0
  79. package/tools/codegraph-card-preview.test.js +254 -0
  80. package/tools/codegraph-card.test.js +1080 -0
  81. package/tools/codegraph-compaction.test.js +378 -0
  82. package/tools/codegraph-daemon.test.js +248 -0
  83. package/tools/codegraph-edit-sync.test.js +295 -0
  84. package/tools/codegraph-guard-target.test.js +174 -0
  85. package/tools/codegraph-guard.test.js +238 -0
  86. package/tools/codegraph-index.test.js +1948 -0
  87. package/tools/codegraph-lock.test.js +932 -0
  88. package/tools/codegraph-mcp-config.test.js +181 -0
  89. package/tools/codegraph-mcp.test.js +194 -0
  90. package/tools/codegraph-paths.test.js +44 -0
  91. package/tools/codegraph-role.test.js +30 -0
  92. package/tools/codegraph-rules.test.js +250 -0
  93. package/tools/codegraph-session.test.js +660 -391
  94. package/tools/codegraph-warmup.test.js +316 -0
  95. package/tools/commands.test.js +510 -31
  96. package/tools/file-card-markdown.test.js +188 -0
  97. package/tools/file-card.test.js +1289 -0
  98. package/tools/files-bridge.test.js +575 -0
  99. package/tools/files-command.test.js +613 -0
  100. package/tools/files-index.test.js +473 -0
  101. package/tools/files-insert.test.js +139 -0
  102. package/tools/files-orders.test.js +597 -0
  103. package/tools/files-picker-view.test.js +1889 -0
  104. package/tools/files-preview.test.js +452 -0
  105. package/tools/files-scope-detail.test.js +264 -0
  106. package/tools/files-scope-view.test.js +614 -0
  107. package/tools/fixtures/card-codegraph-outputs.js +110 -0
  108. package/tools/fixtures/codegraph-cli-stub.js +16 -0
  109. package/tools/fixtures/codegraph-init-process.js +28 -0
  110. package/tools/fixtures/codegraph-lock-worker.js +117 -0
  111. package/tools/fixtures/daemon-fake.js +98 -0
  112. package/tools/fixtures/daemon-mcp-server.js +39 -0
  113. package/tools/fixtures/daemon-warmup-worker.js +12 -0
  114. package/tools/fixtures/load-extension.js +136 -3
  115. package/tools/gh-issues-feedback.test.js +31 -7
  116. package/tools/gh-issues.test.js +417 -1
  117. package/tools/issue-preview.test.js +44 -7
  118. package/tools/issues-bash-mutation.test.js +101 -0
  119. package/tools/issues-cache-store.test.js +222 -0
  120. package/tools/issues-command.test.js +1517 -67
  121. package/tools/issues-open-guard.test.js +1096 -0
  122. package/tools/issues-section.test.js +4235 -0
  123. package/tools/issues-seed-query-regression.test.js +67 -0
  124. package/tools/issues-view.test.js +1489 -60
  125. package/tools/odd-worktrees-prompt.test.js +98 -65
  126. package/tools/package-surface.test.js +431 -36
  127. package/tools/related-issues-cache.test.js +324 -0
  128. package/tools/shell-card.test.js +834 -0
  129. package/tools/skill-odd-card.test.js +200 -0
  130. package/tools/t5-session-identity.test.js +44 -22
  131. package/tools/warp-busy-guard.test.js +2565 -309
  132. package/tools/warp-create-panel.test.js +499 -74
  133. package/tools/warp-create-picker.test.js +101 -5
  134. package/tools/warp-delete-confirm.test.js +49 -15
  135. package/tools/warp-empty-session.test.js +0 -1
  136. package/tools/warp-fallback-regression.test.js +533 -0
  137. package/tools/warp-selector-view.test.js +460 -196
  138. package/tools/which-command.test.js +126 -0
  139. package/tools/worktree-card.test.js +551 -0
  140. package/tools/worktree-cards.test.js +845 -0
  141. package/tools/worktree-changes.test.js +4 -5
  142. package/tools/worktree-create.test.js +489 -0
  143. package/tools/worktree-guard.test.js +823 -0
  144. package/tools/worktree-hooks.test.js +905 -0
  145. package/tools/worktree-list.test.js +170 -0
  146. package/tools/worktree-registry.test.js +89 -230
  147. package/tools/worktree-remove-async.test.js +318 -0
  148. package/tools/worktree-setup-runner.test.js +276 -0
  149. package/tools/worktree-setup.test.js +140 -0
  150. package/tools/worktree-tools.test.js +419 -199
  151. package/lib/codegraph-commands.js +0 -165
  152. package/lib/odd-prompt/odd-worktrees.with-codegraph.md +0 -19
  153. package/lib/odd-prompt/odd-worktrees.without-codegraph.md +0 -15
  154. package/lib/worktree-model-result.js +0 -291
  155. package/tools/codegraph-commands.test.js +0 -371
  156. package/tools/herdr-free-create.test.js +0 -161
  157. package/tools/worktree-close-herdr-async.test.js +0 -204
  158. package/tools/worktree-odd-migration.test.js +0 -224
  159. package/tools/worktree-registry-cache.test.js +0 -163
  160. package/tools/worktree-registry-odd.test.js +0 -231
@@ -1,8 +1,12 @@
1
1
  'use strict';
2
- // S4/S5/S9: a warp waits for THIS session's own background work — its agent
3
- // tasks AND its background jobs — and the request is QUEUED while that work runs.
2
+ // S4/S5/S9: a warp waits for THIS session's own work — the tools it is
3
+ // executing, its agent tasks AND its background jobs — and the request is
4
+ // QUEUED while that work runs.
4
5
  //
5
- // Two sources are driven here:
6
+ // Three sources are driven here:
7
+ // - the host's `tool_execution_start` / `tool_execution_end` pair, which the
8
+ // extension registers and which fires for EVERY tool of the session (a
9
+ // running bash or read, not only this package's tools);
6
10
  // - the agent-task counters, published in Gentle Shell's presence store (one
7
11
  // header per live session, validated and bounded by
8
12
  // lib/worktree-session-guard.js), which the tests write for their own id;
@@ -10,11 +14,11 @@
10
14
  // (the same seam `session_worktree_register` uses), whose text is one line
11
15
  // per job: `job-1 · running · Probe · 3s · /tmp/…/job-1.log`.
12
16
  //
13
- // Both fronts are driven through the public surface: the `worktree_warp` tool,
14
- // which validates and QUEUES the handoff, and `/warp`, which keeps the request
15
- // PENDING and re-dispatches the SAME validated handoff once neither workload is
16
- // running. A pending warp is never replaced: a second request — including one in
17
- // the same turn — is refused on both fronts.
17
+ // The front is driven through the public surface: `/warp`, which validates the
18
+ // request, keeps it PENDING and re-dispatches the SAME validated handoff once
19
+ // neither workload is running. A pending warp is never replaced: a second
20
+ // request — including one in the same turn — is refused. (T6/S3: the
21
+ // `worktree_warp` TOOL is no longer registered, so there is no second front.)
18
22
  //
19
23
  // A job whose status field is not running/queued is finished, a `job_list` that
20
24
  // is missing, fails or answers in an unknown shape is UNKNOWN (never "no jobs"),
@@ -26,8 +30,12 @@ const fs = require('node:fs');
26
30
  const os = require('node:os');
27
31
  const path = require('node:path');
28
32
  const { spawnSync } = require('node:child_process');
29
- const { loadExtension } = require('./fixtures/load-extension.js');
30
- const busyLib = require('../lib/worktree-warp-busy.js');
33
+ const { pathToFileURL } = require('node:url');
34
+ const { LIB_DIR, stubbedSource, installDefaultBridge } = require('./fixtures/load-extension.js');
35
+ // The queue the extension itself loaded: one extension load compiles its own lib
36
+ // modules, so every fake and every assertion below addresses THAT instance by the
37
+ // extension's `libModule` seam instead of a separate `require` of the same path.
38
+ let busyLib = require('../lib/worktree-warp-busy.js');
31
39
 
32
40
  const scratch = [];
33
41
  function track(dir) {
@@ -47,8 +55,6 @@ after(() => {
47
55
  });
48
56
 
49
57
  const HOOK_BIN = path.resolve(track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-hookbin-'))));
50
- fs.writeFileSync(path.join(HOOK_BIN, 'codegraph'), '#!/bin/sh\nexit 0\n', { mode: 0o755 });
51
- const NO_HERDR = path.join(os.tmpdir(), 'odd-worktree-no-such-herdr-binary');
52
58
  const AGENT_HOME = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-agent-home-')));
53
59
  const PRESENCE = path.join(AGENT_HOME, 'gentle-agents', 'presence');
54
60
  const SESSION_ID = 'thread-1';
@@ -66,7 +72,20 @@ function settlePending() {
66
72
  // The queue is ONE record per session, held in this process and shared by every
67
73
  // test in this file: each test clears its own, and this backstop keeps an
68
74
  // unrelated assertion failure from leaking a record into the tests after it.
69
- afterEach(() => { settlePending(); });
75
+ afterEach(() => {
76
+ settlePending();
77
+ // The tool counter is process memory shared by the whole file: a failed test
78
+ // must not leak an execution into the test after it.
79
+ busyLib.forgetInFlightTools();
80
+ widgetPaints.length = 0;
81
+ appendedEntries.length = 0;
82
+ // S17: the boundary sends the agent nothing, so the message recorder is shared
83
+ // by the whole file and every boundary test asserts it stays empty.
84
+ if (host && Array.isArray(host.steered)) host.steered.length = 0;
85
+ // The pending-changes question is a module seam shared by the whole file: a
86
+ // failed test must not leave its asker behind for the tests after it.
87
+ if (mod && typeof mod.setWarpDirtyAsker === 'function') mod.setWarpDirtyAsker(null);
88
+ });
70
89
 
71
90
  function git(cwd, args) {
72
91
  const out = spawnSync('git', args, { cwd, encoding: 'utf8' });
@@ -123,19 +142,110 @@ async function until(predicate, { timeoutMs = 2000, stepMs = 5 } = {}) {
123
142
  }
124
143
 
125
144
  const notifications = [];
145
+
146
+ // The pending-changes question, driven through the module's own seam (the same
147
+ // helper every front uses) instead of a rendered picker: `calls` is what the
148
+ // human was asked, so a question asked twice is observable. `answer` is 'yes',
149
+ // 'no', null (cancel) or a function of the summary line.
150
+ function dirtyAsker(answer) {
151
+ const calls = [];
152
+ mod.setWarpDirtyAsker(async (_ctx, summaryLine) => {
153
+ calls.push(summaryLine);
154
+ return typeof answer === 'function' ? answer(_ctx, summaryLine) : answer;
155
+ });
156
+ return calls;
157
+ }
158
+
159
+ // The destination the create really writes, from the create's own rule
160
+ // (<repo-parent>/<repo-name>-worktrees/<odd>) instead of a remembered spelling.
161
+ function portedDestination(repo, odd) {
162
+ return require('../lib/worktree-create.js').worktreeDestinationPath(fs.realpathSync(repo), odd);
163
+ }
164
+
165
+ // S8/S9: the queued warp's persistent line reaches the human through
166
+ // `ctx.ui.setWidget(key, content, { placement: "aboveEditor" })` — the zone
167
+ // immediately above the input. The test records every call and renders the
168
+ // component factory the queue handed over, so the line, its dim styling and its
169
+ // one-row truncation are observed exactly as the host would draw them.
170
+ const widgetPaints = [];
171
+ const WIDGET_KEY = 'odd-worktree-warp';
172
+ const WIDGET_DIM = (text) => `\u001b[2m${text}\u001b[0m`;
173
+ // S5 (warp-queue-boundary): the durable fallback of the queued line reaches the
174
+ // transcript through `pi.appendEntry`, rendered by the entry renderer the
175
+ // extension registered for its own customType. Both are recorded from the same
176
+ // load, so a test can read the appended entries and draw them exactly as the
177
+ // host would.
178
+ let appendedEntries = [];
179
+ let entryRenderers = null;
180
+
181
+ // The rows the fallback entry renders at `width`, or null when nothing was
182
+ // appended. This is the one fixed transcript line, read through the renderer the
183
+ // extension registered — never through module internals.
184
+ function fallbackLines(width = 200) {
185
+ const entry = appendedEntries.length > 0 ? appendedEntries[appendedEntries.length - 1] : null;
186
+ if (entry === null || entryRenderers === null) return null;
187
+ const renderer = entryRenderers.get(entry.customType);
188
+ if (typeof renderer !== 'function') return null;
189
+ const theme = { fg: (role, text) => (role === 'dim' ? WIDGET_DIM(text) : text) };
190
+ const component = renderer(
191
+ { type: 'custom', id: 'entry-1', customType: entry.customType, data: entry.data },
192
+ { expanded: false },
193
+ theme,
194
+ );
195
+ return component.render(width);
196
+ }
197
+
198
+ function widgetPaintsFor(ctx) {
199
+ return widgetPaints.filter((entry) => entry.ctx === ctx);
200
+ }
201
+
202
+ // The widget as it stands: how many paints happened, and the rows the last one
203
+ // renders at `width`. `lines: null` means the line was CLEARED (or never shown).
204
+ function widgetState(ctx, width = 200) {
205
+ const paints = widgetPaintsFor(ctx);
206
+ const last = paints.length > 0 ? paints[paints.length - 1] : null;
207
+ if (last === null || last.content === undefined) return { paints: paints.length, lines: null, last };
208
+ const theme = { fg: (role, text) => (role === 'dim' ? WIDGET_DIM(text) : text) };
209
+ const component = last.content({}, theme);
210
+ return { paints: paints.length, lines: component.render(width), last };
211
+ }
212
+
213
+ // S8 (warp-queue-boundary): the queue speaks through ONE surface per request.
214
+ // `queuedNotices()` is every notice that repeats the queued sentence — a second
215
+ // copy in the chat — and `queuedSurface(ctx)` is the line the human was actually
216
+ // shown: the fixed row above the editor, or the durable fallback entry when the
217
+ // host offers no paintable row. A request whose line was shown adds no notice.
218
+ function queuedNotices() {
219
+ return notifications.filter(([, text]) => /^Queued: warp /.test(String(text)));
220
+ }
221
+
222
+ function plainLine(line) {
223
+ return String(line).replace(/\u001b\[[0-9;]*m/g, '');
224
+ }
225
+
226
+ function queuedSurface(ctx, width = 200) {
227
+ const row = widgetState(ctx, width).lines;
228
+ if (row !== null) return row.map(plainLine);
229
+ const entry = fallbackLines(width);
230
+ if (entry === null) return null;
231
+ return entry.map(plainLine);
232
+ }
233
+
126
234
  function makeCtx(cwd, extra = {}) {
127
- return {
235
+ const ctx = {
128
236
  cwd,
129
237
  hasUI: true,
130
238
  mode: 'tui',
131
239
  sessionManager: { getSessionId: () => SESSION_ID },
132
240
  ui: {
133
241
  notify: (text, level) => { notifications.push([level, text]); },
242
+ setWidget: (key, content, options) => { widgetPaints.push({ ctx, key, content, options }); },
134
243
  ...extra,
135
244
  },
136
245
  waitForIdle: async () => {},
137
246
  switchSession: async () => ({ cancelled: false }),
138
247
  };
248
+ return ctx;
139
249
  }
140
250
 
141
251
  // This session's background jobs, as the host's `job_list` tool reports them:
@@ -196,31 +306,98 @@ function makeSessionHost(world) {
196
306
  return FakeSession;
197
307
  }
198
308
 
309
+ // A ctx that can really MOVE: an empty session changes PATH through `create` +
310
+ // `switchSession` (the cheapest real move a test can drive), and every switch is
311
+ // recorded so "nothing moved" is an observation instead of an absence.
312
+ function movableCtx(repo) {
313
+ const world = { sessionDir: track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-sessions-'))), created: 0, createdFiles: [] };
314
+ const SM = makeSessionHost(world);
315
+ const switches = [];
316
+ const ctx = makeCtx(repo);
317
+ ctx.sessionManager = Object.assign(new SM(null, null, null), { getSessionId: () => SESSION_ID });
318
+ ctx.sessionManager.constructor = SM;
319
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
320
+ return { ctx, switches };
321
+ }
322
+
199
323
  let host;
200
324
  let commands;
201
325
  let tools;
202
326
  let hooks;
327
+ let mod;
203
328
  before(async () => {
204
- process.env.HERDR_BIN_PATH = NO_HERDR;
205
329
  process.env.GENTLE_WORKTREE_THREAD = SESSION_ID;
206
330
  process.env.PATH = `${HOOK_BIN}${path.delimiter}${savedEnv.PATH || ''}`;
207
331
  delete process.env.GENTLE_PI_AGENT_HOME;
208
332
  process.env.PI_CODING_AGENT_DIR = AGENT_HOME;
209
- // The command front's bounded drain attempt: tests never wait for it.
210
- process.env.ODD_WORKTREE_WARP_BUSY_WAIT_MS = '0';
211
333
  // The queue's lifetime and poll interval are injected per test; these defaults
212
334
  // keep the poller quiet while a test drives `pendingWarpTick` itself.
213
335
  process.env.ODD_WORKTREE_WARP_PENDING_MS = '600000';
214
336
  process.env.ODD_WORKTREE_WARP_PENDING_POLL_MS = '60000';
215
337
  const sent = [];
216
- const loaded = await loadExtension({ sendUserMessage: (text, options) => { sent.push([text, options]); } });
338
+ // S17 (warp-queue-boundary): the turn boundary must never message the agent, so
339
+ // `pi.sendMessage` is recorded exactly as the host would receive it and every
340
+ // boundary test asserts the recorder stays empty.
341
+ const steered = [];
342
+ const loaded = await loadStubbedModule({
343
+ sendUserMessage: (text, options) => { sent.push([text, options]); },
344
+ sendMessage: (message, options) => { steered.push([message, options]); },
345
+ });
217
346
  host = loaded.host;
218
347
  host.sent = sent;
348
+ host.steered = steered;
219
349
  commands = loaded.commands;
220
350
  tools = loaded.tools;
221
351
  hooks = loaded.hooks;
352
+ mod = loaded.mod;
353
+ busyLib = mod.libModule('worktree-warp-busy.js');
354
+ appendedEntries = loaded.entries;
355
+ entryRenderers = loaded.entryRenderers;
222
356
  });
223
357
 
358
+ // The registration surface AND the extension's own exported seams, from ONE load:
359
+ // a load compiles its own lib modules, so the queue a test asserts and the front
360
+ // that fills it must belong to the same instance (tools/package-surface.test.js
361
+ // pins the freshness; this file pins that one load serves both).
362
+ async function loadStubbedModule(pi) {
363
+ // S18 (T14): the extension registers nothing without gentle-shell-bridge, so this
364
+ // file's own host publishes the shared fixture's bridge before the factory runs.
365
+ installDefaultBridge();
366
+ process.env.GENTLE_WORKTREE_LIB_DIR = LIB_DIR;
367
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-mod-'));
368
+ try {
369
+ const copy = path.join(dir, 'odd-worktree-tools.mjs');
370
+ fs.writeFileSync(copy, stubbedSource());
371
+ const mod = await import(pathToFileURL(copy).href);
372
+ const localCommands = new Map();
373
+ const localTools = new Map();
374
+ const localEntryRenderers = new Map();
375
+ const localEntries = [];
376
+ const localHooks = [];
377
+ const host = {
378
+ registerCommand: (name, handler) => { localCommands.set(name, handler); },
379
+ registerTool: (tool) => { localTools.set(tool.name, tool); },
380
+ registerMessageRenderer: () => {},
381
+ registerEntryRenderer: (type, renderer) => { localEntryRenderers.set(type, renderer); },
382
+ appendEntry: (customType, data) => { localEntries.push({ customType, data }); },
383
+ on: (event, handler) => { localHooks.push([event, handler]); },
384
+ ...pi,
385
+ };
386
+ mod.default(host);
387
+ return {
388
+ mod,
389
+ commands: localCommands,
390
+ tools: localTools,
391
+ hooks: localHooks,
392
+ entries: localEntries,
393
+ entryRenderers: localEntryRenderers,
394
+ host,
395
+ };
396
+ } finally {
397
+ fs.rmSync(dir, { recursive: true, force: true });
398
+ }
399
+ }
400
+
224
401
  function resultText(result) {
225
402
  return (result.content || []).map((part) => (part && part.text) || '').join('\n');
226
403
  }
@@ -273,47 +450,41 @@ describe('lib/worktree-warp-busy.js', () => {
273
450
  assert.equal(activity.busy, false);
274
451
  });
275
452
 
276
- test('the bounded wait drains, and reports when the budget runs out', async () => {
277
- const answers = [
278
- { busy: true, running: 2, queued: 0, label: 'L', status: 'ok' },
279
- { busy: true, running: 1, queued: 0, label: 'L', status: 'ok' },
280
- { busy: false, running: 0, queued: 0, label: 'L', status: 'ok' },
281
- ];
282
- let index = 0;
283
- const slept = [];
284
- const drained = await busyLib.waitForSessionActivity({
285
- read: async () => answers[Math.min(index++, answers.length - 1)],
286
- sleep: async (ms) => { slept.push(ms); },
287
- waitMs: 6000,
288
- pollMs: 2000,
289
- });
290
- assert.equal(drained.activity.busy, false);
291
- assert.equal(drained.waitedOut, false);
292
- assert.deepEqual(slept, [2000, 2000]);
293
-
294
- const never = await busyLib.waitForSessionActivity({
295
- read: async () => ({ busy: true, running: 1, queued: 0, label: 'L', status: 'ok' }),
296
- sleep: async () => {},
297
- waitMs: 3000,
298
- pollMs: 2000,
299
- });
300
- assert.equal(never.waitedOut, true);
301
- assert.equal(never.waited, 3000);
302
- });
303
-
304
- test('the queue texts name both workloads and no longer disclaim jobs', () => {
453
+ test('the queued sentence is one brief line, and the caveat lives in the expiry', () => {
305
454
  assert.equal(
306
- busyLib.queuedText({ running: 2, queued: 1, jobs: { active: 1, status: 'ok' } }),
307
- 'handoff queued — waiting for 2 running agent task(s) and 1 queued agent task(s) and 1 running background job before the move',
455
+ busyLib.queuedText('feat-x', { running: 2, queued: 1, jobs: { active: 1, status: 'ok' } }),
456
+ 'Queued: warp feat-x — waiting for 2 running agent task(s) and 1 queued agent task(s) and 1 running background job',
308
457
  );
309
458
  assert.equal(
310
- busyLib.queuedText({ running: 0, queued: 0, jobs: { active: 2, status: 'ok' } }),
311
- 'handoff queued — waiting for 2 running background jobs before the move',
459
+ busyLib.queuedText('feat-x', { running: 0, queued: 0, jobs: { active: 2, status: 'ok' } }),
460
+ 'Queued: warp feat-x — waiting for 2 running background jobs',
312
461
  );
313
- assert.equal(busyLib.queuedText({ running: 1, jobs: { active: 0, status: 'ok' } }), 'handoff queued — waiting for 1 running agent task(s) before the move');
314
- // The old disclaimer is gone now that jobs are covered.
315
- assert.equal(/not observable/.test(busyLib.queuedText({ running: 1, jobs: { active: 0, status: 'ok' } })), false);
462
+ assert.equal(
463
+ busyLib.queuedText('feat-x', { running: 1, jobs: { active: 0, status: 'ok' } }),
464
+ 'Queued: warp feat-x — waiting for 1 running agent task(s)',
465
+ );
466
+ // S4 (warp-queue-boundary): the queued answer IS the row, so the two
467
+ // surfaces can never describe different work or different state.
468
+ for (const activity of [
469
+ { running: 1, jobs: { active: 1, status: 'ok' } },
470
+ { running: 0, jobs: { active: 0, status: 'ok' }, tools: { inFlight: 2 } },
471
+ { host: { idle: false } },
472
+ null,
473
+ ]) {
474
+ assert.equal(busyLib.queuedText('feat-x', activity), busyLib.pendingSteeringLine('feat-x', activity));
475
+ }
476
+ // The old disclaimer is gone, and so is every second sentence: the queued
477
+ // line never carries the unknown-job clause, a caveat row or a `;` join.
478
+ assert.equal(/not observable/.test(busyLib.queuedText('feat-x', { running: 1, jobs: { active: 0, status: 'ok' } })), false);
316
479
  assert.equal(/not observable/.test(busyLib.expiredText('feat-x', 30)), false);
480
+ assert.equal(/\n/.test(busyLib.queuedText('feat-x', { running: 1 })), false, 'one line, never a second');
481
+ for (const unknown of ['unknown', busyLib.JOB_LIST_TOOL, 'bash_background']) {
482
+ assert.equal(
483
+ busyLib.queuedText('feat-x', { running: 1, jobs: { status: 'unavailable' } }).includes(unknown),
484
+ false,
485
+ `${unknown} belongs to the expiry notice, never the queued line`,
486
+ );
487
+ }
317
488
 
318
489
  assert.equal(busyLib.jobsUnknownText({ jobs: { status: 'ok', active: 0 } }), '', 'a readable job list needs no caveat');
319
490
  assert.match(
@@ -328,8 +499,132 @@ describe('lib/worktree-warp-busy.js', () => {
328
499
  assert.match(busyLib.expiredText('feat-x', 30, { jobs: { status: 'error' } }), /\(the background-job state is unknown \(job_list failed\)/);
329
500
  assert.match(
330
501
  busyLib.pendingWarpRefusalText({ name: 'feat-x' }, 'feat-y'),
331
- /^a warp to feat-x is already pending for this session — it runs when the pending agent tasks and background jobs finish; wait for it or let it expire$/,
502
+ /^a warp to feat-x is already pending for this session — it runs when this session's tools, agent tasks and background jobs finish; wait for it or let it expire$/,
503
+ );
504
+ });
505
+
506
+ test('the steering line names the wait, on one line, and never a move', () => {
507
+ // The same phrase the queued notice uses, so the row and the notice cannot
508
+ // describe different work.
509
+ assert.equal(
510
+ busyLib.pendingSteeringLine('feat-x', {
511
+ running: 1, queued: 0, jobs: { active: 2, status: 'ok' }, tools: { inFlight: 1 },
512
+ }),
513
+ 'Queued: warp feat-x — waiting for 1 running agent task(s) and 2 running background jobs and 1 tool still executing',
514
+ );
515
+ assert.equal(
516
+ busyLib.pendingSteeringLine('feat-x', { running: 0, queued: 0, jobs: { active: 0, status: 'ok' }, tools: { inFlight: 1 } }),
517
+ 'Queued: warp feat-x — waiting for 1 tool still executing',
518
+ );
519
+ // Nothing readable: the workloads are named in words, never promised.
520
+ assert.equal(
521
+ busyLib.pendingSteeringLine('feat-x', null),
522
+ "Queued: warp feat-x — waiting for this session's tools, agent tasks and background jobs",
523
+ );
524
+ assert.equal(
525
+ busyLib.pendingSteeringLine('', {}),
526
+ "Queued: warp that checkout — waiting for this session's tools, agent tasks and background jobs",
527
+ );
528
+ // A name can never break the one-row contract, and it never claims a move.
529
+ assert.equal(
530
+ busyLib.pendingSteeringLine('feat\nline two', { running: 1 }),
531
+ 'Queued: warp feat line two — waiting for 1 running agent task(s)',
332
532
  );
533
+ for (const claim of ['moved', 'switched', 'now in', 'done']) {
534
+ assert.equal(busyLib.pendingSteeringLine('feat-x', { running: 1 }).includes(claim), false, claim);
535
+ }
536
+ });
537
+
538
+ test('the queue paints its line while it waits, and clears it on dispatch, expiry and settle', async () => {
539
+ const key = 'session:lib-steering';
540
+ const clock = { now: 1000 };
541
+ const paints = [];
542
+ const activity = { busy: true, running: 1, queued: 0, jobs: { status: 'ok', active: 0 }, tools: { inFlight: 0 } };
543
+ const handoff = { name: 'feat-s', target: '/t', from: '/f', branch: 'feat/s', changes: { mode: 'none', paths: [] } };
544
+ const queued = busyLib.queuePendingWarp({
545
+ key,
546
+ name: 'feat-s',
547
+ token: '@s',
548
+ handoff,
549
+ activity,
550
+ now: () => clock.now,
551
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '10000', ODD_WORKTREE_WARP_PENDING_POLL_MS: '1000' },
552
+ timers: { set: () => null, clear: () => {} },
553
+ read: async () => activity,
554
+ dispatch: () => ({ ok: true }),
555
+ paint: (line) => { paints.push(line); },
556
+ });
557
+ try {
558
+ assert.equal(queued.ok, true);
559
+ // The line is shown at QUEUE time, naming the work already known.
560
+ assert.deepEqual(paints, ['Queued: warp feat-s — waiting for 1 running agent task(s)']);
561
+
562
+ // The same reason is not repainted: a 30-minute queue is one row, not a
563
+ // repaint every poll.
564
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'waiting');
565
+ assert.equal(paints.length, 1);
566
+
567
+ // The reason changes, so the line does.
568
+ activity.running = 0;
569
+ activity.jobs = { status: 'ok', active: 2 };
570
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'waiting');
571
+ assert.equal(paints.length, 2);
572
+ assert.equal(paints[1], 'Queued: warp feat-s — waiting for 2 running background jobs');
573
+
574
+ // The work drains: the dispatch clears the line, and never a claim of a
575
+ // move that has not happened.
576
+ activity.busy = false;
577
+ activity.jobs = { status: 'ok', active: 0 };
578
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'dispatched');
579
+ assert.equal(paints[paints.length - 1], null, 'a dispatch clears the line');
580
+
581
+ // Every terminal outcome clears it: settling here is the move/refusal/
582
+ // cancellation/shutdown path, and it never paints again.
583
+ const before = paints.length;
584
+ busyLib.settlePendingWarp(key);
585
+ assert.equal(paints.length, before, 'an already cleared line is not repainted');
586
+ } finally {
587
+ busyLib.settlePendingWarp(key);
588
+ }
589
+ });
590
+
591
+ test('an expired queue clears the line together with the record', async () => {
592
+ const key = 'session:lib-steering-expiry';
593
+ const clock = { now: 1000 };
594
+ const paints = [];
595
+ const handoff = { name: 'feat-se', target: '/t', from: '/f', branch: 'feat/se', changes: { mode: 'none', paths: [] } };
596
+ const deps = {
597
+ now: () => clock.now,
598
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '1000' },
599
+ timers: { set: () => null, clear: () => {} },
600
+ read: async () => ({ busy: true, running: 1 }),
601
+ dispatch: () => { throw new Error('an expired warp must not dispatch'); },
602
+ paint: (line) => { paints.push(line); },
603
+ };
604
+ assert.equal(busyLib.queuePendingWarp({ key, name: 'feat-se', token: '@se', handoff, activity: { busy: true, running: 1 }, ...deps }).ok, true);
605
+ assert.deepEqual(paints, ['Queued: warp feat-se — waiting for 1 running agent task(s)']);
606
+ clock.now += 1000;
607
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'expired');
608
+ assert.equal(paints[paints.length - 1], null, 'the expired request leaves no line behind');
609
+ assert.equal(paints.length, 2, 'and it does not repaint a line it already cleared');
610
+ });
611
+
612
+ test('a queue with no widget seam still runs: the line is a convenience, never state', async () => {
613
+ const key = 'session:lib-steering-absent';
614
+ const deps = {
615
+ now: () => 1000,
616
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '5000' },
617
+ timers: { set: () => null, clear: () => {} },
618
+ read: async () => ({ busy: false }),
619
+ dispatch: () => ({ ok: true }),
620
+ };
621
+ const handoff = { name: 'feat-na', target: '/t', from: '/f', branch: 'feat/na', changes: { mode: 'none', paths: [] } };
622
+ try {
623
+ assert.equal(busyLib.queuePendingWarp({ key, name: 'feat-na', token: '@na', handoff, ...deps }).ok, true);
624
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'dispatched');
625
+ } finally {
626
+ busyLib.settlePendingWarp(key);
627
+ }
333
628
  });
334
629
 
335
630
  test('a job is active only while its status field says running or queued', () => {
@@ -370,16 +665,96 @@ describe('lib/worktree-warp-busy.js', () => {
370
665
  assert.equal(noTool.busy, false, 'an unknown job state blocks nothing');
371
666
  });
372
667
 
373
- test('the wait, pending and poll budgets are parsed, defaulted and clamped', () => {
374
- assert.equal(busyLib.DEFAULT_WAIT_MS, 60000);
375
- assert.equal(busyLib.MAX_WAIT_MS, 600000);
376
- assert.equal(busyLib.waitBudgetMs({}), 60000);
377
- assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: '' }), 60000);
378
- assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: '5000' }), 5000);
379
- assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: '-1' }), 60000);
380
- assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: 'abc' }), 60000);
381
- assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: '999999999' }), 600000);
668
+ test('an executing tool is the third workload, counted from the host’s execution pair', async () => {
669
+ const home = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-tools-')));
670
+ const env = { PI_CODING_AGENT_DIR: home };
671
+ clearPresence();
672
+ assert.equal((await busyLib.sessionActivity({ sessionId: SESSION_ID, env })).busy, false, 'nothing executes at the start');
673
+
674
+ busyLib.noteToolStart({ toolCallId: 'call-bash-1', toolName: 'bash' });
675
+ const running = await busyLib.sessionActivity({ sessionId: SESSION_ID, env });
676
+ assert.equal(running.tools.inFlight, 1);
677
+ assert.equal(running.busy, true, 'a tool still executing makes the session busy');
678
+ assert.equal(
679
+ busyLib.queuedText('feat-x', running),
680
+ 'Queued: warp feat-x — waiting for 1 tool still executing',
681
+ );
682
+
683
+ // A second tool is counted too, and only its own end releases it.
684
+ busyLib.noteToolStart({ toolCallId: 'call-read-2', toolName: 'read' });
685
+ assert.equal((await busyLib.sessionActivity({ sessionId: SESSION_ID, env })).tools.inFlight, 2);
686
+ busyLib.noteToolEnd({ toolCallId: 'call-bash-1' });
687
+ const one = await busyLib.sessionActivity({ sessionId: SESSION_ID, env });
688
+ assert.equal(one.tools.inFlight, 1);
689
+ assert.equal(one.busy, true, 'one tool still executing still holds the move');
690
+ busyLib.noteToolEnd({ toolCallId: 'call-read-2' });
691
+ const idleAgain = await busyLib.sessionActivity({ sessionId: SESSION_ID, env });
692
+ assert.equal(idleAgain.tools.inFlight, 0);
693
+ assert.equal(idleAgain.busy, false, 'no tool left executing is not work');
694
+ busyLib.forgetInFlightTools();
695
+ });
696
+
697
+ test('a nested call is never counted, and an unmatched end cannot go negative', async () => {
698
+ const home = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-nested-')));
699
+ const env = { PI_CODING_AGENT_DIR: home };
700
+ clearPresence();
701
+ // The queue's own `job_list` probe (and any codemode child) runs INSIDE a
702
+ // parent execution that is already counted: a warp must never wait on its
703
+ // own probe.
704
+ busyLib.noteToolStart({ toolCallId: 'parent-1/0', parentToolCallId: 'parent-1', toolName: 'job_list' });
705
+ assert.equal(busyLib.inFlightToolCount(), 0);
706
+ assert.equal((await busyLib.sessionActivity({ sessionId: SESSION_ID, env })).busy, false, 'a nested call alone is not a busy session');
707
+
708
+ // A blocked call still gets its `tool_execution_end` without a start: that is
709
+ // a no-op, never a negative count.
710
+ busyLib.noteToolEnd({ toolCallId: 'never-started' });
711
+ assert.equal(busyLib.inFlightToolCount(), 0);
712
+ busyLib.forgetInFlightTools();
713
+ });
714
+
715
+ test('a tool that never ends is bounded by the pending lifetime, and shutdown clears it', async () => {
716
+ const home = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-stuck-')));
717
+ const env = { PI_CODING_AGENT_DIR: home };
718
+ const key = 'session:lib-toolstuck';
719
+ const clock = { now: 1000 };
720
+ const notified = [];
721
+ const handoff = { name: 'feat-stuck', target: '/t', from: '/f', branch: 'feat/stuck', changes: { mode: 'none', paths: [] } };
722
+ clearPresence();
723
+ try {
724
+ busyLib.noteToolStart({ toolCallId: 'call-stuck', toolName: 'bash' });
725
+ const queued = busyLib.queuePendingWarp({
726
+ key,
727
+ name: 'feat-stuck',
728
+ token: '@stuck',
729
+ handoff,
730
+ now: () => clock.now,
731
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '1000', ODD_WORKTREE_WARP_PENDING_POLL_MS: '1000' },
732
+ timers: { set: () => null, clear: () => {} },
733
+ read: () => busyLib.sessionActivity({ sessionId: SESSION_ID, env }),
734
+ dispatch: () => { throw new Error('a tool still executing must hold the move'); },
735
+ notify: (text, level) => { notified.push([level, text]); },
736
+ });
737
+ assert.equal(queued.ok, true);
738
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'waiting', 'a tool that never ends keeps the request queued');
739
+
740
+ // The record’s OWN lifetime bounds the wait: nothing is wedged forever.
741
+ clock.now += 1000;
742
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'expired');
743
+ assert.equal(notified.length, 1);
744
+ assert.equal(notified[0][0], 'error');
745
+ assert.match(notified[0][1], /^worktree warp: the pending warp to feat-stuck expired after 1 min with nothing moved/);
746
+ assert.equal(busyLib.pendingWarpFor(key), null, 'the expired record is cleared');
747
+
748
+ // A session replacement starts from no in-flight tool.
749
+ busyLib.forgetInFlightTools();
750
+ assert.equal((await busyLib.sessionActivity({ sessionId: SESSION_ID, env })).busy, false, 'a shutdown starts with no tool executing');
751
+ } finally {
752
+ busyLib.settlePendingWarp(key);
753
+ busyLib.forgetInFlightTools();
754
+ }
755
+ });
382
756
 
757
+ test('the pending and poll budgets are parsed, defaulted and clamped', () => {
383
758
  assert.equal(busyLib.DEFAULT_PENDING_MS, 30 * 60 * 1000);
384
759
  assert.equal(busyLib.pendingBudgetMs({}), 30 * 60 * 1000);
385
760
  assert.equal(busyLib.pendingBudgetMs({ ODD_WORKTREE_WARP_PENDING_MS: '1500' }), 1500);
@@ -396,6 +771,64 @@ describe('lib/worktree-warp-busy.js', () => {
396
771
  assert.equal(busyLib.pendingKeyFor(null), null);
397
772
  });
398
773
 
774
+ test('a queued handoff keeps its requestedAt through the record and the dispatch', async () => {
775
+ const key = 'session:lib-stamp';
776
+ const dispatched = [];
777
+ const handoff = { name: 'feat-s', target: '/t', from: '/f', branch: 'feat/s', changes: { mode: 'none', paths: [] }, requestedAt: 1234 };
778
+ let activity = { busy: true, running: 1, queued: 0 };
779
+ const queued = busyLib.queuePendingWarp({
780
+ key,
781
+ name: 'feat-s',
782
+ token: '@stamp',
783
+ handoff,
784
+ now: () => 9000,
785
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '10000', ODD_WORKTREE_WARP_PENDING_POLL_MS: '1000' },
786
+ timers: { set: () => null, clear: () => {} },
787
+ read: async () => activity,
788
+ dispatch: (queuedHandoff, token) => { dispatched.push([queuedHandoff, token]); return { ok: true }; },
789
+ });
790
+ try {
791
+ assert.equal(queued.ok, true);
792
+ assert.equal(busyLib.pendingWarpFor(key).handoff.requestedAt, 1234, 'the record keeps the acceptance stamp');
793
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'waiting');
794
+ activity = { busy: false, running: 0, queued: 0 };
795
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'dispatched');
796
+ assert.equal(dispatched.length, 1);
797
+ assert.equal(dispatched[0][0].requestedAt, 1234, 'and the dispatch carries the same stamp, so the move reports ONE span');
798
+ assert.equal(dispatched[0][1], '@stamp');
799
+ } finally {
800
+ busyLib.settlePendingWarp(key);
801
+ }
802
+ });
803
+
804
+ test('a handoff without a usable acceptance stamp carries none', () => {
805
+ const key = 'session:lib-stamp-none';
806
+ const deps = {
807
+ now: () => 9000,
808
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '10000' },
809
+ timers: { set: () => null, clear: () => {} },
810
+ read: async () => ({ busy: true }),
811
+ dispatch: () => ({ ok: true }),
812
+ };
813
+ const shape = (requestedAt) => ({
814
+ name: 'feat-n', target: '/t', from: '/f', branch: 'feat/n', changes: { mode: 'none', paths: [] }, requestedAt,
815
+ });
816
+ for (const unusable of [-1, Number.NaN, Infinity, '1234', null]) {
817
+ assert.equal(busyLib.queuePendingWarp({ key, name: 'feat-n', token: '@n', handoff: shape(unusable), ...deps }).ok, true);
818
+ try {
819
+ assert.equal('requestedAt' in busyLib.pendingWarpFor(key).handoff, false, `${String(unusable)} is not a stamp`);
820
+ } finally {
821
+ busyLib.settlePendingWarp(key);
822
+ }
823
+ }
824
+ assert.equal(busyLib.queuePendingWarp({ key, name: 'feat-n', token: '@n', handoff: shape(0), ...deps }).ok, true);
825
+ try {
826
+ assert.equal(busyLib.pendingWarpFor(key).handoff.requestedAt, 0, 'zero is a real millisecond stamp');
827
+ } finally {
828
+ busyLib.settlePendingWarp(key);
829
+ }
830
+ });
831
+
399
832
  test('sameWarpHandoff matches only the same move and change selection', () => {
400
833
  const base = { name: 'feat-x', target: '/t', from: '/f', branch: 'feat/x', changes: { mode: 'none', paths: [] } };
401
834
  assert.equal(busyLib.sameWarpHandoff(base, { ...base }), true);
@@ -511,229 +944,422 @@ describe('lib/worktree-warp-busy.js', () => {
511
944
  });
512
945
 
513
946
  // ---------------------------------------------------------------------------
514
- // The tool front: it QUEUES the handoff while this session is busy.
947
+ // The queue front while this session has work (T6/S3: `/warp` is the only
948
+ // front — `worktree_warp` is not registered any more, so every case here drives
949
+ // the command handler).
515
950
  // ---------------------------------------------------------------------------
516
- describe('the worktree_warp tool queues while this session has agent tasks or jobs', () => {
517
- test('a busy session gets the queued wording and one handoff, and nothing claims jobs are invisible', async () => {
951
+ describe('/warp queues while this session has tools, agent tasks or jobs', () => {
952
+ test('a busy session gets ONE brief queued line and no jobs caveat', async () => {
518
953
  const repo = makeRepo();
519
954
  const ctx = makeCtx(repo);
520
- const created = await tools.get('worktree_create').execute('busy-1', { branch: 'feat/busy', changes: 'none' }, undefined, undefined, ctx);
955
+ const created = await tools.get('worktree_create').execute('busy-1', { branch: 'feat/busy', odd: 'busy' }, undefined, undefined, ctx);
521
956
  assert.notEqual(created.isError, true, resultText(created));
522
957
 
523
958
  publishSession({ running: 1 });
524
959
  addJobs(ctx, [], 'absent');
525
960
  host.sent.length = 0;
526
961
  notifications.length = 0;
527
- const queued = await tools.get('worktree_warp').execute('busy-2', { name: 'feat-busy' }, undefined, undefined, ctx);
528
- assert.notEqual(queued.isError, true, resultText(queued));
529
- assert.match(
530
- resultText(queued),
531
- /^worktree warp: handoff queued — waiting for 1 running agent task\(s\) before the move$/m,
532
- );
533
- assert.match(
534
- resultText(queued),
535
- /^queue: the background-job state is unknown \(job_list is not available on this host\), so confirm any bash_background or monitor job finished$/m,
536
- );
537
- assert.match(resultText(queued), /^to: feat-busy$/m);
538
- assert.match(resultText(queued), /^branch: feat\/busy$/m);
539
- assert.equal(host.sent.length, 1, 'the busy tool front still queues exactly one handoff');
540
- assert.equal(host.sent[0][0].startsWith('/warp @'), true);
541
- assert.equal(queued.details.busy, true);
542
- assert.equal(queued.details.queued, true);
543
- assert.deepEqual(notifications, [], 'the tool result is the report; nothing is notified twice');
544
- settlePending();
545
- });
546
-
547
- test('an idle session keeps the byte-identical queued wording', async () => {
548
- const repo = makeRepo();
549
- const ctx = makeCtx(repo);
550
- const created = await tools.get('worktree_create').execute('busy-3', { branch: 'feat/free', changes: 'none' }, undefined, undefined, ctx);
551
- assert.notEqual(created.isError, true, resultText(created));
962
+ const switches = [];
963
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
964
+ await commands.get('warp').handler('feat-busy', ctx);
552
965
 
553
- publishSession({ running: 0 });
554
- host.sent.length = 0;
555
- const queued = await tools.get('worktree_warp').execute('busy-4', { name: 'feat-free' }, undefined, undefined, ctx);
556
- assert.notEqual(queued.isError, true, resultText(queued));
557
- assert.match(
558
- resultText(queued),
559
- /^worktree warp: handoff queued — the session moves when this turn ends\nto: feat-free\npath: .+\nbranch: feat\/free$/,
560
- );
561
- assert.equal(queued.details.busy, undefined);
562
- assert.equal(host.sent.length, 1);
966
+ assert.equal(switches.length, 0, 'the session must not move under running work');
967
+ assert.equal(host.sent.length, 0, 'the command front re-dispatches later, not now');
968
+ // S8 (warp-queue-boundary): the row is the ONE surface, so the chat holds no
969
+ // second copy of the same sentence.
970
+ assert.deepEqual(queuedNotices(), [], JSON.stringify(notifications));
971
+ assert.deepEqual(queuedSurface(ctx), ['Queued: warp feat-busy — waiting for 1 running agent task(s)']);
972
+ const queued = queuedSurface(ctx)[0];
973
+ // S3/S4 (warp-queue-boundary): an unreadable job state adds no caveat row to
974
+ // the queued line — it is disclosed by the expiry notice alone — and nothing
975
+ // claims jobs are invisible.
976
+ assert.equal(/unknown|job_list|bash_background|monitor|queue:/.test(queued), false, 'the queued line carries no caveat');
977
+ assert.equal(/not observable/.test(queued), false, 'nothing claims jobs are invisible');
978
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the request is kept pending');
563
979
  settlePending();
564
980
  });
565
981
 
566
982
  test('queued counters queue the warp; waiting and finished counters do not', async () => {
567
983
  const repo = makeRepo();
568
- const ctx = makeCtx(repo);
569
- const created = await tools.get('worktree_create').execute('busy-5', { branch: 'feat/queued', changes: 'none' }, undefined, undefined, ctx);
984
+ const { ctx, switches } = movableCtx(repo);
985
+ const created = await tools.get('worktree_create').execute('busy-3', { branch: 'feat/queued', odd: 'queued' }, undefined, undefined, ctx);
570
986
  assert.notEqual(created.isError, true, resultText(created));
571
987
 
572
988
  publishSession({ running: 0, queued: 2, waiting: 1, finished: 4 });
573
- host.sent.length = 0;
574
- const queued = await tools.get('worktree_warp').execute('busy-6', { name: 'feat-queued' }, undefined, undefined, ctx);
575
- assert.notEqual(queued.isError, true, resultText(queued));
576
- assert.match(resultText(queued), /waiting for 2 queued agent task\(s\) before the move/);
577
- assert.equal(host.sent.length, 1);
578
- // S6: the tool front now holds its own request pending, so a second warp
579
- // must wait for this one to reach a terminal outcome.
989
+ notifications.length = 0;
990
+ await commands.get('warp').handler('feat-queued', ctx);
991
+ assert.equal(switches.length, 0, 'queued counters are work the move must wait for');
992
+ assert.deepEqual(queuedNotices(), [], JSON.stringify(notifications));
993
+ assert.deepEqual(queuedSurface(ctx), ['Queued: warp feat-queued — waiting for 2 queued agent task(s)']);
580
994
  settlePending();
581
995
 
582
996
  publishSession({ running: 0, queued: 0, waiting: 4, finished: 9 });
583
- host.sent.length = 0;
584
- const idle = await tools.get('worktree_warp').execute('busy-7', { name: 'feat-queued' }, undefined, undefined, ctx);
585
- assert.notEqual(idle.isError, true, resultText(idle));
586
- assert.match(resultText(idle), /^worktree warp: handoff queued — the session moves when this turn ends/);
587
- assert.equal(host.sent.length, 1);
588
- settlePending();
997
+ notifications.length = 0;
998
+ await commands.get('warp').handler('feat-queued', ctx);
999
+ assert.equal(switches.length, 1, 'waiting and finished counters are not work');
1000
+ assert.deepEqual(notifications, [], 'a real move notifies nothing');
589
1001
  });
590
1002
 
591
- test('a running job queues the warp, and a same-turn second call is refused', async () => {
1003
+ test('a running job queues the warp, and a second request while one is pending is refused', async () => {
592
1004
  const repo = makeRepo();
593
1005
  const ctx = makeCtx(repo);
594
- const created = await tools.get('worktree_create').execute('busy-j1', { branch: 'feat/jobs', changes: 'none' }, undefined, undefined, ctx);
1006
+ const created = await tools.get('worktree_create').execute('busy-j1', { branch: 'feat/jobs', odd: 'jobs' }, undefined, undefined, ctx);
595
1007
  assert.notEqual(created.isError, true, resultText(created));
1008
+ const second = await tools.get('worktree_create').execute('busy-j2', { branch: 'feat/two', odd: 'two' }, undefined, undefined, ctx);
1009
+ assert.notEqual(second.isError, true, resultText(second));
596
1010
 
597
1011
  const jobs = addJobs(ctx, [{ id: 'job-1', status: 'running', label: 'Probe de job' }]);
598
1012
  host.sent.length = 0;
599
- const queued = await tools.get('worktree_warp').execute('busy-j2', { name: 'feat-jobs' }, undefined, undefined, ctx);
600
- assert.notEqual(queued.isError, true, resultText(queued));
601
- assert.match(resultText(queued), /^worktree warp: handoff queued — waiting for 1 running background job before the move$/m);
1013
+ notifications.length = 0;
1014
+ const switches = [];
1015
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
1016
+ await commands.get('warp').handler('feat-jobs', ctx);
1017
+
1018
+ assert.equal(switches.length, 0, 'a running job holds the move');
1019
+ assert.deepEqual(queuedNotices(), [], JSON.stringify(notifications));
1020
+ assert.deepEqual(queuedSurface(ctx), ['Queued: warp feat-jobs — waiting for 1 running background job']);
602
1021
  assert.ok(jobs.calls > 0, 'the job list was actually read through the host tool');
603
- assert.equal(host.sent.length, 1);
604
- assert.equal(queued.details.busy, true);
605
- // S6: the request is pending from QUEUE time, so a second call in the same
606
- // turn — before the command ever runs — is refused and queues nothing.
607
- assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the tool front keeps its own request pending');
608
- const second = await tools.get('worktree_warp').execute('busy-j3', { name: 'feat-jobs' }, undefined, undefined, ctx);
609
- assert.equal(second.isError, true);
1022
+ assert.equal(host.sent.length, 0, 'the command front re-dispatches later, not now');
1023
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the request is kept pending');
1024
+
1025
+ // A DIFFERENT checkout is a second warp: refused while the first is pending.
1026
+ notifications.length = 0;
1027
+ await commands.get('warp').handler('feat-two', ctx);
1028
+ assert.equal(switches.length, 0, 'the refused second request switches nothing');
1029
+ assert.equal(notifications.length, 1, JSON.stringify(notifications));
1030
+ assert.equal(notifications[0][0], 'error');
610
1031
  assert.match(
611
- resultText(second),
612
- /^worktree warp: a warp to feat-jobs is already pending for this session — it runs when the pending agent tasks and background jobs finish; wait for it or let it expire$/,
1032
+ notifications[0][1],
1033
+ /^worktree warp: a warp to feat-jobs is already pending for this session — it runs when this session's tools, agent tasks and background jobs finish; wait for it or let it expire$/,
613
1034
  );
614
- assert.equal(host.sent.length, 1, 'the refused second warp queues nothing');
615
1035
  settlePending();
616
1036
  });
617
1037
 
1038
+ test('a warp typed while the host is still streaming queues before anything waits for idle', async () => {
1039
+ const repo = makeRepo();
1040
+ const ctx = makeCtx(repo);
1041
+ const created = await tools.get('worktree_create').execute('busy-live', { branch: 'feat/live', odd: 'live' }, undefined, undefined, ctx);
1042
+ assert.notEqual(created.isError, true, resultText(created));
1043
+
1044
+ addJobs(ctx, [{ id: 'job-1', status: 'running' }]);
1045
+ const switches = [];
1046
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
1047
+ // The turn never settles: a front that waits for idle would park the whole
1048
+ // request here, so the question and the queue would only happen at idle.
1049
+ let idleWaits = 0;
1050
+ ctx.waitForIdle = () => { idleWaits += 1; return new Promise(() => {}); };
1051
+ notifications.length = 0;
1052
+ host.sent.length = 0;
1053
+ const key = pendingKey();
1054
+ try {
1055
+ const answered = await Promise.race([
1056
+ commands.get('warp').handler('feat-live', ctx).then(() => 'returned'),
1057
+ new Promise((resolve) => setTimeout(() => resolve('still-waiting'), 400)),
1058
+ ]);
1059
+ assert.equal(answered, 'returned', 'the request must not wait for the turn to settle');
1060
+ assert.notEqual(busyLib.pendingWarpFor(key), null, 'the request is queued while the turn still runs');
1061
+ assert.equal(switches.length, 0, 'nothing moves under a running job');
1062
+ assert.equal(host.sent.length, 0, 'the re-dispatch happens later, not now');
1063
+ assert.equal(
1064
+ widgetState(ctx).lines.length > 0,
1065
+ true,
1066
+ 'the steering row is painted while the turn still runs',
1067
+ );
1068
+ assert.match(String(widgetState(ctx).lines[0]), /Queued: warp feat-live/);
1069
+ assert.equal(idleWaits, 0, 'the request asked and queued before ever waiting for idle');
1070
+ } finally {
1071
+ busyLib.settlePendingWarp(key);
1072
+ }
1073
+ });
1074
+
618
1075
  test('a running agent task and a running job are both named', async () => {
619
1076
  const repo = makeRepo();
620
1077
  const ctx = makeCtx(repo);
621
- const created = await tools.get('worktree_create').execute('busy-j4', { branch: 'feat/both', changes: 'none' }, undefined, undefined, ctx);
1078
+ const created = await tools.get('worktree_create').execute('busy-j4', { branch: 'feat/both', odd: 'both' }, undefined, undefined, ctx);
622
1079
  assert.notEqual(created.isError, true, resultText(created));
623
1080
 
624
1081
  publishSession({ running: 2 });
625
1082
  addJobs(ctx, [{ id: 'job-7', status: 'queued' }]);
626
- host.sent.length = 0;
627
- const queued = await tools.get('worktree_warp').execute('busy-j5', { name: 'feat-both' }, undefined, undefined, ctx);
628
- assert.notEqual(queued.isError, true, resultText(queued));
629
- assert.match(
630
- resultText(queued),
631
- /^worktree warp: handoff queued — waiting for 2 running agent task\(s\) and 1 running background job before the move$/m,
632
- );
633
- assert.equal(host.sent.length, 1);
1083
+ notifications.length = 0;
1084
+ await commands.get('warp').handler('feat-both', ctx);
1085
+ const queued = queuedSurface(ctx);
1086
+ assert.notEqual(queued, null, JSON.stringify(notifications));
1087
+ assert.deepEqual(queued, ['Queued: warp feat-both — waiting for 2 running agent task(s) and 1 running background job']);
634
1088
  // Both workloads were readable, so nothing disclaims jobs any more.
635
- assert.equal(/not observable/.test(resultText(queued)), false, 'the job disclaimer is gone');
636
- assert.equal(/agent-task counters only/.test(resultText(queued)), false);
637
- assert.equal(/^queue:/m.test(resultText(queued)), false, 'a readable job list adds no caveat row');
1089
+ assert.equal(/not observable/.test(queued[0]), false, 'the job disclaimer is gone');
1090
+ assert.equal(/agent-task counters only/.test(queued[0]), false);
1091
+ assert.equal(/queue:/.test(queued[0]), false, 'a readable job list adds no caveat row');
1092
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null);
638
1093
  settlePending();
639
1094
  });
640
1095
 
641
- test('an unavailable, failing or unparsable job list blocks nothing and is disclosed only then', async () => {
1096
+ test('an unavailable, failing or unparsable job list blocks nothing, and only the expiry discloses it', async () => {
642
1097
  const repo = makeRepo();
643
1098
  const ctx = makeCtx(repo);
644
- const created = await tools.get('worktree_create').execute('busy-j6', { branch: 'feat/unknown', changes: 'none' }, undefined, undefined, ctx);
1099
+ const created = await tools.get('worktree_create').execute('busy-j6', { branch: 'feat/unknown', odd: 'unknown' }, undefined, undefined, ctx);
645
1100
  assert.notEqual(created.isError, true, resultText(created));
646
1101
  publishSession({ running: 1 });
647
1102
 
648
1103
  // No host seam at all: the plain ctx has neither `tools` nor `executeTool`.
649
1104
  host.sent.length = 0;
650
- const noSeam = await tools.get('worktree_warp').execute('busy-j7', { name: 'feat-unknown' }, undefined, undefined, ctx);
651
- assert.notEqual(noSeam.isError, true, resultText(noSeam));
652
- assert.match(resultText(noSeam), /waiting for 1 running agent task\(s\) before the move/);
653
- assert.match(resultText(noSeam), /^queue: the background-job state is unknown \(job_list is not available on this host\)/m);
654
- assert.equal(host.sent.length, 1, 'an unavailable job list never blocks the warp');
1105
+ notifications.length = 0;
1106
+ await commands.get('warp').handler('feat-unknown', ctx);
1107
+ const noSeam = queuedSurface(ctx);
1108
+ assert.notEqual(noSeam, null, JSON.stringify(notifications));
1109
+ // S4 (warp-queue-boundary): the queued line is the one brief sentence, so an
1110
+ // unknown job state adds no caveat row and names no tool at all.
1111
+ assert.deepEqual(noSeam, ['Queued: warp feat-unknown — waiting for 1 running agent task(s)']);
1112
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'an unavailable job list never blocks the warp');
655
1113
  settlePending();
656
1114
 
657
1115
  for (const [mode, reason] of [['error', 'job_list failed'], ['unparsable', 'job_list answered in an unexpected shape']]) {
658
1116
  addJobs(ctx, [], mode);
659
- host.sent.length = 0;
660
- const outcome = await tools.get('worktree_warp').execute(`busy-j8-${mode}`, { name: 'feat-unknown' }, undefined, undefined, ctx);
661
- assert.notEqual(outcome.isError, true, resultText(outcome));
662
- assert.match(resultText(outcome), new RegExp(`^queue: the background-job state is unknown \\(${reason}\\)`, 'm'));
663
- assert.equal(host.sent.length, 1, `a ${mode} job list never blocks the warp`);
1117
+ notifications.length = 0;
1118
+ await commands.get('warp').handler('feat-unknown', ctx);
1119
+ const outcome = queuedSurface(ctx);
1120
+ assert.notEqual(outcome, null, `${mode}: ${JSON.stringify(notifications)}`);
1121
+ assert.deepEqual(outcome, ['Queued: warp feat-unknown — waiting for 1 running agent task(s)'], `${mode} adds no caveat`);
1122
+ assert.equal(outcome[0].includes(reason), false, `${mode}: the reason belongs to the expiry notice`);
1123
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, `a ${mode} job list never blocks the warp`);
664
1124
  settlePending();
665
1125
  }
666
1126
 
667
- // An unknown job list with NO agent task either: the idle wording stands and
1127
+ // An unknown job list with NO agent task either: the move is performed and
668
1128
  // nothing claims a queue it did not create.
669
1129
  clearPresence();
670
- addJobs(ctx, [], 'unparsable');
671
- host.sent.length = 0;
672
- const idle = await tools.get('worktree_warp').execute('busy-j9', { name: 'feat-unknown' }, undefined, undefined, ctx);
673
- assert.notEqual(idle.isError, true, resultText(idle));
674
- assert.match(resultText(idle), /^worktree warp: handoff queued — the session moves when this turn ends/);
675
- assert.equal(host.sent.length, 1);
676
- settlePending();
1130
+ const { ctx: moveCtx, switches } = movableCtx(repo);
1131
+ addJobs(moveCtx, [], 'unparsable');
1132
+ notifications.length = 0;
1133
+ await commands.get('warp').handler('feat-unknown', moveCtx);
1134
+ assert.equal(switches.length, 1, `an unknown job list blocks nothing (${JSON.stringify(notifications)})`);
1135
+ assert.deepEqual(notifications, [], 'nothing claims a queue it did not create');
677
1136
  });
678
1137
 
679
- test('a queued (busy) tool warp mutates no checkout and no registry row', async () => {
1138
+ test('the unreadable job state is disclosed by the expiry notice, and nowhere else', async () => {
680
1139
  const repo = makeRepo();
681
1140
  const ctx = makeCtx(repo);
682
- const created = await tools.get('worktree_create').execute('busy-8', { branch: 'feat/intact', changes: 'none' }, undefined, undefined, ctx);
1141
+ const created = await tools.get('worktree_create').execute('busy-j7', { branch: 'feat/expiry-caveat', odd: 'expiry-caveat' }, undefined, undefined, ctx);
683
1142
  assert.notEqual(created.isError, true, resultText(created));
1143
+ clearPresence();
1144
+ // A tool of this session keeps the warp waiting, and the job list cannot be
1145
+ // read at all: the one state the expiry notice still has to name.
1146
+ ctx.tools = [{ name: 'job_list' }];
1147
+ ctx.executeTool = async () => ({ isError: true, content: [{ type: 'text', text: 'job_list failed' }] });
1148
+ for (const [, handler] of hooks.filter(([name]) => name === 'tool_execution_start')) {
1149
+ await handler({ toolCallId: 'call-caveat-1', toolName: 'bash', args: {} }, ctx);
1150
+ }
1151
+ const previousBudget = process.env.ODD_WORKTREE_WARP_PENDING_MS;
1152
+ process.env.ODD_WORKTREE_WARP_PENDING_MS = '1';
1153
+ notifications.length = 0;
1154
+ try {
1155
+ await commands.get('warp').handler('feat-expiry-caveat', ctx);
1156
+ } finally {
1157
+ process.env.ODD_WORKTREE_WARP_PENDING_MS = previousBudget;
1158
+ }
1159
+ const queued = queuedSurface(ctx);
1160
+ assert.notEqual(queued, null, JSON.stringify(notifications));
1161
+ assert.deepEqual(queued, ['Queued: warp feat-expiry-caveat — waiting for 1 tool still executing']);
1162
+ assert.equal(queued[0].includes('unknown'), false, 'the queued line never carries the caveat');
684
1163
 
685
- const registryPath = path.resolve(repo, git(repo, ['rev-parse', '--git-common-dir']), 'pi-worktrees.json');
686
- const listBefore = git(repo, ['worktree', 'list', '--porcelain']);
687
- const registryBefore = crypto.createHash('sha256').update(fs.readFileSync(registryPath)).digest('hex');
688
-
689
- publishSession({ running: 1 });
690
- host.sent.length = 0;
691
- const queued = await tools.get('worktree_warp').execute('busy-9', { name: 'feat-intact' }, undefined, undefined, ctx);
692
- assert.notEqual(queued.isError, true, resultText(queued));
693
- assert.equal(host.sent.length, 1);
694
-
695
- assert.equal(git(repo, ['worktree', 'list', '--porcelain']), listBefore, 'the listing changed');
696
- assert.equal(
697
- crypto.createHash('sha256').update(fs.readFileSync(registryPath)).digest('hex'),
698
- registryBefore,
699
- 'the registry changed',
700
- );
701
- settlePending();
1164
+ const expired = await until(() => notifications.some(([, text]) => /expired .* with nothing moved/.test(String(text))));
1165
+ assert.equal(expired, true, `the queue expired with a notice: ${JSON.stringify(notifications)}`);
1166
+ const [, notice] = notifications.find(([, text]) => /expired .* with nothing moved/.test(String(text)));
1167
+ assert.match(notice, /^worktree warp: the pending warp to feat-expiry-caveat expired after 1 min with nothing moved/);
1168
+ assert.match(notice, /the background-job state is unknown \(job_list failed\)/, 'the expiry still discloses the unreadable job state');
702
1169
  });
703
- });
704
1170
 
705
- // ---------------------------------------------------------------------------
706
- // The command front: the request stays PENDING and the queue performs the move.
707
- // ---------------------------------------------------------------------------
708
- describe('the /warp front queues the move and performs it after the counters drain', () => {
709
- test('it never switches while an agent task runs, and says the warp is queued', async () => {
1171
+ test('a tool executing in this session queues the warp, and the move lands once it ends', async () => {
710
1172
  const repo = makeRepo();
711
- const world = { sessionDir: track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-sessions-'))), created: 0, createdFiles: [] };
712
- const SM = makeSessionHost(world);
713
- const switches = [];
714
- const ctx = makeCtx(repo);
715
- ctx.sessionManager = Object.assign(new SM(null, null, null), { getSessionId: () => SESSION_ID });
716
- ctx.sessionManager.constructor = SM;
717
- ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
718
- const created = await tools.get('worktree_create').execute('busy-10', { branch: 'feat/cmd', changes: 'none' }, undefined, undefined, ctx);
1173
+ const { ctx, switches } = movableCtx(repo);
1174
+ addJobs(ctx, []);
1175
+ const created = await tools.get('worktree_create').execute('busy-t1', { branch: 'feat/toolbusy', odd: 'toolbusy' }, undefined, undefined, ctx);
719
1176
  assert.notEqual(created.isError, true, resultText(created));
720
-
721
- publishSession({ running: 2 });
722
- notifications.length = 0;
1177
+ clearPresence();
723
1178
  host.sent.length = 0;
724
- await commands.get('warp').handler('feat-cmd', ctx);
1179
+ notifications.length = 0;
725
1180
 
726
- assert.equal(switches.length, 0, 'the session must not move under running tasks');
1181
+ // The host announces a bash tool of THIS session: it is executing now.
1182
+ const starts = hooks.filter(([name]) => name === 'tool_execution_start');
1183
+ assert.ok(starts.length > 0, 'the extension registers the host’s execution pair');
1184
+ for (const [, handler] of starts) await handler({ toolCallId: 'call-bash-9', toolName: 'bash', args: { command: 'sleep 5' } }, ctx);
1185
+
1186
+ await commands.get('warp').handler('feat-toolbusy', ctx);
1187
+ assert.equal(switches.length, 0, 'the session must not move while a tool executes');
727
1188
  assert.equal(host.sent.length, 0, 'the command front re-dispatches later, not now');
728
- assert.equal(notifications.length, 1, JSON.stringify(notifications));
729
- assert.equal(notifications[0][0], 'info');
730
- assert.match(
731
- notifications[0][1],
732
- /^worktree warp: handoff queued — waiting for 2 running agent task\(s\) before the move/,
733
- );
734
- const record = busyLib.pendingWarpFor(pendingKey());
735
- assert.notEqual(record, null, 'the request is kept pending');
736
- assert.equal(record.name, 'feat-cmd');
1189
+ const queued = queuedSurface(ctx);
1190
+ assert.notEqual(queued, null, JSON.stringify(notifications));
1191
+ assert.deepEqual(queued, ['Queued: warp feat-toolbusy — waiting for 1 tool still executing']);
1192
+ assert.equal(/queue:/.test(queued[0]), false, 'a readable empty job list adds no caveat row');
1193
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the request is kept pending');
1194
+
1195
+ // Still executing: the same poller waits, and nothing is re-dispatched.
1196
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'waiting');
1197
+ assert.equal(host.sent.length, 0);
1198
+ assert.equal(switches.length, 0);
1199
+
1200
+ // The tool’s result arrives: the poller re-dispatches the SAME handoff. That
1201
+ // run executes no tool of its own, so it performs the move instead of
1202
+ // blocking on itself.
1203
+ for (const [, handler] of hooks.filter(([name]) => name === 'tool_execution_end')) {
1204
+ await handler({ toolCallId: 'call-bash-9', toolName: 'bash', result: {}, isError: false }, ctx);
1205
+ }
1206
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'dispatched');
1207
+ assert.equal(host.sent.length, 1, 'the queued warp re-dispatches itself once the tool ends');
1208
+ const [message, options] = host.sent[0];
1209
+ assert.deepEqual(options, { expandPromptTemplates: true });
1210
+ assert.ok(message.startsWith('/warp @'), `the queued command is /warp (${message})`);
1211
+ notifications.length = 0;
1212
+ await commands.get('warp').handler(message.slice('/warp '.length), ctx);
1213
+ assert.equal(switches.length, 1, 'the queued move landed once the tool ended');
1214
+ assert.deepEqual(notifications, [], 'a real move notifies nothing and does not block on itself');
1215
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'a move clears the pending record');
1216
+ });
1217
+
1218
+ test('a second warp while a tool executes is refused, and the pending one is never replaced', async () => {
1219
+ const repo = makeRepo();
1220
+ const { ctx, switches } = movableCtx(repo);
1221
+ const first = await tools.get('worktree_create').execute('busy-t2', { branch: 'feat/toolone', odd: 'toolone' }, undefined, undefined, ctx);
1222
+ assert.notEqual(first.isError, true, resultText(first));
1223
+ const second = await tools.get('worktree_create').execute('busy-t3', { branch: 'feat/tooltwo', odd: 'tooltwo' }, undefined, undefined, ctx);
1224
+ assert.notEqual(second.isError, true, resultText(second));
1225
+ clearPresence();
1226
+ for (const [, handler] of hooks.filter(([name]) => name === 'tool_execution_start')) {
1227
+ await handler({ toolCallId: 'call-grep-1', toolName: 'grep', args: {} }, ctx);
1228
+ }
1229
+ try {
1230
+ notifications.length = 0;
1231
+ await commands.get('warp').handler('feat-toolone', ctx);
1232
+ const queued = busyLib.pendingWarpFor(pendingKey());
1233
+ assert.notEqual(queued, null, 'the tool keeps the request pending');
1234
+ assert.equal(queued.name, 'feat-toolone');
1235
+ const shown = widgetState(ctx);
1236
+ assert.deepEqual(shown.lines, [WIDGET_DIM('Queued: warp feat-toolone — waiting for 1 tool still executing')]);
1237
+
1238
+ notifications.length = 0;
1239
+ await commands.get('warp').handler('feat-tooltwo', ctx);
1240
+ assert.equal(switches.length, 0);
1241
+ assert.equal(notifications.length, 1, JSON.stringify(notifications));
1242
+ assert.equal(notifications[0][0], 'error');
1243
+ assert.match(notifications[0][1], /^worktree warp: a warp to feat-toolone is already pending for this session/);
1244
+ assert.equal(busyLib.pendingWarpFor(pendingKey()).name, 'feat-toolone', 'the pending request is never replaced');
1245
+ // A refused SECOND warp settles nothing: the pending request is still
1246
+ // waiting, so its line is still on screen, unchanged and unpainted.
1247
+ assert.equal(widgetState(ctx).paints, shown.paints, 'the refusal repaints nothing');
1248
+ assert.deepEqual(widgetState(ctx).lines, shown.lines, 'the pending line survives the refusal');
1249
+ } finally {
1250
+ settlePending();
1251
+ busyLib.forgetInFlightTools();
1252
+ }
1253
+ });
1254
+
1255
+ test('the queued warp is visible above the editor: one dim line, and the line follows the queue', async (t) => {
1256
+ const repo = makeRepo();
1257
+ const { ctx, switches } = movableCtx(repo);
1258
+ addJobs(ctx, []);
1259
+ const created = await tools.get('worktree_create').execute('busy-line', { branch: 'feat/line', odd: 'line' }, undefined, undefined, ctx);
1260
+ assert.notEqual(created.isError, true, resultText(created));
1261
+ clearPresence();
1262
+ host.sent.length = 0;
1263
+ notifications.length = 0;
1264
+ widgetPaints.length = 0;
1265
+
1266
+ assert.equal(widgetState(ctx).lines, null, 'no queue, no line');
1267
+ for (const [, handler] of hooks.filter(([name]) => name === 'tool_execution_start')) {
1268
+ await handler({ toolCallId: 'call-line-1', toolName: 'bash', args: { command: 'sleep 5' } }, ctx);
1269
+ }
1270
+ t.diagnostic('step 1 — one bash tool of this session starts executing; no warp asked yet → nothing painted');
1271
+ assert.equal(widgetState(ctx).lines, null, 'a tool executing alone paints nothing');
1272
+
1273
+ await commands.get('warp').handler('feat-line', ctx);
1274
+ const shown = widgetState(ctx);
1275
+ t.diagnostic(`step 2 — /warp feat-line while the tool runs → setWidget(${JSON.stringify(shown.last.key)}, …, ${JSON.stringify(shown.last.options)}) → ${JSON.stringify(shown.lines)}`);
1276
+ assert.deepEqual(shown.lines, [WIDGET_DIM('Queued: warp feat-line — waiting for 1 tool still executing')]);
1277
+ assert.equal(shown.last.key, WIDGET_KEY);
1278
+ assert.deepEqual(shown.last.options, { placement: 'aboveEditor' });
1279
+ assert.equal(switches.length, 0, 'the session has not moved');
1280
+
1281
+ // A narrow terminal truncates the row instead of wrapping it into several.
1282
+ const narrow = widgetState(ctx, 24);
1283
+ assert.deepEqual(narrow.lines, [WIDGET_DIM('Queued: warp feat-line…')]);
1284
+ assert.equal(widgetState(ctx, 1).lines.length, 1, 'one row even at a single column');
1285
+ assert.deepEqual(widgetState(ctx, 1).lines, [WIDGET_DIM('…')]);
1286
+
1287
+ // The reason has not changed, so the poller does not repaint the row.
1288
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'waiting');
1289
+ assert.equal(widgetState(ctx).paints, shown.paints, 'an unchanged reason is not repainted');
1290
+
1291
+ // The tool ends: the queue dispatches, and the line goes with it.
1292
+ for (const [, handler] of hooks.filter(([name]) => name === 'tool_execution_end')) {
1293
+ await handler({ toolCallId: 'call-line-1', toolName: 'bash', result: {}, isError: false }, ctx);
1294
+ }
1295
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'dispatched');
1296
+ t.diagnostic('step 3 — the tool ends → the queue re-dispatches the same handoff → the line is cleared');
1297
+ assert.equal(widgetState(ctx).lines, null, 'a dispatch clears the line');
1298
+
1299
+ const [message] = host.sent[0];
1300
+ notifications.length = 0;
1301
+ await commands.get('warp').handler(message.slice('/warp '.length), ctx);
1302
+ t.diagnostic('step 4 — the queued handoff runs → the session moved, no line left behind');
1303
+ assert.equal(switches.length, 1, 'the queued move landed once the tool ended');
1304
+ assert.equal(widgetState(ctx).lines, null);
1305
+ });
1306
+
1307
+ test('a queued (busy) warp mutates no checkout and writes no document', async () => {
1308
+ const repo = makeRepo();
1309
+ const ctx = makeCtx(repo);
1310
+ const created = await tools.get('worktree_create').execute('busy-8', { branch: 'feat/intact', odd: 'intact' }, undefined, undefined, ctx);
1311
+ assert.notEqual(created.isError, true, resultText(created));
1312
+
1313
+ // S3/S4: the list document is gone. "Nothing was written" is now asserted against
1314
+ // the absence of any file, before and after the queued request.
1315
+ const documentPath = path.resolve(repo, git(repo, ['rev-parse', '--git-common-dir']), 'pi-worktrees.json');
1316
+ const listBefore = git(repo, ['worktree', 'list', '--porcelain']);
1317
+ assert.equal(fs.existsSync(documentPath), false, 'the create writes no list document');
1318
+
1319
+ publishSession({ running: 1 });
1320
+ host.sent.length = 0;
1321
+ notifications.length = 0;
1322
+ const switches = [];
1323
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
1324
+ await commands.get('warp').handler('feat-intact', ctx);
1325
+ assert.equal(switches.length, 0);
1326
+ assert.deepEqual(queuedNotices(), [], JSON.stringify(notifications));
1327
+ assert.deepEqual(queuedSurface(ctx), ['Queued: warp feat-intact — waiting for 1 running agent task(s)']);
1328
+
1329
+ assert.equal(git(repo, ['worktree', 'list', '--porcelain']), listBefore, 'the listing changed');
1330
+ assert.equal(fs.existsSync(documentPath), false, 'the queued warp writes no list document either');
1331
+ settlePending();
1332
+ });
1333
+ });
1334
+
1335
+ // ---------------------------------------------------------------------------
1336
+ // The command front: the request stays PENDING and the queue performs the move.
1337
+ // ---------------------------------------------------------------------------
1338
+ describe('the /warp front queues the move and performs it after the counters drain', () => {
1339
+ test('it never switches while an agent task runs, and says the warp is queued', async () => {
1340
+ const repo = makeRepo();
1341
+ const world = { sessionDir: track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-sessions-'))), created: 0, createdFiles: [] };
1342
+ const SM = makeSessionHost(world);
1343
+ const switches = [];
1344
+ const ctx = makeCtx(repo);
1345
+ ctx.sessionManager = Object.assign(new SM(null, null, null), { getSessionId: () => SESSION_ID });
1346
+ ctx.sessionManager.constructor = SM;
1347
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
1348
+ const created = await tools.get('worktree_create').execute('busy-10', { branch: 'feat/cmd', odd: 'cmd' }, undefined, undefined, ctx);
1349
+ assert.notEqual(created.isError, true, resultText(created));
1350
+
1351
+ publishSession({ running: 2 });
1352
+ notifications.length = 0;
1353
+ host.sent.length = 0;
1354
+ await commands.get('warp').handler('feat-cmd', ctx);
1355
+
1356
+ assert.equal(switches.length, 0, 'the session must not move under running tasks');
1357
+ assert.equal(host.sent.length, 0, 'the command front re-dispatches later, not now');
1358
+ assert.deepEqual(notifications, [], 'the row is the only surface: no notice repeats it');
1359
+ assert.deepEqual(queuedSurface(ctx), ['Queued: warp feat-cmd — waiting for 2 running agent task(s)']);
1360
+ const record = busyLib.pendingWarpFor(pendingKey());
1361
+ assert.notEqual(record, null, 'the request is kept pending');
1362
+ assert.equal(record.name, 'feat-cmd');
737
1363
  settlePending();
738
1364
  });
739
1365
 
@@ -746,7 +1372,7 @@ describe('the /warp front queues the move and performs it after the counters dra
746
1372
  ctx.sessionManager = Object.assign(new SM(null, null, null), { getSessionId: () => SESSION_ID });
747
1373
  ctx.sessionManager.constructor = SM;
748
1374
  ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
749
- const created = await tools.get('worktree_create').execute('busy-11', { branch: 'feat/drain', changes: 'none' }, undefined, undefined, ctx);
1375
+ const created = await tools.get('worktree_create').execute('busy-11', { branch: 'feat/drain', odd: 'drain' }, undefined, undefined, ctx);
750
1376
  assert.notEqual(created.isError, true, resultText(created));
751
1377
 
752
1378
  publishSession({ running: 1, queued: 1 });
@@ -770,20 +1396,23 @@ describe('the /warp front queues the move and performs it after the counters dra
770
1396
  assert.equal(switches.length, 1, 'the queued move landed once the counters drained');
771
1397
  assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'a move clears the pending record');
772
1398
 
773
- // A later warp is accepted again.
1399
+ // A later warp is accepted again: a busy session queues it instead of being
1400
+ // refused as a second request.
1401
+ publishSession({ running: 1 });
774
1402
  host.sent.length = 0;
775
- const next = await tools.get('worktree_warp').execute('busy-12', { name: 'feat-drain' }, undefined, undefined, ctx);
776
- assert.notEqual(next.isError, true, resultText(next));
777
- assert.equal(host.sent.length, 1);
1403
+ notifications.length = 0;
1404
+ await commands.get('warp').handler('feat-drain', ctx);
1405
+ assert.deepEqual(notifications.filter(([, text]) => /already pending/.test(String(text))), [], JSON.stringify(notifications));
1406
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'a later warp queues again');
778
1407
  settlePending();
779
1408
  });
780
1409
 
781
- test('a second warp is refused while one is pending, on both fronts', async () => {
1410
+ test('a second warp is refused while one is pending, and queues nothing', async () => {
782
1411
  const repo = makeRepo();
783
1412
  const ctx = makeCtx(repo);
784
- const first = await tools.get('worktree_create').execute('busy-13', { branch: 'feat/one', changes: 'none' }, undefined, undefined, ctx);
1413
+ const first = await tools.get('worktree_create').execute('busy-13', { branch: 'feat/one', odd: 'one' }, undefined, undefined, ctx);
785
1414
  assert.notEqual(first.isError, true, resultText(first));
786
- const second = await tools.get('worktree_create').execute('busy-14', { branch: 'feat/two', changes: 'none' }, undefined, undefined, ctx);
1415
+ const second = await tools.get('worktree_create').execute('busy-14', { branch: 'feat/two', odd: 'two' }, undefined, undefined, ctx);
787
1416
  assert.notEqual(second.isError, true, resultText(second));
788
1417
 
789
1418
  publishSession({ running: 2 });
@@ -792,17 +1421,8 @@ describe('the /warp front queues the move and performs it after the counters dra
792
1421
  const queued = busyLib.pendingWarpFor(pendingKey());
793
1422
  assert.notEqual(queued, null);
794
1423
 
795
- // The TOOL refuses and queues nothing at all.
1424
+ // The second request is refused and queues nothing.
796
1425
  host.sent.length = 0;
797
- const refusedTool = await tools.get('worktree_warp').execute('busy-15', { name: 'feat-two' }, undefined, undefined, ctx);
798
- assert.equal(refusedTool.isError, true);
799
- assert.match(
800
- resultText(refusedTool),
801
- /^worktree warp: a warp to feat-one is already pending for this session — it runs when the pending agent tasks and background jobs finish; wait for it or let it expire$/,
802
- );
803
- assert.equal(host.sent.length, 0, 'a refused second warp queues nothing');
804
-
805
- // The COMMAND front refuses the same way and never switches.
806
1426
  const switches = [];
807
1427
  ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
808
1428
  notifications.length = 0;
@@ -810,9 +1430,13 @@ describe('the /warp front queues the move and performs it after the counters dra
810
1430
  assert.equal(switches.length, 0);
811
1431
  assert.equal(notifications.length, 1);
812
1432
  assert.equal(notifications[0][0], 'error');
813
- assert.match(notifications[0][1], /^worktree warp: a warp to feat-one is already pending for this session/);
1433
+ assert.match(
1434
+ notifications[0][1],
1435
+ /^worktree warp: a warp to feat-one is already pending for this session — it runs when this session's tools, agent tasks and background jobs finish; wait for it or let it expire$/,
1436
+ );
1437
+ assert.equal(host.sent.length, 0, 'a refused second warp queues nothing');
814
1438
 
815
- // The pending request is untouched by both refusals.
1439
+ // The pending request is untouched by the refusal.
816
1440
  const after = busyLib.pendingWarpFor(pendingKey());
817
1441
  assert.equal(after.name, 'feat-one');
818
1442
  assert.equal(after.queuedAt, queued.queuedAt);
@@ -822,7 +1446,7 @@ describe('the /warp front queues the move and performs it after the counters dra
822
1446
  test('an expired pending warp notices that nothing moved and clears for a later warp', async () => {
823
1447
  const repo = makeRepo();
824
1448
  const ctx = makeCtx(repo);
825
- const created = await tools.get('worktree_create').execute('busy-16', { branch: 'feat/expire', changes: 'none' }, undefined, undefined, ctx);
1449
+ const created = await tools.get('worktree_create').execute('busy-16', { branch: 'feat/expire', odd: 'expire' }, undefined, undefined, ctx);
826
1450
  assert.notEqual(created.isError, true, resultText(created));
827
1451
 
828
1452
  publishSession({ running: 1 });
@@ -835,6 +1459,7 @@ describe('the /warp front queues the move and performs it after the counters dra
835
1459
  process.env.ODD_WORKTREE_WARP_PENDING_MS = previousBudget;
836
1460
  }
837
1461
  assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null);
1462
+ assert.deepEqual(widgetState(ctx).lines, [WIDGET_DIM('Queued: warp feat-expire — waiting for 1 running agent task(s)')], 'the queued warp is visible');
838
1463
 
839
1464
  const expired = await until(() => notifications.some(([, text]) => /expired .* with nothing moved/.test(String(text))));
840
1465
  assert.equal(expired, true, `the queue noticed nothing: ${JSON.stringify(notifications)}`);
@@ -842,11 +1467,13 @@ describe('the /warp front queues the move and performs it after the counters dra
842
1467
  assert.match(text, /^worktree warp: the pending warp to feat-expire expired after 1 min with nothing moved/);
843
1468
  assert.match(text, /agent tasks and background jobs finish/);
844
1469
  assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'an expired queue is cleared');
1470
+ assert.equal(widgetState(ctx).lines, null, 'an expired warp clears its line');
845
1471
 
846
1472
  host.sent.length = 0;
847
- const next = await tools.get('worktree_warp').execute('busy-17', { name: 'feat-expire' }, undefined, undefined, ctx);
848
- assert.notEqual(next.isError, true, `a new warp is accepted after expiry: ${resultText(next)}`);
849
- assert.equal(host.sent.length, 1);
1473
+ notifications.length = 0;
1474
+ await commands.get('warp').handler('feat-expire', ctx);
1475
+ assert.deepEqual(notifications.filter(([, entry]) => /already pending/.test(String(entry))), [], `a new warp is accepted after expiry: ${JSON.stringify(notifications)}`);
1476
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'a new warp is queued after the expiry');
850
1477
  settlePending();
851
1478
  });
852
1479
 
@@ -860,7 +1487,7 @@ describe('the /warp front queues the move and performs it after the counters dra
860
1487
  ctx.sessionManager.constructor = SM;
861
1488
  ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
862
1489
  const jobs = addJobs(ctx, [{ id: 'job-1', status: 'running', label: 'Probe de job' }]);
863
- const created = await tools.get('worktree_create').execute('busy-j20', { branch: 'feat/jobwait', changes: 'none' }, undefined, undefined, ctx);
1490
+ const created = await tools.get('worktree_create').execute('busy-j20', { branch: 'feat/jobwait', odd: 'jobwait' }, undefined, undefined, ctx);
864
1491
  assert.notEqual(created.isError, true, resultText(created));
865
1492
  // No agent task at all: the JOB is the only thing standing in the way.
866
1493
  clearPresence();
@@ -870,9 +1497,8 @@ describe('the /warp front queues the move and performs it after the counters dra
870
1497
 
871
1498
  assert.equal(switches.length, 0, 'the session must not move while a job is running');
872
1499
  assert.equal(host.sent.length, 0, 'the command front re-dispatches later, not now');
873
- assert.equal(notifications.length, 1, JSON.stringify(notifications));
874
- assert.equal(notifications[0][0], 'info');
875
- assert.match(notifications[0][1], /^worktree warp: handoff queued — waiting for 1 running background job before the move/);
1500
+ assert.deepEqual(notifications, [], 'the row is the only surface: no notice repeats it');
1501
+ assert.deepEqual(queuedSurface(ctx), ['Queued: warp feat-jobwait — waiting for 1 running background job']);
876
1502
  assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'a running job keeps the request pending');
877
1503
 
878
1504
  // Still running: the poller waits, and nothing is re-dispatched.
@@ -895,55 +1521,88 @@ describe('the /warp front queues the move and performs it after the counters dra
895
1521
  test('a refused queued warp clears the record, so a later warp is accepted', async () => {
896
1522
  const repo = makeRepo();
897
1523
  const ctx = makeCtx(repo);
898
- const created = await tools.get('worktree_create').execute('busy-r1', { branch: 'feat/refused', changes: 'none' }, undefined, undefined, ctx);
1524
+ const created = await tools.get('worktree_create').execute('busy-r1', { branch: 'feat/refused', odd: 'refused' }, undefined, undefined, ctx);
899
1525
  assert.notEqual(created.isError, true, resultText(created));
900
1526
 
901
- // The tool queues the request while a job runs, so it is pending.
1527
+ // The command front queues the request while a job runs, so it is pending.
902
1528
  clearPresence();
903
1529
  const jobs = addJobs(ctx, [{ id: 'job-3', status: 'running' }]);
904
1530
  host.sent.length = 0;
905
- const queued = await tools.get('worktree_warp').execute('busy-r2', { name: 'feat-refused' }, undefined, undefined, ctx);
906
- assert.notEqual(queued.isError, true, resultText(queued));
907
- assert.equal(host.sent.length, 1);
908
- const token = host.sent[0][0];
1531
+ notifications.length = 0;
1532
+ await commands.get('warp').handler('feat-refused', ctx);
1533
+ assert.deepEqual(queuedNotices(), [], JSON.stringify(notifications));
1534
+ assert.deepEqual(queuedSurface(ctx), ['Queued: warp feat-refused — waiting for 1 running background job']);
909
1535
  assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null);
910
1536
 
911
- // The job finishes, but the registry is unreadable when the queued warp
912
- // runs: that is a terminal refusal, so the record must be cleared.
1537
+ // The job finishes: the queue re-dispatches the SAME validated handoff.
913
1538
  jobs.jobs[0].status = 'exited 0';
914
- const registryPath = path.resolve(repo, git(repo, ['rev-parse', '--git-common-dir']), 'pi-worktrees.json');
915
- fs.writeFileSync(registryPath, 'not json');
1539
+ assert.ok(widgetState(ctx).lines, 'the row is up while the handoff waits');
1540
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'dispatched');
1541
+ assert.equal(host.sent.length, 1, 'the queued warp re-dispatches itself');
1542
+ const token = host.sent[0][0];
1543
+ // The created checkout is gone when that warp runs, so the name no longer
1544
+ // resolves: a terminal refusal, and the record must be cleared.
1545
+ const target = path.join(path.dirname(repo), `${path.basename(repo)}-worktrees`, 'refused');
1546
+ git(repo, ['worktree', 'remove', target]);
916
1547
  notifications.length = 0;
917
1548
  await commands.get('warp').handler(token.slice('/warp '.length), ctx);
918
1549
  assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'a refused queued warp is cleared');
1550
+ assert.equal(widgetState(ctx).lines, null, 'a refused queued warp clears its line');
919
1551
 
920
- // A later warp is accepted again, not blocked by a dead record.
921
- fs.writeFileSync(registryPath, JSON.stringify({ version: 1, worktrees: [] }));
1552
+ // A later warp is accepted again, not blocked by a dead record. The branch still
1553
+ // exists, and a checkout for it is made again so the name resolves.
1554
+ git(repo, ['worktree', 'add', target, 'feat/refused']);
1555
+ publishSession({ running: 1 });
922
1556
  host.sent.length = 0;
923
- const next = await tools.get('worktree_warp').execute('busy-r3', { name: 'feat-refused' }, undefined, undefined, ctx);
924
- assert.notEqual(next.isError, true, `a new warp is accepted, not refused as pending: ${resultText(next)}`);
925
- assert.equal(host.sent.length, 1);
1557
+ notifications.length = 0;
1558
+ await commands.get('warp').handler('feat-refused', ctx);
1559
+ assert.deepEqual(notifications.filter(([, entry]) => /already pending/.test(String(entry))), [], `a new warp is accepted, not refused as pending: ${JSON.stringify(notifications)}`);
1560
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null);
926
1561
  settlePending();
927
1562
  });
928
1563
 
1564
+ test('a refused handoff clears the line it was showing', async () => {
1565
+ const repo = makeRepo();
1566
+ const ctx = makeCtx(repo);
1567
+ const created = await tools.get('worktree_create').execute('busy-r2', { branch: 'feat/live-refused', odd: 'live-refused' }, undefined, undefined, ctx);
1568
+ assert.notEqual(created.isError, true, resultText(created));
1569
+
1570
+ // The queue holds the request while a job runs, so its row is on screen.
1571
+ clearPresence();
1572
+ const jobs = addJobs(ctx, [{ id: 'job-lr', status: 'running' }]);
1573
+ notifications.length = 0;
1574
+ await commands.get('warp').handler('feat-live-refused', ctx);
1575
+ const record = busyLib.pendingWarpFor(pendingKey());
1576
+ assert.notEqual(record, null);
1577
+ assert.deepEqual(widgetState(ctx).lines, [WIDGET_DIM('Queued: warp feat-live-refused — waiting for 1 running background job')]);
1578
+
1579
+ // The job finishes and the checkout disappears between the queue and the
1580
+ // move, which runs straight away: a terminal REFUSAL while the row is still
1581
+ // on screen, so this is the refusal itself clearing it (no dispatch first).
1582
+ jobs.jobs[0].status = 'exited 0';
1583
+ git(repo, ['worktree', 'remove', path.join(path.dirname(repo), `${path.basename(repo)}-worktrees`, 'live-refused')]);
1584
+ notifications.length = 0;
1585
+ const refused = await mod.executeWorktreeWarp('feat-live-refused', ctx, { handoff: record.handoff });
1586
+ assert.equal(refused.isError, true, JSON.stringify(refused));
1587
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'the refusal settles the record');
1588
+ assert.equal(widgetState(ctx).lines, null, 'and clears the line it was showing');
1589
+ });
1590
+
929
1591
  test('a handoff token for another checkout is refused while one is pending', async () => {
930
1592
  const repo = makeRepo();
931
1593
  const ctx = makeCtx(repo);
932
- const first = await tools.get('worktree_create').execute('busy-18', { branch: 'feat/held', changes: 'none' }, undefined, undefined, ctx);
1594
+ const first = await tools.get('worktree_create').execute('busy-18', { branch: 'feat/held', odd: 'held' }, undefined, undefined, ctx);
933
1595
  assert.notEqual(first.isError, true, resultText(first));
934
- const second = await tools.get('worktree_create').execute('busy-19', { branch: 'feat/other', changes: 'none' }, undefined, undefined, ctx);
1596
+ const second = await tools.get('worktree_create').execute('busy-19', { branch: 'feat/other', odd: 'other' }, undefined, undefined, ctx);
935
1597
  assert.notEqual(second.isError, true, resultText(second));
936
1598
 
937
- // Queue a handoff for feat-other first (idle front), then make the session
938
- // busy and let the command hold the request.
1599
+ // Queue a handoff for feat-other first: the busy front holds the request.
939
1600
  clearPresence();
940
- host.sent.length = 0;
941
- const handoff = await tools.get('worktree_warp').execute('busy-20', { name: 'feat-other' }, undefined, undefined, ctx);
942
- assert.notEqual(handoff.isError, true, resultText(handoff));
943
- assert.equal(host.sent.length, 1);
944
- const token = host.sent[0][0];
945
1601
  publishSession({ running: 1 });
946
- await commands.get('warp').handler(token.slice('/warp '.length), ctx);
1602
+ host.sent.length = 0;
1603
+ notifications.length = 0;
1604
+ await commands.get('warp').handler('feat-other', ctx);
1605
+ assert.equal(host.sent.length, 0, 'the busy front re-dispatches later, not now');
947
1606
  assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the handoff is now pending');
948
1607
 
949
1608
  // A DIFFERENT handoff (feat-held) is a second warp.
@@ -982,76 +1641,65 @@ describe('boundaries: negative cases, every front, unaffected surfaces', () => {
982
1641
  }), { mode: 0o600 });
983
1642
  }
984
1643
 
985
- test('the tool queues normally when the presence store is absent', async () => {
1644
+ test('an absent presence store queues nothing and lets the move land', async () => {
986
1645
  const repo = makeRepo();
987
- const ctx = makeCtx(repo);
988
- const created = await tools.get('worktree_create').execute('busy-21', { branch: 'feat/nostore', changes: 'none' }, undefined, undefined, ctx);
1646
+ const { ctx, switches } = movableCtx(repo);
1647
+ const created = await tools.get('worktree_create').execute('busy-21', { branch: 'feat/nostore', odd: 'nostore' }, undefined, undefined, ctx);
989
1648
  assert.notEqual(created.isError, true, resultText(created));
990
1649
  clearPresence();
991
- host.sent.length = 0;
992
- const queued = await tools.get('worktree_warp').execute('busy-22', { name: 'feat-nostore' }, undefined, undefined, ctx);
993
- assert.notEqual(queued.isError, true, resultText(queued));
994
- assert.match(resultText(queued), /^worktree warp: handoff queued — the session moves when this turn ends/);
995
- assert.equal(host.sent.length, 1, 'an absent store blocks nothing and waits for nothing');
996
- settlePending();
1650
+ notifications.length = 0;
1651
+ await commands.get('warp').handler('feat-nostore', ctx);
1652
+ assert.equal(switches.length, 1, `an absent store blocks nothing and waits for nothing (${JSON.stringify(notifications)})`);
1653
+ assert.deepEqual(notifications, [], 'nothing was queued, so nothing is announced');
1654
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'nothing is left pending');
1655
+ // A warp that moves immediately was never queued, so it never paints the
1656
+ // "waiting" row: the line belongs to the queue, not to the warp.
1657
+ assert.equal(widgetPaintsFor(ctx).length, 0, 'an immediate move paints nothing above the editor');
997
1658
  });
998
1659
 
999
1660
  test('a stale heartbeat and an unreadable record are no evidence of work', async () => {
1000
1661
  const repo = makeRepo();
1001
- const ctx = makeCtx(repo);
1002
- const created = await tools.get('worktree_create').execute('busy-23', { branch: 'feat/stale', changes: 'none' }, undefined, undefined, ctx);
1662
+ const { ctx, switches } = movableCtx(repo);
1663
+ const created = await tools.get('worktree_create').execute('busy-23', { branch: 'feat/stale', odd: 'stale' }, undefined, undefined, ctx);
1003
1664
  assert.notEqual(created.isError, true, resultText(created));
1004
1665
 
1005
1666
  publishSession({ running: 3, heartbeat: Date.now() - 600000 });
1006
- host.sent.length = 0;
1007
- const stale = await tools.get('worktree_warp').execute('busy-24', { name: 'feat-stale' }, undefined, undefined, ctx);
1008
- assert.notEqual(stale.isError, true, `a stale heartbeat is not evidence: ${resultText(stale)}`);
1009
- assert.match(resultText(stale), /the session moves when this turn ends/);
1010
- assert.equal(host.sent.length, 1);
1667
+ notifications.length = 0;
1668
+ await commands.get('warp').handler('feat-stale', ctx);
1669
+ assert.equal(switches.length, 1, `a stale heartbeat is not evidence: ${JSON.stringify(notifications)}`);
1670
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null);
1011
1671
 
1012
1672
  publishSession({ running: 3 });
1013
1673
  fs.chmodSync(PRESENCE, 0o755);
1014
1674
  try {
1015
- // S6: the first warp is pending, so it reaches its outcome before the
1016
- // second is accepted (the queue is per session, not per call).
1017
- settlePending();
1018
- host.sent.length = 0;
1019
- const unreadable = await tools.get('worktree_warp').execute('busy-25', { name: 'feat-stale' }, undefined, undefined, ctx);
1020
- assert.notEqual(unreadable.isError, true, `an unsafe store is no evidence: ${resultText(unreadable)}`);
1021
- assert.equal(host.sent.length, 1);
1675
+ notifications.length = 0;
1676
+ await commands.get('warp').handler('feat-stale', ctx);
1677
+ assert.equal(switches.length, 2, `an unsafe store is no evidence: ${JSON.stringify(notifications)}`);
1022
1678
  } finally {
1023
1679
  fs.chmodSync(PRESENCE, 0o700);
1024
1680
  }
1025
- settlePending();
1681
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null);
1026
1682
  });
1027
1683
 
1028
1684
  test('another session’s running tasks never block this session', async () => {
1029
1685
  const repo = makeRepo();
1030
- const ctx = makeCtx(repo);
1031
- const created = await tools.get('worktree_create').execute('busy-26', { branch: 'feat/other', changes: 'none' }, undefined, undefined, ctx);
1686
+ const { ctx, switches } = movableCtx(repo);
1687
+ const created = await tools.get('worktree_create').execute('busy-26', { branch: 'feat/other', odd: 'other' }, undefined, undefined, ctx);
1032
1688
  assert.notEqual(created.isError, true, resultText(created));
1033
1689
 
1034
1690
  clearPresence();
1035
1691
  writeOtherSession({ running: 5, queued: 3 });
1036
- host.sent.length = 0;
1037
- const queued = await tools.get('worktree_warp').execute('busy-27', { name: 'feat-other' }, undefined, undefined, ctx);
1038
- assert.notEqual(queued.isError, true, `a peer's work is not this session's: ${resultText(queued)}`);
1039
- assert.match(resultText(queued), /the session moves when this turn ends/);
1040
- assert.equal(host.sent.length, 1);
1041
- // S6: that request IS this session's one pending warp, so the command front
1042
- // clears it on its own outcome instead of being treated as a second warp.
1043
- settlePending();
1044
-
1045
1692
  notifications.length = 0;
1046
1693
  await commands.get('warp').handler('feat-other', ctx);
1047
- assert.deepEqual(notifications.filter(([, text]) => /already pending|handoff queued/.test(String(text))), []);
1048
- settlePending();
1694
+ assert.equal(switches.length, 1, `a peer's work is not this session's: ${JSON.stringify(notifications)}`);
1695
+ assert.deepEqual(notifications, [], 'nothing was queued, so nothing is announced');
1696
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'nothing is left pending');
1049
1697
  });
1050
1698
 
1051
1699
  test('the selector pick is queued, never switched, while this session is busy', async () => {
1052
1700
  const repo = makeRepo();
1053
1701
  const createCtx = makeCtx(repo);
1054
- const created = await tools.get('worktree_create').execute('busy-28', { branch: 'feat/pick', changes: 'none' }, undefined, undefined, createCtx);
1702
+ const created = await tools.get('worktree_create').execute('busy-28', { branch: 'feat/pick', odd: 'pick' }, undefined, undefined, createCtx);
1055
1703
  assert.notEqual(created.isError, true, resultText(created));
1056
1704
 
1057
1705
  const switches = [];
@@ -1078,7 +1726,10 @@ describe('boundaries: negative cases, every front, unaffected surfaces', () => {
1078
1726
  picks.push('feat-pick');
1079
1727
  await commands.get('warp').handler('', ctx);
1080
1728
  assert.equal(switches.length, 0, 'the selector must not move the session under a running task');
1081
- assert.equal(notifications.filter(([, text]) => /handoff queued — waiting for 2 running/.test(String(text))).length, 1);
1729
+ // S8: this host offers no zone above the editor, so the durable fallback
1730
+ // entry is the one surface — and the chat still holds no second copy.
1731
+ assert.deepEqual(queuedNotices(), [], JSON.stringify(notifications));
1732
+ assert.deepEqual(queuedSurface(ctx), ['Queued: warp feat-pick — waiting for 2 running agent task(s)']);
1082
1733
  assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the selector pick is kept pending');
1083
1734
  settlePending();
1084
1735
  });
@@ -1086,13 +1737,15 @@ describe('boundaries: negative cases, every front, unaffected surfaces', () => {
1086
1737
  test('session shutdown clears the pending warp', async () => {
1087
1738
  const repo = makeRepo();
1088
1739
  const ctx = makeCtx(repo);
1089
- const created = await tools.get('worktree_create').execute('busy-sd1', { branch: 'feat/shutdown', changes: 'none' }, undefined, undefined, ctx);
1740
+ const created = await tools.get('worktree_create').execute('busy-sd1', { branch: 'feat/shutdown', odd: 'shutdown' }, undefined, undefined, ctx);
1090
1741
  assert.notEqual(created.isError, true, resultText(created));
1091
1742
 
1092
1743
  publishSession({ running: 1 });
1093
1744
  host.sent.length = 0;
1094
- const queued = await tools.get('worktree_warp').execute('busy-sd2', { name: 'feat-shutdown' }, undefined, undefined, ctx);
1095
- assert.notEqual(queued.isError, true, resultText(queued));
1745
+ notifications.length = 0;
1746
+ await commands.get('warp').handler('feat-shutdown', ctx);
1747
+ assert.deepEqual(queuedNotices(), [], JSON.stringify(notifications));
1748
+ assert.deepEqual(queuedSurface(ctx), ['Queued: warp feat-shutdown — waiting for 1 running agent task(s)']);
1096
1749
  assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the request is pending before shutdown');
1097
1750
 
1098
1751
  for (const [, handler] of hooks.filter(([name]) => name === 'session_shutdown')) {
@@ -1101,6 +1754,19 @@ describe('boundaries: negative cases, every front, unaffected surfaces', () => {
1101
1754
  assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'nothing deferred survives its session');
1102
1755
  });
1103
1756
 
1757
+ test('a session shutdown clears the in-flight tools, so a lost end cannot wedge the next session', async () => {
1758
+ const repo = makeRepo();
1759
+ const ctx = makeCtx(repo);
1760
+ for (const [, handler] of hooks.filter(([name]) => name === 'tool_execution_start')) {
1761
+ await handler({ toolCallId: 'call-lost-end', toolName: 'bash', args: {} }, ctx);
1762
+ }
1763
+ assert.equal(busyLib.inFlightToolCount(), 1, 'the tool is executing before shutdown');
1764
+ for (const [, handler] of hooks.filter(([name]) => name === 'session_shutdown')) {
1765
+ await handler({}, ctx);
1766
+ }
1767
+ assert.equal(busyLib.inFlightToolCount(), 0, 'a replacement session starts with no tool executing');
1768
+ });
1769
+
1104
1770
  test('list, create and delete still work while this session reports running work', async () => {
1105
1771
  const repo = makeRepo();
1106
1772
  const ctx = {
@@ -1119,10 +1785,1600 @@ describe('boundaries: negative cases, every front, unaffected surfaces', () => {
1119
1785
 
1120
1786
  const listed = await tools.get('worktree_list').execute('busy-29', {}, undefined, undefined, ctx);
1121
1787
  assert.notEqual(listed.isError, true, resultText(listed));
1122
- const created = await tools.get('worktree_create').execute('busy-30', { branch: 'feat/surface', changes: 'none' }, undefined, undefined, ctx);
1788
+ const created = await tools.get('worktree_create').execute('busy-30', { branch: 'feat/surface', odd: 'surface' }, undefined, undefined, ctx);
1123
1789
  assert.notEqual(created.isError, true, resultText(created));
1124
- const closed = await tools.get('worktree_delete').execute('busy-31', { name: 'feat-surface', force: true }, undefined, undefined, ctx);
1790
+ const closed = await mod.executeWorktreeClose({ name: 'feat-surface', force: true }, ctx);
1125
1791
  assert.notEqual(closed.isError, true, resultText(closed));
1126
1792
  settlePending();
1127
1793
  });
1128
1794
  });
1795
+
1796
+ // ---------------------------------------------------------------------------
1797
+ // warp-queue-order T1 (S1-S3, S5): the pending-changes question is asked at
1798
+ // REQUEST time and a busy session is queued AT ONCE. The counters are read as
1799
+ // they are, never waited on: a request that waited found the session idle
1800
+ // afterwards, skipped the queue (so no steering row was ever painted) and asked
1801
+ // the same question again on every attempt.
1802
+ // ---------------------------------------------------------------------------
1803
+ describe('warp-queue-order: ask the copy question at request time, then queue', () => {
1804
+ test('a busy session asks once, at request time, and queues at once', async () => {
1805
+ const repo = makeRepo();
1806
+ const { ctx, switches } = movableCtx(repo);
1807
+ const created = await tools.get('worktree_create').execute('qo-1', { branch: 'feat/now', odd: 'now' }, undefined, undefined, ctx);
1808
+ assert.notEqual(created.isError, true, resultText(created));
1809
+ // Pending work in the checkout the session stands in, so the question has
1810
+ // something to ask about.
1811
+ fs.writeFileSync(path.join(repo, 'pending.txt'), 'pending\n');
1812
+ clearPresence();
1813
+ // The session's own job is running when the request arrives, and it is over
1814
+ // by a SECOND read of the counters: a front that waits for them to drain
1815
+ // reads twice and then takes the idle path.
1816
+ const jobState = { reads: 0 };
1817
+ ctx.tools = [{ name: 'job_list' }];
1818
+ ctx.executeTool = async (name) => {
1819
+ if (name !== 'job_list') return { isError: true, content: [{ type: 'text', text: `unknown tool ${name}` }] };
1820
+ jobState.reads += 1;
1821
+ const status = jobState.reads === 1 ? 'running' : 'exited 0';
1822
+ return { content: [{ type: 'text', text: `job-1 \u00b7 ${status} \u00b7 Probe \u00b7 3s \u00b7 /tmp/gentle-jobs-1/job-1.log` }] };
1823
+ };
1824
+ const asked = dirtyAsker('yes');
1825
+ host.sent.length = 0;
1826
+ notifications.length = 0;
1827
+ widgetPaints.length = 0;
1828
+ try {
1829
+ await commands.get('warp').handler('feat-now', ctx);
1830
+
1831
+ assert.deepEqual(asked, ['1 file, +1/-0'], 'the pending-changes question is asked once, at request time');
1832
+ assert.equal(jobState.reads, 1, 'the counters are read once, as they are, instead of polled until they drain');
1833
+ assert.equal(switches.length, 0, 'the session must not move under its own running job');
1834
+ assert.equal(host.sent.length, 0, 'nothing is re-dispatched now');
1835
+ const record = busyLib.pendingWarpFor(pendingKey());
1836
+ assert.notEqual(record, null, 'the request is queued immediately');
1837
+ assert.deepEqual(record.handoff.changes, { mode: 'all', paths: [] }, 'the answer given at request time travels in the handoff');
1838
+ // S3: the row is up from the moment the request is queued, and it never
1839
+ // claims a move.
1840
+ assert.deepEqual(widgetState(ctx).lines, [WIDGET_DIM('Queued: warp feat-now — waiting for 1 running background job')]);
1841
+ // S8: the row is the whole message, so the chat holds no second copy.
1842
+ assert.deepEqual(notifications, [], 'the painted row is the only surface');
1843
+
1844
+ // S2: attempts two and three are the existing pending-warp refusal, ask no
1845
+ // question and change nothing.
1846
+ const queuedAt = record.queuedAt;
1847
+ for (const attempt of [2, 3]) {
1848
+ notifications.length = 0;
1849
+ await commands.get('warp').handler('feat-now', ctx);
1850
+ assert.deepEqual(notifications, [['error',
1851
+ "worktree warp: a warp to feat-now is already pending for this session \u2014 it runs when this session's tools, agent tasks and background jobs finish; wait for it or let it expire",
1852
+ ]], `attempt ${attempt}`);
1853
+ assert.equal(switches.length, 0, `attempt ${attempt} switches nothing`);
1854
+ assert.equal(host.sent.length, 0, `attempt ${attempt} queues nothing`);
1855
+ const after = busyLib.pendingWarpFor(pendingKey());
1856
+ assert.equal(after.queuedAt, queuedAt, `attempt ${attempt} never replaced the pending request`);
1857
+ assert.deepEqual(after.handoff, record.handoff, `attempt ${attempt} left the pending handoff untouched`);
1858
+ }
1859
+ assert.deepEqual(asked, ['1 file, +1/-0'], 'one question per request, never one per attempt');
1860
+ } finally {
1861
+ settlePending();
1862
+ }
1863
+ });
1864
+
1865
+ test('an idle session applies the answer it was given, and never asks again', async () => {
1866
+ const repo = makeRepo();
1867
+ const { ctx, switches } = movableCtx(repo);
1868
+ const created = await tools.get('worktree_create').execute('qo-2', { branch: 'feat/quiet', odd: 'quiet' }, undefined, undefined, ctx);
1869
+ assert.notEqual(created.isError, true, resultText(created));
1870
+ fs.writeFileSync(path.join(repo, 'pending.txt'), 'pending\n');
1871
+ clearPresence();
1872
+ addJobs(ctx, []);
1873
+ const asked = dirtyAsker('yes');
1874
+ notifications.length = 0;
1875
+ await commands.get('warp').handler('feat-quiet', ctx);
1876
+ assert.deepEqual(asked, ['1 file, +1/-0'], 'the question is asked exactly once');
1877
+ assert.equal(switches.length, 1, 'a session with no work moves straight away');
1878
+ assert.equal(
1879
+ fs.readFileSync(path.join(created.details.path, 'pending.txt'), 'utf8'),
1880
+ 'pending\n',
1881
+ 'the answer given at request time is what gets copied',
1882
+ );
1883
+ assert.deepEqual(notifications, [], 'a real move notifies nothing');
1884
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'nothing was queued');
1885
+ });
1886
+
1887
+ test('NO COPY travels in the queued handoff as no changes', async () => {
1888
+ const repo = makeRepo();
1889
+ const { ctx, switches } = movableCtx(repo);
1890
+ const created = await tools.get('worktree_create').execute('qo-3', { branch: 'feat/nocopy', odd: 'nocopy' }, undefined, undefined, ctx);
1891
+ assert.notEqual(created.isError, true, resultText(created));
1892
+ fs.writeFileSync(path.join(repo, 'pending.txt'), 'pending\n');
1893
+ clearPresence();
1894
+ addJobs(ctx, [{ id: 'job-nc', status: 'running' }]);
1895
+ const asked = dirtyAsker('no');
1896
+ notifications.length = 0;
1897
+ try {
1898
+ await commands.get('warp').handler('feat-nocopy', ctx);
1899
+ assert.deepEqual(asked, ['1 file, +1/-0']);
1900
+ const record = busyLib.pendingWarpFor(pendingKey());
1901
+ assert.notEqual(record, null, 'the request is queued');
1902
+ assert.deepEqual(record.handoff.changes, { mode: 'none', paths: [] }, 'NO COPY queues a handoff that carries no changes');
1903
+ // S8: the painted row is the only surface (no notice repeats it).
1904
+ assert.deepEqual(notifications, [], JSON.stringify(notifications));
1905
+ assert.deepEqual(queuedSurface(ctx), ['Queued: warp feat-nocopy — waiting for 1 running background job']);
1906
+ assert.equal(switches.length, 0);
1907
+ } finally {
1908
+ settlePending();
1909
+ }
1910
+ });
1911
+
1912
+ test('cancelling the question queues nothing and moves nothing', async () => {
1913
+ const repo = makeRepo();
1914
+ const { ctx, switches } = movableCtx(repo);
1915
+ const created = await tools.get('worktree_create').execute('qo-4', { branch: 'feat/cancel', odd: 'cancel' }, undefined, undefined, ctx);
1916
+ assert.notEqual(created.isError, true, resultText(created));
1917
+ fs.writeFileSync(path.join(repo, 'pending.txt'), 'pending\n');
1918
+ clearPresence();
1919
+ addJobs(ctx, [{ id: 'job-c', status: 'running' }]);
1920
+ const asked = dirtyAsker(null);
1921
+ notifications.length = 0;
1922
+ widgetPaints.length = 0;
1923
+ await commands.get('warp').handler('feat-cancel', ctx);
1924
+ assert.deepEqual(asked, ['1 file, +1/-0']);
1925
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'a cancelled question queues nothing');
1926
+ assert.equal(switches.length, 0, 'and switches nothing');
1927
+ assert.equal(widgetState(ctx).lines, null, 'and paints no steering row');
1928
+ assert.deepEqual(notifications, [['error', `worktree warp: feat-cancel cancelled (the session stays in ${repo})`]]);
1929
+ });
1930
+
1931
+ test('a create that already asked suppresses the second question and the copy', async () => {
1932
+ const repo = makeRepo();
1933
+ const { ctx, switches } = movableCtx(repo);
1934
+ const created = await tools.get('worktree_create').execute('qo-5', { branch: 'feat/skip', odd: 'skip' }, undefined, undefined, ctx);
1935
+ assert.notEqual(created.isError, true, resultText(created));
1936
+ fs.writeFileSync(path.join(repo, 'pending.txt'), 'pending\n');
1937
+ clearPresence();
1938
+ addJobs(ctx, []);
1939
+ const asked = dirtyAsker('yes');
1940
+ notifications.length = 0;
1941
+ const out = await mod.executeWorktreeWarp('feat-skip', ctx, { skipDirtyPrompt: true });
1942
+ assert.notEqual(out.isError, true, JSON.stringify(out));
1943
+ assert.deepEqual(asked, [], 'the question is not asked twice');
1944
+ assert.equal(switches.length, 1, 'the move still lands');
1945
+ assert.equal(
1946
+ fs.existsSync(path.join(created.details.path, 'pending.txt')),
1947
+ false,
1948
+ 'and nothing is copied a second time',
1949
+ );
1950
+ });
1951
+ });
1952
+
1953
+ describe('warp-queue-order: the counters are sampled even without a session id', () => {
1954
+ // A host whose session identity is missing (absent, empty or a throwing
1955
+ // `getSessionId`) still has a tool counter and a `job_list` tool. The counters
1956
+ // belong to THIS session, not to its id: an id-less warp must queue for exactly
1957
+ // the same work an id-ful one waits for, keyed by the checkout it stands in.
1958
+ function ctxWithoutSessionId(repo) {
1959
+ const { ctx, switches } = movableCtx(repo);
1960
+ ctx.sessionManager.getSessionId = () => null;
1961
+ return { ctx, switches };
1962
+ }
1963
+
1964
+ test('the library samples tools and jobs with no session id at all', async () => {
1965
+ const ctx = makeCtx(makeRepo());
1966
+ clearPresence();
1967
+ // The contract the front relies on: only the agent-task source needs an id
1968
+ // (it answers `unknown`, which blocks nothing), while the tool counter and
1969
+ // the host's `job_list` are sampled regardless — this is what the baseline
1970
+ // front's `waitForSessionActivity` -> `sessionActivity` also did with a null
1971
+ // id, so dropping the counters was a regression, not a baseline rule.
1972
+ addJobs(ctx, [{ id: 'job-lib-noid', status: 'running' }]);
1973
+ const withJob = await busyLib.sessionActivity({ sessionId: null, host: ctx });
1974
+ assert.equal(withJob.jobs.active, 1, 'a running job is sampled without any id');
1975
+ assert.equal(withJob.busy, true);
1976
+ assert.equal(withJob.status, 'unknown', 'only the agent-task source answers unknown without an id');
1977
+
1978
+ addJobs(ctx, []);
1979
+ busyLib.noteToolStart({ toolCallId: 'call-lib-noid', toolName: 'bash' });
1980
+ try {
1981
+ const withTool = await busyLib.sessionActivity({ sessionId: null, host: ctx });
1982
+ assert.equal(withTool.tools.inFlight, 1, 'an executing tool is sampled without any id');
1983
+ assert.equal(withTool.busy, true);
1984
+ } finally {
1985
+ busyLib.forgetInFlightTools();
1986
+ }
1987
+ });
1988
+
1989
+ test('a warp with no session id still queues while a tool is executing', async () => {
1990
+ const repo = makeRepo();
1991
+ const maker = makeCtx(repo);
1992
+ const created = await tools.get('worktree_create').execute('qo-9', { branch: 'feat/noid', odd: 'noid' }, undefined, undefined, maker);
1993
+ assert.notEqual(created.isError, true, resultText(created));
1994
+
1995
+ const { ctx, switches } = ctxWithoutSessionId(repo);
1996
+ clearPresence();
1997
+ addJobs(ctx, []);
1998
+ host.sent.length = 0;
1999
+ notifications.length = 0;
2000
+ widgetPaints.length = 0;
2001
+ const rootKey = busyLib.pendingKeyFor({ root: repo });
2002
+ const starts = hooks.filter(([name]) => name === 'tool_execution_start');
2003
+ assert.ok(starts.length > 0, 'the extension registers the host’s execution pair');
2004
+ for (const [, handler] of starts) await handler({ toolCallId: 'call-noid-1', toolName: 'bash', args: {} }, ctx);
2005
+ try {
2006
+ await commands.get('warp').handler('feat-noid', ctx);
2007
+ assert.equal(switches.length, 0, 'the session must not move while a tool executes');
2008
+ assert.equal(host.sent.length, 0, 'nothing is re-dispatched now');
2009
+ const record = busyLib.pendingWarpFor(rootKey);
2010
+ assert.notEqual(record, null, 'the request is queued under the checkout it stands in');
2011
+ assert.equal(record.name, 'feat-noid');
2012
+ assert.deepEqual(widgetState(ctx).lines, [WIDGET_DIM('Queued: warp feat-noid — waiting for 1 tool still executing')]);
2013
+ assert.deepEqual(notifications, [], 'the painted row is the only surface');
2014
+ } finally {
2015
+ busyLib.settlePendingWarp(rootKey);
2016
+ }
2017
+ });
2018
+
2019
+ test('a warp with no session id still queues while a background job is running', async () => {
2020
+ const repo = makeRepo();
2021
+ const maker = makeCtx(repo);
2022
+ const created = await tools.get('worktree_create').execute('qo-10', { branch: 'feat/noidjob', odd: 'noidjob' }, undefined, undefined, maker);
2023
+ assert.notEqual(created.isError, true, resultText(created));
2024
+
2025
+ const { ctx, switches } = ctxWithoutSessionId(repo);
2026
+ clearPresence();
2027
+ addJobs(ctx, [{ id: 'job-noid', status: 'running' }]);
2028
+ host.sent.length = 0;
2029
+ notifications.length = 0;
2030
+ widgetPaints.length = 0;
2031
+ const rootKey = busyLib.pendingKeyFor({ root: repo });
2032
+ try {
2033
+ await commands.get('warp').handler('feat-noidjob', ctx);
2034
+ assert.equal(switches.length, 0, 'the session must not move while a job runs');
2035
+ assert.equal(host.sent.length, 0, 'nothing is re-dispatched now');
2036
+ const record = busyLib.pendingWarpFor(rootKey);
2037
+ assert.notEqual(record, null, 'the request is queued under the checkout it stands in');
2038
+ assert.equal(record.name, 'feat-noidjob');
2039
+ assert.deepEqual(widgetState(ctx).lines, [WIDGET_DIM('Queued: warp feat-noidjob — waiting for 1 running background job')]);
2040
+ assert.deepEqual(notifications, [], 'the painted row is the only surface');
2041
+ } finally {
2042
+ busyLib.settlePendingWarp(rootKey);
2043
+ }
2044
+ });
2045
+ });
2046
+
2047
+ // ---------------------------------------------------------------------------
2048
+ // warp-queue-order T2 (S4): the summary, the question and the copy use the
2049
+ // checkout the session STANDS IN, never the principal checkout.
2050
+ // ---------------------------------------------------------------------------
2051
+ describe('warp-queue-order: the copy source is the session’s own checkout', () => {
2052
+ // Two pending files in the PRINCIPAL and one in the checkout the session
2053
+ // stands in, so a summary that read the principal could never be mistaken for
2054
+ // the right one (2 files, +2/-0 instead of 1 file, +1/-0).
2055
+ function seedBothCheckouts(repo, sessionCheckout) {
2056
+ fs.writeFileSync(path.join(repo, 'principal-one.txt'), 'one\n');
2057
+ fs.writeFileSync(path.join(repo, 'principal-two.txt'), 'two\n');
2058
+ fs.writeFileSync(path.join(sessionCheckout, 'here-only.txt'), 'here\n');
2059
+ }
2060
+
2061
+ test('the warp summarizes, asks about and copies from the session’s checkout', async () => {
2062
+ const repo = makeRepo();
2063
+ const maker = makeCtx(repo);
2064
+ const here = await tools.get('worktree_create').execute('qo-6', { branch: 'feat/here', odd: 'here' }, undefined, undefined, maker);
2065
+ assert.notEqual(here.isError, true, resultText(here));
2066
+ const there = await tools.get('worktree_create').execute('qo-7', { branch: 'feat/there', odd: 'there' }, undefined, undefined, maker);
2067
+ assert.notEqual(there.isError, true, resultText(there));
2068
+ seedBothCheckouts(repo, here.details.path);
2069
+
2070
+ const { ctx, switches } = movableCtx(here.details.path);
2071
+ clearPresence();
2072
+ addJobs(ctx, []);
2073
+ const asked = dirtyAsker('yes');
2074
+ notifications.length = 0;
2075
+ await commands.get('warp').handler('feat-there', ctx);
2076
+ assert.deepEqual(asked, ['1 file, +1/-0'], 'the summary counts the checkout the session stands in');
2077
+ assert.equal(switches.length, 1);
2078
+ assert.equal(
2079
+ fs.readFileSync(path.join(there.details.path, 'here-only.txt'), 'utf8'),
2080
+ 'here\n',
2081
+ 'the copy travelled from the checkout the session stands in',
2082
+ );
2083
+ assert.equal(fs.existsSync(path.join(there.details.path, 'principal-one.txt')), false, 'nothing was copied out of the principal');
2084
+ assert.equal(fs.existsSync(path.join(there.details.path, 'principal-two.txt')), false, 'nothing was copied out of the principal');
2085
+ });
2086
+
2087
+ test('the panel create’s question and copy use the session’s checkout too', async () => {
2088
+ const repo = makeRepo();
2089
+ const maker = makeCtx(repo);
2090
+ const here = await tools.get('worktree_create').execute('qo-8', { branch: 'feat/panel-here', odd: 'panel-here' }, undefined, undefined, maker);
2091
+ assert.notEqual(here.isError, true, resultText(here));
2092
+ seedBothCheckouts(repo, here.details.path);
2093
+ const target = portedDestination(repo, 'panel-made');
2094
+
2095
+ const asked = dirtyAsker('yes');
2096
+ const ui = {
2097
+ mounts: 0,
2098
+ custom: async () => {
2099
+ ui.mounts += 1;
2100
+ if (ui.mounts === 1) return { create: true };
2101
+ if (ui.mounts === 2) return { ok: true, branch: 'feat/panel-made', odd: 'panel-made' };
2102
+ return undefined;
2103
+ },
2104
+ };
2105
+ notifications.length = 0;
2106
+ await commands.get('warp').handler('', makeCtx(here.details.path, { custom: ui.custom }));
2107
+ assert.deepEqual(asked, ['1 file, +1/-0'], 'the create question counts the checkout the session stands in');
2108
+ assert.ok(fs.existsSync(target), `the create made no checkout (${JSON.stringify(notifications)})`);
2109
+ assert.equal(
2110
+ fs.readFileSync(path.join(target, 'here-only.txt'), 'utf8'),
2111
+ 'here\n',
2112
+ 'the copy travelled from the checkout the session stands in',
2113
+ );
2114
+ assert.equal(fs.existsSync(path.join(target, 'principal-one.txt')), false, 'nothing was copied out of the principal');
2115
+ assert.equal(fs.existsSync(path.join(target, 'principal-two.txt')), false, 'nothing was copied out of the principal');
2116
+ });
2117
+ });
2118
+
2119
+ // ---------------------------------------------------------------------------
2120
+ // warp-queue-boundary T8 (S11): the copy question can never be answered by a
2121
+ // keystroke the human did not mean for it. The question is driven through the
2122
+ // REAL picker (`ctx.ui.custom` mounts `lib/warp-create-picker.js`), so what the
2123
+ // host does with a single buffered Enter is observed end to end.
2124
+ // ---------------------------------------------------------------------------
2125
+ describe('S11 (T8): the copy question is never answered by one immediate Enter', () => {
2126
+ test('a single immediate Enter neither answers nor finishes the copy question', async () => {
2127
+ const repo = makeRepo();
2128
+ const maker = makeCtx(repo);
2129
+ const here = await tools.get('worktree_create').execute('grace-1', { branch: 'feat/grace-here', odd: 'grace-here' }, undefined, undefined, maker);
2130
+ assert.notEqual(here.isError, true, resultText(here));
2131
+ const there = await tools.get('worktree_create').execute('grace-2', { branch: 'feat/grace-there', odd: 'grace-there' }, undefined, undefined, maker);
2132
+ assert.notEqual(there.isError, true, resultText(there));
2133
+ fs.writeFileSync(path.join(here.details.path, 'grace-only.txt'), 'here\n');
2134
+
2135
+ const { ctx, switches } = movableCtx(here.details.path);
2136
+ clearPresence();
2137
+ addJobs(ctx, []);
2138
+ // The host mounts the question and the human's single Enter arrives at once —
2139
+ // the Enter that submitted `/warp`, a double tap, or one meant for a queued
2140
+ // message. The prompt then closes without an answer (what the host does when
2141
+ // the overlay is dismissed).
2142
+ const mounts = [];
2143
+ const answers = [];
2144
+ ctx.ui.custom = async (factory) => {
2145
+ const component = factory({ requestRender: () => {} }, null, null, (out) => { answers.push(out); });
2146
+ mounts.push(component);
2147
+ component.handleInput('\r');
2148
+ return undefined;
2149
+ };
2150
+ notifications.length = 0;
2151
+ await commands.get('warp').handler('feat-grace-there', ctx);
2152
+
2153
+ assert.equal(mounts.length, 1, 'a typed warp mounts the copy question exactly once');
2154
+ assert.deepEqual(answers, [], 'the immediate Enter answered nothing and finished nothing');
2155
+ const rows = mounts[0].render(120).map(plainLine);
2156
+ assert.ok(rows.some((line) => /^\s*❯\s+NO COPY$/.test(line)), `the question is still on screen on the safe answer: ${JSON.stringify(rows)}`);
2157
+ assert.ok(!rows.some((line) => /^\s*❯\s+YES COPY$/.test(line)), 'the destructive choice is never the focused one');
2158
+ assert.equal(switches.length, 0, 'an unanswered question moves nothing');
2159
+ assert.equal(
2160
+ fs.existsSync(path.join(there.details.path, 'grace-only.txt')),
2161
+ false,
2162
+ 'one immediate Enter never writes the source changes into the destination',
2163
+ );
2164
+ });
2165
+ });
2166
+
2167
+ // ---------------------------------------------------------------------------
2168
+ // warp-settle-dispatch T1-T3 (S1-S6): a warp typed mid-run is QUEUED and fires
2169
+ // by itself at the host's settle boundary. The host's own idle state
2170
+ // (`ctx.isIdle()`) is the fourth busy source, so "the assistant is still
2171
+ // thinking" — no tool executing, no agent task, no job — is busy too.
2172
+ // ---------------------------------------------------------------------------
2173
+ describe('warp-settle-dispatch: not-idle queues, agent_settled dispatches', () => {
2174
+ // The host's own idle state, mutated by the test. `waitForIdle` never resolves
2175
+ // while the host is processing a run, so a front that parks in a host wait is
2176
+ // observable instead of hanging the suite: it returns, and the wait is counted.
2177
+ function hostIdleState(ctx) {
2178
+ const state = { idle: false, waits: 0 };
2179
+ ctx.isIdle = () => state.idle;
2180
+ ctx.waitForIdle = () => {
2181
+ state.waits += 1;
2182
+ // The host would settle later: a front that parks here is observed by the
2183
+ // race below instead of hanging the suite when the assertion fails.
2184
+ return state.idle ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, 1500));
2185
+ };
2186
+ return state;
2187
+ }
2188
+
2189
+ // The host's settle boundary, driven through the handler the extension
2190
+ // registered. Awaited so a dispatch it starts is observable when it returns.
2191
+ async function settle(ctx) {
2192
+ const handlers = hooks.filter(([name]) => name === 'agent_settled');
2193
+ assert.ok(handlers.length > 0, 'the extension registers an agent_settled handler');
2194
+ for (const [, handler] of handlers) await handler({ aborted: false }, ctx);
2195
+ }
2196
+
2197
+ async function createdCheckout(ctx, callId, branch, odd) {
2198
+ const created = await tools.get('worktree_create').execute(callId, { branch, odd }, undefined, undefined, ctx);
2199
+ assert.notEqual(created.isError, true, resultText(created));
2200
+ return created;
2201
+ }
2202
+
2203
+ test('a mid-run warp with zero counters is queued, never awaited, and paints its row', async () => {
2204
+ const repo = makeRepo();
2205
+ const ctx = makeCtx(repo);
2206
+ const created = await createdCheckout(ctx, 'settle-1', 'feat/mid', 'mid');
2207
+ assert.notEqual(created.isError, true, resultText(created));
2208
+ clearPresence();
2209
+ const jobs = addJobs(ctx, []);
2210
+ const idle = hostIdleState(ctx);
2211
+ const switches = [];
2212
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
2213
+ host.sent.length = 0;
2214
+ notifications.length = 0;
2215
+ widgetPaints.length = 0;
2216
+ try {
2217
+ const answered = await Promise.race([
2218
+ commands.get('warp').handler('feat-mid', ctx).then(() => 'returned'),
2219
+ new Promise((resolve) => setTimeout(() => resolve('still-waiting'), 400)),
2220
+ ]);
2221
+ assert.equal(answered, 'returned', 'a mid-run request never waits for the host');
2222
+ assert.equal(idle.waits, 0, 'the handler entered no host wait');
2223
+ assert.equal(switches.length, 0, 'nothing moves while the run is live');
2224
+ assert.equal(host.sent.length, 0, 'nothing is dispatched before the settle boundary');
2225
+ assert.ok(jobs.calls > 0, 'the counters were read as they are');
2226
+ const record = busyLib.pendingWarpFor(pendingKey());
2227
+ assert.notEqual(record, null, 'the request is queued');
2228
+ assert.equal(record.name, 'feat-mid');
2229
+ assert.deepEqual(widgetState(ctx).lines, [WIDGET_DIM('Queued: warp feat-mid — waiting for the current agent run')]);
2230
+ assert.deepEqual(notifications, [], 'the painted row is the only surface');
2231
+ } finally {
2232
+ settlePending();
2233
+ }
2234
+ });
2235
+
2236
+ test('the settle boundary dispatches the pending record once, as /warp <token>', async () => {
2237
+ const repo = makeRepo();
2238
+ const { ctx, switches } = movableCtx(repo);
2239
+ await createdCheckout(ctx, 'settle-2', 'feat/settled', 'settled');
2240
+ clearPresence();
2241
+ addJobs(ctx, []);
2242
+ const idle = hostIdleState(ctx);
2243
+ host.sent.length = 0;
2244
+ notifications.length = 0;
2245
+ widgetPaints.length = 0;
2246
+ try {
2247
+ await commands.get('warp').handler('feat-settled', ctx);
2248
+ assert.equal(idle.waits, 0, 'the mid-run request waited for nothing');
2249
+ assert.equal(host.sent.length, 0, 'nothing is dispatched while the run is live');
2250
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the request is queued');
2251
+
2252
+ // The run settles: the counters were already zero, and now the host is
2253
+ // idle too. The boundary tick dispatches without waiting for a poll.
2254
+ idle.idle = true;
2255
+ await settle(ctx);
2256
+ assert.equal(host.sent.length, 1, 'the record is dispatched at the settle boundary');
2257
+ const [message, options] = host.sent[0];
2258
+ assert.deepEqual(options, { expandPromptTemplates: true });
2259
+ assert.ok(message.startsWith('/warp @'), `the queued command is /warp (${message})`);
2260
+ assert.equal(widgetState(ctx).lines, null, 'the dispatch clears the row');
2261
+
2262
+ // The dispatched command is the queued move: it lands and settles the
2263
+ // record, so the move started when the session settled.
2264
+ notifications.length = 0;
2265
+ await commands.get('warp').handler(message.slice('/warp '.length), ctx);
2266
+ assert.equal(switches.length, 1, 'the move lands at the settle boundary');
2267
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'the move clears the record');
2268
+ assert.deepEqual(notifications, [], 'a real move notifies nothing');
2269
+ } finally {
2270
+ settlePending();
2271
+ }
2272
+ });
2273
+
2274
+ test('a settle tick that arrives while a dispatch is already in flight dispatches nothing more', async () => {
2275
+ const repo = makeRepo();
2276
+ const { ctx, switches } = movableCtx(repo);
2277
+ await createdCheckout(ctx, 'settle-3', 'feat/race', 'race');
2278
+ clearPresence();
2279
+ // A deliberately slow job list: the first tick is still inside its read when
2280
+ // the second arrives, which is exactly the window a second lock would paper
2281
+ // over. The record's own `dispatching` guard must already cover it.
2282
+ let reads = 0;
2283
+ ctx.tools = [{ name: 'job_list' }];
2284
+ ctx.executeTool = async () => {
2285
+ reads += 1;
2286
+ await new Promise((resolve) => setTimeout(resolve, 40));
2287
+ return { content: [{ type: 'text', text: 'No background jobs in this session.' }] };
2288
+ };
2289
+ const idle = hostIdleState(ctx);
2290
+ host.sent.length = 0;
2291
+ notifications.length = 0;
2292
+ widgetPaints.length = 0;
2293
+ try {
2294
+ await commands.get('warp').handler('feat-race', ctx);
2295
+ assert.equal(host.sent.length, 0);
2296
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null);
2297
+
2298
+ idle.idle = true;
2299
+ const settled = settle(ctx);
2300
+ assert.equal(await until(() => reads > 0), true, 'the boundary tick reached the counters');
2301
+ const polled = busyLib.pendingWarpTick(pendingKey());
2302
+ await settled;
2303
+ assert.equal((await polled).status, 'waiting', 'the tick that found one in flight waits instead of dispatching');
2304
+ assert.equal(host.sent.length, 1, 'one record is dispatched at most once');
2305
+ assert.equal(host.sent[0][0].startsWith('/warp @'), true);
2306
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the record survives its own dispatch');
2307
+ assert.equal(switches.length, 0, 'nothing moved before the dispatched command ran');
2308
+ } finally {
2309
+ settlePending();
2310
+ }
2311
+ });
2312
+
2313
+ test('a second warp while one is pending is refused at once and touches no host wait', async () => {
2314
+ const repo = makeRepo();
2315
+ const ctx = makeCtx(repo);
2316
+ await createdCheckout(ctx, 'settle-4', 'feat/first', 'first');
2317
+ await createdCheckout(ctx, 'settle-5', 'feat/second', 'second');
2318
+ clearPresence();
2319
+ addJobs(ctx, []);
2320
+ const idle = hostIdleState(ctx);
2321
+ const switches = [];
2322
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
2323
+ host.sent.length = 0;
2324
+ notifications.length = 0;
2325
+ widgetPaints.length = 0;
2326
+ try {
2327
+ await commands.get('warp').handler('feat-first', ctx);
2328
+ const queued = busyLib.pendingWarpFor(pendingKey());
2329
+ assert.notEqual(queued, null, 'the first request is queued');
2330
+
2331
+ notifications.length = 0;
2332
+ const answered = await Promise.race([
2333
+ commands.get('warp').handler('feat-second', ctx).then(() => 'returned'),
2334
+ new Promise((resolve) => setTimeout(() => resolve('still-waiting'), 400)),
2335
+ ]);
2336
+ assert.equal(answered, 'returned', 'a second warp answers at once');
2337
+ assert.equal(idle.waits, 0, 'the refusal entered no host wait');
2338
+ assert.equal(switches.length, 0, 'the refused second warp moves nothing');
2339
+ assert.equal(host.sent.length, 0, 'the refusal dispatches nothing');
2340
+ assert.deepEqual(notifications.map(([level]) => level), ['error']);
2341
+ assert.match(
2342
+ notifications[0][1],
2343
+ /^worktree warp: a warp to feat-first is already pending for this session — it runs when this session's tools, agent tasks and background jobs finish; wait for it or let it expire$/,
2344
+ );
2345
+ assert.equal(busyLib.pendingWarpFor(pendingKey()).queuedAt, queued.queuedAt, 'the pending request is never replaced');
2346
+ } finally {
2347
+ settlePending();
2348
+ }
2349
+ });
2350
+
2351
+ test('an idle session still moves immediately: no queue, no row, no settle dispatch', async () => {
2352
+ const repo = makeRepo();
2353
+ const { ctx, switches } = movableCtx(repo);
2354
+ await createdCheckout(ctx, 'settle-6', 'feat/quiet-idle', 'quiet-idle');
2355
+ clearPresence();
2356
+ addJobs(ctx, []);
2357
+ const idle = hostIdleState(ctx);
2358
+ idle.idle = true;
2359
+ host.sent.length = 0;
2360
+ notifications.length = 0;
2361
+ widgetPaints.length = 0;
2362
+ try {
2363
+ await commands.get('warp').handler('feat-quiet-idle', ctx);
2364
+ assert.equal(switches.length, 1, 'an idle session moves straight away');
2365
+ assert.equal(idle.waits, 1, 'only the move path waits for idle');
2366
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'nothing was queued');
2367
+ assert.deepEqual(notifications, [], 'a real move notifies nothing');
2368
+ assert.equal(widgetPaintsFor(ctx).length, 0, 'an immediate move paints no row');
2369
+ await settle(ctx);
2370
+ assert.equal(host.sent.length, 0, 'a settle with nothing queued dispatches nothing');
2371
+ } finally {
2372
+ settlePending();
2373
+ }
2374
+ });
2375
+ });
2376
+
2377
+ // ---------------------------------------------------------------------------
2378
+ // warp-queue-boundary T1/T2/T5 (S1/S2/S5, warp-queue-boundary): a warp typed
2379
+ // mid-run takes effect at the SAME boundary Pi uses for a queued input message —
2380
+ // the end of the current assistant turn, after its tool calls and before the next
2381
+ // model call — and a dispatch is only ever attempted into an idle host. When the
2382
+ // host cannot paint the zone above the editor, the queued line falls back to ONE
2383
+ // fixed transcript entry.
2384
+ // ---------------------------------------------------------------------------
2385
+ describe('warp-queue-boundary: the queued warp lands at the turn boundary', () => {
2386
+ // The host's own state. `isIdle` is false while the run is live, `abort` ends
2387
+ // the run at the turn boundary (Pi then reports it as settled and idle), and
2388
+ // `waitForIdle` never resolves mid-run, so a front that parks in a host wait is
2389
+ // observable instead of hanging the suite.
2390
+ function turnHost(ctx) {
2391
+ const state = { idle: false, aborts: 0 };
2392
+ ctx.isIdle = () => state.idle;
2393
+ ctx.waitForIdle = () => {
2394
+ if (state.idle) return Promise.resolve();
2395
+ return new Promise((resolve) => setTimeout(resolve, 1500));
2396
+ };
2397
+ ctx.abort = () => {
2398
+ state.aborts += 1;
2399
+ state.idle = true;
2400
+ };
2401
+ return state;
2402
+ }
2403
+
2404
+ // The host's turn boundary, driven through the handler the extension
2405
+ // registered, once per registered handler. `tools` says whether the turn that
2406
+ // just ended executed tool calls — the host's `event.toolResults`, which is
2407
+ // S15's own signal: a turn with none is the agent's final answer.
2408
+ async function turnEnd(ctx, { tools = true } = {}) {
2409
+ const handlers = hooks.filter(([name]) => name === 'turn_end');
2410
+ assert.ok(handlers.length > 0, 'the extension registers a turn_end handler');
2411
+ const toolResults = tools ? [{ toolCallId: 'call-turn', toolName: 'bash', result: {} }] : [];
2412
+ for (const [, handler] of handlers) {
2413
+ const returned = await handler({ turnIndex: 0, timestamp: 1, toolResults, entries: [], outcome: 'completed' }, ctx);
2414
+ assert.equal(returned, undefined, 'a turn boundary proposes nothing: entries and continue stay as the host built them');
2415
+ }
2416
+ }
2417
+
2418
+ // The host's settle boundary, once the run is over.
2419
+ async function settle(ctx) {
2420
+ const handlers = hooks.filter(([name]) => name === 'agent_settled');
2421
+ assert.ok(handlers.length > 0, 'the extension registers an agent_settled handler');
2422
+ for (const [, handler] of handlers) await handler({ aborted: true }, ctx);
2423
+ }
2424
+
2425
+ async function created(ctx, callId, branch, odd) {
2426
+ const made = await tools.get('worktree_create').execute(callId, { branch, odd }, undefined, undefined, ctx);
2427
+ assert.notEqual(made.isError, true, resultText(made));
2428
+ return made;
2429
+ }
2430
+
2431
+ test('a warp typed mid-run moves at the turn boundary with no manual stop', async () => {
2432
+ const repo = makeRepo();
2433
+ const { ctx, switches } = movableCtx(repo);
2434
+ await created(ctx, 'wb-1', 'feat/boundary', 'boundary');
2435
+ clearPresence();
2436
+ addJobs(ctx, []);
2437
+ const state = turnHost(ctx);
2438
+ host.sent.length = 0;
2439
+ notifications.length = 0;
2440
+ widgetPaints.length = 0;
2441
+ try {
2442
+ await commands.get('warp').handler('feat-boundary', ctx);
2443
+ assert.equal(state.aborts, 0, 'a request never aborts the run it was typed into');
2444
+ assert.equal(switches.length, 0, 'nothing moved mid-run');
2445
+ assert.equal(host.sent.length, 0, 'nothing was dispatched into the streaming host');
2446
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the request is queued');
2447
+ // S8: the row above the editor is the whole message — the chat holds no
2448
+ // second copy of the same sentence.
2449
+ assert.deepEqual(notifications, [], JSON.stringify(notifications));
2450
+ assert.deepEqual(queuedSurface(ctx), ['Queued: warp feat-boundary — waiting for the current agent run']);
2451
+
2452
+ // The turn ends with its tool calls: the run itself is the only blocker, so
2453
+ // S17 ends the run ONCE, synchronously, and sends the agent nothing.
2454
+ await turnEnd(ctx);
2455
+ assert.equal(state.aborts, 1, 'the first boundary ends the run exactly once');
2456
+ assert.equal(host.steered.length, 0, 'nothing is ever sent to the agent');
2457
+ assert.equal(host.sent.length, 0, 'the run just ended; the settle boundary does the dispatch');
2458
+
2459
+ // Pi reports the aborted run as settled and idle: the queued move starts.
2460
+ await settle(ctx);
2461
+ assert.equal(host.sent.length, 1, 'the settle boundary dispatched the queued move');
2462
+ const [message] = host.sent[0];
2463
+ assert.ok(message.startsWith('/warp @'), message);
2464
+ notifications.length = 0;
2465
+ await commands.get('warp').handler(message.slice('/warp '.length), ctx);
2466
+ assert.equal(switches.length, 1, 'the move landed at the turn boundary with no manual stop');
2467
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'the move clears the record');
2468
+ assert.deepEqual(notifications, [], 'a real move notifies nothing');
2469
+
2470
+ // A record aborts at most once, and a settled record aborts nothing at all.
2471
+ await turnEnd(ctx);
2472
+ assert.equal(state.aborts, 1, 'one record aborts once');
2473
+ } finally {
2474
+ settlePending();
2475
+ }
2476
+ });
2477
+
2478
+ test('a tick while the host is still streaming never dispatches, and the settle tick still does', async () => {
2479
+ const repo = makeRepo();
2480
+ const { ctx, switches } = movableCtx(repo);
2481
+ await created(ctx, 'wb-2', 'feat/stream', 'stream');
2482
+ clearPresence();
2483
+ addJobs(ctx, []);
2484
+ const state = turnHost(ctx);
2485
+ host.sent.length = 0;
2486
+ notifications.length = 0;
2487
+ widgetPaints.length = 0;
2488
+ try {
2489
+ await commands.get('warp').handler('feat-stream', ctx);
2490
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the request is queued');
2491
+
2492
+ // The poller keeps firing while the run is live: the host would reject the
2493
+ // dispatch, so the record must stay pending and re-armed instead.
2494
+ for (let attempt = 0; attempt < 3; attempt += 1) {
2495
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'waiting');
2496
+ assert.equal(host.sent.length, 0, 'a streaming host never receives a dispatch');
2497
+ assert.equal(busyLib.pendingWarpFor(pendingKey()).dispatching, false, `attempt ${attempt} never marked the record dispatched`);
2498
+ }
2499
+ assert.deepEqual(
2500
+ widgetState(ctx).lines,
2501
+ [WIDGET_DIM('Queued: warp feat-stream — waiting for the current agent run')],
2502
+ 'the row names the run it is waiting for',
2503
+ );
2504
+ assert.equal(switches.length, 0, 'nothing moved while the run is live');
2505
+
2506
+ // Once the run ends, the same record dispatches — the wedge is gone.
2507
+ state.idle = true;
2508
+ await settle(ctx);
2509
+ assert.equal(host.sent.length, 1, 'the settle boundary dispatches the record the polls left pending');
2510
+ assert.equal(busyLib.pendingWarpFor(pendingKey()).dispatching, true, 'the dispatched record waits for its own command');
2511
+ const [message] = host.sent[0];
2512
+ await commands.get('warp').handler(message.slice('/warp '.length), ctx);
2513
+ assert.equal(switches.length, 1, 'the queued move lands');
2514
+ } finally {
2515
+ settlePending();
2516
+ }
2517
+ });
2518
+
2519
+ test('the row survives a refused second warp and clears on the boundary dispatch', async () => {
2520
+ const repo = makeRepo();
2521
+ const { ctx, switches } = movableCtx(repo);
2522
+ await created(ctx, 'wb-d1', 'feat/row-one', 'row-one');
2523
+ await created(ctx, 'wb-d2', 'feat/row-two', 'row-two');
2524
+ clearPresence();
2525
+ addJobs(ctx, []);
2526
+ const state = turnHost(ctx);
2527
+ host.sent.length = 0;
2528
+ notifications.length = 0;
2529
+ widgetPaints.length = 0;
2530
+ try {
2531
+ await commands.get('warp').handler('feat-row-one', ctx);
2532
+ const shown = widgetState(ctx);
2533
+ assert.deepEqual(shown.lines, [WIDGET_DIM('Queued: warp feat-row-one — waiting for the current agent run')]);
2534
+
2535
+ notifications.length = 0;
2536
+ await commands.get('warp').handler('feat-row-two', ctx);
2537
+ assert.deepEqual(notifications.map(([level]) => level), ['error'], 'the second warp is refused');
2538
+ assert.equal(switches.length, 0, 'the refusal moves nothing');
2539
+ assert.equal(widgetState(ctx).paints, shown.paints, 'the refusal repaints nothing');
2540
+ assert.deepEqual(widgetState(ctx).lines, shown.lines, 'the pending row survives the refusal');
2541
+ assert.equal(busyLib.pendingWarpFor(pendingKey()).name, 'feat-row-one', 'the pending request is never replaced');
2542
+
2543
+ // S17: the first boundary ends the run once, and nothing is sent to the agent.
2544
+ const abortsBeforeBoundary = state.aborts;
2545
+ host.steered.length = 0;
2546
+ await turnEnd(ctx);
2547
+ assert.equal(state.aborts, abortsBeforeBoundary + 1, 'the boundary ends the run once, for the pending record');
2548
+ assert.equal(host.steered.length, 0, 'and sends the agent nothing');
2549
+ state.idle = true;
2550
+ await settle(ctx);
2551
+ assert.equal(host.sent.length, 1, 'the settle boundary dispatches the pending record');
2552
+ assert.equal(widgetState(ctx).lines, null, 'the dispatch clears the row');
2553
+ assert.equal(busyLib.pendingWarpFor(pendingKey()).dispatching, true, 'the dispatched record waits for its own command');
2554
+ const [message] = host.sent[0];
2555
+ notifications.length = 0;
2556
+ await commands.get('warp').handler(message.slice('/warp '.length), ctx);
2557
+ assert.equal(switches.length, 1, 'the queued move lands');
2558
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'the move clears the record');
2559
+ assert.equal(widgetState(ctx).lines, null, 'and no row is left behind');
2560
+ } finally {
2561
+ settlePending();
2562
+ }
2563
+ });
2564
+
2565
+ test('a host with no widget zone gets ONE fixed transcript entry, never one per poll', async () => {
2566
+ const repo = makeRepo();
2567
+ const { ctx, switches } = movableCtx(repo);
2568
+ delete ctx.ui.setWidget;
2569
+ await created(ctx, 'wb-e1', 'feat/fallback', 'fallback');
2570
+ clearPresence();
2571
+ addJobs(ctx, []);
2572
+ const state = turnHost(ctx);
2573
+ host.sent.length = 0;
2574
+ notifications.length = 0;
2575
+ widgetPaints.length = 0;
2576
+ appendedEntries.length = 0;
2577
+ try {
2578
+ await commands.get('warp').handler('feat-fallback', ctx);
2579
+ assert.equal(widgetPaintsFor(ctx).length, 0, 'the host offers no row to paint');
2580
+ assert.equal(appendedEntries.length, 1, 'the queue appends exactly one durable line');
2581
+ assert.equal(
2582
+ entryRenderers.has(appendedEntries[0].customType),
2583
+ true,
2584
+ 'the entry carries a registered entry renderer, like Pi’s restored-messages line',
2585
+ );
2586
+ assert.deepEqual(fallbackLines(), [WIDGET_DIM('Queued: warp feat-fallback — waiting for the current agent run')]);
2587
+
2588
+ // The same reason adds nothing, and neither does a CHANGED reason: the
2589
+ // fallback is one fixed line per record, never one per poll.
2590
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'waiting');
2591
+ assert.equal(appendedEntries.length, 1, 'an unchanged reason appends nothing');
2592
+ for (const [, handler] of hooks.filter(([name]) => name === 'tool_execution_start')) {
2593
+ await handler({ toolCallId: 'call-fb-1', toolName: 'bash', args: {} }, ctx);
2594
+ }
2595
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'waiting');
2596
+ assert.equal(appendedEntries.length, 1, 'a changed reason adds no second line');
2597
+ assert.deepEqual(
2598
+ fallbackLines(),
2599
+ [WIDGET_DIM('Queued: warp feat-fallback — waiting for the current agent run')],
2600
+ 'the durable line never restates its reason',
2601
+ );
2602
+
2603
+ // The fallback is presentation, never state: the move still lands.
2604
+ for (const [, handler] of hooks.filter(([name]) => name === 'tool_execution_end')) {
2605
+ await handler({ toolCallId: 'call-fb-1', toolName: 'bash', result: {}, isError: false }, ctx);
2606
+ }
2607
+ state.idle = true;
2608
+ await settle(ctx);
2609
+ assert.equal(appendedEntries.length, 1, 'the dispatch appends nothing');
2610
+ assert.equal(host.sent.length, 1, 'the queued move is dispatched');
2611
+ const [message] = host.sent[0];
2612
+ await commands.get('warp').handler(message.slice('/warp '.length), ctx);
2613
+ assert.equal(switches.length, 1, 'the move lands with the fallback line in place');
2614
+ } finally {
2615
+ settlePending();
2616
+ }
2617
+ });
2618
+
2619
+ test('a widget seam that throws falls back to the same one durable line', async () => {
2620
+ const repo = makeRepo();
2621
+ const { ctx } = movableCtx(repo);
2622
+ ctx.ui.setWidget = () => { throw new Error('this host has no zone above the editor'); };
2623
+ await created(ctx, 'wb-e2', 'feat/throw', 'throw');
2624
+ clearPresence();
2625
+ addJobs(ctx, []);
2626
+ const state = turnHost(ctx);
2627
+ host.sent.length = 0;
2628
+ notifications.length = 0;
2629
+ widgetPaints.length = 0;
2630
+ appendedEntries.length = 0;
2631
+ try {
2632
+ await commands.get('warp').handler('feat-throw', ctx);
2633
+ assert.equal(appendedEntries.length, 1, 'a throwing seam appends exactly one durable line');
2634
+ assert.deepEqual(fallbackLines(), [WIDGET_DIM('Queued: warp feat-throw — waiting for the current agent run')]);
2635
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'waiting');
2636
+ assert.equal(appendedEntries.length, 1, 'the poll repaints nothing');
2637
+ state.idle = true;
2638
+ await settle(ctx);
2639
+ assert.equal(host.sent.length, 1, 'the queue still dispatches with no paintable row');
2640
+ } finally {
2641
+ settlePending();
2642
+ }
2643
+ });
2644
+ });
2645
+
2646
+ // ---------------------------------------------------------------------------
2647
+ // warp-queue-boundary T9 (S13, warp-queue-boundary): the boundary abort lands
2648
+ // BETWEEN provider requests. The record's LAST SAMPLED activity decides, and the
2649
+ // abort is taken from it SYNCHRONOUSLY — no awaited read in front of it — so the
2650
+ // host has not started the next request when the run is ended and nothing is
2651
+ // streaming for it to cut. An awaited re-read is only the fallback for a sample
2652
+ // that is absent or too old to trust, and even then the abort follows the read
2653
+ // only when the read proves nothing is running.
2654
+ // ---------------------------------------------------------------------------
2655
+ describe('warp-queue-boundary: the boundary abort lands between requests', () => {
2656
+ // One activity answer in the shape the queue stores: the run itself (host not
2657
+ // idle) is the only thing it reports, unless `extra` names real work.
2658
+ function sample(extra = {}) {
2659
+ return {
2660
+ status: 'ok',
2661
+ running: 0,
2662
+ queued: 0,
2663
+ waiting: 0,
2664
+ label: null,
2665
+ heartbeat: null,
2666
+ jobs: { status: 'ok', active: 0, count: 0 },
2667
+ jobsUnknown: false,
2668
+ tools: { inFlight: 0 },
2669
+ host: { idle: false },
2670
+ busy: true,
2671
+ ...extra,
2672
+ };
2673
+ }
2674
+
2675
+ const handoff = { name: 'feat-s13', target: '/t', from: '/f', branch: 'feat/s13', changes: { mode: 'none', paths: [] } };
2676
+
2677
+ // One pending record with every seam injected: a static clock, no real timers,
2678
+ // the reported activity as its LAST SAMPLE, and `isIdle` as the host's own
2679
+ // state at the boundary. Returns the mutable clock so a test can age the sample.
2680
+ function armed(key, { activity, read, dispatch, isIdle, pollMs = '60000' } = {}) {
2681
+ const clock = { now: 1000 };
2682
+ const queued = busyLib.queuePendingWarp({
2683
+ key,
2684
+ name: 'feat-s13',
2685
+ token: '@s13',
2686
+ handoff,
2687
+ activity: activity === undefined ? sample() : activity,
2688
+ now: () => clock.now,
2689
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '600000', ODD_WORKTREE_WARP_PENDING_POLL_MS: pollMs },
2690
+ timers: { set: () => null, clear: () => {} },
2691
+ isIdle,
2692
+ read,
2693
+ dispatch: dispatch || (() => ({ ok: true })),
2694
+ });
2695
+ assert.equal(queued.ok, true, JSON.stringify(queued));
2696
+ return clock;
2697
+ }
2698
+
2699
+ test('the abort lands synchronously, with no activity read in front of it', async () => {
2700
+ const key = 'session:s13-order';
2701
+ let reads = 0;
2702
+ const order = [];
2703
+ try {
2704
+ armed(key, {
2705
+ activity: sample(),
2706
+ isIdle: () => false,
2707
+ // A read that DID run before the abort is exactly the bug: it lets the
2708
+ // host start the next provider request, which the abort then cuts. Its
2709
+ // own order is recorded so a read cannot hide behind the fallback.
2710
+ read: async () => {
2711
+ reads += 1;
2712
+ order.push(['read', order.length > 0 ? order[0][0] : 'first']);
2713
+ return sample();
2714
+ },
2715
+ });
2716
+ // NOT awaited yet: the abort must already have happened at this point,
2717
+ // because `turn_end` has not yielded to the event loop.
2718
+ const running = busyLib.pendingWarpTurnBoundary({ abort: () => { order.push(['abort', reads]); } });
2719
+ assert.deepEqual(order, [['abort', 0]], 'the abort landed in the same synchronous stretch as the turn boundary, before any read');
2720
+ const results = await running;
2721
+ assert.deepEqual(results, [{ status: 'aborted' }]);
2722
+ assert.equal(reads, 0, 'the normal path reads nothing before it aborts');
2723
+ assert.deepEqual(order, [['abort', 0]], 'nothing ran after the abort either');
2724
+ } finally {
2725
+ busyLib.settlePendingWarp(key);
2726
+ }
2727
+ });
2728
+
2729
+ test('the last sampled work wins: a running job or a tool in flight never aborts, even if a re-read would say otherwise', async () => {
2730
+ const cases = [
2731
+ ['a running background job', sample({ jobs: { status: 'ok', active: 1, count: 1 } })],
2732
+ ['a tool still executing', sample({ tools: { inFlight: 1 } })],
2733
+ ['a running agent task', sample({ running: 1 })],
2734
+ ['a queued agent task', sample({ queued: 2 })],
2735
+ ];
2736
+ for (const [label, activity] of cases) {
2737
+ const key = `session:s13-busy-${label.replace(/\W+/g, '-')}`;
2738
+ let reads = 0;
2739
+ const aborts = [];
2740
+ try {
2741
+ armed(key, {
2742
+ activity,
2743
+ isIdle: () => false,
2744
+ // A read that claimed the work had drained is the trap this pins: the
2745
+ // sample says work is running, so the record must not be cut.
2746
+ read: async () => { reads += 1; return sample(); },
2747
+ });
2748
+ assert.deepEqual(
2749
+ await busyLib.pendingWarpTurnBoundary({ abort: () => aborts.push(label) }),
2750
+ [{ status: 'busy' }],
2751
+ `${label} is real work`,
2752
+ );
2753
+ assert.deepEqual(aborts, [], `${label} must hold the run open`);
2754
+ assert.equal(reads, 0, `${label}: the last sample decided, no read was needed`);
2755
+ } finally {
2756
+ busyLib.settlePendingWarp(key);
2757
+ }
2758
+ }
2759
+ });
2760
+
2761
+ test('a host that is already idle aborts nothing: the settle tick dispatches', async () => {
2762
+ const key = 'session:s13-idle';
2763
+ const aborts = [];
2764
+ const dispatched = [];
2765
+ try {
2766
+ armed(key, {
2767
+ activity: sample({ busy: false, host: { idle: true } }),
2768
+ isIdle: () => true,
2769
+ dispatch: (queuedHandoff, token) => { dispatched.push([queuedHandoff, token]); return { ok: true }; },
2770
+ });
2771
+ assert.deepEqual(await busyLib.pendingWarpTurnBoundary({ abort: () => aborts.push('abort') }), [{ status: 'idle' }]);
2772
+ assert.deepEqual(aborts, [], 'an idle host needs no abort: nothing is running to end');
2773
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'dispatched');
2774
+ assert.deepEqual(dispatched, [[handoff, '@s13']], 'the settle tick moves the record itself');
2775
+ } finally {
2776
+ busyLib.settlePendingWarp(key);
2777
+ }
2778
+ });
2779
+
2780
+ test('one abort per record: a second boundary and a record waiting on its re-dispatch abort nothing', async () => {
2781
+ const key = 'session:s13-once';
2782
+ const aborts = [];
2783
+ // A dispatch the host refuses leaves the record PENDING and re-armed, never
2784
+ // spinning: the boundary still refuses to abort it a second time.
2785
+ let refuse = true;
2786
+ try {
2787
+ armed(key, {
2788
+ activity: sample(),
2789
+ isIdle: () => false,
2790
+ dispatch: () => (refuse ? { ok: false, error: 'the host cannot dispatch the warp command here' } : { ok: true }),
2791
+ });
2792
+ assert.deepEqual(
2793
+ await busyLib.pendingWarpTurnBoundary({ abort: () => aborts.push('first') }),
2794
+ [{ status: 'aborted' }],
2795
+ );
2796
+ assert.deepEqual(aborts, ['first'], 'the run is ended once, for this record');
2797
+
2798
+ // The same turn boundary again: the record already aborted this run.
2799
+ assert.deepEqual(await busyLib.pendingWarpTurnBoundary({ abort: () => aborts.push('second') }), [{ status: 'skipped' }]);
2800
+ assert.deepEqual(aborts, ['first'], 'a record never aborts twice');
2801
+
2802
+ // A refused dispatch releases the slot and re-arms instead of spinning, and
2803
+ // the boundary still does not abort the record a second time.
2804
+ refuse = true;
2805
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'waiting');
2806
+ assert.equal(busyLib.pendingWarpFor(key).dispatching, false, 'a refused dispatch stays pending and re-armed');
2807
+ assert.deepEqual(await busyLib.pendingWarpTurnBoundary({ abort: () => aborts.push('third') }), [{ status: 'skipped' }]);
2808
+ assert.deepEqual(aborts, ['first'], 'a refused dispatch never spins the session');
2809
+ } finally {
2810
+ busyLib.settlePendingWarp(key);
2811
+ }
2812
+ });
2813
+
2814
+ test('a sample too old to trust is re-read, and the abort follows only a read that proves nothing runs', async () => {
2815
+ const key = 'session:s13-stale';
2816
+ const order = [];
2817
+ const answers = [];
2818
+ try {
2819
+ const clock = armed(key, {
2820
+ activity: sample(),
2821
+ pollMs: '1000',
2822
+ isIdle: () => false,
2823
+ read: async () => { order.push('read'); return answers.shift(); },
2824
+ });
2825
+ // Older than one poll interval: the poller would have re-sampled by now, so
2826
+ // this sample cannot decide on its own.
2827
+ clock.now += 5000;
2828
+
2829
+ // The re-read finds a running job: the record must not be cut.
2830
+ answers.push(sample({ jobs: { status: 'ok', active: 1, count: 1 } }));
2831
+ const aborts = [];
2832
+ assert.deepEqual(
2833
+ await busyLib.pendingWarpTurnBoundary({ abort: () => { order.push('abort'); aborts.push('abort'); } }),
2834
+ [{ status: 'busy' }],
2835
+ );
2836
+ assert.deepEqual(order, ['read'], 'the stale sample is re-read before anything else');
2837
+ assert.deepEqual(aborts, [], 'a read that finds real work aborts nothing');
2838
+
2839
+ // That read IS the record's new sample: inside one poll interval the next
2840
+ // boundary decides from it again, with no read in front of the decision.
2841
+ order.length = 0;
2842
+ clock.now += 1;
2843
+ assert.deepEqual(
2844
+ await busyLib.pendingWarpTurnBoundary({ abort: () => order.push('abort') }),
2845
+ [{ status: 'busy' }],
2846
+ );
2847
+ assert.deepEqual(order, [], 'the sample the fallback just proved good is trusted, so no read runs again');
2848
+
2849
+ // Once it ages past the poll interval the fallback reads again, and a read
2850
+ // that proves nothing is running lets the abort follow it.
2851
+ clock.now += 5000;
2852
+ answers.push(sample());
2853
+ assert.deepEqual(
2854
+ await busyLib.pendingWarpTurnBoundary({ abort: () => order.push('abort') }),
2855
+ [{ status: 'aborted' }],
2856
+ );
2857
+ assert.deepEqual(order, ['read', 'abort'], 'the abort follows the read only because it proved nothing runs');
2858
+ } finally {
2859
+ busyLib.settlePendingWarp(key);
2860
+ }
2861
+ });
2862
+
2863
+ test('a record queued with no sample at all is re-read, and aborts when the read proves nothing runs', async () => {
2864
+ const key = 'session:s13-absent';
2865
+ const order = [];
2866
+ try {
2867
+ assert.equal(busyLib.queuePendingWarp({
2868
+ key,
2869
+ name: 'feat-s13',
2870
+ token: '@s13',
2871
+ handoff,
2872
+ activity: null,
2873
+ now: () => 1000,
2874
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '600000' },
2875
+ timers: { set: () => null, clear: () => {} },
2876
+ isIdle: () => false,
2877
+ read: async () => { order.push('read'); return sample(); },
2878
+ dispatch: () => ({ ok: true }),
2879
+ }).ok, true);
2880
+ assert.deepEqual(
2881
+ await busyLib.pendingWarpTurnBoundary({ abort: () => order.push('abort') }),
2882
+ [{ status: 'aborted' }],
2883
+ );
2884
+ assert.deepEqual(order, ['read', 'abort'], 'no sample: the read comes first, and the abort follows only because it proved nothing runs');
2885
+ } finally {
2886
+ busyLib.settlePendingWarp(key);
2887
+ }
2888
+ });
2889
+ });
2890
+
2891
+ // ---------------------------------------------------------------------------
2892
+ // warp-queue-boundary T11 (S17, warp-queue-boundary): the boundary sends the
2893
+ // agent NOTHING and ends the run itself. At the first `turn_end` where the run is
2894
+ // the only blocker and the turn that just ended executed tools, the extension
2895
+ // aborts ONCE, synchronously, so the move lands at the queued-message boundary
2896
+ // and no message of any kind ever reaches the agent (S15's hidden steering
2897
+ // message is removed: a model may answer it with text, and a text turn produces
2898
+ // no later tool-using boundary for a safety net to fire on). A turn that ended
2899
+ // with no tool results is the agent's final answer — the run settles on its own —
2900
+ // and a record with real work pending or an idle host is left alone.
2901
+ // ---------------------------------------------------------------------------
2902
+ describe('warp-queue-boundary: the boundary ends the run itself and sends nothing', () => {
2903
+ // One activity answer in the shape the queue stores: the run itself (host not
2904
+ // idle) is all it reports, unless `extra` names real work.
2905
+ function sample(extra = {}) {
2906
+ return {
2907
+ status: 'ok',
2908
+ running: 0,
2909
+ queued: 0,
2910
+ waiting: 0,
2911
+ label: null,
2912
+ heartbeat: null,
2913
+ jobs: { status: 'ok', active: 0, count: 0 },
2914
+ jobsUnknown: false,
2915
+ tools: { inFlight: 0 },
2916
+ host: { idle: false },
2917
+ busy: true,
2918
+ ...extra,
2919
+ };
2920
+ }
2921
+
2922
+ const handoff = { name: 'feat-abort', target: '/t', from: '/f', branch: 'feat/abort', changes: { mode: 'none', paths: [] } };
2923
+
2924
+ // One pending record with every seam injected: a static clock, no real timers,
2925
+ // the given activity as its LAST SAMPLE, and `isIdle` as the host's own state
2926
+ // at the boundary.
2927
+ function armed(key, { activity, read, isIdle, dispatch } = {}) {
2928
+ const queued = busyLib.queuePendingWarp({
2929
+ key,
2930
+ name: 'feat-abort',
2931
+ token: '@abort',
2932
+ handoff,
2933
+ activity: activity === undefined ? sample() : activity,
2934
+ now: () => 1000,
2935
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '600000', ODD_WORKTREE_WARP_PENDING_POLL_MS: '60000' },
2936
+ timers: { set: () => null, clear: () => {} },
2937
+ isIdle,
2938
+ read,
2939
+ dispatch: dispatch || (() => ({ ok: true })),
2940
+ });
2941
+ assert.equal(queued.ok, true, JSON.stringify(queued));
2942
+ }
2943
+
2944
+ // The host's own state for the front-driven tests: live until the boundary
2945
+ // abort ends it, with `waitForIdle` parked so a front that waits forever is
2946
+ // observable instead of hanging the suite.
2947
+ function turnHost(ctx) {
2948
+ const state = { idle: false, aborts: 0 };
2949
+ ctx.isIdle = () => state.idle;
2950
+ ctx.waitForIdle = () => {
2951
+ if (state.idle) return Promise.resolve();
2952
+ return new Promise((resolve) => setTimeout(resolve, 1500));
2953
+ };
2954
+ ctx.abort = () => {
2955
+ state.aborts += 1;
2956
+ state.idle = true;
2957
+ };
2958
+ return state;
2959
+ }
2960
+
2961
+ // The host's turn boundary, driven through the handler the extension
2962
+ // registered. `event.toolResults` is the host's own evidence about the turn that
2963
+ // just ended: a turn with none is the agent's final answer.
2964
+ async function turnEnd(ctx, { tools = true } = {}) {
2965
+ const handlers = hooks.filter(([name]) => name === 'turn_end');
2966
+ assert.ok(handlers.length > 0, 'the extension registers a turn_end handler');
2967
+ const toolResults = tools ? [{ toolCallId: 'call-t11', toolName: 'bash', result: {} }] : [];
2968
+ for (const [, handler] of handlers) {
2969
+ const returned = await handler({ turnIndex: 0, timestamp: 1, toolResults, entries: [], outcome: 'completed' }, ctx);
2970
+ assert.equal(returned, undefined, 'the boundary proposes nothing: entries and continue stay as the host built them');
2971
+ }
2972
+ }
2973
+
2974
+ async function settle(ctx) {
2975
+ const handlers = hooks.filter(([name]) => name === 'agent_settled');
2976
+ assert.ok(handlers.length > 0, 'the extension registers an agent_settled handler');
2977
+ for (const [, handler] of handlers) await handler({ aborted: true }, ctx);
2978
+ }
2979
+
2980
+ async function created(ctx, callId, branch, odd) {
2981
+ const made = await tools.get('worktree_create').execute(callId, { branch, odd }, undefined, undefined, ctx);
2982
+ assert.notEqual(made.isError, true, resultText(made));
2983
+ return made;
2984
+ }
2985
+
2986
+ test('the first boundary with tool results aborts once, and the host sends no message of any kind', async () => {
2987
+ const repo = makeRepo();
2988
+ const { ctx, switches } = movableCtx(repo);
2989
+ await created(ctx, 't11-1', 'feat/abort-one', 'abort-one');
2990
+ clearPresence();
2991
+ addJobs(ctx, []);
2992
+ const state = turnHost(ctx);
2993
+ host.sent.length = 0;
2994
+ host.steered.length = 0;
2995
+ notifications.length = 0;
2996
+ widgetPaints.length = 0;
2997
+ try {
2998
+ await commands.get('warp').handler('feat-abort-one', ctx);
2999
+ assert.equal(host.steered.length, 0, 'queueing sends no message');
3000
+ assert.equal(state.aborts, 0, 'queueing aborts nothing');
3001
+ assert.deepEqual(queuedSurface(ctx), ['Queued: warp feat-abort-one — waiting for the current agent run']);
3002
+
3003
+ // The turn ends with its tool calls: the run is the only blocker, so the
3004
+ // extension ends it — once, at THIS first boundary.
3005
+ await turnEnd(ctx, { tools: true });
3006
+ assert.equal(state.aborts, 1, 'the first boundary aborts the run exactly once');
3007
+ assert.equal(host.steered.length, 0, 'the boundary sends the agent no message of any kind');
3008
+ assert.deepEqual(notifications, [], 'and nothing of it is a chat line either');
3009
+ assert.equal(switches.length, 0, 'nothing moved at the boundary');
3010
+ assert.equal(host.sent.length, 0, 'nothing was dispatched into the live host');
3011
+
3012
+ // Pi reports the aborted run as settled and idle: the queued move lands.
3013
+ state.idle = true;
3014
+ await settle(ctx);
3015
+ assert.equal(host.sent.length, 1, 'the settle boundary dispatches the queued move');
3016
+ const [dispatch] = host.sent[0];
3017
+ notifications.length = 0;
3018
+ await commands.get('warp').handler(dispatch.slice('/warp '.length), ctx);
3019
+ assert.equal(switches.length, 1, 'the move lands at the turn boundary with no manual stop');
3020
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'the move clears the record');
3021
+ assert.deepEqual(notifications, [], 'a real move notifies nothing');
3022
+ assert.equal(host.steered.length, 0, 'no message was sent at any point');
3023
+ } finally {
3024
+ settlePending();
3025
+ }
3026
+ });
3027
+
3028
+ test('the abort lands synchronously, with no read in front of it, and there is no message seam at all', async () => {
3029
+ const key = 'session:t11-order';
3030
+ const order = [];
3031
+ let reads = 0;
3032
+ try {
3033
+ armed(key, {
3034
+ isIdle: () => false,
3035
+ // A read that ran before the step is exactly the S13 bug: it lets the host
3036
+ // start the next provider request, which the abort then cuts.
3037
+ read: async () => { reads += 1; order.push('read'); return sample(); },
3038
+ });
3039
+ // NOT awaited: the abort must already have happened, because `turn_end` has
3040
+ // not yielded to the event loop.
3041
+ const running = busyLib.pendingWarpTurnBoundary({
3042
+ abort: () => order.push('abort'),
3043
+ sawTools: true,
3044
+ });
3045
+ assert.deepEqual(order, ['abort'], 'the abort landed in the same synchronous stretch as the boundary');
3046
+ assert.deepEqual(await running, [{ status: 'aborted' }]);
3047
+ assert.equal(reads, 0, 'the abort reads nothing in front of it');
3048
+ // S17: the module offers no text to send, so no host could send one.
3049
+ assert.equal(typeof busyLib.steerText, 'undefined', 'the steering seam is gone from the module surface');
3050
+
3051
+ // Every later boundary is inert: one abort per record.
3052
+ order.length = 0;
3053
+ assert.deepEqual(
3054
+ await busyLib.pendingWarpTurnBoundary({ abort: () => order.push('abort-again'), sawTools: true }),
3055
+ [{ status: 'skipped' }],
3056
+ );
3057
+ assert.deepEqual(order, [], 'a record never aborts twice');
3058
+ } finally {
3059
+ busyLib.settlePendingWarp(key);
3060
+ }
3061
+ });
3062
+
3063
+ test('a second boundary of the same record never aborts again, and the queued move still lands', async () => {
3064
+ const repo = makeRepo();
3065
+ const { ctx, switches } = movableCtx(repo);
3066
+ await created(ctx, 't11-2', 'feat/abort-twice', 'abort-twice');
3067
+ clearPresence();
3068
+ addJobs(ctx, []);
3069
+ const state = turnHost(ctx);
3070
+ host.sent.length = 0;
3071
+ host.steered.length = 0;
3072
+ notifications.length = 0;
3073
+ widgetPaints.length = 0;
3074
+ try {
3075
+ await commands.get('warp').handler('feat-abort-twice', ctx);
3076
+
3077
+ await turnEnd(ctx, { tools: true });
3078
+ assert.equal(state.aborts, 1, 'the first boundary ends the run once');
3079
+ assert.equal(host.steered.length, 0, 'and sends nothing');
3080
+
3081
+ // A later boundary of the same record is inert, however many arrive.
3082
+ await turnEnd(ctx, { tools: true });
3083
+ await turnEnd(ctx, { tools: true });
3084
+ assert.equal(state.aborts, 1, 'one abort per record, never twice');
3085
+ assert.equal(host.steered.length, 0, 'and still no message');
3086
+
3087
+ state.idle = true;
3088
+ await settle(ctx);
3089
+ assert.equal(host.sent.length, 1, 'the settle boundary still dispatches the queued move');
3090
+ const [dispatch] = host.sent[0];
3091
+ await commands.get('warp').handler(dispatch.slice('/warp '.length), ctx);
3092
+ assert.equal(switches.length, 1, 'the move lands');
3093
+ } finally {
3094
+ settlePending();
3095
+ }
3096
+ });
3097
+
3098
+ test('a turn with no tool results neither aborts nor sends, and the run settling dispatches', async () => {
3099
+ const repo = makeRepo();
3100
+ const { ctx, switches } = movableCtx(repo);
3101
+ await created(ctx, 't11-3', 'feat/abort-final', 'abort-final');
3102
+ clearPresence();
3103
+ addJobs(ctx, []);
3104
+ const state = turnHost(ctx);
3105
+ host.sent.length = 0;
3106
+ host.steered.length = 0;
3107
+ notifications.length = 0;
3108
+ widgetPaints.length = 0;
3109
+ try {
3110
+ await commands.get('warp').handler('feat-abort-final', ctx);
3111
+ // No tool results: that turn WAS the agent's final answer, so the run
3112
+ // settles by itself and the extension has nothing to send or to end.
3113
+ await turnEnd(ctx, { tools: false });
3114
+ assert.equal(state.aborts, 0, 'a final answer is never aborted');
3115
+ assert.equal(host.steered.length, 0, 'and never messaged');
3116
+ assert.equal(busyLib.pendingWarpFor(pendingKey()).dispatching, false, 'the record is still pending');
3117
+
3118
+ state.idle = true;
3119
+ await settle(ctx);
3120
+ assert.equal(host.sent.length, 1, 'the settled run dispatches the queued move on its own');
3121
+ const [dispatch] = host.sent[0];
3122
+ await commands.get('warp').handler(dispatch.slice('/warp '.length), ctx);
3123
+ assert.equal(switches.length, 1, 'the move lands');
3124
+ } finally {
3125
+ settlePending();
3126
+ }
3127
+ });
3128
+
3129
+ test('real work pending means no abort and no message', async () => {
3130
+ const cases = [
3131
+ ['a running background job', sample({ jobs: { status: 'ok', active: 1, count: 1 } })],
3132
+ ['a tool still executing', sample({ tools: { inFlight: 1 } })],
3133
+ ['a running agent task', sample({ running: 1 })],
3134
+ ['a queued agent task', sample({ queued: 2 })],
3135
+ ];
3136
+ for (const [label, activity] of cases) {
3137
+ const key = `session:t11-busy-${label.replace(/\W+/g, '-')}`;
3138
+ const aborts = [];
3139
+ try {
3140
+ armed(key, { activity, isIdle: () => false });
3141
+ assert.deepEqual(
3142
+ await busyLib.pendingWarpTurnBoundary({
3143
+ abort: () => aborts.push(label),
3144
+ sawTools: true,
3145
+ }),
3146
+ [{ status: 'busy' }],
3147
+ `${label} is real work`,
3148
+ );
3149
+ assert.deepEqual(aborts, [], `${label} must never cut the run`);
3150
+ } finally {
3151
+ busyLib.settlePendingWarp(key);
3152
+ }
3153
+ }
3154
+ });
3155
+
3156
+ test('an idle host does nothing: the settle tick dispatches the move', async () => {
3157
+ const key = 'session:t11-idle';
3158
+ const aborts = [];
3159
+ const dispatched = [];
3160
+ try {
3161
+ armed(key, {
3162
+ activity: sample({ busy: false, host: { idle: true } }),
3163
+ isIdle: () => true,
3164
+ dispatch: (queuedHandoff, token) => { dispatched.push([queuedHandoff, token]); return { ok: true }; },
3165
+ });
3166
+ assert.deepEqual(
3167
+ await busyLib.pendingWarpTurnBoundary({ abort: () => aborts.push('abort'), sawTools: true }),
3168
+ [{ status: 'idle' }],
3169
+ );
3170
+ assert.deepEqual(aborts, [], 'an idle host has no run to end');
3171
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'dispatched');
3172
+ assert.deepEqual(dispatched, [[handoff, '@abort']], 'the settle tick moves the record itself');
3173
+ } finally {
3174
+ busyLib.settlePendingWarp(key);
3175
+ }
3176
+ });
3177
+ });
3178
+ // ---------------------------------------------------------------------------
3179
+ // warp-queue-boundary T6 (S8, warp-queue-boundary): the queue speaks through ONE
3180
+ // surface per request. When the fixed row above the editor (or its durable
3181
+ // fallback entry) showed the line, the chat gets NO second copy of the same
3182
+ // sentence; a host with no surface at all still gets the one notice, because
3183
+ // otherwise the human would never learn the request is queued.
3184
+ // ---------------------------------------------------------------------------
3185
+ describe('warp-queue-boundary: one surface per queued request', () => {
3186
+ async function queuedCheckout(ctx, callId, branch, odd) {
3187
+ const made = await tools.get('worktree_create').execute(callId, { branch, odd }, undefined, undefined, ctx);
3188
+ assert.notEqual(made.isError, true, resultText(made));
3189
+ return made;
3190
+ }
3191
+
3192
+ test('a painted row is the only surface, and a host with no surface at all still gets one notice', async () => {
3193
+ const repo = makeRepo();
3194
+ const { ctx } = movableCtx(repo);
3195
+ await queuedCheckout(ctx, 's8-1', 'feat/s8one', 's8one');
3196
+ clearPresence();
3197
+ const jobs = addJobs(ctx, [{ id: 'job-s8', status: 'running' }]);
3198
+ notifications.length = 0;
3199
+ widgetPaints.length = 0;
3200
+ appendedEntries.length = 0;
3201
+ try {
3202
+ await commands.get('warp').handler('feat-s8one', ctx);
3203
+ const line = 'Queued: warp feat-s8one — waiting for 1 running background job';
3204
+ assert.deepEqual(queuedSurface(ctx), [line], 'the row above the editor shows the one line');
3205
+ assert.equal(queuedNotices().length, 0, `the chat holds no second copy: ${JSON.stringify(notifications)}`);
3206
+ assert.deepEqual(notifications, [], 'the painted row is the whole message');
3207
+ assert.equal(jobs.calls > 0, true, 'the request really was queued while the job ran');
3208
+ settlePending();
3209
+
3210
+ // A host with NO surface at all: no zone above the editor and no
3211
+ // `appendEntry` seam, so nothing can show the line. The one notice is then
3212
+ // the only surface, and it is emitted exactly once.
3213
+ const bare = makeCtx(repo);
3214
+ delete bare.ui.setWidget;
3215
+ const savedAppendEntry = host.appendEntry;
3216
+ host.appendEntry = undefined;
3217
+ addJobs(bare, [{ id: 'job-s8b', status: 'running' }]);
3218
+ notifications.length = 0;
3219
+ appendedEntries.length = 0;
3220
+ try {
3221
+ await commands.get('warp').handler('feat-s8one', bare);
3222
+ assert.deepEqual(appendedEntries, [], 'the host offers no durable entry to fall back to');
3223
+ assert.equal(widgetPaintsFor(bare).length, 0, 'and no row to paint');
3224
+ assert.deepEqual(notifications, [['info', line]], 'a surface-less host gets the line exactly once');
3225
+ } finally {
3226
+ host.appendEntry = savedAppendEntry;
3227
+ }
3228
+ } finally {
3229
+ settlePending();
3230
+ }
3231
+ });
3232
+
3233
+ test('the queued answer still carries the line in its result object', async () => {
3234
+ const repo = makeRepo();
3235
+ const { ctx } = movableCtx(repo);
3236
+ await queuedCheckout(ctx, 's8-2', 'feat/s8result', 's8result');
3237
+ clearPresence();
3238
+ addJobs(ctx, [{ id: 'job-s8r', status: 'running' }]);
3239
+ notifications.length = 0;
3240
+ widgetPaints.length = 0;
3241
+ try {
3242
+ const out = await mod.executeWorktreeWarp('feat-s8result', ctx);
3243
+ assert.notEqual(out.isError, true, JSON.stringify(out));
3244
+ assert.equal(out.stillQueued, true, 'the request is queued, not moved');
3245
+ assert.equal(out.text, 'Queued: warp feat-s8result — waiting for 1 running background job', 'the result still carries the line');
3246
+ assert.equal(out.details.queued, true);
3247
+ assert.deepEqual(queuedSurface(ctx), [out.text], 'the row shows that same line, once');
3248
+ assert.deepEqual(notifications, [], 'printing it again in the chat is the duplicate the report named');
3249
+ } finally {
3250
+ settlePending();
3251
+ }
3252
+ });
3253
+ });
3254
+
3255
+ // ---------------------------------------------------------------------------
3256
+ // warp-queue-boundary T7 (S9, warp-queue-boundary): a carrying copy the
3257
+ // destination REFUSES never blocks the move. When the refusal proves nothing
3258
+ // landed, the warp proceeds without copying, overwrites nothing and discloses it
3259
+ // in ONE line naming the copies it could not carry. A copy that DID land — even
3260
+ // partially — remains a hard failure, because that is real state.
3261
+ // ---------------------------------------------------------------------------
3262
+ describe('warp-queue-boundary: a refused carry-copy never blocks the move', () => {
3263
+ // A destination that committed its own version of the same line the source has
3264
+ // pending: the three-way merge has no automatic answer, so the copy refuses
3265
+ // and writes nothing — the shape the report hit.
3266
+ async function conflictedDestination(callId) {
3267
+ const repo = makeRepo();
3268
+ fs.writeFileSync(path.join(repo, 'conflict.txt'), 'l1\nl2\n');
3269
+ git(repo, ['add', 'conflict.txt']);
3270
+ git(repo, ['commit', '-m', 'base']);
3271
+ const { ctx, switches } = movableCtx(repo);
3272
+ const made = await tools.get('worktree_create').execute(callId, { branch: 'feat/s9dest', odd: 's9dest' }, undefined, undefined, ctx);
3273
+ assert.notEqual(made.isError, true, resultText(made));
3274
+ const destPath = made.details.path;
3275
+ fs.writeFileSync(path.join(destPath, 'conflict.txt'), 'l1\nDEST-L2\n');
3276
+ git(destPath, ['commit', '-am', 'destination: its own line']);
3277
+ fs.writeFileSync(path.join(repo, 'conflict.txt'), 'l1\nSRC-PENDING-L2\n');
3278
+ return { repo, ctx, switches, destPath };
3279
+ }
3280
+
3281
+ test('the move happens without the copy, and the result names the refused copies in one line', async () => {
3282
+ const { repo, ctx, switches, destPath } = await conflictedDestination('s9-1');
3283
+ const handoff = {
3284
+ name: 'feat-s9dest',
3285
+ target: destPath,
3286
+ from: repo,
3287
+ branch: 'feat/s9dest',
3288
+ changes: { mode: 'all', paths: [] },
3289
+ };
3290
+ notifications.length = 0;
3291
+ const out = await mod.executeWorktreeWarp('feat-s9dest', ctx, { handoff });
3292
+ assert.notEqual(out.isError, true, `a refused copy is disclosed, never the answer: ${out.text}`);
3293
+ assert.equal(switches.length, 1, 'the human asked to move, so the session moves');
3294
+ const lines = String(out.text).split('\n').filter((line) => /^changes not copied:/.test(line));
3295
+ assert.equal(lines.length, 1, `ONE disclosure line, got ${JSON.stringify(out.text)}`);
3296
+ assert.match(lines[0], /conflict\.txt/, 'the line names the copies it could not carry');
3297
+ assert.match(lines[0], /nothing was overwritten/);
3298
+ assert.equal(out.details.copyRefused, lines[0], 'the details record the same one line');
3299
+ assert.deepEqual(out.details.copiedFiles, [], 'nothing was copied');
3300
+ // Nothing was copied and nothing was overwritten on either side.
3301
+ assert.equal(fs.readFileSync(path.join(destPath, 'conflict.txt'), 'utf8'), 'l1\nDEST-L2\n', 'the destination keeps its own version');
3302
+ assert.equal(git(destPath, ['status', '--porcelain']).trim(), '', 'the destination stays clean');
3303
+ assert.equal(fs.readFileSync(path.join(repo, 'conflict.txt'), 'utf8'), 'l1\nSRC-PENDING-L2\n', 'the source keeps its pending work');
3304
+ });
3305
+
3306
+ test('a queued handoff with a refused copy moves and tells the human once', async () => {
3307
+ const { ctx, switches, destPath } = await conflictedDestination('s9-2');
3308
+ clearPresence();
3309
+ const jobs = addJobs(ctx, [{ id: 'job-s9', status: 'running' }]);
3310
+ const asked = dirtyAsker('yes');
3311
+ notifications.length = 0;
3312
+ widgetPaints.length = 0;
3313
+ host.sent.length = 0;
3314
+ try {
3315
+ await commands.get('warp').handler('feat-s9dest', ctx);
3316
+ assert.equal(asked.length, 1, 'the pending-changes question is asked once, at request time');
3317
+ const record = busyLib.pendingWarpFor(pendingKey());
3318
+ assert.notEqual(record, null, 'the request is queued with its changes');
3319
+ assert.deepEqual(record.handoff.changes, { mode: 'all', paths: [] });
3320
+ assert.equal(switches.length, 0, 'nothing moves under the running job');
3321
+
3322
+ jobs.jobs[0].status = 'exited 0';
3323
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'dispatched');
3324
+ assert.equal(host.sent.length, 1);
3325
+ assert.equal(widgetState(ctx).lines, null, 'the row goes with the dispatch');
3326
+
3327
+ notifications.length = 0;
3328
+ await commands.get('warp').handler(host.sent[0][0].slice('/warp '.length), ctx);
3329
+ assert.equal(switches.length, 1, 'the queued handoff moves even though the copy was refused');
3330
+ assert.equal(
3331
+ fs.readFileSync(path.join(destPath, 'conflict.txt'), 'utf8'),
3332
+ 'l1\nDEST-L2\n',
3333
+ 'the destination keeps its own version',
3334
+ );
3335
+ assert.equal(git(destPath, ['status', '--porcelain']).trim(), '', 'nothing was written there');
3336
+ const errors = notifications.filter(([level]) => level === 'error');
3337
+ assert.deepEqual(errors, [], `no error is reported for a move that happened: ${JSON.stringify(notifications)}`);
3338
+ const told = notifications.filter(([level]) => level === 'info');
3339
+ assert.equal(told.length, 1, `told once: ${JSON.stringify(notifications)}`);
3340
+ assert.match(told[0][1], /^changes not copied: 1 file: conflict\.txt could not be carried/, 'one line, naming the file');
3341
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'the move clears the record');
3342
+ } finally {
3343
+ settlePending();
3344
+ }
3345
+ });
3346
+
3347
+ test('a partial copy still fails hard: the session stays, and the landed file is named', async (t) => {
3348
+ if (path.sep !== '/' || (typeof process.getuid === 'function' && process.getuid() === 0)) {
3349
+ return t.skip('needs POSIX permission bits and a non-root user');
3350
+ }
3351
+ const repo = makeRepo();
3352
+ const { ctx, switches } = movableCtx(repo);
3353
+ const made = await tools.get('worktree_create').execute('s9-3', { branch: 'feat/s9partial', odd: 's9partial' }, undefined, undefined, ctx);
3354
+ assert.notEqual(made.isError, true, resultText(made));
3355
+ const destPath = made.details.path;
3356
+ // An empty read-only directory in the destination: planning creates nothing,
3357
+ // so the second copy only fails once the writes begin — after the first one
3358
+ // already landed. That is real state, and it must stop the move.
3359
+ const blocked = path.join(destPath, 'blocked');
3360
+ fs.mkdirSync(blocked);
3361
+ fs.chmodSync(blocked, 0o555);
3362
+ try {
3363
+ fs.writeFileSync(path.join(repo, 'a-first.txt'), 'first\n');
3364
+ fs.mkdirSync(path.join(repo, 'blocked'));
3365
+ fs.writeFileSync(path.join(repo, 'blocked/second.txt'), 'second\n');
3366
+ const handoff = {
3367
+ name: 'feat-s9partial',
3368
+ target: destPath,
3369
+ from: repo,
3370
+ branch: 'feat/s9partial',
3371
+ changes: { mode: 'all', paths: [] },
3372
+ };
3373
+ const out = await mod.executeWorktreeWarp('feat-s9partial', ctx, { handoff });
3374
+ assert.equal(out.isError, true, `a copy that landed a file is real state, never a move to make anyway: ${out.text}`);
3375
+ assert.match(out.text, /1 of 2 files already copied/, `the failure counts what landed: ${out.text}`);
3376
+ assert.match(out.text, /a-first\.txt/, 'and names it');
3377
+ assert.equal(switches.length, 0, 'the session stays where it is');
3378
+ assert.equal(fs.readFileSync(path.join(destPath, 'a-first.txt'), 'utf8'), 'first\n', 'the landed file really landed');
3379
+ assert.equal(fs.existsSync(path.join(destPath, 'blocked/second.txt')), false, 'and the refused one did not');
3380
+ } finally {
3381
+ fs.chmodSync(blocked, 0o755);
3382
+ }
3383
+ });
3384
+ });