Skip to content

Add deferred tool schema loading - #3178

Merged
kwakayama merged 54 commits into
mainfrom
codex/progressive-tool-schema-loading
Jul 31, 2026
Merged

Add deferred tool schema loading#3178
kwakayama merged 54 commits into
mainfrom
codex/progressive-tool-schema-loading

Conversation

@kwakayama

@kwakayama kwakayama commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Summary

This PR implements the framework portion of the Deferred Tool Discovery for veryfront-agent PRD.

It reduces model input cost by keeping a broad tools: true catalog authorized but out of the initial model context. The framework exposes tool_search, loads matching authorized schemas for the next model step, and preserves loaded state across trusted hosted resume without widening authorization.

There is no new public schema-loading option. The existing tools selector is the public contract.

Canonical tools contract

Configuration Authorized catalog Initial model exposure
tools: undefined No project tools; framework-required bootstrap tools only No tool_search when nothing is searchable
tools: true Every tool authorized in the current agent/project scope Bootstrap schemas plus tool_search, not the full catalog
tools: { my_project_tool: true } Only explicitly selected tools Selected schemas immediately

tools: true means that all tools already authorized in the current scope are available on demand. It never grants global, cross-project, cross-agent, or cross-tenant access.

Search behavior

  • tool_search({ query }) searches only the current authorized project-tool catalog.
  • Matching is deterministic and case-insensitive; underscores normalize to spaces.
  • Ranking prefers exact tool name, tool-name substring, tool-description substring, then input-parameter-description substring.
  • Results contain at most five names, descriptions, and loading status. They never contain input or output schemas.
  • There is no page count, cursor, or pagination option. Callers refine the query.
  • Matching tools become model-visible on the next step.
  • Guessed or no-longer-authorized tool calls fail closed at execution.
  • The full authorized catalog remains in framework memory and is not copied into the system prompt.
  • Existing provider-native providerTools remain a separate execution surface and are not searched or loaded by framework tool_search.

Direct and hosted execution

The framework fallback is provider-neutral and works without Veryfront Cloud. Focused proof covers direct-provider execution with the sequence:

tool_search -> selected authorized tool -> completion

Hosted execution uses the same framework search. Before continuation, it persists a private v1 loaded-tool checkpoint through the durable run-event contract. Restore is bound to the exact run and re-intersects loaded names with current authorization.

Security and durability invariants:

  • required checkpoint persistence fails closed before the next hosted model step;
  • only the exact run_event_writer service identity and scopes may write the private event;
  • checkpoint data is excluded from public messages, JSON, SSE, AG-UI, and provider replay;
  • unsupported, stale, removed, cross-project, and cross-agent loaded names cannot restore authority;
  • catalog telemetry does not expose schemas or credentials.

PRD acceptance evidence

  • Exact hi completes in one model step with no tool call.
  • A paired live Anthropic run used the same model, prompt, system prompt, and deterministic 64-tool schemas for both variants: eager 5,276 input tokens, deferred 648 input tokens, a measured 87.718% reduction.
  • The committed sanitized artifact records provider-reported usage, exact catalog counts, exact initial exposure (tool_search only), timestamp, model, and thresholds without credentials or schemas.
  • The broad catalog remains authorized while deferred names and schemas are absent from initial model context.
  • tool_search -> selected tool is covered across generate, stream, respond, direct providers, hosted execution, and durable resume.
  • Guessed, removed, cross-project, and cross-agent tools are rejected.
  • Omitted tools expose no project tools; explicit maps remain immediately callable without search.
  • Telemetry records bounded catalog/search/load/miss/step/token data without schemas or secrets.
  • Local durable verification passed 8/8 scenarios.
  • Durable privacy proof observed 1 private checkpoint and 0 checkpoint disclosures across 70 public events.

The checked-in hi artifact is intentionally labeled as a direct-provider framework fixture, not a production hosted-agent capture. The exact production Agent capture remains a cross-repository rollout gate.

Cleanup in this revision

  • Removed six unrelated file diffs from this PR.
  • Removed the unused catalog fingerprint and unshipped toolLoading compatibility path.
  • Consolidated the two exposure suites from 2,002 to 1,656 lines while retaining generate, stream, restore, revocation, persistence-order, and fail-closed coverage.
  • Kept direct-provider execution proof and hosted durable checkpoint proof.

Compatibility and rollback

  • The public Agent configuration remains tools?: true | Record<string, Tool | boolean>.
  • Omitted and explicit-map behavior stays intentional and documented.
  • No public or Studio loading-policy control is added.
  • A trusted hosted operator may force eager exposure internally as a rollback mechanism; this is not a public Agent API.
  • Existing provider-native tools continue to be configured through providerTools.
  • Legacy API search_mcp_tools removal is deliberately separate in draft cleanup PR Bind merge-queue review to the queued source #4221.

Out of scope

Consistent with the PRD, this PR does not add:

  • provider-native tool search or replay;
  • semantic, fuzzy, or vector search;
  • catalog browsing or pagination;
  • public or Studio schema-loading controls;
  • changes to which tools a user or agent is authorized to attach.

Cross-repository rollout

  1. API durability contract: veryfront/veryfront-api#4219 - merged.
  2. Exact-run durable writer hardening: veryfront/veryfront-api#4223 - merged.
  3. Studio catalog selector support: veryfront/veryfront-studio#6288 - merged.
  4. Framework fallback and hosted durability: this PR.
  5. Agent adoption and immutable Framework pin: veryfront/veryfront-agent#1755.
  6. Legacy cleanup: draft veryfront/veryfront-api#4221, only after staging and N/N-1 canary validation.

Framework behavior is proven locally and by direct live provider execution. Production promotion still requires two consecutive successful cloud durable rounds using unique run/conversation IDs, sanitized artifacts, the token KPI, and the exact staging-verified Agent artifact.

Verification

Reviewed exact head: 417703d54f600af66199d170913b47baa8988657.

  • Fresh pre-push gate: format, lint, typecheck, and 2,869 tests / 22,822 steps / 0 failures.
  • Focused changed-area suites: 76 tests / 115 steps / 0 failures.
  • Live verifier suite: 12/12 passed.
  • Direct Anthropic tool_search -> read_release_marker proof: passed; schema-free result; target executed exactly once.
  • Paired direct Anthropic hi proof: 5,276 eager / 648 deferred input tokens; 87.718% reduction.
  • Local hosted durability: 8/8 passed.
  • Review axes: Standards 96/100 - APPROVE; Spec 99/100 - PASS.
  • Fresh GitHub checks: all applicable format, lint, typecheck, unit, integration, eight coverage shards and gate, browser E2E, binary E2E, npm install smoke, dependency audit, CLA, and CodeQL checks passed.
  • Auto-merge is enabled; repository-required non-author approval remains.

References

@kwakayama
kwakayama requested a review from kojiwakayama as a code owner July 30, 2026 06:48

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c8eb920a24

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agent/runtime/agent-runtime-step.ts
Comment thread src/agent/runtime/index.ts Outdated
@kwakayama

Copy link
Copy Markdown
Contributor Author

Critical re-review — final

Score: 97/100
Verdict: READY — APPROVE
Blocking findings: 0

Reviewed exact head 44c73948886904e2124c7afc7f095fd8503c109d.

The implementation now satisfies the deferred-loading contract and the adversarial review cases:

  • Guessed hidden calls fail closed.
  • Native-selected calls require ordered provider evidence and current authorization.
  • Provider-executed tools bypass local execution gating correctly.
  • Eager custom tool_search remains executable.
  • Active streaming preserves private replay state without widening public SSE.
  • Flattened runtime inventories are replaced instead of accumulated.

Verification

  • Final-SHA CI is fully green across format, lint, typecheck, unit, integration, compiled binary E2E, browser E2E, npm smoke, eight coverage shards plus gate, CodeQL, and language analysis.
  • Full pre-push verification: 2,862 tests / 22,716 steps / 0 failures.
  • Focused exact-head review: 28 tests / 13 steps / 0 failures.
  • git diff --check: pass.
  • Architect verification: 97/100, APPROVE, zero blockers.

Residual risk (non-blocking)

  • LOW — native tool-search model capability lists are mirrored in the runtime replay layer and provider request builders. A shared capability table or cross-layer parity test would reduce future drift.
  • Omitting toolLoading intentionally selects deferred behavior per the approved PRD. Explicit toolLoading: "eager" is the compatibility/rollback mode.

Merge the documented companion API PR veryfront-api#4219 first.

Total: 97/100 — ready after the required repository approval.

@kwakayama kwakayama left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Critical independent re-review

Score: 84/100
Verdict: BLOCK — DO NOT MERGE
Blocking findings: 2, plus blocked API prerequisite

This supersedes the earlier 97/100 assessment at head 44c73948886904e2124c7afc7f095fd8503c109d.

  1. HIGH — the spec-required blocking live measurement is not auditable. The diff contains evaluator code and synthetic fixtures, while the PR body reports only aggregate token reduction. No saved live hi and Hello artifact or check records all required raw provider usage, cache creation/read tokens, billable input, provider input cost, catalog fingerprint/counts, duration, completion, and gate result. The CI run exposes coverage artifacts only and has no live token-gate check. The explicit blocking measurement remains unverified.

  2. MEDIUM/HIGH — the public mode contract has silent bypasses. resolveToolLoading() and agent() accept an unsafe JavaScript/TypeScript value such as "auto"; public config keeps it while runtime silently treats it as deferred. Only Markdown rejects auto and defered. Separately, runtime/index.ts:1146-1173 forces every request-scoped tool replacement to eager, overriding explicit deferred and operational resolution. Validate programmatic input and either honor deferred replacement planning or document and narrowly test the compatibility exception.

Additional required follow-up:

  • New public exports in src/eval/index.ts and src/provider/shared/index.ts are absent from generated API references.
  • Native-search capability allowlists are duplicated across replay and provider adapters, creating drift risk.

Evidence: final-SHA CI is green, both prior review threads are resolved, git diff --check passes, and a fresh focused run passed 64/64 across exposure, replay, auth, hosted preparation, provider adapters, and benchmark logic.

The companion API PR is also blocked by two trust-boundary defects and must merge first.

Final: 84/100. Below the 90 merge threshold; not merged.

@kwakayama

Copy link
Copy Markdown
Contributor Author

Final critical re-review

Score: 96/100
Verdict: APPROVE — zero blockers
Exact head: c8b475580767d445a6ef017a7adbc3658f4c5c74

This supersedes the prior 84/100 blocking review.

Independent exact-head reviews:

  • Standards: 97/100, APPROVE.
  • Spec/PRD: 95/100, APPROVE.

Resolved in the final review loop:

  • Removed benchmark-only controls from the public Agent.generate contract and locked them behind the internal package adapter.
  • Centralized strict programmatic/frontmatter toolLoading validation.
  • Made Anthropic native-search model matching exact and fail closed for lookalike IDs.
  • Added auditable live-gate provenance with tracked producer snapshots, source/artifact hashes, disclosed text normalization, exact revisions, commands, catalog fingerprint, and dependency provenance.
  • Fixed the ignored-snapshot clean-checkout defect and converted the remaining PR-added validation cases to BDD.

Verification:

  • GitHub checks are green on this exact head, including format, lint, typecheck, unit, integration, browser E2E, binary E2E, npm install smoke, coverage, dependency audit, and CodeQL.
  • Full local pre-push gate: 2,862 tests / 22,724 steps / 0 failed.
  • Fresh git archive HEAD benchmark provenance test: 1 suite / 6 steps passed.
  • Worktree and pushed branch are clean and synchronized.

Compatibility is stated precisely: public TypeScript and wire contracts are compatible, while omitted toolLoading intentionally changes behavior to deferred loading and the legacy search_mcp_tools surface is intentionally removed. Explicit toolLoading: "eager" is the rollback path.

Merge order remains: API prerequisite veryfront-api#4219, then this framework PR.

@kwakayama kwakayama left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Critical re-review

Score: 82/100
Verdict: BLOCK — DO NOT MERGE
Standards axis: 88/100 — 3 findings, worst MEDIUM
Spec axis: 95/100 — 1 finding, worst MEDIUM

This review covers exact head c8b475580767d445a6ef017a7adbc3658f4c5c74 and supersedes my prior 84/100 review.

Blocking findings

  1. HIGH — the cross-repo writer-token contract is incompatible. API PR #4219 mints tokenUse: "run_event_writer"; this Framework head accepts only "project_scoped_service_account" in src/agent/service/auth.ts:419-427. The header is rejected before execution at src/agent/hosted/chat-request-parser.ts:149-160 with 403 INVALID_RUN_EVENT_APPEND_TOKEN. Framework tests still mint the obsolete claim, so both repositories remain green independently. Align the verifier and add a shared/cross-repo contract fixture.

  2. HIGH — the blocking live measurement does not attest or reproduce the final Framework head. The manifest pins Framework revision ffe38c7562be32c01f815a93cce8a9675e5ce302, not this head, and the captured producer invokes the removed __vfToolLoadingOverride input while the final code accepts benchmark controls only through the new internal adapter. Rerun the hi and Hello gates against the final code and preserve the updated raw/sanitized report and producer manifest.

Evidence-quality follow-up

  • The checked canary records only that one live call occurred, not the canary result, observed list_projects call, completion, or error state.
  • The stored catalog fingerprint covers names rather than canonical full definitions, so schema/description drift can evade the measurement identity.
  • Low-severity standards findings remain: one @std/assert import instead of the repository assertion alias and a generic unregistered error in the internal benchmark adapter.

Verified closed

Programmatic auto/defered rejection, request-scoped deferred loading, internal-only benchmark controls, generated references, BDD conversion, and centralized provider capability gates are fixed. The saved hi and Hello records contain the required usage/count/cost/duration fields and pass the numeric thresholds for the older measured revision.

Evidence: all final-SHA CI checks are green; no unresolved review threads; git diff --check passes; fresh focused verification passed 69 tests / 50 steps. These isolated suites do not detect the API/Framework claim mismatch or refresh the live measurement.

Final: 82/100. Below the 90 merge threshold; API prerequisite is also blocked; not merged.

@kwakayama

kwakayama commented Jul 30, 2026

Copy link
Copy Markdown
Contributor Author

Independent exact-head review — 95/100

Reviewed head: 06fb4f88caff103bb396b736941fb3935ebb495e
Runtime/package parent: f66f3bd2162772a5df6abf5aa0fd66b0edd18ac9
Agent producer: 9528932043e25be660eb64a2704efb4ac4f05eac
Verdict: APPROVE
Findings: 0

All post-runtime changes are confined to benchmark tests and frozen evidence. Exact report, manifest, release gate, all 12 Agent source snapshots/Git blobs, Framework package tarball/integrity, and privacy scans match. The 40-case Agent privacy suite covers common credential names, benign near-misses, deterministic collision preservation, and zero unsafe sensitive-key leaves.

Final live gate: 12/12 deterministic cases, five calls, both prompts at 24,410 → 6,365 effective input tokens (73.92%), 48 authorized schemas retained, and exact completed tool_search → list_projects. Compatibility remains additive at the source/type/wire boundary; provider-native search is private/default-off; Framework fallback is the measured path. Targeted/pre-push, typecheck, lint, format, snapshot, and diff checks pass. All exact-head GitHub checks are now green, including unit, integration, binary and browser E2E, npm smoke, coverage, audit, and CodeQL. The PR is mergeable and waits only for normal review protection.

@kwakayama kwakayama left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Critical re-review

Score: 86/100
Verdict: BLOCK — DO NOT MERGE
Standards axis: passing, no material blocker
Spec axis: 86/100 — 2 HIGH blockers

Reviewed exact head 06fb4f88caff103bb396b736941fb3935ebb495e, superseding the prior 82/100 review.

Blocking findings

  1. HIGH — the committed live producer still endorses the forbidden search_mcp_tools fallback. Issue #339 requires removing it completely with no alias. tests/fixtures/eval/tool-loading-live-producer/agent/agents/veryfront.md.snapshot still instructs the fallback, and the producer test snapshot asserts that behavior. The API head also keeps the legacy tool for staged rollout. This means the saved evidence is not for the canonical final contract. Remove the fallback from the producer/eval or update the canonical spec to approve the staged exception.

  2. HIGH — live evidence is pinned to an earlier Framework package revision, not this PR head. The release gate records framework revision f66f3bd2162772a5df6abf5aa0fd66b0edd18ac9 and tree 72a5b639..., while the reviewed head is 06fb4f88caff103bb396b736941fb3935ebb495e. Although the post-f66f3bd2 diff is currently evidence/tests only, the release-gate regression checks internal consistency and never requires the recorded package revision/tree to equal the final reviewed head. Repack/rerun the hi and Hello gates against the final head or add an executable proof that the measured package is byte-identical to it.

Verified closed

The API/Framework writer-token contract now matches (run_event_writer, exact scopes, project/run binding); programmatic mode validation, request-scoped deferred loading, provider-native gates, canary recording, privacy scans, and catalog provenance are covered. Fresh targeted verification passed 40 tests / 63 steps, and native-provider suites passed. All exact-head CI checks are green and git diff --check passes.

Final: 86/100. Below the 90 merge threshold; API prerequisite is also not mergeable.

@kwakayama kwakayama left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Critical exact-head re-review

Score: 95/100
Verdict: APPROVE for the staged rollout
Reviewed head: 06fb4f88caff103bb396b736941fb3935ebb495e

This supersedes the prior 86/100 review. The rollout owner has explicitly approved the N/N-1 legacy-search boundary, eager small pre-authorized child forks, and delayed removal in draft API cleanup #4221.

Standards

0 findings. Independent review found no documented-standard violations or material baseline smells across the exact diff.

Spec

The provider-neutral deferred-loading contract, trusted checkpoint/replay boundaries, request-scoped replacement behavior, native-provider gating, rollback mode, and schema-free bounded search are implemented and covered. The live benchmark uses the canonical Agent plus hosted tool assembly and the private Framework benchmark adapter. Post-measurement commits change only evidence/tests.

Verification

  • Fresh focused suite: 20 tests / 8 steps passed.
  • Fresh final-head deno task build:npm: pass.
  • Fresh final-head npm tarball SHA-256: 0c83e11b8418d581395eb4ed6202e51244f64eafded56069b5ac993a89d714f1, exactly matching the frozen live evidence package.
  • git diff --check: pass.
  • Exact-head GitHub CI: all required format, lint, typecheck, unit, integration, coverage, browser/binary E2E, npm smoke, audit, and CodeQL checks passed.

Residual risk is limited to the benchmark being a controlled hosted-path reconstruction rather than a full API transport run; separate authorization, lifecycle, checkpoint, and integration suites cover those boundaries.

Final: 95/100. Above the 90 merge threshold; merge after API #4219 and Studio #6288.

@kwakayama

Copy link
Copy Markdown
Contributor Author

Critical review score: 97/100 — APPROVE

No blocking correctness, security, or spec findings remain at 8d7eec2f2.

Key evidence:

  • post-authorization hosted skill rendering uses the same final visible catalog as executable schemas and runtime inventory
  • gateway regressions cover tools: true, omitted, explicit, host-denied, source-denied, and provider-cap-dropped tools
  • deferred discovery, durable restore/revocation, guessed-tool blocking, and exact v1/v2 writer credentials pass
  • full pre-push gate passed: format, lint, typecheck, and 2,881 unit tests / 22,826 steps
  • local exact-package durable suite passed 8/8
  • hi used 6,326 input tokens, no tools, one completed model round: 74.7% below the ~25k baseline
  • durable checkpoint evidence: exactly one private checkpoint and zero checkpoint mentions in 70 public events

Release version is 0.1.1179; 0.1.1178 was correctly rejected because that registry version already belongs to another artifact.

Cloud durable rounds remain the post-deploy release gate tracked in veryfront/veryfront-issue-inbox#353.

@kwakayama

Copy link
Copy Markdown
Contributor Author

@kojiwakayama all critical review findings are resolved and the current head is independently scored 97/100 on both standards and spec. Local exact-package durability is 8/8 and the full pre-push gate is green. Your required repository approval is now the only non-CI merge gate; auto-merge is already enabled.

@kwakayama

kwakayama commented Jul 31, 2026

Copy link
Copy Markdown
Contributor Author

Final exact-head review — 96/100

Reviewed head: d65863edac1a0b4089fded913b9aa790863456f6
Verdict: APPROVE — technically mergeable; waiting only for required repository approval.

Review axes

  • Standards: 96/100 — APPROVE. The generated veryfront/agent API reference now includes HostedHostToolPolicy, and the unrelated cacheWriteInputTokens schema addition was removed.
  • Spec: 97/100 — PASS. No missing, partial, incorrectly implemented, or scope-creep findings against plans/agent-tool-discovery-prd-2026-07-31.md.

CI and verification

  • The original red status was caused by a cancelled coverage shard 6, which left the aggregate gate without its artifact; no code assertion failed.
  • The cancelled shard and coverage gate passed on rerun.
  • The new exact head is fully green: format, lint, typecheck, unit, integration, all 8 coverage shards and gate, browser E2E, binary E2E, npm install smoke, dependency audit, CLA, and CodeQL.
  • Fresh local pre-push gate: 2,881 tests / 22,826 steps, 0 failures.
  • Durable local flow: 8/8 passed; saved benchmark and privacy evidence remain valid.

Remaining risk

One low-severity duplication remains in model-visible catalog reduction between initial assembly and steering refresh. It is covered by tests and is better handled as a small follow-up than by expanding this already-large PR.

Merge state: MERGEABLE
Auto-merge: enabled
Only remaining gate: required approval from a non-author reviewer.

@kwakayama

Copy link
Copy Markdown
Contributor Author

Final critical review — 97/100 (APPROVE)

Reviewed exact head 417703d54f600af66199d170913b47baa8988657 after the requested cleanup and proof iteration.

  • Standards: 96/100 — APPROVE
  • Spec/PRD: 99/100 — PASS
  • Blocking findings: 0
  • GitHub checks: all applicable checks passed

Evidence:

  • six unrelated file diffs removed;
  • unused fingerprint and unshipped toolLoading compatibility removed;
  • exposure suites consolidated from 2,002 to 1,656 lines without losing generate/stream/restore/revocation/persistence/fail-closed coverage;
  • paired live direct Anthropic exact-hi measurement uses identical model, prompt, system, and 64 schemas: 5,276 eager vs 648 deferred input tokens, 87.718% measured reduction;
  • live direct-provider tool_search -> read_release_marker completed with schema-free search output and exactly one target execution;
  • hosted durable checkpoint persistence/restore and privacy proof retained;
  • pre-push gate: format, lint, typecheck, 2,869 tests / 22,822 steps / 0 failures;
  • focused changed-area suites: 76 tests / 115 steps; verifier: 12/12.

One non-blocking LOW remains: the hosted deferred visibility reducer is duplicated in chat-runtime-tool-assembly.ts and default-project-steering-refresh.ts. It is small, covered, and not worth expanding this already-large PR.

Recommendation: merge. Auto-merge/merge queue is enabled; repository-required independent approval is the only remaining gate.

@kwakayama
kwakayama added this pull request to the merge queue Jul 31, 2026
Merged via the queue into main with commit 5beb26d Jul 31, 2026
30 checks passed
@kwakayama
kwakayama deleted the codex/progressive-tool-schema-loading branch July 31, 2026 21:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants