Skip to content

Native subagent scheduling: watchers + task background mode - #16

Merged
Jaiminp007 merged 9 commits into
devfrom
codex/native-scheduled-watchers
May 12, 2026
Merged

Jaiminp007 merged 9 commits into
devfrom
codex/native-scheduled-watchers

Conversation

@Nisarg38

@Nisarg38 Nisarg38 commented May 7, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Scheduled watchers (schedule_subagent / list_subagents / stop_subagent): cron-driven monitoring subagents tied to the calling session. The watcher subagent runs finny_monitor_snapshot and only wakes the parent session on material changes, so silence = strategy is fine.
  • Task background mode: the task tool gains mode: "foreground" | "background". Background tasks track lifecycle in a new task_state table, run with interaction disabled, and stream results / blocks / errors back via cron-injected messages. Companion tools (list_tasks, task_status, stop_task) let agents inspect or cancel them.
  • Chat agent post-deploy workflow: chat now schedules a watcher right after an algorithm is deployed and treats "no action needed" as a valid response when the watcher pings.

Test plan

  • cd packages/opencode && bun run typecheck (passes locally)
  • cd packages/opencode && bun test test/tool/task.test.ts (8/8 passing locally)
  • Manual: deploy a paper-trading strategy, confirm chat schedules a watcher and the session wakes only on material moves
  • Manual: kick off a long task(mode="background") and confirm list_tasks / task_status reflect it; stop_task cancels it
  • Manual: schedule_subagent recurring watcher auto-expires after the 7-day TTL or on stop_subagent
  • Migration 20260507190000_task_run_background applies cleanly on a fresh DB

Summary by CodeRabbit

  • New Features

    • Scheduled algorithm monitoring: schedule hidden watcher subagents to periodically check algorithms and notify only on material changes; can inject findings into sessions or send OS notifications.
    • Background tasks: run long-running work concurrently and wake the conversation on completion/failure/blocking.
    • Tools: schedule/list/stop watchers, list/stop/check background tasks, and produce monitoring snapshots.
  • Improvements

    • Safer monitoring (delivery retry, rate-limited fallbacks, expiry/auto-disable on failure, run-rate estimation).
  • Documentation

    • Updated agent/tool guidance and commit/PR messaging rules.
  • Tests

    • New tests covering cron parsing, URL handling, scheduler locks, watcher/task state, and background task behavior.

Review Change Stack

Nisarg38 added 3 commits May 7, 2026 17:20
Watcher sub-agents that spawn from the main agent via a tool call,
fire on a cron cadence, inspect a single algorithm's performance,
and post findings inline into the spawning session.

Builds on the existing fork-only cron infrastructure (PR #10) plus the
upstream agent/task subagent abstraction. Adds parentSessionID +
expiresAt to Job.Schema, an Inject module for idle-gated session
delivery, three LLM-callable tools (schedule/list/stop_subagent),
and a constrained .opencode/agent/watcher.md definition.
Extend the task tool with mode="foreground|background" so subagents can
run in parallel without blocking the controller session. Background tasks
track lifecycle in a new task state table and stream results, blocks, or
errors back to the parent session via cron-injected messages. Three
companion tools (list_tasks, task_status, stop_task) let agents inspect
and cancel in-flight subagents.

Also teach the chat agent to schedule a watcher right after an algorithm
is deployed so live strategies don't run unattended, and to treat "no
action needed" as a valid response when the watcher pings.
@Nisarg38 Nisarg38 changed the title Add native scheduled monitoring subagents Native subagent scheduling: watchers + task background mode May 8, 2026
…-watchers

# Conflicts:
#	packages/opencode/src/agent/prompt/finny-build.txt
#	packages/opencode/src/agent/prompt/finny-chat.txt
#	packages/opencode/src/tool/registry.ts
@Nisarg38
Nisarg38 requested a review from Jaiminp007 May 8, 2026 05:16
@Nisarg38
Nisarg38 marked this pull request as ready for review May 8, 2026 05:48
Nisarg38 and others added 3 commits May 8, 2026 01:51
Scheduler now retries ownership every tick, so a stale Flock lock from a
hard-killed TUI self-heals within ~3 min instead of requiring a manual
rm -rf locks/. Boot sweep gates on Session.get so non-durable watchers
survive a TUI restart when the parent session still exists.

Inject.post always queues+flushes (no immediate-deliver shortcut that
could reorder relative to entries already pending). retryPending now
skips jobs already represented in the in-memory queue to avoid double
delivery on idle events. fallback() is rate-limited per pendingJobID
to once per hour so a stuck session doesn't spam OS notifications.
New Inject.shutdown() tears down the bus subscription on Scheduler.stop.

WatcherState.markPending appends instead of clobbering a prior undelivered
finding, preserving the design's "findings survive a restart" guarantee
when two ticks fire before the first delivers.

WatcherEvaluator no longer falls back to parsing the prompt text for
algorithmID/Name; the WatcherState row is the source of truth and a
missing row reports unavailable instead of silently auto-pausing on a
formatting drift. Notes regex is now multi-line tolerant.

Alpaca tradingURL helper strips a trailing /v2 or / from credential
endpoints before joining, fixing /v2/v2/account 404s when users paste
the full versioned URL into the endpoint field.

Algorithm.resolve picks the lookup by ULID shape so we don't double
round-trip to Convex on every watcher fire.

Background task tool now rejects resuming a blocked task as well as a
running one, matching user expectations.

Chat/Build prompts: drop "when an algorithm is deployed" instruction
since algorithm.status is always "draft" — agents kept refusing to
schedule watchers based on that field.

Observability: emit Convex analytics events on the full watcher and
background-task lifecycle (scheduled, fired, delivered, fallback,
paused, expired, stopped; task started/completed/blocked/failed/cancelled)
with the full finding/prompt/result/error text so dashboards can show
what users are actually doing.

Tests: scheduler-ownership (4) covers clean acquire, fresh-lock blocks,
stale-lock auto-recovery, ownership handoff after release. alpaca-data
(6) covers every endpoint suffix variant. watcher-state gains 2 tests
for markPending append vs overwrite-after-delivery. 42/42 pass.
@coderabbitai

coderabbitai Bot commented May 11, 2026 •

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 04e38096-30e1-4af9-947b-adc0856ef208

📥 Commits

Reviewing files that changed from the base of the PR and between 663ed36 and bd99e0d.

📒 Files selected for processing (1)
  • packages/opencode/src/cron/inject.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/opencode/src/cron/inject.ts

📝 Walkthrough

Walkthrough

Adds scheduled watcher subagents for monitoring trading algorithms: cron-scheduled jobs that periodically inspect performance, detect material changes via snapshot comparison, and inject findings into parent sessions when idle. Includes database tables for task/watcher state, state models, background task execution, injection system, scheduler updates with distributed ownership, and new LLM tools for scheduling/listing/stopping watchers alongside watcher agent definition and comprehensive design documentation.

Changes

Scheduled Subagents Monitoring Feature

Layer / File(s) Summary
Database Schema & Migrations
packages/opencode/migration/*
SQL migrations create task_run and watcher_state tables with required metadata, optional result fields, timestamps, and indexed foreign keys.
Task & Watcher State Models
packages/opencode/src/task/state.*, packages/opencode/src/cron/watcher-state.*
TaskState and WatcherState namespaces with CRUD operations, lifecycle transitions (queued→running→completed/blocked/failed), snapshot recording, and delivery state management (pending→delivered/notified).
Watcher Evaluation & Materiality Detection
packages/opencode/src/cron/watcher-evaluator.ts
WatcherEvaluator.evaluate validates watcher jobs, fetches algorithm and Alpaca market data, computes material changes using percentage thresholds/tolerances, records snapshots, and returns run/skip/unavailable decisions.
Injection & Delivery System
packages/opencode/src/cron/inject.ts
Inject module queues watcher findings in per-session FIFO queues, delivers via idle-gated session prompt injection, falls back to rate-limited OS notifications, manages duplicate prevention and queue expiry.
Scheduler Ownership, Lifecycle & Expiration
packages/opencode/src/cron/scheduler.ts (lines 9–147)
Scheduler uses distributed Flock-based ownership for single-TUI execution, includes boot sweep for stale jobs, handles expiration with auto-disable and analytics, and exposes test helpers.
Scheduler Watcher Execution & Findings
packages/opencode/src/cron/scheduler.ts (lines 164–294)
Scheduler delegates to WatcherEvaluator, implements skip/unavailable/run branches with failure auto-disable, posts material findings via Inject or direct notification, and records analytics.
Session Prompt Background Execution Support
packages/opencode/src/session/prompt.ts
SessionPrompt adds promptMode context for background settings, blocks disallowed tool interactions with BackgroundTaskBlockedError, implements async promptAsync with lifecycle callbacks, and extends PromptInput schema.
Background Task Execution & Lifecycle
packages/opencode/src/tool/task.ts
TaskTool supports background mode: creates task runs, calls promptAsync with lifecycle hooks, detects BLOCKED responses, finalizes state, and posts injections to parent session.
Monitoring & Snapshot Tools
packages/opencode/src/tool/monitor-snapshot.ts
MonitorSnapshotTool produces algorithm monitoring payloads with live Alpaca market/account/position data when available; includes latestBacktest helper.
Subagent Scheduling & Management Tools
packages/opencode/src/tool/schedule-subagent.ts, list-subagents.ts, stop-subagent.ts
ScheduleSubagentTool creates watcher jobs with cron parsing, run-rate thresholding (soft/hard caps), and expiry; ListSubagentsTool and StopSubagentTool manage active watchers with permission checks and analytics.
Background Task Management Tools
packages/opencode/src/tool/list-tasks.ts, task-status.ts, stop-task.ts
ListTasksTool, TaskStatusTool, StopTaskTool query and manage background task lifecycle with session-scoped filtering and JSON output.
Tool Registry & Wiring
packages/opencode/src/tool/registry.ts
ToolRegistry imports and registers new task, subagent, and monitoring tools; wires them into Effect.all and builtin tool lists.
Core Infrastructure & Utilities
packages/opencode/src/algorithm/index.ts, src/cron/alpaca-data.ts, src/cron/schedule.ts, src/cron/job.ts, src/cli/cmd/tui/worker.ts, src/task/error.ts, src/cron/index.ts, src/session/status.ts
Algorithm lookup (getById/resolve), Alpaca URL normalization, cron schedule estimation, job schema extensions (parentSessionID/recurring/durable/expiresAt), TUI scheduler lifecycle, BackgroundTaskBlockedError, cron re-exports, session status note.
Watcher Agent Definition & Prompt Updates
.opencode/agent/watcher.md, AGENTS.md, packages/opencode/src/agent/prompt/*
Read-only watcher subagent with tightly scoped permissions and strict reporting rules; updated prompt templates (finny-chat/build/research) with monitoring tool guidance and scheduling workflows.
Design Specification & Architecture Documentation
docs/superpowers/specs/2026-05-07-scheduled-subagents-design.md
Comprehensive design covering goals, architectural execution model, job schema extensions, scheduler/prompt-runner behavior, tool specifications, edge cases, testing strategy, v1 non-goals, and risks.
Unit & Integration Tests
packages/opencode/test/cron/*, packages/opencode/test/tool/task.test.ts
AlpacaData URL normalization; Schedule run-rate estimation; Scheduler ownership acquisition and stale recovery; WatcherState operations; background TaskTool execution and promptAsync test helpers.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

🐰 A watcher hops through the garden now,
Checking each algorithm with a thoughtful bow,
When changes appear, it sends a bright note,
Back to the session, a timely backstroke!
Hop, monitor, inject—the rabbit's complete.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description follows the template structure with Summary section, but missing Issue/Type/Verification/Checklist sections that are required by the template. Add missing template sections: Issue reference (Closes #), Type of change checkboxes, How did you verify section, and Checklist items (tested locally, no unrelated changes).
Docstring Coverage ⚠️ Warning Docstring coverage is 15.94% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The PR title clearly and concisely summarizes the main changes: scheduled watchers and task background mode execution.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/native-scheduled-watchers

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 8

🧹 Nitpick comments (1)
packages/opencode/src/agent/prompt/finny-chat.txt (1)

42-43: ⚡ Quick win

Avoid treating watcher silence as proof of health.

Current wording is too absolute; silence can also happen when a watcher expires/stops or delivery fails. Tightening this phrasing will reduce overconfident assistant responses.

Suggested wording tweak
-- **schedule_subagent** / **list_subagents** / **stop_subagent** — Schedule, list, and stop a watcher subagent tied to this session. The watcher only wakes you on material moves; silence means the strategy is fine.
+- **schedule_subagent** / **list_subagents** / **stop_subagent** — Schedule, list, and stop a watcher subagent tied to this session. The watcher wakes you on material moves; no ping means no material change was reported while the watcher is active.

-... The watcher only wakes this session on material moves; silence means the strategy is fine.
+... The watcher only wakes this session on material moves; no ping means no material change was reported while that watcher remains active.

Also applies to: 102-103

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/opencode/src/agent/prompt/finny-chat.txt` around lines 42 - 43, The
phrasing for the watcher commands (schedule_subagent, list_subagents,
stop_subagent) claims silence implies the strategy is fine—change it to a
cautious statement that silence does not guarantee health and may reflect
expiry, a stopped watcher, delivery failures, or missed events; update the same
wording for the other occurrence (around the list_tasks / task_status /
stop_task block) so both places explicitly note that lack of notifications is
not definitive proof of correct operation and recommend checking watcher
status/logs instead.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/opencode/src/algorithm/index.ts`:
- Around line 151-158: The resolve heuristic currently tests looksLikeULID (ULID
regex) but new IDs are generated with crypto.randomUUID(), so update the
detection to also recognize UUIDs and prefer getById for those; specifically
replace or augment the looksLikeULID check with a UUID regex (e.g. the standard
v4 UUID pattern) and if it matches return (await getById(identifier)) ?? (await
get(identifier)), otherwise fall back to the other order; touch the
looksLikeULID variable and the branch that calls getById/get so getById is used
when the identifier matches the UUID pattern generated by crypto.randomUUID().
- Around line 145-148: getById currently calls ConvexAlgorithms.getById without
enforcing tenant/user scoping and can return any user's algorithm by ID; change
it to require and validate the caller's userId (or tenantId) and call a scoped
query (e.g., add or use a ConvexAlgorithms.getByIdForUser or modify the
underlying query to filter by userId) so the returned Info is only returned when
algorithmId AND userId match; update getById signature to accept the userId (or
obtain it from request/context) and ensure the ConvexAlgorithms layer enforces
the user constraint similarly to getByName.

In `@packages/opencode/src/session/status.ts`:
- Around line 90-98: SessionStatus.get() and .list() currently call
makeRuntime(Service, defaultLayer) creating an isolated runtime and a separate
InstanceState; change them to use the application's active runtime instead of
creating a new one — either (A) accept a runtime/context or effect injection and
call runPromise from that runtime (i.e. use the existing AppRuntime or injected
runtime to run svc.get(SessionID.make(sessionID)) / svc.list()), or (B) if you
must run directly, obtain the shared InstanceState instance used by the app (the
same InstanceState returned by InstanceState.make in the main AppLayer) and pass
it into Service so the memoMap/Map<SessionID,Info> is the same; update the get
and list functions to reference the Service via the app runtime/context (or use
the shared InstanceState) rather than calling makeRuntime(Service,
defaultLayer).

In `@packages/opencode/src/task/state.sql.ts`:
- Around line 6-25: The TaskRunTable schema is missing the foreign key reference
for the id column (should match the migration), so update the id definition in
the sqliteTable call to reference SessionTable.id with matching actions; e.g.
change id: text().$type<SessionID>().primaryKey() to id:
text().$type<SessionID>().primaryKey().references(() => SessionTable.id, {
onDelete: "cascade", onUpdate: "no action" }) (ensure SessionTable is
imported/available).

In `@packages/opencode/src/task/state.ts`:
- Around line 156-157: The cancel flow doesn't clear last_error because the
update logic only writes last_error when the incoming value !== undefined;
change the update so an explicit undefined from cancel() clears the stored
last_error. Concretely, in the state update code used by cancel() (and the
sibling update paths around the blocks handling input: { status..., lastError? }
at the locations referenced), stop skipping last_error when undefined—either
check for the presence of the lastError key (hasOwnProperty) or directly assign
last_error = input.lastError so that cancel()'s lastError: undefined clears the
field. Ensure this change is applied to the same update logic used at the other
two sites (the lines described: 172-173 and 191-192).
- Around line 184-189: markRunning currently reads state with get() then writes
with update(), allowing a race where a concurrent cancel/finalizeActive sets a
terminal status that gets overwritten; make the operation atomic by performing a
conditional/compare-and-set update so the status is only changed to
Status.running if the stored status is neither terminal nor already running.
Modify markRunning to call an update method that accepts an expected previous
status (or a predicate) and only applies { status: Status.running, startedAt:
..., finishedAt: undefined } when the current status matches the expected
non-terminal state (use isTerminal to guard), returning the resulting record or
undefined on mismatch; reference functions: markRunning, get, update,
isTerminal, and the concurrent cancel/finalizeActive callers when implementing
the conditional update.

In `@packages/opencode/src/tool/stop-subagent.ts`:
- Around line 12-14: The schema refinement currently allows either jobID or name
(and silently prefers jobID when both are set) using .refine((value) =>
!!value.jobID || !!value.name, ...); change that to require exactly one by using
a strict XOR check (e.g., (Boolean(value.jobID) !== Boolean(value.name))) and
update the message to "Provide exactly one of jobID or name."; apply the same
change to the other identical refinement occurrence in this file (the block at
lines 31-35).

In `@packages/opencode/src/tool/stop-task.ts`:
- Around line 58-65: The code unconditionally logs a successful cancellation and
treats the task as cancelled even when TaskState.cancel(task.id) returns
undefined; modify the stop logic around SessionPrompt.cancel and
TaskState.cancel so you check the returned value (the cancelled variable) for a
truthy/confirmed result before calling Analytics.track or returning cancelled:
true, and only track "task.background.cancelled" and set the response as
cancelled when TaskState.cancel(task.id) actually indicates success; apply the
same guarded check to the analogous block handling the other cancellation path
(the code around lines covering 67–78) to avoid misreporting.

---

Nitpick comments:
In `@packages/opencode/src/agent/prompt/finny-chat.txt`:
- Around line 42-43: The phrasing for the watcher commands (schedule_subagent,
list_subagents, stop_subagent) claims silence implies the strategy is
fine—change it to a cautious statement that silence does not guarantee health
and may reflect expiry, a stopped watcher, delivery failures, or missed events;
update the same wording for the other occurrence (around the list_tasks /
task_status / stop_task block) so both places explicitly note that lack of
notifications is not definitive proof of correct operation and recommend
checking watcher status/logs instead.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: a36223bd-0c1c-4fd9-b2c5-30b0953c68d3

📥 Commits

Reviewing files that changed from the base of the PR and between 038728d and 9dc7d95.

⛔ Files ignored due to path filters (1)
  • bun.lock is excluded by !**/*.lock
📒 Files selected for processing (39)
  • .opencode/agent/watcher.md
  • AGENTS.md
  • docs/superpowers/specs/2026-05-07-scheduled-subagents-design.md
  • packages/opencode/migration/20260507190000_task_run_background/migration.sql
  • packages/opencode/migration/20260508120000_watcher_state/migration.sql
  • packages/opencode/src/agent/prompt/finny-build.txt
  • packages/opencode/src/agent/prompt/finny-chat.txt
  • packages/opencode/src/agent/prompt/finny-research.txt
  • packages/opencode/src/algorithm/index.ts
  • packages/opencode/src/cli/cmd/tui/worker.ts
  • packages/opencode/src/cron/alpaca-data.ts
  • packages/opencode/src/cron/index.ts
  • packages/opencode/src/cron/inject.ts
  • packages/opencode/src/cron/job.ts
  • packages/opencode/src/cron/schedule.ts
  • packages/opencode/src/cron/scheduler.ts
  • packages/opencode/src/cron/watcher-evaluator.ts
  • packages/opencode/src/cron/watcher-state.sql.ts
  • packages/opencode/src/cron/watcher-state.ts
  • packages/opencode/src/session/prompt.ts
  • packages/opencode/src/session/status.ts
  • packages/opencode/src/task/error.ts
  • packages/opencode/src/task/state.sql.ts
  • packages/opencode/src/task/state.ts
  • packages/opencode/src/tool/list-subagents.ts
  • packages/opencode/src/tool/list-tasks.ts
  • packages/opencode/src/tool/monitor-snapshot.ts
  • packages/opencode/src/tool/registry.ts
  • packages/opencode/src/tool/schedule-subagent.ts
  • packages/opencode/src/tool/stop-subagent.ts
  • packages/opencode/src/tool/stop-task.ts
  • packages/opencode/src/tool/task-status.ts
  • packages/opencode/src/tool/task.ts
  • packages/opencode/src/tool/task.txt
  • packages/opencode/test/cron/alpaca-data.test.ts
  • packages/opencode/test/cron/schedule.test.ts
  • packages/opencode/test/cron/scheduler-ownership.test.ts
  • packages/opencode/test/cron/watcher-state.test.ts
  • packages/opencode/test/tool/task.test.ts

Comment thread packages/opencode/src/session/status.ts Resolved
Comment thread packages/opencode/src/task/state.sql.ts Resolved
Comment thread packages/opencode/src/task/state.ts Resolved
Comment thread packages/opencode/src/task/state.ts Resolved
Comment thread packages/opencode/src/tool/stop-task.ts Resolved
- algorithm/index.ts: getById now drops cross-tenant rows by checking the
  returned algorithm's userId against the caller's DeviceProfile.userId,
  closing a bypass where any client could read another user's algorithm by
  ID. resolve heuristic updated to match the UUIDv4 shape produced by
  crypto.randomUUID() (kept ULID branch for legacy rows).
- session/status.ts: removed the static get()/list() helpers that built a
  separate ManagedRuntime via makeRuntime(Service, defaultLayer). That
  composition produced a different Layer instance than AppLayer, so the
  underlying InstanceState Map was always empty for callers — reads never
  reflected app-runtime state.
- cron/inject.ts: now tracks session status locally from the bus
  SessionStatus.Event.Status subscription instead of querying the removed
  helper. Unknown sessions default to idle (preserves prior semantics);
  flush reads the local map.
- task/state.sql.ts: added the missing references(SessionTable.id, onDelete:
  "cascade") on the id column so the Drizzle schema matches the migration
  SQL (which already had the FK).
- task/state.ts: markRunning now performs the compare-and-set inside a
  Database.transaction so a concurrent finalizeActive cannot land a
  terminal status between the read and the write. finalizeActive uses
  "in" presence checks for resultSummary/lastError so cancel() can clear
  the stored last_error by passing null (previously undefined was skipped
  and stale errors persisted).
- tool/stop-subagent.ts: schema refinement now requires exactly one of
  jobID xor name; previously both were accepted with jobID silently
  winning, which could stop the wrong watcher.
- tool/stop-task.ts: only emits the cancelled analytics event and reports
  cancelled:true when TaskState.cancel actually returns a row. If the
  row vanished between get() and the transaction, returns the latest
  state with cancelled:false instead of misreporting.
- agent/prompt/finny-chat.txt: softened "silence means the strategy is
  fine" wording in both monitoring sections to acknowledge that no ping
  can also mean a stopped/expired watcher or a delivery failure, and
  point the agent at list_subagents when the user is worried.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
packages/opencode/src/task/state.ts (1)

94-130: 💤 Low value

Consider defensive handling for the post-transaction assertion.

Line 129 uses ! to assert the record exists after the upsert transaction. While this should always succeed if the transaction commits, if an unexpected error occurs between the transaction and the get(), the assertion will throw an unclear TypeError instead of returning undefined.

♻️ Optional: Add defensive null check
    })
-   return (await get(input.id))!
+   const result = await get(input.id)
+   if (!result) {
+     throw new Error(`TaskRun ${input.id} disappeared after upsert`)
+   }
+   return result
  }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/opencode/src/task/state.ts` around lines 94 - 130, The upsert
function currently uses a non-null assertion on (await get(input.id))! which can
throw an unclear TypeError if the record is missing; update upsert to handle the
post-transaction result defensively by awaiting get(input.id) into a variable,
checking if it's undefined, and then either return undefined (and change the
function signature to Promise<Info | undefined>) or throw a clear, descriptive
Error (e.g., `throw new Error(\`upsert: missing TaskRun ${input.id}\`)`); modify
the function signature and callers as needed and reference the upsert, get,
CreateInput and Info symbols when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/opencode/src/cron/inject.ts`:
- Around line 27-31: The sessionStatus Map is currently defaulting unknown
sessions to idle which allows post()/flush() to inject into sessions that may be
busy; instead initialize/seed sessionStatus from the authoritative shared source
(e.g. call SessionStatus.get or equivalent shared provider) for existing
sessions at startup/subscribe time, and for sessions not yet observed fail
closed (treat as busy) until the first status event arrives; update the logic
around the sessionStatus Map usage (the Map declaration and places where post()
and flush() check session status) so they consult the seeded status and only
allow waking the parent session when the seeded/observed status is explicitly
idle.
- Around line 199-203: The current
Session.get(SessionID.make(sessionID)).catch(() => undefined) masks all errors
and treats transient DB/runtime failures as "session missing"; change this to
try/catch around Session.get in the same block (and the similar block at lines
236-239) and differentiate errors: if the caught error is a real not-found (or
whatever Session.get returns for missing sessions) then run the fallback loop
for pending, call queue.delete(sessionID), and return; if the error is any other
(transient/infrastructure) error, log it (include error details) and do NOT call
fallback or queue.delete so the items remain queued for retry. Reference:
Session.get, SessionID.make, pending, fallback, queue.delete, sessionID.
- Around line 209-220: The code removes the queued item before awaiting
deliver(sessionID, delivering), so on error the message is lost; instead, fetch
the current queue and peek the next item into delivering, call await
deliver(sessionID, delivering) first, and only after successful return shift the
item from the queue (update or delete the sessionID entry) — in the catch block
keep the queue unchanged and call
WatcherState.markDeliveryError(delivering.pendingJobID,
String(err).slice(0,250)) if pendingJobID exists; adjust logic around
queue.get(sessionID), delivering, and queue.set/delete to perform dequeuing only
on successful delivery.

---

Nitpick comments:
In `@packages/opencode/src/task/state.ts`:
- Around line 94-130: The upsert function currently uses a non-null assertion on
(await get(input.id))! which can throw an unclear TypeError if the record is
missing; update upsert to handle the post-transaction result defensively by
awaiting get(input.id) into a variable, checking if it's undefined, and then
either return undefined (and change the function signature to Promise<Info |
undefined>) or throw a clear, descriptive Error (e.g., `throw new
Error(\`upsert: missing TaskRun ${input.id}\`)`); modify the function signature
and callers as needed and reference the upsert, get, CreateInput and Info
symbols when making the change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 7051a64d-2c2c-4fa6-a202-3cf94013d67e

📥 Commits

Reviewing files that changed from the base of the PR and between 9dc7d95 and 663ed36.

📒 Files selected for processing (8)
  • packages/opencode/src/agent/prompt/finny-chat.txt
  • packages/opencode/src/algorithm/index.ts
  • packages/opencode/src/cron/inject.ts
  • packages/opencode/src/session/status.ts
  • packages/opencode/src/task/state.sql.ts
  • packages/opencode/src/task/state.ts
  • packages/opencode/src/tool/stop-subagent.ts
  • packages/opencode/src/tool/stop-task.ts
✅ Files skipped from review due to trivial changes (3)
  • packages/opencode/src/session/status.ts
  • packages/opencode/src/tool/stop-subagent.ts
  • packages/opencode/src/agent/prompt/finny-chat.txt
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/opencode/src/tool/stop-task.ts
  • packages/opencode/src/task/state.sql.ts
  • packages/opencode/src/algorithm/index.ts

Comment thread packages/opencode/src/cron/inject.ts Resolved
Comment thread packages/opencode/src/cron/inject.ts Resolved
Comment thread packages/opencode/src/cron/inject.ts Resolved
- Seed sessionStatus map from AppRuntime on first ensureSubscription.
  Previously the local map only filled from future bus events, so the
  first post/flush after subscribe could deliver into a session that
  was already busy. Subscribe first, then snapshot via AppRuntime and
  merge with "subscription wins" so events that arrive between subscribe
  and snapshot aren't overwritten by stale data.
- getStatus is now async and awaits the seed before reading, closing the
  cold-start race where unknown sessions would be treated as idle.
- Replaced Session.get(...).catch(() => undefined) with resolveSession
  which distinguishes a genuinely missing session (returns null →
  fallback to OS notification) from a transient lookup failure (throws →
  keep queue intact, retry next idle event). Previously every read error
  emitted desktop notifications and emptied the queue.
- flush() now peeks the head entry and only shifts after deliver()
  succeeds. If deliver throws, the entry stays at the front of the queue
  for the next idle event. Task-side injections have no pendingJobID
  and therefore no DB-backed retry path — losing them on a transient
  deliver failure would be unrecoverable.
@Jaiminp007
Jaiminp007 merged commit 1e515bc into dev May 12, 2026
1 check passed
spandanniroula pushed a commit to spandanniroula/finny that referenced this pull request Jun 12, 2026
Fixes all 17 Copilot comments:

Telemetry opt-out (polarline-markets#1, polarline-markets#2, polarline-markets#3, polarline-markets#9, polarline-markets#16):
- tracker.ts now reads FINNY_TELEMETRY=0 / OPENCODE_TELEMETRY=0 at module
  load, so the opt-out applies in every entrypoint (TUI worker, server,
  CLI), not just the bootstrap path.
- Email dialog auto-prompt and /subscribe slash command also gated on
  Analytics.isEnabled() — email POST goes to the same Convex deployment.

Tracker correctness (polarline-markets#5, polarline-markets#14, polarline-markets#17):
- drain() now also waits for the DeviceProfile.userId() resolution promise,
  not just the post-send promise.
- worker rpc.shutdown() and main-thread thread.ts both call
  Analytics.drain() before tearing down — neither beforeExit nor SIGTERM
  fire on worker.terminate() / process.exit(0).
- beforeExit handler runs at most once per process, preventing an infinite
  drain loop when a hung telemetry request later resolves and re-empties
  the loop.

Privacy (polarline-markets#10, polarline-markets#11, polarline-markets#12):
- Drop process.argv from tui.worker.booted (could include --prompt text
  and project paths).
- error.surfaced now sends only error.name; error messages frequently
  embed user prompt content and local file paths.
- Don't persist the submitted email address to local KV (no reader, just
  unnecessary PII retention).

Email dialog state machine (polarline-markets#4, polarline-markets#6, polarline-markets#8):
- Wait for kv.ready before evaluating the prompt gate so we don't re-show
  the dialog to users who already submitted/skipped.
- Conditional dismiss handler — only marks "skipped" when no terminal
  status has been set, so a successful submit isn't overwritten by the
  dismiss callback that fires on dialog.clear() and isn't suppressed by
  another dialog replacing this one.

Server-side validation (polarline-markets#15):
- subscribe mutation now rejects empty / oversized / regex-failing emails
  with a ConvexError, so the public Convex client can't bypass the TUI
  regex.

Command coverage (polarline-markets#13):
- Hook Analytics.track() in DialogCommand.trigger() instead of the bus
  event handler. trigger() is the central activation point for palette,
  slash, keybind, plugin, and bus paths — single hook, full coverage,
  no double-counting.

Comment wording (polarline-markets#7):
- bootstrap.ts: "opt-in by default" → "enabled by default" (correct
  description of opt-out semantics).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants