Turn repeated agent reasoning into validated software.
AI agents are useful because they can operate under ambiguity. They can interpret a request, inspect an unfamiliar environment, choose tools, recover from errors, and assemble a plan that was not known in advance.
But most agent runtimes make a costly assumption: every request is new.
A data agent regenerates SQL for a question it has already learned how to answer. A coding agent repeatedly searches the same repository to rediscover its architecture. A tool-using agent reads the same documentation, resolves the same identifiers, and reconstructs the same sequence of calls on every run.
That is not intelligence. It is repeated inference over knowledge the system could have retained as software.
A Deterministic Agent Harness is a runtime that identifies which parts of an agent task are already understood, executes those parts through validated deterministic workflows, and invokes model reasoning only where unresolved uncertainty remains.
Deterministic when known. Agentic when necessary.
The motivating essay is in docs/article.md.
An agent should not merely remember what it did. It should become less agentic where experience has removed uncertainty.
The harness observes successful executions, extracts their stable structure, validates it, and promotes it into a versioned fast path. Requests that match an approved path execute without reconstructing the plan. Unknown, ambiguous, or invalidated requests fall back to the general agent.
flowchart TD
A[Request] --> B[Harness]
B --> C{Validated path?}
C -- Yes --> D[Deterministic execution]
C -- No --> E[Agent reasoning]
E --> F[Validate result]
F --> G[Workflow candidate]
G --> B
The goal is not to eliminate models. It is to place them at the boundary of uncertainty instead of using them as universal control flow.
The harness is the software boundary around the model. It owns the guarantees the model cannot provide:
- typed inputs and outputs;
- authorization and policy enforcement;
- workflow selection;
- deterministic execution;
- dependency tracking;
- validation and testing;
- versioning and provenance;
- invalidation and fallback;
- observability, cost, and latency budgets.
The model can propose a path. The harness decides whether that path is safe to reuse.
| Technique | What it reuses | Limitation |
|---|---|---|
| Prompt caching | Identical input tokens | Does not capture equivalent intent |
| Semantic caching | An answer to a similar request | Can return stale or contextually wrong answers |
| Agent memory | A description of prior experience | Requires the model to reinterpret it at runtime |
| Procedural memory | Instructions for repeating a task | Often remains probabilistic control flow |
| Deterministic Agent Harness | A typed, validated, executable procedure | Requires conservative matching and invalidation |
The reusable artifact is not a conversation or a saved response. It is a parameterized program with an applicability contract.
The first time a user asks:
What was recognized revenue by region in Q3?
the agent may need to determine what "revenue" means, locate the correct tables, understand the fiscal calendar, generate SQL, and validate the result.
After validation, the learned operation can become:
SELECT region, SUM(net_revenue) AS revenue
FROM recognized_revenue
WHERE fiscal_year = :fiscal_year
AND fiscal_quarter = :quarter
GROUP BY region;with an explicit contract:
intent: recognized_revenue_by_region
inputs:
fiscal_year: integer
quarter:
enum: [Q1, Q2, Q3, Q4]
requires:
permissions: [finance.read]
dependencies:
recognized_revenue: schema-hash-84f09c
net_revenue: metric-definition-v7
execution:
read_only: true
max_rows: 1000Future requests with the same intent can bind validated parameters and execute the query directly. A schema change, metric-definition change, permission mismatch, ambiguous intent, or low-confidence match invalidates the fast path and returns control to the agent.
If a user supplies SQL directly, the default path should not ask a model to regenerate it. The harness should parse it, enforce policy, execute it, and optionally use a model only to explain the result.
Coding agents repeatedly pay an orientation tax. They search the file tree, reopen configuration files, trace familiar dependencies, and reconstruct conventions already discovered in previous runs.
The harness should maintain a versioned repository model built from deterministic sources:
- the file tree and Git history;
- ASTs and symbol tables;
- imports, references, and call relationships;
- build and test targets;
- code ownership and package boundaries;
- validated architectural facts with file-level provenance.
For each task, the agent receives the relevant slice of that model. After a commit, only changed files and affected dependencies are re-indexed. A stored fact becomes stale when its supporting files or assumptions change.
The model still reasons about the new change. It does not have to rediscover the unchanged repository first.
The harness runs a single loop. Every successful agent execution is treated as a candidate software artifact, and the loop progressively converts repeated reasoning into validated software:
Observe -> Extract -> Validate -> Execute -> Monitor -> Invalidate
Record structured execution traces rather than only chat transcripts:
- request and resolved intent;
- model, prompt, and tool versions;
- tool calls, arguments, outputs, and errors;
- retries and abandoned exploration;
- environmental and authorization context;
- validation results and human corrections.
Look for recurring operations, then separate required steps from exploration and retries, identify the variable inputs, and trace which outputs feed later operations. Cluster executions using more than linguistic similarity — compare intent, entities, tools, argument structure, data dependencies, side effects, and validated outcomes.
Classify each part of an execution as one of:
- constant configuration;
- user input;
- output copied from an earlier step;
- deterministic transformation;
- branch or guard;
- residual model decision;
- recovery or exploratory noise.
Only proven data dependencies should constrain the compiled workflow. Consecutive tool calls are not necessarily dependent. Under-merging is safer than over-merging: missing a fast-path match costs another agent run, while selecting the wrong workflow can execute the wrong operation.
Treat the candidate workflow as untrusted generated code, and subject it to appropriate checks before activation:
- schema and type validation;
- permission review;
- replay against successful traces;
- unit and regression tests;
- read-only or dry-run execution;
- cost, row, time, and side-effect limits;
- human approval where the consequences justify it.
A useful lifecycle is:
candidate -> tested -> approved -> active -> stale -> retired
Once approved, the workflow becomes a deterministic fast path. A future request uses it only if the request, permissions, inputs, and environmental dependencies still satisfy its applicability contract — that is, only when:
- the intent match is sufficiently precise;
- all required parameters are present and valid;
- the caller has the required permissions;
- dependency versions still match;
- the workflow is approved for the requested side effects.
Otherwise, the system falls back to the agent.
Watch every execution for drift and failed matches: fallback rate, replay failures, abnormal runtime results, and requests that almost matched a known path. A rising fallback rate signals a workflow that has gone stale or a new operation worth compiling; monitoring is what turns the loop back on itself.
Every artifact must declare what would make it unsafe or incorrect to reuse. Examples include:
- database schema changes;
- business-metric definition changes;
- API or tool version changes;
- repository commits affecting supporting files;
- policy or authorization changes;
- expired credentials or session state;
- abnormal runtime results.
Time-to-live is a fallback, not a substitute for dependency-aware invalidation.
Invalidation need not be all-or-nothing. A workflow may declare a reverify()
hook, giving a graded middle state: when a dependency changes, the runtime
re-checks against live source before deciding, and reuses the fast path only if
the change did not actually affect this workflow — otherwise it falls back.
- Reason at discovery time; validate at reuse time.
- Prefer deterministic execution once uncertainty has been resolved.
- Compile decisions, not accidental execution history.
- Preserve provenance for every reusable value and dependency.
- Favor false negatives over false positives when routing.
- Never turn one successful execution into permanent truth.
- Keep unresolved judgment explicit as an agent or human node.
- Make invalidation part of the artifact, not an operational afterthought.
The entire system is not guaranteed to produce identical outcomes. The router may use probabilistic retrieval, external data changes, and some workflow nodes may still call a model.
The narrower guarantee is useful: once the harness selects an approved workflow, its known control flow, constraints, transformations, and side-effect boundaries are explicit, testable, auditable, and reproducible.
The harness makes uncertainty visible instead of allowing it to spread through the entire execution path.
This repository ships a working Phase 1 runtime. Sources live under src/, organized along the proposed package boundaries:
src/
trace/ Structured agent traces and provenance
registry/ Versioned workflow artifacts and lifecycle
validator/ Static checks: parameter validation and dependency fingerprints
router/ Conservative intent matching and applicability checks
runtime/ Deterministic workflow execution and escalation
adapters/ Agent fallback, example SQL workflow, knowledge-graph adapter
compiler/ (future) Trace normalization and workflow extraction
An initial implementation does not need automatic compilation. It begins with manually approved templates and can build the trace-to-workflow compiler later.
The harness has a procedure plane (route/execute/validate/invalidate workflows) and a knowledge plane (store/retrieve/validate/invalidate facts). The knowledge-graph adapter is a thin implementation of the second, in the spirit of an agent-maintained knowledge base: the agent compiles what it has learned into structured, typed memory once, and deterministic retrieval pulls only the relevant slice per query — instead of re-reading a whole wiki on every question.
Concepts are OKF-style records (typed subject–predicate–object relations,
sources, and a trust tier). contextFor(query) blends three signals —
exact-title, coverage-gated keyword overlap, and a lexical-cosine proxy for
neural embeddings — fuses them with Reciprocal Rank Fusion, expands two hops
through typed relations (weighted by predicate and trust), and packs a bounded,
token-budgeted context. It plugs into the harness two ways:
- As a fast path — retrieval is registered as a read-only workflow
(
knowledge.context) pinned to the graph's fingerprint; retrieving known context costs zero model calls, and a reindex invalidates it. - As the router's intent resolver —
resolveRequest()maps natural language to(intent, confidence), which is where the router'sconfidenceactually comes from. A query it cannot map falls back to the agent.
The graph sits behind a MemoryStore seam (retain / recall / reflect / snapshot / version) shaped after production memory services. KnowledgeGraph
is the in-repo implementation; a hosted memory service could implement the same
interface and drop in without touching the harness. The knowledge plane is a
"buy, don't build" component — the procedure plane (routing, contracts,
deterministic execution) is the harness's own contribution. (Our reflect is
the deterministic subset — intent resolution with provenance; a full service's
reflect adds agentic reasoning, which lives on the agent side of the
determinism boundary.)
Freshness re-verification. A workflow may declare an optional reverify()
hook. When the caller's dependency fingerprints no longer match, instead of a
hard fallback the runtime re-checks against live source: for retrieval, whether
the concepts this query actually returns are unchanged. An unrelated reindex
therefore stays on the fast path; a change to a retrieved concept falls back.
This is a graded middle state — reuse / re-verify / fall back — borrowed from
memory systems that re-check stale beliefs against raw facts rather than
trusting or discarding them wholesale.
npm run demo:kg # retrieval slice, intent resolution, and reindex invalidationA semantic cache keys a stored answer by input similarity and expires it on a timer. The knowledge plane is different in kind:
- It serves validated facts with provenance, not a remembered answer. Every
card carries
sourcesand a trust tier and is inspectable; a cache returns whatever the model last said, opaque and unattributed. - Correctness is gated by an applicability contract, not surface similarity. Retrieval is served only when the dependency fingerprint (index + model version) matches; a reindex invalidates deterministically. A semantic cache can return a stale or contextually-wrong hit because it matched closely enough and hadn't expired yet.
- It composes; a cache looks up. Bounded multi-hop traversal assembles an answer to a query never seen before from facts the graph holds. A key→value cache can only replay a prior hit — it cannot synthesize.
- It is a program input, not a memoized output. The retrieved slice feeds fresh reasoning about a new task; the model still reasons, it just doesn't rediscover the unchanged environment. A cache short-circuits the computation; the graph provisions it.
- It fails safe. The confidence score feeds a router biased toward fallback, so a weak match does extra work (agent run) rather than returning the wrong context — false negatives over false positives.
- It is maintained, not written-once. Reindex/lint/evaluate keep facts correct as sources change; a stale cache entry silently serves wrong data.
Retrieval ranking is heuristic (the probabilistic-router side of the boundary), but once a fact is selected its content and provenance are fixed, typed, and testable — the same determinism boundary the rest of the harness draws.
npm install
npm test # run the test suite (Node's built-in runner)
npm run demo # end-to-end lifecycle with measured savingsThe demo walks the full lifecycle for one intent:
- Unknown — with nothing registered, the first request falls back to the agent.
- Promote — the validated result is registered as a deterministic workflow.
- Known — the same intent now takes the deterministic fast path (zero model calls).
- Fallbacks — a changed dependency fingerprint, a missing permission, an invalid parameter, and a low-confidence intent match each return control to the agent.
- Measure — it prints model calls and tokens spent versus avoided.
Every decision emits a structured trace. Sample tail:
== Measured savings ==
requests: 7 fast-path: 2 agent: 5 fallback-rate: 71%
model calls spent: 5 (avoided by fast paths: 2)
tokens spent: 9000 (avoided: ~3600, at ~1800 tokens/agent call)
Savings are an auditable estimate, not a claim: each deterministic run counts as
one avoided agent invocation, valued at the mean token cost of the agent runs
actually observed (see src/metrics.ts).
import { Harness, summarize } from "./src";
import {
recognizedRevenueByRegion,
currentDependencyFingerprints,
} from "./src/adapters/sqlWorkflow";
const harness = new Harness({
// called only when no validated fast path applies
agent: async (request) => ({ output: await runYourAgent(request), cost: { modelCalls: 1, tokens: 1800 } }),
// optional: re-checked at execution time against a live authz service
authorize: (request) => hasLiveAccess(request.permissions),
});
harness.register(recognizedRevenueByRegion);
const result = await harness.handle({
intent: "recognized_revenue_by_region",
params: { fiscal_year: 2026, quarter: "Q3" },
permissions: ["finance.read"],
dependencies: currentDependencyFingerprints, // must match what the workflow was validated against
confidence: 1, // upstream intent-match confidence
});
console.log(result.path); // "deterministic" | "agent"
console.log(result.trace); // full structured trace, including cost
console.log(summarize(harness.traces.all())); // model calls / tokens avoidedWhat this repository actually does today, versus what is still design:
| Capability | Status | Where |
|---|---|---|
| Workflow + applicability contract schemas | ✅ Implemented | src/registry/types.ts |
Versioned registry + lifecycle (only approved/active are routable) |
✅ Implemented | src/registry/registry.ts |
| Typed parameter validation and coercion | ✅ Implemented | src/validator/validate.ts |
| Dependency-fingerprint invalidation (schema / metric / tool version) | ✅ Implemented | src/validator/fingerprint.ts |
| Conservative routing (intent, params, permissions, deps, side effects, confidence) | ✅ Implemented | src/router/router.ts |
Deterministic execution with max_rows / timeout limits |
✅ Implemented | src/runtime/harness.ts |
| Permissions re-checked at execution time + live authorizer | ✅ Implemented | src/runtime/harness.ts |
| Workflow failure safely escalates to the agent | ✅ Implemented | src/runtime/harness.ts |
| Structured traces with provenance and cost | ✅ Implemented | src/trace/, src/runtime/harness.ts |
| Measured model-call / token savings | ✅ Implemented | src/metrics.ts |
| Learn → promote → reuse arc (manual registration) | ✅ Implemented | src/demo.ts |
| Knowledge-plane adapter: deterministic retrieval + intent resolution | ✅ Implemented | src/adapters/knowledgeGraph/ |
MemoryStore seam (retain/recall/reflect) for swappable memory backends |
✅ Implemented | src/adapters/memory.ts |
| Freshness re-verification middle state (reuse / re-verify / fall back) | ✅ Implemented | src/runtime/harness.ts, src/registry/types.ts |
| Automatic trace clustering into workflow candidates | 🔭 Roadmap (Phase 3) | src/compiler/ (not yet present) |
| Replay-based validation and auto-generated regression tests | 🔭 Roadmap (Phase 4) | — |
| Repository-map adapter with incremental invalidation | 🔭 Roadmap (Phase 2) | — |
| Drift monitoring and automatic recompile/retire | 🔭 Roadmap (Phase 5) | — |
The six test cases that matter most are all covered
(test/lifecycle.test.ts, test/router.test.ts, test/harness.test.ts):
- A known request avoids the LLM (zero model calls).
- Invalid parameters never execute.
- Insufficient routing confidence invokes the agent.
- A changed schema/tool/dependency fingerprint invalidates the artifact.
- A workflow failure safely returns control to the agent.
- Permissions are re-checked at execution time.
Phase 1: deterministic registry (implemented here)
- Define the workflow and applicability schemas.
- Register workflows manually.
- Implement parameter validation, dependency fingerprints, routing, and fallback.
- Emit complete execution traces.
Phase 2: domain adapters
- Add parameterized Text-to-SQL workflows.
- Add repository maps with incremental invalidation.
- Measure fast-path precision, coverage, latency, and cost.
Phase 3: candidate extraction
- Cluster repeated agent traces.
- Remove retries and exploratory steps.
- Infer parameters and proven data dependencies.
- Produce reviewable workflow candidates.
Phase 4: controlled promotion
- Replay candidates against historical traces.
- Generate regression tests.
- Add approval policies based on side-effect risk.
- Promote only artifacts that satisfy their validation contract.
Phase 5: continuous determinization
- Monitor drift and failed matches.
- Recompile or retire stale workflows.
- Retain model calls only at genuinely open decision points.
Accuracy alone is insufficient. Track:
- fast-path precision;
- fast-path coverage;
- fallback rate;
- invalidation correctness;
- end-to-end latency;
- model tokens and tool calls avoided;
- workflow replay success;
- human-review burden;
- errors caused by incorrect reuse;
- residual model decisions per workflow.
The central metric is not how often the system avoids an LLM. It is how much known work it can execute without sacrificing correctness.
This repository ships a working Phase 1 runtime: manually registered deterministic workflows, conservative routing, typed validation, dependency-aware invalidation, execution-time authorization, structured traces with cost, measured savings, and an agent fallback. The trace-to-workflow compiler (Phases 3–5) is future work. See Implemented vs. roadmap for the exact boundary.
- Building Effective Agents — distinguishes predefined workflows from model-directed agents and recommends adding agentic complexity only when needed.
- A Practical Guide to Building Agents — positions agents for workflows where deterministic approaches fall short.
- The Shift from Models to Compound AI Systems — argues for systems combining models with conventional software components.
- Reducing Text2SQL latency with parameterized query templates — production example of bypassing repeated SQL generation through semantic matching and parameterized templates.
- Aider repository map — a practical, structured representation of a codebase for coding-agent context.
- CodeMEM — AST-guided memory for repository-level iterative code generation.
- TraceCompiler, Etchplan, and AgentJIT — recent projects that observe repeated agent behavior and compile its stable portions into reusable, mostly deterministic workflows.
- AI Agents That Matter — argues that agent evaluation must optimize cost alongside accuracy.
The most valuable early contributions are concrete recurring-agent use cases, workflow contract proposals, routing tests, invalidation strategies, and failure cases where deterministic reuse would be unsafe.
MIT. See LICENSE.