- Rotation triggered when run count exceeds maxRuns threshold
- Rotation triggered when token count exceeds maxTokens threshold
- Handoff markdown generated with task title and run history
- New session after rotation has clean counters (0 runs, 0 tokens)
- Claude connector exempt from rotation (nativeContextManagement)
- Codex connector exempt from rotation (nativeContextManagement)
- Handoff markdown available for next run context after rotation
- In-flight run completes normally when budget exhausted by another run
- Budget gate blocks next run after exhaustion
- BlockedBy returns detailed policy/scope/spent/limit info
- Agent-scope exhaustion blocks even when company budget has room
- Budget gate transitions from allowed to blocked after spending
- Cost entry recorded even when budget would be exceeded
- 10 tests covering worker crash detection, lock release, agent reset
- Session handoff markdown generation with real DB
- Context preservation (D-02): agent assignment retained after crash
- DB consistency verification: no running runs/agents, no orphaned locks
- Multiple concurrent runs all interrupted on crash
- Uses real AppDatabase with temp dirs, gemini_local connector
- CAS rejects second claimer when two agents attempt same task
- Losing agent can checkout a different task
- In-progress status guard blocks new checkouts
- Lock release clears fields but CAS still checks status
- Stale lock recovery frees locks and resets status to todo
- Recovered task can be re-checked-out by another agent
- STALE_LOCK_TIMEOUT_MS validated at 15 minutes
- Replace createEventBatcher with createDomainEventBatcher in App.tsx
- Add handleGranularBatch for task, run, approval, agent, and budget events
- Task/run/approval events trigger targeted IPC fetch and Zustand patch
- Run completion and budget changes trigger full refresh (cross-entity)
- Failed entity fetches fall back to removeTask or full refresh
- Unknown event types trigger full refresh (PERF-03 safety)
- Sidebar badges refresh after every successful granular batch
- Add 12 integration tests for handleGranularBatch in selective-ipc.test.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Resolve merge conflicts in worker-service.ts and ipc-core-work-graph-handlers.ts
- Keep granular emitEvent calls from plan 02 while preserving session management and task validation from main
- Fix duplicate createSkillService import in service-graph.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Replace publishDomainChanged() with granular events at 9 high-frequency callsites
- saveTask/deleteTask emit task-updated events in ipc-core-work-graph-handlers
- decideApproval emits approval-updated, addComment emits task-updated
- worker-service emits run-updated for status changes and completion
- worker-service emits agent-updated for budget hard-stop pause
- orchestration-service emits agent-updated for auto-pause, run-updated for dispatch
- Wire emitEvent dependency to orchestration-service via service-graph
- Keep publishDomainChanged for low-frequency and multi-entity paths
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add createDomainEventBatcher with entity type+ID dedup within 50ms window
- Domain-changed overrides all granular events in same batch
- More than 10 unique entities triggers full refresh fallback
- Delete action preserved during coalescing (last-write-wins otherwise)
- Unknown event types trigger full refresh as safety fallback
- Legacy createEventBatcher preserved for backward compatibility
- Add 12 comprehensive tests for all coalescing behaviors
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add RunActivityChart (area chart), SuccessRateChart (line chart), CostTrendChart (area chart), AgentWorkloadChart (bar chart) using Recharts
- Add BudgetUtilization with CSS progress bars, color thresholds (success/warn/danger), and empty state
- Create ChartSection container orchestrating all charts with Framer Motion entrance animation
- Integrate ChartSection into Dashboard.tsx between MetricsGrid and NeedsAttention
- Add companyId prop to DashboardProps and pass from App.tsx
- Include Plan 01 infrastructure: chart-utils.ts, ChartCard.tsx, ChartTooltip.tsx, recharts dependency
- All charts respect reduced motion via useReducedMotion hook
- 16 unit tests pass for aggregation functions
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- ChartCard: shared chart card with title, period badge, empty state, role="img" accessibility
- ChartTooltip: custom Recharts tooltip with design system tokens, color dots, mono font
- Both use CSS custom properties for automatic dark mode support
- TypeScript compiles cleanly with Recharts TooltipContentProps type
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Install recharts@3.8.1 as dependency
- Create chart-utils.ts with 4 exported pure functions: aggregateRunsByDay, aggregateCostsByDay, aggregateAgentWorkload, formatShortDate
- Create dashboard-charts.test.ts with 16 unit tests covering all aggregation behaviors
- All tests pass: 14-day bucketing with zero-fill, timed_out/interrupted as failed, null cost handling, top-8 + Others grouping, name truncation
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Import sweepStaleReviews, resolveApprovalDecision, dispatchAgentMessage
- Insert stale review sweep into per-company heartbeat loop after budget reset
- Sweep runs on every 15-second heartbeat cycle for each active company
- Local callback stubs for handleTaskStatusChange and handleApprovalResolved
- Error handling prevents sweep failures from crashing the heartbeat loop
- Fix test type casts to use as-unknown-as for vi.fn mock compatibility
- TypeScript compiles cleanly, 249/249 tests pass
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- sweepStaleReviews queries tasks in in_review status exceeding 30-min timeout
- Escalation dispatched to reviewer's manager (manager's manager in chain)
- When reviewer is CEO (no higher manager), desktop notification sent to human
- Pending approvals auto-approved with documented timeout note
- Task status advanced from in_review to done after escalation
- Race condition with manual approval handled via try-catch (Pitfall 3)
- Tasks without assigneeAgentId skipped gracefully
- Exports REVIEW_TIMEOUT_MS (1800000ms) and SweepStaleReviewsDeps interface
- 8 comprehensive unit tests covering all TASK-04 behaviors
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Cherry-pick plan 01 task quality gate validation module and its
integration into IPC, API server, and automation service.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add SaveTaskResult type to contracts.ts (id + optional capabilityWarning)
- IPC handler: validate new tasks, reject with TASK_VALIDATION_FAILED, check capability match
- API server: validate POST /issues and meeting action items before db.saveTask
- Automation service: validate create_task action, skip with warning if invalid
- CapabilityMatchDb interface uses optional skill methods for graceful degradation
- TypeScript compiles cleanly across all process boundaries
- All 241 tests pass with zero regressions
- Add sessionHandoff field to PromptContext interface and Session Handoff section in buildSystemPrompt
- Add getSessionHandoff dependency to orchestration service, load handoff before prompt build
- Update orchestration to prefer task_sessions table over legacy tasks.session_json (SESS-01)
- Wire getSessionHandoff through ServiceGraph into createOrchestrationService
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Add getActiveTaskSession, incrementSessionUsage, archiveSession, createNewSession,
getRecentRunsForTask, getRecentActivityForTask methods to AppDatabase
- Add nativeContextManagement optional boolean to ServerAdapterModule interface
- Set nativeContextManagement: true for claude_local and codex_local, false for gemini_local
- Add TaskSessionRecord interface to shared types
- Add unit tests for task_sessions CRUD and adapter exemption flags
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- BudgetSummary shows policy-level utilization bars when companyId provided, falls back to agent-level
- BudgetAlertBanner loads open incidents for policy-based alerts (warn_threshold/hard_stop), falls back to agent thresholds
- AgentEditor reads budget from budget_policies and writes budget as policy on save (D-11)
- Dashboard passes companyId through to BudgetAlertBanner
- Create PolicyList with utilization bars, edit/delete, empty state
- Create PolicyFormModal with scope selector, dollar amount, warn/hard-stop toggles
- Create IncidentList with status filtering and manual resolve action
- Add tabbed navigation (Cost Entries | Policies | Incidents) to costs section
- Export new components from execution barrel file
- Replace flat budgetMonthlyUsd check with evaluateBudgetGate in getRunEligibilityFailure
- Add projectId parameter to getRunEligibilityFailure for project-scope policy evaluation
- Update all 3 call sites to pass projectId where task context is available
- Wire checkAndCreateIncidents into worker-service run-finished handler for post-run incident creation
- Wire autoCloseExpiredIncidents into heartbeat for window rollover cleanup (D-06)
- Pass budgetService dependency to orchestration-service and worker-service via service-graph
- Mark autoPauseBudgetExceededAgent as deprecated (superseded by BudgetEnforcementService)
- Create ipc-budget-handlers.ts with 6 budget channel handlers (save/delete/list policies, list/resolve incidents, get status)
- Add budgetService to RegisterDomainHandlersDependencies interface
- Register budget handlers in ipc-domain-handlers.ts composition
- Add BudgetEnforcementService lazy slot in service-graph.ts with getOrCreateBudgetEnforcementService
- Pass budgetService to domain handler registration in main-runtime-support.ts
- Fix preload bridge to pass {companyId} object for listBudgetPolicies and getBudgetStatus
- D-06: checkAutoResolve called on saveBudgetPolicy to auto-resolve incidents on limit increase
Migration 13 columns were skipped when ensureOptionalColumns added
checkout_run_id first, triggering 'duplicate column' catch that marked
the entire migration as applied without running remaining ALTERs.
- Add releaseTaskLock to worker crash recovery after finishRun (EXEC-02)
- Track affected agent company IDs for targeted wake promotion
- Replace listWakeupRequests+loop with promoteWakeupRequests+wakeAgentIfPossible in run completion
- Track hadDeferredWakes flag for circuit breaker self-wake decision
- Add listWakeupRequests IPC channel to IPC_CHANNELS
- Add wakeupQuerySchema with Zod validation and WakeupRequestRecord interface
- Add listWakeupRequests to DesktopApi type
- Add listWakeupRequests preload bridge method
- Add registerHandle for listWakeupRequests IPC handler with company validation
- Add randomUUID import for pre-generated runId in CAS checkout flow
- Replace task-level hasActiveRun checks with db.checkoutTask CAS in startAgentHeartbeatRun and queueTaskRun
- Pass pre-generated runId to createRun (database.ts accepts optional id field)
- Log execution.checkout_rejected activity on CAS failure (D-04)
- Return fail("CHECKOUT_RACE_LOST") in queueTaskRun on CAS failure
- Rewrite wakeAgentIfPossible with proper lifecycle tracking via enqueueWakeupRequest
- Add stale lock recovery sweep at startup (resumeQueuedRuns) and each heartbeat tick
- Log execution.lock_recovered activity entries for recovered stale locks
- Fix SQLInputValue type in listWakeupRequests params
- Fix leftover pendingWakes reference in worker-service.ts
- Fix RunStatus 'completed' -> 'succeeded' in atomic-checkout test
- Update autonomous-chain.spec.ts to use new wakeup lifecycle API
- Rewrite checkoutTask to use runId-based CAS with checkout_run_id IS NULL guard
- Add releaseTaskLock and recoverStaleLocks methods
- Add lock release in finishRun and cancelRunForDeletion exit paths
- Add migration 16: pending_wakes to wakeup_requests cutover with DROP TABLE
- Replace all pending_wakes references with wakeup_requests
- Add wakeup lifecycle CRUD: enqueue, claim, complete, defer, promote, list
- Update api-server, orchestration-service, worker-service callers
- Update existing database.test.ts for new checkoutTask signature
- 8 test cases covering CAS semantics, lock release on finishRun/deleteAgent, stale recovery
- Tests expect STALE_LOCK_TIMEOUT_MS export, checkout_run_id/execution_locked_at columns
- RED phase: 5 of 8 tests fail as expected before implementation
- Import SkillAgentToggles and Zustand skill state into AgentEditor
- Add lazy skill loading for navigation paths that bypass Skills section
- Render Skills section with agent-centric toggle mode between heartbeat and save
- Add listSkillAgents and listAgentSkills IPC channels with Zod schemas
- Create SkillDetail component with metadata, file viewer, update check, delete
- Create SkillAgentToggles with discriminated union for skill/agent-centric modes
- Wire SkillDetail into SkillsSection right column replacing placeholder
- Remove duplicate skill method declarations from DesktopApi type