harvey

package module
v0.0.20 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: AGPL-3.0-or-later Imports: 59 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 written in Go and designed to use Llamafile models or Ollama server to access language models locally. It is a terminal based application.

The Harvey name was inspired by the play of that name by Mary Chase. I saw parallels between the story Harvey and my personal language model agent. Many people think of agents only in the context of very big companies. I think small models running on small or tiny computers are an opportunity. Harvey, is a small agent for small and tiny computers and is a play on a mythic creature. Harvey is a Púca, a software Púca. Harvey can be fun for those who take time for it. It runs on a little computers. Have an adventure and some fun with Harvey.

Security Note

Harvey is experimental — a working proof of concept, not production-ready software. Letting a probabilistic model direct command execution is an inherently risky attack surface; Harvey mitigates this with safe mode, workspace sandboxing, permission checks, audit logging, and security reviews with each release, but the risk is never zero. Don't use Harvey where the risks might endanger your data, people, or planet. See SECURITY.md for details.

Features

Language Model Support
  • Llamafile (primary): register and run local model binaries — no server required
  • Ollama: connect to a local Ollama server for broader model selection
  • Cloud routes: Anthropic, DeepSeek, Gemini, Mistral, and OpenAI via configured routes
  • Multi-model dispatch via @mention and model aliasing; routing feedback shown in spinner
Core Capabilities
  • Interactive terminal REPL sandboxed to a workspace directory
  • Auto-execute: tagged code blocks in model replies are written to workspace files automatically
  • HARVEY.md provides a customizable system prompt per workspace
  • Context utilization hint [ctx: N%] in spinner when approaching the model's context window
Knowledge, Memory & Sessions
  • Three-silo memory: RAG vector stores, session-experience memory with rolling summaries, and a SQLite knowledge base
  • Sessions recorded as human-readable Fountain screenplay (.spmd) files — replay, continue, or mine them for memories
  • Model provenance recorded in session headers for audit and replay accuracy
  • Pinned context and conversation summarization to manage the context window
File & Code Support
  • Code-aware RAG chunking, documentation extraction, and ANSI syntax highlighting (13 languages)
  • Automatic code formatting on write_file: gofmt, clang-format, black, rustfmt, prettier, and built-in Pascal/Oberon/Basic formatters
  • PDF text extraction via poppler; image reading via vision-capable model routes
  • Remote RAG ingest: s3://, sftp://, scp://, http://, https:// URIs
  • File-reference injection: for models that ignore the tools schema, Harvey pre-injects workspace files mentioned in the prompt so they can still work with file content
Extensibility
  • SKILL.md skills, bundled skill sets, and multi-step prompt pipelines
  • Git integration and per-workspace profile templates

Quick Start

  1. Download a llamafile from the Mozilla AI pre-built models page and make it executable
  2. Install Harvey: run the installer for your platform
    • Linux/macOS: ./installer.sh
    • Windows: run installer.ps1 in PowerShell
  3. Run: harvey
  4. Try it:
    harvey > /model use
    harvey > /read LICENSE
    harvey > /help
    

See Getting Started and Installation for detailed instructions.

Platform Support

Harvey runs on:

  • Linux: x86_64, aarch64, armv7l (including Raspberry Pi OS)
  • macOS: Intel and Apple Silicon (M1 and above)
  • Windows: x86_64

Documentation

Release Notes

  • version: 0.0.19

  • status: active

  • released: 2026-10-10

  • Behaviour changes, see CHANGES.md upgrade notes: llama.cpp models are looked for in llama.cpp's cache ($LLAMA_CACHE, else ~/.cache/llama.cpp) and ~/Models is for llamafiles only, so set llamacpp.models_dir to keep the old directory (harvey DR-0031, proposed); skills.catalog is off by default (set skills: catalog: full to restore it); the command line now beats harvey.yaml for --llamafile-url, --llamafile-dir, -r, --record-file, --resume, --continue, --replay, --replay-output and --replay-continue as well as --ollama and -m, and HARVEY_LLAMAFILE_DIR beats llamafile.models_dir

  • A chat stream that ends before its final chunk is an error (ErrStreamTruncated, exit 74) instead of an empty reply recorded as a success

  • Hailo (AI HAT+ 2) is an engine beside Ollama (harvey DR-0030): a hailo: section in harvey.yaml, card and server detected apart, engine/model names (a bare name on both engines asks, or is exit 2 unattended), the catalog shown as not pulled with /model pull [--yes] NAME, and a capability table so harvey stops sending tools or asking for embeddings where Hailo has none

  • Per-model prompt limits: /model limit, the system prompt and history fitted to the limit, a turn over it refused before sending, and a failed turn retried on smaller prompts that teaches the limit; the model cache is keyed by engine and model

  • /memory mine reads a session too large for the model in parts, records an empty session as empty, and remembers a model that failed on a session so auto-mine does not retry it; a RAG retrieval failure is reported once per session instead of silently

  • harvey completion bash|powershell [-install] for shell completion of verbs, options and help topics

  • A write offer no longer treats a command, end of input or arbitrary text as an answer; piping /exit used to create a file named exit

  • Switching to a llama.cpp model mid-session keeps the --debug log and records the switch, as the Ollama paths already did

  • make test-models runs live model tests and skips a missing model system with the reason; make build no longer runs cmt, make generate does

  • knowledge bumped to the released v0.0.20

Authors
  • Doiel, R. S.

Software Requirements

  • Llamafile v0.10 models or Ollama plus Ollama models
Software Suggestions
  • Go >= 1.26.4
  • CMTools >= 0.0.45
  • Pandoc >= 3.9
  • GNU Make >= 3.8

Getting Help & License

Documentation

Overview

Package harvey — backend.go defines the ManagedBackend abstraction shared by OllamaBackend, LlamafileBackend, and LlamaCppBackend.

Package harvey — backend_llamacpp.go implements ManagedBackend for llama.cpp's llama-server.

Package harvey — backend_llamafile.go implements ManagedBackend for llamafile.

Package harvey — backend_ollama.go implements ManagedBackend for Ollama.

Package harvey — backend_startup.go handles backend probing and the interactive model-selection flow that runs at session start.

Package harvey — commands_kb.go implements the /kb slash command family for managing the knowledge base.

Package harvey — commands_memory.go implements the /memory slash command family for managing Harvey's experience memory store.

Package harvey — commands_rag.go implements the /rag slash command family for managing RAG stores and ingesting documents.

Package harvey — commands_route.go implements the /route slash command family for managing remote LLM endpoints.

Package harvey — commands_skill.go implements the /skill and /skill-set slash command families for managing Harvey agent skills.

Package harvey — config_yaml.go defines the on-disk YAML adapter types that map between harvey.yaml and the in-memory Config struct. These types are only used by LoadHarveyYAML and the Save* functions in config.go; they are never exposed to callers outside this package.

Package harvey — grounding.go detects when a model's response contains quoted text that does not appear in any file content retrieved via tool calls during the same turn, which is a strong signal of hallucination.

Package harvey — llamafile.go implements llamafile model registration, switching, and management, reached through the /model command.

Package harvey — llamafile_service.go provides helpers for managing a llamafile inference server process: probing whether one is running and launching it as a background service when it is not.

Package harvey — model_picker.go implements the unified /model use picker that aggregates all locally available models across llamafile, llama.cpp, and Ollama backends.

Package harvey — plan.go implements bounded-context plan-execute support. Plans are stored as GFM checklists in agents/plan.md so they survive /clear and session restarts. Each step is executed with a fresh context containing only the system prompt + current plan state, keeping turn times flat regardless of how many steps have been completed.

Package harvey — plan_cmd.go implements the /plan slash command family for generating and executing bounded-context task plans.

Package harvey — sensor_event.go introduces the SensorEvent type: a single shape for every sensor/status signal surfaced to the user during or after a turn (tool-call outcomes, grounding-check findings, tool-call- format warnings). This is pure routing plumbing per harness-prerequisite-refactor-plan.md Phase C — rendering is unchanged from before this type existed. See harness-engineering-exploration.md Direction C for the planned follow-on (a two-view sensor sidecar distinguishing human vs. agent-facing output); this type is the prerequisite for that design, not the design itself.

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/.

Package harvey — skill_suggestor.go implements /skill suggest, which reads a session transcript and proposes multi-step workflows as skill candidates.

Package harvey — workspace_init.go implements the /workspace init command and the --init-from CLI flag. Both copy model aliases from a source workspace or YAML file into the current workspace without any runtime inheritance.

Index

Constants

View Source
const (
	// SkillsCatalogOff keeps the skills catalog out of the system prompt. The
	// skills are still scanned and their slash commands registered. This is the
	// default: the model cannot load a skill itself, so the catalog only costs
	// tokens.
	SkillsCatalogOff = "off"
	// SkillsCatalogFull appends the full catalog (name and a one-line
	// description per skill) to the system prompt.
	SkillsCatalogFull = "full"
)

Values for SkillsConfig.Catalog (harvey.yaml skills.catalog).

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

Permission types

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

	// ReleaseDate, the date version.go was generated
	ReleaseDate = "2026-10-20"

	// ReleaseHash, the Git hash when version.go was generated
	ReleaseHash = "cd480d8"
	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 DefaultRetractionWatchURL = "https://api.retractionwatch.com/api/v1/retractiondata/"

DefaultRetractionWatchURL is the base URL for the Retraction Watch API.

View Source
const ManifestStatusEmpty = "empty"

ManifestStatusEmpty marks a manifest entry for a session that had no dialogue to mine. The model was never asked about it.

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.

View Source
const ToolModeAuto = ""

* ToolModeAuto is the zero value for the ToolMode field of ModelCapability.

  • When ToolMode is Auto, Harvey falls back to CapabilityStatus-based logic:
  • toolsReliable() returns true iff SupportsTools == CapYes. *
  • Example:
  • cap.ToolMode = ToolModeAuto // clear a previously set override
View Source
const ToolModeInject = "inject"

* ToolModeInject tells Harvey to skip tool calling entirely and pre-inject

  • file content from the prompt directly (injectFileContext). Used for models
  • that reliably ignore the tools schema. *
  • Example:
  • cap.ToolMode = ToolModeInject
View Source
const ToolModeNone = "none"

* ToolModeNone disables both tool calling and file injection for the model.

  • Harvey sends the prompt as plain text and does not attempt any tool dispatch. *
  • Example:
  • cap.ToolMode = ToolModeNone
View Source
const ToolModeProse = "prose"

* ToolModeProse forces Harvey to use the prose JSON-fence fallback for the

  • model (tryExecuteProseToolCalls). RunToolLoop is bypassed even when
  • SupportsTools == CapYes. *
  • Example:
  • cap.ToolMode = ToolModeProse
View Source
const ToolModeStructured = "structured"

* ToolModeStructured forces Harvey to use the OpenAI-style structured

  • tool_calls API path (RunToolLoop) for the model, regardless of the
  • SupportsTools capability status. *
  • Example:
  • cap.ToolMode = ToolModeStructured

Variables

View Source
var (
	ClassOK           = ExitClass{"ok", 0}
	ClassNegative     = ExitClass{"negative", 1}
	ClassUsage        = ExitClass{"usage", 2}
	ClassData         = ExitClass{"data", 65}
	ClassNoInput      = ExitClass{"no_input", 66}
	ClassUnavailable  = ExitClass{"unavailable", 69}
	ClassInternal     = ExitClass{"internal", 70}
	ClassCantCreate   = ExitClass{"cant_create", 73}
	ClassIO           = ExitClass{"io", 74}
	ClassTempFail     = ExitClass{"temp_fail", 75}
	ClassNoPermission = ExitClass{"no_permission", 77}
	ClassConfig       = ExitClass{"config", 78}
)

* The twelve classes of the workspace convention. The numbers are the BSD

  • sysexits.h values except 0, 1 and 2. 64, 67, 68, 71, 72 and 76 are not
  • used, and nothing above 125 may be, because the shell owns those. *
  • Example:
  • err := harvey.NoInputf("corpus %s does not exist", path) // exits 66
View Source
var (

	// HelpText is the primary harvey(1) man page. Displayed by harvey --help
	// or harvey help (no topic). Generates harvey.1.md.
	HelpText = `` /* 14123-byte string literal not displayed */

	// FirstRunWizardText is shown at startup when no backend is reachable and
	// no backend has been configured. It guides new users to their first model.
	FirstRunWizardText = `` /* 552-byte string literal not displayed */

	// ModelHelpText is shown by /help model and harvey --help model.
	ModelHelpText = `` /* 6303-byte string literal not displayed */

	// ModelAliasHelpText is shown by /help model-alias and harvey --help model-alias.
	// It covers @mention inline switching and the /model alias subcommands.
	ModelAliasHelpText = `` /* 3181-byte string literal not displayed */

	// RoutingHelpText is shown by /help routing and harvey --help routing.
	// Generates harvey-routing.7.md.
	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 local llamafile server (running on default port 8080)
  /route add lf llamafile://localhost:8080 bonsai-8b

  # Register a local llama.cpp server (llama-server on port 8081)
  /route add cpp llamacpp://localhost:8081 phi4-Q4_K_M

  # Register a Pi cluster node running Ollama
  /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

  # Send a task to the llamafile server
  @lf summarise this function in one sentence

  # Send a task to the llama.cpp server
  @cpp write a unit test for the Parse function

  # Run a quick task on a Pi node
  @pi2 what does this error mean?

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

  # Local model handles everything else (no @mention)
  what is the overall structure of this package?
~~~

# SLASH COMMANDS

~~~
  /route add NAME URL [MODEL]        register a remote endpoint
                                       @lf     llamafile://localhost:8080 bonsai-8b
                                       @cpp    llamacpp://localhost:8081 phi4-Q4_K_M
                                       @pi2    ollama://192.168.1.12:11434 llama3.1:8b
                                       @claude anthropic:// claude-sonnet-4-20250514
  /route remove NAME                 unregister an endpoint (alias: rm)
  /route rm NAME                     alias for remove
  /route use [NAME]                  set NAME as the sticky route so all prompts
                                       dispatch there without an @mention; omit NAME
                                       to clear the sticky route
  /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.` + "`" + `

# SEE ALSO

  /model use NAME        — backend-agnostic model switching
  /help model            — list, start, and switch local models
  /help security         — API key filtering for cloud endpoints

`

	// FilesHelpText is shown by /help files and harvey --help files.
	// Generates harvey-files.7.md.
	FilesHelpText = `` /* 1064-byte string literal not displayed */

	// FileTreeHelpText is shown by /help file-tree and harvey --help file-tree.
	// Generates harvey-file-tree.7.md.
	FileTreeHelpText = `` /* 857-byte string literal not displayed */

	// ReadHelpText is shown by /help read and harvey --help read.
	// Generates harvey-read.7.md.
	ReadHelpText = `` /* 2090-byte string literal not displayed */

	// ReadDirHelpText is shown by /help read-dir and harvey --help read-dir.
	// Generates harvey-read-dir.7.md.
	ReadDirHelpText = `` /* 1587-byte string literal not displayed */

	// ReadPDFHelpText is shown by /help read-pdf and harvey --help read-pdf.
	// Generates harvey-read-pdf.7.md.
	ReadPDFHelpText = `` /* 2203-byte string literal not displayed */

	// AttachHelpText is shown by /help attach and harvey --help attach.
	// Generates harvey-attach.7.md.
	AttachHelpText = `` /* 2411-byte string literal not displayed */

	// WorkspaceHelpText is shown by /help workspace and harvey --help workspace.
	// Generates harvey-workspace.7.md.
	WorkspaceHelpText = `` /* 1753-byte string literal not displayed */

	// WriteHelpText is shown by /help write and harvey --help write.
	// Generates harvey-write.7.md.
	WriteHelpText = `` /* 1323-byte string literal not displayed */

	// FormatHelpText is shown by /help format and harvey --help format.
	// Generates harvey-format.7.md.
	FormatHelpText = `` /* 3421-byte string literal not displayed */

	// SearchHelpText is shown by /help search and harvey --help search.
	// Generates harvey-search.7.md.
	SearchHelpText = `` /* 1315-byte string literal not displayed */

	// GitHelpText is shown by /help git and harvey --help git.
	// Generates harvey-git.7.md.
	GitHelpText = `` /* 1534-byte string literal not displayed */

	// RunHelpText is shown by /help run and harvey --help run.
	// Generates harvey-run.7.md.
	RunHelpText = `` /* 1694-byte string literal not displayed */

	// ClearHelpText is shown by /help clear and harvey --help clear.
	// Generates harvey-clear.7.md.
	ClearHelpText = `` /* 1527-byte string literal not displayed */

	// ContextHelpText is shown by /help context and harvey --help context.
	// Generates harvey-context.7.md.
	ContextHelpText = `` /* 1994-byte string literal not displayed */

	// SummarizeHelpText is shown by /help summarize and harvey --help summarize.
	// Also dispatched for the "compact" alias. Generates harvey-summarize.7.md.
	SummarizeHelpText = `` /* 1813-byte string literal not displayed */

	// EditingHelpText is shown by /help editing and harvey --help editing.
	// Also dispatched for "edit" and "keys" aliases. Generates harvey-editing.7.md.
	EditingHelpText = `` /* 1777-byte string literal not displayed */

	// StatusHelpText is shown by /help status and harvey --help status.
	// Generates harvey-status.7.md.
	StatusHelpText = `` /* 2586-byte string literal not displayed */

	// HintHelpText is shown by /help hint and harvey --help hint.
	// Generates harvey-hint.7.md.
	HintHelpText = `` /* 2346-byte string literal not displayed */

	// RecordHelpText is shown by /help record and harvey --help record.
	// Generates harvey-record.7.md.
	RecordHelpText = `` /* 1679-byte string literal not displayed */

	// RenameHelpText is shown by /help rename and harvey --help rename.
	// Generates harvey-rename.7.md.
	RenameHelpText = `` /* 957-byte string literal not displayed */

	// SessionHelpText is shown by /help session and harvey --help session.
	// Generates harvey-session.7.md.
	SessionHelpText = `` /* 3119-byte string literal not displayed */

	// RagHelpText is shown by /help rag and harvey --help rag.
	// Generates harvey-rag.7.md.
	RagHelpText = `` /* 9343-byte string literal not displayed */

	// KBHelpText is shown by /help kb and harvey --help kb.
	// Also dispatched for "knowledge" and "knowledge-base" aliases. Generates harvey-kb.7.md.
	KBHelpText = `` /* 6640-byte string literal not displayed */

	// MemoryHelpText is shown by /help memory and harvey --help memory.
	// Also dispatched for "profile" and "recall" aliases. Generates harvey-memory.7.md.
	MemoryHelpText = `` /* 9150-byte string literal not displayed */

	// LearnHelpText is shown by /help learn and harvey --help learn.
	// Generates harvey-learn.7.md.
	LearnHelpText = `` /* 3327-byte string literal not displayed */

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

	// SkillSetHelpText is shown by /help skill-set and harvey --help skill-set.
	// Generates harvey-skill-set.7.md.
	SkillSetHelpText = `` /* 1994-byte string literal not displayed */

	// SecurityHelpText is shown by /help security and harvey --help security.
	// Also dispatched for "safemode", "safe", "permissions", "audit" aliases.
	// Generates harvey-security.7.md.
	SecurityHelpText = `` /* 3428-byte string literal not displayed */

	// PipelineHelpText is shown by /help pipeline and harvey --help pipeline.
	// Generates harvey-pipeline.7.md.
	PipelineHelpText = `` /* 2732-byte string literal not displayed */

	// PlanHelpText is shown by /help plan and harvey --help plan.
	// Generates harvey-plan.7.md.
	PlanHelpText = `` /* 2788-byte string literal not displayed */

	// LoopHelpText is shown by /help loop and harvey --help loop.
	// Generates harvey-loop.7.md.
	LoopHelpText = `` /* 2834-byte string literal not displayed */

	// BuiltinToolsHelpText is shown by /help builtin-tools and harvey --help builtin-tools.
	// Also dispatched for "tools" and "builtins" aliases. Generates harvey-builtin-tools.7.md.
	BuiltinToolsHelpText = `` /* 3133-byte string literal not displayed */

	// InspectHelpText is shown by /help inspect and harvey --help inspect.
	// Generates harvey-inspect.7.md.
	InspectHelpText = `` /* 1414-byte string literal not displayed */

	// AssayHelpText is the help page for the assay evaluation harness.
	// Displayed by: assay --help
	AssayHelpText = `` /* 6430-byte string literal not displayed */

)
View Source
var (
	PDFToolsHelpText       string
	GettingStartedHelpText string
)

Package-level help text vars loaded from embedded guides at init time. These are accessible to cmdHelp alongside the other HelpText vars in helptext.go.

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",
	"kb", "man",
}

* DefaultConfig returns a Config populated with sensible defaults. WorkDir

  • defaults to "." (the process working directory at startup). Session.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.Ollama.URL) // "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 EmbeddedTemplates embed.FS
View Source
var ErrAutoArchived = errors.New("memory auto-archived: confidence below threshold")

ErrAutoArchived is returned by SetConfidence when the memory's confidence fell to or below the auto-archive threshold (0.2) and Archive was called.

View Source
var ErrInvalid = errors.New("invalid value")

* ErrInvalid marks an error raised because a value is not acceptable. It

  • classifies as usage (exit 2), which is right when the value came from the
  • command line. A value read from a file is wrong content instead: wrap the
  • error with ClassedAs(ClassData, err), and the outermost class wins. *
  • Example:
  • return fmt.Errorf("--overlap %q: %w", v, harvey.ErrInvalid)
View Source
var ErrNotFound = errors.New("not found")

* ErrNotFound marks an error raised because a named thing does not exist: a

  • model, a skill, a session. It classifies as negative (exit 1): the command
  • ran correctly and the answer is no. Wrap it with %w so the message says
  • what was not found. *
  • Example:
  • return fmt.Errorf("model %q: %w", name, harvey.ErrNotFound)
View Source
var ErrStreamTruncated = errors.New("chat stream truncated")

* ErrStreamTruncated marks a chat reply whose stream ended before the server

  • said it was done: the connection was closed early, or the server sent
  • nothing. The reply so far is incomplete, so Chat returns it as an error
  • rather than as an empty or partial success. It classifies as io (exit 74). *
  • Example:
  • if errors.Is(err, harvey.ErrStreamTruncated) { retry() }
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.

Functions

func AsCreate added in v0.0.17

func AsCreate(err error) error

* AsCreate reclassifies a failure to create an output as cant_create (exit

  • 73): the file or directory could not be made. A missing parent or an
  • existing target is not "no input" here, it is an output that cannot be
  • created. A permission failure keeps its own class (77), a failure part way
  • through writing stays io (74), and an error that already carries an explicit
  • class is returned unchanged. *
  • Parameters:
  • err (error) — an error from creating a file or directory; may be nil. *
  • Returns:
  • error — err, or err classed as cant_create. *
  • Example:
  • return harvey.AsCreate(fmt.Errorf("creating %s: %w", dir, err))

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 CantCreatef added in v0.0.17

func CantCreatef(format string, a ...any) error

* CantCreatef is fmt.Errorf that marks its result as an output that cannot be

  • created (exit 73): the target exists, or its directory cannot be made. *
  • Parameters:
  • format (string) — a fmt.Errorf format.
  • a (...any) — the format's arguments. *
  • Returns:
  • error — a *ClassedError of ClassCantCreate. *
  • Example:
  • return harvey.CantCreatef("cannot create recording %s: %w", path, err)

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 CheckDOIRetraction added in v0.0.16

func CheckDOIRetraction(doi, apiURL string) (retracted bool, note string, err error)

* CheckDOIRetraction queries the Retraction Watch API for the given DOI and

  • reports whether the work has been retracted. *
  • Parameters:
  • doi (string) — DOI to query, e.g. "10.1234/example".
  • apiURL (string) — base URL of the Retraction Watch API; use
  • DefaultRetractionWatchURL for production. *
  • Returns:
  • retracted (bool) — true when the DOI appears in the retraction database.
  • note (string) — human-readable note with reason and date; empty when
  • not retracted.
  • error — on network failure, non-200 response, or bad JSON. *
  • Example:
  • retracted, note, err := CheckDOIRetraction("10.1234/paper", DefaultRetractionWatchURL)
  • if retracted { fmt.Println("retracted:", note) }

func CheckLlamafileInput added in v0.0.17

func CheckLlamafileInput(path string) error

* CheckLlamafileInput verifies a llamafile named with --llamafile: the file

  • must exist (66) and carry the .llamafile or .llamafile.exe extension Harvey
  • is willing to launch (66, the wrong kind of file). *
  • Parameters:
  • path (string) — the path given to --llamafile. *
  • Returns:
  • error — nil, or an error classified as a missing input. *
  • Example:
  • if err := harvey.CheckLlamafileInput("~/Models/qwen.llamafile"); err != nil { return err }

func CheckStartupInputs added in v0.0.17

func CheckStartupInputs(cfg *Config) error

* CheckStartupInputs verifies the inputs named on the command line: the file

  • given to --continue and --replay must exist (66), a --replay file must parse
  • as a session (65), and the --record-file path must be creatable (73 when its
  • directory cannot be made, 77 when the operating system refuses). It touches
  • nothing but a short-lived probe file in the recording directory, and returns
  • the first problem. *
  • Parameters:
  • cfg (*Config) — the configuration built from the command line. *
  • Returns:
  • error — nil, or an error classified for the first input that is unusable. *
  • Example:
  • if err := harvey.CheckStartupInputs(cfg); err != nil { return err }

func ClassedAs added in v0.0.17

func ClassedAs(class ExitClass, err error) error

* ClassedAs marks an existing error with a class and leaves nil alone. Use it

  • to reclassify what a helper returned. The outermost class in the chain wins,
  • so it overrides both an inner ClassedError and what the wrapped error would
  • have classified as. *
  • Parameters:
  • class (ExitClass) — the class to give the error.
  • err (error) — the error to mark, or nil. *
  • Returns:
  • error — nil for a nil err, otherwise a *ClassedError wrapping err. *
  • Example:
  • return harvey.ClassedAs(harvey.ClassData, fmt.Errorf("%s: %w", path, err))

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 Configf added in v0.0.17

func Configf(format string, a ...any) error

* Configf is fmt.Errorf that marks its result as a configuration file that is

  • present but wrong (exit 78). *
  • Parameters:
  • format (string) — a fmt.Errorf format.
  • a (...any) — the format's arguments. *
  • Returns:
  • error — a *ClassedError of ClassConfig. *
  • Example:
  • return harvey.Configf("harvey.yaml: %w", err)

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 CountTokensFor added in v0.0.19

func CountTokensFor(ctx context.Context, engine, baseURL, model, text string) (int, bool)

* CountTokensFor is CountTokens for a named engine: an engine whose

  • capability row says it has no tokenizer is not asked, and gets the
  • character estimate directly. *
  • Parameters:
  • ctx (context.Context) — controls the HTTP request lifetime.
  • engine (string) — engine label, e.g. "hailo" or "ollama"; "" asks.
  • baseURL (string) — server base URL.
  • model (string) — model name.
  • text (string) — text to count. *
  • Returns:
  • int — number of tokens.
  • bool — true when the count came from the server's tokenizer. *
  • Example:
  • n, exact := CountTokensFor(ctx, "hailo", url, "llama3.2:3b", prompt) // estimate, false

func Dataf added in v0.0.17

func Dataf(format string, a ...any) error

* Dataf is fmt.Errorf that marks its result as wrong content (exit 65): a

  • malformed corpus, Fountain file or YAML the tool was asked to read. A bad
  • value on the command line is a usage error instead. *
  • Parameters:
  • format (string) — a fmt.Errorf format.
  • a (...any) — the format's arguments. *
  • Returns:
  • error — a *ClassedError of ClassData. *
  • Example:
  • return harvey.Dataf("%s: not a Fountain session file", path)

func DefaultLlamafileModelsDir added in v0.0.12

func DefaultLlamafileModelsDir() string

* DefaultLlamafileModelsDir returns the default discovery directory ($HOME/Models).

  • Exported so cmd/harvey/main.go can detect whether the user has overridden it
  • before applying the HARVEY_LLAMAFILE_DIR environment variable. *
  • Returns:
  • string — default models directory path. *
  • Example:
  • if cfg.Llamafile.ModelsDir == harvey.DefaultLlamafileModelsDir() { ... }

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) (bool, 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:
  • bool — true when the skill used the LLM fallback path and the caller should
  • send the enriched history to the LLM to generate a response.
  • false when a compiled script handled everything autonomously.
  • error — on unexpected I/O or execution failure; non-zero script exit is reported but not returned. *
  • Example:
  • llmNeeded, 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 ExtractJSONFlag added in v0.0.17

func ExtractJSONFlag(args []string) (bool, []string)

* ExtractJSONFlag reports whether "-json" or "--json" appears anywhere in

  • args and returns args with every occurrence removed, so a flag parser
  • downstream never sees it as an unknown flag. Both spellings are accepted
  • since harvey's own flags are double-dash-only and assay's (the standard
  • library flag package) are conventionally single-dash. Both binaries call
  • this before their own argument parsing, so --json is honoured even when a
  • later flag on the same command line — or the flag package's own parse —
  • is what fails. *
  • Parameters:
  • args ([]string) — the raw command line, args[0] is the program name. *
  • Returns:
  • bool — true when -json or --json was present.
  • []string — args with every occurrence removed; the relative order of
  • everything else is unchanged. *
  • Example:
  • jsonOut, args := harvey.ExtractJSONFlag(os.Args) // ["prog","--json","-x"] -> true, ["prog","-x"]

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 FindArXivIDs added in v0.0.11

func FindArXivIDs(text string) []string

* FindArXivIDs scans text for arXiv preprint identifiers, either as an

  • "arXiv:" CURIE (arXiv:2412.03631) or an arxiv.org/abs/ URL. A bare
  • numeric identifier with no "arxiv:" label or URL is not matched —
  • the YYMM.NNNNN shape alone is too easily confused with version
  • numbers or other decimals. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated arXiv identifiers as lower-case "arxiv:"
  • CURIEs (e.g. "arxiv:2412.03631"), in first-seen order. *
  • Example:
  • ids := FindArXivIDs("see arXiv:2412.03631 for the preprint")
  • // ids == []string{"arxiv:2412.03631"}

func FindDOIs added in v0.0.11

func FindDOIs(text string) []string

* FindDOIs scans text for DOIs in any common form — extended URLs

  • (https://doi.org/...), "doi:"/"DOI:" labeled CURIEs, or bare short
  • form (10.xxxx/yyyy), which is the most common form in running text.
  • Every match is normalized to the extended URL form via
  • metadatatools.NormalizeDOI. *
  • Note: a https://raid.org/10.xxxx/yyyy URL is also picked up here
  • (its local identifier is a real DOI too) — see FindRAiDs for the
  • RAiD-specific extraction rule. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated DOIs in extended URL form
  • (https://doi.org/10.xxxx/yyyy), in first-seen order. *
  • Example:
  • dois := FindDOIs("See DOI: 10.1234/abcd.5678 for details.")
  • // dois == []string{"https://doi.org/10.1234/abcd.5678"}

func FindFreePort added in v0.0.13

func FindFreePort() (int, error)

* FindFreePort asks the OS for an available TCP port by briefly binding to

  • :0, then returns the assigned port number. Used to select a distinct port
  • for an assay llamafile run so it does not conflict with a running Harvey
  • session on the default llamafile port. *
  • Returns:
  • int — a free port number.
  • error — if no port could be obtained. *
  • Example:
  • port, err := FindFreePort()
  • url := fmt.Sprintf("http://localhost:%d", port)

func FindFundRefIDs added in v0.0.11

func FindFundRefIDs(text string) []string

* FindFundRefIDs scans text for Crossref Funder Registry identifiers —

  • DOIs under the reserved 10.13039 prefix that identify a funding
  • organization. *
  • A 10.13039/xxxxx string is simultaneously a real DOI and a funder
  • identifier (unlike the RAiD/DOI case, there is no ambiguity to
  • resolve), so the same string is correctly returned by both FindDOIs
  • and FindFundRefIDs. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated FundRef identifiers in bare DOI-shaped
  • form (e.g. "10.13039/100006961"), in first-seen order. *
  • Example:
  • ids := FindFundRefIDs("Funder: 10.13039/100006961 (Caltech Library)")
  • // ids == []string{"10.13039/100006961"}

func FindISBNs added in v0.0.11

func FindISBNs(text string) []string

* FindISBNs scans text for ISBN-10 and ISBN-13 identifiers. A match

  • requires either an explicit "ISBN"/"ISBN-10"/"ISBN-13" label, or the
  • hyphen-grouped form beginning with the reserved 978/979 bookland
  • prefix — a bare run of digits alone is too ambiguous to scan
  • reliably. Each candidate is confirmed via its ISBN-10 (Mod 11) or
  • ISBN-13 (Mod 10 / EAN-13) checksum. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated ISBNs in hyphenated normalized form, in
  • first-seen order. *
  • Example:
  • isbns := FindISBNs("ISBN: 978-3-16-148410-0")
  • // isbns == []string{"978-3-1-61-484100-0"} // see metadatatools.NormalizeISBN

func FindISNIs added in v0.0.11

func FindISNIs(text string) []string
  • FindISNIs scans text for International Standard Name Identifiers. *
  • ISNI shares its exact shape and ISO 7064 Mod 11-2 checksum with
  • ORCID (16 digits in four groups, optional trailing X) — a bare match
  • is ambiguous between the two. Per the convention in
  • towards_a_scholarly_memory_design.md, a bare grouped+checksum match
  • defaults to ORCID (see FindORCIDs); FindISNIs only matches when an
  • explicit "ISNI:" label or isni.org URL provides disambiguating
  • context. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated ISNIs in space-grouped form
  • (e.g. "0000 0003 0900 6903"), in first-seen order. *
  • Example:
  • isnis := FindISNIs("ISNI: 0000 0003 0900 6903")
  • // isnis == []string{"0000 0003 0900 6903"}

func FindISSNs added in v0.0.11

func FindISSNs(text string) []string

* FindISSNs scans text for International Standard Serial Numbers in

  • their NNNN-NNNX hyphenated form. The 8-character hyphenated shape
  • with a Mod 11 checksum digit (validated via
  • metadatatools.ValidateISSN) is distinctive enough to scan without
  • requiring a label. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated ISSNs in NNNN-NNNX form, in first-seen
  • order. *
  • Example:
  • issns := FindISSNs("Journal ISSN 1058-6180, online edition.")
  • // issns == []string{"1058-6180"}

func FindIdentifiers added in v0.0.11

func FindIdentifiers(text string) map[IdentifierType][]string

* FindIdentifiers scans text for every identifier type

  • scholarly_identifiers.go supports and returns them grouped by
  • IdentifierType. Each value is normalized via the corresponding
  • metadatatools Normalize* function (see the per-type canonical-form
  • table in towards_a_scholarly_memory_design.md). Types with no matches
  • are omitted from the result map, keeping it compact for storage in
  • the `chunks.identifiers` JSON column. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • map[IdentifierType][]string — identifiers found, keyed by type. *
  • Example:
  • ids := FindIdentifiers("DOI: 10.1234/abcd.5678, ORCID: 0000-0003-0900-6903")
  • // ids[IdentifierDOI] == []string{"https://doi.org/10.1234/abcd.5678"}
  • // ids[IdentifierORCID] == []string{"0000-0003-0900-6903"}

func FindLCNAFs added in v0.0.11

func FindLCNAFs(text string) []string

* FindLCNAFs scans text for Library of Congress Name Authority File

  • identifiers. metadatatools' LCNAFPattern (any alphanumeric string)
  • is far too permissive for bare scanning, so FindLCNAFs only matches
  • when an explicit "LCNAF:" label or an id.loc.gov/authorities/names/
  • URL provides context, using the conventional LC control number shape
  • (1-3 letters followed by 8-10 digits). *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated LCNAF identifiers, in first-seen order. *
  • Example:
  • ids := FindLCNAFs("LCNAF: n79021164")
  • // ids == []string{"n79021164"}

func FindORCIDs added in v0.0.11

func FindORCIDs(text string) []string

* FindORCIDs scans text for ORCID iDs in URL form

  • (https://orcid.org/...), "ORCID:"/"orcid:" labeled form, or bare
  • hyphenated form (0000-0003-0900-6903) — the common form next to an
  • author's name in a byline. A bare match must pass the ISO 7064
  • Mod 11-2 checksum (via metadatatools.ValidateORCID) to be accepted,
  • which keeps false positives from incidental 16-digit groups low. *
  • Note: this is also the default classification for any bare
  • 16-digit, hyphen-grouped, checksum-valid identifier — see FindISNIs
  • for why ISNI requires explicit context to be recognized separately. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated ORCID iDs in bare hyphenated form
  • (e.g. "0000-0003-0900-6903"), in first-seen order. *
  • Example:
  • ids := FindORCIDs("R. S. Doiel (ORCID: 0000-0003-0900-6903)")
  • // ids == []string{"0000-0003-0900-6903"}

func FindPMCIDs added in v0.0.11

func FindPMCIDs(text string) []string

* FindPMCIDs scans text for PubMed Central identifiers. The "PMC"

  • prefix is part of the identifier itself, so the bare PMCxxxxxxx form
  • is self-distinctive and needs no label or URL context. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated PMCIDs (e.g. "PMC1234567"), in first-seen
  • order. *
  • Example:
  • pmcids := FindPMCIDs("available at PMC1234567")
  • // pmcids == []string{"PMC1234567"}

func FindPMIDs added in v0.0.11

func FindPMIDs(text string) []string

* FindPMIDs scans text for PubMed identifiers. metadatatools'

  • PMIDPattern is "one or more digits", which alone matches any integer,
  • so FindPMIDs only matches when an explicit "PMID:" label or a
  • pubmed.ncbi.nlm.nih.gov URL provides context. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated PMIDs (bare digit strings), in first-seen
  • order. *
  • Example:
  • pmids := FindPMIDs("PMID: 33417889")
  • // pmids == []string{"33417889"}

func FindRAiDs added in v0.0.11

func FindRAiDs(text string) []string
  • FindRAiDs scans text for Research Activity Identifiers (RAiDs). *
  • RAiD and DOI are format-identical (10.xxxx/yyyy — a RAiD is a
  • DataCite DOI per ISO 23527), so format alone cannot disambiguate
  • them. Per the convention recorded in
  • towards_a_scholarly_memory_design.md, FindRAiDs matches ONLY an
  • explicit https://raid.org/10.xxxx/yyyy resolver URL. A bare or
  • "DOI:"-labeled 10.xxxx/yyyy is always classified as a DOI (see
  • FindDOIs), never as a RAiD. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated RAiDs in extended URL form
  • (https://raid.org/10.xxxx/yyyy), in first-seen order. *
  • Example:
  • raids := FindRAiDs("Project RAiD: https://raid.org/10.83962/fb5be317")
  • // raids == []string{"https://raid.org/10.83962/fb5be317"}

func FindRORs added in v0.0.11

func FindRORs(text string) []string

* FindRORs scans text for Research Organization Registry identifiers,

  • either as a ror.org URL (https://ror.org/05dxps055) or an explicit
  • "ROR:" label followed by the bare identifier. A bare 9-character
  • token with no URL or label is not matched — the shape alone is too
  • generic to scan reliably. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated ROR identifiers in extended URL form
  • (https://ror.org/05dxps055), in first-seen order. *
  • Example:
  • rors := FindRORs("Affiliation: https://ror.org/05dxps055")
  • // rors == []string{"https://ror.org/05dxps055"}

func FindSNACs added in v0.0.11

func FindSNACs(text string) []string

* FindSNACs scans text for Social Networks and Archival Context

  • identifiers. metadatatools' SNACPattern is "one or more digits",
  • which alone matches any integer, so FindSNACs only matches when an
  • explicit "SNAC:" label or a snaccooperative.org/view/ URL provides
  • context. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated SNAC identifiers (bare digit strings), in
  • first-seen order. *
  • Example:
  • ids := FindSNACs("SNAC: 12345678")
  • // ids == []string{"12345678"}

func FindVIAFs added in v0.0.11

func FindVIAFs(text string) []string

* FindVIAFs scans text for Virtual International Authority File

  • identifiers. metadatatools' VIAFPattern is "one or more digits",
  • which alone matches any integer, so FindVIAFs only matches when an
  • explicit "VIAF:" label or a viaf.org/viaf/ URL provides context. *
  • Parameters:
  • text (string) — the text to scan. *
  • Returns:
  • []string — deduplicated VIAF identifiers (bare digit strings), in
  • first-seen order. *
  • Example:
  • ids := FindVIAFs("VIAF: 12345678")
  • // ids == []string{"12345678"}

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 HelpTopicsText added in v0.0.12

func HelpTopicsText() string

* HelpTopicsText returns a formatted index of all help topics with one-line

  • descriptions, suitable for printing to stdout or an io.Writer. *
  • Returns:
  • string — formatted topic listing. *
  • Example:
  • fmt.Print(HelpTopicsText())

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 IOf added in v0.0.17

func IOf(format string, a ...any) error

* IOf is fmt.Errorf that marks its result as a read or write that failed part

  • way (exit 74). *
  • Parameters:
  • format (string) — a fmt.Errorf format.
  • a (...any) — the format's arguments. *
  • Returns:
  • error — a *ClassedError of ClassIO. *
  • Example:
  • return harvey.IOf("writing %s: %w", path, err)

func ImportAliasesFrom added in v0.0.16

func ImportAliasesFrom(sourcePath string, destWS *Workspace, destCfg *Config, out io.Writer) (copied, skipped int, err error)

* ImportAliasesFrom reads model aliases from sourcePath and merges them into

  • destCfg, then persists the result to destWS. sourcePath may be:
  • - a directory containing agents/harvey.yaml (another Harvey workspace)
  • - a YAML file with a model_aliases map at the top level *
  • Existing aliases in destCfg are never overwritten; source aliases fill gaps
  • only. The number of aliases copied and skipped are returned. *
  • Parameters:
  • sourcePath (string) — path to a workspace directory or a harvey.yaml file.
  • destWS (*Workspace) — workspace receiving the aliases.
  • destCfg (*Config) — config receiving the aliases (mutated in place).
  • out (io.Writer) — progress output. *
  • Returns:
  • copied (int) — number of aliases added to destCfg.
  • skipped (int) — number of aliases skipped (name already existed).
  • err (error) — non-nil on read or parse failure. *
  • Example:
  • copied, skipped, err := ImportAliasesFrom("/other/project", ws, cfg, os.Stdout)
  • // " Imported 3 aliases (2 skipped — already defined)\n"

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 LlamafileModelNameFromPath added in v0.0.12

func LlamafileModelNameFromPath(path string) string

* LlamafileModelNameFromPath is the exported form of llamafileModelName,

  • used by cmd/harvey/main.go when building a session-only registry entry
  • from the --llamafile CLI flag. *
  • Parameters:
  • path (string) — path to a llamafile binary. *
  • Returns:
  • string — name derived from the filename with ".llamafile" stripped. *
  • Example:
  • name := harvey.LlamafileModelNameFromPath("/home/user/Models/Qwen3.5-4B.llamafile")
  • // name == "Qwen3.5-4B"

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 LoadHelpGuide added in v0.0.8

func LoadHelpGuide(name string) ([]byte, error)

* LoadHelpGuide reads an embedded help guide by stem name (the filename

  • without directory or extension). *
  • Parameters:
  • name (string) — guide stem, e.g. "ollama", "pdf-tools", "getting-started". *
  • Returns:
  • []byte — raw guide file contents (Markdown).
  • error — if the guide is not found in the embedded FS. *
  • Example:
  • data, err := LoadHelpGuide("pdf-tools")

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 LoadTemplate added in v0.0.8

func LoadTemplate(name string) ([]byte, error)

* LoadTemplate reads a built-in profile template by stem name (the filename

  • without directory or extension). Returns the raw file bytes for display or
  • editing. Does not load workspace-local templates; callers that need those
  • can read the file directly using the path derived from TemplateEntry.File. *
  • Parameters:
  • name (string) — template stem, e.g. "backend-developer". *
  • Returns:
  • []byte — raw template file contents.
  • error — if the template is not found in the embedded FS. *
  • Example:
  • data, err := LoadTemplate("backend-developer")

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 MostRecentSession added in v0.0.13

func MostRecentSession(sessDir string) string

* MostRecentSession returns the path of the most recently modified .spmd or

  • .fountain file in sessDir, or "" if the directory is empty or does not exist.
  • It delegates to ListSessionFiles, which returns files sorted newest-first. *
  • Parameters:
  • sessDir (string) — absolute path to the sessions directory. *
  • Returns:
  • string — absolute path to the most recent session file, or "". *
  • Example:
  • path := MostRecentSession("/workspace/agents/sessions")

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 Negativef added in v0.0.17

func Negativef(format string, a ...any) error

* Negativef is fmt.Errorf that marks its result as a normal negative answer

  • (exit 1): the command ran correctly and the answer is no. *
  • Parameters:
  • format (string) — a fmt.Errorf format.
  • a (...any) — the format's arguments. *
  • Returns:
  • error — a *ClassedError of ClassNegative. *
  • Example:
  • return harvey.Negativef("no prompts match category %q", category)

func NoInputf added in v0.0.17

func NoInputf(format string, a ...any) error

* NoInputf is fmt.Errorf that marks its result as a missing input (exit 66): a

  • named file or directory, or the workspace, that is not there or is the wrong
  • kind of thing. *
  • Parameters:
  • format (string) — a fmt.Errorf format.
  • a (...any) — the format's arguments. *
  • Returns:
  • error — a *ClassedError of ClassNoInput. *
  • Example:
  • return harvey.NoInputf("session file %s does not exist", path)

func NoPermissionf added in v0.0.18

func NoPermissionf(format string, a ...any) error

* NoPermissionf is fmt.Errorf that marks its result as a permission refusal

  • (exit 77): the operating system or Harvey's own permission rules refused
  • access to a path or an action. *
  • Parameters:
  • format (string) — a fmt.Errorf format; %w keeps a cause reachable.
  • a (...any) — the format's arguments. *
  • Returns:
  • error — a *ClassedError of ClassNoPermission. *
  • Example:
  • return harvey.NoPermissionf("%s: read permission denied", path)

func NotFoundf added in v0.0.17

func NotFoundf(format string, a ...any) error

* NotFoundf is fmt.Errorf that marks its result as "no such item" (exit 1). It

  • is the same class as Negativef; the name says what the caller means. *
  • Parameters:
  • format (string) — a fmt.Errorf format.
  • a (...any) — the format's arguments. *
  • Returns:
  • error — a *ClassedError of ClassNegative. *
  • Example:
  • return harvey.NotFoundf("skill %q not found", name)

func ParseApertusToolCalls added in v0.0.15

func ParseApertusToolCalls(text string) []anyllm.ToolCall

* ParseApertusToolCalls scans raw response text for Apertus-native tool call

  • blocks and returns them as anyllm.ToolCall values. *
  • Apertus emits tool calls as <SPECIAL_71>[{"name": args}, ...]<SPECIAL_72>
  • where each array element is a single-key object: the key is the function name
  • and the value is the arguments (any JSON value). *
  • Parameters:
  • text (string) — raw LLM response text to scan. *
  • Returns:
  • []anyllm.ToolCall — parsed tool calls; nil when none found. *
  • Example:
  • calls := ParseApertusToolCalls(`<SPECIAL_71>[{"read_file": {"path": "x.go"}}]<SPECIAL_72>`)
  • // calls[0].Function.Name == "read_file"

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 PrintHelpTopic added in v0.0.12

func PrintHelpTopic(w io.Writer, topic, appName, version, releaseDate, releaseHash string) bool

* PrintHelpTopic writes the help guide for the named topic to w, substituting

  • appName, version, releaseDate, and releaseHash into man-page-style headers.
  • Pass empty strings when version metadata is not needed (e.g. inside the REPL). *
  • Parameters:
  • w (io.Writer) — destination writer.
  • topic (string) — topic name or alias (case-insensitive).
  • appName (string) — binary name, e.g. "harvey".
  • version (string) — semver string, e.g. "0.0.12".
  • releaseDate (string) — ISO date, e.g. "2026-06-17".
  • releaseHash (string) — short git hash. *
  • Returns:
  • bool — true if the topic was recognized, false if unknown. *
  • Example:
  • ok := PrintHelpTopic(os.Stdout, "rag", "harvey", Version, ReleaseDate, ReleaseHash)
  • if !ok {
  • fmt.Fprintln(os.Stderr, "unknown topic")
  • }

func PrintJSONError added in v0.0.17

func PrintJSONError(w io.Writer, err error) int

* PrintJSONError writes err to w as the workspace convention's machine-

  • readable error envelope, matching kb's --json shape (workspace DR-0003):
  • {"error": "...", "class": "...", "code": N}. A nil err writes nothing.
  • Both harvey and assay use this for their --json mode, so a script reading
  • either binary's stderr gets the same shape kb already produces. *
  • Parameters:
  • w (io.Writer) — destination, normally the process's stderr.
  • err (error) — the error to report; a no-op when nil. *
  • Returns:
  • int — the exit code err classifies to (0 for nil). *
  • Example:
  • os.Exit(harvey.PrintJSONError(os.Stderr, err))

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 PrintPlan added in v0.0.12

func PrintPlan(p *Plan, out io.Writer)
  • PrintPlan writes a human-readable plan checklist to out. *
  • Parameters:
  • p (*Plan) — plan to display.
  • out (io.Writer) — destination for output. *
  • Example:
  • PrintPlan(p, 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 ProbeLlamafile added in v0.0.12

func ProbeLlamafile(baseURL string) bool

* ProbeLlamafile returns true if a llamafile HTTP server is reachable at

  • baseURL. It sends a GET request to the /v1/models endpoint with a short
  • timeout so that Harvey's startup sequence does not stall when nothing is
  • listening. *
  • Parameters:
  • baseURL (string) — llamafile server base URL, e.g. "http://localhost:8080". *
  • Returns:
  • bool — true when the server responds with HTTP 200. *
  • Example:
  • if ProbeLlamafile("http://localhost:8080") {
  • fmt.Println("llamafile is ready")
  • }

func ProbeLlamafileContextLength added in v0.0.14

func ProbeLlamafileContextLength(baseURL string) int

* ProbeLlamafileContextLength queries the /v1/models endpoint of a running

  • llamafile server and returns the runtime context window size in tokens from
  • the data[0].meta.n_ctx field. Returns 0 when the server is unreachable,
  • the field is absent, or any error occurs. *
  • Parameters:
  • baseURL (string) — llamafile API base URL, e.g. "http://localhost:8080". *
  • Returns:
  • int — context window in tokens, or 0 if unknown. *
  • Example:
  • ctxLen := ProbeLlamafileContextLength("http://localhost:8080")
  • // ctxLen == 16384 for Qwen3.5 models at default settings

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 RequireCWDInRoot added in v0.0.16

func RequireCWDInRoot(cwd, root string) error

* RequireCWDInRoot verifies that cwd lies inside root (or equals it), after

  • resolving both to absolute, symlink-free paths. This is the enforcement
  • half of Harvey's workspace security model: launching with no -w/--workdir
  • flag always trusts cwd as the workspace, but an explicitly-passed root
  • must not be allowed to point somewhere the process isn't actually standing
  • inside — otherwise agents/, sessions, and HARVEY.md would all be anchored
  • to a tree unrelated to where the user is actually working. *
  • Parameters:
  • cwd (string) — the process's current working directory.
  • root (string) — the workspace root requested via -w/--workdir. *
  • Returns:
  • error — non-nil, naming both directories, when cwd does not lie inside
  • root; nil when cwd equals root or is a descendant of it. *
  • Example:
  • cwd, _ := os.Getwd()
  • if err := RequireCWDInRoot(cwd, cfg.WorkDir); err != nil {
  • log.Fatal(err)
  • }

func ResolveHandoffDir added in v0.0.8

func ResolveHandoffDir(ws *Workspace) (string, error)

* ResolveHandoffDir returns the absolute path to the hand-off directory

  • (agents/hand-off/ inside the workspace), creating it if it does not exist.
  • Hand-off documents are written there by /profile use when switching profiles. *
  • Parameters:
  • ws (*Workspace) — the Harvey workspace. *
  • Returns:
  • string — absolute path to the hand-off directory.
  • error — if the directory cannot be created. *
  • Example:
  • dir, err := ResolveHandoffDir(ws)

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 RunChunkedAnalysis added in v0.0.16

func RunChunkedAnalysis(ctx context.Context, client LLMClient, rec *Recorder, params ChunkAnalysisParams, w io.Writer) (string, error)

func RunOnboarding added in v0.0.6

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

* RunOnboarding presents a profile template picker, optionally opens the

  • chosen template in $EDITOR, and saves the result as a workspace_profile
  • memory document. A project_fact is also extracted and saved when the
  • workspace contains a recognisable manifest file. *
  • The editor step is skipped when stdin is not an interactive terminal
  • (e.g. replay mode, pipes, or test runners). The selected template is
  • saved as-is in that case. *
  • Parameters:
  • a (*Agent) — the Harvey agent (provides 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 newLineReader(os.Stdin).
  • 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, "", newLineReader(os.Stdin), os.Stdout)
  • if err != nil { log.Fatal(err) }
  • fmt.Println("created:", relPath)

func SaveLlamaCppConfig added in v0.0.16

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

* SaveLlamaCppConfig writes the llama.cpp settings back to agents/harvey.yaml.

  • Only the llamacpp: section is updated; all other sections are preserved. *
  • Parameters:
  • ws (*Workspace) — workspace whose harvey.yaml is updated.
  • cfg (*Config) — source of llama.cpp fields to persist. *
  • Returns:
  • error — on I/O or marshal failure. *
  • Example:
  • if err := SaveLlamaCppConfig(ws, cfg); err != nil {
  • fmt.Println("could not save llamacpp config:", err)
  • }

func SaveLlamafileConfig added in v0.0.12

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

* SaveLlamafileConfig writes the llamafile registry back to agents/harvey.yaml,

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

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 SavePlan added in v0.0.12

func SavePlan(ws *Workspace, p *Plan) error
  • SavePlan writes the plan to agents/plan.md as a GFM checklist. *
  • Parameters:
  • ws (*Workspace) — workspace whose agents/ directory is written.
  • p (*Plan) — plan to persist. *
  • Returns:
  • error — on path resolution or file write failure. *
  • Example:
  • err := SavePlan(agent.Workspace, p)

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 SelectFrom added in v0.0.13

func SelectFrom(items []SelectItem, prompt string, in io.Reader, out io.Writer) (string, error)

* SelectFrom presents a numbered list of items and returns the Value of

  • the chosen item. If items contains exactly one entry it is returned
  • without displaying the list or prompting the user. Empty input, "q",
  • or "0" cancel the selection and return ("", nil). Non-numeric input
  • that is non-empty is returned as-is so callers can accept typed values
  • (e.g. file paths) in addition to numbered selections. *
  • Parameters:
  • items ([]SelectItem) — options to present; must not be nil.
  • prompt (string) — text shown after the list, e.g. "Select [1-3]: ".
  • in (io.Reader) — input source; typically a.In.
  • out (io.Writer) — output destination. *
  • Returns:
  • string — the Value of the chosen item, the raw input if non-numeric,
  • or "" on cancellation.
  • error — only non-nil on unexpected I/O failure. *
  • Example:
  • stores := []SelectItem{
  • {Value: "harvey", Label: "harvey", Active: true},
  • {Value: "docs", Label: "docs"},
  • }
  • name, err := SelectFrom(stores, "Select store: ", a.In, out)

func SelectFromStrings added in v0.0.13

func SelectFromStrings(items []string, prompt string, in io.Reader, out io.Writer) (string, error)

* SelectFromStrings is a convenience wrapper around SelectFrom where each

  • item's Label and Value are identical. Use this when the display name is
  • the same string that the command handler needs (e.g. store names, type
  • names). For richer display (e.g. "ID — description") build []SelectItem
  • directly and call SelectFrom. *
  • Parameters:
  • items ([]string) — options to present.
  • prompt (string) — text shown after the list.
  • in (io.Reader) — input source.
  • out (io.Writer) — output destination. *
  • Returns:
  • string — the chosen item string, or "" on cancellation.
  • error — only non-nil on unexpected I/O failure. *
  • Example:
  • types := []string{"tool_use", "workflow", "user_preference"}
  • chosen, err := SelectFromStrings(types, "Select type: ", a.In, out)

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 StartLlamafileService added in v0.0.12

func StartLlamafileService(path, baseURL, logPath string, timeout time.Duration, gpuLayers, ctxSize int, progress io.Writer) (*os.Process, error)

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 TemplateNoteField added in v0.0.8

func TemplateNoteField(content []byte) string

* TemplateNoteField extracts the content of the NOTE: field from a template

  • file. The NOTE: block begins at the line starting with "NOTE:" and ends at
  • the next line that starts a new all-caps field (e.g. "NAME:", "ROLE:") or
  • at end of file. Returns "" when no NOTE: field is present. *
  • Parameters:
  • content ([]byte) — raw template file bytes. *
  • Returns:
  • string — trimmed note text, or "" if absent. *
  • Example:
  • data, _ := LoadTemplate("backend-developer")
  • note := TemplateNoteField(data)
  • // "Recommended model: qwen2.5-coder:7b · ingest project source and deps"

func Unavailablef added in v0.0.17

func Unavailablef(format string, a ...any) error

* Unavailablef is fmt.Errorf that marks its result as a service that cannot be

  • reached (exit 69): a model server that is down or will not start. *
  • Parameters:
  • format (string) — a fmt.Errorf format.
  • a (...any) — the format's arguments. *
  • Returns:
  • error — a *ClassedError of ClassUnavailable. *
  • Example:
  • return harvey.Unavailablef("no backend connected; use /model use")

func Usagef added in v0.0.17

func Usagef(format string, a ...any) error

* Usagef is fmt.Errorf that marks its result as a usage error (exit 2): an

  • unknown flag, a missing or surplus argument, or any bad value passed on the
  • command line. Nothing was attempted. *
  • Parameters:
  • format (string) — a fmt.Errorf format; %w keeps a cause reachable.
  • a (...any) — the format's arguments. *
  • Returns:
  • error — a *ClassedError of ClassUsage. *
  • Example:
  • return harvey.Usagef("%s requires an argument", "-m")

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          *knowledge.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

	Out               io.Writer       // destination for interactive output; defaults to os.Stdout
	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
	Memory            *MemorySystem   // session-scoped memory subsystems; nil until initMemory runs
	LastRAGInfo       *RAGAugmentInfo // set after each chat turn that fires RAG; cleared by ClearHistory
	LastObservationID int64           // ID of the most recently recorded /kb observe; cleared by ClearHistory

	AuditBuffer *AuditBuffer   // in-memory audit log ring buffer; nil until initialized
	DebugLog    *DebugLog      // JSONL diagnostic log; nil when --debug not set
	Backend     ManagedBackend // active inference backend; nil when no backend is wired

	ActiveRoute string // session-sticky route name; when set, prompts are auto-dispatched via @NAME
	// ActiveStatus is the current turn's StatusReporter, set by runChatTurn
	// alongside the ToolExecutor's own Status field and cleared once the
	// turn's spinner stops. Lets tool handlers (which capture *Agent via
	// RegisterBuiltinTools but have no ToolExecutor reference) report a
	// SensorEvent during their own execution without a ToolHandler signature
	// change. nil outside an active tool-calling turn.
	ActiveStatus StatusReporter
	// 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
  • initKnowledgeBase 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)
  • }

func (*Agent) WriteHandoff added in v0.0.8

func (a *Agent) WriteHandoff(store *MemoryStore, handoffDir string) (string, error)

* WriteHandoff extracts a structural summary from the current conversation

  • history and writes it as a Markdown document to handoffDir, per
  • HANDOFF_FORMAT.md (Laboratory workspace `agents/decisions/0005`). The file
  • is named by timestamp and uses the .md extension so `kb learn` and
  • learnCandidates can process it in a future session. *
  • No LLM call is made, so this carries only a `## State Recap` section, not
  • a full carried-forward-and-corrected recap in HANDOFF_FORMAT.md's sense —
  • it does not read or repoint STATE.md, since a heuristic delta snapshot is
  • exactly the kind of hand-off that spec warns should not become "current
  • state." `scope: workspace` and an empty `projects:` list are used
  • unconditionally: Harvey's Workspace has no concept of which experiment a
  • conversation belongs to, so this cannot claim a project tier honestly. *
  • The summary is built from three heuristics:
  • - Last topics: first line of the last three assistant messages.
  • - Files touched: path-like tokens (containing "/" but not "://") from
  • the last twenty turns, capped at five unique paths.
  • - Open questions: user messages whose first line ends with "?", capped
  • at three. *
  • Parameters:
  • store (*MemoryStore) — open memory store; used to read the current
  • profile name. May be nil.
  • handoffDir (string) — directory to write the file into. *
  • Returns:
  • string — absolute path of the file written.
  • error — on write failure. *
  • Example:
  • path, err := a.WriteHandoff(store, handoffDir)

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 NewLlamafileLLMClient added in v0.0.16

func NewLlamafileLLMClient(apiURL, model string, timeout time.Duration) *AnyLLMClient

* NewLlamafileLLMClient creates an AnyLLMClient for any OpenAI-compatible

  • server (llamafile, llama.cpp, or Ollama's /v1 shim). This is the exported
  • variant of newLlamafileLLMClient, intended for use by cmd/assay and other
  • programs outside the harvey package. *
  • Parameters:
  • apiURL (string) — full base URL including /v1, e.g. "http://localhost:8080/v1"
  • model (string) — model name to pass in each chat request
  • timeout (time.Duration) — HTTP timeout; pass 0 for no timeout *
  • Returns:
  • *AnyLLMClient — ready-to-use client implementing LLMClient *
  • Example:
  • client := harvey.NewLlamafileLLMClient("http://localhost:8080/v1", "phi4", 120*time.Second)
  • defer client.Close()

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) Engine added in v0.0.19

func (a *AnyLLMClient) Engine() string

Engine returns the label set by SetEngine; "" when none was set.

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"

func (*AnyLLMClient) SetEngine added in v0.0.19

func (a *AnyLLMClient) SetEngine(engine string)

SetEngine records which engine's server this client talks to, so the engine's capability row applies (a "hailo" client never sends tools).

func (*AnyLLMClient) SetMaxTokens added in v0.0.15

func (a *AnyLLMClient) SetMaxTokens(n int)

* SetMaxTokens configures the per-request completion token limit.

  • A value of 0 means no limit (the provider or model decides). *
  • Parameters:
  • n (int) — maximum tokens to generate; 0 = unlimited. *
  • Example:
  • client.SetMaxTokens(4096)

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 {
	LogPath string // path of the open log file, empty when none
	// contains filtered or unexported fields
}

AuditBuffer is a thread-safe ring buffer for storing audit events. When a log file is open (via OpenLogFile), every event is also appended to that file in NDJSON format so the audit trail survives restarts.

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 ring buffer and, if a log file is open, writes a JSON line to it. File write errors are silently discarded so that a full disk never breaks the agent REPL.

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) CloseLogFile added in v0.0.13

func (b *AuditBuffer) CloseLogFile()

* CloseLogFile flushes and closes the current audit log file.

  • It is safe to call when no file is open. *
  • Example:
  • defer buf.CloseLogFile()

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) OpenLogFile added in v0.0.13

func (b *AuditBuffer) OpenLogFile(path string) error

* OpenLogFile opens (or creates) the file at path in append mode and

  • directs future audit events to it in NDJSON format. Each line is a
  • JSON object with ts, action, details, and status fields. *
  • Parameters:
  • path (string) — absolute path to the audit log file. *
  • Returns:
  • error — if the file cannot be opened or created. *
  • Example:
  • err := buf.OpenLogFile("/workspace/agents/audit.jsonl")

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 BackendPID added in v0.0.16

type BackendPID struct {
	Backend string `json:"backend"`
	PID     int    `json:"pid"`
	Model   string `json:"model"`
	URL     string `json:"url"`
}

* BackendPID is the JSON payload written to agents/.harvey-backend.pid when

  • Harvey starts a backend process. It persists across Harvey restarts so that
  • the next session can re-adopt or clean up the prior server. *
  • Fields:
  • Backend (string) — backend name: "ollama", "llamafile", or "llamacpp".
  • PID (int) — OS process ID of the server process.
  • Model (string) — model name or path the server was started with.
  • URL (string) — base HTTP URL the server is listening on. *
  • Example:
  • p := BackendPID{Backend: "llamafile", PID: 12345, Model: "phi4", URL: "http://127.0.0.1:8080"}
  • _ = writePIDFile("/workspace/agents", p)

type BasicChunker added in v0.0.10

type BasicChunker struct{}

* BasicChunker splits Basic (FreeBasic / QB64) source into enriched chunks

  • at SUB and FUNCTION boundaries. *
  • Example:
  • b := NewBasicChunker()
  • chunks := b.Chunk("SUB Hello()\n PRINT \"Hi\"\nEND SUB", "prog.bas")

func NewBasicChunker added in v0.0.10

func NewBasicChunker() *BasicChunker
  • NewBasicChunker returns a BasicChunker. *
  • Returns:
  • *BasicChunker — ready-to-use chunker. *
  • Example:
  • b := NewBasicChunker()

func (*BasicChunker) Chunk added in v0.0.10

func (b *BasicChunker) Chunk(content string, _ string) []EnrichedChunk
  • Chunk splits Basic source into SUB/FUNCTION chunks and code sections. *
  • Parameters:
  • content (string) — Basic source text.
  • filePath (string) — source path; used for context only. *
  • Returns:
  • []EnrichedChunk — chunks with location and symbol metadata. *
  • Example:
  • chunks := b.Chunk(src, "prog.bas")

func (*BasicChunker) Language added in v0.0.10

func (b *BasicChunker) Language() string
  • Language returns "basic". *
  • Returns:
  • string — "basic". *
  • Example:
  • b.Language() // "basic"

type BasicDocExtractor added in v0.0.10

type BasicDocExtractor struct{}

* BasicDocExtractor extracts documentation from FreeBasic / QB64 source code.

  • It recognises REM statements (case-insensitive) and single-quote (') comments.
  • Consecutive comment lines are grouped into one DocumentationBlock. *
  • Example:
  • e := NewBasicDocExtractor()
  • docs := e.ExtractDocs("' Prints a greeting.\nSUB Hello()\n PRINT \"Hi\"\nEND SUB\n")

func NewBasicDocExtractor added in v0.0.10

func NewBasicDocExtractor() *BasicDocExtractor
  • NewBasicDocExtractor returns a BasicDocExtractor. *
  • Returns:
  • *BasicDocExtractor — ready-to-use extractor. *
  • Example:
  • e := NewBasicDocExtractor()

func (*BasicDocExtractor) ExtractDocs added in v0.0.10

func (e *BasicDocExtractor) ExtractDocs(content string) []DocumentationBlock
  • ExtractDocs returns all DocumentationBlocks found in Basic source. *
  • Parameters:
  • content (string) — Basic source text. *
  • Returns:
  • []DocumentationBlock — blocks with line range and symbol association. *
  • Example:
  • docs := e.ExtractDocs("' Adds a and b.\nFUNCTION Add(a As Integer, b As Integer)\n")

func (*BasicDocExtractor) ExtractSymbols added in v0.0.10

func (e *BasicDocExtractor) ExtractSymbols(content string) map[string]string
  • ExtractSymbols returns a map of symbol name → documentation text for Basic. *
  • Parameters:
  • content (string) — Basic source text. *
  • Returns:
  • map[string]string — symbol → doc text. *
  • Example:
  • syms := e.ExtractSymbols("REM Adds two numbers.\nFUNCTION Add(a, b)\n")
  • // syms["Add"] == "Adds two numbers."

func (*BasicDocExtractor) Language added in v0.0.10

func (e *BasicDocExtractor) Language() string
  • Language returns "basic". *
  • Returns:
  • string — "basic". *
  • Example:
  • e.Language() // "basic"

type BudgetTracker added in v0.0.16

type BudgetTracker struct {
	Total int
	Used  int
}

* BudgetTracker is a shared, per-turn token pool. Callers call Reserve

  • before adding content to the turn's prompt; a failed Reserve means "this
  • doesn't fit — skip it and note that it was skipped," not an error. *
  • A nil *BudgetTracker is treated by its callers (ragAugment,
  • injectOrChunk) as "unconstrained" — this keeps every call site that
  • doesn't care about budget cutoff behavior unchanged. *
  • Fields:
  • Total (int) — total token budget for this turn.
  • Used (int) — tokens reserved so far. *
  • Example:
  • tracker := NewBudgetTracker(remainingContext(a))
  • augmented, info := a.ragAugment(input, tracker)
  • augmented = a.injectOrChunk(ctx, augmented, out, tracker)

func NewBudgetTracker added in v0.0.16

func NewBudgetTracker(total int) *BudgetTracker

* NewBudgetTracker returns a BudgetTracker with the given total token

  • budget and nothing yet reserved. *
  • Parameters:
  • total (int) — total token budget for this turn. *
  • Returns:
  • *BudgetTracker — a tracker ready for Reserve calls. *
  • Example:
  • tracker := NewBudgetTracker(4096)

func (*BudgetTracker) Remaining added in v0.0.16

func (b *BudgetTracker) Remaining() int

* Remaining returns the number of tokens still available in the tracker's

  • budget. *
  • Returns:
  • int — Total minus Used. *
  • Example:
  • rem := tracker.Remaining() // tokens still available

func (*BudgetTracker) Reserve added in v0.0.16

func (b *BudgetTracker) Reserve(tokens int) bool

* Reserve attempts to reserve tokens tokens from the tracker's remaining

  • budget. It succeeds (and increments Used) only when doing so would not
  • exceed Total; a rejected reservation leaves Used unchanged. *
  • Parameters:
  • tokens (int) — number of tokens to reserve. *
  • Returns:
  • bool — true when the reservation fit and was applied; false otherwise. *
  • Example:
  • if !tracker.Reserve(estimateTokens(chunk.Content)) {
  • // doesn't fit — skip this chunk
  • }

type BuiltinFormatter added in v0.0.10

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

* BuiltinFormatter applies a pure-Go formatting function to source text.

  • It implements the PipeFormatter mode and requires no external tools, safe
  • mode, or workspace access. *
  • Example:
  • f := newBuiltinFormatter("pascal", normaliseText)
  • formatted, err := f.Format(" x := 1; \n", "module.pas")

func (*BuiltinFormatter) Check added in v0.0.10

func (f *BuiltinFormatter) Check(content string, _ string) (bool, []FormatIssue)
  • Check reports whether content matches its formatted form. *
  • Parameters:
  • content (string) — source code to check.
  • filePath (string) — unused. *
  • Returns:
  • bool — true when already formatted.
  • []FormatIssue — empty on pass.

func (*BuiltinFormatter) Format added in v0.0.10

func (f *BuiltinFormatter) Format(content string, _ string) (string, error)
  • Format applies the built-in formatting function to content. *
  • Parameters:
  • content (string) — source code to format.
  • filePath (string) — unused; present for interface conformance. *
  • Returns:
  • string — formatted content.
  • error — always nil. *
  • Example:
  • out, _ := f.Format("var x: integer; \n", "prog.pas")

func (*BuiltinFormatter) Language added in v0.0.10

func (f *BuiltinFormatter) Language() string
  • Language returns the language ID. *
  • Returns:
  • string — language ID.

func (*BuiltinFormatter) Mode added in v0.0.10

func (f *BuiltinFormatter) Mode() FormatterMode
  • Mode returns PipeFormatter (built-ins are pure in-process formatters). *
  • Returns:
  • FormatterMode — always PipeFormatter.

type CChunker added in v0.0.10

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

* CChunker splits C or C++ source code into enriched chunks at brace-balanced

  • top-level boundaries. Function definitions, struct/class definitions, and
  • preprocessor/declaration sections each become their own chunk. *
  • Example:
  • c := NewCChunker("c")
  • chunks := c.Chunk("#include <stdio.h>\nint main(){return 0;}\n", "main.c")

func NewCChunker added in v0.0.10

func NewCChunker(langID string) *CChunker
  • NewCChunker returns a CChunker for the given language ID ("c" or "cpp"). *
  • Parameters:
  • langID (string) — "c" or "cpp". *
  • Returns:
  • *CChunker — ready-to-use chunker. *
  • Example:
  • c := NewCChunker("cpp")

func (*CChunker) Chunk added in v0.0.10

func (c *CChunker) Chunk(content string, _ string) []EnrichedChunk

* Chunk splits C/C++ source into enriched chunks. Brace depth is tracked

  • through strings and comments so function bodies are never split. *
  • Parameters:
  • content (string) — C/C++ source text.
  • filePath (string) — source path; used for context only. *
  • Returns:
  • []EnrichedChunk — source chunks with location and symbol metadata. *
  • Example:
  • chunks := c.Chunk("void foo(){}\nvoid bar(){}\n", "lib.c")

func (*CChunker) Language added in v0.0.10

func (c *CChunker) Language() string
  • Language returns the language ID this chunker handles. *
  • Returns:
  • string — "c" or "cpp". *
  • Example:
  • c.Language() // "c"

type CDocExtractor added in v0.0.10

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

* CDocExtractor extracts documentation blocks from C or C++ source code.

  • It recognises line comments (//), block comments (/* * /), and
  • Doxygen-style doc-comments (/** * / and /*! * /). Comments immediately
  • preceding (no intervening blank line) a code line are associated with the
  • symbol defined on that line. *
  • Example:
  • e := NewCDocExtractor("c")
  • docs := e.ExtractDocs("// foo docs\nvoid foo(){}\n")

func NewCDocExtractor added in v0.0.10

func NewCDocExtractor(langID string) *CDocExtractor
  • NewCDocExtractor returns a CDocExtractor for the given language ID. *
  • Parameters:
  • langID (string) — "c" or "cpp". *
  • Returns:
  • *CDocExtractor — ready-to-use extractor. *
  • Example:
  • e := NewCDocExtractor("c")

func (*CDocExtractor) ExtractDocs added in v0.0.10

func (e *CDocExtractor) ExtractDocs(content string) []DocumentationBlock
  • ExtractDocs returns all DocumentationBlocks found in C/C++ source. *
  • Parameters:
  • content (string) — C or C++ source text. *
  • Returns:
  • []DocumentationBlock — blocks with type, line range, and symbol association. *
  • Example:
  • docs := e.ExtractDocs("/** Foo does X. * /\nvoid foo(){}\n")

func (*CDocExtractor) ExtractSymbols added in v0.0.10

func (e *CDocExtractor) ExtractSymbols(content string) map[string]string
  • ExtractSymbols returns a map of symbol name → documentation text for C/C++. *
  • Parameters:
  • content (string) — C or C++ source text. *
  • Returns:
  • map[string]string — symbol → doc text; only symbols with comments are included. *
  • Example:
  • syms := e.ExtractSymbols("// Returns x.\nint getX(){return x;}\n")
  • // syms["getX"] == "Returns x."

func (*CDocExtractor) Language added in v0.0.10

func (e *CDocExtractor) Language() string
  • Language returns the language ID this extractor handles. *
  • Returns:
  • string — "c" or "cpp". *
  • Example:
  • e.Language() // "c"

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
	SourceURL   string
	SourceDOI   string
	SourceTitle 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 ChunkAnalysisParams added in v0.0.16

type ChunkAnalysisParams struct {
	Filename    string
	Chunks      []DocumentChunk
	Instruction string
	Model       string
	DocType     DocType
	Config      ChunkConfig
}

* ChunkAnalysisParams bundles all inputs to RunChunkedAnalysis.

  • Keeping them in a struct avoids a long parameter list and makes it
  • easy to add fields (e.g. a synthesis model distinct from the chunk
  • model) without changing the call site. *
  • Fields:
  • Filename (string) — display name of the document being analysed.
  • Chunks ([]DocumentChunk) — document segments from ChunkDocument.
  • Instruction (string) — the user's chunk prompt (any @mention already resolved out).
  • Model (string) — model name for LLM calls; used in recording only.
  • DocType (DocType) — DocTypeProse or DocTypeSource; determines boundary label.
  • Config (ChunkConfig) — chunking configuration from harvey.yaml or defaults. *
  • Example:
  • params := ChunkAnalysisParams{
  • Filename: "README.md",
  • Chunks: chunks,
  • Instruction: "Summarize each section.",
  • Model: "llama3.2:1b",
  • DocType: DocTypeProse,
  • Config: DefaultChunkConfig(),
  • }

type ChunkConfig added in v0.0.16

type ChunkConfig struct {
	Enabled        bool
	Threshold      float64
	ChunkSizeBytes int
	MaxChunks      int
	Overlap        string
	STMWarnPct     float64
}

* ChunkConfig holds tuneable parameters for chunked document analysis,

  • mirroring the harvey.yaml chunking: stanza. *
  • Fields:
  • Enabled (bool) — when false, the overflow alert and chunking are disabled.
  • Threshold (float64) — fraction of remaining context that triggers the alert (0.80 = 80%).
  • ChunkSizeBytes (int) — target chunk size in bytes; default 6000 (~1500 tokens).
  • MaxChunks (int) — chunk count above which Harvey warns before proceeding.
  • Overlap (string) — "paragraph", "sentence", or "none".
  • STMWarnPct (float64) — fraction of total context limit below which a summary_context
  • nudge is appended to the user message (0.20 = warn when <20%
  • remains). Set to 0 to disable. *
  • Example:
  • cfg := DefaultChunkConfig()
  • cfg.ChunkSizeBytes = 4000

func DefaultChunkConfig added in v0.0.16

func DefaultChunkConfig() ChunkConfig

* DefaultChunkConfig returns the ChunkConfig used when no chunking: stanza

  • is present in harvey.yaml. *
  • Returns:
  • ChunkConfig — ready-to-use configuration with sensible defaults. *
  • Example:
  • cfg := DefaultChunkConfig()
  • fmt.Println(cfg.ChunkSizeBytes) // 6000

type ClassedError added in v0.0.17

type ClassedError struct {
	Class ExitClass
	Err   error
}

* ClassedError carries an exit class with an error. Error and Unwrap forward

  • to the wrapped error, so a message reads exactly as it would have without
  • the class, and errors.Is and errors.As still reach the cause. *
  • Fields:
  • Class (ExitClass) — the class the error exits with.
  • Err (error) — the underlying error. *
  • Example:
  • var ce *harvey.ClassedError
  • if errors.As(err, &ce) { fmt.Println(ce.Class.Name) }

func (*ClassedError) Error added in v0.0.17

func (c *ClassedError) Error() string
  • Error returns the wrapped error's message unchanged. *
  • Returns:
  • string — the message of the underlying error. *
  • Example:
  • msg := harvey.Usagef("unknown flag %s", "-x").Error() // "unknown flag -x"

func (*ClassedError) Unwrap added in v0.0.17

func (c *ClassedError) Unwrap() error
  • Unwrap returns the underlying error, so errors.Is and errors.As reach it. *
  • Returns:
  • error — the underlying error. *
  • Example:
  • cause := errors.Unwrap(harvey.IOf("write: %w", io.ErrShortWrite)) // io.ErrShortWrite

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 CodeChunker added in v0.0.10

type CodeChunker interface {
	// Chunk splits content into enriched units.  filePath is used for context only.
	Chunk(content string, filePath string) []EnrichedChunk

	// Language returns the language ID this chunker handles.
	Language() string
}

* CodeChunker splits source code into semantically meaningful chunks for

  • RAG ingestion. Each chunk preserves code boundaries (functions, procedures,
  • etc.) and carries source-location metadata in EnrichedChunk. *
  • Example:
  • chunks := chunker.Chunk(src, "main.go")

type CodeFormatter added in v0.0.10

type CodeFormatter interface {
	// Format returns formatted source code.
	// PipeFormatter: content → formatted string (file not touched).
	// FileFormatter: Harvey writes the file first; Format is called after and
	//                returns the re-read file content.
	Format(content string, filePath string) (string, error)

	// Check returns true when content is already properly formatted,
	// plus a list of issues if it is not.
	Check(content string, filePath string) (bool, []FormatIssue)

	// Language returns the language ID this formatter handles.
	Language() string

	// Mode returns PipeFormatter or FileFormatter.
	Mode() FormatterMode
}
  • CodeFormatter formats source code according to language conventions. *
  • Two modes are supported; see FormatterMode for details. *
  • Example:
  • formatted, err := f.Format(src, "main.go")

type CombinedDetector added in v0.0.10

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

* CombinedDetector implements LanguageDetector by trying extension-based

  • detection first (confidence 1.0) and falling back to content-based detection
  • when the extension is absent or unrecognised. *
  • Example:
  • d := NewCombinedDetector("python", []string{".py"})
  • lang, conf := d.Detect("script", []byte("#!/usr/bin/env python3\n"))
  • // "python", 0.9 (no extension → content fallback)

func NewCombinedDetector added in v0.0.10

func NewCombinedDetector(langID string, exts []string) *CombinedDetector
  • NewCombinedDetector returns a CombinedDetector for the given language. *
  • Parameters:
  • langID (string) — language identifier, e.g. "go".
  • exts ([]string) — file extensions for this language, e.g. [".go"]. *
  • Returns:
  • *CombinedDetector — ready-to-use detector. *
  • Example:
  • d := NewCombinedDetector("oberon", []string{".Mod", ".obn"})

func (*CombinedDetector) Detect added in v0.0.10

func (d *CombinedDetector) Detect(filePath string, content []byte) (string, float64)

* Detect returns the language and confidence, trying extension first.

  • If the extension yields no match, content inspection is attempted. *
  • Parameters:
  • filePath (string) — path to the file.
  • content ([]byte) — file contents. *
  • Returns:
  • language (string) — language ID or "".
  • confidence (float64) — 1.0 for extension match; content confidence otherwise. *
  • Example:
  • lang, conf := d.Detect("main.go", data) // "go", 1.0

func (*CombinedDetector) DetectFromExtension added in v0.0.10

func (d *CombinedDetector) DetectFromExtension(ext string) (string, bool)
  • DetectFromExtension delegates to the embedded ExtensionDetector. *
  • Parameters:
  • ext (string) — file extension with leading dot. *
  • Returns:
  • language (string) — language ID or "".
  • ok (bool) — true on match. *
  • Example:
  • lang, ok := d.DetectFromExtension(".go") // "go", true

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
	Subcommands   []string
	ArgCompletion map[string]func(*Agent) []string
}
  • 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).
  • Subcommands ([]string) — valid second-token subcommand names; used by
  • buildCompleter for tab completion. Empty for
  • commands that take no subcommand.
  • ArgCompletion (map) — maps each subcommand name to a function that
  • returns candidate strings for its first positional
  • argument. Called at tab time; must not make LLM
  • or network calls. nil if not applicable. *
  • 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 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
	Routes         []RouteEndpoint // registered remote endpoints; persisted across sessions
	RoutingEnabled bool            // when false, @mentions are rejected with a warning
	ModelCacheDB   string          // path to model_cache.db; empty = harvey/model_cache.db

	// Grouped settings
	Skills    SkillsConfig
	Ollama    OllamaConfig
	Hailo     HailoConfig
	Llamafile LlamafileConfig
	Security  SecurityConfig
	Session   SessionConfig
	// LlamaCpp backend settings
	LlamaCpp LlamaCppConfig
	// Model aliases: short name → ModelAlias (model ID + optional purpose tags)
	ModelAliases map[string]ModelAlias
	// 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
	ToolResultCompaction bool // when true, prior tool-call rounds are compacted before each new LLM turn
	// Debug mode: set by --debug at startup; enables JSONL debug log and OLLAMA_DEBUG
	Debug bool
	// SyntaxHighlight enables ANSI colour highlighting of code blocks in responses.
	SyntaxHighlight bool
	// AutoFormat enables automatic code formatting after write_file writes a source file.
	AutoFormat bool
	// SensorInjectFormatFindings, when true, appends CodeFormatter.Check()
	// findings to the write_file/edit_file tool-result string (costing
	// tokens) in addition to the default human-visible SensorEvent. Default
	// false: Check() findings after a successful auto-format are rare and
	// low-severity, so token cost isn't spent on them unless requested. See
	// computational-sensors-design.md.
	SensorInjectFormatFindings bool
	// Memory system: RAG stores, knowledge base, and retrieval settings
	Memory MemoryConfig
	// Chunking: context-overflow detection and chunked document analysis settings.
	Chunking ChunkConfig
	// LearnModel names the route or local model `/kb learn draft` uses to draft
	// document summaries (knowledge-learning-mode-design.md decision 6). Empty
	// means the active model. Kept distinct from any retrieval-time model: the
	// model that drafts a summary should not be the one that matches against it.
	// An @name on the command overrides it for one run.
	LearnModel string
	// contains filtered or unexported fields
}
  • 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.
  • Ollama (OllamaConfig) — Ollama connection and model settings.
  • Llamafile (LlamafileConfig) — llamafile backend settings.
  • Security (SecurityConfig) — safe-mode and permission settings.
  • Session (SessionConfig) — recording and replay settings.
  • 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) ActiveLlamafileContextLength added in v0.0.15

func (c *Config) ActiveLlamafileContextLength() int

* ActiveLlamafileContextLength returns the configured context window size for

  • the active llamafile model, or 0 when unknown (server default applies). *
  • Returns:
  • int — context window in tokens, or 0. *
  • Example:
  • ctxSize := cfg.ActiveLlamafileContextLength()
  • // ctxSize == 49152 when set in harvey.yaml; 0 means use the model default

func (*Config) ActiveLlamafileEntry added in v0.0.12

func (c *Config) ActiveLlamafileEntry() *LlamafileEntry

* ActiveLlamafileEntry returns a pointer to the active LlamafileEntry in the

  • config, or nil when no active model is set or the name is not found. *
  • Returns:
  • *LlamafileEntry — the active entry, or nil. *
  • Example:
  • if e := cfg.ActiveLlamafileEntry(); e != nil {
  • fmt.Println(e.Path)
  • }

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) AddOrUpdateLlamafileEntry added in v0.0.12

func (c *Config) AddOrUpdateLlamafileEntry(e LlamafileEntry)

* AddOrUpdateLlamafileEntry inserts e into the registry if its name is new,

  • or replaces the existing entry if one with the same name exists. *
  • Parameters:
  • e (LlamafileEntry) — the entry to add or replace. *
  • Example:
  • cfg.AddOrUpdateLlamafileEntry(LlamafileEntry{Name: "qwen", Path: "/home/user/Models/qwen.llamafile"})

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) AliasesByTag added in v0.0.16

func (c *Config) AliasesByTag(tag string) []string

* AliasesByTag returns the alias names whose Tags slice contains tag

  • (case-insensitive). Returns nil when no aliases carry that tag. *
  • Parameters:
  • tag (string) — purpose label to search for, e.g. "code". *
  • Returns:
  • []string — sorted list of matching alias names. *
  • Example:
  • names := cfg.AliasesByTag("code") // → ["granite", "qwen-coder"]

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) IsExplicit added in v0.0.19

func (c *Config) IsExplicit(key string) bool
  • IsExplicit reports whether a setting was fixed with MarkExplicit. *
  • Parameters:
  • key (string) — harvey.yaml path of the setting. *
  • Returns:
  • bool — true when the command line or environment gave it. *
  • Example:
  • if !cfg.IsExplicit("llamafile.models_dir") { cfg.Llamafile.ModelsDir = dir }

func (*Config) LlamafileEntryByName added in v0.0.12

func (c *Config) LlamafileEntryByName(name string) *LlamafileEntry

* LlamafileEntryByName returns a pointer to the named LlamafileEntry, or nil

  • when not found. *
  • Parameters:
  • name (string) — registry name to look up. *
  • Returns:
  • *LlamafileEntry — matching entry, or nil. *
  • Example:
  • if e := cfg.LlamafileEntryByName("qwen"); e != nil {
  • fmt.Println(e.Path)
  • }

func (*Config) MarkExplicit added in v0.0.19

func (c *Config) MarkExplicit(keys ...string)

* MarkExplicit records that a setting was given on the command line or in

  • the environment, so LoadHarveyYAML leaves it as it is: the command line
  • beats harvey.yaml, and the environment beats it too. Keys are the setting's
  • harvey.yaml path, for example "llamafile.url" or "session.record_path". *
  • Parameters:
  • keys (...string) — harvey.yaml paths of the settings now fixed. *
  • Example:
  • cfg.Llamafile.URL = "http://localhost:9090"
  • cfg.MarkExplicit("llamafile.url")

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 ContentDetector added in v0.0.10

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

* ContentDetector implements LanguageDetector using shebang and keyword

  • pattern matching. It is language-specific: it only returns its own langID
  • so that it can be registered per-language in the registry. *
  • Example:
  • d := NewContentDetector("python")
  • lang, conf := d.Detect("script", []byte("#!/usr/bin/env python3\n"))
  • // "python", 0.9

func NewContentDetector added in v0.0.10

func NewContentDetector(langID string) *ContentDetector
  • NewContentDetector returns a ContentDetector for the given language. *
  • Parameters:
  • langID (string) — language identifier, e.g. "python". *
  • Returns:
  • *ContentDetector — ready-to-use detector. *
  • Example:
  • d := NewContentDetector("lisp")

func (*ContentDetector) Detect added in v0.0.10

func (d *ContentDetector) Detect(_ string, content []byte) (string, float64)

* Detect scans content for shebang lines and keyword patterns. It returns

  • a non-zero confidence only when the detected language matches this
  • detector's langID. Binary content always returns ("", 0.0). *
  • Parameters:
  • filePath (string) — path to the file; used only for context, not parsed.
  • content ([]byte) — file contents to inspect. *
  • Returns:
  • language (string) — this detector's langID or "".
  • confidence (float64) — 0.9 for shebang, keyword confidence otherwise; 0 on no match. *
  • Example:
  • lang, conf := d.Detect("", []byte("(defun hello () nil)"))
  • // "lisp", 0.95

func (*ContentDetector) DetectFromExtension added in v0.0.10

func (d *ContentDetector) DetectFromExtension(_ string) (string, bool)

* DetectFromExtension always returns ("", false) for a ContentDetector because

  • content-based detection does not use file extensions. *
  • Parameters:
  • ext (string) — ignored. *
  • Returns:
  • language (string) — always "".
  • ok (bool) — always false. *
  • Example:
  • lang, ok := d.DetectFromExtension(".py") // "", false

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 DispatchTarget added in v0.0.16

type DispatchTarget struct {
	Client  LLMClient
	Restore func()
}
  • DispatchTarget is a resolved model to run one bounded turn against. *
  • Fields:
  • Client (LLMClient) — the client to dispatch this turn's messages to.
  • Restore (func()) — call after the turn completes. No-op for a route
  • endpoint or an already-active local model (neither mutated Agent
  • state); for a local model switch, relaunches the pre-switch model —
  • a real, non-trivial cost (see subagent-dispatch-design.md), not a
  • cheap reference swap. *
  • Example:
  • target, ok, err := resolveDispatchTarget(a, "granite", out)
  • if ok {
  • defer target.Restore()
  • reply, err := target.Client.Chat(ctx, messages, w)
  • }

type DocExtractor added in v0.0.10

type DocExtractor interface {
	// ExtractDocs returns all documentation blocks found in content.
	ExtractDocs(content string) []DocumentationBlock

	// ExtractSymbols returns a map of symbol name → documentation text.
	ExtractSymbols(content string) map[string]string

	// Language returns the language ID this extractor handles.
	Language() string
}

* DocExtractor pulls documentation blocks out of source code and associates

  • them with the symbols they document. *
  • Example:
  • docs := extractor.ExtractDocs(src)

type DocType added in v0.0.16

type DocType int

DocType classifies a file path for chunking strategy selection.

const (
	// DocTypeProse uses paragraph (double-newline) boundaries.
	DocTypeProse DocType = iota
	// DocTypeSource uses blank-line-then-signature boundaries.
	DocTypeSource
)

func DetectDocType added in v0.0.16

func DetectDocType(path string) DocType

* DetectDocType returns the DocType for path based on its file extension.

  • Source code extensions return DocTypeSource; all others return DocTypeProse.
  • Unknown extensions default to DocTypeProse. *
  • Parameters:
  • path (string) — file path; only the extension is examined. *
  • Returns:
  • DocType — DocTypeProse or DocTypeSource. *
  • Example:
  • DetectDocType("main.go") // DocTypeSource
  • DetectDocType("README.md") // DocTypeProse
  • DetectDocType("data.xyz") // DocTypeProse

type DocumentChunk added in v0.0.16

type DocumentChunk struct {
	Content   string
	StartLine int
	EndLine   int
}

* DocumentChunk is a segment of a document produced by ChunkDocument. It

  • carries the chunk text together with its 1-indexed line span in the original
  • document so that LLM prompts and tool responses can cite precise locations. *
  • Fields:
  • Content (string) — the chunk text (trimmed units joined by "\n\n").
  • StartLine (int) — 1-indexed first line of this chunk in the source document.
  • EndLine (int) — 1-indexed last line of this chunk in the source document.
  • With overlap enabled, adjacent chunks share boundary lines. *
  • Example:
  • for i, ch := range chunks {
  • fmt.Printf("chunk %d: lines %d–%d\n", i+1, ch.StartLine, ch.EndLine)
  • }

func ChunkDocument added in v0.0.16

func ChunkDocument(content string, cfg ChunkConfig, docType DocType) []DocumentChunk

* ChunkDocument splits content into DocumentChunks according to cfg and docType.

  • Returns at least one chunk. When content fits within cfg.ChunkSizeBytes,
  • the returned slice has exactly one element covering the full document. *
  • Each chunk records its 1-indexed StartLine and EndLine in the original content.
  • With overlap enabled, the last paragraph of chunk N is repeated at the start
  • of chunk N+1, so adjacent chunks share boundary line numbers. *
  • Overlap behaviour (cfg.Overlap):
  • "paragraph" — the last unit of chunk N is prepended to chunk N+1.
  • "none" — no content is repeated between chunks.
  • (other) — treated as "paragraph". *
  • ChunkDocument never enforces cfg.MaxChunks; that guard is the caller's
  • responsibility so it can prompt the user before proceeding. *
  • Parameters:
  • content (string) — document text to split.
  • cfg (ChunkConfig) — chunking parameters.
  • docType (DocType) — DocTypeProse or DocTypeSource. *
  • Returns:
  • []DocumentChunk — non-empty slice; each element carries Content, StartLine, EndLine. *
  • Example:
  • chunks := ChunkDocument(longMarkdown, DefaultChunkConfig(), DocTypeProse)
  • fmt.Printf("%d chunks, first spans lines %d–%d\n", len(chunks), chunks[0].StartLine, chunks[0].EndLine)

type DocumentationBlock added in v0.0.10

type DocumentationBlock struct {
	Content   string
	StartLine int
	EndLine   int
	Symbol    string
	Type      string
}
  • DocumentationBlock represents a comment or docstring extracted from source. *
  • Fields:
  • Content (string) — the documentation text (comment markers stripped).
  • StartLine (int) — first line of the block, 1-indexed.
  • EndLine (int) — last line of the block, 1-indexed.
  • Symbol (string) — name of the associated symbol, or "" if free-standing.
  • Type (string) — "line_comment", "block_comment", or "docstring". *
  • Example:
  • doc := DocumentationBlock{Content: "Foo does X.", StartLine: 9, EndLine: 9,
  • Symbol: "Foo", Type: "line_comment"}

type DraftOutcome added in v0.0.16

type DraftOutcome struct {
	SectionID  int64
	Document   string
	Heading    string
	Level      string
	Status     string
	Reason     string
	Confidence *float64
}
  • DraftOutcome is what happened to one queue item during a drafting run. *
  • Fields:
  • SectionID (int64) — the document_sections row.
  • Document (string) — the document's title.
  • Heading (string) — the section's heading, empty for the gist.
  • Level (string) — "section" or "gist".
  • Status (string) — "drafted", "skipped" or "failed".
  • Reason (string) — why it was skipped or failed.
  • Confidence (*float64) — the heuristic confidence saved with a draft, or nil. *
  • Example:
  • // {Document: "Notes", Heading: "Alpha", Status: "drafted"}

type DraftReport added in v0.0.16

type DraftReport struct {
	Drafted, Skipped, Failed int
}
  • DraftReport totals a drafting run. *
  • Fields:
  • Drafted (int) — summaries written.
  • Skipped (int) — items not attempted (a gist whose sections have no summary yet).
  • Failed (int) — items the model or the store failed on. *
  • Example:
  • fmt.Printf("%d drafted, %d failed\n", rep.Drafted, rep.Failed)

type Drafter added in v0.0.16

type Drafter interface {
	Name() string
	Draft(ctx context.Context, msgs []Message) (string, error)
}

* Drafter writes a summary for a prompt. It is the only thing about a model

  • that LearnSession knows, so the drafting logic is tested without one, and a
  • routed endpoint, a local llamafile and the active model are all the same
  • to it. *
  • Methods:
  • Name() — the model's name, recorded as the draft's generated_by.
  • Draft() — the model's reply to msgs, exactly as returned. *
  • Example:
  • var d Drafter = newLLMDrafter(target.Client, "granite")

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.Ollama.URL)
  • 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 EngineCaps added in v0.0.19

type EngineCaps struct {
	Tools       CapabilityStatus
	Embed       CapabilityStatus
	Tokenize    CapabilityStatus
	ProcessList CapabilityStatus
}

* EngineCaps states what an engine's server can and cannot do, for the

  • things Harvey would otherwise find out by asking it. A field that is
  • CapNo is not asked about: the request that would learn it is not made. *
  • Fields:
  • Tools (CapabilityStatus) — structured tool calls (a tools key in /api/chat).
  • Embed (CapabilityStatus) — POST /api/embed.
  • Tokenize (CapabilityStatus) — POST /api/tokenize.
  • ProcessList (CapabilityStatus) — GET /api/ps, the running models. *
  • Example:
  • if c, ok := capsForEngine("hailo"); ok && c.Tokenize == CapNo { estimate() }

type EnrichedChunk added in v0.0.10

type EnrichedChunk struct {
	Content     string
	StartLine   int
	StartCol    int
	EndLine     int
	EndCol      int
	ChunkType   string
	Symbols     []string
	Docs        string
	Identifiers map[string][]string
	Citations   []string
}

* EnrichedChunk is a fragment of source code or document text with location

  • and semantic metadata. StartLine/StartCol and EndLine/EndCol give a precise
  • re-location address so a reader can jump directly to the chunk in the source
  • file. Columns are 0-indexed byte offsets from the start of the line. *
  • Fields:
  • Content (string) — the text of this chunk.
  • StartLine (int) — first line of the chunk, 1-indexed.
  • StartCol (int) — byte offset from the start of StartLine, 0-indexed.
  • EndLine (int) — last line of the chunk, 1-indexed.
  • EndCol (int) — byte offset from the start of EndLine, 0-indexed.
  • ChunkType (string) — "function", "class", "procedure", "comment", "code",
  • or for scholarly documents: "abstract", "introduction",
  • "methods", "results", "discussion", "conclusion",
  • "references", "body".
  • Symbols ([]string) — identifiers defined in this chunk.
  • Docs (string) — extracted comment/docstring text associated with the chunk.
  • Identifiers (map[string][]string) — the source document's own scholarly identifiers
  • (DOI, ORCID, ROR, FundRef, etc.), keyed by
  • IdentifierType string; shared across every chunk
  • from the same document. Empty/nil for non-scholarly chunks.
  • Citations ([]string) — scholarly identifiers found in this chunk's text that
  • point to OTHER works (e.g. DOIs cited in a references
  • section). Empty/nil for non-scholarly chunks. *
  • Example:
  • chunk := EnrichedChunk{Content: "func Foo() {}", StartLine: 10, StartCol: 0,
  • EndLine: 10, EndCol: 14, ChunkType: "function", Symbols: []string{"Foo"}}

type ExitClass added in v0.0.17

type ExitClass struct {
	Name string
	Code int
}

* ExitClass is one row of the workspace exit-code table: a class name a

  • machine-readable caller can match on, and the number the process exits with. *
  • Fields:
  • Name (string) — the class name, for example "no_input".
  • Code (int) — the process exit status. *
  • Example:
  • os.Exit(harvey.ClassNoInput.Code) // 66

func ExitClassOf added in v0.0.17

func ExitClassOf(err error) (ExitClass, bool)

* ExitClassOf returns the exit class of err, and whether anything classified

  • it. An explicit class (the outermost *ClassedError in the chain) wins.
  • Otherwise standard-library errors classify themselves: ErrNotFound is
  • negative and ErrInvalid usage; a SQLite error is by result code (see
  • sqliteClass); content that will not decode as JSON is data; fs.ErrNotExist
  • is no_input, fs.ErrPermission no_permission, fs.ErrExist cant_create, any
  • other file error io; a network error (checked by type before the file errors,
  • since a refused connection wraps a syscall error) or an expired deadline is
  • unavailable.
  • An error nothing classified is ClassInternal with false. nil is ClassOK. *
  • Parameters:
  • err (error) — the error to classify; may be nil. *
  • Returns:
  • ExitClass — the class.
  • bool — false only when nothing classified err. *
  • Example:
  • class, ok := harvey.ExitClassOf(fmt.Errorf("read: %w", fs.ErrNotExist)) // ClassNoInput, true

func ExitCodeFor added in v0.0.17

func ExitCodeFor(err error) ExitClass

* ExitCodeFor is the class a binary exits with for err: what ExitClassOf

  • says, and ClassInternal (70, not 1) for an error nothing classified, so a
  • missing classification shows up as an exit code instead of hiding as an
  • ordinary "no". *
  • Parameters:
  • err (error) — the error a run returned; may be nil. *
  • Returns:
  • ExitClass — the class to exit with. *
  • Example:
  • os.Exit(harvey.ExitCodeFor(err).Code)

type ExtensionDetector added in v0.0.10

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

* ExtensionDetector implements LanguageDetector using file-extension matching.

  • It is language-specific: it only returns its own langID. *
  • Example:
  • d := NewExtensionDetector("go", []string{".go", ".mod", ".sum"})
  • lang, conf := d.Detect("main.go", nil) // "go", 1.0

func NewExtensionDetector added in v0.0.10

func NewExtensionDetector(langID string, exts []string) *ExtensionDetector
  • NewExtensionDetector returns an ExtensionDetector for the given language. *
  • Parameters:
  • langID (string) — language identifier, e.g. "go".
  • exts ([]string) — file extensions including the dot, e.g. [".go"]. *
  • Returns:
  • *ExtensionDetector — ready-to-use detector. *
  • Example:
  • d := NewExtensionDetector("pascal", []string{".pas", ".p"})

func (*ExtensionDetector) Detect added in v0.0.10

func (d *ExtensionDetector) Detect(filePath string, content []byte) (string, float64)

* Detect returns (langID, 1.0) when the file extension matches, otherwise

  • ("", 0.0). content is ignored. *
  • Parameters:
  • filePath (string) — path to the file; only the extension is used.
  • content ([]byte) — ignored. *
  • Returns:
  • language (string) — language ID or "".
  • confidence (float64) — 1.0 on match, 0.0 otherwise. *
  • Example:
  • lang, conf := d.Detect("hello.pas", nil) // "pascal", 1.0

func (*ExtensionDetector) DetectFromExtension added in v0.0.10

func (d *ExtensionDetector) DetectFromExtension(ext string) (string, bool)

* DetectFromExtension returns the language ID when ext exactly matches one of

  • the registered extensions for this language. A case-insensitive comparison
  • is also tried as a fallback (e.g., ".Mod" and ".mod" both match Oberon). *
  • Parameters:
  • ext (string) — file extension with leading dot, e.g. ".go". *
  • Returns:
  • language (string) — language ID or "".
  • ok (bool) — true on match. *
  • Example:
  • lang, ok := d.DetectFromExtension(".Mod") // "oberon", true

type FileExternalFormatter added in v0.0.10

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

* FileExternalFormatter invokes an external tool that reads and rewrites a

  • file in-place. The caller MUST write the file to disk first, then call
  • Format. This mode requires safe mode to be disabled at the call site; the
  • formatter itself does not enforce that constraint. *
  • If the executable is not found on $PATH, Format returns (content, nil). *
  • Example:
  • f := newFileExtFormatter("pascal", "ptop", "-")
  • formatted, err := f.Format(content, "/abs/path/module.pas")

func (*FileExternalFormatter) Check added in v0.0.10

func (f *FileExternalFormatter) Check(content string, filePath string) (bool, []FormatIssue)
  • Check reports whether the file is already formatted. *
  • Parameters:
  • content (string) — source code to check.
  • filePath (string) — absolute path hint. *
  • Returns:
  • bool — true when already formatted.
  • []FormatIssue — empty on pass.

func (*FileExternalFormatter) Format added in v0.0.10

func (f *FileExternalFormatter) Format(content string, filePath string) (string, error)

* Format runs the external formatter on filePath (which must already be

  • written to disk) and returns the re-read content. *
  • Parameters:
  • content (string) — original content; returned unchanged on tool error.
  • filePath (string) — absolute path to the already-written file. *
  • Returns:
  • string — reformatted file content, or original content on error.
  • error — non-nil when the tool ran but failed. *
  • Example:
  • out, err := f.Format(src, "/workspace/module.pas")

func (*FileExternalFormatter) Language added in v0.0.10

func (f *FileExternalFormatter) Language() string
  • Language returns the language ID this formatter targets. *
  • Returns:
  • string — language ID.

func (*FileExternalFormatter) Mode added in v0.0.10

  • Mode returns FileFormatter. *
  • Returns:
  • FormatterMode — always FileFormatter.

type FormatIssue added in v0.0.10

type FormatIssue struct {
	Line     int
	Column   int
	Message  string
	Severity string
}
  • FormatIssue describes a formatting problem found by a CodeFormatter. *
  • Fields:
  • Line (int) — 1-indexed line number.
  • Column (int) — 0-indexed byte offset from line start.
  • Message (string) — human-readable description.
  • Severity (string) — "error", "warning", or "info". *
  • Example:
  • issue := FormatIssue{Line: 3, Column: 0, Message: "missing newline", Severity: "warning"}

type FormatterMode added in v0.0.10

type FormatterMode int
  • FormatterMode describes how a CodeFormatter exchanges content with Harvey. *
  • Two modes are supported:
  • PipeFormatter — content is piped to the formatter's stdin; formatted
  • output is read from its stdout. Works with safe mode on.
  • FileFormatter — Harvey writes the file first, then invokes the formatter
  • on the path so it can rewrite the file in place.
  • Requires safe mode off; the executable is validated
  • against allowed_commands before invocation. *
  • Example:
  • if f.Mode() == PipeFormatter { ... }
const (
	// PipeFormatter reads from stdin and writes to stdout.
	PipeFormatter FormatterMode = iota
	// FileFormatter reads and rewrites the file at the given path.
	FileFormatter
)

type HailoBackend added in v0.0.19

type HailoBackend struct {
	*OllamaBackend
}

* HailoBackend is the ManagedBackend for hailo-ollama, the Ollama-shaped

  • server for the Raspberry Pi AI HAT+ 2. It is an engine label over the
  • Ollama client, not a fourth client (DR-0030): it embeds OllamaBackend, so
  • chat, listing and detection are Ollama's, and only the name, the engine
  • label on listed models, and the lifecycle differ. Harvey never starts or
  • stops hailo-ollama. *
  • Example:
  • b := NewHailoBackend("http://localhost:8000", 0, "/workspace/agents")
  • b.SetActiveModel("llama3.2:3b")
  • client, _ := b.NewClient()

func NewHailoBackend added in v0.0.19

func NewHailoBackend(url string, timeout time.Duration, agentsDir string) *HailoBackend

* NewHailoBackend returns a HailoBackend for the hailo-ollama server at url.

  • No network calls are made. *
  • Parameters:
  • url (string) — hailo-ollama base URL, e.g. "http://localhost:8000".
  • timeout (time.Duration) — HTTP timeout for LLM client calls.
  • agentsDir (string) — workspace agents directory. *
  • Returns:
  • *HailoBackend — ready to call Detect() or NewClient(). *
  • Example:
  • b := NewHailoBackend(cfg.Hailo.URL, cfg.Ollama.Timeout, filepath.Join(ws.Root, "agents"))

func (*HailoBackend) ListModels added in v0.0.19

func (b *HailoBackend) ListModels() ([]ModelSummary, error)

* ListModels returns the models pulled on the hailo-ollama server, labelled

  • with the engine "hailo". *
  • Returns:
  • []ModelSummary — one entry per pulled model.
  • error — non-nil if /api/tags cannot be reached. *
  • Example:
  • models, err := b.ListModels()

func (*HailoBackend) Name added in v0.0.19

func (b *HailoBackend) Name() string
  • Name returns the engine label "hailo". *
  • Returns:
  • string — always "hailo". *
  • Example:
  • fmt.Println(b.Name()) // "hailo"

func (*HailoBackend) Start added in v0.0.19

func (b *HailoBackend) Start(_ context.Context, _ string, _ io.Writer) error

* Start does not start anything: Harvey does not launch hailo-ollama. It

  • returns an unavailable error that names the command to run. *
  • Parameters:
  • ctx (context.Context) — unused.
  • model (string) — unused.
  • out (io.Writer) — unused. *
  • Returns:
  • error — always non-nil, class unavailable. *
  • Example:
  • err := b.Start(ctx, "", os.Stdout) // "hailo-ollama is not running; start it with: systemctl --user start hailo-ollama"

func (*HailoBackend) Stop added in v0.0.19

func (b *HailoBackend) Stop() error

* Stop does nothing: Harvey never owns the hailo-ollama process, and killing

  • it mid-request wedges the card. *
  • Returns:
  • error — always nil. *
  • Example:
  • _ = b.Stop()

type HailoConfig added in v0.0.19

type HailoConfig struct {
	URL    string
	URLSet bool
}

* HailoConfig holds the connection setting for a hailo-ollama server, the

  • Ollama-shaped server for the Raspberry Pi AI HAT+ 2. It sits beside
  • OllamaConfig so chat can go to the HAT while embeddings stay on Ollama. *
  • Fields:
  • URL (string) — hailo-ollama base URL; default "http://localhost:8000".
  • URLSet (bool) — true when harvey.yaml gave hailo.url. An unset URL is
  • probed only when a Hailo card is present; a set one is
  • always probed, which is how a remote server is used. *
  • Example:
  • cfg.Hailo = HailoConfig{URL: "http://pi5.local:8000", URLSet: true}

type HailoStatus added in v0.0.19

type HailoStatus struct {
	CardPresent bool
	Probed      bool
	URL         string
	ServerUp    bool
	Catalog     []string
}

* HailoStatus is what DetectHailo found. The card and the server are separate

  • facts: a card with the service stopped, and a server on another machine, are
  • both real cases. *
  • Fields:
  • CardPresent (bool) — the Hailo device node exists on this machine.
  • Probed (bool) — a request was made; false means none was tried.
  • URL (string) — the URL probed; "" when Probed is false.
  • ServerUp (bool) — URL answered /hailo/v1/list in the expected shape.
  • Catalog ([]string) — model names the server can run; empty unless ServerUp. *
  • Example:
  • st := DetectHailo(cfg.Hailo, "")
  • if st.CardPresent && !st.ServerUp { fmt.Println("AI HAT+ 2 found, hailo-ollama is not running") }

func DetectHailo added in v0.0.19

func DetectHailo(cfg HailoConfig, devicePath string) HailoStatus

* DetectHailo looks for a Hailo card and a hailo-ollama server. It probes the

  • server only when a card is present or cfg.URLSet is true; with neither it
  • makes no request, prints nothing and waits for nothing, so a machine without
  • the HAT pays no cost. An answer that is not 200, not JSON, or not
  • {"models": strings} means "not Hailo", never an error. *
  • Parameters:
  • cfg (HailoConfig) — the hailo: section of harvey.yaml.
  • devicePath (string) — the card's device node; "" = /dev/hailo0. *
  • Returns:
  • HailoStatus — what was found; see its fields. *
  • Example:
  • st := DetectHailo(cfg.Hailo, "")
  • if st.ServerUp { fmt.Println(len(st.Catalog), "models in the Hailo catalog") }

type HighlightStyle added in v0.0.10

type HighlightStyle struct {
	Keyword  string
	String   string
	Comment  string
	Number   string
	Operator string
	Function string
	Type     string
	Builtin  string
	Reset    string
}

* HighlightStyle defines ANSI terminal colors for syntax elements.

  • Each field holds an ANSI escape prefix, e.g. "\033[34m" for blue.
  • Empty string means "no color". *
  • Fields:
  • Keyword — color for language keywords.
  • String — color for string literals.
  • Comment — color for comments.
  • Number — color for numeric literals.
  • Operator — color for operators and punctuation.
  • Function — color for function/procedure names.
  • Type — color for type names.
  • Builtin — color for built-in identifiers.
  • Reset — ANSI reset sequence; normally "\033[0m". *
  • Example:
  • style := HighlightStyle{Keyword: "\033[34m", Reset: "\033[0m"}

type IdentifierType added in v0.0.11

type IdentifierType string

* IdentifierType names a kind of scholarly identifier that

  • scholarly_identifiers.go can find and normalize. Values are the
  • lower-case strings used as keys in FindIdentifiers' result map and,
  • later, in the `chunks.identifiers` JSON column and
  • `concepts.identifier_type` column described in
  • towards_a_scholarly_memory_design.md. *
  • Example:
  • var t IdentifierType = IdentifierDOI
  • fmt.Println(string(t)) // "doi"
const (
	// IdentifierDOI is a Digital Object Identifier (10.xxxx/yyyy).
	IdentifierDOI IdentifierType = "doi"
	// IdentifierORCID is a researcher ORCID iD (0000-0003-0900-6903).
	IdentifierORCID IdentifierType = "orcid"
	// IdentifierROR is a Research Organization Registry identifier.
	IdentifierROR IdentifierType = "ror"
	// IdentifierRAiD is a Research Activity Identifier (DataCite DOI
	// resolved via raid.org).
	IdentifierRAiD IdentifierType = "raid"
	// IdentifierArXiv is an arXiv preprint identifier.
	IdentifierArXiv IdentifierType = "arxiv"
	// IdentifierFundRef is a Crossref Funder Registry identifier
	// (a DOI under the reserved 10.13039 prefix).
	IdentifierFundRef IdentifierType = "fundref"
	// IdentifierISBN is an International Standard Book Number
	// (10 or 13 digit).
	IdentifierISBN IdentifierType = "isbn"
	// IdentifierISSN is an International Standard Serial Number.
	IdentifierISSN IdentifierType = "issn"
	// IdentifierISNI is an International Standard Name Identifier.
	IdentifierISNI IdentifierType = "isni"
	// IdentifierPMID is a PubMed identifier.
	IdentifierPMID IdentifierType = "pmid"
	// IdentifierPMCID is a PubMed Central identifier (PMCxxxxxxx).
	IdentifierPMCID IdentifierType = "pmcid"
	// IdentifierVIAF is a Virtual International Authority File identifier.
	IdentifierVIAF IdentifierType = "viaf"
	// IdentifierSNAC is a Social Networks and Archival Context identifier.
	IdentifierSNAC IdentifierType = "snac"
	// IdentifierLCNAF is a Library of Congress Name Authority File
	// identifier.
	IdentifierLCNAF IdentifierType = "lcnaf"
)

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 LanguageDetector added in v0.0.10

type LanguageDetector interface {
	// Detect returns the language ID and a confidence score in [0, 1].
	// A score below 0.5 should be treated as a non-match.
	Detect(filePath string, content []byte) (language string, confidence float64)

	// DetectFromExtension returns the language ID for a file extension (with dot).
	// ok is false when the extension is not recognised.
	DetectFromExtension(ext string) (language string, ok bool)
}
  • LanguageDetector identifies the programming language of a file. *
  • Example:
  • lang, conf := d.Detect("main.go", data)

type LanguageInfo added in v0.0.10

type LanguageInfo struct {
	ID             string
	Name           string
	Extensions     []string
	CommentMarkers []string
	BlockStart     string
	BlockEnd       string
	Shebang        string

	HasChunking     bool
	HasExtraction   bool
	HasFormatting   bool
	HasHighlighting bool
}
  • LanguageInfo holds static metadata about a programming or markup language. *
  • Fields:
  • ID (string) — canonical lowercase identifier, e.g. "go", "c".
  • Name (string) — display name, e.g. "Go", "C".
  • Extensions ([]string) — file extensions including the dot, e.g. [".go"].
  • Extensions are stored as-is (case-preserving);
  • see LanguageRegistry.HasExtension for matching rules.
  • CommentMarkers ([]string) — line and block comment delimiters.
  • BlockStart (string) — token that opens a code block, e.g. "{" or "begin".
  • BlockEnd (string) — token that closes a code block, e.g. "}" or "end".
  • Shebang (string) — typical shebang line when used as a script, or "".
  • HasChunking (bool) — code-aware chunker planned/available.
  • HasExtraction (bool) — documentation extractor planned/available.
  • HasFormatting (bool) — formatter planned/available.
  • HasHighlighting (bool) — syntax highlighter planned/available. *
  • Example:
  • info := LanguageInfo{ID: "go", Name: "Go", Extensions: []string{".go"}}

type LanguageRegistry added in v0.0.10

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

* LanguageRegistry is a central catalogue that maps language identifiers to

  • their metadata and optional handlers (chunker, extractor, formatter,
  • highlighter, detector). *
  • The registry is populated once at package initialisation via init() and is
  • read-only thereafter. No mutex is required for concurrent reads. *
  • Example:
  • lang, ok := globalRegistry.DetectFromExtension(".go")
  • chunker := globalRegistry.GetChunker("go") // nil until Phase 3

func NewLanguageRegistry added in v0.0.10

func NewLanguageRegistry() *LanguageRegistry
  • NewLanguageRegistry returns an empty, ready-to-use registry. *
  • Returns:
  • *LanguageRegistry — empty registry. *
  • Example:
  • r := NewLanguageRegistry()
  • r.RegisterLanguage(goInfo, nil, nil, nil, nil, nil)

func (*LanguageRegistry) DetectFromExtension added in v0.0.10

func (r *LanguageRegistry) DetectFromExtension(ext string) (string, bool)

* DetectFromExtension returns the language ID for the given file extension.

  • ext must include the leading dot, e.g. ".go". Matching is case-sensitive
  • (exact) first; if no exact match is found, a case-insensitive fallback is
  • tried. Returns ("", false) when no language owns that extension. *
  • Parameters:
  • ext (string) — file extension with leading dot, e.g. ".go", ".Mod". *
  • Returns:
  • language (string) — language ID, or "".
  • ok (bool) — true when a match was found. *
  • Example:
  • lang, ok := r.DetectFromExtension(".go") // "go", true
  • lang, ok = r.DetectFromExtension(".Mod") // "oberon", true
  • lang, ok = r.DetectFromExtension(".xyz") // "", false

func (*LanguageRegistry) DetectLanguage added in v0.0.10

func (r *LanguageRegistry) DetectLanguage(filePath string, content []byte) (string, float64)

* DetectLanguage identifies the language of a file using a three-stage pipeline:

  • (1) binary check — returns ("", 0) for binary content,
  • (2) extension-based detection (confidence 1.0),
  • (3) shebang detection (confidence 0.9),
  • (4) keyword pattern detection (variable confidence).
  • Returns ("", 0) when no language can be identified. *
  • Parameters:
  • filePath (string) — path to the file; extension is extracted with filepath.Ext.
  • content ([]byte) — file contents; only the first maxKeywordScan bytes are scanned. *
  • Returns:
  • language (string) — language ID or "".
  • confidence (float64) — confidence in [0, 1]; 0 means "not detected". *
  • Example:
  • lang, conf := globalRegistry.DetectLanguage("main.go", data) // "go", 1.0
  • lang, conf = globalRegistry.DetectLanguage("script", shData) // "python", 0.9

func (*LanguageRegistry) GetChunker added in v0.0.10

func (r *LanguageRegistry) GetChunker(id string) CodeChunker
  • GetChunker returns the CodeChunker registered for id, or nil. *
  • Parameters:
  • id (string) — language ID. *
  • Returns:
  • CodeChunker — handler, or nil. *
  • Example:
  • c := r.GetChunker("c")

func (*LanguageRegistry) GetDetector added in v0.0.10

func (r *LanguageRegistry) GetDetector(id string) LanguageDetector
  • GetDetector returns the LanguageDetector registered for id, or nil. *
  • Parameters:
  • id (string) — language ID. *
  • Returns:
  • LanguageDetector — handler, or nil. *
  • Example:
  • d := r.GetDetector("go")

func (*LanguageRegistry) GetExtractor added in v0.0.10

func (r *LanguageRegistry) GetExtractor(id string) DocExtractor
  • GetExtractor returns the DocExtractor registered for id, or nil. *
  • Parameters:
  • id (string) — language ID. *
  • Returns:
  • DocExtractor — handler, or nil. *
  • Example:
  • e := r.GetExtractor("pascal")

func (*LanguageRegistry) GetFormatter added in v0.0.10

func (r *LanguageRegistry) GetFormatter(id string) CodeFormatter
  • GetFormatter returns the CodeFormatter registered for id, or nil. *
  • Parameters:
  • id (string) — language ID. *
  • Returns:
  • CodeFormatter — handler, or nil. *
  • Example:
  • f := r.GetFormatter("go")

func (*LanguageRegistry) GetHighlighter added in v0.0.10

func (r *LanguageRegistry) GetHighlighter(id string) SyntaxHighlighter
  • GetHighlighter returns the SyntaxHighlighter registered for id, or nil. *
  • Parameters:
  • id (string) — language ID. *
  • Returns:
  • SyntaxHighlighter — handler, or nil. *
  • Example:
  • h := r.GetHighlighter("lisp")

func (*LanguageRegistry) GetLanguageInfo added in v0.0.10

func (r *LanguageRegistry) GetLanguageInfo(id string) (LanguageInfo, bool)

* GetLanguageInfo returns the LanguageInfo for the given language ID.

  • ok is false when the language is not registered. *
  • Parameters:
  • id (string) — language ID, e.g. "go". *
  • Returns:
  • LanguageInfo — metadata struct.
  • bool — true when the language is registered. *
  • Example:
  • info, ok := r.GetLanguageInfo("pascal")

func (*LanguageRegistry) HasExtension added in v0.0.10

func (r *LanguageRegistry) HasExtension(ext string) bool

* HasExtension returns true when ext (matched case-insensitively) belongs to

  • any registered language. Use this for membership tests when you do not need
  • to know which language owns the extension. *
  • Parameters:
  • ext (string) — file extension with leading dot, e.g. ".mod". *
  • Returns:
  • bool — true when the extension is known. *
  • Example:
  • r.HasExtension(".go") // true
  • r.HasExtension(".Mod") // true (Oberon, case-insensitive)
  • r.HasExtension(".xyz") // false

func (*LanguageRegistry) LanguageIDs added in v0.0.10

func (r *LanguageRegistry) LanguageIDs() []string
  • LanguageIDs returns the IDs of all registered languages in an unspecified order. *
  • Returns:
  • []string — slice of language IDs. *
  • Example:
  • for _, id := range r.LanguageIDs() { fmt.Println(id) }

func (*LanguageRegistry) RegisterLanguage added in v0.0.10

func (r *LanguageRegistry) RegisterLanguage(
	info LanguageInfo,
	detector LanguageDetector,
	chunker CodeChunker,
	extractor DocExtractor,
	formatter CodeFormatter,
	highlighter SyntaxHighlighter,
)

* RegisterLanguage adds a language and its optional handlers to the registry.

  • Any handler may be nil; nil handlers are silently ignored in later lookups
  • (GetChunker etc. return nil). Calling RegisterLanguage for the same ID a
  • second time overwrites the previous entry. *
  • Parameters:
  • info (LanguageInfo) — language metadata.
  • detector (LanguageDetector) — content/extension detector, or nil.
  • chunker (CodeChunker) — code-aware chunker, or nil.
  • extractor (DocExtractor) — documentation extractor, or nil.
  • formatter (CodeFormatter) — code formatter, or nil.
  • highlighter (SyntaxHighlighter)— syntax highlighter, or nil. *
  • Example:
  • r.RegisterLanguage(goInfo, nil, nil, nil, nil, nil)

func (*LanguageRegistry) SetChunker added in v0.0.10

func (r *LanguageRegistry) SetChunker(id string, c CodeChunker)

* SetChunker registers a CodeChunker for an already-registered language ID.

  • Calling SetChunker for an unregistered ID is a no-op (the chunker is stored
  • but no language metadata exists to associate it with). *
  • Parameters:
  • id (string) — language identifier, e.g. "c".
  • c (CodeChunker) — chunker to register. *
  • Example:
  • r.SetChunker("c", NewCChunker("c"))

func (*LanguageRegistry) SetExtractor added in v0.0.10

func (r *LanguageRegistry) SetExtractor(id string, e DocExtractor)

* SetExtractor registers a DocExtractor for an already-registered language ID.

  • Calling SetExtractor for an unregistered ID is a no-op (the extractor is
  • stored but no language metadata exists to associate it with). *
  • Parameters:
  • id (string) — language identifier, e.g. "c".
  • e (DocExtractor)— extractor to register. *
  • Example:
  • r.SetExtractor("c", NewCDocExtractor("c"))

func (*LanguageRegistry) SetFormatter added in v0.0.10

func (r *LanguageRegistry) SetFormatter(id string, f CodeFormatter)
  • SetFormatter registers a CodeFormatter for an already-registered language ID. *
  • Parameters:
  • id (string) — language identifier, e.g. "go".
  • f (CodeFormatter) — formatter to register. *
  • Example:
  • r.SetFormatter("go", newPipeExtFormatter("go", "gofmt"))

func (*LanguageRegistry) SetHighlighter added in v0.0.10

func (r *LanguageRegistry) SetHighlighter(id string, h SyntaxHighlighter)

* SetHighlighter registers a SyntaxHighlighter for an already-registered

  • language ID. *
  • Parameters:
  • id (string) — language identifier, e.g. "c".
  • h (SyntaxHighlighter)— highlighter to register. *
  • Example:
  • r.SetHighlighter("c", NewTerminalHighlighter())

type LearnCandidate added in v0.0.16

type LearnCandidate struct {
	Path       string
	StoredPath string
	Kind       string
	Words      int
	Turns      int
	ModTime    time.Time
}

* LearnCandidate is one file `/kb learn ingest` can offer to the knowledge

  • base as a document: a recorded session or a hand-off note. *
  • Fields:
  • Path (string) — absolute path of the file.
  • StoredPath (string) — the path form passed to IngestDocument: relative
  • to the working directory, with forward slashes,
  • which is what `kb document ingest FILE` stores
  • when run from there. DocumentByPath is an exact
  • match, so this form is a contract across tools.
  • Kind (string) — "hand-off" or "session".
  • Words (int) — whitespace-separated words in the file.
  • Turns (int) — chat turns recorded in it, for information; it
  • is not used to decide anything.
  • ModTime (time.Time) — the file's modification time, used to list the
  • newest first. *
  • Example:
  • cs, _ := learnCandidates(kb, ws.Root, 200)
  • fmt.Println(cs[0].Kind, cs[0].StoredPath)

type LearnSession added in v0.0.16

type LearnSession struct {
	KB             *knowledge.KnowledgeBase
	ProjectID      int64
	Drafter        Drafter
	MaxSourceBytes int
}

* LearnSession is the terminal-free core of learning mode

  • (knowledge-learning-mode-design.md decisions 3 to 5). It drafts summaries for
  • the review queue through a Drafter, and it promotes a summary only from
  • Accept, the human keypath: "a model may write but not accept" is
  • `knowledge`'s rule, enforced here by construction, and a test asserts that
  • exactly one call to PromoteDocumentSummary exists, in Accept. A terminal or a
  • later bubbletea menu is a renderer over this type. *
  • Fields:
  • KB (*knowledge.KnowledgeBase) — the open knowledge base.
  • ProjectID (int64) — whose queue this session works.
  • Drafter (Drafter) — the model that drafts; may be nil for a session that only reviews.
  • MaxSourceBytes (int) — cap on a section's text in a prompt; zero uses the default. *
  • Example:
  • s := &LearnSession{KB: a.KB, ProjectID: pid, Drafter: newLLMDrafter(a.Client, "")}
  • rep, err := s.DraftPending(ctx, 25, nil)

func (*LearnSession) Accept added in v0.0.16

func (s *LearnSession) Accept(sectionID int64) error

* Accept promotes a drafted summary to reviewed, the only human action that

  • makes a summary trusted and searchable. It is the single place harvey calls
  • PromoteDocumentSummary. A section that was never drafted is refused by the
  • knowledge base. *
  • Parameters:
  • sectionID (int64) — the document_sections row to promote. *
  • Returns:
  • error — if the section is not drafted, or on database failure. *
  • Example:
  • err := s.Accept(item.ID)

func (*LearnSession) DraftPending added in v0.0.16

func (s *LearnSession) DraftPending(ctx context.Context, limit int, progress func(DraftOutcome, int, int)) (DraftReport, error)

* DraftPending drafts a summary for every unsummarized item in the session's

  • project: the sections first, then the gist of each document whose sections
  • now all have one. Nothing is promoted; every draft waits in the review queue
  • for a human. A failure on one item is recorded and the run continues. Items
  • that are already drafted or reviewed are left alone. *
  • Parameters:
  • ctx (context.Context) — cancels the run between items.
  • limit (int) — most items to attempt (drafted or failed); 0 means all.
  • progress (func(DraftOutcome, int, int)) — called after each item with the outcome, the number attempted so far and the number planned; may be nil. *
  • Returns:
  • DraftReport — totals.
  • error — on a database failure listing the queue, or ctx being cancelled. *
  • Example:
  • rep, err := s.DraftPending(ctx, 25, func(o DraftOutcome, done, total int) { fmt.Println(done, total, o.Status) })

func (*LearnSession) DraftedItems added in v0.0.16

func (s *LearnSession) DraftedItems() ([]knowledge.DocumentReviewItem, error)

* DraftedItems returns the human review queue: drafted items awaiting accept,

  • edit or skip: sections first, then gists (a gist is drafted from the section
  • summaries, so it is reviewed after them), otherwise document then position. *
  • Returns:
  • []knowledge.DocumentReviewItem — the drafted items.
  • error — on database failure. *
  • Example:
  • items, _ := s.DraftedItems()

func (*LearnSession) Edit added in v0.0.16

func (s *LearnSession) Edit(sectionID int64, text string) error

* Edit replaces a section's draft with text a human wrote or edited, recorded

  • as generated_by "human" with no confidence. It leaves the section drafted:
  • editing is not accepting. *
  • Parameters:
  • sectionID (int64) — the document_sections row.
  • text (string) — the new summary; empty text is refused. *
  • Returns:
  • error — for empty text, or on database failure. *
  • Example:
  • err := s.Edit(item.ID, edited)

func (*LearnSession) Redraft added in v0.0.16

func (s *LearnSession) Redraft(ctx context.Context, sectionID int64) error

* Redraft asks the model for a fresh draft of a queue item and replaces the

  • existing one. The section stays drafted. *
  • Parameters:
  • ctx (context.Context) — cancels the call.
  • sectionID (int64) — the document_sections row. *
  • Returns:
  • error — if the item is not in the review queue, the model failed, or on database failure. *
  • Example:
  • err := s.Redraft(ctx, item.ID)

type LispChunker added in v0.0.10

type LispChunker struct{}

* LispChunker splits Lisp/Common Lisp/Emacs Lisp source into enriched chunks

  • at parenthesis-balanced top-level form boundaries. Each defun, defmacro,
  • defvar, defclass, etc. becomes its own chunk. *
  • Example:
  • l := NewLispChunker()
  • chunks := l.Chunk("(defun hello () (print \"hi\"))", "greet.lisp")

func NewLispChunker added in v0.0.10

func NewLispChunker() *LispChunker
  • NewLispChunker returns a LispChunker. *
  • Returns:
  • *LispChunker — ready-to-use chunker. *
  • Example:
  • l := NewLispChunker()

func (*LispChunker) Chunk added in v0.0.10

func (l *LispChunker) Chunk(content string, _ string) []EnrichedChunk
  • Chunk splits Lisp source into enriched chunks at top-level form boundaries. *
  • Parameters:
  • content (string) — Lisp source text.
  • filePath (string) — source path; used for context only. *
  • Returns:
  • []EnrichedChunk — chunks with location and symbol metadata. *
  • Example:
  • chunks := l.Chunk(src, "funcs.lisp")

func (*LispChunker) Language added in v0.0.10

func (l *LispChunker) Language() string
  • Language returns "lisp". *
  • Returns:
  • string — "lisp". *
  • Example:
  • l.Language() // "lisp"

type LispDocExtractor added in v0.0.10

type LispDocExtractor struct{}

* LispDocExtractor extracts documentation from Lisp/Common Lisp/Emacs Lisp source.

  • It recognises semicolon line comments (;, ;;, ;;;), block comments (#| |#),
  • and docstrings embedded in DEFUN/DEFMACRO/DEFMETHOD forms. *
  • Example:
  • e := NewLispDocExtractor()
  • docs := e.ExtractDocs(";; Add two numbers.\n(defun add (a b) \"Add a and b.\" (+ a b))\n")

func NewLispDocExtractor added in v0.0.10

func NewLispDocExtractor() *LispDocExtractor
  • NewLispDocExtractor returns a LispDocExtractor. *
  • Returns:
  • *LispDocExtractor — ready-to-use extractor. *
  • Example:
  • l := NewLispDocExtractor()

func (*LispDocExtractor) ExtractDocs added in v0.0.10

func (e *LispDocExtractor) ExtractDocs(content string) []DocumentationBlock
  • ExtractDocs returns all DocumentationBlocks found in Lisp source. *
  • Parameters:
  • content (string) — Lisp source text. *
  • Returns:
  • []DocumentationBlock — blocks including semicolon comments, #| |# blocks,
  • and DEFUN docstrings. *
  • Example:
  • docs := e.ExtractDocs(";; Returns x.\n(defun get-x () x)\n")

func (*LispDocExtractor) ExtractSymbols added in v0.0.10

func (e *LispDocExtractor) ExtractSymbols(content string) map[string]string
  • ExtractSymbols returns a map of symbol name → documentation text for Lisp. *
  • Parameters:
  • content (string) — Lisp source text. *
  • Returns:
  • map[string]string — symbol → doc text. *
  • Example:
  • syms := e.ExtractSymbols(";; Returns x.\n(defun get-x () x)\n")
  • // syms["get-x"] == "Returns x."

func (*LispDocExtractor) Language added in v0.0.10

func (e *LispDocExtractor) Language() string
  • Language returns "lisp". *
  • Returns:
  • string — "lisp". *
  • Example:
  • e.Language() // "lisp"

type LlamaCppBackend added in v0.0.16

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

* LlamaCppBackend implements ManagedBackend for the llama.cpp llama-server process.

  • It exposes an OpenAI-compatible API at BaseURL/v1, so the same LLM client
  • used for llamafile works here. Start launches llama-server with --model, --port,
  • and optional --ctx-size / --threads / --n-gpu-layers flags. ListModels scans
  • modelsDir for *.gguf files; unless llamacpp.models_dir is set that is
  • llama.cpp's own download cache (see llamaCppDefaultModelsDir). *
  • Fields:
  • serverBin (string) — path to llama-server binary; "" = "llama-server" (PATH lookup).
  • url (string) — API base URL, e.g. "http://127.0.0.1:8081".
  • agentsDir (string) — directory for the PID file.
  • modelsDir (string) — directory scanned by ListModels for *.gguf files.
  • ctxSize (int) — --ctx-size; 0 = server default.
  • threads (int) — --threads; 0 = server default.
  • gpuLayers (int) — --n-gpu-layers; 0 = CPU-only.
  • pinCPU (bool) — wrap launch with `taskset -c 0-(threads-1)`; requires threads > 0.
  • startTimeout (time.Duration) — how long to wait for the server after launch.
  • activeModel (string) — model name set on Start.
  • running (bool) — reflects the last Detect probe.
  • proc (*os.Process) — process Harvey started; nil if adopted externally. *
  • Example:
  • b := NewLlamaCppBackend(cfg, filepath.Join(ws.Root, "agents"))
  • if err := b.Start(ctx, "/home/user/Models/phi4-Q4_K_M.gguf", os.Stdout); err != nil { ... }

func NewLlamaCppBackend added in v0.0.16

func NewLlamaCppBackend(cfg *Config, agentsDir string) *LlamaCppBackend

* NewLlamaCppBackend returns a LlamaCppBackend configured from cfg.

  • No network calls are made during construction. *
  • Parameters:
  • cfg (*Config) — source of LlamaCpp settings (URL, GPULayers, CtxSize, etc.).
  • agentsDir (string) — directory for the PID file. *
  • Returns:
  • *LlamaCppBackend — ready to call Detect() or Start(). *
  • Example:
  • b := NewLlamaCppBackend(cfg, filepath.Join(ws.Root, "agents"))

func (*LlamaCppBackend) ActiveModel added in v0.0.16

func (b *LlamaCppBackend) ActiveModel() string
  • ActiveModel returns the name of the model currently in use, or "" when none is set. *
  • Returns:
  • string — model name, or "" before Start is called. *
  • Example:
  • fmt.Println(b.ActiveModel()) // "phi4-Q4_K_M"

func (*LlamaCppBackend) BaseURL added in v0.0.16

func (b *LlamaCppBackend) BaseURL() string
  • BaseURL returns the HTTP base URL of the llama-server. *
  • Returns:
  • string — the URL configured for this backend. *
  • Example:
  • fmt.Println(b.BaseURL()) // "http://127.0.0.1:8081"

func (*LlamaCppBackend) Detect added in v0.0.16

func (b *LlamaCppBackend) Detect() bool

* Detect probes the llama-server at BaseURL/health and updates IsRunning.

  • llama-server exposes GET /health which returns {"status":"ok"} when ready. *
  • Returns:
  • bool — true if the server is reachable and healthy. *
  • Example:
  • if b.Detect() { fmt.Println("llama-server is up") }

func (*LlamaCppBackend) IsRunning added in v0.0.16

func (b *LlamaCppBackend) IsRunning() bool

* IsRunning reports the result of the most recent Detect probe without making

  • a network call. Call Detect() first to refresh. *
  • Returns:
  • bool — true if the last Detect() succeeded. *
  • Example:
  • b.Detect()
  • if b.IsRunning() { ... }

func (*LlamaCppBackend) ListModels added in v0.0.16

func (b *LlamaCppBackend) ListModels() ([]ModelSummary, error)

* ListModels scans modelsDir for *.gguf files and returns a backend-neutral

  • ModelSummary for each one found. *
  • Returns:
  • []ModelSummary — one entry per .gguf file found in modelsDir.
  • error — non-nil only on unexpected filesystem errors. *
  • Example:
  • models, err := b.ListModels()
  • for _, m := range models { fmt.Println(m.Name, m.SizeBytes) }

func (*LlamaCppBackend) ModelPath added in v0.0.16

func (b *LlamaCppBackend) ModelPath() string

* ModelPath returns the absolute path of the active model file, reconstructed

  • from modelsDir and activeModel. Returns "" when no model is active. *
  • Returns:
  • string — absolute path ending in ".gguf", or "". *
  • Example:
  • fmt.Println(b.ModelPath()) // "/Users/user/Models/SmolLM3-3B-Instruct-Q4_K_M.gguf"

func (*LlamaCppBackend) Name added in v0.0.16

func (b *LlamaCppBackend) Name() string
  • Name returns the backend identifier "llamacpp". *
  • Returns:
  • string — always "llamacpp". *
  • Example:
  • fmt.Println(b.Name()) // "llamacpp"

func (*LlamaCppBackend) NewClient added in v0.0.16

func (b *LlamaCppBackend) NewClient() (LLMClient, error)

* NewClient returns an LLM client configured for the active model.

  • Returns an error when no active model has been set (call Start first). *
  • Returns:
  • LLMClient — client pointing at BaseURL/v1 with the active model name.
  • error — non-nil when ActiveModel is empty. *
  • Example:
  • client, err := b.NewClient()

func (*LlamaCppBackend) Start added in v0.0.16

func (b *LlamaCppBackend) Start(ctx context.Context, model string, out io.Writer) error

* Start launches llama-server for the given model path, waits for the health

  • endpoint to respond, and writes a PID file. If a server is already running
  • at BaseURL, Start adopts it without launching a new process. *
  • Parameters:
  • ctx (context.Context) — controls the launch lifetime (passed for interface conformance; actual timeout is b.startTimeout).
  • model (string) — absolute path to a .gguf model file.
  • out (io.Writer) — status messages sink. *
  • Returns:
  • error — non-nil if the binary cannot be launched or the server does not respond. *
  • Example:
  • err := b.Start(ctx, "/home/user/Models/phi4-Q4_K_M.gguf", os.Stdout)

func (*LlamaCppBackend) StartedByHarvey added in v0.0.16

func (b *LlamaCppBackend) StartedByHarvey() bool
  • StartedByHarvey reports whether Harvey launched this server process. *
  • Returns:
  • bool — true when Harvey started the process (proc != nil). *
  • Example:
  • if b.StartedByHarvey() { defer b.Stop() }

func (*LlamaCppBackend) Stop added in v0.0.16

func (b *LlamaCppBackend) Stop() error

* Stop sends SIGINT to the llama-server Harvey started. Safe to call when

  • Harvey did not start the server (no-op) or when the process is already gone.
  • Also deletes the PID file on success. *
  • Returns:
  • error — non-nil only on unexpected kill failures. *
  • Example:
  • defer b.Stop()

type LlamaCppConfig added in v0.0.16

type LlamaCppConfig struct {
	ServerBin    string        // path to llama-server binary; "" = "llama-server" (PATH lookup)
	ModelsDir    string        // directory for *.gguf files; "" = llama.cpp's cache (llamaCppDefaultModelsDir)
	URL          string        // API base URL; default http://127.0.0.1:8081
	CtxSize      int           // --ctx-size; 0 = server default
	Threads      int           // --threads; 0 = server default
	GPULayers    int           // --n-gpu-layers; 0 = CPU-only
	PinCPU       bool          // wrap launch with `taskset -c 0-(Threads-1)`; requires Threads > 0
	StartTimeout time.Duration // startup probe timeout; default 120s
}
  • LlamaCppConfig holds workspace-level llama.cpp (llama-server) settings. *
  • Fields:
  • ServerBin (string) — path to the llama-server binary; defaults to "llama-server" (PATH lookup).
  • ModelsDir (string) — directory scanned for *.gguf model files; defaults to llama.cpp's cache ($LLAMA_CACHE, else ~/.cache/llama.cpp).
  • URL (string) — API base URL; defaults to http://127.0.0.1:8081.
  • CtxSize (int) — --ctx-size passed to llama-server; 0 = server default.
  • Threads (int) — --threads; 0 = server default.
  • GPULayers (int) — --n-gpu-layers; 0 = CPU-only.
  • PinCPU (bool) — wrap the launch with `taskset -c 0-(Threads-1)`; no-op if Threads is 0 or taskset is unavailable.
  • StartTimeout (time.Duration) — how long to wait for the server to respond on startup; default 120s. *
  • Example:
  • cfg.LlamaCpp = LlamaCppConfig{URL: "http://127.0.0.1:8081", GPULayers: 35}

type LlamafileBackend added in v0.0.16

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

* LlamafileBackend implements ManagedBackend for llamafile inference servers.

  • Each llamafile binary is its own single-model server; Start launches the
  • binary for the requested model path. It wraps StartLlamafileService and
  • adds unified lifecycle tracking through the ManagedBackend interface. *
  • Fields:
  • url (string) — llamafile server base URL, e.g. "http://localhost:8080".
  • timeout (time.Duration) — HTTP client timeout passed to the LLM client.
  • agentsDir (string) — directory for the PID file.
  • modelsDir (string) — directory scanned by ListModels for *.llamafile files.
  • workspaceRoot (string) — workspace root used to resolve relative model paths.
  • gpuLayers (int) — -ngl value; -1 = CPU, 99 = maximise GPU.
  • ctxSize (int) — -c value; 0 = server default.
  • startupTimeout (time.Duration) — how long to wait for the server after launch.
  • maxTokens (int) — max completion tokens; 0 = no limit.
  • activeModel (string) — model name recorded when Start is called.
  • running (bool) — reflects the last Detect probe.
  • proc (*os.Process) — process Harvey started; nil if adopted externally. *
  • Example:
  • b := NewLlamafileBackend(cfg, filepath.Join(ws.Root, "agents"), ws.Root)
  • if err := b.Start(ctx, "/home/user/Models/phi4.llamafile", out); err != nil { ... }

func NewLlamafileBackend added in v0.0.16

func NewLlamafileBackend(cfg *Config, agentsDir, workspaceRoot string) *LlamafileBackend

* NewLlamafileBackend returns a LlamafileBackend configured from cfg.

  • No network calls are made during construction. *
  • Parameters:
  • cfg (*Config) — source of URL, GPU layers, timeout, models dir, etc.
  • agentsDir (string) — directory for the PID file.
  • workspaceRoot (string) — workspace root for resolving relative model paths. *
  • Returns:
  • *LlamafileBackend — ready to call Detect() or Start(). *
  • Example:
  • b := NewLlamafileBackend(cfg, filepath.Join(ws.Root, "agents"), ws.Root)

func (*LlamafileBackend) ActiveModel added in v0.0.16

func (b *LlamafileBackend) ActiveModel() string
  • ActiveModel returns the name of the model currently in use, or "" when none is set. *
  • Returns:
  • string — model name, or "" before Start is called. *
  • Example:
  • fmt.Println(b.ActiveModel()) // "phi4-Q4_K_M"

func (*LlamafileBackend) BaseURL added in v0.0.16

func (b *LlamafileBackend) BaseURL() string
  • BaseURL returns the HTTP base URL of the llamafile server. *
  • Returns:
  • string — the URL configured for this backend. *
  • Example:
  • fmt.Println(b.BaseURL()) // "http://localhost:8080"

func (*LlamafileBackend) Detect added in v0.0.16

func (b *LlamafileBackend) Detect() bool
  • Detect probes the llamafile server at BaseURL and updates IsRunning. *
  • Returns:
  • bool — true if the server is reachable at /v1/models. *
  • Example:
  • if b.Detect() { fmt.Println("llamafile is up") }

func (*LlamafileBackend) IsRunning added in v0.0.16

func (b *LlamafileBackend) IsRunning() bool

* IsRunning reports the result of the most recent Detect probe without making

  • a network call. Call Detect() first to refresh. *
  • Returns:
  • bool — true if the last Detect() succeeded. *
  • Example:
  • b.Detect()
  • if b.IsRunning() { ... }

func (*LlamafileBackend) ListModels added in v0.0.16

func (b *LlamafileBackend) ListModels() ([]ModelSummary, error)

* ListModels scans modelsDir for *.llamafile (and *.llamafile.exe) files and

  • returns a backend-neutral ModelSummary for each one found. *
  • Returns:
  • []ModelSummary — one entry per .llamafile file found in modelsDir.
  • error — non-nil only on unexpected filesystem errors. *
  • Example:
  • models, err := b.ListModels()
  • for _, m := range models { fmt.Println(m.Name, m.SizeBytes) }

func (*LlamafileBackend) Name added in v0.0.16

func (b *LlamafileBackend) Name() string
  • Name returns the backend identifier "llamafile". *
  • Returns:
  • string — always "llamafile". *
  • Example:
  • fmt.Println(b.Name()) // "llamafile"

func (*LlamafileBackend) NewClient added in v0.0.16

func (b *LlamafileBackend) NewClient() (LLMClient, error)

* NewClient returns a wired LLMClient pointing at the running llamafile server

  • using the active model name. Returns an error when no active model has been set. *
  • Returns:
  • LLMClient — ready for chat calls.
  • error — non-nil when ActiveModel() is "". *
  • Example:
  • client, err := b.NewClient()

func (*LlamafileBackend) Start added in v0.0.16

func (b *LlamafileBackend) Start(ctx context.Context, model string, out io.Writer) error

* Start launches the llamafile binary at model (an absolute path or a path

  • relative to workspaceRoot), waits for the server to become reachable, sets
  • the active model name to the stem of the path, marks StartedByHarvey, and
  • writes a PID file. If a server is already running at BaseURL, Start adopts
  • it without launching a new process. *
  • Parameters:
  • ctx (context.Context) — controls the launch lifetime (passed for interface conformance; actual timeout is b.startupTimeout).
  • model (string) — absolute or workspace-relative path to the .llamafile binary.
  • out (io.Writer) — status messages sink. *
  • Returns:
  • error — non-nil if the binary cannot be launched or the server does not respond. *
  • Example:
  • err := b.Start(ctx, "/home/user/Models/phi4.llamafile", os.Stdout)

func (*LlamafileBackend) StartedByHarvey added in v0.0.16

func (b *LlamafileBackend) StartedByHarvey() bool

* StartedByHarvey reports whether Harvey launched the llamafile process in

  • this session. Returns false when the server was adopted from an external process. *
  • Returns:
  • bool — true when Harvey started the llamafile server. *
  • Example:
  • if b.StartedByHarvey() { defer b.Stop() }

func (*LlamafileBackend) Stop added in v0.0.16

func (b *LlamafileBackend) Stop() error

* Stop sends SIGINT to the llamafile process Harvey started. Safe to call

  • when Harvey did not start the server (no-op) or when the process is gone.
  • Also deletes the PID file on success. *
  • Returns:
  • error — non-nil only on unexpected kill failures. *
  • Example:
  • defer b.Stop()

type LlamafileConfig added in v0.0.16

type LlamafileConfig struct {
	URL            string
	ModelsDir      string
	StartupTimeout time.Duration
	GPULayers      int
	MaxTokens      int
	Models         []LlamafileEntry
	Active         string
}
  • LlamafileConfig holds settings for the llamafile inference backend. *
  • Fields:
  • URL (string) — API base URL; default "http://localhost:8080".
  • ModelsDir (string) — discovery directory; default "$HOME/Models".
  • StartupTimeout (time.Duration) — how long to wait for server response; default 120s.
  • GPULayers (int) — -ngl value; 0 = CPU-only (default; safe on every
  • platform Harvey targets, including Raspberry Pi,
  • which has no usable GPU-compute backend). Set to
  • 99 (maximise GPU) or a specific layer count in
  • harvey.yaml on hardware with real GPU support.
  • MaxTokens (int) — max tokens per completion; 0 = no limit.
  • Models ([]LlamafileEntry) — registered llamafile models.
  • Active (string) — name of the active model; "" = none. *
  • Example:
  • cfg.Llamafile = LlamafileConfig{URL: "http://localhost:8080", GPULayers: 0}

type LlamafileEntry added in v0.0.12

type LlamafileEntry struct {
	Name          string `yaml:"name"`
	Path          string `yaml:"path"`
	ContextLength int    `yaml:"context_length,omitempty"`
}
  • LlamafileEntry describes a registered llamafile model. *
  • Fields:
  • Name (string) — short identifier used with /model use and /model alias add.
  • Path (string) — path to the llamafile binary, relative to workspace root or absolute.
  • ContextLength (int) — context window size in tokens; 0 means unknown (probed at startup). *
  • Example:
  • e := LlamafileEntry{Name: "qwen-coding", Path: "~/Models/Qwen2.5-Coder-7B.llamafile", ContextLength: 8192}

type LlamafileProps added in v0.0.16

type LlamafileProps struct {
	SupportsTools CapabilityStatus
	ToolMode      string
}

* LlamafileProps holds the capability information extracted from the /props

  • endpoint of a running llamafile or llama.cpp server. *
  • Fields:
  • SupportsTools (CapabilityStatus) — CapYes when a recognised tool-call marker
  • was found in chat_template; CapNo otherwise.
  • ToolMode (string) — ToolModeStructured when tools are supported;
  • ToolModeNone otherwise. *
  • Example:
  • props := ProbeLlamafileProps("http://localhost:8080")
  • fmt.Println(props.SupportsTools) // "✓" or "—"

func ProbeLlamafileProps added in v0.0.16

func ProbeLlamafileProps(baseURL string) LlamafileProps

* ProbeLlamafileProps reads the /props endpoint of a running llamafile or

  • llama.cpp server and returns the detected tool-calling capability derived
  • from the chat_template field. It recognises the following markers: *
  • <tool_call> — Qwen / Hermes style
  • [TOOL_CALLS] — Mistral style
  • <|python_tag|> — Llama 3.1+ style
  • <|tool_call|> — Phi-3/4 style *
  • When any marker is found, SupportsTools is CapYes and ToolMode is
  • ToolModeStructured. When /props is unreachable or returns no template,
  • SupportsTools is CapNo and ToolMode is ToolModeNone. *
  • Parameters:
  • baseURL (string) — llamafile server base URL, e.g. "http://localhost:8080". *
  • Returns:
  • LlamafileProps — detected capability; CapNo/ToolModeNone on any error. *
  • Example:
  • props := ProbeLlamafileProps("http://localhost:8080")
  • if props.SupportsTools == CapYes {
  • fmt.Println("model supports structured tool calls")
  • }

type ManagedBackend added in v0.0.16

type ManagedBackend interface {
	Name() string
	BaseURL() string
	ActiveModel() string
	IsRunning() bool
	Detect() bool
	Start(ctx context.Context, model string, out io.Writer) error
	Stop() error
	ListModels() ([]ModelSummary, error)
	NewClient() (LLMClient, error)
	StartedByHarvey() bool
}

* ManagedBackend represents a local inference backend Harvey can start,

  • stop, and query. It is implemented by OllamaBackend, LlamafileBackend,
  • and LlamaCppBackend. All methods must be safe to call when the backend
  • is not running; Start and Stop are idempotent. *
  • Methods:
  • Name() — backend identifier: "ollama", "llamafile", or "llamacpp".
  • BaseURL() — HTTP base URL of the server, e.g. "http://127.0.0.1:11434".
  • ActiveModel() — name of the currently loaded model, or "" when idle.
  • IsRunning() — true when the server is reachable via HTTP probe.
  • Detect() — probe the server and return IsRunning().
  • Start() — launch the server with the given model; writes PID file.
  • Stop() — stop the server Harvey started; no-op if not owned.
  • ListModels() — enumerate locally available models.
  • NewClient() — return a wired LLMClient pointing at the running server.
  • StartedByHarvey() — true when Harvey started the currently running server. *
  • Example:
  • var b ManagedBackend = NewOllamaBackend(cfg)
  • if b.Detect() {
  • client, _ := b.NewClient()
  • }

type Manifest added in v0.0.6

type Manifest struct {
	Sessions []ManifestEntry   `yaml:"sessions"`
	Failures []ManifestFailure `yaml:"failures,omitempty"`
}

* 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) FailedOn added in v0.0.19

func (m *Manifest) FailedOn(sessionPath, model string) bool
  • FailedOn reports whether model has already failed to process sessionPath. *
  • Parameters:
  • sessionPath (string) — the session file.
  • model (string) — engine-qualified model key. *
  • Returns:
  • bool — true when a failure is recorded for that session and model. *
  • Example:
  • if m.FailedOn(path, key) {
  • fmt.Println("try another model")
  • }

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) RecordEmpty added in v0.0.19

func (m *Manifest) RecordEmpty(sessionPath string)

* RecordEmpty appends an entry for a session with no dialogue, so it stops

  • counting as unmined. Status is ManifestStatusEmpty. *
  • Parameters:
  • sessionPath (string) — path to the empty session file. *
  • Example:
  • m.RecordEmpty("agents/sessions/foo.spmd")
  • m.Save(store.Dir())

func (*Manifest) RecordFailure added in v0.0.19

func (m *Manifest) RecordFailure(sessionPath, model, reason string)

* RecordFailure remembers that model could not process sessionPath. The

  • session stays unmined. One entry is kept per session and model; a repeat
  • replaces the reason and time. *
  • Parameters:
  • sessionPath (string) — the session file.
  • model (string) — engine-qualified model key.
  • reason (string) — why the model could not process it. *
  • Example:
  • m.RecordFailure(path, "hailo/qwen2.5-coder:1.5b", "reply truncated")

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"`
	Status          string   `yaml:"status,omitempty"`
}
  • 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.
  • Status (string) — "" for a session a model processed, or
  • ManifestStatusEmpty for one with no dialogue. *
  • Example:
  • fmt.Printf("mined %s: created %d, skipped %d\n",
  • e.Path, len(e.MemoriesCreated), e.MemoriesSkipped)

type ManifestFailure added in v0.0.19

type ManifestFailure struct {
	Path   string `yaml:"path"`
	Model  string `yaml:"model"`
	Reason string `yaml:"reason"`
	At     string `yaml:"at"`
}

* ManifestFailure records that a model could not process a session: the

  • reply was cut off, or it was not the JSON the miner asked for. The session
  • is not mined; the entry stops auto-mining from asking the same model again. *
  • Fields:
  • Path (string) — the session file.
  • Model (string) — the engine-qualified model key (see Agent.modelKey).
  • Reason (string) — why, in a sentence.
  • At (string) — RFC3339 time of the most recent failure. *
  • Example:
  • m.RecordFailure("agents/sessions/foo.spmd", "hailo/qwen2.5-coder:1.5b", "reply truncated")

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, empty Supersedes, and default Confidence of 0.5.
  • The caller is responsible for populating FountainBody, Kind, and Action
  • 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 explanation of what happened and why it matters.
  • tags ([]string) — keyword tags for filtering. *
  • Returns:
  • *MemoryDoc — new document with empty FountainBody, Kind, Action and Confidence 0.5. *
  • Example:
  • doc := NewMemoryDoc("git_fix_a3f891", MemoryTypeToolUse,
  • "Fixed fatal: not a git repository", "...", []string{"git","fix"})
  • doc.Meta.Kind = "pitfall"
  • doc.Meta.Action = "Run `git init` in project root, then retry."

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, summary, and action (when present)
  • 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"`
	Kind          string         `yaml:"kind,omitempty"`
	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"`
	Action        string         `yaml:"action,omitempty"`
	Confidence    float64        `yaml:"confidence,omitempty"`
	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. *
  • Kind classifies why the knowledge matters: "pitfall" (permanent gotcha),
  • "workaround" (useful now, may be superseded), "recommendation" (preferred
  • approach), "pattern" (recurring success), or "" (unclassified). *
  • Action is the imperative step a future agent should take. Empty when no
  • clear action applies. *
  • Confidence is a reliability score in [0.0, 1.0]. New memories default to
  • 0.5. Memories that fall to or below 0.2 are auto-archived. *
  • Example:
  • meta := MemoryMeta{
  • ID: "git_fix_a3f891",
  • Type: MemoryTypeToolUse,
  • Kind: "pitfall",
  • Description: "Fixed 'fatal: not a git repository' with git init",
  • Action: "Run `git init` in project root, then retry.",
  • Confidence: 0.5,
  • }

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. An embedding failure
  • writes nothing; an index failure removes the file it wrote (or restores
  • the one it replaced), so a failed save never leaves an orphan. *
  • 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) SetConfidence added in v0.0.12

func (s *MemoryStore) SetConfidence(id string, delta float64) (float64, error)

* SetConfidence adjusts the confidence of an active memory by delta and

  • clamps the result to [0.0, 1.0]. Both the database row and the on-disk
  • .fountain file are updated so that a database rebuild preserves the value.
  • If the resulting confidence is <= 0.2 the memory is automatically archived
  • and ErrAutoArchived is returned alongside the final confidence value. *
  • Parameters:
  • id (string) — ID of the memory to adjust.
  • delta (float64) — positive to increase, negative to decrease confidence. *
  • Returns:
  • float64 — the clamped confidence value after adjustment.
  • error — ErrAutoArchived when auto-archival triggered; other errors on
  • database or file failure; nil on success. *
  • Example:
  • newConf, err := store.SetConfidence("git_fix_a3f891", -0.1)
  • if errors.Is(err, ErrAutoArchived) {
  • fmt.Println("memory archived due to low confidence")
  • }

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 *‌/ }

func (*MemoryStore) WriteDigest added in v0.0.12

func (s *MemoryStore) WriteDigest(path string) error

* WriteDigest renders a Markdown summary of all active memories to path.

  • Memories are grouped by kind (pitfall → workaround → recommendation →
  • pattern → unclassified) and sorted by confidence descending within each
  • group. The file is not written when there are no active memories. *
  • Parameters:
  • path (string) — absolute path to write the digest file. *
  • Returns:
  • error — on database query or file write failure. *
  • Example:
  • _ = store.WriteDigest(filepath.Join(store.Dir(), "DIGEST.md"))

type MemorySystem added in v0.0.16

type MemorySystem struct {
	Store   *MemoryStore
	Unified *UnifiedMemory
}

* MemorySystem owns the complete lifecycle of Harvey's memory subsystems.

  • Open it once per session via OpenMemory; close it on session exit. *
  • Fields:
  • Store (*MemoryStore) — session-scoped memory store; nil if open failed.
  • Unified (*UnifiedMemory) — retrieval layer over Store; nil if Store is nil. *
  • Example:
  • ms, err := OpenMemory(ws, &cfg.Memory)
  • defer ms.Close()

func OpenMemory added in v0.0.16

func OpenMemory(ws *Workspace, cfg *MemoryConfig) (*MemorySystem, error)

* OpenMemory initializes all memory subsystems in dependency order.

  • Returns a non-nil *MemorySystem even on partial failure — Store and Unified
  • are nil when the store could not be opened, and callers must nil-check them. *
  • Parameters:
  • ws (*Workspace) — workspace whose agents/memories directory is used.
  • cfg (*MemoryConfig) — memory configuration (top-K, budget, RAG settings). *
  • Returns:
  • *MemorySystem — never nil.
  • error — non-nil if the store could not be opened. *
  • Example:
  • ms, err := OpenMemory(ws, &cfg.Memory)
  • if err != nil {
  • log.Printf("memory unavailable: %v", err)
  • }
  • defer ms.Close()

func (*MemorySystem) Close added in v0.0.16

func (ms *MemorySystem) Close() error

* Close shuts down all memory subsystems. Safe to call on a nil receiver or

  • when the store was never successfully opened. *
  • Returns:
  • error — first non-nil error encountered during shutdown. *
  • Example:
  • defer ms.Close()

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 ModelAlias added in v0.0.16

type ModelAlias struct {
	Model  string   // full model name / path passed to the backend
	Engine string   // "ollama", "llamafile", or "llamacpp"; "" means any (legacy aliases)
	Tags   []string // purpose labels, e.g. ["code", "instruct"]
}

* ModelAlias maps a short alias name to a full model identifier and optional

  • purpose tags. Tags allow @mention routing to resolve by capability rather
  • than exact name (e.g. @code → the alias tagged "code"). *
  • Fields:
  • Model (string) — full model name or path passed to the backend.
  • Tags ([]string) — purpose labels, e.g. ["code", "instruct"]. *
  • Example:
  • cfg.ModelAliases["granite"] = ModelAlias{Model: "granite3.3:8b", Tags: []string{"code", "instruct"}}

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
	ToolMode             string
	// MaxPromptTokens caps the whole prompt (system prompt, history and the new
	// message) in estimateTokens units (chars/4); 0 = unknown. It is separate
	// from ContextLength: hailo-ollama's llama3.2:3b fails at about 750 of these
	// though no context window is advertised. Set by the probe seed, by
	// /model limit, or learned from a failure; a re-probe never overwrites it.
	MaxPromptTokens int
	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.
  • ToolMode (string) — explicit execution strategy; one of ToolModeAuto/Structured/Prose/Inject/None.
  • 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 ModelSummary

type ModelSummary struct {
	Name      string
	Path      string
	Engine    string
	SizeBytes int64
	Modified  time.Time
	// NotPulled marks an entry from the Hailo catalog (what the card can run)
	// that has not been pulled to the server yet.
	NotPulled bool
}

* ModelSummary is a backend-neutral description of a locally available model.

  • OllamaBackend.ListModels returns Ollama models; LlamafileBackend and
  • LlamaCppBackend return filesystem-scanned entries. The Engine field
  • distinguishes the source. *
  • Fields:
  • Name (string) — display or alias name, e.g. "phi4-Q4_K_M".
  • Path (string) — absolute filesystem path; empty for Ollama models.
  • Engine (string) — "ollama", "llamafile", or "llamacpp".
  • SizeBytes (int64) — model weight size in bytes; 0 if unknown.
  • Modified (time.Time) — last modified time of the file; zero if unknown. *
  • Example:
  • models, _ := backend.ListModels()
  • for _, m := range models {
  • fmt.Printf("%s (%s)\n", m.Name, m.Engine)
  • }

func (ModelSummary) EngineLabel added in v0.0.19

func (m ModelSummary) EngineLabel() string

EngineLabel is the engine as shown to the user: "hailo", or "hailo, not pulled" for a catalog entry that has not been pulled.

type OberonChunker added in v0.0.10

type OberonChunker struct{}

* OberonChunker splits Oberon source into enriched chunks at PROCEDURE

  • boundaries. MODULE headers and IMPORT/CONST/TYPE/VAR sections are emitted
  • as "code" chunks; each PROCEDURE is its own chunk. *
  • Note: Oberon supports nested comment delimiters (* (* *) *); this chunker
  • treats them as non-nested (known approximation). *
  • Example:
  • o := NewOberonChunker()
  • chunks := o.Chunk("MODULE Foo;\nPROCEDURE Bar;\nBEGIN END Bar;\nEND Foo.", "Foo.Mod")

func NewOberonChunker added in v0.0.10

func NewOberonChunker() *OberonChunker
  • NewOberonChunker returns an OberonChunker. *
  • Returns:
  • *OberonChunker — ready-to-use chunker. *
  • Example:
  • o := NewOberonChunker()

func (*OberonChunker) Chunk added in v0.0.10

func (o *OberonChunker) Chunk(content string, _ string) []EnrichedChunk
  • Chunk splits Oberon source into PROCEDURE chunks and code sections. *
  • Parameters:
  • content (string) — Oberon source text.
  • filePath (string) — source path; used for context only. *
  • Returns:
  • []EnrichedChunk — chunks with location and symbol metadata. *
  • Example:
  • chunks := o.Chunk(src, "Foo.Mod")

func (*OberonChunker) Language added in v0.0.10

func (o *OberonChunker) Language() string
  • Language returns "oberon". *
  • Returns:
  • string — "oberon". *
  • Example:
  • o.Language() // "oberon"

type OberonDocExtractor added in v0.0.10

type OberonDocExtractor struct{}

* OberonDocExtractor extracts documentation from Oberon source code.

  • It recognises only (* *) block comments; Oberon has no line-comment syntax.
  • Note: nested (* (* *) *) comments are treated as non-nested (same
  • approximation as OberonChunker). *
  • Example:
  • e := NewOberonDocExtractor()
  • docs := e.ExtractDocs("(* Adds a to b. *)\nPROCEDURE Add*(a,b:INTEGER):INTEGER;\n")

func NewOberonDocExtractor added in v0.0.10

func NewOberonDocExtractor() *OberonDocExtractor
  • NewOberonDocExtractor returns an OberonDocExtractor. *
  • Returns:
  • *OberonDocExtractor — ready-to-use extractor. *
  • Example:
  • e := NewOberonDocExtractor()

func (*OberonDocExtractor) ExtractDocs added in v0.0.10

func (e *OberonDocExtractor) ExtractDocs(content string) []DocumentationBlock
  • ExtractDocs returns all DocumentationBlocks found in Oberon source. *
  • Parameters:
  • content (string) — Oberon source text. *
  • Returns:
  • []DocumentationBlock — blocks with line range and symbol association. *
  • Example:
  • docs := e.ExtractDocs("(* Greet the user. *)\nPROCEDURE Greet*;\n")

func (*OberonDocExtractor) ExtractSymbols added in v0.0.10

func (e *OberonDocExtractor) ExtractSymbols(content string) map[string]string
  • ExtractSymbols returns a map of symbol name → documentation text for Oberon. *
  • Parameters:
  • content (string) — Oberon source text. *
  • Returns:
  • map[string]string — symbol → doc text. *
  • Example:
  • syms := e.ExtractSymbols("(* Greet user. *)\nPROCEDURE Greet*;\n")
  • // syms["Greet"] == "Greet user."

func (*OberonDocExtractor) Language added in v0.0.10

func (e *OberonDocExtractor) Language() string
  • Language returns "oberon". *
  • Returns:
  • string — "oberon". *
  • Example:
  • e.Language() // "oberon"

type OllamaBackend added in v0.0.16

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

* OllamaBackend implements ManagedBackend for the Ollama inference server.

  • It wraps the existing ProbeOllama and newOllamaLLMClient helpers and adds
  • lifecycle tracking (start/stop, PID file, StartedByHarvey flag). *
  • Fields:
  • url (string) — Ollama base URL, e.g. "http://127.0.0.1:11434".
  • timeout (time.Duration) — HTTP timeout passed to the LLM client.
  • agentsDir (string) — directory for the PID file (typically workspace agents/).
  • activeModel (string) — model name chosen at session start; "" until set.
  • running (bool) — reflects the last Detect() probe result.
  • startedByHarvey (bool) — true when this instance launched ollama serve.
  • proc (*os.Process) — process Harvey started; nil if not started here. *
  • Example:
  • b := NewOllamaBackend("http://127.0.0.1:11434", 30*time.Second, "/workspace/agents")
  • if b.Detect() {
  • client, _ := b.NewClient()
  • }

func NewOllamaBackend added in v0.0.16

func NewOllamaBackend(url string, timeout time.Duration, agentsDir string) *OllamaBackend

* NewOllamaBackend returns a new OllamaBackend configured with the given URL,

  • HTTP timeout, and agents directory. No network calls are made. *
  • Parameters:
  • url (string) — Ollama server base URL.
  • timeout (time.Duration) — HTTP timeout for LLM client calls.
  • agentsDir (string) — directory for the PID file. *
  • Returns:
  • *OllamaBackend — ready to call Detect() or Start(). *
  • Example:
  • b := NewOllamaBackend(cfg.Ollama.URL, cfg.Ollama.Timeout, filepath.Join(ws.Root, "agents"))

func (*OllamaBackend) ActiveModel added in v0.0.16

func (b *OllamaBackend) ActiveModel() string
  • ActiveModel returns the name of the model currently in use, or "" when none is set. *
  • Returns:
  • string — model name, or "" before Start or SetActiveModel is called. *
  • Example:
  • fmt.Println(b.ActiveModel()) // "granite3.3:8b"

func (*OllamaBackend) BaseURL added in v0.0.16

func (b *OllamaBackend) BaseURL() string
  • BaseURL returns the HTTP base URL of the Ollama server. *
  • Returns:
  • string — the URL passed to NewOllamaBackend. *
  • Example:
  • fmt.Println(b.BaseURL()) // "http://127.0.0.1:11434"

func (*OllamaBackend) Detect added in v0.0.16

func (b *OllamaBackend) Detect() bool
  • Detect probes the Ollama server at BaseURL and updates IsRunning. *
  • Returns:
  • bool — true if the server is reachable. *
  • Example:
  • if b.Detect() { fmt.Println("Ollama is up") }

func (*OllamaBackend) IsRunning added in v0.0.16

func (b *OllamaBackend) IsRunning() bool

* IsRunning reports the result of the most recent Detect probe. It does not

  • make a network call; call Detect() first to refresh. *
  • Returns:
  • bool — true if the last Detect() probe succeeded. *
  • Example:
  • b.Detect()
  • if b.IsRunning() { ... }

func (*OllamaBackend) ListModels added in v0.0.16

func (b *OllamaBackend) ListModels() ([]ModelSummary, error)

* ListModels returns all models installed on the Ollama server as backend-neutral

  • ModelSummary values. Returns an error when the server is not reachable. *
  • Returns:
  • []ModelSummary — one entry per installed Ollama model.
  • error — non-nil if /api/tags cannot be reached. *
  • Example:
  • models, err := b.ListModels()
  • for _, m := range models { fmt.Println(m.Name, m.Engine) }

func (*OllamaBackend) Name added in v0.0.16

func (b *OllamaBackend) Name() string
  • Name returns the backend identifier "ollama". *
  • Returns:
  • string — always "ollama". *
  • Example:
  • fmt.Println(b.Name()) // "ollama"

func (*OllamaBackend) NewClient added in v0.0.16

func (b *OllamaBackend) NewClient() (LLMClient, error)

* NewClient returns a wired LLMClient pointing at the running Ollama server

  • using the active model. Returns an error when no active model has been set. *
  • Returns:
  • LLMClient — ready for chat and embed calls.
  • error — non-nil when ActiveModel() is "". *
  • Example:
  • client, err := b.NewClient()

func (*OllamaBackend) SetActiveModel added in v0.0.16

func (b *OllamaBackend) SetActiveModel(model string)

* SetActiveModel records the given model name as the active model without

  • making any network calls. Used by callers that wire the model name through
  • Config (e.g. pickOllamaModel) rather than through Start. *
  • Parameters:
  • model (string) — Ollama model name, e.g. "granite3.3:8b". *
  • Example:
  • b.SetActiveModel("granite3.3:8b")

func (*OllamaBackend) Start added in v0.0.16

func (b *OllamaBackend) Start(ctx context.Context, model string, out io.Writer) error

* Start launches "ollama serve" if it is not already running, waits up to 5 s

  • for it to become reachable, sets the active model, marks StartedByHarvey,
  • and writes a PID file to agentsDir. If the server is already running, Start
  • is a no-op (it does not set StartedByHarvey). The model argument is recorded
  • as the active model name; pass "" when the model is not yet known. *
  • Parameters:
  • ctx (context.Context) — controls the launch lifetime.
  • model (string) — model name to record as active; "" is allowed.
  • out (io.Writer) — status messages sink. *
  • Returns:
  • error — non-nil if ollama cannot be launched or does not respond. *
  • Example:
  • err := b.Start(ctx, "granite3.3:8b", os.Stdout)

func (*OllamaBackend) StartedByHarvey added in v0.0.16

func (b *OllamaBackend) StartedByHarvey() bool

* StartedByHarvey reports whether this Harvey session launched the Ollama server.

  • Returns false when Harvey adopted an already-running Ollama instance. *
  • Returns:
  • bool — true when Harvey ran "ollama serve" through this backend. *
  • Example:
  • if b.StartedByHarvey() { defer b.Stop() }

func (*OllamaBackend) Stop added in v0.0.16

func (b *OllamaBackend) Stop() error

* Stop sends SIGINT to the ollama process Harvey started. Safe to call when

  • Harvey did not start Ollama (no-op) or when the process is already gone.
  • Also deletes the PID file on success. *
  • Returns:
  • error — non-nil only on unexpected kill failures. *
  • Example:
  • defer b.Stop()

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 NewOllamaClientFor added in v0.0.19

func NewOllamaClientFor(engine, baseURL, model string) *OllamaClient

NewOllamaClientFor is NewOllamaClient for a server of the named engine; the engine's capability row decides which utility requests are made.

func (*OllamaClient) ModelSummaries

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

* ModelSummaries returns an OllamaModelSummary 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:
  • []OllamaModelSummary — 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) (OllamaModelDetail, 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:
  • OllamaModelDetail — 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 OllamaConfig added in v0.0.16

type OllamaConfig struct {
	URL           string
	Model         string
	ContextLength int
	Timeout       time.Duration
	// URLExplicit and ModelExplicit are set when --ollama or -m/--model gave
	// the value, so LoadHarveyYAML leaves it alone: the command line wins.
	URLExplicit   bool
	ModelExplicit bool
}
  • OllamaConfig holds all Ollama-specific connection and model settings. *
  • Fields:
  • URL (string) — Ollama base URL; default "http://localhost:11434".
  • Model (string) — currently selected Ollama model.
  • ContextLength (int) — context window size in tokens; 0 = unknown.
  • Timeout (time.Duration) — HTTP timeout for Ollama requests; 0 = no timeout. *
  • Example:
  • cfg.Ollama = OllamaConfig{URL: "http://localhost:11434", Model: "llama3.1:8b"}

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 OllamaModelDetail added in v0.0.16

type OllamaModelDetail struct {
	OllamaModelSummary
	ContextLength int
	RawParameters string
	Template      string
	Capabilities  []string // e.g. ["completion", "tools", "vision"]; nil on older Ollama
	Format        string   // details.format, e.g. "gguf"; "hef" on hailo-ollama
}

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

  • extending OllamaModelSummary with context-window size and Modelfile parameters. *
  • Fields:
  • OllamaModelSummary — 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 OllamaModelSummary added in v0.0.16

type OllamaModelSummary struct {
	Name          string
	Family        string
	ParameterSize string
	Quantization  string
	SizeBytes     int64
	Running       bool
}
  • OllamaModelSummary 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 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 PascalChunker added in v0.0.10

type PascalChunker struct{}

* PascalChunker splits Pascal source into enriched chunks at PROCEDURE and

  • FUNCTION boundaries, tracking nested BEGIN/END blocks. *
  • Example:
  • p := NewPascalChunker()
  • chunks := p.Chunk("PROCEDURE Foo;\nBEGIN\nWRITELN('hi');\nEND;", "foo.pas")

func NewPascalChunker added in v0.0.10

func NewPascalChunker() *PascalChunker
  • NewPascalChunker returns a PascalChunker. *
  • Returns:
  • *PascalChunker — ready-to-use chunker. *
  • Example:
  • p := NewPascalChunker()

func (*PascalChunker) Chunk added in v0.0.10

func (p *PascalChunker) Chunk(content string, _ string) []EnrichedChunk
  • Chunk splits Pascal source into PROCEDURE/FUNCTION chunks and code sections. *
  • Parameters:
  • content (string) — Pascal source text.
  • filePath (string) — source path; used for context only. *
  • Returns:
  • []EnrichedChunk — chunks with location and symbol metadata. *
  • Example:
  • chunks := p.Chunk(src, "prog.pas")

func (*PascalChunker) Language added in v0.0.10

func (p *PascalChunker) Language() string
  • Language returns "pascal". *
  • Returns:
  • string — "pascal". *
  • Example:
  • p.Language() // "pascal"

type PascalDocExtractor added in v0.0.10

type PascalDocExtractor struct{}

* PascalDocExtractor extracts documentation from Pascal source code.

  • It recognises line comments (//), brace block comments ({ }),
  • and parenthesis-star block comments ((* *)). {$...} compiler directives
  • are ignored. *
  • Example:
  • e := NewPascalDocExtractor()
  • docs := e.ExtractDocs("{ Adds a and b. }\nFUNCTION Add(a,b:Integer):Integer;\n")

func NewPascalDocExtractor added in v0.0.10

func NewPascalDocExtractor() *PascalDocExtractor
  • NewPascalDocExtractor returns a PascalDocExtractor. *
  • Returns:
  • *PascalDocExtractor — ready-to-use extractor. *
  • Example:
  • e := NewPascalDocExtractor()

func (*PascalDocExtractor) ExtractDocs added in v0.0.10

func (e *PascalDocExtractor) ExtractDocs(content string) []DocumentationBlock
  • ExtractDocs returns all DocumentationBlocks found in Pascal source. *
  • Parameters:
  • content (string) — Pascal source text. *
  • Returns:
  • []DocumentationBlock — blocks with type, line range, and symbol association. *
  • Example:
  • docs := e.ExtractDocs("{ Sort the list. }\nPROCEDURE Sort(var L:TList);\n")

func (*PascalDocExtractor) ExtractSymbols added in v0.0.10

func (e *PascalDocExtractor) ExtractSymbols(content string) map[string]string
  • ExtractSymbols returns a map of symbol name → documentation text for Pascal. *
  • Parameters:
  • content (string) — Pascal source text. *
  • Returns:
  • map[string]string — symbol → doc text. *
  • Example:
  • syms := e.ExtractSymbols("(* Sort items. *)\nPROCEDURE Sort;\n")
  • // syms["Sort"] == "Sort items."

func (*PascalDocExtractor) Language added in v0.0.10

func (e *PascalDocExtractor) Language() string
  • Language returns "pascal". *
  • Returns:
  • string — "pascal". *
  • Example:
  • e.Language() // "pascal"

type PipeExternalFormatter added in v0.0.10

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

* PipeExternalFormatter invokes an external tool that reads source code from

  • stdin and writes formatted code to stdout. This is the pipe-mode path and
  • does not require safe mode to be disabled; the caller is responsible for any
  • allowed-command checks before invoking Format. *
  • If the executable is not found on $PATH, Format returns (content, nil)
  • (identity) so that a missing tool degrades gracefully. *
  • Fields (set via newPipeExtFormatter):
  • langID — language this formatter targets, e.g. "go".
  • exe — executable name, e.g. "gofmt".
  • args — additional arguments appended before content is piped in.
  • timeout — per-invocation deadline; 0 = 30 s default. *
  • Example:
  • f := newPipeExtFormatter("go", "gofmt")
  • formatted, err := f.Format("package main\n", "main.go")

func (*PipeExternalFormatter) Check added in v0.0.10

func (f *PipeExternalFormatter) Check(content string, filePath string) (bool, []FormatIssue)

* Check reports whether content is already formatted. Returns true and no

  • issues when content matches its formatted form; false and a single FormatIssue
  • when it differs or the tool is unavailable. *
  • Parameters:
  • content (string) — source code to check.
  • filePath (string) — file path hint. *
  • Returns:
  • bool — true when content is already properly formatted.
  • []FormatIssue — empty on pass; single entry on fail. *
  • Example:
  • ok, issues := f.Check("package main\n", "main.go")

func (*PipeExternalFormatter) Format added in v0.0.10

func (f *PipeExternalFormatter) Format(content string, filePath string) (string, error)

* Format passes content through the external formatter and returns the result.

  • filePath is used for context (e.g. to pick a parser) but is not read or
  • written; content is passed via stdin. *
  • Parameters:
  • content (string) — source code to format.
  • filePath (string) — file path hint passed to the formatter if needed. *
  • Returns:
  • string — formatted content, or original content when the tool is absent.
  • error — non-nil only when the tool ran but returned an error. *
  • Example:
  • out, err := f.Format("package main\n", "main.go")

func (*PipeExternalFormatter) Language added in v0.0.10

func (f *PipeExternalFormatter) Language() string
  • Language returns the language ID this formatter targets. *
  • Returns:
  • string — language ID, e.g. "go". *
  • Example:
  • fmt.Println(f.Language()) // "go"

func (*PipeExternalFormatter) Mode added in v0.0.10

  • Mode returns PipeFormatter, indicating this formatter uses stdin/stdout. *
  • Returns:
  • FormatterMode — always PipeFormatter. *
  • Example:
  • fmt.Println(f.Mode() == PipeFormatter) // true

type Plan added in v0.0.12

type Plan struct {
	Goal    string
	Steps   []PlanStep
	Created time.Time
	Updated time.Time
}
  • Plan represents a multi-step task decomposed into ordered, checkable steps. *
  • Fields:
  • Goal (string) — short description of the overall objective.
  • Steps ([]PlanStep) — ordered list of steps.
  • Created (time.Time) — when the plan was first generated.
  • Updated (time.Time) — when the plan was last modified. *
  • Example:
  • p := &Plan{Goal: "Create a web component demo", Steps: []PlanStep{...}}

func LoadPlan added in v0.0.12

func LoadPlan(ws *Workspace) (*Plan, error)

* LoadPlan reads agents/plan.md from the workspace and returns the parsed Plan.

  • Returns an error when the file does not exist or cannot be parsed. *
  • Parameters:
  • ws (*Workspace) — workspace whose agents/ directory is read. *
  • Returns:
  • *Plan — parsed plan.
  • error — if file is missing or unreadable. *
  • Example:
  • p, err := LoadPlan(agent.Workspace)

func PlanFromLLMResponse added in v0.0.12

func PlanFromLLMResponse(text, goal string) (*Plan, error)

* PlanFromLLMResponse parses a Plan from raw LLM output. It looks for a

  • GFM checklist (lines beginning with "- [ ]" or "- [x]") and an optional
  • goal heading ("# Plan: ..." or "## Goal: ..."). Falls back to a numbered
  • list ("1. Step") when no checklist is found. goal is used as a fallback
  • when the response contains no heading. *
  • Parameters:
  • text (string) — raw model response.
  • goal (string) — fallback goal text when none is found in the response. *
  • Returns:
  • *Plan — parsed plan; may have zero steps if none could be extracted.
  • error — always nil; included for future validation. *
  • Example:
  • p, _ := PlanFromLLMResponse(response, "build the web component demo")

func (*Plan) AllDone added in v0.0.12

func (p *Plan) AllDone() bool
  • AllDone reports whether every step in the plan is marked complete. *
  • Returns:
  • bool — true when all steps are done. *
  • Example:
  • if p.AllDone() { fmt.Println("Task complete") }

func (*Plan) MarkDone added in v0.0.12

func (p *Plan) MarkDone(i int)
  • MarkDone marks step at index i as complete and updates the Updated timestamp. *
  • Parameters:
  • i (int) — zero-based step index to mark done. *
  • Example:
  • p.MarkDone(0)

func (*Plan) NextStep added in v0.0.12

func (p *Plan) NextStep() *PlanStep
  • NextStep returns the first uncompleted step, or nil if all are done. *
  • Returns:
  • *PlanStep — pointer to the first step where Done is false; nil when all done. *
  • Example:
  • if s := p.NextStep(); s != nil { fmt.Println("next:", s.Title) }

func (*Plan) Summary added in v0.0.12

func (p *Plan) Summary() string

* Summary returns a compact one-line description of plan state suitable for

  • injecting into a bounded LLM context. *
  • Returns:
  • string — e.g. "Plan: Create demo [2/5 done] — next: Write styles.css" *
  • Example:
  • fmt.Println(p.Summary())

type PlanStep added in v0.0.12

type PlanStep struct {
	Index int
	Done  bool
	Title string
	Model string // from [model: name] annotation; "" = use the default model
}
  • PlanStep represents a single actionable step within a Plan. *
  • Fields:
  • Index (int) — zero-based position in the plan.
  • Done (bool) — true when the step has been executed successfully.
  • Title (string) — one-line description of the action to perform.
  • Model (string) — optional model name from a [model: name] annotation; "" means use default. *
  • Example:
  • step := PlanStep{Index: 0, Done: false, Title: "Create demo/ directory"}

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 ProvenanceMeta added in v0.0.15

type ProvenanceMeta struct {
	URL     string
	DOI     string
	Title   string
	Version string
	Rights  string
}

* ProvenanceMeta carries scholarly-provenance metadata for a batch of chunks

  • ingested from a single source. All fields are optional; empty values are
  • stored as empty strings. *
  • Fields:
  • URL (string) — source URL.
  • DOI (string) — Digital Object Identifier, e.g. "10.1234/example".
  • Title (string) — human-readable title of the source document.
  • Version (string) — version or edition of the source.
  • Rights (string) — licence or rights statement. *
  • Example:
  • meta := ProvenanceMeta{DOI: "10.1234/sparql", Title: "SPARQL 1.1"}
  • err := store.Ingest("spec.md", chunks, embedder, meta)

type RAGAugmentInfo added in v0.0.15

type RAGAugmentInfo struct {
	StoreName string
	Chunks    int
	TopScore  float64
	// Sources holds deduplicated source refs ordered by retrieval rank.
	Sources []RAGChunkRef
}

RAGAugmentInfo holds metadata about a RAG retrieval that fired for a chat turn, for recording as a [[rag: ...]] Fountain note.

type RAGChunkRef added in v0.0.15

type RAGChunkRef struct {
	Source      string // file path or store key
	SourceURL   string
	SourceDOI   string
	SourceTitle string
}

RAGChunkRef carries provenance metadata for a single retrieved RAG chunk, used to emit per-source [[rag-source:]] Fountain notes.

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, meta ...ProvenanceMeta) 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) IngestEnriched added in v0.0.10

func (r *RagStore) IngestEnriched(source string, chunks []EnrichedChunk, embedder Embedder, meta ...ProvenanceMeta) error

* IngestEnriched embeds each EnrichedChunk using embedder and stores the

  • resulting vectors alongside source-location and semantic metadata. The
  • chunks table is lazily migrated with ALTER TABLE … ADD COLUMN on first use,
  • so existing RAG stores without the new columns continue to work.
  • Returns an error if the embedder's name does not match the store's model. *
  • Parameters:
  • source (string) — file path or identifier recorded with each chunk.
  • chunks ([]EnrichedChunk)— enriched chunks 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.IngestEnriched("main.c", chunks, 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"
	SkipPerPrompt  bool   // when true, ragAugment skips this store (per_prompt: false in YAML)
}
  • 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".
  • SkipPerPrompt (bool) — when true, ragAugment skips this store; the model uses
  • retrieve_memory instead. Set via per_prompt: false in YAML. *
  • 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) RecordChunkAnalysisStart added in v0.0.16

func (r *Recorder) RecordChunkAnalysisStart(filename string, totalChunks int, model string, docType DocType, cfg ChunkConfig) error

* RecordChunkAnalysisStart opens an INT. CHUNK ANALYSIS scene in the session

  • recording. Call this once before the first RecordChunkResult of an analysis
  • pass. The scene heading includes the filename so the session reader can locate
  • a specific document's analysis without scanning dialogue content. *
  • Parameters:
  • filename (string) — the document being analysed (basename or path).
  • totalChunks (int) — number of chunks the document was split into.
  • model (string) — model name that will process the chunks.
  • docType (DocType) — DocTypeProse or DocTypeSource (sets boundary label).
  • cfg (ChunkConfig) — chunking configuration (supplies chunk-size). *
  • Returns:
  • error — if the write fails. *
  • Example:
  • r.RecordChunkAnalysisStart("README.md", 5, "llama3.2:1b", DocTypeProse, cfg)

func (*Recorder) RecordChunkResult added in v0.0.16

func (r *Recorder) RecordChunkResult(n, total int, chunkModel, response, outcome string) error

* RecordChunkResult appends the result of a single chunk pass to the current

  • INT. CHUNK ANALYSIS scene. Call RecordChunkAnalysisStart before the first
  • call to this method. *
  • Parameters:
  • n (int) — 1-based chunk number.
  • total (int) — total chunks in this analysis pass.
  • chunkModel (string) — model name that processed this chunk.
  • response (string) — the model's response text for this chunk.
  • outcome (string) — "ok" or "error: <message>". *
  • Returns:
  • error — if the write fails. *
  • Example:
  • r.RecordChunkResult(1, 5, "llama3.2:1b", "Summary of chunk 1.", "ok")

func (*Recorder) RecordChunkSynthesis added in v0.0.16

func (r *Recorder) RecordChunkSynthesis(model, response, outcome string) error

* RecordChunkSynthesis appends the synthesis step to the current INT. CHUNK

  • ANALYSIS scene. Call this after the last RecordChunkResult of an analysis
  • pass to record Harvey's final combined answer. *
  • Parameters:
  • model (string) — model used for synthesis (may differ from chunk model).
  • response (string) — the synthesis model's response text.
  • outcome (string) — "ok" or "error: <message>". *
  • Returns:
  • error — if the write fails. *
  • Example:
  • r.RecordChunkSynthesis("llama3.2:1b", "Combined answer here.", "ok")

func (*Recorder) RecordContextRecall added in v0.0.15

func (r *Recorder) RecordContextRecall(results []UnifiedResult) error

* RecordContextRecall writes an INT. CONTEXT RECALL scene listing every

  • memory item injected by UnifiedMemory.Recall at session start. The scene
  • appears before the first chat turn and is a no-op when results is empty. *
  • Parameters:
  • results ([]UnifiedResult) — items returned by UnifiedMemory.Recall. *
  • Returns:
  • error — if the write fails. *
  • Example:
  • r.RecordContextRecall(results)

func (*Recorder) RecordExteriorTurn added in v0.0.15

func (r *Recorder) RecordExteriorTurn(endpoint, userInput, reply string) error

* RecordExteriorTurn appends a chat turn as a Fountain EXT. scene for remote

  • computation (route dispatch to a remote Ollama instance or cloud API).
  • HARVEY appears as the forwarding character; the remote endpoint replies. *
  • Scene structure: *
  • EXT. {ENDPOINT} AND {USER} {TIMESTAMP} *
  • Harvey routing to {ENDPOINT}. Workspace: {ws}. *
  • {USER}
  • (user's input) *
  • HARVEY
  • Forwarding to {ENDPOINT}. *
  • {ENDPOINT}
  • (remote reply) *
  • Parameters:
  • endpoint (string) — ALL-CAPS route or model name, e.g. "PI2" or "MISTRAL".
  • userInput (string) — the user's raw input text.
  • reply (string) — the remote endpoint's response text. *
  • Returns:
  • error — if the write fails. *
  • Example:
  • r.RecordExteriorTurn("PI2", "@pi2 analyze this", "Analysis complete.")

func (*Recorder) RecordModelSwitch added in v0.0.14

func (r *Recorder) RecordModelSwitch(newModel, backend string) error

* RecordModelSwitch appends a Fountain note recording that the active model

  • changed during the session. The note format is:
  • [[model switch: NAME (BACKEND) at TIMESTAMP]] *
  • Parameters:
  • newModel (string) — name of the model switched to.
  • backend (string) — backend identifier, e.g. "llamafile" or "ollama". *
  • Returns:
  • error — if the write fails. *
  • Example:
  • r.RecordModelSwitch("phi-mini", "llamafile")

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, ragInfo *RAGAugmentInfo) error

RecordTurnWithStats appends a full chat turn as a Fountain INT. scene (local computation).

Scene structure:

INT. HARVEY AND {USER} TALKING {TIMESTAMP}

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

[[rag: N chunks from STORE, top score S.SS]]   ← omitted when ragInfo is nil

{USER}
(user's input)

HARVEY
Forwarding to {MODEL}.

[[tool: name(args) — status]]   ← Fountain note 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.
ragInfo     (*RAGAugmentInfo)  — RAG retrieval metadata; nil when RAG did not fire.

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, 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 SecurityConfig added in v0.0.16

type SecurityConfig struct {
	SafeMode        bool
	AllowedCommands []string
	Permissions     map[string][]string
	RunTimeout      time.Duration
}
  • SecurityConfig holds safe-mode and command permission settings. *
  • Fields:
  • SafeMode (bool) — when true, only AllowedCommands can be executed via ! or /run.
  • AllowedCommands ([]string) — command names permitted when SafeMode is enabled.
  • Permissions (map[string][]string) — path prefix → allowed actions (read, write, exec, delete).
  • RunTimeout (time.Duration) — timeout for shell commands; 0 = no timeout. *
  • Example:
  • cfg.Security = SecurityConfig{SafeMode: true, AllowedCommands: []string{"ls", "cat"}}

type SelectItem added in v0.0.13

type SelectItem struct {
	Value  string
	Label  string
	Active bool
}
  • SelectItem is one choosable option in a numbered select list. *
  • Fields:
  • Value (string) — the string returned when this item is chosen; used
  • as the completion candidate in tab completion.
  • Label (string) — the display text shown in the list; may be longer
  • than Value (e.g. "store-name (3 documents)").
  • Active (bool) — when true the item is rendered with a "→" prefix
  • to indicate the currently selected/active item. *
  • Example:
  • items := []SelectItem{
  • {Value: "harvey", Label: "harvey", Active: true},
  • {Value: "docs", Label: "docs"},
  • }

type SensorClass added in v0.0.16

type SensorClass int

* SensorClass distinguishes deterministic, CPU-run findings from LLM-judged

  • ones, per the harness-engineering framework in
  • harness-engineering-exploration.md (Böckeler's computational/inferential
  • split). Every sensor Harvey currently emits — tool-call results, the
  • grounding check, the prose-tool-call-syntax warning — is Computational:
  • each is a deterministic check over already-known content, not another LLM
  • call. Inferential exists so a future sensor (e.g. an LLM-based review) has
  • a place to mark itself as probabilistic rather than as certain as the
  • checks above. *
  • Example:
  • ev := SensorEvent{Kind: "grounding", Message: "...", Class: Computational}
const (
	// Computational marks a deterministic, CPU-run finding (e.g. a string
	// match, a static check) — safe to treat as certain.
	Computational SensorClass = iota
	// Inferential marks an LLM-judged finding — probabilistic, not yet
	// produced by anything in Harvey today.
	Inferential
)

type SensorEvent added in v0.0.16

type SensorEvent struct {
	Kind    string
	Message string
	Class   SensorClass
}

* SensorEvent is a single sensor/status signal surfaced to the user during

  • or after a turn. Every sensor signal in Harvey constructs one of these —
  • tool-call outcomes (tool_executor.go), the grounding check (grounding.go),
  • and the prose-tool-call-syntax warning (terminal.go) — even though today's
  • rendering is unchanged from before this type existed. *
  • Fields:
  • Kind (string) — short identifier, e.g. "tool_call", "grounding", "prose_tool_syntax".
  • Message (string) — human-readable text to show the user.
  • Class (SensorClass) — Computational or Inferential. *
  • Example:
  • ev := SensorEvent{Kind: "tool_call", Message: "Calling read_file…", Class: Computational}

type ServerFamily added in v0.0.19

type ServerFamily struct {
	OllamaURL    string
	HailoURL     string
	Relabelled   bool
	HailoCatalog []string // what the Hailo server can run, pulled or not
}

* ServerFamily says which Ollama-shaped servers Harvey can use this session

  • and where. Ollama and hailo-ollama speak the same API, so a Hailo server
  • can be sitting at ollama.url (harvey.local's hand-edited setup); it is then
  • relabelled "hailo", and there is no Ollama server. *
  • Fields:
  • OllamaURL (string) — Ollama base URL; "" when ollama.url is really a Hailo server.
  • HailoURL (string) — hailo-ollama base URL; "" when no Hailo server answered.
  • Relabelled (bool) — the Hailo server was found at ollama.url.
  • HailoCatalog ([]string) — the models the Hailo server can run, pulled or not. *
  • Example:
  • f := a.ollamaFamily()
  • if f.HailoURL != "" { fmt.Println("Hailo at", f.HailoURL) }

type SessionConfig added in v0.0.16

type SessionConfig struct {
	AutoRecord       bool
	RecordPath       string
	ContinuePath     string
	ResumeLatest     bool
	ReplayPath       string
	ReplayOutputPath string
	ReplayContinue   bool
}
  • SessionConfig holds session recording and replay settings. *
  • Fields:
  • 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.
  • ResumeLatest (bool) — auto-select most recent session file.
  • ReplayPath (string) — session file to replay instead of entering the REPL.
  • ReplayOutputPath (string) — output path for replay recording; empty = auto-generated.
  • ReplayContinue (bool) — drop into the REPL after replay finishes. *
  • Example:
  • cfg.Session = SessionConfig{AutoRecord: true}

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 SkillCandidate added in v0.0.16

type SkillCandidate struct {
	Name            string          `json:"name"`
	Description     string          `json:"description"`
	LongDescription string          `json:"long_description"`
	Variables       []SkillVariable `json:"variables"`
	Steps           []string        `json:"steps"`
}

SkillCandidate holds a single skill proposal extracted from a session transcript by the LLM.

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 `json:"name"`
	Type        string `json:"type,omitempty"`
	Description string `json:"description"`
	Example     string `json:"example"`
}

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

  • SKILL.md frontmatter variables: block, or proposed by the skill suggestor. *
  • Fields:
  • Name (string) — variable name as declared (e.g. "EDIR").
  • Type (string) — variable type hint; typically "string" (used by suggestor).
  • 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 SkillsConfig added in v0.0.19

type SkillsConfig struct {
	Catalog string
}
  • SkillsConfig holds settings for skill discovery and prompting. *
  • Fields:
  • Catalog (string) — SkillsCatalogOff (default) or SkillsCatalogFull: whether
  • the catalog of available skills is put in the system prompt. *
  • Example:
  • cfg.Skills = SkillsConfig{Catalog: SkillsCatalogFull}

type Spinner

type Spinner struct {
	StatusCh chan string // receives transient status update strings
	// 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.

Call UpdateStatus to show a transient message on line 2 in place of the Lear quote. The message reverts to a Lear quote at the next message tick (~6 s).

func (*Spinner) ReportSensor added in v0.0.16

func (s *Spinner) ReportSensor(ev SensorEvent)

* ReportSensor renders a SensorEvent on the spinner's status line, using

  • its Message exactly as UpdateStatus would. Class/Kind are not yet
  • reflected in the rendering — pure routing plumbing per
  • harness-prerequisite-refactor-plan.md Phase C. See
  • harness-engineering-exploration.md Direction C for the planned sensor-
  • sidecar UI this is a prerequisite for, not the redesign itself. *
  • Parameters:
  • ev (SensorEvent) — the sensor signal to display. *
  • Example:
  • spin.ReportSensor(SensorEvent{Kind: "tool_call", Message: "Calling read_file…", Class: Computational})

func (*Spinner) UpdateStatus added in v0.0.13

func (s *Spinner) UpdateStatus(msg string)

* UpdateStatus sends a transient status message to the spinner's message line.

  • Non-blocking: if a previous status has not been consumed, the new one
  • replaces it. Calling UpdateStatus on a stopped spinner is safe. *
  • Parameters:
  • msg (string) — status string, e.g. "Calling read_file…" *
  • Example:
  • spin.UpdateStatus("Searching knowledge base…")

type StatusReporter added in v0.0.13

type StatusReporter interface {
	UpdateStatus(msg string)
	ReportSensor(ev SensorEvent)
}

* StatusReporter is an optional sink for transient status messages during

  • tool execution. The Spinner satisfies this interface; pass nil to suppress
  • status updates. ReportSensor is the SensorEvent-shaped entry point
  • (harness-prerequisite-refactor-plan.md Phase C); UpdateStatus remains for
  • callers that only have a bare string. *
  • Example:
  • ex.Status = spin // spin is a *Spinner

type Suggestor added in v0.0.16

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

* Suggestor drives the /skill suggest pipeline: it reads a session transcript,

  • asks the LLM to propose skill candidates, and interactively writes accepted
  • candidates as SKILL.md files to the workspace. *
  • Parameters:
  • ws (*Workspace) — workspace used for file I/O and sessions directory. *
  • Returns:
  • *Suggestor — ready to call Suggest. *
  • Example:
  • sg := NewSuggestor(a.Workspace)
  • err := sg.Suggest(ctx, "", a, os.Stdout, os.Stdin)

func NewSuggestor added in v0.0.16

func NewSuggestor(ws *Workspace) *Suggestor
  • NewSuggestor creates a Suggestor anchored to the given workspace. *
  • Parameters:
  • ws (*Workspace) — workspace providing the sessions dir and skill output path. *
  • Returns:
  • *Suggestor *
  • Example:
  • sg := NewSuggestor(a.Workspace)

func (*Suggestor) Suggest added in v0.0.16

func (s *Suggestor) Suggest(ctx context.Context, sessionPath string, agent *Agent, out io.Writer, in io.Reader) error

* Suggest reads sessionPath (or the most recent session when empty), asks the

  • LLM to propose skill candidates, and writes accepted candidates as SKILL.md
  • files under agents/skills/<name>/. *
  • Parameters:
  • ctx (context.Context) — context for the LLM call.
  • sessionPath (string) — path to a .spmd file; "" = most recent session.
  • agent (*Agent) — running agent (provides Client and Workspace).
  • out (io.Writer) — progress and prompt output.
  • in (io.Reader) — user input for the interactive review. *
  • Returns:
  • error — non-nil on I/O or LLM failure. *
  • Example:
  • err := sg.Suggest(ctx, "agents/sessions/foo.spmd", a, os.Stdout, os.Stdin)

type SyntaxHighlighter added in v0.0.10

type SyntaxHighlighter interface {
	// Highlight returns ANSI-coloured content for terminal display.
	Highlight(content string, lang string) string

	// GetStyle returns the colour configuration for a language.
	GetStyle(lang string) *HighlightStyle
}

* SyntaxHighlighter adds ANSI colour codes to source code for terminal display.

  • Implementations must strip existing ANSI sequences from the input before
  • adding their own, to avoid corrupting the terminal. *
  • Example:
  • coloured := h.Highlight(src, "go")

type TemplateEntry added in v0.0.8

type TemplateEntry struct {
	Name        string
	File        string
	Source      string
	Recommended string
}
  • TemplateEntry describes one profile template available to the user. *
  • Parameters: (none — struct fields)
  • Name (string) — human-readable display name, e.g. "Back End Developer".
  • File (string) — filename without directory, e.g. "backend-developer.fountain".
  • Source (string) — "builtin" for embedded templates, "workspace" for
  • templates found in agents/templates/profiles/.
  • Recommended (string) — content of the NOTE: field, or "" if absent.
  • Displayed during template selection as a non-enforced suggestion. *
  • Example:
  • entries := ListTemplates("/home/user/myproject")
  • for _, e := range entries {
  • fmt.Printf("[%s] %s\n", e.Source, e.Name)
  • }

func ListTemplates added in v0.0.8

func ListTemplates(wsRoot string) []TemplateEntry

* ListTemplates returns all available profile templates, merging built-in

  • (embedded) templates with any .fountain files found in
  • agents/templates/profiles/ within the workspace. Workspace-local entries
  • appear after built-ins; a workspace entry with the same filename as a
  • built-in shadows the built-in. *
  • Parameters:
  • wsRoot (string) — absolute path to the workspace root. Pass "" to skip
  • workspace-local template discovery. *
  • Returns:
  • []TemplateEntry — ordered list: built-ins first (in directory order),
  • then workspace-local additions. *
  • Example:
  • entries := ListTemplates(agent.Workspace.Root)
  • for i, e := range entries {
  • fmt.Printf(" [%d] %s\n", i+1, e.Name)
  • }

type TerminalHighlighter added in v0.0.10

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

* TerminalHighlighter applies ANSI syntax highlighting to source code for

  • terminal display. A single instance handles all registered languages by
  • dispatching to per-language tokenisers based on the lang parameter. *
  • Implementations must strip existing ANSI sequences from the input before
  • adding their own — this is satisfied here because code blocks extracted from
  • LLM responses are not expected to contain prior ANSI codes. *
  • Example:
  • h := NewTerminalHighlighter()
  • coloured := h.Highlight("int main(){return 0;}", "c")

func NewTerminalHighlighter added in v0.0.10

func NewTerminalHighlighter() *TerminalHighlighter

* NewTerminalHighlighter returns a TerminalHighlighter pre-loaded with

  • highlighters for all supported languages. *
  • Returns:
  • *TerminalHighlighter — ready-to-use multi-language highlighter. *
  • Example:
  • h := NewTerminalHighlighter()

func (*TerminalHighlighter) GetStyle added in v0.0.10

func (h *TerminalHighlighter) GetStyle(lang string) *HighlightStyle

* GetStyle returns the HighlightStyle for the given language, or nil when the

  • language is not registered. *
  • Parameters:
  • lang (string) — language ID. *
  • Returns:
  • *HighlightStyle — colour configuration, or nil. *
  • Example:
  • style := h.GetStyle("go")

func (*TerminalHighlighter) Highlight added in v0.0.10

func (h *TerminalHighlighter) Highlight(content string, lang string) string

* Highlight returns content with ANSI colour codes for the given language.

  • Returns content unchanged when lang is not recognised. *
  • Parameters:
  • content (string) — source text to highlight.
  • lang (string) — language ID (e.g. "go", "c", "python"). *
  • Returns:
  • string — highlighted text, or content unchanged when lang is unknown. *
  • Example:
  • coloured := h.Highlight("void foo(){}", "c")

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
	Result    string // "ok" or "error: <first line>" — empty defaults to "ok"
	Character string // ALL-CAPS model name when attributed; empty = HARVEY (default)
}

ToolCallRecord holds the name, raw JSON arguments, result status, and optional character attribution 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
	ToolResultCompaction bool           // when true, compact prior tool rounds before each new LLM turn
	Status               StatusReporter // optional: receives transient status during tool calls
	CharacterName        string         // ALL-CAPS model name for session attribution; "" = HARVEY (default)
}

* 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) LoadHarveyMD added in v0.0.16

func (ws *Workspace) LoadHarveyMD() string

* LoadHarveyMD reads HARVEY.md from the workspace root 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:
  • cfg.SystemPrompt = ws.LoadHarveyMD()

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)

Source Files

Directories

Path Synopsis
cmd
assay command
assay runs evaluation prompts from a corpus YAML against one or more LLM backends and writes a Markdown report plus JSON results for human review and machine processing.
assay runs evaluation prompts from a corpus YAML against one or more LLM backends and writes a Markdown report plus JSON results for human review and machine processing.
harvey command

Jump to

Keyboard shortcuts

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