Skip to content

feat(ledger): declare the session entry types and validate data on write - #11317

Merged
iamwhatever merged 1 commit into
kirodotdev:mainfrom
chenmingwei23:feat/ledger-type-schema
Sep 17, 2026
Merged

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

Conversation

@chenmingwei23

@chenmingwei23 chenmingwei23 commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

The session ledger owns a vocabulary of entry types, and TYPE_OWNERSHIP answers
whether 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 data payload
was 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/completed as {"turn": 1, "reason": "end_turn"} while
on_turn_completed writes stop_reason (session_ledger_emit.py:2597). Nothing
declared the payload, so the wrong field name sat in the repo undetected. RFC
#10090 settled the envelope and the event families, not what a data payload
carries; 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.inputs instead of tokens.input is told the entry landed as
asked, 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_types declares the 20 session entry types that have a
writer as data: one EntryType per type, one Field per member, carrying the
JSON 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_many and the chunk-citing path in append_many
validate data against that declaration before any byte is written, so a refusal
costs nothing and cannot tear a file. A refusal raises LedgerError with the new
additive code bad_data_field and a field naming the offending path
(data.tokens.input, data.items[0].state), so a caller can point at it without
parsing prose. bad_data_field is a new code this PR adds, additive alongside the
existing bad_data: bad_data is 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:

  • A type with no declaration passes through untouched. This is what keeps crew
    ledgers and any future family working without this layer learning about them.
  • Only a vocabulary the writer itself clamps is enforced. turn/started.actor and
    turn/refused.actor are coerced to ACTORS at the emitter, so enforcing them
    costs nothing. Everything else - a provider's stop_reason, the gateway's
    end_reason, a provider's tool status, a subagent runtime's outcome - is
    recorded 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 generated
from 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.py and the two
test/fixtures/ledger_*_child.py helpers were completed to satisfy the
declarations they now pass through. #11185 only appends to test_ledger_core.py
and #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.

  1. Six types the spec table describes have no writer on this base: plan/updated,
    background/completed, subagent/spawned, subagent/steered,
    subagent/completed, subagent/failed. session_ledger_emit has no
    on_plan_*, on_background_* or on_subagent_* entry point at all, so there
    is 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 is
    the posture message/steered already gets. feat(ledger): resolve slot keys and wire eight session emitters #11185 wires these emitters; a small
    additive PR declares them once it lands.
  2. A few fields the spec table marks required are optional here, because
    required holds only when every writer produces the field. The crash-repair
    closer 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.
  3. message/steered has an entry point whose own docstring records that it has no
    production caller, so it stays undeclared with the other eight never-written
    types a sibling work item is removing.
  4. turn/completed.tokens names four dimensions the spec marks individually
    optional. on_turn_completed builds the whole mapping in a single literal with
    each dimension defaulted to zero, so a present tokens always carries all four
    and they are required INSIDE the object. The parent field stays optional, which
    is what lets the crash-repair closer write a turn/completed with no tokens
    at all.

One gap this change does not close

The crash-repair path appends its closers through _append_line, not
Ledger.append, so those writes are not gated by the new validation. The closers
are 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.md documents that path - so it is tracked as a follow-up sequenced
after #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.py and
test_ledger_edge_exhaustion.py. 35 of them are new, covering:

  • Every canonical example validates, and the canonical set covers exactly the
    declared types, so a type cannot be declared without an example.
  • Negative cases per rule, parametrised rather than hand-written per type: a
    missing required field, a wrong JSON type, an undeclared key, a value outside a
    closed enum, a true where a count belongs, and a nested member at its own path.
  • A refusal leaves the file byte-identical and the handle usable.
  • A group is refused whole when one member is bad, and when the citing entry is
    bad.
  • The closed-enum rule is held to code that exists: a closed vocabulary may only
    sit on a type that has a producing site.
  • The declared set IS the set with a producing site, derived by reading the writers
    rather than restating a list, so wiring an emitter is what makes a declaration
    legitimate.
  • What is not declared passes through, including crew families and the fifteen
    session types nothing writes on this base.
  • The Markdown dump covers every type and field, addresses nested members by path,
    and the module runs as a command.

Mutations killed: 5 of 5. One per enforcement site - append, append_many, and
the chunk-citing entry - each with a distinct killing test; making
turn/completed.tokens members optional again, caught at the member path; and
putting 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 2 and 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 --markdown renders the reference table.
  • flake8, isort, black 26.3.1 via scripts/check_black_formatting.py, and mypy on
    src/kiro_crew/ledger are clean.
  • scripts/docs_lint.py, scripts/docs-lint.sh,
    scripts/check_lockdown_before_publish.py and the seven base-scoped gates pass
    with their base ref set to origin/main. The comment-history gate reports its
    scope as 11 changed files against the merge base, so it is not a vacuous pass.

The pre-existing mypy findings in test_ledger_core.py are on lines this change
does 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/completed and the four subagent/* types are left
undeclared 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.md section 5 still carries hand-maintained
per-type tables, and several diverge from what the emitters write. Generating that
section from render_markdown is the point of having the dump, and is tracked as
WI-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_markdown has only test callers by design: it is the generator
that follow-up consumes, not a second statement of the fact.

Moving the crash-repair closers onto Ledger.append closes the runtime gap named
above. It touches the repair path in store.py and 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 in
test/ledger_type_helpers.py rather than beside the declarations, because every
caller is a test - the production write path is handed real data by its emitter.

Both local review lanes ran on claude-opus-5 rather than their pinned
gpt-5.6-sol and claude-opus-4.8, so local green here is weaker than server
green and the CI lanes are the authority.

Checklist

  • Tests cover the new behaviour, and each new behaviour is mutation-verified.
  • Lint, format, type and repo gates pass locally.
  • One commit, no unrelated changes.
  • The new error code is additive and does not change bad_data.
  • Public surface documented in the module that owns it.

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

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5, fork) — 🟡 CONCERNS

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

Design-Verdict: CONCERNS

The drift this PR exists to kill survives it: the owning specs still state the old shapes, unreconciled and unpinned to the new registry.

Watch

The 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. session-ledger-emitter.md keeps its payload table, ledger-core.md documents the append path's refusal codes as API surface (line 190) plus its own payload table (line 97), and this PR adds a new refusal stage and bad_data_field code to that path without updating either — despite AGENTS.md's same-commit rule. Consequence: a contributor writing a payload from the spec that the registry doesn't declare gets the entry permanently dropped and counted in dropped_writes(), silent record loss caused by trusting the doc — the exact failure the PR argues it prevents, now with three statements of one fact instead of two.
Clears when: both owning specs are updated in this PR (or their tables replaced by a pointer to --markdown), and a test pins the spec's tables to render_markdown() output so they cannot drift again.

Suggestions

  • Since render_markdown exists precisely so the table is "generated from the enforced source," a parity test (spec section == rendered output) closes the loop more durably than a one-time manual reconciliation.

[DESIGN-REVIEWED] 58ba8a3

@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review (fork) — ✅ no blocking findings

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

Review details

No findings.
[GPT-REVIEWED] 58ba8a3

@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

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

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

First-Principles-Verdict: CONCERNS

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

  • Item 4 — zero consumers: "the table is generated from the enforced source instead of maintained beside it" — yet the diff touches no doc; grepped render_markdown across base and patch: only test_ledger_types.py consumes it, and the hand table (docs/system-specs/modules/session-ledger-emitter.md:43-60) stays hand-maintained.
    Subtraction: delete render_markdown, main and their kiro_crew.ledger exports until the generated output actually replaces the hand rows.
    Clears when: the generated table replaces the hand-maintained rows (a first real consumer), or the renderer is deleted.
  • Item 2 — inherited: "Implements the registry described in merged RFC docs: append-only ledger RFC #10090" — rfc-append-only-ledger.md (grepped registry|declar|schema|valid: zero hits) describes envelope and families, never a data-shape registry or write-time validation; the checkable provenance is the defect this diff itself evidences (base tests wrote reason where the emitter writes stop_reason).
    Clears when: the description grounds the registry in that checkable defect instead of an RFC that does not record it.

What this change ships

Inventory (7 items) — 5 justified

Intent: stop a misspelled or mistyped data field from landing silently in an append-only session ledger — an ADDITION.

  1. A write on a declared session type with a missing, misspelled, mistyped, or out-of-closed-enum field is refused before any byte lands — justified
  2. A machine-readable registry of the 20 written session types, public on kiro_crew.ledger — inherited: cited RFC docs: append-only ledger RFC #10090 describes no registry
  3. Refusals carry new code bad_data_field naming the offending path, beside untouched bad_data — justified
  4. python -m kiro_crew.ledger.entry_types --markdown renders reference tables — zero consumers: nothing but its own tests invokes it
  5. Undeclared types (15 unwritten session types, crew and guest families) pass through untouched — justified
  6. Spec-required fields the crash-repair closer cannot supply are enforced optional — justified
  7. Existing test payloads and fixtures completed; minimal_data helper builds smallest-valid payloads — justified

[FIRST-PRINCIPLES-REVIEWED] 58ba8a3

@github-actions

github-actions Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Opus 4.8 Review (fork) — ✅ no blocking findings

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

Review details

No findings.

[OPUS-REVIEWED] 58ba8a3

@chenmingwei23
chenmingwei23 force-pushed the feat/ledger-type-schema branch from ba2e842 to 61c3a31 Compare September 16, 2026 15:05
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Sep 16, 2026
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.
@chenmingwei23
chenmingwei23 force-pushed the feat/ledger-type-schema branch from 61c3a31 to 58ba8a3 Compare September 16, 2026 15:39
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 16, 2026
@chenmingwei23

Copy link
Copy Markdown
Contributor Author

Dispositions for this round, on head 58ba8a3bf8.

First Principles BLOCK -- fixed by subtraction. The verdict was right: the six
declarations for plan/updated, background/completed and the four subagent/*
types rested on "a specified, tested entry point in session_ledger_emit", and
that entry point does not exist on this base -- on_plan_*, on_background_* and
on_subagent_* are all absent. The six EntryType blocks, their CANONICAL
examples and the tests that exercised them are deleted. The registry declares 20
types, exactly the set with a producing site, and the six pass through undeclared
like message/steered already does. #11185 wires those emitters; a small additive
PR declares them against what those writers actually produce once it lands.

A test now holds this rule to code rather than to a list: it reads the producing
modules and asserts the declared set equals the set of types they name, so wiring
an emitter is what makes a declaration legitimate.

First Principles item 6, minimal_data -- taken. It had only test callers, so
it moved to test/ledger_type_helpers.py and is out of kiro_crew.ledger.__all__.

First Principles item 5, render_markdown -- kept, with its consumer named.
The dump is the generator for replacing the hand-maintained per-type tables in
docs/system-specs/modules/ledger-core.md section 5, which is tracked as WI-4
work (noted on #11313). It is not done in this PR because #11185 already edits that
same spec while wiring the emitters, so reconciling it here would collide on one
file. Until that lands the dump has test callers only, by design.

Design Review CONCERNS -- agreed, and it is the same finding. The spec's
section 5 tables do diverge from what the emitters write, and every instance named
checks out: message/sent lists usage the registry has no field for,
tool/completed omits the required name/server, approval/requested says id
where the registry requires approval_id, subagent/completed lists
tokens, credits. Deleting the six declarations removes the sharpest edge of it,
since those were the types a contributor would have wired from that table. The
remaining divergence is the WI-4 generation work above, and the suggested
doc-to-registry parity test belongs with it -- pinning parity against tables that
are about to be regenerated would pin the wrong side.

GPT 5.6 -- taken. The entry_types docstring no longer claims a warrant the
base contradicts; the derivation paragraph now says what it can, which is that
every declared field is read off its writer. The earlier finding on the shared
_TOKEN_FIELDS tuple is also settled: with background/completed gone,
turn/completed is the only consumer and the four dimensions are required inside
the mapping, while the mapping itself stays optional so the crash-repair closer can
still write a turn/completed with no tokens.

Two claims in the PR description were wrong and are corrected. It said
bad_data_field was "reused from main rather than freshly minted" -- it is absent
on origin/main, so this PR adds it, additive alongside the untouched bad_data.
It also carried the same false "specified, tested entry point" warrant the BLOCK
named. Counts are restated: 20 types, 99 top-level fields, 106 counting nested
members, 68 required.

E2E (stub ACP backend, offline) failed in Require real private workflow MCP execution, which is unrelated to the ledger and has been seen on other PRs; this
push re-runs it.

573 tests pass across the five ledger test files, 5 of 5 mutations killed, and the
13 local gates are clean including the subprocess text-mode encoding gate that
caught the new python -m test -- that call now passes encoding="utf-8" rather
than the baseline being widened.

@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision readiness: checking Automated validation is still running and removed readiness: checking Automated validation is still running readiness: passed Eligible automated validation passed for the current revision labels Sep 16, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor

Reviewed on the current head for approval. readiness: passed is green because whole-design CONCERNS are advisory server-side; they still need an answer before a human approval lands. Fork-risk scan (CI, install, deps, network, subprocess, eval): clean. Holding on the items below.

  • Design Watch (updated after your 15:40Z comment): both owning specs must be updated in this PR and a test must pin the spec tables to render_markdown(). Not done.
  • First Principles "Not justified as shipped": render_markdown has zero consumers; either add one or apply the subtraction.
  • Your own comment concedes four spec/registry divergences (message/sent lists usage with no field; tool/completed omits required name/server; approval/requested says id vs approval_id) and defers them to WI-4/feat(ledger): resolve slot keys and wire eight session emitters #11185 with no deferred-finding issue, owner or due date. File it.
  • Because an undeclared key is refused and the emitter counts a LedgerError as a permanent drop, any declaration that mismatches its writer silently loses entries. Worth stating in the body.

@iamwhatever
iamwhatever merged commit 039d3e8 into kirodotdev:main Sep 17, 2026
96 of 102 checks passed
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Sep 17, 2026
iamwhatever pushed a commit that referenced this pull request Sep 17, 2026
…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.
@didhd didhd mentioned this pull request Sep 17, 2026
5 tasks done
iamwhatever pushed a commit that referenced this pull request Sep 17, 2026
…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.
iamwhatever pushed a commit that referenced this pull request Sep 17, 2026
…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.
iamwhatever pushed a commit that referenced this pull request Sep 17, 2026
…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.
iamwhatever pushed a commit that referenced this pull request Sep 17, 2026
…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.
iamwhatever pushed a commit that referenced this pull request Sep 17, 2026
…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.
iamwhatever pushed a commit that referenced this pull request Sep 17, 2026
…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.
iamwhatever pushed a commit that referenced this pull request Sep 17, 2026
…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.
iamwhatever pushed a commit that referenced this pull request Sep 18, 2026
…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.
iamwhatever pushed a commit that referenced this pull request Sep 18, 2026
…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.
chenmingwei23 pushed a commit that referenced this pull request Sep 18, 2026
…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>
amadsalmon pushed a commit to amadsalmon/KiroCrew that referenced this pull request Sep 22, 2026
…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.
amadsalmon pushed a commit to amadsalmon/KiroCrew that referenced this pull request Sep 22, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants