From 58a07fd6753aa7d55780703d69e97d7950fcbd58 Mon Sep 17 00:00:00 2001 From: Sajal Narang Date: Sun, 27 Sep 2026 06:47:47 +0000 Subject: [PATCH] fix(members): honour the inherited-resources opt-out in snapshots A member whose workspace sets chat.disableInheritingDefaultResources still received the operator's global steering, AGENTS.md and undeclared workspace steering in its V2 essential snapshot, because the snapshot scanned them unconditionally. kiro-cli gives such an agent only the resources it declares, so the snapshot re-added the very rules the member was configured without. The opt-out is kiro-cli's own setting, so it binds only sessions kiro-cli serves; every other harness keeps inheriting. Each member turn reads the verdict once, from the preference the native skill projection records (Crew's own overlay included), and hands it to the snapshot, the kiro harness's launch-document model and the folder-steering dedup. Settings that cannot be read keep inheritance. A profile validation pass reads no setting and measures the inheriting envelope, the largest any harness can build. The snapshot skips the implicit scans when it opts out, and a folder that declares one of the skipped steering trees delivers those documents itself, once: the folder reader skips a file whose canonical path the template already delivered, compared as a string before its label is folded, so no path is resolved again and two files whose labels fold alike both arrive. Non-member kiro chats follow the same verdict, so their folder steering no longer skips trees kiro-cli will not load. The projection routes its existing decision through the same function. --- .../modules/memory-skills-hooks.md | 19 +- docs/system-specs/modules/providers.md | 18 +- src/kiro_crew/acp/skill_projection.py | 63 ++- src/kiro_crew/agent_sdk/drivers/acp.py | 14 + src/kiro_crew/context.py | 87 +++- src/kiro_crew/folder_steering.py | 17 +- src/kiro_crew/member_essential_context.py | 69 ++- test/test_folder_steering.py | 51 ++ test/test_folder_steering_provider_dedup.py | 120 ++++- test/test_member_essential_context.py | 465 ++++++++++++++++++ test/test_native_skill_projection.py | 47 ++ 11 files changed, 916 insertions(+), 54 deletions(-) diff --git a/docs/system-specs/modules/memory-skills-hooks.md b/docs/system-specs/modules/memory-skills-hooks.md index c870460e4a9a..83abdb9d695b 100644 --- a/docs/system-specs/modules/memory-skills-hooks.md +++ b/docs/system-specs/modules/memory-skills-hooks.md @@ -1310,7 +1310,24 @@ unbounded archival memory. Admitted project essentials are the active project's root `AGENTS.md` and `SOUL.md`, default/`always` documents under `.kiro/steering`, and Markdown file -resources explicitly declared by the template. Native `manual`, `auto` and +resources explicitly declared by the template. The global `~/.kiro/steering` +always documents, the root `AGENTS.md` and undeclared `.kiro/steering` +documents are kiro-cli default resources: when kiro-cli serves the session and +`chat.disableInheritingDefaultResources` opts the workspace out, the snapshot +omits them and keeps the prompt, the declared resources and `SOUL.md`, which is +Crew's own file rather than a kiro-cli default. The verdict is computed once +per normal turn, where the harness is known, and handed to the snapshot and the +folder-steering dedup; no consumer reads the setting itself, and on any other +harness the member keeps inheriting because a kiro-cli setting changes nothing +there. A profile validation pass does not read the setting and instead measures +the inheriting envelope, which is the largest envelope any harness can build. +The preference comes from the skill projection's decision (see +[ACP client](acp-client.md)), so Crew's overlay on that key never reads as an +opt-out; settings that cannot be read keep inheritance. A non-member kiro-cli +chat follows the same decision: in an opted-out workspace a folder that +declares the project's or the global `.kiro/steering` root carries those +always documents itself, at session start and after a compaction, instead of +skipping them as already delivered. Native `manual`, `auto` and `fileMatch` steering retain their trigger semantics. A custom template's declared prompt may be inline or a file source. Missing optional root files are allowed; an unreadable declared source or malformed/shadowed template diff --git a/docs/system-specs/modules/providers.md b/docs/system-specs/modules/providers.md index 72dde6c2068c..264c308d5a22 100644 --- a/docs/system-specs/modules/providers.md +++ b/docs/system-specs/modules/providers.md @@ -162,7 +162,12 @@ Kiro's supported `--agent` prompt/resources contract, not a per-file model recei Changes to a launch-version source receive a complete manual replacement. Kiro's implicit workspace-root AGENTS and default/always steering in project and global steering directories also belong to that launch contract, even when no -resource glob declares them. SOUL is native-owned only when explicitly declared. +resource glob declares them, while the workspace inherits kiro-cli's default +resources; an opted-out workspace's contract is its declared sources alone. The +opt-out is kiro-cli's own setting, so it applies only when kiro-cli serves the +session: every other harness keeps the inheriting contract, and the non-member +folder-steering dedup follows the same decision. +SOUL is native-owned only when explicitly declared. The mirrored steering reference records engine/version differences for conditional modes, so Kiro uses the fallback selector instead of claiming full native support. @@ -176,11 +181,12 @@ the harnesses carry no folder-steering field, so every harness produces an identical `SpawnPlan` for a folder chat and a non-folder chat; delivery cannot be lost by adding a provider. A file whose realpath lies under the chat project's `.kiro/steering` or under `~/.kiro/steering` is skipped ONLY where the active provider -already delivers those trees -- kiro-cli loads them natively, the Claude Code seam -receives the explicit steering load, KAS reports `native_steering` -- so they are -not sent twice; on a harness with no such path (Codex, OpenCode, Pi, Goose, -DeepSeek) the folder delivers them like any other document rather than skipping -rules nothing else would carry. Documents honor the steering +already delivers those trees -- kiro-cli loads them natively while the workspace +inherits kiro-cli's default resources, the Claude Code seam receives the explicit +steering load, KAS reports `native_steering` -- so they are not sent twice; on a +harness with no such path (Codex, OpenCode, Pi, Goose, DeepSeek) the folder +delivers them like any other document rather than skipping rules nothing else +would carry. Documents honor the steering `inclusion` frontmatter (`always`, or absent, is included; `manual`, `auto` and `fileMatch` are skipped and left to their native trigger), and each file is admitted against its own declared directory as the trust base, so a symlink can diff --git a/src/kiro_crew/acp/skill_projection.py b/src/kiro_crew/acp/skill_projection.py index 85d948ad7710..7fd54f799204 100644 --- a/src/kiro_crew/acp/skill_projection.py +++ b/src/kiro_crew/acp/skill_projection.py @@ -736,6 +736,55 @@ def _settings(path: Path) -> dict[str, Any]: return data +def _inheritance_preference( + local: dict[str, Any], global_settings: dict[str, Any] +) -> tuple[bool, Any, bool]: + """Return ``(inherited, source, overlaid)`` for custom agents in one workspace. + + Once Crew's overlay is in place the native key reads ``true`` whatever the + user chose, so the recorded preference decides: a ``global`` source follows + the live global setting and any other source keeps the recorded value. + Without the overlay, or after the user moves the native key off ``true``, + the native key decides -- the workspace value when present, else the global + one -- and only the literal ``true`` opts out. + """ + inherited = local.get(_MANAGED_SETTING) + source = local.get(_INHERIT_SOURCE) + if not isinstance(inherited, bool) or local.get(_INHERIT_SETTING) is not True: + source = "local" if _INHERIT_SETTING in local else "global" + native = local.get(_INHERIT_SETTING, global_settings.get(_INHERIT_SETTING)) + return native is not True, source, False + if source == "global": + return global_settings.get(_INHERIT_SETTING) is not True, source, True + return inherited, source, True + + +def inherits_default_resources(work_dir: str | os.PathLike[str] | None) -> bool: + """Whether a custom agent started in *work_dir* inherits kiro-cli's default resources. + + Those defaults are global and workspace steering plus ``AGENTS.md``. This is + the read-only twin of the decision :func:`prepare_native_skill_projection` + makes, for callers that must mirror what the native agent loads. Settings + that cannot be read keep inheritance, which is how those callers behaved + before they asked. + """ + try: + global_settings = _settings(kiro_home() / "settings" / "cli.json") + local = ( + _settings(Path(work_dir) / ".kiro" / "settings" / "cli.json") + if work_dir is not None + else {} + ) + # RuntimeError: Path.resolve() reports a symlink loop that way before Python 3.13. + except (OSError, ValueError, RuntimeError, RecursionError, FileTooLargeError): + logger.warning( + "skill projection: Kiro settings unreadable; keeping inherited resources", + exc_info=True, + ) + return True + return _inheritance_preference(local, global_settings)[0] + + def _restore_inheritance(path: Path, local: dict[str, Any]) -> None: """Undo only our overlay; a changed or removed native setting wins.""" inherited = local.get(_MANAGED_SETTING) @@ -1595,20 +1644,14 @@ def prepare_native_skill_projection( # the same sidecar lock, so no effort or Tool Search update can land # between this read and commit. local = _settings(locked_settings) - inherited = local.get(_MANAGED_SETTING) - preference_source = local.get(_INHERIT_SOURCE) - if not isinstance(inherited, bool) or local.get(_INHERIT_SETTING) is not True: + inherited, preference_source, overlaid = _inheritance_preference( + local, global_settings + ) + if not overlaid: local[_PREVIOUS_INHERITANCE] = { "present": _INHERIT_SETTING in local, "value": local.get(_INHERIT_SETTING), } - preference_source = "local" if _INHERIT_SETTING in local else "global" - inherited = ( - local.get(_INHERIT_SETTING, global_settings.get(_INHERIT_SETTING)) - is not True - ) - elif preference_source == "global": - inherited = global_settings.get(_INHERIT_SETTING) is not True if inherited: for view in specs.values(): diff --git a/src/kiro_crew/agent_sdk/drivers/acp.py b/src/kiro_crew/agent_sdk/drivers/acp.py index 979e8e299982..742369f9c9b7 100644 --- a/src/kiro_crew/agent_sdk/drivers/acp.py +++ b/src/kiro_crew/agent_sdk/drivers/acp.py @@ -606,6 +606,20 @@ def projected_session_mcp_servers( return session_mcp_servers(agent, work_dir=work_dir) +def inherits_default_resources(work_dir: str | Path | None) -> bool: + """Whether a custom agent started in *work_dir* inherits kiro-cli's default resources. + + Global and workspace steering plus ``AGENTS.md``. The answer is the skill + projection's, so Crew's own overlay on the native setting is not mistaken for + the user opting out. + """ + from kiro_crew.acp.skill_projection import ( + inherits_default_resources as projection_inherits_default_resources, + ) + + return projection_inherits_default_resources(work_dir) + + def skill_view_alias_census(agents_dir: "Path") -> dict[str, int]: """Count projected skill-view aliases as plain integers; reads, never writes. diff --git a/src/kiro_crew/context.py b/src/kiro_crew/context.py index a201c72fc626..9f8aa1947be2 100644 --- a/src/kiro_crew/context.py +++ b/src/kiro_crew/context.py @@ -25,6 +25,7 @@ from kiro_crew._sqlite_compat import sqlite3 from kiro_crew.agent import _prompt_path, is_managed_prompt from kiro_crew.agent_discovery import agent_skill_globs +from kiro_crew.agent_sdk.drivers import acp as acp_driver from kiro_crew.agent_sdk.provider_identity import PROVIDER_ACP, is_claude_code from kiro_crew.agent_spec_format import iter_agent_spec_files, parse_agent_spec_text from kiro_crew.board_tag_grammar import is_grantable_tag_id @@ -54,6 +55,7 @@ _MAX_DOCUMENTS, ESSENTIAL_MAX_CHARS, MemberEssentialContextError, + member_inherits_default_resources, render_essentials, ) from kiro_crew.members import ( @@ -2218,20 +2220,32 @@ def _load_steering_resources() -> str: return "" -def _project_steering_delivered(provider_type: str, native_steering: bool) -> bool: +def _project_steering_delivered( + provider_type: str, native_steering: bool, project: str | None +) -> bool: """Whether the project/global ``.kiro/steering`` trees already reach the model. Three paths exist and this names all of them, so the folder-steering dedup skips those trees ONLY where one of them is in effect: kiro-cli (the ACP default label) loads an agent's ``resources`` natively when spawned with - ``--agent``; the Claude Code seam receives the explicit ``[Steering - resources]`` load in ``build_message`` (gated on ``is_cc``); KAS reports - ``native_steering`` on its session provider. Every other harness -- Codex, - OpenCode, Pi, Goose, DeepSeek -- has NO path for those trees today, so a - folder that declares one of them must deliver its documents itself rather - than skip them as "already delivered" with nothing arriving in their place. + ``--agent``, but only while *project* inherits kiro-cli's default resources + (a workspace that sets ``chat.disableInheritingDefaultResources`` gets + those trees from nobody, so the folder must carry them); the Claude Code + seam receives the explicit ``[Steering resources]`` load in + ``build_message`` (gated on ``is_cc``); KAS reports ``native_steering`` on + its session provider. Every other harness -- Codex, OpenCode, Pi, Goose, + DeepSeek -- has NO path for those trees today, so a folder that declares one + of them must deliver its documents itself rather than skip them as "already + delivered" with nothing arriving in their place. The opt-out is read only + on the kiro-cli disjunct: a kiro-cli setting changes nothing on another + harness. The driver is asked directly, with no admission check on + *project*: this path also serves non-member sessions and must not raise. """ - return provider_type == PROVIDER_ACP or is_claude_code(provider_type) or bool(native_steering) + return ( + (provider_type == PROVIDER_ACP and acp_driver.inherits_default_resources(project)) + or is_claude_code(provider_type) + or bool(native_steering) + ) def _render_folder_steering_section( @@ -3729,6 +3743,7 @@ def _build_v2_essentials( trigger_text: str = "", steering_dirs: tuple[str, ...] = (), template_selected: bool = False, + provider_type: str = PROVIDER_ACP, ) -> str: """Refresh complete member essentials without opening learned memory. @@ -3736,6 +3751,11 @@ def _build_v2_essentials( for the execution being built and is handed to the member-section builder unchanged: the envelope keeps the member's identity, rules, documents and anchors, and withholds only the desk protocol and briefing. + + ``provider_type`` names the harness serving the session. Only kiro-cli + (:data:`PROVIDER_ACP`) honours ``chat.disableInheritingDefaultResources``, + so its verdict is read once here, where the harness is known, and handed + to every consumer; no consumer reads the setting itself. """ from kiro_crew.member_essential_context import ( MemberEssentialContextError, @@ -3765,17 +3785,29 @@ def _build_v2_essentials( if profile_overrides is None: context_groups = _config_scoped_groups(context_groups) reads = not blocks_reads and _group_included(context_groups, CONTEXT_GROUP_MEMORY) + include_project = not blocks_reads and _group_included( + context_groups, CONTEXT_GROUP_PROJECT + ) identity = self._build_member_section( owner, strict=True, include_briefing=reads, template_selected=template_selected ) + # A validation pass measures the largest envelope any harness can build, + # so it keeps inheritance and never reads kiro-cli's opt-out. On a normal + # turn, the setting changes what a member loads only on a session + # kiro-cli serves: every other harness keeps inheriting. Read once, where + # the project group applies, and pass the verdict to the snapshot and the + # folder-steering dedup below so the two cannot disagree. + inherits_default_resources = True + if profile_overrides is None and include_project and provider_type == PROVIDER_ACP: + inherits_default_resources = member_inherits_default_resources(project) documents = documents_for_member( template, project, conditional_index=conditional_index, context_settings=True, trigger_text=trigger_text, - include_project=not blocks_reads - and _group_included(context_groups, CONTEXT_GROUP_PROJECT), + include_project=include_project, + inherits_default_resources=inherits_default_resources, ) if execution_template and execution_template != template: sources = dict(documents) @@ -3785,8 +3817,8 @@ def _build_v2_essentials( conditional_index=conditional_index, context_settings=True, trigger_text=trigger_text, - include_project=not blocks_reads - and _group_included(context_groups, CONTEXT_GROUP_PROJECT), + include_project=include_project, + inherits_default_resources=inherits_default_resources, ): if source in sources and sources[source] != body: raise MemberEssentialContextError( @@ -3809,14 +3841,29 @@ def _build_v2_essentials( # until the folder shrinks. The character budget depends on the memory # documents appended below, so the candidates are collected here (their # position recorded) and fitted just before the envelope renders. + # + # The project and global ``.kiro/steering`` trees are skipped as already + # delivered only while the snapshot above actually delivered them: a + # kiro-cli workspace that opts out of the default resources gets them + # from neither the snapshot nor the harness, so a folder that declares + # one of those roots must carry its documents itself. The template's + # declared resources can still carry some of those files, so under the + # opt-out a folder document whose canonical path the template already + # delivered is not collected again. Same verdict as the snapshot, read + # once above. folder_docs: SteeringCollection = SteeringCollection() folder_insert_at = len(documents) - if ( - steering_dirs - and not blocks_reads - and _group_included(context_groups, CONTEXT_GROUP_PROJECT) - ): - folder_docs = collect_folder_steering(steering_dirs, project=project) + if steering_dirs and include_project: + folder_docs = collect_folder_steering( + steering_dirs, + project=project, + skip_delivered_roots=inherits_default_resources, + delivered_sources=( + tuple(source for source, _ in documents) + if not inherits_default_resources + else () + ), + ) if reads: from kiro_crew.memory_stores import memory_store_dir_for @@ -3983,6 +4030,7 @@ def append_required(text: str) -> None: member_template=execution_context.template_id if execution_context else "", steering_dirs=steering_dirs, template_selected=_template_selected_on_member_store(execution_context), + provider_type=provider_type, ) # Minimal V1 stays date/time + agent identity. Private V2 also carries @@ -4964,6 +5012,7 @@ def build_message( and not context_provider.native_steering, steering_dirs=steering_dirs, template_selected=_template_selected_on_member_store(execution_context), + provider_type=provider_type, ) if _essentials and not is_new_session: parts.append(_essentials) @@ -5151,6 +5200,7 @@ def build_message( skip_delivered_roots=_project_steering_delivered( provider_type, context_provider is not None and context_provider.native_steering, + project, ), ) if _folder_ctx: @@ -5298,6 +5348,7 @@ def build_message( skip_delivered_roots=_project_steering_delivered( provider_type, context_provider is not None and context_provider.native_steering, + project, ), ) if _folder_ctx: diff --git a/src/kiro_crew/folder_steering.py b/src/kiro_crew/folder_steering.py index eb3babd9f320..d5efcaf9de58 100644 --- a/src/kiro_crew/folder_steering.py +++ b/src/kiro_crew/folder_steering.py @@ -18,7 +18,7 @@ import logging import os -from collections.abc import Callable, Iterator, Sequence +from collections.abc import Callable, Collection, Iterator, Sequence from dataclasses import dataclass, field from pathlib import Path @@ -581,6 +581,7 @@ def collect_folder_steering( project: str | None, home: Path | None = None, skip_delivered_roots: bool = True, + delivered_sources: Collection[str] = (), ) -> SteeringCollection: """``(source_path, body)`` for every always-inclusion ``*.md`` under *steering_dirs*. @@ -599,15 +600,20 @@ def collect_folder_steering( *skip_delivered_roots* says whether documents under the project's and the operator's ``.kiro/steering`` trees are ALREADY reaching the model by the - provider's own steering path (kiro-cli loads them natively, the Claude Code - seam loads them explicitly, KAS reports ``native_steering``) and so must not - be re-sent here. A provider with no such path -- Codex, and the other + provider's own steering path (kiro-cli loads them natively while the + workspace inherits kiro-cli's default resources, the Claude Code seam loads + them explicitly, KAS reports ``native_steering``) and so must not be re-sent + here. A provider with no such path -- Codex, and the other harnesses that neither load ``.kiro/steering`` nor receive the explicit load -- passes ``False`` and receives them through the folder like any other document; skipping there would drop the rules with nothing delivered in their place. The default keeps the dedup for callers that know their provider delivers. + *delivered_sources* names canonical document paths the caller already + delivers. Matching candidates are skipped before they are read. The paths + are compared as strings and are never resolved or otherwise opened here. + *home* exists for the tests and for a caller that knows the operator home without paying ``Path.home()``; it defaults to ``Path.home()``. """ @@ -616,6 +622,7 @@ def collect_folder_steering( omissions = result.omissions if not steering_dirs: return result + delivered_source_keys = {os.path.normcase(source) for source in delivered_sources} if not pinned_fs.supports_pinned_tree_walk(): # Refuse BEFORE resolving any root: the walker's own refusal fires only # after ``validate_file_path`` has canonicalized the name, and on a host @@ -697,6 +704,8 @@ def collect_folder_steering( continue if key in seen: continue + if os.path.normcase(key) in delivered_source_keys: + continue if any(_is_within(resolved, skip_root) for skip_root in skip_roots): continue if not _admissible(resolved, root_resolved): diff --git a/src/kiro_crew/member_essential_context.py b/src/kiro_crew/member_essential_context.py index 8c106047ac3c..5ff2d8aa1795 100644 --- a/src/kiro_crew/member_essential_context.py +++ b/src/kiro_crew/member_essential_context.py @@ -7,6 +7,7 @@ import os from pathlib import Path +from kiro_crew.agent_sdk.drivers import acp as acp_driver from kiro_crew.config import KiroCrewConfig, config_dir from kiro_crew.config.loader import workspace_dir_for from kiro_crew.config.paths import project_agents_dir @@ -327,6 +328,32 @@ def resolve_relative_prompt_path( return None +def _admitted_project_root(project: str | None) -> Path | None: + """The member's project as the essential readers may open it, or ``None``.""" + if not project: + return None + admitted = validate_file_path(project) + if admitted is None: + raise MemberEssentialContextError(f"Essential project {project}: cannot be read safely") + project_root = Path(admitted) + _refuse_managed_source(project_root) + return project_root + + +def member_inherits_default_resources(project: str | None) -> bool: + """Whether kiro-cli hands a member in its admitted *project* the default resources. + + Global and workspace steering plus ``AGENTS.md``. Settings that cannot be + read keep inheritance; the caller decides whether kiro-cli serves the + session at all, since a kiro-cli setting changes nothing on another harness. + Computed once per member turn by the caller that knows the provider and + handed to :func:`documents_for_member` and the folder-steering dedup, so a + document under a ``.kiro/steering`` root is delivered by exactly one of them + whichever way the workspace decides. + """ + return acp_driver.inherits_default_resources(_admitted_project_root(project)) + + def documents_for_member( template: str, project: str | None, @@ -336,25 +363,25 @@ def documents_for_member( conditional_index: bool = False, context_settings: bool = False, trigger_text: str = "", + inherits_default_resources: bool = True, ) -> list[tuple[str, str]]: """Read actual project instructions and the owner's declared template sources. Native project steering defaults to always; manual, auto and fileMatch documents are deliberately left to their native trigger. Generic product prompts keep their existing provider/session-start path. + + *inherits_default_resources* is the caller's verdict on whether the session's + harness hands the member kiro-cli's default resources (global and workspace + steering, ``AGENTS.md``). It defaults to inheriting because only a session + kiro-cli serves can opt out, and only that caller knows which harness it has. """ from kiro_crew.agent import is_managed_prompt from kiro_crew.agent_discovery import _read_agent_spec documents: list[tuple[str, str]] = [] seen: set[Path] = set() - project_root = None - if project: - admitted = validate_file_path(project) - if admitted is None: - raise MemberEssentialContextError(f"Essential project {project}: cannot be read safely") - project_root = Path(admitted) - _refuse_managed_source(project_root) + project_root = _admitted_project_root(project) def add(path: Path, root: Path, *, steering: bool = False) -> None: if Path(os.path.abspath(path)) in seen: @@ -426,17 +453,25 @@ def add(path: Path, root: Path, *, steering: bool = False) -> None: if len(documents) > _MAX_DOCUMENTS: raise MemberEssentialContextError(f"Essential source {path}: too many documents") - if include_project and not native_only: + # kiro-cli appends its default resources (global and workspace steering, + # AGENTS.md) to a custom agent only while the workspace inherits them. A + # member whose workspace opts out loads just what its template declares, so + # the snapshot must not re-add the operator's global steering behind it. + inherits = include_project and not native_only and inherits_default_resources + if inherits: for path in _matches(Path.home(), ".kiro/steering/**/*.md"): add(path, Path.home(), steering=True) if project_root is not None and include_project and not native_only: - for name in ("AGENTS.md", "SOUL.md"): + # SOUL.md is Crew's own member file, not a kiro-cli default resource, so + # the opt-out leaves it in place. + for name in ("AGENTS.md", "SOUL.md") if inherits else ("SOUL.md",): path = project_root / name if path.exists() or path.is_symlink(): add(path, project_root) - for path in _matches(project_root, ".kiro/steering/**/*.md"): - add(path, project_root, steering=True) + if inherits: + for path in _matches(project_root, ".kiro/steering/**/*.md"): + add(path, project_root, steering=True) spec_path = resolve_template_path(template, project) if spec_path is None: @@ -616,13 +651,21 @@ def kiro_launch_documents(template: str, project: str | None) -> list[tuple[str, """Selected resources plus Kiro's implicit AGENTS/always-steering scan. SOUL is not an implicit native source. Conditional modes vary by engine and - version, so this responsibility includes only default/always steering. + version, so this responsibility includes only default/always steering. The + implicit scan applies only while the workspace inherits kiro-cli's default + resources, as it does natively; this model is kiro-cli's by construction, so + it takes that verdict itself, once. """ + inherits = member_inherits_default_resources(project) declared = dict(documents_for_member(template, project, native_only=True)) - for source, body in documents_for_member(template, project): + for source, body in documents_for_member( + template, project, inherits_default_resources=inherits + ): path = Path(source) if path.name == "AGENTS.md" or "steering" in path.parts: declared[source] = body + if not inherits: + return list(declared.items()) for path in _matches(Path.home(), ".kiro/steering/**/*.md"): body = _read(path, Path.home()) fields, _ = split_frontmatter(body, STEERING_LOADER) diff --git a/test/test_folder_steering.py b/test/test_folder_steering.py index ac32f8079a9e..db6cbc649b8d 100644 --- a/test/test_folder_steering.py +++ b/test/test_folder_steering.py @@ -235,6 +235,57 @@ def test_realpath_dedup_across_two_roots(tmp_path): assert [path for path, _ in docs] == [str(doc.resolve())] +def test_delivered_sources_skip_only_the_same_canonical_file(tmp_path, monkeypatch): + """Delivered inputs stay string-only while fold-colliding siblings survive.""" + root = tmp_path / "standards" + delivered = _write(root / "a\nb.md", "always", body="Already delivered.") + sibling = _write(root / "a\ufffdb.md", "always", body="Folder-only sibling.") + outside = tmp_path / "outside" / "not-walked.md" + delivered_path = str(delivered.resolve()) + sibling_path = str(sibling.resolve()) + outside_path = str(outside.absolute()) + read_paths: list[str] = [] + resolved_delivered_inputs: list[str] = [] + validated_delivered_inputs: list[str] = [] + real_read = folder_steering.safe_read_file_bytes_nolink + real_realpath = os.path.realpath + real_validate = folder_steering.validate_file_path + + def recording_read(path: str, *args, **kwargs): + read_paths.append(path) + return real_read(path, *args, **kwargs) + + def recording_realpath(path, *args, **kwargs): + if str(path) == outside_path: + resolved_delivered_inputs.append(str(path)) + return real_realpath(path, *args, **kwargs) + + def recording_validate(path, *args, **kwargs): + if str(path) == outside_path: + validated_delivered_inputs.append(str(path)) + return real_validate(path, *args, **kwargs) + + monkeypatch.setattr(folder_steering, "safe_read_file_bytes_nolink", recording_read) + monkeypatch.setattr(os.path, "realpath", recording_realpath) + monkeypatch.setattr(folder_steering, "validate_file_path", recording_validate) + + docs = collect_folder_steering( + [str(root)], + project=None, + home=_fake_home(tmp_path), + delivered_sources=(delivered_path, outside_path), + ) + + assert [path for path, _ in docs] == [sibling_path] + assert delivered_path not in read_paths + assert docs[0][1].strip() == "Folder-only sibling." + assert folder_steering._source_label(delivered_path) == folder_steering._source_label( + sibling_path + ) + assert resolved_delivered_inputs == [] + assert validated_delivered_inputs == [] + + def test_project_and_home_kiro_steering_are_skipped(tmp_path): """On a provider with its own steering path, project and global steering are not resent (the default; the provider-aware switch is pinned in diff --git a/test/test_folder_steering_provider_dedup.py b/test/test_folder_steering_provider_dedup.py index f28dad2b9bd8..974c1417744e 100644 --- a/test/test_folder_steering_provider_dedup.py +++ b/test/test_folder_steering_provider_dedup.py @@ -12,6 +12,7 @@ from __future__ import annotations +import json from pathlib import Path import pytest @@ -54,6 +55,7 @@ def trees(tmp_path, monkeypatch): _write(tmp_path / "standards" / "own.md", OWN_RULE) monkeypatch.setenv("HOME", str(home)) monkeypatch.setenv("USERPROFILE", str(home)) + monkeypatch.setenv("KIRO_HOME", str(home / ".kiro")) monkeypatch.setattr(Path, "home", classmethod(lambda cls: home)) return { "home": home, @@ -66,6 +68,15 @@ def trees(tmp_path, monkeypatch): } +def _opt_out(project: Path) -> None: + """The workspace tells kiro-cli not to load its default resources.""" + settings = project / ".kiro" / "settings" / "cli.json" + settings.parent.mkdir(parents=True, exist_ok=True) + settings.write_text( + json.dumps({"chat.disableInheritingDefaultResources": True}), encoding="utf-8" + ) + + @pytest.mark.parametrize( ("provider_type", "native", "delivered"), [ @@ -77,8 +88,43 @@ def trees(tmp_path, monkeypatch): ("acme-config-authored-harness", False, False), ], ) -def test_project_steering_delivered_names_every_existing_path(provider_type, native, delivered): - assert _project_steering_delivered(provider_type, native) is delivered +def test_project_steering_delivered_names_every_existing_path( + trees, provider_type, native, delivered +): + assert _project_steering_delivered(provider_type, native, str(trees["project"])) is delivered + + +@pytest.mark.parametrize( + ("provider_type", "native", "delivered"), + [ + (PROVIDER_ACP, False, False), + (PROVIDER_CLAUDE_CODE, False, True), + (PROVIDER_LABEL_KAS, True, True), + (PROVIDER_LABEL_CODEX, False, False), + ], +) +def test_the_opt_out_removes_only_the_kiro_cli_path(trees, provider_type, native, delivered): + """``chat.disableInheritingDefaultResources`` is kiro-cli's setting: on kiro it + means nobody loads the trees, and on every other harness it means nothing.""" + _opt_out(trees["project"]) + assert _project_steering_delivered(provider_type, native, str(trees["project"])) is delivered + + +@pytest.mark.parametrize("driver_verdict", [False, True]) +def test_the_kiro_cli_verdict_is_the_drivers(trees, monkeypatch, driver_verdict): + """On kiro the verdict is the ACP driver's reading of the setting, nothing else.""" + from kiro_crew.agent_sdk.drivers import acp as acp_driver + + asked: list[object] = [] + + def patched(work_dir): + asked.append(work_dir) + return driver_verdict + + monkeypatch.setattr(acp_driver, "inherits_default_resources", patched) + project = str(trees["project"]) + assert _project_steering_delivered(PROVIDER_ACP, False, project) is driver_verdict + assert asked == [project] @_needs_pinned_walk @@ -139,3 +185,73 @@ def test_a_provider_that_delivers_the_trees_does_not_receive_them_twice( assert OWN_RULE in section assert PROJECT_RULE not in section assert GLOBAL_RULE not in section + + +REINJECT_HEADER = "[REINJECTED AFTER COMPACTION -- folder steering]" + + +def _kiro_turn(tmp_path, trees, *, fresh: bool) -> str: + """A non-member kiro-cli turn: a fresh session, or the one after a compaction.""" + msg, _ = _builder(tmp_path).build_message( + "hello", + fresh, + "dashboard:kiro", + provider_type=PROVIDER_ACP, + project=str(trees["project"]), + steering_dirs=trees["dirs"], + needs_reinjection=not fresh, + ) + return msg + + +@_needs_pinned_walk +def test_an_opted_out_kiro_chat_receives_the_trees_once_through_the_folder(tmp_path, trees): + """On kiro in an opted-out workspace nobody else loads the declared trees. + + The folder section carries their always documents, once, both at session + start and when it is re-injected after a compaction; a manual document under + the same root keeps its native trigger. + """ + _write( + trees["project"] / ".kiro" / "steering" / "manual.md", + "---\ninclusion: manual\n---\nMANUAL-ONLY-4c2d", + ) + _opt_out(trees["project"]) + fresh = _kiro_turn(tmp_path, trees, fresh=True) + section = fresh[fresh.index(FOLDER_STEERING_HEADER) :] + for rule in (PROJECT_RULE, GLOBAL_RULE, OWN_RULE): + assert section.count(rule) == 1 + assert "MANUAL-ONLY-4c2d" not in fresh + + reinjected = _kiro_turn(tmp_path, trees, fresh=False) + block = reinjected[reinjected.index(REINJECT_HEADER) :] + for rule in (PROJECT_RULE, GLOBAL_RULE, OWN_RULE): + assert block.count(rule) == 1 + assert "MANUAL-ONLY-4c2d" not in reinjected + + +@_needs_pinned_walk +def test_an_inheriting_kiro_chat_still_skips_the_trees_after_a_compaction(tmp_path, trees): + reinjected = _kiro_turn(tmp_path, trees, fresh=False) + block = reinjected[reinjected.index(REINJECT_HEADER) :] + assert OWN_RULE in block + assert PROJECT_RULE not in block + assert GLOBAL_RULE not in block + + +@_needs_pinned_walk +def test_an_opted_out_workspace_changes_nothing_for_another_harness(tmp_path, trees): + """Codex kept delivering the trees through the folder before; the opt-out is + a kiro-cli setting, so it keeps doing exactly that and nothing more.""" + _opt_out(trees["project"]) + msg, _ = _builder(tmp_path).build_message( + "hello", + True, + "dashboard:codex", + provider_type=PROVIDER_LABEL_CODEX, + project=str(trees["project"]), + steering_dirs=trees["dirs"], + ) + section = msg[msg.index(FOLDER_STEERING_HEADER) :] + for rule in (PROJECT_RULE, GLOBAL_RULE, OWN_RULE): + assert section.count(rule) == 1 diff --git a/test/test_member_essential_context.py b/test/test_member_essential_context.py index 76d77cf00e2c..badd251f2f5d 100644 --- a/test/test_member_essential_context.py +++ b/test/test_member_essential_context.py @@ -1,5 +1,6 @@ """V2 keeps actual essential sources complete through every provider lifecycle.""" +import gc import json import os import threading @@ -11,6 +12,8 @@ from conftest import make_dir_link, requires_symlinks from kiro_crew import context as context_module +from kiro_crew import pinned_fs +from kiro_crew.agent_sdk.provider_identity import PROVIDER_ACP, PROVIDER_CLAUDE_CODE from kiro_crew.config.loader import KiroCrewAgentConfig, KiroCrewConfig from kiro_crew.context import CONTEXT_GROUP_LESSONS, ContextBuilder from kiro_crew.learn import LessonStore @@ -31,6 +34,25 @@ def _close_skills_loaders(close_skills_loaders): """The ``env`` fixture builds a ``SkillsLoader`` it never closes: close it (rootdir conftest).""" +@pytest.fixture +def cyclic_gc_quiesced(): + """Keep a cyclic-GC pass (and any finalizer it runs) out of a deep JSON parse. + + A recursion-limit fixture drives the parser to the bottom of the stack; a + collection firing there could run an inherited finalizer with no stack + left. Drain first, disable for the parse, then restore and drain again. + """ + gc.collect() + was_enabled = gc.isenabled() + gc.disable() + try: + yield + finally: + if was_enabled: + gc.enable() + gc.collect() + + @pytest.fixture def env(tmp_path, monkeypatch): home = tmp_path / "host-home" @@ -1686,3 +1708,446 @@ def test_resources_still_refuse_an_entry_that_is_neither_uri_nor_object(env, mal projected_resource_documents( {"id": "writer-template", "resources": resources}, str(env.project) ) + + +_OPERATOR_RULE = "Operator rule: ask before every comment." +_INHERITED_PROJECT_GUIDES = ( + "Project rules: run the review checks.", + "Always guide: explain assumptions.", +) + + +@pytest.fixture +def operator_steering(env): + """One global steering file, the operator's own rule the member may not want.""" + steering = Path.home() / ".kiro" / "steering" + steering.mkdir(parents=True, exist_ok=True) + (steering / "operator.md").write_text(_OPERATOR_RULE, encoding="utf-8") + return env + + +def _write_kiro_settings(kiro_dir: Path, values: dict) -> None: + path = kiro_dir / "settings" / "cli.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(values), encoding="utf-8") + + +def _snapshot_bodies(env, provider_type: str = PROVIDER_ACP) -> str: + """The member's essential envelope as a session served by *provider_type* builds it. + + The builder is where the harness is known, so it is the builder that decides + whether kiro-cli's opt-out applies; :func:`documents_for_member` only takes + that verdict. kiro-cli is the default because it is the harness the setting + belongs to. + """ + return env.builder._build_v2_essentials( + env.store, member=env.member, project=str(env.project), provider_type=provider_type + ) + + +def test_workspace_opt_out_keeps_only_what_the_template_declares(operator_steering): + """kiro-cli gives an opted-out custom agent only its declared resources. + + The snapshot is what the member works from, so it must not hand back the + operator's global steering, AGENTS.md or undeclared workspace steering. + """ + env = operator_steering + assert _OPERATOR_RULE in _snapshot_bodies(env) + + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": True}) + bodies = _snapshot_bodies(env) + assert _OPERATOR_RULE not in bodies + for guide in _INHERITED_PROJECT_GUIDES: + assert guide not in bodies + assert "Declared guide: examples must be reproducible." in bodies + assert "Bound Soul: preserve the user's voice." in bodies + assert "Project Soul: write with empathy." in bodies + + +def test_opt_out_still_loads_steering_the_template_declares(operator_steering): + env = operator_steering + (env.project / ".kiro" / "agents" / "writer-template.json").write_text( + json.dumps({"name": "writer-template", "resources": ["file://.kiro/steering/**/*.md"]}), + encoding="utf-8", + ) + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": True}) + bodies = _snapshot_bodies(env) + assert "Always guide: explain assumptions." in bodies + assert _OPERATOR_RULE not in bodies + + +@pytest.mark.parametrize( + ("source", "global_opt_out", "expected"), + [ + ("local", False, True), + ("local", True, True), + ("global", False, True), + ("global", True, False), + ], +) +def test_crew_overlay_is_not_read_as_an_opt_out( + operator_steering, source, global_opt_out, expected +): + """The projection pins the native key to true and records the real choice beside it.""" + env = operator_steering + _write_kiro_settings( + env.project / ".kiro", + { + "chat.disableInheritingDefaultResources": True, + "kirocrew.skillDiscovery.inheritFiles": True, + "kirocrew.skillDiscovery.inheritSource": source, + }, + ) + if global_opt_out: + _write_kiro_settings( + Path.home() / ".kiro", {"chat.disableInheritingDefaultResources": True} + ) + assert (_OPERATOR_RULE in _snapshot_bodies(env)) is expected + + +@pytest.mark.parametrize(("workspace_value", "expected"), [(None, False), (False, True)]) +def test_global_opt_out_applies_unless_the_workspace_overrides_it( + operator_steering, workspace_value, expected +): + env = operator_steering + _write_kiro_settings(Path.home() / ".kiro", {"chat.disableInheritingDefaultResources": True}) + if workspace_value is not None: + _write_kiro_settings( + env.project / ".kiro", {"chat.disableInheritingDefaultResources": workspace_value} + ) + assert (_OPERATOR_RULE in _snapshot_bodies(env)) is expected + + +@pytest.mark.parametrize("value", ["true", 1]) +def test_only_the_literal_true_opts_out(operator_steering, value): + env = operator_steering + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": value}) + assert _OPERATOR_RULE in _snapshot_bodies(env) + + +@pytest.mark.parametrize( + "contents", + ["{not json", "[" * 100_000 + "]" * 100_000], + ids=["malformed", "deeply-nested"], +) +def test_unreadable_settings_keep_inherited_guides(operator_steering, contents, cyclic_gc_quiesced): + env = operator_steering + settings = env.project / ".kiro" / "settings" / "cli.json" + settings.parent.mkdir(parents=True, exist_ok=True) + settings.write_text(contents, encoding="utf-8") + assert _OPERATOR_RULE in _snapshot_bodies(env) + + +@requires_symlinks +def test_cyclic_kiro_home_keeps_inherited_guides(operator_steering, monkeypatch): + env = operator_steering + loop = env.project.parent / "kiro-home-loop" + os.symlink(loop, loop) + monkeypatch.setenv("KIRO_HOME", str(loop)) + + from kiro_crew.acp import skill_projection + + assert skill_projection.inherits_default_resources(env.project) is True + assert _OPERATOR_RULE in _snapshot_bodies(env) + + +def test_launch_documents_follow_the_workspace_opt_out(operator_steering): + from kiro_crew.member_essential_context import kiro_launch_documents + + env = operator_steering + + def launched() -> list[str]: + return [body for _, body in kiro_launch_documents("writer-template", str(env.project))] + + assert _OPERATOR_RULE in launched() + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": True}) + bodies = launched() + assert _OPERATOR_RULE not in bodies + assert "Project rules: run the review checks." not in bodies + assert "Declared guide: examples must be reproducible." in bodies + + +def _envelope_with_folder_steering_trees(env, provider_type: str = PROVIDER_ACP) -> str: + """A member turn in a folder that declares both ``.kiro/steering`` trees.""" + message, _ = env.builder.build_message( + "Continue", + True, + "dashboard:member", + memory_store=env.store, + member=env.member, + project=str(env.project), + provider_type=provider_type, + steering_dirs=( + str(env.project / ".kiro" / "steering"), + str(Path.home() / ".kiro" / "steering"), + ), + ) + env.forbidden.assert_not_called() + return message + + +_OTHER_HARNESSES = pytest.mark.parametrize( + "provider_type", [PROVIDER_CLAUDE_CODE, "codex", "acme-config-authored-harness"] +) + + +@_OTHER_HARNESSES +def test_opt_out_binds_only_a_session_kiro_cli_serves(operator_steering, provider_type): + """``chat.disableInheritingDefaultResources`` is kiro-cli's setting. + + On any other harness the member keeps the operator's global steering, + ``AGENTS.md`` and the project's always steering: the setting changes what a + member loads only on a session kiro-cli serves. + """ + env = operator_steering + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": True}) + assert _OPERATOR_RULE not in _snapshot_bodies(env) + bodies = _snapshot_bodies(env, provider_type=provider_type) + assert _OPERATOR_RULE in bodies + for guide in _INHERITED_PROJECT_GUIDES: + assert guide in bodies + + +def _count_setting_reads(monkeypatch) -> list[object]: + """Record every call of the one settings reader behind the verdict.""" + from kiro_crew.agent_sdk.drivers import acp as acp_driver + + reads: list[object] = [] + real = acp_driver.inherits_default_resources + + def counted(work_dir): + reads.append(work_dir) + return real(work_dir) + + monkeypatch.setattr(acp_driver, "inherits_default_resources", counted) + return reads + + +def test_profile_validation_measures_inheriting_envelope_without_reading_setting( + operator_steering, monkeypatch +): + """Validation measures the largest envelope, independent of the current harness.""" + env = operator_steering + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": True}) + reads = _count_setting_reads(monkeypatch) + + validation = env.builder._build_v2_essentials( + env.store, + member=env.member, + project=str(env.project), + profile_overrides={"preferences.md": "Candidate preference."}, + ) + + assert "Candidate preference." in validation + assert _OPERATOR_RULE in validation + for guide in _INHERITED_PROJECT_GUIDES: + assert guide in validation + assert reads == [] + + normal_turn = _snapshot_bodies(env) + assert _OPERATOR_RULE not in normal_turn + for guide in _INHERITED_PROJECT_GUIDES: + assert guide not in normal_turn + assert len(reads) == 1 + + +def test_documents_for_member_takes_the_verdict_and_never_reads_the_setting( + operator_steering, monkeypatch +): + """The snapshot reader is a consumer: without the caller's verdict it inherits.""" + from kiro_crew.member_essential_context import documents_for_member + + env = operator_steering + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": True}) + reads = _count_setting_reads(monkeypatch) + bodies = [body for _, body in documents_for_member("writer-template", str(env.project))] + assert _OPERATOR_RULE in bodies + opted_out = [ + body + for _, body in documents_for_member( + "writer-template", str(env.project), inherits_default_resources=False + ) + ] + assert _OPERATOR_RULE not in opted_out + assert reads == [] + + +_needs_pinned_walk = pytest.mark.skipif( + not pinned_fs.supports_pinned_tree_walk(), + reason="folder steering refuses to walk by name on this platform", +) + + +def _declare_project_steering_in_template(env) -> None: + path = env.project / ".kiro" / "agents" / "writer-template.json" + spec = json.loads(path.read_text(encoding="utf-8")) + spec["resources"].append("file://.kiro/steering/**/*.md") + path.write_text(json.dumps(spec), encoding="utf-8") + + +@_needs_pinned_walk +def test_folder_declared_steering_trees_reach_an_opted_out_member_once(operator_steering): + """The snapshot skips the trees, so the folder dedup must not skip them too. + + Otherwise an always-inclusion document under a declared root reaches the + member zero times: the snapshot leaves it to kiro-cli, which the workspace + told not to load it, and the folder section assumes the snapshot sent it. + """ + env = operator_steering + _declare_project_steering_in_template(env) + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": True}) + message = _envelope_with_folder_steering_trees(env) + assert message.count(_OPERATOR_RULE) == 1 + assert message.count("Always guide: explain assumptions.") == 1 + # AGENTS.md is a kiro-cli default resource, not a steering document, so the + # folder does not carry it back in. + assert "Project rules: run the review checks." not in message + assert "MANUAL_SECRET" not in message + + +@_needs_pinned_walk +def test_opted_out_folder_dedup_does_not_resolve_source_labels(operator_steering, monkeypatch): + """Canonical dedup does not re-resolve the collector's emitted labels.""" + from kiro_crew import member_essential_context as essential_context + + env = operator_steering + _declare_project_steering_in_template(env) + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": True}) + + snapshot_sources: set[str] = set() + folder_sources: set[str] = set() + dedup_started = False + resolved_labels: list[str] = [] + real_documents_for_member = essential_context.documents_for_member + real_collect_folder_steering = context_module.collect_folder_steering + real_realpath = os.path.realpath + + def recording_documents_for_member(*args, **kwargs): + result = real_documents_for_member(*args, **kwargs) + snapshot_sources.update(source for source, _body in result) + return result + + def recording_collect_folder_steering(*args, **kwargs): + nonlocal dedup_started + result = real_collect_folder_steering(*args, **kwargs) + folder_sources.update(source for source, _body in result.documents) + dedup_started = True + return result + + def recording_realpath(path, *args, **kwargs): + spelling = str(path) + if dedup_started and spelling in snapshot_sources | folder_sources: + resolved_labels.append(spelling) + return real_realpath(path, *args, **kwargs) + + monkeypatch.setattr(essential_context, "documents_for_member", recording_documents_for_member) + monkeypatch.setattr( + context_module, "collect_folder_steering", recording_collect_folder_steering + ) + monkeypatch.setattr(os.path, "realpath", recording_realpath) + + message = _envelope_with_folder_steering_trees(env) + + assert message.count("Always guide: explain assumptions.") == 1 + assert resolved_labels == [] + + +@_needs_pinned_walk +@pytest.mark.parametrize( + ("template_name", "folder_name"), + [ + ("a\ufffdb.md", "a\nb.md"), + ("a\nb.md", "a\ufffdb.md"), + ], + ids=["template-replacement", "template-newline"], +) +def test_opted_out_folder_dedup_keeps_distinct_fold_colliding_sources( + operator_steering, template_name, folder_name +): + """Distinct canonical files survive even when their rendered labels collide.""" + env = operator_steering + steering = env.project / ".kiro" / "steering" + template_body = "Template-only folded-label guide." + folder_body = "Folder-only folded-label guide." + (steering / template_name).write_text(template_body, encoding="utf-8") + (steering / folder_name).write_text(folder_body, encoding="utf-8") + spec_path = env.project / ".kiro" / "agents" / "writer-template.json" + spec = json.loads(spec_path.read_text(encoding="utf-8")) + spec["resources"].append(f"file://.kiro/steering/{template_name}") + spec_path.write_text(json.dumps(spec), encoding="utf-8") + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": True}) + + message = _envelope_with_folder_steering_trees(env) + + assert message.count(template_body) == 1 + assert message.count(folder_body) == 1 + + +@_needs_pinned_walk +def test_opted_out_folder_dedup_matches_control_folded_source_label(operator_steering): + """A control character folded out of a folder label does not duplicate its body.""" + env = operator_steering + folded = env.project / ".kiro" / "steering" / "folded\nname.md" + folded.write_text("Folded label guide: keep one copy.", encoding="utf-8") + _declare_project_steering_in_template(env) + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": True}) + + message = _envelope_with_folder_steering_trees(env) + + assert message.count("Folded label guide: keep one copy.") == 1 + + +@_needs_pinned_walk +def test_folder_declared_steering_trees_reach_an_inheriting_member_once(operator_steering): + env = operator_steering + _declare_project_steering_in_template(env) + message = _envelope_with_folder_steering_trees(env) + assert message.count(_OPERATOR_RULE) == 1 + assert message.count("Always guide: explain assumptions.") == 1 + assert message.count("Project rules: run the review checks.") == 1 + + +@_needs_pinned_walk +@_OTHER_HARNESSES +def test_folder_declared_steering_trees_reach_an_opted_out_member_once_on_another_harness( + operator_steering, provider_type +): + """The opted-out workspace is irrelevant off kiro-cli: the snapshot delivers + the trees, so the folder skips them and each guide arrives exactly once.""" + env = operator_steering + _declare_project_steering_in_template(env) + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": True}) + message = _envelope_with_folder_steering_trees(env, provider_type=provider_type) + assert message.count(_OPERATOR_RULE) == 1 + assert message.count("Always guide: explain assumptions.") == 1 + assert message.count("Project rules: run the review checks.") == 1 + assert "MANUAL_SECRET" not in message + + +@_needs_pinned_walk +@pytest.mark.parametrize("opted_out", [False, True]) +def test_a_kiro_member_turn_reads_the_setting_exactly_once( + operator_steering, monkeypatch, opted_out +): + """One verdict per turn feeds the snapshot and the folder dedup alike.""" + env = operator_steering + _declare_project_steering_in_template(env) + if opted_out: + _write_kiro_settings( + env.project / ".kiro", {"chat.disableInheritingDefaultResources": True} + ) + reads = _count_setting_reads(monkeypatch) + message = _envelope_with_folder_steering_trees(env) + assert message.count(_OPERATOR_RULE) == 1 + assert len(reads) == 1 + + +@_needs_pinned_walk +@_OTHER_HARNESSES +def test_another_harness_never_reads_the_setting(operator_steering, monkeypatch, provider_type): + env = operator_steering + _declare_project_steering_in_template(env) + _write_kiro_settings(env.project / ".kiro", {"chat.disableInheritingDefaultResources": True}) + reads = _count_setting_reads(monkeypatch) + _envelope_with_folder_steering_trees(env, provider_type=provider_type) + assert reads == [] diff --git a/test/test_native_skill_projection.py b/test/test_native_skill_projection.py index c9546d5cf85d..bdfa8184bf36 100644 --- a/test/test_native_skill_projection.py +++ b/test/test_native_skill_projection.py @@ -3318,3 +3318,50 @@ def test_a_read_only_agents_directory_produces_the_refusal_warning( assert "EACCES" in warnings[0].getMessage() assert "is not writable by this process" in warnings[0].getMessage() assert all(p.exists() for p in backlog) + + +@pytest.mark.parametrize( + ("workspace", "global_value"), + [ + ({}, None), + ({"chat.disableInheritingDefaultResources": True}, None), + ({}, True), + ({"chat.disableInheritingDefaultResources": False}, True), + ({"chat.disableInheritingDefaultResources": "true"}, None), + ], +) +def test_reader_agrees_with_the_projection_across_its_overlay(native_tree, workspace, global_value): + """Readers that mirror native loading must decode Crew's overlay as the projection wrote it. + + After the projection runs, the workspace's native key reads ``true`` whatever + the user chose, so a reader of the raw key would see an opt-out everywhere. + """ + home, agents, project = native_tree + (agents / "custom.json").write_text('{"name":"custom"}', encoding="utf-8") + if workspace: + settings = project / ".kiro" / "settings" / "cli.json" + settings.parent.mkdir(parents=True) + settings.write_text(json.dumps(workspace), encoding="utf-8") + if global_value is not None: + settings = home / "settings" / "cli.json" + settings.parent.mkdir(parents=True) + settings.write_text( + json.dumps({"chat.disableInheritingDefaultResources": global_value}), encoding="utf-8" + ) + before = projection.inherits_default_resources(project) + prepared = projection.prepare_native_skill_projection(project) + projected = any("steering" in item for item in prepared.specs["custom"]["resources"]) + assert before is projected + assert projection.inherits_default_resources(project) is projected + + +def test_reader_follows_a_live_global_preference_under_the_overlay(native_tree): + home, agents, project = native_tree + (agents / "custom.json").write_text('{"name":"custom"}', encoding="utf-8") + settings = home / "settings" / "cli.json" + settings.parent.mkdir() + settings.write_text('{"chat.disableInheritingDefaultResources":true}', encoding="utf-8") + projection.prepare_native_skill_projection(project) + assert projection.inherits_default_resources(project) is False + settings.write_text('{"chat.disableInheritingDefaultResources":false}', encoding="utf-8") + assert projection.inherits_default_resources(project) is True