From afba5800b2b8fc995901043d5979cbd8bbc958e9 Mon Sep 17 00:00:00 2001 From: Samuel Catlow Date: Sat, 5 Sep 2026 13:25:34 +1000 Subject: [PATCH] feat(gateway): wire progressive tool disclosure (bridge tools) Compose the base registry with per-turn extras into a turn-local registry and let ContextPressureGate decide full-vs-bridge disclosure per chat turn. The three bridge tools (tool_search, tool_describe, tool_call) are now wired into the chat toolset and only disclosed under context pressure, keeping the LLM's schema footprint small while preserving full arsenal access on demand. Per-turn extras are identity-bound per channel and cannot live in the process-wide registry (agentexec.BuildToolSetFrom invariant), so the bridge is composed turn-locally rather than registered globally. Thread the model's context window through TurnModel.Prepare (TurnPrepareContext) so the gate activates with a real window. Refs #167 --- .beads/issues.jsonl | 3 +- docs/prds/progressive-tool-disclosure.md | 127 +++++++++++++++++++++++ internal/app/archied/chat_turn_model.go | 7 +- internal/app/archied/main.go | 17 ++- internal/app/archied/main_test.go | 45 +++++++- internal/gateway/turn.go | 25 +++-- internal/gateway/turn_test.go | 4 +- internal/tools/disclosure.go | 39 ++++++- internal/tools/disclosure_test.go | 52 ++++++++++ 9 files changed, 298 insertions(+), 21 deletions(-) create mode 100644 docs/prds/progressive-tool-disclosure.md diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 351af1098..70cc7dc8f 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -100,6 +100,7 @@ {"_type":"issue","id":"archie-core-g7tm","title":"telegram: finalize the reply through a live context, matching the error branch","description":"The success path calls live.finalize(turnCtx, reply) with the raw cancellable turn context (telegram.go:582), while the error branch two lines above deliberately uses context.WithoutCancel(turnCtx). If /stop lands during finalize, the rich edit, the plain-text retry, and the split-send fallback all abort with context.Canceled (go-telegram/bot builds requests with NewRequestWithContext), so the authoritative reply is never delivered and the live message keeps the ▌ cursor forever. The reply is persisted to the ledger, so the loss is delivery-level — but the user sees a frozen half-answer.\n\nFailure: a long tool-using turn is /stop-ped as it completes; turnCtx is cancelled mid-finalize; every send fails on the dead context; the chat shows the last live frame with a blinking cursor and no final answer.\n\nFound by code-review of PR #476 (feat/467, merged 98e8dda).","design":"live.finalize(context.WithoutCancel(turnCtx), reply) — the one-liner the error branch already uses. Consider making finalize take a live context internally rather than trusting each caller to remember.","acceptance_criteria":"A /stop landing mid-finalize still delivers the authoritative reply and drops the cursor; a test covers the cancellable-context finalize path.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-14T14:43:08Z","created_by":"Sam Catlow","updated_at":"2026-08-14T15:07:36Z","started_at":"2026-08-14T14:53:28Z","closed_at":"2026-08-14T15:03:28Z","close_reason":"Fixed in internal/channels/telegram/live.go and telegram.go: finalize/abandon strip context cancellation before sending (mirroring each other), ToolCall escapes Markdown metacharacters via bot.EscapeMarkdown, splitLongMessage splits on rune boundaries. All new/changed tests verified red-then-green; task check clean; adversarial review pass found no blocking issues.","external_ref":"https://github.com/samcharles93/archie-core/issues/484","labels":["code-review","streaming","telegram"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-tb3a","title":"Fix streaming review blockers for inline tool calls","description":"Resolve the four evidence-gated findings in merged inline tool-call streaming: preserve the authoritative Telegram reply when final edits fail; keep Telegram network I/O off the model FullStream consumer and cancellable; correlate tool inputs with results and render a bounded redacted parameter summary; snapshot show_tool_calls per live reply to avoid reload races. Add regression tests for every path and run task check plus lint/race validation.","acceptance_criteria":"Regression tests fail on the merged implementation and pass after the fix. Final edit failure falls back to normal split delivery. Delta and ToolCall callbacks do not wait on Telegram HTTP and stop cancels in-flight rendering. Completed tool events include bounded redacted parameters correlated by tool-call ID. Reload cannot race an in-flight reply's show_tool_calls setting. task check passes, golangci-lint reports no new findings, and focused race tests pass.","notes":"Implemented in worktree /tmp/archie-core-tb3a on branch fix/archie-core-tb3a. Added cancellable async Telegram rendering, final edit failure fallback through normal split delivery, call-ID-correlated bounded conservative parameter summaries, atomic per-reply show_tool_calls snapshots, SSE/UI parameter rendering, rebuilt ui/dist, and regression tests. Validation: GOFLAGS=-buildvcs=false task check passed; golangci-lint --new-from-rev=HEAD ./... reported 0 issues; focused race suite passed; fresh adversarial reviewer reported PASS with zero findings. Plain task check is blocked in linked worktrees by Go VCS stamping exit 128, hence buildvcs override.\n2026-08-24 reconciliation: the close reason's 'worktree left uncommitted' is stale. The work did land on main via ba33527 (Merge pull request #477 from samcharles93/fix/archie-core-tb3a); verified on main: gateway/stream.go sensitiveParameterKey+redactToolParameters, telegram/live.go per-reply showToolCalls snapshot, webui/api_chat.go gating. The /tmp/archie-core-tb3a worktree and its branch are gone, as expected.\n","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T18:05:35Z","created_by":"Sam Catlow","updated_at":"2026-08-24T07:29:09Z","started_at":"2026-08-13T18:05:39Z","closed_at":"2026-08-13T18:35:26Z","close_reason":"Completed and independently reviewed; worktree left uncommitted per conservative repository policy.","external_ref":"https://github.com/samcharles93/archie-core/issues/485","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-dzx","title":"Remove duplicate archie-agent safe.directory setup","description":"## Problem\\ncmd/archie-agent/main.go configures git safe.directory inline and then calls markWorktreeSafe, so startup writes the same global git configuration twice.\\n\\n## Scope\\nKeep markWorktreeSafe as the single tested production path and remove the older inline exec.Command block/import. Add regression coverage proving startup wiring has exactly one authoritative safe-directory call.\\n\\n## Acceptance\\n- archie-agent startup invokes markWorktreeSafe exactly once\\n- no second inline safe.directory command remains in main.go\\n- cmd/archie-agent tests and repository quality gate pass","acceptance_criteria":"Single tested safe.directory setup path remains; duplicate inline command is removed; tests and task check pass","notes":"Red proof: TestMainConfiguresWorktreeSafetyOnce failed with 2 setup paths before implementation. Green proof: go test/vet/build ./cmd/archie-agent/... passed; golangci-lint --new-from-rev=HEAD reported 0 issues. Fresh adversarial review found no blockers. Full task check was not run because the working tree contains unrelated in-progress changes and task check rewrites files; scoped package gate used per repository protocol.","status":"closed","priority":1,"issue_type":"bug","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-08-13T16:10:09Z","created_by":"Sam Catlow","updated_at":"2026-08-13T16:13:48Z","started_at":"2026-08-13T16:10:24Z","closed_at":"2026-08-13T16:13:48Z","close_reason":"Removed duplicate inline safe.directory setup; markWorktreeSafe is now the single tested production path","external_ref":"https://github.com/samcharles93/archie-core/issues/470","dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-14cs","title":"Resolve pre-existing task check gate blockers (lint + jsdom)","description":"Two pre-existing blockers keep the authoritative task check gate red, independently of the progressive-tool-disclosure wiring (issue #167):\n\n1. golangci-lint: 5 issues in files untouched by #167:\n - internal/app/archied/bootstrap.go:316 (cyclop: setupObservability complexity 16 \u003e 15)\n - internal/app/archied/bootstrap.go:405 (nestif)\n - internal/app/archied/telegram_setup_test.go:64 (usetesting: os.Setenv -\u003e t.Setenv)\n - internal/releaseupdate/install_script_test.go:143,160 (noctx: exec.Command -\u003e CommandContext)\n\n All 5 confirmed reproducible on clean main (git stash comparison) and match the documented non-green lint baseline in the archie-build-and-env skill.\n\n2. task test:ui fails because ui/node_modules is not installed (ERR_MODULE_NOT_FOUND: jsdom, declared at ui/package.json:16). Needs npm install before the ui test can run.\n\nBlockers are environmental/baseline, not introduced by the tool-disclosure wiring.\n","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-09-05T03:25:29Z","created_by":"Sam Catlow","updated_at":"2026-09-05T03:25:29Z","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-t2db.22","title":"eda: carry originating task identity on DispatchInput (gap-2 prereq)","description":"Prerequisite for the t2db.17 idempotency resolution. DispatchInput (internal/domain/eda/playbook/playbook.go:187) is {Labels, Kind, Event} with no task identity, so a playbook run cannot derive an event_id for a playbook_dispatches ledger key. Thread the originating task's identity (store.Task.ID, or the TaskEnvelope idempotency key that produced it). IMPORTANT: there is NO production caller of Store.Dispatch today -- DispatchInput is only constructed in tests -- so confirm which identity is actually available at the real Dispatch call site before fixing the field type; do not assume store.Task.ID is available at label/kind classification time (it is not: pollNATS/classify produces the envelope before any task row exists, so the TaskEnvelope.IdempotencyKey string is the identity available there).","design":"Add an identity field to DispatchInput, populated by the (currently nonexistent) production caller. Decide field type against the discovery-path evidence: pollNATS (internal/daemon/daemon.go:844) and the webhook receiver (receiver.go:243) both compute kind/labels from a TaskEnvelope BEFORE any store.Task row exists, and TaskEnvelope.IdempotencyKey() returns 'archie:owner/repo/number' -- so a string identity (the idempotency key) is the available, stable value at the dispatch point, not a store.Task.ID int64. Add a test proving DispatchInput carries it end to end; wire the real production caller only when the coordinator lands.","acceptance_criteria":"DispatchInput carries the originating task's identity (typed as decided against evidence). A test demonstrates the identity is present on the input and reaches the key-derivation path. No production dispatch caller is wired in this ticket (none exists today). task check passes.","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","estimated_minutes":30,"created_at":"2026-09-04T17:07:09Z","created_by":"Sam Catlow","updated_at":"2026-09-04T17:10:44Z","closed_at":"2026-09-04T17:10:44Z","close_reason":"Implementation complete and gate-verified for its scope. Playbook gains ID (path-relative) + Version (sha256 content hash), populated in loadOne; DispatchInput gains TaskID string carrying TaskEnvelope.IdempotencyKey(), per evidence that the discovery point computes kind/labels before any store.Task row exists. Red-green verified; gofumpt/vet/build/golangci-lint clean for the package. NOTE: task check has 5 lint failures PRE-EXISTING at HEAD in unrelated files (bootstrap.go cyclop/nestif, install_script_test.go noctx, telegram_setup_test.go usetesting) -- not caused by this change. Forced close because the earlier blocked-by: t2db.17 dependency is inverted -- .17 is doc-only sign-off; these are its implementation prereqs, not gated on it.","dependencies":[{"issue_id":"archie-core-t2db.22","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-09-04T17:07:09Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.22","depends_on_id":"archie-core-t2db.17","type":"blocks","created_at":"2026-09-04T17:07:09Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-t2db.21","title":"eda: thread Playbook ID and Version for idempotency-ledger keying (gap-2 prereq)","description":"Prerequisite for the t2db.17 idempotency resolution. The shipped Playbook struct (internal/domain/eda/playbook/playbook.go) is {Trigger, Actions} with no ID and no Version, so a playbook_dispatches ledger keyed on (playbook_id, playbook_version, event_id) cannot be built. Add ID (stable path-relative identifier) and Version (content hash of the loaded file, recomputed on every load), both populated at load time. Mirror Binding.Version's purpose: pin dispatched-run provenance to the exact definition that was active when it fired.","status":"closed","priority":2,"issue_type":"task","owner":"sam@catlow.tech","estimated_minutes":30,"created_at":"2026-09-04T17:07:01Z","created_by":"Sam Catlow","updated_at":"2026-09-04T17:10:44Z","closed_at":"2026-09-04T17:10:44Z","close_reason":"Implementation complete and gate-verified for its scope. Playbook gains ID (path-relative) + Version (sha256 content hash), populated in loadOne; DispatchInput gains TaskID string carrying TaskEnvelope.IdempotencyKey(), per evidence that the discovery point computes kind/labels before any store.Task row exists. Red-green verified; gofumpt/vet/build/golangci-lint clean for the package. NOTE: task check has 5 lint failures PRE-EXISTING at HEAD in unrelated files (bootstrap.go cyclop/nestif, install_script_test.go noctx, telegram_setup_test.go usetesting) -- not caused by this change. Forced close because the earlier blocked-by: t2db.17 dependency is inverted -- .17 is doc-only sign-off; these are its implementation prereqs, not gated on it.","dependencies":[{"issue_id":"archie-core-t2db.21","depends_on_id":"archie-core-t2db","type":"parent-child","created_at":"2026-09-04T17:07:01Z","created_by":"Sam Catlow","metadata":"{}"},{"issue_id":"archie-core-t2db.21","depends_on_id":"archie-core-t2db.17","type":"blocks","created_at":"2026-09-04T17:07:01Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":1,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-wdn0","title":"Reconcile beads\u003c-\u003eGitHub issue state after cross-machine sync","description":"After the 2026-09-03 helix/carina reconciliation, bead statuses are authoritative locally but GitHub was never reconciled. Walk closed beads against gh issue list --state all via external_ref and push the differences. Per prior incident notes: bd github push takes ONE id per invocation (multiple ids silently no-op and exit 0), and identical updated_at timestamps make sync skip an issue forever -- close directly with gh issue close in that case.","status":"open","priority":2,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-09-03T12:28:29Z","created_by":"Sam Catlow","updated_at":"2026-09-03T12:28:29Z","dependency_count":0,"dependent_count":0,"comment_count":0} @@ -505,7 +506,7 @@ {"_type":"issue","id":"archie-core-1786637493676-149-96f35179","title":"MCP client: HTTP/StreamableHTTP transport","description":"Implement MCP HTTP/StreamableHTTP transport: make JSON-RPC requests over HTTP/HTTPS with support for streamable HTTP responses. Handle connection lifecycle, keep-alive, reconnection, and error classification for remote MCP servers accessed via HTTP.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:38:54Z","updated_at":"2026-08-08T14:38:56Z","closed_at":"2026-08-08T14:38:57Z","external_ref":"https://github.com/samcharles93/archie-core/issues/170","source_system":"github:https://github.com/samcharles93/archie-core/issues/170:170","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637493651-148-5a1e6482","title":"MCP client: stdio transport (subprocess management)","description":"Implement the MCP stdio transport: spawn and manage MCP server subprocesses, handle stdin/stdout JSON-RPC message framing, subprocess lifecycle (start/stop/restart), and auto-restart with exponential backoff. This is the foundational MCP transport that most local MCP servers use.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:38:48Z","updated_at":"2026-08-08T14:38:51Z","closed_at":"2026-08-08T14:38:52Z","external_ref":"https://github.com/samcharles93/archie-core/issues/169","source_system":"github:https://github.com/samcharles93/archie-core/issues/169:169","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637493624-147-3a7826d5","title":"Context-pressure threshold gating","description":"Implement context-pressure threshold gating: when the combined size of tool schemas exceeds a configurable percentage of the LLM context window, automatically switch to progressive tool disclosure mode (bridge tools). Monitor context usage and toggle between full disclosure and bridge-tool mode dynamically.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:38:43Z","updated_at":"2026-08-08T14:38:46Z","closed_at":"2026-08-08T14:38:47Z","external_ref":"https://github.com/samcharles93/archie-core/issues/168","source_system":"github:https://github.com/samcharles93/archie-core/issues/168:168","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-1786637493594-146-10de5e79","title":"Progressive tool disclosure (bridge tools)","description":"Implement the progressive tool disclosure pattern with three bridge tools: tool_search (search available tools by keyword), tool_describe (return full schema for one tool), and tool_call (invoke a tool by name after discovery). This keeps the LLM's tool schema footprint small while providing full access to the tool arsenal on demand.","status":"open","priority":2,"issue_type":"task","created_at":"2026-08-08T14:38:40Z","updated_at":"2026-08-08T15:34:57Z","external_ref":"https://github.com/samcharles93/archie-core/issues/167","source_system":"github:https://github.com/samcharles93/archie-core/issues/167:167","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-1786637493594-146-10de5e79","title":"Progressive tool disclosure (bridge tools)","description":"Implement the progressive tool disclosure pattern with three bridge tools: tool_search (search available tools by keyword), tool_describe (return full schema for one tool), and tool_call (invoke a tool by name after discovery). This keeps the LLM's tool schema footprint small while providing full access to the tool arsenal on demand.","status":"in_progress","priority":2,"issue_type":"task","assignee":"Sam Catlow","created_at":"2026-08-08T14:38:40Z","updated_at":"2026-09-05T00:06:07Z","started_at":"2026-09-05T00:06:07Z","lease_expires_at":"2026-09-05T00:11:07Z","heartbeat_at":"2026-09-05T00:06:07Z","external_ref":"https://github.com/samcharles93/archie-core/issues/167","source_system":"github:https://github.com/samcharles93/archie-core/issues/167:167","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637493566-145-06408456","title":"Guardrail decision engine: warning vs hard-stop","description":"Implement the guardrail decision engine that uses ToolCallGuardrailConfig thresholds to decide between sending a warning to the LLM or issuing a hard-stop (aborting the tool loop). Considers exact_failure_warn_after, same_tool_failure_warn_after, and no_progress_warn_after. Must track per-session and per-turn counters.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:38:35Z","updated_at":"2026-08-08T14:38:37Z","closed_at":"2026-08-08T14:38:38Z","external_ref":"https://github.com/samcharles93/archie-core/issues/166","source_system":"github:https://github.com/samcharles93/archie-core/issues/166:166","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637493546-144-8a3074d2","title":"Mutating tool classification set","description":"Define and maintain a classification set of mutating (mutation-capable) tools. These tools can modify state and require serialization, checkpointing, and stricter guardrail monitoring. The set should be extensible via registration metadata and feed into dispatch gating and checkpointing decisions.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:38:29Z","updated_at":"2026-08-08T14:38:32Z","closed_at":"2026-08-08T14:38:33Z","external_ref":"https://github.com/samcharles93/archie-core/issues/165","source_system":"github:https://github.com/samcharles93/archie-core/issues/165:165","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-1786637493519-143-983868b0","title":"Idempotent tool classification set","description":"Define and maintain a classification set of idempotent (read-only) tools. These tools can be safely retried and run in parallel. The set should be extensible via registration metadata. Classification feeds into dispatch gating, guardrail decisions, and budget enforcement.","status":"closed","priority":2,"issue_type":"task","created_at":"2026-08-08T14:38:24Z","updated_at":"2026-08-08T14:38:27Z","closed_at":"2026-08-08T14:38:28Z","external_ref":"https://github.com/samcharles93/archie-core/issues/164","source_system":"github:https://github.com/samcharles93/archie-core/issues/164:164","metadata":null,"labels":["task"],"dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/docs/prds/progressive-tool-disclosure.md b/docs/prds/progressive-tool-disclosure.md new file mode 100644 index 000000000..fa234001c --- /dev/null +++ b/docs/prds/progressive-tool-disclosure.md @@ -0,0 +1,127 @@ +# Progressive tool disclosure (bridge tools) — wiring + +**Status:** Implemented (wiring landed) +**Date:** 2026-08-15 +**Compound:** the "keep the LLM tool schema small, give full access on demand" work (issue #167) + +## Decision + +The bridge-tool pattern is **already implemented and tested** in +`internal/tools/disclosure.go` (`tool_search`, `tool_describe`, `tool_call` ++ `ContextPressureGate` + `DisclosureMode`, section 17.14/17.15) — but it is +**never wired into the daemon**. `BridgeTools` and `ContextPressureGate` are +referenced only in `disclosure_test.go`. This task is therefore a **wiring** +task, not a feature build. + +Wire the existing bridge into the per-chat-turn toolset: + +1. **Compose a per-turn registry** seeded from the base registry plus the + per-turn extra tools, register the bridge tools into it, and hand it to both + the bridge handlers and the `ContextPressureGate`. +2. **Run the gate in `chatGenerateOptions`** (`internal/app/archied/main.go:69`) + so it decides full-vs-bridge disclosure per turn, and build the + `core.ToolSet` from the gate's filtered output. +3. **Thread the model's context window** into the preparation seam so the gate + has a real `ContextWindowSize` (it disables itself at 0, falling back to + full disclosure). + +## Why the naive "register extras into the base registry" is wrong + +`BuildToolSetFrom` (`internal/agentexec/toolset.go:170`) documents the invariant: + +> the task tools carry the calling gateway's identity, so there is one set of +> them per gateway and they **cannot live in the process-wide registry**. + +This is confirmed by wiring: gateways are per-channel +(`telegram_setup.go:291,308` build a `TurnRunner` per channel), and the extra +tools (`task_*`, `session_*`, `dashboard_*`) close over that channel's identity +via `TurnRunnerConfig` (`turn.go:66`). Registering them into `b.toolReg` would +let channel A's session/identity-bound tools be invoked by channel B — a real +cross-channel privilege bug. The bridge handlers iterate `reg.All()` +(`disclosure.go:53,107,146`), so the extras must be discoverable; the fix is a +**per-turn composed registry**, not a mutation of the process-wide one. + +## Shape of the change + +### 1. Per-turn composed registry + gate inside `chatGenerateOptions` + +Replace the current base-set + extra-set merge (`main.go:90-100`) with a single +composed-registry pass: + +```go +// new helper, in internal/tools/disclosure.go or the archied wiring package +func ComposeForTurn(reg *tools.Registry, extra []tools.ToolEntry) (*tools.Registry, error) { + composed := tools.NewRegistry() + for _, e := range reg.All() { + if err := composed.Register(e); err != nil { return nil, err } + } + for _, e := range extra { + if err := composed.Register(e); err != nil { return nil, err } + } + if _, err := composed.RegisterBatch(tools.BridgeTools(composed)); err != nil { + return nil, err + } + return composed, nil +} +``` + +`chatGenerateOptions` then: + +```go +composed, err := ComposeForTurn(registry, extra) +// ... +gate := tools.NewContextPressureGate(contextWindow) +gate.SetAlwaysVisible(...) // e.g. session/session_resume, task/task_list +disclosed := gate.FilterTools(composed) +toolSet, err := agentexec.BuildToolSetFrom(disclosed, toolOpts) +``` + +`FilterTools` (`disclosure.go:327`) already returns `all` in full mode and +`bridge + always-visible` in bridge mode, and `BuildToolSetFrom` re-applies +availability/approval/schema rules, so the two layers compose cleanly. + +### 2. Thread context window through the preparation seam + +`ContextPressureGate` disables at `ContextWindowSize == 0`. The model context +window is resolved in `TurnRunner.prepareTurn` (`turn.go:303-306`) but is not +passed to `TurnModel.Prepare`. Extend the seam: + +```go +type TurnPrepareContext struct { + Model string + Extra []tools.ToolEntry + ContextWindow int // model's context window in tokens; 0 = gate disabled +} +``` + +`TurnModel.Prepare(ctx, context TurnPrepareContext)`; `prepareTurn` fills +`ContextWindow` from `modelDetails.ContextWindow`. This touches one interface +(`turn.go:18`), one production impl (`chat_turn_model.go:40`), and the test +mock (`turn_test.go:21`). + +### 3. Bridge-handler parity note + +`bridgeCallHandler` calls `e.Handler` directly (`disclosure.go:158`), bypassing +`toolExecute` — so a `tool_call` invocation does **not** apply `CapPayload` / +`MaxResultSizeChars` spilling or `OnToolCall` reporting, and it pre-refuses +`RequiresApproval` tools (`disclosure.go:150-152`). This is acceptable for the +first wiring (the bridge is read-discover/describe plus a guarded call), but a +later hardening should route the invoked tool through the same +cap/approval path the model's direct call uses. Recorded as a follow-up, not a +blocker for this task. + +## Files touched + +- `internal/app/archied/main.go` — `chatGenerateOptions` composes + gates. +- `internal/app/archied/chat_turn_model.go` — `Prepare` accepts `TurnPrepareContext`. +- `internal/gateway/turn.go` — `TurnModel.Prepare` signature; `prepareTurn` fills context window. +- `internal/gateway/turn_test.go` — update the `turnTestModel.Prepare` mock. +- `internal/tools/disclosure.go` — add `ComposeForTurn` helper (or place in archied). + +## Out of scope / follow-ups + +- Delegate `tool_call` through `toolExecute` for cap/approval/observability parity. +- Cover the compose-and-gate path with tests (compressed footprint under a + small window; always-visible minus bridge margin). +- Reconcile any `ContextPressureGate` mode with the compression budget already + computed in `prepareTurn` (`turn.go:311-315`). diff --git a/internal/app/archied/chat_turn_model.go b/internal/app/archied/chat_turn_model.go index 42ecc6c6d..d0536ef12 100644 --- a/internal/app/archied/chat_turn_model.go +++ b/internal/app/archied/chat_turn_model.go @@ -39,10 +39,9 @@ func newChatTurnModel( func (m *chatTurnModel) Prepare( ctx context.Context, - model string, - extra []tools.ToolEntry, + req gateway.TurnPrepareContext, ) (gateway.PreparedTurnModel, error) { - options, err := chatGenerateOptions(ctx, nil, m.registry, m.maxSteps, m.limits, extra) + options, err := chatGenerateOptions(ctx, nil, m.registry, m.maxSteps, m.limits, req.Extra, req.ContextWindow) if err != nil { return nil, err } @@ -52,7 +51,7 @@ func (m *chatTurnModel) Prepare( } return &preparedChatTurnModel{ llm: m.llm, - model: model, + model: req.Model, options: options, toolInfo: toolSummaries(options.Tools), toolTokens: gateway.EstimateTokens(string(toolSchema)), diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index d39adb163..c0fbdc10d 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -12,7 +12,6 @@ import ( "flag" "fmt" "log/slog" - "maps" "net" "net/http" "net/http/httptest" @@ -82,20 +81,30 @@ func chatGenerateOptions( maxSteps int, limits agentexec.ToolLimits, extra []tools.ToolEntry, + contextWindow int, ) (core.GenerateOptions, error) { toolOpts := limits.Options() if approval := gateway.ApprovalFromContext(ctx); approval != nil { toolOpts.Approval = approval } - toolSet, err := agentexec.BuildToolSet(registry, toolOpts) + + // Progressive tool disclosure: compose the base registry with the per-turn + // extras into a turn-local registry (extras are identity-bound and cannot + // live in the process-wide registry), then let the ContextPressureGate + // decide whether to serve the full arsenal directly or fall back to the + // bridge tools. The bridge tools are never registered process-wide, so they + // stay inside this composed, per-turn registry. + composed, err := tools.ComposeForTurn(registry, extra) if err != nil { return core.GenerateOptions{}, err } - extraSet, err := agentexec.BuildToolSetFrom(extra, toolOpts) + gate := tools.NewContextPressureGate(contextWindow) + gate.Evaluate(composed.All()) + toolSet, err := agentexec.BuildToolSetFrom(gate.FilterTools(composed), toolOpts) if err != nil { return core.GenerateOptions{}, err } - maps.Copy(toolSet, extraSet) + if maxSteps <= 0 { maxSteps = defaultChatMaxSteps } diff --git a/internal/app/archied/main_test.go b/internal/app/archied/main_test.go index fa83edbc7..207d56876 100644 --- a/internal/app/archied/main_test.go +++ b/internal/app/archied/main_test.go @@ -264,7 +264,7 @@ func TestChatGenerateOptionsIncludesToolsAndMultipleSteps(t *testing.T) { } messages := []chat.Message{{Role: chat.RoleUser, Content: "remember this"}} - options, err := chatGenerateOptions(context.Background(), messages, registry, 0, agentexec.ToolLimits{}, nil) + options, err := chatGenerateOptions(context.Background(), messages, registry, 0, agentexec.ToolLimits{}, nil, 0) if err != nil { t.Fatal(err) } @@ -290,7 +290,7 @@ func TestChatGenerateOptionsReportsInvalidToolSchemas(t *testing.T) { }); err != nil { t.Fatal(err) } - if _, err := chatGenerateOptions(context.Background(), nil, registry, 0, agentexec.ToolLimits{}, nil); err == nil { + if _, err := chatGenerateOptions(context.Background(), nil, registry, 0, agentexec.ToolLimits{}, nil, 0); err == nil { t.Fatal("chatGenerateOptions(context.Background(),) error = nil, want invalid tool schema error") } } @@ -298,8 +298,47 @@ func TestChatGenerateOptionsReportsInvalidToolSchemas(t *testing.T) { // TestChatGenerateOptionsHonoursConfiguredMaxSteps keeps the step budget // deployment-controlled. A cap that cannot be raised without a rebuild is // the situation this replaced. +func TestChatGenerateOptionsProgressiveDisclosure(t *testing.T) { + registry := tools.NewRegistry() + if err := registry.Register(tools.ToolEntry{ + Name: "big-tool", + Description: strings.Repeat("x", 800), + Handler: func(context.Context, map[string]any) (any, error) { return "ok", nil }, + }); err != nil { + t.Fatal(err) + } + + // A tiny context window drives the gate into bridge mode: only the three + // bridge tools are disclosed, and the full-schema tool is hidden. + options, err := chatGenerateOptions(context.Background(), nil, registry, 0, agentexec.ToolLimits{}, nil, 1000) + if err != nil { + t.Fatal(err) + } + if len(options.Tools) != 3 { + t.Fatalf("bridge mode Tools = %#v, want the 3 bridge tools", options.Tools) + } + if _, ok := options.Tools["big-tool"]; ok { + t.Error("bridge mode should not disclose the full-schema big-tool") + } + if _, ok := options.Tools["tool_search"]; !ok { + t.Error("bridge mode should disclose tool_search") + } + + // A large context window keeps full disclosure: the real tool is present. + options, err = chatGenerateOptions(context.Background(), nil, registry, 0, agentexec.ToolLimits{}, nil, 100_000) + if err != nil { + t.Fatal(err) + } + if _, ok := options.Tools["big-tool"]; !ok { + t.Error("full mode should disclose the real tool") + } + if len(options.Tools) != 1 { + t.Errorf("full mode Tools length = %d, want 1 (bridge tools must not leak)", len(options.Tools)) + } +} + func TestChatGenerateOptionsHonoursConfiguredMaxSteps(t *testing.T) { - options, err := chatGenerateOptions(context.Background(), nil, tools.NewRegistry(), 250, agentexec.ToolLimits{}, nil) + options, err := chatGenerateOptions(context.Background(), nil, tools.NewRegistry(), 250, agentexec.ToolLimits{}, nil, 0) if err != nil { t.Fatal(err) } diff --git a/internal/gateway/turn.go b/internal/gateway/turn.go index 65f3342f0..cf9b11a37 100644 --- a/internal/gateway/turn.go +++ b/internal/gateway/turn.go @@ -12,11 +12,20 @@ import ( "github.com/samcharles93/archie-core/internal/tools" ) +// TurnPrepareContext carries the per-turn inputs the model seam needs to build +// a generation plan: the active model, the per-turn extra (identity-bound) +// tools, and the model's context window used for progressive tool disclosure. +type TurnPrepareContext struct { + Model string + Extra []tools.ToolEntry + ContextWindow int +} + // TurnModel prepares provider-specific tools and executes one completed chat // generation. The gateway owns the conversation lifecycle; the composition // root implements this seam over the selected model runtime. type TurnModel interface { - Prepare(ctx context.Context, model string, extra []tools.ToolEntry) (PreparedTurnModel, error) + Prepare(ctx context.Context, req TurnPrepareContext) (PreparedTurnModel, error) } // PreparedTurnModel is a provider-specific generation plan. Preparation is @@ -277,7 +286,15 @@ func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, msg Mess // UI only: a non-web channel has no dashboard to point at. extraTools = append(extraTools, PageIndexTools(r.Channel)...) modelName := r.Models.ActiveModel() - prepared, err := r.Model.Prepare(ctx, modelName, extraTools) + modelDetails := ModelDetails{} + if detailed, ok := r.Models.(DetailedModelManager); ok { + modelDetails, _ = detailed.ModelDetails(modelName) + } + prepared, err := r.Model.Prepare(ctx, TurnPrepareContext{ + Model: modelName, + Extra: extraTools, + ContextWindow: modelDetails.ContextWindow, + }) if err != nil { return preparedTurn{}, fmt.Errorf("build chat model: %w", err) } @@ -297,10 +314,6 @@ func (r *TurnRunner) prepareTurn(ctx context.Context, sessionID string, msg Mess Now: time.Now(), Page: msg.Page, }) - modelDetails := ModelDetails{} - if detailed, ok := r.Models.(DetailedModelManager); ok { - modelDetails, _ = detailed.ModelDetails(modelName) - } compression, err := CompressionConfigForModel( modelDetails, EstimateTokens(systemPrompt)+prepared.ToolSchemaTokens(), diff --git a/internal/gateway/turn_test.go b/internal/gateway/turn_test.go index 95092864c..12039ec94 100644 --- a/internal/gateway/turn_test.go +++ b/internal/gateway/turn_test.go @@ -18,8 +18,8 @@ type turnTestModel struct { gotExtra []tools.ToolEntry } -func (m *turnTestModel) Prepare(_ context.Context, _ string, extra []tools.ToolEntry) (PreparedTurnModel, error) { - m.gotExtra = append([]tools.ToolEntry(nil), extra...) +func (m *turnTestModel) Prepare(_ context.Context, req TurnPrepareContext) (PreparedTurnModel, error) { + m.gotExtra = append([]tools.ToolEntry(nil), req.Extra...) if m.prepareErr != nil { return nil, m.prepareErr } diff --git a/internal/tools/disclosure.go b/internal/tools/disclosure.go index 8ce50d6fe..210b15372 100644 --- a/internal/tools/disclosure.go +++ b/internal/tools/disclosure.go @@ -228,6 +228,33 @@ func BridgeTools(reg *Registry) []ToolEntry { } } +// ComposeForTurn builds a per-turn Registry that combines the base registry's +// tools, the per-turn extra tools, and the three bridge tools. The returned +// registry is detached from the process-wide registry: extra tools are +// per-gateway identity-bound (see agentexec.BuildToolSetFrom) and must never be +// registered globally, so composing them into a turn-local registry is the only +// way the bridge handlers (which enumerate reg.All) can discover and invoke +// them. +func ComposeForTurn(reg *Registry, extra []ToolEntry) (*Registry, error) { + composed := NewRegistry() + if reg != nil { + for _, e := range reg.All() { + if err := composed.Register(e); err != nil { + return nil, err + } + } + } + for _, e := range extra { + if err := composed.Register(e); err != nil { + return nil, err + } + } + if err := composed.RegisterBatch(BridgeTools(composed)); err != nil { + return nil, err + } + return composed, nil +} + // --------------------------------------------------------------------------- // 17.15 -- Context-pressure threshold gating // --------------------------------------------------------------------------- @@ -333,7 +360,17 @@ func (g *ContextPressureGate) FilterTools(reg *Registry) []ToolEntry { all := reg.All() if mode == DisclosureFull { - return all + // Full disclosure serves the real arsenal directly. Bridge tools are + // the on-demand fallback -- they are only exposed under context + // pressure (bridge mode). Leaking them into full mode would inflate + // the toolset the model must carry for no benefit. + out := make([]ToolEntry, 0, len(all)) + for _, e := range all { + if !IsBridgeTool(e.Name) { + out = append(out, e) + } + } + return out } // Bridge mode: only bridge tools + always-visible tools. diff --git a/internal/tools/disclosure_test.go b/internal/tools/disclosure_test.go index 6ac059795..517ee6f66 100644 --- a/internal/tools/disclosure_test.go +++ b/internal/tools/disclosure_test.go @@ -299,6 +299,58 @@ func TestBridgeToolsRegistration(t *testing.T) { } } +func TestComposeForTurnMergesBaseExtrasAndBridge(t *testing.T) { + base := NewRegistry() + _ = base.Register(ToolEntry{Name: "memory_search", Toolset: "memory", Handler: noopHandler, Description: "Search memory"}) + extra := []ToolEntry{ + {Name: "session_resume", Toolset: "session", Handler: noopHandler, Description: "Resume a session"}, + } + + composed, err := ComposeForTurn(base, extra) + if err != nil { + t.Fatalf("ComposeForTurn: %v", err) + } + + names := make(map[string]bool) + for _, e := range composed.All() { + names[e.Name] = true + } + + if !names["memory_search"] { + t.Error("composed registry missing base tool memory_search") + } + if !names["session_resume"] { + t.Error("composed registry missing extra tool session_resume") + } + for _, bridge := range []string{BridgeToolSearch, BridgeToolDescribe, BridgeToolCall} { + if !names[bridge] { + t.Errorf("composed registry missing bridge tool %q", bridge) + } + } + + // The bridge handlers must be wired to the composed registry so they can + // discover both base and extra tools. + if _, ok := composed.Get(BridgeToolSearch); !ok { + t.Errorf("bridge tool %q not present in composed registry", BridgeToolSearch) + } +} + +func TestComposeForTurnDoesNotMutateBaseRegistry(t *testing.T) { + base := NewRegistry() + _ = base.Register(ToolEntry{Name: "memory_search", Handler: noopHandler, Description: "Search memory"}) + + if _, err := ComposeForTurn(base, nil); err != nil { + t.Fatalf("ComposeForTurn: %v", err) + } + + if _, ok := base.Get(BridgeToolSearch); ok { + t.Error("ComposeForTurn must not register bridge tools into the base registry") + } + if got := len(base.All()); got != 1 { + t.Errorf("base registry mutated: got %d tools, want 1", got) + } +} + func TestNewContextPressureGate(t *testing.T) { g := NewContextPressureGate(100_000)