Commit Graph

388 Commits

Author SHA1 Message Date
Ollie Agent 6131fad5c5 Cancel timed out 9P reads 2026-08-17 17:41:55 +02:00
Ollie Agent c652c562c3 Fix 9P response writer shutdown 2026-08-17 17:39:56 +02:00
Levi Neely 9147fd790a session: expand ~ and env vars in SetCwd 2026-08-17 14:29:02 +02:00
Levi Neely 8a1efe0907 session: require cwd, make agent cwd read-only, sanitize message history
Session creation now requires cwd= parameter (no fallback to daemon cwd).
Agent cwd is read-only — agents inherit from session, cannot override.

Frontends updated:
- NewSessionDialog: added Directory field with Browse button
- NewAgentDialog: removed Directory field
- createAgent(): removed cwd parameter
- Kate plugin: passes cwd when creating kate session
- Dolphin: removed cwd from agent/new call

Message history sanitization (backend.SanitizeMessages):
- Removes dangling tool calls (assistant with ToolCalls but missing results)
- Removes orphan tool results (tool message without preceding call)
- Applied before sub-agent context inheritance
- Applied before session persistence save
- Applied after compaction (defensive)

Includes unit tests for all sanitization cases.
2026-08-17 14:15:55 +02:00
Levi Neely 025c351dcb Fix ollie-9p UNAME fallback, goal file permissions
- ollie-9p: Fall back to USER when OLLIE_UNAME not set (remove fatal error)
- goal/goalstatus: Use mode 0666 (world readable/writable) while keeping GID agent
2026-08-17 13:46:44 +02:00
Levi Neely a17dd683df Split session/idx and agent/idx, fix sub-agent tree display
Server:
- session/idx now outputs: session-id, session-name, paused, connected, remote, cwd
- session/{s}/agent/idx now outputs: session-id, agent-id, agent-name, parent-id, depth, state
- Add error if parent agent not found during sub-agent spawn

GUI:
- refreshSessions() reads session index, then agent/idx per session
- Auto-select first top-level agent (depth 0) instead of first in list
- SessionModel tracks agent expansion separately from session expansion
- Agents with children show expand/collapse arrows and are collapsible
- Add hasChildren role to SessionModel

Tools:
- subagent_spawn now passes parent= argument for proper depth tracking
- Remove hardcoded max_depth=5, use server default of 1
- Makefile installs shell script tools from data/tools/

KRunner:
- Update to parse new session/idx format
2026-08-17 13:03:26 +02:00
Levi Neely 958d3d2ddf workflows: script-based workflows with session-level CWD
- Workflows are executable scripts in data/workflows/
- New 'workflows' 9P file lists available workflows
- Goal file stores text; writing triggers workflow if status allows
- goalstatus file for status read/write, goalwait for blocking
- Session ctl accepts 'run [workflow]' command
- Session now owns CWD; agents inherit via callback
- Conductor workflow: creates agent, primes with instructions, exits
- GUI workflow combo reads from workflows, not agents
- Persistence includes goal, goalstatus, workflow, and session CWD
2026-08-17 12:00:10 +02:00
Levi Neely 743e40c2f8 selectable workflow in new session 2026-08-17 10:52:53 +02:00
Levi Neely 2cde59ac3b session-level goals: goal file + goalwait + conductor workflow
Write to session/{s}/goal to set a session-level objective.
A conductor agent is spawned automatically in the background,
decomposes the goal, spawns sub-agents, and reports completion.

- goal file: write sets goal + starts conductor; read returns status
- goalwait file: blocks until goal status changes (BlockOnce)
- Conductor writes status=complete/blocked back to goal when done
- Session.Goal() / SetGoal() / GoalSignal() on Session struct
2026-08-17 10:15:00 +02:00
Levi Neely 74ba5ae7ac remove maxSteps and ResetsCounter entirely
The step budget mechanism is gone. Agents run until they finish,
are interrupted by the user, or (for sub-agents) hit the timeout.

No replacement. The human is the kill switch.
2026-08-17 09:48:58 +02:00
Levi Neely da0ee4456f sub-agent guardrails: depth, parallelism, timeout
Enforce three limits on sub-agent spawning:
- depth (default 1): sub-agents cannot spawn their own sub-agents
- parallelism (default unlimited): cap concurrent children per parent
- timeout (default 600s): sub-agents are killed after 10 minutes

Top-level agents are never constrained by timeout.

Also: refactored parseAgentNewRequest to return a struct instead of
4 positional values. Added depth/activeChildren fields to Agent.
OLLIE_SUBAGENT_DEPTH env var set on sub-agents.

Deferred: remove maxSteps (replace entirely with timeout).
2026-08-17 09:37:59 +02:00
Levi Neely ecb9406413 agent/new: fork_at= parameter for historical context forking
Sub-agents can now inherit parent context truncated at a specific
user turn: fork_at=5 means 'fork from the state after the 5th
user message.' Enables backtracking without losing unsummarized
context from before a failed approach.

Without fork_at (or fork_at=0), full history is inherited as before.
2026-08-17 09:04:57 +02:00
Ollie Agent 9789eb56ff show agent reasoning output 2026-08-17 00:08:27 +02:00
Ollie Agent 5d834934de sandbox update 2026-08-16 21:23:15 +02:00
Ollie Agent 45ff8a2864 Remove legacy backend environment configuration 2026-08-16 19:48:52 +02:00
Ollie Agent e51a1d4ff7 Update architecture documentation and remove obsolete frontends 2026-08-16 19:21:26 +02:00
Ollie Agent 57aa906e5f move toolsrv client into olliesrv 2026-08-16 19:07:25 +02:00
Ollie Agent b321eed99f use 9fans client directly 2026-08-16 19:00:48 +02:00
Ollie Agent 16a2b72051 consolidate 9P clients 2026-08-16 18:56:11 +02:00
Ollie Agent 59c4ed23ac merge paths utilities into util 2026-08-16 18:37:03 +02:00
Ollie Agent aca5546ea5 refactor environment utilities and file tools 2026-08-16 18:20:50 +02:00
Ollie Agent 81933e5281 refactor toolsrv into client protocol and metadata packages 2026-08-16 17:22:59 +02:00
Ollie Agent e972b5666a add metrics queries and agent-scoped plans 2026-08-16 17:00:11 +02:00
Ollie Agent 9409920c61 Propagate parent ID for spawned sub-agents 2026-08-16 11:44:39 +02:00
Ollie Agent 72209239b0 Add parent IDs for sub-agents 2026-08-16 11:44:06 +02:00
Ollie Agent ab9fd60901 Document sub-agent context isolation 2026-08-16 11:39:21 +02:00
Ollie Agent e1ac2df3fb Lower tool output cap and add Markdown parsing 2026-08-16 11:31:31 +02:00
Ollie Agent f82b36ea80 Integrate OptMem memory backend 2026-08-16 11:10:50 +02:00
Ollie Agent 929b94e34d Clarify workspace path placeholders 2026-08-16 10:30:56 +02:00
Ollie Agent 741ac689f8 Persist and expose aggregate usage metrics 2026-08-15 20:12:21 +02:00
Ollie Agent a945445c1f Expose cache metrics in agent stats 2026-08-15 20:04:34 +02:00
Ollie Agent 45746a3164 Expose agent stats through ctl 2026-08-15 19:58:54 +02:00
Ollie Agent 9330632402 Use compaction model context limit 2026-08-15 14:13:44 +02:00
Ollie Agent 8553bc7283 measure provider prompt cache hits 2026-08-15 14:09:00 +02:00
Ollie Agent 64b76d9bf0 stabilize provider prompt prefix 2026-08-15 13:57:31 +02:00
Ollie Agent 5dbfa3060f include tool semantics in summary cache 2026-08-15 13:46:29 +02:00
Ollie Agent 82ab9dd2e3 version summary cache keys 2026-08-15 13:43:04 +02:00
Ollie Agent 60c4541fa4 normalize summary cache keys 2026-08-15 13:42:11 +02:00
Ollie Agent adf7242774 reduce cold results locally 2026-08-15 13:33:26 +02:00
Ollie Agent 32180bee4d defer cold summaries until needed 2026-08-15 13:27:16 +02:00
Ollie Agent f167168df3 incrementalize cold summaries 2026-08-15 13:13:22 +02:00
Ollie Agent 25d502cfc2 cache cold result summaries 2026-08-15 13:10:15 +02:00
Ollie Agent b6584d35e7 cancellation persistence fix 2026-08-15 12:59:21 +02:00
Ollie Agent f38b130111 explicit summary state on stripCold 2026-08-15 12:55:04 +02:00
Ollie Agent f4cb1ea290 validate cold history summaries 2026-08-15 12:42:28 +02:00
Ollie Agent 329edc3218 account for stripCold in cost 2026-08-15 12:37:13 +02:00
Ollie Agent e4c24e8a5f fix cancellation and configure compaction model 2026-08-15 12:29:55 +02:00
Ollie Agent 93f021f068 feat: add userPrompts config field for active global rules
- Add UserPrompts Prompt field to AgentConfig (same JSON format as prompt).
- Resolve userPrompts via resolvePrompt() in BuildRuntime, store in Runtime.UserPrompt.
- Prepend resolved user prompts to every user message at executeTurn start.
- Document userPrompts in data/agents/README.md.
2026-08-15 11:52:21 +02:00
Ollie Agent f61a93e426 refactor: move stripCold to executeTurn, replace clone with rollback pointer
- Remove per-step stripCold from run(); call once per turn in executeTurn
  after accumulator reset and before preamble injection.
- Replace expensive deep-clone snapshot with pre-turn length truncation.
- Delete unused cloneMessages() helper.
2026-08-15 11:30:19 +02:00
Ollie Agent e0f846bd31 fix: batch preamble injection and stripCold into single LLM calls
- Remove per-step preamble prepending in loop.go; inject once at turn start
  in turn.go instead of re-sending thousands of tokens every tool step.
- Re-inject preamble after overflow retry compaction where it was lost.
- Replace stripCold() N sequential LLM calls with one batched call that
  summarizes all cold-zone tool results via a single JSON response.
2026-08-15 11:16:49 +02:00
Levi Neely 617bb5586a subagent: inherit parent context via parent= parameter
Sub-agents now clone the parent agent's conversation history into
their initial context. The tool script passes parent=$OLLIE_UNAME
automatically. Mechanically identical to session restore — uses
RestoreHistoryFromMessages on the parent's Messages().
2026-08-14 15:12:16 +02:00
Levi Neely a8d087a080 system prompt: document sub-agent mechanism
Add Sub-Agents section explaining agent/new with prompt= key.
Include examples for single and parallel sub-agent spawning.
Update 9P namespace table to show agent/new as rdwr.
2026-08-14 14:52:53 +02:00
Levi Neely 250ad4b233 agent/new: sub-agent support via rdwr with prompt=
Writing to session/{s}/agent/new with a prompt= key now blocks
until the agent completes its task, then returns the reply and
destroys the transient agent. Without prompt=, behaves as before
(creates agent, returns ID).

Also:
- Move ParsePayload/UnescapeValue to shared ollie/toolsrv package
- Remove duplicate implementations from cmd/toolsrv/internal/server
- Add session.CreateAgentWithParams for direct AgentParams usage
- Eliminate flattenParams/unescapeValue redundancy in fs package
2026-08-14 14:48:12 +02:00
Levi Neely ab4668cb3f virtfs: rename Request to Rdwr
Read, Write, and Rdwr are the three atomic 9P operations:
- Read: non-blocking read
- Write: non-blocking write (fire-and-forget)
- Rdwr: atomic write-then-read (blocking, produces result)

BlockOnce and Stream are special cases of Read.
Rdwr is its own primitive — not a variant of either.
2026-08-14 14:42:19 +02:00
Levi Neely 5dcde264e6 toolsrv: add path-based lock table for cross-agent serialization
All foreground tool calls now acquire a lock based on the tool's
declared scope and file path before execution:

  - scope "read":  no lock (reads never conflict)
  - scope "write": exclusive lock on the file path
  - scope "global": exclusive global lock (serializes with everything)

This ensures writes to the same path serialize regardless of which
agent initiated the call, enabling safe parallel sub-agents within
a session without explicit coordination.

Cross-session serialization (shared toolsrv per host) is left as
future work.
2026-08-14 14:27:21 +02:00
Levi Neely c61fada3e9 extract rebuildAgentRuntime, remove nil guards on things that must not be nil 2026-08-14 08:47:59 +02:00
Levi Neely 785fe0996f fix: rebuild full agent runtime on session resume
Paused sessions restored agents with stub Runtime (nil Backend,
nil Preamble). On resume, now rebuilds the complete runtime:
loads config, builds preamble, creates backend, loads tools.
Added Agent.SetRuntime for this path.
2026-08-14 08:45:54 +02:00
Levi Neely a8fd7a658f fix: nil Preamble on restored paused sessions
The persist path created agents with &Runtime{} (nil Preamble).
If a prompt arrived before resume rebuilt the runtime, Preamble.Set
panicked. Initialize with an empty Preamble.
2026-08-14 08:42:03 +02:00
Levi Neely dc26871bdc proc/list: use fixed-width columns instead of tabs 2026-08-13 22:28:33 +02:00
Levi Neely 0fed1aa124 proc/list: include command in output 2026-08-13 22:24:50 +02:00
Levi Neely d64f6c1d76 proc: rename ListDetachedRaw→ListProcs, use proc/list rdwr (agent-filtered)
ListProcs now does rdwr to toolsrv proc/list with the agent ID.
Returns pre-formatted text. Ctl proc handler uses it directly.
Removed all ListDetachedRaw map-parsing logic.
2026-08-13 22:22:54 +02:00
Levi Neely 9246c44c0e agent: remove proc/detach/tool wrapper methods — inline in ctl handler
Removed from Agent: ListProcs, SignalProc, ProcOutput, DismissProc,
Detach, ListDetached, SignalDetached, GetDetachedOutput,
DismissDetached, BgProc type, DetachedInfo type.

The ctl handler now calls toolsrv client methods directly.
RefreshTools replaced by SetToolsPreamble + inline ListTools call.
renderTools exported as RenderTools.
2026-08-13 22:14:37 +02:00
Levi Neely c767ee10c9 ctl proc top: include STATUS column 2026-08-13 22:09:09 +02:00
Levi Neely de33f954e2 toolsrv: proc/list now rdwr with agent filtering
Write agent ID to filter, or empty for all. Returns pid\tstate\ttool.
Added ListProcsForAgent to State.
2026-08-13 22:08:15 +02:00
Levi Neely 48add8f7bb remove proc/ directory from agent namespace (processes live in toolsrv) 2026-08-13 22:01:06 +02:00
Levi Neely 6e5b1aa5f0 system prompt: remove proc/ from agent table (managed via ctl) 2026-08-13 21:59:34 +02:00
Levi Neely 6d4e7e237d system prompt: remove tools file from table (it's a ctl command, not a file) 2026-08-13 21:59:04 +02:00
Levi Neely fd4a3afa4f move tool catalog to toolsrv: add /all file, tools_all ctl command
- Remove /tools from olliesrv root (toolsrv owns all tool state)
- Add /all file to toolsrv namespace (lists all available tools on disk)
- Add ListAllTools() to toolsrv client library
- Add tools_all ctl command to agent (reads from toolsrv/all)
- Update system prompt with tools_all usage
2026-08-13 21:58:08 +02:00
Levi Neely a1e78bca80 remove tool_load: use ctl directly
tool_load was a built-in intercept in the agent loop — the only
'tool' that didn't run in toolsrv. Removed entirely:
- Intercept in loop.go (25 lines)
- Script + .meta in data/tools/
- autoLoad references in agent configs

Loading tools is now exclusively via ctl (which already existed):
  echo 'tool_load X' | ollie-9p write .../ctl

System prompt updated to show the ctl pattern.
2026-08-13 21:44:46 +02:00
Levi Neely 324247b6a5 fs: remove dead streamChat and mergeCtx 2026-08-13 21:09:53 +02:00
Levi Neely 4bb08e860b toolsrv: fix shutdown ordering — close conn before draining
On context cancellation, close the connection first to unblock
ReadFcall. Then wait for in-flight handlers, drain the response
channel, and wait for the writer to finish. No writes hit a
closed socket.
2026-08-13 21:08:01 +02:00
Levi Neely d9026499fd toolsrv: suppress write errors during shutdown 2026-08-13 21:04:19 +02:00
Levi Neely bcaac146d2 server: on BlockOnce timeout, fall back to non-blocking Read
Frontends rely on getting the current state on timeout (heartbeat).
When BlockOnce returns empty (5s timeout), the server now calls the
plain Read handler as fallback. Files without a Read handler (like
feed) return nothing — consumer unaffected.
2026-08-13 20:59:05 +02:00
Levi Neely dd0021fd9a fix: restore sessions after 9P listener is ready
ConsumeFeed dials the 9P socket. Moving session restore to after
the listener starts ensures the socket exists when feed consumers
connect.
2026-08-13 20:55:02 +02:00
Levi Neely dcd119c853 virtfs: refactor Stream to accept (readFn, signalFn)
Same pattern as BlockOnce: framework handles the blocking loop.
readFn takes a base string, returns (data, nextBase, error).
signal fires when new data may be available.

Chat stream handlers now use Stream(a.ChatRead, a.ChatSignal).
StreamRaw retained for custom handlers.

streamChat() in support.go is now dead code (replaced by ChatRead).
2026-08-13 20:50:27 +02:00
Levi Neely 794673a5d0 virtfs: refactor BlockOnce to accept (readFn, signalFn)
BlockOnce now takes a value-reader and a signal source. The framework
handles the blocking loop: read → compare hash to base → if different
return → else wait on signal or timeout.

On timeout (ctx.Done), returns empty (not error) so clients re-open
cleanly.

BlockOnceRaw retained for queue-style handlers (bypass/pending,
proc/wait) that manage their own blocking.

EventValue adapter wraps a <-chan Event into BlockOnce-compatible
(readFn, signalFn) pair via a thin goroutine.
2026-08-13 20:44:50 +02:00
Levi Neely b5cb8c397d feed: BlockOnce with base init, ConsumeFeed via lib9p client
- BlockOnce handler initializes base to current hash on fresh open,
  then blocks until hash changes. Same pattern as statewait.
- ConsumeFeed is a plain function: dials 9P, reads feed in a loop
  (open → block → data → close → repeat), submits to agent.
- Context cancellation closes the 9P client, unblocking Read().
- Called as go ConsumeFeed(ctx, ag) from AddAgent and session resume.
2026-08-13 20:26:08 +02:00
Levi Neely e2695d6f50 feed: export Feed field, remove wrapper methods, use direct access everywhere 2026-08-13 20:09:28 +02:00
Levi Neely 1537e35685 feed: inline handlers, remove FeedBlockingRead wrapper 2026-08-13 20:06:32 +02:00
Levi Neely 721b49ffa2 feed: use BlockOnce for read side, dedup via base comparison
Feed is now read-write (0666):
- Write: store data, signal via notifyChange
- Read (BlockOnce): block until content hash differs from base

Dedup lives in the read layer (same pattern as statewait). The
internal consumer goroutine and external 9P clients both call
FeedBlockingRead — same codepath, same dedup logic.

Consumer started from AddAgent (if ctx available) and session resume.
2026-08-13 20:05:46 +02:00
Levi Neely dfacdfed94 agent: add feed file — change-detecting streaming input gate
Feed is a write-only file in the agent namespace. Writes are
deduplicated against the previous value; the internal consumer
(blocking on WaitChange/WatchFeed) only wakes when genuinely new
data arrives.

Wiring is external and source-agnostic:
  # human → observer (poll git):
  while :; do git diff HEAD; sleep 5; done | ollie-9p write .../feed
  # agent → observer (stream chat):
  ollie-9p read .../coder/chat | ollie-9p write .../observer/feed

Uses the agent's existing signalCh/notifyChange plumbing — no new
channel infrastructure. Consumer goroutine spawned at agent creation
(AddAgent) and session resume, tied to session context.
2026-08-13 20:02:06 +02:00
Levi Neely 5459e7fa2a fix: XDG default fallback in prompt resolver; deduplicate tool headers
- envLookup: provide XDG spec defaults (XDG_CONFIG_HOME, XDG_DATA_HOME,
  XDG_CACHE_HOME) when env vars are unset, so agent profile prompts
  resolve correctly on systems without explicit XDG vars.
- renderTools: skip generated '## name' header when the tool's prompt
  text already starts with a markdown header, eliminating duplicates.
2026-08-13 15:45:35 +02:00
Levi Neely 6a19c135eb prompts: drop tool path from system prompt, use absolute path in copilot example 2026-08-13 12:04:52 +02:00
Levi Neely 83b0b59a0a prompts: remove /home/user path examples that bias tilde expansion
- file_grep.meta: replace /home/user/project with /abs/path
- system_prompt.md: use $XDG_CONFIG_HOME instead of ~
- agent-copilot.md: use relative path in code block example
2026-08-13 12:02:27 +02:00
Levi Neely 1ac50d97e1 agent: drain FIFO after interrupted/failed turns
Fix holes where queued prompts were orphaned:
- After turn loop exits (interrupt, toolsrv unavailable), drain remaining FIFO items
- On panic recovery, pop next FIFO item and re-submit in a new goroutine
- fifo file write triggers Submit when agent is idle
2026-08-13 11:59:11 +02:00
Levi Neely 9b98a958cc fix: treat meta cmd as shell command string, prepend tools dir to PATH
- ResolveTool now returns cmd field as-is instead of trying to resolve
  it as a binary path. This allows meta-only tools to use full shell
  command strings with env vars, pipes, and subshells.

- Prepend ~/.config/ollie/tools to PATH when executing tools so cmd
  fields can reference other tools by name.
2026-08-12 18:44:16 +02:00
Levi Neely 23f3a6092b refactor: eliminate TurnCtx, make loop functions Agent methods
- Delete TurnCtx struct (was progressively populated with optional nil fields)
- Convert run(), streamResponse(), execToolCalls(), execBatch(), execOne(),
  trackErrors(), retryCountdown() to Agent methods
- Extract autoCompact() and popInject() as Agent methods
- turn.go now installs a turn-scoped output handler wrapper instead of
  building TurnCtx closures
- context.Context is now passed as plain context.Context, not smuggled
  with unrelated state

Add history compaction tests:
- TestBuildCompactedHistory_OrphanedToolWalkback: verifies walk-back logic
  prevents orphaned tool messages at hot zone boundary
- TestBuildCompactedHistory_NoOrphanAtBoundary: verifies tool messages
  always have preceding assistant with tool_calls
2026-08-12 18:06:19 +02:00
Levi Neely 0a4149218a fix: set agent ID on toolsrv connection after resume 2026-08-12 17:10:22 +02:00
Levi Neely bc7f51a9dc refactor: push proc completion from toolsrv to agent prompt
- toolsrv pushes <system-proc-complete> to agent prompt when bg proc exits
- Remove bgTracker and CollectInterrupts from olliesrv
- Add Cmd, AgentID, SessionID fields to Proc
- Add OnProcExit callback to State
- Add command field to Proc.Stat() output
2026-08-12 16:39:43 +02:00
Levi Neely 6eb3bf960b refactor: query toolsrv directly for proc list
- ListProcs() now queries toolsrv directly instead of local tracker
- Remove ownership verification from SignalProc/ProcOutput/DismissProc
- Clean up stale procs from local tracker when they disappear from toolsrv
- Document local tracker quirk in TODO.md for future cleanup
2026-08-12 16:06:22 +02:00
Levi Neely 1d5e9c4f8d fix: background proc output capture and status display
- Detach background proc context from request context so processes survive
  after the 9P request returns (fixes premature SIGTERM)
- Add /proc/list file to toolsrv showing all procs with state
- Show status (running/exited (N)) in agent proc list
- Keep exited procs in tracker until explicitly dismissed
- Skip 'list' entry in ListDetachedRaw
2026-08-12 14:10:08 +02:00
Levi Neely 85435447bf fix: clean shutdown without connection errors
- Use read deadline + context check instead of forcibly closing connections
- ReadBypassPending now takes context and exits cleanly on cancellation
- Remove forced conn.Close() loop from Kill() - context cancellation suffices
2026-08-12 12:40:40 +02:00
Levi Neely 9057d36f05 docs: clarify tool usage in system prompt, add cancellation flow doc
- Explicitly tell model not to invoke tool scripts via filesystem path
- Add concrete examples of native tool calls vs shell
- Document context cancellation flow from interrupt to process kill
2026-08-12 12:20:34 +02:00
Levi Neely aedfdec564 fix: set agent ID on tool server after /agent switch
SwitchProfile creates a new tool server connection but wasn't calling
SetAgentID on it, causing 'agent ID required' errors when listing tools.
2026-08-12 11:08:37 +02:00
Levi Neely edd5ade471 refactor: simplify bypass - toolsrv is the broker, olliesrv is just a client
- Remove olliesrv's bypass broker machinery (pendingCh, EvaluateRequest, etc)
- Session bypass loop now just reads from toolsrv's bypass/pending and notifies
- Notification handler writes directly to toolsrv's bypass/resolve (fire and forget)
- Remove bypass/ directory from olliesrv's 9P namespace
- Remove session/*/bypass file (policy can be added back to toolsrv later if needed)

The flow is now:
1. toolsrv blocks tool execution, exposes request via bypass/pending
2. olliesrv reads from toolsrv, shows D-Bus notification
3. User clicks approve/deny, olliesrv writes to toolsrv's bypass/resolve
4. toolsrv unblocks and executes (or denies)
2026-08-12 11:01:29 +02:00
Levi Neely 46bd0dd999 fix: toolsrv 9P server now handles BlockOnce/Stream reads correctly
- Added BlockingReadMode() and StreamMode() handling to toolsrv's handleRead()
- Made NextPending() context-aware in both toolsrv and olliesrv bypass packages
- This fixes the bypass approval flow via 9P - reads now properly block until
  a request is available and respect context cancellation
2026-08-12 10:49:08 +02:00
Levi Neely d59f49ee54 feat: context cancellation for tool calls
Wire context cancellation through the toolsrv 9P server so that
canceling a CallTool context properly terminates the running tool.

Changes:
- virtfs: Add Close() to File interface with CloseFn for Request handlers
- toolsrv/p9.go: Handle requests concurrently to allow Tclunk during
  blocking Twrite; call entry.Close() in handleClunk
- toolsrv/internal/server/proc.go: Check ctx.Done() while waiting for
  tool completion in NewProc
- Integration tests for context cancellation chain

The cancellation chain: client cancels ctx → fid.Close() → Tclunk →
handleClunk calls entry.Close() → closeFn cancels reqCtx → NewProc
sees ctx.Done() and returns ctx.Err()
2026-08-12 10:00:44 +02:00
Levi Neely 31681cb4e7 Add context cancellation to bypass.Submit
bypass.Submit now takes a context and returns early when cancelled.
This allows the stop command to properly cancel pending bypass requests
that haven't been approved or denied yet.

The full context chain is now:
1. stop command -> Interrupt -> cancel actCtx
2. actCtx cancellation -> closes CallTool fid
3. toolsrv proc/new sees closed fid -> propagates ctx cancellation
4. ExecuteTool -> executeBypassDirect -> bypass.Submit
5. bypass.Submit returns ctx.Err() when context is cancelled
2026-08-12 09:32:21 +02:00
Levi Neely 5dc7cdc2ea Make Request() always context-aware
Remove RequestCtx variant - all Request handlers now take context.
This is required for proper cancellation of blocking operations
like tool execution when the client disconnects or stop is called.
2026-08-12 09:30:39 +02:00
Levi Neely 861cb47d13 Add RequestCtx for context-aware request handlers
- Add RequestCtx field to FsNodeDecl for handlers that need context
- Add RequestCtx() helper function in virtfs/decl.go
- Update builder.go to handle RequestCtx in validation and Open
- Use RequestCtx in toolsrv proc/new and proc/new.bg handlers

This allows the context to be cancelled when the 9P fid is closed,
enabling proper stop/interrupt of running tool calls.
2026-08-12 09:26:02 +02:00
Levi Neely 3a68b0be53 Fix bypass broker and stop command
- Wire BypassBroker into fs.Config before creating root tree
- Move defer bypassBroker.Close() outside block scope (was closing immediately)
- Rewrite /bypass/ FS nodes to match toolsrv's expected interface:
  - bypass/pending: blocking read returning JSON {id,cmd,cwd,env}
  - bypass/resolve: write JSON {id,approved,error}
- Add NextPending() method to broker with channel-based blocking
- Add JSON tags to Request struct for proper serialization
- Start bypass loop for restored sessions (was only for new sessions)
- Add context cancellation support to CallTool (closes fid on cancel)
2026-08-12 09:16:59 +02:00
Levi Neely 9bb3cd76b8 Remove sudo mechanism from bypass system
The sudo credential broker was never functional and added complexity
without value. This removes:

- Sudo field from bypass Request structs (broker, client, toolsrv)
- Sudo parameter from EvaluateRequest interface and implementations
- Sudo/ResetsCounter fields from MetaFile and Variant structs
- sudo: true from system_logs.meta variants
- All sudo documentation from writing-tools.md, tool-registry.md,
  core.md, evolution.md, and misc.md

Bypass remains fully functional for sandbox escapes. Tools that need
elevated privileges should handle that internally or be run manually.
2026-08-12 08:58:41 +02:00
Levi Neely 62a7d0d13f bypass: remove socket-based execution (dead code)
The old bypass broker used a Unix socket to receive requests and
execute commands locally. This was replaced by the 9P-based flow
where toolsrv executes commands after receiving approval from
olliesrv.

Removed:
- acceptLoop, handleConn, executeAndStream, executeWithSudo
- sendFrame, indexOf, socketDir helpers
- SocketPath and Credential config options
- Frame constants (FrameData, FrameExit)
- net.Conn field on Request

The broker now only handles:
- Policy management (global + per-session)
- Request evaluation (EvaluateRequest)
- Rate limiting
- User notification callbacks

Execution happens in toolsrv, not olliesrv.
2026-08-12 08:51:19 +02:00
Levi Neely 8bb5c098cc bypass: route approval through 9P instead of Unix socket
This refactors the bypass (sandbox escape) mechanism to work with remote
toolsrv deployments. Previously, bypass used a Unix socket which only
works when toolsrv runs locally. Now:

1. toolsrv exposes bypass/{pending,resolve} 9P files
   - pending: blocking read returns next bypass request as JSON
   - resolve: write JSON {id, approved, error} to complete request

2. olliesrv reads bypass/pending in a loop per session
   - Evaluates requests through the existing bypass broker
   - Policy check, rate limiting, user notification all stay in olliesrv
   - Writes approval/denial back to bypass/resolve

3. When approved, toolsrv executes the command directly (no sandbox)
   - Execution happens on toolsrv's host (local or remote)
   - Output streams back through the normal tool call path

This enables bypass to work when toolsrv is remote:
- User sees the approval notification locally
- Command executes on the remote host outside its sandbox

Architecture:
  toolsrv (remote)          olliesrv (local)
  ┌─────────────────┐      ┌──────────────────┐
  │ sandboxed cmd   │      │ bypass broker    │
  │      ↓          │      │  - policy        │
  │ bypass.Submit() │──────│  - notification  │
  │      ↓          │ 9P   │  - rate limit    │
  │ wait for result │←─────│  - user approval │
  │      ↓          │      └──────────────────┘
  │ execute direct  │
  └─────────────────┘
2026-08-12 08:48:32 +02:00
Levi Neely 1814f82928 toolsrv: include session ID in bypass broker requests
The bypass broker requires a 'session' field in the JSON request
to identify which session is making the bypass request. The toolsrv
was sending requests without this field, causing 'denied (no session
identity)' errors.

Fix: Include OLLIE_SESSION_ID from environment in the bypass request.
2026-08-12 08:34:52 +02:00
Levi Neely 23b427f97b toolsrv: fix integration test to provide sandbox.yaml 2026-08-12 08:30:09 +02:00
Levi Neely 3ee4f16653 fs: remove proc/ proxy, add tool_unload to agent ctl
- Remove session/{sname}/agent/{aname}/proc/ tree (redundant proxy to toolsrv)
- Add tool_unload command to agent ctl file
2026-08-12 08:25:22 +02:00
Ollie Agent 47b460b2da fs: eliminate AgentLog, SessionNode, RootState
State now lives where it belongs:
- Chat log/plan/condvar → agent.Agent (new chatlog.go)
- Models cache → session.Session
- Event handler → agent.Agent.initChatHandler() (self-wiring)
- Message replay → agent.Agent.ReplayMessages()

The fs package is now a pure presentation layer: spec.go (namespace),
support.go (shared utils), newroot.go (entry point), cache.go (ModelCache).
No wrapper types, no parallel registries.

Deleted: AgentLog, SessionNode, RootState, lifecycle.go, agent_log.go,
session_node.go. Removed replay_test.go (needs rewrite against agent pkg).
2026-08-11 21:50:18 +02:00
Ollie Agent 31d3466b3b agent: add chat log fields and methods
Moved log buffer, plan, mutex, and condvar onto agent.Agent directly.
These were previously on the fs package's AgentLog type. The fs package
will be migrated to use these in the next commit.

New methods: AppendChat, EnsureTrailingNewline, ChatMu, ChatCond,
ChatLog, Plan, SetPlan.
2026-08-11 21:41:12 +02:00
Ollie Agent b01dbdfba8 sandbox: single config, no named profiles
Removed the named sandbox concept. One config file: sandbox.yaml
(installed to ~/.config/ollie/sandbox.yaml). Removed sandbox-remote.yaml,
moved restricted.yaml to doc/ as a sample. Removed the 'sandbox' arg
from tool dispatch.
2026-08-11 21:23:23 +02:00
Ollie Agent d06183c8d5 fix file header comment 2026-08-11 21:19:05 +02:00
Ollie Agent b5411f930f toolsrv: rename server.go → p9.go 2026-08-11 21:17:18 +02:00
Ollie Agent 62fe1dab83 toolsrv: rename internal/fs → internal/server
The package defines the Server type and its namespace — 'fs' was a
leftover name from when it only held the filesystem spec. Now it's
the server definition. File renamed spec.go → server.go to match.
2026-08-11 21:15:03 +02:00
Ollie Agent 8ce8390421 toolsrv/fs: move Server into spec.go, delete state.go
Server is the top-level type that Spec() takes as input. It belongs
with the namespace declaration, not in a separate file.
2026-08-11 21:12:51 +02:00
Ollie Agent 7591b2369b fs: remove connected file, agent tools file; fix session/idx hang
- Removed session/connected (used blocking Ping() on potentially stale conn)
- Removed per-agent tools file (tool management now via toolsrv ctl)
- Fixed session/idx: replaced blocking IsConnected() with non-blocking
  toolsConn != nil check, preserving the field for GUI compatibility
- Removed dead IsConnected() method from session.Session
2026-08-11 21:06:42 +02:00
Ollie Agent 066659b8b6 olliesrv/fs: inline all handlers into spec.go
The namespace spec is now fully self-contained. Every handler is a
closure right where it's declared — no jumping between files.

Deleted: handlers_root.go, handlers_session.go, handlers_agent.go, ctl.go
Added: support.go (shared utilities: mergeCtx, streamChat, stripMarkers,
dispatch, wireAgentEvents, help memoization)

spec.go grew to ~920 lines but is now the single source of truth for
the entire 9P namespace. Know where to look.
2026-08-11 20:41:08 +02:00
Ollie Agent 5a09e603cd virtfs: eliminate Binding type
Each() now returns []FsNodeDecl directly. The Binding type was a
redundant subset of FsNodeDecl with a slightly different Remove
signature. Dynamic entries are now expressed uniformly — Remove,
Rename, Children, Aliases all live on FsNodeDecl like everything else.

Also added: Alias() and RenameNode() options, DirNode accepts
[]FsNodeDecl for passing pre-built child slices.
2026-08-11 20:24:29 +02:00
Ollie Agent ee7426d628 rename fsedsl → virtfs
The package has outgrown its original 'eDSL' framing. It's a virtual
filesystem library. Rename to match.
2026-08-11 17:21:44 +02:00
Ollie Agent d71ff80993 olliesrv/fs: embed *session.Session in SessionNode, kill delegation
SessionNode now embeds *session.Session instead of wrapping it.
All delegation methods (ID(), Name(), Ctx(), Pause(), etc.) are removed.
Handlers access session fields/methods directly through promotion.

Moved pause/resume event publishing into session.Session itself since
the session package already owns PublishEvent.

Eliminated all s.Session.X stutter from handler code.
2026-08-11 17:19:10 +02:00
Ollie Agent 1474eeaaed olliesrv/fs: eliminate Hctx adapter struct
Handlers now accept their actual dependencies directly:
- Root handlers: ModelCache, Broker, context.Context, etc.
- Session handlers: *SessionNode, removeFn, renameFn
- Agent handlers: *agent.Agent, *AgentLog, *SessionNode

Ctl dispatch tables are now per-instance closures built at binding
time rather than package-level vars with generic Hctx.

Also inlined the intermediate internalBinding type — adapt functions
now build fsedsl.Binding directly from raw data.

Removed: Hctx struct, rdwrHandler type, rdwrDispatch func,
bypassBindings helper, processBindings helper, internalBinding type.
2026-08-11 17:15:01 +02:00
Ollie Agent 95eb402c68 olliesrv/fs: migrate to closure-capture fsedsl API
Converted the entire 9P namespace spec from progressive Hctx population
to closure capture. Handlers are now closures that capture their
dependencies (session, agent, etc.) at binding time.

Hctx remains as a transitional adapter — handlers still receive it,
but it's constructed per-call from captured state rather than threaded
through the tree. Will be removed in a follow-up once handlers are
converted to use captured state directly.
2026-08-11 17:04:40 +02:00
Ollie Agent 53b4618561 toolsrv: migrate to closure-capture fsedsl API
Spec() now takes *Server and all handlers are closures that capture it.
Removed Ctx type, type aliases, and separate handler functions.
The tree structure and behavior are declared together in one place.
2026-08-11 16:56:34 +02:00
Ollie Agent 8a5883fcb2 fs: rename HandlerCtx → Hctx, SessionNode.Core → Session 2026-08-11 16:30:05 +02:00
Ollie Agent de5456e4aa toolsrv: fix per-agent tool registry to actually work
The registry was keyed by agent ID but read it from a shared env map
(st.env["OLLIE_UNAME"]) that all agents overwrote — making it
effectively per-session with a race condition.

Fix: pass agent ID explicitly through the protocol at every call site.

- ctl protocol: 'load <agentID> <tool>', 'unload <agentID> <tool>'
- tools file: rdwr (Request) — write agent ID, read filtered list
- proc/new payload: 'agent=<id>' field required
- Client: SetAgentID() stores identity, included in all operations
- Empty agent ID is a hard error everywhere
- Setting OLLIE_UNAME via env ctl is blocked (prevents reintroduction)
2026-08-11 16:26:12 +02:00
Ollie Agent 659f89fcbf toolsrv: per-agent tool registry
Tools are now scoped per-agent within a session. The registry uses
OLLIE_UNAME (agent identity) to partition loaded tools. Each agent
sees only its own tools — load/unload/list/lookup all key on the
agent ID read from the toolsrv environment.
2026-08-11 11:49:19 +02:00
Ollie Agent 7dfd769c25 server: fix BlockingReadMode truncation, separate stream/blocking paths
BlockingReadMode had the same 512-byte truncation bug: it returned EOF
on offset>0 before the full content was delivered. Now caches content
on the fid like normal reads.

StreamMode is separated into its own path since it has fundamentally
different semantics (each Tread blocks for the next chunk, no caching).
2026-08-11 11:45:47 +02:00
Ollie Agent cfc526b0d7 server: cache read content on fid for offset-based paging
In 9P, clients issue multiple Treads at increasing offsets to read
files larger than the initial buffer (io.ReadAll starts at 512 bytes).
The server was calling entry.Read() on every Tread, which for Request
files cleared the result after the first call, causing truncation.

Fix: cache the Read() result on the fid (readCache). Subsequent Treads
at higher offsets serve from the cache via readSlice. The cache is
cleared on write (for rdwr files) so the next request-response cycle
gets fresh data. This mirrors how dirCache already works for directories.
2026-08-11 11:44:30 +02:00
Ollie Agent 83f6211369 toolsrv: simplify registry to flat list, remove session scoping
One toolsrv per session means the session-scoped map was unnecessary
indirection. Registry now tracks a flat map of loaded tools with no
session ID parameter. This eliminates the class of bugs where sessID
could be empty or mismatched between Load and Loaded calls.
2026-08-11 11:30:47 +02:00
Ollie Agent cfc429f5f4 fix: expand ~ in toolsrv CWD to prevent fork/exec ENOENT
Shell doesn't expand ~ in programmatically-passed arguments, so
toolsrv received literal ~/src/ollie as --cwd. Go's os/exec fails
with ENOENT on chdir before exec, breaking all tool execution.

Expand ~ at two boundaries:
- main.go: immediately after flag parsing
- proc.go SetCWD(): for runtime cwd changes via 9P
2026-08-11 11:24:10 +02:00
Ollie Agent 686a560e84 agent: toolsrv is sole owner of tool state
Remove all cached tool state from agent:
- Remove toolRegistryRevision from Runtime
- Remove wireToolsChanged (OnToolsChanged callback)
- Remove toolsNeedRefresh (revision-based cache invalidation)
- Remove refreshToolListing (redundant with RefreshTools)

Tools are now fetched fresh from toolsrv at the start of every turn.
The preamble tools section is also rebuilt at turn start. No local
caching means tool_load/unload take effect immediately on the next
turn and /tools always shows the live state from toolsrv.
2026-08-11 10:59:31 +02:00
Ollie Agent 6b4e97aaf7 fix: tool_load and tools use agent's ToolServer consistently
tool_load was loading on the session connection but tools listed from
the agent connection. Now both use ctx.Agent.ToolServer() so loads are
immediately visible. writeAgentTools also calls RefreshTools after load.
2026-08-11 10:50:38 +02:00
Ollie Agent c3afe1453d ctl: add /i alias for inject 2026-08-11 10:47:58 +02:00
Ollie Agent 573c9f4462 cleanup: fix structural inconsistencies, remove dead code
- backend/openai: fix DefaultModel() dead 'anthropic' case, default to gpt-4o
- agent: SetCWD no longer sets stale envBlock first, uses runtime.GOOS
- backend/kiro: ContextLength cache now checks ctxModel consistently
- agent: AgentConfigPath uses agentsDir as the only search location
- fs: ctl 'tools' handler delegates to readAgentTools (dedup)
- agent: remove redundant TurnCtx field assignments in executeTurn
- agent: remove spending cap feature entirely (OLLIE_MAX_SESSION_COST)
- agent: inline stripColdResults into stripCold, remove wrapper
- agent: remove orphaned doc comment at end of text_parse.go
- agent: remove dead Prompt.MarshalJSON
- agent: cloneMessages now copies ID, Reasoning, ContentBlocks
- agent: fix newHistory comment (Session → History)
- agent: fix orphaned CompactionModel godoc on ListModels
- agent: toolCalls only captured from Done event (fix contract)
- agent: HandleCommand uses lib9p client instead of shelling out
2026-08-11 10:46:38 +02:00
Ollie Agent 5740333ad2 prompt: instruct agent to make parallel tool calls
Agents now know to batch independent reads and writes in a single
turn rather than serializing them across multiple turns.
2026-08-11 10:24:53 +02:00
Ollie Agent 3a3d471e06 toolsrv: switch from log/slog to ollie/log
Unify logging across the project. toolsrv now uses the same
async non-blocking logger as olliesrv.
2026-08-11 10:23:27 +02:00
Ollie Agent 391465be77 doc+fix: background procs force timeout=0, update docs
- Background procs get timeout=0 (no deadline) set by toolsrv at
  the execution layer — not injected as an arg from olliesrv.
  Foreground default remains 30s. User can still override via args.
- Timeout logic simplified: caller sets default, ExecuteTool honors it.
- System prompt: clarify background has no timeout, uses 'stop' not 'kill'
- architecture.md: document lifecycle (connection-based ownership)
- evolution.md: update interrupt section with streaming, lifecycle, id= format
- README.md: add parallel execution to capabilities table
2026-08-11 10:18:30 +02:00
Ollie Agent 97c208fa39 toolsrv: kill all procs on shutdown, add Pdeathsig
- KillAll(): sends SIGKILL to all running proc groups on clean shutdown
- Pdeathsig: SIGKILL ensures child procs die if toolsrv crashes
- Shell tool: use subshell + set +e for streaming without exit propagation
- Fix integration test to match new error format

This is the connection-based ownership model: toolsrv death = proc death.
The session owns the toolsrv process, so session death cascades to all procs.
2026-08-11 10:02:53 +02:00
Ollie Agent 0d1eeaa46b fix: background process lifecycle, streaming output, and connection deadlocks
- Timeout: timeout=0 means no deadline (was defaulting to 30s)
- Signal: send to process group (-pgid) not just process; SIGTERM no longer
  cancels context (only SIGKILL does); cmd.Cancel sends SIGTERM with 5s WaitDelay
- Streaming: background procs stream output in real-time via procWriter;
  shell tool no longer buffers all output into a bash variable
- Proc tree: olliesrv exposes proc/{id}/out, proc/{id}/ctl, proc/{id}/status
  as proper 9P directory (was broken flat file)
- Connection: proc handlers dial fresh toolsrv conn per request via
  Session.DialToolServer() to avoid deadlocking the agent's blocked conn
- Stat format: key=value (exited=true, exit_code=N, id=N) matching client parser
- GC: procs auto-removed 10min after LastRead (exited procs only)
- Rename: PID -> ID throughout (synthetic, not OS PID)
- Ctl commands: term (SIGTERM), kill (SIGKILL), signal <n>, dismiss
- System prompt: correct ollie-9p commands for proc management
2026-08-11 09:44:08 +02:00
Ollie Agent 945ce69984 agent: add tests for dispatch flag injection and background helpers 2026-08-11 08:28:54 +02:00
Ollie Agent a098fbff0c agent: inject dispatch flags (bypass, timeout, sandbox, background) into all tool schemas
Dispatch-level flags are now injected into every tool's JSON schema
at runtime via injectDispatchFlags(). No need to declare them in
individual .meta files — they're universal.

Removed redundant declarations from shell.meta (now injected globally).
2026-08-11 08:26:14 +02:00
Ollie Agent aa270525a5 agent: background process interrupts — auto-inject output at safe points
When a tool call includes "background": true, it executes via
proc/new.bg and returns immediately with a PID in a
<system-proc-background> tag. The agent tracks active background
processes and injects their output as <system-proc-interrupt> blocks
alongside subsequent tool results.

The model sees background updates without polling. It can react to
build failures, log events, etc. naturally. Kill via PID when done.

Implementation:
- toolsrv client: CallToolBackground (uses proc/new.bg as rdwr)
- toolsrv: proc/new.bg upgraded from write-only to request-response
- agent: bgTracker collects last 20 lines of output per proc
- agent loop: injects interrupts after execToolCalls, before h.update
- system prompt: documents the background mechanism and rules
2026-08-11 08:23:00 +02:00
Ollie Agent 2870da593d agent: default unset scope to global (safe by default)
Only tools that explicitly declare scope="write" get path-based
parallelism. Unset scope is now global (full barrier), avoiding the
"path is a lie" problem where a tool has a path arg but modifies
other files (e.g., lsp_rename).

Tools must opt in to parallelism:
- scope=read: never conflicts
- scope=write: conflicts on same path only
- scope=global (or unset): serialization barrier

Added scope=write to file_edit.meta and file_write.meta.
2026-08-11 07:57:22 +02:00
Ollie Agent 586edc1332 agent: replace ReadOnly with explicit scope field (read/write/global)
Rename ToolInfo.ReadOnly bool → ToolInfo.Scope string with three values:
- "read"  — path-scoped read, never conflicts (always parallel)
- "write" — path-scoped write, conflicts on same file path only
- "global" — full serialization barrier, runs alone

Tools declare scope in their .meta file. If unset, inferred from path
arg presence (write if path exists, global otherwise).

This correctly classifies lsp_rename as global (cross-file workspace
edits) despite having a path argument. The path arg in lsp_rename is
a symbol coordinate, not a resource scope.

All .meta files updated: readOnly:true → scope:read,
readOnly:false → scope:global, lsp_rename gets scope:global.
2026-08-11 07:56:00 +02:00
Ollie Agent 3dccb36e82 agent: resource-based parallel tool execution
Replace binary ReadOnly/not batching with path-based conflict detection.
Tool calls that operate on different file paths now execute in parallel,
while same-path writes and shell (global barrier) serialize.

Conflict rules:
- ReadOnly tools: never conflict (unchanged from before)
- Write tools with path arg: conflict only on same path
- Shell / unknown (no path): global barrier, runs alone

This parallelizes the common refactoring case where the model edits
multiple files in one turn (e.g., 5 file_edits on different files
complete in 1 round-trip instead of 5).

Safety argument:
- LLM API is turn-based: model reads files first, plans edits based
  on known content, emits writes in a subsequent turn
- file_edit carries old_string context: self-contained per-file
- Same-path conflicts serialize (detected via extractFilePath)
- Shell is conservative: always a full serialization barrier
2026-08-11 07:48:53 +02:00
Ollie Agent df74c3fa60 toolsrv: restructure into internal packages, fix process lifecycle
- Move toolsrv logic into internal/{fs,exec,registry} packages to match
  olliesrv's structure. server.go (9P protocol) stays at top level.

- Deduplicate parseKV/parsePayload: remove dead code from old spec9p.go,
  single implementation in internal/fs/parse.go.

- Add structured logging via log/slog (replaces fmt.Fprintf to stderr).

- Standardize qid path hashing to fnv.New64a (matches olliesrv).

- Fix toolsrv process leaks:
  - Add Pdeathsig to local spawn so toolsrv dies when olliesrv exits.
  - Add idle timeout (30s with no connections after first client seen).
  - ProcessKeeper.Dial() kills old process before respawning.
2026-08-11 07:21:14 +02:00
Levi Neely e8239927de toolsrv: move Registry to cmd/toolsrv, keep only client SDK in shared package
Split toolsrv/registry.go:
- cmd/toolsrv/registry.go: Registry type with session-scoped tool state
  (Load, Unload, Loaded, Lookup, Revision methods)
- toolsrv/registry.go: shared types only (ToolInfo, ToolsPath, DiscoverTools)

The toolsrv/ package is now a pure client SDK:
- Dial, Conn for 9P connection
- ToolInfo, ToolResult, HostInfo types
- DiscoverTools for listing available tools

Server-only code lives in cmd/toolsrv/:
- Registry for session-scoped tool state
- 9P handlers and execution logic
- Sandbox integration
2026-08-10 20:57:32 +02:00
Levi Neely a0315a558a refactor: move toolsrv spawn/process management to toolclient
Move spawn.go from toolsrv/ to cmd/olliesrv/internal/toolclient/:
- Process, ProcessKeeper, Spawn, SpawnRemote now in toolclient package
- toolsrv/ now only contains client code (Dial, Conn, etc.)

This clarifies the architecture:
- toolsrv/ = client SDK for connecting to toolsrv
- cmd/toolsrv/ = the toolsrv server
- cmd/olliesrv/internal/toolclient/ = olliesrv's toolsrv process management

Removed ProcessKeeper tests from toolsrv integration tests since they
now belong to toolclient.
2026-08-10 20:49:22 +02:00
Levi Neely d292f2aa59 feat: make tool_load a built-in tool
tool_load must be handled specially by the agent runtime because tools
run inside toolsrv's sandbox and cannot load other tools into
themselves. The runtime now intercepts tool_load calls and directly
invokes ToolServer.LoadTool().

This is the only built-in tool - all others are external scripts.
2026-08-10 20:37:37 +02:00
Levi Neely be4f6aaf09 feat: add tools file to agent namespace
Add /session/{sid}/agent/{aid}/tools file:
- Read: list loaded tools for this agent
- Write: load a tool by name

Also add missing tool_load to justfile install.
2026-08-10 20:29:04 +02:00
Levi Neely 5815c3e0c9 fix: add nil check for runtime in SetSessionEnv 2026-08-10 20:26:14 +02:00
Levi Neely 4045ae8f91 fix: add env and cwd handlers to toolsrv ctl
HandleCtl was only handling load/unload commands. The client sends
'env KEY=VALUE' and 'cwd PATH' via SetEnv() and SetCWD(), but toolsrv
was returning 'unknown command' errors. This broke tool_load and any
tool that depends on OLLIE_SESSION_ID/OLLIE_UNAME env vars.
2026-08-10 20:23:26 +02:00
Levi Neely 1fc051e3bf refactor: move olliesrv and toolsrv packages to cmd/*/internal/
Move server-only packages under their respective cmd directories:

olliesrv:
- agent/ -> cmd/olliesrv/internal/agent/
- backend/ -> cmd/olliesrv/internal/backend/
- bypass/ -> cmd/olliesrv/internal/bypass/
- fs/ -> cmd/olliesrv/internal/fs/
- prompts/ -> cmd/olliesrv/internal/prompts/
- session/ -> cmd/olliesrv/internal/session/

toolsrv:
- Server-only code (exec9p, fs9p, server9p, spec9p, auth9p) -> cmd/toolsrv/
- sandbox/ -> cmd/toolsrv/internal/sandbox/
- Keep shared client code (client9p, spawn, registry, meta) in toolsrv/
- Add toolsrv/types.go for shared types (ToolResult, ToolResultContent)

This enforces package boundaries - code in cmd/*/internal/ cannot be
imported by external packages, while shared code remains importable.
2026-08-10 20:16:44 +02:00
Levi Neely 89493c32da toolsrv 9P: session ID, JSON tool schemas, remote deployment
- Pass session ID via --session-id flag (not env var) so tool registry is configured when olliesrv spawns toolsrv

- /tools now returns JSON array with full ToolInfo including InputSchema (fixes Bedrock validation error requiring type: object)

- Implement SpawnRemote: deploy ~/.config/ollie via tarball over SSH, set XDG_CONFIG_HOME so tools/*.meta are found on remote

- Add --no-auth flag for debugging Tauth issues
2026-08-10 19:34:00 +02:00
Levi Neely 11c67a7fb1 toolsrv: implement 9P Tauth authentication
Replace HMAC-based registration with proper 9P Tauth flow:
- First client to connect sets the secret via Tauth afid write
- Server stores secret in memory, returns session token
- Subsequent clients must provide matching secret
- Secret never in env vars or disk, only transmitted over socket

Changes:
- server9p.go: Authenticate() replaces RegisterAgent/GetAgent
- client9p.go: Dial() does Tauth handshake (write secret, read token)
- spawn.go: generates secret, no longer passes via TOOLSRV_SECRET env
- auth9p.go: simplified to just GenerateSecret()
- spec9p.go: removed /register file, token validation at connection level
- cmd/toolsrv/server.go: handleAuth/handleAuthWrite/handleAuthRead

Security model:
- Session generates secret on Spawn()
- All agents share session's secret via ProcessKeeper
- Socket permissions (local) or SSH (remote) protect transport
- Secret dies with toolsrv process, new secret on respawn

Added integration tests verifying:
- First connection sets secret
- Reconnect with same secret works
- Wrong secret rejected
- ProcessKeeper reconnect/respawn behavior
- Concurrent connections
2026-08-10 19:03:10 +02:00
Levi Neely 75f364dd85 cmd/toolsrv: implement 9P protocol server
- server.go: Full 9P2000 protocol handling
  - version, auth, attach, walk, open, read, write, clunk, stat
  - Uses fsedsl.Tree for all operations
  - Handles directories and files
  - Supports rdwr files (RequestRespMode)

- main.go: Remove placeholder serve9P, use new implementation

The toolsrv binary now serves a working 9P filesystem with the
namespace defined in toolsrv/spec9p.go:
  /register, /ctl, /tools, /proc/*, /info
2026-08-10 17:53:01 +02:00
Levi Neely 427cadeb29 toolsrv: remove JSON-RPC, add compat stubs for 9P transition
BREAKING CHANGE: Removes all JSON-RPC toolsrv code.

Deleted files:
- server.go, rpcserver.go, rpcwire.go (JSON-RPC server)
- conn.go, dial.go (JSON-RPC client)
- exec.go, stream.go, detach.go (old execution tied to Server)
- spawn.go, transport.go, processkeeper.go, remote.go (spawning)
- shell_validate.go (tied to old Server)

New/modified:
- compat.go: Stub types to keep agent/session/fs packages compiling
  - Conn, Process, ProcessKeeper with TODO implementations
  - Spawn, SpawnRemote stubs
  - HostInfo, RemoteConfig, Option types
  - All marked TODO for 9P implementation

- cmd/toolsrv/main.go: Updated to use 9P model
  - Requires TOOLSRV_SECRET env var
  - Builds fsedsl tree
  - serve9P placeholder for 9P protocol handling

- exec9p.go: Added ToolResult types, limitedWriter, plan9Namespace

The codebase compiles but toolsrv is non-functional until:
1. serve9P implements 9P protocol
2. Conn stubs are replaced with lib9p client
3. Spawn/ProcessKeeper spawn 9P server
2026-08-10 16:48:40 +02:00
Levi Neely 1cd158926a rename ollie-remote to toolsrv
- cmd/ollie-remote -> cmd/toolsrv
- Update all references in toolsrv package
- Update justfile build targets
- Binary now installed as ~/.local/bin/toolsrv
2026-08-10 15:01:42 +02:00
Ollie Agent fbe8059cf5 maintainability: docs, contracts, structural cleanup
- doc/boot-sequence.md: init chain from main → fs.NewRoot → session.Init
- Event protocol: comprehensive table on Event struct (all roles, semantics)
- RPC server moved from cmd/ollie-remote into toolsrv/rpcserver.go
  (binary is now a 93-line thin wrapper)
- SetSessionEnv folded into NewAgent (no post-construction wiring needed)
- AgentCfg → AgentParams (distinguish from AgentConfig JSON schema)
- ToolResult/ToolResultContent shared types in toolsrv/rpcwire.go
- toolsrv/shell.go → toolsrv/exec.go (name matches purpose)
- Resume unified: single path, always through Keeper
- AGENTS.md: fix fs/builder.go → fsedsl/builder.go, handlers_*.go
- fsedsl/Tree: document dual-mode (EDSL lazy vs Manual Mount)
- Truncation stack documented at defaultToolResultMaxBytes
- Integration test rewritten to use srv.ServeRPC directly
2026-08-09 21:45:56 +02:00
Ollie Agent 2d74ffb95e prompt audit: trim system prompt, kill dead code, improve maintainability
- System prompt: ~200 → ~80 lines (removed tool-first table, API docs,
  output protocol, dead 9P entries)
- Removed AllowTools entirely (field, RPC, configs)
- Removed PRIME_* env vars, replaced with typed struct fields
- Merged tool listing + docs into single renderTools()
- Killed BuildToolListing, changed OnToolsChanged to func() signal
- Typed Preamble.Section (compile-time safety)
- Added protocol docs on extractToolResult
- Added session/ package godoc
- Moved output protocol to per-agent prompts
- Rewrote data/agents/README.md
- Moved 7 reference docs from doc/resources/ to doc/
- Deleted PromptEnv() dead function
2026-08-09 14:13:52 +02:00
Ollie Agent 199acabd61 refactor: code review items 15-17
- Extract paths.IsGitRepo() replacing 3 inline copies
  (agent/agent.go, agent/prompt_resolver.go, cmd/ollie-remote/main.go)

- Extract newStreamScanner() in backend.go replacing 3 identical
  bufio.NewScanner + Buffer setups (ollama, openai, anthropic)

- Replace kiroUserDataDir() with paths.UserDataHome() — deletes 18-line
  platform-switch function (darwin/windows branches were dead code)

- Unexport AnthropicBackend.BaseURL → baseURL for consistency with other
  backends. Add export_test.go with SetBaseURLForTest for external tests.
2026-08-09 12:24:15 +02:00
Ollie Agent 74635b8e00 refactor: items 8-10, 12, 13 from code review
- Move parseRetryAfter to backend.go (where it's called)
- Extract paths.RuntimeDir() replacing 3 divergent XDG_RUNTIME_DIR impls
- Rename CodeWhispererBackend → KiroBackend, NewCodeWhisperer → NewKiro
- Export RPCRequest/RPCError/OutputNotification from toolsrv/rpcwire.go
- Factor tools/lsp/cmdutil: Run() and RunCustom() for 7 LSP binaries
2026-08-09 11:32:31 +02:00
Ollie Agent c7aea0db59 rename elevate→bypass throughout
The sandbox escape mechanism is a bypass, not privilege elevation.
The old name caused the agent to confuse it with sudo.

- elevate/ → bypass/ (package, types, tests)
- elevate_notify.go → bypass_notify.go
- Namespace: /elevate → /bypass, session/*/elevate → session/*/bypass
- Tool arg: "elevated" → "bypass"
- Env: OLLIE_ELEVATE_SOCKET → OLLIE_BYPASS_SOCKET
- File: elevate-policy.yaml → bypass-policy.yaml
- All docs, prompts, and scripts updated
2026-08-09 02:22:39 +02:00
Ollie Agent 8152dec075 all: delete dead code, tighten API surface
toolsrv:
- Delete WithOnClose, WithOnEnvSet, SetOnExit (dead Options)
- Delete ListDetached, ListDetachedInfo (only ListDetachedRaw used)
- Delete Execute (dead wrapper)
- Delete CWD, ToolRegistry, SessionID, InjectContent (dead accessors)
- Delete ExecuteInSandbox, ExecuteElevated (zero external callers)
- Delete Summaries, RefreshLoaded from Registry (dead)
- Delete DialSSH (alias for RemoteDial)
- Simplify Dial: takes socket string directly, kill Addr/LocalAddr/SSHAddr
- Rename Server receiver e → s
- Unexport context import (no longer needed in tools.go)

session:
- Delete SaveFuncs, AgentAt, AgentCount, NextUncheckedStep
- Delete SetDisallowTools, SaveAllSessions

env:
- Delete Set, Get, All, Format, managed (dead exports)
- Unexport LoadFile → loadFile

fs:
- Delete HandlerCtx.ToolReg, Skills, SaveFn (never read by handlers)
- Delete Config.MkdirAll, Config.SkillsRegistry (dead plumbing)
- Delete AgentLog: Plan, SetPlan, PrevPrompt, Mu, LogInfo, Remote methods
- Delete unused type aliases (NodeOption, FileTree, FileConfig, etc.)

backend:
- Delete ClosePool, PoolStats (dead), New() (dead)
- Delete kiroTokenExpiringSoon standalone func (dead)
- Unexport SharedTransport/SharedClient → sharedTransport/sharedClient

skills:
- Delete entire package (zero importers; feature works via tool scripts)

agent:
- Delete BroadcastChange (dead duplicate of notifyChange)
- Delete HasHistory, ToolCallCount, CompactionModel, SetCompactionModel
- Unexport SetReply, BuildPreamble, DefaultPromptsDir
2026-08-08 15:51:13 +02:00
Ollie Agent 3b83b9d373 all: delete dead interfaces, kill globalRootState
- agent: delete 'state' interface (one implementation: *History). run()
  now takes *History directly.
- agent: delete 'backendNamer' interface. resolveCompactionModel takes
  backend.Backend directly.
- fs: delete Shutdown/InterruptAll/Lookup wrappers that took *Tree they
  never used. Callers (olliesrv) now call session.* directly.
- fs: delete globalRootState. sessionBindings uses ctx.Root.Data.(*RootState)
  via the HandlerCtx that was always available.
2026-08-08 14:58:47 +02:00
Ollie Agent 63c4cd6173 all: kill dead code, remove classifier system, clean up names
Dead code removed:
- agent: firstSentence, Checkpoint, WaitForChange, InitCond, cfgDir,
  execServer, SaveTo, SaveFull, saveTo, saveToFull, sanitizeMessages,
  LoadPersistedAgent, RestoreHistory, Restore, PersistedAgent type
- toolsrv: entire tier.go (MemoryTier, MemoryTierArgs, OutputFormat,
  CanParallelize on Server), same methods on Conn
- cmd/ollie-remote: can_parallelize, memory_tier, memory_tier_args RPC
  handlers
- toolsrv/rpc_integration_test: all classifier tests
- fs/lifecycle: state(root) dead helper

Renames:
- session.Session receiver: 'a' → 's' throughout
- SaveSession(path) → Save() (dead parameter removed)
- execServer() eliminated — callers use ag.runtime.ToolServer directly

The agent-package save/restore chain was entirely dead: PersistSession
in session/persist.go reads agent accessors directly and never called
SaveTo/SaveFull.
2026-08-08 14:52:10 +02:00
Ollie Agent 38b35f1ba5 toolsrv/agent: rename ClassifyTool→CanParallelize, ClassifyTier→MemoryTier
Rename throughout: Go methods, interface types, Runtime fields, wire
protocol RPCs, tests, and ollie-remote.

- IsParallelRead / ParallelClassifier → CanParallelize
- ResultTier / ResultTierArgs / TierClassifier → MemoryTier / MemoryTierArgs / MemoryTierClassifier
- Wire: is_parallel_read → can_parallelize, result_tier → memory_tier, result_tier_args → memory_tier_args
2026-08-08 14:29:41 +02:00
Levi Neely e7185afc37 ollie-9p: stream all reads instead of buffering until EOF
cmdRead now opens the file and reads incrementally, writing each chunk
to stdout immediately. This fixes streaming for stream-mode files (chat,
statewait, eventwait) which block per-Tread until data arrives.

The previous io.ReadAll approach buffered internally and never flushed
to stdout because stream files never return EOF.

No separate 'tail' command needed — 'read' just works for both
one-shot files (server returns data then EOF) and stream files
(server blocks between chunks).
2026-08-07 09:13:25 +02:00
Ollie Agent 851ced1286 lib9p: unify 9P client — ollie-9p now imports lib9p/client instead of duplicating it
- Extract shared 9P operations (Dial, Read, Write, Rdwr, Stat, Ls, Create, Remove, Mkdir, Rename, ModeString) into lib9p/client package
- lib9p/lib9p.go (C FFI layer) delegates to lib9p/client for all operations
- cmd/ollie-9p/main.go uses lib9p/client directly, eliminating ~250 lines of duplicated dial/open/write/close boilerplate
- Removed lib9p/go.mod and go.sum (no longer a separate module; lives in main module)
2026-08-07 07:30:22 +02:00
Ollie Agent d80a87eb86 clean up OLLIE_* env vars: replace with XDG conventions
- Remove all OLLIE_*_PATH vars (TOOLS_PATH, CFG_PATH, DATA_PATH, etc.)
  Use XDG_CONFIG_HOME/ollie/* and XDG_DATA_HOME/ollie/* instead
- Replace OLLIE_<TAG>_LOG per-component logging with single OLLIE_LOG={level}
- Replace OLLIE_USAGE_LOG with XDG_DATA_HOME-based path
- Replace OLLIE_OLLAMA_URL with standard OLLAMA_HOST (or omit entirely)
- Rename protocol markers: OLLIE_LISTEN_READY → ListenReady, OLLIE_9P_OPEN → Open
- Remove freeloader hooks from agent configs
- Update sandbox YAMLs to use XDG paths instead of OLLIE_*_PATH tokens
- Update shell tools to use $(dirname "$0") fallback instead of OLLIE_TOOLS_PATH
- Update docs and prompts accordingly
2026-08-07 07:11:53 +02:00
Ollie Agent fc0c368e91 Good idea fairy cleanup: ~960 lines removed
Phase 1:
- agent/hooks.go (entire hooks engine, 237 lines)
- backend/noop.go (unused test backend)
- backend/oneshot.go: Route/RouteRequest/RouteResult + /route 9P file
- cmd/ollie-9p/mount/ (FUSE mount, 336 lines)
- toolsrv/schema.go (ParseToolInfo, zero callers)
- toolsrv/discover.go: ToolPrompt/ReadTool (zero callers)
- agent/commands.go: CompactionSnapshot + history.go: PreCompactionSnapshot
- data/tools/route.meta + justfile route install

Phase 2:
- detach/process.go: stripped Signal(), Cmd field, unused imports
- SignalDetached reimplemented with syscall.Kill directly

24 files changed, 19 insertions, ~980 deletions
2026-08-05 21:51:55 +02:00
Ollie Agent 1372a6b55b Remove OLLIE_ELEVATE_SOCKET from config: derived from XDG_RUNTIME_DIR convention
- Removed from env.go managed list and defaults map
- main.go and shell.go derive path from XDG_RUNTIME_DIR directly
- main.go sets OLLIE_ELEVATE_SOCKET in process env for subprocesses
2026-08-05 19:43:52 +02:00
Levi Neely 593584a673 Move mount/ package to ollie-9p
FUSE mount is a client-side QoL feature, not a server concern.
Usage: ollie-9p mount <address> [mountpoint]
2026-08-04 16:38:44 +02:00
Levi Neely 5678ee723a remove: acme backend (cmd/Ollie)
Replaced by the 'o' command which provides a simpler interface.
2026-08-04 14:04:26 +02:00
Levi Neely 66850e822f cleanup: remove dead code from olliesrv
- Remove unused GroupTable.Remove() method, rename Add to Populate
- Remove unused toolPrompt field from Server struct and Config
- Remove unused ModelCache type alias
- Remove unused toolsrv import
- Flatten if true {} blocks (debugging remnants)
- Convert fcallTypeName switch to map lookup
- Remove unused Tree.Unmount() method

-44 lines
2026-08-04 10:19:12 +02:00
Levi Neely 6d902ba7e9 9p: default log level to warn, not debug
The 9P logger was hardcoded to LevelDebug, causing all 9P operations
to print timing info to stdout. This blocked the server on terminal
output, hurting GUI responsiveness.

Now uses NewLogger('9p') which:
- Defaults to the sink's level (warn)
- Can be overridden with OLLIE_9P_LOG=debug

Also updates kde submodule with incremental session tree updates.
2026-08-03 19:52:07 +02:00
Levi Neely 73de0b3cc0 hierarchical event topics and TCP support
Event topics now follow session hierarchy:
  session.{sid}.new/kill/pause/resume/rename
  session.{sid}.agent.{aid}.new/kill/state

Wildcard routing publishes to all ancestors:
  session.{sid}.agent.{aid}.state publishes to:
    session.{sid}.agent.{aid}.*
    session.{sid}.agent.*
    session.{sid}.*
    session.*
    *

GUI can subscribe to session.{sid}.* to get all events
for one session including its agents.

Also:
- ollie-9p -a flag now supports TCP (host:port or tcp!host:port)
- Add Session.ID() accessor method
2026-08-03 19:10:31 +02:00
Levi Neely ff3f8c8819 fix: ollie-9p write/rdwr propagate clunk errors
The 9P protocol returns write handler errors via Rclunk, not Rwrite.
cmdWrite and cmdRdwr were using defer fid.Close() which discarded the
error. Now they check fid.Close() return value and exit non-zero on
failure, allowing the GUI to detect rename errors.
2026-08-03 18:04:12 +02:00
Levi Neely 256d5177d1 ollie-remote: call env.EnsureDefaults, keep OLLIE_SESSION_ID/OLLIE_UNAME current
- Load ~/.config/ollie/env and set path defaults at startup (same as olliesrv)
- Remove hard exit on missing OLLIE_SESSION_ID; accept it from inherited env
  or via set_env RPC (SSH bootstrap path)
- Wire OnEnvSet to propagate OLLIE_SESSION_ID into tool registry and process
  env when it arrives dynamically; same for OLLIE_UNAME
2026-08-03 11:27:04 +02:00
Levi Neely 8aff88d0a1 ollie-remote: use OLLIE_SESSION_ID for elevate broker identity
ollie-remote was sending 'agent-<pid>' as the session identity to the
elevate broker, which never matches any real session. Now reads
OLLIE_SESSION_ID from inherited environment (set by the parent
olliesrv process) so the broker can validate the session exists.
2026-08-03 11:06:17 +02:00
Levi Neely f83b1f0f89 olliesrv: fix double-fire on Request files opened ORDWR
For Request-mode files (session/new, complete, generate, route), the
write handler fires immediately during Twrite. On clunk, the server
was also flushing the (empty) writeBuf to Write(), causing the handler
to fire a second time. This created duplicate sessions.

Skip the clunk-time writeBuf flush for Request-mode files since they
already handle writes inline during Twrite.
2026-08-03 09:20:49 +02:00
Ollie Agent 60fafd5381 remove tools/builtin/ — zero built-in tools, all tools are external scripts
With the zero-tools transition complete, the tools/builtin/ package
served no purpose — Builtins() returned nil. Removed:

- tools/builtin/builtins.go and the directory
- builtins field, WithBuiltins, Dispatch from toolsrv.Server
- Handler type from toolsrv (only used by builtins)
- OnPreDispatch/WithOnPreDispatch (dead code)
- Strict field and WithStrict (dead code, never read)
- CallTool simplified — no fallback to Dispatch
- builtin import and WithBuiltins/WithStrict calls from ollie-remote
- tools/builtin from justfile build/test targets

Updated AGENTS.md, ARCHITECTURE.md, README.md, EVOLUTION.md
2026-08-03 00:55:22 +02:00
Ollie Agent b2fe5f1b4e connection statuses 2026-08-02 23:35:30 +02:00
Ollie Agent 39ce817f51 Remove hard-coded tool autoloads 2026-08-02 22:33:54 +02:00
Ollie Agent 1f2870dd20 fix rename session and agent 2026-08-02 22:16:22 +02:00
Ollie Agent 9af742acd6 fs/lifecycle: fix nil MkdirAll panic blocking agent creation and autoload
The panic at fs/lifecycle.go:463 was a nil function pointer: fs.Config.MkdirAll
is a func field, not a method, and the struct literal in cmd/olliesrv/main.go
omitted it, defaulting to nil. When CreateAgent called
rs.cfg.MkdirAll(...), it panicked before ever reaching the autoload loop.

- Add MkdirAll: os.MkdirAll to fs.Config in main.go
- Spawn tool server in Create() so empty session/new sessions are
  operational, then reuse it in CreateAgent (else if sess.proc != nil)
- Wrap create agent error with fmt.Errorf for clearer messages
- Add panic stack trace to stderr for debugging
2026-08-02 21:16:12 +02:00
Ollie Agent 8fba664f11 cleanup / unify toolsrv bootstrap 2026-08-02 20:08:45 +02:00
Ollie Agent e25157ffcd multiplex toolsrv, wip zero-tool server 2026-08-02 19:18:39 +02:00
Ollie Agent bb152f401d create: set f.entry after creating files
After Tcreate on a file, the fid is open and should be usable for
read/write without a separate Topen. Set f.entry via root.Open()
after creation so subsequent reads/writes on the same fid work.
2026-08-02 16:23:08 +02:00
Ollie Agent b23785a4d9 Fix directory read: entry not required for dirs
Tree.Open() returns an error for directories (is a directory), so
f.entry stays nil after Topen on a dir. The entry == nil guard in
read() was firing before the isDir branch, breaking directory reads.
Moved the guard after the isDir check — directories use buildDirData
directly and never need entry.
2026-08-02 16:22:13 +02:00
Ollie Agent e1e03e50ae Inline handle into Start; rename Serve→Start, Shutdown→Kill
- handle() is gone — the dispatch + panic recovery is inlined into
  the per-request goroutine in Start(). Panic recovery is lifecycle,
  not protocol handling.
- Serve → Start: accepts a connection and runs the 9P loop
- Shutdown → Kill: stops accepting, cancels sessions, waits for
  goroutines to drain.
- 2 methods remain on *Server: Start, Kill. Server is purely lifecycle.
- All 9P protocol handlers are package-level functions.
2026-08-02 16:18:32 +02:00
Ollie Agent 447156ce13 Extract attach and open from *Server; pass groups and log explicitly
- attach() is now a function taking (*olog.Logger, *GroupTable, ...)
- open() is now a function taking (*fs.Tree, *GroupTable, ...)
- Both captured in the handler map via closures over s.sink, s.groups
- 3 methods remain on *Server: Serve, handle, Shutdown
2026-08-02 16:13:23 +02:00
Ollie Agent 3242f108f9 Store opened file on fid; read/write use f.entry instead of path re-resolution
- Added entry (fs.File) field to fid struct
- open() stores the result of rootTree.Open() on f.entry after
  permission check succeeds
- read() uses f.entry instead of calling root.Open(path[1:]) —
  fids survive renames because the File object references the
  tree entry by pointer, not by path
- write() uses f.entry for RequestRespMode writes — no longer
  needs root parameter at all; it's a pure connState+fid function
2026-08-02 16:11:57 +02:00
Ollie Agent 05e0aba155 Server owns the fid map: validate newfids, GC stale fids
- attach: reject if fc.Fid already in use (was silently overwriting)
- walk: reject if fc.Newfid already in use (both clone and full walk)
- open: validate fid path exists; delete stale fid if path is gone
- stat: validate fid path exists; delete stale fid if path is gone
- wstat: after rename, GC all fids on this connection that reference
  the old path tree (was previously updating paths — now just deletes)

The server fully owns the fid map. The client proposes fid numbers,
the server validates and accepts or rejects. Stale fids (pointing to
renamed/deleted paths) are garbage collected when detected.
2026-08-02 16:08:23 +02:00
Ollie Agent 8601562962 Extract GroupTable from Server; replace permission boolean dance with bitmask OR
- GroupTable is a standalone type with Add/Remove/IsMember, owns its
  own mutex and map. Server now holds groups *GroupTable.
- Removed AddGroup/RemoveGroup/InGroup from *Server (3 fewer methods).
- Permission check in open() now computes effective bits as a mask:
    bits := perm & 7                      // world bits
    if in group { bits |= (perm >> 3) & 7 }  // group bits
    if is owner { bits |= (perm >> 6) & 7 }  // owner bits
    if !hasPermBits(mode, bits) → denied
- No boolean accumulator, no tiered if/else, just bitmask OR.
- 6 remaining Server methods (down from 23).
2026-08-02 15:59:50 +02:00
Ollie Agent 0b4daf016a Replace checkPermBits error-return with hasPermBits bool
- hasPermBits uses a 4-entry mask array indexed by mode&3 to select
  the required permission bits: OREAD→4, OWRITE→2, ORDWR→6, OEXEC→1
- Zero branches, zero error paths — returns bits&mask == mask
- open() uses OR semantics: checks owner, group, world independently;
  any tier granting access is sufficient
- checkPerm removed entirely; permission logic is pure boolean math
2026-08-02 15:55:25 +02:00
Ollie Agent 325ad224be Extract checkPerm to package-level function, resolve perms in open
- checkPerm no longer needs *Server: it takes uid, perm, and inGroup
  directly. The caller (open) resolves uid/gid via fileOwnerGroup,
  perm via makeStat, and group membership via InGroup.
- checkPerm is now a pure function: (uname, mode, uid, perm, inGroup)
  → returns only on permissions, needs nothing from Server state.
- open is the remaining method that resolves these values.

server.go: 10 remaining Server methods.
2026-08-02 15:50:31 +02:00
Ollie Agent 8a13174b4f Extract 9 rootTree-only methods to package-level functions; replace switch with handler map
Converted walk, create, read, write, stat, clunk, remove, makeStat,
and buildDirData from *Server methods to functions taking *fs.Tree
as first parameter. Exactly the same pattern as fileOwnerGroup.

Also:
- Replaced the switch in handle() with a s.handler map, built once
  in New(). All 11 9P message types (Tversion through Tremove) now
  dispatch through the map.
- Extracted flush() as a package-level function (was inlined in switch)
- handle() is now: recover + map lookup. No inline cases, no switch.
- server.go: 802 lines, 10 remaining Server methods (down from 23)
- 20 package-level functions handle the actual protocol logic
2026-08-02 15:44:19 +02:00
Ollie Agent 54403a1ce2 Inline readFile/writeFile; remove unused FileTree alias
- readFile was dead code (defined but never called)
- writeFile was a 7-line helper called only once in clunk;
  inlined as direct s.rootTree.Open + e.Write
- FileTree type alias now unused after both deletions
2026-08-02 15:33:06 +02:00
Ollie Agent 082ba1c511 fileOwnerGroup: convert from method to package-level function
fileOwnerGroup only needed s.rootTree, not the full *Server. Making
it a function taking (*fs.Tree, string) removes one more method from
Server, makes the dependency explicit, and makes it unit-testable.
2026-08-02 15:31:33 +02:00
Ollie Agent 3279725128 Inline three thin wrapper methods in server.go
- openEntry (one-liner delegating to rootTree.Open): inlined into
  the two call sites in read() and write()
- statPath (one-liner delegating to rootTree.Stat): inlined into
  three call sites (fileOwnerGroup, walk, makeStat)
- InterruptAll (one-liner delegating to fs.InterruptAll): deleted,
  it was dead code with no callers anywhere

Also cleaned up: removed unused File type alias and unused 'os' import.

server.go: 825 -> 810 lines. Server method count drops by 3, but more
importantly, zero forwarding boilerplate remains.
2026-08-02 15:27:50 +02:00