Skip to content

feat(bin): append the spend-ledger line on every close path and add pipeline columns - #79

Merged
andrewesweet merged 7 commits into
mainfrom
fm/retro9-p2-ledger-pipeline
Sep 28, 2026
Merged

andrewesweet merged 7 commits into
mainfrom
fm/retro9-p2-ledger-pipeline

Conversation

@andrewesweet

@andrewesweet andrewesweet commented Sep 28, 2026 •

Copy link
Copy Markdown
Owner

Intent

The task spend ledger records one line per closed ship or scout task from the worker session only, so tasks closed through some paths leave no line and no line carries the no-mistakes pipeline's cost, which dominates the total. This change makes every closure path append its worker line and adds pipeline columns to the ledger line, sourced from the no-mistakes run records for the task's runs: tokens, agent duration and cost, where invocations that were killed or never started are recorded as unmeasured with their duration rather than as zero cost.

What Changed

  • Added bin/fm-spend-ledger-append.sh as the single spend-ledger producer that every close path now funnels through: fm-teardown.sh appends before staging a landed backlog close, stashes a state/<id>.spend-context when the captain's call is retained so a later answer-close can still append, and appends once past every possible refusal on homes where the backlog gate does not apply; fm-captain-hold.sh appends after a done close that never saw a teardown. Lines stay deduplicated, so a re-run close prints the recorded line instead of writing a second one.
  • Extended bin/fm-spend-query.py to schema version 2, adding pipeline columns read read-only from the no-mistakes inventory for the task's runs on its ship branch: run and invocation counts, tokens by class, summed agent duration, and a cost priced at the same assumed rates. Killed or never-started invocations (cancelled/error exit status, or no reported input tokens) are counted with their duration rather than priced as zero, unknown-rate models keep their tokens under a partial cost lane, and an unresolvable repo or absent branch records the pipeline as unmeasured with a reason. Lookup is scoped to the task's project clone and its own pooled worktree, matching how the inventory keys a repo.
  • Documented the shared producer and the new columns in docs/configuration.md, docs/scripts.md, and AGENTS.md, and added tests covering the producer (tests/fm-spend-ledger-append.test.sh), the pipeline columns (tests/fm-spend-query.test.sh), and the teardown, captain-hold, and backlog-atomicity close paths.

Risk Assessment

✅ Low: Every previously selected defect is closed in the current code and verified read-only against the live no-mistakes inventory; the one remaining issue is a single false clause in a rarely reached fallback reason string, with no wrong figure, label, or set produced on any reachable intended path.

Testing

I stood the producer up the way a closing task does — an isolated FM_HOME plus a no-mistakes SQLite inventory built to the live schema — and drove each closure path through the real scripts. A ship close emitted one schema-2 line whose pipeline columns I checked by hand against the rate table: 1.5375 USD over the two completed claude invocations, with the cancelled row's 1258 tokens excluded and its 900s of duration landing in pipeline_unmeasured_ms alongside the errored and never-started rows (3 invocations, 1,025,000 ms), which is exactly the unmeasured-with-duration treatment the intent requires. Rerunning the same close printed the recorded line and appended nothing, and five concurrent closes still produced a single line with the file valid JSON throughout. The retain path stashed a spend context, survived removal of the task record and sidecars, and the later answer-close appended the scout's line with a relative outcome_ref. Adversarially, a pipeline with nothing priceable reported lane "unmeasured" rather than "partial" with a note saying no invocation could be priced, an unnamed model surfaced as "unknown" rather than an empty hole, an inventory without exit_status fell back to the reported-token test instead of erroring, and a non-worker kind recorded nothing. The three suites that drive fm-teardown.sh and fm-captain-hold.sh as whole programs all passed, covering the two guards I could not stage by hand: the no-backlog teardown refused at treehouse return leaves no ledger file, and an Orca cleanup recovery records no phantom close. No screenshots apply — every surface this change touches is a CLI writing a JSONL ledger, so the transcripts and the emitted ledger lines are the end-user artefact. The transient fixture home and temp logs were removed and the worktree is clean.

  • Live validation: ✅ go - 12 of 12 scenarios driven live against the product
Scenario Result Live Evidence
A closed ship records one ledger line carrying the no-mistakes pipeline's tokens, duration and cost ✅ pass live bin/fm-spend-ledger-append.sh demo-1 against an isolated FM_HOME with a seeded inventory; line carries pipeline_runs 1, pipeline_input_tokens 150000, pipeline_agent_ms 90000, pipeline_usd 1.5375, la…
Killed and never-started invocations are recorded as unmeasured duration, never priced as zero cost ✅ pass live The same close: a cancelled row carrying 1258 tokens, an errored row carrying 4000, and a NULL-token row all land in pipeline_unmeasured_invocations 3 / pipeline_unmeasured_ms 1025000, and their token…
A task closed by the captain's answer after teardown removed its record still records its line ✅ pass live --stash retained-1, record and sidecars deleted, then bin/fm-spend-ledger-append.sh retained-1 emitted the scout line with outcome_ref data/retained-1/report.md; also `bash tests/fm-captain-hold-l…
A teardown on a home with no backlog transition records its line ✅ pass live bash tests/fm-teardown.test.sh case a closed ship appends one schema-versioned spend ledger line with its outcome, driving fm-teardown.sh end to end (exit 0)
Adversarial: a teardown refused at treehouse return on a no-backlog home records no close ✅ pass live bash tests/fm-teardown.test.sh case a teardown refused at treehouse return on a no-backlog home records no ledger line — teardown exits 1, no spend-ledger.jsonl exists, task record survives
Adversarial: an Orca cleanup recovery records no phantom close ✅ pass live bash tests/fm-backlog-atomicity.test.sh case Orca cleanup recovery is excluded from backlog lifecycle transitions, which now fails if the ledger names the task (exit 0)
Adversarial: reruns and concurrent closes never double-count a task ✅ pass live Second bin/fm-spend-ledger-append.sh demo-1 reprinted the recorded ts and left the count at 1; five concurrent closes of race-1 produced 1 line with the whole file valid JSON (live-close-and-dedupe.…
Adversarial: a pipeline where nothing could be priced is labelled unmeasured, not partial ✅ pass live bin/fm-spend-ledger-append.sh unpriced-1 returned lane unmeasured, usd null, note "no known rate for model(s) gpt-6-astra, unknown; no invocation could be priced"; mixed-1 kept lane partial with 0.0…
Adversarial: an invocation with no recorded model is named rather than leaving a hole in the note ✅ pass live Both unpriced-1 and mixed-1 notes name unknown for the empty-model row instead of rendering an empty entry (live-pipeline-lanes.txt)
Adversarial: an older inventory without exit_status still answers, falling back to the reported-token test ✅ pass live bin/fm-spend-ledger-append.sh oldschema-1 against an agent_invocations table with no exit_status column: 2 invocations, 1 unmeasured (7000 ms), lane api-equiv, usd 0.625 (live-schema-fallback-and-ga…
Adversarial: a task kind that never ran a worker records nothing ✅ pass live bin/fm-spend-ledger-append.sh secondmate-1 printed nothing, exited 0, and added no ledger line (live-schema-fallback-and-gate.txt)
A close whose spend query fails still records an explicit unmeasured line rather than none ✅ pass live bash tests/fm-teardown.test.sh case a broken spend query never fails the cleanup and still records unmeasured, plus bash tests/fm-spend-ledger-append.test.sh case `a failed spend query records a…
Evidence: Ship close: one schema-2 ledger line with pipeline columns, and a rerun that appends nothing

Source: Ship close: one schema-2 ledger line with pipeline columns, and a rerun that appends nothing

\### Scenario A: ship close records one ledger line with pipeline columns
$ bin/fm-spend-ledger-append.sh demo-1
{
  "schema": 2,
  "task": "demo-1",
  "kind": "ship",
  "harness": "codex",
  "model": "default",
  "effort": "default",
  "window": null,
  "calls": null,
  "mean_context_tokens": null,
  "cache_read_share": null,
  "usd_lane": "unmeasured",
  "usd": null,
  "models": [],
  "unmeasured_reason": "no verified per-call usage parser for this runtime",
  "pipeline_runs": 1,
  "pipeline_invocations": 5,
  "pipeline_input_tokens": 150000,
  "pipeline_output_tokens": 7000,
  "pipeline_cache_read_tokens": 1300000,
  "pipeline_cache_creation_tokens": 30000,
  "pipeline_agent_ms": 90000,
  "pipeline_unmeasured_invocations": 3,
  "pipeline_unmeasured_ms": 1025000,
  "pipeline_usd": 1.5375,
  "pipeline_cost_lane": "api-equiv",
  "ts": "2026-09-28T17:55:23Z",
  "outcome": "pr",
  "outcome_ref": "https://github.com/example/demo/pull/42"
}

\### Scenario B: rerun of the same close appends no second line
$ bin/fm-spend-ledger-append.sh demo-1   # again
{"task":"demo-1","ts":"2026-09-28T17:55:23Z"}
ledger line count: 1
Evidence: Captain-answer close: stashed spend context survives record removal and records the line

Source: Captain-answer close: stashed spend context survives record removal and records the line

\### Scenario C: teardown retains the captain's call, later answer-close still records the line
$ bin/fm-spend-ledger-append.sh --stash retained-1   # teardown, record still in hand
stashed context:
schema=fm-spend-context.v1
task=retained-1
kind=scout
harness=codex
model=
effort=
worktree=/tmp/fm-spend-live.7fO1gn/home/wt
project=/tmp/fm-spend-live.7fO1gn/home/project
branch=fm/demo-ship
mode=no-mistakes
spawn_epoch=1700000000
end_epoch=1790618157
outcome=report
outcome_ref=data/retained-1/report.md

# cleanup removes the task record and sidecars
$ bin/fm-spend-ledger-append.sh retained-1   # captain answer closes it
{
  "task": "retained-1",
  "kind": "scout",
  "outcome": "report",
  "outcome_ref": "data/retained-1/report.md",
  "usd_lane": "unmeasured",
  "pipeline_cost_lane": "api-equiv",
  "pipeline_usd": 1.5375,
  "pipeline_unmeasured_invocations": 3
}
spend-context removed after a successful append: yes

\### Ledger after every close path (data/spend-ledger.jsonl)
{"task":"demo-1","kind":"ship","outcome":"pr","pipeline_usd":1.5375,"pipeline_cost_lane":"api-equiv"}
{"task":"unpriced-1","kind":"ship","outcome":"local-main","pipeline_usd":null,"pipeline_cost_lane":"unmeasured"}
{"task":"mixed-1","kind":"ship","outcome":"local-main","pipeline_usd":0.075,"pipeline_cost_lane":"partial"}
{"task":"retained-1","kind":"scout","outcome":"report","pipeline_usd":1.5375,"pipeline_cost_lane":"api-equiv"}
Evidence: Pipeline cost lanes: nothing priceable reports unmeasured, an unnamed model reports "unknown"

Source: Pipeline cost lanes: nothing priceable reports unmeasured, an unnamed model reports "unknown"

\### Scenario D: no invocation priceable -> lane unmeasured (not partial), unnamed model named 'unknown'
{
  "pipeline_cost_lane": "unmeasured",
  "pipeline_usd": null,
  "pipeline_note": "no known rate for model(s) gpt-6-astra, unknown; no invocation could be priced",
  "pipeline_input_tokens": 8000
}

\### Scenario E: some tokens priced, one unnamed model -> lane partial, note names 'unknown'
{
  "pipeline_cost_lane": "partial",
  "pipeline_usd": 0.075,
  "pipeline_note": "no known rate for model(s) unknown; pipeline_usd covers the priced invocations only"
}
Evidence: Older inventory without exit_status, and the worker-proof gate on a non-worker kind

Source: Older inventory without exit_status, and the worker-proof gate on a non-worker kind

\### Scenario F: inventory without exit_status still answers, falling back to the reported-token test
{
  "pipeline_invocations": 2,
  "pipeline_unmeasured_invocations": 1,
  "pipeline_unmeasured_ms": 7000,
  "pipeline_agent_ms": 60000,
  "pipeline_cost_lane": "api-equiv",
  "pipeline_usd": 0.625
}

\### Scenario G: a kind that never ran a worker records nothing
$ bin/fm-spend-ledger-append.sh secondmate-1
stdout: ''  exit=0
0
no secondmate line in the ledger
Evidence: Five concurrent closes of one task still record exactly one line

Source: Five concurrent closes of one task still record exactly one line

\### Scenario H: two close paths racing the same task still record exactly one line
[1]   Done                    FM_ROOT_OVERRIDE="$W" NM_HOME="$H/nm" FM_STATE_OVERRIDE="$H/state" FM_DATA_OVERRIDE="$H/data" FM_CONFIG_OVERRIDE="$H/config" HOME="$H" "$W/bin/fm-spend-ledger-append.sh" race-1 > /dev/null 2>&1
[2]   Done                    FM_ROOT_OVERRIDE="$W" NM_HOME="$H/nm" FM_STATE_OVERRIDE="$H/state" FM_DATA_OVERRIDE="$H/data" FM_CONFIG_OVERRIDE="$H/config" HOME="$H" "$W/bin/fm-spend-ledger-append.sh" race-1 > /dev/null 2>&1
[4]-  Done                    FM_ROOT_OVERRIDE="$W" NM_HOME="$H/nm" FM_STATE_OVERRIDE="$H/state" FM_DATA_OVERRIDE="$H/data" FM_CONFIG_OVERRIDE="$H/config" HOME="$H" "$W/bin/fm-spend-ledger-append.sh" race-1 > /dev/null 2>&1
[3]-  Done                    FM_ROOT_OVERRIDE="$W" NM_HOME="$H/nm" FM_STATE_OVERRIDE="$H/state" FM_DATA_OVERRIDE="$H/data" FM_CONFIG_OVERRIDE="$H/config" HOME="$H" "$W/bin/fm-spend-ledger-append.sh" race-1 > /dev/null 2>&1
[5]+  Done                    FM_ROOT_OVERRIDE="$W" NM_HOME="$H/nm" FM_STATE_OVERRIDE="$H/state" FM_DATA_OVERRIDE="$H/data" FM_CONFIG_OVERRIDE="$H/config" HOME="$H" "$W/bin/fm-spend-ledger-append.sh" race-1 > /dev/null 2>&1
race-1 lines in the ledger: 1
total ledger lines: 6
every line is valid JSON: yes
Evidence: fm-teardown.sh spend-ledger cases, including the refused no-backlog teardown

Source: fm-teardown.sh spend-ledger cases, including the refused no-backlog teardown

# bash tests/fm-teardown.test.sh  (real fm-teardown.sh driven end to end; exit 0)
ok - a teardown refused at treehouse return on a no-backlog home records no ledger line
ok - a closed ship appends one schema-versioned spend ledger line with its outcome
ok - a closed ship with session logs records measured api-equiv spend
ok - a closed scout records its report as the ledger outcome
ok - a rerun teardown keeps one spend ledger line per closed task
Evidence: Orca-recovery and captain-answer close paths from the lifecycle suites

Source: Orca-recovery and captain-answer close paths from the lifecycle suites

# Close paths driven through the real CLIs (targeted suites)

## bash tests/fm-backlog-atomicity.test.sh  (real fm-teardown.sh on an Orca recovery record)
ok - Orca cleanup recovery is excluded from backlog lifecycle transitions

## bash tests/fm-captain-hold-lifecycle.test.sh  (real fm-captain-hold.sh answer-close)
ok - a task closed by a captain answer after cleanup still records its spend line
Evidence: Ledger after four different closure paths
{"task":"demo-1","kind":"ship","outcome":"pr","pipeline_usd":1.5375,"pipeline_cost_lane":"api-equiv"}
{"task":"unpriced-1","kind":"ship","outcome":"local-main","pipeline_usd":null,"pipeline_cost_lane":"unmeasured"}
{"task":"mixed-1","kind":"ship","outcome":"local-main","pipeline_usd":0.075,"pipeline_cost_lane":"partial"}
{"task":"retained-1","kind":"scout","outcome":"report","pipeline_usd":1.5375,"pipeline_cost_lane":"api-equiv"}

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

⚠️ **Review** - 1 info
  • 🚨 bin/fm-spend-query.py:409 - Spec: the intent requires "invocations that were killed or never started are recorded as unmeasured with their duration rather than as zero cost", but collect_pipeline proxies "killed" by input_tokens is None only, so a killed invocation that reported partial usage is counted as completed work: its tokens are summed, its duration lands in pipeline_agent_ms, and its cost is priced. Verified read-only against the live inventory (~/.no-mistakes/state.sqlite): agent_invocations carries an exit_status column, and 49 rows with exit_status in ('cancelled','error') have non-NULL input_tokens (20 cancelled, 13 error also report >0 tokens). Concrete case: branch fm/fm-herdr-restore-slot-guard has 6 such rows totalling 1258 input tokens and 9,200,666 ms of duration, all of which the current code reports as measured agent time and priced api-equiv cost instead of unmeasured duration. Every site of the same invariant, one fix closes the class: the SELECT list at bin/fm-spend-query.py:383 does not fetch exit_status (needs a schema-tolerant read because an older daemon schema may lack the column, per the user's recorded instruction to fall back to the NULL test alone); the unmeasured/never-priced branch at bin/fm-spend-query.py:409-413; the schema header at bin/fm-spend-query.py:46-50 which describes the rule as "reported no tokens"; docs/configuration.md:706 with the same wording; and the fixtures that cannot express the case, tests/fm-spend-query.test.sh sp_nm_seed (agent_invocations DDL, no exit_status) and tests/fm-spend-ledger-append.test.sh:189. The user's recorded decision already authorises this exact remedy, including a test where a cancelled row carrying non-zero tokens must land as unmeasured.
  • ⚠️ bin/fm-spend-query.py:439 - Spec: the lane reads "partial" whenever any model lacks a rate, even when NO invocation was priceable, and the note then claims coverage the line does not have. Traced live (read-only) over every branch in the inventory: 8 branches return pipeline_cost_lane "partial" with pipeline_usd null, e.g. fm/hostup-pi-otel-ext (7,952,942 input tokens, note "no known rate for model(s) gpt-6-astra; pipeline_usd covers the priced invocations only") - zero invocations were priced, so the note states a falsehood and the label contradicts this file's own header at bin/fm-spend-query.py:53-63, which reserves "unmeasured" for "no honest pipeline figure exists" and defines "partial" as covering the priced part only. Every priceable prefix in RATE_TABLE (bin/fm-spend-query.py:124-128) is claude-*, so this is the ordinary outcome for any task whose pipeline ran on a codex/astra/sol profile. Sibling sites of the same label decision: bin/fm-spend-query.py:440 (usd set to None while the lane still reads partial) and :441-444 (the note text). Remedy: when priced_tokens == 0 set lane "unmeasured" with a note that no invocation carried a known rate, keeping "partial" only when some tokens were priced. Reported and selected in the previous round; the uncertified fix commits left it unchanged.
  • ⚠️ bin/fm-spend-query.py:423 - Spec: the unpriced-model guard substitutes "unknown" only for a non-str model, but the live inventory stores the empty string, never NULL, for an invocation whose model was not recorded - 106 such rows. Those rows enter unpriced_models as '' and the durable note renders with a hole. Verified live (read-only): collect_pipeline('feat/mods-branch', <its repo path>) emits pipeline_note "no known rate for model(s) ; pipeline_usd covers the priced invocations only" - it names nothing at all - and fm/branch-supervision-mod-v2 emits "no known rate for model(s) gpt-5.6-sol" only because a second, named model happens to share the branch. The operator cannot tell what the unnamed model was, and the line is silently downgraded from api-equiv by a nameless entry. Remedy: unpriced_models.add(model or &#34;unknown&#34;), which also covers the None case the current guard handles. Note this overlaps the killed-invocation finding above: most empty-model rows are cancelled/error rows that should not reach this code path at all once exit_status is honoured. Reported and selected in the previous round; unchanged by the uncertified fix commits.
  • ⚠️ bin/fm-teardown.sh:3611 - Spec: the new no-backlog-transition append runs for every ship or scout record, including the Orca spawn-recovery record, so the ledger gains a close for a task whose worker never ran. Concrete sequence: bin/fm-spawn.sh:1335-1350 publishes a recovery record carrying cleanup_recovery=orca plus kind=ship when a SPAWN aborted and the orca worktree could not be removed; bin/fm-teardown.sh:562 then leaves TEARDOWN_BACKLOG_APPLIES=0 for exactly that record, so control reaches this else branch, which sets BACKLOG_SKIP_REASON="Orca cleanup recovery is not a launched backlog worker" (bin/fm-teardown.sh:3604) and seven lines later appends a spend ledger line anyway - the producer's worker-proof gate at bin/fm-spend-ledger-append.sh:108-111 only checks kind, and the record reads kind=ship, so it passes. The retrospective then reads a closed ship with an unmeasured worker figure and pipeline columns for a branch that never ran, and the dedupe at bin/fm-spend-ledger-append.sh:272 means the real close of a reused id would append nothing. The user's recorded decision authorises the remedy: skip the append when CLEANUP_RECOVERY=orca, matching the skip reason already printed here. The sibling close-path append at bin/fm-teardown.sh:3558 is not reachable for such a record (TEARDOWN_BACKLOG_APPLIES=0), so this one site closes the class.
  • ℹ️ bin/fm-spend-ledger-append.sh:108 - Standards: two owners now decide a task's kind. bin/fm-teardown.sh:514-515 defaults TEARDOWN_META_KIND to ship when the record carries no kind= line, while the producer reads kind straight from the record and exits 0 silently when it is empty (bin/fm-spend-ledger-append.sh:84, :108-111). For such a record teardown believes it is closing a ship, gets no line back, and prints "error: could not append <id>'s spend ledger entry; continuing cleanup" - a false error with no line recorded - at both new call sites (bin/fm-teardown.sh:3558 close path, :3611 no-backlog path), while bin/fm-captain-hold.sh:982 discards it silently. Remedy: pass the caller's kind through, or mirror teardown's ship default in the producer, so one owner decides.
  • ℹ️ bin/fm-spend-ledger-append.sh:150 - Standards: moving outcome derivation out of teardown replaced fm_backlog_data_relative (bin/fm-backlog-transition-lib.sh:169-187, which yields the data directory's path relative to the home, e.g. "data/<id>/report.md") with an equality test against "$FM_HOME/data". A home reached through FM_DATA_OVERRIDE that does not spell out "$FM_HOME/data" - the exact shape tests/fm-teardown.test.sh:637-643 uses (FM_ROOT_OVERRIDE plus FM_DATA_OVERRIDE, no FM_HOME) - now records an ABSOLUTE outcome_ref in a durable field where the prior producer recorded the relative one. The assertion at tests/fm-captain-hold-lifecycle.test.sh:2874 is assert_contains, so it passes either way and cannot catch the shape change. Remedy: source fm-backlog-transition-lib.sh and reuse fm_backlog_data_relative instead of re-deriving the rule at bin/fm-spend-ledger-append.sh:150-154; teardown already sources that library for backlog_done_args.
  • ℹ️ bin/fm-spend-ledger-append.sh:230 - Standards: the last-resort jq object hardcodes unmeasured_reason "task record unreadable; session window cannot be bounded" (bin/fm-spend-ledger-append.sh:230) and pipeline_note "pipeline not queried: no task record and no python3" (:236), but it is also reached with a perfectly readable record whenever both fm-spend-query.sh invocations (:207, :209) return empty - for example the wrapper not being executable - so the durable line asserts two facts that are false for that state. Sibling site with the same mislabel: bin/fm-spend-query.sh:113, whose note asserts "python3 unavailable in the shell fallback" although emit_unmeasured also falls through to jq when python3 exists but exits non-zero, which is exactly what tests/fm-spend-ledger-append.test.sh:132 stubs. Remedy: word both after the observed condition ("no spend line could be built" / "pipeline not queried in the shell fallback"). Removing this third copy of the unmeasured shape is not available: it is the only producer of the shape for a context-only close on a host without python3.
  • ℹ️ docs/configuration.md:704 - Standards: the sentence "a failed append prints one stderr line and leaves an explicit unmeasured line rather than a missing one" holds on neither half unconditionally. With jq unavailable the producer exits after bin/fm-spend-ledger-append.sh:238 having written nothing, and the change's own test asserts exactly that (tests/fm-spend-ledger-append.test.sh:156: no ledger file exists). The captain-answer close path redirects the producer's stderr to /dev/null (bin/fm-captain-hold.sh:982, &gt;/dev/null 2&gt;&amp;1 || true), so no stderr line reaches the operator there. Remedy: narrow the claim to the paths that hold it.

🔧 Fix applied.
6 issues (1 error, 4 warnings, 1 info) still open:

  • 🚨 bin/fm-spend-query.py:409 - Spec: the intent requires "invocations that were killed or never started are recorded as unmeasured with their duration rather than as zero cost", but collect_pipeline proxies "killed" by input_tokens is None only, so a killed invocation that reported partial usage is counted as completed work: its tokens are summed, its duration lands in pipeline_agent_ms, and its cost is priced. Verified read-only against the live inventory (~/.no-mistakes/state.sqlite): agent_invocations carries an exit_status column, and 49 rows with exit_status in ('cancelled','error') have non-NULL input_tokens (20 cancelled, 13 error also report >0 tokens). Concrete case: branch fm/fm-herdr-restore-slot-guard has 6 such rows totalling 1258 input tokens and 9,200,666 ms of duration, all of which the current code reports as measured agent time and priced api-equiv cost instead of unmeasured duration. Every site of the same invariant, one fix closes the class: the SELECT list at bin/fm-spend-query.py:383 does not fetch exit_status (needs a schema-tolerant read because an older daemon schema may lack the column, per the user's recorded instruction to fall back to the NULL test alone); the unmeasured/never-priced branch at bin/fm-spend-query.py:409-413; the schema header at bin/fm-spend-query.py:46-50 which describes the rule as "reported no tokens"; docs/configuration.md:706 with the same wording; and the fixtures that cannot express the case, tests/fm-spend-query.test.sh sp_nm_seed (agent_invocations DDL, no exit_status) and tests/fm-spend-ledger-append.test.sh:189. The user's recorded decision already authorises this exact remedy, including a test where a cancelled row carrying non-zero tokens must land as unmeasured.
  • ⚠️ bin/fm-spend-query.py:439 - Spec: the lane reads "partial" whenever any model lacks a rate, even when NO invocation was priceable, and the note then claims coverage the line does not have. Traced live (read-only) over every branch in the inventory: 8 branches return pipeline_cost_lane "partial" with pipeline_usd null, e.g. fm/hostup-pi-otel-ext (7,952,942 input tokens, note "no known rate for model(s) gpt-6-astra; pipeline_usd covers the priced invocations only") - zero invocations were priced, so the note states a falsehood and the label contradicts this file's own header at bin/fm-spend-query.py:53-63, which reserves "unmeasured" for "no honest pipeline figure exists" and defines "partial" as covering the priced part only. Every priceable prefix in RATE_TABLE (bin/fm-spend-query.py:124-128) is claude-*, so this is the ordinary outcome for any task whose pipeline ran on a codex/astra/sol profile. Sibling sites of the same label decision: bin/fm-spend-query.py:440 (usd set to None while the lane still reads partial) and :441-444 (the note text). Remedy: when priced_tokens == 0 set lane "unmeasured" with a note that no invocation carried a known rate, keeping "partial" only when some tokens were priced. Reported and selected in the previous round; the uncertified fix commits left it unchanged.
  • ⚠️ bin/fm-spend-query.py:423 - Spec: the unpriced-model guard substitutes "unknown" only for a non-str model, but the live inventory stores the empty string, never NULL, for an invocation whose model was not recorded - 106 such rows. Those rows enter unpriced_models as '' and the durable note renders with a hole. Verified live (read-only): collect_pipeline('feat/mods-branch', <its repo path>) emits pipeline_note "no known rate for model(s) ; pipeline_usd covers the priced invocations only" - it names nothing at all - and fm/branch-supervision-mod-v2 emits "no known rate for model(s) gpt-5.6-sol" only because a second, named model happens to share the branch. The operator cannot tell what the unnamed model was, and the line is silently downgraded from api-equiv by a nameless entry. Remedy: unpriced_models.add(model or &#34;unknown&#34;), which also covers the None case the current guard handles. Note this overlaps the killed-invocation finding above: most empty-model rows are cancelled/error rows that should not reach this code path at all once exit_status is honoured. Reported and selected in the previous round; unchanged by the uncertified fix commits.
  • ⚠️ bin/fm-teardown.sh:3611 - Spec: the new no-backlog-transition append runs for every ship or scout record, including the Orca spawn-recovery record, so the ledger gains a close for a task whose worker never ran. Concrete sequence: bin/fm-spawn.sh:1335-1350 publishes a recovery record carrying cleanup_recovery=orca plus kind=ship when a SPAWN aborted and the orca worktree could not be removed; bin/fm-teardown.sh:562 then leaves TEARDOWN_BACKLOG_APPLIES=0 for exactly that record, so control reaches this else branch, which sets BACKLOG_SKIP_REASON="Orca cleanup recovery is not a launched backlog worker" (bin/fm-teardown.sh:3604) and seven lines later appends a spend ledger line anyway - the producer's worker-proof gate at bin/fm-spend-ledger-append.sh:108-111 only checks kind, and the record reads kind=ship, so it passes. The retrospective then reads a closed ship with an unmeasured worker figure and pipeline columns for a branch that never ran, and the dedupe at bin/fm-spend-ledger-append.sh:272 means the real close of a reused id would append nothing. The user's recorded decision authorises the remedy: skip the append when CLEANUP_RECOVERY=orca, matching the skip reason already printed here. The sibling close-path append at bin/fm-teardown.sh:3558 is not reachable for such a record (TEARDOWN_BACKLOG_APPLIES=0), so this one site closes the class.
  • ⚠️ bin/fm-teardown.sh:3611 - Spec: the no-backlog-transition append (added by this change) records the ledger line before teardown's destructive-step refusals, and unlike the close path it has no close marker to make that line true. Concrete sequence on a home where the backlog gate does not apply (manual backend, or a markdown home with no backlog file): a plain treehouse-owned ship reaches bin/fm-teardown.sh:3611, the shared producer appends its line, then teardown_treehouse_return fails and teardown exits 1 at bin/fm-teardown.sh:3680 ("treehouse return failed for worktree ...; teardown aborted"). The task record, endpoint and worker all survive, so the task is not closed - but the ledger now names it closed with that attempt's window bound (the sidecar mtimes at the time) and that attempt's outcome (no PR URL if the pr= line was not yet on the record). Because the producer deduplicates by task id (bin/fm-spend-ledger-append.sh:270-279), the real close later prints the stale line and appends nothing, so the ledger permanently under-reports that task. The close path at bin/fm-teardown.sh:3558 is not exposed the same way: its append is immediately followed by fm_backlog_close_marker_write, so every later refusal happens with the close already durably staged and replayable by bootstrap. The user's earlier docs-only decision covered exactly that marker-staged case and does not describe this one. Two sites hold the same invariant: this append, and the documentation claim at docs/configuration.md:704 ("A teardown refused before capture records nothing; one refused while staging the pending close has already appended its line"), which does not mention the no-backlog path at all. Smallest honest remedy is an ordering change (move this append past the destructive-step refusals, next to the record removal) or an explicit doc correction - both are the author's call about when a close counts, so this needs authorization rather than a reviewer fix.
  • ℹ️ bin/fm-spend-query.py:102 - Standards: the schema owner's header still states the pre-fix rule - "an invocation whose model matches no prefix keeps its tokens in the token sums while its cost stays unmeasured (lane &feat(bin): record shadow advisory facts and add the candidate gates scorer #34;partial&feat(bin): record shadow advisory facts and add the candidate gates scorer #34;)" - but the fix round added the nothing-priced case at bin/fm-spend-query.py:456-461, which returns lane "unmeasured" with the note "no known rate for model(s) ...; no invocation could be priced". Verified read-only against the live inventory: 8 of 190 branch/repo pairs now report lane "unmeasured" (e.g. fm/fm-trace-attrs, all-gpt-6-astra invocations), so the header describes a lane the code no longer produces for that input. docs/configuration.md:706 was updated for this case ("or unmeasured when no invocation could be priced"); the header the docs point at as the single owner was not. The lane enumeration a few lines above (bin/fm-spend-query.py:59-66) is still accurate, so only this paragraph needs the added clause.

🔧 Fix applied.
1 info still open:

  • ℹ️ bin/fm-spend-ledger-append.sh:232 - Standards: the fix round reworded the last-resort line's unmeasured_reason to "no spend line could be built; session window cannot be bounded", but kept the second clause, which is false for the state that actually reaches this jq object with a readable record. Concrete sequence: state/<id>.meta is readable and carries spawn_gen=s1700000000.1.x plus a state/<id>.turn-ended sidecar (window fully boundable), but bin/fm-spend-query.sh cannot be executed at all - for example the wrapper loses its execute bit after an interrupted checkout - so both invocations at bin/fm-spend-ledger-append.sh:209 and :211 return empty, the context branch at :214 is skipped because no state/<id>.spend-context exists, and control falls to :226. The durable ledger line then records a reason asserting the window could not be bounded when it could; a retrospective reading that field concludes the record was unusable rather than that the query binary was. The prior round's own change is what left this clause: it prefixed the observed condition and did not drop the inherited one. Sibling site holding the same invariant is now correct after that round - bin/fm-spend-query.sh:113 reads "pipeline not queried in the shell fallback" and asserts nothing about python3 - so only this one string remains. Remedy: end the reason at the observed condition ("no spend line could be built for this task").
✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 12 of 12 scenarios driven live against the product
Scenario Result Live Evidence
A closed ship records one ledger line carrying the no-mistakes pipeline's tokens, duration and cost ✅ pass live bin/fm-spend-ledger-append.sh demo-1 against an isolated FM_HOME with a seeded inventory; line carries pipeline_runs 1, pipeline_input_tokens 150000, pipeline_agent_ms 90000, pipeline_usd 1.5375, la…
Killed and never-started invocations are recorded as unmeasured duration, never priced as zero cost ✅ pass live The same close: a cancelled row carrying 1258 tokens, an errored row carrying 4000, and a NULL-token row all land in pipeline_unmeasured_invocations 3 / pipeline_unmeasured_ms 1025000, and their token…
A task closed by the captain's answer after teardown removed its record still records its line ✅ pass live --stash retained-1, record and sidecars deleted, then bin/fm-spend-ledger-append.sh retained-1 emitted the scout line with outcome_ref data/retained-1/report.md; also `bash tests/fm-captain-hold-l…
A teardown on a home with no backlog transition records its line ✅ pass live bash tests/fm-teardown.test.sh case a closed ship appends one schema-versioned spend ledger line with its outcome, driving fm-teardown.sh end to end (exit 0)
Adversarial: a teardown refused at treehouse return on a no-backlog home records no close ✅ pass live bash tests/fm-teardown.test.sh case a teardown refused at treehouse return on a no-backlog home records no ledger line — teardown exits 1, no spend-ledger.jsonl exists, task record survives
Adversarial: an Orca cleanup recovery records no phantom close ✅ pass live bash tests/fm-backlog-atomicity.test.sh case Orca cleanup recovery is excluded from backlog lifecycle transitions, which now fails if the ledger names the task (exit 0)
Adversarial: reruns and concurrent closes never double-count a task ✅ pass live Second bin/fm-spend-ledger-append.sh demo-1 reprinted the recorded ts and left the count at 1; five concurrent closes of race-1 produced 1 line with the whole file valid JSON (live-close-and-dedupe.…
Adversarial: a pipeline where nothing could be priced is labelled unmeasured, not partial ✅ pass live bin/fm-spend-ledger-append.sh unpriced-1 returned lane unmeasured, usd null, note "no known rate for model(s) gpt-6-astra, unknown; no invocation could be priced"; mixed-1 kept lane partial with 0.0…
Adversarial: an invocation with no recorded model is named rather than leaving a hole in the note ✅ pass live Both unpriced-1 and mixed-1 notes name unknown for the empty-model row instead of rendering an empty entry (live-pipeline-lanes.txt)
Adversarial: an older inventory without exit_status still answers, falling back to the reported-token test ✅ pass live bin/fm-spend-ledger-append.sh oldschema-1 against an agent_invocations table with no exit_status column: 2 invocations, 1 unmeasured (7000 ms), lane api-equiv, usd 0.625 (live-schema-fallback-and-ga…
Adversarial: a task kind that never ran a worker records nothing ✅ pass live bin/fm-spend-ledger-append.sh secondmate-1 printed nothing, exited 0, and added no ledger line (live-schema-fallback-and-gate.txt)
A close whose spend query fails still records an explicit unmeasured line rather than none ✅ pass live bash tests/fm-teardown.test.sh case a broken spend query never fails the cleanup and still records unmeasured, plus bash tests/fm-spend-ledger-append.test.sh case `a failed spend query records a…
  • bin/fm-spend-ledger-append.sh demo-1 against an isolated FM_HOME with a seeded no-mistakes inventory (5 invocations: 2 completed claude, 1 cancelled carrying 1258 tokens, 1 error carrying 4000 tokens, 1 with NULL tokens)
  • bin/fm-spend-ledger-append.sh demo-1 a second time (dedupe)
  • bin/fm-spend-ledger-append.sh --stash retained-1, then record removal, then bin/fm-spend-ledger-append.sh retained-1 (captain-answer close path)
  • bin/fm-spend-ledger-append.sh unpriced-1 (no invocation priceable) and mixed-1 (one unnamed model among priced ones)
  • bin/fm-spend-ledger-append.sh oldschema-1 against an inventory whose agent_invocations lacks exit_status
  • bin/fm-spend-ledger-append.sh secondmate-1 (kind that never ran a worker)
  • 5 concurrent bin/fm-spend-ledger-append.sh race-1 processes against one ledger
  • bash tests/fm-spend-ledger-append.test.sh (7 cases, exit 0)
  • bash tests/fm-spend-query.test.sh (27 cases, exit 0)
  • bash tests/fm-teardown.test.sh (112 cases, exit 0; includes a teardown refused at treehouse return on a no-backlog home records no ledger line)
  • bash tests/fm-captain-hold-lifecycle.test.sh (56 cases, exit 0; includes a task closed by a captain answer after cleanup still records its spend line)
  • bash tests/fm-backlog-atomicity.test.sh (99 cases, exit 0; includes Orca cleanup recovery is excluded from backlog lifecycle transitions, now asserting no spend line)
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

andrewesweet and others added 7 commits September 28, 2026 17:39
…columns

Every ship/scout close funnels through bin/fm-spend-ledger-append.sh, so a
retained captain call (stashed context, appended at answer), a home without a
backlog gate, and a failed query (explicit unmeasured fallback) all record
exactly one schema 2 line. The line gains pipeline columns from no-mistakes
agent_invocations: run/invocation counts, tokens by class, agent duration and
cost at known rates, with tokenless invocations counted with duration rather
than priced as zero.
The two teardown cases waited 10s for the watcher to notice a deleted
state directory or home. The watcher only checks at the top of its next
cycle, so on a loaded CI runner one already-running cycle outlasts that
bound and the case failed with "watcher pid ... outlived its deleted
state directory". Both waits now use one TEARDOWN_EXIT_POLLS ceiling of
40s, matching the file's existing re-arm convention.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…ontention

The held-marker-lock fixture took .watcher-down.lock with a single
fm_lock_try_acquire. In the plain (non-successor) case the watcher under
test takes that same lock once per poll in resurface_after_downtime with
FM_POLL=1, so an ordinary race made the holder exit immediately and the
case failed with "the fixture could not take the downtime-marker lock" -
the serial-1 shard failure, not a defect in the code under review.

Retry the acquire in a bounded loop (50 ticks, 5s) before the branch, so
both the successor and non-successor fixtures share it while staying
inside the caller's 10s wait for the held marker; genuine contention
still fails the fixture.

Verified: shellcheck -x clean; bash tests/fm-watch-triage.test.sh exit=0,
140 ok, 0 not ok.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@andrewesweet
andrewesweet merged commit 395c723 into main Sep 28, 2026
19 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.

1 participant