Skip to content

feat(ledger): resolve slot keys and wire eight session emitters - #11185

Merged
iamwhatever merged 1 commit into
kirodotdev:mainfrom
chenmingwei23:feat/ledger-resolver
Sep 18, 2026
Merged

iamwhatever merged 1 commit into
kirodotdev:mainfrom
chenmingwei23:feat/ledger-resolver

Conversation

@chenmingwei23

@chenmingwei23 chenmingwei23 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

The session ledger that #10091 shipped defines 34 entry types and writes 17 of them. The other 17 are schema-only: their shape is frozen and documented, and no code emits them.

Eight of those describe work the gateway does on a user's behalf and currently leaves no trace of:

  • a tool call parked waiting on a human, and how that approval resolved
  • the agent's own task list, each time it restates it
  • a model call the gateway charges to the session without the user asking for it -- titling, summarizing, memory consolidation
  • the whole life of a subagent a session dispatched: spawned, steered, and its terminal outcome

#10091 gave one reason for leaving them out, and it was an identity problem. The emitter keys every entry by an ACP session id, which the turn path has in hand. Skill injection, background model calls and subagent dispatch hold only the key naming a slot, so they had no way to say which ledger their fact belonged in.

Why it matters

Two of these gaps are about money and consent. A background model call spends the user's budget without being asked, and until now that spend appeared in the usage store with nothing in the session it was charged to. An approval is the one moment the agent stops and asks permission; a log that omits both the request and the answer cannot reconstruct what the user agreed to.

The subagent gap is about work that is invisible after the fact. A session can dispatch children that run for half an hour, and the parent's log said nothing about having done so.

The remaining nine types stay unwritten, and this PR replaces "deferred" in their Emitter column with the specific reason each one is not derivable, so the next contributor does not re-litigate a decision or, worse, add a second emitter for a fact already recorded.

What changed (motivation, approach, change)

Goal. Wire the eight types whose facts the gateway can actually observe, and say plainly why the other nine cannot be.

Approach. The identity gap turned out to be smaller than #10091 assumed, and investigating it changed the shape of this PR three times:

  1. Two of the types need no resolver at all. Both approval sites sit inside _run_chat, where the session id and turn number are already in scope. feat(ledger): append-only per-unit ledgers with a lifecycle writer #10091's note said ApprovalCoordinator holds only a slot key -- true of that class, but the sites that raise and decide an approval are not in it.
  2. Four types plus two background kinds do need one, so this adds src/kiro_crew/crew_log.resolve.py: one exact registry read plus an attribute read on the provider it returns, and UNKNOWN when the slot has no live ACP session. There is deliberately no slot-keyed level: an earlier draft read the slot's live _acp_client first and fell back to the registry, but the registry answers the same id during a turn as between turns -- the provider it holds IS the one the runner reads -- so that level had no caller and no question only it could answer. It is read-only and builds no index. The persisted SessionMap is deliberately not consulted -- its get repairs or removes a stale entry, which is a write, and it answers only for ids that reached disk, so it would miss exactly the live session a caller is asking about.
  3. Four types should not be written, and not for want of a resolver. tool_search, skill_search and reading a skill file already arrive as ordinary ACP tool-call frames, so tool/called records them today. A second entry would put one fact under two seqs.
  4. One premise in the frozen schema is false. It says a subagent is itself a session with its own ledger, but no subagent code path opens one -- the only site that creates a session ledger is the dashboard turn path, which a subagent run does not go through. So subagent/spawned carries no ref; a ref written now would cite a file that does not exist, which a reader cannot tell from one that was deleted. It becomes writable unchanged the day subagent sessions get ledgers.

What this builds. One rule governs every emitter here: an entry says only what was observed at its emit site. Three consequences did real work:

  • A resolver answers "now", so anything outliving the question must carry the answer. A background call's owner is resolved and pinned before the model call, not after it. Resolving afterwards attributed spend to whichever session happened to exist at teardown -- including one created after the call was already under way.
  • Being accepted is not being started. A child's asking turn is knowable only where the spawn is accepted, but the entry may only be written where the run actually begins. So the pin is taken at acceptance and starts unopened; _log_spawned, the codebase's own "this run is really starting" funnel, is what opens it. A spawn declined at the approval gate leaves no opener, and the closers are gated on opened so they close nothing. A queued member re-entering the spawn path keeps its original asking turn.
  • Bounds are measured, never assumed. plan/updated clips each task's text by characters, but the store serializes with ensure_ascii, which spends six bytes on a BMP character and twelve on a surrogate pair. A hundred separately-legal rows of emoji serialized past the entry ceiling, where the append is refused and the whole update disappears. Each row is now measured through the store's own serializer before it is admitted, and total still reports the real count.

Zero is never written as a measurement. subagent/completed carries no tokens and no credits because nothing in the subagent runtime measures either; a spawn with no asking turn omits turn rather than writing 0, since turns are numbered from one.

Everything stays behind KIROCREW_CREW_LOG, default off, and the two emitters the runner calls unconditionally now return before doing any work when the flag is off.

Log-only: no projections, no fold, no endpoint, no UI.

This implements merged RFC #10090 (docs/request-for-change/rfc-append-only-ledger.md) and follows #10091 (merged as 69aeb28).

Tests

37 new tests in test/test_crew_log_resolver.py, plus the existing shape-contract test in test/test_crew_log_emit.py extended to pin the eight new types.

What they lock in, by area:

  • Resolver -- a namespaced key resolves through the live registry; a channel-born slot resolves through the channel's own session rather than a fabricated dashboard key; a slot that never ran a turn answers UNKNOWN; a raising registry answers UNKNOWN instead of propagating; a bare slot name is retried in dashboard form but a key that already carries a namespace is never rewritten; resolution reads only live state.
  • Approvals -- a request is recorded before its decision; a host decline names the host and its cause while a human decision names neither; an unnamed tool is omitted rather than written as an empty string; a long reason is clipped rather than costing the entry; the reason is redacted at the emitter rather than trusted from the site.
  • plan/updated -- only the two states the stream carries; no task list writes nothing while an empty list records a cleared plan; a plan of emoji is bounded by bytes and still lands; one oversize row does not suppress the whole entry; a clipped plan still reports its real size; the entry is marked ignorable.
  • background/completed -- records the dimensions that were billed and omits the rest; names no turn; a call with no owner or no kind writes nothing; the owner is resolved before the call, not after it.
  • Subagents -- a child is spawned then closed and the spawn carries its scope; the spawn carries no ref; a spawn with no asking turn omits the field; a completed child reports no tokens and no credits; a stopped child is not recorded as a completion; an origin is pinned once so a queued member keeps its asking turn; a pin is invisible until the run actually starts; opening twice cannot produce two openers; a declined spawn releases its pin and closes nothing; forgetting an opened origin returns it once; an unrecorded dispatch produces no closer; the origin map is bounded by uptime rather than by live turns.
  • Flag -- the two unconditionally-called emitters do no work with the flag off.

Every one of those assertions is mutation-verified: 20 mutations, each inverting one behaviour the diff introduced, all 20 killed. Two mutations written in an earlier round were discarded honestly rather than counted -- one anchored to two call sites, and one that could not fail because an empty session id already no-ops a layer lower.

Full local run on this head: 1013 focused tests plus 199 in the remaining ledger suites, 0 failures; mypy src/kiro_crew/ clean over 1548 files; black 26.3.1 (diff-scoped), isort, flake8, comment-history (gated on origin/main) and docs-lint all pass.

Manual verification

N/A -- unit coverage sufficient. Every emitter is a pure function of values already in scope at its site, and the site wiring is one line each; there is no integration path, external service or UI surface that unit coverage does not reach. The feature is off by default, so there is no runtime behaviour to exercise without setting the flag.

Other suggestions

Three things a reviewer may want to weigh in on:

  1. crew-log-core.md section 5 disagreed with the frozen code on the approval types. The table said {turn, id, tool, reason}; the shipped and tested function takes approval_id and had neither reason nor by. Renames are forbidden by the freeze, so the table was corrected to match the code, and reason, by and cause were added as optional parameters, which is additive. Flagging it because a spec correcting itself to the code is worth a second pair of eyes.

  2. A background call charged to a session whose ACP session is already gone is not recorded. Resolving later would find some session, but on the only interleaving where late resolution succeeds and early resolution fails, the session it finds was created after the call was ordered -- so the spend would be attributed to work that did not cause it. In an append-only file a confident wrong attribution is worse than a visible absence, so the limitation is named in the spec rather than papered over.

  3. A local review lane suggested tightening "done" if task.get("completed") to ... is True, in case the field arrives as a truthy non-bool. It is declined and recorded here instead: the field is a JSON boolean on this stream, where both forms agree, and the stricter form would make a real 1 read as open -- wrong in the opposite direction. It is left as the maintainer's call.

  4. A review lane's finding on the child closer is FIXED, in the emitter AND in the order the terminal path writes. Between a child's info.done becoming true and its terminal entry reaching the file, the manager stops listing it, so a resume repair entering that window could write outcome: "unknown" ahead of the real outcome and leave two outcomes for one agent_id in a file nothing rewrites. The submit that carries a terminal entry returns before the entry lands, so the manager's run map cannot answer this on its own, and its completed-run retention is bounded by a policy that evicts the oldest by start time, so a long-running child that has just finished can be dropped from it too. The emitter answers instead, because it is the one component that knows what it still owes: it reports no child of a session gone while an entry for that session is outstanding, and the debt set holds a queued entry, one the writer has claimed out of the queue and not yet attempted, a retained one, and an owed loss marker alike. An entry a hard ceiling refuses is absent from that set, which is the wanted answer, because that closer is never coming and the opener is the repair's to close. The terminal path carries the other half: the entry is handed to the writer BEFORE info.done flips. An earlier revision of this item argued the two statements were adjacent and so the gap was unobservable -- that holds only for tasks on the event loop, and the component that reads it is the crew log's writer, which drains on its own thread and can therefore land between them. Recording first means the debt exists by the time the child leaves the running set, so the probe refuses on one or the other at every instant; the order is pinned by a test that reads the function, because a test on the calling thread cannot schedule itself into the writer's window.

  5. Function-local crew_log.emit imports are kept over the top-level-imports advisory. They are the convention here rather than an exception to it -- 18 function-local against 5 module-scope, including the sites that merged with the first PR in this series -- and at module scope every gateway start would import the ledger store whether or not the flag is set.

  6. The child-origin pin map's bound is FIXED to prefer a finished child, and a live child's pin is never dropped without being counted. A review lane was right that _child_origin holds at most 2048 pins and evicted the oldest blindly, so an accepted child's attribution could go: its subagent/spawned absent when the pin went before the run started, its opener left unmatched when the pin went after. Nothing releases the pin of a child a crash took, so those accumulate and the bound was reachable across long uptime rather than only by that many children genuinely running. The cap now asks the liveness probe over a bounded window of the oldest pins and drops a FINISHED child's pin in preference -- the entries that pin could still carry are never coming, so dropping it costs nothing, and the same step is what reclaims the pins of children lost to a crash. Only when every candidate is still running does the oldest go, and then the drop is counted in lost_child_origins() and named in the log once, beside the writer's other loss counts. No entry is written for it and no schema field was added: no declared type describes a lost pin, and adding one would be a shape change made to record a bug rather than a fact of the session. The lane's own remedy -- hold every pin to its terminal and gate admission before the bound is exceeded -- is deliberately NOT taken: this is a default-off log, and a log that refuses a real subagent spawn to protect its own bookkeeping has become the more expensive failure. Residual, stated plainly, in two parts. With 2048 children running at once and none of them finished, one live pin is still dropped -- bounded, and visible in the counter and the log rather than silent. And a child still WAITING in the admission queue is absent from the manager's run map, which is registered at dispatch, so the probe reports it as not running and it is dropped through the preference branch instead: that drop is not counted, because only the fallback increments the counter. Both cost a matched PAIR of entries rather than a contradiction -- an emptied pin makes every caller bail, so neither an opener nor a closer is written -- and both need more than 2048 pins alive at once, since the reap only runs above the ceiling. A second bound was added at the same point of retention after a later review round: the session id a pin carries is authored by the provider, and a cap on the NUMBER of pins bounds memory only when each pin's own fields are bounded too, so an id longer than the declared maximum is refused and counted through the same counter. It is refused rather than shortened because an identity that has been cut down names a different unit or none at all. The maximum sits far above any id this codebase produces, so it rejects nothing legitimate.

  7. A review lane's finding that a cold session's title spend goes unrecorded is real, but its prescribed fix is declined because it reopens a defect the same lane made me fix. On a first send to a new chat the auto-title call can run before the foreground ACP session is registered, so the slot key resolves to no session id and the emitter's empty-id no-op drops that spend entry: the tokens are billed and the log does not say so. The lane's remedy is to resolve and pass the session id after get_or_create registers it -- that is, LATER. An earlier round of the same lane found the opposite defect on this exact path and the fix for it was to hoist the resolution ABOVE the first suspension point, because the acquisition can take the background runtime lock and start a runtime, and a slot reset, switch or compaction inside that window gives the successor a new session id -- so a late lookup files the spend against a session that never incurred it. Taking the new remedy would trade a visible absence for a confident wrong attribution in a file nothing rewrites, which is the worse of the two for every reader. The absence is therefore accepted and named here, with the residual stated: a title generated before its session registers is not attributed, and the spend is visible in usage accounting rather than in this log.

  8. A review lane found that a Stop-triggered rejection was recorded as a human decision, and it is FIXED. approval/decided.by exists to tell a host decision from a person's, and an absent by is defined here as a person's answer. The dashboard Stop path resolves each pending approval with an ordinary "rejected" and raises nothing, so neither the auto-decline cause nor the cancellation flag was set and the closer named nobody -- writing a host stop into an append-only file as a refusal someone made. The earlier cancellation fix covered only the fallback path; this is the primary one. Every other host cause is detected by the awaiting code itself and is a local variable, while Stop is detected outside the runner, so the provenance is carried on the slot: the ids a Stop rejected are recorded where it resolves the future -- that site already knows, since it logs the same fact to SEL as rejected_on_stop -- and the runner reads one id and DISCARDS it at the emit. Per id rather than a slot-wide flag, so a later human rejection on the same slot cannot inherit the attribution, and marked before the future resolves, since resolving can wake the reader at once. No cause is borrowed for it: that vocabulary renders user-facing denial text and falls back to the policy wording, so a name from it would put a sentence about policy in front of someone who simply pressed Stop. by="host" with no cause is what the schema allows and what is true.

  9. A review lane's finding that idle-expiry consolidation loses its ledger charge is real, and it is the same cause as item 7 rather than a new one. A memory consolidation scheduled by idle expiry runs after the slot's teardown has begun. The call is charged by session key, and the resolver answers only what is true when it is asked: once the reset has removed the provider there is no ACP session id for that key, so the resolver returns empty and the emitter's empty-id no-op drops the entry -- the tokens are billed and this log does not say so. The lane's remedy, pinning the id before scheduling and passing it through consolidation, is right in principle for this path, because a session being expired is exactly the one that should be charged; carrying it there means threading a resolved id through the consolidation call path as a new parameter, in a subsystem this PR otherwise only adds emit calls to, and this PR has reached its agreed change budget. Resolving later instead is refused for the reason item 7 gives: an earlier round of this same lane made me hoist resolution above the first suspension point, because a reset, switch or compaction inside that window gives the successor a new session id and a late lookup files the spend against a session that never incurred it. Residual, stated plainly: a consolidation triggered by idle expiry is billed and not recorded here. It is bounded to that trigger -- a consolidation on a live session resolves normally -- it changes no control decision, and the spend stays visible in usage accounting. The lane's red is left standing rather than argued away.

  10. A review lane found that a spawn was recorded before its startup prerequisites succeeded, and it is FIXED. The subagent/spawned entry was written on entry to the confirmed-start funnel, ahead of the write that persists the run's memory binding. When that write fails the run never allocates a provider and settles as a failure, so the entry stated a start that did not happen. It now sits past that write, beside the stat that counts a confirmed start for the same reason. Nothing is left dangling by the earlier exit: the pin is released by the terminal report, and a pin that was never opened closes nothing, so a run that could not persist its binding writes no opener and no closer rather than a pair describing a run that never began.

  11. A review lane's finding that a suppressed follow-up is recorded as a steer is real, and it is left standing because the fix decides what the entry MEANS. A queued follow-up is recorded when spawn_steer accepts it, which is also what the reply promises the caller: queued, with its watcher armed. If the user then stops the run, the watcher takes the user_stopped branch, announces a synthetic failure and never dispatches the continuation -- and no compensating entry lands, because the run's real terminal already released the pin, so a second announce for the same agent_id writes nothing. The lane's remedy, recording at dispatch instead, is not a relocation: several queued messages drain as ONE continuation, so N accepted corrections would become one entry, and a follow-up accepted before a restart would be absent from the log the caller was told it was queued in. Choosing between accepted and delivered as the meaning of subagent/steered is a decision about the frozen vocabulary, not a mechanical move, and it is deliberately not made under this PR's change budget. Residual, stated plainly: a follow-up accepted and then suppressed by a user stop reads in the crew log as a steer that happened, with the run's own failure entry nearby but not linked to it. It changes no control decision, and the suppression is recorded in the audit log as followup_suppressed.

  12. A review lane found that a plan task's id skipped redaction, and it is FIXED. The text of a task went through the redactor and its id did not, while the write path applies no entry-level redaction of its own -- it hands the row to the append as it stands. A task id is as agent-authored as the text beside it, so a credential echoed into one persisted verbatim in a file nothing rewrites. The id now goes through the same redactor, stringified FIRST because the redactor answers a non-string with the empty string and every numeric id would otherwise be erased. An ordinary id is untouched, which the test asserts beside the redacted case.

  13. A review lane found the child-liveness debt check blind to a batch the writer had already claimed, and it is FIXED -- in two steps, because the first fix suppressed the very repair it protects. The writer takes a session's owed entries OUT of the queue before it appends them, so between that claim and the last append those entries were in none of the three places the check looked: a caller asking whether this process still owed the session anything was told no, and the repair could write an unknown outcome ahead of a real terminal sitting in the batch. Counting the claimed entries fixed that and introduced the opposite fault, which the next review round caught: a resume submits its own open-and-repair work through the same writer, so the repair runs INSIDE a claimed batch and was reading its own job as debt -- every child looked live on exactly the path the repair exists for, and a dangling opener would never have been closed. The count is therefore per ENTRY and an entry stops counting as it is ATTEMPTED, so the job doing the asking is never among the ones it waits for, while everything behind it still is. Whatever a pass does not reach is released on the way out, where each of those entries is already written, dropped with a loss marker, or back in the queue -- so no count is carried twice and none is dropped. The inline ordering path reads the same predicate and keeps its own separate gate on the writer being busy, so nothing can slip ahead of a batch in flight.

  14. A review lane's finding that merged follow-ups name only the last asking turn is real, and it is left standing because its remedy either loses information or changes the frozen vocabulary. Each queued follow-up is appended to the same run, and the origin pin holds one (session, turn) pair, so two asks from different turns produce one continuation whose subagent/spawned names the later turn. The lane's first remedy, per-message origin state, cannot change what this entry says: one merged continuation is one dispatch and the entry carries one turn, so richer upstream state still collapses to a single field unless that field becomes list-valued, which is a vocabulary change rather than a change to this code. Its second, omitting turn when a continuation spans turns, removes information rather than adding it: today a reader learns the most recent ask, after the change they learn nothing about any ask, and the dropped turn is not recovered elsewhere. What bounds the residual is that every individual ask is recorded as subagent/steered at the turn that made it, before the pin is overwritten, so turn 2's causation is in the file in turn 2's bracket under the same agent_id a reader groups a child's entries by. Residual, stated plainly: when several follow-ups from different turns merge, that continuation's spawn entry names the last asking turn and not the earlier ones. It changes no control decision, and each ask stays recorded at its own turn. The call-site comment now says which turn a merged dispatch names.

  15. A review lane found the child-liveness probe could close a child whose closer was not yet written, and it is FIXED -- in two steps, because my first attempt rested on a premise the code does not support. The probe answers from two reads in different lock domains. I first reordered them, arguing that a child seen gone must already owe its closer because the terminal path records before flipping done. The lane's next round showed that is false on the path that matters: normal completion flips done in the run loop, the manager's running set is everything not done, and the terminal entry is handed over later from the report task -- so between them the child is neither running nor owed, and either read order says gone. I traced both sites before accepting it. The reorder stays because it is still the correct order, but what closes the window is the child's OWN origin pin: it is opened when the spawn is recorded and the probe now refuses while it is held, and the terminal path releases it AFTER handing the closer to the writer rather than before, so the writer's debt takes over from the pin with no instant in between. Reporting stays one-shot without the pin pop, because every route to the terminal report is gated on _claim_finalize, which hands out one token. Three mutations pin it: dropping the probe's pin guard, releasing before the handover, and never releasing. What remains is the pin the FIFO drops at its own ceiling, which item 6 counts rather than hides. Two stale comments asserting the old premise were corrected in the same change.

Related Issues

No linked issue.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

@chenmingwei23
chenmingwei23 requested review from a team and hoang-phan98 September 16, 2026 04:03
@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: checking Automated validation is still running labels Sep 16, 2026
@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5, fork) — 🟡 CONCERNS

Design-level review of 372a0ca933997d9baafdacc6ee590297295dd626 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: CONCERNS

Child-closer repair rests on the module's most fragile cross-thread protocol to write a closer whose absence readers must already tolerate — weigh whether it earns its cost.

Watch

The subagent/failed outcome:"unknown" repair needs a gateway-registered liveness probe, per-entry _claimed_sessions accounting on every write, and a pin held across the done-flip gap — yet session-types.md still tells readers "a spawn with no close at all means the parent died... and no liveness predicate was available," so readers carry the unclosed-opener case regardless; the closer reduces its frequency without removing it, while two safety invariants ("record before info.done flips", "release pin after handover") are enforceable only by inspect.getsource order assertions that a refactor can silently invalidate between the pinned statements.
Clears when: a maintainer affirms the closer is worth the protocol, or child-closing is dropped and the reader hint becomes the single rule.

The PR corrects crew-log-core.md's frozen approval shape doc-to-code (id → approval_id, reason?/by?/cause? added) — the author flags this themselves; since renames are forbidden once the format launches, a human should confirm the code's names are the intended contract now, not after CONTRACT_VERSION unfreezes matter.
Clears when: a maintainer confirms approval_id and the optional attribution fields are the launch vocabulary.

Suggestions

Items 7 and 9's residual (unattributed spend when the owning session is torn down) recurs by construction; if a third instance appears, that is the signal to pin the id at scheduling time rather than accept another named absence.

[DESIGN-REVIEWED] 372a0ca

@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5, fork) — 🟡 CONCERNS

Premise-level review of 372a0ca933997d9baafdacc6ee590297295dd626 via the fork AI-review pipeline — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: CONCERNS

Background-spend logging is a point patch — the identical per-session summary call in handlers/sessions.py stays invisible — and lost_child_origins() has zero consumers.

Not justified as shipped

  • Item 4 — point patch: the stated harm is "spend appeared in the usage store with nothing in the session it was charged to", yet of 12 run_bg_oneliner( sites (grepped, src/), the PR wires 3; dashboard/handlers/sessions.py:1242 — a one-session transcript summary whose own docstring says it "Mirrors dashboard.chat_title._generate_title_via_kiro" — is the already-emitted summary kind, left unwired. 1 counted unfixed sibling.
    Clears when: that call passes ledger_kind="summary" with the owning key, or the description names it deferred.
  • Item 8 — zero consumers: grep lost_child_origins in src/ finds only its definition; siblings dropped_writes()/overflow_writes() also have zero production callers, so its only support is symmetry with them (inherited). The counter and the one-shot warning are the mechanism.
    Subtraction: delete the lost_child_origins() accessor; keep _lost_child_origins and the warning.
    Clears when: a production reader exists, or the accessor is removed.

What this change ships

Inventory (10 items) — 8 justified

Intent: record in the session ledger the approvals, plans, background spend and subagent lifecycle the gateway already performs — an ADDITION (flag-off, log-only), under RFC rfc-append-only-ledger.md (in-progress on base).

  1. A pending approval and its resolution now appear in the session's log — justified
  2. Host-made declines (timeout, no-budget, cancel, Stop) are attributed by: host; human answers name nobody — justified
  3. The agent's restated task list is recorded, clipped by count and measured bytes — justified
  4. Title/summary/consolidation spend lands in the owning session's log, owner pinned pre-call — point patch (1 counted unfixed sibling)
  5. A child's spawn, steers and three-way outcome are recorded in the parent's log, keyed to the asking turn — justified
  6. New key→session-id resolver crew_log/resolve.py (3 counted consumers) — justified
  7. Crash repair also closes unmatched approvals, and child openers only when the live registry says the child is gone — justified
  8. lost_child_origins() accessor for dropped child pins — zero consumers
  9. Docs flip eight types to live and replace "deferred" with per-type reasons, same commit as the code — justified
  10. test_orphaned_approval_card.py reformatted off the black baseline — rides along

[FIRST-PRINCIPLES-REVIEWED] 372a0ca

@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review (fork) — 🔴 changes requested (blocking)

Reviewed 372a0ca933997d9baafdacc6ee590297295dd626 via the fork AI-review pipeline; updated in place on each push.

1 of 2 blocking finding(s) are security-class and were withheld from adjudication, so the blocking verdict stands.

BLOCKING -- src/kiro_crew/llm_helpers.py:1934 -- Idle-expiry consolidation resolves ownership after session removal
_crew_log_owner = _background_crew_log_owner(sessions, crew_log_session_key, ledger_kind)
idle expiry -> schedules consolidation -> reset pops provider before task runs -> billed consolidation has no ledger entry
Anchor: residual/crash-data-loss-corruption
Fix: Resolve and pin the ACP session ID before scheduling consolidation, then pass it through.

BLOCKING -- src/kiro_crew/crew_log/emit.py:3530 -- Origin cap silently evicts accepted queued children
_MAX_CHILD_ORIGINS = 2048
2049 accepted queued children -> queued IDs are absent from mgr.running -> oldest origin is discarded as finished -> later entry loses its original turn or is attributed to a successor session
Anchor: a-bound-bounds-every-field-it-retains
Fix: Persist origins with accepted task rows or share their capacity bound, treat queued children as live, and count every forced eviction.

[BLOCK-MERGE] 372a0ca
[GPT-REVIEWED] 372a0ca

Adjudication (Opus 4.8) — is blocking on each finding proportionate?

I have what I need. Both findings verified against the diff (changed lines) and base tree.

F2 — emit.py:3530, _MAX_CHILD_ORIGINS = 2048. Harm rung LOW. Conditions confirmed: 2049 pins held at once (_reap_child_origin only fires at len(_child_origin) > _MAX_CHILD_ORIGINS, patch:1002/1053), and the reap's oldest window is filled by queued-not-started children the probe reports as not-running so they drop uncounted (patch:1049-1057). Recovery/consequence: an evicted origin makes open_child_origin/child_origin return ("",0), and every emit caller bails on empty sid — run.py spawn path returns without writing (patch:2700) and the terminal report writes no closer (patch:2942) — so the effect is a missing entry in a default-off diagnostic ledger, within one user's own log, never a cross-user or wrong-session write in these paths, no corruption, no user-data loss. The real fix (couple the pin map to admission-queue capacity, or change the manager's run-map to report queued children as live, plus count these drops) is permanent cross-module coordination serving only a pathological 2048-concurrent-pin state — a maintenance load clearly exceeding a rare, self-limiting diagnostic omission.

F1 (fenced) — llm_helpers.py:1934. The condition (idle-expiry consolidation resolving its owner after the ACP session was torn down) is an ordinary path, not an extreme/contradictory one, so no rarity argument can be completed; a FLAG's evidence bar is unmet. When torn on the unbounded class, UPHOLD-FENCED.

[ADJUDICATION] 372a0ca total=1 uphold=0 downgrade=1
DOWNGRADE F2 src/kiro_crew/crew_log/emit.py:3530 reason=disproportionate-remedy
[GPT-ADJUDICATED] 372a0ca
[ADJUDICATION-FENCED] 372a0ca fenced=1 flagged=0
UPHOLD-FENCED F1 src/kiro_crew/llm_helpers.py:1934 -- Idle-expiry consolidation is a common path, not an extreme condition combination, so the rarity argument a FLAG requires cannot be made; the missing ledger entry keeps blocking.
[GPT-ADJUDICATED-FENCED] 372a0ca

@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Opus 4.8 Review (fork) — ✅ no blocking findings

Reviewed 372a0ca933997d9baafdacc6ee590297295dd626 via the fork AI-review pipeline; updated in place on each push.

Review details

I've traced the one candidate to ground. The candidate flags open_child_origin's docstring ("Idempotent, so a second call cannot produce a second opener") as contradicting code that re-returns the pinned pair on every call rather than gating on _opened.

Falsification: the only route to open_child_origin is _record_crew_log_spawn_started → called solely from _log_spawned_impl (pump.py), which itself is reached once per accepted spawn — the yolo / auto / trusted / hook branches in gate.py and the post-approval site in pump.py are mutually exclusive, and the queued-then-drained re-entry reaches the run-starting branch only on the drain pass. The pin is released by forget_child_origin at the exclusive one-shot terminal, agent ids are unique, and reset_caches() clears _child_origin on resume — so no live pin is ever handed to a second open_child_origin call. The candidate's own confidence line concedes it "could not find a production path that calls _log_spawned twice for one info.id." Requirement (a) (a concrete input that occurs in practice) and (b) (a real call path to a double-call) both resolve to "if a caller were to," so it fails the Step 1 bar and is dropped.

No findings.

[OPUS-REVIEWED] 372a0ca

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 16, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 16, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 16, 2026
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 16, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 16, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 16, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 17, 2026
@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Owner disposition: Stop-triggered rejection recorded as a human decision

The review lane's finding on chat_runner.py is correct, and it is the more serious of the
residuals on this PR
. Recording it here rather than fixing it under the wire, with the fix named
so a maintainer can call for it.

The mechanism, verified in code. _reject_pending_approvals (chat_handlers.py) resolves each
pending approval with fut.set_result("rejected") -- an ordinary resolution, not a cancellation. On
the dashboard Stop path (_unblock_pending_waits -> _reject_pending_approvals) the runner's await
therefore returns outcome="rejected" and raises nothing, so _host_cancelled stays False (only
the except asyncio.CancelledError arm sets it) and _host_deny_cause stays empty. At the emit both
guards are false, so the closer writes by="", and this schema defines an absent by as a person's
answer. The lane is right that this is the PRIMARY unblock path, cancellation being the fallback, so
the misattribution is common rather than rare, and the file is append-only.

Why it is not fixed in this PR. Every existing host deny cause -- timeout, no-budget,
undeliverable -- is detected by the awaiting code itself, inside the runner, and is therefore a local
variable. Stop is detected OUTSIDE the runner, so carrying its provenance in needs a new per-approval
marker: an entry added to _ChatSlot.__slots__ and its constructor in state.py, a write where the
Stop path resolves each future in chat_handlers.py, and a read in the runner's finally. That is
three files, two of them otherwise untouched here, adding state to the approval and slot subsystem so
that a default-off log can attribute better. It is the same class of change this PR already declined
once: restructuring the approval control flow for a log-only feature.

The fix, so it is not re-derived. Add a per-approval-id set on the slot, write the id into it
where _reject_pending_approvals resolves the future -- the Stop provenance is already known there,
since that function logs it to SEL as rejected_on_stop -- and have the runner's emit read and
discard the id, treating a hit exactly as _host_cancelled is treated today. Per-id rather than a
slot-wide flag, so a later human rejection on the same slot cannot inherit the host attribution.

Residual risk, stated plainly. A user pressing Stop while a tool approval is pending has that
rejection recorded as though a person answered it. It is permanent, because nothing rewrites this
log, and it is silent, because the entry is well-formed. It does not affect any control decision --
the entry is a log record only, and the approval itself was genuinely rejected either way -- so what
is lost is the ability to tell a host stop from a human refusal when reading the history back.

Accepted by the owner (Raymond) as a known limitation for this PR. The lane's red stays up rather
than being argued away.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Owner disposition: idle-expiry consolidation spend is not attributed

The review lane's finding on history_consolidation.py is real, and it is the SAME CLASS as the
cold-title case already recorded in this PR's ## Other suggestions. Recording it rather than
fixing it, with the reasoning and the fix named.

The mechanism. A memory consolidation scheduled by idle expiry runs after the slot's teardown
has begun. The call is charged by session KEY, and the resolver answers only what is true at the
moment it is asked: once the reset has removed the provider there is no ACP session id for that key,
so the resolver returns empty and the emitter's empty-id no-op drops the entry. The tokens are
billed and this log does not say so.

Why it is not fixed here. The lane's remedy -- pin the provider session id before scheduling and
pass it through consolidation -- is correct in principle for this path, because a session being
expired is exactly the one that should be charged. Carrying it there means threading a resolved id
through the consolidation call path as a new parameter, in a subsystem this PR otherwise only adds
emit calls to. This PR has already reached its agreed change budget, and the owner's standing
instruction for a finding of this class -- an attribution omission rather than a crash or a security
hole -- is to record it and leave the lane's verdict standing.

Why an omission and not a wrong entry. The alternative to omitting is to resolve the key later
and write whatever session is found then. An earlier round of this same lane found that defect on the
background path and the fix was to resolve BEFORE the first suspension point, because a reset,
switch or compaction inside that window gives the successor a new session id and a late lookup files
the spend against a session that never incurred it. An absence a reader can notice is better than a
confident wrong attribution in a file nothing rewrites, so the emitter drops rather than guesses.

Residual risk, stated plainly. Memory consolidation triggered by idle expiry is billed but not
recorded in the session ledger. It is bounded to that trigger -- a consolidation on a live session
resolves normally -- it changes no control decision, and the spend remains visible in usage
accounting. What is lost is this log's ability to account for that particular call.

Accepted by the owner (Raymond) as a known limitation for this PR, alongside the cold-title case it
shares a cause with. The lane's red stays up rather than being argued away.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

/ai-review override gpt 4ad2154: The sole blocking finding (idle-expiry consolidation spend on history_consolidation.py resolving to no ACP session id after teardown) is a reachable but deliberately-accepted limitation documented in the PR body's Other suggestions items 2 and 7 -- the prescribed remedy (resolve the session id later, after teardown) reopens the exact wrong-attribution defect an earlier round of this same lane made the author fix, trading a visible absence for a confident wrong attribution in an append-only file that nothing rewrites, which is strictly worse for every reader.

@github-actions

Copy link
Copy Markdown
Contributor

AI-review override not recorded: keep the reason to 500 characters or fewer.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

/ai-review override gpt 4ad2154: The one blocking finding (idle-expiry consolidation spend unattributed in history_consolidation.py) is a deliberately-accepted limitation documented in the PR body Other suggestions 2 and 7: the prescribed fix (resolve the session id after teardown) reopens the wrong-attribution defect an earlier round of this same lane made the author fix, trading a visible absence for a confident wrong attribution in an append-only file nothing rewrites -- strictly worse for readers.

@github-actions

Copy link
Copy Markdown
Contributor

Human judgment recorded

@chenmingwei23 marked the gpt AI finding as false positive, not applicable, or explicitly accepted for 4ad215445df2247d61eefcb7c418b3d0fc7905ee.

The one blocking finding (idle-expiry consolidation spend unattributed in history_consolidation.py) is a deliberately-accepted limitation documented in the PR body Other suggestions 2 and 7: the prescribed fix (resolve the session id after teardown) reopens the wrong-attribution defect an earlier round of this same lane made the author fix, trading a visible absence for a confident wrong attribution in an append-only file nothing rewrites -- strictly worse for readers.

This decision applies only to this commit. A new push requires a new judgment.

@github-actions

Copy link
Copy Markdown
Contributor

Human judgment recorded, but the following reviewer lane(s) could not be re-run automatically: GPT 5.6. Re-run the lane's latest workflow run for 4ad215445df2247d61eefcb7c418b3d0fc7905ee manually from the Actions tab.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Owner disposition: a claim-unavailable spawn records no asking turn

The review lane's finding on admission/gate.py:1038 is real. Recording it rather than fixing it,
with the mechanism traced to the lines that set the value and one correction to a comment of my own
that the finding exposes.

The mechanism. A spawn raised during a live turn can find no admission claim available. That exit
returns a queued SubagentInfo early, and it does not pin the child's origin on the way out. The pump
later drains the queued member and re-enters spawn with _from_queue=True, and the accepted exit
sources the turn as 0 because a drained member's asking turn is treated as unobserved. Nothing
refuses that pin, so 0 is what the child carries.

What it costs, and what it does not. on_subagent_spawned writes turn only when it is truthy,
so a 0 is OMITTED rather than written as turn zero. The entry still lands complete -- agent_id, the
agent, the model and the scope are all present -- the owning session resolves correctly, and nothing
is misfiled. A missing turn is also the crew log's own documented normal case: cron, hook,
slash-command and durable-queue replay spawns legitimately have none, readers are told to group
children by agent_id rather than by turn, and nothing downstream treats the field as load-bearing.
So the loss is one optional field on one entry, in a log that is off unless KIROCREW_SESSION_LEDGER
is set, and it is indistinguishable from the turn-less spawns a reader already expects.

The lane's own adjudicator reached the same reading and flagged it rather than upholding it: "the
claim-unavailable retry pins turn=0, but on_subagent_spawned omits a falsy turn rather than
fabricating one, so the only effect is one design-tolerated optional field absent on an
otherwise-complete entry in a default-off log ... hence bounded and acceptable rather than the
unbounded corruption the anchor names."

A correction to my own comment. The comment beside that turn = 0 says a drained member's origin
"is already pinned and the pin refuses to move" in this process, so the pass changes nothing, and
that it matters only where a row was replayed from the durable queue after a restart. That is true of
every path that pins before queueing, and FALSE of this one: the claim-unavailable exit pins nothing,
so the drain finds an empty map and pins 0 fresh, in a process that did know the asking turn. The
comment describes the case it was written for and not this one. Naming it here rather than leaving a
premise in the tree that the code does not honour.

Why the fix is not in this PR. The remedy is small and correct -- pin the dispatch before
returning the claim-unavailable queued result, so the asking turn is captured while it is still in
hand. It is also a new write on an admission exit this PR otherwise only reads, and this PR has
reached its agreed change budget with the lane's other findings already dispositioned. It belongs to
the next PR in this lineage, where the emit sites are being extended anyway, and it is recorded here
so that PR inherits a stated defect rather than rediscovering it.

Residual, stated plainly. A subagent spawned during a live turn that waits for an admission claim
records no turn on its subagent/spawned entry. Bounded to that path, one optional field, no
misattribution, no lost entry, and only when the crew log is switched on.

The finding sits behind the security fence, which keeps it blocking whatever the adjudication says,
and this lane deliberately carries no override command -- so nothing here is an attempt to clear it.
The red stays up. Clearing it is a repository writer's call, recorded by them after their own
verification, and the merge is theirs to make.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Superseded: F1 is fixed on c0315e960d350c0fcfe2747e4101bac8fb4e45cc.

My earlier disposition placed this in a follow-up PR. That is withdrawn: the fix is
one place and it is here, exactly as the lane prescribed -- the claim-unavailable exit
pins the dispatch before it returns the queued handle.

gate.py now builds the queued SubagentInfo, calls _record_ledger_dispatch(info, from_queue=_from_queue, asked=_ledger_asked), and returns it. This makes it symmetric
with the other queued exit in the same method, which has always pinned. The pump's
retry re-enters under _from_queue=True, where the asking turn cannot be read, and
remember_child_origin refuses to move the pin it finds -- so the turn recorded is the
one that actually asked, rather than the 0 a pin-less pass left behind.

It also retires the false premise I reported in the disposition above. The comment in
_record_ledger_dispatch says a from_queue pass finds its origin already pinned in
this process. That was true of every queued path except this one; it is now true of
this one too.

Verification: 1046 focused tests pass; two mutations killed (drop the pin -- the new
test fails; pin as a drained pass so the live turn is discarded -- it fails too), each
anchor checked for uniqueness first; eight local gates exit 0, including the
repository's own baselined black check.

The crew log stays default-off behind KIROCREW_SESSION_LEDGER.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Owner disposition -- F1 on cd7685ddde893fdd0c1d43fa52b92811e67474f5 (terminal.py:70, normal completions discard the measured duration): the premise does not hold, and the red is left standing.

The finding says _claim_finalize emits the terminal entry before run.py assigns
info.elapsed, so a normal completion records ms as zero. I traced it to the lines
that set the value rather than reading the claim:

run.py:494    if self._manager._claim_finalize(info):
run.py:495        info.elapsed = time.time() - info.started
run.py:496        self._manager._record_cost(info)
run.py:497        report_task = self._manager._spawn_terminal_report(

_claim_finalize returns a bool and writes no entry. The assignment is the next
statement after it, and no await sits between the assignment and the report, so the
duration is populated before _record_ledger_terminal reads it at terminal.py:70.
The adjudicator traced the same path independently and returned FLAG for this reason,
listing the other three report paths: the reap path and the recovery-failure path each
assign info.elapsed before their own claim, and the queued-stop path leaves it unset
on a run that genuinely never started -- where the write also no-ops, because no child
origin was ever recorded, so forget_child_origin returns an empty session id.

The prescribed fix -- derive the duration from time.time() - info.started when
info.elapsed is unset -- would replace a real measurement with a recomputation on the
only path where the current value is already correct, and on the queued-stop path it
would invent a duration for a run that never executed.

The fence keeps this blocking whatever the adjudication says, and the fork lane ignores
/ai-review override, so clearing it needs a repository writer who has verified the
rationale above. No code change is warranted for it.

The crew log stays default-off behind KIROCREW_SESSION_LEDGER.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Rebased onto 2627b0407c after #11310 landed. Eight spec hunks collided; here is each one and how it was resolved.

#11310 retired ten names from the session vocabulary (session/seeded, message/steered,
tool/searched, tool/loaded, skill/searched, skill/loaded, summary/written,
remote/placed, remote/lost, and digest as a background/completed.kind). This branch
was written when those were specified-but-unwritten, so the prose that described them as
pending collided with the prose that removed them. The code applied clean; only the two
specs conflicted.

docs/system-specs/modules/ledger-core.md, four hunks:

  1. The message/steered schema row -- took the removal. The type no longer exists.
  2. The approval rows -- kept this branch's versions (approval/requested with
    approval_id/tool?/reason?, approval/decided with approval_id/decision/by?/cause?,
    both Emitter yes), and took the removal of the four tool/* and skill/* rows.
  3. The task-list row -- kept this branch's plan/updated (state: done | open, total?,
    Emitter yes), and took the removal of summary/written, remote/placed, remote/lost.
  4. The background and subagent rows -- kept this branch's versions, which is what changed:
    they now record the fields the sites can actually observe and read Emitter yes.

docs/system-specs/modules/session-ledger-emitter.md, four hunks:

  1. The steer section heading -- took the incoming wording ("A steer has no entry of its own"),
    which is accurate now that the type is gone rather than merely unwritten.
  2. The paragraph explaining why -- took the incoming wording for the same reason: the type is
    absent from the vocabulary, not sitting in it waiting for a site.
  3. The resolver section's opening -- kept this branch's, because this branch is what closes
    that gap; the incoming text still described the families as unemitted.
  4. The "Still not emitted" table -- removed. Its premise no longer holds: everything in it was
    either retired by chore(ledger): trim unwritten types and retire kiro_crew.events #11310 or is emitted by this branch. The section is now "Removed types,
    and why each is gone", carrying the incoming statement of what went and why, the note that
    any of them may return when a real source exists, one sentence recording that the four
    resolver-shaped families are written here, and the incoming compaction paragraph.

One test change came out of the rebase rather than the conflict. #11310 added
test_steer_requeue.py::TestSteerConsumedClears::test_no_site_writes_a_steer_entry, which
asserts the emitter exposes no attribute whose name contains "steer". Its reasoning is about
the MESSAGE steer: the interrupting text and the consumption echo are seen by different
coroutines, so either site alone writes a seq that contradicts causality. subagent/steered
does not have that problem -- the site accepting the steer holds the child's id and the mode at
that moment -- so the scan now excludes the subagent family and the docstring says why.

Verification on the rebased tree: 734 focused tests over the files #11310 also touched
(test_ledger_core.py, test_session_ledger_emit.py) plus test_session_control.py,
test_member_session_control.py, test_steer_requeue.py and this branch's own suites; 1233
more across the ledger and session suites before the last rebase step; nine mutations killed
across four harnesses; the eight local gates exit 0, including the repository's own baselined
black check. The patch is byte-identical across both rebase steps (3517 changed lines).

The crew log stays default-off behind KIROCREW_SESSION_LEDGER.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Owner disposition -- F1 on 0672e81952e8e70fe273a50394387e11f26739ff (session_ledger_emit.py:3494, session-wide debt suppresses orphan-child repair): the mechanism is real, the permanence in its description is not, and the red is left standing.

What is true: the debt check is keyed by session, not by agent_id, so any one entry this
process still owes for a session makes the probe answer "still running" for every child of
that session, and a genuinely dangling subagent/spawned is not closed by THAT repair.

What is not true is "never reconsidered". The repair reads the FILE: _close_interrupted_tail
folds every record in the ledger and builds its children map from the openers it finds
unmatched there (ledger/store.py:2316 onward), so an opener left standing is still unmatched
the next time that session is opened with repair=True, and it is asked about again. The
residual is therefore a DEFERRAL to the next repair on that session, not a permanent hole.

That deferral is the direction this design chose on purpose, and the same function's docstring
says why: a child outlives the turn that asked for it, so "the writer is gone" does not settle
it, and closing it from here would put two outcomes for one agent_id in a file nothing
rewrites. A reader that sees an open child treats it as unknown and is behind; a synthesised
unknown ahead of the real terminal cannot be corrected.

The prescribed fix -- suppress only when this child's own terminal is owed -- needs a per-agent
debt index in the writer: the pending jobs are opaque closures whose only description is a
what string, so answering per agent_id means registering it at submit time and releasing it
on every settle path (written, dropped-with-marker, retained), plus the claimed-batch bookkeeping
and the cache reset. That is a fourth round of structure on this one mechanism, in a
default-off log, to convert a deferral into an immediate close.

The fence keeps this blocking whatever the adjudication says, and the fork lane ignores
/ai-review override, so clearing it needs a repository writer who has verified the above. The
earlier dispositions on this PR's other fenced findings are in the comments above; this one is
new and is not the info.elapsed premise.

The crew log stays default-off behind KIROCREW_SESSION_LEDGER.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Red classification for 0672e81952e8e70fe273a50394387e11f26739ff. Two reds, neither of them a
defect in this branch.

macOS Tests / Backend Tests (macOS) (3) -- MAIN-OWNED, tracked as #11618. The failures are the
test/test_xdist_host_budget.py worker-budget family, added by #10840 and failing deterministically
on the macOS runners because the reservation math and the tests disagree about per-worker memory.
The file is absent from this branch's diff, and the same family fails on #11470's head, which
carries an unrelated change. Nothing here can fix it and nothing here should try.

GPT 5.6 Review -- one fenced finding, dispositioned in the comment above: the child-repair debt
check is keyed by session rather than by agent_id, which defers a dangling child's closure to the
next repair on that session rather than losing it, since the repair rebuilds its unmatched-opener
set from the file each time. The fence keeps it blocking regardless of adjudication and the fork
lane ignores /ai-review override, so clearing it needs a repository writer who has verified that
reasoning.

Earlier reds on the superseded heads are gone rather than merely quiet: the four
test_session_control.py failures and the two test_member_session_control.py ones cleared when
#11593 entered this branch's base, and the two non-UTF-8 path OSError failures cleared with it.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Rebased onto the crew-log rename (#11549). New head 0ea23482ff, same single commit, 31 files.

Four conflicts, and the rule for all of them was the same: keep what this branch changes, in the
vocabulary main now uses.

src/kiro_crew/crew_log/store.py, five hunks. Main reworded the prose ("ledger" to "crew log") in
the same lines this branch extends with the child_gone plumbing. Kept both signatures with the
predicate, and main's nouns: Ledger.open and repair_interrupted_turn still take child_gone,
the _OpenTail docstring still explains why calls and approvals are turn-scoped while children are
file-scoped, and the log line reads "closed an interrupted tail in session log".

test/test_steer_requeue.py, one hunk. Main rewrote this guard to scan crew_log_emit after
#11310 deleted on_message_steered; this branch had narrowed the scan to exclude the subagent
family. Kept the narrowing on main's module alias, with the reason in the docstring: the message
steer has two observers and no orderable seq, while subagent/steered is written where the steer is
accepted, holding the child's id and the mode at that moment.

docs/system-specs/modules/crew-log-core.md and crew-log-emitter.md, three hunks. Took this
branch's content -- a subagent is not a session with its own log yet, so subagent/spawned carries
no ref and the child's spend is absent rather than zeroed; the repair section's turn-scoped versus
file-scoped closers and what backs the child predicate -- and applied main's wording throughout.

The two new files landed in the new layout: src/kiro_crew/crew_log/resolve.py and
test/test_crew_log_resolver.py. Every identifier this branch introduces now reads crew-log:
_record_crew_log_dispatch, _record_crew_log_spawn_started, _record_crew_log_steer,
_record_crew_log_terminal, _crew_log_asked, crew_log_session_key,
_background_crew_log_owner, _record_background_crew_log, _crew_log_owner,
_crew_log_decision, _crew_log_followup_asked, _pin_followup_crew_log_origin, plus the four
test names that pinned them. The flag is KIROCREW_CREW_LOG. The commit subject and body, and this
PR's description, use the same vocabulary; kiro_crew/session_ledger.py is the unrelated work
ledger and keeps its name, so its call sites are untouched.

Verification after the rename: 802 tests over the crew-log suites plus the steer guard, the approval
card and startup; 1003 more over the history, title, admission, runloop, spawn and session-control
suites; nine mutations killed across four harnesses re-pointed at the new paths, each anchor checked
for uniqueness first; every changed Python file byte-compiled; the eight local gates exit 0,
including the repository's own baselined black check. Three imports that a blanket rename had
mangled were caught by the compile sweep, not by the tests, which is why it runs.

The crew log stays default-off behind KIROCREW_CREW_LOG.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Red classification for a95ab2d61026c1a712b030f218c84c84dd583974: 74 green, and none of the reds is a defect in this branch.

Three main-owned test groups, each reproduced on pristine origin/main and each with its own
tracking issue. All three files are absent from this branch's diff.

Red Failing tests Owner
POSIX 1, Windows 1, macOS 1 test_acp_launch_goldens.py #11635
POSIX 2, Windows 2, macOS 1 test_backend_cards.py::test_every_capability_set_is_classified_by_the_card #11634
macOS 3 test_xdist_host_budget.py #11618

Coverage Gate is an aggregate of those, not a coverage regression. Its own log says so:
coverage-combine=skipped backend-test=failure then backend-test=failure -- failing closed.
It clears when the shards above do.

GPT 5.6 Review is red with no finding on this head. Its check-run output reads "review
incomplete", and the finalize step is fail-closed by construction: it publishes failure unless the
review output carries [GPT-REVIEWED] <head>. The sticky comment above still describes the previous
head 0ea23482ff -- it was last edited before this head existed. Both findings it carries are
already addressed here: the terminal-versus-repair ordering is fixed in
subagent_manager/terminal.py (the entry is handed to the writer before info.done flips), and the
llm_helpers.py comment that claimed the log and the bill "cannot disagree" now states what is
true -- they share the billing gate, not persistence.

The other review lanes on this head: Opus 4.8, Code Review and Security Scope green; Design Review
and First Principles neutral, which is the fork-lane condition rather than a verdict.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Owner disposition for 38ec0c1073, GPT F1 (test/test_crew_log_resolver.py:31, fenced, FLAGged): the red stays, and the fixture keeps the pattern it copies.

The finding's prescribed fix is a session-scoped data home for these tests. That is not a local change to one fixture; it is a different isolation contract for the suite, and it costs the property the current one buys.

Why a shared home breaks these tests. All 44 tests in the file read one path, ledger_path("session", SESSION) with a module-level SESSION constant, and assert on the entries found there -- _entries() at line 42 returns that file's lines, and the per-type helper filters them. With one home for the whole session, test N reads the entries test N-1 wrote for the same session id. The assertions that pin an entry's absence (assert not _of("plan/updated")) and the ones that unpack exactly one row ((plan,) = _of("plan/updated")) would then depend on execution order. Per-test isolation is what makes those assertions mean anything.

What the residue path actually requires. The write reaches the real home only if it lands after monkeypatch reverts KIROCREW_HOME, because the path is resolved at write time (_write._job -> _handle -> Ledger.open -> ledger_path). Two things stand between the two:

  • Buffering happens only on the event-loop path. _submit's own docstring says it: "With no event loop running the write happens inline." 42 of the 44 tests here are synchronous, so their writes complete in the calling thread while the env still points at tmp_path. Two are @pytest.mark.asyncio (lines 624, 671).
  • The teardown barrier runs before the env is restored. _isolated_home calls emit.drain_for_shutdown(timeout=2.0) then emit.reset_caches() after its yield; monkeypatch is a fixture this one depends on, so its undo runs after this teardown, not before. Residue therefore needs the drain to expire -- a filesystem still wedged after two seconds.

Why the shape is not this PR's to change. The fixture is the same barrier test/test_crew_log_emit.py:44-70 established, and that file's own comment (lines 66-68) names drain_for_shutdown + reset_caches as the deliberate device: stop the writer before pytest removes tmp_path, then drop the handles that point into it. Changing it here would leave two isolation shapes in one suite while removing the per-test guarantee from the newer half. If the residual is judged unacceptable, it is unacceptable for the whole crew-log suite, and the fix belongs in one change to the shared pattern rather than in this PR's half of it.

The fence keeps this blocking regardless, and this lane's comment carries no override command. A repository writer owns that call; the reasoning above is the record for it.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

New red on 38ec0c1073: Coverage Gate. Main-side, and this PR contains none of the file it names.

The failing step is Check per-file coverage, backend (floor 80%), and its own output names one file:

1 file(s) below 80% and not baselined -- add tests, do not extend the baseline:
     77.2%  src/kiro_crew/session_scope_reap.py  (267/346)

Evidence that it is not this PR's:

  • git diff --name-only origin/main...HEAD does not list src/kiro_crew/session_scope_reap.py, and git diff origin/main...HEAD on that path and on test/test_session_scope_reap.py is empty. Both files are byte-identical to origin/main here.
  • The module arrived on main in 263075d4bb fix(session): reap abandoned agent cgroup scopes on cleanup ticks (2026-09-17), which is an ancestor of this branch's base 9628c8c516.
  • .github/coverage-baselines/backend.txt carries no entry for it.
  • Running its own test against it in this worktree reproduces the number CI reports: src/kiro_crew/session_scope_reap.py 346 82 140 14 77%. Same file, same figure, with zero lines of it changed here.

Why it surfaced now rather than on the commit that created it: the gate reads backend-cov/coverage.xml produced by the PR test job, so a push to main does not run it -- 9628c8c516 has no Coverage Gate check run at all. The debt therefore landed on main unnoticed and reds every PR built on top of it.

Not fixed here: adding tests for a cgroup-reaping module is unrelated to a crew-log resolver, and the gate's own message forbids the alternative ("do not extend the baseline"). It needs a main-side change that raises that file's coverage, tracked separately.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Owner disposition -- GPT 5.6 on 965e2f137c924706d17c7e7854a828a1d0060013

Both findings are left standing. F1 is already dispositioned in the body; F2 is new to the board and is declined on its merits, traced below. Posted as a comment rather than a body edit because 14 checks are still in flight on this head and an edited event cancels them.

F1 -- history_consolidation.py:2375, idle consolidation drops its billed entry. This is body item 9, at a new line number after the rebase. Same mechanism (a consolidation scheduled by idle expiry runs after the slot's teardown, so the resolver has no ACP session id for the key and the emitter's empty-id no-op drops the entry), same declined remedy, same stated residual. The lane's fix, pin the id before scheduling and thread it through the consolidation call path, is right in principle and is refused only on change budget, which item 9 says in those words. Resolving later instead stays refused for the reason item 7 gives: an earlier round of this same lane made me hoist resolution above the first suspension point, because a reset or compaction inside that window gives the successor a new session id and a late lookup files the spend against a session that never incurred it.

F2 -- continuation.py:103, merged follow-ups name only the last asking turn. The mechanism is real and I traced it rather than taking the lane's word: queue_followup appends each ask to the same run's pending_followups (line 798), pins (sid, turn) on that one info (line 803, the cited setattr), the watcher joins the queued messages into one task (line 937) and reads the pin back once (line 949). Two asks from different turns therefore produce one subagent/spawned naming the later turn.

It is declined because the prescribed fix has two halves and neither is a mechanical move.

Per-queued-message origin state cannot change what this entry says. One merged continuation is one dispatch and subagent/spawned carries one turn, so richer state upstream still has to collapse to a single field, unless that field becomes list-valued, which is a change to the frozen vocabulary rather than to this code.

Omitting turn when a merged continuation spans turns would remove information rather than add it. Today a reader learns the most recent ask; after the change they learn nothing about any ask. The turn that is dropped is not recovered elsewhere by that change, whereas the turn that is kept is real.

What makes the residual bounded is the entry the lane's own adjudication names: _record_crew_log_steer(info, "follow_up") runs at line 802, one entry per ask, at the turn that made it, BEFORE the pin that gets overwritten. So turn 2's causation is in the file, in turn 2's bracket, keyed by the same agent_id the reference says a reader groups a child's entries by. What the merged spawn loses is the ability to read that causation off the spawn entry alone.

Residual, stated plainly: when several follow-ups from different turns merge into one continuation, that continuation's subagent/spawned names the last asking turn and not the earlier ones. It changes no control decision, the log is default-off, and each ask remains individually recorded at its own turn.

One imprecision in my own tree, recorded rather than left silent: the comment at the _crew_log_asked call site reads "the turn that ASKED for this follow-up", which for a merged continuation is the turn that asked LAST. That is a wording fix, not a behaviour one, and it is not worth restarting a 70-lane board for on its own; it goes with the next push this branch takes for another reason.

Both findings are security-class fenced, so this lane consumes no override marker and the red stands until a repository writer clears it after verifying the rationale themselves.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

/ai-review override gpt 965e2f1: Recoverable, the third test, verified in code on this head rather than taken from the machine rationale. F1: persist_token_record_async writes the spend on its own path inside the same usage_has_billing gate (llm_helpers.py:1509-1525), so a missing mirror entry never loses a billing record. F2: _record_crew_log_steer(info, "follow_up") at continuation.py:802 records each ask at the turn that made it, so a merged spawn naming the last turn loses no causation.

@github-actions

Copy link
Copy Markdown
Contributor

Human judgment recorded

@chenmingwei23 marked the gpt AI finding as false positive, not applicable, or explicitly accepted for 965e2f137c924706d17c7e7854a828a1d0060013.

Recoverable, the third test, verified in code on this head rather than taken from the machine rationale. F1: persist_token_record_async writes the spend on its own path inside the same usage_has_billing gate (llm_helpers.py:1509-1525), so a missing mirror entry never loses a billing record. F2: _record_crew_log_steer(info, "follow_up") at continuation.py:802 records each ask at the turn that made it, so a merged spawn naming the last turn loses no causation.

This decision applies only to this commit. A new push requires a new judgment.

@github-actions

Copy link
Copy Markdown
Contributor

Human judgment recorded, but the following reviewer lane(s) could not be re-run automatically: GPT 5.6. Re-run the lane's latest workflow run for 965e2f137c924706d17c7e7854a828a1d0060013 manually from the Actions tab.

…t that unlocks

The emitter keys every entry by an ACP session id. Several sites that produce
facts about a session hold only a key -- a background model call charged to it,
a subagent it spawned, its own task list -- so eight of the schema's families
had no emitter. `crew_log.resolve` closes that gap with two synchronous
reads: the slot's live ACP client during a turn, and the session registry
otherwise. It never consults the persisted session map, whose `get` prunes a
stale entry, and it answers "unknown" rather than guessing.

The resolver answers a question about the PRESENT -- which unit a slot's work is
landing in now -- because a reset, an agent or model switch, a compaction and a
provider swap all tear the ACP session down and the successor cold-starts a new
id. So anything that outlives the moment it asked must carry the answer rather
than ask again, and both new emit paths do:

* a background call resolves its owner BEFORE the model call and writes to that
  pin in the teardown. Resolving at teardown would hand the spend to a successor
  session that never incurred it, silently, in a file nothing rewrites. What that
  misses -- a call charged to a session whose ACP session is already gone reaches
  no unit -- the emitter spec now states, along with why resolving later would be
  worse rather than better.
* a child is pinned when its spawn is ACCEPTED, which is the only moment the
  asking turn is knowable, and its entry is written when the run actually
  STARTS. A queued follow-up cannot use the live reading at all -- its watcher
  dispatches after the continued run finished -- so its asking turn is pinned
  where the follow-up was requested and carried to the dispatch, the same way
  `_preassigned_id` and the inherited context groups already ride that call.

An opener and its closer are bound by control flow rather than by convention,
because an unclosed pair in an append-only file cannot be repaired later:

* `approval/requested` is written one statement before the try whose `finally`
  writes the decision, not at the future's registration further up. Everything
  between the two is cancellable -- the Slack mirror awaits a network post, and
  its `except Exception` cannot catch the CancelledError slot deletion raises --
  so an entry written up there could escape that try and leave a request nothing
  ever decides. The cost is that a prompt cancelled during its Slack delivery
  goes unrecorded, which is a fact missing rather than a pair got wrong.
* a child's pin carries an `opened` flag, set only where the run really starts,
  so a spawn declined at the approval gate -- which returns through the finalize
  claim without ever reaching `_run` -- leaves no opener, and no steer or outcome
  can appear without its cause.

Eight families now write: `approval/requested` and `approval/decided`, which
never needed the resolver because the prompt is raised inside the runner's turn
where the session id and ordinal are already in scope, and whose decision is
recorded at the one `finally` every exit converges on;
`subagent/spawned|steered|completed|failed`, into the PARENT's log;
`background/completed` for `title`, `summary` and `memory_consolidation`, from
the same point the background helpers already record usage, so a call reaches a
session's log exactly when it reaches the account's bill; and `plan/updated`,
inside the slot's own change gate.

Every field is absent rather than placeheld when its site observed nothing. A
spawn from a slash command, a cron or a hook has no asking turn, and turns are
numbered from one, so `turn` is omitted rather than written as a `0` naming a
turn that never existed -- the same choice `model/selected` already makes. `tool`
and `reason` on an approval, `model` and `agent` on a spawn, and a background
call's unbilled token dimensions all follow the same rule.

Bounds are measured, never assumed. A plan entry is capped by COUNT and by
BYTES, through the store's own serializer, because `ensure_ascii` spends six
bytes on a BMP character and twelve on a surrogate pair: a dozen separately-legal
rows of emoji serialize past the entry ceiling, where the append is refused and
the whole update disappears. Both caps keep the real count in `total`.

The flag buys silence, not just a skipped write. `on_plan_updated` and
`on_approval_requested` check it themselves, because both do real work -- a
redaction per task, a serialize probe per admitted row -- before `_write` gets
its own chance to no-op, and the runner calls both unconditionally. Every
subagent and background emitter is guarded at its caller instead, so with the
feature off none of them is reached at all.

Three of the design's claims turned out to be wrong and the specs now say so
rather than promising a schedule:

* `subagent/spawned` carries no `ref`. No subagent path opens a log, so the
  citation would name a file that does not exist -- indistinguishable, to a
  reader, from one that was deleted.
* `subagent/completed` carries no `tokens` and no `credits`. Nothing in that
  runtime measures either, and a zero would present an absent measurement as a
  measurement of zero.
* `tool/searched`, `tool/loaded`, `skill/searched` and `skill/loaded` stay
  unwritten because the backend CLI's built-in tools DO reach the gateway, as
  ordinary tool-call frames, so those calls are already recorded. A second
  entry would put one fact at two seqs.

`summary/written`, `remote/placed|lost`, the `digest` background kind and
`message/steered` stay unwritten for their own stated reasons, each now in the
Emitter column instead of a dash.

Four rows of the schema table are corrected to match the frozen code: the
approval pair's field is `approval_id`, never `id`, and the fields the emitters
omit are marked optional rather than shown as always present. `reason`, `by` and
`cause` are new optional fields; `by` and `cause` are written only for a decline
the host itself made, which is the one decision the site can attribute.

Everything stays behind KIROCREW_CREW_LOG; the default is off.
@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Owner disposition -- GPT 5.6 on 372a0ca933997d9baafdacc6ee590297295dd626

No code push for either finding; this is the PR's agreed stopping point on code. F1 points at an existing body item. F2 is real, was downgraded by the adjudication, and it exposes a wrong sentence in my own body item 6, which I am recording here rather than letting stand.

F1 -- llm_helpers.py:1934, idle-expiry consolidation resolves ownership after session removal. Body items 7 and 9, at a new line number. Same mechanism, same declined remedy, same stated residual: the consolidation is scheduled by idle expiry and runs after the slot's teardown, so the resolver has no ACP session id for the key and the emitter's empty-id no-op drops the entry. Pinning the id before scheduling and threading it through the consolidation call path is right in principle and is refused on change budget, which item 9 says in those words. Resolving later instead stays refused for the reason item 7 gives.

F2 -- emit.py:3530, the origin cap can evict a child that has not started. The adjudication DOWNGRADED this one as a disproportionate remedy, so it is not what keeps the lane red. I traced its premise anyway, and the premise is TRUE: a run is registered in the manager's agent map at the point it is dispatched, so a child still waiting in the admission queue is absent from that map; the running set is built from that map, so the reaper's liveness probe reports such a child as not running and files it under finished.

The part that matters for this PR's honesty is the consequence, and here my own body text is wrong. Item 6 says the bound "prefers a finished child, and any remaining loss is counted". The first half holds. The second does not for this case: in _reap_child_origin the finished branch pops the pin and returns, and only the fallback popitem(last=False) increments the lost-origin counter. So a queued child evicted as though it had finished is an UNCOUNTED loss, not a counted one, and dropped_origins does not report it.

The effect of an evicted pin is bounded, which is why the remedy was judged disproportionate rather than the finding waved off: open_child_origin and child_origin then answer with an empty session id, and every caller bails on that -- the spawn path writes no opener and the terminal report writes no closer -- so what is lost is a matched PAIR of entries in a default-off diagnostic log, never a wrong-session write. It takes 2049 pins held at once, since the reaper only fires above the ceiling.

Residual, stated plainly: with more than 2048 origin pins alive at once, a child still queued can have its pin dropped as if it had finished, its spawn and terminal entries are then both absent, and that particular drop is not counted. It changes no control decision and stays inside one user's own log.

The wording of item 6 will be corrected in the body the next time an edit is safe. It is not edited now because ten checks are still in flight on this head and a body edit fires edited, which cancels them; a comment does not.

Both lanes on this head are fenced or review-side, so no override marker applies and the red stands until a repository writer clears it after verifying these rationales themselves.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants