Repository navigation
fix(bin): reconcile inactive terminal outcomes - #2140
Closed
kunchenguid wants to merge 25 commits into
Closed
kunchenguid wants to merge 25 commits into
kunchenguid wants to merge 25 commits into
Conversation
Owner
Author
|
Superseded by #2167. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Intent
Implement the report-approved inactive terminal-outcome reconciliation for Firstmate supervision. On the existing watcher poll loop and locked session start only, deterministically inspect long-inactive, non-captain-held direct crewmates with fm-crew-state and surface only authoritative done or failed outcomes. Keep a durable outcome receipt distinct from heartbeat markers until the secondmate parent report or main captain presentation is acknowledged. Have secondmate homes idempotently report their own terminal children through the established local or remote parent channel. Have the main home independently inspect validated secondmate structured summaries, create one marked correlated pending-reply request for a missing report, and preserve the obligation. Never treat a healthy parked or idle secondmate as wedged. Never call GitHub, a forge, PR APIs, PR polls, or state check scripts. Use the independent 60..1800 second bounded gate instead of heartbeat backoff and add behavioral tests for both levels, missing reports, restart idempotency including remote mirror input, heartbeat cap, nonterminal and captain-held exclusions, no false wedge, and zero forge calls. Also preserve structured-summary compatibility and prevent Bearings PR enrichment from treating a descendant directory as its ancestor git worktree.
What Changed
doneorfailedcrewmate outcomes, with durable receipts acknowledged only after parent reporting or captain presentation.Risk Assessment
✅ Low: The reconciliation changes now appear to satisfy the stated durability, compatibility, bounded-cadence, pagination, and no-forge requirements without a substantiated remaining defect.
Testing
Inspected the change, repaired stale remote-summary protocol assertions, added the missing behavioral descendant-worktree regression, and reran both targeted suites successfully; evidence demonstrates durable two-level reconciliation, paging and restart behavior, exclusions, heartbeat independence, no false wedge, zero forge calls, and safe Bearings PR enrichment. This is CLI behavior, so no visual screenshot was applicable.
Evidence: Inactive terminal-outcome reconciliation behavioral transcript
Evidence: Bearings projection and descendant-worktree behavioral transcript
Evidence: Inactive reconciliation test timing artifact
Evidence: Bearings test timing artifact
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
🔧 **Review** - 4 issues found → auto-fixed (21) ✅
bin/fm-wake-drain.sh:64- Lock ordering can deadlock: reconciliation holds.inactive-outcome-reconcile.lockwhilefm_wake_appendwaits for.wake-queue.lock, whereas drain holds.wake-queue.lockhere whileacknowledgewaits for the reconciliation lock. Apply receipts outside the queue-lock critical section or enforce one shared lock order.bin/fm-inactive-reconcile.sh:297- Local and remote secondmate summary commands are unbounded. An unreachable remote or hung child-state probe can indefinitely block the watcher poll, its beacon, and the reconciliation lock. Use the existingfm_run_timedsummary timeout and output byte cap around both summary paths.bin/fm-inactive-reconcile.sh:314- This contradicts the required behavior to "create one marked correlated pending-reply request for a missing report, and preserve the obligation":request_attempted=1is committed before pending-reply creation or delivery. Creation failure sends an uncorrelated request, while delivery failure leaves an undelivered record that pending-reply ticking ignores; all later scans return early permanently. Preserve/retry the same correlated request until delivery is confirmed or explicitly recorded unknown.bin/fm-inactive-reconcile.sh:410- This contradicts the requirement to inspect "validated secondmate structured summaries" and surface only authoritative outcomes. Validation checks only schema and array type, so wrong-home, stale, or otherwise malformed output can create requests and captain wakes. Validate home identity, freshness where applicable, required typed fields, and bounded output using the established structured-summary boundary before consuming terminal children.🔧 Fix: Bound summaries and eliminate wake lock inversion
3 errors still open:
bin/fm-inactive-reconcile.sh:352- The required “one marked correlated pending-reply request … and preserve the obligation” is not durable: request_attempted is committed before correlation creation or delivery. A creation or send failure permanently suppresses later attempts, and an awaiting_report record without confirmed delivery is ignored by pending-reply ticking. Preserve and retry the same correlation until delivery is confirmed or explicitly recorded unknown.bin/fm-inactive-reconcile.sh:448- The required “validated secondmate structured summaries” boundary checks only schema and array type. A wrong-home, stale, or malformed summary can therefore create requests and captain wakes. Apply the established home/generated/type validation, including typed terminal entries and the expected terminal-in-flight invalidity, before consuming outcomes.bin/fm-fleet-snapshot.sh:752- terminal_children is permanently truncated to the first FM_SNAPSHOT_SECONDMATE_CHILDREN entries (default 20), with no terminal omission marker or pagination. If an omitted terminal child lacks its parent report, every main-home scan sees the same prefix and never creates the required missing-report obligation. Expose all bounded terminal anomalies or provide deterministic pagination/omission reconciliation.🔧 Fix: Preserve and validate inactive reconciliation obligations
5 errors still open:
bin/fm-inactive-reconcile.sh:434- This still violates “create one marked correlated pending-reply request”: if delivery succeeds and the process exits before line 435 records request_attempted, the pending reply is already awaiting_report but the next scan reuses its correlation and sends the request again. Persist the attempt after durable delivery preparation but before invoking the transport, leaving delivery uncertainty to the pending-reply owner.bin/fm-inactive-reconcile.sh:414- A valid summary permanently moves the mate's fixed summary-obligation fingerprint to .reported. If that summary later becomes stale, malformed, or unavailable, ensure_record sees the tombstone and cannot create or announce a new obligation, contradicting the requirement that such summaries preserve or raise reconciliation. Clear or version the resolved summary episode so later failures can become pending again.bin/fm-fleet-snapshot.sh:752- terminal_children now emits every anomaly into one unbounded JSON array, while the reconciliation reader rejects the entire summary above FM_SNAPSHOT_SECONDMATE_MAX_BYTES. With enough terminal children, every scan therefore loses all child-specific missing-report obligations and raises only a generic summary error. Implement a deterministic bounded/paginated anomaly channel that eventually exposes every terminal child.bin/fm-inactive-reconcile.sh:391- A producer-valid terminal_children channel is rejected whenever an earlier strict invalidity also exists: fm-fleet-snapshot selects only the first invalidity (for example unstructured_current), but this validator requires invalidity.kind=terminal_in_flight. Thus a terminal child plus one competing anomaly never reaches reconcile_secondmate_child and never gets its required correlated missing-report request. Validate the terminal anomaly channel independently of the summary's primary invalidity, or expose all invalidities authoritatively.bin/fm-inactive-reconcile.sh:336- Startup intentionally skips every remote summary, but scan_secondmates converts that deliberate skip into an unavailable-summary obligation and actionable wake. Consequently any long-idle healthy remote secondmate produces a false reconciliation alert at locked session start, contrary to “Never treat a healthy parked or idle secondmate as wedged.” Skip remote summary reconciliation at startup and leave its bounded inspection to the watcher poll.🔧 Fix: Harden paginated inactive outcome reconciliation
3 errors still open:
bin/fm-inactive-reconcile.sh:434- The required “create one marked correlated pending-reply request” is not crash-safe:fm_pending_reply_createdurably creates an expectation before its correlation is stored in the outcome record. A process exit before line 436 leaves an orphan; the next scan creates a second correlation. Create/link the expectation atomically or recover an existing expectation by a durable outcome identity.bin/fm-inactive-reconcile.sh:366- The requirement that malformed summaries “preserve or raise the reconciliation obligation rather than … trust them” remains violated. Validation accepts semantically inconsistent pages, includingvalid:truewith terminal children, entries not ordered or greater thanafter, and a first page declaringhas_more:falsewhiletotalexceeds its length. Such input is consumed as authoritative and can create false requests or conceal omitted children. Validate these paging and terminal-state invariants before consumption.bin/fm-inactive-reconcile.sh:584- The required guarantee that bounded pagination eventually exposes every unresolved terminal child is lost when cursor persistence fails: the error is ignored, every later scan rereads the same first page, and later children remain unreachable. Preserve/raise a reconciliation obligation and fail the scan when the cursor cannot be committed.🔧 Fix: Harden inactive reconciliation crash recovery and pagination
3 errors still open:
bin/fm-inactive-reconcile.sh:384- This contradicts “preserve structured-summary compatibility”: existingfm-secondmate-home-summary.v1output has noterminal_children, so it is rejected and a healthy older/remote secondmate raises a false summary obligation. Accept the legacy shape as having no authoritative terminal channel while retaining strict validation for the new channel.bin/fm-inactive-reconcile.sh:391- The validated-summary boundary acceptsterminal_childrenwhenterminal_pageis absent (else true). Such a malformed summary can present an arbitrary partial list while concealing omitted terminal children, violating the requirement to preserve reconciliation obligations. Require paging metadata whenever the terminal anomaly channel is present; handle genuinely legacy summaries separately.tests/fm-bearings-snapshot.test.sh:767- Both exactterminal_pageassertions omit the newly emittedcountandremainingfields, so the behavioral test necessarily rejects the producer output at lines 766–772. Update both expected objects to include the page counters.🔧 Fix: Update terminal page counter expectations
4 errors still open:
bin/fm-inactive-reconcile.sh:384- This contradicts the required “preserve structured-summary compatibility”: existing fm-secondmate-home-summary.v1 producers omit terminal_children, so healthy older or remote secondmates are rejected and raise false reconciliation alerts. Accept the legacy shape as having no terminal anomaly channel.bin/fm-inactive-reconcile.sh:391- A summary containing terminal_children is accepted without terminal_page metadata. An arbitrary partial anomaly list can therefore be trusted while omitted children remain concealed. Require valid paging metadata whenever terminal_children is present, while handling genuinely legacy summaries separately.bin/fm-inactive-reconcile.sh:593- The return from reconcile_secondmate_child is ignored, so failure to persist a child obligation still advances the page cursor. If that child then disappears from the producer’s terminal set before pagination wraps, its missing report is never preserved. Abort the page and retain its cursor when any child reconciliation fails.bin/fm-inactive-reconcile.sh:491- This contradicts the requirement that secondmate homes “idempotently report their own terminal children”: the receipt fingerprint includes the mutable latest status line and PR. After one done outcome is reported, a later status-detail or PR update creates a new fingerprint and appends another parent report for the same stable outcome key. Base receipt identity on the terminal outcome episode rather than mutable presentation details.🔧 Fix: Retain pagination cursor after child reconciliation failure
4 errors still open:
bin/fm-inactive-reconcile.sh:384- This contradicts “preserve structured-summary compatibility”: existing fm-secondmate-home-summary.v1 producers omit terminal_children, so healthy older or remote secondmates are rejected and raise false reconciliation alerts. Treat the legacy shape as having no authoritative terminal-anomaly channel.bin/fm-inactive-reconcile.sh:391- A summary containing terminal_children is accepted without terminal_page metadata. An arbitrary partial anomaly list can therefore be trusted while omitted children remain concealed. Require valid paging metadata whenever terminal_children is present, while handling genuinely legacy summaries separately.bin/fm-inactive-reconcile.sh:390- Malformed summaries still pass the authoritative boundary: valid:true may carry a non-null invalidity/reason, and valid:false may claim no invalidity or terminal anomaly. Such input clears the durable summary obligation at line 603 despite the requirement that malformed summaries preserve or raise it. Validate reason/invalidity/state consistency before consumption.bin/fm-inactive-reconcile.sh:491- This contradicts the requirement that secondmate homes “idempotently report their own terminal children”: the receipt fingerprint includes mutable latest-status text and PR data. A later detail or PR update creates a new receipt and duplicate parent report for the same stable outcome key. Base identity on a durable terminal-outcome episode identifier emitted at the shared producer boundary.🔧 Fix: Harden summary compatibility and terminal outcome identity
2 errors still open:
bin/fm-inactive-reconcile.sh:534- Contradicts “create one marked correlated pending-reply request ... and preserve the obligation.” If the process crashes after fm_pending_reply_create but before storing correlation, and the parent report arrives before restart, this branch skips owner-key recovery; settlement sees no correlation, leaving the orphan awaiting_report to repost or escalate despite the report. Recover and link the owned expectation before checking/settling the report.bin/fm-inactive-reconcile.sh:508- The fingerprint is only child ID plus terminal state (likewise line 530 for summarized children), not a terminal-episode identity. Teardown removes task metadata but retains terminal-outcome receipts, so a later task reusing the same ID and reaching the same state is permanently suppressed by the old .reported/.presented record. Emit an immutable spawn/terminal-episode identifier at the shared state/summary boundary and include it in fingerprints while keeping mutable prose and PR metadata excluded.🔧 Fix: Preserve reply settlement and terminal episode identity
2 issues (1 error, 1 warning) still open:
bin/fm-inactive-reconcile.sh:645- This contradicts the required “Use the independent 60..1800 second bounded gate”:--startupbypasses the scan-marker age check, so repeated locked session starts can run reconciliation and every local summary probe without any cadence bound. Apply the same gate on startup while retaining startup as an authorized invocation path.bin/fm-spawn.sh:2477- On systems withsha256sumbut noshasum, episode generation falls back tocksum, reducing the timestamp/PID/random seed to roughly 32 bits and allowing unrelated spawns to share a durable outcome identity. Usesha256sumas the existing supported fallback before consideringcksum.🔧 Fix: Enforce bounded startup reconciliation cadence
1 error still open:
bin/fm-inactive-reconcile.sh:339- This contradicts the required main-home inspection of validated secondmate summaries for remote mirror input. The remote path invokesfm-on.sh <id> env ..., butfm-on.shonly accepts anfm-*.shbasename and therefore always rejectsenv; every regular remote scan becomes an unavailable-summary alert and can never reconcile terminal children. Invokefm-fleet-snapshot.shdirectly through the supported remote boundary and expose the pagination cursor through a supported argument or other validated protocol.🔧 Fix: Fix remote secondmate summary pagination
2 errors still open:
bin/fm-fleet-snapshot.sh:726- This contradicts the requirement that the main home inspect secondmate summaries and preserve each missing-report obligation.orphan_in_flight,unowned_current, andchild_current_unavailableserialize every ID into unboundedinvalidity.idsand reason text before the bounded terminal page. With enough competing anomalies, the summary exceedsFM_SNAPSHOT_SECONDMATE_MAX_BYTES, so every scan rejects it and a terminal child never receives its correlated request. Bound nonterminal invalidity detail at this producer boundary so the complete terminal page always fits the reader cap.bin/fm-inactive-reconcile.sh:657- Failures fromreconcile_direct_childare ignored. If outcome persistence, parent reporting, or presentation-state persistence fails, the scan still returns success and advances its durable cadence marker, so the watcher records no reconciliation failure and delays retry for the full interval. Propagate a failed child reconciliation as the scan result, as already done for secondmate-page failures.🔧 Fix: Bound invalidity details and propagate reconciliation failures
2 errors still open:
bin/fm-pending-reply-lib.sh:308- Crash recovery only finds four pending-reply phases. If an owned expectation reaches recovery_failed, recovery_unknown, or escalated before its outcome record is linked, a later keyed parent report cannot recover the correlation for synthetic settlement; the orphan remains unresolved and may continue escalating. Recover every unresolved owner-key phase so the matching report can settle the original expectation.bin/fm-inactive-reconcile.sh:563- This contradicts “preserve the obligation”: request creation/delivery failure is ignored and the summary cursor advances, while direct parent-report failures also return success. If the terminal child is then torn down or disappears from the summary, scans only revisit live metadata/pages and never replay the durable .pending record, so it cannot retry, settle a later report, or reach presentation. Replay unresolved outcome records at the bounded scan boundary, or retain the page/source until an active pending-reply/report owner is durably attached.🔧 Fix: Replay durable outcomes and recover unresolved owned replies
1 error still open:
bin/fm-fleet-snapshot.sh:821- This still contradicts the requirement to “preserve the obligation.” The boundedholds/queueditem counts retain unbounded nestedblocked_by_idsandunresolved_blocker_idsarrays (lines 824–825). A backlog row with enough blockers can exceedFM_SNAPSHOT_SECONDMATE_MAX_BYTES; the reader then rejects the entire summary, so its complete terminal page is never reconciled. Bound nested nonterminal arrays with omission counts, or enforce a byte-aware producer boundary that reserves space for the terminal page.🔧 Fix: Bound nested secondmate blocker details
1 error still open:
bin/fm-fleet-snapshot.sh:715- This contradicts the required bounded terminal-anomaly guarantee:episode_idis copied from metadata into the terminal page without producer-side validation or bounding. An oversized or invalid persisted value can exceed the summary byte cap (or fail reader validation), causing the entire page to be rejected and the child-specific missing-report obligation never to be created. Validate the episode identity at the producer boundary and emit a bounded stable representation that preserves uniqueness.🔧 Fix: Bound malformed terminal episode identities
3 errors still open:
bin/fm-inactive-reconcile.sh:522- The direct reporter accepts any path-safe episode ID, while the summary producer accepts only 16/24-character lowercase hex. With malformed metadata, the secondmate reports a key containing that value, but its summary emitsepisode_id:null; the main cannot match the existing report and creates a redundant missing-report request. This contradicts the required idempotent parent reporting and validated-summary reconciliation. Use one shared fixed-width episode validation/normalization boundary.bin/fm-fleet-snapshot.sh:734- Terminal paging is bounded only by item count and is not coupled toFM_SNAPSHOT_SECONDMATE_MAX_BYTES. For example, 20 valid 64-character task IDs are repeated acrossterminal_children, invalidity IDs, and reason text and can exceed a supported 4096-byte reader cap; the reader then rejects every page and no child obligation is created. Size pages against the byte budget or enforce compatible minimum/count bounds so every terminal page remains consumable.bin/fm-fleet-snapshot.sh:770-malformed_terminal_episodeemits every malformed child ID and joins the complete list intoreason, unlike the other bounded invalidities. Enough malformed terminal records therefore exceed the summary byte cap and conceal the terminal page, contradicting the required bounded child-specific obligation guarantee. Bound this list with deterministic omission counts.🔧 Fix: Bound terminal pages and normalize episode identities
2 errors still open:
bin/fm-inactive-reconcile.sh:341- This contradicts required remote-mirror reconciliation: terminal paging now depends on FM_SNAPSHOT_SECONDMATE_MAX_BYTES, but the remote fm-on invocation passes only the cursor, and fm-on deliberately uses an empty remote environment. If the parent uses a smaller supported cap than the remote default, the remote emits an oversized page that every scan rejects, so terminal children never receive their missing-report obligations. Add a validated snapshot argument carrying the reader byte budget.bin/fm-fleet-snapshot.sh:934- The bounded producer does not guarantee consumable output for every accepted positive byte cap: with zero terminal children it returns an oversized summary successfully, and with one child it fails rather than emitting that child. This violates the required durable child-specific obligation guarantee. Enforce a supported minimum budget or emit a minimal valid envelope that always fits one bounded terminal entry.🔧 Fix: Propagate and validate secondmate summary byte budgets
2 errors still open:
bin/fm-inactive-reconcile.sh:349- This contradicts “preserve structured-summary compatibility”: every local and remote probe now supplies--summary-max-bytes, but the existing v1 producer accepts only--secondmate-home-summary [--terminal-after ...]. Older remote mirrors therefore reject the command before their compatible v1 JSON can be validated, producing false unavailable-summary alerts. Add a bounded compatibility path or capability negotiation for legacy producers.bin/fm-fleet-snapshot.sh:965- The declared 4096-byte minimum still does not guarantee consumable output. After removing nonterminal surfaces, an oversized zero-child summary is emitted unchanged, while an oversized one-child page fails at line 969. Long supported home paths can trigger either path, causing a healthy secondmate alert or preventing its terminal child obligation. Emit a minimal envelope guaranteed to fit or choose a minimum that accounts for every retained bounded field.🔧 Fix: Preserve legacy summaries and guarantee bounded envelopes
2 errors still open:
bin/fm-inactive-reconcile.sh:353- The legacy retry runs after every bounded-protocol failure, including timeout, transport failure, oversized output, or an internal producer error—not only rejection of unsupported arguments. If the fallback then returns a valid legacy shape, the scan accepts it as having no terminal channel and can clear the cursor/summary obligation, contradicting the requirement to independently inspect secondmate outcomes and preserve missing-report obligations. Retry legacy only for an explicit unsupported-argument result; surface all other failures.bin/fm-inactive-reconcile.sh:671- Failures to persist invalid-home, unavailable, or malformed-summary obligations are ignored before continuing. The scan consequently returns success with its cadence marker already advanced, leaving neither a durable obligation nor watcher failure signal until the next interval. Propagate summary_obligation failure from all three branches, as done for child and cursor persistence failures.🔧 Fix: Restrict legacy fallback to explicit unsupported arguments
2 issues (1 error, 1 warning) still open:
bin/fm-fleet-snapshot.sh:756- This contradicts the required “long-inactive, non-captain-held direct crewmates” boundary. The terminal summary includes every in-flight child whose current state is done/failed without checking that child’s activity age or captain-held status. A long-idle secondmate with a freshly completed child—or a captain-held child whose crew state is terminal—therefore causes the main scan to create a premature/forbidden missing-report request. Apply the same eligibility invariant at the shared terminal-summary boundary or carry validated eligibility evidence for the main reader.bin/fm-fleet-snapshot.sh:1392- The general remote summary aggregation retries the legacy invocation after every nonzero result, including timeout, transport failure, and internal producer errors. This can mask a modern-protocol failure and doubles the bounded remote call. As in the reconciliation path, retry only after an explicit unsupported-new-argument result.🔧 Fix: Enforce inactive child eligibility in terminal summaries
1 error still open:
bin/fm-fleet-snapshot.sh:1435- This contradicts “preserve structured-summary compatibility.” The legacy producer’s unsupported-argument response includes the full usage/help text, but this branch compares it to only two usage lines, so the fallback is unreachable and compatible remote v1 summaries are reported as failed. Detect the explicit legacy usage signature without requiring exact full-output equality, as the reconciliation path does.🔧 Fix: Restore remote legacy summary fallback
1 error still open:
bin/fm-fleet-snapshot.sh:998- The producer measures only the compact JSON bytes against the configured cap, then line 1018 appends a newline. When JSON length equals the accepted budget,run_bounded_summarycounts the newline, rejects the output as oversized, and the main home cannot inspect or preserve child-specific obligations. Reserve one byte for the newline or emit without it.🔧 Fix: Account for summary framing byte budget
✅ Re-checked - no issues remain.
✅ **Test** - passed
✅ No issues found.
Inspected commit diff and changed-file scope withgit diffandgit status.Ranbin/fm-test-run.sh ... tests/fm-inactive-reconcile.test.sh tests/fm-bearings-snapshot.test.sh; identified stale remote-summary command expectations.Updated remote-summary tests to verify propagation of the independent--inactive-secs 60threshold.Ranbin/fm-test-run.sh ... tests/fm-inactive-reconcile.test.shsuccessfully.Added an executable Bearings regression using a temporary Git repository to prove descendant directories trigger zero ancestor-repository forge calls.Ranbin/fm-test-run.sh ... tests/fm-bearings-snapshot.test.shsuccessfully after correcting the focused output assertion.Checked the final working-tree diff and removed no artifacts because the tests cleaned their temporary fixtures.✅ **Document** - passed
✅ No issues found.
🔧 **Lint** - 1 issue found → auto-fixed ✅
🔧 Fix: Fix reconciliation ShellCheck findings
✅ Re-checked - no issues remain.
✅ **Push** - passed
✅ No issues found.