pi-odd-worktree 2.0.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.
package/README.md CHANGED
@@ -66,7 +66,13 @@ as commands, and the four `worktree_*` tools are offered to the agent.
66
66
  `worktree_create` needs a `branch` and a mandatory `changes` selection:
67
67
  `"all"`, `"none"`, or a list of checkout-relative paths. It never guesses,
68
68
  and a repository with no local `main` is refused before anything is written.
69
- An existing branch is adopted as-is instead of being recreated.
69
+ An existing branch is adopted as-is instead of being recreated. **A create is
70
+ instant**: the checkout and its registry row are the answer, and the slow half
71
+ of the setup — dependency install, `codegraph init` — continues in a tracked
72
+ background task on both fronts. The panel notifies you when it finishes; the
73
+ tool says `setup: running in the background (install, codegraph)` and a later
74
+ `worktree_create` for the same checkout reports how it ended. Nothing is
75
+ skipped, and a deferred setup never turns a successful create into an error.
70
76
  2. **List** — `worktree_list`, or open `/warp`. Pass `all: true` to the tool (or
71
77
  `v` in the panel) to also see live checkouts the registry does not know.
72
78
  3. **Move** — `/warp <name>`, the selector's `enter`, or `worktree_warp`. The
@@ -220,9 +226,11 @@ start, unless you set `CODEGRAPH_FORCE=1`, which answers "present" without
220
226
  probing.
221
227
 
222
228
  - **On creation**, `worktree_create` runs `codegraph init` inside the new
223
- checkout, so it starts with its own index. A session where the gate answered
224
- false reports that step as `skipped` and names the gate as the reason; it never
225
- silently pretends to have indexed anything.
229
+ checkout, so it starts with its own index. It runs in the background half of
230
+ the create's setup (see *Create* above), so the checkout is usable before the
231
+ index is written. A session where the gate answered false reports that step as
232
+ `skipped` and names the gate as the reason; it never silently pretends to have
233
+ indexed anything.
226
234
  - **On edits**, a successful `edit` or `write` schedules `codegraph sync` for the
227
235
  git toplevel of the file touched, so a worktree syncs that worktree. The sync is
228
236
  detached: the tool result never waits for it, and a failure never reaches you.
@@ -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
  }
@@ -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
 
@@ -8064,9 +8148,11 @@ export default function (pi) {
8064
8148
  });
8065
8149
  // Nothing deferred survives its session: shutdown advances the startup epoch,
8066
8150
  // so work still in flight drops instead of writing into the session that
8067
- // replaced it.
8151
+ // replaced it, and it drops the deferred creation setups with it — a late
8152
+ // settle records and reports nothing.
8068
8153
  pi.on("session_shutdown", () => {
8069
8154
  startupEpoch += 1;
8155
+ forgetCreationSetups();
8070
8156
  });
8071
8157
  pi.on("tool_call", (event, ctx) => handleWorktreeOddEvent(event, ctx, pi));
8072
8158
  pi.on("tool_result", (event, ctx) => handleWorktreeOddEvent(event, ctx, pi, true));
@@ -304,12 +304,13 @@ async function isTrackedByGitAsync(runAsync, principalRoot, candidate, timeoutMs
304
304
  // error / timeout / abort kills it). Never skips installs/codegraph as
305
305
  // a speed fix; no extra retries beyond the npm fallback. Fixed argv only.
306
306
  //
307
- // `deferSetup: true` splits the run for the INTERACTIVE create: the file-level
308
- // steps (unversioned copies, principal links) still settle before it returns,
309
- // while the slow half (dependency install, `codegraph init`) travels back as
310
- // `setup()` — one callable, run once, never rejecting — so the human returns to
311
- // Warp as soon as the checkout path exists. Nothing is skipped: the deferred
312
- // phases still run, just after the caller has handed control back.
307
+ // `deferSetup: true` splits the run for BOTH create fronts (the `worktree_create`
308
+ // tool and the panel): the file-level steps (unversioned copies, principal links)
309
+ // still settle before it returns, while the slow half (dependency install,
310
+ // `codegraph init`) travels back as `setup()` — one callable, run once, never
311
+ // rejecting — so the caller hands the checkout back as soon as it exists.
312
+ // Nothing is skipped: the deferred phases still run, just after the caller has
313
+ // handed control back.
313
314
  async function runCreationHooksAsync(opts = {}) {
314
315
  const principalRoot = resolvePrincipal(opts);
315
316
  const worktreePath = resolveWorktree(opts);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-odd-worktree",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "description": "Pi package for odd-worktree: the Agent Worktree tools (create, list, close, warp), the /warp worktree panel, the /odd-list ODD viewer, and the /issues GitHub issue reader. Works in Pi alone; Herdr is optional.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -19,7 +19,7 @@
19
19
  // A job whose status field is not running/queued is finished, a `job_list` that
20
20
  // is missing, fails or answers in an unknown shape is UNKNOWN (never "no jobs"),
21
21
  // and unknown blocks nothing.
22
- const { test, describe, before, after } = require('node:test');
22
+ const { test, describe, before, after, afterEach } = require('node:test');
23
23
  const assert = require('node:assert/strict');
24
24
  const crypto = require('node:crypto');
25
25
  const fs = require('node:fs');
@@ -63,6 +63,11 @@ function settlePending() {
63
63
  busyLib.settlePendingWarp(pendingKey());
64
64
  }
65
65
 
66
+ // The queue is ONE record per session, held in this process and shared by every
67
+ // test in this file: each test clears its own, and this backstop keeps an
68
+ // unrelated assertion failure from leaking a record into the tests after it.
69
+ afterEach(() => { settlePending(); });
70
+
66
71
  function git(cwd, args) {
67
72
  const out = spawnSync('git', args, { cwd, encoding: 'utf8' });
68
73
  if (out.status !== 0) throw new Error(`git ${args.join(' ')} failed: ${out.stderr}`);
@@ -11,7 +11,8 @@ const fs = require('node:fs');
11
11
  const os = require('node:os');
12
12
  const path = require('node:path');
13
13
  const { spawnSync } = require('node:child_process');
14
- const { loadExtension } = require('./fixtures/load-extension.js');
14
+ const { pathToFileURL } = require('node:url');
15
+ const { LIB_DIR, stubbedSource } = require('./fixtures/load-extension.js');
15
16
 
16
17
  const scratch = [];
17
18
  function track(dir) {
@@ -168,15 +169,45 @@ function makeUiCtx(repoRoot, thread = 'thread-1') {
168
169
  }
169
170
 
170
171
  let tools;
172
+ let extensionMod;
173
+ let extensionHooks;
171
174
  before(async () => {
172
175
  process.env.HERDR_BIN_PATH = NO_HERDR;
173
176
  process.env.GENTLE_WORKTREE_THREAD = 'thread-1';
174
177
  process.env.PATH = `${HOOK_BIN}${path.delimiter}${savedEnv.PATH || ''}`;
175
178
  delete process.env.GENTLE_PI_AGENT_HOME;
176
179
  process.env.PI_CODING_AGENT_DIR = AGENT_HOME;
177
- ({ tools } = await loadExtension({}));
180
+ ({ tools, mod: extensionMod, hooks: extensionHooks } = await loadExtensionWithModule({}));
178
181
  });
179
182
 
183
+ // The create is instant on BOTH fronts, and its deferred setup is tracked by the
184
+ // module instance that registered the tool. `awaitPendingCreationSetups` is that
185
+ // instance's own exported seam (the same one a shutdown path uses), so this file
186
+ // loads the extension itself — same stubs, same lib override, same fake host as
187
+ // the shared fixture — and keeps the module namespace beside the registrations.
188
+ async function loadExtensionWithModule(pi) {
189
+ process.env.GENTLE_WORKTREE_LIB_DIR = LIB_DIR;
190
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'odd-wt-ext-'));
191
+ try {
192
+ const copy = path.join(dir, 'odd-worktree-tools.mjs');
193
+ fs.writeFileSync(copy, stubbedSource());
194
+ const mod = await import(pathToFileURL(copy).href);
195
+ const commands = new Map();
196
+ const tools = new Map();
197
+ const hooks = [];
198
+ mod.default({
199
+ registerCommand: (name, handler) => { commands.set(name, handler); },
200
+ registerTool: (tool) => { tools.set(tool.name, tool); },
201
+ registerMessageRenderer: () => {},
202
+ on: (event, handler) => { hooks.push([event, handler]); },
203
+ ...pi,
204
+ });
205
+ return { mod, commands, tools, hooks };
206
+ } finally {
207
+ fs.rmSync(dir, { recursive: true, force: true });
208
+ }
209
+ }
210
+
180
211
  describe('worktree_list', () => {
181
212
  test('a fresh repository lists its principal checkout only', async () => {
182
213
  const repo = makeRepo();
@@ -456,3 +487,136 @@ describe('worktree_delete', () => {
456
487
  assert.ok(branches(repo).includes('feat/stale'), 'the branch is kept');
457
488
  });
458
489
  });
490
+
491
+ // ---------------------------------------------------------------------------
492
+ // The create is INSTANT on both fronts: the checkout and its registry row are
493
+ // the answer, and the slow half of the setup (dependency install, `codegraph
494
+ // init`) finishes behind it in a tracked task. Nothing is skipped, and the tool
495
+ // front never notifies a UI its call did not ask for.
496
+ // ---------------------------------------------------------------------------
497
+ describe('an instant create finishes its setup in the background', { concurrency: false }, () => {
498
+ // A `codegraph` that is visibly SLOW: it records that it started, waits, then
499
+ // records that it finished. A create that awaited the setup could never return
500
+ // between the two lines.
501
+ function slowCodegraph(markerPath) {
502
+ const dir = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-wt-slowbin-')));
503
+ fs.writeFileSync(
504
+ path.join(dir, 'codegraph'),
505
+ `#!/bin/sh\nprintf 'started\\n' >> '${markerPath}'\nsleep 0.5\nprintf 'finished\\n' >> '${markerPath}'\n`,
506
+ { mode: 0o755 },
507
+ );
508
+ return dir;
509
+ }
510
+
511
+ function markerFile() {
512
+ return path.join(track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-wt-marker-'))), 'codegraph.log');
513
+ }
514
+
515
+ function readMarker(marker) {
516
+ return fs.existsSync(marker) ? fs.readFileSync(marker, 'utf8') : '';
517
+ }
518
+
519
+ function binWith(name, script) {
520
+ const dir = track(fs.mkdtempSync(path.join(os.tmpdir(), 'odd-wt-bin-')));
521
+ fs.writeFileSync(path.join(dir, name), script, { mode: 0o755 });
522
+ return dir;
523
+ }
524
+
525
+ test('the result returns first, the codegraph step still runs to the end, and a later create reports it', async () => {
526
+ const repo = makeRepo();
527
+ const marker = markerFile();
528
+ const savedPath = process.env.PATH;
529
+ process.env.PATH = `${slowCodegraph(marker)}${path.delimiter}${savedPath}`;
530
+ try {
531
+ const { ctx, notifications } = makeCtx(repo);
532
+ const created = await tools.get('worktree_create').execute('instant-1', { branch: 'feat/instant', changes: 'none' }, undefined, undefined, ctx);
533
+ assert.notEqual(created.isError, true, resultText(created));
534
+ const text = resultText(created);
535
+ assert.match(text, /^created: feat-instant · feat\/instant$/m);
536
+ assert.match(text, /^setup: running in the background \(install, codegraph\)$/m, text);
537
+ assert.match(text, /^codegraph: pending /m, 'the create states the step is not done yet');
538
+ assert.equal(created.details.setupPending, true);
539
+ assert.equal(/finished/.test(readMarker(marker)), false, 'the create returned only after its setup had finished');
540
+ assert.ok(fs.existsSync(path.join(path.dirname(repo), `${path.basename(repo)}-worktrees`, 'feat-instant')), 'the checkout is usable at return time');
541
+
542
+ // Nothing is skipped: the deferred task still reaches the end of the
543
+ // codegraph step, observed through the module's own
544
+ // `awaitPendingCreationSetups` seam.
545
+ await extensionMod.awaitPendingCreationSetups();
546
+ assert.equal(readMarker(marker).includes('finished'), true, 'the background codegraph step never ran to the end');
547
+
548
+ // The settled lifecycle is readable through the tool surface: asking again
549
+ // for the same checkout reports the state and the steps that really ran.
550
+ const replay = await tools.get('worktree_create').execute('instant-2', { branch: 'feat/instant', changes: 'none' }, undefined, undefined, ctx);
551
+ assert.notEqual(replay.isError, true, resultText(replay));
552
+ assert.match(resultText(replay), /^registered: unchanged$/m);
553
+ assert.match(resultText(replay), /^setup: finished$/m, resultText(replay));
554
+ assert.ok(
555
+ replay.details.setup.steps.some((step) => step.name === 'codegraph-init' && step.status === 'done'),
556
+ `the codegraph step is reported as done: ${JSON.stringify(replay.details.setup.steps)}`,
557
+ );
558
+ assert.deepEqual(notifications, [], 'the tool front never notifies a UI its call did not ask for');
559
+ } finally {
560
+ process.env.PATH = savedPath;
561
+ }
562
+ });
563
+
564
+ test('only a caller that asks for the notice gets it, and a session that ends gets none', async () => {
565
+ const repo = makeRepo();
566
+ const { ctx } = makeCtx(repo);
567
+ const notes = [];
568
+ const notify = (message, level) => { notes.push([level, message]); };
569
+ const created = await extensionMod.executeWorktreeCreate(
570
+ { branch: 'feat/notified', changes: 'none' },
571
+ ctx,
572
+ { backgroundHooks: true, notify },
573
+ );
574
+ assert.notEqual(created.isError, true, resultText(created));
575
+ await extensionMod.awaitPendingCreationSetups();
576
+ assert.deepEqual(notes, [['info', 'warp: setup finished for feat/notified: codegraph initialized']]);
577
+
578
+ // A setup that settles after its session ended records and reports nothing:
579
+ // the session it belonged to is gone, so there is no UI to write into.
580
+ const marker = markerFile();
581
+ const savedPath = process.env.PATH;
582
+ process.env.PATH = `${slowCodegraph(marker)}${path.delimiter}${savedPath}`;
583
+ try {
584
+ const late = await extensionMod.executeWorktreeCreate(
585
+ { branch: 'feat/late', changes: 'none' },
586
+ ctx,
587
+ { backgroundHooks: true, notify },
588
+ );
589
+ assert.notEqual(late.isError, true, resultText(late));
590
+ notes.length = 0;
591
+ // The shutdown hooks of the SAME instance that owns the deferred task: it
592
+ // is the session that created the checkout that ends here.
593
+ for (const [, handler] of extensionHooks.filter(([name]) => name === 'session_shutdown')) await handler({}, ctx);
594
+ await extensionMod.awaitPendingCreationSetups();
595
+ assert.deepEqual(notes, [], 'a setup that settles after shutdown reports nothing');
596
+ } finally {
597
+ process.env.PATH = savedPath;
598
+ }
599
+ });
600
+
601
+ test('a problem in the deferred setup is a warning, never an error', async () => {
602
+ const repo = makeRepo();
603
+ const { ctx } = makeCtx(repo);
604
+ const notes = [];
605
+ const savedPath = process.env.PATH;
606
+ process.env.PATH = `${binWith('codegraph', '#!/bin/sh\nexit 1\n')}${path.delimiter}${savedPath}`;
607
+ try {
608
+ const created = await extensionMod.executeWorktreeCreate(
609
+ { branch: 'feat/broken', changes: 'none' },
610
+ ctx,
611
+ { backgroundHooks: true, notify: (message, level) => { notes.push([level, message]); } },
612
+ );
613
+ assert.notEqual(created.isError, true, resultText(created));
614
+ await extensionMod.awaitPendingCreationSetups();
615
+ assert.deepEqual(notes.map(([level]) => level), ['warning'], JSON.stringify(notes));
616
+ assert.match(notes[0][1], /^warp: setup for feat\/broken finished with problems: codegraph-init: codegraph init failed/);
617
+ assert.match(notes[0][1], / — the checkout at .+ is usable$/);
618
+ } finally {
619
+ process.env.PATH = savedPath;
620
+ }
621
+ });
622
+ });