Skip to content

Research: context gathering and dynamic model routing for small + frontier models #18

Open

Description

@angelrdavila

Summary

Research notes from harness design work targeting small models (9B–34B) plus frontier models (e.g. Kimi). This issue captures what exists in the wild, what thee-harness already implements, and where the caller’s proposed directions sit: per-task effort ranking with dynamic model selection, SQLite/Turso edge-indexed context with index-time summaries and tool-driven code walking, and dual prompt variants (compact vs standard) for small vs frontier roles.


1. Smart context gathering architectures

Context engineering & progressive disclosure

  • Anthropic — Effective context engineering for AI agents
    JIT loading, tool search, memory tool, paginated tool results; treat context as a scarce budget rather than dumping everything up front.

  • Progressive disclosure (general pattern): orient with a thin structural view (symbols, file list, summaries); fetch bodies and dependencies on demand via tools; avoid silent prefetch that burns input tokens on small models.

  • Harness-level “retrieve, don’t explore”: agent loops that penalize blind list_dir / full-file reads in favor of search → read targeted ranges (aligned with coding-agent best practices and external products like Augment’s retrieval-first harness).

Repo maps & structural context

  • Aider repo map
    Tree-sitter parsing + PageRank over symbol references; dynamic vs static prefix; gives the model a map of where things live without full file contents.
    Reference: Aider documentation / repo map.

  • OpenHands repo map experiment
    OpenHands and related SWE agents have experimented with repository maps and condensation strategies (structural hints + history compression) for long-horizon coding tasks. Worth comparing to Aider’s static/dynamic repomap and to in-harness JIT retrieval.
    Pointers: OpenHands (condensation / context management in agent loop).

Retrieval tuning & selection

  • Adaptive-k retrieval
    Dynamic choice of how many chunks to retrieve based on query difficulty, confidence, or budget—not fixed top-k. Relevant when small models need fewer, sharper chunks and frontier models can tolerate broader retrieval.

  • Context-Picker
    Line of work on selecting which context slices enter the window (ranking / picking among candidates) rather than naive concatenation—closest cousin to “smart prefix assembly” under a token cap.

Summarization & compaction (turn / session level)

  • Turn summarization
    Replace or fold older turns with shorter summaries to preserve intent and outcomes while dropping verbatim tool noise.

  • Anchored incremental summaries
    Summaries that anchor to stable identifiers (goal, files touched, decisions) and grow incrementally—reduces “lost in compaction” drift vs one-shot aggressive summarization.

  • Research / risks on compaction

    • ACON, DTOC, COMPINT (“lost in compaction”), SJC-style approaches—over-trimming can drop verify-critical failures.
    • ACE (ace-agent/ace) — evolving playbooks / structured memory rather than only raw chat truncation.

Other architectural patterns (related)

  • RLMs — external prompt in REPL + recursive sub-calls (arxiv 2512.24601): extreme form of “context outside the window.”
  • Memory layers — Mem0, Zep/Graphiti, Letta, LangMem + LangGraph store: long-horizon state outside the turn budget.
  • Output token reduction — verbosity caps, structured outputs, anti–“three-act” replies (especially important for 9B–34B).

External products named “Context Engine” (not thee-harness)

Disambiguation for future readers:

Product Notes
context-engine.ai MCP dual server: hybrid search + symbol graph + memory; budgeted tools
Augment Context Engine codebase-retrieval, embeddings, commit lineage
context-engine.app Local Rust “headless IDE”, LSP handles, batched MCP

thee-harness implements its own internal/contextengine per architecture docs—not these MCP products.


2. In-repo Context Engine (harness/internal/contextengine)

Spec: docs/harness-architecture/context-engine.md
Flow: director each acting round → compactHistory → BuildTurn → provider with MaxOutputTokens.

Area Implementation
BuildTurn (build.go) System = rules + tool catalog + skills placeholder + project instructions + repo map from index.LoadOrBuild; tail = phase, two_step schema, goal; TurnInputBudget = window − 10% − 4096; prefix_hash
Compaction (compact.go) Elide old tool results; keep verify failures; foldOlder bullet summary (no LLM summarize yet)
Prefix budgeting (windows.go) % caps on AGENTS.md and repo map (≤25% prefix)
Prompt variants (render.go + assets/prompts/{compact,standard}/*.tmpl) Small vs frontier template sets
Instructions (instructions.go) ~/.thee/AGENTS.md + project files; untrusted wrap
Token estimation (tokens.go) Estimator chars/3.5 + ObserveUsage ratio calibration
Messages (messages.go) Append tool results / assistant tool calls to history
Repo map (index/repomap.go) Go-only symbol map, goal token ranking, .thee/index/repomap.json
JIT tools tools/impl/search.go, read.go, repomap.go; tools/result.go wraps <tool_result>

Model pairing today (models.yaml): e.g. 9B → two_step + compact prompts; frontier → native + standard prompts.

Escalation (not per-task routing): router/escalate.go swaps whole session to escalated role on verify/loop/parse failures—not per subtask model assignment.

Gaps vs spec / research: no memory tool, skills bodies in prefix, LLM compaction, embeddings, served_context in budget (probe stub in router/probe_integration.go).

Alignment: Strong JIT—orient in prefix (symbols only), bodies via tools; no silent prefetch.


3. Proposed: SQLite + Turso edge-indexed context

Idea (caller proposal)

  • Index time: build a graph / edge index of code relationships (imports, calls, types, file adjacency) in SQLite (optionally Turso for sync/replication at the edge).
  • Index time summaries: per-file or per-symbol short summaries stored in the index—not full sources in the prompt.
  • Runtime: agent uses tools to walk the graph (“connected code”) on demand—fetch only the next hop(s) needed for the current subgoal.
  • Budget-aware: retrieval depth and summary vs source tradeoffs tied to TurnInputBudget and model tier.

How this compares

Approach Prefix Retrieval Summaries Graph walk
Static repo dump Huge None Rare No
Aider repo map Medium (symbols) Manual reads No Implicit via map
Embeddings RAG Small Vector top-k Chunk-level Weak structure
External Context Engine MCP Small Hybrid search + graph Yes Via MCP tools
SQLite/Turso edge index (proposed) Small (map + optional summary index) Structured edges At index time Explicit tool-driven walks

Why this matches small + frontier

  • Small models: cheap orienting summaries + 1–2 hop reads beat dumping files; graph limits wandering.
  • Frontier models: same index; can request deeper walks or wider fan-out when planner detects hard refactors.
  • Token economics: summaries amortize index cost; sources paid only when execution proves need.

Open gaps / study items

  • Summary staleness vs git churn; incremental re-index.
  • Correctness when summary wrong—must fall back to raw read with line ranges.
  • Whether Turso adds value vs local SQLite + optional remote mirror for multi-machine dev.
  • Overlap with symbol graph already in external context-engine.ai vs first-party .thee/index evolution.

4. Dynamic model routing by task weight

What most gateways do (per request, not per todo item)

System Link Behavior
OpenRouter Auto Auto router docs ~30 task types + market spend ranking; cost_tier; one model per HTTP call
Inferbase auto Routing Classify → benchmark bar → cost/quality/latency; per request
Not Diamond Model select modelSelect from candidates; custom routers from eval data
LiteLLM Auto router / complexity_router SIMPLE/MEDIUM/COMPLEX/REASONING tiers → models
Amazon Bedrock Intelligent prompt routing Two models same family; prompt-level
RouteLLM Paper Learned strong-vs-weak per query
FrugalGPT / AutoMix FrugalGPT, AutoMix Cascade: cheap first, escalate on quality

Caller note: OpenRouter Auto and Inferbase-style “auto” are adjacent but not true per-task routing from a decomposed plan with effort scores.

Agent-loop routing (per step / cascade)

Closest to caller proposal: plan + per-item model

Pattern: planner emits todos with effort / complexity → router assigns 9B / 27B / 34B / Kimi (frontier) per item → executor runs DAG → escalate on failure.

Project Link Relevance
Tokenwise github.com/itsarbit/tokenwise Planner assigns model per step + budget; DAG executor + escalation
Ordewell per-task models Tasks carry runner + model + effort
UAP MULTI_MODEL guide TaskPlanner + ModelRouter per subtask
Pydantic AI Planning Planning harness Planner vs executor models; subtasks/deps
pyagent-router guide Difficulty 1–10 → model per call (middleware)
NVIDIA NeMo Switchyard blog Stage + escalation routers

Plan-and-execute blogs (frontier planner once, small executor many times): e.g. Spheron plan-and-execute — often fixed role split, not always explicit per-line model in plan.

Emphasis: caller’s three pillars vs state of the art

Pillar Status
Per-task effort ranking + dynamic model selection (9B–34B vs Kimi) Partially real in Tokenwise / Ordewell / UAP; not commodity on OpenRouter/Inferbase Auto. Calibrated effort → model maps for coding agents remain harness R&D. thee today: session escalation only (router/classify.go labels goal; escalate.go on failures).
SQLite/Turso edge index + index-time summaries + tool graph walks No dominant OSS product as a thin DeepInfra wrapper; closest = MCP symbol graphs + hybrid search (external Context Engine) + Aider-style maps. Structured edge walk + summary index is a credible differentiator for small models.
Dual prompt variants (compact vs standard) Already in thee-harness (models.yaml + prompt templates). Research gap is pairing with per-task routing and cache-aware model switches (skillforge model-routing skill notes prefix cache breaks).

Suggested harness shape (for future implementation issues)

  1. Planner (cheap or frontier once): structured todos with effort, deps, capabilities.
  2. Router (task, budget, context) → model_id + rules/classifier/RouteLLM-style scorer.
  3. Executor per ready DAG node with compact vs standard prompts by tier.
  4. Context tools backed by SQLite/Turso index (summary → optional source read).
  5. Cascade fallback on verify/parse/low confidence; log planned effort vs actual cost.

Papers / theory worth keeping


Suggested follow-ups (out of scope for this issue)

  • ADR or design doc: SQLite/Turso index schema (nodes, edges, summaries, staleness).
  • Spike: planner + per-subtask model field in director vs separate orchestration package.
  • Benchmark: compact+9B vs standard+frontier on same tasks with token/cost accounting.
  • Compare .thee/index/repomap.json evolution vs full edge graph.

Compiled from harness architecture review and external research (Oct 2025).

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions