Commit Graph

166 Commits

Author SHA1 Message Date
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
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
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
e5d8dbb583 feat(20): add SSE streaming support and subscription procedures
Fix tRPC HTTP adapter to stream ReadableStream responses instead of
buffering (required for SSE). Create subscriptions module that bridges
EventBus domain events into tRPC async generator subscriptions using a
queue-based pattern. Add three subscription procedures: onEvent (all
events), onAgentUpdate (agent lifecycle), onTaskUpdate (task/phase).
2026-02-04 22:16:14 +01:00
Lukas May
9d7002d2bd fix(19): wire AgentManager into server tRPC context
AgentManager was never instantiated or passed to the CoordinationServer,
causing all agent-related tRPC procedures to throw "Agent manager not
available". Creates DrizzleAgentRepository, SimpleGitWorktreeManager,
and ClaudeAgentManager in startServer() and passes agentManager into
the server context deps.
2026-02-04 22:03:09 +01:00
Lukas May
049810ffae fix(19): gracefully handle missing agentManager in read-only agent procedures
listWaitingAgents, listAgents, and getAgentQuestions now return empty
results instead of throwing when agentManager is not wired into the
tRPC context. Mutation procedures (spawn, stop, resume) still throw.
2026-02-04 22:00:34 +01:00
Lukas May
004140ea83 feat(19-01): add getAgentQuestions and listWaitingAgents tRPC procedures
- getAgentQuestions returns structured PendingQuestions from AgentManager
- listWaitingAgents filters agents to waiting_for_input status
- Updated JSDoc procedure list with both new procedures
2026-02-04 21:51:25 +01:00
Lukas May
cbf0ed28cb fix: wire database and repositories into server startup for tRPC context
The server never created a database or instantiated repositories, so all
tRPC procedures requiring initiativeRepository (and other repos) threw
"Initiative repository not available" on every request.

- Create ensureSchema() for shared database table initialization
- Extend TrpcAdapterOptions to accept all repository/manager dependencies
- Add ServerContextDeps to CoordinationServer for dependency injection
- Wire database, schema, and repositories in CLI startServer()
- Refactor test-helpers to use shared ensureSchema()
2026-02-04 21:18:30 +01:00
Lukas May
93f2b0f5ee fix(16-05): wire eventBus into CLI server startup
startServer() was creating CoordinationServer without an EventBus,
causing all tRPC requests to fail with "Server not initialized or
missing eventBus". Create and pass EventBus through to both
ProcessManager and CoordinationServer.
2026-02-04 20:48:37 +01:00
Lukas May
0d5645f9c8 feat(16-03): wire tRPC React Query client with providers
Create tRPC client with httpBatchLink targeting /trpc (Vite proxy).
Wrap app in trpc.Provider and QueryClientProvider with sensible
defaults. Add health check query to App.tsx for connection
verification. Add vite-env.d.ts for CSS module types. Remove
unused Plan import from backend router.
2026-02-04 18:07:15 +01:00
Lukas May
1aac486f48 test(14-07): add DefaultPhaseDispatchManager tests
- Add queuePhase tests (add to queue, emit event, include deps)
- Add getNextDispatchablePhase tests (empty, no deps first, skip incomplete, oldest)
- Add dispatchNextPhase tests (update status, emit event, remove from queue)
- Add completePhase tests (update status, remove from queue, emit event)
- Add blockPhase tests (update status, add to blocked, emit event)
- Add dependency scenario test (diamond dependency pattern)
2026-02-02 13:48:35 +01:00
Lukas May
03fefd896a test(14-08): add phase dispatch E2E tests
- Test independent phases dispatch in parallel
- Test dependent phase waits for prerequisite
- Test diamond dependency pattern (A -> B,C -> D)
- Test blocked phase prevents dispatch
- Test blocked phase propagates down dependency chain
2026-02-02 13:48:28 +01:00
Lukas May
38ee2d17c4 feat(14-08): add phaseDispatchManager to TestHarness
- Import PhaseDispatchManager type and DefaultPhaseDispatchManager
- Add phaseDispatchManager property to TestHarness interface
- Wire DefaultPhaseDispatchManager with phaseRepository and eventBus
2026-02-02 13:47:09 +01:00
Lukas May
26778c60f5 test(14-07): add PhaseRepository dependency tests
- Add createDependency tests (create, FK constraint, multiple deps)
- Add getDependencies tests (empty, with deps, direct only)
- Add getDependents tests (empty, with dependents, direct only)
- Add phase_dependencies table to test-helpers.ts
2026-02-02 13:46:53 +01:00
Lukas May
8ad262d05e feat(cli): add phase dependency and dispatch commands
Add phase command group with dependency management and dispatch operations:
- cw phase add-dependency: Create dependency between phases
- cw phase dependencies: List dependencies for a phase
- cw phase queue: Queue phase for execution
- cw phase dispatch: Dispatch next available phase
- cw phase queue-status: Show queued, ready, and blocked phases
2026-02-02 13:43:52 +01:00
Lukas May
5e6d507eb8 feat(14-05): add phase dependency and dispatch procedures
- Import PhaseDispatchManager type from dispatch module
- Add requirePhaseDispatchManager helper function
- Add createPhaseDependency: creates dependency between two phases
- Add getPhaseDependencies: returns phase IDs that a phase depends on
- Add queuePhase: queues phase for dispatch
- Add dispatchNextPhase: dispatches next available phase
- Add getPhaseQueueState: returns phase queue state

All procedures follow existing naming conventions and error handling patterns.
2026-02-02 13:40:51 +01:00
Lukas May
053168f6cf feat(14-04): export DefaultPhaseDispatchManager from dispatch module
- Add export for phase dispatch adapter
- Consistent with DefaultDispatchManager export pattern
2026-02-02 13:40:33 +01:00
Lukas May
1ba95871f5 feat(14-04): implement DefaultPhaseDispatchManager adapter
- In-memory queue with Map<string, QueuedPhase>
- Dependency checking via phaseRepository.getDependencies()
- queuePhase: fetch phase, get dependencies, emit PhaseQueuedEvent
- getNextDispatchablePhase: filter queue, sort by queuedAt
- dispatchNextPhase: update status to in_progress, emit PhaseStartedEvent
- completePhase: update status to completed, emit PhaseCompletedEvent
- blockPhase: update status to blocked, emit PhaseBlockedEvent
- getPhaseQueueState: return queued, ready, blocked arrays
2026-02-02 13:40:17 +01:00
Lukas May
28622cbd04 feat(14-05): add PhaseDispatchManager to tRPC context
- Import PhaseDispatchManager type from dispatch module
- Add optional phaseDispatchManager to TRPCContext interface
- Add phaseDispatchManager to CreateContextOptions
- Wire phaseDispatchManager through createContext function

Includes blocking fix: added 'blocked' status to phases schema enum
2026-02-02 13:39:47 +01:00
Lukas May
a890df75d5 feat(14-03): export phase dispatch types from dispatch module
- Export QueuedPhase interface
- Export PhaseDispatchResult interface
- Export PhaseDispatchManager port interface
2026-02-02 13:36:25 +01:00
Lukas May
22cd82da40 feat(14-03): define PhaseDispatchManager port interface
- Add QueuedPhase interface (phaseId, initiativeId, queuedAt, dependsOn)
- Add PhaseDispatchResult interface (success, phaseId, reason)
- Add PhaseDispatchManager interface with queue/dispatch operations
- Methods mirror DispatchManager for consistency
2026-02-02 13:36:12 +01:00
Lukas May
e8ee7f39d7 feat(14-02): export phase events from events module
- PhaseQueuedEvent
- PhaseStartedEvent
- PhaseCompletedEvent
- PhaseBlockedEvent
2026-02-02 13:33:32 +01:00
Lukas May
8e68a6e89e feat(14-01): add dependency methods to PhaseRepository
- Add createDependency(phaseId, dependsOnPhaseId) to interface and adapter
- Add getDependencies(phaseId) returning IDs of phases this phase depends on
- Add getDependents(phaseId) returning IDs of phases that depend on this phase
- Import phaseDependencies table in DrizzlePhaseRepository
- Follow exact pattern from DrizzleTaskRepository.createDependency
2026-02-02 13:33:16 +01:00
Lukas May
cd02439ca9 feat(14-02): add phase domain events
- PhaseQueuedEvent for tracking phases awaiting execution
- PhaseStartedEvent for phase execution start
- PhaseCompletedEvent for phase completion with success flag
- PhaseBlockedEvent for blocked phases with reason
2026-02-02 13:32:24 +01:00
Lukas May
a55d08fffe feat(14-01): add phase_dependencies table to schema
- Add phase_dependencies table mirroring task_dependencies pattern
- Add phaseId and dependsOnPhaseId FK columns with cascade delete
- Add phasesRelations with dependsOn and dependents many relations
- Add phaseDependenciesRelations with phase and dependsOnPhase one relations
- Export PhaseDependency and NewPhaseDependency types
2026-02-02 13:32:19 +01:00
Lukas May
accbaca49d docs(13-01): document Claude CLI structured_output findings
- Add proper test timeouts (120s for real API calls)
- Document key finding: result field is empty, structured_output has data
- Add validation cost estimates (~$0.025 per simple call)
- Confirm MockAgentManager accurately simulates real CLI behavior
2026-02-02 10:40:05 +01:00
Lukas May
5605547aea fix(13-01): parse structured_output from Claude CLI response
- Add structured_output field to ClaudeCliResult interface
- Read from structured_output when present (--json-schema response)
- Fall back to parsing result for backwards compatibility
2026-02-02 10:38:10 +01:00
Lukas May
3c98dbe541 test(13-01): create real Claude CLI integration tests
- Add test file for validating JSON schemas with real Claude CLI
- Tests are skipped by default (REAL_CLAUDE_TESTS=1 to enable)
- Covers execute, discuss, breakdown, and decompose modes
- Helper function callClaudeCli() handles CLI invocation
2026-02-02 10:37:40 +01:00
Lukas May
9b370a2617 test(12-08): add E2E tests for decompose workflow
- Add tests for spawn decompose agent with completion
- Add tests for Q&A flow with questions and resume
- Add tests for multiple questions handling
- Add tests for task persistence from decomposition
- Add tests for all task types (auto, checkpoint variants)
- Add tests for task dependencies
- Add full workflow test: initiative -> phase -> plan -> decompose -> tasks
2026-02-01 11:56:55 +01:00
Lukas May
4263c0884e feat(12-08): add TestHarness decompose mode helpers
- Add setArchitectDecomposeComplete and setArchitectDecomposeQuestions helpers
- Add planRepository to harness for plan operations
- Add createPlan and getTasksForPlan convenience methods
- Import TaskBreakdown and Plan types
2026-02-01 11:55:28 +01:00
Lukas May
a61530359a test(12-07): add PlanRepository getNextNumber tests
Add tests for getNextNumber method:
- Returns 1 for phase with no plans
- Returns max + 1 for phase with existing plans
- Not affected by plans in other phases
2026-02-01 11:54:43 +01:00
Lukas May
a79b15376e test(12-07): add MockAgentManager decompose mode tests
Add tests for decompose mode scenarios:
- Spawn agent in decompose mode
- Complete with tasks on decompose_complete
- Pause on questions in decompose mode
- Emit stopped event with decompose_complete reason
- Set result message with task count
2026-02-01 11:54:20 +01:00
Lukas May
6a2b835fdf feat(12-06): add plan CLI commands and architect decompose command
Add CLI commands for plan management:
- cw plan list --phase <id>: List plans in a phase
- cw plan create --phase <id> --name <name>: Create a plan
- cw plan get <id>: Get plan details
- cw plan tasks <id>: List tasks in a plan

Add architect decompose command:
- cw architect decompose <planId>: Spawn agent to decompose plan into tasks
2026-02-01 11:51:54 +01:00