Skip to content

feat(slack): add a Reconnect action so saved credentials apply without a restart - #16332

Closed
iamwhatever wants to merge 2 commits into
mainfrom
rebase/14574-slack-reconnect
Closed

iamwhatever wants to merge 2 commits into
mainfrom
rebase/14574-slack-reconnect

Conversation

@iamwhatever

Copy link
Copy Markdown
Contributor

Replaces #14574 — rebased onto current main to resolve the merge conflict. Original author: @CrysisDeu (the commits here are authored by them so Rebase-and-merge lands under their name).

Problem / Motivation

Goal: Saved Slack credentials take effect from Settings with one click, without restarting the gateway.

Slack tokens and the owner ID are read exactly once, in GatewayOrchestrator.__init__. Saving new credentials from Settings → Slack (PUT /api/slack/config) writes them to the credential store, but the running Socket Mode client keeps the old ones, and the panel's only advice was "restart the gateway". POST /api/restart execvs the whole process and tears down every in-flight agent run just to re-run one websocket handshake.

Two details made a lighter fix non-trivial:

  • init_socket_mode early-returns when _slack_enabled is False, and its own failure paths set it False. Re-calling it after any earlier failure (a typo'd token at boot, say) is a silent no-op unless the flag is recomputed from the tokens now on disk.
  • WSSocketModeClient.__init__ needs a current event loop in the constructing thread, so the handshake has to be awaited on the gateway loop, not offloaded.

Why it matters

The first-run Slack setup path is exactly where a token typo happens. Today the recovery is "fix it, restart everything, wait, look again". With Reconnect it is one click and the outcome is on the same screen.

Not a goal

  • Changing POST /api/restart or the schema restart_required badge on the slash command (that field still needs a restart; the config watcher does not watch .env).
  • Hot-reloading Slack credentials automatically on save. Reconnect is explicit so a half-typed token is never applied to a working connection by accident.
  • Registry channels (Discord, Telegram, ...). Slack is host-managed; they reconnect through their own lifecycle.

What changed (motivation → approach → change)

Backend

  • GatewayOrchestrator.reconnect_slack() (src/kiro_crew/slack/gateway.py): re-reads cfg.load_credentials() off-loop FIRST (an unreadable store leaves the live connection untouched and raises), closes the old _socket_client (bounded 2 s, best-effort) and clears the dashboard's slack_client mirror with it, reassigns _app_token / _bot_token / _owner_id / _allowed_users and moves DashboardState.owner_id (the owner-only handlers' authorization subject, otherwise set once at boot) to the saved owner, recomputes _slack_enabled = bool(app and bot), rebuilds the Web API client, then awaits init_socket_mode + _connect_slack on the current loop. The Web API client is published to the dashboard ONLY behind a connected socket: a workspace the enterprise gate rejected, a missing owner, a policy deny or a failed handshake all leave the mirror None, so no dashboard sender (chat_slack, send_message, hooks) can use a workspace that was not admitted. Records slack_socket_connected / slack_connect_error where GET /api/slack/config already reads them, and on a connected socket fires the same deferred warn_unreadable_tracked_channels probe boot runs after its connect (a tracked private channel the install cannot read is warned about whether the operator restarted or reconnected). Concurrent callers share ONE in-flight task via asyncio.shield, so a double-click never races two handshakes; a cancelled HTTP request does not cancel the shared attempt. The shared attempt runs under the dashboard's _get_config_lock() — the lock the PUT holds across its .env write — so a reconnect landing mid-save cannot snapshot the credentials being replaced and hoist them after the save commits (the former owner would stay authorized on the live socket). The lock is taken INSIDE the shared task, not by the HTTP handler: a handler-held lock would serialize two concurrent clicks into two full attempts, the second tearing down the socket the first had just established. It stays held until the attempt ends even when every caller has been cancelled. The boot-time SeenCache is kept across reconnects so redelivered envelopes are still dropped.
  • Declines get a named connect_error the panel can explain: tokens_missing, owner_id_missing, enterprise_validation_failed, denied_by_policy; Slack API errors (e.g. invalid_auth) pass through as before.
  • POST /api/slack/reconnect (dashboard/handlers/messaging.py, registered in dashboard/routes/messaging.py): same guards as the sibling PUT (token auth + CSRF middleware, is_direct_local_request → 403), 503 when no gateway owns a socket (API-only server, DashboardState._slack_reconnect is None), 500 when the store cannot be read; every denial carries a machine-readable code (remote_read_only, slack_reconnect_unavailable, credential_store_unreadable) per the error-code contract. Returns {connected, connect_error} — the pair the GET already documents (no configured: the panel reads it from the GET). SEL access log entry slack.reconnect.
  • PUT /api/slack/config now returns reconnect_required (true when a token/owner was written) and narrows restart_required to config-schema fields. Docstrings that said "restart" now name the reconnect route.
  • Queued Slack turns answer through the client that received them (slack/events.py): the listener init_socket_mode installs captures the socket's own Web API client once, beside the socket it builds, and passes it to _route_message(slack_client=…); all three queue writers there bind THAT client into the entry (not orch.slack sampled at the enqueue line — routing suspends on the governance gate, users.info and file downloads, and a Reconnect in that gap swaps orch.slack to another workspace), and _dispatch_queued uses the bound client for the ⏳ reaction and the turn. Without it a Reconnect to a different workspace would carry a workspace-A reply onto workspace B's client (lost on an unknown channel id, misrouted on a colliding one). Callers without a socket (tests) fall back to orch.slack as it is on entry; entries without the key fall back to the live client.
  • The orchestrator wires dashboard_state._slack_reconnect = self.reconnect_slack right after dashboard init, the same seam the MCP-gateway handlers use.
  • Workspace identity (slack/gateway.py, session_map.py, slack/enterprise.py). Persisted Slack destinations (session-map thread / channel links) name no workspace, so the gateway now records the auth.test team_id they were written under in a NEW small state file beside the session map, slack_workspace.json (SLACK_WORKSPACE_STATE_FILENAME, atomic write), and on every connected handshake — boot and reconnect alike, _adopt_slack_workspace via _bind_slack_workspace — compares it with the workspace just validated. A different one is a SWITCH: every persisted Slack link is swept (SessionManager.clear_all_slack_links), the sweep is awaited to disk (aflush) BEFORE the client is published, and the new identity is persisted and only then adopted in memory. When NO workspace is recorded — every existing install, on its first boot after upgrading — the links are KEPT and the workspace is only recorded (a sweep there would end every live mirror on installs whose workspace never changed). A record that exists but cannot be read is not taken for absent: the attempt is refused with workspace_record_unreadable until the file is repaired or removed, re-read on the next Reconnect (no restart). A handshake that connects but establishes no identity while a workspace is recorded is refused with workspace_identity_unverified (socket torn down again); a record that cannot be written, or a sweep whose flush raises, with workspace_identity_unrecorded — in every refusal the freshly built socket is retired, never left live behind an error.
  • Link generation fence (session_map.py, slack/events.py, slack/handler.py, slack/transport_dispatch.py): a sweep advances SessionMap.slack_links_generation(); a Slack turn captures it when its event is received and presents it to every set_slack_link / set_channel it performs (carried with the queued-turn entry and into both dispatch paths); a stale value is refused, so a turn received under the former workspace and resumed after a switch cannot re-persist its thread.
  • Client affinity (slack/affinity.py): the listener binds the Web API client an envelope arrived through to that envelope's task context (client_scope; _dispatch_queued binds the queue entry's), and GatewayOrchestrator.slack is now a property that resolves to the bound client inside it. Every orch.slack read an interaction, slash command, message turn or the tasks they spawn make keeps answering through the workspace whose destinations it holds; code outside any envelope (routes, boot, cron) sees the live client. The registered listener (_on_envelope) is a synchronous binding around _on_event, whose reserve-before-ack contract is unchanged.

Frontend (website/src/pages/settings/SlackPanel.tsx, api/client.ts)

  • A Reconnect button (labelled, with lucide's RefreshCw glyph — a plug glyph was tried and read as a padlock, a locked/switched-off control, to a cold reader) in the panel header next to the status pill. Pending: label "Reconnecting…", button disabled. Success: "Connected to Slack." beside the button and the pill flips to Connected (the GET is invalidated). Failure: the notice reads "Reconnect failed: ", the reason coming from one describeConnectError mapper shared with the startup connect_error, so a boot failure and a click failure never describe the same thing in different words — and the prefix shows that the click ran even when the reason is the same text as before the click. A refusal the gateway itself answered — recognised by its own {error, code} JSON body, whatever the status: 403 remote, 500 credential store unreadable, 503 no socket owner — shows the gateway's reason and remedy; only a request that never got the gateway's answer (network error, or an unstructured 5xx such as a proxy body) is the one plain question, "Reconnect failed. Is the gateway running?". No notice in the panel is closable: like the save's own error, each clears when the next click gets an answer, so the two kinds of failure behave as one kind of warning.
  • After a credential save the confirmation reads "Saved. Click Reconnect to apply." instead of pointing at a restart, and the Reconnect button is rendered right beside it (the header may be scrolled off above the long form); it stays until a reconnect succeeds — including across a later save that touched only config fields, which must not hide the reminder that the earlier credentials are still not live. The row's buttons never wrap; a long confirmation wraps in its own column. Slash-command saves keep the restart wording; a save that changed a token AND the slash command names both steps ("Click Reconnect to apply the tokens; the slash command still needs a gateway restart").
  • One notice at a time: while the transport-failure notice is on screen, the connect error the gateway recorded earlier steps aside (two stacked notices read as two problems), and while a click is in flight the previous failure steps aside too ("Reconnecting…" beside a red "failed" reads as the retry having failed already); the recorded reading returns when the next click gets an answer.
  • Hidden on read-only remote sessions, like Save.
  • i18n: new keys in en.manual.json, all 12 locale catalogs and en-XA; en.context.json entries.

Docs: docs/system-specs/modules/messaging.md and docs/feature-map/README.md describe the route and the reconnect flow.

Backwards compatibility

  • Additive: one new POST route, one new response field (reconnect_required) on the PUT. The reconnect response carries only connected / connect_error. Existing clients that only read restart_required see it become false for pure credential saves — the restart they would have offered is no longer necessary, and the button they would have hidden is now the panel's Reconnect.
  • POST /api/restart is untouched and still works as the fallback.
  • Storage: ONE new state file beside the session map, slack_workspace.json ({"team_id": ...}), written on the first connected handshake and rewritten only on a workspace switch. No config-file or schema change. Existing installs: the first boot on this code finds no record, KEEPS every persisted Slack link and only records the workspace — nothing is swept on upgrade; from then on a switch to another workspace sweeps the former workspace's links. A pre-record switch (credentials replaced while the gateway was stopped, before this file existed) is not detected retroactively — the status-quo exposure, unchanged.
  • Fail-closed trade, deliberate: once an identity is recorded, a handshake that connects without establishing one (auth.test failed — the enterprise gate alone tolerated that) is refused and Slack stays down until Reconnect or a restart; a damaged slack_workspace.json is refused the same way until repaired or removed. Both are named in the panel with their remedy.
  • GatewayOrchestrator.slack becomes a property (context-bound inside a Slack envelope, the live client elsewhere); assignment semantics are unchanged.

Tests

Backend — test/test_slack_reconnect.py (83 tests) and 1 added to test/test_slack_config_handlers.py:

  • recomputes _slack_enabled and hoists the new credentials (red on base: base has no reconnect_slack)

  • awaits init_socket_mode on the running loop (asserts asyncio.get_running_loop() identity inside the fake)

  • load failure leaves the live connection untouched (old client still set, no close())

  • missing tokens disable Slack without a handshake; missing owner ID is named for the badge; connect failure reason surfaced

  • old client close() raising does not block the new handshake

  • a rejected workspace leaves no client in the dashboard (the mirror is already None while init_socket_mode runs, and stays None); a failed handshake publishes no client; an owner change moves DashboardState.owner_id; a cleared owner clears it

  • a connected reconnect schedules the tracked-channel probe with the new client and the dashboard notifier; a failed one does not

  • concurrent callers share one handshake (3 awaits → 1 init_socket_mode call); cancelled caller does not cancel the shared attempt

  • the shared attempt waits for _get_config_lock() while a save holds it (no load_credentials call until the lock is released) and keeps the lock until it ends after its caller is cancelled; two concurrent POSTs both reach the orchestrator before either finishes (a handler-held lock would serialize them: red with the lock in the handler)

  • gateway wires the callback onto DashboardState

  • route: answers the GET shape; denies remote sessions like the PUT (403); 503 without a socket owner; 500 when the store cannot be read; registered as POST beside the PUT

  • PUT: a credential change flags reconnect_required, not restart_required

  • route denials carry their code (403 / 503 / 500)

  • queued turn answers through the client bound at enqueue, not the post-reconnect orch.slack (reaction removal and handle_message first arg); an entry without the key uses the live client; all three _route_message enqueue sites bind slack_client (red on base: 2 of 3 fail without the binding); a Reconnect that swaps orch.slack while routing is suspended (inside the governance gate) still leaves the socket's own client in the queue entry and on the ⏳ reaction (red when the enqueue line samples orch.slack); the listener passes its captured client to _route_message

  • workspace identity: a switch sweeps + flushes before publishing and the identity moves last; a flush failure refuses (workspace_identity_unrecorded), retires the new socket and keeps the former identity (no exception, no live listener); the first recorded identity keeps existing links and sweeps nothing; same workspace keeps links; unknown identity with nothing recorded is accepted; unverified with a recorded workspace refuses and tears down; boot binds through the same refusing step; a missing record reads as nothing recorded, a damaged or unreadable one as damaged (never absent); a damaged record refuses (workspace_record_unreadable), sweeps nothing and leaves the file alone; a repaired or removed record recovers on the next reconnect without a restart (removed → first record, same → no switch, former → the switch is caught); construction keeps the damaged reading; an unwritable record refuses and keeps the former identity; the record is on disk before it is adopted in memory

  • generation fence and affinity: stale generation refused; receipt generation carried to both dispatch paths and all three enqueue sites; every envelope kind is dispatched inside the binding by the registered wrapper, which adds no suspension ahead of _on_event (the reserve-before-ack contract in test_update_check_install_aware.py reads _on_event)

Mutation checks (each reverted in turn, test went red, restored): dropping the _slack_enabled recompute → test_reconnect_recomputes_enabled_and_hoists_new_credentials fails; dropping the shared-task coalescing → test_concurrent_callers_share_one_handshake fails; publishing the mirror before validation (and not clearing it at teardown) → 2 tests fail; not moving DashboardState.owner_id → 3 tests fail; dropping the queue-entry client binding → 2 tests fail; sampling orch.slack at the enqueue line → 1 test fails; moving the config lock back into the handler → 1 test fails; dropping the lock from the shared attempt → 2 tests fail; sweeping on the first recorded identity → 2 tests fail; letting an adoption exception out of _bind_slack_workspace → 1 test fails; reading a damaged record as absent → 10 tests fail.

Frontend — website/src/test/SettingsSlackPanelCoverage.test.tsx, new Reconnect block: success shows "Connected to Slack."; pending label + disabled; the previous failure is off screen while a retry is in flight and the outcome replaces it (red without the change); a rejected reconnect is labelled "Reconnect failed: …" in the same words as a startup failure; the gateway-side decline codes; the gateway's own 403, 500 and 503 refusals are shown as-is (red with the old status < 500 gate); a network error and an unstructured 5xx (a proxy body) both become the one plain question; the workspace_record_unreadable code names the file and the remedy; with a recorded connect error on screen, a transport failure leaves exactly one notice, it has no close button, and the next click's answer replaces it; hidden on read-only; a saved credential change points at Reconnect and renders the button beside the confirmation; a save that changed a token and the slash command names both steps; the save-row button survives a later config-only save (red without the change), goes after a successful reconnect and stays after a failed one.

Run by path only (pytest -n0 <file>, npx vitest run <file>); static gates (black, isort, flake8, mypy; tsc -b --force, eslint, i18n gates) green on the changed files. Full suites run in CI.

Manual verification

Dev stack (gateway + Vite) with deliberately invalid Slack tokens in the credential store, so the gateway booted with connect_error: invalid_auth:

  1. Panel shows "Not connected" with the invalid_auth explanation and the Reconnect button (shot 1).
  2. Click Reconnect → "Reconnecting…", button disabled, the recorded failure off screen while it runs (shot 2).
  3. Slack rejects the tokens → "Reconnect failed: Slack rejected the stored tokens (invalid_auth) …" inline, pill stays Not connected (shot 3).
  4. Save a new owner ID → confirmation reads "Saved. Click Reconnect to apply." with the Reconnect button beside it (shot 4).
  5. Clear the owner ID and Reconnect → owner_id_missing explained in plain language (shot 5).
  6. Stop the gateway process (Vite still serving the SPA), click Reconnect → "Reconnect failed. Is the gateway running?" as the only notice, no close button; the recorded invalid_auth reading steps aside (shot 6).
  7. Change the owner ID and the slash command in one save → "Saved. Click Reconnect to apply the tokens; the slash command still needs a gateway restart." with the Reconnect button beside it; Save and Reconnect stay on one line (measured: button height ≤ 40 px) and the message wraps (shot 7).
  8. Three simultaneous POST /api/slack/reconnect (curl) → one real handshake, all three responses identical.
  9. The connected outcome: the build host has no Slack workspace that admits a handshake, so for shots 8 and 9 only the click's answer is stubbed at the network layer (POST /api/slack/reconnect → {connected: true}, and the GET the panel refetches reports the same), armed after the panel rendered the gateway's real recorded state. Header Reconnect → "Connected to Slack." beside the button, pill Connected, the failure notice gone (shot 8); save an owner ID, click the save-row Reconnect → the save-row button retires (shot 9). The real handshake path is pinned by the vitest re-runs the handshake in place and confirms the connection and reuses the existing Connected pill unchanged.

Every screenshot was retaken at this head (the Reconnect glyph in each is asserted to be RefreshCw, no Plug, before the frame is written).

Screenshots / video

Committed under .github/screenshots/ (this account cannot use --attach, cli/cli#14302).

Not connected at startup, Reconnect available:

Slack panel: Not connected after an invalid_auth boot, Reconnect button in the header

Pending state while the handshake runs:

Slack panel: Reconnecting… label, button disabled

Reconnect ran and Slack rejected the tokens — labelled as the click's outcome:

Slack panel: "Reconnect failed: Slack rejected the stored tokens (invalid_auth) …" inside the panel

More states

Saved credentials point at Reconnect instead of a restart, with the button beside the confirmation:

Slack panel: Saved. Click Reconnect to apply., Reconnect button beside it

Reconnect declined because the owner ID is missing:

Slack panel: owner ID missing explained after Reconnect

The request never reached a gateway (process stopped) — one plain question, the only notice on screen:

Slack panel: Reconnect failed. Is the gateway running?

A save that changed a credential AND the slash command names both steps:

Slack panel: Saved. Click Reconnect to apply the tokens; the slash command still needs a gateway restart.

Connected outcome (handshake answer stubbed, see Manual verification 9): "Connected to Slack." beside the header button, pill Connected:

Slack panel: Connected to Slack. beside the Reconnect button, Connected pill

Saved owner ID, then the save-row Reconnect succeeds and retires:

Slack panel: Saved confirmation, Connected to Slack., no save-row Reconnect

Related Issues

Closes #10306

Pattern harvest

Rule candidate: review-prompt
Pattern: a "retry" entry point that re-calls an init routine guarded by a sticky enabled/failed flag must recompute the flag from current inputs first, or the retry is a silent no-op.

Checklist

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

@iamwhatever
iamwhatever requested a review from a team October 3, 2026 00:12
@iamwhatever
iamwhatever requested a review from a team as a code owner October 3, 2026 00:12
@github-actions github-actions Bot added the readiness: action required A blocking check or review needs attention label Oct 3, 2026
@iamwhatever
iamwhatever force-pushed the rebase/14574-slack-reconnect branch from 45deb5f to 2085daa Compare October 3, 2026 01:20
@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 Oct 3, 2026
@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5) — 🟡 CONCERNS

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

UX-Verdict: CONCERNS

There are three ways to "start again" (Reconnect, "restart", "gateway restart") and only one has a button. The reader couldn't tell them apart and saw no way to do a restart.

Watch

  • The save message names a step the page doesn't offer. saved_reconnect_and_restart reads "the slash command still needs a gateway restart", but the panel has no restart control. The reader (shot-07): "I wouldn't know how to do a 'gateway restart'. Nothing on the page offers one." The Reconnect button uses the same circling-arrow look as the "changes need a restart" tag on the slash command field, so the two read as one action. That invites users to click Reconnect to apply a slash-command change. Severity: medium. It happens on every save that changes the command, and the result is a change that silently doesn't apply. Fix: show a restart action, or say where restart lives, next to that message. Give the Reconnect button a glyph that differs from the restart tag.
  • The network-failure notice offers no next step. "Reconnect failed. Is the gateway running?" got "no idea… this one doesn't tell me what to do" (shot-06). "Gateway" is a word this user doesn't know. Severity: medium. It's rare, but it's a dead end when it happens. Fix: "Couldn't reach Kiro Crew. Check that it's still running, then click Reconnect."
  • The main control was understood, but only as a guess. The reader rated Reconnect "a guess" (shot-01) and wasn't sure why it stays on screen once connected (shot-08). Severity: low. The meaning is right, but users may hesitate. Fix: on the connected state, keep the "Connected to Slack." text and make the button secondary.

Suggestions

  • reconnect_workspace_record_unreadable asks the user to "Repair or remove slack_workspace.json", and the workspace_switch_* messages run to two or three long clauses. Trim each to one sentence about what happened and one about what to do. Keep file names out of the main text.
  • reconnect_denied_by_policy says what happened but gives no next step. Add who to ask, or where the policy lives.
  • In the invalid_auth message, drop "(invalid_auth)". The reader didn't know what it meant (shot-01).

[UX-REVIEWED] e177d3d

Description read

[DESCRIPTION-READ] 9e6e465550aec656abedebf3abbf223e9e37e460dd79bc8c47a22b0fc3d6f508

That sha256 names everything this verdict read: the PR description, plus the 12 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5) — 🔴 BLOCK

Premise-level review of e177d3daed26d51bff3d975a79326a22cab356c1 — 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: BLOCK

Boot now refuses Slack whenever the enterprise gate reports no workspace id. That turns a fail-open channel into a fail-closed one for a Goal about one-click Reconnect.

Not justified as shipped

  • Item 4 — premise risk: "a gate that names no workspace, or omits the method, reads as no identity and is refused"; getattr(current_context().slack_gate, "validated_team_id", None) → "" → workspace_identity_unverified.
    Subtraction: delete the workspace_identity_unverified refusal from _bind_slack_workspace so boot is as permissive as on base.
    Clears when: the refusal is removed, or the author confirms every shipped edition's gate implements validated_team_id.
  • Item 5 — oversized: the Goal is "Saved Slack credentials take effect… with one click". A workspace switch already leaves stale links via restart on base, and no issue is linked.
    Subtraction: delete slack_workspace.json, workspace_record.py, the freeze/sweep/undo and _adopt_slack_workspace.
    Clears when: the mechanism is removed, or a human amends the Goal.
  • Item 6 — oversized: it exists only to serve item 5.
    Subtraction: delete expect_destination, DESTINATION_ANY and CronDestinationMismatch.
    Clears when: the mechanism is removed, or a human amends the Goal.
  • Item 7 — oversized: it exists only to carry item 5's record.
    Subtraction: revert the snapshot_components, IMPORT_ROOT_EXCLUDE and snapshot_restore record handling.
    Clears when: the mechanism is removed, or a human amends the Goal.
  • Item 9 — oversized: link writes now return False, which drives a 503 on the slack-link route, purely to serve item 5's freeze.
    Clears when: the mechanism is removed, or a human amends the Goal.

What this change ships

Inventory (10 items) — 5 justified

Intent: apply saved Slack credentials without restarting the gateway — ADDITION

  1. Reconnect button in Settings → Slack, backed by POST /api/slack/reconnect — justified
  2. Saving Slack config now reports "reconnect required" instead of "restart" — justified
  3. Named reasons when a reconnect is declined, shown in the panel — justified
  4. Boot and Reconnect refuse Slack when the gate reports no workspace id — undeclared in Goal; fail-closed boot
  5. Persisted workspace record; every Slack link is swept on a workspace switch — oversized
  6. Cron jobs' Slack channel/thread cleared on a switch, then restored by compare-and-swap — oversized
  7. Snapshot and import carry and validate the workspace record — oversized
  8. In-flight and queued turns answer through the client and owner that received them — justified
  9. Link writes refused during a switch; the slack-link route returns 503 — oversized
  10. New SlackEnterpriseGate.validated_team_id protocol method — justified

Blockers

  • Unverified premise on a core availability path (Slack channel at gateway boot). The new rule refuses the whole channel at boot whenever the gate names no workspace, and that happens in two cases:

    • an edition whose gate lacks validated_team_id;
    • any auth.test failure (with no record, too: "The refusal holds with NO identity recorded too").

    On base the gate passed those open. Nobody has confirmed any non-default edition's gate implements the method.
    Subtraction: drop the refusal at _bind_slack_workspace.
    Clears when: the refusal is removed, or the author confirms the method on every shipped edition gate and restores today's boot behaviour when no record exists.

[FIRST-PRINCIPLES-REVIEWED] e177d3d

Description read

[DESCRIPTION-READ] 0126897def6c5509d1e65c699887effa2a78df05beaaee08e935d7b2261bba02

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions github-actions Bot added the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Oct 3, 2026
@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review — 🔴 changes requested (blocking)

GPT 6.1 found at least one blocking issue that must be resolved before merging e177d3daed26d51bff3d975a79326a22cab356c1. 3 of 3 blocking finding(s) are security-class and were withheld from adjudication, so the blocking verdict stands.

This comment is updated in place on each push.

BLOCKING -- src/kiro_crew/slack/gateway.py:5851 -- Cron delivery can restore a swept workspace destination

await self.sessions.set_channel(session_key, channel)
A workspace-A cron post awaits post_blocks -> Reconnect completes the A→B sweep and thaws the map -> the resumed unfenced set_thread/set_channel writes persist A’s destination again; subsequent cron follow-ups send it through B’s client.
Anchor: residual/crash-data-loss-corruption
Fix: Capture the link generation beside the settled client before Slack awaits, then persist the thread/channel through one generation-fenced set_slack_link and honor refusal.

BLOCKING -- src/kiro_crew/slack/gateway.py:13560 -- In-flight cron creation escapes the workspace sweep

for row in _cron_destination_rows(rows):
A workspace-A cron_add reaches api_cron_tools and commits after _snapshot_cron_slack_destinations returns, during the awaited switch writes -> this loop visits only captured job IDs -> B is adopted while the new job retains A’s destination, which its next run sends through B’s client.
Anchor: residual/crash-data-loss-corruption
Fix: Fence cron destination submissions by the workspace generation captured at request receipt, keeping the fence effective through snapshot, sweep, and identity commit.

BLOCKING -- src/kiro_crew/snapshot.py:889 -- Snapshot pairing excludes workspace-bound cron destinations

stage, SLACK_WORKSPACE_STATE_FILENAME, "session_map.json", _stage_core_file
A default snapshot copies crons.json under A -> Reconnect completes A→B before the config copies -> the pairing check accepts B’s record/map alongside A’s cron destinations; restoring under B sees no switch and retains those invalid destinations.
Anchor: residual/crash-data-loss-corruption
Fix: Stage selected crons.json inside the workspace-record pairing window and re-stage it alongside the map whenever the identity probe changes.

[BLOCK-MERGE] e177d3d
[GPT-REVIEWED] e177d3d

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

F1 (fenced). Harm is cross-workspace delivery, a security-class rung. Conditions confirmed: the post awaits at gateway.py:5810, and then set_thread (session.py:3687-3690) and set_channel (session.py:3662-3667) run without a generation, so a sweep that finishes in between cannot refuse the write. Reconnect is something an operator does, and a cron post can easily be mid-await when it happens, so this is plausible in real use.

F2 (fenced). Same harm rung. The cron sweep in gateway.py:13560 only visits rows taken by _snapshot_cron_slack_destinations (gateway.py:13140, 13474-13517). A job written by cron_add after the snapshot is outside those rows and nothing fences it. A cron created by the agent during a switch is plausible.

F3 (fenced). Same harm rung. The pairing re-check at snapshot.py:888-890 covers only the workspace record and session_map.json. crons.json is copied earlier in the loop at snapshot.py:875-877, outside that window. I could not confirm a restore-time recovery path, so the FLAG record is incomplete.

[ADJUDICATION] e177d3daed26d51bff3d975a79326a22cab356c1 total=0 uphold=0 downgrade=0
[GPT-ADJUDICATED] e177d3daed26d51bff3d975a79326a22cab356c1

[ADJUDICATION-FENCED] e177d3daed26d51bff3d975a79326a22cab356c1 fenced=3 flagged=0
UPHOLD-FENCED F1 src/kiro_crew/slack/gateway.py:5851 -- An unfenced set_thread/set_channel after the awaited post_blocks can write A's destination back after an operator-triggered Reconnect sweep, and that is a plausible overlap.
UPHOLD-FENCED F2 src/kiro_crew/slack/gateway.py:13560 -- The sweep only visits snapshotted cron rows, so a cron_add that lands during the awaited switch keeps A's destination with nothing to fence it.
UPHOLD-FENCED F3 src/kiro_crew/snapshot.py:889 -- crons.json is staged outside the record/map pairing re-check, and I could not confirm any restore-time recovery from code opened in this run.
[GPT-ADJUDICATED-FENCED] e177d3daed26d51bff3d975a79326a22cab356c1

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

@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5) — 🟡 CONCERNS

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

Design-Verdict: CONCERNS

Supporting a cross-workspace switch through Reconnect makes a one-click credential refresh rewrite persisted session-map links and cron destinations, with a two-phase marker and undo protocol.

Watch

  • The scope grew well past the goal. The goal is "saved Slack credentials take effect … with one click", but the patch also adds slack_workspace.json, a freeze/sweep/restore protocol over every Slack link, cron expect_destination compare-and-swaps (_clear_cron_slack_destinations), a snapshot record/map pairing retry (SlackPairingUnstable), an import exclusion, and context-var client and owner affinity with a revocable SocketAuthority. All of it exists only because a Reconnect may land on a different workspace. If Reconnect refused a team_id that differs from the live or recorded workspace (switching stays restart-only, as on main), most of this machinery would not be needed. The description gives no reason for rejecting that option.
    Clears when: the description says why same-workspace-only Reconnect was rejected, or the workspace-switch machinery moves to its own PR.
  • This changes boot behaviour and deletes persisted data on every handshake, not only on Reconnect. "on every connected handshake — boot and reconnect alike" sweeps every Slack link, and clears a cron job's channel so it "falls back to its creator's DM". Slack also stays down at boot (workspace_record_unreadable) until someone repairs or removes the file. These are new outcomes for a plain restart. The description is cut off at 8000 bytes before any ## Backwards compatibility section, so I can't check whether the cron store, the session map and snapshot restore are listed as readers that see this data rewritten.
    Clears when: a non-truncated ## Backwards compatibility section names those readers (cron_service/store.py, session_map.py, snapshot_restore.py) and the tests that cover a boot-time switch and an unreadable record.

Suggestions

  • Compare the handshake's team_id with the live socket's and refuse a mismatch with a named connect_error (e.g. workspace_changed_restart_required). That covers the stated typo-recovery case without touching persisted links, cron jobs or snapshots.

[DESIGN-REVIEWED] e177d3d

Description read

[DESCRIPTION-READ] c407eec102d0c07c9bd1bd3d4c55e3bc0bdc36adeb88885d8e5c853f5994063c

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@iamwhatever
iamwhatever force-pushed the rebase/14574-slack-reconnect branch from 2085daa to 67b5849 Compare October 3, 2026 01:54
@github-actions github-actions Bot removed the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Oct 3, 2026
@github-actions

github-actions Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review — ✅ no blocking findings

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

Review details

No findings that block the merge; 2 advisory findings.

FINDING — src/kiro_crew/slack/gateway.py:13502 — On a workspace switch, the sweep clears the channel of a script or command cron (return {"channel": None}, (channel, DESTINATION_ANY)). But cron_script.delivery_fingerprint binds "channel" into the secret-grant pin, so _secret_env_precheck fails closed on every later run of each granted script or command cron with a Slack channel, with "cron code changed (or its delivery session was rewired)", until someone re-approves it. The thread is left alone for exactly this reason, but the channel is not. → Fix: skip a script or command cron that carries secret_env in _snapshot_cron_slack_destinations, or re-pin or invalidate that grant explicitly with a notice the operator can see, instead of breaking the pin silently.

FINDING — src/kiro_crew/slack/gateway.py:13737 — init_socket_mode binds received_owner.bind_self_bot_id(validated_self_bot_id()) only once (events.py:988). That bind can run after a transient auth.test failure, which the default gate passes open, and then it binds "". If a _revalidate_slack_identity retry in _bind_slack_workspace then succeeds and the socket is published, _on_event still passes self_bot_id="". Every listed trusted bot is then refused with trusted_bot_requires_verified_self_id for as long as that connection lives. → Fix: after a successful revalidation, call self._slack_socket_authority.bind_self_bot_id(validated_self_bot_id()) before _adopt_slack_workspace runs again.

[OPUS-REVIEWED] e177d3d

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

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

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Oct 3, 2026
@iamwhatever
iamwhatever force-pushed the rebase/14574-slack-reconnect branch from 67b5849 to d9f7c0c Compare October 3, 2026 02:46
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 3, 2026
@iamwhatever
iamwhatever force-pushed the rebase/14574-slack-reconnect branch from d9f7c0c to 322ac25 Compare October 3, 2026 03:59
@github-actions github-actions Bot added readiness: checking Automated validation is still running merge conflict Branch has merge conflicts with its base — author must resolve before merge and removed readiness: action required A blocking check or review needs attention labels Oct 3, 2026
@iamwhatever
iamwhatever force-pushed the rebase/14574-slack-reconnect branch from 322ac25 to 98cad69 Compare October 3, 2026 04:20
@github-actions github-actions Bot removed the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Oct 3, 2026
@iamwhatever
iamwhatever force-pushed the rebase/14574-slack-reconnect branch 2 times, most recently from a520e04 to b19f98b Compare October 3, 2026 05:08
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 3, 2026
@iamwhatever
iamwhatever force-pushed the rebase/14574-slack-reconnect branch from 033a519 to 346019f Compare October 3, 2026 05:51
@github-actions github-actions Bot added readiness: checking Automated validation is still running merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 3, 2026
@iamwhatever
iamwhatever force-pushed the rebase/14574-slack-reconnect branch from 346019f to a779359 Compare October 3, 2026 06:14
@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 merge conflict Branch has merge conflicts with its base — author must resolve before merge labels Oct 3, 2026
@iamwhatever
iamwhatever force-pushed the rebase/14574-slack-reconnect branch from a779359 to c6a0d03 Compare October 3, 2026 06:32
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention merge conflict Branch has merge conflicts with its base — author must resolve before merge and removed readiness: checking Automated validation is still running labels Oct 3, 2026
CrysisDeu and others added 2 commits October 3, 2026 07:30
…t a restart

Slack credentials were hoisted once, in GatewayOrchestrator.__init__, and
nothing reassigned them afterwards, so a token or owner ID saved from the
dashboard could take effect only through POST /api/restart, which execv's
the gateway and tears down every in-flight run.

GatewayOrchestrator.reconnect_slack re-runs the Socket Mode handshake in
place: it re-reads the credential store first (an unreadable store leaves
the live socket untouched), closes the old socket client, reassigns the
boot-hoisted tokens and owner, recomputes _slack_enabled from the tokens
now on disk (init_socket_mode early-returns on a stale False and its own
failure paths set it False), rebuilds the Web API client and awaits
init_socket_mode + _connect_slack on the gateway loop. Concurrent callers
share one in-flight attempt. POST /api/slack/reconnect exposes it behind
the PUT's direct-local gate and answers the connected / connect_error pair
GET /api/slack/config already reports; the PUT now returns
reconnect_required for credential writes, leaving restart_required to the
slash command.

The Slack settings panel gains a Reconnect button beside the status pill
with a pending label, renders the outcome through the panel's existing
error notice (one mapper for startup and reconnect failures), and every
"restart the gateway" hint now points at Reconnect instead.

Closes #10306
…ials

Round-3 review fixes for the Reconnect route (#10306):

- A queued Slack turn now answers through the client that received it
  (`slack_client` in the queue entry) instead of whatever `orch.slack` is
  when the queue drains: a Reconnect to another workspace between enqueue
  and drain no longer carries a workspace-A reply onto workspace B's
  client (GPT F1). All three `_route_message` queue writers bind it;
  entries without the key fall back to the live client.
- `POST /api/slack/reconnect` denials carry a machine-readable `code`
  (`remote_read_only`, `slack_reconnect_unavailable`,
  `credential_store_unreadable`) -- the error-code contract gate
  (test_error_code_contract.py) counted the new site as a regression.
- Slack panel: one notice at a time -- while a transport failure is on
  screen the connect error the gateway recorded earlier steps aside, and
  returns when the next click gets an answer (UX watch item).
- Screenshots: shot 6 re-taken with the single notice; shot 7 added for
  the owner-id + slash-command save (combined confirmation).

Round-4 review fixes:

- A reconnect whose old socket client fails (or times out) to close now
  ABORTS instead of continuing: the old listener may still be receiving
  envelopes, and a reconnect that then stops at `tokens_missing` or
  `owner_id_missing` would have left it up under the credentials the
  operator just replaced, with the handler module still bound to the
  former owner (GPT F1, security). The client stays referenced for the
  next attempt or shutdown to close again, nothing from the store is
  hoisted, the handler module's owner / allowlist are cleared, and the
  outcome is `previous_client_close_failed` (mapped in the panel).
- Step 3 rebinds the handler module's owner / allowlist to the saved owner
  on every reconnect, not only on the path that reaches a handshake.
- Screenshots 8 and 9 show the connected state (header
  reconnect; save-row reconnect retiring), with the Slack handshake
  answer stubbed at the network layer as the UX lane asked.

Round-5 review fixes:

- The credential read runs under the config lock the Slack save holds,
  so a reconnect landing mid-save cannot hoist the credentials being
  replaced after the save commits (GPT security finding, round 4). The
  lock is taken INSIDE the shared attempt, not by the HTTP handler: a
  handler-held lock serialized two concurrent clicks into two full
  attempts, the second tearing down the socket the first had just
  established (GPT finding, round 5).
- The socket listener captures its own Web API client once and passes it
  to `_route_message(slack_client=)`; the queue writers bind THAT client,
  not `orch.slack` sampled at the enqueue line -- routing suspends on the
  governance gate, `users.info` and file downloads, and a Reconnect in
  that gap swapped `orch.slack` to another workspace (GPT blocking
  finding, round 5).
- Slack panel: the Reconnect glyph is RefreshCw again -- the plug read as
  a padlock to a cold reader (UX blocker); the previous failure is off
  screen while a retry is in flight; no notice is closable (the two
  notices behaved as two kinds of warning); the save row's buttons never
  wrap; a later config-only save keeps the pending Reconnect reminder
  (GPT finding). Every screenshot retaken at this head.

- First workspace adoption is deferred to the socket connect through the
  same prepare/commit/undo lifecycle a switch uses, so a failed first
  connect never durably records a workspace it did not reach (GPT 6.1
  data-loss finding, gateway.py:_adopt_slack_workspace).

- Cron Slack delivery binds the settled client across DM resolution
  and send (slack_affinity.client_scope) and resolves the destination
  from the current cron record, so a workspace Reconnect between a
  cron's ack/edit and its delivery no longer opens the DM through the
  former workspace's client or posts a stale channel/thread, which
  consumed a one-shot without its Slack notification (GPT 6.1 F1/F2).

- Every workspace-record write stamps a fresh non-reusable `rev`, so a
  write-then-rollback to the same team_id is never byte-identical and the
  snapshot pairing probe recopies the session map rather than accepting a
  backup whose map was staged while the Slack links were swept (GPT 6.1).
  The cron destination re-read is guarded to a real CronJob so a degraded
  store read falls back to the captured job.

Co-authored-by: cixuuz <26782336+cixuuz@users.noreply.github.com>
@iamwhatever
iamwhatever force-pushed the rebase/14574-slack-reconnect branch from c6a0d03 to e177d3d Compare October 3, 2026 07:32
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: checking Automated validation is still running labels Oct 3, 2026
@iamwhatever

Copy link
Copy Markdown
Contributor Author

Closing this rebase replacement. The rebase onto main is done and all the real bugs found along the way are fixed on branch rebase/14574-slack-reconnect, but a design conflict (GPT wants a generation-fenced cron write at gateway.py:5851; main's eviction-safety needs the unfenced set_thread/set_channel pair) plus First Principles' scope BLOCK on the workspace-switch subsystem are an author/maintainer call. Details and the full fix list are on the original PR: #14574 (comment) — the branch is kept for whoever picks it up.

@iamwhatever iamwhatever closed this Oct 3, 2026
@github-actions github-actions Bot removed the readiness: action required A blocking check or review needs attention label Oct 3, 2026
@bolichen97
bolichen97 deleted the rebase/14574-slack-reconnect branch November 6, 2026 07:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Slack: add a Reconnect action so saved credentials take effect without restarting the gateway

2 participants