diff --git a/docs/system-specs/modules/learn-cron-dashboard.md b/docs/system-specs/modules/learn-cron-dashboard.md index 379b2b989b62..13970e94e0dd 100644 --- a/docs/system-specs/modules/learn-cron-dashboard.md +++ b/docs/system-specs/modules/learn-cron-dashboard.md @@ -1218,7 +1218,7 @@ specified compatibility change. headless Slack/API server attach the service to application and dashboard state and close it during runner cleanup; explicit offline test gateways use the service's `assume_ready` mode. -- `handlers/members.py` owns the Crew Members page routes. A `cfg.agents` key is an exact Crew Member display name validated by `members.validate_member_name`. The display name does not use `_AGENT_NAME_RE`. `kiro_agent` template identifiers use `validation.TEMPLATE_NAME_RE` at create, update, publish, and CLI boundaries. `_AGENT_NAME_RE` remains the grammar for slot names, workspaces, and spec-file resolution. Routes preserve the exact display name and resolve its stable member ID and path-safe slug through `members.member_slug`. `GET /api/members` returns one roster row per GLOBAL crew (name, slug via `members.member_slug`, the crew-record fields, `bound`/`slot_key` from the member dir's `dm.json` read off-loop, and an O(1) `running` flag); richer live detail rides the already-subscribed WS `slots` frames, so the endpoint only fills the cold-start gap. It is a read with one ownership-gated write: a member with no event log is served from live config, and each row carries the `roster` projection alone, so `GET /api/members/{slug}/projections?member=` serves the open drawer's remaining views for the one member it has open; the only append the roster read performs is the config/preview reconcile into a log whose header holds that exact member name (or no header yet) -- a placeholder or foreign header is served but never written to. `GET /api/members` OMITS a stored name that fails `members.is_dispatchable_member_name`, so a name that becomes non-dispatchable never reaches the roster. A legacy spelling that differs from a valid name ONLY by NFC canonicalization stays dispatchable — it reaches the roster and its thread opens under its exact stored bytes, without rewriting the stored name, slug, binding ownership, or `member_pin_matches` equality to NFC. The count-and-recreate path below applies to every OTHER non-dispatchable name: the owner-only Crew Manager catalog still lists the record, and `kirocrew doctor` reports only the number of affected names. It never prints the names or their slugs. Crew Manager has no rename operation. Create a replacement with a safe name, make it the default if needed, then delete the old record. The replacement gets a new member identity. It does not inherit the old member key's DM history. `POST /api/members/{slug}/thread` is the idempotent get-or-create of a member's pinned DM thread and the ONLY birthplace of member slots: it derives `member-` for V1 and `member-.memory-` for a new V2 member's store generation (`members.member_slot_key`). An existing canonical V2 thread keeps its bound key. Existing V1 members keep their memory and thread bindings; creating a separate V2 member does not import V1 messages or native provider context. The persisted DM binding records the current generation, and restore, send, OpenAI-compatible requests and rule reinjection follow that exact key. The endpoint creates the slot with `mode="member"` and the crew as its agent, and persists the binding via `members.write_dm_binding` (atomic, records the exact crew name so a lossy slug collision stays disambiguated). `mode="member"` is what keeps these threads out of the ordinary Sessions list (the frontend surface filter never admits it) and it round-trips through history restore, so the pin survives restarts. The pin itself is enforced at every agent-writer and again at the local model-dispatch chokepoint: the chat send path and the slot-agent switch endpoint refuse re-pinning with 409 `member_thread_agent_pinned`, the OpenAI-compat per-request write refuses in OpenAI error shape, a mid-turn `EVENT_AGENT_SWITCHED` on a member slot is vetoed (slot agent kept, session marked for reset so the next turn cold-starts on the pinned crew), and `_run_chat` refuses a non-dispatchable stored member name before provider acquisition or context construction. Boot restore skips such a binding, while explicit resume, chat send, slot-agent update, and OpenAI-compatible requests return 409 `member_pin_mismatch`; this keeps credential-shaped or otherwise unsafe legacy names out of prompts even when an internal caller bypasses HTTP routes. App tokens are denied on both routes. Errors carry machine-readable `code` fields (`invalid_member_slug`, `member_not_found`, `member_slot_conflict`, `member_binding_write_failed`, `member_pin_mismatch`). **Reopening a RUNNING member thread is read-only.** The owner clicking their own member while a turn is in flight is the ordinary case, not a conflict, so the endpoint answers it without writing an assignment and without touching the turn: 200 only when the live slot is still the registered one, its session is the canonical member key, its agent/mode/store still match, the session's published private store matches, the member still privately owns that store (`chat_persistence.member_store_ownership_holds` — immutable member id, sole ownership, the store database's own recorded identity, AND the record's `owner_member` name, because that last field is what `session_control` admits on), and the persisted `dm.json` binding still names this slot and member; anything else is 409 `member_slot_conflict` (with the linked-session and differing-assignment messages kept distinct). The same validation answers BOTH running windows — a turn already in flight on entry, one that starts while the opener waits for `slot._lock`, and one that starts while it awaits the assignment — because `slot._lock` does NOT exclude turn dispatch (`api_chat` reads `slot.running` and publishes `slot.task` without taking it), so the route re-checks `slot.running` after the assignment too and drops the assignment write rather than publishing onto a live turn. Lock order on this route is **dashboard config → `slot._lock` → `memory_store_namespace_lock`**, matching member create/update/delete (config → namespace); the namespace lock is held from the fresh config load and ownership validation through `bind_session_execution`, so a member deleted, recreated or repointed mid-request is refused instead of published. **Member system prompt (four layers, distinct ownership)**: a member DM turn passes `member=slot.agent` (the crew name — distinct from `agent=`, which is the resolved TEMPLATE) into `build_message`, and `ContextBuilder._build_member_section` injects a `[MEMBER IDENTITY]` block right after the `[CURRENT AGENT]` identity for `mode="member"` sessions only. Layer 1 (identity) is DERIVED from the crew's registered config (name, description, triggers) so a crew with an empty description still gets a floor; layer 2 (`[HOW YOU WORK]`, the module constant `_MEMBER_HOW_YOU_WORK`) is the product-owned working protocol — worker-not-Q&A-bot, front-desk-vs-workshop dispatch, the four-rung stuck ladder (different approach → alternative around the wall → escalate only at a permission/reachability/one-way-door wall → park and continue), zero-context escalation format with a stranger's-eye self-review, quiet-run reporting, and briefing self-maintenance; layer 3 (`[PERMANENT RULES]`) is USER-owned, stored as JSON (`{member, slug, rules}`) at `trust/member-rules/.json` under the keystone-gated `trust/` subtree so the member's own file tools cannot rewrite its safety boundary — the payload records the EXACT crew name (slugification is lossy, same reason `dm.json` does) and the read is name-scoped, so a colliding crew name reads the shared file as "never set" rather than inheriting another member's boundary; an EXISTING file that cannot be read/parsed raises `MemberRulesUnreadable` which PROPAGATES and aborts the member turn (degrading to an ordinary session would let a member the user bounded run with no bounds — the one layer where degrade is fail-open); refused-not-truncated at `MEMBER_RULES_MAX_CHARS` on write, empty write deletes; layer 4 (`[CURRENT ASSIGNMENT]`) is MEMBER-owned working memory read from the agent-writable `members//briefing.md`, injection-capped at `MEMBER_BRIEFING_MAX_CHARS` with a visible truncation marker — and because the file is agent-written and read with the GATEWAY's privileges, the read refuses a symlink leaf at open time (`O_NOFOLLOW`; on platforms WITHOUT the flag — Windows — the read fails CLOSED to "no briefing", since a check-then-open probe is exactly the TOCTOU an agent-writable path invites), opens `O_NONBLOCK` and rejects non-regular files via `fstat` (an agent-planted FIFO would otherwise block the open forever and hang the member's turn) so a briefing repointed at a trust/ payload cannot enter the prompt, and reads at most `(cap+2)*4` bytes so an arbitrarily large briefing costs a bounded allocation. Every VARIABLE payload the section frames (name, description, triggers, rules, briefing) is scrubbed of forgeable member-authority markers (`_MEMBER_MARKER_RES` — both the genuine variable-tail forms and the exact closing-bracket spellings; detection runs on a normalized view — NFKC first, so fullwidth/compatibility glyphs collapse to ASCII, then Cf dropped and dashes folded — but the rewrite is span-local in the ORIGINAL text via an origin map, so legitimate fullwidth paths, emoji ZWJ sequences and prose dashes outside a forgery reach the member byte-exact; if the span-scrubbed result still trips any pattern on the whole-string normalized view the scrub fails closed to injecting that fully-normalized view with every match substituted) BEFORE the genuine headers are minted around it, so a forged `[PERMANENT RULES — …]` (or bare `[PERMANENT RULES]`) planted in the agent-writable briefing cannot render as the user-owned layer; the patterns are deliberately NOT in `_STRUCTURAL_MARKER_RES`, whose scan covers the session-context tail CONTAINING the genuine section. The member section is also re-injected on the post-compaction `needs_reinjection` turn (beside the skills index), re-reading the CURRENT briefing and passed through `_neutralize_structural_markers` (that path has no session-context tail scrub; the genuine member headers are not in `_STRUCTURAL_MARKER_RES`, so they survive) — without it a compacted member thread would run with no identity and no permanent rules. Precedence is the injection order with one stated exception: layer 3's header explicitly outranks the whole section — the working protocol above included — so the user's safety boundary is never formally outranked by product prose. The rules layer is prompt-level STEERING, not runtime enforcement: nothing at the PreToolUse gate reads these rules, so any UI over them (the eventual rules editor included) must present them as instructions the member follows, never as enforced policy — governance profiles are the enforced path. `GET/PUT /api/members/{slug}/rules` is the rules layer's ONLY write path (a human dashboard action: app tokens denied; GET requires the exact `member` query name like the activity endpoint and answers `""` for absent rules but 500 `rules_unreadable` for an unreadable file; PUT off-loads config load, requires slug-match + a registered crew, and REFUSES with 409 `rules_slug_ambiguous` when two registered crews collide onto the slug — one file per slug, so either save would overwrite the other's safety boundary; `member_slug_mismatch`/`member_not_found`/`rules_too_long`/`missing_rules` codes (the `rules` key is REQUIRED — an omitted key must not read as the documented empty-string clear); successful reads and writes emit `allowed` SEL api-access events (`members.rules.read`/`members.rules.write` — the rules are the owner's private safety boundary, so disclosure and change both leave a trace); a successful write also flags the thread's session `needs_reinjection` — best-effort — so a WARM member session picks the fresh rules up on its next turn instead of running under the old boundary until a compaction or cold start). +- `handlers/members.py` owns the Crew Members page routes. A `cfg.agents` key is a Crew Member name validated by `members.validate_member_name`. A NEW crew is keyed by an id (`members.is_crew_id`, the `_AGENT_NAME_RE` grammar) and shows `display_name`: `POST /api/agents` and `kirocrew agent create` keep an id-shaped `name` as the key, and turn a free-form one (spaces, CJK) into the `display_name` of an id `members.crew_id_for_display_name` derives (slug, `-2`… past a taken id, `crew-` for a name with no slug characters); the create answer's `name` is that id. Both create surfaces decide through `members.key_new_crew`: the create is `409 agent_exists` when the key is taken, or when the name the new crew would show (an explicit `display_name`, else the typed free-form name, else the key) is exactly what another crew already shows (its `display_name`, else its key). Editing an existing crew's `display_name` is not checked. Crews already stored under a free-form key stay readable and addressable and are never renamed. `kiro_agent` template identifiers use `validation.TEMPLATE_NAME_RE` at create, update, publish, and CLI boundaries. `_AGENT_NAME_RE` remains the grammar for slot names, workspaces, and spec-file resolution. Routes preserve the exact display name and resolve its stable member ID and path-safe slug through `members.member_slug`. `GET /api/members` returns one roster row per GLOBAL crew (name, slug via `members.member_slug`, the crew-record fields, `bound`/`slot_key` from the member dir's `dm.json` read off-loop, and an O(1) `running` flag); richer live detail rides the already-subscribed WS `slots` frames, so the endpoint only fills the cold-start gap. It is a read with one ownership-gated write: a member with no event log is served from live config, and each row carries the `roster` projection alone, so `GET /api/members/{slug}/projections?member=` serves the open drawer's remaining views for the one member it has open; the only append the roster read performs is the config/preview reconcile into a log whose header holds that exact member name (or no header yet) -- a placeholder or foreign header is served but never written to. `GET /api/members` OMITS a stored name that fails `members.is_dispatchable_member_name`, so a name that becomes non-dispatchable never reaches the roster. A legacy spelling that differs from a valid name ONLY by NFC canonicalization stays dispatchable — it reaches the roster and its thread opens under its exact stored bytes, without rewriting the stored name, slug, binding ownership, or `member_pin_matches` equality to NFC. The count-and-recreate path below applies to every OTHER non-dispatchable name: the owner-only Crew Manager catalog still lists the record, and `kirocrew doctor` reports only the number of affected names. It never prints the names or their slugs. Crew Manager has no rename operation. Create a replacement with a safe name, make it the default if needed, then delete the old record. The replacement gets a new member identity. It does not inherit the old member key's DM history. `POST /api/members/{slug}/thread` is the idempotent get-or-create of a member's pinned DM thread and the ONLY birthplace of member slots: it derives `member-` for V1 and `member-.memory-` for a new V2 member's store generation (`members.member_slot_key`). An existing canonical V2 thread keeps its bound key. Existing V1 members keep their memory and thread bindings; creating a separate V2 member does not import V1 messages or native provider context. The persisted DM binding records the current generation, and restore, send, OpenAI-compatible requests and rule reinjection follow that exact key. The endpoint creates the slot with `mode="member"` and the crew as its agent, and persists the binding via `members.write_dm_binding` (atomic, records the exact crew name so a lossy slug collision stays disambiguated). `mode="member"` is what keeps these threads out of the ordinary Sessions list (the frontend surface filter never admits it) and it round-trips through history restore, so the pin survives restarts. The pin itself is enforced at every agent-writer and again at the local model-dispatch chokepoint: the chat send path and the slot-agent switch endpoint refuse re-pinning with 409 `member_thread_agent_pinned`, the OpenAI-compat per-request write refuses in OpenAI error shape, a mid-turn `EVENT_AGENT_SWITCHED` on a member slot is vetoed (slot agent kept, session marked for reset so the next turn cold-starts on the pinned crew), and `_run_chat` refuses a non-dispatchable stored member name before provider acquisition or context construction. Boot restore skips such a binding, while explicit resume, chat send, slot-agent update, and OpenAI-compatible requests return 409 `member_pin_mismatch`; this keeps credential-shaped or otherwise unsafe legacy names out of prompts even when an internal caller bypasses HTTP routes. App tokens are denied on both routes. Errors carry machine-readable `code` fields (`invalid_member_slug`, `member_not_found`, `member_slot_conflict`, `member_binding_write_failed`, `member_pin_mismatch`). **Reopening a RUNNING member thread is read-only.** The owner clicking their own member while a turn is in flight is the ordinary case, not a conflict, so the endpoint answers it without writing an assignment and without touching the turn: 200 only when the live slot is still the registered one, its session is the canonical member key, its agent/mode/store still match, the session's published private store matches, the member still privately owns that store (`chat_persistence.member_store_ownership_holds` — immutable member id, sole ownership, the store database's own recorded identity, AND the record's `owner_member` name, because that last field is what `session_control` admits on), and the persisted `dm.json` binding still names this slot and member; anything else is 409 `member_slot_conflict` (with the linked-session and differing-assignment messages kept distinct). The same validation answers BOTH running windows — a turn already in flight on entry, one that starts while the opener waits for `slot._lock`, and one that starts while it awaits the assignment — because `slot._lock` does NOT exclude turn dispatch (`api_chat` reads `slot.running` and publishes `slot.task` without taking it), so the route re-checks `slot.running` after the assignment too and drops the assignment write rather than publishing onto a live turn. Lock order on this route is **dashboard config → `slot._lock` → `memory_store_namespace_lock`**, matching member create/update/delete (config → namespace); the namespace lock is held from the fresh config load and ownership validation through `bind_session_execution`, so a member deleted, recreated or repointed mid-request is refused instead of published. **Member system prompt (four layers, distinct ownership)**: a member DM turn passes `member=slot.agent` (the crew name — distinct from `agent=`, which is the resolved TEMPLATE) into `build_message`, and `ContextBuilder._build_member_section` injects a `[MEMBER IDENTITY]` block right after the `[CURRENT AGENT]` identity for `mode="member"` sessions only. Layer 1 (identity) is DERIVED from the crew's registered config (name, description, triggers) so a crew with an empty description still gets a floor; layer 2 (`[HOW YOU WORK]`, the module constant `_MEMBER_HOW_YOU_WORK`) is the product-owned working protocol — worker-not-Q&A-bot, front-desk-vs-workshop dispatch, the four-rung stuck ladder (different approach → alternative around the wall → escalate only at a permission/reachability/one-way-door wall → park and continue), zero-context escalation format with a stranger's-eye self-review, quiet-run reporting, and briefing self-maintenance; layer 3 (`[PERMANENT RULES]`) is USER-owned, stored as JSON (`{member, slug, rules}`) at `trust/member-rules/.json` under the keystone-gated `trust/` subtree so the member's own file tools cannot rewrite its safety boundary — the payload records the EXACT crew name (slugification is lossy, same reason `dm.json` does) and the read is name-scoped, so a colliding crew name reads the shared file as "never set" rather than inheriting another member's boundary; an EXISTING file that cannot be read/parsed raises `MemberRulesUnreadable` which PROPAGATES and aborts the member turn (degrading to an ordinary session would let a member the user bounded run with no bounds — the one layer where degrade is fail-open); refused-not-truncated at `MEMBER_RULES_MAX_CHARS` on write, empty write deletes; layer 4 (`[CURRENT ASSIGNMENT]`) is MEMBER-owned working memory read from the agent-writable `members//briefing.md`, injection-capped at `MEMBER_BRIEFING_MAX_CHARS` with a visible truncation marker — and because the file is agent-written and read with the GATEWAY's privileges, the read refuses a symlink leaf at open time (`O_NOFOLLOW`; on platforms WITHOUT the flag — Windows — the read fails CLOSED to "no briefing", since a check-then-open probe is exactly the TOCTOU an agent-writable path invites), opens `O_NONBLOCK` and rejects non-regular files via `fstat` (an agent-planted FIFO would otherwise block the open forever and hang the member's turn) so a briefing repointed at a trust/ payload cannot enter the prompt, and reads at most `(cap+2)*4` bytes so an arbitrarily large briefing costs a bounded allocation. Every VARIABLE payload the section frames (name, description, triggers, rules, briefing) is scrubbed of forgeable member-authority markers (`_MEMBER_MARKER_RES` — both the genuine variable-tail forms and the exact closing-bracket spellings; detection runs on a normalized view — NFKC first, so fullwidth/compatibility glyphs collapse to ASCII, then Cf dropped and dashes folded — but the rewrite is span-local in the ORIGINAL text via an origin map, so legitimate fullwidth paths, emoji ZWJ sequences and prose dashes outside a forgery reach the member byte-exact; if the span-scrubbed result still trips any pattern on the whole-string normalized view the scrub fails closed to injecting that fully-normalized view with every match substituted) BEFORE the genuine headers are minted around it, so a forged `[PERMANENT RULES — …]` (or bare `[PERMANENT RULES]`) planted in the agent-writable briefing cannot render as the user-owned layer; the patterns are deliberately NOT in `_STRUCTURAL_MARKER_RES`, whose scan covers the session-context tail CONTAINING the genuine section. The member section is also re-injected on the post-compaction `needs_reinjection` turn (beside the skills index), re-reading the CURRENT briefing and passed through `_neutralize_structural_markers` (that path has no session-context tail scrub; the genuine member headers are not in `_STRUCTURAL_MARKER_RES`, so they survive) — without it a compacted member thread would run with no identity and no permanent rules. Precedence is the injection order with one stated exception: layer 3's header explicitly outranks the whole section — the working protocol above included — so the user's safety boundary is never formally outranked by product prose. The rules layer is prompt-level STEERING, not runtime enforcement: nothing at the PreToolUse gate reads these rules, so any UI over them (the eventual rules editor included) must present them as instructions the member follows, never as enforced policy — governance profiles are the enforced path. `GET/PUT /api/members/{slug}/rules` is the rules layer's ONLY write path (a human dashboard action: app tokens denied; GET requires the exact `member` query name like the activity endpoint and answers `""` for absent rules but 500 `rules_unreadable` for an unreadable file; PUT off-loads config load, requires slug-match + a registered crew, and REFUSES with 409 `rules_slug_ambiguous` when two registered crews collide onto the slug — one file per slug, so either save would overwrite the other's safety boundary; `member_slug_mismatch`/`member_not_found`/`rules_too_long`/`missing_rules` codes (the `rules` key is REQUIRED — an omitted key must not read as the documented empty-string clear); successful reads and writes emit `allowed` SEL api-access events (`members.rules.read`/`members.rules.write` — the rules are the owner's private safety boundary, so disclosure and change both leave a trace); a successful write also flags the thread's session `needs_reinjection` — best-effort — so a WARM member session picks the fresh rules up on its next turn instead of running under the old boundary until a compaction or cold start). - `handlers/teams.py` — crewmate teams, the Crewmates page's roster grouping and team view. A team is a name plus an ORDERED list of exact crew names (`kiro_crew.crew_teams.Team` — `crew_teams`, because `kiro_crew.teams` is the Microsoft Teams channel package and a same-named module would be shadowed by it), nothing else: no memory, no chat, no prompt of its own; everything the team view shows is derived from its members' existing threads, activity records and live presence. Storage is one document, `teams.json` in its own data-home directory `crew-teams/` (`{"version": 1, "teams": [{id, name, members}]}` — `TEAMS_SCHEMA_VERSION`, written on every save; a document from a NEWER build is refused whole). The directory is deliberately NOT under `trust/`: `trust` is a declared sandbox READ-WRITE exception (in-sandbox code appends to the audit log there), so a record under it stays writable by a sandboxed command that builds the path at runtime — the `crew-panels` lesson. `crew-teams` is instead a whole-directory leaf on `sandbox._CREW_HIDDEN_LEAVES` (masked from every sandboxed process) and `sandbox._CREW_PRECREATE_HIDDEN_DIR_LEAVES` (materialised empty at 0700 before every spawn, because the store is created on the first team and `mount(2)` cannot mask an absent name) and on `security._CREW_SECRET_LEAVES` (agent file tools refuse read and write); only the gateway, on a human dashboard action, opens it, so a crewmate's own tools cannot re-team itself or its siblings (`test_store_directory_is_masked_and_fenced`). Every mutation runs read → mutate → rewrite under TWO locks — a process-wide `threading.Lock` (`_WRITE_LOCK`) and, inside it, an advisory file lock on `crew-teams/.lock` (`platform_compat.file_lock`, `crew_teams.document_lock`, public only for the cross-process test; NOT re-entrant — no caller holds it across another store call): the gateway's writers (owner routes, the crew create/delete/sync hooks) run off-loop in worker threads, `kirocrew agent create` / `delete` write from ANOTHER process, and only the file lock reaches it; a contended acquire past the default ceiling fails closed as `OSError` → 500 `teams_write_failed` rather than writing unserialized (`test_writers_hold_a_cross_process_file_lock`) — atomically with fsync (`crew_teams.write_teams`; the parent-directory sync after the committed rename is best-effort, because the rename has already published the document and a 500 there would make a retry create the team twice — `test_a_failed_directory_sync_does_not_fail_a_committed_write`), and the read (`crew_teams.read_teams`) treats an ABSENT file as no teams but an existing-yet-unparseable one — or one past any cap it declares: more than `TEAMS_MAX` teams, a non-12-hex id, a blank or over-`TEAM_NAME_MAX_CHARS` name, more than `TEAM_MEMBERS_MAX` members, an empty or over-`MEMBER_NAME_MAX_CHARS` member, or a name or member holding an escaped lone surrogate (legal JSON, unencodable as UTF-8 — retained, it would make the next mutation's own encode raise mid-write) (`test_read_refuses_a_document_past_the_caps`) — as `TeamsUnreadable`, which every route answers as 500 `teams_unreadable` rather than an empty list — reading it empty would let the next write erase every team the user made. There is deliberately NO repair route: a route that reset the document would have to read the document it is repairing, and an unreadable document also refuses crew creation (below), so the accepted remedy is the operator's shell — fix the `teams.json` document inside the data home's `crew-teams` directory, or remove it, since an absent file reads as no teams. The store logs exactly that, with the path, every time a read fails (`crew_teams._log_unreadable`); the API answers never carry the path, because a dashboard reader is not necessarily the host's operator, and `kirocrew agent create` prints it on stderr. Two invariants the store enforces so no UI has to: a crewmate is on AT MOST ONE team (`create_team` / `update_team` detach the listed names from every other team in the same write; a foreign document listing a name twice reads as the FIRST team, `_parse_teams`), and members are bounded on WRITE exactly as on read — a member past `MEMBER_NAME_MAX_CHARS` or one UTF-8 cannot encode is refused as `invalid_members` BEFORE the registry lookup (`test_a_member_the_reader_would_refuse_is_never_written`), and the handler's registry view applies the roster's own filter (`members.is_dispatchable_member_name`, via `handlers.members._member_name_is_addressable`) so a crew is teamable exactly when the roster lists it — a free-form display name such as `dr. eggbot` included — and `MEMBER_NAME_MAX_CHARS` is the display-name cap (`validation.MAX_SHORT_STRING`, 500), with `TEAMS_FILE_MAX_BYTES` sized above the widest document those caps allow — and names are validated against the registered crews at write time (`unknown_member`), never against slugs — slugification is lossy and the roster is keyed by exact name. Ids are 12 random hex chars (`_new_team_id`), path- and query-safe; the routes refuse any other spelling with 400 `invalid_team_id` before touching the file. Names are stripped, capped at `TEAM_NAME_MAX_CHARS` (refused, never truncated), and refuse lone surrogates plus Unicode category `Cc` / `Zl` / `Zp` — control characters and line separators (a roster header is not a place for a terminal-control payload); format characters (a ZWJ emoji sequence) and the no-break space are legitimate in a pasted name and pass. `drop_member` is the crew-DELETE path's hook (`api_kirocrew_agent_delete`, best-effort off-loop): a team must not keep counting a crewmate with no roster row; a stale name is otherwise tolerated by every reader, which is why BOTH an unreadable document and a failed rewrite (`OSError`) are logged and swallowed there — the crew's config write has already committed, and neither may turn a completed delete into a 500. The document is bounded on WRITE as well as read, and the read itself is bounded: `read_teams` reads at most `TEAMS_FILE_MAX_BYTES + 1` bytes (`atomic_write.read_bytes_with_retry(max_bytes=…)`) and refuses a longer document, so a restored file far past the cap is never allocated whole on the way to its refusal (`test_an_oversized_document_is_refused_without_being_read_whole`). `TEAMS_FILE_MAX_BYTES` is sized above `max_document_bytes()` (the largest document every cap admits, pinned by `test_a_valid_write_can_never_outgrow_the_read_cap`), and a save that would exceed it is refused with 400 `teams_too_large` before anything lands, so a valid sequence of writes can never leave the store `teams_unreadable`. Two removal paths never reach that route's hook — `kirocrew agent delete` runs in another process, and the package sync prunes agents whose package is gone — so both call `drop_member` with the SAME best-effort contract (the CLI after its registry write, never refusing a delete over the grouping store — `test_delete_drops_the_crew_from_its_team_best_effort`; the sync prune ONLY for the names its locked mutate actually deleted, a snapshot candidate edited concurrently survives and keeps its team) — AND `GET /api/teams` reconciles the document against the live registry on every read (`crew_teams.prune_unknown`): an API answer never names a crewmate the registry lacks, whatever path removed it, while the document itself is left as written and re-validated by the next membership write. The one harm a stale entry could still do — a crew deleted and later RECREATED under the same name silently rejoining its old team, because `prune_unknown` hides a gone name but not a re-known one — is closed at the only moment it can materialize, the CREATE: every create path (`api_kirocrew_agents_create`, `kirocrew agent create`, the package sync for each name it is about to add) purges it from any team it was left on with `crew_teams.release_for_create` — NOT as a caller's option but inside `persist_member_config` itself for every `create=True` publication (the dashboard, the CLI, an app's `ensure_team`; the package sync, which registers through its own locked mutation, calls it from there), INSIDE the registry's cross-process locked mutation, after that mutation has found the name free and immediately before it registers it. Inside the lock, not before it: a purge outside the lock races a same-name create-and-team in another process and would erase THAT crew's fresh membership (`test_every_create_purges_the_name_inside_the_locked_mutation`). Symmetrically every removal path runs `drop_member` through `update_config_locked(after_write=…)` — AFTER the registry write has committed and still INSIDE its lock (the dashboard delete, the CLI delete, the sync prune): after the commit, so a registry write that fails leaves the membership as it was (the crew stays, on its team), inside the lock, so a same-name create cannot land between the delete and the drop (`test_after_write_runs_only_once_the_registry_write_committed`). Unlike `drop_member` this is NOT best-effort — registering the name while its stale membership cannot be purged is exactly what would expose it — so `TeamsUnreadable` / `OSError` refuse the create: 409 `teams_unavailable` on the route, exit 1 `cannot create agent` from the CLI, and the sync simply leaves that name out of THIS run (`deferred_names`) — out of its `synced` answer and its audit record too, a deferral is not a registration — and picks it up next time (`test_release_name_purges_a_recreated_crews_stale_membership`, `test_release_name_propagates_a_failure_so_the_create_is_refused`, `test_create_releases_the_name_from_a_stale_team_first`, `test_create_is_refused_while_a_stale_membership_cannot_be_purged`). An ABSENT document — no team was ever made — answers False and writes nothing (`test_release_name_without_a_store_writes_no_document`), but absence is decided INSIDE the document lock, not before it: a restore or import installing a document in the gap between a pre-lock stat and the registration would let the name inherit that document's membership, and every such installer holds this same lock (`test_release_name_decides_absence_under_the_lock`); absence is decided by `stat` raising `FileNotFoundError`, never by `Path.exists`, which folds every `OSError` into False and would let a directory the process cannot stat into read as "no teams" (`test_release_name_does_not_read_an_unstatable_store_as_absent`). Routes: `GET /api/teams` (`{teams}`), `POST /api/teams {name, members}` → 201 `{team}`, `PUT /api/teams/{id} {name?, members?, add?, remove?}` → `{team}` (omitted fields unchanged; all omitted is 400 `nothing_to_update`; `members` REPLACES the list while `add` / `remove` are deltas applied to the list as it stands inside the document lock, so an editor holding a stale copy changes only the crewmates it touched — `_validate_names` bounds a removal without a registry check, since a deleted crew's stale entry is what a caller may want gone; the two shapes are exclusive, `invalid_members`; `test_membership_deltas_never_write_a_stale_snapshot_back`), `DELETE /api/teams/{id}` → `{ok}`; unknown id is 404 `team_not_found`, malformed bodies are coded 400s (`invalid_json`, `invalid_team_name`, `team_name_too_long`, `invalid_members`, `unknown_member`, `too_many_teams`, `too_many_members`, `teams_too_large`), a failed persist is 500 `teams_write_failed`. The create and update routes run INSIDE the crew registry's in-process config lock (`agents._get_config_lock`, resolved late), the same lock the dashboard's crew-delete route holds from removing the crew through `drop_member` and the crew-create route from `release_name` through registering the name; and the registry read itself happens INSIDE the store's document lock — `known` is a callable (`crew_teams.KnownCrews`, `handlers/teams._registered_crews`) the store evaluates after acquiring the lock, so the snapshot a write validates against is the freshest available (`test_registry_is_read_inside_the_document_lock`). Lock order everywhere is config lock (the in-process asyncio lock and the cross-process sidecar lock), then document lock; `KiroCrewConfig.load` takes no lock, so the `known` read inside the document lock cannot invert it. So the in-process delete cannot interleave between "the crew exists" and "the team is written"; `kirocrew agent delete` in another process still can, and the team then names a gone crewmate — hidden by `prune_unknown`, purged by `release_name` if the name ever comes back (`test_writers_hold_a_cross_process_file_lock` — a real second process holds the file lock, on every platform). Same posture as the members routes: app tokens are denied with 404 on every route (`_deny_app_caller`), and the three writes are OWNER actions (`_require_owner_write` → `require_owner_dashboard_request`, gated BEFORE body validation so a non-owner's answer stays a uniform 401/403 that leaks nothing about what would have validated; the shared gate audits only the denial, so the handler records the owner's ALLOW as a SEL `log_api_access(outcome="allowed")` event, enqueued and non-fatal — `test_an_owner_write_records_the_allow_in_sel`). Ids are matched with `fullmatch` on read and in the route, since `$` alone admits a trailing newline. The document rides every backup path: `crew-teams` is a snapshot component of its own (`snapshot.COMPONENTS`, a whole tree, so replace swaps it and merge copies it in where absent; the tree's `.lock` is host-local and never rides, `snapshot._HOST_LOCAL_PATHS`), the dashboard export zip writes the `teams.json` document, under its `crew-teams` directory, beside the core files and the import installs it where the destination has none, and both paths — snapshot restore in either mode and the dashboard import in either mode — validate the document they would install with the store's OWN reader (`crew_teams.read_document`, the same bounded read and `_parse_teams` the live `read_teams` runs, via `snapshot._TREE_DOCUMENT_VALIDATORS`) before anything moves, so a restore refuses exactly what the live read would refuse — a directory or a link standing at the document's name is refused outright, in every mode — and never installs a file that fails every team route and every crew create. The restore WRITES the way every other writer does: `crew_teams.install_document` / `remove_document` take the store's lock (`document_lock(directory)`, the restored home's own `crew-teams/.lock`) and move ONLY the document — replace, merge and the failed-restore rollback never remove or swap the directory or its lock file (`snapshot._LOCKED_DOCUMENT_TREES`); a replace from a bundle that carries no document — a tree without it, or no `crew-teams/` tree at all, which is what a home that never made a team exports — REMOVES the live one, so the destination's own teams cannot outlive a reported full replace (`test_replace_from_a_bundle_with_no_team_tree_removes_the_live_document`), because a writer already inside the lock would otherwise hold an orphaned file and commit its stale document over the restored one; a removal syncs the directory after the unlink, under the same lock, so a power loss cannot resurrect the removed document (`remove_document`, as `install_document` and `write_teams` already do); the replace-mode rollback copy of the document is taken by the installer INSIDE that same lock hold (`save_existing`), not in the restore's earlier backup phase, and is staged beside its name and published by rename only once the copy completed (a copy that fails midway leaves nothing where recovery reads), so a team write committed before the install can never be lost from both the live store and the rollback; a failed restore's rollback puts that copy back VERBATIM under the lock (`crew_teams.restore_document`) — recovery restores the operator's state, it does not validate it — STREAMED into a temporary file beside the document and published by rename, never read whole (the saved copy is whatever size the live store held, which the reader's cap does not bound), and raises only `OSError`, which the rollback loop names per target instead of aborting on. Only a MISSING path counts as "no document" to these writers: a directory or link where the data home's `teams.json` belongs (inside `crew-teams/`) raises `OSError` from `install_document` / `remove_document` (`_has_document`), so a document-less replace fails and rolls back instead of reporting success with the entry still in place and every team route still answering `teams_unreadable`. `_parse_teams` reads a document nested past the interpreter's stack (`RecursionError`) as `TeamsUnreadable`, the same coded 500 as any other unparseable document (`TestBackupCoverage`). - `handlers/source_providers.py` + `source_providers/` — the handler keeps the `/api/source/*` HTTP handlers, their SEL API audit and error mapping, and the dashboard owner gate (`is_owner_dashboard_request`, `owner_view_for_request`, `stale_owner_session_response`). Every other name it defined, and each import callers reach through it, still resolves through it; apart from what the handler binds itself (its logger, its own module imports such as `asyncio`, `web`, `json` and `time`, and the three errors its handlers catch), each is read from and written to the one owner module that holds it (`_OWNED_NAMES`/`_EXPORTS`, per-access resolution through `sys.modules` plus a forwarding `__setattr__`, so an import or a patch through the handler reaches the running code; a delete is forwarded the same way, so `monkeypatch` and `mock.patch` without `create=True` restore exactly, nested in either order, while `mock.patch(create=True)` of a forwarded name, which would leave the owner without it, is refused by a guard test; the forwarding `__getattr__` is hidden from type checkers, which read the handler's typed imports instead), in import order: `contract` (refs, payload shapes, `SourceProviderPlugin`, errors), `sanitize` (the redaction chokepoint and payload cap), `hosts` (GitLab/Jira allowlists and the chip switch), `plugins` (registry, chip labels, path markers, search seam), `links` (URL validation), `runner` (the bounded, audited `gh`/`glab` spawn), `projection` (the payload, chip and merge-state vocabulary), `github`/`gitlab` (provider reads), `adf` (Jira ADF to markdown), `jira` (Jira reads), `chip_status` (chip cache, deltas, visibility gate), `cache` (coalesced full, checks, issue and contributor reads, admission, revalidation, invalidation), `chip_refresh` (background chip reads), and `mutations`/`review` (owner writes). An owner imports only owners earlier in that order and reaches a sibling as a module, copying nothing but types, so a patch reaches every caller. Together they validate GitHub PR and GitLab MR URLs, delegate authentication to `gh`/`glab`, normalize metadata/files/comments/reviews/checks, recursively redact provider strings, enforce subprocess and aggregate-payload limits, and maintain separate bounded caches for full source payloads and lightweight sidebar check state. Both caches age an entry by the lifecycle it describes: an open PR/MR by the short TTL (`_CACHE_TTL_SECS` for the payload, `_CHECK_TTL_SECS` for the chip), a **merged** one by `_TERMINAL_TTL_SECS` (six hours) and a **closed** one by `_CLOSED_TTL_SECS` (one hour — it can be reopened and keeps accruing discussion), because re-reading a finished pull request on the open-PR cadence for as long as its chip stays in a sidebar was one provider subprocess per finished PR per minute, forever. The payload TTL is decided from the payload itself through the same `_project_state` the chip projection uses (`_full_payload_ttl`), so the two caches cannot disagree about whether a URL is finished; the explicit refresh button and mutation invalidation still bypass both, and the turn-boundary force (`request_check_refresh_now`) still re-reads a closed chip (an agent can reopen one) but never a merged one (`_chip_refresh_due`). Those lifecycle clocks govern the chip cache and the full payloads that have no cheaper read (GitLab, registered plugins). A github.com full payload is instead REVALIDATED past the open TTL whatever its lifecycle: `_revalidate_pull_request` first issues small conditional REST GETs through `gh api -i -H If-None-Match` — `issues/{n}` (its ETag follows the pull request's `updated_at`: title/body/labels/lifecycle including a reopen, a push, reviews, comments) and, for an OPEN pull request only, `commits/{head_sha}/check-runs` plus `commits/{head_sha}/status` (CI hangs off the commit and never moves `updated_at`; check runs and legacy commit statuses are separate resources and the rollup renders both) — and only when any probe answers something other than `304` does the fanout run; all-304 re-stamps the cached entry instead. So post-merge comments and a reopen reach the panel within one open TTL for one rate-limit-free request. It is strictly 304-only: the first probe of a URL has no validator, answers 200, and only LEARNS the ETags (`_REVALIDATORS`, bounded, the two commit-level validators scoped to the head sha so a push cannot reuse the old commit's), a failed probe is "unknown", and nothing is ever judged unchanged by comparing bodies. Validators returned by an all-304 are committed at once; those returned by a 200 describe a payload the cache does not hold yet and are committed only after the full read that follows has succeeded, so a failed fanout can never pair the old payload with new validators (which would make every later probe re-stamp it as current). Re-stamping is also capped: each validator set remembers when its payload was last read in full (`read_at`), and past `_REVALIDATED_MAX_AGE_SECS` (the merged TTL, 6 h) one full read runs without probing and the validators are dropped so the next cycle learns a fresh set — the probes rest on GitHub moving the issue ETag for every rendered field, which the API does not promise, so a coverage gap degrades to bounded staleness instead of unbounded. `pulls/{n}` is deliberately not the probe (its ETag churns on the embedded repository counters), GitHub's GraphQL API — what `gh pr view` speaks — has no conditional requests, an authenticated 304 costs nothing on the primary rate limit, and `gh` exits 1 on a 304 so `_parse_conditional_get` reads the status line rather than the exit code. The merge pair moves no validator and stays with the chip protocol; an explicit refresh, a mutation invalidation, GitLab and registered plugins never probe. Full source payloads carry a normalized merge-state pair shared by both providers: `mergeable` is `mergeable|conflicting|unknown` (`''` when the provider omitted it) and `mergeStateStatus` uses GitHub's lowercased merge-state vocabulary extended with a GitLab-specific value (`clean|dirty|behind|blocked|unstable|draft|need_rebase|unknown|''`). GitHub maps `mergeable`/`mergeStateStatus` from `gh pr view` directly; GitLab derives `mergeable` from `detailed_merge_status` (falling back to legacy `merge_status`) and maps `detailed_merge_status` onto the shared vocabulary (`conflict`→`dirty`, `need_rebase`→`need_rebase` (kept distinct: on fast-forward-only projects a merge commit cannot unblock the MR, so it must not be conflated with `behind`), approval/CI/discussion/policy/security gates (including `status_checks_must_pass`, `policies_denied`, `security_policy_violations`, `merge_request_blocked`)→`blocked`, `ci_still_running`→`unstable`, unrecognized non-empty values→`unknown`). Both providers compute mergeability **lazily**: the first read of a pull request they have not evaluated recently answers "not known yet" (GitHub `UNKNOWN`, GitLab `checking`/`unchecked`) *and* is what starts the computation, so a single read reports a conflicting pull request as having no merge blocker at all. Each full fetch therefore re-reads the merge fields alone — `gh pr view --json mergeable,mergeStateStatus` / the GitLab merge-request endpoint, which is the only place `detailed_merge_status` is exposed — at most `_MERGE_STATE_REREADS` (2) times spaced `_MERGE_STATE_REREAD_DELAY_SECS` (0.8s) apart, dispatched inside the existing secondary fanout so the wait overlaps calls the request was already making. A value that is empty rather than unknown is never re-read (the provider omitted the field; re-reading cannot settle it), and an unsettled, failed, or malformed re-read degrades to `unknown` rather than raising — an unknown merge state costs one banner, never the panel. Settledness is judged on the **pair**, not on `mergeable` alone: GitLab settles `need_rebase` and its branch-protection gates in the detail field while `mergeable` stays `unknown`, so keying on `mergeable` would re-read a state the provider had already answered and then discard it. Provider CLIs run through `sandboxed_spawn_argv(..., mode="standard")` using absolute paths only: an explicit absolute `KIROCREW_GH_BIN` / `KIROCREW_GLAB_BIN` override, else the fixed well-known install dirs, else the ambient `PATH` (`provider_executable_candidates()`). The trust policy itself (candidate dirs, validation, strict mode) is single-sourced in `kiro_crew.github_runner` and re-exported by `source_providers/runner.py` under the historical names the handler still exposes, so this panel, Issue Radar, and Code Review Sage can never drift apart. The default policy is *if the CLI works in the user's terminal, it works here*: the gateway user's OWN install is accepted — Homebrew/Linuxbrew/asdf symlink layouts included — and only provenance the user did not choose is refused, namely a binary (or ancestor) owned by another unprivileged account, anything world-writable (a world-writable *directory* is tolerated only when sticky — `/tmp`-style 1777, where only the owner may replace an entry, so the ownership check still decides), and anything inside the agent-writable project checkout or workspace root (`github_runner.agent_writable_roots()`, the one substitution vector the model controls; the same rule codex applies to its own sandbox helper). A gateway running as **root** is refused outright in BOTH modes, because every process it spawns — the agent's own shell included — would be root too, which makes the ownership and agent-tree checks vacuous. Requiring a root-owned copy instead made every stock `brew install gh` fail and pushed users into a `sudo cp` ritual for a CLI they had already installed and authenticated, so provenance was traded for containment: the provider child still gets only a minimal provider-scoped env, and every spawn is SEL-audited. `KIROCREW_PROVIDER_BIN_STRICT=1` restores the historical hardened rule for shared or multi-tenant hosts — canonical, symlink-free, root-owned and non-writable through every ancestor, `PATH` never consulted — and its setup error then names the privileged `/usr/local/libexec/kirocrew/` (or `/usr/libexec/kirocrew/`) copy to provision plus the override to point at it. The child receives a fixed system `PATH`, never the gateway/workspace `PATH`; `resource_limit_preexec()`, a minimal provider-specific environment, and host pinning remain enforced, and unrelated gateway/AWS/Slack credentials are not inherited. `github.com` and `gitlab.com` are always accepted; a self-managed GitLab instance is accepted only when the URL's exact `host[:port]` is a member of the operator's `dashboard.gitlab_hosts` allowlist (deny-by-default, config-only, never browser-supplied, no suffix or wildcard matching, `www.` not stripped, and a portless entry does not authorize an arbitrary port; an explicit `:443` is treated as absent on both sides so it matches the browser URL API, which drops the default HTTPS port). The allowlist is served from a process-cached snapshot refreshed at most once per 30s by `ensure_gitlab_hosts_loaded()`, which every async entry point awaits before validating a URL: the config read runs in a worker thread, never on the event loop, and the synchronous accessor that URL parsing and slot serialization use only reads the cached snapshot (empty before the first refresh, which fails closed). Refreshes are serialized behind a lock with a post-acquire freshness recheck, so a loader holding the pre-revocation config cannot install its snapshot after a newer one and re-admit a just-removed host for another interval. Each content change bumps `gitlab_hosts_generation()`, which `_ChatSlot._pr_source_links()` folds into its per-slot cache key alongside the message revision -- the synchronous scan can run before the first load, and without the generation that cold-snapshot rejection would stay memoized until the next message mutation, leaving a self-managed chip missing (or a revoked one present). A `glab` call to a self-managed host drops `GITLAB_TOKEN` from the child environment: that variable carries no host binding, so forwarding it would hand a gitlab.com credential to the self-managed server; such hosts authenticate from their per-host entry in glab's own config, still reachable via `GLAB_CONFIG_DIR`. gitlab.com keeps the ambient token. `host` is a REQUIRED argument for every `glab` invocation rather than a defaulted one: an omitted host raises instead of silently resolving to gitlab.com, so no future call site (including a mutation endpoint) can read or write an allowlisted self-managed MR on the public instance at the same project/IID. Because slot source-link extraction is synchronous and cannot load the snapshot itself, the owner WebSocket awaits `ensure_gitlab_hosts_loaded()` before its first `serialize_slots()` and again once per refresh round, pushing a slots update whenever the generation changes -- otherwise a newly authorized (or revoked) self-managed chip would wait for an unrelated message mutation. `GET /api/chat/slots` performs the same warm-up so a cold direct fetch is not missing those links either. A full payload's `url`/`number` identity always comes from the validated `SourceRef`, never from the provider's echoed `web_url`/`iid`/`url`: the browser submits that url back for refresh and thread resolution, so a hostile or compromised instance echoing a different merge request could otherwise steer an owner-authenticated call at an unrelated one. Each `glab` invocation pins `GITLAB_HOST` to the host `parse_source_url` authorized for that URL and re-checks it against the allowlist at spawn time, so a configured self-managed default in `glab` config cannot redirect bare API paths and a caller that skipped URL validation is denied rather than reaching an unauthorized instance. The dashboard-config GET exposes `gitlab_hosts` read-only (absent from the PUT allowlist) purely so the client knows which pasted links to surface as source tabs. Provider stdout is section-bounded at 1 MiB for metadata/checks, 2 MiB for discussions, and 4 MiB for diffs/changes; normalized full payloads are capped at 8 MiB. A global four-command semaphore covers full-source, direct-check, resolve, and sidebar work. Unique direct full/check tasks share a 16-task ceiling and a conservative 128 MiB retained-byte budget: full tasks reserve 64 MiB and checks tasks reserve 8 MiB until the underlying task terminates. Same-URL callers coalesce before admission, detached stale full fetches retain their leases, and a stale pre-mutation fetch plus its required fresh successor can coexist at the exact aggregate ceiling. Successful thread resolution advances that URL's cache generation and detaches older shared fetches so pre-mutation results cannot refill the cache or satisfy the post-resolution refresh. Secondary metadata endpoints degrade independently so core source details remain available, but every failed files, commits, discussion/thread, pipeline, job, or GitHub check-rollup request is named in `partialSections` before its data falls back to an empty section. GitHub's `statusCheckRollup` is never bundled into another `gh pr view` field set: `gh` resolves a `--json` field set atomically, so a fine-grained token without Checks read access would lose the fields it WAS authorized for — the full payload, the sidebar chip, and the checks poll all read the rollup through one isolated query (`_github_rollup_read`, which also carries `headRefOid`), and a rollup read that fails or that straddled a push (its head sha differing from the core read's) marks `checks` partial with an empty list instead of failing the read or rendering another commit's checks; provider page limits and overflow evidence use the same deduplicated markers. Native Windows is not refused by a platform check of its own: it has no OS-level provider sandbox backend, so it reaches the same no-backend policy a backend-less Linux host does — `sandboxed_spawn_argv` fail-closes and the read is refused unless the operator set `agent.sandbox_allow_unsandboxed_exec`, whose refusal text names that opt-in. With the opt-in set, provider commands (reads and the PR/MR mutations alike) do spawn on Windows, under the same non-sandbox bounds every host keeps: the `{gh, glab}` allowlist, the validated absolute executable, the minimal provider env with a fixed system `PATH`, host pinning, the output caps, and the SEL audit. Every provider execution emits credential-free SEL `invoked` plus `completed`/`failed` lifecycle events; policy and provenance rejections emit `denied`. The critical `invoked` append is shielded and awaited on a worker thread before spawn, preserving audit-or-deny ordering without blocking the gateway event loop; cancellation waits for that worker, pairs a landed `invoked` event with `failed/request_cancelled`, and never spawns, while other terminal events are best effort. Events contain only the logical provider and coarse reason, never argv, URL, repository, output, environment, credentials, thread id, or exception text. Sidebar refreshes run outside slot serialization with inflight deduplication, a 16-task pending ceiling, one-TTL overflow backoff, and a 512-entry status cache. Scheduling requires an exact dashboard-owner request. Cached check state is otherwise only repopulated at WebSocket-connect and slots-GET time, so each owner WebSocket connection additionally runs a background refresh driver that re-schedules refreshes for its currently-rendered sidebar chip URLs (`DashboardState.source_link_urls()` — the first `_SERIALIZED_SOURCE_LINKS_PER_SLOT` links of every slot) once per cache TTL (`CHECK_STATUS_TTL_SECS`, sleeping exactly one TTL so each round finds the previous round's entries just expired — one provider fetch per URL per TTL, coalesced across tabs by the inflight dedup; a merged or closed chip is skipped by the same `_chip_refresh_due` gate until its terminal TTL lapses); without it a PR merged or a CI run completed after page load would keep its stale connect-time chip until a full reload. The driver is owner-gated (never created for non-owner connections), cancelled with the connection, and advances a per-round starting offset by the pending admission cap (`CHECK_STATUS_PENDING_MAX`) each round so that when the number of stale chips exceeds the cap the admitted window rotates across every chip within `ceil(len/cap)` rounds instead of the same slot-order prefix winning every TTL and starving newer slots' chips indefinitely. Each round's work is individually guarded so a transient failure is logged and the loop continues rather than the driver dying silently and reverting to frozen chips. Generic slot serialization and broadcasts omit cached `state`/`ci`; owner HTTP and WebSocket snapshots opt in, and changed statuses trigger a debounced generic update followed by an owner-WebSocket-only overlay. `_ChatSlot` retains only the first 64 unique durable source links and stops scanning at the cap; `to_dict()` exposes up to three sidebar chips as `{url, provider, number}` to all authenticated callers and adds the whole cached chip-status entry — `{state?, ci?, mergeable?, mergeStateStatus?}` — only at an owner-authorized serialization boundary. `state` is `open|draft|merged|closed` and `ci` is `running|passed|failed` when known; the merge pair uses the shared merge-state vocabulary above and is present only once settled. Both providers derive `state` with terminal states outranking draft (a GitLab MR keeps `draft` set after being closed as a draft, so draft is reported only while the MR is `opened`), and a provider state outside the known set (e.g. GitLab `locked`) yields no `state` rather than a mislabeled `open`. `ci` rolls a GitLab pipeline status up the same way GitHub's check conclusions roll up: any failure fails, anything still in flight runs, and a terminal non-failure -- including a wholly `skipped` pipeline -- passes, so a skipped pipeline settles instead of spinning. Pipeline-level `manual` is the one deliberate split from the job-level bucket: a pipeline in `manual` is blocked awaiting a required manual job, so it reports `running` rather than green, while a single `manual` job among finished ones still buckets as skipped -- unless it carries `allow_failure: false`, which makes it a required gate and therefore pending. GitLab's chip status reads `head_pipeline` from the merge-request payload and falls back to the MR pipelines list only when that field is absent. GitHub's chip refresh pairs its core-field read (`state,isDraft,mergeable,mergeStateStatus,headRefOid`) with the same isolated rollup read, concurrently; only the core read is load-bearing — a rollup that fails or describes a different head degrades to an internal ci-unavailable marker that `_refresh_check_status` strips before caching, keeping a previously known `ci` glyph rather than erasing it (the same keep-known posture the full-payload write-through applies when `checks` is partial), while a successful rollup with zero checks still clears a stale glyph. Because the chip entry is spread whole, a refresh in which only the merge pair settles also counts as a status change and triggers the same debounced generic update plus owner overlay. `source_providers/plugins.py` also owns the TRANSCRIPT-SEARCH seam for provider ids: `SourceProviderPlugin` carries an optional `search_ref(token) -> (canonical, alts) | None` hook (getattr-discovered, like `path_markers()`), `source_search_ref()` fans out across the registered plugins and asks each registered plugin until one answers and hands that answer through UNVALIDATED, without reading `alts` itself (the shape checks belong to the single normalizer, whose guard also wraps this collector because it IS the resolver core calls, while a raising hook is caught per provider in `source_search_ref()`); the FIRST plugin to ANSWER wins, for every token shape, and the spellings it contributes are bounded once in core by `_MAX_SEARCH_REF_SPELLINGS` rather than by a collector-side ceiling that would drift from it. There is deliberately no cross-plugin merge: one would exist to serve two registrants holding a real item at the same number, and this repo registers no provider at all, so it would be surface no code path can reach — additive if a second registrant ever appears. `register_source_provider()` additionally publishes that collector downward into `history_search.register_search_ref_resolver` — dashboard → core, at registration rather than from a route handler, so the non-HTTP callers of `parse_search_query` answer identically. Casefolding, dedup and the per-provider spelling cap belong to `history_search._provider_search_ref`, the single normalizer; `reset_source_providers_for_tests()` unpublishes the resolver alongside the plugin registry. - `server.py` — app factory, route registration, startup, SPA fallback middleware for React Router, `/api/ws` WebSocket route, token auth middleware, loopback-only binding (`127.0.0.1`). Fires background MCP probe at startup via `asyncio.create_task()`. Honors `agent.yolo=true` config at startup via `_apply_startup_yolo()` — attempts SEL audit first and only activates dashboard YOLO (6h TTL) if the audit succeeds (fail-closed). diff --git a/src/kiro_crew/cli.py b/src/kiro_crew/cli.py index ed188e605071..1ba0161651eb 100644 --- a/src/kiro_crew/cli.py +++ b/src/kiro_crew/cli.py @@ -2916,7 +2916,12 @@ def _tunnel_opts(p: "argparse.ArgumentParser") -> None: agent_sub = agent_parser.add_subparsers(dest="agent_action") agent_sub.add_parser("list", help="List Kiro Crew agents") agent_create = agent_sub.add_parser("create", help="Create a Kiro Crew agent") - agent_create.add_argument("--name", required=True, help="Agent name") + agent_create.add_argument( + "--name", + required=True, + help="Agent id, or any name: shown as typed, stored under a URL-safe id", + ) + agent_create.add_argument("--display-name", default="", help="Label the dashboard shows") agent_create.add_argument("--kiro-agent", default="kirocrew", help="Kiro agent name") agent_create.add_argument("--workspace", default="default", help="Workspace name") agent_create.add_argument( diff --git a/src/kiro_crew/cli_commands.py b/src/kiro_crew/cli_commands.py index fa21068b4126..5ccd5d18505e 100644 --- a/src/kiro_crew/cli_commands.py +++ b/src/kiro_crew/cli_commands.py @@ -118,7 +118,7 @@ _vet_shell_command, ) from kiro_crew.member_memory_auth import require_member_memory_creation -from kiro_crew.members import MemberNameError, validate_member_name +from kiro_crew.members import MemberNameError, key_new_crew, validate_member_name from kiro_crew.memory import MemoryStore from kiro_crew.memory_stores import ( DEFAULT_MEMORY_STORE, @@ -1441,9 +1441,14 @@ def _handle_agent(args: argparse.Namespace) -> None: except MemberNameError as exc: print(f"Error: invalid Crew Member name ({exc})", file=sys.stderr) sys.exit(1) - if args.name in cfg.agents: - print(f"Error: agent '{args.name}' already exists", file=sys.stderr) + # Same keying as POST /api/agents. + keyed = key_new_crew( + args.name, (getattr(args, "display_name", None) or "").strip(), cfg.agents + ) + if keyed.taken: + print(f"Error: agent '{keyed.taken}' already exists", file=sys.stderr) sys.exit(1) + args.name, display_name = keyed.key, keyed.display_name if not TEMPLATE_NAME_RE.fullmatch(args.kiro_agent): print("Error: invalid kiro agent name", file=sys.stderr) sys.exit(1) @@ -1463,6 +1468,7 @@ def _handle_agent(args: argparse.Namespace) -> None: kiro_agent=args.kiro_agent, workspace=args.workspace, memory_store=memory_store, + display_name=display_name, ) previous_store = cfg.agents[args.name].memory_store previous_member_id = cfg.agents[args.name].member_id @@ -1493,7 +1499,10 @@ def _handle_agent(args: argparse.Namespace) -> None: raise print(f"Error: {exc}", file=sys.stderr) sys.exit(1) - print(f"Created agent: {args.name}") + if display_name: + print(f"Created agent: {args.name} (display name: {display_name})") + else: + print(f"Created agent: {args.name}") elif action == "update": if args.name not in cfg.agents: diff --git a/src/kiro_crew/dashboard/handlers/agents.py b/src/kiro_crew/dashboard/handlers/agents.py index 46928b4214bc..27f5387bfbfc 100644 --- a/src/kiro_crew/dashboard/handlers/agents.py +++ b/src/kiro_crew/dashboard/handlers/agents.py @@ -138,7 +138,7 @@ from kiro_crew.external_text import redact_external_text as _redact_external from kiro_crew.kiro_prerequisite import spawn_supervised_oneshot from kiro_crew.loop_lock import LoopBoundLock -from kiro_crew.members import MemberNameError, validate_member_name +from kiro_crew.members import MemberNameError, key_new_crew, validate_member_name from kiro_crew.memory_stores import ( DEFAULT_MEMORY_STORE, MemberAlreadyExists, @@ -5071,10 +5071,15 @@ async def api_kirocrew_agents_create(request: web.Request) -> web.Response: ) async with _get_config_lock(): cfg = KiroCrewConfig.load() - if name in cfg.agents: + # The config key is an id and the name the user typed is its label + # (`members.key_new_crew`, shared with `kirocrew agent create`). + keyed = key_new_crew(name, display_name, cfg.agents) + if keyed.taken: return web.json_response( - {"error": f"Agent '{name}' already exists", "code": "agent_exists"}, status=409 + {"error": f"Agent '{keyed.taken}' already exists", "code": "agent_exists"}, + status=409, ) + name, display_name = keyed.key, keyed.display_name model_reason = _model_pin_rejected( model, request, cfg.agent.provider, backend=_pin_entitlement_backend(cfg) ) diff --git a/src/kiro_crew/members.py b/src/kiro_crew/members.py index df3eedcd88e9..29c8821b497d 100644 --- a/src/kiro_crew/members.py +++ b/src/kiro_crew/members.py @@ -24,6 +24,7 @@ import os import re import stat +from collections.abc import Container, Mapping from dataclasses import dataclass from datetime import datetime, timezone from enum import Enum @@ -41,7 +42,12 @@ supports_pinned_walk, ) from kiro_crew.slugs import slug_hash_fallback -from kiro_crew.validation import MAX_SHORT_STRING, normalize_unicode, sanitize_string +from kiro_crew.validation import ( + _AGENT_NAME_RE, + MAX_SHORT_STRING, + normalize_unicode, + sanitize_string, +) logger = logging.getLogger(__name__) @@ -400,6 +406,78 @@ def validate_member_name(name: object) -> str: return name +#: Longest base a derived crew id keeps, leaving room for a ``-`` suffix +#: inside ``_AGENT_NAME_RE``'s 64-character cap. +_CREW_ID_BASE_MAX_CHARS = 56 + +#: Suffixes tried before a derived crew id falls back to the name's hash. +_CREW_ID_SUFFIX_ATTEMPTS = 99 + + +def is_crew_id(value: object) -> bool: + """Return whether *value* is shaped like a new crew's config key. + + A crew id is the identifier grammar crews carried before free-form names + (``validation._AGENT_NAME_RE``). New crews are keyed by one; a crew already + stored under a free-form name stays readable and is never renamed. + """ + return isinstance(value, str) and bool(_AGENT_NAME_RE.match(value)) + + +def crew_id_for_display_name(name: str, taken: Container[str]) -> str: + """Derive an unused crew id for a crew the user named *name*. + + The id is a slug of the name, suffixed ``-2``, ``-3``... past any id in + *taken*. A name with no slug-safe characters (CJK, emoji) derives from its + hash, so two such names never share an id. Deterministic for a given + *name* and *taken*. + """ + base = slugify(name)[:_CREW_ID_BASE_MAX_CHARS].strip("-") + if not base or base == slug_hash_fallback(name, "artifact"): + base = slug_hash_fallback(name, "crew") + for n in range(1, _CREW_ID_SUFFIX_ATTEMPTS + 1): + candidate = base if n == 1 else f"{base}-{n}" + if candidate not in taken and is_crew_id(candidate): + return candidate + return slug_hash_fallback(name, "crew") + + +@dataclass(frozen=True) +class NewCrewKey: + """How a crew being created is keyed and labelled. + + ``taken`` is the name the user would see twice when the create must be + refused (``409 agent_exists``), else ``""``. + """ + + key: str + display_name: str + taken: str + + +def key_new_crew(name: str, display_name: str, agents: Mapping[str, object]) -> NewCrewKey: + """Decide the config key and label for a crew created as *name*. + + An id-shaped *name* is the key as sent. A free-form one is kept as the + label of an id :func:`crew_id_for_display_name` derives. An explicit + *display_name* is the label either way. The create is refused when the + key is taken, or when the name the crew would show (its label, else its + key) is exactly what another crew already shows. The one decision both + create surfaces (``POST /api/agents``, ``kirocrew agent create``) share. + """ + if is_crew_id(name): + key, label = name, display_name + if key in agents: + return NewCrewKey(key, label, name) + else: + key, label = crew_id_for_display_name(name, agents), display_name or name + shown = label or key + for other_key, other in agents.items(): + if (getattr(other, "display_name", "") or other_key) == shown: + return NewCrewKey(key, label, shown) + return NewCrewKey(key, label, "") + + def is_valid_member_name(value: object) -> bool: """Return whether *value* is a valid Crew Member display name.""" try: diff --git a/test/test_cli_agent.py b/test/test_cli_agent.py index 5c53c2820914..e8ad936521ab 100644 --- a/test/test_cli_agent.py +++ b/test/test_cli_agent.py @@ -126,6 +126,44 @@ def test_create_duplicate_exits_nonzero( err = capsys.readouterr().err assert "already exists" in err + def test_create_free_form_name_keys_a_derived_id( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + cfg_path = _write_config(tmp_path, _base_config()) + + with ( + unittest.mock.patch("kiro_crew.config.loader.config_path", return_value=cfg_path), + unittest.mock.patch( + "sys.argv", + ["kirocrew", "agent", "create", "--name", "Release Writer"], + ), + ): + main() + + assert "Created agent: release-writer (display name: Release Writer)" in ( + capsys.readouterr().out + ) + saved = json.loads(cfg_path.read_text(encoding="utf-8")) + assert "Release Writer" not in saved["agents"] + assert saved["agents"]["release-writer"]["display_name"] == "Release Writer" + + def test_create_display_name_flag_labels_an_id( + self, tmp_path: Path, capsys: pytest.CaptureFixture[str] + ) -> None: + cfg_path = _write_config(tmp_path, _base_config()) + + with ( + unittest.mock.patch("kiro_crew.config.loader.config_path", return_value=cfg_path), + unittest.mock.patch( + "sys.argv", + ["kirocrew", "agent", "create", "--name", "scribe", "--display-name", "Scribe"], + ), + ): + main() + + saved = json.loads(cfg_path.read_text(encoding="utf-8")) + assert saved["agents"]["scribe"]["display_name"] == "Scribe" + def test_create_rejects_free_form_template_identifier( self, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: diff --git a/test/test_config_api.py b/test/test_config_api.py index 0da547083153..3a92f76bf8e2 100644 --- a/test/test_config_api.py +++ b/test/test_config_api.py @@ -21,7 +21,7 @@ SCHEMA_REGISTRY, config_entry_to_dict, ) -from kiro_crew.members import is_valid_member_name +from kiro_crew.members import is_crew_id, is_valid_member_name @pytest.fixture(autouse=True) @@ -322,21 +322,29 @@ async def test_crud_create_round_trip( assert private_store != "default" # The immutable identity a client binds to (never the name). assert create_data["member_id"] + # An id-shaped name is the key as sent; a free-form one is + # the label of a derived id. + key = create_data["name"] + if is_crew_id(name): + assert key == name + else: + assert is_crew_id(key) # List and verify resp = await client.get("/api/agents") assert resp.status == 200 data = await resp.json() agents_by_name = {a["name"]: a for a in data["agents"]} - assert name in agents_by_name - created = agents_by_name[name] + assert key in agents_by_name + created = agents_by_name[key] + assert created["display_name"] == ("" if is_crew_id(name) else name) assert created["kiro_agent"] == kiro_agent assert created["workspace"] == workspace assert created["memory_store"] == private_store persisted = json.loads(tmp.read_text()) - assert persisted["agents"][name]["memory_store"] == private_store + assert persisted["agents"][key]["memory_store"] == private_store store = persisted["memory_stores"][private_store] - assert store["owner_member"] == name + assert store["owner_member"] == key assert store["memory_version"] == 2 finally: tmp.unlink(missing_ok=True) diff --git a/test/test_crew_display_name.py b/test/test_crew_display_name.py index 273cacde839c..fbffb3785b67 100644 --- a/test/test_crew_display_name.py +++ b/test/test_crew_display_name.py @@ -198,6 +198,135 @@ async def test_create_refuses_non_string(self): # Refused before any state was touched: nothing persisted. assert cfg.saved == [] + @pytest.mark.asyncio + async def test_free_form_name_becomes_the_label_of_a_derived_id(self): + """An older client sends only `name`. A free-form one keys the crew by + a derived id and keeps the typed text as the label, and the answer + names the id so the client can address what it made.""" + cfg = self._fake_config() + status, data = await self._post({"name": "Release Writer", "kiro_agent": "kirocrew"}, cfg) + assert status == 200 + assert data["name"] == "release-writer" + agents = cfg.written["doc"]["agents"] + assert list(agents) == ["release-writer"] + assert agents["release-writer"]["display_name"] == "Release Writer" + + @pytest.mark.asyncio + async def test_explicit_label_wins_over_the_free_form_name(self): + cfg = self._fake_config() + status, data = await self._post( + {"name": "Release Writer", "kiro_agent": "kirocrew", "display_name": "Scribe"}, cfg + ) + assert status == 200 + assert data["name"] == "release-writer" + assert cfg.written["doc"]["agents"]["release-writer"]["display_name"] == "Scribe" + + @pytest.mark.asyncio + async def test_id_shaped_name_is_the_key_unchanged(self): + cfg = self._fake_config() + status, data = await self._post({"name": "Scribe_2", "kiro_agent": "kirocrew"}, cfg) + assert status == 200 + assert data["name"] == "Scribe_2" + assert cfg.written["doc"]["agents"]["Scribe_2"]["display_name"] == "" + + @pytest.mark.asyncio + async def test_derived_id_skips_a_taken_id(self): + cfg = self._fake_config() + cfg.agents["release-writer"] = KiroCrewAgentConfig(kiro_agent="kirocrew") + status, data = await self._post({"name": "Release Writer", "kiro_agent": "kirocrew"}, cfg) + assert status == 200 + assert data["name"] == "release-writer-2" + + @pytest.mark.asyncio + @pytest.mark.parametrize( + "body", + [ + # An explicit label on an id-shaped name is what the crew shows. + {"name": "scribe2", "display_name": "Release Writer"}, + # A free-form name with an explicit label shows the label, not the name. + {"name": "Launch Notes", "display_name": "Release Writer"}, + ], + ) + async def test_an_explicit_label_another_crew_shows_is_taken(self, body): + cfg = self._fake_config() + cfg.agents["legacy"] = KiroCrewAgentConfig( + kiro_agent="kirocrew", display_name="Release Writer" + ) + status, data = await self._post({**body, "kiro_agent": "kirocrew"}, cfg) + assert status == 409 + assert data["code"] == "agent_exists" + assert cfg.saved == [] + + @pytest.mark.asyncio + async def test_a_free_form_name_is_free_when_its_explicit_label_is(self): + """The check is on what the crew will show: a typed name another crew + shows is fine when this crew shows a different label.""" + cfg = self._fake_config() + cfg.agents["legacy"] = KiroCrewAgentConfig( + kiro_agent="kirocrew", display_name="Release Writer" + ) + status, data = await self._post( + {"name": "Release Writer", "display_name": "Scribe", "kiro_agent": "kirocrew"}, cfg + ) + assert status == 200 + assert data["name"] == "release-writer" + + @pytest.mark.asyncio + @pytest.mark.parametrize( + "existing", + [ + ("legacy", KiroCrewAgentConfig(kiro_agent="kirocrew", display_name="Release Writer")), + # A crew stored under a free-form key before ids: its key is its label. + ("Release Writer", KiroCrewAgentConfig(kiro_agent="kirocrew")), + ], + ) + async def test_free_form_name_a_crew_already_shows_is_taken(self, existing): + cfg = self._fake_config() + cfg.agents[existing[0]] = existing[1] + status, data = await self._post({"name": "Release Writer", "kiro_agent": "kirocrew"}, cfg) + assert status == 409 + assert data["code"] == "agent_exists" + assert cfg.saved == [] + + +class TestCrewIdDerivation: + @pytest.mark.parametrize( + "name, expected", + [("Release Writer", "release-writer"), ("Café Bot!", "cafe-bot"), ("a" * 100, "a" * 56)], + ) + def test_slugs_the_name(self, name, expected): + from kiro_crew.members import crew_id_for_display_name + + assert crew_id_for_display_name(name, set()) == expected + + def test_name_with_no_slug_characters_derives_from_its_hash(self): + from kiro_crew.members import crew_id_for_display_name, is_crew_id + + first = crew_id_for_display_name("数据助手", set()) + assert first.startswith("crew-") and is_crew_id(first) + assert crew_id_for_display_name("代码助手", set()) != first + + def test_suffixes_past_taken_ids(self): + from kiro_crew.members import crew_id_for_display_name + + taken = {"release-writer", "release-writer-2"} + assert crew_id_for_display_name("Release Writer", taken) == "release-writer-3" + + @pytest.mark.parametrize( + "value, ok", + [ + ("scribe", True), + ("Scribe_2", True), + ("Release Writer", False), + ("数据", False), + (1, False), + ], + ) + def test_is_crew_id(self, value, ok): + from kiro_crew.members import is_crew_id + + assert is_crew_id(value) is ok + class TestRosterSurfaces: @pytest.mark.asyncio diff --git a/website/src/pages/members/MembersPage.test.tsx b/website/src/pages/members/MembersPage.test.tsx index 73afc0fedbf3..6e402ca40c7b 100644 --- a/website/src/pages/members/MembersPage.test.tsx +++ b/website/src/pages/members/MembersPage.test.tsx @@ -3230,6 +3230,36 @@ describe('New crewmate dialog', () => { await waitFor(() => expect(screen.queryByTestId('crewmate-create-form')).toBeNull()) }) + it('a free-form name opens the crewmate under the id the server answered and greets it by the name it shows', async () => { + const membersMock = api.members as ReturnType + await renderPage([row()]) + expect(await screen.findByTestId('chat-pane-stub', undefined, PANE_READY)).toHaveTextContent('member-oncall') + await openDialog() + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Launch Notes' } }) + ;(api.createKirocrewAgent as ReturnType).mockResolvedValueOnce({ ok: true, name: 'launch-notes' }) + membersMock.mockResolvedValue({ + members: [row(), row({ name: 'launch-notes', slug: 'launch-notes', display_name: 'Launch Notes' })], + default_agent: 'kirocrew', + }) + fireEvent.click(screen.getByTestId('crewmate-create-submit')) + await waitFor(() => expect(api.memberThread).toHaveBeenCalledWith('launch-notes')) + await waitFor(() => expect(currentUrl()).toBe('/members?member=launch-notes')) + await waitFor(() => expect(api.sendChat).toHaveBeenCalledTimes(1)) + const [message] = (api.sendChat as ReturnType).mock.calls[0] + expect(message).toContain('Launch Notes') + expect(message).not.toContain('launch-notes') + }) + + it('a name another crewmate shows is refused up front, like a taken key', async () => { + await renderPage([row({ display_name: 'Oncall Sentinel' })]) + expect(await screen.findByTestId('chat-pane-stub', undefined, PANE_READY)).toHaveTextContent('member-oncall') + await openDialog() + fireEvent.change(screen.getByLabelText('Name'), { target: { value: 'Oncall Sentinel' } }) + fireEvent.click(screen.getByTestId('crewmate-create-submit')) + expect(await screen.findByTestId('crewmate-create-name-hint')).toHaveTextContent('Oncall Sentinel') + expect(api.createKirocrewAgent).not.toHaveBeenCalled() + }) + it('while the create is in flight every control locks — the Advanced toggle and its fields included', async () => { let finish: (v: { ok: true }) => void = () => {} ;(api.createKirocrewAgent as ReturnType).mockReturnValueOnce(new Promise((resolve) => { finish = resolve })) diff --git a/website/src/pages/members/MembersPage.tsx b/website/src/pages/members/MembersPage.tsx index d1b4a3c6ac98..dc0121151010 100644 --- a/website/src/pages/members/MembersPage.tsx +++ b/website/src/pages/members/MembersPage.tsx @@ -692,9 +692,14 @@ export default function MembersPage() { // error after a good read keeps showing the last roster. const rosterQuery = useQuery(membersRosterQuery) const rows = rosterQuery.data ?? EMPTY_ROSTER - // The raw roster's names (not the filtered/projected list): what the create - // dialog refuses up front, and the premise of its post-failure reconcile. - const existingNames = useMemo(() => rows.map((r) => r.name), [rows]) + // The raw roster's keys and shown names (not the filtered/projected list): + // what the create dialog refuses up front, and the premise of its + // post-failure reconcile. The server refuses a name another crewmate shows + // as well as a taken key (`members.key_new_crew`). + const existingNames = useMemo( + () => rows.flatMap((r) => (r.display_name ? [r.name, r.display_name] : [r.name])), + [rows], + ) const loaded = rosterQuery.data !== undefined || rosterQuery.isError const loadError = rosterQuery.data === undefined && rosterQuery.isError // ONE source of truth for the roster fields the page derives from (starred @@ -1344,9 +1349,13 @@ export default function MembersPage() { if (greet && !postCreateErrorRef.current && !otherFollowUp) { pendingGreets.current.delete(m.name) if (pageMounted.current) { + // Greet the crewmate by the name it shows: a crewmate made from a + // free-form name is keyed by a derived id (`launch-notes`) and shows + // the typed text as its label. + const shown = m.display_name?.trim() || greet.name const message = greet.job - ? t('pages.membersPage.greeting_seed_with_job', { name: greet.name, job: greet.job }) - : t('pages.membersPage.greeting_seed', { name: greet.name }) + ? t('pages.membersPage.greeting_seed_with_job', { name: shown, job: greet.job }) + : t('pages.membersPage.greeting_seed', { name: shown }) void seedGreeting(greet, r.slot_key, message) } } diff --git a/website/src/pages/members/NewCrewmateDialog.tsx b/website/src/pages/members/NewCrewmateDialog.tsx index 8fa79dc1b7bc..8fb225496e3a 100644 --- a/website/src/pages/members/NewCrewmateDialog.tsx +++ b/website/src/pages/members/NewCrewmateDialog.tsx @@ -297,7 +297,7 @@ export default function NewCrewmateDialog({ open, onClose, onCreated, existingNa } }, []) const createMut = useMutation({ - mutationFn: (body: CreateBody) => api.createKirocrewAgent(body) as Promise<{ error?: string }>, + mutationFn: (body: CreateBody) => api.createKirocrewAgent(body) as Promise<{ error?: string; name?: string }>, onSuccess: async (r, body) => { // A 2xx whose body still carries `error` is a refusal in the server's // words; like every other failure it is said in the product's. @@ -324,7 +324,10 @@ export default function NewCrewmateDialog({ open, onClose, onCreated, existingNa ]) await Promise.race([warm, new Promise((resolve) => setTimeout(resolve, CACHE_WARM_BOUND_MS))]) if (!mounted.current) return - onCreated({ name: body.name, job: body.description }) + // The server keys a free-form name by a derived id (the typed name + // becomes its display_name), so the crewmate is opened by the id it + // answered with, not the text the user typed. + onCreated({ name: r?.name || body.name, job: body.description }) }, onError: async (e: Error, body) => { if (e instanceof ApiError) {