84 Commits
Author SHA1 Message Date
sausheong d3c74e5681 docs: drop Co-Authored-By trailer references from run-total-usage plan 2026-06-26 23:35:05 -07:00
sausheong d1c63cac56 Merge run-total-usage: emit run-total token usage on terminal EventDone
Runtime.Run now accumulates token usage across all turns (summing all four
llm.Usage fields via a pure addUsage helper) and emits the run total on the
terminal EventDone, instead of only the last turn. Fixes multi-turn undercount
for consumers metering AgentEvent.Usage. RunTurn unchanged (one turn per call).
2026-06-26 22:28:04 -07:00
sausheong ef3a1d4927 test(runtime): assert addUsage returns a distinct pointer (aliasing safety) 2026-06-26 21:41:23 -07:00
sausheong 2f97b1cf78 docs(runtime): clarify EventDone.Usage is the run total 2026-06-26 21:37:28 -07:00
sausheong 69f58903eb fix(runtime): emit run-total token usage on terminal EventDone
Run accumulated only the last turn's usage into the terminal EventDone, so
multi-turn runs under-reported tokens to consumers metering AgentEvent.Usage.
Sum all four usage fields across turns; RunTurn is unchanged (one turn/call).
2026-06-26 21:33:58 -07:00
sausheong 1ec0f9cac3 feat(runtime): add pure addUsage helper for field-wise usage summation 2026-06-26 21:29:27 -07:00
sausheong 2630d88245 docs: implementation plan for run-total token usage 2026-06-26 21:28:10 -07:00
sausheong a797d446f8 docs: design for run-total token usage on terminal EventDone 2026-06-26 21:07:11 -07:00
sausheong ac724d18e1 Merge branch 'security/s1-bash-bypass': close S1 bash allowlist bypass
Fix the CRITICAL allowlist-confinement escape: the metacharacter guard
checked the two-byte literal "\\n" instead of a real newline, so a
newline in the command ran subsequent lines unchecked via bash -c. Also
treat background & as a command separator and reject output redirection
(>) in allowlist mode.
2026-06-13 16:34:00 +08:00
sausheong 7f0c3fd23d fix(bash): reject real newline/CR and redirection in allowlist mode (S1) 2026-06-13 16:25:44 +08:00
sausheong a5f21d3a2c fix(bash): treat background & as a command separator in allowlist mode (S1) 2026-06-13 16:23:51 +08:00
sausheong 34435736c5 Merge branch 'cleanup/low-batch': low-priority sweep (L1/L3/L4/L5/L10)
tokens image accounting, Qwen usage stats, one-time degraded-persistence
warning (AppendEntry+Rewrite), RunSync abort surfacing, retry classifier
bounded 429/529 forms + typed Gemini APIError path.
2026-06-13 15:57:04 +08:00
sausheong 3da8fe8ed3 fix(llm): recognize Gemini 429/5xx as retryable via typed APIError path 2026-06-13 15:52:33 +08:00
sausheong 9292731d79 fix(llm): scope retry classifier to bounded 429/529 forms 2026-06-13 15:34:19 +08:00
sausheong 04f02c56d6 fix(runtime): RunSync returns context.Canceled on aborted run 2026-06-13 15:33:02 +08:00
sausheong 3eb9596ee6 fix(session): extend degraded-persistence warning to Rewrite path 2026-06-13 15:31:27 +08:00
sausheong 275636ed20 fix(session): emit one-time warning when persistence is degraded 2026-06-13 15:29:57 +08:00
sausheong 754721bc30 fix(qwen): request usage stats (IncludeUsage) and use MaxCompletionTokens
no request-capture seam; covered by build + openai sibling parity
2026-06-13 15:28:29 +08:00
sausheong 22f4329f44 fix(tokens): count attached images in Estimate (~1500 tokens each) 2026-06-13 15:27:43 +08:00
sausheong 8c9bc2963d Merge branch 'correctness/round5': provider stream + file correctness (R7/N11/N12) 2026-06-13 13:42:59 +08:00
sausheong 1752cbf2fb fix(file): honor ctx cancellation in read_file/edit_file (N12) 2026-06-13 12:51:30 +08:00
sausheong e133f97e1e fix(web): decode all HTML entities via html.UnescapeString (N11) 2026-06-13 12:50:07 +08:00
sausheong 373e44b9c7 fix(anthropic): surface in-band stream error + Builder accumulation (R7c) 2026-06-13 12:48:10 +08:00
sausheong d0cd0989a9 fix(gemini): emit a single EventDone with final usage (R7b) 2026-06-13 12:45:56 +08:00
sausheong 385cd26e4b fix(openai): strings.Builder for tool-arg accumulation (R7c) 2026-06-13 12:44:06 +08:00
sausheong 79a69e5dce fix(qwen): index-order tool emit + strings.Builder accumulation (R7a/R7c) 2026-06-13 12:42:41 +08:00
sausheong e40733145f fix(openai): emit tool calls in index order for prompt-cache determinism (R7a) 2026-06-13 12:40:57 +08:00
sausheong b85ffeac69 Merge branch 'security/round4': SSRF + file-size hardening (S2/N4/S3/N5) 2026-06-13 12:06:50 +08:00
sausheong d6db565d7c fix(web): dial all validated IPs for dual-stack fallback (I1); fix live SSRF test to await fetch (M1) 2026-06-13 11:56:30 +08:00
sausheong fb5103fb87 feat(file): cap read_file/edit_file size to prevent OOM (N5) 2026-06-13 11:27:34 +08:00
sausheong 01b55a1446 fix(browser): block private-IP resolution via host-resolver-rules (S3) 2026-06-13 11:25:22 +08:00
sausheong 7d85074509 fix(web): all web_search backends use SafeHTTPClient (N4) 2026-06-13 11:22:15 +08:00
sausheong d7777f7c89 fix(web): web_fetch uses SafeHTTPClient — pins validated IP (S2) 2026-06-13 11:20:12 +08:00
sausheong 1e00916a82 fix(web): block 0.0.0.0/8, CGNAT, and reserved ranges in isPrivateIP (S2 hardening) 2026-06-13 11:19:03 +08:00
sausheong 083122a81f feat(web): add SafeHTTPClient with IP-pinning transport (S2) 2026-06-13 11:15:26 +08:00
sausheong 5d5dcd1902 Merge branch 'perf/round3': agent hot-path performance (P2/P3/P8/P1/P5)
Drop dead O(n^2) message-assembly work and a never-read tool-result map;
hoist tool-def normalization out of the turn loop; debounce calibrator
persistence to once per Run; skip re-writing spilled tool results each
turn; move the session disk write off the session lock (order-preserving
via lock-coupling). Zero observable behavior change.
2026-06-13 10:29:52 +08:00
sausheong 34ebfc5e95 fix(session): lock-couple writeMu to preserve disk order under concurrent Append (P5)
The earlier P5 change released s.mu before the store write, which let
concurrent appends on one Session reach the disk writer out of in-memory
order. Acquire a dedicated writeMu while still holding s.mu, then release
s.mu before the disk write — disk latency stays off s.mu while on-disk
order still matches append order. Adds a disk-order regression test.
2026-06-13 10:29:07 +08:00
sausheong e1fd4dc689 fix(runtime): recompute calibrator estimate at EventDone (P8 stale-estimate bug)
The earlier P8 change reused the pre-compaction turnEstimate at EventDone,
but mid-turn compaction reassembles msgs without recomputing it — so the
persisted calibration ratio diverged from main whenever compaction fired,
changing future compaction timing. Recompute fresh at EventDone exactly as
the pre-debounce code did; keep only the disk-write debounce (the real win).
2026-06-13 10:27:53 +08:00
sausheong 25b2e9163f perf(session): persist entry after releasing the session lock (P5) 2026-06-13 10:06:43 +08:00
sausheong c710ea5a94 perf(runtime): track spilled tool-call IDs to skip re-writing spills each turn (P1) 2026-06-13 10:04:46 +08:00
sausheong 671c10e89a perf(runtime): persist calibrator once per Run; reuse per-turn estimate (P8) 2026-06-13 10:00:52 +08:00
sausheong 1da0584530 perf(runtime): hoist tool-def filter/sort/normalize out of the turn loop (P3) 2026-06-13 09:57:39 +08:00
sausheong 7151562d99 perf(runtime): drop dead resultIDs map and mid-loop tool-result injection (P2) 2026-06-13 09:55:58 +08:00
sausheong 86ad622144 Merge branch 'reliability/round2': pre-first-token stream-error recovery (R1)
EventError delivered before the first token now runs the same reactive
compaction + fallback-model recovery as the synchronous ChatStream-error
path, via recoverFromPreTokenError (single-shot per turn). Fixes the
primary Anthropic/Gemini path where 429/overflow aborted the turn.
2026-06-13 01:52:25 +08:00
sausheong 7052a66e38 fix(runtime): recover from pre-first-token stream errors (compaction/fallback) — R1 2026-06-13 01:46:38 +08:00
sausheong de23ad986a Merge branch 'harden/safe-defaults': atomic file writes + 0600 perms
WriteFileAtomic helper; write_file/edit_file atomic + restrictive perms;
spill files 0600. Part of the cross-repo safe-by-default hardening.
2026-06-13 01:13:06 +08:00
sausheong 27fecf4588 feat(runtime): spill files 0600 via atomic write 2026-06-13 00:53:22 +08:00
sausheong 87f77c76ba feat(tools/file): edit_file atomic + preserve existing mode 2026-06-13 00:51:57 +08:00
sausheong 7ae944f0eb feat(tools/file): write_file atomic + 0600 2026-06-13 00:50:46 +08:00
sausheong c4750347e6 feat(tool): add WriteFileAtomic helper 2026-06-13 00:49:50 +08:00
sausheong 7fa3e75ad1 feat(llm): PromptCachingProvider capability — cache on renamed providers
providerSupportsCaching gated on the provider NAME being literally
'anthropic', so an Anthropic-shaped provider registered under a custom
config name (platformai, bedrock, any relay) never set
CacheLastMessage — every turn re-processed the full conversation
history uncached (~120K input tokens and 4-6s TTFT per turn on a
large session).

Add llm.PromptCachingProvider capability interface; AnthropicProvider
declares it; runtime gates providerSupportsCaching and
providerSupportsMidLoopCompaction on the capability first, with the
name check kept as legacy fallback for custom impls.
2026-06-11 22:02:37 +08:00
sausheong d5e8abf492 feat(runtime): surface and recover from model refusals
Claude Fable 5 safety classifiers decline requests with HTTP 200 +
stop_reason=refusal and empty content. The Anthropic stream parser
never read stop_reason, so a refused turn looked like a successful
empty response — the UI showed nothing and the agent appeared hung.

- llm: ChatEvent carries StopReason/StopCategory on EventDone;
  StopReasonRefusal constant
- anthropic: parse stop_reason + stop_details.category from
  message_delta (streaming) and the message (non-streaming); WARN log
  on refusal
- runtime Run + RunTurn: on refusal, retry the turn once on
  FallbackModel (refusals are model-specific; Opus-tier has no
  bio/cyber classifiers), discarding any partial output; without a
  fallback (or if the fallback also refuses) synthesize a visible
  'model declined this request' message with the policy category
  instead of silent emptiness
2026-06-10 21:13:48 +08:00
sausheong 3064a0da14 fix(tokens): 1M context window for Fable 5 / Mythos 5 / Opus 4.6+ / Sonnet 4.6
The blanket claude→200k rule predates the 1M-window generation. With
a 200k detected window, preventive compaction (threshold 0.6) fired
at ~120k tokens on models that actually hold 1M — 5x too early.

Match the 1M family explicitly (claude-fable, claude-mythos,
claude-opus-4-6/7/8/9, claude-sonnet-4-6) before the 200k fallback;
older Claude models (3.x, 4.0-4.5 era, Haiku 4.5) keep 200k.
2026-06-10 19:32:09 +08:00
sausheong cf47b2fca8 feat(mcp): expose session Ping on Client
Gateway supervisors need a cheap liveness probe to detect mid-flight
upstream death (crashed stdio child, restarted HTTP server). Client.Ping
forwards to the SDK session's MCP ping; a non-nil error means the
session is no longer usable.

Also moves examples/minimal's keep-import-live statement above the REPL
loop — it sat after an infinite for loop, tripping go vet's unreachable
code check.
2026-06-10 12:44:21 +08:00
sausheong 6f0040f606 fix(anthropic): adaptive thinking for Fable 5 / Mythos 5 / Opus 4.7+
These models reject the legacy thinking config — sending
{type:"enabled", budget_tokens:N} returns HTTP 400
("thinking.type.enabled is not supported for this model"), and
sampling params (temperature) are removed too.

For adaptive-only models (matched by substring so gateway model-group
names like claude-fable-5-global and Bedrock-style IDs are covered):
- emit thinking: {type:"adaptive"} plus output_config.effort
  (low/medium/high mapped from the unified ReasoningMode)
- omit thinking entirely when reasoning is off (Fable 5 also rejects
  an explicit {type:"disabled"})
- drop temperature

Pre-4.7 models keep the existing enabled+budget_tokens behavior.
2026-06-10 12:41:01 +08:00
sausheong 0341628068 Merge: wire KnowledgeGraph (recall+ingest) into RunTurn
RunTurn now consults r.KG — bounded-synchronous semantic recall folded into
the prompt on the first round of an exchange, async auto-ingest on the
completing round. Fixes the gap where the KG seam was inert on the runtime's
serve path (RunTurn never read r.KG). Interface + BuildRuntime unchanged.
2026-06-10 00:23:53 +08:00
sausheong 5d6326981e docs(runtime): update RunTurn contract — it now does KG recall/ingest 2026-06-09 23:58:21 +08:00
sausheong b7cbfc584c docs(runtime): note IngestSource/growth-gate rationale at RunTurn ingest 2026-06-09 23:42:58 +08:00
sausheong 8f8d75cd06 feat(runtime): KG ingest on RunTurn exchange completion 2026-06-09 23:39:26 +08:00
sausheong fe71e7b36d feat(runtime): bounded-synchronous KG recall in RunTurn 2026-06-09 23:34:44 +08:00
sausheong f35070594f test(runtime): strengthen sessionThread compaction-skip + undecodable coverage 2026-06-09 23:32:30 +08:00
sausheong 67178e018a feat(runtime): sessionThread helper for KG ingest in RunTurn 2026-06-09 23:28:16 +08:00
sausheong ecdf97ca79 Merge feat/run-turn-api: add RunTurn single-turn API 2026-06-08 01:04:42 +08:00
sausheong b7f4cfcf4a refactor(runtime): serial tool dispatch in RunTurn + error/abort tests
- Drop the wasted partitionToolCalls call; RunTurn dispatches serially by
  design (deterministic ordering for durable replay), so loop toolCalls directly.
- Fix doc-comment overclaim: RunTurn is headless and does not emit Run's
  trace/slog tool-result lines nor parallelize batches.
- Make TurnResult.Err consistent: mid-dispatch abort now passes ctx.Err().
- Document single-active-turn invariant on turnSlice.
- Add TestRunTurn_LLMError and TestRunTurn_PreCancelledContext.
2026-06-07 23:47:32 +08:00
sausheong 35896d215a feat(runtime): add single-turn RunTurn API
RunTurn executes exactly one turn of the agent loop against the current
session and returns the SessionEntries it produced, enabling external
platforms to drive the loop one turn at a time (e.g. for durable
per-turn checkpointing). Purely additive: Run() is unchanged.

RunTurn reuses the existing tested helpers (assembleMessages,
dispatchTool, partitionToolCalls) and deliberately omits compaction,
knowledge-graph, and streaming-tool kickoff, which remain in Run.
2026-06-07 23:40:07 +08:00
Chang Sau Sheong 1c6a05c0d8 Merge pull request #1 from sausheong/feat/configurable-tool-result-cap
feat(runtime): configurable per-tool-result truncation cap
2026-05-21 07:55:33 +08:00
sausheong e5c9b5dbb5 feat(runtime): configurable per-tool-result truncation cap
Adds LoopConfig.MaxToolResultLen with the same config > env > default precedence as the existing MaxToolConcurrency / MaxAgentDepth knobs:

  1. Runtime.AgentLoop.MaxToolResultLen (>0) — config wins
  2. HARNESS_MAX_TOOL_RESULT_LEN env (>0) — env fallback
  3. defaultMaxToolResultLen (4000) — unchanged for back-compat

The previous 4000-char cap was conservative for agents doing real engineering work (read_file, web_fetch, browser, bash output). Setting MaxToolResultLen to 16000-25000 lets a typical source file or test run land in-context without hitting spillover; spill remains the safety net for genuinely large outputs.

No behaviour change for callers that don't set the field.
2026-05-21 07:55:16 +08:00
sausheong 65021e1fe2 fix(file tools): resolve relative paths against WorkDir before workspace validation
When the agent supplies a relative path (e.g. "app.py"), filepath.Abs resolves
it against the process CWD, not the workspace — causing ValidatePathInWorkDir
to reject paths that are legitimately inside the workspace.

Join relative paths with WorkDir before resolution so the agent can use bare
filenames without hitting the outside-workspace error.
2026-05-12 17:10:32 +08:00
sausheong c2af8f389d examples: add self-improving-agent + v0.2.0 README updates 2026-05-09 16:34:44 +08:00
sausheong c7acd5a30e runtime: add Review integration test (memory save round-trip via fake LLM) 2026-05-09 16:34:40 +08:00
sausheong d9580eee8f runtime: implement Review with snapshot/build/run/extract/origin + spec-override tests 2026-05-09 16:34:36 +08:00
sausheong fd16dcefee runtime: add Review interface (spec, result, sentinel, prompts) 2026-05-09 16:33:57 +08:00
sausheong 53a7986fa0 skills: add end-to-end integration tests + polish 2026-05-09 15:42:45 +08:00
sausheong 7e394276da skills: add SkillTool with six actions (create/patch/replace/remove/list/get) 2026-05-09 15:42:42 +08:00
sausheong c884ef130a skills/disk: add disk-backed Store with full CRUD, frontmatter parser, concurrent-safe writes, and provider adapter 2026-05-09 15:42:37 +08:00
sausheong e9eea7c842 skills: add SkillStore interface, Skill type, OriginKey, name validation 2026-05-09 15:42:33 +08:00
sausheong 4877db85ae memory: add end-to-end integration tests + polish 2026-05-09 06:54:16 +08:00
sausheong 9381b2b661 memory: add MemoryTool with five actions (save/update/remove/list/get) 2026-05-09 06:54:12 +08:00
sausheong d2491dc90f memory/jsonl: add disk-backed Store with full CRUD, Compact, flock, and provider adapter 2026-05-09 06:54:07 +08:00
sausheong 1acf0d48a3 memory: add MemoryStore interface, Entry type, OriginKey 2026-05-09 06:53:58 +08:00
sausheong 0ca0fed9f7 fix(browser): reap orphaned Chromes when parent dies hard
chromedp launches Chrome as detached subprocesses; on SIGKILL, OOM, or
any path that bypasses our cleanup chain they reparent to PID 1 and
survive indefinitely. Each launch now allocates a known harness-browser-*
user-data-dir and registers it with a single detached /bin/sh watchdog
spawned via Setsid. When the parent dies the watchdog detects stdin EOF
and pkills + rm -rfs every still-tracked path. Clean teardown untracks
the path so a later hard exit can't kill the next session sharing the
process.
2026-05-08 22:08:58 +08:00
sausheong cc0406d30c Sharpen README: when to use Harness, and for what
Removes the standalone comparison.md (analysis kept locally only) and
folds its key positioning insights into the README without naming
specific competitors.

Why-Harness section:
- Reframes the substrate-vs-DSL distinction more directly: the
  runtime is treated as strategic infrastructure you own, not as
  plumbing hidden behind a graph builder.
- Capitalises 'Harness' in prose to match the project name.

New 'What Harness is for' section enumerates the use cases the
runtime is shaped around:
  - coding agents
  - infrastructure-automation agents
  - long-running autonomous loops
  - local-first agents
  - tool-heavy agents
  - developer-tooling agents
Plus a one-paragraph note on why Go's operational profile (static
binary, low memory, native concurrency, embeddability) matters
for these.

New 'When Harness is the wrong fit' section names the workflow
shapes the package isn't optimised for — visual / declarative
workflows, role-based crews, RAG-first products, notebook research,
heavily-regulated enterprise orchestration — without naming any
competing framework.

The existing 'Non-goals' section still covers what the library
doesn't ship (CLI, UI, channel adapters, etc.); the two sections
serve adjacent purposes.
2026-05-08 15:06:24 +08:00
sausheong 4df84b76d0 Add comparison.md surveying Harness against the agent-framework landscape
New top-level document comparing Harness's approach against LangGraph,
CrewAI, AutoGen/AG2, Semantic Kernel, OpenAI Agents SDK, Claude Agent
SDK, LlamaIndex, Mastra, and the Go peers eino + langchaingo.

Frames Harness as a runtime-centric, in-process Go library closer in
spirit to coding-agent runtimes (Claude Code, OpenClaw, OpenHands)
than to graph-based or role-based orchestration frameworks. Includes
current GitHub stats, per-framework architectural comparisons, the
language-choice tradeoff, the abstraction-fatigue trend, and where
Harness is the right (and wrong) pick.

README links to it next to the developer.md pointer; .gitignore
whitelists comparison.md alongside the other tracked docs.
2026-05-08 14:59:39 +08:00
sausheong 7e9801bf9c Remove upstream-project attribution from docs and code comments
Strips references to the upstream npm-package agent harness from
README design notes, developer.md, the compaction package, the
runtime context/streaming comments, and the tools/mcp adapter
doc-comments. The technical patterns being described stand on their
own; the attribution chain isn't needed.

Remaining mentions of the word in the providers/anthropic package
are literal Anthropic model identifiers (the 'claude-…' API model
strings) — those are functional product names, not attribution.
2026-05-08 13:43:10 +08:00
91 changed files with 8772 additions and 204 deletions

No files matched your search

+83 -19
View File
@@ -8,20 +8,78 @@ concrete tools, BYO provider clients, BYO memory/knowledge-graph plugins.
> **Status: v0.1.0.** First tagged release. The `runtime` API
> surface may still shift in the v0.x line — pin your version.
## Why harness
## Why Harness
If you're building an LLM agent in Go and you find yourself writing
the same things over and over — a streaming think-act loop, parallel
tool dispatch, prompt-cache-stable request building, summarize-and-
splice context compaction, JSONL session storage, MCP-server glue —
that's what harness is. It's the substrate. You bring the tools, the
prompts, and the binary; it brings the loop.
If you're building an LLM agent in Go, you'll find yourself rewriting
the same substrate over and over: a streaming think-act loop,
parallel tool dispatch, prompt-cache-stable request building,
summarize-and-splice context compaction, JSONL session storage,
MCP-server glue. **That substrate is what Harness is.**
It is **not** a CLI, a UI, an agent product, or a framework with
It treats the runtime — the orchestration / context / execution
layer — as the strategic infrastructure, not as plumbing to be
hidden behind a DSL or a graph builder. You own the loop you ship.
You can read every line.
It is **not** a CLI, a UI, a hosted runtime, or a framework with
opinions about how your agents should be deployed. There is no
`harness` binary. You import packages, compose a `Runtime`, and call
`rt.Run(ctx, msg, nil)`.
## What Harness is for
Harness is well-suited to:
- **Coding agents** — terminal-integrated, IDE-adjacent, or
repo-rooted assistants that read and write files, run shells, and
call tools across many turns.
- **Infrastructure-automation agents** — agents that drive cloud
APIs, internal tooling, or operational workflows where Go's
deployment story (static binary, low memory, embeddable in
existing services) is a real win.
- **Long-running autonomous loops** — daemons, cron-driven runners,
multi-day tasks. The streaming loop, compaction, and JSONL
session resume cover the substrate.
- **Local-first agents** — anything that needs to ship as a single
binary, run without a Python interpreter, or embed inside another
Go service.
- **Tool-heavy agents** — agents whose value comes from many tools
(custom + MCP servers + skills), not from elaborate workflow
logic.
- **Developer-tooling agents** — internal CLIs, build assistants,
code-review bots, log-triage agents — where a small dependency
tree and predictable runtime matter.
The operational profile of Go matters here: static binaries,
low memory footprint, native concurrency primitives, and the
ability to embed the agent inside a service you already own. Harness
leans into all of these.
## When Harness is the wrong fit
Harness deliberately doesn't try to be a graph orchestrator, a
multi-role agent crew, a RAG-first knowledge platform, or a
notebook-style experimentation toolkit. If your problem is one of
these, you'll be fighting the grain:
- **Visual or declarative workflows** — agents whose value comes
from inspectable graphs of explicit steps with branching, joins,
checkpointing, and human-in-the-loop pauses.
- **Role-based multi-agent crews** — "researcher / writer /
reviewer" decompositions where the framework's main value is
coordinating personas.
- **RAG-first products** — anything where the bulk of the work is
document ingest, chunking, embedding, indexing, and retrieval.
Harness has no opinion about your knowledge layer.
- **Notebook / research workflows** — fast iteration in a Python
notebook with the latest open-source ML libraries arriving daily.
- **Heavily regulated enterprise orchestration** — workflows that
need replayability, RBAC, governance dashboards, and visual
compliance views as first-class.
You can build any of these on top of Harness, but you'd be writing
a lot. The package is optimized for the use cases above, not these.
## Requirements
- **Go 1.25.1 or newer.** The module declares `go 1.25.1` and uses
@@ -141,6 +199,7 @@ self-contained `main.go` you can `go run`:
| [`data-agent/`](./examples/data-agent) | BYO custom tools (no `tools/*` deps) hitting Singapore's open-data APIs (`data.gov.sg`). Includes a `//go:build live` smoke test. | `tool.Tool` interface for 5 custom HTTP-backed tools |
| [`lta-agent/`](./examples/lta-agent) | Same shape as data-agent, talks to LTA Datamall. Demonstrates `IsConcurrencySafe=true` for parallel HTTP fanout. | Custom tools + parallel dispatch via `MaxToolConcurrency` |
| [`support-agent/`](./examples/support-agent) | Mock customer-support agent showing **`SkillProvider` + `PermissionChecker` + `LifecycleHooks`** wired together. KB articles via `//go:embed`; supervisor-mode gating; JSONL audit log. Closest to a real product. | All of the above, plus `runtime.SkillProvider`, `tool.PermissionChecker`, `runtime.LifecycleHooks` (`AfterToolUse` + `OnStop`) |
| [`self-improving-agent/`](./examples/self-improving-agent) | Wires `tool/memory` + `tool/skills` + `runtime.Review` end-to-end. The agent curates its own memory and skill library at end of every turn via `LifecycleHooks.OnStop`. Storage at `~/.harness/self-improving-agent/`. | `memory.MemoryTool`, `skills.SkillTool`, `runtime.Review`, `LifecycleHooks.OnStop` |
To run any of them:
@@ -177,10 +236,11 @@ none of it.
## Components
A general agent harness has ~13 conceptual components: the loop, the
A general agent harness has ~16 conceptual components: the loop, the
model invocation layer, the tool registry, permission gating,
context/compaction, the system prompt, sub-agents, hooks, MCP, skills,
session persistence, UI, and entrypoints. harness implements the
session persistence, writable memory, writable skills, a
self-improvement reviewer, UI, and entrypoints. harness implements the
in-process, library-shaped subset of those. The rest is left to the
caller — you own the binary, you own the UI, you own the channel.
@@ -197,11 +257,14 @@ caller — you own the binary, you own the UI, you own the channel.
| 9 | **MCP** | `tools/mcp` package: `mcp.Connect(ctx, ServerConfig)` adapts an external MCP server's tools as `tool.Tool`s. Declare `AgentSpec.MCPServers` for auto-wiring; `Runtime.Close()` releases sessions |
| 10 | **Skills** | `runtime.SkillProvider` (`FormatIndex` + `Get`); auto-registers `load_skill` so the model can pull a skill on demand. See `examples/support-agent/` for a `//go:embed kb/*.md` example |
| 11 | **Session persistence** | `session.Session` (in-memory, append-only) + optional `session.Store` for JSONL persistence and cross-process resume |
| 12 | **Writable memory** | `tool/memory` package: `MemoryStore` interface, `MemoryTool` (action-discriminated), JSONL on-disk default. Wraps any backend; `*jsonl.Store` doubles as a `runtime.MemoryProvider`. |
| 13 | **Writable skills** | `tool/skills` package: `SkillStore` interface, `SkillTool` (six actions: create/patch/replace/remove/list/get), directory-on-disk default. Patch supports surgical string-match with three error categories. |
| 14 | **Self-improvement reviewer** | `runtime.Review` — one-shot reviewer Runtime against a finished session. Designed to be called from `LifecycleHooks.OnStop` in a goroutine. Snapshots parent's session; shares Memory/Skills writes; recursion guard via `AgentID = "__review__"`. |
Deliberately not in scope (numbers from the same conceptual list):
- **12 — UI**: harness emits events; the caller renders.
- **13 — Entrypoints**: harness is a library. There is no `harness`
- **15 — UI**: harness emits events; the caller renders.
- **16 — Entrypoints**: harness is a library. There is no `harness`
binary. The example agents in `examples/` show how a binary is
assembled.
@@ -221,10 +284,10 @@ Deliberately not in scope (numbers from the same conceptual list):
valid.
- **Compaction at a clean boundary.** `compaction.Split` walks
backward counting user messages and cuts at one — never inside a
tool-call/tool-result pair. The prompt itself (`compaction/prompt.go`)
is adapted from Claude Code's `BASE_COMPACT_PROMPT` and emits a
9-section structured summary inside an `<analysis>` + `<summary>`
envelope; the `<analysis>` block is stripped before re-injection.
tool-call/tool-result pair. The prompt (`compaction/prompt.go`)
emits a 9-section structured summary inside an `<analysis>` +
`<summary>` envelope; the `<analysis>` block is stripped before
re-injection.
- **Plug-points are nil-friendly.** `MemoryProvider`,
`KnowledgeGraph`, `SkillProvider`, `SubagentResolver`,
`PermissionChecker`, `LifecycleHooks`, and `session.Store` are all
@@ -252,7 +315,7 @@ Deliberately not in scope (numbers from the same conceptual list):
Adding a fifth is implementing `llm.Provider` (~300 LOC).
See [`developer.md`](./developer.md) for a step-by-step guide to
building agents on top of harness, including diagrams of the
building agents on top of Harness, including diagrams of the
composition surface and the per-Run loop.
## Non-goals
@@ -284,8 +347,9 @@ these, you'll need to bring them yourself or layer them on top:
- **Auth / billing / multi-tenant infrastructure.** Per-agent
policy lives in `PermissionChecker`; everything else is your
problem.
- **Shell-command hooks (Claude Code style).** Hooks are typed Go
callbacks on `LifecycleHooks`, not subprocess invocations.
- **Shell-command hooks.** Hooks are typed Go callbacks on
`LifecycleHooks`, not subprocess invocations driven by a config
file.
## Testing
-3
View File
@@ -19,9 +19,6 @@ import (
// The breaker resets on any genuine summarizer success (stage 1 or 2
// returning real content). It exists to prevent a session whose context
// is irrecoverably over the limit from hammering the API on every turn.
//
// Pattern from Claude Code MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES
// (src/services/compact/autoCompact.ts:67-70).
const MaxConsecutiveFailures = 3
// Reason identifies why compaction was triggered.
-6
View File
@@ -57,9 +57,6 @@ func transcriptDelimiterSuffix() string {
// - The <analysis> block is a drafting scratchpad (stripped before
// injection by FormatCompactSummary). It improves summary quality on
// small models without polluting the resulting context.
//
// Pattern adapted from Claude Code's BASE_COMPACT_PROMPT
// (claude-code-source/src/services/compact/prompt.ts:61-143).
const summarizationPromptHeader = `You are summarizing an AI assistant's conversation so it can continue past the context window.
CRITICAL: Respond with TEXT ONLY. Do NOT call any tools. The output must be an <analysis> block followed by a <summary> block — nothing else.
@@ -247,9 +244,6 @@ var blankLineCollapseRE = regexp.MustCompile(`\n{3,}`)
// returned as-is so we never silently drop content. Multiple <summary>
// blocks (rare, but possible) are each unwrapped consistently so no literal
// tags leak into the injected context.
//
// Pattern adapted from Claude Code's formatCompactSummary
// (claude-code-source/src/services/compact/prompt.ts:311-335).
func FormatCompactSummary(raw string) string {
out := analysisBlockRE.ReplaceAllString(raw, "")
+2 -2
View File
@@ -362,8 +362,8 @@ reg.Register(&EnvTool{})
### Returning images
Vision-capable models (Claude, GPT-4o, Gemini) can see images returned
from a tool. Set `ToolResult.Images`:
Vision-capable models can see images returned from a tool. Set
`ToolResult.Images`:
```go
return tool.ToolResult{
@@ -0,0 +1,387 @@
# Run-Total Token Usage Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make `Runtime.Run`'s terminal `EventDone.Usage` carry the token total accumulated across all turns, instead of only the last turn.
**Architecture:** Add a pure, non-mutating `addUsage` helper that field-wise sums two `*llm.Usage` snapshots; declare a run-scoped accumulator in `Run` outside the turn loop; fold each turn's provider usage into it; emit the accumulator (not `lastUsage`) on the single terminal `EventDone`. `RunTurn` is unchanged (one turn per call, already correct).
**Tech Stack:** Go 1.25, harness `runtime` + `llm` packages, `llmtest.Base`, testify.
## Global Constraints
- Module `github.com/sausheong/harness`. Work on branch `run-total-usage` — do NOT switch branches.
- `EventDone` stays the SINGLE terminal event (subagent layer keys `Done` on it). No new events, no new fields.
- Behavior preserved: usage-less providers → terminal `EventDone.Usage` stays nil; single-turn runs → identical to today; the calibrator block keeps using the per-turn `event.Usage`, NOT the accumulator.
- Only `runtime/runtime.go`'s `Run` changes. Do NOT modify `RunTurn` (`runtime/runturn.go`).
- Sum ALL FOUR `llm.Usage` fields: `InputTokens`, `OutputTokens`, `CacheCreationInputTokens`, `CacheReadInputTokens`.
- Gates per task: `go build ./...`, `go vet ./...` clean; named tests pass.
---
### Task 1: addUsage helper (pure)
**Files:**
- Modify: `runtime/runtime.go` (add the helper; or create `runtime/usage.go` — implementer's choice, but keep it in package `runtime`)
- Test: `runtime/usage_test.go`
**Interfaces:**
- Consumes: `llm.Usage` (fields `InputTokens`, `OutputTokens`, `CacheCreationInputTokens`, `CacheReadInputTokens`, all `int`).
- Produces: `func addUsage(acc, turn *llm.Usage) *llm.Usage` — field-wise sum; nil treated as zero; returns a fresh pointer; returns nil only when both args are nil; never mutates either argument.
- [ ] **Step 1: Write the failing test**
Create `runtime/usage_test.go`:
```go
package runtime
import (
"testing"
"github.com/sausheong/harness/llm"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAddUsage_BothNil(t *testing.T) {
assert.Nil(t, addUsage(nil, nil))
}
func TestAddUsage_AccNil(t *testing.T) {
turn := &llm.Usage{InputTokens: 7, OutputTokens: 3, CacheCreationInputTokens: 2, CacheReadInputTokens: 1}
got := addUsage(nil, turn)
require.NotNil(t, got)
assert.Equal(t, llm.Usage{InputTokens: 7, OutputTokens: 3, CacheCreationInputTokens: 2, CacheReadInputTokens: 1}, *got)
// input not mutated
assert.Equal(t, 7, turn.InputTokens)
}
func TestAddUsage_TurnNil(t *testing.T) {
acc := &llm.Usage{InputTokens: 5}
got := addUsage(acc, nil)
require.NotNil(t, got)
assert.Equal(t, 5, got.InputTokens)
}
func TestAddUsage_SumsAllFourFields(t *testing.T) {
acc := &llm.Usage{InputTokens: 100, OutputTokens: 40, CacheCreationInputTokens: 10, CacheReadInputTokens: 6}
turn := &llm.Usage{InputTokens: 10, OutputTokens: 5, CacheCreationInputTokens: 1, CacheReadInputTokens: 2}
got := addUsage(acc, turn)
require.NotNil(t, got)
assert.Equal(t, 110, got.InputTokens)
assert.Equal(t, 45, got.OutputTokens)
assert.Equal(t, 11, got.CacheCreationInputTokens)
assert.Equal(t, 8, got.CacheReadInputTokens)
// neither input mutated
assert.Equal(t, 100, acc.InputTokens)
assert.Equal(t, 10, turn.InputTokens)
}
```
- [ ] **Step 2: Run test to verify it fails**
Run: `go test ./runtime/ -run TestAddUsage -v`
Expected: FAIL — `addUsage` undefined.
- [ ] **Step 3: Implement the helper**
Add to `runtime/runtime.go` (near other unexported helpers) or a new `runtime/usage.go`:
```go
// addUsage returns the field-wise sum of two usage snapshots. A nil operand is
// treated as zero. It returns a fresh pointer and never mutates its arguments,
// so callers may safely pass a pointer that aliases a provider stream event.
// Returns nil only when BOTH operands are nil, preserving the contract that
// EventDone.Usage stays nil for providers that never report usage.
func addUsage(acc, turn *llm.Usage) *llm.Usage {
if acc == nil && turn == nil {
return nil
}
var out llm.Usage
if acc != nil {
out = *acc
}
if turn != nil {
out.InputTokens += turn.InputTokens
out.OutputTokens += turn.OutputTokens
out.CacheCreationInputTokens += turn.CacheCreationInputTokens
out.CacheReadInputTokens += turn.CacheReadInputTokens
}
return &out
}
```
If creating `runtime/usage.go`, start it with `package runtime` and `import "github.com/sausheong/harness/llm"`.
- [ ] **Step 4: Run test to verify it passes**
Run: `go test ./runtime/ -run TestAddUsage -v`
Expected: PASS (4 tests).
- [ ] **Step 5: Commit**
```bash
git add runtime/usage.go runtime/usage_test.go runtime/runtime.go
git commit -m "feat(runtime): add pure addUsage helper for field-wise usage summation"
```
(Adjust `git add` to whichever files you actually touched.)
---
### Task 2: Accumulate run-total usage in Run
**Files:**
- Modify: `runtime/runtime.go` (the `Run` method — accumulator decl, the `llm.EventDone` case ~line 586-591, the terminal emit ~line 716)
- Test: `runtime/run_usage_test.go`
**Interfaces:**
- Consumes: `addUsage` (Task 1); harness `llmtest.Base`, `llm.ChatEvent`, `llm.EventDone`, `llm.Usage`; `runtime.AgentEvent`, `runtime.EventDone`.
- Produces: corrected terminal `EventDone.Usage` (run total). No new exported symbols.
- [ ] **Step 1: Write the failing test**
Create `runtime/run_usage_test.go`. This uses a scripted provider that emits a tool call on turn 1 (forcing a second turn) with usage, then text + usage on turn 2, mirroring the `threeToolCallLLM` pattern already in `agent_test.go`.
```go
package runtime
import (
"context"
"encoding/json"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// twoTurnUsageLLM: turn 1 emits a noop tool call + EventDone{Usage:u1};
// turn 2 (after the tool result) emits text + EventDone{Usage:u2} and stops.
type twoTurnUsageLLM struct {
llmtest.Base
u1, u2 *llm.Usage
calls int
}
func (f *twoTurnUsageLLM) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
ch := make(chan llm.ChatEvent, 8)
first := f.calls == 0
f.calls++
go func() {
defer close(ch)
if first {
tc := llm.ToolCall{ID: "tc_0", Name: "noop", Input: json.RawMessage(`{}`)}
ch <- llm.ChatEvent{Type: llm.EventToolCallStart, ToolCall: &tc}
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &tc}
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: f.u1}
return
}
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "done"}
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: f.u2}
}()
return ch, nil
}
// noopExecutor returns "ok" for a "noop" tool.
type noopExecutor struct{}
func (noopExecutor) Execute(_ context.Context, _ string, _ json.RawMessage) (tool.ToolResult, error) {
return tool.ToolResult{Output: "ok"}, nil
}
func (noopExecutor) ToolDefs() []llm.ToolDef { return []llm.ToolDef{{Name: "noop"}} }
func (noopExecutor) Names() []string { return []string{"noop"} }
func (noopExecutor) Get(string) (tool.Tool, bool) { return nil, false }
func drainUsage(t *testing.T, events <-chan AgentEvent) *llm.Usage {
t.Helper()
var done *llm.Usage
var sawDone bool
for ev := range events {
if ev.Type == EventDone {
done = ev.Usage
sawDone = true
}
}
require.True(t, sawDone, "expected a terminal EventDone")
return done
}
func TestRun_UsageAccumulatesAcrossTurns(t *testing.T) {
r := &Runtime{
LLM: &twoTurnUsageLLM{
u1: &llm.Usage{InputTokens: 100, OutputTokens: 40, CacheCreationInputTokens: 10, CacheReadInputTokens: 6},
u2: &llm.Usage{InputTokens: 10, OutputTokens: 5, CacheCreationInputTokens: 1, CacheReadInputTokens: 2},
},
Tools: noopExecutor{},
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test-model",
MaxTurns: 5,
}
events, err := r.Run(context.Background(), "go", nil)
require.NoError(t, err)
got := drainUsage(t, events)
require.NotNil(t, got)
assert.Equal(t, 110, got.InputTokens)
assert.Equal(t, 45, got.OutputTokens)
assert.Equal(t, 11, got.CacheCreationInputTokens)
assert.Equal(t, 8, got.CacheReadInputTokens)
}
func TestRun_UsageSingleTurn(t *testing.T) {
r := &Runtime{
LLM: &twoTurnUsageLLM{
u2: &llm.Usage{InputTokens: 7, OutputTokens: 3},
},
Tools: noopExecutor{},
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test-model",
MaxTurns: 5,
}
// calls=0 path emits a tool call; to get a pure single turn, mark calls so
// the first ChatStream takes the text+stop branch.
r.LLM.(*twoTurnUsageLLM).calls = 1
events, err := r.Run(context.Background(), "go", nil)
require.NoError(t, err)
got := drainUsage(t, events)
require.NotNil(t, got)
assert.Equal(t, 7, got.InputTokens)
assert.Equal(t, 3, got.OutputTokens)
}
func TestRun_UsageNilWhenProviderSilent(t *testing.T) {
r := &Runtime{
LLM: &twoTurnUsageLLM{calls: 1}, // single turn, u2 nil → EventDone with nil usage
Tools: noopExecutor{},
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test-model",
MaxTurns: 5,
}
events, err := r.Run(context.Background(), "go", nil)
require.NoError(t, err)
got := drainUsage(t, events)
assert.Nil(t, got, "usage must stay nil when the provider never reports it")
}
```
Note: confirm the exact `tool.Executor` interface method set by reading `tool/registry.go` or an existing fake in `agent_test.go` (e.g. `cancelOnNthExecutor`). Match its method signatures exactly — `Execute`, `ToolDefs`, `Names`, `Get` are what the existing fake implements; adjust if the interface differs.
- [ ] **Step 2: Run test to verify it fails**
Run: `go test ./runtime/ -run TestRun_Usage -v`
Expected: FAIL — `TestRun_UsageAccumulatesAcrossTurns` gets 10/5 (last turn only), not 110/45, because Run still emits `lastUsage`.
- [ ] **Step 3: Implement the accumulation**
In `runtime/runtime.go`, in the `Run` method:
(a) Declare the accumulator just BEFORE the turn loop `for turn := 0; turn < maxTurns; turn++ {` (~line 397):
```go
var runUsage *llm.Usage // accumulated across all turns; nil until first reported
```
(b) In the `case llm.EventDone:` block (~line 586-591), after `lastUsage = event.Usage`, fold into the accumulator:
```go
case llm.EventDone:
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
if event.Usage != nil {
lastUsage = event.Usage
runUsage = addUsage(runUsage, event.Usage)
}
// (existing calibrator block below stays exactly as-is —
// it uses event.Usage, the per-turn figure, not runUsage)
```
(c) At the terminal completed emit (~line 716), change `lastUsage` to `runUsage`:
```go
stopReason = "completed"
r.emit(AgentEvent{Type: EventDone, Usage: runUsage})
```
Do NOT change the calibrator block, `lastUsage`'s other uses, or any other emission. Confirm via `grep -n "EventDone" runtime/runtime.go` that line 716 is the only `AgentEvent{Type: EventDone}` emit in `Run` (it is, per the spec); if there are others on terminal paths, switch them to `runUsage` too and note it in the report.
- [ ] **Step 4: Run tests to verify they pass**
Run: `go test ./runtime/ -run 'TestRun_Usage|TestAddUsage' -v`
Expected: PASS (accumulate=110/45/11/8; single-turn=7/3; nil-when-silent=nil).
- [ ] **Step 5: Full runtime suite (no regression)**
Run: `go test ./runtime/... && go vet ./... && go build ./...`
Expected: all PASS / clean. If any pre-existing test asserted the old last-turn-only usage, investigate and report before "fixing" it — that would be a behavior the change intentionally alters; flag it rather than silently editing.
- [ ] **Step 6: Commit**
```bash
git add runtime/runtime.go runtime/run_usage_test.go
git commit -m "fix(runtime): emit run-total token usage on terminal EventDone
Run accumulated only the last turn's usage into the terminal EventDone, so
multi-turn runs under-reported tokens to consumers metering AgentEvent.Usage.
Sum all four usage fields across turns; RunTurn is unchanged (one turn/call)."
```
---
### Task 3: Document the field semantics
**Files:**
- Modify: `runtime/runtime.go` (the `AgentEvent.Usage` field doc comment, line ~48)
- Modify: `developer.md` (the usage example region, ~line 471 — only if it characterizes the figure; otherwise leave)
**Interfaces:**
- Consumes: nothing.
- Produces: accurate doc comment.
- [ ] **Step 1: Update the field doc comment**
In `runtime/runtime.go`, change the `AgentEvent.Usage` comment (~line 48) from:
```go
Usage *llm.Usage // populated for EventDone when the provider reported it
```
to:
```go
Usage *llm.Usage // on the terminal EventDone, the token total accumulated across all turns of the run (nil if the provider never reported usage); per-turn figures are available via RunTurn's TurnResult.Usage
```
- [ ] **Step 2: Check developer.md**
Read `developer.md` around line 471. If the surrounding prose describes `ev.Usage` as per-call/per-turn in a way the change now contradicts, update it to say the terminal `EventDone` carries the run total. If it only prints the numbers without characterizing them, leave it unchanged.
- [ ] **Step 3: Verify build (docs/comment only)**
Run: `go build ./... && go vet ./...`
Expected: clean.
- [ ] **Step 4: Commit**
```bash
git add runtime/runtime.go developer.md
git commit -m "docs(runtime): clarify EventDone.Usage is the run total"
```
(Drop `developer.md` from the add if you didn't change it.)
---
## Self-Review Notes
- **Spec coverage:** addUsage helper (T1), accumulator + terminal emit + preserved calibrator/nil/single-turn behavior (T2), field doc (T3). All spec items mapped.
- **Scope guard:** plan explicitly forbids touching `RunTurn` and the calibrator block; T2 step 3 calls this out.
- **Type consistency:** `addUsage(acc, turn *llm.Usage) *llm.Usage` used identically in T1 and T2; the four `llm.Usage` field names match across tests and helper.
- **Behavior preservation** is directly tested: single-turn (T2 test 2) and nil-when-silent (T2 test 3), not just asserted in prose.
- **Test-fixture risk flagged:** T2 step 1 tells the implementer to verify the `tool.Executor` interface method set against the real interface / existing fakes rather than trust the snippet.
@@ -0,0 +1,155 @@
# Design: Run-Total Token Usage on Terminal EventDone
**Date:** 2026-06-26
**Project:** harness (`github.com/sausheong/harness`)
**Status:** Approved (design)
## Motivation
`Runtime.Run` executes a multi-turn agent loop. Each turn captures the provider's
per-turn token usage into a local `lastUsage`, but the terminal
`AgentEvent{Type: EventDone}` is emitted once carrying only the **last turn's**
usage (`runtime/runtime.go:716`). For a multi-turn run, all prior turns' tokens
are silently dropped.
Downstream consumers that meter spend from `AgentEvent.Usage` (e.g. sidecar's
daily token budget cap) therefore undercount multi-turn runs — the cap reads one
turn instead of the whole run. The field's doc comment ("populated for EventDone
when the provider reported it") implies a complete figure; today it is partial.
## Goal
Make the terminal `EventDone.Usage` carry the **accumulated total across all
turns of the run**, summing all four `llm.Usage` fields (InputTokens,
OutputTokens, CacheCreationInputTokens, CacheReadInputTokens).
## Non-goals
- No new events and no new fields: `EventDone` stays the single terminal event
(the subagent layer keys `Done` on it — `runtime/subagent.go:134` — so adding
per-turn `EventDone`s would break that contract). This is a value-correctness
fix to the existing field, not a protocol change.
- No per-turn usage telemetry surface. (Out of scope; `RunTurn` already exposes
per-turn usage via `TurnResult.Usage` for callers that want it.)
## Scope: `Run` only, not `RunTurn`
`RunTurn` executes **exactly one turn per call** by contract; its caller drives
the loop and accumulates `TurnResult.Usage` itself. Its `EventDone.Usage` (one
turn) is therefore already correct. **Do not change `RunTurn`.** The bug is
solely in `Run`'s internal `for turn := 0; turn < maxTurns; turn++` loop.
## Design
In `Runtime.Run` (`runtime/runtime.go`), introduce a run-scoped accumulator
declared **outside** the turn loop (the loop starts at line 397):
```go
var runUsage *llm.Usage // accumulated across all turns; nil until first reported
```
Inside the turn loop, at the point where the provider's `llm.EventDone` is
handled and `lastUsage = event.Usage` is set (currently ~line 589–591), fold the
turn's usage into the accumulator:
```go
case llm.EventDone:
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
if event.Usage != nil {
lastUsage = event.Usage
runUsage = addUsage(runUsage, event.Usage)
}
// ... existing calibrator block unchanged (it still uses event.Usage,
// the per-turn figure — calibration is per-request, not per-run) ...
```
The terminal completed emission (line 716) changes from `lastUsage` to the
accumulator:
```go
stopReason = "completed"
r.emit(AgentEvent{Type: EventDone, Usage: runUsage})
```
### Helper
Add an unexported helper (in `runtime/runtime.go` or a small `usage.go` in
package runtime):
```go
// addUsage returns the field-wise sum of two usage snapshots. A nil operand is
// treated as zero. Returns a new pointer; never mutates its arguments. Returns
// nil only when both are nil (so EventDone.Usage stays nil when the provider
// never reported usage — preserving today's behavior for usage-less providers).
func addUsage(acc, turn *llm.Usage) *llm.Usage {
if acc == nil && turn == nil {
return nil
}
var out llm.Usage
if acc != nil {
out = *acc
}
if turn != nil {
out.InputTokens += turn.InputTokens
out.OutputTokens += turn.OutputTokens
out.CacheCreationInputTokens += turn.CacheCreationInputTokens
out.CacheReadInputTokens += turn.CacheReadInputTokens
}
return &out
}
```
### Why a non-mutating helper
`event.Usage` points into the provider's stream event; mutating it could corrupt
provider-side state or other observers. `addUsage` always returns a fresh value.
## Behavior preservation
- **Usage-less providers** (never send `llm.EventDone.Usage`): `runUsage` stays
nil → terminal `EventDone.Usage` is nil, exactly as today.
- **Single-turn runs:** `runUsage` == that turn's usage → identical to today.
- **Calibrator:** unchanged — it consumes the per-turn `event.Usage`
(per-request calibration), not the run total.
- **`lastUsage`:** retained; still used by the non-streaming/other terminal
paths if any reference it. (Verify during implementation that every terminal
`EventDone` emission in `Run` uses `runUsage`; if there is more than one, all
must switch. The known one is line 716.)
## Error handling
No new failure modes. `addUsage` is pure and total. nil-safe on both operands.
## Testing
Mirror the existing scripted-provider pattern in `runtime/agent_test.go` (a fake
`llm.LLMProvider` whose `ChatStream` emits canned events including
`llm.EventDone` with a `*llm.Usage`).
| Test | Setup | Assert |
|------|-------|--------|
| `TestRun_UsageAccumulatesAcrossTurns` | scripted provider: turn 1 emits a tool call + `EventDone{Usage: 100/40/…}`, turn 2 emits text + `EventDone{Usage: 10/5/…}` and stops | terminal `AgentEvent{EventDone}.Usage` == field-wise sum (110 in / 45 out / summed cache) |
| `TestRun_UsageSingleTurn` | one turn, `EventDone{Usage: 7/3}` | terminal usage == 7/3 (no regression) |
| `TestRun_UsageNilWhenProviderSilent` | provider never sets `EventDone.Usage` | terminal `EventDone.Usage` == nil |
| `TestAddUsage` (pure) | nil+nil, nil+x, x+nil, x+y across all four fields | correct sums; inputs not mutated |
Gate: `go test ./runtime/...`, `go vet ./...`, `go build ./...` clean. Run the
broader `go test ./...` to confirm no other runtime test asserted the old
last-turn-only behavior.
## Downstream note (sidecar)
This fixes the root cause of sidecar's documented budget undercount for the
**coding** runtime (multi-turn) and the **evaluator** (up to 8 turns). After
harness ships this, sidecar's CLAUDE.md / sidecar.yaml caveat about multi-turn
undercount can be softened to note only provider-reported-usage caveats. (Triage
is single-turn and already exact.) That doc update is a separate sidecar change,
not part of this harness spec.
## Files
- Modified: `runtime/runtime.go` (accumulator + helper + terminal emission).
- New test cases: `runtime/runtime_usage_test.go` (or appended to
`runtime/agent_test.go`).
- New: this design doc.
+2 -1
View File
@@ -82,6 +82,8 @@ func main() {
}
defer rt.Close() // no-op here (no MCP), but idiomatic
_ = llm.ReasoningOff // keep llm import live for clarity in the demo
// 5. REPL loop.
in := bufio.NewScanner(os.Stdin)
fmt.Println("harness demo — type a message, blank line to exit")
@@ -115,5 +117,4 @@ func main() {
}
}
}
_ = llm.ReasoningOff // keep llm import live for clarity in the demo
}
+164
View File
@@ -0,0 +1,164 @@
// Self-improving agent example — fourth shipped example, demonstrating
// the v0.2.0 self-improvement primitives wired together end-to-end:
//
// - tool/memory: durable cross-session preferences/facts
// - tool/skills: durable procedural knowledge
// - runtime.Review: end-of-turn reviewer that decides what to save
//
// Storage lives at ~/.harness/self-improving-agent/{memory.jsonl,skills/}.
// The agent has file (read/write/edit) and bash tools for foreground work;
// the reviewer has WRITE-ONLY memory + skills tools so it can curate but
// not modify the workspace.
//
// export ANTHROPIC_API_KEY=sk-ant-...
// go run ./examples/self-improving-agent
//
// Type prompts at the > marker. After each turn, an "💾 self-review:"
// line summarizes anything the reviewer saved.
package main
import (
"bufio"
"context"
"fmt"
"log"
"os"
"path/filepath"
"strings"
"github.com/sausheong/harness/providers/anthropic"
"github.com/sausheong/harness/runtime"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
memorytool "github.com/sausheong/harness/tool/memory"
memoryjsonl "github.com/sausheong/harness/tool/memory/jsonl"
skilltool "github.com/sausheong/harness/tool/skills"
skilldisk "github.com/sausheong/harness/tool/skills/disk"
"github.com/sausheong/harness/tools/bash"
"github.com/sausheong/harness/tools/file"
)
func main() {
apiKey := os.Getenv("ANTHROPIC_API_KEY")
if apiKey == "" {
log.Fatal("ANTHROPIC_API_KEY must be set")
}
home, err := os.UserHomeDir()
if err != nil {
log.Fatalf("home dir: %v", err)
}
storeRoot := filepath.Join(home, ".harness", "self-improving-agent")
if err := os.MkdirAll(storeRoot, 0o755); err != nil {
log.Fatalf("mkdir store: %v", err)
}
memStore := memoryjsonl.NewStore(filepath.Join(storeRoot, "memory.jsonl"))
skillStore := skilldisk.NewStore(filepath.Join(storeRoot, "skills"))
workspace := storeRoot
// Foreground tool registry: read tools + memory/skills (so the
// agent CAN save during the user turn if it wants, in addition to
// the reviewer).
foreground := tool.NewRegistry()
foreground.Register(&file.ReadFileTool{WorkDir: workspace})
foreground.Register(&file.WriteFileTool{WorkDir: workspace})
foreground.Register(&file.EditFileTool{WorkDir: workspace})
foreground.Register(&bash.BashTool{WorkDir: workspace})
foreground.Register(&memorytool.MemoryTool{Store: memStore})
foreground.Register(&skilltool.SkillTool{Store: skillStore})
// Reviewer registry: WRITE-ONLY memory + skills. No file/bash —
// the reviewer's job is curation, not workspace mutation.
reviewTools := tool.NewRegistry()
reviewTools.Register(&memorytool.MemoryTool{Store: memStore})
reviewTools.Register(&skilltool.SkillTool{Store: skillStore})
provider := anthropic.NewAnthropicProvider(apiKey, "")
// Declare rt early so the OnStop closure can capture it by
// reference. The hook only fires AFTER rt is assigned, so by the
// time it runs, the closure sees the constructed Runtime.
var rt *runtime.Runtime
spec := runtime.AgentSpec{
ID: "self-improving",
Name: "Self-Improving Agent",
Model: "anthropic/claude-haiku-4-5-20251001",
Workspace: workspace,
SystemPrompt: "You are a helpful assistant. Save important user preferences and reusable workflows for future sessions.",
MaxTurns: 25,
}
// OnStop: at end of every successful turn, fire a Review against
// the parent session in a goroutine. Surfaces a one-line
// "💾 self-review:" summary if the reviewer saved anything.
spec.Loop.Hooks.OnStop = func(ctx context.Context, reason string) {
if reason != "completed" {
return
}
// Capture rt by closure so we can pass it to Review.
go func() {
res := runtime.Review(context.Background(), rt, runtime.ReviewSpec{
Prompt: runtime.ReviewPromptDefault,
Tools: reviewTools,
})
if res.Err != nil {
fmt.Printf("⚠️ self-review error: %v\n", res.Err)
return
}
if len(res.Actions) > 0 {
fmt.Printf("💾 self-review: %s\n", strings.Join(res.Actions, " · "))
}
}()
}
rt, err = runtime.BuildRuntime(
runtime.RuntimeDeps{
Memory: memStore.AsMemoryProvider(),
Skills: skillStore.AsSkillProvider(),
},
runtime.RuntimeInputs{
Provider: provider,
Tools: foreground,
Session: session.NewSession("self-improving", "main"),
},
spec,
)
if err != nil {
log.Fatalf("build runtime: %v", err)
}
defer rt.Close()
// REPL.
fmt.Println("Self-improving agent ready. Type a prompt and press Enter (Ctrl+D to exit).")
scanner := bufio.NewScanner(os.Stdin)
scanner.Buffer(make([]byte, 64*1024), 1024*1024)
for {
fmt.Print("> ")
if !scanner.Scan() {
fmt.Println()
break
}
prompt := strings.TrimSpace(scanner.Text())
if prompt == "" {
continue
}
events, err := rt.Run(context.Background(), prompt, nil)
if err != nil {
fmt.Printf("error: %v\n", err)
continue
}
for ev := range events {
switch ev.Type {
case runtime.EventTextDelta:
fmt.Print(ev.Text)
case runtime.EventDone:
fmt.Println()
case runtime.EventError:
fmt.Printf("\nerror: %v\n", ev.Error)
}
}
}
}
+1 -1
View File
@@ -12,6 +12,7 @@ require (
github.com/stretchr/testify v1.11.1
go.opentelemetry.io/otel v1.43.0
go.opentelemetry.io/otel/trace v1.43.0
golang.org/x/sys v0.42.0
google.golang.org/genai v1.49.0
)
@@ -47,7 +48,6 @@ require (
golang.org/x/net v0.52.0 // indirect
golang.org/x/oauth2 v0.35.0 // indirect
golang.org/x/sync v0.20.0 // indirect
golang.org/x/sys v0.42.0 // indirect
golang.org/x/text v0.35.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect
google.golang.org/grpc v1.80.0 // indirect
+27
View File
@@ -135,8 +135,23 @@ type ChatEvent struct {
ToolCall *ToolCall
Usage *Usage
Error error
// StopReason carries the provider's terminal stop reason on EventDone
// ("end_turn", "tool_use", "max_tokens", "refusal", ...). Empty when
// the provider doesn't report one. StopReasonRefusal is the value the
// runtime branches on: Claude Fable 5 safety classifiers decline a
// request with HTTP 200 + stop_reason=refusal and empty content —
// without surfacing it the turn looks like a silent empty success.
StopReason string
// StopCategory is the refusal policy category from stop_details
// ("cyber", "bio", "reasoning_extraction"); informational only and
// may be empty even on a refusal.
StopCategory string
}
// StopReasonRefusal is the StopReason value for safety-classifier and
// model-initiated refusals (Claude Fable 5+).
const StopReasonRefusal = "refusal"
// ModelInfo describes an available model.
type ModelInfo struct {
ID string
@@ -171,6 +186,18 @@ type NonStreamingProvider interface {
ChatNonStreaming(ctx context.Context, req ChatRequest) (<-chan ChatEvent, error)
}
// PromptCachingProvider is an optional capability interface: providers
// that implement Anthropic-style explicit prompt caching (cache_control
// breakpoints, CacheLastMessage) declare it here. The runtime gates
// caching on this capability rather than on the provider's configured
// NAME — a user-named provider block ("platformai", "bedrock", any
// relay) wrapping an Anthropic-shaped API must still get caching;
// matching the name string alone silently disabled it for every
// renamed provider.
type PromptCachingProvider interface {
SupportsPromptCaching() bool
}
// ParseProviderModel splits "provider/model" into (provider, model).
// If no slash is present, returns ("", name) and the caller should use a default.
func ParseProviderModel(name string) (provider, model string) {
+26 -6
View File
@@ -6,6 +6,7 @@ import (
anthropic "github.com/anthropics/anthropic-sdk-go"
openai "github.com/sashabaranov/go-openai"
"google.golang.org/genai"
)
// IsRetryableModelError reports whether err is a transient capacity
@@ -14,14 +15,17 @@ import (
//
// - Anthropic 429 (rate limit) and 529 (overloaded)
// - OpenAI 429 (rate limit) and 5xx (server / overloaded)
// - Gemini 429 (quota/RESOURCE_EXHAUSTED) and 5xx (overloaded/unavailable),
// recognized via a typed genai.APIError path (Gemini's error string
// "Error 429, ... Status: RESOURCE_EXHAUSTED" does not match the
// bounded substring forms, so the typed path is required).
//
// Anything else (including 4xx auth/validation errors) returns false:
// retrying with a different model wouldn't fix the underlying problem.
//
// Errors from local providers (Ollama, etc.) and Gemini are NOT
// classified as retryable here; their failure modes are different
// and a model swap rarely helps. Add cases as new providers
// accumulate retry experience.
// Errors from local providers (Ollama, etc.) are NOT classified as
// retryable here; their failure modes are different and a model swap
// rarely helps. Add cases as new providers accumulate retry experience.
func IsRetryableModelError(err error) bool {
if err == nil {
return false
@@ -47,13 +51,29 @@ func IsRetryableModelError(err error) bool {
return openaiReqErr.HTTPStatusCode == 429 ||
(openaiReqErr.HTTPStatusCode >= 500 && openaiReqErr.HTTPStatusCode < 600)
}
// genai.APIError.Error() is a value receiver, so the error interface is
// satisfied by the value; errors.As targets the value type.
var genaiErr genai.APIError
if errors.As(err, &genaiErr) {
return genaiErr.Code == 429 ||
(genaiErr.Code >= 500 && genaiErr.Code < 600)
}
// Last-ditch: substring match on common SDK error wrappers that
// don't unwrap cleanly to typed errors. Cheap belt-and-braces;
// only reached when no typed match found above.
msg := strings.ToLower(err.Error())
if strings.Contains(msg, "429") || strings.Contains(msg, "529") ||
strings.Contains(msg, "rate limit") || strings.Contains(msg, "overloaded") {
// Bounded forms so a bare "429"/"529" inside a request id or unrelated
// digits doesn't trigger a retry. Word matches stay as-is (specific).
for _, sig := range []string{
"status 429", "code: 429", "code:429", " 429 ", "429 too many requests",
"status 529", "code: 529", "code:529", " 529 ", "529 overloaded",
} {
if strings.Contains(msg, sig) {
return true
}
}
if strings.Contains(msg, "rate limit") || strings.Contains(msg, "overloaded") {
return true
}
return false
+28
View File
@@ -8,8 +8,26 @@ import (
anthropic "github.com/anthropics/anthropic-sdk-go"
openai "github.com/sashabaranov/go-openai"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/genai"
)
func TestIsRetryable_Gemini429(t *testing.T) {
// Mirror genai.APIError's real shape.
err := genai.APIError{Code: 429, Message: "Resource has been exhausted (e.g. check quota).", Status: "RESOURCE_EXHAUSTED"}
require.True(t, IsRetryableModelError(err))
}
func TestIsRetryable_Gemini503(t *testing.T) {
err := genai.APIError{Code: 503, Message: "The model is overloaded.", Status: "UNAVAILABLE"}
require.True(t, IsRetryableModelError(err))
}
func TestIsRetryable_Gemini400NotRetryable(t *testing.T) {
err := genai.APIError{Code: 400, Message: "Invalid argument", Status: "INVALID_ARGUMENT"}
require.False(t, IsRetryableModelError(err))
}
func TestIsRetryableModelErrorAnthropic429(t *testing.T) {
err := &anthropic.Error{StatusCode: 429}
assert.True(t, IsRetryableModelError(err))
@@ -89,3 +107,13 @@ func TestIsRetryableModelErrorUnrelatedError(t *testing.T) {
err := errors.New("some other failure")
assert.False(t, IsRetryableModelError(err))
}
func TestRetry_DigitsInRequestIDNotRetryable(t *testing.T) {
err := errors.New("request failed: req_abc429def something went wrong")
require.False(t, IsRetryableModelError(err))
}
func TestRetry_RealStatus429Retryable(t *testing.T) {
err := errors.New("openai: error, status 429 too many requests")
require.True(t, IsRetryableModelError(err))
}
+90 -9
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log/slog"
"strings"
@@ -28,6 +29,11 @@ func NewAnthropicProvider(apiKey, baseURL string) *AnthropicProvider {
return &AnthropicProvider{client: client}
}
// SupportsPromptCaching implements llm.PromptCachingProvider: the
// Anthropic Messages API honours cache_control breakpoints regardless
// of what the provider block is named in user config.
func (p *AnthropicProvider) SupportsPromptCaching() bool { return true }
func (p *AnthropicProvider) Models() []llm.ModelInfo {
return []llm.ModelInfo{
{ID: "claude-sonnet-4-5-20250514", Name: "Claude Sonnet 4.5", Provider: "anthropic"},
@@ -87,10 +93,28 @@ func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.Me
if sys := buildAnthropicSystem(req); len(sys) > 0 {
params.System = sys
}
if req.Temperature > 0 {
if req.Temperature > 0 && !anthropicAdaptiveThinkingOnly(model) {
params.Temperature = anthropic.Float(req.Temperature)
}
if cfg, ok := p.BuildThinkingConfig(model, req.Reasoning); ok {
if anthropicAdaptiveThinkingOnly(model) {
// Fable 5 / Mythos 5 / Opus 4.7+ reject the legacy
// enabled+budget_tokens config (400 "thinking.type.enabled is
// not supported"). They take {type:"adaptive"} plus
// output_config.effort; sampling params are also removed.
// Reasoning off → omit thinking entirely (Fable 5 rejects an
// explicit {type:"disabled"} too).
if req.Reasoning != llm.ReasoningOff {
params.Thinking = anthropic.ThinkingConfigParamUnion{
OfAdaptive: &anthropic.ThinkingConfigAdaptiveParam{},
}
params.OutputConfig = anthropic.OutputConfigParam{
Effort: anthropicEffort(req.Reasoning),
}
slog.Info("anthropic adaptive thinking",
"model", model,
"effort", string(anthropicEffort(req.Reasoning)))
}
} else if cfg, ok := p.BuildThinkingConfig(model, req.Reasoning); ok {
required := cfg.BudgetTokens + 4096
if maxTokens < required {
maxTokens = required
@@ -141,8 +165,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
type pendingTC struct {
id string
name string
inputJSON string // built from input_json_delta events
startInput string // captured from content_block_start (proxy fallback)
inputJSON strings.Builder // built from input_json_delta events
startInput string // captured from content_block_start (proxy fallback)
}
var pendingTools []pendingTC
var currentBlockType string
@@ -197,18 +221,21 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
}
case "input_json_delta":
if len(pendingTools) > 0 {
pendingTools[len(pendingTools)-1].inputJSON += delta.PartialJSON
pendingTools[len(pendingTools)-1].inputJSON.WriteString(delta.PartialJSON)
}
}
case "content_block_stop":
if currentBlockType == "tool_use" && len(pendingTools) > 0 {
tc := pendingTools[len(pendingTools)-1]
// Index in place rather than copying the element: the
// pendingTC holds a strings.Builder, which must not be
// copied after first write (vet copylock).
tc := &pendingTools[len(pendingTools)-1]
// Prefer streamed deltas (canonical Anthropic). Fall
// back to start-time input (proxy emitting full input
// upfront). Default to "{}" so MCP servers receive a
// valid empty-args envelope rather than null/empty.
inp := tc.inputJSON
inp := tc.inputJSON.String()
if inp == "" {
inp = tc.startInput
}
@@ -227,7 +254,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
currentBlockType = ""
case "message_delta":
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 {
stopReason := string(event.Delta.StopReason)
stopCategory := string(event.Delta.StopDetails.Category)
if stopReason == llm.StopReasonRefusal {
slog.Warn("anthropic refusal stop reason",
"category", stopCategory,
"output_tokens", event.Usage.OutputTokens)
}
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 || stopReason != "" {
slog.Info("anthropic stream usage",
"input_tokens", inputTokens,
"output_tokens", event.Usage.OutputTokens,
@@ -242,6 +276,8 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
CacheCreationInputTokens: int(cacheCreationTokens),
CacheReadInputTokens: int(cacheReadTokens),
},
StopReason: stopReason,
StopCategory: stopCategory,
}
}
@@ -249,7 +285,14 @@ func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest)
// Final event — nothing extra to emit
case "error":
slog.Error("anthropic stream error", "event", event.Type)
// The SDK surfaces error detail via stream.Err() (handled after
// the loop); this in-band branch must not be a silent no-op —
// emit an EventError so the runtime treats it as a failure.
slog.Error("anthropic stream error event", "event", event.Type)
events <- llm.ChatEvent{
Type: llm.EventError,
Error: fmt.Errorf("anthropic stream error event"),
}
}
}
@@ -326,6 +369,8 @@ func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRe
CacheCreationInputTokens: int(msg.Usage.CacheCreationInputTokens),
CacheReadInputTokens: int(msg.Usage.CacheReadInputTokens),
},
StopReason: string(msg.StopReason),
StopCategory: string(msg.StopDetails.Category),
}
}()
return events, nil
@@ -374,6 +419,42 @@ func (p *AnthropicProvider) BuildThinkingConfig(model string, mode llm.Reasoning
}
}
// anthropicAdaptiveThinkingOnly reports whether the model accepts ONLY
// adaptive thinking: Claude Fable 5, Claude Mythos 5, and Opus 4.7+.
// On these the legacy {type:"enabled", budget_tokens:N} config and
// sampling params (temperature/top_p/top_k) return HTTP 400. Matched by
// substring so gateway model-group names (claude-fable-5-global) and
// Bedrock-style IDs (us.anthropic.claude-opus-4-8-v1) are covered.
func anthropicAdaptiveThinkingOnly(model string) bool {
adaptiveOnly := []string{
"claude-fable-5",
"claude-mythos-5",
"claude-mythos-preview",
"claude-opus-4-7",
"claude-opus-4-8",
"claude-opus-4-9", // future-proof within the 4.x line
}
for _, marker := range adaptiveOnly {
if strings.Contains(model, marker) {
return true
}
}
return false
}
// anthropicEffort maps the unified ReasoningMode onto output_config.effort
// for adaptive-thinking-only models.
func anthropicEffort(mode llm.ReasoningMode) anthropic.OutputConfigEffort {
switch mode {
case llm.ReasoningLow:
return anthropic.OutputConfigEffortLow
case llm.ReasoningMedium:
return anthropic.OutputConfigEffortMedium
default:
return anthropic.OutputConfigEffortHigh
}
}
// anthropicSupportsThinking returns true for Claude models that accept
// extended thinking. Conservative — unknown IDs default to true so we
// let the API decide rather than silently drop a knob the user set.
+196
View File
@@ -6,6 +6,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
anthropic "github.com/anthropics/anthropic-sdk-go"
@@ -521,3 +522,198 @@ data: {"type":"message_stop"}
assert.Equal(t, `{}`, string(toolDone.ToolCall.Input),
"argument-less tool call must serialize as {} so MCP transport accepts it")
}
// --- Adaptive-thinking model mapping ---------------------------------
//
// Claude Fable 5, Claude Mythos 5, and Opus 4.7/4.8 reject the legacy
// thinking config: `thinking: {type:"enabled", budget_tokens:N}` returns
// HTTP 400 ("thinking.type.enabled is not supported for this model").
// They also removed sampling params — sending `temperature` is a 400.
// For these models the provider must emit `thinking: {type:"adaptive"}`
// plus `output_config.effort`, and drop temperature.
func wireJSON(t *testing.T, p *AnthropicProvider, req llm.ChatRequest) string {
t.Helper()
params := p.buildMessageParams(req)
b, err := json.Marshal(params)
require.NoError(t, err)
return string(b)
}
func TestAdaptiveThinkingModels_EmitAdaptiveNotEnabled(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
models := []string{
"claude-fable-5",
"claude-fable-5-global", // LiteLLM / gateway model-group names
"claude-mythos-5",
"claude-opus-4-7",
"claude-opus-4-8",
"us.anthropic.claude-opus-4-8-v1", // Bedrock-style ID
}
for _, model := range models {
t.Run(model, func(t *testing.T) {
got := wireJSON(t, p, llm.ChatRequest{
Model: model,
Reasoning: llm.ReasoningHigh,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.Contains(t, got, `"thinking":{"type":"adaptive"}`,
"adaptive-only models must send thinking.type=adaptive")
assert.NotContains(t, got, `"budget_tokens"`,
"budget_tokens is rejected with 400 on adaptive-only models")
assert.Contains(t, got, `"output_config":{"effort":"high"}`,
"reasoning mode maps to output_config.effort on adaptive-only models")
})
}
}
func TestAdaptiveThinkingModels_EffortMapping(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
cases := []struct {
mode llm.ReasoningMode
effort string
}{
{llm.ReasoningLow, "low"},
{llm.ReasoningMedium, "medium"},
{llm.ReasoningHigh, "high"},
}
for _, c := range cases {
t.Run(string(c.mode), func(t *testing.T) {
got := wireJSON(t, p, llm.ChatRequest{
Model: "claude-opus-4-8",
Reasoning: c.mode,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.Contains(t, got, `"output_config":{"effort":"`+c.effort+`"}`)
})
}
}
func TestAdaptiveThinkingModels_ReasoningOffOmitsThinking(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
got := wireJSON(t, p, llm.ChatRequest{
Model: "claude-fable-5",
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.NotContains(t, got, `"thinking"`,
"reasoning off must omit the thinking param entirely — Fable 5 "+
"rejects an explicit {type:disabled} with 400")
assert.NotContains(t, got, `"output_config"`)
}
func TestAdaptiveThinkingModels_TemperatureDropped(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
for _, model := range []string{"claude-fable-5", "claude-opus-4-7", "claude-opus-4-8"} {
t.Run(model, func(t *testing.T) {
got := wireJSON(t, p, llm.ChatRequest{
Model: model,
Temperature: 0.7,
Reasoning: llm.ReasoningMedium,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.NotContains(t, got, `"temperature"`,
"sampling params are removed on these models — sending temperature is a 400")
})
}
}
func TestLegacyThinkingModels_KeepBudgetTokens(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
got := wireJSON(t, p, llm.ChatRequest{
Model: "claude-sonnet-4-5",
Reasoning: llm.ReasoningHigh,
Messages: []llm.Message{{Role: "user", Content: "hi"}},
})
assert.Contains(t, got, `"budget_tokens":16384`,
"pre-4.7 models keep the enabled+budget_tokens config")
assert.NotContains(t, got, `"output_config"`)
}
// TestAnthropicStream_RefusalStopReasonSurfaced reproduces the Claude
// Fable 5 classifier refusal: HTTP 200, a message_delta carrying
// stop_reason=refusal + stop_details.category, and NO content blocks.
// The parser previously dropped stop_reason entirely, so the runtime
// saw an empty-but-successful turn and the user saw a silent nothing.
func TestAnthropicStream_RefusalStopReasonSurfaced(t *testing.T) {
const sseBody = `event: message_start
data: {"type":"message_start","message":{"id":"msg_r","type":"message","role":"assistant","content":[],"model":"claude-fable-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":29,"output_tokens":0}}}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"refusal","stop_sequence":null,"stop_details":{"type":"refusal","category":"bio","explanation":null}},"usage":{"output_tokens":4}}
event: message_stop
data: {"type":"message_stop"}
`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(sseBody))
}))
t.Cleanup(srv.Close)
p := NewAnthropicProvider("test-key", srv.URL)
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-fable-5"})
require.NoError(t, err)
var done *llm.ChatEvent
for ev := range stream {
if ev.Type == llm.EventDone {
ev := ev
done = &ev
}
}
require.NotNil(t, done, "stream must emit EventDone")
assert.Equal(t, "refusal", done.StopReason)
assert.Equal(t, "bio", done.StopCategory)
}
// Normal end_turn streams must carry the stop reason too (and no category).
func TestAnthropicStream_EndTurnStopReason(t *testing.T) {
const sseBody = `event: message_start
data: {"type":"message_start","message":{"id":"msg_n","type":"message","role":"assistant","content":[],"model":"claude-fable-5","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0}}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}
event: message_stop
data: {"type":"message_stop"}
`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(sseBody))
}))
t.Cleanup(srv.Close)
p := NewAnthropicProvider("test-key", srv.URL)
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-fable-5"})
require.NoError(t, err)
var done *llm.ChatEvent
for ev := range stream {
if ev.Type == llm.EventDone {
ev := ev
done = &ev
}
}
require.NotNil(t, done)
assert.Equal(t, "end_turn", done.StopReason)
assert.Empty(t, done.StopCategory)
}
func TestAnthropicInputAccumulation(t *testing.T) {
var b strings.Builder
for _, part := range []string{`{"a"`, `:1`, `}`} {
b.WriteString(part)
}
require.Equal(t, `{"a":1}`, b.String())
}
+13 -8
View File
@@ -182,6 +182,8 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
go func() {
defer close(events)
var lastUsage *llm.Usage
for resp, err := range p.client.Models.GenerateContentStream(ctx, model, contents, config) {
if err != nil {
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
@@ -189,13 +191,9 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
if resp.UsageMetadata != nil {
events <- llm.ChatEvent{
Type: llm.EventDone,
Usage: &llm.Usage{
InputTokens: int(resp.UsageMetadata.PromptTokenCount),
OutputTokens: int(resp.UsageMetadata.CandidatesTokenCount),
},
}
lastUsage = updateUsage(lastUsage,
int(resp.UsageMetadata.PromptTokenCount),
int(resp.UsageMetadata.CandidatesTokenCount))
}
for _, cand := range resp.Candidates {
@@ -240,12 +238,19 @@ func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
// Ensure a Done event is always sent
events <- llm.ChatEvent{Type: llm.EventDone}
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
}()
return events, nil
}
// updateUsage returns a *llm.Usage carrying the latest cumulative counts.
// Gemini sends cumulative usage on multiple chunks; we keep only the last and
// emit a single EventDone at stream end (mirrors the OpenAI provider's lastUsage).
func updateUsage(_ *llm.Usage, prompt, candidates int) *llm.Usage {
return &llm.Usage{InputTokens: prompt, OutputTokens: candidates}
}
// geminiUnsupportedFields are JSON Schema fields Gemini's "OpenAPI 3.0
// subset" rejects. This is the broadest strip set across the four
// providers — most of the cross-provider portability gap shows up here.
+9
View File
@@ -24,3 +24,12 @@ func TestGeminiResolveSystemPromptEmpty(t *testing.T) {
got := geminiResolveSystemPrompt(llm.ChatRequest{})
require.Equal(t, "", got)
}
func TestGeminiUsageBuffer_KeepsLast(t *testing.T) {
var last *llm.Usage
last = updateUsage(last, 10, 5)
last = updateUsage(last, 20, 9) // final cumulative
require.NotNil(t, last)
require.Equal(t, 20, last.InputTokens)
require.Equal(t, 9, last.OutputTokens)
}
+38 -19
View File
@@ -271,11 +271,6 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
defer stream.Close()
// Track tool calls being built up across deltas
type pendingTC struct {
id string
name string
argsJSON string
}
toolCalls := make(map[int]*pendingTC)
var lastUsage *llm.Usage
@@ -337,25 +332,13 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
}
if tc.Function.Arguments != "" {
pending.argsJSON += tc.Function.Arguments
pending.args.WriteString(tc.Function.Arguments)
}
}
// Finish reason
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
// Emit completed tool calls
for _, tc := range toolCalls {
if tc.name != "" {
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: tc.id,
Name: tc.name,
Input: json.RawMessage(tc.argsJSON),
},
}
}
}
emitToolCalls(events, toolCalls)
}
}
}
@@ -366,6 +349,42 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
return events, nil
}
// pendingTC accumulates a single streamed tool call across deltas. The
// streamed tool-call index is the map key in toolCalls; the id, name, and
// arguments arrive in separate chunks.
type pendingTC struct {
id string
name string
args strings.Builder
}
// emitToolCalls sends EventToolCallDone for each completed tool call in
// ascending index order. The map key is the streamed tool-call index;
// iterating in order keeps the assistant message's tool_use block order
// deterministic across turns so the prompt cache stays warm.
func emitToolCalls(events chan<- llm.ChatEvent, toolCalls map[int]*pendingTC) {
maxIdx := -1
for idx := range toolCalls {
if idx > maxIdx {
maxIdx = idx
}
}
for idx := 0; idx <= maxIdx; idx++ {
tc, ok := toolCalls[idx]
if !ok || tc.name == "" {
continue
}
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: tc.id,
Name: tc.name,
Input: json.RawMessage(tc.args.String()),
},
}
}
}
// openaiUnsupportedFields are JSON Schema fields the OpenAI function-
// calling schema rejects. anyOf/oneOf/format are accepted and kept.
var openaiUnsupportedFields = []string{"$ref", "definitions"}
+19
View File
@@ -73,3 +73,22 @@ func TestOpenAIChatStreamPartsBeatString(t *testing.T) {
require.GreaterOrEqual(t, len(captured.Messages), 1)
require.Equal(t, "new", captured.Messages[0].Content)
}
func TestEmitToolCalls_OrderedByIndex(t *testing.T) {
mk := func(id, name string) *pendingTC {
p := &pendingTC{id: id, name: name}
p.args.WriteString("{}")
return p
}
toolCalls := map[int]*pendingTC{2: mk("c", "third"), 0: mk("a", "first"), 1: mk("b", "second")}
ch := make(chan llm.ChatEvent, 10)
emitToolCalls(ch, toolCalls)
close(ch)
var ids []string
for ev := range ch {
if ev.Type == llm.EventToolCallDone {
ids = append(ids, ev.ToolCall.ID)
}
}
require.Equal(t, []string{"a", "b", "c"}, ids, "tool calls must emit in index order")
}
+43 -23
View File
@@ -14,6 +14,41 @@ import (
"github.com/sausheong/harness/llm"
)
// pendingTC accumulates a streamed tool call across deltas. args uses
// strings.Builder so repeated argument fragments append in O(n) total
// (not O(n²) from string concatenation).
type pendingTC struct {
id string
name string
args strings.Builder
}
// emitToolCalls sends EventToolCallDone for each completed tool call in
// ascending index order so tool_use block order is deterministic across
// turns (prompt-cache stability).
func emitToolCalls(events chan<- llm.ChatEvent, toolCalls map[int]*pendingTC) {
maxIdx := -1
for idx := range toolCalls {
if idx > maxIdx {
maxIdx = idx
}
}
for idx := 0; idx <= maxIdx; idx++ {
tc, ok := toolCalls[idx]
if !ok || tc.name == "" {
continue
}
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: tc.id,
Name: tc.name,
Input: json.RawMessage(tc.args.String()),
},
}
}
}
// QwenProvider implements llm.LLMProvider using the Qwen Chat Completions API.
// Qwen uses an OpenAI-compatible API, so we reuse the go-openai client.
type QwenProvider struct {
@@ -169,10 +204,11 @@ func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-c
}
openaiReq := openai.ChatCompletionRequest{
Model: model,
Messages: msgs,
MaxTokens: maxTokens,
Stream: true,
Model: model,
Messages: msgs,
MaxCompletionTokens: maxTokens,
Stream: true,
StreamOptions: &openai.StreamOptions{IncludeUsage: true},
}
if len(tools) > 0 {
@@ -217,11 +253,6 @@ func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-c
defer stream.Close()
// Track tool calls being built up across deltas
type pendingTC struct {
id string
name string
argsJSON string
}
toolCalls := make(map[int]*pendingTC)
for {
@@ -271,25 +302,14 @@ func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-c
}
}
if tc.Function.Arguments != "" {
pending.argsJSON += tc.Function.Arguments
pending.args.WriteString(tc.Function.Arguments)
}
}
// Finish reason
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
// Emit completed tool calls
for _, tc := range toolCalls {
if tc.name != "" {
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: tc.id,
Name: tc.name,
Input: json.RawMessage(tc.argsJSON),
},
}
}
}
// Emit completed tool calls in index order.
emitToolCalls(events, toolCalls)
}
}
}
+19
View File
@@ -24,3 +24,22 @@ func TestQwenResolveSystemPromptEmpty(t *testing.T) {
got := qwenResolveSystemPrompt(llm.ChatRequest{})
require.Equal(t, "", got)
}
func TestEmitToolCalls_OrderedByIndex(t *testing.T) {
mk := func(id, name string) *pendingTC {
p := &pendingTC{id: id, name: name}
p.args.WriteString("{}")
return p
}
toolCalls := map[int]*pendingTC{1: mk("b", "second"), 0: mk("a", "first")}
ch := make(chan llm.ChatEvent, 10)
emitToolCalls(ch, toolCalls)
close(ch)
var ids []string
for ev := range ch {
if ev.Type == llm.EventToolCallDone {
ids = append(ids, ev.ToolCall.ID)
}
}
require.Equal(t, []string{"a", "b"}, ids)
}
+63 -7
View File
@@ -246,7 +246,7 @@ func TestPruneToolResults(t *testing.T) {
}
// Empty spillConfig → legacy in-place truncation path.
pruneToolResults(msgs, 10000, spillConfig{})
pruneToolResults(msgs, 10000, spillConfig{}, nil)
// User message should be unchanged
assert.Equal(t, "hello", msgs[0].Content)
@@ -261,7 +261,7 @@ func TestPruneToolResultsShort(t *testing.T) {
{Role: "user", Content: "short output", ToolCallID: "tc_1"},
}
pruneToolResults(msgs, 10000, spillConfig{})
pruneToolResults(msgs, 10000, spillConfig{}, nil)
assert.Equal(t, "short output", msgs[0].Content)
}
@@ -279,7 +279,7 @@ func TestPruneToolResultsNewlineBoundary(t *testing.T) {
{Role: "user", Content: content, ToolCallID: "tc_1"},
}
pruneToolResults(msgs, 10000, spillConfig{})
pruneToolResults(msgs, 10000, spillConfig{}, nil)
// Should be truncated and contain the truncation marker
truncated := msgs[0].Content
@@ -298,7 +298,7 @@ func TestPruneToolResultsSpillsToDisk(t *testing.T) {
{Role: "user", Content: original, ToolCallID: "tc_42"},
}
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_abc"})
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_abc"}, nil)
// Message rewritten to head + spill marker pointing at the file.
got := msgs[0].Content
@@ -324,14 +324,14 @@ func TestPruneToolResultsIdempotentAfterSpill(t *testing.T) {
{Role: "user", Content: strings.Repeat("b", 20000), ToolCallID: "tc_99"},
}
pruneToolResults(msgs, 10000, cfg)
pruneToolResults(msgs, 10000, cfg, nil)
afterFirst := msgs[0].Content
require.Contains(t, afterFirst, spillMarker)
// Second call: marker is present, so the message must be untouched.
// Mutating it (e.g. spilling again or appending another marker)
// would silently grow the prefill across turns and burn cache.
pruneToolResults(msgs, 10000, cfg)
pruneToolResults(msgs, 10000, cfg, nil)
assert.Equal(t, afterFirst, msgs[0].Content)
}
@@ -349,7 +349,7 @@ func TestPruneToolResultsFallsBackToTruncationWhenSpillFails(t *testing.T) {
{Role: "user", Content: strings.Repeat("c", 20000), ToolCallID: "tc_fail"},
}
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_fail"})
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_fail"}, nil)
got := msgs[0].Content
assert.Less(t, len(got), 20000, "fallback must still bound the message")
@@ -357,6 +357,31 @@ func TestPruneToolResultsFallsBackToTruncationWhenSpillFails(t *testing.T) {
assert.NotContains(t, got, spillMarker, "spilled marker must not appear when write failed")
}
func TestPruneToolResultsSpillsOncePerID(t *testing.T) {
workspace := t.TempDir()
cfg := spillConfig{Workspace: workspace, SessionKey: "sess_once"}
spilled := map[string]bool{}
big := strings.Repeat("x", 50000)
mk := func() []llm.Message {
return []llm.Message{{ToolCallID: "call_big", Content: big}}
}
m1 := mk()
pruneToolResults(m1, 10000, cfg, spilled)
require.Contains(t, m1[0].Content, spillMarker)
spillPath := filepath.Join(workspace, ".harness", "spill", "sess_once", "call_big.txt")
require.FileExists(t, spillPath)
require.True(t, spilled["call_big"], "ID recorded as spilled")
require.NoError(t, os.Remove(spillPath))
m2 := mk()
pruneToolResults(m2, 10000, cfg, spilled)
require.Contains(t, m2[0].Content, spillMarker, "message still rewritten to the marker")
require.NoFileExists(t, spillPath, "turn 2 must NOT re-write the spill file (idempotent via spilled set)")
}
// --- Runtime tests ---
func TestRuntimeRun(t *testing.T) {
@@ -871,6 +896,37 @@ func TestRun_AbortMidDispatchProducesPairedSession(t *testing.T) {
}
}
// TestRunSync_ReturnsErrorOnAbort verifies that RunSync surfaces an aborted run
// as a non-nil error (context.Canceled) rather than returning (partialText,
// nil). Cron/sync callers must be able to distinguish a completed run from a
// cancelled one. Reuses the same abort scaffolding as
// TestRun_AbortMidDispatchProducesPairedSession (a tool batch + cancelOnNth).
func TestRunSync_ReturnsErrorOnAbort(t *testing.T) {
threeToolCalls := []llm.ToolCall{
{ID: "tc_0", Name: "noop", Input: json.RawMessage(`{}`)},
{ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`)},
{ID: "tc_2", Name: "noop", Input: json.RawMessage(`{}`)},
}
llmFake := &threeToolCallLLM{toolCalls: threeToolCalls}
ctx, cancel := context.WithCancel(context.Background())
count := 0
exec := &cancelOnNthExecutor{n: 1, cancel: cancel, count: &count}
r := &Runtime{
LLM: llmFake,
Tools: exec,
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test-model",
MaxTurns: 5,
}
_, err := r.RunSync(ctx, "go", nil)
require.Error(t, err)
require.ErrorIs(t, err, context.Canceled)
}
// threeToolCallLLM emits the configured tool_calls as one assistant turn,
// then EventDone. On the next call (after tool results, if the runtime
// loops back), emits only EventDone with no tool_calls so Run terminates.
+58
View File
@@ -0,0 +1,58 @@
package runtime
import (
"context"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tokens"
"github.com/sausheong/harness/tool"
"github.com/stretchr/testify/require"
)
// usageDoneProvider emits a usage-bearing EventDone so the agent loop can
// populate (and persist) the per-session token calibrator.
type usageDoneProvider struct {
llmtest.Base
}
func (p *usageDoneProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
ch := make(chan llm.ChatEvent, 4)
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "answer"}
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 1000, OutputTokens: 10}}
close(ch)
return ch, nil
}
// TestCalibratorPersistsByEndOfRun guards that the per-session calibrator is
// persisted to the CalibratorStore by the time Run completes. After the P8
// debounce change the Save moves from per-round to a single deferred flush at
// Run end; this test asserts the observable end state (persisted) is unchanged.
func TestCalibratorPersistsByEndOfRun(t *testing.T) {
dir := t.TempDir()
store := tokens.NewCalibratorStore(dir)
rt := &Runtime{
LLM: &usageDoneProvider{},
Tools: tool.NewRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "claude-sonnet-4-5",
// Compaction must be non-nil for the runtime to lazily create the
// per-session calibrator (the calibrator-creation path is gated on
// it). MessageCap/threshold left at defaults so no compaction fires
// during this short run.
Compaction: newCompactionMgr(),
Provider: "anthropic",
MaxTurns: 2,
Workspace: t.TempDir(),
CalibratorStore: store,
}
_, err := rt.RunSync(context.Background(), "go", nil)
require.NoError(t, err)
ratio, count := tokens.NewCalibratorStore(dir).Load("a", "k")
require.Greater(t, count, 0, "calibrator must be persisted by end of Run")
require.Greater(t, ratio, 0.0)
}
+27
View File
@@ -0,0 +1,27 @@
package runtime
import (
"os"
"strconv"
)
// maxToolResultLen returns the per-result truncation cap (chars) for tool
// results in the in-context message history. Precedence:
// 1. Runtime.AgentLoop.MaxToolResultLen (>0) — config wins.
// 2. HARNESS_MAX_TOOL_RESULT_LEN env var (>0) — env fallback.
// 3. defaultMaxToolResultLen (4000).
//
// Tool results longer than this are truncated (or spilled to disk via
// spillConfig when supplied). 4000 is conservative; engineering-style
// agents that read source files and run tests typically want 16000-25000.
func (r *Runtime) maxToolResultLen() int {
if r.AgentLoop.MaxToolResultLen > 0 {
return r.AgentLoop.MaxToolResultLen
}
if v := os.Getenv("HARNESS_MAX_TOOL_RESULT_LEN"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
return n
}
}
return defaultMaxToolResultLen
}
+50
View File
@@ -0,0 +1,50 @@
package runtime
import (
"testing"
)
// TestMaxToolResultLen_Precedence locks in the config > env > default
// precedence so a regression here doesn't silently swap one source for
// another.
func TestMaxToolResultLen_Precedence(t *testing.T) {
t.Run("default when nothing set", func(t *testing.T) {
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "")
r := &Runtime{}
if got := r.maxToolResultLen(); got != defaultMaxToolResultLen {
t.Fatalf("want %d, got %d", defaultMaxToolResultLen, got)
}
})
t.Run("env overrides default", func(t *testing.T) {
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "12345")
r := &Runtime{}
if got := r.maxToolResultLen(); got != 12345 {
t.Fatalf("want 12345, got %d", got)
}
})
t.Run("config overrides env", func(t *testing.T) {
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "12345")
r := &Runtime{AgentLoop: LoopConfig{MaxToolResultLen: 25000}}
if got := r.maxToolResultLen(); got != 25000 {
t.Fatalf("want 25000, got %d", got)
}
})
t.Run("zero env is ignored", func(t *testing.T) {
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "0")
r := &Runtime{}
if got := r.maxToolResultLen(); got != defaultMaxToolResultLen {
t.Fatalf("want %d, got %d", defaultMaxToolResultLen, got)
}
})
t.Run("garbage env is ignored", func(t *testing.T) {
t.Setenv("HARNESS_MAX_TOOL_RESULT_LEN", "not-a-number")
r := &Runtime{}
if got := r.maxToolResultLen(); got != defaultMaxToolResultLen {
t.Fatalf("want %d, got %d", defaultMaxToolResultLen, got)
}
})
}
+57
View File
@@ -0,0 +1,57 @@
package runtime
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
anthropicprovider "github.com/sausheong/harness/providers/anthropic"
)
// cachingCapableFake implements llm.LLMProvider plus the
// llm.PromptCachingProvider capability.
type cachingCapableFake struct {
llmtest.Stub
}
func (*cachingCapableFake) SupportsPromptCaching() bool { return true }
// TestProviderSupportsCaching_CapabilityInterfaceWins: an Anthropic-shaped
// provider registered under a custom name (platformai, bedrock, any relay)
// must still get prompt caching. Gating on the config block's NAME meant
// every turn on a renamed provider re-processed the full history uncached.
func TestProviderSupportsCaching_CapabilityInterfaceWins(t *testing.T) {
r := &Runtime{Provider: "platformai", LLM: &cachingCapableFake{}}
assert.True(t, r.providerSupportsCaching(),
"capability interface must win over the provider name")
}
func TestProviderSupportsCaching_NameFallbackStillWorks(t *testing.T) {
r := &Runtime{Provider: "anthropic", LLM: &llmtest.Stub{}}
assert.True(t, r.providerSupportsCaching(),
"legacy name-based gate kept for providers without the capability interface")
}
func TestProviderSupportsCaching_NonCachingProviderFalse(t *testing.T) {
r := &Runtime{Provider: "local", LLM: &llmtest.Stub{}}
assert.False(t, r.providerSupportsCaching())
}
// TestAnthropicProviderDeclaresPromptCaching pins the wiring end-to-end:
// the real Anthropic provider must implement the capability interface.
func TestAnthropicProviderDeclaresPromptCaching(t *testing.T) {
p := anthropicprovider.NewAnthropicProvider("k", "")
pc, ok := any(p).(llm.PromptCachingProvider)
assert.True(t, ok, "AnthropicProvider must implement llm.PromptCachingProvider")
if ok {
assert.True(t, pc.SupportsPromptCaching())
}
}
// Mid-loop compaction was gated on the same name list; an Anthropic-shaped
// provider under a custom name must support it too.
func TestProviderSupportsMidLoopCompaction_CapabilityInterfaceWins(t *testing.T) {
r := &Runtime{Provider: "platformai", LLM: &cachingCapableFake{}}
assert.True(t, r.providerSupportsMidLoopCompaction())
}
+27 -21
View File
@@ -11,9 +11,15 @@ import (
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
)
const maxToolResultLen = 4000 // truncate tool results longer than this
// defaultMaxToolResultLen is the fallback cap used when LoopConfig.MaxToolResultLen
// is unset and the HARNESS_MAX_TOOL_RESULT_LEN env var is unset/invalid. Tool
// results longer than this get truncated (or spilled to disk + truncated-with-
// marker when spillConfig is supplied). 4000 chars (~1000 tokens) is conservative
// so behaviour is unchanged for callers that don't opt into a larger budget.
const defaultMaxToolResultLen = 4000
// detectImageMIME returns the actual MIME type based on magic bytes.
// Falls back to the provided hint if the format is unrecognized.
@@ -162,17 +168,6 @@ func buildDynamicSystemPromptSuffix(dateLine, cortexContext string) string {
// corresponding tool_result in the next user message. Orphaned tool calls
// (e.g. from interrupted sessions) get synthetic error results injected.
func assembleMessages(history []session.SessionEntry) []llm.Message {
// First pass: collect tool result IDs so we can detect orphaned tool calls.
resultIDs := make(map[string]bool)
for _, entry := range history {
if entry.Type == session.EntryTypeToolResult {
var tr session.ToolResultData
if err := json.Unmarshal(entry.Data, &tr); err == nil {
resultIDs[tr.ToolCallID] = true
}
}
}
var msgs []llm.Message
for _, entry := range history {
@@ -213,9 +208,6 @@ func assembleMessages(history []session.SessionEntry) []llm.Message {
if err := json.Unmarshal(entry.Data, &md); err != nil {
continue
}
// Before appending a new message, check if the last assistant
// message has orphaned tool calls that need synthetic results.
msgs = injectMissingToolResults(msgs)
msg := llm.Message{
Role: entry.Role,
Content: md.Text,
@@ -428,7 +420,7 @@ func spillToolResult(cfg spillConfig, toolCallID, content string) (string, error
return "", fmt.Errorf("spill mkdir: %w", err)
}
path := filepath.Join(dir, toolCallID+".txt")
if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
if err := tool.WriteFileAtomic(path, []byte(content), 0o600); err != nil {
return "", fmt.Errorf("spill write: %w", err)
}
return path, nil
@@ -455,7 +447,7 @@ func spillToolResult(cfg spillConfig, toolCallID, content string) (string, error
// nearest newline boundary — most tool outputs (file reads, command
// output) are front-loaded with the most relevant info, so the head
// preview is usually enough on its own.
func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig) {
func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig, spilled map[string]bool) {
for i := range msgs {
if msgs[i].ToolCallID == "" || len(msgs[i].Content) <= maxLen {
continue
@@ -475,11 +467,25 @@ func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig) {
// Try spill first if configured. On any failure, fall through to
// legacy truncation so the prefill stays bounded either way.
if cfg.Workspace != "" && cfg.SessionKey != "" {
if path, err := spillToolResult(cfg, msgs[i].ToolCallID, msgs[i].Content); err == nil {
id := msgs[i].ToolCallID
// Spill content is immutable per ToolCallID and lands at a
// deterministic path. If this Run already spilled this ID,
// skip the (multi-MB) disk re-write and just rebuild the
// in-memory marker pointing at the same path.
if spilled != nil && spilled[id] {
path := filepath.Join(cfg.Workspace, ".harness", "spill", cfg.SessionKey, id+".txt")
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars saved to %s; use read_file to access the full output]",
head, spillMarker, len(head), originalLen, path)
continue
}
if writtenPath, err := spillToolResult(cfg, id, msgs[i].Content); err == nil {
if spilled != nil {
spilled[id] = true
}
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars saved to %s; use read_file to access the full output]",
head, spillMarker, len(head), originalLen, writtenPath)
continue
}
}
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars; re-run the tool with offset/limit to see more]",
@@ -501,8 +507,8 @@ func FormatDateLine(now time.Time) string {
// PostCompactRestoreFiles caps how many recently-touched files
// buildPostCompactRestore re-injects after a successful compaction.
// 5 mirrors Claude Code's harness behaviour (harness.md §3) and keeps
// the restore message bounded.
// 5 keeps the restore message bounded while covering the typical
// "the last few files I was working on" recall horizon.
const PostCompactRestoreFiles = 5
// PostCompactRestoreBytesPerFile bounds the per-file byte budget for
@@ -542,7 +548,7 @@ func extractPathFromInput(raw []byte) string {
//
// Format is wrapped in <system-reminder>...<file path="...">...</file>
// tags so the model recognises it as out-of-band context, not a fresh
// user request. Mirrors how Claude Code re-injects POST_COMPACT files.
// user request.
func buildPostCompactRestore(files []string, maxFiles, maxBytesPerFile int) llm.Message {
if len(files) == 0 || maxFiles <= 0 || maxBytesPerFile <= 0 {
return llm.Message{}
+27
View File
@@ -1,12 +1,14 @@
package runtime
import (
jsonpkg "encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/sausheong/harness/session"
"github.com/stretchr/testify/require"
)
@@ -123,3 +125,28 @@ func TestFormatDateLine(t *testing.T) {
})
}
}
func mustJSON(t *testing.T, v any) jsonpkg.RawMessage {
t.Helper()
b, err := jsonpkg.Marshal(v)
require.NoError(t, err)
return b
}
func TestAssembleMessagesInjectsOrphanedToolResult(t *testing.T) {
history := []session.SessionEntry{
{Type: session.EntryTypeMessage, Role: "user", Data: mustJSON(t, session.MessageData{Text: "hi"})},
{Type: session.EntryTypeToolCall, Role: "assistant", Data: mustJSON(t, session.ToolCallData{
ID: "call_1", Tool: "bash", Input: jsonpkg.RawMessage(`{}`),
})},
{Type: session.EntryTypeMessage, Role: "user", Data: mustJSON(t, session.MessageData{Text: "still there?"})},
}
msgs := assembleMessages(history)
var found bool
for _, m := range msgs {
if m.ToolCallID == "call_1" {
found = true
}
}
require.True(t, found, "orphaned tool call must get a synthetic tool result from the terminal pass")
}
+107
View File
@@ -266,3 +266,110 @@ func TestBuildRuntimeRejectsCrossProviderFallback(t *testing.T) {
func decodeMessage(e session.SessionEntry, dst *session.MessageData) error {
return json.Unmarshal(e.Data, dst)
}
// refusalThenSuccessProvider returns a classifier-refusal stream (HTTP
// 200, EventDone with StopReason=refusal, no content) on the first call
// and a normal text stream on the second. Mirrors Claude Fable 5 safety
// classifier behavior: refusals are NOT transport errors, so the
// existing IsRetryableModelError path never sees them.
type refusalThenSuccessProvider struct {
llmtest.Base
calls int
modelsSeen []string
finalText string
}
func (p *refusalThenSuccessProvider) ChatStream(_ context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.calls++
p.modelsSeen = append(p.modelsSeen, req.Model)
ch := make(chan llm.ChatEvent, 4)
if p.calls == 1 {
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: llm.StopReasonRefusal, StopCategory: "bio"}
} else {
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: p.finalText}
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: "end_turn"}
}
close(ch)
return ch, nil
}
// TestRuntimeRefusalRetriesOnFallbackModel: a refusal turn with a
// configured fallback must transparently re-run the turn on the
// fallback model instead of surfacing an empty response.
func TestRuntimeRefusalRetriesOnFallbackModel(t *testing.T) {
prov := &refusalThenSuccessProvider{finalText: "fallback answered"}
rt := &Runtime{
LLM: prov,
Tools: tool.NewRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "claude-fable-5",
FallbackModel: "claude-opus-4-8",
Provider: "anthropic",
MaxTurns: 3,
Workspace: t.TempDir(),
}
out, err := rt.RunSync(context.Background(), "summarise the biology article", nil)
require.NoError(t, err)
assert.Equal(t, "fallback answered", out)
require.Equal(t, 2, prov.calls, "refusal + fallback retry = 2 calls")
assert.Equal(t, "claude-fable-5", prov.modelsSeen[0])
assert.Equal(t, "claude-opus-4-8", prov.modelsSeen[1])
}
// alwaysRefusalProvider refuses every call — covers the no-fallback and
// fallback-also-refused paths.
type alwaysRefusalProvider struct {
llmtest.Base
calls int
}
func (p *alwaysRefusalProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.calls++
ch := make(chan llm.ChatEvent, 2)
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: llm.StopReasonRefusal, StopCategory: "cyber"}
close(ch)
return ch, nil
}
// TestRuntimeRefusalWithoutFallbackSurfacesVisibleText: with no fallback
// the user must see an explanation, not an empty response.
func TestRuntimeRefusalWithoutFallbackSurfacesVisibleText(t *testing.T) {
prov := &alwaysRefusalProvider{}
rt := &Runtime{
LLM: prov,
Tools: tool.NewRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "claude-fable-5",
Provider: "anthropic",
MaxTurns: 3,
Workspace: t.TempDir(),
}
out, err := rt.RunSync(context.Background(), "do something", nil)
require.NoError(t, err, "a refusal is a model decision, not a transport error")
assert.Contains(t, out, "declined", "refusal must produce visible explanation text")
assert.Contains(t, out, "cyber", "category should be included when present")
assert.Equal(t, 1, prov.calls, "no fallback configured → no retry")
}
// TestRuntimeRefusalFallbackAlsoRefusesSurfacesText: when the fallback
// refuses too, stop (no infinite retry) and surface the explanation.
func TestRuntimeRefusalFallbackAlsoRefusesSurfacesText(t *testing.T) {
prov := &alwaysRefusalProvider{}
rt := &Runtime{
LLM: prov,
Tools: tool.NewRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "claude-fable-5",
FallbackModel: "claude-opus-4-8",
Provider: "anthropic",
MaxTurns: 3,
Workspace: t.TempDir(),
}
out, err := rt.RunSync(context.Background(), "do something", nil)
require.NoError(t, err)
assert.Contains(t, out, "declined")
assert.Equal(t, 2, prov.calls, "primary + one fallback attempt, then stop")
}
+354
View File
@@ -0,0 +1,354 @@
// Package runtime — Review primitive.
//
// runtime.Review runs a one-shot reviewer Runtime against a finished
// parent session, designed to be called from LifecycleHooks.OnStop in
// a goroutine. The reviewer sees a snapshot of the parent's
// conversation but writes durable memory/skills into the SHARED stores
// the parent reads from — that's how an agent built on harness curates
// its own memory and skill library across sessions.
//
// Typical wiring (10 lines from OnStop):
//
// spec.Loop.Hooks.OnStop = func(ctx context.Context, reason string) {
// if reason != "completed" { return }
// go func() {
// runtime.Review(context.Background(), rt, runtime.ReviewSpec{
// Prompt: runtime.ReviewPromptDefault,
// Tools: reviewTools,
// })
// }()
// }
//
// Note: pass context.Background() — the parent's ctx is canceled by
// the time OnStop fires.
//
// Concurrency: if your OnStop loop fires Review concurrently (e.g.,
// back-to-back turns where reviewer N is still running when turn N+1
// completes), ensure your MemoryStore/SkillStore are concurrency-safe.
// The bundled tool/memory/jsonl and tool/skills/disk implementations
// are; custom backends must guarantee safe concurrent writes.
package runtime
import (
"context"
"encoding/json"
"errors"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/sausheong/harness/tool/memory"
"github.com/sausheong/harness/tool/skills"
)
// ReviewSpec describes one reviewer pass over the parent Runtime's
// just-finished session. Only Prompt and Tools are required.
type ReviewSpec struct {
// Prompt is the user-message-shaped review instruction handed to
// the reviewer LLM. Use ReviewPromptDefault or ReviewPromptVerbose
// from review_prompts.go, or write your own.
Prompt string
// Tools is the restricted toolset the reviewer can call. Typically
// just write-only memory + skill tools so the reviewer can't read
// files or execute shell commands. Required.
Tools tool.Executor
// MaxTurns caps the reviewer's tool-use loop, counted independently
// of the parent's MaxTurns. 0 → default 16.
MaxTurns int
// Timeout is the hard envelope for the reviewer's Run. The reviewer
// is canceled when exceeded; partial Actions are returned. 0 →
// default 60 seconds.
Timeout time.Duration
// Provider, when non-nil, routes the reviewer to a (typically
// cheaper) auxiliary LLM. nil → inherit parent.LLM.
Provider llm.LLMProvider
// Model overrides the parent's model id. "" → inherit parent.Model.
Model string
// ContextWindow overrides the parent's context window. 0 → inherit.
ContextWindow int
// SystemPrompt overrides the reviewer's static system prompt. "" →
// the reviewer gets a minimal default identity composed from its
// tool names.
SystemPrompt string
// Permission, when non-nil, gates the reviewer's tool calls.
// nil → allow-all (the reviewer's tool registry is already
// restricted by spec.Tools).
Permission tool.PermissionChecker
// Memory, when non-nil, overrides the parent's MemoryProvider.
// nil → inherit (writes share the parent's memory store).
Memory MemoryProvider
// Skills, when non-nil, overrides the parent's SkillProvider.
// nil → inherit (writes share the parent's skill store).
Skills SkillProvider
// OnEvent, when non-nil, receives a copy of every reviewer event
// as it arrives. nil → events are drained silently. Run on the
// reviewer goroutine; keep callbacks fast.
OnEvent func(AgentEvent)
}
// ReviewResult summarizes one Review pass.
type ReviewResult struct {
// Actions is the list of human-readable one-liners extracted from
// the reviewer's successful tool calls (the "message" field of the
// canonical {"success": true, "message": "...", "target": "..."}
// JSON envelope).
Actions []string
// ToolCalls is the count of tool_call entries the reviewer made
// (regardless of success).
ToolCalls int
// Turns is the count of LLM turns the reviewer used.
Turns int
// Duration is the wall time from the start of Review to its return
// (including snapshot + Run + extraction).
Duration time.Duration
// Err is non-nil for setup failures (recursion guard, nil Tools,
// build errors). Mid-Run failures (LLM errors, tool errors) are
// counted in Turns/ToolCalls but do not populate Err — partial
// Actions are returned.
Err error
}
// ErrReviewRecursion is returned (via ReviewResult.Err) when Review is
// called on a Runtime whose AgentID is the reserved "__review__"
// sentinel — i.e., the reviewer would itself spawn a reviewer.
var ErrReviewRecursion = errors.New("runtime: review recursion (parent is itself a reviewer)")
// reviewerAgentID is the reserved AgentID assigned to every reviewer
// Runtime. Review checks parent.AgentID against this value and refuses
// to recurse.
const reviewerAgentID = "__review__"
// Review runs a one-shot reviewer Runtime against parent's just-
// finished session. See package doc for the typical OnStop wiring.
//
// Required spec fields: Prompt, Tools. All other fields have sensible
// defaults (see ReviewSpec doc-comments).
//
// Returns ReviewResult with non-nil Err for setup failures (nil parent,
// recursion guard, nil Tools, empty Prompt, build errors). Mid-Run
// failures populate Turns/ToolCalls but leave Err nil.
//
// Cancelation: pass context.Background() when calling from OnStop —
// the parent's ctx is canceled by the time OnStop fires.
func Review(ctx context.Context, parent *Runtime, spec ReviewSpec) ReviewResult {
start := time.Now()
if parent == nil {
return ReviewResult{Err: errors.New("runtime.Review: parent Runtime is nil"), Duration: time.Since(start)}
}
if parent.AgentID == reviewerAgentID {
return ReviewResult{Err: ErrReviewRecursion, Duration: time.Since(start)}
}
if spec.Tools == nil {
return ReviewResult{Err: errors.New("runtime.Review: spec.Tools is required"), Duration: time.Since(start)}
}
if spec.Prompt == "" {
return ReviewResult{Err: errors.New("runtime.Review: spec.Prompt is required"), Duration: time.Since(start)}
}
rt, err := buildReviewerRuntime(parent, spec)
if err != nil {
return ReviewResult{Err: err, Duration: time.Since(start)}
}
defer rt.Close()
// Capture the inherited prefix length BEFORE the reviewer runs so
// extractActions can skip parent-session entries and only extract
// tool-result envelopes appended by the reviewer itself.
inheritedCount := len(rt.Session.View())
// Apply hard timeout. If spec.Timeout is 0, default to 60s.
timeout := spec.Timeout
if timeout == 0 {
timeout = 60 * time.Second
}
runCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Provenance: tag every memory/skills write the reviewer makes
// with origin "review". Both keys are independent (per-package
// design); set both so whichever tool the reviewer calls picks up
// the right value without coordination.
runCtx = context.WithValue(runCtx, memory.OriginKey, "review")
runCtx = context.WithValue(runCtx, skills.OriginKey, "review")
events, err := rt.Run(runCtx, spec.Prompt, nil)
if err != nil {
return ReviewResult{Err: err, Duration: time.Since(start)}
}
// Drain events. Forward to OnEvent if set; count Turns and ToolCalls.
var turns, toolCalls int
for ev := range events {
if spec.OnEvent != nil {
spec.OnEvent(ev)
}
switch ev.Type {
case EventToolCallStart:
toolCalls++
case EventDone:
turns++
}
}
actions := extractActions(rt.Session, inheritedCount)
return ReviewResult{
Actions: actions,
Turns: turns,
ToolCalls: toolCalls,
Duration: time.Since(start),
}
}
// extractActions walks sess.View() starting at startIdx and returns
// the Message field of every tool_result entry whose Output parses as
// the canonical action-result envelope with Success=true.
//
// Convention is over schema: tools that don't emit the envelope
// (e.g. list returns a raw array, get returns the entry struct, edit
// tools return plain text) are silently skipped.
//
// Note: SessionEntry stores the per-type payload as a json.RawMessage
// in the Data field, so we first unmarshal Data into ToolResultData to
// recover Output, then unmarshal Output into the action envelope.
func extractActions(sess *session.Session, startIdx int) []string {
view := sess.View()
if startIdx >= len(view) {
return nil
}
var actions []string
for _, e := range view[startIdx:] {
if e.Type != session.EntryTypeToolResult {
continue
}
var tr session.ToolResultData
if err := json.Unmarshal(e.Data, &tr); err != nil {
continue
}
var env struct {
Success bool `json:"success"`
Message string `json:"message"`
}
if err := json.Unmarshal([]byte(tr.Output), &env); err != nil {
continue
}
if !env.Success || env.Message == "" {
continue
}
actions = append(actions, env.Message)
}
return actions
}
// buildReviewerRuntime constructs a Runtime configured for a one-shot
// review pass over parent's just-finished session.
//
// Inheritance defaults:
// - LLM: spec.Provider, falling back to parent.LLM
// - Model: spec.Model, falling back to parent.Provider+"/"+parent.Model
// - ContextWindow: spec.ContextWindow, falling back to parent.ContextWindow
// - Workspace: parent.Workspace (for trace/spill paths)
// - Memory: spec.Memory, falling back to parent.Memory (SHARED, not snapshotted)
// - Skills: spec.Skills, falling back to parent.Skills (SHARED)
// - Permission: spec.Permission (NOT inherited from parent — defaults to nil)
// - SystemPrompt: spec.SystemPrompt (override) or empty (default identity built from tool names)
// - MaxTurns: spec.MaxTurns or 16
//
// Always-set on reviewer:
// - AgentID = "__review__" (recursion guard)
// - IngestSource = "review" (KG ingest skips)
// - Hooks zeroed (no OnStop reentry, no observation noise)
// - KG nil (reviewer doesn't recall or ingest)
// - Compaction nil (short-lived; MaxTurns 16 keeps context small)
func buildReviewerRuntime(parent *Runtime, spec ReviewSpec) (*Runtime, error) {
provider := spec.Provider
if provider == nil {
provider = parent.LLM
}
model := spec.Model
if model == "" {
// Re-compose parent.Provider/parent.Model since runtime stores
// them split (after ParseProviderModel).
if parent.Provider != "" && parent.Model != "" {
model = parent.Provider + "/" + parent.Model
} else {
model = parent.Model // best-effort fallback when parent has no provider
}
}
ctxWindow := spec.ContextWindow
if ctxWindow == 0 {
ctxWindow = parent.ContextWindow
}
mem := spec.Memory
if mem == nil {
mem = parent.Memory
}
skillProv := spec.Skills
if skillProv == nil {
skillProv = parent.Skills
}
maxTurns := spec.MaxTurns
if maxTurns == 0 {
maxTurns = 16
}
deps := RuntimeDeps{
Skills: skillProv,
Memory: mem,
Permission: spec.Permission, // defaults to nil = allow-all
// KGFn nil — reviewer never recalls or ingests
// AgentLoop zeroed — Hooks left nil so no OnStop reentry
}
inputs := RuntimeInputs{
Provider: provider,
Tools: spec.Tools,
Session: snapshotSession(parent.Session),
Compaction: nil, // reviewer is short-lived
IngestSource: "review",
}
agentSpec := AgentSpec{
ID: reviewerAgentID,
Name: "Review",
Model: model,
Workspace: parent.Workspace,
SystemPrompt: spec.SystemPrompt,
MaxTurns: maxTurns,
ContextWindow: ctxWindow,
}
rt, err := BuildRuntime(deps, inputs, agentSpec)
if err != nil {
return nil, err
}
return rt, nil
}
// snapshotSession returns a fresh *session.Session that contains a
// copy of parent's current View. The clone preserves AgentID (so the
// reviewer sees the same agent identity in entries) but rewrites Key
// to "review-" + parent.Key — this ensures the reviewer's compaction
// locks don't contend with the parent's (locks are keyed on
// AgentID/Key) and that the JSONL store (if attached) writes to a
// separate file.
//
// The clone is in-memory only; SetStore is NOT called on it.
//
// Mirror of inheritParentHistory in subagent.go: the FIRST inherited
// entry gets its ParentID cleared so the fresh session's empty leaf
// doesn't leave a dangling pointer; subsequent entries chain naturally
// as Append re-stitches them.
func snapshotSession(parent *session.Session) *session.Session {
clone := session.NewSession(parent.AgentID, "review-"+parent.Key)
view := parent.View()
for i, e := range view {
if i == 0 {
e.ParentID = ""
}
clone.Append(e)
}
return clone
}
+90
View File
@@ -0,0 +1,90 @@
package runtime
import (
"context"
"path/filepath"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/sausheong/harness/tool/memory"
"github.com/sausheong/harness/tool/memory/jsonl"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestReview_Integration_MemorySaveRoundTrip wires:
// - jsonl.Store (real disk-backed memory, t.TempDir)
// - memory.MemoryTool over the store
// - Review with the tool registry restricted to memory only
// - A fake LLM (statefulReviewMock) that emits a single tool-call to memory.save
//
// Expected: after Review completes, the memory store has one entry with
// origin="review", visible via Get and FormatIndex.
func TestReview_Integration_MemorySaveRoundTrip(t *testing.T) {
dir := t.TempDir()
memStore := jsonl.NewStore(filepath.Join(dir, "memory.jsonl"))
reviewTools := tool.NewRegistry()
reviewTools.Register(&memory.MemoryTool{Store: memStore})
// Fake LLM: respond to the review prompt by calling memory.save once,
// then finish.
mock := &statefulReviewMock{
responses: [][]llm.ChatEvent{
// First call: emit a tool call to memory with action=save.
{
{Type: llm.EventToolCallStart, ToolCall: &llm.ToolCall{
ID: "tc_1", Name: "memory",
}},
{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{
ID: "tc_1",
Name: "memory",
Input: []byte(`{"action":"save","content":"user prefers terse explanations"}`),
}},
{Type: llm.EventDone},
},
// Second call: finish with text.
{
{Type: llm.EventTextDelta, Text: "Saved."},
{Type: llm.EventDone},
},
},
}
parent := &Runtime{
AgentID: "main",
AgentName: "Main",
Provider: "anthropic",
Model: "claude-haiku-4-5",
Workspace: dir,
Session: session.NewSession("main", "main"),
LLM: mock,
}
// Pre-seed parent's session with a sentinel exchange so the reviewer
// has something to read.
parent.Session.Append(session.UserMessageEntry("please use terse explanations"))
parent.Session.Append(session.AssistantMessageEntry("Got it."))
res := Review(context.Background(), parent, ReviewSpec{
Prompt: "review and save anything worth remembering",
Tools: reviewTools,
})
require.NoError(t, res.Err, "Review setup must succeed")
require.Len(t, res.Actions, 1, "exactly one save action expected")
assert.Contains(t, res.Actions[0], "saved memory")
// The store has the entry.
all, err := memStore.List(context.Background(), "")
require.NoError(t, err)
require.Len(t, all, 1)
assert.Equal(t, "user prefers terse explanations", all[0].Content)
assert.Equal(t, "review", all[0].Origin, `Origin must be set to "review" by the OriginKey context`)
// The provider adapter sees it too — proves the system-prompt path
// would pick it up on the next Run.
provider := memStore.AsMemoryProvider()
idx := provider.FormatIndex()
assert.Contains(t, idx, "user prefers terse explanations")
}
+68
View File
@@ -0,0 +1,68 @@
package runtime
// ReviewPromptDefault is the standard reviewer instruction. Concise:
// asks the reviewer to identify durable preferences/facts/workflows
// from the just-finished conversation and save them via memory or
// skill tools.
//
// Use as ReviewSpec.Prompt when you don't have a domain-specific
// reviewer prompt.
const ReviewPromptDefault = `You are reviewing a conversation that just completed. Your job is to extract anything worth remembering for future sessions.
Look for:
- User preferences (style, format, tools, conventions) — save as memory
- Project facts (architecture decisions, constraints, naming) — save as memory
- Reusable workflows or techniques the agent figured out — save as a skill
Use the memory tool (action=save) for short, durable facts. Use the skill_manage tool (action=create) for procedural knowledge that has its own name and would benefit from a body.
Skip:
- Things obvious from reading the code
- One-off task details that won't recur
- Information that's already been saved (check the existing memory and skills first via action=list)
If nothing is worth saving, do nothing and finish. A clean review is a successful review.`
// ReviewPromptVerbose is the elaborated reviewer instruction. Adds
// explicit examples and a worked-out decision tree. Use for stronger
// reviewers (capable models that benefit from longer context) or in
// the early days of a deployment when you want the reviewer to
// over-explain its choices.
const ReviewPromptVerbose = `You are reviewing a conversation that just completed between a user and an agent. Your job is to extract anything worth remembering for future sessions.
## What to look for
1. **User preferences** — style, format, tools, conventions the user has expressed. Examples:
- "User prefers terse explanations without summaries at the end"
- "User wants commits without Co-Authored-By trailers"
- "User runs Go tests with -race by default"
Save these via the memory tool (action=save).
2. **Project facts** — architectural decisions, constraints, naming choices, dependency choices that explain the codebase's shape. Examples:
- "This project uses RFC3339Nano for timestamps to preserve precision"
- "The skills package mirrors the memory package's structural template"
Save these via the memory tool (action=save).
3. **Reusable workflows** — procedural knowledge the agent figured out that has a name and would benefit from a body. Examples:
- A debugging routine the agent invented for this codebase
- A multi-step deployment process the agent walked through
- A test strategy specific to a tricky concurrency scenario
Save these via the skill_manage tool (action=create) with kebab-case names.
## Decision tree
- One-line fact, no body needed → memory
- Multi-paragraph technique with a name → skill
- Already in memory or skills (check via action=list first) → don't duplicate
- Trivial / one-off / obvious from the code → skip
## Worked example
Conversation: User and agent debugged a flaky test that turned out to be a 1-second mtime resolution issue.
Reviewer extracts:
- memory: "Filesystem mtime resolution is 1s on this project's macOS dev machines; tests checking mtime advance need time.Sleep(1100ms)"
- skill (name=debugging-mtime-flakes): full body explaining the symptom, the diagnostic process, and the fix pattern
## Closing
If nothing is worth saving, finish without calling any write tools. A clean review is a successful review — quality over quantity.`
+494
View File
@@ -0,0 +1,494 @@
package runtime
import (
"context"
"encoding/json"
"errors"
"testing"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/sausheong/harness/tool/memory"
"github.com/sausheong/harness/tool/skills"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestReviewSpec_Defaults(t *testing.T) {
// ReviewSpec with only required fields should compile.
spec := ReviewSpec{
Prompt: "review the conversation",
Tools: tool.NewRegistry(),
}
assert.NotNil(t, spec.Tools)
assert.Equal(t, "review the conversation", spec.Prompt)
// Optional fields default to zero.
assert.Equal(t, 0, spec.MaxTurns)
assert.Equal(t, time.Duration(0), spec.Timeout)
assert.Nil(t, spec.OnEvent)
}
func TestReviewResult_Zero(t *testing.T) {
res := ReviewResult{}
assert.Empty(t, res.Actions)
assert.Equal(t, 0, res.ToolCalls)
assert.Equal(t, 0, res.Turns)
assert.NoError(t, res.Err)
}
func TestErrReviewRecursion_IsExported(t *testing.T) {
assert.True(t, errors.Is(ErrReviewRecursion, ErrReviewRecursion))
assert.NotEmpty(t, ErrReviewRecursion.Error())
}
func TestReviewPrompts_Exported(t *testing.T) {
assert.NotEmpty(t, ReviewPromptDefault)
assert.NotEmpty(t, ReviewPromptVerbose)
// Verbose should be at least as long as default (more guidance).
assert.GreaterOrEqual(t, len(ReviewPromptVerbose), len(ReviewPromptDefault))
// Both should reference the canonical action verbs.
for _, p := range []string{ReviewPromptDefault, ReviewPromptVerbose} {
assert.Contains(t, p, "memory")
assert.Contains(t, p, "skill")
}
}
func TestReview_RecursionGuard(t *testing.T) {
// A reviewer Runtime has AgentID = "__review__"; Review on it
// must refuse with ErrReviewRecursion.
parent := &Runtime{AgentID: reviewerAgentID}
spec := ReviewSpec{Prompt: "x", Tools: tool.NewRegistry()}
res := Review(context.Background(), parent, spec)
assert.ErrorIs(t, res.Err, ErrReviewRecursion)
}
func TestReview_NilToolsRejected(t *testing.T) {
parent := &Runtime{AgentID: "main"}
res := Review(context.Background(), parent, ReviewSpec{Prompt: "x", Tools: nil})
assert.Error(t, res.Err)
assert.Contains(t, res.Err.Error(), "Tools")
}
func TestReview_EmptyPromptRejected(t *testing.T) {
parent := &Runtime{AgentID: "main"}
res := Review(context.Background(), parent, ReviewSpec{Prompt: "", Tools: tool.NewRegistry()})
assert.Error(t, res.Err)
assert.Contains(t, res.Err.Error(), "Prompt")
}
func TestSnapshotSession_KeyPrefix(t *testing.T) {
parent := session.NewSession("main-agent", "alpha")
parent.Append(session.UserMessageEntry("first prompt"))
parent.Append(session.AssistantMessageEntry("first reply"))
clone := snapshotSession(parent)
assert.Equal(t, "main-agent", clone.AgentID, "AgentID should be preserved")
assert.Equal(t, "review-alpha", clone.Key, "Key should be prefixed with review-")
// Has the same number of entries.
assert.Len(t, clone.View(), len(parent.View()))
}
func TestSnapshotSession_DoesNotMutateParent(t *testing.T) {
parent := session.NewSession("main-agent", "main")
parent.Append(session.UserMessageEntry("hello"))
originalCount := len(parent.View())
clone := snapshotSession(parent)
clone.Append(session.AssistantMessageEntry("review note"))
// Parent's entry count must NOT have changed.
assert.Equal(t, originalCount, len(parent.View()),
"appending to clone must not affect parent")
// Clone's entry count is original + 1.
assert.Equal(t, originalCount+1, len(clone.View()))
}
// fakeMemoryProvider is a minimal MemoryProvider for tests.
type fakeMemoryProvider struct{ index string }
func (f *fakeMemoryProvider) FormatIndex() string { return f.index }
func (f *fakeMemoryProvider) Get(id string) (string, bool) { return "", false }
// fakeSkillProvider is a minimal SkillProvider for tests.
type fakeSkillProvider struct{ index string }
func (f *fakeSkillProvider) FormatIndex() string { return f.index }
func (f *fakeSkillProvider) Get(name string) (string, bool) { return "", false }
// denyAllPermission is a PermissionChecker that denies everything.
type denyAllPermission struct{}
func (denyAllPermission) Check(ctx context.Context, agentID, toolName string, input json.RawMessage) tool.Decision {
return tool.Decision{Behavior: tool.DecisionDeny, Reason: "denied by test checker"}
}
func (denyAllPermission) FilterToolDefs(defs []llm.ToolDef, agentID string) []llm.ToolDef {
return nil
}
// newReviewTestParent constructs a minimal parent Runtime suitable for
// build/run tests.
func newReviewTestParent(t *testing.T) *Runtime {
t.Helper()
return &Runtime{
AgentID: "main-agent",
AgentName: "Main",
Provider: "anthropic",
Model: "claude-haiku-4-5",
Workspace: t.TempDir(),
Session: session.NewSession("main-agent", "main"),
LLM: &llmtest.Stub{Text: "ok"},
}
}
func TestBuildReviewerRuntime_AgentIDIsReviewer(t *testing.T) {
parent := newReviewTestParent(t)
rt, err := buildReviewerRuntime(parent, ReviewSpec{
Prompt: "x",
Tools: tool.NewRegistry(),
})
require.NoError(t, err)
assert.Equal(t, reviewerAgentID, rt.AgentID)
}
func TestBuildReviewerRuntime_InheritsParentLLMAndModel(t *testing.T) {
parent := newReviewTestParent(t)
rt, err := buildReviewerRuntime(parent, ReviewSpec{
Prompt: "x", Tools: tool.NewRegistry(),
})
require.NoError(t, err)
assert.Same(t, parent.LLM, rt.LLM, "LLM should inherit from parent when spec.Provider is nil")
assert.NotEmpty(t, rt.Model, "Model should be inherited and parsed")
}
func TestBuildReviewerRuntime_InheritsMemoryAndSkills(t *testing.T) {
parent := newReviewTestParent(t)
parent.Memory = &fakeMemoryProvider{index: "from parent memory"}
parent.Skills = &fakeSkillProvider{index: "from parent skills"}
rt, err := buildReviewerRuntime(parent, ReviewSpec{
Prompt: "x", Tools: tool.NewRegistry(),
})
require.NoError(t, err)
assert.NotNil(t, rt.Memory, "Memory should inherit from parent")
assert.NotNil(t, rt.Skills, "Skills should inherit from parent")
}
func TestBuildReviewerRuntime_HooksAreZeroed(t *testing.T) {
parent := newReviewTestParent(t)
parent.AgentLoop.Hooks.OnStop = func(ctx context.Context, reason string) {
t.Errorf("parent OnStop should NOT propagate to reviewer")
}
rt, err := buildReviewerRuntime(parent, ReviewSpec{
Prompt: "x", Tools: tool.NewRegistry(),
})
require.NoError(t, err)
assert.Nil(t, rt.AgentLoop.Hooks.OnStop)
assert.Nil(t, rt.AgentLoop.Hooks.OnUserPromptSubmit)
assert.Nil(t, rt.AgentLoop.Hooks.BeforeToolUse)
assert.Nil(t, rt.AgentLoop.Hooks.AfterToolUse)
assert.Nil(t, rt.AgentLoop.Hooks.OnSessionStart)
}
func TestBuildReviewerRuntime_PermissionDefaultsToNil(t *testing.T) {
parent := newReviewTestParent(t)
parent.Permission = denyAllPermission{}
rt, err := buildReviewerRuntime(parent, ReviewSpec{
Prompt: "x", Tools: tool.NewRegistry(),
})
require.NoError(t, err)
assert.Nil(t, rt.Permission, "reviewer Permission should default to nil (allow-all)")
}
func TestBuildReviewerRuntime_IngestSourceIsReview(t *testing.T) {
parent := newReviewTestParent(t)
rt, err := buildReviewerRuntime(parent, ReviewSpec{
Prompt: "x", Tools: tool.NewRegistry(),
})
require.NoError(t, err)
assert.Equal(t, "review", rt.IngestSource, `reviewer IngestSource must be "review" so KG ingest skips it`)
}
// statefulReviewMock embeds llmtest.Base so we satisfy the LLMProvider
// interface even as it grows; only ChatStream is custom.
type statefulReviewMock struct {
llmtest.Base
responses [][]llm.ChatEvent
callCount int
}
func (m *statefulReviewMock) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
idx := m.callCount
m.callCount++
if idx >= len(m.responses) {
idx = len(m.responses) - 1
}
events := m.responses[idx]
ch := make(chan llm.ChatEvent, len(events))
for _, e := range events {
ch <- e
}
close(ch)
return ch, nil
}
// reviewNoopTool emits a canonical action-result envelope so action
// extraction (Task 7) has something to find.
type reviewNoopTool struct{ name string }
func (n *reviewNoopTool) Name() string { return n.name }
func (n *reviewNoopTool) Description() string { return "noop for review tests" }
func (n *reviewNoopTool) Parameters() json.RawMessage { return json.RawMessage(`{"type":"object"}`) }
func (n *reviewNoopTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
func (n *reviewNoopTool) Execute(_ context.Context, _ json.RawMessage) (tool.ToolResult, error) {
return tool.ToolResult{Output: `{"success":true,"message":"ok","target":"test"}`}, nil
}
func TestReview_DrainsEventsSilently(t *testing.T) {
parent := newReviewTestParent(t)
parent.LLM = &statefulReviewMock{
responses: [][]llm.ChatEvent{
// Single response: text then done.
{
{Type: llm.EventTextDelta, Text: "review complete"},
{Type: llm.EventDone},
},
},
}
res := Review(context.Background(), parent, ReviewSpec{
Prompt: "review please",
Tools: tool.NewRegistry(),
})
// Setup must succeed (no Err for guards).
assert.NoError(t, res.Err, "Review should not error on happy path")
assert.GreaterOrEqual(t, res.Turns, 1, "Turns counter should be populated")
assert.Greater(t, res.Duration, time.Duration(0), "Duration must be populated")
}
func TestReview_OnEventReceivesEvents(t *testing.T) {
parent := newReviewTestParent(t)
parent.LLM = &statefulReviewMock{
responses: [][]llm.ChatEvent{
{
{Type: llm.EventTextDelta, Text: "hi"},
{Type: llm.EventDone},
},
},
}
var captured []AgentEvent
res := Review(context.Background(), parent, ReviewSpec{
Prompt: "x",
Tools: tool.NewRegistry(),
OnEvent: func(ev AgentEvent) {
captured = append(captured, ev)
},
})
assert.NoError(t, res.Err)
require.NotEmpty(t, captured, "OnEvent should have received at least one event")
var sawDone bool
for _, ev := range captured {
if ev.Type == EventDone {
sawDone = true
break
}
}
assert.True(t, sawDone, "OnEvent should have received EventDone")
}
func TestReview_CountsToolCalls(t *testing.T) {
parent := newReviewTestParent(t)
parent.LLM = &statefulReviewMock{
responses: [][]llm.ChatEvent{
// First call: emit a tool call to "noop".
{
{Type: llm.EventToolCallStart, ToolCall: &llm.ToolCall{ID: "tc_1", Name: "noop"}},
{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "tc_1", Name: "noop", Input: json.RawMessage(`{}`)}},
{Type: llm.EventDone},
},
// Second call: finish with text.
{
{Type: llm.EventTextDelta, Text: "done"},
{Type: llm.EventDone},
},
},
}
reg := tool.NewRegistry()
reg.Register(&reviewNoopTool{name: "noop"})
res := Review(context.Background(), parent, ReviewSpec{
Prompt: "x",
Tools: reg,
})
assert.NoError(t, res.Err)
assert.GreaterOrEqual(t, res.ToolCalls, 1, "ToolCalls should reflect the tool dispatch")
}
func TestExtractActions_ParsesSuccessEnvelope(t *testing.T) {
// Build a session with a snapshot of 2 entries (the inherited
// prefix), then 2 tool-result entries (the reviewer's actions).
sess := session.NewSession("main", "review-main")
sess.Append(session.UserMessageEntry("user prompt"))
sess.Append(session.AssistantMessageEntry("assistant reply"))
inheritedCount := len(sess.View())
sess.Append(session.ToolResultEntry("call-1", `{"success":true,"message":"saved memory: user prefers terse","target":"memory","id":"mem_x"}`, "", nil))
sess.Append(session.ToolResultEntry("call-2", `{"success":true,"message":"created skill: my-flow","target":"skill","name":"my-flow"}`, "", nil))
actions := extractActions(sess, inheritedCount)
require.Len(t, actions, 2)
assert.Equal(t, "saved memory: user prefers terse", actions[0])
assert.Equal(t, "created skill: my-flow", actions[1])
}
func TestExtractActions_SkipsFailures(t *testing.T) {
sess := session.NewSession("main", "review-main")
inheritedCount := 0
sess.Append(session.ToolResultEntry("call-1", `{"success":true,"message":"ok","target":"memory","id":"x"}`, "", nil))
sess.Append(session.ToolResultEntry("call-2", `{"success":false,"error":"some error","target":"memory"}`, "", nil))
sess.Append(session.ToolResultEntry("call-3", `{"success":true,"message":"another ok","target":"skill","name":"y"}`, "", nil))
actions := extractActions(sess, inheritedCount)
require.Len(t, actions, 2, "only successful results should appear")
assert.Equal(t, "ok", actions[0])
assert.Equal(t, "another ok", actions[1])
}
func TestExtractActions_SkipsNonEnvelopeOutputs(t *testing.T) {
// Tools that don't follow the convention (e.g. return raw JSON
// arrays for list, or plain text) should be silently skipped.
sess := session.NewSession("main", "review-main")
inheritedCount := 0
sess.Append(session.ToolResultEntry("call-1", `[]`, "", nil)) // list output (raw array)
sess.Append(session.ToolResultEntry("call-2", `{"success":true,"message":"ok","target":"x"}`, "", nil))
sess.Append(session.ToolResultEntry("call-3", `not json at all`, "", nil))
actions := extractActions(sess, inheritedCount)
require.Len(t, actions, 1)
assert.Equal(t, "ok", actions[0])
}
func TestExtractActions_OnlyAfterInheritedPrefix(t *testing.T) {
// Tool-result entries from BEFORE inheritedCount must NOT be
// extracted — those came from the parent's session, not the
// reviewer's actions.
sess := session.NewSession("main", "review-main")
sess.Append(session.ToolResultEntry("inherit-1", `{"success":true,"message":"OLD action","target":"memory"}`, "", nil))
sess.Append(session.UserMessageEntry("review prompt"))
inheritedCount := len(sess.View())
sess.Append(session.ToolResultEntry("review-1", `{"success":true,"message":"NEW action","target":"memory"}`, "", nil))
actions := extractActions(sess, inheritedCount)
require.Len(t, actions, 1, "only NEW actions appended after inheritedCount should appear")
assert.Equal(t, "NEW action", actions[0])
}
func TestReview_SetsOriginToReviewOnContext(t *testing.T) {
// Verify by registering a fake tool that captures the context's
// OriginKey values and then asserting on them.
parent := newReviewTestParent(t)
parent.LLM = &statefulReviewMock{
responses: [][]llm.ChatEvent{
// First call: tool call to capture_origin.
{
{Type: llm.EventToolCallStart, ToolCall: &llm.ToolCall{ID: "tc_1", Name: "capture_origin"}},
{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "tc_1", Name: "capture_origin", Input: json.RawMessage(`{}`)}},
{Type: llm.EventDone},
},
// Second call: finish with text.
{
{Type: llm.EventTextDelta, Text: "done"},
{Type: llm.EventDone},
},
},
}
captured := make(chan struct {
mem string
ski string
}, 1)
reg := tool.NewRegistry()
reg.Register(&originCapturingTool{captured: captured})
res := Review(context.Background(), parent, ReviewSpec{
Prompt: "x",
Tools: reg,
})
assert.NoError(t, res.Err)
select {
case got := <-captured:
assert.Equal(t, "review", got.mem, `memory.OriginKey should be "review"`)
assert.Equal(t, "review", got.ski, `skills.OriginKey should be "review"`)
case <-time.After(2 * time.Second):
t.Fatalf("originCapturingTool was never called")
}
}
// originCapturingTool reads both memory.OriginKey and skills.OriginKey
// from the context and sends them to a channel.
type originCapturingTool struct {
captured chan struct {
mem string
ski string
}
}
func (o *originCapturingTool) Name() string { return "capture_origin" }
func (o *originCapturingTool) Description() string { return "test" }
func (o *originCapturingTool) Parameters() json.RawMessage { return json.RawMessage(`{"type":"object"}`) }
func (o *originCapturingTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
func (o *originCapturingTool) Execute(ctx context.Context, _ json.RawMessage) (tool.ToolResult, error) {
mem, _ := ctx.Value(memory.OriginKey).(string)
ski, _ := ctx.Value(skills.OriginKey).(string)
o.captured <- struct {
mem string
ski string
}{mem, ski}
return tool.ToolResult{Output: `{"success":true,"message":"captured","target":"test"}`}, nil
}
func TestBuildReviewerRuntime_SpecOverridesParent(t *testing.T) {
// Verify that spec values WIN over parent values when set.
// Inheritance fallback is covered by the InheritsParent* tests above;
// this test covers the symmetric "override" path so future refactors
// can't silently swap precedence.
parent := newReviewTestParent(t)
parent.Memory = &fakeMemoryProvider{index: "parent-mem"}
parent.Skills = &fakeSkillProvider{index: "parent-skills"}
parent.ContextWindow = 100000
overrideMem := &fakeMemoryProvider{index: "override-mem"}
overrideSkills := &fakeSkillProvider{index: "override-skills"}
overrideLLM := &llmtest.Stub{Text: "override"}
rt, err := buildReviewerRuntime(parent, ReviewSpec{
Prompt: "x",
Tools: tool.NewRegistry(),
Provider: overrideLLM,
Model: "anthropic/claude-opus-4-7",
ContextWindow: 200000,
Memory: overrideMem,
Skills: overrideSkills,
MaxTurns: 32,
SystemPrompt: "I AM THE OVERRIDE PROMPT",
})
require.NoError(t, err)
assert.Same(t, overrideLLM, rt.LLM, "spec.Provider should override parent.LLM")
assert.Equal(t, "claude-opus-4-7", rt.Model, "spec.Model should override parent's recomposed model")
assert.Equal(t, 200000, rt.ContextWindow, "spec.ContextWindow should override parent.ContextWindow")
assert.NotSame(t, parent.Memory, rt.Memory, "spec.Memory should override parent.Memory")
assert.NotSame(t, parent.Skills, rt.Skills, "spec.Skills should override parent.Skills")
assert.Equal(t, 32, rt.MaxTurns, "spec.MaxTurns should override default 16")
assert.Equal(t, "I AM THE OVERRIDE PROMPT", rt.SystemPrompt, "spec.SystemPrompt should be set on the reviewer")
}
+125
View File
@@ -0,0 +1,125 @@
package runtime
import (
"context"
"encoding/json"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// twoTurnUsageLLM: turn 1 emits a noop tool call + EventDone{Usage:u1};
// turn 2 (after the tool result) emits text + EventDone{Usage:u2} and stops.
type twoTurnUsageLLM struct {
llmtest.Base
u1, u2 *llm.Usage
calls int
}
func (f *twoTurnUsageLLM) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
ch := make(chan llm.ChatEvent, 8)
first := f.calls == 0
f.calls++
go func() {
defer close(ch)
if first {
tc := llm.ToolCall{ID: "tc_0", Name: "noop", Input: json.RawMessage(`{}`)}
ch <- llm.ChatEvent{Type: llm.EventToolCallStart, ToolCall: &tc}
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &tc}
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: f.u1}
return
}
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "done"}
ch <- llm.ChatEvent{Type: llm.EventDone, Usage: f.u2}
}()
return ch, nil
}
// usageNoopExecutor returns "ok" for a "noop" tool. (Distinct from the
// error-returning noopExecutor in agent_test.go, which has no tool defs.)
type usageNoopExecutor struct{}
func (usageNoopExecutor) Execute(_ context.Context, _ string, _ json.RawMessage) (tool.ToolResult, error) {
return tool.ToolResult{Output: "ok"}, nil
}
func (usageNoopExecutor) ToolDefs() []llm.ToolDef { return []llm.ToolDef{{Name: "noop"}} }
func (usageNoopExecutor) Names() []string { return []string{"noop"} }
func (usageNoopExecutor) Get(string) (tool.Tool, bool) { return nil, false }
func drainUsage(t *testing.T, events <-chan AgentEvent) *llm.Usage {
t.Helper()
var done *llm.Usage
var sawDone bool
for ev := range events {
if ev.Type == EventDone {
done = ev.Usage
sawDone = true
}
}
require.True(t, sawDone, "expected a terminal EventDone")
return done
}
func TestRun_UsageAccumulatesAcrossTurns(t *testing.T) {
r := &Runtime{
LLM: &twoTurnUsageLLM{
u1: &llm.Usage{InputTokens: 100, OutputTokens: 40, CacheCreationInputTokens: 10, CacheReadInputTokens: 6},
u2: &llm.Usage{InputTokens: 10, OutputTokens: 5, CacheCreationInputTokens: 1, CacheReadInputTokens: 2},
},
Tools: usageNoopExecutor{},
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test-model",
MaxTurns: 5,
}
events, err := r.Run(context.Background(), "go", nil)
require.NoError(t, err)
got := drainUsage(t, events)
require.NotNil(t, got)
assert.Equal(t, 110, got.InputTokens)
assert.Equal(t, 45, got.OutputTokens)
assert.Equal(t, 11, got.CacheCreationInputTokens)
assert.Equal(t, 8, got.CacheReadInputTokens)
}
func TestRun_UsageSingleTurn(t *testing.T) {
r := &Runtime{
LLM: &twoTurnUsageLLM{
u2: &llm.Usage{InputTokens: 7, OutputTokens: 3},
},
Tools: usageNoopExecutor{},
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test-model",
MaxTurns: 5,
}
// calls=0 path emits a tool call; to get a pure single turn, mark calls so
// the first ChatStream takes the text+stop branch.
r.LLM.(*twoTurnUsageLLM).calls = 1
events, err := r.Run(context.Background(), "go", nil)
require.NoError(t, err)
got := drainUsage(t, events)
require.NotNil(t, got)
assert.Equal(t, 7, got.InputTokens)
assert.Equal(t, 3, got.OutputTokens)
}
func TestRun_UsageNilWhenProviderSilent(t *testing.T) {
r := &Runtime{
LLM: &twoTurnUsageLLM{calls: 1}, // single turn, u2 nil → EventDone with nil usage
Tools: usageNoopExecutor{},
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test-model",
MaxTurns: 5,
}
events, err := r.Run(context.Background(), "go", nil)
require.NoError(t, err)
got := drainUsage(t, events)
assert.Nil(t, got, "usage must stay nil when the provider never reports it")
}
+189 -29
View File
@@ -45,7 +45,7 @@ type AgentEvent struct {
Result *tool.ToolResult
Error error
Compaction *compaction.Result // populated for EventCompaction* events
Usage *llm.Usage // populated for EventDone when the provider reported it
Usage *llm.Usage // on the terminal EventDone, the token total accumulated across all turns of the run (nil if the provider never reported usage); per-turn figures are available via RunTurn's TurnResult.Usage
}
// Runtime is the agent think-act loop.
@@ -105,6 +105,14 @@ type Runtime struct {
touchedMu sync.Mutex
touchedFiles []string
// spilledIDs records ToolCallIDs whose oversized results have already
// been written to the deterministic spill path during this Runtime's
// lifetime. Content is immutable per ToolCallID, so once spilled we
// skip the (multi-MB) disk re-write on subsequent turns and only
// rebuild the in-memory marker.
spilledMu sync.Mutex
spilledIDs map[string]bool
// IngestSource controls whether this run's thread is ingested into the KG.
// "chat" (or empty) ingests; any other value skips ingest.
IngestSource string
@@ -114,6 +122,12 @@ type Runtime struct {
calibrator *tokens.Calibrator
// calibratorDirty records that the calibrator was updated during this
// Run and must be flushed to CalibratorStore once at Run end. Accessed
// only on the Run goroutine (EventDone handling + deferred flush), so no
// lock is needed.
calibratorDirty bool
// mcpClients holds the MCP client sessions resolved from
// AgentSpec.MCPServers. Released by Close. Untouched when MCP is
// not used.
@@ -181,14 +195,26 @@ func (r *Runtime) maybeKickoffAsyncCompaction(msgs []llm.Message, parts []llm.Sy
}
// providerSupportsCaching returns true when the runtime's provider implements
// Anthropic-style explicit prompt caching.
// Anthropic-style explicit prompt caching. The capability interface wins:
// a provider block named "platformai" (or "bedrock", or anything else)
// wrapping the Anthropic implementation still caches. The name check is
// the legacy fallback for custom LLMProvider impls that predate the
// capability interface.
func (r *Runtime) providerSupportsCaching() bool {
if pc, ok := r.LLM.(llm.PromptCachingProvider); ok {
return pc.SupportsPromptCaching()
}
return r.Provider == "anthropic"
}
// providerSupportsMidLoopCompaction returns true for hosted frontier
// providers that handle mid-loop summary injection cleanly.
// providers that handle mid-loop summary injection cleanly. Same
// capability-over-name rule as providerSupportsCaching: an
// Anthropic-shaped provider under a custom name qualifies.
func (r *Runtime) providerSupportsMidLoopCompaction() bool {
if pc, ok := r.LLM.(llm.PromptCachingProvider); ok && pc.SupportsPromptCaching() {
return true
}
switch r.Provider {
case "anthropic", "openai", "gemini":
return true
@@ -223,6 +249,18 @@ func (r *Runtime) snapshotTouchedFiles() []string {
return out
}
// prune shortens oversized tool results in msgs, spilling to disk where
// configured. It carries the Runtime's per-Run spilled-ID set so a result
// already spilled this Run is not re-written to disk on subsequent turns.
func (r *Runtime) prune(msgs []llm.Message, spillCfg spillConfig) {
r.spilledMu.Lock()
if r.spilledIDs == nil {
r.spilledIDs = map[string]bool{}
}
pruneToolResults(msgs, r.maxToolResultLen(), spillCfg, r.spilledIDs)
r.spilledMu.Unlock()
}
// isFileTool reports whether a tool name's input contains a "path" field.
func isFileTool(name string) bool {
switch name {
@@ -242,6 +280,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
defer close(r.events)
defer tr.Summary()
// Flush the per-session calibrator once at Run end (all exit paths:
// normal, error, abort) instead of writing to disk on every LLM
// round. EventDone sets calibratorDirty when it folds in a usage
// sample; this defer persists the final state. Registered here so it
// runs regardless of which return below fires.
defer func() {
if r.calibratorDirty && r.CalibratorStore != nil && r.Session != nil && r.calibrator != nil {
ratio, count := r.calibrator.Snapshot()
r.CalibratorStore.Save(r.AgentID, r.Session.Key, ratio, count)
}
}()
// stopReason is read by the OnStop deferred hook below. Each early
// return path reassigns it before returning. Default is "max_turns"
// so the natural fall-through (loop exhausted MaxTurns) records the
@@ -326,6 +376,26 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
// Computed once per Run so the date stays stable across turns.
dateLine := FormatDateLine(time.Now())
// Tool defs are invariant for the whole Run (tools and permission don't
// change mid-Run), so normalize once instead of per turn (P3).
toolDefs := r.Tools.ToolDefs()
if r.Permission != nil {
toolDefs = r.Permission.FilterToolDefs(toolDefs, r.AgentID)
}
sort.SliceStable(toolDefs, func(i, j int) bool {
return toolDefs[i].Name < toolDefs[j].Name
})
toolDefs, diags := r.LLM.NormalizeToolSchema(toolDefs)
for _, d := range diags {
slog.Info("tool schema normalized",
"tool", d.ToolName,
"field", d.Field,
"action", d.Action,
"reason", d.Reason)
}
var runUsage *llm.Usage // accumulated across all turns; nil until first reported
for turn := 0; turn < maxTurns; turn++ {
if ctx.Err() != nil {
stopReason = "aborted"
@@ -364,23 +434,8 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
msgs := assembleMessages(history)
spillCfg := spillConfig{Workspace: r.Workspace, SessionKey: r.Session.Key}
pruneToolResults(msgs, maxToolResultLen, spillCfg)
r.prune(msgs, spillCfg)
toolDefs := r.Tools.ToolDefs()
if r.Permission != nil {
toolDefs = r.Permission.FilterToolDefs(toolDefs, r.AgentID)
}
sort.SliceStable(toolDefs, func(i, j int) bool {
return toolDefs[i].Name < toolDefs[j].Name
})
toolDefs, diags := r.LLM.NormalizeToolSchema(toolDefs)
for _, d := range diags {
slog.Info("tool schema normalized",
"tool", d.ToolName,
"field", d.Field,
"action", d.Action,
"reason", d.Reason)
}
tr.Mark("context.assemble", "turn", turn, "msgs", len(msgs), "tools", len(toolDefs), "sysprompt_chars", len(staticText)+len(dynamicSuffix), "dur_ms_local", time.Since(phaseStart).Milliseconds())
// Wait briefly on any in-flight async compaction kicked off by
@@ -390,7 +445,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
history = r.Session.View()
msgs = assembleMessages(history)
pruneToolResults(msgs, maxToolResultLen, spillCfg)
r.prune(msgs, spillCfg)
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
}
}
@@ -416,7 +471,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
history = r.Session.View()
msgs = assembleMessages(history)
pruneToolResults(msgs, maxToolResultLen, spillCfg)
r.prune(msgs, spillCfg)
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
} else {
r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res})
@@ -449,7 +504,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
history = r.Session.View()
msgs = assembleMessages(history)
pruneToolResults(msgs, maxToolResultLen, spillCfg)
r.prune(msgs, spillCfg)
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
req.Messages = msgs
stream, err = r.LLM.ChatStream(ctx, req)
@@ -475,7 +530,6 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
var textContent strings.Builder
var lastUsage *llm.Usage
var toolCalls []llm.ToolCall
gotFirstToken := false
@@ -485,6 +539,10 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
streamSource := stream
retriedNonStreaming := false
preTokenRetried := false
retriedRefusal := false
var refused bool
var refusalCategory string
streamLoop:
for {
for event := range streamSource {
@@ -527,18 +585,35 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}()
case llm.EventDone:
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
if event.Usage != nil {
lastUsage = event.Usage
runUsage = addUsage(runUsage, event.Usage)
}
if event.Usage != nil && r.calibrator != nil {
// Recompute the estimate on the CURRENT msgs (which may
// have been reassembled by mid-turn compaction) so the
// calibration ratio matches event.Usage.InputTokens, as
// the pre-debounce code did. The P8 change only debounces
// the disk write (calibratorDirty + deferred flush), not
// the estimate computation.
r.calibrator.Update(event.Usage.InputTokens, tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs))
if r.CalibratorStore != nil && r.Session != nil {
ratio, count := r.calibrator.Snapshot()
r.CalibratorStore.Save(r.AgentID, r.Session.Key, ratio, count)
}
r.calibratorDirty = true
}
case llm.EventError:
if !gotFirstToken && !preTokenRetried {
if newStream, ok := r.recoverFromPreTokenError(ctx, event.Error, &req, &msgs, spillCfg); ok {
preTokenRetried = true
drainKickoffs(kickoffs)
kickoffs = map[string]chan kickoffResult{}
textContent.Reset()
toolCalls = nil
kickoffStopped = false
streamSource = newStream
continue streamLoop
}
}
if gotFirstToken && !retriedNonStreaming {
if ns, ok := r.LLM.(llm.NonStreamingProvider); ok {
slog.Warn("stream died mid-flight; retrying as non-streaming",
@@ -567,6 +642,53 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
return
}
}
// Classifier/model refusal (Claude Fable 5+): HTTP 200,
// stop_reason=refusal, usually no content. Without handling,
// the turn ends as a silent empty success. Retry once on the
// fallback model (refusals are model-specific — Opus-tier
// has no bio/cyber classifiers); otherwise synthesize a
// visible explanation. Mid-stream refusals discard partial
// output per the API contract.
if refused {
if !retriedRefusal && r.FallbackModel != "" && r.FallbackModel != req.Model {
slog.Warn("model refused; retrying on fallback model",
"agent", r.AgentID,
"primary", req.Model,
"fallback", r.FallbackModel,
"category", refusalCategory)
tr.Mark("llm.refusal_fallback", "turn", turn,
"primary", req.Model, "fallback", r.FallbackModel,
"category", refusalCategory)
textContent.Reset()
toolCalls = nil
drainKickoffs(kickoffs)
kickoffs = map[string]chan kickoffResult{}
gotFirstToken = false
kickoffStopped = false
refused = false
retriedRefusal = true
req.Model = r.FallbackModel
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
if retryErr != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: retryErr})
return
}
streamSource = retryStream
continue streamLoop
}
textContent.Reset()
toolCalls = nil
drainKickoffs(kickoffs)
note := "The model declined this request (safety classifier"
if refusalCategory != "" {
note += ", category: " + refusalCategory
}
note += "). Try rephrasing, or switch this agent to a model without these classifiers."
textContent.WriteString(note)
r.emit(AgentEvent{Type: EventTextDelta, Text: note})
}
break streamLoop
}
tr.Mark("llm.stream_end", "turn", turn,
@@ -592,7 +714,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
tr.Mark("agent.done", "turn", turn, "reason", "no_tool_calls")
stopReason = "completed"
r.emit(AgentEvent{Type: EventDone, Usage: lastUsage})
r.emit(AgentEvent{Type: EventDone, Usage: runUsage})
r.maybeKickoffAsyncCompaction(msgs, parts, toolDefs)
return
}
@@ -679,6 +801,42 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
return r.events, nil
}
// recoverFromPreTokenError attempts the same recovery the synchronous
// ChatStream-error path performs, for an error delivered via EventError
// before any token arrived (Anthropic/Gemini deliver HTTP errors this way).
// Returns a fresh stream to resume from and true if recovered; false if the
// error is not recoverable (caller should abort). May mutate *req (model
// swap) and the session (compaction), and reassigns *msgs on compaction.
func (r *Runtime) recoverFromPreTokenError(ctx context.Context, err error, req *llm.ChatRequest, msgs *[]llm.Message, spillCfg spillConfig) (<-chan llm.ChatEvent, bool) {
if compaction.IsContextOverflow(err) && r.Compaction != nil {
r.emit(AgentEvent{Type: EventCompactionStart})
res, _ := r.Compaction.MaybeCompact(ctx, r.Session, compaction.ReasonReactive, "")
if res.Compacted {
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
history := r.Session.View()
newMsgs := assembleMessages(history)
r.prune(newMsgs, spillCfg)
newMsgs = prependPostCompactRestore(newMsgs, r.snapshotTouchedFiles())
*msgs = newMsgs
req.Messages = newMsgs
if s, e := r.LLM.ChatStream(ctx, *req); e == nil {
return s, true
}
} else {
r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res})
}
}
if r.FallbackModel != "" && r.FallbackModel != req.Model && llm.IsRetryableModelError(err) {
slog.Info("llm fallback model engaged (stream error)",
"agent", r.AgentID, "primary", req.Model, "fallback", r.FallbackModel, "err", err.Error())
req.Model = r.FallbackModel
if s, e := r.LLM.ChatStream(ctx, *req); e == nil {
return s, true
}
}
return nil, false
}
// RunSync is a convenience method that runs the agent and collects the
// full text response.
func (r *Runtime) RunSync(ctx context.Context, userMsg string, images []llm.ImageContent) (string, error) {
@@ -692,6 +850,8 @@ func (r *Runtime) RunSync(ctx context.Context, userMsg string, images []llm.Imag
switch event.Type {
case EventTextDelta:
response.WriteString(event.Text)
case EventAborted:
return response.String(), context.Canceled
case EventError:
return response.String(), event.Error
}
+265
View File
@@ -0,0 +1,265 @@
package runtime
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"sort"
"strings"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
)
// TurnResult describes the outcome of a single RunTurn call.
type TurnResult struct {
Done bool // true when no tool calls were produced (loop should stop)
StopReason string // "continue" | "completed" | "error" | "aborted"
Entries []session.SessionEntry // entries appended during THIS turn, in order
Err error
Usage *llm.Usage
}
// TurnEmit is an optional live-streaming callback. Pass nil for headless
// execution (e.g. durable replay, where live emission must be suppressed).
type TurnEmit func(AgentEvent)
// RunTurn executes exactly one turn of the agent loop against the current
// session and returns the entries it produced. The first call of a session
// passes the user message; continuation calls pass "".
//
// RunTurn is the durable unit for a per-turn driver: each call can be wrapped
// as a checkpointed step whose return value (TurnResult.Entries) rebuilds
// session state on replay. It differs from Run by design: it is headless
// (live events go only through the emit callback, never an internal channel),
// it dispatches tool calls serially (Run parallelizes concurrency-safe
// batches), and it does NOT perform compaction, streaming-tool kickoff, or the
// trace/slog emissions that Run's emitToolResult produces (those remain Run's
// responsibility). It DOES perform bounded-synchronous knowledge-graph recall on
// the first round of an exchange (folding the hint into the system prompt) and
// async knowledge-graph ingest on the completing round.
func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.ImageContent, emit TurnEmit) (TurnResult, error) {
if emit == nil {
emit = func(AgentEvent) {}
}
startLen := len(r.Session.Entries())
if userMsg != "" || len(images) > 0 {
if len(images) > 0 {
var imgData []session.ImageData
for _, img := range images {
imgData = append(imgData, session.ImageData{
MimeType: img.MimeType,
Data: base64.StdEncoding.EncodeToString(img.Data),
})
}
r.Session.Append(session.UserMessageWithImagesEntry(userMsg, imgData))
} else {
r.Session.Append(session.UserMessageEntry(userMsg))
}
}
if ctx.Err() != nil {
return r.turnSlice(startLen, true, "aborted", nil, ctx.Err()), nil
}
history := r.Session.View()
msgs := assembleMessages(history)
toolDefs := r.Tools.ToolDefs()
if r.Permission != nil {
toolDefs = r.Permission.FilterToolDefs(toolDefs, r.AgentID)
}
sort.SliceStable(toolDefs, func(i, j int) bool { return toolDefs[i].Name < toolDefs[j].Name })
toolDefs, _ = r.LLM.NormalizeToolSchema(toolDefs)
// KG recall (first round of the exchange only): bounded-synchronous so a
// slow embedder cannot stall the turn. The hint is a non-cached suffix —
// it varies per query, so caching it would poison the static prefix cache.
var kgHint string
if r.KG != nil && (userMsg != "" || len(images) > 0) && r.KG.ShouldRecall(userMsg) {
rctx, cancel := context.WithTimeout(ctx, 800*time.Millisecond)
kgHint = r.KG.Recall(rctx, userMsg)
cancel()
}
parts := []llm.SystemPromptPart{{Text: r.StaticSystemPrompt, Cache: true}}
if kgHint != "" {
parts = append(parts, llm.SystemPromptPart{Text: kgHint, Cache: false})
}
req := llm.ChatRequest{
Model: r.Model,
Messages: msgs,
Tools: toolDefs,
MaxTokens: 8192,
SystemPromptParts: parts,
CacheLastMessage: r.providerSupportsCaching(),
Reasoning: r.Reasoning,
}
stream, err := r.LLM.ChatStream(ctx, req)
if err != nil {
if r.FallbackModel != "" && r.FallbackModel != req.Model && llm.IsRetryableModelError(err) {
req.Model = r.FallbackModel
stream, err = r.LLM.ChatStream(ctx, req)
}
if err != nil {
emit(AgentEvent{Type: EventError, Error: fmt.Errorf("llm error: %w", err)})
return r.turnSlice(startLen, true, "error", nil, err), nil
}
}
var textContent strings.Builder
var toolCalls []llm.ToolCall
var lastUsage *llm.Usage
retriedRefusal := false
streamLoop:
for {
var refused bool
var refusalCategory string
for event := range stream {
switch event.Type {
case llm.EventTextDelta:
textContent.WriteString(event.Text)
emit(AgentEvent{Type: EventTextDelta, Text: event.Text})
case llm.EventToolCallStart:
emit(AgentEvent{Type: EventToolCallStart, ToolCall: event.ToolCall})
case llm.EventToolCallDone:
if event.ToolCall != nil {
toolCalls = append(toolCalls, *event.ToolCall)
}
case llm.EventDone:
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
if event.Usage != nil {
lastUsage = event.Usage
}
case llm.EventError:
emit(AgentEvent{Type: EventError, Error: event.Error})
return r.turnSlice(startLen, true, "error", lastUsage, event.Error), nil
}
}
// Same refusal contract as Run: retry once on the fallback model,
// else surface a visible explanation instead of empty silence.
if refused {
if !retriedRefusal && r.FallbackModel != "" && r.FallbackModel != req.Model {
retriedRefusal = true
textContent.Reset()
toolCalls = nil
req.Model = r.FallbackModel
retryStream, retryErr := r.LLM.ChatStream(ctx, req)
if retryErr != nil {
emit(AgentEvent{Type: EventError, Error: retryErr})
return r.turnSlice(startLen, true, "error", lastUsage, retryErr), nil
}
stream = retryStream
continue streamLoop
}
textContent.Reset()
toolCalls = nil
note := "The model declined this request (safety classifier"
if refusalCategory != "" {
note += ", category: " + refusalCategory
}
note += "). Try rephrasing, or switch this agent to a model without these classifiers."
textContent.WriteString(note)
emit(AgentEvent{Type: EventTextDelta, Text: note})
}
break streamLoop
}
if textContent.Len() > 0 {
r.Session.Append(session.AssistantMessageEntry(textContent.String()))
}
if len(toolCalls) == 0 {
// Exchange complete: ingest the full thread once. Background + best-effort
// (the KG spawns its own bounded goroutine), so it never delays the turn.
// context.Background() because the request ctx may be cancelling and the
// ingest goroutine deliberately outlives the turn. Unlike Run, RunTurn does
// not pre-filter trivial threads or gate on IngestSource: the KG impl owns
// its own growth gate (so single-message threads are skipped there), and the
// only RunTurn caller today is the chat serve loop. TODO: if a reviewer or
// subagent path is ever migrated to RunTurn, add an IngestSource-style gate
// here so non-chat transcripts are not ingested.
if r.KG != nil {
r.KG.Ingest(context.Background(), sessionThread(r.Session.View()))
}
emit(AgentEvent{Type: EventDone, Usage: lastUsage})
return r.turnSlice(startLen, true, "completed", lastUsage, nil), nil
}
// RunTurn dispatches tool calls serially by design: deterministic
// ordering keeps durable replay simple, and parallel/concurrency-safe
// batching deliberately stays in Run (see the doc comment). dispatchTool
// appends the tool_call and tool_result entries to the session.
for _, tc := range toolCalls {
result, aborted := r.dispatchTool(ctx, tc, nil)
emit(AgentEvent{Type: EventToolResult, ToolCall: &tc, Result: &result})
if aborted {
return r.turnSlice(startLen, true, "aborted", lastUsage, ctx.Err()), nil
}
}
return r.turnSlice(startLen, false, "continue", lastUsage, nil), nil
}
// turnSlice builds a TurnResult from the entries appended since startLen.
// It assumes a single active turn per session: the delta entries[startLen:]
// is correct only because no other goroutine appends to this session
// concurrently during the turn.
func (r *Runtime) turnSlice(startLen int, done bool, reason string, usage *llm.Usage, err error) TurnResult {
all := r.Session.Entries()
var delta []session.SessionEntry
if startLen <= len(all) {
delta = append(delta, all[startLen:]...)
}
return TurnResult{Done: done, StopReason: reason, Entries: delta, Usage: usage, Err: err}
}
// sessionThread converts session history into the minimal []Message the
// KnowledgeGraph ingests, mirroring how Run accumulates its thread: user and
// assistant messages by role+text, tool calls as "[tool: name]\n<input>"
// (assistant), tool results as their output or "[error] <err>" (user).
// Compaction/meta and non-user/assistant message entries are skipped — the
// thread carries only conversation turns and tool exchanges.
// On the runtime's per-turn serve path each call sees one turn's fresh session,
// so a compaction summary's absence here is intentional, not a gap.
func sessionThread(history []session.SessionEntry) []Message {
var thread []Message
for _, e := range history {
switch e.Type {
case session.EntryTypeMessage:
if e.Role != "user" && e.Role != "assistant" {
continue // skip system/summary messages
}
var d session.MessageData
if json.Unmarshal(e.Data, &d) != nil {
continue
}
thread = append(thread, Message{Role: e.Role, Content: d.Text})
case session.EntryTypeToolCall:
var d session.ToolCallData
if json.Unmarshal(e.Data, &d) != nil {
continue
}
thread = append(thread, Message{
Role: "assistant",
Content: fmt.Sprintf("[tool: %s]\n%s", d.Tool, string(d.Input)),
})
case session.EntryTypeToolResult:
var d session.ToolResultData
if json.Unmarshal(e.Data, &d) != nil {
continue
}
content := d.Output
if d.Error != "" {
content = "[error] " + d.Error
}
thread = append(thread, Message{Role: "user", Content: content})
}
}
return thread
}
+216
View File
@@ -0,0 +1,216 @@
package runtime
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/stretchr/testify/require"
)
func TestSessionThread_RendersEntries(t *testing.T) {
sess := session.NewSession("a", "k")
sess.Append(session.UserMessageEntry("hello"))
sess.Append(session.AssistantMessageEntry("hi there"))
sess.Append(session.ToolCallEntry("tc1", "echo", json.RawMessage(`{"x":1}`)))
sess.Append(session.ToolResultEntry("tc1", "echoed", "", nil))
sess.Append(session.ToolResultEntry("tc2", "", "boom", nil))
thread := sessionThread(sess.View())
require.Equal(t, []Message{
{Role: "user", Content: "hello"},
{Role: "assistant", Content: "hi there"},
{Role: "assistant", Content: "[tool: echo]\n{\"x\":1}"},
{Role: "user", Content: "echoed"},
{Role: "user", Content: "[error] boom"},
}, thread)
}
func TestSessionThread_SkipsCompaction(t *testing.T) {
sess := session.NewSession("a", "k")
// Compaction is appended FIRST so the entries that follow remain on the
// View() walk-back path. View() stops its back-walk at the most recent
// compaction (inclusive), so appending user/assistant AFTER it yields
// View() == [compaction, user, assistant] — the compaction is genuinely
// present in the slice handed to sessionThread, exercising the skip path.
// (Appending compaction last would make it the leaf, and View() would
// return only [compaction], never reaching the messages.)
sess.Append(session.CompactionEntry("summary", "", "", "m", 0, 0, 0))
sess.Append(session.UserMessageEntry("hello"))
sess.Append(session.AssistantMessageEntry("hi"))
view := sess.View()
require.Equal(t, session.EntryTypeCompaction, view[0].Type, "View() must include the compaction entry to exercise the skip")
got := sessionThread(view)
require.Equal(t, []Message{
{Role: "user", Content: "hello"},
{Role: "assistant", Content: "hi"},
}, got)
}
func TestSessionThread_SkipsUndecodableEntry(t *testing.T) {
history := []session.SessionEntry{
{Type: session.EntryTypeToolCall, Data: []byte("not json")},
session.UserMessageEntry("after"),
}
got := sessionThread(history)
require.Equal(t, []Message{{Role: "user", Content: "after"}}, got)
}
func TestSessionThread_Empty(t *testing.T) {
require.Nil(t, sessionThread(nil))
}
// fakeKG is a controllable KnowledgeGraph for RunTurn wiring tests.
type fakeKG struct {
shouldRecall bool
recallReturn string
recallDelay time.Duration
recallCalls int
recallQuery string
ingestCalls int
ingestThreads [][]Message
}
func (f *fakeKG) ShouldRecall(q string) bool { return f.shouldRecall }
func (f *fakeKG) Recall(ctx context.Context, q string) string {
f.recallCalls++
f.recallQuery = q
if f.recallDelay > 0 {
select {
case <-time.After(f.recallDelay):
case <-ctx.Done():
return ""
}
}
return f.recallReturn
}
func (f *fakeKG) Ingest(_ context.Context, thread []Message) {
f.ingestCalls++
f.ingestThreads = append(f.ingestThreads, thread)
}
func TestRunTurn_RecallInjectedIntoPrompt(t *testing.T) {
var captured []llm.SystemPromptPart
cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }}
kg := &fakeKG{shouldRecall: true, recallReturn: "Relevant memories:\n- the user likes tea\n"}
rt := &Runtime{
LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg,
}
_, err := rt.RunTurn(context.Background(), "what do I like?", nil, nil)
require.NoError(t, err)
require.Equal(t, 1, kg.recallCalls)
require.Equal(t, "what do I like?", kg.recallQuery)
require.GreaterOrEqual(t, len(captured), 2, "expected static + recall parts")
require.Equal(t, "STATIC", captured[0].Text)
require.True(t, captured[0].Cache)
require.Equal(t, "Relevant memories:\n- the user likes tea\n", captured[len(captured)-1].Text)
require.False(t, captured[len(captured)-1].Cache, "recall hint must NOT be cached")
}
func TestRunTurn_NoRecallWhenShouldRecallFalse(t *testing.T) {
var captured []llm.SystemPromptPart
cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }}
kg := &fakeKG{shouldRecall: false, recallReturn: "should not appear"}
rt := &Runtime{
LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg,
}
_, err := rt.RunTurn(context.Background(), "hi", nil, nil)
require.NoError(t, err)
require.Equal(t, 0, kg.recallCalls, "ShouldRecall false ⇒ Recall not called")
require.Len(t, captured, 1, "only the static part")
require.Equal(t, "STATIC", captured[0].Text)
}
func TestRunTurn_NoRecallOnContinuationRound(t *testing.T) {
var captured []llm.SystemPromptPart
cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }}
kg := &fakeKG{shouldRecall: true, recallReturn: "hint"}
rt := &Runtime{
LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg,
}
_, err := rt.RunTurn(context.Background(), "", nil, nil)
require.NoError(t, err)
require.Equal(t, 0, kg.recallCalls, "continuation round must not recall")
require.Len(t, captured, 1)
}
func TestRunTurn_RecallTimeoutInjectsNothing(t *testing.T) {
var captured []llm.SystemPromptPart
cap := &capturingLLMStub{onChatStream: func(req llm.ChatRequest) { captured = req.SystemPromptParts }}
kg := &fakeKG{shouldRecall: true, recallReturn: "late", recallDelay: 2 * time.Second}
rt := &Runtime{
LLM: cap, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "STATIC", KG: kg,
}
start := time.Now()
_, err := rt.RunTurn(context.Background(), "slow?", nil, nil)
require.NoError(t, err)
require.Less(t, time.Since(start), 1500*time.Millisecond, "recall must be bounded ~800ms")
require.Len(t, captured, 1, "timed-out recall injects nothing")
}
func TestRunTurn_IngestOnCompletion(t *testing.T) {
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
{typ: llm.EventTextDelta, text: "done"},
{typ: llm.EventDone},
}}
kg := &fakeKG{}
rt := &Runtime{
LLM: llmProvider, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "S", KG: kg,
}
res, err := rt.RunTurn(context.Background(), "remember I like tea", nil, nil)
require.NoError(t, err)
require.True(t, res.Done)
require.Equal(t, 1, kg.ingestCalls, "ingest fires once on the completing round")
require.NotEmpty(t, kg.ingestThreads[0], "ingest gets a non-empty thread")
require.Equal(t, "user", kg.ingestThreads[0][0].Role)
require.Equal(t, "remember I like tea", kg.ingestThreads[0][0].Content)
}
func TestRunTurn_NoIngestOnToolRound(t *testing.T) {
tc := &llm.ToolCall{ID: "tc_1", Name: "echo", Input: json.RawMessage(`{"x":1}`)}
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
{typ: llm.EventToolCallStart, toolCall: tc},
{typ: llm.EventToolCallDone, toolCall: tc},
{typ: llm.EventDone},
}}
kg := &fakeKG{}
rt := &Runtime{
LLM: llmProvider, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "S", KG: kg,
}
res, err := rt.RunTurn(context.Background(), "use echo", nil, nil)
require.NoError(t, err)
require.False(t, res.Done, "tool round is not terminal")
require.Equal(t, 0, kg.ingestCalls, "no ingest on a round that produced tool calls")
}
func TestRunTurn_NoIngestWhenKGNil(t *testing.T) {
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
{typ: llm.EventTextDelta, text: "done"},
{typ: llm.EventDone},
}}
rt := &Runtime{
LLM: llmProvider, Tools: newEchoRegistry(), Session: session.NewSession("a", "k"),
AgentID: "a", Model: "test", StaticSystemPrompt: "S", KG: nil,
}
res, err := rt.RunTurn(context.Background(), "hi", nil, nil)
require.NoError(t, err)
require.True(t, res.Done)
}
+165
View File
@@ -0,0 +1,165 @@
package runtime
import (
"context"
"encoding/json"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/stretchr/testify/require"
)
// echoTool is a minimal tool.Tool implementation for RunTurn tests. It
// satisfies the real tool.Tool interface (Name/Description/Parameters/
// Execute/IsConcurrencySafe) and echoes its raw input back as output.
type echoTool struct{}
func (echoTool) Name() string { return "echo" }
func (echoTool) Description() string { return "echoes its input" }
func (echoTool) Parameters() json.RawMessage { return json.RawMessage(`{"type":"object"}`) }
func (echoTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
return tool.ToolResult{Output: string(input)}, nil
}
func (echoTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
// newEchoRegistry returns a tool.Registry containing only echoTool.
func newEchoRegistry() *tool.Registry {
reg := tool.NewRegistry()
reg.Register(echoTool{})
return reg
}
// TestRunTurn_TextOnly_IsDone: provider emits a text delta then EventDone
// with NO tool calls. The turn must be terminal (Done=true, StopReason
// "completed") and append exactly two entries: the user message and the
// assistant message.
func TestRunTurn_TextOnly_IsDone(t *testing.T) {
// scriptedStreamLLM emits its scripted events only on the FIRST call;
// subsequent calls emit a bare EventDone. For a text-only first turn we
// script text + done directly.
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
{typ: llm.EventTextDelta, text: "hello world"},
{typ: llm.EventDone},
}}
rt := &Runtime{
LLM: llmProvider,
Tools: newEchoRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test",
}
res, err := rt.RunTurn(context.Background(), "hi", nil, nil)
require.NoError(t, err)
require.True(t, res.Done, "text-only turn should be terminal")
require.Equal(t, "completed", res.StopReason)
require.Len(t, res.Entries, 2, "expected user + assistant entries")
require.Equal(t, session.EntryTypeMessage, res.Entries[0].Type)
require.Equal(t, "user", res.Entries[0].Role)
require.Equal(t, session.EntryTypeMessage, res.Entries[1].Type)
require.Equal(t, "assistant", res.Entries[1].Role)
}
// TestRunTurn_ToolCall_NotDone_ThenDone: turn 1 the model calls echo ⇒ the
// turn is NOT done and the entries include a tool_result entry. Turn 2
// (continuation, empty userMsg) the model emits text only ⇒ the turn is done.
func TestRunTurn_ToolCall_NotDone_ThenDone(t *testing.T) {
tc := &llm.ToolCall{ID: "tc_1", Name: "echo", Input: json.RawMessage(`{"x":1}`)}
// scriptedStreamLLM emits the scripted events on call 1 and a bare
// EventDone on every subsequent call — which is exactly the turn-2
// text-only/no-tool-calls behavior we need.
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
{typ: llm.EventToolCallStart, toolCall: tc},
{typ: llm.EventToolCallDone, toolCall: tc},
{typ: llm.EventDone},
}}
rt := &Runtime{
LLM: llmProvider,
Tools: newEchoRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test",
}
// Turn 1: tool call ⇒ not done, has a tool_result entry.
res1, err := rt.RunTurn(context.Background(), "use echo", nil, nil)
require.NoError(t, err)
require.False(t, res1.Done, "a turn that produced tool calls must not be terminal")
require.Equal(t, "continue", res1.StopReason)
var sawToolResult bool
for _, e := range res1.Entries {
if e.Type == session.EntryTypeToolResult {
sawToolResult = true
}
}
require.True(t, sawToolResult, "turn 1 entries should include a tool_result")
// Turn 2: continuation with empty userMsg ⇒ model emits no tool calls
// (bare EventDone) ⇒ terminal.
res2, err := rt.RunTurn(context.Background(), "", nil, nil)
require.NoError(t, err)
require.True(t, res2.Done, "second turn (no tool calls) should be terminal")
require.Equal(t, "completed", res2.StopReason)
}
// TestRunTurn_LLMError: the provider emits a mid-stream EventError. RunTurn
// does NOT use Run's stream-fallback path, so the error surfaces directly:
// the turn is terminal with StopReason "error" and a non-nil Err.
//
// Note on the fake: scriptedStreamLLM's scriptedStreamEvent cannot carry an
// error value (it has no error field), so it cannot emit a meaningful
// EventError. We reuse streamingOnlyProvider from streamfallback_test.go —
// the same-package fake the streaming tests use to simulate a mid-stream
// error (text delta then EventError with a real error).
func TestRunTurn_LLMError(t *testing.T) {
llmProvider := &streamingOnlyProvider{}
rt := &Runtime{
LLM: llmProvider,
Tools: newEchoRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test",
}
res, err := rt.RunTurn(context.Background(), "do it", nil, nil)
require.NoError(t, err, "RunTurn surfaces stream errors via TurnResult.Err, not its own error return")
require.True(t, res.Done, "an errored turn must be terminal")
require.Equal(t, "error", res.StopReason)
require.Error(t, res.Err)
require.EqualValues(t, 1, llmProvider.streamCalls.Load(), "stream hit exactly once (no fallback in RunTurn)")
}
// TestRunTurn_PreCancelledContext: a context cancelled before RunTurn runs
// must short-circuit to an aborted turn with a non-nil Err, and the LLM must
// never be called. scriptedStreamLLM exposes a `calls` counter, so we assert
// the provider was never invoked.
func TestRunTurn_PreCancelledContext(t *testing.T) {
llmProvider := &scriptedStreamLLM{events: []scriptedStreamEvent{
{typ: llm.EventTextDelta, text: "should never run"},
{typ: llm.EventDone},
}}
rt := &Runtime{
LLM: llmProvider,
Tools: newEchoRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "test",
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
res, err := rt.RunTurn(ctx, "hi", nil, nil)
require.NoError(t, err)
require.Equal(t, "aborted", res.StopReason)
require.Error(t, res.Err)
require.EqualValues(t, 0, llmProvider.calls.Load(), "LLM must not be called when context is pre-cancelled")
}
+1 -1
View File
@@ -14,7 +14,7 @@ import (
// 3. Otherwise off.
//
// Strict "1" for the env fallback (rather than truthy parsing) keeps the
// env contract simple and matches Claude Code's binary-feature-gate posture.
// env contract simple and unambiguous.
// Note: an explicit `false` in JSON5 behaves the same as the field being
// absent — to disable, leave both unset.
func (r *Runtime) streamingToolsEnabled() bool {
+79
View File
@@ -0,0 +1,79 @@
package runtime
import (
"context"
"errors"
"sync/atomic"
"testing"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// streamErrThenOKProvider emits EventError (no token) on the first stream
// call, then clean text on the second.
type streamErrThenOKProvider struct {
llmtest.Base
calls atomic.Int64
streamErr error
finalText string
}
func (p *streamErrThenOKProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) {
n := p.calls.Add(1)
ch := make(chan llm.ChatEvent, 4)
if n == 1 {
ch <- llm.ChatEvent{Type: llm.EventError, Error: p.streamErr}
} else {
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: p.finalText}
ch <- llm.ChatEvent{Type: llm.EventDone}
}
close(ch)
return ch, nil
}
func TestStreamErrorRetryableEngagesFallback(t *testing.T) {
prov := &streamErrThenOKProvider{
streamErr: errors.New("429 rate limit exceeded"),
finalText: "RECOVERED_VIA_FALLBACK",
}
rt := &Runtime{
LLM: prov,
Tools: tool.NewRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "claude-opus-4-8",
FallbackModel: "claude-sonnet-4-5",
Provider: "anthropic",
MaxTurns: 2,
Workspace: t.TempDir(),
}
out, err := rt.RunSync(context.Background(), "do it", nil)
require.NoError(t, err)
assert.Contains(t, out, "RECOVERED_VIA_FALLBACK")
assert.EqualValues(t, 2, prov.calls.Load(), "must retry once after the pre-first-token 429")
}
func TestStreamErrorNonRetryableStillAborts(t *testing.T) {
prov := &streamErrThenOKProvider{
streamErr: errors.New("400 invalid input"),
finalText: "SHOULD_NOT_BE_REACHED",
}
rt := &Runtime{
LLM: prov,
Tools: tool.NewRegistry(),
Session: session.NewSession("a", "k"),
AgentID: "a",
Model: "claude-opus-4-8",
Provider: "anthropic",
MaxTurns: 2,
Workspace: t.TempDir(),
}
_, err := rt.RunSync(context.Background(), "do it", nil)
require.Error(t, err)
assert.EqualValues(t, 1, prov.calls.Load(), "non-retryable pre-first-token error must abort, not retry")
}
+8
View File
@@ -71,6 +71,14 @@ type LoopConfig struct {
// StreamingTools enables mid-stream concurrency-safe tool kickoff.
// false ⇒ env fallback (HARNESS_STREAMING_TOOLS=1) then off.
StreamingTools bool
// MaxToolResultLen caps the in-context length of any single tool
// result; longer results are truncated to their first MaxToolResultLen
// chars (cut at a newline boundary) with the remainder either spilled
// to disk via spillConfig or simply dropped. 0 ⇒ env fallback
// (HARNESS_MAX_TOOL_RESULT_LEN) then default 4000. Common pick for
// engineering-style agents (reading source files, running tests) is
// 16000-25000.
MaxToolResultLen int
// Hooks are optional callbacks the runtime fires at well-known
// points in the loop. Zero value (all nil fields) disables every
// hook with no overhead.
+25
View File
@@ -0,0 +1,25 @@
package runtime
import "github.com/sausheong/harness/llm"
// addUsage returns the field-wise sum of two usage snapshots. A nil operand is
// treated as zero. It returns a fresh pointer and never mutates its arguments,
// so callers may safely pass a pointer that aliases a provider stream event.
// Returns nil only when BOTH operands are nil, preserving the contract that
// EventDone.Usage stays nil for providers that never report usage.
func addUsage(acc, turn *llm.Usage) *llm.Usage {
if acc == nil && turn == nil {
return nil
}
var out llm.Usage
if acc != nil {
out = *acc
}
if turn != nil {
out.InputTokens += turn.InputTokens
out.OutputTokens += turn.OutputTokens
out.CacheCreationInputTokens += turn.CacheCreationInputTokens
out.CacheReadInputTokens += turn.CacheReadInputTokens
}
return &out
}
+45
View File
@@ -0,0 +1,45 @@
package runtime
import (
"testing"
"github.com/sausheong/harness/llm"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAddUsage_BothNil(t *testing.T) {
assert.Nil(t, addUsage(nil, nil))
}
func TestAddUsage_AccNil(t *testing.T) {
turn := &llm.Usage{InputTokens: 7, OutputTokens: 3, CacheCreationInputTokens: 2, CacheReadInputTokens: 1}
got := addUsage(nil, turn)
require.NotNil(t, got)
assert.Equal(t, llm.Usage{InputTokens: 7, OutputTokens: 3, CacheCreationInputTokens: 2, CacheReadInputTokens: 1}, *got)
// input not mutated, and the result must be a distinct pointer (the
// non-mutating/aliasing-safety contract the accumulator relies on).
assert.NotSame(t, turn, got)
assert.Equal(t, 7, turn.InputTokens)
}
func TestAddUsage_TurnNil(t *testing.T) {
acc := &llm.Usage{InputTokens: 5}
got := addUsage(acc, nil)
require.NotNil(t, got)
assert.Equal(t, 5, got.InputTokens)
}
func TestAddUsage_SumsAllFourFields(t *testing.T) {
acc := &llm.Usage{InputTokens: 100, OutputTokens: 40, CacheCreationInputTokens: 10, CacheReadInputTokens: 6}
turn := &llm.Usage{InputTokens: 10, OutputTokens: 5, CacheCreationInputTokens: 1, CacheReadInputTokens: 2}
got := addUsage(acc, turn)
require.NotNil(t, got)
assert.Equal(t, 110, got.InputTokens)
assert.Equal(t, 45, got.OutputTokens)
assert.Equal(t, 11, got.CacheCreationInputTokens)
assert.Equal(t, 8, got.CacheReadInputTokens)
// neither input mutated
assert.Equal(t, 100, acc.InputTokens)
assert.Equal(t, 10, turn.InputTokens)
}
+19 -4
View File
@@ -85,6 +85,12 @@ type Session struct {
entryMap map[string]*SessionEntry
leafID string // current leaf for history traversal
store *Store
// writeMu serializes store writes and preserves their order. Acquired in
// Append while s.mu is still held (lock-coupling), then s.mu is released
// before the disk write — so disk latency stays off s.mu while on-disk
// order still matches in-memory append order under concurrent callers. (P5)
writeMu sync.Mutex
}
// NewSession creates a new empty session.
@@ -100,7 +106,6 @@ func NewSession(agentID, key string) *Session {
// Append adds an entry to the session.
func (s *Session) Append(entry SessionEntry) {
s.mu.Lock()
defer s.mu.Unlock()
if entry.ID == "" {
entry.ID = generateID("e")
}
@@ -115,9 +120,19 @@ func (s *Session) Append(entry SessionEntry) {
s.entryMap[entry.ID] = &s.entries[len(s.entries)-1]
s.leafID = entry.ID
// Persist if store is set
if s.store != nil {
s.store.AppendEntry(s, entry)
finalized := entry // value copy with all fields set
store := s.store
// Lock-coupling: take writeMu BEFORE releasing s.mu so the disk-write
// order matches the in-memory append order even under concurrent callers,
// then release s.mu so disk latency doesn't block concurrent View()/append.
if store != nil {
s.writeMu.Lock()
s.mu.Unlock()
store.AppendEntry(s, finalized)
s.writeMu.Unlock()
} else {
s.mu.Unlock()
}
}
+57
View File
@@ -350,3 +350,60 @@ func TestSession_ViewReturnsCopy(t *testing.T) {
require.Len(t, v2, 1)
require.Equal(t, "e_1", v2[0].ID, "internal state must not be mutated by caller's slice modification")
}
func TestConcurrentAppendAndViewNoRace(t *testing.T) {
dir := t.TempDir()
store := NewStore(dir)
require.NoError(t, store.Create("a", "k"))
sess := NewSession("a", "k")
sess.SetStore(store)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 500; i++ {
sess.Append(SessionEntry{Type: EntryTypeMessage, Role: "user", Data: []byte(`{"text":"x"}`)})
}
}()
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 500; i++ {
_ = sess.View()
}
}()
wg.Wait()
require.Len(t, sess.Entries(), 500)
}
// TestAppendPreservesDiskOrder verifies that the P5 lock-coupling keeps the
// on-disk JSONL order identical to the in-memory append order: sequential
// appends must persist in order, and reloading from disk must round-trip them
// in the same sequence.
func TestAppendPreservesDiskOrder(t *testing.T) {
dir := t.TempDir()
store := NewStore(dir)
require.NoError(t, store.Create("a", "k"))
sess := NewSession("a", "k")
sess.SetStore(store)
const n = 200
for i := 0; i < n; i++ {
sess.Append(SessionEntry{
Type: EntryTypeMessage,
Role: "user",
Data: json.RawMessage(fmt.Sprintf(`{"text":"%d"}`, i)),
})
}
reloaded, err := store.Load("a", "k")
require.NoError(t, err)
got := reloaded.Entries()
require.Len(t, got, n)
for i := 0; i < n; i++ {
require.JSONEq(t, fmt.Sprintf(`{"text":"%d"}`, i), string(got[i].Data),
"on-disk entry %d out of order", i)
}
}
+20 -2
View File
@@ -9,6 +9,7 @@ import (
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
)
@@ -22,8 +23,19 @@ type SessionInfo struct {
// Store handles JSONL file I/O for sessions.
type Store struct {
baseDir string
mu sync.Mutex
baseDir string
mu sync.Mutex
degraded atomic.Bool
}
// markDegraded emits a single warning the first time session persistence
// fails, so a user notices that in-memory state may not survive a restart.
// Subsequent failures stay at their existing Error level to avoid log spam.
func (s *Store) markDegraded(reason string, err error) {
if s.degraded.CompareAndSwap(false, true) {
slog.Warn("session persistence degraded; in-memory state may not survive restart",
"reason", reason, "error", err)
}
}
// NewStore creates a new session store.
@@ -94,6 +106,7 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
dir := s.sessionDir(sess.AgentID)
if err := os.MkdirAll(dir, 0o755); err != nil {
s.markDegraded("create session dir", err)
slog.Error("failed to create session dir", "error", err)
return
}
@@ -101,6 +114,7 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
path := s.sessionPath(sess.AgentID, sess.Key)
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
s.markDegraded("open session file", err)
slog.Error("failed to open session file", "error", err)
return
}
@@ -114,6 +128,7 @@ func (s *Store) AppendEntry(sess *Session, entry SessionEntry) {
data = append(data, '\n')
if _, err := f.Write(data); err != nil {
s.markDegraded("write session entry", err)
slog.Error("failed to write session entry", "error", err)
}
}
@@ -252,6 +267,7 @@ func (s *Store) Rewrite(sess *Session) {
dir := s.sessionDir(sess.AgentID)
if err := os.MkdirAll(dir, 0o755); err != nil {
s.markDegraded("create session dir", err)
slog.Error("failed to create session dir", "error", err)
return
}
@@ -260,6 +276,7 @@ func (s *Store) Rewrite(sess *Session) {
f, err := os.Create(path)
if err != nil {
s.markDegraded("create session file for rewrite", err)
slog.Error("failed to create session file for rewrite", "error", err)
return
}
@@ -277,6 +294,7 @@ func (s *Store) Rewrite(sess *Session) {
}
if err := w.Flush(); err != nil {
s.markDegraded("flush session file", err)
slog.Error("failed to flush session file", "error", err)
}
}
+52
View File
@@ -0,0 +1,52 @@
package session
import (
"bytes"
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestStore_DegradedPersistenceWarnsOnce(t *testing.T) {
var buf bytes.Buffer
prev := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})))
defer slog.SetDefault(prev)
// Make a path where the agent dir cannot be created: a regular FILE used
// as baseDir means sessionDir(agentID) = <file>/<agentID> and MkdirAll fails.
tmp := t.TempDir()
blocker := filepath.Join(tmp, "blocker")
require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600))
s := NewStore(blocker)
sess := &Session{AgentID: "a", Key: "k"}
s.AppendEntry(sess, SessionEntry{})
s.AppendEntry(sess, SessionEntry{})
s.AppendEntry(sess, SessionEntry{})
require.Equal(t, 1, strings.Count(buf.String(), "session persistence degraded"),
"degraded warning must fire exactly once across multiple failures")
}
func TestStore_RewriteDegradedWarns(t *testing.T) {
var buf bytes.Buffer
prev := slog.Default()
slog.SetDefault(slog.New(slog.NewTextHandler(&buf, &slog.HandlerOptions{Level: slog.LevelWarn})))
defer slog.SetDefault(prev)
tmp := t.TempDir()
blocker := filepath.Join(tmp, "blocker")
require.NoError(t, os.WriteFile(blocker, []byte("x"), 0o600))
s := NewStore(blocker)
sess := &Session{AgentID: "a", Key: "k"}
s.Rewrite(sess)
require.Equal(t, 1, strings.Count(buf.String(), "session persistence degraded"),
"Rewrite failure must emit the degraded warning")
}
+23 -1
View File
@@ -21,6 +21,10 @@ func Estimate(msgs []llm.Message, systemPrompt string, tools []llm.ToolDef) int
for _, tc := range m.ToolCalls {
total += len(tc.ID) + len(tc.Name) + len(tc.Input)
}
// Images are not part of Content (Images is json:"-"); approximate
// each attached image's token cost. perImageTokens is expressed in
// tokens, so multiply by 4 to survive the final divide-by-4.
total += len(m.Images) * perImageTokens * 4
}
for _, t := range tools {
total += len(t.Name) + len(t.Description) + len(t.Parameters)
@@ -33,6 +37,12 @@ func Estimate(msgs []llm.Message, systemPrompt string, tools []llm.ToolDef) int
// since the final divide-by-4 maps it back to tokens.
const perMessageOverhead = 3
// perImageTokens approximates the token cost of one attached image. Vision
// models bill images by tiles/resolution; ~1500 tokens is a deliberately
// conservative flat estimate so image-heavy sessions trigger preventive
// compaction rather than hitting a reactive overflow.
const perImageTokens = 1500
// ContextWindow returns the maximum input tokens for the given
// "provider/model" identifier.
//
@@ -110,8 +120,20 @@ func windowByModelFamily(modelID string) int {
leaf = leaf[i+1:]
}
switch {
case strings.Contains(id, "claude-fable"),
strings.Contains(id, "claude-mythos"),
strings.Contains(id, "claude-opus-4-6"),
strings.Contains(id, "claude-opus-4-7"),
strings.Contains(id, "claude-opus-4-8"),
strings.Contains(id, "claude-opus-4-9"),
strings.Contains(id, "claude-sonnet-4-6"):
// The 1M-window Claude generation: Fable 5, Mythos 5,
// Opus 4.6+, Sonnet 4.6. Matching the 200k blanket rule below
// would make preventive compaction fire ~5x too early.
return 1000000
case strings.Contains(id, "claude"):
// All current Claude chat models share a 200k window.
// Older Claude chat models (3.x through the 4.5 era, Haiku 4.5)
// share a 200k window.
return 200000
case strings.HasPrefix(leaf, "gpt-4o"), strings.HasPrefix(leaf, "gpt-4-turbo"):
return 128000
+42 -1
View File
@@ -4,6 +4,7 @@ import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
@@ -84,7 +85,7 @@ func TestContextWindowProxyProviderDetectedByModelFamily(t *testing.T) {
model string
want int
}{
{"platformai/claude-sonnet-4-6-asia-southeast1", 200000},
{"platformai/claude-sonnet-4-6-asia-southeast1", 1000000},
{"openrouter/anthropic/claude-3-opus", 200000},
{"bedrock/anthropic.claude-3-haiku", 200000},
{"vertex/gemini-1.5-pro-001", 2000000},
@@ -97,6 +98,17 @@ func TestContextWindowProxyProviderDetectedByModelFamily(t *testing.T) {
}
}
func TestEstimate_CountsImages(t *testing.T) {
textOnly := []llm.Message{{Role: "user", Content: "hello"}}
withImg := []llm.Message{{Role: "user", Content: "hello", Images: []llm.ImageContent{
{MimeType: "image/png", Data: []byte("x")},
{MimeType: "image/png", Data: []byte("y")},
}}}
base := Estimate(textOnly, "", nil)
withImages := Estimate(withImg, "", nil)
require.GreaterOrEqual(t, withImages-base, 2*perImageTokens)
}
func TestContextWindowOllamaDefault(t *testing.T) {
// Without RegisterOllamaContext call, ollama models fall back to a sane default
assert.Equal(t, 32000, ContextWindow("local/qwen2.5:3b-instruct"))
@@ -135,3 +147,32 @@ func TestCalibratorIgnoresZeroOrNegative(t *testing.T) {
c.Update(-5, 100)
assert.Equal(t, 100, c.Adjust(100), "bad samples must be ignored")
}
// TestContextWindow1MClaudeFamily pins the 1M-window Claude generation:
// Fable 5, Mythos 5, Opus 4.6+, and Sonnet 4.6 all ship a 1M context
// window. The old blanket claude→200k rule made compaction fire ~5x too
// early on these models. Older Claude (3.x, 4.0-4.5 era) stays 200k.
func TestContextWindow1MClaudeFamily(t *testing.T) {
tests := []struct {
model string
want int
}{
{"anthropic/claude-fable-5", 1000000},
{"platformai/claude-fable-5-global", 1000000},
{"anthropic/claude-mythos-5", 1000000},
{"anthropic/claude-opus-4-6", 1000000},
{"anthropic/claude-opus-4-7", 1000000},
{"anthropic/claude-opus-4-8", 1000000},
{"platformai/claude-sonnet-4-6-asia-southeast1", 1000000},
// Older generations keep 200k.
{"anthropic/claude-haiku-4-5-20251001", 200000},
{"anthropic/claude-sonnet-4-5", 200000},
{"anthropic/claude-3-5-sonnet-20241022", 200000},
{"anthropic/claude-opus-4-0-20250514", 200000},
}
for _, tc := range tests {
t.Run(tc.model, func(t *testing.T) {
assert.Equal(t, tc.want, ContextWindow(tc.model))
})
}
}
+40
View File
@@ -0,0 +1,40 @@
package tool
import (
"fmt"
"os"
"path/filepath"
)
// WriteFileAtomic writes data to path atomically: it writes to a temp file in
// the same directory, fsyncs, sets perm, then renames over path. A crash
// mid-write leaves either the old file or the complete new file, never a
// truncated one. The rename is atomic on POSIX within a single filesystem.
func WriteFileAtomic(path string, data []byte, perm os.FileMode) error {
dir := filepath.Dir(path)
tmp, err := os.CreateTemp(dir, ".tmp-"+filepath.Base(path)+"-*")
if err != nil {
return fmt.Errorf("create temp: %w", err)
}
tmpName := tmp.Name()
defer func() { _ = os.Remove(tmpName) }()
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return fmt.Errorf("write temp: %w", err)
}
if err := tmp.Sync(); err != nil {
_ = tmp.Close()
return fmt.Errorf("sync temp: %w", err)
}
if err := tmp.Close(); err != nil {
return fmt.Errorf("close temp: %w", err)
}
if err := os.Chmod(tmpName, perm); err != nil {
return fmt.Errorf("chmod temp: %w", err)
}
if err := os.Rename(tmpName, path); err != nil {
return fmt.Errorf("rename temp: %w", err)
}
return nil
}
+33
View File
@@ -0,0 +1,33 @@
package tool
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestWriteFileAtomic(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "out.txt")
require.NoError(t, WriteFileAtomic(path, []byte("hello"), 0o600))
data, err := os.ReadFile(path)
require.NoError(t, err)
require.Equal(t, "hello", string(data))
info, err := os.Stat(path)
require.NoError(t, err)
require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
require.NoError(t, WriteFileAtomic(path, []byte("world"), 0o644))
data, _ = os.ReadFile(path)
require.Equal(t, "world", string(data))
entries, err := os.ReadDir(dir)
require.NoError(t, err)
require.Len(t, entries, 1)
require.Equal(t, "out.txt", entries[0].Name())
}
+129
View File
@@ -0,0 +1,129 @@
package memory_test
// Separate _test package to verify the public surface wires together
// without internal fakes.
import (
"context"
"encoding/json"
"path/filepath"
"testing"
"github.com/sausheong/harness/tool/memory"
"github.com/sausheong/harness/tool/memory/jsonl"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestEndToEnd_SaveListUpdateRemoveRoundTrip(t *testing.T) {
dir := t.TempDir()
store := jsonl.NewStore(filepath.Join(dir, "memory.jsonl"))
tool := &memory.MemoryTool{Store: store}
// Save two entries.
for _, content := range []string{"first preference", "second preference"} {
in, _ := json.Marshal(map[string]any{
"action": "save",
"content": content,
"tags": []string{"pref"},
})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
assert.Empty(t, res.Error)
}
// List both back.
in, _ := json.Marshal(map[string]any{"action": "list"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var entries []memory.Entry
require.NoError(t, json.Unmarshal([]byte(res.Output), &entries))
require.Len(t, entries, 2)
// Update the first.
firstID := entries[0].ID
in, _ = json.Marshal(map[string]any{
"action": "update",
"id": firstID,
"content": "first preference (revised)",
})
res, err = tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar struct {
Success bool `json:"success"`
ID string `json:"id"`
}
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.True(t, ar.Success)
newID := ar.ID
assert.NotEqual(t, firstID, newID)
// Old id is gone via the provider adapter (the system-prompt path).
provider := store.AsMemoryProvider()
_, ok := provider.Get(firstID)
assert.False(t, ok, "old id must be unreachable through MemoryProvider")
body, ok := provider.Get(newID)
assert.True(t, ok)
assert.Equal(t, "first preference (revised)", body)
// FormatIndex includes both live entries.
idx := provider.FormatIndex()
assert.Contains(t, idx, "first preference (revised)")
assert.Contains(t, idx, "second preference")
assert.NotContains(t, idx, "first preference\n", "old version must not appear")
// Remove the second.
secondID := entries[1].ID
in, _ = json.Marshal(map[string]any{"action": "remove", "id": secondID})
_, err = tool.Execute(context.Background(), in)
require.NoError(t, err)
in, _ = json.Marshal(map[string]any{"action": "list"})
res, err = tool.Execute(context.Background(), in)
require.NoError(t, err)
require.NoError(t, json.Unmarshal([]byte(res.Output), &entries))
require.Len(t, entries, 1)
assert.Equal(t, "first preference (revised)", entries[0].Content)
}
func TestEndToEnd_ProviderRoundTripAfterCompact(t *testing.T) {
// Save 5, remove 2, update 1, compact, verify state preserved.
dir := t.TempDir()
store := jsonl.NewStore(filepath.Join(dir, "memory.jsonl"))
memTool := &memory.MemoryTool{Store: store}
ids := []string{}
for range 5 {
in, _ := json.Marshal(map[string]any{
"action": "save",
"content": "entry",
})
res, _ := memTool.Execute(context.Background(), in)
var ar struct {
ID string `json:"id"`
}
_ = json.Unmarshal([]byte(res.Output), &ar)
ids = append(ids, ar.ID)
}
// Remove 2.
for _, id := range ids[:2] {
in, _ := json.Marshal(map[string]any{"action": "remove", "id": id})
_, _ = memTool.Execute(context.Background(), in)
}
// Update 1.
in, _ := json.Marshal(map[string]any{
"action": "update",
"id": ids[2],
"content": "updated",
})
_, _ = memTool.Execute(context.Background(), in)
require.NoError(t, store.Compact(context.Background()))
// State preserved post-compact.
all, err := store.List(context.Background(), "")
require.NoError(t, err)
require.Len(t, all, 3)
}
+22
View File
@@ -0,0 +1,22 @@
//go:build !windows
package jsonl
import (
"os"
"golang.org/x/sys/unix"
)
// lockExclusive acquires an exclusive (write) advisory lock on f.
// Blocks until the lock is available. Released when the file descriptor
// is closed (caller's defer f.Close() does this).
func lockExclusive(f *os.File) error {
return unix.Flock(int(f.Fd()), unix.LOCK_EX)
}
// lockShared acquires a shared (read) advisory lock on f. Multiple
// shared lockers can coexist; an exclusive locker blocks them.
func lockShared(f *os.File) error {
return unix.Flock(int(f.Fd()), unix.LOCK_SH)
}
+13
View File
@@ -0,0 +1,13 @@
//go:build windows
package jsonl
import "os"
// lockExclusive is a no-op on Windows. Cross-process safety on Windows
// would require LockFileEx / Mutex; out of scope for this default
// implementation. Single-process Windows users are unaffected.
func lockExclusive(_ *os.File) error { return nil }
// lockShared is a no-op on Windows. See lockExclusive.
func lockShared(_ *os.File) error { return nil }
+404
View File
@@ -0,0 +1,404 @@
// Package jsonl is the default disk-backed MemoryStore implementation.
// It uses one append-only JSONL file with three line shapes:
//
// - create: {"op":"create", id, content, tags, origin, created_at}
// - update: {"op":"update", id, supersedes, content, origin, created_at, original_created_at}
// - delete: {"op":"delete", id, origin, created_at}
//
// Reads project the file by walking it once: latest write wins,
// tombstoned ids are dropped, superseded chains collapse so old IDs
// don't ghost.
//
// Crash safety rests on three properties:
//
// 1. O_APPEND writes are atomic for buffers ≤ PIPE_BUF (≥4KB on POSIX).
// The MemoryTool caps content at 4KB so a single line never
// interleaves with concurrent appenders.
// 2. fsync is called after each append.
// 3. Torn lines on crash are tolerated — the projection skips
// unparseable lines.
//
// Cross-process safety: appendLine acquires flock(LOCK_EX); projectLocked
// acquires flock(LOCK_SH). The store assumes at most a few processes
// share one file. The locks are advisory POSIX flocks (BSD style); they
// do not prevent processes that don't call flock from corrupting the
// file. Do NOT point hundreds of processes at the same store. On
// Windows the locks are no-ops; single-process users are unaffected.
package jsonl
import (
"bufio"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"os"
"path/filepath"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/sausheong/harness/tool/memory"
)
// Store is a JSONL-on-disk MemoryStore.
type Store struct {
path string
mu sync.RWMutex
}
// NewStore returns a Store backed by path. The file is created lazily
// on first write; reads of a non-existent file return an empty result.
// The parent directory must exist.
func NewStore(path string) *Store {
return &Store{path: path}
}
// line is the on-disk row shape for all three op types. Optional fields
// stay omitted when zero so the file stays grep-friendly.
type line struct {
Op string `json:"op"` // "create" | "update" | "delete"
ID string `json:"id"`
Content string `json:"content,omitempty"`
Tags []string `json:"tags,omitempty"`
Origin string `json:"origin,omitempty"`
Supersedes string `json:"supersedes,omitempty"`
// CreatedAt is the time THIS line was written (treated as the
// entry's UpdatedAt during projection).
CreatedAt time.Time `json:"created_at"`
// OriginalCreatedAt is set on update lines to carry the original
// entry's birth time forward through the supersedes chain. Omitted
// on create and delete lines.
OriginalCreatedAt time.Time `json:"original_created_at,omitzero"`
}
// generateID returns a sortable, collision-resistant id of the form
// mem_YYYY-MM-DD_<8-char-hex>. The hex tail makes same-day collisions
// astronomically unlikely (2^32 space) while keeping ids short.
func generateID(now time.Time) string {
var buf [4]byte
_, _ = rand.Read(buf[:])
return fmt.Sprintf("mem_%s_%s", now.UTC().Format("2006-01-02"), hex.EncodeToString(buf[:]))
}
// appendLine writes one line to the data file with O_APPEND + fsync.
// Caller holds s.mu in write mode.
func (s *Store) appendLine(l line) error {
f, err := os.OpenFile(s.path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600)
if err != nil {
return fmt.Errorf("open: %w", err)
}
defer f.Close()
if err := lockExclusive(f); err != nil {
return fmt.Errorf("lock: %w", err)
}
enc := json.NewEncoder(f) // adds trailing newline automatically
if err := enc.Encode(l); err != nil {
return fmt.Errorf("encode: %w", err)
}
if err := f.Sync(); err != nil {
return fmt.Errorf("fsync: %w", err)
}
return nil
}
// Save implements memory.MemoryStore.
func (s *Store) Save(_ context.Context, e memory.Entry) (memory.Entry, error) {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now().UTC()
if e.ID == "" {
e.ID = generateID(now)
}
e.CreatedAt = now
e.UpdatedAt = now
if err := s.appendLine(line{
Op: "create",
ID: e.ID,
Content: e.Content,
Tags: e.Tags,
Origin: e.Origin,
CreatedAt: now,
}); err != nil {
return memory.Entry{}, err
}
return e, nil
}
// Update implements memory.MemoryStore. The new entry gets a fresh ID
// and supersedes the old one in projection. The original entry's
// CreatedAt is preserved on the new entry; UpdatedAt reflects the time
// of the update write. Tags and Origin are preserved from the original.
func (s *Store) Update(_ context.Context, id, content string) (memory.Entry, error) {
s.mu.Lock()
defer s.mu.Unlock()
entries, _, err := s.projectLocked()
if err != nil {
return memory.Entry{}, err
}
old, ok := entries[id]
if !ok {
return memory.Entry{}, memory.ErrNotFound
}
now := time.Now().UTC()
newID := generateID(now)
if err := s.appendLine(line{
Op: "update",
ID: newID,
Supersedes: id,
Content: content,
Tags: old.Tags, // preserve tags
Origin: old.Origin, // preserve origin
CreatedAt: now,
OriginalCreatedAt: old.CreatedAt,
}); err != nil {
return memory.Entry{}, err
}
return memory.Entry{
ID: newID,
Content: content,
Tags: old.Tags,
Origin: old.Origin,
CreatedAt: old.CreatedAt, // preserved birth time
UpdatedAt: now,
}, nil
}
// Remove implements memory.MemoryStore. Idempotent: removing an unknown
// id returns nil. The store still appends a tombstone in that case to
// keep the operation auditable; projection treats the tombstone as
// authoritative regardless of whether a matching create exists.
func (s *Store) Remove(_ context.Context, id string) error {
s.mu.Lock()
defer s.mu.Unlock()
now := time.Now().UTC()
return s.appendLine(line{
Op: "delete",
ID: id,
CreatedAt: now,
})
}
// List implements memory.MemoryStore.
func (s *Store) List(_ context.Context, tag string) ([]memory.Entry, error) {
s.mu.RLock()
defer s.mu.RUnlock()
entries, _, err := s.projectLocked()
if err != nil {
return nil, err
}
out := make([]memory.Entry, 0, len(entries))
for _, e := range entries {
if tag != "" && !slices.Contains(e.Tags, tag) {
continue
}
out = append(out, e)
}
sort.Slice(out, func(i, j int) bool {
return out[i].CreatedAt.Before(out[j].CreatedAt)
})
return out, nil
}
// projectLocked walks the file once and returns the live entry map +
// the set of tombstoned ids. Caller holds s.mu (any mode).
//
// Returns (empty maps, nil) when the file does not exist — a fresh store
// has no entries, not an error.
func (s *Store) projectLocked() (map[string]memory.Entry, map[string]struct{}, error) {
f, err := os.Open(s.path)
if err != nil {
if os.IsNotExist(err) {
return map[string]memory.Entry{}, map[string]struct{}{}, nil
}
return nil, nil, fmt.Errorf("open: %w", err)
}
defer f.Close()
if err := lockShared(f); err != nil {
return nil, nil, fmt.Errorf("lock: %w", err)
}
entries := map[string]memory.Entry{}
deleted := map[string]struct{}{}
scanner := bufio.NewScanner(f)
scanner.Buffer(make([]byte, 64*1024), 1024*1024) // 1 MB max line
for scanner.Scan() {
var l line
if err := json.Unmarshal(scanner.Bytes(), &l); err != nil {
// Torn / unparseable line — skip. Last entry on a crashed
// process may be incomplete; we tolerate that.
continue
}
switch l.Op {
case "delete":
delete(entries, l.ID)
deleted[l.ID] = struct{}{}
case "create", "update":
if _, gone := deleted[l.ID]; gone {
// Defensive: a later tombstone for this id has already
// been seen. Out-of-order writes from concurrent
// processes shouldn't happen with our flock, but skip
// just in case.
continue
}
if l.Supersedes != "" {
delete(entries, l.Supersedes)
// supersedes only retires the OLD id; the new id is
// recorded below.
}
createdAt := l.CreatedAt
if !l.OriginalCreatedAt.IsZero() {
createdAt = l.OriginalCreatedAt
}
entries[l.ID] = memory.Entry{
ID: l.ID,
Content: l.Content,
Tags: l.Tags,
Origin: l.Origin,
CreatedAt: createdAt,
UpdatedAt: l.CreatedAt,
}
}
}
if err := scanner.Err(); err != nil {
return nil, nil, fmt.Errorf("scan: %w", err)
}
return entries, deleted, nil
}
// Compact rewrites the data file with only live entries (no tombstones,
// no superseded creates). Atomic: writes to a temp file then renames
// over the data file. Caller is responsible for picking when to call
// (typically when len(file) > N × len(live entries)).
//
// Holds s.mu.Lock for the duration. Concurrent reads and writes to
// this Store are blocked until Compact returns.
//
// Compaction preserves each live entry's original CreatedAt: the
// rewritten file uses one create line per entry, with the entry's
// original birth time as the line's created_at. The supersedes-chain
// history is collapsed.
func (s *Store) Compact(_ context.Context) error {
s.mu.Lock()
defer s.mu.Unlock()
entries, _, err := s.projectLocked()
if err != nil {
return err
}
tmp := s.path + ".compacting"
f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
if err != nil {
return fmt.Errorf("open temp: %w", err)
}
enc := json.NewEncoder(f)
// Write in CreatedAt order so the compacted file remains
// chronological — handy for grep/inspection.
ordered := make([]memory.Entry, 0, len(entries))
for _, e := range entries {
ordered = append(ordered, e)
}
sort.Slice(ordered, func(i, j int) bool {
return ordered[i].CreatedAt.Before(ordered[j].CreatedAt)
})
for _, e := range ordered {
if err := enc.Encode(line{
Op: "create",
ID: e.ID,
Content: e.Content,
Tags: e.Tags,
Origin: e.Origin,
CreatedAt: e.CreatedAt,
}); err != nil {
f.Close()
os.Remove(tmp)
return fmt.Errorf("encode: %w", err)
}
}
if err := f.Sync(); err != nil {
f.Close()
os.Remove(tmp)
return fmt.Errorf("fsync: %w", err)
}
if err := f.Close(); err != nil {
os.Remove(tmp)
return fmt.Errorf("close: %w", err)
}
if err := os.Rename(tmp, s.path); err != nil {
os.Remove(tmp)
return fmt.Errorf("rename: %w", err)
}
// Fsync the parent directory so the rename is durable across crashes.
// On Linux, an unfsync'd directory metadata change can be rolled back
// after a power loss even though the rename(2) syscall succeeded.
// On Windows, opening a directory like this isn't supported; ignore
// the error there since flock is also a no-op.
if dir, err := os.Open(filepath.Dir(s.path)); err == nil {
_ = dir.Sync()
_ = dir.Close()
}
return nil
}
// Get implements memory.MemoryStore.
func (s *Store) Get(_ context.Context, id string) (memory.Entry, bool, error) {
s.mu.RLock()
defer s.mu.RUnlock()
entries, _, err := s.projectLocked()
if err != nil {
return memory.Entry{}, false, err
}
e, ok := entries[id]
return e, ok, nil
}
// MemoryProviderAdapter wraps a *Store with the read-only signature
// runtime.MemoryProvider expects (FormatIndex + Get(string)(string,bool)).
// Lets one *Store value serve both writes (via the MemoryStore interface)
// and reads (via runtime.MemoryProvider).
type MemoryProviderAdapter struct{ s *Store }
// AsMemoryProvider returns a wrapper that satisfies
// runtime.MemoryProvider — pass it as RuntimeInputs.Memory while still
// using the same *Store as the MemoryTool's backend.
func (s *Store) AsMemoryProvider() *MemoryProviderAdapter {
return &MemoryProviderAdapter{s: s}
}
// FormatIndex satisfies runtime.MemoryProvider. Returns a markdown
// block for inclusion in the static system prompt; empty when the
// store has no live entries.
func (a *MemoryProviderAdapter) FormatIndex() string {
entries, err := a.s.List(context.Background(), "")
if err != nil || len(entries) == 0 {
return ""
}
var b strings.Builder
b.WriteString("## Memory\n\n")
for _, e := range entries {
b.WriteString("- ")
b.WriteString(e.Content)
b.WriteString("\n")
}
return b.String()
}
// Get satisfies runtime.MemoryProvider. Returns the entry's content
// (not the full Entry struct) so the runtime interface stays simple.
func (a *MemoryProviderAdapter) Get(id string) (string, bool) {
e, ok, err := a.s.Get(context.Background(), id)
if err != nil || !ok {
return "", false
}
return e.Content, true
}
+398
View File
@@ -0,0 +1,398 @@
package jsonl
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/sausheong/harness/tool/memory"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestStore_SaveAssignsID(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
e, err := s.Save(context.Background(), memory.Entry{Content: "user prefers concise responses"})
require.NoError(t, err)
assert.NotEmpty(t, e.ID)
assert.True(t, strings.HasPrefix(e.ID, "mem_"), "id should start with mem_, got %q", e.ID)
assert.Equal(t, "user prefers concise responses", e.Content)
assert.False(t, e.CreatedAt.IsZero())
assert.Equal(t, e.CreatedAt, e.UpdatedAt)
}
func TestStore_GetReturnsSavedEntry(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
saved, err := s.Save(context.Background(), memory.Entry{Content: "hello"})
require.NoError(t, err)
got, ok, err := s.Get(context.Background(), saved.ID)
require.NoError(t, err)
assert.True(t, ok)
assert.Equal(t, saved.ID, got.ID)
assert.Equal(t, "hello", got.Content)
}
func TestStore_GetUnknownReturnsFalseNoError(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
got, ok, err := s.Get(context.Background(), "mem_does_not_exist")
require.NoError(t, err)
assert.False(t, ok)
assert.Equal(t, memory.Entry{}, got)
}
func TestStore_GetOnEmptyFileNoError(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
// File doesn't exist; Get must not error.
_, ok, err := s.Get(context.Background(), "mem_anything")
require.NoError(t, err)
assert.False(t, ok)
}
func TestStore_ListReturnsAllInCreationOrder(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
a, _ := s.Save(context.Background(), memory.Entry{Content: "first"})
b, _ := s.Save(context.Background(), memory.Entry{Content: "second"})
c, _ := s.Save(context.Background(), memory.Entry{Content: "third"})
all, err := s.List(context.Background(), "")
require.NoError(t, err)
require.Len(t, all, 3)
assert.Equal(t, a.ID, all[0].ID)
assert.Equal(t, b.ID, all[1].ID)
assert.Equal(t, c.ID, all[2].ID)
}
func TestStore_ListFiltersByTag(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
_, _ = s.Save(context.Background(), memory.Entry{Content: "general", Tags: []string{"misc"}})
_, _ = s.Save(context.Background(), memory.Entry{Content: "user pref A", Tags: []string{"style", "pref"}})
_, _ = s.Save(context.Background(), memory.Entry{Content: "user pref B", Tags: []string{"pref"}})
pref, err := s.List(context.Background(), "pref")
require.NoError(t, err)
require.Len(t, pref, 2)
for _, e := range pref {
assert.Contains(t, e.Tags, "pref")
}
}
func TestStore_ListEmptyFile(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
all, err := s.List(context.Background(), "")
require.NoError(t, err)
assert.Empty(t, all)
}
func TestStore_UpdateRetiresOldIDAndAssignsNew(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
original, err := s.Save(context.Background(), memory.Entry{Content: "v1"})
require.NoError(t, err)
updated, err := s.Update(context.Background(), original.ID, "v2")
require.NoError(t, err)
assert.NotEqual(t, original.ID, updated.ID, "Update must assign a fresh ID")
assert.Equal(t, "v2", updated.Content)
// Old id is gone.
_, ok, err := s.Get(context.Background(), original.ID)
require.NoError(t, err)
assert.False(t, ok, "old id must be unreachable after Update")
// New id is reachable.
got, ok, err := s.Get(context.Background(), updated.ID)
require.NoError(t, err)
assert.True(t, ok)
assert.Equal(t, "v2", got.Content)
// List shows exactly one entry.
all, err := s.List(context.Background(), "")
require.NoError(t, err)
require.Len(t, all, 1)
assert.Equal(t, updated.ID, all[0].ID)
}
func TestStore_UpdateChainCollapses(t *testing.T) {
// v1 → v2 → v3. After all writes, only v3 should be visible.
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
v1, _ := s.Save(context.Background(), memory.Entry{Content: "v1"})
v2, _ := s.Update(context.Background(), v1.ID, "v2")
v3, _ := s.Update(context.Background(), v2.ID, "v3")
all, err := s.List(context.Background(), "")
require.NoError(t, err)
require.Len(t, all, 1)
assert.Equal(t, v3.ID, all[0].ID)
assert.Equal(t, "v3", all[0].Content)
}
func TestStore_UpdateUnknownReturnsErrNotFound(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
_, err := s.Update(context.Background(), "mem_does_not_exist", "v2")
require.ErrorIs(t, err, memory.ErrNotFound)
}
func TestStore_UpdatePreservesOriginalCreatedAt(t *testing.T) {
// Update should preserve CreatedAt from the original entry; UpdatedAt
// should reflect the time of the update.
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
original, err := s.Save(context.Background(), memory.Entry{Content: "v1"})
require.NoError(t, err)
// Sleep a measurable amount so timestamps diverge.
time.Sleep(10 * time.Millisecond)
updated, err := s.Update(context.Background(), original.ID, "v2")
require.NoError(t, err)
assert.Equal(t, original.CreatedAt.UnixNano(), updated.CreatedAt.UnixNano(),
"CreatedAt must be preserved from the original entry across Update")
assert.True(t, updated.UpdatedAt.After(original.CreatedAt),
"UpdatedAt must be later than original CreatedAt; got UpdatedAt=%v CreatedAt=%v",
updated.UpdatedAt, original.CreatedAt)
// Same invariant must hold after a fresh projection (List re-reads from disk).
all, err := s.List(context.Background(), "")
require.NoError(t, err)
require.Len(t, all, 1)
assert.Equal(t, original.CreatedAt.UnixNano(), all[0].CreatedAt.UnixNano(),
"CreatedAt must be preserved across reload")
assert.True(t, all[0].UpdatedAt.After(all[0].CreatedAt),
"UpdatedAt must be after CreatedAt across reload")
}
func TestStore_UpdateChainPreservesOriginalCreatedAt(t *testing.T) {
// v1 → v2 → v3. v3's CreatedAt must equal v1's CreatedAt.
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
v1, _ := s.Save(context.Background(), memory.Entry{Content: "v1"})
time.Sleep(5 * time.Millisecond)
v2, _ := s.Update(context.Background(), v1.ID, "v2")
time.Sleep(5 * time.Millisecond)
v3, _ := s.Update(context.Background(), v2.ID, "v3")
assert.Equal(t, v1.CreatedAt.UnixNano(), v3.CreatedAt.UnixNano(),
"CreatedAt must propagate through the entire supersedes chain")
assert.True(t, v3.UpdatedAt.After(v1.CreatedAt),
"v3 UpdatedAt should be later than v1 CreatedAt")
}
func TestStore_RemoveDropsEntryFromList(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
a, _ := s.Save(context.Background(), memory.Entry{Content: "keep"})
b, _ := s.Save(context.Background(), memory.Entry{Content: "drop"})
require.NoError(t, s.Remove(context.Background(), b.ID))
all, err := s.List(context.Background(), "")
require.NoError(t, err)
require.Len(t, all, 1)
assert.Equal(t, a.ID, all[0].ID)
_, ok, err := s.Get(context.Background(), b.ID)
require.NoError(t, err)
assert.False(t, ok)
}
func TestStore_RemoveUnknownIsIdempotent(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
require.NoError(t, s.Remove(context.Background(), "mem_does_not_exist"))
require.NoError(t, s.Remove(context.Background(), "mem_does_not_exist"))
}
func TestStore_RemoveAfterUpdateAffectsNewID(t *testing.T) {
// After Update, the OLD id is already gone; only the NEW id remains
// removable. Removing the OLD id is a no-op.
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
v1, _ := s.Save(context.Background(), memory.Entry{Content: "v1"})
v2, _ := s.Update(context.Background(), v1.ID, "v2")
require.NoError(t, s.Remove(context.Background(), v1.ID)) // no-op
all, err := s.List(context.Background(), "")
require.NoError(t, err)
require.Len(t, all, 1) // v2 still present
require.NoError(t, s.Remove(context.Background(), v2.ID))
all, err = s.List(context.Background(), "")
require.NoError(t, err)
assert.Empty(t, all)
}
func TestStore_TornLineIsSkipped(t *testing.T) {
// Simulate a crash mid-write: append a complete entry, then a
// corrupted half-line, then another complete entry. Projection
// must keep both completes and silently drop the torn line.
dir := t.TempDir()
path := filepath.Join(dir, "memory.jsonl")
s := NewStore(path)
a, err := s.Save(context.Background(), memory.Entry{Content: "before"})
require.NoError(t, err)
// Manually inject a torn line.
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0o600)
require.NoError(t, err)
_, err = f.WriteString(`{"op":"create","id":"mem_torn","content":"this line is incomplete`)
require.NoError(t, err)
require.NoError(t, f.Close())
require.NoError(t, appendNewline(path))
b, err := s.Save(context.Background(), memory.Entry{Content: "after"})
require.NoError(t, err)
all, err := s.List(context.Background(), "")
require.NoError(t, err)
require.Len(t, all, 2, "torn line must be skipped, before+after must remain")
ids := []string{all[0].ID, all[1].ID}
assert.Contains(t, ids, a.ID)
assert.Contains(t, ids, b.ID)
}
func appendNewline(path string) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0o600)
if err != nil {
return err
}
defer f.Close()
_, err = f.Write([]byte{'\n'})
return err
}
func TestStore_CompactRemovesTombstonesAndSupersededEntries(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "memory.jsonl")
s := NewStore(path)
a, _ := s.Save(context.Background(), memory.Entry{Content: "keep-1"})
b, _ := s.Save(context.Background(), memory.Entry{Content: "drop"})
c, _ := s.Save(context.Background(), memory.Entry{Content: "keep-2"})
// b → tombstoned
require.NoError(t, s.Remove(context.Background(), b.ID))
// c → updated to c2; c retired
c2, _ := s.Update(context.Background(), c.ID, "keep-2-updated")
beforeStat, err := os.Stat(path)
require.NoError(t, err)
beforeSize := beforeStat.Size()
require.NoError(t, s.Compact(context.Background()))
afterStat, err := os.Stat(path)
require.NoError(t, err)
assert.Less(t, afterStat.Size(), beforeSize, "compaction should shrink the file")
// Live state must be unchanged.
all, err := s.List(context.Background(), "")
require.NoError(t, err)
require.Len(t, all, 2)
ids := []string{all[0].ID, all[1].ID}
assert.Contains(t, ids, a.ID)
assert.Contains(t, ids, c2.ID)
assert.NotContains(t, ids, b.ID)
assert.NotContains(t, ids, c.ID)
}
func TestStore_CompactOnEmptyStoreNoError(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
require.NoError(t, s.Compact(context.Background()))
}
func TestStore_ConcurrentSavesDoNotCorruptFile(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
const N = 50
var wg sync.WaitGroup
wg.Add(N)
errs := make(chan error, N)
for i := range N {
go func(i int) {
defer wg.Done()
_, err := s.Save(context.Background(), memory.Entry{
Content: fmt.Sprintf("entry %d", i),
})
if err != nil {
errs <- err
}
}(i)
}
wg.Wait()
close(errs)
for e := range errs {
t.Errorf("save error: %v", e)
}
all, err := s.List(context.Background(), "")
require.NoError(t, err)
assert.Len(t, all, N, "all 50 concurrent saves must be readable")
}
func TestStore_FormatIndexEmpty(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
provider := s.AsMemoryProvider()
assert.Empty(t, provider.FormatIndex())
}
func TestStore_FormatIndexNonEmpty(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
_, _ = s.Save(context.Background(), memory.Entry{Content: "User prefers concise responses."})
_, _ = s.Save(context.Background(), memory.Entry{Content: "Project uses Go 1.25."})
provider := s.AsMemoryProvider()
idx := provider.FormatIndex()
assert.Contains(t, idx, "## Memory")
assert.Contains(t, idx, "User prefers concise responses.")
assert.Contains(t, idx, "Project uses Go 1.25.")
}
func TestStore_AsMemoryProviderGet(t *testing.T) {
dir := t.TempDir()
s := NewStore(filepath.Join(dir, "memory.jsonl"))
saved, _ := s.Save(context.Background(), memory.Entry{Content: "hello"})
provider := s.AsMemoryProvider()
body, ok := provider.Get(saved.ID)
assert.True(t, ok)
assert.Equal(t, "hello", body)
_, ok = provider.Get("mem_does_not_exist")
assert.False(t, ok)
}
+89
View File
@@ -0,0 +1,89 @@
// Package memory defines the writable memory subsystem for harness:
// the MemoryStore interface that any backend implements, the canonical
// Entry record type, and the OriginKey context value for write
// provenance.
//
// The MemoryTool in tool.go wraps any MemoryStore implementation as a
// tool.Tool the agent can call. The default disk-backed implementation
// lives in tool/memory/jsonl/ — that package's *Store value satisfies
// MemoryStore directly, and satisfies runtime.MemoryProvider via
// Store.AsMemoryProvider() which returns a small wrapper that adapts
// the read signature. One underlying *Store can therefore serve as the
// system-prompt index source, the foreground memory tool's backend,
// AND the review-pass tool's backend.
package memory
import (
"context"
"errors"
"time"
)
// Entry is one durable memory record. ID is stable across reads/writes;
// the store generates one when the caller doesn't supply it (Save with
// Entry.ID == ""). Content is opaque to harness.
type Entry struct {
ID string `json:"id"`
Content string `json:"content"`
Tags []string `json:"tags,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Origin string `json:"origin,omitempty"` // "user", "agent", "review", or any caller-defined label
}
// MemoryStore is the writable backend the MemoryTool dispatches against.
// Implementations should be safe for concurrent use within a single
// process. Cross-process safety is implementation-specific (the JSONL
// default uses flock).
//
// Implementations may also satisfy runtime.MemoryProvider (FormatIndex
// + Get(string) (string, bool)) so the same instance powers both the
// system-prompt index and the write tool.
type MemoryStore interface {
// Save appends a new entry. If e.ID is empty, the store assigns one.
// CreatedAt and UpdatedAt are set by the store; caller-supplied
// values are ignored. Returns the persisted entry with all fields
// populated.
Save(ctx context.Context, e Entry) (Entry, error)
// Update replaces the content of an existing entry. The new entry
// gets a fresh ID and supersedes the old one in projection; the
// old ID becomes invalid for subsequent reads. Returns the new
// entry. Returns ErrNotFound if id is unknown.
Update(ctx context.Context, id string, content string) (Entry, error)
// Remove tombstones an entry. Idempotent — removing an unknown id
// returns nil (the store may log a warning).
Remove(ctx context.Context, id string) error
// List returns all live entries in CreatedAt order. tag == "" returns
// all; tag != "" filters to entries whose Tags contains the tag.
List(ctx context.Context, tag string) ([]Entry, error)
// Get returns one entry by id. The bool is false (no error) when the
// id is unknown or has been tombstoned.
Get(ctx context.Context, id string) (Entry, bool, error)
}
// OriginKey is the context.Value key the MemoryTool reads to tag the
// Origin field of saved entries. runtime.Review sets this to "review";
// foreground calls inherit the default "agent". Callers that want a
// different label set the value before invoking the tool.
type contextKey struct{ name string }
var OriginKey = &contextKey{"memory.origin"}
// Sentinel errors returned by MemoryStore implementations.
var (
// ErrNotFound is returned by Update and Get when the id is unknown
// or has been tombstoned.
ErrNotFound = errors.New("memory: entry not found")
// ErrInvalidContent is returned by Save and Update when content
// fails server-side validation (empty, exceeds size cap).
ErrInvalidContent = errors.New("memory: invalid content")
// ErrInvalidID is returned by Save when a caller-supplied ID fails
// pattern validation.
ErrInvalidID = errors.New("memory: invalid id")
)
+264
View File
@@ -0,0 +1,264 @@
package memory
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/sausheong/harness/tool"
)
// MemoryTool is the action-discriminated tool the agent calls to read
// or write memory entries. Wraps any MemoryStore; the default JSONL
// implementation is in tool/memory/jsonl/.
//
// Five actions are dispatched on the "action" field:
// - save: create a new entry (id auto-generated when omitted)
// - update: replace an existing entry's content (assigns a fresh id)
// - remove: tombstone an entry (idempotent for unknown ids)
// - list: return all entries as a JSON array, optionally tag-filtered
// - get: return one entry as a JSON object by id
//
// Schema is one tool with an "action" enum rather than five separate
// tools, to keep the request prefix small (less schema bloat -> better
// prompt-cache hits).
type MemoryTool struct {
Store MemoryStore
}
// Name returns "memory".
func (t *MemoryTool) Name() string { return "memory" }
// Description is shown to the model in the tool list.
func (t *MemoryTool) Description() string {
return "Save, update, remove, list, or get memory entries — durable facts " +
"and preferences that survive across sessions. Use to capture user " +
"preferences, project context, or workflow conventions worth " +
"remembering."
}
// Parameters returns the JSON-Schema for the tool input.
func (t *MemoryTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["save", "update", "remove", "list", "get"],
"description": "Operation to perform."
},
"id": {
"type": "string",
"description": "Required for update/remove/get. Optional for save (auto-generated when omitted)."
},
"content": {
"type": "string",
"maxLength": 4000,
"description": "Required for save/update. The memory text. Max 4000 characters."
},
"tags": {
"type": "array",
"items": {"type": "string"},
"maxItems": 8,
"description": "Optional categorization for save. Up to 8 tags."
}
},
"required": ["action"]
}`)
}
// IsConcurrencySafe returns false — Save/Update/Remove all mutate the
// underlying store. Even action=list/get touch shared state we don't
// want racing with writes.
func (t *MemoryTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
// memoryInput is the parsed tool input.
type memoryInput struct {
Action string `json:"action"`
ID string `json:"id"`
Content string `json:"content"`
Tags []string `json:"tags"`
}
// actionResult is the canonical envelope every successful or failed
// MemoryTool call returns. runtime.Review reads this shape to extract
// human-readable action summaries.
type actionResult struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
Error string `json:"error,omitempty"`
Target string `json:"target,omitempty"`
ID string `json:"id,omitempty"`
}
func (r actionResult) toToolResult() tool.ToolResult {
b, _ := json.Marshal(r)
return tool.ToolResult{Output: string(b)}
}
func successResult(message, id string) tool.ToolResult {
return actionResult{
Success: true,
Message: message,
Target: "memory",
ID: id,
}.toToolResult()
}
func errorResult(errMsg, id string) tool.ToolResult {
return actionResult{
Success: false,
Error: errMsg,
Target: "memory",
ID: id,
}.toToolResult()
}
// truncatePreview returns content suitable for inclusion in a success
// message — truncated to ~60 chars with an ellipsis.
func truncatePreview(s string) string {
const max = 60
s = strings.TrimSpace(s)
if len(s) <= max {
return s
}
return s[:max] + "…"
}
const maxContentBytes = 4000
// originFromContext returns the OriginKey value or "agent" as default.
func originFromContext(ctx context.Context) string {
if v := ctx.Value(OriginKey); v != nil {
if s, ok := v.(string); ok && s != "" {
return s
}
}
return "agent"
}
// Execute dispatches on the action enum.
func (t *MemoryTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
if t.Store == nil {
return errorResult("memory tool: no store configured", ""), nil
}
var in memoryInput
if err := json.Unmarshal(input, &in); err != nil {
return errorResult(fmt.Sprintf("invalid input: %v", err), ""), nil
}
switch in.Action {
case "save":
return t.executeSave(ctx, in), nil
case "update":
return t.executeUpdate(ctx, in), nil
case "remove":
return t.executeRemove(ctx, in), nil
case "list":
return t.executeList(ctx, in), nil
case "get":
return t.executeGet(ctx, in), nil
case "":
return errorResult("action is required", ""), nil
default:
return errorResult(fmt.Sprintf("unknown action %q", in.Action), ""), nil
}
}
func (t *MemoryTool) executeSave(ctx context.Context, in memoryInput) tool.ToolResult {
content := strings.TrimSpace(in.Content)
if content == "" {
return errorResult("content is required for save", "")
}
if len(content) > maxContentBytes {
return errorResult(fmt.Sprintf("content exceeds max length (%d > %d)", len(content), maxContentBytes), "")
}
if len(in.Tags) > 8 {
return errorResult(fmt.Sprintf("too many tags (max 8, got %d)", len(in.Tags)), "")
}
saved, err := t.Store.Save(ctx, Entry{
Content: content,
Tags: in.Tags,
Origin: originFromContext(ctx),
})
if err != nil {
return errorResult(err.Error(), "")
}
return successResult(fmt.Sprintf("saved memory: %s", truncatePreview(saved.Content)), saved.ID)
}
func (t *MemoryTool) executeUpdate(ctx context.Context, in memoryInput) tool.ToolResult {
if in.ID == "" {
return errorResult("id is required for update", "")
}
content := strings.TrimSpace(in.Content)
if content == "" {
return errorResult("content is required for update", "")
}
if len(content) > maxContentBytes {
return errorResult(fmt.Sprintf("content exceeds max length (%d > %d)", len(content), maxContentBytes), in.ID)
}
updated, err := t.Store.Update(ctx, in.ID, content)
if err != nil {
return errorResult(err.Error(), in.ID)
}
return successResult(fmt.Sprintf("updated memory: %s", truncatePreview(updated.Content)), updated.ID)
}
// executeList returns the entries as a raw JSON array (not the
// action-result envelope) so the model receives a list-shaped value
// it can iterate over directly. runtime.Review's action extractor
// ignores list/get results — they're not "actions taken", they're
// reads.
func (t *MemoryTool) executeList(ctx context.Context, in memoryInput) tool.ToolResult {
tag := ""
if len(in.Tags) > 0 {
tag = in.Tags[0] // first tag is the filter; we don't intersect multi-tag
}
entries, err := t.Store.List(ctx, tag)
if err != nil {
return errorResult(err.Error(), "")
}
if entries == nil {
entries = []Entry{}
}
b, err := json.Marshal(entries)
if err != nil {
return errorResult(err.Error(), "")
}
return tool.ToolResult{Output: string(b)}
}
// executeGet returns the raw Entry as JSON on success; the action-result
// envelope on failure.
func (t *MemoryTool) executeGet(ctx context.Context, in memoryInput) tool.ToolResult {
if in.ID == "" {
return errorResult("id is required for get", "")
}
e, ok, err := t.Store.Get(ctx, in.ID)
if err != nil {
return errorResult(err.Error(), in.ID)
}
if !ok {
return errorResult("not found", in.ID)
}
b, err := json.Marshal(e)
if err != nil {
return errorResult(err.Error(), in.ID)
}
return tool.ToolResult{Output: string(b)}
}
func (t *MemoryTool) executeRemove(ctx context.Context, in memoryInput) tool.ToolResult {
if in.ID == "" {
return errorResult("id is required for remove", "")
}
if err := t.Store.Remove(ctx, in.ID); err != nil {
return errorResult(err.Error(), in.ID)
}
return successResult(fmt.Sprintf("removed memory: %s", in.ID), in.ID)
}
// Compile-time assertion that *MemoryTool satisfies tool.Tool.
var _ tool.Tool = (*MemoryTool)(nil)
+365
View File
@@ -0,0 +1,365 @@
package memory
import (
"context"
"encoding/json"
"fmt"
"slices"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestMemoryTool_NameDescriptionSchema(t *testing.T) {
tool := &MemoryTool{}
assert.Equal(t, "memory", tool.Name())
assert.NotEmpty(t, tool.Description())
var schema struct {
Type string `json:"type"`
Properties map[string]any `json:"properties"`
Required []string `json:"required"`
}
require.NoError(t, json.Unmarshal(tool.Parameters(), &schema))
assert.Equal(t, "object", schema.Type)
assert.Contains(t, schema.Properties, "action")
assert.Contains(t, schema.Properties, "id")
assert.Contains(t, schema.Properties, "content")
assert.Contains(t, schema.Properties, "tags")
assert.Equal(t, []string{"action"}, schema.Required)
}
func TestMemoryTool_IsConcurrencySafeFalse(t *testing.T) {
tool := &MemoryTool{}
assert.False(t, tool.IsConcurrencySafe(nil))
}
// fakeStore is an in-memory MemoryStore for tool tests.
type fakeStore struct {
entries []Entry
failOn string // method name to fail on, e.g. "Save"
nextID int // auto-incremented for empty-id Save calls
}
func (f *fakeStore) Save(_ context.Context, e Entry) (Entry, error) {
if f.failOn == "Save" {
return Entry{}, assertErr("save failed")
}
if e.ID == "" {
f.nextID++
e.ID = fmt.Sprintf("fake_id_%d", f.nextID)
}
e.CreatedAt = time.Now()
e.UpdatedAt = e.CreatedAt
f.entries = append(f.entries, e)
return e, nil
}
func (f *fakeStore) Update(_ context.Context, id, content string) (Entry, error) {
for i, e := range f.entries {
if e.ID == id {
e.Content = content
e.ID = "fake_id_updated"
f.entries[i] = e
return e, nil
}
}
return Entry{}, ErrNotFound
}
func (f *fakeStore) Remove(_ context.Context, id string) error {
out := f.entries[:0]
for _, e := range f.entries {
if e.ID != id {
out = append(out, e)
}
}
f.entries = out
return nil
}
func (f *fakeStore) List(_ context.Context, tag string) ([]Entry, error) {
if tag == "" {
return f.entries, nil
}
out := []Entry{}
for _, e := range f.entries {
if slices.Contains(e.Tags, tag) {
out = append(out, e)
}
}
return out, nil
}
func (f *fakeStore) Get(_ context.Context, id string) (Entry, bool, error) {
for _, e := range f.entries {
if e.ID == id {
return e, true, nil
}
}
return Entry{}, false, nil
}
type assertErr string
func (a assertErr) Error() string { return string(a) }
func TestMemoryTool_SaveHappyPath(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "save", Content: "user likes terse output"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.True(t, ar.Success)
assert.Equal(t, "memory", ar.Target)
assert.Equal(t, "fake_id_1", ar.ID)
assert.Contains(t, ar.Message, "user likes terse output")
require.Len(t, store.entries, 1)
}
func TestMemoryTool_SaveRejectsEmptyContent(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "save", Content: ""})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "content")
assert.Empty(t, store.entries)
}
func TestMemoryTool_SaveRejectsOversizedContent(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
big := make([]byte, 4001)
for i := range big {
big[i] = 'x'
}
in, _ := json.Marshal(memoryInput{Action: "save", Content: string(big)})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "4000")
assert.Empty(t, store.entries)
}
func TestMemoryTool_SaveOriginFromContext(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
ctx := context.WithValue(context.Background(), OriginKey, "review")
in, _ := json.Marshal(memoryInput{Action: "save", Content: "from review"})
_, err := tool.Execute(ctx, in)
require.NoError(t, err)
require.Len(t, store.entries, 1)
assert.Equal(t, "review", store.entries[0].Origin)
}
func TestMemoryTool_SaveOriginDefault(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "save", Content: "from foreground"})
_, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Len(t, store.entries, 1)
assert.Equal(t, "agent", store.entries[0].Origin)
}
func TestMemoryTool_UpdateHappyPath(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
saved, _ := store.Save(context.Background(), Entry{Content: "v1"})
in, _ := json.Marshal(memoryInput{Action: "update", ID: saved.ID, Content: "v2"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.True(t, ar.Success)
assert.Equal(t, "fake_id_updated", ar.ID)
assert.Contains(t, ar.Message, "updated")
}
func TestMemoryTool_UpdateRejectsMissingID(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "update", Content: "v2"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "id")
}
func TestMemoryTool_UpdateNotFound(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "update", ID: "nope", Content: "v2"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "not found")
}
func TestMemoryTool_UpdateRejectsEmptyContent(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
saved, _ := store.Save(context.Background(), Entry{Content: "v1"})
in, _ := json.Marshal(memoryInput{Action: "update", ID: saved.ID, Content: ""})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
}
func TestMemoryTool_RemoveHappyPath(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
saved, _ := store.Save(context.Background(), Entry{Content: "doomed"})
in, _ := json.Marshal(memoryInput{Action: "remove", ID: saved.ID})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.True(t, ar.Success)
assert.Equal(t, saved.ID, ar.ID)
assert.Contains(t, ar.Message, "removed")
assert.Empty(t, store.entries)
}
func TestMemoryTool_RemoveRejectsMissingID(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "remove"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "id")
}
func TestMemoryTool_RemoveUnknownIsSuccessful(t *testing.T) {
// Idempotent: removing a never-existed id returns success.
store := &fakeStore{}
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "remove", ID: "ghost"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.True(t, ar.Success)
}
func TestMemoryTool_ListReturnsAllAsJSON(t *testing.T) {
store := &fakeStore{}
_, _ = store.Save(context.Background(), Entry{Content: "first", Tags: []string{"a"}})
_, _ = store.Save(context.Background(), Entry{Content: "second", Tags: []string{"b"}})
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "list"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
assert.Empty(t, res.Error)
// List output is the raw entries array, not the action-result envelope.
var entries []Entry
require.NoError(t, json.Unmarshal([]byte(res.Output), &entries))
require.Len(t, entries, 2)
assert.Equal(t, "first", entries[0].Content)
assert.Equal(t, "second", entries[1].Content)
}
func TestMemoryTool_ListWithTagFilter(t *testing.T) {
store := &fakeStore{}
_, _ = store.Save(context.Background(), Entry{Content: "general"})
_, _ = store.Save(context.Background(), Entry{Content: "preference", Tags: []string{"pref"}})
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "list", Tags: []string{"pref"}})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var entries []Entry
require.NoError(t, json.Unmarshal([]byte(res.Output), &entries))
require.Len(t, entries, 1)
assert.Equal(t, "preference", entries[0].Content)
}
func TestMemoryTool_ListEmpty(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "list"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
assert.Equal(t, "[]", res.Output)
}
func TestMemoryTool_GetHappyPath(t *testing.T) {
store := &fakeStore{}
saved, _ := store.Save(context.Background(), Entry{Content: "hello"})
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "get", ID: saved.ID})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var entry Entry
require.NoError(t, json.Unmarshal([]byte(res.Output), &entry))
assert.Equal(t, saved.ID, entry.ID)
assert.Equal(t, "hello", entry.Content)
}
func TestMemoryTool_GetUnknownReturnsError(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "get", ID: "ghost"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "not found")
}
func TestMemoryTool_GetRejectsMissingID(t *testing.T) {
store := &fakeStore{}
tool := &MemoryTool{Store: store}
in, _ := json.Marshal(memoryInput{Action: "get"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "id")
}
+508
View File
@@ -0,0 +1,508 @@
// Package disk is the default disk-backed SkillStore implementation.
// It uses one directory per skill: <root>/<name>/SKILL.md holds the
// full body, including a YAML-ish frontmatter block at the top with
// description, tags, origin, and created_at. The directory shape leaves
// room for future supporting files (references/, templates/, scripts/)
// without changing the on-disk schema.
//
// Concurrent writes within one process are protected by a per-skill
// mutex (Task 8). Cross-process safety is best-effort: Create/Replace
// write to a temp file then atomically rename over SKILL.md, but two
// processes racing on the same skill name may still produce
// last-writer-wins behavior. Single-process per store is the
// assumption.
package disk
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/sausheong/harness/tool/skills"
)
// Store is a directory-on-disk SkillStore.
type Store struct {
root string
mu sync.Mutex // guards locks map only
locks map[string]*sync.Mutex // skill name → per-skill lock
}
// NewStore returns a Store rooted at dir. The directory is created
// lazily on first write; reads of a non-existent root return an empty
// result. Callers should pass an absolute path.
func NewStore(root string) *Store {
return &Store{root: root}
}
// lockFor returns the per-skill mutex, allocating it on first use.
// Callers must call mu.Lock() before any read-modify-write on the
// skill's directory.
func (s *Store) lockFor(name string) *sync.Mutex {
s.mu.Lock()
defer s.mu.Unlock()
if s.locks == nil {
s.locks = make(map[string]*sync.Mutex)
}
if l, ok := s.locks[name]; ok {
return l
}
l := &sync.Mutex{}
s.locks[name] = l
return l
}
// skillDir returns the per-skill directory path. Caller must have
// validated name via skills.ValidName first.
func (s *Store) skillDir(name string) string {
return filepath.Join(s.root, name)
}
// skillFile returns the SKILL.md path for the given name.
func (s *Store) skillFile(name string) string {
return filepath.Join(s.skillDir(name), "SKILL.md")
}
// writeBodyAtomic writes body to the skill's SKILL.md via temp+rename,
// creating the parent directory if needed. Caller holds the per-skill
// lock.
func (s *Store) writeBodyAtomic(name, body string) error {
dir := s.skillDir(name)
if err := os.MkdirAll(dir, 0o755); err != nil {
return fmt.Errorf("mkdir: %w", err)
}
tmp, err := os.CreateTemp(dir, ".SKILL.md.*")
if err != nil {
return fmt.Errorf("create temp: %w", err)
}
if _, err := tmp.WriteString(body); err != nil {
tmp.Close()
os.Remove(tmp.Name())
return fmt.Errorf("write: %w", err)
}
if err := tmp.Sync(); err != nil {
tmp.Close()
os.Remove(tmp.Name())
return fmt.Errorf("fsync: %w", err)
}
if err := tmp.Close(); err != nil {
os.Remove(tmp.Name())
return fmt.Errorf("close: %w", err)
}
if err := os.Rename(tmp.Name(), s.skillFile(name)); err != nil {
os.Remove(tmp.Name())
return fmt.Errorf("rename: %w", err)
}
return nil
}
// composeBody assembles a SKILL.md body from a Skill struct: emits a
// frontmatter block with description, tags, origin, created_at, then
// the body sans any pre-existing frontmatter.
func composeBody(s skills.Skill, body string) string {
var b strings.Builder
b.WriteString("---\n")
if s.Description != "" {
b.WriteString("description: ")
b.WriteString(s.Description)
b.WriteString("\n")
}
if len(s.Tags) > 0 {
b.WriteString("tags: [")
b.WriteString(strings.Join(s.Tags, ", "))
b.WriteString("]\n")
}
if s.Origin != "" {
b.WriteString("origin: ")
b.WriteString(s.Origin)
b.WriteString("\n")
}
if !s.CreatedAt.IsZero() {
b.WriteString("created_at: ")
b.WriteString(s.CreatedAt.UTC().Format(time.RFC3339Nano))
b.WriteString("\n")
}
b.WriteString("---\n\n")
// Strip any leading frontmatter from the caller-supplied body so we
// don't double-emit. parseFrontmatter (added in Task 3) returns the
// body without the FM block; for now the simple "if it starts with
// ---\n, drop until the next ---\n" trick suffices.
body = stripFrontmatter(body)
b.WriteString(body)
return b.String()
}
// stripFrontmatter removes a leading YAML-ish frontmatter block from
// body if present. Conservative: only strips when body starts with
// "---\n" and a closing "\n---\n" or "\n---" is found.
func stripFrontmatter(body string) string {
if !strings.HasPrefix(body, "---\n") {
return body
}
rest := body[4:]
if _, after, ok := strings.Cut(rest, "\n---\n"); ok {
// Eat one optional leading blank line after the closing fence.
return strings.TrimPrefix(after, "\n")
}
if i := strings.Index(rest, "\n---"); i >= 0 && i == len(rest)-4 {
return ""
}
return body
}
// Create implements skills.SkillStore.
func (s *Store) Create(_ context.Context, sk skills.Skill) (skills.Skill, error) {
if !skills.ValidName(sk.Name) {
return skills.Skill{}, fmt.Errorf("%w: %q", skills.ErrInvalidName, sk.Name)
}
lock := s.lockFor(sk.Name)
lock.Lock()
defer lock.Unlock()
// Reject duplicates.
if _, err := os.Stat(s.skillFile(sk.Name)); err == nil {
return skills.Skill{}, fmt.Errorf("%w: %q", skills.ErrAlreadyExists, sk.Name)
} else if !errors.Is(err, os.ErrNotExist) {
return skills.Skill{}, fmt.Errorf("stat: %w", err)
}
// Derive metadata from body frontmatter when caller didn't set it.
if sk.Description == "" || len(sk.Tags) == 0 || sk.Origin == "" {
fm, _ := parseFrontmatter(sk.Body)
if sk.Description == "" {
sk.Description = fm.Description
}
if len(sk.Tags) == 0 {
sk.Tags = fm.Tags
}
if sk.Origin == "" {
sk.Origin = fm.Origin
}
}
now := time.Now().UTC()
sk.CreatedAt = now
sk.UpdatedAt = now
if err := s.writeBodyAtomic(sk.Name, composeBody(sk, sk.Body)); err != nil {
return skills.Skill{}, err
}
return sk, nil
}
// frontmatter is the parsed shape of the YAML-ish header block.
type frontmatter struct {
Description string
Tags []string
Origin string
CreatedAt time.Time
}
// parseFrontmatter extracts the leading frontmatter block from body.
// Returns the parsed metadata and the body sans frontmatter. If body
// does not begin with "---\n" or the closing fence is missing, returns
// (zero, body) untouched.
//
// Recognized keys: description, tags, origin, created_at. Unknown keys
// are silently ignored. Tags parse as either "[a, b, c]" or a single
// scalar treated as one tag.
func parseFrontmatter(body string) (frontmatter, string) {
if !strings.HasPrefix(body, "---\n") {
return frontmatter{}, body
}
rest := body[4:]
var fmText, afterFM string
if before, after, ok := strings.Cut(rest, "\n---\n"); ok {
fmText = before
afterFM = after
} else if strings.HasSuffix(rest, "\n---") {
fmText = rest[:len(rest)-4]
afterFM = ""
} else {
return frontmatter{}, body
}
afterFM = strings.TrimPrefix(afterFM, "\n")
var fm frontmatter
for line := range strings.SplitSeq(fmText, "\n") {
line = strings.TrimRight(line, "\r")
key, val, ok := strings.Cut(line, ":")
if !ok {
continue
}
key = strings.TrimSpace(key)
val = strings.TrimSpace(val)
switch key {
case "description":
fm.Description = val
case "origin":
fm.Origin = val
case "created_at":
if t, err := time.Parse(time.RFC3339Nano, val); err == nil {
fm.CreatedAt = t
}
case "tags":
fm.Tags = parseTags(val)
}
}
return fm, afterFM
}
// parseTags accepts "[a, b, c]" (returns ["a","b","c"]) or "a"
// (returns ["a"]). Empty input returns nil.
func parseTags(s string) []string {
s = strings.TrimSpace(s)
if s == "" {
return nil
}
if strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]") {
s = s[1 : len(s)-1]
}
parts := strings.Split(s, ",")
out := make([]string, 0, len(parts))
for _, p := range parts {
p = strings.TrimSpace(p)
if p != "" {
out = append(out, p)
}
}
if len(out) == 0 {
return nil
}
return out
}
// Patch implements skills.SkillStore. Replaces the unique occurrence
// of oldContent with newContent. Returns one of three sentinel errors
// when the patch can't apply cleanly so the model can recover:
//
// - ErrPatchNoMatch: re-read with Get and try again
// - ErrPatchAmbiguous: include more surrounding context in oldContent
// - ErrPatchIdentical: no change requested
//
// Error message includes the match count for the ambiguous case.
func (s *Store) Patch(ctx context.Context, name, oldContent, newContent string) (skills.Skill, error) {
if !skills.ValidName(name) {
return skills.Skill{}, fmt.Errorf("%w: %q", skills.ErrInvalidName, name)
}
lock := s.lockFor(name)
lock.Lock()
defer lock.Unlock()
existing, ok, err := s.Get(ctx, name)
if err != nil {
return skills.Skill{}, err
}
if !ok {
return skills.Skill{}, fmt.Errorf("%w: %q", skills.ErrNotFound, name)
}
if oldContent == newContent {
return skills.Skill{}, skills.ErrPatchIdentical
}
count := strings.Count(existing.Body, oldContent)
switch count {
case 0:
return skills.Skill{}, skills.ErrPatchNoMatch
case 1:
// happy path
default:
return skills.Skill{}, fmt.Errorf("%w (matched %d times)", skills.ErrPatchAmbiguous, count)
}
newBody := strings.Replace(existing.Body, oldContent, newContent, 1)
if err := s.writeBodyAtomic(name, newBody); err != nil {
return skills.Skill{}, err
}
got, ok, err := s.Get(ctx, name)
if err != nil || !ok {
return skills.Skill{}, fmt.Errorf("post-write read: %w", err)
}
return got, nil
}
// Replace implements skills.SkillStore.
func (s *Store) Replace(ctx context.Context, name, body string) (skills.Skill, error) {
if !skills.ValidName(name) {
return skills.Skill{}, fmt.Errorf("%w: %q", skills.ErrInvalidName, name)
}
lock := s.lockFor(name)
lock.Lock()
defer lock.Unlock()
// Confirm existence and read existing CreatedAt.
existing, ok, err := s.Get(ctx, name)
if err != nil {
return skills.Skill{}, err
}
if !ok {
return skills.Skill{}, fmt.Errorf("%w: %q", skills.ErrNotFound, name)
}
// Compose with preserved CreatedAt; refresh UpdatedAt to now.
sk := skills.Skill{
Name: name,
Body: body,
Origin: existing.Origin, // preserved across Replace; caller can include `origin:` in new frontmatter to override
CreatedAt: existing.CreatedAt,
}
fm, _ := parseFrontmatter(body)
if fm.Description != "" {
sk.Description = fm.Description
}
if fm.Origin != "" {
sk.Origin = fm.Origin
}
if len(fm.Tags) > 0 {
sk.Tags = fm.Tags
} else {
sk.Tags = existing.Tags
}
if err := s.writeBodyAtomic(name, composeBody(sk, body)); err != nil {
return skills.Skill{}, err
}
// Re-read to get true mtime. CreatedAt round-trips with full
// nanosecond precision via RFC3339Nano in compose+parse.
got, ok, err := s.Get(ctx, name)
if err != nil || !ok {
return skills.Skill{}, fmt.Errorf("post-write read: %w", err)
}
return got, nil
}
// Remove implements skills.SkillStore. Idempotent — removing an unknown
// name returns nil. Removes the entire per-skill directory (so any
// supporting files added in future, like references/, are cleaned up
// too).
func (s *Store) Remove(_ context.Context, name string) error {
if !skills.ValidName(name) {
return fmt.Errorf("%w: %q", skills.ErrInvalidName, name)
}
lock := s.lockFor(name)
lock.Lock()
defer lock.Unlock()
if err := os.RemoveAll(s.skillDir(name)); err != nil {
return fmt.Errorf("remove: %w", err)
}
return nil
}
// List implements skills.SkillStore.
func (s *Store) List(ctx context.Context) ([]skills.Skill, error) {
entries, err := os.ReadDir(s.root)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return []skills.Skill{}, nil
}
return nil, fmt.Errorf("readdir: %w", err)
}
out := make([]skills.Skill, 0, len(entries))
for _, e := range entries {
if !e.IsDir() {
continue
}
name := e.Name()
if !skills.ValidName(name) {
continue
}
// Confirm SKILL.md exists; otherwise skip.
if _, err := os.Stat(filepath.Join(s.root, name, "SKILL.md")); err != nil {
continue
}
sk, ok, err := s.Get(ctx, name)
if err != nil || !ok {
continue
}
out = append(out, sk)
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out, nil
}
// Get implements skills.SkillStore.
func (s *Store) Get(_ context.Context, name string) (skills.Skill, bool, error) {
if !skills.ValidName(name) {
return skills.Skill{}, false, fmt.Errorf("%w: %q", skills.ErrInvalidName, name)
}
data, err := os.ReadFile(s.skillFile(name))
if err != nil {
if errors.Is(err, os.ErrNotExist) {
return skills.Skill{}, false, nil
}
return skills.Skill{}, false, fmt.Errorf("read: %w", err)
}
stat, err := os.Stat(s.skillFile(name))
if err != nil {
return skills.Skill{}, false, fmt.Errorf("stat: %w", err)
}
body := string(data)
fm, _ := parseFrontmatter(body)
return skills.Skill{
Name: name,
Description: fm.Description,
Body: body, // full body including frontmatter; callers see what's on disk
Tags: fm.Tags,
Origin: fm.Origin,
CreatedAt: fm.CreatedAt,
UpdatedAt: stat.ModTime().UTC(),
}, true, nil
}
// SkillProviderAdapter wraps a *Store with the read-only signature
// runtime.SkillProvider expects (FormatIndex + Get(string)(string,bool)).
// Lets one *Store value serve both writes (via the SkillStore interface)
// and reads (via runtime.SkillProvider).
type SkillProviderAdapter struct{ s *Store }
// AsSkillProvider returns a wrapper that satisfies
// runtime.SkillProvider — pass it as RuntimeInputs.Skills while still
// using the same *Store as the SkillTool's backend.
func (s *Store) AsSkillProvider() *SkillProviderAdapter {
return &SkillProviderAdapter{s: s}
}
// FormatIndex satisfies runtime.SkillProvider. Returns a markdown block
// for inclusion in the static system prompt; empty when the store has
// no skills. Format: one bullet per skill, "name: description". Bodies
// are NOT included — that's what load_skill is for.
func (a *SkillProviderAdapter) FormatIndex() string {
all, err := a.s.List(context.Background())
if err != nil || len(all) == 0 {
return ""
}
var b strings.Builder
b.WriteString("## Skills\n\n")
for _, sk := range all {
b.WriteString("- ")
b.WriteString(sk.Name)
if sk.Description != "" {
b.WriteString(": ")
b.WriteString(sk.Description)
}
b.WriteString("\n")
}
return b.String()
}
// Get satisfies runtime.SkillProvider. Returns the full SKILL.md body
// (frontmatter included).
func (a *SkillProviderAdapter) Get(name string) (string, bool) {
sk, ok, err := a.s.Get(context.Background(), name)
if err != nil || !ok {
return "", false
}
return sk.Body, true
}
+532
View File
@@ -0,0 +1,532 @@
package disk
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/sausheong/harness/tool/skills"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestStore_CreateWritesSkillMd(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
created, err := s.Create(context.Background(), skills.Skill{
Name: "my-skill",
Body: "---\ndescription: A test skill.\n---\n\nDo the thing.\n",
})
require.NoError(t, err)
assert.Equal(t, "my-skill", created.Name)
assert.Equal(t, "A test skill.", created.Description)
assert.False(t, created.CreatedAt.IsZero())
assert.Equal(t, created.CreatedAt, created.UpdatedAt)
// File on disk has expected content.
path := filepath.Join(dir, "my-skill", "SKILL.md")
data, err := os.ReadFile(path)
require.NoError(t, err)
body := string(data)
assert.True(t, strings.HasPrefix(body, "---\n"), "should have frontmatter")
assert.Contains(t, body, "description: A test skill.")
assert.Contains(t, body, "Do the thing.")
}
func TestStore_CreateRejectsInvalidName(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Create(context.Background(), skills.Skill{
Name: "Bad Name With Spaces",
Body: "anything",
})
require.ErrorIs(t, err, skills.ErrInvalidName)
}
func TestStore_CreateRejectsDuplicate(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Create(context.Background(), skills.Skill{Name: "dup", Body: "first"})
require.NoError(t, err)
_, err = s.Create(context.Background(), skills.Skill{Name: "dup", Body: "second"})
require.ErrorIs(t, err, skills.ErrAlreadyExists)
}
func TestStore_CreateRejectsPathTraversal(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
// Names with ".." or "/" are caught by ValidName (regex rejects them).
// Confirm the store relays the rejection.
for _, bad := range []string{"../escape", "sub/skill", ".."} {
_, err := s.Create(context.Background(), skills.Skill{Name: bad, Body: "x"})
require.ErrorIs(t, err, skills.ErrInvalidName, "name %q should be rejected", bad)
}
// And the parent dir contains nothing the store didn't put there.
entries, err := os.ReadDir(dir)
require.NoError(t, err)
for _, e := range entries {
assert.NotEqual(t, "..", e.Name())
}
}
func TestStore_GetReturnsCreatedSkill(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
body := "---\ndescription: My test skill.\ntags: [a, b]\n---\n\nBody content.\n"
created, err := s.Create(context.Background(), skills.Skill{Name: "round-trip", Body: body})
require.NoError(t, err)
got, ok, err := s.Get(context.Background(), "round-trip")
require.NoError(t, err)
require.True(t, ok)
assert.Equal(t, "round-trip", got.Name)
assert.Equal(t, "My test skill.", got.Description)
assert.Equal(t, []string{"a", "b"}, got.Tags)
assert.Contains(t, got.Body, "Body content.")
assert.False(t, got.CreatedAt.IsZero())
assert.Equal(t, created.CreatedAt.Truncate(time.Second), got.CreatedAt.Truncate(time.Second))
}
func TestStore_GetUnknownReturnsFalse(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
got, ok, err := s.Get(context.Background(), "does-not-exist")
require.NoError(t, err)
assert.False(t, ok)
assert.Equal(t, skills.Skill{}, got)
}
func TestStore_GetRejectsInvalidName(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, _, err := s.Get(context.Background(), "../escape")
require.ErrorIs(t, err, skills.ErrInvalidName)
}
func TestStore_GetReadsFrontmatterTagsAndOrigin(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Create(context.Background(), skills.Skill{
Name: "tagged",
Body: "Body.",
Tags: []string{"workflow", "git"},
Origin: "review",
})
require.NoError(t, err)
got, ok, err := s.Get(context.Background(), "tagged")
require.NoError(t, err)
require.True(t, ok)
assert.Equal(t, []string{"workflow", "git"}, got.Tags)
assert.Equal(t, "review", got.Origin)
}
func TestStore_ListReturnsAllInNameOrder(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
for _, name := range []string{"charlie", "alpha", "bravo"} {
_, err := s.Create(context.Background(), skills.Skill{
Name: name,
Body: "---\ndescription: " + name + " skill.\n---\n\nBody.\n",
})
require.NoError(t, err)
}
all, err := s.List(context.Background())
require.NoError(t, err)
require.Len(t, all, 3)
assert.Equal(t, "alpha", all[0].Name)
assert.Equal(t, "bravo", all[1].Name)
assert.Equal(t, "charlie", all[2].Name)
assert.Equal(t, "alpha skill.", all[0].Description)
}
func TestStore_ListEmptyRoot(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
all, err := s.List(context.Background())
require.NoError(t, err)
assert.Empty(t, all)
}
func TestStore_ListNonexistentRoot(t *testing.T) {
// Pointing at a non-existent root should yield empty, not error.
s := NewStore("/tmp/does-not-exist-skills-xyz-" + t.Name())
all, err := s.List(context.Background())
require.NoError(t, err)
assert.Empty(t, all)
}
func TestStore_ListSkipsBogusDirs(t *testing.T) {
// A directory in root that doesn't contain SKILL.md, or whose name
// fails ValidName, must be silently skipped (it's user data we
// don't own).
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Create(context.Background(), skills.Skill{Name: "real", Body: "ok"})
require.NoError(t, err)
// Empty subdir.
require.NoError(t, os.Mkdir(filepath.Join(dir, "empty"), 0o755))
// Subdir with bogus name (uppercase) but containing SKILL.md.
require.NoError(t, os.Mkdir(filepath.Join(dir, "BAD"), 0o755))
require.NoError(t, os.WriteFile(filepath.Join(dir, "BAD", "SKILL.md"), []byte("x"), 0o644))
// File at root level (not a directory).
require.NoError(t, os.WriteFile(filepath.Join(dir, "stray.txt"), []byte("x"), 0o644))
all, err := s.List(context.Background())
require.NoError(t, err)
require.Len(t, all, 1)
assert.Equal(t, "real", all[0].Name)
}
func TestStore_ReplaceOverwritesBody(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
original, err := s.Create(context.Background(), skills.Skill{
Name: "evolving",
Body: "---\ndescription: v1.\n---\n\nv1 body.\n",
})
require.NoError(t, err)
originalCreated := original.CreatedAt
// Sleep 1s so mtime tick is observable.
time.Sleep(1100 * time.Millisecond)
updated, err := s.Replace(context.Background(), "evolving",
"---\ndescription: v2.\n---\n\nv2 body.\n")
require.NoError(t, err)
assert.Equal(t, "evolving", updated.Name)
assert.Equal(t, "v2.", updated.Description)
assert.Contains(t, updated.Body, "v2 body.")
assert.NotContains(t, updated.Body, "v1 body.")
assert.True(t, originalCreated.Equal(updated.CreatedAt) || updated.CreatedAt.IsZero(),
"CreatedAt should survive (got %v, want %v)", updated.CreatedAt, originalCreated)
assert.True(t, updated.UpdatedAt.After(originalCreated),
"UpdatedAt must advance past original CreatedAt")
}
func TestStore_ReplaceRejectsUnknown(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Replace(context.Background(), "ghost", "x")
require.ErrorIs(t, err, skills.ErrNotFound)
}
func TestStore_ReplaceRejectsInvalidName(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Replace(context.Background(), "Bad Name", "x")
require.ErrorIs(t, err, skills.ErrInvalidName)
}
func TestStore_ReplacePreservesCreatedAtAcrossDays(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
original, err := s.Create(context.Background(), skills.Skill{
Name: "stable", Body: "---\ndescription: x.\n---\n\nbody",
})
require.NoError(t, err)
_, err = s.Replace(context.Background(), "stable", "---\ndescription: y.\n---\n\nbody")
require.NoError(t, err)
got, ok, err := s.Get(context.Background(), "stable")
require.NoError(t, err)
require.True(t, ok)
assert.Equal(t,
original.CreatedAt.Truncate(time.Second),
got.CreatedAt.Truncate(time.Second),
"CreatedAt must survive Replace",
)
}
func TestStore_RemoveDeletesSkill(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Create(context.Background(), skills.Skill{Name: "doomed", Body: "x"})
require.NoError(t, err)
require.NoError(t, s.Remove(context.Background(), "doomed"))
_, ok, err := s.Get(context.Background(), "doomed")
require.NoError(t, err)
assert.False(t, ok)
// Directory is gone.
_, err = os.Stat(filepath.Join(dir, "doomed"))
assert.True(t, os.IsNotExist(err))
}
func TestStore_RemoveUnknownIsIdempotent(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
require.NoError(t, s.Remove(context.Background(), "ghost"))
require.NoError(t, s.Remove(context.Background(), "ghost"))
}
func TestStore_RemoveRejectsInvalidName(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
err := s.Remove(context.Background(), "../escape")
require.ErrorIs(t, err, skills.ErrInvalidName)
}
func TestStore_PatchReplacesUniqueOccurrence(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Create(context.Background(), skills.Skill{
Name: "patchable",
Body: "---\ndescription: x.\n---\n\nThe quick brown fox.\n",
})
require.NoError(t, err)
updated, err := s.Patch(context.Background(), "patchable", "brown fox", "lazy dog")
require.NoError(t, err)
assert.Contains(t, updated.Body, "The quick lazy dog.")
assert.NotContains(t, updated.Body, "brown fox")
}
func TestStore_PatchNoMatchReturnsErrPatchNoMatch(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Create(context.Background(), skills.Skill{Name: "p1", Body: "Hello world."})
require.NoError(t, err)
_, err = s.Patch(context.Background(), "p1", "missing", "x")
require.ErrorIs(t, err, skills.ErrPatchNoMatch)
}
func TestStore_PatchMultipleMatchesReturnsAmbiguous(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Create(context.Background(), skills.Skill{Name: "p2", Body: "foo bar foo bar foo"})
require.NoError(t, err)
_, err = s.Patch(context.Background(), "p2", "foo", "x")
require.ErrorIs(t, err, skills.ErrPatchAmbiguous)
assert.Contains(t, err.Error(), "3", "error message should include match count")
}
func TestStore_PatchIdenticalReturnsErrPatchIdentical(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Create(context.Background(), skills.Skill{Name: "p3", Body: "hello"})
require.NoError(t, err)
_, err = s.Patch(context.Background(), "p3", "hello", "hello")
require.ErrorIs(t, err, skills.ErrPatchIdentical)
}
func TestStore_PatchUnknownReturnsErrNotFound(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Patch(context.Background(), "ghost", "a", "b")
require.ErrorIs(t, err, skills.ErrNotFound)
}
func TestStore_PatchUnknownTakesPrecedenceOverIdentical(t *testing.T) {
// Patch on a missing skill with old==new must return ErrNotFound,
// not ErrPatchIdentical — so the model gets the actionable error.
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Patch(context.Background(), "ghost", "x", "x")
require.ErrorIs(t, err, skills.ErrNotFound)
require.NotErrorIs(t, err, skills.ErrPatchIdentical)
}
func TestStore_PatchRejectsInvalidName(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Patch(context.Background(), "Bad Name", "a", "b")
require.ErrorIs(t, err, skills.ErrInvalidName)
}
func TestStore_PatchPreservesCreatedAtRefreshesUpdatedAt(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
original, err := s.Create(context.Background(), skills.Skill{
Name: "p4",
Body: "---\ndescription: orig.\n---\n\nfind me.\n",
})
require.NoError(t, err)
time.Sleep(1100 * time.Millisecond)
updated, err := s.Patch(context.Background(), "p4", "find me", "FOUND")
require.NoError(t, err)
assert.Equal(t,
original.CreatedAt.Truncate(time.Second),
updated.CreatedAt.Truncate(time.Second),
"CreatedAt must survive Patch")
assert.True(t, updated.UpdatedAt.After(original.CreatedAt),
"UpdatedAt must advance")
}
func TestStore_ConcurrentPatchesDoNotInterleave(t *testing.T) {
// 20 goroutines each Patch a unique substring within the same skill.
// Without per-skill serialization, two concurrent read-modify-write
// cycles would race and lose updates. With it, every patch must
// land.
dir := t.TempDir()
s := NewStore(dir)
// Body has 20 distinct sentinels: M00, M01, ..., M19.
var b strings.Builder
b.WriteString("---\ndescription: race test.\n---\n\n")
for i := range 20 {
fmt.Fprintf(&b, "M%02d\n", i)
}
_, err := s.Create(context.Background(), skills.Skill{Name: "race", Body: b.String()})
require.NoError(t, err)
var wg sync.WaitGroup
wg.Add(20)
errs := make(chan error, 20)
for i := range 20 {
go func(i int) {
defer wg.Done()
old := fmt.Sprintf("M%02d", i)
replacement := fmt.Sprintf("X%02d", i)
if _, err := s.Patch(context.Background(), "race", old, replacement); err != nil {
errs <- err
}
}(i)
}
wg.Wait()
close(errs)
for err := range errs {
t.Errorf("patch error: %v", err)
}
got, ok, err := s.Get(context.Background(), "race")
require.NoError(t, err)
require.True(t, ok)
for i := range 20 {
assert.NotContains(t, got.Body, fmt.Sprintf("M%02d", i),
"sentinel M%02d should have been patched", i)
assert.Contains(t, got.Body, fmt.Sprintf("X%02d", i),
"replacement X%02d should be present", i)
}
}
func TestStore_ConcurrentCreatesDoNotDoubleWrite(t *testing.T) {
// 10 goroutines try to Create the same name. Exactly one should
// succeed; the rest get ErrAlreadyExists.
dir := t.TempDir()
s := NewStore(dir)
var wg sync.WaitGroup
wg.Add(10)
successes := make(chan struct{}, 10)
conflicts := make(chan struct{}, 10)
for range 10 {
go func() {
defer wg.Done()
_, err := s.Create(context.Background(), skills.Skill{
Name: "race-create", Body: "x",
})
switch {
case err == nil:
successes <- struct{}{}
case errors.Is(err, skills.ErrAlreadyExists):
conflicts <- struct{}{}
default:
t.Errorf("unexpected error: %v", err)
}
}()
}
wg.Wait()
close(successes)
close(conflicts)
assert.Len(t, drain(successes), 1, "exactly one Create should succeed")
assert.Len(t, drain(conflicts), 9, "the other nine should see ErrAlreadyExists")
}
func drain(ch <-chan struct{}) []struct{} {
out := []struct{}{}
for v := range ch {
out = append(out, v)
}
return out
}
func TestStore_AsSkillProvider_FormatIndexEmpty(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
provider := s.AsSkillProvider()
assert.Empty(t, provider.FormatIndex())
}
func TestStore_AsSkillProvider_FormatIndexLists(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Create(context.Background(), skills.Skill{
Name: "writing-clearly",
Body: "---\ndescription: Tighten prose.\n---\n\nbody",
})
require.NoError(t, err)
_, err = s.Create(context.Background(), skills.Skill{
Name: "git-bisect",
Body: "---\ndescription: Find the bad commit.\n---\n\nbody",
})
require.NoError(t, err)
provider := s.AsSkillProvider()
idx := provider.FormatIndex()
assert.Contains(t, idx, "## Skills")
assert.Contains(t, idx, "git-bisect")
assert.Contains(t, idx, "Find the bad commit.")
assert.Contains(t, idx, "writing-clearly")
assert.Contains(t, idx, "Tighten prose.")
// Body content must not leak — only one-liners.
assert.NotContains(t, idx, "\nbody")
}
func TestStore_AsSkillProvider_GetReturnsBody(t *testing.T) {
dir := t.TempDir()
s := NewStore(dir)
_, err := s.Create(context.Background(), skills.Skill{
Name: "lookup",
Body: "---\ndescription: x.\n---\n\nThe full body.\n",
})
require.NoError(t, err)
provider := s.AsSkillProvider()
body, ok := provider.Get("lookup")
assert.True(t, ok)
assert.Contains(t, body, "The full body.")
_, ok = provider.Get("does-not-exist")
assert.False(t, ok)
}
+133
View File
@@ -0,0 +1,133 @@
package skills_test
// Separate _test package to verify the public surface wires together
// without internal fakes.
import (
"context"
"encoding/json"
"path/filepath"
"strings"
"testing"
"github.com/sausheong/harness/tool/skills"
"github.com/sausheong/harness/tool/skills/disk"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestEndToEnd_CreatePatchReplaceRemoveRoundTrip(t *testing.T) {
dir := t.TempDir()
store := disk.NewStore(filepath.Join(dir, "skills"))
tool := &skills.SkillTool{Store: store}
// Create two skills.
for _, name := range []string{"writing-clearly", "git-bisect"} {
body := "---\ndescription: " + name + " skill.\n---\n\nThe " + name + " body.\n"
in, _ := json.Marshal(map[string]any{
"action": "create",
"name": name,
"body": body,
})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
assert.Empty(t, res.Error)
}
// List both back (index-only — bodies stripped).
in, _ := json.Marshal(map[string]any{"action": "list"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var entries []skills.Skill
require.NoError(t, json.Unmarshal([]byte(res.Output), &entries))
require.Len(t, entries, 2)
for _, e := range entries {
assert.Empty(t, e.Body, "list output must strip body")
assert.NotEmpty(t, e.Description, "list output must include description")
}
// Patch one.
in, _ = json.Marshal(map[string]any{
"action": "patch",
"name": "writing-clearly",
"old_string": "writing-clearly body.",
"new_string": "writing-clearly body, revised.",
})
res, err = tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar struct {
Success bool `json:"success"`
}
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.True(t, ar.Success)
// Verify via the provider adapter (the system-prompt path).
provider := store.AsSkillProvider()
body, ok := provider.Get("writing-clearly")
assert.True(t, ok)
assert.Contains(t, body, "writing-clearly body, revised.")
// FormatIndex includes both skills with descriptions, no body content.
idx := provider.FormatIndex()
assert.Contains(t, idx, "writing-clearly")
assert.Contains(t, idx, "git-bisect")
assert.Contains(t, idx, "writing-clearly skill.")
assert.NotContains(t, idx, "writing-clearly body, revised.",
"FormatIndex must not leak body content")
// Replace the other.
newBody := "---\ndescription: New body.\n---\n\nFresh content.\n"
in, _ = json.Marshal(map[string]any{
"action": "replace",
"name": "git-bisect",
"body": newBody,
})
res, err = tool.Execute(context.Background(), in)
require.NoError(t, err)
var rr struct {
Success bool `json:"success"`
}
require.NoError(t, json.Unmarshal([]byte(res.Output), &rr))
assert.True(t, rr.Success)
got, ok := provider.Get("git-bisect")
assert.True(t, ok)
assert.Contains(t, got, "Fresh content.")
// Remove one.
in, _ = json.Marshal(map[string]any{"action": "remove", "name": "writing-clearly"})
_, err = tool.Execute(context.Background(), in)
require.NoError(t, err)
in, _ = json.Marshal(map[string]any{"action": "list"})
res, err = tool.Execute(context.Background(), in)
require.NoError(t, err)
require.NoError(t, json.Unmarshal([]byte(res.Output), &entries))
require.Len(t, entries, 1)
assert.Equal(t, "git-bisect", entries[0].Name)
}
func TestEndToEnd_GetReturnsFullBody(t *testing.T) {
dir := t.TempDir()
store := disk.NewStore(filepath.Join(dir, "skills"))
tool := &skills.SkillTool{Store: store}
body := "---\ndescription: A test.\n---\n\nFull body content here.\n"
in, _ := json.Marshal(map[string]any{
"action": "create",
"name": "fetch-me",
"body": body,
})
_, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
in, _ = json.Marshal(map[string]any{"action": "get", "name": "fetch-me"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var sk skills.Skill
require.NoError(t, json.Unmarshal([]byte(res.Output), &sk))
assert.Equal(t, "fetch-me", sk.Name)
assert.Equal(t, "A test.", sk.Description)
assert.True(t, strings.Contains(sk.Body, "Full body content here."))
}
+149
View File
@@ -0,0 +1,149 @@
// Package skills defines the writable skills subsystem for harness:
// the SkillStore interface that any backend implements, the canonical
// Skill record type, and the OriginKey context value for write
// provenance.
//
// The SkillTool in tool.go wraps any SkillStore implementation as a
// tool.Tool the agent can call. The default disk-backed implementation
// lives in tool/skills/disk/ — that package's *Store value satisfies
// SkillStore directly, and satisfies runtime.SkillProvider via
// Store.AsSkillProvider() which returns a small wrapper that adapts
// the Get signature ((Skill, bool, error) → (string, bool)). One
// underlying *Store can therefore serve as the system-prompt index
// source, the foreground skill tool's backend, AND the review-pass
// tool's backend.
//
// Skill names are kebab-case and validated by ValidName: lowercase
// letters and digits, hyphen-separated, 1–64 chars, no leading hyphen,
// no slashes, no dots, no underscores, no double-underscore prefix
// (reserved for runtime use, e.g. "__review__").
package skills
import (
"context"
"errors"
"regexp"
"time"
)
// Skill is one durable procedural-knowledge record. Name is the stable
// identifier (and primary key); Body is the full SKILL.md content
// including any frontmatter. Description is taken from the
// caller-supplied field when set; otherwise the store derives it from
// the body's frontmatter `description:` line.
type Skill struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Body string `json:"body,omitempty"`
Tags []string `json:"tags,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Origin string `json:"origin,omitempty"`
}
// SkillStore is the writable backend the SkillTool dispatches against.
// Implementations should be safe for concurrent use within a single
// process. Cross-process safety is implementation-specific and not
// guaranteed by the default disk implementation.
//
// Implementations may also satisfy runtime.SkillProvider (FormatIndex
// + Get(string) (string, bool)) so the same instance powers both the
// system-prompt index and the write tool.
type SkillStore interface {
// Create writes a new skill. Rejects with ErrAlreadyExists when a
// skill of the same name already exists; rejects with ErrInvalidName
// when s.Name fails ValidName. CreatedAt and UpdatedAt are set by
// the store; caller-supplied values are ignored. Description is
// parsed from frontmatter on the way in. Returns the persisted
// skill with all fields populated.
Create(ctx context.Context, s Skill) (Skill, error)
// Patch replaces the first occurrence of oldContent with newContent
// inside the existing skill's Body. Errors:
// - ErrNotFound — no skill of that name
// - ErrPatchNoMatch — oldContent not found in the body
// - ErrPatchAmbiguous — oldContent matched more than once
// (error wraps the count for the model to read)
// - ErrPatchIdentical — oldContent == newContent
// On success returns the updated skill (UpdatedAt refreshed).
Patch(ctx context.Context, name, oldContent, newContent string) (Skill, error)
// Replace overwrites the entire body of an existing skill. Returns
// ErrNotFound when name is unknown. Preserves CreatedAt; refreshes
// UpdatedAt; re-derives Description from the new frontmatter.
Replace(ctx context.Context, name, body string) (Skill, error)
// Remove deletes a skill. Idempotent — removing an unknown name
// returns nil (the store may log a warning).
Remove(ctx context.Context, name string) error
// List returns all skills in Name order.
List(ctx context.Context) ([]Skill, error)
// Get returns one skill by name. The bool is false (no error) when
// the name is unknown.
Get(ctx context.Context, name string) (Skill, bool, error)
}
// OriginKey is the context.Value key the SkillTool reads to tag the
// Origin field of created skills. runtime.Review sets this to "review";
// foreground calls inherit the default "agent". Callers that want a
// different label set the value before invoking the tool.
//
// Note: tool/memory defines its own memory.OriginKey. The two are
// independent context values; runtime.Review sets both when it forks
// a reviewer Runtime. Per-package keys keep tool/skills and tool/memory
// import-independent.
type contextKey struct{ name string }
var OriginKey = &contextKey{"skills.origin"}
// nameRE is the on-disk name pattern. Kebab-case, lowercase, 1–64 chars,
// no leading hyphen, no underscores, no slashes, no dots.
var nameRE = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`)
// ValidName reports whether name is a legal skill name. Used by stores
// before any filesystem touch — keeps invalid names out of the store
// and out of error logs.
func ValidName(name string) bool {
if !nameRE.MatchString(name) {
return false
}
// Reject the "__"-prefix range (reserved for runtime-internal names
// like "__review__"). The base regex already excludes underscores
// entirely so this is currently belt-and-braces, but kept explicit
// in case the regex relaxes later.
if len(name) >= 2 && name[0] == '_' && name[1] == '_' {
return false
}
return true
}
// Sentinel errors returned by SkillStore implementations.
var (
// ErrNotFound is returned by Patch, Replace, and Get when the name
// is unknown.
ErrNotFound = errors.New("skills: skill not found")
// ErrAlreadyExists is returned by Create when the name is taken.
ErrAlreadyExists = errors.New("skills: skill already exists")
// ErrInvalidName is returned by Create when the name fails ValidName.
ErrInvalidName = errors.New("skills: invalid name")
// ErrInvalidContent is returned by Create/Replace when the body
// fails server-side validation (empty, exceeds size cap).
ErrInvalidContent = errors.New("skills: invalid content")
// ErrPatchNoMatch is returned by Patch when oldContent is not
// present in the body.
ErrPatchNoMatch = errors.New("skills: patch old_string not found")
// ErrPatchAmbiguous is returned by Patch when oldContent matches
// more than once. The error message includes the match count.
ErrPatchAmbiguous = errors.New("skills: patch old_string matched multiple times")
// ErrPatchIdentical is returned by Patch when oldContent == newContent
// (no-op rejected as likely model mistake).
ErrPatchIdentical = errors.New("skills: patch old_string and new_string are identical")
)
+40
View File
@@ -0,0 +1,40 @@
package skills
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestValidName_Accepts(t *testing.T) {
for _, name := range []string{
"a",
"abc",
"my-skill",
"skill-with-many-dashes",
"a1b2c3",
"writing-clearly-and-concisely",
// 64 chars exactly
"abcdefghij-abcdefghij-abcdefghij-abcdefghij-abcdefghij-abcdefghi",
} {
assert.True(t, ValidName(name), "expected %q to validate", name)
}
}
func TestValidName_Rejects(t *testing.T) {
for _, name := range []string{
"", // empty
"-leading-dash", // can't start with dash
"UPPER", // no uppercase
"snake_case", // no underscores
"with space", // no spaces
"path/traversal", // no slashes
"..", // no dots
"my.skill", // no dots
"__reserved", // reserved prefix
// 65 chars (one over)
"abcdefghij-abcdefghij-abcdefghij-abcdefghij-abcdefghij-abcdefghij",
} {
assert.False(t, ValidName(name), "expected %q to be rejected", name)
}
}
+290
View File
@@ -0,0 +1,290 @@
package skills
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/sausheong/harness/tool"
)
// maxBodyBytes is the server-side cap on skill body length. Mirrors the
// schema's maxLength so the model and the server agree.
const maxBodyBytes = 32000
// SkillTool is the action-discriminated tool the agent calls to manage
// skills. Wraps any SkillStore; the default disk implementation is in
// tool/skills/disk/.
//
// Schema is one tool with an "action" enum (vs six separate tools) to
// keep the request prefix small (less schema bloat → better
// prompt-cache hits).
type SkillTool struct {
Store SkillStore
}
// Name returns "skill_manage" (matches the Hermes naming for parity
// with the spec's reference implementation).
func (t *SkillTool) Name() string { return "skill_manage" }
// Description is shown to the model in the tool list.
func (t *SkillTool) Description() string {
return "Create, patch, replace, remove, list, or get skills — durable " +
"procedural knowledge that survives across sessions. Use to " +
"capture workflows, conventions, or reusable techniques worth " +
"keeping."
}
// Parameters returns the JSON-Schema for the tool input.
func (t *SkillTool) Parameters() json.RawMessage {
return json.RawMessage(`{
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["create", "patch", "replace", "remove", "list", "get"],
"description": "Operation to perform."
},
"name": {
"type": "string",
"pattern": "^[a-z0-9][a-z0-9-]{0,63}$",
"description": "Skill name (kebab-case, 1-64 chars). Required for create/patch/replace/remove/get."
},
"body": {
"type": "string",
"maxLength": 32000,
"description": "Full SKILL.md content for create/replace. May include YAML-ish frontmatter (---\ndescription: ...\n---\n) at the top. Max 32000 characters."
},
"old_string": {
"type": "string",
"description": "Required for patch. The string to replace. Must occur exactly once in the existing body."
},
"new_string": {
"type": "string",
"description": "Required for patch. The replacement string."
}
},
"required": ["action"]
}`)
}
// IsConcurrencySafe returns false — every action that modifies the
// store mutates shared state. Even read-only actions (list, get) touch
// the same on-disk hierarchy and are best serialized.
func (t *SkillTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
// skillInput is the parsed tool input.
type skillInput struct {
Action string `json:"action"`
Name string `json:"name"`
Body string `json:"body"`
OldString string `json:"old_string"`
NewString string `json:"new_string"`
}
// actionResult is the canonical envelope every successful or failed
// SkillTool call returns. runtime.Review reads this shape (target +
// success + message + name) to extract human-readable summaries.
//
// Same shape as memory.actionResult; we keep it duplicated rather than
// importing tool/memory for one struct so the two tool packages remain
// independent.
type actionResult struct {
Success bool `json:"success"`
Message string `json:"message,omitempty"`
Error string `json:"error,omitempty"`
Target string `json:"target,omitempty"`
Name string `json:"name,omitempty"`
}
func (r actionResult) toToolResult() tool.ToolResult {
b, _ := json.Marshal(r)
return tool.ToolResult{Output: string(b)}
}
func successResult(message, name string) tool.ToolResult {
return actionResult{
Success: true,
Message: message,
Target: "skill",
Name: name,
}.toToolResult()
}
func errorResult(errMsg, name string) tool.ToolResult {
return actionResult{
Success: false,
Error: errMsg,
Target: "skill",
Name: name,
}.toToolResult()
}
// truncatePreview returns content suitable for inclusion in a success
// message — truncated to ~60 chars with an ellipsis.
func truncatePreview(s string) string {
const max = 60
s = strings.TrimSpace(s)
if len(s) <= max {
return s
}
return s[:max] + "…"
}
// originFromContext returns the OriginKey value or "agent" as default.
func originFromContext(ctx context.Context) string {
if v := ctx.Value(OriginKey); v != nil {
if s, ok := v.(string); ok && s != "" {
return s
}
}
return "agent"
}
// Execute dispatches on the action enum.
func (t *SkillTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
if t.Store == nil {
return errorResult("skill tool: no store configured", ""), nil
}
var in skillInput
if err := json.Unmarshal(input, &in); err != nil {
return errorResult(fmt.Sprintf("invalid input: %v", err), ""), nil
}
switch in.Action {
case "create":
return t.executeCreate(ctx, in), nil
case "patch":
return t.executePatch(ctx, in), nil
case "replace":
return t.executeReplace(ctx, in), nil
case "remove":
return t.executeRemove(ctx, in), nil
case "list":
return t.executeList(ctx, in), nil
case "get":
return t.executeGet(ctx, in), nil
case "":
return errorResult("action is required", ""), nil
default:
return errorResult(fmt.Sprintf("unknown action %q", in.Action), ""), nil
}
}
func (t *SkillTool) executeCreate(ctx context.Context, in skillInput) tool.ToolResult {
if in.Name == "" {
return errorResult("name is required for create", "")
}
if !ValidName(in.Name) {
return errorResult(fmt.Sprintf("invalid name %q (must be kebab-case, 1-64 chars)", in.Name), in.Name)
}
body := in.Body
if strings.TrimSpace(body) == "" {
return errorResult("body is required for create", in.Name)
}
if len(body) > maxBodyBytes {
return errorResult(fmt.Sprintf("body exceeds max length (%d > %d)", len(body), maxBodyBytes), in.Name)
}
created, err := t.Store.Create(ctx, Skill{
Name: in.Name,
Body: body,
Origin: originFromContext(ctx),
})
if err != nil {
return errorResult(err.Error(), in.Name)
}
return successResult(fmt.Sprintf("created skill: %s", truncatePreview(created.Name)), created.Name)
}
func (t *SkillTool) executePatch(ctx context.Context, in skillInput) tool.ToolResult {
if in.Name == "" {
return errorResult("name is required for patch", "")
}
if in.OldString == "" {
return errorResult("old_string is required for patch", in.Name)
}
updated, err := t.Store.Patch(ctx, in.Name, in.OldString, in.NewString)
if err != nil {
// All three Patch sentinels are returned via err.Error(); we
// surface them verbatim so the model can recognize the category
// from the message.
return errorResult(err.Error(), in.Name)
}
return successResult(fmt.Sprintf("patched skill: %s", truncatePreview(updated.Name)), updated.Name)
}
func (t *SkillTool) executeReplace(ctx context.Context, in skillInput) tool.ToolResult {
if in.Name == "" {
return errorResult("name is required for replace", "")
}
body := in.Body
if strings.TrimSpace(body) == "" {
return errorResult("body is required for replace", in.Name)
}
if len(body) > maxBodyBytes {
return errorResult(fmt.Sprintf("body exceeds max length (%d > %d)", len(body), maxBodyBytes), in.Name)
}
updated, err := t.Store.Replace(ctx, in.Name, body)
if err != nil {
return errorResult(err.Error(), in.Name)
}
return successResult(fmt.Sprintf("replaced skill: %s", truncatePreview(updated.Name)), updated.Name)
}
// executeList returns the skills as a raw JSON array (not the
// action-result envelope) so the model receives a list-shaped value it
// can iterate over directly. Body is stripped — the model can call
// action=get to fetch a specific body.
func (t *SkillTool) executeList(ctx context.Context, _ skillInput) tool.ToolResult {
all, err := t.Store.List(ctx)
if err != nil {
return errorResult(err.Error(), "")
}
if all == nil {
all = []Skill{}
}
stripped := make([]Skill, len(all))
for i, sk := range all {
sk.Body = "" // index only
stripped[i] = sk
}
b, err := json.Marshal(stripped)
if err != nil {
return errorResult(err.Error(), "")
}
return tool.ToolResult{Output: string(b)}
}
// executeGet returns the raw Skill as JSON on success; the action-result
// envelope on failure.
func (t *SkillTool) executeGet(ctx context.Context, in skillInput) tool.ToolResult {
if in.Name == "" {
return errorResult("name is required for get", "")
}
sk, ok, err := t.Store.Get(ctx, in.Name)
if err != nil {
return errorResult(err.Error(), in.Name)
}
if !ok {
return errorResult("not found", in.Name)
}
b, err := json.Marshal(sk)
if err != nil {
return errorResult(err.Error(), in.Name)
}
return tool.ToolResult{Output: string(b)}
}
func (t *SkillTool) executeRemove(ctx context.Context, in skillInput) tool.ToolResult {
if in.Name == "" {
return errorResult("name is required for remove", "")
}
if err := t.Store.Remove(ctx, in.Name); err != nil {
return errorResult(err.Error(), in.Name)
}
return successResult(fmt.Sprintf("removed skill: %s", in.Name), in.Name)
}
// Compile-time assertion that *SkillTool satisfies tool.Tool.
var _ tool.Tool = (*SkillTool)(nil)
+524
View File
@@ -0,0 +1,524 @@
package skills
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSkillTool_NameDescriptionSchema(t *testing.T) {
tool := &SkillTool{}
assert.Equal(t, "skill_manage", tool.Name())
assert.NotEmpty(t, tool.Description())
var schema struct {
Type string `json:"type"`
Properties map[string]any `json:"properties"`
Required []string `json:"required"`
}
require.NoError(t, json.Unmarshal(tool.Parameters(), &schema))
assert.Equal(t, "object", schema.Type)
for _, key := range []string{"action", "name", "body", "old_string", "new_string"} {
assert.Contains(t, schema.Properties, key, "missing %q in schema", key)
}
assert.Equal(t, []string{"action"}, schema.Required)
}
func TestSkillTool_IsConcurrencySafeFalse(t *testing.T) {
tool := &SkillTool{}
assert.False(t, tool.IsConcurrencySafe(nil))
}
// fakeStore is an in-memory SkillStore for tool tests.
type fakeStore struct {
skills map[string]Skill
}
func newFakeStore() *fakeStore { return &fakeStore{skills: map[string]Skill{}} }
func (f *fakeStore) Create(_ context.Context, s Skill) (Skill, error) {
if !ValidName(s.Name) {
return Skill{}, ErrInvalidName
}
if _, ok := f.skills[s.Name]; ok {
return Skill{}, ErrAlreadyExists
}
now := time.Now()
s.CreatedAt = now
s.UpdatedAt = now
f.skills[s.Name] = s
return s, nil
}
func (f *fakeStore) Patch(_ context.Context, name, oldC, newC string) (Skill, error) {
if oldC == newC {
return Skill{}, ErrPatchIdentical
}
s, ok := f.skills[name]
if !ok {
return Skill{}, ErrNotFound
}
if !contains(s.Body, oldC) {
return Skill{}, ErrPatchNoMatch
}
s.Body = replaceFirst(s.Body, oldC, newC)
s.UpdatedAt = time.Now()
f.skills[name] = s
return s, nil
}
func contains(haystack, needle string) bool {
for i := 0; i+len(needle) <= len(haystack); i++ {
if haystack[i:i+len(needle)] == needle {
return true
}
}
return false
}
func replaceFirst(haystack, old, new string) string {
for i := 0; i+len(old) <= len(haystack); i++ {
if haystack[i:i+len(old)] == old {
return haystack[:i] + new + haystack[i+len(old):]
}
}
return haystack
}
func (f *fakeStore) Replace(_ context.Context, name, body string) (Skill, error) {
s, ok := f.skills[name]
if !ok {
return Skill{}, ErrNotFound
}
s.Body = body
s.UpdatedAt = time.Now()
f.skills[name] = s
return s, nil
}
func (f *fakeStore) Remove(_ context.Context, name string) error {
delete(f.skills, name)
return nil
}
func (f *fakeStore) List(_ context.Context) ([]Skill, error) {
out := make([]Skill, 0, len(f.skills))
for _, s := range f.skills {
out = append(out, s)
}
return out, nil
}
func (f *fakeStore) Get(_ context.Context, name string) (Skill, bool, error) {
s, ok := f.skills[name]
return s, ok, nil
}
func TestSkillTool_CreateHappyPath(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{
Action: "create",
Name: "my-skill",
Body: "---\ndescription: A skill.\n---\n\nbody",
})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.True(t, ar.Success)
assert.Equal(t, "skill", ar.Target)
assert.Equal(t, "my-skill", ar.Name)
assert.Contains(t, ar.Message, "my-skill")
require.Len(t, store.skills, 1)
}
func TestSkillTool_CreateRejectsMissingName(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "create", Body: "x"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "name")
}
func TestSkillTool_CreateRejectsInvalidName(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "create", Name: "Bad Name", Body: "x"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "invalid")
}
func TestSkillTool_CreateRejectsEmptyBody(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "create", Name: "x", Body: ""})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "body")
}
func TestSkillTool_CreateRejectsOversizedBody(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
big := make([]byte, 32001)
for i := range big {
big[i] = 'x'
}
in, _ := json.Marshal(skillInput{Action: "create", Name: "big", Body: string(big)})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "32000")
}
func TestSkillTool_CreateOriginFromContext(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
ctx := context.WithValue(context.Background(), OriginKey, "review")
in, _ := json.Marshal(skillInput{Action: "create", Name: "from-review", Body: "x"})
_, err := tool.Execute(ctx, in)
require.NoError(t, err)
require.Len(t, store.skills, 1)
assert.Equal(t, "review", store.skills["from-review"].Origin)
}
func TestSkillTool_CreateOriginDefault(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "create", Name: "from-fg", Body: "x"})
_, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Len(t, store.skills, 1)
assert.Equal(t, "agent", store.skills["from-fg"].Origin)
}
func TestSkillTool_CreateAlreadyExistsRetainsOriginal(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "create", Name: "dup", Body: "first"})
_, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
in, _ = json.Marshal(skillInput{Action: "create", Name: "dup", Body: "second"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "exists")
// Original still intact.
assert.Equal(t, "first", store.skills["dup"].Body)
}
func TestSkillTool_PatchHappyPath(t *testing.T) {
store := newFakeStore()
_, _ = store.Create(context.Background(), Skill{Name: "p", Body: "find me here"})
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{
Action: "patch", Name: "p", OldString: "find me", NewString: "FOUND",
})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.True(t, ar.Success)
assert.Equal(t, "p", ar.Name)
assert.Contains(t, ar.Message, "patched")
assert.Equal(t, "FOUND here", store.skills["p"].Body)
}
func TestSkillTool_PatchRejectsMissingName(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "patch", OldString: "a", NewString: "b"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "name")
}
func TestSkillTool_PatchRejectsMissingOldString(t *testing.T) {
store := newFakeStore()
_, _ = store.Create(context.Background(), Skill{Name: "p", Body: "x"})
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "patch", Name: "p", NewString: "b"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "old_string")
}
func TestSkillTool_PatchSurfacesNoMatchError(t *testing.T) {
store := newFakeStore()
_, _ = store.Create(context.Background(), Skill{Name: "p", Body: "hello world"})
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{
Action: "patch", Name: "p", OldString: "missing", NewString: "x",
})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "not found")
}
func TestSkillTool_PatchSurfacesIdenticalError(t *testing.T) {
store := newFakeStore()
_, _ = store.Create(context.Background(), Skill{Name: "p", Body: "x"})
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{
Action: "patch", Name: "p", OldString: "same", NewString: "same",
})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "identical")
}
func TestSkillTool_PatchUnknownNameReturnsErrNotFound(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{
Action: "patch", Name: "ghost", OldString: "a", NewString: "b",
})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "not found")
}
func TestSkillTool_ReplaceHappyPath(t *testing.T) {
store := newFakeStore()
_, _ = store.Create(context.Background(), Skill{Name: "r", Body: "v1"})
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "replace", Name: "r", Body: "v2"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.True(t, ar.Success)
assert.Contains(t, ar.Message, "replaced")
assert.Equal(t, "v2", store.skills["r"].Body)
}
func TestSkillTool_ReplaceRejectsMissingName(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "replace", Body: "v2"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "name")
}
func TestSkillTool_ReplaceRejectsEmptyBody(t *testing.T) {
store := newFakeStore()
_, _ = store.Create(context.Background(), Skill{Name: "r", Body: "v1"})
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "replace", Name: "r", Body: ""})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
}
func TestSkillTool_ReplaceRejectsOversizedBody(t *testing.T) {
store := newFakeStore()
_, _ = store.Create(context.Background(), Skill{Name: "r", Body: "v1"})
tool := &SkillTool{Store: store}
big := make([]byte, 32001)
for i := range big {
big[i] = 'x'
}
in, _ := json.Marshal(skillInput{Action: "replace", Name: "r", Body: string(big)})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "32000")
}
func TestSkillTool_ReplaceUnknownReturnsErrNotFound(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "replace", Name: "ghost", Body: "x"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "not found")
}
func TestSkillTool_RemoveHappyPath(t *testing.T) {
store := newFakeStore()
_, _ = store.Create(context.Background(), Skill{Name: "doomed", Body: "x"})
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "remove", Name: "doomed"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.True(t, ar.Success)
assert.Equal(t, "doomed", ar.Name)
assert.Contains(t, ar.Message, "removed")
assert.Empty(t, store.skills)
}
func TestSkillTool_RemoveRejectsMissingName(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "remove"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "name")
}
func TestSkillTool_RemoveUnknownIsSuccessful(t *testing.T) {
// Idempotent.
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "remove", Name: "ghost"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.True(t, ar.Success)
}
func TestSkillTool_ListReturnsAllAsJSON(t *testing.T) {
store := newFakeStore()
_, _ = store.Create(context.Background(), Skill{Name: "alpha", Body: "alpha body", Description: "first"})
_, _ = store.Create(context.Background(), Skill{Name: "bravo", Body: "bravo body", Description: "second"})
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "list"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
assert.Empty(t, res.Error)
// List output is the raw skills array (without bodies — this is an
// index, not a content dump).
var entries []Skill
require.NoError(t, json.Unmarshal([]byte(res.Output), &entries))
require.Len(t, entries, 2)
for _, e := range entries {
assert.Empty(t, e.Body, "list output must omit Body to keep the index small")
}
}
func TestSkillTool_ListEmpty(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "list"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
assert.Equal(t, "[]", res.Output)
}
func TestSkillTool_GetHappyPath(t *testing.T) {
store := newFakeStore()
_, _ = store.Create(context.Background(), Skill{Name: "g", Body: "the body"})
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "get", Name: "g"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var sk Skill
require.NoError(t, json.Unmarshal([]byte(res.Output), &sk))
assert.Equal(t, "g", sk.Name)
assert.Equal(t, "the body", sk.Body)
}
func TestSkillTool_GetUnknownReturnsError(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "get", Name: "ghost"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "not found")
}
func TestSkillTool_GetRejectsMissingName(t *testing.T) {
store := newFakeStore()
tool := &SkillTool{Store: store}
in, _ := json.Marshal(skillInput{Action: "get"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
var ar actionResult
require.NoError(t, json.Unmarshal([]byte(res.Output), &ar))
assert.False(t, ar.Success)
assert.Contains(t, ar.Error, "name")
}
+14 -7
View File
@@ -132,10 +132,12 @@ func extractCommands(cmd string) []string {
// Find the earliest operator
minIdx := len(remaining)
opLen := 0
for _, op := range []string{"&&", "||", "|", ";"} {
if idx := strings.Index(remaining, op); idx != -1 && idx < minIdx {
minIdx = idx
opLen = len(op)
for _, op := range []string{"&&", "||", "|", ";", "&"} {
if idx := strings.Index(remaining, op); idx != -1 {
if idx < minIdx || (idx == minIdx && len(op) > opLen) {
minIdx = idx
opLen = len(op)
}
}
}
@@ -190,9 +192,14 @@ func (t *BashTool) Execute(ctx context.Context, input json.RawMessage) (tool.Too
case "deny":
return tool.ToolResult{Error: "bash execution is disabled by policy"}, nil
case "allowlist":
// Block shell metacharacters that can execute arbitrary code
// inside an otherwise-allowed command (e.g. ls $(curl evil.com))
for _, meta := range []string{"$(", "`", "<(", ">(", "${", "\\n"} {
// Block shell metacharacters that can execute arbitrary code or
// write files inside an otherwise-allowed command. Covers command
// substitution (e.g. ls $(curl evil.com)), real newline/CR bytes
// (bash -c treats them as command separators, so trailing lines
// would run unvalidated), and output redirection (">" matches ">",
// ">>", "2>", "&>", "2>&1" — all write/overwrite primitives).
// Input redirection "<" is intentionally allowed (not a write/exec bypass).
for _, meta := range []string{"$(", "`", "<(", ">(", "${", "\n", "\r", ">"} {
if strings.Contains(in.Command, meta) {
return tool.ToolResult{Error: "command contains shell metacharacters not allowed in allowlist mode"}, nil
}
+70
View File
@@ -1,13 +1,48 @@
package bash
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/sausheong/harness/tool"
)
// runAllowlist executes cmd under an allowlist policy and returns the
// ToolResult.Error (empty string = the command was permitted by policy).
func runAllowlist(t *testing.T, allow []string, command string) string {
t.Helper()
bt := &BashTool{ExecPolicy: &ExecPolicy{Level: "allowlist", Allowlist: allow}}
in, err := json.Marshal(bashInput{Command: command})
if err != nil {
t.Fatalf("marshal: %v", err)
}
res, err := bt.Execute(context.Background(), in)
if err != nil {
t.Fatalf("Execute returned a Go error (should use ToolResult.Error): %v", err)
}
return res.Error
}
func TestExtractCommands_BackgroundAmpersand(t *testing.T) {
// "ls & curl ..." must validate BOTH sides; curl is not allowed →
// rejected by policy BEFORE any command executes. Asserting the policy
// rejection message (not just a non-empty Error) is essential: without
// the fix, curl actually runs and its own runtime stderr lands in
// res.Error, which would mask the bypass.
got := runAllowlist(t, []string{"ls"}, "ls & curl http://evil")
if !strings.Contains(got, "not in the exec allowlist") {
t.Fatalf("background-& bypass: expected allowlist rejection of curl, got %q", got)
}
// "ls && echo hi" must still split on && (both allowed) → permitted.
if got := runAllowlist(t, []string{"ls", "echo"}, "ls && echo hi"); got != "" {
t.Fatalf("&& chain wrongly rejected: %q", got)
}
}
func TestSanitizeLLMText(t *testing.T) {
tests := []struct {
name string
@@ -142,3 +177,38 @@ func TestResolveExistingPath(t *testing.T) {
})
}
}
func TestAllowlist_RejectsNewlineCRAndRedirection(t *testing.T) {
allow := []string{"ls", "echo", "cat"}
const metaMsg = "shell metacharacters not allowed"
// The live exploit: a real newline runs a second, unvalidated line.
if got := runAllowlist(t, allow, "ls\ncurl http://evil"); !strings.Contains(got, metaMsg) {
t.Fatalf("newline bypass: expected metacharacter rejection, got %q", got)
}
// Carriage return likewise.
if got := runAllowlist(t, allow, "ls\rcurl http://evil"); !strings.Contains(got, metaMsg) {
t.Fatalf("CR bypass: expected metacharacter rejection, got %q", got)
}
// Redirection write-primitive (allowed cmd overwriting a file).
if got := runAllowlist(t, allow, "echo hi > /tmp/s1_x"); !strings.Contains(got, metaMsg) {
t.Fatalf("redirection > not rejected, got %q", got)
}
if got := runAllowlist(t, allow, "echo hi >> /tmp/s1_x"); !strings.Contains(got, metaMsg) {
t.Fatalf("append redirection >> not rejected, got %q", got)
}
// fd redirection also contains '>' so it is caught too.
if got := runAllowlist(t, allow, "cat a 2>&1"); !strings.Contains(got, metaMsg) {
t.Fatalf("fd redirection 2>&1 not rejected, got %q", got)
}
// Sanity: a plain allowed command still passes the policy gate.
if got := runAllowlist(t, allow, "ls -l"); got != "" {
t.Fatalf("plain allowed command wrongly rejected: %q", got)
}
// Sanity: input redirection '<' is NOT blocked (deliberate scope boundary);
// cat is allowed so policy permits it (it may still fail at runtime if the
// file is missing, but it must NOT be a policy rejection).
if got := runAllowlist(t, allow, "cat < /etc/hostname"); strings.Contains(got, "metacharacters") || strings.Contains(got, "not in the exec allowlist") {
t.Fatalf("input redirection wrongly rejected by policy: %q", got)
}
}
+37
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"os"
"strings"
"sync"
"time"
@@ -35,6 +36,24 @@ const (
janitorInterval = 1 * time.Minute
)
// hostResolverRules forces Chrome to fail DNS resolution for private/internal
// IP ranges and localhost, so in-page fetch() and evaluate()'d JS cannot reach
// cloud-metadata endpoints or localhost services — the Go-side
// ValidateURLNotInternal check only sees the top-level URL, so this covers
// sub-resource and script-initiated requests. (S3)
//
// Residual gap: name-based rules do not stop a page that dials a *literal*
// private IP URL in some Chrome builds; the complete fix is an allowlisting
// proxy (deferred). See the security-deeper spec's limitations section.
const hostResolverRules = "MAP localhost ~NOTFOUND," +
"MAP *.localhost ~NOTFOUND," +
"MAP 127.0.0.0/8 ~NOTFOUND," +
"MAP 10.0.0.0/8 ~NOTFOUND," +
"MAP 172.16.0.0/12 ~NOTFOUND," +
"MAP 169.254.0.0/16 ~NOTFOUND," +
"MAP 192.168.0.0/16 ~NOTFOUND," +
"MAP [::1] ~NOTFOUND"
// stealthScript runs before any page script on every new document. It hides the
// most common headless/automation tells that JS-heavy sites use to refuse to
// render content (Cloudflare, Akamai, anti-bot scripts, "please enable JS"
@@ -453,7 +472,19 @@ func (t *BrowserTool) reapIdleSessions() {
// launchBrowser starts a fresh Chrome and returns its task context plus a
// teardown function that closes both the task and the underlying allocator.
//
// Each launch gets its own user-data-dir created up-front so the path is
// known to both Chrome (it appears in argv as --user-data-dir=…) and the
// reaper watchdog. If the parent dies hard before cleanup runs, the
// watchdog SIGKILLs any process whose argv contains that path and rm -rfs
// the dir.
func launchBrowser(parent context.Context) (context.Context, context.CancelFunc, error) {
udd, err := os.MkdirTemp("", "harness-browser-")
if err != nil {
return nil, nil, fmt.Errorf("create user-data-dir: %w", err)
}
trackDirForReaping(udd)
allocCtx, allocCancel := chromedp.NewExecAllocator(parent,
append(chromedp.DefaultExecAllocatorOptions[:],
chromedp.NoSandbox,
@@ -461,6 +492,8 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc,
chromedp.UserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"),
chromedp.Flag("disable-blink-features", "AutomationControlled"),
chromedp.Flag("lang", "en-US"),
chromedp.Flag("host-resolver-rules", hostResolverRules),
chromedp.UserDataDir(udd),
)...,
)
taskCtx, taskCancel := chromedp.NewContext(allocCtx)
@@ -474,11 +507,15 @@ func launchBrowser(parent context.Context) (context.Context, context.CancelFunc,
); err != nil {
taskCancel()
allocCancel()
untrackDirForReaping(udd)
_ = os.RemoveAll(udd)
return nil, nil, err
}
cleanup := func() {
taskCancel()
allocCancel()
untrackDirForReaping(udd)
_ = os.RemoveAll(udd)
}
return taskCtx, cleanup, nil
}
+44
View File
@@ -0,0 +1,44 @@
//go:build live
package browser
import (
"context"
"testing"
"time"
"github.com/chromedp/cdproto/runtime"
"github.com/chromedp/chromedp"
"github.com/stretchr/testify/require"
)
// TestInPageFetchPrivateIPBlocked_Live verifies host-resolver-rules stops an
// in-page fetch to a metadata IP. Requires a real Chrome. Run:
// go test -tags live ./tools/browser/ -run TestInPageFetchPrivateIPBlocked_Live
func TestInPageFetchPrivateIPBlocked_Live(t *testing.T) {
tool := NewBrowserTool()
defer tool.Shutdown()
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
taskCtx, ccancel, err := launchBrowser(ctx)
require.NoError(t, err)
defer ccancel()
require.NoError(t, chromedp.Run(taskCtx, chromedp.Navigate("https://example.com")))
var result string
script := `(async () => {
try {
await fetch('http://169.254.169.254/latest/meta-data/', {mode:'no-cors'});
return 'REACHED';
} catch (e) {
return 'BLOCKED';
}
})()`
err = chromedp.Run(taskCtx, chromedp.Evaluate(script, &result, func(p *runtime.EvaluateParams) *runtime.EvaluateParams {
return p.WithAwaitPromise(true)
}))
require.NoError(t, err)
require.Equal(t, "BLOCKED", result, "in-page fetch to metadata IP must be blocked by host-resolver-rules")
}
+11
View File
@@ -4,12 +4,23 @@ import (
"context"
"encoding/json"
"fmt"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestHostResolverRules_BlocksPrivateRanges(t *testing.T) {
require.Contains(t, hostResolverRules, "127.0.0.0/8")
require.Contains(t, hostResolverRules, "169.254.0.0/16")
require.Contains(t, hostResolverRules, "10.0.0.0/8")
require.Contains(t, hostResolverRules, "192.168.0.0/16")
require.Contains(t, hostResolverRules, "172.16.0.0/12")
require.Contains(t, hostResolverRules, "localhost")
require.True(t, strings.Contains(hostResolverRules, "~NOTFOUND"))
}
func TestBrowserToolName(t *testing.T) {
tool := &BrowserTool{}
assert.Equal(t, "browser", tool.Name())
+10
View File
@@ -0,0 +1,10 @@
//go:build !unix
package browser
// Stubs for platforms without POSIX pkill/sh. Windows callers fall back
// to chromedp's own teardown; hard-kill orphans are a known limitation
// there until we add a native implementation (e.g. Job Objects).
func trackDirForReaping(dir string) {}
func untrackDirForReaping(dir string) {}
+119
View File
@@ -0,0 +1,119 @@
//go:build unix
package browser
import (
"fmt"
"io"
"os/exec"
"sync"
"syscall"
)
// Why a watchdog subprocess?
//
// chromedp launches Chrome through os/exec; the resulting processes do
// not share a process group with us. On clean shutdown the alloc
// context cancel kills them. On SIGKILL / OOM / force-quit / panic that
// bypasses our cleanup chain, they reparent to PID 1 and survive
// indefinitely — each holding ~150 MB and a temp profile dir.
//
// startReaper spawns a single /bin/sh subprocess detached from our
// process group (Setsid). It accumulates user-data-dir paths from its
// stdin and, when the parent dies (stdin EOF), runs `pkill -9 -f` on
// each path and `rm -rf` the dirs. The watchdog cannot be reaped from
// outside because we never Wait on it; it exits on stdin EOF and the
// kernel cleans up.
var (
reaperOnce sync.Once
reaperMu sync.Mutex
reaperPipe io.WriteCloser
)
// reaperScript reads lines from stdin. A bare path is "tracked"; a line
// of the form "REMOVE <path>" is "untracked" (cleanly closed by us, so
// don't kill it on parent death). On EOF, kill -9 every still-tracked
// process whose argv contains the path, then rm -rf the path.
//
// Pure POSIX sh — no bash-isms. Tested on macOS /bin/sh (dash on Linux
// behaves the same).
const reaperScript = `
paths=""
while IFS= read -r line; do
case "$line" in
"REMOVE "*)
removed="${line#REMOVE }"
new=""
for x in $paths; do
[ "$x" = "$removed" ] && continue
new="$new $x"
done
paths="$new"
;;
*)
paths="$paths $line"
;;
esac
done
for p in $paths; do
[ -z "$p" ] && continue
pkill -9 -f "$p" 2>/dev/null
rm -rf "$p" 2>/dev/null
done
`
func startReaper() {
reaperOnce.Do(func() {
cmd := exec.Command("/bin/sh", "-c", reaperScript)
// Setsid detaches from our controlling terminal and process
// group, so signals to us don't propagate to the watchdog.
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
// Discard stdout/stderr so a closed terminal can't EPIPE the
// watchdog before it runs cleanup.
cmd.Stdout = nil
cmd.Stderr = nil
stdin, err := cmd.StdinPipe()
if err != nil {
return
}
if err := cmd.Start(); err != nil {
_ = stdin.Close()
return
}
// Deliberately do not Wait — the watchdog must outlive us.
reaperPipe = stdin
})
}
// trackDirForReaping registers a Chrome user-data-dir with the
// watchdog. If the parent dies hard before untrackDirForReaping is
// called, the watchdog will SIGKILL any process whose argv contains
// dir and rm -rf the dir.
func trackDirForReaping(dir string) {
if dir == "" {
return
}
startReaper()
reaperMu.Lock()
defer reaperMu.Unlock()
if reaperPipe == nil {
return
}
_, _ = fmt.Fprintf(reaperPipe, "%s\n", dir)
}
// untrackDirForReaping tells the watchdog this dir was torn down
// cleanly. Best-effort; failure is harmless (worst case the watchdog
// rm -rfs an already-empty dir on parent death).
func untrackDirForReaping(dir string) {
if dir == "" {
return
}
reaperMu.Lock()
defer reaperMu.Unlock()
if reaperPipe == nil {
return
}
_, _ = fmt.Fprintf(reaperPipe, "REMOVE %s\n", dir)
}
+19 -2
View File
@@ -5,7 +5,9 @@ import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/sausheong/harness/tool"
)
@@ -50,7 +52,7 @@ func (t *EditFileTool) Parameters() json.RawMessage {
// IsConcurrencySafe returns false — edit_file mutates the filesystem.
func (t *EditFileTool) IsConcurrencySafe(_ json.RawMessage) bool { return false }
func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
func (t *EditFileTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
var in editFileInput
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
@@ -61,6 +63,9 @@ func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
}
in.Path = tool.ExpandHome(in.Path)
if t.WorkDir != "" && !filepath.IsAbs(in.Path) {
in.Path = filepath.Join(t.WorkDir, in.Path)
}
in.Path = tool.ResolveExistingPath(in.Path)
if t.WorkDir != "" {
@@ -69,6 +74,14 @@ func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
}
}
if err := ctx.Err(); err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
if msg := checkFileSize(in.Path, int64(maxTextFileSize), "text"); msg != "" {
return tool.ToolResult{Error: msg}, nil
}
data, err := os.ReadFile(in.Path)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil
@@ -86,7 +99,11 @@ func (t *EditFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
newContent := strings.Replace(content, in.OldString, in.NewString, 1)
if err := os.WriteFile(in.Path, []byte(newContent), 0o644); err != nil {
mode := os.FileMode(0o600)
if info, statErr := os.Stat(in.Path); statErr == nil {
mode = info.Mode().Perm()
}
if err := tool.WriteFileAtomic(in.Path, []byte(newContent), mode); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to write file: %v", err)}, nil
}
+34
View File
@@ -0,0 +1,34 @@
package file
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestEditFilePreservesMode(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "code.txt")
require.NoError(t, os.WriteFile(path, []byte("alpha beta"), 0o640))
tool := &EditFileTool{WorkDir: dir}
in, _ := json.Marshal(map[string]string{
"path": path,
"old_string": "alpha",
"new_string": "gamma",
})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Empty(t, res.Error)
data, _ := os.ReadFile(path)
require.Equal(t, "gamma beta", string(data))
info, err := os.Stat(path)
require.NoError(t, err)
require.Equal(t, os.FileMode(0o640), info.Mode().Perm())
}
+27
View File
@@ -0,0 +1,27 @@
package file
import (
"fmt"
"os"
)
const (
maxTextFileSize = 10 * 1024 * 1024 // 10 MB
maxImageFileSize = 5 * 1024 * 1024 // 5 MB
)
// checkFileSize stats path and returns a non-empty error string if the file
// exceeds limit. kind is "text" or "image" for the message. Empty return means
// within bounds (or stat failed, in which case the caller's read surfaces the
// real error).
func checkFileSize(path string, limit int64, kind string) string {
fi, err := os.Stat(path)
if err != nil {
return ""
}
if fi.Size() > limit {
return fmt.Sprintf("file too large: %d bytes exceeds the %d byte limit for %s files; read a specific range or use a different tool",
fi.Size(), limit, kind)
}
return ""
}
+29 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
@@ -71,7 +72,7 @@ func detectImageMIMEFromBytes(data []byte, hint string) string {
// IsConcurrencySafe returns true — read_file is a pure read.
func (t *ReadFileTool) IsConcurrencySafe(_ json.RawMessage) bool { return true }
func (t *ReadFileTool) Execute(_ context.Context, input json.RawMessage) (tool.ToolResult, error) {
func (t *ReadFileTool) Execute(ctx context.Context, input json.RawMessage) (tool.ToolResult, error) {
var in readFileInput
if err := json.Unmarshal(input, &in); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("invalid input: %v", err)}, nil
@@ -82,6 +83,9 @@ func (t *ReadFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
}
in.Path = tool.ExpandHome(in.Path)
if t.WorkDir != "" && !filepath.IsAbs(in.Path) {
in.Path = filepath.Join(t.WorkDir, in.Path)
}
in.Path = tool.ResolveExistingPath(in.Path)
if t.WorkDir != "" {
@@ -90,13 +94,35 @@ func (t *ReadFileTool) Execute(_ context.Context, input json.RawMessage) (tool.T
}
}
data, err := os.ReadFile(in.Path)
if err := ctx.Err(); err != nil {
return tool.ToolResult{Error: err.Error()}, nil
}
ext := strings.ToLower(filepath.Ext(in.Path))
limit := int64(maxTextFileSize)
kind := "text"
if _, isImg := imageExtMap[ext]; isImg {
limit = int64(maxImageFileSize)
kind = "image"
}
if msg := checkFileSize(in.Path, limit, kind); msg != "" {
return tool.ToolResult{Error: msg}, nil
}
f, err := os.Open(in.Path)
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil
}
defer f.Close()
data, err := io.ReadAll(io.LimitReader(f, limit+1))
if err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to read file: %v", err)}, nil
}
if int64(len(data)) > limit {
return tool.ToolResult{Error: fmt.Sprintf("file too large: exceeds the %d byte limit for %s files; read a specific range or use a different tool", limit, kind)}, nil
}
// Check if this is an image file
ext := strings.ToLower(filepath.Ext(in.Path))
if mimeType, ok := imageExtMap[ext]; ok {
mimeType = detectImageMIMEFromBytes(data, mimeType)
return tool.ToolResult{
+86
View File
@@ -0,0 +1,86 @@
package file
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func writeSized(t *testing.T, dir, name string, n int) string {
t.Helper()
p := filepath.Join(dir, name)
require.NoError(t, os.WriteFile(p, make([]byte, n), 0o600))
return p
}
func TestReadFile_RejectsOversizedText(t *testing.T) {
dir := t.TempDir()
p := writeSized(t, dir, "big.txt", maxTextFileSize+1)
tool := &ReadFileTool{}
in, _ := json.Marshal(map[string]string{"path": p})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Contains(t, res.Error, "too large")
}
func TestReadFile_AllowsNormalText(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "ok.txt")
require.NoError(t, os.WriteFile(p, []byte("hello"), 0o600))
tool := &ReadFileTool{}
in, _ := json.Marshal(map[string]string{"path": p})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Empty(t, res.Error)
require.Equal(t, "hello", res.Output)
}
func TestReadFile_RejectsOversizedImage(t *testing.T) {
dir := t.TempDir()
p := writeSized(t, dir, "big.png", maxImageFileSize+1)
tool := &ReadFileTool{}
in, _ := json.Marshal(map[string]string{"path": p})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Contains(t, res.Error, "too large")
}
func TestEditFile_RejectsOversized(t *testing.T) {
dir := t.TempDir()
p := writeSized(t, dir, "big.txt", maxTextFileSize+1)
tool := &EditFileTool{}
in, _ := json.Marshal(map[string]string{"path": p, "old_string": "a", "new_string": "b"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Contains(t, res.Error, "too large")
}
func TestReadFile_HonorsCancelledContext(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "f.txt")
require.NoError(t, os.WriteFile(p, []byte("hello"), 0o600))
ctx, cancel := context.WithCancel(context.Background())
cancel()
tool := &ReadFileTool{}
in, _ := json.Marshal(map[string]string{"path": p})
res, err := tool.Execute(ctx, in)
require.NoError(t, err)
require.NotEmpty(t, res.Error, "cancelled ctx must short-circuit")
}
func TestEditFile_HonorsCancelledContext(t *testing.T) {
dir := t.TempDir()
p := filepath.Join(dir, "f.txt")
require.NoError(t, os.WriteFile(p, []byte("hello"), 0o600))
ctx, cancel := context.WithCancel(context.Background())
cancel()
tool := &EditFileTool{}
in, _ := json.Marshal(map[string]string{"path": p, "old_string": "h", "new_string": "H"})
res, err := tool.Execute(ctx, in)
require.NoError(t, err)
require.NotEmpty(t, res.Error, "cancelled ctx must short-circuit")
}
+4 -1
View File
@@ -56,6 +56,9 @@ func (t *WriteFileTool) Execute(_ context.Context, input json.RawMessage) (tool.
}
in.Path = tool.ExpandHome(in.Path)
if t.WorkDir != "" && !filepath.IsAbs(in.Path) {
in.Path = filepath.Join(t.WorkDir, in.Path)
}
if t.WorkDir != "" {
if err := tool.ValidatePathInWorkDir(in.Path, t.WorkDir); err != nil {
@@ -69,7 +72,7 @@ func (t *WriteFileTool) Execute(_ context.Context, input json.RawMessage) (tool.
return tool.ToolResult{Error: fmt.Sprintf("failed to create directory: %v", err)}, nil
}
if err := os.WriteFile(in.Path, []byte(in.Content), 0o644); err != nil {
if err := tool.WriteFileAtomic(in.Path, []byte(in.Content), 0o600); err != nil {
return tool.ToolResult{Error: fmt.Sprintf("failed to write file: %v", err)}, nil
}
+26
View File
@@ -0,0 +1,26 @@
package file
import (
"context"
"encoding/json"
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
)
func TestWriteFileIsRestrictive(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "secret.txt")
tool := &WriteFileTool{WorkDir: dir}
in, _ := json.Marshal(map[string]string{"path": path, "content": "data"})
res, err := tool.Execute(context.Background(), in)
require.NoError(t, err)
require.Empty(t, res.Error)
info, err := os.Stat(path)
require.NoError(t, err)
require.Equal(t, os.FileMode(0o600), info.Mode().Perm())
}
+2 -3
View File
@@ -20,9 +20,8 @@ type mcpToolAdapter struct {
}
// Name returns "mcp__<server>__<tool>". The double-underscore
// namespacing matches Claude Code so the LLM treats these tools the
// same way it would in CC and so they can't collide with built-in
// harness tools.
// namespacing prevents collisions with built-in harness tools and
// is the convention most agent harnesses use for MCP-sourced tools.
func (a *mcpToolAdapter) Name() string {
return "mcp__" + a.serverName + "__" + a.sdkTool.Name
}
+9 -2
View File
@@ -35,8 +35,8 @@ import (
// (Streamable HTTP via the SDK's StreamableClientTransport).
type ServerConfig struct {
// Name namespaces the server's tools. Adapter tool names become
// "mcp__<Name>__<tool>", matching Claude Code's convention so the
// LLM treats them the same way.
// "mcp__<Name>__<tool>" — the conventional double-underscore
// scheme that prevents collisions with built-in tools.
Name string
// Command + Args + Env wire the stdio transport. Env is merged into
@@ -125,6 +125,13 @@ func (c *Client) Tools() []tool.Tool { return c.tools }
// Name returns the configured server name.
func (c *Client) Name() string { return c.name }
// Ping verifies the session is alive by sending an MCP ping. A non-nil
// error means the session (and for stdio servers, likely the child
// process) is no longer usable.
func (c *Client) Ping(ctx context.Context) error {
return c.session.Ping(ctx, nil)
}
// Close releases the underlying MCP session. Safe to call multiple
// times — subsequent calls are no-ops.
func (c *Client) Close() error {
+23
View File
@@ -150,6 +150,29 @@ func TestMCPClient_ConnectDiscovers(t *testing.T) {
assert.ElementsMatch(t, []string{"mcp__srv__a", "mcp__srv__b"}, got)
}
func TestMCPClient_PingLiveAndDead(t *testing.T) {
// Built inline (not via startInProcessServer) because the test needs the
// server session to kill the connection mid-life.
ctx := context.Background()
server := sdk.NewServer(&sdk.Implementation{Name: "test-server", Version: "v0"}, nil)
tf := stringArgTool("noop", "no-op", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
return &sdk.CallToolResult{Content: []sdk.Content{&sdk.TextContent{Text: ""}}}, nil
})
server.AddTool(tf.Tool, tf.Handler)
clientTransport, serverTransport := sdk.NewInMemoryTransports()
serverSession, err := server.Connect(ctx, serverTransport, nil)
require.NoError(t, err)
cli, err := connectWithTransport(ctx, "srv", clientTransport, nil)
require.NoError(t, err)
t.Cleanup(func() { _ = cli.Close() })
require.NoError(t, cli.Ping(ctx), "ping against a live session must succeed")
require.NoError(t, serverSession.Close())
assert.Error(t, cli.Ping(ctx), "ping after the server side died must fail")
}
func TestMCPClient_CloseIsIdempotent(t *testing.T) {
cli := startInProcessServer(t, "srv", []sdkToolFixture{
stringArgTool("noop", "no-op", func(_ context.Context, _ *sdk.CallToolRequest) (*sdk.CallToolResult, error) {
+66
View File
@@ -0,0 +1,66 @@
package web
import (
"context"
"fmt"
"net"
"net/http"
"time"
)
// SafeHTTPClient returns an *http.Client whose transport resolves and validates
// the destination host, then dials the exact validated IP — closing the
// TOCTOU/DNS-rebinding window where a stock http.Client would re-resolve the
// hostname independently of ValidateURLNotInternal. Redirects are re-validated.
func SafeHTTPClient(timeout time.Duration) *http.Client {
dialer := &net.Dialer{Timeout: timeout}
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
ips, err := net.DefaultResolver.LookupIP(ctx, "ip", host)
if err != nil {
return nil, fmt.Errorf("cannot resolve %q — blocking to prevent SSRF", host)
}
// Fail closed: if ANY resolved IP is private, refuse — this defeats
// DNS-rebinding where one A record is public and another is private.
for _, ip := range ips {
if isPrivateIP(ip) {
return nil, fmt.Errorf("access to internal address %s (%s) is blocked", host, ip)
}
}
if len(ips) == 0 {
return nil, fmt.Errorf("no usable address for %q", host)
}
// Try each validated public IP in order, falling back on dial
// failure so dual-stack hosts still connect on IPv4-only or
// IPv6-broken networks (stock happy-eyeballs is bypassed because we
// dial literal IPs to pin the validated address).
var lastErr error
for _, ip := range ips {
conn, derr := dialer.DialContext(ctx, network, net.JoinHostPort(ip.String(), port))
if derr == nil {
return conn, nil
}
lastErr = derr
}
return nil, lastErr
},
}
return &http.Client{
Timeout: timeout,
Transport: transport,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return fmt.Errorf("too many redirects (max 10)")
}
if err := ValidateURLNotInternal(req.URL.String()); err != nil {
return fmt.Errorf("redirect blocked: %w", err)
}
return nil
},
}
}
+54
View File
@@ -0,0 +1,54 @@
package web
import (
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestSafeHTTPClient_BlocksPrivateAtDial(t *testing.T) {
client := SafeHTTPClient(5 * time.Second)
// 127.0.0.1 is itself private, so dialing it directly must be refused.
_, err := client.Get("http://127.0.0.1:9/")
require.Error(t, err)
require.Contains(t, err.Error(), "internal address")
}
func TestSafeHTTPClient_AllowsPublic(t *testing.T) {
client := SafeHTTPClient(5 * time.Second)
tr, ok := client.Transport.(*http.Transport)
require.True(t, ok)
require.NotNil(t, tr.DialContext)
require.NotNil(t, client.CheckRedirect)
require.Equal(t, 5*time.Second, client.Timeout)
}
func TestSafeHTTPClient_RedirectToPrivateBlocked(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://169.254.169.254/latest/meta-data/", http.StatusFound)
}))
defer srv.Close()
client := SafeHTTPClient(5 * time.Second)
// The httptest server binds loopback (private), so the FIRST dial is already blocked.
_, err := client.Get(srv.URL)
require.Error(t, err)
}
func TestSafeHTTPClient_PublicUnreachableReturnsDialError(t *testing.T) {
// 192.0.2.1 is RFC5737 TEST-NET-1 (public, unrouteable). It is NOT in the
// private blocklist, so validation passes and we should get a DIAL error
// (timeout/unreachable), not a "blocked" validation error — proving the
// path dials rather than rejecting.
client := SafeHTTPClient(2 * time.Second)
_, err := client.Get("http://192.0.2.1/")
require.Error(t, err)
require.NotContains(t, err.Error(), "internal address")
}
var _ = isPrivateIP(net.IPv4(127, 0, 0, 1))
var _ = strings.TrimSpace
+4
View File
@@ -14,9 +14,13 @@ var privateNetworks = []string{
"172.16.0.0/12", // RFC 1918
"192.168.0.0/16", // RFC 1918
"169.254.0.0/16", // link-local
"0.0.0.0/8", // "this" network / unspecified; routes to loopback on Linux
"100.64.0.0/10", // CGNAT (RFC 6598)
"192.0.0.0/24", // IETF protocol assignments (RFC 6890)
"::1/128", // IPv6 loopback
"fc00::/7", // IPv6 unique local
"fe80::/10", // IPv6 link-local
"::/128", // IPv6 unspecified
}
var parsedPrivateNets []*net.IPNet
+27
View File
@@ -1,10 +1,12 @@
package web
import (
"net"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidateURLNotInternal_BlocksLoopback(t *testing.T) {
@@ -45,3 +47,28 @@ func TestValidateURLNotInternal_RejectsBadScheme(t *testing.T) {
assert.Error(t, err, "non-http schemes must be rejected")
_ = strings.TrimSpace(err.Error())
}
func TestIsPrivateIP_BlocksReservedRanges(t *testing.T) {
blocked := []string{
"0.0.0.0", // unspecified / routes to loopback on Linux
"0.0.0.1", // 0.0.0.0/8
"100.64.0.0", // CGNAT 100.64.0.0/10
"100.127.255.255", // CGNAT upper
"192.0.0.1", // 192.0.0.0/24 IETF protocol assignments
"::", // IPv6 unspecified ::/128
}
for _, s := range blocked {
ip := net.ParseIP(s)
require.NotNil(t, ip, "parse %s", s)
require.True(t, isPrivateIP(ip), "%s must be treated as private/blocked", s)
}
}
func TestIsPrivateIP_AllowsPublic(t *testing.T) {
pub := []string{"8.8.8.8", "1.1.1.1", "93.184.216.34", "2606:2800:220:1:248:1893:25c8:1946"}
for _, s := range pub {
ip := net.ParseIP(s)
require.NotNil(t, ip, "parse %s", s)
require.False(t, isPrivateIP(ip), "%s must be allowed (public)", s)
}
}
+1 -13
View File
@@ -85,19 +85,7 @@ func (t *WebFetchTool) Execute(ctx context.Context, input json.RawMessage) (tool
req.Header.Set(k, v)
}
client := &http.Client{
Timeout: fetchTimeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return fmt.Errorf("too many redirects (max 10)")
}
// Re-validate each redirect destination against SSRF blocklist
if err := ValidateURLNotInternal(req.URL.String()); err != nil {
return fmt.Errorf("redirect blocked: %w", err)
}
return nil
},
}
client := SafeHTTPClient(fetchTimeout)
resp, err := client.Do(req)
if err != nil {
+16
View File
@@ -0,0 +1,16 @@
package web
import (
"context"
"testing"
"github.com/stretchr/testify/require"
)
func TestWebFetch_BlocksPrivateHost(t *testing.T) {
tool := &WebFetchTool{}
res, err := tool.Execute(context.Background(),
[]byte(`{"url":"http://169.254.169.254/latest/meta-data/"}`))
require.NoError(t, err)
require.NotEmpty(t, res.Error, "private metadata IP must be rejected")
}
+8 -7
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"html"
"io"
"net/http"
"net/url"
@@ -14,6 +15,11 @@ import (
const searchTimeout = 15 * time.Second
// searchClient is the shared SSRF-safe HTTP client for all web_search
// backends. It pins the validated IP and re-validates redirects, bringing
// web_search to parity with web_fetch. (N4)
var searchClient = SafeHTTPClient(searchTimeout)
// WebSearchTool searches the web and returns results via a configurable
// backend. The default backend (when Backend is nil) scrapes DuckDuckGo's
// HTML interface — no API key required, but fragile to upstream HTML
@@ -131,7 +137,7 @@ func duckDuckGoSearch(ctx context.Context, query string, maxResults int) ([]sear
}
req.Header.Set("User-Agent", "harness/1.0 (Go agent framework)")
resp, err := http.DefaultClient.Do(req)
resp, err := searchClient.Do(req)
if err != nil {
return nil, err
}
@@ -266,11 +272,6 @@ func cleanHTMLText(s string) string {
}
}
result := out.String()
result = strings.ReplaceAll(result, "&amp;", "&")
result = strings.ReplaceAll(result, "&lt;", "<")
result = strings.ReplaceAll(result, "&gt;", ">")
result = strings.ReplaceAll(result, "&quot;", `"`)
result = strings.ReplaceAll(result, "&#x27;", "'")
result = strings.ReplaceAll(result, "&nbsp;", " ")
result = html.UnescapeString(result)
return strings.TrimSpace(result)
}
+7 -3
View File
@@ -17,6 +17,10 @@ import (
// are constructed with their config (API key, base URL, etc.) at
// registration time and remain immutable thereafter. This keeps the tool
// dispatch path zero-allocation in the hot loop.
//
// Implementations that make outbound HTTP calls MUST use the package
// searchClient (SafeHTTPClient) so a configured/typo'd internal base URL
// cannot be used for SSRF. (N4)
type WebSearchBackend interface {
Name() string
Search(ctx context.Context, query string, maxResults int) ([]searchResult, error)
@@ -58,7 +62,7 @@ func (b *braveBackend) Search(ctx context.Context, q string, n int) ([]searchRes
}
req.Header.Set("Accept", "application/json")
req.Header.Set("X-Subscription-Token", b.apiKey)
resp, err := http.DefaultClient.Do(req)
resp, err := searchClient.Do(req)
if err != nil {
return nil, err
}
@@ -119,7 +123,7 @@ func (b *tavilyBackend) Search(ctx context.Context, q string, n int) ([]searchRe
return nil, err
}
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
resp, err := searchClient.Do(req)
if err != nil {
return nil, err
}
@@ -169,7 +173,7 @@ func (b *searxngBackend) Search(ctx context.Context, q string, n int) ([]searchR
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
resp, err := searchClient.Do(req)
if err != nil {
return nil, err
}
+37
View File
@@ -0,0 +1,37 @@
package web
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func testCtx(t *testing.T) context.Context {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
t.Cleanup(cancel)
return ctx
}
func TestSearchClient_IsSafe(t *testing.T) {
require.NotNil(t, searchClient)
require.NotNil(t, searchClient.Transport)
require.NotNil(t, searchClient.CheckRedirect)
require.Equal(t, searchTimeout, searchClient.Timeout)
}
func TestSearxng_BlocksPrivateBaseURL(t *testing.T) {
b := newSearxngBackend("http://127.0.0.1:8080")
_, err := b.Search(testCtx(t), "hello", 3)
require.Error(t, err)
}
func TestCleanHTMLText_DecodesNumericEntities(t *testing.T) {
out := cleanHTMLText("<b>caf&#233;</b> &amp; t&#8217;is &nbsp;done")
require.Contains(t, out, "café")
require.Contains(t, out, "&", "amp must decode")
require.Contains(t, out, "t’is", "numeric entity must decode")
require.NotContains(t, out, "&#", "no raw numeric entities remain")
}