Investigated the user's 'STT microphone not working properly' report.
Found two real problems on this machine:
1. GROQ_API_KEY in .env.local returns 401 from Groq (direct probe of
https://api.groq.com/openai/v1/audio/transcriptions with the same
bearer returned {'error':{'message':'Invalid API Key'}}). User
needs to rotate the key at https://console.groq.com.
2. Local Whisper 'base' fallback takes 38-45s per 1-second WAV —
within the route's 60s timeout but well past any user's patience.
The route's 401 path previously wrapped the failure as a generic HTTP
500 with the error body inlined as a string — easy to miss in a network
tab, no actionable hint. Now classifies common Groq failure modes:
• 401 (Invalid API Key) → HTTP 502 with 'rotate the key' hint
• 429 (rate limited) → HTTP 429 with 'retry or switch to local'
• timeout / abort → HTTP 504 with 'try a shorter recording'
• other → HTTP 502 (was 500; bad-upstream is more
honest — the route itself didn't fail)
The original error is preserved as for debugging without
poisoning the user-facing string. Local Whisper path
unchanged — the slowness there is a separate question (model size +
GPU vs CPU) and outside the scope of error-message work.
tsc clean, eslint clean. Doesn't fix the user's 401 — they still need
to rotate the Groq key — but ensures future occurrences are diagnosed
in seconds instead of requiring a deep dive into the route source.
Yesterday's session diagnosed a silent trap: cockpit-daemon.sh's
_base_url() prefers local-when-reachable, so a user running both
cockpit-app systemd on localhost:3000 AND $COCKPIT_BASE_URL pointed
at https://cockpitapp.vercel.app silently polls local, ignoring every
dispatch from the production /control page. The fix on the user's
machine was a one-line daemon.env edit (DAEMON_FORCE_REMOTE=1) — but
nothing in the script tells them they're in this state.
Added a startup-time warning in _init_base_url: when the daemon picks
LOCAL but $COCKPIT_BASE_URL is a non-localhost URL, three log lines
fire explaining the trap and the fix. Stays silent for genuine dev
setups ($COCKPIT_BASE_URL pointing at localhost or 127.0.0.1) so it
doesn't cry wolf.
Bash syntax clean. No behavior change — same routing logic, just a
diagnostic log when the trap configuration is detected.
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.
CLAUDE.md is the first file future agents read when entering this
repo. It described src/ tree, design system, conventions, and dev
commands — but never mentioned the home/ stack (server.ts + watcher.ts
+ worker.ts) that's been the focus of the last twenty commits. A new
agent walking in cold would only find the local Brain by accident.
Added a home/ block right after the src/ tree explaining the three
processes, the JSONL log, the UI port (3001), and pointing at the
boot command + npm run test:home + home/README.md for the full
breakdown. Also added 'npm run test:home' and 'bash scripts/
home-start.sh' to the Dev Commands section and a note about the
pre-push hook's gate.
No code change. Pure docs.
.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.
Each home/ module ships an inline test suite (state/decide/projects/
render/emit/log/watcher/worker — 76 tests total as of 00058f9), but
running them required eight separate npx tsx invocations. Added
scripts/test-home.sh that chains them in a stable order, captures
each suite's output, parses the N/M passed footer, and aggregates a
total at the end. Wired as 'npm run test:home' alongside the existing
smoke and check:design scripts.
The footer regex matches '^N/M' rather than 'N/M passed' specifically
because render.ts prints '12/12 intents render' — most suites use
'passed' but the loose anchor catches both shapes. Exits non-zero on
the first suite that fails (set -euo pipefail + a tracked total_fail
counter for the summary line).
Output of npm run test:home ends with:
✓ 76 total tests passed across 8 home/ self-test suites
No code change in home/. tsc unaffected.
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 safety bug surfaced while auditing the home/ dispatch path. When
injectIntoTab was asked to write into a tab that didn't exist (closed,
typo'd, zellij not reachable from the caller's env), the sequence:
zellij action go-to-tab-name <missing> # no-op, exits 0
waitForTabFocus(missing) # times out, returns void
zellij action write-chars <prompt> # → types into whatever IS focused
…would type the prompt into the user's CURRENTLY-FOCUSED pane, which on
a long-running worker process is almost certainly NOT the intended
agent tab. Could garble a private terminal session, paste secrets, or
trigger a wrong agent. Silent failure — every caller's try/catch
considered it a success.
src/lib/zellij.ts
waitForTabFocus now returns boolean (true = focused, false = timeout)
injectIntoTab throws when waitForTabFocus returns false
sendRawKey throws likewise (same wrong-pane risk for raw key codes)
Error message names the tab + hints at the likely cause:
"injectIntoTab: zellij tab "<name>" did not gain focus within 1s —
is the tab open and zellij reachable?"
Caller impact: every existing call site (orchestration/run, inject,
agent/launch, switch-agent, plus home/worker.ts) already wraps
injectIntoTab in try/catch, so the new throw cleanly surfaces as a
500 / worker.crashed event instead of corrupting an unrelated pane.
All five home/ self-test suites still green: state 8/8, worker 6/6,
decide 10/10, render 12/12, projects 7/7.
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>
Symmetric to the watcher.ts fix in 58e195b. emit_worker_finished was
appending worker.finished events to ~/.${APP_SLUG}/events.jsonl for any
tab the stop hook fired in — including scratch shells, ad-hoc one-off
tabs (Tab #1, Logo, …). The brain's state map would still accumulate
junk via this path, even though the watcher half was now filtering.
Closes the loop: both event-producing paths in the home/ system now
respect ~/.config/agent-projects.conf as the SSOT for which projects
the brain tracks.
awk-based filter (no jq dependency for the lookup itself):
- reads ${APP_PROJECTS_CONF:-${AGENT_PROJECTS_CONF:-${CLAUDE_PROJECTS_CONF:-$HOME/.config/agent-projects.conf}}}
- case-insensitive match on the first |-delimited field
- skips comment lines
- missing conf file means no filter — preserves the existing behaviour
for users who never registered projects
Verified against the live ~/.config/agent-projects.conf with 8 sample
tab names: Cockpit/cockpit/COCKPIT → REGISTERED; Tab #1, Logo,
NonexistentTab → skip; OpenClaw/openclaw → REGISTERED.
After this commit, the brain's view is curated symmetrically on both
input paths. Adding/removing a project name happens in exactly one
file: ~/.config/agent-projects.conf.
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>
During log replay, when a bridge.dispatch was followed later in the same
log by its matching worker.started, the worker's pendingDispatches map
still held the dispatch. The setImmediate replay-end scan then iterated
that map and re-injected every historical run on every worker restart.
Root cause: handleEvent's worker.started branch added the runId to
startedRunIds but didn't delete from pendingDispatches. The two state
collections drifted.
One-line fix: when a worker.started clears a run, also clear it from
pendingDispatches. Crash recovery still works — bridge.dispatch with no
downstream worker.started stays in the map and fires after replay.
Refactor in the same commit (~20 lines moved): extracted the pure state
transition into applyEvent(state, event, phase) — no I/O, no injection,
returns the dispatch the caller should execute. This makes the bug
testable: 6 inline cases including a regression test for exactly the
"replayed dispatch + worker.started → pending cleared" scenario.
Run: npx tsx home/worker.ts --self-test
6/6 passed
The original handleEvent + executeDispatch + setImmediate flow still
works identically — the refactor just lifts the pure logic out for
testability. Side effects (injectIntoTab, appendEvent, console.log,
SIGINT/SIGTERM handlers) all sit in executeDispatch + start() exactly
where they were.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Eighth milestone of the greenfield rewrite. home/worker.ts is the consumer
half of the dispatch loop. Tails the same JSONL log home/server.ts reads,
filters for bridge.dispatch events, and injects each prompt into the
right zellij tab via @/lib/zellij.injectIntoTab. On success emits
worker.started with the same runId; on injection failure emits
worker.crashed.
With M8 the loop closes locally:
user/UI POST → /api/dispatch → bridge.dispatch event in the log
→ worker.ts (this commit) → injectIntoTab → claude runs
→ claude writes session.md → M3 watcher → worker.idle event
→ claude stop hook → M4 emit → worker.finished event
→ Brain projects all of it back into state
Idempotency: home/log.ts gained a phase flag ("replay" | "live") so the
worker can distinguish initial log replay (build the set of already-started
runIds) from live appends (act on new dispatches). Restarting the worker
never re-injects. Bridge dispatches that exist in the log with no matching
worker.started downstream are treated as crash-recovery and fired after
replay completes (setImmediate signals the event-loop rollover).
Three Node processes now run side by side:
home/server.ts Brain. /api/state, /api/dispatch, the UI.
home/watcher.ts Bridge. session.md → worker.idle.
home/worker.ts Consumer. bridge.dispatch → injectIntoTab → worker.started.
home/log.ts: tailLog signature gained `phase` as the second arg to onEvent.
home/server.ts ignores it (just updates state), home/worker.ts uses it.
Existing call site is forward-compatible (TS allows ignoring optional
trailing arg), no other home/ file needed an update.
home/README.md rewritten to document the three-process model + a curl-
based smoke test of the dispatch loop.
What this commit deliberately does NOT do:
- retire /api/control/dispatch on Vercel (M9 — parity verification first)
- persist startedRunIds across restarts in any way other than via log
replay (the log IS the durable state)
- per-project adapter selection — worker.started always claims adapter:
"claude" for now; M9 reads project config
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Seventh milestone of the greenfield rewrite. home/render.ts is now a thin
adapter over src/lib/orchestration/renderers.ts:renderTaskForAdapter — the
existing SSOT for prompt text. The home/ Brain produces full, agent-ready
prompts for every canonical intent instead of the M6 placeholder string.
home/render.ts renderPromptForDispatch({project, projectPath?,
intent, adapter?, customInstructions?}) → string
Reuses renderTaskForAdapter; no duplication of
the per-intent bodies. Inline self-test covers all
12 canonical intents (next_best, test_and_fix,
quality, full_audit, product, ux_review,
deploy_check, commit_push, close_session,
hard_stop, continue, custom) — 12/12 pass.
home/server.ts buildPromptForDispatch now uses the new renderer.
The queue-drain case (decision.action.prompt is
set) collapses to intent="custom" with the queue
item as customInstructions — matches today's
flip in /api/orchestration/run when a queueHead
exists.
POST /api/dispatch body now accepts an optional projectPath so the renderer
can produce "Work on the project at /home/g/dev/<x>" instead of falling
back to the project name. Missing path is harmless — agents are already
in the right cwd.
What this commit deliberately does NOT do:
- write a worker that consumes bridge.dispatch (next session — the new
M8 milestone, since M7 split cleanly into render + dispatch consumer)
- retire /api/control/dispatch on Vercel (parity check first)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Sixth milestone of the greenfield rewrite. The Brain now has a callable
dispatch endpoint: hit POST /api/dispatch with a project name (+ optional
queueHead + autonomy), the server runs decide() against the current
projected state, and either emits a bridge.dispatch event to the JSONL
log (when autonomy + confidence say "go") or returns the proposed action
for a confirm-mode UI to render.
Request:
POST /api/dispatch
{ "project": "Cockpit", "queueHead": "run security audit", "autonomy": "auto" }
Response on auto-execute:
{ "dispatched": true, "decision": {...}, "runId": "<uuid>" }
↑ A v=1 bridge.dispatch event with the same runId is appended to
~/.${APP_SLUG}/events.jsonl, ready for a future worker to consume.
Response on hold:
{ "dispatched": false, "decision": {...} }
↑ Confirm-mode UIs render this — the user clicks to fire, or the
countdown auto-fires after the deadline.
Stub prompt builder: when the queue item IS the prompt, passes it through
verbatim. Otherwise emits "[m6 dispatch stub] intent=<x> project=<y> …"
as a placeholder. The real renderer port from src/lib/orchestration lands
in M7 along with the cutover that retires /api/control/dispatch entirely.
What this commit deliberately does NOT do:
- render real prompts (M7)
- have any worker actually consume bridge.dispatch events (M7+)
- touch /api/control/dispatch on Vercel (stays alive during parity check)
Live exercise blocked in this session (you reasonably denied the bg-process
spawn that would have written under HOME=/tmp), but the path is shallow:
3 routes share a single state Map, decide() is 9/9 unit-tested, the event
schema is locked in M1. Easy to verify with curl once you start the server.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Fifth milestone of the greenfield rewrite. home/decide.ts is now the only
decision function in the new system: given a ProjectState (from M2's
projection) + queueHead + autonomy preference + clock, returns the
proposed action, a confidence score, and whether to auto-execute.
Pure. No I/O. Deterministic given inputs. Unit-testable by feeding canned
states and asserting on the output — proven by an inline self-test that
covers the 9 representative cases:
✓ wait when a run is in flight
✓ recovery when health is critical
✓ recovery when tests fail (test_and_fix)
✓ queue head dispatched when present and health OK
✓ empty queue + healthy → next_best
✓ manual autonomy never auto-executes
✓ sleep mode auto-fires on high confidence + healthy
✓ sleep mode holds when recent errors drop confidence
✓ empty outcome history gives neutral 0.5 confidence
Run: npx tsx home/decide.ts
Confidence v1 is a piecewise mapping of weighted outcome history:
per-outcome weight {success:+1, partial:0, error:-2, hang:-2, timeout:-1.5, user_abort:0}
asymmetric on purpose — errors scream louder than successes earn
empty history → neutral 0.5
Autonomy gating layers on top:
manual → never auto-execute, regardless of confidence
confirm → always proposes (UI countdown still gates the actual fire)
auto → auto-executes at confidence ≥ 0.55
sleep → auto-executes at confidence ≥ 0.75 AND health is not 'critical'
What this commit deliberately does NOT do:
- call decide() from anywhere yet (M6 wires it into dispatch)
- replace /api/control/dispatch (still load-bearing for cockpitapp.vercel.app)
- persist confidence history (it's derived from projection every call)
decide() is the single function that any future tweaking of autonomy
behavior touches. Sleep mode is no longer a binary localStorage toggle —
it's a real strategy with a confidence floor.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Fourth milestone of the greenfield rewrite. handle_stop in agent-hook-bridge.sh
now appends a properly-stamped worker.finished JSONL event to
~/.${APP_SLUG}/events.jsonl in parallel with the existing
finish_orchestration_run cloud call. The new home/ Brain gets a complete
view of each run (idle from M3 watcher + finished from this commit) without
the cloud-round-trip dependency.
Two new functions:
infer_outcome_v1 Bash port of src/lib/orchestration/infer-outcome.ts.
Same precedence: health=critical → error; long-running
with empty done → hang; tests has 'fail' or health
'needs attention' → partial; health=good + done set
→ success; else partial.
emit_worker_finished Reads done/next/tests/todos/health out of the session
file the agent just wrote, derives durationMs from
/tmp/${APP_SLUG}-run-<tab> mtime (the dispatch
sentinel), assembles a v=1 worker.finished envelope
via jq, appends to the log. Skips silently if jq
isn't installed — the cloud finish path keeps working
unchanged.
Wired into handle_stop right after finish_orchestration_run. Both consume
the same session.md, so they always agree on the handoff. The new path adds
zero latency to the stop hook (jq append is sub-ms) and zero blocking — if
the log file is full or unwritable, the error path is squashed via
|| true so the popup still fires.
What this commit deliberately does NOT do:
- retire the legacy /tmp/agent-* sentinels (still written for daemon parity)
- stop calling finish_orchestration_run (cloud path stays during cutover)
- emit worker.started yet (M5 — once dispatch flows through the new
bridge.dispatch event path)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Third milestone of the greenfield rewrite. The Bridge is a standalone Node
process that watches ~/.claude/sessions/<TAB>.md and emits worker.idle
events to ~/.<APP_SLUG>/events.jsonl whenever an agent writes its
end-of-session handoff. Brain sees the events in real time via the M2
tail; existing daemon + agent-hook-bridge.sh keep running untouched.
home/watcher.ts fs.watch SESSIONS_DIR with 250ms debounce. Parses the
standard handoff (done/next/tests/todos/health) out of
the .md file and emits {kind:"worker.idle", project,
handoff}. Seeds lastMtime at boot so existing files
don't replay; only changes from this process onward
emit. APP_SESSIONS_DIR env var overrides the path for
isolated testing.
home/emit.ts Single append-only writer to the JSONL log. Stamps id
(uuidv4) + ts (ISO) + v (=1) at write time. Uses a
DistributiveOmit<Event, K> so the kind-specific fields
(handoff, outcome, prompt, …) stay attached to their
discriminant — naked Omit collapses the union.
Observer-only by design. M3 deliberately does NOT:
- modify any Claude hook script
- touch /tmp/agent-* sentinels (legacy daemon keeps using them)
- replace the existing cockpit-daemon or agent-hook-bridge
After M3 proves stable in parallel, M4 deletes the redundant legacy paths
(stop hook stops writing /tmp/agent-ready-* once the watcher is the SSOT).
Run side-by-side:
npx tsx home/server.ts # the Brain
npx tsx home/watcher.ts # the Bridge
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Second milestone of the greenfield rewrite. A standalone Node HTTP server
in home/ that boots, tails ~/.<APP_SLUG>/events.jsonl, projects each event
into per-project state, and serves a minimal status UI at localhost:3001.
No external deps beyond node:* and the existing zod via @/lib/events.
home/state.ts pure applyEvent(state, event) → state — testable in
isolation; project view stays minimal (currentRun,
lastHandoff, recentOutcomes ≤ 5) for M2
home/log.ts tail one JSONL file via fs.watch + position tracking;
replays existing content on boot, recovers from file
truncation, returns parse errors via onError instead of
throwing (so a garbled line doesn't kill the daemon)
home/server.ts HTTP server with /control HTML view + /api/state +
/api/health + /api/events (manual append for testing).
Vanilla JS in the HTML, no React yet — that lands when
the brain replaces the existing /control surface.
End-to-end verification (against ~/.cockpit/events.jsonl):
- worker.started → project appears with running pill
- worker.finished → pill clears, outcome glyph ✓ in streak,
handoff text shown
tsconfig.json includes home/**/*.ts so the existing tsc + eslint gates
cover the new code. Runs separately from the Next.js app — no port
collision, no Vercel involvement, no DB needed.
What this commit deliberately does NOT do:
- emit events (M4 — replace the agent stop-hook to append to the log)
- decide (M5 — pure decide() function over state)
- dispatch (M6 — wire bridge.dispatch back to a worker)
- persist beyond the log (state rebuilds from log replay on boot)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
First milestone of the greenfield rewrite (Brain-on-the-user's-machine,
append-only JSONL event log as the Worker⇄Bridge contract). No runtime
yet, no migration yet — just the wire-format contract that everything
downstream builds against.
src/lib/events.ts is the SSOT for:
- Versioned envelope (v=1, id, ts) so future schema changes are explicit
- WorkerStarted / Progress / Idle / Finished / Crashed (worker → log)
- BridgeDispatch / BridgeCancel (brain → log)
- BrainOutcome (brain projection)
- parseEvent(line) — never throws; returns structured error on bad lines
- serializeEvent(event) — JSON + newline, no surprises
Field reuses for compatibility with existing infra: the Handoff shape
matches session.md fields, the Outcome enum matches orchestration_runs.outcome,
the Adapter enum matches src/lib/orchestration.ADAPTERS. So the new system
can ingest events from the current daemon during migration without
translation.
Why this lands alone: the whole architecture downstream — the local Brain
server, the Bridge tail, the new Worker hooks, the decide() function —
all depend on these types being right. Easier to redline 170 lines of
zod schemas now than 5 files of runtime later. M2 (local Brain skeleton)
builds on this.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>