Commit Graph
1545 Commits
Author SHA1 Message Date
g-butandClaude Opus 4.7 bebc82ffcf refactor(brand): zsh typing-hook contract derived from APP_SLUG
Last hidden 3-way contract between brand and runtime:

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

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 00:19:28 +02:00
g-butandClaude Opus 4.7 2d5d19a0ea refactor(brand): PG NOTIFY channel + trigger function derived from APP_SLUG
The Postgres LISTEN/NOTIFY contract that drives sub-second SSE state
propagation was hardcoded in two files:

  src/db/setup-notify-trigger.ts   creates fn 'cockpit_notify_project_state'
                                   and notifies channel 'cockpit_state'
  src/app/api/control/stream/route.ts   listens on channel 'cockpit_state'

If a brand rename only flipped APP_SLUG without touching these, the trigger
would still emit to 'cockpit_state' but the listener wouldn't subscribe to it
— SSE state push silently breaks while every gate (tsc/lint/smoke) stays
green. Hard-to-spot failure mode.

Now both sides import NOTIFY_CHANNEL + NOTIFY_FN_NAME from
src/db/setup-notify-trigger.ts. Both names derive from APP_SLUG (sanitized
to [a-z0-9_] for safe SQL interpolation, since APP_SLUG itself isn't
user-controlled but the sanitizer is defense-in-depth). The startup
instrumentation logs the resolved names so a deploy mismatch surfaces in
Vercel logs.

After a rename:
  1. Deploy lands new fn+channel names
  2. setupNotifyTrigger runs on next instrumentation boot (idempotent
     CREATE OR REPLACE), installing the new function
  3. Listener subscribes to the new channel on next /api/control/stream
     connection
  4. (Optional cleanup): manually DROP the old cockpit_notify_project_state
     function from DB — orphaned but harmless if left

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

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 00:02:32 +02:00
g-butandClaude Opus 4.7 e86dc0c8be fix(ivy): surface real Groq failure in fallback (was opaque 500)
Probed /api/ivy on cockpitapp.vercel.app: every request returns HTTP 500
with body "Ivy is unavailable right now — please try again in a moment."
because (1) the local openclaw gateway isn't reachable in cloud mode and
(2) the Groq fallback throws on the same invalid GROQ_API_KEY that
/api/control/dispatch already exposes via classified error reasons.

Mirror the classification from 97b6d09 (dispatch route): catch the Groq
exception, regex-match on status code / timeout, and return 503 with a
specific cause in the error body ("Groq API key is invalid", "Groq
rate-limited", etc.). Status changes from 500 to 503 since "service
unavailable" is a more accurate code for upstream-dependency failure.

User-visible: the "Ask Ivy" buttons across the app now say *why* Ivy is
offline instead of looking like a generic crash. Same root cause as
dispatch — rotate GROQ_API_KEY on Vercel to restore full functionality.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 23:51:59 +02:00
g-butandClaude Opus 4.7 42ad38a2f5 refactor(brand): route Ivy system prompt + 11 remaining UI strings through APP_NAME
Audit after a46702f surfaced one more wave of user-visible "Cockpit"
literals — including the Ivy system prompt itself, where the agent
introduces itself as "inside Cockpit". After a rename that string would
make every Ivy response sound wrong. Routed through APP_NAME:

- src/app/api/ivy/route.ts            Ivy system prompt
- src/app/invite/[token]/page.tsx     "Create your Cockpit account"
- src/app/(app)/not-found.tsx         "doesn't exist in Cockpit"
- src/app/(app)/today/page.tsx        first-run callout copy
- src/app/(app)/(private)/goals/page.tsx  Ivy goals-bootstrap prompt
- src/app/verify-email/page.tsx       "Go to Cockpit →"
- src/app/api/agent/launch/route.ts   503 error body
- src/config/marketing.ts             "Continuation loop" feature body
- src/config/beacon.ts                popup-mode description + cons
- src/lib/constants/today.ts          PLAN_DAY_PROMPT preamble
- src/config/prompt-library.ts        Project Status Report + Weekly Review templates

Result: only 2 "Cockpit" refs remain in src/ — both are JSDoc comments
(crons-shared.ts and alerts.ts schema), zero are user- or agent-visible.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 23:44:05 +02:00
g-butandClaude Opus 4.7 a46702f74f refactor(brand): CockpitMark → BrandMark (brand-agnostic component name)
The logo + wordmark component was the last brand-bound name in the
component layer — every importer plus the file itself referenced
'CockpitMark'. Renaming it to 'BrandMark' completes the brand-agnostic
naming pass: after a chosen new name, no component or file in src/
needs touching.

Touches 4 files (rename + 3 import sites): the file itself, PublicSurface,
SidebarBrand, /u/[username]/page. git tracks the move so blame/history
is preserved.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 23:25:29 +02:00
g-butandClaude Opus 4.7 e5c2793fcd refactor(brand): close the rest of the brand leakage the SSOT didn't catch
Audit of remaining 'cockpit' refs after 9ee1df4 surfaced UI-visible leakage
the first pass missed:

- ProfileSettings.tsx           "cockpit.app" → APP_DOMAIN
- onboarding/page.tsx           public-profile preview → APP_DOMAIN
- ThemeProvider.tsx             storageKey="cockpit-theme" → `${APP_SLUG}-theme`
- AgentTokenSettings.tsx        "@cockpit/agent init" → `@${APP_SLUG}/agent init`
- DaemonStatusBanner.tsx        env-var instructions reference APP_DAEMON_TOKEN
                                + the daemon script now interpolates APP_SLUG
- orchestration/run/route.ts    /tmp/cockpit-<adapter>-prompt-* → APP_SLUG

Out of scope (intentional):
- Stripe metadata key cockpitUserId — stable identifier on Stripe's side,
  renaming would orphan existing subscriber records.
- weather route's COCKPIT_LAT/LON/TZ — env-var contract with the weather.sh
  tool, not brand-derived in spirit.
- File names like cockpit-daemon.sh, CockpitMark.tsx — `git mv` is a
  follow-up after a name is chosen, not a prerequisite to renaming the
  visible product.
- README.md, content/*.md — editorial, hand-written, deserves a real pass
  not mechanical sed.

The "one-line rename" claim from 9ee1df4 is now closer to honest: every
user-visible string and every runtime-derived path resolves through
src/config/brand.ts. The remaining work after a chosen name is `git mv`
for component/script file names + content edits, both better done by hand.

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 22:11:32 +02:00
g-butandClaude Opus 4.7 97b6d09b15 fix(dispatch): surface real Groq failure in fallback reason
Probed the /api/control/dispatch endpoint on production: it returns
{action:"queue", reason:"Groq unavailable — using queue order.",
source:"fallback"} regardless of the actual error. Direct curl against
api.groq.com with the GROQ_API_KEY from Vercel env shows 401
"Invalid API Key" — the key on prod is invalid, so the smart-dispatch
streak reasoning hasn't been working at all since outcome tracking
shipped, and the UI gave no hint why.

Catch now inspects the error and classifies (key invalid / rate-limited /
server error / timeout / verbatim) into the reason field, plus a
console.error so debug_logs picks up failures the same way the auth path
already does. Behaviour on success is unchanged.

Action item out of this commit: rotate GROQ_API_KEY on Vercel
production — the current value returns 401 from the Groq API.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 22:02:24 +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 403f47cdd5 fix(control): solo user's own projects were excluded from /control
getOrgProjects(userId) called getOrgPeerIds which intentionally excludes
the caller (it answers "who *else* is in my orgs"). That left a solo user
— or anyone in an org alone, like every new signup before they invite
teammates — with peerIds=[] and getOrgProjects returning [].

Symptom: /api/control returned trackedProjectCount=0 and an empty
projects array on cockpitapp.vercel.app, even with 10 active user_projects
rows for the logged-in user. The control panel rendered no cards, so the
whole outcome-tracking + sleep-mode + dispatch loop we shipped over the
last several sessions had no surface to render against.

Fix: union memberIds = [userId, ...peerIds] before the inArray lookup.
The peer-only semantics live in getOrgEntityProjects (entity layer, with a
readonly:true marker) which is correctly distinct.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 21:37:23 +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 Opus 4.7 c3ded1f2aa docs(env): document COCKPIT_ALLOW_LEGACY_DAEMON_TOKEN requirement
The local daemon authenticates writes to cockpitapp.vercel.app
(patch_project_state, /api/orchestration/runs/<id>/finish, etc.) via the
COCKPIT_DAEMON_TOKEN bearer. src/lib/session.ts:getApiUserId only honors
that token when COCKPIT_ALLOW_LEGACY_DAEMON_TOKEN=1 is also set on the
server — a safety gate to prevent accidental multi-tenant misuse.

Verified by curl: PATCH /api/project-states/<tab> returns 401 without
the flag, even with a valid token. With the flag, the daemon-side loop
(state push + outcome finish) closes against the cloud deployment.

Companion change: set COCKPIT_ALLOW_LEGACY_DAEMON_TOKEN=1 on Vercel
production (via vercel env add, no commit).

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

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

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:40:56 +02:00
g-butandClaude Opus 4.7 66bb13e0bd feat(control): sleep mode — global toggle that auto-fires every ready banner
The third leg of the autonomous loop. The first two (outcome capture →
streak surfacing) shipped last session. This closes the user's "I want to
go to bed and have it just build" ask.

- New useSleepMode() hook backed by SLEEP_MODE_KEY localStorage. Auto-exits
  on the next keydown/pointerdown so simply touching the laptop restores
  normal-confirm behavior — no need to find the toggle.
- New POST /api/control/sleep-mode writes /tmp/cockpit-sleep-mode for
  agent-hook-bridge.sh to read in a follow-up (skip-popup entirely while
  sleep is on). Web-app path is already covered.
- ReadyBanner forces seconds=0 when sleep is on, so the existing
  onAutoInject path fires immediately instead of after AUTO_INJECT_S
  (default 12s). Timer label switches to "Sleep" so the state is visible.
- Control panel header gains a Moon icon next to the view-mode toggle.
  Filled when on, accent-text colored, tooltip explains the wake gesture.

Deliberately small: not the full autonomyMode enum refactor, just the
user-visible "walk away" feature on top of the existing autoContinue
machinery. The enum migration can land later without breaking this.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:34:28 +02:00
g-butandClaude Opus 4.7 cf241e8e51 chore(auth): trim signIn diagnostic now that root cause is fixed
Keep:
- logger.error → debug_logs (low volume; first line of diagnosis next time
  Vercel CLI logs are unreachable)
- events.signIn org bootstrap (the actual fix, not diagnostic)

Remove:
- debug: true (noisy in steady state)
- verbose logger.warn / logger.debug stubs
- per-call signIn try/catch DB write (debug_logs already captures via the
  logger when Auth.js wraps the error as AccessDenied)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:09:28 +02:00
g-butandClaude Opus 4.7 270587a53b feat(control): surface recent outcomes on ProjectCard and dispatch reasoner
Visible payoff of the outcome-tracking loop:

- ProjectCard header gains a compact 5-glyph streak chip
  (✓ success · ~ partial · ✗ error/hang/timeout · ✕ user_abort)
  rendered via the new <OutcomeStreak> component using existing
  ui-tag-positive / -warning / -negative tone classes — no new tokens.
- /api/control/route.ts batches outcome lookup across all projects in a
  single query (getRecentOutcomesByProjectKeys) and threads it into the
  per-project ProjectState shape under `recentOutcomes`.
- /api/control/dispatch reads getRecentOutcomes(projectKey, 5), feeds the
  glyph streak into the Groq prompt so the strategist sees recent
  performance, and appends "[last 5: ✓✓✗✓✓]" to the dispatchReason
  surfaced in the ReadyBanner.
- Client now passes projectKey along with the existing handoff/queue/git
  context to /api/control/dispatch.

Together with the data-layer commit, this closes the smallest possible
loop: dispatch → outcome capture → next dispatch reads outcomes →
strategist + UI see what worked last time.

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 20:03:34 +02:00
g-butandClaude Opus 4.7 7fa4e7b971 fix(auth): don't pass OAuth provider's user id to UUID-typed Postgres queries
Auth.js v5 calls the signIn callback BEFORE handleLoginOrRegister creates the
DB user, so user.id at that point is the OAuth provider's id (e.g. GitHub's
numeric "41178744"), not our DB UUID. Calling getOrgMembershipCount(user.id)
then trips PostgreSQL's UUID parser, which Auth.js wraps as AccessDenied.

Move the org-bootstrap call into the events.signIn hook, which fires AFTER
the DB user is created/linked — at that point user.id is the real UUID.

Profile sync stays in signIn callback but now resolves the DB user via email
before any UUID-typed write.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 19:57:32 +02:00
g-butandClaude Opus 4.7 29b3365694 chore(auth): unwrap nested cause when persisting Auth.js errors
The first capture surfaced "AccessDenied" but the inner cause object was
JSON.stringified as "[object Object]". Walk Error.cause chains and serialize
nested Error fields so the actionable detail (which adapter/provider call
threw) lands in debug_logs.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 19:52:55 +02:00
g-butandClaude Opus 4.7 665211b22a chore(auth): write Auth.js errors to debug_logs table for diagnosis
Vercel runtime logs aren't reachable via CLI/API in this environment.
Persist Auth.js error events to the database so they can be queried directly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 19:35:56 +02:00
g-butandClaude Opus 4.7 969db60610 chore(auth): enable Auth.js debug + logger to surface AccessDenied cause
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 19:22:03 +02:00
g-butandClaude Opus 4.7 2916db290d chore(auth): log signIn callback path to diagnose AccessDenied on Vercel
Temporary diagnostic — will be removed once the root cause is fixed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 19:02:41 +02:00
g-butandClaude Opus 4.7 4d3cad64d1 perf(beacon): filter to main window and reorder xdotool to skip slide
Two related fixes for the off-screen pre-warm window flow:

1. --name Beacon: Brave creates 2-3 internal splash subwindows that
   share WM_CLASS=cockpit-beacon but have no title. Chaining
   map/move/activate across all of them was wasted work; only the
   actual page window has "Beacon" in its title.

2. Move before map: KWin Wayland animates a slide-in (~150-200ms) when
   a window is mapped at a position different from its last-known
   geometry. Moving the unmapped window first costs ~0ms (no
   compositor work — the window isn't visible), and the subsequent
   map then has nothing to animate. Drops show latency from ~380ms
   to ~36ms on KDE Plasma 6. --sync no longer needed since each
   step is fast and the chain is serialized inside xdotool anyway.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 18:15:24 +02:00
g-butandClaude Opus 4.7 a9fd60d5a7 fix(beacon): resolve transcribe.py path under standalone deployment
The cockpit-app systemd service runs Next.js from .next/standalone, so
process.cwd() points at the bundle root and scripts/transcribe.py was
missing. Probe the repo-root and standalone-relative locations, with
COCKPIT_SCRIPTS_DIR override for relocated bundles.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 18:13:42 +02:00
g-butandClaude Sonnet 4.6 252bfea7b5 fix(beacon): stale session ID on multi-session SSE updates
BeaconPageClient used useState(initialSession) which only captures the
prop on first mount. When a second beacon session arrived via SSE,
BeaconLiveClient updated its session state (showing the new content)
but BeaconPageClient stayed mounted with the OLD session ID — so every
PATCH went to the previous session, which beacon.py wasn't polling.

Fix: add key={session.id} so React remounts BeaconPageClient when the
session changes; also drop the redundant useState and use the prop
directly since the component is now always fresh on arrival.

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 16:31:14 +02:00
g-butandClaude Sonnet 4.6 b9dbbc436b fix(weather): geocode city to lat/lon; remove shell injection risk
The weather route was embedding the user's city string directly in the
bash command passed to runTool (shell: bash), making it vulnerable to
command injection via $() and backtick expansion inside double quotes.

Fix: geocode the active city via Open-Meteo's geocoding API in the
route (24 h in-memory cache), then pass lat/lon/timezone as env vars
to weather.sh — safe numerics never interpreted by the shell.

Update weather.sh to read COCKPIT_LAT / COCKPIT_LON / COCKPIT_TZ with
Zurich as fallback, so the weather data actually matches the user's city
instead of always showing Zurich regardless of the location setting.

Also add extraEnv parameter to runTool so callers can inject env vars
without putting user data in the command string.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 16:24:06 +02:00
g-butandClaude Sonnet 4.6 1369768bcd fix(settings): location UI stays stale after save/clear
After saving or clearing the current location override, the "Currently
in" badge and dirty-check both used the original server props, so the
badge never disappeared and the Save button re-enabled immediately.
Introduced savedPrefs state that mirrors the server and gets updated on
every successful PATCH, so the UI reflects what was actually persisted.

Also merged the two duplicate @/lib/api/fetch imports in AccountSettings.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 16:17:06 +02:00
g-butandClaude Sonnet 4.6 1cea8cc6d0 fix(location): active city/timezone ignored when no expiry date set
getActiveCity and getActiveTimezone required currentCityUntil to exist
before currentCity/currentTimezone was used. The UI marks 'Until' as
optional, so setting a current location without an expiry silently fell
back to home — making the feature appear broken.

Fix: only skip currentCity when an expiry IS set and has already passed.

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

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 15:40:08 +02:00
g-butandClaude Sonnet 4.6 55a06d5141 refactor(today): extract ui-btn-pill classes, clean unnecessary grid wrapper
- Add ui-btn-pill / ui-btn-pill-muted / ui-btn-pill-positive to globals.css
  (DRY: was copy-pasted as 60-char className in 4 places)
- Use ui-btn-pill-positive for IvyDispatchButton (Plan/Wrap up day)
- Use ui-btn-pill-muted for LogConversationButton and QuickCaptureButton
- Remove single-child grid wrapper around RecentRunsCard
- Remove wrapper divs in RecentRunsCard and StuckGoalsCard; use Card id= directly

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 14:55:25 +02:00
g-butandClaude Sonnet 4.6 38ecdfc995 feat(mobile): projects page responsive fixes
- ProjectDetailHeader: always flex-row so X close button is top-right on
  all screen sizes, not buried below name/desc on mobile
- ProjectCard: always flex-row items-start justify-between so action icons
  are top-right rather than left-aligning below the name on mobile
- ProjectDetailTabBar: flex-1 justify-center on each tab — equal-width
  tabs filling the full drawer width instead of content-width tabs
- Drawer: sm:border-l — suppress left border on full-width mobile drawer

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 12:05:29 +02:00
g-butandClaude Sonnet 4.6 98876dfee8 fix(beacon): SSE delivers pending sessions to new subscribers
The seen-set was seeded with ALL existing files at connect time, so any
session written by beacon.py before the browser window opened was never
pushed — causing the /beacon/live window to hang on "Waiting for Claude…"
indefinitely.

Fix: seed seen-set with only resolved sessions (choice != null); push the
most recently created pending session immediately on connect so pre-warmed
windows and freshly opened windows both receive the current beacon.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 11:49:54 +02:00
g-butandClaude Sonnet 4.6 1c00febd1a refactor(projects): createdAt display, SSOT channels, status badge map, ivy-prompts
- Add createdAt to ProjectData and display relative date in header
- CHANNEL_CONFIG replaces PROJECT_CHANNELS string array as SSOT (key+label pairs)
- StatusBadge uses lookup map instead of string-matching conditionals
- buildProjectIvyPrompt extracted to lib/ivy-prompts — removes duplication between ProjectGrid and ProjectDetailHeader
- DescriptionEditor shows pencil icon on hover
- "No context" placeholder replaced with dashed border call-to-action

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 11:47:44 +02:00
g-butandClaude Sonnet 4.6 24f83b8d63 refactor(projects): SSOT health signals, IvyDispatch in header, real-data goal reload
- HEALTH_SIGNAL_BASE moved to project-detail-types.ts (no Lucide dep — safe for
  any importer); project-badges.tsx merges in icons via KIND_ICON map
- ISSUE_ATTRS now derived from HEALTH_SIGNAL_BASE — never hand-maintained again
- ProjectDetailHeader: IvyDispatchButton wired with project context prompt;
  Issues badge upgraded to ui-tag-negative chip
- GoalsTab: drops optimistic state, uses onReload() so parent refetches and real
  progress/status/milestones flow back in; empty state gets Target icon
- OverviewTab: CHANNEL_ICON map for recent-activity entries
- Drawer gains "2xl" size; ProjectDetail uses it for more breathing room
- modal.tsx: Drawer size union extended to include "2xl"

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

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

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

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 10:50:25 +02:00
g-butandClaude Sonnet 4.6 c99eb81833 perf(sse): event-driven SSE — file watcher + Postgres LISTEN + failed command surfacing
Replace 2s polling loop with three event sources:
- File watcher on /tmp/agent-* sentinels (local, <50ms latency)
- Postgres LISTEN/NOTIFY on project_states (Vercel, ~200ms)
- HTTP push from daemon → SSE bus → immediate wake (both paths)
Fallback tick reduced: 10s local, 5s Vercel (was 2s unconditional).
Failed commands (ok=false in last 10min) now surface in AttentionBar
with per-item dismiss via localStorage.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 10:32:39 +02:00