ProjectCard.tsx was 809 lines (god component per CLAUDE.md >300 rule).
The 8 self-contained presentational helpers — SessionBadge, MaturityBar,
ClosedBanner, ClosingBanner, RunningBanner, ReadyBanner,
LatestOrchestrationPanel, ProfilePanel — are moved to
project-card-helpers.tsx (298 lines). ProjectCard.tsx is now 524 lines
containing only the main interactive component logic.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Next.js 16 renamed middleware.ts to proxy.ts. Having both files caused a
build error. Merged the complete auth logic (public paths, invite bypass,
API pass-through, onboarding redirect) into proxy.ts and deleted the
redundant middleware.ts.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Greeting now shows the logged-in user's name (via getCurrentUserName())
instead of the hardcoded DEFAULT_USER_NAME constant
- getAllProjectStates() replaced with getProjectStatesByUserId(userId) so
the control panel only surfaces project states owned by the current user
(or legacy rows with null userId for backward compat)
- auth.ts Session type uses explicit fields instead of Omit<DefaultSession>
which was collapsing to {} under TypeScript's union distribution
- session.ts: add getCurrentUserName() helper
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- /api/inject: pass userId to upsertProjectState so project-state rows are
scoped to the authenticated user (matches the rest of the multi-user migration)
- control-fast-state: validate JSON shape in readCurrentPrompt() before casting
to CurrentPrompt — malformed /tmp files no longer silently produce undefined fields
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Every DB query now scopes data to the authenticated user via userId param
sourced from getCurrentUserId(). Invited team members no longer see the
owner's data. Affected: people, projects, memory, utils, orchestration-runs,
prompt-history, events, habits, money, alerts, actions, today.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Navigation:
- Add description field to NavItem type (navigation.ts is now SSOT)
- Write real per-item descriptions for all 12 nav items
- Control: "Dispatch agents across projects" (was "Brain switching")
- 9 generic items: specific descriptions (was "Tracked view" x9)
- Sidebar reads item.description instead of hardcoded ternary
- Control page subtitle: "Dispatch AI agents across your projects — pick an intent and fire"
(was "Switch brains, models, and terminal sessions")
Multi-user read path fix:
- today.ts: all 5 functions now accept userId param (was DEFAULT_USER_ID)
- goals.ts: getGoals/getGoalStats now accept userId param
- goals/page.tsx, prompts/page.tsx: call getCurrentUserId()
- CommitmentsCard, GoalsDueCard, SubscriptionsCard, SummaryBar: call getCurrentUserId()
- actions.ts fulfillCommitment: call getCurrentUserId() in server action
CLAUDE.md:
- Add Mission section (2-sentence product definition)
- Add control/ to Architecture component list
- Add /control, /thoughts, /settings to Views table
- Update /control description to match actual fleet command feature
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Invitation system: token-based /invite/[token] registration page, TeamSettings
component in /settings, DB schema + queries, full API (create/list/accept)
- Create & Launch: "New project" modal in ControlPanel, ensureTabExists() in
agent-runtime so zellij tab is created if not open, Play button on idle tiles
- Git sync guard: behindRemote field in GitState (git rev-list HEAD..@{u}),
"↓ N behind" warning badge + git pull button + /api/project/sync route
- Clear context: /api/project/clear-context sends /clear to Claude without
writing prompt state; "Clear context" button in ProjectCard More section,
only shown when currentAdapter === "claude"
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
First-run flow:
- /setup page + /api/setup: creates first user with hashed password
(Node crypto scrypt, no new deps). POST rejects if users already exist.
- Landing page redirects to /setup when DB has no users
- middleware.ts: protects app routes, passes public pages through
Auth:
- passwordHash column added to users schema (drizzle-kit push applied)
- src/lib/password.ts: hashPassword/verifyPassword via Node scrypt
- auth.ts Credentials: env var takes priority, falls back to DB hash
so packaged installs work without LOCAL_AUTH_PASSWORD
Multi-tenancy groundwork:
- Replaced DEFAULT_USER_ID with getCurrentUserId() across all 12 API
route files (people, subscriptions, events, goals, projects, commitments)
Docker:
- Dockerfile: multi-stage Node 22 alpine, standalone output
- docker-compose.yml: postgres + migrate + app services
- .dockerignore, .env.example with documented required vars
- next.config.ts: output: standalone
- package.json: added migrate script (drizzle-kit push)
- tsconfig.json: scope to src/ only, exclude .next generated files
Install: clone → cp .env.example .env.local → docker-compose up
First visit → /setup → create account → sign in → done.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Deep near-black background (#080808) with subtle 72px grid overlay
- Radial center glow adds depth without color
- 80px bold headline at lg, tight -3% tracking
- Reduced text/CTA to essentials — no feature card grid
- Proof line at bottom: "Built on Claude · Runs on your machine"
- Rounded-full CTAs: white primary, ghost outline secondary
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Active projects (agent running, recent ready/closed/closing signal, or current
prompt) show as full ProjectCards. Idle projects compress to a 3-column tile
grid with name, health, git branch, and session.next preview.
- ProjectTile.tsx: new compact tile with spinner for running, health dot,
branch, and session.next truncated to one line
- ControlPanel: isActiveProject() helper (5-min window), expandedTabs state
to promote tiles back to full cards on click, collapsible idle section
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Design system:
- globals.css: add status color tokens (status-positive/warning/negative)
- constants/control.ts: replace hardcoded color classes with semantic tokens
- Components: replace hardcoded colors (emerald-400, amber-400, red-400) with
status-positive/warning/negative tokens throughout
Route structure:
- Move all app pages into (app)/ route group alongside shared layout
- Remove flat src/app/ page files (moved to src/app/(app)/)
Orchestration SSOT:
- contract.ts: convert AdapterId and OrchestrationTaskIntentId from string union
types to const arrays so z.enum() can use them as runtime values
- run/route.ts: remove hardcoded intent/adapter enum lists; import from contract
- run/route.ts: use getCurrentUserId() instead of DEFAULT_USER_ID
Misc:
- control/route.ts: remove unused fs import
- Sessions API: minor cleanup
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Control panel:
- Add SSE endpoint (/api/control/stream) pushing agent state diffs every 2s
- Extract shared fast-state reader to lib/control-fast-state.ts (DRY)
- ControlPanel: reduce polling from 10s to 30s; SSE handles fast path (2s latency)
- ControlPanel: add collapsible 24h activity log (was fetched but never rendered)
- ProjectCard: fix RunningBanner elapsed time bug ("154s" → "2m 34s")
- ProjectCard: add warning color to elapsed timer after 15 min (possible stall)
- ProjectCard: fix ClosingBanner elapsed time bug ("3ms running" → "3m running")
- ProjectCard: remove duplicate Pause icon from auto-continue toggle button
- ProjectCard: show session.tests and session.todos in status tab summary
Navigation:
- Move /control to mobile nav (remove /money from mobile); control is flagship view
DB schema:
- project_states: add user_id FK column + index (was only table missing user isolation)
- prompt_history: add idx_prompt_history_user_id index
- habits.habit_completions: add idx_habit_completions_user_id index
- goals: add composite idx_goals_user_status index on (userId, status)
- getRecentActivity query added to prompt-history queries
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Auth & multi-user:
- GitHub OAuth via next-auth DrizzleAdapter; signIn callback absorbs first
login into is_default=true user so all pre-auth data stays accessible
- getCurrentUserId() helper; onboarding + profile pages
- normalizeUsername() extracted to lib/username.ts (DRY fix)
Design system:
- All public pages (landing, sign-in, onboarding, settings) rebuilt to use
ui-* classes and semantic tokens only — zero raw Tailwind color violations
- ui-input, ui-btn-*, ui-panel, bg-surface-*, text-text-* throughout
Reliability (M1–M7):
- M1: Stale claude-stop-active lock cleanup on stop hook entry
- M2: /api/inject validates tab exists in Zellij before writing /tmp
- M3: Prompt SSOT unified — claude-prompts.json single array format
- M4: DBUS UID hardcode removed (already in dotfiles)
- M5: auth.ts signIn callback + AdapterAccountType cast
- M6: project_states DB table — persists ready/closing/closed/session/prompt
across reboots; stop.sh PATCHes on stop/close; control falls back to DB
when /tmp is empty (24h window); inject writes currentPrompt to DB
- M7: scheduleOpenClawWorker now async; waits for spawn event (2s timeout);
marks run as error in DB if worker fails to start
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add ProjectProfile tab to every project card: 7 dimensions (Engineering,
Product, UX, Marketing, Content, Business, Deploy), each with 3 crafted
prompts that interpolate project context (name, path, mission, stack, url)
- Per-project agent selector: override global brain per card; chosen agent
used for all dimension prompt dispatches and auto-launches agent in tab
if not running (via /api/agent/launch → restartTab)
- Add intent:"custom" to orchestration contract so dimension prompts dispatch
as full free-form text, not a fixed intent enum
- Add prompt_history table (append-only log of every dispatch: adapter,
intent, custom_prompt, dispatched_at) — foundation for reuse and learning
- Log every /api/orchestration/run dispatch to prompt_history regardless of adapter
- Return recentCustomPrompts per project in /api/control response (batch query)
- Show reusable chips below custom input: click to prefill, ×N for repeat use
- Show usage count on dimension prompt buttons in Profile tab
- Add /api/agent/launch route: wraps restartTab + launchAgentInTab
- Extract launchAgentInTab to agent-runtime.ts (shared, no duplication)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Unsorted join caused cache misses whenever project list order changed
between polls (same set, different order = treated as different dirs).
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Was duplicated verbatim in inject/route.ts and orchestration/run/route.ts —
any fix to the shell-escape logic needed double application. Now SSOT.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Runs stuck in "running" beyond 60 min now auto-transition to error state
on every /api/control poll (every ~10s), preventing phantom active states.
Cleanup runs in parallel with the latestRuns query so it adds no latency.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Old message implied codex had no orchestration support. All switchable
agents now dispatch tasks via prompt injection. The real distinction is
session lifecycle signals (stop/ready hooks), which only claude supports.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
agentRunning was scanning /proc only for the configured switchable agent's
process matchers. Switching to codex meant Claude sessions were invisible —
projects showed as idle while Claude was actively running in their tabs.
Fix: union all registered agents' processMatchers before scanning /proc.
A project is agentRunning if any known agent (claude, codex, openclaw…)
has a process in that directory.
Also hardcodes orchestration capability flags to true since the banners
now gate on readyAt signals rather than agent capability.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
readyAt/closedAt/closingAt signals are written by lifecycle hooks (stop.sh)
independently of which agent is set as the switchable default. Gating the
banners on autonomousPromptLoop suppressed them whenever the user switched
to codex — even when Claude sessions had genuinely finished.
Fix: remove the supportsAutonomousLoop gate from isClosed/isClosing/isReady.
The signals are sufficient evidence. agentRunning=false (no matching process
found) plus readyAt set is the correct ready condition regardless of agent.
Also removes the now-stale "This backend does not support autonomous loop"
message — intent buttons dispatch to any agent, so the disclaimer was wrong.
Drops the unused orchestration prop from ProjectCard.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
New /thoughts route renders markdown-based long-form content from
content/thoughts/. Seed content covers the autonomous loop philosophy
and the next-best-step prompt pattern. ThoughtMeta parsed from YAML
frontmatter; reading time auto-calculated from word count.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Replaces the Claude-only prompt loop with a neutral orchestration layer
that dispatches tasks to whichever agent is available. When one brain
runs out of tokens, switching to another requires one tap.
New infrastructure:
- src/lib/orchestration/ — contract, 10 task intents, adapter definitions,
prompt renderer, OpenClaw runner, summary parser
- src/lib/agent-registry.ts — detects claude/codex/openclaw/gemini from
PATH; reads configured model from dotfiles
- src/lib/agent-preferences.ts — persists selected brain to
~/.config/cockpit-agent.json; syncs model back to Claude settings
- src/lib/agent-catalog.ts, agent-runtime.ts, switch-agent.ts — catalog,
zellij tab restart logic, agent switching action
- src/db/schema/orchestration-runs.ts + queries — DB-tracked runs
New API routes:
- /api/control/agent — GET brain config, POST to switch + restart zellij tabs
- /api/orchestration/run — brain-agnostic dispatch: claude/codex → inject
rendered prompt into zellij tab; openclaw → fires detached worker
- /api/orchestration/run/execute — synchronous execute endpoint for worker
Control panel UX:
- Brain section collapsed to a single pill, expanding only when needed
- Intent buttons replace hardcoded "OpenClaw" buttons — Next best, Test & fix,
Quality, Commit, +5 under More; each shows "via {adapter}"
- agentRunning detection uses /proc scan against configured agent matchers
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add paused prop to ReadyBanner — countdown stops when paused=true
- ProjectCard passes paused={customFocused || custom.trim().length > 0}
- Custom input gains onFocus/onBlur to track focus state
- Countdown display shows ⏸ when paused instead of remaining seconds
Prevents the "Claude finished" banner from auto-firing while the user
is composing a custom prompt in the input below.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- lib/api/fetch.ts: getJson<T>(url, options?) — typed GET that throws on !ok
- hooks/use-fetch.ts: use getJson internally (DRY, typed error handling)
- PersonDetail, ProjectDetail, ClaudeSession: replace fetch+ok+json chain
- PeopleGrid, LogConversationButton: replace fetch+json with typed getJson
No logic changes — only the boilerplate layer is removed.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
New src/components/ui/modal-form.tsx owns the shared skeleton that all
four "New X" buttons repeated: green trigger button, Modal wrapper,
header (title + X close), error block, and primary submit button.
Uses <form onSubmit> so Enter in any <input> submits natively — removes
the per-field onKeyDown handlers that were previously copy-pasted.
NewPersonButton / NewProjectButton / NewGoalButton / NewSubscriptionButton
now contain only their unique field state and field JSX. Combined line
count: 507 → 453 (−54 lines), and any future modal button costs ~35 lines
instead of ~100.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Add stateFile.{ready,closing,closed,sentinel,prompt,lock}(tab) helpers
to claude-config.ts as the single TypeScript source for /tmp state file
paths. Update inject and control routes to use them — eliminates raw
string interpolation scattered across two files.
Add a STATE FILE CONTRACT comment block documenting what each sentinel
means and which actor owns reads/writes — the bash dotfiles (stop.sh,
notification.sh) duplicate these names as string literals, so the
comment is the only shared spec.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- New src/lib/claude-config.ts: SSOT for all Claude local-config paths
and file-reading helpers (parseProjectsConf, readProjectsMap,
readPromptMeta, readPrompts, buildPromptWithSession, PromptMeta type)
- control/route.ts + inject/route.ts: import from shared lib; removes
~50 lines of duplicated constants and functions
- route-helpers.ts: add handleDuplicateEntityNameError() helper
- people/route.ts + projects/route.ts: use the shared helper instead
of inline uq_entities_user_name_type string comparison
Also fixes notification.sh: skip auto-inject when close_session is in
flight (sentinel or closing marker present) — prevents a new prompt
firing immediately after a session closes.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Shows all open Zellij tabs as a strip at the top of the control panel
(project-matched tabs brighter, unknown tabs dimmer). Adds a Terminal
icon in each project card header when its tab is currently open.
Wires zellijTabs through the ControlData type to the GET response.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Cache strategy:
- git state + DB profiles: 20s stale-while-revalidate (background refresh)
- Claude CWD detection: 3s TTL, reads /proc directly (no fork at all)
- Session files + tmp files: always fresh (cheap fs reads)
No more pgrep fork() on every request — replaced with direct /proc scan
(readdirSync + readFileSync per PID). Zero fork() calls on warm cache.
Result: cold=2s (first call or after 20s), warm=50–200ms (application-code).
Also: recent commits (last 4) shown per project card in the control panel.
Each row: "hash date: subject" from git log -5, joined with ~.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
API (/api/control):
- ProjectState gains closingAt, currentPrompt, profile fields
- profile pulled from DB entities (fuzzy tab→name match): description,
status, maturity, stack, mission, url + all attrs
- currentPrompt: reads /tmp/claude-current-prompt-<tab> set by inject
- closingAt: set when close_session injected; closedAt: set only after
Claude actually finishes (stop.sh writes it, not inject)
API (/api/inject):
- Writes claude-current-prompt-<tab> on every injection
- For close_session: writes closing file (not closed) — closed deferred to stop.sh
- Reads prompt meta to include icon+label in current prompt tracking
UI (ControlPanel):
- ClosingBanner: amber spinner "Closing session…" while prompt runs
- RunningBanner: indigo pill showing current prompt label + elapsed time
- ProfilePanel: collapsible — description, mission, maturity bar (10-dot),
stack, status, url, customers, architecture, owner
- MaturityBar: visual 10-dot progress indicator
- Status bar: running/waiting counts + total today's commits across all projects
- Sort: closed > ready > running > active (today commits) > idle
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
fork() in the large Next.js process blocks the event loop for ~800ms each.
4 exec() calls × 19 repos = 76 sequential forks = 60s total.
Fix: one bash invocation with background jobs (&/wait) runs all repo git
queries in parallel. 2 total forks (bash + pgrep) instead of 76+.
Also fixes shell-injection bug: --format=%ar|%s was split by sh as a pipe,
making git log silently return null for all projects.
Result: /api/control drops from ~60s to ~2s application-code time.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Add Page Visibility API + useRef in-flight guard to ControlPanel:
- Skips polls while the browser tab is in the background
- Skips a new poll if a request is already in progress
- Re-polls immediately when the tab becomes visible again
Prevents the server backlog that accumulated when the browser kept
sending new requests every 10s while the event loop was blocked.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Replace 76 sequential execSync calls (19 projects × 4 git commands)
with Promise.all — all projects and the pgrep check now run in parallel.
Event loop no longer blocks on each request; response time drops from
~40s to ~2s.
Also: add /control and /api/control to smoke.sh route lists; bump
reachability probe timeout from 5s to 20s for dev-mode compilation.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- GET /api/control: reads claude-projects.conf, session files, git state,
claude process CWDs, ready/closed tmp files → returns ProjectState[]
- POST /api/inject: validates tab, builds prompt with session context,
shells to zellij; clears ready file; writes sentinel+closed when close_session
- /control page: polls every 10s, shows all projects with session state,
prompt buttons, custom input, ready-countdown banner, and close_session
celebration banner (no auto-countdown, shows shipped/next/tests)
- stop.sh: writes claude-ready-<TAB> on exit; writes sentinel+closed files
when close_session is chosen from popup (infrastructure-side, not LLM)
- close_session prompt simplified: infrastructure now handles sentinel
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>