Commit Graph
4 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 bd143e2588 fix(home): close /api/dispatch race by eagerly projecting freshly-appended events
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.
2026-05-20 07:07:18 +02:00
g-but d0e120f2ea test(home): add self-test suite for emit.ts — the single append-only writer
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.
2026-05-20 06:08:45 +02:00
g-butandClaude Opus 4.7 e512b54a38 feat(home): M3 — Bridge layer (session-file watcher → worker.idle events)
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>
2026-05-20 01:33:39 +02:00