Skip to content

feat(crew-log): fold the session ledger from the session crew log - #12027

Merged
bolichen97 merged 2 commits into
mainfrom
feat/session-ledger-as-projection
Sep 20, 2026
Merged

bolichen97 merged 2 commits into
mainfrom
feat/session-ledger-as-projection

Conversation

@chenmingwei23

@chenmingwei23 chenmingwei23 commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

What is the problem?

A session's durable work state and a session's history are two records of the same
session, kept in two places. The session work ledger holds the state record -- goal,
phase, resumable next step, rejected approaches, artifact pointers, a bounded event
tail -- in a document of its own, replaced whole on every write. The session crew log
holds the append-only history beside it and says nothing about that state.

Two consequences follow from the duplication. The ledger's central rule, that a phase
never moves without a logged reason, is a property the writer enforces rather than one
the record guarantees; a reader has no way to tell which store is right when they
disagree. And the two are keyed differently -- the ledger by slot, the crew log by ACP
session id -- so nothing joins them, even though a slot's workstream and the sessions it
ran under are the same work.

Why this issue matters to the user

A long-horizon loop reads the ledger to recover its next step after compaction, and
treats it as authoritative over its memory of prior cycles. When a second store can
disagree with the log, the loop can resume on state the history contradicts and nothing
surfaces the conflict. Reading a session's history has the mirror problem: the phase
changes, the approaches already ruled out and the artifact pointers that history
produced live in a file the history never mentions, so the record a person most wants
while reading a session is the one they cannot see from it.

How our fix solves it

The symptom is two records of one session's state that can disagree. The root cause is
that the ledger owns a document, which makes "what this session's state is" a question
with two authorities. So the document goes and the crew log becomes the single one.

session_ledger.record appends exactly one ledger/recorded entry per call, carrying
only the fields that call set plus the event explaining them, and every reader folds
those entries back with a new ledger fold registered in crew_log/projection.py. The
phase rule stops being enforcement and becomes structure: a phase and its reason are the
same appended line, so no ordering exists in which a reader sees one without the other
and no crash can separate them.

The fold is keyed by SLOT and joins every session crew log the slot ran under, oldest
unit first. That join is required rather than convenient: a slot owns one ACP session id
at a time, not for its whole life, so a reset or an agent, model or provider change
spreads one workstream across several units. A seq is comparable only within one file,
so the guard advance applies is re-based per unit -- the state carries forward while the
seq restarts -- and the unit list comes from headers proved to belong to the store that
holds them.

Two costs of that shape are paid rather than accepted. The record is read on every loop
wake, so the fold checkpoint is kept per slot and advanced over the entries that arrived
since, instead of re-walking the whole log each time; a changed unit list, a newest unit
whose seq went backwards, or a cold cache each force a full rebuild, because each would
otherwise be a wrong answer rather than a slow one. And the append is waited on before
the call answers, so an acknowledgement is not merely a queued entry.

state.json is never written. It is read exactly once per slot, by an upgrade
carry-forward: the first update that finds a slot's folded record empty carries that
document into the log as one entry and then appends its own, so a workstream in flight
across the upgrade keeps the state a resume needs. The carry is a consumption rather
than a fallback -- nothing consults the document to answer a read -- so the log remains
the single authority. An entry holds one rejected approach, so the carry brings the
goal, phase, next step, artifacts and the newest approach, and its event names how many
earlier approaches and event lines it could not bring.

Permanent deletion of a live record happens with the session's crew log unit, through
the funnel that already removes it, and kirocrew ledger-sweep still collects the
legacy directories. The sandbox and file-tool fences needed no edit, and that is worth
stating rather than passing over: the crew-log root is already a fenced leaf, so the new
home inherits the protection, and the old leaf is retained so residue on disk stays
unforgeable.

One consequence is deliberate and visible to a caller: recording requires the crew log
to be enabled and the session to have one. Otherwise record raises LedgerUnavailable
and the route answers HTTP 409 crew_log_unavailable, because a durable record must
never report a write that went nowhere.

What tests we did

A new suite pins the properties the change has to keep: the record-to-fold round trip;
one call appending exactly one entry; a phase without an event refused with nothing
appended; a phase and its reason proved to be the same entry; the fold joining two units
of one slot with the older unit's goal carried across the boundary and the newer unit's
step winning; units of a neighbouring slot excluded; a unit whose header names no slot
attributed to none; the injected snapshot pinned line by line; a terminal phase
suppressing it and leaving one bringing it back; the field clamps, event tail and
artifact map re-applied on read against hand-written entries.

The review round added more, each pinning a defect it found: the upgrade carry-forward
and what it declines to carry; the entry proved on disk before the call returns; a unit
whose header lands after a scan becoming visible; a same-count unit swap inside one
mtime tick invalidating the slot map; a timestamp outside the datetime range folding to
an empty stamp instead of a 500; and the warm fold equalling a cold fold after every
update, which is what caught a cache keyed on the slot without the data home.

Two existing suites were rewritten where their fixtures exercised the removed write
path. The ledger suite keeps every property that still exists and builds legacy stores
directly on disk for the delete machinery, which still governs that directory. The sweep
suite is fixtures only.

Counts on the pushed head: 855 passed across the ledger, sweep, crew-log type, crew-log
projection, crew-log core, conductor-entry and reference-doc suites; 553 passed across
ten crew-log suites the change does not own, to check for collateral damage. The
repository's backend gate floor passes, including the black, isort, flake8, mypy,
docs-lint, feature-map, comment-history, sync-IO, loop-lock and per-file-coverage gates.
Two platform_compat cases about /usr/bin being root-owned fail in this environment
and fail identically on an untouched checkout that contains none of this change, so they
are an environment artifact rather than a regression.

Any other suggestions on the work

The flag dependency is the one real trade-off and a maintainer may want it decided
differently. The alternative was to make the ledger's append unconditional, which would
widen the emitter's own activation rule and create a session crew log for a gateway that
never asked for one -- including a unit retention cannot collect, since nothing would
write its close. Refusing loudly was chosen over degrading silently or widening quietly,
and the decision is with the maintainer who owns scope for this work.

Two follow-ups are worth noting rather than folding in here. Once a previous pointer
between a slot's successive units lands, the fold can follow that chain instead of
scanning the sessions root. And the ledger fold is deliberately not one of the five
panel folds, so it is not pushed on growth; a client that wants it live would need a
slot-addressed push rather than the per-session frame.

@chenmingwei23
chenmingwei23 requested review from a team and pepmach September 19, 2026 13:23
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Sep 19, 2026
@github-actions

github-actions Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5) — 🟡 CONCERNS

Design-level review of a1ab61eebe52c9af189478d44dfc798dd3d89ce8 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: CONCERNS

Ledger recording now refuses by default: KIROCREW_CREW_LOG is opt-in, so every default-install gateway loses a feature that previously worked unconditionally.

Watch

  • The old ledger wrote its own document regardless of any flag; after this PR record raises LedgerUnavailable → HTTP 409 whenever the crew log is off ("a gateway started without KIROCREW_CREW_LOG=1 cannot record one"). A long-horizon loop mid-workstream on a default install upgrades, can still read its carried legacy state, but every phase/next-step update is refused until an operator restarts with the flag — a regression the author explicitly leaves "with the maintainer who owns scope." That decision needs an actual owner's yes, not silence.
    Clears when: a maintainer explicitly accepts the flag dependency on this PR, or the crew log (or ledger-triggered unit creation) becomes default-on.

Suggestions

  • Land the previous unit pointer follow-up promptly: the unit-order, deleted-units and carried control files are a hand-rolled transactional layer that exists only because the log can't order or chain a slot's units itself, and each is permanent maintenance surface until the pointer replaces the scan.

[DESIGN-REVIEWED] a1ab61e

@github-actions

github-actions Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — ✅ no blocking findings (all downgraded on adjudication)

GPT 5.6 flagged blocking issues on a1ab61eebe52c9af189478d44dfc798dd3d89ce8; Opus 4.8 adjudication downgraded every one of them to advisory. Adjudication downgraded all 1 blocking finding(s) to advisory: the remedy each one requires is disproportionate to the harm it prevents. Read them as advice, not as merge conditions.

This comment is updated in place on each push.

Review details

BLOCKING -- src/kiro_crew/dashboard/handlers/session_ledger.py:181 -- A non-durable update is acknowledged as recorded
return web.json_response({"ok": True, "durable": durable, "state": state_record})
Writer exceeds flush deadline -> speculative state returns successfully -> restart can lose the acknowledged update.
Anchor: persist-before-you-publish
Fix: Require per-entry persistence confirmation and return a retryable error unless that exact append lands.
[BLOCK-MERGE-DOWNGRADED] a1ab61e
[GPT-REVIEWED] a1ab61e

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

The code returns durable as a first-class field alongside ok: True; the caller is explicitly told whether the append reached disk. The finding's "acknowledged as recorded" reading ignores that field.

F1 — Harm: LOW. Conditions confirmed: flush exceeding _APPEND_FLUSH_SECONDS yields drained=False→durable=False (session_ledger.py:956,964); the entry is then QUEUED not lost, and loss additionally requires an unclean death inside the queue-to-flush window (documented session_ledger.py:941-942). Recovery: the response carries durable: false (session_ledger.py:181) so the caller is informed (not silent), a warning is logged (session_ledger.py:982-987), and the next update re-reads base from disk and supersedes (session_ledger.py:954-955, record() docstring 1017-1018). The proposed remedy (per-entry confirmation + retryable error) is explicitly rejected in code at session_ledger.py:951-955 as causing double-appends or rejecting good concurrent writes — a high-cost contradiction of the intentional async-writer design. Visible + recoverable + rare vs. a disproportionate fix.

[ADJUDICATION] a1ab61eebe52c9af189478d44dfc798dd3d89ce8 total=1 uphold=0 downgrade=1
DOWNGRADE F1 src/kiro_crew/dashboard/handlers/session_ledger.py:181 reason=disproportionate-remedy
[GPT-ADJUDICATED] a1ab61eebe52c9af189478d44dfc798dd3d89ce8

False positive or not applicable? A repository writer can comment:
/ai-review override gpt a1ab61eebe52c9af189478d44dfc798dd3d89ce8: <one-sentence reason>

@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 19, 2026
@github-actions

github-actions Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5) — 🟡 CONCERNS

Premise-level review of a1ab61eebe52c9af189478d44dfc798dd3d89ce8 — 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

Ledger recording now refuses on every default build (crew log off), a trade-off the description itself hands to the maintainer — and the delete-refusal subsystem is undeclared.

Not justified as shipped

  • Item 2 — inherited: "recording requires the crew log to be enabled" plus KIROCREW_CREW_LOG defaulting off means session_ledger_record answers 409 on a stock gateway where it worked before; the description says "the decision is with the maintainer who owns scope for this work." The in-progress rfc-append-only-ledger names session_ledger.py as a head to be replaced by a fold, but the refuse-by-default window until Session ledger bodies are outside deletion, accounting and retention #10705 flips the flag is a coverage call, not a read fact.
    Clears when: a maintainer explicitly accepts the flag dependency on this head, or the Session ledger bodies are outside deletion, accounting and retention #10705 default-on gate lands first.
  • Item 5 — undeclared: the description says deletion happens "through the funnel that already removes it," while the diff adds persisted control files (ledger/control/: deleted-units, unit-order, carried) and two new user-facing delete failures — 409 ledger_exclusion_unwritable refusing a history delete, 503 ledger_rollback_failed — that can now block deleting a conversation that never used the ledger.
    Clears when: a maintainer knowingly accepts the new delete-refusal path (it is nowhere in the author's account of the change).
  • Item 9 — one consumer, generalized: SLOT_PROJECTION_NAMES holds exactly one name and has one membership consumer (handlers/crew_log.py:292; grep SLOT_PROJECTION_NAMES in src/), and _slot_units_for_fold's session_units_for_slot fallback branch has zero reachable callers.
    Subtraction: replace the membership test with name == LEDGER_FOLD_NAME and delete _slot_units_for_fold's fallback branch.
    Clears when: the singular form ships, or a second slot-keyed fold exists.

What this change ships

Inventory (10 items) — 7 justified

Intent: give a session's durable work state one authority — the session's append-only crew log — so the record and its history can never disagree. A re-architecture (ADDITION of the fold, removal of the document) whose provenance is the in-progress rfc-append-only-ledger, framed by the author as a fix; more than 10 quiet differences exist (MCP hint text, docs type count, find_key_by_sid(exclude=) rides along), capped at the 10 a person would notice.

  1. Ledger state lives in the session crew log as ledger/recorded entries; state.json never written — justified
  2. Recording refuses 409 unless the crew log is on — inherited: default builds lose recording; author defers the decision
  3. The record joins every session a slot ran under, so state survives resets and model switches — justified
  4. Permanently deleting a session now deletes its ledger record (previously preserved) — justified
  5. History delete can now be refused over new ledger/control/ bookkeeping files — undeclared, non-trivial surface on the delete path
  6. Legacy state.json carried forward once, newest rejected approach only, loss counted — justified
  7. Responses carry durable; the MCP tool warns when the append is not yet on disk — justified
  8. Oversized updates refused up front with 413 — justified
  9. Ledger readable at GET .../crew-log/projection/ledger — one consumer, generalized (SLOT_PROJECTION_NAMES has one entry)
  10. Fold checkpoint and slot-map caches keep loop wakes from re-walking the log — justified

[FIRST-PRINCIPLES-REVIEWED] a1ab61e

@github-actions

github-actions Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Opus 4.8 Review — ✅ no blocking findings

Reviewed a1ab61eebe52c9af189478d44dfc798dd3d89ce8 — this comment is updated in place on each push.

Review details

No findings.

Both candidates concern the ledger-as-projection conversion and both fail falsification.

CANDIDATE 1 (dashboard read_slot_projection skips the _legacy_preview carry that read_state applies): the divergence in code is real, but no reader reaches it in the pre-carry window. The frontend fetches only the plural /crew-log/projections route, which folds PROJECTION_NAMES (the five panel folds) and excludes ledger; nothing in website/src fetches /crew-log/projection/ledger or /api/session-ledger. The MCP tool and nudge snapshot go through read_state, which does preview. So the "empty ledger panel during the upgrade window" outcome has no consumer in practice — (c) is unreachable without a hand-issued API call, and the state is transient and self-healing on first record.

CANDIDATE 2 (record_update returns state folded on base.last_seq+1 when the live unit is absent from the folded unit list): the pending entry is never written from this object — the store assigns the real seq under its lock — so seq=base.last_seq+1 only has to clear advance's at-or-below guard, which it always does; advance folds the update correctly regardless. canonical_slot resolves to the live unit's own header slot, so session_units_for_slot(canonical) normally contains it. The absence case requires an unprovable header or a fail-closed listing exception, and its only effect is a transient acknowledgement folded over a base missing prior fields — the on-disk append is unaffected and the next read supersedes it. No persistent-corruption path; (c) is display-only and self-correcting, below the bar.

No self-originated finding cleared 80.

[OPUS-REVIEWED] a1ab61e

Verdict parsed from the review's SHA-scoped output markers for commit a1ab61eebe52c9af189478d44dfc798dd3d89ce8.

False positive or not applicable? A repository writer can comment:
/ai-review override fable a1ab61eebe52c9af189478d44dfc798dd3d89ce8: <one-sentence reason>

@chenmingwei23
chenmingwei23 force-pushed the feat/session-ledger-as-projection branch from 9f5c02d to 14a0a26 Compare September 19, 2026 13:43
@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 19, 2026
@chenmingwei23
chenmingwei23 force-pushed the feat/session-ledger-as-projection branch from 14a0a26 to 0fb8446 Compare September 19, 2026 13:51
@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 19, 2026
@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Every finding on 9f5c02de6a is dispositioned. Head is now 0fb84462bb.

GPT F1 -- existing durable ledgers disappear after upgrade. Fixed. The first update that finds a slot's folded record empty carries the pre-projection document into the log as one entry, then appends its own. Carried as an entry rather than kept as a read fallback, so the log stays the single authority and the document is consumed instead of consulted. My original trigger was wrong in a way the tests caught: a session's crew log is created on its first turn, so keying the carry on "no unit exists" would never have fired. It keys on the empty folded record. An entry holds one rejected approach, so the carry brings goal, phase, next, artifacts and the newest approach, and its event names how many earlier approaches and event lines it could not bring, which keeps that loss visible rather than silent. The phase rides with that event, so the carried entry keeps the invariant the record rests on.

GPT F2 -- record success can precede durable persistence. Fixed, although adjudication downgraded it. record now waits for the writer to drain before answering, so an acknowledgement means the entry is on disk. The route already runs this on a worker thread, so the wait costs no event-loop time. On expiry the entry is still owed and counted by the writer, and the call logs that it is not yet durable rather than raising, because raising would invite a retry that appends the same update twice. The one exception is the carry-forward: if its own append does not drain, the update is refused rather than written over state that has not landed, since that would order the update ahead of the state it extends.

GPT F3 -- an incomplete unit can poison the slot cache. Fixed. The finding is exact: create publishes the header after its mkdir, and the header lands inside the directory, so the root's mtime and child count do not move with it. A scan inside that window cached a map missing a real unit, and the miss outlived the window until unrelated child churn happened to invalidate it. The scan now names the children it could not prove and a cache hit re-checks just those. That is nothing at all in the ordinary case, and one header read per hit for a permanently unprovable child such as a stray directory.

Design review, third Watch item -- every read re-folds all entries from seq 1. Fixed. This was a real regression against a documented promise, and the suggested remedy was the right one. The checkpoint is now kept per slot and advanced over the entries that arrived since, through the same seq-anchored machinery a cold fold uses. A different unit list, a newest unit whose seq went backwards, or an empty cache each force a cold rebuild, because each would otherwise be a wrong answer rather than a slow one. A test asserts the warm fold equals a cold fold after every update, and it earned its place immediately: it caught the cache keyed on the slot alone, so two data homes in one process could share a checkpoint. The key now includes the data home, the same precaution the store's scan fingerprint takes.

First principles, item 8 -- the updates counter nothing reads. Deleted.

First principles, item 7 -- the slot-keyed fold surface is generalized over one variant. Keeping it. SLOT_PROJECTION_NAMES is the seam the projection route dispatches on; collapsing it to a literal comparison moves a fold's identity out of the fold registry and into an HTTP handler, which is the coupling the registry exists to prevent. The registry is also how a second slot-keyed fold arrives without touching the route.

First principles, item 9 -- two specs rewritten wholesale, deleting rationale for unchanged behavior. Correct, and worse than the wording suggests: the rewrite cut crew-log-projection.md from 3060 words to 989 and session-work-ledger.md from 5787 to 1520. This change alters almost nothing about the five panel folds, so most of what went from the projection spec was rationale that still holds. Both files are being restored from base and edited additively instead. That is in flight and is the one item not yet on this head.

Design review, first Watch item, and first principles item 2 -- the ledger now depends on a default-off flag. Both reviews are right that this needs an owner rather than a note, and it is with the maintainer who owns scope for this work, with the alternatives written out: accept the gating, sequence behind the flag defaulting on, or keep the document as a flag-off fallback. I have not chosen on their behalf and have not used an override.

@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 19, 2026
@chenmingwei23
chenmingwei23 force-pushed the feat/session-ledger-as-projection branch from 0fb8446 to 19b3c83 Compare September 19, 2026 14:07
@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 19, 2026
@chenmingwei23
chenmingwei23 force-pushed the feat/session-ledger-as-projection branch from 19b3c83 to 0e40cc6 Compare September 19, 2026 14:20
@chenmingwei23

chenmingwei23 commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor Author

The spec condensation (first principles item 9) is addressed on head 0e40cc6867.

Both files were restored from base and edited additively instead of rewritten.
crew-log-projection.md is 3637 words against a base of 3060, and
session-work-ledger.md is 7098 against 5787 -- against the 989 and 1520 the
rewrite had left. The rationale the finding named is back verbatim, including the
whole lock-inode paragraph: the require_lock_inode identity check, the in-hold
unlink and its Windows asymmetry, the post-release step touching only the paths the
hold could not, and the file-presence rule that separates a purged store from a
damaged one. The projection spec keeps the push-rebind rule, the omitted-count
saturation posture and "a close is not a turn ending", none of which this change
touches.

What the two specs now add rather than replace: the slot-keyed ledger fold and why
it is the module's one stated exception to FR-4; why it is kept out of
PROJECTION_NAMES and therefore out of the growth push; the per-unit re-basing of
the seq guard; the upgrade carry-forward and what it declines to carry; and the
durable-acknowledgement contract stated as what the wait actually proves rather than
as a claim the drain does not support.

@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 19, 2026
@github-actions

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — 🔴 changes requested (blocking)

GPT 5.6 found at least one blocking issue that must be resolved before merging e4208fc992520b81d9bac8d406e336a5ade23df0. Adjudication produced no [GPT-ADJUDICATED] marker for e4208fc: the adjudication stage FAILED TO RUN (its raw output is in the Adjudication details block -- typically an API or setup error), so no proportionality review took place and GPT's blocking verdict stands unreviewed.

This comment is updated in place on each push.

BLOCKING -- src/kiro_crew/dashboard/handlers/session_ledger.py:175 -- a refused append still returns success
return web.json_response({"ok": True, "durable": durable, "state": state_record})
32 maximum-size artifacts -> 68,389-byte entry exceeds 64 KiB -> append is refused -> synthetic state is reported recorded but disappears after restart.
Anchor: persist-before-you-publish
Fix: reject oversized aggregate entries before enqueueing and return non-success whenever the append is not durable.

BLOCKING -- src/kiro_crew/session_ledger.py:1256 -- unit IDs are retained without their declared byte bound
added = tuple(unit for unit in dict.fromkeys(unit_ids) if unit not in current) / fh.write(f"{session_id}\n")
Seven 10-KB ACP session IDs -> truncated unit-order read omits the newest unit -> older units fold afterward and overwrite current ledger state.
Anchor: a-bound-bounds-every-field-it-retains
Fix: enforce _MAX_UNIT_ID_BYTES before retaining unit IDs and derive both control-file bounds from it.

[BLOCK-MERGE] e4208fc
[GPT-REVIEWED] e4208fc
False positive or not applicable? A repository writer can comment:
/ai-review override gpt e4208fc992520b81d9bac8d406e336a5ade23df0: <one-sentence reason>

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Both GPT blocking findings on e4208fc992 were real. Fixed on 164489c889.

Its adjudication stage failed to run, so that verdict stood unreviewed. Both findings were verified against the code first, and both held.

1. session_ledger.py -- a unit id was retained without its declared byte bound

Verified, and the module's own docstring already names the hazard class. _MAX_UNIT_ID_BYTES = 128 said in its own comment that it existed "for sizing the read below": an assumption about input, appearing only at its definition and in the derived _MAX_EXCLUDED_BYTES, enforced nowhere. The order file's read uses _read_lines with reject_oversized false, which TRUNCATES rather than rejecting -- text = text[:limit], taking the oldest bytes -- and _note_unit_order is a read-modify-write, so the truncation is persisted. That is exactly what _read_lines' own docstring warns about: "a caller that rewrites what it reads would otherwise persist the truncation, which is a silent loss". The consequence is the one reported: the newest unit is dropped permanently and older units fold afterward over the current record.

This is not the ordering finding from an earlier round. That one was about WHICH unit sorts last, and it is fixed and tested. This is the file's byte bound and a per-id bound that was never enforced -- a different defect in the same area.

Fixed by making the relationship structural rather than a comment. _retainable_unit() enforces the bound at the boundary, and all three sites that write an id go through it: the exclusion's added, the order log's append, and the order log's move-to-end branch. Both order bounds are now derived -- _MAX_ORDER_BYTES = _MAX_ORDERED_UNITS * (_MAX_UNIT_ID_BYTES + 1) and _MAX_ORDER_READ_BYTES twice that -- so a full compaction window of maximum-size ids is read whole by construction, with a compaction's slack for a file caught between the threshold and the rewrite. Refusing is the safe direction at both sites: an exclusion becomes a refused delete, which is what that file's count bound already does, and the order log becomes a missing line, which falls back to header order -- the same state a crash between the entry and the line leaves.

2. handlers/session_ledger.py -- a refused append still returned success

Verified, including the arithmetic. The clamps permit _MAX_ARTIFACTS (32) artifacts at _MAX_ARTIFACT_KEY (128) and _MAX_TEXT (2000) each; measured, the largest entry the public surface can be asked to write serializes to 78,634 bytes against the 65,536-byte ceiling. So the ceiling is reachable through clamped input, not only through a runaway writer.

Only the first half of the suggested remedy is right, and the measurement is what separates them. An over-ceiling entry is refused by the writer, which counts it and drops it, and that reaches the caller as the same durable=false a writer that is merely still busy gives -- but that update IS recorded and does land. The two need opposite answers: the busy writer's update is taken and the caller may proceed, while an entry over the ceiling can never land however often it is retried. The size is the one part knowable before the append, so it is now decided there: record_update() asks crew_log.emit.ledger_entry_fits() -- the same serializer, entry type and src the append uses, so the two cannot disagree -- and raises LedgerEntryTooLarge before enqueueing anything. The route answers 413 ledger_entry_too_large, ahead of the 400 branch it subclasses, because the remedy differs: a discipline refusal is fixed by supplying a field, this one by sending less.

The second half -- return non-success whenever the append is not durable -- is still declined, on the reasoning adjudication itself supplied in nine earlier rounds: durable is also false for an entry that is queued and will land, so refusing on it rejects good writes, and a retry would append the same update twice because nothing here is idempotent.

Verification

Three tests, one per property. Four mutations, all killed, with an independent control green each time: dropping the oversize refusal, unenforcing the bound on exclusions, unenforcing it on the order append, and restoring the hardcoded order-file bound. The control is deliberately independent of all three -- it touches no entry size, no control file and no unit id.

One correction to my own first attempt, since it changed the evidence: the oversize test initially used 4096-byte artifact values and did NOT raise, because record_update clamps to _MAX_TEXT first, so the clamped entry fitted. Measuring the clamps' own worst case is what showed the ceiling is genuinely reachable; the test now uses that shape.

1412 tests across the ledger, projection, crew-log core/projection/types/routes/emit, sweep, slot-removal, conductor-entry and reference-doc suites. flake8, black, isort clean on the changed files, mypy src/kiro_crew/ clean at CI's own scope, six fast-gate scripts pass including comment-history in enforcing mode.

The two advisory verdicts on the previous head

Design Review and First Principles both returned CONCERNS, and their primary finding is the same one: recording now refuses on a default gateway unless KIROCREW_CREW_LOG=1. The PR description already says that decision belongs to the maintainer who owns scope for this work, and both lanes name the same clearing path, so it is recorded here and left to them rather than decided in the diff.

One correction to First Principles' second item, which is otherwise accurate. The slot-keyed projection route does have zero product consumers -- projection/ledger has no hits repo-wide, and read_slot_projection and slot_of_session are reached only from the route and from tests. But SLOT_PROJECTION_NAMES cannot be deleted with them: projection.py asserts tuple(_FOLDS) == FOLD_NAMES at import time and FOLD_NAMES is built from it, so that tuple is half of the fold registry's consistency check, and the fold behind it is the one read_state itself uses. The removable part is narrower than the four symbols named: the route's dispatch branch plus _read_slot_fold, read_slot_projection and slot_of_session.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

The shard-7 red on 164489c889 is an unrelated stress-test flake, re-run once

Backend Tests (3.12, 7) failed on test/test_memory_multistore_stress.py::test_private_store_mixed_load[8] with asyncio.exceptions.CancelledError. Coverage Gate is downstream of it and PR Readiness failed on the pair.

Ownership, measured rather than assumed:

  • Not in git diff --name-only origin/main...HEAD for this branch -- zero files matching memory in the change set.
  • Byte-identical to origin/main.
  • Zero references to session_ledger or crew_log in the file, so it imports nothing this branch changes.
  • All three parametrizations, including [8], pass locally on this exact tree.

A CancelledError in a parametrized stress test that passes locally and cannot reach any changed module is a timing failure on a loaded runner, not a verdict about this diff. The run had already concluded at attempt 1 and no newer round was queued on this sha, so the failed jobs were re-run once -- attempt 2 is in flight. It is not a rebase candidate: the file is identical to main, so there is nothing on main to inherit.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=9bc7f518c977 (WATCH, recording refuses on a default build): ACCEPT AND DEFER to the maintainer who owns scope.

The reading is accurate. On a gateway without KIROCREW_CREW_LOG=1 and a live crew log, record_update raises LedgerUnavailable and the route answers 409, where the document store previously wrote unconditionally. The description states this is the maintainer's decision, and that is not a restatement of the problem: the alternative is to give recording a path that does not depend on the flag, which means either turning the crew log on by default or adding a config key, and both are decisions about the release this lands in rather than about this diff.

Nothing in this change set can clear it, so it is recorded here rather than patched. It clears exactly as the lane says: a maintainer accepts the flag dependency on this head, or this lands with or after the release that turns the flag on by default. The refusal is loud and its remedy is one environment variable, which is why it ships as a watch item and not as a silent degradation.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=c50a8e48b769 (WATCH, rollback then re-upgrade loses ledger state): ACCEPT AND DEFER, and the reason is that the proposed remedy reopens a hazard this PR spent several rounds closing.

The mechanism is real as described. The carry marker reads committed once per slot and never again, so a downgrade that resumes writing state.json produces updates that a later re-upgrade will not carry, and the loop resumes on pre-rollback state.

That marker is doing load-bearing work, which is why it is not simply made re-armable. committed is also what a permanent delete leaves when it tombstones the slot, and it is what stops a successor on a recycled slot key folding a deleted conversation's document into its own record. Making a changed document re-carry means the marker has to record the consumed document's identity and then trust that identity on a later read, which reintroduces exactly the question that tombstone answers: a recycled slot key whose document has been rewritten since the tombstone is indistinguishable, from the marker alone, from a legitimate downgrade-and-resume. Trading a silent cross-conversation state leak for a recovered downgrade window is the wrong direction, and it is a larger design change than a converged head should carry.

So the window is accepted and recorded, not fixed here. Downgrading across this change and then re-upgrading is not a supported path; the interim loss is bounded to updates written by the older build while it was in place, and the re-upgraded loop starts from the last carried record rather than from nothing.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=7282b30edc84 (Item 2, default-availability change): ACCEPT AND DEFER to the maintainer who owns scope.

Confirmed as stated. A capability that worked on every gateway now refuses on the default one, because KIROCREW_CREW_LOG defaults off per the RFC's FR-7, and the RFC decides that every other view is a fold without deciding that the ledger itself may refuse on a default gateway. The description defers it deliberately rather than by omission.

This is the one premise in the change set that no code in the change set can settle, because the two ways to settle it are both release decisions: default the crew log on, or add a config key that lets recording proceed without it. Either is larger than this diff and changes behaviour for gateways that are not running this feature at all.

Recorded here for the maintainer. The lane's own clearance applies: a repository writer records the decision on this head, or the flag dependency is confirmed as the RFC-intended shape.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=72b714230e06 (Item 6, the new 409 refusal is undeclared): ACCEPTED as accurate, and the missing surface is declared here.

The description says only that a permanent delete goes through the funnel that already removes the session, and that does omit a new way for it to refuse. Stating it properly: a permanent delete now writes the slot's ledger exclusion before it unlinks the transcript, and when that write fails the delete does not proceed. The single delete answers HTTP 409 with ledger_exclusion_unwritable; a bulk row is reported in undeletable with the same code and its transcript is left alone.

The refusal is the point rather than a side effect. If the exclusion cannot be written, deleting anyway would leave the slot's surviving units foldable by the next session on a recycled slot key, which is a cross-conversation state leak. Refusing costs the caller a retry; proceeding costs a leak that nothing reports.

Declared in this comment rather than by editing the description, because a description edit fires pull_request_target: edited, which re-runs PR Readiness and the codex review lane and would discard a board that is green on this exact head for a documentation gap. If a maintainer would rather have it in the body, it is one edit and I will make it on request.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=76fa355c31fc (Item 7, three new persisted control files are undeclared): ACCEPTED as accurate, and the surface is declared here.

The change persists three per-slot files under ledger/control/, and the description does not list them. What each one holds and why it has to survive a restart:

deleted-units carries the crew-log unit ids a permanent delete excluded from the slot's fold, so a session that recycles the slot key cannot fold the deleted conversation's record. unit-order carries the order in which units recorded, so the fold knows which unit holds the newest entry when a slot has run several sessions; the unit currently recording is moved to the end, which makes that answer an observation rather than a claim about clocks. carried is the one-time marker saying the legacy state.json document has been folded in, so the carry happens once per slot and a later read cannot re-carry a document that a delete has tombstoned.

All three are control state rather than record content: a reader that cannot read them degrades to the header order and to the un-carried record, which is the same state a crash between the entry and the control write leaves. None of them is an authority over the appended entries, which remain the only record.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=e08b122adb2b (Item 10, session_ledger.record() has zero consumers): MEASURED AND CONFIRMED, deferred to a follow-up rather than done here.

The count is right and I reproduced it: grep -rn "session_ledger\.record(" src/ returns 0. Every other .record( in the tree belongs to a different object, the auto-improvement spine's own ledger and the MCP gateway's hazard ledger, so the wrapper genuinely has no production caller. One test calls it directly. By itself the subtraction is eight lines plus that one call site.

What makes it a follow-up rather than a free win is the prose, not the code. session_ledger.record() is the term of art for the recording operation throughout docs/system-specs/modules/session-work-ledger.md and once in docs/reference/crew-log/session-types.md, in roughly ten sentences that describe what recording does, not which Python symbol does it. Deleting the symbol turns the change into a two-document rewrite of load-bearing spec prose, and prose cannot fail a test: the likely outcome is a stale-documentation finding next round on a head that is currently green, for a two-line delegation whose own docstring states its contract.

So the honest state is that this is a real YAGNI item with a measured zero, and the right place for it is a small follow-up that deletes the wrapper and renames the operation in both specs in one pass.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=21910eb8fc84 (bulk clear double-counts a row when its ledger rollback fails): CONFIRMED REAL, recorded as a fast-follow rather than fixed on this head.

I verified the mechanism in the code rather than reasoning about it. In api_sessions_clear, the result is None branch does skipped += 1 and the else branch does failed += 1, and each then awaits _rollback_ledger_exclusion(..., restore_carry=True) unguarded. If unexclude_units raises LedgerExclusionError there, control leaves the row's own branch and lands in the batch's except session_ledger.LedgerExclusionError, which appends the row to undeletable. The row is then counted twice, and cleared/skipped/failed/undeletable stop partitioning the processed rows. The third rollback site, in the except Exception branch, already wraps the same call in its own try and logs instead, so two of three sites are unguarded and the asymmetry is the defect.

The remedy needs no judgement, because the same function already decided it: one guarded helper used at all three bulk sites, logging what the except Exception branch logs today. Guarding them one at a time is what produced the asymmetry, so a third spelling would be the wrong shape.

Why it is not fixed on this head. The lane itself reports no blocking findings and files this as advisory. Reaching it needs an OSError writing a control file during the rollback of a delete that had already been skipped or had already failed, and the outcome is a wrong count in one response: the row is still reported as undeletable with its own code, and the underlying rollback failure is logged with the manual repair path. That is visible and recoverable, so on a head whose board is green across 90 lanes with PR Readiness passing, spending it re-rolls five non-deterministic review lanes for an error path inside an error path. The maintainer merging this should treat it as a small follow-up against the same function.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=596c3fd926a1 (a refused append still follows the committed path): DOWNGRADED ON ADJUDICATION, no action, and I agree with the adjudicator's reading.

The lane's own adjudication on this head returned total=1 uphold=0 downgrade=1 with reason disproportionate-remedy, so there is no live block. Recording the substance so the decision is not re-derived from scratch next time it surfaces.

The finding asks that a durable=False result be returned to the caller as a retryable failure. The reason that is the wrong trade is in the code it names: the process-wide dropped-write counter cannot tell a permanent refusal from a writer that is merely still busy. A busy writer's entry does land, so answering retryable there fails writes that succeeded and invites a retry that appends the same update twice. The adjudicator reached the same conclusion from the same lines, and added the recovery that makes it recoverable rather than silent: the next successful record re-reads its base from disk and moves the live unit back to last, the caller is told durable=False with its documented meaning, and the loss is logged and surfaced by dropped_writes().

One part of the same theme was genuinely closeable and was closed on an earlier head: an update too large for a single entry can never become durable however many times it is retried, so size is now refused before the append with HTTP 413 ledger_entry_too_large instead of being reported as a success that no read will ever show. What remains under this span is only the case where durability is unknown at answer time, and that is the case the adjudicator is right about.

iamwhatever
iamwhatever previously approved these changes Sep 20, 2026

@iamwhatever iamwhatever left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved on the current head: CI green, readiness passed, no security-sensitive path in the diff.

The session ledger's state record is a projection of the session's
append-only crew log rather than a document beside it. session_ledger.record
appends exactly one ledger/recorded entry per call, carrying the fields that
call set and the event explaining them, and every reader folds those entries
back with a new slot-keyed ledger fold.

A slot owns one ACP session id at a time, so the fold joins every session
crew log the slot ran under, oldest first, and a write only needs the unit it
is in. state.json is neither written nor read; that directory is residue the
ledger-sweep command collects, and permanent deletion of a live record
removes the session's crew log unit through the existing funnel.
@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=6d658f756250 (WATCH, recording refuses on an unflagged gateway): ACCEPT AND DEFER to the maintainer who owns scope.

The reading is accurate. emit.enabled() is false unless KIROCREW_CREW_LOG is set, so on a gateway without it record_update raises LedgerUnavailable and the route answers HTTP 409, where the pre-projection document store wrote unconditionally.

Nothing in this change set can clear it, so it is recorded here rather than patched. The alternative is to give recording a path that does not depend on the flag, and that means either turning the crew log on by default or adding a second config key. Both are decisions about which release this lands in rather than about this diff. The refusal is loud and its remedy is one environment variable, which is why it ships as a watch item and not as a silent degradation.

It clears exactly as the lane says: a maintainer accepts the flag dependency on this head, or this lands with or after the release that turns the flag on by default.

This is the same item already dispositioned on head 164489c in comment 5748562751. That head was rebased onto current main to clear a merge conflict that blocked the merge button; the rebase re-rolled the design lane and the finding returned with its substance unchanged.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=107bbf8dad7e (WATCH, the upgrade carry brings only the newest rejected approach): ACCEPT AND DEFER, and the loss is counted rather than silent.

The mechanism is real, and I checked it against the code rather than against the description. In _legacy_carry_payload, the carry reads newest = tried[-1] and carries that single row, sets dropped_tried = len(tried) - 1, and appends that count to the carried event as "not carried: N earlier rejected approach(es)". A loop resuming across the upgrade therefore sees the newest rejected approach plus a statement of how many older ones existed, so it can retry an approach it had already ruled out.

Two things bound it. The entry shape holds one tried, so carrying every row would mean an append per row on a path that runs inside a turn, which is unbounded work; that is the reason the function's own docstring gives for counting instead of carrying. And the legacy document is marked consumed rather than deleted, so the dropped rows stay on disk until a separate sweep and the loss is recoverable by reading them.

It clears exactly as the lane says: the carry preserves the full rejected-approach list, or a maintainer accepts the counted loss. Widening the entry shape to hold a list of approaches is a larger change than a converged head should carry, which is why it is recorded here rather than patched.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=8b19a9b816da (Item 2, default-availability change): ACCEPT AND DEFER to the maintainer who owns scope.

Confirmed as stated, and re-checked on this head: emit.py still documents itself as inert unless KIROCREW_CREW_LOG is truthy. A capability that worked on every gateway now refuses on the default one, and the RFC decides that every other view is a fold without deciding that the ledger itself may refuse on a default gateway. The description defers this deliberately rather than by omission.

This is the one premise in the change set that no code in the change set can settle, because the two ways to settle it are both release decisions: default the crew log on, or add a config key that lets recording proceed without it. Either is larger than this diff, and either changes behaviour for gateways that are not running this feature at all.

The lane names a maintainer /ai-review override first-principles as one clearing path. That is a maintainer action, and it is deliberately not taken by the agent driving this branch; it is recorded here so the decision stays visible to whoever owns it.

This item was dispositioned in the same terms on head 164489c in comment 5748563290. That head was rebased onto current main to clear a merge conflict that blocked the merge button; the rebase re-rolled this lane and the item returned under a new span id with its substance unchanged.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=e78a16081eb8 (Item 4, the new 409 refusal on delete is undeclared): ACCEPTED as accurate, and the missing surface is declared here.

The description says only that a permanent delete goes through the funnel that already removes the session, and that does omit a new way for it to refuse. Stating it properly: a permanent delete now writes the slot's ledger exclusion before it unlinks the transcript, and when that write fails the delete does not proceed. The single delete answers HTTP 409 with ledger_exclusion_unwritable; a bulk row is reported in undeletable carrying the same code, and its transcript is left alone. Both are still present on this head.

The refusal is the point rather than a side effect. If the exclusion cannot be written, deleting anyway would leave the slot's surviving units foldable by the next session on a recycled slot key, which is a cross-conversation state leak. Refusing costs the caller a retry; proceeding costs a leak that nothing reports.

This item was dispositioned in the same terms on head 164489c in comment 5748563553. The rebase onto current main re-rolled this lane and the item returned under a new span id with its substance unchanged.

GPT review upheld this on f2fbf02 (adjudication: harm-warrants-remedy).

_note_unit_order ran before the flush and before `landed` was known, so a
refused or still-queued append still moved its unit to the end of the order
file. That rewrite is fsynced immediately, so no crash was needed for the wrong
order to persist: a retired unit was pinned ahead of its successor, and a
successor resuming with no ledger content of its own then folded the retired
unit's stale goal and phase as current and acted on it.

The call now runs only once this unit's own newest seq has moved. Gated on
`landed` rather than `durable` deliberately: `durable` also requires `drained`
and an unmoved refusal counter, and that counter is process-wide, so a
concurrent session's refusal would suppress a precedence note this unit had
genuinely earned. `landed` is exactly the fact the order file asserts.

The sibling site that computes the same `landed` signal, the legacy carry, never
published precedence and already refused on it, so there is one defective site
and _note_unit_order has one caller.

Test pins it and was mutation-verified: neutering the guard reddens
test_an_append_that_did_not_land_does_not_publish_the_units_precedence with
('acp-2', 'acp-1') == ('acp-2',), the retired unit pinned last.
@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=6e119094988c (WATCH, recording refuses whenever the crew log is off): ACCEPT AND DEFER to the maintainer who owns scope.

The reading is accurate and still holds on this head: emit.py documents itself as inert unless KIROCREW_CREW_LOG is truthy, so record raises LedgerUnavailable and the route answers HTTP 409 on a gateway that did not set it, where the pre-projection document store wrote unconditionally.

Nothing in this change set can clear it, so it is recorded here rather than patched. The alternative is to give recording a path that does not depend on the flag, and that means either turning the crew log on by default or adding a second config key. Both are decisions about which release this lands in rather than about this diff, and both change behaviour for gateways that are not running this feature at all. The refusal is loud and its remedy is one environment variable, which is why it ships as a watch item and not as a silent degradation.

It clears exactly as the lane says: a maintainer accepts the flag dependency, or the crew log becomes default-on first.

This item has now been dispositioned in the same terms on two earlier heads, in comments 5748562751 and 5751494799. It recurs because each new head re-rolls the lane, not because the substance has changed.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=1950a5454d2a (Item 2, default-availability change): ACCEPT AND DEFER to the maintainer who owns scope.

Confirmed as stated, and re-checked on this head. A capability that worked on every gateway now refuses on a stock one, because KIROCREW_CREW_LOG defaults off, and the RFC decides that every other view is a fold without deciding that the ledger itself may refuse on a default gateway. The description defers this deliberately rather than by omission.

This is the one premise in the change set that no code in the change set can settle, because the two ways to settle it are both release decisions: default the crew log on, or add a config key that lets recording proceed without it. Either is larger than this diff, and either changes behaviour for gateways that are not running this feature at all.

The lane names a maintainer decision, and one route it offers is a review override. That is a maintainer action; it is deliberately not taken by the agent driving this branch, and is recorded here so the decision stays visible to whoever owns it.

This item has now been dispositioned in the same terms on two earlier heads, in comments 5748563290 and 5751507102. It recurs because each new head re-rolls the lane, not because the substance has changed.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=2f05529e5dae (Item 5, the control files and the new delete refusals are undeclared): ACCEPTED as accurate, and both surfaces are declared here.

The description says only that a permanent delete goes through the funnel that already removes the session, and that does omit two things the diff adds.

The persisted control files, all per-slot under ledger/control/. deleted-units carries the crew-log unit ids a permanent delete excluded from the slot's fold, so a session that recycles the slot key cannot fold the deleted conversation's record. unit-order carries the order in which units recorded, so the fold knows which unit holds the newest entry when a slot has run several sessions; the unit currently recording is moved to the end only once its own append has landed, which makes that answer an observation rather than a claim about clocks. carried is the one-time marker saying the legacy state.json document has been folded in, so the carry happens once per slot and a later read cannot re-carry a document that a delete has tombstoned.

The new refusal on delete. A permanent delete now writes the slot's ledger exclusion before it unlinks the transcript, and when that write fails the delete does not proceed: a single delete answers HTTP 409 with ledger_exclusion_unwritable, and a bulk row is reported in undeletable carrying the same code with its transcript left alone. The refusal is the point rather than a side effect. If the exclusion cannot be written, deleting anyway would leave the slot's surviving units foldable by the next session on a recycled slot key, which is a cross-conversation state leak. Refusing costs the caller a retry; proceeding costs a leak that nothing reports.

Both halves were dispositioned separately on an earlier head, in comments 5748563553 and 5748564164, and this head's lane raises them as one item. The substance is unchanged, and the unit-order description above is tightened to match the fix made on this head.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Disposition for span=76faa62a45a5 (Item 9, one consumer generalized): MEASURED AND CONFIRMED, deferred to a follow-up rather than collapsed here.

I reproduced every count rather than taking them from the description. SLOT_PROJECTION_NAMES is ("ledger",), one name. Its only membership consumer is handlers/crew_log.py:292; the other two hits are a docstring and the FOLD_NAMES composition. _slot_units_for_fold has one caller, read_slot_projection, which itself has one caller, handlers/crew_log.py:402. Since that route admits only a name in SLOT_PROJECTION_NAMES, and _FOLD_NAME is "ledger", the if is always true and the return session_units_for_slot(slot) fall-through is unreachable today. The reading is right.

One correction to what that implies: the fall-through is an unreachable BRANCH, not a dead stack. session_units_for_slot has real production callers outside it, at handlers/sessions.py:2297 and at session_ledger.py:582 and :591, so removing the branch subtracts one line and leaves the function it calls fully used. Nothing here is unreferenced code.

What makes it a follow-up rather than a free win is the prose. read_slot_projection's own docstring explains the fall-through in its closing sentences as the deliberate contract for a fold whose owner has no ordering rule, and the fall-through is described in two spec documents, crew-log-projection.md and session-work-ledger.md. Collapsing the registry to a singular form means rewriting that docstring and those passages, and prose cannot fail a test, so the likely outcome is a stale-documentation finding on a head where the review lanes have just converged.

It clears exactly as the lane says: the singular form ships, or a second slot-keyed fold consumes the plural one. Recorded here so the next person does not re-measure it.

@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Known deferred defect, recorded here so it is on the record at merge time rather than found later.

src/kiro_crew/dashboard/handlers/sessions.py:2808 -- that handler is except session_ledger.LedgerExclusionError:, but session_ledger is imported later inside its own try (at :2794), with six statements ahead of the import, including crew_log_emit.flush(...) and unit_header_slot(...).

Mechanism: if any of those raises, evaluating the handler's exception type touches an unbound local, so Python raises UnboundLocalError and never consults the following except Exception: at :2819 -- which would otherwise have logged the real cause and returned. So a contained, logged, best-effort failure escapes the function instead, and the true exception is lost.

Not fixed on this head deliberately: the review board has converged green, and a converged PR is the wrong place to land an unrelated change. Follow-up after merge.

Scope: verified at head a1ab61e, and this is the only occurrence. An AST pass over all fourteen changed source files, looking for an except clause naming a module imported inside its own try, returned exactly one hit.

Copy link
Copy Markdown
Contributor

Maintainer readiness-sweep record (agent-assisted, on behalf of @bolichen97), head a1ab61e: verified readiness: passed label + PR Readiness status success on this exact head, no failing or pending required checks, no outstanding CHANGES_REQUESTED, no unresolved blocking review thread, and no textual conflict with current main. The intended APPROVE review on this head failed to post before the squash-merge call, so the merge went through on repository-admin standing rather than a recorded approval. Recording the approval rationale here for the audit trail.

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.

3 participants