Skip to content

hub: generation-keyed durable live-work (#2658) - #2659

Open
heavygee wants to merge 59 commits into
tiann:mainfrom
heavygee:feat/live-work-by-generation
Open

heavygee wants to merge 59 commits into
tiann:mainfrom
heavygee:feat/live-work-by-generation

Conversation

@heavygee

@heavygee heavygee commented Nov 28, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Add metadata.liveWorkByGeneration keyed by reporting machineId:hostPid:hostStartMarker so durable live-work survives worker replacement without stranding or ignoring a prior generation.
  • Clear refinement (Clear live-work generations only on authoritative exit events #2697): a generation's durable latch clears only on an authoritative exit for that exact owner. A stamped session-end is the generation-bound terminal record. Wrapper session-child-exited clears only when childExitMayClearGeneration holds (no Codex flavor, no sticky descendantsRegistered / open-tool / background descendants); otherwise child-exit strands. Each clear writes hub-owned metadata.liveWorkGenerationExits[ownerKey], then drops that owner's latch, pending requests, and transient/derived bits. Same generation-keyed approach already assessed: the clear path is narrowed from "PID+marker probe verifies exit" to "exit record exists for that owner," then narrowed again so wrapper exit is not treated as generation-bound completion.
  • Platform scope: the durable Archive refuse does not apply on Windows (metadata.platform === 'win32'). Windows keeps merge-base KillSession / StopSession cleanup until launch-time tree containment lands (Windows: launch-time process-tree containment for generation-keyed ProbeSessionExit #2660).
  • Read-path projects legacy unresolvedTurn / backgroundWork when the keyed map is absent. Empty-map clears use the hub-owned null sentinel.
  • Durable tool work tracks openToolCallIds per owner; matching results retire that id only (#2673). Synthetic ACP cancel publish is not in this PR.

Fixes #2657.
Fixes #2658.
Fixes #2697.
Fixes #2672.
Fixes #2673.

Approach (refinement of generation-keyed clear)

The generation-keyed model stands. What changed is what counts as proof that a generation may be cleared.

What this contract guarantees

  • Never clear a durable generation on a probe sample (either direction).
  • Never clear on wrapper child-exit when the generation may still own descendants (Codex app-server / registered tool or background children).
  • Clear only when a matching liveWorkGenerationExits record exists from stamped session-end, or from child-exit under childExitMayClearGeneration.
  • POSIX Archive refuses (archive-session-working) while a durable generation has no exit record - kill-direction fail-closed relative to main's unguarded KillSession.
  • Windows Archive is merge-base parity (not worse than main) until Windows: launch-time process-tree containment for generation-keyed ProbeSessionExit #2660.

What it strands (intentionally)

  • Prior generation whose runner died with no exit event and no generation-bound terminal record.
  • Wrapper child-exit when descendants were registered (or Codex flavor) - wrapper exit ≠ generation-bound completion.
  • POSIX durable work without an exit record, even if a probe says already_gone.

Route out

Authoritative (may clear)

  • a worker-stamped session-end for that generation (generation-bound terminal record)
  • wrapper child-exit only if childExitMayClearGeneration (no Codex; no sticky descendants / open-tool / bg descendants)
  • the resulting generation-matched exit record in liveWorkGenerationExits

Never authoritative (samples - must not clear, either direction)

  • ProbeSessionExit already_gone / stopped / still_alive / unknown
  • process-group scans, /proc reads, heartbeat gaps, empty snapshots, Codex registry lookups
  • wrapper child-exit when descendants may survive

A probe is not proof of absence and not proof of presence for clear decisions. Blocking on uncertainty remains safe, but the refusal reason is no exit record, not "we looked and it seemed alive." Positive still_alive is not a clear path.

Named boundary - terminal asks (#2662)

Consult ≠ clear. Archive / reconcile may still consult a ProbeSessionExit sample for terminal pending-ask UX (e.g. whether to keep waiting). That sample must never drift into clear authority for a generation latch or for retiring durable live-work. Operator recovery for abandoned standalone-terminal asks remains #2662; ordinary Archive stays fail-closed through reconnects.

Draft PR #2699 carried an early cut of this refinement and is closed as superseded by this tip (2247ade26 on feat/live-work-by-generation).

Bounded limitations (not main-worse regressions)

These remain open as gaps in new behaviour. Main has no generation cutoff and no keyed transcript latch, so neither is "main archives / tip refuses or destroys" on a shared Archive path. Tracked rather than fixed here:

Limitation Tracked Regression-test result
Tool ingest can read generation cutoff from a ~1s stale socket snapshot after replacement #2701 Tip-only; main has no cutoff
Interleaved owners can bypass tool-call transcript compaction (index growth) #2702 Tip-only; neither refuses Archive nor destroys vs main

Costs (operator-approved severance)

Windows retains merge-base archive behaviour pending #2660. Hub omits Windows durables from Archive refuse so unplanned exits fall through to today's KillSession / StopSession path. Stamped Windows permission requests are omitted from the in-memory Archive guard only and cleared after confirmed Stop/Kill on that machine (or on generation-matched exit); another machine's stamped wait is not erased. Unstamped Windows Runner asks omit from the guard and clear only after confirmed Stop. Windows is not worse than main on abandoned-permission Archive.

User-Stop Archive on ACP can refuse until the cancel-wire follow-up lands (#2696). Hub per-owner openToolCallIds + matching-result settlement stay; without a confirmed cancel publish, an open call id can keep Archive refused after Stop until that wire ships.

Accepted trade

Archive checks for live work before shutdown and refuses when a durable generation has no exit record - where the refuse applies (POSIX). At the merge base, Archive called KillSession with no live-work guard. Covered POSIX paths are strictly better than main on the kill direction. Windows is exactly as good as today (merge-base cleanup), not worse.

This tip must not manufacture permanent failed archives for sessions that main could clean up except where the strand is intentional and documented (no exit event; route named above). Fail-open clears of live terminal work remain defects.

Platform scope (not a gap)

Platform Durable Archive refuse Cleanup
POSIX (linux/darwin/…) On - refuse while no exit record for durable owners Clear after authoritative exit record
Windows (win32) Off until #2660 Merge-base KillSession / StopSession

Still deferred (different subsystems)

Surface Tracked
Windows launch-time tree containment / generation-bound tree-exit tombstones #2660
ACP cancel wire (confirmed cancel retires openToolCallIds on Stop) #2696
Markerless terminal scan after PID reuse (fail-open KillSession risk) #2671
Standalone terminal abandoned permission asks (operator recovery) #2662
Sticky orphan after rewind / worker replace #2668
History-merge transcript cutoff translation #2669
Permanent archive-cleanup-unconfirmed after prior Runner #2408
Stale socket snapshot for generation cutoff #2701
Interleaved-owner tool-call compaction #2702

Acceptance criteria (must not regress when #2021 rebases)

  • POSIX: prior generation with durable work and no exit record → Archive refuses (archive-session-working); stop RPCs not started for that refuse. Probe already_gone alone does not clear.
  • POSIX: prior generation + stamped session-end → exit record; that owner's entry cleared. Wrapper child-exit clears only under childExitMayClearGeneration; otherwise strands.
  • Windows: session with outstanding durable work + unplanned complete exit → Archive proceeds via merge-base StopSession (not permanent 409).
  • Offline terminal with unfinished transcript call → Archive can proceed.
  • Live terminal open call + prior runner authoritative exit → Archive still refuses; unattributed derivedToolWork preserved.
  • Concurrent ACP calls: settling call-b does not clear an aged-out call-a latched via openToolCallIds.
  • idleReconcileExempt alone does not block explicit Archive; metadata.waiting still does.
  • Terminal-asks may consult a probe sample; that sample never authorizes generation clear (hub: operator recovery for abandoned standalone-terminal permission asks #2662 boundary).
  • Markerless terminal background expires on BACKGROUND_STALE_MS while a replacement stays online.
  • Stop on this machine does not erase another machine's stamped Windows pending ask.

Non-goals

Test plan

  • hub archive: strand without exit record even if probe says already_gone; clear on session-end; child-exit strands for Codex / open-tool descendants; unresolvedTurn-only child-exit still clears
  • hub archive: Windows cross-machine ask preserved; unstamped Windows Runner ask archives after Stop; markerless bg expires
  • hub archive / idle / getLiveToolWork / sessionCache (call-id, owner-scoped clear, exit records)
  • vitest run.stopSession / process Linux state-axis + successor-churn (probe hardening retained; no longer clear-authority)
  • bun run typecheck hub + cli
  • CI green on tip 2247ade26
  • Operator attestation (cold-review-clean / dogfooded) then Meta Gate A merge

Replace single-slot unresolvedTurn/backgroundWork with liveWorkByGeneration
keyed by hostStartMarker so archive can refuse or clear per worker generation.
Runner-owned rows probe PID+marker via ProbeSessionExit before clearing;
empty-map clears use the hub-owned null sentinel. Closes tiann#2657.

Co-authored-by: Cursor <[email protected]>
@github-actions github-actions Bot added the codex-review:changes HAPI Bot: review requests changes label Nov 28, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: initial

Requirement — Pass

Archive needs to retain evidence of a prior worker’s live work after a replacement registers. It should refuse before issuing stop RPCs while the prior owner may still be running and proceed once that owner’s exit is verified.

Evidence

  • Issues #2657 and #2658 describe how a replacement can hide a prior worker’s live work and how a stale latch can strand an otherwise archivable session.
  • Base hub/src/sync/syncEngine.ts:3832 starts archive cleanup without checking prior-generation work. Its runner fallback at line 3880 is a stop operation.

Approach — Needs changes

A read-only probe before Archive is a sound direction. The proposed write path assigns work to the current session owner instead of the worker that reported it. It also persists blocking work for terminal sessions without an exit reconciliation path for those sessions.

Evidence

  • Heartbeats and background-task snapshots reach the hub without a reporting generation, and the cache takes the marker from the current row. After B registers, a late report from A can write under B. B’s next idle heartbeat can then erase the only record of A’s live turn, letting Archive start cleanup. See hub/src/socket/handlers/cli/sessionHandlers.ts:199 and :467 and hub/src/sync/sessionCache.ts:919.
  • On Unix, the marker is a process start time with second-level precision. Processes started in the same second can share it, so a marker-only key can merge work from distinct PIDs or machines. See cli/src/utils/process.ts:125 and hub/src/sync/sessionCache.ts:925.
  • Terminal sessions ordinarily omit the marker. A terminal CLI that crashes during a turn leaves an unknown-generation latch that survives heartbeat expiry. Archive counts that latch but only probes runner-owned sessions, so it keeps returning 409 after the terminal process has exited. See cli/src/agent/sessionFactory.ts:133, hub/src/sync/sessionCache.ts:1275, and hub/src/sync/syncEngine.ts:3860.

Suggestions

  • Bind heartbeat and background-task reports to the originating worker’s registered generation. Key entries by machine, PID, and start marker, and clear only the exact owner for which the runner verified exit.
  • Keep terminal and other non-runner sessions on their transient work lifecycle unless they have a way to reconcile durable entries after exit. Preserve the requested legacy read-path guard.

Code — Not reviewed

Code review stopped at the approach stage because generation attribution and exit reconciliation need design changes.

Testing

Not run (automation; PR code execution is prohibited).

  • At the fixed head, GitHub reported success for core, unit-cli, wrapper-parity, windows-codex-mcp, and drift-gate. Integration, unit-web, browser, and pr-review were in progress when checked.
  • The Archive tests seed the generation map and stub the exit probe. They do not cover work reports from overlapping workers or Archive after a terminal CLI exits mid-turn. No PR code or tests were run during this review.

HAPI Bot

Attribute durable latches to the keepalive's hostPid+marker, not the
current row; key owners as machineId:hostPid:hostStartMarker; skip
durable writes for terminal/unmarked reports so Archive cannot strand
non-runner rows. Addresses remasure Approach on tiann#2659.

Co-authored-by: Cursor <[email protected]>
@heavygee

Copy link
Copy Markdown
Collaborator Author

Addressed the Approach findings on tip 633a3fd1a:

  1. Report-bound attribution — session-alive now carries hostPid + processStartMarker; durable upserts/clears bind to that owner only. A late prior-worker heartbeat cannot write under the replacement, and the replacement's idle heartbeat cannot erase the prior latch. Unmarked heartbeats skip durable write/clear.
  2. Owner key — machineId:hostPid:hostStartMarker (hostStartMarker remains the generation identity; pid+machine complete the probe owner so same-second markers cannot merge distinct PIDs).
  3. Terminal / non-runner — durable liveWorkByGeneration writes are runner-owned only. Terminal stays on transient thinking/backgroundTasks, so Archive is not stranded after a mid-turn terminal exit.

New coverage: sessionCache.liveWork.test.ts (late A after B; terminal no latch; unmarked idle preserves prior). Prior #2658 archive refuse/clear cases updated to owner keys.

@github-actions github-actions Bot removed the codex-review:changes HAPI Bot: review requests changes label Nov 28, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: follow-up after new commits

Requirement — Pass

Archive should retain evidence of a replaced worker’s live work, refuse before issuing stop RPCs while that worker may still be running, and proceed once its exit is verified and no other work blocks Archive.

Evidence

  • Issues #2657 and #2658 describe the two failure modes: ignoring work from a prior owner and leaving Archive blocked after that owner exits.
  • On the base commit, heartbeat expiry clears transient work in hub/src/sync/sessionCache.ts:1181, and Archive starts with KillSession in hub/src/sync/syncEngine.ts:3857.

Approach — Needs changes

The per-owner map and read-only preflight fit the requirement. The write and legacy projection paths still infer ownership from the current row, so Archive can discard a prior worker’s live-work evidence without verifying that worker’s exit.

Evidence

  • Background snapshots carry only the session ID and tasks into the cache (hub/src/socket/handlers/cli/sessionHandlers.ts:199). After B registers, a late nonempty snapshot from A is stored under B’s PID and marker. An empty snapshot from B can then erase it while A is still working (hub/src/sync/sessionCache.ts:878).
  • Heartbeats now supply the sender’s PID and marker, but the cache still takes machineId from the current row. If the replacement changes machines, a late report can pair A’s PID and marker with B’s machine (shared/src/socket.ts:272, hub/src/sync/sessionCache.ts:956).
  • Legacy projection can pair A’s latch marker with B’s current PID. If B has exited while A is still alive, the probe reports B’s absent PID as already_gone and Archive clears A’s latch (hub/src/sync/liveWorkByGeneration.ts:98, cli/src/runner/run.ts:1775, hub/src/sync/syncEngine.ts:3889).

Suggestions

  • Bind heartbeat and background-task snapshots to the reporting worker’s registered machine, PID, and start marker. Apply updates and clears only to that owner’s entry.
  • Keep legacy latches blocking when their owner cannot be established. Allow probe-based clearing only when the projected machine, PID, and marker are known to identify the worker that produced the latch.

Code — Not reviewed

Code review stopped at the approach stage because the guard depends on reliable owner attribution.

Testing

Not run (automation; PR code execution is prohibited).

  • At head 633a3fd, GitHub reported core and drift-gate passed. Integration, unit-cli, unit-web, wrapper-parity, windows-codex-mcp, browser, and pr-review were in progress.
  • The attribution test covers same-machine heartbeats, and the Archive tests seed prior-owner entries and stub the probe. The added coverage does not exercise overlapping background snapshots or a legacy latch whose marker differs from the current owner’s. This review was static.

HAPI Bot

@github-actions github-actions Bot added the codex-review:changes HAPI Bot: review requests changes label Nov 28, 2026
KeepAlive carries machineId; durable writes never take owner fields from
the current row. Background snapshots stay in-memory only until they can
carry a reporting owner. Legacy projection refuses to pair a prior latch
marker with the replacement's pid. Refresh Claude parity goldens for the
new session-alive fields.

Co-authored-by: Cursor <[email protected]>
@heavygee

Copy link
Copy Markdown
Collaborator Author

Follow-up on tip 4d0ab68ce for the remaining Approach points:

  1. Background snapshots — no longer durable-latch under the current row. In-memory session.backgroundTasks only until snapshots can carry a reporting owner (avoids late A nonempty / B empty erase).
  2. machineId — keepAlive now reports machineId; durable upserts take machine/pid/marker exclusively from the report, never the current row (cross-machine late A covered in tests).
  3. Legacy projection — only attaches current-row pid/machine when the latch marker still matches hostStartMarker. Otherwise the latch stays blocking and is not probe-clearable (no pairing A marker with B pid).

Parity goldens refreshed for the new session-alive fields (fixes wrapper-parity).

@github-actions github-actions Bot removed the codex-review:changes HAPI Bot: review requests changes label Nov 28, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: follow-up after new commits

Requirement — Pass

Archive should retain a replaced runner worker’s live-work evidence, refuse before issuing stop RPCs while that worker is still alive, and proceed once its exit is verified and other work has cleared.

Evidence

  • Issues #2657 and #2658 describe how a single slot can either hide a prior worker’s live work or leave Archive blocked after that worker exits.
  • On the base commit, heartbeat expiry clears transient work at hub/src/sync/sessionCache.ts:1187, and Archive starts cleanup with KillSession at hub/src/sync/syncEngine.ts:3857.

Approach — Needs changes

The per-owner map and read-only preflight fit the requirement. The write path still leaves background work transient and derives heartbeat ownership from mutable session metadata.

Evidence

  • Antigravity publishes commands still running at the end of a turn and then reports thinking=false (cli/src/agy/agyAcpRemoteLauncher.ts:1483 and :1429). The hub stores those snapshots only in memory, and heartbeat expiry clears them (hub/src/sync/sessionCache.ts:881 and :1340). A live prior worker whose only remaining work is a background command can therefore lose its Archive guard before any exit probe runs.
  • Heartbeat identity comes from this.metadata (cli/src/api/apiSession.ts:1378), which the client replaces with accepted updates to the shared session row (cli/src/api/apiSession.ts:905). Replacement bootstrap also constructs the client from the existing row before updating it with the local worker’s metadata (cli/src/agent/sessionFactory.ts:468). The reported tuple can therefore describe a different worker from the sender whose work is being recorded or cleared.

Suggestions

  • Capture the worker’s machine, PID, and start marker from its local runner registration and keep that tuple stable across session metadata refreshes. Attach it to both heartbeats and background snapshots, and persist or clear each signal only under its reporting owner.

Code — Not reviewed

Code review stopped at the approach stage because the preflight depends on durable work reports with reliable worker attribution.

Testing

Not run (automation; PR code execution is prohibited).

  • Static review only. No PR code or tests were run.
  • The added Archive tests seed prior-owner turn entries, and the attribution tests supply owner tuples directly. They leave background-only work across expiry and sender identity across a metadata refresh unverified.
  • For head 4d0ab68, GitHub reported core, drift-gate, and windows-codex-mcp passed. Unit CLI, unit web, integration, wrapper parity, browser, and PR review were in progress at the time of inspection.

HAPI Bot

@github-actions github-actions Bot added the codex-review:changes HAPI Bot: review requests changes label Nov 28, 2026
Freeze hostPid/start-marker from the OS process at ApiSessionClient
construct time so metadata refreshes after replacement cannot re-attribute
heartbeats. Stamp reportingOwner on background_tasks_changed messages and
durable-latch attributed snapshots under that owner only.

Co-authored-by: Cursor <[email protected]>
@heavygee

Copy link
Copy Markdown
Collaborator Author

Tip $(git rev-parse --short HEAD) addresses the remaining Approach points:

  1. Stable sender identity — localWorkerIdentity is frozen from process.pid + getProcessStartMarker at ApiSessionClient construct; keepAlive never takes pid/marker from refreshed session metadata.
  2. Attributed background snapshots — sendAgentMessage stamps reportingOwner on background_tasks_changed; hub durable-latches under that owner only. Empty B snapshot cannot erase A's bg latch. Unmarked snapshots stay in-memory.

@heavygee

Copy link
Copy Markdown
Collaborator Author

Correction: tip is d12d230ae (prior comment mangled the short SHA).

@github-actions github-actions Bot added codex-review:changes HAPI Bot: review requests changes and removed codex-review:changes HAPI Bot: review requests changes labels Nov 28, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: follow-up after new commits

Requirement — Pass

Archive should retain evidence of a replaced runner worker’s live work, refuse before sending stop RPCs while that worker is alive, and proceed once the worker’s exit is verified and other work has cleared.

Evidence

  • Issues #2657 and #2658 explain how a single slot can either hide a prior worker’s live work or leave Archive blocked after that worker exits.
  • On the base commit, heartbeat expiry clears transient work at hub/src/sync/sessionCache.ts:1187, and Archive starts cleanup with KillSession at hub/src/sync/syncEngine.ts:3857.

Approach — Needs changes

The per-worker map and read-only Archive preflight fit the requirement. The report path still lets a replacement inherit the previous worker’s identity fields, and the background snapshots used by Claude and Antigravity remain transient.

Evidence

  • cli/src/agent/sessionFactory.ts:449 builds the replacement’s local metadata, but :470 constructs the client from the existing session row before publishing the replacement metadata. cli/src/api/apiSession.ts:283 takes machineId and the fallback start marker from that row, and :1267 only corrects the machine after matching metadata arrives. A cross-machine resume can therefore record work under the wrong runner before the update is acknowledged, leaving Archive to probe a PID on the wrong machine.
  • Antigravity sends background snapshots through sendClaudeSessionMessage at cli/src/agy/agyAcpRemoteLauncher.ts:2141, and Claude forwards SDK output through the same method at cli/src/claude/claudeRemoteLauncher.ts:1006. That method emits without reportingOwner at cli/src/api/apiSession.ts:1178. The hub requires an owner to persist the snapshot at hub/src/sync/sessionCache.ts:895 and clears the transient count on heartbeat expiry at :1351. A prior worker whose only remaining work is a background command can lose its Archive guard before any exit probe runs.

Suggestions

  • Pass the locally registered machine ID, PID, and start marker from runner bootstrap into the session client before it connects. Keep that tuple independent of session metadata refreshes and use it for heartbeats and the background snapshots emitted through sendClaudeSessionMessage.

Code — Not reviewed

Code review stopped at the approach stage because Archive’s preflight depends on durable reports attributed to the workers that emitted them.

Testing

Not run (automation; PR code execution is prohibited).

  • Static review only. No PR code or tests were run.
  • The new hub tests supply owner tuples directly. They leave cross-machine resume before metadata acknowledgement and background-only work sent through the CLI and retained across heartbeat expiry unverified.
  • For d12d230, GitHub reported core, drift-gate, and windows-codex-mcp passed. Unit CLI, unit web, integration, wrapper parity, browser, and PR review were in progress at the last check.

HAPI Bot

Construct ApiSessionClient with this process's metadata (not the prior
row), refuse inherited hostPid/marker from a different PID, and stamp
reportingOwner on sendClaudeSessionMessage background snapshots so AGY
and Claude durable-latch under the real sender.

Co-authored-by: Cursor <[email protected]>
@heavygee

Copy link
Copy Markdown
Collaborator Author

Tip 4f6574474: sessionFactory now constructs the client with local bootstrap metadata; sendClaudeSessionMessage stamps reportingOwner on background_tasks_changed (Claude + AGY path).

@github-actions github-actions Bot removed the codex-review:changes HAPI Bot: review requests changes label Nov 28, 2026
@heavygee

Copy link
Copy Markdown
Collaborator Author

Tip 2b0f91c70: sessionFactory test updated for local-bootstrap client construct.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: follow-up after new commits

Requirement — Pass

Archive needs to retain a replaced runner worker’s live-work evidence, refuse before sending stop RPCs while that worker’s runtime is alive, and proceed once its exit is verified and other work has cleared.

Evidence

  • Issues #2657 and #2658 describe how a single slot can hide a live prior generation or leave Archive blocked after that generation exits.
  • On the base commit, heartbeat expiry clears transient work at hub/src/sync/sessionCache.ts:1187, and Archive starts cleanup with KillSession at hub/src/sync/syncEngine.ts:3857.

Approach — Needs changes

The generation-keyed map and sender attribution fit the requirement. The read-only probe treats the wrapper’s exit as proof that its runtime exited. If a prior Codex wrapper dies while its owned app-server is still running, Archive can clear that generation’s latch and send stop RPCs while the prior runtime remains live.

Evidence

  • hub/src/sync/syncEngine.ts:3882 passes the wrapper PID and start marker to the probe, clears the latch on already_gone at line 3893, and sends KillSession at line 3914.
  • cli/src/runner/run.ts:1775 returns already_gone as soon as the wrapper PID is absent. cli/src/codex/shared/registry.ts:51 checks both the wrapper and the owned app-server, and line 108 explicitly handles an app-server surviving its wrapper.

Suggestions

  • Pass the session ID with the recorded owner tuple and use the runner’s existing runtime and containment checks in the read-only preflight. Keep the latch if the owned app-server is live or exit cannot be verified. Cover a dead wrapper with a live app-server and assert that neither stop RPC runs.

Code — Not reviewed

Code review stopped at the approach stage because the probe cannot establish the exit condition required to clear durable work.

Testing

Not run (automation; PR code execution is prohibited).

  • Static review only. The Archive tests stub probe results, leaving the dead-wrapper case with a live app-server unverified.
  • For 2b0f91c, GitHub reported core, drift-gate, unit-cli, windows-codex-mcp, and wrapper-parity passed. Browser, integration, unit-web, and PR review were in progress.

HAPI Bot

@github-actions github-actions Bot added the codex-review:changes HAPI Bot: review requests changes label Nov 28, 2026
When the wrapper PID is gone, still return still_alive if a Codex owned
runtime for that wrapper generation has a live app-server. Prevents
Archive from clearing a prior-gen latch while the owned server remains.

Co-authored-by: Cursor <[email protected]>
@heavygee

Copy link
Copy Markdown
Collaborator Author

Tip 1c906e651: ProbeSessionExit PID path now consults Codex runtimeMayBeAlive so a dead wrapper with a live owned app-server stays still_alive (no latch clear / no stop RPCs).

@github-actions github-actions Bot removed the codex-review:changes HAPI Bot: review requests changes label Nov 28, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes (4 Major, 2 Minor)

Review mode: follow-up after new commits

Requirement — Pass

Archive should retain evidence of a replaced runner’s work, refuse before sending stop RPCs while that owner may still be running, and proceed once its exit is verified and other work has cleared.

Evidence

  • Issues #2657 and #2658 explain how a replacement can hide a prior worker’s live work and how a stale latch can strand Archive after the worker exits.
  • At base 88c2c13, heartbeat expiry clears transient work in hub/src/sync/sessionCache.ts:1187, and Archive starts cleanup with KillSession in hub/src/sync/syncEngine.ts:3857.

Approach — Pass

The reporting worker’s machine, PID, and start marker let the hub track each generation independently. A read-only preflight lets Archive verify the recorded owner before entering cleanup. The fixed head now checks for an owned Codex app-server that survives its wrapper.

Evidence

  • hub/src/sync/sessionCache.ts:982 keys durable writes by the reported owner, and hub/src/sync/syncEngine.ts:3882 probes that recorded owner before cleanup.
  • cli/src/runner/run.ts:1787 checks matching runtime records with runtimeMayBeAlive, which includes the owned app-server in cli/src/codex/shared/registry.ts:51.

Code — Reviewed

The preflight can clear work without sufficient exit evidence, or leave Archive blocked after verified exit. Unchanged heartbeats also add metadata writes.

  • [Major] Keep the latch when the runtime registry is unreadable — cli/src/runner/run.ts:1787
  • [Major] Scope the exit probe to the session namespace — hub/src/sync/syncEngine.ts:3883
  • [Major] Preserve separate owners for legacy turn and background work — hub/src/sync/liveWorkByGeneration.ts:98
  • [Major] Resolve stale permission requests after verified owner exit — hub/src/sync/sessionIdle.ts:81
  • [Minor] Check probe support on the recorded owner’s machine — hub/src/sync/syncEngine.ts:3868
  • [Minor] Skip metadata writes for unchanged live work — hub/src/sync/sessionCache.ts:1011

Testing

Not run (automation; PR code execution is prohibited).

  • Static review only. The hub Archive tests stub probe responses, and the changed CLI tests do not exercise the runner’s exit decision for a dead wrapper with a surviving app-server.
  • For 1c906e6, GitHub reported core, drift-gate, integration, unit-cli, unit-web, windows-codex-mcp, and wrapper-parity passed. Browser and PR review were in progress.

HAPI Bot

Comment thread cli/src/runner/run.ts Resolved
Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread hub/src/sync/liveWorkByGeneration.ts Resolved
Comment thread hub/src/sync/sessionIdle.ts Resolved
Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread hub/src/sync/sessionCache.ts Resolved
Recheck process-group membership after a zombie-only classify so a
forking successor cannot invent absence; treat an unreaped Linux wrapper
zombie as not still_alive and continue to group/owned-runtime checks.

Co-authored-by: Cursor <[email protected]>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes (5 Major, 2 Minor)

Review mode: follow-up after new commits

Requirement — Pass

Archive should preserve live work across worker replacement and proceed once that work settles or its owner is confirmed gone. Concurrent calls need independent settlement. Windows should retain ordinary cleanup while generation-bound tree verification is deferred.

Evidence

  • At the merge base, Archive invokes KillSession before checking for live work at hub/src/sync/syncEngine.ts:3857.
  • Issues #2657 and #2658 describe how an idle replacement can hide work still running under the prior owner. #2657 #2658
  • Issue #2673 identifies the need to retire individual calls after their start rows age out of the transcript window. #2673

Approach — Pass

Binding reports to the sender's machine, PID, and start marker preserves ownership across replacement. A read-only POSIX probe can verify exit before shutdown, and matching call IDs allow independent settlement. Keeping ordinary Windows cleanup is appropriate given the current tree visibility limit.

Evidence

  • The hub applies durable work and matching call retirements to the reporting owner's entry at hub/src/sync/sessionCache.ts:1491 and hub/src/sync/sessionCache.ts:1512.
  • Probe dispatch checks both the registered machine and the authenticated socket against the session namespace at hub/src/sync/rpcGateway.ts:320 and hub/src/sync/rpcGateway.ts:335.
  • Issue #2660 explains why Windows parent links cannot establish complete tree exit after reparenting. #2660

Code — Reviewed

Static review of bbe14e9 found premature ACP settlement, Windows Archive regressions, and a remaining Linux zombie case. The new process-group membership recheck addresses the prior finding about successors appearing during classification.

  • [Major] A rejected ACP prompt can retire a running tool — cli/src/agent/backends/acp/AcpSdkBackend.ts:979
  • [Major] Failed Windows Archive discards pending permissions — hub/src/sync/syncEngine.ts:4329
  • [Major] An unstamped permission strands Windows Archive — hub/src/sync/syncEngine.ts:4269
  • [Major] Windows StopSession rejects a dead PID when Archive supplies a marker — cli/src/runner/run.ts:1459
  • [Major] The Codex registry counts an unreaped wrapper as live — cli/src/runner/run.ts:1945
  • [Minor] Provider cancellation can render an unknown running tool — cli/src/agent/backends/acp/AcpMessageHandler.ts:1141
  • [Minor] Interleaved owners bypass tool-call compaction — hub/src/store/messages.ts:864

Testing

Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. No PR code or tests were executed locally.
  • GitHub reported success for the aggregate test check, core, unit-cli, unit-web, integration, browser, windows-codex-mcp, wrapper-parity, and fixture drift on the fixed head. The review check was in progress. https://github.com/tiann/hapi/actions/runs/46219209835 https://github.com/tiann/hapi/actions/runs/46219209813
  • The Windows Archive test uses a fully stamped request and successful cleanup. The ACP cancellation test returns a successful cancelled response. The Linux zombie test uses an empty Codex registry.

HAPI Bot

Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread cli/src/runner/run.ts Resolved
Comment thread cli/src/runner/run.ts Resolved
Comment thread hub/src/store/messages.ts Resolved
…n#2659

Operator cut (A): drop Windows exit-evidence / request-stripping and the
ACP synthetic cancel publish. Keep hub POSIX-only durable refuse (win32
omits ProbeSessionExit and falls through to merge-base cleanup). Costs
and follow-ups: tiann#2660, tiann#2696, tiann#2697.

Co-authored-by: Cursor <[email protected]>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes (4 Major, 1 Minor)

Review mode: follow-up after new commits

Requirement — Pass

Archive should preserve live work when a worker is replaced and proceed once that work settles or its owner is confirmed gone. Concurrent tool calls need independent settlement. Windows should retain ordinary cleanup while generation-bound tree verification is deferred.

Evidence

  • The merge-base Archive calls KillSession before checking for live work at hub/src/sync/syncEngine.ts:3857. Issues #2657 and #2658 describe the resulting gap for replaced workers.
  • Issue #2673 documents how a matching tool result can arrive after its start row leaves the transcript lookback. Issue #2660 documents the limits of Windows tree-exit evidence.

Approach — Pass

Binding durable records to the reporting machine, PID, and start marker preserves ownership across replacement. A read-only, namespace-scoped exit probe can inform the Archive guard before shutdown, and per-owner call IDs support independent settlement.

Evidence

  • hub/src/sync/sessionCache.ts:1491 keys durable updates by reporting generation and applies matching call retirements at line 1512.
  • hub/src/sync/rpcGateway.ts:320 and hub/src/sync/rpcGateway.ts:335 check the registered machine and authenticated socket against the session namespace.
  • hub/src/sync/syncEngine.ts:4099 skips durable probes for Windows owners and line 4223 excludes their durable entries from the Archive guard.

Code — Reviewed

The fixed head removes the premature ACP cancellation publishing and restores Windows marked-PID cleanup. The remaining findings cover abandoned Windows requests, transcript attribution, terminal background work, and Runner exit classification.

  • [Major] An abandoned Windows permission blocks Archive indefinitely — hub/src/sync/syncEngine.ts:4243
  • [Major] Tool ingestion attributes old unstamped calls to the replacement — hub/src/socket/handlers/cli/sessionHandlers.ts:332
  • [Major] A late Runner snapshot erases a live terminal's background work — hub/src/sync/sessionCache.ts:1210
  • [Major] The Codex registry still counts an unreaped wrapper as live — cli/src/runner/run.ts:1819
  • [Minor] Interleaved owners bypass tool-call compaction — hub/src/store/messages.ts:864

Testing

Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. Review was static and PR code was not executed locally.
  • GitHub reported success on eb17e0e for the aggregate test check, core, unit-cli, unit-web, integration, browser, windows-codex-mcp, wrapper-parity, and fixture drift. The review job was in progress. https://github.com/tiann/hapi/actions/runs/46412525765 https://github.com/tiann/hapi/actions/runs/46412525325
  • The Windows archive-success test has no pending request, the background replacement test gives the terminal a start marker, and the Linux zombie test uses an empty Codex registry.

HAPI Bot

Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread hub/src/sync/sessionCache.ts Resolved
Comment thread cli/src/runner/run.ts Resolved
Comment thread hub/src/store/messages.ts Resolved
Reopen-class fixes: Windows abandoned permissions no longer permanently
block Archive (in-memory guard omit; clear after confirmed stop or
child-exit). Codex registry treats Linux unreaped zombies as not alive.
Ingest applies generation cutoff for the boundary owner; markerless
terminal background survives late attributed empty snapshots.

Co-authored-by: Cursor <[email protected]>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes (5 Major, 1 Minor)

Review mode: follow-up after new commits

Requirement — Pass

Archive should preserve live work across worker replacement and proceed when the work settles or the owner’s exit is verified. Concurrent tool calls need independent settlement. Windows should retain its existing cleanup path while generation-bound tree verification is deferred.

Evidence

  • Issues #2657 and #2658 describe how a replacement can hide an older worker that is still running. The merge base calls KillSession before checking for live work at hub/src/sync/syncEngine.ts:3857.
  • Issue #2673 documents matching results that arrive after the original call leaves the transcript lookback. Issue #2660 documents the limits of Windows process-tree exit evidence.

Approach — Pass

A durable record keyed by the reporting worker’s machine, PID, and start marker can preserve work across replacement. A read-only, namespace-scoped probe supports the pre-shutdown guard, and per-owner call IDs support independent settlement.

Evidence

  • hub/src/sync/sessionCache.ts:1488 keys durable updates by reporting owner and applies matching call retirements at line 1509.
  • hub/src/sync/rpcGateway.ts:320 and hub/src/sync/rpcGateway.ts:335 check the machine and authenticated CLI socket against the session namespace.
  • hub/src/sync/syncEngine.ts:4108 excludes Windows owners from the durable probe path, and hub/src/sync/syncEngine.ts:4161 reconciles derived work after the probe loop.

Code — Reviewed

The fixed head addresses the earlier Linux zombie classification and preserves live markerless background snapshots across an empty Runner report. Archive still has gaps in Windows request cleanup, transcript attribution, and exit classification.

  • [Major] Cleanup of a replacement can erase another worker’s Windows request — hub/src/sync/syncEngine.ts:4401
  • [Major] An unstamped Windows Runner request blocks ordinary cleanup — hub/src/sync/syncEngine.ts:4244
  • [Major] Tool ingestion reads the generation cutoff from a stale snapshot — hub/src/socket/handlers/cli/sessionHandlers.ts:335
  • [Major] A departed terminal’s markerless background snapshot never expires — hub/src/sync/sessionCache.ts:1219
  • [Major] A reused process-group ID can keep Archive blocked — cli/src/runner/run.ts:1837
  • [Minor] Interleaved owners still bypass tool-call compaction — hub/src/store/messages.ts:864

Testing

Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. Review was static.
  • GitHub reported success for the aggregate Test check, core, unit-cli, unit-web, integration, browser, windows-codex-mcp, wrapper-parity, and fixture drift on f5467ac. The review job was still in progress. https://github.com/tiann/hapi/actions/runs/46415466332 https://github.com/tiann/hapi/actions/runs/46415466361
  • The Windows Archive tests use a fully stamped request on the current machine. The transcript cutoff test supplies an already-current access snapshot, and the markerless background test clears the snapshot explicitly.

HAPI Bot

Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread hub/src/sync/sessionCache.ts Resolved
Comment thread cli/src/runner/run.ts Resolved
Comment thread hub/src/store/messages.ts Resolved
…nn#2697)

A generation's durable latch now clears solely from an owning-runner
session-child-exited or a stamped session-end for that exact owner
(machineId + hostPid + processStartMarker). Both write a hub-owned
metadata.liveWorkGenerationExits[ownerKey] record, then drop that
owner's latch, pending requests and transient/derived bits. Stamped
prior-worker ends now reach the engine (socket still skips the queue
sweep) and clear their own latch without deactivating the replacement.
Late reports from an exited owner never re-latch.

Archive no longer treats ProbeSessionExit already_gone/stopped as clear
authority. Durable work without an exit record refuses
(archive-session-working) - documented strand, routed to tiann#2660 /
operator recovery. Windows platform-scope omit is unchanged.

Co-authored-by: Cursor <[email protected]>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: follow-up after new commits

Requirement — Pass

Archive should protect work that survives worker replacement and proceed once the prior generation's exit is verified. Concurrent tool calls need independent settlement. Windows retains its existing cleanup path while generation-bound process-tree verification is deferred.

Evidence

  • Issues #2657 and #2658 explain how a replacement can hide live work from an earlier worker. At the merge base, hub/src/sync/syncEngine.ts:3857 starts KillSession before checking for live work.
  • Issue #2673 documents matching tool results arriving after the original call leaves the transcript lookback. Issue #2660 documents the limits of Windows process-tree exit evidence.

Approach — Needs changes

The fixed head requires a recorded exit notice to clear a prior POSIX generation before Archive. If that worker and its Runner exit without delivering a notice, Archive keeps returning archive-session-working even after the prior generation is gone and ordinary cleanup could succeed. This conflicts with the PR's explicit requirement to avoid permanent Archive refusals.

Evidence

  • The fixed PR description requires a conclusive POSIX ProbeSessionExit response to clear the matching entry and lists the exit-notice-only design as deferred in #2697.
  • hub/src/sync/syncEngine.ts:4065 makes recorded child-exit or stamped session-end notices the basis for clearing prior POSIX work. The guard at line 4222 refuses before ordinary cleanup can start.
  • hub/src/sync/syncEngineArchiveSession.test.ts:722 expects Archive to refuse and preserve the prior entry with no exit notice, even with ProbeSessionExit and StopSession configured to return already_gone.

Suggestions

  • Keep generation-keyed tracking and matching exit notices. Provide a generation-bound source of exit evidence that survives the reporting Runner's loss, and have the POSIX probe use that evidence to clear the matching entry before Archive reevaluates live work. Keep refusal for live or uncertain owners and cover a fully exited prior generation that delivered neither notice.

Code — Not reviewed

Code review stopped because the Archive design does not meet the POSIX recovery requirement.

Testing

Not run (automation; PR code execution is prohibited).

HAPI Bot

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: follow-up after context changes

Requirement — Pass

Archive should preserve live work from an earlier POSIX worker generation after a replacement takes over. The updated PR scope explicitly accepts continued refusal when authoritative exit evidence is unavailable and keeps Windows on the existing cleanup path.

Evidence

  • At the merge base, hub/src/sync/syncEngine.ts:3857 starts KillSession before checking for live work. Issue #2657 describes how a replacement can hide an earlier generation’s work. #2657
  • The fixed PR description explicitly accepts refusal when no exit record arrives. Issue #2697 documents why process-group samples cannot establish that a generation has exited. #2697
  • Issue #2673 documents why each outstanding tool call needs independent settlement after it leaves the transcript lookback. #2673

Approach — Needs changes

Generation-keyed tracking addresses worker replacement, but the proposed exit authority can still release live work. If a prior wrapper crashes while its owned Codex app-server or another descendant continues working, the wrapper’s child-exit notice clears the prior generation’s latch and lets Archive start shutdown.

Evidence

  • cli/src/runner/run.ts:1914 handles the direct child’s exit and emits the notice at line 1944. The same callback withholds a PID exit record at line 1922 because descendants can survive. The runner explicitly handles a dead wrapper with a live owned Codex app-server at line 1863.
  • hub/src/sync/syncEngine.ts:1168 promotes the stamped notice to a generation exit even after replacement. hub/src/sync/sessionCache.ts:1461 then drops the prior owner’s latch, allowing the Archive guard at hub/src/sync/syncEngine.ts:4222 to pass if the replacement is idle.

Suggestions

  • Keep generation-keyed tracking and use the wrapper exit notice for wrapper lifecycle updates. Release durable work only on a generation-bound completion event that covers the owned runtime and its outstanding work. Where the runner cannot produce that event, preserve the latch and the documented Archive refusal.

Code — Not reviewed

Code review stopped because the proposed exit event can release a generation that still owns live work.

Testing

Not run (automation; PR code execution is prohibited).

  • The fixed merge-base diff passed git diff --check. No PR code or tests were run locally.
  • hub/src/sync/syncEngineArchiveSession.test.ts:740 injects a child-exit notice and mocks StopSession as already_gone. The missing case is a prior wrapper exiting while an owned runtime continues working, with Archive expected to refuse before sending stop RPCs.
  • For eb48aae, GitHub reported success for core, integration, unit-cli, unit-web, wrapper-parity, windows-codex-mcp, and fixture drift. Browser and the current review job were in progress. https://github.com/tiann/hapi/actions/runs/46428398648 https://github.com/tiann/hapi/actions/runs/46428398932

HAPI Bot

heavygee and others added 2 commits November 30, 2026 13:40
…ssions

Wrapper child-exit clears a generation only when no descendants were
registered (Codex / open-tool / sticky descendantsRegistered); otherwise
strand. Stamped session-end remains the generation-bound terminal clear.

Archive no longer erases another machine's Windows pending ask after Stop
on this machine, omits unstamped Windows Runner asks from the guard so
ordinary cleanup matches main, and expires markerless terminal background
snapshots on the same BACKGROUND_STALE_MS clock while a replacement stays
online.

Co-authored-by: Cursor <[email protected]>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: follow-up after new commits

Requirement — Pass

Archive should preserve durable work from a previous POSIX worker after an idle replacement takes over. The fixed PR scope accepts an Archive refusal when authoritative completion evidence is unavailable and preserves the existing Windows cleanup path.

Evidence

  • At the merge base, hub/src/sync/syncEngine.ts:3857 calls KillSession before checking for live work. Issues #2657 and #2658 explain why a single live-work slot cannot represent both workers. #2657 #2658
  • The fixed PR description and issue #2697 explain why a process probe cannot establish that an earlier generation finished its work. #2697

Approach — Needs changes

Generation-keyed accounting addresses worker replacement, but the exit policy treats a stamped session-end as proof of work completion even when Codex emits it after failing to stop its app-server. The hub can then drop the only latch for that generation and start Archive shutdown while its work can still be running.

Evidence

  • cli/src/codex/shared/runtime.ts:138–150 retains runtime ownership when app-server shutdown cannot be confirmed, then closes the roots in finally. Root close still sends session-end at cli/src/codex/shared/root.ts:906–916, and cli/src/api/apiSession.ts:1606–1631 stamps the runner generation on that event.
  • hub/src/sync/syncEngine.ts:1072–1088 records a fully stamped session-end before checking whether the sender still owns the row. hub/src/sync/sessionCache.ts:1495–1526 then removes that generation’s durable and transient work.
  • The new child-exit restriction can also be bypassed by the lifecycle path itself. After the cache declines to record a Codex child exit, hub/src/sync/syncEngine.ts:1168–1193 forwards the same stamped notice to handleSessionEnd if the wrapper still owns an active row. That creates the exit record before a replacement registers.

Suggestions

  • Keep generation-keyed tracking and require an explicit generation-bound completion signal from the component that owns the runtime and can confirm its work has ended. Let wrapper exit and ordinary session-end update row lifecycle while preserving the durable latch when cleanup is unconfirmed.

Code — Not reviewed

Code review stopped at the approach stage because the proposed exit events can release durable work before runtime completion is established.

Testing

Not run (automation; PR code execution is prohibited).

HAPI Bot

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: follow-up after context changes

Requirement — Pass

An idle replacement worker must not let Archive overlook live work from an earlier POSIX worker. The PR gives each generation its own durable record, accepts Archive refusal when completion cannot be confirmed, and preserves the existing Windows cleanup path.

Evidence

  • At the merge base, hub/src/sync/syncEngine.ts:3857 calls KillSession before checking for live work. Issues #2657 and #2658 explain how an idle replacement can hide an earlier worker's unresolved work. #2657 #2658
  • The fixed PR description defines the POSIX refusal and Windows exception. Issue #2697 explains why a process probe alone cannot establish that a generation's work ended. #2697

Approach — Needs changes

Generation-keyed tracking addresses worker replacement, but the exit policy treats a stamped session-end as proof of completion. That event can be emitted while the generation's Codex app-server may still be running. The hub can then clear the durable record and let Archive start shutdown.

Evidence

  • cli/src/codex/shared/runtime.ts:138–150 retains runtime ownership when app-server shutdown fails, then closes the roots in finally. cli/src/codex/shared/root.ts:906–916 still calls sendSessionDeath, and cli/src/api/apiSession.ts:1606–1631 emits session-end with the runner's generation stamp.
  • hub/src/sync/syncEngine.ts:1072–1088 records a fully stamped session-end even after a replacement takes ownership. hub/src/sync/sessionCache.ts:1495–1526 then clears that generation's durable record and associated work state.
  • If a stamped wrapper exit arrives while the wrapper still owns an active row, hub/src/sync/syncEngine.ts:1168–1193 forwards it to handleSessionEnd even when the child-exit policy rejects it as proof of completion. This lets the same notice clear the generation through the session-end path.

Suggestions

  • Keep generation-keyed tracking. Require an explicit generation-bound completion signal from the component that can confirm the work ended. Let ordinary session-end and wrapper-exit notices update row lifecycle while preserving the durable record whenever completion remains unconfirmed.

Code — Not reviewed

Code review stopped at the approach stage because the exit signal can release the Archive guard before the owning runtime finishes.

Testing

Not run (automation; PR code execution is prohibited).

HAPI Bot

When childExitMayClearGeneration declines, forward lifecycle-only
handleSessionEnd (no stamps) so Codex / descendant wrapper exits cannot
mint a session-end exit record that clears the latch.

Co-authored-by: Cursor <[email protected]>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: follow-up after new commits

Requirement — Pass

An idle replacement worker can hide unresolved work from a prior worker. Archive should preserve that evidence and refuse to start cleanup on POSIX when the prior generation's exit is unconfirmed, while retaining the existing Windows cleanup path.

Evidence

  • At the merge base, hub/src/sync/syncEngine.ts:3857 calls KillSession before checking for live work. The linked issues explain why a single durable record cannot represent both the prior worker and its replacement. #2657 #2658
  • The fixed PR description defines the Windows exception. Issue #2697 explains why a process probe cannot establish that the prior generation's work ended. #2697

Approach — Needs changes

Generation-keyed tracking addresses worker replacement, and this head fixes the wrapper-exit bypass. A separate Codex lifecycle path still emits a stamped session-end after an unconfirmed app-server shutdown. The hub accepts that event as proof of completion and removes the durable guard, so Archive can start cleanup while the prior generation may still be running.

Evidence

  • hub/src/sync/syncEngine.ts:1181 applies the child-exit policy. When the policy declines a clear, the lifecycle call at hub/src/sync/syncEngine.ts:1200 omits the generation stamp and preserves the durable record.
  • cli/src/codex/shared/runtime.ts:138 treats failure to stop the app-server as an error and retains runtime ownership, but still closes the roots at line 150. cli/src/codex/shared/root.ts:915 calls sendSessionDeath during that close, and cli/src/api/apiSession.ts:1622 emits session-end with the available runner identity fields.
  • hub/src/sync/syncEngine.ts:1077 records any fully stamped session-end before checking whether a replacement owns the row. hub/src/sync/sessionCache.ts:1522 then clears the matching durable record and pending requests. If no other work blocks Archive, hub/src/sync/syncEngine.ts:4292 starts cleanup.

Suggestions

  • Keep generation-keyed tracking and require explicit generation-bound completion evidence from the runtime that can confirm the work ended. Let ordinary session-end update row lifecycle while preserving the durable record whenever runtime shutdown remains unconfirmed.

Code — Not reviewed

Code review stopped at the approach stage because the exit signal can release the Archive guard before runtime completion is confirmed.

Testing

Not run (automation; PR code execution is prohibited).

HAPI Bot

Failed app-server kill retained ownership but still stamped session-end,
which cleared the durable latch while the engine could keep running.
Lifecycle-only end now preserves the latch (strand + route).

Co-authored-by: Cursor <[email protected]>
@heavygee

Copy link
Copy Markdown
Collaborator Author

Addressed latest Approach finding (stamped session-end after unconfirmed Codex app-server shutdown):

  • cli now tracks runtimeShutdownConfirmed in shared Codex shutdown. Kill failure / early abort keeps it false; only then do roots close with omitOwnerStamp.
  • sendSessionDeath({ omitOwnerStamp: true }) emits lifecycle-only session-end (no machineId/hostPid/processStartMarker), so the hub does not write liveWorkGenerationExits or clear the durable latch.
  • Confirmed kill (or already-exited engine) still stamps as before and clears.
  • Coverage: CLI omit-stamp unit + hub Archive refuse on unstamped end with live latch (c3fb6d65e).

Child-exit → stamped handleSessionEnd bypass was already fixed on 48f1676f6 (lifecycle-only when clear declined).

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: follow-up after new commits

Requirement — Pass

An idle replacement worker can hide unresolved work from a prior generation. POSIX Archive should retain that evidence and refuse cleanup while the prior owner's exit is unconfirmed. Windows should retain its existing cleanup path until tree containment is available.

Evidence

  • At the merge base, hub/src/sync/syncEngine.ts:3857 calls KillSession before checking for live work. Issues #2657 and #2658 explain why the prior worker and its replacement need independent records. #2657 #2658
  • Issue #2697 explains why sampled process state cannot establish generation exit. The fixed PR description specifies authoritative exit evidence and the Windows exception. #2697

Approach — Needs changes

Generation-keyed tracking addresses worker replacement, and the new Codex branch preserves the latch when the kill helper reports failure. The protocol still treats any fully stamped lifecycle end as proof of completion. A launcher can emit that event after a teardown timeout, clearing the prior generation's guard and allowing POSIX Archive to start cleanup while its work may still be running.

Evidence

  • cli/src/kimi/kimiRemoteLauncher.ts:57 uses the bounded ACP shutdown helper. cli/src/modules/common/remote/settleAcpLauncherShutdown.ts:35 resolves after five seconds even if teardown is pending. cli/src/agent/runnerLifecycle.ts:67 then emits the ordinary session-end, which cli/src/api/apiSession.ts:1641 stamps by default.
  • cli/src/codex/shared/runtime.ts:358 starts shutdown when the app-server exits. Lines 143–146 then skip tree cleanup and mark shutdown confirmed even if registered tool descendants outlive the app-server.
  • hub/src/sync/syncEngine.ts:1077 records any fully stamped end before checking the current row owner. hub/src/sync/sessionCache.ts:1522 drops that owner's durable work. With an idle replacement and no other guard, hub/src/sync/syncEngine.ts:4292 can then start cleanup.
  • The new Codex failure path drops owner identity along with completion authority. hub/src/sync/liveWorkByGeneration.ts:136 accepts an unstamped end without checking which generation owns the row, so a late lifecycle end can deactivate a replacement.

Suggestions

  • Keep the owner stamp on lifecycle events and require a separate, explicit completion signal from a runtime that can confirm the generation's owned work ended. Preserve the latch after a teardown timeout or an app-server exit with unresolved descendants, and use the owner stamp to reject stale row updates.

Code — Not reviewed

Code review stopped at the approach stage because the exit protocol can release the Archive guard before generation completion is established.

Testing

Not run (automation; PR code execution is prohibited).

HAPI Bot

Dropping owner stamps on unconfirmed Codex shutdown let an unstamped end
deactivate a replacement. Keep stamps for the owner gate and pass
omitGenerationExit so the hub skips authoritative latch clear.

Co-authored-by: Cursor <[email protected]>

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: follow-up after new commits

Requirement — Pass

POSIX Archive should retain evidence of unfinished work across worker replacement and refuse cleanup until the owning generation's completion is confirmed. Windows should retain its existing cleanup path pending tree containment.

Evidence

  • At the merge base, hub/src/sync/syncEngine.ts:3857 calls KillSession before checking for live work. Issues #2657 and #2658 explain how an idle replacement can hide a prior worker's unfinished work. #2657 #2658
  • Issue #2697 explains why a process sample cannot establish generation completion. The fixed PR description defines the Windows exception. #2697

Approach — Needs changes

Generation-keyed tracking addresses worker replacement, and the new lifecycle-only flag preserves the owner check on an unconfirmed Codex shutdown. The protocol still grants clear authority to stamped lifecycle events by default, so POSIX Archive can start cleanup while a prior generation's work may still be running.

Evidence

  • Kimi runs launcher teardown before closing at cli/src/kimi/runKimi.ts:86. The kill handler uses cli/src/modules/common/remote/settleAcpLauncherShutdown.ts:35, which resolves after five seconds even when teardown is pending. cli/src/agent/runnerLifecycle.ts:67 then sends the ordinary session-end, which cli/src/api/apiSession.ts:1632 stamps.
  • On an unexpected Codex app-server exit, cli/src/codex/shared/runtime.ts:358 starts shutdown. Lines 143–146 skip tree cleanup for an already-exited app-server and mark shutdown confirmed even when a tool descendant survives. The root then sends an authoritative end at cli/src/codex/shared/root.ts:917.
  • hub/src/sync/syncEngine.ts:1084 records either stamped end before checking the current row owner, and hub/src/sync/sessionCache.ts:1522 removes that owner's latch. With an idle replacement and no other guard, Archive can reach KillSession at hub/src/sync/syncEngine.ts:4300.

Suggestions

  • Keep generation identity on lifecycle events and require an explicit completion signal before the hub records an authoritative exit. Have runtimes emit it only after confirming their owned work ended. Preserve the latch after an ACP teardown timeout or an app-server exit with unresolved descendants.

Code — Not reviewed

Code review stopped at the approach stage because the exit protocol can release the Archive guard before generation completion is established.

Testing

Not run (automation; PR code execution is prohibited).

HAPI Bot

Resolve DIRTY/CONFLICTING merge state for tiann#2659 after main moved.
Keep groupLeaderId with liveWorkByGeneration hub-owned metadata keys.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Needs changes

Review mode: follow-up after new commits

Requirement — Pass

POSIX Archive should refuse cleanup while a prior worker generation has unresolved work and lacks an authoritative exit record, even after an idle replacement takes over. Windows retains its existing cleanup path pending tree containment.

Evidence

  • At the merge base, hub/src/sync/syncEngine.ts:3930 calls KillSession without checking for live work. Issues #2657 and #2658 describe how a replacement can hide the prior worker's unfinished work. #2657 #2658
  • Issue #2697 establishes that process samples cannot prove generation completion. The fixed PR description specifies the Windows exception. #2697

Approach — Needs changes

Generation-keyed tracking addresses worker replacement. The protocol still grants clear authority by default to stamped session-end events, including events emitted before the owning runtime confirms its work has ended.

Evidence

  • Kimi uses the bounded shutdown helper at cli/src/kimi/kimiRemoteLauncher.ts:57. The helper can resolve after five seconds while teardown is pending at cli/src/modules/common/remote/settleAcpLauncherShutdown.ts:35. The lifecycle then sends an ordinary session-end at cli/src/agent/runnerLifecycle.ts:67, which cli/src/api/apiSession.ts:1632 stamps without a completion signal.
  • An unexpected Codex app-server exit triggers shutdown at cli/src/codex/shared/runtime.ts:358. If a tool descendant survives, lines 143–146 still skip tree cleanup and mark shutdown confirmed because the app-server itself has exited. The root then sends an end with clear authority at cli/src/codex/shared/root.ts:919.
  • hub/src/sync/syncEngine.ts:1085 records either stamped end before checking the current row owner. hub/src/sync/sessionCache.ts:1553 clears the prior generation's latch. If the replacement is idle and no other guard applies, Archive can reach KillSession at hub/src/sync/syncEngine.ts:4373 while prior work may still be running.

Suggestions

  • Keep owner stamps on lifecycle events and require an explicit generation-completion signal before clearing durable work. Have runtime shutdown paths emit it only after they establish that the owned work has ended. Preserve the latch on ACP teardown timeouts and Codex app-server exits with unresolved descendants.

Code — Not reviewed

Code review stopped at the approach stage because ordinary shutdown events can release the Archive guard before generation completion is confirmed.

Testing

Not run (automation; PR code execution is prohibited).

HAPI Bot

Resolve CONFLICTING/DIRTY for tiann#2659. Keep Linux PGID/zombie axis and adopt
upstream probeProcessLiveness, with EPERM still counting as alive on POSIX.

Co-authored-by: Cursor <[email protected]>
@heavygee

heavygee commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

Merge resolution note (bb8e20d60 ← upstream/main)

Conflict was only in cli/src/utils/process.ts (+ its test). Resolution axes:

  1. Graft, not whole-file take. Kept this branch’s Linux PGID / zombie state axis (parseLinuxStatExecutionState, readLinuxProcessExecutionState, processGroupMayBeAlive and call sites). Adopted upstream’s probeProcessLiveness / isProcessAlive wrapper shape.

  2. One fork-side guard on the graft. In probeProcessLiveness’s catch: EPERM → 'alive' on POSIX. process.kill(pid, 0) here is ESRCH (→ exited) or EPERM (process exists but we cannot signal it). Inventing exit on EPERM would break ProbeSessionExit / archive evidence (hub: generation-keyed durable live-work + owner exit probe #2658). Windows still uses upstream’s unknown when tasklist fails and signal-0 throws.

  3. Exports. Tip adds the three Linux helpers above; all upstream exports retained. processGroupMayBeAlive / readLinuxProcessExecutionState remain wired from cli/src/runner/run.ts and cli/src/codex/shared/registry.ts.

  4. Test. Existing PGID/zombie coverage kept; upstream probeProcessLiveness cases kept; added POSIX EPERM → alive regression.

No Approach chase on this tip. CI test suite green on bb8e20d60; Codex PR Review startup_failure is repo-wide (not tip-specific).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codex-review:changes HAPI Bot: review requests changes

Projects

None yet

1 participant