Files
archie/internal/store/store.go
T
sam e0b6aa6105 feat(workflow): post line-anchored review comments with suggested fixes (#891)
* feat(workflow): post line-anchored review comments with suggested fixes

Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached
the operator only as a flat list in the PR body, so the author had to map every
finding back to its line by hand and apply mechanical fixes by hand. Now the
line-anchored findings are also posted as inline review comments, carrying a
one-click suggestion when the reviewer could state the fix.

Domain (internal/domain/workflow):
- ReviewFinding gains Suggestion; Validate rejects one on anything but a
  confirmed finding, so the agent's record_finding call is refused with
  something it can act on. Validate splits into validateAnchor /
  validateClassification / validateDisposition, which also brings it back under
  the cyclop limit the gate enforces.
- StagePostReviewComments runs after StageOpenPR in the implement workflow. It
  posts only line-anchored findings (Line > 0); a whole-file finding has no line
  to attach to and stays in the body list, which remains the complete record.
  It is best-effort: the PR is open and the body already lists every finding, so
  a failed comment is logged, never a park -- the same reasoning as OpenPR's
  existing best-effort LinkBranch call.
- The suggestion fence is gated on Verdict == confirmed where the fence is
  written, because it is a one-click apply: a wrong suggestion breaks the code
  and the author has to notice.

Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations,
type-asserted like PullRequestReader so a forge that cannot is skipped rather
than faked (NoopForge is pinned as not satisfying it). GitHub loops one
CreateComment per comment and joins the failures, so one refused anchor cannot
drop the rest; Gitea carries them on a single COMMENT-state review.

Two deliberate departures from the PRD's sketch, both recorded in it:
- The interface is batch (CreateReviewComments), not one call per comment:
  Gitea's only inline shape is one submitted review, and the set then crosses
  NATS once instead of once per finding.
- The head SHA is resolved inside each forge implementation rather than by the
  caller. The stage runs in archie-agent, which holds no forge credentials and
  has no PullRequestReader; the daemon-side forgerpc handler is the only place
  that does.

Transport (internal/forgerpc): workflow.Forger gains the method, so the agent
reaches the daemon over the new create_review_comments subject; the server
type-asserts the writer and answers an incapable forge with an error the stage
logs. This is the one proxied method whose absence on an image skew does not
park a task.

The reviewer prompt and record_finding schema ask for a suggestion on a
confirmed, mechanically fixable defect only.

Regenerating the wfextract symbol table -- the documented way a new exported
workflow symbol reaches interpreted stage plugins -- also picked up symbols that
were missing from the committed table (the Status* and Source* constants,
ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to
every wrapper afterwards, as that file's header requires.

Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new
stage logic each fail a test that names the behaviour -- dropping the
confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure
escape -- so the tests discriminate rather than passing vacuously.

* fix(build): drop the Dockerfile pin assertion

The guard fetched golangci-lint's go.mod at image build time to fail the build
when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped
on self-inflicted pin drift, but it added a network fetch and a new failure
mode to the release build, which is not where that belongs.

The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0
equals GOFUMPT_VERSION) and the comment above them still states the invariant,
so the reasoning survives without the build-time machinery. The pin change
itself reaches the agent image through the normal release path: CI rebuilds
and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only
release deliberately does not.

* feat(workflow): add the remediate workflow for PR review remediation

Implements step 5 of docs/prds/pr-review-remediation.md: a remediate
workflow that resumes the task's existing worktree onto its PR branch
(worktree.Manager.Resume, not Prepare's refresh), runs a builder agent
against the review's actionable comments, commits and pushes to the
same branch, and replies via the forge's ReplyToReview. Task.RetryCount
doubles as the remediation round counter, capped by the repo's
max_retries; the round-cap stage parks the task and posts one comment
when it's hit.

Task gains a ReviewPayload field (JSON-encoded review unit) with full
store/proto/staterpc plumbing. workflow.Forger gains Comment and
ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume
and its Dir lookup are added as an unexported optional Trees capability
rather than widening the exported interface, which is already at
golangci-lint's interfacebloat cap and is projected into wfextract's
Yaegi symbol table for repository-authored stage plugins.

The daemon-side reaction consumer that dispatches into this workflow
(subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing
per-task serialization) is tracked separately in archie-core-8li9.4.

* feat(messaging): extract standalone messaging service binary and process composition

* feat(messaging): adapt channel frontends to consume Gateway ChatContract

* feat(messaging): remove in-process channels and Router from daemon bootstrap

Telegram, email and webhook now run only in the Messaging Service, which
reaches this process through the Gateway's ChatContract. The daemon builds
no channel and no gateway.Router, so the wiring that existed only to serve
them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway,
setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the
release-announcement path helper.

The seams those paths owned move to where they can still be honoured:

- Channel ValidateConfig runs in archiemessaging.compose, which now returns
  an error, so a configured-but-invalid front-end fails the service rather
  than being dropped silently.
- The inbound rate limiter moves to the Gateway process, which owns the only
  Router and therefore the only place a per-sender budget applies to every
  channel's turns.
- The daemon's gateway readiness probe becomes a ContractProbe against the
  Gateway. It cannot observe a channel lifecycle it no longer runs, and a
  channel-count probe would have reported every daemon degraded.
- telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a
  chat turn runner actually reads.

Telegram operator features that were wired only in the daemon (/update,
release announcements, version reporting, SIGHUP reload) are not yet wired
in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting:
archie-core-8cda.6.8. The Gateway process builds no worktree manager, so
review_pr is unadvertised on every channel: archie-core-8cda.6.7.

* feat(messaging): re-wire the Telegram operator surface in the Messaging Service

setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's
own process. Each is resolved by where the fact it needs is owned, not by
where it used to be built; the decision table is in
docs/architecture/migration-decisions.md.

Wired here: /update (built from this service's own [chat.telegram] check and
install commands), the update-report relay (same sha256(bot_user)[:8] path the
daemon wrote, so a pending report is found rather than written afresh),
show_tool_calls, and /restart's config reload, which re-resolves the token and
allowlist from this service's own file and refuses a reload that resolves to
an empty token.

/version is sourced from the Gateway: ChatSnapshot gains a Version field
carrying the Gateway's rendered build block, read per call and bounded by the
dependency timeout. cmd/archie-messaging deliberately takes no version
ldflags, so it cannot report a partial upgrade as a matched one.

RunningVersions and ReleaseAnnouncements stay nil. Both need a component's
real running version, and the only versions this process can obtain are a
different binary's stamps -- reporting them would manufacture exactly the
false success the update check exists to catch, and the announcer without
parseable versions is a no-op that reads as configured. archie-core-8cda.6.9
carries the contract that unblocks them. Dangerous stays nil: no composition
has ever supplied a command authority.

Enrich is dropped from the update service: componentInstallTypeEnricher read
[nats], which this service must not decode, so the check command's own
reported install type stands.

* fix(workflow): guard inline review comments against head drift

Two findings from the review of q9au.

A comment's line numbers describe exactly one revision of the branch, but the
forge resolved the pull request's head at posting time -- after the review had
already read the worktree. A push in that window (a collaborator, a retry) meant
the findings were anchored to whatever now occupied those lines, mislabelling
instead of failing. The revision the review measured now travels with the
comment set: OpenPR records it from the same worktree read it already performs
(TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through
Forger to forgerpc, and the forge refuses the whole set once the head it reads
has moved off it -- which the best-effort stage logs, the PR body remaining the
record. An unmeasured revision posts unverified rather than dropping every
finding, so a worktree that cannot report one degrades instead of regressing.

Suggestion was documented single-line only, because GitHub applies a suggestion
fence up to its first line and a multi-line replacement would silently corrupt
the file. Only the verdict was validated, so a multi-line suggestion reached the
renderer and posted as that truncated fence. Validate now rejects an embedded
newline, which makes record_finding refuse it with feedback the model can act on
instead of the reviewer discovering the corruption later.
2026-09-19 23:37:23 +10:00

682 lines
24 KiB
Go

// Package store is archied's SQLite state: one row per task (a GitHub
// issue picked up for work), with every lifecycle transition recorded.
package store
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"unicode/utf8"
_ "modernc.org/sqlite"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/events"
)
type Store struct {
db *sql.DB
bindingsCipher BindingCipher
}
const taskSchemaVersion = 3
// OpenOption configures the store at open time.
type OpenOption func(*openOptions)
type openOptions struct {
bindingsCipher BindingCipher
}
// WithBindingCipher installs an at-rest encryption cipher for binding secrets
// (docs/prds/binding-secret-encryption.md). When omitted, binding secrets are
// persisted as plaintext -- legacy behaviour, unchanged.
func WithBindingCipher(c BindingCipher) OpenOption {
return func(o *openOptions) { o.bindingsCipher = c }
}
// Open opens (creating if needed) the SQLite database and its schema.
func Open(ctx context.Context, path string, opts ...OpenOption) (*Store, error) {
var o openOptions
for _, opt := range opts {
opt(&o)
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return nil, err
}
db, err := sql.Open("sqlite", sqliteDSN(path))
if err != nil {
return nil, err
}
db.SetMaxOpenConns(1)
if _, err := db.ExecContext(ctx, schema+eventsSchema+capturesSchema+mappingsSchema+bindingsSchema+configSnapshotSchema); err != nil {
return nil, errors.Join(fmt.Errorf("store: init schema: %w", err), db.Close())
}
if err := migrateTasks(ctx, db); err != nil {
return nil, errors.Join(fmt.Errorf("store: migrate: %w", err), db.Close())
}
return &Store{db: db, bindingsCipher: o.bindingsCipher}, nil
}
func sqliteDSN(path string) string {
separator := "?"
if strings.HasSuffix(path, "?") || strings.HasSuffix(path, "&") {
separator = ""
} else if strings.Contains(path, "?") {
separator = "&"
}
return path + separator + "_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)"
}
func migrateTasks(ctx context.Context, db *sql.DB) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
var version int
if err := tx.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&version); err != nil {
return err
}
if version > taskSchemaVersion {
return fmt.Errorf("database schema version %d is newer than supported version %d", version, taskSchemaVersion)
}
columns, err := taskColumns(ctx, tx)
if err != nil {
return err
}
bindingColumns, err := tableColumns(ctx, tx, "bindings")
if err != nil {
return err
}
// events is created by `CREATE TABLE IF NOT EXISTS` (eventsSchema), which
// is a no-op against a database that already has the table. On an existing
// archie.db this read plus the `events` arm below is therefore the ONLY
// thing that adds events.attempt; without it the first insert fails with
// `table events has no column named attempt`.
eventsColumns, err := tableColumns(ctx, tx, "events")
if err != nil {
return err
}
migrations := []struct {
table string
column string
sql string
}{
{"tasks", "watch_comment_id", `ALTER TABLE tasks ADD COLUMN watch_comment_id INTEGER NOT NULL DEFAULT 0`},
{"tasks", "retry_count", `ALTER TABLE tasks ADD COLUMN retry_count INTEGER NOT NULL DEFAULT 0`},
{"tasks", "source", `ALTER TABLE tasks ADD COLUMN source TEXT NOT NULL DEFAULT 'forge'`},
{"tasks", "identity", `ALTER TABLE tasks ADD COLUMN identity TEXT NOT NULL DEFAULT ''`},
{"tasks", "binding_id", `ALTER TABLE tasks ADD COLUMN binding_id INTEGER NOT NULL DEFAULT 0`},
{"tasks", "binding_version", `ALTER TABLE tasks ADD COLUMN binding_version INTEGER NOT NULL DEFAULT 0`},
{"tasks", "review_payload", `ALTER TABLE tasks ADD COLUMN review_payload TEXT NOT NULL DEFAULT ''`},
{"bindings", "owner", `ALTER TABLE bindings ADD COLUMN owner TEXT NOT NULL DEFAULT ''`},
{"bindings", "repo", `ALTER TABLE bindings ADD COLUMN repo TEXT NOT NULL DEFAULT ''`},
{"events", "attempt", `ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`},
}
for _, migration := range migrations {
present := columns
switch migration.table {
case "bindings":
present = bindingColumns
case "events":
present = eventsColumns
}
if present[migration.column] {
continue
}
if _, err := tx.ExecContext(ctx, migration.sql); err != nil {
return err
}
}
return finishTaskMigration(ctx, tx, columns)
}
func finishTaskMigration(ctx context.Context, tx *sql.Tx, columns map[string]bool) error {
if columns["owner"] && columns["repo"] && columns["pr_number"] {
if _, err := tx.ExecContext(ctx, `CREATE INDEX IF NOT EXISTS idx_tasks_pr ON tasks(owner, repo, pr_number)`); err != nil {
return err
}
}
if _, err := tx.ExecContext(ctx, `PRAGMA user_version = 3`); err != nil {
return err
}
return tx.Commit()
}
func taskColumns(ctx context.Context, tx *sql.Tx) (_ map[string]bool, retErr error) {
return tableColumns(ctx, tx, "tasks")
}
func tableColumns(ctx context.Context, tx *sql.Tx, table string) (_ map[string]bool, retErr error) {
rows, err := tx.QueryContext(ctx, fmt.Sprintf(`PRAGMA table_info(%s)`, table))
if err != nil {
return nil, err
}
defer func() { retErr = errors.Join(retErr, rows.Close()) }()
columns := make(map[string]bool)
for rows.Next() {
var cid, notNull, primaryKey int
var name, columnType string
var defaultValue any
if err := rows.Scan(&cid, &name, &columnType, &notNull, &defaultValue, &primaryKey); err != nil {
return nil, err
}
columns[name] = true
}
return columns, rows.Err()
}
const schema = `
CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner TEXT NOT NULL,
repo TEXT NOT NULL,
issue_number INTEGER NOT NULL,
title TEXT NOT NULL DEFAULT '',
body TEXT NOT NULL DEFAULT '',
labels TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT '` + workflow.StatusQueued + `',
workflow TEXT NOT NULL DEFAULT '',
stage TEXT NOT NULL DEFAULT '',
branch TEXT NOT NULL DEFAULT '',
plan TEXT NOT NULL DEFAULT '',
notes TEXT NOT NULL DEFAULT '',
pr_number INTEGER NOT NULL DEFAULT 0,
tokens_used INTEGER NOT NULL DEFAULT 0,
iterations INTEGER NOT NULL DEFAULT 0,
attempt INTEGER NOT NULL DEFAULT 0,
park_reason TEXT NOT NULL DEFAULT '',
watch_comment_id INTEGER NOT NULL DEFAULT 0,
retry_count INTEGER NOT NULL DEFAULT 0,
source TEXT NOT NULL DEFAULT 'forge',
identity TEXT NOT NULL DEFAULT '',
binding_id INTEGER NOT NULL DEFAULT 0,
binding_version INTEGER NOT NULL DEFAULT 0,
review_payload TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
UNIQUE(owner, repo, issue_number)
);
CREATE TABLE IF NOT EXISTS transitions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
task_id INTEGER NOT NULL,
at TEXT NOT NULL DEFAULT (datetime('now')),
from_status TEXT NOT NULL,
to_status TEXT NOT NULL,
detail TEXT NOT NULL DEFAULT ''
);
`
func (s *Store) Close() error { return s.db.Close() }
// DB exposes the underlying *sql.DB so tests outside the store
// package can drive fixtures that the public surface does not (yet)
// cover -- e.g. advancing a binding draft -> pending_approval without
// going through the operator edit flow. Production callers must NOT
// use this; the structured methods above are the contract.
func (s *Store) DB() *sql.DB { return s.db }
// OpenTest opens an in-memory SQLite store suitable for tests.
func OpenTest(t interface {
TempDir() string
Context() context.Context
},
) *Store {
s, err := Open(t.Context(), filepath.Join(t.TempDir(), "test.db"))
if err != nil {
panic(err)
}
return s
}
// EnqueueIssue inserts a new queued task for the issue; returns false if
// the issue is already tracked (the idempotency key is owner/repo/number).
// The task's Source defaults to "forge" (the SQLite column default).
// identity is the archie identity whose forge poll discovered this issue
// (empty for single-identity deployments); it scopes which identity's
// forge client, worktree manager, and config downstream processing uses.
func (s *Store) EnqueueIssue(ctx context.Context, owner, repo string, number int, title, body, labels, identity string) (bool, error) {
res, err := s.db.ExecContext(ctx, `
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, identity)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(owner, repo, issue_number) DO NOTHING`,
owner, repo, number, title, body, labels, identity)
if err != nil {
return false, err
}
n, _ := res.RowsAffected()
return n > 0, nil
}
// EnqueueChatTask inserts a new queued task with Source "chat" and no
// backing forge issue, returning the full created row (with its real
// database ID). The store allocates the synthetic issue number durably so
// multiple processes sharing the database cannot generate the same value.
// Workflow stages and daemon reconciliation must check workflow.Task.IsForgeBacked()
// before treating it as a real forge issue number.
func (s *Store) EnqueueChatTask(ctx context.Context, owner, repo, title, body, wf, identity string) (*workflow.Task, error) {
const syntheticIssueNumberBase = 1_000_000_000_000_000
row := s.db.QueryRowContext(ctx, `
INSERT INTO tasks (owner, repo, issue_number, title, body, labels, workflow, source, identity)
VALUES (?, ?, COALESCE((
SELECT MAX(issue_number) FROM tasks
WHERE owner = ? AND repo = ? AND source = 'chat'
), ?) + 1, ?, ?, 'chat', ?, 'chat', ?)
RETURNING id, owner, repo, issue_number, title, body, labels, status,
workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload, created_at, updated_at`,
owner, repo, owner, repo, syntheticIssueNumberBase-1, title, body, wf, identity)
return scanTask(row)
}
// EnqueueBindingTask enqueues a task triggered by a playbook binding
// dispatch (t2db.4 Phase B). It builds the row through EnqueueChatTask
// (so the synthetic issue-number allocator stays the single source of
// truth for chat-sourced tasks) and then stamps binding_id and
// binding_version on the new row in a second statement.
//
// A crash between the two writes leaves the task without provenance
// (binding_id == 0); the binding_dispatches ledger row written by the
// dispatch loop still records the (binding, capture, task) triple, so
// a future repair pass could backfill. This is the same
// best-effort-provenance pattern the rest of the task lifecycle uses
// for fields added after the row's primary insert.
func (s *Store) EnqueueBindingTask(ctx context.Context, owner, repo, title, body, wf, identity string, bindingID int64, bindingVersion int) (*workflow.Task, error) {
t, err := s.EnqueueChatTask(ctx, owner, repo, title, body, wf, identity)
if err != nil {
return nil, err
}
if _, err := s.db.ExecContext(ctx,
`UPDATE tasks SET binding_id=?, binding_version=? WHERE id=?`,
bindingID, bindingVersion, t.ID); err != nil {
return nil, fmt.Errorf("store: stamp binding provenance: %w", err)
}
t.BindingID = bindingID
t.BindingVersion = bindingVersion
return t, nil
}
// ClaimNext atomically moves the oldest queued task to running and
// returns it; nil when the queue is empty.
func (s *Store) ClaimNext(ctx context.Context) (*workflow.Task, error) {
row := s.db.QueryRowContext(ctx, `
UPDATE tasks SET status=?, attempt=attempt+1, updated_at=datetime('now')
WHERE id = (SELECT id FROM tasks WHERE status=? ORDER BY id LIMIT 1)
RETURNING id, owner, repo, issue_number, title, body, labels, status,
workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload, created_at, updated_at`,
workflow.StatusRunning, workflow.StatusQueued)
t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return t, err
}
func scanTask(row *sql.Row) (*workflow.Task, error) {
var t workflow.Task
err := row.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.Title, &t.Body,
&t.Labels, &t.Status, &t.Workflow, &t.Stage, &t.Branch, &t.Plan, &t.Notes,
&t.PRNumber, &t.TokensUsed, &t.Iterations, &t.Attempt, &t.ParkReason,
&t.WatchCommentID, &t.RetryCount, &t.Source, &t.Identity,
&t.BindingID, &t.BindingVersion, &t.ReviewPayload,
sqliteTime{&t.CreatedAt}, sqliteTime{&t.UpdatedAt})
if err != nil {
return nil, err
}
return &t, nil
}
// ClaimByIssue atomically claims a queued task by owner/repo/issue_number.
// Returns nil if the task is not in queued state (already claimed, parked,
// or terminal). Used by the NATS consumer path where the task was just
// inserted via EnqueueIssue and needs an immediate targeted claim.
func (s *Store) ClaimByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) {
row := s.db.QueryRowContext(ctx, `
UPDATE tasks SET status=?, attempt=attempt+1, updated_at=datetime('now')
WHERE owner=? AND repo=? AND issue_number=? AND status=?
RETURNING id, owner, repo, issue_number, title, body, labels, status,
workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload, created_at, updated_at`,
workflow.StatusRunning, owner, repo, number, workflow.StatusQueued)
t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return t, err
}
// ErrStaleTransition is returned when a guarded transition fails because
// the task's current status does not match the expected from status.
// Transition moves a task to a new status and records the audit detail. The
// from status guards the update; a mismatch returns ErrStaleTransition without
// writing an audit row. Transitioning to parked also stores detail as
// ParkReason in the same transaction. Detail used to exist only in the
// timeline, which left daemon-side parks looking reasonless in task APIs and
// the dashboard.
func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail string) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
res, err := tx.ExecContext(ctx, `
UPDATE tasks
SET status=?,
park_reason=CASE WHEN ?=? THEN ? ELSE park_reason END,
updated_at=datetime('now')
WHERE id=? AND status=?`,
to, to, workflow.StatusParked, clip(detail, 4000), taskID, from)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return ErrStaleTransition
}
_, err = tx.ExecContext(ctx,
`INSERT INTO transitions (task_id, from_status, to_status, detail) VALUES (?, ?, ?, ?)`,
taskID, from, to, clip(detail, 4000))
if err != nil {
return err
}
return tx.Commit()
}
// Update persists mutable task fields written by workflows.
func (s *Store) Update(ctx context.Context, t *workflow.Task) error {
_, err := s.db.ExecContext(ctx, `
UPDATE tasks SET workflow=?, stage=?, branch=?, plan=?, notes=?,
pr_number=?, tokens_used=?, iterations=?, park_reason=?,
watch_comment_id=?, retry_count=?, review_payload=?, updated_at=datetime('now')
WHERE id=?`,
t.Workflow, t.Stage, t.Branch, t.Plan, t.Notes,
t.PRNumber, t.TokensUsed, t.Iterations, clip(t.ParkReason, 4000),
t.WatchCommentID, t.RetryCount, t.ReviewPayload, t.ID)
return err
}
// TaskByIssue returns the task tracking an issue, or nil.
func (s *Store) TaskByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) {
row := s.db.QueryRowContext(ctx, `
SELECT id, owner, repo, issue_number, title, body, labels, status,
workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload, created_at, updated_at
FROM tasks WHERE owner=? AND repo=? AND issue_number=?`, owner, repo, number)
t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return t, err
}
// OpenTaskByPR returns the live task that owns the given pull request, or nil.
func (s *Store) OpenTaskByPR(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) {
row := s.db.QueryRowContext(ctx, `
SELECT id, owner, repo, issue_number, title, body, labels, status,
workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload, created_at, updated_at
FROM tasks
WHERE owner=? AND repo=? AND pr_number=? AND status=?`,
owner, repo, number, workflow.StatusPROpen)
t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return t, err
}
// TaskByID returns the task with the given database ID, or nil. Used by
// chat controls (/approve, /cancel) that reference a task by its real
// ID rather than a forge issue number.
func (s *Store) TaskByID(ctx context.Context, taskID int64) (*workflow.Task, error) {
row := s.db.QueryRowContext(ctx, `
SELECT id, owner, repo, issue_number, title, body, labels, status,
workflow, stage, branch, plan, notes, pr_number, tokens_used,
iterations, attempt, park_reason, watch_comment_id, retry_count,
source, identity, binding_id, binding_version, review_payload, created_at, updated_at
FROM tasks WHERE id=?`, taskID)
t, err := scanTask(row)
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return t, err
}
// Requeue puts a task back on the queue. A non-empty workflow forces it
// (the waiting_human → approved → implement handoff); empty keeps the
// task's current workflow (retrying a parked task).
// The fromStatus acts as a guard: the UPDATE only affects rows whose
// current status matches fromStatus. If no row matches, ErrStaleTransition
// is returned and no audit row is written. Both statements execute in a
// single transaction.
func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, wf string) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
res, err := tx.ExecContext(ctx, `
UPDATE tasks SET status=?,
workflow=CASE WHEN ?='' THEN workflow ELSE ? END,
stage='', park_reason='', updated_at=datetime('now')
WHERE id=? AND status=?`, workflow.StatusQueued, wf, wf, taskID, fromStatus)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return ErrStaleTransition
}
_, err = tx.ExecContext(ctx,
`INSERT INTO transitions (task_id, from_status, to_status, detail) VALUES (?, ?, ?, ?)`,
taskID, fromStatus, workflow.StatusQueued, "requeued "+wf)
if err != nil {
return err
}
return tx.Commit()
}
// RetryTask requeues a task and increments retry_count in the same guarded
// transaction. A queued task with an uncounted retry would make max_retries a
// suggestion rather than a cap.
func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, wf string) error {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
res, err := tx.ExecContext(ctx, `
UPDATE tasks SET status=?, retry_count=retry_count+1,
workflow=CASE WHEN ?='' THEN workflow ELSE ? END,
stage='', park_reason='', updated_at=datetime('now')
WHERE id=? AND status=?`, workflow.StatusQueued, wf, wf, taskID, fromStatus)
if err != nil {
return err
}
n, err := res.RowsAffected()
if err != nil {
return err
}
if n == 0 {
return ErrStaleTransition
}
if _, err := tx.ExecContext(ctx,
`INSERT INTO transitions (task_id, from_status, to_status, detail) VALUES (?, ?, ?, ?)`,
taskID, fromStatus, workflow.StatusQueued, "retried "+wf); err != nil {
return err
}
return tx.Commit()
}
// ArchiveTask removes one terminal task from the active task board. The
// expected status is part of the delete predicate so a stale browser cannot
// remove a task that has since resumed or otherwise changed state. Historical
// transition and activity rows remain as the operator audit trail.
func (s *Store) ArchiveTask(
ctx context.Context,
taskID int64,
fromStatus string,
audit events.Event,
) (int64, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer func() { _ = tx.Rollback() }()
eventID, err := insertEvent(ctx, tx, audit)
if err != nil {
return 0, err
}
res, err := tx.ExecContext(ctx, `DELETE FROM tasks WHERE id=? AND status=?`, taskID, fromStatus)
if err != nil {
return 0, err
}
n, err := res.RowsAffected()
if err != nil {
return 0, err
}
if n == 0 {
return 0, ErrStaleTransition
}
if err := tx.Commit(); err != nil {
return 0, err
}
return eventID, nil
}
// RecoverStale re-queues tasks left running by a crashed daemon.
func (s *Store) RecoverStale(ctx context.Context) (int64, error) {
res, err := s.db.ExecContext(ctx,
`UPDATE tasks SET status=?, updated_at=datetime('now') WHERE status=?`,
workflow.StatusQueued, workflow.StatusRunning)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// OpenPRs returns tasks whose PR state should be reconciled with GitHub.
//
// It carries attempt deliberately: the reconcile loop attributes pr_merged and
// pr_rejected to the attempt that opened the PR, and it reaches the state store
// over the wire, so the row must carry the value for taskProto to publish it.
// Narrowing this projection back silently sends those events out unattributed.
func (s *Store) OpenPRs(ctx context.Context) (tasks []workflow.Task, retErr error) {
rows, err := s.db.QueryContext(ctx, `
SELECT id, owner, repo, issue_number, pr_number, status, source, identity, attempt
FROM tasks WHERE status=?`, workflow.StatusPROpen)
if err != nil {
return nil, err
}
defer func() {
retErr = errors.Join(retErr, rows.Close())
}()
for rows.Next() {
var t workflow.Task
if err := rows.Scan(&t.ID, &t.Owner, &t.Repo, &t.IssueNumber, &t.PRNumber,
&t.Status, &t.Source, &t.Identity, &t.Attempt); err != nil {
return nil, err
}
tasks = append(tasks, t)
}
return tasks, rows.Err()
}
// ClearTerminalTasks deletes tasks whose status is terminal. Parked work is
// deliberately excluded because it is recoverable.
func (s *Store) ClearTerminalTasks(ctx context.Context) (int64, error) {
res, err := s.db.ExecContext(ctx,
`DELETE FROM tasks WHERE status IN (?, ?, ?, ?)`,
workflow.StatusMerged, workflow.StatusRejected, workflow.StatusDead, workflow.StatusClosedWontDo)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
func clip(s string, n int) string {
if len(s) <= n {
return s
}
// Walk forward by runes; stop when the next rune would exceed n bytes.
pos := 0
for pos < len(s) {
_, size := utf8.DecodeRuneInString(s[pos:])
if pos+size > n {
break
}
pos += size
}
return s[:pos]
}
// sqliteTime scans SQLite's TEXT datetime columns into a time.Time.
//
// The tasks table stores timestamps as TEXT via datetime('now') rather than a
// typed column, so the driver hands back a string and the standard time.Time
// scan fails. Parsing here keeps the column definition untouched -- changing
// it would need a migration over existing rows for no behavioural gain.
type sqliteTime struct{ t *time.Time }
// sqliteTimeLayout is what datetime('now') produces: UTC, no zone suffix.
const sqliteTimeLayout = "2006-01-02 15:04:05"
func (s sqliteTime) Scan(v any) error {
switch value := v.(type) {
case nil:
return nil
case time.Time:
*s.t = value.UTC()
return nil
case []byte:
return s.parse(string(value))
case string:
return s.parse(value)
default:
return fmt.Errorf("store: cannot scan %T into time", v)
}
}
func (s sqliteTime) parse(v string) error {
if v == "" {
return nil
}
// RFC3339 first: rows written by other paths may carry a zone.
for _, layout := range []string{time.RFC3339Nano, time.RFC3339, sqliteTimeLayout} {
if parsed, err := time.Parse(layout, v); err == nil {
*s.t = parsed.UTC()
return nil
}
}
return fmt.Errorf("store: unrecognised time %q", v)
}