Commit Graph

171 Commits

Author SHA1 Message Date
Levi Neely dee0fda330 agent: emit hook timeout/start-failure warnings as info events
- Add Warning field to HookResult
- runHookCmd sets Warning on timeout and start failure
- Hooks.Run collects warnings across commands
- All hook call sites emit warnings via infoEvent
- Test verifies timeout warning is surfaced
2026-04-21 21:20:55 +02:00
Levi Neely 53442e193b store: cover renameSession OnRename + SetSessionID error (89.2%) 2026-04-21 20:33:21 +02:00
Levi Neely bd6d9a09a8 store: add NewCore factory injection, integration tests (88.9% coverage)
- Add NewCore to SessionStoreConfig and BatchStoreConfig
- When set, bypasses backend.New + agent.NewAgentCore for testability
- Integration tests: createSession, handleNewBatch, runJob, executeJob
- Tests cover named/auto-ID sessions, parallel jobs, duplicates, cancellation, factory errors
- 98 tests total (was 88)
2026-04-21 20:28:20 +02:00
Levi Neely d64a8d8854 store: improve test coverage 58.6% -> 78.2% (51 -> 88 tests)
- SessionFileStore: content, readFile, writeFile, handleCtl, blockingRead, makePublish
- SessionStore: OpenStore, createSession error paths, Interrupt
- BatchJobStore: AppendLog, RunnableID, Interrupt, Cancel, write rejection
- SkillStore: open write path, entry Stat on non-existent
- Enhanced stubCore with recording and controllable WaitChange
2026-04-21 20:18:53 +02:00
Levi Neely 130bf60708 store: replace Get/Put with Store+StoreEntry model
- Store: Stat, List, Open, Create, Delete, Rename
- StoreEntry: Stat, Read, Write, BlockingRead
- RunnableStore: Store + Runnable
- Open(name) returns StoreEntry (file handle)
- OpenStore(id) on SessionStore/BatchStore returns RunnableStore
- Remove ReadableStore, WritableStore, ReadWriteStore, BlobStore, BlockingReadStore
- Export EntryConfig for external store implementations
- Wait/LogInfo no longer require type assertions
2026-04-21 20:07:27 +02:00
Levi Neely 9b0bf8aca8 store: add Open to Store, move Rename to BlobStore
- Store = BlobStore + Open(name) (Store, error)
- BlobStore = ReadWriteStore + Delete, Create, Rename
- NewFlatDir/NewSkillStore return BlobStore (flat, no subdirectories)
- SessionStore/BatchStore satisfy Store via Open for child stores
- SessionFileStore/BatchJobStore embed *storeConfig, satisfy Store
- Replace SessionStore.SessionFileStore/BatchStore.JobStore with Open
- Add StoreEntry type alias for os.DirEntry
2026-04-21 18:59:31 +02:00
Levi Neely ac0970c5b2 store: add SessionStore.SessionFileStore to match BatchStore.JobStore pattern
- SessionStore now owns construction of its child SessionFileStore
- Add SaveTranscript to SessionStoreConfig
- Server delegates to SessionStore instead of assembling the child
2026-04-21 18:28:54 +02:00
Levi Neely 24e4209a95 store: refactor to storeConfig architecture
- Replace FlatDir type with storeConfig (unexported) + NewFlatDir returning Store
- Refactor SkillStore to skillState + storeConfig, NewSkillStore returns Store
- SessionStore/BatchStore embed *storeConfig for Store interface methods
- Add Runnable interface (RunnableID, Cancel, Interrupt, AppendLog, LogInfo)
- Session and batchJob satisfy Runnable
- Add Terminator-style Shutdown/InterruptAll on SessionStore and BatchStore
- NewSession constructor replaces exported field access
- Rename AppendChat->AppendLog, ChatInfo->LogInfo on Session
2026-04-21 18:23:18 +02:00
Levi Neely 500f7fe96b store: move Session, SessionStore, SessionFileStore to core
Session holds chat buffer + agent.Core + context.
SessionStore takes SessionStoreConfig with OnRename callback for
protocol-level fixups. SessionFileStore unchanged (already used callbacks).
Also adds FormatParams, ParseParams, SessionStoreFileMode, ChatInfo.
2026-04-21 16:37:34 +02:00
Levi Neely 72e4019493 store: move BatchStore, LoadAgentConfig, FormatEvent to core
BatchStore takes BatchStoreConfig instead of *Server, breaking the
9p coupling. LoadAgentConfig and FormatEvent are now exported from
pkg/store.
2026-04-21 16:29:31 +02:00
Levi Neely 0511f7c8b5 store: move SkillStore to core 2026-04-21 16:22:05 +02:00
Levi Neely 3c3e9cf917 store: add SyntheticFileInfo, SyntheticEntry, FileEntry, DirEntry 2026-04-21 16:14:34 +02:00
Levi Neely fb96721f2e store: new pkg/store with interfaces and FlatDir
Move ReadableStore, WritableStore, ReadWriteStore, BlobStore, Store
interfaces and FlatDir (née FlatDirStore) implementation from 9p into
core so the agent runtime and other consumers can use them directly.
2026-04-21 16:10:13 +02:00
Levi Neely 4710e3239f agent: simplify AgentConfigPath to plain concatenation, remove dead config.json fallback 2026-04-21 16:06:07 +02:00
Levi Neely 31a6937d46 agent: test expandSystemPrompt git detection 2026-04-21 16:01:16 +02:00
Levi Neely a4d4744eae agent: inline loadSystemPrompt into BuildAgentEnv 2026-04-21 15:58:17 +02:00
Levi Neely 0b705a1ee7 agent: extract expandSystemPrompt, 100% coverage for BuildAgentEnv
- Extract expandSystemPrompt(content, cwd) from loadSystemPrompt for
  testability without file I/O
- Add tests: ListTools error, tools populated, TrustedTools injection,
  agent prompt without system prompt, exec dispatch success/error/isError
- Add mockDispatcher and mockTrustedSetter test helpers
2026-04-21 15:56:35 +02:00
Levi Neely d957bda8a0 backend: remove unreachable NewRequestWithContext guards (URL validated in ctor) 2026-04-21 15:47:34 +02:00
Levi Neely 5cfa5a0df9 backend: 100% coverage for buildAnthropicMessages and streamAnthropicSSE
- Test all buildAnthropicMessages branches: system concat, assistant
  tool-calls-only, nil arguments default, tool batching, unknown role,
  full multi-turn conversation
- Test streamAnthropicSSE done re-entry: events after message_stop and
  error are ignored
- Remove unreachable done guard in process closure
2026-04-21 15:45:46 +02:00
Levi Neely 38dd34ea20 backend: cover Ollama Models/ContextLength HTTP paths, constructor URL validation 2026-04-21 15:42:27 +02:00
Levi Neely 13b17cd777 backend: extract parseOllamaContextLength, 100% coverage 2026-04-21 15:39:52 +02:00
Levi Neely 6a60f5014b backend: extract newFromEnv, 100% coverage for new.go 2026-04-21 15:36:26 +02:00
Levi Neely 9d8398bab0 backend: test coverage for new.go (loadEnvFile, openAIName, Backends) 2026-04-21 15:34:01 +02:00
Levi Neely 21827c57eb backend: extract stream parsers, shared HTTP, url.URL, comprehensive tests
- Extract streamOpenAISSE, streamOllamaNDJSON from ChatStream goroutines
  into standalone functions taking io.Reader for direct testability
- Remove ctx parameter from streamAnthropicSSE (caller handles cancellation)
- Extract streamRequest into backend.go: shared HTTP execution, 429/error
  handling, and goroutine lifecycle for all three backends
- Extract encodeOpenAIMessages, encodeOpenAITools from ChatStream
- Replace string baseURL with *url.URL; validate in constructors
- Constructors (NewOpenAI, NewOllama, NewAnthropic, NewCopilot) now return error
- Remove unreachable json.Marshal and http.NewRequestWithContext error branches

ChatStream coverage: 100% (OpenAI, Ollama, Anthropic)
Stream parsers: 100% (OpenAI, Ollama), 96.6% (Anthropic)
streamRequest: 100%

Test files:
- openai_encode_test.go: message/tool encoding, JSON round-trip
- openai_stream_test.go: SSE parsing via io.Reader
- ollama_stream_test.go: NDJSON parsing via io.Reader
- anthropic_stream_test.go: SSE parsing, mapAnthropicStopReason
- openai_test.go: HTTP integration, error paths, models, context length
- backend_test.go: contract checks (all interface methods), stream text/usage/
  tool calls/tool conversation, HTTP errors, rate limits for all backends
2026-04-21 15:32:03 +02:00
Levi Neely 549e1ccb45 pkg/log: remove globals, inject Sink as dependency
- Sink owns async writers and Flush; created once at startup
- Logger created via Sink.Logger/NewLogger/NewWriter
- agentCore.log field replaces package-level clog
- hooks.Run/runHookCmd accept *Logger parameter
- No globals, no init(). 100% test coverage.
2026-04-21 14:48:41 +02:00
Levi Neely 6b4d401d03 pkg/env: add tests (0% -> 100% coverage) 2026-04-21 13:53:38 +02:00
Levi Neely aa8301a900 pkg/config, pkg/skills: accept io.Reader, remove filesystem access
- config.Load takes io.Reader, uses json.NewDecoder (100% coverage)
- skills package reduced to pure ParseFrontMatter(io.Reader) parser
- Filesystem operations moved to callers (9p/skillstore, agent/core)
- All tests use strings.NewReader — no temp files
2026-04-21 13:51:46 +02:00
Levi Neely 0b64808ef5 pkg/tools: add contract tests, remove Close from Server/Dispatcher
- Add contract tests for tools.Server and tools.Dispatcher interfaces
  (tools_test.go), covering all exported behavior including error paths.
  pkg/tools coverage: 0% -> 100%.
- Add contract test for execute.Server (ListTools, CallTool), Decl
  factory test, and executeElevated early-exit test. execute coverage:
  68% -> 71%.
- Remove Close() from Server and Dispatcher interfaces and all
  implementations/callers. These existed for MCP server cleanup which
  has been removed.
2026-04-21 13:38:02 +02:00
Levi Neely 85b0d7f6fa remove MCP support, add execute_code tests
- Remove pkg/mcp/ (client, transport, JSON-RPC handshake)
- Remove mcpServer adapter and NewServer() from tools.go
- Remove MCPServers/ServerConfig from config
- Remove MCP server connection loop from BuildAgentEnv
- Remove ListServers() from Core interface and agentCore
- Remove /mcp command and help line
- Rename extractMCPResult -> extractToolResult
- Rename mcpToolsToBackend -> toolInfosToBackend
- Add execute_test.go: 28 tests covering detectLanguage, injectArgs,
  ansiCEscape, ValidateCode, allowed, ReadTool, Execute, Dispatch
  (pipeline, parallel, tool steps), limitedWriter, rate limiting,
  SetEnv, SetCWD (68.2% coverage from 0%)
- Add testdata/sandbox/default.yaml for real sandboxed test execution
2026-04-21 13:25:32 +02:00
Levi Neely 46272f22a6 test: sandbox coverage + backend contract tests
- sandbox: remove dead code (DefaultConfig, Load/Save, LayeredConfig, Merge,
  Version, SystemDefaults, validateName, ConfigPath, OpenSandbox); unexport
  internal symbols; LoadSandbox now takes io.Reader; loadSandboxConfig owns
  file opening; 83% package coverage via new sandbox_test.go
- backend: add BaseURL field to AnthropicBackend for testability; new
  backend_test.go runs checkContract against all five implementations
  (Ollama, OpenAI, Copilot, Anthropic, CodeWhisperer) via httptest servers

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 13:00:06 +02:00
Levi Neely c6f6e7feeb agent: testability, dead code removal, coverage to 83%
- Hook timeout configurable via hookTimeout var (unlocks <-timeout branch)
- newBackend injection into agentCore (unlocks /backend switch in tests)
- Remove dead code: WatchSignals, Prompt(), Goal(), isComplete/markComplete,
  contextStatsString, extractMCPText, DefaultAgentsDir, DefaultSessionsDir,
  Dispatcher() on AgentEnv
- Signal handling moved to process entry points; core has no OS signal knowledge
- Tests: extractMCPResult, mcpToolsToBackend, RestoreSession, SetEnv,
  BuildAgentEnv, firstSentence, hook timeout, backend injection

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 12:28:29 +02:00
Levi Neely 8d4e265b60 tests: fill critical-path coverage gaps
- loop.go: rate-limit retry (retryCountdown 100%), pre-tool cancellation,
  ChatStream+ctx-cancel (recordInterruption "request"), exec-cancel with
  pending inject
- executeTurn: startup messages, backend error event, auto-compact with
  preCompact/postCompact hook context injection
- session: compact backend error, empty summary, tool-message flattening
- handleCommand: /compact while running/nil-session/preHook-blocks,
  /clear while running, /agents with files
- hooks: non-zero exit code (non-blocking), context cancellation
- accessors: AgentName, BackendName, ModelName, SystemPrompt,
  GenerationParams (get+set), ListModels, CtxSz, Usage
- SetSessionID rename and same-ID no-op
- autoCompactLimit with zero ctxLen, agentSpawn with context output,
  hooksRan plural branch

55.2% → 73.7% total; executeTurn 87.7%→98.6%, run 62.7%→93.1%,
retryCountdown 0%→100%, compact 84.2%→94.7%

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 11:05:30 +02:00
Levi Neely faaf968f64 tests: spec command behaviors guaranteed by 9P ctl/file interface
Adds tests for every slash command exposed through the session's ctl
file and direct r/w files (backend, model, agent, cwd). Each test pins
the exact behavioral guarantee 9P depends on: show-current, set-value,
error-while-running, empty-dir, current-item-marked, no-session guard.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 10:52:56 +02:00
Levi Neely 8b8b675ff6 agent: /clear keeps session ID to avoid 9P desync
Generating a new ID on /clear silently orphaned the 9P session directory.
Now /clear only nils the in-memory session; the ID (and its directory)
remain valid. The next turn overwrites the session file in place.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 10:45:40 +02:00
Levi Neely 4b1229353f agent: add compacting state; assert in compact tests
setState("compacting") wraps session.compact() at both sites — manual
/compact (idle → compacting → idle) and auto-compact (thinking →
compacting → thinking). Tests capture state during the backend call to
verify the transition.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 10:42:48 +02:00
Levi Neely d7e44e26ef agent: Submit-while-running always queues to FIFO; add /i inject command
Concurrent Submit now unconditionally pushes to the FIFO rather than
trying pendingInject first. Use /i <prompt> to inject into the running
turn's tool-call loop, and /irw <prompt> to overwrite a pending inject.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 10:38:26 +02:00
Levi Neely 40b003219b agent: add core primitive tests (3.6% → 43.3% coverage)
Tests cover the full agent turn lifecycle: happy path, state transitions
(idle→thinking→calling→idle), preTurn hook blocking and context injection,
postTurn hook continuation, FIFO drain, pendingInject as next turn,
interrupt mid-turn, manual and auto compaction, agentSpawn idempotency,
loadSystemPrompt panic on missing file, panic recovery in Submit, and
command dispatch (/help, /clear). Each test is a spec for a primitive the
9P layer and frontends depend on.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 10:27:52 +02:00
Levi Neely cfdaf18150 agent: replace handleCommand switch with dispatch map
Each slash command is now a closure in a map[string]cmdFn. Adding or
removing a command is a single map entry with no fall-through risk.
The ! shell handler is unchanged. handler(infoEvent("")) now fires only
for recognized commands, not unknown /foo inputs.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 10:19:09 +02:00
Levi Neely c3d749d2d3 agent: sweep stale tmpdirs at startup
Crash-left /tmp/ollie/{id}/ directories are now cleared once at process
start via sync.Once before the first session tmpdir is created.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 10:15:02 +02:00
Levi Neely d6fa9458e5 agent: hard-fail on loadSystemPrompt error and auto-compact error
Both failures now panic with a descriptive message. Submit recovers,
logs the panic and stack trace via clog, cancels any in-progress action,
resets state to idle, and emits an error event to the handler.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 10:12:58 +02:00
Levi Neely 5ffda77972 agent: convert Submit recursion to explicit loop
Post-turn hook continue, unconsumed pendingInject, and FIFO drain all
previously re-entered Submit recursively, growing the stack with each
continuation. Replace with an explicit loop in Submit and extract the
single-turn logic into executeTurn, which returns the next prompt or "".

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 10:07:14 +02:00
Levi Neely 5569b3917b agent: load SYSTEM_PROMPT.md as base system prompt, append agentPrompt
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-21 09:14:07 +02:00
Levi Neely 93e5fe9f43 agent: remove Role:"newline" event
setState("idle") was called before handler(Event{Role:"newline"}),
meaning the final appendChat("\n") raced against statewait watchers
and clients that poll state. Remove the event entirely; clients no
longer see it.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-19 21:01:04 +02:00
Levi Neely 5a3f76d035 agent: fix AfterFunc broadcast missing lock; add WaitChange tests
context.AfterFunc callback was broadcasting without holding changeMu,
risking a missed wakeup if ctx cancels between the consumer's check
and cond.Wait(). Add unit tests covering the full state-change cycle
and the missed-wakeup race under -race.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-19 16:55:57 +02:00
Levi Neely f03ccadd43 agent: fix missed-wakeup race in WaitChange
notifyChange must hold changeMu when broadcasting. Without the lock,
the broadcast can fire between the consumer's value check and its
cond.Wait call — the signal is lost and the consumer sleeps until the
next change, causing an apparent off-by-one lag.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-19 16:25:43 +02:00
Levi Neely fdc77618ab agent: add WaitChange for blocking reads on state/usage/ctxsz/cwd
Adds a sync.Cond-based change notification mechanism. setState,
SetCWD, and usage updates all broadcast. WaitChange blocks until the
named field changes from the given current value, with context
cancellation support via context.AfterFunc.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-19 16:09:03 +02:00
Levi Neely 524dccdc81 agent: rename userPromptSubmit→preTurn, stop→postTurn
Names now reflect the turn lifecycle rather than implementation details.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-19 15:47:42 +02:00
Levi Neely 800dfa526e agent: remove Go-based systemPrompt composition; priming now via hooks
systemPrompt() loaded and templated files from DefaultPromptsDir() at
startup and on cwd change. This is now handled entirely by the
agentSpawn hook using the prime script, eliminating the parallel
prompt-injection path.

DefaultPromptsDir() is kept for the 9P server's p/ directory exposure.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-19 12:10:07 +02:00
Levi Neely be42fbd739 hooks: support array of commands per hook event
Hook values can now be a string or array of strings in agent JSON config.
Commands run in order; exit 2 from any command blocks immediately.
Context from all successful commands is concatenated.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-19 11:53:57 +02:00
Levi Neely aeeb0a3e22 execute: prepend \$OLLIE/x/ to PATH for tool subprocesses
Allows wrapper scripts in ~/.config/ollie/scripts/x/ to shadow system
binaries transparently without modifying the user's shell environment.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-19 11:07:23 +02:00