Commit Graph
26 Commits
Author SHA1 Message Date
Mao NakamotoandClaude Opus 4.7 796f1f8290 fix(control): unblock prod queries + remove per-card polling
Two related fixes that together restore the /control page to a working state.

1. Missing migration 0030_session_block_reason.sql

Commit 729237c added session_block_reason + session_no_op_count to the
project_states schema without generating a SQL migration. Production
Postgres lacked both columns, so every SELECT on project_states crashed
with 42703 (errorMissingColumn). Symptom: /api/beacon/queue/<tab>
returning 500/503 in a tight loop, /api/control/stream emitting empty
project state, every project rendering "Offline · Live status
unavailable" on /control.

The migration is additive and idempotent.

2. Per-card polling → SSE-piped state

usePromptQueue and useAutoContinue each opened a per-card HTTP read loop
(setInterval @ 2 s and an on-mount fetch) against /api/beacon/queue/<tab>
and /api/control/auto-continue?tab=<tab>. With 21 projects on the page
that meant an N+1 request storm for state that the /api/control/stream
SSE endpoint can deliver as a single push.

Stream the data instead:
  - FastProjectState gains optional promptQueue / promptQueueRevision /
    autoContinueEnabled
  - /api/control/stream dbToFastState emits them from project_states
  - /api/control populates the same fields so the first paint matches the
    stream shape and no second mount-fetch is needed
  - useControlData.mergeProjectPatches forwards the fields onto each
    ProjectState
  - usePromptQueue / useAutoContinue accept the values as props, drop
    the polling loop, and only fall back to a one-shot HTTP load when
    the props are absent (local /proc-backed runtime path that doesn't
    project DB fields)
  - ProjectCard threads project.promptQueue + project.autoContinueEnabled
    into the hooks

Mutation paths (PUT /api/beacon/queue/<tab>, POST /api/control/auto-continue)
are unchanged. Optimistic local state + revision-based CAS retry still work
exactly as before; the stream just pushes the post-write revision back
instead of the hook polling for it.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-09 11:31:55 +02:00
Mao NakamotoandCursor b1c4a3eb74 fix(control): stabilize autopilot injection and fleet observability
Align stop-hook, beacon, and UI dispatch gates so autopilot respects per-project pause, choice wire format, and typing blocks; add control audit trail, Fleet Doctor, and updated cloud-local docs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-09 02:28:06 +02:00
Mao Nakamoto 152c8e9493 feat(db): bootstrap drizzle.__drizzle_migrations ledger (task #57)
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.
2026-06-07 19:42:19 +02:00
Mao Nakamoto 3079780b10 fix(db): drop duplicate project_states trigger + cap event-stream-token leak
Live Hetzner DB inspection on 2026-06-07 surfaced two real defects.

BUG 1 — DUPLICATE NOTIFY TRIGGERS ON project_states
The table had two trigger sets firing on every INSERT/UPDATE:
  * fc_notify_project_states (correct, from migration 0022 — emits on
    the canonical 'fc:state' channel via fc_emit_change)
  * project_states_notify (legacy pre-rename — emits on 'fleetcrown_state'
    via fleetcrown_notify_project_state, which nothing listens to)

Every state push fired both, doubling bridge NOTIFY traffic + giving
every SSE subscriber two events to process for one change.

drizzle/0026_drop_legacy_project_states_trigger.sql: drops the legacy
trigger + its function. Applied directly to prod via psql (verified
before: 5 trigger rows; after: 3). Idempotent (IF EXISTS).

BUG 2 — TOKEN TABLE LEAKS ON EVERY BROWSER LOAD
/api/event-stream-token mints a fresh ck_* token on every call. The
file's own comment (lines 33-39) literally said 'we always mint a fresh
one regardless'. Result: my account had 10 stale event-stream rows over
36 hours, all live, no cleanup. At any user scale agent_tokens grows
unboundedly.

Fix (three parts):

  a. NEW src/db/queries/agent-tokens.ts: getReusableEventStreamToken
     returns the most-recent event-stream token if last_used_at < 7 days,
     reused as-is.
  b. /api/event-stream-token: try reuse first, mint only as fallback.
     Response now includes {reused: true|false} for telemetry.
  c. NEW src/db/queries/agent-tokens.ts: deleteStaleEventStreamTokens
     deletes event-stream tokens with last_used_at older than 30 days
     (never touches other labels — daemon tokens are persistent).
  d. NEW src/app/api/crons/prune-agent-tokens/route.ts: Vercel Cron at
     05:00 UTC daily runs the cleanup, logs result to debug_logs as a
     heartbeat.
  e. vercel.json: register the new cron path.

ONE-TIME CLEANUP (already applied to prod during inspection):
  DELETE FROM agent_tokens WHERE label='event-stream' AND id NOT IN (
    SELECT id FROM (most-recently-used event-stream row per user)
  )
  Result: 10 stale rows → 1 active token per user.

Both fixes are deploy-on-Vercel-push safe; the SQL is already on prod.
Vercel deploy picks up the new cron route + endpoint change.

DEFERRED (separate batch): bootstrap drizzle.__drizzle_migrations
ledger so future migrations are traceable. The schema arrived via
'drizzle-kit push' so the migrations table doesn't exist; not blocking
this round.
2026-06-07 15:53:18 +02:00
Mao NakamotoandClaude Opus 4.7 e4753728dd feat(prompts): v2.1 — user-owned prompt library (schema + API + UI)
Pre-v2.1 the prompt library was 41 templates baked into
src/config/prompt-library.ts. Users couldn't add their own, pin to a
project, or capture successful ad-hoc dispatches. v2.1 is the
structural fix — each user can now create their own prompts that
merge with the FC defaults on /prompts.

Multi-disciplinary design (product · UX · engineer · prompt engineer):
- Product: prompts are repeatable work units; users need their own +
  per-project recipes. Library grows with use.
- UX: user-owned section above FC defaults; +New button opens an
  inline form (modal in v2.2 if needed); edit/delete on each card;
  scope toggle global vs project.
- Engineer: new prompts table (user_id, scope, project_id nullable,
  body, variables JSONB, tags, source, run_count, success_count).
  Migration applied to Hetzner.
- Prompt engineer: body supports {{name}} and {{name|default}}
  placeholders; parsed once at insert time into a variables[] array
  so v2.2's variables-at-run modal doesn't re-parse.

Shipped:
  + drizzle/0025_prompts.sql (applied to Hetzner)
  + src/db/schema/prompts.ts
  + src/db/queries/prompts.ts — parsePromptVariables, renderPromptBody,
    CRUD helpers, listPromptsForUser, listPromptsForProject
  + src/app/api/prompts/route.ts (GET list, POST create)
  + src/app/api/prompts/[id]/route.ts (GET, PATCH, DELETE soft)
  + src/components/prompts/UserPromptsSection.tsx — list + inline
    create / edit form with scope picker, tags, body textarea,
    variable-syntax hint
  ~ src/components/prompts/PromptLibraryClient.tsx — accepts
    optional userPrompts prop; renders UserPromptsSection above the
    FC-defaults grid
  ~ src/app/(app)/prompts/page.tsx — fetches user prompts via
    listPromptsForUser and passes to the client component

Roadmap noted in comments:
- v2.2: variables-at-run modal (quick-fill {{name}} placeholders
  before sending)
- v2.3: "Save as prompt" capture from /history rows
- v2.3: success-rate analytics from orchestration_runs.outcome
- v2.4: scheduled prompts (cron, integrates with the autonomous
  scheduler shipped in Change 5)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-06 13:47:31 +02:00
Mao NakamotoandClaude Opus 4.7 963e97e426 feat(beacon): Change 4 — migrate /tmp file-based sessions to DB table
Pre-v0.7: /api/beacon wrote one JSON file per session to
/tmp/<APP_SLUG>-beacon/<id>.json. The SSE route polled the directory
every 150ms with fs.readdirSync(). That worked while traffic was
single-pod-single-user, but had three real drawbacks:

  - /tmp isn't durable; a function instance restart loses pending
    popups silently
  - Cross-pod reads impossible — a popup written by pod A is invisible
    to pod B (latent landmine that hasn't bitten yet)
  - Filesystem polling on every SSE tick is exactly the work
    NOTIFY/LISTEN was added to obsolete in v0.6

This change moves storage to a beacon_sessions DB table. Same product
behavior, durable + queryable + user-scoped. A NOTIFY trigger on the
table is the v2 step that obsoletes the poll loop entirely — the
bridge already has the LISTEN side. This commit keeps the SSE poll
cadence to keep the diff small.

The beacon product feature itself (L3 of the autopilot ladder — the
"popup with countdown" tier between Manual and Continuous) is
unchanged. This was the file-based hack INSIDE the L3 product, not
the product itself.

Files:
  + drizzle/0024_beacon_sessions.sql (applied to Hetzner prod)
  + src/db/schema/beacon-sessions.ts
  + src/db/queries/beacon-sessions.ts
  ~ src/app/api/beacon/route.ts — POST + helpers delegate to DB
  ~ src/app/api/beacon/[id]/route.ts — GET/PATCH via DB
  ~ src/app/api/beacon/cancel/route.ts — userId-scoped (was global)
  ~ src/app/api/beacon/sse/route.ts — polls DB instead of /tmp,
    requires auth (was unauthenticated)
  ~ src/app/api/inject/route.ts — passes userId to cancel
  ~ src/app/api/orchestration/run/route.ts — passes userId to cancel
  ~ src/app/beacon/[id]/page.tsx — await readBeaconSession (now async)
  ~ src/app/beacon/live/page.tsx — userId-scoped + await
  + src/db/schema/index.ts — export beacon-sessions

Behavior changes worth flagging:
  - SSE endpoint now requires auth (returns 401 unauthenticated).
    Pre-Change-4 it served any /tmp content. The file version's lack
    of auth was incidental, not intentional.
  - cancelActiveBeaconSessions / readLatestPendingSession became
    user-scoped. Callers updated to thread userId through.
  - beaconPath export removed — meaningless for DB-backed storage,
    no remaining callers after the migration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-05 20:24:59 +02:00
Mao NakamotoandClaude Opus 4.7 6402666152 feat(control): per-project autopilot pause/resume
Pre-v0.7: a single user-level beacon_settings.auto_inject_mode applied
to every project. User question while dogfooding: "how can I easily
pause and continue auto-inject for different projects?"

Now each project entity carries an optional auto_inject_mode_override.
NULL = inherit the user-level mode (today's behavior). Any
AUTO_INJECT_MODE_VALUES value (typically "off") = pin this specific
project to a different tier. /api/control/dispatch reads the override
before falling back to the user default.

End-to-end:

Schema (drizzle/0023_entities_auto_inject_mode_override.sql):
  + entities.auto_inject_mode_override TEXT (nullable, no CHECK —
    validation is at the API boundary so future enum churn doesn't
    orphan rows).

Query layer (src/db/queries/projects.ts):
  + getProjectAutopilotOverride(userId, projectKey) → AutoInjectMode|null,
    defensively coerces unknown stored values to null
  + patchProject() accepts autoInjectModeOverride: AutoInjectMode|null
  + PatchProjectBody validator extended (zod enum + null)

Dispatch route (src/app/api/control/dispatch/route.ts):
  + Reads project override before user default. Both lookups fail-safe
    to default mode so a transient DB hiccup doesn't kill dispatch.

/api/control snapshot (src/app/api/control/route.ts):
  + ProjectState.autoInjectModeOverride populated per-project via
    resolveAutoInjectOverride() helper. Mirror of matchProfile's
    fuzzy-match (id-first, then tab/dir basename).

UI (src/components/control/ProjectAutopilotToggle.tsx + ProjectCard):
  + Pause/Play button on each ProjectCard. "Active" = inheriting the
    user-level mode. "Paused" = override is "off". Hover-tooltip
    shows the user-level mode so "Inherit" isn't opaque.
  + Hidden when projectId is null (legacy paths-only projects with
    no entity row can't be overridden — PATCH would 404).
  + Fires FLEETCROWN_REFRESH_EVENT on success so /control refetches.

Full per-tier control per-project (off/queue/beacon/continuous/mission
per project, not just binary pause) is the v2 follow-up; binary
pause/resume covers the dominant use case in scan-light shape.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-05 16:19:49 +02:00
Mao NakamotoandClaude Opus 4.7 e3541e2374 feat(v0.6): Phase A — event bus foundation (Postgres NOTIFY → SSE bridge)
The end-to-end push pipeline that replaces /api/control polling. This
commit ships the foundation; phases B-E light it up across the web,
desktop, and daemon. Read the architectural narrative in
/thoughts/from-polling-to-listening-fleetcrown-v0-6.

drizzle/0022_notify_triggers.sql
  - Generic fc_emit_change() plpgsql function: receives (user_col,
    key_col) via TG_ARGV, emits NOTIFY 'fc:state' with a compact
    {t, u, k, op, ts} JSON payload. IDs only — no row content — so
    the bus stays under Postgres's 8 KB NOTIFY limit even on bursts.
  - AFTER INSERT/UPDATE/DELETE triggers on the five UI-relevant
    tables: project_states, runtime_snapshots, pending_commands,
    orchestration_runs, beacon_settings.
  - Adding more tables in the future is two lines: drop + create
    trigger pointing at the same fc_emit_change function.

bridge/  (new ~300-line Node service)
  - src/server.ts — HTTP server with /sse (SSE endpoint, ?token=ck_*
    auth, Last-Event-ID replay) and /healthz. CORS open; the bridge
    sits on a different origin than Vercel and the desktop app.
  - src/listen.ts — single dedicated pg Client running LISTEN
    "fc:state" forever, with exponential-backoff reconnect on
    disconnect. Notifications fan out to subscriptions.
  - src/subscriptions.ts — in-memory Map<userId, Set<connection>>.
    Per-user routing; fanout writes SSE frames; idempotent remove
    on disconnect.
  - src/auth.ts — validates ck_* tokens against agent_tokens using
    the same plaintext lookup the cloud API uses (mirrors src/db/
    queries/agent-tokens.ts validateAgentToken).
  - src/types.ts — ChangeEvent and Subscription shapes.
  - In-memory ring buffer (1000 events) for Last-Event-ID replay so
    a brief disconnect doesn't drop state.
  - Heartbeat (SSE comment) every 25s to keep proxies happy.
  - Graceful SIGINT/SIGTERM shutdown with 5s hard-fail timeout.
  - .env.example, .gitignore, README with the Oracle systemd deploy
    runbook.

next.config.ts
  - Exclude ./bridge/** from output: standalone tracing. Same lesson
    as ./desktop/** — bridge has its own node_modules and is
    deployed separately. Don't let Vercel bundle it into every
    serverless function.

Verified end-to-end locally:
  - psql UPDATE on project_states → fc_emit_change fires →
    pg_notify reaches the bridge's LISTEN client → fanout to the
    subscribed curl SSE connection in ~milliseconds.
  - Per-user routing: a token bound to user A only receives events
    for user A's rows; tested by minting under two different users.
  - Last-Event-ID replay: reconnect with header skips already-
    delivered events, then live events arrive immediately.

Next: Phase B (web client subscribes to the bridge instead of polling
/api/control). Phases C-E follow.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-04 10:59:06 +02:00
Mao NakamotoandClaude Opus 4.7 acb81480b5 feat(orangecat): persist orangecat_service_id + render "OC ✓" badge on /money
Closes the Loop A persistence story. After
syncSubscriptionToOrangeCat() succeeds, the subscription row now stores
the OrangeCat service id back, so the /money page can render a per-row
"OC ✓" badge and future backfill jobs can target only the still-null
rows.

Schema (drizzle migration 0021):
- subscriptions.orangecat_service_id (uuid, nullable). Null = not
  mirrored (integration off, sync failed, or row predates the
  integration). Apply via `npm run migrate`.
- Partial index on (user_id) WHERE orangecat_service_id IS NULL — the
  shape the "what still needs syncing" backfill query will use; the
  column is mostly null for now.

orangecat.ts:
- syncSubscriptionToOrangeCat() now writes the back-link after a
  successful POST. The DB update is also non-fatal — OrangeCat already
  has the truth, and the next /money render still reflects the synced
  state once the column is populated.

UI (/money page SubRow):
- New "OC ✓" badge appears next to the subscription name when
  orangecatServiceId is present. Hover shows the OrangeCat service id
  for cross-system debugging.

SDK bump:
- @orangecat/sdk moved from 0.1.0 → 0.2.0 (file:vendor/). 0.2.0 adds
  .list() on every resource, which a future backfill script uses to
  enumerate what's already on the OrangeCat side before re-syncing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-03 16:06:15 +02:00
g-butandCursor 60f0cff749 feat(push): web push subscriptions and stop-hook notifications
Adds VAPID-backed subscribe/notify API, service worker, top-bar pill,
and Stop hook push_notify_stop for ambient agent-done signals on mobile.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-30 21:05:35 +02:00
g-butandClaude Opus 4.7 997f1aa622 feat(autopilot): flip default auto_inject_mode to strategist
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>
2026-05-29 13:31:13 +02:00
g-but 09f7bfb770 fix(control): make operations state race-safe 2026-05-27 21:52:33 +02:00
g-but 7c28ab15f8 refactor(control): create trustworthy agent operations workspace 2026-05-27 19:02:18 +02:00
g-but f39b942148 fix(auth): allow OAuth accounts to set password 2026-05-26 13:11:03 +02:00
g-butandCursor d1db4e292e feat(control): add live Zellij workspace panel with full tab sync
Control buried fleet state behind config metrics and only showed an open-tab count on cloud. Push the full Zellij tab list from the daemon, store it in runtime_snapshots, and lead the page with a workspace table showing agent, state, and current activity per tab.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-21 19:10:09 +02:00
g-but 6fa1158703 feat(db): unique-on-lower(project_key) index to kill case-collision dups
The composite primary key (user_id, project_key) is case-sensitive,
so two writer paths could each insert a row for the same logical
project — the API canonical-name path used user_projects.name
("Cockpit") and the daemon path used the zellij tab name
("cockpit"). The conflict target missed and a duplicate row was
inserted. Reads then returned both rows, and downstream sync code
could let the empty row stomp the row holding the real prompt
queue (the exact incident that 852c51b's runtime-state defensive
grouping was working around).

Migration 0012 fixes this at the database layer:

  1. Dedupe existing collisions deterministically. The survivor is
     the row with the longest prompt_queue (so no queued user data
     is lost), with updated_at DESC as tiebreaker. Other fields like
     tab_open and session_status repopulate from the next daemon
     heartbeat, so dropping them on the loser row is acceptable.

  2. Add a functional unique index on (user_id, lower(project_key)).
     From this point on, any writer that bypasses normalization gets
     a DB-level constraint violation instead of silently creating a
     stale duplicate.

Applied to Neon prod: confirmed 0 remaining collisions, the right
row was kept ('cockpit' lowercase with the 2-item queue, not the
empty 'Cockpit' row), and a follow-up probe with
INSERT 'CoCkPiT' rolled back inside BEGIN…ROLLBACK was rejected
with the expected unique_violation error.

Schema declaration uses uniqueIndex + sql\`lower(\${col})\` so
drizzle-kit push treats the live state as authoritative — verified
no drift on project_states. (Unrelated orgs_slug_unique drift was
flagged by drizzle but is out of scope for this commit.)

The defensive .toLowerCase() grouping in runtime-state/route.ts and
stream/route.ts remains useful for in-memory dedup of legacy state
but is no longer load-bearing — the DB now guarantees uniqueness.
2026-05-20 14:16:16 +02:00
g-but 852c51bbab feat(strategist): prompt intelligence v1 — Groq composes context-aware auto-inject bodies
Closes the gap Cursor's audit named and Claude's response confirmed:
auto-inject had become 'generic next_best ladder' instead of
'context-aware prompt that drives the product forward.' Thirty commits
of plumbing (status field, queue in DB, daemon heartbeat, /tmp mirror)
didn't change what the model reads when it wakes up. This commit does.

Full reasoning + design in content/thoughts/strategist-and-prompt-quality.md.

Changes (in order of blast radius):

  1. /api/control/dispatch — strategist v1 (the meat)
     • DispatchAction expands from 'queue | nextbest' to add 'composed'
       and 'off'.
     • DispatchResult.prompt holds the Groq-composed body when
       action='composed'.
     • Groq prompt asks for one of three actions + an optional PROMPT:
       body. The composer drafts a fresh prompt from handoff.next,
       queue tail, recent commits, and outcome streak — concrete verbs,
       named files where possible, ≤2000 chars.
     • maxTokens 100 → 1500 so the composed body has room.
     • Reads auto_inject_mode from beacon_settings and gates:
       off → action='off' (suppress), queue_only → queue or off,
       next_best → skip Groq + return nextbest, strategist → full chain.
     • Strategist now runs even with empty queue — that's when it's
       most valuable (smart nudge from session.next + commits alone).
       Previously short-circuited to nextbest on empty queue.

  2. src/lib/orchestration/renderers.ts — SSOT next_best body
     • Adopts the bash hook's shape (the concrete one user has been
       pasting every loop turn). Old abstract scan ladder is gone.
     • Model-agnostic: avoids assumed tech stack (no hardcoded `git
       status` / `npx tsc`). Verifies via 'are there type/lint/compile
       errors' phrasing that translates across runtimes.

  3. src/hooks/use-project-card-actions.ts — consume composed bodies
     • handleAutoInject branches on action='composed' and injects the
       returned prompt body as a custom prompt instead of firing
       sendIntent('next_best').
     • Respects action='off' from mode_gate by returning early.
     • Pre-fetch fires whenever ready (not gated on queue.length > 0)
       so the strategist can compose even when queue is empty.

  4. beacon_settings.auto_inject_mode (drizzle/0011)
     • New text column, default 'strategist'. Values: strategist |
       queue_only | next_best | off.
     • Schema TS + queries plumbed; UI carryover patched in
       BeaconSettings.tsx (full UI for the toggle is a follow-up).

  5. /api/control/runtime-state — defensive against duplicate keys
     • Found two rows for same lowercase project_key ('cockpit' and
       'Cockpit', empty queue won iteration order). Sync now groups
       by lowercase and prefers the row with the longest queue. The
       duplicate row was deleted from Neon as a one-time fix; long-
       term a uniqueness-on-lowercase migration is queued.

Migrations applied to Neon prod: 0011 via psql + neonctl. Local PG
is no longer authoritative (.env.local now points cockpit-app at
Neon; verified daemon-token auth resolves to default user b94a359d
and runtime-state sync writes /tmp/agent-queue-cockpit with the real
queue content).

Tests: tsc clean, eslint clean (src/ + home/), npm run test:home
89/89. UI for autoInjectMode toggle is queued.

Co-developed with: prompt-quality audit pass from Cursor Composer
2.5 + Claude synthesis; provenance + design rationale in
content/thoughts/strategist-and-prompt-quality.md.
2026-05-20 13:31:57 +02:00
g-but 07549afd2d feat(db): prompt queue moves from /tmp file to project_states.prompt_queue column
Closes the queue-storage gap raised in last turn's evaluation. Before:
the per-project prompt queue lived in /tmp/agent-queue-<tab>, which is
ephemeral on Vercel (lost on cold start) and not user-scoped. After:
project_states.prompt_queue (text[] not null default '{}') is the
source of truth — persists across browsers, Vercel cold starts, and
backed by the same per-(user, project) PK as the rest of session
state.

Files touched:
  • drizzle/0010_project_states_prompt_queue.sql — ADD COLUMN IF
    NOT EXISTS text[] not null default '{}'. Applied to both Neon
    prod and local Postgres via psql.
  • src/db/schema/project-states.ts — promptQueue field added next
    to sessionStatus (also new this week, similar shape).
  • src/app/api/beacon/queue/[tab]/route.ts — rewritten to read/
    write the DB row. Adds proper auth (was unauthenticated; closed
    a real auth gap on the way through). Keeps a best-effort file
    mirror so scripts/agent-hook-bridge.sh's two /tmp/agent-queue-*
    readers don't break (user has denied prior edits to that file
    3x — file mirror stays until that path is touched).

Auth note: the old route had NO auth check. Any unauthenticated
caller could read or overwrite any tab's queue. usePromptQueue is the
only consumer in the codebase and runs in an authed session, so the
new 401 doesn't break any production flow.

What's NOT in this commit (deliberate scope cut):
  • The bash hook's two /tmp readers. Long-term they should query
    the DB via authed API — that's a separate ticket since user has
    repeatedly denied agent-hook-bridge.sh edits.

tsc clean, eslint clean, npm run test:home 85/85.
2026-05-20 11:22:34 +02:00
g-but 15af9d93ea feat(db): add session_status column to project_states (migration 0009)
Completes scope cut #1 from yesterday's 27f31cb commit. The auto-inject
gate now reads status from project_states server-side (not just from
raw session.md content in the beacon), so the cloud /control flow
surfaces the agent's lifecycle state end-to-end.

Plumbing:
  • src/db/schema/project-states.ts — sessionStatus column declared
    (text, nullable). Position: before sessionDone so the SELECT row
    shape reads top-down as status → done → next → ... → health.
  • drizzle/0009_project_states_session_status.sql — idempotent
    ADD COLUMN IF NOT EXISTS. Apply with drizzle-kit push (no
    auto-runner; matches the 0001-0008 pattern).
  • src/app/api/control/route.ts — both upsertProjectState callsites
    (mtime-advanced + bootstrap) now persist session.status.
  • src/app/api/control/stream/route.ts — SSE row construction reads
    r.sessionStatus into session.status alongside the other fields.
  • src/app/api/project-states/[key]/route.ts — PATCH body schema +
    upsert object both accept sessionStatus for the daemon's push.

Migration safety:
  • Column is nullable + new — existing rows get NULL.
  • The auto-inject gate treats NULL/undefined as suppress (matches
    the user's stated default: only fire on explicit 'ready').
  • Idempotent SQL — re-applying the migration won't error.

Apply on production: \`DATABASE_URL=<neon> npx drizzle-kit push\` (or
the user's preferred migration runner).

tsc clean, npm run test:home 82/82.

Scope cut #2 remains queued: agent-hook-bridge.sh:emit_worker_finished
including session_status in worker.finished events (user denied prior
edits 3x — happy to ship if they want or leave it for them to land).
2026-05-20 09:47:42 +02:00
g-butandClaude Opus 4.7 b166f025cc fix(db): create beacon_settings and user_preferences tables
Two tables were declared in src/db/schema (beacon-settings.ts and
user-preferences.ts) but no migration ever shipped them. Production
returned HTTP 500 on /api/beacon-settings and the location/timezone
read paths silently failed because every Drizzle query resolved to a
nonexistent table.

CREATE TABLE IF NOT EXISTS + index for both, matching the schema 1:1.
Applied to the live Neon DB; /api/beacon-settings on prod now returns
200 with the default settings shape ({popup_mode:"web",countdown_seconds:12,
min_idle_seconds:0,whisper_model:"base",transcription_provider:"auto"}).

This concludes the drift sweep started in 0005/0006/0007. A full grep of
src/db/schema/*.ts vs prod information_schema.columns now shows no
missing tables and no real column drift (the remaining false positives
are auth.ts containing 4 tables in one file).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 21:52:58 +02:00
g-butandClaude Opus 4.7 a3e085f6fa fix(db): persist user_projects.org_id migration (control panel was empty)
Same schema-drift pattern as 0005/0006: Drizzle schema declared user_projects.org_id
(uuid → orgs.id, on delete set null) but no migration shipped it. Every SELECT
through Drizzle requested the column, so the query crashed on production,
ensureUserProjectEntityLinks landed in its .catch returning [], and /api/control
reported trackedProjectCount=0 despite 20 active user_projects rows for the
logged-in user. With the column in place, /api/control now returns all 20
project cards — the autonomous loop (outcome streak, sleep mode, dispatch
reasoner, beacon countdown) finally has a surface to render against.

Applied to the live Neon DB; verified via the production /api/control endpoint
returning 20 projects with full dirPath linkage.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 21:45:41 +02:00
g-butandClaude Opus 4.7 3075f7a06c fix(db): align project_states with declared schema (composite PK + missing cols)
The daemon's PATCH /api/project-states/<tab> was returning HTTP 500 against
production with "insert into project_states (...lock_at, agent_running,
tab_open, active_agents...)" — none of those columns existed on prod, plus
the PK was still the legacy single-column form, so the daemon could never
record agent lifecycle (readyAt/closingAt/closedAt) for cloud-mode
deployments. The agent stop hook's patch_project_state was a silent no-op.

Migration adds the four missing runtime-state columns with sane defaults
(agent_running=false, tab_open=false, active_agents='{}'::text[], nullable
lock_at), re-applies the 0002 composite-PK swap idempotently, and verified
against the live Neon DB:

  HTTP 200 {"success":true,"data":{...,"agentRunning":false,"tabOpen":false,
  "activeAgents":[],"readyAt":"...","lockAt":null,...}}

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 21:27:49 +02:00
g-butandClaude Opus 4.7 90c4a4a712 fix(db): persist orchestration_runs.org_id + outcome migration
Production was missing both columns the Drizzle schema declared. The cloud-
mode outcome-tracking loop crashed with HTTP 500 (empty body) because
Drizzle's .returning() RETURNING clause referenced a nonexistent org_id
column. After ALTER TABLE on prod, the finish endpoint returns 200 with
{ok:true, outcome:"success"} for a real run row — verified end-to-end via
the daemon bearer token against cockpitapp.vercel.app.

Includes the partial index that backs getRecentOutcomes() — the ProjectCard
streak chip + dispatch reasoner depend on it being there.

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

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 15:16:18 +02:00
g-butandClaude Sonnet 4.6 1424d0f338 chore(drizzle): track migration journal artifact
drizzle-kit push emits drizzle/meta/_journal.json alongside the SQL files.
Committing so the directory structure is complete.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 04:47:14 +02:00
g-butandClaude Sonnet 4.6 d57e520ea0 fix(build): remove middleware.ts — proxy.ts already handles auth routing
Next.js/Vercel rejects having both middleware.ts and proxy.ts. The existing
proxy.ts already protected all app routes and handles the onboarding redirect.
Extended it with /sign-out and /thoughts as public paths.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-14 15:52:25 +02:00