Dogfooding the local dispatch loop (drive orangecat from FleetCrown) dead-ends
immediately: the documented way to boot the engine references files deleted in
a3f470d. That commit retired the standalone Brain (home/server.ts, :3001) and
its scripts/home-start.sh launcher — Fleet Runner desktop is now the sole local
executor — but explicitly deferred the doc cleanup to a "Session 4c" that never
happened. So a reader following the docs runs commands for files that don't
exist.
home/README.md:
- Title/intro/diagram no longer present the 3-process Brain stack as current;
they describe the 2 remaining pieces (watcher + worker) + Fleet Runner.
- "## Run": drop `bash scripts/home-start.sh` and `npx tsx home/server.ts`;
document the real per-piece `--start` iteration path.
- Smoke-test sections: replace dead `POST :3001/api/dispatch|/api/cancel` with
the verified current path — appending bridge.dispatch / bridge.cancel events
straight to ~/.<slug>/events.jsonl (the worker's actual contract).
- Files table: drop the deleted server.ts row; add the real state.ts / log.ts.
- Testing note: server.ts HTTP testing claim removed.
CLAUDE.md: home/ stack description + Dev Commands updated to match (Fleet
Runner is the executor; no home-start.sh).
Docs-only; every remaining server.ts/home-start mention is explicitly historical.
Session 4 of killing-the-bash-daemon plan, commit A — removes every
TS reference that pointed at the bash daemon, the bash bridge, or the
standalone home/server.ts. Bash file deletion (commit B) follows.
DELETED:
home/server.ts (790 LoC)
The standalone Brain HTTP server at 127.0.0.1:3001. Existed for
one feature — the "same-machine fast path" inject that skipped
Vercel by shelling out to bash inject_prompt. Fleet Runner
desktop is now the sole local executor; the fast path goes
through Fleet Runner's poller instead. The Brain's library
pieces (home/watcher.ts, home/decide.ts, home/render.ts, home/
state.ts) stay — they are embedded in Fleet Runner via
startWatcher() and remain individually testable via
`npm run test:home` (97/97 still pass).
scripts/home-start.sh (74 LoC)
Launcher for the deleted Brain server. Nothing to launch.
src/app/api/system/daemon/route.ts (103 LoC)
POST/GET that controlled the fleetcrown-daemon.service systemd
unit. The unit was disabled in Session 1; the route's
raison-d'être is gone.
src/components/control/DaemonControls.tsx (102 LoC)
UI for the deleted /api/system/daemon route. Showed start/
restart/stop buttons that called into the bash daemon. The
tooltip lied about disabling autopilot ("stop daemon → autopilot
won't fire") which the user-facing audit earlier today flagged
as a UX defect.
REWRITTEN:
src/app/api/agent/daemon/route.ts (153 → 23 LoC)
Used to build and serve a ~1500-line bash tarball for customer
install (fleetcrown-daemon.sh + agent-hook-bridge.sh +
agent-hook-lib.sh + Python beacon stack). Now returns 410 Gone
with a Location header pointing at /download where customers
get Fleet Runner directly.
src/app/api/system/doctor/route.ts
Removed the beacon-window and bash-daemon systemd unit probes.
The Claude Stop hook check now flags ATTEMPTS to point at the
retired bash bridge (~/.local/share/fleetcrown-beacon/
agent-hook-bridge.sh) as failures — a hook that exec's a
deleted path is broken, not a feature.
src/components/control/DaemonStatusBanner.tsx
Removed the embedded DaemonControls. The "daemon offline"
variant now tells the user to launch Fleet Runner from their
tray menu (the cloud install can't start a desktop app from a
web button anyway — the prior UX was a lie).
src/hooks/use-control-data.ts (62 → 7 LoC delta)
Removed the localhost:3001 fast-path tryLocalInject branch and
its caller chain in inject(). Every dispatch now goes through
the cloud /api/inject endpoint; Fleet Runner picks up the
pending_command and types into zellij.
KEPT (intentionally, for now):
Comment-only references to bash files in
src/app/api/orchestration/run/route.ts
src/db/schema/pending-commands.ts
src/config/prompt-library.ts
home/{watcher,worker,projects}.ts
desktop/src/main/{dispatch,poller}.ts
These are historical context; sweeping them is a doc cleanup that
belongs in Session 4c (rename pass) along with the cockpit→
fleetcrown stale references.
Verification: tsc clean. test:home 97/97. test:autopilot-defaults
11/11. test:dispatch-gates 11/11. lint clean (11 pre-existing
warnings, no errors).
Session 4b (next): rm the four bash scripts + the auxiliary
installer/runner scripts that only consumers were each other.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Chrome's Private Network Access requires the cross-origin target (the
local home/ daemon on 127.0.0.1) to opt in when the requesting page
is on a public network (cloud /control on https://fleetcrown.vercel.app).
Without this header the preflight silently aborts and the same-machine
fast path falls through to the cloud path 100% of the time even with the
daemon running.
This header is the documented spec opt-in
(https://developer.chrome.com/blog/private-network-access-preflight).
Chrome may still apply mixed-content gates on top of it for HTTPS pages
reaching plain-HTTP loopbacks; in that case the fast path only engages
from dev (http://localhost:3000/control) and the cloud path is
authoritative for production. Future work: terminate TLS on the local
daemon so the public→private hop becomes HTTPS→HTTPS and the gate
clears entirely.
curl-level preflight verified:
Access-Control-Allow-Origin: https://fleetcrown.vercel.app
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Private-Network: true
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Phase A of /home/g/.claude/plans/ethereal-crunching-clover.md. Three
independent changes share one goal: make /control inject actually
diagnosable + actually reliable on the common case.
A1. Surface real inject failure reasons
- inject_prompt() emits a structured single-line reason via stderr on
every failure path (no-tab, no-session, focus-timeout,
write-chars-failed) instead of returning bare 1
- Daemon callsites capture that stderr into a temp file and forward
the reason to mark_done — the user sees "no zellij tab matches
'revampit' — currently open: Kivvi, FleetCrown, OrangeCat, Revamp-It"
instead of the previous generic "inject_prompt failed"
- Applied to all 7 inject_prompt callsites in fleetcrown-daemon.sh
A2. Match agents by cwd, not just by tab name
- New _resolve_live_tab_by_cwd() walks zellij dump-layout, reconstructs
each pane's absolute cwd from the layout-level cwd + pane cwd, and
returns the tab whose pane is rooted in the target project_dir
- inject_prompt() takes an optional project_dir 3rd arg; when the
name match fails (revampit vs Revamp-It vs revamp-it kind of bug),
the cwd fallback fires
- Daemon callsites thread project_dir through. Fixes the revampit
dispatch we observed.
A3. Same-machine fast path
- home/server.ts gains POST /api/inject. Spawns bash, sources
agent-hook-lib.sh, calls inject_prompt directly. Returns
{ok:true} or {ok:false, reason}. Binds 127.0.0.1 only so the
LAN cannot reach it.
- CORS allow-list permits https://fleetcrown.vercel.app and the local
dev origins — every other origin's browser blocks the response.
- src/hooks/use-control-data.ts::inject() tries the local fast path
first with a 600ms abort timeout. Success returns; failure with a
reason re-throws (caller renders); no-daemon falls through to the
cloud path silently.
- Result: 7 hops (browser → Vercel → DB → daemon poll → exec → focus
→ write) collapse to 3 (browser → home → exec) for the common case.
Reliability follows from deletion.
Bonus: home/projects.ts::resolveProjectPath() now does a loose match
(strip hyphens + underscores) when the literal lookup misses. Lets the
cloud send "revampit" find the conf entry "revamp-it" without forcing a
rebrand. Tested with revampit; injection lands.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Embedded watcher gains an optional onIdle subscriber; the desktop main
process passes a callback that fires an OS notification (with a health
badge prefix and the handoff "done" line) every time a dispatched agent
writes its handoff. Clicking the notification surfaces the main window.
This closes the fire-and-walk-away loop: dispatch an intent, switch
context, get pinged when it lands.
Tray + window icon: replaces the placeholder nativeImage.createEmpty()
with the FleetCrown control-window mark, pre-rendered to PNG by a small
pure-Node generator (scripts/generate-tray-icon.mjs — wired into
prebuild + dev). 22px tray, 44px @2x, 256px window/builder icon. Icons
checked in under desktop/resources/ with a targeted gitignore exception
so packaged binaries pick them up without a build step. electron-builder
config gains buildResources + extraResources so the PNGs ship with
AppImage / deb / dmg / nsis.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- Refactor home/watcher.ts for dual use: library (startWatcher() returns {close}, no auto process.exit, conditional SIG handlers) + CLI (--start / --self-test unchanged, 8/8 tests pass).
- Wire in desktop/src/main/index.ts: import + start on whenReady (after createWindow), store closer, stop on before-quit.
- desktop runtime status now advertises hasWatcher + updated version string.
- Desktop main process now owns the full local event loop for its dispatches: append bridge.dispatch + started/crashed (with sentinel) on the way in, worker.idle (from real session.md changes) on the way out.
- Rebuilds clean; home/ 89/89; no separate watcher process required when Fleet Runner is the runtime.
- Docs + session updated.
This largely completes the "real worker idle path" part of desktop-2/3. GUI dogfood + projection verification in a graphical env still needed for the last mile.
- desktop build clean, tsc clean, lint 0, home/ 89/89
- advances desktop-2/3: dispatches now produce durable events in ~/.fleetcrown/events.jsonl with proper runId/sentinel so stop-hooks and web control plane treat them as first-class
- still no embedded watcher (idle via co-running home/watcher.ts for now)
Refs: desktop-app.md phases, Cockpit.roadmap T1/T2, prior landing 2d98638
Adjacent gap from the queue-storage work — the home/ stack now writes
queue items but doesn't display them. Users on home/ /control had no
visibility into what was queued for each project, even though the
data is sitting in /tmp/agent-queue-<tab>.
Changes:
• /api/state response now annotates each project with queueLen by
reading /tmp/agent-queue-<project>.toLowerCase() and counting the
JSON array. File missing or unreadable → queueLen=0 (no badge).
• New .queue-pill CSS rule (blue, matches the broader pill palette).
• Project header renders '<N> queued' when queueLen > 0, sitting
next to the existing running/status pill.
Stays local-first: no DB dependency from home/. The /tmp mirror is
the right source because it's written by both the cloud route's PUT
(via /api/beacon/queue/[tab]) and home/ itself if invoked from a
direct API call. Cross-stack visibility without coupling.
tsc clean, npm run test:home 89/89.
Two ships shipped the queue-into-prompt path: e6bd03b added the queue
field to OrchestrationTaskRequest + renderQueueBlock in
src/lib/orchestration/renderers.ts; 1cacfd2 plumbed it through home/'s
render.ts + /api/dispatch. Neither was covered by the existing
home/render self-tests (which only verified that all 12 intents
produce non-empty strings).
A future change to renderQueueBlock — different header wording, item
ordering, overflow threshold — would silently break both stacks
without any regression signal. Four new cases pin the contract:
• queue items render under 'User's prompt queue for this project'
and are 1-indexed
• empty queue → no block (suppression for the trivial case)
• undefined queue → no block (back-compat for callers that don't
plumb queue yet)
• queue > 10 items → first 10 + '…and N more' overflow indicator
home/render: 16 tests (was 12); full home/ suite total: 89/89.
tsc clean.
home/render.ts gained an optional queue field (mirroring
OrchestrationTaskRequest.queue from e6bd03b); home/server.ts's
/api/dispatch now sources the queue from caller-supplied body OR
falls back to /tmp/agent-queue-<tab> (the file mirror cloud's
/api/beacon/queue/[tab] writes for cross-stack visibility). Either
source threads through buildPromptForDispatch → renderPromptForDispatch
→ renderQueueBlock, so a home/-dispatched prompt now carries the
same 'User's prompt queue for this project' block the cloud path
already had. Closes the asymmetry: home/ and cloud both surface
queue context to the agent now.
Queue items added after the drained head still render — the agent
sees both what they're currently working on (the dispatch prompt
itself) and what's queued behind it.
tsc clean, npm run test:home 85/85.
After 27f31cb + b51fa18 wired the status field into the auto-inject
gates, the home/ Brain's /control UI had no visible indicator of
which projects were marked 'ready' vs 'working'. User couldn't tell
at a glance why an autonomous dispatch was or wasn't firing — the
status was hidden in the handoff text.
Added a status pill rendered next to the project name when no
currentRun is in flight:
• status: ready → green pill, same palette as the running pill
• status: working → yellow pill, same palette as outcome=partial
• missing / empty → no pill (silent, matches the suppress-default)
The render is browser-side JS inside the INDEX_HTML template literal
(the IIFE shape was the cleanest way to keep the conditional inline
without rewriting the surrounding JSX-style map). When currentRun IS
active, the running pill takes the slot as before — status is
implicitly 'working' during a run, so no overlap needed.
No new event kinds, no schema change, no DB touch. The home/ Brain
already parsed status into lastHandoff via the watcher's FIELDS
update from 27f31cb — this commit just surfaces it.
tsc clean, eslint clean, npm run test:home 85/85, smoke-verified the
new HTML lands.
27f31cb introduced the agent-driven status field as the gate for the
cloud /control auto-inject. The home/ Brain's decide() function read
lastHandoff.health but not lastHandoff.status — meaning the home/
stack's autonomous dispatches (autonomy=auto, autonomy=sleep) would
fire on a project whose agent said status=working, contradicting the
cloud's behavior.
shouldAutoExecute now takes a status parameter (defaults to '' for
back-compat with any external callers). When autonomy is non-manual
AND status is anything other than 'ready' (including empty, missing,
or 'working'), it returns false — same strict semantics as the cloud
gate in src/hooks/use-project-card-actions.ts and BeaconClient.tsx.
Manual mode bypasses (user click is the gate).
decide() pulls status from project.lastHandoff?.status and threads it
to all four shouldAutoExecute call sites (the recovery branch, the
queue-head branch, and the next_best branch — caught one I missed on
the first pass by re-running tests).
home/decide tests: 14/14 (was 11) — three new cases:
• sleep mode does NOT fire when status='working'
• auto mode does NOT fire when status is missing
• manual mode ignores status (user click IS the gate)
Plus an update to the existing 'sleep auto-fires on high confidence'
fixture to include status: 'ready' (otherwise it'd fail the new
gate). All eight home/ suites: 85/85 total (was 82).
tsc clean, eslint clean.
User asked: stop firing auto-inject prompts while the agent is mid-task;
inject should only fire when the agent has done everything and now
needs a nudge. They also called out the broader goal that this should
work for any model (claude, codex, gemini, openclaw, or future
adapters) — not just claude — since today's behavior is implicitly
claude-coupled through ~/.claude/sessions/*.md and the stop hook.
Added a new \`status\` field to the canonical handoff format. The
agent self-reports lifecycle state per turn:
status: ready — task fully done, auto-inject may proceed
status: working — agent is mid-task, suppress auto-inject
Missing / undefined / any-other-value is treated as NOT ready. This
inverts today's implicit default (auto-fire fires on every turn end)
so the agent must explicitly signal it's done with everything before
the beacon/ReadyBanner countdown fires the next prompt. Matches the
user's stated intent literally.
Why this is model-agnostic: the field lives in the canonical
ORCHESTRATION_TASK_SUMMARY_FIELDS constant that ALL adapters' handoff
templates read from (claude via buildPromptWithSession, openclaw via
renderSharedHandoffBlock, codex/gemini will inherit when their
handoff plumbing is wired). The parsers (parseSessionFile,
parseSessionText, home/watcher.ts:parseHandoff) all pick it up
automatically. Any new adapter that writes the standard handoff
format gets the same gating.
Files touched:
• src/lib/orchestration/contract.ts — added 'status' to
ORCHESTRATION_TASK_SUMMARY_FIELDS; OrchestrationTaskSummary makes
status optional for back-compat.
• src/lib/events.ts — Handoff zod schema gains status (defaults to
"") so home/ events with status round-trip cleanly.
• src/lib/control-types.ts — SessionState.status is optional;
legacy construction sites that don't yet plumb session_status can
omit it and naturally suppress auto-fire.
• src/lib/agent-config.ts:buildPromptWithSession — new status line
in the handoff template prose (the one claude reads each turn).
• src/lib/orchestration/renderers.ts:renderSharedHandoffBlock —
same line for openclaw.
• src/lib/session-content.ts:parseSessionText — beacon DB parser
extracts status.
• home/watcher.ts:FIELDS — home/ watcher's handoff parser includes
status (cascades to worker.idle events).
• src/hooks/use-project-card-actions.ts:handleAutoInject —
explicit gate: only fires when status === 'ready' (or
health-critical for recovery dispatches).
• src/app/beacon/[id]/BeaconClient.tsx:handleAutoInject — same
gate, parsing status out of session.sessionContent via
parseSessionText (BeaconSession carries raw md text).
• src/app/api/orchestration/runs/[id]/finish/route.ts — finish
body summary preserves status.
• home/{decide,emit,state,worker}.ts test fixtures — added
status: "" to all Handoff literals so the new required-after-
default field type-checks.
tsc clean, eslint clean, npm run test:home 82/82.
Transition note: until adapters start emitting status in their
handoffs, auto-inject will suppress for everyone. This is the user's
explicit choice ("only fire when the agent has done everything").
The handoff template prose now tells the agent to write the field,
so going forward agents will include it.
NOT shipped in this commit (deliberate scope cut, queued for next):
• DB column session_status on project_states (mirror of the new
field) — without it, control/stream/route.ts can't surface the
field server-side. Today the BeaconClient parses status directly
from raw session.md content; the broader cloud /control flow
will get accurate status once the column lands.
• Bash side (agent-hook-bridge.sh:emit_worker_finished) reading
status from session.md and including in worker.finished events.
The user has denied prior edits to that file; happy to ship if
they want or leave it for them to land.
Every dispatch out of /api/dispatch was defaulting to 'claude' because
the caller (the UI Dispatch button) doesn't send an adapter, the
project state doesn't carry one, and the brain had no other source.
Projects that should run codex or gemini (e.g. anything cross-checking
a Claude session, or codex for OpenClaw) silently got the wrong agent.
Extended agent-projects.conf with an optional 3rd pipe-separated field:
Cockpit|/home/g/dev/cockpit
OrangeCat|/home/g/dev/orangecat|codex
Two-field entries keep their semantics (adapter stays undefined →
downstream defaults to claude, same as before). The 3rd field is
validated against @/lib/events ADAPTERS — unknown values silently
degrade to undefined so a typo doesn't poison dispatches.
Files touched:
• home/projects.ts: ProjectConfig grows an optional adapter field,
loader parses the 3rd column, new resolveProjectAdapter() helper.
• home/server.ts: /api/dispatch adapter resolution now does
caller-body ?? resolveProjectAdapter(project) ?? undefined; worker
keeps defaulting to claude when both are absent.
• home/README.md: files table updated to reflect the new format.
home/projects 11/11 (was 7) — four new cases cover the codex 3rd
field, resolveProjectAdapter, two-field entries staying undefined,
and the unknown-adapter typo-defence path. Full suite: 82/82
across the eight home/ modules. tsc clean, eslint clean.
Last commit (614bde2) hit an opaque tsc syntax error when a stylistic
backtick around 'reason' in a code comment inside the INDEX_HTML
template literal closed the literal mid-comment. The error message
pointed at the comment line, not the offending backtick — easy to
misread as 'the new code is wrong' when actually the new comment is.
Buried the diagnostic in the previous commit message; future edits to
this body won't see it. Moved the warning into a comment block right
above the template literal so anyone touching the HTML/JS body gets
the heads-up: backticks need escaping or avoidance in comments and
strings inside the template; ${expr} interpolates at server-render
time, so JS that should evaluate in the browser needs \${.
No code change. tsc clean, eslint clean.
When the user clicked Cancel and it succeeded, the chip rendered as:
proposed cancelled — Ctrl+C sent... · 0% confidence
because renderProposal had only two branches: dispatched (the
post-/api/dispatch happy chip) and the catch-all 'proposed' shape for
real decide() outputs. Cancel and error results fell into the latter,
inheriting both the 'proposed' label and the meaningless 0% confidence
pill that came from the synthetic confidence:0 we set when stuffing
those non-decision events into the proposals Map.
Split renderProposal into three explicit branches:
• kind === 'cancelled' → 'cancelled · <reason>' (no confidence)
• kind === 'error' → red 'error · <reason>' (no confidence)
• everything else → the existing 'proposed' chip with confidence
Side note: a non-obvious bash trap during this commit — the comment
above the new branches initially used backticks around the word
'reason' for stylistic emphasis. The whole HTML body lives inside a
template literal, so those backticks closed the literal mid-comment
and tsc reported syntax errors on the comment line. Reworded the
comment to avoid backticks. Worth flagging for future home/server.ts
edits inside the INDEX_HTML body.
tsc clean, eslint clean, smoke confirmed the new template lands in
the served HTML.
home/log.ts:selfTest used `require("node:os")` and `require("node:crypto")`
to avoid adding top-level imports for test-only deps. Eslint's
@typescript-eslint/no-require-imports flagged both as errors. The
pre-commit hook only ran `eslint src/` so it never caught them.
Two fixes in one commit:
• Moved the imports to top-level alongside the existing fs + path
imports. randomUUID is named-imported (matches the existing
home/emit.ts style); os stays default-imported.
• Extended .husky/pre-commit's eslint step from 'src/' to 'src/ home/'
so future home/ lint regressions can't slip through.
Three remaining cryp.randomUUID() callsites and the import block all
updated together. tsc clean, eslint clean, home/log 6/6 still green.
home/README.md said 'state.ts # 15 tests' and CLAUDE.md said '76 inline
tests' — both stale already (3ff199f added 2 state regressions so the
true count is 17/78). Every test-add commit was implicitly creating
a doc-rot debt. Replaced the hardcoded numbers with semantic labels
('event projection', 'autonomy + confidence', etc.) and added one
short note that 'npm run test:home' aggregates the actual N/M total —
the real count lives in the test runner output, not in prose.
No code change. tsc clean.
bd143e2 closed a /api/dispatch race by eagerly applying the
freshly-appended event to state, then tailLog re-applies the same
event when fs.watch fires — so each event flows through
state.applyEvent twice in production. The fix's correctness depends
on those two applications producing the same state. No test asserted
that, so a future change to the bridge.dispatch or bridge.cancel
projection that accidentally broke idempotency would slip through.
Two new state.ts regression cases:
• bridge.dispatch applied twice → currentRun unchanged (runId,
intent, adapter, reason, confidence all match the single-apply
snapshot).
• bridge.cancel applied twice → cancelledRunIds contains exactly
one copy of the runId (the existing filter() in the projection
dedupes — verify it stays that way).
home/state 17/17 (was 15/15). Total: 78/78 across the eight home/
suites. tsc clean.
Two concurrent /api/dispatch requests could both pass decide()'s
'currentRun is falsy' gate because state.applyEvent only runs when
fs.watch fires — which can lag the synchronous appendEvent by tens
of ms. Result: two bridge.dispatch events for the same project, both
inject into the same zellij tab, agent gets bombarded with two prompts.
Made appendEvent return the stamped Event (was void). The /api/dispatch
and /api/cancel handlers now eagerly apply the returned event to state
immediately after the write, before res.end. A second request arriving
between the file write and fs.watch's callback now reads post-state and
decide() returns 'wait' for the same-project case. tailLog will re-apply
the same event when fs.watch eventually fires — idempotent for the two
event kinds emitted by these handlers (bridge.dispatch just overwrites
currentRun; bridge.cancel's cancelledRunIds filter dedupes).
All other appendEvent callers ignore the return value, so void→Event is
non-breaking. 76 home/ tests still green, tsc clean.
.husky/pre-push already runs the dev-server smoke when the server is
detected; the eight inline home/ self-test suites had no automatic
gate, so a typo in state.ts or decide.ts could push to origin without
anyone noticing until the next /control session went sideways.
Added 'npm run test:home' at the top of .husky/pre-push (always runs,
no server dependency, ~14s). Smoke still follows when the server is
up. Net push time: tsc+eslint (pre-commit, <5s) + test:home (~14s) +
smoke (~3s when server up). Pre-commit stays fast — 14s on every
commit would be too much friction.
Pre-commit unchanged. Updated home/README.md's 'Inline self-tests'
section to lead with 'npm run test:home' and note it's wired to
pre-push.
Dry-ran the pre-push hook end-to-end: 76 home/ tests + 40 smoke
routes all pass. tsc clean.
executeDispatch writes /tmp/<slug>-run-<tab> with the runId before
calling injectIntoTab so the stop hook can later read it and include
runId on worker.finished (fb6d5a0). On the happy path the sentinel is
consumed and deleted by finish_orchestration_run in the stop hook. On
the inject-failure path, no agent is running and no stop hook will
ever fire — so the sentinel sat in /tmp forever with the runId of a
dispatch that crashed at the wire.
The next manual claude launch in that tab would write a session.md
and trigger the stop hook, which reads the stale sentinel and tags an
unrelated worker.finished with our crashed runId. state.applyEvent
matches on runId for the cancelledRunIds → user_abort relabel, so a
stale match would also pollute confidence for the wrong run.
Added a fs.rmSync alongside the existing appendEvent worker.crashed
in the catch branch — symmetric with the dispatch-success path that
delegates cleanup to the stop hook chain. Wrapped in try/catch
because the sentinel write may have failed first (read-only /tmp,
weird FS), in which case there's nothing to clean up.
Worker self-tests still 12/12 (the cleanup happens in executeDispatch
which is I/O and not covered by the pure-function applyEvent suite —
manually verified the only behavior change is the cleanup path on
the catch branch). tsc clean.
The README's individual-process invocation section pointed at
worker.ts --self-test as a one-off, but emit/log/watcher all gained
their own --self-test branches in the last three commits (d0e120f,
9576807, e85e249). New 'Inline self-tests' section between
Idempotency and What's not here yet, with the exact invocation for
each of the eight suites and current test counts (76 total inline
tests across the stack).
Also documents why server.ts is the lone holdout — its route
handlers are bound to req/res streams, so unit-testing them in
isolation isn't worth the mocking cost; npm run smoke (which boots
the real dev server and curls every route) covers it instead.
No code change. tsc clean.
Completes the symmetric tests-for-untested-helpers pass that d0e120f
started with emit.ts and 9576807 continued with log.ts. Watcher
parseHandoff is the function that turns a session.md blob into the
five-field Handoff that flows into worker.idle events — a regex
regression silently corrupts the brain's lastHandoff state for every
project. Eight inline cases:
• Extracts all five fields from a well-formed session.md.
• Missing fields default to empty string (no undefined).
• Trims trailing whitespace from values.
• Doesn't get fooled by field names embedded INSIDE other values
(e.g. 'done: implementing next: foo' — next regex shouldn't
catch 'next:' on a line that starts with 'done:').
• All-empty Handoff for a blank input.
• tabFromFilename strips .md.
• Returns null for non-.md files (README.txt, noextension).
• Preserves multi-word tab names verbatim (Tab #1, Revamp-Info).
Also adjusted the --start gate: --self-test is now an allowed entry
point alongside --start, with the bottom-of-file dispatch picking the
right branch. Naked invocation still prints the usage banner and
exits 0.
home/state 15/15 · home/decide 11/11 · home/projects 7/7 · home/worker
12/12 · home/render 12/12 · home/emit 5/5 · home/log 6/6 · home/watcher
8/8 (new). tsc clean. The only home/ module without a self-test now is
server.ts (HTTP route handlers — hard to exercise without booting the
server).
Symmetric with d0e120f: home/log.ts had zero tests despite being the
read path every consumer relies on. A regression in the replay loop or
the per-line parser would silently drop events for the brain (state
drift) or the worker (lost dispatches). Six inline tests covering the
synchronous replay path:
• Initial replay classifies every existing line as phase='replay'.
• Garbled line surfaces via onError AND subsequent valid lines on
the same replay still arrive — single bad line never poisons the
rest of the stream.
• Missing log file (and missing parent dir) is auto-created.
• Empty file produces zero events, zero errors.
• position() reflects bytes consumed during replay.
• Blank lines between events are skipped silently (no onError noise).
Each test uses a fresh os.tmpdir + randomUUID file so cases don't
leak state between each other; everything is cleaned up via fs.rmSync.
Live-append testing is intentionally skipped — fs.watch is async/
debounced/best-effort on Linux, so the same consume() code path is
already exercised by the synchronous replay tests.
home/state 15/15 · home/decide 11/11 · home/projects 7/7 · home/worker
12/12 · home/render 12/12 · home/emit 5/5 · home/log 6/6 (new).
tsc clean.
home/emit.ts had zero tests despite being the only path that writes to
~/.<APP_SLUG>/events.jsonl in production. If appendEvent corrupted the
wire format, every consumer (server.ts tail, worker.ts tail) would
silently skip the bad lines and the brain's state would drift without
any signal. Adding a small inline suite, same pattern as the other
home/ modules (--self-test flag, no extra deps):
• Envelope stamping: v/id/ts present, id is a UUID, ts is ISO 8601.
• Round-trip via parseEvent — wire format survives serialize→parse.
• Two appends produce distinct ids (no accidental reuse).
• appendEvent creates the parent directory if missing.
• DistributiveOmit sanity: bridge.dispatch-specific fields (prompt,
autonomy, confidence) survive serialization — guards against the
union flattening that bit me earlier when introducing the type.
• worker.crashed payload preserves the error message.
All writes go to a unique mkdtemp directory, cleaned up at the end
even on assertion failure — the real production log is never touched.
home/state 15/15 · home/decide 11/11 · home/projects 7/7 · home/worker
12/12 · home/render 12/12 · home/emit 5/5 (new). tsc clean.
When the user clicks Dispatch, the /control UI optimistically shows a
'dispatched · runId xxxxx' chip and clears it once the brain's state
reflects currentRun (i.e. when the worker emits worker.started after
injecting). If the worker isn't running, the chip stays forever
showing 'dispatched' — looking like success even though nothing
actually fired. Same trap as the dispatch button bootstrapping bug
from 4237260: user gets no diagnostic, just stale optimism.
The dispatch response now timestamps the proposals map entry with
postedAt; renderProposal compares against DISPATCH_ACK_TIMEOUT_MS
(10s). Once the chip's been waiting that long with no currentRun
arrival, it flips to a red 'unacked' diagnostic: '... but
worker.started never arrived · runId xxxxx · is the worker running?'
Pure HTML/JS — no server change. The existing 2s setInterval keeps
the renderer ticking past the timeout. The chip still clears the
moment currentRun arrives (worker just slow), so a healthy stack
sees the diagnostic only when the worker really is dead.
tsc clean; smoke verified the new template bits land in the served
HTML (DISPATCH_ACK_TIMEOUT_MS, unacked, postedAt). All five home/
self-test suites untouched and still green.
The cancelledRunIds → user_abort relabel I shipped in e81d9ee matches
on event.runId. But the chain that produces worker.finished didn't
preserve the runId:
1. home/worker.ts:executeDispatch injected the prompt but never
wrote the /tmp/<slug>-run-<tab> sentinel that the stop hook reads
to learn the runId. Cloud's cockpit-daemon.sh writes it; the
local worker had been silently skipping it.
2. scripts/agent-hook-bridge.sh:emit_worker_finished didn't include
runId on the event at all — the JSON template only had
{v,id,ts,kind,project,outcome,durationMs,handoff}. It DID read
the sentinel for duration_ms, then threw the runId on the floor.
Net effect: every user-cancelled run was missing runId in
worker.finished, the relabel never matched, and the cancel
was recorded as whatever infer_outcome_v1 inferred (typically
"partial"). e81d9ee was working in tests but dead in production.
Fix:
• home/worker.ts: write event.runId to the sentinel before
injectIntoTab. Wrapped in try/catch since failure to write a /tmp
file shouldn't block dispatch — degrades gracefully to runId-less
worker.finished.
• scripts/agent-hook-bridge.sh: read the sentinel into run_id
alongside the existing duration_ms read, build a separate
{runId:...} object via jq, and merge it into the worker.finished
via jq's `+` operator. Empty sentinel → empty object → merge is a
no-op (matches the legacy shape, parseEvent accepts both).
Validated the jq merge output through parseEvent: both shapes parse
clean as worker.finished events. tsc + all home/ self-test suites
still green.
Yesterday's commit (4551933) made executeCancel emit worker.crashed on
sendRawKey failure so lastError would surface in the UI. But
state.applyEvent on worker.crashed unconditionally prepends "error" to
recentOutcomes — meaning a cancel attempt failing on infra (zellij
unreachable, tab gone) was dragging computeConfidence down as if the
agent itself had errored. The underlying run might still be alive in
the tab. The cancel attempt is its own event, separate from the run's
eventual outcome.
state.applyEvent now distinguishes the two cases by checking
cancelledRunIds when a worker.crashed arrives:
• Cancelled runId crashed → set lastError ONLY. recentOutcomes
stays clean so confidence isn't poisoned. If the run later emits
worker.finished, the e81d9ee relabel kicks in and records
user_abort instead.
• Non-cancelled runId crashed → unchanged: lastError + "error"
outcome added. A real inject failure still shifts confidence.
home/state.ts self-tests: 15/15 (was 13/13) — added both branches as
explicit cases, including a regression that the inject-failure path
still records "error". tsc clean.
Symmetric with executeDispatch — when injectIntoTab throws, the worker
emits worker.crashed and the brain's lastError surfaces the reason in
red on /control. Cancellation didn't have that path: sendRawKey could
throw (zellij tab gone, daemon unreachable), the worker logged to
stderr, and that was it. state.applyEvent had already cleared currentRun
optimistically on the bridge.cancel itself, so the UI would show the
project as idle while the agent kept running. Silent failure.
executeCancel now emits worker.crashed on sendRawKey failure with the
underlying message ("cancel failed: <msg>"). state.applyEvent sets
lastError and adds an "error" outcome to recentOutcomes — the cancel
attempt is its own event, separate from the run's eventual outcome (if
a stop hook fires later, the cancelled runId is still in
state.cancelledRunIds and that future worker.finished still gets
relabelled to user_abort).
home/worker self-tests still 12/12 (executeCancel is I/O so it's not
covered by the pure-function suite; state.ts already handles the new
event flow via the existing worker.crashed projection). tsc clean.
Everything that's shipped in the last five commits invalidated chunks
of home/README.md. Bringing it back in sync:
• Per-process invocations now need --start (commit 7ecbc0f). The
naked examples were footgun-bait — anyone copying them would hit
the new usage-banner and assume the docs were wrong.
• The dispatch smoke test used autonomy=auto, which after commit
4237260 doesn't fire on a fresh project (confidence 0.5 < 0.55).
Added the four-mode threshold table so the semantic difference
between manual/confirm/auto/sleep is clear, and the example uses
manual (the human-clicks-Dispatch path) for an immediate fire.
• Added a /api/cancel smoke (commit dd382eb) with a note that the
eventual worker.finished gets re-labelled user_abort (commit
e81d9ee) since the bash stop hook can't infer that on its own.
• Files table: added home/projects.ts (registry SSOT), listed
/api/cancel + /api/events on server.ts, mentioned watcher's
registry filter, and noted the worker also handles bridge.cancel
+ emits worker.crashed.
No code change. Tests untouched; tsc clean.
The foot-gun: \`npx tsx home/worker.ts | tail -3\` looks like a one-shot
test invocation but actually starts a fs.watch + log tailer that runs
forever after \`tail\` closes the pipe. Last session I tripped this twice:
once with a bad self-test loop that ran the worker without --self-test
(leaving a hot worker hours later), and once with a server smoke that
left an orphan on port 3088. The hot worker then picked up a real
bridge.dispatch from a separate smoke test and injected the next_best
prompt straight into the Cockpit zellij tab — i.e. into the active
agent session running the smoke test.
Structural fix: all three long-running home/ processes now require an
explicit --start flag. Naked invocations print a usage banner and exit
0, so accidental \`| tail -N\` or \`| head\` piping no longer leaves
orphans. worker keeps its existing --self-test branch.
• home/server.ts: --start guard at top, before any tailLog/listen
• home/watcher.ts: --start guard before fs.watch on SESSIONS_DIR
• home/worker.ts: --start | --self-test | (default: help+exit)
• scripts/home-start.sh: passes --start to all three launches
home/worker.ts self-tests still 12/12; tsc clean. State/decide/render/
projects suites untouched and still green.
Bug: a fresh project (zero outcome history) has confidence 0.5, but the
Dispatch button posted autonomy="auto" which gates on confidence >= 0.55.
Result: clicking Dispatch on a fresh project returned a proposal, not a
fire. With no fires, no outcomes accrued, confidence never moved, and
the brain stayed stuck at 0.5 forever. The system could not bootstrap.
Root cause was a wrong mental model in AUTONOMY_THRESHOLD: 'manual' was
set to Infinity (never auto-execute) with a comment saying "UI shows
the proposal, user clicks" — but the user clicking IS what makes it
manual. There's no second click step. Manual conflated with confirm.
Sharpened the meanings:
manual → 0 human clicked Dispatch — fire on receipt, the
human IS the gate. Confidence still flows for
display but never blocks.
confirm → Infinity show the proposal so the human can review or
click Dispatch (manual) to fire.
auto → 0.55 autonomous scheduler (cron, queue drain) — moderate
confidence gate.
sleep → 0.75 autonomous while-away — high confidence gate.
Health-critical still blocks manual via shouldAutoExecute's hard gate,
so an unhealthy project can't be force-dispatched past recovery.
Wired the UI Dispatch button to send autonomy="manual" instead of
"auto". Propose stays on "confirm".
home/decide.ts self-tests: 11/11 (was 10/10) — flipped the now-wrong
"manual never auto-executes" case to assert it ALWAYS fires, and added
the health-critical-still-blocks-manual regression. state 13/13 and
worker 12/12 still green. tsc clean.
The bash stop hook's infer_outcome_v1 has no branch for user_abort —
it can only return success/partial/error/hang based on session.md
contents. So when bridge.cancel sends Ctrl+C, the agent's eventual
worker.finished comes in tagged "partial" (or "error" if health was
already bad), which then flows into recentOutcomes and drags
computeConfidence down. A user clicking Cancel ten times in a row
would convince the brain the project is failing — wrong signal.
The brain has the truth: it processed the bridge.cancel itself, so it
knows the run was killed deliberately. Recording the cancelled runId
on the ProjectState (capped at 10 to keep growth bounded) lets the
subsequent worker.finished match by runId and overwrite outcome with
"user_abort" before it lands in recentOutcomes. The cancelled runId is
consumed by the matching finish so it can't bleed into an unrelated
future run, and ProjectState.cancelledRunIds is optional so the
registry-idle ProjectState fallbacks in server.ts and the decide.ts
test fixtures don't need a churn-only empty-array seed.
home/state.ts self-tests: 13/13 (was 11/11) — added cancel→partial
relabels to user_abort, and cancel-for-a does-NOT-relabel-finish-of-b.
home/worker.ts 12/12 still green. tsc clean.
bridge.cancel was schema-only: declared in events.ts, projected by
state.ts (clears currentRun on runId match), but no producer and no
consumer. A running agent in a zellij tab could not be interrupted from
the home/ UI — user had to switch tabs and Ctrl+C manually, leaving the
brain blind to the cancellation until the next stop-hook fired.
Wired the three missing pieces:
• home/server.ts: POST /api/cancel { project, runId?, reason? }. When
runId is omitted, falls back to the live currentRun.runId. Emits a
bridge.cancel event into the log. 404 with a hint when nothing is
running. Validation matches the other endpoints.
• home/worker.ts: applyEvent now returns { dispatch?, cancel? }. A
live bridge.cancel triggers sendRawKey(project, 3) — same Ctrl+C
pattern src/app/api/control/switch-agent/route.ts uses for stuck
agents. Replay-phase cancels are historical (already happened) so
they update state but do NOT re-send Ctrl+C. A cancel also clears
the runId from pendingDispatches so crash-recovery on next boot
doesn't re-fire a dispatch the user already killed.
• home/server.ts (UI): running cards now render a Cancel button next
to the running pill; idle cards keep the Propose + Dispatch pair.
Single delegated click listener handles both via data-action attrs.
The stop-hook still emits worker.finished with whatever outcome
infer_outcome_v1 derives from session.md at shutdown time (typically
"partial" when the agent was mid-task) — we don't forge a finish event
ourselves, the natural flow catches up.
home/worker.ts self-tests: 12/12 (was 8/8) — added live-cancel-emits,
replay-cancel-no-emit, cancel-drops-pending, dispatch-after-cancel-skips.
home/state.ts: 11/11 still green. tsc clean.
Before: only worker.started cleared a runId from pendingDispatches. If
injectIntoTab failed (wrong tab name, zellij unreachable), the worker
emitted worker.crashed but kept the dispatch live in its replay-pending
set. On the next restart, the same dispatch got re-tried — failed again —
emitted another crashed — and repeated forever, scrolling the log with
duplicate crashes for the same runId.
Fix: applyEvent treats worker.crashed the same as worker.started — the
run is over, don't re-execute. User can re-dispatch from the UI if they
fixed the underlying tab issue. Adds two regression tests covering
replay-after-crash and live-skip-after-crash.
home/worker.ts self-tests now 8/8 (was 6/6).
The /control page polled state every 2s but had no interactive surface —
firing a dispatch meant remembering the curl JSON shape. Added two buttons
per idle project: 'Propose' (autonomy=confirm, returns the brain's pick
without firing) and 'Dispatch' (autonomy=auto, fires when the confidence
gate clears). Result renders inline as a 'proposed' or 'dispatched' chip
that clears the next time the project enters a run. Click is wired via
data-attrs + a single delegated listener so project names containing
quotes don't break the handler.
All five home/ self-test suites still green; tsc clean.
POST /api/events was append-anything-as-a-line. A typo, half-built event,
or buggy test harness would write a garbled JSON line straight to
~/.${APP_SLUG}/events.jsonl — permanent until the user manually edited
the log file. parseEvent on the read side handles the bad line cleanly
(skip + onError), but it stays on disk for every future boot's replay
and shows up in /api/state.lastError on every refresh.
Fix: parse + validate the body via parseEvent before writing. Invalid
→ 400 with the parse error + raw line in the response so the caller can
see exactly what failed (mirrors the home/log.ts onError path). Valid →
append the original line (preserves the caller's field ordering and
formatting; parsed.event is just the validation product).
Response on success grows a tiny `kind` echo so callers can confirm
which event variant was accepted.
The smoke-test recipe in home/README.md still works — it sends complete
v=1 events with all required envelope fields. Anything malformed is
caught at the boundary instead of corrupting the log.
All five home/ self-test suites still green:
state 11/11 · decide 10/10 · render 12/12 · projects 7/7 · worker 6/6
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adjacent gap from the zellij silent-write fix (5cd54d5): worker.crashed
now reliably surfaces ("zellij tab X did not gain focus"), but the actual
error message was getting discarded during state projection — the user
saw a bare ✗ glyph in the streak with no hint what went wrong. Had to
grep the events.jsonl log by hand.
ProjectState gains an optional `lastError: { ts, message }` field.
applyEvent for worker.crashed sets it. worker.finished with a non-error
outcome (success / partial / user_abort) clears it — project has moved
past the failure. worker.finished with outcome=error PRESERVES the
prior message (the older context might still be the most actionable).
UI: a small red-bordered line below the outcome streak shows
"last error @ HH:MM:SS: <message>" whenever lastError is set. Styled
with a left border + tinted background so it stands out without
shouting.
3 new self-test cases in state.ts (now 11/11):
✓ worker.crashed sets lastError with the event message
✓ successful worker.finished clears lastError
✓ worker.finished with outcome=error PRESERVES lastError from prior crash
Other suites still green: decide 10/10, worker 6/6, render 12/12,
projects 7/7. M9 live exercise now surfaces failure modes in the UI
the moment the user sees them — no log-grepping required.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Real bug in home/decide.ts. The autonomy threshold map had:
confirm: 0.0
…which combined with shouldAutoExecute's `confidence >= AUTONOMY_THRESHOLD[autonomy]`
check meant confirm-mode dispatches ALWAYS returned autoExecute=true (any
non-negative confidence cleared the bar). Defeated the whole point of
"confirm" as a UI-mediated gate — every POST /api/dispatch with
autonomy=confirm would fire the bridge.dispatch event immediately,
exactly like autonomy=auto.
Per the original design comment ("UI countdown gates the actual fire"),
confirm should never auto-execute from the API. The UI runs a countdown
then re-POSTs with autonomy=auto to fire, or the user clicks NOW. Same
shape as manual from the API's perspective: both return the proposal
with dispatched=false.
Fix: confirm threshold → Infinity. Now:
manual : Infinity – never auto-execute
confirm : Infinity – never auto-execute (UI countdown takes over)
auto : 0.55 – moderate-confidence fire
sleep : 0.75 – high-confidence fire while user away
Regression test added — confirm with full-success outcome history +
healthy state must return autoExecute=false. decide() suite grows to
10/10. All other suites still green: state 8/8, worker 6/6,
render 12/12, projects 7/7.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
UX gap on fresh boot: /api/state only returned projects that had
emitted at least one event, so a freshly-installed home/ stack with
nothing dispatched yet rendered the bare "no events yet" empty state
even when the user has 7 projects registered in agent-projects.conf.
No surface to click on, no obvious next step.
Fix: assembleProjectList() unions the live event-projected state with
registered projects from the conf file. Registered-but-eventless
entries get synthesized as ProjectState { project, lastEventTs: "",
recentOutcomes: [] } — same shape as live entries so the UI doesn't
need to branch. Live state always wins on case-insensitive name
collision (matches the registry's lookup convention).
UI compact(iso) helper handles empty / invalid timestamps by
returning 'idle' instead of "Invalid Date", so the synthesized
entries render cleanly. Other render paths (recentOutcomes, handoff,
currentRun) already guard on truthiness.
After M9, the user opens localhost:3001 right after `home-start.sh`
and immediately sees the project list. Each idle row has the
project name + 'idle' timestamp; live rows show their current state
on top. Same surface, no fresh-install moment of "is this thing on?"
Self-tests still green: state 8/8 · worker 6/6 · decide 9/9 ·
render 12/12 · projects 7/7.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Real foot-gun: home/watcher.ts emitted worker.idle for ANY .md file in
~/.claude/sessions/, including scratch tabs (Tab #1.md, Logo.md) that
aren't actual projects. The brain's state map would accumulate junk
entries on every boot once those files had been touched. ~17 .md files
in the dir on this machine, only 7 of which are real projects per
~/.config/agent-projects.conf.
Fix: at start(), load loadProjects() and build a Set of lowercase
registered names. readAndEmit() filters out filenames that don't have
a registry entry. First skipped file per filename logs a one-time line
("skipping Tab #1.md — not in ~/.config/agent-projects.conf") so first-
run debuggability stays high.
Empty registry isn't fatal — emits a WARN line at boot pointing at the
conf file. User restart-after-edit picks up new entries; live config
reloading is M11+ if it ever matters.
Behaviour matrix:
Tab in registry → emit worker.idle on change (existing path)
Tab not in registry → skip silently (one-time log per filename)
Empty registry → skip everything + boot WARN
Self-tests still green: home/state 8/8, worker 6/6, decide 9/9,
render 12/12, projects 7/7. The watcher itself doesn't have a self-test
(I/O-bound), but the filter is small enough to review by eye.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
First-time setup foot-gun: POST /api/dispatch returned 404 for any project
that hadn't yet emitted events into ~/.${APP_SLUG}/events.jsonl. So a
brand-new home/ install couldn't dispatch into a known project unless the
user manually appended a fake worker.started first. Friction on day one.
Fix: when the project isn't in the live event-projected state, fall back
to resolveProjectPath() against ~/.config/agent-projects.conf — the
existing registry of TabName|/path mappings. If found, synthesize a neutral
ProjectState (empty outcomes, no currentRun) and let decide() run normally.
First dispatch fires correctly; subsequent events populate the real state
through the normal event-log path.
If the name isn't in state OR the registry, return 404 with a hint:
"hint": "Add it to ~/.config/agent-projects.conf (TabName|/absolute/path),
or POST a worker.* event first."
Behaviour matrix:
in state → use existing projection (no change)
in registry only → synthesize neutral state, dispatch
in neither → 404 with actionable hint
decide() against the neutral synthetic state lands at confidence=0.5
(empty outcome history, see home/decide.ts) which gates correctly for
all four autonomy modes: manual + confirm hold (UI confirms), auto +
sleep wait for confidence to build via successful runs.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When the brain dispatches, the UI now shows *why* — not just the
intent pill. Until this commit, bridge.dispatch.reason and .confidence
were schema-locked but projected nowhere; the brain's reasoning vanished
the moment worker.started overwrote currentRun with a leaner shape from
the worker layer.
state.ts:
- ProjectState.currentRun gains optional reason + confidence
- bridge.dispatch projects both
- worker.started preserves them when the runId matches (subtle: a
worker.started for a DIFFERENT runId — race condition — does NOT
inherit stale reasoning, by design)
server.ts: HTML view renders a small .reason line under the intent pill,
optionally with "· 80% confidence". Adapter is shown next to the intent
when it's not the default claude (so codex / gemini runs stand out).
Two new CSS rules for the muted reason text.
Self-test: state.ts gains 2 new cases — total 8/8 — including a
regression test for the "stale dispatch's reason leaks onto a fresh
worker.started" foot-gun. Other suites still green:
worker 6/6 · decide 9/9 · render 12/12 · projects 7/7
Effect after M9: when the brain auto-fires in sleep mode, the user
glancing at /control sees both what's running and why the brain picked
it — not just an opaque "next_best in flight."
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes the "UI looks idle between dispatch and worker.started" gap. Until
this commit, applyEvent explicitly skipped bridge.dispatch with a TODO
("M5+ will populate currentRun"). The gap is usually <200ms but during a
slow zellij focus or a crashed worker it could be seconds — and during
crash recovery the UI would never reflect that a run was dispatched
without a confirming worker.started.
bridge.dispatch → pre-populates currentRun {runId, intent, adapter,
startedAt: event.ts}. worker.started overwrites with
the same-shape confirmed version.
bridge.cancel → clears currentRun ONLY when its runId matches the
active run — a stale cancel never drops a later
dispatch's currentRun.
brain.outcome → no state change (worker.finished is what updates
recentOutcomes + lastHandoff; brain.outcome is the
analytics-only mirror).
state.ts didn't have a self-test before; now it has 6 cases covering the
full dispatch→started→finished lifecycle plus the cancel-match / -mismatch
edges plus the default-adapter fallback. All other suites still green:
worker 6/6, decide 9/9, render 12/12, projects 7/7.
Run: npx tsx home/state.ts
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closing a metadata-correctness gap: home/worker.ts was hardcoding
adapter="claude" on every worker.started event, so analytics + the
decide() function would always see "claude" even when the run was
actually a codex or gemini agent.
Schema: BridgeDispatch gains an optional `adapter` field (Adapter enum).
Server: POST /api/dispatch body accepts an `adapter` string; validated
against ADAPTERS before forwarding into the appended event.
Worker: executeDispatch echoes event.adapter onto worker.started, with
"claude" as the default when the brain didn't set one (matches
DEFAULT_AGENT in src/lib/agent-preferences.ts).
The caller (UI / API client) is the source of truth for adapter choice
in this round. M10 wires per-project agent_pref so the brain's autonomous
dispatches use the right agent without a caller telling it — that needs
either DB access from home/ or a flat-file agent_pref export from the
existing system. Out of scope here.
All four self-test suites still green:
home/projects 7/7 · home/worker 6/6 · home/render 12/12 · home/decide 9/9
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The renderer was falling back to the project name when no projectPath was
supplied to POST /api/dispatch, producing "Work on the project at Cockpit"
instead of the real path. Meanwhile the existing system has been keeping
the tab-name → directory mapping in ~/.config/agent-projects.conf for a
while — the new home/ system just wasn't reading it.
home/projects.ts:
- projectsConfPath() resolves APP_PROJECTS_CONF / legacy env
names / default ~/.config/agent-projects.conf
- loadProjects(confPath?) parses "name|path" lines, skips comments,
returns a Map keyed by lowercase name
- resolveProjectPath(name) case-insensitive lookup
home/server.ts: when POST /api/dispatch doesn't carry an explicit
projectPath, falls back to resolveProjectPath(projectName) before invoking
the renderer. Caller-supplied still wins so test harnesses + alt routes
keep working.
Self-test (npx tsx home/projects.ts): 7/7
✓ loads valid entries, skips comments + malformed lines
✓ case-insensitive lookup (uppercase + lowercase + mixed)
✓ tab names with embedded spaces resolve
✓ unknown project returns undefined (no throw)
✓ preserves display-case in ProjectConfig.name
✓ missing conf file returns empty map without throwing
Other suites still green: worker 6/6, decide 9/9, render 12/12.
The home/ stack now produces correct project-rooted prompts for every
intent. After M9's live exercise, the renderer will print real paths
instead of the project-name fallback.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
scripts/home-start.sh starts server + watcher + worker together, merges
their output (with [server] / [watcher] / [worker] prefixes per line)
into /tmp/${APP_SLUG}-home.log, and traps SIGINT to take the whole stack
down cleanly. Removes the previous three-terminal ceremony — one command,
one log, one Ctrl-C.
Pre-flight: refuses to start if anything is already serving
localhost:3001, so two stacks can't race on the same events.jsonl file.
Wait -n: if any child process exits unexpectedly, the launcher tears the
remaining two down. The user gets one obvious signal instead of a quiet
half-broken loop where (say) the worker crashed but the server kept
serving stale state.
home/README.md updated to point at the launcher first, with the
three-terminal recipe kept for iterative development.
Unblocks the M9 live exercise: previously each test required three
terminals + remembering each command + cleaning up three pids manually.
Now it's `bash scripts/home-start.sh` → curl /api/dispatch → Ctrl-C.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>