pi-odd-worktree 1.1.1 → 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,12 +10,11 @@
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
  //
17
- // Herdr is optional, never required: every Herdr call is attempted first and
18
- // falls back to plain git, so the package works in Pi alone.
17
+ // Worktree creation and removal use git; no Herdr workspace is opened.
19
18
  //
20
19
  // The file is plain JavaScript with a .ts extension (// @ts-nocheck, no type
21
20
  // annotations), so the test copy-to-.mjs loading pattern keeps working under
@@ -69,54 +68,6 @@ function setWarpTuiLoader(loader) {
69
68
  warpTuiLoader = loader;
70
69
  }
71
70
 
72
- // The herdr binary honors the documented HERDR_BIN_PATH override (tests),
73
- // else `herdr` on PATH.
74
- //
75
- // lib/worktree-git.js `resolveHerdrBinary` is the SINGLE authority and its
76
- // answer is propagated verbatim, including its refusal: under the test harness
77
- // (GENTLE_WORKTREE_LIB_DIR, set only by the test loaders) a value that may be
78
- // the live binary is refused unless the CURRENT test opted in with
79
- // GENTLE_WORKTREE_ALLOW_LIVE_HERDR=1. A `catch {}` around that call used to
80
- // swallow the refusal and then re-apply an inherited HERDR_BIN_PATH here, which
81
- // handed a test process exactly the live binary the authority had just refused
82
- // (a real Herdr workspace, created from a test). No fallback in this file may
83
- // re-decide the binary: the only remaining branch is for a lib that is missing
84
- // entirely, and it fails closed under the harness.
85
- function herdrBinary() {
86
- let git = null;
87
- try {
88
- git = libRequire("worktree-git.js");
89
- } catch {
90
- git = null;
91
- }
92
- if (git && typeof git.resolveHerdrBinary === "function") {
93
- return git.resolveHerdrBinary(process.env);
94
- }
95
- const harness = process.env.GENTLE_WORKTREE_LIB_DIR;
96
- if (typeof harness === "string" && harness.length > 0) {
97
- throw new Error(
98
- "refusing to run live herdr from a test harness: herdr binary cannot be resolved "
99
- + "(lib/worktree-git.js is unavailable, so no binary is injected)",
100
- );
101
- }
102
- const bin = process.env.HERDR_BIN_PATH;
103
- if (typeof bin === "string" && bin.length > 0) return bin;
104
- return "herdr";
105
- }
106
-
107
- // The texts the authority (and the missing-lib branch above) use to refuse.
108
- // Matching on text keeps the boundary between lib and extension small: a
109
- // refusal is a resolved STATE, not an error class shared across it.
110
- const HERDR_REFUSAL_PATTERN = /refusing to run live herdr|herdr binary is not injected/;
111
-
112
- function isHerdrRefusal(err) {
113
- return !!(
114
- err
115
- && typeof err.message === "string"
116
- && HERDR_REFUSAL_PATTERN.test(err.message)
117
- );
118
- }
119
-
120
71
  function toolCwd(ctx) {
121
72
  if (ctx && typeof ctx.cwd === "string" && ctx.cwd.length > 0) return ctx.cwd;
122
73
  return process.cwd();
@@ -543,12 +494,6 @@ function withWorktreeCardRenderer(tool) {
543
494
  // Model text and visual cards are independent presentation layers. Keep
544
495
  // backend helpers unchanged so runtime callers retain their raw contract.
545
496
  //
546
- // The same seam turns a herdr resolution REFUSAL into an error result: the
547
- // guard's refusal (a test harness handing over a possible live binary, or a
548
- // harness with no binary injected) says the resolution failed, not that the
549
- // tool crashed. Letting it escape would be an uncaught throw out of a tool
550
- // handler, so every refusal is answered with its own text and `isError`, and
551
- // every other exception is re-thrown untouched.
552
497
  const execute = tool.execute;
553
498
  let format = null;
554
499
  try {
@@ -559,13 +504,7 @@ function withWorktreeCardRenderer(tool) {
559
504
  }
560
505
  if (typeof execute === "function") {
561
506
  tool.execute = async function (...args) {
562
- let result;
563
- try {
564
- result = await execute.apply(this, args);
565
- } catch (err) {
566
- if (!isHerdrRefusal(err)) throw err;
567
- result = errorResult(`${tool.name}: ${err.message}`, { tool: tool.name, herdrRefused: true });
568
- }
507
+ const result = await execute.apply(this, args);
569
508
  if (!format) return result;
570
509
  try {
571
510
  return format(tool.name, result);
@@ -703,7 +642,7 @@ async function awaitPendingCreationSetups() {
703
642
  }
704
643
  }
705
644
 
706
- // Core of `worktree_create`: validation (S2, S3) then herdr-first creation
645
+ // Core of `worktree_create`: validation (S2, S3) then git creation
707
646
  // with a git fallback. Exported for unit tests; the registered tool calls
708
647
  // it with the live Pi context. It only ever CREATES: the branch plus the
709
648
  // `changes` selection (S3/S4), and no issue or ODD association is verified,
@@ -711,15 +650,6 @@ async function awaitPendingCreationSetups() {
711
650
  async function executeWorktreeCreate(params, ctx, opts) {
712
651
  const git = libRequire("worktree-git.js");
713
652
  const registry = libRequire("worktree-registry.js");
714
- // S53 git-only route (create-from-warp): the wizard creates a plain
715
- // git checkout plus the registry row and nothing else — never a Herdr
716
- // workspace (`herdr worktree create/open` is what materialized the
717
- // stray Herdr worktree the user never asked for). The route reuses
718
- // every validation and the registry machinery below; only the
719
- // backends change. Subprocesses run through the async runner here so
720
- // a hanging child aborts on its bound instead of freezing the
721
- // interactive session on the main thread.
722
- const gitOnly = !!(opts && opts.gitOnly === true);
723
653
  // `backgroundHooks` is the INTERACTIVE create's speed contract: the checkout
724
654
  // plus its registry row are all the warp needs, so the slow half of the hooks
725
655
  // (install, codegraph) is handed to a tracked background task instead of
@@ -1104,7 +1034,7 @@ async function executeWorktreeCreate(params, ctx, opts) {
1104
1034
 
1105
1035
  // No approval dialog: a create touches no existing data — the checkout and
1106
1036
  // its registry row are both new — and the panel's create path never asked
1107
- // either. The confirmation that matters lives in `worktree_close`.
1037
+ // either. The confirmation that matters lives in `worktree_delete`.
1108
1038
 
1109
1039
  // (g) Create. S20 branch adoption is resolved BEFORE creating: when
1110
1040
  // `refs/heads/<branch>` already exists (and is not checked out at a
@@ -1112,24 +1042,12 @@ async function executeWorktreeCreate(params, ctx, opts) {
1112
1042
  // EXISTING branch with `git worktree add <target> <branch>` — no `-b`,
1113
1043
  // no base, the ref never created, rewritten or deleted — and the result
1114
1044
  // reports `branchCreated: false` plus a warning naming the adopted
1115
- // branch. Herdr's `worktree create` cannot adopt an existing branch, so
1116
- // the adopt case goes through git and then associates the Herdr
1117
- // workspace BEST-EFFORT via `herdr worktree open --path <path>
1118
- // --cwd <root>`; the checkout succeeding never depends on herdr.
1119
- // When the ref does not exist, creation keeps the herdr-first path
1120
- // with a `git worktree add -b` fallback and reports `branchCreated:
1121
- // true`. Fixed argv only, values as separate elements (herdr rejects
1122
- // --flag=value). Never --focus, never --trust-repository: trusting a
1123
- // repository is a human decision these tools never take. The base is
1124
- // LOCAL MAIN (S2), resolved in (d1) before anything was written: a session
1125
- // working inside a linked worktree can never seed the new branch with its
1126
- // own unmerged commits, and a repository without a local `main` was already
1127
- // refused there instead of falling back to the invoking HEAD.
1045
+ // branch. New branches start at local main; existing branches are adopted
1046
+ // unchanged. Both tool and panel creation use git only.
1128
1047
  const base = baseInfo !== null ? baseInfo.commit : null;
1129
1048
  let createdBy = null;
1130
1049
  let createError = null;
1131
1050
  let branchCreated = null;
1132
- let herdrAssociated = null;
1133
1051
  const adoptWarnings = [];
1134
1052
  if (branchExists) {
1135
1053
  // Adopt: check out the existing branch at the fresh path. No `-b`
@@ -1142,45 +1060,9 @@ async function executeWorktreeCreate(params, ctx, opts) {
1142
1060
  adoptWarnings.push(
1143
1061
  `adopted existing branch '${branch}' at ${target}: the worktree checks out that branch as-is, the branch ref was left untouched`,
1144
1062
  );
1145
- // Best-effort Herdr workspace association: reported, never fatal.
1146
- // Skipped on the git-only route: that checkout is git plus the
1147
- // registry row by design, so no association is expected.
1148
- if (!gitOnly) {
1149
- try {
1150
- const opened = await runGit(herdrBinary(), git.herdrArgv("open", { cwd: repo.root, path: target }), {
1151
- cwd: repo.root,
1152
- timeoutMs: 60000,
1153
- });
1154
- herdrAssociated = opened.status === 0;
1155
- } catch (err) {
1156
- herdrAssociated = false;
1157
- }
1158
- if (herdrAssociated !== true) {
1159
- adoptWarnings.push(
1160
- `herdr workspace association failed for ${target} ('herdr worktree open' did not succeed): the checkout itself is fine, associate it by hand when needed`,
1161
- );
1162
- }
1163
- }
1164
1063
  } else {
1165
1064
  createError = ((adopted.stderr || adopted.error || "unknown error") + "").trim();
1166
1065
  }
1167
- } else {
1168
- // The git-only route skips the herdr-first attempt outright: no
1169
- // `herdr worktree create` runs, so no Herdr workspace is ever
1170
- // materialized from the wizard. The tool path keeps herdr-first
1171
- // with the git fallback below, byte-identical.
1172
- let herdrRes = null;
1173
- if (!gitOnly) {
1174
- const createParams = { cwd: repo.root, branch, path: target };
1175
- if (base) createParams.base = base;
1176
- herdrRes = await runGit(herdrBinary(), git.herdrArgv("create", createParams), {
1177
- cwd: repo.root,
1178
- timeoutMs: 120000,
1179
- });
1180
- }
1181
- if (herdrRes !== null && herdrRes.status === 0) {
1182
- createdBy = "herdr";
1183
- branchCreated = true;
1184
1066
  } else {
1185
1067
  const fallbackArgv = ["worktree", "add", "-b", branch, target];
1186
1068
  if (base) fallbackArgv.push(base);
@@ -1212,10 +1094,9 @@ async function executeWorktreeCreate(params, ctx, opts) {
1212
1094
  }
1213
1095
  }
1214
1096
  }
1215
- }
1216
1097
  if (!createdBy) {
1217
1098
  return errorResult(
1218
- `failed to create worktree for branch '${branch}': ${createError || "herdr and git both failed"}`,
1099
+ `failed to create worktree for branch '${branch}': ${createError || "git failed"}`,
1219
1100
  { branch, path: target, pruned: prunedStale },
1220
1101
  );
1221
1102
  }
@@ -1519,11 +1400,8 @@ async function executeWorktreeCreate(params, ctx, opts) {
1519
1400
  // S6: the ONE CodeGraph fact of this create, read from the hooks that just
1520
1401
  // ran (never re-run, never inferred).
1521
1402
  const codegraph = codegraphStatus(hooks);
1522
- // S20 adoption reporting: whether the branch was created or adopted,
1523
- // and (adopt case only) whether the best-effort Herdr workspace
1524
- // association happened. The checkout succeeding never depends on herdr.
1403
+ // Report whether the branch was created or adopted.
1525
1404
  const adoptionDetails = { branchCreated };
1526
- if (herdrAssociated !== null) adoptionDetails.herdrAssociated = herdrAssociated;
1527
1405
  // (l) T41/S50 changes registration: register the checkout just
1528
1406
  // created on the CURRENT session through gentle-shell's
1529
1407
  // `session_worktree_register` host tool, but ONLY when that tool is
@@ -2143,7 +2021,7 @@ async function vanishedCheckouts(git, repoRoot, live, resolvedTarget, after) {
2143
2021
  }
2144
2022
 
2145
2023
  // S24 name resolution — the ONE place checkout names resolve to
2146
- // checkouts. `worktree_close` (by `name`) and the `warp` command verb
2024
+ // checkouts. `worktree_delete` (by `name`) and the `warp` command verb
2147
2025
  // both call this, never separate logic. A name is the flattened branch
2148
2026
  // slug (`slugifyBranch`, already exported by lib/worktree-git.js), or
2149
2027
  // `principal` for the principal checkout.
@@ -2440,7 +2318,7 @@ function closeSessionString(ctx, method) {
2440
2318
  }
2441
2319
  }
2442
2320
 
2443
- // 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
2444
2322
  // panel's Ctrl+D (lib/worktree-session-guard.js).
2445
2323
  //
2446
2324
  // The guard answers one question per checkout: is a live Pi session working
@@ -2564,7 +2442,7 @@ async function yoloActiveFor(ctx) {
2564
2442
  }
2565
2443
  }
2566
2444
 
2567
- // 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
2568
2446
  // branch, drop the registry entry. Exported for unit tests; the registered tool
2569
2447
  // calls it with the live Pi context, and the warp panel's Ctrl+D calls it with
2570
2448
  // `opts.approved` after its own question.
@@ -2596,7 +2474,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2596
2474
  const hasName = typeof rawName === "string" && rawName.length > 0;
2597
2475
  if (!hasPath && !hasBranch && !hasName) {
2598
2476
  return errorResult(
2599
- "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",
2600
2478
  { force },
2601
2479
  );
2602
2480
  }
@@ -2605,7 +2483,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2605
2483
  // agree-or-disagree behaviour below.)
2606
2484
  if (hasName && (hasPath || hasBranch)) {
2607
2485
  return errorResult(
2608
- "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",
2609
2487
  { path: rawPath, branch: rawBranch, name: rawName, force },
2610
2488
  );
2611
2489
  }
@@ -2626,7 +2504,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2626
2504
  const byBranch = hasBranch && !hasName ? registry.findByBranch(repo.root, rawBranch) : null;
2627
2505
  if (hasPath && hasBranch && byPath && byBranch && byPath.branch !== byBranch.branch) {
2628
2506
  return errorResult(
2629
- `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`,
2630
2508
  { path: rawPath, branch: rawBranch, force },
2631
2509
  );
2632
2510
  }
@@ -2659,7 +2537,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2659
2537
  }
2660
2538
  } else if (resolved.kind === "principal") {
2661
2539
  return errorResult(
2662
- `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`,
2663
2541
  { name: rawName, path: resolved.path, branch: resolved.branch, force },
2664
2542
  );
2665
2543
  } else {
@@ -2677,7 +2555,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2677
2555
  const pid = pst.real !== null ? pst.real : pst.absolute;
2678
2556
  if (entryId !== null && pid !== null && entryId === pid) {
2679
2557
  return errorResult(
2680
- `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`,
2681
2559
  { name: rawName, path: principalRef.path, branch: principalRef.branch, force },
2682
2560
  );
2683
2561
  }
@@ -2755,7 +2633,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2755
2633
  // is invoked. Without that, a path replaced by a symbolic link while the
2756
2634
  // human answered would be handed to `git worktree remove`, which resolves the
2757
2635
  // spelling it is given and would name ANOTHER checkout. No tool reaches this:
2758
- // `worktree_close` calls this function without options.
2636
+ // `worktree_delete` calls this function without options.
2759
2637
  const expectedReal = opts && typeof opts.expectedReal === "string" && opts.expectedReal.length > 0
2760
2638
  ? opts.expectedReal
2761
2639
  : null;
@@ -2822,7 +2700,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2822
2700
  // selector's keyboard delete, which never consults YOLO at all
2823
2701
  // (`warpDeleteCheckout`). It suppresses the second dialog only: every check
2824
2702
  // above and below, the live-session protections and the removal itself are
2825
- // 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
2826
2704
  // this function without options.
2827
2705
  const alreadyApproved = !!(opts && opts.approved === true);
2828
2706
  if (ctx && ctx.hasUI && !alreadyApproved) {
@@ -2863,7 +2741,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2863
2741
  }
2864
2742
  if (!approved) {
2865
2743
  return errorResult(
2866
- `worktree close cancelled: approval declined for branch '${branch}'`,
2744
+ `worktree delete cancelled: approval declined for branch '${branch}'`,
2867
2745
  { cancelled: true, branch, path: target, force },
2868
2746
  );
2869
2747
  }
@@ -3045,15 +2923,15 @@ const worktreeListTool = withWorktreeCardRenderer(defineTool({
3045
2923
  }));
3046
2924
 
3047
2925
  const worktreeCloseTool = withWorktreeCardRenderer(defineTool({
3048
- name: "worktree_close",
3049
- label: "Worktree Close",
2926
+ name: "worktree_delete",
2927
+ label: "Worktree Delete",
3050
2928
  exposure: "codemode",
3051
- 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.",
3052
2930
  parameters: Type.Object({
3053
- name: opt(Type.String({ description: "Name of the registered worktree to close (the flattened branch slug, or principal)" })),
3054
- path: opt(Type.String({ description: "Path of the registered worktree to close" })),
3055
- branch: opt(Type.String({ description: "Branch of the registered worktree to close" })),
3056
- 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" })),
3057
2935
  }),
3058
2936
  async execute(toolCallId, params, signal, onUpdate, ctx) {
3059
2937
  return executeWorktreeClose(params, ctx);
@@ -3593,6 +3471,16 @@ async function executeWorktreeWarpTool(params, ctx, opts) {
3593
3471
  const warpSessions = libRequire("worktree-warp-sessions.js");
3594
3472
  const raw = params && typeof params.name === "string" ? params.name.trim() : "";
3595
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
+ }
3596
3484
  // S21: the warp is interactive too, so its preflight reads are awaited.
3597
3485
  const runAsync = libRunner(git);
3598
3486
  let repo;
@@ -3787,35 +3675,72 @@ async function executeWorktreeWarpTool(params, ctx, opts) {
3787
3675
  // `fromName`/`name`/`path`/`branch`), so the card falls back to that line
3788
3676
  // instead of painting a move that has not happened. The one visible "moved"
3789
3677
  // card comes from the switched-to session once the move is real.
3790
- 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({
3791
3688
  name: displayName,
3792
3689
  target: targetCwd,
3793
3690
  from: fromCwd,
3794
3691
  branch: displayBranch,
3795
3692
  changes: toolChanges,
3796
- }));
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);
3797
3713
  if (!handoffDispatched.ok) {
3714
+ // Nothing was handed off, so nothing may stay pending.
3715
+ if (toolQueue.ok && toolQueue.pending) warpSettlePending(toolQueue.pending.key);
3798
3716
  return errorResult(
3799
3717
  `worktree warp: ${handoffDispatched.error}`,
3800
3718
  { tool: "worktree_warp", name: displayName, path: targetCwd, branch: displayBranch, kind: resolved.kind, alreadyThere: false, cancelled: false },
3801
3719
  );
3802
3720
  }
3721
+ if (toolQueue.ok && toolQueue.pending) warpMarkDispatched(toolQueue.pending.key);
3803
3722
  const changesNote = toolChanges.mode === "all"
3804
3723
  ? "\nchanges: all (copied when the move lands)"
3805
3724
  : toolChanges.mode === "paths"
3806
3725
  ? `\nchanges: ${toolChanges.paths.length} file${toolChanges.paths.length === 1 ? "" : "s"} (copied when the move lands)`
3807
3726
  : "";
3808
- const pendingText =
3809
- `worktree warp: handoff queued — the session moves when this turn ends\n` +
3810
- `to: ${warpClean(displayName, "worktree")}\n` +
3811
- `path: ${warpClean(targetCwd, "(unknown checkout)")}\n` +
3812
- `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");
3813
3737
  return textResult(
3814
3738
  pendingText,
3815
3739
  {
3816
3740
  tool: "worktree_warp", handoff: true, pending: true,
3817
3741
  pendingName: displayName, pendingPath: targetCwd, pendingBranch: displayBranch,
3818
3742
  from: fromCwd, target: targetCwd, kind: resolved.kind,
3743
+ ...(toolBusy ? { busy: true, queued: true } : {}),
3819
3744
  },
3820
3745
  false,
3821
3746
  );
@@ -4203,6 +4128,240 @@ async function sessionManagerClassFor(ctx) {
4203
4128
  return null;
4204
4129
  }
4205
4130
 
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;
4158
+ let lib = null;
4159
+ try {
4160
+ lib = libRequire("worktree-warp-busy.js");
4161
+ } catch {
4162
+ return null;
4163
+ }
4164
+ if (!lib || typeof lib.sessionActivity !== "function") return null;
4165
+ try {
4166
+ return await lib.sessionActivity({ sessionId, host: host || null });
4167
+ } catch {
4168
+ return null;
4169
+ }
4170
+ }
4171
+
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) {
4192
+ try {
4193
+ const lib = libRequire("worktree-warp-busy.js");
4194
+ if (lib && typeof lib.jobsUnknownText === "function") return lib.jobsUnknownText(activity);
4195
+ } catch {
4196
+ // fall through to the fixed sentence
4197
+ }
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
+ }
4341
+ }
4342
+
4343
+ // The COMMAND front's bounded wait: a warp lands after this turn settles, so it
4344
+ // gives the published counters a chance to drain before it refuses. Null when
4345
+ // the module or the session identity is unavailable (best effort, blocks
4346
+ // nothing).
4347
+ async function warpWaitForIdleSession(ctx) {
4348
+ let lib = null;
4349
+ try {
4350
+ lib = libRequire("worktree-warp-busy.js");
4351
+ } catch {
4352
+ return null;
4353
+ }
4354
+ if (!lib || typeof lib.waitForSessionActivity !== "function") return null;
4355
+ const sessionId = closeSessionString(ctx, "getSessionId");
4356
+ try {
4357
+ // The budget travels through the environment so a session can bound its own
4358
+ // wait (ODD_WORKTREE_WARP_BUSY_WAIT_MS); the default keeps a warp short.
4359
+ return await lib.waitForSessionActivity({ sessionId, env: process.env, host: warpJobHost(ctx) });
4360
+ } catch {
4361
+ return null;
4362
+ }
4363
+ }
4364
+
4206
4365
  function warpFail(text, details) {
4207
4366
  return { text, details: details || {}, isError: true };
4208
4367
  }
@@ -4515,7 +4674,62 @@ async function warpMaybeCopyDirty({ ctx, git, fromCheckout, targetCwd, options }
4515
4674
  }
4516
4675
  return { ok: true, copied };
4517
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.
4518
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) {
4519
4733
  const options = opts || {};
4520
4734
  const git = libRequire("worktree-git.js");
4521
4735
  const registry = libRequire("worktree-registry.js");
@@ -4545,6 +4759,14 @@ async function executeWorktreeWarp(rawName, ctx, opts) {
4545
4759
  );
4546
4760
  }
4547
4761
  await ctx.waitForIdle();
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.
4768
+ const busyWait = await warpWaitForIdleSession(ctx);
4769
+ const sessionLoad = busyWait && busyWait.activity ? busyWait.activity : null;
4548
4770
  const fromCwd = typeof ctx.cwd === "string" && ctx.cwd.length > 0 ? ctx.cwd : process.cwd();
4549
4771
  // S21: the same awaited preflight reads as the tool, so a slow repository
4550
4772
  // never freezes the session that is being moved.
@@ -4662,6 +4884,92 @@ async function executeWorktreeWarp(rawName, ctx, opts) {
4662
4884
  // through `failAfterCopy` (below) and why a retry must prove the copied state
4663
4885
  // byte for byte before it skips anything.
4664
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
+ }
4665
4973
  // A handoff copy that has landed in the destination is REAL state. It is never
4666
4974
  // rolled back automatically — deleting or reverting files nobody authorized us
4667
4975
  // to touch is exactly the destructive guess this path refuses — so every
@@ -5975,8 +6283,8 @@ async function warpCreateAndEnter(ctx, git, notify) {
5975
6283
  return { closed: true, created: false, cancelled: true };
5976
6284
  }
5977
6285
  createParams.changes = pending.copy ? 'all' : 'none';
5978
- // S53: the git-only route — a plain git checkout plus the registry row,
5979
- // never a Herdr workspace — reusing the same creation path (validations,
6286
+ // S53: the panel's create — a plain git checkout plus the registry row —
6287
+ // reusing the same creation path (validations,
5980
6288
  // refusals, registration), which never prompts. The layout is
5981
6289
  // principal-anchored (S56): the new checkout lands beside the PRINCIPAL
5982
6290
  // checkout even when the panel runs inside a linked worktree, while the
@@ -5989,7 +6297,6 @@ async function warpCreateAndEnter(ctx, git, notify) {
5989
6297
  // can move, or the human would switch into a checkout that is missing the
5990
6298
  // work they just asked to carry.
5991
6299
  const created = await executeWorktreeCreate(createParams, ctx, {
5992
- gitOnly: true,
5993
6300
  principalLayout: true,
5994
6301
  backgroundHooks: true,
5995
6302
  ...(typeof notify === 'function' ? { notify } : {}),
@@ -6081,7 +6388,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6081
6388
  }
6082
6389
  }
6083
6390
 
6084
- // 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
6085
6392
  // BEFORE anything reads the pending changes or builds the deletion question.
6086
6393
  // A keypress may never turn into a confirmation dialog for a checkout a live
6087
6394
  // Pi session is working in: the human is told to finish/warp that session
@@ -6140,7 +6447,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6140
6447
  // realpath comparison cannot see. An unreadable pair is a REFUSAL: without it
6141
6448
  // the removal cannot say which directory it is about to destroy.
6142
6449
  if (typeof before.identity.dev !== "number" || typeof before.identity.ino !== "number") {
6143
- 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");
6144
6451
  return;
6145
6452
  }
6146
6453
  const approvedPin = { real: approvedReal, dev: before.identity.dev, ino: before.identity.ino };
@@ -6156,7 +6463,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6156
6463
  const reason = changes && typeof changes.reason === "string" && changes.reason.length > 0
6157
6464
  ? changes.reason
6158
6465
  : "the change summary failed";
6159
- 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");
6160
6467
  return;
6161
6468
  }
6162
6469
  const content = evidence.content && typeof evidence.content === "object" ? evidence.content : null;
@@ -6164,7 +6471,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6164
6471
  const reason = content && typeof content.reason === "string" && content.reason.length > 0
6165
6472
  ? content.reason
6166
6473
  : "the pending content could not be fingerprinted";
6167
- 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");
6168
6475
  return;
6169
6476
  }
6170
6477
  const ignored = evidence.ignored && typeof evidence.ignored === "object" ? evidence.ignored : null;
@@ -6172,7 +6479,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6172
6479
  const reason = ignored && typeof ignored.reason === "string" && ignored.reason.length > 0
6173
6480
  ? ignored.reason
6174
6481
  : "the ignored-file listing failed";
6175
- 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");
6176
6483
  return;
6177
6484
  }
6178
6485
 
@@ -6674,6 +6981,20 @@ function registerWarpCommand(pi) {
6674
6981
  handler: async (args, ctx) => {
6675
6982
  const notify = ctx?.ui?.notify;
6676
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
+ }
6677
6998
  // An agent handoff (queued by the `worktree_warp` tool) travels as ONE
6678
6999
  // `@<token>` argument. It is decoded and re-validated here; a rejected
6679
7000
  // token changes nothing and names no part of what it carried. Everything
@@ -7736,6 +8057,11 @@ export default function (pi) {
7736
8057
  await checkIssuesGate(pi, ctx);
7737
8058
  });
7738
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
+ });
7739
8065
  // Nothing deferred survives its session: shutdown advances the startup epoch,
7740
8066
  // so work still in flight drops instead of writing into the session that
7741
8067
  // replaced it.