pi-odd-worktree 1.2.0 → 2.0.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,15 +1,24 @@
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
+ // 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.
13
22
  const { test, describe, before, after } = require('node:test');
14
23
  const assert = require('node:assert/strict');
15
24
  const crypto = require('node:crypto');
@@ -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,15 @@ 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
+ }
46
65
 
47
66
  function git(cwd, args) {
48
67
  const out = spawnSync('git', args, { cwd, encoding: 'utf8' });
@@ -66,11 +85,10 @@ function makeRepo() {
66
85
  function publishSession({ running = 0, queued = 0, waiting = 0, heartbeat = Date.now(), label = 'Busy session' } = {}) {
67
86
  fs.mkdirSync(PRESENCE, { recursive: true, mode: 0o700 });
68
87
  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({
88
+ fs.writeFileSync(path.join(PRESENCE, `${SESSION_HASH}.${INCARNATION}.header.json`), JSON.stringify({
71
89
  schema: 1,
72
90
  sessionHash: SESSION_HASH,
73
- incarnation,
91
+ incarnation: INCARNATION,
74
92
  label,
75
93
  heartbeat,
76
94
  generation: 1,
@@ -78,8 +96,8 @@ function publishSession({ running = 0, queued = 0, waiting = 0, heartbeat = Date
78
96
  digest: 'c'.repeat(64),
79
97
  unavailable: null,
80
98
  }), { mode: 0o600 });
81
- fs.writeFileSync(path.join(PRESENCE, `${SESSION_HASH}.${incarnation}.discovery.json`), JSON.stringify({
82
- schema: 1, sessionHash: SESSION_HASH, incarnation, generation: 1,
99
+ fs.writeFileSync(path.join(PRESENCE, `${SESSION_HASH}.${INCARNATION}.discovery.json`), JSON.stringify({
100
+ schema: 1, sessionHash: SESSION_HASH, incarnation: INCARNATION, generation: 1,
83
101
  metadata: { activation: 'd'.repeat(64), workspace: '/tmp/workspace', tasks: [], omitted: 0 },
84
102
  }), { mode: 0o600 });
85
103
  }
@@ -88,60 +106,132 @@ function clearPresence() {
88
106
  try { fs.rmSync(PRESENCE, { recursive: true, force: true }); } catch { /* absent is fine */ }
89
107
  }
90
108
 
109
+ // A bounded wait for a background poller/timer to become observable. The budgets
110
+ // are injected (env or pendingWarpTick), so nothing here waits on a real warp.
111
+ async function until(predicate, { timeoutMs = 2000, stepMs = 5 } = {}) {
112
+ const started = Date.now();
113
+ for (;;) {
114
+ if (predicate()) return true;
115
+ if (Date.now() - started > timeoutMs) return false;
116
+ await new Promise((resolve) => setTimeout(resolve, stepMs));
117
+ }
118
+ }
119
+
91
120
  const notifications = [];
92
121
  function makeCtx(cwd, extra = {}) {
93
- const switches = [];
94
122
  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 }; },
123
+ cwd,
124
+ hasUI: true,
125
+ mode: 'tui',
126
+ sessionManager: { getSessionId: () => SESSION_ID },
127
+ ui: {
128
+ notify: (text, level) => { notifications.push([level, text]); },
129
+ ...extra,
107
130
  },
131
+ waitForIdle: async () => {},
132
+ switchSession: async () => ({ cancelled: false }),
108
133
  };
109
134
  }
110
135
 
111
- function resultText(result) {
112
- return (result.content || []).map((part) => (part && part.text) || '').join('\n');
136
+ // This session's background jobs, as the host's `job_list` tool reports them:
137
+ // one line per job, `id · status · label · elapsed · log`. `mode` selects the
138
+ // other answers a host can give instead of a job list: `absent` (the tool is not
139
+ // registered), `error` (the call fails) and `unparsable` (a shape the parser does
140
+ // not know). Returns the mutable state the test drives.
141
+ function addJobs(ctx, jobs = [], mode = 'ok') {
142
+ const state = { jobs, mode, calls: 0 };
143
+ ctx.tools = mode === 'absent' ? [] : [{ name: 'job_list' }];
144
+ ctx.executeTool = async (name) => {
145
+ if (name !== 'job_list') return { isError: true, content: [{ type: 'text', text: `unknown tool ${name}` }] };
146
+ state.calls += 1;
147
+ if (state.mode === 'error') return { isError: true, content: [{ type: 'text', text: 'job_list failed' }] };
148
+ if (state.mode === 'unparsable') return { content: [{ type: 'text', text: 'something else entirely' }] };
149
+ const lines = state.jobs.map((job) => `${job.id} · ${job.status} · ${job.label || 'Probe de job'} · 3s · /tmp/gentle-jobs-1/${job.id}.log`);
150
+ return { content: [{ type: 'text', text: lines.length > 0 ? lines.join('\n') : 'No background jobs in this session.' }] };
151
+ };
152
+ return state;
153
+ }
154
+
155
+ // The minimal host session manager a warp needs: an empty session (no entries)
156
+ // changes PATH through `create` + `switchSession`, which is the cheapest real
157
+ // move a test can drive end to end.
158
+ function makeSessionHost(world) {
159
+ class FakeSession {
160
+ constructor(cwd, file, header) {
161
+ this.cwd = cwd;
162
+ this.file = file;
163
+ this.header = header;
164
+ }
165
+
166
+ getSessionFile() { return this.file; }
167
+
168
+ getSessionDir() { return world.sessionDir; }
169
+
170
+ getSessionId() { return SESSION_ID; }
171
+
172
+ getSessionName() { return ''; }
173
+
174
+ getHeader() { return this.header; }
175
+
176
+ getEntries() { return []; }
177
+
178
+ getLeafId() { return null; }
179
+
180
+ static create(cwd, dir) {
181
+ world.created += 1;
182
+ const file = path.join(dir || world.sessionDir, `created-${world.created}.jsonl`);
183
+ world.createdFiles.push(file);
184
+ return new FakeSession(cwd, file, { type: 'session', version: 3, id: `id-${world.created}`, timestamp: 1, cwd });
185
+ }
186
+
187
+ static forkFrom() {
188
+ throw new Error('an empty session must never fork');
189
+ }
190
+ }
191
+ return FakeSession;
113
192
  }
114
193
 
115
194
  let host;
116
195
  let commands;
117
196
  let tools;
197
+ let hooks;
118
198
  before(async () => {
119
199
  process.env.HERDR_BIN_PATH = NO_HERDR;
120
200
  process.env.GENTLE_WORKTREE_THREAD = SESSION_ID;
121
201
  process.env.PATH = `${HOOK_BIN}${path.delimiter}${savedEnv.PATH || ''}`;
122
202
  delete process.env.GENTLE_PI_AGENT_HOME;
123
203
  process.env.PI_CODING_AGENT_DIR = AGENT_HOME;
124
- // The command front's wait is bounded by this budget; tests never wait.
204
+ // The command front's bounded drain attempt: tests never wait for it.
125
205
  process.env.ODD_WORKTREE_WARP_BUSY_WAIT_MS = '0';
206
+ // The queue's lifetime and poll interval are injected per test; these defaults
207
+ // keep the poller quiet while a test drives `pendingWarpTick` itself.
208
+ process.env.ODD_WORKTREE_WARP_PENDING_MS = '600000';
209
+ process.env.ODD_WORKTREE_WARP_PENDING_POLL_MS = '60000';
126
210
  const sent = [];
127
211
  const loaded = await loadExtension({ sendUserMessage: (text, options) => { sent.push([text, options]); } });
128
212
  host = loaded.host;
129
213
  host.sent = sent;
130
214
  commands = loaded.commands;
131
215
  tools = loaded.tools;
216
+ hooks = loaded.hooks;
132
217
  });
133
218
 
134
- describe('lib/worktree-warp-busy.js', () => {
135
- const busyLib = require('../lib/worktree-warp-busy.js');
219
+ function resultText(result) {
220
+ return (result.content || []).map((part) => (part && part.text) || '').join('\n');
221
+ }
136
222
 
223
+ // ---------------------------------------------------------------------------
224
+ // The module itself: counters, texts and the pending queue (injected clock).
225
+ // ---------------------------------------------------------------------------
226
+ describe('lib/worktree-warp-busy.js', () => {
137
227
  test('reads only this session’s own counters', async () => {
138
228
  const home = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-lib-')));
139
229
  const dir = path.join(home, 'gentle-agents', 'presence');
140
230
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
141
231
  const mine = crypto.createHash('sha256').update('session-a').digest('hex');
142
232
  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',
233
+ const write = (hash, running) => fs.writeFileSync(path.join(dir, `${hash}.${INCARNATION}.header.json`), JSON.stringify({
234
+ schema: 1, sessionHash: hash, incarnation: INCARNATION,
145
235
  label: 'L', heartbeat: 1000, generation: 1,
146
236
  counts: { running, queued: 0, waiting: 0, finished: 0 },
147
237
  digest: 'e'.repeat(64), unavailable: null,
@@ -167,8 +257,8 @@ describe('lib/worktree-warp-busy.js', () => {
167
257
  const dir = path.join(home, 'gentle-agents', 'presence');
168
258
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
169
259
  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',
260
+ fs.writeFileSync(path.join(dir, `${mine}.${INCARNATION}.header.json`), JSON.stringify({
261
+ schema: 1, sessionHash: mine, incarnation: INCARNATION,
172
262
  label: 'L', heartbeat: 1000, generation: 1,
173
263
  counts: { running: 3, queued: 0, waiting: 0, finished: 0 },
174
264
  digest: 'e'.repeat(64), unavailable: null,
@@ -206,32 +296,252 @@ describe('lib/worktree-warp-busy.js', () => {
206
296
  assert.equal(never.waited, 3000);
207
297
  });
208
298
 
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/);
299
+ test('the queue texts name both workloads and no longer disclaim jobs', () => {
300
+ assert.equal(
301
+ busyLib.queuedText({ running: 2, queued: 1, jobs: { active: 1, status: 'ok' } }),
302
+ 'handoff queued — waiting for 2 running agent task(s) and 1 queued agent task(s) and 1 running background job before the move',
303
+ );
304
+ assert.equal(
305
+ busyLib.queuedText({ running: 0, queued: 0, jobs: { active: 2, status: 'ok' } }),
306
+ 'handoff queued — waiting for 2 running background jobs before the move',
307
+ );
308
+ assert.equal(busyLib.queuedText({ running: 1, jobs: { active: 0, status: 'ok' } }), 'handoff queued — waiting for 1 running agent task(s) before the move');
309
+ // The old disclaimer is gone now that jobs are covered.
310
+ assert.equal(/not observable/.test(busyLib.queuedText({ running: 1, jobs: { active: 0, status: 'ok' } })), false);
311
+ assert.equal(/not observable/.test(busyLib.expiredText('feat-x', 30)), false);
312
+
313
+ assert.equal(busyLib.jobsUnknownText({ jobs: { status: 'ok', active: 0 } }), '', 'a readable job list needs no caveat');
314
+ assert.match(
315
+ busyLib.jobsUnknownText({ jobs: { status: 'unavailable' } }),
316
+ /^the background-job state is unknown \(job_list is not available on this host\), so confirm any bash_background or monitor job finished$/,
317
+ );
318
+ assert.match(busyLib.jobsUnknownText({ jobs: { status: 'error' } }), /unknown \(job_list failed\)/);
319
+ assert.match(busyLib.jobsUnknownText({ jobs: { status: 'unparsable' } }), /unknown \(job_list answered in an unexpected shape\)/);
320
+
321
+ assert.match(busyLib.expiredText('feat-x', 30), /the pending warp to feat-x expired after 30 min with nothing moved/);
322
+ assert.match(busyLib.expiredText('feat-x', 30), /agent tasks and background jobs finish/);
323
+ assert.match(busyLib.expiredText('feat-x', 30, { jobs: { status: 'error' } }), /\(the background-job state is unknown \(job_list failed\)/);
324
+ assert.match(
325
+ busyLib.pendingWarpRefusalText({ name: 'feat-x' }, 'feat-y'),
326
+ /^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$/,
327
+ );
328
+ });
329
+
330
+ test('a job is active only while its status field says running or queued', () => {
331
+ const line = (status) => `job-1 · ${status} · Probe de job · 3s · /tmp/gentle-jobs-1/job-1.log`;
332
+ assert.deepEqual(busyLib.parseJobList(line('running')), { status: 'ok', active: 1, count: 1 });
333
+ assert.deepEqual(busyLib.parseJobList(line('queued')), { status: 'ok', active: 1, count: 1 });
334
+ assert.deepEqual(busyLib.parseJobList(`m-1 · monitor running · Watch · 4s · /tmp/gentle-jobs-1/m-1.log`), { status: 'ok', active: 1, count: 1 });
335
+ for (const finished of ['exited 0', 'failed 1', 'stopped', 'monitor stopped']) {
336
+ assert.deepEqual(busyLib.parseJobList(line(finished)), { status: 'ok', active: 0, count: 1 }, `${finished} is finished, never active`);
337
+ }
338
+ assert.equal(busyLib.parseJobList(`${line('running')}\n${line('exited 0')}`).active, 1, 'only the running row counts');
339
+ assert.deepEqual(busyLib.parseJobList('No background jobs in this session.'), { status: 'ok', active: 0, count: 0 });
340
+ assert.deepEqual(busyLib.parseJobList(''), { status: 'ok', active: 0, count: 0 });
341
+ assert.equal(busyLib.parseJobList('job-1 is doing something').status, 'unparsable', 'an unknown shape is not an empty list');
342
+ });
343
+
344
+ test('sessionActivity merges this session’s jobs through the host tool', async () => {
345
+ const home = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-jobs-')));
346
+ const plain = makeCtx(os.tmpdir());
347
+ const ctx = makeCtx(os.tmpdir());
348
+ const jobs = addJobs(ctx, [{ id: 'job-1', status: 'running' }]);
349
+
350
+ const running = await busyLib.sessionActivity({ sessionId: SESSION_ID, env: { PI_CODING_AGENT_DIR: home }, host: ctx });
351
+ assert.equal(running.jobs.status, 'ok');
352
+ assert.equal(running.jobs.active, 1);
353
+ assert.equal(running.jobsUnknown, false);
354
+ assert.equal(running.busy, true, 'a running job alone makes the session busy');
355
+ assert.equal(jobs.calls, 1);
356
+
357
+ jobs.jobs[0].status = 'exited 0';
358
+ const done = await busyLib.sessionActivity({ sessionId: SESSION_ID, env: { PI_CODING_AGENT_DIR: home }, host: ctx });
359
+ assert.equal(done.jobs.active, 0);
360
+ assert.equal(done.busy, false, 'a finished job is not work');
361
+
362
+ const noTool = await busyLib.sessionActivity({ sessionId: SESSION_ID, env: { PI_CODING_AGENT_DIR: home }, host: plain });
363
+ assert.equal(noTool.jobs.status, 'unavailable', 'no host seam is unknown, never "no jobs"');
364
+ assert.equal(noTool.jobsUnknown, true);
365
+ assert.equal(noTool.busy, false, 'an unknown job state blocks nothing');
366
+ });
367
+
368
+ test('the wait, pending and poll budgets are parsed, defaulted and clamped', () => {
369
+ assert.equal(busyLib.DEFAULT_WAIT_MS, 60000);
370
+ assert.equal(busyLib.MAX_WAIT_MS, 600000);
371
+ assert.equal(busyLib.waitBudgetMs({}), 60000);
372
+ assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: '' }), 60000);
373
+ assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: '5000' }), 5000);
374
+ assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: '-1' }), 60000);
375
+ assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: 'abc' }), 60000);
376
+ assert.equal(busyLib.waitBudgetMs({ ODD_WORKTREE_WARP_BUSY_WAIT_MS: '999999999' }), 600000);
377
+
378
+ assert.equal(busyLib.DEFAULT_PENDING_MS, 30 * 60 * 1000);
379
+ assert.equal(busyLib.pendingBudgetMs({}), 30 * 60 * 1000);
380
+ assert.equal(busyLib.pendingBudgetMs({ ODD_WORKTREE_WARP_PENDING_MS: '1500' }), 1500);
381
+ assert.equal(busyLib.pendingBudgetMs({ ODD_WORKTREE_WARP_PENDING_MS: 'nope' }), 30 * 60 * 1000);
382
+ assert.equal(busyLib.pendingBudgetMs({ ODD_WORKTREE_WARP_PENDING_MS: '999999999999' }), busyLib.MAX_PENDING_MS);
383
+ assert.equal(busyLib.pendingPollMs({}), busyLib.DEFAULT_PENDING_POLL_MS);
384
+ assert.equal(busyLib.pendingPollMs({ ODD_WORKTREE_WARP_PENDING_POLL_MS: '999999999999' }), busyLib.MAX_PENDING_POLL_MS);
385
+ });
386
+
387
+ test('the queue keys on the session id, then on the checkout root', () => {
388
+ assert.equal(busyLib.pendingKeyFor({ sessionId: 's-1', root: '/repo' }), 'session:s-1');
389
+ assert.equal(busyLib.pendingKeyFor({ sessionId: '', root: '/repo' }), 'root:/repo');
390
+ assert.equal(busyLib.pendingKeyFor({}), null);
391
+ assert.equal(busyLib.pendingKeyFor(null), null);
392
+ });
393
+
394
+ test('sameWarpHandoff matches only the same move and change selection', () => {
395
+ const base = { name: 'feat-x', target: '/t', from: '/f', branch: 'feat/x', changes: { mode: 'none', paths: [] } };
396
+ assert.equal(busyLib.sameWarpHandoff(base, { ...base }), true);
397
+ assert.equal(busyLib.sameWarpHandoff(base, { ...base, changes: { mode: 'all', paths: [] } }), false);
398
+ assert.equal(busyLib.sameWarpHandoff(base, { ...base, changes: { mode: 'paths', paths: ['a'] } }), false);
399
+ assert.equal(busyLib.sameWarpHandoff(base, { ...base, target: '/other' }), false);
400
+ assert.equal(busyLib.sameWarpHandoff(base, null), false);
401
+ });
402
+
403
+ test('the pending warp waits for the counters, then dispatches the same handoff once', async () => {
404
+ const key = 'session:lib-queue';
405
+ const clock = { now: 1000 };
406
+ const dispatched = [];
407
+ const handoff = { name: 'feat-q', target: '/t', from: '/f', branch: 'feat/q', changes: { mode: 'none', paths: [] } };
408
+ let activity = { busy: true, running: 2, queued: 0 };
409
+ const queued = busyLib.queuePendingWarp({
410
+ key,
411
+ name: 'feat-q',
412
+ token: '@token',
413
+ handoff,
414
+ now: () => clock.now,
415
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '10000', ODD_WORKTREE_WARP_PENDING_POLL_MS: '1000' },
416
+ timers: { set: () => null, clear: () => {} },
417
+ read: async () => activity,
418
+ dispatch: (queuedHandoff, token) => { dispatched.push([queuedHandoff, token]); return { ok: true }; },
419
+ });
420
+ try {
421
+ assert.equal(queued.ok, true);
422
+ assert.equal(busyLib.pendingWarpFor(key).name, 'feat-q');
423
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'waiting');
424
+ assert.deepEqual(dispatched, [], 'a busy session dispatches nothing');
425
+
426
+ activity = { busy: false, running: 0, queued: 0 };
427
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'dispatched');
428
+ assert.deepEqual(dispatched, [[handoff, '@token']], 'the SAME validated handoff is re-dispatched');
429
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'waiting');
430
+ assert.equal(dispatched.length, 1, 'one queued warp is never dispatched twice');
431
+ assert.equal(busyLib.pendingWarpFor(key).dispatching, true);
432
+ } finally {
433
+ assert.equal(busyLib.settlePendingWarp(key).name, 'feat-q');
434
+ assert.equal(busyLib.pendingWarpFor(key), null);
435
+ }
436
+ });
437
+
438
+ test('a second queue is refused and leaves the pending warp untouched', () => {
439
+ const key = 'session:lib-second';
440
+ const first = { name: 'feat-first', target: '/t', from: '/f', branch: 'feat/first', changes: { mode: 'none', paths: [] } };
441
+ const second = { name: 'feat-second', target: '/t2', from: '/f', branch: 'feat/second', changes: { mode: 'none', paths: [] } };
442
+ const deps = {
443
+ now: () => 1000,
444
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '10000' },
445
+ timers: { set: () => null, clear: () => {} },
446
+ read: async () => ({ busy: true }),
447
+ dispatch: () => ({ ok: true }),
448
+ };
449
+ try {
450
+ assert.equal(busyLib.queuePendingWarp({ key, name: 'feat-first', token: '@one', handoff: first, ...deps }).ok, true);
451
+ const refused = busyLib.queuePendingWarp({ key, name: 'feat-second', token: '@two', handoff: second, ...deps });
452
+ assert.equal(refused.ok, false);
453
+ assert.equal(refused.reason, 'pending');
454
+ assert.equal(refused.pending.name, 'feat-first');
455
+ assert.deepEqual(busyLib.pendingWarpFor(key).handoff, first);
456
+ } finally {
457
+ busyLib.settlePendingWarp(key);
458
+ }
459
+ });
460
+
461
+ test('the pending warp expires with a notice that nothing moved, and clears', async () => {
462
+ const key = 'session:lib-expiry';
463
+ const clock = { now: 1000 };
464
+ const notified = [];
465
+ const deps = {
466
+ now: () => clock.now,
467
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '1000' },
468
+ timers: { set: () => null, clear: () => {} },
469
+ read: async () => ({ busy: true, running: 1 }),
470
+ dispatch: () => { throw new Error('an expired warp must not dispatch'); },
471
+ notify: (text, level) => { notified.push([level, text]); },
472
+ };
473
+ const handoff = { name: 'feat-e', target: '/t', from: '/f', branch: 'feat/e', changes: { mode: 'none', paths: [] } };
474
+ assert.equal(busyLib.queuePendingWarp({ key, name: 'feat-e', token: '@e', handoff, ...deps }).ok, true);
475
+ clock.now += 1000;
476
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'expired');
477
+ assert.equal(busyLib.pendingWarpFor(key), null, 'an expired request is cleared, so a later warp is accepted');
478
+ assert.equal(notified.length, 1);
479
+ assert.equal(notified[0][0], 'error');
480
+ assert.match(notified[0][1], /the pending warp to feat-e expired after 1 min with nothing moved/);
481
+ });
482
+
483
+ test('a refused re-dispatch stays queued instead of throwing', async () => {
484
+ const key = 'session:lib-refused';
485
+ const deps = {
486
+ now: () => 1000,
487
+ env: { ODD_WORKTREE_WARP_PENDING_MS: '10000' },
488
+ timers: { set: () => null, clear: () => {} },
489
+ read: async () => ({ busy: false }),
490
+ dispatch: () => ({ ok: false, error: 'the host cannot dispatch the warp command here' }),
491
+ };
492
+ const handoff = { name: 'feat-r', target: '/t', from: '/f', branch: 'feat/r', changes: { mode: 'none', paths: [] } };
493
+ try {
494
+ assert.equal(busyLib.queuePendingWarp({ key, name: 'feat-r', token: '@r', handoff, ...deps }).ok, true);
495
+ assert.equal((await busyLib.pendingWarpTick(key)).status, 'waiting');
496
+ const record = busyLib.pendingWarpFor(key);
497
+ assert.notEqual(record, null);
498
+ assert.equal(record.dispatching, false, 'a refused dispatch is retried, not lost');
499
+ // Resuming after a refused dispatch re-arms the poller for the same key.
500
+ assert.equal(busyLib.resumePendingWarp(key), true);
501
+ assert.equal(busyLib.pendingWarpFor(key).dispatching, false);
502
+ } finally {
503
+ busyLib.settlePendingWarp(key);
504
+ }
213
505
  });
214
506
  });
215
507
 
216
- describe('warp fronts while this session is busy', () => {
217
- test('the tool queues nothing while an agent task is running', async () => {
508
+ // ---------------------------------------------------------------------------
509
+ // The tool front: it QUEUES the handoff while this session is busy.
510
+ // ---------------------------------------------------------------------------
511
+ describe('the worktree_warp tool queues while this session has agent tasks or jobs', () => {
512
+ test('a busy session gets the queued wording and one handoff, and nothing claims jobs are invisible', async () => {
218
513
  const repo = makeRepo();
219
- const { ctx } = makeCtx(repo);
514
+ const ctx = makeCtx(repo);
220
515
  const created = await tools.get('worktree_create').execute('busy-1', { branch: 'feat/busy', changes: 'none' }, undefined, undefined, ctx);
221
516
  assert.notEqual(created.isError, true, resultText(created));
222
517
 
223
518
  publishSession({ running: 1 });
519
+ addJobs(ctx, [], 'absent');
224
520
  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);
521
+ notifications.length = 0;
522
+ const queued = await tools.get('worktree_warp').execute('busy-2', { name: 'feat-busy' }, undefined, undefined, ctx);
523
+ assert.notEqual(queued.isError, true, resultText(queued));
524
+ assert.match(
525
+ resultText(queued),
526
+ /^worktree warp: handoff queued — waiting for 1 running agent task\(s\) before the move$/m,
527
+ );
528
+ assert.match(
529
+ resultText(queued),
530
+ /^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,
531
+ );
532
+ assert.match(resultText(queued), /^to: feat-busy$/m);
533
+ assert.match(resultText(queued), /^branch: feat\/busy$/m);
534
+ assert.equal(host.sent.length, 1, 'the busy tool front still queues exactly one handoff');
535
+ assert.equal(host.sent[0][0].startsWith('/warp @'), true);
536
+ assert.equal(queued.details.busy, true);
537
+ assert.equal(queued.details.queued, true);
538
+ assert.deepEqual(notifications, [], 'the tool result is the report; nothing is notified twice');
539
+ settlePending();
230
540
  });
231
541
 
232
- test('the tool queues the handoff once the counters drain', async () => {
542
+ test('an idle session keeps the byte-identical queued wording', async () => {
233
543
  const repo = makeRepo();
234
- const { ctx } = makeCtx(repo);
544
+ const ctx = makeCtx(repo);
235
545
  const created = await tools.get('worktree_create').execute('busy-3', { branch: 'feat/free', changes: 'none' }, undefined, undefined, ctx);
236
546
  assert.notEqual(created.isError, true, resultText(created));
237
547
 
@@ -239,49 +549,422 @@ describe('warp fronts while this session is busy', () => {
239
549
  host.sent.length = 0;
240
550
  const queued = await tools.get('worktree_warp').execute('busy-4', { name: 'feat-free' }, undefined, undefined, ctx);
241
551
  assert.notEqual(queued.isError, true, resultText(queued));
242
- assert.match(resultText(queued), /^worktree warp: handoff queued/);
552
+ assert.match(
553
+ resultText(queued),
554
+ /^worktree warp: handoff queued — the session moves when this turn ends\nto: feat-free\npath: .+\nbranch: feat\/free$/,
555
+ );
556
+ assert.equal(queued.details.busy, undefined);
557
+ assert.equal(host.sent.length, 1);
558
+ settlePending();
559
+ });
560
+
561
+ test('queued counters queue the warp; waiting and finished counters do not', async () => {
562
+ const repo = makeRepo();
563
+ const ctx = makeCtx(repo);
564
+ const created = await tools.get('worktree_create').execute('busy-5', { branch: 'feat/queued', changes: 'none' }, undefined, undefined, ctx);
565
+ assert.notEqual(created.isError, true, resultText(created));
566
+
567
+ publishSession({ running: 0, queued: 2, waiting: 1, finished: 4 });
568
+ host.sent.length = 0;
569
+ const queued = await tools.get('worktree_warp').execute('busy-6', { name: 'feat-queued' }, undefined, undefined, ctx);
570
+ assert.notEqual(queued.isError, true, resultText(queued));
571
+ assert.match(resultText(queued), /waiting for 2 queued agent task\(s\) before the move/);
572
+ assert.equal(host.sent.length, 1);
573
+ // S6: the tool front now holds its own request pending, so a second warp
574
+ // must wait for this one to reach a terminal outcome.
575
+ settlePending();
576
+
577
+ publishSession({ running: 0, queued: 0, waiting: 4, finished: 9 });
578
+ host.sent.length = 0;
579
+ const idle = await tools.get('worktree_warp').execute('busy-7', { name: 'feat-queued' }, undefined, undefined, ctx);
580
+ assert.notEqual(idle.isError, true, resultText(idle));
581
+ assert.match(resultText(idle), /^worktree warp: handoff queued — the session moves when this turn ends/);
582
+ assert.equal(host.sent.length, 1);
583
+ settlePending();
584
+ });
585
+
586
+ test('a running job queues the warp, and a same-turn second call is refused', async () => {
587
+ const repo = makeRepo();
588
+ const ctx = makeCtx(repo);
589
+ const created = await tools.get('worktree_create').execute('busy-j1', { branch: 'feat/jobs', changes: 'none' }, undefined, undefined, ctx);
590
+ assert.notEqual(created.isError, true, resultText(created));
591
+
592
+ const jobs = addJobs(ctx, [{ id: 'job-1', status: 'running', label: 'Probe de job' }]);
593
+ host.sent.length = 0;
594
+ const queued = await tools.get('worktree_warp').execute('busy-j2', { name: 'feat-jobs' }, undefined, undefined, ctx);
595
+ assert.notEqual(queued.isError, true, resultText(queued));
596
+ assert.match(resultText(queued), /^worktree warp: handoff queued — waiting for 1 running background job before the move$/m);
597
+ assert.ok(jobs.calls > 0, 'the job list was actually read through the host tool');
598
+ assert.equal(host.sent.length, 1);
599
+ assert.equal(queued.details.busy, true);
600
+ // S6: the request is pending from QUEUE time, so a second call in the same
601
+ // turn — before the command ever runs — is refused and queues nothing.
602
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the tool front keeps its own request pending');
603
+ const second = await tools.get('worktree_warp').execute('busy-j3', { name: 'feat-jobs' }, undefined, undefined, ctx);
604
+ assert.equal(second.isError, true);
605
+ assert.match(
606
+ resultText(second),
607
+ /^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$/,
608
+ );
609
+ assert.equal(host.sent.length, 1, 'the refused second warp queues nothing');
610
+ settlePending();
611
+ });
612
+
613
+ test('a running agent task and a running job are both named', async () => {
614
+ const repo = makeRepo();
615
+ const ctx = makeCtx(repo);
616
+ const created = await tools.get('worktree_create').execute('busy-j4', { branch: 'feat/both', changes: 'none' }, undefined, undefined, ctx);
617
+ assert.notEqual(created.isError, true, resultText(created));
618
+
619
+ publishSession({ running: 2 });
620
+ addJobs(ctx, [{ id: 'job-7', status: 'queued' }]);
621
+ host.sent.length = 0;
622
+ const queued = await tools.get('worktree_warp').execute('busy-j5', { name: 'feat-both' }, undefined, undefined, ctx);
623
+ assert.notEqual(queued.isError, true, resultText(queued));
624
+ assert.match(
625
+ resultText(queued),
626
+ /^worktree warp: handoff queued — waiting for 2 running agent task\(s\) and 1 running background job before the move$/m,
627
+ );
628
+ assert.equal(host.sent.length, 1);
629
+ // Both workloads were readable, so nothing disclaims jobs any more.
630
+ assert.equal(/not observable/.test(resultText(queued)), false, 'the job disclaimer is gone');
631
+ assert.equal(/agent-task counters only/.test(resultText(queued)), false);
632
+ assert.equal(/^queue:/m.test(resultText(queued)), false, 'a readable job list adds no caveat row');
633
+ settlePending();
634
+ });
635
+
636
+ test('an unavailable, failing or unparsable job list blocks nothing and is disclosed only then', async () => {
637
+ const repo = makeRepo();
638
+ const ctx = makeCtx(repo);
639
+ const created = await tools.get('worktree_create').execute('busy-j6', { branch: 'feat/unknown', changes: 'none' }, undefined, undefined, ctx);
640
+ assert.notEqual(created.isError, true, resultText(created));
641
+ publishSession({ running: 1 });
642
+
643
+ // No host seam at all: the plain ctx has neither `tools` nor `executeTool`.
644
+ host.sent.length = 0;
645
+ const noSeam = await tools.get('worktree_warp').execute('busy-j7', { name: 'feat-unknown' }, undefined, undefined, ctx);
646
+ assert.notEqual(noSeam.isError, true, resultText(noSeam));
647
+ assert.match(resultText(noSeam), /waiting for 1 running agent task\(s\) before the move/);
648
+ assert.match(resultText(noSeam), /^queue: the background-job state is unknown \(job_list is not available on this host\)/m);
649
+ assert.equal(host.sent.length, 1, 'an unavailable job list never blocks the warp');
650
+ settlePending();
651
+
652
+ for (const [mode, reason] of [['error', 'job_list failed'], ['unparsable', 'job_list answered in an unexpected shape']]) {
653
+ addJobs(ctx, [], mode);
654
+ host.sent.length = 0;
655
+ const outcome = await tools.get('worktree_warp').execute(`busy-j8-${mode}`, { name: 'feat-unknown' }, undefined, undefined, ctx);
656
+ assert.notEqual(outcome.isError, true, resultText(outcome));
657
+ assert.match(resultText(outcome), new RegExp(`^queue: the background-job state is unknown \\(${reason}\\)`, 'm'));
658
+ assert.equal(host.sent.length, 1, `a ${mode} job list never blocks the warp`);
659
+ settlePending();
660
+ }
661
+
662
+ // An unknown job list with NO agent task either: the idle wording stands and
663
+ // nothing claims a queue it did not create.
664
+ clearPresence();
665
+ addJobs(ctx, [], 'unparsable');
666
+ host.sent.length = 0;
667
+ const idle = await tools.get('worktree_warp').execute('busy-j9', { name: 'feat-unknown' }, undefined, undefined, ctx);
668
+ assert.notEqual(idle.isError, true, resultText(idle));
669
+ assert.match(resultText(idle), /^worktree warp: handoff queued — the session moves when this turn ends/);
670
+ assert.equal(host.sent.length, 1);
671
+ settlePending();
672
+ });
673
+
674
+ test('a queued (busy) tool warp mutates no checkout and no registry row', async () => {
675
+ const repo = makeRepo();
676
+ const ctx = makeCtx(repo);
677
+ const created = await tools.get('worktree_create').execute('busy-8', { branch: 'feat/intact', changes: 'none' }, undefined, undefined, ctx);
678
+ assert.notEqual(created.isError, true, resultText(created));
679
+
680
+ const registryPath = path.resolve(repo, git(repo, ['rev-parse', '--git-common-dir']), 'pi-worktrees.json');
681
+ const listBefore = git(repo, ['worktree', 'list', '--porcelain']);
682
+ const registryBefore = crypto.createHash('sha256').update(fs.readFileSync(registryPath)).digest('hex');
683
+
684
+ publishSession({ running: 1 });
685
+ host.sent.length = 0;
686
+ const queued = await tools.get('worktree_warp').execute('busy-9', { name: 'feat-intact' }, undefined, undefined, ctx);
687
+ assert.notEqual(queued.isError, true, resultText(queued));
243
688
  assert.equal(host.sent.length, 1);
689
+
690
+ assert.equal(git(repo, ['worktree', 'list', '--porcelain']), listBefore, 'the listing changed');
691
+ assert.equal(
692
+ crypto.createHash('sha256').update(fs.readFileSync(registryPath)).digest('hex'),
693
+ registryBefore,
694
+ 'the registry changed',
695
+ );
696
+ settlePending();
697
+ });
698
+ });
699
+
700
+ // ---------------------------------------------------------------------------
701
+ // The command front: the request stays PENDING and the queue performs the move.
702
+ // ---------------------------------------------------------------------------
703
+ describe('the /warp front queues the move and performs it after the counters drain', () => {
704
+ test('it never switches while an agent task runs, and says the warp is queued', async () => {
705
+ const repo = makeRepo();
706
+ const world = { sessionDir: track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-sessions-'))), created: 0, createdFiles: [] };
707
+ const SM = makeSessionHost(world);
708
+ const switches = [];
709
+ const ctx = makeCtx(repo);
710
+ ctx.sessionManager = Object.assign(new SM(null, null, null), { getSessionId: () => SESSION_ID });
711
+ ctx.sessionManager.constructor = SM;
712
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
713
+ const created = await tools.get('worktree_create').execute('busy-10', { branch: 'feat/cmd', changes: 'none' }, undefined, undefined, ctx);
714
+ assert.notEqual(created.isError, true, resultText(created));
715
+
716
+ publishSession({ running: 2 });
717
+ notifications.length = 0;
718
+ host.sent.length = 0;
719
+ await commands.get('warp').handler('feat-cmd', ctx);
720
+
721
+ assert.equal(switches.length, 0, 'the session must not move under running tasks');
722
+ assert.equal(host.sent.length, 0, 'the command front re-dispatches later, not now');
723
+ assert.equal(notifications.length, 1, JSON.stringify(notifications));
724
+ assert.equal(notifications[0][0], 'info');
725
+ assert.match(
726
+ notifications[0][1],
727
+ /^worktree warp: handoff queued — waiting for 2 running agent task\(s\) before the move/,
728
+ );
729
+ const record = busyLib.pendingWarpFor(pendingKey());
730
+ assert.notEqual(record, null, 'the request is kept pending');
731
+ assert.equal(record.name, 'feat-cmd');
732
+ settlePending();
244
733
  });
245
734
 
246
- test('the command refuses and never switches while an agent task is running', async () => {
735
+ test('the pending warp re-dispatches the same handoff once the counters drain, and the move lands', async () => {
247
736
  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);
737
+ const world = { sessionDir: track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-sessions-'))), created: 0, createdFiles: [] };
738
+ const SM = makeSessionHost(world);
739
+ const switches = [];
740
+ const ctx = makeCtx(repo);
741
+ ctx.sessionManager = Object.assign(new SM(null, null, null), { getSessionId: () => SESSION_ID });
742
+ ctx.sessionManager.constructor = SM;
743
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
744
+ const created = await tools.get('worktree_create').execute('busy-11', { branch: 'feat/drain', changes: 'none' }, undefined, undefined, ctx);
250
745
  assert.notEqual(created.isError, true, resultText(created));
251
746
 
747
+ publishSession({ running: 1, queued: 1 });
748
+ host.sent.length = 0;
749
+ await commands.get('warp').handler('feat-drain', ctx);
750
+ assert.equal(switches.length, 0);
751
+ assert.equal(host.sent.length, 0);
752
+
753
+ // The counters drain: the poller re-dispatches the SAME validated handoff.
754
+ publishSession({ running: 0, queued: 0 });
755
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'dispatched');
756
+ assert.equal(host.sent.length, 1, 'the queued warp re-dispatches itself');
757
+ const [message, options] = host.sent[0];
758
+ assert.deepEqual(options, { expandPromptTemplates: true });
759
+ assert.ok(message.startsWith('/warp @'), `the queued command is /warp (${message})`);
760
+
761
+ // That exact handoff is not a second warp: it performs the queued move.
762
+ notifications.length = 0;
763
+ await commands.get('warp').handler(message.slice('/warp '.length), ctx);
764
+ assert.deepEqual(notifications, [], 'a real move notifies nothing');
765
+ assert.equal(switches.length, 1, 'the queued move landed once the counters drained');
766
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'a move clears the pending record');
767
+
768
+ // A later warp is accepted again.
769
+ host.sent.length = 0;
770
+ const next = await tools.get('worktree_warp').execute('busy-12', { name: 'feat-drain' }, undefined, undefined, ctx);
771
+ assert.notEqual(next.isError, true, resultText(next));
772
+ assert.equal(host.sent.length, 1);
773
+ settlePending();
774
+ });
775
+
776
+ test('a second warp is refused while one is pending, on both fronts', async () => {
777
+ const repo = makeRepo();
778
+ const ctx = makeCtx(repo);
779
+ const first = await tools.get('worktree_create').execute('busy-13', { branch: 'feat/one', changes: 'none' }, undefined, undefined, ctx);
780
+ assert.notEqual(first.isError, true, resultText(first));
781
+ const second = await tools.get('worktree_create').execute('busy-14', { branch: 'feat/two', changes: 'none' }, undefined, undefined, ctx);
782
+ assert.notEqual(second.isError, true, resultText(second));
783
+
252
784
  publishSession({ running: 2 });
253
785
  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');
786
+ await commands.get('warp').handler('feat-one', ctx);
787
+ const queued = busyLib.pendingWarpFor(pendingKey());
788
+ assert.notEqual(queued, null);
789
+
790
+ // The TOOL refuses and queues nothing at all.
791
+ host.sent.length = 0;
792
+ const refusedTool = await tools.get('worktree_warp').execute('busy-15', { name: 'feat-two' }, undefined, undefined, ctx);
793
+ assert.equal(refusedTool.isError, true);
794
+ assert.match(
795
+ resultText(refusedTool),
796
+ /^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$/,
797
+ );
798
+ assert.equal(host.sent.length, 0, 'a refused second warp queues nothing');
799
+
800
+ // The COMMAND front refuses the same way and never switches.
801
+ const switches = [];
802
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
803
+ notifications.length = 0;
804
+ await commands.get('warp').handler('feat-two', ctx);
805
+ assert.equal(switches.length, 0);
256
806
  assert.equal(notifications.length, 1);
257
807
  assert.equal(notifications[0][0], 'error');
258
- assert.match(notifications[0][1], /^worktree warp: this session still has 2 running agent task\(s\)/);
808
+ assert.match(notifications[0][1], /^worktree warp: a warp to feat-one is already pending for this session/);
809
+
810
+ // The pending request is untouched by both refusals.
811
+ const after = busyLib.pendingWarpFor(pendingKey());
812
+ assert.equal(after.name, 'feat-one');
813
+ assert.equal(after.queuedAt, queued.queuedAt);
814
+ settlePending();
259
815
  });
260
816
 
261
- test('an unavailable presence store does not block the command', async () => {
817
+ test('an expired pending warp notices that nothing moved and clears for a later warp', async () => {
262
818
  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);
819
+ const ctx = makeCtx(repo);
820
+ const created = await tools.get('worktree_create').execute('busy-16', { branch: 'feat/expire', changes: 'none' }, undefined, undefined, ctx);
265
821
  assert.notEqual(created.isError, true, resultText(created));
266
822
 
823
+ publishSession({ running: 1 });
824
+ notifications.length = 0;
825
+ const previousBudget = process.env.ODD_WORKTREE_WARP_PENDING_MS;
826
+ process.env.ODD_WORKTREE_WARP_PENDING_MS = '1';
827
+ try {
828
+ await commands.get('warp').handler('feat-expire', ctx);
829
+ } finally {
830
+ process.env.ODD_WORKTREE_WARP_PENDING_MS = previousBudget;
831
+ }
832
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null);
833
+
834
+ const expired = await until(() => notifications.some(([, text]) => /expired .* with nothing moved/.test(String(text))));
835
+ assert.equal(expired, true, `the queue noticed nothing: ${JSON.stringify(notifications)}`);
836
+ const [, text] = notifications.find(([, entry]) => /expired .* with nothing moved/.test(String(entry)));
837
+ assert.match(text, /^worktree warp: the pending warp to feat-expire expired after 1 min with nothing moved/);
838
+ assert.match(text, /agent tasks and background jobs finish/);
839
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'an expired queue is cleared');
840
+
841
+ host.sent.length = 0;
842
+ const next = await tools.get('worktree_warp').execute('busy-17', { name: 'feat-expire' }, undefined, undefined, ctx);
843
+ assert.notEqual(next.isError, true, `a new warp is accepted after expiry: ${resultText(next)}`);
844
+ assert.equal(host.sent.length, 1);
845
+ settlePending();
846
+ });
847
+
848
+ test('a running background job keeps the move pending until the job reports exited', async () => {
849
+ const repo = makeRepo();
850
+ const world = { sessionDir: track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-busy-sessions-'))), created: 0, createdFiles: [] };
851
+ const SM = makeSessionHost(world);
852
+ const switches = [];
853
+ const ctx = makeCtx(repo);
854
+ ctx.sessionManager = Object.assign(new SM(null, null, null), { getSessionId: () => SESSION_ID });
855
+ ctx.sessionManager.constructor = SM;
856
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
857
+ const jobs = addJobs(ctx, [{ id: 'job-1', status: 'running', label: 'Probe de job' }]);
858
+ const created = await tools.get('worktree_create').execute('busy-j20', { branch: 'feat/jobwait', changes: 'none' }, undefined, undefined, ctx);
859
+ assert.notEqual(created.isError, true, resultText(created));
860
+ // No agent task at all: the JOB is the only thing standing in the way.
267
861
  clearPresence();
268
862
  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)}`);
863
+ host.sent.length = 0;
864
+ await commands.get('warp').handler('feat-jobwait', ctx);
865
+
866
+ assert.equal(switches.length, 0, 'the session must not move while a job is running');
867
+ assert.equal(host.sent.length, 0, 'the command front re-dispatches later, not now');
868
+ assert.equal(notifications.length, 1, JSON.stringify(notifications));
869
+ assert.equal(notifications[0][0], 'info');
870
+ assert.match(notifications[0][1], /^worktree warp: handoff queued — waiting for 1 running background job before the move/);
871
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'a running job keeps the request pending');
872
+
873
+ // Still running: the poller waits, and nothing is re-dispatched.
874
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'waiting');
875
+ assert.equal(host.sent.length, 0);
876
+ assert.equal(switches.length, 0);
877
+
878
+ // The job exits: the poller re-dispatches the SAME handoff, and it lands.
879
+ jobs.jobs[0].status = 'exited 0';
880
+ assert.equal((await busyLib.pendingWarpTick(pendingKey())).status, 'dispatched');
881
+ assert.equal(host.sent.length, 1, 'the queued warp re-dispatches itself once the job is finished');
882
+ const [message, options] = host.sent[0];
883
+ assert.deepEqual(options, { expandPromptTemplates: true });
884
+ assert.ok(message.startsWith('/warp @'), `the queued command is /warp (${message})`);
885
+ await commands.get('warp').handler(message.slice('/warp '.length), ctx);
886
+ assert.equal(switches.length, 1, 'the move lands only after the job finished');
887
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'a move clears the pending record');
888
+ });
889
+
890
+ test('a refused queued warp clears the record, so a later warp is accepted', async () => {
891
+ const repo = makeRepo();
892
+ const ctx = makeCtx(repo);
893
+ const created = await tools.get('worktree_create').execute('busy-r1', { branch: 'feat/refused', changes: 'none' }, undefined, undefined, ctx);
894
+ assert.notEqual(created.isError, true, resultText(created));
895
+
896
+ // The tool queues the request while a job runs, so it is pending.
897
+ clearPresence();
898
+ const jobs = addJobs(ctx, [{ id: 'job-3', status: 'running' }]);
899
+ host.sent.length = 0;
900
+ const queued = await tools.get('worktree_warp').execute('busy-r2', { name: 'feat-refused' }, undefined, undefined, ctx);
901
+ assert.notEqual(queued.isError, true, resultText(queued));
902
+ assert.equal(host.sent.length, 1);
903
+ const token = host.sent[0][0];
904
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null);
905
+
906
+ // The job finishes, but the registry is unreadable when the queued warp
907
+ // runs: that is a terminal refusal, so the record must be cleared.
908
+ jobs.jobs[0].status = 'exited 0';
909
+ const registryPath = path.resolve(repo, git(repo, ['rev-parse', '--git-common-dir']), 'pi-worktrees.json');
910
+ fs.writeFileSync(registryPath, 'not json');
911
+ notifications.length = 0;
912
+ await commands.get('warp').handler(token.slice('/warp '.length), ctx);
913
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'a refused queued warp is cleared');
914
+
915
+ // A later warp is accepted again, not blocked by a dead record.
916
+ fs.writeFileSync(registryPath, JSON.stringify({ version: 1, worktrees: [] }));
917
+ host.sent.length = 0;
918
+ const next = await tools.get('worktree_warp').execute('busy-r3', { name: 'feat-refused' }, undefined, undefined, ctx);
919
+ assert.notEqual(next.isError, true, `a new warp is accepted, not refused as pending: ${resultText(next)}`);
920
+ assert.equal(host.sent.length, 1);
921
+ settlePending();
922
+ });
923
+
924
+ test('a handoff token for another checkout is refused while one is pending', async () => {
925
+ const repo = makeRepo();
926
+ const ctx = makeCtx(repo);
927
+ const first = await tools.get('worktree_create').execute('busy-18', { branch: 'feat/held', changes: 'none' }, undefined, undefined, ctx);
928
+ assert.notEqual(first.isError, true, resultText(first));
929
+ const second = await tools.get('worktree_create').execute('busy-19', { branch: 'feat/other', changes: 'none' }, undefined, undefined, ctx);
930
+ assert.notEqual(second.isError, true, resultText(second));
931
+
932
+ // Queue a handoff for feat-other first (idle front), then make the session
933
+ // busy and let the command hold the request.
934
+ clearPresence();
935
+ host.sent.length = 0;
936
+ const handoff = await tools.get('worktree_warp').execute('busy-20', { name: 'feat-other' }, undefined, undefined, ctx);
937
+ assert.notEqual(handoff.isError, true, resultText(handoff));
938
+ assert.equal(host.sent.length, 1);
939
+ const token = host.sent[0][0];
940
+ publishSession({ running: 1 });
941
+ await commands.get('warp').handler(token.slice('/warp '.length), ctx);
942
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the handoff is now pending');
943
+
944
+ // A DIFFERENT handoff (feat-held) is a second warp.
945
+ const heldHandoff = `@${Buffer.from(JSON.stringify({
946
+ v: 1,
947
+ name: 'feat-held',
948
+ target: path.join(repo, '..', 'other-checkout'),
949
+ from: repo,
950
+ branch: 'feat/held',
951
+ }), 'utf8').toString('base64url')}`;
952
+ notifications.length = 0;
953
+ const switches = [];
954
+ ctx.switchSession = async (file) => { switches.push(file); return { cancelled: false }; };
955
+ await commands.get('warp').handler(heldHandoff, ctx);
956
+ assert.equal(switches.length, 0);
957
+ assert.equal(notifications.length, 1);
958
+ assert.match(notifications[0][1], /^worktree warp: a warp to feat-other is already pending for this session/);
959
+ settlePending();
274
960
  });
275
961
  });
276
962
 
277
963
  // ---------------------------------------------------------------------------
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.
964
+ // S4 boundaries: what the queue must NOT block, every entry path, and the
965
+ // surfaces that keep working while this session reports running work.
280
966
  // ---------------------------------------------------------------------------
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
-
967
+ describe('boundaries: negative cases, every front, unaffected surfaces', () => {
285
968
  function writeOtherSession(counts) {
286
969
  fs.mkdirSync(PRESENCE, { recursive: true, mode: 0o700 });
287
970
  fs.chmodSync(PRESENCE, 0o700);
@@ -294,114 +977,76 @@ describe('S4 boundaries: negative cases, every front, unaffected surfaces', () =
294
977
  }), { mode: 0o600 });
295
978
  }
296
979
 
297
- test('the tool queues its handoff when the presence store is absent', async () => {
980
+ test('the tool queues normally when the presence store is absent', async () => {
298
981
  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);
982
+ const ctx = makeCtx(repo);
983
+ const created = await tools.get('worktree_create').execute('busy-21', { branch: 'feat/nostore', changes: 'none' }, undefined, undefined, ctx);
301
984
  assert.notEqual(created.isError, true, resultText(created));
302
985
  clearPresence();
303
986
  host.sent.length = 0;
304
- const queued = await tools.get('worktree_warp').execute('busy-8', { name: 'feat-nostore' }, undefined, undefined, ctx);
987
+ const queued = await tools.get('worktree_warp').execute('busy-22', { name: 'feat-nostore' }, undefined, undefined, ctx);
305
988
  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');
989
+ assert.match(resultText(queued), /^worktree warp: handoff queued — the session moves when this turn ends/);
990
+ assert.equal(host.sent.length, 1, 'an absent store blocks nothing and waits for nothing');
991
+ settlePending();
308
992
  });
309
993
 
310
- test('a stale heartbeat and an unreadable record never block the tool', async () => {
994
+ test('a stale heartbeat and an unreadable record are no evidence of work', async () => {
311
995
  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);
996
+ const ctx = makeCtx(repo);
997
+ const created = await tools.get('worktree_create').execute('busy-23', { branch: 'feat/stale', changes: 'none' }, undefined, undefined, ctx);
314
998
  assert.notEqual(created.isError, true, resultText(created));
315
999
 
316
1000
  publishSession({ running: 3, heartbeat: Date.now() - 600000 });
317
1001
  host.sent.length = 0;
318
- const stale = await tools.get('worktree_warp').execute('busy-10', { name: 'feat-stale' }, undefined, undefined, ctx);
1002
+ const stale = await tools.get('worktree_warp').execute('busy-24', { name: 'feat-stale' }, undefined, undefined, ctx);
319
1003
  assert.notEqual(stale.isError, true, `a stale heartbeat is not evidence: ${resultText(stale)}`);
1004
+ assert.match(resultText(stale), /the session moves when this turn ends/);
320
1005
  assert.equal(host.sent.length, 1);
321
1006
 
322
1007
  publishSession({ running: 3 });
323
1008
  fs.chmodSync(PRESENCE, 0o755);
324
1009
  try {
1010
+ // S6: the first warp is pending, so it reaches its outcome before the
1011
+ // second is accepted (the queue is per session, not per call).
1012
+ settlePending();
325
1013
  host.sent.length = 0;
326
- const unreadable = await tools.get('worktree_warp').execute('busy-11', { name: 'feat-stale' }, undefined, undefined, ctx);
1014
+ const unreadable = await tools.get('worktree_warp').execute('busy-25', { name: 'feat-stale' }, undefined, undefined, ctx);
327
1015
  assert.notEqual(unreadable.isError, true, `an unsafe store is no evidence: ${resultText(unreadable)}`);
328
1016
  assert.equal(host.sent.length, 1);
329
1017
  } finally {
330
1018
  fs.chmodSync(PRESENCE, 0o700);
331
1019
  }
1020
+ settlePending();
332
1021
  });
333
1022
 
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 () => {
1023
+ test('another session’s running tasks never block this session', async () => {
379
1024
  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);
1025
+ const ctx = makeCtx(repo);
1026
+ const created = await tools.get('worktree_create').execute('busy-26', { branch: 'feat/other', changes: 'none' }, undefined, undefined, ctx);
382
1027
  assert.notEqual(created.isError, true, resultText(created));
383
1028
 
384
1029
  clearPresence();
1030
+ writeOtherSession({ running: 5, queued: 3 });
385
1031
  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));
1032
+ const queued = await tools.get('worktree_warp').execute('busy-27', { name: 'feat-other' }, undefined, undefined, ctx);
1033
+ assert.notEqual(queued.isError, true, `a peer's work is not this session's: ${resultText(queued)}`);
1034
+ assert.match(resultText(queued), /the session moves when this turn ends/);
388
1035
  assert.equal(host.sent.length, 1);
389
- const token = host.sent[0][0].replace(/^\/warp /, '');
1036
+ // S6: that request IS this session's one pending warp, so the command front
1037
+ // clears it on its own outcome instead of being treated as a second warp.
1038
+ settlePending();
390
1039
 
391
- publishSession({ running: 2 });
392
1040
  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\)/);
1041
+ await commands.get('warp').handler('feat-other', ctx);
1042
+ assert.deepEqual(notifications.filter(([, text]) => /already pending|handoff queued/.test(String(text))), []);
1043
+ settlePending();
399
1044
  });
400
1045
 
401
- test('the selector pick refuses and never switches while this session is busy', async () => {
1046
+ test('the selector pick is queued, never switched, while this session is busy', async () => {
402
1047
  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);
1048
+ const createCtx = makeCtx(repo);
1049
+ const created = await tools.get('worktree_create').execute('busy-28', { branch: 'feat/pick', changes: 'none' }, undefined, undefined, createCtx);
405
1050
  assert.notEqual(created.isError, true, resultText(created));
406
1051
 
407
1052
  const switches = [];
@@ -428,31 +1073,31 @@ describe('S4 boundaries: negative cases, every front, unaffected surfaces', () =
428
1073
  picks.push('feat-pick');
429
1074
  await commands.get('warp').handler('', ctx);
430
1075
  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);
1076
+ assert.equal(notifications.filter(([, text]) => /handoff queued — waiting for 2 running/.test(String(text))).length, 1);
1077
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the selector pick is kept pending');
1078
+ settlePending();
432
1079
  });
433
1080
 
434
- test('another session’s running tasks never block this session', async () => {
1081
+ test('session shutdown clears the pending warp', async () => {
435
1082
  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);
1083
+ const ctx = makeCtx(repo);
1084
+ const created = await tools.get('worktree_create').execute('busy-sd1', { branch: 'feat/shutdown', changes: 'none' }, undefined, undefined, ctx);
438
1085
  assert.notEqual(created.isError, true, resultText(created));
439
1086
 
440
- clearPresence();
441
- writeOtherSession({ running: 5, queued: 3 });
1087
+ publishSession({ running: 1 });
442
1088
  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);
1089
+ const queued = await tools.get('worktree_warp').execute('busy-sd2', { name: 'feat-shutdown' }, undefined, undefined, ctx);
1090
+ assert.notEqual(queued.isError, true, resultText(queued));
1091
+ assert.notEqual(busyLib.pendingWarpFor(pendingKey()), null, 'the request is pending before shutdown');
446
1092
 
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))), []);
1093
+ for (const [, handler] of hooks.filter(([name]) => name === 'session_shutdown')) {
1094
+ await handler({}, ctx);
1095
+ }
1096
+ assert.equal(busyLib.pendingWarpFor(pendingKey()), null, 'nothing deferred survives its session');
450
1097
  });
451
1098
 
452
- test('list, create and close still work while this session reports running work', async () => {
1099
+ test('list, create and delete still work while this session reports running work', async () => {
453
1100
  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
1101
  const ctx = {
457
1102
  cwd: repo,
458
1103
  hasUI: true,
@@ -467,22 +1112,12 @@ describe('S4 boundaries: negative cases, every front, unaffected surfaces', () =
467
1112
  };
468
1113
  publishSession({ running: 2, queued: 1 });
469
1114
 
470
- const listed = await tools.get('worktree_list').execute('busy-22', {}, undefined, undefined, ctx);
1115
+ const listed = await tools.get('worktree_list').execute('busy-29', {}, undefined, undefined, ctx);
471
1116
  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);
1117
+ const created = await tools.get('worktree_create').execute('busy-30', { branch: 'feat/surface', changes: 'none' }, undefined, undefined, ctx);
473
1118
  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);
1119
+ const closed = await tools.get('worktree_delete').execute('busy-31', { name: 'feat-surface', force: true }, undefined, undefined, ctx);
475
1120
  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);
1121
+ settlePending();
487
1122
  });
488
1123
  });