Commit Graph
8 Commits
Author SHA1 Message Date
g-but 27f31cb664 feat(handoff): agent-driven auto-inject gate via status field — model-agnostic
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.
2026-05-20 09:23:41 +02:00
g-but 3ff199f67b test(home): pin the idempotency contract bd143e2's eager-apply relies on
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.
2026-05-20 07:14:09 +02:00
g-but 122f31e4fb fix(home): cancel-failure crash no longer drags confidence down via recentOutcomes
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.
2026-05-20 05:40:33 +02:00
g-but e81d9ee1d7 fix(home): relabel cancelled runs as user_abort so confidence isn't poisoned
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.
2026-05-20 05:01:07 +02:00
g-butandClaude Opus 4.7 b3c72d9bf4 feat(home): surface worker.crashed error message in /api/state + UI
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>
2026-05-20 04:08:50 +02:00
g-butandClaude Opus 4.7 466f558ce6 feat(home): surface dispatch reason + confidence in the UI
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>
2026-05-20 03:10:45 +02:00
g-butandClaude Opus 4.7 79855288f5 feat(home): state.ts handles bridge.dispatch / bridge.cancel + self-test
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>
2026-05-20 03:00:01 +02:00
g-butandClaude Opus 4.7 aeeaa466f7 feat(home): M2 — local Brain skeleton (tail event log → project state → /api/state)
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>
2026-05-20 01:23:03 +02:00