graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat: fx-style overflow handles, named prefix caps, extra roots (#574)
Rach9eca9eff07ab
diff --git a/docs/adr/0012-overflow-handles-named-limits-extra-roots.md b/docs/adr/0012-overflow-handles-named-limits-extra-roots.mdnew file mode 100644index 00000000..4b78f040--- /dev/null+++ b/docs/adr/0012-overflow-handles-named-limits-extra-roots.md@@ -0,0 +1,38 @@+# 0012. Overflow handles, named prefix caps, and extra roots++Status: accepted 2026-08-19++## Context++fx (vercel-labs) keeps a fat tool result out of history with+`read_tool_result`, caps named prefix slices (`skill_catalog_bytes`, MCP+schema, AGENTS.md), searches MCP then selects, and adds extra workspace+roots with `--add-dir` (max 16) that do not contribute skills or sessions.++graff already spilled oversized results (#440) and folded MCP behind+`load_tool_schemas`. The missing pieces were a first-class pager for the+spill, discrete byte knobs instead of ad-hoc `desc_cap`, search-without-+load, and extra roots that are not a `workspace` cwd switch.++## Decision++- A result over the handle threshold is stored as `.graff/tool-results/tr_N.txt`.+ The model pages it with `read_tool_result` (`offset`/`limit` or `query`).+ The full blob does not re-enter history.+- `--context-limit name=N` (and `GRAFF_CONTEXT_LIMIT`) caps+ `skill_catalog_bytes`, `mcp_schema_bytes`, and `agents_md_bytes`. `apply`+ never grows. Defaults 4 KiB / 8 KiB / 8 KiB.+- `mcp_search_tools` lists deferred tools and does not enable them.+ `mcp_select_tool` loads chosen names. `load_tool_schemas` stays for bulk.+- `--add-dir` (max 16) is a PathConfine allow-list for file tools.+ Extra roots never contribute skills or sessions. `workspace` still+ switches cwd.++## Consequences++- One fat bash/codedb hit costs one preview plus later slices.+- Named caps are prompt-cache-stable: shrinking a listing does not rewrite+ tool names or pin policy.+- Extra-root absolute paths become `confinedPath` when they stay under a+ registered root with no `..`. The Lean PathConfine fixtures stay the+ empty-roots jail; extra roots are the extension.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 5619f8a2..ed63b993 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -22,6 +22,7 @@ record only when you need the evidence or the edge cases.| [0009](0009-gpt-5-6-explicit-prompt-cache-boundary.md) | GPT-5.6 OpenAI Platform marks the stable prefix explicitly; Codex and xAI stay on their supported keyed automatic-cache paths. || [0010](0010-background-jobs-wait-for-exit.md) | `bash_output`/`agent_output` `wait_ms>0` blocks until exit (10h cap); do not poll every 30s. || [0011](0011-prompt-cache-max-is-visible.md) | Prompt-cache max is `/cache` posture, not a new default; `/btw` rides the parent prefix. |+| [0012](0012-overflow-handles-named-limits-extra-roots.md) | Fat tool results become `tr_N` handles; named `--context-limit` caps prefix bytes; `--add-dir` extra roots are PathConfine allow-lists, not cwd/skill/session sources. |## When to write onediff --git a/lean-proofs/Graff/ToolCatalog.lean b/lean-proofs/Graff/ToolCatalog.leanindex b053e943..f2050517 100644--- a/lean-proofs/Graff/ToolCatalog.lean+++ b/lean-proofs/Graff/ToolCatalog.lean@@ -23,22 +23,24 @@ deriving Repr, BEqdef localTools : List String :=["bash", "bash_output", "bash_kill", "read_file", "edit_file",- "write_file", "codedb", "imagegen"]+ "write_file", "codedb", "read_tool_result", "imagegen"]def leanTools : List String :=["bash", "read_file", "edit_file", "write_file", "codedb",- "subagent", "attempt_completion", "load_tool_schemas"]+ "read_tool_result", "subagent", "attempt_completion",+ "load_tool_schemas"]def optionalTools : List String :=["imagegen"]def baseTools : List String :=["bash", "bash_output", "bash_kill", "read_file", "edit_file",- "write_file", "webfetch", "skill", "codedb"]+ "write_file", "webfetch", "skill", "codedb", "read_tool_result"]def metaTools : List String :=["todo_write", "todo_read", "eval", "note_constraint", "ask_user",- "attempt_completion", "load_tool_schemas", "clock_sleep"]+ "attempt_completion", "load_tool_schemas", "mcp_search_tools",+ "mcp_select_tool", "clock_sleep"]def rootExtras : List String :=["subagent", "workflow", "agent_output", "learn_candidate", "peer_message",@@ -132,7 +134,8 @@ example : unique (baseTools ++ metaTools ++ rootExtras) = true := by native_deciexample : catalog {} =(baseTools ++["todo_write", "todo_read", "eval", "note_constraint", "ask_user",- "attempt_completion", "load_tool_schemas"] +++ "attempt_completion", "load_tool_schemas", "mcp_search_tools",+ "mcp_select_tool"] ++["subagent", "workflow", "agent_output", "peer_message", "workspace"]) := by native_decideexample : catalog { imagegen := true } =diff --git a/sdk/py/harness_sdk.py b/sdk/py/harness_sdk.pyindex 967e3689..8dc5d12e 100644--- a/sdk/py/harness_sdk.py+++ b/sdk/py/harness_sdk.py@@ -14,7 +14,7 @@ import urllib.requestfrom typing import Iterator, OptionalMODELS = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "openai/gpt-oss-120b"]-TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"]+TOOLS = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"]PROVIDERS = ["anthropic", "codegraff", "deepseek", "openai", "minimax", "xiaomi", "kilo", "groq", "mistral", "kimi", "moonshot", "xai", "zai", "fugu", "fireworks", "mlx", "lmstudio", "codex"]diff --git a/sdk/ts/harness.ts b/sdk/ts/harness.tsindex c1d9e0b3..850d99dc 100644--- a/sdk/ts/harness.ts+++ b/sdk/ts/harness.ts@@ -12,7 +12,7 @@ import type { Readable, Writable } from "node:stream";export const HARNESS_VERSION = "0.12";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-opus-5" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "claude-sonnet-5" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-4.6" | "grok-build" | "k3" | "kilo-auto/small" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mistral-medium-latest" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | "openai/gpt-oss-120b" | (string & {});-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kilo" | "groq" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by `harness --json` (one JSON object per stdout line), each@@ -661,4 +661,4 @@ export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<Event> {}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "openai/gpt-oss-120b"];-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];diff --git a/sdk/ts/remote.ts b/sdk/ts/remote.tsindex 2e1a29f0..1d42fe3a 100644--- a/sdk/ts/remote.ts+++ b/sdk/ts/remote.ts@@ -10,7 +10,7 @@export const HARNESS_VERSION = "0.12";export type ModelName = "MiniMax-M2.5" | "MiniMax-M2.7" | "MiniMax-M3" | "accounts/fireworks/models/deepseek-v4-flash" | "accounts/fireworks/models/deepseek-v4-pro" | "accounts/fireworks/models/glm-5p2" | "accounts/fireworks/models/gpt-oss-120b" | "accounts/fireworks/models/kimi-k2p6" | "accounts/fireworks/models/kimi-k2p7-code" | "accounts/fireworks/models/minimax-m3" | "accounts/fireworks/models/qwen3p7-plus" | "claude-fable-5" | "claude-haiku-4-5" | "claude-opus-4-5" | "claude-opus-4-6" | "claude-opus-4-7" | "claude-opus-4-8" | "claude-opus-4.8" | "claude-opus-5" | "claude-sonnet-4-5" | "claude-sonnet-4-6" | "claude-sonnet-4.6" | "claude-sonnet-5" | "deepseek-chat" | "deepseek-reasoner" | "deepseek-v4-flash" | "deepseek-v4-pro" | "fugu" | "fugu-ultra" | "fugu-ultra-20260615" | "glm-4.5" | "glm-4.7" | "glm-5" | "glm-5.2" | "gpt-5-codex" | "gpt-5.2" | "gpt-5.3-codex-spark" | "gpt-5.4" | "gpt-5.4-mini" | "gpt-5.4-pro" | "gpt-5.5" | "gpt-5.6" | "gpt-5.6-luna" | "gpt-5.6-sol" | "gpt-5.6-terra" | "grok-4.3" | "grok-4.6" | "grok-build" | "k3" | "kilo-auto/small" | "kimi-for-coding" | "kimi-for-coding-highspeed" | "kimi-k2.6" | "kimi-latest" | "lmstudio" | "mimo-v2-flash" | "mimo-v2.5" | "mimo-v2.5-pro" | "mimo-v2.5-pro-ultraspeed" | "minimax-m3" | "mistral-medium-latest" | "mlx-community/Qwen3.6-27B-OptiQ-4bit" | "openai/gpt-oss-120b" | (string & {});-export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";+export type ToolName = "bash" | "bash_output" | "bash_kill" | "read_file" | "edit_file" | "write_file" | "webfetch" | "skill" | "codedb" | "read_tool_result" | "todo_write" | "todo_read" | "eval" | "note_constraint" | "ask_user" | "attempt_completion" | "load_tool_schemas" | "mcp_search_tools" | "mcp_select_tool" | "clock_sleep" | "subagent" | "workflow" | "agent_output" | "learn_candidate" | "peer_message" | "workspace" | "imagegen";export type ProviderId = "anthropic" | "codegraff" | "deepseek" | "openai" | "minimax" | "xiaomi" | "kilo" | "groq" | "mistral" | "kimi" | "moonshot" | "xai" | "zai" | "fugu" | "fireworks" | "mlx" | "lmstudio" | "codex";/** Events streamed by the bridge (same `--json` contract as the stdio SDK).@@ -508,4 +508,4 @@ export async function* runAgentRemote(opts: RunAgentRemoteOptions): AsyncGenerat}export const MODELS: ModelName[] = ["MiniMax-M2.5", "MiniMax-M2.7", "MiniMax-M3", "accounts/fireworks/models/deepseek-v4-flash", "accounts/fireworks/models/deepseek-v4-pro", "accounts/fireworks/models/glm-5p2", "accounts/fireworks/models/gpt-oss-120b", "accounts/fireworks/models/kimi-k2p6", "accounts/fireworks/models/kimi-k2p7-code", "accounts/fireworks/models/minimax-m3", "accounts/fireworks/models/qwen3p7-plus", "claude-fable-5", "claude-haiku-4-5", "claude-opus-4-5", "claude-opus-4-6", "claude-opus-4-7", "claude-opus-4-8", "claude-opus-4.8", "claude-opus-5", "claude-sonnet-4-5", "claude-sonnet-4-6", "claude-sonnet-4.6", "claude-sonnet-5", "deepseek-chat", "deepseek-reasoner", "deepseek-v4-flash", "deepseek-v4-pro", "fugu", "fugu-ultra", "fugu-ultra-20260615", "glm-4.5", "glm-4.7", "glm-5", "glm-5.2", "gpt-5-codex", "gpt-5.2", "gpt-5.3-codex-spark", "gpt-5.4", "gpt-5.4-mini", "gpt-5.4-pro", "gpt-5.5", "gpt-5.6", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "grok-4.3", "grok-4.6", "grok-build", "k3", "kilo-auto/small", "kimi-for-coding", "kimi-for-coding-highspeed", "kimi-k2.6", "kimi-latest", "lmstudio", "mimo-v2-flash", "mimo-v2.5", "mimo-v2.5-pro", "mimo-v2.5-pro-ultraspeed", "minimax-m3", "mistral-medium-latest", "mlx-community/Qwen3.6-27B-OptiQ-4bit", "openai/gpt-oss-120b"];-export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];+export const TOOLS: ToolName[] = ["bash", "bash_output", "bash_kill", "read_file", "edit_file", "write_file", "webfetch", "skill", "codedb", "read_tool_result", "todo_write", "todo_read", "eval", "note_constraint", "ask_user", "attempt_completion", "load_tool_schemas", "mcp_search_tools", "mcp_select_tool", "clock_sleep", "subagent", "workflow", "agent_output", "learn_candidate", "peer_message", "workspace", "imagegen"];diff --git a/spec/kernels/tool_catalog.json b/spec/kernels/tool_catalog.jsonindex 68cd8d87..999b11e6 100644--- a/spec/kernels/tool_catalog.json+++ b/spec/kernels/tool_catalog.json@@ -11,7 +11,8 @@"write_file","webfetch","skill",- "codedb"+ "codedb",+ "read_tool_result"],"meta": ["todo_write",@@ -21,6 +22,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","clock_sleep"],"root_extras": [@@ -42,6 +45,7 @@"edit_file","write_file","codedb",+ "read_tool_result","imagegen"],"lean": [@@ -50,6 +54,7 @@"edit_file","write_file","codedb",+ "read_tool_result","subagent","attempt_completion","load_tool_schemas"@@ -76,6 +81,7 @@"webfetch","skill","codedb",+ "read_tool_result","todo_write","todo_read","eval",@@ -83,6 +89,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","subagent","workflow","agent_output",@@ -112,7 +120,8 @@"write_file","webfetch","skill",- "codedb"+ "codedb",+ "read_tool_result"],"blocked": ["imagegen"@@ -138,6 +147,7 @@"webfetch","skill","codedb",+ "read_tool_result","todo_write","todo_read","eval",@@ -145,6 +155,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","subagent","workflow","agent_output",@@ -175,7 +187,8 @@"write_file","webfetch","skill",- "codedb"+ "codedb",+ "read_tool_result"],"blocked": ["imagegen"@@ -201,6 +214,7 @@"webfetch","skill","codedb",+ "read_tool_result","todo_write","todo_read","eval",@@ -208,6 +222,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","clock_sleep","subagent","workflow",@@ -238,7 +254,8 @@"write_file","webfetch","skill",- "codedb"+ "codedb",+ "read_tool_result"],"blocked": ["imagegen"@@ -264,6 +281,7 @@"webfetch","skill","codedb",+ "read_tool_result","todo_write","todo_read","eval",@@ -271,6 +289,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","clock_sleep","subagent","workflow",@@ -302,7 +322,8 @@"write_file","webfetch","skill",- "codedb"+ "codedb",+ "read_tool_result"],"blocked": ["imagegen"@@ -328,6 +349,7 @@"webfetch","skill","codedb",+ "read_tool_result","todo_write","todo_read","eval",@@ -335,6 +357,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","subagent","workflow","agent_output",@@ -364,6 +388,7 @@"webfetch","skill","codedb",+ "read_tool_result","imagegen"],"blocked": []@@ -388,6 +413,7 @@"webfetch","skill","codedb",+ "read_tool_result","todo_write","todo_read","eval",@@ -395,6 +421,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","subagent","workflow","agent_output",@@ -425,6 +453,7 @@"webfetch","skill","codedb",+ "read_tool_result","imagegen"],"blocked": []@@ -449,6 +478,7 @@"webfetch","skill","codedb",+ "read_tool_result","todo_write","todo_read","eval",@@ -456,6 +486,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","clock_sleep","subagent","workflow",@@ -486,6 +518,7 @@"webfetch","skill","codedb",+ "read_tool_result","imagegen"],"blocked": []@@ -510,6 +543,7 @@"webfetch","skill","codedb",+ "read_tool_result","todo_write","todo_read","eval",@@ -517,6 +551,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","clock_sleep","subagent","workflow",@@ -548,6 +584,7 @@"webfetch","skill","codedb",+ "read_tool_result","imagegen"],"blocked": []@@ -568,6 +605,7 @@"edit_file","write_file","codedb",+ "read_tool_result","attempt_completion","load_tool_schemas","subagent"@@ -595,7 +633,8 @@"write_file","webfetch","skill",- "codedb"+ "codedb",+ "read_tool_result"],"blocked": ["imagegen"@@ -617,6 +656,7 @@"edit_file","write_file","codedb",+ "read_tool_result","attempt_completion","load_tool_schemas","subagent"@@ -644,7 +684,8 @@"write_file","webfetch","skill",- "codedb"+ "codedb",+ "read_tool_result"],"blocked": ["imagegen"@@ -666,6 +707,7 @@"edit_file","write_file","codedb",+ "read_tool_result","attempt_completion","load_tool_schemas","subagent"@@ -693,7 +735,8 @@"write_file","webfetch","skill",- "codedb"+ "codedb",+ "read_tool_result"],"blocked": ["imagegen"@@ -715,6 +758,7 @@"edit_file","write_file","codedb",+ "read_tool_result","attempt_completion","load_tool_schemas","subagent"@@ -742,7 +786,8 @@"write_file","webfetch","skill",- "codedb"+ "codedb",+ "read_tool_result"],"blocked": ["imagegen"@@ -764,6 +809,7 @@"edit_file","write_file","codedb",+ "read_tool_result","attempt_completion","load_tool_schemas","subagent"@@ -790,6 +836,7 @@"webfetch","skill","codedb",+ "read_tool_result","imagegen"],"blocked": []@@ -810,6 +857,7 @@"edit_file","write_file","codedb",+ "read_tool_result","attempt_completion","load_tool_schemas","subagent"@@ -836,6 +884,7 @@"webfetch","skill","codedb",+ "read_tool_result","imagegen"],"blocked": []@@ -856,6 +905,7 @@"edit_file","write_file","codedb",+ "read_tool_result","attempt_completion","load_tool_schemas","subagent"@@ -882,6 +932,7 @@"webfetch","skill","codedb",+ "read_tool_result","imagegen"],"blocked": []@@ -902,6 +953,7 @@"edit_file","write_file","codedb",+ "read_tool_result","attempt_completion","load_tool_schemas","subagent"@@ -928,6 +980,7 @@"webfetch","skill","codedb",+ "read_tool_result","imagegen"],"blocked": []@@ -952,6 +1005,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","subagent","workflow","agent_output",@@ -966,6 +1021,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -991,6 +1047,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1014,6 +1071,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","subagent","workflow","agent_output",@@ -1029,6 +1088,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1054,6 +1114,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1077,6 +1138,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","clock_sleep","subagent","workflow",@@ -1092,6 +1155,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1117,6 +1181,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1140,6 +1205,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","clock_sleep","subagent","workflow",@@ -1156,6 +1223,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1181,6 +1249,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1204,6 +1273,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","subagent","workflow","agent_output",@@ -1218,6 +1289,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1243,6 +1315,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1266,6 +1339,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","subagent","workflow","agent_output",@@ -1281,6 +1356,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1306,6 +1382,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1329,6 +1406,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","clock_sleep","subagent","workflow",@@ -1344,6 +1423,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1369,6 +1449,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1392,6 +1473,8 @@"ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","clock_sleep","subagent","workflow",@@ -1408,6 +1491,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1433,6 +1517,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1459,6 +1544,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1484,6 +1570,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1510,6 +1597,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1535,6 +1623,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1561,6 +1650,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1586,6 +1676,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1612,6 +1703,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1637,6 +1729,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1663,6 +1756,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1688,6 +1782,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1714,6 +1809,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1739,6 +1835,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1765,6 +1862,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1790,6 +1888,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1816,6 +1915,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]},@@ -1841,6 +1941,7 @@"edit_file","imagegen","read_file",+ "read_tool_result","write_file"]}diff --git a/spec/kernels/tool_catalog.md b/spec/kernels/tool_catalog.mdindex a45edad8..bff02465 100644--- a/spec/kernels/tool_catalog.md+++ b/spec/kernels/tool_catalog.md@@ -11,7 +11,7 @@ always in this order:two compile-time optional rows).2. **Add** every `#352` optional whose flag is on (`imagegen` today).3. **Subtract** `#330` `--no-local-tools` (host-touching built-ins).-4. **Keep** `--lean` (eight one-shot tools). Description compaction does+4. **Keep** `--lean` (nine one-shot tools). Description compaction doesnot change names.A subagent starts from `base_specs` only (no meta, no `subagent`), then@@ -22,12 +22,12 @@ run the keep-list.| Set | Names ||---|---|-| base | `bash` `bash_output` `bash_kill` `read_file` `edit_file` `write_file` `webfetch` `skill` `codedb` |-| meta (root) | `todo_write` `todo_read` `eval` `note_constraint` `ask_user` `attempt_completion` `load_tool_schemas` `clock_sleep` |+| base | `bash` `bash_output` `bash_kill` `read_file` `edit_file` `write_file` `webfetch` `skill` `codedb` `read_tool_result` |+| meta (root) | `todo_write` `todo_read` `eval` `note_constraint` `ask_user` `attempt_completion` `load_tool_schemas` `mcp_search_tools` `mcp_select_tool` `clock_sleep` || root extras | `subagent` `workflow` `agent_output` `learn_candidate` `peer_message` `workspace` || optional | `imagegen` |-| local (`#330`) | `bash` `bash_output` `bash_kill` `read_file` `edit_file` `write_file` `codedb` `imagegen` |-| lean keep | `bash` `read_file` `edit_file` `write_file` `codedb` `subagent` `attempt_completion` `load_tool_schemas` |+| local (`#330`) | `bash` `bash_output` `bash_kill` `read_file` `edit_file` `write_file` `codedb` `read_tool_result` `imagegen` |+| lean keep | `bash` `read_file` `edit_file` `write_file` `codedb` `read_tool_result` `subagent` `attempt_completion` `load_tool_schemas` |`webfetch`, every meta tool except the lean keepers, and every `mcp__*`name are **not** local. MCP is outside this kernel.diff --git a/spec/ref/tool_catalog.py b/spec/ref/tool_catalog.pyindex 44ff887e..2822004e 100644--- a/spec/ref/tool_catalog.py+++ b/spec/ref/tool_catalog.py@@ -18,6 +18,7 @@ LOCAL_TOOLS = ("edit_file","write_file","codedb",+ "read_tool_result","imagegen",)LEAN_TOOLS = (@@ -26,6 +27,7 @@ LEAN_TOOLS = ("edit_file","write_file","codedb",+ "read_tool_result","subagent","attempt_completion","load_tool_schemas",@@ -41,6 +43,7 @@ BASE_TOOLS = ("webfetch","skill","codedb",+ "read_tool_result",)META_TOOLS = ("todo_write",@@ -50,6 +53,8 @@ META_TOOLS = ("ask_user","attempt_completion","load_tool_schemas",+ "mcp_search_tools",+ "mcp_select_tool","clock_sleep",)ROOT_EXTRAS = (diff --git a/src/agent_tools.zig b/src/agent_tools.zigindex db727471..860f6ac9 100644--- a/src/agent_tools.zig+++ b/src/agent_tools.zig@@ -366,7 +366,7 @@ pub fn handleMeta(self: *Agent, call: ToolCall) !ExecResult {return .{ .text = try clockSleepSuccessText(self.arena, parsed.ms, parsed.clamped), .is_error = false };}if (std.mem.eql(u8, call.name, "note_constraint")) return playbook_glue.noteConstraint(self, call.input); // #381: append-only, and it re-composes the root's own prompt- if (std.mem.eql(u8, call.name, mcp_schema_gate.tool_name)) return (native_fold.handleLoadNative(self, call.input) catch null) orelse mcp_schema_gate.handleLoad(self, call.input); // #416: inline, one writer — folded natives answered first+ if (std.mem.eql(u8, call.name, mcp_schema_gate.tool_name) or @import("mcp_select.zig").isName(call.name)) return (native_fold.handleLoadNative(self, call.input) catch null) orelse @import("mcp_select.zig").dispatch(self, call);if (std.mem.eql(u8, call.name, "ask_user")) return self.askUser(call);// todo_readreturn .{ .text = self.renderTodos(goal_state.currentEpoch(self.goal)), .is_error = false };diff --git a/src/args.zig b/src/args.zigindex 883d97de..4fbab5b2 100644--- a/src/args.zig+++ b/src/args.zig@@ -25,6 +25,7 @@ const Allocator = std.mem.Allocator;const main_mod = @import("main.zig");const learning_privacy = @import("learning_privacy.zig");const no_local_tools = @import("no_local_tools.zig"); // #330: `--no-local-tools` arms the process-global gate (same set-only pattern as the main_mod globals)+const context_limits = @import("context_limits.zig");/// Every CLI-flag local main() used to declare, plus the resolved/// positionals/subcommand-detection/one-shot-prompt outputs computed right@@ -63,6 +64,8 @@ pub const Flags = struct {goal_flag: ?[]const u8 = null, // --goal: standing objective (todos) every turn gets, incl. --json/-peval_cmd_flag: ?[]const u8 = null, // --eval: scoring command for the eval-driven loopworktree_flag: ?[]const u8 = null, // --worktree/-w: isolate this session in a git worktree (parallel agents, no file collisions)+ add_dirs: std.ArrayList([]const u8) = .empty, // --add-dir: extra file-tool roots, max 16+ context_limits: std.ArrayList([]const u8) = .empty, // --context-limit name=Neval_target_flag: ?u8 = null, // --until: target score 0-100 for the eval loopeval_niche_flag: ?[]const u8 = null, // --niche: fleet niche this eval-driven session optimizes (tags submitted scores)output_schema_flag: ?[]const u8 = null, // --output-schema: JSON schema (inline or @file) the final answer must satisfy (#502)@@ -130,6 +133,13 @@ pub fn parse(init: std.process.Init) !Flags {flags.lean_flag = true;} else if (std.mem.eql(u8, arg, "--worktree") or std.mem.eql(u8, arg, "-w")) {flags.worktree_flag = it.next() orelse std.process.fatal("--worktree needs a name (e.g. --worktree agent1)", .{});+ } else if (std.mem.eql(u8, arg, "--add-dir")) {+ const dir = it.next() orelse std.process.fatal("--add-dir needs a directory (repeatable, max 16)", .{});+ flags.add_dirs.append(arena, try arena.dupe(u8, dir)) catch std.process.fatal("--add-dir: out of memory", .{});+ } else if (std.mem.eql(u8, arg, "--context-limit")) {+ const pair = it.next() orelse std.process.fatal("--context-limit needs name=N (skill_catalog_bytes|mcp_schema_bytes|agents_md_bytes)", .{});+ context_limits.applyPair(pair) catch std.process.fatal("invalid --context-limit '{s}' (want name=N)", .{pair});+ flags.context_limits.append(arena, try arena.dupe(u8, pair)) catch {};} else if (std.mem.eql(u8, arg, "--goal")) {flags.goal_flag = it.next() orelse std.process.fatal("--goal needs an objective", .{});} else if (std.mem.eql(u8, arg, "--eval")) {diff --git a/src/cli.zig b/src/cli.zigindex dd7deb08..b67fc581 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -209,9 +209,11 @@ pub const usage_text =\\ --until <0-100> eval-loop target score; stop when reached (default 90)\\ --niche <name> fleet niche this eval optimizes (reviewer/researcher/implementer/skeptic or a custom agent); tags submitted scores so the DGM can promote a champion for that role\\ -w, --worktree <name> isolate this session in a git worktree (.graff/worktrees/<name>) so parallel agents don't collide on files+ \\ --add-dir <path> extra file-tool root (repeatable, max 16). Not a cwd switch; no skills/sessions from it+ \\ --context-limit name=N cap a named prefix: skill_catalog_bytes|mcp_schema_bytes|agents_md_bytes\\ --no-autocommit with -w, don't auto-commit each turn (default on; land work with `graff worktree merge`)\\ --yolo skip all permission prompts for the session- \\ --lean slim tool surface (8 core tools) + MCP deferred behind load_tool_schemas — the DEFAULT for -p one-shots (GRAFF_LEAN=1)+ \\ --lean slim tool surface (9 core tools) + MCP deferred behind load_tool_schemas — the DEFAULT for -p one-shots (GRAFF_LEAN=1)\\ --no-lean opt a one-shot out of the implied --lean: full tool surface + eager MCP, the pre-default -p behavior\\ --no-local-tools embedder mode: hard-disable the built-in bash/bash_output/bash_kill/read_file/edit_file/write_file/codedb tools for the whole process (subagents included), so graff can run outside the sandbox and get its coding tools from an MCP server instead; webfetch, orchestration and MCP tools still work (GRAFF_NO_LOCAL_TOOLS=1)\\ -p, --print one-shot print mode (answer on stdout, progress on stderr)diff --git a/src/context_limits.zig b/src/context_limits.zignew file mode 100644index 00000000..f53d5af2--- /dev/null+++ b/src/context_limits.zig@@ -0,0 +1,111 @@+//! Named prompt-prefix byte caps. Discrete knobs so a skill catalog, MCP+//! listing, or AGENTS.md cannot eat the cached prefix. `--context-limit+//! name=N` and `GRAFF_CONTEXT_LIMIT` set them; `apply` never grows.++const std = @import("std");++const util = @import("util.zig");++pub const Name = enum {+ skill_catalog_bytes,+ mcp_schema_bytes,+ agents_md_bytes,++ pub fn parse(raw: []const u8) ?Name {+ if (std.mem.eql(u8, raw, "skill_catalog_bytes")) return .skill_catalog_bytes;+ if (std.mem.eql(u8, raw, "mcp_schema_bytes")) return .mcp_schema_bytes;+ if (std.mem.eql(u8, raw, "agents_md_bytes")) return .agents_md_bytes;+ return null;+ }+};++pub const defaults = struct {+ pub const skill_catalog_bytes: usize = 4096;+ pub const mcp_schema_bytes: usize = 8192;+ pub const agents_md_bytes: usize = 8192;+};++pub var skill_catalog_bytes: usize = defaults.skill_catalog_bytes;+pub var mcp_schema_bytes: usize = defaults.mcp_schema_bytes;+pub var agents_md_bytes: usize = defaults.agents_md_bytes;++pub fn resetForTest() void {+ skill_catalog_bytes = defaults.skill_catalog_bytes;+ mcp_schema_bytes = defaults.mcp_schema_bytes;+ agents_md_bytes = defaults.agents_md_bytes;+}++fn set(name: Name, n: usize) void {+ if (n == 0) return;+ switch (name) {+ .skill_catalog_bytes => skill_catalog_bytes = n,+ .mcp_schema_bytes => mcp_schema_bytes = n,+ .agents_md_bytes => agents_md_bytes = n,+ }+}++/// `name=N`. Unknown name or 0 is an error (a knob that silently no-ops+/// would hide a typo until the prefix blew up).+pub fn applyPair(raw: []const u8) !void {+ const eq = std.mem.indexOfScalar(u8, raw, '=') orelse return error.BadLimit;+ const name = Name.parse(std.mem.trim(u8, raw[0..eq], " \t")) orelse return error.UnknownLimit;+ const n = std.fmt.parseInt(usize, std.mem.trim(u8, raw[eq + 1 ..], " \t"), 10) catch return error.BadLimit;+ if (n == 0) return error.BadLimit;+ set(name, n);+}++/// Comma-separated pairs for `GRAFF_CONTEXT_LIMIT`.+pub fn applyEnv(raw: []const u8) void {+ var it = std.mem.splitScalar(u8, raw, ',');+ while (it.next()) |part| {+ const t = std.mem.trim(u8, part, " \t");+ if (t.len == 0) continue;+ applyPair(t) catch {};+ }+}++const marker = "\n[truncated by --context-limit]";++/// Truncate `text` to `cap` on a codepoint boundary. Never grows.+pub fn apply(text: []const u8, cap: usize) []const u8 {+ if (text.len <= cap) return text;+ if (cap <= marker.len) return util.utf8Prefix(text, cap);+ const head = util.utf8Prefix(text, cap - marker.len);+ // util.utf8Prefix returns a prefix of `text`; stitch the marker only when+ // the caller copied onto a buffer they own. Here we return the bare+ // prefix — callers that need the marker use `applyAlloc`.+ return head;+}++pub fn applyAlloc(arena: std.mem.Allocator, text: []const u8, cap: usize) []const u8 {+ if (text.len <= cap) return text;+ if (cap <= marker.len) return util.utf8Prefix(text, cap);+ const head = util.utf8Prefix(text, cap - marker.len);+ return std.fmt.allocPrint(arena, "{s}{s}", .{ head, marker }) catch head;+}++test "named limits parse and refuse a silent no-op" {+ resetForTest();+ defer resetForTest();+ try applyPair("skill_catalog_bytes=512");+ try std.testing.expectEqual(@as(usize, 512), skill_catalog_bytes);+ try std.testing.expectError(error.UnknownLimit, applyPair("nope=8"));+ try std.testing.expectError(error.BadLimit, applyPair("agents_md_bytes=0"));+ try std.testing.expectError(error.BadLimit, applyPair("mcp_schema_bytes"));+ applyEnv("mcp_schema_bytes=100,agents_md_bytes=200");+ try std.testing.expectEqual(@as(usize, 100), mcp_schema_bytes);+ try std.testing.expectEqual(@as(usize, 200), agents_md_bytes);+}++test "apply never grows and marks a truncate" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const small = "short";+ try std.testing.expectEqualStrings(small, apply(small, 32));+ const big = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";+ const cut = applyAlloc(a, big, 40);+ try std.testing.expect(cut.len <= 40);+ try std.testing.expect(std.mem.indexOf(u8, cut, "[truncated by --context-limit]") != null);+ try std.testing.expect(std.mem.startsWith(u8, cut, "abc"));+}diff --git a/src/exec.zig b/src/exec.zigindex 3e6d84a8..f7a1e7ef 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -1,12 +1,4 @@-//! Tool dispatch: `execTool` (the timed/traced/hooked outer wrapper, whose-//! guard chain starts with the #330 `--no-local-tools` refusal) and-//! `execToolInner` (the big per-tool-name switch — bash, bash_output,-//! bash_kill, webfetch, read_file, codedb, edit_file, write_file, subagent,-//! workflow, learn_candidate). Split out of main.zig (600-line goal); LAST in-//! the tool-exec region since it's the glue that imports tools.zig/-//! subagent.zig/workflow.zig as siblings, plus approvals.zig/mcp.zig/jobs.zig/-//! skills.zig/telemetry.zig. Back-imports main (`main_mod`) for `ToolCall`/-//! `plan_mode` (pub-flipped) and `utf8Prefix`.+//! Tool dispatch: `execTool` + `execToolInner`. Split out of main.zig.const std = @import("std");const Io = std.Io;@@ -64,6 +56,7 @@ const skills = @import("skills.zig");const skill_docs = @import("skill_docs.zig");const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: refuse an MCP tool whose schema was never loadedconst read_file = @import("read_file.zig");+const result_read = @import("result_read.zig");// #337: edit_file's verified write path, plus the file-tool helpers that moved// out with it (this file is at the 600-line ceiling).const edit_verify = @import("edit_verify.zig");@@ -394,6 +387,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {}return rawFetch(gpa, ctx.client, url);}+ if (std.mem.eql(u8, call.name, result_read.tool_name)) return result_read.exec(ctx, call);if (std.mem.eql(u8, call.name, "read_file")) {const path = strField(input, "path") orelse return missingArg(gpa, "path");if (!confinedPath(path) or !noSymlinkEscape(io, path, ctx.agent_cwd)) return outsideCwd(gpa, path);diff --git a/src/harness_policy.zig b/src/harness_policy.zigindex 55a5a2cf..74da46ee 100644--- a/src/harness_policy.zig+++ b/src/harness_policy.zig@@ -181,6 +181,7 @@ pub fn destructiveGitAllowed(yolo: bool, sub: bool) bool {/// elsewhere). Returns true when the path is safe.pub fn confinedPath(path: []const u8) bool {if (path.len == 0) return false;+ if (@import("workspace_roots.zig").confined(path)) return true;if (std.fs.path.isAbsolute(path)) return false;var it = std.mem.tokenizeAny(u8, path, "/\\");while (it.next()) |comp| {diff --git a/src/mcp_schema_gate.zig b/src/mcp_schema_gate.zigindex c6153c41..9f9de903 100644--- a/src/mcp_schema_gate.zig+++ b/src/mcp_schema_gate.zig@@ -290,7 +290,10 @@ pub fn anyDeferred(all: []const mcp.Tool) bool {/// session with no MCP (or with everything eager) is never charged for it —/// the same "advertise only what can be used" rule #330/#352 apply.pub fn hiddenSpec(name: []const u8, all: []const mcp.Tool) bool {- return std.mem.eql(u8, name, tool_name) and !anyDeferred(all);+ const progressive = std.mem.eql(u8, name, tool_name) or+ std.mem.eql(u8, name, "mcp_search_tools") or+ std.mem.eql(u8, name, "mcp_select_tool");+ return progressive and !anyDeferred(all);}/// The description a deferred tool advertises: the first line (or paragraph)@@ -532,7 +535,7 @@ pub fn descWithListing(arena: Allocator, all: []const mcp.Tool) ![]const u8 {}try aw.writer.writeAll(");");}- return aw.writer.buffered();+ return @import("context_limits.zig").applyAlloc(arena, aw.writer.buffered(), @import("context_limits.zig").mcp_schema_bytes);}/// What is deferred right now, names + short descriptions. Doubles as thediff --git a/src/mcp_select.zig b/src/mcp_select.zignew file mode 100644index 00000000..67ce4a76--- /dev/null+++ b/src/mcp_select.zig@@ -0,0 +1,127 @@+//! fx-style MCP progressive load: search, then select.+//!+//! `load_tool_schemas` already folds schemas and can `query` (which LOADS+//! matches). These two tools split that into a cache-friendlier dance:+//! `mcp_search_tools` lists names + short descriptions and does not enable+//! anything; `mcp_select_tool` loads the chosen names. Same session state+//! as the existing fold — consent is untouched.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const mcp = @import("mcp.zig");+const mcp_schema_gate = @import("mcp_schema_gate.zig");+const tools_mod = @import("tools.zig");++pub const search_name = "mcp_search_tools";+pub const search_desc = "Search deferred MCP tools by keyword. Returns names and one-line descriptions only — it does not load schemas. Call mcp_select_tool with a name you want to enable.";+pub const search_schema =+ \\{"type": "object", "properties": {"query": {"type": "string", "description": "Keywords to match against deferred MCP tool names and descriptions"}, "server": {"type": "string", "description": "Optional: restrict the search to one MCP server"}}, "required": ["query"]}+;++pub const select_name = "mcp_select_tool";+pub const select_desc = "Load the full JSON schema for one deferred MCP tool (or a short list) and enable it for the rest of this session. Search first with mcp_search_tools if you do not know the exact name.";+pub const select_schema =+ \\{"type": "object", "properties": {"name": {"type": "string", "description": "Exact qualified MCP tool name, e.g. mcp__deepwiki__ask_question"}, "tools": {"type": "array", "items": {"type": "string"}, "description": "Several exact names to load in one call"}, "server": {"type": "string", "description": "Load every deferred tool on this MCP server"}}}+;++pub fn isName(name: []const u8) bool {+ return std.mem.eql(u8, name, search_name) or std.mem.eql(u8, name, select_name);+}++fn scoreTool(t: mcp.Tool, query: []const u8) usize {+ var score: usize = 0;+ var tok = std.mem.tokenizeAny(u8, query, " \t,;:/_-");+ while (tok.next()) |w| {+ if (w.len < 2) continue;+ if (mcp_schema_gate.containsIgnoreCase(t.qualified_name, w) or+ mcp_schema_gate.containsIgnoreCase(t.description, w)) score += 1;+ }+ return score;+}++/// Names + short descriptions only. Does not call enable().+pub fn searchInto(arena: Allocator, all: []const mcp.Tool, input: Value) !mcp_schema_gate.Loaded {+ const query = tools_mod.strField(input, "query") orelse+ return .{ .text = "mcp_search_tools needs query", .is_error = true };+ const server = tools_mod.strField(input, "server");+ var hits: std.ArrayList(struct { score: usize, idx: usize }) = .empty;+ for (all, 0..) |t, i| {+ if (!mcp_schema_gate.isDeferred(all, t)) continue;+ if (server) |sv| {+ if (!std.mem.eql(u8, mcp_schema_gate.serverOf(t.qualified_name), sv)) continue;+ }+ const score = scoreTool(t, query);+ if (score == 0) continue;+ try hits.append(arena, .{ .score = score, .idx = i });+ }+ if (hits.items.len == 0) {+ return .{ .text = try std.fmt.allocPrint(arena, "no deferred MCP tool matched '{s}'. Use load_tool_schemas with no args to list what is deferred.", .{query}), .is_error = true };+ }+ std.mem.sort(@TypeOf(hits.items[0]), hits.items, {}, struct {+ fn lessThan(_: void, a: @TypeOf(hits.items[0]), b: @TypeOf(hits.items[0])) bool {+ return a.score > b.score;+ }+ }.lessThan);+ const cap = @min(hits.items.len, 8);+ var aw: Io.Writer.Allocating = .init(arena);+ try aw.writer.print("{d} deferred match(es). Call mcp_select_tool name=<qualified> to load a schema.\n", .{cap});+ for (hits.items[0..cap]) |h| {+ const t = all[h.idx];+ try aw.writer.print(" {s}: {s}\n", .{ t.qualified_name, mcp_schema_gate.shortDesc(t.description) });+ }+ return .{ .text = aw.writer.buffered() };+}++pub fn handleSearch(agent: anytype, input: Value) tools_mod.ExecResult {+ if (agent.sub) return .{ .text = "mcp_search_tools is root-only; a subagent has no MCP registry of its own", .is_error = true };+ const reg = agent.registry orelse return .{ .text = "no MCP servers are connected, so there are no tools to search", .is_error = true };+ const r = searchInto(agent.arena, reg.tools, input) catch+ return .{ .text = "mcp_search_tools failed", .is_error = true };+ return .{ .text = r.text, .is_error = r.is_error };+}++fn selectInput(arena: Allocator, input: Value) Value {+ const one = tools_mod.strField(input, "name") orelse return input;+ var obj: std.json.ObjectMap = .empty;+ var argv = std.json.Array.init(arena);+ argv.append(.{ .string = one }) catch return input;+ obj.put(arena, "tools", .{ .array = argv }) catch return input;+ if (tools_mod.strField(input, "server")) |sv| obj.put(arena, "server", .{ .string = sv }) catch {};+ return .{ .object = obj };+}++pub fn handleSelect(agent: anytype, input: Value) tools_mod.ExecResult {+ return mcp_schema_gate.handleLoad(agent, selectInput(agent.arena, input));+}++pub fn dispatch(agent: anytype, call: tools_mod.ToolCall) tools_mod.ExecResult {+ if (std.mem.eql(u8, call.name, search_name)) return handleSearch(agent, call.input);+ if (std.mem.eql(u8, call.name, select_name)) return handleSelect(agent, call.input);+ return mcp_schema_gate.handleLoad(agent, call.input);+}++test "search lists matches and does not enable them" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ mcp_schema_gate.reset();+ defer mcp_schema_gate.reset();+ mcp_schema_gate.g_policy = .{ .enabled = true, .budget = 0, .eager = &.{} };+ const all = try @import("mcp_schema_gate_tests.zig").fixture(a, "wiki", 2, 2000);+ const req = try std.json.parseFromSliceLeaky(Value, a, "{\"query\":\"first line\"}", .{ .allocate = .alloc_always });+ const r = try searchInto(a, all, req);+ try std.testing.expect(!r.is_error);+ try std.testing.expect(std.mem.indexOf(u8, r.text, "mcp__wiki__t0") != null);+ try std.testing.expect(std.mem.indexOf(u8, r.text, "mcp_select_tool") != null);+ try std.testing.expect(!mcp_schema_gate.isLoaded("mcp__wiki__t0"));+}++test "isName covers only the progressive pair" {+ try std.testing.expect(isName(search_name));+ try std.testing.expect(isName(select_name));+ try std.testing.expect(!isName("load_tool_schemas"));+ try std.testing.expect(!isName("bash"));+}diff --git a/src/no_local_tools.zig b/src/no_local_tools.zigindex d3856e71..f58a1141 100644--- a/src/no_local_tools.zig+++ b/src/no_local_tools.zig@@ -41,6 +41,7 @@ pub const gated_tools = [_][]const u8{"edit_file","write_file","codedb",+ "read_tool_result",// #352: imagegen looks like a content tool but is a local write-and-spawn// primitive — it starts `codex exec --sandbox workspace-write` or python3// on THIS host and writes a file into the working tree. Being optional@@ -88,6 +89,7 @@ pub const lean_tools = [_][]const u8{"edit_file","write_file","codedb",+ "read_tool_result","subagent","attempt_completion","load_tool_schemas",@@ -136,7 +138,7 @@ pub fn compactLeanSpecs(comptime Spec: type, arena: Allocator, specs: []const Sp/// Refusal text. Names the flag so the model stops retrying the same call, and/// points it at what does work in this deployment.-pub const refusal_text = "--no-local-tools is set for this process: the built-in bash, bash_output, bash_kill, read_file, edit_file, write_file and codedb tools are hard-disabled and cannot be re-enabled by asking. Run commands and touch files through the sandbox tools the connected MCP server provides instead; webfetch still works.";+pub const refusal_text = "--no-local-tools is set for this process: the built-in bash, bash_output, bash_kill, read_file, edit_file, write_file, codedb and read_tool_result tools are hard-disabled and cannot be re-enabled by asking. Run commands and touch files through the sandbox tools the connected MCP server provides instead; webfetch still works.";/// `GRAFF_NO_LOCAL_TOOLS` - affirmative-only, like GRAFF_CLOCK_SLEEP, and OR'd/// onto the CLI flag by the caller so a stray value can never turn@@ -182,7 +184,7 @@ test "#330: the gated set is exactly the host-touching built-ins; webfetch, metadefer enabled = saved;for (gated_tools) |tool| try std.testing.expect(isLocalTool(tool));- try std.testing.expectEqual(@as(usize, 8), gated_tools.len);+ try std.testing.expectEqual(@as(usize, 9), gated_tools.len);try std.testing.expect(isLocalTool("imagegen")); // #352: optional, but still a local spawn+writefor ([_][]const u8{ "webfetch", "skill", "subagent", "workflow", "todo_write", "eval", "mcp__sandbox__exec", "mcp__sandbox__bash" }) |tool|try std.testing.expect(!isLocalTool(tool));@@ -229,10 +231,10 @@ test "lean: the filter keeps exactly the seven one-shot tools, and allocates nottry std.testing.expectEqualStrings("read_file", kept[1].name);try std.testing.expectEqualStrings("subagent", kept[2].name);try std.testing.expectEqualStrings("attempt_completion", kept[3].name);- // The keep-list is exactly the eight documented tools — subagent stays+ // The keep-list is exactly the nine documented tools — subagent stays// (the unattended delegation path), load_tool_schemas stays (lean folds// MCP behind it), everything orchestration/meta goes.- try std.testing.expectEqual(@as(usize, 8), lean_tools.len);+ try std.testing.expectEqual(@as(usize, 9), lean_tools.len);for (lean_tools) |tool| try std.testing.expect(leanKeeps(tool));try std.testing.expect(!leanKeeps("workflow"));try std.testing.expect(!leanKeeps("todo_write"));diff --git a/src/result_read.zig b/src/result_read.zignew file mode 100644index 00000000..6c2a76b4--- /dev/null+++ b/src/result_read.zig@@ -0,0 +1,151 @@+//! `read_tool_result`: byte-range or literal-search a spilled #440 handle.+//!+//! A fat bash/codedb result lands in `.graff/tool-results/tr_N.txt` and the+//! model sees a preview + handle id. This tool is how it pages the rest+//! without pulling the whole payload back into history (fx's overflow+//! handle). The path jail is the handle dir itself — not an extra workspace+//! root, and not a way around PathConfine for arbitrary files.++const std = @import("std");+const Io = std.Io;++const tools = @import("tools.zig");+const tool_handle = @import("tool_handle.zig");+const util = @import("util.zig");++pub const tool_name = "read_tool_result";+pub const tool_desc = "Read a spilled tool-result handle. Pass handle (tr_N from the overflow marker) plus offset/limit in bytes, or query for a literal search. Never pull the whole payload — one fat bash/codedb hit stays out of history.";+pub const tool_schema =+ \\{"type": "object", "properties": {"handle": {"type": "string", "description": "Handle id (tr_N) from a tool-result overflow marker, or the handle file path"}, "offset": {"type": "integer", "description": "Byte offset into the stored result (default 0)"}, "limit": {"type": "integer", "description": "Max bytes to return (default 4096, cap 16384)"}, "query": {"type": "string", "description": "Optional literal search; returns matching windows instead of a raw slice"}}, "required": ["handle"]}+;++pub const default_limit: usize = 4096;+pub const max_limit: usize = 16384;+const max_hits: usize = 8;+const window_pad: usize = 80;++/// Parse `tr_12` (or `TR_12`) into the sequence number. null when the token+/// is not a handle id.+pub fn parseId(raw: []const u8) ?u64 {+ const t = std.mem.trim(u8, raw, " \t");+ if (t.len < 4) return null;+ if (!std.ascii.eqlIgnoreCase(t[0..3], "tr_")) return null;+ return std.fmt.parseInt(u64, t[3..], 10) catch null;+}++/// Relative path under cwd for handle `tr_N`.+pub fn relPath(arena: std.mem.Allocator, id: u64) ![]const u8 {+ return std.fmt.allocPrint(arena, "{s}/tr_{d}.txt", .{ tool_handle.handles_dir, id });+}++fn clampLimit(n: ?i64) usize {+ const raw: usize = if (n) |v| (if (v <= 0) default_limit else @intCast(v)) else default_limit;+ return @min(raw, max_limit);+}++fn clampOffset(n: ?i64, len: usize) usize {+ if (n == null or n.? <= 0) return 0;+ const off: usize = @intCast(n.?);+ return @min(off, len);+}++/// Literal search: up to `max_hits` windows around each match.+fn search(arena: std.mem.Allocator, text: []const u8, query: []const u8) ![]const u8 {+ if (query.len == 0) return error.EmptyQuery;+ var aw: Io.Writer.Allocating = .init(arena);+ var hits: usize = 0;+ var i: usize = 0;+ while (i < text.len and hits < max_hits) {+ const rest = text[i..];+ const at = std.mem.indexOf(u8, rest, query) orelse break;+ const abs = i + at;+ const lo = abs -| window_pad;+ const hi = @min(text.len, abs + query.len + window_pad);+ try aw.writer.print("hit {d} at byte {d}:\n{s}\n---\n", .{ hits + 1, abs, text[lo..hi] });+ hits += 1;+ i = abs + query.len;+ }+ if (hits == 0) return std.fmt.allocPrint(arena, "no match for {s} in {d} bytes", .{ query, text.len });+ try aw.writer.print("{d} hit(s), {d} bytes total", .{ hits, text.len });+ return aw.writer.buffered();+}++fn sliceText(arena: std.mem.Allocator, text: []const u8, offset: usize, limit: usize) ![]const u8 {+ if (offset >= text.len) return std.fmt.allocPrint(arena, "offset {d} is past the {d}-byte result", .{ offset, text.len });+ const end = @min(text.len, offset + limit);+ const body = text[offset..end];+ if (end == text.len and offset == 0) return arena.dupe(u8, body);+ return std.fmt.allocPrint(arena, "{s}\n\n[{d}..{d} of {d} bytes]", .{ body, offset, end, text.len });+}++/// Resolve a handle token to a cwd-relative path under the handle dir.+pub fn resolveRel(arena: std.mem.Allocator, handle: []const u8) ![]const u8 {+ const t = std.mem.trim(u8, handle, " \t");+ if (parseId(t)) |id| return relPath(arena, id);+ // Accept the file's own relative or absolute path when it still names+ // the handle dir (old markers printed the absolute path).+ const needle = tool_handle.handles_dir;+ if (std.mem.indexOf(u8, t, needle)) |at| {+ const rest = t[at..];+ if (std.mem.indexOfScalar(u8, rest, '/') == null) return error.BadHandle;+ if (std.mem.indexOf(u8, rest, "..") != null) return error.BadHandle;+ return rest;+ }+ return error.BadHandle;+}++pub fn readStored(io: Io, arena: std.mem.Allocator, rel: []const u8) ![]const u8 {+ return Io.Dir.cwd().readFileAlloc(io, rel, arena, .limited(64 * 1024 * 1024)) catch return error.MissingHandle;+}++pub fn exec(ctx: tools.ToolCtx, call: tools.ToolCall) !tools.ToolOutput {+ const gpa = ctx.gpa;+ var scratch = std.heap.ArenaAllocator.init(gpa);+ defer scratch.deinit();+ const arena = scratch.allocator();+ const handle = tools.strField(call.input, "handle") orelse return tools.missingArg(gpa, "handle");+ const rel = resolveRel(arena, handle) catch+ return .{ .text = try std.fmt.allocPrint(gpa, "read_tool_result: '{s}' is not a handle (want tr_N)", .{handle}), .is_error = true };+ const stored = readStored(ctx.io, arena, rel) catch+ return .{ .text = try std.fmt.allocPrint(gpa, "read_tool_result: no stored result at {s}", .{rel}), .is_error = true };+ const text = if (tools.strField(call.input, "query")) |q| blk: {+ break :blk search(arena, stored, q) catch+ return .{ .text = try gpa.dupe(u8, "read_tool_result: query must not be empty"), .is_error = true };+ } else blk: {+ const off = clampOffset(tools.intField(call.input, "offset"), stored.len);+ const lim = clampLimit(tools.intField(call.input, "limit"));+ break :blk try sliceText(arena, stored, off, lim);+ };+ return .{ .text = try gpa.dupe(u8, text) };+}++test "parseId accepts tr_N only" {+ try std.testing.expectEqual(@as(?u64, 0), parseId("tr_0"));+ try std.testing.expectEqual(@as(?u64, 12), parseId("TR_12"));+ try std.testing.expect(parseId("tr_") == null);+ try std.testing.expect(parseId("/etc/passwd") == null);+ try std.testing.expect(parseId("run-0.txt") == null);+}++test "resolveRel maps tr_N and rejects escape" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ try std.testing.expectEqualStrings(".graff/tool-results/tr_3.txt", try resolveRel(a, "tr_3"));+ try std.testing.expectEqualStrings(".graff/tool-results/tr_1.txt", try resolveRel(a, "/tmp/proj/.graff/tool-results/tr_1.txt"));+ try std.testing.expectError(error.BadHandle, resolveRel(a, "../secret"));+ try std.testing.expectError(error.BadHandle, resolveRel(a, "/etc/passwd"));+}++test "byte-range and query stay bounded" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const big = "aaa NEEDLE aaa NEEDLE zzz";+ const sliced = try sliceText(a, big, 4, 6);+ try std.testing.expect(std.mem.indexOf(u8, sliced, "NEEDLE") != null);+ try std.testing.expect(std.mem.indexOf(u8, sliced, "of 25 bytes") != null);+ const hits = try search(a, big, "NEEDLE");+ try std.testing.expect(std.mem.indexOf(u8, hits, "2 hit(s)") != null);+ try std.testing.expectError(error.EmptyQuery, search(a, big, ""));+}diff --git a/src/schema.zig b/src/schema.zigindex 21c7a8ff..047c2272 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -1,9 +1,4 @@-//! Tool-schema + provider-tool JSON emission: the built-in/meta ToolSpec-//! catalog, the per-provider tool-array renderers (anthropic/openai/responses),-//! and emitSchema (the --schema / `graff serve` /v1/schema document). Split out-//! of main.zig (#123). Back-imports main for Provider (.Kind) and the-//! provider catalog and the active model table. main-//! re-exports emitSchema + schema_version so serve.zig stays untouched.+//! Tool-schema + provider-tool JSON emission. Split out of main.zig (#123).const std = @import("std");const Io = std.Io;@@ -19,8 +14,10 @@ const workspace_switch = @import("workspace_switch.zig");const no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-local-tools gate (layer 1 lives here, layer 2 in exec.zig)const tool_gates = @import("tool_gates.zig"); // #352: the additive twin — optional tools that only exist when startup found their backing capabilityconst imagegen = @import("imagegen.zig"); // #352: name/desc/schema as plain strings, like skill_docs, so this catalog needs one entry and no import cycle-const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: which MCP tools are served schema-first vs description-only, and the `load_tool_schemas` strings-const native_fold = @import("native_fold.zig"); // folded native power tools: same two-phase pattern for the harness's own catalog+const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: load_tool_schemas strings+const mcp_select = @import("mcp_select.zig"); // fx search-then-select+const result_read = @import("result_read.zig"); // overflow handle pager+const native_fold = @import("native_fold.zig"); // folded native power toolsconst render = @import("schema_render.zig"); // the comptime provider-tool renderers moved out when #352's optional-tool catalogs doubled the number held here (600-line ceiling)const anthropicToolsJson = render.anthropicToolsJson;const openaiToolsJson = render.openaiToolsJson;@@ -112,6 +109,7 @@ const base_specs = [_]ToolSpec{\\{"type": "object", "properties": {"command": {"type": "string", "description": "codedb subcommand + args, e.g. \"search parseHeader\", \"symbol buildBody --body\", \"callers switchProvider\""}}, "required": ["command"]},},+ .{ .name = result_read.tool_name, .desc = result_read.tool_desc, .schema = result_read.tool_schema },};// Meta tools act on the agent's own state, not the outside world; the@@ -160,6 +158,8 @@ const meta_specs = [_]ToolSpec{// (and enables those tools) on demand. Meta because it mutates the root's// own tool catalog; renderRootTools drops it while nothing is deferred..{ .name = mcp_schema_gate.tool_name, .desc = mcp_schema_gate.tool_desc, .schema = mcp_schema_gate.tool_schema },+ .{ .name = mcp_select.search_name, .desc = mcp_select.search_desc, .schema = mcp_select.search_schema },+ .{ .name = mcp_select.select_name, .desc = mcp_select.select_desc, .schema = mcp_select.select_schema },.{.name = "clock_sleep",.desc = "Pause the current turn for up to 12 hours of wall-clock time; interruptible by user input, and reported as a normal (non-error) result either way. For autonomous /loop runs that need to wait before re-checking something (e.g. a long external job). Root-only; off unless --clock-sleep/GRAFF_CLOCK_SLEEP=1 is set.",@@ -224,7 +224,7 @@ const root_specs_without_clock = rootSpecsWithout(&.{"clock_sleep"});const root_specs_without_learning = rootSpecsWithout(&.{"learn_candidate"});const root_specs_without_optional = rootSpecsWithout(&.{ "clock_sleep", "learn_candidate" });-pub const meta_names = [_][]const u8{ "todo_write", "todo_read", "ask_user", "eval", "attempt_completion", "clock_sleep", "note_constraint", mcp_schema_gate.tool_name, peer_channel.tool_name, workspace_switch.tool_name };+pub const meta_names = [_][]const u8{ "todo_write", "todo_read", "ask_user", "eval", "attempt_completion", "clock_sleep", "note_constraint", mcp_schema_gate.tool_name, mcp_select.search_name, mcp_select.select_name, peer_channel.tool_name, workspace_switch.tool_name };pub fn isMetaName(name: []const u8) bool {for (meta_names) |m| if (std.mem.eql(u8, name, m)) return true;diff --git a/src/schema_protocol.zig b/src/schema_protocol.zigindex 0cd642d7..c12273b9 100644--- a/src/schema_protocol.zig+++ b/src/schema_protocol.zig@@ -17,6 +17,8 @@ pub const flags =\\ {"flag": "--yolo", "arg": null, "description": "skip all permission prompts for the session"},\\ {"flag": "--lean", "arg": null, "description": "slim the tool surface to 8 core tools and connect MCP servers DEFERRED behind the load_tool_schemas meta tool (names + one-line descriptions up front, full schemas on demand) instead of paying every server's schemas in every model turn. DEFAULT for -p one-shots; GRAFF_LEAN=1 forces it on anywhere"},\\ {"flag": "--no-lean", "arg": null, "description": "opt a one-shot out of the implied --lean: full tool surface and eager MCP schemas, the pre-default -p behavior"},+ \\ {"flag": "--add-dir", "arg": "path", "description": "extra workspace root file tools may touch (repeatable, max 16). Complementary to workspace switch; extra roots do not contribute skills or sessions"},+ \\ {"flag": "--context-limit", "arg": "name=N", "description": "named prefix byte cap: skill_catalog_bytes, mcp_schema_bytes, or agents_md_bytes (repeatable). GRAFF_CONTEXT_LIMIT is the env form"},\\ {"flag": "--no-local-tools", "arg": null, "description": "embedder mode: hard-disable the built-in bash/bash_output/bash_kill/read_file/edit_file/write_file/codedb tools for the whole process, so the harness can run outside the sandbox and source its coding tools from an MCP server instead; webfetch, orchestration and MCP tools are unaffected, and subagents inherit the gate. GRAFF_NO_LOCAL_TOOLS=1 is the equivalent"},\\ {"flag": "--system-prompt", "arg": "text", "description": "replace the built-in system prompt (cwd project-instructions file is still appended)"},\\ {"flag": "--append-system-prompt", "arg": "text", "description": "append extra text to the end of the system prompt"},diff --git a/src/session_settings.zig b/src/session_settings.zigindex e2c8d506..97068b38 100644--- a/src/session_settings.zig+++ b/src/session_settings.zig@@ -150,6 +150,7 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {} else |_| {}}if (environ_map.get("GRAFF_TOOL_HANDLE_BYTES")) |v| tool_handle.applyEnv(v); // #440: bytes at which a tool result becomes preview + handle+ if (environ_map.get("GRAFF_CONTEXT_LIMIT")) |v| @import("context_limits.zig").applyEnv(v);// #204: GRAFF_COMPACT_PCT overrides the auto-compaction threshold as a percent// of the window (default 80). Clamped to 1..100; ignored if unparseable or 0.if (environ_map.get("GRAFF_COMPACT_PCT")) |v| {diff --git a/src/session_start.zig b/src/session_start.zigindex ea08f093..eef52db4 100644--- a/src/session_start.zig+++ b/src/session_start.zig@@ -102,6 +102,11 @@ pub fn setupWorktreeAndBanner(engine_sink.enableColor();}const sink = engine_sink.writerSink(out);+ // --add-dir before --worktree chdir so a relative extra root is resolved+ // against the launch cwd, not the scratch tree.+ for (flags.add_dirs.items) |dir| {+ @import("workspace_roots.zig").add(io, arena, dir) catch |err| std.process.fatal("--add-dir '{s}': {t}", .{ dir, err });+ }// --worktree/-w: run this session in an isolated git worktree so parallel// agents don't collide on files. Creates .graff/worktrees/<name> on branch// worktree-<name> (from HEAD) and enters it; reuses it if it already exists.diff --git a/src/skill_docs.zig b/src/skill_docs.zigindex a5a822e2..4bad93da 100644--- a/src/skill_docs.zig+++ b/src/skill_docs.zig@@ -284,7 +284,7 @@ pub fn promptCatalog(arena: Allocator, list: []const Skill) []const u8 {const sk = list[i];aw.writer.print("- {s} ({s}): {s}\n", .{ sk.name, sk.source.label(), util.utf8Prefix(sk.desc, desc_cap) }) catch return "";}- return aw.writer.buffered();+ return @import("context_limits.zig").applyAlloc(arena, aw.writer.buffered(), @import("context_limits.zig").skill_catalog_bytes);}/// The `skill` tool. A named load already in the session catalog (`g_skills`)diff --git a/src/startup.zig b/src/startup.zigindex 277bf3df..9bece751 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -107,7 +107,8 @@ pub fn buildSystemPrompt(const body = Io.Dir.cwd().readFileAlloc(io, fname, arena, .limited(64 * 1024)) catch continue;const trimmed = std.mem.trim(u8, body, " \t\r\n");if (trimmed.len == 0) continue;- sys_normal = try std.fmt.allocPrint(arena, "{s}\n\n# Project instructions (from {s})\n{s}", .{ base_prompt, fname, trimmed });+ const capped = @import("context_limits.zig").applyAlloc(arena, trimmed, @import("context_limits.zig").agents_md_bytes);+ sys_normal = try std.fmt.allocPrint(arena, "{s}\n\n# Project instructions (from {s})\n{s}", .{ base_prompt, fname, capped });if (!quiet) {try out.print("loaded project instructions from {s} ({d} bytes)\n", .{ fname, trimmed.len });try out.flush();diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 1c32c2a2..c3090093 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -127,6 +127,10 @@ const peer_context_compact_test = @import("peer_context_compact_test.zig");const peer_inbox = @import("peer_inbox.zig"); // Claude-style list/inbox pullconst peer_target = @import("peer_target.zig"); // exact DM / goal targetingconst workspace_switch = @import("workspace_switch.zig"); // ADR 0006 mid-session worktree switch+const result_read = @import("result_read.zig"); // overflow handle pager+const context_limits = @import("context_limits.zig"); // named prefix caps+const workspace_roots = @import("workspace_roots.zig"); // --add-dir extra roots+const mcp_select = @import("mcp_select.zig"); // search-then-select MCPconst plugins = @import("plugins.zig"); // ADR 0007 in-place plugin / foreign MCP discoveryconst plugin_layout = @import("plugin_layout.zig"); // Claude commands/ + inline MCP + ${CLAUDE_PLUGIN_ROOT}const plugin_scan = @import("plugin_scan.zig"); // timed discover + production cache@@ -264,6 +268,10 @@ test {_ = peer_inbox;_ = peer_target;_ = workspace_switch;+ _ = result_read;+ _ = context_limits;+ _ = workspace_roots;+ _ = mcp_select;_ = plugins;_ = plugin_layout;_ = plugin_scan;diff --git a/src/tool_handle.zig b/src/tool_handle.zigindex 5aa0d19e..90c5d516 100644--- a/src/tool_handle.zig+++ b/src/tool_handle.zig@@ -161,11 +161,16 @@ pub fn withFirstNote(arena: Allocator, r: Result, shown: *bool) ![]const u8 {return std.fmt.allocPrint(arena, "{s}{s}", .{ r.text, first_note });}+fn handleId(path: []const u8) []const u8 {+ const base = std.fs.path.basename(path);+ return if (std.mem.endsWith(u8, base, ".txt")) base[0 .. base.len - 4] else base;+}+fn markerText(arena: Allocator, path: ?[]const u8, total: usize, threshold: usize, shape: []const u8) ![]const u8 {if (path) |p| return std.fmt.allocPrint(arena,- "[tool result handle: {d} bytes, {s} — the COMPLETE result is at {s}. Slice what you need out of that file (read_file with start_line/end_line, a grep-style bash command, codedb) instead of re-running the tool (#440).]",- .{ total, shape, p },+ "[tool result handle: {d} bytes, {s} — handle {s} at {s}. Page it with read_tool_result (offset/limit or query); do not re-run the tool (#440).]",+ .{ total, shape, handleId(p), p },);return std.fmt.allocPrint(arena,@@ -183,11 +188,19 @@ fn persist(arena: Allocator, target: Target, text: []const u8) ?[]const u8 {if (!reserve(text.len)) return null;// createDirPath is idempotent; `.graff` normally already exists (trace setup).target.dir.createDirPath(target.io, handles_dir) catch return refund(text.len);- const seq = g_seq.fetchAdd(1, .monotonic);- const run_id = if (target.run_id.len > 0) target.run_id else "untraced";- const rel = std.fmt.allocPrint(arena, "{s}/{s}-{d}.txt", .{ handles_dir, run_id, seq }) catch return refund(text.len);- target.dir.writeFile(target.io, .{ .sub_path = rel, .data = text, .flags = .{ .exclusive = true } }) catch return refund(text.len);- return absolute(target, arena, rel);+ // `g_seq` is per-process. A prior graff in this cwd may have left tr_N;+ // exclusive create must skip those instead of dropping the handle.+ var spins: u32 = 0;+ while (spins < 1024) : (spins += 1) {+ const seq = g_seq.fetchAdd(1, .monotonic);+ const rel = std.fmt.allocPrint(arena, "{s}/tr_{d}.txt", .{ handles_dir, seq }) catch return refund(text.len);+ target.dir.writeFile(target.io, .{ .sub_path = rel, .data = text, .flags = .{ .exclusive = true } }) catch |err| {+ if (err == error.PathAlreadyExists) continue;+ return refund(text.len);+ };+ return absolute(target, arena, rel);+ }+ return refund(text.len);}/// Resolved through the same dir handle the file was written with, so the path@@ -356,13 +369,14 @@ test "#440: over the threshold returns preview + handle path + byte count + shaptry std.testing.expect(std.unicode.utf8ValidateSlice(r.text));// (a) the handle holds the complete original bytes- const rel = handles_dir ++ "/run-0.txt";+ const rel = handles_dir ++ "/tr_0.txt";const stored = try tmp.dir.readFileAlloc(io, rel, std.testing.allocator, .limited(1 << 20));defer std.testing.allocator.free(stored);try std.testing.expectEqualStrings(big, stored);// (b) the path handed to the model is absolute and names that filetry std.testing.expect(std.fs.path.isAbsolute(r.path.?));- try std.testing.expect(std.mem.endsWith(u8, r.path.?, "run-0.txt"));+ try std.testing.expect(std.mem.endsWith(u8, r.path.?, "tr_0.txt"));+ try std.testing.expect(std.mem.indexOf(u8, r.text, "handle tr_0") != null);try std.testing.expect(std.mem.indexOf(u8, r.text, r.path.?) != null);// (c) the byte count and the shape hint are both in the markertry std.testing.expect(std.mem.indexOf(u8, r.text, "40000 bytes") != null);@@ -504,5 +518,28 @@ test "#440: the run byte budget bounds the handle dir, and over it the result istry std.testing.expect(std.mem.indexOf(u8, second.text, "8192 bytes total") != null);try std.testing.expect(std.mem.indexOf(u8, second.text, "No handle could be written") != null);try std.testing.expect(second.text.len <= 1024);- try std.testing.expect(tmp.dir.statFile(io, handles_dir ++ "/run-1.txt", .{}) == error.FileNotFound);+ try std.testing.expect(tmp.dir.statFile(io, handles_dir ++ "/tr_1.txt", .{}) == error.FileNotFound);+}++test "#440: a leftover tr_N from a prior process still gets a handle" {+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ resetForTest();+ defer resetForTest();++ const big = try a.alloc(u8, 8192);+ @memset(big, 'x');+ const first = try forResult(std.testing.allocator, a, testTarget(&tmp), big, 1024);+ try std.testing.expect(first.path != null);+ try std.testing.expect(std.mem.endsWith(u8, first.path.?, "tr_0.txt"));++ // New process: seq restarts at 0, leftover file stays.+ resetForTest();+ const second = try forResult(std.testing.allocator, a, testTarget(&tmp), big, 1024);+ try std.testing.expect(second.path != null);+ try std.testing.expect(std.mem.endsWith(u8, second.path.?, "tr_1.txt"));+ try std.testing.expect(std.mem.indexOf(u8, second.text, "handle tr_1") != null);}diff --git a/src/workspace_roots.zig b/src/workspace_roots.zignew file mode 100644index 00000000..5509534a--- /dev/null+++ b/src/workspace_roots.zig@@ -0,0 +1,135 @@+//! Extra workspace roots (`--add-dir`). Complementary to the `workspace`+//! tool: these are additional trees file tools may touch, not a cwd switch.+//! Max 16. Extra roots never contribute skills or sessions — those stay on+//! the primary checkout and `$HOME`. Fits PathConfine: an absolute path is+//! confined only when it stays under one of these roots with no `..`.++const std = @import("std");+const Io = std.Io;++pub const max_roots: usize = 16;++var g_roots: [max_roots][]const u8 = undefined;+var g_n: usize = 0;++pub fn resetForTest() void {+ g_n = 0;+}++pub fn count() usize {+ return g_n;+}++pub fn items() []const []const u8 {+ return g_roots[0..g_n];+}++fn hasDotDot(path: []const u8) bool {+ var it = std.mem.tokenizeAny(u8, path, "/\\");+ while (it.next()) |comp| {+ if (std.mem.eql(u8, comp, "..")) return true;+ }+ return false;+}++fn under(path: []const u8, root: []const u8) bool {+ if (!std.mem.startsWith(u8, path, root)) return false;+ if (path.len == root.len) return true;+ const next = path[root.len];+ return next == '/' or next == '\\';+}++/// True when `path` is an absolute path under `roots` and has no `..`.+pub fn confinedUnder(path: []const u8, roots: []const []const u8) bool {+ if (roots.len == 0) return false;+ if (path.len == 0) return false;+ if (!std.fs.path.isAbsolute(path)) return false;+ if (hasDotDot(path)) return false;+ for (roots) |root| {+ if (under(path, root)) return true;+ }+ return false;+}++/// True when `path` is an absolute path under a registered extra root and+/// has no `..` components. Relative paths stay on the cwd jail.+pub fn confined(path: []const u8) bool {+ return confinedUnder(path, g_roots[0..g_n]);+}++/// Extra roots are file-tool allow-lists only. Skills, sessions, plugins,+/// and MCP config never scan them.+pub fn contributesSkills(_: []const u8) bool {+ return false;+}++pub fn contributesSessions(_: []const u8) bool {+ return false;+}++fn realDir(io: Io, arena: std.mem.Allocator, raw: []const u8) ![]const u8 {+ var dir = Io.Dir.cwd().openDir(io, raw, .{}) catch return error.NotADir;+ defer dir.close(io);+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = dir.realPath(io, &buf) catch return error.NotADir;+ return arena.dupe(u8, buf[0..n]);+}++/// Register one extra root. Resolves to a real directory now so later+/// `--worktree` chdir cannot rewrite a relative `--add-dir`.+pub fn add(io: Io, arena: std.mem.Allocator, raw: []const u8) !void {+ if (g_n >= max_roots) return error.TooManyRoots;+ const owned = try realDir(io, arena, raw);+ // De-dupe: adding the same tree twice is harmless.+ for (g_roots[0..g_n]) |r| if (std.mem.eql(u8, r, owned)) return;+ g_roots[g_n] = owned;+ g_n += 1;+}++/// Pure seat of add(): cap + de-dupe, no filesystem. Used by the test so+/// parallel cases do not share g_n.+pub fn accept(n: usize, existing: []const []const u8, candidate: []const u8) error{TooManyRoots}!bool {+ if (n >= max_roots) return error.TooManyRoots;+ for (existing) |r| if (std.mem.eql(u8, r, candidate)) return false;+ return true;+}++test "extra roots allow a lexical child and refuse escape" {+ const roots = [_][]const u8{"/work/docs"};+ try std.testing.expect(confinedUnder("/work/docs/readme.md", &roots));+ try std.testing.expect(confinedUnder("/work/docs", &roots));+ try std.testing.expect(!confinedUnder("/work/docs/../secret", &roots));+ try std.testing.expect(!confinedUnder("/etc/passwd", &roots));+ try std.testing.expect(!confinedUnder("src/main.zig", &roots)); // relative stays on the cwd jail+ try std.testing.expect(!contributesSkills("/work/docs"));+ try std.testing.expect(!contributesSessions("/work/docs"));+}++test "add refuses a 17th root and skips a duplicate" {+ const existing = [_][]const u8{"/work/docs"};+ try std.testing.expect(!(try accept(1, &existing, "/work/docs")));+ try std.testing.expect(try accept(1, &existing, "/work/other"));+ try std.testing.expectError(error.TooManyRoots, accept(max_roots, &existing, "/work/other"));+}++test "add stores a live path that confined accepts" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ tmp.dir.writeFile(io, .{ .sub_path = "marker.txt", .data = "ok" }) catch unreachable;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ resetForTest();+ defer resetForTest();++ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = try tmp.dir.realPath(io, &buf);+ const root = try a.dupe(u8, buf[0..n]);+ try add(io, a, root);+ try std.testing.expectEqual(@as(usize, 1), count());+ const child = try std.fmt.allocPrint(a, "{s}/marker.txt", .{items()[0]});+ try std.testing.expect(confined(child));+ try std.testing.expect(confined(items()[0]));+ try std.testing.expect(!confined("/etc/passwd"));+}