Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c2af8f389d | ||
|
|
c7acd5a30e | ||
|
|
d9580eee8f | ||
|
|
fd16dcefee | ||
|
|
53a7986fa0 | ||
|
|
7e394276da | ||
|
|
c884ef130a | ||
|
|
e9eea7c842 | ||
|
|
4877db85ae | ||
|
|
9381b2b661 | ||
|
|
d2491dc90f | ||
|
|
1acf0d48a3 | ||
|
|
0ca0fed9f7 | ||
|
|
cc0406d30c | ||
|
|
4df84b76d0 | ||
|
|
7e9801bf9c |
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
@@ -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,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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
+3
-3
@@ -501,8 +501,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 +542,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{}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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.`
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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 }
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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")
|
||||
)
|
||||
@@ -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)
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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."))
|
||||
}
|
||||
@@ -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")
|
||||
)
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
@@ -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")
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -453,7 +454,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 +474,7 @@ 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.UserDataDir(udd),
|
||||
)...,
|
||||
)
|
||||
taskCtx, taskCancel := chromedp.NewContext(allocCtx)
|
||||
@@ -474,11 +488,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
|
||||
}
|
||||
|
||||
@@ -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) {}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
+2
-2
@@ -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
|
||||
|
||||
Reference in new issue
Block a user