opencode-model-router 2.9.1 → 2.11.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.
Files changed (59) hide show
  1. package/CHANGELOG.md +482 -0
  2. package/README.md +4 -2
  3. package/package.json +12 -5
  4. package/src/compat/background.ts +56 -19
  5. package/src/compat/child-history.ts +134 -0
  6. package/src/compat/child-report.ts +185 -0
  7. package/src/compat/child-session.ts +10 -0
  8. package/src/compat/session-lookup.ts +21 -0
  9. package/src/compat/v2-client.ts +124 -6
  10. package/src/compat/v2-hooks.ts +525 -203
  11. package/src/compat/v2-observations.ts +1 -0
  12. package/src/compat/v2-vocabulary.ts +14 -0
  13. package/src/executor/create.ts +47 -28
  14. package/src/executor/git.ts +226 -30
  15. package/src/executor/integrate/checks.ts +29 -11
  16. package/src/executor/integrate/land.ts +32 -2
  17. package/src/executor/integrate/queue.ts +95 -13
  18. package/src/executor/ledger.ts +16 -12
  19. package/src/executor/lfs-restore.ts +492 -0
  20. package/src/executor/paths.ts +7 -2
  21. package/src/executor/recovery.ts +2 -1
  22. package/src/executor/runtime.ts +1062 -243
  23. package/src/executor/slots/pool.ts +120 -19
  24. package/src/executor/slots/provision.ts +111 -23
  25. package/src/executor/slots/root.ts +81 -0
  26. package/src/executor/types.ts +28 -2
  27. package/src/executor/unattended.ts +6 -1
  28. package/src/executor/verify-trees.ts +507 -0
  29. package/src/guard/enforce.ts +2 -1
  30. package/src/guard/fingerprint.ts +9 -0
  31. package/src/guard/guards.ts +7 -1
  32. package/src/index.ts +191 -31
  33. package/src/router/answer-dedup.ts +198 -0
  34. package/src/router/common-dir.ts +241 -0
  35. package/src/router/config.ts +228 -40
  36. package/src/router/diff-handles.ts +322 -0
  37. package/src/router/diff-summary.ts +318 -0
  38. package/src/router/git-metadata-guard.ts +317 -0
  39. package/src/router/git-tools.ts +1136 -49
  40. package/src/router/read-only.ts +37 -13
  41. package/src/router/role-agents.ts +100 -36
  42. package/src/router/run-summary.ts +253 -0
  43. package/src/router/run-tools.ts +177 -25
  44. package/src/router/sessions.ts +23 -1
  45. package/src/router/tool-paths.ts +62 -4
  46. package/src/routing/classify/rules.ts +93 -14
  47. package/src/routing/roles/read-set.ts +10 -1
  48. package/src/routing/roles/work-root.ts +20 -3
  49. package/src/routing/wire/hint.ts +9 -2
  50. package/src/v2.ts +3 -1
  51. package/src/verify/exec.ts +454 -2
  52. package/src/verify/head.ts +6 -1
  53. package/src/verify/pending.ts +14 -1
  54. package/src/verify/plan-task.ts +86 -26
  55. package/src/verify/reference.ts +60 -7
  56. package/src/verify/runner.ts +14 -6
  57. package/src/verify/tree.ts +34 -10
  58. package/src/verify/types.ts +44 -0
  59. package/src/verify/wiring.ts +134 -22
@@ -16,20 +16,28 @@ import { gitPointers } from "../router/git-tools";
16
16
  import { expandTask, loadExpansionEnv, type ExpandedTask } from "./expand";
17
17
  import {
18
18
  deleteSlotRef,
19
+ gitCommitFailure,
20
+ gitStderrTail,
19
21
  listSlotRefs,
20
22
  orphanRefName,
21
23
  phaseTagName,
22
24
  planRefPrefix,
23
25
  restoreSlotWork,
26
+ STALE_INDEX_LOCK_PATTERN,
27
+ sanitizeGitDiagnostic,
24
28
  snapshotSlotWork,
29
+ slotCommitIdentityArgs,
25
30
  taskBranchName,
26
31
  wipRefName,
27
32
  wipTrailer,
28
33
  type WipRestore,
34
+ type ResolveCommitIdentity,
29
35
  } from "./git";
30
36
  import { dependentPhases } from "./integrate/queue";
31
37
  import type { PlanRoleBindings } from "./launch";
32
38
  import type { ProcessIdentity } from "./process-identity";
39
+ import type { ProcessJournal } from "../verify/types";
40
+ import type { AliveVerifyTree, VerifyTrees, VerifyTreeSweep } from "./verify-trees";
33
41
  import { createQaLoop } from "./qa-loop";
34
42
  import {
35
43
  RECOVER_TAKEOVER_REASON,
@@ -63,6 +71,7 @@ import {
63
71
  type CapacityView,
64
72
  type ChildEnd,
65
73
  type Clock,
74
+ type ContextRef,
66
75
  type Edge,
67
76
  type ExecutorConfig,
68
77
  type ExecutorEvent,
@@ -323,10 +332,17 @@ function errorCode(e: unknown): string | null {
323
332
  return null;
324
333
  }
325
334
 
326
- const IDENTITY_PATTERN = /please tell me who you are|unable to auto-detect|empty ident|author identity unknown/i;
335
+ /** Git errors keep stderr in details; carry a safe summary through logs, contexts and blocking items. */
336
+ function gitDiagnostic(e: unknown): { message: string; gitExitCode: string; stderr: string } {
337
+ const detail = e instanceof ExecutorError && typeof e.detail === "object" && e.detail !== null && !Array.isArray(e.detail) ? e.detail : {};
338
+ const gitExitCode = typeof detail.code === "number" ? String(detail.code) : "unknown";
339
+ const stderr = gitStderrTail(typeof detail.stderr === "string" ? detail.stderr : "");
340
+ const message = sanitizeGitDiagnostic(errorText(e)).slice(0, 1200);
341
+ return { message: `${message}${gitExitCode === "unknown" || message.includes("exit ") ? "" : ` (git exit ${gitExitCode})`}${stderr === "" || message.includes(stderr) ? "" : `; stderr: ${stderr}`}`, gitExitCode, stderr };
342
+ }
327
343
 
328
- /** A git step that failed on a leftover `index.lock` (a git killed mid-commit, D11). */
329
- const INDEX_LOCK_PATTERN = /index\.lock/i;
344
+ /** A git step that failed on a leftover `index.lock` (a git killed mid-commit, D11); #189 L7: git's own wording only. */
345
+ const INDEX_LOCK_PATTERN = STALE_INDEX_LOCK_PATTERN;
330
346
 
331
347
  /** D11: the trailer line of attempt `n` (nonce `nonce`) of `taskId`. */
332
348
  export function attemptTrailer(planId: PlanId, taskId: TaskId, n: number, nonce: string): string {
@@ -360,7 +376,7 @@ async function removeIndexLock(git: GitRunner, o: { cwd: string; timeoutMs: numb
360
376
  */
361
377
  export async function commitTaskInSlot(
362
378
  git: GitRunner,
363
- i: { slot: SlotLease; branch: string; message: string; timeoutMs: number; trailer?: string },
379
+ i: { slot: SlotLease; branch: string; message: string; timeoutMs: number; trailer?: string; identity?: ResolveCommitIdentity },
364
380
  ): Promise<{ changed: false } | { changed: true; commit: string }> {
365
381
  const o = { cwd: i.slot.path, timeoutMs: i.timeoutMs };
366
382
  let lockRemoved = false;
@@ -371,12 +387,7 @@ export async function commitTaskInSlot(
371
387
  if (await removeIndexLock(git, o)) r = await git.run(args, o);
372
388
  }
373
389
  if (r.code !== 0) {
374
- const text = `${r.stderr}\n${r.stdout}`;
375
- throw new ExecutorError(IDENTITY_PATTERN.test(text) ? "E_IDENTITY" : "E_GIT", `git ${args[0] ?? ""} failed`, {
376
- args: [...args],
377
- code: r.code,
378
- stderr: r.stderr.slice(0, 2000),
379
- });
390
+ throw gitCommitFailure(args.includes("commit") ? "commit" : args[0] ?? "", r);
380
391
  }
381
392
  return r.stdout;
382
393
  };
@@ -393,11 +404,52 @@ export async function commitTaskInSlot(
393
404
  }
394
405
  await step(["switch", "-C", i.branch]);
395
406
  await step(["add", "-A"]);
396
- await step(["commit", "-m", i.message, ...(i.trailer === undefined ? [] : ["-m", i.trailer])]);
407
+ const identity = await slotCommitIdentityArgs(git, o, i.identity);
408
+ await step([...identity, "commit", "--no-verify", "--no-gpg-sign", "-m", i.message, ...(i.trailer === undefined ? [] : ["-m", i.trailer])]);
397
409
  const head = (await step(["rev-parse", "HEAD"])).trim();
398
410
  return { changed: true, commit: head };
399
411
  }
400
412
 
413
+ /**
414
+ * QA-5.1-28 (#187): the notes of a gc report (`<path>: <why>`) about an entry of the plan's slots directory that the gc did
415
+ * not remove (EBUSY, a lock mismatch, an unmarked folder, ...). `slotsDir` null (unresolvable): every note that is not
416
+ * about a removed slot counts (fail closed).
417
+ */
418
+ function slotsLeftBehind(slotsDir: string | null, report: { removed: readonly string[]; reported: readonly string[] }): string[] {
419
+ const win = process.platform === "win32";
420
+ const norm = (s: string): string => (win ? s.replace(/\//g, "\\").toLowerCase() : s);
421
+ const gone = report.removed.map((path) => `${norm(path)}: `);
422
+ const dir = slotsDir === null ? null : `${norm(slotsDir).replace(/[\\/]+$/, "")}${win ? "\\" : "/"}`;
423
+ return report.reported.filter((note) => {
424
+ const n = norm(note);
425
+ return !gone.some((prefix) => n.startsWith(prefix)) && (dir === null || n.startsWith(dir));
426
+ });
427
+ }
428
+
429
+ /**
430
+ * QA-5.1-28 (#187): what the user does about the slots `slotsLeftBehind` found, by kind of note. A held file: close what
431
+ * holds it and purge again (the gc finishes a removal it began). A folder git does not list as locked by the executor, or
432
+ * an entry without a slot marker: the executor never deletes it; git's own commands remove it with its worktree entry
433
+ * (deleting only the folder leaves an entry the next gc refuses to drop).
434
+ */
435
+ function purgeWayOut(left: readonly string[]): string {
436
+ const steps: string[] = [];
437
+ if (left.some((note) => /\b(EBUSY|EPERM|EACCES|ENOTEMPTY)\b|still present after removal/.test(note))) {
438
+ steps.push("A slot whose files are in use: close the program that holds them, then purge again (the gc finishes a removal it began)");
439
+ }
440
+ const byHand = "check it for work you want to keep; if `git worktree list` shows it, run `git worktree unlock <path>` (when it is "
441
+ + "locked) and `git worktree remove --force <path>` (deleting only the folder would leave git's worktree entry, which the next gc "
442
+ + "refuses to drop); otherwise delete it; then purge again";
443
+ if (left.some((note) => note.includes("git does not list the folder as a worktree locked by the executor"))) {
444
+ steps.push(`A folder git does not list as locked by the executor is never deleted by it: ${byHand}`);
445
+ }
446
+ if (left.some((note) => note.endsWith(": unmarked"))) {
447
+ steps.push(`An unmarked entry (a folder or a file without a slot marker) is never deleted by the executor: ${byHand}`);
448
+ }
449
+ if (steps.length === 0) steps.push("Fix those slots, then purge again");
450
+ return `${steps.join(". ")}.`;
451
+ }
452
+
401
453
  // ---- runtime
402
454
 
403
455
  export interface PlanCollaborators {
@@ -414,6 +466,11 @@ export interface PlanTaskContext {
414
466
  orchestratorSessionID: string;
415
467
  /** An attachment change cuts old work without disposing the process-wide verifier. */
416
468
  signal?: AbortSignal;
469
+ /**
470
+ * #189 R2-pre-2 (`verify` only, with `RuntimeDeps.verifyTrees`): the attempt's process journal; the verifier's check
471
+ * seams record every root they spawn in it, so a restart can end what a dead server left running.
472
+ */
473
+ processJournal?: ProcessJournal;
417
474
  }
418
475
 
419
476
  /**
@@ -449,6 +506,13 @@ export interface RuntimeDeps {
449
506
  store: LedgerStore;
450
507
  /** Executor storage root; metadata-less slot directories are preserved here, outside the pool. */
451
508
  executorHome?: string;
509
+ /**
510
+ * #189 R2-pre-2 (v2 assembly): the process journal of plan-task verifications. Each `verify` gets the attempt's journal
511
+ * (`PlanTaskContext.processJournal`), and every activation sweeps the plan's journals of dead servers before recovered
512
+ * work runs; a kill that cannot be confirmed parks the slot's recovered work (`verify-tree-alive`) with one blocking item
513
+ * per slot until a resume sweeps again. Absent: nothing is journaled or swept.
514
+ */
515
+ verifyTrees?: VerifyTrees;
452
516
  compiler: PlanCompiler;
453
517
  slots: SlotPool;
454
518
  /** Per-plan pools; legacy callers keep using `slots`. */
@@ -458,6 +522,8 @@ export interface RuntimeDeps {
458
522
  * directory and removes the plan's empty slots directory). Without it, purge runs `slotsFor(planId).gc`.
459
523
  */
460
524
  purgeSlots?(planId: PlanId, finished: Parameters<SlotPool["gc"]>[0]): ReturnType<SlotPool["gc"]>;
525
+ /** Drop a closed pool entry only after a new plan with this id has been created. */
526
+ forgetSlots?(planId: PlanId): void;
461
527
  /** Revalidate the fixed slots directory before approval has any side effects. */
462
528
  /** Approve-time validation of the resolved slots root; `planId` names the plan being approved (its ledger, its base). */
463
529
  checkSlotsDir?(slotsDir: string, toplevel: string, planId: PlanId): void | Promise<void>;
@@ -466,6 +532,8 @@ export interface RuntimeDeps {
466
532
  routes: RouteResolver;
467
533
  verifier: PlanTaskVerifier;
468
534
  git: GitRunner;
535
+ /** User-mode config read, validated and cached by readCommitIdentity; never enables global config for writes. */
536
+ commitIdentity?: ResolveCommitIdentity;
469
537
  hosts: HostSessions;
470
538
  clock: Clock;
471
539
  leaseRegistry: LeaseRegistryPort;
@@ -646,8 +714,11 @@ interface RecoveredWork {
646
714
  readonly n: number;
647
715
  readonly nonce: string;
648
716
  readonly state: TaskState;
649
- readonly work: { kind: "reverify"; slotValid: boolean | null } | { kind: "end"; end: ChildEnd };
717
+ /** `vanished` (#189): the slot was lost mid-run (`slotVanished`), not found invalid at a restart. */
718
+ readonly work: { kind: "reverify"; slotValid: boolean | null; vanished?: boolean } | { kind: "end"; end: ChildEnd };
650
719
  started: boolean;
720
+ /** #194: why this work was last counted as parked (`recovered-work-parked`); null until parked, reset on admission. */
721
+ parked: string | null;
651
722
  }
652
723
 
653
724
  interface PlanRt {
@@ -689,10 +760,12 @@ interface PlanRt {
689
760
  /** Consecutive pre-confirmation losses (row 11, QA-3.1-4); reset on a confirmed launch and on resume. */
690
761
  preConfirmLosses: number;
691
762
  /**
692
- * Capture (router call) of the last counted pre-confirmation loss and the tasks lost under it (QA-3.1-17): parallel
693
- * launches lost under one capture count once; a task relaunched and lost again under the same capture counts again.
763
+ * Every capture (boot id, epoch, router call) of the current pre-confirmation streak and the tasks lost under it
764
+ * (QA-3.1-17, #194): parallel launches lost under one capture count once, also when losses of captures interleave
765
+ * (C1, C2, C1); a task relaunched and lost again under the same capture counts again. Each new capture is a counted
766
+ * loss and the streak clears it at PRECONFIRM_STREAK, so between clears it holds at most PRECONFIRM_STREAK - 1 captures.
694
767
  */
695
- preConfirmCapture: { key: string; tasks: Set<TaskId> } | null;
768
+ preConfirmCaptures: Map<string, Set<TaskId>>;
696
769
  /** Consecutive RouteResolver failures (QA-3.1-22); one inbox item at ROUTE_STREAK, reset by a tick that resolved cleanly. */
697
770
  routeFails: number;
698
771
  routeRaised: boolean;
@@ -705,11 +778,25 @@ interface PlanRt {
705
778
  recovering: boolean;
706
779
  /** Attachment-local identities; waiting for context retains the task's slot and leases. */
707
780
  recoveredWork: Map<TaskId, RecoveredWork>;
708
- /** Work that must observe an attachment cut before its writer closes (including already-decided verdicts). */
709
- attachmentWork: Set<Promise<void>>;
781
+ /**
782
+ * Work that must observe an attachment cut before its writer closes (including already-decided verdicts), with the label
783
+ * `closePlan`'s watchdog names it by (Recovery-R1-m1, #190).
784
+ */
785
+ attachmentWork: Map<Promise<void>, string>;
710
786
  attachment: AbortController;
711
787
  /** §9: `queue.resume()` ran in this activation and did not halt; a user `resume` retries while false. */
712
788
  integrationResumed: boolean;
789
+ /**
790
+ * #189: this activation's `reconcile` threw, so the plan was paused before any recovery step ran (never run with no
791
+ * feeds); the user's `resume` runs the activation, and so the recovery, again.
792
+ */
793
+ unreconciled: boolean;
794
+ /**
795
+ * #189 R2-pre-2: the slots (by name; VERIFY_TREES_ANY when the journal could not be read) whose dead server's
796
+ * verification trees the last sweep could not prove gone. Their recovered work stays parked (`verify-tree-alive`)
797
+ * until a resume (or the next activation) sweeps again.
798
+ */
799
+ treesAlive: Map<string, AliveVerifyTree>;
713
800
  /** R1a: children adopted on probation, keyed by child session id. */
714
801
  probation: Map<string, ProbationWatch>;
715
802
  /** R1a: the poll timer of the probation watch (one per plan), null when no child is on probation. */
@@ -764,8 +851,23 @@ const ATTEMPT_TRAILER = "Omr-Attempt";
764
851
  export const RESUME_PROMPT = "continue and finish";
765
852
  /** QA-4.2-16: states a failed lease rebuild holds (no commit, verify or enqueue until the leases are back). */
766
853
  const LEASE_HELD_STATES: readonly TaskState[] = ["running", "completed", "verifying", "verified"];
854
+ /** #189 R2-pre-2: the park reason (`recovered-work-parked`) of recovered work whose slot may still run a dead server's checks. */
855
+ export const VERIFY_TREE_ALIVE = "verify-tree-alive";
856
+ /**
857
+ * #189 R2-pre-2: the `treesAlive` key when the plan's journal could not be read (every recovered work waits); followed by
858
+ * a task id, the key of one attempt's journal whose slot is not known.
859
+ */
860
+ const VERIFY_TREES_ANY = "*";
861
+ /** L6: the answer journaled on a verification-tree item once a sweep confirmed its slot clear. */
862
+ export const VERIFY_TREE_RESOLVED = "resolved: the sweep found nothing of the dead server left running";
767
863
  /** QA-4.2-3: how long closing a plan waits for its integration queue to dispose (a hung queue never blocks a close). */
768
864
  const QUEUE_DISPOSE_MS = 10_000;
865
+ /**
866
+ * Recovery-R1-m1 (#190): after how long `closePlan`'s (unbounded) wait for the cut attachment's pipelines warns once. Equal to
867
+ * PLAN_TASK_ABORT_MS (verify/plan-task.ts), the bound of a cut gate's drain: a verification whose gate needed that whole bound
868
+ * (plus its own cleanup) can still be named by the warning; anything else named has outlived the drain bound.
869
+ */
870
+ export const CLOSE_WAIT_WARN_MS = 5_000;
769
871
  /** QA-5.1-7: the first re-check of a finished plan that is not quiescent yet; it doubles up to COLLECT_RETRY_MAX_MS. */
770
872
  export const COLLECT_RETRY_BASE_MS = 100;
771
873
  /** QA-5.1-7: the cap of the finished-plan collection backoff. */
@@ -778,6 +880,32 @@ export function nextCollectDelay(delay: number): number {
778
880
  return Math.min(Math.max(delay, COLLECT_RETRY_BASE_MS) * 2, COLLECT_RETRY_MAX_MS);
779
881
  }
780
882
 
883
+ /** #202: the slots directories a purged plan's pool trusts: the configured one and the drive default (when there is one). */
884
+ function purgeSlotsDirs(configured: string | null, toplevel: string, planId: PlanId): string[] {
885
+ const dirs = configured === null ? [] : [configured];
886
+ try {
887
+ dirs.push(defaultSlotsDir(toplevel, planId));
888
+ } catch {
889
+ // no drive-letter default for this repository: only the configured directory applies
890
+ }
891
+ return dirs;
892
+ }
893
+
894
+ /** `/` separators, runs collapsed, case folded: a looser match only makes more notes this plan's (refusing stays the default). */
895
+ function slotNoteKey(s: string): string {
896
+ return s.replace(/[\\/]+/g, "/").toLowerCase();
897
+ }
898
+
899
+ /**
900
+ * #202: whether a gc note (`<slot path>: …`) names a slot outside every directory of `dirs`. A note that does not start
901
+ * with an absolute path is never foreign; with no known directory, no note is.
902
+ */
903
+ function foreignSlotNote(note: string, dirs: readonly string[]): boolean {
904
+ if (dirs.length === 0 || !/^(?:[A-Za-z]:)?[\\/]/.test(note)) return false;
905
+ const key = slotNoteKey(note);
906
+ return !dirs.some((dir) => key.startsWith(`${slotNoteKey(dir).replace(/\/$/, "")}/`));
907
+ }
908
+
781
909
  /**
782
910
  * QA-5.1-7: whether a finished plan's phase tags are settled. An aborted plan tags nothing: settled. A completed plan's passed
783
911
  * phase is settled once tagged, or once the queue settled its tag without one: the tag name exists at another commit
@@ -802,6 +930,101 @@ export function planTagsSettled(l: Readonly<LedgerV1>): boolean {
802
930
  /** QA-4.2-13: context of a `completed` task whose slot was lost before its commit (R2 re-provision failed). */
803
931
  const SLOT_LOST_BEFORE_COMMIT = "slot lost before commit";
804
932
 
933
+ /**
934
+ * QA-4.2-13/-32: where attempt `n`'s commit (its trailer) is: in the history of the task branch at `tip`, nowhere, or
935
+ * unknown (git cannot tell, or `elsewhere`: a commit only another ref reaches).
936
+ */
937
+ type AttemptCommit = { kind: "on-branch"; tip: string } | { kind: "none" } | { kind: "unknown"; elsewhere: string | null };
938
+
939
+ /** #189 (QA-4.2-31): why R2 could not re-provision a slot; the blocking item names it. */
940
+ type ReprovisionFailure =
941
+ | "no branch"
942
+ | "branch unreadable"
943
+ | "release failed"
944
+ | "slot unavailable"
945
+ | "save failed"
946
+ | "reset failed"
947
+ | "checkout failed"
948
+ | "lease cap"
949
+ | "lease invalid"
950
+ | "lease error"
951
+ | "journal failed"
952
+ | "task moved"
953
+ /** Recovery-R1-m1 (#190): the attachment was cut after the slot was acquired; the caller raises no item for it. */
954
+ | "attachment cut";
955
+
956
+ /**
957
+ * #189 (QA-4.2-31): the outcome of R2's re-provisioning. `held`: the new slot is journaled and kept, but its leases are
958
+ * held elsewhere, so the task is held (`leaseHeld`) on it until they are back.
959
+ */
960
+ type Reprovision =
961
+ | { kind: "ok" }
962
+ | { kind: "held"; holders: LeaseHolderInfo[] }
963
+ | { kind: "failed"; reason: ReprovisionFailure; detail: string };
964
+
965
+ /** QA-4.2-26: how every lease-hold item of `taskId` starts (#189 dedupes on it). */
966
+ function leaseHoldPrefix(taskId: TaskId): string {
967
+ return `could not re-take the leases of ${taskId} `;
968
+ }
969
+
970
+ /**
971
+ * QA-4.2-26: the item of a task held because another holder has its leases: it says the task is held and what ends the
972
+ * hold. `where`: "after restart" (the lease rebuild) or the re-provisioned slot (#189, QA-4.2-31).
973
+ */
974
+ function leaseHoldText(taskId: TaskId, holders: readonly LeaseHolderInfo[], where: string): string {
975
+ return (
976
+ `${leaseHoldPrefix(taskId)}${where}; held by ${holders.map((h) => h.holderID).join(", ")}. ` +
977
+ `${taskId} is held (no adopt, commit, verify or enqueue) until its leases are free: finish or abort the holder ` +
978
+ `(or abort ${taskId}); it resumes on its own once the leases are released`
979
+ );
980
+ }
981
+
982
+ /** Why R2 raises the slot-lost item: the trailer search's `unknown` (QA-4.2-32) or a failed re-provisioning. */
983
+ type SlotLostWhy = { elsewhere: string | null } | { reason: ReprovisionFailure; detail: string };
984
+
985
+ /**
986
+ * #189 (QA-4.2-31): the end of the slot-lost item, after "could not be re-provisioned from <branch>". Only a task branch
987
+ * that does not exist (or does not reach this attempt's commit) asks for the branch to be restored; every other failure
988
+ * is named, with its detail.
989
+ */
990
+ function slotLostCause(why: SlotLostWhy): string {
991
+ const retry = "fix the cause and restart to re-provision it, or abort the task";
992
+ if ("elsewhere" in why) {
993
+ if (why.elsewhere === null) return `: git could not tell whether this attempt's commit exists; ${retry}`;
994
+ return `; this attempt's commit ${why.elsewhere} is reachable only from another ref, not from the task branch; restore the task branch or abort the task`;
995
+ }
996
+ const said = why.detail.replace(/\s+/g, " ").trim().slice(0, 300);
997
+ const detail = said === "" ? "" : ` (${said})`;
998
+ switch (why.reason) {
999
+ case "no branch":
1000
+ return ": the task branch does not exist; restore the task branch or abort the task";
1001
+ case "branch unreadable":
1002
+ return `: the task branch could not be read${detail}; ${retry}`;
1003
+ case "release failed":
1004
+ return `: its old slot could not be given back to the pool first${detail}; ${retry}`;
1005
+ case "slot unavailable":
1006
+ return `: no slot could be acquired${detail}; ${retry}`;
1007
+ case "save failed":
1008
+ return `: the work in the new slot could not be saved before its reset (its own item names that slot); ${retry}`;
1009
+ case "reset failed":
1010
+ return `: resetting the new slot to the branch tip failed${detail}; ${retry}`;
1011
+ case "checkout failed":
1012
+ return `: checking out the branch tip in the new slot failed${detail}; ${retry}`;
1013
+ case "lease cap":
1014
+ return `: the lease registry is at capacity${detail}; ${retry}`;
1015
+ case "lease invalid":
1016
+ return `: the lease registry refused its leases as invalid${detail}; ${retry}`;
1017
+ case "lease error":
1018
+ return `: taking its leases on the new slot failed${detail}; ${retry}`;
1019
+ case "journal failed":
1020
+ return `: journaling the new slot failed${detail}; ${retry}`;
1021
+ case "task moved":
1022
+ return ": the task moved on while it was re-provisioned; check its state, or abort the task";
1023
+ case "attachment cut":
1024
+ return `: its attachment was cut while it was re-provisioned; ${retry}`;
1025
+ }
1026
+ }
1027
+
805
1028
  /**
806
1029
  * Wake reason of the refused plan's one wake (QA-3.1-19). `WakeReason` (types.ts, owned elsewhere) has no `plan-refused`
807
1030
  * member yet; the wake goes out as an inbox wake under the state key `plan-refused:<planId>:<active>` until it does.
@@ -884,6 +1107,11 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
884
1107
  /** Fallback step counter per session (QA-3.1-8: `e.stepKey` wins); bounded, and dropped when the session ends. */
885
1108
  const stepState = new Map<string, { k: number; open: boolean }>();
886
1109
  let disposed = false;
1110
+ /**
1111
+ * #190: every `start()` in flight (each never rejects; removed once settled; create.ts memoises `start`, but a direct
1112
+ * caller may start twice). `dispose` waits for them, bounded by QUEUE_DISPOSE_MS, before closing the plans.
1113
+ */
1114
+ const startRuns = new Set<Promise<void>>();
887
1115
  const collected = new Set<PlanId>();
888
1116
  const forgotten = new Set<string>();
889
1117
  /** The child's final text of a completed attempt (row 15), by `<plan>/<task>#<n>`, for the plan-task verifier's `observe`. */
@@ -935,8 +1163,17 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
935
1163
  );
936
1164
  }
937
1165
 
938
- function holdAttachment(p: PlanRt, work: Promise<void>): Promise<void> {
939
- p.attachmentWork.add(work);
1166
+ /**
1167
+ * Recovery-R1-m1 (#190): the attachment's work was cut: `closePlan` (adopt, dispose) or a user `abort`, which aborts the
1168
+ * attachment without disposing the plan. A pipeline stops at its next checkpoint without an item or a journal row.
1169
+ */
1170
+ function attachmentCut(p: PlanRt): boolean {
1171
+ return p.disposed || p.attachment.signal.aborted;
1172
+ }
1173
+
1174
+ /** `label` names the work in `closePlan`'s slow-close warning (Recovery-R1-m1, #190). */
1175
+ function holdAttachment(p: PlanRt, label: string, work: Promise<void>): Promise<void> {
1176
+ p.attachmentWork.set(work, label);
940
1177
  const done = (): void => { p.attachmentWork.delete(work); };
941
1178
  void work.then(done, done);
942
1179
  return work;
@@ -995,6 +1232,18 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
995
1232
  return { orchestratorSessionID: p.writer.ledger.orchestrator.sessionID, signal: p.attachment.signal };
996
1233
  }
997
1234
 
1235
+ /** #189 R2-pre-2: `verify`'s context also carries the attempt's process journal (with `verifyTrees`). */
1236
+ function verifyContext(p: PlanRt, taskId: TaskId, n: number, lease: SlotLease): PlanTaskContext {
1237
+ const ctx = planTaskContext(p);
1238
+ if (d.verifyTrees === undefined) return ctx;
1239
+ try {
1240
+ return { ...ctx, processJournal: d.verifyTrees.journal(p.planId, taskId, n, { name: lease.slot, path: lease.path }) };
1241
+ } catch (e) {
1242
+ d.log("warn", `the verification of ${taskId}#${n} is not journaled`, errorText(e));
1243
+ return ctx;
1244
+ }
1245
+ }
1246
+
998
1247
  /**
999
1248
  * QA-PDF21-15: the abort's releases still running, by plan: a cancelled child's settled launch is followed by its slot's save,
1000
1249
  * then its reset and release, or its hold when the save fails. Until that ends the slot is neither collectable nor known held.
@@ -1138,7 +1387,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1138
1387
  * left its held states (or its slot) leaves the hold without one.
1139
1388
  */
1140
1389
  async function retryHeldLeases(p: PlanRt): Promise<void> {
1141
- if (p.leaseHeld.size === 0 || p.disposed || p.passive) return;
1390
+ if (p.leaseHeld.size === 0 || p.disposed || p.passive || p.unreconciled) return;
1142
1391
  const l = p.writer.ledger;
1143
1392
  const tasks: Array<{ id: TaskId; slot: string | null; tree: string | null; footprint: Footprint }> = [];
1144
1393
  for (const id of [...p.leaseHeld].sort()) {
@@ -1148,17 +1397,19 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1148
1397
  continue;
1149
1398
  }
1150
1399
  // QA-4.2-26: the pool's record itself, never the cached lease (`slotLeaseOf` caches it on the first retry, which
1151
- // would hide a record that vanished since). A lookup error is retried next tick.
1400
+ // would hide a record that vanished since). A lookup error is retried next tick. #189: a record no longer leased to
1401
+ // this task (back in the pool, or another task's) counts as vanished: its leases are never rebuilt on that tree.
1152
1402
  let tree: string | null;
1153
1403
  try {
1154
- tree = (await slotsFor(p.planId).get(t.slot))?.path ?? null;
1404
+ const rec = await slotsFor(p.planId).get(t.slot);
1405
+ tree = rec !== null && rec.owner === leaseHolderID(p.planId, id) && rec.state === "leased" ? rec.path : null;
1155
1406
  } catch (e) {
1156
1407
  d.log("warn", `slot lookup of held ${id} failed; retried next tick`, errorText(e));
1157
1408
  continue;
1158
1409
  }
1159
1410
  if (tree === null) {
1160
- // A vanished slot record never comes back, so no retry could succeed: the task leaves the hold at once and goes
1161
- // through R2 (re-provisioning from its branch).
1411
+ // A vanished slot record never comes back (nor does a slot that is not ours), so no retry could succeed: the task
1412
+ // leaves the hold at once and goes through R2 (re-provisioning from its branch).
1162
1413
  p.leaseHeld.delete(id);
1163
1414
  counter(p, "lease-held-slot-lost", { taskId: id });
1164
1415
  slotVanished(p, id);
@@ -1184,15 +1435,18 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1184
1435
  }
1185
1436
 
1186
1437
  /**
1187
- * QA-4.2-26: R2 for a held task whose slot record vanished: `completed`/`verifying` re-verify with an invalid slot
1188
- * (QA-4.2-13/-20 included), `verified` is re-provisioned from its branch and re-enqueued; a `running` task needs
1189
- * nothing here (its end is processed as usual and a commit without a slot fails, counted).
1438
+ * QA-4.2-26: R2 for a held task whose slot record vanished (#189: or is no longer leased to it): `completed`/
1439
+ * `verifying` re-verify with an invalid slot (QA-4.2-13/-20 included), `verified` is re-provisioned from its branch and
1440
+ * re-enqueued; a `running` task needs nothing here (its end is processed as usual and a commit without a slot fails,
1441
+ * counted). #189 (QA-4.2-31): leases still held elsewhere keep the task held on its re-provisioned slot;
1442
+ * `resumeHeldTask` resumes it once they are back.
1190
1443
  */
1191
1444
  function slotVanished(p: PlanRt, taskId: TaskId): void {
1192
1445
  p.slotLeases.delete(taskId);
1193
1446
  const waiting = p.recoveredWork.get(taskId);
1194
1447
  if (waiting?.work.kind === "reverify" && !waiting.started) {
1195
1448
  waiting.work.slotValid = false;
1449
+ waiting.work.vanished = true;
1196
1450
  schedule(p);
1197
1451
  return;
1198
1452
  }
@@ -1200,8 +1454,8 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1200
1454
  withTask(p, taskId, async () => {
1201
1455
  const t = own(p.writer.ledger, taskId);
1202
1456
  if (t === null || p.disposed) return;
1203
- if (t.state === "completed" || t.state === "verifying") await reverify(p, taskId, false);
1204
- else if (t.state === "verified" && (await reprovisionOrRaise(p, t)) && !p.latch) p.collab.queue.enqueue([taskId]);
1457
+ if (t.state === "completed" || t.state === "verifying") await reverify(p, taskId, false, true);
1458
+ else if (t.state === "verified" && (await reprovisionOrRaise(p, t, true)) && !p.latch) p.collab.queue.enqueue([taskId]);
1205
1459
  }),
1206
1460
  );
1207
1461
  }
@@ -1249,10 +1503,20 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1249
1503
  function registerRecoveredWork(p: PlanRt, t: TaskNode, work: RecoveredWork["work"]): void {
1250
1504
  const a = t.attempts[t.attempts.length - 1];
1251
1505
  if (a === undefined || p.disposed || disposed || p.recoveredWork.has(t.id)) return;
1252
- p.recoveredWork.set(t.id, { taskId: t.id, n: a.n, nonce: a.nonce, state: t.state, work, started: false });
1506
+ p.recoveredWork.set(t.id, { taskId: t.id, n: a.n, nonce: a.nonce, state: t.state, work, started: false, parked: null });
1253
1507
  schedule(p);
1254
1508
  }
1255
1509
 
1510
+ /**
1511
+ * #194 (Recovery-R1-m7): recovered work that cannot be admitted yet (no root context, or its leases are held) is
1512
+ * counted once per park and reason (`recovered-work-parked`), so a parked task is visible in the ledger's metrics.
1513
+ */
1514
+ function noteParked(p: PlanRt, w: RecoveredWork, reason: string): void {
1515
+ if (w.parked === reason) return;
1516
+ w.parked = reason;
1517
+ counter(p, "recovered-work-parked", { taskId: w.taskId, n: String(w.n), work: w.work.kind, reason });
1518
+ }
1519
+
1256
1520
  /**
1257
1521
  * minor-1: clears the plan's recovered work (abort, close). Since 4070b22 the launcher keeps a `completed` child's
1258
1522
  * binding until the end is processed, so a dropped recovered end releases that binding here
@@ -1267,21 +1531,67 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1267
1531
  p.recoveredWork.clear();
1268
1532
  }
1269
1533
 
1534
+ /**
1535
+ * R2 must still try to recover an invalid slot even when the old tree's lease rebuild failed. Re-provisioning
1536
+ * performs its own lease acquisition: leases still held elsewhere keep the new slot and hold the task on it (#189,
1537
+ * QA-4.2-31), any other failure undoes it. Only commit/check/verify remains held until leases are back: a
1538
+ * re-verify of a valid slot and a completed child's end (commit then verify). An end that needs no verification
1539
+ * (a failed, lost, capacity-stopped or interrupted child) is recorded at once and releases its token.
1540
+ */
1541
+ function recoveredWorkHeld(p: PlanRt, w: RecoveredWork): boolean {
1542
+ return p.leaseHeld.has(w.taskId) && (w.work.kind === "reverify" ? w.work.slotValid !== false : w.work.end.kind === "completed");
1543
+ }
1544
+
1545
+ /**
1546
+ * #189 R2-pre-2: the task's slot (or the task itself) may still run a dead server's verification trees: its recovered work
1547
+ * (any kind: a re-verify, a commit-and-verify, an end whose retry would reuse the slot) waits for a sweep to prove them gone.
1548
+ */
1549
+ function verifyTreeAlive(p: PlanRt, w: RecoveredWork): boolean {
1550
+ if (p.treesAlive.size === 0) return false;
1551
+ if (p.treesAlive.has(VERIFY_TREES_ANY)) return true;
1552
+ const slot = own(p.writer.ledger, w.taskId)?.slot ?? null;
1553
+ for (const [name, alive] of p.treesAlive) if (name === slot || alive.taskId === w.taskId) return true;
1554
+ return false;
1555
+ }
1556
+
1557
+ /** Why unadmitted recovered work waits besides the root's context: its leases, a live tree of a dead server, or nothing. */
1558
+ function recoveredWorkParkReason(p: PlanRt, w: RecoveredWork): string | null {
1559
+ if (recoveredWorkHeld(p, w)) return "lease-held";
1560
+ return verifyTreeAlive(p, w) ? VERIFY_TREE_ALIVE : null;
1561
+ }
1562
+
1563
+ /** Recovery-R1-n2 (#189): recovered work admission would start now; lease-held work requests no wake. */
1564
+ function recoveredWorkWaiting(p: PlanRt): boolean {
1565
+ return [...p.recoveredWork.values()].some((w) => !w.started && recoveredWorkParkReason(p, w) === null);
1566
+ }
1567
+
1270
1568
  /** The launcher's live context gate is also the admission gate for recovered verification (D14). */
1271
1569
  function admitRecoveredWork(p: PlanRt): void {
1272
1570
  if (p.recovering || p.disposed || disposed || p.passive) return;
1273
1571
  for (const w of p.recoveredWork.values()) {
1274
- // R2 must still try to recover an invalid slot even when the old tree's lease rebuild failed. Re-provisioning
1275
- // performs its own lease acquisition/undo; only commit/check/verify remains held until leases are back: a
1276
- // re-verify of a valid slot and a completed child's end (commit then verify). An end that needs no verification
1277
- // (a failed, lost, capacity-stopped or interrupted child) is recorded at once and releases its token.
1278
- const held = (): boolean => p.leaseHeld.has(w.taskId)
1279
- && (w.work.kind === "reverify" ? w.work.slotValid !== false : w.work.end.kind === "completed");
1280
- if (w.started || held()) continue;
1281
- if (!d.launcher.gate(p.writer.ledger.orchestrator.sessionID).ok) return;
1572
+ // Leases held elsewhere, or (#189 R2-pre-2) a dead server's verification tree that may still run in its slot.
1573
+ const held = (): string | null => recoveredWorkParkReason(p, w);
1574
+ // The gate's reason, or null when it is open.
1575
+ const closed = (): string | null => {
1576
+ const g = d.launcher.gate(p.writer.ledger.orchestrator.sessionID);
1577
+ return g.ok ? null : g.reason;
1578
+ };
1579
+ if (w.started) continue;
1580
+ const heldBy = held();
1581
+ if (heldBy !== null) {
1582
+ noteParked(p, w, heldBy);
1583
+ continue;
1584
+ }
1585
+ const gateClosed = closed();
1586
+ if (gateClosed !== null) {
1587
+ // Nothing is admitted without the root's context: every waiting work is parked (#194).
1588
+ for (const r of p.recoveredWork.values()) if (!r.started) noteParked(p, r, recoveredWorkParkReason(p, r) ?? gateClosed);
1589
+ return;
1590
+ }
1282
1591
  w.started = true; // synchronous reservation: repeated ticks/captures cannot queue a second pipeline
1283
- holdAttachment(p, bg("recovered task work", () => withTask(p, w.taskId, async () => {
1284
- let parked = false;
1592
+ w.parked = null;
1593
+ holdAttachment(p, `recovered ${w.work.kind} of ${w.taskId}#${w.n}`, bg("recovered task work", () => withTask(p, w.taskId, async () => {
1594
+ let parked: string | null = null;
1285
1595
  try {
1286
1596
  const t = own(p.writer.ledger, w.taskId);
1287
1597
  const a = t?.attempts[t.attempts.length - 1];
@@ -1290,18 +1600,27 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1290
1600
  // A re-verify of a task that moved on has nothing left to do.
1291
1601
  if (moved && w.work.kind === "reverify") return;
1292
1602
  // Context/leases may have changed while this task waited for its mutex. Never spend a grader rerun on admission.
1293
- if (held() || !d.launcher.gate(p.writer.ledger.orchestrator.sessionID).ok) {
1294
- parked = true;
1295
- return;
1603
+ parked = held() ?? closed();
1604
+ if (parked !== null) return;
1605
+ if (w.work.kind === "reverify") {
1606
+ // #189 (QA-4.2-31): re-provisioned, but held on the new slot: the work waits again as a re-verify of a valid
1607
+ // slot (parked `lease-held`, as `parkWithoutContext` re-parks). Re-registered here, not in `finally`: leases
1608
+ // released meanwhile resume it (`resumeHeldTask` finds it), and `finally` leaves the new entry alone.
1609
+ if ((await reverify(p, w.taskId, w.work.slotValid, w.work.vanished === true)) === "held" && p.recoveredWork.get(w.taskId) === w) {
1610
+ p.recoveredWork.delete(w.taskId);
1611
+ const cur = own(p.writer.ledger, w.taskId);
1612
+ if (cur !== null) registerRecoveredWork(p, cur, { kind: "reverify", slotValid: true });
1613
+ }
1296
1614
  }
1297
- if (w.work.kind === "reverify") await reverify(p, w.taskId, w.work.slotValid);
1298
1615
  // N3 / minor-1: an end whose task moved on (e.g. row 34 closed the attempt) still needs its bookkeeping:
1299
1616
  // `processEndNow` ignores a closed attempt and still releases its token and binding and forgets its session.
1300
1617
  else await processEndNow(p, w.taskId, w.n, w.work.end);
1301
1618
  } finally {
1302
1619
  if (p.recoveredWork.get(w.taskId) === w) {
1303
- if (parked) w.started = false;
1304
- else p.recoveredWork.delete(w.taskId);
1620
+ if (parked !== null) {
1621
+ w.started = false;
1622
+ noteParked(p, w, parked);
1623
+ } else p.recoveredWork.delete(w.taskId);
1305
1624
  }
1306
1625
  schedule(p);
1307
1626
  }
@@ -1460,6 +1779,15 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1460
1779
  }
1461
1780
  }
1462
1781
 
1782
+ /** The plan's slots directory as its pool resolves it (create.ts `makePool`); null when it cannot be resolved. */
1783
+ function planSlotsDirOf(p: PlanRt): string | null {
1784
+ try {
1785
+ return p.writer.ledger.config.slotsDir ?? defaultSlotsDir(p.writer.ledger.repo.toplevel, p.planId);
1786
+ } catch {
1787
+ return null;
1788
+ }
1789
+ }
1790
+
1463
1791
  /**
1464
1792
  * Only a missing slot directory is gone. Missing repository metadata is not evidence that its files are disposable.
1465
1793
  */
@@ -1473,13 +1801,18 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1473
1801
  }
1474
1802
  }
1475
1803
 
1476
- /** Whether the pool still leases `slotName` to `taskId` (a policy that already returned it leaves nothing to do). */
1477
- async function slotHeldBy(p: PlanRt, taskId: TaskId, slotName: string): Promise<boolean> {
1804
+ /**
1805
+ * Whether the pool still leases `slotName` to `taskId` (a policy that already returned it leaves nothing to do).
1806
+ * N-3 (#187): a lookup that throws answers `unknown`: false by default, so a release gate fails closed (the slot is
1807
+ * kept, never released on a guess); a caller for which "held" is the safe side passes true.
1808
+ */
1809
+ async function slotHeldBy(p: PlanRt, taskId: TaskId, slotName: string, unknown = false): Promise<boolean> {
1478
1810
  try {
1479
1811
  const rec = await slotsFor(p.planId).get(slotName);
1480
1812
  return rec !== null && rec.owner === leaseHolderID(p.planId, taskId) && rec.state === "leased";
1481
- } catch {
1482
- return true;
1813
+ } catch (e) {
1814
+ d.log("warn", `slot lookup of ${slotName} failed; ${unknown ? "treated as held" : "the slot is kept, not released"}`, errorText(e));
1815
+ return unknown;
1483
1816
  }
1484
1817
  }
1485
1818
 
@@ -1517,6 +1850,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1517
1850
  const wipRestored = new Map<string, number>();
1518
1851
  /** QA-PDF21-3: `<plan>/<slot>` of the slots whose failed save raised its blocking item already (cleared by a save). */
1519
1852
  const wipFailRaised = new Set<string>();
1853
+ const wipFailures = new Map<string, string>();
1520
1854
 
1521
1855
  /** The quarantine directory is durable even if the process dies between the rename and journaling its item. */
1522
1856
  function quarantinedSlots(p: PlanRt): string[] {
@@ -1584,14 +1918,19 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1584
1918
  timeoutMs: GIT_TIMEOUT_MS,
1585
1919
  ...(slot.base === undefined || slot.base === null ? {} : { base: slot.base }),
1586
1920
  fallbackRef: orphanRefName(p.planId, slot.slot, d.clock.now(), orphanTag()),
1587
- removeIndexLock: () => removeIndexLock(d.git, o),
1921
+ removeIndexLock: () => removeSlotIndexLock(p, slot.slot, o),
1922
+ ...(d.commitIdentity === undefined ? {} : { identity: d.commitIdentity }),
1588
1923
  });
1589
1924
  wipFailRaised.delete(`${p.planId}/${slot.slot}`);
1925
+ wipFailures.delete(`${p.planId}/${slot.slot}`);
1590
1926
  if (r.saved) counter(p, "wip-saved", taskId === null ? { slot: slot.slot, ref } : { taskId, slot: slot.slot, ref }, deferredMetrics);
1591
1927
  return r.saved || r.reason === "unchanged" ? "saved" : "clean";
1592
1928
  } catch (e) {
1593
- d.log("error", `saving the work in slot ${slot.slot} failed; the slot is kept as it is`, errorText(e));
1594
- counter(p, "wip-failed", taskId === null ? { slot: slot.slot } : { taskId, slot: slot.slot }, deferredMetrics);
1929
+ const diagnostic = gitDiagnostic(e);
1930
+ wipFailures.set(`${p.planId}/${slot.slot}`, diagnostic.message);
1931
+ d.log("error", `saving the work in slot ${slot.slot} failed; the slot is kept as it is`, diagnostic);
1932
+ counter(p, "wip-failed", { ...(taskId === null ? {} : { taskId }), slot: slot.slot,
1933
+ gitExitCode: diagnostic.gitExitCode, stderr: diagnostic.stderr }, deferredMetrics);
1595
1934
  return "failed";
1596
1935
  }
1597
1936
  }
@@ -1655,7 +1994,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1655
1994
  counter(p, "wip-foreign-slot", { taskId, slot: slotName }, deferredMetrics);
1656
1995
  return "clean";
1657
1996
  }
1658
- if (t === null || a === undefined || !(await slotHeldBy(p, taskId, slotName))) return snapshotOrphan(p, { slot: slotName, path: at.path }, deferredMetrics);
1997
+ if (t === null || a === undefined || !(await slotHeldBy(p, taskId, slotName, true))) return snapshotOrphan(p, { slot: slotName, path: at.path }, deferredMetrics);
1659
1998
  return snapshotWip(p, { slot: slotName, path: at.path, base: at.base }, taskId, a.n, a.nonce, outcome, deferredMetrics);
1660
1999
  }
1661
2000
 
@@ -1674,7 +2013,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1674
2013
  kind: "failure",
1675
2014
  severity: "blocking",
1676
2015
  taskId,
1677
- text: wipHoldText(slotName, what, taskId),
2016
+ text: wipHoldText(p, slotName, what, taskId),
1678
2017
  options: [],
1679
2018
  });
1680
2019
  return item.id;
@@ -1716,6 +2055,9 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1716
2055
  try { markers = await slotsFor(p.planId).list(); }
1717
2056
  catch (error) { throw new ExecutorError("E_PLAN_STATE", `plan ${p.planId}: unsaved slot markers could not be read (${errorText(error)})`, { planId: p.planId }); }
1718
2057
  for (const marker of markers) {
2058
+ // #187: a slot the gc began deleting after its unsaved-work check passed holds nothing to save (and what is left of
2059
+ // it, without its `.git` link, would be quarantined instead of collected).
2060
+ if (marker.removing === true) continue;
1719
2061
  if (marker.planId === p.planId && (terminal || marker.state === "leased")) wipFailRaised.add(`${p.planId}/${marker.slot}`);
1720
2062
  }
1721
2063
  }
@@ -1795,8 +2137,9 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1795
2137
  }
1796
2138
 
1797
2139
  /** The text of `wipHold`'s item; `answer` reads the slot back from it (`wipHoldSlotOf`, QA-PDF21-15). */
1798
- function wipHoldText(slotName: string, what: string, taskId: TaskId | null): string {
1799
- return `${WIP_HOLD_PREFIX}${slotName} could not be saved before ${what}; the slot keeps its work and stays leased${taskId === null ? "" : ` to ${taskId}`} (see the log). Fix the slot's git state, then answer`;
2140
+ function wipHoldText(p: PlanRt, slotName: string, what: string, taskId: TaskId | null): string {
2141
+ const diagnostic = wipFailures.get(`${p.planId}/${slotName}`);
2142
+ return `${WIP_HOLD_PREFIX}${slotName} could not be saved before ${what}; the slot keeps its work and stays leased${taskId === null ? "" : ` to ${taskId}`} (see the log).${diagnostic === undefined ? "" : ` ${diagnostic}`} Fix the slot's git state, then answer`;
1800
2143
  }
1801
2144
 
1802
2145
  /**
@@ -2037,8 +2380,9 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2037
2380
  function schedule(p: PlanRt): void {
2038
2381
  observe(p, "schedule");
2039
2382
  // A passively attached (refused) plan never ticks (QA-3.1-19); an activation under way neither (4.2.5: recovery and
2040
- // the integration resume come before the first tick, which `recoverPlan`/`activate` schedule themselves).
2041
- if (p.disposed || disposed || p.passive || p.recovering) return;
2383
+ // the integration resume come before the first tick, which `recoverPlan`/`activate` schedule themselves). #189: nor
2384
+ // a plan whose recovery could not classify it, until a resume recovers it (even if its pause could not be journaled).
2385
+ if (p.disposed || disposed || p.passive || p.recovering || p.unreconciled) return;
2042
2386
  if (p.ticking) {
2043
2387
  p.again = true;
2044
2388
  return;
@@ -2097,7 +2441,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2097
2441
  if (l.status !== "running") {
2098
2442
  closeIdle(p);
2099
2443
  // Recovery also re-verifies paused plans. Their pending work needs a root context even without launchable work.
2100
- if ([...p.recoveredWork.values()].some((w) => !w.started)) {
2444
+ if (recoveredWorkWaiting(p)) {
2101
2445
  const gate = d.launcher.gate(l.orchestrator.sessionID);
2102
2446
  if (!gate.ok && gate.wake !== null) await wakeOnce(p, gate.wake.reason, gate.wake.stateKey);
2103
2447
  }
@@ -2143,7 +2487,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2143
2487
  }
2144
2488
  observe(p, "launch-gate", () => ({ ok: gate.ok, ready: ready.map((r) => r.taskId) }));
2145
2489
  if (ready.length === 0 || !gate.ok) {
2146
- if ((ready.length > 0 || [...p.recoveredWork.values()].some((w) => !w.started)) && !gate.ok && gate.wake !== null) {
2490
+ if ((ready.length > 0 || recoveredWorkWaiting(p)) && !gate.ok && gate.wake !== null) {
2147
2491
  await wakeOnce(p, gate.wake.reason, gate.wake.stateKey);
2148
2492
  }
2149
2493
  updateIdle(p, ready, 0);
@@ -2460,7 +2804,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2460
2804
  counter(p, "launch-failed", { row: code === "E_LAUNCH_TASK" ? "L2" : code === "E_NO_CONTEXT" ? "L3" : "L4" });
2461
2805
  if (code === "E_LAUNCH_TASK") await rowLaunchFailed(p, taskId, n, errorText(e));
2462
2806
  else if (code === "E_DISPOSED") releaseToken(p, taskId, n, "other");
2463
- else await rowLost(p, taskId, n, code === "E_NO_CONTEXT" ? "no-context" : "launch-error");
2807
+ else await rowLost(p, taskId, n, code === "E_NO_CONTEXT" ? "no-context" : "launch-error", req.context);
2464
2808
  return "skipped";
2465
2809
  }
2466
2810
  launchRequests.set(requestKey(p, taskId, n), req);
@@ -2659,7 +3003,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2659
3003
  if (c.kind === "confirmed") {
2660
3004
  const p = current(p0);
2661
3005
  p.preConfirmLosses = 0;
2662
- p.preConfirmCapture = null;
3006
+ p.preConfirmCaptures.clear();
2663
3007
  return;
2664
3008
  }
2665
3009
  await withTask(current(p0), taskId, async () => {
@@ -2672,8 +3016,11 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2672
3016
  });
2673
3017
  }
2674
3018
 
2675
- /** Row 11: dispatched -> ready, uncounted; slot and leases are kept (R4). */
2676
- async function rowLost(p: PlanRt, taskId: TaskId, n: number, reason: string): Promise<void> {
3019
+ /**
3020
+ * Row 11: dispatched -> ready, uncounted; slot and leases are kept (R4). `ref`: the capture the launch was pinned to,
3021
+ * when the launch threw before its request was kept.
3022
+ */
3023
+ async function rowLost(p: PlanRt, taskId: TaskId, n: number, reason: string, ref?: ContextRef): Promise<void> {
2677
3024
  const at = d.clock.iso();
2678
3025
  let applied = false;
2679
3026
  try {
@@ -2691,32 +3038,39 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2691
3038
  d.log("error", "row 11 failed", errorText(e));
2692
3039
  }
2693
3040
  releaseToken(p, taskId, n, "other");
2694
- if (applied) await preConfirmLost(p, taskId, n, reason);
3041
+ if (applied) await preConfirmLost(p, taskId, n, reason, ref);
2695
3042
  schedule(p);
2696
3043
  }
2697
3044
 
2698
3045
  /**
2699
- * QA-3.1-17: whether a row 11 counts toward the pre-confirmation streak. A loss counts once per capture (the attempt's
2700
- * `callID`): N parallel launches lost under one capture change (E_NO_CONTEXT, superseded: the expected uncounted L3/L5
2701
- * race) are one loss, not N. A `superseded`/`no-context` loss is ignored outright when a newer capture is already
2702
- * current (the relaunch goes out under it). Within one capture a task lost AGAIN (a relaunch that failed the same way)
2703
- * counts again, so a failure that repeats on each relaunch still pauses (QA-3.1-4).
3046
+ * QA-3.1-17: whether a row 11 counts toward the pre-confirmation streak. A loss counts once per capture: N parallel
3047
+ * launches lost under one capture change (E_NO_CONTEXT, superseded: the expected uncounted L3/L5 race) are one loss,
3048
+ * not N. A `superseded`/`no-context` loss is ignored outright when a newer capture is already current (the relaunch
3049
+ * goes out under it). Within one capture a task lost AGAIN (a relaunch that failed the same way) counts again, so a
3050
+ * failure that repeats on each relaunch still pauses (QA-3.1-4). #194: every capture of the streak is remembered, so
3051
+ * interleaved losses (C1, C2, C1) count C1 once; a capture is the launch's (boot id, epoch, call id) when this process
3052
+ * launched it, else the attempt's journaled `callID`.
2704
3053
  */
2705
- function preConfirmCounts(p: PlanRt, taskId: TaskId, n: number, reason: string): boolean {
3054
+ function preConfirmCounts(p: PlanRt, taskId: TaskId, n: number, reason: string, given?: ContextRef): boolean {
2706
3055
  const l = p.writer.ledger;
2707
3056
  const callID = own(l, taskId)?.attempts.find((a) => a.n === n)?.callID ?? null;
3057
+ const kept = given ?? launchRequests.get(requestKey(p, taskId, n))?.context;
3058
+ const ref = kept !== undefined && kept.bootID !== "" ? kept : null;
2708
3059
  if ((reason === "superseded" || reason === "no-context") && callID !== null) {
2709
3060
  const g = d.launcher.gate(l.orchestrator.sessionID);
2710
- if (g.ok && g.context.callID !== callID) return false;
2711
- }
2712
- const key = callID ?? `\u0000${taskId}#${n}`;
2713
- const cap = p.preConfirmCapture;
2714
- if (cap === null || cap.key !== key) {
2715
- p.preConfirmCapture = { key, tasks: new Set([taskId]) };
3061
+ const newer = !g.ok ? false : ref !== null
3062
+ ? g.context.bootID !== ref.bootID || g.context.epoch !== ref.epoch || g.context.callID !== ref.callID
3063
+ : g.context.callID !== callID;
3064
+ if (newer) return false;
3065
+ }
3066
+ const key = ref !== null ? `${ref.bootID}:${ref.epoch}:${ref.callID}` : callID ?? `\u0000${taskId}#${n}`;
3067
+ const tasks = p.preConfirmCaptures.get(key);
3068
+ if (tasks === undefined) {
3069
+ p.preConfirmCaptures.set(key, new Set([taskId]));
2716
3070
  return true;
2717
3071
  }
2718
- if (cap.tasks.has(taskId)) return true;
2719
- cap.tasks.add(taskId);
3072
+ if (tasks.has(taskId)) return true;
3073
+ tasks.add(taskId);
2720
3074
  return false;
2721
3075
  }
2722
3076
 
@@ -2726,12 +3080,12 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2726
3080
  * PRECONFIRM_STREAK consecutive counted losses (`preConfirmCounts`, QA-3.1-17) the plan pauses (no more launches, so
2727
3081
  * no more stale-context wakes) and ONE blocking item is raised. A confirmed launch, and a resume, reset the count.
2728
3082
  */
2729
- async function preConfirmLost(p: PlanRt, taskId: TaskId, n: number, reason: string): Promise<void> {
2730
- if (!preConfirmCounts(p, taskId, n, reason)) return;
3083
+ async function preConfirmLost(p: PlanRt, taskId: TaskId, n: number, reason: string, ref?: ContextRef): Promise<void> {
3084
+ if (!preConfirmCounts(p, taskId, n, reason, ref)) return;
2731
3085
  p.preConfirmLosses += 1;
2732
3086
  if (p.preConfirmLosses < PRECONFIRM_STREAK) return;
2733
3087
  p.preConfirmLosses = 0;
2734
- p.preConfirmCapture = null;
3088
+ p.preConfirmCaptures.clear();
2735
3089
  let paused = false;
2736
3090
  try {
2737
3091
  paused = await appendIf(p, (cur) =>
@@ -3259,7 +3613,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
3259
3613
  // `parkItemOf` picks that item on the answer), its pending dependents are blocked and its file leases are kept with
3260
3614
  // the slot (as the policy's park keeps them for a kept slot, and `rebuildLeases` rebuilds them after a restart).
3261
3615
  const holdWhat = "its release (lease-needed)";
3262
- const holdText = saved === "failed" && slotName !== null ? wipHoldText(slotName, holdWhat, t.id) : null;
3616
+ const holdText = saved === "failed" && slotName !== null ? wipHoldText(p, slotName, holdWhat, t.id) : null;
3263
3617
  const applied = await appendIf(p, (cur) => {
3264
3618
  const c = own(cur, t.id);
3265
3619
  if (c === null || c.state !== "running" || openAttempt(c, a.n) === null) return [];
@@ -3317,7 +3671,10 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
3317
3671
  // QA-4.2-16: held until the leases are back (`retryHeldLeases` resumes it).
3318
3672
  if (p.leaseHeld.has(taskId)) return;
3319
3673
  const slotName = t.slot;
3320
- const commitFailed = async (msg: string): Promise<void> => {
3674
+ const commitFailed = async (error: string): Promise<void> => {
3675
+ // QA-4.2-38 (#188): never an empty context; it marks the commit failure of a task an abort cancels later
3676
+ // (`isCommitFailure`).
3677
+ const msg = error.trim() === "" ? "commit failed" : error;
3321
3678
  const applied = await appendIf(p, (cur) => {
3322
3679
  const c = own(cur, taskId);
3323
3680
  if (c === null || c.state !== "completed") return [];
@@ -3330,22 +3687,31 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
3330
3687
  let lease: SlotLease;
3331
3688
  let r: { changed: false } | { changed: true; commit: string };
3332
3689
  const branch = taskBranchName(p.planId, taskId);
3690
+ const att = t.attempts.find((x) => x.n === n);
3333
3691
  try {
3334
3692
  lease = await slotLeaseOf(p, t);
3335
3693
  // D11: the attempt's trailer makes the commit idempotent across a crash between the commit and row 21.
3336
- const att = t.attempts.find((x) => x.n === n);
3337
3694
  if (att !== undefined && d.verifier.observe !== undefined) await d.verifier.observe(t, lease, att, await finalTextOf(p, taskId, att), planTaskContext(p));
3695
+ } catch (e) {
3696
+ if (p.disposed) return;
3697
+ await commitFailed(errorText(e));
3698
+ return;
3699
+ }
3700
+ try {
3338
3701
  if (p.disposed) return;
3339
3702
  r = await commitTaskInSlot(d.git, {
3340
3703
  slot: lease,
3341
3704
  branch,
3342
3705
  message: `${taskId}: ${t.title} (attempt ${n})`,
3343
3706
  timeoutMs: GIT_TIMEOUT_MS,
3707
+ ...(d.commitIdentity === undefined ? {} : { identity: d.commitIdentity }),
3344
3708
  ...(att === undefined ? {} : { trailer: attemptTrailer(p.planId, taskId, n, att.nonce) }),
3345
3709
  });
3346
3710
  } catch (e) {
3347
3711
  if (p.disposed) return;
3348
- await commitFailed(errorText(e));
3712
+ const diagnostic = gitDiagnostic(e);
3713
+ d.log("warn", `task ${taskId} git commit failed`, diagnostic);
3714
+ await commitFailed(diagnostic.message);
3349
3715
  return;
3350
3716
  }
3351
3717
  if (p.disposed) return;
@@ -3385,7 +3751,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
3385
3751
  function verifyAttempt(p: PlanRt, taskId: TaskId, n: number, lease: SlotLease): Promise<void> {
3386
3752
  // QA-5.1-21: tracked on every path (a recovery re-verify too, not only an end's processing), so dispose's wait for running
3387
3753
  // work covers the journaling of a verdict that settles after the verifier was cut; `closePlan` runs after that wait.
3388
- return holdAttachment(p, track(verifyAttemptNow(p, taskId, n, lease)));
3754
+ return holdAttachment(p, `verification of ${taskId}#${n}`, track(verifyAttemptNow(p, taskId, n, lease)));
3389
3755
  }
3390
3756
 
3391
3757
  async function verifyAttemptNow(p: PlanRt, taskId: TaskId, n: number, lease: SlotLease): Promise<void> {
@@ -3412,9 +3778,11 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
3412
3778
  nonce = att.nonce;
3413
3779
  forgotten.delete(`${p.planId}/${taskId}#${n}`);
3414
3780
  if (d.verifier.observe !== undefined) await d.verifier.observe(cur, lease, att, await finalTextOf(p, taskId, att), planTaskContext(p));
3781
+ // Recovery-R1-m1 (#190): an attachment cut during the observation cleans nothing (the next attachment re-verifies).
3782
+ if (attachmentCut(p)) return;
3415
3783
  await slotsFor(p.planId).cleanForChecks(lease.slot);
3416
3784
  if (p.disposed || parkWithoutContext()) return;
3417
- const v = await d.verifier.verify(cur, lease, att, planTaskContext(p));
3785
+ const v = await d.verifier.verify(cur, lease, att, verifyContext(p, taskId, n, lease));
3418
3786
  verdict = v.verdict;
3419
3787
  findings = v.findings;
3420
3788
  ref = v.ref;
@@ -3606,7 +3974,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
3606
3974
  if (sweep.stop === "cut") return;
3607
3975
  if (sweep.stop === "held") {
3608
3976
  // The slot stays leased to the task under its hold; the sweep raised it when it knew the slot.
3609
- if (sweep.slot === null && sweep.child !== null && (await slotHeldBy(p, taskId, slot))) {
3977
+ if (sweep.slot === null && sweep.child !== null && (await slotHeldBy(p, taskId, slot, true))) {
3610
3978
  sweep.slot = slot;
3611
3979
  await holdAdoptedSlot(p, taskId, slot, sweep.child, "dep-reverted");
3612
3980
  }
@@ -3958,12 +4326,14 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
3958
4326
  const p = await build(writer, refusedBy !== null);
3959
4327
  onRegistered();
3960
4328
  if (refusedBy !== null) {
3961
- await refusePassive(p, refusedBy);
4329
+ // #190: no refusal item or orchestrator wake once dispose began.
4330
+ if (!disposed) await refusePassive(p, refusedBy);
3962
4331
  return p;
3963
4332
  }
3964
4333
  const st = writer.ledger.status;
3965
4334
  // An existing ledger (start, adopt, a plan opened by an action) is recovered; a just-created one is not (4.2.5).
3966
- if (st === "running" || st === "paused") await activate(p, existingLedger);
4335
+ // #190: never once dispose began (the plan is registered: dispose closes it).
4336
+ if ((st === "running" || st === "paused") && !disposed) await activate(p, existingLedger);
3967
4337
  return p;
3968
4338
  } finally {
3969
4339
  if (reserved) unreserve(planId);
@@ -4089,15 +4459,17 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4089
4459
  provisionFails: 0,
4090
4460
  provisionRaised: false,
4091
4461
  preConfirmLosses: 0,
4092
- preConfirmCapture: null,
4462
+ preConfirmCaptures: new Map(),
4093
4463
  routeFails: 0,
4094
4464
  routeRaised: false,
4095
4465
  passive,
4096
4466
  recovering: false,
4097
4467
  recoveredWork: new Map(),
4098
- attachmentWork: new Set(),
4468
+ attachmentWork: new Map(),
4099
4469
  attachment: new AbortController(),
4100
4470
  integrationResumed: false,
4471
+ unreconciled: false,
4472
+ treesAlive: new Map(),
4101
4473
  probation: new Map(),
4102
4474
  probationTimer: null,
4103
4475
  interrupting: new Set(),
@@ -4119,6 +4491,12 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4119
4491
  attachSlotObservations(d.observations, d.clock, writer);
4120
4492
  try { await rebuildHeldSlots(p); }
4121
4493
  catch (error) { d.log("warn", "slot holds will be rechecked before collection", errorText(error)); }
4494
+ if (disposed) {
4495
+ // #190: a dispose that landed during the awaits above registers nothing; the caller closes the writer it opened.
4496
+ detachSlotObservations(d.clock, writer);
4497
+ await disposeQueue(p);
4498
+ throw new ExecutorError("E_DISPOSED", "the runtime is disposing; no new attachment");
4499
+ }
4122
4500
  plans.set(planId, p);
4123
4501
  observeSchedulerLedger(d.observations, writer.ledger, "attach");
4124
4502
  observe(p, "runtime-attach");
@@ -4191,8 +4569,6 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4191
4569
  });
4192
4570
  }
4193
4571
 
4194
- /** Plans `recover()` reported eligible (same toplevel) or adopted here: only these may be taken over by `start()`. */
4195
- const recoverable = new Set<PlanId>();
4196
4572
  /** QA-4.2-17: plans of another toplevel `start()` attached passively; never recovered, resumed or ticked here. */
4197
4573
  const foreignPlans = new Set<PlanId>();
4198
4574
  /**
@@ -4263,11 +4639,22 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4263
4639
  */
4264
4640
  async function recoverPlan(p: PlanRt): Promise<void> {
4265
4641
  // (2) classification, read-only; launches this process tracks are never reconciled (D12)
4266
- const feeds = await reconcileFeeds(p);
4642
+ const got = await reconcileFeeds(p);
4643
+ // #189: a ledger that could not be classified (e.g. a stale plan `start` took over outside the recover() report,
4644
+ // whose slot markers cannot be read) is never run with no feeds: paused, one blocking item, no recovery step.
4645
+ if (!Array.isArray(got)) {
4646
+ await reconcileFailed(p, got.failed);
4647
+ return;
4648
+ }
4649
+ p.unreconciled = false;
4650
+ const feeds = got;
4267
4651
  // (3) orphans, best effort
4268
4652
  for (const f of feeds) for (const s of f.orphans) await interruptQuiet(s);
4269
4653
  // (4) the integration queue, before any dequeue (D7)
4270
4654
  await resumeIntegration(p);
4655
+ // #189 R2-pre-2: the verification trees a dead server left running are ended before any recovered work can verify
4656
+ // (or clean) in their slots; a slot whose kill is not confirmed parks its recovered work.
4657
+ await sweepVerifyTrees(p);
4271
4658
  // (5) the matrix, in task-id order
4272
4659
  for (const f of feeds) {
4273
4660
  try {
@@ -4302,7 +4689,126 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4302
4689
  }
4303
4690
  }
4304
4691
 
4305
- async function reconcileFeeds(p: PlanRt): Promise<ReconcileFeed[]> {
4692
+ /**
4693
+ * #189 R2-pre-2: sweeps the plan's process journals of dead servers (`VerifyTrees.sweep`) and rebuilds `treesAlive` from
4694
+ * the result: a slot whose trees could not be proven gone parks its recovered work (`verify-tree-alive`) and raises one
4695
+ * blocking item naming the PIDs (deduplicated on its text); a resume sweeps again. Never throws.
4696
+ */
4697
+ async function sweepVerifyTrees(p: PlanRt): Promise<void> {
4698
+ if (d.verifyTrees === undefined) return;
4699
+ const signal = p.attachment.signal;
4700
+ const l = p.writer.ledger;
4701
+ let swept: VerifyTreeSweep;
4702
+ try {
4703
+ // L8: each journal's slot must be the pool's path of a slot in the plan's slots directory. M2: the attachment's
4704
+ // signal (closePlan, dispose) aborts the sweep.
4705
+ swept = await d.verifyTrees.sweep(p.planId, { slotsDir: l.config.slotsDir ?? defaultSlotsDir(l.repo.toplevel, p.planId), signal });
4706
+ } catch (e) {
4707
+ swept = { alive: [{ slot: "", taskId: null, n: null, serverPid: null, pids: [], reason: errorText(e) }], killed: [], cleared: 0, refused: [] };
4708
+ }
4709
+ // A sweep cut by the attachment closing decided nothing: the next activation sweeps again.
4710
+ if (p.disposed || disposed || signal.aborted) return;
4711
+ if (swept.killed.length > 0) counter(p, "verify-tree-killed", { pids: swept.killed.join(",") });
4712
+ for (const r of swept.refused) {
4713
+ counter(p, "verify-tree-refused", { file: r.file });
4714
+ d.log("warn", `plan ${p.planId}: verification journal ${r.file} refused, never acted on`, r.reason);
4715
+ }
4716
+ const bySlot = new Map<string, AliveVerifyTree>();
4717
+ for (const a of swept.alive) {
4718
+ const key = verifyTreeKey(a);
4719
+ const seen = bySlot.get(key);
4720
+ bySlot.set(key, seen === undefined ? a : {
4721
+ ...seen,
4722
+ pids: [...new Set([...seen.pids, ...a.pids])],
4723
+ reason: seen.reason === a.reason ? seen.reason : `${seen.reason}; ${a.reason}`,
4724
+ });
4725
+ }
4726
+ p.treesAlive = bySlot;
4727
+ for (const [key, a] of bySlot) {
4728
+ const pids = a.pids.length === 0 ? "" : ` (pid ${a.pids.join(", ")})`;
4729
+ counter(p, "verify-tree-alive", { slot: key, taskId: a.taskId ?? "", pids: a.pids.join(",") });
4730
+ d.log("warn", `plan ${p.planId}: verification processes a dead server left in slot ${key} may still run${pids}`, a.reason);
4731
+ await raiseSafe(p, { kind: "failure", severity: "blocking", taskId: key === VERIFY_TREES_ANY ? null : a.taskId, text: verifyTreeItemText(p, key, a), options: [] });
4732
+ }
4733
+ await closeClearedTreeItems(p);
4734
+ }
4735
+
4736
+ /** The `treesAlive` key of an unconfirmed journal: its slot, else its attempt's task, else the whole plan. */
4737
+ function verifyTreeKey(a: AliveVerifyTree): string {
4738
+ if (a.slot !== "") return a.slot;
4739
+ return a.taskId === null ? VERIFY_TREES_ANY : `${VERIFY_TREES_ANY}${a.taskId}`;
4740
+ }
4741
+
4742
+ /** The blocking item of one `treesAlive` key; `treeItemKey` reads the key back from it. */
4743
+ function verifyTreeItemText(p: PlanRt, key: string, a: AliveVerifyTree): string {
4744
+ const resume = `/plan resume ${p.planId} (the resume sweeps again)`;
4745
+ if (key === VERIFY_TREES_ANY) {
4746
+ return `the verification process journal of plan ${p.planId} could not be swept (${a.reason}); every recovered verification of the plan waits so it cannot overlap a dead server's checks: fix the cause, then ${resume}`;
4747
+ }
4748
+ if (a.slot === "") {
4749
+ return `the verification process journal of ${a.taskId ?? "a task"}${a.n === null ? "" : `#${a.n}`} in plan ${p.planId} could not be swept (${a.reason}); its recovered work waits so it cannot overlap a dead server's checks: fix the cause, then ${resume}`;
4750
+ }
4751
+ // Re-review 5: a `late` process was started after the recorded run could still start processes, so it may be the
4752
+ // user's own (an editor or a shell on the slot); it is listed apart from the ones the kill failed on.
4753
+ const late = new Set(a.late ?? []);
4754
+ const failed = a.pids.filter((pid) => !late.has(pid));
4755
+ const pids = failed.length === 0 ? "" : ` (pid ${failed.join(", ")})`;
4756
+ const lateText = late.size === 0
4757
+ ? ""
4758
+ : `; pid ${[...late].join(", ")} started after the dead server's run could still start processes, so they may be your own processes (an editor or a shell on the slot): check them before ending them`;
4759
+ return `the verification of ${a.taskId ?? "a task"}${a.n === null ? "" : `#${a.n}`} that a dead server${a.serverPid === null ? "" : ` (pid ${a.serverPid})`} ran in slot ${key} may still be running${pids}: ${a.reason}${lateText}; the slot's recovered work waits so it cannot overlap those processes: end them, then ${resume}`;
4760
+ }
4761
+
4762
+ /** The `treesAlive` key an open item of `verifyTreeItemText` names, or null for any other item. */
4763
+ function treeItemKey(p: PlanRt, text: string): string | null {
4764
+ if (text.startsWith(`the verification process journal of plan ${p.planId} could not be swept (`)) return VERIFY_TREES_ANY;
4765
+ const task = /^the verification process journal of (\S+?)(?:#\d+)? in plan (\S+) could not be swept \(/.exec(text);
4766
+ if (task !== null) return task[2] === p.planId ? `${VERIFY_TREES_ANY}${task[1]}` : null;
4767
+ const slot = /^the verification of \S+ that a dead server.*? ran in slot (\S+) may still be running/.exec(text);
4768
+ return slot?.[1] ?? null;
4769
+ }
4770
+
4771
+ /** L6: an open item of a key the last sweep confirmed clear is closed (journaled as answered). Never throws. */
4772
+ async function closeClearedTreeItems(p: PlanRt): Promise<void> {
4773
+ const cleared = p.writer.ledger.inbox.filter((i) => {
4774
+ if (i.answer !== null || i.kind !== "failure") return false;
4775
+ const key = treeItemKey(p, i.text);
4776
+ return key !== null && !p.treesAlive.has(key);
4777
+ }).map((i) => i.id);
4778
+ if (cleared.length === 0) return;
4779
+ try {
4780
+ await appendIf(p, (cur) => cleared
4781
+ .filter((id) => cur.inbox.some((i) => i.id === id && i.answer === null))
4782
+ .map((id): ExecutorEventInput => ({ type: "inbox-answered", id, answer: VERIFY_TREE_RESOLVED })));
4783
+ } catch (e) {
4784
+ d.log("warn", "closing the verification-tree items failed", errorText(e));
4785
+ }
4786
+ }
4787
+
4788
+ /** #189: pauses a plan whose `reconcile` threw and raises ONE blocking item naming the cause; never throws. */
4789
+ async function reconcileFailed(p: PlanRt, e: unknown): Promise<void> {
4790
+ p.unreconciled = true;
4791
+ let paused = false;
4792
+ try {
4793
+ paused = await appendIf(p, (cur) =>
4794
+ cur.status === "running" ? [{ type: "status-changed", from: "running", to: "paused", reason: "reconcile-failed" }] : [],
4795
+ );
4796
+ } catch (e2) {
4797
+ d.log("error", "reconcile pause failed", errorText(e2));
4798
+ }
4799
+ if (paused) closeIdle(p);
4800
+ counter(p, "reconcile-failed");
4801
+ await raiseSafe(p, {
4802
+ kind: "failure",
4803
+ severity: "blocking",
4804
+ taskId: null,
4805
+ text: `the restart recovery of plan ${p.planId} could not classify its tasks (${errorText(e).slice(0, 500)}); the plan is paused and no recovery step ran: resume it once the cause is fixed (the resume recovers it again)`,
4806
+ options: [],
4807
+ });
4808
+ }
4809
+
4810
+ /** The recovery feeds of `p`; `{ failed }` when `reconcile` threw (#189: the caller pauses the plan). */
4811
+ async function reconcileFeeds(p: PlanRt): Promise<ReconcileFeed[] | { failed: unknown }> {
4306
4812
  const rec = d.recovery;
4307
4813
  const l = p.writer.ledger;
4308
4814
  const tracked = new Set<string>();
@@ -4330,7 +4836,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4330
4836
  return await rec.reconcile(l, tracked);
4331
4837
  } catch (e) {
4332
4838
  d.log("error", "reconcile failed", errorText(e));
4333
- return [];
4839
+ return { failed: e };
4334
4840
  }
4335
4841
  }
4336
4842
 
@@ -4397,7 +4903,8 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4397
4903
  async function adoptChild(p: PlanRt, t: TaskNode, f: ReconcileFeed): Promise<void> {
4398
4904
  const a = t.attempts.find((x) => x.n === f.n);
4399
4905
  const child = f.childSessionID;
4400
- if (a === undefined || child === null) return;
4906
+ // QA-4.2-40 (#189): only the child the attempt records is adopted (token, handle, re-bind, probation).
4907
+ if (a === undefined || child === null || a.childSessionID !== child) return;
4401
4908
  const n = a.n;
4402
4909
  const live = f.evidence !== "finished";
4403
4910
  // QA-4.2-16: a task whose leases could not be re-taken never adopts a live child (it would write without leases):
@@ -4574,7 +5081,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4574
5081
  const task = own(p.writer.ledger, taskId);
4575
5082
  if (task === null || task.state !== "ready") return;
4576
5083
  const slotName = task.slot;
4577
- if (slotName !== null && !(await releaseGoneSlot(p, taskId, slotName))) return;
5084
+ if (slotName !== null && (await releaseGoneSlot(p, taskId, slotName)) !== null) return;
4578
5085
  const applied = await appendIf(p, (cur) => {
4579
5086
  const c = own(cur, taskId);
4580
5087
  return c === null || c.state !== "ready" || c.slot === null ? [] : [ts(taskId, null, null)];
@@ -4587,8 +5094,9 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4587
5094
  /**
4588
5095
  * R2: a foreign slot is untouched. An owned slot with a missing/invalid marker can still hold work: save it before
4589
5096
  * returning it to the pool, or retain its lease and durable hold. Metadata-less directories are quarantined, not lost.
5097
+ * Null when the slot went back to the pool (or was not ours); else why it could not (#189: R2's item names it).
4590
5098
  */
4591
- async function releaseGoneSlot(p: PlanRt, taskId: TaskId, slotName: string): Promise<boolean> {
5099
+ async function releaseGoneSlot(p: PlanRt, taskId: TaskId, slotName: string): Promise<string | null> {
4592
5100
  let held = false;
4593
5101
  try {
4594
5102
  const rec = await slotsFor(p.planId).get(slotName);
@@ -4596,13 +5104,13 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4596
5104
  } catch (e) {
4597
5105
  d.log("warn", `slot lookup of the bad slot ${slotName} failed`, errorText(e));
4598
5106
  await wipHold(p, taskId, slotName, "its recovery release");
4599
- return false;
5107
+ return `its pool record could not be read: ${errorText(e)}; its own item names the slot`;
4600
5108
  }
4601
- if (!held) return true;
5109
+ if (!held) return null;
4602
5110
  const saved = await snapshotTaskSlot(p, taskId, slotName, "recovery-release");
4603
5111
  if (saved === "failed") {
4604
5112
  await wipHold(p, taskId, slotName, "its recovery release");
4605
- return false;
5113
+ return "its work could not be saved; its own item names the slot";
4606
5114
  }
4607
5115
  if (p.slotLeases.get(taskId)?.slot === slotName) p.slotLeases.delete(taskId);
4608
5116
  wipFailRaised.delete(`${p.planId}/${slotName}`);
@@ -4611,48 +5119,81 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4611
5119
  counter(p, "bad-slot-released", { taskId, slot: slotName });
4612
5120
  } catch (e) {
4613
5121
  d.log("warn", `releasing the bad slot ${slotName} of ${taskId} failed`, errorText(e));
4614
- return false;
5122
+ return `the pool's release failed: ${errorText(e)}`;
4615
5123
  }
4616
- return true;
5124
+ return null;
4617
5125
  }
4618
5126
 
4619
5127
  /**
4620
5128
  * R2: a `completed`/`verifying`/`verified` task whose slot marker is missing or foreign gets a slot again from its task
4621
5129
  * branch `omr/<planId>/t/<taskId>`: the stale slot goes back to the pool (only if the pool still records it as ours), a
4622
5130
  * slot is acquired, reset to the branch tip and checked out (detached) at it, the task's leases move to the new tree
4623
- * (released and re-taken, as `rebuild` does) and the slot is journaled (state re-checked, D2). False when the branch
4624
- * does not exist (nothing touched) or a later step fails (the new slot is returned); the caller raises the blocking item.
5131
+ * (released and re-taken, as `rebuild` does) and the slot is journaled (state re-checked, D2). `failed` (with its
5132
+ * reason) when the branch does not exist (nothing touched) or a later step fails (the new slot is returned); the caller
5133
+ * raises the blocking item. #189 (QA-4.2-31): `held` when the leases are held elsewhere: the new slot is journaled and
5134
+ * kept (its cached lease too) and the task is held on it (`leaseHeld`, one hold item while none is open);
5135
+ * `retryHeldLeases` re-takes its leases on the new tree and resumes it once they are free. A failed journal write still
5136
+ * returns the new slot (`failed`). A failure after the stale slot was given up also ends a hold: the ledger's slot is
5137
+ * not this task's any more, so no lease rebuild may resume the task on it.
4625
5138
  */
4626
- async function reprovisionSlot(p: PlanRt, taskId: TaskId): Promise<boolean> {
5139
+ async function reprovisionSlot(p: PlanRt, taskId: TaskId, knownTip?: string): Promise<Reprovision> {
4627
5140
  const t0 = own(p.writer.ledger, taskId);
4628
- if (t0 === null || (t0.state !== "completed" && t0.state !== "verifying" && t0.state !== "verified")) return false;
5141
+ if (t0 === null || (t0.state !== "completed" && t0.state !== "verifying" && t0.state !== "verified")) {
5142
+ return { kind: "failed", reason: "task moved", detail: t0 === null ? "the task is gone" : `it is ${t0.state}` };
5143
+ }
4629
5144
  const from = t0.state;
4630
5145
  const branch = taskBranchName(p.planId, taskId);
4631
5146
  const o = { cwd: p.writer.ledger.repo.toplevel, timeoutMs: GIT_TIMEOUT_MS };
4632
- let tip = "";
4633
- try {
4634
- const r = await d.git.run(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}^{commit}`], o);
4635
- tip = r.code === 0 ? r.stdout.trim() : "";
4636
- } catch (e) {
4637
- d.log("warn", `task branch of ${taskId} unreadable`, errorText(e));
5147
+ // QA-4.2-32 (#188): the tip whose history the trailer search read, when there was one.
5148
+ let tip = knownTip ?? "";
5149
+ if (tip === "") {
5150
+ // Why the branch could not be read; "" when it does not exist (`--verify --quiet`: exit 1, no output).
5151
+ let unreadable = "";
5152
+ try {
5153
+ const r = await d.git.run(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}^{commit}`], o);
5154
+ tip = r.code === 0 ? r.stdout.trim() : "";
5155
+ if (tip === "" && !(r.code === 1 && r.stdout.trim() === "")) {
5156
+ const stderr = r.stderr.trim();
5157
+ unreadable = `exit ${r.code}: ${stderr === "" ? "no commit id" : stderr.slice(0, 2000)}`;
5158
+ }
5159
+ } catch (e) {
5160
+ unreadable = errorText(e);
5161
+ }
5162
+ if (unreadable !== "") d.log("warn", `task branch of ${taskId} unreadable`, unreadable);
5163
+ if (tip === "") return { kind: "failed", reason: unreadable === "" ? "no branch" : "branch unreadable", detail: unreadable };
4638
5164
  }
4639
- if (tip === "") return false;
4640
5165
  const stale = t0.slot;
4641
- // Missing marker evidence is not permission to discard an owned tree. A failed save stops re-provisioning.
4642
- if (stale !== null && !(await releaseGoneSlot(p, taskId, stale))) return false;
5166
+ // Missing marker evidence is not permission to discard an owned tree. A failed save (or release) stops here.
5167
+ const kept = stale === null ? null : await releaseGoneSlot(p, taskId, stale);
5168
+ if (kept !== null) return { kind: "failed", reason: "release failed", detail: kept };
5169
+ // #189: from here the ledger's slot is not this task's (back in the pool, or another task's). A failure must not
5170
+ // leave the task held on it: a lease release would rebuild its leases on that tree and resume it there.
5171
+ const failed = (reason: ReprovisionFailure, detail: string): Reprovision => {
5172
+ p.leaseHeld.delete(taskId);
5173
+ return { kind: "failed", reason, detail };
5174
+ };
4643
5175
  p.slotLeases.delete(taskId);
4644
5176
  let slot: SlotLease | null = null;
4645
- const undo = async (why: string, e?: unknown): Promise<false> => {
4646
- d.log("warn", `re-provisioning ${taskId} from ${branch}: ${why}`, e === undefined ? "" : errorText(e));
5177
+ const undo = async (reason: ReprovisionFailure, cause: unknown): Promise<Reprovision> => {
5178
+ const detail = errorText(cause);
5179
+ // Recovery-R1-m1 (#190): an undo after the attachment's cut is expected (info); any other undo is a failure (warn).
5180
+ d.log(attachmentCut(p) ? "info" : "warn", `re-provisioning ${taskId} from ${branch}: ${reason}`, detail);
4647
5181
  const s = slot;
4648
- if (s !== null && !(await releaseSlotSaved(p, taskId, s.slot, "reprovision-undo"))) return false;
5182
+ if (s !== null && !(await releaseSlotSaved(p, taskId, s.slot, "reprovision-undo"))) return failed(reason, detail);
4649
5183
  p.slotLeases.delete(taskId);
4650
- return false;
5184
+ return failed(reason, detail);
4651
5185
  };
5186
+ // The step a throw below comes from (the item names it).
5187
+ let step: ReprovisionFailure = "slot unavailable";
4652
5188
  try {
4653
- const { verifiedResetBase, ...acquired } = await slotsFor(p.planId).acquire(p.planId, leaseHolderID(p.planId, taskId), tip);
5189
+ // Recovery-R1-m1 (#190): an attachment cut aborts the claim while it is still queued (a running provisioning ends).
5190
+ const { verifiedResetBase, ...acquired } = await slotsFor(p.planId).acquire(p.planId, leaseHolderID(p.planId, taskId), tip,
5191
+ { signal: p.attachment.signal });
4654
5192
  slot = acquired;
4655
5193
  p.slotLeases.set(taskId, slot);
5194
+ // Recovery-R1-m1 (#190): cut while the slot was acquired: it goes back to the pool and no item is raised.
5195
+ if (attachmentCut(p)) return await undo("attachment cut", "the attachment was cut while its slot was acquired");
5196
+ step = "reset failed";
4656
5197
  if (verifiedResetBase === undefined) {
4657
5198
  const saved = await saveBeforeLaunchReset(p, t0, slot, slot.commit);
4658
5199
  if (saved === "failed") {
@@ -4660,26 +5201,30 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4660
5201
  // still names the stale slot, and a cache naming this one would hand it to the verifier or a release.
4661
5202
  await wipHold(p, taskId, slot.slot, "its re-provisioning reset");
4662
5203
  if (p.slotLeases.get(taskId)?.slot === slot.slot) p.slotLeases.delete(taskId);
4663
- return false;
5204
+ return failed("save failed", "");
4664
5205
  }
4665
5206
  }
4666
5207
  if (verifiedResetBase !== tip) await slotsFor(p.planId).reset(slot.slot, tip);
4667
5208
  // QA-PDF21-12: the cached lease follows the reset (a re-acquired slot's lease names its pre-reset commit).
4668
5209
  slot = leaseAt(slot, tip);
4669
5210
  p.slotLeases.set(taskId, slot);
5211
+ step = "checkout failed";
4670
5212
  // Detached at the tip: the branch may still be checked out in the stale worktree, and the ref itself stays put.
4671
5213
  const r = await d.git.run(["switch", "--detach", tip], { cwd: slot.path, timeoutMs: GIT_TIMEOUT_MS });
4672
5214
  if (r.code !== 0) return await undo("checkout failed", r.stderr.slice(0, 2000));
4673
5215
  } catch (e) {
4674
- return await undo("slot unavailable", e);
5216
+ return await undo(step, e);
4675
5217
  }
4676
5218
  const lease = slot;
4677
5219
  releaseLeases(p, taskId);
5220
+ // #189 (QA-4.2-31): the holders when another task holds the leases (the new slot is kept, the task held on it).
5221
+ let holders: LeaseHolderInfo[] | null = null;
4678
5222
  try {
4679
5223
  const got = p.leases.acquireTask({ taskId, tree: lease.path, writes: t0.footprint.writes });
4680
- if (!got.ok) return await undo("leases held elsewhere");
5224
+ if (!got.ok && got.reason !== "held") return await undo(got.reason === "cap" ? "lease cap" : "lease invalid", got.message);
5225
+ if (!got.ok) holders = got.holders;
4681
5226
  // QA-4.2-16: the leases are back on the new tree; a hold from the failed rebuild ends here.
4682
- p.leaseHeld.delete(taskId);
5227
+ else p.leaseHeld.delete(taskId);
4683
5228
  } catch (e) {
4684
5229
  return await undo("lease error", e);
4685
5230
  }
@@ -4693,36 +5238,70 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4693
5238
  return await undo("journal failed", e);
4694
5239
  }
4695
5240
  const now = own(p.writer.ledger, taskId);
4696
- if (now === null || now.slot !== lease.slot) return await undo("the task moved");
5241
+ if (now === null || now.slot !== lease.slot) {
5242
+ return await undo("task moved", now === null ? "the task is gone" : `it is ${now.state} on ${now.slot ?? "no slot"}`);
5243
+ }
5244
+ if (holders !== null) {
5245
+ // Held only once the ledger names the new slot: a retry before that would look up the stale (vanished) record.
5246
+ p.leaseHeld.add(taskId);
5247
+ counter(p, "slot-reprovisioned-held", { taskId, slot: lease.slot });
5248
+ // A lease release during the journal write found no hold to retry: this tick retries it.
5249
+ schedule(p);
5250
+ // Only while still held: a hold that already ended leaves no stale blocking item.
5251
+ if (p.leaseHeld.has(taskId)) await raiseLeaseHold(p, taskId, holders, `on its re-provisioned slot ${lease.slot}`);
5252
+ return { kind: "held", holders };
5253
+ }
4697
5254
  counter(p, "slot-reprovisioned", { taskId });
4698
- return true;
5255
+ return { kind: "ok" };
4699
5256
  }
4700
5257
 
4701
5258
  /**
4702
5259
  * R2 for `completed`/`verifying`/`verified`: re-provision from the task branch; when that is impossible (no branch, a
4703
5260
  * failed step) the slot is not this task's any more and its work cannot be trusted: one blocking item, a human decides.
5261
+ * #189 (QA-4.2-31): a task held on its new slot gets the hold item instead; `resumeHeldTask` resumes it once its leases
5262
+ * are back. `vanished`: the slot was lost mid-run (`slotVanished`), not found invalid at a restart.
4704
5263
  */
4705
- async function reprovisionOrRaise(p: PlanRt, t: TaskNode): Promise<boolean> {
4706
- if (await reprovisionSlot(p, t.id)) return true;
4707
- await raiseSlotLost(p, t);
4708
- return false;
5264
+ async function reprovisionOrRaise(p: PlanRt, t: TaskNode, vanished = false): Promise<boolean> {
5265
+ // Recovery-R1-m1 (#190): an attachment cut re-provisions nothing and raises no item (the next attachment recovers it).
5266
+ if (attachmentCut(p)) return false;
5267
+ const r = await reprovisionSlot(p, t.id);
5268
+ if (r.kind === "failed" && !attachmentCut(p)) await raiseSlotLost(p, t, r, vanished);
5269
+ return r.kind === "ok";
4709
5270
  }
4710
5271
 
4711
5272
  /**
4712
- * QA-4.2-13: whether a commit of the repository carries attempt `n`'s trailer (D11); null when git cannot tell. On
4713
- * attempt 1 the task branch is created by the commit itself, so a missing branch usually means "never committed".
5273
+ * QA-4.2-13: whether the task branch carries attempt `n`'s trailer (D11); null when git cannot tell. On attempt 1 the
5274
+ * task branch is created by the commit itself, so a missing branch usually means "never committed". QA-4.2-32 (#188):
5275
+ * `on-branch` (with the tip read, which R2 re-provisions from) only when the history of the task branch carries it. A
5276
+ * commit with the trailer that only another ref reaches is work R2 cannot re-provision: `unknown` naming it (fail
5277
+ * closed, the blocking item, a human decides), as when git cannot tell (`elsewhere` null).
4714
5278
  */
4715
- async function attemptCommitted(p: PlanRt, taskId: TaskId, a: Attempt): Promise<boolean | null> {
5279
+ async function attemptCommitted(p: PlanRt, taskId: TaskId, a: Attempt): Promise<AttemptCommit> {
4716
5280
  const trailer = attemptTrailer(p.planId, taskId, a.n, a.nonce);
5281
+ const o = { cwd: p.writer.ledger.repo.toplevel, timeoutMs: GIT_TIMEOUT_MS };
5282
+ const unknown: AttemptCommit = { kind: "unknown", elsewhere: null };
5283
+ /** The first commit `revs` reach that carries the trailer, "" for none, null when git cannot tell. */
5284
+ const search = async (revs: readonly string[]): Promise<string | null> => {
5285
+ const r = await d.git.run(["log", "--fixed-strings", `--grep=${trailer}`, "--format=%H", "-n", "1", ...revs, "--"], o);
5286
+ return r.code === 0 ? r.stdout.trim() : null;
5287
+ };
4717
5288
  try {
4718
- const r = await d.git.run(["log", "--all", "--fixed-strings", `--grep=${trailer}`, "--format=%H", "-n", "1"], {
4719
- cwd: p.writer.ledger.repo.toplevel,
4720
- timeoutMs: GIT_TIMEOUT_MS,
4721
- });
4722
- return r.code === 0 ? r.stdout.trim() !== "" : null;
5289
+ const ref = await d.git.run(["rev-parse", "--verify", "--quiet", `refs/heads/${taskBranchName(p.planId, taskId)}^{commit}`], o);
5290
+ const tip = ref.stdout.trim();
5291
+ const missing = ref.code === 1 && tip === "";
5292
+ if (!missing && (ref.code !== 0 || tip === "")) return unknown;
5293
+ if (!missing) {
5294
+ const onBranch = await search([tip]);
5295
+ if (onBranch === null) return unknown;
5296
+ if (onBranch !== "") return { kind: "on-branch", tip };
5297
+ }
5298
+ // One pass over the history the task branch does not reach.
5299
+ const elsewhere = await search(missing ? ["--all"] : ["--all", "--not", tip]);
5300
+ if (elsewhere === null) return unknown;
5301
+ return elsewhere === "" ? { kind: "none" } : { kind: "unknown", elsewhere };
4723
5302
  } catch (e) {
4724
5303
  d.log("warn", `trailer search for ${taskId} failed`, errorText(e));
4725
- return null;
5304
+ return unknown;
4726
5305
  }
4727
5306
  }
4728
5307
 
@@ -4748,77 +5327,153 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4748
5327
  await clearBadSlot(p, taskId);
4749
5328
  }
4750
5329
 
4751
- /** R2: the blocking item of a task whose slot cannot be re-provisioned and whose work may exist (a human decides). */
4752
- async function raiseSlotLost(p: PlanRt, t: TaskNode): Promise<void> {
5330
+ /**
5331
+ * R2: the blocking item of a task whose slot cannot be re-provisioned and whose work may exist (a human decides).
5332
+ * QA-4.2-32 (#188): `elsewhere` names this attempt's commit when only another ref reaches it (null: git could not tell
5333
+ * whether it exists). #189 (QA-4.2-31): a failed re-provisioning names its reason (`slotLostCause`); `vanished`: the
5334
+ * slot was lost mid-run (`slotVanished`: its pool record is gone or no longer this task's), not found invalid at a restart.
5335
+ */
5336
+ async function raiseSlotLost(p: PlanRt, t: TaskNode, why: SlotLostWhy, vanished = false): Promise<void> {
5337
+ const lost = vanished ? "is no longer leased to it in the slot pool" : "no longer carries its marker after a restart";
4753
5338
  await raiseSafe(p, {
4754
5339
  kind: "failure",
4755
5340
  severity: "blocking",
4756
5341
  taskId: t.id,
4757
- text: `the slot of ${t.id} (${t.slot ?? "none"}) no longer carries its marker after a restart and it could not be re-provisioned from ${taskBranchName(p.planId, t.id)}; restore the task branch or abort the task`,
5342
+ text: `the slot of ${t.id} (${t.slot ?? "none"}) ${lost} and it could not be re-provisioned from ${taskBranchName(p.planId, t.id)}${slotLostCause(why)}`,
4758
5343
  options: [],
4759
5344
  });
4760
5345
  }
4761
5346
 
4762
- /** R4: `reset --hard HEAD` + `clean -fd` in the task's slot (ignored files kept); idempotent, never throws. */
5347
+ /**
5348
+ * R4: `reset --hard HEAD` + `clean -fd` in the task's slot (ignored files kept); idempotent, never throws.
5349
+ * R2-pre-3 (#187): a git exit other than 0 is a failure too, logged with the slot. The next launch into the slot never
5350
+ * relies on this reset: `launchStep` resets the slot through the pool first, and a failed pool reset skips the launch.
5351
+ */
4763
5352
  async function resetSlotContents(p: PlanRt, t: TaskNode): Promise<void> {
4764
- // pdf2-1 (b): the slot's work is saved at the task's WIP ref before the reset. QA-PDF21-3: a failed save keeps the
4765
- // slot as it is (no reset) and raises the item that names it.
4766
- if (t.slot !== null && (await snapshotTaskSlot(p, t.id, t.slot, "restart")) === "failed") {
4767
- await wipHold(p, t.id, t.slot, "its reset (restart)");
4768
- return;
4769
- }
5353
+ // #189 L7: one `index.lock` removal for the whole reset, the snapshot's included (`removeSlotIndexLock`).
5354
+ const budgetKey = t.slot === null ? null : `${p.planId}/${t.slot}`;
5355
+ const budget = { used: false };
5356
+ if (budgetKey !== null) lockBudgets.set(budgetKey, budget);
4770
5357
  try {
5358
+ // pdf2-1 (b): the slot's work is saved at the task's WIP ref before the reset. QA-PDF21-3: a failed save keeps the
5359
+ // slot as it is (no reset) and raises the item that names it.
5360
+ if (t.slot !== null && (await snapshotTaskSlot(p, t.id, t.slot, "restart")) === "failed") {
5361
+ await wipHold(p, t.id, t.slot, "its reset (restart)");
5362
+ return;
5363
+ }
4771
5364
  const lease = await slotLeaseOf(p, t);
4772
5365
  const o = { cwd: lease.path, timeoutMs: GIT_TIMEOUT_MS };
4773
- await d.git.run(["reset", "--hard", "HEAD"], o);
4774
- await d.git.run(["clean", "-fd"], o);
5366
+ // #189 (R2-pre-2 / R2-pre-3): a git killed with its server, or by the restart sweep of its verification tree, can leave
5367
+ // a stale `index.lock`: a step that fails on it (git's own wording) removes it, within the reset's one removal and
5368
+ // never in a slot a dead server's verification may still run in, and is retried (the caller holds the plan's lock,
5369
+ // as for commitTaskInSlot). R2-pre-3 (#187): a step that still exits non-zero is a failure, counted, and logged with
5370
+ // the slot once both steps ran; it is never taken as a reset.
5371
+ const failed: string[] = [];
5372
+ for (const args of [["reset", "--hard", "HEAD"], ["clean", "-fd"]]) {
5373
+ let r = await d.git.run(args, o);
5374
+ if (r.code !== 0 && INDEX_LOCK_PATTERN.test(`${r.stderr}\n${r.stdout}`) && (await removeSlotIndexLock(p, lease.slot, o))) {
5375
+ r = await d.git.run(args, o);
5376
+ }
5377
+ if (r.code === 0) continue;
5378
+ counter(p, "slot-reset-failed", { taskId: t.id, op: args[0] ?? "" });
5379
+ failed.push(`git ${args.join(" ")} exited ${String(r.code)}: ${r.stderr.trim().slice(0, 200)}`);
5380
+ }
5381
+ if (failed.length > 0) throw new Error(failed.join("; "));
4775
5382
  } catch (e) {
4776
- d.log("warn", `slot reset of ${t.id} failed`, errorText(e));
5383
+ d.log("warn", `slot reset of ${t.id} (${t.slot ?? "no slot"}) failed; its next launch resets it through the pool first`, errorText(e));
5384
+ } finally {
5385
+ if (budgetKey !== null && lockBudgets.get(budgetKey) === budget) lockBudgets.delete(budgetKey);
4777
5386
  }
4778
5387
  }
4779
5388
 
4780
- /** `completed` -> commit-and-verify (D11 finds a commit made before the crash); `verifying` -> the verifier again. */
4781
- async function reverify(p: PlanRt, taskId: TaskId, slotValid: boolean | null): Promise<void> {
5389
+ /** #189 L7: `<plan>/<slot>` -> the one `index.lock` removal of the reset running there (`resetSlotContents`). */
5390
+ const lockBudgets = new Map<string, { used: boolean }>();
5391
+
5392
+ /** Whether `slotName` may still run a dead server's verification trees (`treesAlive`). */
5393
+ function slotTreesAlive(p: PlanRt, slotName: string): boolean {
5394
+ if (p.treesAlive.has(VERIFY_TREES_ANY) || p.treesAlive.has(slotName)) return true;
5395
+ for (const a of p.treesAlive.values()) if (a.taskId !== null && own(p.writer.ledger, a.taskId)?.slot === slotName) return true;
5396
+ return false;
5397
+ }
5398
+
5399
+ /**
5400
+ * #189 L7: removes the stale `index.lock` of `slotName`: never in a slot a dead server's verification may still run in
5401
+ * (its git may hold the lock), and at most once per reset of the slot (its snapshot's removal included). Never throws.
5402
+ */
5403
+ async function removeSlotIndexLock(p: PlanRt, slotName: string, o: { cwd: string; timeoutMs: number }): Promise<boolean> {
5404
+ if (slotTreesAlive(p, slotName)) {
5405
+ d.log("warn", `the index.lock of slot ${slotName} is kept: a dead server's verification may still run there`);
5406
+ return false;
5407
+ }
5408
+ const budget = lockBudgets.get(`${p.planId}/${slotName}`);
5409
+ if (budget !== undefined) {
5410
+ if (budget.used) return false;
5411
+ budget.used = true;
5412
+ }
5413
+ return removeIndexLock(d.git, o);
5414
+ }
5415
+
5416
+ /**
5417
+ * `completed` -> commit-and-verify (D11 finds a commit made before the crash); `verifying` -> the verifier again.
5418
+ * #189 (QA-4.2-31): `held` when the task was re-provisioned but its leases are held elsewhere: it waits on its new
5419
+ * slot (`leaseHeld`) and nothing else ran; `done` otherwise. `vanished`: an invalid slot was lost mid-run
5420
+ * (`slotVanished`), which the slot-lost item says.
5421
+ */
5422
+ async function reverify(p: PlanRt, taskId: TaskId, slotValid: boolean | null, vanished = false): Promise<"held" | "done"> {
4782
5423
  const t0 = own(p.writer.ledger, taskId);
4783
5424
  const a = t0 === null ? undefined : t0.attempts[t0.attempts.length - 1];
4784
- if (t0 === null || a === undefined || t0.slot === null) return;
5425
+ if (t0 === null || a === undefined || t0.slot === null) return "done";
4785
5426
  const n = a.n;
4786
5427
  if (slotValid === false) {
4787
5428
  // QA-4.2-20: the branch tip may hold an EARLIER attempt's commit, so a `completed` task is re-provisioned only once
4788
5429
  // this attempt's own commit is known to exist. QA-4.2-13: none -> its work went with the slot: failed, retried.
4789
5430
  // git cannot tell -> the blocking item (a human decides).
5431
+ let tip: string | undefined;
5432
+ // Recovery-R1-m1 (#190): every checkpoint below ends a pipeline its attachment cut without an item or a journal row;
5433
+ // the next attachment recovers the task again.
4790
5434
  if (t0.state === "completed") {
5435
+ if (attachmentCut(p)) return "done";
4791
5436
  const committed = await attemptCommitted(p, taskId, a);
4792
- if (committed === false) {
5437
+ if (attachmentCut(p)) return "done";
5438
+ if (committed.kind === "none") {
4793
5439
  await slotLostBeforeCommit(p, taskId, n);
4794
- return;
5440
+ return "done";
4795
5441
  }
4796
- if (committed === null) {
4797
- await raiseSlotLost(p, t0);
4798
- return;
5442
+ if (committed.kind === "unknown") {
5443
+ await raiseSlotLost(p, t0, { elsewhere: committed.elsewhere }, vanished);
5444
+ return "done";
4799
5445
  }
5446
+ tip = committed.tip; // QA-4.2-32 (#188): re-provisioned from the very tip whose history carries the commit
4800
5447
  }
4801
- if (!(await reprovisionSlot(p, taskId))) {
4802
- await raiseSlotLost(p, t0);
4803
- return;
5448
+ if (attachmentCut(p)) return "done";
5449
+ const r = await reprovisionSlot(p, taskId, tip);
5450
+ // #189 (QA-4.2-31): held on its new slot (its hold item raised): the caller re-parks it (or `resumeHeldTask` resumes
5451
+ // it).
5452
+ if (r.kind === "held") return "held";
5453
+ if (r.kind === "failed") {
5454
+ if (attachmentCut(p)) return "done"; // undone by the cut, not a lost slot
5455
+ await raiseSlotLost(p, t0, r, vanished);
5456
+ return "done";
4804
5457
  }
4805
5458
  }
5459
+ if (attachmentCut(p)) return "done";
4806
5460
  // Re-read: a re-provisioned task has a new slot.
4807
5461
  const t = own(p.writer.ledger, taskId);
4808
- if (t === null || t.slot === null) return;
5462
+ if (t === null || t.slot === null) return "done";
4809
5463
  if (t.state === "completed") {
4810
5464
  await commitAndVerify(p, taskId, n);
4811
- return;
5465
+ return "done";
4812
5466
  }
4813
- if (t.state !== "verifying") return;
5467
+ if (t.state !== "verifying") return "done";
4814
5468
  let lease: SlotLease;
4815
5469
  try {
4816
5470
  lease = await slotLeaseOf(p, t);
4817
5471
  } catch (e) {
4818
5472
  d.log("warn", `reverify of ${taskId}: slot unavailable`, errorText(e));
4819
- return;
5473
+ return "done";
4820
5474
  }
4821
5475
  await verifyAttempt(p, taskId, n, lease);
5476
+ return "done";
4822
5477
  }
4823
5478
 
4824
5479
  /** Step 7: `qa-running` with no QA task in flight -> the latest done QA task's report; `awaiting-qa` -> onAwaitingQa. */
@@ -5062,10 +5717,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5062
5717
  severity: "blocking",
5063
5718
  taskId: f.taskId,
5064
5719
  // QA-4.2-26: the item says the task is held and what ends the hold.
5065
- text:
5066
- `could not re-take the leases of ${f.taskId} after restart; held by ${f.holders.map((h) => h.holderID).join(", ")}. ` +
5067
- `${f.taskId} is held (no adopt, commit, verify or enqueue) until its leases are free: finish or abort the holder ` +
5068
- `(or abort ${f.taskId}); it resumes on its own once the leases are released`,
5720
+ text: leaseHoldText(f.taskId, f.holders, "after restart"),
5069
5721
  options: [],
5070
5722
  });
5071
5723
  } catch (e) {
@@ -5074,6 +5726,16 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5074
5726
  }
5075
5727
  }
5076
5728
 
5729
+ /**
5730
+ * #189 (QA-4.2-31): the hold item of a task R2 re-provisioned onto a slot whose leases another holder has, unless an
5731
+ * item announcing its hold is still open (the restart's lease rebuild raises one when the old tree still existed).
5732
+ */
5733
+ async function raiseLeaseHold(p: PlanRt, taskId: TaskId, holders: readonly LeaseHolderInfo[], where: string): Promise<void> {
5734
+ const prefix = leaseHoldPrefix(taskId);
5735
+ if (p.writer.ledger.inbox.some((x) => x.answer === null && x.taskId === taskId && x.text.startsWith(prefix))) return;
5736
+ await raiseSafe(p, { kind: "failure", severity: "blocking", taskId, text: leaseHoldText(taskId, holders, where), options: [] });
5737
+ }
5738
+
5077
5739
  /** R1a: a rejected interrupt that still means "nothing runs any more" (not found / not busy) is a success. */
5078
5740
  function interruptSettled(e: unknown): boolean {
5079
5741
  return /not[-_ ]?found|not[-_ ]?busy|no such session/i.test(`${errorCode(e) ?? ""} ${errorText(e)}`);
@@ -5087,7 +5749,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5087
5749
  p.attachment.abort();
5088
5750
  dropRecoveredWork(p, false);
5089
5751
  // An adopt closes this writer only after old-attachment pipelines have observed their cut.
5090
- await Promise.allSettled([...p.attachmentWork]);
5752
+ await waitForAttachmentWork(p);
5091
5753
  p.offSlotRelease?.();
5092
5754
  p.offSlotRelease = null;
5093
5755
  observe(p, "detach");
@@ -5119,6 +5781,46 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5119
5781
  await p.writer.close();
5120
5782
  }
5121
5783
 
5784
+ /**
5785
+ * Recovery-R1-m1 (#190): `closePlan`'s wait for the cut attachment's pipelines. It has no hard limit (a pipeline mid-commit
5786
+ * or mid-provisioning must finish before the writer closes; each checks the cut at its next checkpoint). A wait longer than
5787
+ * CLOSE_WAIT_WARN_MS on the injected clock logs one warning naming what is still pending and records `close-wait-slow`.
5788
+ */
5789
+ async function waitForAttachmentWork(p: PlanRt): Promise<void> {
5790
+ const work = [...p.attachmentWork.keys()];
5791
+ if (work.length === 0) return;
5792
+ const started = d.clock.now();
5793
+ const h = d.clock.setTimer(CLOSE_WAIT_WARN_MS, () => {
5794
+ const pending = [...p.attachmentWork.values()].sort();
5795
+ if (pending.length === 0) return;
5796
+ const waitedMs = d.clock.now() - started;
5797
+ d.log("warn", `closing plan ${p.planId} still waits after ${waitedMs} ms for: ${pending.join(", ")}`);
5798
+ observe(p, "close-wait-slow", () => ({ waitedMs, pending }));
5799
+ });
5800
+ try {
5801
+ await Promise.allSettled(work);
5802
+ } finally {
5803
+ d.clock.clearTimer(h);
5804
+ }
5805
+ }
5806
+
5807
+ /** #190: `dispose`'s wait for the starts in flight, bounded by QUEUE_DISPOSE_MS on the injected clock (one warning). */
5808
+ async function waitForStarts(runs: ReadonlyArray<Promise<void>>): Promise<void> {
5809
+ const fire: { timeout: () => void } = { timeout: () => undefined };
5810
+ const timeout = new Promise<"timeout">((resolve) => {
5811
+ fire.timeout = () => resolve("timeout");
5812
+ });
5813
+ const h = d.clock.setTimer(QUEUE_DISPOSE_MS, () => fire.timeout());
5814
+ try {
5815
+ const done = Promise.all(runs).then(() => "started" as const);
5816
+ if ((await Promise.race([done, timeout])) === "timeout") {
5817
+ d.log("warn", `start did not finish in ${QUEUE_DISPOSE_MS} ms; disposing without it (it attaches nothing now)`);
5818
+ }
5819
+ } finally {
5820
+ d.clock.clearTimer(h);
5821
+ }
5822
+ }
5823
+
5122
5824
  /** QA-4.2-3: `queue.dispose()`, bounded by QUEUE_DISPOSE_MS (a hung queue is logged, never blocks the close). */
5123
5825
  async function disposeQueue(p: PlanRt): Promise<void> {
5124
5826
  const fire: { timeout: () => void } = { timeout: () => undefined };
@@ -5145,7 +5847,31 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5145
5847
  const ledger = await d.store.read(planId);
5146
5848
  if (isForeign(ledger.repo.toplevel)) return attach(readOnlyWriter(ledger), true, undefined, { foreign: true });
5147
5849
  const writer = await d.store.open(planId, d.holder(sessionID));
5148
- return attach(writer, true);
5850
+ return attachOpened(writer);
5851
+ }
5852
+
5853
+ /** #190: an action that would open, take over or create a ledger refuses once dispose began, before any store change. */
5854
+ function refuseDisposed(): void {
5855
+ if (disposed) throw new ExecutorError("E_DISPOSED", "the runtime is disposing; no plan is opened or created");
5856
+ }
5857
+
5858
+ /**
5859
+ * #190: `attach` of a writer the caller opened or created; one that never registered (a dispose cut its `build`) is closed
5860
+ * here. `existing: false` for a just-created ledger (compile).
5861
+ */
5862
+ async function attachOpened(writer: LedgerWriter, o: { existing?: boolean; onRegistered?: () => void } = {}): Promise<PlanRt> {
5863
+ try {
5864
+ return await attach(writer, o.existing ?? true, o.onRegistered);
5865
+ } catch (err) {
5866
+ if (plans.get(writer.planId)?.writer !== writer) {
5867
+ try {
5868
+ await writer.close();
5869
+ } catch (e) {
5870
+ d.log("warn", `ledger of ${writer.planId} could not be closed`, errorText(e));
5871
+ }
5872
+ }
5873
+ throw err;
5874
+ }
5149
5875
  }
5150
5876
 
5151
5877
  /**
@@ -5161,7 +5887,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5161
5887
  return;
5162
5888
  }
5163
5889
  const writer = await d.store.open(planId, d.holder(orchestrator));
5164
- await attach(writer, true, onRegistered);
5890
+ await attachOpened(writer, { onRegistered });
5165
5891
  d.log("warn", `adopt of ${planId} failed; the plan is attached again for ${orchestrator}`);
5166
5892
  } catch (e) {
5167
5893
  d.log("error", `plan ${planId} could not be attached again after a failed adopt`, errorText(e));
@@ -5443,8 +6169,74 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5443
6169
  if (!ok) throw new ExecutorError("E_PLAN_STATE", `plan ${p.planId} is ${p.writer.ledger.status}`, p.writer.ledger.status);
5444
6170
  }
5445
6171
 
6172
+ /** `start()`'s work: the host feed, recovery and the attachment of every running or paused plan of the store. */
6173
+ async function startPlans(): Promise<void> {
6174
+ // QA-3.1-1 (memo M46): the runtime feeds itself from the host's session events: provider of each step, capacity
6175
+ // signals, the orchestrator's idle flag and the end of a late-adopted child (L12) all come from here.
6176
+ if (offEvents === null) offEvents = d.hosts.onEvent(onHostEvent);
6177
+ // QA-4.2-17/-21: a running or paused plan of another repository (its own toplevel, never its absence from the
6178
+ // recover() report) is attached passively.
6179
+ if (d.recovery !== null) {
6180
+ try {
6181
+ // L2: recover() reports this repository's running or paused plans. It no longer limits takeover (QA-4.2-33,
6182
+ // #189): any stale plan of this repository is taken over below, and one `reconcile` cannot classify is paused.
6183
+ for (const r of await d.recovery.recover()) {
6184
+ // Nit: the engine's report carries full feeds; the plan's first recoverPlan reuses it (one reconcile, not two).
6185
+ const feeds: ReconcileFeed[] = [];
6186
+ for (const a of r.actions) if (isFeed(a)) feeds.push(a);
6187
+ if (d.recovery.reconcile !== undefined && feeds.length === r.actions.length) recoverReports.set(r.planId, feeds);
6188
+ }
6189
+ } catch (e) {
6190
+ d.log("error", "recovery failed", errorText(e));
6191
+ }
6192
+ }
6193
+ // QA-3.1-19: deterministic single-plan pick: a running plan before a paused one, then by plan id; the others attach
6194
+ // passively (refused, woken once) instead of not at all.
6195
+ const rank = (s: LedgerStatus): number => (s === "running" ? 0 : 1);
6196
+ const entries = disposed ? [] : (await d.store.list())
6197
+ .filter((e) => e.status === "running" || e.status === "paused")
6198
+ .sort((a, b) => rank(a.status) - rank(b.status) || (a.planId < b.planId ? -1 : a.planId > b.planId ? 1 : 0));
6199
+ for (const e of entries) {
6200
+ // QA-5.1-33: a dispose that lands while start() reads the store attaches nothing more (dispose closed what it saw).
6201
+ if (disposed) break;
6202
+ if (plans.has(e.planId)) continue;
6203
+ try {
6204
+ const ledger = await d.store.read(e.planId);
6205
+ if (disposed) break;
6206
+ if (isForeign(ledger.repo.toplevel)) {
6207
+ await attach(readOnlyWriter(ledger), true, undefined, { foreign: true });
6208
+ continue;
6209
+ }
6210
+ const holder = d.holder(e.orchestratorSessionID);
6211
+ let writer: LedgerWriter;
6212
+ try {
6213
+ writer = await d.store.open(e.planId, holder);
6214
+ } catch (err) {
6215
+ // L2: `open` never takes over; a stale holder of an eligible plan is (the store refuses a live one with
6216
+ // E_LOCK_HELD: skipped and logged below, nothing interrupted). Plans of another toplevel are never taken over.
6217
+ // QA-4.2-33 (#189): eligible is this repository's plan (foreign ones attached above), whether or not the
6218
+ // recover() report carried it; the attachment reconciles a plan the report missed (QA-4.2-21).
6219
+ if (errorCode(err) !== "E_LOCK_HELD" || d.recovery === null) throw err;
6220
+ writer = await d.store.takeover(e.planId, holder, RECOVER_TAKEOVER_REASON);
6221
+ }
6222
+ if (disposed) {
6223
+ // QA-5.1-33: opened while dispose ran: closed, never attached (the next process recovers the plan).
6224
+ await writer.close();
6225
+ break;
6226
+ }
6227
+ // A same-repo plan the report missed still attaches actively and recoverPlan reconciles it.
6228
+ await attachOpened(writer);
6229
+ } catch (err) {
6230
+ d.log("warn", `plan ${e.planId} not attached`, errorText(err));
6231
+ }
6232
+ }
6233
+ // A report no activation consumed (a refused or failed attach) is stale for any later activation.
6234
+ recoverReports.clear();
6235
+ }
6236
+
5446
6237
  const handle: ExecutorRuntimeHandle = {
5447
6238
  async compile(i) {
6239
+ refuseDisposed();
5448
6240
  const r = await d.compiler.compile(i.path, {
5449
6241
  ...(i.phases === undefined ? {} : { phases: i.phases }),
5450
6242
  ...(i.doneBefore === undefined ? {} : { doneBefore: i.doneBefore }),
@@ -5453,8 +6245,16 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5453
6245
  now: d.clock.iso(),
5454
6246
  });
5455
6247
  if (isForeign(r.draft.repo.toplevel)) throw new ExecutorError("E_INVALID_INPUT", "the plan belongs to another repository");
6248
+ refuseDisposed();
5456
6249
  const writer = await d.store.create(r.draft, d.holder(i.sessionID));
5457
- await attach(writer, false);
6250
+ const planId = r.draft.planId;
6251
+ d.forgetSlots?.(planId);
6252
+ collected.delete(planId);
6253
+ const timer = collectionTimers.get(planId);
6254
+ if (timer !== undefined) d.clock.clearTimer(timer);
6255
+ collectionTimers.delete(planId);
6256
+ collectionDelays.delete(planId);
6257
+ await attachOpened(writer, { existing: false });
5458
6258
  return { planId: r.draft.planId, summary: r.summary, residuePrompt: r.residueRequest?.prompt ?? null };
5459
6259
  },
5460
6260
 
@@ -5646,6 +6446,13 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5646
6446
  const other = reserve(planId);
5647
6447
  if (other !== null) await refuseSecondPlan(p.writer, other);
5648
6448
  }
6449
+ // #189 R2-pre-2 (L6): a running plan whose only open matter is a dead server's verification trees: the resume sweeps
6450
+ // again and nothing else (no streak, backoff, phase or queue reset); what the sweep proves gone is admitted.
6451
+ if (!promote && !p.unreconciled && p.writer.ledger.status === "running" && p.integrationResumed && p.treesAlive.size > 0) {
6452
+ await sweepVerifyTrees(p);
6453
+ schedule(p);
6454
+ return;
6455
+ }
5649
6456
  // QA-4.2-6: a running plan whose integration resume failed (or halted) is resumed again by the user's `resume`.
5650
6457
  const retryOnly = !promote && p.writer.ledger.status === "running" && !p.integrationResumed;
5651
6458
  try {
@@ -5654,16 +6461,22 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5654
6461
  p.passive = false;
5655
6462
  observe(p, "promote");
5656
6463
  await activate(p, true);
5657
- } else if (!p.integrationResumed) {
6464
+ } else if (p.unreconciled) {
6465
+ // #189: the activation whose `reconcile` threw runs again (leases, recovery, integration resume).
6466
+ await activate(p, true);
6467
+ if (p.unreconciled) return;
6468
+ } else {
5658
6469
  // §9: a halted (or failed) integration resume is retried by the user's resume.
5659
- await resumeIntegration(p);
6470
+ if (!p.integrationResumed) await resumeIntegration(p);
6471
+ // #189 R2-pre-2: what the sweep proves gone now releases its parked recovered work (the tick below admits it).
6472
+ if (p.treesAlive.size > 0) await sweepVerifyTrees(p);
5660
6473
  }
5661
6474
  } finally {
5662
6475
  if (promote) unreserve(planId);
5663
6476
  }
5664
6477
  // A resume is the user's answer to the streak pauses: they start over (QA-3.1-4, QA-3.1-6, QA-3.1-22).
5665
6478
  p.preConfirmLosses = 0;
5666
- p.preConfirmCapture = null;
6479
+ p.preConfirmCaptures.clear();
5667
6480
  p.skipStreak = 0;
5668
6481
  p.provisionFails = 0;
5669
6482
  p.provisionRaised = false;
@@ -5734,9 +6547,12 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5734
6547
  ev.push({ type: "status-changed", from: cur.status, to: "aborted", reason: "user-abort" });
5735
6548
  return ev;
5736
6549
  });
6550
+ // Phase-6.1 N2 (#190): the cut verifications keep their plan-task records for a next attachment; an aborted plan has
6551
+ // none, so the closed attempts are forgotten now, before any slot release below can throw or wait.
6552
+ await forgetClosed(p);
5737
6553
  closeIdle(p);
5738
6554
  unpinPlan(p);
5739
- const attachmentWork = [...p.attachmentWork];
6555
+ const attachmentWork = [...p.attachmentWork.keys()];
5740
6556
  const attachmentsSettled = Promise.allSettled(attachmentWork);
5741
6557
  // QA-4.2-23: the abort closed every attempt, the adopted children's bindings go with them.
5742
6558
  for (const id of [...p.rebound.keys()]) evictRebound(p, id, null);
@@ -5825,6 +6641,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5825
6641
  },
5826
6642
 
5827
6643
  async adopt(planId, sessionID) {
6644
+ refuseDisposed();
5828
6645
  const recovery = d.recovery;
5829
6646
  if (recovery === null) throw new ExecutorError("E_PLAN_STATE", "recovery is not available", planId);
5830
6647
  // QA-3.1-19 / QA-4.2-25: every cheap refusal (state, foreign repository, single-plan rule, with the slot reserved,
@@ -5848,6 +6665,11 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5848
6665
  st,
5849
6666
  );
5850
6667
  }
6668
+ // pdf2-1 minor-5 (#189): a finished plan is never adopted (`recovery.adopt` refuses it too); refused before its
6669
+ // attachment is closed, so an abort's background cleanup (stops, saves, releases, collection) is not cut.
6670
+ if (st === "completed" || st === "aborted") {
6671
+ throw new ExecutorError("E_PLAN_STATE", `plan ${planId} is ${st}`, { planId, status: st });
6672
+ }
5851
6673
  // QA-4.2-21: a plan of another repository is never adopted here; its passive attachment stays as it is.
5852
6674
  if (seen !== null && isForeign(seen.repo.toplevel)) {
5853
6675
  throw new ExecutorError(
@@ -5894,7 +6716,8 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5894
6716
  throw new ExecutorError("E_PLAN_STATE", `plan ${planId} belongs to another repository; its attachment is read-only`, { planId });
5895
6717
  }
5896
6718
  // L3: the reopened local ledger is reconciled on activation.
5897
- recoverable.add(planId);
6719
+ // #190: a dispose that landed meanwhile opens and takes over nothing.
6720
+ refuseDisposed();
5898
6721
  let writer: LedgerWriter;
5899
6722
  try {
5900
6723
  writer = await d.store.open(planId, d.holder(sessionID));
@@ -5903,11 +6726,11 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5903
6726
  writer = await d.store.takeover(planId, d.holder(sessionID), "adopt");
5904
6727
  }
5905
6728
  // The gate opens once the new attachment is registered (before its recovery runs: recovery takes task mutexes).
5906
- await attach(writer, true, openGate);
6729
+ await attachOpened(writer, { onRegistered: openGate });
5907
6730
  } catch (e) {
5908
6731
  // QA-4.2-25: the old attachment is closed and the adopt failed: the plan is attached again under its own
5909
- // orchestrator, so it is not stranded and the ends waiting on the gate are processed.
5910
- if (oldOrchestrator !== null && !plans.has(planId)) await reattachAfterFailedAdopt(planId, oldOrchestrator, openGate);
6732
+ // orchestrator, so it is not stranded and the ends waiting on the gate are processed (#190: not once disposing).
6733
+ if (oldOrchestrator !== null && !plans.has(planId) && !disposed) await reattachAfterFailedAdopt(planId, oldOrchestrator, openGate);
5911
6734
  throw e;
5912
6735
  }
5913
6736
  } finally {
@@ -5917,6 +6740,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5917
6740
  },
5918
6741
 
5919
6742
  async gc() {
6743
+ refuseDisposed();
5920
6744
  // A restarted runtime has not attached terminal plans. Open them before entering the pool's gc so failures
5921
6745
  // propagate as E_PLAN_STATE (and no pool mutex is held while a save consults its markers).
5922
6746
  for (const entry of await d.store.list()) {
@@ -5924,7 +6748,8 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5924
6748
  if (plans.has(entry.planId)) continue;
5925
6749
  const ledger = await d.store.read(entry.planId);
5926
6750
  if (isForeign(ledger.repo.toplevel)) continue;
5927
- await attach(await d.store.open(entry.planId, d.holder(ledger.orchestrator.sessionID)));
6751
+ refuseDisposed();
6752
+ await attachOpened(await d.store.open(entry.planId, d.holder(ledger.orchestrator.sessionID)));
5928
6753
  }
5929
6754
  // QA-PDF21-15: a finished plan's slot whose work could not be saved is saved again first; a save that fails again
5930
6755
  // refuses the gc (its worktree would be deleted with the work).
@@ -5986,15 +6811,40 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5986
6811
  // before anything is removed (its worktree would go with the work).
5987
6812
  await refuseUnsaved(p, "purge");
5988
6813
  const toplevel = p.writer.ledger.repo.toplevel;
6814
+ const slotsDir = planSlotsDirOf(p);
6815
+ const ownSlots = purgeSlotsDirs(p.writer.ledger.config.slotsDir, toplevel, planId);
5989
6816
  await closePlan(p);
5990
6817
  // QA-5.1-11: the full gc runs before the ledger is removed; a pool that collection already closed still answers it
5991
6818
  // through a gc-only handle (create.ts PlanSlotPools), so a slot a partial gc could not remove is retried here.
5992
- const purged = async (id: PlanId): Promise<boolean | null> => (id === planId ? true : null);
6819
+ // #202: any other plan follows the manual gc's rule: a plan whose ledger exists (paused, too) keeps its slots
6820
+ // whatever their marker's age; only a plan with no ledger is left to the pool's age rule (`null`).
6821
+ const purged = async (id: PlanId): Promise<boolean | null> => {
6822
+ if (id === planId) return true;
6823
+ try {
6824
+ await d.store.read(id);
6825
+ return false;
6826
+ } catch (e) {
6827
+ if (errorCode(e) === "E_LEDGER_NOT_FOUND") return null;
6828
+ throw e;
6829
+ }
6830
+ };
5993
6831
  // QA-5.1-22: an invalid slotsDir with slot markers refuses here, before any ref or the ledger is removed.
5994
6832
  const report = d.purgeSlots !== undefined ? await d.purgeSlots(planId, purged) : await slotsFor(planId).gc(purged);
5995
- if (report.reported.some((note) => /uncommitted changes|unsaved work/.test(note))) {
6833
+ // #202: only unsaved work of this plan's slots refuses; a note naming a slot outside its slots directory does not.
6834
+ if (report.reported.some((note) => /uncommitted changes|unsaved work/.test(note) && !foreignSlotNote(note, ownSlots))) {
5996
6835
  throw new ExecutorError("E_PLAN_STATE", `plan ${planId}: pool refused unsaved work; purge refused`, { planId, reported: report.reported });
5997
6836
  }
6837
+ // QA-5.1-28 (#187): a slot of this plan the gc reported and did not remove (EBUSY, lock mismatch, ...) keeps the refs
6838
+ // and the ledger, so the slot can still be found, saved and collected by the next purge.
6839
+ const left = slotsLeftBehind(slotsDir, report);
6840
+ if (left.length > 0) {
6841
+ throw new ExecutorError(
6842
+ "E_PLAN_STATE",
6843
+ `plan ${planId}: the gc could not remove ${left.length} slot(s): ${left.slice(0, 5).join("; ")}${left.length > 5 ? "; …" : ""}; `
6844
+ + `purge refused, the refs and the ledger are kept. ${purgeWayOut(left)}`,
6845
+ { planId, reported: left },
6846
+ );
6847
+ }
5998
6848
  for (const ns of ["heads", "tags"]) {
5999
6849
  const prefix = `refs/${ns}/omr/${planId}/`;
6000
6850
  const r = await d.git.run(["for-each-ref", "--format=%(refname)", prefix], { cwd: toplevel, timeoutMs: GIT_TIMEOUT_MS });
@@ -6003,6 +6853,8 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
6003
6853
  await d.git.run(["update-ref", "-d", ref], { cwd: toplevel, timeoutMs: GIT_TIMEOUT_MS });
6004
6854
  }
6005
6855
  }
6856
+ // #189 R2-pre-2: the plan's verification process journals go with it (never rejects).
6857
+ await d.verifyTrees?.purge(planId);
6006
6858
  await d.store.remove(planId);
6007
6859
  },
6008
6860
 
@@ -6049,62 +6901,23 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
6049
6901
  return null;
6050
6902
  },
6051
6903
 
6052
- async start() {
6053
- // QA-3.1-1 (memo M46): the runtime feeds itself from the host's session events: provider of each step, capacity
6054
- // signals, the orchestrator's idle flag and the end of a late-adopted child (L12) all come from here.
6055
- if (offEvents === null && !disposed) offEvents = d.hosts.onEvent(onHostEvent);
6056
- // QA-4.2-17/-21: a running or paused plan of another repository (its own toplevel, never its absence from the
6057
- // recover() report) is attached passively.
6058
- if (d.recovery !== null) {
6059
- try {
6060
- // L2: only the plans recover() reports (same toplevel, running or paused) may be taken over and reconciled.
6061
- for (const r of await d.recovery.recover()) {
6062
- recoverable.add(r.planId);
6063
- // Nit: the engine's report carries full feeds; the plan's first recoverPlan reuses it (one reconcile, not two).
6064
- const feeds: ReconcileFeed[] = [];
6065
- for (const a of r.actions) if (isFeed(a)) feeds.push(a);
6066
- if (d.recovery.reconcile !== undefined && feeds.length === r.actions.length) recoverReports.set(r.planId, feeds);
6067
- }
6068
- } catch (e) {
6069
- d.log("error", "recovery failed", errorText(e));
6070
- }
6071
- }
6072
- // QA-3.1-19: deterministic single-plan pick: a running plan before a paused one, then by plan id; the others attach
6073
- // passively (refused, woken once) instead of not at all.
6074
- const rank = (s: LedgerStatus): number => (s === "running" ? 0 : 1);
6075
- const entries = (await d.store.list())
6076
- .filter((e) => e.status === "running" || e.status === "paused")
6077
- .sort((a, b) => rank(a.status) - rank(b.status) || (a.planId < b.planId ? -1 : a.planId > b.planId ? 1 : 0));
6078
- for (const e of entries) {
6079
- if (plans.has(e.planId)) continue;
6080
- try {
6081
- const ledger = await d.store.read(e.planId);
6082
- if (isForeign(ledger.repo.toplevel)) {
6083
- await attach(readOnlyWriter(ledger), true, undefined, { foreign: true });
6084
- continue;
6085
- }
6086
- const holder = d.holder(e.orchestratorSessionID);
6087
- let writer: LedgerWriter;
6088
- try {
6089
- writer = await d.store.open(e.planId, holder);
6090
- } catch (err) {
6091
- // L2: `open` never takes over; a stale holder of an eligible plan is (the store refuses a live one with
6092
- // E_LOCK_HELD: skipped and logged below, nothing interrupted). Plans of another toplevel are never taken over.
6093
- if (errorCode(err) !== "E_LOCK_HELD" || !recoverable.has(e.planId)) throw err;
6094
- writer = await d.store.takeover(e.planId, holder, RECOVER_TAKEOVER_REASON);
6095
- }
6096
- // A same-repo plan the report missed still attaches actively and recoverPlan reconciles it.
6097
- await attach(writer, true);
6098
- } catch (err) {
6099
- d.log("warn", `plan ${e.planId} not attached`, errorText(err));
6100
- }
6101
- }
6102
- // A report no activation consumed (a refused or failed attach) is stale for any later activation.
6103
- recoverReports.clear();
6904
+ start() {
6905
+ // QA-5.1-33: a disposed runtime starts nothing: no host feed, no recovery, no attachment.
6906
+ if (disposed) return Promise.resolve();
6907
+ // #190: dispose waits for an in-flight start (it can still register a plan, which dispose must close).
6908
+ const run = startPlans();
6909
+ const tracked = run.then(() => undefined, () => undefined);
6910
+ startRuns.add(tracked);
6911
+ void tracked.then(() => {
6912
+ startRuns.delete(tracked);
6913
+ });
6914
+ return run;
6104
6915
  },
6105
6916
 
6106
6917
  async dispose() {
6107
6918
  disposed = true;
6919
+ // #189 re-review 1: the verification journals' heartbeat stops with the runtime; the journals stay for the next sweep.
6920
+ d.verifyTrees?.dispose?.();
6108
6921
  // QA-5.1-4: the verifier is cut FIRST (gate deadlines, grader sessions, backoff sleeps), so no pending verify keeps the
6109
6922
  // wait for running work below (and the process claim) for the length of a gate. Its synchronous part runs now; it is
6110
6923
  // awaited after the plans are detached. A cut verdict is never journaled (`verifyAttempt`); QA-5.1-21: a real verdict
@@ -6165,10 +6978,16 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
6165
6978
  } catch (e) {
6166
6979
  d.log("warn", "launcher dispose failed", errorText(e));
6167
6980
  }
6981
+ // #190: the starts in flight too: a plan one still registers is closed below, never left attached after dispose. The
6982
+ // wait is bounded (a host call that never answers during recovery must not hold the claim); a start that ends later
6983
+ // registers nothing (`build`) and closes the writer it opened (`attachOpened`).
6984
+ let startWait: Promise<void> | null = startRuns.size === 0 ? null : waitForStarts([...startRuns]);
6168
6985
  for (;;) {
6169
6986
  const work = [...pending].filter((pr) => !childWaits.has(pr));
6987
+ if (startWait !== null) work.push(startWait);
6170
6988
  if (work.length === 0) break;
6171
6989
  await Promise.allSettled(work);
6990
+ startWait = null; // settled: the starts ended, or the bound gave up on them
6172
6991
  }
6173
6992
  for (const p of [...plans.values()]) {
6174
6993
  try {