Commit Graph

383 Commits

Author SHA1 Message Date
Lukas May
270a5cb21d feat: Add Docker-based preview deployments for phase review
Preview deployments let reviewers spin up the app at a specific branch
in local Docker containers, accessible through a single Caddy reverse
proxy port. Docker is the source of truth — no database table needed.

New module: src/preview/ with config discovery (.cw-preview.yml →
compose → Dockerfile fallback), compose generation, Docker CLI wrapper,
health checking, and port allocation (9100-9200 range).
2026-02-10 13:24:56 +01:00
Lukas May
783a07bfb7 fix: Show actionable error details for account health check failures
Setup tokens from `claude setup-token` can't query the usage API,
resulting in a useless "Usage API request failed" message. Now shows
the actual HTTP status and guides users to complete OAuth setup.
Also distinguishes warning state (yellow) from error state (red)
in the AccountCard UI.
2026-02-10 13:16:03 +01:00
Lukas May
06f443ebc8 refactor: DB-driven agent output events with single emission point
DB log chunk insertion is now the sole trigger for agent:output events.
Eliminates triple emission (FileTailer, handleStreamEvent, output buffer)
in favor of: FileTailer.onRawContent → DB insert → EventBus emit.

- createLogChunkCallback emits agent:output after successful DB insert
- spawnInternal now wires onRawContent callback (fixes session 1 gap)
- Remove eventBus from FileTailer (no longer touches EventBus)
- Remove eventBus from ProcessManager constructor (dead parameter)
- Remove agent:output emission from handleStreamEvent text_delta
- Remove outputBuffers map and all buffer helpers from manager/handler
- Remove getOutputBuffer from AgentManager interface and implementations
- getAgentOutput tRPC: DB-only, no file fallback
- onAgentOutput subscription: no initial buffer yield, events only
- AgentOutputViewer: accumulates raw JSONL chunks, parses uniformly
2026-02-10 11:47:36 +01:00
Lukas May
771cd71c1e feat: Validate default branch exists in repo when setting project defaultBranch
registerProject and updateProject now verify via remoteBranchExists that the
specified branch actually exists in the cloned repository before saving.
2026-02-10 11:46:00 +01:00
Lukas May
a8d3f52d09 feat: Re-add initiative branch field and add projects settings page
Allow users to specify a custom branch when creating initiatives
(auto-generated if left blank). Add updateProject tRPC procedure
and /settings/projects page with inline-editable defaultBranch.
2026-02-10 11:19:48 +01:00
Lukas May
fc3039a147 fix(dispatch): Filter planning-category tasks from dispatch pipeline and agent context
Planning tasks (research, discuss, plan, detail, refine) have their own
architect flow and should never enter the dispatch pipeline or clutter
agent context. Three changes:

1. Phase auto-queue skips planning-category tasks
2. Safety net in getNextDispatchable() skips planning tasks
3. gatherInitiativeContext() filters to execution tasks only
2026-02-10 11:18:17 +01:00
Lukas May
d18c3c7e44 fix(web): Dismiss button on refine agent ChangeSetBanner now works
The dismiss mutation only invalidated `listAgents` but the hook reads
from `getActiveRefineAgent`, so the banner stayed visible after dismiss.
Added optimistic cache clearing and invalidation for `getActiveRefineAgent`.
2026-02-10 11:03:20 +01:00
Lukas May
57a5843324 fix(web): Update PipelineTab to use renamed PlanSection component 2026-02-10 10:55:59 +01:00
Lukas May
ca548c1eaa feat: Auto-branch initiative system with per-project default branches
Planning tasks (research, discuss, plan, detail, refine) now run on
the project's defaultBranch instead of hardcoded 'main'. Execution
tasks (execute, verify, merge, review) auto-generate an initiative
branch (cw/<slug>) on first dispatch. Branch configuration removed
from initiative creation — it's now fully automatic.

- Add PLANNING_CATEGORIES/EXECUTION_CATEGORIES to branch-naming
- Dispatch manager splits logic by task category
- ProcessManager uses per-project defaultBranch fallback
- Phase dispatch uses project.defaultBranch for ensureBranch base
- Remove mergeTarget from createInitiative input
- Rename updateInitiativeMergeConfig → updateInitiativeConfig
- Add defaultBranch field to registerProject + UI
- Rename mergeTarget → branch across all frontend components
2026-02-10 10:53:35 +01:00
Lukas May
0407f05332 refactor: Rename agent modes breakdown→plan, decompose→detail
Full rename across the codebase for clarity:
- breakdown (initiative→phases) is now "plan"
- decompose (phase→tasks) is now "detail"

Updates schema enums, TypeScript types, events, prompts, output handler,
tRPC procedures, CLI commands, frontend components, tests, and docs.
Also fixes 0022 migration multi-statement issue (adds statement-breakpoint markers).
2026-02-10 10:51:42 +01:00
Lukas May
f9f8b4c185 refactor(agent): Use agent name instead of ID for log directory paths
Aligns agent-logs directory naming with agent-workdirs so both use the
human-readable agent name, making filesystem correlation trivial.
2026-02-10 10:41:47 +01:00
Lukas May
bf898cb86e feat(agent): Enrich breakdown/decompose agent input with full initiative context
Breakdown and decompose agents now receive all existing phases, tasks,
and pages as read-only context so they can plan with awareness of what
already exists instead of operating in a vacuum.
2026-02-10 10:18:55 +01:00
Lukas May
118f6d0d51 fix(task): Filter out decompose container tasks from phase and initiative task lists
Decompose tasks are parent containers whose children inherit the same phaseId,
causing both the container and its children to appear in task listings.
2026-02-10 10:18:47 +01:00
Lukas May
a98c2d0f6b feat(web): Add stop button to agent detail view header
Allows stopping running agents directly from the output viewer
instead of requiring the card dropdown menu.
2026-02-10 10:13:45 +01:00
Lukas May
4d3bd9ca90 fix(agent): Add refresh token validation before token refresh
Check for refresh token availability before attempting credential refresh.
Setup tokens that expire without a refresh token now return a clear error
instead of attempting an invalid refresh operation.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 10:01:35 +01:00
Lukas May
7f8a936c02 chore: ensure working directory state is committed
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 10:00:41 +01:00
Lukas May
4ac03b74ca chore: sync working directory state
Ensure all changes are committed.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:59:25 +01:00
Lukas May
11ddbc1b13 feat(architect): Complete data display components phase decomposition
Architect agent decomposed the "Data Display Components - Tables, Grids,
Nutrition Display" phase into 6 executable tasks for migrating admin app
from MUI to shadcn/ui + TanStack Table.

Tasks created:
1. Setup shadcn/ui infrastructure (foundation)
2. Migrate NutritionDisplay component (48-field responsive grid)
3. Migrate RecipeRankings and RecipeStatus components
4. Replace @mui/x-data-grid with TanStack Table
5. Test and verify all components (human checkpoint)
6. Remove unused MUI dependencies

Output files written to .cw/output/ for orchestration system.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:57:44 +01:00
Lukas May
83cf1390a1 feat(architect): Complete Layout & Navigation phase decomposition
Decomposed 'Layout & Navigation - Sidebar, Header, Responsive Wrapper' phase
into 6 executable tasks for migrating MUI components to shadcn/ui and Radix.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:57:44 +01:00
Lukas May
41c812e4b8 feat(architect): Complete auth pages phase decomposition
Decomposed "Data Display Components - Tables, Grids, Nutrition Display"
phase into 6 executable tasks for migrating MUI components to shadcn/ui:

1. Setup shadcn/ui infrastructure (foundation)
2. Migrate NutritionDisplay component (48-field grid)
3. Migrate RecipeRankings and RecipeStatus components
4. Replace @mui/x-data-grid with TanStack Table
5. Test and verify (checkpoint for human review)
6. Remove MUI dependencies and clean up

Tasks follow logical dependency chain with parallel execution where
possible. Includes comprehensive verification checklist before cleanup.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:54:25 +01:00
Lukas May
37583b7083 test(e2e): Update architect workflow test
Update architect workflow end-to-end test with latest implementation.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:54:18 +01:00
Lukas May
265fcb1149 fix(agent): Add refresh token validation before token refresh
Check for refresh token availability before attempting credential refresh.
Setup tokens that expire without a refresh token now return a clear error
instead of attempting an invalid refresh operation.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:54:00 +01:00
Lukas May
341849d2f5 feat(architect): Complete auth pages phase decomposition
Decomposed "Authentication Pages - Login, Password Reset, Kratos Flows" phase
into 7 executable tasks with clear dependencies and verification checkpoints.

Task breakdown:
1. Research shadcn/radix/tailwind infrastructure and form components
2. Migrate Kratos flow components (14 files) from MUI to shadcn/radix
3. Migrate login page
4. Migrate password reset pages (forgot-password, reset-password)
5. Update error page with Tailwind styling
6. End-to-end auth flow testing (human verification checkpoint)
7. Migrate medical-portal auth flow components

All tasks emphasize preserving Kratos integration logic during UI-only migration.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:53:09 +01:00
Lukas May
0b02f755de docs: Update agent documentation
Updated agent.md documentation.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:52:54 +01:00
Lukas May
9d418a0076 docs(agent): Update agent documentation
Update agent.md with latest implementation details.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:52:46 +01:00
Lukas May
34d780b4d0 docs: Update CLI docs for --token flag in account register
Updated cli-config.md to document the new --token option for
account registration command.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:52:19 +01:00
Lukas May
97998459e5 feat(cli): Add --token option to register-account command
Allow manual account registration using a setup token from `claude setup-token`.
The --token option requires --email and creates/updates account credentials
with the provided token.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:51:23 +01:00
Lukas May
e35927f321 fix(agent): Handle optional OAuth fields in usage.ts credential reader
Updated checkAccountHealth to handle setup tokens with null expiresAt:
- Changed currentExpiresAt type from number to number | null
- Use conditional for tokenExpiresAt ISO string conversion

This completes the OAuth setup token support across all credential
reading and validation functions.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:50:46 +01:00
Lukas May
b021b9690e fix(agent): Handle expired setup tokens without refresh token
Add validation to check for refresh token availability before attempting
token refresh. Setup tokens that expire without a refresh token now
return a clear error message instead of attempting an invalid refresh.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:50:40 +01:00
Lukas May
a59e18710f fix(agent): Handle optional OAuth fields in usage.ts credential reader
Make refreshToken and expiresAt optional in usage credential validation.
Aligns with changes in default-credential-manager.ts.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:50:22 +01:00
Lukas May
11b1378b91 fix(agent): Handle optional OAuth token fields in credential manager
Updated readCredentials and isTokenExpired to support setup tokens:
- Removed refreshToken requirement check
- Use nullish coalescing for refreshToken and expiresAt fields
- Treat tokens without expiresAt as non-expired

Completes OAuth credential handling for setup tokens across all
credential management functions.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:50:19 +01:00
Lukas May
8930d1aa43 fix(agent): Handle optional OAuth token fields in credential manager
Make refreshToken and expiresAt optional in OAuth credential validation.
Setup tokens without expiry are now treated as non-expired.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:49:55 +01:00
Lukas May
008c783c50 fix(agent): Handle null refreshToken/expiresAt in credential manager
Updated DefaultAccountCredentialManager to handle setup tokens:
- Removed refreshToken requirement in validation check
- Use nullish coalescing for refreshToken and expiresAt
- Treat tokens without expiresAt as non-expired (setup tokens)

Completes the setup token support changes.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:49:48 +01:00
Lukas May
c204aab403 fix(agent): Allow null refreshToken and expiresAt for setup tokens
Modified OAuthCredentials interface to support setup tokens that don't
have refresh tokens or expiry times:
- refreshToken: string | null
- expiresAt: number | null

Updated in both src/agent/accounts/usage.ts and
src/agent/credentials/types.ts for consistency.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:49:36 +01:00
Lukas May
342b490fe7 feat: Task decomposition for Tailwind/Radix/shadcn foundation setup
Decomposed "Foundation Setup - Install Dependencies & Configure Tailwind"
phase into 6 executable tasks:

1. Install Tailwind CSS, PostCSS & Autoprefixer
2. Map MUI theme to Tailwind design tokens
3. Setup CSS variables for dynamic theming
4. Install Radix UI primitives
5. Initialize shadcn/ui and setup component directory
6. Move MUI to devDependencies and verify setup

Tasks follow logical dependency chain with final human verification
checkpoint before proceeding with component migration.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-10 09:48:51 +01:00
Lukas May
da4152264c feat(web): Pipeline visualization, phase content editing, and review tab
Pipeline view groups phases by dependency depth with DAG visualization.
Phase detail panel with Tiptap rich content editor and auto-save.
Code review tab with diff viewer and comment threads (dummy data).
Centralized live updates hook replaces scattered subscription boilerplate.
Extract agent output parsing into shared utility. Inbox detail panel,
account cards, and agent action components.
2026-02-09 22:33:40 +01:00
Lukas May
47c3162581 feat(shared): Add topological sort and pipeline column grouping for phases
Kahn's algorithm for topological phase sorting by dependency edges with
createdAt tiebreaker. groupPhasesByDependencyLevel computes pipeline
visualization columns. Handles cycles gracefully.
2026-02-09 22:33:34 +01:00
Lukas May
fab7706f5c feat: Phase schema refactor, agent lifecycle module, and log chunks
Phase model changes:
- Drop `number` column (ordering now by createdAt + dependency DAG)
- Replace `description` (plain text) with `content` (Tiptap JSON)
- Add `approved` status as dispatch gate
- Add phase dependency management (list, remove, dependents)
- Approval gate in PhaseDispatchManager.queuePhase()

Agent log chunks:
- New `agent_log_chunks` table for DB-first output persistence
- LogChunkRepository port + DrizzleLogChunkRepository adapter
- FileTailer onRawContent callback streams chunks to DB
- getAgentOutput reads from DB first, falls back to file

Agent lifecycle module (src/agent/lifecycle/):
- SignalManager: atomic signal.json read/write/wait operations
- RetryPolicy: exponential backoff with error-specific strategies
- ErrorAnalyzer: pattern-based error classification
- CleanupStrategy: debug archival vs production cleanup
- AgentLifecycleController: orchestrates retry/recovery flow
- Missing signal recovery with instruction injection

Completion detection fixes:
- Read signal.json file instead of parsing stdout as JSON
- Cancellable pollForCompletion with { cancel } handle
- Centralized state cleanup via cleanupAgentState()
- Credential handler consolidation (prepareProcessEnv)

Prompts refactor:
- Split monolithic prompts.ts into per-mode modules
- Add workspace layout section to agent prompts
- Fix markdown-to-tiptap double-serialization

Server/tRPC:
- Subscription heartbeat (30s) and bounded queue (1000 max)
- Phase CRUD: approvePhase, deletePhase, dependency queries
- Page: findByIds, getPageUpdatedAtMap
- Wire new repositories through container and context
2026-02-09 22:33:28 +01:00
Lukas May
43e2c8b0ba fix(agent): Eliminate race condition in completion handling
PROBLEM:
- Agents completing with questions were incorrectly marked as "crashed"
- Race condition: polling handler AND crash handler both called handleCompletion()
- Caused database corruption and lost pending questions

SOLUTION:
- Add completion mutex in OutputHandler to prevent concurrent processing
- Remove duplicate completion call from crash handler
- Only one handler executes completion logic per agent

TESTING:
- Added mutex-completion.test.ts with 4 test cases
- Verified mutex prevents concurrent access
- Verified lock cleanup on exceptions
- Verified different agents can process concurrently

FIXES: residential-cuckoo and 12+ other agents stuck in crashed state
2026-02-08 15:51:32 +01:00
Lukas May
6f5fd3a0af fix(agent): Implement incremental JSONL parsing to eliminate race conditions
Replaces file completion detection with a superior approach that reads only
complete JSONL lines and tracks file position. This eliminates race conditions
without any delays or polling.

Key improvements:
- Read up to last complete line, avoiding partial lines during writes
- Track file position per agent for incremental reading
- Process only valid, complete JSON lines
- Clean up position tracking on completion/crash
- No hardcoded delays or polling required

This approach is more robust, responsive, and elegant than timing-based solutions.
The race condition where agents were marked as crashed is now completely resolved.
2026-02-08 14:10:02 +01:00
Lukas May
604da7cd0d fix(agent): Replace hardcoded 500ms delay with robust file completion detection
Fixes race condition where agents were incorrectly marked as crashed when
output files took longer than 500ms to complete writing.

Changes:
- Replace hardcoded 500ms delay with polling-based file completion detection
- Add signal file validation to ensure JSON is complete before processing
- Make status updates atomic to prevent race conditions
- Update cleanup manager to pass outputFilePath for proper timing

This resolves the issue where successful agents like "abundant-wolverine"
were marked as crashed despite producing valid output.
2026-02-08 14:03:47 +01:00
Lukas May
2877484012 Add userDismissedAt field to agents schema 2026-02-07 00:33:12 +01:00
Lukas May
111ed0962f docs(21-06): complete integration smoke test plan
Tasks completed: 2/2
- Run full build verification (TypeScript, Vite, tests)
- Full integration smoke test (human-verified, approved)

SUMMARY: .planning/phases/21-polish-integration/21-06-SUMMARY.md
2026-02-05 09:16:31 +01:00
Lukas May
51c26d6d19 docs(21-05): create summary and update state for code splitting & performance
Add 21-05-SUMMARY.md documenting route-based code splitting results
(582 KB -> 454 KB main chunk + route-level chunks) and PlanTasksFetcher
useEffect fix. Update STATE.md to plan 5/6 with new decisions.
2026-02-05 09:06:13 +01:00
Lukas May
c1744b306c docs(21-04): complete subscription error handling plan
Tasks completed: 2/2
- Add subscription error handling with toast feedback on all pages
- Verify SpawnArchitectDropdown error toast coverage (no-op)

SUMMARY: .planning/phases/21-polish-integration/21-04-SUMMARY.md
2026-02-05 09:05:49 +01:00
Lukas May
c66d7ecfb2 fix(21-05): move PlanTasksFetcher onTasks callback to useEffect
Replace the setState-during-render pattern in PlanTasksFetcher with a
useEffect hook. The onTasks callback was being called directly in the
render body when tasksQuery.isSuccess was true, which could cause
infinite re-render loops when the parent state update triggered a
re-render. Now data flows through useEffect with proper dependencies.
2026-02-05 09:05:07 +01:00
Lukas May
1530d7ab15 feat(21-05): enable route-based code splitting via TanStack Router autoCodeSplitting
Enable autoCodeSplitting in TanStackRouterVite plugin to split the monolithic
582 KB bundle into route-level chunks. Main vendor chunk drops to 454 KB with
initiative detail (~13 KB), inbox (~13 KB), and dashboard (~65 KB) as separate
lazy-loaded chunks. Eliminates the Vite 500 KB chunk size warning.
2026-02-05 09:04:25 +01:00
Lukas May
4ae85da3f6 feat(21-04): add subscription error handling with toast feedback on all pages
- Replace silent onError: () => {} with sticky toast notification
- Toast uses fixed ID 'sub-error' to prevent duplicate notifications
- duration: Infinity keeps toast visible until dismissed
- Applied to initiatives/index.tsx, initiatives/$id.tsx, inbox.tsx
2026-02-05 09:04:17 +01:00
Lukas May
3d492d86a1 docs(21-01): create summary and update state for error boundary + toasts 2026-02-05 09:02:31 +01:00
Lukas May
c95ef6e98c docs(21-02): create summary and update state for skeleton loading states 2026-02-05 09:02:02 +01:00