opencode-model-router 2.10.0 → 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 (47) hide show
  1. package/CHANGELOG.md +306 -0
  2. package/README.md +3 -2
  3. package/package.json +8 -1
  4. package/src/compat/background.ts +5 -0
  5. package/src/compat/session-lookup.ts +21 -0
  6. package/src/compat/v2-hooks.ts +256 -88
  7. package/src/compat/v2-observations.ts +1 -0
  8. package/src/compat/v2-vocabulary.ts +14 -0
  9. package/src/executor/create.ts +3 -0
  10. package/src/executor/git.ts +110 -26
  11. package/src/executor/integrate/checks.ts +29 -11
  12. package/src/executor/integrate/queue.ts +95 -13
  13. package/src/executor/ledger.ts +16 -12
  14. package/src/executor/lfs-restore.ts +492 -0
  15. package/src/executor/paths.ts +7 -2
  16. package/src/executor/recovery.ts +2 -1
  17. package/src/executor/runtime.ts +1010 -226
  18. package/src/executor/slots/pool.ts +120 -19
  19. package/src/executor/slots/provision.ts +111 -23
  20. package/src/executor/slots/root.ts +81 -0
  21. package/src/executor/types.ts +28 -2
  22. package/src/executor/unattended.ts +6 -1
  23. package/src/executor/verify-trees.ts +507 -0
  24. package/src/guard/enforce.ts +2 -1
  25. package/src/guard/fingerprint.ts +9 -0
  26. package/src/guard/guards.ts +7 -1
  27. package/src/index.ts +107 -27
  28. package/src/router/answer-dedup.ts +198 -0
  29. package/src/router/common-dir.ts +241 -0
  30. package/src/router/config.ts +71 -12
  31. package/src/router/diff-handles.ts +322 -0
  32. package/src/router/diff-summary.ts +318 -0
  33. package/src/router/git-metadata-guard.ts +144 -7
  34. package/src/router/git-tools.ts +930 -73
  35. package/src/router/role-agents.ts +100 -36
  36. package/src/router/run-summary.ts +253 -0
  37. package/src/router/run-tools.ts +145 -23
  38. package/src/router/sessions.ts +14 -1
  39. package/src/routing/classify/rules.ts +93 -14
  40. package/src/routing/wire/hint.ts +9 -2
  41. package/src/v2.ts +3 -1
  42. package/src/verify/exec.ts +454 -2
  43. package/src/verify/plan-task.ts +86 -26
  44. package/src/verify/runner.ts +14 -6
  45. package/src/verify/tree.ts +5 -1
  46. package/src/verify/types.ts +44 -0
  47. package/src/verify/wiring.ts +87 -10
@@ -23,6 +23,7 @@ import {
23
23
  phaseTagName,
24
24
  planRefPrefix,
25
25
  restoreSlotWork,
26
+ STALE_INDEX_LOCK_PATTERN,
26
27
  sanitizeGitDiagnostic,
27
28
  snapshotSlotWork,
28
29
  slotCommitIdentityArgs,
@@ -35,6 +36,8 @@ import {
35
36
  import { dependentPhases } from "./integrate/queue";
36
37
  import type { PlanRoleBindings } from "./launch";
37
38
  import type { ProcessIdentity } from "./process-identity";
39
+ import type { ProcessJournal } from "../verify/types";
40
+ import type { AliveVerifyTree, VerifyTrees, VerifyTreeSweep } from "./verify-trees";
38
41
  import { createQaLoop } from "./qa-loop";
39
42
  import {
40
43
  RECOVER_TAKEOVER_REASON,
@@ -68,6 +71,7 @@ import {
68
71
  type CapacityView,
69
72
  type ChildEnd,
70
73
  type Clock,
74
+ type ContextRef,
71
75
  type Edge,
72
76
  type ExecutorConfig,
73
77
  type ExecutorEvent,
@@ -337,8 +341,8 @@ function gitDiagnostic(e: unknown): { message: string; gitExitCode: string; stde
337
341
  return { message: `${message}${gitExitCode === "unknown" || message.includes("exit ") ? "" : ` (git exit ${gitExitCode})`}${stderr === "" || message.includes(stderr) ? "" : `; stderr: ${stderr}`}`, gitExitCode, stderr };
338
342
  }
339
343
 
340
- /** A git step that failed on a leftover `index.lock` (a git killed mid-commit, D11). */
341
- 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;
342
346
 
343
347
  /** D11: the trailer line of attempt `n` (nonce `nonce`) of `taskId`. */
344
348
  export function attemptTrailer(planId: PlanId, taskId: TaskId, n: number, nonce: string): string {
@@ -406,6 +410,46 @@ export async function commitTaskInSlot(
406
410
  return { changed: true, commit: head };
407
411
  }
408
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
+
409
453
  // ---- runtime
410
454
 
411
455
  export interface PlanCollaborators {
@@ -422,6 +466,11 @@ export interface PlanTaskContext {
422
466
  orchestratorSessionID: string;
423
467
  /** An attachment change cuts old work without disposing the process-wide verifier. */
424
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;
425
474
  }
426
475
 
427
476
  /**
@@ -457,6 +506,13 @@ export interface RuntimeDeps {
457
506
  store: LedgerStore;
458
507
  /** Executor storage root; metadata-less slot directories are preserved here, outside the pool. */
459
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;
460
516
  compiler: PlanCompiler;
461
517
  slots: SlotPool;
462
518
  /** Per-plan pools; legacy callers keep using `slots`. */
@@ -658,8 +714,11 @@ interface RecoveredWork {
658
714
  readonly n: number;
659
715
  readonly nonce: string;
660
716
  readonly state: TaskState;
661
- 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 };
662
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;
663
722
  }
664
723
 
665
724
  interface PlanRt {
@@ -701,10 +760,12 @@ interface PlanRt {
701
760
  /** Consecutive pre-confirmation losses (row 11, QA-3.1-4); reset on a confirmed launch and on resume. */
702
761
  preConfirmLosses: number;
703
762
  /**
704
- * Capture (router call) of the last counted pre-confirmation loss and the tasks lost under it (QA-3.1-17): parallel
705
- * 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.
706
767
  */
707
- preConfirmCapture: { key: string; tasks: Set<TaskId> } | null;
768
+ preConfirmCaptures: Map<string, Set<TaskId>>;
708
769
  /** Consecutive RouteResolver failures (QA-3.1-22); one inbox item at ROUTE_STREAK, reset by a tick that resolved cleanly. */
709
770
  routeFails: number;
710
771
  routeRaised: boolean;
@@ -717,11 +778,25 @@ interface PlanRt {
717
778
  recovering: boolean;
718
779
  /** Attachment-local identities; waiting for context retains the task's slot and leases. */
719
780
  recoveredWork: Map<TaskId, RecoveredWork>;
720
- /** Work that must observe an attachment cut before its writer closes (including already-decided verdicts). */
721
- 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>;
722
786
  attachment: AbortController;
723
787
  /** §9: `queue.resume()` ran in this activation and did not halt; a user `resume` retries while false. */
724
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>;
725
800
  /** R1a: children adopted on probation, keyed by child session id. */
726
801
  probation: Map<string, ProbationWatch>;
727
802
  /** R1a: the poll timer of the probation watch (one per plan), null when no child is on probation. */
@@ -776,8 +851,23 @@ const ATTEMPT_TRAILER = "Omr-Attempt";
776
851
  export const RESUME_PROMPT = "continue and finish";
777
852
  /** QA-4.2-16: states a failed lease rebuild holds (no commit, verify or enqueue until the leases are back). */
778
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";
779
863
  /** QA-4.2-3: how long closing a plan waits for its integration queue to dispose (a hung queue never blocks a close). */
780
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;
781
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. */
782
872
  export const COLLECT_RETRY_BASE_MS = 100;
783
873
  /** QA-5.1-7: the cap of the finished-plan collection backoff. */
@@ -790,6 +880,32 @@ export function nextCollectDelay(delay: number): number {
790
880
  return Math.min(Math.max(delay, COLLECT_RETRY_BASE_MS) * 2, COLLECT_RETRY_MAX_MS);
791
881
  }
792
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
+
793
909
  /**
794
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
795
911
  * phase is settled once tagged, or once the queue settled its tag without one: the tag name exists at another commit
@@ -814,6 +930,101 @@ export function planTagsSettled(l: Readonly<LedgerV1>): boolean {
814
930
  /** QA-4.2-13: context of a `completed` task whose slot was lost before its commit (R2 re-provision failed). */
815
931
  const SLOT_LOST_BEFORE_COMMIT = "slot lost before commit";
816
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
+
817
1028
  /**
818
1029
  * Wake reason of the refused plan's one wake (QA-3.1-19). `WakeReason` (types.ts, owned elsewhere) has no `plan-refused`
819
1030
  * member yet; the wake goes out as an inbox wake under the state key `plan-refused:<planId>:<active>` until it does.
@@ -896,6 +1107,11 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
896
1107
  /** Fallback step counter per session (QA-3.1-8: `e.stepKey` wins); bounded, and dropped when the session ends. */
897
1108
  const stepState = new Map<string, { k: number; open: boolean }>();
898
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>>();
899
1115
  const collected = new Set<PlanId>();
900
1116
  const forgotten = new Set<string>();
901
1117
  /** The child's final text of a completed attempt (row 15), by `<plan>/<task>#<n>`, for the plan-task verifier's `observe`. */
@@ -947,8 +1163,17 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
947
1163
  );
948
1164
  }
949
1165
 
950
- function holdAttachment(p: PlanRt, work: Promise<void>): Promise<void> {
951
- 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);
952
1177
  const done = (): void => { p.attachmentWork.delete(work); };
953
1178
  void work.then(done, done);
954
1179
  return work;
@@ -1007,6 +1232,18 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1007
1232
  return { orchestratorSessionID: p.writer.ledger.orchestrator.sessionID, signal: p.attachment.signal };
1008
1233
  }
1009
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
+
1010
1247
  /**
1011
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,
1012
1249
  * then its reset and release, or its hold when the save fails. Until that ends the slot is neither collectable nor known held.
@@ -1150,7 +1387,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1150
1387
  * left its held states (or its slot) leaves the hold without one.
1151
1388
  */
1152
1389
  async function retryHeldLeases(p: PlanRt): Promise<void> {
1153
- if (p.leaseHeld.size === 0 || p.disposed || p.passive) return;
1390
+ if (p.leaseHeld.size === 0 || p.disposed || p.passive || p.unreconciled) return;
1154
1391
  const l = p.writer.ledger;
1155
1392
  const tasks: Array<{ id: TaskId; slot: string | null; tree: string | null; footprint: Footprint }> = [];
1156
1393
  for (const id of [...p.leaseHeld].sort()) {
@@ -1160,17 +1397,19 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1160
1397
  continue;
1161
1398
  }
1162
1399
  // QA-4.2-26: the pool's record itself, never the cached lease (`slotLeaseOf` caches it on the first retry, which
1163
- // 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.
1164
1402
  let tree: string | null;
1165
1403
  try {
1166
- 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;
1167
1406
  } catch (e) {
1168
1407
  d.log("warn", `slot lookup of held ${id} failed; retried next tick`, errorText(e));
1169
1408
  continue;
1170
1409
  }
1171
1410
  if (tree === null) {
1172
- // A vanished slot record never comes back, so no retry could succeed: the task leaves the hold at once and goes
1173
- // 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).
1174
1413
  p.leaseHeld.delete(id);
1175
1414
  counter(p, "lease-held-slot-lost", { taskId: id });
1176
1415
  slotVanished(p, id);
@@ -1196,15 +1435,18 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1196
1435
  }
1197
1436
 
1198
1437
  /**
1199
- * QA-4.2-26: R2 for a held task whose slot record vanished: `completed`/`verifying` re-verify with an invalid slot
1200
- * (QA-4.2-13/-20 included), `verified` is re-provisioned from its branch and re-enqueued; a `running` task needs
1201
- * 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.
1202
1443
  */
1203
1444
  function slotVanished(p: PlanRt, taskId: TaskId): void {
1204
1445
  p.slotLeases.delete(taskId);
1205
1446
  const waiting = p.recoveredWork.get(taskId);
1206
1447
  if (waiting?.work.kind === "reverify" && !waiting.started) {
1207
1448
  waiting.work.slotValid = false;
1449
+ waiting.work.vanished = true;
1208
1450
  schedule(p);
1209
1451
  return;
1210
1452
  }
@@ -1212,8 +1454,8 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1212
1454
  withTask(p, taskId, async () => {
1213
1455
  const t = own(p.writer.ledger, taskId);
1214
1456
  if (t === null || p.disposed) return;
1215
- if (t.state === "completed" || t.state === "verifying") await reverify(p, taskId, false);
1216
- 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]);
1217
1459
  }),
1218
1460
  );
1219
1461
  }
@@ -1261,10 +1503,20 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1261
1503
  function registerRecoveredWork(p: PlanRt, t: TaskNode, work: RecoveredWork["work"]): void {
1262
1504
  const a = t.attempts[t.attempts.length - 1];
1263
1505
  if (a === undefined || p.disposed || disposed || p.recoveredWork.has(t.id)) return;
1264
- 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 });
1265
1507
  schedule(p);
1266
1508
  }
1267
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
+
1268
1520
  /**
1269
1521
  * minor-1: clears the plan's recovered work (abort, close). Since 4070b22 the launcher keeps a `completed` child's
1270
1522
  * binding until the end is processed, so a dropped recovered end releases that binding here
@@ -1279,21 +1531,67 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1279
1531
  p.recoveredWork.clear();
1280
1532
  }
1281
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
+
1282
1568
  /** The launcher's live context gate is also the admission gate for recovered verification (D14). */
1283
1569
  function admitRecoveredWork(p: PlanRt): void {
1284
1570
  if (p.recovering || p.disposed || disposed || p.passive) return;
1285
1571
  for (const w of p.recoveredWork.values()) {
1286
- // R2 must still try to recover an invalid slot even when the old tree's lease rebuild failed. Re-provisioning
1287
- // performs its own lease acquisition/undo; only commit/check/verify remains held until leases are back: a
1288
- // re-verify of a valid slot and a completed child's end (commit then verify). An end that needs no verification
1289
- // (a failed, lost, capacity-stopped or interrupted child) is recorded at once and releases its token.
1290
- const held = (): boolean => p.leaseHeld.has(w.taskId)
1291
- && (w.work.kind === "reverify" ? w.work.slotValid !== false : w.work.end.kind === "completed");
1292
- if (w.started || held()) continue;
1293
- 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
+ }
1294
1591
  w.started = true; // synchronous reservation: repeated ticks/captures cannot queue a second pipeline
1295
- holdAttachment(p, bg("recovered task work", () => withTask(p, w.taskId, async () => {
1296
- 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;
1297
1595
  try {
1298
1596
  const t = own(p.writer.ledger, w.taskId);
1299
1597
  const a = t?.attempts[t.attempts.length - 1];
@@ -1302,18 +1600,27 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1302
1600
  // A re-verify of a task that moved on has nothing left to do.
1303
1601
  if (moved && w.work.kind === "reverify") return;
1304
1602
  // Context/leases may have changed while this task waited for its mutex. Never spend a grader rerun on admission.
1305
- if (held() || !d.launcher.gate(p.writer.ledger.orchestrator.sessionID).ok) {
1306
- parked = true;
1307
- 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
+ }
1308
1614
  }
1309
- if (w.work.kind === "reverify") await reverify(p, w.taskId, w.work.slotValid);
1310
1615
  // N3 / minor-1: an end whose task moved on (e.g. row 34 closed the attempt) still needs its bookkeeping:
1311
1616
  // `processEndNow` ignores a closed attempt and still releases its token and binding and forgets its session.
1312
1617
  else await processEndNow(p, w.taskId, w.n, w.work.end);
1313
1618
  } finally {
1314
1619
  if (p.recoveredWork.get(w.taskId) === w) {
1315
- if (parked) w.started = false;
1316
- 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);
1317
1624
  }
1318
1625
  schedule(p);
1319
1626
  }
@@ -1472,6 +1779,15 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1472
1779
  }
1473
1780
  }
1474
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
+
1475
1791
  /**
1476
1792
  * Only a missing slot directory is gone. Missing repository metadata is not evidence that its files are disposable.
1477
1793
  */
@@ -1485,13 +1801,18 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1485
1801
  }
1486
1802
  }
1487
1803
 
1488
- /** Whether the pool still leases `slotName` to `taskId` (a policy that already returned it leaves nothing to do). */
1489
- 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> {
1490
1810
  try {
1491
1811
  const rec = await slotsFor(p.planId).get(slotName);
1492
1812
  return rec !== null && rec.owner === leaseHolderID(p.planId, taskId) && rec.state === "leased";
1493
- } catch {
1494
- 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;
1495
1816
  }
1496
1817
  }
1497
1818
 
@@ -1597,7 +1918,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1597
1918
  timeoutMs: GIT_TIMEOUT_MS,
1598
1919
  ...(slot.base === undefined || slot.base === null ? {} : { base: slot.base }),
1599
1920
  fallbackRef: orphanRefName(p.planId, slot.slot, d.clock.now(), orphanTag()),
1600
- removeIndexLock: () => removeIndexLock(d.git, o),
1921
+ removeIndexLock: () => removeSlotIndexLock(p, slot.slot, o),
1601
1922
  ...(d.commitIdentity === undefined ? {} : { identity: d.commitIdentity }),
1602
1923
  });
1603
1924
  wipFailRaised.delete(`${p.planId}/${slot.slot}`);
@@ -1673,7 +1994,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1673
1994
  counter(p, "wip-foreign-slot", { taskId, slot: slotName }, deferredMetrics);
1674
1995
  return "clean";
1675
1996
  }
1676
- 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);
1677
1998
  return snapshotWip(p, { slot: slotName, path: at.path, base: at.base }, taskId, a.n, a.nonce, outcome, deferredMetrics);
1678
1999
  }
1679
2000
 
@@ -1734,6 +2055,9 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
1734
2055
  try { markers = await slotsFor(p.planId).list(); }
1735
2056
  catch (error) { throw new ExecutorError("E_PLAN_STATE", `plan ${p.planId}: unsaved slot markers could not be read (${errorText(error)})`, { planId: p.planId }); }
1736
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;
1737
2061
  if (marker.planId === p.planId && (terminal || marker.state === "leased")) wipFailRaised.add(`${p.planId}/${marker.slot}`);
1738
2062
  }
1739
2063
  }
@@ -2056,8 +2380,9 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2056
2380
  function schedule(p: PlanRt): void {
2057
2381
  observe(p, "schedule");
2058
2382
  // A passively attached (refused) plan never ticks (QA-3.1-19); an activation under way neither (4.2.5: recovery and
2059
- // the integration resume come before the first tick, which `recoverPlan`/`activate` schedule themselves).
2060
- 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;
2061
2386
  if (p.ticking) {
2062
2387
  p.again = true;
2063
2388
  return;
@@ -2116,7 +2441,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2116
2441
  if (l.status !== "running") {
2117
2442
  closeIdle(p);
2118
2443
  // Recovery also re-verifies paused plans. Their pending work needs a root context even without launchable work.
2119
- if ([...p.recoveredWork.values()].some((w) => !w.started)) {
2444
+ if (recoveredWorkWaiting(p)) {
2120
2445
  const gate = d.launcher.gate(l.orchestrator.sessionID);
2121
2446
  if (!gate.ok && gate.wake !== null) await wakeOnce(p, gate.wake.reason, gate.wake.stateKey);
2122
2447
  }
@@ -2162,7 +2487,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2162
2487
  }
2163
2488
  observe(p, "launch-gate", () => ({ ok: gate.ok, ready: ready.map((r) => r.taskId) }));
2164
2489
  if (ready.length === 0 || !gate.ok) {
2165
- 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) {
2166
2491
  await wakeOnce(p, gate.wake.reason, gate.wake.stateKey);
2167
2492
  }
2168
2493
  updateIdle(p, ready, 0);
@@ -2479,7 +2804,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2479
2804
  counter(p, "launch-failed", { row: code === "E_LAUNCH_TASK" ? "L2" : code === "E_NO_CONTEXT" ? "L3" : "L4" });
2480
2805
  if (code === "E_LAUNCH_TASK") await rowLaunchFailed(p, taskId, n, errorText(e));
2481
2806
  else if (code === "E_DISPOSED") releaseToken(p, taskId, n, "other");
2482
- 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);
2483
2808
  return "skipped";
2484
2809
  }
2485
2810
  launchRequests.set(requestKey(p, taskId, n), req);
@@ -2678,7 +3003,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2678
3003
  if (c.kind === "confirmed") {
2679
3004
  const p = current(p0);
2680
3005
  p.preConfirmLosses = 0;
2681
- p.preConfirmCapture = null;
3006
+ p.preConfirmCaptures.clear();
2682
3007
  return;
2683
3008
  }
2684
3009
  await withTask(current(p0), taskId, async () => {
@@ -2691,8 +3016,11 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2691
3016
  });
2692
3017
  }
2693
3018
 
2694
- /** Row 11: dispatched -> ready, uncounted; slot and leases are kept (R4). */
2695
- 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> {
2696
3024
  const at = d.clock.iso();
2697
3025
  let applied = false;
2698
3026
  try {
@@ -2710,32 +3038,39 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2710
3038
  d.log("error", "row 11 failed", errorText(e));
2711
3039
  }
2712
3040
  releaseToken(p, taskId, n, "other");
2713
- if (applied) await preConfirmLost(p, taskId, n, reason);
3041
+ if (applied) await preConfirmLost(p, taskId, n, reason, ref);
2714
3042
  schedule(p);
2715
3043
  }
2716
3044
 
2717
3045
  /**
2718
- * QA-3.1-17: whether a row 11 counts toward the pre-confirmation streak. A loss counts once per capture (the attempt's
2719
- * `callID`): N parallel launches lost under one capture change (E_NO_CONTEXT, superseded: the expected uncounted L3/L5
2720
- * race) are one loss, not N. A `superseded`/`no-context` loss is ignored outright when a newer capture is already
2721
- * current (the relaunch goes out under it). Within one capture a task lost AGAIN (a relaunch that failed the same way)
2722
- * 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`.
2723
3053
  */
2724
- 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 {
2725
3055
  const l = p.writer.ledger;
2726
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;
2727
3059
  if ((reason === "superseded" || reason === "no-context") && callID !== null) {
2728
3060
  const g = d.launcher.gate(l.orchestrator.sessionID);
2729
- if (g.ok && g.context.callID !== callID) return false;
2730
- }
2731
- const key = callID ?? `\u0000${taskId}#${n}`;
2732
- const cap = p.preConfirmCapture;
2733
- if (cap === null || cap.key !== key) {
2734
- 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]));
2735
3070
  return true;
2736
3071
  }
2737
- if (cap.tasks.has(taskId)) return true;
2738
- cap.tasks.add(taskId);
3072
+ if (tasks.has(taskId)) return true;
3073
+ tasks.add(taskId);
2739
3074
  return false;
2740
3075
  }
2741
3076
 
@@ -2745,12 +3080,12 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
2745
3080
  * PRECONFIRM_STREAK consecutive counted losses (`preConfirmCounts`, QA-3.1-17) the plan pauses (no more launches, so
2746
3081
  * no more stale-context wakes) and ONE blocking item is raised. A confirmed launch, and a resume, reset the count.
2747
3082
  */
2748
- async function preConfirmLost(p: PlanRt, taskId: TaskId, n: number, reason: string): Promise<void> {
2749
- 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;
2750
3085
  p.preConfirmLosses += 1;
2751
3086
  if (p.preConfirmLosses < PRECONFIRM_STREAK) return;
2752
3087
  p.preConfirmLosses = 0;
2753
- p.preConfirmCapture = null;
3088
+ p.preConfirmCaptures.clear();
2754
3089
  let paused = false;
2755
3090
  try {
2756
3091
  paused = await appendIf(p, (cur) =>
@@ -3336,7 +3671,10 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
3336
3671
  // QA-4.2-16: held until the leases are back (`retryHeldLeases` resumes it).
3337
3672
  if (p.leaseHeld.has(taskId)) return;
3338
3673
  const slotName = t.slot;
3339
- 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;
3340
3678
  const applied = await appendIf(p, (cur) => {
3341
3679
  const c = own(cur, taskId);
3342
3680
  if (c === null || c.state !== "completed") return [];
@@ -3413,7 +3751,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
3413
3751
  function verifyAttempt(p: PlanRt, taskId: TaskId, n: number, lease: SlotLease): Promise<void> {
3414
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
3415
3753
  // work covers the journaling of a verdict that settles after the verifier was cut; `closePlan` runs after that wait.
3416
- return holdAttachment(p, track(verifyAttemptNow(p, taskId, n, lease)));
3754
+ return holdAttachment(p, `verification of ${taskId}#${n}`, track(verifyAttemptNow(p, taskId, n, lease)));
3417
3755
  }
3418
3756
 
3419
3757
  async function verifyAttemptNow(p: PlanRt, taskId: TaskId, n: number, lease: SlotLease): Promise<void> {
@@ -3440,9 +3778,11 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
3440
3778
  nonce = att.nonce;
3441
3779
  forgotten.delete(`${p.planId}/${taskId}#${n}`);
3442
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;
3443
3783
  await slotsFor(p.planId).cleanForChecks(lease.slot);
3444
3784
  if (p.disposed || parkWithoutContext()) return;
3445
- 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));
3446
3786
  verdict = v.verdict;
3447
3787
  findings = v.findings;
3448
3788
  ref = v.ref;
@@ -3634,7 +3974,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
3634
3974
  if (sweep.stop === "cut") return;
3635
3975
  if (sweep.stop === "held") {
3636
3976
  // The slot stays leased to the task under its hold; the sweep raised it when it knew the slot.
3637
- 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))) {
3638
3978
  sweep.slot = slot;
3639
3979
  await holdAdoptedSlot(p, taskId, slot, sweep.child, "dep-reverted");
3640
3980
  }
@@ -3986,12 +4326,14 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
3986
4326
  const p = await build(writer, refusedBy !== null);
3987
4327
  onRegistered();
3988
4328
  if (refusedBy !== null) {
3989
- await refusePassive(p, refusedBy);
4329
+ // #190: no refusal item or orchestrator wake once dispose began.
4330
+ if (!disposed) await refusePassive(p, refusedBy);
3990
4331
  return p;
3991
4332
  }
3992
4333
  const st = writer.ledger.status;
3993
4334
  // An existing ledger (start, adopt, a plan opened by an action) is recovered; a just-created one is not (4.2.5).
3994
- 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);
3995
4337
  return p;
3996
4338
  } finally {
3997
4339
  if (reserved) unreserve(planId);
@@ -4117,15 +4459,17 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4117
4459
  provisionFails: 0,
4118
4460
  provisionRaised: false,
4119
4461
  preConfirmLosses: 0,
4120
- preConfirmCapture: null,
4462
+ preConfirmCaptures: new Map(),
4121
4463
  routeFails: 0,
4122
4464
  routeRaised: false,
4123
4465
  passive,
4124
4466
  recovering: false,
4125
4467
  recoveredWork: new Map(),
4126
- attachmentWork: new Set(),
4468
+ attachmentWork: new Map(),
4127
4469
  attachment: new AbortController(),
4128
4470
  integrationResumed: false,
4471
+ unreconciled: false,
4472
+ treesAlive: new Map(),
4129
4473
  probation: new Map(),
4130
4474
  probationTimer: null,
4131
4475
  interrupting: new Set(),
@@ -4147,6 +4491,12 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4147
4491
  attachSlotObservations(d.observations, d.clock, writer);
4148
4492
  try { await rebuildHeldSlots(p); }
4149
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
+ }
4150
4500
  plans.set(planId, p);
4151
4501
  observeSchedulerLedger(d.observations, writer.ledger, "attach");
4152
4502
  observe(p, "runtime-attach");
@@ -4219,8 +4569,6 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4219
4569
  });
4220
4570
  }
4221
4571
 
4222
- /** Plans `recover()` reported eligible (same toplevel) or adopted here: only these may be taken over by `start()`. */
4223
- const recoverable = new Set<PlanId>();
4224
4572
  /** QA-4.2-17: plans of another toplevel `start()` attached passively; never recovered, resumed or ticked here. */
4225
4573
  const foreignPlans = new Set<PlanId>();
4226
4574
  /**
@@ -4291,11 +4639,22 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4291
4639
  */
4292
4640
  async function recoverPlan(p: PlanRt): Promise<void> {
4293
4641
  // (2) classification, read-only; launches this process tracks are never reconciled (D12)
4294
- 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;
4295
4651
  // (3) orphans, best effort
4296
4652
  for (const f of feeds) for (const s of f.orphans) await interruptQuiet(s);
4297
4653
  // (4) the integration queue, before any dequeue (D7)
4298
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);
4299
4658
  // (5) the matrix, in task-id order
4300
4659
  for (const f of feeds) {
4301
4660
  try {
@@ -4330,7 +4689,126 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4330
4689
  }
4331
4690
  }
4332
4691
 
4333
- 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 }> {
4334
4812
  const rec = d.recovery;
4335
4813
  const l = p.writer.ledger;
4336
4814
  const tracked = new Set<string>();
@@ -4358,7 +4836,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4358
4836
  return await rec.reconcile(l, tracked);
4359
4837
  } catch (e) {
4360
4838
  d.log("error", "reconcile failed", errorText(e));
4361
- return [];
4839
+ return { failed: e };
4362
4840
  }
4363
4841
  }
4364
4842
 
@@ -4425,7 +4903,8 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4425
4903
  async function adoptChild(p: PlanRt, t: TaskNode, f: ReconcileFeed): Promise<void> {
4426
4904
  const a = t.attempts.find((x) => x.n === f.n);
4427
4905
  const child = f.childSessionID;
4428
- 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;
4429
4908
  const n = a.n;
4430
4909
  const live = f.evidence !== "finished";
4431
4910
  // QA-4.2-16: a task whose leases could not be re-taken never adopts a live child (it would write without leases):
@@ -4602,7 +5081,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4602
5081
  const task = own(p.writer.ledger, taskId);
4603
5082
  if (task === null || task.state !== "ready") return;
4604
5083
  const slotName = task.slot;
4605
- if (slotName !== null && !(await releaseGoneSlot(p, taskId, slotName))) return;
5084
+ if (slotName !== null && (await releaseGoneSlot(p, taskId, slotName)) !== null) return;
4606
5085
  const applied = await appendIf(p, (cur) => {
4607
5086
  const c = own(cur, taskId);
4608
5087
  return c === null || c.state !== "ready" || c.slot === null ? [] : [ts(taskId, null, null)];
@@ -4615,8 +5094,9 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4615
5094
  /**
4616
5095
  * R2: a foreign slot is untouched. An owned slot with a missing/invalid marker can still hold work: save it before
4617
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).
4618
5098
  */
4619
- async function releaseGoneSlot(p: PlanRt, taskId: TaskId, slotName: string): Promise<boolean> {
5099
+ async function releaseGoneSlot(p: PlanRt, taskId: TaskId, slotName: string): Promise<string | null> {
4620
5100
  let held = false;
4621
5101
  try {
4622
5102
  const rec = await slotsFor(p.planId).get(slotName);
@@ -4624,13 +5104,13 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4624
5104
  } catch (e) {
4625
5105
  d.log("warn", `slot lookup of the bad slot ${slotName} failed`, errorText(e));
4626
5106
  await wipHold(p, taskId, slotName, "its recovery release");
4627
- return false;
5107
+ return `its pool record could not be read: ${errorText(e)}; its own item names the slot`;
4628
5108
  }
4629
- if (!held) return true;
5109
+ if (!held) return null;
4630
5110
  const saved = await snapshotTaskSlot(p, taskId, slotName, "recovery-release");
4631
5111
  if (saved === "failed") {
4632
5112
  await wipHold(p, taskId, slotName, "its recovery release");
4633
- return false;
5113
+ return "its work could not be saved; its own item names the slot";
4634
5114
  }
4635
5115
  if (p.slotLeases.get(taskId)?.slot === slotName) p.slotLeases.delete(taskId);
4636
5116
  wipFailRaised.delete(`${p.planId}/${slotName}`);
@@ -4639,48 +5119,81 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4639
5119
  counter(p, "bad-slot-released", { taskId, slot: slotName });
4640
5120
  } catch (e) {
4641
5121
  d.log("warn", `releasing the bad slot ${slotName} of ${taskId} failed`, errorText(e));
4642
- return false;
5122
+ return `the pool's release failed: ${errorText(e)}`;
4643
5123
  }
4644
- return true;
5124
+ return null;
4645
5125
  }
4646
5126
 
4647
5127
  /**
4648
5128
  * R2: a `completed`/`verifying`/`verified` task whose slot marker is missing or foreign gets a slot again from its task
4649
5129
  * branch `omr/<planId>/t/<taskId>`: the stale slot goes back to the pool (only if the pool still records it as ours), a
4650
5130
  * slot is acquired, reset to the branch tip and checked out (detached) at it, the task's leases move to the new tree
4651
- * (released and re-taken, as `rebuild` does) and the slot is journaled (state re-checked, D2). False when the branch
4652
- * 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.
4653
5138
  */
4654
- async function reprovisionSlot(p: PlanRt, taskId: TaskId): Promise<boolean> {
5139
+ async function reprovisionSlot(p: PlanRt, taskId: TaskId, knownTip?: string): Promise<Reprovision> {
4655
5140
  const t0 = own(p.writer.ledger, taskId);
4656
- 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
+ }
4657
5144
  const from = t0.state;
4658
5145
  const branch = taskBranchName(p.planId, taskId);
4659
5146
  const o = { cwd: p.writer.ledger.repo.toplevel, timeoutMs: GIT_TIMEOUT_MS };
4660
- let tip = "";
4661
- try {
4662
- const r = await d.git.run(["rev-parse", "--verify", "--quiet", `refs/heads/${branch}^{commit}`], o);
4663
- tip = r.code === 0 ? r.stdout.trim() : "";
4664
- } catch (e) {
4665
- 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 };
4666
5164
  }
4667
- if (tip === "") return false;
4668
5165
  const stale = t0.slot;
4669
- // Missing marker evidence is not permission to discard an owned tree. A failed save stops re-provisioning.
4670
- 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
+ };
4671
5175
  p.slotLeases.delete(taskId);
4672
5176
  let slot: SlotLease | null = null;
4673
- const undo = async (why: string, e?: unknown): Promise<false> => {
4674
- 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);
4675
5181
  const s = slot;
4676
- 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);
4677
5183
  p.slotLeases.delete(taskId);
4678
- return false;
5184
+ return failed(reason, detail);
4679
5185
  };
5186
+ // The step a throw below comes from (the item names it).
5187
+ let step: ReprovisionFailure = "slot unavailable";
4680
5188
  try {
4681
- 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 });
4682
5192
  slot = acquired;
4683
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";
4684
5197
  if (verifiedResetBase === undefined) {
4685
5198
  const saved = await saveBeforeLaunchReset(p, t0, slot, slot.commit);
4686
5199
  if (saved === "failed") {
@@ -4688,26 +5201,30 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4688
5201
  // still names the stale slot, and a cache naming this one would hand it to the verifier or a release.
4689
5202
  await wipHold(p, taskId, slot.slot, "its re-provisioning reset");
4690
5203
  if (p.slotLeases.get(taskId)?.slot === slot.slot) p.slotLeases.delete(taskId);
4691
- return false;
5204
+ return failed("save failed", "");
4692
5205
  }
4693
5206
  }
4694
5207
  if (verifiedResetBase !== tip) await slotsFor(p.planId).reset(slot.slot, tip);
4695
5208
  // QA-PDF21-12: the cached lease follows the reset (a re-acquired slot's lease names its pre-reset commit).
4696
5209
  slot = leaseAt(slot, tip);
4697
5210
  p.slotLeases.set(taskId, slot);
5211
+ step = "checkout failed";
4698
5212
  // Detached at the tip: the branch may still be checked out in the stale worktree, and the ref itself stays put.
4699
5213
  const r = await d.git.run(["switch", "--detach", tip], { cwd: slot.path, timeoutMs: GIT_TIMEOUT_MS });
4700
5214
  if (r.code !== 0) return await undo("checkout failed", r.stderr.slice(0, 2000));
4701
5215
  } catch (e) {
4702
- return await undo("slot unavailable", e);
5216
+ return await undo(step, e);
4703
5217
  }
4704
5218
  const lease = slot;
4705
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;
4706
5222
  try {
4707
5223
  const got = p.leases.acquireTask({ taskId, tree: lease.path, writes: t0.footprint.writes });
4708
- 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;
4709
5226
  // QA-4.2-16: the leases are back on the new tree; a hold from the failed rebuild ends here.
4710
- p.leaseHeld.delete(taskId);
5227
+ else p.leaseHeld.delete(taskId);
4711
5228
  } catch (e) {
4712
5229
  return await undo("lease error", e);
4713
5230
  }
@@ -4721,36 +5238,70 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4721
5238
  return await undo("journal failed", e);
4722
5239
  }
4723
5240
  const now = own(p.writer.ledger, taskId);
4724
- 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
+ }
4725
5254
  counter(p, "slot-reprovisioned", { taskId });
4726
- return true;
5255
+ return { kind: "ok" };
4727
5256
  }
4728
5257
 
4729
5258
  /**
4730
5259
  * R2 for `completed`/`verifying`/`verified`: re-provision from the task branch; when that is impossible (no branch, a
4731
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.
4732
5263
  */
4733
- async function reprovisionOrRaise(p: PlanRt, t: TaskNode): Promise<boolean> {
4734
- if (await reprovisionSlot(p, t.id)) return true;
4735
- await raiseSlotLost(p, t);
4736
- 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";
4737
5270
  }
4738
5271
 
4739
5272
  /**
4740
- * QA-4.2-13: whether a commit of the repository carries attempt `n`'s trailer (D11); null when git cannot tell. On
4741
- * 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).
4742
5278
  */
4743
- async function attemptCommitted(p: PlanRt, taskId: TaskId, a: Attempt): Promise<boolean | null> {
5279
+ async function attemptCommitted(p: PlanRt, taskId: TaskId, a: Attempt): Promise<AttemptCommit> {
4744
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
+ };
4745
5288
  try {
4746
- const r = await d.git.run(["log", "--all", "--fixed-strings", `--grep=${trailer}`, "--format=%H", "-n", "1"], {
4747
- cwd: p.writer.ledger.repo.toplevel,
4748
- timeoutMs: GIT_TIMEOUT_MS,
4749
- });
4750
- 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 };
4751
5302
  } catch (e) {
4752
5303
  d.log("warn", `trailer search for ${taskId} failed`, errorText(e));
4753
- return null;
5304
+ return unknown;
4754
5305
  }
4755
5306
  }
4756
5307
 
@@ -4776,77 +5327,153 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
4776
5327
  await clearBadSlot(p, taskId);
4777
5328
  }
4778
5329
 
4779
- /** R2: the blocking item of a task whose slot cannot be re-provisioned and whose work may exist (a human decides). */
4780
- 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";
4781
5338
  await raiseSafe(p, {
4782
5339
  kind: "failure",
4783
5340
  severity: "blocking",
4784
5341
  taskId: t.id,
4785
- 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)}`,
4786
5343
  options: [],
4787
5344
  });
4788
5345
  }
4789
5346
 
4790
- /** 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
+ */
4791
5352
  async function resetSlotContents(p: PlanRt, t: TaskNode): Promise<void> {
4792
- // 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
4793
- // slot as it is (no reset) and raises the item that names it.
4794
- if (t.slot !== null && (await snapshotTaskSlot(p, t.id, t.slot, "restart")) === "failed") {
4795
- await wipHold(p, t.id, t.slot, "its reset (restart)");
4796
- return;
4797
- }
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);
4798
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
+ }
4799
5364
  const lease = await slotLeaseOf(p, t);
4800
5365
  const o = { cwd: lease.path, timeoutMs: GIT_TIMEOUT_MS };
4801
- await d.git.run(["reset", "--hard", "HEAD"], o);
4802
- 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("; "));
4803
5382
  } catch (e) {
4804
- 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);
5386
+ }
5387
+ }
5388
+
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;
4805
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);
4806
5414
  }
4807
5415
 
4808
- /** `completed` -> commit-and-verify (D11 finds a commit made before the crash); `verifying` -> the verifier again. */
4809
- async function reverify(p: PlanRt, taskId: TaskId, slotValid: boolean | null): Promise<void> {
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"> {
4810
5423
  const t0 = own(p.writer.ledger, taskId);
4811
5424
  const a = t0 === null ? undefined : t0.attempts[t0.attempts.length - 1];
4812
- if (t0 === null || a === undefined || t0.slot === null) return;
5425
+ if (t0 === null || a === undefined || t0.slot === null) return "done";
4813
5426
  const n = a.n;
4814
5427
  if (slotValid === false) {
4815
5428
  // QA-4.2-20: the branch tip may hold an EARLIER attempt's commit, so a `completed` task is re-provisioned only once
4816
5429
  // this attempt's own commit is known to exist. QA-4.2-13: none -> its work went with the slot: failed, retried.
4817
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.
4818
5434
  if (t0.state === "completed") {
5435
+ if (attachmentCut(p)) return "done";
4819
5436
  const committed = await attemptCommitted(p, taskId, a);
4820
- if (committed === false) {
5437
+ if (attachmentCut(p)) return "done";
5438
+ if (committed.kind === "none") {
4821
5439
  await slotLostBeforeCommit(p, taskId, n);
4822
- return;
5440
+ return "done";
4823
5441
  }
4824
- if (committed === null) {
4825
- await raiseSlotLost(p, t0);
4826
- return;
5442
+ if (committed.kind === "unknown") {
5443
+ await raiseSlotLost(p, t0, { elsewhere: committed.elsewhere }, vanished);
5444
+ return "done";
4827
5445
  }
5446
+ tip = committed.tip; // QA-4.2-32 (#188): re-provisioned from the very tip whose history carries the commit
4828
5447
  }
4829
- if (!(await reprovisionSlot(p, taskId))) {
4830
- await raiseSlotLost(p, t0);
4831
- 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";
4832
5457
  }
4833
5458
  }
5459
+ if (attachmentCut(p)) return "done";
4834
5460
  // Re-read: a re-provisioned task has a new slot.
4835
5461
  const t = own(p.writer.ledger, taskId);
4836
- if (t === null || t.slot === null) return;
5462
+ if (t === null || t.slot === null) return "done";
4837
5463
  if (t.state === "completed") {
4838
5464
  await commitAndVerify(p, taskId, n);
4839
- return;
5465
+ return "done";
4840
5466
  }
4841
- if (t.state !== "verifying") return;
5467
+ if (t.state !== "verifying") return "done";
4842
5468
  let lease: SlotLease;
4843
5469
  try {
4844
5470
  lease = await slotLeaseOf(p, t);
4845
5471
  } catch (e) {
4846
5472
  d.log("warn", `reverify of ${taskId}: slot unavailable`, errorText(e));
4847
- return;
5473
+ return "done";
4848
5474
  }
4849
5475
  await verifyAttempt(p, taskId, n, lease);
5476
+ return "done";
4850
5477
  }
4851
5478
 
4852
5479
  /** Step 7: `qa-running` with no QA task in flight -> the latest done QA task's report; `awaiting-qa` -> onAwaitingQa. */
@@ -5090,10 +5717,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5090
5717
  severity: "blocking",
5091
5718
  taskId: f.taskId,
5092
5719
  // QA-4.2-26: the item says the task is held and what ends the hold.
5093
- text:
5094
- `could not re-take the leases of ${f.taskId} after restart; held by ${f.holders.map((h) => h.holderID).join(", ")}. ` +
5095
- `${f.taskId} is held (no adopt, commit, verify or enqueue) until its leases are free: finish or abort the holder ` +
5096
- `(or abort ${f.taskId}); it resumes on its own once the leases are released`,
5720
+ text: leaseHoldText(f.taskId, f.holders, "after restart"),
5097
5721
  options: [],
5098
5722
  });
5099
5723
  } catch (e) {
@@ -5102,6 +5726,16 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5102
5726
  }
5103
5727
  }
5104
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
+
5105
5739
  /** R1a: a rejected interrupt that still means "nothing runs any more" (not found / not busy) is a success. */
5106
5740
  function interruptSettled(e: unknown): boolean {
5107
5741
  return /not[-_ ]?found|not[-_ ]?busy|no such session/i.test(`${errorCode(e) ?? ""} ${errorText(e)}`);
@@ -5115,7 +5749,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5115
5749
  p.attachment.abort();
5116
5750
  dropRecoveredWork(p, false);
5117
5751
  // An adopt closes this writer only after old-attachment pipelines have observed their cut.
5118
- await Promise.allSettled([...p.attachmentWork]);
5752
+ await waitForAttachmentWork(p);
5119
5753
  p.offSlotRelease?.();
5120
5754
  p.offSlotRelease = null;
5121
5755
  observe(p, "detach");
@@ -5147,6 +5781,46 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5147
5781
  await p.writer.close();
5148
5782
  }
5149
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
+
5150
5824
  /** QA-4.2-3: `queue.dispose()`, bounded by QUEUE_DISPOSE_MS (a hung queue is logged, never blocks the close). */
5151
5825
  async function disposeQueue(p: PlanRt): Promise<void> {
5152
5826
  const fire: { timeout: () => void } = { timeout: () => undefined };
@@ -5173,7 +5847,31 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5173
5847
  const ledger = await d.store.read(planId);
5174
5848
  if (isForeign(ledger.repo.toplevel)) return attach(readOnlyWriter(ledger), true, undefined, { foreign: true });
5175
5849
  const writer = await d.store.open(planId, d.holder(sessionID));
5176
- 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
+ }
5177
5875
  }
5178
5876
 
5179
5877
  /**
@@ -5189,7 +5887,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5189
5887
  return;
5190
5888
  }
5191
5889
  const writer = await d.store.open(planId, d.holder(orchestrator));
5192
- await attach(writer, true, onRegistered);
5890
+ await attachOpened(writer, { onRegistered });
5193
5891
  d.log("warn", `adopt of ${planId} failed; the plan is attached again for ${orchestrator}`);
5194
5892
  } catch (e) {
5195
5893
  d.log("error", `plan ${planId} could not be attached again after a failed adopt`, errorText(e));
@@ -5471,8 +6169,74 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5471
6169
  if (!ok) throw new ExecutorError("E_PLAN_STATE", `plan ${p.planId} is ${p.writer.ledger.status}`, p.writer.ledger.status);
5472
6170
  }
5473
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
+
5474
6237
  const handle: ExecutorRuntimeHandle = {
5475
6238
  async compile(i) {
6239
+ refuseDisposed();
5476
6240
  const r = await d.compiler.compile(i.path, {
5477
6241
  ...(i.phases === undefined ? {} : { phases: i.phases }),
5478
6242
  ...(i.doneBefore === undefined ? {} : { doneBefore: i.doneBefore }),
@@ -5481,6 +6245,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5481
6245
  now: d.clock.iso(),
5482
6246
  });
5483
6247
  if (isForeign(r.draft.repo.toplevel)) throw new ExecutorError("E_INVALID_INPUT", "the plan belongs to another repository");
6248
+ refuseDisposed();
5484
6249
  const writer = await d.store.create(r.draft, d.holder(i.sessionID));
5485
6250
  const planId = r.draft.planId;
5486
6251
  d.forgetSlots?.(planId);
@@ -5489,7 +6254,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5489
6254
  if (timer !== undefined) d.clock.clearTimer(timer);
5490
6255
  collectionTimers.delete(planId);
5491
6256
  collectionDelays.delete(planId);
5492
- await attach(writer, false);
6257
+ await attachOpened(writer, { existing: false });
5493
6258
  return { planId: r.draft.planId, summary: r.summary, residuePrompt: r.residueRequest?.prompt ?? null };
5494
6259
  },
5495
6260
 
@@ -5681,6 +6446,13 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5681
6446
  const other = reserve(planId);
5682
6447
  if (other !== null) await refuseSecondPlan(p.writer, other);
5683
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
+ }
5684
6456
  // QA-4.2-6: a running plan whose integration resume failed (or halted) is resumed again by the user's `resume`.
5685
6457
  const retryOnly = !promote && p.writer.ledger.status === "running" && !p.integrationResumed;
5686
6458
  try {
@@ -5689,16 +6461,22 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5689
6461
  p.passive = false;
5690
6462
  observe(p, "promote");
5691
6463
  await activate(p, true);
5692
- } 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 {
5693
6469
  // §9: a halted (or failed) integration resume is retried by the user's resume.
5694
- 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);
5695
6473
  }
5696
6474
  } finally {
5697
6475
  if (promote) unreserve(planId);
5698
6476
  }
5699
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).
5700
6478
  p.preConfirmLosses = 0;
5701
- p.preConfirmCapture = null;
6479
+ p.preConfirmCaptures.clear();
5702
6480
  p.skipStreak = 0;
5703
6481
  p.provisionFails = 0;
5704
6482
  p.provisionRaised = false;
@@ -5769,9 +6547,12 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5769
6547
  ev.push({ type: "status-changed", from: cur.status, to: "aborted", reason: "user-abort" });
5770
6548
  return ev;
5771
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);
5772
6553
  closeIdle(p);
5773
6554
  unpinPlan(p);
5774
- const attachmentWork = [...p.attachmentWork];
6555
+ const attachmentWork = [...p.attachmentWork.keys()];
5775
6556
  const attachmentsSettled = Promise.allSettled(attachmentWork);
5776
6557
  // QA-4.2-23: the abort closed every attempt, the adopted children's bindings go with them.
5777
6558
  for (const id of [...p.rebound.keys()]) evictRebound(p, id, null);
@@ -5860,6 +6641,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5860
6641
  },
5861
6642
 
5862
6643
  async adopt(planId, sessionID) {
6644
+ refuseDisposed();
5863
6645
  const recovery = d.recovery;
5864
6646
  if (recovery === null) throw new ExecutorError("E_PLAN_STATE", "recovery is not available", planId);
5865
6647
  // QA-3.1-19 / QA-4.2-25: every cheap refusal (state, foreign repository, single-plan rule, with the slot reserved,
@@ -5883,6 +6665,11 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5883
6665
  st,
5884
6666
  );
5885
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
+ }
5886
6673
  // QA-4.2-21: a plan of another repository is never adopted here; its passive attachment stays as it is.
5887
6674
  if (seen !== null && isForeign(seen.repo.toplevel)) {
5888
6675
  throw new ExecutorError(
@@ -5929,7 +6716,8 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5929
6716
  throw new ExecutorError("E_PLAN_STATE", `plan ${planId} belongs to another repository; its attachment is read-only`, { planId });
5930
6717
  }
5931
6718
  // L3: the reopened local ledger is reconciled on activation.
5932
- recoverable.add(planId);
6719
+ // #190: a dispose that landed meanwhile opens and takes over nothing.
6720
+ refuseDisposed();
5933
6721
  let writer: LedgerWriter;
5934
6722
  try {
5935
6723
  writer = await d.store.open(planId, d.holder(sessionID));
@@ -5938,11 +6726,11 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5938
6726
  writer = await d.store.takeover(planId, d.holder(sessionID), "adopt");
5939
6727
  }
5940
6728
  // The gate opens once the new attachment is registered (before its recovery runs: recovery takes task mutexes).
5941
- await attach(writer, true, openGate);
6729
+ await attachOpened(writer, { onRegistered: openGate });
5942
6730
  } catch (e) {
5943
6731
  // QA-4.2-25: the old attachment is closed and the adopt failed: the plan is attached again under its own
5944
- // orchestrator, so it is not stranded and the ends waiting on the gate are processed.
5945
- 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);
5946
6734
  throw e;
5947
6735
  }
5948
6736
  } finally {
@@ -5952,6 +6740,7 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5952
6740
  },
5953
6741
 
5954
6742
  async gc() {
6743
+ refuseDisposed();
5955
6744
  // A restarted runtime has not attached terminal plans. Open them before entering the pool's gc so failures
5956
6745
  // propagate as E_PLAN_STATE (and no pool mutex is held while a save consults its markers).
5957
6746
  for (const entry of await d.store.list()) {
@@ -5959,7 +6748,8 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
5959
6748
  if (plans.has(entry.planId)) continue;
5960
6749
  const ledger = await d.store.read(entry.planId);
5961
6750
  if (isForeign(ledger.repo.toplevel)) continue;
5962
- 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)));
5963
6753
  }
5964
6754
  // QA-PDF21-15: a finished plan's slot whose work could not be saved is saved again first; a save that fails again
5965
6755
  // refuses the gc (its worktree would be deleted with the work).
@@ -6021,15 +6811,40 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
6021
6811
  // before anything is removed (its worktree would go with the work).
6022
6812
  await refuseUnsaved(p, "purge");
6023
6813
  const toplevel = p.writer.ledger.repo.toplevel;
6814
+ const slotsDir = planSlotsDirOf(p);
6815
+ const ownSlots = purgeSlotsDirs(p.writer.ledger.config.slotsDir, toplevel, planId);
6024
6816
  await closePlan(p);
6025
6817
  // QA-5.1-11: the full gc runs before the ledger is removed; a pool that collection already closed still answers it
6026
6818
  // through a gc-only handle (create.ts PlanSlotPools), so a slot a partial gc could not remove is retried here.
6027
- 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
+ };
6028
6831
  // QA-5.1-22: an invalid slotsDir with slot markers refuses here, before any ref or the ledger is removed.
6029
6832
  const report = d.purgeSlots !== undefined ? await d.purgeSlots(planId, purged) : await slotsFor(planId).gc(purged);
6030
- 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))) {
6031
6835
  throw new ExecutorError("E_PLAN_STATE", `plan ${planId}: pool refused unsaved work; purge refused`, { planId, reported: report.reported });
6032
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
+ }
6033
6848
  for (const ns of ["heads", "tags"]) {
6034
6849
  const prefix = `refs/${ns}/omr/${planId}/`;
6035
6850
  const r = await d.git.run(["for-each-ref", "--format=%(refname)", prefix], { cwd: toplevel, timeoutMs: GIT_TIMEOUT_MS });
@@ -6038,6 +6853,8 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
6038
6853
  await d.git.run(["update-ref", "-d", ref], { cwd: toplevel, timeoutMs: GIT_TIMEOUT_MS });
6039
6854
  }
6040
6855
  }
6856
+ // #189 R2-pre-2: the plan's verification process journals go with it (never rejects).
6857
+ await d.verifyTrees?.purge(planId);
6041
6858
  await d.store.remove(planId);
6042
6859
  },
6043
6860
 
@@ -6084,62 +6901,23 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
6084
6901
  return null;
6085
6902
  },
6086
6903
 
6087
- async start() {
6088
- // QA-3.1-1 (memo M46): the runtime feeds itself from the host's session events: provider of each step, capacity
6089
- // signals, the orchestrator's idle flag and the end of a late-adopted child (L12) all come from here.
6090
- if (offEvents === null && !disposed) offEvents = d.hosts.onEvent(onHostEvent);
6091
- // QA-4.2-17/-21: a running or paused plan of another repository (its own toplevel, never its absence from the
6092
- // recover() report) is attached passively.
6093
- if (d.recovery !== null) {
6094
- try {
6095
- // L2: only the plans recover() reports (same toplevel, running or paused) may be taken over and reconciled.
6096
- for (const r of await d.recovery.recover()) {
6097
- recoverable.add(r.planId);
6098
- // Nit: the engine's report carries full feeds; the plan's first recoverPlan reuses it (one reconcile, not two).
6099
- const feeds: ReconcileFeed[] = [];
6100
- for (const a of r.actions) if (isFeed(a)) feeds.push(a);
6101
- if (d.recovery.reconcile !== undefined && feeds.length === r.actions.length) recoverReports.set(r.planId, feeds);
6102
- }
6103
- } catch (e) {
6104
- d.log("error", "recovery failed", errorText(e));
6105
- }
6106
- }
6107
- // QA-3.1-19: deterministic single-plan pick: a running plan before a paused one, then by plan id; the others attach
6108
- // passively (refused, woken once) instead of not at all.
6109
- const rank = (s: LedgerStatus): number => (s === "running" ? 0 : 1);
6110
- const entries = (await d.store.list())
6111
- .filter((e) => e.status === "running" || e.status === "paused")
6112
- .sort((a, b) => rank(a.status) - rank(b.status) || (a.planId < b.planId ? -1 : a.planId > b.planId ? 1 : 0));
6113
- for (const e of entries) {
6114
- if (plans.has(e.planId)) continue;
6115
- try {
6116
- const ledger = await d.store.read(e.planId);
6117
- if (isForeign(ledger.repo.toplevel)) {
6118
- await attach(readOnlyWriter(ledger), true, undefined, { foreign: true });
6119
- continue;
6120
- }
6121
- const holder = d.holder(e.orchestratorSessionID);
6122
- let writer: LedgerWriter;
6123
- try {
6124
- writer = await d.store.open(e.planId, holder);
6125
- } catch (err) {
6126
- // L2: `open` never takes over; a stale holder of an eligible plan is (the store refuses a live one with
6127
- // E_LOCK_HELD: skipped and logged below, nothing interrupted). Plans of another toplevel are never taken over.
6128
- if (errorCode(err) !== "E_LOCK_HELD" || !recoverable.has(e.planId)) throw err;
6129
- writer = await d.store.takeover(e.planId, holder, RECOVER_TAKEOVER_REASON);
6130
- }
6131
- // A same-repo plan the report missed still attaches actively and recoverPlan reconciles it.
6132
- await attach(writer, true);
6133
- } catch (err) {
6134
- d.log("warn", `plan ${e.planId} not attached`, errorText(err));
6135
- }
6136
- }
6137
- // A report no activation consumed (a refused or failed attach) is stale for any later activation.
6138
- 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;
6139
6915
  },
6140
6916
 
6141
6917
  async dispose() {
6142
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?.();
6143
6921
  // QA-5.1-4: the verifier is cut FIRST (gate deadlines, grader sessions, backoff sleeps), so no pending verify keeps the
6144
6922
  // wait for running work below (and the process claim) for the length of a gate. Its synchronous part runs now; it is
6145
6923
  // awaited after the plans are detached. A cut verdict is never journaled (`verifyAttempt`); QA-5.1-21: a real verdict
@@ -6200,10 +6978,16 @@ export function createExecutorRuntime(d: RuntimeDeps): ExecutorRuntimeHandle {
6200
6978
  } catch (e) {
6201
6979
  d.log("warn", "launcher dispose failed", errorText(e));
6202
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]);
6203
6985
  for (;;) {
6204
6986
  const work = [...pending].filter((pr) => !childWaits.has(pr));
6987
+ if (startWait !== null) work.push(startWait);
6205
6988
  if (work.length === 0) break;
6206
6989
  await Promise.allSettled(work);
6990
+ startWait = null; // settled: the starts ended, or the bound gave up on them
6207
6991
  }
6208
6992
  for (const p of [...plans.values()]) {
6209
6993
  try {