Skip to content

Agents v1 (2/17): Database migration and definition store for agent definitions and runs #2801

Closed

Description

@propr-dev

Context

Issue 1 defined the Agents contract in @propr/shared. This issue adds durable storage: one table for saved agent definitions and one for agent runs, plus a core data-access module for definitions (agentDefinitionStore). Run storage and its state machine come in issue 3 so each PR stays reviewable.

An agent run is executed as an ordinary isolated task run (the existing tasks / task_history tables and worker pipeline). The agent_runs row is a thin receipt that links the definition, the trigger and the produced report to the underlying task IDs (report_task_id, action_task_id). We never duplicate task execution state here.

Requirements

  1. New Knex migration packages/core/src/db/migrations/20261006000000_create_agent_definitions.js creating:
    • agent_definitions: id (uuid PK), owner_id, name, description, repositories (JSON text), prompt, attachments (JSON text), agent_alias, model_name, capabilities (JSON text), include_previous_reports (bool, default true), previous_reports_limit (int, default 1), schedule_cron (nullable), schedule_timezone (default 'UTC'), schedule_enabled (bool, default false), next_run_at (bigint ms, nullable), autonomy_mode, enabled (bool, default true), revision (int, default 0), created_at, updated_at (bigint ms). Indexes: (owner_id, updated_at), (schedule_enabled, enabled, next_run_at) for the scheduler sweep.
    • agent_runs: id (uuid PK), definition_id (FK → agent_definitions, cascade delete), owner_id, trigger, trigger_source, idempotency_key (nullable), state, autonomy_mode (snapshot), definition_snapshot (JSON text — the definition as it was when triggered), report_task_id, action_task_id, report (text), report_truncated (bool), action_summary, skip_reason, failure_reason, approved_by, deferred_until (bigint, nullable), deferrals (int, default 0), created_at, started_at, reported_at, finished_at, updated_at. Unique (definition_id, idempotency_key); indexes (definition_id, created_at), (owner_id, state), (state, deferred_until).
    • A matching down that drops agent_runs then agent_definitions.
  2. New packages/core/src/services/agents/agentDefinitionStore.ts with createAgentDefinition, getAgentDefinition(id, ownerId), listAgentDefinitions(ownerId, page), updateAgentDefinition(id, ownerId, patch, expectedRevision?), deleteAgentDefinition, setAgentDefinitionAttachments, and a pure rowToAgentDefinition mapper. Every function accepts an optional database: Knex (defaulting to the shared db) — the same injection pattern epicExecutionQueue uses for tests.
  3. updateAgentDefinition recomputes next_run_at with nextCronOccurrence whenever schedule or enablement changes, and uses revision for optimistic concurrency (409 on mismatch), mirroring the configRevision pattern used by MCP configuration tools.
  4. Export the store from packages/core/src/index.ts.
  5. Tests in test/agentDefinitionStore.test.ts using an in-memory SQLite db and running the migration.

Implementation Specification

  • Store JSON as text (SQLite); parse defensively in the mapper (a corrupt row must not crash list pages — fall back to empty arrays).
  • Owner scoping is enforced in the store: every read/update/delete filters by owner_id. Definitions are private to their owner in v1, like goals and plans.
  • Timestamps are epoch milliseconds (bigint), consistent with epic_execution_queues and mcp_operations.
  • A definition with scheduleEnabled=false, enabled=false or no cron has next_run_at = null, so the sweep index stays small.

Acceptance Criteria

  • npm run db:migrate applies cleanly on an existing database; rollback drops both tables.
  • Deleting a definition deletes its runs (cascade).
  • updateAgentDefinition with a stale expectedRevision throws an error with status: 409.
  • Enabling a schedule sets next_run_at to the next UTC cron occurrence; disabling clears it.
  • Another owner's definition is never returned (getAgentDefinition 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

    Two tables, one store module. Definitions and runs are separate because a run must keep a frozen definition_snapshot — editing an agent after triggering it must not change what an in-flight or historical run claims it ran with. Runs reference task IDs rather than copying execution state: the existing tasks/task_history tables remain the durable receipt for the actual isolated execution.

    Alternatives considered: storing definitions in system_configs JSON (like repos_to_monitor) — rejected because definitions are per-owner, need indexed scheduler queries (next_run_at) and cascade-delete to runs. Storing runs inside tasks — rejected because one agent run can span two tasks (report + acting) plus non-executing states (skipped/deferred/awaiting approval).

    File: packages/core/src/db/migrations/20261006000000_create_agent_definitions.js (new file)

    Why this file: Schema for the feature. Indexes are chosen for the three hot queries: the owner's list page, the scheduler's due-definition sweep, and deferred-run retry.

    /**
     * Agents: saved definitions that spawn ordinary isolated task runs, and the
     * thin receipts (agent_runs) linking each trigger to its report and tasks.
     */
    export async function up(knex) {
      await knex.schema.createTable('agent_definitions', table => {
        table.uuid('id').primary();
        table.string('owner_id', 255).notNullable();
        table.string('name', 120).notNullable();
        table.text('description');
        // JSON text: SQLite has no array type; the store parses defensively.
        table.text('repositories').notNullable();
        table.text('prompt').notNullable();
        table.text('attachments').notNullable().defaultTo('[]');
        table.string('agent_alias', 255).notNullable();
        table.string('model_name', 255).notNullable();
        table.text('capabilities').notNullable().defaultTo('[]');
        table.boolean('include_previous_reports').notNullable().defaultTo(true);
        table.integer('previous_reports_limit').notNullable().defaultTo(1);
        table.string('schedule_cron', 120);
        // v1 evaluates UTC only; the column keeps room for timezone support later.
        table.string('schedule_timezone', 64).notNullable().defaultTo('UTC');
        table.boolean('schedule_enabled').notNullable().defaultTo(false);
        table.bigInteger('next_run_at');
        table.string('autonomy_mode', 20).notNullable().defaultTo('dry_run');
        table.boolean('enabled').notNullable().defaultTo(true);
        table.integer('revision').notNullable().defaultTo(0);
        table.bigInteger('created_at').notNullable();
        table.bigInteger('updated_at').notNullable();
        table.index(['owner_id', 'updated_at']);
        // The daemon sweep reads only enabled, scheduled definitions that are due.
        table.index(['schedule_enabled', 'enabled', 'next_run_at']);
      });
    
      await knex.schema.createTable('agent_runs', table => {
        table.uuid('id').primary();
        table.uuid('definition_id').notNullable().references('id').inTable('agent_definitions').onDelete('CASCADE');
        table.string('owner_id', 255).notNullable();
        table.string('trigger', 20).notNullable();
        // Free-form caller label, e.g. "github-actions:acme/web#run-123".
        table.string('trigger_source', 255);
        // Callers retrying the trigger primitive reuse the key; the unique index makes it idempotent.
        table.string('idempotency_key', 128);
        table.string('state', 32).notNullable();
        table.string('autonomy_mode', 20).notNullable();
        // Frozen copy of the definition at trigger time: later edits never rewrite history.
        table.text('definition_snapshot').notNullable();
        table.string('report_task_id', 255);
        table.string('action_task_id', 255);
        table.text('report');
        table.boolean('report_truncated').notNullable().defaultTo(false);
        table.text('action_summary');
        table.text('skip_reason');
        table.text('failure_reason');
        table.string('approved_by', 255);
        table.bigInteger('deferred_until');
        table.integer('deferrals').notNullable().defaultTo(0);
        table.bigInteger('created_at').notNullable();
        table.bigInteger('started_at');
        table.bigInteger('reported_at');
        table.bigInteger('finished_at');
        table.bigInteger('updated_at').notNullable();
        table.unique(['definition_id', 'idempotency_key']);
        table.index(['definition_id', 'created_at']);
        table.index(['owner_id', 'state']);
        table.index(['state', 'deferred_until']);
      });
    }
    
    export async function down(knex) {
      await knex.schema.dropTableIfExists('agent_runs');
      await knex.schema.dropTableIfExists('agent_definitions');
    }

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

    Why this file: Single data-access layer for definitions. The API, MCP tools and scheduler all go through it, so owner scoping and next_run_at maintenance live in one place.

    import { randomUUID } from 'node:crypto';
    import type { Knex } from 'knex';
    import { nextCronOccurrence, type AgentDefinition, type AgentDefinitionInput, type AgentRunAttachment } from '@propr/shared';
    import { db } from '../../db/connection.js';
    
    interface AgentDefinitionRow {
      id: string; owner_id: string; name: string; description: string | null; repositories: string; prompt: string;
      attachments: string; agent_alias: string; model_name: string; capabilities: string;
      include_previous_reports: number | boolean; previous_reports_limit: number; schedule_cron: string | null;
      schedule_enabled: number | boolean; next_run_at: number | null; autonomy_mode: string; enabled: number | boolean;
      revision: number; created_at: number; updated_at: number;
    }
    
    function parseArray<T>(value: string | null | undefined): T[] {
      // A corrupt JSON column must not take down the whole list page.
      try { const parsed = JSON.parse(value ?? '[]'); return Array.isArray(parsed) ? parsed : []; } catch { return []; }
    }
    const iso = (ms: number | null) => (ms == null ? null : new Date(Number(ms)).toISOString());
    
    export function rowToAgentDefinition(row: AgentDefinitionRow): AgentDefinition {
      return {
        id: row.id, ownerId: row.owner_id, name: row.name, description: row.description ?? '',
        repositories: parseArray<string>(row.repositories), prompt: row.prompt,
        attachments: parseArray<AgentRunAttachment>(row.attachments),
        agentAlias: row.agent_alias, model: row.model_name,
        capabilities: parseArray(row.capabilities),
        includePreviousReports: Boolean(row.include_previous_reports), previousReportsLimit: Number(row.previous_reports_limit),
        schedule: row.schedule_cron, scheduleEnabled: Boolean(row.schedule_enabled),
        autonomyMode: row.autonomy_mode as AgentDefinition['autonomyMode'], enabled: Boolean(row.enabled),
        nextRunAt: iso(row.next_run_at), revision: Number(row.revision),
        createdAt: iso(row.created_at)!, updatedAt: iso(row.updated_at)!,
      };
    }
    
    /**
     * The single rule for when a definition is due. Computed on every write so the
     * scheduler sweep is a cheap indexed `next_run_at <= now` query.
     */
    export function computeNextRunAt(def: { schedule: string | null; scheduleEnabled: boolean; enabled: boolean }, now = Date.now()): number | null {
      if (!def.enabled || !def.scheduleEnabled || !def.schedule) return null;
      return nextCronOccurrence(def.schedule, new Date(now)).getTime();
    }
    
    export async function createAgentDefinition(ownerId: string, input: AgentDefinitionInput, database: Knex = db): Promise<AgentDefinition> {
      const now = Date.now();
      const enabled = input.enabled ?? true;
      const scheduleEnabled = input.scheduleEnabled ?? Boolean(input.schedule);
      const row = {
        id: randomUUID(), owner_id: ownerId, name: input.name.trim(), description: input.description ?? null,
        repositories: JSON.stringify(input.repositories), prompt: input.prompt, attachments: '[]',
        agent_alias: input.agentAlias, model_name: input.model, capabilities: JSON.stringify([...new Set(input.capabilities)]),
        include_previous_reports: input.includePreviousReports ?? true, previous_reports_limit: input.previousReportsLimit ?? 1,
        schedule_cron: input.schedule || null, schedule_enabled: scheduleEnabled,
        next_run_at: computeNextRunAt({ schedule: input.schedule || null, scheduleEnabled, enabled }, now),
        autonomy_mode: input.autonomyMode, enabled, revision: 0, created_at: now, updated_at: now,
      };
      await database('agent_definitions').insert(row);
      return rowToAgentDefinition(row as unknown as AgentDefinitionRow);
    }
    
    export async function getAgentDefinition(id: string, ownerId: string, database: Knex = db): Promise<AgentDefinition | undefined> {
      // Owner scoping lives here, not in every caller: definitions are private in v1.
      const row = await database<AgentDefinitionRow>('agent_definitions').where({ id, owner_id: ownerId }).first();
      return row ? rowToAgentDefinition(row) : undefined;
    }
    
    /** Unscoped read for trusted internal callers (scheduler, worker) that already hold the owner id. */
    export async function getAgentDefinitionById(id: string, database: Knex = db): Promise<AgentDefinition | undefined> {
      const row = await database<AgentDefinitionRow>('agent_definitions').where({ id }).first();
      return row ? rowToAgentDefinition(row) : undefined;
    }
    
    export async function listAgentDefinitions(ownerId: string, page: { offset: number; limit: number }, database: Knex = db) {
      const rows = await database<AgentDefinitionRow>('agent_definitions').where({ owner_id: ownerId })
        .orderBy('updated_at', 'desc').orderBy('id', 'desc').offset(page.offset).limit(page.limit + 1);
      return {
        definitions: rows.slice(0, page.limit).map(rowToAgentDefinition),
        nextOffset: rows.length > page.limit ? page.offset + page.limit : null,
      };
    }
    
    const PATCH_COLUMNS: Record<string, string> = {
      name: 'name', description: 'description', prompt: 'prompt', agentAlias: 'agent_alias', model: 'model_name',
      includePreviousReports: 'include_previous_reports', previousReportsLimit: 'previous_reports_limit',
      schedule: 'schedule_cron', scheduleEnabled: 'schedule_enabled', autonomyMode: 'autonomy_mode', enabled: 'enabled',
    };
    
    export async function updateAgentDefinition(
      id: string, ownerId: string, patch: Partial<AgentDefinitionInput>,
      options: { expectedRevision?: number; database?: Knex } = {},
    ): Promise<AgentDefinition> {
      const database = options.database ?? db;
      return database.transaction(async tx => {
        const current = await getAgentDefinition(id, ownerId, tx);
        if (!current) throw Object.assign(new Error('Agent not found'), { status: 404 });
        // Optimistic concurrency: two tabs editing the same agent must not silently overwrite.
        if (options.expectedRevision !== undefined && options.expectedRevision !== current.revision) {
          throw Object.assign(new Error('Agent was changed by someone else; reload and retry'), { status: 409, currentRevision: current.revision });
        }
        const update: Record<string, unknown> = { updated_at: Date.now(), revision: current.revision + 1 };
        for (const [key, column] of Object.entries(PATCH_COLUMNS)) {
          if (patch[key as keyof AgentDefinitionInput] !== undefined) update[column] = patch[key as keyof AgentDefinitionInput];
        }
        if (patch.repositories) update.repositories = JSON.stringify(patch.repositories);
        if (patch.capabilities) update.capabilities = JSON.stringify([...new Set(patch.capabilities)]);
        if (patch.schedule === '') update.schedule_cron = null;
        const merged = { ...current, ...patch, schedule: (update.schedule_cron as string | null | undefined) ?? current.schedule };
        // Recompute on every write: cheaper than reasoning about which fields affect timing.
        update.next_run_at = computeNextRunAt({ schedule: merged.schedule, scheduleEnabled: merged.scheduleEnabled, enabled: merged.enabled });
        await tx('agent_definitions').where({ id, owner_id: ownerId, revision: current.revision }).update(update);
        return (await getAgentDefinition(id, ownerId, tx))!;
      });
    }
    
    export async function setAgentDefinitionAttachments(id: string, ownerId: string, attachments: AgentRunAttachment[], database: Knex = db): Promise<void> {
      await database('agent_definitions').where({ id, owner_id: ownerId })
        .update({ attachments: JSON.stringify(attachments), updated_at: Date.now(), revision: database.raw('revision + 1') });
    }
    
    export async function deleteAgentDefinition(id: string, ownerId: string, database: Knex = db): Promise<boolean> {
      // agent_runs cascade; underlying task rows stay as ordinary task history.
      return (await database('agent_definitions').where({ id, owner_id: ownerId }).delete()) > 0;
    }

    File: packages/core/src/index.ts

    Why this file: Public surface for the API, worker and daemon.

    --- a/packages/core/src/index.ts
    +++ b/packages/core/src/index.ts
    @@
     export * from './services/taskPlanning/epicExecutionQueue.js';
    +// Agents: saved definitions that spawn ordinary isolated task runs.
    +export * from './services/agents/agentDefinitionStore.js';

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

    Why this file: Proves owner scoping, revisions, cascade and schedule maintenance against the real migration.

    import assert from 'node:assert/strict';
    import { after, test } from 'node:test';
    import knex from 'knex';
    import { closeConnection, createAgentDefinition, deleteAgentDefinition, getAgentDefinition, updateAgentDefinition } 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 database.raw('PRAGMA foreign_keys = ON');
      await up(database);
      return database;
    }
    const input = { name: 'Triage', repositories: ['acme/web'], prompt: 'Look at new bugs', agentAlias: 'claude', model: 'claude-opus-5-5', capabilities: ['repository_read' as const], autonomyMode: 'dry_run' as const };
    
    test('scopes by owner and enforces revisions', async () => {
      const database = await fixture();
      const created = await createAgentDefinition('alice', input, database);
      assert.equal(await getAgentDefinition(created.id, 'bob', database), undefined);
      const updated = await updateAgentDefinition(created.id, 'alice', { name: 'Renamed' }, { expectedRevision: 0, database });
      assert.equal(updated.revision, 1);
      await assert.rejects(updateAgentDefinition(created.id, 'alice', { name: 'Stale' }, { expectedRevision: 0, database }), (error: { status?: number }) => error.status === 409);
      await database.destroy();
    });
    
    test('maintains next_run_at and cascades runs on delete', async () => {
      const database = await fixture();
      const created = await createAgentDefinition('alice', input, database);
      assert.equal(created.nextRunAt, null);
      const scheduled = await updateAgentDefinition(created.id, 'alice', { schedule: '@daily', scheduleEnabled: true }, { database });
      assert.ok(scheduled.nextRunAt);
      const disabled = await updateAgentDefinition(created.id, 'alice', { enabled: false }, { database });
      assert.equal(disabled.nextRunAt, null);
      await database('agent_runs').insert({ id: '00000000-0000-4000-8000-000000000001', definition_id: created.id, owner_id: 'alice', trigger: 'manual', state: 'queued', autonomy_mode: 'dry_run', definition_snapshot: '{}', created_at: 1, updated_at: 1 });
      assert.equal(await deleteAgentDefinition(created.id, 'alice', database), true);
      assert.equal((await database('agent_runs').count({ count: '*' }).first())?.count, 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: 2801/claude-opus-5-5-agents-v1-2-17-database-m-20261006-1319-u63
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2801-20261006-1319-claude-opus-5-5-u63

    🔍 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