Skip to content

feat(hooks): limit a Hooks-page hook to one bot or one folder - #47124

Merged
buluoray merged 3 commits into
mainfrom
crew/slack/hook-card
Dec 5, 2026
Merged

buluoray merged 3 commits into
mainfrom
crew/slack/hook-card

Conversation

@buluoray

@buluoray buluoray commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: A person can limit a Hooks-page hook to one bot (its chat and the tasks it starts) or to one folder, so a guard meant for one bot or one repository does not fire in every chat.

Every Hooks-page hook fires in every chat today. A person who wants a deny rule for one bot's own tasks, or for any chat that touches one repository, has no way to say so: the hook either stops every chat, or its script has to work out who is calling from fields an agent can set.

Why it matters

Hooks are the one rule a model cannot skip, but a hook that fires everywhere is too blunt to write for one bot's habits or one repository. People end up writing no hook, or a script that guesses its caller.

Not a goal

  • Agents proposing hooks (a card for that is stacked on this PR).
  • Changing where Hooks-page hooks are stored.
  • Parsing shell commands beyond plain path spellings.

What changed (motivation → approach → change)

  • Goal: a scope on a hook, decided by Kiro Crew before the hook runs, never by the hook's own script.
  • Approach: two optional fields on a hook, scope_bot (the bot's id, which a rename keeps) and scope_folder (an absolute folder, stored resolved). A hook fires when any scope it names matches; with neither, it fires everywhere as before. The scope is one decision per session, hook_scope.scope_of(key) -> (bot, project), read through one predicate, in_scope, by every path that picks stored hooks: ScriptHookStore.fire (every event), the lane dispatch, the KAS hooks list and execute, the KAS auto-approval matchers (so a bot's hook does not take auto-approval away from other chats), the Stop-presence check and /hooks. The key is the call's own session (scope_key); a sub-agent takes the project of the chat it was started from, a task step the scope of its starting chat.
  • Who is calling comes from the session Kiro Crew runs the call under: the call's own session first, its spawning session only for a sub-agent. A bot's task is known from the record the gateway writes when the task starts. When the caller cannot be named, a scoped hook does not run, and the gateway log says so once.
  • Folder scope means the chat's project is inside the folder. A tool call's arguments and shell command are never read. Known limit: a folder-scoped hook does not fire when a chat whose project is elsewhere touches files in that folder; to guard a folder from every chat, use All chats and test the path in the command.
  • Two notify-only PreToolUse paths now pass the session key they already had, so a scoped hook is judged there too.
  • A task's folder: a task runs the folder hooks of the folder its chat had when it started the task. The run stores it once at the start (Project.origin_project, from run_inputs.start_folder in start_background, plan and the new-from-steps route) and persists it beside origin_session_key, so a later project change, a closed chat or a restart does not move it. A task started from a task step copies its parent's folder; a start with no chat keeps the folder the person picked, or none. A session key finds its run by whole-key equality with the keys a run id makes, checked across every run first; only when no run owns the key exactly does the longest run id whose chat-tab prefix it carries win, so a run named after another run's chat tab still finds its own run; a plan still being decomposed is found through TaskRunner._planning_runs. A chat reads its live slot only.
  • The Hooks tab names bots from the dashboard's one Bots roster (membersRosterQuery, matched by member id with the Schedule page's crewmateForJob rule); GET /api/hooks returns only hooks. Until the roster has loaded, a scoped row names its bot by id and none reads as deleted.
  • Hooks tab: a Runs in picker (All chats, or a bot) and a folder field on the form, and a Runs in column on the table. With a bot picked and a folder typed, the picker's shown value reads "{bot} and its tasks, and chats working in {folder}" (the scope_either string the table cell uses); on a phone the line wraps instead of being cut. A hook whose bot was deleted fires nowhere, and its row says "Its bot was deleted, so this hook doesn't run. Choose another bot or folder." (on a phone, in a full-width line under the row), and the picker lists it as "Deleted bot".
  • Docs: the hooks page's field table and a section on scope; the hooks spec's module table.

Known limits: where a task cannot find the chat that started it

Read from the code at bba9153. In each case below, a bot- or folder-scoped hook does not run for that work, and nothing reports it. Unscoped hooks are not affected.

  • A run saved before this change. It has no recorded folder, so its folder-scoped hooks do not run, a retry included. Its bot-scoped hooks still run. The person sees a folder hook that does not stop a call in an old task.
  • A workflow-engine run (wf:, wf-pool:, wf-worker: keys). These are not task runs, so they have no folder. They run bot hooks only when the session's own record names the bot. The person sees folder hooks never stop a call in a workflow.
  • A /task sent from a Slack code channel. The channel is not a dashboard slot, so the task has no folder. Only bot hooks can run.
  • A start with no chat behind it: a schedule (cron) or the Projects page. Neither names a bot, so bot-scoped hooks do not run for the task. A Projects-page start keeps the folder the person picked; a schedule has no folder.
  • A folder renamed or moved after the start. The task keeps the old path. A folder hook on the new path does not run for it.
  • A chat whose project is set only after it started the task. The task keeps no folder.
  • A finished run that the run table has dropped. The table keeps the last 10 finished runs, and drops finished schedule runs at the next start. A sub-agent still working under a dropped run no longer finds the run, so its scoped hooks stop running.
  • A sub-agent chain deeper than 16 hops, or a sub-agent whose live record and saved state.json are both gone. No chat is found, so no scoped hook runs.

Backwards compatibility

Compatible: a hook with no scope fields loads and fires exactly as before; the two new fields are optional on create and update, and an edit that leaves them out keeps them.

Removes nothing: no field, route or behaviour is taken away; an unscoped hook is unchanged on every path.

Tests

  • test/test_hook_scope.py: one matrix asks every event path (PreToolUse, PostToolUse, UserPromptSubmit, Stop presence, SessionLaneChanged, KAS list, execute and withhold, /hooks) about every caller kind (bot chat, worker, delegate, sub-agent, nested and continued sub-agent, task step, channel-linked chat, cron, another bot's worker, plain chat, unknown) for an unscoped, bot, folder, other-bot and bot-or-folder hook. Also: an unnamed caller or an unreadable config is a logged miss; a deleted bot matches nothing; a sibling folder with the same prefix is outside; a scope only ever narrows; the store round-trips and keeps scope on edit; an ACP client's PostToolUse names the same session as its PreToolUse.
  • test/test_hook_scope_task_folder.py: one test per case of a task's folder (start from a chat, background and plan, the placeholder run() replaces; project changed; project cleared; restart; chat closed; task from a task; sub-agent of a step, live and evicted; cron and Projects-page starts; ids with : or a leading run:; a plain chat). Each was seen to fail when its rule was removed.
  • website/src/test/HooksPage.scope.test.tsx: the Runs in cell for a bot and folder, a removed bot, and all chats; no row reads as deleted before the Bots roster loads; the form sends the folder typed.
  • Mutation-checked: dropping the sub-agent walk to its root chat, the Stop-presence filter, the /hooks filter or the KAS execute re-check each turns matrix cases red.

Proof: not provable -- other: feature PR, the base has no scope fields for the tests to exercise

Manual verification

Frames below are from head fb6c7df0b9, after the rebase onto main with #47747. New UI copy, awaiting the owner's sign-off: Runs in · All chats · Chats working in {folder} (the empty choice once a folder is typed) · {bot} and its tasks or {folder} · Folder (optional) · Its bot was deleted, so this hook doesn't run. Choose another bot or folder. (decided by the Bot on the owner's hand-over, 12-04); accessible names Bot and Folder.

Real-machine verification

Machine: the same throwaway cloud dev box as before (label hcscope-c2833), Amazon Linux 2023, x86_64, with a scratch data home holding one bot, mate. Each side was installed from a git archive of its commit into a fresh venv on a standalone CPython 3.12.16.

Path: the gateway's own PreToolUse gate, hook_runtime.hook_dispatch.permission_pre_tool_block (the gate task, sub-agent and channel calls go through), with its real sandboxed hook runner. This is an in-process run, not a live agent turn: the box has no model sign-in. The gateway registers the slot table as the scope's project resolver at startup; the script registers the two chats' folders the same way. The bot's task is recorded with the real record writer (note_crewmate_worker_session).

Hooks: two PreToolUse guards on execute_bash, each a /bin/sh one-liner, printf '<name>: stopped this call\n' >&2; exit 2. It starts inside the hook sandbox, so a deny is the guard's own verdict. bot-guard is scoped to bot mate; folder-guard is scoped to guarded-repo. Script: proof2.py, the same file on both sides.

Before (main 9b73736edf, this PR's base): python proof2.py ->

-- bot-scoped guard
mate's task (in scope)                       DENIED  (bot-guard: bot-guard: stopped this call)
another chat (out of scope)                  DENIED  (bot-guard: bot-guard: stopped this call)
-- folder-scoped guard
chat working in guarded-repo (in scope)      DENIED  (folder-guard: folder-guard: stopped this call)
chat working in other-repo (out of scope)    DENIED  (folder-guard: folder-guard: stopped this call)

After (head bba91530a1): same command ->

-- bot-scoped guard
mate's task (in scope)                       DENIED  (bot-guard: bot-guard: stopped this call)
another chat (out of scope)                  ALLOWED
-- folder-scoped guard
chat working in guarded-repo (in scope)      DENIED  (folder-guard: folder-guard: stopped this call)
chat working in other-repo (out of scope)    ALLOWED

On main a scope does not exist, so both guards stop every caller. On the head each guard still starts and denies its own caller, and lets an out-of-scope caller's call through.

Since this run (head bba91530a1), the branch was rebased onto main after #47747 merged, which made the Hooks page a stacked list on a phone. Only the Hooks page changed: HooksPage.tsx carries the Runs in column, the deleted-bot line and the picker onto main's version, and the scope line that sat under the name in the phone table moved into HooksPhoneList.tsx. No backend file changed, so the run above stands for the gate. Pinned by website/src/test/HooksPage.scope.test.tsx (the desktop Runs in column, and a new phone case: the scope line under each name, wrapped and never cut, and a deleted bot's line describing its switch) and by the Hooks page suites (113 tests).

Cleanup: the box was deleted at 2026-12-05T14:47:59Z. The provider's listing filtered to its label, at 14:48:31Z:

$ <list dev boxes> | grep hcscope
(no rows, exit 1)

Screenshots / video

From head fb6c7df0b9: this branch's Hooks page with a fake hook list and a one-bot roster (Release Helper). One hook names a deleted bot: its row is dimmed and left out of ENABLED (4 of 5), and its sentence is a dotted-underline button that opens the editor on the Runs in picker. A bot plus a folder reads "{bot} and its tasks, and chats working in {folder}". On a phone the page is #47747's list, with the scope line under each hook's name.

Rows: folder, bot, all chats, bot or folder, deleted bot; ENABLED 4 of 5; desktop light
The same hooks on a phone, light: the scope line under each name

More

Rows, desktop dark
The hooks on a phone, dark

Related Issues

Related: #46782 (lessons checked at the tool call).

Checklist

  • A Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...); PR Hygiene does not count commits
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

Contribution License Agreement

Contributions are accepted under the project's Apache-2.0 license.

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

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Sensitive Change Review

Sensitive files changed:

  • src/kiro_crew/hook_runtime/hook_dispatch.py

  • src/kiro_crew/hook_runtime/script_hooks.py

  • src/kiro_crew/hooks.py

  • @buluoray posted a complete reasoning template for fb6c7df.

@github-actions

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5) — ✅ PASS

Design-level review of fb6c7df0b968d3b043797a6a358d611f5c336876 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS does not.

Design-Verdict: PASS

Nothing blocks. The scope narrows only hooks a person opts into, unscoped hooks behave as before, and one predicate decides it on every event path.

Notes

  • Several documented cases skip a scoped deny hook without a word to the user: workflow-engine runs, cron starts, runs saved before this change, and runs dropped from the run table. The gateway log may record the skip once, but nothing shows it to the user. A one-line warning on the Hooks form when a bot or folder scope is picked would stop people reading a scoped hook as a guarantee.

[DESIGN-REVIEWED] fb6c7df

Description read

[DESCRIPTION-READ] 4bf6da16eb1778afe5a99975c341f3480d49e494ad6eb7e6d8182de99d582718

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 Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5) — ✅ PASS

Premise-level review of fb6c7df0b968d3b043797a6a358d611f5c336876 — 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 does not.

First-Principles-Verdict: PASS

Nothing blocks: the scope fields are optional, an unscoped hook runs as before, and each scoped path has a consumer. One new private helper re-implements an existing slot lookup.

Notes

  • Item 1 — duplicate of src/kiro_crew/shared_crew/memory_changes.py:108: the new _effective_key_slot_project loops effective_session_key(slot) == session_key again. slot_for_session already finds a slot by its slot key or its effective key and has 6 call sites. In _shared_workspace.py that loop now appears 3 times (lines 227, 405, 458), and line 227 is the new one. Subtraction: delete _effective_key_slot_project and the requesting_slot_project → fallback pair in _folder_of, and use _slot_project(slot_for_session(state, key)).

What this change ships

Inventory (10 items) — 9 justified

Intent: let a person limit a Hooks-page hook to one bot's chats and tasks, or to one folder, so a narrow guard stops firing in every chat. ADDITION.

  1. A scoped hook fires only for its bot's sessions or chats in its folder, on every event path — duplicate of shared_crew/memory_changes.py:slot_for_session (slot lookup only)
  2. The hook form has a "Runs in" bot picker and a folder field — justified
  3. The table has a "Runs in" column, and the phone list has a scope line — justified
  4. A hook whose bot was deleted fires nowhere, reads as deleted, is dimmed, isn't counted as enabled, and its line opens the editor — justified
  5. A task remembers its starting chat's folder across restarts (origin_project in runs.json) — justified
  6. A scoped hook no longer withholds KAS auto-approval from chats outside its scope — justified
  7. /hooks lists only the hooks that fire for that chat — justified
  8. The auto-approved cron/turn and sub-agent PreToolUse fires now pass their session key — justified
  9. The /api/members rows gain has_member_id, and the picker offers only those bots — justified
  10. A Bots-roster load failure shows a partial-impact notice with Retry on the Hooks page — undeclared

[FIRST-PRINCIPLES-REVIEWED] fb6c7df

Description read

[DESCRIPTION-READ] 10111077b9d5095971aa6a09ff8d41c24ef6942e86cc5aa101e9f17ed84175fc

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 Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5) — ✅ PASS (a BLOCK with no Trigger and no Outcome does not block)

UX-level review of fb6c7df0b968d3b043797a6a358d611f5c336876 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS does not.

UX-Verdict: PASS

cannot evaluate: missing the hook form's new "Runs in" picker and folder field. Those two controls are how a person limits a hook to one bot or one folder, which is what this PR is for, and no screenshot shows them.

Evidence gaps

  • The form's "Runs in" picker (the SimpleSelect with options "All chats", "{name} and its tasks", "Deleted bot"). No screenshot shows it, open or closed, so nobody saw the shown value change to the scope_either string when both a bot and a folder are set. Close it with stills of the New Hook and Edit forms, closed and open, with a bot and a folder chosen.
  • The "Folder (optional)" field. It appears in no screenshot. Close it with the same form stills.
  • Clicking the deleted-bot line, which opens the editor and moves focus to the picker. No screenshot shows the form it lands on. Close it with a still of the editor right after that click.
  • The "Failed to load" Bots roster notice with its Retry button. It appears in no screenshot. Close it with one still of that error.

Notes

  • The PR says the phone line "wraps instead of being cut", but shot-02 shows "Chats working in /home/alex..." and "Release Helper and its tasks..." cut off. Either the screenshot predates the fix or the claim is wrong; whichever it is, re-capture it.
  • The blind reader did not see the deleted-bot line as a button: "I see no place to 'choose another bot or folder'… I can't tell whether the dotted-underlined text is a link, a hover note or just styling." Give it a clear action label, such as "Choose another bot or folder" in link styling, separate from the explanation.
  • The switch on a hook whose bot was deleted still sits on the "on" side, while the row is dimmed and "ENABLED 4" leaves it out. The reader said: "I can't tell whether it is on, off or locked." Make the switch show that the hook isn't running, for example with a "Not running" tag next to it.

[UX-REVIEWED] fb6c7df

Description read

[DESCRIPTION-READ] 3b06112aaa8dbd163b5b58a140c8d584373273b101147650e3e51a6108bbd10e

That sha256 names everything this verdict read: the PR description, plus the 7 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 Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review — ✅ no blocking findings

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

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] fb6c7df

False positive or not applicable? A repository writer can comment:
/ai-review override gpt fb6c7df0b968d3b043797a6a358d611f5c336876 false-positive: <reason, 20 to 500 characters>

@github-actions

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review — ✅ no blocking findings

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

Review details

No findings.

[OPUS-REVIEWED] fb6c7df

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

False positive or not applicable? A repository writer can comment:
/ai-review override fable fb6c7df0b968d3b043797a6a358d611f5c336876 false-positive: <reason, 20 to 500 characters>

@github-actions

github-actions Bot commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Security Scope Review -- ✅ PASS

Which legitimate operations does fb6c7df0b968d3b043797a6a358d611f5c336876 newly refuse? Updated in place on each push. A script-confirmed regression blocks; the model proposes candidates and never decides a refusal.

Verdict basis: adjudicated, zero confirmed regressions.

Security scope review -- adjudicated candidates

  • macos-latest (platform posix): 9 classified, 0 newly refused, 9 still allowed.
  • ubuntu-latest (platform posix): 9 classified, 0 newly refused, 9 still allowed.
  • windows-latest (platform windows): 7 classified, 0 newly refused, 7 still allowed.

No candidate flipped from allowed to refused.

Scope-Verdict: PASS

Reason: The change limits where Hooks-page hooks fire, by session bot or folder. It does not touch the tool-call deny composite (sensitive-bash, exfil, deny-rules), so I expect the classifier to find nothing that flipped. The stricter parts are outside what the classifier can check: the new refusal in KAS hooks/execute, and the absolute-path check on scope_folder. Both are named below and do not block.

TIGHTENING: A Hooks-page hook with a scope now runs only for sessions in that scope, and KAS execution of such a hook is refused outside it -- the threat is a hook meant for one bot or folder running (or blocking work) in some other chat: if is_scoped(hook) and not hook_in_scope(hook, session_key=session_key): raise HookExecuteRefused("hook is not scoped to this session") (kas_wire.py _resolve_listed_hook), together with if is_scoped(hook): ... if not in_scope(hook, caller_scope, caller): continue (script_hooks.py ScriptHookStore.fire) and the write-boundary check if "\x00" in scope_folder or not os.path.isabs(os.path.expanduser(scope_folder)): raise ValueError("scope_folder must be an absolute path") (hook_scope.py validate_scope).

ADJUDICATED: 15 candidates, 0 confirmed newly-refused

PLATFORM COVERAGE: posix, windows and any. The diff assumes things about paths: os.path.isabs, os.sep prefix matching in _inside, case-folding when sys.platform is darwin or win32, and realpath/expanduser normalization. So the rows come in pairs:

  • posix: /work/repo, ~/.kirocrew, $PWD.
  • windows: a drive letter with \ separators, a UNC share (\\fileserver\share\repo), $env:USERPROFILE and .venv\Scripts\python.exe.
  • any: the one Windows/posix-neutral frontend test command.

These rows are commands that scoped hooks and their maintainers actually run, used as controls on the deny composite. They cannot check the path comparison inside hook_scope itself, because the classifier never reaches it. No assumed platform was left without a candidate.

UNADJUDICATED:

  • validate_scope (absolute-path check on scope_folder)
    • Call path: Hooks page form → POST/PUT hooks route (HOOK_CREATE_SCHEMA/HOOK_UPDATE_SCHEMA, max_len=4096) → ScriptHookStore.create/update → _apply_scope → validate_scope → normalize_folder.
    • Inputs I would have submitted:
      • /work/repo
      • ~/work/repo
      • C:\work\repo
      • C:/work/repo
      • \\fileserver\share\repo
      • \\?\C:\work\repo
      • a drive-relative C:work\repo
      • a root-relative \work\repo on Windows
    • The last one matters: os.path.isabs on Python 3.13+ under Windows rejects \work\repo, while earlier versions accept it. The result depends on the interpreter version, and no row can show it.
  • _inside (project-under-folder check)
    • Call path: scope_of → _project_for → dashboard _folder_of → realpath; then in_scope → _inside.
    • Inputs I would have submitted:
      • a project at the filesystem root under a folder of /
      • a folder C:\ with project C:\work
      • a case-differing Work/Repo against work/repo on Linux, where there is no folding
      • a mapped drive Z:\repo against the UNC spelling of the same share; realpath may not unify them, so a folder hook could miss
    • Unchecked possible over-refusal: rstrip(os.sep) on a root folder (/ or C:\) gives "" or C:. The / case still matches, but behavior at a drive root is not confirmed.
  • KAS hooks/execute and hooks/list scope refusal, and pre_tool_hook_matchers
    • Call path: KAS JSON-RPC → session_handle_kas._answer_kas_hooks_request / kas_wire.hooks_execute → _resolve_listed_hook → hook_in_scope.
    • Inputs I would have submitted:
      • a bot-scoped hook listed and executed from that bot's own chat
      • the same from its cron job (execution record only)
      • from a task step whose run started before origin_project existed (the docs say it has no folder, so a folder hook stops firing there after upgrade)
      • from a channel-linked slot whose effective key is the channel key
      • from a pooled KAS runtime with no session key yet, where every scoped hook withholds auto-approval and an extra permission prompt is expected
    • These are tool calls and JSON-RPC requests, not shell command lines, so the classifier gives them no verdict.

[SCOPE-REVIEWED] fb6c7df

@buluoray
buluoray force-pushed the crew/slack/hook-card branch from 166196a to 0f5c3df Compare December 4, 2026 09:29
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Dec 4, 2026
@buluoray
buluoray force-pushed the crew/slack/hook-card branch 2 times, most recently from 94a5e58 to c621f40 Compare December 4, 2026 11:01
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Dec 4, 2026
@buluoray
buluoray force-pushed the crew/slack/hook-card branch from c621f40 to 3ec500c Compare December 4, 2026 11:22
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Dec 4, 2026
@buluoray
buluoray force-pushed the crew/slack/hook-card branch from 3ec500c to cc0429c Compare December 4, 2026 12:23
@buluoray

buluoray commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Review dispositions for cc0429ca1920b462f7786013a00b2fe30ba8eb70 (findings on 3ec500c0711):

GPT F1 / named delegates lose their bot's scope — fixed. Class: every path that names the bot a call belongs to goes through hook_scope._member_id_for (store fire, KAS list and execute, kas_agents.pre_tool_hook_matchers, lane dispatch, spec hooks). It now falls back to the gateway-admitted execution identity (read_session_execution(...).member_id) when the session is not a recorded worker, and counts it only while that member is still one configured bot (member_config_for_id), so a deleted bot's hook still fires nowhere. Tests per caller kind: test_a_named_delegate_keeps_the_bot_it_was_admitted_as, test_the_store_fires_a_bot_hook_for_its_named_delegate, and delegate cases in the KAS list and auto-approve matcher tests. Reverting the fallback turns four of them red.

GPT F3 / channel-linked slots have no project — fixed. The resolver the dashboard installs (install_hook_scope_projects) now also finds the one slot whose effective session key is the firing key (_effective_key_slot_project), with no cross-slot fallback. Test: test_a_chat_linked_to_a_channel_reads_its_own_slots_project.

GPT F2 / Opus — PostToolUse folder scope sees no call paths — narrowed and documented. A call's paths and cwd are read before it runs; none of the four PostToolUse fire sites holds the call's input at result time. Rather than add a per-call input table to four subsystems in this PR, the rule is stated where users read it (steering-and-hooks.md) and in the spec: paths and cwd count for PreToolUse; a PostToolUse hook with a folder runs when the calling chat's project is inside the folder. Opus named this as the acceptable alternative. The card in #47125 proposes PreToolUse hooks only.

@buluoray
buluoray force-pushed the crew/slack/hook-card branch from cc0429c to 8889aa3 Compare December 4, 2026 12:51
@buluoray

buluoray commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Review dispositions for 8889aa35763dcd06eeb56e786df7b4d930df96aa (findings on cc0429ca192):

Opus — folder scope misses a batched tool's nested paths — fixed. hook_scope.call_paths now collects file paths at any depth with platform.tool_paths.target_paths (the walker the sensitive-path gate uses), so {"operations": [{"path": ...}]} matches; the cwd keys and shell words are read as before. Test: test_a_batched_tool_path_nested_in_its_operations (red when the walk is reverted to top-level keys).

Frontend Tests (2) — narrowFirstBaseline — fixed. The name cell's phone width is now written narrow-first (max-w-[7rem] sm:max-w-none).

UX — "screenshots show an older build". The description now carries screenshots captured from this branch: the open picker with and without a folder typed, the table with "Bot and its tasks or /home/…", "Removed bot", a folder and "All chats", the cell wrapping after /, and the phone table with Runs in under the name. Please re-read on this head.

@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Dec 4, 2026
@buluoray
buluoray force-pushed the crew/slack/hook-card branch from 8889aa3 to 11a618a Compare December 4, 2026 13:20
@buluoray

buluoray commented Dec 4, 2026

Copy link
Copy Markdown
Contributor Author

Review dispositions for 11a618a90c541d9e1583625cf2ebe1247457004b (findings on 8889aa35763):

GPT F1 — folder scope misses targetFile (KAS delete_file) — fixed. The scope extractor now reads every spelling the platform path gate reads (platform.tool_paths.TARGET_PATH_KEYS) plus its own directory keys, at any depth. Test: test_every_file_path_spelling_the_path_gate_reads (path, file_path, filePath, targetFile, target_file).

Lint Gate / Coverage Gate were held by the AI review BLOCK on the previous head; they run again on this one.

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Dec 4, 2026
@buluoray
buluoray force-pushed the crew/slack/hook-card branch from 11a618a to 91ab7cd Compare December 4, 2026 13:29
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Dec 5, 2026
@buluoray

buluoray commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Disposition for the review round on 7f0f60b. Fixed in 1f4485c.

  • GPT: start_folder resolved the no-chat folder on the event loop (run_inputs.py:110). Fixed by removing the second resolve rather than offloading it. Both callers already resolve the person's folder one line earlier with _resolve_workspace_dir. start_folder(session_key, picked) now takes that resolved value and keeps it as given, so it reads no file system on the loop. Callers: plan_mode.plan passes _override, and run_lifecycle.start_background passes picked. The dashboard's new-from-steps route already passed "".
    Test: test_a_start_with_no_chat_reads_no_file_system_on_the_event_loop makes Path.resolve raise. It fails when start_folder resolves again.
    Not changed: the callers' own _resolve_workspace_dir call was on the loop before this PR, and this PR does not touch it.

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Dec 5, 2026
@buluoray
buluoray force-pushed the crew/slack/hook-card branch from 1f4485c to bba9153 Compare December 5, 2026 10:44
@buluoray

buluoray commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Disposition for head bba9153 (rebased on main, no conflicts).

GPT: a task can find another run's chat instead of its own (_run_of_key). Fixed in its own commit, fix(hooks): match a run's own keys before another run's chat tab. A session key is now matched by whole-key equality against the keys every run id makes, across all runs, before any prefix match. Only when no run owns the key exactly does the longest run id whose :chat: prefix the key carries win. test_a_run_named_after_another_runs_chat_tab_finds_its_own_run covers the case GPT named; it fails on the previous head. The spec (memory-skills-hooks.md) says the same.

The cases where a scoped hook still cannot find the chat that started a task are listed in the PR body under Known limits: where a task cannot find the chat that started it. In each of them a bot- or folder-scoped hook does not run, and unscoped hooks are not affected. Further findings of this class are handled against that list rather than with another lookup path.

UX: the Runs in text.

  • With a bot and a folder, the picker and the table cell now read "{bot} and its tasks, and chats working in {folder}" (scope_either), in all 12 locales.
  • A hook whose bot was deleted is listed in the picker as "Deleted bot". The row keeps the full sentence: "Its bot was deleted, so this hook doesn't run. Choose another bot or folder."
  • On a phone the scope line wraps instead of being cut at the end.

@buluoray
buluoray marked this pull request as ready for review December 5, 2026 12:01
@buluoray
buluoray requested review from a team and KiroCrewCaptain as code owners December 5, 2026 12:01
@buluoray
buluoray requested a review from bolichen97 December 5, 2026 12:01
@buluoray
buluoray enabled auto-merge (squash) December 5, 2026 12:01
@buluoray

buluoray commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Sensitive change review

  • Head commit: bba9153
  • What rule changed: a Hooks-page hook may carry scope_bot (a bot's member id) and/or scope_folder (a resolved folder). Every path that picks stored hooks (ScriptHookStore.fire, the lane dispatch, the KAS hooks list, execute and auto-approval matchers, the Stop-presence check, /hooks) asks one predicate, hook_scope.in_scope, and skips a scoped hook for a call outside its scope. An unscoped hook is unchanged. A task's folder is fixed when the task starts (Project.origin_project), and a run's starting chat is registered before its first turn (TaskRunner._register_run_origin), so a task's keys, :decompose included, have that chat's bot. A key finds its run by exact match across all runs first, and only then by the longest run id whose chat-tab prefix it carries. The cases where a task cannot find its starting chat (a scoped hook then does not run) are listed under Known limits in the PR body.
  • Before -> after (what was allowed/blocked, now): before, every enabled hook ran for every chat's matching call. After, a scoped hook runs only for its bot's own chats, the tasks they start and their sub-agents, or for a session whose project is inside its folder. A scope only narrows where a hook runs: no stored value, an unreadable one included, makes a hook run where an unscoped copy would not. A caller the runner cannot name does not run a scoped hook (logged once). KAS auto-approval is withheld only where a bot-scoped hook can fire; a folder-scoped hook still withholds it everywhere. The notify-only PreToolUse paths that fired with no session key, stream_and_collect among them, now pass the key they had.
  • Worst case if wrong (breaks commands / leaks secret / locks user out): a scoped deny hook misses a call it was meant to stop, so the person's own guard is narrower than intended. No path widens a hook. Unscoped hooks, the deny list, the sandbox, approvals and governance are untouched.
  • Evidence checked (which sandbox result proves it): on a throwaway Linux box (Amazon Linux 2023), main ran a bot-scoped and a folder-scoped guard on every call; head 166196a ran the bot guard only in the bot's task, the folder guard only for the chat in the folder, and neither with no session key (PR body, Real-machine verification). Later heads change how a task finds its starting chat and folder; those are pinned per case in test_hook_scope_task_folder.py (each seen to fail with its rule removed), and test_a_scope_only_ever_narrows_where_a_hook_fires pins that any stored scope only narrows.
  • No regression:
    • Tools still work (which tools/commands were run, result): Hooks tab create, edit, list and the Runs in column on a running gateway (the box above); hook fire through ScriptHookStore.fire, the KAS hooks list, execute and withhold, and the lane dispatch, in the event-path by caller-kind matrix of test_hook_scope.py.
    • Backward compatible (old config / old data / old callers still work, how checked): a stored hook without scope fields loads and fires as before; the fields are optional on create and update and kept on an edit that leaves them out (test_scope_round_trips_and_an_edit_keeps_it). A run saved before origin_project existed loads with no folder, so its folder hooks do not run; its bot hooks still do.
    • Existing tests (which suites passed on this head): CI on this head (rebased onto main at 9b73736): backend Linux and Windows shards, frontend shards and the E2E runs. Locally on this head: test_hook_scope, test_hook_scope_task_folder, test_taskrunner_bindings, test_legacy_binding_roster, test_tool_permission, test_deferred_followup_notice, test_workflow_security, test_validation_parts_facade (1060 passed); website HooksPage suites (19 passed), tsc and the i18n check.
  • How to undo: revert this PR. Stored scope_bot/scope_folder and origin_project keys are then ignored on load, and every hook fires everywhere again.

@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: action required A blocking check or review needs attention labels Dec 5, 2026

@bolichen97 bolichen97 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 on bba91530a1. The scope design reads right in src/kiro_crew/hook_scope.py: the bot and project come from the session Kiro Crew runs the call under, never from the hook's script or the tool call's arguments; an unreadable scope loads as UNREADABLE_SCOPE and matches nothing; a deleted bot matches nothing; and a scope only ever narrows an unscoped hook. The known-limits list is clear about where a scoped hook does not run, and the test matrix covers every event path against every caller kind.

The real-machine section is what holds this back, on three points (real-machine-verify, "Reviewing"):

  1. The hooks never ran their own logic. Every row exited 1 because the box's interpreter could not load inside the hook sandbox, and a hook that cannot start blocks. So the run shows which hooks were picked, but not that a scoped hook which does start still denies, or that an out-of-scope one lets the call through. Please run it with a hook command that starts in the sandbox (for example a /bin/sh one-liner that prints and exits 2), and show one denied call and one allowed call.
  2. The After run is on 166196aaf8f, not the head. Please re-run on the current head, or name what changed since and which test pins it.
  3. Cleanup is still open. "The box is deleted once the stacked card PR is verified" means it still exists. Please delete it and paste the empty listing, or say where it is and when it goes.

A live agent turn would be best (a bot's task stopped by its bot-scoped guard, and another chat not stopped). If the model sign-in is still missing, a pod run through the real PreToolUse path is enough, and please say which one you used.

Non-blocking question: _member_id_for loads KiroCrewConfig on each lookup. Is scope_of cached per session, or does every PreToolUse pay for a config load once a scoped hook exists?

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: passed Eligible automated validation passed for the current revision labels Dec 5, 2026
@buluoray

buluoray commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

@bolichen97 thanks. All three points are fixed in the description; the head is unchanged (bba91530a1), so nothing was pushed.

  1. The hooks now run their own logic. Both guards are /bin/sh one-liners, printf '<name>: stopped this call\n' >&2; exit 2, which start inside the hook sandbox. On the head, the bot-scoped guard denies the bot's task ("bot-guard: stopped this call") and lets another chat's call through; the folder-scoped guard denies a chat working in its folder and lets a chat elsewhere through. On main both stop every caller. The earlier exit 1 came from the box's default Python not loading its own library path inside the sandbox; this run uses a standalone CPython 3.12.16 for the parent and /bin/sh for the hooks.
  2. The run is on the current head. After is bba91530a1, Before is this PR's base 9b73736edf, each installed from a git archive of that commit into a fresh venv. The path is the gateway's own PreToolUse gate (permission_pre_tool_block) with the real sandboxed runner, in process, not a live agent turn: the box has no model sign-in. The description says so and names how the bot's task and the two chats' folders were recorded.
  3. Cleanup is done. The box was deleted at 14:47:59Z; the listing filtered to its label is empty, pasted in the description.

Your question: no, scope_of is not cached per session. It is computed once per fire, lazily, and only when a scoped hook is stored (ScriptHookStore.fire takes it once for all hooks of the fire, off the event loop). So once a scoped hook exists, every PreToolUse fire does one KiroCrewConfig.load(), which is a stat-keyed cache hit for the parsed document but still rebuilds the section dataclasses. It should be cheaper; #47818 tracks reusing the bot lookup through config.load_memo.memoized, keeping the project lookup per fire. I left it out of this PR so the reviewed head does not move.

@buluoray
buluoray requested a review from bolichen97 December 5, 2026 14:49
@github-actions github-actions Bot added the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Dec 5, 2026
buluoray and others added 3 commits December 5, 2026 17:54
A hook can now carry scope_bot (a bot's id) and scope_folder (an
absolute folder). A bot-scoped hook fires only in that bot's own chat,
the tasks it starts and their sub-agents; a folder-scoped hook fires
in a chat whose project is under the folder. Either match fires; no
scope keeps today's every-chat behaviour.

The scope is one decision per session, hook_scope.scope_of: the
session's bot and its chat's project. A sub-agent takes the project of
the chat it was started from, a task step the scope of its starting
chat. A tool call's arguments are never read, so a folder hook does
not fire when a chat whose project is elsewhere touches that folder;
to guard a folder from every chat, use All chats and test the path in
the command. A caller it cannot name is a logged miss, never a fire.

Every path that picks stored hooks reads the same decision: the
store's fire, the lane dispatch, the KAS hooks list and execute, the
KAS auto-approval matchers, the Stop-presence check and /hooks. The
Hooks tab gets a Runs in picker and folder field, and each scoped row
names its bot and folder; with both set, the picker's shown value joins
them with "or".
A run named <id>:chat:... took the older run's folder and bot, because
_run_of_key matched the first run whose :chat: prefix fit, in table order.
Match every run's own keys first, then the longest-id :chat: prefix.
The phone Hooks page is now a list (#47747), so the scope line that
sat under the name in the phone table moves into HooksPhoneList, with
the deleted-bot line as the control that opens the editor and the
switch described by it. The Bots roster notice is a partial failure,
and the page's newer tests mock the roster.
@buluoray

buluoray commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

@bolichen97 the head moved to fb6c7df0b9 for the conflict with main only: #47747 merged and made the Hooks page a stacked list on a phone, and both PRs change HooksPage.tsx.

  • The Runs in column, the deleted-bot line and the picker are carried onto main's version of the page; the scope line that sat under the name in the phone table now sits under the name in the phone list (HooksPhoneList.tsx), and a deleted bot's line still describes its switch.
  • One new commit on top, fix(hooks): show a hook's scope on the phone Hooks list; no backend file changed. HooksPage.scope.test.tsx gained a phone case, and the Hooks page suites (113 tests), tsc and the backend scope suites pass.
  • The real-machine run in the description is the one on bba91530a1 and says so, with a line on what changed since and which tests pin it. The screenshots are retaken at fb6c7df0b9.

Your earlier three points stand as answered above.

@buluoray

buluoray commented Dec 5, 2026

Copy link
Copy Markdown
Contributor Author

Sensitive change review

  • Head commit: fb6c7df
  • Since the earlier review (posted on bba91530a1ed): the branch was rebased onto main after feat(hooks): show the Hooks page as a compact list on a phone #47747 merged, to clear a conflict in the Hooks page only. One new commit moves the scope line into the phone Hooks list; no backend file changed, so the rule below is unchanged.
  • What rule changed: a Hooks-page hook may carry scope_bot (a bot's member id) and/or scope_folder (a resolved folder). Every path that picks stored hooks (ScriptHookStore.fire, the lane dispatch, the KAS hooks list, execute and auto-approval matchers, the Stop-presence check, /hooks) asks one predicate, hook_scope.in_scope, and skips a scoped hook for a call outside its scope. An unscoped hook is unchanged. A task's folder is fixed when the task starts (Project.origin_project), and a run's starting chat is registered before its first turn (TaskRunner._register_run_origin), so a task's keys, :decompose included, have that chat's bot. A key finds its run by exact match across all runs first, and only then by the longest run id whose chat-tab prefix it carries. The cases where a task cannot find its starting chat (a scoped hook then does not run) are listed under Known limits in the PR body.
  • Before -> after (what was allowed/blocked, now): before, every enabled hook ran for every chat's matching call. After, a scoped hook runs only for its bot's own chats, the tasks they start and their sub-agents, or for a session whose project is inside its folder. A scope only narrows where a hook runs: no stored value, an unreadable one included, makes a hook run where an unscoped copy would not. A caller the runner cannot name does not run a scoped hook (logged once). KAS auto-approval is withheld only where a bot-scoped hook can fire; a folder-scoped hook still withholds it everywhere. The notify-only PreToolUse paths that fired with no session key, stream_and_collect among them, now pass the key they had.
  • Worst case if wrong (breaks commands / leaks secret / locks user out): a scoped deny hook misses a call it was meant to stop, so the person's own guard is narrower than intended. No path widens a hook. Unscoped hooks, the deny list, the sandbox, approvals and governance are untouched.
  • Evidence checked (which sandbox result proves it): on a throwaway Linux box (Amazon Linux 2023), main ran a bot-scoped and a folder-scoped guard on every call; head 166196a ran the bot guard only in the bot's task, the folder guard only for the chat in the folder, and neither with no session key (PR body, Real-machine verification). Later heads change how a task finds its starting chat and folder; those are pinned per case in test_hook_scope_task_folder.py (each seen to fail with its rule removed), and test_a_scope_only_ever_narrows_where_a_hook_fires pins that any stored scope only narrows.
  • No regression:
    • Tools still work (which tools/commands were run, result): Hooks tab create, edit, list and the Runs in column on a running gateway (the box above); hook fire through ScriptHookStore.fire, the KAS hooks list, execute and withhold, and the lane dispatch, in the event-path by caller-kind matrix of test_hook_scope.py.
    • Backward compatible (old config / old data / old callers still work, how checked): a stored hook without scope fields loads and fires as before; the fields are optional on create and update and kept on an edit that leaves them out (test_scope_round_trips_and_an_edit_keeps_it). A run saved before origin_project existed loads with no folder, so its folder hooks do not run; its bot hooks still do.
    • Existing tests (which suites passed on this head): CI on this head (rebased onto main at eb23e9b): backend Linux and Windows shards, frontend shards and the E2E runs. Locally on this head: test_hook_scope, test_hook_scope_task_folder, test_taskrunner_bindings, test_legacy_binding_roster, test_tool_permission, test_deferred_followup_notice, test_workflow_security, test_validation_parts_facade (1060 passed, serial); website HooksPage suites (113 passed), tsc and the i18n check.
  • How to undo: revert this PR. Stored scope_bot/scope_folder and origin_project keys are then ignored on load, and every hook fires everywhere again.

@KiroCrewCaptain

Copy link
Copy Markdown
Collaborator

Code change approver recommendation: A person should decide

Why: the decider thinks the change is probably fine but estimates a 20% chance that this change introduces a defect, above the 15% limit for approving on its own.

I recommend approving. The PR adds two optional fields to a Hooks-page hook, scope_bot (a bot's member id) and scope_folder (an absolute folder, stored resolved). Every path that picks stored hooks checks them through one decision per session (scope_of) and one check (in_scope). I traced each path against the code:

  • ScriptHookStore.fire, the call behind every event.
  • The lane dispatch, which reads the session key the payload carries.
  • The KAS hooks list, execute (scope checked again at execute time) and auto-approval matchers. The re-projection check before each turn reads the new key, so a later change of project is picked up.
  • The Stop-presence check and /hooks.
  • The dashboard, channel, task-step and sub-agent PreToolUse gates, all of which pass a session key or a parent key.

Unscoped hooks behave exactly as before. The new fields round-trip through asdict/from_dict. A partial update keeps them. A non-string value on disk loads as a value that matches nothing. The bundle-import sanitizer keeps unknown fields. A run's new origin_project is persisted and reloaded with origin_session_key. It is registered before the run's first turn, and both are removed to

Tier: 2, held for a person: changes requested.

An automated recommendation, not a review: a maintainer still decides. It approves on its own only when the estimated chance of a defect is at most 15% and the change has at most 400 changed lines. Decider v3c (217fe607) · commit fb6c7df0b9 · 2209 changed lines. If this recommendation is wrong, reply here: replies are how the approver is evaluated.

@bolichen97 bolichen97 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 on fb6c7df0b9. All three real-machine points from my change request are now covered (real-machine-verify, "Reviewing"):

  1. The guards are /bin/sh one-liners that start inside the hook sandbox, so each deny is the guard's own verdict. On main 9b73736edf both guards stop every caller. On the branch each guard denies its own caller and lets the out-of-scope call through, for the bot scope and the folder scope.
  2. The run is on bba91530a1. Since then the branch was only rebased: 7af1efa591 is the same backend commit, and fb6c7df0b9 touches only HooksPage.tsx and its tests, pinned by HooksPage.scope.test.tsx (desktop column and the new phone case).
  3. The box was deleted at 14:47:59Z, and the label-filtered listing is empty.

The Captain's line on this head is verdict=human final=yes, and all checks are green. Approving, with auto merge on.

AI-assisted, sent by Bolin Review bot

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants