Skip to content

refactor(slack): compose the gateway's sub-agent path and constructor - #21176

Merged
bolichen97 merged 1 commit into
mainfrom
refactor/linecap-g02-gateway-p4
Oct 16, 2026
Merged

bolichen97 merged 1 commit into
mainfrom
refactor/linecap-g02-gateway-p4

Conversation

@bolichen97

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: Bring slack/gateway.py under the 1,200-line target by composing its sub-agent completion path, its constructor and its channel boot from owner modules, with no behaviour change.

slack/gateway.py is 4,035 lines after the third PR of this series (#20761). The repository is adopting a 2,000-line cap on hand-written files (#20192), and this file's 7-day churn puts its target at 1,200. GatewayOrchestrator._init_subagents alone is 1,888 lines: one closure, _subagent_done, consumes every sub-agent's terminal report, so moving whole definitions cannot shrink it. This PR decomposes that closure into methods with explicit inputs and moves them out, together with the constructor, the channel hoists and the runtime-death charge. It is the fourth and last PR of the series.

Why it matters

The sub-agent completion path is where every fix to wave digests, completion delivery and injection retries lands. Each of those now gets a file the size of one responsibility, and the facade, which every gateway change touches, drops to 1,178 lines, leaving room under the cap for the features that follow.

Not a goal

What changed (motivation → approach → change)

_init_subagents held the whole completion consumer in one closure, so its phases shared locals instead of parameters. This PR first turns each phase into a method or function whose closure inputs become parameters, still in gateway.py, then moves them, with the constructor and the channel boot, into six new owners and eight existing ones:

Owner Responsibility
orchestrator_init.py __init__: the initial value of every field the owners share
channel_boot.py the per-channel hoists, the config-applier registration, starting the channel transports
subagent_wiring.py _init_subagents: the manager and its callbacks, and the _subagent_done spine (tab resolution, the "done" frame, the wave peek, the routing calls)
subagent_report.py composing a completion's report and card facts; the wave digest, synchronous from the wave record to the hold-or-flush decision
subagent_injection.py delivering a completion to its parent's tab, channel or session, cron session, or the bell
runtime_charge.py charging a runtime death only to whoever caused it: the cron verdict, attribution and charge, and the injection retry whose death arms reset the parent

The update restart's body moves to update_schedule.py behind the decorated _restart_after_update, which compose cannot rebind; a few small members and constants join the owners that read them (cron_fire, cron_exec, exit_path, service_boot, cron_delivery, heartbeat_turns, process_entry). The class declares, without values, every field the constructor and the hoists assign, because an inline annotation on self: GatewayOrchestrator is a type error there; a __new__ fixture still gets AttributeError. __init__ is bound under the else of if TYPE_CHECKING:, whose branch gives the type checker the owner's signature, because mypy reads a class-body assignment to __init__ as an incompatible override of object.__init__. The class body's owner bindings drop the blank row between them.

gateway.py goes from 4,035 to 1,178 lines; the largest new file is 877.

Backwards compatibility

Compatible: every name kiro_crew.slack.gateway bound before this PR stays bound, pinned by test_campaign_facades_base_public_names.py; every moved member keeps its name, kind, signature, __module__ and __qualname__, pinned by _BASE_SURFACE; inspect.signature(GatewayOrchestrator) is unchanged, pinned by test_gateway_orchestrator_init.py.

Removes nothing: no public module-level function moves out of a product file, and every moved name stays reachable on the facade or the class.

Log lines keep the kiro_crew.slack.gateway logger: the owners read the facade's logger through the composed globals.

Tests

  • New test_gateway_subagent_wiring.py, test_gateway_subagent_report.py, test_gateway_subagent_injection.py and test_gateway_runtime_charge.py (57 tests) characterise what the decomposition must keep, driven through the real on_done and passing unchanged before and after the move: which tab a completion lands in and which slot its frames name, the restored tab's window load, the records that route nothing, the report's text and redaction order, the card facts, the wave's lookups, failure arms, chunk and close, the inline-collected skips, the in-flight count across a wait and a cancellation, the turn's provenance, each channel attempt's session wiring and timeout bound, the cron session's reset decision, and every arm of the injection retry. Each was proven by mutation on the code before the move (58 mutations, all red).
  • New test_gateway_orchestrator_init.py (6 tests): the class declares exactly the fields the constructor and the hoists assign, with the 75 annotations they carried inline; no declaration creates a class attribute; the constructor keeps its name, module and signature; the type checker's stub is the owner's signature.
  • Re-pointed guards: listed below; each turned red when its construct was altered in its new home.
  • Local runs: the 343 test files that import, patch or read the gateway or a file whose citation moved: 22,146 passed, 47 skipped; per-file coverage of the new owners: orchestrator_init 100%, channel_boot 100%, subagent_wiring 84%, subagent_report 97%, subagent_injection 93%, runtime_charge 97% (and the owners that gained members: update_schedule 82%, cron_fire 97%, cron_exec 93%); cold mypy clean (2,477 source files); black, isort, flake8, comment-history, brand, harness, subprocess-encoding, agent-sdk boundary, sync-io, docs-lint and line-cap gates clean; semgrep on the changed files against main: 0 findings, 0 parse errors; the flake ratchet passes; the new test files pass 5 runs at -n0, one at -n 3 and one in reversed order; the six owners ship in the wheel and import from it.

Re-pointed guards

Guard Re-point
test_runtime_death_is_a_process_event _GUARDED_CHARGES row and the hand-over sites -> runtime_charge.py; the death-arm scan and the attribution-flag reachability scan read the facade and every owner
composition contract _BASE_SURFACE rows for every moved and new member; _GUARDED_TOKEN_HOMES re-keyed for 12 tokens; the hoisted-attribute check exempts the two files the hot-reload test reads
test_channel_boot_hot_reload dedents a hoist's source whatever its column; reads consumed attributes from orchestrator_init.py and channel_boot.py too
test_channel_readiness derives the channels' credential needs from the facade and every owner
test_memory_v2_isolation the parent-key surface row -> subagent_injection.py
test_no_config_dir_in_async four owner rows
test_security_posture census slack/gateway.py 1 -> 0 (row dropped), subagent_injection.py 1; security_posture.py re-keys the "Slack cron / notification posts" sink from slack/gateway.py to slack/gateway_runtime/subagent_injection.py, which holds that row's redaction, and lists subagent_report.py and subagent_wiring.py as non-egress
test_spawn_approval_channel_delivery_2381, test_spawn_approval_no_surface_2381 the seam-first ratchet reads subagent_wiring.py; the one-raising-instance count reads the facade and every owner
test_gateway_runtime_bindings _SLACK_APPLIER_PREFIXES is a bound class constant of channel_boot
test_memory_startup, test_slack_gateway_overload_wiring the boot-path negative pins (no crew_log_emit, no _start_adaptive_controller) read _init_subagents and the six completion phases it calls
test_feature_videos_boot_path the constructor sets self._feature_video_task = None, and the class declares the field with the annotation the constructor carried
test_slack_gateway (the uncredentialed-probe ratchet) the probe table and the hoists' enable predicates are read from the facade's methods and then the owners' functions
test_gateway_restart_uses_respawn_executable the no-resolver-import pin checks the decorated method and the body it runs
test_session (delivery-routing producers) unchanged; the producer list it reads, subagent.DELIVERY_ROUTING_MODULES, names the completion consumer's four owners (see below)

Cross-scope edit (Master grant)

src/kiro_crew/subagent.py: DELIVERY_ROUTING_MODULES replaces slack/gateway.py with slack/gateway_runtime/subagent_wiring.py, subagent_report.py, subagent_injection.py and runtime_charge.py: the three that write the routing fields, and subagent_wiring.py, whose _subagent_done spine routes every completion, so a field a later change writes there is classified too; and the comment above it names those producers; docs/system-specs/modules/subagent.md says the same, and the INJECTION_TIMEOUT comment in src/kiro_crew/subagent_parts/run_limits.py names where _subagent_done lives. Without it the producer scan reads a facade that writes none of those fields, and its stale-classification check fails.

Citations (L29)

File Old → new
docs/system-specs/modules/slack-gateway.md the facade row, six owner rows, three owner rows extended, "What stays in the facade" rewritten, the live-configuration note
docs/system-specs/modules/subagent.md, messaging.md, heartbeat.md, memory-skills-hooks.md, common/injected-messages.md, architecture/resource-protection.md slack/gateway.py → the owner that holds the cited code
src/kiro_crew/subagent.py, src/kiro_crew/subagent_parts/run_limits.py (comments) the routing producers; slack/gateway.py → subagent_wiring.py for _subagent_done
src/kiro_crew/slack/gateway_runtime/cron_exec.py (comment) cron.py's _execute_with_timeout → CronService._execute_with_timeout (#20862 moved it)
src/kiro_crew/slack/gateway_runtime/cron_fire.py (two comments) config/sections.py → config/sections_agent.py, where agent.default_agent lives (#21129 split it)
src/kiro_crew/messaging/registry.py, slack/gateway_runtime/__init__.py, channel_lifecycle.py, cron_verdict.py, delivery.py, slack/gateway.py docstrings name the new homes
src/kiro_crew/messaging/spawn_approval_delivery.py (docstring), dashboard/ws_event_scope.py (comment) slack/gateway.py → slack/gateway_runtime/subagent_wiring.py (the spawn-approval callback; the _subagent_event closure)
src/kiro_crew/dashboard/messaging_api/teams_settings.py (two comments) the boot path slack/gateway.py → _hoist_teams in slack/gateway_runtime/channel_boot.py
docs/system-specs/modules/learn-cron-dashboard.md the _acquired flag pattern: gateway.py → the gateway's turn owners
test/test_members_preview_speech_only.py (comment) slack/gateway.py → slack/gateway_runtime/subagent_report.py

Manual verification

N/A — a structural move: the characterisation tests drive the completion consumer through the unchanged on_done, and test/integration/test_boot_smoke.py boots the gateway in-process.

Move audit

src/kiro_crew/slack/gateway.py: 4035 -> 1178 lines; moved 15.07% (python-ast)

move_audit.py compares whole definitions, so it lists the units this PR cut or re-plumbed as changed: _init_subagents (its closure's phases became methods), __init__ and eight hoists (their inline annotations moved to the class), _restart_after_update (its body moved behind the decorated method), _start_channel_transports (one reworded docstring line), and the class itself. With the self: annotation, the dropped @staticmethod and docstring re-indent normalised away, 25 more units move verbatim. The region audit re-derives every region from the base and compares its tokens with the def that now holds it: 9,536 of 9,865 base tokens unchanged; every difference is one of the listed edits, a stripped annotation, a reworded comment, or a pair of parentheses black drops once an annotation is gone.

Diff alignment (L36)

git diff --numstat and git diff --minimal --numstat agree on every changed file except two, where the default diff re-shows blank lines only (accepted under L41): src/kiro_crew/slack/gateway.py 236/3093 vs 234/3091 (two blank rows inside the new declaration and constructor-stub block) and docs/system-specs/modules/slack-gateway.md 28/23 vs 27/22 (one blank row).

Files over 2,000 lines this PR grows

src/kiro_crew/security_posture.py, +4: the non-egress rows for two redacting sub-agent owners, the re-keyed sink row and the reworded comment above them.

src/kiro_crew/subagent.py, +5 (Master grant, see above): the four routing producers and the two comments naming them.

test/test_slack_gateway.py, +5 (Master grant): the uncredentialed-probe ratchet reads the probe table and the enable predicates from the owners as well as the facade.

All three are report-only under the line-cap guard; their rows are left as they are.

.github/file-line-cap-baseline.txt deletes the slack/gateway.py row: the facade is now 1,178 lines.

CI path references

None changed. AUTOSDE.yaml already covers src/kiro_crew/slack/gateway_runtime/**/*.py, and no workflow filter or file list names slack/gateway.py.

Related Issues

Part of #20192

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title
  • 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

Contribution License Agreement

Contributed under the project's Apache-2.0 license.

slack/gateway.py was 4,035 lines after the cron split, and its target under
the 2,000-line cap (#20192) is 1,200. _init_subagents alone was 1,888
lines: one closure, _subagent_done, consumes every sub-agent's terminal
report, so moving whole definitions could not shrink it.

The closure's phases become methods and functions whose closure inputs
are parameters, and they move with the constructor, the channel hoists
and the runtime-death charge into six owners under gateway_runtime:
orchestrator_init, channel_boot, subagent_wiring, subagent_report,
subagent_injection and runtime_charge. The update restart's body moves
behind the decorated _restart_after_update, and small members and
constants join the owners that read them. The class declares, without
values, every field the constructor and the hoists assign; __init__ is
bound under the else of if TYPE_CHECKING, whose branch gives the type
checker the owner's signature. gateway.py is now 1,178 lines.

Regions move verbatim apart from re-plumbing, stripped inline
annotations and reworded comments. Characterisation tests drive the
completion consumer through on_done before and after the move;
re-pointed guards read the owners, and the delivery-routing producer
list names them.

Part of #20192
@bolichen97

Copy link
Copy Markdown
Contributor Author

Sensitive change review

  • Head commit: 7c6c23c
  • What rule changed: no rule changes. src/kiro_crew/security_posture.py re-keys the registered "Slack cron / notification posts" redaction sink from slack/gateway.py to slack/gateway_runtime/subagent_injection.py, the composed owner that now holds that sink's redaction (the sub-agent completion's failure reason before it reaches a channel), and adds slack/gateway_runtime/subagent_report.py and slack/gateway_runtime/subagent_wiring.py to NON_EGRESS_REDACTION_MODULES; the comment above those rows says which owner is the sink and why the others add no egress path.
  • Before -> after (what was allowed/blocked, now): before, the sink row named slack/gateway.py, which held those redactor calls; after, the same calls, moved verbatim, live in subagent_injection.py (the sink row) and in subagent_report.py (what a completion's report quotes) and subagent_wiring.py (the orphan notices, the failure frames and the recovery turn's queued failures), listed as non-egress modules because, like the gateway's other composed owners, they run in the sink's process on the facade's namespace, so the split adds no egress path of its own. Nothing is newly allowed or blocked.
  • Worst case if wrong (breaks commands / leaks secret / locks user out): the security posture panel would show the Slack cron / notification sink under the wrong file; no redaction is removed or weakened, because every moved call keeps its arguments and order and runs on the facade's globals through gateway_runtime.compose.
  • Evidence checked (which sandbox result proves it): no sandbox path changes, so no sandbox result applies; test/test_security_posture.py (sink registry, omission detection, and the gate-side log census re-keyed to subagent_injection.py 1 with the slack/gateway.py row dropped) passes on this head, as do the 343 related test files and cold mypy; a planted unregistered redactor call in subagent_injection.py and a removed non-egress row each turn it red.
  • No regression:
    • Tools still work (which tools/commands were run, result): no tool, gate, policy or sandbox path changes; the composition contract test pins that every owner function runs on the facade namespace, and it passes.
    • Backward compatible (old config / old data / old callers still work, how checked): every redactor call site keeps its arguments and order, and no registry row is removed or narrowed, only re-keyed to the file that holds the call; checked by the census and omission tests above.
    • Existing tests (which suites passed on this head): test_security_posture.py, test_core_path_redact_before_bound.py and the gateway suite pass with their assertions unchanged; only rows are re-pointed.
  • How to undo: revert this commit; the sink row returns to slack/gateway.py together with the moved code.

@github-actions

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5) — ⏭️ skipped

Revision 7c6c23c33fe32dca1937c8e95d844413a457a898 touches no user-facing surface (no changes under website/ or committed screenshots), so the UX review was skipped. Advisory — does not block merge.

@github-actions

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5) — ✅ PASS

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

Design-Verdict: PASS

Check that the hand-written __init__ stub under TYPE_CHECKING matches orchestrator_init.__init__; test_gateway_orchestrator_init.py is what keeps the two from drifting.

[DESIGN-REVIEWED] 7c6c23c

Description read

[DESCRIPTION-READ] f4dc8456014eaa65b724e60a3b7a87bb244f28fb895c2e88430e60c7b114168f

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.

@github-actions

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5) — ✅ PASS

Premise-level review of 7c6c23c33fe32dca1937c8e95d844413a457a898 — 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: PASS

Check that moving security_posture's "Slack cron / notification posts" sink to subagent_injection.py still covers every egress leg gateway.py used to hold.

What this change ships

Inventory (8 items) — 8 justified

Intent: bring slack/gateway.py under the 1,200-line target for the line cap by splitting it into owner modules, with no behaviour change. This is a FIX (cap compliance), not an ADDITION.

  1. The _subagent_done closure is split into methods and moved into subagent_wiring, subagent_report, subagent_injection and runtime_charge — justified
  2. The constructor moves to orchestrator_init.py, and the channel hoists and transport start move to channel_boot.py — justified
  3. The class body now declares 75 fields without values, which mypy needs once the constructor is on a non-self receiver — justified
  4. __init__ is bound under the else of if TYPE_CHECKING: for mypy — justified
  5. The update-restart body moves behind _restart_after_update in update_schedule.py, and small members join seven existing owners — justified
  6. security_posture moves the cron/notification sink to subagent_injection.py and lists two non-egress owners — justified
  7. The gateway.py row is dropped from file-line-cap-baseline.txt — justified
  8. Guards and spec/comment citations are re-pointed to the new owner paths — justified

[FIRST-PRINCIPLES-REVIEWED] 7c6c23c

Description read

[DESCRIPTION-READ] 4e8205a9dad73de4afa18432e7f1198d640da2dfcd077e6e1652f311a8a04b54

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

Copy link
Copy Markdown
Contributor

Sensitive Change Review

Sensitive files changed:

  • src/kiro_crew/security_posture.py

  • @bolichen97 posted a complete reasoning template for 7c6c23c.

@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Oct 16, 2026
@bolichen97
bolichen97 enabled auto-merge (squash) October 16, 2026 09:05
@github-actions

Copy link
Copy Markdown
Contributor

Opus 5.5 Review — ✅ no blocking findings

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

Review details

No findings.

[OPUS-REVIEWED] 7c6c23c

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

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

@github-actions

Copy link
Copy Markdown
Contributor

GPT 6.1 Review — ✅ no blocking findings

GPT 6.1 completed its review of 7c6c23c33fe32dca1937c8e95d844413a457a898 and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 7c6c23c

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

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • Design punchline: the TYPE_CHECKING __init__ stub matches orchestrator_init.__init__ — answered, checked

Nobody writes the stub by hand. The split recipe copies it from the owner's def __init__ header, with self: GatewayOrchestrator turned into self and the body turned into .... The facade binds the real function under the stub's else branch, so the stub only ever reaches the type checker.
test_gateway_orchestrator_init.py::test_the_type_checkers_constructor_stub_is_the_owners_signature compares the stub's parsed signature with the owner's: parameter names, kinds, defaults and annotations. The recorded mutation that flips one default in the stub (no_open: bool = True) turns it red.
Separately, inspect.signature(GatewayOrchestrator) is pinned to the base signature in the same file, and cold mypy (2,516 files) checks every constructor call against the stub.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • First Principles punchline: the re-keyed sink still covers every egress leg gateway.py held — answered, checked

At this PR's base, slack/gateway.py holds 32 redactor-call lines. At this head it holds none. The same 32 calls moved verbatim: 14 to subagent_injection.py, which is the re-keyed "Slack cron / notification posts" sink row and holds the tab, channel and cron injections plus the failure reason; 11 to subagent_wiring.py (orphan notices, owner DM, failure frames); and 7 to subagent_report.py (the report and card text). The last two are listed in NON_EGRESS_REDACTION_MODULES.
test_security_posture.py's omission test requires every module holding a redactor call to be a registered sink or listed non-egress. Its census re-keys slack/gateway.py 1 to subagent_injection.py 1. Both pass at this head. A planted unregistered redactor call, and a removed non-egress row, each turn it red.
Every moved call keeps its arguments and order, and runs on the facade's globals through gateway_runtime.compose.

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

Copy link
Copy Markdown
Contributor

HOLD at 7c6c23c. This needs a human review because it touches src/kiro_crew/security_posture.py. It moves the "Slack cron / notification posts" redaction sink to slack/gateway_runtime/subagent_injection.py and lists subagent_report.py and subagent_wiring.py as non-egress owners (security_posture.py#L926-L930, #L2500-L2523). It also moves the runtime-death charge and parent-reset path into runtime_charge.py.

I found no defect. I recounted the redactor calls: the 32 that leave gateway.py land as 14 in subagent_injection.py, 7 in subagent_report.py and 11 in subagent_wiring.py, which matches the author's census. The non-egress listing follows the same rule the gateway's other composed owners already use. Both current-head lane punchlines (Design, First Principles) are answered with test evidence. GPT and Opus report no findings, and CI is green.

A maintainer's sign-off on the posture re-key clears this. A new push needs a fresh review.

— crew-pr-reviewer (r107)

@KiroCrewCaptain KiroCrewCaptain left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approved by a maintainer. The triage automation held this on a size, path or move-check rule only; every review lane is clean. Any lane note is accepted as follow-up work.

@bolichen97
bolichen97 merged commit 1ae9ac7 into main Oct 16, 2026
102 checks passed
@bolichen97
bolichen97 deleted the refactor/linecap-g02-gateway-p4 branch October 16, 2026 18:11
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Oct 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants