Skip to content

fix(pi): gate first provider call on startup context - #3158

Merged
kunchenguid merged 9 commits into
kunchenguid:mainfrom
M00NLIG7:fm/firstmate-pi-new-startup-race-fix-v1-f9
Aug 29, 2026
Merged

kunchenguid merged 9 commits into
kunchenguid:mainfrom
M00NLIG7:fm/firstmate-pi-new-startup-race-fix-v1-f9

Conversation

@M00NLIG7

Copy link
Copy Markdown
Contributor

Intent

Fix the reproducible Pi /new startup-context race on the fetched current origin/main implementation base and publish one PR whose canonical base is exactly github.com/kunchenguid/firstmate, without merging it. The user-visible failure is triggered by submitting the first prompt immediately after /new while native startup digest generation is still running: the first provider call can occur before native delivery, lacks startup context, causes the documented manual fallback to run, and a later call then contains both manual and native startup digests. Preserve the comparison with the proven path where native startup completes before prompt submission, retain the deterministic local-provider reproduction as the regression basis, and seek disconfirming evidence for the ownership fix.

Implement the smallest current-code-aligned generation-bound owner in .pi/extensions/fm-primary-turnend-guard.ts: activate one generation on session_start, bind it to the Pi session and monotonic generation, make before_agent_start await that matching startup result and return the persistent context message immediately upstream of the first provider call, prevent asynchronous native delivery from racing that call, ignore stale generations, and terminate the matching child process group with no late delivery on shutdown or replacement. If an eligible native attempt fails or yields no digest, let that exact attempt settle before injecting the existing exact manual fallback instruction so native and manual generation never run concurrently. Preserve conservative full-start behavior, lock/refusal behavior, loud truncation and direct-inspection guidance, context-preserving source behavior, compaction behavior, and every supported Pi and pi-signed source route. Do not implement the investigation report's unrelated context-efficiency items 1-7.

Acceptance requires an end-to-end immediate-/new regression proving no provider call occurs before the matching prerequisite settles; exactly one startup execution and one model-visible startup context for each generation; the first provider payload contains that context; and deterministic executable coverage for interruption, shutdown, child/grandchild retirement, two rapid replacements, stale completion, empty output, spawn error, nonzero failure, intentional ineligibility, timeout, and truncation with no stale delivery. Keep existing startup, supervision, wake, and harness behavior passing across applicable Pi and pi-signed surfaces. Correct maintained documentation that previously claimed race-free delivery, keep one sentence per Markdown line, and route evidence to its proper owner. Run repository-prescribed syntax and lint checks, bin/fm-doc-audience-check.sh, documentation validation, applicable startup suites, and the real no-network Pi 0.84.0 regression using an isolated home, barrier-controlled digest, and deterministic local provider.

The preserved read-only investigation at /Users/cmagana/cerebro/data/firstmate-public-head-context-plan-v1-s6/report.md must remain unchanged. A later bounded base-vs-branch counterfactual established that the unchanged bootstrap-parallelism overlap assertion fails identically on exact origin/main under equivalent conditions, with byte-identical normalized timelines and no task diff touching its owners; preserve that as a pre-existing or environment-sensitive limitation and do not weaken, skip, or edit the unrelated bootstrap regression merely to obtain green. Publish only the task branch through the full no-mistakes pipeline, use GitHub author and committer identity exactly M00NLIG7 <[email protected]> with no agent co-author, verify that identity again before publication, open the authorized upstream PR against exactly github.com/kunchenguid/firstmate, and stop when its required CI is green. Never merge the PR.

What Changed

  • Gate Pi’s first provider call on the matching session-start generation and inject its startup context exactly once, with manual fallback only after an eligible native attempt settles unsuccessfully.
  • Supervise and retire startup process groups on replacement, shutdown, interruption, or stale completion, while distinguishing intentional Pi prerequisite stand-downs from failures.
  • Expand portable and offline Pi regression coverage for immediate /new, lifecycle and failure paths, and update documentation to reflect prerequisite-based delivery.

Risk Assessment

✅ Low: Captain, the generation-bound prerequisite, supervised process-group lifecycle, failure fallback, and fixture dependency changes are coherent and no material source risk remains.

Testing

With no prior baseline results supplied, I verified the required runtime, passed the targeted executable lifecycle/failure regression, and passed the real isolated no-network Pi 0.84.0 /new reproduction; the saved transcript demonstrates prompt blocking, exactly one native context per generation, and no manual fallback for both immediate and completed-before-prompt paths.

Evidence: Offline Pi `/new` race transcript

Source: Offline Pi /new race transcript

Pi 0.84.0: immediate and completed-before-prompt /new paths each made one first provider call with exactly one native startup context and no manual execution.

ok - Pi 0.84.0: immediate and completed-before-prompt /new paths each made one first provider call with exactly one native startup context and no manual execution
# fm-sessionstart-hook-live-e2e.test.sh: offline Pi /new race assertions passed

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

🔧 **Review** - 1 issue found → auto-fixed (6) ✅
  • 🚨 .pi/extensions/fm-primary-turnend-guard.ts:189 - Retirement treats the direct child's close as proof that the entire process group exited. If a descendant ignores SIGTERM and has redirected/closed stdio, the leader can close first, childClosed becomes true, and SIGKILL is skipped, leaving that descendant running after replacement or shutdown. After the grace period, probe/kill the captured process group independently of the leader's close state, and cover a TERM-resistant descendant with closed stdio.

🔧 Fix: Captain, fix startup process-group retirement after leader exit
1 warning still open:

  • ⚠️ .pi/extensions/fm-primary-turnend-guard.ts:395 - The module-level exit listener is never removed. Pi clears and reloads extension modules on /reload, so each reload adds another retained process.once(&#34;exit&#34;) callback holding that module generation and potentially its 512 KiB result. Repeated reloads cause memory growth and eventually MaxListenersExceededWarning. Register cleanup per bound extension instance and remove it during session_shutdown so the replacement instance owns the sole exit fallback.

🔧 Fix: Captain, release reload exit listeners on shutdown
2 errors still open:

  • 🚨 .pi/extensions/fm-primary-turnend-guard.ts:484 - Pi supports same-bound-instance session_shutdown → session_start replacement, but shutdown permanently removes this instance's exit listener and session start never restores it. After /new, /resume, or /fork, a later active startup generation therefore lacks process-exit cleanup. Re-register the listener idempotently when each session activates, and add same-instance replacement coverage.
  • 🚨 .pi/extensions/fm-primary-turnend-guard.ts:439 - The process-exit fallback still depends on generation.child. If the leader closes while a TERM-resistant descendant with closed stdio remains, markClosed() clears that field, so exit cleanup skips the captured process group and orphans the descendant. On non-Windows platforms, signal the retained processGroupId directly even after leader close; preserve the current Windows path and cover this sequence.

🔧 Fix: Captain, complete startup exit lifecycle ownership
1 error still open:

  • 🚨 .pi/extensions/fm-primary-turnend-guard.ts:445 - A completed generation retains its numeric process-group ID indefinitely. After the child closes and that ID is reused, /new, shutdown, or process-exit cleanup can send TERM/SIGKILL to an unrelated process group. Monitor the retained group after leader close and clear processGroupId as soon as the group becomes empty, while preserving it for verified surviving descendants.

🔧 Fix: Captain, release empty startup process-group ownership promptly
2 errors still open:

  • 🚨 .pi/extensions/fm-primary-turnend-guard.ts:392 - The required criterion says, “If an eligible native attempt fails or yields no digest ... inject[] the existing exact manual fallback instruction,” but this allowlist suppresses fallback for resume and fork even when their child has a spawn error or nonzero exit. Preserve intentional context-restored silence for expected empty results, but return the exact fallback for failed eligible attempts on every source.
  • 🚨 .pi/extensions/fm-primary-turnend-guard.ts:193 - The 10 ms existence polling still retains only a reusable numeric process-group ID: after a successful probe, the matching group can empty and its ID can be reused before the next tick; the monitor then accepts the unrelated group as alive, and later replacement or process-exit cleanup sends it SIGTERM/SIGKILL. This leaves the previously reported unrelated-process termination reachable. Move retained ownership to a stable launch boundary—such as a supervisor that remains the group leader until ownership is released—rather than retaining an unidentifiable bare PGID after the leader closes.

🔧 Fix: Captain, supervise startup ownership and restore failure fallback
1 error still open:

  • 🚨 tests/fm-sessionstart-hook-live-e2e.test.sh:354 - Both isolated Pi fixture builders in this file copy the extension without its new lib/fm-sessionstart-supervisor.mjs runtime dependency (also see line 179). Node therefore exits with a missing-module error, and the required /new regression reaches fallback instead of producing RACE_NATIVE context. Copy the supervisor into each fixture’s lib directory so the live tests exercise the production path.

🔧 Fix: Captain, restore live Pi supervisor execution
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • pi --version and tmux -V confirmed Pi 0.84.0 and tmux 3.6a.
  • tests/fm-sessionstart-nudge.test.sh
  • FM_PI_SESSIONSTART_RACE_LIVE_E2E=1 tests/fm-sessionstart-hook-live-e2e.test.sh
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@greptile-apps

greptile-apps Bot commented Aug 27, 2026

Copy link
Copy Markdown

Confidence Score: 5/5

The PR appears safe to merge, with no concrete changed-code failure remaining after review.

The generation owner gates provider startup on the matching result, suppresses stale delivery, retires supervised process groups across lifecycle transitions, and preserves intentional silence separately from failure fallback.

Reviews (1): Last reviewed commit: "no-mistakes(document): docs: clarify Pi ..." | Re-trigger Greptile

@kunchenguid

Copy link
Copy Markdown
Owner

Speaking as Kun's firstmate:

Reviewed HEAD a2d755e50509e9d617e0ebc33a565e3127e088ec vs main d63b0e2feeafd5a91e6f229ab9510d6d7f5ed17d. Whole thread read (Greptile success). Full diff reviewed: .pi/extensions/fm-primary-turnend-guard.ts, .pi/extensions/lib/fm-sessionstart-supervisor.mjs, bin/fm-session-start.sh, bin/fm-sessionstart-run.sh, docs/sessionstart-nudge.md, docs/verification/supervision.md, tests/fm-sessionstart-hook-live-e2e.test.sh, tests/fm-sessionstart-nudge.test.sh. No .github/workflows/*. Not pull_request_target, not a proposed-head checkout, not a pin change, not a no-mistakes-gate weaken. The new supervisor only wraps bin/fm-sessionstart-run.sh and reports exit/bytes over IPC; process-group TERM/KILL is retirement of that child tree. Not disguised security.

Class: corrective. Immediate /new could make the first provider call before native startup settled, so the first turn lacked startup context and a later call could carry both manual and native digests. Gating before_agent_start on the matching generation, injecting one context, and falling back only after an eligible native attempt settles restores the existing run-tier contract. Docs that previously claimed race-free delivery are corrected, not expanded into a new product default.

VISION (per rule, inspected evidence):

  • One captain, one interface — aligns. The first turn after /new keeps the helm digest instead of racing a context-less provider call.
  • Authority is explicit — aligns. No new autonomy; gate/scope stand-downs stay silent (exit 3 only on the internal --pi-prerequisite path).
  • Scripts own the mechanics — aligns. Generation ownership, process-group retirement, and the exit-3 ineligible signal are scripted; the agent is not asked to guess whether startup finished.
  • A restart is a non-event — aligns. Replacement and shutdown retire the matching child group; stale generations cannot deliver.
  • Delegation with a spine — aligns. Restores an existing session-start contract, not a new task shape.
  • The fleet outlives any vendor — aligns. Other run-tier harnesses keep hook-stdout delivery; this is the Pi message-injection path only.
  • Scope — aligns. Command-layer session-start transport, not workshop/merge policy.

First-time fork CI: after that full-diff review I approved workflow runs 33043729510 (CI) and 33043729470 (Require no-mistakes) for this HEAD.

Not merging. no-mistakes-pipeline-attestation:v1 matches this HEAD, but forge CI had not run yet (held at action_required). Waiting on those checks to go green, not on a product rewrite. Not a captain-decision hold.

Merge-eligible: NO (waiting-ci). Captain-flag NOW: NO.

@M00NLIG7

M00NLIG7 commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

@kunchenguid Thanks for reviewing and approving the workflow runs. All 14 checks are now green on the same reviewed HEAD a2d755e50509e9d617e0ebc33a565e3127e088ec, with no conflicts. Ready for merge when convenient.

@M00NLIG7

Copy link
Copy Markdown
Contributor Author

Any updates on this?