50 Commits

Author SHA1 Message Date
Lukas May
7e6921f01e feat: enrich listWaitingAgents with task/phase/initiative context via DB joins
Replaces the in-memory filter (agentManager.list() + filter) with a direct
repository query that LEFT JOINs tasks, phases, and initiatives to return
taskName, phaseName, initiativeName, and taskDescription alongside agent fields.

- Adds AgentWithContext interface and findWaitingWithContext() to AgentRepository port
- Implements findWaitingWithContext() in DrizzleAgentRepository using getTableColumns
- Wires agentRepository into TRPCContext, CreateContextOptions, and TrpcAdapterOptions
- Adds requireAgentRepository() helper following existing pattern
- Updates listWaitingAgents to use repository query instead of agentManager
- Adds 5 unit tests for findWaitingWithContext() covering all FK join edge cases
- Updates existing AgentRepository mocks to satisfy updated interface

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-06 23:29:49 +01:00
Lukas May
1416e6bf62 docs: update server-api.md to include qualityReview in updateInitiativeConfig
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-06 21:54:17 +01:00
Lukas May
ba6ebe2594 Merge branch 'cw/review-tab-performance' into cw-merge-1772826318787 2026-03-06 20:45:19 +01:00
Lukas May
f63b1c5eec Merge branch 'cw/radar' into cw-merge-1772825408137 2026-03-06 20:30:08 +01:00
Lukas May
a50ee01626 test: Add DiffCache unit tests and getPhaseReviewDiff cache integration tests
Creates diff-cache.ts module with generic DiffCache<T> class (TTL, prefix
invalidation, env-var configuration) and exports phaseMetaCache / fileDiffCache
singletons. Wires cache into getPhaseReviewDiff via getHeadCommitHash on
BranchManager. Adds 6 unit tests for DiffCache and 5 integration tests
verifying cache hit/miss behaviour, prefix invalidation, and NOT_FOUND guard.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-06 20:06:28 +01:00
Lukas May
4890721a92 feat: split getPhaseReviewDiff into metadata + add getFileDiff procedure
Rewrites getPhaseReviewDiff to return file-level metadata (path, status,
additions, deletions) instead of a raw diff string, eliminating 10MB+
payloads for large repos. Adds getFileDiff for on-demand per-file hunk
content with binary detection via numstat. Multi-project initiatives
prefix file paths with the project name to avoid collisions.

Adds integration tests that use real local git repos + in-memory SQLite
to verify both procedures end-to-end (binary files, deleted files,
spaces in paths, error cases).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-06 19:45:57 +01:00
Lukas May
5598e1c10f feat: implement Radar backend tRPC procedures with repository extensions
Add five new tRPC query procedures powering the Radar page's per-agent
behavioral metrics (questions asked, subagent spawns, compaction events,
inter-agent messages) plus the batch repository methods they require.

Repository changes:
- LogChunkRepository: add findByAgentIds() for batch fetching without N+1
- ConversationRepository: add countByFromAgentIds() and findByFromAgentId()
- Drizzle adapters: implement all three new methods using inArray()
- InMemoryConversationRepository (integration test): implement new methods

tRPC procedures added:
- agent.listForRadar: filtered agent list with per-agent metrics computed
  from log chunks (questionsCount, subagentsCount, compactionsCount) and
  conversation counts (messagesCount); supports timeRange/status/mode/initiative filters
- agent.getCompactionEvents: compact system init chunks for one agent (cap 200)
- agent.getSubagentSpawns: Agent tool_use entries with prompt preview (cap 200)
- agent.getQuestionsAsked: AskUserQuestion tool calls with questions array (cap 200)
- conversation.getByFromAgent: conversations by fromAgentId with toAgentName resolved

All 13 new unit tests pass; existing test suite unaffected.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-06 16:40:18 +01:00
Lukas May
1e16ad82e8 fix: Show conflict resolution agents in HQ dashboard
getHeadquartersDashboard had no section for active conflict agents,
so initiatives with a running conflict-* agent disappeared from all
HQ sections. Add resolvingConflicts array to surface them.
2026-03-06 16:39:48 +01:00
Lukas May
89c98d38cc feat: Add getHeadquartersDashboard tRPC procedure for HQ action items
Aggregates all user-blocking action items into a single composite query:
- waitingForInput: agents paused on questions (oldest first)
- pendingReviewInitiatives: initiatives awaiting content review
- pendingReviewPhases: phases awaiting diff review
- planningInitiatives: active initiatives with all phases pending and no running agents
- blockedPhases: phases in blocked state with optional last-message snippet

Wired into appRouter and covered by 10 unit tests using in-memory Drizzle DB
and an inline MockAgentManager (no real processes required).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-06 15:35:54 +01:00
Lukas May
d867a5f397 Merge branch 'main' into cw/account-ui-conflict-1772803526476
# Conflicts:
#	apps/server/trpc/router.test.ts
#	docs/server-api.md
2026-03-06 14:27:38 +01:00
Lukas May
6f38ae21ed Merge branch 'main' into cw/agent-details-conflict-1772802863659
# Conflicts:
#	docs/server-api.md
2026-03-06 14:15:30 +01:00
Lukas May
1629285778 Merge branch 'refs/heads/main' into cw/agent-details-conflict-1772799979862
# Conflicts:
#	apps/server/drizzle/meta/_journal.json
2026-03-06 13:34:28 +01:00
Lukas May
d52317ac5d feat: Add timestamps to agent logs and fix horizontal scroll
- getAgentOutput now returns timestamped chunks ({ content, createdAt }[])
  instead of a flat string, preserving DB chunk timestamps
- parseAgentOutput accepts TimestampedChunk[] and propagates timestamps
  to each ParsedMessage
- AgentOutputViewer displays HH:MM:SS timestamps on text, tool_call,
  system, and session_end messages
- Live subscription chunks get client-side Date.now() timestamps
- Fix horizontal scroll: overflow-x-hidden + break-words on content areas
- AgentLogsTab polls getTaskAgent every 5s until an agent is found,
  then stops polling for live subscription to take over
- Fix slide-over layout: details tab scrolls independently, logs tab
  fills remaining flex space for proper AgentOutputViewer sizing
2026-03-06 13:18:42 +01:00
Lukas May
b2f4004191 feat: Persist agent prompt in DB so getAgentPrompt survives log cleanup
The `getAgentPrompt` tRPC procedure previously read exclusively from
`.cw/agent-logs/<name>/PROMPT.md`. Once the cleanup-manager removes
that directory, the prompt is gone forever.

Adds a `prompt` text column to the `agents` table and writes the fully
assembled prompt (including workspace layout, inter-agent comms, and
preview sections) to the DB in the same `repository.update()` call
that saves pid/outputFilePath after spawn.

`getAgentPrompt` now reads from DB first (`agent.prompt`) and falls
back to the filesystem only for agents spawned before this change.

Addresses review comment [MMcmVlEK16bBfkJuXvG6h].

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-06 13:13:01 +01:00
Lukas May
6cf6bd076f feat: Add merge conflict detection and agent resolution in initiative review
Pre-merge mergeability check via `git merge-tree --write-tree` (dry-run, no
side effects). When conflicts exist the "Merge & Push" button is disabled and
a ConflictResolutionPanel shows conflict files with options to resolve manually
or spawn a conflict-resolution agent. Agent questions appear inline via
QuestionForm; on completion the mergeability re-checks automatically.

New server-side: MergeabilityResult type, BranchManager.checkMergeability,
conflict-resolution prompt, checkInitiativeMergeability query,
spawnConflictResolutionAgent mutation, getActiveConflictAgent query.

New frontend: useConflictAgent hook, ConflictResolutionPanel component,
mergeability badge + panel integration in InitiativeReview.
2026-03-06 11:17:25 +01:00
Lukas May
9c4131c814 feat: add addAccountByToken tRPC mutation with upsert logic and tests
Adds a new mutation that accepts an email + raw OAuth token and upserts
the account — creating it if it doesn't exist, updating credentials if
it does. Covers all four scenarios with unit tests (new, existing,
empty-email, empty-token validation).
2026-03-06 10:58:02 +01:00
Lukas May
7695604da2 feat: Add threaded review comments + agent comment responses
Introduces GitHub-style threaded comments via parentCommentId self-reference.
Users and agents can reply within comment threads, and review agents receive
comment IDs so they can post targeted responses via comment-responses.json.

- Migration 0032: parentCommentId column + index on review_comments
- Repository: createReply() copies parent context, default author 'you' → 'user'
- tRPC: replyToReviewComment procedure, requestPhaseChanges passes threaded comments
- Orchestrator: formats [comment:ID] tags with full reply threads in task description
- Agent IO: readCommentResponses() reads .cw/output/comment-responses.json
- OutputHandler: processes agent comment responses (creates replies, resolves threads)
- Execute prompt: conditional <review_comments> block when task has [comment:] markers
- Frontend: CommentThread renders root+replies with agent-specific styling + reply form
- Sidebar/ReviewTab: root-only comment counts, reply mutation plumbing through DiffViewer chain
2026-03-06 10:21:22 +01:00
Lukas May
2da6632298 docs: Update dispatch-events, server-api, frontend for request-changes fixes 2026-03-06 09:42:28 +01:00
Lukas May
269a2d2616 feat: Extend AgentInfo with exitCode + add getAgentInputFiles/getAgentPrompt tRPC procedures
Adds exitCode to AgentInfo type and propagates it through all toAgentInfo()
implementations. Enhances getAgent to also return taskName and initiativeName
from their respective repositories. Adds two new filesystem-reading tRPC
procedures for the Agent Details tab: getAgentInputFiles (reads .cw/input/
files with binary detection, 500 KB cap, sorted) and getAgentPrompt (reads
.cw/agent-logs/<name>/PROMPT.md with 1 MB cap and structured ENOENT handling).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 21:39:29 +01:00
Lukas May
0adbb55898 docs: Document addAccountByToken in server-api.md
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 20:59:01 +01:00
Lukas May
2eac5b9908 fix: Remove agent:output from general SSE subscriptions to prevent listener leak
agent:output is high-frequency streaming data that was included in
ALL_EVENT_TYPES and AGENT_EVENT_TYPES, causing every onEvent/onAgentUpdate
SSE subscription to register a listener. With multiple subscriptions per
browser tab plus reconnections, this exceeded the 100 listener limit.

The dedicated onAgentOutput subscription handles output streaming already.
Bonus: stops useLiveUpdates from refetching listAgents on every output chunk.
2026-03-05 17:50:01 +01:00
Lukas May
8804455c77 Remove task-level approval system
Task-level approval (requiresApproval, mergeRequiresApproval,
pending_approval status) was redundant with executionMode
(yolo vs review_per_phase) and blocked the orchestrator's
phase completion flow. Tasks now complete directly;
phase-level review via executionMode is the right granularity.

Removed: schema columns (left in DB, removed from Drizzle),
TaskPendingApprovalEvent, approveTask/listPendingApprovals
procedures, findPendingApproval repository method, and all
frontend approval UI.
2026-03-05 17:09:48 +01:00
Lukas May
209629241d feat: Add PREVIEW_EVENT_TYPES, CONVERSATION_EVENT_TYPES, and subscription procedures
- Add preview:building/ready/stopped/failed to ALL_EVENT_TYPES
- Export PREVIEW_EVENT_TYPES and CONVERSATION_EVENT_TYPES constants
- Add onPreviewUpdate and onConversationUpdate subscription procedures
- Add audit comment confirming phase:pending_review presence (gap 3 verified)
- Add unit tests covering constants, filtering behavior, and procedure shape
- Update server-api.md to document new subscription procedures

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 17:07:00 +01:00
Lukas May
dab1a2ab13 docs: Add initiative review gate to dispatch-events, server-api, and database docs 2026-03-05 17:00:38 +01:00
Lukas May
5e77bf104c feat: Add remote sync for project clones
Fetch remote changes before agents start working so they build on
up-to-date code. Adds ProjectSyncManager with git fetch + ff-only
merge of defaultBranch, integrated into phase dispatch to sync
before branch creation.

- Schema: lastFetchedAt column on projects table (migration 0029)
- Events: project:synced, project:sync_failed
- Phase dispatch: sync all linked projects before creating branches
- tRPC: syncProject, syncAllProjects, getProjectSyncStatus
- CLI: cw project sync [name] --all, cw project status [name]
- Frontend: sync button + ahead/behind badge on projects settings
2026-03-05 11:45:09 +01:00
Lukas May
8ae3916c90 docs: Add Request Changes feature to dispatch-events and server-api docs 2026-03-05 11:34:27 +01:00
Lukas May
173c7f7916 feat: Persist review comments to database
Review comments on phase diffs now survive page reloads and phase
switches. Adds review_comments table (migration 0028), repository
port/adapter (13th repo), tRPC procedures (listReviewComments,
createReviewComment, resolveReviewComment, unresolveReviewComment),
and replaces useState-based comments in ReviewTab with tRPC queries
and mutations.
2026-03-05 11:16:54 +01:00
Lukas May
c58e0ea77e feat: Redesign review tab with phase selection, commit navigation, and consolidated toolbar
- Add BranchManager.listCommits() and diffCommit() for commit-level navigation
- Add getPhaseReviewCommits and getCommitDiff tRPC procedures
- New ReviewHeader: consolidated toolbar with phase selector pills, branch info,
  stats, integrated preview controls, and approve/reject actions
- New CommitNav: horizontal commit strip with "All changes" + individual commits,
  each showing hash, message, and change stats
- Slim down ReviewSidebar: file list only with dimming for out-of-scope files
  when viewing a single commit
- ReviewTab orchestrates all pieces in a single bordered card layout
2026-03-05 10:20:43 +01:00
Lukas May
069eb66acb feat: Add project filter to listInitiatives
Add findByProjectId to InitiativeRepository using a subquery on the
initiative_projects junction table. Extend the listInitiatives tRPC
procedure to accept an optional projectId filter that composes with
the existing status filter. Add a project dropdown to the initiatives
page alongside the status filter.
2026-03-04 11:40:32 +01:00
Lukas May
1aef986127 fix: Sort pipeline tasks by dependency order instead of priority+createdAt
The Execution tab's PipelinePhaseGroup was using sortByPriorityAndQueueTime
which ignores task dependencies entirely. Tasks now sort topologically via
topologicalSortPhases, matching the Plan tab's TaskGraph behavior.

- Add listInitiativeTaskDependencies tRPC procedure (bulk fetch)
- Fetch task deps in PipelineTab, group by phase, pass through
- Replace priority sort with topological sort in PipelinePhaseGroup
- Show "blocked by N" count on PipelineTaskCard
2026-03-04 10:18:26 +01:00
Lukas May
fcf822363c feat: Add persistent chat sessions for iterative phase/task refinement
Introduces a chat loop where users send instructions to an agent that
applies changes (create/update/delete phases, tasks, pages) and stays
alive for follow-up messages. Includes schema + migration, repository
layer, chat prompt, file-io action field extension, output handler chat
mode, revert support for deletes, tRPC procedures, events, frontend
slide-over UI with inline changeset display and revert, and docs.
2026-03-04 10:14:28 +01:00
Lukas May
2948eb1139 feat: Add tiptap editor for task descriptions in slide-over panel
- Add updateTask tRPC mutation (name, description fields)
- Replace static description with TiptapEditor in TaskSlideOver
- Auto-detect existing markdown descriptions and convert to tiptap JSON
- Debounced auto-save with flush on close/unmount
- Saving indicator in header
2026-03-04 09:06:44 +01:00
Lukas May
9e7c246280 fix: Switch auto-spawn from discuss to refine agent, surface in UI
The auto-spawned agent on initiative creation was using discuss mode
(Q&A) when it should use refine mode (expand content). Now:

- Description seeds root page as tiptap content (split on double newlines)
- Spawns refine agent with the populated page in inputContext
- getActiveRefineAgent broadened to also surface discuss agents (for
  CLI-spawned discuss agents)
- RefineAgentPanel shows mode-appropriate label for discuss vs refine
2026-03-03 14:25:43 +01:00
Lukas May
9b91ffe0e5 fix: Persist and expose task dependencies from detail output
Detail agents define task dependencies in YAML frontmatter but they were
silently dropped — never written to the task_dependencies table. This
caused all tasks to dispatch in parallel regardless of intended ordering,
and the frontend showed no dependency information.

- Add fileIdToDbId mapping and second-pass dependency creation in
  output-handler.ts (mirrors existing phase dependency pattern)
- Add task_dependency to changeset entry entityType enum
- Add listPhaseTaskDependencies tRPC procedure for batch querying
- Wire blockedBy in PhaseDetailPanel and PhaseWithTasks from real data
- Clarify dependency semantics in detail prompt
2026-03-03 13:46:29 +01:00
Lukas May
86a1912959 feat: Add description field and auto-spawn discuss agent on initiative creation 2026-03-03 13:40:37 +01:00
Lukas May
411700d37d feat: Show detailing status in initiative overview and phase sidebar
Add 'detailing' activity state derived from active detail agents
(mode=detail, status running/waiting_for_input). Initiative cards show
pulsing "Detailing" indicator. Phase sidebar items show spinner during
active detailing and "Review changes" when the agent finishes.
2026-03-03 13:08:05 +01:00
Lukas May
96386e1c3d feat: Replace initiative card N+1 queries with server-computed activity indicator
listInitiatives now returns an activity object (state, activePhase, phase
counts) derived server-side from phases, eliminating per-card listPhases
queries. Initiative cards show a StatusDot with pulse animation + label
instead of a static StatusBadge. Removed redundant View and Spawn Architect
buttons from cards. Added variant override prop to StatusDot.
2026-03-03 12:49:07 +01:00
Lukas May
34578d39c6 refactor: Restructure monorepo to apps/server/ and apps/web/ layout
Move src/ → apps/server/ and packages/web/ → apps/web/ to adopt
standard monorepo conventions (apps/ for runnable apps, packages/
for reusable libraries). Update all config files, shared package
imports, test fixtures, and documentation to reflect new paths.

Key fixes:
- Update workspace config to ["apps/*", "packages/*"]
- Update tsconfig.json rootDir/include for apps/server/
- Add apps/web/** to vitest exclude list
- Update drizzle.config.ts schema path
- Fix ensure-schema.ts migration path detection (3 levels up in dev,
  2 levels up in dist)
- Fix tests/integration/cli-server.test.ts import paths
- Update packages/shared imports to apps/server/ paths
- Update all docs/ files with new paths
2026-03-03 11:22:53 +01:00
Lukas May
6fa025251e feat: Wire up initiative deletion end-to-end
Add deleteInitiative tRPC procedure, wire Delete button in InitiativeCard
with confirm dialog (Shift+click bypass), remove unused onDelete prop chain.
Fix agents table FK constraints (initiative_id, account_id missing ON DELETE
SET NULL) via table recreation migration. Register conversations migration
in journal. Expand cascade delete tests to cover pages, projects, change
sets, agents (set null), and conversations (set null).
2026-02-18 17:54:53 +09:00
Lukas May
62a542116d feat: Add task deletion with shift+click auto-confirm
- Add deleteTask tRPC mutation (repo already had delete method)
- Add X button to TaskRow, hidden until hover, with confirmation dialog
- Shift+click bypasses confirmation for fast bulk deletion
- Invalidates listInitiativeTasks on success
- Document shift+click pattern in CLAUDE.md as standard for destructive actions
2026-02-10 15:58:24 +01:00
Lukas May
c2d665c24f feat: Make initiative branch and execution mode editable from header
- Execution mode badge toggles between YOLO/REVIEW on click
- Branch badge opens inline editor (input + save/cancel)
- Branch editing locked once any task has left pending status
- Server-side guard rejects branch changes after work has started
- getInitiative returns branchLocked flag
- updateInitiativeConfig now accepts optional branch field
2026-02-10 15:52:40 +01:00
Lukas May
a6371e156a feat: Add inter-agent conversation system (listen, ask, answer)
Enables parallel agents to communicate through a CLI-based conversation
mechanism coordinated via tRPC. Agents can ask questions to peers and
receive answers, with target resolution by agent ID, task ID, or phase ID.
2026-02-10 13:43:30 +01:00
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
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
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
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
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