Skip to content

refactor(subagent): compose module-level helpers from subagent_parts - #20401

Merged
bolichen97 merged 1 commit into
mainfrom
refactor/linecap-g07-subagent
Oct 16, 2026
Merged

bolichen97 merged 1 commit into
mainfrom
refactor/linecap-g07-subagent

Conversation

@bolichen97

@bolichen97 bolichen97 commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: Bring src/kiro_crew/subagent.py closer to the 2,000-line cap by moving its module-level helpers into focused kiro_crew.subagent_parts modules, with no change in behaviour.

subagent.py is 6,923 lines and among the most edited files in the repository (25 commits in the last 7 days). The campaign in #20192 caps hand-written files at 2,000 lines; a file this size cannot be split by moving definitions alone, because SubagentManager by itself is 3,084 lines. This PR is the first of two: it moves everything above the class (lines 288-2755 at the base); the second PR moves the class body the same way.

Why it matters

A 7,000-line file is where every subagent change lands and conflicts, and reviewers (human and AI) read it in fragments. Each moved group gets one module with one stated responsibility, so new code has an obvious home and the facade stops growing.

Not a goal

  • No behaviour change: function bodies move verbatim; no logic, wording, logging or error text changes.
  • Not the SubagentManager class: its split is the second PR of this series.
  • No new public API: every name stays importable and patchable at kiro_crew.subagent.
  • No change to subagent_manager/ or its bind_component_globals mechanism.

What changed (motivation → approach → change)

subagent.py drops from 7,095 to 4,697 lines. 152 module-level definitions move into six owners under a new package, kiro_crew.subagent_parts:

Owner Lines Owns
run_limits.py 361 timeouts, intervals and limits a run is held to
run_output.py 221 redaction, error chains, the done result, the usage line, credit accounting
agent_policy.py 918 which agent a spawn may name: roster, refusal codes, allowlists, validate_cwd
model_choice.py 339 the model and effort a spawn starts with, and the effort notes
host_memory.py 690 host, container and cgroup memory readings and the subagent ceiling
start_pricing.py 332 what a start costs in memory and the off-loop host read

The point is that kiro_crew.subagent stays one namespace. Tests patch about 1,500 kiro_crew.subagent.<name> targets, and moved code must still see those patches. So subagent.py re-exports every moved name, and subagent_parts.compose() (in the package __init__, 143 lines) rebinds every owner function onto the facade's globals, the same way slack/gateway_runtime composes slack/gateway.py. Owners import the facade only under TYPE_CHECKING. The values an owner computes when it is imported (defaults, class bodies, one dataclass field factory) import what they read directly, and run_output imports Any for real so typing.get_type_hints(SubagentDelivery) resolves as before.

Everything a path-keyed guard reads stays in subagent.py: the seven agent-sdk boundary imports, the class, and the existing bind_component_globals tail.

Backwards compatibility

Compatible: every name kiro_crew.subagent bound at the base still resolves there to the same object (test_campaign_facades_base_public_names.py), and every kiro_crew.subagent.<name> patch still reaches the moved code, because the moved functions run on the facade's globals.

The 19 public module-level functions below moved from subagent.py into kiro_crew.subagent_parts; subagent.py re-exports each one, so their import path is unchanged.

Reader: src/kiro_crew/mcp_tools/spawn.py:visible_agent_names -- subagent -- imports it from kiro_crew.subagent, which re-exports the same object; test_spawn_agent_roster.py
Reader: src/kiro_crew/subagent_parts/agent_policy.py:spawn_allowlist -- subagent -- _scan_parent_spawn_allowlists reads it as a facade global; test_spawn_parent_available_agents.py
Reader: src/kiro_crew/mcp_tools/spawn.py:agent_matches_allowlist -- subagent -- imports it from kiro_crew.subagent (re-exported); test_spawn_parent_available_agents.py
Reader: src/kiro_crew/dashboard/messaging_api/spawn.py:parent_spawn_allowlists -- chat -- imports it from kiro_crew.subagent (re-exported); test_campaign_facades_base_public_names.py
Reader: src/kiro_crew/subagent_manager/admission/gate.py:parent_spawn_policy -- subagent -- imports it from kiro_crew.subagent (re-exported); test_campaign_facades_base_public_names.py
Reader: src/kiro_crew/slack/gateway.py:format_subagent_usage -- chat -- imports it from kiro_crew.subagent (re-exported); test_campaign_facades_base_public_names.py
Reader: src/kiro_crew/dashboard/messaging_api/spawn.py:effort_drop_reason -- chat -- imports it from kiro_crew.subagent (re-exported); test_campaign_facades_base_public_names.py
Reader: src/kiro_crew/dashboard/messaging_api/spawn.py:effort_applied_note -- chat -- imports it from kiro_crew.subagent (re-exported); test_campaign_facades_base_public_names.py
Reader: src/kiro_crew/dashboard/messaging_api/spawn.py:effort_pending_note -- chat -- imports it from kiro_crew.subagent (re-exported); test_campaign_facades_base_public_names.py
Reader: src/kiro_crew/subagent_manager/admission/gate.py:pop_memory_check_cause -- subagent -- imports it from kiro_crew.subagent (re-exported); test_subagent_parts_composition_contract.py
Reader: src/kiro_crew/subagent_manager/admission/gate.py:check_memory_available -- subagent -- imports it from kiro_crew.subagent (re-exported); the conftest healthy_host_memory patch still reaches it
Reader: src/kiro_crew/slack/gateway_runtime/admission.py:subagent_count_ceiling -- chat -- imports it from kiro_crew.subagent (re-exported); test_campaign_facades_base_public_names.py
Reader: src/kiro_crew/subagent_parts/host_memory.py:compute_max_subagents -- subagent -- resolve_max_subagents reads it as a facade global, so test_adaptive_controller.py's patch still reaches it
Reader: src/kiro_crew/taskrunner.py:compute_memory_sized_parallel_cap -- cron -- imports it from kiro_crew.subagent (re-exported); test_campaign_facades_base_public_names.py
Reader: src/kiro_crew/context.py:resolve_max_subagents -- chat -- imports it from kiro_crew.subagent (re-exported); test_campaign_facades_base_public_names.py
Reader: src/kiro_crew/spawn_warm.py:validate_cwd -- subagent -- imports it from kiro_crew.subagent (re-exported); test_campaign_facades_base_public_names.py
Reader: src/kiro_crew/dashboard/state.py:set_parent_project_resolver -- chat -- imports it from kiro_crew.subagent (re-exported); the resolver it installs lands in the facade's namespace, which parent_project_dirs reads; test_spawn_parent_available_agents.py
Reader: src/kiro_crew/subagent_parts/agent_policy.py:parent_project_dirs -- subagent -- parent_template_allowlists reads it as a facade global; test_spawn_parent_available_agents.py
Reader: src/kiro_crew/dashboard/messaging_api/spawn.py:parent_template_allowlists -- chat -- imports it from kiro_crew.subagent (re-exported); test_spawn_parent_available_agents.py

__module__ of the moved functions still names kiro_crew.subagent (compose sets it); the four moved classes (SubagentDelivery, _RunCreditAccounting, _SharingPlan, ParentRecordUnreadable) keep their owner module as __module__. Nothing reads those (pickle, copyreg, shelve, repr and error-text greps: no hits).

Tests

  • test/test_subagent_parts_composition_contract.py (new, 31 tests) pins the composition:
    • every owner function runs on the facade's globals, and every global it reads is bound there (bytecode sweep with a self-test);
    • every name the test trees patch on kiro_crew.subagent (corpus-derived, with a spelling self-test) is read by no owner code that runs elsewhere, plus two executed patches through moved code;
    • each moved name keeps its base kind and signature and is one object on the facade and the owner;
    • __module__, __qualname__ and the logger still name the facade;
    • nothing but the facade imports an owner; owners import the facade only for type checking and no sibling, with self-tests;
    • owners carry 0 agent-sdk boundary edges and the facade keeps 7;
    • every import the facade keeps only for owners is read by one;
    • a synthetic compose() run, and a fresh-interpreter import that loads every owner.
  • The contract's "one object" check skips names owner code rebinds with global (_parent_project_resolver, _host_read_in_flight): their live value is the facade's, so it checks their base shape on the owner's import-time binding and test_a_setter_moved_into_an_owner_rebinds_the_facade_state pins the setter. This fixes an order-dependent identity check: a test that leaves the dashboard's resolver installed (set_parent_project_resolver(...) with no restore), run before the contract test in one process, reddened the old check.
  • test/campaign_facade_inventories/kiro_crew.subagent.json: the facade's frozen inventory (225 base public names, 35 rebound to their owner), checked by test_campaign_facades_base_public_names.py.
  • Determinism: the contract test uses tmp_path, monkeypatch and a bounded subprocess; no clock, sleep, port or order assertion. Passed 5 runs at -n0 and one at -n 3.

Local runs on this head (Python 3.12, -n 3):

  • every test file that imports or patches the subagent family or names subagent.py: 183 files, 14,306 passed, 4 skipped;
  • every test file that names an edited doc or AUTOSDE.yaml, plus every changed test file: 136 files, 16,062 passed, 10 skipped;
  • mypy src/kiro_crew: no issues in 2,335 files; isort, flake8 and black clean on every changed file.
  • scripts/local-gate.py --dry-run selects 1,715 backend and 474 frontend related files, over what one shared host runs, so the two file sets above ran instead; CI runs the full suites.

Manual verification

  • The split is generated by a recipe from the base file, and re-running it reproduces all eight source files and the contract test byte-for-byte.
  • Installed-mode smoke: a wheel built from this head, installed into a scratch venv, imports kiro_crew.subagent and every kiro_crew.subagent_parts module.

Related Issues

Part of #20192

Move audit

move_audit.py --origin src/kiro_crew/subagent.py:

src/kiro_crew/subagent.py: 7095 -> 4697 lines; moved 99.18% (python-ast)
   changed: _read_inactive_file_bytes [FunctionDef] 28 lines
   changed: _read_int_file [FunctionDef] 18 lines

Both changed units are docstring-only: "this module's open" becomes "kiro_crew.subagent's open", because the functions now live in host_memory.py but still read the facade's open, which the sizing tests patch. Everything else in subagent.py that differs from the base is facade glue: the owner imports and re-exports, two binding tuples, the compose call, and two dropped imports nothing reads any more (re, NamedTuple). git diff and git diff --minimal add the same lines in every changed file (38 files; 222 lines in subagent.py).

Upstream changes carried

The split is generated by a recipe from main's one-module subagent.py, so upstream changes to it are carried byte-for-byte:

Composition mechanism

The facade already rebinds subagent_manager coordinator functions with bind_component_globals, but that helper only touches *_impl attributes of coordinator classes and cannot rebind module-level functions or class members, so it is left untouched. The new owners use a package-local compose() in subagent_parts/__init__.py, with the same shape and contract as slack/gateway_runtime.compose and chat_turn (bytecode sweep plus "nothing but the facade imports an owner"); it does not import slack's helper. Reusing that helper is not possible from here: test_slack_gateway_composition_contract.py::test_nothing_but_the_facade_imports_an_owner fails on any module other than slack/gateway.py that imports kiro_crew.slack.gateway_runtime. Folding the per-package copies into one shared helper is tracked in #20421.

No test patches kiro_crew.subagent.provider_last_turn_usage, the one name _RunCreditAccounting.total's field factory reads on run_output's own globals.

An owner that calls os or time imports it as import <module> under TYPE_CHECKING rather than from the facade, because scripts/check_sync_io_in_async.py resolves those modules only from a same-file import; a time.sleep(1) planted in a moved coroutine is flagged.

Logger (L25): moved code keeps the original logger. Owners define no logger and read logger from the facade's globals, so every record still carries kiro_crew.subagent.

Source-reading tests re-pointed

Path or row changes only, assertions unchanged; each re-point was proved by a mutation in the new home that turns the test red:

  • test/test_agent_roster_shared.py (grammar-filter ratchet): reads the facade plus subagent_parts/*.py.
  • test/test_spawn_agent_roster.py (refusal-code and reserved-set ratchets): the same join for the facade.
  • test/test_agent_spec_hardened_reads.py: the spawn_available_agents call-site key moves to kiro_crew/subagent_parts/agent_policy.py.
  • test/test_eval_subagent_deny_notice.py, test/test_spawn_admission_verdict_census.py, test/test_subagent_result_path_spelling.py, test/test_subagent_turn_resilience.py: their scanned file lists add subagent_parts/*.py.
  • test/test_subagent_scale.py (one-draw-site ratchet): its two whole-family checks (os.urandom( once, no uuid4()) read the facade plus subagent_parts/*.py; the _mint_agent_id slice still reads the facade, where that method stays in this PR.

Registries, docs and CI path references

  • src/kiro_crew/security_posture.py NON_EGRESS_REDACTION_MODULES: + subagent_parts/agent_policy.py, subagent_parts/run_output.py (they hold moved redaction helpers).
  • AUTOSDE.yaml: the harness-parity rule's paths add src/kiro_crew/subagent_parts/*.py.
  • .github/docs-lint-baseline.txt: 8 rows deleted by hand for RFC subagent.py:NNN citations rewritten as symbols.
  • .github/file-line-cap-baseline.txt: the subagent.py row is lowered by hand from 6,923 to 4,697 (the second PR deletes it). The re-pointed test_subagent_scale.py (+5 lines) and test_subagent_turn_resilience.py (+1), and security_posture.py's new rows (+4), grow three baselined files a little; the guard reports that, it does not fail.
  • docs/system-specs/modules/subagent.md gains a Composition section: the owner table, the one-namespace rule, and where new code goes.
  • Prose citations that named subagent.py as the home of a moved name now name its owner: code-style.md, crew-mode.md, pipeline-conductor.md, governance.md, learn-cron-dashboard.md, overview.md, six RFCs, the RFC index, a docstring in dashboard/handlers/tasks.py and in test/test_api_tasks.py.
  • No workflow file changes.

Risks

  • subagent_parts joins the agent-sdk capabilities owner census in PR2: test_agent_sdk_capabilities.py's composed-owner row needs at least 13 owner modules, which this package reaches only when the class moves. The moved code holds no harness-identity read today, and the added-line harness-parity gate still covers the new files.

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

@bolichen97
bolichen97 requested review from a team and KiroCrewCaptain as code owners October 14, 2026 17:42
@bolichen97
bolichen97 requested a review from mbriones98 October 14, 2026 17:42
@bolichen97

bolichen97 commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Sensitive change review

Head: 7b86e6f

  • What rule changed: No rule changed. security_posture.NON_EGRESS_REDACTION_MODULES gains two rows, subagent_parts/agent_policy.py and subagent_parts/run_output.py, because redactor call sites moved there verbatim from subagent.py. subagent.py stays the one registered redaction sink of the family; the two owners join its internal partitions (the subagent_manager/* rows) as non-egress modules.
  • Before -> after (what was allowed/blocked, now): Before, the redaction helpers lived in subagent.py; after, the same functions live in the two owners and still run on subagent.py's globals. Nothing newly allowed or blocked: the registry only classifies where redactor calls sit, and the drift guard would fail on an unregistered one.
  • Worst case if wrong (breaks commands / leaks secret / locks user out): A redactor call site would be misclassified as non-egress, so the security posture panel would not count it as an output sink. No command breaks and no secret leaks: the redaction calls themselves are byte-identical (move audit) and still run.
  • Evidence checked (which sandbox result proves it): Not a sandbox change. test/test_security_posture.py (drift guard over every redactor call site) passes on this head, and a mutation that adds an unregistered redact_and_truncate call to a subagent_parts owner turns it red.
  • No regression:
    • Tools still work (which tools/commands were run, result): The subagent family suites (295 test files, 25,914 passed, 12 skipped) cover spawn, run, terminal reports and redacted output on this head.
    • Backward compatible (old config / old data / old callers still work, how checked): Every kiro_crew.subagent name and patch target still resolves to the same object (test_campaign_facades_base_public_names.py, the new composition contract test); no config or data format changes.
    • Existing tests (which suites passed on this head): test_security_posture.py, test_subagent_parts_composition_contract.py, test_campaign_facades_base_public_names.py and the 295-file subagent family set, all green at 7b86e6f.
  • How to undo: Revert this one commit; the two registry rows go with the code they classify.

@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Sensitive Change Review

Sensitive files changed:

  • src/kiro_crew/security_posture.py

  • @bolichen97 posted a complete reasoning template for 822f915.

@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Oct 14, 2026
@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5) — ✅ PASS

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

Design-Verdict: PASS

Before PR 2 moves the class, check every guard that still reads only subagent.py by path (e.g. test_ws_event_scoping_frames.py's _fire_event scan).

[DESIGN-REVIEWED] 822f915

Description read

[DESCRIPTION-READ] 79df93fc35484a60f351e971ddc91f09a625f3ea1bca98b84f11b7e3dcdc3d49

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

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5) — 🟡 CONCERNS

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

First-Principles-Verdict: CONCERNS

subagent_parts.compose copies slack/gateway_runtime.compose line for line, including the host rebinding, and nothing in this PR binds onto SubagentManager.

Not justified as shipped

  • Item 3 — duplicate of src/kiro_crew/slack/gateway_runtime/__init__.py:compose: this is the 10th def compose(namespace in src/kiro_crew (grepped). Its body matches the gateway one line for line; only the docstring differs.
    Subtraction: import an existing compose and delete the ~100-line copy in subagent_parts/__init__.py.
    Clears when: the copy is deleted, or the PR shows why this one must differ.
  • Item 4 — one consumer, generalized: _compose_parts(globals(), SubagentManager, …) passes a host, but SubagentManager's body assigns no owner functions (0 hits). The host parameter, the prefix requalify loop and _requalify do no work here; they serve "the second PR".
    Subtraction: use the two-argument compose(namespace, owners) that six packages already share (for example hook_runtime/__init__.py), and drop host and _requalify.
    Clears when: the host path is removed, or the class methods bound to it land in this PR.

What this change ships

Inventory (6 items) — 4 justified

Intent: shrink subagent.py toward the 2,000-line cap with no change in behaviour. A REFACTOR, not a FIX or an ADDITION.

  1. 152 module-level definitions move into six subagent_parts owners — justified
  2. subagent.py re-exports every moved name — justified
  3. New compose() rebinds owner functions onto the facade's globals — duplicate of slack/gateway_runtime/__init__.py
  4. compose host and qualname-rebinding path — one consumer, generalized
  5. Guards and censuses widened to scan subagent_parts/*.py — justified
  6. Line-cap baseline, docs-lint baseline and spec references updated — justified

[FIRST-PRINCIPLES-REVIEWED] 822f915

Description read

[DESCRIPTION-READ] 5aaff97a2536105a5e7b46b22c37bbde2e893be7ec81101639573d2e53909883

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 commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5) — ⏭️ skipped

Revision 822f91500f4ea9bfdcbc1dac1ef8a0c04a1196f1 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

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review — ✅ no blocking findings

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

Review details

No findings.

[OPUS-REVIEWED] 822f915

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

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

@github-actions

github-actions Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review — ✅ no blocking findings

GPT 6.1 completed its review of 822f91500f4ea9bfdcbc1dac1ef8a0c04a1196f1 and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 822f915

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

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=86751ac9d169 compose() duplicates slack/gateway_runtime compose

Disposition: rebutted (out of goal). The copy is the mechanism this campaign's design ruling for this split requires: a package-local compose with the same shape and contract as chat_turn/gateway_runtime, and it must not import slack's helper, so subagent.py does not depend on the Slack package.
Merging the existing copies into one shared helper changes every composed facade (slack, chat_turn, server_runtime, hooks, ...) and their contract tests; this PR's goal is moving subagent.py's definitions with no behaviour change, and its Not-a-goal excludes changes outside that.
The copy carries its own contract pins (synthetic compose test, bytecode sweep), so a later consolidation can replace it mechanically.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=799604e3d2bf one shared rebinding helper instead of another copy

Disposition: rebutted (out of goal). Same class as the First Principles item: the package-local copy is what the design ruling for this split requires (no import of slack's helper), and consolidating the copies is a change to every composed facade, outside this PR's goal of moving subagent.py's definitions unchanged.
test_subagent_parts_composition_contract.py pins this copy's behaviour (synthetic compose run plus the bytecode sweep), so a later shared helper can replace it with the pins as the check.

@bolichen97

Copy link
Copy Markdown
Contributor Author

Design Review punchline (advisory PASS) — answer:

Yes, subagent_parts/agent_policy.py and subagent_parts/run_output.py belong in NON_EGRESS_REDACTION_MODULES. subagent.py is the one registered redaction sink for this family (_REDACTION_SINKS), and these two owners are internal partitions behind it, the same way the six subagent_manager/* rows above them are: their functions run on subagent.py's globals, and the redacted text they produce leaves only through the facade's event and completion callbacks. They add no transport or audience of their own, and test_subagent_parts_composition_contract.py pins that nothing but subagent.py imports a subagent_parts module. A later owner edit that adds a real egress path would be the same review question as one in a subagent_manager partition today.

@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 14, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=86751ac9d169 compose() duplicates slack/gateway_runtime compose

Disposition: tracked follow-up. Consolidating the facade-package compose() copies (the six on main, gateway_runtime and this subagent_parts copy) into one shared helper is tracked in #20421, which this lane's clear condition names as sufficient.
This PR keeps the package-local copy the design ruling for this split requires, pinned by its own contract tests, so #20421 can replace it mechanically.

mbriones98
mbriones98 previously approved these changes Oct 14, 2026

@mbriones98 mbriones98 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Checks green and readiness passed at 7b86e6f; no behavior change.

@github-actions github-actions Bot added the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Oct 14, 2026
@bolichen97
bolichen97 force-pushed the refactor/linecap-g07-subagent branch from 7b86e6f to 62507b1 Compare October 14, 2026 20:56
@bolichen97

Copy link
Copy Markdown
Contributor Author

Sensitive change review

Head: 62507b1

  • What rule changed: No rule changed. security_posture.NON_EGRESS_REDACTION_MODULES gains two rows, subagent_parts/agent_policy.py and subagent_parts/run_output.py, because redactor call sites moved there verbatim from subagent.py. subagent.py stays the one registered redaction sink of the family; the two owners join its internal partitions (the subagent_manager/* rows) as non-egress modules.
  • Before -> after (what was allowed/blocked, now): Before, the redaction helpers lived in subagent.py; after, the same functions live in the two owners and still run on subagent.py's globals. Nothing newly allowed or blocked: the registry only classifies where redactor calls sit, and the drift guard would fail on an unregistered one.
  • Worst case if wrong (breaks commands / leaks secret / locks user out): A redactor call site would be misclassified as non-egress, so the security posture panel would not count it as an output sink. No command breaks and no secret leaks: the redaction calls themselves are byte-identical (move audit) and still run.
  • Evidence checked (which sandbox result proves it): Not a sandbox change. test/test_security_posture.py (drift guard over every redactor call site) passes on this head, and a mutation that adds an unregistered redact_and_truncate call to a subagent_parts owner turns it red.
  • No regression:
    • Tools still work (which tools/commands were run, result): The subagent family suites (295 test files, 25,914 passed, 12 skipped) cover spawn, run, terminal reports and redacted output on this head.
    • Backward compatible (old config / old data / old callers still work, how checked): Every kiro_crew.subagent name and patch target still resolves to the same object (test_campaign_facades_base_public_names.py, the new composition contract test); no config or data format changes.
    • Existing tests (which suites passed on this head): test_security_posture.py, test_subagent_parts_composition_contract.py, test_campaign_facades_base_public_names.py and the 295-file subagent family set, all green at 62507b1.
  • How to undo: Revert this one commit; the two registry rows go with the code they classify.

@bolichen97

Copy link
Copy Markdown
Contributor Author

Rebased onto main 3572d1c to clear a conflict in the shared rows of test/test_campaign_facades_base_public_names.py (row union with main's new facade rows); no content change beyond lowering this file's line-cap baseline row to its new size. CI re-running.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: passed Eligible automated validation passed for the current revision merge conflict Branch has merge conflicts with its base — author must resolve before merge labels Oct 14, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=0ddffc45b980 compose() duplicates slack/gateway_runtime compose

Disposition: rebutted (out of goal), tracked in #20421. The package-local copy is what the design ruling for this split requires: the same shape and contract as chat_turn/gateway_runtime, and no import of slack's helper, so subagent.py takes no dependency on the Slack package.
Making the copies one shared module changes every composed facade and its contract tests, outside this PR's goal of moving subagent.py's definitions with no behaviour change; #20421 tracks exactly that consolidation, and this copy's own contract pins let it be replaced mechanically.

@bolichen97

bolichen97 commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author
  • span=b271610b423c move compose into one shared helper before the class-body split

Disposition: rebutted (out of goal), tracked in #20421 (one shared compose helper across facade packages). This PR and the class-body split keep the package-local copy the design ruling requires; consolidating changes every composed facade at once, which #20421 does with all eight copies in one place.
test_subagent_parts_composition_contract.py pins this copy's behaviour (synthetic compose run, bytecode sweep), so the two compositions cannot drift silently before then.

@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 14, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author

Rebased onto main 0694e63, conflicts in src/kiro_crew/subagent.py (ported main's #20686 project-scope availableAgents change, hunk for hunk, into the moved subagent_parts/agent_policy.py, and re-exported its new names from the facade), test/test_agent_spec_hardened_reads.py (both SEL labels now under agent_policy.py), test/test_subagent_parts_composition_contract.py (base signatures follow #20686), .github/file-line-cap-baseline.txt (subagent.py row 4,697), docs/request-for-change/rfc-resumable-subagent-sessions.md and test/test_campaign_facades_base_public_names.py (both sides kept) resolved mechanically, tests: the files this PR and #20686 touch plus every test naming parent_spawn_allowlists / spawn_available_agents / subagent_parts (9,647 passed) pass.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: passed Eligible automated validation passed for the current revision merge conflict Branch has merge conflicts with its base — author must resolve before merge labels Oct 15, 2026
@bolichen97
bolichen97 force-pushed the refactor/linecap-g07-subagent branch from 58ceafa to 17702bc Compare October 15, 2026 18:46
@bolichen97

Copy link
Copy Markdown
Contributor Author

Rebased onto main 8da5b41, no new conflicts; fixed the isort order of the two re-exported names my previous rebase added (_scope_spawn_allowlists, _ScopeAllowlists). isort, flake8, black and mypy clean on the touched files; tests test_subagent_parts_composition_contract.py, test_agent_spec_hardened_reads.py, test_campaign_facades_base_public_names.py, test_file_line_cap.py pass.

@github-actions github-actions Bot added 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: checking Automated validation is still running labels Oct 15, 2026
subagent.py is 6,923 lines, over the 2,000-line cap the repository is
adopting. This first step of a two-part split moves its module-level
helpers (spawn and run limits, run output, agent policy, model choice,
host memory, start pricing) into six owners under
kiro_crew.subagent_parts, one responsibility each.

subagent.py stays the facade: it re-exports every moved name, and
subagent_parts.compose rebinds every owner function onto the facade's
globals, so each kiro_crew.subagent.<name> import and patch keeps
reaching the code it reached before. Function bodies move verbatim.
A composition contract test pins the one-namespace sweep, the patch
reach, the base surface and the import graph.
@bolichen97
bolichen97 force-pushed the refactor/linecap-g07-subagent branch from 17702bc to 822f915 Compare October 15, 2026 22:22
@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 15, 2026
@bolichen97

Copy link
Copy Markdown
Contributor Author

This head supersedes the rebases pushed at 58ceafa and 17702bc, which did not come from this PR's author session. It is the split regenerated by its recipe on main c6d6106:

  • Upstream changes carried: fix(subagent): honour project-scope parent availableAgents at spawn gate #20686 changed code this PR moves (project-scope parent availableAgents at the spawn gate). Its ten new helpers and the changed parent_spawn_allowlists / _scan_parent_spawn_allowlists move into agent_policy.py byte-for-byte (move audit: 99.18% moved, only the two docstring units changed); its new hardened-reader label is re-keyed with the old one; its three new public functions are in the facade inventory and the Reader list. fix(subagent): clear an owed expiry report only on a delivery ack #20508 sits in the region this PR keeps in subagent.py and is carried unchanged.
  • The facade inventory is now test/campaign_facade_inventories/kiro_crew.subagent.json (the campaign's per-facade file), replacing this PR's rows in test_campaign_facades_base_public_names.py.
  • The composition contract treats global-rebound owner state (_parent_project_resolver, _host_read_in_flight) as facade-held: a run order with the dashboard's resolver left installed reddened the old identity check.
  • Against 17702bc: same subagent.py, docs and hardened-reader keys; this head keeps the recipe's black-formatted blank lines in agent_policy.py, the contract's BASE shapes for fix(subagent): honour project-scope parent availableAgents at spawn gate #20686's names, the order fix above, and the inventory file.

The line-cap row matches the facade's 4,697 lines. CI re-running.

git range-diff b2c5fbb~1..b2c5fbb HEAD~1..HEAD
1:  b2c5fbb6b5 ! 1:  822f91500f refactor(subagent): compose module-level helpers from subagent_parts
    @@ .github/file-line-cap-baseline.txt
      3892 src/kiro_crew/slack/interactions.py
      2115 src/kiro_crew/snapshot.py
     -6923 src/kiro_crew/subagent.py
    -+4686 src/kiro_crew/subagent.py
    ++4697 src/kiro_crew/subagent.py
      2220 src/kiro_crew/subagent_manager/admission/gate.py
      2464 src/kiro_crew/subagent_manager/admission/taskq_bridge.py
      4774 src/kiro_crew/subagent_manager/run.py
    @@ docs/request-for-change/rfc-resumable-subagent-sessions.md: Record rows use the
     @@ docs/request-for-change/rfc-resumable-subagent-sessions.md: Keeping the kiro session files means touching **four** unlink sites:
      | `AcpSessionHandle._cleanup_transcript` (`acp/session_handle.py:799-814`), via `destroy()` (`:775`) | the session-sharing arm — the default — through `AcpSessionProvider.shutdown` (`acp/session_provider.py:173`) from `subagent_manager/run.py`'s `_teardown_run_session_impl` |
      | `AcpSessionProvider.cleanup_session` (`acp/session_provider.py:180-200`) | `SessionManager._safe_cleanup` |
    - | `AcpProvider.cleanup_session` (`providers/acp.py:1124-1141`) | `SessionManager._safe_cleanup` |
    + | `AcpProvider.cleanup_session` (`providers/acp_lifecycle.py`) | `SessionManager._safe_cleanup` |
     -| `_cleanup_session_files_sync` (`subagent_persistence.py:293`) | tombstone prune (`:280`) and orphan reconcile (`subagent.py:1187-1195`) |
     +| `_cleanup_session_files_sync` (`subagent_persistence.py:293`) | tombstone prune (`:280`) and orphan reconcile (`_reconcile_orphans_impl`) |
      
    @@ src/kiro_crew/subagent.py: from kiro_crew.subagent_manager.monitoring import (
     +    _MAX_AVAILABLE_AGENTS_GLOBS,
     +    _MAX_AVAILABLE_IN_ERROR,
     +    _PARENT_ALLOWLIST_MEMO,
    ++    _PARENT_PROJECT_ALLOWLIST_MEMO,
    ++    _UNRESOLVED_PARENT_WARNED,
    ++    _UNRESOLVED_PARENT_WARNED_MAX,
     +    AGENT_INTERNAL_CODE,
     +    AGENT_NOT_AVAILABLE_CODE,
     +    AGENT_NOT_FOUND_CODE,
    @@ src/kiro_crew/subagent.py: from kiro_crew.subagent_manager.monitoring import (
     +    _available_agents_hint,
     +    _inherited_member_agent,
     +    _internal_agent_refusal,
    ++    _parent_project_resolver,
     +    _parent_template_for_spawn,
     +    _scan_parent_spawn_allowlists,
    ++    _scope_spawn_allowlists,
    ++    _ScopeAllowlists,
    ++    _surface_unresolved_parent_spec,
     +    _validate_agent,
     +    _validate_app_agent_ownership,
     +    _vet_parent_available_agents,
     +    _vet_spawn_governance,
     +    agent_matches_allowlist,
    ++    parent_project_dirs,
     +    parent_spawn_allowlists,
     +    parent_spawn_policy,
    ++    parent_template_allowlists,
    ++    set_parent_project_resolver,
     +    spawn_allowlist,
     +    validate_cwd,
     +    visible_agent_names,
    @@ src/kiro_crew/subagent.py: AGENT_NOT_FOUND_CODE = "agent_not_found"
     -    )
     -
     -
    --def parent_spawn_allowlists(parent_template: str) -> tuple[tuple[str, ...], ...] | None:
    +-def parent_spawn_allowlists(
    +-    parent_template: str,
    +-    project_dirs: Sequence[str | Path] = (),
    +-    *,
    +-    parent_session_key: str = "",
    +-) -> tuple[tuple[str, ...], ...] | None:
     -    """Every ``availableAgents`` list the specs naming *parent_template* declare.
     -
    +-    *project_dirs* are the directories the PARENT session's kiro-cli may be
    +-    running in (:func:`parent_project_dirs`). For each,
    +-    ``<project_dir>/.kiro/agents`` is resolved too, by the same rules and the
    +-    same hardened reader under its own SEL label, and its lists are ADDED to the
    +-    user-level ones: the target must satisfy every list from every scope. kiro-cli lets a project spec shadow a
    +-    user-level one of the same name; the gate does not pick the winner, it
    +-    applies both, so honouring the project scope can only narrow what a parent
    +-    may spawn, never widen it. ``None`` from either scope is ``None``.
    +-
    +-    *parent_session_key* is used only to audit the case this function cannot
    +-    resolve: no project directory is known for the parent and no user-level spec
    +-    names it, so a project-scope declaration may exist that is not honoured
    +-    (:func:`_surface_unresolved_parent_spec`).
    +-
     -    Resolution follows :func:`kiro_crew.agent.agent_spec_path`: a spec whose
     -    DECLARED ``name`` is *parent_template* wins; ``<parent_template>.json`` (or
     -    ``.md``) is read only when no spec declares the name. Two specs declaring
    @@ src/kiro_crew/subagent.py: AGENT_NOT_FOUND_CODE = "agent_not_found"
     -    read, so the event-loop entry points call it through ``asyncio.to_thread``
     -    (see :func:`parent_spawn_policy`) rather than from the gate. A parent living
     -    only in a project's ``.kiro/agents`` is not resolved here (its declaration
    --    is not honoured yet; see the module spec).
    +-    is resolved only when *project_dirs* is given -- see :func:`parent_project_dirs`.
     -    """
     -    # ``match``, not ``fullmatch``: the pattern is anchored, and the roster
     -    # ratchet reserves the ``fullmatch`` spelling for ``visible_agent_names``.
     -    if not parent_template or not _AGENT_NAME_RE.match(parent_template):
     -        return ()
    --    agents_dir = _kiro_agents_dir()
    +-    user_lists, user_found = _scope_spawn_allowlists(
    +-        _kiro_agents_dir(), parent_template, _PARENT_ALLOWLIST_MEMO, "spawn_available_agents"
    +-    )
    +-    project_dirs = tuple(dict.fromkeys(str(d) for d in project_dirs if d))
    +-    if not project_dirs:
    +-        if user_lists is not None and not user_found and parent_session_key:
    +-            _surface_unresolved_parent_spec(parent_template, parent_session_key)
    +-        return user_lists
    +-    if user_lists is None:
    +-        return None
    +-    lists = user_lists
    +-    for directory in project_dirs:
    +-        project_lists, _project_found = _scope_spawn_allowlists(
    +-            project_agents_dir(directory),
    +-            parent_template,
    +-            _PARENT_PROJECT_ALLOWLIST_MEMO,
    +-            "spawn_available_agents_project",
    +-        )
    +-        if project_lists is None:
    +-            return None
    +-        # Every scope applies (tightest-wins): an added list can only refuse more.
    +-        lists = lists + project_lists
    +-    return lists
    +-
    +-
    +-#: ``(allowlists, found)`` for one agents directory: *allowlists* as
    +-#: :func:`parent_spawn_allowlists` answers it for that directory alone, *found*
    +-#: whether any readable spec there resolved the parent's name at all.
    +-_ScopeAllowlists = tuple["tuple[tuple[str, ...], ...] | None", bool]
    +-
    +-
    +-def _scope_spawn_allowlists(
    +-    agents_dir: Path,
    +-    parent_template: str,
    +-    memo: "AgentsDirMemo[_ScopeAllowlists]",
    +-    operation: str,
    +-) -> _ScopeAllowlists:
    +-    """Resolve *parent_template* in one agents directory (user or project scope)."""
     -    # Probe the walk first: a directory that is absent declares nothing
     -    # (nothing could have loaded the parent from it either), while one that
     -    # exists but cannot be scanned -- unreadable, or the path replaced by a
    @@ src/kiro_crew/subagent.py: AGENT_NOT_FOUND_CODE = "agent_not_found"
     -        with os.scandir(agents_dir):
     -            pass
     -    except FileNotFoundError:
    --        return ()
    +-        return (), False
     -    except OSError as exc:
     -        logger.warning("agents directory %s is not scannable (%s); refusing spawn", agents_dir, exc)
    --        return None
    +-        return None, False
     -    try:
    --        return _PARENT_ALLOWLIST_MEMO.get(
    +-        return memo.get(
     -            agents_dir,
     -            parent_template,
    --            lambda: _scan_parent_spawn_allowlists(agents_dir, parent_template),
    +-            lambda: _scan_parent_spawn_allowlists(agents_dir, parent_template, operation),
     -        )
     -    except OSError as exc:  # the directory walk itself failed: an unknown answer
     -        logger.warning("agents directory %s is not scannable (%s); refusing spawn", agents_dir, exc)
    --        return None
    +-        return None, False
    +-
    +-
    +-#: Parent templates already warned about by :func:`_surface_unresolved_parent_spec`
    +-#: in this process, so the log line is said once per name rather than per spawn.
    +-#: Bounded: past the cap nothing more is recorded and the warning keeps firing,
    +-#: which is noisier, never quieter.
    +-_UNRESOLVED_PARENT_WARNED: set[str] = set()
    +-_UNRESOLVED_PARENT_WARNED_MAX = 256
    +-
    +-#: Resolves a CALLING session key to every project directory its kiro-cli may
    +-#: be running in: the live session's bound cwd AND the slot's staged project for
    +-#: a chat (they differ while a project change waits for the next cold start), the
    +-#: run's cwd for a sub-agent. Wired by the gateway (``DashboardState``); unset in
    +-#: a process with no chat slots, where :func:`parent_project_dirs` answers ``()``.
    +-_parent_project_resolver: Callable[[str], "Iterable[str | Path]"] | None = None
    +-
    +-
    +-def set_parent_project_resolver(resolver: Callable[[str], "Iterable[str | Path]"] | None) -> None:
    +-    """Install the gateway's session-key -> project-directories resolver."""
    +-    global _parent_project_resolver
    +-    _parent_project_resolver = resolver
    +-
    +-
    +-def parent_project_dirs(parent_session_key: str) -> tuple[str, ...]:
    +-    """The project directories the parent session may run in, ``()`` when unknown.
    +-
    +-    Only the session's OWN bindings are used (its live runtime's cwd and its
    +-    slot's project, or a sub-agent's cwd), never a guess such as "the one project
    +-    every slot shares". Every directory returned is applied, so a binding that
    +-    is stale can only add restrictions. A resolver that raises is "unknown",
    +-    which keeps today's user-level-only resolution and is audited by
    +-    :func:`_surface_unresolved_parent_spec` when it matters.
    +-    """
    +-    resolver = _parent_project_resolver
    +-    if resolver is None or not parent_session_key:
    +-        return ()
    +-    try:
    +-        values = resolver(parent_session_key)
    +-        return tuple(dict.fromkeys(str(v) for v in (values or ()) if v))
    +-    except Exception:  # noqa: BLE001 - a resolver failure is "unknown", never a crash
    +-        logger.debug("parent project resolver failed for %s", parent_session_key, exc_info=True)
    +-        return ()
    +-
    +-
    +-def _surface_unresolved_parent_spec(parent_template: str, parent_session_key: str) -> None:
    +-    """Say that a parent's ``availableAgents`` may be unhonoured, loudly.
    +-
    +-    Reached when no project directory is known for the parent session and no
    +-    user-level spec names its template: the parent may be a project-scope agent
    +-    whose declaration this gate cannot see. The spawn keeps today's admission
    +-    (there is nothing readable to refuse on), and the gap is logged at WARNING
    +-    once per name and audited to the SEL on every occurrence.
    +-    """
    +-    shown = redact_via_context(parent_template)
    +-    if parent_template not in _UNRESOLVED_PARENT_WARNED:
    +-        if len(_UNRESOLVED_PARENT_WARNED) < _UNRESOLVED_PARENT_WARNED_MAX:
    +-            _UNRESOLVED_PARENT_WARNED.add(parent_template)
    +-        logger.warning(
    +-            "parent agent %r has no user-level spec and the parent session's project "
    +-            "directory is unknown, so a project-scope "
    +-            "toolsSettings.subagent.availableAgents declaration (if any) is not honoured "
    +-            "for this spawn",
    +-            shown,
    +-        )
    +-    try:
    +-        sel().log_tool_invocation(
    +-            session_key=parent_session_key,
    +-            source="subagent",
    +-            tool_name="spawn_run",
    +-            outcome="parent_spec_unresolved",
    +-            metadata={"parent_agent": shown, "scope": "user", "project_dir": "unknown"},
    +-        )
    +-    except Exception:  # noqa: BLE001 - the audit is best-effort; the warning above stands
    +-        logger.debug("SEL audit failed for unresolved parent spec", exc_info=True)
     -
     -
     -#: The gate's answers, one set per agents directory, each pinned to the
    @@ src/kiro_crew/subagent.py: AGENT_NOT_FOUND_CODE = "agent_not_found"
     -#: whenever freshness cannot be proven, and the walk then runs uncached. Its
     -#: own instance, not shared with the KAS projection's or the tool-policy read's:
     -#: the three reads carry different SEL ``operation`` labels.
    --_PARENT_ALLOWLIST_MEMO: AgentsDirMemo[tuple[tuple[str, ...], ...] | None] = AgentsDirMemo()
    +-_PARENT_ALLOWLIST_MEMO: AgentsDirMemo[_ScopeAllowlists] = AgentsDirMemo()
    +-#: The same, for a parent session's ``<project>/.kiro/agents``: its own
    +-#: instance because its reads carry their own SEL ``operation`` label.
    +-_PARENT_PROJECT_ALLOWLIST_MEMO: AgentsDirMemo[_ScopeAllowlists] = AgentsDirMemo()
     -
     -
     -def _scan_parent_spawn_allowlists(
    --    agents_dir: Path, parent_template: str
    --) -> tuple[tuple[str, ...], ...] | None:
    +-    agents_dir: Path, parent_template: str, operation: str = "spawn_available_agents"
    +-) -> _ScopeAllowlists:
     -    """One fresh walk of *agents_dir* for :func:`parent_spawn_allowlists`.
     -
    +-    Answers ``(allowlists, found)``; *found* is whether a readable spec resolved
    +-    the parent's name (by declared ``name`` or filename stem).
    +-
     -    Every spec file goes through the hardened reader under the gate's own SEL
    --    labels, and a file the reader refuses is kept as UNREADABLE rather than
    +-    labels (*operation* tells the user scope from the project scope), and a file the reader refuses is kept as UNREADABLE rather than
     -    folded into "no spec" -- except a markdown file with no opening frontmatter
     -    fence, which is not a spec at all (:func:`plain_markdown_document`) and is
     -    skipped like the AppleDouble sidecar. Propagates ``OSError`` from the
    @@ src/kiro_crew/subagent.py: AGENT_NOT_FOUND_CODE = "agent_not_found"
     -        if path.name.startswith("._"):
     -            # AppleDouble sidecar: rejected by design, not by failure.
     -            continue
    --        data = _read_agent_spec(path, operation="spawn_available_agents", source="subagent")
    +-        # Literal labels at each call, so the reader's label ratchet attributes both.
    +-        if operation == "spawn_available_agents_project":
    +-            data = _read_agent_spec(
    +-                path, operation="spawn_available_agents_project", source="subagent"
    +-            )
    +-        else:
    +-            data = _read_agent_spec(path, operation="spawn_available_agents", source="subagent")
     -        if data is None:
     -            if is_markdown_spec(path) and plain_markdown_document(path):
     -                # No opening frontmatter fence: a README or a shared prompt
    @@ src/kiro_crew/subagent.py: AGENT_NOT_FOUND_CODE = "agent_not_found"
     -                parent_template,
     -                ", ".join(repr(path.name) for path in unreadable),
     -            )
    --            return None
    +-            return None, False
     -        declared = [data for data, path in rows if path.stem == parent_template]
     -    lists = (spawn_allowlist(data) for data in declared)
    --    return tuple(allowlist for allowlist in lists if allowlist is not None)
    +-    return tuple(allowlist for allowlist in lists if allowlist is not None), bool(declared)
     -
     -
     -class ParentRecordUnreadable(RuntimeError):
    @@ src/kiro_crew/subagent.py: AGENT_NOT_FOUND_CODE = "agent_not_found"
     -        template = _parent_template_for_spawn(parent_session_key)
     -    except ParentRecordUnreadable:
     -        return "", None
    --    return template, (parent_spawn_allowlists(template) if template else ())
    +-    return template, parent_template_allowlists(parent_session_key, template)
    +-
    +-
    +-def parent_template_allowlists(
    +-    parent_session_key: str, template: str
    +-) -> tuple[tuple[str, ...], ...] | None:
    +-    """:func:`parent_spawn_allowlists` for *template*, in the parent session's project.
    +-
    +-    The one spelling every gate entry point uses once it holds the parent's
    +-    template, so each resolves the user scope AND the parent session's project
    +-    scope (:func:`parent_project_dirs`) the same way. Blocking: call it off the
    +-    event loop.
    +-    """
    +-    if not template:
    +-        return ()
    +-    return parent_spawn_allowlists(
    +-        template,
    +-        parent_project_dirs(parent_session_key),
    +-        parent_session_key=parent_session_key,
    +-    )
     -
     -
     -def _vet_parent_available_agents(
    @@ src/kiro_crew/subagent.py: AGENT_NOT_FOUND_CODE = "agent_not_found"
     -    """
     -    try:
     -        from kiro_crew.config.loader import KiroCrewConfig
    --
    + 
     -        cfg = cfg if cfg is not None else KiroCrewConfig.load()
     -        val = cfg.agent.role_efforts.get("subagent", "")
     -        return val if isinstance(val, str) else ""
    @@ src/kiro_crew/subagent.py: AGENT_NOT_FOUND_CODE = "agent_not_found"
     -        return float(agent_cfg.spawn_min_memory_gb), max(0.0, float(agent_cfg.subagent_cost_gb))
     -    except Exception:
     -        return DEFAULT_SPAWN_MIN_MEMORY_GB, DEFAULT_SUBAGENT_COST_GB
    - 
    +-
     -
     -def _host_memory_reading(min_gb: float) -> tuple[float, str]:
     -    """The floor's host reading and its cause, on whichever thread calls it.
    @@ src/kiro_crew/subagent.py: AGENT_NOT_FOUND_CODE = "agent_not_found"
     +    math,
     +    model_supports_effort,
     +    plain_markdown_document,
    ++    project_agents_dir,
     +    provider_last_turn_usage,
     +    read_cap_costs,
     +    read_session_execution,
    @@ src/kiro_crew/subagent_parts/agent_policy.py (new)
     +        _AGENT_NAME_RE,
     +        KIRO_CLI_BUILTIN_AGENTS,
     +        Any,
    ++        Callable,
     +        Container,
     +        Iterable,
     +        Mapping,
     +        Path,
    ++        Sequence,
     +        _kiro_agents_dir,
     +        _read_agent_spec,
     +        cached_project_agent_names,
    @@ src/kiro_crew/subagent_parts/agent_policy.py (new)
     +        list_agents,
     +        logger,
     +        plain_markdown_document,
    ++        project_agents_dir,
     +        read_session_execution,
     +        readonly_base_name,
     +        redact_via_context,
    ++        sel,
     +    )
     +
     +
    @@ src/kiro_crew/subagent_parts/agent_policy.py (new)
     +    )
     +
     +
    -+def parent_spawn_allowlists(parent_template: str) -> tuple[tuple[str, ...], ...] | None:
    ++def parent_spawn_allowlists(
    ++    parent_template: str,
    ++    project_dirs: Sequence[str | Path] = (),
    ++    *,
    ++    parent_session_key: str = "",
    ++) -> tuple[tuple[str, ...], ...] | None:
     +    """Every ``availableAgents`` list the specs naming *parent_template* declare.
     +
    ++    *project_dirs* are the directories the PARENT session's kiro-cli may be
    ++    running in (:func:`parent_project_dirs`). For each,
    ++    ``<project_dir>/.kiro/agents`` is resolved too, by the same rules and the
    ++    same hardened reader under its own SEL label, and its lists are ADDED to the
    ++    user-level ones: the target must satisfy every list from every scope. kiro-cli lets a project spec shadow a
    ++    user-level one of the same name; the gate does not pick the winner, it
    ++    applies both, so honouring the project scope can only narrow what a parent
    ++    may spawn, never widen it. ``None`` from either scope is ``None``.
    ++
    ++    *parent_session_key* is used only to audit the case this function cannot
    ++    resolve: no project directory is known for the parent and no user-level spec
    ++    names it, so a project-scope declaration may exist that is not honoured
    ++    (:func:`_surface_unresolved_parent_spec`).
    ++
     +    Resolution follows :func:`kiro_crew.agent.agent_spec_path`: a spec whose
     +    DECLARED ``name`` is *parent_template* wins; ``<parent_template>.json`` (or
     +    ``.md``) is read only when no spec declares the name. Two specs declaring
    @@ src/kiro_crew/subagent_parts/agent_policy.py (new)
     +    read, so the event-loop entry points call it through ``asyncio.to_thread``
     +    (see :func:`parent_spawn_policy`) rather than from the gate. A parent living
     +    only in a project's ``.kiro/agents`` is not resolved here (its declaration
    -+    is not honoured yet; see the module spec).
    ++    is resolved only when *project_dirs* is given -- see :func:`parent_project_dirs`.
     +    """
     +    # ``match``, not ``fullmatch``: the pattern is anchored, and the roster
     +    # ratchet reserves the ``fullmatch`` spelling for ``visible_agent_names``.
     +    if not parent_template or not _AGENT_NAME_RE.match(parent_template):
     +        return ()
    -+    agents_dir = _kiro_agents_dir()
    ++    user_lists, user_found = _scope_spawn_allowlists(
    ++        _kiro_agents_dir(), parent_template, _PARENT_ALLOWLIST_MEMO, "spawn_available_agents"
    ++    )
    ++    project_dirs = tuple(dict.fromkeys(str(d) for d in project_dirs if d))
    ++    if not project_dirs:
    ++        if user_lists is not None and not user_found and parent_session_key:
    ++            _surface_unresolved_parent_spec(parent_template, parent_session_key)
    ++        return user_lists
    ++    if user_lists is None:
    ++        return None
    ++    lists = user_lists
    ++    for directory in project_dirs:
    ++        project_lists, _project_found = _scope_spawn_allowlists(
    ++            project_agents_dir(directory),
    ++            parent_template,
    ++            _PARENT_PROJECT_ALLOWLIST_MEMO,
    ++            "spawn_available_agents_project",
    ++        )
    ++        if project_lists is None:
    ++            return None
    ++        # Every scope applies (tightest-wins): an added list can only refuse more.
    ++        lists = lists + project_lists
    ++    return lists
    ++
    ++
    ++#: ``(allowlists, found)`` for one agents directory: *allowlists* as
    ++#: :func:`parent_spawn_allowlists` answers it for that directory alone, *found*
    ++#: whether any readable spec there resolved the parent's name at all.
    ++_ScopeAllowlists = tuple["tuple[tuple[str, ...], ...] | None", bool]
    ++
    ++
    ++def _scope_spawn_allowlists(
    ++    agents_dir: Path,
    ++    parent_template: str,
    ++    memo: "AgentsDirMemo[_ScopeAllowlists]",
    ++    operation: str,
    ++) -> _ScopeAllowlists:
    ++    """Resolve *parent_template* in one agents directory (user or project scope)."""
     +    # Probe the walk first: a directory that is absent declares nothing
     +    # (nothing could have loaded the parent from it either), while one that
     +    # exists but cannot be scanned -- unreadable, or the path replaced by a
    @@ src/kiro_crew/subagent_parts/agent_policy.py (new)
     +        with os.scandir(agents_dir):
     +            pass
     +    except FileNotFoundError:
    -+        return ()
    ++        return (), False
     +    except OSError as exc:
     +        logger.warning("agents directory %s is not scannable (%s); refusing spawn", agents_dir, exc)
    -+        return None
    ++        return None, False
     +    try:
    -+        return _PARENT_ALLOWLIST_MEMO.get(
    ++        return memo.get(
     +            agents_dir,
     +            parent_template,
    -+            lambda: _scan_parent_spawn_allowlists(agents_dir, parent_template),
    ++            lambda: _scan_parent_spawn_allowlists(agents_dir, parent_template, operation),
     +        )
     +    except OSError as exc:  # the directory walk itself failed: an unknown answer
     +        logger.warning("agents directory %s is not scannable (%s); refusing spawn", agents_dir, exc)
    -+        return None
    ++        return None, False
    ++
    ++
    ++#: Parent templates already warned about by :func:`_surface_unresolved_parent_spec`
    ++#: in this process, so the log line is said once per name rather than per spawn.
    ++#: Bounded: past the cap nothing more is recorded and the warning keeps firing,
    ++#: which is noisier, never quieter.
    ++_UNRESOLVED_PARENT_WARNED: set[str] = set()
    ++
    ++
    ++_UNRESOLVED_PARENT_WARNED_MAX = 256
    ++
    ++
    ++#: Resolves a CALLING session key to every project directory its kiro-cli may
    ++#: be running in: the live session's bound cwd AND the slot's staged project for
    ++#: a chat (they differ while a project change waits for the next cold start), the
    ++#: run's cwd for a sub-agent. Wired by the gateway (``DashboardState``); unset in
    ++#: a process with no chat slots, where :func:`parent_project_dirs` answers ``()``.
    ++_parent_project_resolver: Callable[[str], "Iterable[str | Path]"] | None = None
    ++
    ++
    ++def set_parent_project_resolver(resolver: Callable[[str], "Iterable[str | Path]"] | None) -> None:
    ++    """Install the gateway's session-key -> project-directories resolver."""
    ++    global _parent_project_resolver
    ++    _parent_project_resolver = resolver
    ++
    ++
    ++def parent_project_dirs(parent_session_key: str) -> tuple[str, ...]:
    ++    """The project directories the parent session may run in, ``()`` when unknown.
    ++
    ++    Only the session's OWN bindings are used (its live runtime's cwd and its
    ++    slot's project, or a sub-agent's cwd), never a guess such as "the one project
    ++    every slot shares". Every directory returned is applied, so a binding that
    ++    is stale can only add restrictions. A resolver that raises is "unknown",
    ++    which keeps today's user-level-only resolution and is audited by
    ++    :func:`_surface_unresolved_parent_spec` when it matters.
    ++    """
    ++    resolver = _parent_project_resolver
    ++    if resolver is None or not parent_session_key:
    ++        return ()
    ++    try:
    ++        values = resolver(parent_session_key)
    ++        return tuple(dict.fromkeys(str(v) for v in (values or ()) if v))
    ++    except Exception:  # noqa: BLE001 - a resolver failure is "unknown", never a crash
    ++        logger.debug("parent project resolver failed for %s", parent_session_key, exc_info=True)
    ++        return ()
    ++
    ++
    ++def _surface_unresolved_parent_spec(parent_template: str, parent_session_key: str) -> None:
    ++    """Say that a parent's ``availableAgents`` may be unhonoured, loudly.
    ++
    ++    Reached when no project directory is known for the parent session and no
    ++    user-level spec names its template: the parent may be a project-scope agent
    ++    whose declaration this gate cannot see. The spawn keeps today's admission
    ++    (there is nothing readable to refuse on), and the gap is logged at WARNING
    ++    once per name and audited to the SEL on every occurrence.
    ++    """
    ++    shown = redact_via_context(parent_template)
    ++    if parent_template not in _UNRESOLVED_PARENT_WARNED:
    ++        if len(_UNRESOLVED_PARENT_WARNED) < _UNRESOLVED_PARENT_WARNED_MAX:
    ++            _UNRESOLVED_PARENT_WARNED.add(parent_template)
    ++        logger.warning(
    ++            "parent agent %r has no user-level spec and the parent session's project "
    ++            "directory is unknown, so a project-scope "
    ++            "toolsSettings.subagent.availableAgents declaration (if any) is not honoured "
    ++            "for this spawn",
    ++            shown,
    ++        )
    ++    try:
    ++        sel().log_tool_invocation(
    ++            session_key=parent_session_key,
    ++            source="subagent",
    ++            tool_name="spawn_run",
    ++            outcome="parent_spec_unresolved",
    ++            metadata={"parent_agent": shown, "scope": "user", "project_dir": "unknown"},
    ++        )
    ++    except Exception:  # noqa: BLE001 - the audit is best-effort; the warning above stands
    ++        logger.debug("SEL audit failed for unresolved parent spec", exc_info=True)
     +
     +
     +#: The gate's answers, one set per agents directory, each pinned to the
    @@ src/kiro_crew/subagent_parts/agent_policy.py (new)
     +#: whenever freshness cannot be proven, and the walk then runs uncached. Its
     +#: own instance, not shared with the KAS projection's or the tool-policy read's:
     +#: the three reads carry different SEL ``operation`` labels.
    -+_PARENT_ALLOWLIST_MEMO: AgentsDirMemo[tuple[tuple[str, ...], ...] | None] = AgentsDirMemo()
    ++_PARENT_ALLOWLIST_MEMO: AgentsDirMemo[_ScopeAllowlists] = AgentsDirMemo()
    ++
    ++
    ++#: The same, for a parent session's ``<project>/.kiro/agents``: its own
    ++#: instance because its reads carry their own SEL ``operation`` label.
    ++_PARENT_PROJECT_ALLOWLIST_MEMO: AgentsDirMemo[_ScopeAllowlists] = AgentsDirMemo()
     +
     +
     +def _scan_parent_spawn_allowlists(
    -+    agents_dir: Path, parent_template: str
    -+) -> tuple[tuple[str, ...], ...] | None:
    ++    agents_dir: Path, parent_template: str, operation: str = "spawn_available_agents"
    ++) -> _ScopeAllowlists:
     +    """One fresh walk of *agents_dir* for :func:`parent_spawn_allowlists`.
     +
    ++    Answers ``(allowlists, found)``; *found* is whether a readable spec resolved
    ++    the parent's name (by declared ``name`` or filename stem).
    ++
     +    Every spec file goes through the hardened reader under the gate's own SEL
    -+    labels, and a file the reader refuses is kept as UNREADABLE rather than
    ++    labels (*operation* tells the user scope from the project scope), and a file the reader refuses is kept as UNREADABLE rather than
     +    folded into "no spec" -- except a markdown file with no opening frontmatter
     +    fence, which is not a spec at all (:func:`plain_markdown_document`) and is
     +    skipped like the AppleDouble sidecar. Propagates ``OSError`` from the
    @@ src/kiro_crew/subagent_parts/agent_policy.py (new)
     +        if path.name.startswith("._"):
     +            # AppleDouble sidecar: rejected by design, not by failure.
     +            continue
    -+        data = _read_agent_spec(path, operation="spawn_available_agents", source="subagent")
    ++        # Literal labels at each call, so the reader's label ratchet attributes both.
    ++        if operation == "spawn_available_agents_project":
    ++            data = _read_agent_spec(
    ++                path, operation="spawn_available_agents_project", source="subagent"
    ++            )
    ++        else:
    ++            data = _read_agent_spec(path, operation="spawn_available_agents", source="subagent")
     +        if data is None:
     +            if is_markdown_spec(path) and plain_markdown_document(path):
     +                # No opening frontmatter fence: a README or a shared prompt
    @@ src/kiro_crew/subagent_parts/agent_policy.py (new)
     +                parent_template,
     +                ", ".join(repr(path.name) for path in unreadable),
     +            )
    -+            return None
    ++            return None, False
     +        declared = [data for data, path in rows if path.stem == parent_template]
     +    lists = (spawn_allowlist(data) for data in declared)
    -+    return tuple(allowlist for allowlist in lists if allowlist is not None)
    ++    return tuple(allowlist for allowlist in lists if allowlist is not None), bool(declared)
     +
     +
     +class ParentRecordUnreadable(RuntimeError):
    @@ src/kiro_crew/subagent_parts/agent_policy.py (new)
     +        template = _parent_template_for_spawn(parent_session_key)
     +    except ParentRecordUnreadable:
     +        return "", None
    -+    return template, (parent_spawn_allowlists(template) if template else ())
    ++    return template, parent_template_allowlists(parent_session_key, template)
    ++
    ++
    ++def parent_template_allowlists(
    ++    parent_session_key: str, template: str
    ++) -> tuple[tuple[str, ...], ...] | None:
    ++    """:func:`parent_spawn_allowlists` for *template*, in the parent session's project.
    ++
    ++    The one spelling every gate entry point uses once it holds the parent's
    ++    template, so each resolves the user scope AND the parent session's project
    ++    scope (:func:`parent_project_dirs`) the same way. Blocking: call it off the
    ++    event loop.
    ++    """
    ++    if not template:
    ++        return ()
    ++    return parent_spawn_allowlists(
    ++        template,
    ++        parent_project_dirs(parent_session_key),
    ++        parent_session_key=parent_session_key,
    ++    )
     +
     +
     +def _vet_parent_available_agents(
    @@ src/kiro_crew/subagent_parts/start_pricing.py (new)
     +        return agent
     +    return str(getattr(execution, "template_id", "") or "")
     
    + ## test/campaign_facade_inventories/kiro_crew.subagent.json (new) ##
    +@@
    ++{
    ++ "base_public_names": [
    ++  "AGENT_INTERNAL_CODE",
    ++  "AGENT_NOT_AVAILABLE_CODE",
    ++  "AGENT_NOT_FOUND_CODE",
    ++  "AcpSessionProvider",
    ++  "AgentCheck",
    ++  "AgentConfig",
    ++  "AgentsDirMemo",
    ++  "AnnounceCallback",
    ++  "COMPLETION_KEEP_DEFAULT_CHARS",
    ++  "CONTEXT_GROUP_LESSONS",
    ++  "CONTEXT_GROUP_MEMORY",
    ++  "CONTEXT_GROUP_PROJECT",
    ++  "CancellationCoordinator",
    ++  "ClaimPoint",
    ++  "ClaudeCodeProvider",
    ++  "ContextBuilder",
    ++  "ContinuationCoordinator",
    ++  "DEFAULT_MODEL",
    ++  "DEFAULT_SPAWN_MIN_MEMORY_GB",
    ++  "DEFAULT_SUBAGENT_COST_GB",
    ++  "DEFAULT_SUBAGENT_MAX_TURNS",
    ++  "DEFAULT_SUBAGENT_QUEUE_MAX_WAIT_SECS",
    ++  "DEFERRED_QUEUED_REASONS",
    ++  "DELIVERY_ROUTING_FIELDS",
    ++  "DELIVERY_ROUTING_MODULES",
    ++  "DENY_CAUSE_APPROVAL_UNDELIVERABLE",
    ++  "DENY_CAUSE_HOOK_ERROR",
    ++  "DIGEST_HOLD_SECS",
    ++  "DISMISSAL_FAILED",
    ++  "EVENT_AGENT_SWITCHED",
    ++  "EVENT_COMPLETE",
    ++  "EVENT_PERMISSION_REQUEST",
    ++  "EVENT_TEXT_CHUNK",
    ++  "EVENT_TOOL_CALL",
    ++  "EVENT_TOOL_RESULT",
    ++  "FALLBACK_CANDIDATE_ATTEMPTS",
    ++  "FALLBACK_STORY_ATTR",
    ++  "FallbackState",
    ++  "HOOK_EVENT_POST_TOOL_USE",
    ++  "INITIALIZE_TIMEOUT_SECS",
    ++  "INJECTION_TIMEOUT",
    ++  "InFlightToolTracker",
    ++  "KIRO_CLI_BUILTIN_AGENTS",
    ++  "KiroCrewConfig",
    ++  "LLMEvent",
    ++  "LivenessOracle",
    ++  "MAX_ERROR_DETAIL_LEN",
    ++  "MEMORY_CAUSE_CGROUP_USAGE_UNREADABLE",
    ++  "MEMORY_CAUSE_READ_UNANSWERED",
    ++  "MEMORY_PRESSURE_DETAIL",
    ++  "MEMORY_PRESSURE_NEVER_STARTED",
    ++  "MEMORY_PRESSURE_RECHECK_SECS",
    ++  "MemoryReadPoint",
    ++  "NOT_DELIVERY_STATE",
    ++  "ORPHAN_NOTICE_OWED",
    ++  "OUTCOME_FAILED",
    ++  "OUTCOME_INTERRUPTED",
    ++  "OUTCOME_OK",
    ++  "OrphanStallMonitor",
    ++  "PARKS_WHEN_SET",
    ++  "PARKS_WHEN_UNSET",
    ++  "PROVIDER_CLAUDE_CODE",
    ++  "PROVIDER_LABEL_CLAUDE",
    ++  "PROVIDER_LABEL_DEFAULT",
    ++  "ParentRecordUnreadable",
    ++  "ParentSpawnPolicy",
    ++  "PreparedSpawn",
    ++  "ProcessHandle",
    ++  "PublishedQueueDepths",
    ++  "QUEUED_REASON_CONCURRENCY_LIMIT",
    ++  "QUEUED_REASON_LOW_MEMORY",
    ++  "QUEUED_REASON_MEMORY_PRESSURE",
    ++  "QUEUED_WAIT_EXPIRED_TEXT",
    ++  "RunEventCoordinator",
    ++  "SEL_MEMORY_PRESSURE_NEVER_STARTED",
    ++  "SESSION_NOT_FOUND_GIVE_UP_TEXT",
    ++  "SESSION_NOT_FOUND_NOT_REPLAYED_TEXT",
    ++  "SESSION_START_TIMEOUT_MIN",
    ++  "STOP_CLASS_CANCELLED",
    ++  "STOP_CLASS_FAILED",
    ++  "STOP_CLASS_SUCCEEDED",
    ++  "STOP_RECOVERY_MAX_RETRIES",
    ++  "STUB_MODULE",
    ++  "SUBAGENT_COMPLETION_PREFIX",
    ++  "SUBAGENT_TIMEOUT_SECS",
    ++  "SUCCESSOR_PENDING",
    ++  "SUCCESSOR_UNKNOWN",
    ++  "SessionManager",
    ++  "SpawnAdmissionCoordinator",
    ++  "SpawnApprovalCallback",
    ++  "SpawnApprovalUnreachable",
    ++  "Stats",
    ++  "SubagentDelivery",
    ++  "SubagentEventCallback",
    ++  "SubagentInfo",
    ++  "SubagentManager",
    ++  "TERMINAL_TOOL_STATUSES",
    ++  "TRANSIENT_RETRIES",
    ++  "TerminalCoordinator",
    ++  "ToolApprovalCallback",
    ++  "ToolCallState",
    ++  "UNADVERTISED_AGENTS",
    ++  "VERDICT_DEAD",
    ++  "VERDICT_STUCK_INPUT",
    ++  "VERDICT_UNKNOWN",
    ++  "VERDICT_WORKING",
    ++  "WaveDigestCoordinator",
    ++  "acp_error_is_session_not_found",
    ++  "acp_error_is_transient",
    ++  "add_handle",
    ++  "advance_fallback_candidate",
    ++  "agent_dir_for_display",
    ++  "agent_matches_allowlist",
    ++  "annotate_model_fallback",
    ++  "append_cost_sample",
    ++  "append_fallback_story",
    ++  "apply_completion_keep",
    ++  "bind_component_globals",
    ++  "boottime_now",
    ++  "cached_project_agent_names",
    ++  "cached_session_start_concurrency",
    ++  "cap_buckets",
    ++  "capabilities_of",
    ++  "check_memory_available",
    ++  "child_process_helpers",
    ++  "classify_stop_reason",
    ++  "clear_leaked_process",
    ++  "clear_tombstone",
    ++  "compact_cost_log",
    ++  "compute_max_subagents",
    ++  "compute_memory_sized_parallel_cap",
    ++  "configured_fallback_chain",
    ++  "consult_offloaded",
    ++  "copy_component_docs",
    ++  "create_agent_folder",
    ++  "data_home",
    ++  "delivery_is_parked",
    ++  "effort_applied_note",
    ++  "effort_drop_reason",
    ++  "effort_pending_note",
    ++  "effort_settings_key",
    ++  "ending_fence",
    ++  "evict_completed_agents",
    ++  "extract_options",
    ++  "failure_name",
    ++  "fire_tool_hooks",
    ++  "format_subagent_usage",
    ++  "has_dashboard_surface",
    ++  "hook_gate_kwargs",
    ++  "invalidate_stale_kas_session",
    ++  "is_internal_agent_spec",
    ++  "is_markdown_spec",
    ++  "is_registered_agent_name",
    ++  "is_runtime_death",
    ++  "iter_agent_spec_files",
    ++  "join_failures",
    ++  "kill_each",
    ++  "kill_set",
    ++  "kill_verified_process",
    ++  "learned_settled_for",
    ++  "list_agents",
    ++  "list_leaked_processes",
    ++  "list_orphans",
    ++  "live",
    ++  "logger",
    ++  "maintenance_executor",
    ++  "mark_delivered",
    ++  "model_supports_effort",
    ++  "on_event_loop",
    ++  "orphan_carried_fields",
    ++  "orphan_resume_hint",
    ++  "parent_project_dirs",
    ++  "parent_spawn_allowlists",
    ++  "parent_spawn_policy",
    ++  "parent_template_allowlists",
    ++  "plain_markdown_document",
    ++  "platform_compat",
    ++  "pop_memory_check_cause",
    ++  "pressure_level_held",
    ++  "process_handle_of",
    ++  "process_survived_async",
    ++  "project_agents_dir",
    ++  "provider_fallback_active",
    ++  "provider_last_turn_usage",
    ++  "prune_stale_tombstones",
    ++  "read_cap_costs",
    ++  "read_learned_costs_checked",
    ++  "read_memory_pressure_level",
    ++  "read_session_execution",
    ++  "read_state",
    ++  "read_tombstone",
    ++  "readonly_base_name",
    ++  "record_panel_dismissal_outcome",
    ++  "record_slow_command",
    ++  "redact_and_truncate",
    ++  "redact_credentials",
    ++  "redact_exfiltration_urls",
    ++  "redact_via_context",
    ++  "refresh_live_process_tree",
    ++  "refuse_stale_switch",
    ++  "replace_stale_shared_session",
    ++  "reproject_claimed_session",
    ++  "resolve_max_subagents",
    ++  "result_is_whole",
    ++  "run_in_embed_pool",
    ++  "sel",
    ++  "set_parent_project_resolver",
    ++  "settle_delivered_batch",
    ++  "single_completion_meta",
    ++  "spawn_allowlist",
    ++  "spawn_in_flight",
    ++  "subagent_count_ceiling",
    ++  "subprocess_executor",
    ++  "teardown_capture",
    ++  "tombstone_recovery_action",
    ++  "transient_retry_delay",
    ++  "turn_spec_hooks",
    ++  "update_state",
    ++  "validate_cwd",
    ++  "visible_agent_names",
    ++  "window_for_provider_client",
    ++  "with_kill_failure",
    ++  "write_finished_result",
    ++  "write_result_chunk",
    ++  "write_tombstone"
    ++ ],
    ++ "note": "G07 split of subagent.py: module-level helpers moved into kiro_crew.subagent_parts owners; subagent.py re-exports each, and subagent_parts.compose runs them on its globals.",
    ++ "rebound": {
    ++  "AGENT_INTERNAL_CODE": "kiro_crew.subagent_parts.agent_policy",
    ++  "AGENT_NOT_AVAILABLE_CODE": "kiro_crew.subagent_parts.agent_policy",
    ++  "AGENT_NOT_FOUND_CODE": "kiro_crew.subagent_parts.agent_policy",
    ++  "AgentCheck": "kiro_crew.subagent_parts.agent_policy",
    ++  "DIGEST_HOLD_SECS": "kiro_crew.subagent_parts.run_limits",
    ++  "INJECTION_TIMEOUT": "kiro_crew.subagent_parts.run_limits",
    ++  "MEMORY_CAUSE_CGROUP_USAGE_UNREADABLE": "kiro_crew.subagent_parts.host_memory",
    ++  "MEMORY_CAUSE_READ_UNANSWERED": "kiro_crew.subagent_parts.host_memory",
    ++  "ORPHAN_NOTICE_OWED": "kiro_crew.subagent_parts.run_output",
    ++  "ParentRecordUnreadable": "kiro_crew.subagent_parts.agent_policy",
    ++  "ParentSpawnPolicy": "kiro_crew.subagent_parts.agent_policy",
    ++  "SEL_MEMORY_PRESSURE_NEVER_STARTED": "kiro_crew.subagent_parts.run_limits",
    ++  "SUCCESSOR_PENDING": "kiro_crew.subagent_parts.run_limits",
    ++  "SUCCESSOR_UNKNOWN": "kiro_crew.subagent_parts.run_limits",
    ++  "SubagentDelivery": "kiro_crew.subagent_parts.run_output",
    ++  "UNADVERTISED_AGENTS": "kiro_crew.subagent_parts.agent_policy",
    ++  "agent_matches_allowlist": "kiro_crew.subagent_parts.agent_policy",
    ++  "check_memory_available": "kiro_crew.subagent_parts.host_memory",
    ++  "compute_max_subagents": "kiro_crew.subagent_parts.host_memory",
    ++  "compute_memory_sized_parallel_cap": "kiro_crew.subagent_parts.host_memory",
    ++  "effort_applied_note": "kiro_crew.subagent_parts.model_choice",
    ++  "effort_drop_reason": "kiro_crew.subagent_parts.model_choice",
    ++  "effort_pending_note": "kiro_crew.subagent_parts.model_choice",
    ++  "format_subagent_usage": "kiro_crew.subagent_parts.run_output",
    ++  "parent_project_dirs": "kiro_crew.subagent_parts.agent_policy",
    ++  "parent_spawn_allowlists": "kiro_crew.subagent_parts.agent_policy",
    ++  "parent_spawn_policy": "kiro_crew.subagent_parts.agent_policy",
    ++  "parent_template_allowlists": "kiro_crew.subagent_parts.agent_policy",
    ++  "pop_memory_check_cause": "kiro_crew.subagent_parts.host_memory",
    ++  "resolve_max_subagents": "kiro_crew.subagent_parts.host_memory",
    ++  "set_parent_project_resolver": "kiro_crew.subagent_parts.agent_policy",
    ++  "spawn_allowlist": "kiro_crew.subagent_parts.agent_policy",
    ++  "subagent_count_ceiling": "kiro_crew.subagent_parts.host_memory",
    ++  "validate_cwd": "kiro_crew.subagent_parts.agent_policy",
    ++  "visible_agent_names": "kiro_crew.subagent_parts.agent_policy"
    ++ }
    ++}
    +
      ## test/test_agent_roster_shared.py ##
     @@ test/test_agent_roster_shared.py: class TestNoSurfaceReimplementsThePipeline:
          tests in ``test_spawn_agent_roster``."""
    @@ test/test_agent_roster_shared.py: class TestNoSurfaceReimplementsThePipeline:
     
      ## test/test_agent_spec_hardened_reads.py ##
     @@ test/test_agent_spec_hardened_reads.py: _EXPECTED_CALL_SITE_LABELS: dict[str, list[tuple[str, str]]] = {
    -     # ``toolsSettings.subagent.availableAgents`` allowlist, and keeps a file the
          # reader refuses as unreadable (refuse) rather than as "no spec"; a denial
    -     # there belongs to the sub-agent surface that asked to spawn.
    --    "kiro_crew/subagent.py": [("spawn_available_agents", "subagent")],
    -+    "kiro_crew/subagent_parts/agent_policy.py": [("spawn_available_agents", "subagent")],
    -     # `list_apps` confirms a contributed command's agent was actually registered by
    -     # reading the app's materialized `<app>--<agent>.json` -- a user-writable dir, so
    -     # it goes through the hardened reader; a denial belongs to the app listing.
    +     # there belongs to the sub-agent surface that asked to spawn. The second
    +     # label is the same walk over the parent session's ``<project>/.kiro/agents``.
    +-    "kiro_crew/subagent.py": [
    ++    "kiro_crew/subagent_parts/agent_policy.py": [
    +         ("spawn_available_agents", "subagent"),
    +         ("spawn_available_agents_project", "subagent"),
    +     ],
     
      ## test/test_api_tasks.py ##
     @@ test/test_api_tasks.py: def test_redaction_runs_exfil_before_credentials() -> None:
    @@ test/test_api_tasks.py: def test_redaction_runs_exfil_before_credentials() -> No
          """
          scrubbed = tasks_mod._scrub_prose(_EXFIL_URL)
     
    - ## test/test_campaign_facades_base_public_names.py ##
    -@@ test/test_campaign_facades_base_public_names.py: _BASE_PUBLIC_NAMES: dict[str, frozenset[str]] = {
    -         voice_runtime_workspace_conflict warm_backend wrap_argv wrap_argv_async
    -         wrapped_by_crew_sandbox
    -         """.split()),
    -+    "kiro_crew.subagent": frozenset("""
    -+        AGENT_INTERNAL_CODE AGENT_NOT_AVAILABLE_CODE AGENT_NOT_FOUND_CODE
    -+        AcpSessionProvider AgentCheck AgentConfig AgentsDirMemo AnnounceCallback
    -+        COMPLETION_KEEP_DEFAULT_CHARS CONTEXT_GROUP_LESSONS CONTEXT_GROUP_MEMORY
    -+        CONTEXT_GROUP_PROJECT CancellationCoordinator ClaimPoint ClaudeCodeProvider
    -+        ContextBuilder ContinuationCoordinator DEFAULT_MODEL DEFAULT_SPAWN_MIN_MEMORY_GB
    -+        DEFAULT_SUBAGENT_COST_GB DEFAULT_SUBAGENT_MAX_TURNS
    -+        DEFAULT_SUBAGENT_QUEUE_MAX_WAIT_SECS DEFERRED_QUEUED_REASONS
    -+        DELIVERY_ROUTING_FIELDS DELIVERY_ROUTING_MODULES
    -+        DENY_CAUSE_APPROVAL_UNDELIVERABLE DENY_CAUSE_HOOK_ERROR DIGEST_HOLD_SECS
    -+        DISMISSAL_FAILED EVENT_AGENT_SWITCHED EVENT_COMPLETE EVENT_PERMISSION_REQUEST
    -+        EVENT_TEXT_CHUNK EVENT_TOOL_CALL EVENT_TOOL_RESULT FALLBACK_CANDIDATE_ATTEMPTS
    -+        FALLBACK_STORY_ATTR FallbackState HOOK_EVENT_POST_TOOL_USE
    -+        INITIALIZE_TIMEOUT_SECS INJECTION_TIMEOUT InFlightToolTracker
    -+        KIRO_CLI_BUILTIN_AGENTS KiroCrewConfig LLMEvent LivenessOracle
    -+        MAX_ERROR_DETAIL_LEN MEMORY_CAUSE_CGROUP_USAGE_UNREADABLE
    -+        MEMORY_CAUSE_READ_UNANSWERED MEMORY_PRESSURE_DETAIL
    -+        MEMORY_PRESSURE_NEVER_STARTED MEMORY_PRESSURE_RECHECK_SECS MemoryReadPoint
    -+        NOT_DELIVERY_STATE ORPHAN_NOTICE_OWED OUTCOME_FAILED OUTCOME_INTERRUPTED
    -+        OUTCOME_OK OrphanStallMonitor PARKS_WHEN_SET PARKS_WHEN_UNSET
    -+        PROVIDER_CLAUDE_CODE PROVIDER_LABEL_CLAUDE PROVIDER_LABEL_DEFAULT
    -+        ParentRecordUnreadable ParentSpawnPolicy PreparedSpawn ProcessHandle
    -+        PublishedQueueDepths QUEUED_REASON_CONCURRENCY_LIMIT QUEUED_REASON_LOW_MEMORY
    -+        QUEUED_REASON_MEMORY_PRESSURE QUEUED_WAIT_EXPIRED_TEXT RunEventCoordinator
    -+        SEL_MEMORY_PRESSURE_NEVER_STARTED SESSION_NOT_FOUND_GIVE_UP_TEXT
    -+        SESSION_NOT_FOUND_NOT_REPLAYED_TEXT SESSION_START_TIMEOUT_MIN
    -+        STOP_CLASS_CANCELLED STOP_CLASS_FAILED STOP_CLASS_SUCCEEDED
    -+        STOP_RECOVERY_MAX_RETRIES STUB_MODULE SUBAGENT_COMPLETION_PREFIX
    -+        SUBAGENT_TIMEOUT_SECS SUCCESSOR_PENDING SUCCESSOR_UNKNOWN SessionManager
    -+        SpawnAdmissionCoordinator SpawnApprovalCallback SpawnApprovalUnreachable Stats
    -+        SubagentDelivery SubagentEventCallback SubagentInfo SubagentManager
    -+        TERMINAL_TOOL_STATUSES TRANSIENT_RETRIES TerminalCoordinator
    -+        ToolApprovalCallback ToolCallState UNADVERTISED_AGENTS VERDICT_DEAD
    -+        VERDICT_STUCK_INPUT VERDICT_UNKNOWN VERDICT_WORKING WaveDigestCoordinator
    -+        acp_error_is_session_not_found acp_error_is_transient add_handle
    -+        advance_fallback_candidate agent_dir_for_display agent_matches_allowlist
    -+        annotate_model_fallback append_cost_sample append_fallback_story
    -+        apply_completion_keep bind_component_globals boottime_now
    -+        cached_project_agent_names cached_session_start_concurrency cap_buckets
    -+        capabilities_of check_memory_available child_process_helpers
    -+        classify_stop_reason clear_leaked_process clear_tombstone compact_cost_log
    -+        compute_max_subagents compute_memory_sized_parallel_cap
    -+        configured_fallback_chain consult_offloaded copy_component_docs
    -+        create_agent_folder data_home delivery_is_parked effort_applied_note
    -+        effort_drop_reason effort_pending_note effort_settings_key ending_fence
    -+        evict_completed_agents extract_options failure_name fire_tool_hooks
    -+        format_subagent_usage has_dashboard_surface hook_gate_kwargs
    -+        invalidate_stale_kas_session is_internal_agent_spec is_markdown_spec
    -+        is_registered_agent_name is_runtime_death iter_agent_spec_files join_failures
    -+        kill_each kill_set kill_verified_process learned_settled_for list_agents
    -+        list_leaked_processes list_orphans live logger maintenance_executor
    -+        mark_delivered model_supports_effort on_event_loop orphan_carried_fields
    -+        orphan_resume_hint parent_spawn_allowlists parent_spawn_policy
    -+        plain_markdown_document platform_compat pop_memory_check_cause
    -+        pressure_level_held process_handle_of process_survived_async
    -+        provider_fallback_active provider_last_turn_usage prune_stale_tombstones
    -+        read_cap_costs read_learned_costs_checked read_memory_pressure_level
    -+        read_session_execution read_state read_tombstone readonly_base_name
    -+        record_panel_dismissal_outcome record_slow_command redact_and_truncate
    -+        redact_credentials redact_exfiltration_urls redact_via_context
    -+        refresh_live_process_tree refuse_stale_switch replace_stale_shared_session
    -+        reproject_claimed_session resolve_max_subagents result_is_whole
    -+        run_in_embed_pool sel settle_delivered_batch single_completion_meta
    -+        spawn_allowlist spawn_in_flight subagent_count_ceiling subprocess_executor
    -+        teardown_capture tombstone_recovery_action transient_retry_delay turn_spec_hooks
    -+        update_state validate_cwd visible_agent_names window_for_provider_client
    -+        with_kill_failure write_finished_result write_result_chunk write_tombstone
    -+        """.split()),
    - }
    - 
    - #: Facade -> ``{name: module holding it}`` for each base name the facade re-binds by import.
    -@@ test/test_campaign_facades_base_public_names.py: _REBOUND: dict[str, dict[str, str]] = {
    -         "sandbox_plan": "kiro_crew",
    -         "sandbox_seatbelt": "kiro_crew",
    -     },
    -+    "kiro_crew.subagent": {
    -+        "AGENT_INTERNAL_CODE": "kiro_crew.subagent_parts.agent_policy",
    -+        "AGENT_NOT_AVAILABLE_CODE": "kiro_crew.subagent_parts.agent_policy",
    -+        "AGENT_NOT_FOUND_CODE": "kiro_crew.subagent_parts.agent_policy",
    -+        "AgentCheck": "kiro_crew.subagent_parts.agent_policy",
    -+        "DIGEST_HOLD_SECS": "kiro_crew.subagent_parts.run_limits",
    -+        "INJECTION_TIMEOUT": "kiro_crew.subagent_parts.run_limits",
    -+        "MEMORY_CAUSE_CGROUP_USAGE_UNREADABLE": "kiro_crew.subagent_parts.host_memory",
    -+        "MEMORY_CAUSE_READ_UNANSWERED": "kiro_crew.subagent_parts.host_memory",
    -+        "ORPHAN_NOTICE_OWED": "kiro_crew.subagent_parts.run_output",
    -+        "ParentRecordUnreadable": "kiro_crew.subagent_parts.agent_policy",
    -+        "ParentSpawnPolicy": "kiro_crew.subagent_parts.agent_policy",
    -+        "SEL_MEMORY_PRESSURE_NEVER_STARTED": "kiro_crew.subagent_parts.run_limits",
    -+        "SUCCESSOR_PENDING": "kiro_crew.subagent_parts.run_limits",
    -+        "SUCCESSOR_UNKNOWN": "kiro_crew.subagent_parts.run_limits",
    -+        "SubagentDelivery": "kiro_crew.subagent_parts.run_output",
    -+        "UNADVERTISED_AGENTS": "kiro_crew.subagent_parts.agent_policy",
    -+        "agent_matches_allowlist": "kiro_crew.subagent_parts.agent_policy",
    -+        "check_memory_available": "kiro_crew.subagent_parts.host_memory",
    -+        "compute_max_subagents": "kiro_crew.subagent_parts.host_memory",
    -+        "compute_memory_sized_parallel_cap": "kiro_crew.subagent_parts.host_memory",
    -+        "effort_applied_note": "kiro_crew.subagent_parts.model_choice",
    -+        "effort_drop_reason": "kiro_crew.subagent_parts.model_choice",
    -+        "effort_pending_note": "kiro_crew.subagent_parts.model_choice",
    -+        "format_subagent_usage": "kiro_crew.subagent_parts.run_output",
    -+        "parent_spawn_allowlists": "kiro_crew.subagent_parts.agent_policy",
    -+        "parent_spawn_policy": "kiro_crew.subagent_parts.agent_policy",
    -+        "pop_memory_check_cause": "kiro_crew.subagent_parts.host_memory",
    -+        "resolve_max_subagents": "kiro_crew.subagent_parts.host_memory",
    -+        "spawn_allowlist": "kiro_crew.subagent_parts.agent_policy",
    -+        "subagent_count_ceiling": "kiro_crew.subagent_parts.host_memory",
    -+        "validate_cwd": "kiro_crew.subagent_parts.agent_policy",
    -+        "visible_agent_names": "kiro_crew.subagent_parts.agent_policy",
    -+    },
    - }
    - 
    - _PROBE = """
    -
      ## test/test_eval_subagent_deny_notice.py ##
     @@ test/test_eval_subagent_deny_notice.py: _SUBAGENT_MODULES = [
          *sorted(
    @@ test/test_subagent_parts_composition_contract.py (new)
     +        (
     +            "parent_spawn_allowlists",
     +            "function",
    -+            "(parent_template: 'str') -> 'tuple[tuple[str, ...], ...] | None'",
    ++            "(parent_template: 'str', project_dirs: 'Sequence[str | Path]' = (), *, parent_session_key: 'str' = '') -> 'tuple[tuple[str, ...], ...] | None'",
    ++        ),
    ++        ("_ScopeAllowlists", "value", "GenericAlias"),
    ++        (
    ++            "_scope_spawn_allowlists",
    ++            "function",
    ++            "(agents_dir: 'Path', parent_template: 'str', memo: \"'AgentsDirMemo[_ScopeAllowlists]'\", operation: 'str') -> '_ScopeAllowlists'",
    ++        ),
    ++        ("_UNRESOLVED_PARENT_WARNED", "value", "set"),
    ++        ("_UNRESOLVED_PARENT_WARNED_MAX", "value", "int"),
    ++        ("_parent_project_resolver", "value", "NoneType"),
    ++        (
    ++            "set_parent_project_resolver",
    ++            "function",
    ++            "(resolver: \"Callable[[str], 'Iterable[str | Path]'] | None\") -> 'None'",
    ++        ),
    ++        ("parent_project_dirs", "function", "(parent_session_key: 'str') -> 'tuple[str, ...]'"),
    ++        (
    ++            "_surface_unresolved_parent_spec",
    ++            "function",
    ++            "(parent_template: 'str', parent_session_key: 'str') -> 'None'",
     +        ),
    ++        ("_PARENT_PROJECT_ALLOWLIST_MEMO", "value", "AgentsDirMemo"),
     +        ("_PARENT_ALLOWLIST_MEMO", "value", "AgentsDirMemo"),
     +        (
     +            "_scan_parent_spawn_allowlists",
     +            "function",
    -+            "(agents_dir: 'Path', parent_template: 'str') -> 'tuple[tuple[str, ...], ...] | None'",
    ++            "(agents_dir: 'Path', parent_template: 'str', operation: 'str' = 'spawn_available_agents') -> '_ScopeAllowlists'",
    ++        ),
    ++        (
    ++            "parent_template_allowlists",
    ++            "function",
    ++            "(parent_session_key: 'str', template: 'str') -> 'tuple[tuple[str, ...], ...] | None'",
     +        ),
     +        ("ParentRecordUnreadable", "class", ""),
     +        ("_parent_template_for_spawn", "function", "(parent_session_key: 'str') -> 'str'"),
    @@ test/test_subagent_parts_composition_contract.py (new)
     +    return "value", type(value).__name__
     +
     +
    ++def _stored_globals(code: types.CodeType):
    ++    """Every global a code object and its nested code objects assign or delete."""
    ++    for instruction in dis.get_instructions(code):
    ++        if instruction.opname in ("STORE_GLOBAL", "DELETE_GLOBAL"):
    ++            yield instruction.argval
    ++    for constant in code.co_consts:
    ++        if isinstance(constant, types.CodeType):
    ++            yield from _stored_globals(constant)
    ++
    ++
    ++def _state_the_owners_rebind() -> set[str]:
    ++    """Names owner code rebinds with ``global``: compose runs that code on the facade, so
    ++    the live value is the facade's, and the owner keeps only its import-time binding."""
    ++    return {name for _label, fn in _owner_functions() for name in _stored_globals(fn.__code__)}
    ++
    ++
     +def test_every_moved_name_keeps_its_base_shape_and_is_one_object() -> None:
     +    moved = {name for names in _BASE_SURFACE.values() for name, _kind_, _sig in names}
     +    assert len(moved) == sum(len(names) for names in _BASE_SURFACE.values())
    ++    rebound = _state_the_owners_rebind()
    ++    assert {"_host_read_in_flight", "_parent_project_resolver"} <= rebound
     +    for short, names in _BASE_SURFACE.items():
     +        owner = importlib.import_module(f"{subagent_parts.__name__}.{short}")
     +        for name, kind, shape in names:
     +            assert name in vars(owner), f"{short} does not define {name}"
    ++            if name in rebound:
    ++                # Live state lives on the facade (a setter or a test may have rebound it);
    ++                # the BASE shape is the owner's import-time binding.
    ++                assert name in vars(subagent), name
    ++                assert _kind(vars(owner)[name]) == (kind, shape), name
    ++                continue
     +            value = vars(subagent)[name]
     +            assert value is vars(owner)[name], f"{name} is two objects"
     +            assert _kind(value) == (kind, shape), name
     +
     +
    ++def test_a_setter_moved_into_an_owner_rebinds_the_facade_state(
    ++    monkeypatch: pytest.MonkeyPatch,
    ++) -> None:
    ++    """``set_parent_project_resolver`` writes the global ``parent_project_dirs`` reads."""
    ++    monkeypatch.setattr(subagent, "_parent_project_resolver", None)
    ++
    ++    def resolver(_key: str) -> tuple[str, ...]:
    ++        return ()
    ++
    ++    subagent.set_parent_project_resolver(resolver)
    ++    assert subagent._parent_project_resolver is resolver
    ++
    ++
     +def test_module_and_qualname_still_name_the_facade() -> None:
     +    for label, fn in _owner_functions():
     +        if "." in label.split(".", 1)[1]:

@bolichen97

Copy link
Copy Markdown
Contributor Author

Sensitive change review

Head: 822f915

  • What rule changed: No rule changed. security_posture.NON_EGRESS_REDACTION_MODULES gains two rows, subagent_parts/agent_policy.py and subagent_parts/run_output.py, because redactor call sites moved there verbatim from subagent.py. subagent.py stays the one registered redaction sink of the family; the two owners join its internal partitions (the subagent_manager/* rows) as non-egress modules.
  • Before -> after (what was allowed/blocked, now): Before, the redaction helpers lived in subagent.py; after, the same functions live in the two owners and still run on subagent.py's globals. Nothing newly allowed or blocked: the registry only classifies where redactor calls sit, and the drift guard would fail on an unregistered one.
  • Worst case if wrong (breaks commands / leaks secret / locks user out): A redactor call site would be misclassified as non-egress, so the security posture panel would not count it as an output sink. No command breaks and no secret leaks: the redaction calls themselves are byte-identical (move audit) and still run.
  • Evidence checked (which sandbox result proves it): Not a sandbox change. test/test_security_posture.py (drift guard over every redactor call site) passes on this head, and a mutation that adds an unregistered redact_and_truncate call to a subagent_parts owner turns it red.
  • No regression:
    • Tools still work (which tools/commands were run, result): The subagent family suites (295 test files, 25,914 passed, 12 skipped) cover spawn, run, terminal reports and redacted output on this head.
    • Backward compatible (old config / old data / old callers still work, how checked): Every kiro_crew.subagent name and patch target still resolves to the same object (test_campaign_facades_base_public_names.py, the new composition contract test); no config or data format changes.
    • Existing tests (which suites passed on this head): test_security_posture.py, test_subagent_parts_composition_contract.py, test_campaign_facades_base_public_names.py and the 295-file subagent family set, all green at 822f915.
  • How to undo: Revert this one commit; the two registry rows go with the code they classify.

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

Copy link
Copy Markdown
Contributor Author
  • span=fae8f56a4a25 compose() duplicates slack/gateway_runtime compose

Disposition: rebutted. Why this one cannot be the Slack one: test_slack_gateway_composition_contract.py::test_nothing_but_the_facade_imports_an_owner fails on any module other than slack/gateway.py that imports kiro_crew.slack.gateway_runtime, so importing that compose from subagent.py turns Slack's contract red; the split's design ruling requires the package-local copy.
Folding the per-package copies into one shared helper is #20421, outside this PR's goal of moving subagent.py's definitions unchanged.

@bolichen97

Copy link
Copy Markdown
Contributor Author
  • span=6feb2a3ec6db the host path does no work in this PR

Disposition: rebutted. The copy keeps the exact signature and contract of the existing per-package compose helpers (the design ruling's condition), so #20421 can fold all of them into one; trimming host here would make this copy the one that differs.
The host path is not untested: test_compose_rebinds_functions_methods_and_members runs a synthetic host with a bound function, a staticmethod and a property through it. The class-body PR of this approved two-PR series binds every SubagentManager method through it.

@bolichen97

Copy link
Copy Markdown
Contributor Author

Design Review punchline (advisory PASS, head 822f915) — answer:

Agreed, and tracked for the class-body PR: before it moves SubagentManager, every guard that still reads only subagent.py by path gets the subagent_parts/*.py join, starting with test_ws_event_scoping_frames.py's _fire_event scan (its file was another split's live target until now). This PR moves no _fire_event( call site and no method, so that scan's verdict is unchanged here; the guards this PR's moved code could escape are already joined and mutation-proved (test_subagent_scale, test_eval_subagent_deny_notice, test_spawn_admission_verdict_census, test_subagent_result_path_spelling, test_subagent_turn_resilience, the roster and hardened-reader pins).

@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 15, 2026

@buluoray buluoray left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verified head: 822f915 (merge-base with main c6d6106). Re-review after my approval at 62507b1 (merge-base 3572d1c) was dismissed.

What this does for users

There is no runtime change. src/kiro_crew/subagent.py drops from 6,923 to 4,697 lines because its module-level helpers move into six owners under kiro_crew.subagent_parts. kiro_crew.subagent is still the only import path and the only patch surface. For contributors, the file is reviewable again and conflicts less often. This is PR 1 of 2.

What changed since 62507b1

git range-diff 3572d1c540..62507b12c7 c6d610673b..822f91500f shows a single commit. Apart from rebase context, the differences all come from three things that landed on main since then:

  1. #20686 (project-scope availableAgents at the spawn gate) added five functions and five module values to subagent.py. The rebase moves them into subagent_parts/agent_policy.py with the rest of the allowlist code: _scope_spawn_allowlists, set_parent_project_resolver, parent_project_dirs, _surface_unresolved_parent_spec, parent_template_allowlists, _ScopeAllowlists, _PARENT_PROJECT_ALLOWLIST_MEMO, _UNRESOLVED_PARENT_WARNED, _UNRESOLVED_PARENT_WARNED_MAX and _parent_project_resolver (agent_policy.py:505-640, :671-697). The facade re-exports them (subagent.py:240-267). agent_policy's TYPE_CHECKING import gains Callable, Sequence, project_agents_dir and sel.
  2. The new global-statement setter. set_parent_project_resolver uses global _parent_project_resolver (agent_policy.py:591-594). compose runs owner functions on the facade's globals, so the setter writes kiro_crew.subagent._parent_project_resolver. parent_project_dirs reads that same binding (agent_policy.py:607), and so does the gateway's caller, dashboard/state.py:6769-6771, which imports the setter from kiro_crew.subagent. The owner's own _parent_project_resolver stays None and nothing reads it (I grepped src/ for every reference). _host_read_in_flight already followed this pattern (start_pricing.py:173-199). The contract test handles it correctly: test_every_moved_name_keeps_its_base_shape_and_is_one_object excludes the names owner code STORE_GLOBALs from the one-object check, and test_a_setter_moved_into_an_owner_rebinds_the_facade_state pins the write location (test/test_subagent_parts_composition_contract.py:641-689).
  3. #20911 (per-facade inventory files). This dissolved the conflict this PR had on test/test_campaign_facades_base_public_names.py. The PR no longer touches that file. It adds test/campaign_facade_inventories/kiro_crew.subagent.json instead, which is the same name set as before plus #20686's three public names (parent_project_dirs, parent_template_allowlists, set_parent_project_resolver) in both base_public_names and rebound.

Two smaller items: the .github/file-line-cap-baseline.txt row now reads 4697, which matches wc -l, and the spawn_available_agents_project label row in test/test_agent_spec_hardened_reads.py:1150-1153 follows the walk to agent_policy.py. The rest of the range-diff is context for the RFC docs and AUTOSDE paths that main rewrote.

Evidence (my own runs at this head)

  • Nothing dropped, bodies identical. I compared the AST of every top-level def, class and assignment in subagent.py at merge-base c6d6106 against the facade plus subagent_parts/*.py at this head:
    • The base has 179 units (92 defs or classes, 87 assignments). That is the 169 from the last round plus #20686's 10.
    • Missing: 0. Defined twice: 0. Moved defs: 79 (was 74).
    • Only _read_int_file and _read_inactive_file_bytes differ, as at 62507b1, and only in their docstrings ("this module's open" became "kiro_crew.subagent's open").
    • #20508's change, which stays in the facade, also compares identical.
  • No test lost. I collected the 12 affected test files (the 9 the PR edits, plus test_spawn_parent_available_agents.py, test_subagent_queue_max_wait.py and test_campaign_facades_base_public_names.py) on the merge-base and on this head. The base has 526 ids and the head has 534. Every base id is still present. The 8 new ids are the kiro_crew.subagent facade-inventory case and the per-file parametrisations over the 7 subagent_parts files in test_eval_subagent_deny_notice.py.
  • Shared state is a single instance. The re-exported memos, _UNRESOLVED_PARENT_WARNED and every other non-rebound moved value are the same object in owner and facade, which the contract test asserts. The only two names that differ are the global-rebound ones above, and their live value is the facade's.
  • Mutation. I stopped compose from rebinding set_parent_project_resolver. Four contract tests went red, including test_a_setter_moved_into_an_owner_rebinds_the_facade_state and test_every_name_the_tests_patch_on_the_facade_reaches_every_owner_reader. I restored the file and git status came back clean.
  • Tests. test_subagent_parts_composition_contract.py, the 12 files above and test_spawn_parent_available_agents.py gave 566 passed.
  • CI. At this head the latest row per check name gives 88 success, 11 skipped and 0 failures, out of 99 rows across all pages.
  • Mergeability. GitHub reports MERGEABLE. The PR is BLOCKED only because it needs a review, and auto-merge (squash) is armed.

Previous reviews

All three earlier reviews were approvals that later pushes dismissed. None was CHANGES_REQUESTED, so I had no requested changes to check point by point: mbriones98 at 7b86e6f, mine at 62507b1, KiroCrewCaptain at b2c5fbb.

Blocking

None.

Follow-ups (non-blocking)

  • The subagent_parts/__init__.py:28-29 docstring gives _host_read_in_flight as its only example of owner state rebound with global. Since _parent_project_resolver is now a second one, please name it there too. Please also add one line to the Composition section of docs/system-specs/modules/subagent.md: the owner keeps a stale import-time copy of such a name, so nobody should read it from the owner module.
  • Under the mutation above, the end-to-end tests in test_spawn_parent_available_agents.py stayed green, because they install the resolver by setting the facade attribute directly. A wrong rebinding of the setter would therefore be caught only by the composition contract. That is acceptable, but one gate test that installs the resolver through subagent.set_parent_project_resolver would pin the production path too.

Not verified

  • I did not run the full suite. I ran only the files listed above.
  • I did not run a gateway process to exercise DashboardState's resolver wiring live. The claim about it rests on reading dashboard/state.py:6769-6771 plus the contract tests.

@bolichen97
bolichen97 merged commit 2a8c936 into main Oct 16, 2026
103 of 104 checks passed
@bolichen97
bolichen97 deleted the refactor/linecap-g07-subagent branch October 16, 2026 00:30
@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.

5 participants