Skip to content

feat(bin): record durable task outcomes and extend fleet telemetry - #27

Merged
HelloWorldSungin merged 9 commits into
mainfrom
fm/fleet-outcome-manifest
Aug 4, 2026
Merged

HelloWorldSungin merged 9 commits into
mainfrom
fm/fleet-outcome-manifest

Conversation

@HelloWorldSungin

@HelloWorldSungin HelloWorldSungin commented Aug 4, 2026 •

Copy link
Copy Markdown
Owner

Closes #18

Why

A finished task used to leave nothing structured behind. Teardown removes state/<id>.meta, and the backlog's Done section is pruned to a recent window, so once a task was cleaned up there was no canonical record of what it was, what it shipped, or which session ran it. Nothing downstream could attribute its usage, ingest its outcome, or place it in history.

This is the data-contract foundation shared by both the memory epic (#3) and the dashboard epic (#4): archive ingestion (#7), usage attribution (#13), kanban cards (#11), inbox health (#12), and durable history (#16) all consume it.

What landed

Three artifacts, with their wire shapes owned by bin/fm-outcome-lib.sh:

Artifact Schema Producer Lifetime
data/<id>/outcome.json fm-outcome-manifest.v1 bin/fm-outcome-manifest.sh durable, survives teardown
data/<id>/work-items.json fm-work-items.v1 bin/fm-work-item.sh durable, survives teardown
state/<id>.pr-status fm-pr-status.v1 bin/fm-pr-status.sh volatile, removed by teardown

The manifest. bin/fm-teardown.sh publishes it atomically before removing the volatile records it is composed from, and refuses the cleanup when publication fails rather than erasing a task it could not archive. Publication sits after the last refusal gate and the confirmed endpoint close, but before a retired secondmate's home is removed, because that home can contain the very records the manifest is composed from.

Work-item references. Forge- and host-agnostic: canonical URL plus parsed forge, host, project path, owner, repo, number, and kind. Several per task or none. Each marked intake or pr-linked. Enrichment is nullable by contract and consumers must render a reference that was never enriched. An unrecognized host stores forge: "unknown" rather than being guessed at, and an explicit override handles self-hosted instances. This PR owns storage and transport only; population and per-forge resolution belong to #21.

Normalized PR state. bin/fm-pr-status.sh is the one network caller and the one place each forge's vocabulary maps onto state / review / checks / mergeable enums. The observation is cached so the read-only snapshot stays offline; fm-pr-check.sh seeds it and fm-pr-merge.sh refreshes it, both best effort, and a failed refresh keeps the previous good reading instead of overwriting it with unknown.

Snapshot projection. fm-fleet-snapshot.v1 grows additively, so existing v1 consumers keep working unchanged and no renderer migration is required: task model and effort, last task-event timestamp and computed age, parsed PR identity with normalized state and age, work_items, a computed card, top-level card_precedence, supervision (watcher beacon age against the shared grace window plus away-mode state), and manifest-backed history.

Card precedence. Signals overlap constantly, so exactly one column wins per task against a published ladder, with card.rank and the deciding card.signals carried alongside so a surprising column is inspectable:

needs_decision > blocked > parked > failed > review > done > waiting > active > secondmate > idle

An open decision outranks everything because it is unanswered work even when a PR is open; a blocker outranks a failure because the worker is still there and asking; a failure outranks an open PR because the PR is not the live problem; and an open PR outranks done because a task that reported "PR checks green" has not landed until that PR is merged.

Secret safety is enforced, not described. A fixed recursive key allowlist gates manifest publication, so a field can only be emitted by being declared in one place. Bounded type, enum, and length conformance runs at the shared read boundaries, so a hand-edited or corrupt store cannot carry arbitrary text through an allowlisted value. Every durable free-text value is control-stripped, collapsed to one line, and capped. Deliberately not a general secret scanner: values are conformed to the contract's own types, enums, and lengths and nothing more.

docs/fleet-data-contracts.md (maintainer-architecture) owns the field-ownership map. Script headers keep exact mechanics. AGENTS.md gains only layout lines and one refusal clause.

Decisions worth knowing

  • Additive v1 over a v2 schema. Every new field is purely additional, so no renderer migration is required.
  • A null title for a secondmate is intended, not a defect. Secondmates are never backlog items by contract, so no synthetic title is manufactured; the contract documents the null. "Required" in the manifest validator therefore means the key is present with the right type or null, which is also what keeps an absent GBrain provider, a task with no PR, and unenriched work items valid.
  • No created= line was added to state/<id>.meta. A live-harness Herdr end-to-end test asserts spawn metadata is byte-identical except for container IDs, and a per-spawn timestamp would break that claim. Timestamps instead carry explicit provenance in timestamp_sources, and a future recorded stamp can supersede a source without a schema change.
  • jq is now a universal bootstrap requirement. The snapshot, the dispatch-profile reader, and now the manifest all need it, and without it a home cannot archive a finished task. Making that explicit keeps the new teardown refusal from surfacing as a mystery.
  • The legacy issue=<number> metadata field is deliberately not migrated into the work-item store here. Resolving a bare number to a URL needs the project's repository, which is foundation: Project-scoped work-item linkage across managed forges #21's resolution territory; doing it here would fork a second schema.

Two defects the work surfaced in itself

  • Publishing the manifest after remove_firstmate_home broke remote secondmate retirement, because the remote parent-route keeps its state and data inside the home being removed. The remote lifecycle e2e caught it; a new assertion in the local secondmate lifecycle suite now pins the ordering.
  • The backend old-versus-new conformance fixture rebuilds bin/ from a fixed sibling list and lacked the new writer, so the rebuilt teardown refused a cleanup that should have succeeded.

Findings the pipeline fixed on top

Recorded for review, since they are corrections the original change missed:

  • PR-status cache was not bound to the task's current PR identity, so a stale merged observation could be read against a replacement PR.
  • GitLab review state came from the deprecated approvals_before_merge, then from approved alone; it now keys on approvals_left to separate none, review_required, and approved, degrading contradictions to unknown.
  • FM_PR_STATUS_TIMEOUT was not a real bound when GNU timeout was unavailable.
  • A corrupt or old-schema work-item store was silently overwritten by add/remove/clear, losing durable references; mutation paths now refuse while the read-only projection keeps its fallback.
  • The manifest allowlist rejected extra keys but never required the documented ones, so a stub record passed show and history.
  • The shared JSON reader accepted concatenated top-level documents and silently used the first.
  • The validator spawned roughly ten jq processes per work-item reference; consolidated to one pass per document.
  • Two documentation-accuracy defects this change introduced: the secondmate card reason claimed queue evidence the predicate never checks, and the generated scout brief still called the report the only surviving artifact.

Verification

bin/fm-lint.sh, bin/fm-doc-audience-check.sh, and the test coverage guard all pass. Both portable parallel lanes and the portable serial lane are green. New coverage lives in tests/fm-outcome-manifest.test.sh, with additions to the fleet-snapshot, teardown, and secondmate lifecycle suites.

Rebase after the pipeline run

The no-mistakes pipeline validated this work at d78036e3. Sibling PRs then merged and moved main, so the branch was rebased onto 3df0ac3 and force-pushed with lease as e1d92fa.

One conflict, in bin/fm-teardown.sh, resolved by composing both sides rather than replacing either: main's fix: preserve crew run attribution during validation (#25) adds state/<id>.run-step to the task cleanup list, and this branch adds state/<id>.pr-status and state/<id>.gbrain to the same list. The final list carries all three. The acceptance-critical ordering is unchanged and re-verified: publish_outcome_manifest still runs before the secondmate home removal, the per-task temp root removal, the PR-poll cleanup, the busy-state retirement, and the state-file rm.

Re-verified after the rebase: bin/fm-lint.sh, bin/fm-doc-audience-check.sh, and the fm-outcome-manifest, fm-teardown, fm-gotmp, fm-crew-state, fm-fleet-snapshot-view, fm-secondmate-lifecycle-e2e, fm-backend, and fm-brief suites.

The pipeline section below is the run's own record and its commit references predate that rebase.

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

⏭️ **Rebase** - skipped
  • ⚠️ .agents/skills/afk/SKILL.md - branch carries 58 commit(s) that exist on your local main branch but were never pushed to origin/main; rebasing would bundle this unrelated work (69 file(s)) into the PR:
  • 149c812 Merge pull request Sync the fork with upstream and land the ten reviewed changes #17 from HelloWorldSungin/fm/fm-fork-upstream-reconcile
  • 07a281f Conform the cursor/agy adapter test to upstream's tightened contracts
  • cc840d8 Complete two test fixtures for the merged tree
  • e4a3787 Restore teardown functions dropped by my merge resolution
  • 20b879f Keep one window_harness definition after the upstream merge
  • 26a9bff Merge fm/fm-endpoint-binding-migration (upstream PR 1492)
  • 5cd2fc8 Merge fm/fm-pi-auth-surface-unresolved (upstream PR 1491)
  • e45fb62 Merge fm/fm-test-run-comm-sort-exit (upstream PR 1490)
  • 5777773 Merge fm/fm-watcher-term-hup-latency
  • b8c5c34 Merge fm/firstmate-watcher-lock-flake
  • 3d5d952 Merge fm/fm-brief-status-protocol-gaps
  • de00adc Merge fm/fm-pi-afk-dual-supervision
  • b7a413a Merge fm/fm-session-start-e2e-failure (upstream PR 1476)
  • 7a18213 Merge fm/fm-bearings-snapshot-arg-too-long (upstream PR 1442)
  • f1a8979 Merge fm/fm-issue-lifecycle-wiring (upstream PR 1271)
  • 05058ac Merge upstream/main into the fork, preserving the cursor/agy adapters
  • a473c4e no-mistakes(document): Clarify coverage-guard collation documentation
  • e9eefb3 fix(tests): run coverage-guard set operations under the C collation
  • 890bd37 no-mistakes(document): Document endpoint-binding migration behavior
  • e174818 no-mistakes(review): Refuse concurrent endpoint metadata rewrites
  • 0246f94 revert: drop the test-runner locale fix from this branch
  • c1b74c6 fix(bin): migrate legacy non-tmux endpoint records so they stay cleanable
  • 9018941 no-mistakes: apply CI fixes
  • ca99120 fix(snapshot): stop passing fleet-sized JSON to jq through argv
  • fd39d53 no-mistakes: apply CI fixes
  • 1ea1c2d no-mistakes(document): Clarify brief status-protocol header scope
  • c93ab0b fix(brief): close three status-reporting gaps in the crewmate scaffold
  • 2aca111 no-mistakes(document): Clarify catalog-backed authentication evidence
  • 343bb9f fix(dispatch): resolve pi surfaces from the harness catalog
  • c50b2ce no-mistakes(document): docs: correct interruptible poll-path description
  • c46e3b1 fix(tests): wait for the TERM-resistant peer before restarting the watcher
  • dc107ba fix(watch): honor TERM and HUP without waiting out the poll interval
  • 3db0341 fix(tests): wait for the TERM-resistant peer before restarting the watcher
  • 6c60252 no-mistakes(document): Document Pi away-mode supervision handoff
  • d7c1660 fix(pi): hand supervision to the away daemon while away mode is active
  • 38951b1 test(session-start): make the MISSING-tool fixture independent of the host PATH
  • c6ba037 no-mistakes(lint): Suppress literal backtick fixture ShellCheck warning
  • 433b66e no-mistakes(document): Document GitHub issue delivery lifecycle
  • 19f6c91 no-mistakes(review): Add exact no-issue brief golden coverage
  • 8a97167 Stabilize locale and Calm regression checks
  • 7b32a51 Wire GitHub issues into task delivery
  • d50dcca Merge pull request feat(harness): add crew-only cursor and agy adapters #1 from HelloWorldSungin/fm/cursor-agy-build
  • 640fd60 no-mistakes(document): Align cursor and agy documentation ownership
  • 41b71b6 no-mistakes(review): Gate credentialed smoke outside portable tests
  • f446c89 no-mistakes(review): Re-arm native completion and clean smoke trust
  • 46680c5 test: conform the cursor/agy tests to main's tightened contracts
  • 912dad5 Merge origin/main into fm/cursor-agy-build
  • 2d0c4c2 no-mistakes(document): Document restricted cursor and agy harness adapters
  • 6159bad no-mistakes(test): Guard launch rendering against unresolved placeholders
  • 52f816e no-mistakes(review): Fix native identity and trust teardown ordering
  • 2df62e3 Merge origin/main into fm/cursor-agy-build (overlay, per captain Option A)
  • ae5aab2 fix(harness): harden B1 with an exec-time PATH guard for raw cursor/agy launches
  • 7b60904 test: green the 3 environment-sensitive full-suite failures
  • 65b2dd4 fix(harness): close B1 variable-indirection bypass + fix 2 regressed tests
  • 4571ab1 fix(harness): close re-review B1/B3 + add S2 bootstrap backend warning
  • 553a862 test(harness): mark new cursor/agy test scripts executable (review N1)
  • 7e2cfa0 fix(harness): close the 4 cursor/agy review blockers (B1-B4) + failure-path tests
  • 6237eb9 feat(harness): add cursor + agy as crew-only, herdr-only adapters

Push main to origin, or rebase your branch onto origin/main, before gating.

🔧 **Review** - 6 issues found → auto-fixed (3) ✅
  • 🚨 bin/fm-outcome-lib.sh:295 - The required guarantee that manifests and snapshots contain no credentials or secret-bearing payloads is not enforced by the current validators. fm_outcome_work_items_read accepts arbitrary reference contents, fm_outcome_pr_status_read accepts any status object, and the manifest allowlist validates keys but not values, so a sentinel placed in an allowed field such as enrichment.title or status.source is emitted unchanged. Either add strict type, enum, length, and value validation at these shared read/write boundaries, or explicitly narrow the secret-safety guarantee; I recommend validation because retaining the current claim leaves a reachable disclosure path.
  • 🚨 bin/fm-outcome-lib.sh:328 - The cached PR status is not checked against the task's current PR identity. If PR A is cached as merged, fm-pr-check.sh replaces metadata with PR B, and B's best-effort refresh fails, consumers combine B's URL with A's merged status; the card can then classify B as done and teardown archives the mismatched observation. Bind cache reads to the expected canonical URL and return unknown on an identity mismatch while retaining same-PR observations after refresh failures.
  • 🚨 bin/fm-outcome-manifest.sh:91 - The required manifest title is not reliably retained. backlog_title returns empty for tasks without a backlog row, which includes retired secondmates, and its blanket parenthesis removal turns a legitimate title such as Refresh sidebar (mobile) into Refresh sidebar. The smallest compliant fix is to reuse the canonical backlog-title parser and source secondmate titles from their structured registry or intake record; otherwise the contract must explicitly make title nullable and lossy. I recommend preserving the actual title for every task.
  • 🚨 bin/fm-pr-status.sh:128 - GitLab review state is derived from approvals_before_merge, which is the deprecated configured approval count rather than the current approval decision. Consequently an approved MR with a nonzero threshold still reports review_required, while approval-rule configurations can report none incorrectly. Read GitLab's approvals or approval-state endpoint and map its current approved result, degrading to unknown when unavailable. See the official GitLab approvals API.
  • ⚠️ bin/fm-pr-status.sh:71 - FM_PR_STATUS_TIMEOUT is not a bound when GNU timeout is unavailable: the fallback executes gh-axi, gh, or glab without any timeout. On supported macOS environments this can leave fm-pr-check.sh or the post-merge refresh blocked indefinitely despite the documented 20-second contract. Use the repository's established gtimeout/Perl fallback or fail bounded when no timer is available.
  • 🚨 bin/fm-outcome-lib.sh:295 - Malformed and absent work-item stores are collapsed to the same empty document. Because add, remove, and clear consume this reader, a present corrupt or old-schema durable store is silently overwritten, losing all prior references. Keep the empty fallback for an absent read-only projection, but make mutation paths fail when a present store does not validate.

🔧 Fix: Harden outcome contracts and preserve cache identity
2 issues (1 error, 1 warning) still open:

  • 🚨 bin/fm-pr-status.sh:139 - The GitLab fix maps every approved:false response to review_required, but GitLab Community Edition also returns false when an MR has zero required approvals and nobody has voluntarily approved it; that ordinary no-review case must be none. Enterprise Edition can conversely return true with zero rules and no approving users. Use approvals_required plus approved_by or approvals_left to distinguish none, review_required, and approved, degrading ambiguous responses to unknown. See the official GitLab approvals API.
  • ⚠️ bin/fm-outcome-lib.sh:375 - The new validator starts roughly ten separate jq processes per work-item reference, and history invokes it for every retained manifest before applying FM_SNAPSHOT_HISTORY. A durable history of 1,000 tasks with two references can therefore launch tens of thousands of processes on every snapshot. Consolidate structural validation and field extraction into one jq invocation per document or reference, retaining only canonical URL reconstruction in shell.

🔧 Fix: Normalize GitLab approvals and bound outcome validation
3 errors still open:

  • 🚨 bin/fm-outcome-lib.sh:536 - GitLab can return approved:true while approvals_left remains positive, including on Community Edition where any approval makes approved true. The current branch checks approved first and incorrectly reports approved even though required reviews remain. Prioritize a present approvals_left: positive means review_required, zero plus a consistent approved result means approved, and contradictions mean unknown. See the official GitLab approvals API.
  • 🚨 bin/fm-outcome-lib.sh:830 - Manifest validation checks only work_items and pr; the key allowlist rejects extra paths but does not require missing ones. A same-schema record containing only schema, task_id, valid work_items, and valid pr therefore passes show and history without required fields such as title, timestamps, outcome, report, attribution, or GBrain status. Validate the complete manifest shape, required keys, types, enums, nullability, lengths, and task identity at this shared boundary so malformed or old records are disclosed instead of emitted.
  • 🚨 bin/fm-outcome-lib.sh:182 - The generic reader applies its predicate independently to every top-level JSON value, so a file containing two concatenated valid objects is accepted. For work-item stores, mutation then processes both documents but publication selects the first slurped reference array, silently discarding references from the second; history can likewise emit two records while incrementing total once. Slurp input and require exactly one object at the shared read boundary, with the same invariant enforced during publication.

🔧 Fix: Enforce outcome contracts and approval precedence
✅ Re-checked - no issues remain.

✅ **Test** - passed

✅ No issues found.

  • bash bin/fm-test-run.sh tests/fm-outcome-manifest.test.sh tests/fm-fleet-snapshot-view.test.sh tests/fm-teardown.test.sh tests/fm-secondmate-lifecycle-e2e.test.sh
  • Added unenriched GitHub intake and GitLab PR-linked references through bin/fm-work-item.sh, then published the canonical artifact through bin/fm-outcome-manifest.sh write.
  • Removed the demo task’s volatile metadata and pruned its Done backlog entry, then ran bin/fm-fleet-snapshot.sh --json and confirmed the task remained in manifest-backed history with attribution and both work-item references.
  • Used jq -e to validate the generated manifest and snapshot contracts and rg to prove a brief-embedded secret sentinel was absent from both outputs.
  • Inspected git status --short after testing to confirm no transient working-tree artifacts remained.
🔧 **Document** - 2 issues found → auto-fixed ✅
  • ⚠️ bin/fm-fleet-snapshot.sh:690 - The secondmate card reason claims the home has an empty queue, but the predicate only checks that no higher-priority task signal exists. Align the executable reason with the predicate or add queue evidence.
  • ⚠️ bin/fm-brief.sh:349 - The generated scout brief says the report is the only surviving artifact, but teardown now also preserves the outcome manifest and work-item store. Rephrase this as the only task-authored deliverable.

🔧 Fix: Align fleet documentation wording
✅ Re-checked - no issues remain.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@cursor

cursor Bot commented Aug 4, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@HelloWorldSungin
HelloWorldSungin force-pushed the fm/fleet-outcome-manifest branch from d78036e to e1d92fa Compare August 4, 2026 06:47
Sungin Kim added 9 commits August 4, 2026 07:21
A finished task used to leave nothing structured behind. Teardown removes
state/<id>.meta, and the backlog's Done section is pruned to a recent window,
so once a task was cleaned up there was no canonical record of what it was,
what it shipped, or which session ran it. Nothing downstream could attribute
its usage, ingest its outcome, or place it in history.

Introduce three data contracts and project all three through the read-only
fleet snapshot:

- data/<id>/outcome.json (fm-outcome-manifest.v1) is the canonical completion
  manifest. Teardown publishes it atomically before removing the volatile
  records it is composed from, and refuses the cleanup when publication fails
  rather than erasing a task it could not archive.
- data/<id>/work-items.json (fm-work-items.v1) carries forge- and host-agnostic
  work-item references, several per task or none, each marked as declared at
  intake or derived from a PR, with nullable enrichment consumers must render
  without. This owns storage and transport only; population and per-forge
  resolution stay with the project-issue-linkage work.
- state/<id>.pr-status (fm-pr-status.v1) holds one normalized review, check,
  and mergeability observation per PR, refreshed only by fm-pr-status.sh so
  read-only consumers never call a forge.

fm-fleet-snapshot.v1 grows additively, so existing v1 consumers keep working
unchanged: task model and effort, the last task-event timestamp and its age,
the parsed PR identity with its normalized state, work-item references, a
computed card column resolved against a published and tested precedence
ladder, watcher heartbeat age with away-mode state, and manifest-backed
durable history that outlives teardown.

Secret safety is enforced rather than described. A fixed recursive key
allowlist gates manifest publication, so a field can only be emitted by being
declared in one place, and every free-text value is stripped of control
characters, collapsed to one line, and length-capped.

jq becomes a universal bootstrap requirement: the snapshot, the dispatch
profile reader, and now the manifest all depend on it, and without it a home
cannot archive a finished task.
A retired secondmate's state and data directories can live inside the home
teardown removes, which is exactly the shape the remote parent-route shadow
uses. Publishing the manifest after that removal left the writer with no task
metadata to compose from, so the remote lifecycle end-to-end run failed on a
retirement that should have succeeded.

Move the publication to the last point where every source record still exists:
after the final refusal gate and the confirmed endpoint close, before the home
removal. Pin it with an assertion that a retired secondmate leaves a manifest
recording its retirement in the parent's durable history.

Also give the gate-refusal teardown fixture its own data directory so the suite
stops writing a manifest into the repository's own gitignored data/.
The old-versus-new teardown conformance case rebuilds a bin/ tree from a fixed
sibling list, and teardown now shells out to fm-outcome-manifest.sh. Without
the writer and its library in that tree the rebuilt teardown could not publish
a manifest and refused a cleanup that should have succeeded.
CI caught two ways the hardening round's value validation was stricter than
the rest of firstmate, and because teardown refuses when a manifest cannot be
published, each one made a real task impossible to clean up.

The task-id rule invented a 64-character cap and a bounded character pattern.
bin/fm-pr-lib.sh's fm_task_id_path_safe has no length cap, so a legacy id the
whole rest of the system accepts could not be archived and its teardown
refused. The manifest now mirrors that predicate exactly: the archive records
the ids that exist rather than policing them.

The mode field was validated against a closed delivery-mode vocabulary, but
mode is provenance copied verbatim from task metadata, and task kinds appear
there in practice alongside delivery modes. A scout task therefore could not be
torn down at all. mode now gets the same bounded type and length treatment as
project, harness, and model; enums stay only on the values this contract
generates itself.

Also bump the snapshot test count CI pins for the stock-macOS-Bash job from 15
to 19, which this branch's four new fleet-snapshot cases changed. The Bash 3.2
parse sweep in that job passed unchanged.
@HelloWorldSungin
HelloWorldSungin force-pushed the fm/fleet-outcome-manifest branch from 052c1fe to 207f862 Compare August 4, 2026 07:24
@HelloWorldSungin
HelloWorldSungin merged commit 8967ff1 into main Aug 4, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

foundation: Durable outcome manifest + fleet snapshot telemetry contract

1 participant