The earlier sweep cleaned the hot path (worker/runtime/automation/api-
server/ipc core — 59 sites). This pass finishes the deferred long tail:
main/* services, database/* CRUD modules, api-server/* routes, ipc-*
handlers, thread-integration, automation helpers, browser, skills.
Default strategy: catch (error) { logger.warn("[module] context:", ...) }
— preserve current behavior, make the failure visible instead of
silently hidden. Widened 3 logger interface signatures to include warn
where callers only passed info/error previously (thread-helpers,
host-environment-service, ipc-domain-common).
Legitimate boundaries left intact: JSON.parse on untrusted input, DNS
resolver no-records paths, explicit safe* helpers (safeJson, parseJson,
parseTriggerDetail), URL-parse predicates, and `<unserialisable>`
fallbacks inside the prompt-builder summarisers. Each kept catch now
either has a reason in context or is a documented safe* helper.
Tests adjusted only where test-constructed no-op loggers needed a warn
stub (message-dispatch, company-mode-switch, ipc-agent-graph-handlers).
With the earlier pass, AgentCompany no longer has silently-swallowing
catch blocks in main-process or renderer business code.
Cost was written through three independent paths: worker-runner shipped
`finalUsage.costUsd` in run-finished -> finishRun wrote `runs.cost_usd`,
`tasks.cost_usd += costUsd`, `agents.spent_monthly_usd += costUsd`, and
inserted a per-run aggregate row in cost_entries. CostWriter
additionally inserted per-message rows in cost_entries from main. Any
CostWriter failure created silent drift between `SUM(cost_entries)`
(read by budget enforcement) and `runs.cost_usd` (read by the UI).
Make CostWriter the single writer, finishRun the single reader.
- Add `db.recordCostEntry(...)` as the first-class insert path for
per-message cost rows. CostWriter calls it; tests call it directly.
- Remove the aggregate INSERT from finishRun. finishRun now reads
`SELECT COALESCE(SUM(amount_usd), 0) FROM cost_entries WHERE run_id=?
AND unattributed=0` and writes that as the authoritative run total to
runs.cost_usd, tasks.cost_usd, and agents.spent_monthly_usd.
- Drop `costUsd` from `finishRun` input, the worker `run-finished`
ChildMessage shape, the automation `RunFinishedEvent` type, and every
caller + test fixture. Cost is owned by the per-message path.
- worker-runner stops extracting `usage.cost.total` — token counts stay
for session accumulation, cost comes from pi-ai via CostWriter.
- run-finished-helpers now gates budget incident checks on
`event.status === "succeeded"` instead of a cost field that no longer
exists on the event.
- automation-run-completion fires `budget_threshold` on every succeeded
run (post-run spent_monthly_usd already reflects the SUM path).
- Update budget tests to write a `recordCostEntry` before `finishRun`
to simulate the per-message cost path; drop `costUsd` from cross-
subsystem, edge-case-budget, database, and related fixtures.
One writer, one reader, one source of truth. No drift.
Two coupled user-visible defects were fixed.
1. Every tool call (shell / edit / write / read / ...) triggered a
synchronous human-approval prompt under BOTH execution modes. The
worker blocked inside pi's beforeToolCall waiting on a DB approval
row, so runs never progressed — "等待日志输出" forever.
The execution-mode contract is now enforced:
- AI CEO → fully autonomous, no framework gate.
- AI Co-Founder → still fully autonomous at the pi layer. Human
review is a model-driven decision (LLM calls an explicit
`request_approval` tool when it judges review necessary), not
a framework-level interrupt.
HumanApprovalHook collapses to a no-op `before` / `after` /
`cancelAll`. All machinery that queued `dangerous_command`
approvals from the worker-side hook is removed. No more starving
the agent on `node -e` self-call checks.
2. The Console panel only subscribed to `run-log` stdout/stderr
chunks, so pi's agent-event stream (assistant_message_delta,
tool_call_start/end, errors, turn_end) produced zero visible
output. With bug (1) fixed, runs now execute — but the user
would still see a blank Console.
runtime-bridge.handleAgentEvent now projects each meaningful
agent-event into a run-log chunk (assistant_message_delta → raw
delta, tool_call_start → `[tool:bash] {args}`, tool_call_end →
`[tool:done|error:name] {result}`, error → stderr). ConsoleView
picks these up via the existing run-log DesktopEvent pipe with
no renderer change.
tests/unit/approval-hook.test.ts rewritten to assert the new
autonomous contract (before always returns {}, no approval rows
written, cancelAll is a no-op). Tests 508/508 pass.
typecheck 0 / lint 0-0 / build:verify 0-0.
- DB introspection tests: introduce local RawDb alias for casts
that poke into the private .db handle.
- IPC handler tests: introduce IpcHandler alias matching the
registerHandle signature (event + unknown args).
- selective-ipc / session-management: narrow handler and data
params to unknown or the minimum shape the code reads.
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.
The original tests/integration/autonomous-chain.spec.ts was ~1400 lines
and 50 KB, covering 19 describe blocks across 10 orthogonal scenarios.
Physically extract each describe (or closely related group) into its
own file inside tests/integration/autonomous-chain/ so each file stays
under the project's 500-line ceiling and failures point at the
scenario that regressed.
Shared beforeEach / afterEach / createAgent / buildCtx helpers move to
autonomous-chain/shared-setup.ts, which exposes installSharedSetup() as
a factory that each spec calls at module load. The tests themselves
are moved byte-for-byte; only module-level references (`db`,
`companyId`, `workspaceId`, `tempDirs`) are rewritten to go through
the shared handle. No assertions, it() calls, or behavior are changed.
Split layout:
role-detection.spec.ts — Step 1: CEO role detection
ceo-phased-prompts.spec.ts — Step 2: phased prompts + approvals
wakeup-queue.spec.ts — Step 3: deferred wake queue
approval-decisions.spec.ts — Step 4: hire approval decisions
task-propagation.spec.ts — Step 5: task/comment wake propagation
run-failure.spec.ts — Step 6: run failure escalation
crash-recovery.spec.ts — Step 7: worker crash recovery
wake-reason.spec.ts — Step 8: wake reason injection
e2e-flows.spec.ts — full-chain + review-fix regressions
automation-messages.spec.ts — automation/messages/assignment/workflows
Test count stays at 363 passing; typecheck stays at 156 errors.
3 code paths in desktop.smoke.spec.ts used bare `return` when fixtures
were unavailable (runtime not configured, too few model toggles), which
caused the test to silently pass without exercising the real flow.
Replace with `test.skip(true, reason)` so Playwright reports the skip
and surfaces the missing precondition.
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
- 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>
- 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