pi-odd-worktree 1.2.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
  //
@@ -549,24 +549,49 @@ async function resolveCreateBase(runGit, repo) {
549
549
  return null;
550
550
  }
551
551
 
552
- // The INTERACTIVE create (the warp panel) returns to the selector as soon as
553
- // the checkout path exists: the SLOW half of the creation hooks — dependency
554
- // install, `codegraph init` — is what made a confirmed create feel like a hang,
555
- // because a package manager can run for minutes. `backgroundHooks` hands that
556
- // half to this managed background task instead of awaiting it, so the path the
557
- // warp needs is usable immediately and the setup finishes behind it.
552
+ // A create is INSTANT on BOTH fronts — the `worktree_create` tool and the
553
+ // `/warp` panel: the checkout plus its registry row are all a warp needs, so the
554
+ // SLOW half of the creation hooks — dependency install, `codegraph init` — is
555
+ // handed to this managed background task instead of being awaited. A package
556
+ // manager can run for minutes, and awaiting it is exactly what made a confirmed
557
+ // create feel like a hang.
558
558
  //
559
559
  // Nothing is skipped and nothing is orphaned:
560
560
  // - the hooks library still runs both phases (through the `setup()` callable
561
561
  // it returns), so the checkout is set up exactly as before;
562
562
  // - every task is tracked here until it settles, and
563
- // `awaitPendingCreationSetups` is the seam a test (or a shutdown path) uses
564
- // to wait for the last one;
565
- // - each task settles into exactly ONE report, so a failure reaches the human
566
- // instead of vanishing into a detached promise, and the task itself never
567
- // rejects (nothing is left unobserved).
563
+ // `awaitPendingCreationSetups` is the seam a test (or a caller) uses to wait
564
+ // for the last one;
565
+ // - the settled outcome is recorded per checkout, so a later `worktree_create`
566
+ // for that same checkout reports what the background work actually did;
567
+ // - each task settles into at most ONE report, and the task itself never
568
+ // rejects (nothing is left unobserved);
569
+ // - a task that settles after `session_shutdown` records and reports nothing:
570
+ // it belongs to a session whose UI the runtime already invalidated.
568
571
  const creationSetups = new Set();
569
572
 
573
+ // Session epoch for deferred setups. Shutdown advances it, so late work drops
574
+ // instead of writing into the session that replaced it.
575
+ let creationEpoch = 0;
576
+
577
+ // The deferred setup's lifecycle record, one entry per checkout path: `running`
578
+ // while the background task owns it, then `done` or `failed` with the steps that
579
+ // really ran. Session state only — never written to disk, cleared on shutdown.
580
+ const creationSetupStates = new Map();
581
+
582
+ function beginCreationTask() {
583
+ return creationEpoch;
584
+ }
585
+
586
+ function creationTaskLive(epoch) {
587
+ return epoch === creationEpoch;
588
+ }
589
+
590
+ function forgetCreationSetups() {
591
+ creationEpoch += 1;
592
+ creationSetupStates.clear();
593
+ }
594
+
570
595
  // Fold a child's stderr into one escape-free line, the same shape every
571
596
  // summary row uses, so a multi-line failure cannot break the notification.
572
597
  function setupReportLine(text) {
@@ -576,8 +601,50 @@ function setupReportLine(text) {
576
601
  .trim();
577
602
  }
578
603
 
579
- // The one report a settled setup produces: what ran on success, and the reasons
580
- // on failure — plus the fact that the checkout stays usable either way.
604
+ // The create result's row for that lifecycle. It states the SETUP's state, never
605
+ // the index on disk (`codegraphIndexState` reads that), so the two rows of one
606
+ // result can never contradict each other.
607
+ function setupStateRow(state) {
608
+ if (!state || typeof state !== 'object') return null;
609
+ if (state.status === 'running') return 'setup: running in the background (install, codegraph)';
610
+ if (state.status === 'failed') {
611
+ const reason = setupReportLine(state.reason || '');
612
+ return `setup: finished with problems: ${reason.length > 0 ? reason : 'the setup reported a failure'} — the checkout is usable`;
613
+ }
614
+ if (state.status === 'done') return 'setup: finished';
615
+ return null;
616
+ }
617
+
618
+ // One settled step, in the words the create's rows use.
619
+ function setupStepLabel(step) {
620
+ const name = String((step && step.name) || 'setup');
621
+ if (name === 'codegraph-init') return 'codegraph initialized';
622
+ return setupReportLine(name.replace(/^install:/, 'install '));
623
+ }
624
+
625
+ // The ONE reading of a settled setup, shared by the record a later tool result
626
+ // reports and by the notice a caller asked for: the steps that ran, and the
627
+ // reason it went wrong when it did.
628
+ function settledCreationSetup(outcome) {
629
+ const steps = outcome && Array.isArray(outcome.steps) ? outcome.steps : [];
630
+ const failed = steps.filter((step) => step && step.status === 'failed');
631
+ const done = steps.filter((step) => step && step.status === 'done');
632
+ const warnings = outcome && Array.isArray(outcome.warnings) ? outcome.warnings : [];
633
+ const wentWrong = failed.length > 0 || !!(outcome && outcome.ok === false) || warnings.length > 0;
634
+ if (!wentWrong) return { steps, done, problem: null };
635
+ const reasons = warnings.length > 0 ? warnings : failed.map((step) => `${step.name} failed`);
636
+ const named = reasons.map(setupReportLine).filter((line) => line.length > 0).join('; ');
637
+ return { steps, done, problem: named.length > 0 ? named : 'the setup reported a failure' };
638
+ }
639
+
640
+ // WHERE THE COMPLETION NOTICE GOES. It belongs to the caller that asked for one:
641
+ // only an explicitly supplied `notify` receives it. The `/warp` panel supplies
642
+ // the UI notification a human is watching. The `worktree_create` tool supplies
643
+ // NOTHING — an agent's tool result is its report, so a create never fires a
644
+ // `ui.notify` the call did not ask for, and never reports the deferred setup as
645
+ // an error: a problem is a warning, and the checkout stays usable either way.
646
+ // The agent learns the outcome later from the tool surface: a create for the same
647
+ // checkout reports the recorded state (`setupStateRow`) and its steps.
581
648
  //
582
649
  // A run in which NO step completed reports NOTHING. Every step can be skipped
583
650
  // (no lockfile detected, `codegraph` not on PATH), and a "setup finished" toast
@@ -585,34 +652,22 @@ function setupReportLine(text) {
585
652
  // create used to show on every such checkout. Failures are never suppressed by
586
653
  // that rule: a failed step, a failed outcome or any warning is reported first
587
654
  // and returns, so silence can only ever mean "nothing ran, nothing failed".
588
- function reportCreationSetup({ branch, target, outcome, notify }) {
655
+ function reportCreationSetup({ branch, target, settled, notify }) {
589
656
  if (typeof notify !== 'function') return;
590
- const steps = outcome && Array.isArray(outcome.steps) ? outcome.steps : [];
591
- const failed = steps.filter((step) => step && step.status === 'failed');
592
- const done = steps.filter((step) => step && step.status === 'done');
593
- const uninformedFailure = !!(outcome && outcome.ok === false);
594
- const label = (step) => {
595
- const name = String(step.name || 'setup');
596
- if (name === 'codegraph-init') return 'codegraph initialized';
597
- return setupReportLine(name.replace(/^install:/, 'install '));
598
- };
599
- const warnings = outcome && Array.isArray(outcome.warnings) ? outcome.warnings : [];
600
- if (failed.length > 0 || uninformedFailure || warnings.length > 0) {
601
- const reasons = warnings.length > 0 ? warnings : failed.map((step) => `${step.name} failed`);
602
- const reasonText = reasons.map(setupReportLine).filter((line) => line.length > 0).join('; ');
657
+ if (settled.problem !== null) {
603
658
  notify(
604
- `warp: setup for ${branch} finished with problems: ${reasonText.length > 0 ? reasonText : 'the setup reported a failure'} — the checkout at ${target} is usable`,
605
- 'error',
659
+ `warp: setup for ${branch} finished with problems: ${settled.problem} — the checkout at ${target} is usable`,
660
+ 'warning',
606
661
  );
607
662
  return;
608
663
  }
609
- if (done.length === 0) return;
610
- notify(`warp: setup finished for ${branch}: ${done.map(label).join(', ')}`, 'info');
664
+ if (settled.done.length === 0) return;
665
+ notify(`warp: setup finished for ${branch}: ${settled.done.map(setupStepLabel).join(', ')}`, 'info');
611
666
  }
612
667
 
613
668
  // Start (and track) the deferred setup. The returned task never rejects: a
614
- // throwing phase is reported as a failed setup, never as an unhandled rejection.
615
- function startCreationSetup({ run, branch, target, notify }) {
669
+ // throwing phase is recorded as a failed setup, never as an unhandled rejection.
670
+ function startCreationSetup({ run, branch, target, key, notify, epoch }) {
616
671
  const task = (async () => {
617
672
  let outcome;
618
673
  try {
@@ -621,8 +676,14 @@ function startCreationSetup({ run, branch, target, notify }) {
621
676
  const message = `creation setup failed: ${(err && err.message) || err}`;
622
677
  outcome = { ok: false, steps: [{ name: 'setup', status: 'failed', detail: message }], warnings: [message] };
623
678
  }
679
+ // A setup whose session ended writes nothing at all: no record, no report.
680
+ if (!creationTaskLive(epoch)) return;
681
+ const settled = settledCreationSetup(outcome);
682
+ creationSetupStates.set(key, settled.problem === null
683
+ ? { status: 'done', branch, steps: settled.steps }
684
+ : { status: 'failed', branch, steps: settled.steps, reason: settled.problem });
624
685
  try {
625
- reportCreationSetup({ branch, target, outcome, notify });
686
+ reportCreationSetup({ branch, target, settled, notify });
626
687
  } catch {
627
688
  // Reporting is the last step of a settled task: a hostile notify never
628
689
  // leaves the task unobserved or the tracking set dirty.
@@ -634,8 +695,9 @@ function startCreationSetup({ run, branch, target, notify }) {
634
695
  return task;
635
696
  }
636
697
 
637
- // Resolves once every tracked setup has settled. Exported for tests and for a
638
- // shutdown path that must not leave a child running behind it.
698
+ // Resolves once every tracked setup has settled. The task stays tracked after its
699
+ // session dropped it, so this seam (exported for tests and for a caller that
700
+ // must not leave a child running behind it) still sees the real completion.
639
701
  async function awaitPendingCreationSetups() {
640
702
  while (creationSetups.size > 0) {
641
703
  await Promise.all(Array.from(creationSetups));
@@ -650,11 +712,12 @@ async function awaitPendingCreationSetups() {
650
712
  async function executeWorktreeCreate(params, ctx, opts) {
651
713
  const git = libRequire("worktree-git.js");
652
714
  const registry = libRequire("worktree-registry.js");
653
- // `backgroundHooks` is the INTERACTIVE create's speed contract: the checkout
654
- // plus its registry row are all the warp needs, so the slow half of the hooks
655
- // (install, codegraph) is handed to a tracked background task instead of
656
- // being awaited. The AGENT tool never sets it — its result is the agent's only
657
- // report, so the hooks must have settled before that result is returned.
715
+ // `backgroundHooks` is the create's speed contract on BOTH fronts: the checkout
716
+ // plus its registry row are all anyone needs, so the slow half of the hooks
717
+ // (dependency install, `codegraph init`) is handed to a tracked background task
718
+ // instead of being awaited. The tool passes it exactly like the panel, so a
719
+ // create answers as soon as the checkout exists and its result says
720
+ // `setup: running in the background` instead of implying a finished install.
658
721
  const backgroundHooks = !!(opts && opts.backgroundHooks === true);
659
722
  // S21: BOTH routes are interactive (the tool handler and the create
660
723
  // panel), so both wait for their children on the async runner. The
@@ -835,11 +898,23 @@ async function executeWorktreeCreate(params, ctx, opts) {
835
898
  // no hook — and it says so instead of claiming a create or an update. The
836
899
  // registry row already exists (`registered: unchanged`), and the CodeGraph
837
900
  // row reports the index the checkout really has, read without initializing
838
- // anything.
901
+ // anything. The one thing a repeat call can add is the deferred setup this
902
+ // checkout already carries: its state rides along as its own row, with the
903
+ // steps that really ran in `details.setup`.
839
904
  const codegraph = codegraphIndexState(owned.path);
905
+ const setup = creationSetupStates.get(path.resolve(owned.path)) || null;
906
+ const lines = [createSuccessText(owned.branch, owned.path, true), 'registered: unchanged', codegraphLine(codegraph), setupStateRow(setup)]
907
+ .filter((line) => typeof line === 'string' && line.length > 0);
840
908
  return textResult(
841
- `${createSuccessText(owned.branch, owned.path, true)}\nregistered: unchanged\n${codegraphLine(codegraph)}`,
842
- { path: owned.path, branch: owned.branch, alreadyExists: true, registered: 'unchanged', codegraph },
909
+ lines.join('\n'),
910
+ {
911
+ path: owned.path,
912
+ branch: owned.branch,
913
+ alreadyExists: true,
914
+ registered: 'unchanged',
915
+ codegraph,
916
+ ...(setup !== null ? { setup } : {}),
917
+ },
843
918
  false,
844
919
  );
845
920
  }
@@ -1034,7 +1109,7 @@ async function executeWorktreeCreate(params, ctx, opts) {
1034
1109
 
1035
1110
  // No approval dialog: a create touches no existing data — the checkout and
1036
1111
  // its registry row are both new — and the panel's create path never asked
1037
- // either. The confirmation that matters lives in `worktree_close`.
1112
+ // either. The confirmation that matters lives in `worktree_delete`.
1038
1113
 
1039
1114
  // (g) Create. S20 branch adoption is resolved BEFORE creating: when
1040
1115
  // `refs/heads/<branch>` already exists (and is not checked out at a
@@ -1362,17 +1437,21 @@ async function executeWorktreeCreate(params, ctx, opts) {
1362
1437
  // overlap and turn a good copy into a reported failure, so the copy is the
1363
1438
  // last awaited step and the setup runs behind it. The create returns as soon
1364
1439
  // as the copy settles (or fails, and says so): the setup's own outcome is
1365
- // reported by `reportCreationSetup`, never swallowed and never awaited here.
1440
+ // recorded for a later create and reported to a caller that asked for a
1441
+ // notice, never awaited here.
1366
1442
  let setupPending = false;
1367
1443
  if (deferredSetup !== null) {
1368
1444
  setupPending = true;
1445
+ creationSetupStates.set(resolvedTarget, { status: 'running', branch });
1369
1446
  startCreationSetup({
1370
1447
  run: deferredSetup,
1371
1448
  branch,
1372
1449
  target,
1373
- notify: (opts && typeof opts.notify === 'function')
1374
- ? opts.notify
1375
- : (ctx && ctx.ui && typeof ctx.ui.notify === 'function' ? (message, level) => ctx.ui.notify(message, level) : null),
1450
+ key: resolvedTarget,
1451
+ epoch: beginCreationTask(),
1452
+ // Only a caller that supplied a notice gets one: the panel's UI. The tool
1453
+ // front supplies none, so no create notifies behind the agent's back.
1454
+ notify: opts && typeof opts.notify === 'function' ? opts.notify : null,
1376
1455
  });
1377
1456
  }
1378
1457
 
@@ -1422,7 +1501,7 @@ async function executeWorktreeCreate(params, ctx, opts) {
1422
1501
  // S7: the registry-write fact sits right after the identity rows, before the
1423
1502
  // hook fact: it is the tool's own bookkeeping and must never be inferred.
1424
1503
  const successText = [createSuccessText(branch, target, false), `registered: ${registeredOutcome}`, codegraphLine(codegraph)].filter((line) => typeof line === "string" && line.length > 0);
1425
- if (setupPending) successText.push("setup: running in the background (install, codegraph)");
1504
+ if (setupPending) successText.push(setupStateRow({ status: 'running' }));
1426
1505
  if (changesRegistered) successText.push("changes: already registered for this session");
1427
1506
  // S3/S4: what the copy actually did, in the same `N files, +A/-B` shape the
1428
1507
  // rest of the worktree surface uses. A clean selection adds no row.
@@ -1517,7 +1596,12 @@ const worktreeCreateTool = withWorktreeCardRenderer(defineTool({
1517
1596
  changes: changesParameterSchema(CHANGES_DESCRIPTION),
1518
1597
  }),
1519
1598
  async execute(toolCallId, params, signal, onUpdate, ctx) {
1520
- return executeWorktreeCreate(params, ctx);
1599
+ // Instant create: the checkout and its registry row settle, the slow setup
1600
+ // (install, codegraph) keeps running in a tracked background task. No notify
1601
+ // callback is passed, so this front never fires a `ui.notify` the agent's
1602
+ // call did not ask for; the result reports the setup state and a later
1603
+ // create for the same checkout reports how the background work ended.
1604
+ return executeWorktreeCreate(params, ctx, { backgroundHooks: true });
1521
1605
  },
1522
1606
  }));
1523
1607
 
@@ -2021,7 +2105,7 @@ async function vanishedCheckouts(git, repoRoot, live, resolvedTarget, after) {
2021
2105
  }
2022
2106
 
2023
2107
  // S24 name resolution — the ONE place checkout names resolve to
2024
- // checkouts. `worktree_close` (by `name`) and the `warp` command verb
2108
+ // checkouts. `worktree_delete` (by `name`) and the `warp` command verb
2025
2109
  // both call this, never separate logic. A name is the flattened branch
2026
2110
  // slug (`slugifyBranch`, already exported by lib/worktree-git.js), or
2027
2111
  // `principal` for the principal checkout.
@@ -2318,7 +2402,7 @@ function closeSessionString(ctx, method) {
2318
2402
  }
2319
2403
  }
2320
2404
 
2321
- // S7/S8/S9: the active-session refusal, shared by `worktree_close` and the warp
2405
+ // S7/S8/S9: the active-session refusal, shared by `worktree_delete` and the warp
2322
2406
  // panel's Ctrl+D (lib/worktree-session-guard.js).
2323
2407
  //
2324
2408
  // The guard answers one question per checkout: is a live Pi session working
@@ -2442,7 +2526,7 @@ async function yoloActiveFor(ctx) {
2442
2526
  }
2443
2527
  }
2444
2528
 
2445
- // Core of `worktree_close` (S7, D6, S6-S9): remove the checkout, keep the
2529
+ // Core of `worktree_delete` (S7, D6, S6-S9): remove the checkout, keep the
2446
2530
  // branch, drop the registry entry. Exported for unit tests; the registered tool
2447
2531
  // calls it with the live Pi context, and the warp panel's Ctrl+D calls it with
2448
2532
  // `opts.approved` after its own question.
@@ -2474,7 +2558,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2474
2558
  const hasName = typeof rawName === "string" && rawName.length > 0;
2475
2559
  if (!hasPath && !hasBranch && !hasName) {
2476
2560
  return errorResult(
2477
- "worktree_close requires a path or a branch or a name: pass the worktree path, branch, or name to close",
2561
+ "worktree_delete requires a path or a branch or a name: pass the worktree path, branch, or name to close",
2478
2562
  { force },
2479
2563
  );
2480
2564
  }
@@ -2483,7 +2567,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2483
2567
  // agree-or-disagree behaviour below.)
2484
2568
  if (hasName && (hasPath || hasBranch)) {
2485
2569
  return errorResult(
2486
- "worktree_close accepts only one of path, branch, or name: pass only one",
2570
+ "worktree_delete accepts only one of path, branch, or name: pass only one",
2487
2571
  { path: rawPath, branch: rawBranch, name: rawName, force },
2488
2572
  );
2489
2573
  }
@@ -2504,7 +2588,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2504
2588
  const byBranch = hasBranch && !hasName ? registry.findByBranch(repo.root, rawBranch) : null;
2505
2589
  if (hasPath && hasBranch && byPath && byBranch && byPath.branch !== byBranch.branch) {
2506
2590
  return errorResult(
2507
- `worktree_close path and branch disagree: path resolves to branch '${byPath.branch}' but branch '${rawBranch}' is registered elsewhere; pass only one`,
2591
+ `worktree_delete path and branch disagree: path resolves to branch '${byPath.branch}' but branch '${rawBranch}' is registered elsewhere; pass only one`,
2508
2592
  { path: rawPath, branch: rawBranch, force },
2509
2593
  );
2510
2594
  }
@@ -2537,7 +2621,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2537
2621
  }
2538
2622
  } else if (resolved.kind === "principal") {
2539
2623
  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`,
2624
+ `cannot close the principal checkout at ${resolved.path}: worktree_delete only closes registered agent worktrees; the checkout and the registry were left untouched`,
2541
2625
  { name: rawName, path: resolved.path, branch: resolved.branch, force },
2542
2626
  );
2543
2627
  } else {
@@ -2555,7 +2639,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2555
2639
  const pid = pst.real !== null ? pst.real : pst.absolute;
2556
2640
  if (entryId !== null && pid !== null && entryId === pid) {
2557
2641
  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`,
2642
+ `cannot close the principal checkout at ${principalRef.path}: worktree_delete only closes registered agent worktrees; the checkout and the registry were left untouched`,
2559
2643
  { name: rawName, path: principalRef.path, branch: principalRef.branch, force },
2560
2644
  );
2561
2645
  }
@@ -2633,7 +2717,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2633
2717
  // is invoked. Without that, a path replaced by a symbolic link while the
2634
2718
  // human answered would be handed to `git worktree remove`, which resolves the
2635
2719
  // spelling it is given and would name ANOTHER checkout. No tool reaches this:
2636
- // `worktree_close` calls this function without options.
2720
+ // `worktree_delete` calls this function without options.
2637
2721
  const expectedReal = opts && typeof opts.expectedReal === "string" && opts.expectedReal.length > 0
2638
2722
  ? opts.expectedReal
2639
2723
  : null;
@@ -2700,7 +2784,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2700
2784
  // selector's keyboard delete, which never consults YOLO at all
2701
2785
  // (`warpDeleteCheckout`). It suppresses the second dialog only: every check
2702
2786
  // 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
2787
+ // unchanged, and no tool can reach this flag because `worktree_delete` calls
2704
2788
  // this function without options.
2705
2789
  const alreadyApproved = !!(opts && opts.approved === true);
2706
2790
  if (ctx && ctx.hasUI && !alreadyApproved) {
@@ -2741,7 +2825,7 @@ async function executeWorktreeClose(params, ctx, opts) {
2741
2825
  }
2742
2826
  if (!approved) {
2743
2827
  return errorResult(
2744
- `worktree close cancelled: approval declined for branch '${branch}'`,
2828
+ `worktree delete cancelled: approval declined for branch '${branch}'`,
2745
2829
  { cancelled: true, branch, path: target, force },
2746
2830
  );
2747
2831
  }
@@ -2923,15 +3007,15 @@ const worktreeListTool = withWorktreeCardRenderer(defineTool({
2923
3007
  }));
2924
3008
 
2925
3009
  const worktreeCloseTool = withWorktreeCardRenderer(defineTool({
2926
- name: "worktree_close",
2927
- label: "Worktree Close",
3010
+ name: "worktree_delete",
3011
+ label: "Worktree Delete",
2928
3012
  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.",
3013
+ 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
3014
  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" })),
3015
+ name: opt(Type.String({ description: "Name of the registered worktree to delete (the flattened branch slug, or principal)" })),
3016
+ path: opt(Type.String({ description: "Path of the registered worktree to delete" })),
3017
+ branch: opt(Type.String({ description: "Branch of the registered worktree to delete" })),
3018
+ force: opt(Type.Boolean({ description: "Delete even when the checkout is dirty" })),
2935
3019
  }),
2936
3020
  async execute(toolCallId, params, signal, onUpdate, ctx) {
2937
3021
  return executeWorktreeClose(params, ctx);
@@ -3471,6 +3555,16 @@ async function executeWorktreeWarpTool(params, ctx, opts) {
3471
3555
  const warpSessions = libRequire("worktree-warp-sessions.js");
3472
3556
  const raw = params && typeof params.name === "string" ? params.name.trim() : "";
3473
3557
  const fromCwd = toolCwd(ctx);
3558
+ // S5: one pending warp per session. While one waits, a second request is
3559
+ // REFUSED here — before anything is resolved, copied or queued — and the
3560
+ // pending request is never disturbed: it is the move someone already asked
3561
+ // for, and the refusal says where it stands.
3562
+ const pendingGate = warpPendingGate(ctx, fromCwd, null);
3563
+ if (pendingGate.pending) {
3564
+ return errorResult(`worktree warp: ${warpPendingRefusalText(pendingGate.pending, raw)}`, {
3565
+ tool: "worktree_warp", name: raw, pending: true,
3566
+ });
3567
+ }
3474
3568
  // S21: the warp is interactive too, so its preflight reads are awaited.
3475
3569
  const runAsync = libRunner(git);
3476
3570
  let repo;
@@ -3665,46 +3759,72 @@ async function executeWorktreeWarpTool(params, ctx, opts) {
3665
3759
  // `fromName`/`name`/`path`/`branch`), so the card falls back to that line
3666
3760
  // instead of painting a move that has not happened. The one visible "moved"
3667
3761
  // 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({
3762
+ // S5/S9: this session's own workloads no longer refuse the handoff — the
3763
+ // request is QUEUED exactly as it is when idle, and the command's pending warp
3764
+ // performs the move once no agent task and no background job is running. What
3765
+ // this tool reports is always the QUEUE, never a move: the idle wording is
3766
+ // byte-identical to before, a busy session gets the waiting line naming both
3767
+ // workloads, and the `queue:` line appears only when the job state could not
3768
+ // be read at all.
3769
+ const toolActivity = await warpSessionActivity(ctx);
3770
+ const toolBusy = !!(toolActivity && toolActivity.busy === true);
3771
+ const preparedToolHandoff = prepareWarpHandoff({
3680
3772
  name: displayName,
3681
3773
  target: targetCwd,
3682
3774
  from: fromCwd,
3683
3775
  branch: displayBranch,
3684
3776
  changes: toolChanges,
3685
- }));
3777
+ });
3778
+ if (!preparedToolHandoff.ok) {
3779
+ return errorResult(
3780
+ `worktree warp: ${preparedToolHandoff.error}`,
3781
+ { tool: "worktree_warp", name: displayName, path: targetCwd, branch: displayBranch, kind: resolved.kind, alreadyThere: false, cancelled: false },
3782
+ );
3783
+ }
3784
+ // S6: the request becomes this session's ONE pending warp at QUEUE time, not
3785
+ // when the command finally runs, so a second `worktree_warp` in the same turn
3786
+ // meets the gate above instead of queueing another handoff. The record is
3787
+ // created only after every validation above passed, so a request refused for
3788
+ // another reason queues nothing, and every terminal outcome on the command
3789
+ // front (moved, refused, cancelled, expired, shutdown) clears this same record.
3790
+ const toolQueue = warpQueuePending({ ctx, fromCwd, name: displayName, prepared: preparedToolHandoff });
3791
+ if (!toolQueue.ok && toolQueue.pending) {
3792
+ return errorResult(`worktree warp: ${warpPendingRefusalText(toolQueue.pending, raw)}`, {
3793
+ tool: "worktree_warp", name: raw, pending: true,
3794
+ });
3795
+ }
3796
+ const handoffDispatched = dispatchWarpHandoff(preparedToolHandoff);
3686
3797
  if (!handoffDispatched.ok) {
3798
+ // Nothing was handed off, so nothing may stay pending.
3799
+ if (toolQueue.ok && toolQueue.pending) warpSettlePending(toolQueue.pending.key);
3687
3800
  return errorResult(
3688
3801
  `worktree warp: ${handoffDispatched.error}`,
3689
3802
  { tool: "worktree_warp", name: displayName, path: targetCwd, branch: displayBranch, kind: resolved.kind, alreadyThere: false, cancelled: false },
3690
3803
  );
3691
3804
  }
3805
+ if (toolQueue.ok && toolQueue.pending) warpMarkDispatched(toolQueue.pending.key);
3692
3806
  const changesNote = toolChanges.mode === "all"
3693
3807
  ? "\nchanges: all (copied when the move lands)"
3694
3808
  : toolChanges.mode === "paths"
3695
3809
  ? `\nchanges: ${toolChanges.paths.length} file${toolChanges.paths.length === 1 ? "" : "s"} (copied when the move lands)`
3696
3810
  : "";
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}`;
3811
+ const jobsNote = toolBusy ? warpJobsUnknownText(toolActivity) : "";
3812
+ const pendingText = [
3813
+ toolBusy
3814
+ ? `worktree warp: ${warpQueuedText(toolActivity)}`
3815
+ : "worktree warp: handoff queued — the session moves when this turn ends",
3816
+ `to: ${warpClean(displayName, "worktree")}`,
3817
+ `path: ${warpClean(targetCwd, "(unknown checkout)")}`,
3818
+ `branch: ${warpClean(displayBranch, "(detached)")}${changesNote}`,
3819
+ ...(jobsNote.length > 0 ? [`queue: ${jobsNote}`] : []),
3820
+ ].join("\n");
3702
3821
  return textResult(
3703
3822
  pendingText,
3704
3823
  {
3705
3824
  tool: "worktree_warp", handoff: true, pending: true,
3706
3825
  pendingName: displayName, pendingPath: targetCwd, pendingBranch: displayBranch,
3707
3826
  from: fromCwd, target: targetCwd, kind: resolved.kind,
3827
+ ...(toolBusy ? { busy: true, queued: true } : {}),
3708
3828
  },
3709
3829
  false,
3710
3830
  );
@@ -4092,12 +4212,33 @@ async function sessionManagerClassFor(ctx) {
4092
4212
  return null;
4093
4213
  }
4094
4214
 
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) {
4215
+ // S4/S9: THIS session's own workloads — its agent-task counters, read from the
4216
+ // presence store the close guard already consumes, and its background jobs, read
4217
+ // through the host's `job_list` tool (lib/worktree-warp-busy.js). Both are one
4218
+ // answer: `busy` is true while an agent task runs or queues OR a job runs.
4219
+ //
4220
+ // The host seam is the one `session-worktree-register.js` already uses:
4221
+ // `ctx.tools` names `job_list` and `ctx.executeTool` calls it. Only those two
4222
+ // members are kept for a queued warp's lifetime, so a 30-minute record pins one
4223
+ // host method (and a projected tool list) instead of the whole command context.
4224
+ // A host without the tool answers `unknown` and blocks nothing.
4225
+ function warpJobHost(ctx) {
4226
+ try {
4227
+ if (!ctx || typeof ctx.executeTool !== "function") return null;
4228
+ const tools = Array.isArray(ctx.tools) ? ctx.tools : null;
4229
+ if (tools === null) return null;
4230
+ const executeTool = ctx.executeTool;
4231
+ return {
4232
+ tools: tools.map((tool) => ({ name: tool && typeof tool.name === "string" ? tool.name : "" })),
4233
+ executeTool: (name, args) => executeTool.call(ctx, name, args),
4234
+ };
4235
+ } catch {
4236
+ return null;
4237
+ }
4238
+ }
4239
+
4240
+ async function warpSessionActivityById(sessionId, host) {
4241
+ if (typeof sessionId !== "string" || sessionId.length === 0) return null;
4101
4242
  let lib = null;
4102
4243
  try {
4103
4244
  lib = libRequire("worktree-warp-busy.js");
@@ -4105,25 +4246,182 @@ async function warpSessionActivity(ctx) {
4105
4246
  return null;
4106
4247
  }
4107
4248
  if (!lib || typeof lib.sessionActivity !== "function") return null;
4108
- const sessionId = closeSessionString(ctx, "getSessionId");
4109
4249
  try {
4110
- return await lib.sessionActivity({ sessionId });
4250
+ return await lib.sessionActivity({ sessionId, host: host || null });
4111
4251
  } catch {
4112
4252
  return null;
4113
4253
  }
4114
4254
  }
4115
4255
 
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) {
4256
+ function warpSessionActivity(ctx) {
4257
+ return warpSessionActivityById(closeSessionString(ctx, "getSessionId"), warpJobHost(ctx));
4258
+ }
4259
+
4260
+ // S5: the queue texts come from the module that produced the counters, so the
4261
+ // tool result, the command notice and the expiry notice cannot drift apart. A
4262
+ // missing module falls back to the same sentences.
4263
+ function warpQueuedText(activity) {
4120
4264
  try {
4121
4265
  const lib = libRequire("worktree-warp-busy.js");
4122
- if (lib && typeof lib.busyText === "function") return lib.busyText(activity);
4266
+ if (lib && typeof lib.queuedText === "function") return lib.queuedText(activity);
4123
4267
  } catch {
4124
4268
  // fall through to the fixed sentence
4125
4269
  }
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";
4270
+ return "handoff queued — waiting for this session's agent tasks and background jobs before the move";
4271
+ }
4272
+
4273
+ // The one line a queued answer adds when, and only when, the job state was
4274
+ // unreadable. An empty string means both workloads were seen.
4275
+ function warpJobsUnknownText(activity) {
4276
+ try {
4277
+ const lib = libRequire("worktree-warp-busy.js");
4278
+ if (lib && typeof lib.jobsUnknownText === "function") return lib.jobsUnknownText(activity);
4279
+ } catch {
4280
+ // fall through to the fixed sentence
4281
+ }
4282
+ return "";
4283
+ }
4284
+
4285
+ function warpPendingRefusalText(pending, requestedName) {
4286
+ try {
4287
+ const lib = libRequire("worktree-warp-busy.js");
4288
+ if (lib && typeof lib.pendingWarpRefusalText === "function") return lib.pendingWarpRefusalText(pending, requestedName);
4289
+ } catch {
4290
+ // fall through to the fixed sentence
4291
+ }
4292
+ const name = pending && typeof pending.name === "string" && pending.name.length > 0 ? pending.name : "that checkout";
4293
+ 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`;
4294
+ }
4295
+
4296
+ // S5: the ONE pending-warp gate. Both fronts ask it, keyed by the session id
4297
+ // (falling back to the checkout the session stands in) so the tool and the
4298
+ // command can never disagree about whether a warp is queued. `retry` is true
4299
+ // only for the pending request's OWN re-dispatched handoff, which must not be
4300
+ // refused as a second warp.
4301
+ function warpPendingGate(ctx, fromCwd, handoff) {
4302
+ const empty = { key: null, pending: null, retry: false };
4303
+ let lib = null;
4304
+ try {
4305
+ lib = libRequire("worktree-warp-busy.js");
4306
+ } catch {
4307
+ return empty;
4308
+ }
4309
+ if (!lib || typeof lib.pendingKeyFor !== "function" || typeof lib.pendingWarpFor !== "function") return empty;
4310
+ let key = null;
4311
+ try {
4312
+ key = lib.pendingKeyFor({ sessionId: closeSessionString(ctx, "getSessionId"), root: fromCwd });
4313
+ } catch {
4314
+ return empty;
4315
+ }
4316
+ if (key === null) return empty;
4317
+ const pending = lib.pendingWarpFor(key);
4318
+ if (!pending) return { key, pending: null, retry: false };
4319
+ let retry = false;
4320
+ try {
4321
+ retry = handoff !== null
4322
+ && handoff !== undefined
4323
+ && typeof lib.sameWarpHandoff === "function"
4324
+ && lib.sameWarpHandoff(pending.handoff, handoff) === true;
4325
+ } catch {
4326
+ retry = false;
4327
+ }
4328
+ return { key, pending, retry };
4329
+ }
4330
+
4331
+ // Hold the validated handoff as this session's one pending warp and start its
4332
+ // poller, which re-dispatches the SAME token through `ctx`-free closures (a
4333
+ // 30-minute queue must not pin a command context). Never throws; `ok:false`
4334
+ // with `pending` means another request got there first, and `ok:false` alone
4335
+ // means this process cannot hold a queue at all.
4336
+ function warpQueuePending({ ctx, fromCwd, name, prepared }) {
4337
+ let lib = null;
4338
+ try {
4339
+ lib = libRequire("worktree-warp-busy.js");
4340
+ } catch {
4341
+ return { ok: false };
4342
+ }
4343
+ if (!lib || typeof lib.queuePendingWarp !== "function" || typeof lib.pendingKeyFor !== "function") return { ok: false };
4344
+ const sessionId = closeSessionString(ctx, "getSessionId");
4345
+ const host = warpJobHost(ctx);
4346
+ let key = null;
4347
+ try {
4348
+ key = lib.pendingKeyFor({ sessionId, root: fromCwd });
4349
+ } catch {
4350
+ return { ok: false };
4351
+ }
4352
+ if (key === null) return { ok: false };
4353
+ // Only the bound notifier is captured: the queue outlives this invocation, and
4354
+ // a 30-minute record must not pin the whole command context (nor anything it
4355
+ // reaches through) just to report an expiry.
4356
+ const ui = ctx && ctx.ui && typeof ctx.ui.notify === "function" ? ctx.ui : null;
4357
+ try {
4358
+ return lib.queuePendingWarp({
4359
+ key,
4360
+ name,
4361
+ token: prepared.token,
4362
+ handoff: prepared.request,
4363
+ env: process.env,
4364
+ host,
4365
+ read: () => warpSessionActivityById(sessionId, host),
4366
+ dispatch: (queuedHandoff) => {
4367
+ const reprepared = prepareWarpHandoff(queuedHandoff);
4368
+ if (!reprepared.ok) return { ok: false, error: reprepared.error };
4369
+ return dispatchWarpHandoff(reprepared);
4370
+ },
4371
+ notify: ui
4372
+ ? (text, level) => { try { ui.notify(text, level); } catch { /* a dead UI never fails the queue */ } }
4373
+ : null,
4374
+ });
4375
+ } catch {
4376
+ return { ok: false };
4377
+ }
4378
+ }
4379
+
4380
+ function warpSettlePending(key) {
4381
+ if (typeof key !== "string" || key.length === 0) return;
4382
+ try {
4383
+ const lib = libRequire("worktree-warp-busy.js");
4384
+ if (lib && typeof lib.settlePendingWarp === "function") lib.settlePendingWarp(key);
4385
+ } catch {
4386
+ // Nothing to clear without the module that holds the queue.
4387
+ }
4388
+ }
4389
+
4390
+ function warpResumePending(key) {
4391
+ if (typeof key !== "string" || key.length === 0) return;
4392
+ try {
4393
+ const lib = libRequire("worktree-warp-busy.js");
4394
+ if (lib && typeof lib.resumePendingWarp === "function") lib.resumePendingWarp(key);
4395
+ } catch {
4396
+ // The dispatched retry settles or expires on its own.
4397
+ }
4398
+ }
4399
+
4400
+ // The tool front already handed its request to the command: the record it just
4401
+ // created only has to refuse a second warp and wait for that dispatch to settle
4402
+ // (or expire), never to send a second copy of the same handoff.
4403
+ function warpMarkDispatched(key) {
4404
+ if (typeof key !== "string" || key.length === 0) return;
4405
+ try {
4406
+ const lib = libRequire("worktree-warp-busy.js");
4407
+ if (lib && typeof lib.markPendingWarpDispatched === "function") lib.markPendingWarpDispatched(key);
4408
+ } catch {
4409
+ // Without the module the queue does not exist, so there is nothing to mark.
4410
+ }
4411
+ }
4412
+
4413
+ // Nothing deferred survives its session: a queued warp dies with the session
4414
+ // that asked for it, so no timer outlives the context it would move.
4415
+ function forgetPendingWarp(ctx) {
4416
+ try {
4417
+ const lib = libRequire("worktree-warp-busy.js");
4418
+ if (!lib || typeof lib.pendingKeyFor !== "function" || typeof lib.settlePendingWarp !== "function") return;
4419
+ const root = ctx && typeof ctx.cwd === "string" && ctx.cwd.length > 0 ? ctx.cwd : null;
4420
+ const key = lib.pendingKeyFor({ sessionId: closeSessionString(ctx, "getSessionId"), root });
4421
+ if (key !== null) lib.settlePendingWarp(key);
4422
+ } catch {
4423
+ // A shutdown never fails on bookkeeping.
4424
+ }
4127
4425
  }
4128
4426
 
4129
4427
  // The COMMAND front's bounded wait: a warp lands after this turn settles, so it
@@ -4142,7 +4440,7 @@ async function warpWaitForIdleSession(ctx) {
4142
4440
  try {
4143
4441
  // The budget travels through the environment so a session can bound its own
4144
4442
  // wait (ODD_WORKTREE_WARP_BUSY_WAIT_MS); the default keeps a warp short.
4145
- return await lib.waitForSessionActivity({ sessionId, env: process.env });
4443
+ return await lib.waitForSessionActivity({ sessionId, env: process.env, host: warpJobHost(ctx) });
4146
4444
  } catch {
4147
4445
  return null;
4148
4446
  }
@@ -4460,7 +4758,62 @@ async function warpMaybeCopyDirty({ ctx, git, fromCheckout, targetCwd, options }
4460
4758
  }
4461
4759
  return { ok: true, copied };
4462
4760
  }
4761
+ // S5: the change selection a QUEUED human warp carries. A queued handoff cannot
4762
+ // prompt (the command's handoff path never asks), so the same YES COPY / NO COPY
4763
+ // question the idle warp asks is answered NOW and travels in the token; the copy
4764
+ // itself still runs at move time inside the command. Cancelling queues nothing.
4765
+ // Never throws.
4766
+ async function warpQueuedChangesSelection({ ctx, git, fromCheckout, skipPrompt, options }) {
4767
+ const none = { ok: true, changes: { mode: 'none', paths: [] } };
4768
+ if (skipPrompt === true) return none;
4769
+ let changesLib = null;
4770
+ try {
4771
+ changesLib = libRequire('worktree-changes.js');
4772
+ } catch {
4773
+ return none;
4774
+ }
4775
+ let summary;
4776
+ try {
4777
+ summary = await changesLib.summarizeChanges(fromCheckout, { git });
4778
+ } catch {
4779
+ return none;
4780
+ }
4781
+ if (!summary || summary.ok !== true || summary.files === 0) return none;
4782
+ const summaryLine = `${summary.files} file${summary.files === 1 ? '' : 's'}, +${summary.added}/-${summary.deleted}`;
4783
+ const choice = await askWarpDirtyChoice(ctx, summaryLine, options);
4784
+ if (choice === null) return { cancelled: true };
4785
+ return choice === 'yes'
4786
+ ? { ok: true, changes: { mode: 'all', paths: [] } }
4787
+ : none;
4788
+ }
4789
+
4790
+ // S5: the ONE warp gate every front shares (the tool's queued handoff, a typed
4791
+ // `/warp <name>`, the selector pick and a create's follow-up warp). While a
4792
+ // pending warp exists, a SECOND request is refused here — it queues nothing,
4793
+ // switches nothing and never touches the pending request. The pending retry is
4794
+ // recognised by its own handoff, so the re-dispatched `/warp @<token>` runs, and
4795
+ // every terminal outcome (moved, refused, cancelled) clears the record so a
4796
+ // later warp is accepted again. A retry that finds the counters busy again
4797
+ // resumes the queue instead of settling it.
4463
4798
  async function executeWorktreeWarp(rawName, ctx, opts) {
4799
+ const options = opts || {};
4800
+ const gate = warpPendingGate(ctx, toolCwd(ctx), normalizeWarpHandoff(options.handoff));
4801
+ if (gate.pending && gate.retry !== true) {
4802
+ return warpFail(`worktree warp: ${warpPendingRefusalText(gate.pending, rawName)}`, {
4803
+ name: typeof rawName === "string" ? rawName.trim() : "",
4804
+ alreadyThere: false, cancelled: false, pending: true,
4805
+ });
4806
+ }
4807
+ const out = await performWorktreeWarp(rawName, ctx, options, gate.retry === true);
4808
+ if (out && out.stillQueued === true) {
4809
+ if (gate.pending && gate.key !== null) warpResumePending(gate.key);
4810
+ return out;
4811
+ }
4812
+ if (gate.key !== null) warpSettlePending(gate.key);
4813
+ return out;
4814
+ }
4815
+
4816
+ async function performWorktreeWarp(rawName, ctx, opts, retry) {
4464
4817
  const options = opts || {};
4465
4818
  const git = libRequire("worktree-git.js");
4466
4819
  const registry = libRequire("worktree-registry.js");
@@ -4490,17 +4843,14 @@ async function executeWorktreeWarp(rawName, ctx, opts) {
4490
4843
  );
4491
4844
  }
4492
4845
  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.
4846
+ // S4/S5: a session with running agent tasks is IDLE for the host, so the wait
4847
+ // above does not wait for that work. This front gives the published counters a
4848
+ // bounded chance to drain (ODD_WORKTREE_WARP_BUSY_WAIT_MS) and QUEUES the
4849
+ // request when they have not: nothing switches under work that is still
4850
+ // running, and the queued handoff is performed once the counters drain. A
4851
+ // store that is absent or unreadable blocks nothing.
4498
4852
  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
- }
4853
+ const sessionLoad = busyWait && busyWait.activity ? busyWait.activity : null;
4504
4854
  const fromCwd = typeof ctx.cwd === "string" && ctx.cwd.length > 0 ? ctx.cwd : process.cwd();
4505
4855
  // S21: the same awaited preflight reads as the tool, so a slow repository
4506
4856
  // never freezes the session that is being moved.
@@ -4618,6 +4968,92 @@ async function executeWorktreeWarp(rawName, ctx, opts) {
4618
4968
  // through `failAfterCopy` (below) and why a retry must prove the copied state
4619
4969
  // byte for byte before it skips anything.
4620
4970
  const dirtyFrom = warpDeepestContaining(sessionId, warpLiveIdentities(live, repo.root)) || fromCwd;
4971
+ // S5: the QUEUED warp. This session still reports running or queued agent
4972
+ // tasks, so nothing switches: the request is validated and kept as this
4973
+ // session's one pending warp, and lib/worktree-warp-busy.js re-dispatches the
4974
+ // SAME handoff once the counters drain. What this returns says queued, never
4975
+ // moved, and says plainly that only this session's agent-task counters drain
4976
+ // the queue.
4977
+ if (sessionLoad && sessionLoad.busy === true) {
4978
+ const queuedSelection = handoff
4979
+ ? { ok: true, changes: handoff.changes }
4980
+ : await warpQueuedChangesSelection({
4981
+ ctx, git, fromCheckout: dirtyFrom, skipPrompt: skipDirtyPrompt, options: opts,
4982
+ });
4983
+ if (queuedSelection.cancelled === true) {
4984
+ return warpFail(
4985
+ `worktree warp: ${name} cancelled (the session stays in ${fromCwd})`,
4986
+ { name, alreadyThere: false, cancelled: true },
4987
+ );
4988
+ }
4989
+ const queuedHandoff = prepareWarpHandoff({
4990
+ name: displayName,
4991
+ target: targetCwd,
4992
+ from: fromCwd,
4993
+ branch: displayBranch,
4994
+ changes: queuedSelection.changes,
4995
+ });
4996
+ if (!queuedHandoff.ok) {
4997
+ return warpFail(`worktree warp: ${queuedHandoff.error}`, { name, alreadyThere: false, cancelled: false });
4998
+ }
4999
+ const queued = warpQueuePending({ ctx, fromCwd, name: displayName, prepared: queuedHandoff });
5000
+ // Both workloads are named in the queue text; the extra line appears only
5001
+ // when the job state could not be read at all.
5002
+ const queuedJobsNote = warpJobsUnknownText(sessionLoad);
5003
+ const queuedLines = [
5004
+ `worktree warp: ${warpQueuedText(sessionLoad)}`,
5005
+ ...(queuedJobsNote.length > 0 ? [`queue: ${queuedJobsNote}`] : []),
5006
+ ];
5007
+ if (!queued.ok && queued.pending) {
5008
+ // This IS the pending retry and the workloads filled up again: keep the
5009
+ // queue (the wrapper resumes its poller) instead of refusing our own move.
5010
+ if (retry === true) {
5011
+ return {
5012
+ text: queuedLines.join("\n"),
5013
+ details: {
5014
+ name: displayName, path: targetCwd, branch: displayBranch, kind: resolved.kind,
5015
+ alreadyThere: false, cancelled: false, busy: true, queued: true, pending: true,
5016
+ },
5017
+ stillQueued: true,
5018
+ };
5019
+ }
5020
+ return warpFail(`worktree warp: ${warpPendingRefusalText(queued.pending, name)}`, {
5021
+ name, alreadyThere: false, cancelled: false, pending: true,
5022
+ });
5023
+ }
5024
+ if (!queued.ok) {
5025
+ return warpFail(
5026
+ "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",
5027
+ { name, alreadyThere: false, cancelled: false, busy: true },
5028
+ );
5029
+ }
5030
+ // A human front is told ONCE that the request is queued (a handoff already
5031
+ // reported itself in the tool result); the queue's own notice covers expiry
5032
+ // later. The retry says nothing, so one queued warp makes one notice.
5033
+ if (!handoff && ctx && ctx.ui && typeof ctx.ui.notify === "function") {
5034
+ try {
5035
+ ctx.ui.notify(queuedLines.join("; "), "info");
5036
+ } catch {
5037
+ // A dead UI never fails the queue.
5038
+ }
5039
+ }
5040
+ const queuedChangesNote = queuedSelection.changes && queuedSelection.changes.mode === "all"
5041
+ ? "\nchanges: all (copied when the move lands)"
5042
+ : queuedSelection.changes && queuedSelection.changes.mode === "paths"
5043
+ ? `\nchanges: ${queuedSelection.changes.paths.length} file${queuedSelection.changes.paths.length === 1 ? "" : "s"} (copied when the move lands)`
5044
+ : "";
5045
+ return {
5046
+ text: `worktree warp: ${warpQueuedText(sessionLoad)}\n`
5047
+ + `to: ${warpClean(displayName, "worktree")}${queuedChangesNote}`
5048
+ + (queuedJobsNote.length > 0 ? `\nqueue: ${queuedJobsNote}` : ""),
5049
+ details: {
5050
+ name: displayName, path: targetCwd, branch: displayBranch, kind: resolved.kind,
5051
+ alreadyThere: false, cancelled: false, busy: true, queued: true, pending: true,
5052
+ expiresAt: queued.pending ? queued.pending.expiresAt : null,
5053
+ },
5054
+ stillQueued: true,
5055
+ };
5056
+ }
4621
5057
  // A handoff copy that has landed in the destination is REAL state. It is never
4622
5058
  // rolled back automatically — deleting or reverting files nobody authorized us
4623
5059
  // to touch is exactly the destructive guess this path refuses — so every
@@ -6036,7 +6472,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6036
6472
  }
6037
6473
  }
6038
6474
 
6039
- // S7/S8/S9: the SAME active-session guard `worktree_close` runs, and it runs
6475
+ // S7/S8/S9: the SAME active-session guard `worktree_delete` runs, and it runs
6040
6476
  // BEFORE anything reads the pending changes or builds the deletion question.
6041
6477
  // A keypress may never turn into a confirmation dialog for a checkout a live
6042
6478
  // Pi session is working in: the human is told to finish/warp that session
@@ -6095,7 +6531,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6095
6531
  // realpath comparison cannot see. An unreadable pair is a REFUSAL: without it
6096
6532
  // the removal cannot say which directory it is about to destroy.
6097
6533
  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");
6534
+ 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
6535
  return;
6100
6536
  }
6101
6537
  const approvedPin = { real: approvedReal, dev: before.identity.dev, ino: before.identity.ino };
@@ -6111,7 +6547,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6111
6547
  const reason = changes && typeof changes.reason === "string" && changes.reason.length > 0
6112
6548
  ? changes.reason
6113
6549
  : "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");
6550
+ 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
6551
  return;
6116
6552
  }
6117
6553
  const content = evidence.content && typeof evidence.content === "object" ? evidence.content : null;
@@ -6119,7 +6555,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6119
6555
  const reason = content && typeof content.reason === "string" && content.reason.length > 0
6120
6556
  ? content.reason
6121
6557
  : "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");
6558
+ 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
6559
  return;
6124
6560
  }
6125
6561
  const ignored = evidence.ignored && typeof evidence.ignored === "object" ? evidence.ignored : null;
@@ -6127,7 +6563,7 @@ async function warpDeleteCheckout(targetPath, ctx, deps) {
6127
6563
  const reason = ignored && typeof ignored.reason === "string" && ignored.reason.length > 0
6128
6564
  ? ignored.reason
6129
6565
  : "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");
6566
+ 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
6567
  return;
6132
6568
  }
6133
6569
 
@@ -6629,6 +7065,20 @@ function registerWarpCommand(pi) {
6629
7065
  handler: async (args, ctx) => {
6630
7066
  const notify = ctx?.ui?.notify;
6631
7067
  const raw = String(args ?? "").trim();
7068
+ // S5: one pending warp per session, refused on EVERY front here — the
7069
+ // selector is not even opened for a request that cannot run — except for
7070
+ // the pending request's own re-dispatched handoff, which is the move this
7071
+ // queue exists to perform.
7072
+ const earlyHandoff = raw.startsWith(WARP_HANDOFF_PREFIX) ? decodeWarpHandoff(raw) : null;
7073
+ const earlyGate = warpPendingGate(
7074
+ ctx,
7075
+ toolCwd(ctx),
7076
+ earlyHandoff && earlyHandoff.ok === true ? earlyHandoff.request : null,
7077
+ );
7078
+ if (earlyGate.pending && earlyGate.retry !== true) {
7079
+ notify?.(`worktree warp: ${warpPendingRefusalText(earlyGate.pending, raw)}`, "error");
7080
+ return;
7081
+ }
6632
7082
  // An agent handoff (queued by the `worktree_warp` tool) travels as ONE
6633
7083
  // `@<token>` argument. It is decoded and re-validated here; a rejected
6634
7084
  // token changes nothing and names no part of what it carried. Everything
@@ -7691,11 +8141,18 @@ export default function (pi) {
7691
8141
  await checkIssuesGate(pi, ctx);
7692
8142
  });
7693
8143
  pi.on("session_shutdown", forgetWorktreeCardUi);
8144
+ // A queued warp is session state: shutdown clears its record and its timer so
8145
+ // nothing outlives the session that asked for the move.
8146
+ pi.on("session_shutdown", (event, ctx) => {
8147
+ forgetPendingWarp(ctx);
8148
+ });
7694
8149
  // Nothing deferred survives its session: shutdown advances the startup epoch,
7695
8150
  // so work still in flight drops instead of writing into the session that
7696
- // replaced it.
8151
+ // replaced it, and it drops the deferred creation setups with it — a late
8152
+ // settle records and reports nothing.
7697
8153
  pi.on("session_shutdown", () => {
7698
8154
  startupEpoch += 1;
8155
+ forgetCreationSetups();
7699
8156
  });
7700
8157
  pi.on("tool_call", (event, ctx) => handleWorktreeOddEvent(event, ctx, pi));
7701
8158
  pi.on("tool_result", (event, ctx) => handleWorktreeOddEvent(event, ctx, pi, true));