Commit Graph
1545 Commits
Author SHA1 Message Date
g-butandClaude Opus 4.7 a7c37c358d fix(projects): GitHubStatus shows 'connect daemon' instead of fake 'No repo data'
Same pattern as commit 3ee1567 (CalendarCard on /today). The
GitHubStatus card on /projects always rendered "No repo data" for
cloud users because /api/github returned `{repos: []}` when
isRuntimeAvailable was false — the github-status.sh script runs the
local `gh` CLI which doesn't exist on Vercel. Users saw an empty
"CI / GitHub" card and had no way to know it was a runtime gap rather
than a genuinely-no-repos state.

Fix mirrors the calendar fix:
  • /api/github cloud branch now returns {repos: [], runtimeOnly: true}.
  • GitHubStatus checks data.runtimeOnly before the repos.length === 0
    branch and renders "CI status shows here once the local daemon is
    connected." — ties the empty state to the same daemon-install
    requirement that DaemonStatusBanner on /control already names.

Local dev (runtimeAvailable=true) behavior unchanged — when the gh
CLI returns no repos for real, the old "No repo data" copy still shows.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 09:22:41 +02:00
g-butandClaude Opus 4.7 3ee1567d56 fix(today): cloud users see 'connect daemon' instead of fake 'No events today'
Onboarding-funnel audit continued — /today is the default landing
surface, and a brand-new cockpitapp.vercel.app user always sees the
CalendarCard render "No events today" because:

  • /api/calendar returns `{events: []}` in cloud mode (isRuntimeAvailable
    is false — the calendar source is `gog calendar list`, a local
    Google CLI), and
  • CalendarCard treats events.length === 0 as the "you have nothing
    on today's calendar" branch.

That's misleading. The user might have a packed calendar locally but
is staring at "No events today" with no indication that the empty state
is a runtime gap, not a real reflection of their day. They have no
reason to ever check Settings or install anything based on what they
see.

Fix: the cloud branch now returns `{events: [], runtimeOnly: true}`.
CalendarCard checks `data.runtimeOnly` before the empty branch and
shows "Calendar shows here once the local daemon is connected." —
links the surface to the same daemon-install requirement that
DaemonStatusBanner on /control already names.

WeatherCard already handles cloud mode correctly via 947fc55 (HTTP
fallback to open-meteo); GitHubStatus is on /projects, not /today, so
out of scope for this commit.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 09:08:59 +02:00
g-butandClaude Opus 4.7 954030218c fix(control): "+ New" toolbar opens Register on cloud instead of Bootstrap
Session next caught the remaining leak. Commit 3b2fbad hid Bootstrap-
with-AI from the /control empty state on cloud (where /api/project/
ai-brief always 503s), but the BrainConfigPanel headerRight toolbar
still had a "+ New" button hard-wired to open BootstrapModal — same
dead-end, just from a different entry point.

Routed the toolbar "+ New" through the same runtimeAvailable check:

  • runtimeAvailable=true  (local dev with claude CLI) → BootstrapModal,
    title "Bootstrap new project" (unchanged behavior).
  • runtimeAvailable=false (cockpitapp cloud) → NewProjectModal, title
    "Register existing project" — same intent ("add a project"), but
    routes to the flow that actually works in cloud mode.

Preserves the affordance for cloud users instead of hiding it; they
still get a working "+ New" button, just one that lands them on the
Register path. Verified live on local — title still reads "Bootstrap
new project" and clicks BootstrapModal as before.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 08:54:50 +02:00
g-butandClaude Opus 4.7 3b2fbadaae fix(control): hide Bootstrap-with-AI on cloud where the API always 503s
Onboarding-funnel dead-end. A brand-new cockpitapp.vercel.app user lands
on /control, sees the existing empty state's "Bootstrap new project →"
primary button, types a project idea, clicks Generate — and gets a 503
from /api/project/ai-brief because that route requires
isRuntimeAvailable() (true only on local dev where the claude CLI is
on $PATH). Cloud users have no path forward on the Bootstrap button
ever; the only working option is "Register existing project."

ProjectFleetView didn't know whether the runtime was available, so it
showed Bootstrap unconditionally. Threaded the existing runtimeAvailable
flag from useControlData → ControlPanel → ProjectFleetView and:

  • Hide the Bootstrap button entirely when runtimeAvailable is false.
  • Promote Register existing project to the primary button (was
    secondary alongside Bootstrap) so cloud users get one clear CTA.
  • Add a one-line helper underneath: "Bootstrap-with-AI is available
    once the local daemon + claude CLI are installed (see the 'Finish
    setup' banner above)." — sets expectations without dumping a wall
    of text into the empty state.

On local dev (RUNTIME_AVAILABLE=true) the empty state looks unchanged:
Bootstrap stays primary, Register stays secondary, no helper text.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 08:40:54 +02:00
g-butandClaude Opus 4.7 7c41e9b12c fix(settings): /settings#<tab> deep links open the right tab
Onboarding-funnel audit found a broken handoff. The DaemonStatusBanner
shipped in 0f96cb2 directs new users to /settings#tokens to mint a
daemon token, but SettingsTabs initialized to "profile" with no URL-hash
handling — the deep link silently dumped the user on Profile, and they
had to discover the Agent tab themselves. Two-fix combo:

  1. SettingsTabs reads window.location.hash via a useState lazy
     initializer (pure function so no cascading-renders lint hit and SSR-
     safe via `typeof window` guard). Direct tab-id match wins;
     otherwise a HASH_TO_TAB alias table handles drift between the
     banner copy ("tokens") and the tab id ("agent"). Tokens, agent-token,
     agent-tokens all resolve to the Agent tab.

  2. Banner deep link updated from /settings#tokens → /settings#agent
     (the canonical tab id). The HASH_TO_TAB alias keeps any cached/
     bookmarked /settings#tokens URLs working after the change.

Verified live in Playwright at desktop width:
  • /settings#agent → activeTab=Agent, Agent Tokens panel visible ✓
  • /settings#tokens → activeTab=Agent (alias resolves) ✓

Side-benefit: any future /control nudge that wants to deep-link to a
specific settings tab can now do so just by writing the right hash —
no more silent-Profile dumps.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 08:27:03 +02:00
g-butandClaude Opus 4.7 0f96cb2e70 feat(control): first-time setup checklist replaces single-command nudge
Onboarding gap surfaced in a user conversation: a brand-new web user
who signs up on cockpitapp.vercel.app gets the life-OS surfaces
immediately, but the agent fleet (the headline /control feature) only
works after they install three pieces locally — none of which the UI
ever names. They discovered the requirement by hitting the wall: try
to dispatch, see DaemonStatusBanner pop up with a single "start the
daemon" command and no mention of Zellij or the agent CLIs.

Replaced the daemonNeverSeen branch of DaemonStatusBanner with a
three-step checklist that names every prerequisite up front:

  1. Install Zellij (link to zellij.dev — the terminal multiplexer the
     daemon injects prompts into).
  2. Install at least one agent CLI of choice (Claude Code, Codex,
     Gemini, openclaw) on $PATH.
  3. Mint a daemon token at Settings → Agent tokens (deep-linked) and
     run the daemon command shown.

The daemonOffline branch (returning user whose daemon dropped — they
already have everything installed) keeps its existing minimal restart
copy unchanged. That user doesn't need the install steps re-explained.

Title shifted from "Local daemon not connected" → "Finish setup to
dispatch agents" so the warning reads as a guided onboarding step
rather than a runtime error.

Side benefits:
  • Deep-link to /settings#tokens makes the token flow discoverable.
  • External Zellij link uses noopener+noreferrer (security default).
  • Existing dismiss button still works — power users can hide it.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 08:08:49 +02:00
g-butandClaude Opus 4.7 23174f37a3 fix(auth): suppress redundant catch-all log row on CredentialsSignin
After commits 91a5989 (logAuthReject) and 5287904 (logAuthAccept) added
structured forensics for every credentials sign-in attempt, the old
catch-all logger.error path kept firing in parallel — Auth.js calls
logger.error after authorize() returns null, so every credentials reject
landed TWO rows in debug_logs:

  • auth.authorize / warn  — provider/reason/identifier structured row
  • auth / error          — useless "Read more at .../credentialssignin"
                            with minified stack and nothing actionable

Verified live by triggering a reject on prod — both rows landed within
the same second, both pointed to the same user attempt.

The structured row is the canonical one. Suppress the catch-all when
err.type === "CredentialsSignin"; keep every other type flowing
(MissingCSRF, AccessDenied, OAuthCallbackError, system errors) since
those don't have dedicated loggers and the catch-all is their only
debug_logs surface.

Three-line guard at the top of logger.error.

Verified live: triggered a credentials reject against the local dev
server (which writes to the shared Neon DB) and confirmed only ONE
new row landed in debug_logs with source='auth.authorize' —
no companion source='auth' row this time. Halves the row count on
brute-force bursts.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 07:57:15 +02:00
g-butandClaude Opus 4.7 360e8ce1aa fix(control): toolbar icons 18×18 on tablet — extend tap target through lg
User's "this area still looks awful" complaint had two parts. The model-input
duplication was addressed in ec27b5c; this fixes the other half — the four
toolbar buttons in the BrainConfigPanel headerRight strip (sleep mode,
view mode, refresh, "+ New") were 18×18 px at iPad portrait width
(768×1024), well below the WCAG 2.5.5 / iOS HIG 44px tap target.

Root cause: ui-icon-btn carries `sm:min-h-0 sm:min-w-0` which collapses
the 44px tap target at the 640px breakpoint, but iPad portrait is at
768px and is still a touch-only device. The toolbar bar effectively
became unusable from a tablet — four invisible-to-fat-finger dots
crowded together in the top-right corner.

Fix: added a touch-friendly SSOT variant `ui-icon-btn-touch` that
collapses at `lg:` (≥1024px) instead of `sm:` — keeps 44×44 through
tablet widths, only releases at true desktop where a pointer is the
dominant input. Applied to the three control toolbar buttons that
used ui-icon-btn, plus updated the inline-class "+ New" button from
`sm:min-h-0` to `lg:min-h-0` to match the new policy.

Did NOT change the SSOT `ui-icon-btn` class itself — 14 other call
sites (goal-card-helpers, project-overview-helpers, queue-list, etc.)
sit inside dense desktop layouts where 44×44 would push rows taller.
The new class is opt-in for explicitly touch-friendly toolbars.

Verified live in Playwright:
  • 768×1024 (iPad portrait): all 4 toolbar buttons 44×44 (or 47×44 for
    the wider "+ New").
  • 1280×800 (desktop): same buttons collapse back to 18×18 / 20px —
    desktop look unchanged.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 07:42:42 +02:00
g-butandClaude Opus 4.7 ec27b5c758 fix(control): hide redundant model input when value matches a chip
User complaint, verbatim: "this area still looks awful. wtf … sonnet
sonnet haiku opus." The BrainConfigPanel on /control rendered both:

  • An <input> with value "sonnet"
  • A chip-toggle button labeled "sonnet" (highlighted as active)

…stacked one above the other. Readers parse the duplication as a bug,
not as "same value, two views." Verified live at 768×1024 (iPad
portrait) — the input was a full-width box visually competing with the
chips below it.

The chips already cover the common case (sonnet / haiku / opus for
Claude, similar lists for Codex / Gemini). The input is only useful
when the user wants a model name NOT in the suggestion list. So:

  • Hide the <input> when modelSuggestions.includes(model) — chips
    handle it.
  • Add a "Custom…" chip after the suggestion chips that, when clicked,
    sets the model value to "" (which falls outside modelSuggestions),
    causing the input to render so the user can type.
  • Clicking any suggestion chip while in custom mode collapses the
    input back away (same logic).

Verified live in Playwright:
  • iPad portrait 768×1024: panel collapses from "input + 4 chips"
    to just "4 chips + Custom…" — no more "sonnet" twice.
  • Custom click → input appears with empty value.
  • Click any suggestion chip → input hides again.
  • iPhone 390×844: same behavior, panel ~30% shorter.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 07:26:33 +02:00
g-butandClaude Opus 4.7 c6f57d1bbb refactor(orchestration): unify detail field on task_completed/task_failed events
After commit a12d2d9 closed the lifecycle pair across every adapter, the
detail field — the human-readable summary attached to each
orchestration_events row — had drifted across five emit sites into four
different formats:

  • route.ts:354    ${intent.name} — ${message}            (em-dash)
  • route.ts:436    openclaw worker start failed: ${msg}   (verbose prefix)
  • inject.ts:225   ${promptLabel} — ${result.error}       (em-dash)
  • worker.ts:72-3  ${intent} done | ${intent}: ${error}   (split formats)
  • worker.ts:88    ${error.message}                       (no intent context)

Downstream chart/list queries would need to grep multiple separator
formats and strip multiple prefix variants. Unified to one canonical
shape across all five sites:

  success → "<intent_or_label>"            (no trailing " done")
  failure → "<intent_or_label>: <error>"   (single-colon separator)

Operators can now split on the first colon to extract the intent label,
or pattern-match `:.*` to extract the error. The verbose "openclaw
worker start failed:" prefix is gone — the `source: 'api-orchestration'`
column already carries that context.

No schema changes. detail column is still truncated to 400 chars. The
existing task_started emits (which only carry the intent name with no
error) were already consistent and untouched.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 07:06:23 +02:00
g-butandClaude Opus 4.7 a12d2d9841 fix(orchestration): wire openclaw lifecycle events end-to-end
The codex/gemini branch in /api/orchestration/run emits task_started at
line ~296 before injectIntoTab. The openclaw branch did not. So every
successful openclaw run was invisible in orchestration_events — only
its orchestration_runs row existed. Commit 9a0ac77 closed the worker-
start-failure pair (failed-to-spawn now emits task_failed), but the
happy path and the in-worker error path were both still silent.

Three coordinated changes:

  1. Route emits task_started before scheduleOpenClawWorker — mirrors
     the codex/gemini emit shape so dispatches across all adapters look
     uniform in queries.

  2. scheduleOpenClawWorker signature gains userId, encodes it into
     the base64 payload. The worker needs user_id to write to
     orchestration_events (NOT NULL constraint).

  3. Worker emits task_completed (state:'done') or task_failed
     (state:'error' or thrown) after its terminal updateOrchestrationRun.
     Source field 'openclaw-worker' (vs 'api-orchestration' on the start
     event) so timeline queries can tell which process emitted what.

After this, orchestration_events carries a full started/completed-or-
failed pair for every openclaw dispatch — same shape as codex/gemini —
and the single dispatch-success-rate query introduced in 9a0ac77 covers
every adapter without per-adapter casing.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 06:55:58 +02:00
g-butandClaude Opus 4.7 9a0ac77ac3 fix(orchestration): emit task_failed on dispatch failure paths
Completes the lifecycle pair on the failure side. After commit 81f4dc3
closed task_started → task_completed on the happy path, the failure path
was still silent in orchestration_events:

  task_failed: 0 rows (lifetime)

…despite three real failure code paths each calling logDebug and either
returning 500 or marking orchestration_runs outcome:'error' — none wrote
to orchestration_events, so a single one-query dispatch-outcome timeline
could only see successes.

Three sites instrumented, each mirrors the existing task_started emit
shape (userId, projectId, projectKey, source, adapter, intent, detail)
with eventType:'task_failed' and detail carrying the truncated error
message:

  1. src/app/api/inject/route.ts !result.ok branch
     — covers the /api/inject failure path (the most-trafficked dispatch
       entry); previously every failed inject left an orphan task_started
  2. src/app/api/orchestration/run/route.ts codex/gemini catch
     — task_started was already emitted ~line 296 before injectIntoTab;
       if that throws, the pair closes here
  3. src/app/api/orchestration/run/route.ts openclaw worker catch
     — the orchestration_runs row was already marked outcome:'error'
       by commit 384cacc, but orchestration_events had nothing — now
       has the matching event row

All three writes are fire-and-forget (.catch(console.error)) so
telemetry failures don't break the user-facing error response. detail
field truncated to 400 chars (column is text but no need to dump full
stack into an events stream).

After this lands, the operator query becomes:

  SELECT date_trunc('hour', happened_at) hr,
         event_type, COUNT(*)
    FROM orchestration_events
   WHERE happened_at > NOW() - INTERVAL '24 hours'
     AND event_type IN ('task_started','task_completed','task_failed')
   GROUP BY 1, 2 ORDER BY 1 DESC, 2;

…which reads as a chronological dispatch-success-rate view. Previously
the same query showed only the 'task_started' column populated.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 06:44:16 +02:00
g-butandClaude Opus 4.7 81f4dc397a fix(orchestration): emit task_completed alongside input_requested on ready sentinel
Lifecycle telemetry was half-wired. Across all time the orchestration_events
table had:

  task_started:       336
  input_requested:    352
  continue_requested: 146
  close_requested:      2
  task_completed:       0  ← the gap

`task_completed` was a defined OrchestrationEventType in contract.ts but
no code ever wrote it. Every dispatch landed a task_started row, then
either an input_requested (when the agent signaled ready) or nothing
(stalled / closed / etc.) — leaving every started task in an indeterminate
end-state. Pair queries like "how many tasks completed in the last hour"
or "which started tasks never finished" weren't answerable.

Root cause in collectRuntimeLifecycleEvents: when runtime.readyAt fires
it only pushed input_requested. Semantically the "ready" sentinel means
TWO things simultaneously — the agent is done with the current task AND
is waiting for the next input. Emit both events from the same timestamp
so the lifecycle pair closes:

  • input_requested  → drives the UI ready-banner via deriveLifecycleState
                       (existing consumer, unchanged)
  • task_completed   → closes the started/completed pair for queries

shouldPersistLifecycleEvent dedupes per-type so we won't double-write
on subsequent control polls — the second emit is no-op once the table
has a row. No code consumes task_completed yet, so this is forward-only
instrumentation: future commits can answer dispatch-success rate, MTTR
on agent runs, etc., without bookkeeping changes elsewhere.

Cost: doubles the row count for the readyAt code path (~336 lifetime
events → ~672). Trivial.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 06:32:30 +02:00
g-butandClaude Opus 4.7 41aee9e602 fix(telemetry): replace useless "[object Object]" cause fallback with best-effort shape
A 2026-05-19 accessdenied entry surfaced an unrelated telemetry bug: when
Auth.js threw with a circular-ref `cause` (its internal errors carry
context object refs that loop), JSON.stringify in the unwrapCause helper
threw, the catch ran `String(c)`, and we got `"cause": "[object Object]"`
in debug_logs — the worst possible fallback. Forensics value: zero. The
operator can't tell what kind of object the cause was, what URL or
provider triggered it, nothing.

Replaced the catch path with a best-effort shape extractor:

  1. __ctor   — c.constructor?.name (e.g. "URL", "Request", "AuthError")
  2. scalars  — every own-property whose value is string/number/boolean/null
  3. errors   — nested Errors get {name, message} flattened (one level)

This is safe by construction:
  • No recursion → can't loop on circular refs
  • Reads only own enumerable keys → won't trip getters/Proxy traps
  • Wrapped in its own try/catch → falls back to String(c) if even Object.keys throws

The result for the failing accessdenied case would have been roughly:
  { __ctor: "Object", url: "https://.../api/auth/callback/github", ... }
instead of the useless "[object Object]".

The happy path (JSON.stringify succeeds — every well-behaved cause) is
unchanged, so this only kicks in for pathological cases that previously
gave zero signal.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 06:20:55 +02:00
g-butandClaude Opus 4.7 5287904cc0 feat(auth): record credentials sign-in successes alongside rejects
Follow-up to 91a5989 (structured reject forensics). The reject helper made
"why did sign-in fail" answerable, but without a matching success record
the pair correlation is lost — debug_logs can't tell:

  • 5 rejects + 1 success  →  forgotten password recovered
  • 5 rejects + 0 success  →  locked-out user gave up OR attacker bailed
  • 0 rejects + 1 success  →  normal sign-in
  • 5 rejects + 5 success  →  busy household sharing a laptop (benign)

Added a `logAuthAccept(provider, identifier, userId)` companion that mirrors
the existing logAuthReject helper but with level:'info' and message
'credentials accepted'. Wired into the success return path of all three
Credentials providers (local / email-password / user-password). Identifier
preserved (email or userId) plus the resolved DB userId so an operator can
join across the user table for richer queries.

Operator workflow becomes:

  SELECT to_char(created_at, 'HH24:MI:SS') t, level, message, meta->>'identifier'
    FROM debug_logs
   WHERE source='auth.authorize'
     AND created_at > NOW() - INTERVAL '1h'
   ORDER BY created_at;

…which reads chronologically as "X tried 5 times, succeeded on the 6th"
or "X tried 5 times, never succeeded" — exactly the signal needed to
distinguish a real lockout from a recovery.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 06:10:01 +02:00
g-butandClaude Opus 4.7 91a5989182 feat(auth): structured forensics on credentials sign-in failures
debug_logs forensics on auth was useless: six "Read more at
https://errors.authjs.dev#credentialssignin" entries clustered in a
2-minute window on 2026-05-20 with no way to tell brute-force from
forgotten-password from missing-account. Auth.js wraps every
authorize()→null in a generic CredentialsSignin error whose .message
is just the help URL — and the meta only carries the minified stack
(name:"w", type:"CredentialsSignin"), nothing about which provider
was tried or why it rejected.

Three Credentials providers in src/auth.ts (local, email-password,
user-password), each with 4 null-return paths. Replaced all 12
`return null` reject sites with `return logAuthReject(provider,
reason, identifier)` — a small helper that fire-and-forgets a warn-
level debug_logs row capturing:
  • provider:    "local" | "email-password" | "user-password"
  • reason:      "missing-input" | "user-not-found"
              | "no-password-hash" | "wrong-password"
  • identifier:  email or userId, NEVER the password

This makes "why can't I sign in" a one-query answer:

  SELECT meta FROM debug_logs
   WHERE source='auth.authorize' AND created_at > NOW() - INTERVAL '1h'

Operator can now distinguish:
  - 6 wrong-password for one email → forgotten password
  - 6 user-not-found for varying emails → enumeration/brute-force
  - 6 no-password-hash for one email → OAuth-only account hitting
    the password form (a real UX bug worth chasing)

Did NOT modify the catch-all logger at src/auth.ts:67 — it still
captures system errors (DB unreachable, etc.) where the generic
message is appropriate. This change targets the reject path only.

tsc + eslint + build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 05:59:11 +02:00
g-butandClaude Opus 4.7 1762d86ff2 fix(mobile): inline-edit icon buttons — 26px → 44px tap target (height only)
Last unfixed mobile tap-target SSOT. ui-btn-confirm-icon (the green Check
button in inline-edit rows on HabitRow, GoalCard, AddHabitForm,
goal-milestone-helpers, project-overview-helpers, goal-card-sections,
HabitCard) and its paired sibling ui-btn-inline-cancel (the X button next
to it) were both 26-32px tall.

Decision: height-only lift (min-h-11 sm:min-h-0). The instinct to also
add min-w-11 would have made the buttons 44×44 on mobile, but they sit
in flex rows next to a `flex-1` text input — pushing them to 44 wide
would steal ~30px from the input on a 390px viewport and squeeze it
below readability. A 26×44 vertical-strip target is the same pattern
as iOS keyboard arrow keys: narrow but tall enough to thumb-tap reliably,
and the whole inline-edit row now reads as a single 44px-tall control
strip with the input vertically-centered in it.

Verified live on /today AddHabitForm at 390×844:
  • ui-btn-confirm-icon (Check): 26×26 → 26×44
  • ui-btn-inline-cancel (X):     24×24 → 24×44
  • input:                        170×44 (vertically centered, unchanged width)
Desktop at 1280×800: both buttons return to 32px (sm:min-h-0 collapses,
natural p-1.5 height takes over).

This closes the mobile tap-target audit on the canonical button/chip/link
SSOT classes. Every primitive in @layer components now carries the
min-h-11 sm:min-h-0 trick.

tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 05:47:07 +02:00
g-butandClaude Opus 4.7 94b31ec7d9 fix(mobile): ui-btn-confirm/-sm/-danger — 34px → 44px tap target on touch
Cross-route sweep after the button-primitive fix (commit e811c50) caught
the last big SSOT gap: the confirm/destructive family. /goals showed the
page-level "New Goal" CTA at 112×34 — the primary call-to-action of the
view, sub-spec on every iPhone. Same primitive powers ~20 sites:

  • ui-btn-confirm    — page CTAs ("New Goal"), modal-form submits,
                        ProjectInlineEditors save, JobDetail confirm
  • ui-btn-confirm-sm — every Add row across today (commitments,
                        habits, events), ProjectGoalsTab, AddEventForm,
                        ProjectPromptsTab, ProjectsSettings
  • ui-btn-danger     — destructive confirms (mirrors ui-btn-confirm
                        for consistency)

All three were 34px tall on mobile, under the WCAG 2.5.5 / iOS HIG 44px
floor. Added `min-h-11 sm:min-h-0` to each — same trick already proven
across ui-btn-primary/-secondary/-ghost, ui-btn-add, ui-chip-toggle,
ui-link-subtle, ui-btn-ready-primary.

Intentionally NOT lifted: ui-btn-confirm-icon (icon-only sibling).
Adding min-w-11 there would push adjacent inputs in inline-edit rows
(HabitRow, GoalCard, AddHabitForm, ProjectInlineEditors). Needs separate
layout analysis to decide between width-extend vs row-min-height; tracked
in session next.

Verified live at 390×844:
  • /goals: "New Goal" 34 → 44; stillSmall: []
  • /events: stillSmall: []
  • /money: stillSmall: []
Verified desktop preservation at 1280×800: "New Goal" still 34px
(sm:min-h-0 collapses correctly).

tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 05:35:48 +02:00
g-butandClaude Opus 4.7 e811c50f3d fix(mobile): ui-btn-primary/secondary/ghost — 36px → 44px tap target on touch
After the chip-picker fix landed (commit 3e7b889), the remaining sub-44px
elements on /control were the two main page CTAs — "Bootstrap new project →"
at 225×36 and "Register existing project" at 221×38 — both using the
universal `ui-btn-secondary` SSOT class. Same story everywhere else: every
modal footer, settings form save/cancel pair, billing tier card, and
control-panel action that uses `ui-btn-primary` or `ui-btn-secondary` was
36px tall on mobile, under the WCAG 2.5.5 / iOS HIG 44px floor.

These three classes are used in 30+ places across the app — modals,
settings (account/profile/billing/team/projects/location/beacon/agent-token),
bootstrap-modal-steps, control-panel-helpers, project-profile-helpers,
PrivatePinGate. One change to globals.css, every secondary/primary/ghost
button gets a real mobile tap target.

Added `min-h-11 sm:min-h-0` to all three sibling button primitives. Same
trick already proven on ui-btn-add, ui-chip-toggle, ui-link-subtle,
ui-btn-ready-primary.

Verified live:
  • /control at 390×844: "Bootstrap new project →" 36 → 44; "Register
    existing project" 38 → 44; sub-44px count 3 → 1 (remaining is the
    icon-only "New" header button, intentional 14×44 on mobile).
  • /people at 390×844: zero sub-44px (Unlock was 36 → 44).
  • /control at 1280×800: secondary buttons stay at 38px, chips stay at
    26/34 — desktop look unchanged thanks to sm:min-h-0.

tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 05:24:46 +02:00
g-butandClaude Opus 4.7 3e7b889e10 fix(mobile): /control chip pickers were 26–34px tap targets — extend ui-chip-toggle SSOT
Cross-route iPhone-width sweep landed on /control as the worst offender:
9 sub-44px interactive elements, including the per-project LLM model
picker (sonnet/haiku/opus) at 26px tall and the adapter picker
(Claude/Codex/Gemini) at 34px. These are the two most critical controls
on the page — switching agent or model — and they were both physically
hard to hit on a phone.

Two SSOT problems to fix:

1. The adapter chips use the existing `ui-chip-toggle` /
   `ui-chip-toggle-active` SSOT, but those classes didn't enforce a
   mobile tap target. Added `inline-flex items-center min-h-11
   sm:min-h-0` to both — fixes adapter chips on /control plus the
   PeopleGrid filter chips on /people in one stroke.

2. The model chips were a separate bare pattern (`rounded-full border
   px-2.5 py-1 text-xs ...`) duplicated across control-panel-helpers
   and control-panel-modals — a smaller compact variant that never
   made it into the SSOT. Created `ui-chip-toggle-compact` /
   `ui-chip-toggle-compact-active` with the same mobile-tap-target
   trick, migrated both call sites, dropped the now-unused `cn` imports.

Verified live at 390×844: sonnet/haiku/opus and Claude/Codex/Gemini all
26/34 → 44px tap height; /control sub-44px count fell from 9 to 3
(remaining 3 are layout artifacts / 36px primary buttons not in scope).
tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 05:13:59 +02:00
g-butandClaude Opus 4.7 050526eeb1 fix(mobile): card-header → links and first-run callout had 16-20px tap targets
Continuation of the iPhone-width audit on /today. After the empty-state add
CTAs went 16 → 44px (commit 05315e3), two text-nav links were still under
spec:

  • "Control →" on Recent Agent Work card header — 59×16
  • "Go to Control Panel →" in the first-run callout — 149×20

The first is the ui-link-subtle SSOT, used in six card headers across the
app (RecentRunsCard, EventsDueCard, GoalsDueCard, StuckGoalsCard,
HabitsCard, PersonCard cancel). Extending it with
`inline-flex items-center min-h-11 sm:min-h-0` lifts every card-header →
shortcut to a real tap target on mobile in one stroke while keeping the
desktop one-liner tight — same trick already used by ui-btn-add and
ui-btn-ready-primary. The CardHeader right-slot wrapper is `sm:ml-auto`
so the taller mobile button just lines up below the title; desktop is
unaffected.

The second is a one-off accent CTA in the first-run empty state — added
`min-h-11 sm:min-h-0` inline since it's a unique shape (text-sm,
font-medium, accent-text) that doesn't yet warrant its own class.

Verified live at 390×844 (iPhone 14): zero sub-44px interactive elements
remain on /today. "Control →" 59×16 → 59×44; "Go to Control Panel →"
149×20 → 149×44. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 05:01:44 +02:00
g-butandClaude Opus 4.7 05315e3a88 fix(mobile): empty-state add CTAs were 16px tall — extend ui-btn-add with min-h-11
Live audit at iPhone width caught the next broken-but-tolerated UX trap:
the primary CTA in the habits empty state ("Add first habit"), the
commitments empty state ("Add commitment"), and four sibling spots
(milestones, log activity, new autopilot job, etc.) were 16px tall —
far below the WCAG 2.5.5 / iOS HIG 44px minimum. A new mobile user
landing on /today with zero habits literally had a 16-pixel tap target
to add their first one.

Root cause: six places copy-pasted the same `flex items-center gap-1.5
text-xs text-text-tertiary hover:text-status-positive transition-colors`
string when the codebase already had `ui-btn-add` for this shape. They
diverged on hover color (status-positive green vs accent-text yellow),
which was a real semantic intent: achievement-flavored "create something
good" vs generic "add a thing."

Fix:
  • ui-btn-add now has `min-h-11 sm:min-h-0` — mobile gets a real 44px
    tap target, desktop keeps the tight one-line look since hover is
    reliable there. Same trick as ui-btn-ready-primary.
  • New ui-btn-add-success sibling carries the green hover for habits,
    commitments, milestones, goal activity, and project prompts.
  • Migrated all six bare-pattern sites to the new class.

Verified live at 390×844 (iPhone 14): "Add first habit" and "Add
commitment" went from 16 → 44px tap height. tsc + eslint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 04:50:21 +02:00
g-butandClaude Opus 4.7 4cfed1973c fix(mobile): hover-only buttons invisible on touch — collapse to ui-hover-reveal
Live audit-driven sweep: grepped for the bare `opacity-0 group-hover:opacity-100`
pattern and found five buttons that vanish completely on touch devices
because there's no hover state on mobile. These are real broken-but-tolerated
UX traps — the icon literally cannot be tapped because it's not rendered:

  • QuickCaptureButton recent-captures trash → can't delete a capture from phone
  • HabitRow edit pencil → can't edit a habit row from phone
  • HabitRow remove X → can't remove a habit from phone
  • HabitGoalLinks unlink × → can't unlink a goal-habit pair from phone
  • ProjectInlineEditors description pencil → can't see edit affordance from phone

The codebase already has the right SSOT for this (ui-hover-reveal in
globals.css = `sm:opacity-0 sm:group-hover:opacity-100`), so mobile always
shows the icon and desktop keeps the hover-reveal polish. Swap each broken
spot to either the SSOT class or the sm: prefix where named groups (group/desc)
preclude the class.

Caught by `grep -rn "opacity-0 group-hover" src/components/` — now returns
zero hits.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 04:35:43 +02:00
g-butandClaude Opus 4.7 4f13245d62 fix(today): Recent Agent Work clusters adjacent same-project runs
Live mobile audit (the same one that found the weather bug) surfaced
"Cockpit · 5h ago" rendering five times in a row, then "6h ago", then
"10h ago" — back-to-back orchestration_runs entries on the same project
flooding the card with near-duplicates.

Cluster pass after the query: walk the already finishedAt-desc list,
each run either extends the previous cluster (same projectKey + within
60 min of the latest run's finishedAt) or starts a new one. Render one
row per cluster with a "↻ ×N" badge when N > 1.

Cluster window matches the rough duration of a back-to-back session
burst; anything longer feels like distinct work and deserves its own
row. Latest run's done/next/health drive the visible summary so the
freshest signal stays prominent.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 04:15:08 +02:00
g-butandClaude Opus 4.7 947fc557f7 fix(weather): WeatherCard shows real weather on Vercel via open-meteo HTTP
Caught during a live audit at mobile viewport on cockpitapp.vercel.app:
WeatherCard rendered "Unavailable" indefinitely. Root cause: /api/weather's
GET handler bails to {weather: null} when isRuntimeAvailable() is false
(serverless can't shell out to scripts/weather.sh).

But the upstream weather.sh actually calls is open-meteo — a free public
HTTP API. We can hit it directly from Vercel via fetch. Add a
fetchOpenMeteoWeather() path used only when isRuntimeAvailable is false;
local keeps the richer shell path.

Implementation:
  - WMO_DESCRIPTION map: weather codes 0-99 → human strings matching
    weather.sh's vocabulary so WeatherCard's parseWeather +
    WeatherIcon-by-keyword detection still light up the right icon
    (cloud / rain / snow / fog) regardless of source.
  - Output line format matches weather.sh exactly:
      "Now: <desc>, <temp>°C, wind <w> km/h, humidity <h>%"
      "<date>: <lo>-<hi>°C, <desc>"
  - AbortSignal.timeout(7000) so a stalled upstream doesn't pin the route.
  - 503 with explicit error reason when geocoding fails or open-meteo is
    unreachable, so FetchErrorState shows the actual cause rather than a
    silent "Unavailable" wall.

This finally works on the deployed site for the first time. The user has
been seeing "Weather: Unavailable" on their Today page on every mobile
visit; from this deploy onward they'll see real temperature + condition +
tomorrow's forecast.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 04:01:53 +02:00
g-butandClaude Opus 4.7 9054ce9822 refactor(system): SystemStats useFetch uses REFRESH_CADENCE.system
Single cadence story for the /system surface: the server-card AutoRefresh
and the client-side SystemStats useFetch poll now share REFRESH_CADENCE.system.
One edit retunes both.

Other polling useFetch callers (Calendar 5min, Weather 10min, GitHub 2min)
intentionally stay un-unified — those intervals track the backing API's
data-change rate, not the surface's freshness need. Pulling them into
REFRESH_CADENCE would conflate "page cadence" with "endpoint cadence" —
two different concerns that just happen to be numbers in the same range.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 03:48:32 +02:00
g-butandClaude Opus 4.7 ab4a79479b refactor(refresh): REFRESH_CADENCE SSOT for AutoRefresh intervals
Four pages hardcoded their own intervalMs after bd8e4fa + cb86bca. Past
the rule-of-three threshold (we have 4 instances) so extract:

  src/config/refresh.ts
    REFRESH_CADENCE = {
      system:   30_000,  // operational signals — fresh failures visible fast
      today:    60_000,  // user-driven; data shifts slowly
      memory:   60_000,
      projects: 60_000,
    }

Every page imports the key for its surface. One edit to retune the whole
app instead of four.

Skipping env-var override: YAGNI. Comment in the file documents how to
convert these to `Number(process.env.REFRESH_CADENCE_X ?? "30000")` if a
deployment ever hits a bandwidth ceiling — but we don't write the env
plumbing speculatively.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 03:37:33 +02:00
g-butandClaude Opus 4.7 cb86bcaeb6 feat(refresh): AutoRefresh on /today, /memory, /projects (60s)
Mount the existing <AutoRefresh /> on the three other server-rendered
status surfaces. 60s cadence — longer than /system's 30s because these
pages' data changes more slowly (commitments, projects, memory entities)
and an extra Neon round-trip per minute is cheap.

Deviation from the session next: deliberately SKIPPED /control. Its body
is the ControlPanel client component, which already manages its own
polling via useControlData + cockpit:refresh listener — router.refresh()
would only re-render the static PageLayout wrapper, providing no visible
benefit while paying a Neon round-trip. First principles trump the "mount
on every status surface" pattern: AutoRefresh helps server components,
not client-state owners.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 03:23:03 +02:00
g-butandClaude Opus 4.7 bd8e4fa40d feat(system): 30s AutoRefresh keeps telemetry card live
RecentFailuresCard (510bfc0) only re-renders on PullToRefresh / focus-return
gestures. A failure that lands NOW is invisible to a user staring at /system
without doing one of those.

Tiny client component: <AutoRefresh intervalMs={30_000} /> mounts a
visibility-gated setInterval that fires router.refresh() — re-fetches all
server cards on the page in one call, no per-card plumbing. Visibility
check skips polling on a backgrounded tab so we're not chewing Neon
queries for nobody.

Composable with the existing PullToRefresh + RefreshOnFocus — router.refresh
is idempotent enough that two near-simultaneous triggers batch into one
React work pass. No coordination logic needed.

Mounted on /system right after RecentFailuresCard.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 03:11:21 +02:00
g-butandClaude Opus 4.7 510bfc052a feat(system): Recent telemetry card surfaces debug_logs on /system
I've been writing every failure/heartbeat into debug_logs across five
sources (api/inject, api/orchestration/run, api/control/dispatch,
api/crons/prune-debug-logs, auth) but the user had no UI to see any of
it — would have to SQL the table by hand.

Mount a Suspense-wrapped server-component card at the bottom of /system:
  - Last 10 rows via getRecentDebugLogs
  - Per-row: relative time · source · level icon · truncated message
  - Header right-side counter: "N errors" in red OR "all clear" in muted
  - EmptyState when no telemetry yet
  - LEVEL_TONE map for icon + color (error red, warn amber, info muted)
  - title attribute on message for hover-to-see-full-text on desktop

No client poll — the card re-renders on PullToRefresh / RefreshOnFocus
gestures which we already wired earlier. Pivoted away from the previous
session next: (Edge-middleware → Node forwarder for cookie-401 telemetry)
because the forensics value is marginal — the user-facing failure is
already visible via 9c2525c — and the forwarder adds a real DoS-amplification
surface (bots probing /api/* would spam debug_logs through it). Better
spend: make the telemetry I already have visible.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 03:00:12 +02:00
g-butandClaude Opus 4.7 c80c6cf7b3 feat(telemetry): logDebug on /api/inject route-level 401
Captures the route-level unauthenticated branch (line 28) — fires when a
caller passes middleware (Bearer ck_* token) but fails getSessionUserId
(token revoked, mis-configured, expired session that NextAuth couldn't
parse but the middleware let through). Meta includes UA + referer so a
mobile vs desktop attempt is distinguishable.

Scope honest disclosure: this does NOT catch the most-common 401 case —
the cookie-only "session JWT expired" mobile path. Edge-runtime middleware
in src/auth.config.ts intercepts those at line 54-58 before any route
handler runs, and the Edge runtime can't use postgres-js (Node-only).
Capturing that class server-side requires either:
  - moving telemetry to a Node-runtime catch-all route the middleware
    forwards to before returning 401, or
  - using a Vercel-supported Edge telemetry sink (Log Drains / Analytics).

Verified locally: curl with an invalid `Bearer ck_…` token now lands a
row in debug_logs (source=api/inject, level=warn, message="Unauthenticated
inject attempt — likely session expiry"). Cookie-only probes still get a
401 from middleware and bypass this code, by design.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 02:44:51 +02:00
g-butandClaude Opus 4.7 c5a9faa3a7 fix(control): never-lose-a-prompt now covers all four dispatch paths
9c2525c protected sendCustom + sendText (custom-input path). Three other
paths in useProjectCardActions had the same swallow-the-error pattern,
and one of them was destructive:

  handleSendFromQueue: removed the queue item BEFORE the await. A failed
  onInject (network drop / 401 / 5xx) silently destroyed the queue item.
  Same lost-prompt class as the original incident, just on the per-project
  prompt queue instead of the custom input. Swap to remove-on-success:
  await first, then removeFromQueue(index); on throw the item stays in
  the queue and the inline error banner surfaces.

  sendIntent: two await sites (queued-next-best inject + onRunWithBrain)
  with no catch — failures became unhandled promise rejections logged to
  console while the user saw nothing. Wrap each with try/catch → sendError.

  send: same shape, three await sites. Same wrap.

All four now follow the established pattern: clear sendError on entry,
attempt the dispatch, on catch set sendError so the PromptInput red
banner shows. The four error catches are identical because they share
the same fail mode — keep them inline rather than extract a wrapper
since each path has unique state setup before the await.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 02:26:10 +02:00
g-butandClaude Opus 4.7 8faa4e2e6a ci: GitHub Actions watches Vercel deploy on push to main
Pair to the local scripts/wait-for-vercel.sh (154c354). When a deploy
fails in production (CRON_SECRET whitespace last incident, build break,
runtime config drift), the workflow turns the commit's check red so the
failure is visible in the GitHub UI without anyone having to invoke the
local script.

Mechanism:
  - Triggers on push to main, runs in parallel with the existing
    ci.yml tsc+lint job.
  - Polls https://api.vercel.com/v6/deployments?projectId=… via
    Authorization: Bearer $VERCEL_TOKEN; matches deployment by
    github.sha so it waits past any stale "previous deploy" reading
    in the first ~30s after push.
  - 480s deadline (Vercel typically 60-120s build). Exits 0 on READY,
    1 on ERROR|CANCELED, 2 on timeout.
  - Skips gracefully when VERCEL_TOKEN / VERCEL_PROJECT_ID secrets
    are not configured — never breaks CI for unconfigured repos.

One-time setup (documented in the workflow header):
  Settings → Secrets → add VERCEL_TOKEN, VERCEL_PROJECT_ID, VERCEL_ORG_ID.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 02:14:02 +02:00
g-butandClaude Opus 4.7 154c354e68 feat(deploy): wait-for-vercel.sh — fail-fast on bad deploys
Vercel deploy failures previously sat in Error state silently until
someone ran `vercel ls`. The just-fixed CRON_SECRET-whitespace incident
(02c3c0d) is exactly this class: the build error existed for several
minutes before I noticed.

scripts/wait-for-vercel.sh polls vercel ls --prod for the most-recent
deployment, echoes each status transition, and exits:
  0  on Ready
  1  on Error / Failed / Canceled (prints `vercel inspect <url> --logs` hint)
  2  on timeout (default 420s; tunable via env)
  3  when the vercel CLI isn't installed

Gotcha I hit while writing this: `vercel ls` emits the deploy table to
STDERR, not stdout — `2>/dev/null` silently swallows every row. Use
`2>&1` to merge. Comment in the script flags it so the next person
debugging doesn't waste the same hour.

npm scripts:
  wait:vercel    direct invocation
  ship           git push origin main && wait:vercel

Use:
  npm run ship                   # push and wait
  bash scripts/wait-for-vercel.sh --quiet   # exit code only

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 02:03:04 +02:00
g-butandClaude Opus 4.7 712aa5f285 refactor(cron): extract requireCronAuth helper as SSOT
Vercel build of 02c3c0d failed because the CRON_SECRET I set via
`echo $value | vercel env add` carried a trailing newline that HTTP
header validation rejects. Fixed env-side via `printf %s` (re-added the
secret with no whitespace).

Code-side: extract the gate into src/lib/cron-auth.ts so the next janitor
doesn't have to re-implement the same auth pattern (and so the "use
printf not echo" warning lives next to the code that depends on it).
requireCronAuth(req) returns NextResponse on failure (caller `return`s
it) or null on success — same three-branch behavior:

  - VERCEL=1 + no CRON_SECRET → 503 fail-closed
  - CRON_SECRET set → require matching Bearer, else 401
  - VERCEL unset + no CRON_SECRET → allow (local dev curl path)

Refactor /api/crons/prune-debug-logs to use it. Two LOC replace nine
lines of inline auth.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 01:47:59 +02:00
g-butandClaude Opus 4.7 02c3c0d310 fix(cron): /api/crons/prune-debug-logs fails closed in production
Without this, a Vercel deployment with CRON_SECRET unset would leave the
janitor publicly callable — anyone hitting GET /api/crons/prune-debug-logs
could delete forensics data. The previous version silently allowed the
call when the env var was missing (intended for local dev convenience).

Tighten the gate:
  - if (VERCEL=1 && !CRON_SECRET) → 503 "CRON_SECRET not configured"
  - if (CRON_SECRET set) → require matching Bearer header (existing behavior)
  - if (VERCEL unset && !CRON_SECRET) → allow (local dev curl path)

Also set CRON_SECRET in Vercel production envs via `vercel env add`
(64-char hex, encrypted in the dashboard) so the Vercel-issued cron
request matches and runs, and any unauthenticated probe gets 401.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 01:38:19 +02:00
g-butandClaude Opus 4.7 01abb503d7 feat(telemetry): daily debug_logs janitor via Vercel Cron
debug_logs accumulates without bound — every /api/inject failure, every
Groq fallback, every auth event adds a row. Add a daily Vercel Cron Job
that prunes:

  - level=info | warn rows older than 30 days
  - level=error rows older than 90 days  (postmortem value, longer kept)

Implementation:
  - pruneDebugLogs({nonErrorOlderThanDays, errorOlderThanDays}) helper
    composes the two retention windows in one DELETE via OR + returning(),
    returns the deleted row count.
  - GET /api/crons/prune-debug-logs invokes it. Auth: Bearer ${CRON_SECRET}
    if the env var is set (Vercel Cron sends this), otherwise allow
    (local dev — devs can hit it directly with curl).
  - Janitor logs its own outcome to debug_logs (level=info) so we can see
    in production whether the cron actually fires every day. Errors land
    as level=error rows with the same source string.
  - vercel.json crons[] entry: 0 3 * * * (daily at 03:00 UTC) — within the
    Vercel free-tier daily-cron allowance.

Verified locally: curl /api/crons/prune-debug-logs → {"ok":true,"deleted":0}
(no rows are 30+ days old yet — only 8 auth entries exist).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 01:28:10 +02:00
g-butandClaude Opus 4.7 d7e7ce46f5 feat(telemetry): logDebug on orchestration/run + control/dispatch failures
Extend the debug_logs capture from /api/inject (99fca82) to the other two
primary server entry points where failures previously vanished into
journalctl with no DB forensics trail:

  /api/orchestration/run
    - claude path: inject failed → level=error, meta(adapter, intent, projectKey)
    - codex/gemini path: inject failed → same
    - openclaw path: scheduleOpenClawWorker failed → meta includes runId

  /api/control/dispatch
    - Groq fallback (key invalid / rate-limited / 5xx / timeout) → level=warn
      because dispatch gracefully degrades to queue order, but the cause
      still belongs in forensics.

Same fire-and-forget logDebug pattern — telemetry can never break the
observed operation. Auth 401 + the 503/501 "config issue" paths are
intentionally not logged (noisy + not actionable).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 01:17:57 +02:00
g-butandClaude Opus 4.7 99fca8201d feat(telemetry): debug_logs schema + /api/inject failure capture
Per pattern_vercel_log_fallback (memory): journalctl on Vercel is unreliable
for post-incident forensics. The debug_logs table already existed in Neon
(raw-SQL writes from src/auth.ts) but had no Drizzle model and no typed
helper, so other call sites couldn't ergonomically write to it.

Add the missing layer:

- src/db/schema/debug-logs.ts: Drizzle model that matches the live shape
  exactly — column meta (not context), no user_id (the existing auth
  writes don't use it; adding it would require a destructive schema change).
- src/db/queries/debug-logs.ts: logDebug() fire-and-forget helper that
  swallows insert failures (telemetry can never break the operation it
  observes) and a getRecentDebugLogs reader for a future admin view.
- src/app/api/inject/route.ts: logDebug calls on both failure paths
  (unknown-tab → warn, executeInject !ok → error). Meta includes userId,
  tab, mode, adapter, promptKey, promptLabel, customPromptLen, and
  runtimeAvailable so the next incident has full context without needing
  Vercel logs.

Schema push was blocked by drizzle-kit interactive-only column-conflict
prompts on unrelated existing tables — used CREATE TABLE IF NOT EXISTS via
postgres-js to verify the table shape on Neon, then aligned the Drizzle
model to the existing columns. No destructive migration needed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 01:08:40 +02:00
g-butandClaude Opus 4.7 9c2525ca8b fix(control): never lose a custom prompt — draft persistence + inline error
Incident 2026-05-20: user sent a custom prompt from the mobile site, the
request silently failed (or the global page-top error went unseen because
the user was scrolled to a project card), and the typed text was lost.
Queried pending_commands — zero unclaimed, zero stuck, zero failed in the
last hour, so the request never reached the server. The user thought it
worked.

Root causes (all of them):
  1. sendCustom had no per-card error surface — only ControlPanel set a
     global error at the top of the page, invisible on mobile when
     scrolled.
  2. ControlPanel's onInject catch SWALLOWED the throw so children had no
     way to react.
  3. The custom input wasn't persisted anywhere — a failed send + page
     close meant typed text was gone.
  4. PromptInput rendered no failure state at all.

Defense in depth (all in one commit):
  - src/lib/draft-storage.ts (new): per-tab localStorage SSOT
    (getDraft / setDraft / clearDraft). Survives refresh, tab close, failed
    send. Best-effort with try/catch around every localStorage call.
  - useProjectCardActions: lazy-init custom from getDraft, wrap setCustom
    to write to localStorage on every keystroke, sendCustom/sendText
    catch+expose sendError and only clearDraft on confirmed success.
    Exports sendError + clearSendError.
  - ControlPanel: onInject / onRunWithBrain / onRunCustomPrompt now
    setError(global) AND re-throw so child cards can also display inline.
  - ProjectCard + project-intent-panel: thread sendError + onClearSendError
    through to PromptInput.
  - PromptInput: red inline error banner above the textarea — "Send failed
    / <reason> / Your text is preserved below — fix the issue and tap Send
    again" with a dismiss X. Visible right where the user is looking.

Outcome: a failed send is now impossible to miss AND impossible to lose
the typed text from. Every layer of the failure path has its own guard.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 00:55:52 +02:00
g-butandClaude Opus 4.7 c953acc19f feat(meta): per-essay 1200×630 OG card for /thoughts/[slug]
Each essay now generates its own preview image via Next.js file-convention.
Card layout on the same dark canvas as the root + profile OG cards:

  [crosshair mark] Cockpit · Essay        (top-left brand stamp)

  Title (64px, ≤3 lines clamped)
  Summary (28px, ≤2 lines clamped)

  date · read time · by author     [tag] [tag] [tag]   (bottom row)

Verified live on /thoughts/the-model-agnostic-layer/opengraph-image-1fqrkj:
1200×630 RGBA PNG, ~59KB, all fields render correctly (title fully visible
on three lines, summary on three lines, "2026-05-18 · 14 min read · by Ivy",
"product / strategy / agents" tag pills on the right).

twitter-image.tsx imports the default and re-declares the route-segment
config inline (Next.js still rejects re-exports of those constants).

Note on URL: Next 16 file-convention appends a build-time content hash to
the OG route on this codebase (-1fqrkj suffix), unlike /u/-/opengraph-image
which gets no hash. The meta tag emits the correct hashed URL automatically.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 00:28:30 +02:00
g-butandClaude Opus 4.7 c1914f9d6e feat(meta): article-type OG card on /thoughts/[slug]
Essay route's generateMetadata returned only title + description, so the
root layout's generic Cockpit card was inherited everywhere a link was
shared. Add openGraph (type=article + publishedTime + tags) and twitter
(summary_large_image) blocks so Slack / LinkedIn / Facebook render the
preview as a recognized article with the essay metadata.

Verified rendered HTML on /thoughts/the-model-agnostic-layer:
- og:title = essay title
- og:type = article
- article:published_time, article:tag (× N)
- twitter:card = summary_large_image, twitter:title, twitter:description

Image still falls back to the root /opengraph-image (generic Cockpit card)
until a per-essay image generator exists — out of scope here.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 00:10:05 +02:00
g-butandClaude Opus 4.7 9abddfdcc9 feat(seo): sitemap includes the default user's public profile
getDefaultUser query already returns the single canonical site-owner.
Append /u/<username> to the sitemap (priority 0.9, weekly changefreq)
so the canonical public profile gets crawled and indexed.

Privacy guardrail: other users' /u/[username] URLs stay OUT. A public
sitemap that enumerates every registered account in a multi-tenant
deployment leaks the user list to anyone fetching /sitemap.xml. Only
the explicitly-flagged isDefault=true user is intentional public.

Function is now async (sitemap default export supports promises) since
getDefaultUser is async.

Verified: /sitemap.xml now contains <loc>…/u/cat</loc> alongside the
static + essay entries.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 00:00:56 +02:00
g-butandClaude Opus 4.7 b22c51b693 feat(seo): robots.txt + sitemap.xml for search engines
Both routes were auth-redirected (302 → /sign-in) before this — Googlebot,
Bingbot, etc. saw a redirect instead of policy / URL list.

src/app/robots.ts (file-convention): Allow /, disallow the app shell
(/control, /today, /projects, …) + /api/ + /_next/. Points sitemap at
APP_URL/sitemap.xml and sets host=APP_URL.

src/app/sitemap.ts (file-convention): Static marketing surface +
filesystem-backed essays (listThoughts iterated through changeFrequency
yearly). /u/[username] omitted — per-user, would need a DB scan; can be
added later if profile discoverability becomes a priority.

src/proxy.ts allowlists robots\.txt + sitemap\.xml in the same exclusion
matcher that already covers opengraph-image / twitter-image / icon.svg /
manifest.json — search engines and social crawlers are all the same
class of unauthenticated content fetcher.

Verified: 200 text/plain on /robots.txt, 200 application/xml on /sitemap.xml.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:51:56 +02:00
g-butandClaude Opus 4.7 e0bfe650e2 feat(profile): nav links + Sign in on /u/[username]
Public-profile nav was a lone BrandMark — anonymous visitors had to type
URLs to reach Features / Pricing / Whitepaper / Sign in. Mount the same
PUBLIC_NAV_LINKS the landing + auth pages use, plus a Sign in link, on
the right side of the existing nav.

Desktop-only (md:flex) per the established PublicSurface pattern — mobile
already has the footer CTA + tap-the-brand-to-go-home. Subtle styling
(text-secondary → text-primary on hover) so the links don't compete with
the profile content.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:42:34 +02:00
g-butandClaude Opus 4.7 4ac0f2cb4d feat(profile): branded footer CTA on /u/[username]
Empty-state profiles (team member, zero public projects, no writing) rendered
just an avatar + "No public projects yet" with nothing below — barren for
share-target visitors. Even non-empty profiles ended abruptly with the last
essay or project card.

Add a subtle footer below all sections: APP_NAME · APP_TAGLINE on the first
line, "Build your own command center →" link to /sign-up on the second.
Always visible — costs ~40px of trailing space but every shared profile
now ends with a clear next step for the visitor.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:33:29 +02:00
g-butandClaude Opus 4.7 7e3faa72f5 feat(meta): per-profile OG card on /u/[username]
Personalized 1200×630 card via Next's file-convention so shared profile
links render the person, not the generic Cockpit card. Card layout:
  [avatar/initials 200px circle]  Display Name (84px)
                                  @handle (36px, muted)
                                  N public projects · Cockpit · tagline

Implementation notes:
- getInitials moved from Avatar.tsx ("use client") to lib/initials.ts so
  the server-side OG generator can import it without crossing the
  server/client boundary. Avatar re-exports from the new path so existing
  client callers keep working.
- ImageResponse / Satori requires explicit display:flex on any div with
  multiple children, AND treats adjacent text-node + variable as multiple
  children — switched `@{username}` to `{`@${username}`}` and joined the
  meta-row spans similarly. Caught by satori's runtime error in service
  logs ("Expected <div> to have explicit display: flex").
- twitter-image.tsx imports the default and re-declares the route-segment
  config inline (Next.js rejects re-exports of those constants).
- DB lookup runs on Node runtime (default for app route handlers), not
  edge — postgres-js needs Node.
- 404/not-found path renders a "Profile not found" card so even bad
  handles emit a sane preview instead of a 500.

Verified: curl -L on /u/cat/opengraph-image returns a 1200×630 PNG, RGBA,
~144KB, with the user's avatar + name + handle + project count rendered.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:23:33 +02:00
g-butandClaude Opus 4.7 6fc9eeee2d feat(meta): OpenGraph + Twitter card with branded 1200×630 image
Root layout now emits openGraph + twitter metadata blocks (siteName,
title, description, url, locale, summary_large_image card) so links shared
to Slack / Twitter / LinkedIn / iMessage render an intentional preview
instead of plain text.

The image is generated at /opengraph-image via Next.js's file-convention
ImageResponse — a 1200×630 dark canvas with the crosshair brand mark,
APP_NAME wordmark, and APP_TAGLINE. /twitter-image re-exports it (Next
rejects re-exported route-segment config, so the consts are duplicated
inline). metadataBase points to APP_URL so Next can build absolute URLs.

Proxy matcher allowlisted /opengraph-image, /twitter-image, /icon.svg,
/manifest.json — social crawlers, PWA manifests, and tab icons must serve
without an auth redirect. Verified: all four return 200 image/PNG (or the
correct content-type) on a fresh curl from an unauthenticated client.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 23:01:08 +02:00
g-butandClaude Opus 4.7 34e60ffd50 fix(metadata): /invite uses title.absolute so "Join Cockpit" doesn't double
Root layout's "%s — Cockpit" template was wrapping the invite layout's
"Join Cockpit" into "Join Cockpit — Cockpit". Pass title.absolute to bypass
the template entirely — verified curl <title>Join Cockpit</title>.

Same family of fix as 28b0490, different remediation (absolute vs strip)
because "Join" is the verb and "Cockpit" is the brand — neither should be
the suffix.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 22:44:41 +02:00
g-butandClaude Opus 4.7 28b0490a6f fix(metadata): strip duplicate "— Cockpit" suffix from page titles
Root layout's title template ('%s — Cockpit') was double-suffixing pages
that already embedded "— Cockpit" in their own metadata: PublicProfilePage
("George — Cockpit — Cockpit"), its Not Found variant, and the whitepaper.

Fix at the page level — return just the base text and let the template
append the brand. Verified via curl:
- /u/cat → <title>George — Cockpit</title>
- /whitepaper → <title>Whitepaper — Cockpit</title>

Caught during the browser QA pass on /u/cat.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 22:36:05 +02:00