Commit Graph
234 Commits
Author SHA1 Message Date
g-but fb6d5a08a7 fix(home): wire runId end-to-end so cancelled runs actually get relabelled
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.
2026-05-20 05:49:41 +02:00
g-but 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.
2026-05-20 05:19:35 +02:00
g-butandClaude Opus 4.7 a088cce6c9 fix(home): stop-hook emit_worker_finished filters to registered projects
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>
2026-05-20 03:41:39 +02:00
g-butandClaude Opus 4.7 d563d29968 feat(home): one-command launcher for the three home/ processes
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>
2026-05-20 02:34:25 +02:00
g-butandClaude Opus 4.7 43c40bf772 feat(home): M4 — agent stop hook also emits worker.finished to the local log
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>
2026-05-20 01:41:46 +02:00
g-butandClaude Opus 4.7 bebc82ffcf refactor(brand): zsh typing-hook contract derived from APP_SLUG
Last hidden 3-way contract between brand and runtime:

  scripts/install-cockpit-hooks.sh   writes hooks that emit
                                     /tmp/cockpit-typing-<PANE_ID>
  src/lib/zellij.ts                  reads files starting with cockpit-typing-
  scripts/cockpit-daemon.sh          (already routed)

If a rename only touches the install script, existing user shells keep
writing the old prefix while zellij.ts reads the new one — dispatch fires
while the user is typing, garbling input. No static gate would catch it.

Both sides now derive from APP_SLUG. The install script sources _brand.sh
and uses unquoted heredoc with backslash-escaped $-references so the
generated .zshrc block has APP_SLUG baked in literally at install time
(no dependency on the user having APP_SLUG exported at shell startup).
The MARKER + function names + tab variable name + tmp path are all
slug-derived.

After a rename, users need to re-run install-cockpit-hooks.sh to refresh
their .zshrc with the new prefix. The new MARKER means the install is
detected as fresh, not idempotent — by design, since the old hooks need
to be manually removed or they'll keep writing the old prefix.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 00:19:28 +02:00
g-butandClaude Opus 4.7 a7abd67c69 refactor(brand): WM_CLASS contract derived from APP_SLUG
scripts/cockpit-beacon-window.sh launches chromium with --class=cockpit-beacon
and both /api/beacon/window/{show,hide} search by that exact class to find and
move the pre-warmed window. The string was hardcoded in three places — a
rename would silently break beacon visibility (window/show/hide would find
zero matches and no-op).

Now derived from APP_SLUG in all three places (BEACON_WM_CLASS const). The
shell script sources scripts/_brand.sh; both route files compute the same
string from src/config/brand.ts. A rename flips all three together.

Also routed in this commit:
- COCKPIT_BEACON_URL / COCKPIT_BEACON_PROFILE → _brand_env BEACON_URL / BEACON_PROFILE
  (so APP_BEACON_URL is the new spelling, legacy still works)
- /tmp/cockpit-beacon dir → _brand_tmp 'beacon'
- "cockpit-app unreachable" log → "${APP_SLUG}-app unreachable"
- profile dir default ~/.config/cockpit-beacon-profile → uses APP_SLUG

The beacon launch + show/hide endpoints have to be restarted together after
a rename — the running browser still carries the old WM_CLASS until the
window-launcher script is restarted.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 00:02:32 +02:00
g-butandClaude Opus 4.7 9ee1df41c3 refactor(brand): broker the brand through one TS + one shell SSOT
Audit before this commit: 642 case-insensitive 'cockpit' refs across 119
files; only 2 callers actually used src/config/brand.ts. A rename was an
hour of careful sed touching things like email templates, auth UI copy,
/tmp paths, env var names, log prefixes — easy to miss one.

After this commit: every UI string, every /tmp sentinel, every env var,
and every shell log prefix derives from one of two files:

  src/config/brand.ts    APP_NAME · APP_SLUG · APP_DOMAIN · APP_EMAIL_FROM
                         APP_KICKER · APP_DESCRIPTION · APP_TAGLINE
                         APP_URL · APP_PROFILE_URL(username)
  scripts/_brand.sh      $APP_NAME · $APP_SLUG · $APP_DOMAIN
                         _brand_env <KEY> <default>  → $APP_<KEY> || $COCKPIT_<KEY>
                         _brand_tmp <name>           → /tmp/$APP_SLUG-<name>

UI broker (TS): SignInForm, project-intent-panel, bootstrap-modal-steps,
AgentTokenSettings, setup/page, whitepaper/page, /u/[username]/page,
invite/layout, beacon/live/BeaconLiveClient, api/project/bootstrap, and
src/lib/email all import APP_NAME from brand.ts. /tmp paths in
agent-config:stateFile.run, control/sleep-mode/route, control/auto-continue/route,
beacon/route, beacon/sse/route derive from APP_SLUG.

Shell broker: cockpit-daemon.sh and agent-hook-bridge.sh source _brand.sh,
read env via _brand_env (so APP_DAEMON_TOKEN and APP_BASE_URL work alongside
the existing COCKPIT_* names), write /tmp paths via _brand_tmp, log under
[$APP_SLUG-daemon] / [$APP_SLUG-bridge].

Env aliases (TS): src/lib/brand-env.ts mirrors _brand_env. src/lib/constants,
src/lib/daemon-auth, src/lib/session, src/auth.config (Edge), and
api/beacon/transcribe all resolve env via the alias scheme. Existing
COCKPIT_*-prefixed env vars on machines in the wild keep working — APP_*
takes precedence when both are set.

To rebrand the entire product after this commit: edit APP_NAME / APP_SLUG /
APP_DOMAIN in src/config/brand.ts AND in scripts/_brand.sh, swap the
vercel.json alias, point DNS at the new registrar. That's it — no other
code touches the name.

Out of scope (deliberately): content/* essays and whitepaper.md (editorial
voice, not mechanical), README.md (would distract from this commit's
purpose), .env example DATABASE_URL (config value, not code), file names
themselves (CockpitMark.tsx, cockpit-daemon.sh — those become git mv after
a chosen new name).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 23:01:11 +02:00
g-butandClaude Opus 4.7 93e72d9f78 fix(daemon): COCKPIT_DAEMON_FORCE_REMOTE to pin daemon to cloud Cockpit
_base_url() prefers $_LOCAL_URL when /api/health responds, which is the
right default when the user runs everything locally. But when a local
Next.js dev server is up alongside a *different* cloud Cockpit (the
common case for cockpitapp.vercel.app users), the daemon ends up pushing
runtime state and claiming commands from the local DB while the user
watches the cloud — daemonLastPushedAt on cockpitapp.vercel.app stays
frozen for days even though the daemon is healthy.

Add a single env var that skips the local probe entirely. _init_base_url
logs the choice so it shows in the daemon log line at startup.

Verified locally: /api/health responds on localhost:3000 with
{"ok":true,"runtime":true}, but POST /api/control/runtime-state on
cockpitapp.vercel.app already returns {"ok":true,"count":0} with the
daemon bearer — so the moment the user restarts the daemon with the
flag set, state will land on the cloud control panel for the first
time since the schema-drift fixes landed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 22:11:32 +02:00
g-butandClaude Opus 4.7 a003696e7c fix(orchestration): close outcome-tracking loop in cloud mode
Verifying the sleep-mode loop surfaced this gap: cloud-mode dispatches go
through pending_commands and never created an orchestration_runs row, so
agent-hook-bridge.sh:finish_orchestration_run silently no-opped on Vercel
(no /tmp/cockpit-run-<tab> sentinel was ever written).

- InjectPayload gains an optional runId so the run id can be threaded from
  server-side dispatch to the local daemon over the pending-commands queue.
- /api/orchestration/run cloud-mode block now creates a tracked run row
  before enqueueing (mirroring the local-mode path), excluding lifecycle
  intents. runId is returned to the caller so the client can correlate.
- cockpit-daemon.sh:inject case reads payload.runId and writes the
  /tmp/cockpit-run-<tab> sentinel before execute_inject, so the existing
  stop hook closes the loop unchanged.

With this, the next live agent run dispatched from cockpitapp.vercel.app
will produce its first end-to-end outcome row.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:52:06 +02:00
g-butandClaude Opus 4.7 8d43bb042b feat(beacon): honor sleep-mode sentinel in handle_stop
Close the loop on Sleep Mode v1. The web-app side (Moon toggle in /control)
already writes /tmp/cockpit-sleep-mode via POST /api/control/sleep-mode and
short-circuits the ReadyBanner countdown to 0 in the browser. The local
stop hook was still launching the popup regardless — so a user who flipped
sleep mode and closed the lid would come back to a stale popup.

Adds a single check between the popup-mode and min-idle gates: if the
sentinel exists, log + exit 0 (matching the existing 'disabled' semantic).
The browser-side ReadyBanner continues to auto-inject as long as Cockpit
is open in any tab — no other change needed for the loop to close.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:40:56 +02:00
g-butandClaude Opus 4.7 37826adef6 feat(orchestration): per-dispatch outcome tracking
Foundation for the autonomous-dispatch loop — every prompt dispatched into a
zellij tab now produces an outcome row that downstream logic can learn from.

- orchestration_runs gains an `outcome` column (success/partial/error/hang/
  user_abort/timeout) plus a partial index on (user_id, project_key, finished_at)
  scoped to finished rows, sized for the "last 5 outcomes" lookup.
- inferOutcome() classifies a session handoff (done/next/tests/todos/health)
  + durationMs + error into one of the six outcomes. Pure, no I/O.
- Every dispatch for claude/codex/gemini adapters now creates a run row at
  inject time and writes the run id to /tmp/cockpit-run-<tab>. Lifecycle
  intents (hard_stop / close_session) are deliberately not tracked.
- New endpoint POST /api/orchestration/runs/[id]/finish closes a run with
  inferred (or explicit) outcome + summary.
- agent-hook-bridge.sh:handle_stop reads the run sentinel and posts the
  session handoff back. Fire-and-forget, never blocks the stop hook.

The visible side of this loop (dispatch reasoner ingestion + ProjectCard
streak chip) ships in the next commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:03:34 +02:00
g-butandClaude Sonnet 4.6 69da4bc9a4 fix(beacon): use xdotool --sync for unmap; simplify beacon.py window logic
Replace the 10s polling loop (20 × 0.5s sleeps) with `xdotool search --sync
--onlyvisible` which blocks until the window actually appears — no fixed
timeout, no race on slow machines. Guard the xdotool block so the script
stays functional without it installed.

beacon.py no longer cold-spawns its own browser window (that path created
rogue, untargetable windows when the service wasn't running). Instead it
ensures the cockpit-beacon-window.service unit is active (idempotent systemctl
start) and pings /api/beacon/window/show — SSE drives the same path from React,
this is belt-and-suspenders to minimise perceived latency.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 17:18:57 +02:00
g-butandClaude Sonnet 4.6 ca0a002129 fix(beacon): use windowunmap for hide; unmap on first appear
Three issues with the off-screen pre-warm approach:

1. cockpit-beacon-window.sh was using exec (replaced process), so the
   background unmap watcher couldn't run. Changed to background & with
   an explicit wait so the watcher subshell can poll for the window
   and unmap it the moment it appears, preventing any initial flash.

2. hide/route.ts was using windowmove -32000,-32000 to "hide" the
   window. KDE Plasma/KWin clamps offscreen positions back to the
   nearest visible screen edge, so the window was never truly hidden.
   Switched to windowunmap (X11 visibility off) — works reliably.

3. show/route.ts was calling windowmap after windowmove. Moving an
   unmapped window is silently ignored by the WM. Reordered to
   windowmap --sync first, then windowmove/activate/raise.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 16:58:57 +02:00
g-butandClaude Sonnet 4.6 41851c3877 fix(beacon): prevent session race + xdotool visibility on Wayland
Two bugs in the beacon popup:

1. Race condition in BeaconLiveClient: handleClose scheduled
   setSession(null) after 1500ms unconditionally. If a new SSE session
   arrived during that window, the setTimeout would overwrite it with
   null, silently killing the next popup. Fixed with a functional
   updater that only clears if the closing session's ID still matches.

2. Wayland/xdotool invisibility: cockpit-beacon-window.sh was launching
   chromium as a native Wayland window (on KDE Plasma, chromium defaults
   to Wayland for --app windows). xdotool is X11-only and cannot find
   or move Wayland-native windows, making /api/beacon/window/show and
   /hide silently no-op. Fixed by unsetting WAYLAND_DISPLAY and passing
   --ozone-platform=x11 so the window runs through XWayland instead.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 16:53:03 +02:00
g-butandClaude Sonnet 4.6 c039c458da feat(beacon): window show/hide API routes for off-screen pre-warm
/api/beacon/window/show moves the pre-warmed chromium window on-screen
and raises it; /api/beacon/window/hide moves it off-screen (-32000,-32000).
BeaconLiveClient calls these whenever session state changes, so the popup
appears fully populated with no Standby flash visible to the user.

The service script already launches chromium with --class=cockpit-beacon
and --window-position=-32000,-32000 so xdotool targets the right window.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 16:31:14 +02:00
g-butandClaude Sonnet 4.6 da2e1aec6d fix(beacon): service script writes PID file so beacon.py skips xdotool on repeat calls
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 15:43:07 +02:00
g-butandClaude Sonnet 4.6 6c64bea29e fix(beacon): focus service-managed window before cold-spawning browser
When cockpit-beacon-window.service manages the pre-warmed Chromium window,
it never writes _LIVE_PID_FILE. The old code would fail the PID check and
spawn a duplicate window alongside the running one. Now: try xdotool/wmctrl
focus first, only cold-start if no window is found.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 15:40:08 +02:00
g-butandClaude Sonnet 4.6 8a5e94e451 feat(settings): profile/account split, location model, connected accounts
- Split ProfileSettings into Profile (public identity) and Account (auth/security) tabs
- Add LocationSettings with two-tier model: homeCity/timezone/locale + currentCity/timezone/until for travelers
- Add AccountSettings with email display, password change, connected OAuth providers, danger zone
- New SettingsTabs with 7-tab horizontal nav (Profile · Account · Location · Agent · Projects · Team · Billing)
- New user_preferences DB table with getUserPreferences/upsertUserPreferences query functions
- New API routes: GET/PATCH /api/me/preferences, GET/DELETE /api/me/connected-accounts/[provider]
- Wire user's active city into weather API; active timezone into cron default
- beacon: replace "Waiting for Claude…" spinner with clean Standby screen (logo + text)
- beacon: fix grep pipeline crash in agent-hook-bridge.sh (|| true guards), fix token lookup
- beacon: fix _PROJECT_ROOT via agent-projects.conf, fix auto-start without zenity dialog

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 15:16:18 +02:00
g-butandClaude Opus 4.7 41a1c5b1d6 refactor(beacon): finish PyQt retirement, drop zenity start-cockpit popup
Web popup at /beacon/live is the sole popup surface. Deletes the dead
PyQt vendored modules, the foreign-UI zenity/kdialog/notify-send dialog
that asked the user whether to start Cockpit, and the PyQt-import gates
in the install/smoke/runtime check scripts. The session JSON is now
written unconditionally; if Cockpit is unreachable, beacon.py
fire-and-forgets `systemctl --user start cockpit-app` and exits — the
session surfaces via SSE once the service is up.

Also fixes a pre-existing react-hooks/purity error in StuckGoalsCard
(impure Date.now() inside server component body) that was blocking the
pre-commit lint hook for the whole repo.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 14:55:25 +02:00
g-butandClaude Sonnet 4.6 d362b964fd feat(beacon): per-user DB-backed settings — popup mode, countdown, idle gate, transcription
Moves beacon settings from a shared machine file to a per-user `beacon_settings`
Postgres table so every account has independent control. Adds `popup_mode` (web /
pyqt / both / disabled) with pros/cons shown in the settings UI.

- New `beacon_settings` table (userId unique FK, all existing fields + popup_mode)
- `db/queries/beacon-settings.ts` — getBeaconSettings / upsertBeaconSettings
- GET /api/beacon-settings now requires auth; both verbs read/write DB
- beacon.py reads popup_mode via get_popup_mode() and gates PyQt / web accordingly
- _beacon_config.load_settings() fetches from API with 5-min /tmp cache, falls back
  to legacy file when Cockpit is offline
- agent-hook-bridge.sh fetches settings via Bearer token; exports BEACON_POPUP_MODE;
  both stop and notification handlers gate immediately on popup_mode=disabled
- Settings page: 4-card popup mode selector with per-option pros/cons descriptions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 11:24:11 +02:00
g-butandClaude Sonnet 4.6 6c87676f7e feat(beacon): configurable idle gate — default 0 (always show popup)
Replace hardcoded 60s idle threshold with min_idle_seconds setting.
Default is 0 which fires the popup every session end regardless of
keyboard activity. Setting lives in beacon.json, surfaced in Settings UI.
Both the stop-hook beacon and the notification auto-inject respect it.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 10:50:25 +02:00
g-butandClaude Sonnet 4.6 3d4a1d00b1 perf(daemon): long-poll for commands, change-detection for state push
Command pickup latency: 5s → ~100ms. The API now holds requests for up to
25s (local) / 8s (remote Vercel) until a command arrives, eliminating the
sleep-then-poll cycle. The push loop skips the POST when state is unchanged
(md5 hash comparison), cutting idle DB writes from ~30/min to near zero.
After each command execution, a background push fires immediately so the UI
reflects results without waiting for the next push cycle.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 09:28:41 +02:00
g-butandClaude Sonnet 4.6 3c5c8cb346 fix(daemon): execute_inject now clears closing sentinel and cancels beacon on re-dispatch
Non-lifecycle cloud-queued injects had the same gap as the run route (fixed
in 0bc9cd8): stale closing sentinel persisted, keeping UI in "Closing…" state.
Also cancels any open web-beacon popup for the tab (mirrors cancelActiveBeaconSessions)
so the React beacon client self-closes when a new task is injected remotely.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 04:57:00 +02:00
g-butandClaude Sonnet 4.6 5d514730b1 fix(hook-bridge): patch_project_state was always 401 — add Bearer auth
Route used getSessionUserId() (cookie-only); hook bridge sent no auth header.
Switch route to getApiUserId() (cookie + Bearer) and read COCKPIT_DAEMON_TOKEN
from env or .env.local fallback in patch_project_state curl call.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 04:27:37 +02:00
g-butandClaude Sonnet 4.6 585eae54d5 fix(beacon): notification handler respects health gate before queue dequeue
The notification auto-inject path dequeued queue items before reading session
health, so a critical/degraded health state was ignored and queue items fired
when they shouldn't. Moved the health read before the queue dequeue check and
gates the dequeue on auto_key=next_best — mirroring sessionHealthBlocksQueue()
on the client and the server-side gate in /api/orchestration/run.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 04:03:39 +02:00
g-butandClaude Sonnet 4.6 5e4af110b8 fix(cloud): daemon now pushes session content (done/next/health/tests) to DB
In cloud mode (Vercel), session content was never populated in DB —
the runtime-state route only accepted agent/lifecycle fields, and the
daemon only pushed those. The UI showed empty done/next/health/tests
in the ReadyBanner and ClosedBanner for all cloud-mode users.

Daemon reads ~/.claude/sessions/<tab>.md per project each push cycle and
merges sessionDone/Next/Tests/Todos/Health/UpdatedAt into the payload when
the file exists. Route extended to accept and pass these fields through to
upsertProjectState (absent = skip, present = update).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 03:55:03 +02:00
g-butandClaude Sonnet 4.6 6f2c2b3e0c fix(daemon): write current-prompt file after cloud-queued inject
execute_inject injected prompts but never wrote /tmp/agent-current-prompt-<tab>,
so the UI showed no running banner for cloud-queued tasks. Now reads promptLabel
from the payload (already stored by enqueueInjectCommand) and writes the file
after a successful inject, mirroring what the local inject/run routes do.
Skipped for hard_stop and close_session (session-ending, not task-starting).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 03:47:01 +02:00
g-butandClaude Sonnet 4.6 f7a3ccc0e4 fix(daemon): use original-case tab name for sentinel files in execute_inject
Cycle 2 used tab_lower (lowercase) for all /tmp sentinel writes, but the
stop hook and push_runtime_state both read them with the original-cased tab
name (from zellij / conf). The case mismatch meant the stop hook never found
the close_session sentinel, so it showed the beacon popup and wrote readyAt
instead of closedAt — defeating the cycle 2 fix entirely.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 03:37:27 +02:00
g-butandClaude Sonnet 4.6 820d29fbf8 fix(daemon): write close_session/hard_stop sentinel files in execute_inject
When the daemon processes an inject command from the cloud queue, it had
the promptKey but never wrote the sentinel or closing files.  The stop
hook would then treat the session end as a normal completion (readyAt +
beacon popup) instead of writing closedAt.

Mirrors the same fix applied to /api/orchestration/run for the local path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 03:10:27 +02:00
g-butandClaude Sonnet 4.6 4609e63666 fix(ssot): unify session handoff todos format across all dispatch paths
agent-config.ts (buildPromptWithSession), renderers.ts (openclaw path),
and cockpit-daemon.sh (_resolve_prompt) all emitted "todos: <count>"
while agent-hook-bridge.sh, install-beacon.sh, and prompt-library.ts
all emitted "todos: <count> TODOs". Agents dispatched from the web UI
would write "todos: 0" while beacon-fired agents wrote "todos: 0 TODOs",
producing inconsistent session files depending on which dispatch path ran.

Standardised on "todos: <count> TODOs" (the format present in all actual
session files and the majority of the emit sites).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 02:02:09 +02:00
g-butandClaude Sonnet 4.6 86c5ca661a feat(daemon): add --restart flag to install-daemon.sh for code-change reloads
The daemon runs directly from the repo scripts/, so after committing
changes to cockpit-daemon.sh or agent-hook-lib.sh the service must be
restarted to load the new code. Without this flag there was no quick
path — the full installer re-generates the service file unnecessarily.

Also restarted the running daemon which had been running stale code
since before the bc07b0a / 3ac1f01 reliability fixes were committed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 01:29:47 +02:00
g-butandClaude Sonnet 4.6 7b189ef4c9 fix(beacon): add notify-choice.py and get-idle-secs.py to install sync list
Both files are referenced by agent-hook-bridge.sh via \$SCRIPT_DIR and
were already present in the installed location from a prior install, but
were missing from _copy_scripts() — meaning --sync would never update
them when they change. Added to the canonical copy list alongside the
other bridge-referenced scripts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 01:12:00 +02:00
g-butandClaude Sonnet 4.6 f3e706875e fix(beacon): fix two runner script bugs blocking codex/gemini switches
run-codex-task.sh passed --ask-for-approval which only exists on the
interactive codex CLI, not codex exec — causing immediate failure on
every switch. Also both runner scripts computed ROOT=parent-of-scripts-dir
which resolves to ~/.local/share when installed, making the stop-hook
call (agent-hook-bridge.sh) silently fail every run. Fixed to use
SCRIPT_DIR (same directory as the runners) which works both in the
repo and from the installed ~/.local/share/cockpit-beacon/ location.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 01:03:02 +02:00
g-butandClaude Sonnet 4.6 dbe471ed1f fix(beacon): install run-{codex,gemini}-task.sh and sync-agent-runtime-config.py
install-beacon.sh was missing three scripts that agent-hook-bridge.sh
references via \$SCRIPT_DIR:
  - run-codex-task.sh / run-gemini-task.sh — agent-hook-bridge.sh
    constructs 'bash \$SCRIPT_DIR/run-{agent}-task.sh ...' and injects
    it into the terminal for Codex/Gemini switches; without the file
    present the injected command fails silently
  - sync-agent-runtime-config.py — called at bridge startup (non-fatal
    but missing from the install location)

Also DRY the install: extract _copy_scripts() so --sync and the full
install share a single list, eliminating the previous duplication.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 00:50:08 +02:00
g-butandClaude Sonnet 4.6 23ecd45251 feat(beacon): add --sync flag to install-beacon.sh for lightweight re-deploys
Full install is too heavy for day-to-day script updates — it re-creates
hook files and reruns dependency checks. --sync copies only the runtime
scripts (beacon.py, _beacon_config.py, agent-hook-bridge.sh, etc.) to
~/.local/share/cockpit-beacon without touching hooks or config.

Also synced the installed scripts to pick up all 4 recent fixes:
- agent-hook-bridge.sh: reliable switch (send_raw_key_to_tab+inject_prompt)
                        + capacity sentinel write in handle_notification
- agent-hook-lib.sh: grep -qxF exact-line fix in _find_session_for_tab
- beacon.py: nextAgent/capacityIssue computed in local session creation
             + _check_capacity_sentinel
- _beacon_config.py: looks_like_capacity_issue() + resolve_next_agent()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 00:41:56 +02:00
g-butandClaude Sonnet 4.6 11a368d989 fix(beacon): wire Claude Code rate-limit notifications into capacityIssue detection
The Notification hook receives a 'message' field from Claude Code (e.g.
"Claude is at capacity. Please try again in 60 seconds.") but the bridge
never read it, so capacity issues were invisible to the auto-switch system.

Fix: handle_notification now extracts 'message', regex-matches it against
rate-limit phrases (same set as looksLikeAgentCapacityIssue), and writes
/tmp/agent-capacity-issue-<tab> with a timestamp when matched.

beacon.py reads and clears this sentinel in _write_beacon_session so the
beacon session gets capacityIssue=true, triggering the auto-switch countdown
instead of the normal continue prompt. Sentinel expires after 5 minutes so
a missed stop hook doesn't poison the next unrelated session.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 00:27:27 +02:00
g-butandClaude Sonnet 4.6 955a082702 fix(beacon): compute nextAgent + capacityIssue in local session creation
beacon.py writes sessions directly to /tmp when Cockpit is running locally,
bypassing the TypeScript API. It hardcoded nextAgent: null and
capacityIssue: false, silently breaking the auto-switch-on-capacity-issue
flow that the user specifically asked for.

Add looks_like_capacity_issue() and resolve_next_agent() to _beacon_config.py
as Python mirrors of the TypeScript equivalents in src/lib/agent-registry.ts,
and wire them into _write_beacon_session(). The "capacity issue" banner and
auto-continue switch now fire correctly in the local path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 00:17:22 +02:00
g-butandClaude Sonnet 4.6 16d0b80136 fix(beacon): reliable agent switch in stop hook — use send_raw_key_to_tab + inject_prompt
switch_agent_and_continue had the same fragile fixed-sleep pattern as the
TypeScript route and daemon already fixed: manual go-to-tab + sleep 0.2 +
write 3 + sleep 0.1 + write-chars + sleep 0.1 + write 13 racing against
async tab focus.

Replace with:
- send_raw_key_to_tab for Ctrl+C (handles session discovery + tab focus)
- inject_prompt for launch command (polls dump-layout until focused)

This is the third and final execution path for agent switching. All three
paths (TypeScript route, daemon, beacon hook) now use the same reliable
pattern.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 00:08:16 +02:00
g-butandClaude Sonnet 4.6 bc07b0ae74 fix(daemon): 6 correctness fixes from engineering audit
- grep -qixF (exact-line, case-insensitive) in tab_open check and
  _find_session_for_tab — -qiF was a substring match so 'cockpit'
  incorrectly matched 'cockpit-dev'
- --max-time 15/10/8 on claim_next, mark_done, push_runtime_state
  curl calls — missing timeouts let the main loop hang indefinitely
  if the server is unresponsive
- codex default model: codex-4-5 → gpt-5.4 to match agent-registry.ts SSOT
- _is_agent_running_in_dir rewritten to delegate to _scan_agents,
  eliminating the duplicate /proc walking logic

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 23:57:17 +02:00
g-butandClaude Sonnet 4.6 3ac1f017e6 fix(daemon): reliable switch_agent — poll /proc + Ctrl+C fallback
Mirrors the reliability fix applied to the TypeScript switch-agent route
(aa3a743) for the daemon execution path (cloud → daemon → local zellij).

Previously execute_switch_agent used a fixed `sleep 1` after injecting
the quit command, with no verification the old agent actually exited.
If the agent was stuck on a permission dialog the new agent's launch
command would be typed straight into the running session.

Changes:
- cockpit-daemon.sh: adds _is_agent_running_in_dir() to scan /proc for
  the outgoing agent by basename+cwd; replaces sleep 1 with a 2s poll
  loop, then sends Ctrl+C (key 3) + 600ms grace if still alive.
- agent-hook-lib.sh: adds send_raw_key_to_tab() — raw keycode injection
  reusing existing session-discovery logic, parallel to inject_prompt().

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 23:41:29 +02:00
g-butandClaude Sonnet 4.6 97933e5b95 feat(daemon): install-daemon.sh converts daemon to systemd user service
Auto-discovers COCKPIT_DAEMON_TOKEN from .env.local, snapshots the current
login PATH so zellij/jq/ffmpeg are reachable, writes ~/.config/cockpit/daemon.env
(chmod 600) and a user service file, then enables and starts it. Supports
--uninstall. Replaces manual `COCKPIT_DAEMON_TOKEN=... ./scripts/cockpit-daemon.sh`

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 17:10:01 +02:00
g-butandClaude Sonnet 4.6 403b7f90b9 feat(orchestration): context-aware auto-inject + orient/unblock prompts + thoughts article
Hook changes:
- handle_notification now reads session health before picking which prompt
  to auto-inject: health=needs attention|critical → unblock, else → next_best
- Log line and write_inject_state both carry the chosen key and health value

New prompts in agent-prompts.json:
- orient: context reload — reads git log, tsc, session; outputs brief;
  no code changes. For resuming after breaks or context-limit compactions.
- unblock: stabilize before advancing — runs tsc + tests, fixes highest-
  severity failure, stops when baseline is green. Never auto-injects on
  healthy projects.

Thoughts article: "Prompts, Timing, and Orchestration: Where Agent Value
Actually Lives" — covers the decision tree, prompt taxonomy (auto-inject
candidates vs human-selected vs situational), queue-based injection
semantics, and what's still missing (velocity, time-of-day, multi-item
queue drain, inter-project coordination).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 13:38:32 +02:00
g-butandClaude Sonnet 4.6 d1517bffd2 fix(hooks): add queue dequeue to notification hook; improve next_best prompt
Two structural gaps:

1. handle_notification didn't check the queue before injecting next_best.
   If user dispatched a task from Control while Claude was running, the
   notification path would ignore it and inject next_best instead. Now
   mirrors handle_stop's slot-1 queue logic: dequeues and injects the
   first item atomically, skipping next_best entirely when a task is waiting.

2. next_best prompt was underspecified for the "nothing urgent" case.
   Added explicit priority order (type errors → uncommitted → session.next
   → discovery), expanded git log to -10, added tsc check as step 1, and
   replaced the vague "highest-impact gap" directive with a concrete
   discovery method: scan recent commits, find the adjacent broken thing.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 13:23:06 +02:00
g-butandClaude Sonnet 4.6 19c0fc8239 fix(hooks): notification hook fires next_best with session context instead of vague continue
continue prompt gave Claude zero context on what was in progress. next_best already
loads git state and prompts a context-aware resume; same rich session-file append
pattern as handle_stop. Also switches to emit_or_inject_prompt for AGENT_BRIDGE_EMIT_PROMPT
test compatibility and calls write_inject_state so Control panel reflects the injection.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 13:05:56 +02:00
g-butandClaude Sonnet 4.6 75bced70ab feat(beacon): write gitBranch into session JSON; show agent+branch chips in Python popup
- _beacon_config.py: add read_project_git_branch() (mirrors server-side parseProjectsConf logic)
- beacon.py: embed gitBranch in session JSON at write time so SSE/web consumers get it without a server-side lookup
- _beacon_popups.py: rewrite ContinuePopup header — green dot, project name, "Ready" badge, then chips row with agent chip + git branch chip; matches web beacon header exactly
- sse/route.ts: add git branch fallback enrichment for sessions written before this change

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 11:58:21 +02:00
g-butandClaude Sonnet 4.6 19374873e0 fix(beacon): unify countdown to SSOT — session carries configured value to web
Four issues fixed:
- BeaconSession now carries countdownSeconds (read from settings file in both
  the API route and beacon.py), so the web popup always shows the user-configured
  value instead of a hardcoded fallback
- DEFAULT_BEACON_COUNTDOWN_S changed from 30 → 12 to match Python COUNTDOWN_SECONDS;
  fallback is now consistent across all surfaces when no settings file exists
- BeaconClient uses session.countdownSeconds instead of AUTO_INJECT_S / URL param,
  eliminating the split between readyAt-path (12s) and URL-param-path (30s)
- useAutoContinue default changed false → true so new tabs start with auto-continue
  enabled, matching Python popup behaviour and isAutoContinueEnabledSync

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 09:32:57 +02:00
g-butandClaude Sonnet 4.6 5b00bd5595 test(smoke): add dynamic /api/projects/<id> coverage
GET /api/projects/[id] is the most-called endpoint in the app — every
project drawer open hits it. The static smoke test had no coverage for
it because the ID is runtime-derived. Reuses the same jq+curl pattern
used for /api/people/<id>: fetches the first entity project ID from
/api/user-projects, then hits the detail route and verifies it returns
2xx (or 401 without a session).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 03:17:30 +02:00
g-butandClaude Sonnet 4.6 e841c9a42f test(smoke): guard invitation middleware exclusion with regression check
Adds a smoke route check for /api/invitations/<bogus-token> that must return
404, not 401. If it returns 401 it means the middleware exclusion (api/invitations/)
regressed and new users can no longer accept team invitations. The check fails
loudly on 401, passing only on the expected 404 for an invalid token.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 03:00:51 +02:00
g-butandClaude Sonnet 4.6 50d760f772 chore(deploy): postbuild hook copies static assets + restarts cockpit-app service
`npm run build` alone left .next/standalone/ with stale CSS/JS chunks,
causing the production server to serve 404s until `install-app` was run
manually. The new postbuild hook runs deploy-local.sh automatically after
every build: copies .next/static and public/ into standalone, then
conditionally restarts the cockpit-app systemd service if installed.

No-ops cleanly on CI (no standalone dir) and on machines without the
service (systemctl check skipped). install-app is preserved for first-time
setup.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 22:14:33 +02:00