Skip to content

Agents v1 (3/17): Agent run store with guarded state machine, idempotent creation and previous-report lookup #2802

Closed

Description

@propr-dev

Context

Issue 2 created the agent_runs table. This issue adds packages/core/src/services/agents/agentRunStore.ts, the only module that writes run rows. Several processes touch a run concurrently: the API (trigger, approve/reject, cancel), the daemon (schedule and deferred retry), and the worker (report and acting phases). A guarded state machine — every transition is a compare-and-set UPDATE ... WHERE state IN (allowed) — prevents a late worker write from resurrecting a cancelled run, the same technique McpOperations uses for receipts.

This module also implements "previous reports as a first-class input": listPreviousReports(definitionId, limit, beforeRunId) returns the newest completed reports so a recurring agent can diff against last time.

Requirements

  1. createAgentRun({ definition, trigger, triggerSource, idempotencyKey, initialState }) inserts with onConflict(['definition_id','idempotency_key']).ignore() and returns { run, created }. A replay with the same key returns the existing run (created: false).
  2. transitionAgentRun(id, from: AgentRunState[], to, patch) — guarded update; returns the updated run or null if the run was no longer in an allowed state. Terminal states always set finished_at.
  3. An explicit allowed-transition table AGENT_RUN_TRANSITIONS documented in code:
    • queued → running | deferred | skipped | cancelled | failed
    • deferred → queued | skipped | cancelled
    • running → report_ready | failed | cancelled
    • report_ready → completed (dry_run) | awaiting_approval (preview) | acting (auto) | failed
    • awaiting_approval → acting | rejected | cancelled
    • acting → completed | failed | cancelled
  4. getAgentRun(id, ownerId), listAgentRuns(definitionId, ownerId, page), getAgentRunById(id) (internal), listDueDeferredRuns(now, limit).
  5. listPreviousReports(definitionId, { limit, beforeCreatedAt }) returning { runId, reportedAt, report }[] newest-first, only runs that actually produced a report (report_ready, awaiting_approval, acting, completed, rejected).
  6. rowToAgentRun mapper and export from packages/core/src/index.ts.
  7. Tests in test/agentRunStore.test.ts.

Implementation Specification

  • transitionAgentRun validates to against AGENT_RUN_TRANSITIONS for every from and throws a programming error for an illegal pair (catches mistakes in review/tests rather than at runtime).
  • report is truncated to AGENT_REPORT_MAX_CHARS on write and report_truncated set; the full agent output remains available through the underlying task's logs.
  • Deferred runs store deferred_until and increment deferrals (issue 11/12 use this).

Acceptance Criteria

  • Creating twice with the same idempotency key yields one row and created: false the second time.
  • A transition from cancelled to report_ready returns null and leaves the row unchanged.
  • listPreviousReports excludes failed/skipped runs and the current run, ordered newest first, bounded by limit.
  • Owner scoping: getAgentRun(id, 'other') returns undefined.
  • Tests pass.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    All run writes go through one guarded state machine. We chose compare-and-set SQL updates (WHERE state IN (...)) over row locks or Redis locks because SQLite serializes writes anyway, the pattern is already proven in McpOperations and taskSubmissionService, and it makes races observable (null result) rather than silent. Idempotency uses a unique (definition_id, idempotency_key) index with INSERT ... ON CONFLICT IGNORE, the same as mcp_operations, so an external caller (GitHub Action, webhook) can safely retry the trigger primitive.

    File: packages/core/src/services/agents/agentRunStore.ts (new file)

    Why this file: The one writer for agent_runs. API routes, the scheduler and the worker all call these functions, so lifecycle rules cannot diverge between processes.

    import { randomUUID } from 'node:crypto';
    import type { Knex } from 'knex';
    import {
      AGENT_REPORT_MAX_CHARS, TERMINAL_AGENT_RUN_STATES,
      type AgentDefinition, type AgentRun, type AgentRunState, type AgentRunTrigger,
    } from '@propr/shared';
    import { db } from '../../db/connection.js';
    
    /**
     * Allowed transitions. Kept as data (not scattered ifs) so a reviewer can see the
     * whole lifecycle at once and tests can assert it exhaustively.
     */
    export const AGENT_RUN_TRANSITIONS: Record<AgentRunState, readonly AgentRunState[]> = {
      queued: ['running', 'deferred', 'skipped', 'cancelled', 'failed'],
      deferred: ['queued', 'skipped', 'cancelled'],
      running: ['report_ready', 'failed', 'cancelled'],
      // dry_run → completed; preview → awaiting_approval; auto → acting.
      report_ready: ['completed', 'awaiting_approval', 'acting', 'failed'],
      awaiting_approval: ['acting', 'rejected', 'cancelled'],
      acting: ['completed', 'failed', 'cancelled'],
      completed: [], failed: [], skipped: [], rejected: [], cancelled: [],
    };
    
    const REPORTED_STATES: AgentRunState[] = ['report_ready', 'awaiting_approval', 'acting', 'completed', 'rejected'];
    
    interface AgentRunRow {
      id: string; definition_id: string; owner_id: string; trigger: string; trigger_source: string | null;
      idempotency_key: string | null; state: string; autonomy_mode: string; definition_snapshot: string;
      report_task_id: string | null; action_task_id: string | null; report: string | null; report_truncated: number | boolean;
      action_summary: string | null; skip_reason: string | null; failure_reason: string | null; approved_by: string | null;
      deferred_until: number | null; deferrals: number; created_at: number; started_at: number | null;
      reported_at: number | null; finished_at: number | null; updated_at: number;
    }
    const iso = (ms: number | null) => (ms == null ? null : new Date(Number(ms)).toISOString());
    
    export function rowToAgentRun(row: AgentRunRow): AgentRun {
      return {
        id: row.id, definitionId: row.definition_id, ownerId: row.owner_id,
        trigger: row.trigger as AgentRunTrigger, triggerSource: row.trigger_source, state: row.state as AgentRunState,
        reportTaskId: row.report_task_id, actionTaskId: row.action_task_id, report: row.report,
        reportTruncated: Boolean(row.report_truncated), actionSummary: row.action_summary,
        skipReason: row.skip_reason, failureReason: row.failure_reason,
        autonomyMode: row.autonomy_mode as AgentRun['autonomyMode'], approvedBy: row.approved_by,
        createdAt: iso(row.created_at)!, startedAt: iso(row.started_at), reportedAt: iso(row.reported_at), finishedAt: iso(row.finished_at),
      };
    }
    
    /** The frozen definition a run executes with; later edits never change a run. */
    export function runDefinitionSnapshot(row: Pick<AgentRunRow, 'definition_snapshot'>): AgentDefinition {
      return JSON.parse(row.definition_snapshot) as AgentDefinition;
    }
    
    export async function createAgentRun(input: {
      definition: AgentDefinition; trigger: AgentRunTrigger; triggerSource?: string | null;
      idempotencyKey?: string | null; initialState?: Extract<AgentRunState, 'queued' | 'skipped' | 'deferred'>;
      skipReason?: string; deferredUntil?: number;
    }, database: Knex = db): Promise<{ run: AgentRun; created: boolean }> {
      const now = Date.now();
      const id = randomUUID();
      const state = input.initialState ?? 'queued';
      const inserted = await database('agent_runs').insert({
        id, definition_id: input.definition.id, owner_id: input.definition.ownerId,
        trigger: input.trigger, trigger_source: input.triggerSource ?? null, idempotency_key: input.idempotencyKey ?? null,
        state, autonomy_mode: input.definition.autonomyMode, definition_snapshot: JSON.stringify(input.definition),
        skip_reason: input.skipReason ?? null, deferred_until: input.deferredUntil ?? null,
        created_at: now, updated_at: now, finished_at: state === 'skipped' ? now : null,
      }).onConflict(['definition_id', 'idempotency_key']).ignore().returning('id');
      if (inserted.length) return { run: (await getAgentRunById(id, database))!, created: true };
      // NULL keys never conflict in SQLite, so reaching here means a real key replay.
      const existing = await database<AgentRunRow>('agent_runs')
        .where({ definition_id: input.definition.id, idempotency_key: input.idempotencyKey }).first();
      return { run: rowToAgentRun(existing!), created: false };
    }
    
    export async function getAgentRunRowById(id: string, database: Knex = db): Promise<AgentRunRow | undefined> {
      return database<AgentRunRow>('agent_runs').where({ id }).first();
    }
    
    export async function getAgentRunById(id: string, database: Knex = db): Promise<AgentRun | undefined> {
      const row = await getAgentRunRowById(id, database);
      return row ? rowToAgentRun(row) : undefined;
    }
    
    export async function getAgentRun(id: string, ownerId: string, database: Knex = db): Promise<AgentRun | undefined> {
      const row = await database<AgentRunRow>('agent_runs').where({ id, owner_id: ownerId }).first();
      return row ? rowToAgentRun(row) : undefined;
    }
    
    export async function listAgentRuns(definitionId: string, ownerId: string, page: { offset: number; limit: number }, database: Knex = db) {
      const rows = await database<AgentRunRow>('agent_runs').where({ definition_id: definitionId, owner_id: ownerId })
        .orderBy('created_at', 'desc').orderBy('id', 'desc').offset(page.offset).limit(page.limit + 1);
      // The list omits report bodies: they can be 100 KB each; the detail endpoint returns them.
      return { runs: rows.slice(0, page.limit).map(row => ({ ...rowToAgentRun(row), report: null })), nextOffset: rows.length > page.limit ? page.offset + page.limit : null };
    }
    
    export interface AgentRunPatch {
      reportTaskId?: string; actionTaskId?: string; report?: string; actionSummary?: string;
      skipReason?: string; failureReason?: string; approvedBy?: string; deferredUntil?: number | null; incrementDeferrals?: boolean;
    }
    
    /**
     * Compare-and-set transition. Returns null when another writer moved the run
     * first (e.g. user cancelled while the worker was finishing), which callers must
     * treat as "stop, the run is no longer yours".
     */
    export async function transitionAgentRun(
      id: string, from: readonly AgentRunState[], to: AgentRunState, patch: AgentRunPatch = {}, database: Knex = db,
    ): Promise<AgentRun | null> {
      for (const state of from) {
        if (!AGENT_RUN_TRANSITIONS[state].includes(to)) throw new Error(`Illegal agent run transition ${state} -> ${to}`);
      }
      const now = Date.now();
      const update: Record<string, unknown> = { state: to, updated_at: now };
      if (to === 'running' || to === 'acting') update.started_at = database.raw('COALESCE(started_at, ?)', [now]);
      if (to === 'report_ready') update.reported_at = now;
      if (TERMINAL_AGENT_RUN_STATES.includes(to)) update.finished_at = now;
      if (patch.reportTaskId) update.report_task_id = patch.reportTaskId;
      if (patch.actionTaskId) update.action_task_id = patch.actionTaskId;
      if (patch.report !== undefined) {
        // Bound storage; the complete output stays in the task's own logs.
        update.report = patch.report.slice(0, AGENT_REPORT_MAX_CHARS);
        update.report_truncated = patch.report.length > AGENT_REPORT_MAX_CHARS;
      }
      if (patch.actionSummary !== undefined) update.action_summary = patch.actionSummary.slice(0, 20_000);
      if (patch.skipReason !== undefined) update.skip_reason = patch.skipReason;
      if (patch.failureReason !== undefined) update.failure_reason = patch.failureReason.slice(0, 2_000);
      if (patch.approvedBy !== undefined) update.approved_by = patch.approvedBy;
      if (patch.deferredUntil !== undefined) update.deferred_until = patch.deferredUntil;
      if (patch.incrementDeferrals) update.deferrals = database.raw('deferrals + 1');
      const changed = await database('agent_runs').where({ id }).whereIn('state', [...from]).update(update);
      return changed ? (await getAgentRunById(id, database))! : null;
    }
    
    export async function listDueDeferredRuns(now: number, limit: number, database: Knex = db): Promise<AgentRunRow[]> {
      return database<AgentRunRow>('agent_runs').where({ state: 'deferred' }).where('deferred_until', '<=', now)
        .orderBy('deferred_until').limit(limit);
    }
    
    /**
     * Previous reports as first-class input: newest completed reports of the same
     * definition, excluding the current run, so a recurring agent can diff instead
     * of repeating itself.
     */
    export async function listPreviousReports(
      definitionId: string, options: { limit: number; beforeCreatedAt: number; excludeRunId?: string }, database: Knex = db,
    ): Promise<Array<{ runId: string; reportedAt: string | null; report: string }>> {
      if (options.limit <= 0) return [];
      const query = database<AgentRunRow>('agent_runs').where({ definition_id: definitionId })
        .whereIn('state', REPORTED_STATES).whereNotNull('report').where('created_at', '<', options.beforeCreatedAt);
      if (options.excludeRunId) query.whereNot({ id: options.excludeRunId });
      const rows = await query.orderBy('created_at', 'desc').limit(options.limit).select('id', 'reported_at', 'report');
      return rows.map(row => ({ runId: row.id, reportedAt: iso(row.reported_at), report: row.report! }));
    }

    File: packages/core/src/index.ts

    Why this file: Expose the store to API, worker and daemon.

    --- a/packages/core/src/index.ts
    +++ b/packages/core/src/index.ts
    @@
     export * from './services/agents/agentDefinitionStore.js';
    +export * from './services/agents/agentRunStore.js';

    File: test/agentRunStore.test.ts (new file)

    Why this file: Exercises idempotency, guarded transitions and previous-report selection against the real migration.

    import assert from 'node:assert/strict';
    import { after, test } from 'node:test';
    import knex from 'knex';
    import { closeConnection, createAgentDefinition, createAgentRun, getAgentRun, listPreviousReports, transitionAgentRun } from '@propr/core';
    import { up } from '../packages/core/src/db/migrations/20261006000000_create_agent_definitions.js';
    
    after(closeConnection);
    
    async function fixture() {
      const database = knex({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
      await up(database);
      const definition = await createAgentDefinition('alice', { name: 'Research', repositories: ['acme/web'], prompt: 'Compare products', agentAlias: 'claude', model: 'claude-opus-5-5', capabilities: ['web'], autonomyMode: 'dry_run' }, database);
      return { database, definition };
    }
    
    test('trigger is idempotent per definition and key', async () => {
      const { database, definition } = await fixture();
      const first = await createAgentRun({ definition, trigger: 'api', idempotencyKey: 'gh-run-42' }, database);
      const second = await createAgentRun({ definition, trigger: 'api', idempotencyKey: 'gh-run-42' }, database);
      assert.equal(first.created, true);
      assert.equal(second.created, false);
      assert.equal(second.run.id, first.run.id);
      assert.equal(await getAgentRun(first.run.id, 'mallory', database), undefined);
      await database.destroy();
    });
    
    test('guarded transitions cannot resurrect a cancelled run', async () => {
      const { database, definition } = await fixture();
      const { run } = await createAgentRun({ definition, trigger: 'manual' }, database);
      assert.ok(await transitionAgentRun(run.id, ['queued'], 'cancelled', {}, database));
      assert.equal(await transitionAgentRun(run.id, ['running'], 'report_ready', { report: 'late' }, database), null);
      assert.throws(() => transitionAgentRun(run.id, ['completed'], 'running', {}, database));
      await database.destroy();
    });
    
    test('previous reports are newest-first and exclude failed runs', async () => {
      const { database, definition } = await fixture();
      for (const [index, outcome] of (['completed', 'failed', 'completed'] as const).entries()) {
        const { run } = await createAgentRun({ definition, trigger: 'schedule', idempotencyKey: `slot-${index}` }, database);
        await database('agent_runs').where({ id: run.id }).update({ created_at: index + 1 });
        await transitionAgentRun(run.id, ['queued'], 'running', {}, database);
        if (outcome === 'failed') await transitionAgentRun(run.id, ['running'], 'failed', {}, database);
        else {
          await transitionAgentRun(run.id, ['running'], 'report_ready', { report: `report ${index}` }, database);
          await transitionAgentRun(run.id, ['report_ready'], 'completed', {}, database);
        }
      }
      const reports = await listPreviousReports(definition.id, { limit: 5, beforeCreatedAt: 10 }, database);
      assert.deepEqual(reports.map(report => report.report), ['report 2', 'report 0']);
      await database.destroy();
    });
  2. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5-5 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5-5
    • Branch: 2802/claude-opus-5-5-agents-v1-3-17-agent-run--20261006-1344-3if
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2802-20261006-1344-claude-opus-5-5-3if

    🔍 Track Task Execution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions