mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 12:27:28 +01:00
35adca22a8da170bc47ba6e4938bb9c5ffbcc2e3
10
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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.
|
||
|
|
00058f9b64 |
fix(home): clean up runId sentinel on inject failure so it doesn't leak to later sessions
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 (
|
||
|
|
fb6d5a08a7 |
fix(home): wire runId end-to-end so cancelled runs actually get relabelled
The cancelledRunIds → user_abort relabel I shipped in |
||
|
|
4551933e32 |
fix(home): cancel failures emit worker.crashed so they surface in the UI
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.
|
||
|
|
7ecbc0f1f6 |
fix(home): require --start flag to boot — naked invocations now exit cleanly
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. |
||
|
|
dd382eb884 |
feat(home): wire bridge.cancel end-to-end — POST /api/cancel + worker Ctrl+C + UI button
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.
|
||
|
|
63839d1485 |
fix(home): worker.crashed terminates the runId so failed dispatches don't loop
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). |
||
|
|
ca2e62945f |
feat(home): bridge.dispatch can declare the adapter; worker echoes it
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>
|
||
|
|
e179110aa3 |
fix(home): worker re-injected resolved dispatches on restart
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>
|
||
|
|
338237608c |
feat(home): M8 — worker.ts consumes bridge.dispatch events and injects via zellij
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>
|