Before this commit, /activity only knew about prompts dispatched through
/control and runs spawned by orchestration. The much larger pool of
context — every time the founder typed into a local Claude Code session
in their terminal — sat invisible on disk in the JSONL transcripts the
CLI writes to ~/.claude/projects/<encoded-cwd>/<sessionId>.jsonl. The
"god-level context-aware" ask is to fuse the two streams so /activity
becomes "everything you typed about this project anywhere," which is
what an agent fleet's activity view should always have been.
Mechanism:
1. New table claude_code_history mirrors per-event metadata from the
JSONL transcripts. (session_id, event_uuid) is UNIQUE so re-ingest
is idempotent — incremental sync is just a re-run.
2. scripts/ingest-claude-code-history.ts walks the projects dir,
resolves cwd → user_projects.dir_path → projectKey, and inserts
user + assistant turns with ON CONFLICT DO NOTHING. Backfilled the
31,284 historical events on first run (FleetCrown 11.7k, revamp-it
6.3k, OrangeCat 5.2k, etc.).
3. digests.ts pulls the user-only slice into the digest timeline as
a new "local_chat" kind, includes those events in per-project
activity counts so the chip wall ranks projects honestly, and
bumps MAX_TIMELINE_ITEMS 80→120 so a busy day fits without
starving prompts/runs.
EventStream renders the new kind without changes — it was already
content-agnostic. A FilterCard toggle for "include/exclude local chats"
is a natural follow-up but the timeline is already useful as-is.
Schema applied to local Postgres via raw SQL because drizzle-kit push
wanted to interactively confirm an unrelated agent_tokens.token
constraint backfill. The schema file is the SSOT; this commit is the
source of truth a future migration tool will diff against.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The 10-second STALE_CLAIM_SECONDS recovery in
reclaimStalePendingCommands closes the visible symptom of a daemon
crash mid-dispatch — the row becomes claimable again. But it opens a
worse failure: if the first daemon already typed keystrokes into the
terminal before crashing, the second daemon will replay execute_inject
and double-type. This is the actual race A1 was masking, not fixing.
Fix is a 23-line addition to the dispatch loop. Before entering the
case statement, write /tmp/<brand>-attempted-<id> with the current
timestamp. On every dispatch iteration, first check whether that file
exists — if it does, this row was already attempted by some earlier
process (this one or a crashed predecessor). Refuse to re-execute;
PATCH mark_done with a structured "abandoned mid-execution" reason so
the user sees what happened in /control and can retry explicitly. On
clean completion (after esac), remove the marker.
Why a /tmp marker instead of a DB column: tmpfs survives daemon
process death but not machine reboot. That matches the failure modes
we care about — a daemon crash leaves zellij + tmpfs intact (so the
keystrokes really did land, and we must NOT replay), while a machine
reboot wipes both (so the keystrokes never landed, and we MUST be
able to replay). Adding a column to pending_commands would persist
the marker across reboots and prevent legitimate replay.
No double-execution observed in production yet — this closes the
window before it bites. Pairs with Phase 2 (?types= filter) and
Phase 3 (runId sentinel) shipped in cdc042a.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Phase B + C + D of /home/g/.claude/plans/ethereal-crunching-clover.md.
B1. Generate bash state vocabulary from the TS SSOT
- scripts/generate-bash-state-vocab.ts reads STATE_DEFINITIONS from
src/lib/control-states.ts and emits scripts/control-states.generated.sh
with FC_LABEL_<KEY>, FC_DESCRIPTION_<KEY>, FC_COUNTER_CATEGORY_<KEY>
for every state.
- Wired into package.json's prebuild step so every `npm run build`
refreshes the file. Daemon sources it; new states propagate without
hand-editing any bash.
B2. Agent prompt context reads STATE_DEFINITIONS[k].description
- buildPromptWithSession(base, tab, projectStateDescription?) gained
a third optional argument. When passed, prepends
"Project state: <description>" before the session-state block — the
same one-line WHY the human sees on the badge hover tooltip.
- deriveProjectStateKey() in control-states.ts maps the raw signal
set (agentRunning / tabOpen / sessionStatus / readyAt / lockAt /
closingAt / closedAt) to a ProjectStateKey without dragging in the
full presenter machinery.
- Threaded into /api/inject (promptKey path) and the Claude +
Codex/Gemini paths in /api/orchestration/run. The agent now reads
the same words the user reads.
C. ControlFleetStatus migrated to DAEMON_STATE_DEFINITIONS
- lib/control-states.ts gains a sibling SSOT for daemon-side states
(setup_needed / offline / state_unknown / connected). Same shape:
label, description, dotClass, problem hint.
- ControlFleetStatus reads from it for the banner label + tooltip +
problem CTA, dropping the hand-rolled `daemonNeverSeen ? "Setup
needed" : daemonOffline ? "Daemon offline" : ...` tree.
- "Setup needed" surfaces an "Install Fleet Runner" action chip
linking to /download with the longer how-to on hover — same
pattern the per-project badge uses.
- DaemonStatusBanner (the rich 320-line install/recovery card) is
left alone — its UX is distinct from the status indicator.
D. Cleanup
- fleetcrown-daemon.sh now traps EXIT in addition to INT/TERM and
kills its forked sibling daemons (the multi-source polling forks
spawned for each FLEETCROWN_BASE_URLS entry). Was a defensive
improvement; the observed "12+ stale daemons" turned out to be
normal subshell tree.
- .env.vercel.production renamed to .OLD so an accidental
`vercel --prod` from CLI doesn't reupload the stale Neon URLs over
the live Hetzner Postgres (memory/pattern_vercel_cli_env_local_override.md).
.gitignore extended to keep the .OLD file out of git too.
- DATABASE_URL + DATABASE_POOL_URL moved from a single-branch preview
scope to all-preview, so future PRs build without the
"DATABASE_URL is required" build crash we hit on the
arch/control-stream-no-poll branch.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Phase A of /home/g/.claude/plans/ethereal-crunching-clover.md. Three
independent changes share one goal: make /control inject actually
diagnosable + actually reliable on the common case.
A1. Surface real inject failure reasons
- inject_prompt() emits a structured single-line reason via stderr on
every failure path (no-tab, no-session, focus-timeout,
write-chars-failed) instead of returning bare 1
- Daemon callsites capture that stderr into a temp file and forward
the reason to mark_done — the user sees "no zellij tab matches
'revampit' — currently open: Kivvi, FleetCrown, OrangeCat, Revamp-It"
instead of the previous generic "inject_prompt failed"
- Applied to all 7 inject_prompt callsites in fleetcrown-daemon.sh
A2. Match agents by cwd, not just by tab name
- New _resolve_live_tab_by_cwd() walks zellij dump-layout, reconstructs
each pane's absolute cwd from the layout-level cwd + pane cwd, and
returns the tab whose pane is rooted in the target project_dir
- inject_prompt() takes an optional project_dir 3rd arg; when the
name match fails (revampit vs Revamp-It vs revamp-it kind of bug),
the cwd fallback fires
- Daemon callsites thread project_dir through. Fixes the revampit
dispatch we observed.
A3. Same-machine fast path
- home/server.ts gains POST /api/inject. Spawns bash, sources
agent-hook-lib.sh, calls inject_prompt directly. Returns
{ok:true} or {ok:false, reason}. Binds 127.0.0.1 only so the
LAN cannot reach it.
- CORS allow-list permits https://fleetcrown.vercel.app and the local
dev origins — every other origin's browser blocks the response.
- src/hooks/use-control-data.ts::inject() tries the local fast path
first with a 600ms abort timeout. Success returns; failure with a
reason re-throws (caller renders); no-daemon falls through to the
cloud path silently.
- Result: 7 hops (browser → Vercel → DB → daemon poll → exec → focus
→ write) collapse to 3 (browser → home → exec) for the common case.
Reliability follows from deletion.
Bonus: home/projects.ts::resolveProjectPath() now does a loose match
(strip hyphens + underscores) when the literal lookup misses. Lets the
cloud send "revampit" find the conf entry "revamp-it" without forcing a
rebrand. Tested with revampit; injection lands.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The old label implied the project itself was dormant ("waiting for
instructions") when the actual underlying state is "agent process
detected, no recent handoff signal." It also disagreed with the
summary chip ("X awaiting input") that uses different wording for the
same fact.
Two consequences for a developer actively working on a project whose
Claude instance is at the prompt:
- the row badge said "Waiting for instructions" (implies idle project)
- the summary said "N awaiting input" (correct)
The user reasonably reads this as the UI lying.
Pick one honest, actionable phrase ("Awaiting input") and use it in
both places. No state-detection change — only wording.
The deeper truth gap (revampit's Claude isn't writing the
/tmp/agent-handoff-sent-* sentinel that would push the row to "Ready
for next step") is a separate hook-coverage issue that this rename
does not pretend to fix.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
scripts/deploy-local.sh copies runtime assets into .next/standalone and
restarts a local systemd service. Both are wrong on Vercel (no standalone
output by default, no systemd), and any failure inside the script surfaces
as the confusing "Command npm run build exited with 1" on Vercel without
hinting at the postbuild as the culprit.
Bail at the top when VERCEL or CI is set so the build proceeds with just
next build, the way Vercel expects.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
After a PC restart, Fleet Runner now brings zellij + every agent back
without the user opening a terminal or typing CLI names. The last
runtime_snapshot.panes (extended with {tab, paneIndex, agentCli, cwd})
acts as SSOT for "what should be running" — Fleet Runner generates a KDL
layout with embedded `bash -c "cd … && claude"` per pane and spawns
`zellij --session fleet --layout`, bypassing zellij's press-ENTER
resurrection prompt entirely.
Injection is now self-healing end-to-end. Pre-flight ensureZellijReady
re-spawns the session if it died mid-day. /tmp/fc-cmd-<id>.done sentinels
make commands actually idempotent so a PATCH-ack retry can't fire the
same prompt twice. Post-flight watches ~/.claude/sessions/<tab>.md mtime
for 5s after inject and reports verified=false if the agent didn't pick
up — surfaced in AttentionBar via getRecentFailedCommands. The legacy
"No Zellij session found — start Zellij first" throw is replaced with a
synchronous spawn-default-session path so /api/agent/launch on
self-hosted servers self-heals too.
Settings → Agent gets a new Fleet Lifecycle section (auto-restore on/off,
fresh-spawn vs leave-alone for exited zellij sessions, session name,
auto-start at login). Stored as users.fleet_settings jsonb so future
knobs don't need a migration each time.
Bundled binary version-aware (Fleet Runner ≥0.4.0 ships zellij in
resources/bin and prepends to PATH). Inline tests for the KDL generator
run as a 9th suite under `npm run test:home` — 8/8 cases pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Users switch agents from the Control UI without typing quit commands in
Zellij — click the agent chip on a project card, pick from Cmd+K palette,
or accept the rate-limit banner's fallback suggestion. Detection lives in
agent-resolution.ts (client-safe) + agent-process-scan.ts (server /proc
walk); switch enqueues pending_commands type switch_agent which the Fleet
Runner poller executes locally, quitting every running agent in the dir
before launching the next.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Phase 1 of the sustainable autopilot-control refactor. Adds explicit
block-reason + no-op-count fields to the session.md handoff, plumbs
them through parser → desktop pusher → API → DB → React, and updates
the bash guard to read them directly. Eliminates the three-vocabulary
problem that caused the OC no-op spiral on 2026-06-08, where agent's
"health: critical — awaiting user" string collided with the bash
guard's first-word match.
Schema:
- ORCHESTRATION_TASK_SUMMARY_FIELDS gains "block-reason" + "no-op-count"
- SessionState gains blockReason?: string + noOpCount?: number
- project_states adds session_block_reason + session_no_op_count columns
Pipeline:
- control-fast-state.parseSession projects kebab-case → camelCase
- desktop pusher payload + runtime-state route + persistSessionIfNewer
all carry the new fields
- /api/control/route + /api/control/stream re-emit them to React
Consumers:
- session-state.ts derivations prefer structured fields, fall back to
content-sniffing for pre-2026-06-08 sessions
- autopilot-needs-fire bash guard reads block-reason + no-op-count
directly; same fallbacks active
- agent-hook-bridge + fleetcrown-daemon handoff templates and the
blocker_create SPACE prompt now instruct agents to emit the fields
Memory of why this exists: OC ran 21 no-op turns (~60k tokens) in an
hour because three layers parsed the agent's intent from free text
with different rules. Phase 2 (daemon owns the should-fire decision)
follows; bash guard's content-sniff fallbacks live until every agent
has rotated through the new template.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pre-this-commit, the Hetzner DB had ALL 26 historical migrations applied
(via drizzle-kit push during the v0.6 cutover, task #15) but ZERO rows in
drizzle.__drizzle_migrations because push doesn't write the ledger. As a
result drizzle-kit migrate would have tried to re-apply every migration
from scratch on its first run — failing on the first CREATE TABLE for an
already-existing table, OR worse, silently producing drift if any IF NOT
EXISTS / IF EXISTS guards saved the run.
This commit closes that gap permanently.
NEW scripts/db/bootstrap-migration-ledger.ts (175 lines):
Reads all drizzle/NNNN_*.sql files. Computes sha256 of each (drizzle's
canonical hash format). Modes:
--dry-run (default) Print the SQL it would apply
--emit-sql Print to stdout (pipe to psql)
--write-journal Update drizzle/meta/_journal.json locally
--apply Run against DATABASE_URL via psql -f
Idempotent (uses ON CONFLICT DO NOTHING). Safe to re-run.
APPLIED to prod (postgresqlbridge.orangecat.ch):
CREATE SCHEMA IF NOT EXISTS drizzle;
CREATE TABLE IF NOT EXISTS drizzle.__drizzle_migrations (id, hash, created_at);
CREATE UNIQUE INDEX __drizzle_migrations_hash_idx ON (hash);
INSERT one row per migration (26 total) with computed sha256.
Verified: SELECT count(*) FROM drizzle.__drizzle_migrations → 26.
WROTE drizzle/meta/_journal.json:
26 entries, monotonic 'when' timestamps starting 2026-01-01.
Future 'drizzle-kit generate' calls will append entries on top;
'drizzle-kit migrate' will see existing entries' hashes match the
ledger and skip them, applying only new migrations.
GOING FORWARD:
Schema changes: edit src/db/schema/*.ts → drizzle-kit generate → review
the new drizzle/NNNN_*.sql → drizzle-kit migrate to apply.
No more direct 'drizzle-kit push' to prod (kept available for dev DBs).
No more manual 'psql -f drizzle/NNNN_*.sql' shenanigans.
Tech debt this resolves:
- Drift detection: works now. drizzle-kit migrate exits 0 if and only
if the ledger matches the file hashes.
- CI: future deploy pipelines can run drizzle-kit migrate as a step
and have confidence in the result.
- Team scaling: someone other than me can apply migrations without
'how does this DB actually get migrated' tribal knowledge.
Verified: tsc clean, 19/19 control-presenter tests pass. Prod DB
unaffected outside the new drizzle schema.
The hardest UX gap in /control was: you saw your tab NAMES + state chips
('Working', 'Awaiting input') but never the actual screen content. To know
what the agent was saying you had to alt-tab into Zellij and find the
right tab. Web-shell users saw even less.
v0.7.2 closes that. Per-tab eye-icon button on /control workspaces table
opens a drawer that captures the live screen of that Zellij tab and renders
it as a static terminal frame (monospace, dark background, scrollable).
Auto-refresh toggle re-peeks every 3s for watching long-running agents
without permanently leaving the user on the peeked tab.
Mechanism (sub-200ms round-trip):
1. ZellijLiveRows eye-button → setPeekTab(name)
2. PeekTabDrawer mounts → window.fleetRunner.peekTab(name)
3. preload → IPC peek-tab → main process
4. src/lib/zellij.peekTab: save focus, go-to-tab-name, dump-screen to
/tmp file, restore focus, read+strip ANSI, unlink temp
5. Returns content → drawer renders in <pre>
Same focus-dance pattern as injectIntoTab (already in zellij.ts) — users
have accepted that disruption budget for remote dispatch, this reuses it.
Outside Fleet Runner the button is hidden (one-tick mount probe of
window.fleetRunner.peekTab). No degraded "button that always errors"
experience for browser users.
Also in this drop:
- desktop bump 0.7.1 → 0.7.2 (auto-update will pull this on next launch)
- control-presenter test: "cockpit" string was a leftover from the rename,
failed CI on the v0.7.1 push; now compares to 'FleetCrown' as intended
- ZellijLivePanel daemon-offline CTA now points to /releases/latest
instead of the hardcoded fleet-runner-v0.7.0 tag (was pointing users
at the broken bundled-renderer build)
Next: v0.7.3 cloud-fallback (browser-only users get peek via the command
queue → daemon → result table → SSE), v0.8 inline terminal column.
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.