Skip to content

Agents v1 (7/17): Report-run executor — spawn an isolated task run from a definition and store the free-form report #2806

Closed

Description

@propr-dev

Context

This is the core of the feature: the worker processor that turns a queued agent_runs row into an ordinary isolated task run and stores its free-form report. No new execution engine is introduced — the executor composes the same building blocks every other job uses:

Need Existing building block
Durable receipt / task in the Tasks UI WorkerStateManager.createTaskStateIfAbsent, updateTaskState, markTaskCompleted/Failed
Sandboxed checkout ensureRepoCloned + createWorktreeForIssue + cleanupWorktree (as processTaskImportJob)
Model execution in a container AgentRegistry.getAgentByAlias(...).executeTask(...)
Spend cap RunCostGuard / runWithRunCostGuard with the instance default_max_cost_usd
Cancellation the task id is a normal task, so stopTaskExecution works

Previous reports (issue 3 lookup) and input files are fed in through the prompt builder from issue 6.

Requirements

  1. New src/jobs/processAgentRunJob.ts exporting processAgentRunJob(job: Job<AgentRunJobData>) and wire it in src/worker.ts (processors.processAgentRunJob).
  2. Flow:
    1. Load the run (getAgentRunRowById). If its state is not queued (cancelled/skipped meanwhile) return { status: 'skipped' } without side effects.
    2. Read the frozen definition_snapshot. Re-run validateAgentDefinitionRuntime; on failure transition to failed with the reason.
    3. Create the task: taskId = agent-run-<runId>-report, issueRef = { number: 0, repoOwner, repoName, type: 'agent-run', title: 'Agent: <name>', subtitle: 'Report run' } for the primary (first) repository.
    4. Transition queued → running with reportTaskId. A null result means someone cancelled → clean up and stop.
    5. Prepare the workspace (src/jobs/agentRuns/workspace.ts):
      • repository_read on: clone the primary repository and create a worktree (branch name agent-run/<runId>; never pushed). Additional repositories are cloned as shallow read-only copies into .propr/context/<owner>__<repo>/.
      • repository_read off: an empty temporary directory with git init (agents expect a git workspace) — no source code is mounted.
      • Copy input files from storage/agent-definitions/<definitionId>/ into .propr/agent-inputs/.
    6. Load previous reports (listPreviousReports(definitionId, { limit: previousReportsLimit, beforeCreatedAt, excludeRunId })), build the prompt (issue 6).
    7. Execute with agent.executeTask({ worktreePath, issueRef, prompt, model, githubToken, branchName, taskId, toolPolicy }) inside runWithRunCostGuard. toolPolicy (from capabilities) is defined in issue 8; until then pass it and let agents ignore it.
    8. Extract the report with extractAgentReport. Empty report or failed execution → failed with the agent error.
    9. Transition running → report_ready with the report, then call advanceAfterReport(run) (exported from src/jobs/agentRuns/autonomy.ts; in this issue it implements only dry_run → completed; issue 10 adds preview/auto).
    10. markTaskCompleted(taskId, { notificationRecap }) using the first line of the report.
    11. finally: remove the worktree/scratch dir. Nothing is committed or pushed.
  3. Errors: UsageLimitError → run failed with "provider usage limit reached; trigger again later" (no auto-requeue: the cost gate in issue 10 prevents most of these). Any other error → failed, task markTaskFailed.
  4. Tests test/processAgentRunJob.test.ts with injected dependencies (registry, workspace, state manager).

Implementation Specification

  • Inject dependencies via a deps parameter (createAgentRunProcessor(deps)) like handleDispatchWithDeps, so tests run without Docker/GitHub.
  • Use the GitHub App installation token (getAuthenticatedOctokit().auth({ type: 'installation' })) like other jobs; it is already read-only scoped inside agent containers (see execution-safety docs).
  • Never call any commit/push helper. The branch exists only so createWorktreeForIssue can be reused unchanged.

Acceptance Criteria

  • A queued run with repository_read produces a report_ready → completed run (dry_run) with the report stored and report_task_id pointing to a task visible in /api/tasks.
  • With repository_read off the agent workspace contains no repository files.
  • Previous reports are passed to the prompt builder (assert via injected spy).
  • A run cancelled before pickup does nothing (no task, no container).
  • Worktree is cleaned up on success and failure; no git push is ever invoked.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    The executor is a composition of existing pieces, modelled on processTaskImportJob (which already runs an agent in a temporary worktree without publishing anything). The agent_runs row stays the agent-level receipt, while the run's actual execution is a normal task (tasks/task_history), so the Tasks console, live logs, cancellation, LLM logs, spend caps and task-state recovery all work without changes.

    Dependencies are injected so the orchestration logic (state transitions, cancellation races, cleanup) is tested without Docker. Autonomy dispatch after the report lives in a separate module (autonomy.ts) so issue 10 can extend it without touching the executor.

    Trade-off: we create a throwaway branch name for the worktree only to reuse createWorktreeForIssue unchanged; it is never pushed and is deleted on cleanup.

    File: src/jobs/agentRuns/workspace.ts (new file)

    Why this file: Encapsulates the "repository code read" capability: whether the container sees source code is decided here, in one place.

    import path from 'node:path';
    import os from 'node:os';
    import fs from 'fs-extra';
    import { simpleGit } from 'simple-git';
    import {
      cleanupWorktree, createWorktreeForIssue, ensureRepoCloned, getAuthenticatedOctokit, getRepoUrl,
    } from '@propr/core';
    import type { AgentDefinition } from '@propr/shared';
    
    export interface AgentWorkspace {
      path: string;
      branchName: string;
      githubToken: string;
      repositoriesReadable: boolean;
      attachments: Array<{ originalName: string; workspacePath: string }>;
      cleanup: () => Promise<void>;
    }
    
    const ATTACHMENT_ROOT = path.join(process.cwd(), 'storage', 'agent-definitions');
    
    export async function prepareAgentWorkspace(definition: AgentDefinition, runId: string): Promise<AgentWorkspace> {
      const octokit = await getAuthenticatedOctokit();
      const { token } = await octokit.auth({ type: 'installation' }) as { token: string };
      const [primary, ...context] = definition.repositories;
      const [owner, repoName] = primary.split('/');
      const readable = definition.capabilities.includes('repository_read');
      const cleanups: Array<() => Promise<void>> = [];
      let workspacePath: string;
      let branchName = `agent-run/${runId}`;
    
      if (readable) {
        // Same isolation as every other job: a fresh worktree per run.
        const localRepoPath = await ensureRepoCloned({ repoUrl: getRepoUrl({ repoOwner: owner, repoName }), owner, repoName, authToken: token });
        const worktree = await createWorktreeForIssue(localRepoPath, { issueId: `agent-${runId}`, issueTitle: definition.name, owner, repoName }, { baseBranch: null, octokit, modelName: 'agent' });
        workspacePath = worktree.worktreePath;
        branchName = worktree.branchName;
        // deleteBranch: the branch only exists locally to satisfy worktree creation.
        cleanups.push(() => cleanupWorktree(localRepoPath, worktree.worktreePath, worktree.branchName, { deleteBranch: true, success: true }));
        for (const repository of context) {
          const [contextOwner, contextRepo] = repository.split('/');
          const contextClone = await ensureRepoCloned({ repoUrl: getRepoUrl({ repoOwner: contextOwner, repoName: contextRepo }), owner: contextOwner, repoName: contextRepo, authToken: token });
          // A local shallow clone is a cheap, read-only-by-convention snapshot inside the workspace.
          await simpleGit().clone(contextClone, path.join(workspacePath, '.propr', 'context', `${contextOwner}__${contextRepo}`), ['--depth', '1', '--no-local']);
        }
      } else {
        // No source code at all: the agent gets an empty git workspace for scratch notes.
        workspacePath = await fs.mkdtemp(path.join(os.tmpdir(), 'propr-agent-run-'));
        await simpleGit(workspacePath).init();
        cleanups.push(() => fs.remove(workspacePath));
      }
    
      const attachments = [];
      for (const file of definition.attachments) {
        const stored = (file as { storedPath?: string }).storedPath ?? path.join(ATTACHMENT_ROOT, definition.id, file.id);
        const target = path.join(workspacePath, '.propr', 'agent-inputs', path.basename(file.originalName));
        if (await fs.pathExists(stored)) {
          await fs.copy(stored, target);
          attachments.push({ originalName: file.originalName, workspacePath: path.relative(workspacePath, target) });
        }
      }
    
      return {
        path: workspacePath, branchName, githubToken: token, repositoriesReadable: readable, attachments,
        cleanup: async () => { for (const cleanup of cleanups.reverse()) await cleanup().catch(() => undefined); },
      };
    }

    File: src/jobs/agentRuns/autonomy.ts (new file)

    Why this file: One place that decides what happens after a report exists. This issue implements dry_run; issue 10 extends it to preview and auto.

    import { transitionAgentRun, type AgentRunTriggerDeps } from '@propr/core';
    import type { AgentRun } from '@propr/shared';
    
    /**
     * Autonomy = whether/when the acting step runs. Dry run: the report is the
     * result and the run is complete.
     */
    export async function advanceAfterReport(run: AgentRun, _deps: AgentRunTriggerDeps = {}): Promise<AgentRun | null> {
      if (run.autonomyMode === 'dry_run') return transitionAgentRun(run.id, ['report_ready'], 'completed');
      // preview/auto are implemented in issue 10; until then behave like dry_run so no run is stranded.
      return transitionAgentRun(run.id, ['report_ready'], 'completed');
    }

    File: src/jobs/processAgentRunJob.ts (new file)

    Why this file: Worker processor for the report phase: receipt bookkeeping around one ordinary isolated agent execution.

    import type { Job } from 'bullmq';
    import {
      AgentRegistry, getAgentRunRowById, getStateManager, listPreviousReports, logger, readRecordedTaskSpend, RunCostGuard,
      runDefinitionSnapshot, rowToAgentRun, runWithRunCostGuard, transitionAgentRun, UsageLimitError,
      validateAgentDefinitionRuntime, loadDefaultMaxCostUsd, type AgentRunJobData, type JobResult,
    } from '@propr/core';
    import { buildAgentReportPrompt, extractAgentReport } from './agentRuns/reportPrompt.js';
    import { prepareAgentWorkspace, type AgentWorkspace } from './agentRuns/workspace.js';
    import { advanceAfterReport } from './agentRuns/autonomy.js';
    import { toolPolicyForCapabilities } from './agentRuns/toolPolicy.js';
    
    export interface AgentRunProcessorDeps {
      registry?: Pick<AgentRegistry, 'ensureInitialized' | 'getAgentByAlias'>;
      prepareWorkspace?: typeof prepareAgentWorkspace;
      stateManager?: ReturnType<typeof getStateManager>;
      validateRuntime?: typeof validateAgentDefinitionRuntime;
      previousReports?: typeof listPreviousReports;
      afterReport?: typeof advanceAfterReport;
    }
    
    export function createAgentRunProcessor(deps: AgentRunProcessorDeps = {}) {
      return async function processAgentRunJob(job: Job<AgentRunJobData>): Promise<JobResult> {
        const { runId, correlationId } = job.data;
        const log = logger.withCorrelation(correlationId);
        const row = await getAgentRunRowById(runId);
        // Cancelled/skipped/duplicate delivery: the receipt already says what happened.
        if (!row || row.state !== 'queued') return { status: 'skipped', reason: `run is ${row?.state ?? 'missing'}` };
        const definition = runDefinitionSnapshot(row);
        const stateManager = deps.stateManager ?? getStateManager();
        const [repoOwner, repoName] = definition.repositories[0].split('/');
        const taskId = `agent-run-${runId}-report`;
    
        try {
          await (deps.validateRuntime ?? validateAgentDefinitionRuntime)(definition);
        } catch (error) {
          await transitionAgentRun(runId, ['queued'], 'failed', { failureReason: (error as Error).message });
          return { status: 'failed', reason: 'invalid_definition' };
        }
    
        // A normal task: visible in /tasks, stoppable, recorded in task_history and LLM logs.
        await stateManager.createTaskStateIfAbsent(taskId, { number: 0, repoOwner, repoName, type: 'agent-run', title: `Agent: ${definition.name}`, subtitle: 'Report run' } as never, correlationId, String(job.id));
        const running = await transitionAgentRun(runId, ['queued'], 'running', { reportTaskId: taskId });
        if (!running) {
          await stateManager.markTaskCancelled(taskId, 'system', { reason: 'Agent run was cancelled before it started' } as never);
          return { status: 'cancelled' };
        }
    
        let workspace: AgentWorkspace | undefined;
        try {
          const registry = deps.registry ?? AgentRegistry.getInstance();
          await registry.ensureInitialized();
          const agent = registry.getAgentByAlias(definition.agentAlias);
          if (!agent) throw new Error(`Agent ${definition.agentAlias} is not available`);
    
          workspace = await (deps.prepareWorkspace ?? prepareAgentWorkspace)(definition, runId);
          const previousReports = await (deps.previousReports ?? listPreviousReports)(definition.id, {
            limit: definition.includePreviousReports ? definition.previousReportsLimit : 0,
            beforeCreatedAt: Number(row.created_at), excludeRunId: runId,
          });
          const prompt = buildAgentReportPrompt({
            definition, previousReports, attachments: workspace.attachments,
            run: { id: runId, trigger: row.trigger, triggerSource: row.trigger_source, createdAt: new Date(Number(row.created_at)).toISOString() },
            workspace: { repositoriesReadable: workspace.repositoriesReadable, primaryRepository: definition.repositories[0], contextRepositories: definition.repositories.slice(1) },
          });
          await stateManager.updateTaskState(taskId, 'claude_execution', { reason: `${agent.config.type} agent report run started` } as never);
    
          // Same spend cap machinery as issue tasks; the instance default applies.
          const guard = new RunCostGuard({ taskId, inputs: { instanceDefault: await loadDefaultMaxCostUsd() }, defaultModel: definition.model, readRecordedSpend: () => readRecordedTaskSpend([taskId]) });
          await guard.start();
          const result = await runWithRunCostGuard(guard, () => agent.executeTask({
            worktreePath: workspace!.path, issueRef: { number: 0, repoOwner, repoName }, prompt, model: definition.model,
            githubToken: workspace!.githubToken, branchName: workspace!.branchName, taskId,
            toolPolicy: toolPolicyForCapabilities(definition.capabilities, 'report'),
          } as never)).finally(() => guard.close());
    
          const report = extractAgentReport(result);
          if (!result.success || !report) throw new Error(result.error || 'The agent finished without producing a report');
          const reported = await transitionAgentRun(runId, ['running'], 'report_ready', { report });
          if (!reported) return { status: 'cancelled' }; // cancelled while the agent ran: keep nothing
          await (deps.afterReport ?? advanceAfterReport)(reported);
          await stateManager.markTaskCompleted(taskId, { status: 'complete', notificationRecap: report.split('\n').find(Boolean)?.slice(0, 200) } as never);
          log.info({ runId, taskId, reportChars: report.length }, 'Agent report run completed');
          return { status: 'complete', runId };
        } catch (error) {
          const reason = error instanceof UsageLimitError
            ? 'The provider usage limit was reached; trigger the agent again later'
            : (error as Error).message;
          await transitionAgentRun(runId, ['running'], 'failed', { failureReason: reason });
          await stateManager.markTaskFailed(taskId, error as Error);
          log.warn({ runId, error: reason }, 'Agent report run failed');
          return { status: 'failed', runId };
        } finally {
          // Nothing is committed or pushed; the workspace is always discarded.
          await workspace?.cleanup();
        }
      };
    }
    
    export const processAgentRunJob = createAgentRunProcessor();

    Until issue 8 lands, create a stub src/jobs/agentRuns/toolPolicy.ts:

    import type { AgentCapability } from '@propr/shared';
    // Replaced by the real policy in issue 8; v1 stub passes capabilities through unchanged.
    export function toolPolicyForCapabilities(capabilities: AgentCapability[], _phase: 'report' | 'action') {
      return { allowWeb: capabilities.includes('web'), proprMcp: null };
    }

    File: src/worker.ts

    Why this file: Registers the processor with the main worker so the queue's existing concurrency, heartbeat and shutdown logic apply.

    --- a/src/worker.ts
    +++ b/src/worker.ts
    @@
     import { processGoalJob } from './jobs/processGoalJob.js';
    +import { processAgentRunJob } from './jobs/processAgentRunJob.js';
    @@
                 processGoalJob,
    +            processAgentRunJob,
    +            // Replaced by the acting processor in issue 10.
    +            processAgentActionJob: async () => ({ status: 'skipped', reason: 'acting step not enabled' }),
             },

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

    Why this file: Exercises the orchestration with fakes: happy path, cancellation race and cleanup.

    import assert from 'node:assert/strict';
    import { after, test } from 'node:test';
    import { closeConnection, createAgentDefinition, createAgentRun, db, getAgentRunById, runMigrations, transitionAgentRun } from '@propr/core';
    import { createAgentRunProcessor } from '../src/jobs/processAgentRunJob.js';
    
    after(closeConnection);
    
    function fakes(result = { success: true, summary: 'Two new bugs reported since last week.' }) {
      const calls = { cleanup: 0, prompts: [] as string[] };
      const stateManager = { createTaskStateIfAbsent: async () => null, updateTaskState: async () => null, markTaskCompleted: async () => null, markTaskFailed: async () => null, markTaskCancelled: async () => null };
      return {
        calls,
        deps: {
          stateManager: stateManager as never,
          validateRuntime: async () => undefined,
          registry: { ensureInitialized: async () => undefined, getAgentByAlias: () => ({ config: { type: 'claude' }, executeTask: async ({ prompt }: { prompt: string }) => { calls.prompts.push(prompt); return result; } }) } as never,
          prepareWorkspace: async () => ({ path: '/tmp/x', branchName: 'b', githubToken: 't', repositoriesReadable: false, attachments: [], cleanup: async () => { calls.cleanup++; } }),
          previousReports: async () => [{ runId: 'prev', reportedAt: null, report: 'One bug last week.' }],
        },
      };
    }
    
    test('stores the report, completes a dry run and cleans up', async () => {
      await runMigrations();
      const definition = await createAgentDefinition('alice', { name: 'Bugs', repositories: ['acme/web'], prompt: 'Triage', agentAlias: 'claude', model: 'claude-opus-5-5', capabilities: [], autonomyMode: 'dry_run' });
      const { run } = await createAgentRun({ definition, trigger: 'manual' });
      const { deps, calls } = fakes();
      await createAgentRunProcessor(deps)({ id: 'j', data: { runId: run.id, definitionId: definition.id, ownerId: 'alice', phase: 'report', correlationId: 'c' } } as never);
      const stored = await getAgentRunById(run.id);
      assert.equal(stored?.state, 'completed');
      assert.match(stored?.report ?? '', /Two new bugs/);
      assert.match(calls.prompts[0], /One bug last week/);
      assert.equal(calls.cleanup, 1);
      await db('agent_definitions').where({ id: definition.id }).delete();
    });
    
    test('a run cancelled before pickup does nothing', async () => {
      const definition = await createAgentDefinition('alice', { name: 'Bugs', repositories: ['acme/web'], prompt: 'Triage', agentAlias: 'claude', model: 'claude-opus-5-5', capabilities: [], autonomyMode: 'dry_run' });
      const { run } = await createAgentRun({ definition, trigger: 'manual' });
      await transitionAgentRun(run.id, ['queued'], 'cancelled');
      const { deps, calls } = fakes();
      const result = await createAgentRunProcessor(deps)({ id: 'j', data: { runId: run.id, definitionId: definition.id, ownerId: 'alice', phase: 'report', correlationId: 'c' } } as never);
      assert.equal(result.status, 'skipped');
      assert.equal(calls.prompts.length, 0);
      await db('agent_definitions').where({ id: definition.id }).delete();
    });
  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: 2806/claude-opus-5-5-agents-v1-7-17-report-run-20261006-1606-5i8
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2806-20261006-1606-claude-opus-5-5-5i8

    🔍 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