OKLMdocumentation v1.0.3
On this page

Process & Services Spec: Background Processes, Monitor, LSP and Service Integrations

Status: specification; implementation to do (roadmap M11), after the agent specification's milestones it builds on.

Instructions for Claude Code: This spec extends AGENT_SPEC.md. Read both before starting. It covers everything the agent needs to start, watch and manage long-running things: background shells, Monitor, PowerShell, language servers, MCP server processes, background subagents, hooks, and integrations for Docker, Kubernetes, Android and iOS emulators, VMs, dev servers, databases, browsers, cloud CLIs and tunnels.

Rule #1: audit before you build. Same rule as AGENT_SPEC.md §0A.

  1. Phase 0: search the repo for everything in this spec. Look for:

    • process spawning, background jobs, PID handling, signal handling, log capture
    • port checks, LSP or JSON-RPC clients, Docker or adb calls
    • anything already built for AGENT_SPEC.md §5.8–5.9, §12, §15, §16 and §22

    Append the results to docs/gap-analysis.md under a new "Processes & Services" heading, using the same ✅/🟡/❌/⚠️ table with file:line evidence.

  2. Write docs/process-design.md. It should map each section below to an existing module, or say where new code goes.

  3. Stop and show me both. Ask only what you can't infer.

  4. Implement milestone by milestone (§17), only ❌ and 🟡 items. Re-search at the start of each milestone. Test everything. Show evidence and wait for my go-ahead between milestones.

  5. One process manager. Background Bash, Monitor, LSP servers, stdio MCP servers, services, emulators and VMs all go through the same ProcessManager (§2). Never add a second spawning or tracking mechanism.

Fill in before starting:

  • Platforms to support: Linux and Windows (the MinGW build, tested under Wine). macOS is not a target (adr/0011-sandbox.md), so §10.4 (iOS Simulator) and the macOS column of §15 are out of scope until that changes.
  • Model has vision (screenshots from emulators/browsers): the engine yes, the agent not yet. SmolVLM reads images through oklm describe (multimodal.md), but the agent's messages are text only: screenshots need the image content blocks of the agent specification (§3, its milestone M9 or earlier) first.
  • Integrations to prioritize: to decide before P9 (proposed: Docker/Podman, dev servers, databases, then Android; Kubernetes, VMs, cloud CLIs and tunnels as needed).
  • Allowed to install dependencies such as language servers or Playwright: ask (the default until decided otherwise: nothing is installed without a question, and a missing tool is reported with the command that would install it).

Before starting (OKLM)

What this spec needs settled or built before its P0 can start, and how its names map onto OKLM's.

Names. This spec was written for a generic agent; in OKLM:

The spec says OKLM
AGENT_SPEC.md agent_skill_chat_spec.md (roadmap M10)
the agent binary oklm agent
.agent/ (project), ~/.agent/ (user) .oklm/ and ~/.config/oklm/ ($XDG_CONFIG_HOME, %APPDATA% on Windows), as settings and skills already are
~/.agent/processes/<session>.json the session's job journal, .oklm/jobs/<session>.jsonl (ADR-0012)
AGENT_SESSION_ID, AGENT_PROCESS_ID OKLM_SESSION_ID, OKLM_PROCESS_ID
Docker label agent.session=<id> oklm.session=<id>
.agent/services.json .oklm/services.json
/tasks, /bashes /jobs today (an alias to add)

The one process manager is the job manager. OKLM already has it: include/oklm/harness/jobs.h, src/harness/jobs.c, decided in adr/0012-jobs.md. Jobs run in their own process group (a kill-on-close Job Object on Windows), write their output to .oklm/jobs/<session>/<id>.log, are journalled with their process start times, stopped at a normal exit, and re-attached or reported as orphans after a crash. The ProcessManager of §2 is that module extended (kinds, labels, readiness, ports, readers, restart policy), not a second one; the Bash background mode, JobOutput and JobKill are its current tools, and the sandbox (adr/0011-sandbox.md) already confines what it starts. P0 audits it against §2 first.

Prerequisites in the agent specification. Several sections are deltas to it, so these come first:

  • its M0 audit (docs/gap-analysis.md, docs/agent-design.md), to which P0 appends a "Processes & Services" section;
  • its §7 settings beyond permissions (for §12 here: autoReapOrphans, wakeOnEvents, limits, retention);
  • its §11 sessions and --resume (for §2.7 here: re-attaching on resume);
  • its §5.18 ToolSearch (deferred tools, for §3 and §18 here);
  • its §15 hooks (for §8 here) and §16 MCP (for §6 here);
  • its §12 sub-agent definitions (for §7 here; background sub-agents already exist).

Owned elsewhere, not built twice. The /tasks command and its menu are built by the commands framework (commands_spec.md), showing this spec's process list; the JSON-RPC module is shared between the language servers here (Content-Length framing) and MCP (newline-delimited, agent specification §16). The notifications, the status line and the dangerous-pattern list are the agent specification's (§19, §6.4): this spec adds triggers, fields and entries. This spec owns background processes, Monitor, the event bus, scheduled wakeups, the command environment (§2.2) and the processes of MCP servers and sub-agents (§6, §7); the full map is agent-specs.md.

P1 to P5 can start once its M1 to M8 are done; P6 (LSP) needs only P1; P7 waits for its M11 (hooks) and M15 (MCP).

Decisions to take at P0 (each an ADR or an amendment of ADR-0012): the readiness probe set and its defaults (§2.4); log rotation and retention next to ADR-0012's 30 days; whether a foreground command that times out is backgrounded (§3) instead of killed, as Bash does now; the event bus's injection points in the agent loop (§4.2), which the agent's job-ended notes already use; how language servers are found and whether OKLM ships a JSON-RPC client of its own (§5, reused by MCP in §6).


0. Principles

  • Nothing the agent starts outlives the session by accident. Every process is tracked, labeled, and cleaned up, including after a crash of the agent itself.
  • Waiting is event-driven. Readiness probes and Monitor events replace sleep loops.
  • Logs are files, context is precious. Full output goes to disk. Only filtered or recent lines reach the model.
  • Destructive or exposing actions always ask: deleting clusters or volumes, terraform apply, public tunnels, touching non-local contexts.
  • Integrations are knowledge, not code, where possible. Most service support is a skill (recipe + scripts) that drives the generic process tools. Write dedicated code only where a skill can't do the job reliably.

1. Audit checklist (Phase 0)

Area What to search for
Spawning spawn, exec, Popen, fork, child_process, std::process, setsid, CREATE_NEW_PROCESS_GROUP
Tracking PID maps, pidfiles, job tables, /tasks//bashes-style listings
Signals / cleanup SIGTERM/SIGKILL handling, atexit, shutdown hooks, kill-tree code
Output ring buffers, log files, tail/follow code, ANSI stripping
Readiness port polling, HTTP health checks, "wait for" helpers
Event injection anything that pushes messages into the conversation between turns
LSP / JSON-RPC initialize, textDocument/, Content-Length: framing
Integrations docker, compose, kubectl, adb, emulator, simctl, qemu, vagrant, playwright, ngrok
Windows Job Objects, PowerShell invocation, taskkill /T

2. ProcessManager (core)

2.1 Data model

ManagedProcess {
  id: "bg_7f3a"                   // short, model-facing
  kind: shell | monitor | lsp | mcp | service | emulator | vm | agent
  label: "vite dev server"
  command, args, cwd, env (secrets masked in display)
  pid, pgid (Unix) | jobHandle (Windows)
  owner: { sessionId, agentId? }  // subagents own their own processes
  status: starting | ready | running | exited | failed | killed | orphaned
  startedAt, readyAt?, exitedAt?, exitCode?, signal?
  ports: [int]                    // declared or detected listening ports
  readiness?: Probe               // §2.4
  restart: never | on-failure(max N, backoff)
  logPath                         // full output on disk
  ring: last N lines (e.g. 2000)  // fast access
  readers: { readerId -> offset } // so "new output since last read" works per reader
  resources?: { cpuLimit, memLimit } // optional, cgroups on Linux
}

2.2 Spawning

  • Unix: start each process in its own process group or session (setsid), so the whole tree can be signalled.
  • Windows: assign the process to a Job Object with kill-on-close, so the tree dies with it.
  • stdin is closed by default. stdout and stderr are merged into the log file with timestamps.
  • Add environment markers: AGENT_SESSION_ID, AGENT_PROCESS_ID. They make orphan detection and labeling possible.
  • This section owns the environment of every command (Bash, background jobs, hooks, services): besides the markers, it neutralizes editors, pagers and prompts so nothing can hang waiting for input: GIT_EDITOR=true, GIT_SEQUENCE_EDITOR=true, GIT_PAGER=cat, PAGER=cat, GIT_TERMINAL_PROMPT=0 (from git_spec.md §2.4 and agent_skill_chat_spec.md §5.8).
  • Enforce a configurable concurrency limit (e.g. 20). Over the limit, return an instructional error listing what's running.

2.3 Output

  • Strip ANSI codes for the model and keep them for display.
  • read(id, readerId, sinceOffset?, filter?: regex, tail?: n) returns new lines with a byte cap. It says how many lines were skipped and where the full log is.
  • Rotate logs over a size cap. Keep them for logRetentionDays.

2.4 Readiness probes

Probe = port(n, host=127.0.0.1)
      | http(url, expectStatus=2xx|3xx)
      | log(regex)                       // e.g. /ready in \d+ms|Listening on/
      | command(cmd, expectExit=0)       // e.g. pg_isready, adb shell getprop sys.boot_completed
      | delay(ms)
      | all([...]) | any([...])
with timeout (default 120 s), interval, and failFast if the process exits first

The result says how long readiness took, or why it failed, with the last 30 log lines attached.

2.5 Stopping and cleanup

  • stop(id, graceMs=5000): SIGTERM (or a CTRL_BREAK/taskkill /T equivalent) to the group, wait for the grace period, then SIGKILL the tree, then confirm everything is gone.
  • Integration-specific stop hooks run before signals, e.g. docker compose down, adb emu kill, xcrun simctl shutdown, vagrant halt, kind delete cluster (asks first, §11).
  • Session end: stop everything owned by the session, in reverse start order. --keep-services and per-process keepAlive opt out, and a notice is shown.
  • Crash safety: keep a registry file ~/.agent/processes/<session>.json with PIDs, start times and commands. On startup, the orphan reaper finds entries whose session is dead. It verifies each PID still belongs to the same process (start time plus command), lists them, and offers to kill them, or kills them automatically if autoReapOrphans is set.
  • Docker resources started by the agent carry the label agent.session=<id>, so they can be found and cleaned up even if the registry is lost.

2.6 Port management

  • Before starting something with a declared port, check whether the port is free. If it isn't, report who holds it (lsof/ss/netstat) and suggest an alternative.
  • Detect newly opened listening ports from the process tree (Linux /proc/net, lsof elsewhere) and record them.
  • Bind to 127.0.0.1 by default where the tool allows it.

2.7 Persistence across resume

  • When a session is resumed, re-attach to its still-running processes from the registry and re-open their logs.
  • Processes that died while the agent was away are shown as exited with their exit codes.

3. Model-facing tools

Keep the set small. Everything maps onto the ProcessManager.

Tool Purpose Notes
Bash (extended) run_in_background: true returns {id, logPath} immediately. Auto-background on timeout: a foreground command that hits its timeout is moved to the background instead of killed, and the model is told its id. Never auto-background commands starting with sleep. Ctrl+B in the TUI backgrounds the running command
PowerShell Same contract as Bash on Windows (pwsh 7+, falling back to 5.1). Optional on other platforms if pwsh is on PATH. Shares permission semantics with Bash
ProcessOutput New output since this reader's last read, with filter and tail Replaces BashOutput/TaskOutput
ProcessStop Stop one or more ids, with optional grace Runs integration stop hooks
ProcessList Id, kind, label, status, uptime, ports, last line Same data as /tasks
WaitFor Block until a probe (§2.4) passes on an id or globally, with a timeout The model uses this instead of sleep
Monitor §4
LSP §5
Service (optional, later) start/stop/status <name> for services declared in .agent/services.json (§9) Thin wrapper; deferred via ToolSearch

Instructional errors are required. Examples: "id bg_12 already exited with code 1; last lines: …", "port 5173 is in use by node (pid 4411, started by you as bg_3)".


4. Monitor tool and the event bus

4.1 Monitor

  • Inputs: command (a watch script or tail -F-style command), description, filter? (regex: only matching lines become events), batchMs (default 1000), maxEventsPerMinute (default 30), stopWhen? (regex or probe), timeout?.
  • Runs as a kind: monitor ManagedProcess. Each output line that passes the filter becomes an event.
  • The agent can also attach a monitor to an existing process: Monitor({attachTo: "bg_3", filter: "ERROR|WARN"}).
  • Uses the same permission rules as Bash.
  • The model stops a monitor with ProcessStop, and the user can stop it from /tasks.

4.2 Event bus into the agent loop

  • Event sources:
    • Monitor lines
    • background process exit or crash
    • readiness reached or failed
    • background subagent finished
    • LSP diagnostics (§5.3)
    • MCP server crash
    • scheduled wakeups (§4.3)
  • Events are queued per session. Bursts are coalesced, e.g. "12 new lines from monitor m_2 (showing last 5)".
  • Delivery:
    • While the agent is working: inject events as isMeta system reminders at the next safe point, between tool calls.
    • While the agent is idle in the REPL: wake it with a synthetic turn ("Background event: …"), unless wakeOnEvents=false. Show it distinctly in the UI so the user knows why the agent started talking.
    • Headless mode: events are emitted as stream-json lines. The run ends only when the model is done and no attached monitors are pending, or --max-turns or a timeout is hit.
  • Loop safety: cap on wakeups per hour, and a "you've been woken N times by the same monitor; consider stopping it" reminder.

4.3 Scheduled wakeups (optional)

  • ScheduleWakeup(delay | at, message) re-invokes the agent in this session later, e.g. "check whether the build finished in 10 minutes".
  • Listed in /tasks. Cancelled at session end unless persisted.

5. LSP (code intelligence)

5.1 Server management

  • A config map from language to server command:
    "lsp": { "python": {"command": ["pyright-langserver", "--stdio"], "extensions": [".py"]},
             "typescript": {"command": ["typescript-language-server", "--stdio"], "extensions": [".ts", ".tsx", ".js"]},
             "rust": {"command": ["rust-analyzer"], "extensions": [".rs"]},
             "go": {"command": ["gopls"], "extensions": [".go"]},
             "c/c++": {"command": ["clangd"], "extensions": [".c", ".cc", ".cpp", ".h"]} }
  • Servers start lazily, the first time a file of that language is read or edited. They run as kind: lsp ManagedProcesses with restart on failure.
  • If a server's binary is missing, say so once and suggest the install command (asking first if installs need approval). Never block the agent.
  • Protocol: JSON-RPC with Content-Length framing, then initialize with rootUri and capabilities, then initialized. Shut down cleanly with shutdown and exit.

5.2 Document sync

  • Read sends didOpen. Edit, Write and MultiEdit send didChange (full sync is fine) and didSave.
  • Files changed on disk outside the agent are re-synced when they're next touched.

5.3 Diagnostics after edits

  • After every successful edit, wait briefly (e.g. up to 1.5 s, configurable) for publishDiagnostics.
  • Append only new errors and warnings in the edited file to the edit tool's result, capped at 10 lines: LSP: 2 new errors: src/a.ts:14:5 Property 'x' does not exist on type 'Foo'.
  • Pre-existing diagnostics aren't repeated. Diagnostics in other files arrive as events (§4.2) only if they're new and caused by this edit.

5.4 LSP tool

  • Operations:
    • definition, references, hover (type info), documentSymbols, workspaceSymbols, implementation
    • callHierarchy (incoming and outgoing), diagnostics (file or workspace), rename (preview only; applying it goes through Edit with permissions)
  • Input: operation, file_path, line, character (1-based for the model, converted to 0-based internally), query?.
  • Output: compact path:line:col lists with one line of context each, capped.
  • Read-only operations need no permission.

6. MCP server processes (delta to AGENT_SPEC §16)

  • stdio MCP servers are kind: mcp ManagedProcesses: same spawning, logs, kill-tree, orphan reaping and restart-with-backoff.
  • /mcp and /tasks show the same underlying state, never two different truths.
  • A server crash emits an event (§4.2), and its tools return "server restarting" errors until it's back.

7. Background subagents (delta to AGENT_SPEC §12)

  • Background subagents appear in /tasks as kind: agent, with status, elapsed time, token use and the last tool called.
  • Processes a subagent starts are owned by it. When it finishes, its processes are stopped unless it hands them to the parent explicitly (keepAlive plus a mention in its final message).

8. Hooks for services (delta to AGENT_SPEC §15)

  • SessionStart hooks can start services, e.g. docker compose up -d. They run through the ProcessManager so they're tracked.
  • SessionEnd hooks run before the automatic cleanup.
  • New events:
    • ProcessStart and ProcessExit: payload includes id, kind, command and exit code
    • ServiceReady
    • MonitorEvent: can be filtered or blocked by the hook before reaching the model

9. Declarative services (.agent/services.json)

A minimal, compose-like file so a project can describe its dev stack once:

{ "services": {
    "db":   { "command": "docker compose up db", "stop": "docker compose stop db",
              "readiness": {"command": "pg_isready -h 127.0.0.1 -p 5432"}, "autostart": false },
    "api":  { "command": "npm run dev:api", "cwd": "api", "dependsOn": ["db"],
              "ports": [3000], "readiness": {"http": "http://127.0.0.1:3000/health"} },
    "web":  { "command": "npm run dev", "cwd": "web", "dependsOn": ["api"],
              "ports": [5173], "readiness": {"log": "ready in \\d+"}, "monitor": "error|failed" } } }
  • Starting a service brings up its dependsOn chain in order and waits for each readiness probe.
  • A monitor regex auto-attaches a filtered Monitor.
  • /services lists, starts, stops and restarts services, and opens their logs.
  • /init (AGENT_SPEC §8.6) may propose a services.json after detecting package.json scripts, compose files, Procfiles or Makefiles.
  • Project services.json requires folder trust before anything autostarts.

10. Integrations

Each integration is delivered as:

  • a skill under skills/<name>/, with SKILL.md recipes, helper scripts and gotchas
  • dangerous-pattern rules and stop hooks registered in code
  • an optional detection step used by /doctor and /init

Recommended MCP servers are listed as optional upgrades, never requirements. For each integration, implement and test: detect → start → readiness → observe (logs/screenshots) → interact → stop → cleanup.

10.1 Containers (Docker / Podman)

  • Detect: docker info / podman info, plus compose v2 availability.
  • Start: use docker compose -p agent-<session> up -d --wait where possible. Add the agent.session label. For docker run, use --rm --label agent.session=<id> and publish to 127.0.0.1: only.
  • Readiness: container health status (docker inspect), or §2.4 probes.
  • Observe: docker compose logs -f --since via Monitor, with a filter. docker stats --no-stream for resources.
  • Interact: docker exec (non-interactive only, no -it).
  • Stop/cleanup: compose down for the agent's project. Volumes are removed only after asking. Clean up anything left with the label.
  • Always ask: system prune, volume rm, rmi, --privileged, mounting / or the Docker socket, --network host.

10.2 Kubernetes (kind / minikube / k3d)

  • Context safety (critical): read the current context at start. If it isn't a local cluster created by the agent or on an allowlist (kind-*, minikube, k3d-*, docker-desktop), every kubectl/helm call asks, and the prompt shows the context name prominently. Prefer an explicit --context.
  • Start: kind create cluster --name agent-<session>, or equivalents. Wait for nodes to be Ready.
  • Readiness: kubectl rollout status, kubectl wait --for=condition=Ready.
  • Observe: kubectl logs -f and get events -w via Monitor.
  • Interact: kubectl port-forward runs as a managed process with port readiness. tilt up / skaffold dev run as monitored processes.
  • Cleanup: delete agent-created clusters only after asking (they can be slow to recreate).

10.3 Android emulator

  • Detect: emulator -list-avds, adb version, ANDROID_HOME, and KVM/HVF acceleration (warn if missing).
  • Start: emulator -avd <name> -no-window -no-audio -no-snapshot-save -port <free even port> as kind: emulator. The window is optional when the user wants to watch.
  • Readiness: adb -s emulator-<port> wait-for-device, then poll getprop sys.boot_completed = 1, plus an optional unlock of the screen.
  • Observe:
    • adb logcat via Monitor, filtered by package or tag
    • screenshots via adb exec-out screencap -p > file.png, which the model reads with Read if it has vision
    • the UI tree via uiautomator dump for text-only models
  • Interact: adb install -r, am start, input tap/text/swipe/keyevent, pm clear.
  • Stop: adb -s … emu kill, then the process-tree fallback.
  • Always target devices with -s, never the default device, because a physical phone may be attached. Commands that touch physical devices always ask.

10.4 iOS Simulator (macOS only)

  • Detect: xcrun simctl list devices available -j.
  • Start: xcrun simctl boot <udid>, then readiness with xcrun simctl bootstatus <udid> -b. Opening Simulator.app is optional.
  • Observe: xcrun simctl io <udid> screenshot file.png, and xcrun simctl spawn <udid> log stream --predicate … via Monitor.
  • Interact: simctl install, launch, terminate, openurl, privacy grant, push. Use xcodebuild … -destination 'id=<udid>' for builds and tests (long-running, so backgrounded).
  • Stop: xcrun simctl shutdown <udid>. Never erase without asking.

10.5 Virtual machines (QEMU / Vagrant / Multipass / Lima)

  • QEMU:
    • run with -pidfile, -display none, and a -qmp unix: socket for control (powerdown, status)
    • SSH readiness via port forward
    • serial console log via Monitor
  • Vagrant: vagrant up is backgrounded and monitored. Readiness is vagrant ssh -c true. Stop is vagrant halt, and destroy asks.
  • Multipass / Lima: launch/start, exec, stop. delete asks.
  • Watch resource use, because VMs are heavy. Warn when starting more than one.

10.6 Dev servers and watchers

  • Detect from package.json scripts (dev, start, watch), Procfile, Makefile, cargo watch, air, uvicorn --reload, rails s, etc.
  • Start in the background. Readiness by declared or detected port, or a log regex (e.g. Vite's ready in).
  • Monitor for compile errors and HMR failures, using a sensible default filter per framework.
  • Prevent duplicates: if the same command is already running in this cwd, reuse it instead of starting a second copy.

10.7 Databases and local services

  • Prefer containers (§10.1). Native binaries are a fallback.
  • Readiness: pg_isready, mysqladmin ping, redis-cli ping, mongosh --eval 'db.runCommand({ping:1})', LocalStack /_localstack/health.
  • Use ephemeral data by default (tmpfs or a temp volume). Persistent volumes need explicit config.
  • Always ask: DROP, TRUNCATE, or DELETE without WHERE against non-ephemeral databases, and any connection string that isn't localhost.

10.8 Browsers and UI testing

  • Playwright (preferred) or Puppeteer: detect or install the browsers (asking first). Run headless by default.
  • A helper script in the skill:
    • browse.py open <url> --screenshot out.png --text
    • returns the page title, visible text summary and console errors
    • the screenshot goes to the model via Read if it has vision
  • Test runners (playwright test, cypress run) run in the background with Monitor on failures. Trace and video artifact paths are reported.
  • Optional: the Playwright MCP server for interactive multi-step browsing.
  • Only localhost URLs are allowed by default. Other domains follow WebFetch domain rules.

10.9 Cloud and infrastructure CLIs (aws, gcloud, az, terraform, pulumi)

  • Read-only by default: describe, list, get, terraform plan and pulumi preview can be allowed by rules.
  • Always ask, showing the account, project, subscription or workspace in the prompt:
    • apply, destroy, delete, create
    • pulumi up, terraform import
    • IAM changes
  • Show the active identity (aws sts get-caller-identity, gcloud config list, az account show) once per session in a system reminder.
  • Redact credentials in output and logs. Never print env vars that look like secrets.

10.10 Tunnels and networking (ngrok, cloudflared, ssh -L/-R)

  • Always ask. A tunnel exposes local ports to the internet or to other machines.
  • Run as a managed process. Parse and show the public URL. Auto-stop at session end (keepAlive isn't allowed for public tunnels unless set in settings).
  • ssh -L port forwards are allowed by rule for known hosts. -R (remote) always asks.

11. Permissions and safety (additions to AGENT_SPEC §6)

  • Rule examples:
    • Bash(docker compose up:*), Bash(kubectl --context kind-*:*)
    • Bash(adb -s emulator-*:*), Bash(xcrun simctl:*)
    • Monitor(tail -F *)
    • Service(web), ProcessStop(*)
  • Additions to the dangerous-pattern list:
    • docker system prune, docker volume rm, docker run --privileged, -v /:/, -v /var/run/docker.sock
    • kubectl delete (non-agent context), helm uninstall
    • kind/minikube delete, vagrant destroy, multipass delete, simctl erase, adb … uninstall on non-emulator devices
    • terraform apply/destroy, pulumi up/destroy, cloud delete
    • ngrok, cloudflared tunnel, ssh -R
  • The permission prompt shows the target: the Kubernetes context, cloud account, device serial or Docker host.
  • Resource guardrails: warn before more than one VM or emulator, more than N containers, or a memory limit. Optional cgroup limits on Linux.
  • Background processes inherit the sandbox (AGENT_SPEC §6.5) when it's enabled. Network-exposing integrations need explicit sandbox exceptions.

12. Configuration (additions to AGENT_SPEC §7)

processes.maxConcurrent, processes.defaultGraceMs, processes.logRetentionDays, processes.autoReapOrphans, processes.autoBackgroundOnTimeout, processes.keepOnExit (default false), events.wakeOnEvents, events.maxWakeupsPerHour, monitor.defaultBatchMs, lsp.* (§5.1), lsp.diagnosticsWaitMs, integrations.<name>.enabled, kubernetes.allowedContexts, cloud.readOnly (default true).

Env vars: AGENT_DISABLE_BACKGROUND_TASKS, AGENT_BASH_MAX_OUTPUT, ANDROID_HOME, DOCKER_HOST (respected).


13. UI (additions to AGENT_SPEC §19)

  • /tasks is one panel for everything: shells, monitors, LSP and MCP servers, services, emulators, VMs and subagents. It shows kind, label, status, uptime, ports, CPU/memory (optional) and the last log line. Actions: view log, follow, stop, restart, copy id.
  • Status line: counts, e.g. ⚙ 3 running · 1 failed, as a field of the agent specification's status line (its §19). Failures are highlighted.
  • Ctrl+B: §3.
  • Notifications: a crash, a readiness failure, or a background agent finishing are triggers of the agent specification's notifications (its §19).
  • Exit prompt: "3 processes still running (web, api, emulator-5554). Stop them? [Y/n/keep]".

14. Headless and SDK (additions to AGENT_SPEC §20)

  • stream-json events: process_started, process_ready, process_exited, monitor_event.
  • At exit, everything is cleaned up unless --keep-services is passed. The exit code isn't affected by cleanup, but cleanup failures are reported in the result object.
  • SDK: onEvent callback, processManager access for embedding apps.

15. Platform matrix

Concern Linux macOS Windows
Process tree kill setsid + kill group same Job Objects / taskkill /T /F
Listening-port detection /proc/net/tcp, ss lsof -iTCP -sTCP:LISTEN netstat -ano / Get-NetTCPConnection
Shell tool Bash Bash/zsh PowerShell (+ Git Bash)
iOS Simulator ✗ ✓ ✗
Resource limits cgroups v2 — Job Object limits
Android acceleration KVM HVF WHPX/HAXM

Unsupported features say so clearly rather than failing obscurely.


16. Testing

  • Fake process fixtures: a small script with flags to:
    • print N lines at an interval
    • open a port after a delay
    • log "ready"
    • crash with an exit code
    • ignore SIGTERM
    • spawn grandchildren
    • flood output
    • write to stderr
  • Unit/integration tests:
    • spawning and kill-tree (grandchildren must die)
    • every probe type and timeout, including fail-fast on exit
    • auto-background on timeout, and per-reader offsets
    • log rotation, port conflict detection, concurrency limit
    • Monitor filtering, batching and rate limits
    • event delivery mid-turn and on idle wake
    • the wakeup cap
  • Crash safety: kill -9 the agent with 3 children running. Restart it. The orphan reaper must find and offer to kill exactly those 3, and not a reused PID.
  • Resume: reattach to a still-running process and read new output.
  • LSP: a fake LSP server fixture (scripted JSON-RPC) for unit tests, plus one real server (e.g. pyright) in an integration test. Check that an edit introducing a type error gets a diagnostics line in the edit result.
  • Integrations (behind flags, skipped when the tool isn't installed):
    • Docker: start nginx with a label, check readiness, read logs, clean up, and verify no labeled containers remain
    • kind: create, deploy, port-forward, delete
    • Android and iOS: manual or CI-on-capable-runner checklist, i.e. boot, install sample app, screenshot, logcat, shutdown
    • Playwright: open a local page and capture a screenshot and console errors
  • Mock-model E2E: a scripted session that starts web from services.json, waits for readiness, attaches a monitor, receives an error event, edits the file, sees the error clear, and exits with cleanup.
  • Real-model evals:
    • "start the dev server and tell me the URL"
    • "the app logs an error on startup; find and fix it"
    • "run the e2e tests and fix the failing one"

17. Milestones

Every milestone follows the same steps:

  1. Re-search the code.
  2. Update the gap analysis.
  3. Implement only ❌/🟡 items.
  4. Test.
  5. Show evidence.
  6. Report what was reused, extended and new.
# Milestone Done when
P0 Audit + docs/process-design.md Gap table covers §2–§16 with evidence; ⚠️ items reviewed with me
P1 ProcessManager core: spawn, groups/jobs, logs, ring buffer, readers, stop/kill-tree, registry Grandchild-kill and log tests green on all target platforms
P2 Readiness probes + port management + WaitFor All probe tests green; port-conflict message names the holder
P3 Bash background + auto-background + Ctrl+B, ProcessOutput/Stop/List, PowerShell tool, /tasks Agent starts a dev server, gets its URL, reads only new output; Windows parity checked
P4 Orphan reaper + resume reattach + session-end cleanup + exit prompt Kill -9 test passes; nothing left running after normal exit
P5 Event bus + Monitor + idle wake + rate limits (+ optional ScheduleWakeup) Monitor error event wakes idle agent once; bursts coalesced
P6 LSP manager, sync, diagnostics-after-edit, LSP tool Edit introducing a type error gets a diagnostics line; definition/references work
P7 MCP and subagent processes moved onto ProcessManager; hook events /mcp and /tasks agree; MCP crash restarts with an event; ProcessExit hook fires
P8 services.json, dependsOn ordering, /services, /init proposal Mock-model E2E (§16) passes
P9 Integrations wave 1: Docker/Podman, dev servers, databases, Playwright Their integration tests pass; labeled cleanup verified
P10 Integrations wave 2: Kubernetes (with context safety), Android, iOS Context-safety tests pass; emulator/simulator checklist done
P11 Integrations wave 3: VMs, cloud CLIs (read-only default), tunnels Dangerous-pattern tests pass; tunnel prompt shows exposure
P12 Safety pass, resource guardrails, /doctor checks, docs (docs/processes.md), evals Eval report generated; docs cover every tool and integration

Priority if time is short:

  • P1–P5 give robust background work (the biggest day-to-day gain).
  • P6 adds code intelligence.
  • P8–P9 cover most web and backend projects.
  • P10–P11 come as needed.

18. Notes for local models

  • Always loaded: Bash (with background), ProcessOutput, ProcessStop, WaitFor. Defer Monitor, LSP, ProcessList, Service and PowerShell via ToolSearch unless they're used often.
  • Integration knowledge lives in skills, so it costs no tokens until it's needed.
  • Teach the model, with one worked example in the system prompt: start in background → WaitFor readiness → read output → act. Never sleep.
  • Keep event reminders short and structured, e.g. [event] bg_3 (web) exited code=1 · last: "Error: Cannot find module './x'".
  • If the model keeps forgetting running processes, add a compact "Running: web(5173), db(5432)" line to each system reminder.