Repository navigation
feat(ledger): declare the session entry types and validate data on write - #11317
Conversation
Design Review (Fable 5, fork) — 🟡 CONCERNSDesign-level review of Design-Verdict: CONCERNS The drift this PR exists to kill survives it: the owning specs still state the old shapes, unreconciled and unpinned to the new registry. WatchThe PR's stated problem is "two statements of one fact drift," and its discrepancy list concedes the spec table is now wrong in four ways ("the emitter wins each one") — yet the diff touches no docs. Suggestions
[DESIGN-REVIEWED] 58ba8a3 |
GPT 5.6 Review (fork) — ✅ no blocking findingsReviewed Review detailsNo findings. |
First Principles Review (Fable 5, fork) — 🟡 CONCERNSPremise-level review of First-Principles-Verdict: CONCERNS The drift the description claims to end survives it: session-ledger-emitter.md's hand table is untouched, and the renderer meant to replace it ships with zero consumers. Not justified as shipped
What this change shipsInventory (7 items) — 5 justifiedIntent: stop a misspelled or mistyped
[FIRST-PRINCIPLES-REVIEWED] 58ba8a3 |
Opus 4.8 Review (fork) — ✅ no blocking findingsReviewed |
ba2e842 to
61c3a31
Compare
The ledger owned a vocabulary of entry types but nothing said what any of them carries. A writer learned the payload shape by reading call sites, and a reader learned it by reading entries, so a field could be renamed on one side and silently dropped on the other. Declare the 26 session types as data: kiro_crew.ledger.entry_types holds an EntryType per type and a Field per member, with the JSON type, whether it is required, closed enums, array item types and nested members. Ledger.append, append_many and the chunk-citing path validate data against that declaration before any byte is written, refusing with the additive bad_data_field code and naming the offending path. The same declarations render as Markdown via python -m kiro_crew.ledger.entry_types --markdown, so the reference table is generated from the enforced source rather than maintained beside it.
61c3a31 to
58ba8a3
Compare
|
Dispositions for this round, on head First Principles BLOCK -- fixed by subtraction. The verdict was right: the six A test now holds this rule to code rather than to a list: it reads the producing First Principles item 6, First Principles item 5, Design Review CONCERNS -- agreed, and it is the same finding. The spec's GPT 5.6 -- taken. The Two claims in the PR description were wrong and are corrected. It said E2E (stub ACP backend, offline) failed in 573 tests pass across the five ledger test files, 5 of 5 mutations killed, and the |
|
Reviewed on the current head for approval.
|
…switch
One of Crew's own MCP servers can only learn WHICH session is calling it through a
channel that needs the shared MCP gateway: the per-session token minted for
gatewayd rides stub entries alone, and gatewayd is its only reader. On a default
install -- no stub roster, no daemon, pooling off -- there is no per-session
channel at all, so the strict resolver falls back to KIROCREW_SESSION_KEY, which is
wrong by construction in the two topologies that matter most. After a warm-pool
rekey the env a child was spawned with names a different session; under spawn_run
session sharing one kiro-cli process hosts N ACP sessions, so the env var, the
session_pid file and a /proc walk all answer with the PARENT for a subagent's
server.
Give the token a second reader that needs no daemon.
* session_token_sig.py publishes token -> session_key to ONE MAC-signed file per
mapping, named by sha256(token) so a directory listing leaks no bearer name.
The MAC covers "<token>:<body>" under a subkey derived from the SEL trust root
with a domain label distinct from the pid sidecar's -- both protocols sign an
"<identifier>:<session_key>" message, so without the split a pid sidecar for
pid N would verify as a token sidecar for a token spelled N. The hardened
reader and key loader are imported from session_pid_sig rather than copied, so
the two sidecars' read discipline cannot drift apart.
* The token is minted unconditionally. A reachable gatewayd socket is not a
precondition, because gatewayd is not the only reader; the socket gates the
CLAIM alone.
* It rides every control-plane element, through the one owner of that question
(providers/mirrors/identity.control_plane_identity_env, shared by codex,
opencode and goose), plus the member-dispatch element and the child env of a
one-session process (AcpClient._apply_session_identity_env, which serves the
kiro backend among others). KIROCREW_SESSION_KEY rides beside it as the
fallback for the one case the token cannot cover: no SEL trust root to sign a
mapping with. The SHARED kiro runtime has no per-session carrier -- its
control-plane servers reach kiro-cli through --agent rather than a session
array and its process multiplexes N sessions -- so identity there is what it is
for every non-token source, and strict_identity_diagnosis names the missing
channel. Injecting session-level control-plane entries would give it one at the
cost of widening the tool surface, since such an element outranks the spec
entry it shadows while carrying neither its tools allowlist nor its
disabledTools; that is a tool-surface decision rather than a carriage one.
* Both resolvers read the token ABOVE the env var, because where the two
disagree the env var is the stale one. The gateway's per-call caller context
still outranks both, being stamped per call.
* Published at session/new and re-published on every rekey() and every turn
(messaging.identity, the existing single writer), which is what makes a
warm-pool claim visible to an already-running MCP child. Retraction is the
age-based sweep in session_pid.py and only that: a teardown hook cannot reach a
gateway that dies without running one, and pruning cannot cost a live session
its identity because republication precedes every tool call in a turn.
No new config key, and nothing about pooling changes: stub_servers, enabled and
gatewayd behaviour are untouched.
Trust boundary, the same one the env var already has: forgery, cross-token replay,
in-place tampering and symlink planting are blocked; a same-uid process reading the
mapping directory is not, and is not meant to be -- it can already read the
session_pid files and present another session's key through the env var.
Two existing pins move, both because the change makes their premise false rather
than to make a test pass:
* test_no_stub_entries_means_no_token_and_no_claim asserted ([], "") under
"nothing to name, and nothing that would read the name". The second half does
not hold once the token has a file-backed reader. Renamed and re-pinned to the
new contract, keeping the half that does hold: no stub entries means no claim.
* test_identity_topology's session_pid call-site ratchet flags
session_token_sig.py, which appears in its scan only because it imports the pid
sidecar's reader and contrasts the two contracts. Registered with its role and
with why a pid-view parametrization has nothing to vary here: it reads no pid
at all, which is the property that makes it namespace-insensitive.
schedule_session_token_publish type-checks both arguments rather than only
truth-checking them, as schedule_claim does: every caller reads the token off a
session handle with getattr, and a non-string reaching the hash would raise
TypeError out of rekey() -- a warm-pool claim failing because of an identity side
effect is strictly worse than the claim proceeding without one.
Three log messages carry a nosemgrep suppression with its reason, matching the
four precedents in auth/store.py: the logger-credential-disclosure rule matches on
the word "token" in the message literal, while the arguments are a session key and
a sha256 digest. The token itself is never passed to a logger in this change.
Tests: 46 across the mapping protocol and the wiring. Each of seven injected
anti-patterns -- token read below the env var, the pid domain label, the mint
re-gated on a socket, the token withheld from the element env, the MAC comparison
skipped, the child env carrying the key without the token, and an unkeyed child
keeping a stale token -- was verified to fail them (pytest exit 1 with real failure
counts, never exit 4), so none is vacuous.
Windows CI adjudicated four consequences of the unconditional mint that a
diff-gated Linux run had skipped. All eight Windows shards are green on main at
this base, so none of these was pre-existing:
* The harness wire goldens gain an env array on session/load's control-plane
elements: kirocrew-core and kirocrew-cron now carry
KIROCREW_STUB_SESSION_TOKEN there. That is the intended product delta -- the
token rides the control plane -- and it reaches session/load and not
session/new in this capture only because the capture hands session/new an
explicit roster, which create_session deliberately does not re-key. The
capture pins the token the way it already pins the work dir and the session
ids, because a value minted from secrets can never match a golden twice;
pinning the INPUT keeps the golden a byte gate over the whole element, env
pair included, rather than scrubbing the output and gating less.
* test_load_session_redeclares_pooled_stubs compared session/load's array to
session/new's byte-for-byte. Each session start mints its own token and those
are two different sessions, so the comparison now excludes the per-session
identity env and nothing else: the parity it guards is the stub SET, since
re-declaring a different one is what silently un-pools a resumed session, and
a per-session credential is not a server. Verified still load-bearing --
making load_session re-declare an empty array fails it.
* publish_turn_identity resolved the provider twice, because the token
publication added a second sessions.get_provider() beside the one the stub
re-claim already did. One lookup now serves both, which is what a per-turn
hot path should cost and restores the call count a Windows shard asserting an
allocation sequence was pinned to.
* test_owner_only_mode asserted POSIX permission bits. Skipped on Windows
rather than loosened: NTFS carries an ACL and os.chmod moves only the
read-only flag there, so the value reads 666 whatever mode was requested, and
an assertion that accepted that would assert nothing on either platform.
Every remaining red in the affected selection was measured against a detached
origin/main worktree at the same base SHA: 325 failing/erroring ids on each side,
identical sets.
Three advisory findings on the third head, all on claims this change wrote:
* The cleanup lifecycle is named accurately. _prune_stale_session_token_files
runs from cleanup_orphaned_sessions, which session.py documents as startup and
graceful shutdown only, so "periodic sweep" overstated it. Both docstrings now
say what that costs: a gateway running for a month prunes nothing in between,
and the bound is one mapping per session started since the last boot or clean
stop. Deliberate -- what is owed is bounding accumulation rather than prompt
removal, and a boot-time pass covers the case a teardown hook structurally
cannot, a gateway killed without running one. Pruning still cannot cost a live
session its identity at any cadence, because the mapping is republished at the
start of every turn before anything in it can call a tool.
* The forgery claim states the trust root's real fencing. security.md classifies
sel_hmac.key VISIBLE: no OS fence, no bash-layer fence, and a spawned shell
reaches a file through an open() that never routes through the tool gate.
is_sensitive_path refuses the leaf on the FILE-TOOL path and that is the whole
of it, so all three statements -- the module docstring and both docs -- now say
forgery is blocked against the file tools and not against a shell, name the
residual as shared with the SEL audit chain (same key, same gap), and cite
security.md's own remedy: move the in-sandbox reader behind the gateway so the
leaf can become HIDDEN, never another path matcher. A shell that can read the
key can also mint a local API token and skip client-side resolution, so this
protocol is not the narrow point. Rounding that up would have handed the
SO_PEERCRED follow-up an inaccurate baseline.
* THREE pins move, not two. The load_session/create_session parity comparison
now excludes the per-session identity env, and it belongs in that list rather
than only in the Windows-findings note. Equality on that field asserted that
two DIFFERENT sessions were given the same token, which must never hold; what
remains asserted is the stub SET, with command, args and every other env pair
still compared byte-for-byte.
The parity ratchet keeps seeing the token, not just its shape. Excluding the
per-session pair from BOTH sides of the load/new comparison dropped the PRESENCE
assertion along with the value one, so it would have passed just as happily if
load_session stopped carrying a token at all. Repaired rather than reverted, since
reverting restores an equality that asserts two DIFFERENT sessions share a token:
_without_identity_env now rewrites the pair to a fixed placeholder instead of
removing it, so an element with no token still differs from one with a token, and
_identity_tokens asserts separately that every re-declared element carries one and
that the two sessions' tokens differ. Both regressions now fail the class -- the
blind spot (load_session skipping attach_stub_session_token, 1 of 12) and the
un-pooling case it already guarded (an empty re-declared array, 3 of 12).
publish_turn_identity's single provider lookup is its own change rather than a
footnote to the Windows fixes. The token publication had ADDED a second
sessions.get_provider() beside the one the stub re-claim already did, so this
returns the per-turn path to one lookup rather than introducing an optimisation;
_provider_inner exists because both steps then reach the provider surface the same
way through getattr, and two copies of that resolution is how they drift.
Rebased onto 780e75e (main gained 9 commits). Both conflicts were the same
shape -- main and this branch each adding one import at the same line
(recovery.ladder.InfraError vs session_token_sig.schedule_session_token_publish;
metrics.events.CHILD_PERMISSION_DENIED vs mcp_gateway.claim.STUB_SESSION_TOKEN_ENV)
-- and both sides are kept. Re-measured against a base worktree at the new SHA:
325 failing/erroring ids on each side, identical sets.
The child env carries the token unconditionally; only the fallback key is
conditioned. Treating the pair symmetrically broke the case this change exists for:
a warm-pool client is spawned with NO session key -- that is what makes it
poolable -- and a child's environment is fixed at spawn, so withholding the token
there stripped it from exactly the children whose identity has to survive a
rekey(), with nothing able to add it back afterwards. The token is set regardless
because it is minted in __init__ and its signed mapping is published once the key
becomes known, so a child holding a token and no key still resolves through the
mapping to whichever session claimed the process. The KEY stays conditioned because
it is a value rather than a pointer: an inherited one names a session this client is
not serving and the resolver would read it as identity, while the same token names
the current owner after every rekey. An inherited token is OVERWRITTEN rather than
dropped, so a reused env mapping leaves carrying this client's; an absent one is not
carried as an empty value, which the resolver would try first and never verify.
Two reds on this head belong to main rather than to this branch, both introduced by
9ab334b (fix(cloud): preserve Identity Center login through managed launch,
#9840), one of the nine commits this branch rebased onto:
* Backend Lint & Type Check reports F401 'json' imported but unused in
src/kiro_crew/dashboard/handlers/sessions.py, a file this diff does not touch
and which that commit rewrote. Measured rather than asserted: whole-tree flake8
output is byte-identical between this branch and a worktree at the base SHA.
* Backend Tests (Windows) shard 3 fails two protocol assertions in
test_fargate_launch_engine.py over begin_signin gaining a login_target
parameter -- again that commit's surface, and again untouched here. The file
passes 34/34 on Linux in both worktrees.
Rebased onto 04727eb, which main had reached 24 commits past the previous base.
The rebase was clean. Two things it settles:
* 7d1810d (fix(dashboard): drop the unused json import left by #9840, #11415)
removes the F401 this branch was reporting as main's, which is what that
reading predicted.
* 039d3e8 (feat(ledger): declare the session entry types and validate data on
write, #11317) is where the LedgerError "data.agent / data.actor: is required
and absent" failures come from, and 9ab334b is where the
test_fargate_launch_engine begin_signin/login_target ones come from. Neither
file is in this diff, and both reproduce identically at the base: over
test_ledger_kinds, test_ledger_retention, test_fargate_launch_engine and
test_remove_slot_for_history_key the failing/erroring id sets are 48 on each
side and equal.
Checks run against refs/pull/N/merge rather than against this branch's base, so
main's own breakage lands in this PR's results whatever this branch is rebased
onto. The measurement above is what tells the two apart.
…switch
One of Crew's own MCP servers can only learn WHICH session is calling it through a
channel that needs the shared MCP gateway: the per-session token minted for
gatewayd rides stub entries alone, and gatewayd is its only reader. On a default
install -- no stub roster, no daemon, pooling off -- there is no per-session
channel at all, so the strict resolver falls back to KIROCREW_SESSION_KEY, which is
wrong by construction in the two topologies that matter most. After a warm-pool
rekey the env a child was spawned with names a different session; under spawn_run
session sharing one kiro-cli process hosts N ACP sessions, so the env var, the
session_pid file and a /proc walk all answer with the PARENT for a subagent's
server.
Give the token a second reader that needs no daemon.
* session_token_sig.py publishes token -> session_key to ONE MAC-signed file per
mapping, named by sha256(token) so a directory listing leaks no bearer name.
The MAC covers "<token>:<body>" under a subkey derived from the SEL trust root
with a domain label distinct from the pid sidecar's -- both protocols sign an
"<identifier>:<session_key>" message, so without the split a pid sidecar for
pid N would verify as a token sidecar for a token spelled N. The hardened
reader and key loader are imported from session_pid_sig rather than copied, so
the two sidecars' read discipline cannot drift apart.
* The token is minted unconditionally. A reachable gatewayd socket is not a
precondition, because gatewayd is not the only reader; the socket gates the
CLAIM alone.
* It rides every control-plane element, through the one owner of that question
(providers/mirrors/identity.control_plane_identity_env, shared by codex,
opencode and goose), plus the member-dispatch element and the child env of a
one-session process (AcpClient._apply_session_identity_env, which serves the
kiro backend among others). KIROCREW_SESSION_KEY rides beside it as the
fallback for the one case the token cannot cover: no SEL trust root to sign a
mapping with. The SHARED kiro runtime has no per-session carrier -- its
control-plane servers reach kiro-cli through --agent rather than a session
array and its process multiplexes N sessions -- so identity there is what it is
for every non-token source, and strict_identity_diagnosis names the missing
channel. Injecting session-level control-plane entries would give it one at the
cost of widening the tool surface, since such an element outranks the spec
entry it shadows while carrying neither its tools allowlist nor its
disabledTools; that is a tool-surface decision rather than a carriage one.
* Both resolvers read the token ABOVE the env var, because where the two
disagree the env var is the stale one. The gateway's per-call caller context
still outranks both, being stamped per call.
* Published at session/new and re-published on every rekey() and every turn
(messaging.identity, the existing single writer), which is what makes a
warm-pool claim visible to an already-running MCP child. Retraction is the
age-based sweep in session_pid.py and only that: a teardown hook cannot reach a
gateway that dies without running one, and pruning cannot cost a live session
its identity because republication precedes every tool call in a turn.
No new config key, and nothing about pooling changes: stub_servers, enabled and
gatewayd behaviour are untouched.
Trust boundary, the same one the env var already has: forgery, cross-token replay,
in-place tampering and symlink planting are blocked; a same-uid process reading the
mapping directory is not, and is not meant to be -- it can already read the
session_pid files and present another session's key through the env var.
Two existing pins move, both because the change makes their premise false rather
than to make a test pass:
* test_no_stub_entries_means_no_token_and_no_claim asserted ([], "") under
"nothing to name, and nothing that would read the name". The second half does
not hold once the token has a file-backed reader. Renamed and re-pinned to the
new contract, keeping the half that does hold: no stub entries means no claim.
* test_identity_topology's session_pid call-site ratchet flags
session_token_sig.py, which appears in its scan only because it imports the pid
sidecar's reader and contrasts the two contracts. Registered with its role and
with why a pid-view parametrization has nothing to vary here: it reads no pid
at all, which is the property that makes it namespace-insensitive.
schedule_session_token_publish type-checks both arguments rather than only
truth-checking them, as schedule_claim does: every caller reads the token off a
session handle with getattr, and a non-string reaching the hash would raise
TypeError out of rekey() -- a warm-pool claim failing because of an identity side
effect is strictly worse than the claim proceeding without one.
Three log messages carry a nosemgrep suppression with its reason, matching the
four precedents in auth/store.py: the logger-credential-disclosure rule matches on
the word "token" in the message literal, while the arguments are a session key and
a sha256 digest. The token itself is never passed to a logger in this change.
Tests: 46 across the mapping protocol and the wiring. Each of seven injected
anti-patterns -- token read below the env var, the pid domain label, the mint
re-gated on a socket, the token withheld from the element env, the MAC comparison
skipped, the child env carrying the key without the token, and an unkeyed child
keeping a stale token -- was verified to fail them (pytest exit 1 with real failure
counts, never exit 4), so none is vacuous.
Windows CI adjudicated four consequences of the unconditional mint that a
diff-gated Linux run had skipped. All eight Windows shards are green on main at
this base, so none of these was pre-existing:
* The harness wire goldens gain an env array on session/load's control-plane
elements: kirocrew-core and kirocrew-cron now carry
KIROCREW_STUB_SESSION_TOKEN there. That is the intended product delta -- the
token rides the control plane -- and it reaches session/load and not
session/new in this capture only because the capture hands session/new an
explicit roster, which create_session deliberately does not re-key. The
capture pins the token the way it already pins the work dir and the session
ids, because a value minted from secrets can never match a golden twice;
pinning the INPUT keeps the golden a byte gate over the whole element, env
pair included, rather than scrubbing the output and gating less.
* test_load_session_redeclares_pooled_stubs compared session/load's array to
session/new's byte-for-byte. Each session start mints its own token and those
are two different sessions, so the comparison now excludes the per-session
identity env and nothing else: the parity it guards is the stub SET, since
re-declaring a different one is what silently un-pools a resumed session, and
a per-session credential is not a server. Verified still load-bearing --
making load_session re-declare an empty array fails it.
* publish_turn_identity resolved the provider twice, because the token
publication added a second sessions.get_provider() beside the one the stub
re-claim already did. One lookup now serves both, which is what a per-turn
hot path should cost and restores the call count a Windows shard asserting an
allocation sequence was pinned to.
* test_owner_only_mode asserted POSIX permission bits. Skipped on Windows
rather than loosened: NTFS carries an ACL and os.chmod moves only the
read-only flag there, so the value reads 666 whatever mode was requested, and
an assertion that accepted that would assert nothing on either platform.
Every remaining red in the affected selection was measured against a detached
origin/main worktree at the same base SHA: 325 failing/erroring ids on each side,
identical sets.
Three advisory findings on the third head, all on claims this change wrote:
* The cleanup lifecycle is named accurately. _prune_stale_session_token_files
runs from cleanup_orphaned_sessions, which session.py documents as startup and
graceful shutdown only, so "periodic sweep" overstated it. Both docstrings now
say what that costs: a gateway running for a month prunes nothing in between,
and the bound is one mapping per session started since the last boot or clean
stop. Deliberate -- what is owed is bounding accumulation rather than prompt
removal, and a boot-time pass covers the case a teardown hook structurally
cannot, a gateway killed without running one. Pruning still cannot cost a live
session its identity at any cadence, because the mapping is republished at the
start of every turn before anything in it can call a tool.
* The forgery claim states the trust root's real fencing. security.md classifies
sel_hmac.key VISIBLE: no OS fence, no bash-layer fence, and a spawned shell
reaches a file through an open() that never routes through the tool gate.
is_sensitive_path refuses the leaf on the FILE-TOOL path and that is the whole
of it, so all three statements -- the module docstring and both docs -- now say
forgery is blocked against the file tools and not against a shell, name the
residual as shared with the SEL audit chain (same key, same gap), and cite
security.md's own remedy: move the in-sandbox reader behind the gateway so the
leaf can become HIDDEN, never another path matcher. A shell that can read the
key can also mint a local API token and skip client-side resolution, so this
protocol is not the narrow point. Rounding that up would have handed the
SO_PEERCRED follow-up an inaccurate baseline.
* THREE pins move, not two. The load_session/create_session parity comparison
now excludes the per-session identity env, and it belongs in that list rather
than only in the Windows-findings note. Equality on that field asserted that
two DIFFERENT sessions were given the same token, which must never hold; what
remains asserted is the stub SET, with command, args and every other env pair
still compared byte-for-byte.
The parity ratchet keeps seeing the token, not just its shape. Excluding the
per-session pair from BOTH sides of the load/new comparison dropped the PRESENCE
assertion along with the value one, so it would have passed just as happily if
load_session stopped carrying a token at all. Repaired rather than reverted, since
reverting restores an equality that asserts two DIFFERENT sessions share a token:
_without_identity_env now rewrites the pair to a fixed placeholder instead of
removing it, so an element with no token still differs from one with a token, and
_identity_tokens asserts separately that every re-declared element carries one and
that the two sessions' tokens differ. Both regressions now fail the class -- the
blind spot (load_session skipping attach_stub_session_token, 1 of 12) and the
un-pooling case it already guarded (an empty re-declared array, 3 of 12).
publish_turn_identity's single provider lookup is its own change rather than a
footnote to the Windows fixes. The token publication had ADDED a second
sessions.get_provider() beside the one the stub re-claim already did, so this
returns the per-turn path to one lookup rather than introducing an optimisation;
_provider_inner exists because both steps then reach the provider surface the same
way through getattr, and two copies of that resolution is how they drift.
Rebased onto 780e75e (main gained 9 commits). Both conflicts were the same
shape -- main and this branch each adding one import at the same line
(recovery.ladder.InfraError vs session_token_sig.schedule_session_token_publish;
metrics.events.CHILD_PERMISSION_DENIED vs mcp_gateway.claim.STUB_SESSION_TOKEN_ENV)
-- and both sides are kept. Re-measured against a base worktree at the new SHA:
325 failing/erroring ids on each side, identical sets.
The child env carries the token unconditionally; only the fallback key is
conditioned. Treating the pair symmetrically broke the case this change exists for:
a warm-pool client is spawned with NO session key -- that is what makes it
poolable -- and a child's environment is fixed at spawn, so withholding the token
there stripped it from exactly the children whose identity has to survive a
rekey(), with nothing able to add it back afterwards. The token is set regardless
because it is minted in __init__ and its signed mapping is published once the key
becomes known, so a child holding a token and no key still resolves through the
mapping to whichever session claimed the process. The KEY stays conditioned because
it is a value rather than a pointer: an inherited one names a session this client is
not serving and the resolver would read it as identity, while the same token names
the current owner after every rekey. An inherited token is OVERWRITTEN rather than
dropped, so a reused env mapping leaves carrying this client's; an absent one is not
carried as an empty value, which the resolver would try first and never verify.
Two reds on this head belong to main rather than to this branch, both introduced by
9ab334b (fix(cloud): preserve Identity Center login through managed launch,
#9840), one of the nine commits this branch rebased onto:
* Backend Lint & Type Check reports F401 'json' imported but unused in
src/kiro_crew/dashboard/handlers/sessions.py, a file this diff does not touch
and which that commit rewrote. Measured rather than asserted: whole-tree flake8
output is byte-identical between this branch and a worktree at the base SHA.
* Backend Tests (Windows) shard 3 fails two protocol assertions in
test_fargate_launch_engine.py over begin_signin gaining a login_target
parameter -- again that commit's surface, and again untouched here. The file
passes 34/34 on Linux in both worktrees.
Rebased onto 04727eb, which main had reached 24 commits past the previous base.
The rebase was clean. Two things it settles:
* 7d1810d (fix(dashboard): drop the unused json import left by #9840, #11415)
removes the F401 this branch was reporting as main's, which is what that
reading predicted.
* 039d3e8 (feat(ledger): declare the session entry types and validate data on
write, #11317) is where the LedgerError "data.agent / data.actor: is required
and absent" failures come from, and 9ab334b is where the
test_fargate_launch_engine begin_signin/login_target ones come from. Neither
file is in this diff, and both reproduce identically at the base: over
test_ledger_kinds, test_ledger_retention, test_fargate_launch_engine and
test_remove_slot_for_history_key the failing/erroring id sets are 48 on each
side and equal.
Checks run against refs/pull/N/merge rather than against this branch's base, so
main's own breakage lands in this PR's results whatever this branch is rebased
onto. The measurement above is what tells the two apart.
…switch
One of Crew's own MCP servers can only learn WHICH session is calling it through a
channel that needs the shared MCP gateway: the per-session token minted for
gatewayd rides stub entries alone, and gatewayd is its only reader. On a default
install -- no stub roster, no daemon, pooling off -- there is no per-session
channel at all, so the strict resolver falls back to KIROCREW_SESSION_KEY, which is
wrong by construction in the two topologies that matter most. After a warm-pool
rekey the env a child was spawned with names a different session; under spawn_run
session sharing one kiro-cli process hosts N ACP sessions, so the env var, the
session_pid file and a /proc walk all answer with the PARENT for a subagent's
server.
Give the token a second reader that needs no daemon.
* session_token_sig.py publishes token -> session_key to ONE MAC-signed file per
mapping, named by sha256(token) so a directory listing leaks no bearer name.
The MAC covers "<token>:<body>" under a subkey derived from the SEL trust root
with a domain label distinct from the pid sidecar's -- both protocols sign an
"<identifier>:<session_key>" message, so without the split a pid sidecar for
pid N would verify as a token sidecar for a token spelled N. The hardened
reader and key loader are imported from session_pid_sig rather than copied, so
the two sidecars' read discipline cannot drift apart.
* The token is minted unconditionally. A reachable gatewayd socket is not a
precondition, because gatewayd is not the only reader; the socket gates the
CLAIM alone.
* It rides every control-plane element, through the one owner of that question
(providers/mirrors/identity.control_plane_identity_env, shared by codex,
opencode and goose), plus the member-dispatch element and the child env of a
one-session process (AcpClient._apply_session_identity_env, which serves the
kiro backend among others). KIROCREW_SESSION_KEY rides beside it as the
fallback for the one case the token cannot cover: no SEL trust root to sign a
mapping with. The SHARED kiro runtime has no per-session carrier -- its
control-plane servers reach kiro-cli through --agent rather than a session
array and its process multiplexes N sessions -- so identity there is what it is
for every non-token source, and strict_identity_diagnosis names the missing
channel. Injecting session-level control-plane entries would give it one at the
cost of widening the tool surface, since such an element outranks the spec
entry it shadows while carrying neither its tools allowlist nor its
disabledTools; that is a tool-surface decision rather than a carriage one.
* Both resolvers read the token ABOVE the env var, because where the two
disagree the env var is the stale one. The gateway's per-call caller context
still outranks both, being stamped per call.
* Published at session/new and re-published on every rekey() and every turn
(messaging.identity, the existing single writer), which is what makes a
warm-pool claim visible to an already-running MCP child. Retraction is the
age-based sweep in session_pid.py and only that: a teardown hook cannot reach a
gateway that dies without running one, and pruning cannot cost a live session
its identity because republication precedes every tool call in a turn.
No new config key, and nothing about pooling changes: stub_servers, enabled and
gatewayd behaviour are untouched.
Trust boundary, the same one the env var already has: forgery, cross-token replay,
in-place tampering and symlink planting are blocked; a same-uid process reading the
mapping directory is not, and is not meant to be -- it can already read the
session_pid files and present another session's key through the env var.
Two existing pins move, both because the change makes their premise false rather
than to make a test pass:
* test_no_stub_entries_means_no_token_and_no_claim asserted ([], "") under
"nothing to name, and nothing that would read the name". The second half does
not hold once the token has a file-backed reader. Renamed and re-pinned to the
new contract, keeping the half that does hold: no stub entries means no claim.
* test_identity_topology's session_pid call-site ratchet flags
session_token_sig.py, which appears in its scan only because it imports the pid
sidecar's reader and contrasts the two contracts. Registered with its role and
with why a pid-view parametrization has nothing to vary here: it reads no pid
at all, which is the property that makes it namespace-insensitive.
schedule_session_token_publish type-checks both arguments rather than only
truth-checking them, as schedule_claim does: every caller reads the token off a
session handle with getattr, and a non-string reaching the hash would raise
TypeError out of rekey() -- a warm-pool claim failing because of an identity side
effect is strictly worse than the claim proceeding without one.
Three log messages carry a nosemgrep suppression with its reason, matching the
four precedents in auth/store.py: the logger-credential-disclosure rule matches on
the word "token" in the message literal, while the arguments are a session key and
a sha256 digest. The token itself is never passed to a logger in this change.
Tests: 46 across the mapping protocol and the wiring. Each of seven injected
anti-patterns -- token read below the env var, the pid domain label, the mint
re-gated on a socket, the token withheld from the element env, the MAC comparison
skipped, the child env carrying the key without the token, and an unkeyed child
keeping a stale token -- was verified to fail them (pytest exit 1 with real failure
counts, never exit 4), so none is vacuous.
Windows CI adjudicated four consequences of the unconditional mint that a
diff-gated Linux run had skipped. All eight Windows shards are green on main at
this base, so none of these was pre-existing:
* The harness wire goldens gain an env array on session/load's control-plane
elements: kirocrew-core and kirocrew-cron now carry
KIROCREW_STUB_SESSION_TOKEN there. That is the intended product delta -- the
token rides the control plane -- and it reaches session/load and not
session/new in this capture only because the capture hands session/new an
explicit roster, which create_session deliberately does not re-key. The
capture pins the token the way it already pins the work dir and the session
ids, because a value minted from secrets can never match a golden twice;
pinning the INPUT keeps the golden a byte gate over the whole element, env
pair included, rather than scrubbing the output and gating less.
* test_load_session_redeclares_pooled_stubs compared session/load's array to
session/new's byte-for-byte. Each session start mints its own token and those
are two different sessions, so the comparison now excludes the per-session
identity env and nothing else: the parity it guards is the stub SET, since
re-declaring a different one is what silently un-pools a resumed session, and
a per-session credential is not a server. Verified still load-bearing --
making load_session re-declare an empty array fails it.
* publish_turn_identity resolved the provider twice, because the token
publication added a second sessions.get_provider() beside the one the stub
re-claim already did. One lookup now serves both, which is what a per-turn
hot path should cost and restores the call count a Windows shard asserting an
allocation sequence was pinned to.
* test_owner_only_mode asserted POSIX permission bits. Skipped on Windows
rather than loosened: NTFS carries an ACL and os.chmod moves only the
read-only flag there, so the value reads 666 whatever mode was requested, and
an assertion that accepted that would assert nothing on either platform.
Every remaining red in the affected selection was measured against a detached
origin/main worktree at the same base SHA: 325 failing/erroring ids on each side,
identical sets.
Three advisory findings on the third head, all on claims this change wrote:
* The cleanup lifecycle is named accurately. _prune_stale_session_token_files
runs from cleanup_orphaned_sessions, which session.py documents as startup and
graceful shutdown only, so "periodic sweep" overstated it. Both docstrings now
say what that costs: a gateway running for a month prunes nothing in between,
and the bound is one mapping per session started since the last boot or clean
stop. Deliberate -- what is owed is bounding accumulation rather than prompt
removal, and a boot-time pass covers the case a teardown hook structurally
cannot, a gateway killed without running one. Pruning still cannot cost a live
session its identity at any cadence, because the mapping is republished at the
start of every turn before anything in it can call a tool.
* The forgery claim states the trust root's real fencing. security.md classifies
sel_hmac.key VISIBLE: no OS fence, no bash-layer fence, and a spawned shell
reaches a file through an open() that never routes through the tool gate.
is_sensitive_path refuses the leaf on the FILE-TOOL path and that is the whole
of it, so all three statements -- the module docstring and both docs -- now say
forgery is blocked against the file tools and not against a shell, name the
residual as shared with the SEL audit chain (same key, same gap), and cite
security.md's own remedy: move the in-sandbox reader behind the gateway so the
leaf can become HIDDEN, never another path matcher. A shell that can read the
key can also mint a local API token and skip client-side resolution, so this
protocol is not the narrow point. Rounding that up would have handed the
SO_PEERCRED follow-up an inaccurate baseline.
* THREE pins move, not two. The load_session/create_session parity comparison
now excludes the per-session identity env, and it belongs in that list rather
than only in the Windows-findings note. Equality on that field asserted that
two DIFFERENT sessions were given the same token, which must never hold; what
remains asserted is the stub SET, with command, args and every other env pair
still compared byte-for-byte.
The parity ratchet keeps seeing the token, not just its shape. Excluding the
per-session pair from BOTH sides of the load/new comparison dropped the PRESENCE
assertion along with the value one, so it would have passed just as happily if
load_session stopped carrying a token at all. Repaired rather than reverted, since
reverting restores an equality that asserts two DIFFERENT sessions share a token:
_without_identity_env now rewrites the pair to a fixed placeholder instead of
removing it, so an element with no token still differs from one with a token, and
_identity_tokens asserts separately that every re-declared element carries one and
that the two sessions' tokens differ. Both regressions now fail the class -- the
blind spot (load_session skipping attach_stub_session_token, 1 of 12) and the
un-pooling case it already guarded (an empty re-declared array, 3 of 12).
publish_turn_identity's single provider lookup is its own change rather than a
footnote to the Windows fixes. The token publication had ADDED a second
sessions.get_provider() beside the one the stub re-claim already did, so this
returns the per-turn path to one lookup rather than introducing an optimisation;
_provider_inner exists because both steps then reach the provider surface the same
way through getattr, and two copies of that resolution is how they drift.
Rebased onto 780e75e (main gained 9 commits). Both conflicts were the same
shape -- main and this branch each adding one import at the same line
(recovery.ladder.InfraError vs session_token_sig.schedule_session_token_publish;
metrics.events.CHILD_PERMISSION_DENIED vs mcp_gateway.claim.STUB_SESSION_TOKEN_ENV)
-- and both sides are kept. Re-measured against a base worktree at the new SHA:
325 failing/erroring ids on each side, identical sets.
The child env carries the token unconditionally; only the fallback key is
conditioned. Treating the pair symmetrically broke the case this change exists for:
a warm-pool client is spawned with NO session key -- that is what makes it
poolable -- and a child's environment is fixed at spawn, so withholding the token
there stripped it from exactly the children whose identity has to survive a
rekey(), with nothing able to add it back afterwards. The token is set regardless
because it is minted in __init__ and its signed mapping is published once the key
becomes known, so a child holding a token and no key still resolves through the
mapping to whichever session claimed the process. The KEY stays conditioned because
it is a value rather than a pointer: an inherited one names a session this client is
not serving and the resolver would read it as identity, while the same token names
the current owner after every rekey. An inherited token is OVERWRITTEN rather than
dropped, so a reused env mapping leaves carrying this client's; an absent one is not
carried as an empty value, which the resolver would try first and never verify.
Two reds on this head belong to main rather than to this branch, both introduced by
9ab334b (fix(cloud): preserve Identity Center login through managed launch,
* Backend Lint & Type Check reports F401 'json' imported but unused in
src/kiro_crew/dashboard/handlers/sessions.py, a file this diff does not touch
and which that commit rewrote. Measured rather than asserted: whole-tree flake8
output is byte-identical between this branch and a worktree at the base SHA.
* Backend Tests (Windows) shard 3 fails two protocol assertions in
test_fargate_launch_engine.py over begin_signin gaining a login_target
parameter -- again that commit's surface, and again untouched here. The file
passes 34/34 on Linux in both worktrees.
Rebased onto 04727eb, which main had reached 24 commits past the previous base.
The rebase was clean. Two things it settles:
* 7d1810d (fix(dashboard): drop the unused json import left by #9840, #11415)
removes the F401 this branch was reporting as main's, which is what that
reading predicted.
* 039d3e8 (feat(ledger): declare the session entry types and validate data on
write, #11317) is where the LedgerError "data.agent / data.actor: is required
and absent" failures come from, and 9ab334b is where the
test_fargate_launch_engine begin_signin/login_target ones come from. Neither
file is in this diff, and both reproduce identically at the base: over
test_ledger_kinds, test_ledger_retention, test_fargate_launch_engine and
test_remove_slot_for_history_key the failing/erroring id sets are 48 on each
side and equal.
Checks run against refs/pull/N/merge rather than against this branch's base, so
main's own breakage lands in this PR's results whatever this branch is rebased
onto. The measurement above is what tells the two apart.
…switch
One of Crew's own MCP servers can only learn WHICH session is calling it through a
channel that needs the shared MCP gateway: the per-session token minted for
gatewayd rides stub entries alone, and gatewayd is its only reader. On a default
install -- no stub roster, no daemon, pooling off -- there is no per-session
channel at all, so the strict resolver falls back to KIROCREW_SESSION_KEY, which is
wrong by construction in the two topologies that matter most. After a warm-pool
rekey the env a child was spawned with names a different session; under spawn_run
session sharing one kiro-cli process hosts N ACP sessions, so the env var, the
session_pid file and a /proc walk all answer with the PARENT for a subagent's
server.
Give the token a second reader that needs no daemon.
* session_token_sig.py publishes token -> session_key to ONE MAC-signed file per
mapping, named by sha256(token) so a directory listing leaks no bearer name.
The MAC covers "<token>:<body>" under a subkey derived from the SEL trust root
with a domain label distinct from the pid sidecar's -- both protocols sign an
"<identifier>:<session_key>" message, so without the split a pid sidecar for
pid N would verify as a token sidecar for a token spelled N. The hardened
reader and key loader are imported from session_pid_sig rather than copied, so
the two sidecars' read discipline cannot drift apart.
* The token is minted unconditionally. A reachable gatewayd socket is not a
precondition, because gatewayd is not the only reader; the socket gates the
CLAIM alone.
* It rides every control-plane element, through the one owner of that question
(providers/mirrors/identity.control_plane_identity_env, shared by codex,
opencode and goose), plus the member-dispatch element and the child env of a
one-session process (AcpClient._apply_session_identity_env, which serves the
kiro backend among others). KIROCREW_SESSION_KEY rides beside it as the
fallback for the one case the token cannot cover: no SEL trust root to sign a
mapping with. The SHARED kiro runtime has no per-session carrier -- its
control-plane servers reach kiro-cli through --agent rather than a session
array and its process multiplexes N sessions -- so identity there is what it is
for every non-token source, and strict_identity_diagnosis names the missing
channel. Injecting session-level control-plane entries would give it one at the
cost of widening the tool surface, since such an element outranks the spec
entry it shadows while carrying neither its tools allowlist nor its
disabledTools; that is a tool-surface decision rather than a carriage one.
* Both resolvers read the token ABOVE the env var, because where the two
disagree the env var is the stale one. The gateway's per-call caller context
still outranks both, being stamped per call.
* Published at session/new and re-published on every rekey() and every turn
(messaging.identity, the existing single writer), which is what makes a
warm-pool claim visible to an already-running MCP child. Retraction is the
age-based sweep in session_pid.py and only that: a teardown hook cannot reach a
gateway that dies without running one, and pruning cannot cost a live session
its identity because republication precedes every tool call in a turn.
No new config key, and nothing about pooling changes: stub_servers, enabled and
gatewayd behaviour are untouched.
Trust boundary, the same one the env var already has: forgery, cross-token replay,
in-place tampering and symlink planting are blocked; a same-uid process reading the
mapping directory is not, and is not meant to be -- it can already read the
session_pid files and present another session's key through the env var.
Two existing pins move, both because the change makes their premise false rather
than to make a test pass:
* test_no_stub_entries_means_no_token_and_no_claim asserted ([], "") under
"nothing to name, and nothing that would read the name". The second half does
not hold once the token has a file-backed reader. Renamed and re-pinned to the
new contract, keeping the half that does hold: no stub entries means no claim.
* test_identity_topology's session_pid call-site ratchet flags
session_token_sig.py, which appears in its scan only because it imports the pid
sidecar's reader and contrasts the two contracts. Registered with its role and
with why a pid-view parametrization has nothing to vary here: it reads no pid
at all, which is the property that makes it namespace-insensitive.
schedule_session_token_publish type-checks both arguments rather than only
truth-checking them, as schedule_claim does: every caller reads the token off a
session handle with getattr, and a non-string reaching the hash would raise
TypeError out of rekey() -- a warm-pool claim failing because of an identity side
effect is strictly worse than the claim proceeding without one.
Three log messages carry a nosemgrep suppression with its reason, matching the
four precedents in auth/store.py: the logger-credential-disclosure rule matches on
the word "token" in the message literal, while the arguments are a session key and
a sha256 digest. The token itself is never passed to a logger in this change.
Tests: 46 across the mapping protocol and the wiring. Each of seven injected
anti-patterns -- token read below the env var, the pid domain label, the mint
re-gated on a socket, the token withheld from the element env, the MAC comparison
skipped, the child env carrying the key without the token, and an unkeyed child
keeping a stale token -- was verified to fail them (pytest exit 1 with real failure
counts, never exit 4), so none is vacuous.
Windows CI adjudicated four consequences of the unconditional mint that a
diff-gated Linux run had skipped. All eight Windows shards are green on main at
this base, so none of these was pre-existing:
* The harness wire goldens gain an env array on session/load's control-plane
elements: kirocrew-core and kirocrew-cron now carry
KIROCREW_STUB_SESSION_TOKEN there. That is the intended product delta -- the
token rides the control plane -- and it reaches session/load and not
session/new in this capture only because the capture hands session/new an
explicit roster, which create_session deliberately does not re-key. The
capture pins the token the way it already pins the work dir and the session
ids, because a value minted from secrets can never match a golden twice;
pinning the INPUT keeps the golden a byte gate over the whole element, env
pair included, rather than scrubbing the output and gating less.
* test_load_session_redeclares_pooled_stubs compared session/load's array to
session/new's byte-for-byte. Each session start mints its own token and those
are two different sessions, so the comparison now excludes the per-session
identity env and nothing else: the parity it guards is the stub SET, since
re-declaring a different one is what silently un-pools a resumed session, and
a per-session credential is not a server. Verified still load-bearing --
making load_session re-declare an empty array fails it.
* publish_turn_identity resolved the provider twice, because the token
publication added a second sessions.get_provider() beside the one the stub
re-claim already did. One lookup now serves both, which is what a per-turn
hot path should cost and restores the call count a Windows shard asserting an
allocation sequence was pinned to.
* test_owner_only_mode asserted POSIX permission bits. Skipped on Windows
rather than loosened: NTFS carries an ACL and os.chmod moves only the
read-only flag there, so the value reads 666 whatever mode was requested, and
an assertion that accepted that would assert nothing on either platform.
Every remaining red in the affected selection was measured against a detached
origin/main worktree at the same base SHA: 325 failing/erroring ids on each side,
identical sets.
Three advisory findings on the third head, all on claims this change wrote:
* The cleanup lifecycle is named accurately. _prune_stale_session_token_files
runs from cleanup_orphaned_sessions, which session.py documents as startup and
graceful shutdown only, so "periodic sweep" overstated it. Both docstrings now
say what that costs: a gateway running for a month prunes nothing in between,
and the bound is one mapping per session started since the last boot or clean
stop. Deliberate -- what is owed is bounding accumulation rather than prompt
removal, and a boot-time pass covers the case a teardown hook structurally
cannot, a gateway killed without running one. Pruning still cannot cost a live
session its identity at any cadence, because the mapping is republished at the
start of every turn before anything in it can call a tool.
* The forgery claim states the trust root's real fencing. security.md classifies
sel_hmac.key VISIBLE: no OS fence, no bash-layer fence, and a spawned shell
reaches a file through an open() that never routes through the tool gate.
is_sensitive_path refuses the leaf on the FILE-TOOL path and that is the whole
of it, so all three statements -- the module docstring and both docs -- now say
forgery is blocked against the file tools and not against a shell, name the
residual as shared with the SEL audit chain (same key, same gap), and cite
security.md's own remedy: move the in-sandbox reader behind the gateway so the
leaf can become HIDDEN, never another path matcher. A shell that can read the
key can also mint a local API token and skip client-side resolution, so this
protocol is not the narrow point. Rounding that up would have handed the
SO_PEERCRED follow-up an inaccurate baseline.
* THREE pins move, not two. The load_session/create_session parity comparison
now excludes the per-session identity env, and it belongs in that list rather
than only in the Windows-findings note. Equality on that field asserted that
two DIFFERENT sessions were given the same token, which must never hold; what
remains asserted is the stub SET, with command, args and every other env pair
still compared byte-for-byte.
The parity ratchet keeps seeing the token, not just its shape. Excluding the
per-session pair from BOTH sides of the load/new comparison dropped the PRESENCE
assertion along with the value one, so it would have passed just as happily if
load_session stopped carrying a token at all. Repaired rather than reverted, since
reverting restores an equality that asserts two DIFFERENT sessions share a token:
_without_identity_env now rewrites the pair to a fixed placeholder instead of
removing it, so an element with no token still differs from one with a token, and
_identity_tokens asserts separately that every re-declared element carries one and
that the two sessions' tokens differ. Both regressions now fail the class -- the
blind spot (load_session skipping attach_stub_session_token, 1 of 12) and the
un-pooling case it already guarded (an empty re-declared array, 3 of 12).
publish_turn_identity's single provider lookup is its own change rather than a
footnote to the Windows fixes. The token publication had ADDED a second
sessions.get_provider() beside the one the stub re-claim already did, so this
returns the per-turn path to one lookup rather than introducing an optimisation;
_provider_inner exists because both steps then reach the provider surface the same
way through getattr, and two copies of that resolution is how they drift.
Rebased onto 780e75e (main gained 9 commits). Both conflicts were the same
shape -- main and this branch each adding one import at the same line
(recovery.ladder.InfraError vs session_token_sig.schedule_session_token_publish;
metrics.events.CHILD_PERMISSION_DENIED vs mcp_gateway.claim.STUB_SESSION_TOKEN_ENV)
-- and both sides are kept. Re-measured against a base worktree at the new SHA:
325 failing/erroring ids on each side, identical sets.
The child env carries the token unconditionally; only the fallback key is
conditioned. Treating the pair symmetrically broke the case this change exists for:
a warm-pool client is spawned with NO session key -- that is what makes it
poolable -- and a child's environment is fixed at spawn, so withholding the token
there stripped it from exactly the children whose identity has to survive a
rekey(), with nothing able to add it back afterwards. The token is set regardless
because it is minted in __init__ and its signed mapping is published once the key
becomes known, so a child holding a token and no key still resolves through the
mapping to whichever session claimed the process. The KEY stays conditioned because
it is a value rather than a pointer: an inherited one names a session this client is
not serving and the resolver would read it as identity, while the same token names
the current owner after every rekey. An inherited token is OVERWRITTEN rather than
dropped, so a reused env mapping leaves carrying this client's; an absent one is not
carried as an empty value, which the resolver would try first and never verify.
Two reds on this head belong to main rather than to this branch, both introduced by
9ab334b (fix(cloud): preserve Identity Center login through managed launch,
#9840), one of the nine commits this branch rebased onto:
* Backend Lint & Type Check reports F401 'json' imported but unused in
src/kiro_crew/dashboard/handlers/sessions.py, a file this diff does not touch
and which that commit rewrote. Measured rather than asserted: whole-tree flake8
output is byte-identical between this branch and a worktree at the base SHA.
* Backend Tests (Windows) shard 3 fails two protocol assertions in
test_fargate_launch_engine.py over begin_signin gaining a login_target
parameter -- again that commit's surface, and again untouched here. The file
passes 34/34 on Linux in both worktrees.
Rebased onto 04727eb, which main had reached 24 commits past the previous base.
The rebase was clean. Two things it settles:
* 7d1810d (fix(dashboard): drop the unused json import left by #9840, #11415)
removes the F401 this branch was reporting as main's, which is what that
reading predicted.
* 039d3e8 (feat(ledger): declare the session entry types and validate data on
write, #11317) is where the LedgerError "data.agent / data.actor: is required
and absent" failures come from, and 9ab334b is where the
test_fargate_launch_engine begin_signin/login_target ones come from. Neither
file is in this diff, and both reproduce identically at the base: over
test_ledger_kinds, test_ledger_retention, test_fargate_launch_engine and
test_remove_slot_for_history_key the failing/erroring id sets are 48 on each
side and equal.
Checks run against refs/pull/N/merge rather than against this branch's base, so
main's own breakage lands in this PR's results whatever this branch is rebased
onto. The measurement above is what tells the two apart.
…switch
One of Crew's own MCP servers can only learn WHICH session is calling it through a
channel that needs the shared MCP gateway: the per-session token minted for
gatewayd rides stub entries alone, and gatewayd is its only reader. On a default
install -- no stub roster, no daemon, pooling off -- there is no per-session
channel at all, so the strict resolver falls back to KIROCREW_SESSION_KEY, which is
wrong by construction in the two topologies that matter most. After a warm-pool
rekey the env a child was spawned with names a different session; under spawn_run
session sharing one kiro-cli process hosts N ACP sessions, so the env var, the
session_pid file and a /proc walk all answer with the PARENT for a subagent's
server.
Give the token a second reader that needs no daemon.
* session_token_sig.py publishes token -> session_key to ONE MAC-signed file per
mapping, named by sha256(token) so a directory listing leaks no bearer name.
The MAC covers "<token>:<body>" under a subkey derived from the SEL trust root
with a domain label distinct from the pid sidecar's -- both protocols sign an
"<identifier>:<session_key>" message, so without the split a pid sidecar for
pid N would verify as a token sidecar for a token spelled N. The hardened
reader and key loader are imported from session_pid_sig rather than copied, so
the two sidecars' read discipline cannot drift apart.
* The token is minted unconditionally. A reachable gatewayd socket is not a
precondition, because gatewayd is not the only reader; the socket gates the
CLAIM alone.
* It rides every control-plane element, through the one owner of that question
(providers/mirrors/identity.control_plane_identity_env, shared by codex,
opencode and goose), plus the member-dispatch element and the child env of a
one-session process (AcpClient._apply_session_identity_env, which serves the
kiro backend among others). KIROCREW_SESSION_KEY rides beside it as the
fallback for the one case the token cannot cover: no SEL trust root to sign a
mapping with. The SHARED kiro runtime has no per-session carrier -- its
control-plane servers reach kiro-cli through --agent rather than a session
array and its process multiplexes N sessions -- so identity there is what it is
for every non-token source, and strict_identity_diagnosis names the missing
channel. Injecting session-level control-plane entries would give it one at the
cost of widening the tool surface, since such an element outranks the spec
entry it shadows while carrying neither its tools allowlist nor its
disabledTools; that is a tool-surface decision rather than a carriage one.
* Both resolvers read the token ABOVE the env var, because where the two
disagree the env var is the stale one. The gateway's per-call caller context
still outranks both, being stamped per call.
* Published at session/new and re-published on every rekey() and every turn
(messaging.identity, the existing single writer), which is what makes a
warm-pool claim visible to an already-running MCP child. Retraction is the
age-based sweep in session_pid.py and only that: a teardown hook cannot reach a
gateway that dies without running one, and pruning cannot cost a live session
its identity because republication precedes every tool call in a turn.
No new config key, and nothing about pooling changes: stub_servers, enabled and
gatewayd behaviour are untouched.
Trust boundary, the same one the env var already has: forgery, cross-token replay,
in-place tampering and symlink planting are blocked; a same-uid process reading the
mapping directory is not, and is not meant to be -- it can already read the
session_pid files and present another session's key through the env var.
Two existing pins move, both because the change makes their premise false rather
than to make a test pass:
* test_no_stub_entries_means_no_token_and_no_claim asserted ([], "") under
"nothing to name, and nothing that would read the name". The second half does
not hold once the token has a file-backed reader. Renamed and re-pinned to the
new contract, keeping the half that does hold: no stub entries means no claim.
* test_identity_topology's session_pid call-site ratchet flags
session_token_sig.py, which appears in its scan only because it imports the pid
sidecar's reader and contrasts the two contracts. Registered with its role and
with why a pid-view parametrization has nothing to vary here: it reads no pid
at all, which is the property that makes it namespace-insensitive.
schedule_session_token_publish type-checks both arguments rather than only
truth-checking them, as schedule_claim does: every caller reads the token off a
session handle with getattr, and a non-string reaching the hash would raise
TypeError out of rekey() -- a warm-pool claim failing because of an identity side
effect is strictly worse than the claim proceeding without one.
Three log messages carry a nosemgrep suppression with its reason, matching the
four precedents in auth/store.py: the logger-credential-disclosure rule matches on
the word "token" in the message literal, while the arguments are a session key and
a sha256 digest. The token itself is never passed to a logger in this change.
Tests: 46 across the mapping protocol and the wiring. Each of seven injected
anti-patterns -- token read below the env var, the pid domain label, the mint
re-gated on a socket, the token withheld from the element env, the MAC comparison
skipped, the child env carrying the key without the token, and an unkeyed child
keeping a stale token -- was verified to fail them (pytest exit 1 with real failure
counts, never exit 4), so none is vacuous.
Windows CI adjudicated four consequences of the unconditional mint that a
diff-gated Linux run had skipped. All eight Windows shards are green on main at
this base, so none of these was pre-existing:
* The harness wire goldens gain an env array on session/load's control-plane
elements: kirocrew-core and kirocrew-cron now carry
KIROCREW_STUB_SESSION_TOKEN there. That is the intended product delta -- the
token rides the control plane -- and it reaches session/load and not
session/new in this capture only because the capture hands session/new an
explicit roster, which create_session deliberately does not re-key. The
capture pins the token the way it already pins the work dir and the session
ids, because a value minted from secrets can never match a golden twice;
pinning the INPUT keeps the golden a byte gate over the whole element, env
pair included, rather than scrubbing the output and gating less.
* test_load_session_redeclares_pooled_stubs compared session/load's array to
session/new's byte-for-byte. Each session start mints its own token and those
are two different sessions, so the comparison now excludes the per-session
identity env and nothing else: the parity it guards is the stub SET, since
re-declaring a different one is what silently un-pools a resumed session, and
a per-session credential is not a server. Verified still load-bearing --
making load_session re-declare an empty array fails it.
* publish_turn_identity resolved the provider twice, because the token
publication added a second sessions.get_provider() beside the one the stub
re-claim already did. One lookup now serves both, which is what a per-turn
hot path should cost and restores the call count a Windows shard asserting an
allocation sequence was pinned to.
* test_owner_only_mode asserted POSIX permission bits. Skipped on Windows
rather than loosened: NTFS carries an ACL and os.chmod moves only the
read-only flag there, so the value reads 666 whatever mode was requested, and
an assertion that accepted that would assert nothing on either platform.
Every remaining red in the affected selection was measured against a detached
origin/main worktree at the same base SHA: 325 failing/erroring ids on each side,
identical sets.
Three advisory findings on the third head, all on claims this change wrote:
* The cleanup lifecycle is named accurately. _prune_stale_session_token_files
runs from cleanup_orphaned_sessions, which session.py documents as startup and
graceful shutdown only, so "periodic sweep" overstated it. Both docstrings now
say what that costs: a gateway running for a month prunes nothing in between,
and the bound is one mapping per session started since the last boot or clean
stop. Deliberate -- what is owed is bounding accumulation rather than prompt
removal, and a boot-time pass covers the case a teardown hook structurally
cannot, a gateway killed without running one. Pruning still cannot cost a live
session its identity at any cadence, because the mapping is republished at the
start of every turn before anything in it can call a tool.
* The forgery claim states the trust root's real fencing. security.md classifies
sel_hmac.key VISIBLE: no OS fence, no bash-layer fence, and a spawned shell
reaches a file through an open() that never routes through the tool gate.
is_sensitive_path refuses the leaf on the FILE-TOOL path and that is the whole
of it, so all three statements -- the module docstring and both docs -- now say
forgery is blocked against the file tools and not against a shell, name the
residual as shared with the SEL audit chain (same key, same gap), and cite
security.md's own remedy: move the in-sandbox reader behind the gateway so the
leaf can become HIDDEN, never another path matcher. A shell that can read the
key can also mint a local API token and skip client-side resolution, so this
protocol is not the narrow point. Rounding that up would have handed the
SO_PEERCRED follow-up an inaccurate baseline.
* THREE pins move, not two. The load_session/create_session parity comparison
now excludes the per-session identity env, and it belongs in that list rather
than only in the Windows-findings note. Equality on that field asserted that
two DIFFERENT sessions were given the same token, which must never hold; what
remains asserted is the stub SET, with command, args and every other env pair
still compared byte-for-byte.
The parity ratchet keeps seeing the token, not just its shape. Excluding the
per-session pair from BOTH sides of the load/new comparison dropped the PRESENCE
assertion along with the value one, so it would have passed just as happily if
load_session stopped carrying a token at all. Repaired rather than reverted, since
reverting restores an equality that asserts two DIFFERENT sessions share a token:
_without_identity_env now rewrites the pair to a fixed placeholder instead of
removing it, so an element with no token still differs from one with a token, and
_identity_tokens asserts separately that every re-declared element carries one and
that the two sessions' tokens differ. Both regressions now fail the class -- the
blind spot (load_session skipping attach_stub_session_token, 1 of 12) and the
un-pooling case it already guarded (an empty re-declared array, 3 of 12).
publish_turn_identity's single provider lookup is its own change rather than a
footnote to the Windows fixes. The token publication had ADDED a second
sessions.get_provider() beside the one the stub re-claim already did, so this
returns the per-turn path to one lookup rather than introducing an optimisation;
_provider_inner exists because both steps then reach the provider surface the same
way through getattr, and two copies of that resolution is how they drift.
Rebased onto 780e75e (main gained 9 commits). Both conflicts were the same
shape -- main and this branch each adding one import at the same line
(recovery.ladder.InfraError vs session_token_sig.schedule_session_token_publish;
metrics.events.CHILD_PERMISSION_DENIED vs mcp_gateway.claim.STUB_SESSION_TOKEN_ENV)
-- and both sides are kept. Re-measured against a base worktree at the new SHA:
325 failing/erroring ids on each side, identical sets.
The child env carries the token unconditionally; only the fallback key is
conditioned. Treating the pair symmetrically broke the case this change exists for:
a warm-pool client is spawned with NO session key -- that is what makes it
poolable -- and a child's environment is fixed at spawn, so withholding the token
there stripped it from exactly the children whose identity has to survive a
rekey(), with nothing able to add it back afterwards. The token is set regardless
because it is minted in __init__ and its signed mapping is published once the key
becomes known, so a child holding a token and no key still resolves through the
mapping to whichever session claimed the process. The KEY stays conditioned because
it is a value rather than a pointer: an inherited one names a session this client is
not serving and the resolver would read it as identity, while the same token names
the current owner after every rekey. An inherited token is OVERWRITTEN rather than
dropped, so a reused env mapping leaves carrying this client's; an absent one is not
carried as an empty value, which the resolver would try first and never verify.
Two reds on this head belong to main rather than to this branch, both introduced by
9ab334b (fix(cloud): preserve Identity Center login through managed launch,
#9840), one of the nine commits this branch rebased onto:
* Backend Lint & Type Check reports F401 'json' imported but unused in
src/kiro_crew/dashboard/handlers/sessions.py, a file this diff does not touch
and which that commit rewrote. Measured rather than asserted: whole-tree flake8
output is byte-identical between this branch and a worktree at the base SHA.
* Backend Tests (Windows) shard 3 fails two protocol assertions in
test_fargate_launch_engine.py over begin_signin gaining a login_target
parameter -- again that commit's surface, and again untouched here. The file
passes 34/34 on Linux in both worktrees.
Rebased onto 04727eb, which main had reached 24 commits past the previous base.
The rebase was clean. Two things it settles:
* 7d1810d (fix(dashboard): drop the unused json import left by #9840, #11415)
removes the F401 this branch was reporting as main's, which is what that
reading predicted.
* 039d3e8 (feat(ledger): declare the session entry types and validate data on
write, #11317) is where the LedgerError "data.agent / data.actor: is required
and absent" failures come from, and 9ab334b is where the
test_fargate_launch_engine begin_signin/login_target ones come from. Neither
file is in this diff, and both reproduce identically at the base: over
test_ledger_kinds, test_ledger_retention, test_fargate_launch_engine and
test_remove_slot_for_history_key the failing/erroring id sets are 48 on each
side and equal.
Checks run against refs/pull/N/merge rather than against this branch's base, so
main's own breakage lands in this PR's results whatever this branch is rebased
onto. The measurement above is what tells the two apart.
…switch
One of Crew's own MCP servers can only learn WHICH session is calling it through a
channel that needs the shared MCP gateway: the per-session token minted for
gatewayd rides stub entries alone, and gatewayd is its only reader. On a default
install -- no stub roster, no daemon, pooling off -- there is no per-session
channel at all, so the strict resolver falls back to KIROCREW_SESSION_KEY, which is
wrong by construction in the two topologies that matter most. After a warm-pool
rekey the env a child was spawned with names a different session; under spawn_run
session sharing one kiro-cli process hosts N ACP sessions, so the env var, the
session_pid file and a /proc walk all answer with the PARENT for a subagent's
server.
Give the token a second reader that needs no daemon.
* session_token_sig.py publishes token -> session_key to ONE MAC-signed file per
mapping, named by sha256(token) so a directory listing leaks no bearer name.
The MAC covers "<token>:<body>" under a subkey derived from the SEL trust root
with a domain label distinct from the pid sidecar's -- both protocols sign an
"<identifier>:<session_key>" message, so without the split a pid sidecar for
pid N would verify as a token sidecar for a token spelled N. The hardened
reader and key loader are imported from session_pid_sig rather than copied, so
the two sidecars' read discipline cannot drift apart.
* The token is minted unconditionally. A reachable gatewayd socket is not a
precondition, because gatewayd is not the only reader; the socket gates the
CLAIM alone.
* It rides every control-plane element, through the one owner of that question
(providers/mirrors/identity.control_plane_identity_env, shared by codex,
opencode and goose), plus the member-dispatch element and the child env of a
one-session process (AcpClient._apply_session_identity_env, which serves the
kiro backend among others). KIROCREW_SESSION_KEY rides beside it as the
fallback for the one case the token cannot cover: no SEL trust root to sign a
mapping with. The SHARED kiro runtime has no per-session carrier -- its
control-plane servers reach kiro-cli through --agent rather than a session
array and its process multiplexes N sessions -- so identity there is what it is
for every non-token source, and strict_identity_diagnosis names the missing
channel. Injecting session-level control-plane entries would give it one at the
cost of widening the tool surface, since such an element outranks the spec
entry it shadows while carrying neither its tools allowlist nor its
disabledTools; that is a tool-surface decision rather than a carriage one.
* Both resolvers read the token ABOVE the env var, because where the two
disagree the env var is the stale one. The gateway's per-call caller context
still outranks both, being stamped per call.
* Published at session/new and re-published on every rekey() and every turn
(messaging.identity, the existing single writer), which is what makes a
warm-pool claim visible to an already-running MCP child. Retraction is the
age-based sweep in session_pid.py and only that: a teardown hook cannot reach a
gateway that dies without running one, and pruning cannot cost a live session
its identity because republication precedes every tool call in a turn.
No new config key, and nothing about pooling changes: stub_servers, enabled and
gatewayd behaviour are untouched.
Trust boundary, the same one the env var already has: forgery, cross-token replay,
in-place tampering and symlink planting are blocked; a same-uid process reading the
mapping directory is not, and is not meant to be -- it can already read the
session_pid files and present another session's key through the env var.
Two existing pins move, both because the change makes their premise false rather
than to make a test pass:
* test_no_stub_entries_means_no_token_and_no_claim asserted ([], "") under
"nothing to name, and nothing that would read the name". The second half does
not hold once the token has a file-backed reader. Renamed and re-pinned to the
new contract, keeping the half that does hold: no stub entries means no claim.
* test_identity_topology's session_pid call-site ratchet flags
session_token_sig.py, which appears in its scan only because it imports the pid
sidecar's reader and contrasts the two contracts. Registered with its role and
with why a pid-view parametrization has nothing to vary here: it reads no pid
at all, which is the property that makes it namespace-insensitive.
schedule_session_token_publish type-checks both arguments rather than only
truth-checking them, as schedule_claim does: every caller reads the token off a
session handle with getattr, and a non-string reaching the hash would raise
TypeError out of rekey() -- a warm-pool claim failing because of an identity side
effect is strictly worse than the claim proceeding without one.
Three log messages carry a nosemgrep suppression with its reason, matching the
four precedents in auth/store.py: the logger-credential-disclosure rule matches on
the word "token" in the message literal, while the arguments are a session key and
a sha256 digest. The token itself is never passed to a logger in this change.
Tests: 46 across the mapping protocol and the wiring. Each of seven injected
anti-patterns -- token read below the env var, the pid domain label, the mint
re-gated on a socket, the token withheld from the element env, the MAC comparison
skipped, the child env carrying the key without the token, and an unkeyed child
keeping a stale token -- was verified to fail them (pytest exit 1 with real failure
counts, never exit 4), so none is vacuous.
Windows CI adjudicated four consequences of the unconditional mint that a
diff-gated Linux run had skipped. All eight Windows shards are green on main at
this base, so none of these was pre-existing:
* The harness wire goldens gain an env array on session/load's control-plane
elements: kirocrew-core and kirocrew-cron now carry
KIROCREW_STUB_SESSION_TOKEN there. That is the intended product delta -- the
token rides the control plane -- and it reaches session/load and not
session/new in this capture only because the capture hands session/new an
explicit roster, which create_session deliberately does not re-key. The
capture pins the token the way it already pins the work dir and the session
ids, because a value minted from secrets can never match a golden twice;
pinning the INPUT keeps the golden a byte gate over the whole element, env
pair included, rather than scrubbing the output and gating less.
* test_load_session_redeclares_pooled_stubs compared session/load's array to
session/new's byte-for-byte. Each session start mints its own token and those
are two different sessions, so the comparison now excludes the per-session
identity env and nothing else: the parity it guards is the stub SET, since
re-declaring a different one is what silently un-pools a resumed session, and
a per-session credential is not a server. Verified still load-bearing --
making load_session re-declare an empty array fails it.
* publish_turn_identity resolved the provider twice, because the token
publication added a second sessions.get_provider() beside the one the stub
re-claim already did. One lookup now serves both, which is what a per-turn
hot path should cost and restores the call count a Windows shard asserting an
allocation sequence was pinned to.
* test_owner_only_mode asserted POSIX permission bits. Skipped on Windows
rather than loosened: NTFS carries an ACL and os.chmod moves only the
read-only flag there, so the value reads 666 whatever mode was requested, and
an assertion that accepted that would assert nothing on either platform.
Every remaining red in the affected selection was measured against a detached
origin/main worktree at the same base SHA: 325 failing/erroring ids on each side,
identical sets.
Three advisory findings on the third head, all on claims this change wrote:
* The cleanup lifecycle is named accurately. _prune_stale_session_token_files
runs from cleanup_orphaned_sessions, which session.py documents as startup and
graceful shutdown only, so "periodic sweep" overstated it. Both docstrings now
say what that costs: a gateway running for a month prunes nothing in between,
and the bound is one mapping per session started since the last boot or clean
stop. Deliberate -- what is owed is bounding accumulation rather than prompt
removal, and a boot-time pass covers the case a teardown hook structurally
cannot, a gateway killed without running one. Pruning still cannot cost a live
session its identity at any cadence, because the mapping is republished at the
start of every turn before anything in it can call a tool.
* The forgery claim states the trust root's real fencing. security.md classifies
sel_hmac.key VISIBLE: no OS fence, no bash-layer fence, and a spawned shell
reaches a file through an open() that never routes through the tool gate.
is_sensitive_path refuses the leaf on the FILE-TOOL path and that is the whole
of it, so all three statements -- the module docstring and both docs -- now say
forgery is blocked against the file tools and not against a shell, name the
residual as shared with the SEL audit chain (same key, same gap), and cite
security.md's own remedy: move the in-sandbox reader behind the gateway so the
leaf can become HIDDEN, never another path matcher. A shell that can read the
key can also mint a local API token and skip client-side resolution, so this
protocol is not the narrow point. Rounding that up would have handed the
SO_PEERCRED follow-up an inaccurate baseline.
* THREE pins move, not two. The load_session/create_session parity comparison
now excludes the per-session identity env, and it belongs in that list rather
than only in the Windows-findings note. Equality on that field asserted that
two DIFFERENT sessions were given the same token, which must never hold; what
remains asserted is the stub SET, with command, args and every other env pair
still compared byte-for-byte.
The parity ratchet keeps seeing the token, not just its shape. Excluding the
per-session pair from BOTH sides of the load/new comparison dropped the PRESENCE
assertion along with the value one, so it would have passed just as happily if
load_session stopped carrying a token at all. Repaired rather than reverted, since
reverting restores an equality that asserts two DIFFERENT sessions share a token:
_without_identity_env now rewrites the pair to a fixed placeholder instead of
removing it, so an element with no token still differs from one with a token, and
_identity_tokens asserts separately that every re-declared element carries one and
that the two sessions' tokens differ. Both regressions now fail the class -- the
blind spot (load_session skipping attach_stub_session_token, 1 of 12) and the
un-pooling case it already guarded (an empty re-declared array, 3 of 12).
publish_turn_identity's single provider lookup is its own change rather than a
footnote to the Windows fixes. The token publication had ADDED a second
sessions.get_provider() beside the one the stub re-claim already did, so this
returns the per-turn path to one lookup rather than introducing an optimisation;
_provider_inner exists because both steps then reach the provider surface the same
way through getattr, and two copies of that resolution is how they drift.
Rebased onto 780e75e (main gained 9 commits). Both conflicts were the same
shape -- main and this branch each adding one import at the same line
(recovery.ladder.InfraError vs session_token_sig.schedule_session_token_publish;
metrics.events.CHILD_PERMISSION_DENIED vs mcp_gateway.claim.STUB_SESSION_TOKEN_ENV)
-- and both sides are kept. Re-measured against a base worktree at the new SHA:
325 failing/erroring ids on each side, identical sets.
The child env carries the token unconditionally; only the fallback key is
conditioned. Treating the pair symmetrically broke the case this change exists for:
a warm-pool client is spawned with NO session key -- that is what makes it
poolable -- and a child's environment is fixed at spawn, so withholding the token
there stripped it from exactly the children whose identity has to survive a
rekey(), with nothing able to add it back afterwards. The token is set regardless
because it is minted in __init__ and its signed mapping is published once the key
becomes known, so a child holding a token and no key still resolves through the
mapping to whichever session claimed the process. The KEY stays conditioned because
it is a value rather than a pointer: an inherited one names a session this client is
not serving and the resolver would read it as identity, while the same token names
the current owner after every rekey. An inherited token is OVERWRITTEN rather than
dropped, so a reused env mapping leaves carrying this client's; an absent one is not
carried as an empty value, which the resolver would try first and never verify.
Two reds on this head belong to main rather than to this branch, both introduced by
9ab334b (fix(cloud): preserve Identity Center login through managed launch,
#9840), one of the nine commits this branch rebased onto:
* Backend Lint & Type Check reports F401 'json' imported but unused in
src/kiro_crew/dashboard/handlers/sessions.py, a file this diff does not touch
and which that commit rewrote. Measured rather than asserted: whole-tree flake8
output is byte-identical between this branch and a worktree at the base SHA.
* Backend Tests (Windows) shard 3 fails two protocol assertions in
test_fargate_launch_engine.py over begin_signin gaining a login_target
parameter -- again that commit's surface, and again untouched here. The file
passes 34/34 on Linux in both worktrees.
Rebased onto 04727eb, which main had reached 24 commits past the previous base.
The rebase was clean. Two things it settles:
* 7d1810d (fix(dashboard): drop the unused json import left by #9840, #11415)
removes the F401 this branch was reporting as main's, which is what that
reading predicted.
* 039d3e8 (feat(ledger): declare the session entry types and validate data on
write, #11317) is where the LedgerError "data.agent / data.actor: is required
and absent" failures come from, and 9ab334b is where the
test_fargate_launch_engine begin_signin/login_target ones come from. Neither
file is in this diff, and both reproduce identically at the base: over
test_ledger_kinds, test_ledger_retention, test_fargate_launch_engine and
test_remove_slot_for_history_key the failing/erroring id sets are 48 on each
side and equal.
Checks run against refs/pull/N/merge rather than against this branch's base, so
main's own breakage lands in this PR's results whatever this branch is rebased
onto. The measurement above is what tells the two apart.
…switch
One of Crew's own MCP servers can only learn WHICH session is calling it through a
channel that needs the shared MCP gateway: the per-session token minted for
gatewayd rides stub entries alone, and gatewayd is its only reader. On a default
install -- no stub roster, no daemon, pooling off -- there is no per-session
channel at all, so the strict resolver falls back to KIROCREW_SESSION_KEY, which is
wrong by construction in the two topologies that matter most. After a warm-pool
rekey the env a child was spawned with names a different session; under spawn_run
session sharing one kiro-cli process hosts N ACP sessions, so the env var, the
session_pid file and a /proc walk all answer with the PARENT for a subagent's
server.
Give the token a second reader that needs no daemon.
* session_token_sig.py publishes token -> session_key to ONE MAC-signed file per
mapping, named by sha256(token) so a directory listing leaks no bearer name.
The MAC covers "<token>:<body>" under a subkey derived from the SEL trust root
with a domain label distinct from the pid sidecar's -- both protocols sign an
"<identifier>:<session_key>" message, so without the split a pid sidecar for
pid N would verify as a token sidecar for a token spelled N. The hardened
reader and key loader are imported from session_pid_sig rather than copied, so
the two sidecars' read discipline cannot drift apart.
* The token is minted unconditionally. A reachable gatewayd socket is not a
precondition, because gatewayd is not the only reader; the socket gates the
CLAIM alone.
* It rides every control-plane element, through the one owner of that question
(providers/mirrors/identity.control_plane_identity_env, shared by codex,
opencode and goose), plus the member-dispatch element and the child env of a
one-session process (AcpClient._apply_session_identity_env, which serves the
kiro backend among others). KIROCREW_SESSION_KEY rides beside it as the
fallback for the one case the token cannot cover: no SEL trust root to sign a
mapping with. The SHARED kiro runtime has no per-session carrier -- its
control-plane servers reach kiro-cli through --agent rather than a session
array and its process multiplexes N sessions -- so identity there is what it is
for every non-token source, and strict_identity_diagnosis names the missing
channel. Injecting session-level control-plane entries would give it one at the
cost of widening the tool surface, since such an element outranks the spec
entry it shadows while carrying neither its tools allowlist nor its
disabledTools; that is a tool-surface decision rather than a carriage one.
* Both resolvers read the token ABOVE the env var, because where the two
disagree the env var is the stale one. The gateway's per-call caller context
still outranks both, being stamped per call.
* Published at session/new and re-published on every rekey() and every turn
(messaging.identity, the existing single writer), which is what makes a
warm-pool claim visible to an already-running MCP child. Retraction is the
age-based sweep in session_pid.py and only that: a teardown hook cannot reach a
gateway that dies without running one, and pruning cannot cost a live session
its identity because republication precedes every tool call in a turn.
No new config key, and nothing about pooling changes: stub_servers, enabled and
gatewayd behaviour are untouched.
Trust boundary, the same one the env var already has: forgery, cross-token replay,
in-place tampering and symlink planting are blocked; a same-uid process reading the
mapping directory is not, and is not meant to be -- it can already read the
session_pid files and present another session's key through the env var.
Two existing pins move, both because the change makes their premise false rather
than to make a test pass:
* test_no_stub_entries_means_no_token_and_no_claim asserted ([], "") under
"nothing to name, and nothing that would read the name". The second half does
not hold once the token has a file-backed reader. Renamed and re-pinned to the
new contract, keeping the half that does hold: no stub entries means no claim.
* test_identity_topology's session_pid call-site ratchet flags
session_token_sig.py, which appears in its scan only because it imports the pid
sidecar's reader and contrasts the two contracts. Registered with its role and
with why a pid-view parametrization has nothing to vary here: it reads no pid
at all, which is the property that makes it namespace-insensitive.
schedule_session_token_publish type-checks both arguments rather than only
truth-checking them, as schedule_claim does: every caller reads the token off a
session handle with getattr, and a non-string reaching the hash would raise
TypeError out of rekey() -- a warm-pool claim failing because of an identity side
effect is strictly worse than the claim proceeding without one.
Three log messages carry a nosemgrep suppression with its reason, matching the
four precedents in auth/store.py: the logger-credential-disclosure rule matches on
the word "token" in the message literal, while the arguments are a session key and
a sha256 digest. The token itself is never passed to a logger in this change.
Tests: 46 across the mapping protocol and the wiring. Each of seven injected
anti-patterns -- token read below the env var, the pid domain label, the mint
re-gated on a socket, the token withheld from the element env, the MAC comparison
skipped, the child env carrying the key without the token, and an unkeyed child
keeping a stale token -- was verified to fail them (pytest exit 1 with real failure
counts, never exit 4), so none is vacuous.
Windows CI adjudicated four consequences of the unconditional mint that a
diff-gated Linux run had skipped. All eight Windows shards are green on main at
this base, so none of these was pre-existing:
* The harness wire goldens gain an env array on session/load's control-plane
elements: kirocrew-core and kirocrew-cron now carry
KIROCREW_STUB_SESSION_TOKEN there. That is the intended product delta -- the
token rides the control plane -- and it reaches session/load and not
session/new in this capture only because the capture hands session/new an
explicit roster, which create_session deliberately does not re-key. The
capture pins the token the way it already pins the work dir and the session
ids, because a value minted from secrets can never match a golden twice;
pinning the INPUT keeps the golden a byte gate over the whole element, env
pair included, rather than scrubbing the output and gating less.
* test_load_session_redeclares_pooled_stubs compared session/load's array to
session/new's byte-for-byte. Each session start mints its own token and those
are two different sessions, so the comparison now excludes the per-session
identity env and nothing else: the parity it guards is the stub SET, since
re-declaring a different one is what silently un-pools a resumed session, and
a per-session credential is not a server. Verified still load-bearing --
making load_session re-declare an empty array fails it.
* publish_turn_identity resolved the provider twice, because the token
publication added a second sessions.get_provider() beside the one the stub
re-claim already did. One lookup now serves both, which is what a per-turn
hot path should cost and restores the call count a Windows shard asserting an
allocation sequence was pinned to.
* test_owner_only_mode asserted POSIX permission bits. Skipped on Windows
rather than loosened: NTFS carries an ACL and os.chmod moves only the
read-only flag there, so the value reads 666 whatever mode was requested, and
an assertion that accepted that would assert nothing on either platform.
Every remaining red in the affected selection was measured against a detached
origin/main worktree at the same base SHA: 325 failing/erroring ids on each side,
identical sets.
Three advisory findings on the third head, all on claims this change wrote:
* The cleanup lifecycle is named accurately. _prune_stale_session_token_files
runs from cleanup_orphaned_sessions, which session.py documents as startup and
graceful shutdown only, so "periodic sweep" overstated it. Both docstrings now
say what that costs: a gateway running for a month prunes nothing in between,
and the bound is one mapping per session started since the last boot or clean
stop. Deliberate -- what is owed is bounding accumulation rather than prompt
removal, and a boot-time pass covers the case a teardown hook structurally
cannot, a gateway killed without running one. Pruning still cannot cost a live
session its identity at any cadence, because the mapping is republished at the
start of every turn before anything in it can call a tool.
* The forgery claim states the trust root's real fencing. security.md classifies
sel_hmac.key VISIBLE: no OS fence, no bash-layer fence, and a spawned shell
reaches a file through an open() that never routes through the tool gate.
is_sensitive_path refuses the leaf on the FILE-TOOL path and that is the whole
of it, so all three statements -- the module docstring and both docs -- now say
forgery is blocked against the file tools and not against a shell, name the
residual as shared with the SEL audit chain (same key, same gap), and cite
security.md's own remedy: move the in-sandbox reader behind the gateway so the
leaf can become HIDDEN, never another path matcher. A shell that can read the
key can also mint a local API token and skip client-side resolution, so this
protocol is not the narrow point. Rounding that up would have handed the
SO_PEERCRED follow-up an inaccurate baseline.
* THREE pins move, not two. The load_session/create_session parity comparison
now excludes the per-session identity env, and it belongs in that list rather
than only in the Windows-findings note. Equality on that field asserted that
two DIFFERENT sessions were given the same token, which must never hold; what
remains asserted is the stub SET, with command, args and every other env pair
still compared byte-for-byte.
The parity ratchet keeps seeing the token, not just its shape. Excluding the
per-session pair from BOTH sides of the load/new comparison dropped the PRESENCE
assertion along with the value one, so it would have passed just as happily if
load_session stopped carrying a token at all. Repaired rather than reverted, since
reverting restores an equality that asserts two DIFFERENT sessions share a token:
_without_identity_env now rewrites the pair to a fixed placeholder instead of
removing it, so an element with no token still differs from one with a token, and
_identity_tokens asserts separately that every re-declared element carries one and
that the two sessions' tokens differ. Both regressions now fail the class -- the
blind spot (load_session skipping attach_stub_session_token, 1 of 12) and the
un-pooling case it already guarded (an empty re-declared array, 3 of 12).
publish_turn_identity's single provider lookup is its own change rather than a
footnote to the Windows fixes. The token publication had ADDED a second
sessions.get_provider() beside the one the stub re-claim already did, so this
returns the per-turn path to one lookup rather than introducing an optimisation;
_provider_inner exists because both steps then reach the provider surface the same
way through getattr, and two copies of that resolution is how they drift.
Rebased onto 780e75e (main gained 9 commits). Both conflicts were the same
shape -- main and this branch each adding one import at the same line
(recovery.ladder.InfraError vs session_token_sig.schedule_session_token_publish;
metrics.events.CHILD_PERMISSION_DENIED vs mcp_gateway.claim.STUB_SESSION_TOKEN_ENV)
-- and both sides are kept. Re-measured against a base worktree at the new SHA:
325 failing/erroring ids on each side, identical sets.
The child env carries the token unconditionally; only the fallback key is
conditioned. Treating the pair symmetrically broke the case this change exists for:
a warm-pool client is spawned with NO session key -- that is what makes it
poolable -- and a child's environment is fixed at spawn, so withholding the token
there stripped it from exactly the children whose identity has to survive a
rekey(), with nothing able to add it back afterwards. The token is set regardless
because it is minted in __init__ and its signed mapping is published once the key
becomes known, so a child holding a token and no key still resolves through the
mapping to whichever session claimed the process. The KEY stays conditioned because
it is a value rather than a pointer: an inherited one names a session this client is
not serving and the resolver would read it as identity, while the same token names
the current owner after every rekey. An inherited token is OVERWRITTEN rather than
dropped, so a reused env mapping leaves carrying this client's; an absent one is not
carried as an empty value, which the resolver would try first and never verify.
Two reds on this head belong to main rather than to this branch, both introduced by
9ab334b (fix(cloud): preserve Identity Center login through managed launch,
#9840), one of the nine commits this branch rebased onto:
* Backend Lint & Type Check reports F401 'json' imported but unused in
src/kiro_crew/dashboard/handlers/sessions.py, a file this diff does not touch
and which that commit rewrote. Measured rather than asserted: whole-tree flake8
output is byte-identical between this branch and a worktree at the base SHA.
* Backend Tests (Windows) shard 3 fails two protocol assertions in
test_fargate_launch_engine.py over begin_signin gaining a login_target
parameter -- again that commit's surface, and again untouched here. The file
passes 34/34 on Linux in both worktrees.
Rebased onto 04727eb, which main had reached 24 commits past the previous base.
The rebase was clean. Two things it settles:
* 7d1810d (fix(dashboard): drop the unused json import left by #9840, #11415)
removes the F401 this branch was reporting as main's, which is what that
reading predicted.
* 039d3e8 (feat(ledger): declare the session entry types and validate data on
write, #11317) is where the LedgerError "data.agent / data.actor: is required
and absent" failures come from, and 9ab334b is where the
test_fargate_launch_engine begin_signin/login_target ones come from. Neither
file is in this diff, and both reproduce identically at the base: over
test_ledger_kinds, test_ledger_retention, test_fargate_launch_engine and
test_remove_slot_for_history_key the failing/erroring id sets are 48 on each
side and equal.
Checks run against refs/pull/N/merge rather than against this branch's base, so
main's own breakage lands in this PR's results whatever this branch is rebased
onto. The measurement above is what tells the two apart.
…switch
One of Crew's own MCP servers can only learn WHICH session is calling it through a
channel that needs the shared MCP gateway: the per-session token minted for
gatewayd rides stub entries alone, and gatewayd is its only reader. On a default
install -- no stub roster, no daemon, pooling off -- there is no per-session
channel at all, so the strict resolver falls back to KIROCREW_SESSION_KEY, which is
wrong by construction in the two topologies that matter most. After a warm-pool
rekey the env a child was spawned with names a different session; under spawn_run
session sharing one kiro-cli process hosts N ACP sessions, so the env var, the
session_pid file and a /proc walk all answer with the PARENT for a subagent's
server.
Give the token a second reader that needs no daemon.
* session_token_sig.py publishes token -> session_key to ONE MAC-signed file per
mapping, named by sha256(token) so a directory listing leaks no bearer name.
The MAC covers "<token>:<body>" under a subkey derived from the SEL trust root
with a domain label distinct from the pid sidecar's -- both protocols sign an
"<identifier>:<session_key>" message, so without the split a pid sidecar for
pid N would verify as a token sidecar for a token spelled N. The hardened
reader and key loader are imported from session_pid_sig rather than copied, so
the two sidecars' read discipline cannot drift apart.
* The token is minted unconditionally. A reachable gatewayd socket is not a
precondition, because gatewayd is not the only reader; the socket gates the
CLAIM alone.
* It rides every control-plane element, through the one owner of that question
(providers/mirrors/identity.control_plane_identity_env, shared by codex,
opencode and goose), plus the member-dispatch element and the child env of a
one-session process (AcpClient._apply_session_identity_env, which serves the
kiro backend among others). KIROCREW_SESSION_KEY rides beside it as the
fallback for the one case the token cannot cover: no SEL trust root to sign a
mapping with. The SHARED kiro runtime has no per-session carrier -- its
control-plane servers reach kiro-cli through --agent rather than a session
array and its process multiplexes N sessions -- so identity there is what it is
for every non-token source, and strict_identity_diagnosis names the missing
channel. Injecting session-level control-plane entries would give it one at the
cost of widening the tool surface, since such an element outranks the spec
entry it shadows while carrying neither its tools allowlist nor its
disabledTools; that is a tool-surface decision rather than a carriage one.
* Both resolvers read the token ABOVE the env var, because where the two
disagree the env var is the stale one. The gateway's per-call caller context
still outranks both, being stamped per call.
* Published at session/new and re-published on every rekey() and every turn
(messaging.identity, the existing single writer), which is what makes a
warm-pool claim visible to an already-running MCP child. Retraction is the
age-based sweep in session_pid.py and only that: a teardown hook cannot reach a
gateway that dies without running one, and pruning cannot cost a live session
its identity because republication precedes every tool call in a turn.
No new config key, and nothing about pooling changes: stub_servers, enabled and
gatewayd behaviour are untouched.
Trust boundary, the same one the env var already has: forgery, cross-token replay,
in-place tampering and symlink planting are blocked; a same-uid process reading the
mapping directory is not, and is not meant to be -- it can already read the
session_pid files and present another session's key through the env var.
Two existing pins move, both because the change makes their premise false rather
than to make a test pass:
* test_no_stub_entries_means_no_token_and_no_claim asserted ([], "") under
"nothing to name, and nothing that would read the name". The second half does
not hold once the token has a file-backed reader. Renamed and re-pinned to the
new contract, keeping the half that does hold: no stub entries means no claim.
* test_identity_topology's session_pid call-site ratchet flags
session_token_sig.py, which appears in its scan only because it imports the pid
sidecar's reader and contrasts the two contracts. Registered with its role and
with why a pid-view parametrization has nothing to vary here: it reads no pid
at all, which is the property that makes it namespace-insensitive.
schedule_session_token_publish type-checks both arguments rather than only
truth-checking them, as schedule_claim does: every caller reads the token off a
session handle with getattr, and a non-string reaching the hash would raise
TypeError out of rekey() -- a warm-pool claim failing because of an identity side
effect is strictly worse than the claim proceeding without one.
Three log messages carry a nosemgrep suppression with its reason, matching the
four precedents in auth/store.py: the logger-credential-disclosure rule matches on
the word "token" in the message literal, while the arguments are a session key and
a sha256 digest. The token itself is never passed to a logger in this change.
Tests: 46 across the mapping protocol and the wiring. Each of seven injected
anti-patterns -- token read below the env var, the pid domain label, the mint
re-gated on a socket, the token withheld from the element env, the MAC comparison
skipped, the child env carrying the key without the token, and an unkeyed child
keeping a stale token -- was verified to fail them (pytest exit 1 with real failure
counts, never exit 4), so none is vacuous.
Windows CI adjudicated four consequences of the unconditional mint that a
diff-gated Linux run had skipped. All eight Windows shards are green on main at
this base, so none of these was pre-existing:
* The harness wire goldens gain an env array on session/load's control-plane
elements: kirocrew-core and kirocrew-cron now carry
KIROCREW_STUB_SESSION_TOKEN there. That is the intended product delta -- the
token rides the control plane -- and it reaches session/load and not
session/new in this capture only because the capture hands session/new an
explicit roster, which create_session deliberately does not re-key. The
capture pins the token the way it already pins the work dir and the session
ids, because a value minted from secrets can never match a golden twice;
pinning the INPUT keeps the golden a byte gate over the whole element, env
pair included, rather than scrubbing the output and gating less.
* test_load_session_redeclares_pooled_stubs compared session/load's array to
session/new's byte-for-byte. Each session start mints its own token and those
are two different sessions, so the comparison now excludes the per-session
identity env and nothing else: the parity it guards is the stub SET, since
re-declaring a different one is what silently un-pools a resumed session, and
a per-session credential is not a server. Verified still load-bearing --
making load_session re-declare an empty array fails it.
* publish_turn_identity resolved the provider twice, because the token
publication added a second sessions.get_provider() beside the one the stub
re-claim already did. One lookup now serves both, which is what a per-turn
hot path should cost and restores the call count a Windows shard asserting an
allocation sequence was pinned to.
* test_owner_only_mode asserted POSIX permission bits. Skipped on Windows
rather than loosened: NTFS carries an ACL and os.chmod moves only the
read-only flag there, so the value reads 666 whatever mode was requested, and
an assertion that accepted that would assert nothing on either platform.
Every remaining red in the affected selection was measured against a detached
origin/main worktree at the same base SHA: 325 failing/erroring ids on each side,
identical sets.
Three advisory findings on the third head, all on claims this change wrote:
* The cleanup lifecycle is named accurately. _prune_stale_session_token_files
runs from cleanup_orphaned_sessions, which session.py documents as startup and
graceful shutdown only, so "periodic sweep" overstated it. Both docstrings now
say what that costs: a gateway running for a month prunes nothing in between,
and the bound is one mapping per session started since the last boot or clean
stop. Deliberate -- what is owed is bounding accumulation rather than prompt
removal, and a boot-time pass covers the case a teardown hook structurally
cannot, a gateway killed without running one. Pruning still cannot cost a live
session its identity at any cadence, because the mapping is republished at the
start of every turn before anything in it can call a tool.
* The forgery claim states the trust root's real fencing. security.md classifies
sel_hmac.key VISIBLE: no OS fence, no bash-layer fence, and a spawned shell
reaches a file through an open() that never routes through the tool gate.
is_sensitive_path refuses the leaf on the FILE-TOOL path and that is the whole
of it, so all three statements -- the module docstring and both docs -- now say
forgery is blocked against the file tools and not against a shell, name the
residual as shared with the SEL audit chain (same key, same gap), and cite
security.md's own remedy: move the in-sandbox reader behind the gateway so the
leaf can become HIDDEN, never another path matcher. A shell that can read the
key can also mint a local API token and skip client-side resolution, so this
protocol is not the narrow point. Rounding that up would have handed the
SO_PEERCRED follow-up an inaccurate baseline.
* THREE pins move, not two. The load_session/create_session parity comparison
now excludes the per-session identity env, and it belongs in that list rather
than only in the Windows-findings note. Equality on that field asserted that
two DIFFERENT sessions were given the same token, which must never hold; what
remains asserted is the stub SET, with command, args and every other env pair
still compared byte-for-byte.
The parity ratchet keeps seeing the token, not just its shape. Excluding the
per-session pair from BOTH sides of the load/new comparison dropped the PRESENCE
assertion along with the value one, so it would have passed just as happily if
load_session stopped carrying a token at all. Repaired rather than reverted, since
reverting restores an equality that asserts two DIFFERENT sessions share a token:
_without_identity_env now rewrites the pair to a fixed placeholder instead of
removing it, so an element with no token still differs from one with a token, and
_identity_tokens asserts separately that every re-declared element carries one and
that the two sessions' tokens differ. Both regressions now fail the class -- the
blind spot (load_session skipping attach_stub_session_token, 1 of 12) and the
un-pooling case it already guarded (an empty re-declared array, 3 of 12).
publish_turn_identity's single provider lookup is its own change rather than a
footnote to the Windows fixes. The token publication had ADDED a second
sessions.get_provider() beside the one the stub re-claim already did, so this
returns the per-turn path to one lookup rather than introducing an optimisation;
_provider_inner exists because both steps then reach the provider surface the same
way through getattr, and two copies of that resolution is how they drift.
Rebased onto 780e75e (main gained 9 commits). Both conflicts were the same
shape -- main and this branch each adding one import at the same line
(recovery.ladder.InfraError vs session_token_sig.schedule_session_token_publish;
metrics.events.CHILD_PERMISSION_DENIED vs mcp_gateway.claim.STUB_SESSION_TOKEN_ENV)
-- and both sides are kept. Re-measured against a base worktree at the new SHA:
325 failing/erroring ids on each side, identical sets.
The child env carries the token unconditionally; only the fallback key is
conditioned. Treating the pair symmetrically broke the case this change exists for:
a warm-pool client is spawned with NO session key -- that is what makes it
poolable -- and a child's environment is fixed at spawn, so withholding the token
there stripped it from exactly the children whose identity has to survive a
rekey(), with nothing able to add it back afterwards. The token is set regardless
because it is minted in __init__ and its signed mapping is published once the key
becomes known, so a child holding a token and no key still resolves through the
mapping to whichever session claimed the process. The KEY stays conditioned because
it is a value rather than a pointer: an inherited one names a session this client is
not serving and the resolver would read it as identity, while the same token names
the current owner after every rekey. An inherited token is OVERWRITTEN rather than
dropped, so a reused env mapping leaves carrying this client's; an absent one is not
carried as an empty value, which the resolver would try first and never verify.
Two reds on this head belong to main rather than to this branch, both introduced by
9ab334b (fix(cloud): preserve Identity Center login through managed launch,
#9840), one of the nine commits this branch rebased onto:
* Backend Lint & Type Check reports F401 'json' imported but unused in
src/kiro_crew/dashboard/handlers/sessions.py, a file this diff does not touch
and which that commit rewrote. Measured rather than asserted: whole-tree flake8
output is byte-identical between this branch and a worktree at the base SHA.
* Backend Tests (Windows) shard 3 fails two protocol assertions in
test_fargate_launch_engine.py over begin_signin gaining a login_target
parameter -- again that commit's surface, and again untouched here. The file
passes 34/34 on Linux in both worktrees.
Rebased onto 04727eb, which main had reached 24 commits past the previous base.
The rebase was clean. Two things it settles:
* 7d1810d (fix(dashboard): drop the unused json import left by #9840, #11415)
removes the F401 this branch was reporting as main's, which is what that
reading predicted.
* 039d3e8 (feat(ledger): declare the session entry types and validate data on
write, #11317) is where the LedgerError "data.agent / data.actor: is required
and absent" failures come from, and 9ab334b is where the
test_fargate_launch_engine begin_signin/login_target ones come from. Neither
file is in this diff, and both reproduce identically at the base: over
test_ledger_kinds, test_ledger_retention, test_fargate_launch_engine and
test_remove_slot_for_history_key the failing/erroring id sets are 48 on each
side and equal.
Checks run against refs/pull/N/merge rather than against this branch's base, so
main's own breakage lands in this PR's results whatever this branch is rebased
onto. The measurement above is what tells the two apart.
…switch
One of Crew's own MCP servers can only learn WHICH session is calling it through a
channel that needs the shared MCP gateway: the per-session token minted for
gatewayd rides stub entries alone, and gatewayd is its only reader. On a default
install -- no stub roster, no daemon, pooling off -- there is no per-session
channel at all, so the strict resolver falls back to KIROCREW_SESSION_KEY, which is
wrong by construction in the two topologies that matter most. After a warm-pool
rekey the env a child was spawned with names a different session; under spawn_run
session sharing one kiro-cli process hosts N ACP sessions, so the env var, the
session_pid file and a /proc walk all answer with the PARENT for a subagent's
server.
Give the token a second reader that needs no daemon.
* session_token_sig.py publishes token -> session_key to ONE MAC-signed file per
mapping, named by sha256(token) so a directory listing leaks no bearer name.
The MAC covers "<token>:<body>" under a subkey derived from the SEL trust root
with a domain label distinct from the pid sidecar's -- both protocols sign an
"<identifier>:<session_key>" message, so without the split a pid sidecar for
pid N would verify as a token sidecar for a token spelled N. The hardened
reader and key loader are imported from session_pid_sig rather than copied, so
the two sidecars' read discipline cannot drift apart.
* The token is minted unconditionally. A reachable gatewayd socket is not a
precondition, because gatewayd is not the only reader; the socket gates the
CLAIM alone.
* It rides every control-plane element, through the one owner of that question
(providers/mirrors/identity.control_plane_identity_env, shared by codex,
opencode and goose), plus the member-dispatch element and the child env of a
one-session process (AcpClient._apply_session_identity_env, which serves the
kiro backend among others). KIROCREW_SESSION_KEY rides beside it as the
fallback for the one case the token cannot cover: no SEL trust root to sign a
mapping with. The SHARED kiro runtime has no per-session carrier -- its
control-plane servers reach kiro-cli through --agent rather than a session
array and its process multiplexes N sessions -- so identity there is what it is
for every non-token source, and strict_identity_diagnosis names the missing
channel. Injecting session-level control-plane entries would give it one at the
cost of widening the tool surface, since such an element outranks the spec
entry it shadows while carrying neither its tools allowlist nor its
disabledTools; that is a tool-surface decision rather than a carriage one.
* Both resolvers read the token ABOVE the env var, because where the two
disagree the env var is the stale one. The gateway's per-call caller context
still outranks both, being stamped per call.
* Published at session/new and re-published on every rekey() and every turn
(messaging.identity, the existing single writer), which is what makes a
warm-pool claim visible to an already-running MCP child. Retraction is the
age-based sweep in session_pid.py and only that: a teardown hook cannot reach a
gateway that dies without running one, and pruning cannot cost a live session
its identity because republication precedes every tool call in a turn.
No new config key, and nothing about pooling changes: stub_servers, enabled and
gatewayd behaviour are untouched.
Trust boundary, the same one the env var already has: forgery, cross-token replay,
in-place tampering and symlink planting are blocked; a same-uid process reading the
mapping directory is not, and is not meant to be -- it can already read the
session_pid files and present another session's key through the env var.
Two existing pins move, both because the change makes their premise false rather
than to make a test pass:
* test_no_stub_entries_means_no_token_and_no_claim asserted ([], "") under
"nothing to name, and nothing that would read the name". The second half does
not hold once the token has a file-backed reader. Renamed and re-pinned to the
new contract, keeping the half that does hold: no stub entries means no claim.
* test_identity_topology's session_pid call-site ratchet flags
session_token_sig.py, which appears in its scan only because it imports the pid
sidecar's reader and contrasts the two contracts. Registered with its role and
with why a pid-view parametrization has nothing to vary here: it reads no pid
at all, which is the property that makes it namespace-insensitive.
schedule_session_token_publish type-checks both arguments rather than only
truth-checking them, as schedule_claim does: every caller reads the token off a
session handle with getattr, and a non-string reaching the hash would raise
TypeError out of rekey() -- a warm-pool claim failing because of an identity side
effect is strictly worse than the claim proceeding without one.
Three log messages carry a nosemgrep suppression with its reason, matching the
four precedents in auth/store.py: the logger-credential-disclosure rule matches on
the word "token" in the message literal, while the arguments are a session key and
a sha256 digest. The token itself is never passed to a logger in this change.
Tests: 46 across the mapping protocol and the wiring. Each of seven injected
anti-patterns -- token read below the env var, the pid domain label, the mint
re-gated on a socket, the token withheld from the element env, the MAC comparison
skipped, the child env carrying the key without the token, and an unkeyed child
keeping a stale token -- was verified to fail them (pytest exit 1 with real failure
counts, never exit 4), so none is vacuous.
Windows CI adjudicated four consequences of the unconditional mint that a
diff-gated Linux run had skipped. All eight Windows shards are green on main at
this base, so none of these was pre-existing:
* The harness wire goldens gain an env array on session/load's control-plane
elements: kirocrew-core and kirocrew-cron now carry
KIROCREW_STUB_SESSION_TOKEN there. That is the intended product delta -- the
token rides the control plane -- and it reaches session/load and not
session/new in this capture only because the capture hands session/new an
explicit roster, which create_session deliberately does not re-key. The
capture pins the token the way it already pins the work dir and the session
ids, because a value minted from secrets can never match a golden twice;
pinning the INPUT keeps the golden a byte gate over the whole element, env
pair included, rather than scrubbing the output and gating less.
* test_load_session_redeclares_pooled_stubs compared session/load's array to
session/new's byte-for-byte. Each session start mints its own token and those
are two different sessions, so the comparison now excludes the per-session
identity env and nothing else: the parity it guards is the stub SET, since
re-declaring a different one is what silently un-pools a resumed session, and
a per-session credential is not a server. Verified still load-bearing --
making load_session re-declare an empty array fails it.
* publish_turn_identity resolved the provider twice, because the token
publication added a second sessions.get_provider() beside the one the stub
re-claim already did. One lookup now serves both, which is what a per-turn
hot path should cost and restores the call count a Windows shard asserting an
allocation sequence was pinned to.
* test_owner_only_mode asserted POSIX permission bits. Skipped on Windows
rather than loosened: NTFS carries an ACL and os.chmod moves only the
read-only flag there, so the value reads 666 whatever mode was requested, and
an assertion that accepted that would assert nothing on either platform.
Every remaining red in the affected selection was measured against a detached
origin/main worktree at the same base SHA: 325 failing/erroring ids on each side,
identical sets.
Three advisory findings on the third head, all on claims this change wrote:
* The cleanup lifecycle is named accurately. _prune_stale_session_token_files
runs from cleanup_orphaned_sessions, which session.py documents as startup and
graceful shutdown only, so "periodic sweep" overstated it. Both docstrings now
say what that costs: a gateway running for a month prunes nothing in between,
and the bound is one mapping per session started since the last boot or clean
stop. Deliberate -- what is owed is bounding accumulation rather than prompt
removal, and a boot-time pass covers the case a teardown hook structurally
cannot, a gateway killed without running one. Pruning still cannot cost a live
session its identity at any cadence, because the mapping is republished at the
start of every turn before anything in it can call a tool.
* The forgery claim states the trust root's real fencing. security.md classifies
sel_hmac.key VISIBLE: no OS fence, no bash-layer fence, and a spawned shell
reaches a file through an open() that never routes through the tool gate.
is_sensitive_path refuses the leaf on the FILE-TOOL path and that is the whole
of it, so all three statements -- the module docstring and both docs -- now say
forgery is blocked against the file tools and not against a shell, name the
residual as shared with the SEL audit chain (same key, same gap), and cite
security.md's own remedy: move the in-sandbox reader behind the gateway so the
leaf can become HIDDEN, never another path matcher. A shell that can read the
key can also mint a local API token and skip client-side resolution, so this
protocol is not the narrow point. Rounding that up would have handed the
SO_PEERCRED follow-up an inaccurate baseline.
* THREE pins move, not two. The load_session/create_session parity comparison
now excludes the per-session identity env, and it belongs in that list rather
than only in the Windows-findings note. Equality on that field asserted that
two DIFFERENT sessions were given the same token, which must never hold; what
remains asserted is the stub SET, with command, args and every other env pair
still compared byte-for-byte.
The parity ratchet keeps seeing the token, not just its shape. Excluding the
per-session pair from BOTH sides of the load/new comparison dropped the PRESENCE
assertion along with the value one, so it would have passed just as happily if
load_session stopped carrying a token at all. Repaired rather than reverted, since
reverting restores an equality that asserts two DIFFERENT sessions share a token:
_without_identity_env now rewrites the pair to a fixed placeholder instead of
removing it, so an element with no token still differs from one with a token, and
_identity_tokens asserts separately that every re-declared element carries one and
that the two sessions' tokens differ. Both regressions now fail the class -- the
blind spot (load_session skipping attach_stub_session_token, 1 of 12) and the
un-pooling case it already guarded (an empty re-declared array, 3 of 12).
publish_turn_identity's single provider lookup is its own change rather than a
footnote to the Windows fixes. The token publication had ADDED a second
sessions.get_provider() beside the one the stub re-claim already did, so this
returns the per-turn path to one lookup rather than introducing an optimisation;
_provider_inner exists because both steps then reach the provider surface the same
way through getattr, and two copies of that resolution is how they drift.
Rebased onto 780e75e (main gained 9 commits). Both conflicts were the same
shape -- main and this branch each adding one import at the same line
(recovery.ladder.InfraError vs session_token_sig.schedule_session_token_publish;
metrics.events.CHILD_PERMISSION_DENIED vs mcp_gateway.claim.STUB_SESSION_TOKEN_ENV)
-- and both sides are kept. Re-measured against a base worktree at the new SHA:
325 failing/erroring ids on each side, identical sets.
The child env carries the token unconditionally; only the fallback key is
conditioned. Treating the pair symmetrically broke the case this change exists for:
a warm-pool client is spawned with NO session key -- that is what makes it
poolable -- and a child's environment is fixed at spawn, so withholding the token
there stripped it from exactly the children whose identity has to survive a
rekey(), with nothing able to add it back afterwards. The token is set regardless
because it is minted in __init__ and its signed mapping is published once the key
becomes known, so a child holding a token and no key still resolves through the
mapping to whichever session claimed the process. The KEY stays conditioned because
it is a value rather than a pointer: an inherited one names a session this client is
not serving and the resolver would read it as identity, while the same token names
the current owner after every rekey. An inherited token is OVERWRITTEN rather than
dropped, so a reused env mapping leaves carrying this client's; an absent one is not
carried as an empty value, which the resolver would try first and never verify.
Two reds on this head belong to main rather than to this branch, both introduced by
9ab334b (fix(cloud): preserve Identity Center login through managed launch,
#9840), one of the nine commits this branch rebased onto:
* Backend Lint & Type Check reports F401 'json' imported but unused in
src/kiro_crew/dashboard/handlers/sessions.py, a file this diff does not touch
and which that commit rewrote. Measured rather than asserted: whole-tree flake8
output is byte-identical between this branch and a worktree at the base SHA.
* Backend Tests (Windows) shard 3 fails two protocol assertions in
test_fargate_launch_engine.py over begin_signin gaining a login_target
parameter -- again that commit's surface, and again untouched here. The file
passes 34/34 on Linux in both worktrees.
Rebased onto 04727eb, which main had reached 24 commits past the previous base.
The rebase was clean. Two things it settles:
* 7d1810d (fix(dashboard): drop the unused json import left by #9840, #11415)
removes the F401 this branch was reporting as main's, which is what that
reading predicted.
* 039d3e8 (feat(ledger): declare the session entry types and validate data on
write, #11317) is where the LedgerError "data.agent / data.actor: is required
and absent" failures come from, and 9ab334b is where the
test_fargate_launch_engine begin_signin/login_target ones come from. Neither
file is in this diff, and both reproduce identically at the base: over
test_ledger_kinds, test_ledger_retention, test_fargate_launch_engine and
test_remove_slot_for_history_key the failing/erroring id sets are 48 on each
side and equal.
Checks run against refs/pull/N/merge rather than against this branch's base, so
main's own breakage lands in this PR's results whatever this branch is rebased
onto. The measurement above is what tells the two apart.
…switch
One of Crew's own MCP servers can only learn WHICH session is calling it through a
channel that needs the shared MCP gateway: the per-session token minted for
gatewayd rides stub entries alone, and gatewayd is its only reader. On a default
install -- no stub roster, no daemon, pooling off -- there is no per-session
channel at all, so the strict resolver falls back to KIROCREW_SESSION_KEY, which is
wrong by construction in the two topologies that matter most. After a warm-pool
rekey the env a child was spawned with names a different session; under spawn_run
session sharing one kiro-cli process hosts N ACP sessions, so the env var, the
session_pid file and a /proc walk all answer with the PARENT for a subagent's
server.
Give the token a second reader that needs no daemon.
* session_token_sig.py publishes token -> session_key to ONE MAC-signed file per
mapping, named by sha256(token) so a directory listing leaks no bearer name.
The MAC covers "<token>:<body>" under a subkey derived from the SEL trust root
with a domain label distinct from the pid sidecar's -- both protocols sign an
"<identifier>:<session_key>" message, so without the split a pid sidecar for
pid N would verify as a token sidecar for a token spelled N. The hardened
reader and key loader are imported from session_pid_sig rather than copied, so
the two sidecars' read discipline cannot drift apart.
* The token is minted unconditionally. A reachable gatewayd socket is not a
precondition, because gatewayd is not the only reader; the socket gates the
CLAIM alone.
* It rides every control-plane element, through the one owner of that question
(providers/mirrors/identity.control_plane_identity_env, shared by codex,
opencode and goose), plus the member-dispatch element and the child env of a
one-session process (AcpClient._apply_session_identity_env, which serves the
kiro backend among others). KIROCREW_SESSION_KEY rides beside it as the
fallback for the one case the token cannot cover: no SEL trust root to sign a
mapping with. The SHARED kiro runtime has no per-session carrier -- its
control-plane servers reach kiro-cli through --agent rather than a session
array and its process multiplexes N sessions -- so identity there is what it is
for every non-token source, and strict_identity_diagnosis names the missing
channel. Injecting session-level control-plane entries would give it one at the
cost of widening the tool surface, since such an element outranks the spec
entry it shadows while carrying neither its tools allowlist nor its
disabledTools; that is a tool-surface decision rather than a carriage one.
* Both resolvers read the token ABOVE the env var, because where the two
disagree the env var is the stale one. The gateway's per-call caller context
still outranks both, being stamped per call.
* Published at session/new and re-published on every rekey() and every turn
(messaging.identity, the existing single writer), which is what makes a
warm-pool claim visible to an already-running MCP child. Retraction is the
age-based sweep in session_pid.py and only that: a teardown hook cannot reach a
gateway that dies without running one, and pruning cannot cost a live session
its identity because republication precedes every tool call in a turn.
No new config key, and nothing about pooling changes: stub_servers, enabled and
gatewayd behaviour are untouched.
Trust boundary, the same one the env var already has: forgery, cross-token replay,
in-place tampering and symlink planting are blocked; a same-uid process reading the
mapping directory is not, and is not meant to be -- it can already read the
session_pid files and present another session's key through the env var.
Two existing pins move, both because the change makes their premise false rather
than to make a test pass:
* test_no_stub_entries_means_no_token_and_no_claim asserted ([], "") under
"nothing to name, and nothing that would read the name". The second half does
not hold once the token has a file-backed reader. Renamed and re-pinned to the
new contract, keeping the half that does hold: no stub entries means no claim.
* test_identity_topology's session_pid call-site ratchet flags
session_token_sig.py, which appears in its scan only because it imports the pid
sidecar's reader and contrasts the two contracts. Registered with its role and
with why a pid-view parametrization has nothing to vary here: it reads no pid
at all, which is the property that makes it namespace-insensitive.
schedule_session_token_publish type-checks both arguments rather than only
truth-checking them, as schedule_claim does: every caller reads the token off a
session handle with getattr, and a non-string reaching the hash would raise
TypeError out of rekey() -- a warm-pool claim failing because of an identity side
effect is strictly worse than the claim proceeding without one.
Three log messages carry a nosemgrep suppression with its reason, matching the
four precedents in auth/store.py: the logger-credential-disclosure rule matches on
the word "token" in the message literal, while the arguments are a session key and
a sha256 digest. The token itself is never passed to a logger in this change.
Tests: 46 across the mapping protocol and the wiring. Each of seven injected
anti-patterns -- token read below the env var, the pid domain label, the mint
re-gated on a socket, the token withheld from the element env, the MAC comparison
skipped, the child env carrying the key without the token, and an unkeyed child
keeping a stale token -- was verified to fail them (pytest exit 1 with real failure
counts, never exit 4), so none is vacuous.
Windows CI adjudicated four consequences of the unconditional mint that a
diff-gated Linux run had skipped. All eight Windows shards are green on main at
this base, so none of these was pre-existing:
* The harness wire goldens gain an env array on session/load's control-plane
elements: kirocrew-core and kirocrew-cron now carry
KIROCREW_STUB_SESSION_TOKEN there. That is the intended product delta -- the
token rides the control plane -- and it reaches session/load and not
session/new in this capture only because the capture hands session/new an
explicit roster, which create_session deliberately does not re-key. The
capture pins the token the way it already pins the work dir and the session
ids, because a value minted from secrets can never match a golden twice;
pinning the INPUT keeps the golden a byte gate over the whole element, env
pair included, rather than scrubbing the output and gating less.
* test_load_session_redeclares_pooled_stubs compared session/load's array to
session/new's byte-for-byte. Each session start mints its own token and those
are two different sessions, so the comparison now excludes the per-session
identity env and nothing else: the parity it guards is the stub SET, since
re-declaring a different one is what silently un-pools a resumed session, and
a per-session credential is not a server. Verified still load-bearing --
making load_session re-declare an empty array fails it.
* publish_turn_identity resolved the provider twice, because the token
publication added a second sessions.get_provider() beside the one the stub
re-claim already did. One lookup now serves both, which is what a per-turn
hot path should cost and restores the call count a Windows shard asserting an
allocation sequence was pinned to.
* test_owner_only_mode asserted POSIX permission bits. Skipped on Windows
rather than loosened: NTFS carries an ACL and os.chmod moves only the
read-only flag there, so the value reads 666 whatever mode was requested, and
an assertion that accepted that would assert nothing on either platform.
Every remaining red in the affected selection was measured against a detached
origin/main worktree at the same base SHA: 325 failing/erroring ids on each side,
identical sets.
Three advisory findings on the third head, all on claims this change wrote:
* The cleanup lifecycle is named accurately. _prune_stale_session_token_files
runs from cleanup_orphaned_sessions, which session.py documents as startup and
graceful shutdown only, so "periodic sweep" overstated it. Both docstrings now
say what that costs: a gateway running for a month prunes nothing in between,
and the bound is one mapping per session started since the last boot or clean
stop. Deliberate -- what is owed is bounding accumulation rather than prompt
removal, and a boot-time pass covers the case a teardown hook structurally
cannot, a gateway killed without running one. Pruning still cannot cost a live
session its identity at any cadence, because the mapping is republished at the
start of every turn before anything in it can call a tool.
* The forgery claim states the trust root's real fencing. security.md classifies
sel_hmac.key VISIBLE: no OS fence, no bash-layer fence, and a spawned shell
reaches a file through an open() that never routes through the tool gate.
is_sensitive_path refuses the leaf on the FILE-TOOL path and that is the whole
of it, so all three statements -- the module docstring and both docs -- now say
forgery is blocked against the file tools and not against a shell, name the
residual as shared with the SEL audit chain (same key, same gap), and cite
security.md's own remedy: move the in-sandbox reader behind the gateway so the
leaf can become HIDDEN, never another path matcher. A shell that can read the
key can also mint a local API token and skip client-side resolution, so this
protocol is not the narrow point. Rounding that up would have handed the
SO_PEERCRED follow-up an inaccurate baseline.
* THREE pins move, not two. The load_session/create_session parity comparison
now excludes the per-session identity env, and it belongs in that list rather
than only in the Windows-findings note. Equality on that field asserted that
two DIFFERENT sessions were given the same token, which must never hold; what
remains asserted is the stub SET, with command, args and every other env pair
still compared byte-for-byte.
The parity ratchet keeps seeing the token, not just its shape. Excluding the
per-session pair from BOTH sides of the load/new comparison dropped the PRESENCE
assertion along with the value one, so it would have passed just as happily if
load_session stopped carrying a token at all. Repaired rather than reverted, since
reverting restores an equality that asserts two DIFFERENT sessions share a token:
_without_identity_env now rewrites the pair to a fixed placeholder instead of
removing it, so an element with no token still differs from one with a token, and
_identity_tokens asserts separately that every re-declared element carries one and
that the two sessions' tokens differ. Both regressions now fail the class -- the
blind spot (load_session skipping attach_stub_session_token, 1 of 12) and the
un-pooling case it already guarded (an empty re-declared array, 3 of 12).
publish_turn_identity's single provider lookup is its own change rather than a
footnote to the Windows fixes. The token publication had ADDED a second
sessions.get_provider() beside the one the stub re-claim already did, so this
returns the per-turn path to one lookup rather than introducing an optimisation;
_provider_inner exists because both steps then reach the provider surface the same
way through getattr, and two copies of that resolution is how they drift.
Rebased onto 780e75e (main gained 9 commits). Both conflicts were the same
shape -- main and this branch each adding one import at the same line
(recovery.ladder.InfraError vs session_token_sig.schedule_session_token_publish;
metrics.events.CHILD_PERMISSION_DENIED vs mcp_gateway.claim.STUB_SESSION_TOKEN_ENV)
-- and both sides are kept. Re-measured against a base worktree at the new SHA:
325 failing/erroring ids on each side, identical sets.
The child env carries the token unconditionally; only the fallback key is
conditioned. Treating the pair symmetrically broke the case this change exists for:
a warm-pool client is spawned with NO session key -- that is what makes it
poolable -- and a child's environment is fixed at spawn, so withholding the token
there stripped it from exactly the children whose identity has to survive a
rekey(), with nothing able to add it back afterwards. The token is set regardless
because it is minted in __init__ and its signed mapping is published once the key
becomes known, so a child holding a token and no key still resolves through the
mapping to whichever session claimed the process. The KEY stays conditioned because
it is a value rather than a pointer: an inherited one names a session this client is
not serving and the resolver would read it as identity, while the same token names
the current owner after every rekey. An inherited token is OVERWRITTEN rather than
dropped, so a reused env mapping leaves carrying this client's; an absent one is not
carried as an empty value, which the resolver would try first and never verify.
Two reds on this head belong to main rather than to this branch, both introduced by
9ab334b (fix(cloud): preserve Identity Center login through managed launch,
#9840), one of the nine commits this branch rebased onto:
* Backend Lint & Type Check reports F401 'json' imported but unused in
src/kiro_crew/dashboard/handlers/sessions.py, a file this diff does not touch
and which that commit rewrote. Measured rather than asserted: whole-tree flake8
output is byte-identical between this branch and a worktree at the base SHA.
* Backend Tests (Windows) shard 3 fails two protocol assertions in
test_fargate_launch_engine.py over begin_signin gaining a login_target
parameter -- again that commit's surface, and again untouched here. The file
passes 34/34 on Linux in both worktrees.
Rebased onto 04727eb, which main had reached 24 commits past the previous base.
The rebase was clean. Two things it settles:
* 7d1810d (fix(dashboard): drop the unused json import left by #9840, #11415)
removes the F401 this branch was reporting as main's, which is what that
reading predicted.
* 039d3e8 (feat(ledger): declare the session entry types and validate data on
write, #11317) is where the LedgerError "data.agent / data.actor: is required
and absent" failures come from, and 9ab334b is where the
test_fargate_launch_engine begin_signin/login_target ones come from. Neither
file is in this diff, and both reproduce identically at the base: over
test_ledger_kinds, test_ledger_retention, test_fargate_launch_engine and
test_remove_slot_for_history_key the failing/erroring id sets are 48 on each
side and equal.
Checks run against refs/pull/N/merge rather than against this branch's base, so
main's own breakage lands in this PR's results whatever this branch is rebased
onto. The measurement above is what tells the two apart.
…switch (#11383) One of Crew's own MCP servers can only learn WHICH session is calling it through a channel that needs the shared MCP gateway: the per-session token minted for gatewayd rides stub entries alone, and gatewayd is its only reader. On a default install -- no stub roster, no daemon, pooling off -- there is no per-session channel at all, so the strict resolver falls back to KIROCREW_SESSION_KEY, which is wrong by construction in the two topologies that matter most. After a warm-pool rekey the env a child was spawned with names a different session; under spawn_run session sharing one kiro-cli process hosts N ACP sessions, so the env var, the session_pid file and a /proc walk all answer with the PARENT for a subagent's server. Give the token a second reader that needs no daemon. * session_token_sig.py publishes token -> session_key to ONE MAC-signed file per mapping, named by sha256(token) so a directory listing leaks no bearer name. The MAC covers "<token>:<body>" under a subkey derived from the SEL trust root with a domain label distinct from the pid sidecar's -- both protocols sign an "<identifier>:<session_key>" message, so without the split a pid sidecar for pid N would verify as a token sidecar for a token spelled N. The hardened reader and key loader are imported from session_pid_sig rather than copied, so the two sidecars' read discipline cannot drift apart. * The token is minted unconditionally. A reachable gatewayd socket is not a precondition, because gatewayd is not the only reader; the socket gates the CLAIM alone. * It rides every control-plane element, through the one owner of that question (providers/mirrors/identity.control_plane_identity_env, shared by codex, opencode and goose), plus the member-dispatch element and the child env of a one-session process (AcpClient._apply_session_identity_env, which serves the kiro backend among others). KIROCREW_SESSION_KEY rides beside it as the fallback for the one case the token cannot cover: no SEL trust root to sign a mapping with. The SHARED kiro runtime has no per-session carrier -- its control-plane servers reach kiro-cli through --agent rather than a session array and its process multiplexes N sessions -- so identity there is what it is for every non-token source, and strict_identity_diagnosis names the missing channel. Injecting session-level control-plane entries would give it one at the cost of widening the tool surface, since such an element outranks the spec entry it shadows while carrying neither its tools allowlist nor its disabledTools; that is a tool-surface decision rather than a carriage one. * Both resolvers read the token ABOVE the env var, because where the two disagree the env var is the stale one. The gateway's per-call caller context still outranks both, being stamped per call. * Published at session/new and re-published on every rekey() and every turn (messaging.identity, the existing single writer), which is what makes a warm-pool claim visible to an already-running MCP child. Retraction is the age-based sweep in session_pid.py and only that: a teardown hook cannot reach a gateway that dies without running one, and pruning cannot cost a live session its identity because republication precedes every tool call in a turn. No new config key, and nothing about pooling changes: stub_servers, enabled and gatewayd behaviour are untouched. Trust boundary, the same one the env var already has: forgery, cross-token replay, in-place tampering and symlink planting are blocked; a same-uid process reading the mapping directory is not, and is not meant to be -- it can already read the session_pid files and present another session's key through the env var. Two existing pins move, both because the change makes their premise false rather than to make a test pass: * test_no_stub_entries_means_no_token_and_no_claim asserted ([], "") under "nothing to name, and nothing that would read the name". The second half does not hold once the token has a file-backed reader. Renamed and re-pinned to the new contract, keeping the half that does hold: no stub entries means no claim. * test_identity_topology's session_pid call-site ratchet flags session_token_sig.py, which appears in its scan only because it imports the pid sidecar's reader and contrasts the two contracts. Registered with its role and with why a pid-view parametrization has nothing to vary here: it reads no pid at all, which is the property that makes it namespace-insensitive. schedule_session_token_publish type-checks both arguments rather than only truth-checking them, as schedule_claim does: every caller reads the token off a session handle with getattr, and a non-string reaching the hash would raise TypeError out of rekey() -- a warm-pool claim failing because of an identity side effect is strictly worse than the claim proceeding without one. Three log messages carry a nosemgrep suppression with its reason, matching the four precedents in auth/store.py: the logger-credential-disclosure rule matches on the word "token" in the message literal, while the arguments are a session key and a sha256 digest. The token itself is never passed to a logger in this change. Tests: 46 across the mapping protocol and the wiring. Each of seven injected anti-patterns -- token read below the env var, the pid domain label, the mint re-gated on a socket, the token withheld from the element env, the MAC comparison skipped, the child env carrying the key without the token, and an unkeyed child keeping a stale token -- was verified to fail them (pytest exit 1 with real failure counts, never exit 4), so none is vacuous. Windows CI adjudicated four consequences of the unconditional mint that a diff-gated Linux run had skipped. All eight Windows shards are green on main at this base, so none of these was pre-existing: * The harness wire goldens gain an env array on session/load's control-plane elements: kirocrew-core and kirocrew-cron now carry KIROCREW_STUB_SESSION_TOKEN there. That is the intended product delta -- the token rides the control plane -- and it reaches session/load and not session/new in this capture only because the capture hands session/new an explicit roster, which create_session deliberately does not re-key. The capture pins the token the way it already pins the work dir and the session ids, because a value minted from secrets can never match a golden twice; pinning the INPUT keeps the golden a byte gate over the whole element, env pair included, rather than scrubbing the output and gating less. * test_load_session_redeclares_pooled_stubs compared session/load's array to session/new's byte-for-byte. Each session start mints its own token and those are two different sessions, so the comparison now excludes the per-session identity env and nothing else: the parity it guards is the stub SET, since re-declaring a different one is what silently un-pools a resumed session, and a per-session credential is not a server. Verified still load-bearing -- making load_session re-declare an empty array fails it. * publish_turn_identity resolved the provider twice, because the token publication added a second sessions.get_provider() beside the one the stub re-claim already did. One lookup now serves both, which is what a per-turn hot path should cost and restores the call count a Windows shard asserting an allocation sequence was pinned to. * test_owner_only_mode asserted POSIX permission bits. Skipped on Windows rather than loosened: NTFS carries an ACL and os.chmod moves only the read-only flag there, so the value reads 666 whatever mode was requested, and an assertion that accepted that would assert nothing on either platform. Every remaining red in the affected selection was measured against a detached origin/main worktree at the same base SHA: 325 failing/erroring ids on each side, identical sets. Three advisory findings on the third head, all on claims this change wrote: * The cleanup lifecycle is named accurately. _prune_stale_session_token_files runs from cleanup_orphaned_sessions, which session.py documents as startup and graceful shutdown only, so "periodic sweep" overstated it. Both docstrings now say what that costs: a gateway running for a month prunes nothing in between, and the bound is one mapping per session started since the last boot or clean stop. Deliberate -- what is owed is bounding accumulation rather than prompt removal, and a boot-time pass covers the case a teardown hook structurally cannot, a gateway killed without running one. Pruning still cannot cost a live session its identity at any cadence, because the mapping is republished at the start of every turn before anything in it can call a tool. * The forgery claim states the trust root's real fencing. security.md classifies sel_hmac.key VISIBLE: no OS fence, no bash-layer fence, and a spawned shell reaches a file through an open() that never routes through the tool gate. is_sensitive_path refuses the leaf on the FILE-TOOL path and that is the whole of it, so all three statements -- the module docstring and both docs -- now say forgery is blocked against the file tools and not against a shell, name the residual as shared with the SEL audit chain (same key, same gap), and cite security.md's own remedy: move the in-sandbox reader behind the gateway so the leaf can become HIDDEN, never another path matcher. A shell that can read the key can also mint a local API token and skip client-side resolution, so this protocol is not the narrow point. Rounding that up would have handed the SO_PEERCRED follow-up an inaccurate baseline. * THREE pins move, not two. The load_session/create_session parity comparison now excludes the per-session identity env, and it belongs in that list rather than only in the Windows-findings note. Equality on that field asserted that two DIFFERENT sessions were given the same token, which must never hold; what remains asserted is the stub SET, with command, args and every other env pair still compared byte-for-byte. The parity ratchet keeps seeing the token, not just its shape. Excluding the per-session pair from BOTH sides of the load/new comparison dropped the PRESENCE assertion along with the value one, so it would have passed just as happily if load_session stopped carrying a token at all. Repaired rather than reverted, since reverting restores an equality that asserts two DIFFERENT sessions share a token: _without_identity_env now rewrites the pair to a fixed placeholder instead of removing it, so an element with no token still differs from one with a token, and _identity_tokens asserts separately that every re-declared element carries one and that the two sessions' tokens differ. Both regressions now fail the class -- the blind spot (load_session skipping attach_stub_session_token, 1 of 12) and the un-pooling case it already guarded (an empty re-declared array, 3 of 12). publish_turn_identity's single provider lookup is its own change rather than a footnote to the Windows fixes. The token publication had ADDED a second sessions.get_provider() beside the one the stub re-claim already did, so this returns the per-turn path to one lookup rather than introducing an optimisation; _provider_inner exists because both steps then reach the provider surface the same way through getattr, and two copies of that resolution is how they drift. Rebased onto 780e75e (main gained 9 commits). Both conflicts were the same shape -- main and this branch each adding one import at the same line (recovery.ladder.InfraError vs session_token_sig.schedule_session_token_publish; metrics.events.CHILD_PERMISSION_DENIED vs mcp_gateway.claim.STUB_SESSION_TOKEN_ENV) -- and both sides are kept. Re-measured against a base worktree at the new SHA: 325 failing/erroring ids on each side, identical sets. The child env carries the token unconditionally; only the fallback key is conditioned. Treating the pair symmetrically broke the case this change exists for: a warm-pool client is spawned with NO session key -- that is what makes it poolable -- and a child's environment is fixed at spawn, so withholding the token there stripped it from exactly the children whose identity has to survive a rekey(), with nothing able to add it back afterwards. The token is set regardless because it is minted in __init__ and its signed mapping is published once the key becomes known, so a child holding a token and no key still resolves through the mapping to whichever session claimed the process. The KEY stays conditioned because it is a value rather than a pointer: an inherited one names a session this client is not serving and the resolver would read it as identity, while the same token names the current owner after every rekey. An inherited token is OVERWRITTEN rather than dropped, so a reused env mapping leaves carrying this client's; an absent one is not carried as an empty value, which the resolver would try first and never verify. Two reds on this head belong to main rather than to this branch, both introduced by 9ab334b (fix(cloud): preserve Identity Center login through managed launch, #9840), one of the nine commits this branch rebased onto: * Backend Lint & Type Check reports F401 'json' imported but unused in src/kiro_crew/dashboard/handlers/sessions.py, a file this diff does not touch and which that commit rewrote. Measured rather than asserted: whole-tree flake8 output is byte-identical between this branch and a worktree at the base SHA. * Backend Tests (Windows) shard 3 fails two protocol assertions in test_fargate_launch_engine.py over begin_signin gaining a login_target parameter -- again that commit's surface, and again untouched here. The file passes 34/34 on Linux in both worktrees. Rebased onto 04727eb, which main had reached 24 commits past the previous base. The rebase was clean. Two things it settles: * 7d1810d (fix(dashboard): drop the unused json import left by #9840, #11415) removes the F401 this branch was reporting as main's, which is what that reading predicted. * 039d3e8 (feat(ledger): declare the session entry types and validate data on write, #11317) is where the LedgerError "data.agent / data.actor: is required and absent" failures come from, and 9ab334b is where the test_fargate_launch_engine begin_signin/login_target ones come from. Neither file is in this diff, and both reproduce identically at the base: over test_ledger_kinds, test_ledger_retention, test_fargate_launch_engine and test_remove_slot_for_history_key the failing/erroring id sets are 48 on each side and equal. Checks run against refs/pull/N/merge rather than against this branch's base, so main's own breakage lands in this PR's results whatever this branch is rebased onto. The measurement above is what tells the two apart. Co-authored-by: Joe Guo <zejiangg@amazon.com>
…ite (kirodotdev#11317) The ledger owned a vocabulary of entry types but nothing said what any of them carries. A writer learned the payload shape by reading call sites, and a reader learned it by reading entries, so a field could be renamed on one side and silently dropped on the other. Declare the 26 session types as data: kiro_crew.ledger.entry_types holds an EntryType per type and a Field per member, with the JSON type, whether it is required, closed enums, array item types and nested members. Ledger.append, append_many and the chunk-citing path validate data against that declaration before any byte is written, refusing with the additive bad_data_field code and naming the offending path. The same declarations render as Markdown via python -m kiro_crew.ledger.entry_types --markdown, so the reference table is generated from the enforced source rather than maintained beside it.
…switch (kirodotdev#11383) One of Crew's own MCP servers can only learn WHICH session is calling it through a channel that needs the shared MCP gateway: the per-session token minted for gatewayd rides stub entries alone, and gatewayd is its only reader. On a default install -- no stub roster, no daemon, pooling off -- there is no per-session channel at all, so the strict resolver falls back to KIROCREW_SESSION_KEY, which is wrong by construction in the two topologies that matter most. After a warm-pool rekey the env a child was spawned with names a different session; under spawn_run session sharing one kiro-cli process hosts N ACP sessions, so the env var, the session_pid file and a /proc walk all answer with the PARENT for a subagent's server. Give the token a second reader that needs no daemon. * session_token_sig.py publishes token -> session_key to ONE MAC-signed file per mapping, named by sha256(token) so a directory listing leaks no bearer name. The MAC covers "<token>:<body>" under a subkey derived from the SEL trust root with a domain label distinct from the pid sidecar's -- both protocols sign an "<identifier>:<session_key>" message, so without the split a pid sidecar for pid N would verify as a token sidecar for a token spelled N. The hardened reader and key loader are imported from session_pid_sig rather than copied, so the two sidecars' read discipline cannot drift apart. * The token is minted unconditionally. A reachable gatewayd socket is not a precondition, because gatewayd is not the only reader; the socket gates the CLAIM alone. * It rides every control-plane element, through the one owner of that question (providers/mirrors/identity.control_plane_identity_env, shared by codex, opencode and goose), plus the member-dispatch element and the child env of a one-session process (AcpClient._apply_session_identity_env, which serves the kiro backend among others). KIROCREW_SESSION_KEY rides beside it as the fallback for the one case the token cannot cover: no SEL trust root to sign a mapping with. The SHARED kiro runtime has no per-session carrier -- its control-plane servers reach kiro-cli through --agent rather than a session array and its process multiplexes N sessions -- so identity there is what it is for every non-token source, and strict_identity_diagnosis names the missing channel. Injecting session-level control-plane entries would give it one at the cost of widening the tool surface, since such an element outranks the spec entry it shadows while carrying neither its tools allowlist nor its disabledTools; that is a tool-surface decision rather than a carriage one. * Both resolvers read the token ABOVE the env var, because where the two disagree the env var is the stale one. The gateway's per-call caller context still outranks both, being stamped per call. * Published at session/new and re-published on every rekey() and every turn (messaging.identity, the existing single writer), which is what makes a warm-pool claim visible to an already-running MCP child. Retraction is the age-based sweep in session_pid.py and only that: a teardown hook cannot reach a gateway that dies without running one, and pruning cannot cost a live session its identity because republication precedes every tool call in a turn. No new config key, and nothing about pooling changes: stub_servers, enabled and gatewayd behaviour are untouched. Trust boundary, the same one the env var already has: forgery, cross-token replay, in-place tampering and symlink planting are blocked; a same-uid process reading the mapping directory is not, and is not meant to be -- it can already read the session_pid files and present another session's key through the env var. Two existing pins move, both because the change makes their premise false rather than to make a test pass: * test_no_stub_entries_means_no_token_and_no_claim asserted ([], "") under "nothing to name, and nothing that would read the name". The second half does not hold once the token has a file-backed reader. Renamed and re-pinned to the new contract, keeping the half that does hold: no stub entries means no claim. * test_identity_topology's session_pid call-site ratchet flags session_token_sig.py, which appears in its scan only because it imports the pid sidecar's reader and contrasts the two contracts. Registered with its role and with why a pid-view parametrization has nothing to vary here: it reads no pid at all, which is the property that makes it namespace-insensitive. schedule_session_token_publish type-checks both arguments rather than only truth-checking them, as schedule_claim does: every caller reads the token off a session handle with getattr, and a non-string reaching the hash would raise TypeError out of rekey() -- a warm-pool claim failing because of an identity side effect is strictly worse than the claim proceeding without one. Three log messages carry a nosemgrep suppression with its reason, matching the four precedents in auth/store.py: the logger-credential-disclosure rule matches on the word "token" in the message literal, while the arguments are a session key and a sha256 digest. The token itself is never passed to a logger in this change. Tests: 46 across the mapping protocol and the wiring. Each of seven injected anti-patterns -- token read below the env var, the pid domain label, the mint re-gated on a socket, the token withheld from the element env, the MAC comparison skipped, the child env carrying the key without the token, and an unkeyed child keeping a stale token -- was verified to fail them (pytest exit 1 with real failure counts, never exit 4), so none is vacuous. Windows CI adjudicated four consequences of the unconditional mint that a diff-gated Linux run had skipped. All eight Windows shards are green on main at this base, so none of these was pre-existing: * The harness wire goldens gain an env array on session/load's control-plane elements: kirocrew-core and kirocrew-cron now carry KIROCREW_STUB_SESSION_TOKEN there. That is the intended product delta -- the token rides the control plane -- and it reaches session/load and not session/new in this capture only because the capture hands session/new an explicit roster, which create_session deliberately does not re-key. The capture pins the token the way it already pins the work dir and the session ids, because a value minted from secrets can never match a golden twice; pinning the INPUT keeps the golden a byte gate over the whole element, env pair included, rather than scrubbing the output and gating less. * test_load_session_redeclares_pooled_stubs compared session/load's array to session/new's byte-for-byte. Each session start mints its own token and those are two different sessions, so the comparison now excludes the per-session identity env and nothing else: the parity it guards is the stub SET, since re-declaring a different one is what silently un-pools a resumed session, and a per-session credential is not a server. Verified still load-bearing -- making load_session re-declare an empty array fails it. * publish_turn_identity resolved the provider twice, because the token publication added a second sessions.get_provider() beside the one the stub re-claim already did. One lookup now serves both, which is what a per-turn hot path should cost and restores the call count a Windows shard asserting an allocation sequence was pinned to. * test_owner_only_mode asserted POSIX permission bits. Skipped on Windows rather than loosened: NTFS carries an ACL and os.chmod moves only the read-only flag there, so the value reads 666 whatever mode was requested, and an assertion that accepted that would assert nothing on either platform. Every remaining red in the affected selection was measured against a detached origin/main worktree at the same base SHA: 325 failing/erroring ids on each side, identical sets. Three advisory findings on the third head, all on claims this change wrote: * The cleanup lifecycle is named accurately. _prune_stale_session_token_files runs from cleanup_orphaned_sessions, which session.py documents as startup and graceful shutdown only, so "periodic sweep" overstated it. Both docstrings now say what that costs: a gateway running for a month prunes nothing in between, and the bound is one mapping per session started since the last boot or clean stop. Deliberate -- what is owed is bounding accumulation rather than prompt removal, and a boot-time pass covers the case a teardown hook structurally cannot, a gateway killed without running one. Pruning still cannot cost a live session its identity at any cadence, because the mapping is republished at the start of every turn before anything in it can call a tool. * The forgery claim states the trust root's real fencing. security.md classifies sel_hmac.key VISIBLE: no OS fence, no bash-layer fence, and a spawned shell reaches a file through an open() that never routes through the tool gate. is_sensitive_path refuses the leaf on the FILE-TOOL path and that is the whole of it, so all three statements -- the module docstring and both docs -- now say forgery is blocked against the file tools and not against a shell, name the residual as shared with the SEL audit chain (same key, same gap), and cite security.md's own remedy: move the in-sandbox reader behind the gateway so the leaf can become HIDDEN, never another path matcher. A shell that can read the key can also mint a local API token and skip client-side resolution, so this protocol is not the narrow point. Rounding that up would have handed the SO_PEERCRED follow-up an inaccurate baseline. * THREE pins move, not two. The load_session/create_session parity comparison now excludes the per-session identity env, and it belongs in that list rather than only in the Windows-findings note. Equality on that field asserted that two DIFFERENT sessions were given the same token, which must never hold; what remains asserted is the stub SET, with command, args and every other env pair still compared byte-for-byte. The parity ratchet keeps seeing the token, not just its shape. Excluding the per-session pair from BOTH sides of the load/new comparison dropped the PRESENCE assertion along with the value one, so it would have passed just as happily if load_session stopped carrying a token at all. Repaired rather than reverted, since reverting restores an equality that asserts two DIFFERENT sessions share a token: _without_identity_env now rewrites the pair to a fixed placeholder instead of removing it, so an element with no token still differs from one with a token, and _identity_tokens asserts separately that every re-declared element carries one and that the two sessions' tokens differ. Both regressions now fail the class -- the blind spot (load_session skipping attach_stub_session_token, 1 of 12) and the un-pooling case it already guarded (an empty re-declared array, 3 of 12). publish_turn_identity's single provider lookup is its own change rather than a footnote to the Windows fixes. The token publication had ADDED a second sessions.get_provider() beside the one the stub re-claim already did, so this returns the per-turn path to one lookup rather than introducing an optimisation; _provider_inner exists because both steps then reach the provider surface the same way through getattr, and two copies of that resolution is how they drift. Rebased onto 780e75e (main gained 9 commits). Both conflicts were the same shape -- main and this branch each adding one import at the same line (recovery.ladder.InfraError vs session_token_sig.schedule_session_token_publish; metrics.events.CHILD_PERMISSION_DENIED vs mcp_gateway.claim.STUB_SESSION_TOKEN_ENV) -- and both sides are kept. Re-measured against a base worktree at the new SHA: 325 failing/erroring ids on each side, identical sets. The child env carries the token unconditionally; only the fallback key is conditioned. Treating the pair symmetrically broke the case this change exists for: a warm-pool client is spawned with NO session key -- that is what makes it poolable -- and a child's environment is fixed at spawn, so withholding the token there stripped it from exactly the children whose identity has to survive a rekey(), with nothing able to add it back afterwards. The token is set regardless because it is minted in __init__ and its signed mapping is published once the key becomes known, so a child holding a token and no key still resolves through the mapping to whichever session claimed the process. The KEY stays conditioned because it is a value rather than a pointer: an inherited one names a session this client is not serving and the resolver would read it as identity, while the same token names the current owner after every rekey. An inherited token is OVERWRITTEN rather than dropped, so a reused env mapping leaves carrying this client's; an absent one is not carried as an empty value, which the resolver would try first and never verify. Two reds on this head belong to main rather than to this branch, both introduced by 9ab334b (fix(cloud): preserve Identity Center login through managed launch, kirodotdev#9840), one of the nine commits this branch rebased onto: * Backend Lint & Type Check reports F401 'json' imported but unused in src/kiro_crew/dashboard/handlers/sessions.py, a file this diff does not touch and which that commit rewrote. Measured rather than asserted: whole-tree flake8 output is byte-identical between this branch and a worktree at the base SHA. * Backend Tests (Windows) shard 3 fails two protocol assertions in test_fargate_launch_engine.py over begin_signin gaining a login_target parameter -- again that commit's surface, and again untouched here. The file passes 34/34 on Linux in both worktrees. Rebased onto 04727eb, which main had reached 24 commits past the previous base. The rebase was clean. Two things it settles: * 7d1810d (fix(dashboard): drop the unused json import left by kirodotdev#9840, kirodotdev#11415) removes the F401 this branch was reporting as main's, which is what that reading predicted. * 039d3e8 (feat(ledger): declare the session entry types and validate data on write, kirodotdev#11317) is where the LedgerError "data.agent / data.actor: is required and absent" failures come from, and 9ab334b is where the test_fargate_launch_engine begin_signin/login_target ones come from. Neither file is in this diff, and both reproduce identically at the base: over test_ledger_kinds, test_ledger_retention, test_fargate_launch_engine and test_remove_slot_for_history_key the failing/erroring id sets are 48 on each side and equal. Checks run against refs/pull/N/merge rather than against this branch's base, so main's own breakage lands in this PR's results whatever this branch is rebased onto. The measurement above is what tells the two apart. Co-authored-by: Joe Guo <zejiangg@amazon.com>
Problem / Motivation
The session ledger owns a vocabulary of entry types, and
TYPE_OWNERSHIPanswerswhether a kind of unit has such events at all. Nothing answered the next question:
what does one entry of a given type actually carry. The shape of a
datapayloadwas stated twice, once in the emitter that builds it and once in a spec table
describing it, and two statements of one fact drift. A writer learned the shape by
reading call sites and a reader learned it by reading entries, so a field could be
renamed on one side and silently dropped on the other.
The drift is not hypothetical, and this PR's own diff is the evidence: base tests
appended
turn/completedas{"turn": 1, "reason": "end_turn"}whileon_turn_completedwritesstop_reason(session_ledger_emit.py:2597). Nothingdeclared the payload, so the wrong field name sat in the repo undetected. RFC
#10090 settled the envelope and the event families, not what a
datapayloadcarries; this adds that per-type layer on top of it, following the emitter
conventions settled by #10091 (merged as 69aeb28).
Why it matters
A misspelled field is the failure this prevents. Without a declaration, a caller
that writes
tokens.inputsinstead oftokens.inputis told the entry landed asasked, while the value it meant to record is gone. Nothing surfaces that, because
the entry is well formed and the type is owned; only the payload is wrong. The
same gap makes every consumer of the ledger guess which fields it may rely on.
What changed
kiro_crew.ledger.entry_typesdeclares the 20 session entry types that have awriter as data: one
EntryTypeper type, oneFieldper member, carrying theJSON type, whether the field is required, enum values, whether that vocabulary is
closed, array item types and nested members. 99 top-level fields are declared, 106
counting nested members, 68 of those required.
Ledger.append,Ledger.append_manyand the chunk-citing path inappend_manyvalidate
dataagainst that declaration before any byte is written, so a refusalcosts nothing and cannot tear a file. A refusal raises
LedgerErrorwith the newadditive code
bad_data_fieldand afieldnaming the offending path(
data.tokens.input,data.items[0].state), so a caller can point at it withoutparsing prose.
bad_data_fieldis a new code this PR adds, additive alongside theexisting
bad_data:bad_datais about the payload as a whole and stays untouched,while this one is about a field of a declared type.
Two deliberate limits keep the registry from destroying records:
ledgers and any future family working without this layer learning about them.
turn/started.actorandturn/refused.actorare coerced toACTORSat the emitter, so enforcing themcosts nothing. Everything else - a provider's
stop_reason, the gateway'send_reason, a provider's toolstatus, a subagent runtime's outcome - isrecorded for the reference tables and not enforced, because enforcing an
upstream vocabulary converts "the upstream set grew" into a lost entry.
The same declarations render as a Markdown reference via
python -m kiro_crew.ledger.entry_types --markdown, so the table is generatedfrom the enforced source instead of maintained beside it.
Existing test payloads across
test_ledger_core.py,test_ledger_lease.py,test_ledger_edge_exhaustion.py,test_session_ledger_emit.pyand the twotest/fixtures/ledger_*_child.pyhelpers were completed to satisfy thedeclarations they now pass through. #11185 only appends to
test_ledger_core.pyand #11193 touches neither file, so the rebase surface here is small.
Discrepancies found between the spec table and the emitter
The brief asks for these to be listed, and the emitter wins each one.
plan/updated,background/completed,subagent/spawned,subagent/steered,subagent/completed,subagent/failed.session_ledger_emithas noon_plan_*,on_background_*oron_subagent_*entry point at all, so thereis no producing site to read a shape off. They are NOT declared. Declaring them
would state a shape nothing produces, and the first emitter to land would have
to satisfy a contract written without it - and because the emitter classifies a
validation failure as a permanent refusal, a mismatch would be dropped and
counted in
dropped_writes(). Undeclared types pass through untouched, which isthe posture
message/steeredalready gets. feat(ledger): resolve slot keys and wire eight session emitters #11185 wires these emitters; a smalladditive PR declares them once it lands.
requiredholds only when every writer produces the field. The crash-repaircloser knows the turn and the reason and nothing else, and a required field it
cannot supply would refuse the one write that closes an interrupted turn.
message/steeredhas an entry point whose own docstring records that it has noproduction caller, so it stays undeclared with the other eight never-written
types a sibling work item is removing.
turn/completed.tokensnames four dimensions the spec marks individuallyoptional.
on_turn_completedbuilds the whole mapping in a single literal witheach dimension defaulted to zero, so a present
tokensalways carries all fourand they are required INSIDE the object. The parent field stays optional, which
is what lets the crash-repair closer write a
turn/completedwith notokensat all.
One gap this change does not close
The crash-repair path appends its closers through
_append_line, notLedger.append, so those writes are not gated by the new validation. The closersare covered by a test that validates them against the registry explicitly, but at
runtime the repair path remains ungated. Both local review lanes independently
confirmed this. Gating it means moving the repair path onto the checked entry
point, which is a change to the repair path rather than to this registry, and
ledger-core.mddocuments that path - so it is tracked as a follow-up sequencedafter #11185, which already edits both.
Tests
573 tests pass across
test_ledger_types.py,test_ledger_core.py,test_ledger_lease.py,test_session_ledger_emit.pyandtest_ledger_edge_exhaustion.py. 35 of them are new, covering:declared types, so a type cannot be declared without an example.
missing required field, a wrong JSON type, an undeclared key, a value outside a
closed enum, a
truewhere a count belongs, and a nested member at its own path.bad.
sit on a type that has a producing site.
rather than restating a list, so wiring an emitter is what makes a declaration
legitimate.
session types nothing writes on this base.
and the module runs as a command.
Mutations killed: 5 of 5. One per enforcement site -
append,append_many, andthe chunk-citing entry - each with a distinct killing test; making
turn/completed.tokensmembers optional again, caught at the member path; andputting a closed enum on a type with no producing site, caught by the rule test.
Manual verification
Run from the worktree root, tests with
-n 2and every heavy step serialised:python -m pytest test/test_ledger_types.py test/test_ledger_core.py test/test_ledger_lease.py test/test_session_ledger_emit.py test/test_ledger_edge_exhaustion.py -n 2 -q- 573 passed.python -m kiro_crew.ledger.entry_types --markdownrenders the reference table.scripts/check_black_formatting.py, and mypy onsrc/kiro_crew/ledgerare clean.scripts/docs_lint.py,scripts/docs-lint.sh,scripts/check_lockdown_before_publish.pyand the seven base-scoped gates passwith their base ref set to
origin/main. The comment-history gate reports itsscope as 11 changed files against the merge base, so it is not a vacuous pass.
The pre-existing mypy findings in
test_ledger_core.pyare on lines this changedoes not touch and are deliberate wrong-type arguments in existing tests.
Related Issues
Builds on merged RFC #10090, which settled the envelope and the event families
rather than any per-type payload shape. Follows #10091 (merged as 69aeb28).
Shares a test file with #11185 and no files with #11193.
Pattern harvest
Two patterns worth reusing.
A declaration is only as strong as the code that honours it: a closed vocabulary
on a type with no writer looks like a guarantee and behaves like a future lost
record. The test that pins this reads the producing modules instead of restating
their list, so the rule cannot be weakened by wiring an emitter later.
A registry added to a live write path should be additive by construction:
undeclared types pass through, and only writer-clamped vocabularies refuse. That
keeps the failure mode "a mistake is caught" rather than "a record is destroyed".
Other suggestions on the work
Three follow-ups, all deliberately outside this PR.
plan/updated,background/completedand the foursubagent/*types are leftundeclared here because nothing writes them on this base. #11185 wires those
emitters; once it lands, a small additive PR declares the six against the shapes
those writers actually produce, which is a stronger warrant than the spec table
gives today.
docs/system-specs/modules/ledger-core.mdsection 5 still carries hand-maintainedper-type tables, and several diverge from what the emitters write. Generating that
section from
render_markdownis the point of having the dump, and is tracked asWI-4 work (noted on #11313). It is not done here because #11185 already edits that
same spec while wiring the emitters, so reconciling it in parallel would collide.
Until then
render_markdownhas only test callers by design: it is the generatorthat follow-up consumes, not a second statement of the fact.
Moving the crash-repair closers onto
Ledger.appendcloses the runtime gap namedabove. It touches the repair path in
store.pyand the spec that documents it,both of which #11185 also edits, so it is sequenced after that merge.
minimal_data, the smallest-valid-payload builder, lives intest/ledger_type_helpers.pyrather than beside the declarations, because everycaller is a test - the production write path is handed real data by its emitter.
Both local review lanes ran on
claude-opus-5rather than their pinnedgpt-5.6-solandclaude-opus-4.8, so local green here is weaker than servergreen and the CI lanes are the authority.
Checklist
bad_data.