P2-36: Multiple subsystems were string-coupled via the magic
'[Heartbeat]' prefix. Introduce src/main/orchestration/heartbeat-task.ts
as the single source of truth and replace scattered literals in
heartbeat dispatch, automation actions, and run completion.
P3-52: Collapse 5-deep ternary in automation-actions' wake-trigger
selection into lookup helpers (deriveHeartbeatWakeTrigger,
deriveEscalationWakeTrigger).
Function signature reduced from 16 args to 4; setters sourced from
useAppStore.getState() inside callbacks (stable refs, no deps needed).
useCompanyController no longer has to thread 14 setters through.
Delete the useUIController.navigateTo duplicate; augment slice version with
task-with-run lookup (via get().snapshot) so notification-click and command
palette share one codepath. App.tsx now reads navigateTo from the store.
P2-46: Previous bare try/catch hid parse errors, making rules silently
non-firing. Let JSON.parse throw; the caller (evaluateAutomationRules)
already logs and records the failure.
P1-19: Previous string-join with ':' separator could collide when
field values contain colons (e.g. runId='a:b' vs runId='a' + previousStatus='b').
Use JSON.stringify for unambiguous serialization.
Replace the six inline queryAll calls in routes-agents-standup.ts with
typed domain methods: db.agents gains listDirectReportsForStandup and
listReportStatusesForStandup (LEFT JOIN aggregation), db.tasks gains
listAssigneeTasksForStandup and listTasksForAssignees (safe on empty
assignee list), db.approvals gains listAgentPendingApprovals and
listAgentResolvedApprovals. Shared listRecentTaskComments is reused.
Replace the ad-hoc getApproval helper and the filterable list query
in routes-approvals.ts with db.approvals methods. Add findApprovalById
(non-throwing lookup returning null) and listApprovalsForApi (accepts
requestedByAgentId / relatedTaskId / statuses filters and builds the
prepared statement inside the domain layer).
Replace six inline queryAll calls in routes-work-graph.ts with domain
methods. db.entityCrud gains listGoals, getGoalForUpdate, listProjects,
getProjectForUpdate. db.knowledge gains listSprints. db.company gains
getDashboardSnapshot, which returns the raw agent/task/activity rows
the dashboard handler aggregates. The route-level row shapes are
preserved in the new GoalListRow / ProjectListRow / SprintListRow
types so HTTP responses remain identical.
Replace the inline knowledge_base queryAll in routes-misc.ts with
db.listKnowledgeEntries (added in the previous commit). Routes-misc
now holds no raw SQL.
Replace inline queryAll calls in routes-meetings.ts with two new
domain methods on db.knowledge: listMeetings (powers
GET /api/companies/:companyId/meetings) and getMeeting (used by the
PATCH meeting handler). The MeetingListRow shape mirrors the historical
inline projection so HTTP responses stay byte-stable. Also adds
listKnowledgeEntries here for use by routes-misc.
Replace raw queryAll calls in routes-files.ts with two new domain
methods on db.documents: listDocuments (powers
GET /api/companies/:companyId/documents) and getDocumentForUpdate (used
by the PATCH document handler). The DocumentListRow / DocumentLookupRow
shapes preserve the historical inline-SQL projections so HTTP responses
remain identical.
Replace inline queryAll calls in routes-tasks.ts with two new domain
methods: tasks.listTasksByStatuses (used by GET /api/companies/:id/issues)
and documents.listImportantDocsForReview (used by the deliverable-review
gate). Routes now hold no SQL or column-mapping logic; the
TaskListByStatusesRow shape preserves the existing HTTP response fields
including requiresUserReview as a boolean.
Move the duplicated important-document-type list out of routes-tasks.ts
and routes-files.ts into src/shared/document-categories.ts so the array
and lookup set live in one place.
Replace full-company SELECT * + JS filtering with targeted scoped queries:
- direct reports = agents WHERE reports_to = me
- my tasks = tasks WHERE assignee_agent_id = me
- report tasks = tasks WHERE assignee_agent_id IN (...directReports)
- report status counts = LEFT JOIN tasks GROUP BY report agent
- approvals scoped to requested_by = me with separate pending /
resolved queries (resolved capped at 5 in SQL)
JSON response shape unchanged.
Replace 17-table snapshot fetch + 6 JS filter passes with 5 scoped
SELECTs targeting only inbox-relevant rows:
- approvals where state = 'pending'
- runs where status in ('failed', 'timed_out') and created_at > 24h
- agents where budget breach > 80%
- tasks where status in ('blocked', 'in_review')
- agent_messages with __board__ read-receipt left join filtered to
company/incident channel or urgent priority
Agent name lookup is a single id->name map built from one scoped agents
read. Return shape unchanged.
Replace 17-table snapshot fetch + per-agent JS filters with:
- scoped agents row read (excluding terminated/pending_approval)
- tasks GROUP BY assignee_agent_id with conditional sums for
in_progress / blocked / done-in-24h counts
- runs GROUP BY agent_id over 24h window with correlated subquery
for last status, plus max(created_at) for last run timestamp
- cost_entries GROUP BY agent_id over 24h window for cost
- activity GROUP BY actor for review-cycle counts
- single SELECTs for company-level counters (completed tasks, run
aggregates, blocked tasks, pending approvals, urgent unread, active
sprint)
Return shape unchanged.
Replace the racy three-step heartbeat path (listAgentTasks ->
findReusableHeartbeatTask -> saveTask -> checkoutTask) with a single
transactional acquireHeartbeatTask method. The prior flow allowed two
concurrent scheduler ticks to both observe "no reusable heartbeat" and
both INSERT a fresh [Heartbeat] task before either CAS-checked out,
producing duplicates that cleanupDuplicateHeartbeatTasks had to mop up.
acquireHeartbeatTask runs inside BEGIN IMMEDIATE so concurrent ticks
serialize on the writer lock. Inside the transaction it first attempts
to claim any existing claimable [Heartbeat] task (todo/backlog/done/
in_review with checkout_run_id IS NULL), reviving done/in_review by
resetting status. If nothing is claimable but an in-flight heartbeat
exists (status NOT IN done/cancelled), it returns null instead of
creating a duplicate. Only when no heartbeat task exists at all does it
INSERT a new one, already in 'in_progress' with checkout_run_id set.
cleanupDuplicateHeartbeatTasks remains as deletion-side defense.
Replace 17-table snapshot fetch + 50+ JS filters per agent with five
scoped aggregation queries:
- tasks GROUP BY assignee_agent_id with conditional sums for done /
assigned / cancelled counts
- runs (within cutoff) GROUP BY agent_id with conditional sums for
succeeded / failed counts
- runs GROUP BY agent_id over started_at/finished_at for avg duration
+ max(created_at) as last active
- cost_entries GROUP BY agent_id for total cost
- activity GROUP BY actor restricted to status-change actions for
review cycle count
Company-level totals also collapse to single COUNT/SUM queries instead
of in-memory reductions over the full snapshot. Return shape unchanged.
Add explicit LIMIT to all hot-path tables in listSnapshot regardless of
companyId, raise cross-company caps from 500/250 to 2000/1000 so dashboard
no longer truncates silently at 500.
Add migration 28 with composite indexes covering snapshot WHERE/ORDER BY
columns: tasks(company_id, created_at|updated_at), approvals(company_id,
created_at), task_comments(company_id, created_at), documents(company_id,
updated_at), meetings(company_id, scheduled_at), sprints(company_id,
start_date), runs(agent_id, created_at), cost_entries(agent_id,
created_at), activity(company_id, actor, action), tasks(company_id,
assignee_agent_id, status). Indexes match exact ORDER BY direction so
SQLite can satisfy reads via index scan without temp sort.
Sections now subscribe directly to the Zustand store via useSectionContext
(shared data derivation) and useAppStore fine-grained selectors. Delete
useAppController, useExecutionController, useOrganizationController, and
useCommunicationController; the three domain forwarders held no logic
beyond re-exporting store slices.
SectionContentView becomes a 50-line layout dispatcher taking only
{section, error, pageTransition}; cross-domain run actions (startRun /
cancelRun) move into App.tsx and are exposed to sections through a new
AppActionsContext alongside refresh / setError / openPathWithFeedback.
App.tsx now calls useUIController + useCompanyController directly and
composes palette + navigation plumbing itself.
OnboardingStepPanel previously forwarded ~50 props to seven step
components, so adding a single wizard field meant touching four layers.
Introduce a renderer-local React Context (OnboardingProvider /
useOnboarding) that carries all wizard state and actions (connectors,
node status, company inputs, model selection, execution mode, mission,
launch summary, locale, t, error/loading). Step panels now receive only
their navigation callbacks (onContinue / onBack / onLaunch / onFinish)
and read everything else via useOnboarding(). CompanyOnboarding wraps
the step panel tree in OnboardingProvider with a memoised value.
Business logic is unchanged: each onContinueFrom* transition, the
bootstrap call, and the welcome-step branch remain exactly as before;
this refactor only moves the data-passing mechanism.
Extract handleWorkerMessage (380 lines, 12 positional args) into dispatcher
+ focused handler modules. Dispatcher now routes by message.type to
run-log / run-status / run-finished handlers, each receiving (event, deps,
context) triple. run-finished is further decomposed into 5 steps:
finalizeRun, accumulateAndRotateSession, emitAndNotifyCompletion,
runPostCompletionAutomation, triggerSelfWake.
No behavior change: all branches, notifications, lease renewals, circuit
breaker, and escalation semantics preserved. Schema validation stays at
dispatcher top level.
All six step panels previously hard-coded "X / 5" or "X / 6" in their
header captions, which drifted out of sync with the 7-step STEP_ORDER in
OnboardingHero. Export STEP_ORDER / TOTAL_STEPS / getStepNumber from
OnboardingHero and consume them in every step so the counter is always
the single source of truth.