harvey

package module
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 30, 2026 License: AGPL-3.0-or-later Imports: 47 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Harvey

Harvey, a six foot six invisible rabbit

Harvey is an agent REPL. It is written in Go and designed to use Ollama server to access language models. These can be run locally or remotely since Harvey uses Ollama's web service as the integration point. Harvey is a terminal based application. It will run on Raspberry Pi OS (Raspberry Pi 5 hardware), Linux (arm64 and amd64), Windows (arm64, amd64) and macOS (M1 and above). It is designed to specifically run on a Raspberry Pi 500+ computer.

Features

  • integrated knowledge base
  • support for SKILL.md (and extending Harvey by using "compiled" SKILL.md files)
  • knowledge base with RAG support
  • includes an innovative session file format based on Fountain screenplay markup. Session files are both human readable (like reading a screenplay) and machine consumable
  • friendly with other data processing tools and through shared skills with other coding agents

The name Harvey is inspired by the Mary Chase play of the same name. My little agent runs on small computers but is available to those who choose to see its value. Harvey in the play was a Púca, a mythic Celtic spirit who at times was prone to mischief. The Púca chose who could see it but even then the person doing the seeing had to be willing to see it too.

Motivation (Spring 2026)

I think the current AI hype cycle will likely end with a bang and a crash. Since I started working on Harvey we've already seen the token expenses sky rocket. Many flat rate plans ration tokens. Of course if you opt to pay by tokens those services have every reason to encourage more token consumption. That leads me to believe that things will not get cheaper. Add to that the investor's interest in aggressive cost recovery and we have a looming problem. There is now digital divide of resource availability based on wealth.

Where does this leave us? The commercial platforms are just too expensive. There are problematic downsides in additional to costs (example energy consumption, model biases and data privacy issues). We need off ramps. I think one off ramp is bringing the models back in house. The trouble is that model development has been running on an assumption about ever expanding compute resources. That's not sustainable. It doesn't match the reality today where memory pricing has gone through the ceiling and other computing components are rising too. The external GPUs relied on by medium and larger models have never been affordable. Time to change course. Time to revisit small models and get efficient.

Harvey is an exploration of what is possible when we bring models home. This is about local control of the model system and running models on hardware that doesn't have a GPU. Harvey enables me to get useful work done with small models run via Ollama on my Raspberry Pi 500+ desktop. The Pi is a relatively low cost, low power machine. It is enough to run small models. If you have more horse power available Harvey will not mind or stand in your way.

Where I think things are going

I see language models on a continuum like computers. In the beginning computers were large and unaffordable except by governments and the largest of corporations. They took up floors of buildings for a single machine. Eventually they became much smaller and much cheaper. Right now Large Language models are like the huge mainframes of the 1950s and 1960s. Everyone is still thinking in terms of building sized computers. The seeds for a different approach already exist. Ollama is only one example of that. I think real innovation can happen with small models that focus on specific domains and tuned to specific application needs. We've built extremely large general purpose models in part because of a collective desire to see how far we could take these concepts. I think their is a plateau in creating ever larger models. Time to take a step back and see how small models can be while being really helpful. To move things forward I believe we will need a personal sized model. I think this could open interesting doors much as personal computing opened the door to what we have today. I think the pieces are there. They just need to be assembled in a simpler configuration. (2026-05, RSD)

Open Models, Small Models combined with generalized REPLs

The language model system space has enough maturity that we can pick the features that matter and ignore much of the initial growing pains. There is an opportunity ripe for creating tooling around fitness of use and purpose. The current crop of model systems (May 2026) layout base line features which are straight forward to implement. Coding agents are centered around concepts like sessions, skills, knowledge bases and retrieval augmented generation (RAG). There are plenty of papers and blog posts that describe these features, how they work and how to use them and importantly how to build them.

The SKILL.md is a good example. It was proposed by Anthropic and adopted by others (example Mistral Vibe, OpenClaw). It is also pretty easy to implement using Ollama server. The concept of RAG was easy to implement. Some trends like MCP strike me as a way to run up token usage. I remain on the fence about it's usefulness. Pick the proven trends that favor limited resource availability and implement them is the approach I'm taking with Harvey. Harvey isn't being developed in a vacuum. Mozilla AI is working on implementing a way to unify many implementation elements. An example is their any-llm project. Ollama project. Harvey can take advantage of that too. This approach let's me evolve Harvey as a small project while allowing me to explore the domain of small model computing on small computers. That's how Harvey started.

Wait, wait, why Harvey? You should use OpenClaw!

OpenClaw is interesting but it is very easy to mis-configure. I wasn't comfortable with that myself. I felt like OpenClaw opened my computing environment up to a whole lot of hurt. I don't want agents running around my personal communication. I don't want them messing with my editor. I want my code agent to stick to a project directory. I want it focused on what I am working on. I want a safe tool as convenient as Claude Code, GitHub CoPilot or Mistral Vibe. It should be transparent in how in works. It should document what it does. It should let me work with the models I chose for a specific task. It should be human scale and not put tentacles into everything else. I am working with language models on my local machine and my private network. Harvey should let me be able to easily direct appropriate material to a remote service while keeping everything else local so I can continue the processing with models in my local workspace. Harvey came about because I didn't see other applications approaching model systems this way. Safety and locality first.

Security Note

I have attempted to keep safety and locality as top priorities as I've designed and implement the Harvey prototype. Harvey avoids secrets. How Harvey is configured and it's operating data is visible to me as a human. There is risk in using language model agents because you are allowing a probabilistic text model to direct the execution of commands. It is an attack surface ripe for mischief even with mitigating efforts. While I've tried to minimize the risk. I believe the risk will always be non-zero. I use language models in the security reviews I conduct with each round of development. Typically models from different providers. I use them in an effort to both identify and mitigate the worst safety issues. Again, I think there will always a risks. As a result I have deliberately limited what Harvey can do in both where it can operate and the built-in tools. In spite of this you should keep in mind that Harvey is experimental. Harvey is only a working proof of concept. You should NOT consider it complete or production ready. Don't use Harvey where the risks might endanger your data, people or planet. See SECURITY.md for more details.

What is a model? What is infrastructure?

Commercial SaaS language model services need to keep you engaged. They've done a good job of building up the human user interface. The conversations use technique that seem similar to the BITE cult recruitment methodology described by Steven Hassan over the last many decades. When you step back and look at actual implementations the ecosystems like those of OpenAI, Anthropic and others are not just the latest frontier model they include considerable effort in implementing the human user interface to keep engagement up. The frontier models are important but their not mysterious when you look at how everything is wrapped up traditional web services. They've baked in the engagement business model. This is true weather they used a language model to generate the code or not. It's telling. The model is important but the user interface and the infrastructure under it is important too. The engagement wrappings are make the contact with us humans. It's important to keep that in mind.

On a small scale we can build our own language model system. Like the SaaS services we can take advantage of traditional software programs and methods too. That is the core of Harvey. It's just a REPL that is designed to use modeling services through web protocols. Unlike the SaaS offerings it under our control running on our hardware. It takes advantage of our limit resources and single user orientation. Harvey does less so what would be done in parallel by a SaaS service is done sequentially in Harvey. There is an opportunity on a locally run language model system to scale down instead of up.

What's next

I believe useful small open models are hear today. The trick will be is identifying those the models that are mature enough to use day in and day out safely. In the hype that focuses on bigger and more generalized the small specialized models seem undervalued. We can leverage the value if it is easily to run them locally. This is true especially if there are some key additional features like good session management, knowledge bases and RAG. Harvey shows we can have some of those bells and whistles while running on small affordable hardware. Hardware that doesn't require new data centers and power plants to be built. I think smaller models, ones that can run at the edge will be the ones that carry weight in the long wrong. To explore the idea of small models on small computers I dreamed up Harvey. We'll have to wait to see where that adventure could leads.

Release Notes

  • version: 0.0.5
  • status: working proof of concept
Authors
  • Doiel, R. S.

Software Requirements

  • Go >= 1.26.2
Software Suggestions

For building Harvey and documentation from source.

  • CMTools >= 0.0.45
  • Pandoc >= 3.9
  • GNU Make >= 3.8

Documentation

Overview

Package harvey — skill_set.go implements the /skill-set command, which lets the user load, inspect, and manage named YAML bundles of skills stored in agents/skill-sets/.

Index

Constants

View Source
const (
	PermRead   = "read"
	PermWrite  = "write"
	PermExec   = "exec"
	PermDelete = "delete"
)

Permission types

View Source
const (
	// Version number of release
	Version = "0.0.6"

	// ReleaseDate, the date version.go was generated
	ReleaseDate = "2026-05-30"

	// ReleaseHash, the Git hash when version.go was generated
	ReleaseHash = "88504ea"
	LicenseText = `` /* 724-byte string literal not displayed */

)
View Source
const DefaultAuditBufferCapacity = 1000

DefaultAuditBufferCapacity is the default size of the audit ring buffer.

View Source
const RecentContextN = 10

RecentContextN is the number of recent non-system history messages sent alongside a dispatched prompt. Excludes system messages. Tune over time.

Variables

View Source
var (
	// SkillsHelpText explains the Agent Skills feature and is displayed by
	// /help skills (REPL) or harvey --help skills (CLI).
	SkillsHelpText = `` /* 5043-byte string literal not displayed */

	RoutingHelpText = `%{app_name}(7) user manual | version {version} {release_hash}
% R. S. Doiel
% {release_date}

# NAME

ROUTING

# SYNOPSIS

/route <add NAME URL [MODEL]|rm NAME|models URL|probe NAME|set NAME tools on|off|list|on|off|status>

@name prompt text

# DESCRIPTION

Harvey can dispatch individual prompts to remote LLM endpoints — other Ollama
instances on a Pi cluster, Llamafile servers, or cloud providers — using
@mention syntax. Prefix any prompt with @name to send it to the named endpoint instead
of the local model. The reply is streamed back and lands in the local
conversation history so future turns retain full context.

Routing is explicitly user-driven: there is no automatic classification.
You choose which endpoint handles each prompt by using (or omitting) an
@mention.

# CONTEXT WINDOW

When a prompt is dispatched to a remote endpoint, Harvey sends the last
10 non-system messages from the local history alongside it. System messages
are excluded. This gives the remote model enough context to be useful without
sending the entire conversation over the network. The window size is a
starting point and will be tuned over time.

# ENDPOINT TYPES

Local providers (no API key):

  ollama://host:port    A remote Ollama server (also accepts http:// and https://).
  llamafile://host:port A Llamafile binary server (OpenAI-compatible, port 8080).
  llamacpp://host:port  A llama.cpp server (OpenAI-compatible, port 8080).

Cloud providers (API key read from environment):

  anthropic://  Anthropic Claude  (ANTHROPIC_API_KEY)
  deepseek://   DeepSeek          (DEEPSEEK_API_KEY)
  gemini://     Google Gemini     (GEMINI_API_KEY or GOOGLE_API_KEY)
  mistral://    Mistral           (MISTRAL_API_KEY)
  openai://     OpenAI            (OPENAI_API_KEY)

# EXAMPLE SESSION

~~~
  # Register a Pi cluster node
  /route add pi2 ollama://192.168.1.12:11434 llama3.1:8b

  # Register the Anthropic cloud endpoint
  /route add claude anthropic:// claude-sonnet-4-20250514

  # Enable routing
  /route on

  # Dispatch a complex task to the cloud
  @claude refactor this module to use the repository pattern

  # Run a quick task on a Pi node
  @pi2 write a unit test for the Parse function

  # Local model handles everything else (no @mention)
  what does this error mean?
~~~

# SLASH COMMANDS

~~~
  /route add NAME URL [MODEL]        register a remote endpoint
                                       @pi2    ollama://192.168.1.12:11434 llama3.1:8b
                                       @claude anthropic:// claude-sonnet-4-20250514
  /route rm NAME                     remove a registered endpoint
  /route models URL                  list models available at a provider URL
                                       useful before /route add to choose a model
  /route probe NAME                  show reachability, model, and tool-call capability
                                       for a registered endpoint
  /route set NAME tools on|off       toggle tool calling for a registered endpoint
                                       (only for providers that support tool use)
  /route list                        show all endpoints with reachability status
  /route on                          enable @mention dispatch (persisted)
  /route off                         disable @mention dispatch (persisted)
  /route status                      show routing state and endpoint count
~~~

Registered endpoints and the on/off state persist across sessions in
` + "`" + `<workspace>/agents/routes.json.` + "`" + `

`

	OllamaHelpText = `` /* 3077-byte string literal not displayed */

	ClearHelpText = `` /* 1527-byte string literal not displayed */

	EditingHelpText = `` /* 1777-byte string literal not displayed */

	SessionHelpText = `` /* 2376-byte string literal not displayed */

	ContextHelpText = `` /* 1994-byte string literal not displayed */

	KBHelpText = `` /* 3672-byte string literal not displayed */

	RecordHelpText = `` /* 1679-byte string literal not displayed */

	RagHelpText = `` /* 8220-byte string literal not displayed */

	RenameHelpText = `` /* 957-byte string literal not displayed */

	FileTreeHelpText = `` /* 857-byte string literal not displayed */

	ReadDirHelpText = `` /* 1587-byte string literal not displayed */

	SkillSetHelpText = `` /* 1912-byte string literal not displayed */

	StatusHelpText = `` /* 2192-byte string literal not displayed */

	FilesHelpText = `` /* 1064-byte string literal not displayed */

	ReadHelpText = `` /* 1792-byte string literal not displayed */

	AttachHelpText = `` /* 2411-byte string literal not displayed */

	ReadPDFHelpText = `` /* 2203-byte string literal not displayed */

	WriteHelpText = `` /* 1323-byte string literal not displayed */

	RunHelpText = `` /* 1670-byte string literal not displayed */

	SearchHelpText = `` /* 1315-byte string literal not displayed */

	GitHelpText = `` /* 1534-byte string literal not displayed */

	SummarizeHelpText = `` /* 1813-byte string literal not displayed */

	MemoryHelpText = `` /* 4479-byte string literal not displayed */

	PipelineHelpText = `` /* 2498-byte string literal not displayed */

	InspectHelpText = `` /* 1375-byte string literal not displayed */

	SecurityHelpText = `` /* 2852-byte string literal not displayed */

	HelpText = `` /* 7402-byte string literal not displayed */

)

AllPermissions is a slice of all valid permission types.

View Source
var DefaultAllowedCommands = []string{
	"ls", "cat", "grep", "head", "tail", "wc",
	"find", "stat", "jq", "htmlq", "bat", "batcat",
}

* DefaultConfig returns a Config populated with sensible defaults. WorkDir

  • defaults to "." (the process working directory at startup). AutoRecord
  • defaults to true so every session is saved to agents/sessions/. *
  • Returns:
  • *Config — configuration with default values pre-filled. *
  • Example:
  • cfg := DefaultConfig()
  • fmt.Println(cfg.OllamaURL) // "http://localhost:11434"

DefaultAllowedCommands is the default list of commands allowed when SafeMode is enabled. These are considered safe read-only or low-risk utilities.

View Source
var ErrToolLoopExceeded = errors.New("tool loop limit exceeded")

ErrToolLoopExceeded is returned by RunToolLoop when the LLM exceeds the per-turn tool call iteration limit without producing a plain text response.

View Source
var LearMessages = []string{}/* 449 elements not displayed */

learMessages are whimsical waiting messages in the style of Edward Lear's Book of Nonsense, displayed while the Harvey or the LLM is thinking.

ValidMemoryTypes lists the accepted values for MemoryMeta.Type.

View Source
var ValidObservationKinds = []string{"note", "finding", "decision", "question", "hypothesis"}

ValidObservationKinds lists the accepted values for Observation.Kind.

Functions

func AuditLog

func AuditLog(event AuditEvent)

AuditLog logs an audit event to the global buffer if initialized.

func BuildFountainBody added in v0.0.6

func BuildFountainBody(timestamp string, turns [][2]string) string

* BuildFountainBody constructs a minimal valid Fountain body for a memory

  • document. The scene heading uses the INT. MEMORY convention with the
  • provided timestamp. *
  • Parameters:
  • timestamp (string) — ISO-style timestamp, e.g. "2026-05-25 12:00:00".
  • turns ([][2]string) — sequence of [character, dialogue] pairs. *
  • Returns:
  • string — the complete Fountain body from FADE IN: to THE END. *
  • Example:
  • body := BuildFountainBody("2026-05-25 12:00:00", [][2]string{
  • {"RSDOIEL", "I got: fatal: not a git repository"},
  • {"HARVEY", "Running git init to initialize the repository."},
  • {"RSDOIEL", "That fixed it."},
  • })

func CatalogSystemPromptBlock

func CatalogSystemPromptBlock(cat SkillCatalog) string

* CatalogSystemPromptBlock returns the XML catalog block and load

  • instructions to append to Harvey's system prompt. Returns an empty string
  • when cat is empty so callers need not special-case the no-skills case. *
  • Parameters:
  • cat (SkillCatalog) — skills to include; may be nil or empty. *
  • Returns:
  • string — system-prompt fragment; "" if no skills. *
  • Example:
  • block := CatalogSystemPromptBlock(cat)
  • if block != "" {
  • agent.AddMessage("system", block)
  • }

func CompileSkill

func CompileSkill(ctx context.Context, client LLMClient, skill *SkillMeta, out io.Writer) error

* CompileSkill sends the skill body to the LLM with a meta-prompt that instructs

  • it to produce compiled.bash and compiled.ps1 scripts. The generated scripts are
  • written to the skill's scripts/ directory, which is created if absent. *
  • If the LLM response does not contain both expected code blocks, an error is
  • returned and no files are written. *
  • Parameters:
  • ctx (context.Context) — for LLM call cancellation.
  • client (LLMClient) — the connected LLM backend.
  • skill (*SkillMeta) — skill to compile; skill.Path and skill.Body must be set.
  • out (io.Writer) — receives streamed LLM output during generation. *
  • Returns:
  • error — on LLM failure, missing code blocks, or file write failure. *
  • Example:
  • err := CompileSkill(ctx, agent.Client, skill, os.Stdout)
  • if err != nil { log.Fatal(err) }

func CompiledBashPath

func CompiledBashPath(skillPath string) string

* CompiledBashPath returns the absolute path to the compiled bash script

  • for the skill whose SKILL.md lives at skillPath. *
  • Parameters:
  • skillPath (string) — absolute path to a SKILL.md file. *
  • Returns:
  • string — absolute path to scripts/compiled.bash sibling. *
  • Example:
  • p := CompiledBashPath("/proj/agents/skills/my-skill/SKILL.md")
  • // returns "/proj/agents/skills/my-skill/scripts/compiled.bash"

func CompiledPS1Path

func CompiledPS1Path(skillPath string) string

* CompiledPS1Path returns the absolute path to the compiled PowerShell script

  • for the skill whose SKILL.md lives at skillPath. *
  • Parameters:
  • skillPath (string) — absolute path to a SKILL.md file. *
  • Returns:
  • string — absolute path to scripts/compiled.ps1 sibling. *
  • Example:
  • p := CompiledPS1Path("/proj/agents/skills/my-skill/SKILL.md")
  • // returns "/proj/agents/skills/my-skill/scripts/compiled.ps1"

func CompressHistory added in v0.0.6

func CompressHistory(a *Agent, keepTurns int, out io.Writer) error

* CompressHistory replaces all but the last keepTurns conversation turns with

  • a single synthetic summary message produced by the current LLM. The system
  • prompt (if present) is preserved at the front. The compression call is not
  • recorded in the session file; existing recording entries are unaffected. *
  • Parameters:
  • a (*Agent) — the Harvey agent whose History is compressed.
  • keepTurns (int) — number of recent turns to keep verbatim.
  • out (io.Writer) — status output (unused in current implementation;
  • callers print the warning line before calling). *
  • Returns:
  • error — if the LLM summarisation call fails. *
  • Example:
  • if ShouldCompress(tokens, limit, 0.80) {
  • fmt.Fprintln(out, "[context ~82% full — compressing older turns]")
  • CompressHistory(agent, 6, out)
  • }

func CountTokens

func CountTokens(ctx context.Context, baseURL, model, text string) (count int, exact bool)

* CountTokens estimates the number of tokens in text for the named model.

  • It first tries the Ollama /api/tokenize endpoint; if that is unavailable
  • or fails, it falls back to a character-based heuristic (len(text)/4). *
  • Parameters:
  • ctx (context.Context) — controls the HTTP request lifetime.
  • baseURL (string) — Ollama server base URL.
  • model (string) — model name (sent with the tokenize request).
  • text (string) — text to count. *
  • Returns:
  • count (int) — number of tokens.
  • exact (bool) — true when the count came from Ollama, false for the heuristic. *
  • Example:
  • n, exact := CountTokens(ctx, "http://localhost:11434", "llama3", prompt)
  • fmt.Printf("%d tokens (exact=%v)\n", n, exact)

func DefaultSessionPath

func DefaultSessionPath(dir string) string

DefaultSessionPath returns a timestamped default filename for a session script in the given directory, using the .spmd extension.

Parameters:

dir (string) — directory in which to place the file.

Returns:

string — path of the form "<dir>/harvey-session-YYYYMMDD-HHMMSS.spmd".

Example:

path := DefaultSessionPath("/home/user/project/agents/sessions")
// "/home/user/project/agents/sessions/harvey-session-20260415-142300.spmd"

func DispatchSkill

func DispatchSkill(ctx context.Context, a *Agent, skill *SkillMeta, prompt string, reader *bufio.Reader, out io.Writer) error

* DispatchSkill handles the full lifecycle when a skill is triggered:

  • checks for compiled scripts, handles staleness prompts, offers compilation,
  • and either runs the compiled script or falls back to LLM loading. *
  • Dispatch states:
  • 1. No compiled scripts → offer to compile; if declined fall back to LLM.
  • 2. Scripts exist but SKILL.md is newer → offer to recompile; then run.
  • 3. Scripts exist and up to date → run directly. *
  • Parameters:
  • ctx (context.Context) — for LLM calls if compilation is needed.
  • a (*Agent) — the running agent (client, workspace, history).
  • skill (*SkillMeta) — the skill to dispatch.
  • prompt (string) — the user's triggering prompt text (HARVEY_PROMPT).
  • reader (*bufio.Reader) — reads Y/n confirmations from the user.
  • out (io.Writer) — destination for status messages and script output. *
  • Returns:
  • error — on unexpected I/O or execution failure; non-zero script exit is reported but not returned. *
  • Example:
  • err := DispatchSkill(ctx, agent, skill, input, reader, os.Stdout)

func DispatchToEndpoint

func DispatchToEndpoint(ctx context.Context, ep *RouteEndpoint, history []Message, prompt string, cfg *Config, registry *ToolRegistry, out io.Writer) (string, error)

* DispatchToEndpoint sends the recent conversation context plus prompt to ep,

  • streams the reply to out, and returns the full reply text. The context window
  • is capped at RecentContextN non-system messages from history. *
  • When ep.Tools is true and registry is non-nil, the call goes through
  • ToolExecutor so the remote model can invoke Harvey's local tools. Harvey's
  • existing permission constraints (safe_mode, allowed_commands, permissions)
  • are enforced by the registry — the remote model cannot bypass them. *
  • Parameters:
  • ctx (context.Context) — controls the HTTP request lifetime.
  • ep (*RouteEndpoint) — registered endpoint to send to.
  • history ([]Message) — full local conversation history.
  • prompt (string) — current user prompt (already stripped of @mention).
  • cfg (*Config) — used to resolve model defaults and tool limits.
  • registry (*ToolRegistry) — Harvey's tool registry; nil disables tool calling.
  • out (io.Writer) — destination for streamed reply tokens. *
  • Returns:
  • reply (string) — full reply text.
  • err (error) — non-nil on transport or API failure. *
  • Example:
  • reply, err := DispatchToEndpoint(ctx, ep, agent.History, "write a parser", cfg, agent.Tools, os.Stdout)

func ExpandDynamicSections

func ExpandDynamicSections(content string, ws *Workspace) string

* ExpandDynamicSections replaces marker comments in content with live

  • workspace data. Supported markers: *
  • <!-- @date --> current date (YYYY-MM-DD)
  • <!-- @files --> workspace file tree, skipping hidden directories
  • <!-- @git-status --> output of "git status --short" in the workspace root *
  • If ws is nil the content is returned unchanged. *
  • Parameters:
  • content (string) — text to expand (typically HARVEY.md contents).
  • ws (*Workspace) — workspace used to resolve files and run git. *
  • Returns:
  • string — content with all recognised markers replaced. *
  • Example:
  • expanded := ExpandDynamicSections(raw, ws)
  • agent.AddMessage("system", expanded)

func ExtractModelFromSession

func ExtractModelFromSession(path string) (string, error)

* ExtractModelFromSession parses a .spmd or .fountain session file and

  • returns the model name recorded as a CHARACTER element. Returns an empty
  • string when no model character can be identified. *
  • Parameters:
  • path (string) — path to a Harvey session file (.spmd or .fountain). *
  • Returns:
  • string — ALL-CAPS model name (e.g. "GEMMA4"), or "" if not found.
  • error — on parse failure. *
  • Example:
  • model, err := ExtractModelFromSession("agents/sessions/session.spmd")
  • // model == "GEMMA4"

func FmtHelp

func FmtHelp(src string, appName string, version string, releaseDate string, releaseHash string) string

FmtHelp lets you process a text block with simple curly brace markup.

func FormatContext added in v0.0.6

func FormatContext(results []UnifiedResult) string

* FormatContext formats a slice of UnifiedResults into a context injection

  • string grouped by source silo. Returns an empty string when results is empty. *
  • Parameters:
  • results ([]UnifiedResult) — results from Recall. *
  • Returns:
  • string — formatted context block ready to inject as a user message;
  • empty string when results is empty. *
  • Example:
  • block := FormatContext(results)
  • if block != "" { agent.AddMessage("user", block) }

func GenerateMemoryID added in v0.0.6

func GenerateMemoryID(t MemoryType) string

* GenerateMemoryID returns a new unique memory ID for the given type.

  • The format is {type}_{6-hex-suffix} where the suffix is derived from
  • the current nanosecond timestamp. *
  • Parameters:
  • t (MemoryType) — the memory type used as a prefix. *
  • Returns:
  • string — a new unique ID, e.g. "tool_use_a3f891". *
  • Example:
  • id := GenerateMemoryID(MemoryTypeToolUse) // "tool_use_a3f891"

func HistoryText

func HistoryText(messages []Message) string

* HistoryText concatenates every message's content with a newline separator.

  • Used to produce a single string for token-count estimation over the full
  • conversation history. *
  • Parameters:
  • messages ([]Message) — conversation history. *
  • Returns:
  • string — all message bodies joined by newlines. *
  • Example:
  • text := HistoryText(agent.History)
  • n, _ := CountTokens(ctx, baseURL, model, text)

func IsStale

func IsStale(skill *SkillMeta) (stale bool, err error)

* IsStale reports whether SKILL.md is newer than the compiled scripts,

  • meaning the scripts need recompilation. *
  • Returns (true, nil) when either compiled script does not exist or when
  • SKILL.md has a later modification time than either script.
  • Returns (false, nil) when both scripts exist and are at least as new as SKILL.md.
  • Returns (false, error) when SKILL.md itself cannot be stat'd. *
  • Parameters:
  • skill (*SkillMeta) — skill to check; skill.Path must be set. *
  • Returns:
  • stale (bool) — true when recompilation is needed.
  • err (error) — non-nil only when SKILL.md itself is unreadable. *
  • Example:
  • stale, err := IsStale(skill)
  • if err != nil { log.Fatal(err) }
  • if stale { fmt.Println("needs recompile") }

func LlamacppAPIURL

func LlamacppAPIURL(u string) string

LlamacppAPIURL converts a "llamacpp://host:port" URL to "http://host:port/v1".

func LlamafileAPIURL

func LlamafileAPIURL(u string) string

LlamafileAPIURL converts a "llamafile://host:port" URL to the form "http://host:port/v1" expected by the any-llm-go llamafile provider. Already well-formed http(s):// URLs are left unchanged.

func LlamafileHealthURL

func LlamafileHealthURL(u string) string

LlamafileHealthURL returns the base URL (without /v1) suitable for health probing a llamafile or llama.cpp server.

func LoadHarveyMD

func LoadHarveyMD() string

* LoadHarveyMD reads HARVEY.md from the current directory and returns the

  • agent preamble followed by the file contents. The preamble is always
  • included so the LLM knows it must use slash commands for real side-effects
  • rather than narrating fake output. Returns only the preamble when HARVEY.md
  • does not exist. *
  • Returns:
  • string — agentPreamble + HARVEY.md contents (or agentPreamble alone). *
  • Example:
  • prompt := LoadHarveyMD()
  • cfg.SystemPrompt = prompt

func LoadHarveyYAML

func LoadHarveyYAML(ws *Workspace, cfg *Config) error

* LoadHarveyYAML reads agents/harvey.yaml from ws and applies any overrides

  • to cfg. Missing fields are left unchanged. The file is optional — its
  • absence is silently ignored. *
  • Parameters:
  • ws (*Workspace) — workspace whose agents/ directory is searched.
  • cfg (*Config) — config to update in place. *
  • Returns:
  • error — only on YAML parse failure; a missing file returns nil. *
  • Example:
  • if err := LoadHarveyYAML(ws, cfg); err != nil {
  • log.Fatal(err)
  • }

func LoadRouteConfig

func LoadRouteConfig(ws *Workspace, cfg *Config)

* LoadRouteConfig reads agents/routes.json from the workspace and populates

  • cfg.Routes and cfg.RoutingEnabled. Silently no-ops when the file does not
  • exist or cannot be parsed, leaving cfg unchanged. *
  • Parameters:
  • ws (*Workspace) — workspace whose agents/ directory is searched.
  • cfg (*Config) — config to populate; modified in place. *
  • Example:
  • cfg := DefaultConfig()
  • LoadRouteConfig(ws, cfg)

func LogAudit

func LogAudit(action AuditAction, details string, status AuditStatus)

LogAudit is a convenience function for logging audit events.

func LooksLikeSkillQuery

func LooksLikeSkillQuery(s string) bool

* LooksLikeSkillQuery reports whether the user's input looks like a natural-

  • language question about available skills so the REPL can intercept it and
  • answer directly from the catalog rather than passing it to the LLM. *
  • Parameters:
  • s (string) — the raw user input. *
  • Returns:
  • bool — true when the input matches a known skill-query pattern. *
  • Example:
  • if LooksLikeSkillQuery("what skills do you know?") {
  • cmdSkill(a, []string{"list"}, out)
  • }

func MatchesTrigger

func MatchesTrigger(skill *SkillMeta, prompt string) bool

* MatchesTrigger reports whether prompt matches the trigger pattern stored in

  • skill.Trigger. Returns false when skill.Trigger is empty. *
  • Two trigger modes are supported:
  • Regexp mode — trigger value is wrapped in slashes: /pattern/
  • Matched case-insensitively via (?i).
  • Keyword mode — trigger value is a whitespace-separated list of words.
  • Any single word present in the lowercased prompt triggers. *
  • A malformed regexp returns false rather than panicking. *
  • Parameters:
  • skill (*SkillMeta) — skill with optional Trigger field.
  • prompt (string) — raw user input to match against. *
  • Returns:
  • bool — true when prompt matches the trigger. *
  • Example:
  • skill.Trigger = "pdf extract"
  • MatchesTrigger(skill, "please extract the pdf") // true

func NeedsOnboarding added in v0.0.6

func NeedsOnboarding(store *MemoryStore) bool

* NeedsOnboarding reports whether the workspace has no workspace_profile

  • memory documents. When true, RunOnboarding should be called before the
  • REPL starts. *
  • Parameters:
  • store (*MemoryStore) — the open memory store for the workspace. *
  • Returns:
  • bool — true when workspace_profile/ contains no .fountain files. *
  • Example:
  • if NeedsOnboarding(store) {
  • RunOnboarding(a, store, embedder, os.Stdout, os.Stdin)
  • }

func ParseAtMention

func ParseAtMention(input string) (name, prompt string, ok bool)

* ParseAtMention extracts the @name prefix and remaining prompt from input.

  • Returns ok=false when input does not start with "@" followed by a non-empty
  • word. Leading and trailing whitespace is trimmed before parsing. *
  • Parameters:
  • input (string) — raw user input, potentially starting with "@name ". *
  • Returns:
  • name (string) — endpoint name without the "@" sigil.
  • prompt (string) — remaining input after the @name token; may be empty.
  • ok (bool) — false when no @mention is present. *
  • Example:
  • name, prompt, ok := ParseAtMention("@pi2 write a Go parser")
  • // name="pi2", prompt="write a Go parser", ok=true *
  • _, _, ok = ParseAtMention("just a normal prompt")
  • // ok=false

func ParseEmbedderFlags

func ParseEmbedderFlags(args []string) (kind, url string)

* ParseEmbedderFlags extracts --embedder and --embedder-url values from args.

  • Unrecognised tokens are silently ignored. Both values default to "". *
  • Parameters:
  • args ([]string) — remaining arguments after the store name. *
  • Returns:
  • kind (string) — embedder kind: "ollama", "encoderfile", or "".
  • url (string) — embedder base URL, or "". *
  • Example:
  • kind, url := ParseEmbedderFlags([]string{"--embedder", "encoderfile", "--embedder-url", "http://localhost:8080"})

func ParseProseToolCalls added in v0.0.6

func ParseProseToolCalls(blocks []CodeBlock) []anyllm.ToolCall

ParseProseToolCalls converts tool-call code blocks into anyllm.ToolCall values. It handles both qwen2.5 ("arguments") and llama3.2 ("parameters") key names. Blocks that do not parse as tool calls are silently skipped.

func PrintOllamaEnv

func PrintOllamaEnv(out io.Writer)

* PrintOllamaEnv writes the currently active Ollama environment variables to

  • out, skipping any that are not set. It never modifies the environment. *
  • Parameters:
  • out (io.Writer) — destination for the variable listing. *
  • Example:
  • PrintOllamaEnv(os.Stdout)

func ProbeEncoderfile

func ProbeEncoderfile(baseURL string) bool

* ProbeEncoderfile returns true if an Encoderfile server is reachable at

  • baseURL by calling GET /health. *
  • Parameters:
  • baseURL (string) — Encoderfile HTTP base URL, e.g. "http://localhost:8080". *
  • Returns:
  • bool — true when the server responds with HTTP 200. *
  • Example:
  • if ProbeEncoderfile("http://localhost:8080") {
  • fmt.Println("Encoderfile is running")
  • }

func ProbeEncoderfileModel

func ProbeEncoderfileModel(baseURL string) (string, error)

* ProbeEncoderfileModel queries the Encoderfile server's GET /model endpoint

  • and returns the model_id. Returns an error if the server is unreachable or
  • returns an unexpected response. *
  • Parameters:
  • baseURL (string) — Encoderfile HTTP base URL. *
  • Returns:
  • string — model_id from the server, e.g. "nomic-embed-text-v1_5".
  • error — on transport failure, non-200 status, or missing model_id. *
  • Example:
  • id, err := ProbeEncoderfileModel("http://localhost:8080")
  • fmt.Println(id) // "nomic-embed-text-v1_5"

func ProbeOllama

func ProbeOllama(baseURL string) bool

ProbeOllama returns true if an Ollama server is reachable at baseURL.

func RegisterBuiltinTools

func RegisterBuiltinTools(r *ToolRegistry, a *Agent)

* RegisterBuiltinTools registers all of Harvey's built-in schema-based tools

  • with the given registry. Every handler enforces the workspace boundary,
  • agent permission checks, safe-type assertions, and the output size cap. *
  • Parameters:
  • r (*ToolRegistry) — registry to populate.
  • a (*Agent) — agent providing workspace, config, and permissions. *
  • Example:
  • RegisterBuiltinTools(agent.Tools, agent)

func ResolveSessionsDir

func ResolveSessionsDir(ws *Workspace, customPath string) (string, error)

* ResolveSessionsDir returns the absolute path to the sessions directory,

  • creating it if it does not exist. customPath overrides the default location
  • (agents/sessions/ inside the workspace); pass an empty string for the default. *
  • Parameters:
  • ws (*Workspace) — the Harvey workspace.
  • customPath (string) — override path; may be relative (to workspace root) or absolute. *
  • Returns:
  • string — absolute path to the sessions directory.
  • error — if the directory cannot be created. *
  • Example:
  • dir, err := ResolveSessionsDir(ws, cfg.SessionsDir)

func RunOnboarding added in v0.0.6

func RunOnboarding(a *Agent, store *MemoryStore, embedder Embedder, out io.Writer, in io.Reader) error

* RunOnboarding prompts the user for workspace identity and project facts,

  • then writes a workspace_profile memory and, when detectable, a project_fact
  • memory. The flow is skipped automatically on subsequent starts because
  • NeedsOnboarding returns false once the profile exists. *
  • Parameters:
  • a (*Agent) — the Harvey agent (used for workspace root).
  • store (*MemoryStore) — the open memory store for the workspace.
  • embedder (Embedder) — used to compute embedding vectors; may be nil.
  • out (io.Writer) — output writer for prompts and status.
  • in (io.Reader) — input reader for user responses. *
  • Returns:
  • error — if the workspace_profile cannot be saved. *
  • Example:
  • if NeedsOnboarding(store) {
  • err := RunOnboarding(a, store, embedder, os.Stdout, os.Stdin)
  • }

func RunSkillWizard

func RunSkillWizard(ws *Workspace, agentsDir string, reader *bufio.Reader, out io.Writer) (string, error)

* RunSkillWizard interactively collects skill metadata from the user,

  • opens $EDITOR/$VISUAL for the instructions body, and writes the resulting
  • SKILL.md into ws at <agentsDir>/skills/<name>/SKILL.md. *
  • Short fields (name, description, license, compatibility, author, version,
  • trigger) are collected via the provided reader. The instructions body is
  • edited in $VISUAL or $EDITOR (falling back to vi). *
  • Parameters:
  • ws (*Workspace) — workspace for path resolution and file writes.
  • agentsDir (string) — agents directory name; empty defaults to "agents".
  • reader (*bufio.Reader) — reads short field responses; use bufio.NewReaderSize(os.Stdin, 1).
  • out (io.Writer) — destination for prompts and status messages. *
  • Returns:
  • relPath (string) — relative path to the created SKILL.md, e.g. "agents/skills/my-skill/SKILL.md".
  • err (error) — on validation failure, editor error, or write failure. *
  • Example:
  • relPath, err := RunSkillWizard(ws, "", bufio.NewReaderSize(os.Stdin, 1), os.Stdout)
  • if err != nil { log.Fatal(err) }
  • fmt.Println("created:", relPath)

func SaveMemoryConfig added in v0.0.6

func SaveMemoryConfig(ws *Workspace, cfg *Config) error

* SaveMemoryConfig writes the memory-related config fields back to

  • agents/harvey.yaml, merging with any existing content so that unrelated keys
  • are preserved. It writes only to the memory: section; any legacy top-level
  • rag: or knowledge_db: keys are cleared from the file on write. *
  • Parameters:
  • ws (*Workspace) — workspace whose agents/ directory is written.
  • cfg (*Config) — source of Memory fields to persist. *
  • Returns:
  • error — on path resolution, YAML parse, or file write failure. *
  • Example:
  • if err := SaveMemoryConfig(ws, cfg); err != nil {
  • fmt.Println("could not save memory config:", err)
  • }

func SaveModelAliases

func SaveModelAliases(ws *Workspace, cfg *Config) error

* SaveModelAliases writes the model_aliases map back to harvey.yaml,

  • merging with any existing content so that unrelated keys are preserved. *
  • Parameters:
  • ws (*Workspace) — workspace whose agents/ directory is written.
  • cfg (*Config) — source of ModelAliases to persist. *
  • Returns:
  • error — on path resolution, YAML parse, or file write failure. *
  • Example:
  • if err := SaveModelAliases(ws, cfg); err != nil {
  • fmt.Println("could not save aliases:", err)
  • }

func SaveRAGConfig

func SaveRAGConfig(ws *Workspace, cfg *Config) error

* SaveRAGConfig is an alias for SaveMemoryConfig, retained for call-site

  • compatibility. All RAG state now lives in cfg.Memory. *
  • Parameters:
  • ws (*Workspace) — workspace whose agents/ directory is written.
  • cfg (*Config) — source of Memory fields to persist. *
  • Returns:
  • error — on path resolution, YAML parse, or file write failure. *
  • Example:
  • if err := SaveRAGConfig(ws, cfg); err != nil {
  • fmt.Println("could not save RAG config:", err)
  • }

func SaveRouteConfig

func SaveRouteConfig(ws *Workspace, rr *RouteRegistry) error

* SaveRouteConfig persists rr to agents/routes.json in the workspace,

  • creating the directory if necessary. Endpoints are written in alphabetical
  • name order for stable diffs. *
  • Parameters:
  • ws (*Workspace) — workspace whose agents/ directory is written.
  • rr (*RouteRegistry) — registry to persist; nil is treated as empty+disabled. *
  • Returns:
  • error — on path resolution, directory creation, or file write failure. *
  • Example:
  • if err := SaveRouteConfig(ws, agent.Routes); err != nil {
  • fmt.Println("warning:", err)
  • }

func ScrubDoc added in v0.0.6

func ScrubDoc(doc *MemoryDoc, workspacePath string) (*MemoryDoc, ScrubResult, error)

* ScrubDoc applies Scrub to both the YAML front matter text and the

  • FountainBody of a MemoryDoc, returning a new doc with normalised content
  • and combined flags from both sections. *
  • Parameters:
  • doc (*MemoryDoc) — document to scrub.
  • workspacePath (string) — workspace root to normalise away. *
  • Returns:
  • *MemoryDoc — new document with scrubbed content (original is unchanged).
  • ScrubResult — flags from the combined scrub of both sections.
  • error — if the doc cannot be re-serialised after scrubbing. *
  • Example:
  • scrubbed, result, err := ScrubDoc(proposed, ws.Root())
  • if len(result.Flags) > 0 {
  • showWarnings(result.Flags)
  • }

func SetGlobalAuditBuffer

func SetGlobalAuditBuffer(buf *AuditBuffer)

SetGlobalAuditBuffer sets the global audit buffer used by AuditLog.

func ShouldCompress added in v0.0.6

func ShouldCompress(historyTokens, contextLen int, warnAtPct float64) bool

* ShouldCompress reports whether the conversation history has grown large

  • enough to trigger rolling summary compression. Returns true when
  • historyTokens >= contextLen * warnAtPct. Returns false when contextLen or
  • warnAtPct is zero or negative. *
  • Parameters:
  • historyTokens (int) — estimated token count of the full history.
  • contextLen (int) — model's context window size in tokens.
  • warnAtPct (float64) — fraction of contextLen at which to compress
  • (e.g. 0.80 = 80%). *
  • Returns:
  • bool — true when compression is needed. *
  • Example:
  • if ShouldCompress(1640, 2048, 0.80) {
  • CompressHistory(agent, 6, os.Stdout)
  • }

func SortedSkillNames

func SortedSkillNames(cat SkillCatalog) []string

* SortedSkillNames returns the skill names from cat in sorted order.

  • Used to provide deterministic first-match semantics when scanning triggers. *
  • Parameters:
  • cat (SkillCatalog) — the catalog to sort. *
  • Returns:
  • []string — skill names in ascending alphabetical order. *
  • Example:
  • for _, name := range SortedSkillNames(a.Skills) {
  • if MatchesTrigger(a.Skills[name], input) { ... }
  • }

func StartOllamaService

func StartOllamaService(ollamaLogPath string) error

StartOllamaService launches "ollama serve" as a background process and waits up to 5 seconds for it to become reachable. OLLAMA_DEBUG is inherited from Harvey's process environment (set via --debug at startup). When ollamaLogPath is non-empty, subprocess stdout and stderr are redirected to that file so debug output is captured rather than discarded.

func ValidSkillName

func ValidSkillName(name string) bool

* ValidSkillName reports whether name is a valid skill identifier:

  • lowercase letters, digits, and hyphens only, non-empty. *
  • Parameters:
  • name (string) — candidate skill name. *
  • Returns:
  • bool — true when name matches ^[a-z0-9-]+$. *
  • Example:
  • ValidSkillName("go-review") // true
  • ValidSkillName("My Skill") // false

Types

type Agent

type Agent struct {
	Client         LLMClient
	Config         *Config
	History        []Message
	Workspace      *Workspace
	KB             *KnowledgeBase
	ModelCache     *ModelCache  // capability cache for installed Ollama models; nil until initModelCache runs
	Rag            *RagStore    // RAG chunk store; nil when RAG is not configured
	RagOn          bool         // when true, top-K chunks are injected before each Chat call
	SessionsDir    string       // absolute path to the sessions directory
	Skills         SkillCatalog // skills discovered at startup; nil until loadSkills runs
	Recorder       *Recorder
	In             io.Reader      // source for interactive prompts; defaults to os.Stdin
	PinnedContext  string         // persists across /clear; re-injected after system prompt
	Routes         *RouteRegistry // registered remote endpoints; nil when routing not configured
	ActiveSkill    string         // name of the most recently loaded skill; "" when none
	ActiveSkillSet string         // name of the currently loaded skill-set bundle; "" when none
	Tools          *ToolRegistry  // schema-based tool registry; nil when tools are disabled

	AuditBuffer           *AuditBuffer // in-memory audit log ring buffer; nil until initialized
	DebugLog              *DebugLog    // JSONL diagnostic log; nil when --debug not set
	OllamaStartedByHarvey bool         // true when Harvey launched the Ollama subprocess this session
	// contains filtered or unexported fields
}

* Agent holds the state of an active Harvey session, including the LLM

  • backend, conversation history, workspace, knowledge base, and registered
  • slash commands. *
  • Fields:
  • SessionsDir (string) — absolute path to the sessions directory resolved at startup.
  • Skills (SkillCatalog) — skills discovered at startup; nil until loadSkills runs. *
  • Example:
  • cfg := DefaultConfig()
  • ws, _ := NewWorkspace(".")
  • agent := NewAgent(cfg, ws)

func NewAgent

func NewAgent(cfg *Config, ws *Workspace) *Agent

* NewAgent creates an Agent from cfg and ws with an empty conversation

  • history. The knowledge base is opened lazily — it is nil if
  • OpenKnowledgeBase has not been called. *
  • Parameters:
  • cfg (*Config) — runtime configuration.
  • ws (*Workspace) — workspace that anchors all file I/O. *
  • Returns:
  • *Agent — initialised agent ready for Run(). *
  • Example:
  • ws, _ := NewWorkspace(".")
  • agent := NewAgent(DefaultConfig(), ws)

func (*Agent) AddMessage

func (a *Agent) AddMessage(role, content string)
  • AddMessage appends a plain-text message to the conversation history. *
  • Parameters:
  • role (string) — "system", "user", or "assistant".
  • content (string) — message body. *
  • Example:
  • agent.AddMessage("user", "What is the capital of France?")

func (*Agent) AddMessageParts added in v0.0.5

func (a *Agent) AddMessageParts(role string, parts []anyllm.ContentPart)

* AddMessageParts appends a multimodal message to the conversation history.

  • Use this when the message contains image or mixed text+image content.
  • Parts override Content — do not set Content when using this method. *
  • Parameters:
  • role (string) — "user" (multimodal messages are always user-role).
  • parts ([]anyllm.ContentPart) — ordered content parts (text, image_url, etc.). *
  • Example:
  • agent.AddMessageParts("user", []anyllm.ContentPart{
  • {Type: "text", Text: "[attached: photo.jpg]"},
  • {Type: "image_url", ImageURL: &anyllm.ImageURL{URL: "data:image/jpeg;base64,..."}},
  • })

func (*Agent) CheckDeletePermission

func (a *Agent) CheckDeletePermission(path string) bool

CheckDeletePermission returns true if delete is allowed for the given path.

func (*Agent) CheckExecPermission

func (a *Agent) CheckExecPermission(path string) bool

CheckExecPermission returns true if exec is allowed for the given path.

func (*Agent) CheckReadPermission

func (a *Agent) CheckReadPermission(path string) bool

CheckReadPermission returns true if read is allowed for the given path.

func (*Agent) CheckWritePermission

func (a *Agent) CheckWritePermission(path string) bool

CheckWritePermission returns true if write is allowed for the given path.

func (*Agent) ClearHistory

func (a *Agent) ClearHistory()

* ClearHistory resets the conversation, re-injecting the system prompt if

  • one is configured. *
  • Example:
  • agent.ClearHistory()

func (*Agent) ContinueFromFountain

func (a *Agent) ContinueFromFountain(path string) (int, error)

ContinueFromFountain loads the chat history from a Harvey Fountain session file and appends it to the Agent's current history so the conversation can be resumed. Call this after the system prompt has been added to history.

Parameters:

path (string) — path to a Harvey .fountain session file.

Returns:

int   — number of chat turns loaded.
error — if the file cannot be parsed.

Example:

n, err := agent.ContinueFromFountain("session.fountain")
fmt.Printf("Loaded %d turns\n", n)

func (*Agent) HasPermission

func (a *Agent) HasPermission(path string, perm string) bool

* HasPermission checks if the given permission is allowed for a path.

  • This delegates to the Config's permission system. *
  • Parameters:
  • path (string) — the path to check (relative to workspace root).
  • perm (string) — the permission to check (read, write, exec, delete). *
  • Returns:
  • bool — true if the permission is allowed. *
  • Example:
  • if a.HasPermission("src/main.go", PermRead) {
  • // read is allowed
  • }

func (*Agent) ReplayFromFountain

func (a *Agent) ReplayFromFountain(ctx context.Context, srcPath, outPath string, out io.Writer) error

ReplayFromFountain re-sends each user message from srcPath to the current LLM backend, records fresh responses to a new Fountain file at outPath, and streams progress to out.

Tagged code blocks in replies are applied with backup protection: if a target file already exists it is renamed to <path>.bak.<YYYYMMDD-HHMMSS> before the new content is written. Files that cannot be backed up or written are noted as skipped in the new Fountain recording.

Parameters:

ctx     (context.Context) — cancellable context for LLM calls.
srcPath (string)          — Harvey Fountain session file to replay.
outPath (string)          — destination for the new session recording.
out     (io.Writer)       — progress and streaming output.

Returns:

error — on parse failure, recorder creation failure, or unrecoverable LLM error.

Example:

err := agent.ReplayFromFountain(ctx, "old.fountain", "new.fountain", os.Stdout)

func (*Agent) Run

func (a *Agent) Run(out io.Writer) error

* Run prints the startup banner, initialises the workspace and knowledge base,

  • runs the backend selection sequence, then starts the interactive REPL. It
  • reads from os.Stdin and writes to out. *
  • Parameters:
  • out (io.Writer) — destination for all REPL output. *
  • Returns:
  • error — only on fatal startup errors; normal exit returns nil. *
  • Example:
  • agent := NewAgent(DefaultConfig(), ws)
  • if err := agent.Run(os.Stdout); err != nil {
  • log.Fatal(err)
  • }

type AnyLLMClient

type AnyLLMClient struct {
	DebugLog *DebugLog
	// contains filtered or unexported fields
}

* AnyLLMClient wraps an anyllm.Provider and implements Harvey's LLMClient

  • interface. It bridges any-llm-go's channel-based streaming to Harvey's
  • io.Writer-based streaming, and maps anyllm.Usage to ChatStats. *
  • Fields:
  • provider (anyllm.Provider) — underlying provider (e.g. ollama, anthropic).
  • modelName (string) — model name sent in every completion request.
  • provName (string) — provider identifier, e.g. "ollama".
  • backendURL (string) — base URL for local backends; empty for cloud. *
  • Example:
  • p, _ := ollama.New()
  • client := NewAnyLLMClient(p, "llama3.1:8b", "ollama", "http://localhost:11434")
  • stats, err := client.Chat(ctx, history, os.Stdout)

func NewAnyLLMClient

func NewAnyLLMClient(provider anyllm.Provider, modelName, provName, backendURL string) *AnyLLMClient
  • NewAnyLLMClient creates an AnyLLMClient wrapping provider. *
  • Parameters:
  • provider (anyllm.Provider) — underlying any-llm-go provider.
  • modelName (string) — model to request in completions.
  • provName (string) — short provider name for display (e.g. "ollama").
  • backendURL (string) — base URL; pass "" for cloud providers. *
  • Returns:
  • *AnyLLMClient — ready to use. *
  • Example:
  • client := NewAnyLLMClient(p, "llama3.1:8b", "ollama", "http://localhost:11434")

func (*AnyLLMClient) BackendURL

func (a *AnyLLMClient) BackendURL() string

func (*AnyLLMClient) Chat

func (a *AnyLLMClient) Chat(ctx context.Context, messages []Message, out io.Writer) (ChatStats, error)

* Chat sends the conversation history to the provider, streams reply tokens to

  • out, and returns timing and token stats. Harvey's []Message is converted to
  • anyllm.Message before dispatch; the provider's channel-based stream is
  • drained into out. *
  • Parameters:
  • ctx (context.Context) — controls the request lifetime.
  • messages ([]Message) — full conversation history.
  • out (io.Writer) — destination for streamed reply tokens. *
  • Returns:
  • ChatStats — timing and token counts (zero where provider does not report).
  • error — non-nil on transport or API failure. *
  • Example:
  • stats, err := client.Chat(ctx, agent.History, os.Stdout)

func (*AnyLLMClient) ChatWithTools

func (a *AnyLLMClient) ChatWithTools(ctx context.Context, messages []Message, tools []anyllm.Tool, out io.Writer) (ChatStats, []anyllm.ToolCall, error)

* ChatWithTools sends the conversation history with tool schemas to the

  • provider, streams reply tokens to out, and returns accumulated tool calls
  • (if the model requests them) alongside timing stats. *
  • Parameters:
  • ctx (context.Context) — controls the request lifetime.
  • messages ([]Message) — full conversation history including tool results.
  • tools ([]anyllm.Tool) — tool schemas to send in CompletionParams.
  • out (io.Writer) — destination for streamed reply tokens. *
  • Returns:
  • ChatStats — timing and token counts.
  • []anyllm.ToolCall — tool calls requested by the model (nil if none).
  • error — non-nil on transport or API failure. *
  • Example:
  • stats, calls, err := client.ChatWithTools(ctx, history, registry.GetToolSchemas(), os.Stdout)

func (*AnyLLMClient) Close

func (a *AnyLLMClient) Close() error

Close satisfies LLMClient. any-llm-go providers hold no closeable resources.

func (*AnyLLMClient) ModelName

func (a *AnyLLMClient) ModelName() string
  • ModelName returns the model name this client sends in every request. *
  • Returns:
  • string — model name, e.g. "llama3.1:8b". *
  • Example:
  • fmt.Println(client.ModelName()) // "llama3.1:8b"

func (*AnyLLMClient) Models

func (a *AnyLLMClient) Models(ctx context.Context) ([]string, error)

* Models returns the names of models available on this backend. For providers

  • that implement ModelLister the live list is fetched; others return a
  • single-element slice containing the configured model name. *
  • Parameters:
  • ctx (context.Context) — controls the request lifetime. *
  • Returns:
  • []string — model names.
  • error — non-nil on request failure. *
  • Example:
  • names, err := client.Models(ctx)

func (*AnyLLMClient) Name

func (a *AnyLLMClient) Name() string

Name satisfies LLMClient. Returns "provider (model)".

func (*AnyLLMClient) ProviderCapabilities added in v0.0.4

func (a *AnyLLMClient) ProviderCapabilities() anyllm.Capabilities

* ProviderCapabilities returns the feature flags reported by the underlying

  • provider. When the provider does not implement CapabilityProvider, a
  • conservative set with only Completion and CompletionStreaming is returned.
  • No network call is made — all providers return static capability data. *
  • Returns:
  • anyllm.Capabilities — static flags for this provider. *
  • Example:
  • caps := client.ProviderCapabilities()
  • if caps.CompletionTools { fmt.Println("tools supported") }

func (*AnyLLMClient) ProviderName

func (a *AnyLLMClient) ProviderName() string
  • ProviderName returns the short provider identifier. *
  • Returns:
  • string — e.g. "ollama", "anthropic", "openai". *
  • Example:
  • fmt.Println(client.ProviderName()) // "ollama"

type AnyLLMEmbedder

type AnyLLMEmbedder struct {
	// contains filtered or unexported fields
}

* AnyLLMEmbedder wraps an anyllm.EmbeddingProvider and implements Harvey's

  • Embedder interface. *
  • Example:
  • p, _ := ollama.New()
  • e, _ := NewAnyLLMEmbedder(p, "nomic-embed-text")
  • vec, err := e.Embed("hello world")

func NewAnyLLMEmbedder

func NewAnyLLMEmbedder(provider anyllm.Provider, modelName string) (*AnyLLMEmbedder, error)

* NewAnyLLMEmbedder creates an AnyLLMEmbedder from provider. Returns an error

  • if provider does not implement EmbeddingProvider. *
  • Parameters:
  • provider (anyllm.Provider) — provider to wrap; must implement EmbeddingProvider.
  • modelName (string) — embedding model name. *
  • Returns:
  • *AnyLLMEmbedder — ready to call Embed.
  • error — if provider does not support embeddings. *
  • Example:
  • p, _ := ollama.New()
  • e, err := NewAnyLLMEmbedder(p, "nomic-embed-text")

func (*AnyLLMEmbedder) Embed

func (e *AnyLLMEmbedder) Embed(text string) ([]float64, error)

* Embed sends text to the provider's embedding endpoint and returns the

  • embedding vector. *
  • Parameters:
  • text (string) — text to embed. *
  • Returns:
  • []float64 — embedding vector.
  • error — on transport failure or empty response. *
  • Example:
  • vec, err := e.Embed("The sky is blue")
  • fmt.Printf("dims: %d\n", len(vec))

func (*AnyLLMEmbedder) Name

func (e *AnyLLMEmbedder) Name() string

Name satisfies Embedder. Returns the embedding model name.

type AuditAction

type AuditAction string

AuditAction represents the type of action being audited.

const (
	// Command-related actions
	ActionCommand AuditAction = "command"
	// File operation actions
	ActionFileRead   AuditAction = "file_read"
	ActionFileWrite  AuditAction = "file_write"
	ActionFileDelete AuditAction = "file_delete"
	ActionFileList   AuditAction = "file_list"
	// Skill-related actions
	ActionSkillRun AuditAction = "skill_run"
	// Security-related actions
	ActionSecurity AuditAction = "security"
)

type AuditBuffer

type AuditBuffer struct {
	// contains filtered or unexported fields
}

AuditBuffer is a thread-safe ring buffer for storing audit events.

func NewAuditBuffer

func NewAuditBuffer(capacity int) *AuditBuffer

NewAuditBuffer creates a new AuditBuffer with the specified capacity.

func (*AuditBuffer) Add

func (b *AuditBuffer) Add(event AuditEvent)

Add appends an event to the buffer, overwriting the oldest event if full.

func (*AuditBuffer) Capacity

func (b *AuditBuffer) Capacity() int

Capacity returns the maximum number of events the buffer can hold.

func (*AuditBuffer) Clear

func (b *AuditBuffer) Clear()

Clear removes all events from the buffer.

func (*AuditBuffer) Get

func (b *AuditBuffer) Get(n int) []AuditEvent

Get returns the last n events, most recent first.

func (*AuditBuffer) GetAll

func (b *AuditBuffer) GetAll() []AuditEvent

GetAll returns all events in the buffer, most recent first.

func (*AuditBuffer) Log

func (b *AuditBuffer) Log(action AuditAction, details string, status AuditStatus)

Log is a convenience method that creates and adds an event in one call.

func (*AuditBuffer) Size

func (b *AuditBuffer) Size() int

Size returns the current number of events in the buffer.

type AuditEvent

type AuditEvent struct {
	Timestamp time.Time   // When the event occurred
	Action    AuditAction // Type of action (command, file_read, etc.)
	Details   string      // Description of what happened (command line, file path, etc.)
	Status    AuditStatus // Outcome (allowed, denied, error, etc.)
}

AuditEvent represents a single audit log entry.

func (AuditEvent) Format

func (e AuditEvent) Format() string

Format returns a human-readable string representation of the event.

type AuditStatus

type AuditStatus string

AuditStatus represents the outcome of an audited action.

const (
	StatusAllowed AuditStatus = "allowed"
	StatusDenied  AuditStatus = "denied"
	StatusError   AuditStatus = "error"
	StatusSuccess AuditStatus = "success"
	StatusWarning AuditStatus = "warning"
)

type CapabilityStatus

type CapabilityStatus int

* CapabilityStatus records whether a model capability has been confirmed,

  • denied, or not yet probed. *
  • Values:
  • CapUnknown (-1) — not yet probed.
  • CapNo (0) — confirmed absent.
  • CapYes (1) — confirmed present. *
  • Example:
  • if cap.SupportsTools == CapYes { fmt.Println("tools supported") }
const (
	CapUnknown CapabilityStatus = -1
	CapNo      CapabilityStatus = 0
	CapYes     CapabilityStatus = 1
)

func (CapabilityStatus) String

func (c CapabilityStatus) String() string

* String returns a display symbol for the capability status:

  • "✓" for yes, "—" for no, "?" for unknown. *
  • Returns:
  • string — one of "✓", "—", "?". *
  • Example:
  • fmt.Println(CapYes.String()) // "✓"

type ChatStats

type ChatStats struct {
	PromptTokens int
	ReplyTokens  int
	Elapsed      time.Duration
	TokensPerSec float64
}

* ChatStats holds timing and token-count data returned by a backend after

  • each Chat call. Fields are zero for backends that do not report them. *
  • Fields:
  • PromptTokens (int) — tokens in the prompt/history sent.
  • ReplyTokens (int) — tokens in the generated response.
  • Elapsed (time.Duration) — wall-clock time for the full call.
  • TokensPerSec (float64) — generation throughput (reply tokens / s). *
  • Example:
  • stats, err := client.Chat(ctx, history, &buf)
  • fmt.Println(stats.Format())

func (ChatStats) Format

func (s ChatStats) Format() string

* Format returns a human-readable one-line summary of the stats, e.g.

  • "26 prompt + 42 reply tokens · 8.3s · 5.1 tok/s".
  • If token counts are zero (backend does not report them) only elapsed time
  • is returned. *
  • Returns:
  • string — formatted stats line. *
  • Example:
  • fmt.Println(stats.Format()) // "26 prompt + 42 reply tokens · 8.3s · 5.1 tok/s"

func (ChatStats) FormatWithModels

func (s ChatStats) FormatWithModels(models []string) string

* FormatWithModels returns a one-line summary that includes the model name(s)

  • that handled the turn, reply token count, context (prompt) token count,
  • elapsed time, and throughput. Returns an empty string when there are no
  • token counts and no model names — used to suppress the stat block when no
  • meaningful data is available. *
  • Parameters:
  • models ([]string) — ordered list of model names, e.g. ["llama3.2:1b", "Ollama (llama3.1:8b)"].
  • Pass nil or empty for single-model sessions without routing. *
  • Returns:
  • string — formatted stat line, or "" when both models and token counts are absent. *
  • Example:
  • line := stats.FormatWithModels([]string{"llama3.2:1b", "Ollama (llama3.1:8b)"})
  • // "llama3.2:1b → Ollama (llama3.1:8b) · 312 reply + 1840 ctx · 18.4s · 16.9 tok/s"

type Chunk

type Chunk struct {
	ID      int64
	Content string
	Score   float64
	Source  string
}
  • Chunk is a retrieved text chunk returned by RagStore.Query. *
  • Fields:
  • ID (int64) — row ID in the chunks table.
  • Content (string) — the original ingested text.
  • Score (float64) — cosine similarity score [0,1]; 0 when not from Query.
  • Source (string) — source file path set at ingest time; empty when unknown. *
  • Example:
  • chunks, _ := store.Query("sky colour", embedder, 3)
  • for _, c := range chunks { fmt.Printf("[%.2f] %s\n", c.Score, c.Content) }

type CodeBlock added in v0.0.6

type CodeBlock struct {
	Lang    string
	Content string
}
  • CodeBlock holds a single fenced code block parsed from a markdown response. *
  • Fields:
  • Lang (string) — language hint from the opening fence (e.g. "go", "bash"); may be empty.
  • Content (string) — text inside the fence with the trailing newline stripped. *
  • Example:
  • blocks := extractCodeBlocks("```go\npackage main\n```")
  • // blocks[0].Lang == "go", blocks[0].Content == "package main"

type Command

type Command struct {
	Usage       string
	Description string
	UserDefined bool
	// Handler is nil for commands handled directly in the REPL (exit, quit).
	Handler func(a *Agent, args []string, out io.Writer) error
}
  • Command describes a slash command available in the Harvey REPL. *
  • Fields:
  • Usage (string) — short usage synopsis shown by /help.
  • Description (string) — one-line description shown by /help.
  • UserDefined (bool) — true for commands generated from compiled skills.
  • Handler (func) — called when the command is dispatched; nil for
  • commands handled directly in the REPL (exit, quit). *
  • Example:
  • cmd := &Command{
  • Usage: "/greet NAME",
  • Description: "Print a greeting",
  • Handler: func(a *Agent, args []string, out io.Writer) error {
  • fmt.Fprintln(out, "Hello,", args[0])
  • return nil
  • },
  • }

type Concept

type Concept struct {
	ID          int64
	Name        string
	Description string
}

* Concept represents a named idea or term that can be linked to projects and

  • observations. *
  • Example:
  • concepts, err := kb.Concepts()
  • for _, c := range concepts {
  • fmt.Println(c.Name, "-", c.Description)
  • }

type Config

type Config struct {
	WorkDir             string          // workspace root; all file I/O is constrained to this tree
	SessionsDir         string          // directory for .spmd session files; empty = agents/sessions/
	AgentsDir           string          // agents/skills tree root; empty = agents/
	SystemPrompt        string          // contents of HARVEY.md, injected as the system prompt
	OllamaURL           string          // Ollama base URL (default: http://localhost:11434)
	OllamaModel         string          // currently selected Ollama model
	OllamaContextLength int             // context window size in tokens; 0 = unknown
	Routes              []RouteEndpoint // registered remote endpoints; persisted across sessions
	RoutingEnabled      bool            // when false, @mentions are rejected with a warning
	AutoRecord          bool            // record every session to a .spmd file automatically
	RecordPath          string          // file path for auto-recording; empty = auto-generated timestamped name
	ContinuePath        string          // session file to load as pre-history when starting the REPL
	ReplayPath          string          // session file to replay instead of entering the REPL
	ReplayOutputPath    string          // output path for replay recording; empty = auto-generated
	ModelCacheDB        string          // path to model_cache.db; empty = harvey/model_cache.db
	// Security settings
	SafeMode        bool     // when true, only commands in AllowedCommands can be executed via ! or /run
	AllowedCommands []string // list of command names permitted when SafeMode is enabled
	// Permissions: map from path prefix to list of allowed actions (read, write, exec, delete)
	Permissions map[string][]string
	// Timeout settings
	RunTimeout    time.Duration // timeout for shell commands run via ! or /run; 0 means no timeout
	OllamaTimeout time.Duration // HTTP client timeout for local LLM providers; 0 means no timeout
	// Model aliases: short name → full Ollama model identifier
	ModelAliases map[string]string
	// Tool settings
	ToolsEnabled        bool // when true, send tool schemas to models that support it
	MaxToolCallsPerTurn int  // hard limit on tool call rounds per user turn; 0 = defaultMaxToolCallsPerTurn
	MaxOutputBytes      int  // cap on tool output injected into context; 0 = defaultMaxOutputBytes
	// Debug mode: set by --debug at startup; enables JSONL debug log and OLLAMA_DEBUG
	Debug bool
	// Memory system: RAG stores, knowledge base, and retrieval settings
	Memory MemoryConfig
}
  • Config holds Harvey's runtime configuration. *
  • Fields:
  • WorkDir (string) — root directory Harvey is allowed to read/write; defaults to ".".
  • SessionsDir (string) — directory for session .spmd files; empty = agents/sessions/.
  • AgentsDir (string) — base directory for the agents/skills tree; empty = agents/.
  • SystemPrompt (string) — contents of HARVEY.md, injected as the system prompt.
  • OllamaURL (string) — Ollama base URL (default: http://localhost:11434).
  • OllamaModel (string) — currently selected Ollama model.
  • AutoRecord (bool) — record every session to a .spmd file (default true).
  • Memory (MemoryConfig) — unified memory system settings, including RAG and knowledge base. *
  • Example:
  • cfg := DefaultConfig()
  • cfg.WorkDir = "/home/user/myproject"

func DefaultConfig

func DefaultConfig() *Config

func (*Config) AddAllowedCommand

func (c *Config) AddAllowedCommand(cmd string)
  • AddAllowedCommand adds a command to the AllowedCommands list if not already present. *
  • Parameters:
  • cmd (string) — command name to add. *
  • Example:
  • cfg.AddAllowedCommand("git")

func (*Config) AddPermission

func (c *Config) AddPermission(prefix string, perm string)

* AddPermission adds a permission to a path prefix.

  • Creates the prefix entry if it doesn't exist. *
  • Parameters:
  • prefix (string) — the path prefix.
  • perm (string) — the permission to add (read, write, exec, delete). *
  • Example:
  • cfg.AddPermission("src/", "read")

func (*Config) HasPermission

func (c *Config) HasPermission(path string, perm string) bool

* HasPermission checks if the given permission is allowed for a path.

  • It checks the most specific matching path prefix first. *
  • Parameters:
  • path (string) — the path to check (relative to workspace root).
  • perm (string) — the permission to check (read, write, exec, delete). *
  • Returns:
  • bool — true if the permission is allowed. *
  • Example:
  • if cfg.HasPermission("src/main.go", "read") {
  • // read is allowed
  • }

func (*Config) IsCommandAllowed

func (c *Config) IsCommandAllowed(cmd string) bool

* IsCommandAllowed returns true if cmd is in the AllowedCommands list.

  • When SafeMode is false, all commands are allowed (returns true).
  • When SafeMode is true, only commands in AllowedCommands are permitted. *
  • Parameters:
  • cmd (string) — the command name to check. *
  • Returns:
  • bool — true if the command is allowed. *
  • Example:
  • if !cfg.IsCommandAllowed("git") {
  • fmt.Println("git is not allowed in safe mode")
  • }

func (*Config) PermissionString

func (c *Config) PermissionString(prefix string) string
  • PermissionString returns a comma-separated string of permissions for a prefix. *
  • Parameters:
  • prefix (string) — the path prefix. *
  • Returns:
  • string — comma-separated permissions, or "none" if no permissions.

func (*Config) RemoveAllowedCommand

func (c *Config) RemoveAllowedCommand(cmd string)

* RemoveAllowedCommand removes a command from the AllowedCommands list.

  • It is a no-op if the command is not present. *
  • Parameters:
  • cmd (string) — command name to remove. *
  • Example:
  • cfg.RemoveAllowedCommand("git")

func (*Config) RemovePermission

func (c *Config) RemovePermission(prefix string, perm string)

* RemovePermission removes a permission from a path prefix.

  • It is a no-op if the prefix or permission doesn't exist. *
  • Parameters:
  • prefix (string) — the path prefix.
  • perm (string) — the permission to remove. *
  • Example:
  • cfg.RemovePermission("src/", "write")

func (*Config) ResetAllowedCommands

func (c *Config) ResetAllowedCommands()
  • ResetAllowedCommands replaces AllowedCommands with the default list. *
  • Example:
  • cfg.ResetAllowedCommands()

func (*Config) ResetPermissions

func (c *Config) ResetPermissions()
  • ResetPermissions resets permissions to the default (full access to root). *
  • Example:
  • cfg.ResetPermissions()

func (*Config) ResolveModelAlias

func (c *Config) ResolveModelAlias(alias string) string

* ResolveModelAlias returns the full Ollama model identifier for alias, or

  • alias itself when no mapping is defined. Lookup is case-insensitive. *
  • Parameters:
  • alias (string) — short name typed by the user (e.g. "qwen-coder"). *
  • Returns:
  • string — full model identifier (e.g. "qwen2.5-coder:7b") or alias unchanged. *
  • Example:
  • full := cfg.ResolveModelAlias("qwen-coder") // → "qwen2.5-coder:7b"
  • same := cfg.ResolveModelAlias("llama3.2:latest") // → "llama3.2:latest"

func (*Config) SetPermission

func (c *Config) SetPermission(prefix string, perms []string)

* SetPermission sets the permissions for a path prefix.

  • Replaces any existing permissions for that prefix. *
  • Parameters:
  • prefix (string) — the path prefix (e.g., "src/", ".", "docs/"").
  • perms ([]string) — list of permissions (read, write, exec, delete). *
  • Example:
  • cfg.SetPermission("src/", []string{"read"})

type DebugLog added in v0.0.4

type DebugLog struct {
	// contains filtered or unexported fields
}

* DebugLog writes structured JSONL diagnostic events to a per-session log

  • file. Every method is nil-safe: calling any method on a nil *DebugLog is
  • a no-op, so callers never need to guard with if statements. *
  • Each line written is a JSON object with at least a "time" field (RFC3339Nano)
  • and an "event" field identifying the event type. Additional fields vary by
  • event type. The file is safe for concurrent writes. *
  • Example:
  • dl, err := OpenDebugLog("/path/to/agents/logs")
  • if err != nil { log.Fatal(err) }
  • defer dl.Close()
  • dl.LogSessionStart("gemma4:e2b", "ollama", "/workspace", "0.0.3")

func OpenDebugLog added in v0.0.4

func OpenDebugLog(logsDir string) (*DebugLog, error)

* OpenDebugLog creates agents/logs/harvey-TIMESTAMP.jsonl in logsDir.

  • The directory is created with 0755 permissions if it does not exist. *
  • Parameters:
  • logsDir (string) — directory to write the log file into. *
  • Returns:
  • *DebugLog — open log ready for writing.
  • error — on directory creation or file creation failure. *
  • Example:
  • dl, err := OpenDebugLog(filepath.Join(workspace.Root, "agents", "logs"))

func (*DebugLog) Close added in v0.0.4

func (d *DebugLog) Close() error

* Close flushes and closes the underlying file. Safe to call on nil.

func (*DebugLog) Log added in v0.0.4

func (d *DebugLog) Log(fields map[string]any)

Log writes a single JSONL line. fields must include "event". The "time" key is always overwritten with the current UTC time.

func (*DebugLog) LogError added in v0.0.4

func (d *DebugLog) LogError(source, message string)

* LogError records a non-fatal diagnostic error from a named source.

func (*DebugLog) LogLLMRequest added in v0.0.4

func (d *DebugLog) LogLLMRequest(model string, messageCount, toolCount int)

* LogLLMRequest records outgoing LLM request parameters.

func (*DebugLog) LogLLMResponse added in v0.0.4

func (d *DebugLog) LogLLMResponse(stats ChatStats, toolCallCount int)

* LogLLMResponse records the outcome of an LLM call.

func (*DebugLog) LogOllamaStart added in v0.0.4

func (d *DebugLog) LogOllamaStart(debugMode bool, logPath string)

* LogOllamaStart records when Harvey launches the Ollama subprocess.

func (*DebugLog) LogRAGInject added in v0.0.4

func (d *DebugLog) LogRAGInject(store, query string, chunkCount int, topScore float64)
  • LogRAGInject records a RAG context augmentation event. *
  • Parameters:
  • store (string) — name of the active RAG store.
  • query (string) — the user prompt used as the retrieval query.
  • chunkCount (int) — number of chunks injected above the score threshold.
  • topScore (float64) — cosine similarity of the best matching chunk.

func (*DebugLog) LogSessionStart added in v0.0.4

func (d *DebugLog) LogSessionStart(modelID, modelDisplay, provider, workspace, version string)
  • LogSessionStart records Harvey startup information. *
  • Parameters:
  • modelID (string) — bare model identifier, e.g. "gemma4:e2b".
  • modelDisplay (string) — full display name, e.g. "ollama (gemma4:e2b)".
  • provider (string) — provider name, e.g. "ollama".
  • workspace (string) — absolute workspace root path.
  • version (string) — Harvey version string.

func (*DebugLog) LogSkillDispatch added in v0.0.4

func (d *DebugLog) LogSkillDispatch(name, trigger string)

* LogSkillDispatch records a skill execution event.

func (*DebugLog) LogToolCall added in v0.0.4

func (d *DebugLog) LogToolCall(name string, outputBytes int, elapsed time.Duration, callErr string)
  • LogToolCall records a single tool invocation. *
  • Parameters:
  • name (string) — tool name.
  • outputBytes (int) — byte length of the tool's output.
  • elapsed (time.Duration) — wall time for the call.
  • callErr (string) — error message, or "" on success.

func (*DebugLog) OllamaLogPath added in v0.0.4

func (d *DebugLog) OllamaLogPath() string

* OllamaLogPath returns the companion path for capturing Ollama subprocess

  • output, derived from the Harvey log filename by substituting the prefix.
  • Returns "" when called on a nil receiver. *
  • Example:
  • // dl.path == "agents/logs/harvey-20260514-094620.jsonl"
  • // dl.OllamaLogPath() == "agents/logs/ollama-20260514-094620.log"

func (*DebugLog) Path added in v0.0.4

func (d *DebugLog) Path() string

* Path returns the absolute path of the log file, or "" for nil receiver.

type Embedder

type Embedder interface {
	Embed(text string) ([]float64, error)
	Name() string
}
  • Embedder produces vector embeddings for text strings. *
  • Methods:
  • Embed(text string) ([]float64, error) — return a vector for text.
  • Name() string — return the embedding model name. *
  • Example:
  • var e Embedder = NewOllamaEmbedder("http://localhost:11434", "nomic-embed-text")
  • vec, err := e.Embed("hello world")

func NewEmbedderForEntry

func NewEmbedderForEntry(entry *RagStoreEntry, ollamaURL string) Embedder

* NewEmbedderForEntry constructs the correct Embedder for entry based on its

  • EmbedderKind field. "encoderfile" uses EncoderfileEmbedder; anything else
  • (including "" and "ollama") uses OllamaEmbedder. *
  • Parameters:
  • entry (*RagStoreEntry) — store configuration entry.
  • ollamaURL (string) — Ollama base URL, used when kind is "ollama". *
  • Returns:
  • Embedder — the appropriate embedder for this entry. *
  • Example:
  • emb := NewEmbedderForEntry(cfg.Memory.ActiveRagStore(), cfg.OllamaURL)
  • vec, err := emb.Embed("hello world")

type EncoderfileEmbedder

type EncoderfileEmbedder struct {
	// contains filtered or unexported fields
}

* EncoderfileEmbedder implements Embedder using an Encoderfile binary's

  • HTTP REST endpoint. The binary must be a model of type "embedding"
  • built with encoderfile. It is scoped to one Encoderfile server. *
  • Example:
  • e := NewEncoderfileEmbedder("http://localhost:8080", "nomic-embed-text-v1_5")
  • vec, err := e.Embed("hello world")

func NewEncoderfileEmbedder

func NewEncoderfileEmbedder(baseURL, modelName string) *EncoderfileEmbedder

* NewEncoderfileEmbedder returns an EncoderfileEmbedder targeting the

  • given Encoderfile server. modelName must match the model_id from the
  • server's GET /model response; use ProbeEncoderfileModel to fetch it. *
  • Parameters:
  • baseURL (string) — Encoderfile HTTP base URL, e.g. "http://localhost:8080".
  • modelName (string) — model_id that identifies this embedding model. *
  • Returns:
  • *EncoderfileEmbedder — ready to call Embed. *
  • Example:
  • e := NewEncoderfileEmbedder("http://localhost:8080", "nomic-embed-text-v1_5")

func (*EncoderfileEmbedder) Embed

func (e *EncoderfileEmbedder) Embed(text string) ([]float64, error)

* Embed sends text to the Encoderfile server's POST /predict endpoint and

  • returns the embedding vector for the first (CLS) token, which is the
  • standard sentence representation for BERT-style encoder models. *
  • Parameters:
  • text (string) — text to embed. *
  • Returns:
  • []float64 — embedding vector.
  • error — on transport failure, non-200 status, or empty response. *
  • Example:
  • vec, err := e.Embed("The sky is blue")
  • fmt.Printf("dims: %d\n", len(vec))

func (*EncoderfileEmbedder) Name

func (e *EncoderfileEmbedder) Name() string

Name satisfies Embedder. Returns the model name used to identify this embedder.

type KBSearchResult

type KBSearchResult struct {
	Kind    string
	Label   string
	Snippet string
}
  • KBSearchResult holds one row returned by Search. *
  • Fields:
  • Kind (string) — observation kind ("note", "finding", etc.) or "project" / "concept".
  • Label (string) — project name for observations; entity name for projects and concepts.
  • Snippet (string) — observation body; or description for projects and concepts. *
  • Example:
  • results, _ := kb.Search("WAL mode")
  • for _, r := range results {
  • fmt.Printf("[%s] %s — %s\n", r.Kind, r.Label, r.Snippet)
  • }

type KnowledgeBase

type KnowledgeBase struct {
	// contains filtered or unexported fields
}

* KnowledgeBase is a SQLite3-backed store for projects, observations, and

  • concepts within a Harvey workspace. The database file lives at
  • <workspace>/agents/knowledge.db (or a path overridden in harvey.yaml) and
  • is created automatically on first use. *
  • Example:
  • kb, err := OpenKnowledgeBase(ws, "")
  • if err != nil {
  • log.Fatal(err)
  • }
  • defer kb.Close()

func OpenKnowledgeBase

func OpenKnowledgeBase(ws *Workspace, customPath string) (*KnowledgeBase, error)

* OpenKnowledgeBase opens (or creates) the SQLite knowledge base. customPath

  • overrides the default location (agents/knowledge.db inside the workspace);
  • pass an empty string to use the default. The schema is applied on every open
  • so that tables are created on first use without manual migration. *
  • Parameters:
  • ws (*Workspace) — the Harvey workspace that owns the database file.
  • customPath (string) — override path; empty = agents/knowledge.db. *
  • Returns:
  • *KnowledgeBase — ready-to-use knowledge base handle.
  • error — if the database file cannot be opened or the schema
  • cannot be applied. *
  • Example:
  • kb, err := OpenKnowledgeBase(ws, "")
  • if err != nil {
  • log.Fatal(err)
  • }
  • defer kb.Close()

func (*KnowledgeBase) AddConcept

func (kb *KnowledgeBase) AddConcept(name, description string) (int64, error)

* AddConcept inserts a new concept or, if a concept with the same name exists,

  • returns its ID unchanged. *
  • Parameters:
  • name (string) — unique concept name.
  • description (string) — human-readable explanation of the concept. *
  • Returns:
  • int64 — ID of the inserted or existing concept.
  • error — on database failure. *
  • Example:
  • id, err := kb.AddConcept("WAL mode", "SQLite write-ahead logging for concurrency")

func (*KnowledgeBase) AddObservation

func (kb *KnowledgeBase) AddObservation(projectID int64, kind, body string) (int64, error)
  • AddObservation inserts a new observation for a project and returns its ID. *
  • Parameters:
  • projectID (int64) — ID of the owning project.
  • kind (string) — one of: note, finding, decision, question, hypothesis.
  • body (string) — the observation text. *
  • Returns:
  • int64 — ID of the new observation.
  • error — if kind is invalid or the insert fails. *
  • Example:
  • id, err := kb.AddObservation(1, "finding", "WAL mode doubles write throughput")

func (*KnowledgeBase) AddProject

func (kb *KnowledgeBase) AddProject(name, description string) (int64, error)

* AddProject inserts a new project row and returns its auto-assigned ID. If a

  • project with the same name already exists, its ID is returned instead. *
  • Parameters:
  • name (string) — unique project name.
  • description (string) — short human-readable description. *
  • Returns:
  • int64 — ID of the inserted or existing project.
  • error — on database failure. *
  • Example:
  • id, err := kb.AddProject("harvey", "Terminal coding agent backed by Ollama")

func (*KnowledgeBase) Close

func (kb *KnowledgeBase) Close() error

* Close releases the database connection. It should be deferred immediately

  • after a successful OpenKnowledgeBase call. *
  • Returns:
  • error — from the underlying sql.DB.Close call. *
  • Example:
  • kb, _ := OpenKnowledgeBase(ws)
  • defer kb.Close()

func (*KnowledgeBase) Concepts

func (kb *KnowledgeBase) Concepts() ([]Concept, error)
  • Concepts returns all concepts ordered by name. *
  • Returns:
  • []Concept — all concept rows; empty (not nil) if none exist.
  • error — on database failure. *
  • Example:
  • concepts, err := kb.Concepts()
  • for _, c := range concepts {
  • fmt.Println(c.Name)
  • }

func (*KnowledgeBase) FormatMarkdown

func (kb *KnowledgeBase) FormatMarkdown(projectID int64) (string, error)

* FormatMarkdown returns the knowledge base contents as Markdown, suitable for

  • injecting into a conversation as context. When projectID > 0 only that project
  • is included; when projectID == 0 all projects are included. Each project gets
  • a ## heading, and observations are listed with their kind in bold. *
  • Parameters:
  • projectID (int64) — project to export; 0 = all projects. *
  • Returns:
  • string — Markdown-formatted knowledge base contents; "" if no data.
  • error — on database failure. *
  • Example:
  • md, err := kb.FormatMarkdown(0) // all projects
  • md, err := kb.FormatMarkdown(1) // project id=1 only

func (*KnowledgeBase) LinkObservationConcept

func (kb *KnowledgeBase) LinkObservationConcept(observationID, conceptID int64) error

* LinkObservationConcept associates an observation with a concept. Duplicate

  • links are silently ignored. *
  • Parameters:
  • observationID (int64) — ID of the observation.
  • conceptID (int64) — ID of the concept. *
  • Returns:
  • error — on database failure. *
  • Example:
  • err := kb.LinkObservationConcept(obsID, conceptID)

func (*KnowledgeBase) LinkProjectConcept

func (kb *KnowledgeBase) LinkProjectConcept(projectID, conceptID int64) error

* LinkProjectConcept associates a project with a concept. Duplicate links are

  • silently ignored. *
  • Parameters:
  • projectID (int64) — ID of the project.
  • conceptID (int64) — ID of the concept. *
  • Returns:
  • error — on database failure. *
  • Example:
  • err := kb.LinkProjectConcept(projectID, conceptID)

func (*KnowledgeBase) Observations

func (kb *KnowledgeBase) Observations(projectID int64) ([]Observation, error)
  • Observations returns all observations for a project, newest first. *
  • Parameters:
  • projectID (int64) — ID of the project to query. *
  • Returns:
  • []Observation — slice of matching rows; empty (not nil) if none exist.
  • error — on database failure. *
  • Example:
  • obs, err := kb.Observations(1)
  • for _, o := range obs {
  • fmt.Printf("[%s] %s\n", o.Kind, o.Body)
  • }

func (*KnowledgeBase) Path

func (kb *KnowledgeBase) Path() string

Path returns the absolute path of the open knowledge base file.

func (*KnowledgeBase) ProjectByName

func (kb *KnowledgeBase) ProjectByName(name string) (*Project, error)
  • ProjectByName returns the project with the given name, or nil if not found. *
  • Parameters:
  • name (string) — exact project name. *
  • Returns:
  • *Project — the matching project, or nil.
  • error — on database failure. *
  • Example:
  • p, err := kb.ProjectByName("harvey")

func (*KnowledgeBase) ProjectConcepts

func (kb *KnowledgeBase) ProjectConcepts(projectID int64) ([]Concept, error)
  • ProjectConcepts returns all concepts linked to a project, ordered by name. *
  • Parameters:
  • projectID (int64) — ID of the project. *
  • Returns:
  • []Concept — linked concepts; empty (not nil) if none.
  • error — on database failure. *
  • Example:
  • concepts, err := kb.ProjectConcepts(1)

func (*KnowledgeBase) Projects

func (kb *KnowledgeBase) Projects() ([]Project, error)
  • Projects returns all projects ordered by creation date. *
  • Returns:
  • []Project — slice of all project rows; empty (not nil) if none exist.
  • error — on database failure. *
  • Example:
  • projects, err := kb.Projects()
  • for _, p := range projects {
  • fmt.Println(p.Name, p.Status)
  • }

func (*KnowledgeBase) Search

func (kb *KnowledgeBase) Search(term string) ([]KBSearchResult, error)

* Search performs a full-text search across observations, projects, and concepts

  • using the FTS5 index. Results are ranked by relevance (best match first).
  • Returns an error wrapping ErrFTSUnavailable when the FTS index is not present. *
  • The term uses standard FTS5 query syntax: multiple words are ANDed, phrases
  • can be quoted ("WAL mode"), and prefix search is supported (docker*). *
  • Parameters:
  • term (string) — FTS5 query term. *
  • Returns:
  • []KBSearchResult — ranked results; nil if none found.
  • error — on query failure or when FTS is unavailable. *
  • Example:
  • results, err := kb.Search("docker")
  • for _, r := range results {
  • fmt.Printf("[%-10s] %s — %s\n", r.Kind, r.Label, r.Snippet)
  • }

func (*KnowledgeBase) Summary

func (kb *KnowledgeBase) Summary() (string, error)

* Summary returns a human-readable text summary of all projects and their

  • recent observations, suitable for printing in the Harvey REPL. *
  • Returns:
  • string — formatted multi-line summary.
  • error — on database failure. *
  • Example:
  • s, err := kb.Summary()
  • fmt.Print(s)

type LLMClient

type LLMClient interface {
	// Name returns a human-readable identifier shown in the UI.
	Name() string
	// Chat sends the full conversation history, streams the response to out,
	// and returns timing and token-count stats for the call.
	Chat(ctx context.Context, messages []Message, out io.Writer) (ChatStats, error)
	// Models lists models available on this backend.
	Models(ctx context.Context) ([]string, error)
	// Close releases any resources held by the client.
	Close() error
}

* LLMClient is the interface implemented by each LLM backend (Ollama,

  • Llamafile, Anthropic, OpenAI, etc.). *
  • Methods:
  • Name() string — human-readable backend identifier.
  • Chat() func(ctx, messages, out) (ChatStats, error) — send history, stream reply to out.
  • Models() func(ctx) ([]string, error) — list available models.
  • Close() error — release held resources. *
  • Example:
  • var c LLMClient = NewOllamaClient("http://localhost:11434", "llama3")
  • stats, err := c.Chat(ctx, history, os.Stdout)

type Manifest added in v0.0.6

type Manifest struct {
	Sessions []ManifestEntry `yaml:"sessions"`
}

* Manifest tracks which session files have been fully reviewed for memory

  • extraction. It is stored as agents/memories/manifest.yaml so it is
  • human-readable and version-controllable alongside the memory files. *
  • A session is recorded only after the full interactive review completes;
  • an interrupted review leaves the session absent from the manifest so it
  • will be offered again on the next /memory mine run. *
  • Example:
  • m, err := LoadManifest(store.Dir())
  • if m.IsMined("agents/sessions/foo.spmd") {
  • fmt.Println("already reviewed")
  • }

func LoadManifest added in v0.0.6

func LoadManifest(dir string) (*Manifest, error)

* LoadManifest reads the manifest from dir/manifest.yaml. If the file does

  • not exist an empty Manifest is returned without error. *
  • Parameters:
  • dir (string) — absolute path to agents/memories/. *
  • Returns:
  • *Manifest — loaded or empty manifest.
  • error — on read or YAML parse failure (not on missing file). *
  • Example:
  • m, err := LoadManifest(store.Dir())

func (*Manifest) IsMined added in v0.0.6

func (m *Manifest) IsMined(sessionPath string) bool

* IsMined returns true if sessionPath appears in the manifest, indicating

  • that it has already been fully reviewed. *
  • Parameters:
  • sessionPath (string) — path to the session file (any form; compared
  • as a string against stored paths). *
  • Returns:
  • bool — true if the session has a completed review entry. *
  • Example:
  • if !m.IsMined("agents/sessions/foo.spmd") {
  • // offer for review
  • }

func (*Manifest) Record added in v0.0.6

func (m *Manifest) Record(sessionPath string, created []string, skipped int)

* Record appends a completed review entry for sessionPath. created is the

  • list of memory IDs that were accepted; skipped is the count that were
  • declined. *
  • Parameters:
  • sessionPath (string) — path to the reviewed session file.
  • created ([]string) — IDs of memories saved during review.
  • skipped (int) — number of proposed memories the user declined. *
  • Example:
  • m.Record("agents/sessions/foo.spmd", []string{"tool_use_a1b2c3"}, 2)
  • m.Save(store.Dir())

func (*Manifest) Save added in v0.0.6

func (m *Manifest) Save(dir string) error

* Save writes the manifest to dir/manifest.yaml, creating the file if it

  • does not exist. *
  • Parameters:
  • dir (string) — absolute path to agents/memories/. *
  • Returns:
  • error — on YAML marshal or file write failure. *
  • Example:
  • err := m.Save(store.Dir())

func (*Manifest) UnminedSessions added in v0.0.6

func (m *Manifest) UnminedSessions(sessionsDir string) ([]string, error)

* UnminedSessions returns all .spmd files under sessionsDir that do not

  • appear in the manifest, in filesystem order. This is the set of sessions
  • that /memory mine would process. *
  • Parameters:
  • sessionsDir (string) — absolute path to the sessions directory. *
  • Returns:
  • []string — absolute paths to unmined session files.
  • error — on directory read failure. *
  • Example:
  • paths, err := m.UnminedSessions("/home/user/project/agents/sessions")
  • for _, p := range paths {
  • fmt.Println(p)
  • }

type ManifestEntry added in v0.0.6

type ManifestEntry struct {
	Path            string   `yaml:"path"`
	MinedAt         string   `yaml:"mined_at"`
	MemoriesCreated []string `yaml:"memories_created"`
	MemoriesSkipped int      `yaml:"memories_skipped"`
}
  • ManifestEntry records the result of mining a single session file. *
  • Fields:
  • Path (string) — workspace-relative path to the session file.
  • MinedAt (string) — RFC3339 timestamp when review completed.
  • MemoriesCreated ([]string) — IDs of memories accepted during review.
  • MemoriesSkipped (int) — count of proposed memories the user skipped. *
  • Example:
  • fmt.Printf("mined %s: created %d, skipped %d\n",
  • e.Path, len(e.MemoriesCreated), e.MemoriesSkipped)

type MemoryConfig added in v0.0.6

type MemoryConfig struct {
	Enabled          bool
	TopK             int
	InjectOnStart    bool
	BudgetPct        float64              // fraction of model context window for memory injection
	RollingSummary   RollingSummaryConfig // working-memory compression settings
	RagStores        []RagStoreEntry      // all registered named RAG stores
	RagActive        string               // name of the currently active RAG store; "" = none
	RagEnabled       bool                 // when true, inject top-K chunks before each Chat call
	KnowledgeDB      string               // path to knowledge.db; empty = agents/knowledge.db
	CurrentProjectID int64                // in-session active knowledge-base project ID (0 = none)
}
  • MemoryConfig controls the behaviour of Harvey's memory system. *
  • Fields:
  • Enabled (bool) — when false the entire memory system is skipped; default true.
  • TopK (int) — number of memories retrieved at session start; default 5.
  • InjectOnStart (bool) — inject memory context block in ClearHistory; default true.
  • BudgetPct (float64) — fraction of model context window allocated to memory
  • injection (default 0.25); falls back to 512 tokens when
  • OllamaContextLength is unknown.
  • RollingSummary (RollingSummaryConfig) — working-memory compression settings.
  • RagStores ([]RagStoreEntry) — all registered named RAG stores.
  • RagActive (string) — name of the currently active RAG store; "" = none.
  • RagEnabled (bool) — when true, inject top-K chunks before each Chat call.
  • KnowledgeDB (string) — path to knowledge.db; empty = agents/knowledge.db.
  • CurrentProjectID (int64) — in-session active knowledge-base project ID (0 = none). *
  • Example:
  • cfg.Memory = MemoryConfig{Enabled: true, TopK: 5, InjectOnStart: true, BudgetPct: 0.25}

func (*MemoryConfig) ActiveRagStore added in v0.0.6

func (m *MemoryConfig) ActiveRagStore() *RagStoreEntry

* ActiveRagStore returns a pointer to the active RagStoreEntry in the memory

  • config, or nil when no store is configured. *
  • Returns:
  • *RagStoreEntry — the active entry, or nil. *
  • Example:
  • if e := cfg.Memory.ActiveRagStore(); e != nil {
  • fmt.Println(e.DBPath)
  • }

func (*MemoryConfig) AddOrUpdateRagStore added in v0.0.6

func (m *MemoryConfig) AddOrUpdateRagStore(e RagStoreEntry)

* AddOrUpdateRagStore inserts e into the memory config registry if its name

  • is new, or replaces the existing entry if one with the same name exists. *
  • Parameters:
  • e (RagStoreEntry) — the entry to add or replace. *
  • Example:
  • cfg.Memory.AddOrUpdateRagStore(RagStoreEntry{Name: "golang", DBPath: "agents/rag/golang.db"})

func (*MemoryConfig) RagStoreByName added in v0.0.6

func (m *MemoryConfig) RagStoreByName(name string) *RagStoreEntry

* RagStoreByName returns a pointer to the named store entry in the memory

  • config, or nil when not found. *
  • Parameters:
  • name (string) — store name to look up. *
  • Returns:
  • *RagStoreEntry — matching entry, or nil. *
  • Example:
  • if e := cfg.Memory.RagStoreByName("golang"); e != nil {
  • fmt.Println(e.EmbeddingModel)
  • }

func (*MemoryConfig) RemoveRagStore added in v0.0.6

func (m *MemoryConfig) RemoveRagStore(name string)

* RemoveRagStore removes the store with the given name from the memory config

  • registry. It is a no-op when no store with that name exists. *
  • Parameters:
  • name (string) — name of the store to remove. *
  • Example:
  • cfg.Memory.RemoveRagStore("research-llm")

type MemoryDoc added in v0.0.6

type MemoryDoc struct {
	Meta         MemoryMeta
	FountainBody string // everything after the closing ---\n
}

* MemoryDoc is a parsed memory file: structured YAML metadata plus a

  • Fountain-format body. The FountainBody begins at "FADE IN:" and ends
  • with "THE END." and uses the INT. MEMORY <TIMESTAMP> scene heading. *
  • Example:
  • doc, err := ParseMemoryDoc(data)
  • fmt.Println(doc.Meta.Description)

func NewMemoryDoc added in v0.0.6

func NewMemoryDoc(id string, memType MemoryType, description, summary string, tags []string) *MemoryDoc

* NewMemoryDoc creates a new MemoryDoc with the given fields and sets

  • CreatedAt, UpdatedAt, and empty Supersedes. The caller is responsible
  • for populating FountainBody before saving. *
  • Parameters:
  • id (string) — unique identifier (see GenerateMemoryID).
  • memType (MemoryType) — one of MemoryTypeToolUse, etc.
  • description (string) — one-sentence human summary.
  • summary (string) — 2-3 sentence text optimised for embedding.
  • tags ([]string) — keyword tags for filtering. *
  • Returns:
  • *MemoryDoc — new document with empty FountainBody. *
  • Example:
  • doc := NewMemoryDoc("git_fix_a3f891", MemoryTypeToolUse,
  • "Fixed fatal: not a git repository", "...", []string{"git","fix"})

func ParseMemoryDoc added in v0.0.6

func ParseMemoryDoc(data []byte) (*MemoryDoc, error)

* ParseMemoryDoc parses a memory file from raw bytes. The file must begin

  • with a --- delimited YAML front matter block. Everything after the closing
  • --- is the Fountain body. *
  • Parameters:
  • data ([]byte) — raw file contents. *
  • Returns:
  • *MemoryDoc — parsed document.
  • error — if the front matter is missing, malformed, or the YAML
  • cannot be decoded. *
  • Example:
  • data, _ := os.ReadFile("agents/memories/tool_use/git_fix_a3f891.fountain")
  • doc, err := ParseMemoryDoc(data)

func (*MemoryDoc) ArchivePath added in v0.0.6

func (m *MemoryDoc) ArchivePath(baseDir string) string

* ArchivePath returns the file path for this memory document when archived.

  • Archived files live under {baseDir}/archive/{type}/{id}.fountain. *
  • Parameters:
  • baseDir (string) — absolute path to the memories root directory. *
  • Returns:
  • string — absolute archive file path. *
  • Example:
  • path := doc.ArchivePath("/home/user/project/agents/memories")
  • // → "/home/user/project/agents/memories/archive/tool_use/git_fix_a3f891.fountain"

func (*MemoryDoc) Bytes added in v0.0.6

func (m *MemoryDoc) Bytes() ([]byte, error)

* Bytes serialises the MemoryDoc back to its file representation:

  • YAML front matter delimited by --- followed by the Fountain body. *
  • Returns:
  • []byte — the file contents ready to write to disk.
  • error — if the YAML cannot be marshalled. *
  • Example:
  • data, err := doc.Bytes()
  • os.WriteFile(doc.FilePath("agents/memories"), data, 0o644)

func (*MemoryDoc) EmbedText added in v0.0.6

func (m *MemoryDoc) EmbedText() string

* EmbedText returns the text used to generate the embedding for this

  • memory. It combines description, tags, and summary to produce a compact,
  • semantically rich representation. *
  • Returns:
  • string — the text to pass to the embedder. *
  • Example:
  • vec, err := embedder.Embed(doc.EmbedText())

func (*MemoryDoc) FilePath added in v0.0.6

func (m *MemoryDoc) FilePath(baseDir string) string

* FilePath returns the canonical file path for this memory document under

  • baseDir. The path follows the pattern {baseDir}/{type}/{id}.fountain. *
  • Parameters:
  • baseDir (string) — absolute path to the memories root directory
  • (e.g. agents/memories resolved to absolute). *
  • Returns:
  • string — absolute file path for this memory. *
  • Example:
  • path := doc.FilePath("/home/user/project/agents/memories")
  • // → "/home/user/project/agents/memories/tool_use/git_fix_a3f891.fountain"

type MemoryMeta added in v0.0.6

type MemoryMeta struct {
	ID            string         `yaml:"id"`
	Type          MemoryType     `yaml:"type"`
	CreatedAt     string         `yaml:"created_at"`
	UpdatedAt     string         `yaml:"updated_at"`
	Supersedes    []string       `yaml:"supersedes"`
	Tags          []string       `yaml:"tags"`
	Description   string         `yaml:"description"`
	Summary       string         `yaml:"summary"`
	SourceSession string         `yaml:"source_session,omitempty"`
	Metadata      map[string]any `yaml:"metadata,omitempty"`
}

* MemoryMeta holds the structured YAML front matter of a memory document.

  • It replaces the standard Fountain title block, so the file begins with
  • a --- delimited YAML section followed by a proper Fountain body. *
  • Example:
  • meta := MemoryMeta{
  • ID: "git_fix_a3f891",
  • Type: MemoryTypeToolUse,
  • Description: "Fixed 'fatal: not a git repository' with git init",
  • }

type MemoryStore added in v0.0.6

type MemoryStore struct {
	// contains filtered or unexported fields
}

* MemoryStore manages a workspace's memory documents: the on-disk

  • .fountain files under agents/memories/ and a companion SQLite index
  • (memories.db) that stores metadata, FTS5 tokens, and embedding vectors
  • for fast retrieval. *
  • The .fountain files are the source of truth. If memories.db is absent,
  • NewMemoryStore rebuilds it by walking the directory tree. *
  • Example:
  • store, err := NewMemoryStore(ws)
  • if err != nil { log.Fatal(err) }
  • defer store.Close()

func NewMemoryStore added in v0.0.6

func NewMemoryStore(ws *Workspace) (*MemoryStore, error)

* NewMemoryStore opens (or creates) the memory store for the given

  • workspace. It creates the directory tree, opens memories.db, applies
  • the schema, and rebuilds the index from files if the database is empty. *
  • Parameters:
  • ws (*Workspace) — the Harvey workspace. *
  • Returns:
  • *MemoryStore — ready-to-use store.
  • error — if directories cannot be created or the database fails. *
  • Example:
  • store, err := NewMemoryStore(ws)
  • if err != nil { log.Fatal(err) }
  • defer store.Close()

func (*MemoryStore) Archive added in v0.0.6

func (s *MemoryStore) Archive(id string) error

* Archive moves a memory from the active store to the archive directory

  • and marks it as archived in the database. The original file is removed
  • from its type subdirectory. *
  • Parameters:
  • id (string) — ID of the memory to archive. *
  • Returns:
  • error — if the memory is not found, the file cannot be moved, or the
  • database update fails. *
  • Example:
  • err := store.Archive("git_fix_a3f891")

func (*MemoryStore) BudgetStats added in v0.0.6

func (s *MemoryStore) BudgetStats(n int) (avgSaturation, compressionRate, avgToksPerSec float64, err error)

* BudgetStats computes aggregate memory budget statistics from the last n rows

  • of memory_stats. Used by /memory status to generate tuning suggestions. *
  • Parameters:
  • n (int) — number of most-recent sessions to include; e.g. 10. *
  • Returns:
  • avgSaturation (float64) — mean(injected_tokens/budget_tokens); 0 when budget was 0.
  • compressionRate (float64) — fraction of sessions where rolling summary fired.
  • avgToksPerSec (float64) — mean generation throughput across sessions.
  • error — on database failure. *
  • Example:
  • sat, compRate, tps, err := store.BudgetStats(10)
  • fmt.Printf("avg utilisation %.0f%%\n", sat*100)

func (*MemoryStore) ByID added in v0.0.6

func (s *MemoryStore) ByID(id string) (*MemoryDoc, error)

* ByID returns the MemoryDoc with the given ID, reading it from its file.

  • Returns (nil, nil) when the ID is not found. *
  • Parameters:
  • id (string) — memory ID to look up. *
  • Returns:
  • *MemoryDoc — the memory, or nil if not found.
  • error — on database or file read failure. *
  • Example:
  • doc, err := store.ByID("git_fix_a3f891")

func (*MemoryStore) Close added in v0.0.6

func (s *MemoryStore) Close() error
  • Close releases the database connection. *
  • Returns:
  • error — from the underlying sql.DB.Close call. *
  • Example:
  • defer store.Close()

func (*MemoryStore) Count added in v0.0.6

func (s *MemoryStore) Count() (int64, error)
  • Count returns the number of non-archived memories in the store. *
  • Returns:
  • int64 — total active memory count.
  • error — on database failure. *
  • Example:
  • n, _ := store.Count()
  • fmt.Printf("%d memories\n", n)

func (*MemoryStore) Dir added in v0.0.6

func (s *MemoryStore) Dir() string
  • Dir returns the absolute path to the memories root directory. *
  • Returns:
  • string — e.g. "/home/user/project/agents/memories". *
  • Example:
  • fmt.Println(store.Dir())

func (*MemoryStore) List added in v0.0.6

func (s *MemoryStore) List(typeFilter string) ([]MemoryMeta, error)

* List returns metadata for all non-archived memories. When typeFilter is

  • non-empty only memories of that type are returned. Results are ordered
  • by updated_at descending. *
  • Parameters:
  • typeFilter (string) — memory type to filter on, or "" for all types. *
  • Returns:
  • []MemoryMeta — metadata rows; empty (not nil) if none found.
  • error — on database failure. *
  • Example:
  • metas, err := store.List("tool_use")
  • for _, m := range metas {
  • fmt.Printf("%s %s\n", m.ID, m.Description)
  • }

func (*MemoryStore) ListDocs added in v0.0.6

func (s *MemoryStore) ListDocs(typeFilter string) ([]MemoryDoc, error)

* ListDocs returns full MemoryDoc objects for all non-archived memories.

  • When typeFilter is non-empty only memories of that type are returned.
  • Results are ordered by updated_at descending. *
  • Parameters:
  • typeFilter (string) — memory type to filter on, or "" for all types. *
  • Returns:
  • []MemoryDoc — documents with parsed front matter and Fountain body.
  • error — on database or file read failure. *
  • Example:
  • docs, err := store.ListDocs("workspace_profile")
  • for _, d := range docs { fmt.Println(d.Meta.Description) }

func (*MemoryStore) Query added in v0.0.6

func (s *MemoryStore) Query(query string, embedder Embedder, topK int) ([]MemoryDoc, error)

* Query embeds the query string and returns the topK non-archived memories

  • with the highest cosine similarity to the query embedding. *
  • Parameters:
  • query (string) — the search query.
  • embedder (Embedder) — used to embed the query.
  • topK (int) — maximum number of results to return. *
  • Returns:
  • []MemoryDoc — up to topK documents ordered by descending similarity.
  • error — on embedding or database failure. *
  • Example:
  • docs, err := store.Query("git repository error", embedder, 5)

func (*MemoryStore) Recent added in v0.0.6

func (s *MemoryStore) Recent(n int) ([]MemoryDoc, error)

* Recent returns the n most recently updated non-archived MemoryDocs,

  • reading each document from its file. *
  • Parameters:
  • n (int) — maximum number of documents to return. *
  • Returns:
  • []MemoryDoc — up to n documents ordered by updated_at descending.
  • error — on database or file read failure. *
  • Example:
  • docs, err := store.Recent(5)

func (*MemoryStore) RecordSessionStats added in v0.0.6

func (s *MemoryStore) RecordSessionStats(sessionID string, budgetTokens, injectedTokens int, compressed bool, avgToksPerSec float64) error

* RecordSessionStats appends one row to the memory_stats table for the

  • session that just ended. Called at session exit by the REPL. *
  • Parameters:
  • sessionID (string) — filename of the session .spmd file; may be empty.
  • budgetTokens (int) — token budget allocated for memory injection.
  • injectedTokens (int) — tokens actually injected this session.
  • compressed (bool) — true if rolling summary fired at least once.
  • avgToksPerSec (float64) — average generation throughput across all turns. *
  • Returns:
  • error — on database write failure. *
  • Example:
  • _ = store.RecordSessionStats("harvey-session-20260526.spmd", 512, 123, false, 14.2)

func (*MemoryStore) Save added in v0.0.6

func (s *MemoryStore) Save(doc *MemoryDoc, embedder Embedder) error

* Save writes a MemoryDoc to disk and indexes it in the database. If a

  • row with the same ID already exists it is replaced. The embedding is
  • computed from doc.EmbedText() using the provided embedder. *
  • Parameters:
  • doc (*MemoryDoc) — the memory document to persist.
  • embedder (Embedder) — used to compute the embedding vector. *
  • Returns:
  • error — on file write, embedding, or database failure. *
  • Example:
  • err := store.Save(doc, embedder)

func (*MemoryStore) SearchFTS added in v0.0.6

func (s *MemoryStore) SearchFTS(query string, topK int) ([]ScoredDoc, error)

* SearchFTS returns non-archived memories matching query using FTS5 full-text

  • search. Results are ordered by relevance (best match first). Returns nil when
  • FTS5 is unavailable or query is empty. *
  • Parameters:
  • query (string) — search text passed to the FTS5 MATCH operator.
  • topK (int) — maximum number of results to return. *
  • Returns:
  • []ScoredDoc — up to topK documents ordered by descending relevance.
  • error — on database failure. *
  • Example:
  • docs, err := store.SearchFTS("git repository", 5)

func (*MemoryStore) StatsCount added in v0.0.6

func (s *MemoryStore) StatsCount() (int64, error)
  • StatsCount returns the total number of rows in the memory_stats table. *
  • Returns:
  • int64 — row count.
  • error — on database failure. *
  • Example:
  • n, _ := store.StatsCount()
  • if n >= 10 { /* show advice *‌/ }

type MemoryType added in v0.0.6

type MemoryType string
  • MemoryType identifies the category of a memory document. *
  • Example:
  • doc := &MemoryDoc{Meta: MemoryMeta{Type: MemoryTypeToolUse}}
const (
	MemoryTypeToolUse          MemoryType = "tool_use"
	MemoryTypeWorkflow         MemoryType = "workflow"
	MemoryTypeUserPreference   MemoryType = "user_preference"
	MemoryTypeWorkspaceProfile MemoryType = "workspace_profile"
	MemoryTypeProjectFact      MemoryType = "project_fact"
)

type Message

type Message struct {
	Role       string               `json:"role"`
	Content    string               `json:"content"`
	Parts      []anyllm.ContentPart `json:"parts,omitempty"`
	ToolCalls  []anyllm.ToolCall    `json:"tool_calls,omitempty"`
	ToolCallID string               `json:"tool_call_id,omitempty"`
}
  • Message represents a single chat message exchanged with a backend. *
  • Fields:
  • Role (string) — "system", "user", or "assistant".
  • Content (string) — message body; ignored when Parts is non-empty.
  • Parts ([]anyllm.ContentPart) — multimodal content parts (e.g. image + text);
  • when non-empty, overrides Content.
  • ToolCalls ([]anyllm.ToolCall) — tool call requests from the assistant.
  • ToolCallID (string) — correlates a tool-result message to its request. *
  • Example:
  • msg := Message{Role: "user", Content: "Hello!"}

type Miner added in v0.0.6

type Miner struct {
	// contains filtered or unexported fields
}

* Miner drives the mining and interactive review pipeline for a Harvey

  • session file. It calls the LLM once to propose memories, then runs an
  • interactive REPL for the user to accept, edit, skip, or supersede each
  • proposed memory. The session is recorded in the manifest only after the
  • full review completes. *
  • Example:
  • miner := NewMiner(store, manifest, ws)
  • err := miner.Mine(ctx, "agents/sessions/foo.spmd", agent, embedder, os.Stdout, os.Stdin)

func NewMiner added in v0.0.6

func NewMiner(store *MemoryStore, manifest *Manifest, ws *Workspace) *Miner

* NewMiner creates a Miner that writes to store, tracks sessions in

  • manifest, and normalises workspace paths using ws. *
  • Parameters:
  • store (*MemoryStore) — destination memory store.
  • manifest (*Manifest) — manifest tracking mined sessions.
  • ws (*Workspace) — workspace for path normalisation. *
  • Returns:
  • *Miner — ready miner. *
  • Example:
  • miner := NewMiner(store, manifest, ws)

func (*Miner) Mine added in v0.0.6

func (m *Miner) Mine(ctx context.Context, sessionPath string, agent *Agent, embedder Embedder, out io.Writer, in io.Reader) error

* Mine reads sessionPath, asks the LLM to propose memories, runs the

  • interactive review loop, and records the session in the manifest when
  • the review completes fully. An interrupted review (quit) leaves the
  • session absent from the manifest so it is re-offered on the next run. *
  • Parameters:
  • ctx (context.Context) — cancellation context.
  • sessionPath (string) — absolute path to the .spmd session file.
  • agent (*Agent) — Harvey agent providing the LLM client.
  • embedder (Embedder) — used for near-duplicate detection and
  • embedding; nil disables both.
  • out (io.Writer) — where prompts and results are written.
  • in (io.Reader) — where user input is read. *
  • Returns:
  • error — on session read, LLM, or store failure. *
  • Example:
  • err := miner.Mine(ctx, "agents/sessions/foo.spmd", agent, embedder, os.Stdout, os.Stdin)

func (*Miner) MineAuto added in v0.0.6

func (m *Miner) MineAuto(ctx context.Context, sessionPath string, agent *Agent, embedder Embedder, out io.Writer) error

* MineAuto runs non-interactive memory extraction on sessionPath. All

  • proposed memories that are not near-duplicates of existing memories are
  • saved without user review. The session is recorded in the manifest so that
  • a subsequent /memory mine run skips it (or reports "already mined"). *
  • Parameters:
  • ctx (context.Context) — cancellation context.
  • sessionPath (string) — absolute path to the session file.
  • agent (*Agent) — provides the LLM client for extraction.
  • embedder (Embedder) — used for near-duplicate detection; may be nil.
  • out (io.Writer) — status output. *
  • Returns:
  • error — on session read, LLM, or store failure. *
  • Example:
  • miner.MineAuto(ctx, "/agents/sessions/foo.spmd", agent, embedder, os.Stdout)

type ModelCache

type ModelCache struct {
	// contains filtered or unexported fields
}

* ModelCache is a SQLite3-backed store for Ollama model capability metadata.

  • The database file lives at harvey/model_cache.db inside the workspace and
  • is created automatically on first use. *
  • Example:
  • mc, err := OpenModelCache(ws, "")
  • if err != nil {
  • log.Fatal(err)
  • }
  • defer mc.Close()

func OpenModelCache

func OpenModelCache(ws *Workspace, customPath string) (*ModelCache, error)

* OpenModelCache opens (or creates) the model capability cache. customPath

  • overrides the default location (harvey/model_cache.db inside the workspace);
  • pass an empty string to use the default. *
  • Parameters:
  • ws (*Workspace) — the Harvey workspace that owns the cache file.
  • customPath (string) — override path; empty = harvey/model_cache.db. *
  • Returns:
  • *ModelCache — ready-to-use cache handle.
  • error — if the file cannot be opened or the schema cannot be applied. *
  • Example:
  • mc, err := OpenModelCache(ws, "")
  • if err != nil {
  • log.Fatal(err)
  • }
  • defer mc.Close()

func (*ModelCache) All

func (mc *ModelCache) All() ([]ModelCapability, error)
  • All returns every ModelCapability entry in the cache, ordered by name. *
  • Returns:
  • []ModelCapability — all cached entries; empty slice when the cache is empty.
  • error — non-nil on database read failure. *
  • Example:
  • caps, err := mc.All()
  • for _, c := range caps { fmt.Println(c.Name) }

func (*ModelCache) Close

func (mc *ModelCache) Close() error

* Close releases the database connection. Defer immediately after a

  • successful OpenModelCache call. *
  • Returns:
  • error — from the underlying sql.DB.Close call. *
  • Example:
  • mc, _ := OpenModelCache(ws, "")
  • defer mc.Close()

func (*ModelCache) Delete

func (mc *ModelCache) Delete(name string) error

* Delete removes the cache entry for the named model. It is a no-op when

  • the model is not in the cache. *
  • Parameters:
  • name (string) — full model name, e.g. "llama3.2:latest". *
  • Returns:
  • error — non-nil on database write failure. *
  • Example:
  • _ = mc.Delete("llama3.2:latest")

func (*ModelCache) Get

func (mc *ModelCache) Get(name string) (*ModelCapability, error)

* Get returns the cached ModelCapability for the named model, or nil when

  • no entry exists. The name must be the full model identifier including tag,
  • e.g. "llama3.2:latest". *
  • Parameters:
  • name (string) — full model name. *
  • Returns:
  • *ModelCapability — cached entry; nil if not found.
  • error — non-nil on database error (not on missing row). *
  • Example:
  • cap, err := mc.Get("llama3.2:latest")
  • if cap == nil { fmt.Println("not cached") }

func (*ModelCache) Path

func (mc *ModelCache) Path() string

Path returns the absolute path of the open model cache file.

func (*ModelCache) Set

func (mc *ModelCache) Set(cap *ModelCapability) error

* Set upserts a ModelCapability into the cache. An existing entry for the

  • same model name is completely replaced. ProbeLevel and ProbedAt are written
  • as supplied; the caller is responsible for setting them correctly. *
  • Parameters:
  • cap (*ModelCapability) — capability record to store. *
  • Returns:
  • error — non-nil on database write failure. *
  • Example:
  • err := mc.Set(&ModelCapability{Name: "llama3.2:latest", SupportsTools: CapYes})

type ModelCapability

type ModelCapability struct {
	Name                 string
	Family               string
	ParameterSize        string
	Quantization         string
	SizeBytes            int64
	ContextLength        int
	SupportsTools        CapabilityStatus
	SupportsEmbed        CapabilityStatus
	SupportsTaggedBlocks CapabilityStatus
	ProbeLevel           string
	ProbedAt             time.Time
}

* ModelCapability holds the cached capability metadata for a single Ollama

  • model. It is stored in harvey/model_cache.db and populated by
  • FastProbeModel or ThoroughProbeModel. *
  • Fields:
  • Name (string) — full model identifier, e.g. "llama3.2:latest".
  • Family (string) — model family, e.g. "llama".
  • ParameterSize (string) — human-readable size, e.g. "8.0B".
  • Quantization (string) — quantization level, e.g. "Q4_K_M".
  • SizeBytes (int64) — bytes on disk.
  • ContextLength (int) — context window in tokens; 0 = unknown.
  • SupportsTools (CapabilityStatus) — whether the model supports tool/function calling.
  • SupportsEmbed (CapabilityStatus) — whether the model can produce embeddings.
  • SupportsTaggedBlocks (CapabilityStatus) — whether the model reliably emits path-tagged code blocks.
  • ProbeLevel (string) — "none", "fast", or "thorough".
  • ProbedAt (time.Time) — when the last probe ran. *
  • Example:
  • caps, _ := cache.Get("llama3.2:latest")
  • fmt.Printf("tools: %s embed: %s tagged: %s\n", caps.SupportsTools, caps.SupportsEmbed, caps.SupportsTaggedBlocks)

func FastProbeModel

func FastProbeModel(ctx context.Context, baseURL, name string) (*ModelCapability, error)

* FastProbeModel calls /api/show for the named model and applies heuristics

  • to determine tool and embedding capability. It does not make additional
  • network calls beyond the single /api/show request. *
  • Tool support is determined by:
  • 1. The Capabilities array from /api/show (authoritative on Ollama >= 0.3).
  • 2. Known tool-call template markers as a fallback for older Ollama. *
  • Embedding support is determined by:
  • 1. A known embedding-model keyword in the model name.
  • 2. An empty or absent Template field combined with the keyword heuristic.
  • Both signals must agree to avoid false positives from base chat models
  • that happen to have a minimal template. *
  • Parameters:
  • ctx (context.Context) — controls the HTTP request lifetime.
  • baseURL (string) — Ollama server base URL, e.g. "http://localhost:11434".
  • name (string) — full model name, e.g. "llama3.2:latest". *
  • Returns:
  • *ModelCapability — populated capability record with ProbeLevel "fast".
  • error — non-nil if /api/show fails or the model is not found. *
  • Example:
  • cap, err := FastProbeModel(ctx, "http://localhost:11434", "llama3.2:latest")
  • fmt.Printf("tools: %s embed: %s\n", cap.SupportsTools, cap.SupportsEmbed)

func ThoroughProbeModel

func ThoroughProbeModel(ctx context.Context, baseURL, name string) (*ModelCapability, error)

* ThoroughProbeModel runs FastProbeModel and then makes a live /api/embed

  • request to confirm or deny embedding support definitively. A successful
  • response with a non-empty embeddings array sets SupportsEmbed = CapYes;
  • any error or empty response sets it to CapNo. Tool support is not re-tested
  • beyond what FastProbeModel determines — the capabilities API is authoritative. *
  • Parameters:
  • ctx (context.Context) — controls the HTTP request lifetime.
  • baseURL (string) — Ollama server base URL.
  • name (string) — full model name. *
  • Returns:
  • *ModelCapability — populated capability record with ProbeLevel "thorough".
  • error — non-nil if FastProbeModel fails; embed test errors are
  • absorbed into SupportsEmbed = CapNo rather than returned. *
  • Example:
  • cap, err := ThoroughProbeModel(ctx, "http://localhost:11434", "nomic-embed-text")
  • fmt.Printf("embed: %s\n", cap.SupportsEmbed)

type ModelDetail

type ModelDetail struct {
	ModelSummary
	ContextLength int
	RawParameters string
	Template      string
	Capabilities  []string // e.g. ["completion", "tools", "vision"]; nil on older Ollama
}

* ModelDetail holds the full inspection output for a single Ollama model,

  • extending ModelSummary with context-window size and Modelfile parameters. *
  • Fields:
  • ModelSummary — embedded summary fields.
  • ContextLength (int) — context window in tokens (0 if not reported).
  • RawParameters (string) — raw parameter block from the Modelfile.
  • Template (string) — chat template string. *
  • Example:
  • detail, _ := client.ShowModel(ctx, "llama3.1:8b")
  • fmt.Printf("context: %d tokens\n", detail.ContextLength)

type ModelSummary

type ModelSummary struct {
	Name          string
	Family        string
	ParameterSize string
	Quantization  string
	SizeBytes     int64
	Running       bool
}
  • ModelSummary holds the key properties of an installed Ollama model. *
  • Fields:
  • Name (string) — model identifier, e.g. "llama3.1:8b".
  • Family (string) — model family, e.g. "llama", "phi", "mistral".
  • ParameterSize (string) — human-readable parameter count, e.g. "8.0B".
  • Quantization (string) — quantization level, e.g. "Q4_K_M".
  • SizeBytes (int64) — bytes consumed on disk.
  • Running (bool) — true when the model is currently loaded by Ollama. *
  • Example:
  • summaries, _ := client.ModelSummaries(ctx)
  • for _, s := range summaries { fmt.Println(s.Name) }

type Observation

type Observation struct {
	ID        int64
	ProjectID int64
	Kind      string
	Body      string
	CreatedAt time.Time
}

* Observation represents a single timestamped note, finding, decision,

  • question, or hypothesis attached to a project. *
  • Example:
  • obs, err := kb.Observations(projectID)
  • for _, o := range obs {
  • fmt.Printf("[%s] %s\n", o.Kind, o.Body)
  • }

type OllamaClient

type OllamaClient struct {
	// contains filtered or unexported fields
}

OllamaClient is a utility type for Ollama-specific operations (model inspection, capability probing) that are not part of the LLMClient interface. For chat and embeddings use newOllamaLLMClient instead.

func NewOllamaClient

func NewOllamaClient(baseURL, model string) *OllamaClient

NewOllamaClient returns an OllamaClient for Ollama-specific utility calls (ShowModel, ModelSummaries, probing). Pass model="" when only inspecting.

func (*OllamaClient) ModelSummaries

func (o *OllamaClient) ModelSummaries(ctx context.Context) ([]ModelSummary, error)

* ModelSummaries returns a ModelSummary for every model installed on the

  • Ollama server. It also marks which models are currently loaded (running)
  • by querying /api/ps. *
  • Parameters:
  • ctx (context.Context) — controls the HTTP request lifetime. *
  • Returns:
  • []ModelSummary — one entry per installed model, sorted as Ollama returns them.
  • error — non-nil if the /api/tags request fails. *
  • Example:
  • summaries, err := client.ModelSummaries(ctx)

func (*OllamaClient) ShowModel

func (o *OllamaClient) ShowModel(ctx context.Context, model string) (ModelDetail, error)

* ShowModel fetches the full detail for a single installed model by calling

  • /api/show. The context window length is extracted from the model_info
  • metadata by searching for any key ending in ".context_length". *
  • Parameters:
  • ctx (context.Context) — controls the HTTP request lifetime.
  • model (string) — model name, e.g. "llama3.1:8b". *
  • Returns:
  • ModelDetail — full model detail; zero value on error.
  • error — non-nil if the request fails or the model is not found. *
  • Example:
  • detail, err := client.ShowModel(ctx, "llama3.1:8b")
  • fmt.Printf("context: %d tokens\n", detail.ContextLength)

type OllamaEmbedder

type OllamaEmbedder struct {
	// contains filtered or unexported fields
}

* OllamaEmbedder implements Embedder using Ollama's /api/embed endpoint.

  • It is scoped to a single embedding model on one Ollama server. *
  • Example:
  • e := NewOllamaEmbedder("http://localhost:11434", "nomic-embed-text")
  • vec, err := e.Embed("The sky is blue")

func NewOllamaEmbedder

func NewOllamaEmbedder(baseURL, model string) *OllamaEmbedder

* NewOllamaEmbedder returns an OllamaEmbedder targeting the given Ollama

  • server and embedding model. *
  • Parameters:
  • baseURL (string) — Ollama server base URL, e.g. "http://localhost:11434".
  • model (string) — embedding model name, e.g. "nomic-embed-text". *
  • Returns:
  • *OllamaEmbedder — ready to call Embed. *
  • Example:
  • e := NewOllamaEmbedder("http://localhost:11434", "nomic-embed-text")

func (*OllamaEmbedder) Embed

func (e *OllamaEmbedder) Embed(text string) ([]float64, error)

* Embed sends text to Ollama's /api/embed endpoint and returns the embedding

  • vector. Returns an error if the server is unreachable, returns a non-200
  • status, or returns no embeddings. *
  • Parameters:
  • ctx (context.Context) — controls the HTTP request lifetime.
  • text (string) — text to embed. *
  • Returns:
  • []float64 — embedding vector from the model.
  • error — on transport failure, HTTP error, or empty response. *
  • Example:
  • vec, err := e.Embed(ctx, "The sky is blue")
  • fmt.Printf("dims: %d\n", len(vec))

func (*OllamaEmbedder) Name

func (e *OllamaEmbedder) Name() string
  • Name returns the embedding model name, satisfying the Embedder interface. *
  • Returns:
  • string — model name, e.g. "nomic-embed-text". *
  • Example:
  • fmt.Println(e.Name()) // "nomic-embed-text"

type PDFInfo added in v0.0.5

type PDFInfo struct {
	Title     string
	Author    string
	Pages     int
	CreatedAt string
}
  • PDFInfo holds document-level metadata produced by pdfinfo. *
  • Fields:
  • Title (string) — document title from PDF metadata; may be empty.
  • Author (string) — document author from PDF metadata; may be empty.
  • Pages (int) — total page count.
  • CreatedAt (string) — creation date string as reported by pdfinfo.

type PDFResult added in v0.0.5

type PDFResult struct {
	Info         PDFInfo
	Text         string
	DiagramPages []int
}
  • PDFResult holds all content extracted from a PDF by pdfExtract. *
  • Fields:
  • Info (PDFInfo) — document metadata from pdfinfo.
  • Text (string) — full extracted text from pdftotext -layout; pages
  • are separated by the form-feed character (\f).
  • DiagramPages ([]int) — 1-based page numbers that appear to contain only
  • vector graphics (sparse text, no raster images).
  • Content on these pages is incomplete; flag them
  • for follow-up with a vision-capable model.

type PlaybackTurn

type PlaybackTurn struct {
	UserInput  string // USER's message text
	ModelReply string // model's original response (kept for comparison in replay)
}

PlaybackTurn holds one chat exchange extracted from a Harvey Fountain file.

type Project

type Project struct {
	ID          int64
	Name        string
	Description string
	Status      string
	CreatedAt   time.Time
}
  • Project represents a single project row in the knowledge base. *
  • Example:
  • projects, err := kb.Projects()
  • for _, p := range projects {
  • fmt.Printf("%d %s [%s]\n", p.ID, p.Name, p.Status)
  • }

type RagStore

type RagStore struct {
	// contains filtered or unexported fields
}

* RagStore is a SQLite-backed store for text chunks and their vector

  • embeddings. The database is scoped to one embedding model; mixing
  • models in the same database is prevented by an explicit consistency check. *
  • Example:
  • store, err := NewRagStore("rag_nomic_v1.db", "nomic-embed-text")
  • if err != nil { log.Fatal(err) }

func NewRagStore

func NewRagStore(dbPath, embeddingModel string) (*RagStore, error)

* NewRagStore opens (or creates) the RAG SQLite database at dbPath and

  • associates it with embeddingModel. The schema is applied on every open so
  • that the table is created on first use without manual migration. *
  • Parameters:
  • dbPath (string) — path to the SQLite database file.
  • embeddingModel (string) — name of the embedding model used to produce
  • vectors in this database; used for consistency
  • checks on every Ingest and Query call. *
  • Returns:
  • *RagStore — ready-to-use store.
  • error — if the file cannot be opened or the schema cannot be applied. *
  • Example:
  • store, err := NewRagStore("rag_nomic_v1.db", "nomic-embed-text")

func (*RagStore) Close

func (r *RagStore) Close() error
  • Close releases the database connection held by the RagStore. *
  • Returns:
  • error — if the database cannot be closed cleanly. *
  • Example:
  • if err := store.Close(); err != nil {
  • log.Println("rag store close:", err)
  • }

func (*RagStore) Count

func (r *RagStore) Count() (int64, error)
  • Count returns the total number of chunks stored in the database. *
  • Returns:
  • int64 — total chunk count.
  • error — on database failure. *
  • Example:
  • n, _ := store.Count()
  • fmt.Printf("store has %d chunks\n", n)

func (*RagStore) Ingest

func (r *RagStore) Ingest(source string, texts []string, embedder Embedder) error

* Ingest embeds each text string using embedder and stores the resulting

  • vectors in a single transaction. Returns an error if the embedder's name
  • does not match the store's embedding model. *
  • Parameters:
  • source (string) — file path or identifier recorded alongside each chunk;
  • pass "" when the source is not known.
  • texts ([]string) — text strings to embed and store.
  • embedder (Embedder) — must satisfy embedder.Name() == store's model name. *
  • Returns:
  • error — on model mismatch, embedding failure, or database write failure. *
  • Example:
  • err := store.Ingest("harvey/README.md", []string{"The sky is blue"}, embedder)

func (*RagStore) Query

func (r *RagStore) Query(query string, embedder Embedder, topK int) ([]Chunk, error)

* Query embeds query using embedder, computes cosine similarity against every

  • stored chunk, and returns the topK highest-scoring chunks in descending order.
  • Returns an error if the embedder's name does not match the store's model. *
  • Parameters:
  • query (string) — text to find similar chunks for.
  • embedder (Embedder) — must satisfy embedder.Name() == store's model name.
  • topK (int) — maximum number of chunks to return. *
  • Returns:
  • []Chunk — up to topK chunks ordered by descending similarity score.
  • error — on model mismatch, embedding failure, or database read failure. *
  • Example:
  • chunks, err := store.Query("What colour is the sky?", embedder, 3)

type RagStoreEntry

type RagStoreEntry struct {
	Name           string
	DBPath         string
	EmbeddingModel string
	ModelMap       map[string]string
	EmbedderKind   string // "ollama" (default) or "encoderfile"
	EmbedderURL    string // base URL for the embedder when EmbedderKind == "encoderfile"
}
  • RagStoreEntry describes one named RAG knowledge store in the registry. *
  • Fields:
  • Name (string) — short identifier used with /rag use and /rag new.
  • DBPath (string) — path to the SQLite database, relative to workspace root.
  • EmbeddingModel (string) — embedding model name bound to this store.
  • ModelMap (map[string]string) — generation model → embedding model overrides.
  • EmbedderKind (string) — "ollama" (default) or "encoderfile".
  • EmbedderURL (string) — base URL for the embedder; used when EmbedderKind is "encoderfile". *
  • Example:
  • e := RagStoreEntry{Name: "golang", DBPath: "agents/rag/golang.db", EmbeddingModel: "nomic-embed-text"}
  • e2 := RagStoreEntry{Name: "docs", DBPath: "agents/rag/docs.db", EmbeddingModel: "nomic-embed-text-v1_5",
  • EmbedderKind: "encoderfile", EmbedderURL: "http://localhost:8080"}

type Recorder

type Recorder struct {
	// contains filtered or unexported fields
}

Recorder writes a Harvey session to a Fountain screenplay source file, using append-writes so in-progress sessions survive crashes.

Three characters appear in the script:

  • USER — the human operator (name from $USER env, ALL CAPS)
  • HARVEY — the agent program
  • MODEL — the LLM backend (model name, ALL CAPS, e.g. GEMMA4)

Example:

r, err := NewRecorder("session.fountain", "Ollama (gemma4:latest)", "/home/user/proj")
if err != nil { log.Fatal(err) }
defer r.Close()
r.RecordTurnWithStats("Hi", "Hello!", stats, []string{"Ollama (gemma4:latest)"}, "")
r.StartAgentScene("Harvey proposes to write 1 file.")
r.RecordAgentAction("write", "hello.bash", "yes", "ok")

func NewRecorder

func NewRecorder(path, model, workspace string) (*Recorder, error)

NewRecorder creates (or truncates) the Fountain file at path, writes the title page and FADE IN:, and returns a ready-to-use Recorder.

Parameters:

path      (string) — .fountain file path for the session script.
model     (string) — backend string from Client.Name(), e.g. "Ollama (gemma4:latest)".
workspace (string) — absolute path of the Harvey workspace root.

Returns:

*Recorder — open recorder; caller must call Close() when done.
error     — if the file cannot be created or the header cannot be written.

Example:

r, err := NewRecorder("harvey-session.fountain", "Ollama (gemma4:latest)", "/home/user/proj")

func (*Recorder) Close

func (r *Recorder) Close() error

Close writes THE END. and closes the session file. After Close, the Recorder must not be used.

Returns:

error — if the file cannot be closed.

Example:

defer r.Close()

func (*Recorder) Path

func (r *Recorder) Path() string

Path returns the file path this recorder is writing to.

Returns:

string — the file path passed to NewRecorder.

Example:

fmt.Println(r.Path()) // "/home/user/harvey-session.fountain"

func (*Recorder) RecordAgentAction

func (r *Recorder) RecordAgentAction(kind, target, userChoice, outcome string) error

RecordAgentAction records one agent action as HARVEY proposing, USER confirming, and a note with the outcome.

Parameters:

kind       (string) — "write", "run", etc.
target     (string) — file path or command line.
userChoice (string) — "yes", "no", "all", or "quit".
outcome    (string) — "ok", "skipped", "aborted", or "error: <msg>".

Returns:

error — if the write fails.

Example:

r.RecordAgentAction("write", "testout/hello.bash", "yes", "ok")

func (*Recorder) RecordShellCommand

func (r *Recorder) RecordShellCommand(cmdLine, output string, exitCode int) error

RecordShellCommand appends a shell-execution scene to the recording.

Scene structure:

INT. SHELL {TIMESTAMP}

{USER}
! cmdLine                              ← dialogue (the command the user ran)

SHELL
(output text)                          ← dialogue (combined stdout+stderr)

[[shell: cmdLine — exit N]]            ← Fountain note with exit code

Parameters:

cmdLine  (string) — the shell command as typed by the user (without "!").
output   (string) — combined stdout+stderr captured from the command.
exitCode (int)    — process exit code; 0 means success.

Returns:

error — if the write fails.

Example:

r.RecordShellCommand("git status", "On branch main\n...", 0)

func (*Recorder) RecordSkillLoad

func (r *Recorder) RecordSkillLoad(name, description, body string) error

RecordSkillLoad appends a skill-activation scene to the recording.

Scene structure:

INT. SKILL {NAME} {TIMESTAMP}

Harvey executes the {name} skill.      ← action (Harvey's action)

{description}                          ← action (what the skill does)

{NAME}
{body}                                 ← dialogue (skill's output/instructions)

The skill name is uppercased to form the Fountain character name, e.g. "go-review" → "GO-REVIEW". The description is rendered as a stage-direction action block so it reads as the skill taking action. The body is the skill's dialogue — what it delivers to Harvey.

Parameters:

name        (string) — skill identifier, e.g. "go-review".
description (string) — one-line description from the skill's frontmatter.
body        (string) — full markdown body of the SKILL.md file.

Returns:

error — if the write fails.

Example:

r.RecordSkillLoad("go-review", "Review Go source code for quality issues.", body)

func (*Recorder) RecordTurn

func (r *Recorder) RecordTurn(userInput, harveyReply string) error

RecordTurn appends a chat turn without stats. See RecordTurnWithStats.

Parameters:

userInput   (string) — the user's raw input text.
harveyReply (string) — the LLM's complete response text.

Returns:

error — if the write fails.

Example:

err := r.RecordTurn("What is 2+2?", "2 + 2 = 4.")

func (*Recorder) RecordTurnWithStats

func (r *Recorder) RecordTurnWithStats(userInput, harveyReply string, stats ChatStats, models []string, routeStep string, toolCalls []ToolCallRecord) error

RecordTurnWithStats appends a full chat turn as a Fountain scene.

Scene structure:

INT. HARVEY AND {USER} TALKING {TIMESTAMP}

Harvey and {USER} are in chat mode. Model: {MODEL}. Workspace: {ws}.

{USER}
(user's input)

HARVEY
Forwarding to {MODEL}.

Harvey calls tool_name: {...}        ← action block per tool call (omitted when nil)

{MODEL}
(LLM reply)

Routing to llama3.1:8b              ← routeStep action block (omitted when empty)

{models} · {reply} reply + {ctx} ctx · {elapsed} · {tok/s} tok/s

Parameters:

userInput   (string)          — the user's raw input text.
harveyReply (string)          — the LLM's complete response text.
stats       (ChatStats)       — LLM call stats; omitted when empty.
models      ([]string)        — ordered model names that handled the turn; nil for single-model sessions.
routeStep   (string)          — routing decision text; empty when routing is disabled.
toolCalls   ([]ToolCallRecord) — structured tool invocations from the tool loop; nil when none.

Returns:

error — if the write fails.

Example:

err := r.RecordTurnWithStats("Hello", "Hi!", stats, []string{"llama3.2:1b", "Ollama (llama3.1:8b)"}, "Routing to llama3.1:8b", nil)

func (*Recorder) Rename

func (r *Recorder) Rename(newPath string) error

* Rename renames the session file on disk to newPath without ending the

  • session. The recorder continues appending to the renamed file.
  • On failure it attempts to reopen the original file so recording can continue. *
  • Parameters:
  • newPath (string) — absolute destination path for the renamed file. *
  • Returns:
  • error — if sync, close, rename, or reopen fails. *
  • Example:
  • err := r.Rename("/sessions/my-feature.spmd")

func (*Recorder) StartAgentScene

func (r *Recorder) StartAgentScene(description string) error

StartAgentScene opens a new INT. AGENT MODE scene with an action block describing the proposed actions. Call this before the first RecordAgentAction of a group.

Parameters:

description (string) — one-sentence description of what Harvey proposes to do.

Returns:

error — if the write fails.

Example:

r.StartAgentScene("Harvey proposes to write 2 file(s) to the workspace.")

type RemoteObjectInfo added in v0.0.6

type RemoteObjectInfo struct {
	URI         string
	Size        int64
	ContentType string
	IsDir       bool
}
  • RemoteObjectInfo describes a single remote object. *
  • Fields:
  • URI (string) — the full URI of the object
  • Size (int64) — size in bytes; -1 when unknown
  • ContentType (string) — MIME type; may be empty
  • IsDir (bool) — true when the entry represents a prefix/directory *
  • Example:
  • info, err := r.Stat(ctx, "s3://mybucket/file.md")
  • fmt.Println(info.Size) // e.g. 4096

type RemoteReader added in v0.0.6

type RemoteReader interface {
	Stat(ctx context.Context, uri string) (RemoteObjectInfo, error)
	Get(ctx context.Context, uri string, dst io.Writer) error
	List(ctx context.Context, prefix string) ([]RemoteObjectInfo, error)
}

* RemoteReader provides read-only access to a remote storage backend.

  • All Harvey remote access is read-only; no write operations are exposed.
  • Implementations are returned by NewRemoteReader based on the URI scheme. *
  • Methods:
  • Stat(ctx, uri) — metadata for a single object
  • Get(ctx, uri, dst) — download a single object into dst
  • List(ctx, prefix) — enumerate objects under a prefix URI (trailing /) *
  • Example:
  • r, err := NewRemoteReader("s3://mybucket/docs/spec.md")
  • if err != nil { ... }
  • var buf bytes.Buffer
  • if err := r.Get(ctx, "s3://mybucket/docs/spec.md", &buf); err != nil { ... }

func NewRemoteReader added in v0.0.6

func NewRemoteReader(uri string) (RemoteReader, error)

* NewRemoteReader returns a RemoteReader appropriate for the URI scheme.

  • Supported schemes: s3, http, https, sftp, scp.
  • Returns an error when the scheme is unsupported or required credentials
  • are absent. *
  • Parameters:
  • uri (string) — any URI with a "scheme://" prefix. *
  • Returns:
  • RemoteReader — backend implementation for the scheme.
  • error — when the scheme is unsupported or construction fails. *
  • Example:
  • r, err := NewRemoteReader("https://example.com/file.txt")
  • // r is an *httpReader

type RollingSummaryConfig added in v0.0.6

type RollingSummaryConfig struct {
	Enabled   bool
	WarnAtPct float64
	KeepTurns int
}

* RollingSummaryConfig controls automatic working-memory compression.

  • When history token count exceeds WarnAtPct of the model context window,
  • Harvey warns then compresses all but the last KeepTurns turns into a
  • short summary via a separate low-temperature LLM call. *
  • Fields:
  • Enabled (bool) — when false compression never fires; default true.
  • WarnAtPct (float64) — compress when history exceeds this fraction of the
  • model context window; default 0.80.
  • KeepTurns (int) — number of recent turns to keep verbatim; default 6. *
  • Example:
  • cfg.Memory.RollingSummary = RollingSummaryConfig{Enabled: true, WarnAtPct: 0.80, KeepTurns: 6}

type RouteEndpoint

type RouteEndpoint struct {
	Name  string
	URL   string
	Model string
	Kind  RouteKind
	Tools bool `json:",omitempty"` // opt-in tool calling via ToolExecutor
}
  • RouteEndpoint is a named remote LLM endpoint registered for @mention dispatch. *
  • Fields:
  • Name (string) — identifier used in @mention syntax (e.g. "pi2").
  • URL (string) — endpoint URL; e.g. "ollama://host:port" or "anthropic://".
  • Model (string) — default model on this endpoint; empty falls back to Config defaults.
  • Kind (RouteKind) — KindOllama, KindLlamafile, KindLlamaCpp, etc.
  • Tools (bool) — when true, dispatch uses ToolExecutor for tool calling. *
  • Example:
  • ep := RouteEndpoint{Name: "pi2", URL: "ollama://192.168.1.12:11434", Model: "llama3.1:8b", Kind: KindOllama}

type RouteKind

type RouteKind string

RouteKind identifies the protocol used to reach a registered endpoint.

const (
	// Local providers — no API key required.
	KindOllama    RouteKind = "ollama"
	KindLlamafile RouteKind = "llamafile"
	KindLlamaCpp  RouteKind = "llamacpp"

	// Cloud providers — credentials read from environment variables.
	KindAnthropic RouteKind = "anthropic"
	KindDeepSeek  RouteKind = "deepseek"
	KindGemini    RouteKind = "gemini"
	KindMistral   RouteKind = "mistral"
	KindOpenAI    RouteKind = "openai"
)

func InferRouteKind

func InferRouteKind(rawURL string) (RouteKind, error)
  • InferRouteKind returns the RouteKind implied by rawURL. *
  • Local providers (no API key):
  • ollama://host:port, http://, https:// → KindOllama
  • llamafile://host:port → KindLlamafile
  • llamacpp://host:port → KindLlamaCpp *
  • Cloud providers (API key from environment):
  • anthropic:// → KindAnthropic (ANTHROPIC_API_KEY)
  • deepseek:// → KindDeepSeek (DEEPSEEK_API_KEY)
  • gemini:// → KindGemini (GEMINI_API_KEY or GOOGLE_API_KEY)
  • mistral:// → KindMistral (MISTRAL_API_KEY)
  • openai:// → KindOpenAI (OPENAI_API_KEY) *
  • Parameters:
  • rawURL (string) — URL as typed by the user. *
  • Returns:
  • RouteKind — inferred kind.
  • error — when the URL scheme is unrecognised. *
  • Example:
  • kind, err := InferRouteKind("ollama://192.168.1.12:11434")
  • // kind = KindOllama, err = nil
  • kind, err = InferRouteKind("anthropic://")
  • // kind = KindAnthropic, err = nil

type RouteRegistry

type RouteRegistry struct {
	Endpoints map[string]*RouteEndpoint
	Enabled   bool
}
  • RouteRegistry holds all registered endpoints and the routing-enabled flag. *
  • Example:
  • rr := NewRouteRegistry()
  • rr.Add(&RouteEndpoint{Name: "pi2", URL: "ollama://192.168.1.12:11434", Kind: KindOllama})

func NewRouteRegistry

func NewRouteRegistry() *RouteRegistry
  • NewRouteRegistry returns an empty registry with routing enabled. *
  • Returns:
  • *RouteRegistry — empty, enabled registry. *
  • Example:
  • rr := NewRouteRegistry()

func (*RouteRegistry) Add

func (rr *RouteRegistry) Add(ep *RouteEndpoint)

* Add registers ep in the registry, replacing any existing endpoint with the

  • same name. *
  • Parameters:
  • ep (*RouteEndpoint) — endpoint to register. *
  • Example:
  • rr.Add(&RouteEndpoint{Name: "pi2", URL: "ollama://192.168.1.12:11434", Kind: KindOllama})

func (*RouteRegistry) Lookup

func (rr *RouteRegistry) Lookup(name string) *RouteEndpoint
  • Lookup returns the endpoint registered under name, or nil if not found. *
  • Parameters:
  • name (string) — endpoint name. *
  • Returns:
  • *RouteEndpoint — registered endpoint; nil if not found. *
  • Example:
  • ep := rr.Lookup("pi2")
  • if ep == nil { fmt.Println("not registered") }

func (*RouteRegistry) Remove

func (rr *RouteRegistry) Remove(name string)
  • Remove deletes the endpoint with the given name. No-op if not found. *
  • Parameters:
  • name (string) — endpoint name to remove. *
  • Example:
  • rr.Remove("pi2")

type ScoredDoc added in v0.0.6

type ScoredDoc struct {
	Doc   MemoryDoc
	Score float64
}
  • ScoredDoc is a MemoryDoc paired with a retrieval score. *
  • Fields:
  • Doc (MemoryDoc) — the parsed memory document.
  • Score (float64) — relevance score; higher is a better match. *
  • Example:
  • docs, _ := store.SearchFTS("git repository", 5)
  • for _, d := range docs { fmt.Printf("[%.2f] %s\n", d.Score, d.Doc.Meta.Description) }

type ScrubResult added in v0.0.6

type ScrubResult struct {
	Content string
	Flags   []string
}
  • ScrubResult holds the privacy-scrubbed content and any warning flags. *
  • Fields:
  • Content (string) — content with workspace paths normalised to
  • <workspace>. No other automatic redaction is
  • performed; sensitive patterns are only flagged.
  • Flags ([]string) — human-readable descriptions of detected patterns,
  • e.g. ["contains \"password\"", "contains \"token\""].
  • Empty when nothing suspicious was found. *
  • Example:
  • result := Scrub(rawText, "/home/alice/myproject")
  • if len(result.Flags) > 0 {
  • fmt.Println("⚠ Sensitive content detected:")
  • for _, f := range result.Flags { fmt.Println(" -", f) }
  • }

func Scrub added in v0.0.6

func Scrub(content, workspacePath string) ScrubResult

* Scrub normalises workspace paths in content and checks for sensitive

  • patterns. Path normalisation is silent and automatic; pattern detection
  • produces flags that are surfaced to the human reviewer before a memory
  • is saved. *
  • Parameters:
  • content (string) — raw text to scrub (YAML front matter or
  • Fountain body, or the combined file content).
  • workspacePath (string) — absolute workspace root path that will be
  • replaced with the placeholder <workspace>.
  • Pass "" to skip path normalisation. *
  • Returns:
  • ScrubResult — normalised content and any warning flags. *
  • Example:
  • r := Scrub("path: /home/alice/project/src", "/home/alice/project")
  • // r.Content == "path: <workspace>/src"
  • // r.Flags == []

type SessionFileInfo

type SessionFileInfo struct {
	Path    string    // absolute path to the file
	Name    string    // basename without extension
	ModTime time.Time // file modification time
}

SessionFileInfo describes a single session file found on disk.

func ListSessionFiles

func ListSessionFiles(dir string) ([]SessionFileInfo, error)

* ListSessionFiles returns all .spmd and .fountain files in dir, sorted

  • newest first by modification time. Returns nil (not an error) when dir does
  • not exist. *
  • Parameters:
  • dir (string) — directory to scan. *
  • Returns:
  • []SessionFileInfo — session files, newest first; nil if none found.
  • error — on read failure (not on missing dir). *
  • Example:
  • files, err := ListSessionFiles("agents/sessions")
  • for _, f := range files {
  • fmt.Printf("%s %s\n", f.ModTime.Format("2006-01-02 15:04"), f.Name)
  • }

type SkillCatalog

type SkillCatalog map[string]*SkillMeta

* SkillCatalog maps skill names to their parsed metadata.

  • Project-scope entries override user-scope entries when names collide. *
  • Example:
  • cat := ScanSkills("/home/user/myproject")
  • skill, ok := cat["pdf-processing"]

func ScanSkillDirs

func ScanSkillDirs(dirs []SkillSearchDir) SkillCatalog

* ScanSkillDirs discovers skills from an explicit list of search directories.

  • Directories are scanned in order; later entries override earlier ones on
  • name collision, so callers should place higher-priority paths last. *
  • Parameters:
  • dirs ([]SkillSearchDir) — ordered list of directories to scan. *
  • Returns:
  • SkillCatalog — all discovered skills, keyed by name. *
  • Example:
  • dirs := []SkillSearchDir{
  • {Path: "/home/user/agents/skills", Source: SkillSourceUser},
  • {Path: "/proj/agents/skills", Source: SkillSourceProject},
  • }
  • cat := ScanSkillDirs(dirs)

func ScanSkills

func ScanSkills(workDir, agentsDir string) SkillCatalog

* ScanSkills discovers skills from the workspace agents/skills/ directory.

  • agentsDir overrides the agents directory name (default "agents"); pass an
  • empty string to use the default. *
  • Path scanned:
  • <workDir>/<agentsDir>/skills/ *
  • Parameters:
  • workDir (string) — absolute path to the Harvey workspace root.
  • agentsDir (string) — override for the agents directory name; empty = "agents". *
  • Returns:
  • SkillCatalog — all discovered skills. *
  • Example:
  • cat := ScanSkills("/home/user/myproject", "")
  • fmt.Println(len(cat), "skills found")

type SkillMeta

type SkillMeta struct {
	Name          string
	Description   string
	License       string
	Compatibility string
	AllowedTools  string
	Trigger       string
	Variables     []SkillVariable
	Metadata      map[string]string
	Path          string
	Body          string
	Source        SkillSource
}
  • SkillMeta holds the parsed contents of a single SKILL.md file. *
  • Fields:
  • Name (string) — skill identifier from frontmatter (or inferred from dir).
  • Description (string) — when/why to use this skill; injected into the catalog.
  • License (string) — optional license identifier.
  • Compatibility (string) — optional environment requirements.
  • AllowedTools (string) — optional space-separated tool allowlist (experimental).
  • Trigger (string) — optional regex or keywords for auto-dispatch.
  • Variables ([]SkillVariable) — input variables declared in frontmatter variables: block.
  • Metadata (map[string]string) — arbitrary key-value metadata from frontmatter.
  • Path (string) — absolute path to the SKILL.md file.
  • Body (string) — markdown body after the YAML frontmatter.
  • Source (SkillSource) — "user" or "project" (for precedence tracking). *
  • Example:
  • meta, err := ParseSkillFile("/home/user/agents/skills/pdf-processing/SKILL.md")
  • fmt.Println(meta.Name, meta.Description)

func ParseSkillFile

func ParseSkillFile(path string) (*SkillMeta, error)
  • ParseSkillFile reads and parses a SKILL.md file. *
  • The file must begin with YAML frontmatter (--- ... ---) containing at
  • minimum a non-empty description field. If the name field is absent the
  • parent directory name is used instead. Malformed frontmatter (unparseable
  • YAML, missing description) returns a non-nil error and the skill is skipped
  • by callers. *
  • Parameters:
  • path (string) — absolute path to a SKILL.md file. *
  • Returns:
  • *SkillMeta — parsed skill; nil on error.
  • error — parse failure; nil on success. *
  • Example:
  • meta, err := ParseSkillFile("/home/user/agents/skills/my-skill/SKILL.md")
  • if err != nil { log.Println("skip:", err) }

type SkillSearchDir

type SkillSearchDir struct {
	Path   string
	Source SkillSource
}
  • SkillSearchDir pairs a filesystem path with its discovery scope. *
  • Fields:
  • Path (string) — directory to scan for skill subdirectories.
  • Source (SkillSource) — "user" or "project". *
  • Example:
  • dirs := []SkillSearchDir{
  • {Path: "/tmp/skills", Source: SkillSourceProject},
  • }
  • cat := ScanSkillDirs(dirs)

type SkillSetMeta

type SkillSetMeta struct {
	Name        string
	Description string
	Skills      []string
	Metadata    map[string]string
	Path        string
}
  • SkillSetMeta holds the parsed contents of a skill-set YAML file. *
  • Fields:
  • Name (string) — identifier used in /skill-set load.
  • Description (string) — human-readable purpose of the bundle.
  • Skills ([]string) — ordered list of skill names to load.
  • Metadata (map[string]string) — arbitrary key-value pairs (version, author…).
  • Path (string) — absolute path to the source YAML file. *
  • Example:
  • ss, err := ParseSkillSet("/path/to/agents/skill-sets/go-dev.yaml")
  • fmt.Println(ss.Name, ss.Skills)

func ParseSkillSet

func ParseSkillSet(path string) (*SkillSetMeta, error)
  • ParseSkillSet reads and parses a skill-set YAML file at path. *
  • Parameters:
  • path (string) — absolute path to the .yaml file. *
  • Returns:
  • *SkillSetMeta — parsed skill-set.
  • error — if the file cannot be read or parsed. *
  • Example:
  • ss, err := ParseSkillSet("/agents/skill-sets/fountain.yaml")

type SkillSource

type SkillSource string

SkillSource labels the discovery scope that produced a skill entry.

const (
	SkillSourceUser    SkillSource = "user"
	SkillSourceProject SkillSource = "project"
)

type SkillVariable

type SkillVariable struct {
	Name        string
	Description string
	Example     string
}

* SkillVariable holds metadata for one input variable declared in a skill's

  • SKILL.md frontmatter variables: block. *
  • Fields:
  • Name (string) — variable name as declared (e.g. "EDIR").
  • Description (string) — human-readable description of what the variable controls.
  • Example (string) — example value shown in help text. *
  • Example:
  • v := SkillVariable{Name: "EDIR", Description: "experiment directory", Example: "my_exp"}

type Spinner

type Spinner struct {
	// contains filtered or unexported fields
}

Spinner displays an animated 3-line block while the LLM backend processes a request:

<model source and name>
  ⎿ <Edward Lear message>      (updates every ~6 s)
     ⎿ <braille> [elapsed]     (updates every 100 ms)

The label line is omitted when label is empty. When an estimate is provided the timer shows elapsed vs. estimated (e.g. "[8s / ~12s]"); once elapsed exceeds the estimate only elapsed is shown.

type ToolCallRecord added in v0.0.6

type ToolCallRecord struct {
	Name string // tool function name, e.g. "read_file"
	Args string // raw JSON arguments string
}

ToolCallRecord holds the name and raw JSON arguments of a single tool invocation, for use in session recording.

type ToolCapable

type ToolCapable interface {
	ChatWithTools(ctx context.Context, messages []Message, tools []anyllm.Tool, out io.Writer) (ChatStats, []anyllm.ToolCall, error)
}

* ToolCapable is satisfied by LLM clients that support schema-based tool

  • calling. AnyLLMClient implements this interface; other backends that do not
  • support tools do not need to implement it. *
  • Example:
  • if tc, ok := agent.Client.(ToolCapable); ok {
  • stats, calls, err := tc.ChatWithTools(ctx, history, schemas, out)
  • }

type ToolExecutor

type ToolExecutor struct {
	Registry       *ToolRegistry
	Client         LLMClient
	MaxIterations  int
	MaxOutputBytes int
	DebugLog       *DebugLog
}

* ToolExecutor drives the multi-turn tool call loop between the LLM and the

  • tool registry. It handles streaming, tool execution, and re-submission of
  • results until the LLM produces a final text response or the iteration limit
  • is reached. *
  • Fields:
  • Registry (*ToolRegistry) — registered tool handlers.
  • Client (LLMClient) — LLM backend; must implement ToolCapable for tool calls.
  • MaxIterations (int) — hard limit on tool call rounds per user turn.
  • MaxOutputBytes (int) — cap on tool output sent back to the LLM. *
  • Example:
  • ex := NewToolExecutor(agent.Tools, agent.Client, cfg)
  • stats, err := ex.RunToolLoop(ctx, agent.History, os.Stdout)

func NewToolExecutor

func NewToolExecutor(registry *ToolRegistry, client LLMClient, cfg *Config) *ToolExecutor

* NewToolExecutor creates a ToolExecutor from the agent's tool registry,

  • client, and config. *
  • Parameters:
  • registry (*ToolRegistry) — registered tools.
  • client (LLMClient) — LLM backend.
  • cfg (*Config) — source of MaxToolCallsPerTurn and MaxOutputBytes. *
  • Returns:
  • *ToolExecutor — ready to use. *
  • Example:
  • ex := NewToolExecutor(agent.Tools, agent.Client, agent.Config)

func (*ToolExecutor) ExecuteToolCalls

func (e *ToolExecutor) ExecuteToolCalls(ctx context.Context, toolCalls []anyllm.ToolCall) ([]Message, error)

* ExecuteToolCalls runs each tool call from the LLM and returns tool-role

  • messages ready to append to the conversation history. Each message has
  • Role="tool" and ToolCallID set so the next LLM turn can correlate results. *
  • Parameters:
  • ctx (context.Context) — controls the request lifetime.
  • toolCalls ([]anyllm.ToolCall) — tool calls from the LLM's response. *
  • Returns:
  • []Message — one tool-role message per call.
  • error — if any tool execution fails (first error wins). *
  • Example:
  • results, err := ex.ExecuteToolCalls(ctx, calls)

func (*ToolExecutor) RunToolLoop

func (e *ToolExecutor) RunToolLoop(ctx context.Context, messages []Message, out io.Writer) ([]Message, ChatStats, error)

* RunToolLoop drives the full multi-turn tool conversation:

  • 1. Sends messages + tool schemas to the LLM.
  • 2. If the LLM returns tool calls, executes them and appends results.
  • 3. Repeats until the LLM returns a plain text response or MaxIterations
  • is reached — at which point an error is returned (not a silent stop). *
  • If the client does not implement ToolCapable, falls back to regular Chat. *
  • Parameters:
  • ctx (context.Context) — controls the request lifetime.
  • messages ([]Message) — full conversation history (modified in place).
  • out (io.Writer) — destination for streamed reply tokens. *
  • Returns:
  • []Message — updated history including tool results and the final reply.
  • ChatStats — stats from the final LLM call.
  • error — non-nil on transport failure or iteration limit exceeded. *
  • Example:
  • history, stats, err := ex.RunToolLoop(ctx, agent.History, os.Stdout)

type ToolHandler

type ToolHandler func(ctx context.Context, args map[string]any) (string, error)

* ToolHandler executes a named tool and returns its result as a string.

  • It receives the raw argument map decoded from the LLM's JSON arguments. *
  • Parameters:
  • ctx (context.Context) — controls the request lifetime.
  • args (map[string]any) — decoded JSON arguments from the LLM. *
  • Returns:
  • string — tool output to be sent back to the LLM.
  • error — non-nil if the tool failed; the error message is sent back as a tool error. *
  • Example:
  • handler := func(ctx context.Context, args map[string]any) (string, error) {
  • path, ok := args["path"].(string)
  • if !ok { return "", fmt.Errorf("path must be a string") }
  • data, err := os.ReadFile(path)
  • return string(data), err
  • }

type ToolRegistry

type ToolRegistry struct {
	// contains filtered or unexported fields
}

* ToolRegistry manages all available schema-based tools. It is safe for

  • concurrent use. *
  • Example:
  • r := NewToolRegistry()
  • r.RegisterTool("echo", "Return the input", map[string]any{...}, handler)
  • schemas := r.GetToolSchemas()

func NewToolRegistry

func NewToolRegistry() *ToolRegistry
  • NewToolRegistry creates an empty ToolRegistry. *
  • Returns:
  • *ToolRegistry — empty, ready to register tools. *
  • Example:
  • r := NewToolRegistry()

func (*ToolRegistry) Dispatch

func (r *ToolRegistry) Dispatch(ctx context.Context, name, argsJSON string, maxBytes int) (string, error)

* Dispatch looks up the named tool and executes it with args decoded from

  • the LLM's raw JSON argument string. Output is capped at maxBytes. *
  • Parameters:
  • ctx (context.Context) — controls the request lifetime.
  • name (string) — tool name from the LLM's tool_call.
  • argsJSON (string) — raw JSON argument string from FunctionCall.Arguments.
  • maxBytes (int) — output size cap; 0 uses defaultMaxOutputBytes. *
  • Returns:
  • string — tool result (possibly truncated).
  • error — if the tool is unknown, arguments are invalid, or the handler fails. *
  • Example:
  • result, err := r.Dispatch(ctx, "read_file", `{"path":"main.go"}`, 65536)

func (*ToolRegistry) GetTool

func (r *ToolRegistry) GetTool(name string) (anyllm.Tool, ToolHandler, bool)
  • GetTool returns the schema and handler for a tool by name. *
  • Parameters:
  • name (string) — the tool name. *
  • Returns:
  • anyllm.Tool — the JSON Schema definition.
  • ToolHandler — the executor function.
  • bool — false if the name is not registered. *
  • Example:
  • schema, handler, ok := r.GetTool("read_file")

func (*ToolRegistry) GetToolSchemas

func (r *ToolRegistry) GetToolSchemas() []anyllm.Tool

* GetToolSchemas returns all registered anyllm.Tool schemas in alphabetical

  • order, ready to pass in CompletionParams.Tools. *
  • Returns:
  • []anyllm.Tool — tool schema slice. *
  • Example:
  • params.Tools = r.GetToolSchemas()

func (*ToolRegistry) Len

func (r *ToolRegistry) Len() int
  • Len returns the number of registered tools. *
  • Returns:
  • int — tool count. *
  • Example:
  • fmt.Println(r.Len())

func (*ToolRegistry) RegisterTool

func (r *ToolRegistry) RegisterTool(name, description string, parameters map[string]any, handler ToolHandler)
  • RegisterTool adds or replaces a tool in the registry. *
  • Parameters:
  • name (string) — unique function name (must be a valid identifier).
  • description (string) — human-readable description sent to the LLM.
  • parameters (map[string]any) — JSON Schema object describing the tool's parameters.
  • handler (ToolHandler) — Go function that executes the tool. *
  • Example:
  • r.RegisterTool("read_file", "Read a file", map[string]any{
  • "type": "object",
  • "properties": map[string]any{
  • "path": map[string]any{"type": "string"},
  • },
  • "required": []string{"path"},
  • }, myHandler)

type UnifiedMemory added in v0.0.6

type UnifiedMemory struct {
	// contains filtered or unexported fields
}

* UnifiedMemory provides budget-aware retrieval across all memory silos:

  • workspace_profile and project_fact (factual, always first), experiential
  • memories (FTS5 + optional cosine similarity), RAG chunks, and KB
  • observations. *
  • Example:
  • um := NewUnifiedMemory(store, &cfg.Memory, ws)
  • results, err := um.Recall("git error", embedder, 512)
  • agent.AddMessage("user", FormatContext(results))

func NewUnifiedMemory added in v0.0.6

func NewUnifiedMemory(store *MemoryStore, cfg *MemoryConfig, ws *Workspace) *UnifiedMemory
  • NewUnifiedMemory creates a UnifiedMemory instance backed by the given store. *
  • Parameters:
  • store (*MemoryStore) — open memory store.
  • cfg (*MemoryConfig) — memory configuration for RAG and KB access.
  • ws (*Workspace) — workspace for resolving database paths; may be nil
  • to disable RAG and KB retrieval. *
  • Returns:
  • *UnifiedMemory — ready to call Recall. *
  • Example:
  • um := NewUnifiedMemory(store, &cfg.Memory, ws)
  • results, _ := um.Recall("context query", nil, 512)

func (*UnifiedMemory) Recall added in v0.0.6

func (u *UnifiedMemory) Recall(query string, embedder Embedder, budget int) ([]UnifiedResult, error)

* Recall retrieves memories from all silos in priority order, stopping when

  • the token budget is exhausted. Factual types (workspace_profile,
  • project_fact) always appear first with score 1.0. Experiential types are
  • ranked by FTS5 text match and optionally by cosine similarity. RAG chunks
  • and KB observations are appended last if budget permits. *
  • Parameters:
  • query (string) — search text; may be empty to return factual-only.
  • embedder (Embedder) — cosine similarity embedder; nil disables the slow
  • path for experiential memories and RAG.
  • budget (int) — maximum estimated tokens to return; 0 means no limit. *
  • Returns:
  • []UnifiedResult — results in priority order, each within the budget.
  • error — on store or retrieval failure. *
  • Example:
  • results, err := um.Recall("git error", embedder, 512)
  • fmt.Println(FormatContext(results))

type UnifiedResult added in v0.0.6

type UnifiedResult struct {
	Source  string
	ID      string
	Content string
	Score   float64
	Tokens  int
}
  • UnifiedResult is one retrieved item from any memory silo. *
  • Fields:
  • Source (string) — origin silo: "workspace_profile", "project_fact",
  • "experiential", "rag", or "kb".
  • ID (string) — identifier within the silo (memory ID, chunk ID, etc.).
  • Content (string) — text to inject into the context window.
  • Score (float64) — similarity or relevance score; 1.0 for factual types.
  • Tokens (int) — estimated token count for Content (set by Recall). *
  • Example:
  • results, err := um.Recall("git error", embedder, 512)
  • for _, r := range results {
  • fmt.Printf("[%s %.2f] %s\n", r.Source, r.Score, r.Content)
  • }

type Workspace

type Workspace struct {
	// Root is the absolute, canonicalised path of the working directory.
	Root string
}

* Workspace anchors Harvey to a single root directory and enforces that all

  • file operations remain within it. The root is resolved to an absolute,
  • symlink-free path at construction time so that later checks cannot be
  • bypassed by symlinks or relative ".." components. *
  • Harvey's internal state directory is always at <Root>/harvey/. *
  • Example:
  • ws, err := NewWorkspace(".")
  • if err != nil {
  • log.Fatal(err)
  • }
  • data, err := ws.ReadFile("README.md")

func NewWorkspace

func NewWorkspace(dir string) (*Workspace, error)

* NewWorkspace creates a Workspace rooted at dir, resolving the path to an

  • absolute, symlink-free form. The agents/ sub-directory is created if it
  • does not exist. *
  • Parameters:
  • dir (string) — path to use as the workspace root; "." uses the current
  • working directory. *
  • Returns:
  • *Workspace — the initialised workspace.
  • error — if dir cannot be resolved or agents/ cannot be created. *
  • Example:
  • ws, err := NewWorkspace(".")
  • if err != nil {
  • log.Fatal(err)
  • }

func (*Workspace) AbsPath

func (ws *Workspace) AbsPath(rel string) (string, error)

* AbsPath resolves rel relative to the workspace root and verifies that the

  • resulting path lies inside the root. It returns an error for any path that
  • would escape the workspace (e.g. via ".." components or absolute paths
  • outside Root). *
  • Security: Uses filepath.Clean to resolve ".." and "." components, then verifies
  • the cleaned path is a subtree of ws.Root. This prevents path traversal attacks. *
  • Parameters:
  • rel (string) — relative path to resolve; may use "/" as separator. *
  • Returns:
  • string — absolute, cleaned path inside the workspace.
  • error — if the resolved path escapes the workspace root. *
  • Example:
  • p, err := ws.AbsPath("src/main.go")
  • // p == "/home/user/myproject/src/main.go"
  • _, err = ws.AbsPath("../../etc/passwd") // returns error

func (*Workspace) HarveyDir

func (ws *Workspace) HarveyDir() string

* HarveyDir returns the absolute path of Harvey's internal state directory

  • (agents/) inside the workspace root. *
  • Returns:
  • string — absolute path to <Root>/agents/ *
  • Example:
  • fmt.Println(ws.HarveyDir()) // "/home/user/myproject/agents"

func (*Workspace) ListDir

func (ws *Workspace) ListDir(path string) ([]fs.DirEntry, error)

* ListDir returns the directory entries at path (relative to the workspace

  • root). The path must not escape the workspace. *
  • Parameters:
  • path (string) — relative path of the directory to list; use "." for root. *
  • Returns:
  • []fs.DirEntry — sorted directory entries.
  • error — if the path escapes the workspace or the read fails. *
  • Example:
  • entries, err := ws.ListDir(".")
  • for _, e := range entries {
  • fmt.Println(e.Name())
  • }

func (*Workspace) MkdirAll

func (ws *Workspace) MkdirAll(path string) error

* MkdirAll creates path (relative to the workspace root) and any missing

  • parent directories. The path must not escape the workspace. *
  • Parameters:
  • path (string) — relative directory path to create. *
  • Returns:
  • error — if the path escapes the workspace or directory creation fails. *
  • Example:
  • err := ws.MkdirAll("docs/api")

func (*Workspace) ReadFile

func (ws *Workspace) ReadFile(path string) ([]byte, error)

* ReadFile reads the file at path (relative to the workspace root) and

  • returns its contents. The path must not escape the workspace. *
  • Parameters:
  • path (string) — relative path to the file. *
  • Returns:
  • []byte — file contents.
  • error — if the path escapes the workspace or the file cannot be read. *
  • Example:
  • data, err := ws.ReadFile("HARVEY.md")

func (*Workspace) WriteFile

func (ws *Workspace) WriteFile(path string, data []byte, perm fs.FileMode) error

* WriteFile writes data to path (relative to the workspace root), creating

  • parent directories as needed. The path must not escape the workspace. *
  • Parameters:
  • path (string) — relative path to write; parent dirs are created.
  • data ([]byte) — bytes to write.
  • perm (fs.FileMode) — file permission bits (e.g. 0o644). *
  • Returns:
  • error — if the path escapes the workspace or the write fails. *
  • Example:
  • err := ws.WriteFile("notes/todo.md", []byte("# TODO\n"), 0o644)

Directories

Path Synopsis
cmd
harvey command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL