pi-odd-worktree 1.2.0 → 2.1.0

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.
@@ -1,16 +1,25 @@
1
1
  'use strict';
2
- // S4: a warp never lands while THIS session still has running agent tasks.
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.
3
4
  //
4
- // The counters come from Gentle Shell's published presence store (one header
5
- // per live session, validated and bounded by lib/worktree-session-guard.js), so
6
- // the tests publish a header for their own session id and drive both fronts:
7
- // the `worktree_warp` tool (which must queue NOTHING) and the `/warp` command
8
- // (which must refuse instead of switching).
5
+ // Two sources are driven here:
6
+ // - the agent-task counters, published in Gentle Shell's presence store (one
7
+ // header per live session, validated and bounded by
8
+ // lib/worktree-session-guard.js), which the tests write for their own id;
9
+ // - the `job_list` host tool, reached through `ctx.tools` + `ctx.executeTool`
10
+ // (the same seam `session_worktree_register` uses), whose text is one line
11
+ // per job: `job-1 · running · Probe · 3s · /tmp/…/job-1.log`.
9
12
  //
10
- // Background jobs are deliberately NOT asserted: gentle-shell keeps them in
11
- // memory and publishes no durable, session-attributable evidence, so no test
12
- // could prove that half.
13
- const { test, describe, before, after } = require('node:test');
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.
18
+ //
19
+ // A job whose status field is not running/queued is finished, a `job_list` that
20
+ // is missing, fails or answers in an unknown shape is UNKNOWN (never "no jobs"),
21
+ // and unknown blocks nothing.
22
+ const { test, describe, before, after, afterEach } = require('node:test');
14
23
  const assert = require('node:assert/strict');
15
24
  const crypto = require('node:crypto');
16
25
  const fs = require('node:fs');
@@ -18,6 +27,7 @@ const os = require('node:os');
18
27
  const path = require('node:path');
19
28
  const { spawnSync } = require('node:child_process');
20
29
  const { loadExtension } = require('./fixtures/load-extension.js');
30
+ const busyLib = require('../lib/worktree-warp-busy.js');
21
31
 
22
32
  const scratch = [];
23
33
  function track(dir) {
@@ -43,6 +53,20 @@ const AGENT_HOME = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-agent-h
43
53
  const PRESENCE = path.join(AGENT_HOME, 'gentle-agents', 'presence');
44
54
  const SESSION_ID = 'thread-1';
45
55
  const SESSION_HASH = crypto.createHash('sha256').update(SESSION_ID).digest('hex');
56
+ const INCARNATION = '11111111-2222-4333-8444-555555555555';
57
+
58
+ function pendingKey() {
59
+ return busyLib.pendingKeyFor({ sessionId: SESSION_ID });
60
+ }
61
+
62
+ function settlePending() {
63
+ busyLib.settlePendingWarp(pendingKey());
64
+ }
65
+
66
+ // The queue is ONE record per session, held in this process and shared by every
67
+ // test in this file: each test clears its own, and this backstop keeps an
68
+ // unrelated assertion failure from leaking a record into the tests after it.
69
+ afterEach(() => { settlePending(); });
46
70
 
47
71
  function git(cwd, args) {
48
72
  const out = spawnSync('git', args, { cwd, encoding: 'utf8' });
@@ -66,11 +90,10 @@ function makeRepo() {
66
90
  function publishSession({ running = 0, queued = 0, waiting = 0, heartbeat = Date.now(), label = 'Busy session' } = {}) {
67
91
  fs.mkdirSync(PRESENCE, { recursive: true, mode: 0o700 });
68
92
  fs.chmodSync(PRESENCE, 0o700);
69
- const incarnation = '11111111-2222-4333-8444-555555555555';
70
- fs.writeFileSync(path.join(PRESENCE, `${SESSION_HASH}.${incarnation}.header.json`), JSON.stringify({
93
+ fs.writeFileSync(path.join(PRESENCE, `${SESSION_HASH}.${INCARNATION}.header.json`), JSON.stringify({
71
94
  schema: 1,
72
95
  sessionHash: SESSION_HASH,
73
- incarnation,
96
+ incarnation: INCARNATION,
74
97
  label,
75
98
  heartbeat,
76
99
  generation: 1,
@@ -78,8 +101,8 @@ function publishSession({ running = 0, queued = 0, waiting = 0, heartbeat = Date
78
101
  digest: 'c'.repeat(64),
79
102
  unavailable: null,
80
103
  }), { mode: 0o600 });
81
- fs.writeFileSync(path.join(PRESENCE, `${SESSION_HASH}.${incarnation}.discovery.json`), JSON.stringify({
82
- schema: 1, sessionHash: SESSION_HASH, incarnation, generation: 1,
104
+ fs.writeFileSync(path.join(PRESENCE, `${SESSION_HASH}.${INCARNATION}.discovery.json`), JSON.stringify({
105
+ schema: 1, sessionHash: SESSION_HASH, incarnation: INCARNATION, generation: 1,
83
106
  metadata: { activation: 'd'.repeat(64), workspace: '/tmp/workspace', tasks: [], omitted: 0 },
84
107
  }), { mode: 0o600 });
85
108
  }
@@ -88,60 +111,132 @@ function clearPresence() {
88
111
  try { fs.rmSync(PRESENCE, { recursive: true, force: true }); } catch { /* absent is fine */ }
89
112
  }
90
113
 
114
+ // A bounded wait for a background poller/timer to become observable. The budgets
115
+ // are injected (env or pendingWarpTick), so nothing here waits on a real warp.
116
+ async function until(predicate, { timeoutMs = 2000, stepMs = 5 } = {}) {
117
+ const started = Date.now();
118
+ for (;;) {
119
+ if (predicate()) return true;
120
+ if (Date.now() - started > timeoutMs) return false;
121
+ await new Promise((resolve) => setTimeout(resolve, stepMs));
122
+ }
123
+ }
124
+
91
125
  const notifications = [];
92
126
  function makeCtx(cwd, extra = {}) {
93
- const switches = [];
94
127
  return {
95
- switches,
96
- ctx: {
97
- cwd,
98
- hasUI: true,
99
- mode: 'tui',
100
- sessionManager: { getSessionId: () => SESSION_ID },
101
- ui: {
102
- notify: (text, level) => { notifications.push([level, text]); },
103
- ...extra,
104
- },
105
- waitForIdle: async () => {},
106
- switchSession: async (file) => { switches.push(file); return { cancelled: false }; },
128
+ cwd,
129
+ hasUI: true,
130
+ mode: 'tui',
131
+ sessionManager: { getSessionId: () => SESSION_ID },
132
+ ui: {
133
+ notify: (text, level) => { notifications.push([level, text]); },
134
+ ...extra,
107
135
  },
136
+ waitForIdle: async () => {},
137
+ switchSession: async () => ({ cancelled: false }),
108
138
  };
109
139
  }
110
140
 
111
- function resultText(result) {
112
- return (result.content || []).map((part) => (part && part.text) || '').join('\n');
141
+ // This session's background jobs, as the host's `job_list` tool reports them:
142
+ // one line per job, `id · status · label · elapsed · log`. `mode` selects the
143
+ // other answers a host can give instead of a job list: `absent` (the tool is not
144
+ // registered), `error` (the call fails) and `unparsable` (a shape the parser does
145
+ // not know). Returns the mutable state the test drives.
146
+ function addJobs(ctx, jobs = [], mode = 'ok') {
147
+ const state = { jobs, mode, calls: 0 };
148
+ ctx.tools = mode === 'absent' ? [] : [{ name: 'job_list' }];
149
+ ctx.executeTool = async (name) => {
150
+ if (name !== 'job_list') return { isError: true, content: [{ type: 'text', text: `unknown tool ${name}` }] };
151
+ state.calls += 1;
152
+ if (state.mode === 'error') return { isError: true, content: [{ type: 'text', text: 'job_list failed' }] };
153
+ if (state.mode === 'unparsable') return { content: [{ type: 'text', text: 'something else entirely' }] };
154
+ const lines = state.jobs.map((job) => `${job.id} · ${job.status} · ${job.label || 'Probe de job'} · 3s · /tmp/gentle-jobs-1/${job.id}.log`);
155
+ return { content: [{ type: 'text', text: lines.length > 0 ? lines.join('\n') : 'No background jobs in this session.' }] };
156
+ };
157
+ return state;
158
+ }
159
+
160
+ // The minimal host session manager a warp needs: an empty session (no entries)
161
+ // changes PATH through `create` + `switchSession`, which is the cheapest real
162
+ // move a test can drive end to end.
163
+ function makeSessionHost(world) {
164
+ class FakeSession {
165
+ constructor(cwd, file, header) {
166
+ this.cwd = cwd;
167
+ this.file = file;
168
+ this.header = header;
169
+ }
170
+
171
+ getSessionFile() { return this.file; }
172
+
173
+ getSessionDir() { return world.sessionDir; }
174
+
175
+ getSessionId() { return SESSION_ID; }
176
+
177
+ getSessionName() { return ''; }
178
+
179
+ getHeader() { return this.header; }
180
+
181
+ getEntries() { return []; }
182
+
183
+ getLeafId() { return null; }
184
+
185
+ static create(cwd, dir) {
186
+ world.created += 1;
187
+ const file = path.join(dir || world.sessionDir, `created-${world.created}.jsonl`);
188
+ world.createdFiles.push(file);
189
+ return new FakeSession(cwd, file, { type: 'session', version: 3, id: `id-${world.created}`, timestamp: 1, cwd });
190
+ }
191
+
192
+ static forkFrom() {
193
+ throw new Error('an empty session must never fork');
194
+ }
195
+ }
196
+ return FakeSession;
113
197
  }
114
198
 
115
199
  let host;
116
200
  let commands;
117
201
  let tools;
202
+ let hooks;
118
203
  before(async () => {
119
204
  process.env.HERDR_BIN_PATH = NO_HERDR;
120
205
  process.env.GENTLE_WORKTREE_THREAD = SESSION_ID;
121
206
  process.env.PATH = `${HOOK_BIN}${path.delimiter}${savedEnv.PATH || ''}`;
122
207
  delete process.env.GENTLE_PI_AGENT_HOME;
123
208
  process.env.PI_CODING_AGENT_DIR = AGENT_HOME;
124
- // The command front's wait is bounded by this budget; tests never wait.
209
+ // The command front's bounded drain attempt: tests never wait for it.
125
210
  process.env.ODD_WORKTREE_WARP_BUSY_WAIT_MS = '0';
211
+ // The queue's lifetime and poll interval are injected per test; these defaults
212
+ // keep the poller quiet while a test drives `pendingWarpTick` itself.
213
+ process.env.ODD_WORKTREE_WARP_PENDING_MS = '600000';
214
+ process.env.ODD_WORKTREE_WARP_PENDING_POLL_MS = '60000';
126
215
  const sent = [];
127
216
  const loaded = await loadExtension({ sendUserMessage: (text, options) => { sent.push([text, options]); } });
128
217
  host = loaded.host;
129
218
  host.sent = sent;
130
219
  commands = loaded.commands;
131
220
  tools = loaded.tools;
221
+ hooks = loaded.hooks;
132
222
  });
133
223
 
134
- describe('lib/worktree-warp-busy.js', () => {
135
- const busyLib = require('../lib/worktree-warp-busy.js');
224
+ function resultText(result) {
225
+ return (result.content || []).map((part) => (part && part.text) || '').join('\n');
226
+ }
136
227
 
228
+ // ---------------------------------------------------------------------------
229
+ // The module itself: counters, texts and the pending queue (injected clock).
230
+ // ---------------------------------------------------------------------------
231
+ describe('lib/worktree-warp-busy.js', () => {
137
232
  test('reads only this session’s own counters', async () => {
138
233
  const home = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-lib-')));
139
234
  const dir = path.join(home, 'gentle-agents', 'presence');
140
235
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
141
236
  const mine = crypto.createHash('sha256').update('session-a').digest('hex');
142
237
  const other = crypto.createHash('sha256').update('session-b').digest('hex');
143
- const write = (hash, running) => fs.writeFileSync(path.join(dir, `${hash}.11111111-2222-4333-8444-555555555555.header.json`), JSON.stringify({
144
- schema: 1, sessionHash: hash, incarnation: '11111111-2222-4333-8444-555555555555',
238
+ const write = (hash, running) => fs.writeFileSync(path.join(dir, `${hash}.${INCARNATION}.header.json`), JSON.stringify({
239
+ schema: 1, sessionHash: hash, incarnation: INCARNATION,
145
240
  label: 'L', heartbeat: 1000, generation: 1,
146
241
  counts: { running, queued: 0, waiting: 0, finished: 0 },
147
242
  digest: 'e'.repeat(64), unavailable: null,
@@ -167,8 +262,8 @@ describe('lib/worktree-warp-busy.js', () => {
167
262
  const dir = path.join(home, 'gentle-agents', 'presence');
168
263
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
169
264
  const mine = crypto.createHash('sha256').update('session-a').digest('hex');
170
- fs.writeFileSync(path.join(dir, `${mine}.11111111-2222-4333-8444-555555555555.header.json`), JSON.stringify({
171
- schema: 1, sessionHash: mine, incarnation: '11111111-2222-4333-8444-555555555555',
265
+ fs.writeFileSync(path.join(dir, `${mine}.${INCARNATION}.header.json`), JSON.stringify({
266
+ schema: 1, sessionHash: mine, incarnation: INCARNATION,
172
267
  label: 'L', heartbeat: 1000, generation: 1,
173
268
  counts: { running: 3, queued: 0, waiting: 0, finished: 0 },
174
269
  digest: 'e'.repeat(64), unavailable: null,
@@ -206,32 +301,252 @@ describe('lib/worktree-warp-busy.js', () => {
206
301
  assert.equal(never.waited, 3000);
207
302
  });
208
303
 
209
- test('the refusal text names agent tasks and admits jobs are invisible', () => {
210
- const text = busyLib.busyText({ running: 2, queued: 1, label: 'Worker' });
211
- assert.match(text, /2 running and 1 queued agent task\(s\) on "Worker"/);
212
- assert.match(text, /background jobs are not visible here/);
304
+ test('the queue texts name both workloads and no longer disclaim jobs', () => {
305
+ 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',
308
+ );
309
+ 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',
312
+ );
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);
316
+ assert.equal(/not observable/.test(busyLib.expiredText('feat-x', 30)), false);
317
+
318
+ assert.equal(busyLib.jobsUnknownText({ jobs: { status: 'ok', active: 0 } }), '', 'a readable job list needs no caveat');
319
+ assert.match(
320
+ busyLib.jobsUnknownText({ jobs: { status: 'unavailable' } }),
321
+ /^the background-job state is unknown \(job_list is not available on this host\), so confirm any bash_background or monitor job finished$/,
322
+ );
323
+ assert.match(busyLib.jobsUnknownText({ jobs: { status: 'error' } }), /unknown \(job_list failed\)/);
324
+ assert.match(busyLib.jobsUnknownText({ jobs: { status: 'unparsable' } }), /unknown \(job_list answered in an unexpected shape\)/);
325
+
326
+ assert.match(busyLib.expiredText('feat-x', 30), /the pending warp to feat-x expired after 30 min with nothing moved/);
327
+ assert.match(busyLib.expiredText('feat-x', 30), /agent tasks and background jobs finish/);
328
+ assert.match(busyLib.expiredText('feat-x', 30, { jobs: { status: 'error' } }), /\(the background-job state is unknown \(job_list failed\)/);
329
+ assert.match(
330
+ 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$/,
332
+ );
333
+ });
334
+
335
+ test('a job is active only while its status field says running or queued', () => {
336
+ const line = (status) => `job-1 · ${status} · Probe de job · 3s · /tmp/gentle-jobs-1/job-1.log`;
337
+ assert.deepEqual(busyLib.parseJobList(line('running')), { status: 'ok', active: 1, count: 1 });
338
+ assert.deepEqual(busyLib.parseJobList(line('queued')), { status: 'ok', active: 1, count: 1 });
339
+ assert.deepEqual(busyLib.parseJobList(`m-1 · monitor running · Watch · 4s · /tmp/gentle-jobs-1/m-1.log`), { status: 'ok', active: 1, count: 1 });
340
+ for (const finished of ['exited 0', 'failed 1', 'stopped', 'monitor stopped']) {
341
+ assert.deepEqual(busyLib.parseJobList(line(finished)), { status: 'ok', active: 0, count: 1 }, `${finished} is finished, never active`);
342
+ }
343
+ assert.equal(busyLib.parseJobList(`${line('running')}\n${line('exited 0')}`).active, 1, 'only the running row counts');
344
+ assert.deepEqual(busyLib.parseJobList('No background jobs in this session.'), { status: 'ok', active: 0, count: 0 });
345
+ assert.deepEqual(busyLib.parseJobList(''), { status: 'ok', active: 0, count: 0 });
346
+ assert.equal(busyLib.parseJobList('job-1 is doing something').status, 'unparsable', 'an unknown shape is not an empty list');
347
+ });
348
+
349
+ test('sessionActivity merges this session’s jobs through the host tool', async () => {
350
+ const home = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-jobs-')));
351
+ const plain = makeCtx(os.tmpdir());
352
+ const ctx = makeCtx(os.tmpdir());
353
+ const jobs = addJobs(ctx, [{ id: 'job-1', status: 'running' }]);
354
+
355
+ const running = await busyLib.sessionActivity({ sessionId: SESSION_ID, env: { PI_CODING_AGENT_DIR: home }, host: ctx });
356
+ assert.equal(running.jobs.status, 'ok');
357
+ assert.equal(running.jobs.active, 1);
358
+ assert.equal(running.jobsUnknown, false);
359
+ assert.equal(running.busy, true, 'a running job alone makes the session busy');
360
+ assert.equal(jobs.calls, 1);
361
+
362
+ jobs.jobs[0].status = 'exited 0';
363
+ const done = await busyLib.sessionActivity({ sessionId: SESSION_ID, env: { PI_CODING_AGENT_DIR: home }, host: ctx });
364
+ assert.equal(done.jobs.active, 0);
365
+ assert.equal(done.busy, false, 'a finished job is not work');
366
+
367
+ const noTool = await busyLib.sessionActivity({ sessionId: SESSION_ID, env: { PI_CODING_AGENT_DIR: home }, host: plain });
368
+ assert.equal(noTool.jobs.status, 'unavailable', 'no host seam is unknown, never "no jobs"');
369
+ assert.equal(noTool.jobsUnknown, true);
370
+ assert.equal(noTool.busy, false, 'an unknown job state blocks nothing');
371
+ });
372
+
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);
382
+
383
+ assert.equal(busyLib.DEFAULT_PENDING_MS, 30 * 60 * 1000);
384
+ assert.equal(busyLib.pendingBudgetMs({}), 30 * 60 * 1000);
385
+ assert.equal(busyLib.pendingBudgetMs({ ODD_WORKTREE_WARP_PENDING_MS: '1500' }), 1500);
386
+ assert.equal(busyLib.pendingBudgetMs({ ODD_WORKTREE_WARP_PENDING_MS: 'nope' }), 30 * 60 * 1000);
387
+ assert.equal(busyLib.pendingBudgetMs({ ODD_WORKTREE_WARP_PENDING_MS: '999999999999' }), busyLib.MAX_PENDING_MS);
388
+ assert.equal(busyLib.pendingPollMs({}), busyLib.DEFAULT_PENDING_POLL_MS);
389
+ assert.equal(busyLib.pendingPollMs({ ODD_WORKTREE_WARP_PENDING_POLL_MS: '999999999999' }), busyLib.MAX_PENDING_POLL_MS);
390
+ });
391
+
392
+ test('the queue keys on the session id, then on the checkout root', () => {
393
+ assert.equal(busyLib.pendingKeyFor({ sessionId: 's-1', root: '/repo' }), 'session:s-1');
394
+ assert.equal(busyLib.pendingKeyFor({ sessionId: '', root: '/repo' }), 'root:/repo');
395
+ assert.equal(busyLib.pendingKeyFor({}), null);
396
+ assert.equal(busyLib.pendingKeyFor(null), null);
397
+ });
398
+
399
+ test('sameWarpHandoff matches only the same move and change selection', () => {
400
+ const base = { name: 'feat-x', target: '/t', from: '/f', branch: 'feat/x', changes: { mode: 'none', paths: [] } };
401
+ assert.equal(busyLib.sameWarpHandoff(base, { ...base }), true);
402
+ assert.equal(busyLib.sameWarpHandoff(base, { ...base, changes: { mode: 'all', paths: [] } }), false);
403
+ assert.equal(busyLib.sameWarpHandoff(base, { ...base, changes: { mode: 'paths', paths: ['a'] } }), false);
404
+ assert.equal(busyLib.sameWarpHandoff(base, { ...base, target: '/other' }), false);
405
+ assert.equal(busyLib.sameWarpHandoff(base, null), false);
406
+ });
407
+
408
+ test('the pending warp waits for the counters, then dispatches the same handoff once', async () => {
409
+ const key = 'session:lib-queue';
410
+ const clock = { now: 1000 };
411
+ const dispatched = [];
412
+ const handoff = { name: 'feat-q', target: '/t', from: '/f', branch: 'feat/q', changes: { mode: 'none', paths: [] } };
413
+ let activity = { busy: true, running: 2, queued: 0 };
414
+ const queued = busyLib.queuePendingWarp({
415
+ key,
416
+ name: 'feat-q',
417
+ token: '@token',
418
+ handoff,
419
+ now: () => clock.now,
420
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '10000', ODD_WORKTREE_WARP_PENDING_POLL_MS: '1000' },
421
+ timers: { set: () => null, clear: () => {} },
422
+ read: async () => activity,
423
+ dispatch: (queuedHandoff, token) => { dispatched.push([queuedHandoff, token]); return { ok: true }; },
424
+ });
425
+ try {
426
+ assert.equal(queued.ok, true);
427
+ assert.equal(busyLib.pendingWarpFor(key).name, 'feat-q');
428
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'waiting');
429
+ assert.deepEqual(dispatched, [], 'a busy session dispatches nothing');
430
+
431
+ activity = { busy: false, running: 0, queued: 0 };
432
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'dispatched');
433
+ assert.deepEqual(dispatched, [[handoff, '@token']], 'the SAME validated handoff is re-dispatched');
434
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'waiting');
435
+ assert.equal(dispatched.length, 1, 'one queued warp is never dispatched twice');
436
+ assert.equal(busyLib.pendingWarpFor(key).dispatching, true);
437
+ } finally {
438
+ assert.equal(busyLib.settlePendingWarp(key).name, 'feat-q');
439
+ assert.equal(busyLib.pendingWarpFor(key), null);
440
+ }
441
+ });
442
+
443
+ test('a second queue is refused and leaves the pending warp untouched', () => {
444
+ const key = 'session:lib-second';
445
+ const first = { name: 'feat-first', target: '/t', from: '/f', branch: 'feat/first', changes: { mode: 'none', paths: [] } };
446
+ const second = { name: 'feat-second', target: '/t2', from: '/f', branch: 'feat/second', changes: { mode: 'none', paths: [] } };
447
+ const deps = {
448
+ now: () => 1000,
449
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '10000' },
450
+ timers: { set: () => null, clear: () => {} },
451
+ read: async () => ({ busy: true }),
452
+ dispatch: () => ({ ok: true }),
453
+ };
454
+ try {
455
+ assert.equal(busyLib.queuePendingWarp({ key, name: 'feat-first', token: '@one', handoff: first, ...deps }).ok, true);
456
+ const refused = busyLib.queuePendingWarp({ key, name: 'feat-second', token: '@two', handoff: second, ...deps });
457
+ assert.equal(refused.ok, false);
458
+ assert.equal(refused.reason, 'pending');
459
+ assert.equal(refused.pending.name, 'feat-first');
460
+ assert.deepEqual(busyLib.pendingWarpFor(key).handoff, first);
461
+ } finally {
462
+ busyLib.settlePendingWarp(key);
463
+ }
464
+ });
465
+
466
+ test('the pending warp expires with a notice that nothing moved, and clears', async () => {
467
+ const key = 'session:lib-expiry';
468
+ const clock = { now: 1000 };
469
+ const notified = [];
470
+ const deps = {
471
+ now: () => clock.now,
472
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '1000' },
473
+ timers: { set: () => null, clear: () => {} },
474
+ read: async () => ({ busy: true, running: 1 }),
475
+ dispatch: () => { throw new Error('an expired warp must not dispatch'); },
476
+ notify: (text, level) => { notified.push([level, text]); },
477
+ };
478
+ const handoff = { name: 'feat-e', target: '/t', from: '/f', branch: 'feat/e', changes: { mode: 'none', paths: [] } };
479
+ assert.equal(busyLib.queuePendingWarp({ key, name: 'feat-e', token: '@e', handoff, ...deps }).ok, true);
480
+ clock.now += 1000;
481
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'expired');
482
+ assert.equal(busyLib.pendingWarpFor(key), null, 'an expired request is cleared, so a later warp is accepted');
483
+ assert.equal(notified.length, 1);
484
+ assert.equal(notified[0][0], 'error');
485
+ assert.match(notified[0][1], /the pending warp to feat-e expired after 1 min with nothing moved/);
486
+ });
487
+
488
+ test('a refused re-dispatch stays queued instead of throwing', async () => {
489
+ const key = 'session:lib-refused';
490
+ const deps = {
491
+ now: () => 1000,
492
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '10000' },
493
+ timers: { set: () => null, clear: () => {} },
494
+ read: async () => ({ busy: false }),
495
+ dispatch: () => ({ ok: false, error: 'the host cannot dispatch the warp command here' }),
496
+ };
497
+ const handoff = { name: 'feat-r', target: '/t', from: '/f', branch: 'feat/r', changes: { mode: 'none', paths: [] } };
498
+ try {
499
+ assert.equal(busyLib.queuePendingWarp({ key, name: 'feat-r', token: '@r', handoff, ...deps }).ok, true);
500
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'waiting');
501
+ const record = busyLib.pendingWarpFor(key);
502
+ assert.notEqual(record, null);
503
+ assert.equal(record.dispatching, false, 'a refused dispatch is retried, not lost');
504
+ // Resuming after a refused dispatch re-arms the poller for the same key.
505
+ assert.equal(busyLib.resumePendingWarp(key), true);
506
+ assert.equal(busyLib.pendingWarpFor(key).dispatching, false);
507
+ } finally {
508
+ busyLib.settlePendingWarp(key);
509
+ }
213
510
  });
214
511
  });
215
512
 
216
- describe('warp fronts while this session is busy', () => {
217
- test('the tool queues nothing while an agent task is running', async () => {
513
+ // ---------------------------------------------------------------------------
514
+ // The tool front: it QUEUES the handoff while this session is busy.
515
+ // ---------------------------------------------------------------------------
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 () => {
218
518
  const repo = makeRepo();
219
- const { ctx } = makeCtx(repo);
519
+ const ctx = makeCtx(repo);
220
520
  const created = await tools.get('worktree_create').execute('busy-1', { branch: 'feat/busy', changes: 'none' }, undefined, undefined, ctx);
221
521
  assert.notEqual(created.isError, true, resultText(created));
222
522
 
223
523
  publishSession({ running: 1 });
524
+ addJobs(ctx, [], 'absent');
224
525
  host.sent.length = 0;
225
- const refused = await tools.get('worktree_warp').execute('busy-2', { name: 'feat-busy' }, undefined, undefined, ctx);
226
- assert.equal(refused.isError, true);
227
- assert.match(resultText(refused), /^worktree warp: this session still has 1 running agent task\(s\)/);
228
- assert.equal(host.sent.length, 0, 'nothing may be queued while a task runs');
229
- assert.equal(refused.details.busy, true);
526
+ 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();
230
545
  });
231
546
 
232
- test('the tool queues the handoff once the counters drain', async () => {
547
+ test('an idle session keeps the byte-identical queued wording', async () => {
233
548
  const repo = makeRepo();
234
- const { ctx } = makeCtx(repo);
549
+ const ctx = makeCtx(repo);
235
550
  const created = await tools.get('worktree_create').execute('busy-3', { branch: 'feat/free', changes: 'none' }, undefined, undefined, ctx);
236
551
  assert.notEqual(created.isError, true, resultText(created));
237
552
 
@@ -239,49 +554,422 @@ describe('warp fronts while this session is busy', () => {
239
554
  host.sent.length = 0;
240
555
  const queued = await tools.get('worktree_warp').execute('busy-4', { name: 'feat-free' }, undefined, undefined, ctx);
241
556
  assert.notEqual(queued.isError, true, resultText(queued));
242
- assert.match(resultText(queued), /^worktree warp: handoff 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);
563
+ settlePending();
564
+ });
565
+
566
+ test('queued counters queue the warp; waiting and finished counters do not', async () => {
567
+ 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);
570
+ assert.notEqual(created.isError, true, resultText(created));
571
+
572
+ 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.
580
+ settlePending();
581
+
582
+ 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/);
243
587
  assert.equal(host.sent.length, 1);
588
+ settlePending();
244
589
  });
245
590
 
246
- test('the command refuses and never switches while an agent task is running', async () => {
591
+ test('a running job queues the warp, and a same-turn second call is refused', async () => {
247
592
  const repo = makeRepo();
248
- const { ctx, switches } = makeCtx(repo);
249
- const created = await tools.get('worktree_create').execute('busy-5', { branch: 'feat/busy-cmd', changes: 'none' }, undefined, undefined, ctx);
593
+ const ctx = makeCtx(repo);
594
+ const created = await tools.get('worktree_create').execute('busy-j1', { branch: 'feat/jobs', changes: 'none' }, undefined, undefined, ctx);
595
+ assert.notEqual(created.isError, true, resultText(created));
596
+
597
+ const jobs = addJobs(ctx, [{ id: 'job-1', status: 'running', label: 'Probe de job' }]);
598
+ 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);
602
+ 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);
610
+ 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$/,
613
+ );
614
+ assert.equal(host.sent.length, 1, 'the refused second warp queues nothing');
615
+ settlePending();
616
+ });
617
+
618
+ test('a running agent task and a running job are both named', async () => {
619
+ const repo = makeRepo();
620
+ const ctx = makeCtx(repo);
621
+ const created = await tools.get('worktree_create').execute('busy-j4', { branch: 'feat/both', changes: 'none' }, undefined, undefined, ctx);
250
622
  assert.notEqual(created.isError, true, resultText(created));
251
623
 
624
+ publishSession({ running: 2 });
625
+ 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);
634
+ // 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');
638
+ settlePending();
639
+ });
640
+
641
+ test('an unavailable, failing or unparsable job list blocks nothing and is disclosed only then', async () => {
642
+ const repo = makeRepo();
643
+ const ctx = makeCtx(repo);
644
+ const created = await tools.get('worktree_create').execute('busy-j6', { branch: 'feat/unknown', changes: 'none' }, undefined, undefined, ctx);
645
+ assert.notEqual(created.isError, true, resultText(created));
646
+ publishSession({ running: 1 });
647
+
648
+ // No host seam at all: the plain ctx has neither `tools` nor `executeTool`.
649
+ 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');
655
+ settlePending();
656
+
657
+ for (const [mode, reason] of [['error', 'job_list failed'], ['unparsable', 'job_list answered in an unexpected shape']]) {
658
+ 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`);
664
+ settlePending();
665
+ }
666
+
667
+ // An unknown job list with NO agent task either: the idle wording stands and
668
+ // nothing claims a queue it did not create.
669
+ 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();
677
+ });
678
+
679
+ test('a queued (busy) tool warp mutates no checkout and no registry row', async () => {
680
+ const repo = makeRepo();
681
+ const ctx = makeCtx(repo);
682
+ const created = await tools.get('worktree_create').execute('busy-8', { branch: 'feat/intact', changes: 'none' }, undefined, undefined, ctx);
683
+ assert.notEqual(created.isError, true, resultText(created));
684
+
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();
702
+ });
703
+ });
704
+
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 () => {
710
+ 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);
719
+ assert.notEqual(created.isError, true, resultText(created));
720
+
721
+ publishSession({ running: 2 });
722
+ notifications.length = 0;
723
+ host.sent.length = 0;
724
+ await commands.get('warp').handler('feat-cmd', ctx);
725
+
726
+ assert.equal(switches.length, 0, 'the session must not move under running tasks');
727
+ 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');
737
+ settlePending();
738
+ });
739
+
740
+ test('the pending warp re-dispatches the same handoff once the counters drain, and the move lands', async () => {
741
+ const repo = makeRepo();
742
+ const world = { sessionDir: track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-sessions-'))), created: 0, createdFiles: [] };
743
+ const SM = makeSessionHost(world);
744
+ const switches = [];
745
+ const ctx = makeCtx(repo);
746
+ ctx.sessionManager = Object.assign(new SM(null, null, null), { getSessionId: () => SESSION_ID });
747
+ ctx.sessionManager.constructor = SM;
748
+ 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);
750
+ assert.notEqual(created.isError, true, resultText(created));
751
+
752
+ publishSession({ running: 1, queued: 1 });
753
+ host.sent.length = 0;
754
+ await commands.get('warp').handler('feat-drain', ctx);
755
+ assert.equal(switches.length, 0);
756
+ assert.equal(host.sent.length, 0);
757
+
758
+ // The counters drain: the poller re-dispatches the SAME validated handoff.
759
+ publishSession({ running: 0, queued: 0 });
760
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'dispatched');
761
+ assert.equal(host.sent.length, 1, 'the queued warp re-dispatches itself');
762
+ const [message, options] = host.sent[0];
763
+ assert.deepEqual(options, { expandPromptTemplates: true });
764
+ assert.ok(message.startsWith('/warp @'), `the queued command is /warp (${message})`);
765
+
766
+ // That exact handoff is not a second warp: it performs the queued move.
767
+ notifications.length = 0;
768
+ await commands.get('warp').handler(message.slice('/warp '.length), ctx);
769
+ assert.deepEqual(notifications, [], 'a real move notifies nothing');
770
+ assert.equal(switches.length, 1, 'the queued move landed once the counters drained');
771
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'a move clears the pending record');
772
+
773
+ // A later warp is accepted again.
774
+ 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);
778
+ settlePending();
779
+ });
780
+
781
+ test('a second warp is refused while one is pending, on both fronts', async () => {
782
+ const repo = makeRepo();
783
+ const ctx = makeCtx(repo);
784
+ const first = await tools.get('worktree_create').execute('busy-13', { branch: 'feat/one', changes: 'none' }, undefined, undefined, ctx);
785
+ 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);
787
+ assert.notEqual(second.isError, true, resultText(second));
788
+
252
789
  publishSession({ running: 2 });
253
790
  notifications.length = 0;
254
- await commands.get('warp').handler('feat-busy-cmd', ctx);
255
- assert.equal(switches.length, 0, 'the session must not move under a running task');
791
+ await commands.get('warp').handler('feat-one', ctx);
792
+ const queued = busyLib.pendingWarpFor(pendingKey());
793
+ assert.notEqual(queued, null);
794
+
795
+ // The TOOL refuses and queues nothing at all.
796
+ 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
+ const switches = [];
807
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
808
+ notifications.length = 0;
809
+ await commands.get('warp').handler('feat-two', ctx);
810
+ assert.equal(switches.length, 0);
256
811
  assert.equal(notifications.length, 1);
257
812
  assert.equal(notifications[0][0], 'error');
258
- assert.match(notifications[0][1], /^worktree warp: this session still has 2 running agent task\(s\)/);
813
+ assert.match(notifications[0][1], /^worktree warp: a warp to feat-one is already pending for this session/);
814
+
815
+ // The pending request is untouched by both refusals.
816
+ const after = busyLib.pendingWarpFor(pendingKey());
817
+ assert.equal(after.name, 'feat-one');
818
+ assert.equal(after.queuedAt, queued.queuedAt);
819
+ settlePending();
259
820
  });
260
821
 
261
- test('an unavailable presence store does not block the command', async () => {
822
+ test('an expired pending warp notices that nothing moved and clears for a later warp', async () => {
262
823
  const repo = makeRepo();
263
- const { ctx } = makeCtx(repo);
264
- const created = await tools.get('worktree_create').execute('busy-6', { branch: 'feat/no-store', changes: 'none' }, undefined, undefined, ctx);
824
+ const ctx = makeCtx(repo);
825
+ const created = await tools.get('worktree_create').execute('busy-16', { branch: 'feat/expire', changes: 'none' }, undefined, undefined, ctx);
265
826
  assert.notEqual(created.isError, true, resultText(created));
266
827
 
828
+ publishSession({ running: 1 });
829
+ notifications.length = 0;
830
+ const previousBudget = process.env.ODD_WORKTREE_WARP_PENDING_MS;
831
+ process.env.ODD_WORKTREE_WARP_PENDING_MS = '1';
832
+ try {
833
+ await commands.get('warp').handler('feat-expire', ctx);
834
+ } finally {
835
+ process.env.ODD_WORKTREE_WARP_PENDING_MS = previousBudget;
836
+ }
837
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null);
838
+
839
+ const expired = await until(() => notifications.some(([, text]) => /expired .* with nothing moved/.test(String(text))));
840
+ assert.equal(expired, true, `the queue noticed nothing: ${JSON.stringify(notifications)}`);
841
+ const [, text] = notifications.find(([, entry]) => /expired .* with nothing moved/.test(String(entry)));
842
+ assert.match(text, /^worktree warp: the pending warp to feat-expire expired after 1 min with nothing moved/);
843
+ assert.match(text, /agent tasks and background jobs finish/);
844
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'an expired queue is cleared');
845
+
846
+ 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);
850
+ settlePending();
851
+ });
852
+
853
+ test('a running background job keeps the move pending until the job reports exited', async () => {
854
+ const repo = makeRepo();
855
+ const world = { sessionDir: track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-sessions-'))), created: 0, createdFiles: [] };
856
+ const SM = makeSessionHost(world);
857
+ const switches = [];
858
+ const ctx = makeCtx(repo);
859
+ ctx.sessionManager = Object.assign(new SM(null, null, null), { getSessionId: () => SESSION_ID });
860
+ ctx.sessionManager.constructor = SM;
861
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
862
+ 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);
864
+ assert.notEqual(created.isError, true, resultText(created));
865
+ // No agent task at all: the JOB is the only thing standing in the way.
267
866
  clearPresence();
268
867
  notifications.length = 0;
269
- await commands.get('warp').handler('feat-no-store', ctx);
270
- // Whatever this minimal host context can or cannot do later, the busy
271
- // refusal must not appear: without evidence nothing is claimed to be busy.
272
- const busyRefusals = notifications.filter(([, text]) => /still has .* agent task/.test(String(text)));
273
- assert.deepEqual(busyRefusals, [], `no busy refusal without evidence: ${JSON.stringify(notifications)}`);
868
+ host.sent.length = 0;
869
+ await commands.get('warp').handler('feat-jobwait', ctx);
870
+
871
+ assert.equal(switches.length, 0, 'the session must not move while a job is running');
872
+ 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/);
876
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'a running job keeps the request pending');
877
+
878
+ // Still running: the poller waits, and nothing is re-dispatched.
879
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'waiting');
880
+ assert.equal(host.sent.length, 0);
881
+ assert.equal(switches.length, 0);
882
+
883
+ // The job exits: the poller re-dispatches the SAME handoff, and it lands.
884
+ jobs.jobs[0].status = 'exited 0';
885
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'dispatched');
886
+ assert.equal(host.sent.length, 1, 'the queued warp re-dispatches itself once the job is finished');
887
+ const [message, options] = host.sent[0];
888
+ assert.deepEqual(options, { expandPromptTemplates: true });
889
+ assert.ok(message.startsWith('/warp @'), `the queued command is /warp (${message})`);
890
+ await commands.get('warp').handler(message.slice('/warp '.length), ctx);
891
+ assert.equal(switches.length, 1, 'the move lands only after the job finished');
892
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'a move clears the pending record');
893
+ });
894
+
895
+ test('a refused queued warp clears the record, so a later warp is accepted', async () => {
896
+ const repo = makeRepo();
897
+ const ctx = makeCtx(repo);
898
+ const created = await tools.get('worktree_create').execute('busy-r1', { branch: 'feat/refused', changes: 'none' }, undefined, undefined, ctx);
899
+ assert.notEqual(created.isError, true, resultText(created));
900
+
901
+ // The tool queues the request while a job runs, so it is pending.
902
+ clearPresence();
903
+ const jobs = addJobs(ctx, [{ id: 'job-3', status: 'running' }]);
904
+ 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];
909
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null);
910
+
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.
913
+ 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');
916
+ notifications.length = 0;
917
+ await commands.get('warp').handler(token.slice('/warp '.length), ctx);
918
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'a refused queued warp is cleared');
919
+
920
+ // A later warp is accepted again, not blocked by a dead record.
921
+ fs.writeFileSync(registryPath, JSON.stringify({ version: 1, worktrees: [] }));
922
+ 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);
926
+ settlePending();
927
+ });
928
+
929
+ test('a handoff token for another checkout is refused while one is pending', async () => {
930
+ const repo = makeRepo();
931
+ const ctx = makeCtx(repo);
932
+ const first = await tools.get('worktree_create').execute('busy-18', { branch: 'feat/held', changes: 'none' }, undefined, undefined, ctx);
933
+ 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);
935
+ assert.notEqual(second.isError, true, resultText(second));
936
+
937
+ // Queue a handoff for feat-other first (idle front), then make the session
938
+ // busy and let the command hold the request.
939
+ 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
+ publishSession({ running: 1 });
946
+ await commands.get('warp').handler(token.slice('/warp '.length), ctx);
947
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the handoff is now pending');
948
+
949
+ // A DIFFERENT handoff (feat-held) is a second warp.
950
+ const heldHandoff = `@${Buffer.from(JSON.stringify({
951
+ v: 1,
952
+ name: 'feat-held',
953
+ target: path.join(repo, '..', 'other-checkout'),
954
+ from: repo,
955
+ branch: 'feat/held',
956
+ }), 'utf8').toString('base64url')}`;
957
+ notifications.length = 0;
958
+ const switches = [];
959
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
960
+ await commands.get('warp').handler(heldHandoff, ctx);
961
+ assert.equal(switches.length, 0);
962
+ assert.equal(notifications.length, 1);
963
+ assert.match(notifications[0][1], /^worktree warp: a warp to feat-other is already pending for this session/);
964
+ settlePending();
274
965
  });
275
966
  });
276
967
 
277
968
  // ---------------------------------------------------------------------------
278
- // S4 boundaries: what the guard must NOT block, every entry path, and the
279
- // surfaces that must keep working while this session reports running work.
969
+ // S4 boundaries: what the queue must NOT block, every entry path, and the
970
+ // surfaces that keep working while this session reports running work.
280
971
  // ---------------------------------------------------------------------------
281
- describe('S4 boundaries: negative cases, every front, unaffected surfaces', () => {
282
- const busyLib = require('../lib/worktree-warp-busy.js');
283
- const INCARNATION = '11111111-2222-4333-8444-555555555555';
284
-
972
+ describe('boundaries: negative cases, every front, unaffected surfaces', () => {
285
973
  function writeOtherSession(counts) {
286
974
  fs.mkdirSync(PRESENCE, { recursive: true, mode: 0o700 });
287
975
  fs.chmodSync(PRESENCE, 0o700);
@@ -294,114 +982,76 @@ describe('S4 boundaries: negative cases, every front, unaffected surfaces', () =
294
982
  }), { mode: 0o600 });
295
983
  }
296
984
 
297
- test('the tool queues its handoff when the presence store is absent', async () => {
985
+ test('the tool queues normally when the presence store is absent', async () => {
298
986
  const repo = makeRepo();
299
- const { ctx } = makeCtx(repo);
300
- const created = await tools.get('worktree_create').execute('busy-7', { branch: 'feat/nostore', changes: 'none' }, undefined, undefined, ctx);
987
+ const ctx = makeCtx(repo);
988
+ const created = await tools.get('worktree_create').execute('busy-21', { branch: 'feat/nostore', changes: 'none' }, undefined, undefined, ctx);
301
989
  assert.notEqual(created.isError, true, resultText(created));
302
990
  clearPresence();
303
991
  host.sent.length = 0;
304
- const queued = await tools.get('worktree_warp').execute('busy-8', { name: 'feat-nostore' }, undefined, undefined, ctx);
992
+ const queued = await tools.get('worktree_warp').execute('busy-22', { name: 'feat-nostore' }, undefined, undefined, ctx);
305
993
  assert.notEqual(queued.isError, true, resultText(queued));
306
- assert.match(resultText(queued), /^worktree warp: handoff queued/);
307
- assert.equal(host.sent.length, 1, 'an absent store blocks nothing');
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();
308
997
  });
309
998
 
310
- test('a stale heartbeat and an unreadable record never block the tool', async () => {
999
+ test('a stale heartbeat and an unreadable record are no evidence of work', async () => {
311
1000
  const repo = makeRepo();
312
- const { ctx } = makeCtx(repo);
313
- const created = await tools.get('worktree_create').execute('busy-9', { branch: 'feat/stale', changes: 'none' }, undefined, undefined, ctx);
1001
+ const ctx = makeCtx(repo);
1002
+ const created = await tools.get('worktree_create').execute('busy-23', { branch: 'feat/stale', changes: 'none' }, undefined, undefined, ctx);
314
1003
  assert.notEqual(created.isError, true, resultText(created));
315
1004
 
316
1005
  publishSession({ running: 3, heartbeat: Date.now() - 600000 });
317
1006
  host.sent.length = 0;
318
- const stale = await tools.get('worktree_warp').execute('busy-10', { name: 'feat-stale' }, undefined, undefined, ctx);
1007
+ const stale = await tools.get('worktree_warp').execute('busy-24', { name: 'feat-stale' }, undefined, undefined, ctx);
319
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/);
320
1010
  assert.equal(host.sent.length, 1);
321
1011
 
322
1012
  publishSession({ running: 3 });
323
1013
  fs.chmodSync(PRESENCE, 0o755);
324
1014
  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();
325
1018
  host.sent.length = 0;
326
- const unreadable = await tools.get('worktree_warp').execute('busy-11', { name: 'feat-stale' }, undefined, undefined, ctx);
1019
+ const unreadable = await tools.get('worktree_warp').execute('busy-25', { name: 'feat-stale' }, undefined, undefined, ctx);
327
1020
  assert.notEqual(unreadable.isError, true, `an unsafe store is no evidence: ${resultText(unreadable)}`);
328
1021
  assert.equal(host.sent.length, 1);
329
1022
  } finally {
330
1023
  fs.chmodSync(PRESENCE, 0o700);
331
1024
  }
1025
+ settlePending();
332
1026
  });
333
1027
 
334
- test('queued counters block; waiting and finished counters do not', async () => {
335
- const repo = makeRepo();
336
- const { ctx } = makeCtx(repo);
337
- const created = await tools.get('worktree_create').execute('busy-12', { branch: 'feat/queued', changes: 'none' }, undefined, undefined, ctx);
338
- assert.notEqual(created.isError, true, resultText(created));
339
-
340
- publishSession({ running: 0, queued: 2, waiting: 1, finished: 4 });
341
- host.sent.length = 0;
342
- const refused = await tools.get('worktree_warp').execute('busy-13', { name: 'feat-queued' }, undefined, undefined, ctx);
343
- assert.equal(refused.isError, true, 'queued work must refuse');
344
- assert.equal(host.sent.length, 0, 'a refusal queues nothing');
345
- assert.match(resultText(refused), /2 queued agent task\(s\)/);
346
-
347
- publishSession({ running: 0, queued: 0, waiting: 4, finished: 9 });
348
- host.sent.length = 0;
349
- const idle = await tools.get('worktree_warp').execute('busy-14', { name: 'feat-queued' }, undefined, undefined, ctx);
350
- assert.notEqual(idle.isError, true, `waiting/finished work is not busy: ${resultText(idle)}`);
351
- assert.equal(host.sent.length, 1);
352
- });
353
-
354
- test('a busy refusal leaves the worktree listing and the registry byte-identical', async () => {
355
- const repo = makeRepo();
356
- const { ctx } = makeCtx(repo);
357
- const created = await tools.get('worktree_create').execute('busy-15', { branch: 'feat/intact', changes: 'none' }, undefined, undefined, ctx);
358
- assert.notEqual(created.isError, true, resultText(created));
359
-
360
- const registryPath = path.resolve(repo, git(repo, ['rev-parse', '--git-common-dir']), 'pi-worktrees.json');
361
- const listBefore = git(repo, ['worktree', 'list', '--porcelain']);
362
- const registryBefore = crypto.createHash('sha256').update(fs.readFileSync(registryPath)).digest('hex');
363
-
364
- publishSession({ running: 1 });
365
- host.sent.length = 0;
366
- const refused = await tools.get('worktree_warp').execute('busy-16', { name: 'feat-intact' }, undefined, undefined, ctx);
367
- assert.equal(refused.isError, true);
368
- assert.equal(host.sent.length, 0);
369
-
370
- assert.equal(git(repo, ['worktree', 'list', '--porcelain']), listBefore, 'the listing changed');
371
- assert.equal(
372
- crypto.createHash('sha256').update(fs.readFileSync(registryPath)).digest('hex'),
373
- registryBefore,
374
- 'the registry changed',
375
- );
376
- });
377
-
378
- test('a queued handoff token is refused by /warp when this session turns busy', async () => {
1028
+ test('another session’s running tasks never block this session', async () => {
379
1029
  const repo = makeRepo();
380
- const { ctx } = makeCtx(repo);
381
- const created = await tools.get('worktree_create').execute('busy-17', { branch: 'feat/token', changes: 'none' }, undefined, undefined, ctx);
1030
+ const ctx = makeCtx(repo);
1031
+ const created = await tools.get('worktree_create').execute('busy-26', { branch: 'feat/other', changes: 'none' }, undefined, undefined, ctx);
382
1032
  assert.notEqual(created.isError, true, resultText(created));
383
1033
 
384
1034
  clearPresence();
1035
+ writeOtherSession({ running: 5, queued: 3 });
385
1036
  host.sent.length = 0;
386
- const queued = await tools.get('worktree_warp').execute('busy-18', { name: 'feat-token' }, undefined, undefined, ctx);
387
- assert.notEqual(queued.isError, true, resultText(queued));
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/);
388
1040
  assert.equal(host.sent.length, 1);
389
- const token = host.sent[0][0].replace(/^\/warp /, '');
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();
390
1044
 
391
- publishSession({ running: 2 });
392
1045
  notifications.length = 0;
393
- const switches = [];
394
- ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
395
- await commands.get('warp').handler(token, ctx);
396
- assert.equal(switches.length, 0, 'a handoff must not move the session under a running task');
397
- assert.equal(notifications.length, 1, JSON.stringify(notifications));
398
- assert.match(notifications[0][1], /still has 2 running agent task\(s\)/);
1046
+ await commands.get('warp').handler('feat-other', ctx);
1047
+ assert.deepEqual(notifications.filter(([, text]) => /already pending|handoff queued/.test(String(text))), []);
1048
+ settlePending();
399
1049
  });
400
1050
 
401
- test('the selector pick refuses and never switches while this session is busy', async () => {
1051
+ test('the selector pick is queued, never switched, while this session is busy', async () => {
402
1052
  const repo = makeRepo();
403
- const { ctx: createCtx } = makeCtx(repo);
404
- const created = await tools.get('worktree_create').execute('busy-19', { branch: 'feat/pick', changes: 'none' }, undefined, undefined, createCtx);
1053
+ const createCtx = makeCtx(repo);
1054
+ const created = await tools.get('worktree_create').execute('busy-28', { branch: 'feat/pick', changes: 'none' }, undefined, undefined, createCtx);
405
1055
  assert.notEqual(created.isError, true, resultText(created));
406
1056
 
407
1057
  const switches = [];
@@ -428,31 +1078,31 @@ describe('S4 boundaries: negative cases, every front, unaffected surfaces', () =
428
1078
  picks.push('feat-pick');
429
1079
  await commands.get('warp').handler('', ctx);
430
1080
  assert.equal(switches.length, 0, 'the selector must not move the session under a running task');
431
- assert.equal(notifications.filter(([, text]) => /still has .* agent task/.test(String(text))).length, 1);
1081
+ assert.equal(notifications.filter(([, text]) => /handoff queued — waiting for 2 running/.test(String(text))).length, 1);
1082
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the selector pick is kept pending');
1083
+ settlePending();
432
1084
  });
433
1085
 
434
- test('another session’s running tasks never block this session', async () => {
1086
+ test('session shutdown clears the pending warp', async () => {
435
1087
  const repo = makeRepo();
436
- const { ctx } = makeCtx(repo);
437
- const created = await tools.get('worktree_create').execute('busy-20', { branch: 'feat/other', changes: 'none' }, undefined, undefined, ctx);
1088
+ const ctx = makeCtx(repo);
1089
+ const created = await tools.get('worktree_create').execute('busy-sd1', { branch: 'feat/shutdown', changes: 'none' }, undefined, undefined, ctx);
438
1090
  assert.notEqual(created.isError, true, resultText(created));
439
1091
 
440
- clearPresence();
441
- writeOtherSession({ running: 5, queued: 3 });
1092
+ publishSession({ running: 1 });
442
1093
  host.sent.length = 0;
443
- const queued = await tools.get('worktree_warp').execute('busy-21', { name: 'feat-other' }, undefined, undefined, ctx);
444
- assert.notEqual(queued.isError, true, `a peer's work is not this session's: ${resultText(queued)}`);
445
- assert.equal(host.sent.length, 1);
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));
1096
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the request is pending before shutdown');
446
1097
 
447
- notifications.length = 0;
448
- await commands.get('warp').handler('feat-other', ctx);
449
- assert.deepEqual(notifications.filter(([, text]) => /still has .* agent task/.test(String(text))), []);
1098
+ for (const [, handler] of hooks.filter(([name]) => name === 'session_shutdown')) {
1099
+ await handler({}, ctx);
1100
+ }
1101
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'nothing deferred survives its session');
450
1102
  });
451
1103
 
452
- test('list, create and close still work while this session reports running work', async () => {
1104
+ test('list, create and delete still work while this session reports running work', async () => {
453
1105
  const repo = makeRepo();
454
- // The close approval question is part of its own flow: it is answered here
455
- // so this test measures only whether the busy counters leak into it.
456
1106
  const ctx = {
457
1107
  cwd: repo,
458
1108
  hasUI: true,
@@ -467,22 +1117,12 @@ describe('S4 boundaries: negative cases, every front, unaffected surfaces', () =
467
1117
  };
468
1118
  publishSession({ running: 2, queued: 1 });
469
1119
 
470
- const listed = await tools.get('worktree_list').execute('busy-22', {}, undefined, undefined, ctx);
1120
+ const listed = await tools.get('worktree_list').execute('busy-29', {}, undefined, undefined, ctx);
471
1121
  assert.notEqual(listed.isError, true, resultText(listed));
472
- const created = await tools.get('worktree_create').execute('busy-23', { branch: 'feat/surface', changes: 'none' }, undefined, undefined, ctx);
1122
+ const created = await tools.get('worktree_create').execute('busy-30', { branch: 'feat/surface', changes: 'none' }, undefined, undefined, ctx);
473
1123
  assert.notEqual(created.isError, true, resultText(created));
474
- const closed = await tools.get('worktree_close').execute('busy-24', { name: 'feat-surface', force: true }, undefined, undefined, ctx);
1124
+ const closed = await tools.get('worktree_delete').execute('busy-31', { name: 'feat-surface', force: true }, undefined, undefined, ctx);
475
1125
  assert.notEqual(closed.isError, true, resultText(closed));
476
- });
477
-
478
- test('the wait budget is parsed, defaulted and clamped', () => {
479
- assert.equal(busyLib.DEFAULT_WAIT_MS, 60000);
480
- assert.equal(busyLib.MAX_WAIT_MS, 600000);
481
- assert.equal(busyLib.waitBudgetMs({}), 60000);
482
- assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: '' }), 60000);
483
- assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: '5000' }), 5000);
484
- assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: '-1' }), 60000);
485
- assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: 'abc' }), 60000);
486
- assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: '999999999' }), 600000);
1126
+ settlePending();
487
1127
  });
488
1128
  });