Skip to content

Agents v1 (4/17): Trigger primitive service and agent-run queue jobs (shared by run-now, schedule, API, MCP and CLI) #2803

Closed

Description

@propr-dev

Context

v1 supports three triggers (UI "Run now", a cron schedule, and an external API/MCP/CLI call), and they all go through one core function: triggerAgentRun. Funnelling every trigger through one function keeps validation, idempotency, repository/model checks and the cost gate (issue 11) in one place. Event-driven behavior (GitHub label, webhook, the user's own cron) is supplied by external automation calling this primitive; ProPR does not watch events in v1.

A trigger creates an agent_runs receipt (issue 3) and enqueues a BullMQ job on the existing github-issue-processor queue. Executing happens in the worker (issue 7). This issue also introduces the job payload types and the deterministic job IDs.

Requirements

  1. Add job payload types to packages/core/src/queue/taskQueue.types.ts:
    • AgentRunJobData { runId: string; definitionId: string; ownerId: string; phase: 'report' | 'action'; correlationId: string } and add it to the JobData union.
  2. New packages/core/src/services/agents/agentRunTrigger.ts exporting:
    • triggerAgentRun({ definition, trigger, triggerSource?, idempotencyKey?, gate? }, deps?) → { run, created, enqueued }.
    • enqueueAgentRunPhase(run, phase, deps?) — enqueues processAgentRun (phase report) or processAgentAction (phase action) with jobId agent-run-<runId>-<phase> so BullMQ deduplicates double-enqueues.
    • validateAgentDefinitionRuntime(definition) — checks every repository is an enabled monitored repository (loadMonitoredReposRaw) and the agent alias is enabled and supports the model (loadAgents + loadSyntheticAgents, same rule as validatePlanImplementation in packages/api/mcp/tools.ts), and that propr_mcp is only requested for supported agent types.
  3. Behavior of triggerAgentRun:
    • Disabled definition → throws { status: 409, code: 'AGENT_DISABLED' }.
    • Runtime validation failure → { status: 400, code: 'AGENT_INVALID' }.
    • Idempotent replay → returns the existing run, does not enqueue again.
    • Optional gate callback (issue 11 plugs in the cost gate) may return { action: 'skip', reason } or { action: 'defer', until, reason }; the run is then created in skipped/deferred state and not enqueued.
    • Queue failure after the row exists → transition run to failed with a clear reason and rethrow (so the caller sees a definite outcome instead of an orphaned queued row).
  4. Register the new job names in src/workerFactory.ts (MainJobProcessors.processAgentRunJob, processAgentActionJob) with temporary processors that throw Not implemented until issues 7 and 10 land — or land this together with issue 7 if the reviewer prefers. The switch must not fall into Unknown job type.
  5. Export from packages/core/src/index.ts.
  6. Tests test/agentRunTrigger.test.ts with an injected fake queue.

Implementation Specification

  • Dependencies are injectable ({ database, enqueue, loadAgents, loadSyntheticAgents, loadRepos }) like createTaskSubmissionRoutes services, so tests need no Redis.
  • Job options: attempts: 1 — an agent run is not blindly retried by BullMQ because a failure after the agent ran would re-spend tokens; recovery is an explicit new trigger.
  • Do not check GitHub user repository access here: core has no request context. The API/MCP layers do that (issues 5 and 13); the scheduler re-checks enablement at run time.

Acceptance Criteria

  • Triggering twice with one idempotency key enqueues exactly one job.
  • Triggering a definition whose repository was disabled fails with AGENT_INVALID and creates no run.
  • A gate returning defer creates a deferred run with deferred_until and enqueues nothing.
  • Enqueue failure leaves the run failed with failureReason mentioning the queue.
  • Worker dispatches processAgentRun / processAgentAction job names.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    One trigger primitive, many callers. REST "run now", the daemon scheduler, the HTTP trigger endpoint, the MCP tool and the CLI all call triggerAgentRun, so there is exactly one implementation of idempotency, validation, gating and enqueueing. Execution is decoupled through the existing BullMQ queue (github-issue-processor) and the existing main worker — we add two job names rather than a new queue/worker so concurrency limits (WORKER_CONCURRENCY), heartbeats, cancellation and task-state recovery apply automatically.

    Alternatives: a dedicated agent-runs queue — rejected because it would need its own worker, concurrency budget and recovery, i.e. a parallel execution engine, which the request explicitly forbids.

    File: packages/core/src/queue/taskQueue.types.ts

    Why this file: Job payloads are typed centrally; adding to JobData keeps the worker factory's union exhaustive.

    --- a/packages/core/src/queue/taskQueue.types.ts
    +++ b/packages/core/src/queue/taskQueue.types.ts
    @@
    +/**
    + * One phase of an Agent run. The report phase and the optional acting phase are
    + * both ordinary isolated task runs; the job only carries identities, never the
    + * definition, so the worker always reads the frozen snapshot from agent_runs.
    + */
    +export interface AgentRunJobData {
    +    runId: string;
    +    definitionId: string;
    +    ownerId: string;
    +    phase: 'report' | 'action';
    +    correlationId: string;
    +}
    +
    -export type JobData = IssueJobData | CommentJobData | TaskImportJobData | GoalJobData | SystemTaskJobData | IndexingJobData | MergeConflictJobData;
    +export type JobData = IssueJobData | CommentJobData | TaskImportJobData | GoalJobData | SystemTaskJobData | IndexingJobData | MergeConflictJobData | AgentRunJobData;

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

    Why this file: The single trigger primitive. Everything that can start a run calls it.

    import type { Knex } from 'knex';
    import { AGENT_TYPES_SUPPORTING_PROPR_MCP, type AgentDefinition, type AgentRun, type AgentRunTrigger } from '@propr/shared';
    import { db } from '../../db/connection.js';
    import { getIssueQueue } from '../../queue/taskQueue.js';
    import { loadAgents, loadMonitoredReposRaw, loadSyntheticAgents } from '../../config/configManager.js';
    import { generateCorrelationId } from '../../utils/logger.js';
    import type { AgentRunJobData } from '../../queue/taskQueue.types.js';
    import { createAgentRun, transitionAgentRun } from './agentRunStore.js';
    
    export type AgentRunGateDecision =
      | { action: 'proceed' }
      | { action: 'skip'; reason: string }
      | { action: 'defer'; until: number; reason: string };
    
    export interface AgentRunTriggerDeps {
      database?: Knex;
      enqueue?: (name: 'processAgentRun' | 'processAgentAction', data: AgentRunJobData, jobId: string) => Promise<void>;
      loadAgents?: typeof loadAgents;
      loadSyntheticAgents?: typeof loadSyntheticAgents;
      loadRepos?: typeof loadMonitoredReposRaw;
    }
    
    const defaultEnqueue: NonNullable<AgentRunTriggerDeps['enqueue']> = async (name, data, jobId) => {
      const queue = await getIssueQueue();
      // attempts: 1 — a retry after the agent already ran would silently re-spend
      // tokens. Recovery is an explicit, visible new trigger instead.
      await queue.add(name, data as never, { jobId, attempts: 1 });
    };
    
    function error(status: number, code: string, message: string): Error {
      return Object.assign(new Error(message), { status, code });
    }
    
    /**
     * Re-validated at every trigger (not only at save time) because repositories can
     * be disabled and agents/models removed after a definition was written.
     */
    export async function validateAgentDefinitionRuntime(definition: AgentDefinition, deps: AgentRunTriggerDeps = {}): Promise<void> {
      const [repos, agents, synthetic] = await Promise.all([
        (deps.loadRepos ?? loadMonitoredReposRaw)(), (deps.loadAgents ?? loadAgents)(), (deps.loadSyntheticAgents ?? loadSyntheticAgents)(),
      ]);
      for (const repository of definition.repositories) {
        if (!repos.some(repo => repo.enabled && repo.name.toLowerCase() === repository.toLowerCase())) {
          throw error(400, 'AGENT_INVALID', `Repository ${repository} is not an enabled repository on this instance`);
        }
      }
      const direct = agents.find(agent => agent.enabled && agent.alias === definition.agentAlias && agent.supportedModels.includes(definition.model));
      const pool = synthetic.find(agent => agent.enabled && agent.alias === definition.agentAlias && agent.models.some(model => model.enabled && model.id === definition.model));
      if (!direct && !pool) throw error(400, 'AGENT_INVALID', `Model ${definition.agentAlias}:${definition.model} is not an enabled model; choose one from the model catalog`);
      // The ProPR MCP must be injected at container launch; only some runtimes support that in v1.
      if (definition.capabilities.includes('propr_mcp') && (!direct || !(AGENT_TYPES_SUPPORTING_PROPR_MCP as readonly string[]).includes(direct.type))) {
        throw error(400, 'AGENT_INVALID', `The ProPR MCP capability requires a direct ${AGENT_TYPES_SUPPORTING_PROPR_MCP.join(' or ')} agent`);
      }
    }
    
    export async function enqueueAgentRunPhase(run: AgentRun, phase: 'report' | 'action', deps: AgentRunTriggerDeps = {}): Promise<void> {
      const data: AgentRunJobData = { runId: run.id, definitionId: run.definitionId, ownerId: run.ownerId, phase, correlationId: generateCorrelationId() };
      // Deterministic job id: a double enqueue (retry, race) collapses into one job.
      await (deps.enqueue ?? defaultEnqueue)(phase === 'report' ? 'processAgentRun' : 'processAgentAction', data, `agent-run-${run.id}-${phase}`);
    }
    
    export async function triggerAgentRun(input: {
      definition: AgentDefinition; trigger: AgentRunTrigger; triggerSource?: string | null; idempotencyKey?: string | null;
      gate?: (definition: AgentDefinition, trigger: AgentRunTrigger) => Promise<AgentRunGateDecision>;
    }, deps: AgentRunTriggerDeps = {}): Promise<{ run: AgentRun; created: boolean; enqueued: boolean }> {
      const database = deps.database ?? db;
      const { definition } = input;
      if (!definition.enabled) throw error(409, 'AGENT_DISABLED', 'This agent is disabled; enable it before running');
      await validateAgentDefinitionRuntime(definition, deps);
    
      // The gate runs before the row exists so a skipped/deferred run is recorded
      // with its reason, which is what the run history shows the operator.
      const decision = input.gate ? await input.gate(definition, input.trigger) : { action: 'proceed' as const };
      const { run, created } = await createAgentRun({
        definition, trigger: input.trigger, triggerSource: input.triggerSource, idempotencyKey: input.idempotencyKey,
        initialState: decision.action === 'skip' ? 'skipped' : decision.action === 'defer' ? 'deferred' : 'queued',
        skipReason: decision.action === 'proceed' ? undefined : decision.reason,
        deferredUntil: decision.action === 'defer' ? decision.until : undefined,
      }, database);
      if (!created || run.state !== 'queued') return { run, created, enqueued: false };
    
      try {
        await enqueueAgentRunPhase(run, 'report', deps);
      } catch (cause) {
        // Never leave a "queued" row that no worker will ever pick up.
        await transitionAgentRun(run.id, ['queued'], 'failed', { failureReason: `Could not queue the run: ${(cause as Error).message}` }, database);
        throw error(503, 'AGENT_QUEUE_UNAVAILABLE', 'The run was recorded but could not be queued; trigger it again');
      }
      return { run, created, enqueued: true };
    }

    File: src/workerFactory.ts

    Why this file: The main worker dispatches by job name; without these cases the worker throws Unknown job type.

    --- a/src/workerFactory.ts
    +++ b/src/workerFactory.ts
    @@
     import type {
    +    AgentRunJobData,
         CommentJobData,
    @@
    -export type MainJobData = IssueJobData | CommentJobData | GoalJobData | TaskImportJobData | SystemTaskJobData | MergeConflictJobData;
    +export type MainJobData = IssueJobData | CommentJobData | GoalJobData | TaskImportJobData | SystemTaskJobData | MergeConflictJobData | AgentRunJobData;
    @@
         processGoalJob: (job: Job<GoalJobData>) => Promise<JobResult>;
    +    // Agents: report phase and the optional acting phase (both isolated task runs).
    +    processAgentRunJob: (job: Job<AgentRunJobData>) => Promise<JobResult>;
    +    processAgentActionJob: (job: Job<AgentRunJobData>) => Promise<JobResult>;
     }
    @@
                 case 'processGoal':
                     return processors.processGoalJob(job as Job<GoalJobData>);
    +            case 'processAgentRun':
    +                return processors.processAgentRunJob(job as Job<AgentRunJobData>);
    +            case 'processAgentAction':
    +                return processors.processAgentActionJob(job as Job<AgentRunJobData>);
                 default:

    Export AgentRunJobData from packages/core/src/queue/taskQueue.ts (type re-export list) and packages/core/src/index.ts (queue types list), plus:

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

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

    Why this file: Verifies the primitive with fake config loaders and queue — no Redis needed.

    import assert from 'node:assert/strict';
    import { after, test } from 'node:test';
    import knex from 'knex';
    import { closeConnection, createAgentDefinition, triggerAgentRun } from '@propr/core';
    import { up } from '../packages/core/src/db/migrations/20261006000000_create_agent_definitions.js';
    
    after(closeConnection);
    
    async function fixture(enabledRepo = true) {
      const database = knex({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true });
      await up(database);
      const jobs: string[] = [];
      const deps = {
        database,
        enqueue: async (_name: string, _data: unknown, jobId: string) => { jobs.push(jobId); },
        loadRepos: async () => [{ id: 'r', name: 'acme/web', enabled: enabledRepo }],
        loadAgents: async () => [{ id: 'a', alias: 'claude', type: 'claude', enabled: true, supportedModels: ['claude-opus-5-5'] }],
        loadSyntheticAgents: async () => [],
      } as never;
      const definition = await createAgentDefinition('alice', { name: 'Bugs', repositories: ['acme/web'], prompt: 'Triage', agentAlias: 'claude', model: 'claude-opus-5-5', capabilities: [], autonomyMode: 'dry_run' }, database);
      return { database, deps, jobs, definition };
    }
    
    test('idempotent trigger enqueues once', async () => {
      const { database, deps, jobs, definition } = await fixture();
      await triggerAgentRun({ definition, trigger: 'api', idempotencyKey: 'k-123456' }, deps);
      const replay = await triggerAgentRun({ definition, trigger: 'api', idempotencyKey: 'k-123456' }, deps);
      assert.equal(replay.created, false);
      assert.equal(jobs.length, 1);
      await database.destroy();
    });
    
    test('disabled repository is rejected before any run exists', async () => {
      const { database, deps, definition } = await fixture(false);
      await assert.rejects(triggerAgentRun({ definition, trigger: 'manual' }, deps), (e: { code?: string }) => e.code === 'AGENT_INVALID');
      assert.equal((await database('agent_runs').count({ c: '*' }).first())?.c, 0);
      await database.destroy();
    });
    
    test('a defer decision records a deferred run without enqueueing', async () => {
      const { database, deps, jobs, definition } = await fixture();
      const result = await triggerAgentRun({ definition, trigger: 'schedule', gate: async () => ({ action: 'defer', until: Date.now() + 60_000, reason: 'Claude is at 95% usage' }) }, deps);
      assert.equal(result.run.state, 'deferred');
      assert.equal(jobs.length, 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: 2803/claude-opus-5-5-agents-v1-4-17-trigger-pr-20261006-1429-r8l
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2803-20261006-1429-claude-opus-5-5-r8l

    🔍 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