diff --git a/run.json b/run.json index e8ce09ae5..8c2e18585 100644 --- a/run.json +++ b/run.json @@ -492,7 +492,7 @@ "kind": "running" }, "status_updated_at": "2026-05-24T17:13:10.096457Z", - "last_event_at": "2026-05-24T17:40:34.020671Z", + "last_event_at": "2026-05-24T17:57:18.881493Z", "pending_control": null, "checkpoints": [ { @@ -740,9 +740,9 @@ } }, { - "seq": 0, + "seq": 976, "checkpoint": { - "timestamp": "2026-05-24T17:40:34.045362Z", + "timestamp": "2026-05-24T17:40:37.848859Z", "current_node": "implement", "completed_nodes": [ "start", @@ -753,29 +753,152 @@ ], "node_retries": {}, "context_values": { + "graph.goal": "---\ntitle: feat: StageProjection agent tools API\ntype: feat\nstatus: active\ndate: 2026-05-24\n---\n\n# feat: StageProjection Agent Tools API\n\n## Overview\n\nExpose the complete effective tool list for each agent-backed stage through `StageProjection`, so UI and API consumers can show actual tools such as `apply_patch`, `grep`, `glob`, `read_file`, MCP tools, skill tools, and subagent tools without inferring them from `permission_level`.\n\nThe API should expose tool summaries with `name`, `description`, `source`, `category`, and `invoked`. It must not expose full JSON parameter schemas in the run projection.\n\n## Problem Frame\n\nThe stage sidebar currently has permission metadata such as \"Full access\", but `permission_level` is only an access mode. It does not tell consumers which tools were actually exposed to the model after provider profile setup, optional tool registration, MCP integration, and tool access policy filtering.\n\nThe authoritative list already exists at request-build time in the agent session registry. The API needs to capture that effective list once per stage session and project it onto the stage.\n\n## Requirements Trace\n\n- R1. Add a StageProjection API field containing the complete effective tools for a stage session.\n- R2. Include `name`, `description`, `source`, `category`, and `invoked` for each tool.\n- R3. Do not infer tools from `permission_level` in backend or frontend code.\n- R4. Do not expose full tool parameter schemas through StageProjection.\n- R5. Preserve existing `permission_level` and `mcp_servers` fields for compatibility.\n- R6. Mark individual tools as invoked when matching `agent.tool.started` events are projected.\n- R7. Keep legacy runs backward compatible by defaulting missing tool lists to empty.\n\n## Scope Boundaries\n\n- Do not remove or rename `StageProjection.permission_level`.\n- Do not remove the existing MCP server projection or `AgentMcpToolSummary`.\n- Do not change completion API tool definitions.\n- Do not add ACP-native tool discovery in this pass unless an ACP path already has an equivalent effective tool list available.\n- Do not render parameter schemas in the web UI.\n\n## Context & Research\n\n### Relevant Code and Patterns\n\n- OpenAPI is the source of truth for HTTP contracts in `docs/public/api-reference/fabro-api.yaml`.\n- Shared API/projection DTOs should live in `fabro-types`, with `fabro-api/build.rs` replacements to avoid duplicate generated Rust types.\n- `StageProjection` lives in `lib/crates/fabro-types/src/run_projection.rs`.\n- Durable run event props live in `lib/crates/fabro-types/src/run_event/agent.rs` and `lib/crates/fabro-types/src/run_event/mod.rs`.\n- Workflow event conversion and event names live in `lib/crates/fabro-workflow/src/event/convert.rs`, `events.rs`, and `names.rs`.\n- Projection replay lives in `lib/crates/fabro-store/src/run_state.rs`.\n- The effective request tool list is built in `lib/crates/fabro-agent/src/session.rs` from `ToolRegistry::definitions_with_source_for_policy`.\n- Tool source metadata already exists as `ToolSource` and `ToolDefinitionWithSource` in `lib/crates/fabro-agent/src/tool_registry.rs`.\n- Tool category mapping already exists in `lib/crates/fabro-agent/src/tool_permissions.rs`.\n- The sidebar display lives in `apps/fabro-web/app/components/stage-insights-sidebar.tsx`.\n\n### Strategy Docs\n\n- Read `docs/internal/events-strategy.md` before adding the new durable event.\n- Read `docs/internal/testing-strategy.md` before adding or reorganizing tests.\n- Follow the OpenAPI type ownership guidance in `AGENTS.md`: reuse `fabro-types` through `fabro-api/build.rs` replacements when the API schema has the same product meaning and serde shape.\n\n## Key Technical Decisions\n\n- Add a new StageProjection field named `agent_tools`, not `tools`, to avoid ambiguity with MCP nested tools and completion tool definitions.\n- Add a dedicated durable event named `agent.tools.available` instead of overloading `agent.session.activated`.\n- Capture the effective tool list after session setup and filtering, using the same path as model request construction.\n- Store descriptions in the summary because they are useful API/UI metadata; omit parameter schemas to keep projection payloads small and avoid leaking full implementation detail.\n- Keep `AgentMcpToolSummary` MCP-only. Add a new general-purpose `AgentToolSummary` instead of stretching the MCP type beyond its meaning.\n- Treat `invoked` as projected state. The availability event should emit tools with `invoked: false`; replay of `agent.tool.started` flips matching tools to true.\n\n## API Contract\n\nAdd these schemas to OpenAPI and map them to `fabro_types` replacements:\n\n- `AgentToolSummary`\n - required: `name`, `description`, `source`, `category`, `invoked`\n - `name`: exposed tool name, e.g. `apply_patch` or `mcp__filesystem__read_file`\n - `description`: model-facing tool description\n - `source`: `AgentToolSource`\n - `category`: `AgentToolCategory`\n - `invoked`: boolean\n- `AgentToolSource`\n - tagged by `kind`\n - `native`\n - `mcp` with `server_name` and `original_name`\n - `skill`\n- `AgentToolCategory`\n - enum: `read`, `write`, `shell`, `subagent`, `other`\n- `AgentToolsAvailableProps`\n - required: `tools`, `visit`\n - `tools`: array of `AgentToolSummary`\n - `visit`: stage visit number\n\nAdd to `StageProjection`:\n\n- `agent_tools`: array of `AgentToolSummary`\n- Default to an empty array when omitted.\n- Skip serializing when empty, matching existing projection optional-list style.\n\nAdd event body:\n\n- Serialized event name: `agent.tools.available`\n- Event body type: `AgentToolsAvailableProps`\n\n## Implementation Units\n\n- [ ] **Unit 1: Add shared tool summary types**\n\n**Goal:** Define the canonical API/projection DTOs in `fabro-types`.\n\n**Files:**\n- Modify: `lib/crates/fabro-types/src/run_event/agent.rs`\n- Modify: `lib/crates/fabro-types/src/run_event/mod.rs`\n- Modify: `lib/crates/fabro-types/src/run_projection.rs`\n- Modify: `lib/crates/fabro-types/src/lib.rs`\n\n**Work:**\n- Add `AgentToolSummary`, `AgentToolSource`, `AgentToolCategory`, and `AgentToolsAvailableProps`.\n- Add `EventBody::AgentToolsAvailable` serialized as `agent.tools.available`.\n- Add `agent_tools: Vec` to `StageProjection`.\n- Ensure all new fields default cleanly for older persisted events/projections.\n- Export the new public types from `fabro-types`.\n\n- [ ] **Unit 2: Capture effective session tools**\n\n**Goal:** Provide an authoritative one-time source for the list that the model can actually call.\n\n**Files:**\n- Modify: `lib/crates/fabro-agent/src/session.rs`\n- Modify: `lib/crates/fabro-workflow/src/handler/llm/api.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/events.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/names.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/convert.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/stored_fields.rs` only if the new event needs non-standard stored fields.\n\n**Work:**\n- Add `Session::available_tools()` that returns the same effective `ToolDefinitionWithSource` list as `build_request()`.\n- Map `ToolDefinitionWithSource` to `AgentToolSummary` at the workflow boundary.\n- Populate `description` from `ToolDefinition.description`.\n- Populate `source` from `ToolSource`.\n- For MCP tools, include the server name from `ToolSource::Mcp` and derive `original_name` from the qualified exposed name using the existing MCP naming convention.\n- Populate `category` from the existing tool category mapping for known exposed names; use `other` when no category mapping applies.\n- Emit `agent.tools.available` once for the stage session after session setup and filtering are complete.\n\n- [ ] **Unit 3: Project available and invoked tools**\n\n**Goal:** Make `StageProjection.agent_tools` replay-authoritative.\n\n**Files:**\n- Modify: `lib/crates/fabro-store/src/run_state.rs`\n\n**Work:**\n- On `EventBody::AgentToolsAvailable`, replace the current stage visit's `agent_tools` with the event tools.\n- On `EventBody::AgentToolStarted`, find a matching `agent_tools` entry by exposed `tool_name` and set `invoked = true`.\n- Keep the existing MCP server `invoked` update unchanged.\n- If a legacy run has no availability event, do not synthesize a full list from permissions.\n\n- [ ] **Unit 4: Update OpenAPI and generated clients**\n\n**Goal:** Expose the new projection field and event contract through public API clients without duplicate Rust API types.\n\n**Files:**\n- Modify: `docs/public/api-reference/fabro-api.yaml`\n- Modify: `lib/crates/fabro-api/build.rs`\n- Modify: `lib/crates/fabro-api/src/lib.rs`\n- Modify generated files under `lib/crates/fabro-api/src/generated.rs` via `cargo build -p fabro-api`.\n- Modify generated files under `lib/packages/fabro-api-client/src` via TypeScript client generation.\n\n**Work:**\n- Add the OpenAPI schemas listed in the API Contract section.\n- Add `StageProjection.agent_tools`.\n- Add `fabro-api/build.rs` replacements for the new `fabro-types` types.\n- Regenerate Rust API code.\n- Regenerate TypeScript API client code.\n\n- [ ] **Unit 5: Render tools in the web sidebar**\n\n**Goal:** Replace the permission-derived sidebar display with the actual projected tool list.\n\n**Files:**\n- Modify: `apps/fabro-web/app/components/stage-insights-sidebar.tsx`\n- Modify: `apps/fabro-web/app/components/stage-insights-sidebar.test.tsx`\n\n**Work:**\n- Render `stage.agent_tools` when present.\n- Show each tool's name, description, source/category, and invoked state.\n- Keep permission level as secondary metadata or fallback for legacy stages with no `agent_tools`.\n- Do not infer tool availability from permission level.\n\n## Test Plan\n\n- `fabro-types`\n - JSON round-trip for `agent.tools.available`.\n - Serialization checks for `AgentToolSource` and `AgentToolCategory`.\n - Backward compatibility check that missing `agent_tools` deserializes to an empty list.\n\n- `fabro-workflow`\n - Event name and conversion tests for `agent.tools.available`.\n - Capture test proving native tools such as `apply_patch`, `grep`, and `glob` are emitted from the effective registry path.\n - MCP source mapping test for a qualified MCP tool name.\n\n- `fabro-store`\n - Projection test that `agent.tools.available` populates `StageProjection.agent_tools`.\n - Projection test that `agent.tool.started` marks only the matching tool as invoked.\n - Regression test that MCP server `invoked` status still updates as before.\n\n- `fabro-api`\n - Type identity/parity tests confirming API types reuse `fabro_types::AgentToolSummary`, `AgentToolSource`, `AgentToolCategory`, and `AgentToolsAvailableProps`.\n - StageProjection round-trip test including `agent_tools`.\n\n- `fabro-web`\n - Sidebar test rendering tool names and descriptions from `stage.agent_tools`.\n - Sidebar test showing invoked state.\n - Legacy fallback test for stages without `agent_tools`.\n\n## Run Checks\n\n- `cargo +nightly-2026-04-14 fmt --check --all`\n- `cargo nextest run -p fabro-types -p fabro-workflow -p fabro-store -p fabro-api`\n- `cargo build -p fabro-api`\n- `cd lib/packages/fabro-api-client && bun run generate`\n- `cd apps/fabro-web && bun test && bun run typecheck`\n\n## Assumptions\n\n- The first implementation targets normal API-backed agent sessions, not ACP-native sessions.\n- `description` is safe to expose because it is already model-facing tool metadata, but parameter schemas remain out of scope for StageProjection.\n- `agent_tools` is a complete list only for runs that emit `agent.tools.available`; legacy runs return an empty list and may still show existing permission/MCP metadata.\n- If tool registration becomes mutable later, the event contract can be re-emitted and projection replacement semantics will still work.\n", + "internal.thread_id": "preflight_lint", + "internal.retry_count.start": 0, + "failure_signature": "", + "internal.retry_count.toolchain": 0, + "internal.work_dir": "/home/daytona/workspace/fabro", + "last_stage": "implement", + "internal.fidelity": "compact", + "failure_class": "", + "thread.start.current_node": "toolchain", + "current_node": "implement", + "graph.rankdir": "LR", + "internal.retry_count.preflight_compile": 0, + "graph.model_stylesheet": "\n * { model: claude-opus-4-7; }\n ", + "internal.retry_count.implement": 0, + "internal.node_visit_count": 1, + "internal.retry_count.preflight_lint": 0, + "internal.run_id": "01KSDFKD9JJS7D2ZJ6JQYXV58Z", + "last_response": "The TS generator is pinned now, but this sandbox lacks Java, which OpenAPI Generator needs. I’ll install a headless JRE and rerun generation.", + "thread.preflight_compile.current_node": "preflight_lint", + "command.output": "blob://sha256/12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126", + "thread.preflight_lint.current_node": "implement", "response.implement": "The TS generator is pinned now, but this sandbox lacks Java, which OpenAPI Generator needs. I’ll install a headless JRE and rerun generation.", + "thread.toolchain.current_node": "preflight_compile", + "outcome": "succeeded" + }, + "node_outcomes": { + "implement": { + "status": "succeeded", + "context_updates": { + "last_stage": "implement", + "last_response": "The TS generator is pinned now, but this sandbox lacks Java, which OpenAPI Generator needs. I’ll install a headless JRE and rerun generation.", + "response.implement": "The TS generator is pinned now, but this sandbox lacks Java, which OpenAPI Generator needs. I’ll install a headless JRE and rerun generation." + }, + "notes": "Stage completed: implement", + "usage": { + "input": { + "usage": { + "model": { + "provider": "openai", + "model_id": "gpt-5.5" + }, + "tokens": { + "input_tokens": 6711598, + "output_tokens": 22676, + "reasoning_tokens": 11522, + "cache_read_tokens": 16107008, + "cache_write_tokens": 0 + } + }, + "facts": { + "algorithm": "openai" + } + }, + "total_usd_micros": 42637434 + } + }, + "toolchain": { + "status": "succeeded", + "context_updates": { + "command.output": "blob://sha256/fc14b2ba2d770e5cd3169df7a29525c962adfc4cfa3097b9098c63ebd61a748c" + }, + "notes": "Script completed: command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1", + "usage": null + }, + "preflight_compile": { + "status": "succeeded", + "context_updates": { + "command.output": "blob://sha256/12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126" + }, + "notes": "Script completed: cargo check -q --workspace 2>&1", + "usage": null + }, + "start": { + "status": "succeeded", + "usage": null + }, + "preflight_lint": { + "status": "succeeded", + "context_updates": { + "command.output": "blob://sha256/12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126" + }, + "notes": "Script completed: cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1", + "usage": null + } + }, + "next_node_id": "simplify_opus", + "git_commit_sha": "e93905f7589a03544e39e62df728ab414200e93c", + "node_visits": { + "preflight_compile": 1, + "preflight_lint": 1, + "start": 1, + "implement": 1, + "toolchain": 1 + } + }, + "diff": { + "patch": "diff --git a/apps/fabro-web/app/components/stage-insights-sidebar.test.tsx b/apps/fabro-web/app/components/stage-insights-sidebar.test.tsx\nindex c505a9ffd..713f1b4bc 100644\n--- a/apps/fabro-web/app/components/stage-insights-sidebar.test.tsx\n+++ b/apps/fabro-web/app/components/stage-insights-sidebar.test.tsx\n@@ -3,6 +3,7 @@ import TestRenderer, { act } from \"react-test-renderer\";\n import { MemoryRouter } from \"react-router\";\n \n import {\n+ AgentToolCategory,\n AgentSkillActivationSource,\n PermissionLevel,\n StageContextWindowCategory,\n@@ -66,7 +67,7 @@ function makeContextWindow(overrides: Partial = {}): StageCo\n let restoreWindow: (() => void) | null = null;\n beforeAll(() => {\n const store = new Map();\n- for (const key of [\"todos\", \"context\", \"skills\", \"mcps\"]) {\n+ for (const key of [\"todos\", \"context\", \"tools\", \"skills\", \"mcps\"]) {\n store.set(`fabro:stage-insights-section:${key}`, \"1\");\n }\n const stub = {\n@@ -157,6 +158,50 @@ describe(\"StageInsightsSidebar\", () => {\n expect(dom).toContain(\"Full access\");\n });\n \n+ test(\"renders projected agent tool names, descriptions, categories, and invoked state\", () => {\n+ const dom = render(\n+ makeStage({\n+ agent_tools: [\n+ {\n+ name: \"apply_patch\",\n+ description: \"Apply a unified diff patch\",\n+ source: { kind: \"native\" },\n+ category: AgentToolCategory.WRITE,\n+ invoked: true,\n+ },\n+ {\n+ name: \"grep\",\n+ description: \"Search file contents\",\n+ source: { kind: \"native\" },\n+ category: AgentToolCategory.READ,\n+ invoked: false,\n+ },\n+ ],\n+ permission_level: PermissionLevel.FULL,\n+ }),\n+ null,\n+ );\n+\n+ expect(dom).toContain(\"1/2\");\n+ expect(dom).toContain(\"apply_patch\");\n+ expect(dom).toContain(\"Apply a unified diff patch\");\n+ expect(dom).toContain(\"write\");\n+ expect(dom).toContain(\"used\");\n+ expect(dom).toContain(\"grep\");\n+ expect(dom).toContain(\"Search file contents\");\n+ expect(dom).toContain(\"read\");\n+ expect(dom).toContain(\"available\");\n+ // Permission remains secondary compatibility metadata, not the source of\n+ // the tool list.\n+ expect(dom).toContain(\"Full access\");\n+ });\n+\n+ test(\"legacy stages without agent tools keep permission fallback only\", () => {\n+ const dom = render(makeStage({ permission_level: PermissionLevel.READ_WRITE }), null);\n+ expect(dom).toContain(\"Read/write\");\n+ expect(dom).not.toContain(\"apply_patch\");\n+ });\n+\n test(\"renders mcp server used/total count, marks invoked servers as 'used'\", () => {\n const dom = render(\n makeStage({\ndiff --git a/apps/fabro-web/app/components/stage-insights-sidebar.tsx b/apps/fabro-web/app/components/stage-insights-sidebar.tsx\nindex 71ffa5094..135f1dd72 100644\n--- a/apps/fabro-web/app/components/stage-insights-sidebar.tsx\n+++ b/apps/fabro-web/app/components/stage-insights-sidebar.tsx\n@@ -19,6 +19,7 @@ import {\n PuzzlePieceIcon,\n ServerStackIcon,\n Squares2X2Icon,\n+ WrenchScrewdriverIcon,\n } from \"@heroicons/react/24/outline\";\n import {\n AgentSkillActivationSource,\n@@ -30,6 +31,7 @@ import {\n import type {\n ActivatedSkill,\n AgentSkillSummary,\n+ AgentToolSummary,\n McpServerProjection,\n StageContextWindow,\n StageContextWindowBreakdownItem,\n@@ -42,11 +44,12 @@ import { formatTokenCount } from \"../lib/format\";\n const COLLAPSED_STORAGE_KEY = \"fabro:stage-insights-sidebar-collapsed\";\n const SECTION_STORAGE_PREFIX = \"fabro:stage-insights-section:\";\n \n-type SectionKey = \"todos\" | \"context\" | \"skills\" | \"mcps\";\n+type SectionKey = \"todos\" | \"context\" | \"tools\" | \"skills\" | \"mcps\";\n \n const SECTIONS_DEFAULT_OPEN: Record = {\n todos: true,\n context: false,\n+ tools: false,\n skills: false,\n mcps: false,\n };\n@@ -70,11 +73,13 @@ export function StageInsightsSidebar({ stage, contextWindow }: StageInsightsSide\n \n const todos = stage?.todos ?? null;\n const skills = stage?.skills ?? { activated: [], available: [] };\n+ const agentTools = stage?.agent_tools ?? [];\n const mcpServers = stage?.mcp_servers ?? [];\n const permission = stage?.permission_level ?? null;\n \n const todoStats = countTodoStats(todos);\n const activatedSkillNames = new Set(skills.activated.map((s) => s.name));\n+ const invokedToolCount = agentTools.filter((tool) => tool.invoked).length;\n \n return (\n \n \n+ \n+ \n+ \n+\n ;\n }\n \n+// ---------- Tools ----------\n+\n+function AgentToolsSection({ tools }: { tools: AgentToolSummary[] }) {\n+ if (tools.length === 0) return

No tools reported.

;\n+ return (\n+
    \n+ {tools.map((tool) => {\n+ const nameClass = tool.invoked\n+ ? \"min-w-0 flex-1 truncate text-xs text-fg-2\"\n+ : \"min-w-0 flex-1 truncate text-xs text-fg-muted\";\n+ return (\n+
  • \n+
    \n+ {tool.invoked ? (\n+ \n+ ) : (\n+ \n+ )}\n+ {tool.name}\n+ \n+ {tool.invoked ? \"used\" : \"available\"}\n+ \n+
    \n+

    {tool.description}

    \n+
    \n+ \n+ {toolSourceLabel(tool.source)}\n+ \n+ \n+ {tool.category}\n+ \n+
    \n+
  • \n+ );\n+ })}\n+
\n+ );\n+}\n+\n+function toolSourceLabel(source: AgentToolSummary[\"source\"]): string {\n+ switch (source.kind) {\n+ case \"mcp\":\n+ return `mcp:${source.server_name}`;\n+ case \"skill\":\n+ return \"skill\";\n+ case \"native\":\n+ default:\n+ return \"native\";\n+ }\n+}\n+\n+function ToolAvailableIcon({ className }: { className?: string }) {\n+ return ;\n+}\n+\n // ---------- MCPs ----------\n \n function McpSection({ servers }: { servers: McpServerProjection[] }) {\ndiff --git a/docs/public/api-reference/fabro-api.yaml b/docs/public/api-reference/fabro-api.yaml\nindex 58a1e02e9..cc5eaa80b 100644\n--- a/docs/public/api-reference/fabro-api.yaml\n+++ b/docs/public/api-reference/fabro-api.yaml\n@@ -7971,6 +7971,22 @@ components:\n type: integer\n minimum: 1\n \n+ AgentToolsAvailableProps:\n+ description: Properties for the `agent.tools.available` event.\n+ type: object\n+ required:\n+ - tools\n+ - visit\n+ properties:\n+ tools:\n+ type: array\n+ description: Effective model-callable tools exposed to the stage session.\n+ items:\n+ $ref: \"#/components/schemas/AgentToolSummary\"\n+ visit:\n+ type: integer\n+ minimum: 1\n+\n RunSupersededByProps:\n description: Properties for the `run.superseded_by` audit event emitted on a rewound source run after archive succeeds.\n type: object\n@@ -8550,6 +8566,13 @@ components:\n - $ref: \"#/components/schemas/PermissionLevel\"\n - type: \"null\"\n description: Agent tool permission level applied to this stage session.\n+ agent_tools:\n+ type: array\n+ description: >\n+ Effective model-callable tools exposed to this agent stage session.\n+ Tool parameter schemas are intentionally omitted from this projection.\n+ items:\n+ $ref: \"#/components/schemas/AgentToolSummary\"\n mcp_servers:\n type: array\n description: MCP servers observed by this stage.\n@@ -8689,6 +8712,83 @@ components:\n type: string\n enum: [slash, tool]\n \n+ AgentToolSummary:\n+ description: Summary of one effective model-callable tool exposed to an agent stage.\n+ type: object\n+ required:\n+ - name\n+ - description\n+ - source\n+ - category\n+ - invoked\n+ properties:\n+ name:\n+ type: string\n+ description: Exposed model-facing tool name, for example `apply_patch` or `mcp__filesystem__read_file`.\n+ description:\n+ type: string\n+ description: Model-facing tool description.\n+ source:\n+ $ref: \"#/components/schemas/AgentToolSource\"\n+ category:\n+ $ref: \"#/components/schemas/AgentToolCategory\"\n+ invoked:\n+ type: boolean\n+ description: True once this tool has been invoked during the stage.\n+\n+ AgentToolSource:\n+ description: Origin of an effective agent tool.\n+ oneOf:\n+ - $ref: \"#/components/schemas/AgentToolSourceNative\"\n+ - $ref: \"#/components/schemas/AgentToolSourceMcp\"\n+ - $ref: \"#/components/schemas/AgentToolSourceSkill\"\n+ discriminator:\n+ propertyName: kind\n+ mapping:\n+ native: \"#/components/schemas/AgentToolSourceNative\"\n+ mcp: \"#/components/schemas/AgentToolSourceMcp\"\n+ skill: \"#/components/schemas/AgentToolSourceSkill\"\n+\n+ AgentToolSourceNative:\n+ type: object\n+ required:\n+ - kind\n+ properties:\n+ kind:\n+ type: string\n+ enum: [native]\n+\n+ AgentToolSourceMcp:\n+ type: object\n+ required:\n+ - kind\n+ - server_name\n+ - original_name\n+ properties:\n+ kind:\n+ type: string\n+ enum: [mcp]\n+ server_name:\n+ type: string\n+ description: MCP server name that provided the tool.\n+ original_name:\n+ type: string\n+ description: Tool name before MCP qualification.\n+\n+ AgentToolSourceSkill:\n+ type: object\n+ required:\n+ - kind\n+ properties:\n+ kind:\n+ type: string\n+ enum: [skill]\n+\n+ AgentToolCategory:\n+ description: Coarse tool category for display and grouping.\n+ type: string\n+ enum: [read, write, shell, subagent, other]\n+\n McpServerProjection:\n description: Projected state for one MCP server observed by an agent stage.\n type: object\ndiff --git a/lib/crates/fabro-agent/src/session.rs b/lib/crates/fabro-agent/src/session.rs\nindex 62ca5f048..8a8fcf189 100644\n--- a/lib/crates/fabro-agent/src/session.rs\n+++ b/lib/crates/fabro-agent/src/session.rs\n@@ -501,6 +501,11 @@ impl Session {\n self.config.permission_level\n }\n \n+ #[must_use]\n+ pub fn available_tools(&self) -> Vec {\n+ self.effective_tools()\n+ }\n+\n /// Initialize session by discovering project docs and capturing environment\n /// context. Call before `process_input`.\n ///\n@@ -1966,13 +1971,7 @@ impl Session {\n }\n messages.extend(self.history.convert_to_messages());\n \n- let tools_with_source = self\n- .provider_profile\n- .tool_registry()\n- .definitions_with_source_for_policy(\n- self.config.tool_access_policy.as_deref(),\n- self.config.tool_exposure_mode,\n- );\n+ let tools_with_source = self.effective_tools();\n let tools: Vec<_> = tools_with_source\n .iter()\n .map(|tool| tool.definition.clone())\n@@ -2009,13 +2008,11 @@ impl Session {\n }\n \n fn inject_task_reminder_if_needed(&mut self) {\n- let tools = self\n- .provider_profile\n- .tool_registry()\n- .definitions_for_policy(\n- self.config.tool_access_policy.as_deref(),\n- self.config.tool_exposure_mode,\n- );\n+ let tools: Vec<_> = self\n+ .effective_tools()\n+ .into_iter()\n+ .map(|tool| tool.definition)\n+ .collect();\n let tool_names: Vec<&str> = tools.iter().map(|tool| tool.name.as_str()).collect();\n if let Some(reminder) = task_reminder::maybe_reminder(&self.history, &tool_names) {\n self.history.push(Message::System {\n@@ -2024,6 +2021,15 @@ impl Session {\n });\n }\n }\n+\n+ fn effective_tools(&self) -> Vec {\n+ self.provider_profile\n+ .tool_registry()\n+ .definitions_with_source_for_policy(\n+ self.config.tool_access_policy.as_deref(),\n+ self.config.tool_exposure_mode,\n+ )\n+ }\n }\n \n const fn is_auth_error(err: &LlmError) -> bool {\n@@ -3274,6 +3280,38 @@ mod tests {\n assert_eq!(tools[0].name, \"read_file\");\n }\n \n+ #[tokio::test]\n+ async fn available_tools_uses_same_effective_registry_filter_as_requests() {\n+ let provider = Arc::new(CapturingLlmProvider::new());\n+ let client = make_client(provider as Arc).await;\n+ let mut registry = ToolRegistry::new();\n+ registry.register(make_named_noop_tool(\"read_file\"));\n+ registry.register(make_named_noop_tool(\"apply_patch\"));\n+ registry.register(make_named_noop_tool(\"shell\"));\n+ let profile = Arc::new(TestProfile::with_tools(registry));\n+ let env = Arc::new(MockSandbox::default());\n+ let config = SessionOptions {\n+ tool_access_policy: Some(Arc::new(NamedToolAccessPolicy::new(vec![\n+ (\"read_file\", ToolAccess::Allowed),\n+ (\"apply_patch\", ToolAccess::RequiresApproval),\n+ (\"shell\", ToolAccess::Denied),\n+ ]))),\n+ tool_exposure_mode: ToolExposureMode::IncludeRequiresApproval,\n+ ..SessionOptions::default()\n+ };\n+ let session = Session::new(client, profile, env, config, None);\n+\n+ let tools = session.available_tools();\n+ let mut tool_names: Vec<&str> = tools\n+ .iter()\n+ .map(|tool| tool.definition.name.as_str())\n+ .collect();\n+ tool_names.sort_unstable();\n+\n+ assert_eq!(tool_names, vec![\"apply_patch\", \"read_file\"]);\n+ assert!(tools.iter().all(|tool| tool.source == ToolSource::Native));\n+ }\n+\n #[tokio::test]\n async fn request_exposes_approval_required_tools_when_mode_allows_them() {\n let provider = Arc::new(CapturingLlmProvider::new());\ndiff --git a/lib/crates/fabro-agent/src/tool_permissions.rs b/lib/crates/fabro-agent/src/tool_permissions.rs\nindex 3a62931f1..b22dba945 100644\n--- a/lib/crates/fabro-agent/src/tool_permissions.rs\n+++ b/lib/crates/fabro-agent/src/tool_permissions.rs\n@@ -1,11 +1,16 @@\n use fabro_types::PermissionLevel;\n \n pub fn tool_category(name: &str) -> &'static str {\n+ known_tool_category(name).unwrap_or(\"shell\")\n+}\n+\n+pub fn known_tool_category(name: &str) -> Option<&'static str> {\n match name {\n- \"read_file\" | \"read_many_files\" | \"grep\" | \"glob\" | \"list_dir\" => \"read\",\n- \"write_file\" | \"edit_file\" | \"apply_patch\" => \"write\",\n- \"spawn_agent\" | \"send_input\" | \"wait\" | \"close_agent\" => \"subagent\",\n- _ => \"shell\",\n+ \"read_file\" | \"read_many_files\" | \"grep\" | \"glob\" | \"list_dir\" => Some(\"read\"),\n+ \"write_file\" | \"edit_file\" | \"apply_patch\" => Some(\"write\"),\n+ \"shell\" => Some(\"shell\"),\n+ \"spawn_agent\" | \"send_input\" | \"wait\" | \"close_agent\" => Some(\"subagent\"),\n+ _ => None,\n }\n }\n \ndiff --git a/lib/crates/fabro-api/build.rs b/lib/crates/fabro-api/build.rs\nindex 4649ef19e..2a38da779 100644\n--- a/lib/crates/fabro-api/build.rs\n+++ b/lib/crates/fabro-api/build.rs\n@@ -366,6 +366,14 @@ fn main() {\n \"fabro_types::AgentSkillActivationSource\",\n &[],\n ),\n+ (\"AgentToolSummary\", \"fabro_types::AgentToolSummary\", &[]),\n+ (\"AgentToolSource\", \"fabro_types::AgentToolSource\", &[]),\n+ (\"AgentToolCategory\", \"fabro_types::AgentToolCategory\", &[]),\n+ (\n+ \"AgentToolsAvailableProps\",\n+ \"fabro_types::AgentToolsAvailableProps\",\n+ &[],\n+ ),\n (\n \"McpServerProjection\",\n \"fabro_types::McpServerProjection\",\ndiff --git a/lib/crates/fabro-api/src/lib.rs b/lib/crates/fabro-api/src/lib.rs\nindex a148d9aac..d7ab6f416 100644\n--- a/lib/crates/fabro-api/src/lib.rs\n+++ b/lib/crates/fabro-api/src/lib.rs\n@@ -34,8 +34,9 @@ pub mod types {\n };\n pub use fabro_types::{\n ActivatedSkill, AgentMcpToolSummary, AgentSkillActivationSource, AgentSkillSummary,\n- AskFabro, AuthMethod, BilledTokenCounts, CommandTermination, Conclusion, DiffStats,\n- DiffSummary, DirtyStatus, EventEnvelope, ExecOutputTail, FailureCategory, FailureDetail,\n+ AgentToolCategory, AgentToolSource, AgentToolSummary, AgentToolsAvailableProps, AskFabro,\n+ AuthMethod, BilledTokenCounts, CommandTermination, Conclusion, DiffStats, DiffSummary,\n+ DirtyStatus, EventEnvelope, ExecOutputTail, FailureCategory, FailureDetail,\n FailureSignature, GitContext, IdpIdentity, InterviewOption, InterviewQuestionRecord,\n McpServerProjection, McpServerStatus, PairId, PairMessageId, PairMessageRecord,\n PairMessageRequest, PairRecord, PairStartRequest, PairStatus, PairTarget,\ndiff --git a/lib/crates/fabro-api/tests/stage_projection_round_trip.rs b/lib/crates/fabro-api/tests/stage_projection_round_trip.rs\nindex 8c110b5b4..2f26ad612 100644\n--- a/lib/crates/fabro-api/tests/stage_projection_round_trip.rs\n+++ b/lib/crates/fabro-api/tests/stage_projection_round_trip.rs\n@@ -3,9 +3,12 @@ use std::any::{TypeId, type_name};\n use fabro_api::types::{\n ActivatedSkill as ApiActivatedSkill, AgentMcpToolSummary as ApiAgentMcpToolSummary,\n AgentSkillActivationSource as ApiAgentSkillActivationSource,\n- AgentSkillSummary as ApiAgentSkillSummary, McpServerProjection as ApiMcpServerProjection,\n- McpServerStatus as ApiMcpServerStatus, PermissionLevel as ApiPermissionLevel,\n- SkillsProjection as ApiSkillsProjection, StageContextWindow as ApiStageContextWindow,\n+ AgentSkillSummary as ApiAgentSkillSummary, AgentToolCategory as ApiAgentToolCategory,\n+ AgentToolSource as ApiAgentToolSource, AgentToolSummary as ApiAgentToolSummary,\n+ AgentToolsAvailableProps as ApiAgentToolsAvailableProps,\n+ McpServerProjection as ApiMcpServerProjection, McpServerStatus as ApiMcpServerStatus,\n+ PermissionLevel as ApiPermissionLevel, SkillsProjection as ApiSkillsProjection,\n+ StageContextWindow as ApiStageContextWindow,\n StageContextWindowBreakdownItem as ApiStageContextWindowBreakdownItem,\n StageContextWindowCategory as ApiStageContextWindowCategory,\n StageContextWindowCountMethod as ApiStageContextWindowCountMethod,\n@@ -18,6 +21,7 @@ use fabro_api::types::{\n };\n use fabro_types::{\n ActivatedSkill, AgentMcpToolSummary, AgentSkillActivationSource, AgentSkillSummary,\n+ AgentToolCategory, AgentToolSource, AgentToolSummary, AgentToolsAvailableProps,\n McpServerProjection, McpServerStatus, PermissionLevel, SkillsProjection, StageContextWindow,\n StageContextWindowBreakdownItem, StageContextWindowCategory, StageContextWindowCountMethod,\n StageContextWindowProjection, StageContextWindowStaleness, StageContextWindowUnavailableReason,\n@@ -40,6 +44,10 @@ fn stage_projection_reuses_nested_agent_state_types() {\n assert_same_type::();\n assert_same_type::();\n assert_same_type::();\n+ assert_same_type::();\n+ assert_same_type::();\n+ assert_same_type::();\n+ assert_same_type::();\n assert_same_type::();\n assert_same_type::();\n assert_same_type::();\n@@ -135,6 +143,26 @@ fn stage_projection_round_trips_representative_json() {\n ]\n },\n \"permission_level\": \"read-only\",\n+ \"agent_tools\": [\n+ {\n+ \"name\": \"apply_patch\",\n+ \"description\": \"Apply a unified diff patch\",\n+ \"source\": { \"kind\": \"native\" },\n+ \"category\": \"write\",\n+ \"invoked\": true\n+ },\n+ {\n+ \"name\": \"mcp__filesystem__read_file\",\n+ \"description\": \"Read a file through MCP\",\n+ \"source\": {\n+ \"kind\": \"mcp\",\n+ \"server_name\": \"filesystem\",\n+ \"original_name\": \"read_file\"\n+ },\n+ \"category\": \"other\",\n+ \"invoked\": false\n+ }\n+ ],\n \"mcp_servers\": [\n {\n \"server_name\": \"filesystem\",\n@@ -355,6 +383,47 @@ fn nested_agent_state_types_match_openapi_json_shape() {\n assert_eq!(mcp_server.tool_count, 1);\n }\n \n+#[test]\n+fn agent_tool_summary_matches_openapi_json_shape_without_parameter_schema() {\n+ let tool = AgentToolSummary {\n+ name: \"mcp__filesystem__read_file\".to_string(),\n+ description: \"Read a file through MCP\".to_string(),\n+ source: AgentToolSource::Mcp {\n+ server_name: \"filesystem\".to_string(),\n+ original_name: \"read_file\".to_string(),\n+ },\n+ category: AgentToolCategory::Other,\n+ invoked: false,\n+ };\n+\n+ let tool_json = serde_json::to_value(&tool).unwrap();\n+ assert_eq!(\n+ tool_json,\n+ json!({\n+ \"name\": \"mcp__filesystem__read_file\",\n+ \"description\": \"Read a file through MCP\",\n+ \"source\": {\n+ \"kind\": \"mcp\",\n+ \"server_name\": \"filesystem\",\n+ \"original_name\": \"read_file\"\n+ },\n+ \"category\": \"other\",\n+ \"invoked\": false\n+ })\n+ );\n+ assert!(tool_json.as_object().unwrap().get(\"parameters\").is_none());\n+ let api_tool: ApiAgentToolSummary = serde_json::from_value(tool_json).unwrap();\n+ assert_eq!(api_tool, tool);\n+\n+ let props = AgentToolsAvailableProps {\n+ tools: vec![tool],\n+ visit: 2,\n+ };\n+ let props_json = serde_json::to_value(&props).unwrap();\n+ let api_props: ApiAgentToolsAvailableProps = serde_json::from_value(props_json).unwrap();\n+ assert_eq!(api_props, props);\n+}\n+\n fn assert_same_type() {\n assert_eq!(\n TypeId::of::(),\ndiff --git a/lib/crates/fabro-store/src/run_state.rs b/lib/crates/fabro-store/src/run_state.rs\nindex d5854291e..7bd2e8a3e 100644\n--- a/lib/crates/fabro-store/src/run_state.rs\n+++ b/lib/crates/fabro-store/src/run_state.rs\n@@ -411,6 +411,13 @@ impl RunProjectionReducer for RunProjection {\n stage.provider_used = Some(StageModelUsage::from_agent_session_activated(props));\n stage.permission_level = props.permission_level;\n }\n+ EventBody::AgentToolsAvailable(props) => {\n+ let Some(stage) = stage_at_stored_or_visit(self, stored, props.visit, event.seq)\n+ else {\n+ return Ok(());\n+ };\n+ stage.agent_tools.clone_from(&props.tools);\n+ }\n // `AgentAcpStarted` is the start-of-process signal for an external\n // ACP agent. `provider_used` is intentionally sourced from the\n // subsequent `AgentSessionActivated` event, which carries the\n@@ -605,6 +612,13 @@ impl RunProjectionReducer for RunProjection {\n else {\n return Ok(());\n };\n+ if let Some(tool) = stage\n+ .agent_tools\n+ .iter_mut()\n+ .find(|tool| tool.name == props.tool_name)\n+ {\n+ tool.invoked = true;\n+ }\n if let Some(server) = mcp_server_from_tool_name(&props.tool_name) {\n if let Some(projection) = stage\n .mcp_servers\n@@ -1232,9 +1246,11 @@ mod tests {\n AgentSessionEndedProps, AgentSessionStartedProps, AgentSkillActivatedProps,\n AgentSkillActivationSource, AgentSkillSummary, AgentSkillsDiscoveredProps,\n AgentSubClosedProps, AgentSubCompletedProps, AgentSubFailedProps, AgentSubSpawnedProps,\n- AgentToolStartedProps, CheckpointCompletedProps, InterviewCompletedProps, InterviewOption,\n- InterviewStartedProps, RunCompletedProps, RunControlEffectProps, StageCompletedProps,\n- StageFailedProps, StagePromptProps, StageRetryingProps, StageStartedProps,\n+ AgentToolCategory, AgentToolSource, AgentToolStartedProps, AgentToolSummary,\n+ AgentToolsAvailableProps, CheckpointCompletedProps, InterviewCompletedProps,\n+ InterviewOption, InterviewStartedProps, RunCompletedProps, RunControlEffectProps,\n+ StageCompletedProps, StageFailedProps, StagePromptProps, StageRetryingProps,\n+ StageStartedProps,\n };\n use fabro_types::{\n AgentBackend, BilledModelUsage, BilledTokenCounts, BlockedReason, Checkpoint,\n@@ -4599,6 +4615,117 @@ mod tests {\n assert_eq!(legacy_stage.permission_level, None);\n }\n \n+ fn agent_tool(name: &str, category: AgentToolCategory, invoked: bool) -> AgentToolSummary {\n+ AgentToolSummary {\n+ name: name.to_string(),\n+ description: format!(\"{name} description\"),\n+ source: AgentToolSource::Native,\n+ category,\n+ invoked,\n+ }\n+ }\n+\n+ #[test]\n+ fn agent_tools_available_replaces_stage_agent_tools() {\n+ let mut state = initialized_projection();\n+ let stage_id = stage_id();\n+\n+ state\n+ .apply_event(&test_stage_event(\n+ 1,\n+ EventBody::AgentToolsAvailable(AgentToolsAvailableProps {\n+ tools: vec![\n+ agent_tool(\"read_file\", AgentToolCategory::Read, false),\n+ agent_tool(\"apply_patch\", AgentToolCategory::Write, false),\n+ ],\n+ visit: 1,\n+ }),\n+ stage_id.clone(),\n+ ))\n+ .unwrap();\n+ state\n+ .apply_event(&test_stage_event(\n+ 2,\n+ EventBody::AgentToolsAvailable(AgentToolsAvailableProps {\n+ tools: vec![agent_tool(\"grep\", AgentToolCategory::Read, false)],\n+ visit: 1,\n+ }),\n+ stage_id.clone(),\n+ ))\n+ .unwrap();\n+\n+ let stage = state.stage(&stage_id).unwrap();\n+ assert_eq!(stage.agent_tools, vec![agent_tool(\n+ \"grep\",\n+ AgentToolCategory::Read,\n+ false\n+ )]);\n+ }\n+\n+ #[test]\n+ fn agent_tool_started_marks_only_matching_available_tool_invoked() {\n+ let mut state = initialized_projection();\n+ let stage_id = stage_id();\n+\n+ state\n+ .apply_event(&test_stage_event(\n+ 1,\n+ EventBody::AgentToolsAvailable(AgentToolsAvailableProps {\n+ tools: vec![\n+ agent_tool(\"read_file\", AgentToolCategory::Read, false),\n+ agent_tool(\"apply_patch\", AgentToolCategory::Write, false),\n+ ],\n+ visit: 1,\n+ }),\n+ stage_id.clone(),\n+ ))\n+ .unwrap();\n+ state\n+ .apply_event(&test_stage_event(\n+ 2,\n+ EventBody::AgentToolStarted(AgentToolStartedProps {\n+ tool_name: \"apply_patch\".to_string(),\n+ tool_call_id: \"call_patch\".to_string(),\n+ arguments: serde_json::json!({}),\n+ visit: 1,\n+ tool_call: None,\n+ turn_id: None,\n+ parent_message_id: None,\n+ }),\n+ stage_id.clone(),\n+ ))\n+ .unwrap();\n+\n+ let stage = state.stage(&stage_id).unwrap();\n+ assert!(!stage.agent_tools[0].invoked);\n+ assert!(stage.agent_tools[1].invoked);\n+ }\n+\n+ #[test]\n+ fn legacy_tool_started_without_available_tools_does_not_synthesize_tool_list() {\n+ let mut state = initialized_projection();\n+ let stage_id = stage_id();\n+\n+ state\n+ .apply_event(&test_stage_event(\n+ 1,\n+ EventBody::AgentToolStarted(AgentToolStartedProps {\n+ tool_name: \"apply_patch\".to_string(),\n+ tool_call_id: \"call_patch\".to_string(),\n+ arguments: serde_json::json!({}),\n+ visit: 1,\n+ tool_call: None,\n+ turn_id: None,\n+ parent_message_id: None,\n+ }),\n+ stage_id.clone(),\n+ ))\n+ .unwrap();\n+\n+ let stage = state.stage(&stage_id).unwrap();\n+ assert!(stage.agent_tools.is_empty());\n+ }\n+\n #[test]\n fn mcp_server_events_update_stage_projection() {\n let mut state = initialized_projection();\ndiff --git a/lib/crates/fabro-types/src/lib.rs b/lib/crates/fabro-types/src/lib.rs\nindex 622e8729f..d2bbdfbcd 100644\n--- a/lib/crates/fabro-types/src/lib.rs\n+++ b/lib/crates/fabro-types/src/lib.rs\n@@ -96,9 +96,10 @@ pub use run::{\n pub use run_blob_id::RunBlobId;\n pub use run_event::{\n AgentMcpToolSummary, AgentMemoryFileProps, AgentSkillActivationSource, AgentSkillSummary,\n- EventBody, ExecOutputTail, InterviewOption, MetadataSnapshotFailureKind, MetadataSnapshotPhase,\n- RunEvent, RunNoticeCode, RunNoticeLevel, RunPairEndedReason, RunPairFailedReason,\n- RunRunnableSource, SessionCapability, TodoCreatedProps, TodoDeletedProps, TodoUpdatedProps,\n+ AgentToolCategory, AgentToolSource, AgentToolSummary, AgentToolsAvailableProps, EventBody,\n+ ExecOutputTail, InterviewOption, MetadataSnapshotFailureKind, MetadataSnapshotPhase, RunEvent,\n+ RunNoticeCode, RunNoticeLevel, RunPairEndedReason, RunPairFailedReason, RunRunnableSource,\n+ SessionCapability, TodoCreatedProps, TodoDeletedProps, TodoUpdatedProps,\n };\n pub use run_failure::RunFailure;\n pub use run_id::{RunId, fixtures};\ndiff --git a/lib/crates/fabro-types/src/run_event/agent.rs b/lib/crates/fabro-types/src/run_event/agent.rs\nindex d172b2c9e..cbd994690 100644\n--- a/lib/crates/fabro-types/src/run_event/agent.rs\n+++ b/lib/crates/fabro-types/src/run_event/agent.rs\n@@ -1,6 +1,7 @@\n use fabro_model::{ReasoningEffort, Speed};\n use serde::{Deserialize, Serialize};\n use serde_json::Value;\n+use strum::{Display, EnumString, IntoStaticStr};\n \n use super::BilledTokenCounts;\n use crate::transcript::{ToolCall, ToolResult, TranscriptMessage};\n@@ -53,6 +54,56 @@ pub struct AgentSessionDeactivatedProps {\n pub visit: u32,\n }\n \n+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\n+pub struct AgentToolsAvailableProps {\n+ #[serde(default)]\n+ pub tools: Vec,\n+ pub visit: u32,\n+}\n+\n+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\n+pub struct AgentToolSummary {\n+ pub name: String,\n+ pub description: String,\n+ pub source: AgentToolSource,\n+ pub category: AgentToolCategory,\n+ pub invoked: bool,\n+}\n+\n+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]\n+#[serde(tag = \"kind\", rename_all = \"snake_case\")]\n+pub enum AgentToolSource {\n+ Native,\n+ Mcp {\n+ server_name: String,\n+ original_name: String,\n+ },\n+ Skill,\n+}\n+\n+#[derive(\n+ Debug,\n+ Clone,\n+ Copy,\n+ PartialEq,\n+ Eq,\n+ Hash,\n+ Serialize,\n+ Deserialize,\n+ Display,\n+ EnumString,\n+ IntoStaticStr,\n+)]\n+#[serde(rename_all = \"snake_case\")]\n+#[strum(serialize_all = \"snake_case\")]\n+pub enum AgentToolCategory {\n+ Read,\n+ Write,\n+ Shell,\n+ Subagent,\n+ Other,\n+}\n+\n #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]\n pub struct AgentProcessingEndProps {\n pub visit: u32,\ndiff --git a/lib/crates/fabro-types/src/run_event/mod.rs b/lib/crates/fabro-types/src/run_event/mod.rs\nindex 84a58ef16..4b35947f2 100644\n--- a/lib/crates/fabro-types/src/run_event/mod.rs\n+++ b/lib/crates/fabro-types/src/run_event/mod.rs\n@@ -198,6 +198,8 @@ pub enum EventBody {\n AgentSessionStarted(AgentSessionStartedProps),\n #[serde(rename = \"agent.session.activated\")]\n AgentSessionActivated(AgentSessionActivatedProps),\n+ #[serde(rename = \"agent.tools.available\")]\n+ AgentToolsAvailable(AgentToolsAvailableProps),\n #[serde(rename = \"agent.session.deactivated\")]\n AgentSessionDeactivated(AgentSessionDeactivatedProps),\n #[serde(rename = \"agent.session.ended\")]\n@@ -500,6 +502,7 @@ impl EventBody {\n Self::PromptCompleted(_) => \"prompt.completed\",\n Self::AgentSessionStarted(_) => \"agent.session.started\",\n Self::AgentSessionActivated(_) => \"agent.session.activated\",\n+ Self::AgentToolsAvailable(_) => \"agent.tools.available\",\n Self::AgentSessionDeactivated(_) => \"agent.session.deactivated\",\n Self::AgentSessionEnded(_) => \"agent.session.ended\",\n Self::AgentProcessingEnd(_) => \"agent.processing.end\",\n@@ -682,6 +685,7 @@ fn is_known_event_name(event: &str) -> bool {\n | \"prompt.completed\"\n | \"agent.session.started\"\n | \"agent.session.activated\"\n+ | \"agent.tools.available\"\n | \"agent.session.deactivated\"\n | \"agent.session.ended\"\n | \"agent.processing.end\"\n@@ -2261,4 +2265,76 @@ mod tests {\n \"empty tools should be omitted for legacy parity\"\n );\n }\n+\n+ #[test]\n+ fn agent_tools_available_round_trips_without_parameter_schemas() {\n+ let body = EventBody::AgentToolsAvailable(AgentToolsAvailableProps {\n+ tools: vec![\n+ AgentToolSummary {\n+ name: \"apply_patch\".to_string(),\n+ description: \"Apply a unified diff patch\".to_string(),\n+ source: AgentToolSource::Native,\n+ category: AgentToolCategory::Write,\n+ invoked: false,\n+ },\n+ AgentToolSummary {\n+ name: \"mcp__filesystem__read_file\".to_string(),\n+ description: \"Read a file through the filesystem MCP server\".to_string(),\n+ source: AgentToolSource::Mcp {\n+ server_name: \"filesystem\".to_string(),\n+ original_name: \"read_file\".to_string(),\n+ },\n+ category: AgentToolCategory::Other,\n+ invoked: false,\n+ },\n+ ],\n+ visit: 1,\n+ });\n+\n+ let value = serde_json::to_value(&body).unwrap();\n+ assert_eq!(value[\"event\"], \"agent.tools.available\");\n+ assert_eq!(value[\"properties\"][\"visit\"], 1);\n+ assert_eq!(value[\"properties\"][\"tools\"][0][\"name\"], \"apply_patch\");\n+ assert_eq!(value[\"properties\"][\"tools\"][0][\"source\"][\"kind\"], \"native\");\n+ assert_eq!(value[\"properties\"][\"tools\"][0][\"category\"], \"write\");\n+ assert!(\n+ value[\"properties\"][\"tools\"][0]\n+ .as_object()\n+ .unwrap()\n+ .get(\"parameters\")\n+ .is_none(),\n+ \"StageProjection tool summaries must not expose full parameter schemas\"\n+ );\n+\n+ let parsed: EventBody = serde_json::from_value(value).unwrap();\n+ assert_eq!(parsed, body);\n+ }\n+\n+ #[test]\n+ fn agent_tool_source_and_category_use_public_json_shape() {\n+ assert_eq!(\n+ serde_json::to_value(AgentToolCategory::Read).unwrap(),\n+ json!(\"read\")\n+ );\n+ assert_eq!(\n+ serde_json::to_value(AgentToolCategory::Subagent).unwrap(),\n+ json!(\"subagent\")\n+ );\n+ assert_eq!(\n+ serde_json::to_value(AgentToolSource::Skill).unwrap(),\n+ json!({ \"kind\": \"skill\" })\n+ );\n+ assert_eq!(\n+ serde_json::to_value(AgentToolSource::Mcp {\n+ server_name: \"github\".to_string(),\n+ original_name: \"create_issue\".to_string(),\n+ })\n+ .unwrap(),\n+ json!({\n+ \"kind\": \"mcp\",\n+ \"server_name\": \"github\",\n+ \"original_name\": \"create_issue\"\n+ })\n+ );\n+ }\n }\ndiff --git a/lib/crates/fabro-types/src/run_projection.rs b/lib/crates/fabro-types/src/run_projection.rs\nindex fca145920..3bba6d43e 100644\n--- a/lib/crates/fabro-types/src/run_projection.rs\n+++ b/lib/crates/fabro-types/src/run_projection.rs\n@@ -9,10 +9,10 @@ use strum::{Display, EnumString, IntoStaticStr};\n use crate::run_event::{AgentSessionActivatedProps, StagePromptProps};\n use crate::{\n AgentBackend, AgentMcpToolSummary, AgentSkillActivationSource, AgentSkillSummary,\n- BilledTokenCounts, Checkpoint, Conclusion, InterviewQuestionRecord, InvalidTransition,\n- ModelRef, PermissionLevel, PullRequestLink, RunApproval, RunControlAction, RunDiff, RunId,\n- RunSandbox, RunSpec, RunStatus, RunTiming, StageCompletion, StageHandler, StageId, StageState,\n- StageTiming, StartRecord, TodoListProjection,\n+ AgentToolSummary, BilledTokenCounts, Checkpoint, Conclusion, InterviewQuestionRecord,\n+ InvalidTransition, ModelRef, PermissionLevel, PullRequestLink, RunApproval, RunControlAction,\n+ RunDiff, RunId, RunSandbox, RunSpec, RunStatus, RunTiming, StageCompletion, StageHandler,\n+ StageId, StageState, StageTiming, StartRecord, TodoListProjection,\n };\n \n #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]\n@@ -360,6 +360,8 @@ pub struct StageProjection {\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n pub permission_level: Option,\n #[serde(default, skip_serializing_if = \"Vec::is_empty\")]\n+ pub agent_tools: Vec,\n+ #[serde(default, skip_serializing_if = \"Vec::is_empty\")]\n pub mcp_servers: Vec,\n #[serde(default, skip_serializing_if = \"Option::is_none\")]\n pub context_window: Option,\n@@ -440,6 +442,7 @@ impl StageProjection {\n subagents: Vec::new(),\n skills: SkillsProjection::default(),\n permission_level: None,\n+ agent_tools: Vec::new(),\n mcp_servers: Vec::new(),\n context_window: None,\n provider_used: None,\n@@ -744,9 +747,10 @@ mod iter_stages_tests {\n use std::num::NonZeroU32;\n \n use chrono::Utc;\n+ use serde_json::json;\n \n use super::RunProjection;\n- use crate::{Graph, RunId, RunSpec, WorkflowSettings};\n+ use crate::{Graph, RunId, RunSpec, StageProjection, WorkflowSettings};\n \n fn seq(n: u32) -> NonZeroU32 {\n NonZeroU32::new(n).unwrap()\n@@ -817,6 +821,23 @@ mod iter_stages_tests {\n assert_eq!(order, vec![\"a\", \"b\", \"c\"]);\n }\n \n+ #[test]\n+ fn stage_projection_defaults_missing_agent_tools_to_empty_and_omits_empty_list() {\n+ let value = json!({\n+ \"first_event_seq\": 1,\n+ \"state\": \"running\"\n+ });\n+\n+ let stage: StageProjection = serde_json::from_value(value).unwrap();\n+ assert!(stage.agent_tools.is_empty());\n+\n+ let serialized = serde_json::to_value(stage).unwrap();\n+ assert!(\n+ serialized.as_object().unwrap().get(\"agent_tools\").is_none(),\n+ \"empty agent_tools should be omitted from StageProjection JSON\"\n+ );\n+ }\n+\n #[test]\n fn iter_stages_tie_breaks_same_first_event_seq_by_stage_id() {\n for _ in 0..128 {\ndiff --git a/lib/crates/fabro-workflow/src/event/convert.rs b/lib/crates/fabro-workflow/src/event/convert.rs\nindex ff098e6f0..de4998a5f 100644\n--- a/lib/crates/fabro-workflow/src/event/convert.rs\n+++ b/lib/crates/fabro-workflow/src/event/convert.rs\n@@ -1174,6 +1174,12 @@ fn event_body_from_event(event: &Event) -> EventBody {\n capabilities: capabilities.clone(),\n visit: *visit,\n }),\n+ Event::AgentToolsAvailable { tools, visit, .. } => {\n+ EventBody::AgentToolsAvailable(fabro_types::AgentToolsAvailableProps {\n+ tools: tools.clone(),\n+ visit: *visit,\n+ })\n+ }\n Event::AgentSessionDeactivated { visit, .. } => {\n EventBody::AgentSessionDeactivated(fabro_types::AgentSessionDeactivatedProps {\n visit: *visit,\n@@ -1594,6 +1600,31 @@ mod tests {\n assert_eq!(properties[\"visit\"], 2);\n }\n \n+ #[test]\n+ fn run_event_agent_tools_available_moves_session_and_stage_metadata_to_header() {\n+ let stored = to_run_event(&fixtures::RUN_4, &Event::AgentToolsAvailable {\n+ node_id: \"code\".to_string(),\n+ visit: 2,\n+ session_id: \"ses_root\".to_string(),\n+ tools: vec![::fabro_types::AgentToolSummary {\n+ name: \"apply_patch\".to_string(),\n+ description: \"Apply a unified diff patch\".to_string(),\n+ source: ::fabro_types::AgentToolSource::Native,\n+ category: ::fabro_types::AgentToolCategory::Write,\n+ invoked: false,\n+ }],\n+ });\n+\n+ assert_eq!(stored.event_name(), \"agent.tools.available\");\n+ assert_eq!(stored.node_id.as_deref(), Some(\"code\"));\n+ assert_eq!(stored.stage_id, Some(StageId::new(\"code\", 2)));\n+ assert_eq!(stored.session_id.as_deref(), Some(\"ses_root\"));\n+ let properties = stored.properties().unwrap();\n+ assert_eq!(properties[\"visit\"], 2);\n+ assert_eq!(properties[\"tools\"][0][\"name\"], \"apply_patch\");\n+ assert_eq!(properties[\"tools\"][0][\"category\"], \"write\");\n+ }\n+\n #[test]\n fn run_event_sandbox_event_keeps_properties_nested() {\n let stored = to_run_event(&fixtures::RUN_5, &Event::Sandbox {\ndiff --git a/lib/crates/fabro-workflow/src/event/events.rs b/lib/crates/fabro-workflow/src/event/events.rs\nindex e91686d22..a38b184bb 100644\n--- a/lib/crates/fabro-workflow/src/event/events.rs\n+++ b/lib/crates/fabro-workflow/src/event/events.rs\n@@ -619,6 +619,14 @@ pub enum Event {\n permission_level: Option,\n capabilities: Vec,\n },\n+ /// Effective model-callable tools for a stage session after profile setup,\n+ /// optional registrations, MCP integration, and access-policy filtering.\n+ AgentToolsAvailable {\n+ node_id: String,\n+ visit: u32,\n+ session_id: String,\n+ tools: Vec,\n+ },\n /// A stage's steerable live session binding ended.\n AgentSessionDeactivated {\n node_id: String,\n@@ -1466,6 +1474,20 @@ impl Event {\n } => {\n debug!(node_id, visit, session_id, \"Agent session activated\");\n }\n+ Self::AgentToolsAvailable {\n+ node_id,\n+ visit,\n+ session_id,\n+ tools,\n+ } => {\n+ debug!(\n+ node_id,\n+ visit,\n+ session_id,\n+ tool_count = tools.len(),\n+ \"Agent tools available\"\n+ );\n+ }\n Self::AgentSessionDeactivated {\n node_id,\n visit,\ndiff --git a/lib/crates/fabro-workflow/src/event/names.rs b/lib/crates/fabro-workflow/src/event/names.rs\nindex 958f8fdeb..ae645dcf9 100644\n--- a/lib/crates/fabro-workflow/src/event/names.rs\n+++ b/lib/crates/fabro-workflow/src/event/names.rs\n@@ -140,6 +140,7 @@ pub fn event_name(event: &Event) -> &'static str {\n Event::CommandCompleted { .. } => \"command.completed\",\n Event::AgentSessionStarted { .. } => \"agent.session.started\",\n Event::AgentSessionActivated { .. } => \"agent.session.activated\",\n+ Event::AgentToolsAvailable { .. } => \"agent.tools.available\",\n Event::AgentSessionDeactivated { .. } => \"agent.session.deactivated\",\n Event::AgentSessionEnded { .. } => \"agent.session.ended\",\n Event::AgentInterruptInjected { .. } => \"agent.interrupt.injected\",\n@@ -202,6 +203,15 @@ mod tests {\n }),\n \"agent.sub.spawned\"\n );\n+ assert_eq!(\n+ event_name(&Event::AgentToolsAvailable {\n+ node_id: \"code\".to_string(),\n+ visit: 1,\n+ session_id: \"session-1\".to_string(),\n+ tools: Vec::new(),\n+ }),\n+ \"agent.tools.available\"\n+ );\n }\n \n #[test]\ndiff --git a/lib/crates/fabro-workflow/src/event/stored_fields.rs b/lib/crates/fabro-workflow/src/event/stored_fields.rs\nindex f993035de..94fba25ad 100644\n--- a/lib/crates/fabro-workflow/src/event/stored_fields.rs\n+++ b/lib/crates/fabro-workflow/src/event/stored_fields.rs\n@@ -161,6 +161,12 @@ fn stored_event_fields_for_variant(event: &Event) -> StoredEventFields {\n session_id,\n ..\n }\n+ | Event::AgentToolsAvailable {\n+ node_id,\n+ visit,\n+ session_id,\n+ ..\n+ }\n | Event::AgentSessionDeactivated {\n node_id,\n visit,\ndiff --git a/lib/crates/fabro-workflow/src/handler/llm/api.rs b/lib/crates/fabro-workflow/src/handler/llm/api.rs\nindex 42dc0e1f5..135b5e3b7 100644\n--- a/lib/crates/fabro-workflow/src/handler/llm/api.rs\n+++ b/lib/crates/fabro-workflow/src/handler/llm/api.rs\n@@ -3,11 +3,13 @@ use std::sync::{Arc, Mutex};\n \n use async_trait::async_trait;\n use fabro_agent::subagent::{SessionFactory, SubAgentManager};\n-use fabro_agent::tool_registry::{RegisteredTool, ToolContext, ToolRegistry, ToolSource};\n+use fabro_agent::tool_registry::{\n+ RegisteredTool, ToolContext, ToolDefinitionWithSource, ToolRegistry, ToolSource,\n+};\n use fabro_agent::{\n AgentEvent, AgentProfile, AnthropicProfile, CompletionCoordinator, GeminiProfile,\n Message as AgentMessage, OpenAiProfile, Sandbox, Session, SessionOptions, StaticEnvProvider,\n- ToolEnvProvider, register_question_tools,\n+ ToolEnvProvider, register_question_tools, tool_permissions,\n };\n use fabro_auth::{CredentialSource, EnvCredentialSource};\n use fabro_graphviz::graph::{AttrValue, Node};\n@@ -21,7 +23,10 @@ use fabro_mcp::config::McpServerSettings;\n use fabro_model::catalog::LlmCatalogSettings;\n use fabro_model::{AgentProfileKind, Catalog, FallbackTarget, ModelRef, ProviderId};\n use fabro_types::settings::run::RunModelControls;\n-use fabro_types::{PermissionLevel, RunId, SessionCapability, StageId};\n+use fabro_types::{\n+ AgentToolCategory, AgentToolSource, AgentToolSummary, PermissionLevel, RunId,\n+ SessionCapability, StageId,\n+};\n use serde::de::DeserializeOwned;\n use tokio::sync::Mutex as TokioMutex;\n use tokio::task::JoinHandle;\n@@ -496,6 +501,61 @@ fn last_assistant_response(session: &Session) -> String {\n .unwrap_or_default()\n }\n \n+fn agent_tool_summaries_from_definitions(\n+ tools: &[ToolDefinitionWithSource],\n+) -> Vec {\n+ let mut summaries: Vec<_> = tools\n+ .iter()\n+ .map(|tool| AgentToolSummary {\n+ name: tool.definition.name.clone(),\n+ description: tool.definition.description.clone(),\n+ source: agent_tool_source(&tool.definition.name, &tool.source),\n+ category: agent_tool_category(&tool.definition.name),\n+ invoked: false,\n+ })\n+ .collect();\n+ summaries.sort_by(|left, right| left.name.cmp(&right.name));\n+ summaries\n+}\n+\n+fn agent_tool_source(name: &str, source: &ToolSource) -> AgentToolSource {\n+ match source {\n+ ToolSource::Native => AgentToolSource::Native,\n+ ToolSource::Mcp { server_name } => AgentToolSource::Mcp {\n+ server_name: server_name.clone(),\n+ original_name: fabro_mcp::connection_manager::parse_qualified_name(name)\n+ .map(|(_, original_name)| original_name)\n+ .unwrap_or_else(|| name.to_string()),\n+ },\n+ ToolSource::Skill => AgentToolSource::Skill,\n+ }\n+}\n+\n+fn agent_tool_category(name: &str) -> AgentToolCategory {\n+ match tool_permissions::known_tool_category(name) {\n+ Some(\"read\") => AgentToolCategory::Read,\n+ Some(\"write\") => AgentToolCategory::Write,\n+ Some(\"shell\") => AgentToolCategory::Shell,\n+ Some(\"subagent\") => AgentToolCategory::Subagent,\n+ Some(_) | None => AgentToolCategory::Other,\n+ }\n+}\n+\n+fn emit_agent_tools_available(\n+ session: &Session,\n+ node_id: &str,\n+ stage_id: &StageId,\n+ emitter: &Arc,\n+) {\n+ let tools = agent_tool_summaries_from_definitions(&session.available_tools());\n+ emitter.emit(&Event::AgentToolsAvailable {\n+ node_id: node_id.to_string(),\n+ visit: stage_id.visit(),\n+ session_id: session.id().to_string(),\n+ tools,\n+ });\n+}\n+\n /// Spawn a task that subscribes to session events and:\n /// 1. Tracks file changes (write_file/edit_file tool calls) into shared state.\n /// 2. Forwards non-streaming agent events to the pipeline emitter.\n@@ -1197,6 +1257,7 @@ impl CodergenBackend for AgentApiBackend {\n return Err(err);\n }\n }\n+ emit_agent_tools_available(&session, &node.id, &stage_id, emitter);\n session\n .process_input_with_runtime(prompt, agent_tool_runtime.clone())\n .await\n@@ -1323,6 +1384,7 @@ impl CodergenBackend for AgentApiBackend {\n return Err(err);\n }\n }\n+ emit_agent_tools_available(&session, &node.id, &stage_id, emitter);\n match session\n .process_input_with_runtime(prompt, agent_tool_runtime.clone())\n .await\n@@ -1500,6 +1562,7 @@ mod tests {\n \n use chrono::TimeZone;\n use fabro_agent::subagent::SessionFactory;\n+ use fabro_agent::tool_registry::ToolDefinitionWithSource;\n use fabro_agent::{AgentProfile, LocalSandbox, ToolRegistry};\n use fabro_api::types;\n use fabro_auth::{EnvCredentialSource, VaultCredentialSource};\n@@ -1566,6 +1629,68 @@ mod tests {\n }\n }\n \n+ fn test_tool_with_source(name: &str, source: ToolSource) -> ToolDefinitionWithSource {\n+ ToolDefinitionWithSource {\n+ definition: LlmToolDefinition {\n+ name: name.to_string(),\n+ description: format!(\"{name} description\"),\n+ parameters: serde_json::json!({\n+ \"type\": \"object\",\n+ \"properties\": {\n+ \"path\": { \"type\": \"string\" }\n+ }\n+ }),\n+ },\n+ source,\n+ }\n+ }\n+\n+ #[test]\n+ fn agent_tool_summaries_map_known_native_categories_without_schemas() {\n+ let summaries = agent_tool_summaries_from_definitions(&[\n+ test_tool_with_source(\"apply_patch\", ToolSource::Native),\n+ test_tool_with_source(\"grep\", ToolSource::Native),\n+ test_tool_with_source(\"glob\", ToolSource::Native),\n+ test_tool_with_source(\"spawn_agent\", ToolSource::Native),\n+ test_tool_with_source(\"unknown_native\", ToolSource::Native),\n+ ]);\n+\n+ assert_eq!(summaries[0].name, \"apply_patch\");\n+ assert_eq!(summaries[0].description, \"apply_patch description\");\n+ assert_eq!(summaries[0].source, fabro_types::AgentToolSource::Native);\n+ assert_eq!(summaries[0].category, fabro_types::AgentToolCategory::Write);\n+ assert!(!summaries[0].invoked);\n+ assert_eq!(summaries[1].category, fabro_types::AgentToolCategory::Read);\n+ assert_eq!(summaries[2].category, fabro_types::AgentToolCategory::Read);\n+ assert_eq!(\n+ summaries[3].category,\n+ fabro_types::AgentToolCategory::Subagent\n+ );\n+ assert_eq!(summaries[4].category, fabro_types::AgentToolCategory::Other);\n+\n+ let json = serde_json::to_value(&summaries[0]).unwrap();\n+ assert!(\n+ json.as_object().unwrap().get(\"parameters\").is_none(),\n+ \"agent tool summaries should not include tool parameter schemas\"\n+ );\n+ }\n+\n+ #[test]\n+ fn agent_tool_summaries_map_mcp_source_and_original_name_from_qualified_name() {\n+ let summaries = agent_tool_summaries_from_definitions(&[test_tool_with_source(\n+ \"mcp__filesystem__read_file\",\n+ ToolSource::Mcp {\n+ server_name: \"filesystem\".to_string(),\n+ },\n+ )]);\n+\n+ assert_eq!(summaries[0].source, fabro_types::AgentToolSource::Mcp {\n+ server_name: \"filesystem\".to_string(),\n+ original_name: \"read_file\".to_string(),\n+ });\n+ assert_eq!(summaries[0].category, fabro_types::AgentToolCategory::Other);\n+ }\n+\n struct ShutdownTestProvider;\n \n #[async_trait]\ndiff --git a/lib/crates/fabro-workflow/src/operations/fork.rs b/lib/crates/fabro-workflow/src/operations/fork.rs\nindex b4ed04d30..513975d71 100644\n--- a/lib/crates/fabro-workflow/src/operations/fork.rs\n+++ b/lib/crates/fabro-workflow/src/operations/fork.rs\n@@ -230,6 +230,7 @@ fn replay_event_for_fork_projection(body: &EventBody) -> bool {\n | EventBody::InterviewTimeout(_)\n | EventBody::InterviewInterrupted(_)\n | EventBody::AgentSessionActivated(_)\n+ | EventBody::AgentToolsAvailable(_)\n | EventBody::AgentAcpStarted(_)\n | EventBody::AgentAcpCancelled(_)\n | EventBody::AgentAcpTimedOut(_)\n@@ -310,6 +311,12 @@ mod tests {\n visit: 1,\n })\n ));\n+ assert!(replay_event_for_fork_projection(\n+ &EventBody::AgentToolsAvailable(fabro_types::run_event::AgentToolsAvailableProps {\n+ tools: Vec::new(),\n+ visit: 1,\n+ })\n+ ));\n assert!(!replay_event_for_fork_projection(\n &EventBody::AgentSessionStarted(fabro_types::run_event::AgentSessionStartedProps {\n provider: Some(\"openai\".to_string()),\ndiff --git a/lib/packages/fabro-api-client/src/.openapi-generator/FILES b/lib/packages/fabro-api-client/src/.openapi-generator/FILES\nindex f8d333e14..c07a09e4c 100644\n--- a/lib/packages/fabro-api-client/src/.openapi-generator/FILES\n+++ b/lib/packages/fabro-api-client/src/.openapi-generator/FILES\n@@ -27,6 +27,13 @@ models/agent-permissions.ts\n models/agent-session-activated-props.ts\n models/agent-skill-activation-source.ts\n models/agent-skill-summary.ts\n+models/agent-tool-category.ts\n+models/agent-tool-source-mcp.ts\n+models/agent-tool-source-native.ts\n+models/agent-tool-source-skill.ts\n+models/agent-tool-source.ts\n+models/agent-tool-summary.ts\n+models/agent-tools-available-props.ts\n models/aggregate-billing-totals.ts\n models/aggregate-billing.ts\n models/api-question.ts\ndiff --git a/lib/packages/fabro-api-client/src/models/agent-tool-category.ts b/lib/packages/fabro-api-client/src/models/agent-tool-category.ts\nnew file mode 100644\nindex 000000000..8e1eda4b0\n--- /dev/null\n+++ b/lib/packages/fabro-api-client/src/models/agent-tool-category.ts\n@@ -0,0 +1,29 @@\n+/* tslint:disable */\n+/* eslint-disable */\n+/**\n+ * Fabro Run API\n+ * HTTP API for managing Fabro workflow run executions.\n+ *\n+ * The version of the OpenAPI document: 0.1.0\n+ *\n+ *\n+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n+ * https://openapi-generator.tech\n+ * Do not edit the class manually.\n+ */\n+\n+\n+\n+/**\n+ * Coarse tool category for display and grouping.\n+ */\n+\n+export const AgentToolCategory = {\n+ READ: 'read',\n+ WRITE: 'write',\n+ SHELL: 'shell',\n+ SUBAGENT: 'subagent',\n+ OTHER: 'other'\n+} as const;\n+\n+export type AgentToolCategory = typeof AgentToolCategory[keyof typeof AgentToolCategory];\ndiff --git a/lib/packages/fabro-api-client/src/models/agent-tool-source-mcp.ts b/lib/packages/fabro-api-client/src/models/agent-tool-source-mcp.ts\nnew file mode 100644\nindex 000000000..3f8089a92\n--- /dev/null\n+++ b/lib/packages/fabro-api-client/src/models/agent-tool-source-mcp.ts\n@@ -0,0 +1,33 @@\n+/* tslint:disable */\n+/* eslint-disable */\n+/**\n+ * Fabro Run API\n+ * HTTP API for managing Fabro workflow run executions.\n+ *\n+ * The version of the OpenAPI document: 0.1.0\n+ *\n+ *\n+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n+ * https://openapi-generator.tech\n+ * Do not edit the class manually.\n+ */\n+\n+\n+\n+export interface AgentToolSourceMcp {\n+ 'kind': AgentToolSourceMcpKindEnum;\n+ /**\n+ * MCP server name that provided the tool.\n+ */\n+ 'server_name': string;\n+ /**\n+ * Tool name before MCP qualification.\n+ */\n+ 'original_name': string;\n+}\n+\n+export const AgentToolSourceMcpKindEnum = {\n+ MCP: 'mcp'\n+} as const;\n+\n+export type AgentToolSourceMcpKindEnum = typeof AgentToolSourceMcpKindEnum[keyof typeof AgentToolSourceMcpKindEnum];\ndiff --git a/lib/packages/fabro-api-client/src/models/agent-tool-source-native.ts b/lib/packages/fabro-api-client/src/models/agent-tool-source-native.ts\nnew file mode 100644\nindex 000000000..4ea94bead\n--- /dev/null\n+++ b/lib/packages/fabro-api-client/src/models/agent-tool-source-native.ts\n@@ -0,0 +1,25 @@\n+/* tslint:disable */\n+/* eslint-disable */\n+/**\n+ * Fabro Run API\n+ * HTTP API for managing Fabro workflow run executions.\n+ *\n+ * The version of the OpenAPI document: 0.1.0\n+ *\n+ *\n+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n+ * https://openapi-generator.tech\n+ * Do not edit the class manually.\n+ */\n+\n+\n+\n+export interface AgentToolSourceNative {\n+ 'kind': AgentToolSourceNativeKindEnum;\n+}\n+\n+export const AgentToolSourceNativeKindEnum = {\n+ NATIVE: 'native'\n+} as const;\n+\n+export type AgentToolSourceNativeKindEnum = typeof AgentToolSourceNativeKindEnum[keyof typeof AgentToolSourceNativeKindEnum];\ndiff --git a/lib/packages/fabro-api-client/src/models/agent-tool-source-skill.ts b/lib/packages/fabro-api-client/src/models/agent-tool-source-skill.ts\nnew file mode 100644\nindex 000000000..e150e8591\n--- /dev/null\n+++ b/lib/packages/fabro-api-client/src/models/agent-tool-source-skill.ts\n@@ -0,0 +1,25 @@\n+/* tslint:disable */\n+/* eslint-disable */\n+/**\n+ * Fabro Run API\n+ * HTTP API for managing Fabro workflow run executions.\n+ *\n+ * The version of the OpenAPI document: 0.1.0\n+ *\n+ *\n+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n+ * https://openapi-generator.tech\n+ * Do not edit the class manually.\n+ */\n+\n+\n+\n+export interface AgentToolSourceSkill {\n+ 'kind': AgentToolSourceSkillKindEnum;\n+}\n+\n+export const AgentToolSourceSkillKindEnum = {\n+ SKILL: 'skill'\n+} as const;\n+\n+export type AgentToolSourceSkillKindEnum = typeof AgentToolSourceSkillKindEnum[keyof typeof AgentToolSourceSkillKindEnum];\ndiff --git a/lib/packages/fabro-api-client/src/models/agent-tool-source.ts b/lib/packages/fabro-api-client/src/models/agent-tool-source.ts\nnew file mode 100644\nindex 000000000..391f72fd5\n--- /dev/null\n+++ b/lib/packages/fabro-api-client/src/models/agent-tool-source.ts\n@@ -0,0 +1,30 @@\n+/* tslint:disable */\n+/* eslint-disable */\n+/**\n+ * Fabro Run API\n+ * HTTP API for managing Fabro workflow run executions.\n+ *\n+ * The version of the OpenAPI document: 0.1.0\n+ *\n+ *\n+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n+ * https://openapi-generator.tech\n+ * Do not edit the class manually.\n+ */\n+\n+\n+// May contain unused imports in some cases\n+// @ts-ignore\n+import type { AgentToolSourceMcp } from './agent-tool-source-mcp';\n+// May contain unused imports in some cases\n+// @ts-ignore\n+import type { AgentToolSourceNative } from './agent-tool-source-native';\n+// May contain unused imports in some cases\n+// @ts-ignore\n+import type { AgentToolSourceSkill } from './agent-tool-source-skill';\n+\n+/**\n+ * @type AgentToolSource\n+ * Origin of an effective agent tool.\n+ */\n+export type AgentToolSource = { kind: 'mcp' } & AgentToolSourceMcp | { kind: 'native' } & AgentToolSourceNative | { kind: 'skill' } & AgentToolSourceSkill;\ndiff --git a/lib/packages/fabro-api-client/src/models/agent-tool-summary.ts b/lib/packages/fabro-api-client/src/models/agent-tool-summary.ts\nnew file mode 100644\nindex 000000000..b52e220c0\n--- /dev/null\n+++ b/lib/packages/fabro-api-client/src/models/agent-tool-summary.ts\n@@ -0,0 +1,41 @@\n+/* tslint:disable */\n+/* eslint-disable */\n+/**\n+ * Fabro Run API\n+ * HTTP API for managing Fabro workflow run executions.\n+ *\n+ * The version of the OpenAPI document: 0.1.0\n+ *\n+ *\n+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n+ * https://openapi-generator.tech\n+ * Do not edit the class manually.\n+ */\n+\n+\n+// May contain unused imports in some cases\n+// @ts-ignore\n+import type { AgentToolCategory } from './agent-tool-category';\n+// May contain unused imports in some cases\n+// @ts-ignore\n+import type { AgentToolSource } from './agent-tool-source';\n+\n+/**\n+ * Summary of one effective model-callable tool exposed to an agent stage.\n+ */\n+export interface AgentToolSummary {\n+ /**\n+ * Exposed model-facing tool name, for example `apply_patch` or `mcp__filesystem__read_file`.\n+ */\n+ 'name': string;\n+ /**\n+ * Model-facing tool description.\n+ */\n+ 'description': string;\n+ 'source': AgentToolSource;\n+ 'category': AgentToolCategory;\n+ /**\n+ * True once this tool has been invoked during the stage.\n+ */\n+ 'invoked': boolean;\n+}\ndiff --git a/lib/packages/fabro-api-client/src/models/agent-tools-available-props.ts b/lib/packages/fabro-api-client/src/models/agent-tools-available-props.ts\nnew file mode 100644\nindex 000000000..1231a8aa8\n--- /dev/null\n+++ b/lib/packages/fabro-api-client/src/models/agent-tools-available-props.ts\n@@ -0,0 +1,29 @@\n+/* tslint:disable */\n+/* eslint-disable */\n+/**\n+ * Fabro Run API\n+ * HTTP API for managing Fabro workflow run executions.\n+ *\n+ * The version of the OpenAPI document: 0.1.0\n+ *\n+ *\n+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).\n+ * https://openapi-generator.tech\n+ * Do not edit the class manually.\n+ */\n+\n+\n+// May contain unused imports in some cases\n+// @ts-ignore\n+import type { AgentToolSummary } from './agent-tool-summary';\n+\n+/**\n+ * Properties for the `agent.tools.available` event.\n+ */\n+export interface AgentToolsAvailableProps {\n+ /**\n+ * Effective model-callable tools exposed to the stage session.\n+ */\n+ 'tools': Array;\n+ 'visit': number;\n+}\ndiff --git a/lib/packages/fabro-api-client/src/models/index.ts b/lib/packages/fabro-api-client/src/models/index.ts\nindex 78d106d70..1a153e0e7 100644\n--- a/lib/packages/fabro-api-client/src/models/index.ts\n+++ b/lib/packages/fabro-api-client/src/models/index.ts\n@@ -4,6 +4,13 @@ export * from './agent-permissions';\n export * from './agent-session-activated-props';\n export * from './agent-skill-activation-source';\n export * from './agent-skill-summary';\n+export * from './agent-tool-category';\n+export * from './agent-tool-source';\n+export * from './agent-tool-source-mcp';\n+export * from './agent-tool-source-native';\n+export * from './agent-tool-source-skill';\n+export * from './agent-tool-summary';\n+export * from './agent-tools-available-props';\n export * from './aggregate-billing';\n export * from './aggregate-billing-totals';\n export * from './api-question';\ndiff --git a/lib/packages/fabro-api-client/src/models/stage-projection.ts b/lib/packages/fabro-api-client/src/models/stage-projection.ts\nindex 24df4baed..b49e864ca 100644\n--- a/lib/packages/fabro-api-client/src/models/stage-projection.ts\n+++ b/lib/packages/fabro-api-client/src/models/stage-projection.ts\n@@ -13,6 +13,9 @@\n */\n \n \n+// May contain unused imports in some cases\n+// @ts-ignore\n+import type { AgentToolSummary } from './agent-tool-summary';\n // May contain unused imports in some cases\n // @ts-ignore\n import type { BilledTokenCounts } from './billed-token-counts';\n@@ -96,6 +99,10 @@ export interface StageProjection {\n */\n 'skills'?: SkillsProjection;\n 'permission_level'?: PermissionLevel | null;\n+ /**\n+ * Effective model-callable tools exposed to this agent stage session. Tool parameter schemas are intentionally omitted from this projection.\n+ */\n+ 'agent_tools'?: Array;\n /**\n * MCP servers observed by this stage.\n */\n", + "summary": { + "files_changed": 29, + "additions": 1087, + "deletions": 39 + } + } + }, + { + "seq": 0, + "checkpoint": { + "timestamp": "2026-05-24T17:57:19.244493Z", + "current_node": "simplify_opus", + "completed_nodes": [ + "start", + "toolchain", + "preflight_compile", + "preflight_lint", + "implement", + "simplify_opus" + ], + "node_retries": {}, + "context_values": { "graph.rankdir": "LR", "graph.model_stylesheet": "\n * { model: claude-opus-4-7; }\n ", - "internal.retry_count.preflight_lint": 0, - "graph.goal": "---\ntitle: feat: StageProjection agent tools API\ntype: feat\nstatus: active\ndate: 2026-05-24\n---\n\n# feat: StageProjection Agent Tools API\n\n## Overview\n\nExpose the complete effective tool list for each agent-backed stage through `StageProjection`, so UI and API consumers can show actual tools such as `apply_patch`, `grep`, `glob`, `read_file`, MCP tools, skill tools, and subagent tools without inferring them from `permission_level`.\n\nThe API should expose tool summaries with `name`, `description`, `source`, `category`, and `invoked`. It must not expose full JSON parameter schemas in the run projection.\n\n## Problem Frame\n\nThe stage sidebar currently has permission metadata such as \"Full access\", but `permission_level` is only an access mode. It does not tell consumers which tools were actually exposed to the model after provider profile setup, optional tool registration, MCP integration, and tool access policy filtering.\n\nThe authoritative list already exists at request-build time in the agent session registry. The API needs to capture that effective list once per stage session and project it onto the stage.\n\n## Requirements Trace\n\n- R1. Add a StageProjection API field containing the complete effective tools for a stage session.\n- R2. Include `name`, `description`, `source`, `category`, and `invoked` for each tool.\n- R3. Do not infer tools from `permission_level` in backend or frontend code.\n- R4. Do not expose full tool parameter schemas through StageProjection.\n- R5. Preserve existing `permission_level` and `mcp_servers` fields for compatibility.\n- R6. Mark individual tools as invoked when matching `agent.tool.started` events are projected.\n- R7. Keep legacy runs backward compatible by defaulting missing tool lists to empty.\n\n## Scope Boundaries\n\n- Do not remove or rename `StageProjection.permission_level`.\n- Do not remove the existing MCP server projection or `AgentMcpToolSummary`.\n- Do not change completion API tool definitions.\n- Do not add ACP-native tool discovery in this pass unless an ACP path already has an equivalent effective tool list available.\n- Do not render parameter schemas in the web UI.\n\n## Context & Research\n\n### Relevant Code and Patterns\n\n- OpenAPI is the source of truth for HTTP contracts in `docs/public/api-reference/fabro-api.yaml`.\n- Shared API/projection DTOs should live in `fabro-types`, with `fabro-api/build.rs` replacements to avoid duplicate generated Rust types.\n- `StageProjection` lives in `lib/crates/fabro-types/src/run_projection.rs`.\n- Durable run event props live in `lib/crates/fabro-types/src/run_event/agent.rs` and `lib/crates/fabro-types/src/run_event/mod.rs`.\n- Workflow event conversion and event names live in `lib/crates/fabro-workflow/src/event/convert.rs`, `events.rs`, and `names.rs`.\n- Projection replay lives in `lib/crates/fabro-store/src/run_state.rs`.\n- The effective request tool list is built in `lib/crates/fabro-agent/src/session.rs` from `ToolRegistry::definitions_with_source_for_policy`.\n- Tool source metadata already exists as `ToolSource` and `ToolDefinitionWithSource` in `lib/crates/fabro-agent/src/tool_registry.rs`.\n- Tool category mapping already exists in `lib/crates/fabro-agent/src/tool_permissions.rs`.\n- The sidebar display lives in `apps/fabro-web/app/components/stage-insights-sidebar.tsx`.\n\n### Strategy Docs\n\n- Read `docs/internal/events-strategy.md` before adding the new durable event.\n- Read `docs/internal/testing-strategy.md` before adding or reorganizing tests.\n- Follow the OpenAPI type ownership guidance in `AGENTS.md`: reuse `fabro-types` through `fabro-api/build.rs` replacements when the API schema has the same product meaning and serde shape.\n\n## Key Technical Decisions\n\n- Add a new StageProjection field named `agent_tools`, not `tools`, to avoid ambiguity with MCP nested tools and completion tool definitions.\n- Add a dedicated durable event named `agent.tools.available` instead of overloading `agent.session.activated`.\n- Capture the effective tool list after session setup and filtering, using the same path as model request construction.\n- Store descriptions in the summary because they are useful API/UI metadata; omit parameter schemas to keep projection payloads small and avoid leaking full implementation detail.\n- Keep `AgentMcpToolSummary` MCP-only. Add a new general-purpose `AgentToolSummary` instead of stretching the MCP type beyond its meaning.\n- Treat `invoked` as projected state. The availability event should emit tools with `invoked: false`; replay of `agent.tool.started` flips matching tools to true.\n\n## API Contract\n\nAdd these schemas to OpenAPI and map them to `fabro_types` replacements:\n\n- `AgentToolSummary`\n - required: `name`, `description`, `source`, `category`, `invoked`\n - `name`: exposed tool name, e.g. `apply_patch` or `mcp__filesystem__read_file`\n - `description`: model-facing tool description\n - `source`: `AgentToolSource`\n - `category`: `AgentToolCategory`\n - `invoked`: boolean\n- `AgentToolSource`\n - tagged by `kind`\n - `native`\n - `mcp` with `server_name` and `original_name`\n - `skill`\n- `AgentToolCategory`\n - enum: `read`, `write`, `shell`, `subagent`, `other`\n- `AgentToolsAvailableProps`\n - required: `tools`, `visit`\n - `tools`: array of `AgentToolSummary`\n - `visit`: stage visit number\n\nAdd to `StageProjection`:\n\n- `agent_tools`: array of `AgentToolSummary`\n- Default to an empty array when omitted.\n- Skip serializing when empty, matching existing projection optional-list style.\n\nAdd event body:\n\n- Serialized event name: `agent.tools.available`\n- Event body type: `AgentToolsAvailableProps`\n\n## Implementation Units\n\n- [ ] **Unit 1: Add shared tool summary types**\n\n**Goal:** Define the canonical API/projection DTOs in `fabro-types`.\n\n**Files:**\n- Modify: `lib/crates/fabro-types/src/run_event/agent.rs`\n- Modify: `lib/crates/fabro-types/src/run_event/mod.rs`\n- Modify: `lib/crates/fabro-types/src/run_projection.rs`\n- Modify: `lib/crates/fabro-types/src/lib.rs`\n\n**Work:**\n- Add `AgentToolSummary`, `AgentToolSource`, `AgentToolCategory`, and `AgentToolsAvailableProps`.\n- Add `EventBody::AgentToolsAvailable` serialized as `agent.tools.available`.\n- Add `agent_tools: Vec` to `StageProjection`.\n- Ensure all new fields default cleanly for older persisted events/projections.\n- Export the new public types from `fabro-types`.\n\n- [ ] **Unit 2: Capture effective session tools**\n\n**Goal:** Provide an authoritative one-time source for the list that the model can actually call.\n\n**Files:**\n- Modify: `lib/crates/fabro-agent/src/session.rs`\n- Modify: `lib/crates/fabro-workflow/src/handler/llm/api.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/events.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/names.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/convert.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/stored_fields.rs` only if the new event needs non-standard stored fields.\n\n**Work:**\n- Add `Session::available_tools()` that returns the same effective `ToolDefinitionWithSource` list as `build_request()`.\n- Map `ToolDefinitionWithSource` to `AgentToolSummary` at the workflow boundary.\n- Populate `description` from `ToolDefinition.description`.\n- Populate `source` from `ToolSource`.\n- For MCP tools, include the server name from `ToolSource::Mcp` and derive `original_name` from the qualified exposed name using the existing MCP naming convention.\n- Populate `category` from the existing tool category mapping for known exposed names; use `other` when no category mapping applies.\n- Emit `agent.tools.available` once for the stage session after session setup and filtering are complete.\n\n- [ ] **Unit 3: Project available and invoked tools**\n\n**Goal:** Make `StageProjection.agent_tools` replay-authoritative.\n\n**Files:**\n- Modify: `lib/crates/fabro-store/src/run_state.rs`\n\n**Work:**\n- On `EventBody::AgentToolsAvailable`, replace the current stage visit's `agent_tools` with the event tools.\n- On `EventBody::AgentToolStarted`, find a matching `agent_tools` entry by exposed `tool_name` and set `invoked = true`.\n- Keep the existing MCP server `invoked` update unchanged.\n- If a legacy run has no availability event, do not synthesize a full list from permissions.\n\n- [ ] **Unit 4: Update OpenAPI and generated clients**\n\n**Goal:** Expose the new projection field and event contract through public API clients without duplicate Rust API types.\n\n**Files:**\n- Modify: `docs/public/api-reference/fabro-api.yaml`\n- Modify: `lib/crates/fabro-api/build.rs`\n- Modify: `lib/crates/fabro-api/src/lib.rs`\n- Modify generated files under `lib/crates/fabro-api/src/generated.rs` via `cargo build -p fabro-api`.\n- Modify generated files under `lib/packages/fabro-api-client/src` via TypeScript client generation.\n\n**Work:**\n- Add the OpenAPI schemas listed in the API Contract section.\n- Add `StageProjection.agent_tools`.\n- Add `fabro-api/build.rs` replacements for the new `fabro-types` types.\n- Regenerate Rust API code.\n- Regenerate TypeScript API client code.\n\n- [ ] **Unit 5: Render tools in the web sidebar**\n\n**Goal:** Replace the permission-derived sidebar display with the actual projected tool list.\n\n**Files:**\n- Modify: `apps/fabro-web/app/components/stage-insights-sidebar.tsx`\n- Modify: `apps/fabro-web/app/components/stage-insights-sidebar.test.tsx`\n\n**Work:**\n- Render `stage.agent_tools` when present.\n- Show each tool's name, description, source/category, and invoked state.\n- Keep permission level as secondary metadata or fallback for legacy stages with no `agent_tools`.\n- Do not infer tool availability from permission level.\n\n## Test Plan\n\n- `fabro-types`\n - JSON round-trip for `agent.tools.available`.\n - Serialization checks for `AgentToolSource` and `AgentToolCategory`.\n - Backward compatibility check that missing `agent_tools` deserializes to an empty list.\n\n- `fabro-workflow`\n - Event name and conversion tests for `agent.tools.available`.\n - Capture test proving native tools such as `apply_patch`, `grep`, and `glob` are emitted from the effective registry path.\n - MCP source mapping test for a qualified MCP tool name.\n\n- `fabro-store`\n - Projection test that `agent.tools.available` populates `StageProjection.agent_tools`.\n - Projection test that `agent.tool.started` marks only the matching tool as invoked.\n - Regression test that MCP server `invoked` status still updates as before.\n\n- `fabro-api`\n - Type identity/parity tests confirming API types reuse `fabro_types::AgentToolSummary`, `AgentToolSource`, `AgentToolCategory`, and `AgentToolsAvailableProps`.\n - StageProjection round-trip test including `agent_tools`.\n\n- `fabro-web`\n - Sidebar test rendering tool names and descriptions from `stage.agent_tools`.\n - Sidebar test showing invoked state.\n - Legacy fallback test for stages without `agent_tools`.\n\n## Run Checks\n\n- `cargo +nightly-2026-04-14 fmt --check --all`\n- `cargo nextest run -p fabro-types -p fabro-workflow -p fabro-store -p fabro-api`\n- `cargo build -p fabro-api`\n- `cd lib/packages/fabro-api-client && bun run generate`\n- `cd apps/fabro-web && bun test && bun run typecheck`\n\n## Assumptions\n\n- The first implementation targets normal API-backed agent sessions, not ACP-native sessions.\n- `description` is safe to expose because it is already model-facing tool metadata, but parameter schemas remain out of scope for StageProjection.\n- `agent_tools` is a complete list only for runs that emit `agent.tools.available`; legacy runs return an empty list and may still show existing permission/MCP metadata.\n- If tool registration becomes mutable later, the event contract can be re-emitted and projection replacement semantics will still work.\n", "internal.retry_count.start": 0, "internal.fidelity": "compact", - "command.output": "blob://sha256/12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126", "failure_signature": "", - "last_stage": "implement", - "internal.thread_id": "preflight_lint", + "internal.retry_count.toolchain": 0, + "internal.retry_count.preflight_compile": 0, + "thread.implement.current_node": "simplify_opus", + "outcome": "succeeded", + "failure_class": "", + "response.simplify_opus": "## Summary\n\nAggregated three review agents' findings and applied the consensus high-value fixes:\n\n**Quality / reuse fixes:**\n- `tool_permissions::known_tool_category` now returns `Option` directly. Deleted the brittle `Some(\"read\")` → `Read` string match in `handler/llm/api.rs`. `is_auto_approved` and `tool_category` are now enum-typed end-to-end; cli.rs and its tests updated accordingly. Adding a new category is now a compile-time exhaustiveness error instead of a silent `Other`.\n- `ToolSource::Mcp` now carries `original_name` populated from `info.original_tool_name` in `make_mcp_tools`. Workflow code no longer re-parses qualified MCP names (eliminates the silent fallback bug where a malformed prefix would store the qualified name as \"original\").\n- Moved `agent_tool_source` + `agent_tool_summaries_from_definitions` out of `handler/llm/api.rs`. New `ToolDefinitionWithSource::to_agent_tool_summary()` + `Session::agent_tool_summaries()` colocate the conversion next to the source type. Tests moved to `tool_registry.rs`.\n- Collapsed `Session::available_tools` and the duplicate private `effective_tools` into one public `effective_tools()` method.\n- Merged `ToolAvailableIcon` and `TodoPendingIcon` into a single `EmptyCircleIcon` component in the sidebar.\n\n**Efficiency fix:**\n- Gated `emit_agent_tools_available` on `!is_reused` in the primary path. Reused steerable sessions had been re-emitting the full tool list (with descriptions cloned into the event payload) on every prompt even though registry, access policy, and exposure mode are immutable for the session's lifetime. Failover path keeps its emit since it always builds a fresh session.\n\n**Skipped (cost > benefit):** `mcp_server_from_tool_name` dedup in `fabro-store` would require pulling `fabro-mcp` (with `rmcp`) into the store crate or relocating the parse helper into `fabro-types`. The duplicate is 5 lines using the same delimiter convention — not worth the dependency surface.\n\n**Verification:** `cargo check --workspace --all-targets`, `cargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warnings`, `cargo +nightly-2026-04-14 fmt --check --all`, `cargo nextest run -p fabro-types -p fabro-workflow -p fabro-store -p fabro-api -p fabro-agent` (2250+464 tests), `bun test stage-insights-sidebar` (10/10), and `bun run typecheck` all pass. The 14 unrelated `run-actions.test.ts` failures pre-exist on the parent commit.", + "internal.retry_count.simplify_opus": 0, + "response.implement": "The TS generator is pinned now, but this sandbox lacks Java, which OpenAPI Generator needs. I’ll install a headless JRE and rerun generation.", + "internal.retry_count.preflight_lint": 0, + "graph.goal": "---\ntitle: feat: StageProjection agent tools API\ntype: feat\nstatus: active\ndate: 2026-05-24\n---\n\n# feat: StageProjection Agent Tools API\n\n## Overview\n\nExpose the complete effective tool list for each agent-backed stage through `StageProjection`, so UI and API consumers can show actual tools such as `apply_patch`, `grep`, `glob`, `read_file`, MCP tools, skill tools, and subagent tools without inferring them from `permission_level`.\n\nThe API should expose tool summaries with `name`, `description`, `source`, `category`, and `invoked`. It must not expose full JSON parameter schemas in the run projection.\n\n## Problem Frame\n\nThe stage sidebar currently has permission metadata such as \"Full access\", but `permission_level` is only an access mode. It does not tell consumers which tools were actually exposed to the model after provider profile setup, optional tool registration, MCP integration, and tool access policy filtering.\n\nThe authoritative list already exists at request-build time in the agent session registry. The API needs to capture that effective list once per stage session and project it onto the stage.\n\n## Requirements Trace\n\n- R1. Add a StageProjection API field containing the complete effective tools for a stage session.\n- R2. Include `name`, `description`, `source`, `category`, and `invoked` for each tool.\n- R3. Do not infer tools from `permission_level` in backend or frontend code.\n- R4. Do not expose full tool parameter schemas through StageProjection.\n- R5. Preserve existing `permission_level` and `mcp_servers` fields for compatibility.\n- R6. Mark individual tools as invoked when matching `agent.tool.started` events are projected.\n- R7. Keep legacy runs backward compatible by defaulting missing tool lists to empty.\n\n## Scope Boundaries\n\n- Do not remove or rename `StageProjection.permission_level`.\n- Do not remove the existing MCP server projection or `AgentMcpToolSummary`.\n- Do not change completion API tool definitions.\n- Do not add ACP-native tool discovery in this pass unless an ACP path already has an equivalent effective tool list available.\n- Do not render parameter schemas in the web UI.\n\n## Context & Research\n\n### Relevant Code and Patterns\n\n- OpenAPI is the source of truth for HTTP contracts in `docs/public/api-reference/fabro-api.yaml`.\n- Shared API/projection DTOs should live in `fabro-types`, with `fabro-api/build.rs` replacements to avoid duplicate generated Rust types.\n- `StageProjection` lives in `lib/crates/fabro-types/src/run_projection.rs`.\n- Durable run event props live in `lib/crates/fabro-types/src/run_event/agent.rs` and `lib/crates/fabro-types/src/run_event/mod.rs`.\n- Workflow event conversion and event names live in `lib/crates/fabro-workflow/src/event/convert.rs`, `events.rs`, and `names.rs`.\n- Projection replay lives in `lib/crates/fabro-store/src/run_state.rs`.\n- The effective request tool list is built in `lib/crates/fabro-agent/src/session.rs` from `ToolRegistry::definitions_with_source_for_policy`.\n- Tool source metadata already exists as `ToolSource` and `ToolDefinitionWithSource` in `lib/crates/fabro-agent/src/tool_registry.rs`.\n- Tool category mapping already exists in `lib/crates/fabro-agent/src/tool_permissions.rs`.\n- The sidebar display lives in `apps/fabro-web/app/components/stage-insights-sidebar.tsx`.\n\n### Strategy Docs\n\n- Read `docs/internal/events-strategy.md` before adding the new durable event.\n- Read `docs/internal/testing-strategy.md` before adding or reorganizing tests.\n- Follow the OpenAPI type ownership guidance in `AGENTS.md`: reuse `fabro-types` through `fabro-api/build.rs` replacements when the API schema has the same product meaning and serde shape.\n\n## Key Technical Decisions\n\n- Add a new StageProjection field named `agent_tools`, not `tools`, to avoid ambiguity with MCP nested tools and completion tool definitions.\n- Add a dedicated durable event named `agent.tools.available` instead of overloading `agent.session.activated`.\n- Capture the effective tool list after session setup and filtering, using the same path as model request construction.\n- Store descriptions in the summary because they are useful API/UI metadata; omit parameter schemas to keep projection payloads small and avoid leaking full implementation detail.\n- Keep `AgentMcpToolSummary` MCP-only. Add a new general-purpose `AgentToolSummary` instead of stretching the MCP type beyond its meaning.\n- Treat `invoked` as projected state. The availability event should emit tools with `invoked: false`; replay of `agent.tool.started` flips matching tools to true.\n\n## API Contract\n\nAdd these schemas to OpenAPI and map them to `fabro_types` replacements:\n\n- `AgentToolSummary`\n - required: `name`, `description`, `source`, `category`, `invoked`\n - `name`: exposed tool name, e.g. `apply_patch` or `mcp__filesystem__read_file`\n - `description`: model-facing tool description\n - `source`: `AgentToolSource`\n - `category`: `AgentToolCategory`\n - `invoked`: boolean\n- `AgentToolSource`\n - tagged by `kind`\n - `native`\n - `mcp` with `server_name` and `original_name`\n - `skill`\n- `AgentToolCategory`\n - enum: `read`, `write`, `shell`, `subagent`, `other`\n- `AgentToolsAvailableProps`\n - required: `tools`, `visit`\n - `tools`: array of `AgentToolSummary`\n - `visit`: stage visit number\n\nAdd to `StageProjection`:\n\n- `agent_tools`: array of `AgentToolSummary`\n- Default to an empty array when omitted.\n- Skip serializing when empty, matching existing projection optional-list style.\n\nAdd event body:\n\n- Serialized event name: `agent.tools.available`\n- Event body type: `AgentToolsAvailableProps`\n\n## Implementation Units\n\n- [ ] **Unit 1: Add shared tool summary types**\n\n**Goal:** Define the canonical API/projection DTOs in `fabro-types`.\n\n**Files:**\n- Modify: `lib/crates/fabro-types/src/run_event/agent.rs`\n- Modify: `lib/crates/fabro-types/src/run_event/mod.rs`\n- Modify: `lib/crates/fabro-types/src/run_projection.rs`\n- Modify: `lib/crates/fabro-types/src/lib.rs`\n\n**Work:**\n- Add `AgentToolSummary`, `AgentToolSource`, `AgentToolCategory`, and `AgentToolsAvailableProps`.\n- Add `EventBody::AgentToolsAvailable` serialized as `agent.tools.available`.\n- Add `agent_tools: Vec` to `StageProjection`.\n- Ensure all new fields default cleanly for older persisted events/projections.\n- Export the new public types from `fabro-types`.\n\n- [ ] **Unit 2: Capture effective session tools**\n\n**Goal:** Provide an authoritative one-time source for the list that the model can actually call.\n\n**Files:**\n- Modify: `lib/crates/fabro-agent/src/session.rs`\n- Modify: `lib/crates/fabro-workflow/src/handler/llm/api.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/events.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/names.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/convert.rs`\n- Modify: `lib/crates/fabro-workflow/src/event/stored_fields.rs` only if the new event needs non-standard stored fields.\n\n**Work:**\n- Add `Session::available_tools()` that returns the same effective `ToolDefinitionWithSource` list as `build_request()`.\n- Map `ToolDefinitionWithSource` to `AgentToolSummary` at the workflow boundary.\n- Populate `description` from `ToolDefinition.description`.\n- Populate `source` from `ToolSource`.\n- For MCP tools, include the server name from `ToolSource::Mcp` and derive `original_name` from the qualified exposed name using the existing MCP naming convention.\n- Populate `category` from the existing tool category mapping for known exposed names; use `other` when no category mapping applies.\n- Emit `agent.tools.available` once for the stage session after session setup and filtering are complete.\n\n- [ ] **Unit 3: Project available and invoked tools**\n\n**Goal:** Make `StageProjection.agent_tools` replay-authoritative.\n\n**Files:**\n- Modify: `lib/crates/fabro-store/src/run_state.rs`\n\n**Work:**\n- On `EventBody::AgentToolsAvailable`, replace the current stage visit's `agent_tools` with the event tools.\n- On `EventBody::AgentToolStarted`, find a matching `agent_tools` entry by exposed `tool_name` and set `invoked = true`.\n- Keep the existing MCP server `invoked` update unchanged.\n- If a legacy run has no availability event, do not synthesize a full list from permissions.\n\n- [ ] **Unit 4: Update OpenAPI and generated clients**\n\n**Goal:** Expose the new projection field and event contract through public API clients without duplicate Rust API types.\n\n**Files:**\n- Modify: `docs/public/api-reference/fabro-api.yaml`\n- Modify: `lib/crates/fabro-api/build.rs`\n- Modify: `lib/crates/fabro-api/src/lib.rs`\n- Modify generated files under `lib/crates/fabro-api/src/generated.rs` via `cargo build -p fabro-api`.\n- Modify generated files under `lib/packages/fabro-api-client/src` via TypeScript client generation.\n\n**Work:**\n- Add the OpenAPI schemas listed in the API Contract section.\n- Add `StageProjection.agent_tools`.\n- Add `fabro-api/build.rs` replacements for the new `fabro-types` types.\n- Regenerate Rust API code.\n- Regenerate TypeScript API client code.\n\n- [ ] **Unit 5: Render tools in the web sidebar**\n\n**Goal:** Replace the permission-derived sidebar display with the actual projected tool list.\n\n**Files:**\n- Modify: `apps/fabro-web/app/components/stage-insights-sidebar.tsx`\n- Modify: `apps/fabro-web/app/components/stage-insights-sidebar.test.tsx`\n\n**Work:**\n- Render `stage.agent_tools` when present.\n- Show each tool's name, description, source/category, and invoked state.\n- Keep permission level as secondary metadata or fallback for legacy stages with no `agent_tools`.\n- Do not infer tool availability from permission level.\n\n## Test Plan\n\n- `fabro-types`\n - JSON round-trip for `agent.tools.available`.\n - Serialization checks for `AgentToolSource` and `AgentToolCategory`.\n - Backward compatibility check that missing `agent_tools` deserializes to an empty list.\n\n- `fabro-workflow`\n - Event name and conversion tests for `agent.tools.available`.\n - Capture test proving native tools such as `apply_patch`, `grep`, and `glob` are emitted from the effective registry path.\n - MCP source mapping test for a qualified MCP tool name.\n\n- `fabro-store`\n - Projection test that `agent.tools.available` populates `StageProjection.agent_tools`.\n - Projection test that `agent.tool.started` marks only the matching tool as invoked.\n - Regression test that MCP server `invoked` status still updates as before.\n\n- `fabro-api`\n - Type identity/parity tests confirming API types reuse `fabro_types::AgentToolSummary`, `AgentToolSource`, `AgentToolCategory`, and `AgentToolsAvailableProps`.\n - StageProjection round-trip test including `agent_tools`.\n\n- `fabro-web`\n - Sidebar test rendering tool names and descriptions from `stage.agent_tools`.\n - Sidebar test showing invoked state.\n - Legacy fallback test for stages without `agent_tools`.\n\n## Run Checks\n\n- `cargo +nightly-2026-04-14 fmt --check --all`\n- `cargo nextest run -p fabro-types -p fabro-workflow -p fabro-store -p fabro-api`\n- `cargo build -p fabro-api`\n- `cd lib/packages/fabro-api-client && bun run generate`\n- `cd apps/fabro-web && bun test && bun run typecheck`\n\n## Assumptions\n\n- The first implementation targets normal API-backed agent sessions, not ACP-native sessions.\n- `description` is safe to expose because it is already model-facing tool metadata, but parameter schemas remain out of scope for StageProjection.\n- `agent_tools` is a complete list only for runs that emit `agent.tools.available`; legacy runs return an empty list and may still show existing permission/MCP metadata.\n- If tool registration becomes mutable later, the event contract can be re-emitted and projection replacement semantics will still work.\n", + "command.output": "blob://sha256/12ae32cb1ec02d01eda3581b127c1fee3b0dc53572ed6baf239721a03d82e126", + "last_stage": "simplify_opus", + "internal.thread_id": "implement", "thread.start.current_node": "toolchain", "thread.preflight_compile.current_node": "preflight_lint", "internal.node_visit_count": 1, - "internal.retry_count.toolchain": 0, "thread.toolchain.current_node": "preflight_compile", - "internal.retry_count.preflight_compile": 0, "thread.preflight_lint.current_node": "implement", - "outcome": "succeeded", - "last_response": "The TS generator is pinned now, but this sandbox lacks Java, which OpenAPI Generator needs. I’ll install a headless JRE and rerun generation.", + "last_response": "## Summary\n\nAggregated three review agents' findings and applied the consensus high-value fixes:\n\n**Quality / reuse fixes:**\n- `tool_permissions::known_tool_category` now returns `Option` directly. Deleted the brittle `Some(\"read\")` → `Read` string match in `handler/llm/api.rs`. `is_auto_approved` and `tool_category` are now enum-typed end-to-end; cli.rs and its tests updated accordingly. Adding a new category is now a compile-time exhaustiveness error instead of a silent `Other`.\n- `ToolSource::Mcp` now carries `original_name` populated from `info.original_tool_name` in `make_mcp_tools`. Workflow code no longer re-parses qualified MCP names (eliminates the silent fallback bug where a malformed prefix would store the qualified name as \"original\").\n- Moved `agent_tool_source` + `agent_tool_summaries_from_definitions` out of `handler/llm/api.rs`. New `ToolDefinitionWithSource::to_agent_tool_summary()` + `Session::agent_tool_summaries()` colocate the conversion next to the source type. Tests moved to `tool_registry.rs`.\n- Collapsed `Session::available_tools` and the duplicate private `effective_tools` into one public `effective_tools()` method.\n- Merged `ToolAvailableIcon` and `TodoPendingIcon` into a single `EmptyCircleIcon` component in the sidebar.\n\n**Efficiency fix:**\n- Gated `emit_agent_tools_available` on `!is_reused` in the primary path. Reused steerable sessions had been re-emitting the full tool list (with descriptions cloned into the event payload) on every prompt even though registry, access policy, and exposure mode are immutable for the session's lifetime. Failover path keeps its emit since it always builds a fresh session.\n\n**Skipped (cost > benefit):** `mcp_server_from_tool_name` dedup in `fabro-store` would require pulling `fabro-mcp` (with `rmcp`) into the store crate or relocating the parse helper into `fabro-types`. The duplicate is 5 lines using the same delimiter convention — not worth the dependency surface.\n\n**Verification:** `cargo check --workspace --all-targets`, `cargo +nightly-2026-04-14 clippy --workspace --all-targets -- -D warnings`, `cargo +nightly-2026-04-14 fmt --check --all`, `cargo nextest run -p fabro-types -p fabro-workflow -p fabro-store -p fabro-api -p fabro-agent` (2250+464 tests), `bun test stage-insights-sidebar` (10/10), and `bun run typecheck` all pass. The 14 unrelated `run-actions.test.ts` failures pre-exist on the parent commit.", + "last_stage": "simplify_opus", + "last_response": "## Summary\n\nAggregated three review agents' findings and applied the consensus high-value fixes:\n\n**Quality / reuse fixes:**\n- `tool_permissions::known_tool_category` now returns `Option. Could the category mapping be done once in `fabro-types` or directly in tool_permissions instead of double-mapping (str -> Option -> enum)?\n\n2. `agent_tool_source` parses MCP qualified names using `fabro_mcp::connection_manager::parse_qualified_name`. Is there an existing place where a `(ToolSource, name) -> AgentToolSource` mapping should live (e.g., shared between agent + workflow)?\n\n3. The MCP server name extraction from tool name uses `parse_qualified_name`, but `lib/crates/fabro-store/src/run_state.rs` has its own `mcp_server_from_tool_name` doing similar work. Are these duplicates?\n\n4. `AgentToolCategory` derives strum::Display/EnumString/IntoStaticStr. Was `tool_permissions::known_tool_category` returning `&'static str` (which is then string-matched into the enum) the right thing, or should it return `Option` directly to avoid stringly-typed plumbing? Note that `tool_permissions.rs` is in `fabro-agent` and `AgentToolCategory` is in `fabro-types`. Look at `fabro-agent`'s dependencies on `fabro-types`.\n\n5. Look at `agent_tool_summaries_from_definitions` - is there an idiomatic place this should live (e.g. a method on `Session` or on `ToolDefinitionWithSource`)?\n\n6. `ToolAvailableIcon` is a custom React component. Is there an existing icon component already used for \"available but not invoked\" states elsewhere in the app?\n\n7. The new `effective_tools()` helper on Session de-duplicates two call sites. Good. But check if there are other call sites still computing the same thing manually.\n\nReport findings concisely with file:line references and a recommendation per finding. Skip false positives. Do not make any changes.", + "status": { + "kind": "completed", + "success": true, + "turns_used": 73 + } + }, + { + "agent_id": "12b365ea", + "depth": 1, + "task": "You are doing a CODE QUALITY review on a Rust + TypeScript change.\n\nThe change adds a new `StageProjection.agent_tools` field, a new durable event `agent.tools.available`, and a UI section to show tools. Full diff is at /tmp/review_diff.patch (1696 lines). Read it first.\n\nWorking directory: /home/daytona/workspace/fabro\n\nFocus on hacky patterns:\n\n1. **Stringly-typed plumbing**: `tool_permissions::known_tool_category` returns `Option<&'static str>` and then `agent_tool_category` (in `lib/crates/fabro-workflow/src/handler/llm/api.rs`) matches on those strings to convert to `AgentToolCategory`. This is two layers of string mapping when an enum would do. Look at fabro-agent's Cargo.toml — does it already depend on fabro-types? If yes, `known_tool_category` should return `Option` directly.\n\n2. **Redundant state**: `agent_tools: Vec` in StageProjection where `invoked` is mutated during replay. Is the `invoked` bool a derived state that could come from something already projected? Probably fine but check.\n\n3. **Parameter sprawl**: `emit_agent_tools_available` takes 4 params. Check the new functions in handler/llm/api.rs — are any of these parameters easily grouped into an existing struct (e.g., a context already in scope)?\n\n4. **Copy-paste**: The emit call appears twice in `lib/crates/fabro-workflow/src/handler/llm/api.rs` (in two `CodergenBackend::run` paths). Check if these are truly the same logic or have variations.\n\n5. **Leaky abstractions**: `agent_tool_source` calls `fabro_mcp::connection_manager::parse_qualified_name` directly from workflow code to derive `original_name`. Should this derivation live elsewhere (e.g., in `ToolSource::Mcp` carrying the original_name, or in fabro-agent's mcp integration that already knows the original name)?\n\n6. **The category match is brittle**: `match tool_permissions::known_tool_category(name) { Some(\"read\") => ..., ... Some(_) | None => Other }`. If a new category is added to `tool_permissions`, the workflow code silently maps it to `Other`. This is fragile.\n\n7. **AgentToolSource::Mcp original_name** — this is derived by parsing the qualified name. Could it be wrong/empty? The MCP path that generates qualified names is the authority — should original_name come from there directly?\n\n8. **`ToolAvailableIcon` in `stage-insights-sidebar.tsx`**: hand-rolled span with a border class. Is there a more idiomatic existing pattern (e.g., a proper Heroicon)?\n\n9. **Permission_level fallback**: The diff comments say \"Permission remains secondary compatibility metadata, not the source of the tool list.\" Check that the sidebar UI properly handles the legacy fallback case (no agent_tools) — does old permission-derived rendering still work?\n\n10. **Test redundancy**: Are the new tests duplicating coverage that other tests already provide?\n\nReport findings concisely with file:line references and concrete recommendations. Skip false positives. Do not make any changes.", + "status": { + "kind": "completed", + "success": true, + "turns_used": 58 + } + }, + { + "agent_id": "446d0aa8", + "depth": 1, + "task": "You are doing an EFFICIENCY review on a Rust + TypeScript change.\n\nThe change adds a new `StageProjection.agent_tools` field, a new durable event `agent.tools.available`, and a UI section to show tools. Full diff is at /tmp/review_diff.patch (1696 lines). Read it first.\n\nWorking directory: /home/daytona/workspace/fabro\n\nFocus on:\n\n1. **Hot-path bloat**: `emit_agent_tools_available` is called inside the per-stage processing path in `lib/crates/fabro-workflow/src/handler/llm/api.rs`. The work involves cloning all tool definitions (incl. full description strings). Could this be called once per session rather than once per process_input? Look at the call sites — the diff shows it's called before each `session.process_input_with_runtime`. Is the effective tool list constant for the session, or could it change between turns?\n\n2. **Repeated cloning**: `Session::available_tools()` clones the full `Vec` each call. Then `agent_tool_summaries_from_definitions` clones every field again into AgentToolSummary. Could the conversion take owned values or borrow?\n\n3. **N+1 / repeated work**: `definitions_with_source_for_policy` is now called twice per turn — once for the model request and once for emit. Look at how often `effective_tools()` is called per session input.\n\n4. **Memory**: `StageProjection.agent_tools` is a per-stage Vec carrying full descriptions. If a stage has 30 tools each with ~200 char descriptions, that's a few KB per stage in the projection. The projection is in-memory and serialized to clients. Is this bounded/reasonable?\n\n5. **Sorting**: `agent_tool_summaries_from_definitions` does `summaries.sort_by(|left, right| left.name.cmp(&right.name))`. Reasonable for stability but adds O(n log n) per turn. Compare to whether the registry order is already deterministic.\n\n6. **invoked replay**: `lib/crates/fabro-store/src/run_state.rs` ~line 612: for every `AgentToolStarted` event, the code iterates `stage.agent_tools` linearly to find the match. For long-running stages with many tool calls (hundreds), this is O(tools * calls). Is the tools list small enough that this is fine?\n\n7. **React render**: `AgentToolsSection` iterates tools; check if anything obvious like `useMemo` is missing where it would materially help, but don't add unnecessary memoization.\n\n8. **Tool description size**: descriptions can be long (tool prompts often 500+ chars). Multiply by tools count and that's the projection size impact. Note R4 says no parameter schemas, but descriptions are explicit. Just flag the size concern; this was an explicit design decision.\n\nReport findings concisely with file:line references and concrete recommendations. Skip false positives. Do not make any changes.", + "status": { + "kind": "completed", + "success": true, + "turns_used": 69 + } + } + ], + "permission_level": "full", + "context_window": { + "provider": "anthropic", + "model": "claude-opus-4-7", + "context_window_tokens": 1000000, + "input_tokens": 126197, + "usage_percent": 12.6197, + "count_method": "response_usage_scaled_breakdown", + "staleness": "live", + "generated_at": "2026-05-24T17:57:18.880486Z", + "event_seq": 2276, + "breakdown": [ + { + "category": "system_prompt", + "tokens": 2354, + "usage_percent": 0.2354 + }, + { + "category": "tools", + "tokens": 2699, + "usage_percent": 0.2699 + }, + { + "category": "memory", + "tokens": 5639, + "usage_percent": 0.5639 + }, + { + "category": "conversation", + "tokens": 115498, + "usage_percent": 11.5498 + }, + { + "category": "other", + "tokens": 7, + "usage_percent": 0.0007 + } + ], + "warnings": [] + }, + "state": "running" + }, "implement@1": { "first_event_seq": 52, "prompt": null, "response": null, - "completion": null, + "completion": { + "outcome": "succeeded", + "notes": "Stage completed: implement", + "failure_reason": null, + "timestamp": "2026-05-24T17:40:34.044793Z" + }, "provider_used": { "mode": "agent", "provider": "openai", @@ -937,13 +1258,20 @@ "output": null, "started_at": "2026-05-24T17:17:39.928850Z", "handler": "agent", + "timing": { + "wall_time_ms": 1374106, + "inference_time_ms": 0, + "tool_time_ms": 0, + "active_time_ms": 0 + }, "usage": { "input_tokens": 6711598, "output_tokens": 22676, "total_tokens": 22852804, "reasoning_tokens": 11522, "cache_read_tokens": 16107008, - "cache_write_tokens": 0 + "cache_write_tokens": 0, + "total_usd_micros": 42637434 }, "model": { "provider": "openai", @@ -1031,7 +1359,7 @@ ], "warnings": [] }, - "state": "running" + "state": "succeeded" }, "start@1": { "first_event_seq": 18, diff --git a/stages/005-implement@1/diff.patch b/stages/005-implement@1/diff.patch new file mode 100644 index 000000000..32b086008 --- /dev/null +++ b/stages/005-implement@1/diff.patch @@ -0,0 +1,1696 @@ +diff --git a/apps/fabro-web/app/components/stage-insights-sidebar.test.tsx b/apps/fabro-web/app/components/stage-insights-sidebar.test.tsx +index c505a9ffd..713f1b4bc 100644 +--- a/apps/fabro-web/app/components/stage-insights-sidebar.test.tsx ++++ b/apps/fabro-web/app/components/stage-insights-sidebar.test.tsx +@@ -3,6 +3,7 @@ import TestRenderer, { act } from "react-test-renderer"; + import { MemoryRouter } from "react-router"; + + import { ++ AgentToolCategory, + AgentSkillActivationSource, + PermissionLevel, + StageContextWindowCategory, +@@ -66,7 +67,7 @@ function makeContextWindow(overrides: Partial = {}): StageCo + let restoreWindow: (() => void) | null = null; + beforeAll(() => { + const store = new Map(); +- for (const key of ["todos", "context", "skills", "mcps"]) { ++ for (const key of ["todos", "context", "tools", "skills", "mcps"]) { + store.set(`fabro:stage-insights-section:${key}`, "1"); + } + const stub = { +@@ -157,6 +158,50 @@ describe("StageInsightsSidebar", () => { + expect(dom).toContain("Full access"); + }); + ++ test("renders projected agent tool names, descriptions, categories, and invoked state", () => { ++ const dom = render( ++ makeStage({ ++ agent_tools: [ ++ { ++ name: "apply_patch", ++ description: "Apply a unified diff patch", ++ source: { kind: "native" }, ++ category: AgentToolCategory.WRITE, ++ invoked: true, ++ }, ++ { ++ name: "grep", ++ description: "Search file contents", ++ source: { kind: "native" }, ++ category: AgentToolCategory.READ, ++ invoked: false, ++ }, ++ ], ++ permission_level: PermissionLevel.FULL, ++ }), ++ null, ++ ); ++ ++ expect(dom).toContain("1/2"); ++ expect(dom).toContain("apply_patch"); ++ expect(dom).toContain("Apply a unified diff patch"); ++ expect(dom).toContain("write"); ++ expect(dom).toContain("used"); ++ expect(dom).toContain("grep"); ++ expect(dom).toContain("Search file contents"); ++ expect(dom).toContain("read"); ++ expect(dom).toContain("available"); ++ // Permission remains secondary compatibility metadata, not the source of ++ // the tool list. ++ expect(dom).toContain("Full access"); ++ }); ++ ++ test("legacy stages without agent tools keep permission fallback only", () => { ++ const dom = render(makeStage({ permission_level: PermissionLevel.READ_WRITE }), null); ++ expect(dom).toContain("Read/write"); ++ expect(dom).not.toContain("apply_patch"); ++ }); ++ + test("renders mcp server used/total count, marks invoked servers as 'used'", () => { + const dom = render( + makeStage({ +diff --git a/apps/fabro-web/app/components/stage-insights-sidebar.tsx b/apps/fabro-web/app/components/stage-insights-sidebar.tsx +index 71ffa5094..135f1dd72 100644 +--- a/apps/fabro-web/app/components/stage-insights-sidebar.tsx ++++ b/apps/fabro-web/app/components/stage-insights-sidebar.tsx +@@ -19,6 +19,7 @@ import { + PuzzlePieceIcon, + ServerStackIcon, + Squares2X2Icon, ++ WrenchScrewdriverIcon, + } from "@heroicons/react/24/outline"; + import { + AgentSkillActivationSource, +@@ -30,6 +31,7 @@ import { + import type { + ActivatedSkill, + AgentSkillSummary, ++ AgentToolSummary, + McpServerProjection, + StageContextWindow, + StageContextWindowBreakdownItem, +@@ -42,11 +44,12 @@ import { formatTokenCount } from "../lib/format"; + const COLLAPSED_STORAGE_KEY = "fabro:stage-insights-sidebar-collapsed"; + const SECTION_STORAGE_PREFIX = "fabro:stage-insights-section:"; + +-type SectionKey = "todos" | "context" | "skills" | "mcps"; ++type SectionKey = "todos" | "context" | "tools" | "skills" | "mcps"; + + const SECTIONS_DEFAULT_OPEN: Record = { + todos: true, + context: false, ++ tools: false, + skills: false, + mcps: false, + }; +@@ -70,11 +73,13 @@ export function StageInsightsSidebar({ stage, contextWindow }: StageInsightsSide + + const todos = stage?.todos ?? null; + const skills = stage?.skills ?? { activated: [], available: [] }; ++ const agentTools = stage?.agent_tools ?? []; + const mcpServers = stage?.mcp_servers ?? []; + const permission = stage?.permission_level ?? null; + + const todoStats = countTodoStats(todos); + const activatedSkillNames = new Set(skills.activated.map((s) => s.name)); ++ const invokedToolCount = agentTools.filter((tool) => tool.invoked).length; + + return ( +