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.
@@ -10,7 +10,7 @@
10
10
  // /issues read this checkout's GitHub issues, with label/assignee,
11
11
  // comment and close actions when the repository permits them
12
12
  //
13
- // and four tools: worktree_create, worktree_list, worktree_close,
13
+ // and four tools: worktree_create, worktree_list, worktree_delete,
14
14
  // worktree_warp. Create and close prompt for approval when the host offers
15
15
  // dialog UI; list never mutates anything; warp hands the move to /warp.
16
16
  //
@@ -1034,7 +1034,7 @@ async function executeWorktreeCreate(params, ctx, opts) {
1034
1034
 
1035
1035
  // No approval dialog: a create touches no existing data — the checkout and
1036
1036
  // its registry row are both new — and the panel's create path never asked
1037
- // either. The confirmation that matters lives in `worktree_close`.
1037
+ // either. The confirmation that matters lives in `worktree_delete`.
1038
1038
 
1039
1039
  // (g) Create. S20 branch adoption is resolved BEFORE creating: when
1040
1040
  // `refs/heads/<branch>` already exists (and is not checked out at a
@@ -2021,7 +2021,7 @@ async function vanishedCheckouts(git, repoRoot, live, resolvedTarget, after) {
2021
2021
  }
2022
2022
 
2023
2023
  // S24 name resolution — the ONE place checkout names resolve to
2024
- // checkouts. `worktree_close` (by `name`) and the `warp` command verb
2024
+ // checkouts. `worktree_delete` (by `name`) and the `warp` command verb
2025
2025
  // both call this, never separate logic. A name is the flattened branch
2026
2026
  // slug (`slugifyBranch`, already exported by lib/worktree-git.js), or
2027
2027
  // `principal` for the principal checkout.
@@ -2318,7 +2318,7 @@ function closeSessionString(ctx, method) {
2318
2318
  }
2319
2319
  }
2320
2320
 
2321
- // S7/S8/S9: the active-session refusal, shared by `worktree_close` and the warp
2321
+ // S7/S8/S9: the active-session refusal, shared by `worktree_delete` and the warp
2322
2322
  // panel's Ctrl+D (lib/worktree-session-guard.js).
2323
2323
  //
2324
2324
  // The guard answers one question per checkout: is a live Pi session working
@@ -2442,7 +2442,7 @@ async function yoloActiveFor(ctx) {
2442
2442
  }
2443
2443
  }
2444
2444
 
2445
- // Core of `worktree_close` (S7, D6, S6-S9): remove the checkout, keep the
2445
+ // Core of `worktree_delete` (S7, D6, S6-S9): remove the checkout, keep the
2446
2446
  // branch, drop the registry entry. Exported for unit tests; the registered tool
2447
2447
  // calls it with the live Pi context, and the warp panel's Ctrl+D calls it with
2448
2448
  // `opts.approved` after its own question.
@@ -2474,7 +2474,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2474
2474
  const hasName = typeof rawName === "string" && rawName.length > 0;
2475
2475
  if (!hasPath && !hasBranch && !hasName) {
2476
2476
  return errorResult(
2477
- "worktree_close requires a path or a branch or a name: pass the worktree path, branch, or name to close",
2477
+ "worktree_delete requires a path or a branch or a name: pass the worktree path, branch, or name to close",
2478
2478
  { force },
2479
2479
  );
2480
2480
  }
@@ -2483,7 +2483,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2483
2483
  // agree-or-disagree behaviour below.)
2484
2484
  if (hasName && (hasPath || hasBranch)) {
2485
2485
  return errorResult(
2486
- "worktree_close accepts only one of path, branch, or name: pass only one",
2486
+ "worktree_delete accepts only one of path, branch, or name: pass only one",
2487
2487
  { path: rawPath, branch: rawBranch, name: rawName, force },
2488
2488
  );
2489
2489
  }
@@ -2504,7 +2504,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2504
2504
  const byBranch = hasBranch && !hasName ? registry.findByBranch(repo.root, rawBranch) : null;
2505
2505
  if (hasPath && hasBranch && byPath && byBranch && byPath.branch !== byBranch.branch) {
2506
2506
  return errorResult(
2507
- `worktree_close path and branch disagree: path resolves to branch '${byPath.branch}' but branch '${rawBranch}' is registered elsewhere; pass only one`,
2507
+ `worktree_delete path and branch disagree: path resolves to branch '${byPath.branch}' but branch '${rawBranch}' is registered elsewhere; pass only one`,
2508
2508
  { path: rawPath, branch: rawBranch, force },
2509
2509
  );
2510
2510
  }
@@ -2537,7 +2537,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2537
2537
  }
2538
2538
  } else if (resolved.kind === "principal") {
2539
2539
  return errorResult(
2540
- `cannot close the principal checkout at ${resolved.path}: worktree_close only closes registered agent worktrees; the checkout and the registry were left untouched`,
2540
+ `cannot close the principal checkout at ${resolved.path}: worktree_delete only closes registered agent worktrees; the checkout and the registry were left untouched`,
2541
2541
  { name: rawName, path: resolved.path, branch: resolved.branch, force },
2542
2542
  );
2543
2543
  } else {
@@ -2555,7 +2555,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2555
2555
  const pid = pst.real !== null ? pst.real : pst.absolute;
2556
2556
  if (entryId !== null && pid !== null && entryId === pid) {
2557
2557
  return errorResult(
2558
- `cannot close the principal checkout at ${principalRef.path}: worktree_close only closes registered agent worktrees; the checkout and the registry were left untouched`,
2558
+ `cannot close the principal checkout at ${principalRef.path}: worktree_delete only closes registered agent worktrees; the checkout and the registry were left untouched`,
2559
2559
  { name: rawName, path: principalRef.path, branch: principalRef.branch, force },
2560
2560
  );
2561
2561
  }
@@ -2633,7 +2633,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2633
2633
  // is invoked. Without that, a path replaced by a symbolic link while the
2634
2634
  // human answered would be handed to `git worktree remove`, which resolves the
2635
2635
  // spelling it is given and would name ANOTHER checkout. No tool reaches this:
2636
- // `worktree_close` calls this function without options.
2636
+ // `worktree_delete` calls this function without options.
2637
2637
  const expectedReal = opts && typeof opts.expectedReal === "string" && opts.expectedReal.length > 0
2638
2638
  ? opts.expectedReal
2639
2639
  : null;
@@ -2700,7 +2700,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2700
2700
  // selector's keyboard delete, which never consults YOLO at all
2701
2701
  // (`warpDeleteCheckout`). It suppresses the second dialog only: every check
2702
2702
  // above and below, the live-session protections and the removal itself are
2703
- // unchanged, and no tool can reach this flag because `worktree_close` calls
2703
+ // unchanged, and no tool can reach this flag because `worktree_delete` calls
2704
2704
  // this function without options.
2705
2705
  const alreadyApproved = !!(opts && opts.approved === true);
2706
2706
  if (ctx && ctx.hasUI && !alreadyApproved) {
@@ -2741,7 +2741,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2741
2741
  }
2742
2742
  if (!approved) {
2743
2743
  return errorResult(
2744
- `worktree close cancelled: approval declined for branch '${branch}'`,
2744
+ `worktree delete cancelled: approval declined for branch '${branch}'`,
2745
2745
  { cancelled: true, branch, path: target, force },
2746
2746
  );
2747
2747
  }
@@ -2923,15 +2923,15 @@ const worktreeListTool = withWorktreeCardRenderer(defineTool({
2923
2923
  }));
2924
2924
 
2925
2925
  const worktreeCloseTool = withWorktreeCardRenderer(defineTool({
2926
- name: "worktree_close",
2927
- label: "Worktree Close",
2926
+ name: "worktree_delete",
2927
+ label: "Worktree Delete",
2928
2928
  exposure: "codemode",
2929
- description: "Remove a registered agent worktree checkout while keeping the branch. Pass the worktree name, path, or branch (only one), plus force:true to close a dirty checkout. A live Pi session working in that checkout — this session or another — refuses the close: warp to another checkout first, or let that session finish. The checkout is removed with git; no Herdr workspace is closed, opened or removed.",
2929
+ description: "Remove a registered agent worktree checkout while keeping the branch. Pass the worktree name, path, or branch (only one), plus force:true to delete a dirty checkout. A live Pi session working in that checkout — this session or another — refuses the deletion: warp to another checkout first, or let that session finish. The checkout is removed with git; no Herdr workspace is closed, opened or removed.",
2930
2930
  parameters: Type.Object({
2931
- name: opt(Type.String({ description: "Name of the registered worktree to close (the flattened branch slug, or principal)" })),
2932
- path: opt(Type.String({ description: "Path of the registered worktree to close" })),
2933
- branch: opt(Type.String({ description: "Branch of the registered worktree to close" })),
2934
- force: opt(Type.Boolean({ description: "Close even when the checkout is dirty" })),
2931
+ name: opt(Type.String({ description: "Name of the registered worktree to delete (the flattened branch slug, or principal)" })),
2932
+ path: opt(Type.String({ description: "Path of the registered worktree to delete" })),
2933
+ branch: opt(Type.String({ description: "Branch of the registered worktree to delete" })),
2934
+ force: opt(Type.Boolean({ description: "Delete even when the checkout is dirty" })),
2935
2935
  }),
2936
2936
  async execute(toolCallId, params, signal, onUpdate, ctx) {
2937
2937
  return executeWorktreeClose(params, ctx);
@@ -3471,6 +3471,16 @@ async function executeWorktreeWarpTool(params, ctx, opts) {
3471
3471
  const warpSessions = libRequire("worktree-warp-sessions.js");
3472
3472
  const raw = params && typeof params.name === "string" ? params.name.trim() : "";
3473
3473
  const fromCwd = toolCwd(ctx);
3474
+ // S5: one pending warp per session. While one waits, a second request is
3475
+ // REFUSED here — before anything is resolved, copied or queued — and the
3476
+ // pending request is never disturbed: it is the move someone already asked
3477
+ // for, and the refusal says where it stands.
3478
+ const pendingGate = warpPendingGate(ctx, fromCwd, null);
3479
+ if (pendingGate.pending) {
3480
+ return errorResult(`worktree warp: ${warpPendingRefusalText(pendingGate.pending, raw)}`, {
3481
+ tool: "worktree_warp", name: raw, pending: true,
3482
+ });
3483
+ }
3474
3484
  // S21: the warp is interactive too, so its preflight reads are awaited.
3475
3485
  const runAsync = libRunner(git);
3476
3486
  let repo;
@@ -3665,46 +3675,72 @@ async function executeWorktreeWarpTool(params, ctx, opts) {
3665
3675
  // `fromName`/`name`/`path`/`branch`), so the card falls back to that line
3666
3676
  // instead of painting a move that has not happened. The one visible "moved"
3667
3677
  // card comes from the switched-to session once the move is real.
3668
- // S4: this session's own background work is a refusal, not a queue. The
3669
- // command that performs the move waits for idle — and a session with running
3670
- // agent tasks IS idle — so queueing here would move the session out from
3671
- // under work that is still running. Nothing is queued when this refuses.
3672
- const toolBusy = await warpSessionActivity(ctx);
3673
- if (toolBusy && toolBusy.busy === true) {
3674
- return errorResult(`worktree warp: ${warpBusyText(toolBusy)}`, {
3675
- tool: "worktree_warp", name: displayName, path: targetCwd, branch: displayBranch,
3676
- kind: resolved.kind, busy: true,
3677
- });
3678
- }
3679
- const handoffDispatched = dispatchWarpHandoff(prepareWarpHandoff({
3678
+ // S5/S9: this session's own workloads no longer refuse the handoff — the
3679
+ // request is QUEUED exactly as it is when idle, and the command's pending warp
3680
+ // performs the move once no agent task and no background job is running. What
3681
+ // this tool reports is always the QUEUE, never a move: the idle wording is
3682
+ // byte-identical to before, a busy session gets the waiting line naming both
3683
+ // workloads, and the `queue:` line appears only when the job state could not
3684
+ // be read at all.
3685
+ const toolActivity = await warpSessionActivity(ctx);
3686
+ const toolBusy = !!(toolActivity && toolActivity.busy === true);
3687
+ const preparedToolHandoff = prepareWarpHandoff({
3680
3688
  name: displayName,
3681
3689
  target: targetCwd,
3682
3690
  from: fromCwd,
3683
3691
  branch: displayBranch,
3684
3692
  changes: toolChanges,
3685
- }));
3693
+ });
3694
+ if (!preparedToolHandoff.ok) {
3695
+ return errorResult(
3696
+ `worktree warp: ${preparedToolHandoff.error}`,
3697
+ { tool: "worktree_warp", name: displayName, path: targetCwd, branch: displayBranch, kind: resolved.kind, alreadyThere: false, cancelled: false },
3698
+ );
3699
+ }
3700
+ // S6: the request becomes this session's ONE pending warp at QUEUE time, not
3701
+ // when the command finally runs, so a second `worktree_warp` in the same turn
3702
+ // meets the gate above instead of queueing another handoff. The record is
3703
+ // created only after every validation above passed, so a request refused for
3704
+ // another reason queues nothing, and every terminal outcome on the command
3705
+ // front (moved, refused, cancelled, expired, shutdown) clears this same record.
3706
+ const toolQueue = warpQueuePending({ ctx, fromCwd, name: displayName, prepared: preparedToolHandoff });
3707
+ if (!toolQueue.ok && toolQueue.pending) {
3708
+ return errorResult(`worktree warp: ${warpPendingRefusalText(toolQueue.pending, raw)}`, {
3709
+ tool: "worktree_warp", name: raw, pending: true,
3710
+ });
3711
+ }
3712
+ const handoffDispatched = dispatchWarpHandoff(preparedToolHandoff);
3686
3713
  if (!handoffDispatched.ok) {
3714
+ // Nothing was handed off, so nothing may stay pending.
3715
+ if (toolQueue.ok && toolQueue.pending) warpSettlePending(toolQueue.pending.key);
3687
3716
  return errorResult(
3688
3717
  `worktree warp: ${handoffDispatched.error}`,
3689
3718
  { tool: "worktree_warp", name: displayName, path: targetCwd, branch: displayBranch, kind: resolved.kind, alreadyThere: false, cancelled: false },
3690
3719
  );
3691
3720
  }
3721
+ if (toolQueue.ok && toolQueue.pending) warpMarkDispatched(toolQueue.pending.key);
3692
3722
  const changesNote = toolChanges.mode === "all"
3693
3723
  ? "\nchanges: all (copied when the move lands)"
3694
3724
  : toolChanges.mode === "paths"
3695
3725
  ? `\nchanges: ${toolChanges.paths.length} file${toolChanges.paths.length === 1 ? "" : "s"} (copied when the move lands)`
3696
3726
  : "";
3697
- const pendingText =
3698
- `worktree warp: handoff queued — the session moves when this turn ends\n` +
3699
- `to: ${warpClean(displayName, "worktree")}\n` +
3700
- `path: ${warpClean(targetCwd, "(unknown checkout)")}\n` +
3701
- `branch: ${warpClean(displayBranch, "(detached)")}${changesNote}`;
3727
+ const jobsNote = toolBusy ? warpJobsUnknownText(toolActivity) : "";
3728
+ const pendingText = [
3729
+ toolBusy
3730
+ ? `worktree warp: ${warpQueuedText(toolActivity)}`
3731
+ : "worktree warp: handoff queued — the session moves when this turn ends",
3732
+ `to: ${warpClean(displayName, "worktree")}`,
3733
+ `path: ${warpClean(targetCwd, "(unknown checkout)")}`,
3734
+ `branch: ${warpClean(displayBranch, "(detached)")}${changesNote}`,
3735
+ ...(jobsNote.length > 0 ? [`queue: ${jobsNote}`] : []),
3736
+ ].join("\n");
3702
3737
  return textResult(
3703
3738
  pendingText,
3704
3739
  {
3705
3740
  tool: "worktree_warp", handoff: true, pending: true,
3706
3741
  pendingName: displayName, pendingPath: targetCwd, pendingBranch: displayBranch,
3707
3742
  from: fromCwd, target: targetCwd, kind: resolved.kind,
3743
+ ...(toolBusy ? { busy: true, queued: true } : {}),
3708
3744
  },
3709
3745
  false,
3710
3746
  );
@@ -4092,12 +4128,33 @@ async function sessionManagerClassFor(ctx) {
4092
4128
  return null;
4093
4129
  }
4094
4130
 
4095
- // S4: THIS session's own agent-task counters, read from the presence store the
4096
- // close guard already consumes (lib/worktree-warp-busy.js). Best effort: an
4097
- // absent module or store answers null and blocks nothing. Background jobs are
4098
- // NOT covered — gentle-shell keeps them in memory and publishes no durable
4099
- // evidence — so nothing here claims to see one.
4100
- async function warpSessionActivity(ctx) {
4131
+ // S4/S9: THIS session's own workloads — its agent-task counters, read from the
4132
+ // presence store the close guard already consumes, and its background jobs, read
4133
+ // through the host's `job_list` tool (lib/worktree-warp-busy.js). Both are one
4134
+ // answer: `busy` is true while an agent task runs or queues OR a job runs.
4135
+ //
4136
+ // The host seam is the one `session-worktree-register.js` already uses:
4137
+ // `ctx.tools` names `job_list` and `ctx.executeTool` calls it. Only those two
4138
+ // members are kept for a queued warp's lifetime, so a 30-minute record pins one
4139
+ // host method (and a projected tool list) instead of the whole command context.
4140
+ // A host without the tool answers `unknown` and blocks nothing.
4141
+ function warpJobHost(ctx) {
4142
+ try {
4143
+ if (!ctx || typeof ctx.executeTool !== "function") return null;
4144
+ const tools = Array.isArray(ctx.tools) ? ctx.tools : null;
4145
+ if (tools === null) return null;
4146
+ const executeTool = ctx.executeTool;
4147
+ return {
4148
+ tools: tools.map((tool) => ({ name: tool && typeof tool.name === "string" ? tool.name : "" })),
4149
+ executeTool: (name, args) => executeTool.call(ctx, name, args),
4150
+ };
4151
+ } catch {
4152
+ return null;
4153
+ }
4154
+ }
4155
+
4156
+ async function warpSessionActivityById(sessionId, host) {
4157
+ if (typeof sessionId !== "string" || sessionId.length === 0) return null;
4101
4158
  let lib = null;
4102
4159
  try {
4103
4160
  lib = libRequire("worktree-warp-busy.js");
@@ -4105,25 +4162,182 @@ async function warpSessionActivity(ctx) {
4105
4162
  return null;
4106
4163
  }
4107
4164
  if (!lib || typeof lib.sessionActivity !== "function") return null;
4108
- const sessionId = closeSessionString(ctx, "getSessionId");
4109
4165
  try {
4110
- return await lib.sessionActivity({ sessionId });
4166
+ return await lib.sessionActivity({ sessionId, host: host || null });
4111
4167
  } catch {
4112
4168
  return null;
4113
4169
  }
4114
4170
  }
4115
4171
 
4116
- // The one refusal sentence, from the same module that produced the counters. A
4117
- // missing module falls back to a shorter sentence that still names agent tasks
4118
- // only.
4119
- function warpBusyText(activity) {
4172
+ function warpSessionActivity(ctx) {
4173
+ return warpSessionActivityById(closeSessionString(ctx, "getSessionId"), warpJobHost(ctx));
4174
+ }
4175
+
4176
+ // S5: the queue texts come from the module that produced the counters, so the
4177
+ // tool result, the command notice and the expiry notice cannot drift apart. A
4178
+ // missing module falls back to the same sentences.
4179
+ function warpQueuedText(activity) {
4180
+ try {
4181
+ const lib = libRequire("worktree-warp-busy.js");
4182
+ if (lib && typeof lib.queuedText === "function") return lib.queuedText(activity);
4183
+ } catch {
4184
+ // fall through to the fixed sentence
4185
+ }
4186
+ return "handoff queued — waiting for this session's agent tasks and background jobs before the move";
4187
+ }
4188
+
4189
+ // The one line a queued answer adds when, and only when, the job state was
4190
+ // unreadable. An empty string means both workloads were seen.
4191
+ function warpJobsUnknownText(activity) {
4120
4192
  try {
4121
4193
  const lib = libRequire("worktree-warp-busy.js");
4122
- if (lib && typeof lib.busyText === "function") return lib.busyText(activity);
4194
+ if (lib && typeof lib.jobsUnknownText === "function") return lib.jobsUnknownText(activity);
4123
4195
  } catch {
4124
4196
  // fall through to the fixed sentence
4125
4197
  }
4126
- return "this session still has running agent tasks: the warp waits for them to finish (as of the last published heartbeat); background jobs are not visible here, so confirm they finished too";
4198
+ return "";
4199
+ }
4200
+
4201
+ function warpPendingRefusalText(pending, requestedName) {
4202
+ try {
4203
+ const lib = libRequire("worktree-warp-busy.js");
4204
+ if (lib && typeof lib.pendingWarpRefusalText === "function") return lib.pendingWarpRefusalText(pending, requestedName);
4205
+ } catch {
4206
+ // fall through to the fixed sentence
4207
+ }
4208
+ const name = pending && typeof pending.name === "string" && pending.name.length > 0 ? pending.name : "that checkout";
4209
+ return `a warp to ${name} is already pending for this session — it runs when the pending agent tasks finish; wait for it or let it expire`;
4210
+ }
4211
+
4212
+ // S5: the ONE pending-warp gate. Both fronts ask it, keyed by the session id
4213
+ // (falling back to the checkout the session stands in) so the tool and the
4214
+ // command can never disagree about whether a warp is queued. `retry` is true
4215
+ // only for the pending request's OWN re-dispatched handoff, which must not be
4216
+ // refused as a second warp.
4217
+ function warpPendingGate(ctx, fromCwd, handoff) {
4218
+ const empty = { key: null, pending: null, retry: false };
4219
+ let lib = null;
4220
+ try {
4221
+ lib = libRequire("worktree-warp-busy.js");
4222
+ } catch {
4223
+ return empty;
4224
+ }
4225
+ if (!lib || typeof lib.pendingKeyFor !== "function" || typeof lib.pendingWarpFor !== "function") return empty;
4226
+ let key = null;
4227
+ try {
4228
+ key = lib.pendingKeyFor({ sessionId: closeSessionString(ctx, "getSessionId"), root: fromCwd });
4229
+ } catch {
4230
+ return empty;
4231
+ }
4232
+ if (key === null) return empty;
4233
+ const pending = lib.pendingWarpFor(key);
4234
+ if (!pending) return { key, pending: null, retry: false };
4235
+ let retry = false;
4236
+ try {
4237
+ retry = handoff !== null
4238
+ && handoff !== undefined
4239
+ && typeof lib.sameWarpHandoff === "function"
4240
+ && lib.sameWarpHandoff(pending.handoff, handoff) === true;
4241
+ } catch {
4242
+ retry = false;
4243
+ }
4244
+ return { key, pending, retry };
4245
+ }
4246
+
4247
+ // Hold the validated handoff as this session's one pending warp and start its
4248
+ // poller, which re-dispatches the SAME token through `ctx`-free closures (a
4249
+ // 30-minute queue must not pin a command context). Never throws; `ok:false`
4250
+ // with `pending` means another request got there first, and `ok:false` alone
4251
+ // means this process cannot hold a queue at all.
4252
+ function warpQueuePending({ ctx, fromCwd, name, prepared }) {
4253
+ let lib = null;
4254
+ try {
4255
+ lib = libRequire("worktree-warp-busy.js");
4256
+ } catch {
4257
+ return { ok: false };
4258
+ }
4259
+ if (!lib || typeof lib.queuePendingWarp !== "function" || typeof lib.pendingKeyFor !== "function") return { ok: false };
4260
+ const sessionId = closeSessionString(ctx, "getSessionId");
4261
+ const host = warpJobHost(ctx);
4262
+ let key = null;
4263
+ try {
4264
+ key = lib.pendingKeyFor({ sessionId, root: fromCwd });
4265
+ } catch {
4266
+ return { ok: false };
4267
+ }
4268
+ if (key === null) return { ok: false };
4269
+ // Only the bound notifier is captured: the queue outlives this invocation, and
4270
+ // a 30-minute record must not pin the whole command context (nor anything it
4271
+ // reaches through) just to report an expiry.
4272
+ const ui = ctx && ctx.ui && typeof ctx.ui.notify === "function" ? ctx.ui : null;
4273
+ try {
4274
+ return lib.queuePendingWarp({
4275
+ key,
4276
+ name,
4277
+ token: prepared.token,
4278
+ handoff: prepared.request,
4279
+ env: process.env,
4280
+ host,
4281
+ read: () => warpSessionActivityById(sessionId, host),
4282
+ dispatch: (queuedHandoff) => {
4283
+ const reprepared = prepareWarpHandoff(queuedHandoff);
4284
+ if (!reprepared.ok) return { ok: false, error: reprepared.error };
4285
+ return dispatchWarpHandoff(reprepared);
4286
+ },
4287
+ notify: ui
4288
+ ? (text, level) => { try { ui.notify(text, level); } catch { /* a dead UI never fails the queue */ } }
4289
+ : null,
4290
+ });
4291
+ } catch {
4292
+ return { ok: false };
4293
+ }
4294
+ }
4295
+
4296
+ function warpSettlePending(key) {
4297
+ if (typeof key !== "string" || key.length === 0) return;
4298
+ try {
4299
+ const lib = libRequire("worktree-warp-busy.js");
4300
+ if (lib && typeof lib.settlePendingWarp === "function") lib.settlePendingWarp(key);
4301
+ } catch {
4302
+ // Nothing to clear without the module that holds the queue.
4303
+ }
4304
+ }
4305
+
4306
+ function warpResumePending(key) {
4307
+ if (typeof key !== "string" || key.length === 0) return;
4308
+ try {
4309
+ const lib = libRequire("worktree-warp-busy.js");
4310
+ if (lib && typeof lib.resumePendingWarp === "function") lib.resumePendingWarp(key);
4311
+ } catch {
4312
+ // The dispatched retry settles or expires on its own.
4313
+ }
4314
+ }
4315
+
4316
+ // The tool front already handed its request to the command: the record it just
4317
+ // created only has to refuse a second warp and wait for that dispatch to settle
4318
+ // (or expire), never to send a second copy of the same handoff.
4319
+ function warpMarkDispatched(key) {
4320
+ if (typeof key !== "string" || key.length === 0) return;
4321
+ try {
4322
+ const lib = libRequire("worktree-warp-busy.js");
4323
+ if (lib && typeof lib.markPendingWarpDispatched === "function") lib.markPendingWarpDispatched(key);
4324
+ } catch {
4325
+ // Without the module the queue does not exist, so there is nothing to mark.
4326
+ }
4327
+ }
4328
+
4329
+ // Nothing deferred survives its session: a queued warp dies with the session
4330
+ // that asked for it, so no timer outlives the context it would move.
4331
+ function forgetPendingWarp(ctx) {
4332
+ try {
4333
+ const lib = libRequire("worktree-warp-busy.js");
4334
+ if (!lib || typeof lib.pendingKeyFor !== "function" || typeof lib.settlePendingWarp !== "function") return;
4335
+ const root = ctx && typeof ctx.cwd === "string" && ctx.cwd.length > 0 ? ctx.cwd : null;
4336
+ const key = lib.pendingKeyFor({ sessionId: closeSessionString(ctx, "getSessionId"), root });
4337
+ if (key !== null) lib.settlePendingWarp(key);
4338
+ } catch {
4339
+ // A shutdown never fails on bookkeeping.
4340
+ }
4127
4341
  }
4128
4342
 
4129
4343
  // The COMMAND front's bounded wait: a warp lands after this turn settles, so it
@@ -4142,7 +4356,7 @@ async function warpWaitForIdleSession(ctx) {
4142
4356
  try {
4143
4357
  // The budget travels through the environment so a session can bound its own
4144
4358
  // wait (ODD_WORKTREE_WARP_BUSY_WAIT_MS); the default keeps a warp short.
4145
- return await lib.waitForSessionActivity({ sessionId, env: process.env });
4359
+ return await lib.waitForSessionActivity({ sessionId, env: process.env, host: warpJobHost(ctx) });
4146
4360
  } catch {
4147
4361
  return null;
4148
4362
  }
@@ -4460,7 +4674,62 @@ async function warpMaybeCopyDirty({ ctx, git, fromCheckout, targetCwd, options }
4460
4674
  }
4461
4675
  return { ok: true, copied };
4462
4676
  }
4677
+ // S5: the change selection a QUEUED human warp carries. A queued handoff cannot
4678
+ // prompt (the command's handoff path never asks), so the same YES COPY / NO COPY
4679
+ // question the idle warp asks is answered NOW and travels in the token; the copy
4680
+ // itself still runs at move time inside the command. Cancelling queues nothing.
4681
+ // Never throws.
4682
+ async function warpQueuedChangesSelection({ ctx, git, fromCheckout, skipPrompt, options }) {
4683
+ const none = { ok: true, changes: { mode: 'none', paths: [] } };
4684
+ if (skipPrompt === true) return none;
4685
+ let changesLib = null;
4686
+ try {
4687
+ changesLib = libRequire('worktree-changes.js');
4688
+ } catch {
4689
+ return none;
4690
+ }
4691
+ let summary;
4692
+ try {
4693
+ summary = await changesLib.summarizeChanges(fromCheckout, { git });
4694
+ } catch {
4695
+ return none;
4696
+ }
4697
+ if (!summary || summary.ok !== true || summary.files === 0) return none;
4698
+ const summaryLine = `${summary.files} file${summary.files === 1 ? '' : 's'}, +${summary.added}/-${summary.deleted}`;
4699
+ const choice = await askWarpDirtyChoice(ctx, summaryLine, options);
4700
+ if (choice === null) return { cancelled: true };
4701
+ return choice === 'yes'
4702
+ ? { ok: true, changes: { mode: 'all', paths: [] } }
4703
+ : none;
4704
+ }
4705
+
4706
+ // S5: the ONE warp gate every front shares (the tool's queued handoff, a typed
4707
+ // `/warp <name>`, the selector pick and a create's follow-up warp). While a
4708
+ // pending warp exists, a SECOND request is refused here — it queues nothing,
4709
+ // switches nothing and never touches the pending request. The pending retry is
4710
+ // recognised by its own handoff, so the re-dispatched `/warp @<token>` runs, and
4711
+ // every terminal outcome (moved, refused, cancelled) clears the record so a
4712
+ // later warp is accepted again. A retry that finds the counters busy again
4713
+ // resumes the queue instead of settling it.
4463
4714
  async function executeWorktreeWarp(rawName, ctx, opts) {
4715
+ const options = opts || {};
4716
+ const gate = warpPendingGate(ctx, toolCwd(ctx), normalizeWarpHandoff(options.handoff));
4717
+ if (gate.pending && gate.retry !== true) {
4718
+ return warpFail(`worktree warp: ${warpPendingRefusalText(gate.pending, rawName)}`, {
4719
+ name: typeof rawName === "string" ? rawName.trim() : "",
4720
+ alreadyThere: false, cancelled: false, pending: true,
4721
+ });
4722
+ }
4723
+ const out = await performWorktreeWarp(rawName, ctx, options, gate.retry === true);
4724
+ if (out && out.stillQueued === true) {
4725
+ if (gate.pending && gate.key !== null) warpResumePending(gate.key);
4726
+ return out;
4727
+ }
4728
+ if (gate.key !== null) warpSettlePending(gate.key);
4729
+ return out;
4730
+ }
4731
+
4732
+ async function performWorktreeWarp(rawName, ctx, opts, retry) {
4464
4733
  const options = opts || {};
4465
4734
  const git = libRequire("worktree-git.js");
4466
4735
  const registry = libRequire("worktree-registry.js");
@@ -4490,17 +4759,14 @@ async function executeWorktreeWarp(rawName, ctx, opts) {
4490
4759
  );
4491
4760
  }
4492
4761
  await ctx.waitForIdle();
4493
- // S4: a session with running agent tasks is IDLE for the host, so the wait
4494
- // above does not wait for that work. This front gives the published counters
4495
- // a bounded chance to drain and then refuses instead of moving the session
4496
- // out from under a task that is still running. A store that is absent or
4497
- // unreadable blocks nothing.
4762
+ // S4/S5: a session with running agent tasks is IDLE for the host, so the wait
4763
+ // above does not wait for that work. This front gives the published counters a
4764
+ // bounded chance to drain (ODD_WORKTREE_WARP_BUSY_WAIT_MS) and QUEUES the
4765
+ // request when they have not: nothing switches under work that is still
4766
+ // running, and the queued handoff is performed once the counters drain. A
4767
+ // store that is absent or unreadable blocks nothing.
4498
4768
  const busyWait = await warpWaitForIdleSession(ctx);
4499
- if (busyWait && busyWait.activity && busyWait.activity.busy === true) {
4500
- return warpFail(`worktree warp: ${warpBusyText(busyWait.activity)}`, {
4501
- name, alreadyThere: false, cancelled: false, busy: true,
4502
- });
4503
- }
4769
+ const sessionLoad = busyWait && busyWait.activity ? busyWait.activity : null;
4504
4770
  const fromCwd = typeof ctx.cwd === "string" && ctx.cwd.length > 0 ? ctx.cwd : process.cwd();
4505
4771
  // S21: the same awaited preflight reads as the tool, so a slow repository
4506
4772
  // never freezes the session that is being moved.
@@ -4618,6 +4884,92 @@ async function executeWorktreeWarp(rawName, ctx, opts) {
4618
4884
  // through `failAfterCopy` (below) and why a retry must prove the copied state
4619
4885
  // byte for byte before it skips anything.
4620
4886
  const dirtyFrom = warpDeepestContaining(sessionId, warpLiveIdentities(live, repo.root)) || fromCwd;
4887
+ // S5: the QUEUED warp. This session still reports running or queued agent
4888
+ // tasks, so nothing switches: the request is validated and kept as this
4889
+ // session's one pending warp, and lib/worktree-warp-busy.js re-dispatches the
4890
+ // SAME handoff once the counters drain. What this returns says queued, never
4891
+ // moved, and says plainly that only this session's agent-task counters drain
4892
+ // the queue.
4893
+ if (sessionLoad && sessionLoad.busy === true) {
4894
+ const queuedSelection = handoff
4895
+ ? { ok: true, changes: handoff.changes }
4896
+ : await warpQueuedChangesSelection({
4897
+ ctx, git, fromCheckout: dirtyFrom, skipPrompt: skipDirtyPrompt, options: opts,
4898
+ });
4899
+ if (queuedSelection.cancelled === true) {
4900
+ return warpFail(
4901
+ `worktree warp: ${name} cancelled (the session stays in ${fromCwd})`,
4902
+ { name, alreadyThere: false, cancelled: true },
4903
+ );
4904
+ }
4905
+ const queuedHandoff = prepareWarpHandoff({
4906
+ name: displayName,
4907
+ target: targetCwd,
4908
+ from: fromCwd,
4909
+ branch: displayBranch,
4910
+ changes: queuedSelection.changes,
4911
+ });
4912
+ if (!queuedHandoff.ok) {
4913
+ return warpFail(`worktree warp: ${queuedHandoff.error}`, { name, alreadyThere: false, cancelled: false });
4914
+ }
4915
+ const queued = warpQueuePending({ ctx, fromCwd, name: displayName, prepared: queuedHandoff });
4916
+ // Both workloads are named in the queue text; the extra line appears only
4917
+ // when the job state could not be read at all.
4918
+ const queuedJobsNote = warpJobsUnknownText(sessionLoad);
4919
+ const queuedLines = [
4920
+ `worktree warp: ${warpQueuedText(sessionLoad)}`,
4921
+ ...(queuedJobsNote.length > 0 ? [`queue: ${queuedJobsNote}`] : []),
4922
+ ];
4923
+ if (!queued.ok && queued.pending) {
4924
+ // This IS the pending retry and the workloads filled up again: keep the
4925
+ // queue (the wrapper resumes its poller) instead of refusing our own move.
4926
+ if (retry === true) {
4927
+ return {
4928
+ text: queuedLines.join("\n"),
4929
+ details: {
4930
+ name: displayName, path: targetCwd, branch: displayBranch, kind: resolved.kind,
4931
+ alreadyThere: false, cancelled: false, busy: true, queued: true, pending: true,
4932
+ },
4933
+ stillQueued: true,
4934
+ };
4935
+ }
4936
+ return warpFail(`worktree warp: ${warpPendingRefusalText(queued.pending, name)}`, {
4937
+ name, alreadyThere: false, cancelled: false, pending: true,
4938
+ });
4939
+ }
4940
+ if (!queued.ok) {
4941
+ return warpFail(
4942
+ "worktree warp: this session still has running agent tasks or background jobs and this host cannot hold a queued warp; nothing moved — warp again when they finish",
4943
+ { name, alreadyThere: false, cancelled: false, busy: true },
4944
+ );
4945
+ }
4946
+ // A human front is told ONCE that the request is queued (a handoff already
4947
+ // reported itself in the tool result); the queue's own notice covers expiry
4948
+ // later. The retry says nothing, so one queued warp makes one notice.
4949
+ if (!handoff && ctx && ctx.ui && typeof ctx.ui.notify === "function") {
4950
+ try {
4951
+ ctx.ui.notify(queuedLines.join("; "), "info");
4952
+ } catch {
4953
+ // A dead UI never fails the queue.
4954
+ }
4955
+ }
4956
+ const queuedChangesNote = queuedSelection.changes && queuedSelection.changes.mode === "all"
4957
+ ? "\nchanges: all (copied when the move lands)"
4958
+ : queuedSelection.changes && queuedSelection.changes.mode === "paths"
4959
+ ? `\nchanges: ${queuedSelection.changes.paths.length} file${queuedSelection.changes.paths.length === 1 ? "" : "s"} (copied when the move lands)`
4960
+ : "";
4961
+ return {
4962
+ text: `worktree warp: ${warpQueuedText(sessionLoad)}\n`
4963
+ + `to: ${warpClean(displayName, "worktree")}${queuedChangesNote}`
4964
+ + (queuedJobsNote.length > 0 ? `\nqueue: ${queuedJobsNote}` : ""),
4965
+ details: {
4966
+ name: displayName, path: targetCwd, branch: displayBranch, kind: resolved.kind,
4967
+ alreadyThere: false, cancelled: false, busy: true, queued: true, pending: true,
4968
+ expiresAt: queued.pending ? queued.pending.expiresAt : null,
4969
+ },
4970
+ stillQueued: true,
4971
+ };
4972
+ }
4621
4973
  // A handoff copy that has landed in the destination is REAL state. It is never
4622
4974
  // rolled back automatically — deleting or reverting files nobody authorized us
4623
4975
  // to touch is exactly the destructive guess this path refuses — so every
@@ -6036,7 +6388,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6036
6388
  }
6037
6389
  }
6038
6390
 
6039
- // S7/S8/S9: the SAME active-session guard `worktree_close` runs, and it runs
6391
+ // S7/S8/S9: the SAME active-session guard `worktree_delete` runs, and it runs
6040
6392
  // BEFORE anything reads the pending changes or builds the deletion question.
6041
6393
  // A keypress may never turn into a confirmation dialog for a checkout a live
6042
6394
  // Pi session is working in: the human is told to finish/warp that session
@@ -6095,7 +6447,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6095
6447
  // realpath comparison cannot see. An unreadable pair is a REFUSAL: without it
6096
6448
  // the removal cannot say which directory it is about to destroy.
6097
6449
  if (typeof before.identity.dev !== "number" || typeof before.identity.ino !== "number") {
6098
- notify?.(`warp: refusing to delete ${target.path}: the identity of its directory could not be read, so a path replaced by another directory could not be told apart; nothing was removed — retry, or close it with the worktree_close tool.`, "error");
6450
+ notify?.(`warp: refusing to delete ${target.path}: the identity of its directory could not be read, so a path replaced by another directory could not be told apart; nothing was removed — retry, or close it with the worktree_delete tool.`, "error");
6099
6451
  return;
6100
6452
  }
6101
6453
  const approvedPin = { real: approvedReal, dev: before.identity.dev, ino: before.identity.ino };
@@ -6111,7 +6463,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6111
6463
  const reason = changes && typeof changes.reason === "string" && changes.reason.length > 0
6112
6464
  ? changes.reason
6113
6465
  : "the change summary failed";
6114
- notify?.(`warp: refusing to delete ${target.path}: its uncommitted changes could not be read (${reason}), so nothing can say what would be lost; nothing was removed — retry, or close it with the worktree_close tool.`, "error");
6466
+ notify?.(`warp: refusing to delete ${target.path}: its uncommitted changes could not be read (${reason}), so nothing can say what would be lost; nothing was removed — retry, or close it with the worktree_delete tool.`, "error");
6115
6467
  return;
6116
6468
  }
6117
6469
  const content = evidence.content && typeof evidence.content === "object" ? evidence.content : null;
@@ -6119,7 +6471,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6119
6471
  const reason = content && typeof content.reason === "string" && content.reason.length > 0
6120
6472
  ? content.reason
6121
6473
  : "the pending content could not be fingerprinted";
6122
- notify?.(`warp: refusing to delete ${target.path}: what is pending in it could not be fingerprinted (${reason}), so an identical +/- count could hide different work; nothing was removed — retry, or close it with the worktree_close tool.`, "error");
6474
+ notify?.(`warp: refusing to delete ${target.path}: what is pending in it could not be fingerprinted (${reason}), so an identical +/- count could hide different work; nothing was removed — retry, or close it with the worktree_delete tool.`, "error");
6123
6475
  return;
6124
6476
  }
6125
6477
  const ignored = evidence.ignored && typeof evidence.ignored === "object" ? evidence.ignored : null;
@@ -6127,7 +6479,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6127
6479
  const reason = ignored && typeof ignored.reason === "string" && ignored.reason.length > 0
6128
6480
  ? ignored.reason
6129
6481
  : "the ignored-file listing failed";
6130
- notify?.(`warp: refusing to delete ${target.path}: the files git ignores there could not be listed (${reason}), so the removal could destroy work nobody was shown; nothing was removed — retry, or close it with the worktree_close tool.`, "error");
6482
+ notify?.(`warp: refusing to delete ${target.path}: the files git ignores there could not be listed (${reason}), so the removal could destroy work nobody was shown; nothing was removed — retry, or close it with the worktree_delete tool.`, "error");
6131
6483
  return;
6132
6484
  }
6133
6485
 
@@ -6629,6 +6981,20 @@ function registerWarpCommand(pi) {
6629
6981
  handler: async (args, ctx) => {
6630
6982
  const notify = ctx?.ui?.notify;
6631
6983
  const raw = String(args ?? "").trim();
6984
+ // S5: one pending warp per session, refused on EVERY front here — the
6985
+ // selector is not even opened for a request that cannot run — except for
6986
+ // the pending request's own re-dispatched handoff, which is the move this
6987
+ // queue exists to perform.
6988
+ const earlyHandoff = raw.startsWith(WARP_HANDOFF_PREFIX) ? decodeWarpHandoff(raw) : null;
6989
+ const earlyGate = warpPendingGate(
6990
+ ctx,
6991
+ toolCwd(ctx),
6992
+ earlyHandoff && earlyHandoff.ok === true ? earlyHandoff.request : null,
6993
+ );
6994
+ if (earlyGate.pending && earlyGate.retry !== true) {
6995
+ notify?.(`worktree warp: ${warpPendingRefusalText(earlyGate.pending, raw)}`, "error");
6996
+ return;
6997
+ }
6632
6998
  // An agent handoff (queued by the `worktree_warp` tool) travels as ONE
6633
6999
  // `@<token>` argument. It is decoded and re-validated here; a rejected
6634
7000
  // token changes nothing and names no part of what it carried. Everything
@@ -7691,6 +8057,11 @@ export default function (pi) {
7691
8057
  await checkIssuesGate(pi, ctx);
7692
8058
  });
7693
8059
  pi.on("session_shutdown", forgetWorktreeCardUi);
8060
+ // A queued warp is session state: shutdown clears its record and its timer so
8061
+ // nothing outlives the session that asked for the move.
8062
+ pi.on("session_shutdown", (event, ctx) => {
8063
+ forgetPendingWarp(ctx);
8064
+ });
7694
8065
  // Nothing deferred survives its session: shutdown advances the startup epoch,
7695
8066
  // so work still in flight drops instead of writing into the session that
7696
8067
  // replaced it.