From fd16dcefee27297036d8b73a680c73f187bc22c2 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 9 May 2026 16:33:57 +0800 Subject: [PATCH] runtime: add Review interface (spec, result, sentinel, prompts) --- runtime/review.go | 119 ++++++++++++++++++++++++++++++++++++++ runtime/review_prompts.go | 68 ++++++++++++++++++++++ runtime/review_test.go | 49 ++++++++++++++++ 3 files changed, 236 insertions(+) create mode 100644 runtime/review.go create mode 100644 runtime/review_prompts.go create mode 100644 runtime/review_test.go diff --git a/runtime/review.go b/runtime/review.go new file mode 100644 index 0000000..9921e66 --- /dev/null +++ b/runtime/review.go @@ -0,0 +1,119 @@ +// 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. +package runtime + +import ( + "context" + "errors" + "time" + + "github.com/sausheong/harness/llm" + "github.com/sausheong/harness/tool" +) + +// 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 is a stub that later tasks fill in. +func Review(ctx context.Context, parent *Runtime, spec ReviewSpec) ReviewResult { + return ReviewResult{Err: errors.New("not implemented")} +} diff --git a/runtime/review_prompts.go b/runtime/review_prompts.go new file mode 100644 index 0000000..4189157 --- /dev/null +++ b/runtime/review_prompts.go @@ -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.` diff --git a/runtime/review_test.go b/runtime/review_test.go new file mode 100644 index 0000000..655c16d --- /dev/null +++ b/runtime/review_test.go @@ -0,0 +1,49 @@ +package runtime + +import ( + "errors" + "testing" + "time" + + "github.com/sausheong/harness/tool" + "github.com/stretchr/testify/assert" +) + +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") + } +}