Skip to content

feat(cli+hub): archive_peer MCP/CLI with live-work guard (#2020) - #2740

Open
heavygee wants to merge 18 commits into
tiann:mainfrom
heavygee:feat/archive-peer-supersede-2021
Open

heavygee wants to merge 18 commits into
tiann:mainfrom
heavygee:feat/archive-peer-supersede-2021

Conversation

@heavygee

@heavygee heavygee commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Clean supersede of contaminated #2021 (do not rebase that tip - it re-thinned onto fork origin/main and leaked fork-only MCP tools + scripts/tooling into a 957-file upstream-facing tip).

This branch is cut from upstream/main with only:

  • CLI hapi archive-peer + MCP archive_peer - same JWT path as ping_peer / spawn_peer; archive only, never delete; posts {} to POST /api/sessions/:id/archive.
  • Shared hub live-work guard before KillSession/StopSession: 409 archive-session-working when blocksHardArchive is true (idleReconcileExempt, expiredWhileWorking, or hasLiveWork). Builds on already-merged #2616 (metadata.waiting inside hasLiveWork); also treats derivedToolWork as live work. No softStandDown exception - verified Runner cleanup for every caller.
  • Inactive hostPid probe: markerless PID-N — already_gone/stopped may proceed (crash recovery); still_alive refuses; Runner-owned unknown asks read-only STATUS-<hostPid>:<sessionId> for inactive Codex binding / verified exit (shared wrappers with live siblings); terminal unknown/probe throw refuses without KillSession. Prefer codexResumePending.machineId over metadata.machineId so STATUS/cleanup targets the pending resume owner.
  • Heartbeat expiry latch: expireInactive sets hub-owned metadata.expiredWhileWorking when keepalive dies mid-thinking / derived-tool / background work so cleared turn UI flags alone cannot authorize KillSession on a disconnected terminal last seen working. Quiet inactive terminal crash (no latch, no hostPid) still archives Runner-free. Latch clears on become-active.
  • Web: hide row/header Archive and skip Archive-all while live work / exempt; dissolve-group refuses when preflight sees protected work (sessionBlocksHardArchive or sessionHasProtectedArchiveMarkers, including disconnected members with waiting/exempt).

Honest tool/help copy: live-work refuse first; unconfirmed Runner stop still 409 after that.

Approach follow-up (tip-matched)

Approach Needs changes on OID 239257494 (two bullets) was answered on 6de1e0976:

  1. expiredWhileWorking latch across heartbeat expiry (mid-turn disconnect + expiry + no Runner → refuse; quiet crash → archive OK).
  2. Prefer persisted codexResumePending.machineId for inactive probe / STATUS reconciliation.

Codex PR Review on 6de1e0976 hit startup_failure (0 jobs; cannot retry). PR body edit here is the synchronize kick — no content change required beyond documenting that status. Trivial tip 0f88bf15b (comment-only) may also have been pushed earlier for the same reason.

Test plan

  • Hub: sessionIdle / syncEngineArchiveSession / sessions route tests for archive-session-working (thinking, derivedToolWork, waiting, idleReconcileExempt, expiredWhileWorking), probe throw refuse, STATUS Codex sibling recovery, pending-machine prefer, and existing cleanup codes
  • CLI: archivePeer module + arg parse + MCP registration / bridge / permission / expected tool catalogs; runner STATUS-* read-only probe tests
  • Web: sessionHasLiveWork + quick-archive hide-while-busy + dissolve-group protected-marker preflight
  • bun run typecheck:cli|hub|web
  • bun run test (cli green; hub has pre-existing unrelated flakes on upstream/main also: steerDeliveryLifecycle opencode reconnect + two timeouts)

Issues

Fixes #2020

Supersedes #2021 (leave open for operator close after this lands).

Supersedes contaminated tiann#2021: clean tip from upstream/main with only
archive_peer / hapi archive-peer, shared hub archive-session-working
pre-stop guard (builds on tiann#2616 waiting + idleReconcileExempt), and
matching web hide/skip for live work. No softStandDown exception; verified
Runner cleanup for every caller. No fork-only tools.

Co-authored-by: Cursor <[email protected]>
heavygee added a commit to heavygee/hapi that referenced this pull request Dec 2, 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: initial

Requirement — Pass

Orchestrators need a first-class way to stop finished peers and reclaim runner memory while retaining session history. The revised scope adds CLI and MCP entry points, protects sessions with visible work, and requires the existing Runner cleanup confirmation.

Evidence

  • Issue #2020 and its follow-up describe idle peers retaining memory, the manual REST workaround, and the revised requirement to refuse busy archives before sending stop RPCs.
  • The base CLI registers peer discovery, messaging, and spawning commands in cli/src/commands/registry.ts:46. The existing archive operation is documented in hub/README.md:147.

Approach — Pass

Reusing the namespace-scoped archive endpoint gives CLI and MCP callers the same lifecycle contract as web callers. Checking for live work in the hub before process termination keeps that policy enforceable for every caller.

Evidence

  • cli/src/modules/archivePeer/archivePeer.ts:230 exchanges the CLI credential, resolves the target, and calls the existing archive route. hub/src/web/routes/guards.ts:23 scopes access to the authenticated namespace.
  • hub/src/sync/syncEngine.ts:3927 checks eligibility before KillSession and the existing Runner confirmation path.

Code — Reviewed

The fixed-head diff was reviewed statically. The findings cover archive recovery, client behavior, credential exposure, and MCP availability.

  • [Major] Persisted work markers can strand a stopped session — hub/src/sync/syncEngine.ts:3928
  • [Major] Dissolve group partially archives groups with busy members — web/src/components/ProjectGroupRow.tsx:19
  • [Major] Debug output can expose hub credentials — cli/src/commands/archivePeer.ts:101
  • [Major] Peer archive times out before the hub's cleanup deadline — cli/src/modules/archivePeer/archivePeer.ts:199
  • [Minor] Sidebar summaries omit two archive eligibility signals — web/src/lib/sessionHasLiveWork.ts:33
  • [Minor] Pi sessions cannot discover archive_peer — cli/src/claude/utils/startHappyServer.ts:919

Testing

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

  • For head 6ee34dc, core, unit-web, integration, wrapper-parity, windows-codex-mcp, and drift-gate passed. Browser and pr-review were in progress at the last check.
  • unit-cli failed in agyReactiveWakeup.test.ts and opencodeRemoteLauncher.test.ts. The changed archive, MCP registration, bridge, and permission suites passed in that job. Whether the two failures reproduce on base remains unverified.
  • The fixed diff passed git diff --check. Review verification was read-only.

HAPI Bot

Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread web/src/components/ProjectGroupRow.tsx Resolved
Comment thread cli/src/commands/archivePeer.ts Resolved
Comment thread web/src/lib/sessionHasLiveWork.ts Resolved
@github-actions github-actions Bot added the codex-review:changes HAPI Bot: review requests changes label Dec 2, 2026
Inactive stale waiting markers can reach verified Runner cleanup; dissolve
fail-closes on busy members; DEBUG never dumps Axios; client archive
timeout covers the hub 90s budget; summaries project waiting/exempt; Pi
gets archive_peer on the peer MCP allowlist.

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

heavygee commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

Auto-fix tip 3967bbbd0 (bot 4 Major / 2 Minor)

Addressed tip-matched review on 6ee34dcf6:

  1. Inactive + stale work markers - hub live-work refuse now requires active === true, so crashed/stopped rows with leftover waiting / tools can still reach verified Runner cleanup (still 409 when stop is unconfirmed).
  2. Dissolve fail-closed - dissolve refuses before any archive when any target sessionBlocksHardArchive (no partial dissolve / mid-group 409).
  3. DEBUG credential hygiene - hapi archive-peer never dumps raw Axios/config under DEBUG (name/code/status only).
  4. Client archive timeout - POST /archive timeout raised to 100s (> hub ~90s cleanup budget).
  5. Summary projection - toSessionSummaryMetadata now carries waiting + idleReconcileExempt.
  6. Pi allowlist - runPi + hapiExtension register/approve archive_peer.

Local verification: focused hub/cli/web suites + typecheck:cli|hub|web green.

unit-cli FAIL triage (not tip-caused)

CI cited agyReactiveWakeup.test.ts + opencodeRemoteLauncher.test.ts. Reproduced locally:

  • tip 3967bbbd0: both files pass (379 tests)
  • clean upstream/main worktree: both files pass (221 tests on that tip)

Archive/MCP/permission suites in the same unit-cli job already passed. Treating as unrelated CI flake; no tip change for those files.

@github-actions github-actions Bot removed the codex-review:changes HAPI Bot: review requests changes label Dec 2, 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 (2 Major, 2 Minor)

Review mode: follow-up after new commits

Requirement — Pass

Orchestrators need a CLI and MCP command to stop finished peers, reclaim Runner memory, and retain session history. The revised requirement also protects sessions with visible work and preserves verified Runner cleanup.

Evidence

  • Issue #2020 describes idle workers retaining memory and the manual JWT and REST workaround. Its follow-up specifies refusal before stop RPCs for working sessions and retains verified cleanup.
  • The base CLI registers peer discovery, messaging, and spawning without a peer archive command. cli/src/commands/registry.ts:46
  • The base hub already documents an archive endpoint that waits for Runner cleanup. hub/README.md:147

Approach — Pass

Reusing the namespace-scoped archive endpoint gives CLI and MCP callers the existing lifecycle and cleanup contract. A hub-side precondition can protect work across callers, while projected session state lets the web reflect eligibility.

Evidence

  • The shared CLI helper exchanges the CLI credential, resolves the session, and calls the existing archive endpoint. cli/src/modules/archivePeer/archivePeer.ts:233
  • The route resolves session access against the authenticated namespace. hub/src/web/routes/guards.ts:23
  • The hub checks eligibility before its existing KillSession and Runner cleanup sequence. hub/src/sync/syncEngine.ts:3930

Code — Reviewed

Reviewed the full merge-base diff at 3967bbb. The main remaining issues are archiving a live peer after its heartbeat expires and reporting premature failures through the MCP bridge.

  • [Major] Heartbeat expiry lets archive stop a peer that still has work — hub/src/sync/syncEngine.ts:3931
  • [Major] MCP bridge times out before archive can report its result — cli/src/codex/happyMcpStdioBridge.ts:535
  • [Minor] Stale work markers hide archive recovery in the web UI — web/src/lib/sessionHasLiveWork.ts:34
  • [Minor] Archive refusal gives an ineffective next step for metadata blockers — hub/src/sync/archiveCleanupError.ts:16

Testing

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

  • For fixed head 3967bbb, the test, core, unit-cli, unit-web, integration, browser, wrapper-parity, windows-codex-mcp, and drift-gate checks passed. The advisory review check was in progress.
  • The merge-base diff passed git diff --check. Review verification was read-only.
  • The added tests cover already-gone inactive sessions and groups already busy at confirmation. They do not exercise a still-live Runner worker after heartbeat expiry, a member becoming busy after confirmation, or an archive response that crosses the MCP bridge's default deadline.

HAPI Bot

Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread cli/src/codex/happyMcpStdioBridge.ts Resolved
Comment thread web/src/lib/sessionHasLiveWork.ts Resolved
Comment thread hub/src/sync/archiveCleanupError.ts Resolved
@github-actions github-actions Bot added the codex-review:changes HAPI Bot: review requests changes label Dec 2, 2026
Probe inactive protected rows via non-destructive hostPid before stop RPCs;
raise Codex MCP bridge archive_peer timeout to 130s; align web Archive gate
with inactive recovery; return waiting/exempt-specific refusal guidance.

Co-authored-by: Cursor <[email protected]>
@github-actions github-actions Bot removed the codex-review:changes HAPI Bot: review requests changes label Dec 2, 2026
@heavygee

heavygee commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up tip 65c026a2d

Addressed the tip-matched follow-up review (2 Major / 2 Minor) on 3967bbbd0:

  1. Inactive + protected markers require a non-destructive hostPid probe before Kill/Stop (refuse while alive/unknown).
  2. Codex MCP bridge archive_peer forwarding timeout raised to 130s.
  3. Web sessionBlocksHardArchive only gates active rows so inactive recovery stays reachable.
  4. archive-session-working copy distinguishes turn vs waiting vs idleReconcileExempt.

CI re-running on this tip. Prepare-only.

@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 (1 Major, 2 Minor)

Review mode: follow-up after new commits

Requirement — Pass

Orchestrators need a first-class way to stop finished peers, reclaim Runner memory, and keep conversation history. Archive should refuse while the target has live work and continue to require verified Runner cleanup.

Evidence

  • Issue #2020 describes the manual JWT and REST workaround. Its follow-up calls for a live-work check before stopping the session and retains verified cleanup.
  • The base CLI registers peer discovery, messaging, and spawning without a peer archive command. cli/src/commands/registry.ts:46
  • The base hub already documents an archive endpoint with verified Runner cleanup. hub/README.md:147

Approach — Pass

Reusing the namespace-scoped archive endpoint gives CLI and MCP callers the existing lifecycle and cleanup contract. A hub-side guard enforces the policy across callers, and the web can use projected session state to hide unavailable actions.

Evidence

  • The CLI and MCP share a helper that exchanges the CLI credential, resolves the peer, and calls the archive endpoint. cli/src/modules/archivePeer/archivePeer.ts:233
  • The route resolves session access in the authenticated namespace. hub/src/web/routes/guards.ts:23
  • The guard runs before the existing cleanup sequence. hub/src/sync/syncEngine.ts:3930
  • Group dissolve uses the same policy and refuses when its current snapshot contains a protected member. web/src/components/DissolveGroupButton.tsx:97

Code — Reviewed

Reviewed the full merge-base diff at 65c026a. The inactive-session probe can authorize a stop using evidence about an earlier process and can block retries for an already-stopped Codex root.

  • [Major] A dead PID can authorize stopping a replacement worker — hub/src/sync/syncEngine.ts:3948
  • [Minor] Archive retries reject stopped Codex roots on shared wrappers — hub/src/sync/syncEngine.ts:3952
  • [Minor] Dissolve gives ineffective recovery guidance for waiting or exempt members — web/src/lib/locales/en.ts:543

Testing

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

  • For fixed head 65c026a, core, unit-cli, unit-web, integration, wrapper-parity, windows-codex-mcp, and drift-gate passed. Browser and pr-review were still in progress.
  • The merge-base diff passed git diff --check. PR code and tests were not run locally.
  • The added hub tests mock a dead or live PID. They do not cover a binding change during the probe or an archived Codex root whose sibling keeps the wrapper alive.

HAPI Bot

Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread web/src/lib/locales/en.ts Resolved
@github-actions github-actions Bot added the codex-review:changes HAPI Bot: review requests changes label Dec 2, 2026
Recheck hostPid/active after inactive probes so a replacement worker cannot
inherit a dead-PID pass; use session-scoped stop for already-archived shared
roots; dissolve busy toast names waiting/exempt blockers.

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

heavygee commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up tip 83b34304f

Addressed the latest tip-matched findings (1 Major / 2 Minor):

  1. TOCTOU - recheck active + hostPid after inactive probe before KillSession.
  2. Shared Codex archive retry - already-archived protected rows use session-scoped StopSession (inactive binding) rather than raw hostPid.
  3. Dissolve toast - names turn / waiting / idle-reconcile exempt recovery steps.

Prepare-only.

@github-actions github-actions Bot removed the codex-review:changes HAPI Bot: review requests changes label Dec 2, 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 (3 Major, 1 Minor)

Review mode: follow-up after new commits

Requirement — Pass

Orchestrators need a first-class CLI and MCP command that stops finished peers, frees Runner memory, and preserves conversation history. Archive should refuse while work is ongoing and require verified Runner cleanup before reporting success.

Evidence

  • Issue #2020 describes the manual JWT and REST workaround. Its follow-up specifies a live-work check before stopping the session and retains verified cleanup.
  • The base CLI registers peer discovery, messaging, and spawning without a peer archive command. cli/src/commands/registry.ts:46
  • The base hub documents the archive endpoint and its Runner cleanup contract. hub/README.md:147

Approach — Pass

Reusing the namespace-scoped archive endpoint gives CLI and MCP callers the existing cleanup contract. The hub is the right place to enforce the work guard, and the web can use session summaries to reflect archive eligibility.

Evidence

  • The shared CLI and MCP helper resolves the peer and calls the existing archive endpoint. cli/src/modules/archivePeer/archivePeer.ts:233
  • The route resolves session access in the authenticated namespace. hub/src/web/routes/guards.ts:23
  • The hub checks live work before the existing cleanup sequence, and session summaries carry waiting and exemption state. hub/src/sync/syncEngine.ts:3930, shared/src/sessionSummary.ts:282

Suggestions

  • Update the PR description to reflect that group dissolve refuses when its preflight detects protected work.

Code — Reviewed

Reviewed the full merge-base diff at 83b3430. The hub guard has gaps around disconnected workers and archive retries, and group dissolve can still partially archive a group when a disconnected member is protected.

  • [Major] Archive retry can stop a resumed worker during the guard — hub/src/sync/syncEngine.ts:3953
  • [Major] Heartbeat expiry removes the work evidence the guard needs — hub/src/sync/syncEngine.ts:3931
  • [Major] The PID probe can use the wrong Runner's exit evidence — hub/src/sync/syncEngine.ts:3941
  • [Minor] Dissolve preflight misses disconnected members with protected work — web/src/components/DissolveGroupButton.tsx:97

Testing

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

  • For fixed head 83b3430, core, unit-cli, unit-web, integration, browser, wrapper-parity, windows-codex-mcp, drift-gate, and the aggregate test check passed. pr-review was in progress and owner-approval was skipped.
  • The merge-base diff passed git diff --check. PR code and tests were inspected statically.
  • The added hub tests mock the StopSession result and a numeric PID change. They leave live replacement bindings, mismatched Runner and PID ownership, and work-state loss on heartbeat expiry uncovered. The dissolve test covers an active busy member.

HAPI Bot

Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread hub/src/sync/syncEngine.ts Resolved
@github-actions github-actions Bot added the codex-review:changes HAPI Bot: review requests changes label Dec 2, 2026
Drop inactive hostPid/session Stop probes under waiting/exempt markers.
Those races with resume and shared Codex wrappers; recovery is clear the
marker then archive. Web Archive/dissolve gates match the hub refuse.

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

heavygee commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

Tip 9c7ea0239 — fail closed, drop probes

Follow-up review kept finding TOCTOU races in inactive hostPid / session-scoped Stop probes under waiting / idleReconcileExempt. Those races are real; the fix is not more probes.

Policy now: any blocksHardArchive (active or inactive) → 409 archive-session-working before Kill/Stop, with waiting/exempt/turn-specific guidance. No Runner exit probe under markers. Recovery: clear waiting (session_waiting / CLI), remove exemption, or stop the turn, then archive. Verified Runner cleanup still applies once markers are clear.

Web Archive / dissolve gates match (inactive+waiting blocks dissolve preflight so groups cannot partial-archive around a hub 409).

Prepare-only.

@github-actions github-actions Bot removed the codex-review:changes HAPI Bot: review requests changes label Dec 2, 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 (2 Major)

Review mode: follow-up after new commits

Requirement — Pass

Orchestrators need a CLI and MCP command that stops finished peers, frees Runner memory, and preserves session history. Archive should refuse before interrupting ongoing work and report success only after the existing Runner cleanup checks pass.

Evidence

  • Issue #2020 describes the manual JWT and REST workflow. Its follow-up specifies a shared live-work precondition and retains verified Runner cleanup.
  • The base CLI exposes peer discovery, messaging, and spawning. Peer archive still requires a direct request to the existing hub endpoint. cli/src/commands/registry.ts:46, hub/README.md:147

Approach — Pass

A shared CLI and MCP helper reuses the namespace-scoped archive endpoint. The hub enforces eligibility before shutdown, and the web uses session summaries to reflect that policy.

Evidence

  • The helper resolves the target and calls the existing archive endpoint. The route checks access in the authenticated namespace. cli/src/modules/archivePeer/archivePeer.ts:233, hub/src/web/routes/guards.ts:23
  • The hub checks eligibility before KillSession and retains the Runner confirmation sequence. The list summary carries waiting and exemption markers. hub/src/sync/syncEngine.ts:3930, shared/src/sessionSummary.ts:282

Suggestions

  • Update the PR description to say that group dissolve refuses when its preflight finds a protected target.

Code — Reviewed

Reviewed the full merge-base diff at 9c7ea02. The new head removes the destructive guard probes and includes inactive members with a live lifecycle in the dissolve preflight. Heartbeat expiry and recovery from stale waiting markers still have gaps.

  • [Major] Archive can stop a working peer after heartbeat expiry — hub/src/sync/syncEngine.ts:3930
  • [Major] A crashed peer can leave archive permanently blocked — hub/src/sync/archiveCleanupError.ts:6

Testing

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

  • GitHub checks for 9c7ea02 passed for core, unit-cli, unit-web, integration, browser, wrapper-parity, windows-codex-mcp, drift-gate, and the aggregate test check. pr-review was in progress and owner-approval was skipped.
  • The fixed merge-base diff passed git diff --check. PR code and tests were inspected statically.
  • The added hub tests cover refusal with populated flags and an inactive waiting marker. They leave heartbeat expiry during live work and recovery after the waiting peer exits uncovered.

HAPI Bot

Comment thread hub/src/sync/syncEngine.ts Resolved
Comment thread hub/src/sync/archiveCleanupError.ts Resolved
@github-actions github-actions Bot added the codex-review:changes HAPI Bot: review requests changes label Dec 2, 2026
Inactive archives probe markerless hostPid on metadata.machineId only —
already_gone recovers crashed waiting rows; still_alive refuses before
Kill. No session-scoped Stop in the guard. Dissolve still blocks on
waiting/exempt markers to avoid partial archive.

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

heavygee commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

Tip f69549e09 — inactive probe (no session Stop)

Resolves the contradiction between heartbeat-expiry kill risk and crashed+waiting strand:

  • Inactive archives: markerless hostPid probe on metadata.machineId only (never tree-kills; never session-scoped Stop; never codexResumePending.machineId).
    • already_gone / stopped → proceed (including stale waiting/exempt) + TOCTOU recheck of machineId/hostPid/active
    • still_alive / unknown → refuse (unconfirmed, or working if markers present) before Kill
  • Active + blocksHardArchive → refuse as before
  • Dissolve still blocks on waiting/exempt markers so groups cannot partial-archive

Prepare-only.

@github-actions github-actions Bot removed the codex-review:changes HAPI Bot: review requests changes label Dec 2, 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

Orchestrators need a CLI and MCP command to archive finished peers, reclaim Runner memory, and preserve session history. Archive should refuse before interrupting live work and retain verified Runner cleanup.

Evidence

  • Issue #2020 documents the manual JWT and REST workflow. Its follow-up calls for a shared precondition that protects live work for every archive caller.
  • The base CLI exposes peer discovery, messaging, and spawning. Peer archive still requires a direct request to the hub endpoint. cli/src/commands/registry.ts:46, hub/README.md:147

Approach — Needs changes

The namespace-scoped endpoint and shared hub guard are appropriate. The inactive-session guard uses a bare OS PID to decide whether a session can proceed to cleanup. That probe cannot verify the state of an individual session on a shared wrapper, and requiring it also makes inactive terminal sessions depend on a Runner.

Evidence

  • The new guard probes every inactive row with a machine ID and host PID before reaching the existing cleanup logic. A markerless probe returns unknown while the PID is alive. hub/src/sync/syncEngine.ts:3941, cli/src/runner/sharedSessionStop.ts:43
  • A Codex root can complete shutdown while siblings keep its wrapper alive. Its inactive registry binding is existing stop evidence, but the PID gate returns 409 on retry before the Runner can consult that binding. cli/src/codex/shared/runtime.ts:156, cli/src/runner/run.ts:1475, hub/src/web/routes/sessions.ts:1146
  • Terminal sessions also report a machine ID and PID. An inactive terminal row with a live lifecycle and no Runner now fails the mandatory probe before it reaches the terminal path, where Runner cleanup is best effort. cli/src/agent/sessionFactory.ts:128, hub/src/web/routes/sessions.ts:1153, hub/src/sync/syncEngine.ts:4051

Suggestions

  • Base inactive-session recovery on read-only evidence tied to the target session and its owner generation. Accept a verified exit for a dedicated worker or a verified inactive binding for a shared Codex root. Preserve Runner-independent terminal recovery where the session's end is confirmed, and refuse shutdown while ownership or live work remains uncertain.

Code — Not reviewed

Code review stopped at the approach stage because the inactive-session guard needs a session-scoped way to verify cleanup.

Testing

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

  • The fixed merge-base diff passed git diff --check. PR code and tests were inspected statically.
  • For f69549e, drift-gate and windows-codex-mcp passed. Core, unit-cli, unit-web, integration, browser, wrapper-parity, and pr-review were in progress when checked.
  • The added hub tests mock the PID probe for dead and live workers. They leave the shared Codex retry with a live sibling and the inactive terminal case without a Runner uncovered.

HAPI Bot

@heavygee

heavygee commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

Tip ff9e498ec

  • Runner-owned inactive rows: hostPid probe RPC failure → archive-cleanup-unavailable (no Kill).
  • Terminal / non-runner: probe failure still falls through for Runner-independent cleanup.
  • Markerless unknown / still_alive still refuse before Kill.

Remaining approach tension (no inline threads): shared Codex roots with live sibling wrappers still get markerless unknown and 409 before session-scoped inactive-binding confirmation. Fixing that cleanly needs read-only session/generation evidence on the Runner (bot suggestion) — out of scope for more tip thrash without that RPC. Prepare-only.

@github-actions github-actions Bot removed the codex-review:changes HAPI Bot: review requests changes label Dec 2, 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

Orchestrators need a CLI and MCP command to stop finished peers, reclaim worker memory, and retain conversation history. Archive should protect live work and preserve verified Runner cleanup for every caller.

Evidence

  • Issue #2020 documents the manual JWT and REST workflow and calls for a shared live-work precondition with verified cleanup. #2020
  • The base CLI offers peer messaging, inspection, and spawning. Archive requires a direct hub request. cli/src/commands/registry.ts:46, hub/README.md:147

Approach — Needs changes

Reusing the namespace-scoped archive endpoint and checking live work before shutdown are sound. A wrapper PID cannot establish whether an individual Codex root has stopped, and the terminal fallback still permits shutdown when liveness is uncertain.

Evidence

  • A shared Codex root records its binding as inactive when it ends. The existing Runner cleanup can use that binding to confirm the stop while siblings keep the wrapper alive. The new precheck sees the live PID, gets unknown, and returns 409 before the session-scoped confirmation can run. Archive retries can remain blocked until the siblings exit. cli/src/codex/shared/runtime.ts:156, cli/src/runner/sharedSessionStop.ts:43, cli/src/runner/run.ts:1475, hub/src/sync/syncEngine.ts:3948
  • The new commit refuses Runner-owned rows when the probe fails, but terminal rows still proceed to KillSession without a fresh state check. Heartbeat expiry clears transient work flags independently of session RPC registration. If a terminal session is still working and its RPC is reachable, archive can end it while the Runner is absent or its probe times out. hub/src/sync/sessionCache.ts:1198, hub/src/sync/rpcGateway.ts:898, hub/src/sync/syncEngine.ts:3949, cli/src/claude/registerKillSessionHandler.ts:92

Suggestions

  • Use read-only stop evidence tied to the target session and owner generation. Let a verified inactive Codex binding reach cleanup confirmation while siblings keep running.
  • Require affirmative idle or ended evidence before proceeding after a failed probe. Recheck the current session state after the RPC attempt and preserve Runner-independent recovery for terminal sessions with confirmed end evidence.

Code — Not reviewed

Code review stopped at the approach stage because the inactive-session guard can block confirmed cleanup retries and permit shutdown while terminal work remains live.

Testing

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

  • The fixed merge-base diff passed git diff --check. No PR code or tests ran locally.
  • The added tests cover refusal on an unknown wrapper PID and successful terminal archive without a Runner. They do not cover a successful retry with an inactive Codex binding and a live sibling, or refusal when a working terminal session remains reachable after a failed probe. hub/src/sync/syncEngineArchiveSession.test.ts:464, hub/src/sync/syncEngineArchiveSession.test.ts:485
  • For ff9e498, GitHub reported success for core, windows-codex-mcp, integration, and drift-gate. Browser, unit-web, wrapper-parity, unit-cli, and pr-review were still in progress when checked.

HAPI Bot

@github-actions github-actions Bot added the codex-review:changes HAPI Bot: review requests changes label Dec 2, 2026
Probe throw/unavailable no longer falls through to KillSession. Markerless
unknown hostPid asks read-only STATUS-<sessionId> for inactive Codex binding
or verified exit so finished shared roots can archive while siblings keep the
wrapper.

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

heavygee commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

Tip 542279621 addresses the remaining Approach holes on de73/ff9e:

  1. Probe throw / unavailable — inactive hostPid probe failure now always refuses (archive-cleanup-unavailable / working) before KillSession; no fall-through when markers are empty.
  2. Shared Codex recovery — markerless unknown on the wrapper PID now asks read-only STATUS-<sessionId> (inactive Codex binding / verified exit). Destructive session Stop is not used in the guard. Old runners that do not recognize STATUS-* return unknown → fail-closed refuse.

Regression coverage: probe-throw + no markers → zero KillSession; inactive Codex binding + live sibling wrapper → archive proceeds via STATUS evidence (syncEngineArchiveSession + run.stopSession).

PR description updated for dissolve refuse on protected work. Prepare-only; no cold-review-clean requested.

@github-actions github-actions Bot removed the codex-review:changes HAPI Bot: review requests changes label Dec 2, 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

Orchestrators need a first-class way to stop finished peers, reclaim worker memory, and retain conversation history. Archive should protect live work and preserve verified Runner cleanup.

Evidence

  • Issue #2020 documents the manual JWT and REST workflow. The follow-up discussion narrows the request to a shared live-work precondition with verified cleanup. #2020
  • The base CLI exposes peer messaging, inspection, and spawning. Peer archive requires a direct hub request. cli/src/commands/registry.ts:46, hub/README.md:147

Approach — Needs changes

Reusing the namespace-scoped archive endpoint and checking for live work before shutdown are sound. The inactive-session guard can accept evidence from a previous Codex owner and makes terminal crash recovery depend on a Runner.

Evidence

  • A shared Codex wrapper retains an inactive binding while siblings run, and a cold resume can bind the same HAPI session ID in a second wrapper. STATUS looks up the first binding by session ID without receiving the probed PID or generation. If the resumed root's heartbeat expires, the old inactive binding can authorize archive while the new root is still working. cli/src/codex/shared/runtime.ts:156, cli/src/codex/shared/runtime.ts:395, cli/src/runner/sharedSessionStop.ts:65, cli/src/runner/run.ts:1385, hub/src/sync/syncEngine.ts:3987
  • Terminal sessions publish a machine ID and host PID. After an abrupt exit leaves a terminal row inactive with a running or idle lifecycle, archive now returns 503 when its host has no Runner. The base explicitly supported hub-side archive recovery in that configuration. cli/src/agent/sessionFactory.ts:123, hub/src/web/routes/sessions.ts:1153, hub/src/sync/syncEngine.ts:3953, hub/src/sync/syncEngine.ts:4082

Suggestions

  • Tie read-only end evidence and subsequent shutdown to the same current owner generation. Include the wrapper identity in the status request and let any current active binding take precedence over historical inactive bindings or exit records.
  • Provide a Runner-independent terminal recovery path using affirmative idle or end evidence. Keep destructive calls blocked when heartbeat expiry is the only evidence.

Code — Not reviewed

Code review stopped at the approach stage because the inactive-session guard can authorize shutdown for the wrong owner and prevent recovery on Runner-free terminal hosts.

Testing

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

  • The fixed merge-base diff passed git diff --check. No PR code or tests ran locally.
  • The added STATUS tests cover individual active and inactive bindings. They do not exercise an old inactive binding alongside a resumed active binding for the same session. The Runner-free terminal test starts with an active row and does not exercise crash recovery. cli/src/runner/run.stopSession.test.ts:146, hub/src/sync/syncEngineArchiveSession.test.ts:804
  • For 5422796, GitHub reported success for core, windows-codex-mcp, unit-cli, wrapper-parity, integration, and drift-gate. Unit-web, browser, and the current PR review were in progress. An earlier PR review run was cancelled.

HAPI Bot

@github-actions github-actions Bot added the codex-review:changes HAPI Bot: review requests changes label Dec 2, 2026
STATUS-<pid>:<session> prefers any active binding (cold-resume on another
wrapper) over a historical inactive binding. Terminal / non-runnerOwned rows
skip the Runner hostPid probe so crash recovery stays KillSession-based.

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

heavygee commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

Tip 602e7d99f follow-up on tip-matched Approach from 542279621:

  1. STATUS owner generation — wire is now STATUS-<hostPid>:<sessionId>. Any active binding for the logical id (including cold-resume on another wrapper) returns still_alive before an inactive binding on the probed PID can authorize archive.
  2. Terminal no-Runner recovery — hostPid probe applies only to runnerOwned rows. Terminal / non-runnerOwned inactive rows skip it and keep KillSession-based recovery when no Runner is present (fix(runner,hub): cross-platform orphan reap on archive / tracking loss #1911).

Regression: resumed active binding on another PID → STATUS still_alive; quiet inactive terminal + no Runner → archive proceeds. Prepare-only; no CRC.

@github-actions github-actions Bot removed the codex-review:changes HAPI Bot: review requests changes label Dec 2, 2026
heavygee and others added 2 commits December 2, 2026 16:45
Codex PR Review Analyze hung across three attempts on 602e7d9; empty tip
to force a fresh pull_request_target review run.

Co-authored-by: Cursor <[email protected]>
Comment-only sync with the shipped STATUS-<hostPid>:<sessionId> + terminal
skip behavior so synchronize re-triggers CI/review after a hung Analyze.

Co-authored-by: Cursor <[email protected]>
@heavygee
heavygee marked this pull request as draft December 2, 2026 16:52
@heavygee
heavygee marked this pull request as ready for review December 2, 2026 16:52
@heavygee

heavygee commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

Temporary close/reopen to re-trigger CI + tip-matched Codex PR Review after synchronize events stopped delivering (tip 2392574). Prepare-only.

@heavygee heavygee closed this Dec 2, 2026
@heavygee heavygee reopened this Dec 2, 2026
@heavygee

heavygee commented Dec 2, 2026

Copy link
Copy Markdown
Collaborator Author

Ops note (prepare-only): tip 239257494 currently has zero check suites.

Timeline:

  • 602e7d99f addressed tip-matched Approach from 542279621 (STATUS-<hostPid>:<sessionId> with active-anywhere precedence; terminal/non-runnerOwned skip hostPid probe). Product CI was green on that tip.
  • Tip-matched Codex PR Review Analyze hung ~40m then cancelled; reruns stuck on the same Analyze step (openai/codex-action, stream_idle_timeout_ms=600000).
  • Later synchronize / draft↔ready / close↔reopen events are recorded on the PR but spawned no Test or Codex PR Review runs.

Today is also GitHub's 2026-12-02 pull_request_target default-block enforcement date (changelog). Codex PR Review is on: pull_request_target — if tiann/hapi lacks an explicit Actions event policy allowlisting that workflow, tip-matched review will not start until a maintainer adds the policy (or migrates the workflow). Product pull_request Test not firing either still looks like a separate delivery/approval gap.

No cold-review-clean requested from this tip.

@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

Orchestrators need a supported way to stop finished peers, reclaim worker memory, and retain conversation history. The issue discussion calls for a shared archive guard that protects live work and preserves verified Runner cleanup.

Evidence

  • Issue #2020 describes the manual JWT and REST workflow. Its follow-up adopts a common live-work precondition for all archive callers. #2020
  • The base CLI supports pinging, inspecting, and spawning peers. Archive requires a direct hub request. cli/src/commands/registry.ts:46, hub/README.md:147

Approach — Needs changes

Reusing the namespace-scoped archive endpoint and checking live work before shutdown are sound. The inactive-session policy still lets a heartbeat-expired terminal session be archived mid-turn and can make Codex resume recovery depend on an obsolete Runner.

Evidence

  • Heartbeat expiry clears thinking, background tasks, and open-tool state. A terminal-started Codex session disconnected mid-turn can therefore pass the guard without any idle or exit evidence. If KillSession cannot reach it and there is no Runner, the hub writes archive metadata. The CLI reads that metadata on reconnect and ends the root. hub/src/sync/sessionCache.ts:1198, hub/src/sync/syncEngine.ts:3954, hub/src/sync/syncEngine.ts:4095, cli/src/api/apiSession.ts:315, cli/src/codex/shared/root.ts:690
  • An unconfirmed Codex resume can record a pending Runner distinct from the previous machine, such as when resume falls back to an online Runner with the same hostname. The preflight probes the previous machine and returns 503 if it is offline, before cleanup can ask the pending Runner to confirm termination. This blocks an existing recovery path even when the pending Runner can prove the process exited. hub/src/sync/syncEngine.ts:434, hub/src/sync/syncEngine.ts:3951, hub/src/sync/syncEngine.ts:4038, hub/src/sync/syncEngine.ts:5810, hub/src/sync/archivedFork.test.ts:121

Suggestions

  • Preserve the last known working state across heartbeat expiry for archive eligibility. Keep Runner-free recovery for quiet terminal crashes, and require fresh idle or explicit end evidence before archiving a disconnected terminal session last seen working.
  • Use the persisted pending resume target for reconciliation. Require any read-only status evidence to identify that owner, and preserve the existing verified cleanup path for an unconfirmed startup.

Code — Not reviewed

Code review stopped at the approach stage because inactive archive eligibility can discard live terminal work and block recovery of an unconfirmed Codex resume.

Testing

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

  • The fixed merge-base diff passed git diff --check. This review did not execute PR code or tests.
  • The added Runner-free terminal test starts with a quiet inactive row and mocks a successful KillSession. It leaves the mid-turn disconnect case uncovered. hub/src/sync/syncEngineArchiveSession.test.ts:515
  • For 2392574, GitHub reported success for core, windows-codex-mcp, unit-cli, unit-web, wrapper-parity, integration, browser, test, and drift-gate. The current PR review check was in progress and an earlier run was cancelled.

HAPI Bot

@github-actions github-actions Bot added the codex-review:changes HAPI Bot: review requests changes label Dec 2, 2026
heavygee and others added 2 commits December 3, 2026 00:13
Answers tip-matched Evidence on 2392574:
- inactive + hostPid always markerless-probes (terminal included); throw /
  unknown refuse before KillSession; already_gone/stopped may proceed
- prefer codexResumePending.machineId over metadata.machineId for probes

Deliberately declines aspirational Suggestion "preserve last known working
state across heartbeat expiry" (no expireInactive redesign).

Co-authored-by: Cursor <[email protected]>
Preserve mid-turn archive refusal after expireInactive clears thinking/tools;
quiet terminal crashes without the latch still archive Runner-free. Clear the
flag on reconnect; hostPid already_gone still proves exit.

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

heavygee commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed both Approach bullets from tip 239257494 in 6de1e0976 (+ 28b1a8a1d):

  1. Heartbeat-expired terminal mid-turn — expireInactive now latches hub-owned metadata.expiredWhileWorking when keepalive dies mid-thinking / derived-tool / background work. blocksHardArchive honours that latch after turn UI flags are cleared. Mid-turn disconnect + expiry + no Runner → archive-session-working (no KillSession). Quiet inactive terminal crash (no latch, no hostPid) still archives Runner-free. Latch clears on become-active; hostPid already_gone/stopped still proves exit. Regression: refuses mid-turn terminal disconnect after heartbeat expiry without Runner, plus clear-on-alive and dead-pid recovery tests.

  2. Pending Codex resume vs obsolete Runner — inactive probe / Kill follow-up prefer codexResumePending.machineId over metadata.machineId so STATUS/read-only evidence and cleanup hit the pending owner (already on prior tip; covered by probes the pending resume Runner machine before refusing).

No CRC. Prepare-only.

heavygee and others added 2 commits December 3, 2026 01:11
Conflict re-merge only for tiann#2740 Gate 1; preserve Approach semantics.
@heavygee

heavygee commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

Merge resolution note (02b3d7352 ← upstream/main)

Gate 1 conflict re-merge only. git merge upstream/main completed with no conflict markers (ort auto-merge). Axes / live call sites:

  1. Archive Approach semantics (ours kept intact). Inactive guard still: markerless PID-N probe; STATUS-<hostPid>:<sessionId> for Runner-owned unknown; prefer codexResumePending.machineId over metadata.machineId; terminal hostPid throw/unknown refuse with 0 Kill; quiet no-hostPid archive OK; expiredWhileWorking latch via expireInactive → blocksHardArchive. Live sites: hub/src/sync/syncEngine.ts (archiveSessionUnlocked), sessionIdle.ts, sessionCache.ts, shared/src/schemas.ts.

  2. Upstream delete-session graft (theirs). Adopted assertSessionDeletable extraction from fix(hub): keep duplicate merge consistent when a later delete is refused #2764-era main; our tip still calls it from deleteSession and keeps the Codex-resume / rewind refuse paths. No archive-guard edit in that hunk.

  3. Dissolve rename (theirs file + our guards). Upstream renamed DissolveGroupButton.tsx → DissolveGroupDialog.tsx with unconfirmed-storage retry. Auto-merge kept our preflight: sessionBlocksHardArchive / sessionHasProtectedArchiveMarkers before any archive. Live sites: DissolveGroupDialog.tsx, SessionList.tsx.

  4. Locales / SessionList. Auto-merged; our archive busy / dissolve strings retained alongside main's group/UI polish.

No Approach chase, body-edit retrigger, or CRC on this tip. Focused archive unit tests green locally (sessionIdle / syncEngineArchiveSession / sessionHasLiveWork).

Merge with main moved dissolve into the context menu; the quiet-path
group test still clicked a missing button.

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

heavygee commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

Follow-up on merge tip: unit-web failed on SessionList.groups.test.tsx quiet-path dissolve — our branch still clicked a top-level button "Dissolve group", but main's Dialog rename moved the entry to the leader context menu. Fixed in fd9c8504a by using the shared openDissolve() menuitem helper (same as the busy-path test). No product/Approach change.

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

Development

Successfully merging this pull request may close these issues.

feat(cli+hub): archive_peer MCP/CLI — soft stand-down twin of spawn_peer

1 participant