Drops the "isReturning" gate in decideHealPatch so the heal fires on
first sign-in too. When a user signs in with OAuth (GitHub / Google /
Twitter) and we can derive a unique username from their display name
or email local-part, we set it + onboardedAt right there in the JWT
callback. They land authenticated with onboardingComplete=true and
middleware sends them straight to /control instead of via /onboarding.
User-visible effect: GitHub OAuth → /control in ONE page load instead
of two. The /control empty state's GitHubRepoSuggestions / LocalDev-
Suggestions / FleetRunnerAutoMint then take over from there.
Fallback (still works): users whose suggested username collides with
an existing one, or whose display name + email can't yield ≥2 chars
of [a-z0-9-], get null patch → middleware sends them to /onboarding
to pick manually. The page is no longer a forced gate — just a
fallback for the edge cases.
Side benefit: also skips the wasted "onboardedAt-only" write that
the old logic would do for returning users without a valid username,
since onboardedAt without a valid username is a no-op
(isOnboardingComplete still gates on both).
The /settings → Profile editor lets users change the auto-picked
username later, so we're not stealing their choice — just defaulting it.
Tests: 7/7 pass (npm run test:onboarding-heal). Updated existing
brand-new-user assertion to reflect the new policy and added a
collision-fallback test case.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes the second-most-common project-source gap (after GitHub) caught
during dogfooding: builders' projects live in github repos AND on disk
in ~/dev. The GitHub side already had bulk-import via /control/import;
this adds the parallel for local folders.
Pieces:
1. POST /api/projects/import-from-local — accepts { folders: [...] },
creates one project per folder, dedupes by name. Auth via Bearer
ck_* agent token (validateAgentToken — reuses the existing token
surface, no new auth path).
2. scripts/import-from-local.sh (+ public/import-from-local.sh mirror) —
bash one-liner that walks $HOME/dev, $HOME/code, $HOME/Code,
$HOME/Projects (configurable via FC_ROOTS), finds .git directories
(max depth 3), extracts name + path + origin URL + last-commit ISO,
POSTs the batch. Safe to re-run; duplicates are reported, not errored.
3. /control/import-local — new page that walks the user through:
(a) mint a ck_* token at /settings (with link),
(b) paste the one-liner with their token,
(c) refresh /control to see imports.
4. EmptyStateWelcome on /control gets a fourth CTA card: "Import from
~/dev — paste one terminal line." Grid is now 2-col on md, 4-col
on lg so the four import paths fit cleanly.
5. CopyableCommand component (components/control/) for the one-line
bash block with a copy-to-clipboard button. Promotable to
components/ui/ if a second feature needs it.
UX flow:
/control empty → click "Import from ~/dev" → mint token at /settings
→ paste curl|bash in terminal → script scans local repos → refresh
/control → projects appear alongside GitHub imports.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Both fixes apply to scripts/oracle/install.sh based on the actual Hetzner deploy
on 2026-06-04. The install.sh path is now first-try-clean on Ubuntu 26.04.
1. Caddyfile `log { format filter ... query_replace }` removed. The
`caddy.logging.encoders.filter.query_replace` module isn't registered in
Caddy v2.11 — the service refused to start with "module not registered".
Default access logging goes to journalctl. If token-redaction matters
later, look at the `regexp` filter encoder or disable access logs.
2. pg_hba.conf gained host entries for 127.0.0.1/32 (fleetcrown +
orangecat roles, scram-sha-256). Without them, the Node bridge's
pg client couldn't connect to its own Postgres: pg requires explicit
`rejectUnauthorized: false` to accept Postgres's default self-signed
TLS cert, which isn't exposed via DSN. Bridge .env also switched to
`sslmode=disable` — loopback connection only, scram-sha-256 password
is the actual security boundary.
Verified end-to-end on 2026-06-04: SQL `pg_notify('fc:state', ...)` →
bridge `eventLogSize` increments → HTTPS endpoint at bridge.orangecat.ch
serves with valid Let's Encrypt cert.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Runs on the Ubuntu 24.04 ARM box, takes ~10 min, leaves you with:
- Postgres 17 + fleetcrown/orangecat roles + databases (per-role pg_hba)
- v0.6 NOTIFY triggers applied
- Bridge built and running as systemd fleetcrown-bridge.service
- Caddy reverse-proxy with auto letsencrypt TLS at BRIDGE_HOST
- UFW + iptables on 22/80/443/5432 only
- Daily pg_dump cron retaining 30d in /backups
Required env: FLEETCROWN_DB_PASSWORD, ORANGECAT_DB_PASSWORD, BRIDGE_HOST
Optional env: FLEETCROWN_DUMP_URL, ORANGECAT_DUMP_URL (restore from URL)
User flow:
1. Point bridge.fleetcrown.com (or whatever) A record at the Oracle IP
2. ssh ubuntu@<oracle-ip>
3. FLEETCROWN_DB_PASSWORD=... ORANGECAT_DB_PASSWORD=... BRIDGE_HOST=bridge.fleetcrown.com \
curl -fsSL https://raw.githubusercontent.com/maonakamoto/fleetcrown/main/scripts/oracle/install.sh | bash
4. Set the printed Vercel env vars, redeploy
5. /api/health returns 200 against the new DB, /control feels real-time
Idempotent — re-running won't error. Each step checks for the prior
state and skips if already done. Safe to re-run after a partial failure.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Same job, one more source. Now the toolkit handles:
- FleetCrown out of Neon (`dump-from-neon.sh`)
- OrangeCat out of Supabase (`dump-from-supabase.sh`)
- Both consolidated onto one self-hosted Postgres box
scripts/db/dump-from-supabase.sh
Mirrors dump-from-neon.sh's interface. Supabase-specific guards:
- Refuses pooler URLs (port 6543 / pooler.supabase.com) because
pg_dump fails midway through transaction-pooled connections.
- Defaults to --schema=public only. Supabase's auth/storage/realtime/
extensions schemas would create dangling-role FK errors on a vanilla
Postgres target. FULL_DUMP=1 dumps everything when self-hosting
gotrue too (bigger project for another day).
- Same .sql + .manifest.txt output shape as the Neon script;
restore-to-target.sh accepts either without modification.
scripts/db/BOTH_PRODUCTS_ONE_HOST.md
Layers two databases (`fleetcrown`, `orangecat`) on a single Postgres
instance with separate roles and per-role pg_hba.conf lines. Covers:
- role + database setup
- pg_hba rules: each role authenticates only to its own DB
- migration sequence: FleetCrown first (it's broken), OrangeCat
second (still functional on Supabase)
- auth-stays-on-Supabase recommendation for OrangeCat (cheap, no
gotrue self-host needed at this scale)
- shared backup cron with off-box rsync mirror
- PgBouncer add-on for when connection count balloons
- explicit "when to split the box" thresholds (sustained 70% CPU,
<95% cache hit ratio, p95 latency >50ms)
scripts/db/README.md
Updated header + file table to mention both products. Migration
cookbook now has separate Step 1 entries for Neon vs Supabase and
points at BOTH_PRODUCTS_ONE_HOST.md for the dual-product path.
Capacity sanity for the curious: a Hetzner CX22 (€4.51/mo, 2 vCPU, 4 GB
RAM, 40 GB SSD) is over-provisioned by ~3 orders of magnitude for both
products at today's scale (single-user each). Upgrade in-place to CX32
when sustained CPU exceeds 70% — that's many months out.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Grab-and-place migration kit so we can move off Neon (which capped our
data transfer earlier today) on ~30 min notice when the quota resets or
we upgrade the plan just long enough to dump.
scripts/db/dump-from-neon.sh
pg_dump + emit a manifest of pg_stat_user_tables row counts. Plain SQL
format (auditable, diff-friendly). Halts the script if SOURCE_DATABASE_URL
is missing.
scripts/db/restore-to-target.sh
psql --single-transaction --set ON_ERROR_STOP=on against the new host.
Refuses to overwrite a target that already has users rows (set
RECREATE_DB=1 to force). After restore, compares pg_stat_user_tables
row counts against the source manifest and halts if any table
mismatches — keeps a botched migration from making it to "flip Vercel."
scripts/db/SETUP_HETZNER.md
Runbook from "open Hetzner account" to "Vercel deployed + smoke passes"
for a CX22 (~€4.5/mo). Covers Postgres 17 install, SSL, ufw, fail2ban,
pg_hba, env swap, smoke. ~30 min end-to-end.
scripts/db/SETUP_ORACLE_FREE.md
Same shape for Oracle Always-Free ARM (4 OCPU / 24 GB / free forever).
Calls out the gotchas: dual firewall (Oracle Security List + iptables),
ARM-specific Postgres package source, idle-reclamation risk.
scripts/db/README.md
6-step end-to-end migration cookbook tying the scripts and runbooks
together. Why pg_dump over Drizzle migrations: data move, not schema
sync. Why keep the Neon dump cold for 30 days post-migration.
Today the toolkit can't actually run end-to-end because Neon's quota is
blocking pg_dump. That'll clear on monthly reset (or with a one-month
plan upgrade just long enough to dump). When it does, the full migration
is a coffee break, not a project.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The v0.3.0 mirror caught a real reliability gap: the draft release on
maonakamoto/fleetcrown only had Linux assets, even though all three matrix
jobs reported success. Likely a race in electron-builder's GH provider
when concurrent matrix jobs publish to the same draft.
Fix: read from the workflow run's artifacts instead. Each matrix job runs
upload-artifact unconditionally with everything it built, so the workflow
artifacts always reflect the complete set — no race, no partial draft.
- Resolves the workflow run ID automatically (latest successful run on the
fleet-runner-v<version> tag ref) or accepts an explicit run ID arg.
- Flattens the per-OS artifact subdirectories before upload.
- Asserts ≥ 5 assets before publishing (sanity floor — partial uploads
fail loudly instead of silently mirroring a broken release).
The draft-release path is no longer used and the cleanup hint at the end
now warns the draft is "likely incomplete."
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The desktop-release workflow's electron-builder publish lands as a DRAFT
release on maonakamoto/fleetcrown tagged v<version> (no fleet-runner-
prefix — that's an electron-builder limitation). The canonical public
download host is maonakamoto/fleetcrown-releases tagged fleet-runner-v*.
scripts/mirror-desktop-release.sh:
- Downloads the draft assets from fleetcrown by their v<version> tag.
- Creates the fleet-runner-v<version> release on fleetcrown-releases (or
uploads missing assets if it already exists — idempotent).
- Prints the cleanup command for the now-redundant draft.
Workflow comment updated to point at the script and TODO the cross-repo
PAT path (RELEASES_REPO_TOKEN) that would let electron-builder publish
directly to fleetcrown-releases and eliminate the mirror step entirely.
No runtime changes — purely the post-release tooling.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Desktop:
- Fleet Runner ships in web-shell mode by default — the AppImage loads
https://fleetcrown.vercel.app (the same React tree the browser serves) so
desktop and web stay at parity from one codebase. FLEETCROWN_WEB_URL overrides
for previews/dev; `=local` disables web-shell for IPC dev work.
- Stable artifact naming via `artifactName: Fleet-Runner-${os}-${arch}.${ext}`
so /releases/latest/download permalinks work; package.json publish target
corrected from "cockpit" → "fleetcrown".
CI:
- New desktop-release.yml workflow: build matrix on macos-latest, windows-latest,
ubuntu-latest fires on fleet-runner-v* tag push. Each runner produces signed
installers via electron-builder --publish always and uploads to a GitHub
Release. workflow_dispatch with dry_run=true builds-only for pipeline tests.
Download UX:
- Page redesigned for non-technical visitors: hero → web vs desktop comparison
→ platform-aware CTA → 3-step "what happens next" → plain-language prereqs
with required/optional badges → developer drawer (collapsed).
- mac/Windows surfaces no longer point at the repo as a "download" — they show
a Coming Soon panel with a release-feed subscription and an honest "Use the
web app instead" escape hatch. Build-from-source demoted to a dev drawer.
- ~30 new ui-public-download-* semantic classes for the new patterns; design
guard remains clean.
Navigation:
- /download added to the sidebar Site section so logged-in users have an in-app
entry point to the desktop app.
- Homepage redirect dropped for signed-in users (onboarding flow preserved);
hero + footer CTAs now surface "Open FleetCrown →" when authenticated.
Marketing copy:
- Roadmap NOW phase reflects the desktop ship (web-shell, embedded watcher,
multi-OS pipeline); NEXT phase reframed to "Distribution and auto-update"
with concrete remaining work (signed mac/Win binaries publicly shipping,
auto-update, native package channels, IPC bridge polish).
- Investors "what we have built" copy updated to mention the desktop app + CI.
Pre-existing fixes folded in:
- Control surface: AttentionBar deduplicates the "Needs attention" reason chip;
control-presenter labels the session-with-mtime-but-no-readiness case as Idle.
- Scripts: cockpit → fleetcrown rename sweep across beacon/install/deploy.
- /api/system/daemon route updates.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Closes the loop on the github username rename. Replaces every
g-but → maonakamoto reference in:
- desktop/package.json (electron-updater publish.owner — drives auto-update)
- desktop/README.md, src/config/marketing-content.ts (clone/release URLs)
- scripts/install-fleetcrown-{app,daemon,beacon-window}.sh (systemd Documentation=)
- scripts/wait-for-vercel.sh (example output in code comment)
- src/app/api/project/bootstrap/route.ts (default github user fallback)
- legal/IP_ASSIGNMENT_MEMO.md (repository location only — natural-person
identification preserved until bitbaum AG / FleetCrown GmbH incorporate)
Local + global git config (user.name, user.email) and the origin remote
URL already updated outside the tree. GitHub auto-redirects the old URLs
but flipping them eliminates the leak and matches the pseudonymous-founder
direction.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- FleetCrown is customer of OrangeCat (stakeholder 'customer' edge, shared wallet).
- Both + FleetWave as projects/profiles on orangecat.ch for Mao Nakamoto.
- Added integration banner in /money page (visible UX for the customer relationship).
- Updated CLAUDE.md, README, legal/IP memo, marketing-content to reflect current names, FleetWave customer, rebrand.
- Legacy 'cockpit' paths kept per branding-design for transition.
- Data updated live in DB (rename, wallets, relations, new FleetWave project).
- Makes the full stack work for real customer FleetWave; scales to others.
Changes in both cockpit and orangecat for good UX and functioning product.
- desktop build clean, tsc clean, lint 0, home/ 89/89
- advances desktop-2/3: dispatches now produce durable events in ~/.fleetcrown/events.jsonl with proper runId/sentinel so stop-hooks and web control plane treat them as first-class
- still no embedded watcher (idle via co-running home/watcher.ts for now)
Refs: desktop-app.md phases, Cockpit.roadmap T1/T2, prior landing 2d98638
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.