Repository navigation
refactor(subagent): compose module-level helpers from subagent_parts - #20401
Conversation
Sensitive change reviewHead: 7b86e6f
|
Sensitive Change ReviewSensitive files changed:
|
Design Review (Opus 5.5) — ✅ PASSDesign-level review of Design-Verdict: PASS Before PR 2 moves the class, check every guard that still reads only [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 |
First Principles Review (Opus 5.5) — 🟡 CONCERNSPremise-level review of First-Principles-Verdict: CONCERNS
Not justified as shipped
What this change shipsInventory (6 items) — 4 justifiedIntent: shrink
[FIRST-PRINCIPLES-REVIEWED] 822f915 Description read[DESCRIPTION-READ] 5aaff97a2536105a5e7b46b22c37bbde2e893be7ec81101639573d2e53909883 That sha256 names the PR description this verdict read. Recompute it with |
UX Review (Opus 5.5) — ⏭️ skippedRevision |
Opus 5.5 Review — ✅ no blocking findingsReviewed Verdict parsed from the review's SHA-scoped output markers for commit False positive or not applicable? A repository writer can comment: |
GPT 6.1 Review — ✅ no blocking findingsGPT 6.1 completed its review of This comment is updated in place on each push. Review detailsNo findings. False positive or not applicable? A repository writer can comment: |
|
|
|
Design Review punchline (advisory PASS) — answer: Yes, |
|
mbriones98
left a comment
There was a problem hiding this comment.
Checks green and readiness passed at 7b86e6f; no behavior change.
7b86e6f to
62507b1
Compare
Sensitive change reviewHead: 62507b1
|
|
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. |
|
|
|
Rebased onto main 0694e63, conflicts in |
58ceafa to
17702bc
Compare
|
Rebased onto main 8da5b41, no new conflicts; fixed the isort order of the two re-exported names my previous rebase added ( |
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.
17702bc to
822f915
Compare
|
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:
The line-cap row matches the facade's 4,697 lines. CI re-running. git range-diff b2c5fbb~1..b2c5fbb HEAD~1..HEAD1: 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]: |
Sensitive change reviewHead: 822f915
|
|
|
|
Design Review punchline (advisory PASS, head 822f915) — answer: Agreed, and tracked for the class-body PR: before it moves |
buluoray
left a comment
There was a problem hiding this comment.
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:
- #20686 (project-scope
availableAgentsat the spawn gate) added five functions and five module values tosubagent.py. The rebase moves them intosubagent_parts/agent_policy.pywith 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_MAXand_parent_project_resolver(agent_policy.py:505-640,:671-697). The facade re-exports them (subagent.py:240-267).agent_policy'sTYPE_CHECKINGimport gainsCallable,Sequence,project_agents_dirandsel. - The new global-statement setter.
set_parent_project_resolverusesglobal _parent_project_resolver(agent_policy.py:591-594).composeruns owner functions on the facade's globals, so the setter writeskiro_crew.subagent._parent_project_resolver.parent_project_dirsreads that same binding (agent_policy.py:607), and so does the gateway's caller,dashboard/state.py:6769-6771, which imports the setter fromkiro_crew.subagent. The owner's own_parent_project_resolverstaysNoneand nothing reads it (I greppedsrc/for every reference)._host_read_in_flightalready 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_objectexcludes the names owner codeSTORE_GLOBALs from the one-object check, andtest_a_setter_moved_into_an_owner_rebinds_the_facade_statepins the write location (test/test_subagent_parts_composition_contract.py:641-689). - #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 addstest/campaign_facade_inventories/kiro_crew.subagent.jsoninstead, 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 bothbase_public_namesandrebound.
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.pyat merge-base c6d6106 against the facade plussubagent_parts/*.pyat 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_fileand_read_inactive_file_bytesdiffer, as at 62507b1, and only in their docstrings ("this module'sopen" became "kiro_crew.subagent'sopen"). #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.pyandtest_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 thekiro_crew.subagentfacade-inventory case and the per-file parametrisations over the 7subagent_partsfiles intest_eval_subagent_deny_notice.py. - Shared state is a single instance. The re-exported memos,
_UNRESOLVED_PARENT_WARNEDand 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 theglobal-rebound ones above, and their live value is the facade's. - Mutation. I stopped
composefrom rebindingset_parent_project_resolver. Four contract tests went red, includingtest_a_setter_moved_into_an_owner_rebinds_the_facade_stateandtest_every_name_the_tests_patch_on_the_facade_reaches_every_owner_reader. I restored the file andgit statuscame back clean. - Tests.
test_subagent_parts_composition_contract.py, the 12 files above andtest_spawn_parent_available_agents.pygave 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-29docstring gives_host_read_in_flightas its only example of owner state rebound withglobal. Since_parent_project_resolveris now a second one, please name it there too. Please also add one line to the Composition section ofdocs/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.pystayed 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 throughsubagent.set_parent_project_resolverwould 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 readingdashboard/state.py:6769-6771plus the contract tests.
Problem / Motivation
Goal: Bring
src/kiro_crew/subagent.pycloser to the 2,000-line cap by moving its module-level helpers into focusedkiro_crew.subagent_partsmodules, with no change in behaviour.subagent.pyis 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, becauseSubagentManagerby 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
SubagentManagerclass: its split is the second PR of this series.kiro_crew.subagent.subagent_manager/or itsbind_component_globalsmechanism.What changed (motivation → approach → change)
subagent.pydrops from 7,095 to 4,697 lines. 152 module-level definitions move into six owners under a new package,kiro_crew.subagent_parts:run_limits.pyrun_output.pyagent_policy.pyvalidate_cwdmodel_choice.pyhost_memory.pystart_pricing.pyThe point is that
kiro_crew.subagentstays one namespace. Tests patch about 1,500kiro_crew.subagent.<name>targets, and moved code must still see those patches. Sosubagent.pyre-exports every moved name, andsubagent_parts.compose()(in the package__init__, 143 lines) rebinds every owner function onto the facade's globals, the same wayslack/gateway_runtimecomposesslack/gateway.py. Owners import the facade only underTYPE_CHECKING. The values an owner computes when it is imported (defaults, class bodies, one dataclass field factory) import what they read directly, andrun_outputimportsAnyfor real sotyping.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 existingbind_component_globalstail.Backwards compatibility
Compatible: every name
kiro_crew.subagentbound at the base still resolves there to the same object (test_campaign_facades_base_public_names.py), and everykiro_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.pyintokiro_crew.subagent_parts;subagent.pyre-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 nameskiro_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,reprand error-text greps: no hits).Tests
test/test_subagent_parts_composition_contract.py(new, 31 tests) pins the composition: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;__module__,__qualname__and the logger still name the facade;compose()run, and a fresh-interpreter import that loads every owner.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 andtest_a_setter_moved_into_an_owner_rebinds_the_facade_statepins 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 bytest_campaign_facades_base_public_names.py.tmp_path,monkeypatchand a bounded subprocess; no clock, sleep, port or order assertion. Passed 5 runs at-n0and one at-n 3.Local runs on this head (Python 3.12,
-n 3):subagent.py: 183 files, 14,306 passed, 4 skipped;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-runselects 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
kiro_crew.subagentand everykiro_crew.subagent_partsmodule.Related Issues
Part of #20192
Move audit
move_audit.py --origin src/kiro_crew/subagent.py:Both changed units are docstring-only: "this module's
open" becomes "kiro_crew.subagent'sopen", because the functions now live inhost_memory.pybut still read the facade'sopen, which the sizing tests patch. Everything else insubagent.pythat differs from the base is facade glue: the owner imports and re-exports, two binding tuples, thecomposecall, and two dropped imports nothing reads any more (re,NamedTuple).git diffandgit diff --minimaladd the same lines in every changed file (38 files; 222 lines insubagent.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:SubagentInfo._report_delivered, aDELIVERY_ROUTING_FIELDSrow): in the region this PR keeps insubagent.py, carried unchanged.availableAgentsat the spawn gate): its ten new helpers (parent_project_dirs,set_parent_project_resolver,parent_template_allowlists,_scope_spawn_allowlists, ...) and the changedparent_spawn_allowlists/_scan_parent_spawn_allowlistsmove intoagent_policy.pywith the rest of the parent-allowlist code; the move audit still reports only the two docstring units as changed.Composition mechanism
The facade already rebinds
subagent_managercoordinator functions withbind_component_globals, but that helper only touches*_implattributes of coordinator classes and cannot rebind module-level functions or class members, so it is left untouched. The new owners use a package-localcompose()insubagent_parts/__init__.py, with the same shape and contract asslack/gateway_runtime.composeandchat_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_ownerfails on any module other thanslack/gateway.pythat importskiro_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 onrun_output's own globals.An owner that calls
osortimeimports it asimport <module>underTYPE_CHECKINGrather than from the facade, becausescripts/check_sync_io_in_async.pyresolves those modules only from a same-file import; atime.sleep(1)planted in a moved coroutine is flagged.Logger (L25): moved code keeps the original logger. Owners define no logger and read
loggerfrom the facade's globals, so every record still carrieskiro_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 plussubagent_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: thespawn_available_agentscall-site key moves tokiro_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 addsubagent_parts/*.py.test/test_subagent_scale.py(one-draw-site ratchet): its two whole-family checks (os.urandom(once, nouuid4()) read the facade plussubagent_parts/*.py; the_mint_agent_idslice still reads the facade, where that method stays in this PR.Registries, docs and CI path references
src/kiro_crew/security_posture.pyNON_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 addsrc/kiro_crew/subagent_parts/*.py..github/docs-lint-baseline.txt: 8 rows deleted by hand for RFCsubagent.py:NNNcitations rewritten as symbols..github/file-line-cap-baseline.txt: thesubagent.pyrow is lowered by hand from 6,923 to 4,697 (the second PR deletes it). The re-pointedtest_subagent_scale.py(+5 lines) andtest_subagent_turn_resilience.py(+1), andsecurity_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.mdgains a Composition section: the owner table, the one-namespace rule, and where new code goes.subagent.pyas 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 indashboard/handlers/tasks.pyand intest/test_api_tasks.py.Risks
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
feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)