Multi-source polling forks one child per extra base URL (typically
http://127.0.0.1:3000 + https://cockpitapp.vercel.app). Each child's
push-failure budget exit (`kill -TERM "$$"`) only stops itself —
systemd supervises the parent, not the children — so a dead sibling
left its URL silently unpolled while the parent kept working its own.
Observed today: the Vercel-bound child exited at 08:44 after 30
network-error timeouts over a quiet ~1.5h. From then until restart,
dispatches from cockpitapp.vercel.app queued in Neon for ~14h with
nothing on the local end claiming them.
Fix has two parts:
- Parent records forked child PIDs and runs a 10s watchdog. When any
tracked child PID is dead, the parent SIGTERMs itself; systemd's
Restart=always + KillMode=control-group rebuilds the whole tree.
- Push timeout is now remote-aware (8s local, 20s https://) so a
Vercel cold-start tail doesn't burn the failure budget.
Smoke-tested: killing the Vercel child triggers the watchdog and the
whole tree restarts in ~13s.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
User clarified the actual product vision: autopilot is a TRUST LADDER,
not a config screen. Five levels, each adding one more thing Cockpit
decides on your behalf. The middle level (Beacon — popup + countdown
auto-pick) was orphaned by commit 848da6c "stop hook calls strategist
(no more popup race)" — that swap traded the popup race for a
loose-cannon strategist that fired AI-composed prompts without consent.
Bringing the popup back, without the old race (KDE D-Bus + Chrome
+ /tmp polling), since the SSE-driven Chromium window already
replaced the old multi-layer setup.
The five-level ladder, marketing-clear:
L1 Manual — only what you type (Free tier)
L2 Queue — drains your queue (Free tier)
L3 Beacon — popup + countdown (Pro $20/mo) ← new default
L4 Continuous — auto-fires next-best (Pro $20/mo)
L5 Mission — Groq composes from
mission/goals/roadmap (Mission $50/mo)
Concrete changes this commit:
- src/config/beacon.ts: AUTO_INJECT_MODE_VALUES gains "beacon" (the
popup level). All five values have user-facing labels Manual / Queue
/ Beacon / Continuous / Mission with description lines that name the
level number and the sales-grade one-line pitch.
- src/lib/constants/control.ts: DEFAULT_AUTO_INJECT_MODE flips from
"strategist" (L5) to "beacon" (L3). New users start at the right
trust level — Cockpit shows them every dispatch through a popup
with countdown auto-pick, so they earn confidence in the system
before opting into Continuous or Mission.
- scripts/agent-hook-bridge.sh:
• autopilot_dispatch_and_inject() gains a new branch for
mode="beacon": calls ./beacon.py stop $tab $session_file, captures
the user's choice (or countdown auto-pick) on stdout, then
dispatches via emit_or_inject_prompt with the chosen prompt key.
Custom prompts come back as "__custom__<body>".
• Bash defaults for _BEACON_AUTO_MODE change from "strategist" →
"beacon" in both the API-fetch path and the Python-config
fallback path, so a fresh install with no settings row lands at
L3, not L5.
- src/components/control/AutomationPolicyControl.tsx: MODE_STYLE record
gains the "beacon" case (cyan-dot, pulsing). Tooltips for all five
cases rewritten with the level number + the one-line pitch so
hovering the pill teaches the trust ladder.
- src/components/control/ControlFleetStatus.tsx: AUTOMATION_HINT
record gains the "beacon" case. Hints under the fleet chips now
describe the level in plain English (was: jargon like "strategist
composes context-aware prompts" → now: "Mission — Cockpit composes
context-aware prompts from project mission, goals, and history").
Note: the existing "strategist" code value is preserved as the L5
storage key. Mission as a customer-grade feature still needs the
work tracked in roadmap "## Proposed": project context loader,
quality gate, audit trail, sleep budget, trust score. Today's commit
is just the ladder + the missing beacon wire.
beacon.py itself was already installed at
~/.local/share/cockpit-beacon/beacon.py (orphaned since 848da6c);
this commit puts it back in the call path.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
User shared live revamp-it transcript: autopilot was firing the
next_best Setup template at the agent every ~1-2 min, the agent
had nothing to do (branch in sync, no blockers, deploy live), so
it wrote the same ready handoff each iteration, and the cycle
repeated indefinitely. Wasted Claude tokens, wasted agent
attention, surfaced as user-visible noise.
The status:working + blocker gates shipped earlier today
(b89fdfc + 7ded0c2) couldn't break this loop because the AGENT
itself writes status:ready each iteration — the gate is correctly
open. The missing primitive was an absolute MINIMUM INTERVAL
between consecutive autopilot fires for the same project,
independent of handoff content.
scripts/agent-hook-bridge.sh:autopilot_dispatch_and_inject() now
maintains a sentinel file per tab at /tmp/cockpit-daemon/last-
autopilot-<tab>. Default cooldown is 300s (5 min); override via
COCKPIT_AUTOPILOT_COOLDOWN_S. When the file's mtime is younger
than the cooldown, autopilot refuses the fire and logs
"cooldown 12s/300s for <tab> — staying idle". Manual dispatches
via the UI bypass this (they go through /api/orchestration/run
which has its own gates) — the cooldown only governs autopilot's
own decision to compose-and-inject.
Concrete effect: revamp-it can fire at most once per 5 min, so
the agent gets 5 min of breathing room to actually do work
before the next prompt arrives. If 5 min is too aggressive for a
healthy project, the env var lets the user tune it.
Roadmap "## Proposed" entry "Autopilot fires uncoordinated across
ALL zellij tabs" can be partly closed by this — it's the option
(2) per-tab cooldown solution. Options (1) global kill switch
and (3) decision-attestation queue are still open and have their
own design merits, but this is the minimum fix that breaks the
worst current symptom.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Browser dogfood 2026-05-31: user typed into the /control textarea
"Fix the 'Saved agent context Xw ago' wording — it sounds like a
security leak. Use 'Idle · last active Xw ago' instead." Caught
that the label was opaque jargon — it describes the INTERNAL
data state ("we have a saved handoff blob") rather than the
OBSERVABLE state for the human reader ("the agent is idle").
control-presenter.ts:563 — handoff-present-but-no-live-observation
case now reads "Idle" instead of "Saved agent context". The row's
timestamp column already shows recency (Xw ago) so the prefix
doesn't need to duplicate it.
Test updated to match the new wording. 19/19 stays green.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
User audit 2026-05-31 surfaced three loud noise sources in the
project rows that were diluting every other signal on the page:
1. Saved-handoff dumps leaking into row activity text. Lines like
"Saved handoff: Wait for user to (a) resolve the OAuth blocker
by signing in with a fresh GitHub account..." were the agent's
own internal notes being pasted verbatim into the user-facing
table. getTabActivityText() now returns short lifecycle states
only — "Ready — pick the next task", "Agent open · idle",
"Closed", "Tab open · no agent process". Handoff content
belongs in a per-project expand/tooltip, not the always-visible
row.
2. "Last sync 6h ago" prefix repeated on every one of 21 project
rows when the daemon was offline globally. staleEvidenceLabel()
dropped the prefix in the common case — the global offline
banner already owns the "system is stale" signal; rows should
just describe last-known state. Preserve the prefix ONLY when
there's no other evidence to show (rare).
3. "Tab #1 Unlinked" dangling scratch tabs surfacing in the
workspace table. buildLiveTabRows now filters tabs that map to
no registered project — they're visible noise that the user's
actual zellij window already shows. The control surface is for
fleet ops, not a generic tab list. Test updated to assert the
filter behavior (Mystery tab dropped, registered tabs kept).
All three were silent UX papercuts that the SSOT and gate work
couldn't surface — the user had to point at the screenshot.
control-presenter tests stayed 19/19 after the test rewrite.
Items 2, 3, 4 of the 7-item Elon-team-pass plan. Items 5 (hierarchy)
+ 6 (header/rail vocab reconciliation) coming next.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Live regression caught while sessioning with the user. After
b89fdfc shipped the status:working gate on /api/control/dispatch,
the daemon still fired autopilot injects into the user's terminal
— 5 injections in 90 seconds, despite status:working AND a pending
blocker file. Root cause: the daemon has TWO injection paths, and
b89fdfc only covered one.
Path A (gated by b89fdfc):
daemon watchdog → POST /api/control/dispatch → returns prompt
→ daemon writes to terminal via autopilot_dispatch_and_inject()
Path B (the bypass — fired all 5 times):
user click OR ReadyBanner auto-fire OR stop-hook re-fire
→ POST /api/orchestration/run
→ enqueueInjectCommand writes a pending_commands row
→ daemon polls pending_commands, consumes row
→ daemon writes to terminal via execute_inject()
Gates added at TWO chokepoints (defence-in-depth, since either
path can be reached without the other):
1. scripts/cockpit-daemon.sh:execute_inject() — reads local FS for
~/.claude/sessions/<tab>.md status field and the .blockers/pending/
directory count. Refuses the inject (returns 1, logs "REFUSED")
when either signal says the agent is mid-task. hard_stop bypasses
the gate since it's the literal kill switch.
2. src/app/api/orchestration/run/route.ts — reads cached session
state from project_states.sessionStatus (already pushed by the
daemon to the DB). Returns HTTP 409 with reason="agent-status-
working" when working. Saves a database write + pending_commands
queue entry vs letting the request through to be rejected by the
daemon-side gate.
Both gates exempt hard_stop and close_session (lifecycle intents
that end sessions, not start work).
The dispatch-gate test suite (11 tests, scripts/test/dispatch-gates.ts)
still covers the original /api/control/dispatch gate. New tests for
the orchestration/run + execute_inject paths are TODO — gating them
without a live integration test scaffold means I'd be unit-testing
mock interfaces. For now, the live witness is the daemon log line
"inject REFUSED — <tab> session status=working" when a refused
inject lands.
Daemon stopped manually during this session; will be restarted by
the user after they pick where to take the UI work next (we had a
7-item plan queued before this bypass was found).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Until today, prompts lived in two parallel files: 35 entries in
~/.config/agent-prompts.json (out-of-repo, snake_case keys,
dev/ship/vision taxonomy + dimensionId) and 35 in
src/config/prompt-library.ts (in-repo, kebab-case ids, domain
taxonomy + scope). 12+ duplicate pairs with subtly different
bodies; 6 security prompts in TS only (invisible to DimensionSection
in /control); 6 control prompts in JSON only (invisible to /prompts
library page and ProjectPromptLibrary modal). Adding a new prompt
required two edits in two formats. Real SSOT violation.
This commit promotes the in-repo TS file to canonical SSOT for
prompt METADATA (id, name, description, category, scope, style,
slot, sendNow). For the subset of prompts that also need to be
dispatchable by the autopilot daemon, an optional `agentKey` field
ties the TS entry back to the snake_case identifier the daemon
expects. JSON becomes a build artifact, regenerated from TS via
`npm run generate:agent-prompts`.
Mechanics:
- PromptTemplate type gains optional agentKey, icon, style, slot,
dimensionId, sendNow fields. Category enum gains "control" and
"content". CATEGORY_META extended. No breaking changes to existing
fields.
- All 6 JSON-only control prompts (hard_stop, blocker_create,
orient, unblock, roadmap_check, onboarding) added to TS with
agentKey set to their daemon key + dimensionId: "control". They
now appear in BOTH /prompts library page AND DimensionSection AND
remain dispatchable by the daemon. hard_stop is the only one
flagged sendNow:true (kill switch — preview makes no sense).
- /api/prompts/agent route gains a mergePromptSources() helper that
reads JSON, transforms TS entries with agentKey, dedups by key
(TS wins on conflict). The DimensionSection in /control now sees
the unified set without a UI change. Old reference to
PROMPTS_FILE() preserved so the daemon still works during the
incremental migration.
- New scripts/generate-agent-prompts.ts generator transforms
PROMPT_TEMPLATES → AgentPrompt[] and writes them back to JSON,
preserving any legacy JSON entries not yet migrated. Wired as
`npm run generate:agent-prompts`. Backup of pre-regen JSON kept
at ~/.config/agent-prompts.json.bak-20260531-ssot.
Verification: tsc clean. Generator dry-run output: 35 entries (29
legacy + 6 TS-overridden). The 6 TS-sourced entries are byte-
identical to their old JSON bodies (same key, same prompt text).
Adding a new prompt is now ONE TS edit. Migrating the remaining 29
JSON-only entries to TS is a follow-up commit; the bridge keeps
everything working during the transition.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Live-incident regression. Earlier today the autopilot injected a
2000-char next_best template into the user's keystrokes mid-typing
while they were composing a message to the agent, producing garbled
text like "wtf ust happened? what is this injecSetup (run, read
outputs):...". The session handoff said status:working — which is
documented in three places as the suppression signal — but the
daemon fired anyway because nothing in the dispatch pipeline
actually read the status field.
Root cause: agent-hook-bridge.sh:autopilot_dispatch_and_inject()
extracted done/next/tests/todos/health from the session file but
not status. The dispatch route's HandoffSchema didn't include
status either. The user trusted a guarantee the code never made.
Three coordinated fixes:
1. agent-hook-bridge.sh now reads `status:` from the session file
AND counts files in ~/.claude/sessions/<P>.blockers/pending/.
Either condition (status:working OR blockerCount>0) causes the
daemon to skip the dispatch HTTP call entirely — saves a network
round-trip and surfaces the gate in daemon logs.
2. The dispatch route's HandoffSchema gains a `status` field and
the body gains `blockerCount`. Defence-in-depth: even if a
custom integration or cloud-only caller bypasses the daemon's
client-side gate, the route refuses to act on a working status
or pending blockers. Two new DispatchResult.source values
(status_gate, blocker_gate) make these refusals greppable in
logs.
3. The gate logic moves out of the route handler into a pure
helper at src/lib/orchestration/dispatch-gates.ts so the
invariants can be unit-tested without spinning up a real Next
request. 11 inline tests cover: status:working wins over every
mode; blockers beat happy-path; legacy empty status preserves
existing permissive behavior; etc. Wired into
`npm run test:dispatch-gates`.
Closes the highest-impact symptom of the strategist's broken trust
model. The user can now leave autopilot on and trust that their
status:working handoff actually stops it.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
28dae15 made /api/inject carry modelPref into the inject payload, but
execute_launch_agent and execute_switch_agent in the daemon only read
model from their queue payload. So the autopilot watchdog (which
spawns fresh agents via launch_agent without pinning a model) and the
agent dropdown's switch flow (when called without an explicit model)
both fell back to each agent's built-in default — a project pinned to
"opus" still got Sonnet when autopilot restarted it.
Pattern matches the execute_inject auto-launch path (501a6e7): when
payload model is empty, look up _conf_model_for_tab. Three call sites
now do the same fallback consistently — auto-launch, launch_agent,
switch_agent.
No payload schema change; pure daemon-side defensive lookup. Caller-
supplied model still wins; conf model fills the gap.
501a6e7 added modelPref to the conf-file path so the daemon's auto-
launch could read it. But /api/inject didn't write model into the
pending_commands payload at all, and execute_inject's dispatch case
didn't extract it — so cloud-side dispatches still launched with
empty model and fell back to each agent's built-in default. The
conf-file fallback worked, but a user who dispatched right after
changing modelPref (before the 5-minute conf-sync) would miss it.
Three-file change makes the explicit path land:
- InjectPayload: add model?: string. Mirrors the field shape already
on LaunchAgentPayload + SwitchAgentPayload.
- /api/inject route: extract dbMatch.modelPref, include as
`model: eventModel` in the executeInject payload.
- cockpit-daemon.sh: dispatch case reads payload.model; execute_inject
accepts a 7th arg and prefers it over _conf_model_for_tab in the
auto-launch branch. Empty payload model falls through to conf.
Precedence is now: payload_model > conf model > agent's built-in
default. tsc clean, daemon syntax OK.
/api/agent/projects already returned model = project.modelPref for
every project, but the daemon's sync script only wrote 3 columns
(tab|dir|agent), so the model field was silently discarded between
cloud DB and local conf. _agent_launch_cmd accepts a model arg and
passes it through (codex --model, gemini -m, etc.), but the
auto-launch path in execute_inject was hardcoded to empty string.
End result: a Codex project pinned to gpt-5 still launched gpt-5.4,
a Gemini project pinned to flash launched 1.5-pro.
Three-file fix:
- sync-agent-runtime-config.py: write tab|dir|agent|model. Header
comment updated.
- agent-hook-lib.sh: _conf_agent_for_tab IFS read adds a 4th field
variable (legacy 3-col lines still work, unread field is empty).
Add _conf_model_for_tab mirror that reads the 4th column.
- cockpit-daemon.sh execute_inject auto-launch branch: look up the
conf model and pass it to _agent_launch_cmd.
Verified against a synthetic 4-col conf:
DemoProj → agent=claude model=opus
AOZ → agent=gemini model=flash
Legacy → agent=grok model=<none> (3-col line, no break)
NonExist → agent=<none> model=<none>
Not yet wired: launch_agent / switch_agent paths still take model
from queue payload only. Cloud /api/inject doesn't pass model in
payload yet either — those are the next iterations.
483b9b7 added a startup sync + 5-minute periodic re-sync of
agent-projects.conf from cloud. Multi-source polling forks one child
per extra base URL, and each child re-ran the same sync — so a
2-source setup (local + cloud) made 2× HTTPS requests to
/api/agent/projects every 5 min, plus 2 startup syncs, all writing to
the same file on the same filesystem.
Gate both the startup sync and the _conf_sync_loop on
COCKPIT_DAEMON_CHILD == "". The parent owns the conf; children inherit
it via shared filesystem. Atomic os.replace in the sync script already
made the parent-only path safe.
Also guard _CONF_SYNC_PID in _shutdown so children (which never set
the var) don't error on SIGTERM.
Verified live: pre-restart had 2 `sleep 300` PIDs, post-restart has 1.
Both daemon URLs still polling correctly.
agent-projects.conf is the local mirror of user_projects (name, dir,
agent_pref). sync-agent-runtime-config.py fetches /api/agent/projects
and rewrites the file — but only ran from agent-hook-bridge.sh on
agent stop hooks. So a pref change made via the web Settings page sat
unapplied until the next agent stopped: could be hours.
a6b8658 just made _resolve_live_adapter read this conf as a fallback
to honor the user's agent pref. Pairing that with a daemon that never
re-reads the cloud meant the fallback would silently use stale data.
Fix: run sync once at daemon startup (non-blocking, background), and
schedule a _conf_sync_loop that re-syncs every 300s. Both also write
to the same conf file via tempfile+os.replace, so reads are atomic
and never see a half-written file. _CONF_SYNC_PID is killed in the
existing _shutdown trap so SIGTERM cleans both background loops.
Bounded staleness: any pref change in cloud Settings now propagates
to the local daemon within 5 min (or instantly on next daemon restart),
without needing an agent stop event to trigger sync.
/api/inject already honors user_projects.agent_pref end-to-end via
the payload (16d21c2), but the daemon side of agent resolution still
fell back to "claude" whenever it was reached without going through
/api/inject: stop hooks, beacon callbacks, autopilot watchdog. So a
Gemini project's stop hook ended a Claude session and the watchdog
re-launched Claude regardless of the user's pref.
Add _conf_agent_for_tab() to read the agent column from
agent-projects.conf (the local mirror of user_projects.agent_pref
written by the daemon). Insert into _resolve_live_adapter priority
after /proc scan and current-prompt JSON, but before the heuristic
tab-name suffix and the legacy resolve_adapter — so live evidence
still wins, but the user's configured preference beats heuristics.
Verified against the live conf:
AOZ → gemini
Cockpit → claude
OrangeCat → <none> (no conf agent column set)
NonExistentProject → <none> (tab not registered)
execute_inject glued the 20-line handoff block onto every dispatched
prompt. Each Claude turn then tried to write the handoff file, hit the
existing-file guard, and prompted the user "Do you want to overwrite
revamp-it.md?" — surfaced live during cloud-dispatch verification.
Also wasted ~500 input tokens per inject across every project running a
Claude/Cursor/Codex agent.
Gate the append on /tmp/agent-handoff-sent-<tab>. After a successful
inject, touch the sentinel. Clear it everywhere the agent process is
considered fresh:
- close_tab (tab destroyed)
- hard_stop / close_session (lifecycle dispatch)
- launch_agent (explicit launch)
- switch_agent (different agent process)
- auto-launch branch in execute_inject (daemon spun the agent itself)
Net result: first dispatch of each session carries the template; every
subsequent dispatch in the same session is just the user's prompt.
execute_switch_agent sent /exit then Ctrl+C, but Claude's TUI swallows
both when it's busy mid-task — so the new-agent launch_cmd was typed
into the live old agent (claude received "cd /path && agent" as a
prompt instead of bash executing it). Verified live: ran switch claude→
cursor, daemon logged "done ✓" but the old claude PID was still alive
and cursor never started.
Add _kill_agents_in_dir as the escalation path: after the existing
quit+Ctrl+C dance, if the agent is still running in the project dir,
SIGTERM the PIDs (basename-matched, cwd-scoped), wait 1.5s, then SIGKILL
the holdouts. Only fires when the gentler signals didn't land, so
well-behaved CLIs (grok, codex, openclaw) keep their clean exit path.
Local-only daemon installs were silently broken: prompts queued from
localhost:3000 sat unclaimed because the daemon polled cloud, and "Not
running / Workspace tab open" contradicted itself on every project card
whose Zellij tab was open without an agent. This change wires both
sources, auto-launches the configured agent when its tab is empty, and
honestly labels tab-open-but-untracked state.
Daemon (scripts/cockpit-daemon.sh, _agents.sh, agent-hook-lib.sh):
- COCKPIT_BASE_URLS=local,cloud forks one child per extra URL so both
cockpit-app instances drain to the same machine; per-URL flock so
the children coexist.
- execute_inject auto-launches the chosen agent when none is running in
the project dir, then polls 20s for the process before injecting —
fixes prompts being typed into a bare bash shell.
- Wrap every `zellij action` call in `timeout 3` so one hung subprocess
no longer freezes the single-threaded dispatch loop.
- Delete the obsolete _base_url local-probe / DAEMON_FORCE_REMOTE
branch; each child now owns exactly one URL.
Auth (src/lib/session.ts):
- Legacy COCKPIT_DAEMON_TOKEN bearer was short-circuited by the `ck_`
prefix check, returning 401 against local cockpit-app. Fall through to
the legacy env-var path when the ck_ token isn't in the DB.
Control UI (ProjectCard, control-presenter, ZellijLivePanel,
project-intent-panel, ControlPanel):
- Idle + tab-open + !session-open → badge reads "Tab open" (was
contradictory "Not running"); evidence line and intent-panel copy
follow suit.
- Hide Launch CTA + saved-handoff block when the workspace tab is
already open — they were inviting the user to "launch" something
the daemon would have to refuse.
- Replace autonomy hint when tab is open but no agent is tracked.
- Surface "Last dispatch <age> · <prompt>" in the header evidence line
so the cloud UI shows what was sent without scrolling to Activity.
Malformed Vercel VAPID keys caused setVapidDetails to throw; wrap configure
and notify in try/catch. Use STALE_CLAIM_SECONDS in reclaim SQL.
Co-authored-by: Cursor <cursoragent@cursor.com>
Runtime presenter no longer requires agentRunning for Working; handoff
status:working does not stale an active prompt; fleet status bar for mobile.
Co-authored-by: Cursor <cursoragent@cursor.com>
Session-handoff watchdog fires when status:ready is fresh; Stop hook runs
autopilot first and queues inject via /api/inject with bearer fallback.
Co-authored-by: Cursor <cursoragent@cursor.com>
Replaces the two-layer popup race (KDE D-Bus notification + Chrome --app
beacon window + /tmp/beacon-choice polling) with a single POST to
/api/control/dispatch. The hook now becomes a thin autopilot client:
Stop → readyAt + finish_run + worker.finished (unchanged lifecycle)
→ push_notify_stop (Stage 5 lands the endpoint; silent until then)
→ autopilot_dispatch_and_inject:
auto_inject_mode=off → idle
server returns composed → inject strategist prompt
server returns queue → inject queue head, dequeue
server returns nextbest → inject canned next_best with session
server returns off → idle (queue empty, etc.)
Removes ~250 lines of choice-file race, beacon_launch helper, and slot/
custom/switch popup branches. handle_stop drops from ~280 lines to ~70.
beacon_launch is unreferenced and deleted; notify-choice.py + beacon.py
will be repurposed/removed in Stage 6.
Cockpit's promise is autopilot. The Stop hook is the moment that promise
pays off — and the popup was the thing in the way.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Cockpit's promise is autopilot — agents keep working when you're away.
The "queue_only" default introduced 2026-05-25 silenced the strategist on
day one, leaving new users in a non-autopilot product. Safety rails are
already in /api/control/dispatch (manual override, health gate, hard_stop,
queue priority) and the Stop hook respects them; the day-one risk that
prompted the flip no longer applies after /control became trustworthy in
6da8d7e + 7d7c40a.
Centralizes the default in DEFAULT_AUTO_INJECT_MODE (src/lib/constants/
control.ts) so the schema, queries, Settings UI, and Python/shell fallbacks
all source one constant. Adds an inline self-test (test:autopilot-defaults)
that pins every fallback to the autopilot value, wired into pre-push.
Existing users keep their explicit choice — only NEW rows get strategist.
The Drizzle migration is idempotent and reaffirms the column default.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds a claude case to _agent_direct_activity that reads the most recent
~/.claude/projects/<dashed-cwd>/*.jsonl mtime. The daemon already consumes
this signal for grok; with claude wired in, prompts typed straight into the
TUI (no Cockpit dispatch sentinel) surface as Working instead of falling
through to Agent shell open.
Gates direct-terminal evidence on readyAt so a just-finished agent stays
Ready: a Stop hook fires after the last transcript write, and without the
gate the next daemon tick would re-promote the stale mtime back to Working
and overwrite the legitimate ready badge.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This is the UI the user is asking to see live + the reflection fixes for direct terminal use (Cockpit tab showing correct agent).
Part of the approved zellij-control + terminal-reflection plan.
Extracted the branch logic from healReturningUserOnboarding into a
pure decideHealPatch() function in src/lib/onboarding-heal-decision.ts,
so it can be unit-tested without spinning up Postgres (the previous
location imported @/db/queries/* transitively, which fails at import
time without DATABASE_URL).
The I/O wrapper in onboarding-heal.ts now resolves projectCount and
suggested-username availability up front, then delegates the patch
decision to the pure function. Re-exports decideHealPatch + HealPatch
type so existing callers don't need to update import paths.
Test suite (npm run test:onboarding-heal) covers the six observable
branches:
- brand-new user → no heal
- returning user + free suggestion → both fields patched
- returning user + taken suggestion → onboardedAt only
- already-onboarded + valid username → no heal
- legacy migrated row (onboardedAt set, no username) → username only
- zero projects + onboardedAt set → still treated as returning
The never-throws contract on the I/O wrapper is verified by inspection
(try/catch wraps every await — there is no test-framework-friendly way
to inject a throw through the @/db import boundary without a real DB).
Finishes the Oracle migration plumbing started in ec6f423. Three pieces:
1. scripts/db/oracle-await-cutover.sh — polls
~/.config/cockpit/oracle-migration.env every 15s for ORACLE_HOST
(timeout 7200s by default), then runs oracle-cutover.sh with
SKIP_DUMP=1 once the IP is set. Lets the operator launch this
before creating the VM in the Oracle console; cutover fires
automatically the moment the public IP lands in the config.
2. scripts/db/oracle-cutover.sh — SKIP_DUMP=1 reuses an existing
pre-oracle-cutover.sql.gz instead of re-dumping prod, so the await
loop doesn't double-dump on every retry; env -u NODE_ENV wraps
`npm run build` and `vercel deploy`/`vercel redeploy` so the
ambient NODE_ENV=production from systemd or .env files can't
poison the build's mode resolution.
3. package.json — adds db:oracle-await alias.
Vendor-neutral DATABASE_URL helpers, dump/restore/sync tooling, and one-command
Oracle migration after a single console VM step. Publishes the studio-stack
thoughts article and hardens build (dynamic layout, resilient sitemap).
Co-authored-by: Cursor <cursoragent@cursor.com>
Control buried fleet state behind config metrics and only showed an open-tab count on cloud. Push the full Zellij tab list from the daemon, store it in runtime_snapshots, and lead the page with a workspace table showing agent, state, and current activity per tab.
Co-authored-by: Cursor <cursoragent@cursor.com>
Add @cockpit/agent init, server-side PIN enforcement for private APIs,
Postgres-backed cron jobs, daemon auto-continue sync, and cloud/local docs
so SaaS users get a clear path from browser signup to local dispatch.
Co-authored-by: Cursor <cursoragent@cursor.com>
After commit a12d2d9 closed the lifecycle pair across every adapter, the
detail field — the human-readable summary attached to each
orchestration_events row — had drifted across five emit sites into four
different formats:
• route.ts:354 ${intent.name} — ${message} (em-dash)
• route.ts:436 openclaw worker start failed: ${msg} (verbose prefix)
• inject.ts:225 ${promptLabel} — ${result.error} (em-dash)
• worker.ts:72-3 ${intent} done | ${intent}: ${error} (split formats)
• worker.ts:88 ${error.message} (no intent context)
Downstream chart/list queries would need to grep multiple separator
formats and strip multiple prefix variants. Unified to one canonical
shape across all five sites:
success → "<intent_or_label>" (no trailing " done")
failure → "<intent_or_label>: <error>" (single-colon separator)
Operators can now split on the first colon to extract the intent label,
or pattern-match `:.*` to extract the error. The verbose "openclaw
worker start failed:" prefix is gone — the `source: 'api-orchestration'`
column already carries that context.
No schema changes. detail column is still truncated to 400 chars. The
existing task_started emits (which only carry the intent name with no
error) were already consistent and untouched.
tsc + eslint + build clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The codex/gemini branch in /api/orchestration/run emits task_started at
line ~296 before injectIntoTab. The openclaw branch did not. So every
successful openclaw run was invisible in orchestration_events — only
its orchestration_runs row existed. Commit 9a0ac77 closed the worker-
start-failure pair (failed-to-spawn now emits task_failed), but the
happy path and the in-worker error path were both still silent.
Three coordinated changes:
1. Route emits task_started before scheduleOpenClawWorker — mirrors
the codex/gemini emit shape so dispatches across all adapters look
uniform in queries.
2. scheduleOpenClawWorker signature gains userId, encodes it into
the base64 payload. The worker needs user_id to write to
orchestration_events (NOT NULL constraint).
3. Worker emits task_completed (state:'done') or task_failed
(state:'error' or thrown) after its terminal updateOrchestrationRun.
Source field 'openclaw-worker' (vs 'api-orchestration' on the start
event) so timeline queries can tell which process emitted what.
After this, orchestration_events carries a full started/completed-or-
failed pair for every openclaw dispatch — same shape as codex/gemini —
and the single dispatch-success-rate query introduced in 9a0ac77 covers
every adapter without per-adapter casing.
tsc + eslint + build clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Vercel deploy failures previously sat in Error state silently until
someone ran `vercel ls`. The just-fixed CRON_SECRET-whitespace incident
(02c3c0d) is exactly this class: the build error existed for several
minutes before I noticed.
scripts/wait-for-vercel.sh polls vercel ls --prod for the most-recent
deployment, echoes each status transition, and exits:
0 on Ready
1 on Error / Failed / Canceled (prints `vercel inspect <url> --logs` hint)
2 on timeout (default 420s; tunable via env)
3 when the vercel CLI isn't installed
Gotcha I hit while writing this: `vercel ls` emits the deploy table to
STDERR, not stdout — `2>/dev/null` silently swallows every row. Use
`2>&1` to merge. Comment in the script flags it so the next person
debugging doesn't waste the same hour.
npm scripts:
wait:vercel direct invocation
ship git push origin main && wait:vercel
Use:
npm run ship # push and wait
bash scripts/wait-for-vercel.sh --quiet # exit code only
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Follow-up to the stale-Working defense (48fa2b6). Two related bugs:
1. ROOT CAUSE — agent-hook-lib.sh:write_inject_state used a naive printf
to interpolate $label and $key directly between JSON double quotes,
with zero escaping. Any user-supplied custom prompt containing
newlines, quotes, or backslashes broke the JSON so jq rejected it
in the daemon's parser. cpsat then fell back to "null", the
cleanup's outer guard skipped, and the file lingered indefinitely
leaking /tmp space (e.g. the AOZ sentinel from May 19 with a 1132-
byte multi-line prompt).
Fix: switch to `jq -Rs .` for both key and label — the same idiom
the daemon's execute_inject (cockpit-daemon.sh:258-262) already
uses. Newlines and quotes are now correctly escaped on every write.
2. LEGACY CLEANUP — even after fixing the writer, existing corrupted
files keep lingering since the parser still can't extract
startedAt. Added a belt-and-suspenders elif branch in the daemon
sweep: when the file exists but cpsat couldn't be parsed, fall
back to filesystem mtime; if older than 30 min, delete it. Files
that fail to parse never become live again, so a time-based sweep
is safe.
Both edits stay in scripts/agent-hook-lib.sh and scripts/cockpit-
daemon.sh — agent-hook-bridge.sh is untouched.
Companion to the UI staleness gate. Closes the leak at the source so
the sentinel doesn't keep getting re-pushed every 2s — fires the same
two checks the UI uses (session-mtime newer than prompt-start, OR
prompt older than 30min) inside _push_loop, deletes the file, and
clears cpk/cpl/cpsat so the JSON pushed to /api/control/runtime-state
carries nulls.
Verified against live state:
- OrangeCat: 3-day-old "echo ui-dispatch-test" prompt → cleared
after daemon restart (DB row's current_prompt_started_at went
null within one push interval).
- revamp-it: 30-min-old "Auto: next_best" → cleared on next push.
Companion to:
fix(control): stale "Working" defense — gate currentPrompt by
session signals + time
Cursor's audit caught this — the script committed in e33cd22 hardcoded
the live Neon `neondb_owner` password and a specific NEON_USER_ID.
Repo is private so blast radius is limited to anyone with read access,
but the value sits in git history forever and would leak immediately
if the repo were ever open-sourced or accidentally made public.
Refactor: all connection strings + user IDs now read from env vars.
LOCAL_DATABASE_URL / NEON_DATABASE_URL / NEON_USER_ID are required
(with a sensible local default for the source URL); script bails with
a clear hint if NEON_DATABASE_URL_DIRECT-style resolution finds
nothing. Matches drizzle.config.ts's existing env-var pattern.
ACTION REQUIRED (separate from this commit, your action on Neon):
• Rotate the `neondb_owner` password on the cockpit project via
neon.tech dashboard or `neonctl roles reset-password`. The OLD
password lives in commit e33cd22 forever; only a rotation kills it.
• Update Vercel env vars (DATABASE_URL + NEON_DATABASE_URL_DIRECT)
+ your local .env.local with the new password.
Bash syntax clean.
User reported cockpitapp.vercel.app/control still showing 'Local daemon
offline last seen Xm ago' even though the daemon is alive and the
FORCE_REMOTE fix landed yesterday.
Root cause: _push_loop only POSTs to /api/control/runtime-state when
the state hash changes. Between agent actions, state is stable for
minutes, so no push fires. The cloud UI's daemonOffline threshold is
90 s (src/components/control/ControlPanel.tsx:110). Idle daemon →
push gap > 90 s → UI permanently flagged offline.
Added a heartbeat: even when the hash is unchanged, force a push
every DAEMON_HEARTBEAT_S (default 60 s, env-overridable). That stays
comfortably under the 90 s threshold with one missed-push slack.
Pushes on actual state change still fire immediately (the OR
condition runs first). Net cost: 1 push/min from a healthy daemon
instead of 0 — negligible vs the inject claim-loop frequency.
Bash syntax clean. Will take effect after daemon restart on this
machine.
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.
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.