Commit Graph
166 Commits
Author SHA1 Message Date
ZacharyZhang-NY 70d416fa18 fix(connector-auth): expand Linux terminal candidates and honor $TERMINAL 2026-04-16 22:59:06 -04:00
ZacharyZhang-NY 83462a4663 refactor(browser-action): extract getApprovalOrNull helper to drop nested try/catch 2026-04-16 22:58:31 -04:00
ZacharyZhang-NY 5d9639ca4a fix(prompt): CEO priority list numbering + drop trailing locale reminder
P2-49: CEO Priority 1 standup list had two '4.' entries followed by
'5.' and '6.'. Renumber to 3/4/5/6/7.

P2-45: Remove the tail 'Language Requirement Reminder' section. The
body of the prompt is English regardless of locale, so appending
'remember Chinese' after 8KB of English made the locale signal less
coherent rather than more. Keep the single up-front locale instruction.
2026-04-16 22:58:15 -04:00
ZacharyZhang-NY 2bed06ca64 security(agent-auth): rotate signing key on every launch 2026-04-16 22:58:01 -04:00
ZacharyZhang-NY 2df921ca88 refactor(agents): share leadership role detector, use word-boundary match
P2-23: 'lead' in system-prompt.ts matched 'cleaner' / 'leaderboard' via
substring .includes(). Hoist LEADERSHIP_ROLE_KEYWORDS into a shared
agent-role-helpers.ts module; tokenize input on non-alphanum to require
whole-word match.

P3-54: Same keyword list was duplicated in automation-skills with drift
(missing 'ceo', different members). Both sites now call through the
shared helper.
2026-04-16 22:57:35 -04:00
ZacharyZhang-NY ba6ba8360b docs(budget): clarify policy.amount<=0 disables the rule 2026-04-16 22:57:05 -04:00
ZacharyZhang-NY f468f7c238 fix(prompt): use UTC day-of-week to match UTC date/time stamp
P2-24: now.getDay() returns local time weekday but the stamp reads
'UTC', producing off-by-one-day errors near UTC midnight. Switch to
now.getUTCDay().
2026-04-16 22:56:54 -04:00
ZacharyZhang-NY 0706ad78bb refactor(browser-manager): hoist resolvedRoot out of screenshot filter chain 2026-04-16 22:56:46 -04:00
ZacharyZhang-NY 4000854b69 fix(heartbeat): remove silent-default try/catch around getHeartbeatPolicy
P2-35: The policy row is the gate that decides whether the agent runs;
pretending cooldown is 10s when the read fails hides data corruption.
db.getHeartbeatPolicy already supplies field-level defaults from policy
JSON — and the only reason to throw here is 'agent not found', which
is already impossible because the caller just loaded db.getAgent.
2026-04-16 22:56:43 -04:00
ZacharyZhang-NY fc47b60d1b refactor(approval-policy): normalize decisionNote into single local 2026-04-16 22:56:34 -04:00
ZacharyZhang-NY 2deaa0d8b8 feat(automation): add per-action zod schemas for config validation
P2-29: JSON.parse(actionConfigJson) with blanket '(config.x as string)'
coerced malformed config to placeholder values silently (e.g. numeric
priority landed as 'medium'). Introduce parseActionConfig(action, json)
backed by per-action zod schemas in automation-action-schemas.ts.
Validation failures throw, surfaced by evaluateAutomationRules' logger
+ execution recorder. Individual case branches keep existing default
semantics for optional fields.
2026-04-16 22:56:18 -04:00
ZacharyZhang-NY 6429c76ac7 fix(run-housekeeping): gate auto knowledge_base writes on task type or department 2026-04-16 22:56:16 -04:00
ZacharyZhang-NY 9a5cdad86e fix(db): use single timestamp in markRefreshed + recordAutomationExecution (P1-23, P3-46) 2026-04-16 22:55:33 -04:00
ZacharyZhang-NY 7ba19fab77 fix(db): validate backup schema version + recover db on restore failure (P1-21, P1-22) 2026-04-16 22:55:05 -04:00
ZacharyZhang-NY 5feeb96522 fix(browser-manager): enforce 5min per-action timeout with cancellation path 2026-04-16 22:54:53 -04:00
ZacharyZhang-NY 69b1d8b667 security(ipc): add ensureCompanyExists+belongsToCompany guards to operations handlers (P1-20) 2026-04-16 22:54:34 -04:00
ZacharyZhang-NY 3deb1c00ac perf(db): batch skill-words + reports queries for scoreCandidate (P1-18) 2026-04-16 22:53:39 -04:00
ZacharyZhang-NY bb397dff02 refactor(heartbeat): centralize [Heartbeat] prefix as a shared constant
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).
2026-04-16 22:53:19 -04:00
ZacharyZhang-NY 12279005fe fix(db): add run_events(run_id,seq) unique index + wrap appendRunEvent in tx (P1-15) 2026-04-16 22:53:06 -04:00
ZacharyZhang-NY 7f2d028080 fix(updater): only toast 'Up to Date' on manual user-initiated checks 2026-04-16 22:52:16 -04:00
ZacharyZhang-NY 8867f50b37 refactor(db): consolidate BOARD_READER_ID in helpers + escape backslash in LIKE (P3-50, P1-26) 2026-04-16 22:52:09 -04:00
ZacharyZhang-NY e42879bfbe perf(db): push listAgentMessages visibility filter + limit to SQL (P1-17) 2026-04-16 22:51:27 -04:00
ZacharyZhang-NY 66f5e0923d fix(automation): log no-op status-change calls instead of silently returning
P2-34: Silent no-op guard hid caller bugs. Warn-log the violation so
it shows up in traces; callers should still gate.
2026-04-16 22:51:12 -04:00
ZacharyZhang-NY 4ebd98bb99 fix(automation): surface malformed condition JSON instead of silently returning false
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.
2026-04-16 22:51:00 -04:00
ZacharyZhang-NY 6b391887c3 fix(connector-auth): emit .bat file on Windows instead of '&'-chained script 2026-04-16 22:50:56 -04:00
ZacharyZhang-NY 43a03aa5e9 refactor(db): collapse three markRead variants into markMessageReadForReader (P1-16) 2026-04-16 22:50:40 -04:00
ZacharyZhang-NY 62050c9c05 refactor(automation): use JSON-stringified execution keys
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.
2026-04-16 22:50:38 -04:00
ZacharyZhang-NY 2050c0e8fd fix(notification-service): track latest section for batch summary 2026-04-16 22:50:09 -04:00
ZacharyZhang-NY 4ed1e47c32 refactor(desktop-shell-menu): drop dead '?? ""' defense in openPath 2026-04-16 22:49:41 -04:00
ZacharyZhang-NY 1ccf31f6d7 refactor(app-lifecycle): invert window-all-closed for clearer macOS intent 2026-04-16 22:49:30 -04:00
ZacharyZhang-NY 2eb6cb2c06 fix(db): move active runs query into deleteTask transaction (P1-12 TOCTOU) 2026-04-16 22:49:22 -04:00
ZacharyZhang-NY 9874d825b6 refactor(api-server): move agents-standup SQL into db domain methods
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.
2026-04-16 22:39:43 -04:00
ZacharyZhang-NY 4342cf3e2f refactor(api-server): move approvals SQL into db.approvals domain methods
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).
2026-04-16 22:38:05 -04:00
ZacharyZhang-NY 28296b3d5f refactor(api-server): move agents SQL into db.agents/db.activity/db.approvals methods
Replace seven inline queryAll calls in routes-agents.ts with typed
domain methods. db.agents gains listAgentsForApi, listAgentsForStandup,
listExistingAgentsForHireCheck. db.tasks gains listTasksForStandup.
db.approvals gains listApprovalsForStandup and
listPendingHireApprovalPayloads. db.activity gains listRecentTaskComments
(safe on empty taskIds). All HTTP response projections stay identical.
2026-04-16 22:37:10 -04:00
ZacharyZhang-NY efb9fdb8cc refactor(api-server): move work-graph SQL into db domain methods
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.
2026-04-16 22:34:46 -04:00
ZacharyZhang-NY 2be1bd1612 refactor(api-server): move misc SQL into db.knowledge domain method
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.
2026-04-16 22:32:25 -04:00
ZacharyZhang-NY de02351168 refactor(api-server): move meetings SQL into db.knowledge domain methods
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.
2026-04-16 22:32:01 -04:00
ZacharyZhang-NY 79e57567b2 refactor(api-server): move files SQL into db.documents domain methods
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.
2026-04-16 22:30:39 -04:00
ZacharyZhang-NY 7f097e3319 refactor(api-server): move tasks SQL into db.tasks/db.documents domain methods
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.
2026-04-16 22:29:36 -04:00
ZacharyZhang-NY 18bcd0abfc refactor(api-server): extract IMPORTANT_DOC_TYPES constant
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.
2026-04-16 22:27:56 -04:00
ZacharyZhang-NY 466dac117d perf(api-server): scope agent standup route to caller's tasks and reports
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.
2026-04-16 22:22:36 -04:00
ZacharyZhang-NY 94a9e457ce perf(database): replace listSnapshot+JS filter with scoped SQL in getInbox
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.
2026-04-16 22:21:30 -04:00
ZacharyZhang-NY 19c575933d perf(database): replace listSnapshot+JS filter with scoped SQL in getStandupReport
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.
2026-04-16 22:20:09 -04:00
ZacharyZhang-NY 8f7054630b fix(heartbeat): atomic find-or-create + checkout to eliminate duplicate task race
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.
2026-04-16 22:19:42 -04:00
ZacharyZhang-NY 659a2026de perf(database): replace listSnapshot+JS filter with scoped SQL in getCompanyMetrics
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.
2026-04-16 22:18:52 -04:00
ZacharyZhang-NY 47731f61a0 perf(database): scope listSnapshot table reads to current company
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.
2026-04-16 22:17:46 -04:00
ZacharyZhang-NY cc02b45864 refactor(worker): split god-handler into per-message type files
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.
2026-04-16 22:04:37 -04:00
ZacharyZhang-NY d0c6d1f6d0 perf(db): resolve chain of command in a single recursive CTE to eliminate N+1 queries 2026-04-16 21:59:18 -04:00
ZacharyZhang-NY 8cf6be05bb fix(skills): enforce per-file and aggregate size caps for imported SKILL.md content 2026-04-16 21:58:32 -04:00
ZacharyZhang-NY c81d72fb9c fix(api-server): SSE stream pulls incremental events via seq cursor
Replace per-poll 5000-row scan + JS filter with indexed WHERE seq > ?
query (uses idx_run_events_run). Batch up to 500 per call, drain loop
on reconnect. Poll interval raised 500ms -> 1000ms.
2026-04-16 21:57:35 -04:00