Migration 28 (add_snapshot_hot_path_indexes) referenced task_comments,
documents, meetings, sprints, agent_messages, activity — all tables
created by ensureOptionalColumns() which runs AFTER runMigrations() on
a fresh DB. Converted from sql-string migration to fn-based so each
index is gated by tableExists(); safe on both fresh and migrated DBs.
Also updated tests/unit/selective-ipc.test.ts exhaustive switch to
include the 7 new DesktopEvent variants added in ef90a58.
Adapt existing assertions to the current ConnectorDefinition shape:
`auth`, `provider`, and `defaultModel` are declared optional, and the
API-key envvar field is now `envKey`. Use optional chaining and coalesce
to keep the same behavioural checks passing under strict typing.
- Add required `roleLevel` to dashboard-charts and prompt-manager fixtures
so they satisfy the AgentRecord contract.
- Replace legacy "anthropic" connectorId with `claude_local` in
approval-hook fixture to match the current `ConnectorId` union.
CompanySlice's standalone currentCompanyId field + setCurrentCompanyId action
were never written by any caller, so useDesktopEvents.ts read null and fell
through to full refresh for every entity event -- the granular patch
machinery was dead code.
- Remove currentCompanyId field + setCurrentCompanyId from CompanySlice
- refreshBadges reads from snapshot.currentCompanyId
- useDesktopEvents reads companyId from snapshot.currentCompanyId
- Update store unit test to seed snapshot instead of calling removed action
Aligns tests/unit/database.test.ts with the existing convention in
oauth-login-service/credential-resolver/credential-store tests: set
AGENTCOMPANY_ALLOW_INSECURE_VAULT=true in beforeAll so the in-memory
database test can call saveSecret without a real OS keychain.
Follow-up to aa1afd0 which removed the NODE_ENV=test/VITEST auto-enable.
- Add findReusableHeartbeatTask() to find most recent done/in_review heartbeat task per agent
- Add cleanupDuplicateHeartbeatTasks() to cancel old duplicates using ROW_NUMBER window function
- Add 12 unit tests covering coalescing behavior, cross-agent isolation, status filtering
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- 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
- 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>
- 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>
- 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>
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 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>
- 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
- Tests normalizeSkillSlug for edge cases (empty, null, special chars)
- Tests hashSkillValue determinism and 10-char hex output
- Tests deriveCanonicalSkillKey for all 5 source types
- Tests parseSkillImportSource for GitHub, skills.sh, URL, local paths
- Tests parseFrontmatterMarkdown with frontmatter, no frontmatter, CRLF normalization
- Tests classifyInventoryKind for all file type classifications
- Tests deriveTrustLevel for script/asset/markdown-only derivation
- Tests estimateTokens for token estimation logic
- Add createNotificationService with 10s batch window, urgency mapping, click-to-navigate
- Extend DesktopEvent union with NotificationClickEvent type
- Add 10 unit tests covering batching, urgency, NEVER_BATCH, GC protection, Linux urgency
- Platform-specific: silent flag, Windows timeoutType, Linux urgency level
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- Create SocialDraftPreview with platform icon, color, content, char count, media URLs, schedule display
- Integrate SocialDraftPreview into ApprovalInspector for social_post approvals
- Add schedule picker with immediate/scheduled radio group and datetime-local input
- Add social_post to type badge with accent styling
- Approve button shows 'Approve & Post' for social_post approvals
- Accessibility: role=region, aria-label, aria-live=polite, role=radiogroup
- Fix test type annotation for TS compatibility
- Add social_post to ApprovalType union in types.ts
- Add social_post to approvalInputSchema enum in contracts.ts
- Add POST /api/companies/:companyId/social/draft endpoint in api-server.ts
- Add social_post handling in handleApprovalResolved in automation-service.ts
- Browser action payloadJson includes scheduledAt for startup recovery (03-03 contract)
- Scheduled posts use setTimeout for deferred dispatch
- All 13 unit tests pass
- Add searchMessages method to AppDatabase with LIKE query, wildcard escaping, channel scoping, ORDER BY created_at DESC with limit
- Add searchMessages IPC channel and searchMessagesSchema to contracts.ts
- Register IPC handler in ipc-agent-coordination-handlers.ts with Zod validation
- Wire searchMessages through preload bridge
- Add 8 unit tests covering body/subject search, wildcard escaping, channel scoping, empty results, limit, and ordering
- Add notify() calls at 80% budget threshold warning and 100% exhaustion auto-pause
- Compute percentage as Math.round(utilization * 100) for accurate display
- Add scheduled social post timer re-registration on app startup
- Add unit tests for budget threshold detection and notification logic
- Add MAX_RETRY_ATTEMPTS (2) and RETRY_COOLDOWN_MS (30s) constants
- Replace immediate escalation with retry-then-escalate logic
- Escalation chain: retry same agent -> manager -> CEO -> user notification
- Reset retry count on successful task completion
- Update Reassign on run failure automation rule with afterRetryExhaustion condition
- Add comprehensive unit tests for escalation state machine (11 tests)