pi-better-subagents 0.32.0 → 0.32.2

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.
@@ -9,6 +9,7 @@ export interface AssignmentProjection {
9
9
  verified: boolean;
10
10
  }
11
11
  export function assignmentFor(meta: object, processStatus?: string, options?: { baseDir?: string | undefined; coordinatorPath?: string; observation?: object }): AssignmentProjection;
12
+ export function createAssignmentProjector(options?: { baseDir?: string | undefined; coordinatorPath?: string; observation?: object }): (meta: object, processStatus?: string) => AssignmentProjection;
12
13
  export function projectAssignment(meta: object, processStatus: string, observation?: object): AssignmentProjection;
13
14
  export function assignmentDiagnostic(assignment: AssignmentProjection): string;
14
15
  export const ASSIGNMENT_STATES: string[];
@@ -57,18 +57,53 @@ export function projectAssignment(meta, processStatus, observation = { verified:
57
57
 
58
58
  /** All consumers use the same lineage and authoritative wait read. Park caches are hints only. */
59
59
  export function assignmentFor(meta, processStatus = meta.status, options = {}) {
60
+ return assignmentFromSnapshot(meta, processStatus, options, () => readAttempts(options));
61
+ }
62
+
63
+ function readAttempts(options) {
60
64
  const base = options.baseDir ?? join(tmpdir(), "pi-better-subagents");
61
- const attempts = new Map([[meta.id, meta]]);
62
- let current = meta;
65
+ const attempts = [];
63
66
  try {
64
- for (const id of (meta.operations || meta.park ? readdirSync(join(base, "runs")) : [])) {
67
+ for (const id of readdirSync(join(base, "runs"))) {
65
68
  try {
66
69
  const candidate = JSON.parse(readFileSync(join(base, "runs", id, "meta.json"), "utf8"));
67
- if (candidate.sessionId === meta.sessionId && candidate.cwd === meta.cwd
68
- && (!meta.assignment || candidate.assignment?.assignmentId === meta.assignment.assignmentId)) attempts.set(candidate.id, candidate);
69
- } catch { /* A partial unrelated record must not hide a continuation. */ }
70
+ if (candidate && typeof candidate === "object") attempts.push(candidate);
71
+ }
72
+ catch { /* A partial unrelated record must not hide a continuation. */ }
70
73
  }
71
74
  } catch { /* Registry gaps cannot establish a newer attempt. */ }
75
+ return attempts;
76
+ }
77
+
78
+ /** One synchronous UI refresh shares a snapshot; the next refresh reads disk again. */
79
+ export function createAssignmentProjector(options = {}) {
80
+ let snapshot;
81
+ const readSnapshot = (meta) => {
82
+ if (!snapshot) {
83
+ snapshot = new Map();
84
+ for (const candidate of readAttempts(options)) {
85
+ let workspaces = snapshot.get(candidate.sessionId);
86
+ if (!workspaces) snapshot.set(candidate.sessionId, workspaces = new Map());
87
+ let attempts = workspaces.get(candidate.cwd);
88
+ if (!attempts) workspaces.set(candidate.cwd, attempts = []);
89
+ attempts.push(candidate);
90
+ }
91
+ }
92
+ return snapshot.get(meta.sessionId)?.get(meta.cwd) ?? [];
93
+ };
94
+ return (meta, processStatus = meta.status) => assignmentFromSnapshot(meta, processStatus, options,
95
+ () => readSnapshot(meta));
96
+ }
97
+
98
+ function assignmentFromSnapshot(meta, processStatus, options, readSnapshot) {
99
+ const attempts = new Map([[meta.id, meta]]);
100
+ let current = meta;
101
+ if (meta.operations || meta.park) {
102
+ for (const candidate of readSnapshot()) {
103
+ if (candidate.sessionId === meta.sessionId && candidate.cwd === meta.cwd
104
+ && (!meta.assignment || candidate.assignment?.assignmentId === meta.assignment.assignmentId)) attempts.set(candidate.id, candidate);
105
+ }
106
+ }
72
107
  // Conversation roots survive explicit follow-ups. Only automatic resume edges
73
108
  // join attempts into one assignment; manual continuation starts a new one.
74
109
  const lineage = new Map([[meta.id, meta]]);
package/index.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  * launch is the result · completion posts back · the foreground never blocks
12
12
  */
13
13
 
14
- import { assignmentFor } from "./assignment-projection.mjs";
14
+ import { createAssignmentProjector } from "./assignment-projection.mjs";
15
15
  import { historicalWaits, attentionRevision, attentionDismissed, dismissAttention } from "./historical-attention.ts";
16
16
  import { registerAssignmentAttempt, commitAssignmentTerminal, readOutcome, receiptOutcome, outcomeTranscriptReceipt, inspectOutcome, createOutcomeHost, closeOutcomeHost, claimOutcome, type AssignmentBinding } from "./assignment-outcomes.ts";
17
17
  import { currentSandboxPermissions } from "./permission-policy.ts";
@@ -1391,7 +1391,8 @@ function navigatorRows(visible?: RunMeta[], at?: number) {
1391
1391
 
1392
1392
  /** Runs that should advertise/open the left-arrow navigator affordance. */
1393
1393
  function navigatorRunningRuns(): RunMeta[] {
1394
- return sessionVisibleNavigatorRuns().filter((m) => ["running", "waiting"].includes(assignmentFor(m, effectiveStatus(m)).state));
1394
+ const project = createAssignmentProjector();
1395
+ return sessionVisibleNavigatorRuns(Date.now(), project).filter((m) => ["running", "waiting"].includes(project(m, effectiveStatus(m)).state));
1395
1396
  }
1396
1397
 
1397
1398
  function navigatorRunningCount(): number {
@@ -1403,16 +1404,16 @@ function navigatorRunningCount(): number {
1403
1404
  * each rebuild still reads owned non-terminal metadata so external status
1404
1405
  * changes are visible immediately without a time-based memo.
1405
1406
  */
1406
- function sessionVisibleNavigatorRuns(now: number = Date.now()): RunMeta[] {
1407
+ function sessionVisibleNavigatorRuns(now: number = Date.now(), project = createAssignmentProjector()): RunMeta[] {
1407
1408
  const origin = activeCallbackOrigin;
1408
1409
  if (!origin) return [];
1409
1410
  return navigatorVisibleRuns(listMetasForOrigin(origin))
1410
1411
  .filter(belongsToActiveNavigatorSession)
1411
- .filter((m) => !isExpiredTerminalNavigatorRun(m, now));
1412
+ .filter((m) => !isExpiredTerminalNavigatorRun(m, now, project));
1412
1413
  }
1413
1414
 
1414
- function isExpiredTerminalNavigatorRun(meta: RunMeta, now: number): boolean {
1415
- const status = assignmentFor(meta, effectiveStatus(meta)).state;
1415
+ function isExpiredTerminalNavigatorRun(meta: RunMeta, now: number, project = createAssignmentProjector()): boolean {
1416
+ const status = project(meta, effectiveStatus(meta)).state;
1416
1417
  if (!isTerminalNavigatorStatus(status)) return false;
1417
1418
  const endedAt = meta.endedAt ?? meta.lostAt;
1418
1419
  return typeof endedAt === "number" && now - endedAt >= TERMINAL_NAVIGATOR_RETENTION_MS;
@@ -3232,18 +3233,13 @@ export default function (pi: ExtensionAPI) {
3232
3233
  // Register exit supervision before any fallible post-spawn publication.
3233
3234
  // A failed metadata write must not strand a running child without a close
3234
3235
  // handler; the lease stays held until that child has actually exited.
3235
- void spawned.exit.then((code) => {
3236
+ void spawned.exit.then(async (code) => {
3236
3237
  try { finalizeRun(pi, ctx, id, code); }
3237
3238
  finally { lease?.release(); }
3238
3239
  if (workerBridge) workerOperations.release(id, "attempt-exited");
3239
- // After the writer lease is free: a clean park may already have a
3240
- // ready dependency, and a failed park must hold its wait rather
3241
- // than leave an automatic resume armed.
3242
- void settleParkedExit(id);
3243
- // If this attempt was a published resume of an earlier parked
3244
- // assignment, an exit before acknowledgement must settle that
3245
- // unconsumed generation explicitly instead of leaving it resuming.
3246
- void settleResumedAttemptExit({
3240
+ // Reconcile this attempt's earlier published writer before its
3241
+ // next park can admit another continuation of the conversation.
3242
+ await settleResumedAttemptExit({
3247
3243
  attemptId: id,
3248
3244
  service: workerOperations.service,
3249
3245
  status: readMeta(id)?.status ?? "exited",
@@ -3254,6 +3250,7 @@ export default function (pi: ExtensionAPI) {
3254
3250
  try { uiCtx?.ui?.notify?.(message, "warning"); } catch { /* ignore UI failures */ }
3255
3251
  },
3256
3252
  });
3253
+ await settleParkedExit(id);
3257
3254
  });
3258
3255
  writeMeta(meta);
3259
3256
  committed = true;
package/navigator.mjs CHANGED
@@ -24,7 +24,7 @@
24
24
  * with visible-width-aware truncation.
25
25
  */
26
26
 
27
- import { assignmentFor } from "./assignment-projection.mjs";
27
+ import { assignmentFor, createAssignmentProjector } from "./assignment-projection.mjs";
28
28
  import {
29
29
  formatNavigatorHealthFacts,
30
30
  statusThemeColor,
@@ -190,8 +190,9 @@ export function pendingNavigatorPark(meta) {
190
190
 
191
191
  export function buildNavigatorRows(metas, deps) {
192
192
  const now = deps.now ?? Date.now();
193
+ const project = createAssignmentProjector();
193
194
  return metas.map((m) => {
194
- const assignment = assignmentFor(m, deps.effectiveStatus(m));
195
+ const assignment = project(m, deps.effectiveStatus(m));
195
196
  const status = assignment.state;
196
197
  const health = typeof deps.healthFor === "function" ? deps.healthFor(m) : undefined;
197
198
  const effort = typeof deps.effortFor === "function" ? deps.effortFor(m) : (m.effort ?? m.modelEffort);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.32.0",
3
+ "version": "0.32.2",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/registry.ts CHANGED
@@ -385,6 +385,8 @@ export interface ParkRecord {
385
385
  */
386
386
  resumeClaimId?: string;
387
387
  resumeClaimToken?: string;
388
+ /** Exact claim whose writer exit has been reconciled with the coordinator. */
389
+ resumeExitReconciledClaimId?: string;
388
390
  cancelledAt?: number;
389
391
  cancelReason?: string;
390
392
  }
@@ -460,7 +462,8 @@ export function writeParkRecord(id: string, record: ParkRecord, options: { ifAbs
460
462
  const meta = readMeta(id);
461
463
  if (meta && (meta.park?.phase !== record.phase
462
464
  || meta.park?.heldReason !== record.heldReason
463
- || meta.park?.resumedBy !== record.resumedBy)) {
465
+ || meta.park?.resumedBy !== record.resumedBy
466
+ || meta.park?.resumeExitReconciledClaimId !== record.resumeExitReconciledClaimId)) {
464
467
  meta.park = record;
465
468
  writeMeta(meta);
466
469
  }
@@ -500,12 +503,21 @@ export function isPendingPark(record: Pick<ParkRecord, "phase">): boolean {
500
503
  * by resume reconciliation; a consumed or cancelled park is not included.
501
504
  */
502
505
  export function listPendingParkedRuns(metas: readonly RunMeta[] = listMetas()): RunMeta[] {
503
- return metas.filter((meta) => {
506
+ return listParkRecordCandidates(metas).filter((meta) => {
504
507
  const record = meta.park ?? readParkRecord(meta.id);
505
508
  return record !== undefined && isPendingPark(record);
506
509
  });
507
510
  }
508
511
 
512
+ /** Include a park file that was published just before its metadata mirror was lost. */
513
+ export function listParkRecordCandidates(metas: readonly RunMeta[] = listMetas()): RunMeta[] {
514
+ let volatileIds: Set<string>;
515
+ try { volatileIds = new Set(readdirSync(join(baseDir(), "runs"))); }
516
+ catch { volatileIds = new Set(); }
517
+ return metas.filter((meta) => meta.park !== undefined
518
+ || (volatileIds.has(meta.id) && existsSync(parkRecordPath(meta.id))));
519
+ }
520
+
509
521
  /**
510
522
  * How long a launch attempt that never produced a child is kept before a sweep
511
523
  * reclaims it. Launch preparation takes seconds; the grace only exists so a
@@ -484,7 +484,7 @@ export interface ReleaseResumeClaimResult {
484
484
  }
485
485
 
486
486
  /**
487
- * Proof that the published resume attempt can never interpret the generation:
487
+ * Proof that the published resume attempt can no longer write the conversation:
488
488
  * its writer process is gone and its conversation writer lease is free. A live
489
489
  * writer or an unverifiable identity must never be passed here.
490
490
  */
@@ -499,6 +499,8 @@ export interface ResumeAttemptExitProof {
499
499
  * evidence pins stay, and the generation remains visible to its owner. The claim
500
500
  * is invalidated (it can never publish again), which is what makes a second
501
501
  * automatic attempt impossible.
502
+ * If interpretation already consumed the wait, exact exit proof only invalidates
503
+ * the published writer claim and preserves the interpretation receipt.
502
504
  */
503
505
  export interface HoldFailedResumeInput {
504
506
  waitId: string;
@@ -508,7 +510,7 @@ export interface HoldFailedResumeInput {
508
510
  attemptId: string;
509
511
  launchToken: string;
510
512
  proof: ResumeAttemptExitProof;
511
- /** Why the attempt never interpreted the generation; retained on both records. */
513
+ /** Exit reason; a consumed generation's receipt is preserved. */
512
514
  reason: string;
513
515
  }
514
516
 
@@ -913,10 +913,14 @@ export function holdFailedResume(
913
913
 
914
914
  return ctx.transaction(() => {
915
915
  const terminal = getRow(ctx, "SELECT assignment_id FROM assignment_outcome_waits WHERE wait_id = ? AND generation = ?", waitId, generation);
916
- if (terminal) {
916
+ const recorded = requireWait(ctx, waitId, generation);
917
+ // Interpretation ends the wait, but its writer may continue until exit.
918
+ // Exact exit proof releases only that writer's claim, preserving the receipt.
919
+ if (terminal || recorded.phase === "consumed") {
917
920
  const claim = requireClaim(ctx, claimId);
918
921
  if (claim.waitId !== waitId || claim.generation !== generation || claim.claimToken !== claimToken
919
922
  || claim.attemptId !== attemptId || claim.launchToken !== launchToken) throw new StoreError("claim-state", "Terminal writer exit proof does not match the published attempt.");
923
+ if (!terminal && claim.cancelEpoch !== recorded.cancelEpoch) throw new StoreError("stale-cancel-epoch", "Writer exit proof belongs to a different cancellation epoch.");
920
924
  const applied = claim.state === "published";
921
925
  if (applied) run(ctx, "UPDATE resume_claims SET state = 'invalidated', invalidated_at = ?, reason = ? WHERE claim_id = ?", ctx.now(), reason, claimId);
922
926
  return { wait: requireWait(ctx, waitId, generation), claim: requireClaim(ctx, claimId), applied };
package/worker-waits.ts CHANGED
@@ -61,6 +61,7 @@ import { commitAssignmentTerminal } from "./assignment-outcomes.ts";
61
61
  import {
62
62
  effectiveStatus,
63
63
  isPendingPark,
64
+ listParkRecordCandidates,
64
65
  listMetas,
65
66
  listPendingParkedRuns,
66
67
  readMeta,
@@ -2278,7 +2279,7 @@ export async function recoverStagedPark(
2278
2279
  /** Every park record (any phase) that published `attemptId` as its resume. */
2279
2280
  export function parkedWaitsForResumedAttempt(attemptId: string): ParkedWait[] {
2280
2281
  const found: ParkedWait[] = [];
2281
- for (const meta of listMetas()) {
2282
+ for (const meta of listParkRecordCandidates()) {
2282
2283
  const record = readParkRecord(meta.id);
2283
2284
  if (!record || record.resumedBy !== attemptId) continue;
2284
2285
  found.push(parkedEntry(meta, record));
@@ -2339,24 +2340,31 @@ export function conversationWriterLeaseLive(
2339
2340
  * ambiguous identity (live or unverifiable writer, live lease, missing claim
2340
2341
  * identity, missing host capability) is reported as a local hold and the durable
2341
2342
  * generation is left untouched with its live writer — never a fallback cancel.
2343
+ * An interpreted generation needs only claim cleanup; its receipt and assignment
2344
+ * remain unchanged, even if writer exit cannot yet be proved.
2342
2345
  */
2343
2346
  export async function settleResumedAttemptExit(input: ResumedAttemptExitInput): Promise<ResumedAttemptExitResult> {
2344
- const candidates = parkedWaitsForResumedAttempt(input.attemptId);
2347
+ return settleResumedAttemptExitForParks(input, parkedWaitsForResumedAttempt(input.attemptId));
2348
+ }
2349
+
2350
+ async function settleResumedAttemptExitForParks(input: ResumedAttemptExitInput, candidates: readonly ParkedWait[]): Promise<ResumedAttemptExitResult> {
2345
2351
  if (candidates.length === 0) return { outcome: "ignored" };
2346
2352
  const attempt = readMeta(input.attemptId);
2347
2353
  const at = (input.now ?? Date.now)();
2348
2354
  let result: ResumedAttemptExitResult = { outcome: "ignored" };
2349
2355
  for (const park of candidates) {
2350
- if (park.record.phase === "consumed" || (park.record.phase === "cancelled" && !park.meta.assignment)) {
2356
+ if ((park.record.phase === "consumed" && park.record.resumeClaimId && park.record.resumeExitReconciledClaimId === park.record.resumeClaimId)
2357
+ || (park.record.phase === "cancelled" && !park.meta.assignment)) {
2351
2358
  result = { outcome: "ignored", waitPhase: park.record.phase };
2352
2359
  continue;
2353
2360
  }
2354
- const reason = input.reason
2355
- ?? `the published resume attempt ${input.attemptId} exited (${input.status ?? attempt?.status ?? "unknown"}) without interpreting the wait`;
2361
+ let interpreted = park.record.phase === "consumed";
2362
+ const exitReason = `the published resume attempt ${input.attemptId} exited (${input.status ?? attempt?.status ?? "unknown"})`;
2363
+ let reason = input.reason ?? `${exitReason}${interpreted ? "" : " without interpreting the wait"}`;
2356
2364
  const holdLocally = (cause: string, outcome: "deferred" | "settled" = "deferred"): void => {
2357
- updateParkRecord(park.runId, { phase: park.record.phase === "cancelled" ? "cancelled" : "held", heldReason: `${reason}; ${cause}` });
2365
+ updateParkRecord(park.runId, { phase: interpreted ? "consumed" : park.record.phase === "cancelled" ? "cancelled" : "held", heldReason: `${reason}; ${cause}` });
2358
2366
  const report = attempt ?? park.meta;
2359
- if (input.service && report.assignment) {
2367
+ if (!interpreted && input.service && report.assignment) {
2360
2368
  commitAssignmentTerminal({ ...report, status: "lost", failureReason: `${reason}; ${cause}` }, true);
2361
2369
  }
2362
2370
  result = { outcome, reason };
@@ -2385,6 +2393,20 @@ export async function settleResumedAttemptExit(input: ResumedAttemptExitInput):
2385
2393
  retainUnverified("the Background operation service is unavailable");
2386
2394
  continue;
2387
2395
  }
2396
+ const scope = backgroundScopeForMeta(park.meta, park.record);
2397
+ if (!scope) {
2398
+ holdLocally("the parked attempt records no worker conversation scope");
2399
+ continue;
2400
+ }
2401
+ let wait: WorkerWaitView | undefined;
2402
+ try {
2403
+ wait = input.service.listWorkerWaits(scope).find((w) => w.waitId === park.waitId && w.generation === park.generation);
2404
+ interpreted = wait?.phase === "consumed" || interpreted;
2405
+ if (interpreted && !input.reason) reason = exitReason;
2406
+ } catch (error) {
2407
+ retainUnverified(`the coordinator could not verify the wait (${reasonOf(error)})`);
2408
+ continue;
2409
+ }
2388
2410
  if (typeof input.service.holdFailedResumeForWorker !== "function") {
2389
2411
  holdLocally("this Background host has no proven-exit hold capability yet");
2390
2412
  continue;
@@ -2415,15 +2437,9 @@ export async function settleResumedAttemptExit(input: ResumedAttemptExitInput):
2415
2437
  holdLocally("a live conversation writer lease still holds the history, so writer exit is unproven");
2416
2438
  continue;
2417
2439
  }
2418
- const scope = backgroundScopeForMeta(park.meta, park.record);
2419
- if (!scope) {
2420
- holdLocally("the parked attempt records no worker conversation scope");
2421
- continue;
2422
- }
2423
2440
  try {
2424
- const wait = input.service.listWorkerWaits(scope).find((w) => w.waitId === park.waitId && w.generation === park.generation);
2425
2441
  // A held terminal writer needs proof-only reconciliation, not admission.
2426
- const reconcileOnly = park.record.phase === "cancelled" || wait?.phase === "held";
2442
+ const reconcileOnly = interpreted || park.record.phase === "cancelled" || wait?.phase === "held";
2427
2443
  if (!reconcileOnly && attempt.assignment && !input.service.repairFailedResumeForWorker) {
2428
2444
  holdLocally("this Background host does not support bounded autonomous repair");
2429
2445
  continue;
@@ -2456,9 +2472,11 @@ export async function settleResumedAttemptExit(input: ResumedAttemptExitInput):
2456
2472
  const phase = phaseOf(held.phase);
2457
2473
  updateParkRecord(park.runId, {
2458
2474
  phase: park.record.phase === "cancelled" ? "cancelled" : phase,
2475
+ resumeExitReconciledClaimId: claimId,
2476
+ ...(phase === "consumed" ? { heldReason: undefined } : {}),
2459
2477
  ...(phase === "held" && park.record.phase !== "cancelled" ? { heldReason: reason } : {}),
2460
2478
  });
2461
- input.notify?.(`Subagent ${park.runId}: ${reason}. The reconciled wait is ${phase}.`, "warning");
2479
+ if (phase !== "consumed") input.notify?.(`Subagent ${park.runId}: ${reason}. The reconciled wait is ${phase}.`, "warning");
2462
2480
  result = { outcome: "settled", waitPhase: phase, reason };
2463
2481
  } catch (error) {
2464
2482
  // The store refused (stale identity, terminal generation, unproven exit).
@@ -2520,8 +2538,8 @@ export async function reconcileParkedWaits(
2520
2538
  }
2521
2539
  const cached = readParkRecord(report.meta.id);
2522
2540
  const cancelled = (cached ?? report.record).phase === "cancelled";
2523
- if (cancelled && report.attempt && current.publishedClaimId === report.record.resumeClaimId) {
2524
- // Cancellation invalidates execution admission, not exact writer-exit proof.
2541
+ if ((cancelled || current.phase === "consumed") && report.attempt && current.publishedClaimId === report.record.resumeClaimId) {
2542
+ // Terminal waits still retain independent writer-exit proof.
2525
2543
  if (!readMeta(report.meta.id)) writeMeta(report.meta, { ifAbsent: true });
2526
2544
  if (!cached) writeParkRecord(report.meta.id, report.record, { ifAbsent: true });
2527
2545
  if (!readMeta(report.attempt.id)) writeMeta(report.attempt, { ifAbsent: true });
@@ -2568,13 +2586,26 @@ export async function reconcileParkedWaits(
2568
2586
  options.notify?.(`Degraded supervision: outage replay unavailable (${reasonOf(error)}).`, "warning");
2569
2587
  }
2570
2588
  }
2571
- for (const park of parkedWaits()) {
2589
+ // Consumed waits cannot resume, but a missed exit observer may have left
2590
+ // their published writer claim behind. Reconcile that exact claim once.
2591
+ const candidates: ParkedWait[] = [];
2592
+ for (const meta of listParkRecordCandidates()) {
2593
+ const snapshot = meta.park ?? readParkRecord(meta.id);
2594
+ if (!snapshot || (!isPendingPark(snapshot) && !(snapshot.phase === "consumed" && snapshot.resumedBy
2595
+ && snapshot.resumeClaimId && snapshot.resumeExitReconciledClaimId !== snapshot.resumeClaimId))) continue;
2596
+ const record = readParkRecord(meta.id);
2597
+ if (record) candidates.push(parkedEntry(meta, record));
2598
+ }
2599
+ // Release earlier writers before admitting later waits in the conversation.
2600
+ candidates.sort((a, b) => a.record.parkedAt - b.record.parkedAt);
2601
+ for (const park of candidates) {
2572
2602
  const options = scopedOptions(park.meta);
2573
2603
  try {
2574
- if (park.record.phase === "resuming") {
2604
+ if (park.record.phase === "resuming" || park.record.phase === "consumed") {
2575
2605
  const attemptId = park.record.resumedBy ?? "";
2576
2606
  const attempt = attemptId ? readMeta(attemptId) : undefined;
2577
2607
  if (!attemptId || !attempt) {
2608
+ if (park.record.phase === "consumed") { skipped += 1; continue; }
2578
2609
  updateParkRecord(park.runId, {
2579
2610
  phase: "held",
2580
2611
  heldReason: `Resume attempt ${attemptId || "(unknown)"} was published but launch and writer identity remain unproven.`,
@@ -2587,19 +2618,21 @@ export async function reconcileParkedWaits(
2587
2618
  held += 1;
2588
2619
  continue;
2589
2620
  }
2590
- // The published attempt already ended without acknowledging: settle the
2591
- // unconsumed generation now instead of leaving it `resuming` forever.
2592
- if (isTerminalAttempt(attempt)) {
2593
- const settled = await settleResumedAttemptExit({
2621
+ // A missed exit needs either unconsumed-wait recovery or proof-only
2622
+ // cleanup of a consumed wait's writer claim.
2623
+ const consumedWriterGone = park.record.phase === "consumed" && attempt.pid > 0 && writerPresence(attempt) === "absent";
2624
+ if (isTerminalAttempt(attempt) || consumedWriterGone) {
2625
+ const settled = await settleResumedAttemptExitForParks({
2594
2626
  attemptId,
2595
2627
  service,
2596
2628
  status: effectiveStatus(attempt),
2597
2629
  ...(options.notify ? { notify: options.notify } : {}),
2598
- });
2599
- if (settled.outcome === "settled") held += 1;
2630
+ }, [park]);
2631
+ if (settled.outcome === "settled" && settled.waitPhase !== "consumed") held += 1;
2600
2632
  else skipped += 1;
2601
2633
  continue;
2602
2634
  }
2635
+ if (park.record.phase === "consumed") { skipped += 1; continue; }
2603
2636
  }
2604
2637
  if (!service) {
2605
2638
  let reason = "Coordinator state is unverified; awaiting compatible supervision.";
@@ -2628,6 +2661,10 @@ export async function reconcileParkedWaits(
2628
2661
  }
2629
2662
  if (wait.phase === "consumed" || wait.phase === "cancelled") {
2630
2663
  updateParkRecord(park.runId, { phase: phaseOf(wait.phase), heldReason: undefined });
2664
+ if (wait.phase === "consumed" && park.record.resumedBy) {
2665
+ await settleResumedAttemptExitForParks({ attemptId: park.record.resumedBy, service,
2666
+ ...(options.notify ? { notify: options.notify } : {}) }, [park]);
2667
+ }
2631
2668
  skipped += 1;
2632
2669
  continue;
2633
2670
  }
@@ -2638,12 +2675,12 @@ export async function reconcileParkedWaits(
2638
2675
  const attemptId = park.record.resumedBy ?? "";
2639
2676
  const attempt = attemptId ? readMeta(attemptId) : undefined;
2640
2677
  if (!attempt || isTerminalAttempt(attempt)) {
2641
- const settled = await settleResumedAttemptExit({
2678
+ const settled = await settleResumedAttemptExitForParks({
2642
2679
  attemptId: attemptId || park.runId,
2643
2680
  service,
2644
2681
  status: attempt ? effectiveStatus(attempt) : "missing",
2645
2682
  ...(options.notify ? { notify: options.notify } : {}),
2646
- });
2683
+ }, [park]);
2647
2684
  // `deferred` means the local record was held while the durable
2648
2685
  // generation could not be proven (ambiguous identity/capability);
2649
2686
  // it is never a silent success.