Skip to content

fix(dashboard): scope folder agent picker to the folder's project dir - #10107

Closed
mbajaj92 wants to merge 1 commit into
kirodotdev:mainfrom
mbajaj92:fix/folder-project-agent-picker
Closed

mbajaj92 wants to merge 1 commit into
kirodotdev:mainfrom
mbajaj92:fix/folder-project-agent-picker

Conversation

@mbajaj92

@mbajaj92 mbajaj92 commented Sep 11, 2026 •

Copy link
Copy Markdown

Problem / Motivation

Goal: let a chat folder's Default agent be chosen from the agents its own
project directory declares, and refuse — in the modal and on the server — an
agent that directory cannot be confirmed to have.

A chat folder can carry a Project directory. A project can define its own
agents in <project>/.kiro/agents/*.json. Those agents never show up in the
folder's Default agent dropdown. Only the global agents show. So you cannot
pick a project's own agent as a folder's default.

Why it matters

Picking a project's own agent as the default for a folder of chats is the whole
point of setting a project directory on that folder. Today it is impossible: the
agent you want is not in the list. This is the folder-side twin of #8952, which
is the same bug on the Schedule page.

Not a goal

Resolving a folder's default agent server-side. Which agent a new chat gets
stays where it is — the sidebar's own folder actions apply it, and an agent-less
API create still stamps the global default. This PR decides what may be
stored, not who applies it.

Re-validating descendants when a parent folder's project directory later changes,
and re-checking a stored agent that no request touches. The check runs on the
create and update paths, on the value a caller is setting.

Windows folder-level project-agent selection. A platform that cannot pin a
directory descriptor answers scan_unsupported_platform rather than walking a
caller-supplied path by name; the pre-existing session-derived readers keep
working there unchanged.

What changed (motivation → approach → change)

GET /api/agents derived the project from the active chat; creating a folder has
none, so a folder's own project agents never appeared.

It now reads an explicit ?project_path= and lists that directory's project agents.
The scan is owner-only and every attempt is SEL-audited — allowed for a real
directory, denied for a sensitive one or a non-owner. A bad or blocked path falls
back to the old behaviour.

components/FolderConfigModal.tsx requests the roster for the directory you typed,
debounced, and scopes the dropdown to it; website/src/api/client/agents.ts passes
it through. An agent the directory lacks is flagged and blocks submission,
while an existing folder's saved-but-absent agent still round-trips a rename.

chat_folders.py enforces the same rule independently, so the refusal does not
depend on which picker is in front of it. On create and update — including a
parent_id-only move, which shifts the inherited directory — it checks the folder's
effective agent against its effective scope, answering default_agent_out_of_scope,
or 503 default_agent_scope_unverifiable / scan_unsupported_platform when that
scope cannot be read. Accepted global names come from the same execution catalog the
picker reads, so a selectable template is never refused. A non-person caller is held
to those global names and its supplied directory is never scanned, so the refusal
cannot become an existence oracle. One supplying neither an agent nor a directory
inherits its parent's already-checked pair and is accepted with no scan.

flowchart LR
  subgraph Before
    A1[Open folder settings]:::ctx --> B1[dropdown = active chat's agents]:::removed --> C1[project agents absent]:::removed
  end
  subgraph After
    A2[Open folder settings]:::ctx --> B2[fetch agents for the folder's dir]:::added --> C2[project agents listed]:::added
  end
  classDef added fill:#DCFCE7,stroke:#16A34A,color:#14532D,stroke-width:2px
  classDef changed fill:#FEF3C7,stroke:#D97706,color:#78350F,stroke-width:2px
  classDef removed fill:#FEE2E2,stroke:#DC2626,color:#7F1D1D,stroke-dasharray:4 3
  classDef ctx fill:#E0F2FE,stroke:#0284C7,color:#0C4A6E
  linkStyle 0,1 stroke:#DC2626,stroke-dasharray:4 3
  linkStyle 2,3 stroke:#16A34A,stroke-width:2px
Loading

Reading a directory the caller supplied

A UNC spelling is refused
before any filesystem call and again on the resolved value, through the
hooks.is_unc_shape / unc_probe_allowed gate:
resolving \\host\share is an outbound SMB connection. Otherwise it goes through
pinned_fs.py, which gains open_fenced_for_read_at for this: the chain to
<project_dir>/.kiro/agents is opened component by component and each entry is read
from the held descriptor, so nothing is addressed by name after being checked. Where pinning is unavailable, raise_unverifiable stays false
and the by-name fallback preserves discovery, as the session-derived readers do.

First Principles read the walk as oversized, on the argument that
_read_agent_spec's per-file fence already covers it. Stated here because it is
the kind of thing a reviewer should be able to rule on from the description: the
fence cannot cover it, because ?project_path= answers with the name list
derived from the directory listing
, and the per-file fence only applies once
that list exists. A component swapped between the sensitivity verdict and the
listing yields names enumerated from a directory the verdict never approved, and
no per-file check is ever reached for a name that is merely reported.

Saving a folder's project directory

chat_folders._validate_project_dir deliberately does not apply the UNC /
link-chain screen — only the absolute-path, sensitive-path and directory-exists
checks it already had on main. First Principles blocked an earlier revision that
added the screen here, and the objection was right: this validator also re-checks
STORED values on the slot-create read path, where any refusal becomes a 400
folder_project_invalid and the folder can open no session at all.
hooks._screen_windows_links refuses far more than an untrusted share — a
readlink OSError, a .. suffix, a target it cannot normalize, and its own chain
and depth limits all refuse — so screening here would let an ordinary Windows
junction behind someone's already-saved project directory stop that folder from
starting a chat, on a premise untested on Windows. The screen stays where this PR
needs it: the ?project_path= roster read, where it gates a listing rather than
session start. For a stored value the spawn guard remains the authority, exactly as
_folder_project_overlap_denied already says of its own check.

Why the save path enforces as well as the picker

check_folder_agent_scope re-checks the agent/project pair server-side on save,
answering 400 for a scope violation and 503 when the roster scan cannot complete.
Design Review and First Principles both read that as a second enforcement layer and
asked whether the picker's filtering already covers it. It is deliberate, and kept:
the picker narrows what a UI offers, while the endpoint is reachable directly, so
treating a filtered list as the enforcement point would leave the control advisory.
The 503 is fail-closed for the same reason — an unreadable roster cannot prove the
pair is in scope, so it is refused rather than admitted.

The smaller pieces

agent_spec_format.py's split_listed_spec_paths drops a <name>.md with a
<name>.json twin, reusing entries the scan already holds. agent_discovery.py keeps
one verdict per scope: _scan_project_agent_files carries the pinned
walk, and its three callers each decide sensitivity once, before any read.
dashboard/chat_handlers.py carries the folder's directory into a folder-scoped slot
create. Strings live in en.manual.json across twelve catalogs;
docs/feature-map/README.md registers the control, and
.github/black-baseline.txt drops one now-clean file.

Backwards compatibility

Compatible. ?project_path= is a new optional query parameter; a request without
it resolves the project from the session exactly as before, and an invalid or
refused value falls back to that same path rather than erroring. No existing
response field changes meaning — scope is still "global" | "project" on every
row. A folder with no default agent, and a folder whose saved agent is still
present, both behave as they do on main.

POST/PATCH /api/chat/folders gains one refusal: a request that sets a
default agent the folder's effective project directory cannot be confirmed to have
is rejected instead of stored. Clearing the agent, omitting it, and re-sending an
existing folder's own saved agent unchanged are all untouched, so a rename or
recolor of a folder whose agent has since disappeared still succeeds. Project
scaffolding sets no agent of its own, so it is refused only when it also carries a
directory and the inherited agent is not globally installed — a refusal that lands
in its per-folder failed channel. That server-side refusal is deliberate defense in
depth rather than a duplicate of the modal's own gate: the modal withholds Save and
the endpoint refuses independently, so a caller that never went through the picker
is refused too.

One deliberate narrowing for a non-person principal: an app or crew-member caller
setting a folder's default agent is held to the global names and its supplied
project_dir is not scanned for that check. Such a caller can still set any global
agent and any directory; what it cannot do is have the gateway read a directory it
merely named, which is what would turn the refusal into an existence oracle.

The pre-existing readers are never refused for lack of pinning support, so
project-agent discovery still resolves for them on every platform: they take the
by-name walk everywhere, uncapped, exactly as on main. Only an owner-supplied
path reaches the descriptor-pinned walk, which refuses an ancestor swapped
mid-walk instead of following it, and refuses rather than truncating.
agent_discovery._link_chain_refused screens the owner-supplied paths instead
(?project_path= and a folder's project_dir). It invents no new screen: it asks
the one hooks.validate_file_path already runs, hooks._screen_windows_links,
which reads each link's stored target locally (os.readlink connects to no host),
refuses an untrusted share or an ambiguous root- or drive-relative target, then
swaps a vetted target in and walks the rewritten path again so a deeper link under
a benign one is still reached. It is called directly rather than through
validate_file_path so the caller keeps its own sensitive-path refusal and audit
reason, and off Windows it never refuses.

Readers:

  • Reader: api_chat_folder_create (POST /api/chat/folders) -> the sidebar
    modal create (website/src/pages/chat-sidebar/folders.ts): refused 400/503 only
    for an effective agent outside the effective scope, which the modal already
    gates before Save.
  • Reader: mcp_dashboard chat_folder_create and its path walk (_post,
    name + parent only): unaffected; a non-owner naming no agent and no directory
    inherits its parent's pair without a scan.
  • Reader: cron_script.py folder create (name only, top level): unaffected; its
    effective agent is the global default.
  • Reader: chat_folder_scaffold.py root and child create_folder_record calls:
    a candidate whose inherited or global agent the new folder's directory cannot
    confirm lands in the per-folder failed channel; the root failing still
    short-circuits the call.
  • Reader: PATCH /api/chat/folders/{id} sidebar drag (useSidebarDrag.ts,
    {parent_id}): an unchanged own agent under its own directory moves without a
    scan on every platform; an inheriting child moved under a different chain is
    re-validated and can 400/503.
  • Reader: PATCH rename and collapse (ChatSidebar.tsx, folders.ts,
    create.ts, useSidebarDrag.ts): unaffected; no agent, directory or parent.
  • Reader: PATCH from the folder modal (ChatSidebar.tsx): sends touched fields
    only, so it is re-validated only when the agent or directory was edited.
  • Reader: mcp_dashboard chat_folder_move (_patch, parent_id): an app
    principal is validated against the global catalog only, so moving a folder
    whose own agent is project-only is refused 400.

Tests

  • test/test_agents_roster_contract.py — the ?project_path= contract:
    owner-only, the SEL allowed/denied records, fallback to the slot on an
    absent or refused value, and the denied-versus-empty sentinel distinction.
  • test/test_agent_discovery.py — the pinned walk: a symlinked component is
    refused, a missing .kiro is not an error, and
    test_no_pinned_walk_support_still_scans_by_name_when_opted_in pins that the
    pre-existing callers keep working where the pinned walk is unavailable, so the
    capability gate cannot silently widen to them.
  • website/src/test/FolderConfigModal.test.tsx — the picker: the roster is
    fetched for the typed directory, a freshly picked absent agent blocks
    submission, each of the four flags renders for its own case, and a seeded
    orphan agent still round-trips a rename.
  • test/test_markdown_agent_specs.py — a <name>.md with a <name>.json twin
    lists once in the project scope.
  • test/test_chat_folder_agent_scope.py — the server-side refusal: an
    out-of-scope agent is rejected on both create and update, a global agent is
    accepted, an unreadable scope answers 503 and an unpinnable platform names
    scan_unsupported_platform, and an existing folder's own saved agent still
    round-trips. Four more pin the edges: a selectable catalog template is accepted,
    a parent_id-only move is revalidated (and the move is not persisted when it
    fails), the linked-ancestor screen runs before realpath rather than after,
    and a non-person caller's supplied directory is never scanned — asserted on both
    the refusal and the acceptance path. test/test_chat_folder_scaffold.py pins the
    one documented opt-out.
  • test/test_junction_link_fences.py — the linked-ancestor walk against real
    reparse points (a junction on Windows, a directory symlink on POSIX) rather
    than a double: a two-link chain pins that EVERY linked ancestor is yielded
    root-first, so a deeper junction under a benign shallow one is still reached,
    and that the leaf stays excluded.
  • test/test_slot_create_default_agent.py — a chat created in the folder starts
    on the folder's default agent.

Manual verification

Verified on a dev gateway: set a folder's project directory to a checkout with
.kiro/agents, confirmed its agents appear in Default agent, confirmed a
chat created in the folder starts on the picked agent, and confirmed each flag
state disables submission and names its reason. Windows behaviour is covered by
mocked-_winapi tests only — no Windows host was available.

Screenshots / video

The Default agent dropdown now lists the folder's project agents. An agent the
selected directory does not have is flagged in the trigger, and submission is
blocked until it is changed. There are four flags, kept distinct on purpose:
(not installed) for a genuinely uninstalled agent, (not in this project) for
a valid agent picked under a different directory, (can't verify) when the scan
itself failed — so absence is unproven rather than established — and
(needs a project directory) for an agent only a project directory could supply
when no directory is set.

Folder settings, Default agent dropdown open, listing the folder's project
agents (repo-dev, repo-reviewer) above the globals, with
Inherit (kirocrew) at the top:

Default agent dropdown open, listing the folder's project agents above the globals

A project agent picked against a directory that scanned cleanly, as the baseline
for the states below. The hint states what the pick means: it is pre-selected for
new chats created in this folder.

project agent picked against a directory that scanned, pre-selected for new chats hint

While the roster for a newly-typed directory is being fetched, submission is
disabled and the picker still shows the previous scope's agents. The
Loading agents… hint is what explains the disabled button, matching the
Loading tags… hint the Tags field two rows up already shows:

roster loading: Loading agents hint under Default agent, Save changes disabled

Once the roster arrives the hint clears and Save recovers:

roster loaded: hint cleared, Save changes recovered

Both frames come from node scripts/capture-folder-agent-roster-loading.mjs (from
website/), which runs the real built SPA with /api/** stubbed and holds the
roster route open so the in-flight frame is a real render of that state. It
asserts the hint is present and Save is disabled in the first, and that the hint
has cleared and Save has recovered in the second, so a frame that did not show
the claimed state fails the run instead of being published.

The blocked state with a project directory that scans cleanly but does not
declare the picked agent: re-scoping to /repo/other flags the trigger
repo-dev (not in this project), and the notice names both remedies — pick an
agent the directory has, or point the folder at the directory that has it.
Create folder is disabled.

agent not in the rescoped project: trigger reads repo-dev (not in this project), notice says the folder can't be saved and names both remedies, Create folder disabled

The blocked state with no project directory at all, reached by picking a
project agent and then clearing the directory. The Project directory field here
is empty — the grey /Users/you/code/project is its placeholder, not a value.
The trigger reads repo-dev (needs a project directory) rather than
(not in this project), because with nothing in scope there is no project to be
absent from — and it names the cause rather than the symptom, so it cannot be
misread as the separate (not installed) case. The notice
leads with the remedy that applies when nothing is scoped: pick a globally
installed agent. It names no button, because the footer differs by mode —
Cancel / Create folder when creating, Save changes when editing.

The roster-scan error state: a failed directory scan surfaces "Couldn't read this
directory's agents." with a Retry action, scrolled into view rather than left
below the modal's fold — it is the only thing naming why the button went dead.
The trigger keeps naming the pick, flagged repo-dev (can't verify): a failed
scan cannot establish that an agent is absent, only that it could not be checked.
It must never fall back to reading Inherit (default), which would show an
apparently valid form with a dead button and nothing explaining it.

scan error: trigger reads repo-dev (can't verify), Couldn't read this directory's agents with Retry in view, Create folder disabled

That frame comes from node scripts/capture-folder-agent-roster-scan-error.mjs
(from website/), a sibling of the loading harness. It answers one directory
with a roster and fails another with the same 503 the handler returns when the
audit write fails, and asserts on each frame that the trigger names the pick,
that it does not read Inherit, that submission is disabled, that the error
row's bounding box sits inside the modal's, and that the notice does not
contradict its own label.

Every frame above renders the shipped notice wording and the Enter to submit
footer hint, which is unconditional here exactly as on main.

The unsupported-platform state — the one a platform that cannot pin a directory
descriptor reaches — now names the platform rather than saying "this platform", and
its severity follows Save. Three frames cover it, produced by
node scripts/capture-folder-agent-unsupported-platform.mjs (from website/) and
also committed under temp-screenshots/10107-unsupported-platform/.

Save blocked: the roster row reads "Project agents can't be read on Windows yet.
Pick a global agent to save this folder." beside the flagged trigger
repo-dev (not supported on this platform), with no Retry — one could never succeed
where the capability is absent — and Create folder disabled.

unsupported platform, Save blocked: roster row reads Project agents can't be read on Windows yet, Pick a global agent to save this folder; no Retry; trigger flagged repo-dev (not supported on this platform); Create folder disabled

Save still working: the same refusal, but the folder takes the global default, so
nothing is unverifiable. The row drops the instruction it no longer needs and reads
"Project agents can't be read on Windows yet. Global agents still work.", sitting
beside the ordinary "Pre-selected for new chats created here." hint rather than
replacing it, with Save enabled. An explicit pick cannot reach this frame even when
the agent chosen is itself global: once a directory answers 503 the modal cannot
confirm the pick against it, and the row returns to the blocking wording.

unsupported platform, Save enabled: roster row reads Project agents can't be read on Windows yet, Global agents still work, shown beside the Pre-selected for new chats created here hint

A third committed frame shows the distinct inherited form,
Inherit (repo-dev — not supported on this platform), on a real child folder opened
through the sidebar's own Folder settings.

The harness answers the scoped roster call with the 503 the handler returns for that
capability and asserts, before writing any frame, that the row carries the copy for
the state it claims and not the other one, that it offers no Retry, that the
retryable scan-error row did not render in its place, that Save is disabled in the
blocked frame and enabled in the working one, that the pre-selection hint survives
there, and that the row sits inside the modal's visible box. A frame that did not
show the claimed state fails the run instead of being published.

The inherited-agent flag appears in no attachment because every earlier capture
scene pinned an explicit agent, so it is committed under
temp-screenshots/10107-inherited-agent-flag/ instead — the path .gitignore
documents for a contributor without attachment-upload permission, and the one
both review lanes read. capture-folder-agent-inherited-orphan.mjs produces
all four flagged states on a real child folder -- absent, dir-less, unverified,
and the unflagged baseline -- and asserts each one's own cause text, the em-dash
spelling, Save disabled and an unclipped notice before writing any frame. The
(not installed) look is pre-existing.

Related Issues

Closes #10106

Pattern harvest

Rule candidate: review-prompt
Pattern: a feature that reads a user-supplied filesystem path re-implements a
pinned walk instead of calling the module that already owns one, so the security
review lands on the copy rather than on the shared primitive.

Checklist

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

@mbajaj92
mbajaj92 requested review from a team and dwu96 September 11, 2026 10:27
@github-actions github-actions Bot added the fork Pull request from a fork (external contributor) label Sep 11, 2026
@github-actions github-actions Bot added the readiness: action required A blocking check or review needs attention label Sep 11, 2026
@github-actions

github-actions Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5, fork) — 🟡 CONCERNS

UX-level review of 7f76da583dde613aa55d814fae64290f5d61a9a1 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

UX-Verdict: CONCERNS

The Windows platform notice shows in red even when nothing is wrong, and the "Saving still works" notices never say whether chats here will run the agent.

Watch

  • A permanent limitation is shown as an error. agent_roster_unsupported_available ("Project agents can't be read on Windows yet. Global agents still work.") renders in a red danger ErrorNotice even while "Create folder" is enabled and "None" is selected (attachment-20). So every Windows user who opens a folder with a project directory sees a red alarm with nothing to fix. That happens on every open, which turns red into background noise. Fix: render the non-blocking case in muted hint style. Keep red for the case where Save is actually blocked (agent_roster_unsupported).
  • The savable notices hide what the user needs to decide. "Saving still works. To clear this warning, pick an agent this directory has…" (attachment-16, 17) calls the problem a warning to clear. It never says whether new chats in this folder will run the inherited agent. Users with an inherited agent the folder's directory doesn't have will save and only find out when a chat starts. Fix: open with that outcome, e.g. "New chats here can't use repo-dev. Saving still works…".

Suggestions

  • Attachment-07 shows the old wording "(not supported on this platform)". Replace it with the current committed shot (attachment-18), so reviewers judge the copy that actually ships.

[UX-REVIEWED] 7f76da5

Description read

[DESCRIPTION-READ] a76e01862680840e34eceac0f67b8b73e0a5772ad318441ef7158ace94902901

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

@github-actions

github-actions Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5, fork) — 🟡 CONCERNS

Design-level review of 7f76da583dde613aa55d814fae64290f5d61a9a1 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: CONCERNS

The pinned-walk rework also changes the per-turn session reader the description calls "unchanged": existing project agents can now silently drop out of running chats.

Watch

  • Session-path behaviour change the description doesn't mention. The description says "the pre-existing session-derived readers keep working there unchanged". But the patch reroutes _scan_project_agent_files through _pinned_scan_dir_fd even when raise_unverifiable=False, and adds _AGENT_NAME_MAX_CHARS = 64 with "a pre-existing session scan consumes the surviving names". The chain: a project spec whose declared name is over 64 characters, or a .kiro/.kiro/agents symlink that resolves somewhere sensitive, is now dropped from project_agent_names. That set feeds per-turn resolution, spawn_run validation, Slack and the config loader. A chat bound to that agent then fails at dispatch with "agent is unavailable", when it worked on main. I checked fork governance (agent.py:4926) and it is not affected, because fork names are capped at 63 characters by TEMPLATE_NAME_RE.
    Clears when: the cap and the subdir refusal are limited to the raise_unverifiable=True roster path, or the description lists them as session-path take-aways with a test showing a bound session still resolves.
  • Backwards-compatibility section is cut off. The description is truncated inside ## Backwards compatibility, so I could not check its reader list. This holds the take-away check at CONCERNS.
    Clears when: the section is short enough to fit, and it names a Reader: line for each session-path consumer of project_agent_names.

Suggestions

  • check_folder_agent_scope now has nine parameters and four early-return arms, each covering one caller (MCP move, non-owner inherited directory, clearing a binding). Two simpler options: return early whenever the effective pair equals the stored pair, or validate only when default_agent/project_dir actually change. Either would remove most of the seeded/seeded_parent_id/clears_own_binding handling.

[DESIGN-REVIEWED] 7f76da5

Description read

[DESCRIPTION-READ] dd687807ae2db2649dbc5c89c2bb083b392b1c781d9509236774efb06bb8980e

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

@github-actions

github-actions Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review (fork) — ✅ no blocking findings

Reviewed 7f76da583dde613aa55d814fae64290f5d61a9a1 via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 7f76da5

@github-actions

github-actions Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5, fork) — 🟡 CONCERNS

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

First-Principles-Verdict: CONCERNS

The server-side scope refusal costs more than it removes: base dispatch already rejects an unresolvable agent loudly, and adding the check forced its own leak fences and exemptions. Session discovery also changed, undeclared.

Not justified as shipped

  • Item 4 — oversized: the PR's own slot_create.py hunk says a stored agent that doesn't resolve already fails: "dispatch (chat_runner) fails LOUD with an 'agent is unavailable' error". So the 400/503 gate only protects against a direct-API caller storing a name that is already refused at run time. Its 400 names the effective agent, which made it an existence oracle. That in turn needed owner-only gating, two round-trip exemptions (seeded, seeded_parent_id), clears_own_binding, is_owner threaded through the scaffold, and three ownership preflights that repeat the locked forbidden_parent/not_owned gates.
    Subtraction: delete check_folder_agent_scope, FolderAgentScopeError/FolderAgentScopeUnverifiable, the three preflights and the is_owner threading. Keep the modal's Save gate.
    Clears when: a reported harm from a stored out-of-scope name that dispatch's loud failure does not already cover is linked, or the gate is removed.
  • Item 7 — undeclared, rides along: the description says "the pre-existing session-derived readers keep working there unchanged". Yet project_agent_names with raise_unverifiable=False now drops names over 64 characters and returns frozenset() on _ProjectSnapshotChanged, on per-turn resolution and spawn validation.
    Subtraction: limit the name cap and the identity compare to raise_unverifiable=True.
    Clears when: the session branch's roster matches base, or a defect it fixes is linked.

What this change ships

Inventory (9 items) — 7 justified

Intent: let a folder's Default agent be one of its project directory's own agents. FIX.

  1. Folder modal lists the project directory's own agents, re-fetched as you type — justified
  2. GET /api/agents?project_path= (owner-only, audited, falls back on refusal) — justified
  3. Modal flags an agent missing from the directory and disables Save; a saved one round-trips — justified
  4. Folder create/update/move/scaffold refused with 400/503 — oversized
  5. A new chat in a folder resolves its agent in the folder's project scope — justified
  6. The project-agent scan now refuses a .kiro that resolves into a sensitive tree — justified
  7. Session discovery caps names at 64 characters and empties on a mid-scan directory swap — undeclared, rides along
  8. Folder project dir validated off the event loop; a path that can't be expanded returns an error instead of raising — justified
  9. Committed screenshots and capture scripts — justified

[FIRST-PRINCIPLES-REVIEWED] 7f76da5

Description read

[DESCRIPTION-READ] 9cb56aa504bcb1dc1c743a1717f10472df4d2470570e5a06b991d041e38eb053

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

@github-actions

github-actions Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review (fork) — ✅ no blocking findings

Reviewed 7f76da583dde613aa55d814fae64290f5d61a9a1 via the fork AI-review pipeline; updated in place on each push.

Review details

Advisory only: one finding, nothing blocks the merge.

FINDING — src/kiro_crew/agent_discovery_parts/project_agents.py:802 — the new cache caps _store_project_agent_names adds (len(entry[1]) > _PROJECT_NAMES_CACHE_MAX_NAMES or signature_rows > _PROJECT_NAMES_CACHE_MAX_SIGNATURE_ROWS: return) mean a project with more than 512 declared agents, or roughly 512 symlinked specs, is never cached. warm_project_agent_names throws away the result it computed, so the on-loop cached_project_agent_names returns None on every turn. _project_declares_agent (loader_snapshots.py:1170) and agent_switch.py:544 then fall back to the default agent where main used to resolve the project agent → Fix: when an entry is over a cap, still store a bounded entry cached_project_agent_names can serve, such as the names under a signature that never matches so the next call rescans. Do not skip the write.

[OPUS-REVIEWED] 7f76da5

@mbajaj92
mbajaj92 force-pushed the fix/folder-project-agent-picker branch from 3313922 to 891f242 Compare September 11, 2026 17:48
@mbajaj92

Copy link
Copy Markdown
Author
  • Saving during roster refresh persists a stale agent (span=3922b311df81) — fixed
    self-added: yes
    mechanism: submit-guard while the project-roster scan is in flight

Fixed in 891f242. Save is now blocked while the project-dir scan is in flight (canSubmit && !rosterLoading). The re-scope reconciliation that clears a now-invalid pick runs when the new dir's roster resolves; holding submit until then closes the window where the pre-scan selection could be persisted.

@mbajaj92

Copy link
Copy Markdown
Author
  • function-local import violates top-level-imports (span=583f63beb6ea) — fixed

Fixed in 891f242. Moved 'from kiro_crew.security import is_sensitive_path' to module scope in agents.py; the function-local import in _resolve_roster_project_path is gone.

@mbajaj92

Copy link
Copy Markdown
Author
  • realpath mishandles ~/repo folder paths (span=583f63beb6ea) — fixed

Fixed in 891f242. _resolve_roster_project_path now calls os.path.expanduser(raw) before os.path.realpath, so a ~/repo project dir resolves and its project agents appear instead of silently falling through the isdir check.

@mbajaj92

Copy link
Copy Markdown
Author
  • manual .then() fetch violates use-react-query (span=3d755b58415a) — fixed
    mechanism: directory-keyed useQuery replacing the effect+state fetch

Fixed in 891f242. The bespoke useEffect+useState+setTimeout roster fetch is replaced by a directory-keyed useQuery (queryKey ['folder-project-agents', debouncedProjectDir]), with the dir debounced via useDebouncedValue. rosterLoading/projectRoster are derived from the query; re-scope reconciliation runs in an effect gated on the query's isPending so it never judges against a previous dir's roster.

@mbajaj92

Copy link
Copy Markdown
Author
  • Silent selection reset / invalid-dir indistinguishable from no-project-agents — rebutted (disproportional for this PR)

Both are advisory UX polish. The inline notices they ask for need new user-facing strings, which the i18n gate requires across all 14 locale files — a diff far wider than this bug-fix PR's purpose (scope the picker to the folder's project dir). The correctness the review flagged is handled: a re-scoped-away agent is reset to inherit (not silently kept wrong), and a failed/invalid dir falls back to the global roster rather than blanking. The 'add a muted hint' improvements are a good follow-up; tracking them for a dedicated UX pass rather than widening this PR.

  • Loading state on the agent select while scanning — partially addressed

Save is now disabled while rosterLoading, so a mid-scan save cannot persist a stale pick. A visible spinner in the select popup is the same i18n-string-cost polish as above and is deferred to the follow-up.

@mbajaj92

Copy link
Copy Markdown
Author
  • Screenshot evidence gap (dropdown listing project agents) — accepted, screenshot to follow

Agreed the 'no visual delta' waiver was wrong — the dropdown's contents do change. A screenshot of the open Default-agent picker with a project dir set (three project agents listed) will be attached before the review round closes. The behavior itself is locked by the frontend tests in this PR.

@mbajaj92

Copy link
Copy Markdown
Author
  • Design Review CONCERNS — acknowledged

Verdict is advisory (CONCERNS, not BLOCK). The design shape is unchanged from the reviewed head; the round-2 fixes are localized (import scope, ~ expansion, react-query conversion, submit guard). No one-way-door decisions introduced.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 11, 2026
@mbajaj92
mbajaj92 force-pushed the fix/folder-project-agent-picker branch from 891f242 to 1545cd0 Compare September 11, 2026 18:13
@mbajaj92

Copy link
Copy Markdown
Author
  • Arbitrary project scans bypass owner authorization (span=d77e9c4049d0) — fixed
    mechanism: owner-gate on the ?project_path= scan

Fixed in 1545cd0. The ?project_path= scan is now owner-only: it runs only when the request is the owner (guarded by the same is_owner_dashboard_request predicate the handler already computes for redact). A non-owner caller's param is ignored and falls back to the slot-derived project, so a non-owner can no longer point the scan at an arbitrary directory to enumerate agent names. Added test_project_path_is_ignored_for_a_non_owner_caller.

@mbajaj92

Copy link
Copy Markdown
Author
  • Failed roster loads silently clear the selected agent (span=3922b311df81) — fixed

Fixed in 1545cd0. Re-scope reconciliation now runs only on a SUCCESSFUL scan (gated on the query's isSuccess); a failed/errored scan is treated as 'roster unknown' — the picker falls back to the global roster and the user's selection is KEPT, never cleared on a transient scan failure.

@mbajaj92

Copy link
Copy Markdown
Author
  • Submit remains enabled during the debounce window (span=3922b311df81) — fixed

Fixed in 1545cd0. Submit is now disabled whenever the user has CHANGED the project dir since opening and that change is still unresolved (its debounce OR its scan in flight) — draft.projectDir !== seed. This covers the debounce window before the scan starts, so a save cannot land before the new dir's roster resolves and reconciliation runs. The untouched initial open is unaffected. (Also fixed a related bug found while verifying: reconciliation now judges membership against the UNION of the dir's agents and the global roster, so a global agent is never wrongly cleared when a scanned dir exposes no project agents.)

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 11, 2026

@cruisercohen cruisercohen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed locally at head 829dd76. The bug is still present on main: GET /api/agents ignores ?project_path=, and the picker builds its list from the slot roster. The targeted backend suites in this PR pass locally (335 tests). Before this can merge:

  1. Rebase. The branch conflicts with main in website/src/components/FolderConfigModal.tsx (main added a filter box to the same picker), docs/feature-map/README.md and docs/system-specs/modules/learn-cron-dashboard.md.
  2. The earlier change request is still open on this head. There are bare monkeypatch.undo() calls at test/test_agent_discovery.py:746 and :1897, and at test/test_agents_roster_contract.py:1386, :1424 and :1462. These undo the autouse isolation; please use monkeypatch.context() instead.
  3. Also from that request: website/src/test/FolderConfigModal.test.tsx:470 waits a fixed setTimeout(r, 50) before a negative assertion. Please assert on the gate state instead.
  4. Backend Tests (Windows) (7) is red on this head, and the PR adds Windows-only link screening. Please check it after the rebase.

@mbajaj92

Copy link
Copy Markdown
Author

@cruisercohen — all four items addressed on head f7686081df. Thank you for running the backend suites locally; confirming your read of the bug, GET /api/agents on current main resolves its directory from active_project_dir(state, session_key) — the session's project, not the requested folder's — so it still cannot answer "what agents exist at this folder's directory".

1. Rebase — done. Rebased onto origin/main 10350b7294 (1,048 commits of drift). mergeable is now MERGEABLE, where it was CONFLICTING. All three files you named conflicted, plus four more; each was a semantic merge rather than a side to pick, because upstream had evolved the same functions:

file resolution
website/src/components/FolderConfigModal.tsx kept both — main's filter box and this PR's scoping
docs/feature-map/README.md upstream's own row updates + this PR's additions, compared row by row
docs/system-specs/modules/learn-cron-dashboard.md same
src/kiro_crew/agent_spec_format.py kept main's strict= listing, routed both paths through one splitter
src/kiro_crew/agent_discovery.py both imports; dropped a constant main's rewrite made dead
test/test_markdown_agent_specs.py both sides' tests (78 pass)
website/scripts/check-bundle-size.mjs main's re-measured ceiling

2. monkeypatch.undo() — fixed. All five sites now scope their patches in with monkeypatch.context() as scoped:. grep -c 'monkeypatch.undo()' is 0 in both files; two context() blocks in test_agent_discovery.py, three in test_agents_roster_contract.py. I verified each of the five by mutation rather than by the tests passing — two disjoint mutations confirm the three UNC tests each fail on their own subject rather than all riding one gate.

3. The fixed sleep — fixed. setTimeout(r, 50) is gone; the test asserts on the gate state. Verified by forcing blockingOrphan = false, which reddens it — so removing the barrier did not hollow it out.

4. Backend Tests (Windows) (7) — expected to clear with the rebase. Both tests that reddened that shard are fixed on main: bd85f0b206 ("start the console-attach helper once the 259 child is running", #17356) and d69798411b ("drive the slots byte-pacing window on a fake clock", #17315). The shard has not dispatched on this head yet, so I am not claiming it passed — I will confirm and report either way.

Gates on the merged tree: isort/flake8/black clean, mypy clean over 2,291 files, tsc clean, 121 FolderConfigModal tests, build and the bundle gate (901 chunks within budget) both pass.

@mbajaj92

Copy link
Copy Markdown
Author

@buluoray — both blocking items are fixed on head f7686081df, and you were right about the AUTOSDE.yaml rules: testing-conventions.md prescribes exactly the pattern you asked for, so this was a documented repository rule the tests had drifted from, not a preference.

Blocking 1 — bare monkeypatch.undo(): fixed. All five sites (test_agent_discovery.py:746, :1897; test_agents_roster_contract.py:1386, :1424, :1462) now scope their patches in with monkeypatch.context() as scoped:. Your diagnosis was precise — undo() reverted the autouse _reset_session_switch_locks isolation along with the intended patches, so later code in each test ran without it. grep -c 'monkeypatch.undo()' is 0 in both files.

Blocking 2 — the fixed sleep: fixed. The setTimeout(r, 50) before expect(onSubmit).not.toHaveBeenCalled() is gone; the test asserts the gate state instead. Your point that it "passes whether or not the gate works on a slow runner" was the right test: I verified the replacement by forcing blockingOrphan = false, which reddens it, so it still catches the thing it is for.

I checked all six sites by mutation rather than trusting the tests to pass — these were the third and fourth assertions on this PR that would have passed with their subject removed, so a green run was not evidence.

Rebase — done. Onto origin/main 10350b7294. RemoteArtifactDetailPageCoverage.test.tsx is no longer in the tree's failure set, and mergeable is MERGEABLE.

On your three non-blocking notes:

  • The body cites iter_linked_ancestors in platform_compat.py and the diff does not contain it. Confirmed and you are right: neither the symbol nor the file appears in origin/main...HEAD. That is a factual error in the description, not a missing change. Being corrected in the body rewrite — not yet published, so it is still wrong as of this comment.
  • The second server-side enforcement layer (check_folder_agent_scope, 400/503) is deliberate defense in depth: the modal withholds the save and the server refuses it independently, so a caller that bypasses the picker is refused too. Taking your suggestion to state that in the body rather than leaving a reader to infer it.
  • UX's notice-styling and "the agent it had before" notes are addressed. The wording was factually wrong — it claimed provenance for an inherited agent the user never picked, which is the only case these notices render in — and now reads "Saving still works. To clear this warning, pick an agent this directory has, or point the folder at the directory that has it." The Windows notice keeps rendering through ErrorNotice, because errors-use-error-notice is blocking: true and excludes the muted-hint treatment.

@cruisercohen cruisercohen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-reviewed at 997eb70. The code-level points from my review on 829dd76 are addressed:

  1. Rebased: the branch merges cleanly with main, and the picker keeps both main's filter box and this PR's scoping.
  2. The five bare monkeypatch.undo() calls are gone. Each site now uses with monkeypatch.context() as scoped:, and there are none left in either test file.
  3. The fixed setTimeout(r, 50) before the negative assertion in FolderConfigModal.test.tsx is gone, and the test now asserts on the gate state.

My change request is resolved on the code. I am not approving yet, because the merge still needs the following:

  • Point 4 is still open: CI on this head is mostly queued or running, including Backend Tests (Windows) (7). I'll check it once it concludes.
  • The PR adds a descriptor-relative fenced read primitive (open_fenced_for_read_at in pinned_fs.py) and Windows link screening, so it needs a maintainer's review of those security paths.
  • buluoray's change request is still open, and that is theirs to clear.

@cruisercohen

Copy link
Copy Markdown
Contributor

Follow-up on point 4 from my review at 997eb70: Backend Tests (Windows) (7) now passes on this head.

There is one new red from this diff. Backend Tests (Windows) (2) fails test_wait_discipline_ratchet.py::test_no_file_gains_a_short_fixed_wait. The new await asyncio.wait_for(wrote.wait(), timeout=10) in test/test_session_control.py counts as a short fixed wait (a wait_for under 30 s), while the asyncio.sleep(0) loop it replaces was exempt as a loop-turn yield. That takes the file from its baseline of 5 to 6. Please wait through the shared kiro_crew.testing.wait helpers (or give the wait a ceiling of 30 s or more) so the count does not rise.

macOS (1) (test_open_slots_persistence.py) and Windows (5) (test_slot_close_recreation_race.py) fail in files this PR does not touch.

@mbajaj92

Copy link
Copy Markdown
Author
  • fixed: one implementation of the path-validation sequence, not two (span=duplicate-path-validator)

Correct, and the duplication was real: both ran UNC -> expanduser -> link-chain -> realpath -> UNC -> sensitive -> isdir, in that order. The sequence now exists ONCE, as agent_discovery._path_preflights, and both callers delegate to it. Fixed in ab6c27cde3.
The two entry points remain as thin wrappers rather than one, because their contracts differ in ways the shared sequence cannot carry. _validate_project_dir logs SEL inline; _resolve_roster_project_path is invoked through asyncio.to_thread (handlers/agents.py), so a SEL write there would run on a worker thread, and hoisting the validator onto the loop would put blocking realpath+stat on it.
Their return contracts also differ by design: the roster read path answers 3-way so a half-typed directory degrades to GLOBAL rows, while the folder save path answers with an error message for a 400. Calling the save validator from the read path would 400 the picker while the user is still typing, and would additionally apply its absolute-path bar, which the read path deliberately omits.
Behaviour is preserved on both sides, checked rather than assumed: a real sensitive directory is still refused by the unpatched save path, and the refusal audit now names the spelling the gate actually fired on (expanded for a link chain, resolved for a redirected target) instead of the raw text, which a first cut of this refactor had flattened.
Two tests caught that the check moved: they patched chat_folders.is_sensitive_path, which the sequence no longer reads. Repointed to where the check lives; the production path was verified unpatched first, so the tests were corrected to match the code rather than made green over a regression.

The four advisory items in the same verdict (the pinned walk, check_folder_agent_scope, the critical=/503 branch, and the UNC gate) are deliberately untouched here and get their own replies; this disposition covers the blocking item only.

@mbajaj92

Copy link
Copy Markdown
Author
  • rebutted: the enumeration is the disclosure, which the per-file fence does not cover (span=item-5-pinned-walk)

The clause rests on _read_agent_spec's per-file fence standing in for the walk. It cannot: ?project_path= answers with the NAME LIST derived from the directory listing, and the per-file fence is applied after that list exists. A component swapped between the sensitivity verdict and the listing therefore yields names enumerated from a directory the verdict never approved, and no per-file check is reached for a name that is merely reported.
The base callers cited are not the same subject. warm_project_agent_names and the slot-derived reads take a path the gateway itself already holds; this one takes a path from an HTTP query in the same request that returns the answer, which is why it is the first caller to need the pin rather than the only one that could want it.
The Windows cost is stated rather than hidden, and it is a platform limitation reported as scan_unsupported_platform with a notice, not a silent empty roster — the _savable frames in the body show that state.
Not claiming the second arm is met: I have not produced a failing base test, because the disclosure is the enumerated name list rather than a file read, so a per-file fence test cannot express it. If the lane holds that a base test is the only admissible evidence, this is a maintainer call rather than one I can settle.

@mbajaj92

Copy link
Copy Markdown
Author
  • needs-a-decision: item 6's own clause puts this to a human, not to me (span=item-6-unc-on-save)

The clause reads "the mechanism is removed, or a human amends the Goal". Both arms are a person's call, so recording either as my own ruling would be answering a question the lane deliberately addressed elsewhere.
Stating the tradeoff rather than arguing it away. For removal: the Goal names refusing an out-of-scope AGENT, and this adds a refusal on SAVING a project_dir, so the lane is right that it is adjacent to the stated goal. Against removal: _validate_project_dir realpaths a user-typed path, and on Windows resolving a UNC spelling is itself an outbound SMB probe the path's author chooses, so the save path reaches a host before any agent question is asked. That the base already realpaths it is the reason the gate was added here rather than evidence it is unnecessary.
@dwu96 @kyleseaman — the question is narrow: should this PR keep the UNC/link-into-UNC refusal on a folder's project_dir save, or drop it and leave that path as it is on main? I will take either answer; I am not able to amend the Goal myself, and I would rather not strip a security gate on my own judgement.
The companion item 5 (the descriptor-pinned roster walk) is answered separately as rebutted, on the enumeration-versus-per-file-fence distinction.

@cruisercohen cruisercohen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-reviewed at 52a9c8c. The wait-discipline point from my follow-up is fixed: the new asyncio.wait_for(..., timeout=10) in test/test_session_control.py is replaced by the shared await_until helper on an event the executor stub sets, and test_wait_discipline_ratchet.py passes on this head with that file back at its baseline of 5. That was the last open point of mine, so my change request is addressed on the code.

The new shared _path_preflights keeps the same check order on both callers (raw UNC, expanduser, link chain, realpath, resolved UNC, sensitive, isdir), and each refusal still audits the spelling it fired on. I found no new defect in it.

I am not approving, because a maintainer still has to look at this: the head changes path-validation and descriptor-pinned read code, the First Principles item on keeping the UNC refusal on folder save is waiting on a maintainer, buluoray's change request is still open, and CI on this head was still running when I checked.

@cruisercohen cruisercohen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-reviewed at 5b849f4. The only change since 52a9c8c moves the type-checking-only import of PathPreflightOutcome and _path_preflights in dashboard/agent_admin/roster.py to the dashboard/handlers/agents.py re-export. It sits under TYPE_CHECKING, so runtime behaviour is unchanged, and I found no new issue.

The branch now conflicts with main, so CI has not started on this head. It needs a rebase before the checks can be judged.

@mbajaj92

Copy link
Copy Markdown
Author

@cruisercohen — you were right on both counts, and the conflict is resolved. Rebased onto origin/main de2d143dcf82 (88 commits of drift); head is now 29b1fb7e11, mergeable=MERGEABLE, and the pull_request lane has dispatched, so the checks are judgeable again.

One correction to my own earlier read: I had been reporting "dispatch still pending" for two cycles while the actual cause was the conflict blocking merge-ref creation — you named it before I did.

The conflict was one file, docs/feature-map/README.md, two rows with different owners:

row owner
Peer-owned live session (crew window) upstream's change, taken verbatim
Session folders this PR's change, kept

Verified the peer row matches upstream byte-exactly rather than trusting the merge, and re-ran check_feature_map.py with FEATURE_MAP_BASE_REF set — without it the gate reports "Not enforced here" and passes vacuously.

Board on 29b1fb7e11: 19 green, 1 red, 1 skipped. The red is E2E (stub ACP backend, offline), and it is a wall-clock budget rather than a defect:

323 passed (16.9m)   unexpected=0   flaky=0
1 interrupted: playwright/member-memory.spec.ts:320
6 did not run
FAILED test_playwright_e2e.py::test_dashboard_playwright_suite
  - Playwright ran 1020s, past the 1020s bound

No spec failed an assertion. The suite consumed 1014.9s of a 1020s bound — 99.5% — and was cut mid-spec. Three things place it outside this diff:

  • This PR adds no Playwright specs. git diff origin/main..HEAD -- '*playwright*' '*.spec.ts' is empty, so all 323 are upstream's.
  • The interrupted spec is member-memory.spec.ts, a file this PR does not touch.
  • The job routinely runs near its ceiling repo-wide — the four most recent successful runs of that job took 15.82, 16.07, 16.97 and 20.77 minutes. At 16.97 the margin was seconds.

The five capture-folder-agent-*.mjs scripts this PR adds are not invoked by any workflow (grep -rn capture-folder-agent .github/workflows/ scripts/ is empty), so they add nothing to that job either.

I have not opened an issue for it, and I cannot re-run the lane myself — gh run rerun returns HTTP 403: Must have admin rights to Repository for a fork contributor.

On your merge-triage point: you are right that buluoray's change request is the gate. reviewDecision=CHANGES_REQUESTED with their latest review state still CHANGES_REQUESTED from 337d192e48. Both blocking items are fixed on current head — the five bare monkeypatch.undo() calls are scoped with monkeypatch.context(), per testing-conventions.md — but a COMMENTED re-review does not clear a CHANGES_REQUESTED, so that needs @buluoray or a maintainer.

@mbajaj92

Copy link
Copy Markdown
Author

@buluoray — the board is fully green on head d86fd040b6, and your non-blocking body request is now in. Re-stating against the current head rather than my earlier reply, which named a head six pushes ago.

Your two blocking items, verified on this head rather than asserted:

  1. Bare monkeypatch.undo() — gone. grep -nE '\.undo\(' over test/test_agent_discovery.py and test/test_agents_roster_contract.py returns nothing, so none of the five cited sites survives in any spelling. You were right about the mechanism: undo() reverts every patch on the shared monkeypatch, including the autouse _reset_session_switch_locks, so the rest of the test body ran with that isolation removed.
  2. FolderConfigModal.test.tsx fixed setTimeout(r, 50) before a negative assertion — gone. The file has no fixed sleeps; those paths assert on the state that proves the gate held.

The rebase you asked for happened twice since: onto de2d143dcf82, then 328f749e2fb1 (194 commits). Your attribution was correct — Frontend Tests (3), Frontend Coverage Merge and Coverage Gate were the RemoteArtifactDetailPageCoverage.test.tsx flake fixed by #17237, and all three are green now with no change from me.

Board: 96 success, 0 failing, 0 pending. PR Readiness success. GPT 6.1 and Opus 5.5 both report no blocking findings on this head; UX, Design and First Principles are at advisory CONCERNS. No unresolved threads.

Your non-blocking item — the second enforcement layer. Added to the PR body under "Why the save path enforces as well as the picker", since you and both lanes asked for the rationale to be stated rather than implied: the picker narrows what a UI offers, but /api/agents/roster and the save endpoint are reachable directly, so treating a filtered list as the enforcement point would leave the control advisory. The 503 is fail-closed on the same logic — an unreadable roster cannot prove the pair is in scope.

Also fixed from your list: the body no longer cites iter_linked_ancestors, which the diff genuinely did not contain. That was a false citation on my side, not a missing file.

@iamwhatever

Copy link
Copy Markdown
Contributor

HOLD at d86fd04. This adds a fenced filesystem read, caller-supplied path checks, and owner/app-isolation gates. Those security paths require a human maintainer's review. @buluoray's change request also remains active; another COMMENTED review does not clear it. Please obtain that re-review and answer the current-head UX, Design and First Principles findings, including the scope-check layer, changed by-name symlink handling, and the description/build wording mismatch. Coordinate the overlapping resolver and UNC work in #9201 and #13335 before landing. This pass reviewed the key security and scope paths, not every test, screenshot or remaining discovery hunk. I am not approving the full change or clearing anyone else's request. — crew-pr-reviewer (r99)

@mbajaj92

Copy link
Copy Markdown
Author

First Principles blocker — accepted, subtraction made. Head 081c264867.

Your argument held on reading the code, so I took the subtraction rather than arguing for the mechanism.

Why you were right. _screen_windows_links has seven return None paths (hooks.py:1548-1576), and only two are about an untrusted share: a readlink OSError, a .. suffix, a target it cannot normalize, and its own chain and depth limits all refuse too. And the refusal does reach session start exactly as you traced — resolve_folder_project_dir_off_loop (chat_folders.py:755) calls _validate_project_dir on the stored value, and chat_handlers.py turns any error into 400 folder_project_invalid. So an ordinary Windows junction behind an already-saved project directory could stop that folder opening a chat, on a premise I have no Windows box to test.

What changed. _validate_project_dir no longer routes through agent_discovery._path_preflights at all, since steps 1 and 5 of that sequence are the screen. It is back to the base sequence — absolute-path bar, expanduser/realpath, sensitive-path gate with inline SEL, isdir — plus nothing. _log_unc_denied is gone with its last caller, and the TestValidateProjectDirUncGate class this PR added went with the mechanism it pinned.

Worth being explicit that this is a return to main's behaviour, not a new relaxation: base _validate_project_dir had no UNC or link-chain screen either.

The screen stays where the Goal needs it — ?project_path= roster read, agent_discovery (13 call sites, roster.py 3), where a refusal costs a listing rather than session start. For a stored value the spawn guard remains the authority, which is what _folder_project_overlap_denied's own docstring already said about its own check; the validator's docstring now says the same, with the reason, so this does not get re-added by a later round.

Verification. Two new tests replace the removed class: a junction-backed project directory validates, parametrised over both a UNC and a local ancestor target so the outcome provably does not depend on the screen's verdict; and the pre-existing sensitive-path gate still refuses, so the subtraction is bounded. Proven load-bearing by mutation — restoring the screen fails the UNC-ancestor case (1 failed, 2 passed) and removing it again passes (3 passed).

Three test_session_folders.py patch targets moved back to chat_folders (this PR had moved them to agent_discovery for the preflight path). Gates: black / isort / flake8 / mypy 2342 files / feature-map / comment-history / docs-lint all clean; 2134 passed, 0 failed across all 20 backend test files in the diff.

The PR description paragraph you quoted said the opposite of the code and is corrected in the same round.

@mbajaj92

Copy link
Copy Markdown
Author

@buluoray — your review requested changes on head 337d192e48. Both blocking items are fixed, and the three non-blocking notes are addressed. Current head is 081c2648679f2ac4c55782013f8f8210ba7a2e8d.

Blocking 1 — bare monkeypatch.undo()

All five sites converted to with monkeypatch.context() as scoped:, so the autouse _reset_session_switch_locks isolation is no longer reverted mid-test:

your cite now
test/test_agent_discovery.py:746 :727 scoped
test/test_agent_discovery.py:1897 :2002 scoped
test/test_agents_roster_contract.py:1386 :1388 scoped
test/test_agents_roster_contract.py:1424 :1424 scoped
test/test_agents_roster_contract.py:1462 :1460 scoped

No bare monkeypatch.undo() remains in any test file this PR touches.

Blocking 2 — fixed sleep before a negative assertion

The setTimeout(r, 50) is gone; no setTimeout remains in website/src/test/FolderConfigModal.test.tsx. The assertion now waits on the state that proves the gate held, then asserts synchronously in the same tick as the commit:

await waitFor(() => expect(api.kirocrewAgents).toHaveBeenCalledWith(undefined, '/repo'))
await waitFor(() =>
  expect(screen.queryByTestId('folder-config-agent-roster-loading')).not.toBeInTheDocument())
fireEvent.keyDown(dir, { key: 'Enter' })   // commits the field AND calls submit() in one tick
expect(onSubmit).not.toHaveBeenCalled()

There is no interval in which a slow runner can make this pass vacuously: the roster request has resolved and the loading node is gone before the key event, and the assertion is synchronous with it.

Rebase

Done — base moved from 337d192e48 to 7c4c4ec4b6, 1553 commits of upstream history. #17237 (f76058b94c) is in that base, and the three rows you attributed to RemoteArtifactDetailPageCoverage.test.tsx are green: Frontend Tests (1)–(4) and Frontend Coverage Merge all pass. That file is not in this diff.

Non-blocking

  • Second enforcement layer — kept, and the body now says so under "Why the save path enforces as well as the picker": the picker narrows what the UI offers, the endpoint is reachable directly, so treating a filtered list as the enforcement point would leave the control advisory. The 503 is fail-closed because an unreadable roster cannot prove the pair is in scope.
  • iter_linked_ancestors — the stale citation is removed from the body.
  • UX notes — the Windows notice styling and the "the agent it had before" wording are both addressed; that phrasing no longer appears in the tree.

Separately, First Principles escalated to BLOCK on a later head over the UNC/link-chain screen this PR had added to chat_folders._validate_project_dir, and I took the subtraction: _screen_windows_links refuses on seven conditions, most unrelated to an untrusted share, and resolve_folder_project_dir_off_loop runs that validator on stored values, so an ordinary junction behind an already-saved project directory could have blocked session start. Base _validate_project_dir had no such screen, so removing it returns to main's behaviour; the screen stays on the ?project_path= roster read, where a refusal costs a listing. That lane is now CONCERNS.

Remaining red checks

Three, none produced by this diff, each tracked by an open issue:

check issue note
Backend Tests (3.12, 3) #20475 lease census counts before a by-design daemon-thread release; fix in flight as #20485
Backend Tests (Windows) (2) #13732 xdist worker killed by the 180 s timeout inside a SQLite commit(); 7 of 8 shards pass
E2E (stub ACP backend, offline) #18185 326 specs pass, unexpected=0; the run is SIGINT'd at the 1020 s ceiling

Coverage Gate fails only on backend-test=failure -- failing closed, and PR Readiness is the aggregate over the above.

All five AI lanes stamped the current head with no blocking findings — GPT 6.1 and Opus 5.5 clean, Design / UX / First Principles advisory CONCERNS.

Could you take another look when you have a moment?

@cruisercohen cruisercohen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-checked a311625 against c584530. Both changes since then are in tests, and neither blocks.

  • The e2e tests now find the Default agent picker by the button role instead of combobox. That matches main, where the picker is a button.
  • The new commit a311625 raises the nested --collect-only cap in test_ci_ipv6_routing.py to 100 s on Windows and keeps 60 s elsewhere. That is the fix for #21943 (the collection times out at 60 s on hosted Windows runners), and all eight Backend Tests (Windows) groups pass on this head. It has nothing to do with the folder agent picker, though, so while this PR waits, so does that fix. Opened as its own PR with Fixes #21943, it could land now, and this PR could drop the commit.
  • The one red test group, Backend Tests (3.12, 2), hit the 120 s per-test timeout in a whole-tree scan in test_facade_mirror_guards.py, which this diff does not touch. Coverage Gate and PR Readiness are red because of it.

@cruisercohen cruisercohen left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks @mbajaj92. I re-reviewed a311625 against c584530, the last head I checked. This is a comment review: buluoray's change request and the maintainer hold still stand.

  • Commit 1 (dd0d0d3) is a rebase. Its changes match c584530 except that the e2e specs now find the folder's "Default agent" picker by the button role instead of combobox, plus main's own wording in the feature-map row it edits.
  • Commit 2 (a311625) is outside this PR's scope. It raises the per-run cap in test/test_ci_ipv6_routing.py from 60 s to 100 s on Windows. That file is CI routing, not the folder agent picker, and the description does not mention the change. A slow fork-runner red there affects every fork PR, so it is better as its own issue and PR, where a maintainer can decide whether to loosen that ratchet. That change is tracked in #21943, so it can land on its own as a separate PR. Please drop the commit from this branch.

CI on this head: the one red shard, Backend Tests (3.12, 2), is three whole-tree scans in test_facade_mirror_guards.py hitting the 120 s per-test timeout. That is the slow-runner timeout tracked in #19907, not this diff. Coverage Gate and PR Readiness fail behind it.

@cruisercohen cruisercohen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-reviewed 59c5c55 against a311625, the last head I checked. This is a comment review: buluoray's change request and the maintainer hold still stand.

  • The commit that raised the Windows collection cap in test_ci_ipv6_routing.py is gone, as asked; that file is no longer in the diff.
  • The rebase moves this PR's code into main's new owner modules, and the production change since a311625 is a move with no behaviour change. api_kirocrew_agents now calls two helpers in agent_admin/roster_project_path.py: _roster_project_dir_for_request holds the same ?project_path= logic as before (owner-only, audited, and an explicit path suppresses the active-slot fallback), and _refuse_unverifiable_roster_scan raises the same two 503 shapes. Both run on the handlers module's globals through the facade compose, like that module's existing helper, so the existing patch targets still reach them. create_folder_record, project_agent_files and project_agent_names carry the same edits as on a311625, and _scan_project_agent_files differs by one docstring line.
  • Locally, 9 related test files pass (495 tests), including the roster contract's non-owner project_path cases, and flake8 and black are clean on the two files. CI on this head was still running when I checked.
  • Nit, not blocking: the module docstring of roster_project_path.py still says "this module's one function"; it now has three.

A chat folder can carry a project directory, and that project can define its
own agents in `<project>/.kiro/agents/*.json`. Those agents never appeared in
the folder's Default agent dropdown, which listed only the active chat's
agents -- and when creating a folder there is no active chat, so a project
agent could not be chosen as a folder's default at all.

Backend: `GET /api/agents` honors an explicit `?project_path=` and lists that
directory's project agents, overriding the slot-derived project and falling
back to the slot when the parameter is absent or refused. The scan is
owner-only and every attempt is SEL-audited: a real directory logs `allowed`,
a sensitive one logs `denied`, and a non-owner attempt logs `denied` and is
ignored.

Path handling for that caller-supplied directory goes through
`kiro_crew.pinned_fs`, the module that already owns pinned filesystem access.
The chain to `<project_dir>/.kiro/agents` is opened component by component and
enumerated relative to the held descriptor, so no component is re-resolved by
name after it is checked. A platform without `dir_fd`/`O_NOFOLLOW` cannot
perform that walk, so the request-supplied scan reports the roster as
unverifiable there rather than approximating the check by name.

That capability gate is scoped to the request-supplied path alone, via an
`unsupported_ok` flag defaulting to False. The pre-existing readers of
`<project>/.kiro/agents` -- per-turn agent resolution, `spawn_run` validation,
Slack, and the config loader -- resolve the session's already-established
project directory and keep their by-name behaviour, so project-agent discovery
is unchanged for them on every platform.

A refused scan stays distinct from an empty one: `None` means denied and `()`
means nothing to enumerate, so an errored scan never establishes that an agent
is absent.

Frontend: the folder modal fetches the roster for its draft or inherited
project directory, debounced, and scopes the dropdown to it. An agent that
directory cannot be confirmed to have is flagged in the trigger and blocks
submission, naming which case applies -- `(not installed)`, `(not in this
project)`, `(can't verify)` when the scan itself failed, or `(not available)`
when no directory is set. A saved orphan agent still round-trips a benign
rename or recolor, so an existing folder is not held hostage by a directory
that changed underneath it.

Closes kirodotdev#10106

@buluoray buluoray left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving at head 7f76da5. Both blocking points from my review at 337d192 are fixed. I compared the PR-own diffs across the rebase: the server scope check, its error classes and the slot-create and folder-update hunks are unchanged apart from comments. The roster project_path logic moved verbatim into agent_admin/roster_project_path.py.

Blocking points, rechecked:

  1. Bare monkeypatch.undo(): fixed. None is left in any test file this PR touches. All five sites now scope their patches with monkeypatch.context(): test/test_agent_discovery.py:629, test/test_agent_discovery_scan_gate.py:210 (the old :1897 site, moved in the split), and test/test_agents_roster_contract.py:1388, :1424, :1460.
  2. Fixed sleep before a negative assertion: fixed. website/src/test/FolderConfigModal.test.tsx:401 asserts right after the Enter keydown. That is sound, because submit() reaches onSubmit before its first await (FolderConfigModal.tsx:706-731). Pointing blockingOrphan at the display value orphanAgent instead of orphanAgentGate reddens this test, so it still guards the Enter bypass.

Ran the 23 related backend test files and the five FolderConfigModal suites; all pass apart from one sandbox-only failure that also fails on main. Mutating the core guards reddens a named test each time: dropping the raw UNC gate in _path_preflights, a no-op check_folder_agent_scope, honoring project_path for a non-owner, dropping the scan_unsupported_platform branch, dropping the ownership check before scope validation on update, and dropping the re-check of the stored dir.

CI: the one red is Backend Tests (Windows) (1), the known test_ci_ipv6_routing collection timeout (#21943). That file is not in this diff; it needs a re-run.

Non-blocking follow-ups:

  • Design Review and First Principles say the session-path roster changed without being declared: the 64-character name cap, the refusal of a .kiro that resolves into a sensitive tree, and an empty roster when the directory changes mid-scan. On main a name over 64 characters already fails is_registered_agent_name at dispatch (agent.py:3142, chat_send.py:345, agent_switch.py:290), so the cap matches the existing grammar. Please say so in the Backwards compatibility section, and add one test showing a bound session with a valid project agent still resolves.
  • chat_folders_routes.py:549-562 says re-checking the stored dir closes the UNC probe. The function it calls, _validate_project_dir, no longer has a UNC gate since that subtraction, so the comment claims more than the code does. Please reword it.
  • spec_reads.py:717 says both validators share _path_preflights, while chat_folders_paths.py:37 says the save validator deliberately does not. Please make the docstring match.
  • pinned_fs.py grows by 68 lines on an already baselined file. The cap check reports this without failing, but a small split would keep it from growing.

@cruisercohen cruisercohen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-reviewed 7f76da5 against 59c5c55, the head of my last comment. This is a comment review.

  • Apart from the rebase onto 2501be6, the only change to this PR's own lines is in three files: the agent_discovery facade now names the outside names it serves (runtime imports from agent_spec_format, hooks and pinned_fs, plus TYPE_CHECKING names), and ScanUnverifiable and _ProjectSnapshotChanged now carry the facade's __module__. No logic changed. Range-diff and a per-line comparison of the added and removed lines show nothing else moved.
  • That change fixes the two facade contract tests that were red on 59c5c55 (Backend Tests 3.12 shard 5): test_an_exception_an_owner_defines_keeps_the_facade_module and test_every_name_served_from_outside_the_family_is_visible_to_a_type_checker. Putting the 59c5c55 versions of the three files back fails both again.
  • The related backend tests pass locally (5,188, including the facade mirror guards, the roster contract, owner auth, folder agent scope, chat folders and the composition contracts). flake8, black and isort are clean on the three files.
  • CI: the only failure is Backend Tests (Windows) (1), the test_ci_ipv6_routing collection timeout tracked in #21943. That file is not in this diff.
  • The PR now conflicts with main 4d5cb47. A local merge shows only docs/system-specs/modules/learn-cron-dashboard.md conflicting, so it needs a rebase.
  • The docstring nit from my last comment is still open: the roster_project_path module docstring says "this module's one function", and the module has three.

@cruisercohen

Copy link
Copy Markdown
Contributor

@mbajaj92 buluoray approved 7f76da5 on 10-20, so the human review is in. Three things are left before this can land:

  1. Rebase onto main. Only docs/system-specs/modules/learn-cron-dashboard.md conflicts. The rebase also picks up the fix for the Backend Tests (Windows) (1) red, which is the test_ci_ipv6_routing flake closed in Flaky: test_ci_ipv6_routing collection subprocess times out at 60 s on GitHub-hosted Windows #21943.
  2. The docstring nit is still open: the roster_project_path module docstring says "this module's one function", but the module has three.
  3. Reply to iamwhatever's r99 HOLD on how this lands next to feat(cron): bind scheduled jobs to a project's agents #9201, your open PR that overlaps the resolver work. fix(dashboard): fence folder project bindings and refuse UNC project paths #13335 is closed now, so feat(cron): bind scheduled jobs to a project's agents #9201 is the only overlap left to explain.

After that it goes back to iamwhatever to lift the hold.

@bolichen97

Copy link
Copy Markdown
Contributor

[operator: bolichen97] Continuing this in #32008; thanks for the start.

@iamwhatever

Copy link
Copy Markdown
Contributor

Thank you for this work, @mbajaj92. It was carried on in #32008, which merged on 2026-11-09 and fixed #10106, so this PR has nothing left to land. Closing it. Please reopen or comment if you think something here is still missing on main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor) merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: action required A blocking check or review needs attention

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Folder settings: project agents never appear in the Default agent picker

5 participants