Skip to content

Agents v1 (1/17): Shared contracts for agent definitions, runs, capabilities, autonomy and cron schedules #2800

Closed

Description

@propr-dev

Context

ProPR is getting an Agents feature: a saved, reusable definition that runs on demand or on a schedule and produces a free-form report. An agent run is not a new execution engine — it is one of ProPR's existing isolated task runs (sandboxed checkout, model, tool access, durable task receipt), spawned from a saved definition. An optional, separate acting step hands the report to a second isolated run that uses the ProPR MCP tools to create tasks/TODOs/comments.

Every surface (REST API, MCP, CLI, web UI, worker, daemon scheduler) must agree on the same vocabulary, validation rules and limits. This repository already follows that pattern: packages/shared/src/goalCreation.ts is the single authoritative goal creation contract consumed by the API, MCP, UI and CLI. This first issue creates the equivalent contract for Agents, plus a tiny dependency-free cron evaluator so the scheduler (issue 12), the API (validation and "next run" preview) and the UI all compute the same next run time.

This issue contains no runtime behavior: no database, no routes. It is purely types, constants and pure functions, so it is easy to review and unblocks every following issue.

Requirements

  1. Add packages/shared/src/agentDefinitions.ts exporting:
    • AGENT_CAPABILITIES = ['repository_read', 'web', 'propr_mcp'] (each separately togglable).
    • AGENT_AUTONOMY_MODES = ['dry_run', 'preview', 'auto'].
    • AGENT_RUN_TRIGGERS = ['manual', 'schedule', 'api', 'mcp', 'cli'].
    • AGENT_RUN_STATES covering the whole lifecycle: queued, deferred, running, report_ready, awaiting_approval, acting, completed, failed, skipped, rejected, cancelled, plus TERMINAL_AGENT_RUN_STATES.
    • Interfaces AgentDefinition, AgentDefinitionInput, AgentRun, AgentRunAttachment.
    • Limits (name, description, prompt length, max repositories, max attachments, previous-report count and size).
    • validateAgentDefinitionInput(input, { partial }) returning a user-facing error string or null (same style as validateGoalCreationOptions).
    • AGENT_DEFINITION_CONTRACT — a machine-readable description for capability discovery (MCP get_agent_definition_contract, CLI help, UI).
    • isUnattendedTrigger(trigger) — schedule, api, mcp, cli are unattended; manual (UI "Run now") is attended. This drives the cost gate in issue 11.
  2. Add packages/shared/src/cronSchedule.ts exporting:
    • parseCronExpression(expr) supporting standard 5-field cron (minute hour day-of-month month day-of-week) with *, lists 1,2, ranges 1-5, steps */15 and 1-30/5, plus the macros @hourly, @daily, @weekly, @monthly.
    • nextCronOccurrence(expr, after: Date): Date — evaluated in UTC only for v1 (documented limitation; timezones are deferred).
    • MIN_AGENT_SCHEDULE_INTERVAL_MINUTES = 15 and validateAgentSchedule(expr) that rejects schedules firing more often than every 15 minutes (cost guard).
  3. Re-export both modules from packages/shared/src/index.ts.
  4. Unit tests in test/agentDefinitionsContract.test.ts (node:test) for validation and cron evaluation.

Implementation Specification

  • Follow goalCreation.ts conventions: plain functions, no dependencies, user-facing error strings.
  • Repository handles reuse the owner/repo regex already used by goals (GOAL_REPOSITORY_PATTERN).
  • propr_mcp capability is only supported on agent types that can receive an MCP server config at launch (Claude and Codex in v1); export AGENT_TYPES_SUPPORTING_PROPR_MCP so the API rejects unsupported combinations early (issue 4 validates against the live agent config).
  • The acting step (autonomy preview/auto) always runs with propr_mcp; the report step only gets it when the definition enables it. validateAgentDefinitionInput therefore does not require propr_mcp for auto.
  • Cron: brute-force minute stepping is fine and simplest to reason about; cap the search at 366 days and throw if no match (e.g. 0 0 31 2 *).

Acceptance Criteria

  • npm run build -w @propr/shared and npm run typecheck pass.
  • validateAgentDefinitionInput rejects: empty name, >10 repositories, invalid repository format, unknown capability, unknown autonomy mode, schedule more frequent than 15 minutes, malformed cron.
  • nextCronOccurrence('*/15 * * * *', 2026-10-06T10:07Z) is 10:15Z; @daily after 2026-10-06T10:00Z is 2026-10-07T00:00Z; 0 9 * * 1-5 skips weekends.
  • isUnattendedTrigger('manual') === false, all other triggers true.
  • New test file passes with node scripts/run-test-suite.mjs test/agentDefinitionsContract.test.ts.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    We define the Agents vocabulary once in @propr/shared (browser-safe, no dependencies) because five different processes need it: the API (REST + MCP validation), the worker (executor), the daemon (scheduler), the CLI and the UI. This mirrors the existing goalCreation.ts contract, which was introduced precisely so "accepted options cannot drift between entry points".

    We deliberately write a ~80-line cron evaluator instead of adding cron-parser: the shared package has zero dependencies and is bundled into the UI, the feature only needs UTC 5-field cron, and a brute-force minute search is trivially correct and testable. Alternatives considered: (a) a library — rejected for bundle/dependency surface; (b) "every N minutes" intervals only — rejected because the request explicitly asks for a "basic cron-like schedule".

    Key trade-off: v1 evaluates cron in UTC only. Timezone support is a natural follow-up and the stored column (schedule_timezone, issue 2) leaves room for it.

    File: packages/shared/src/agentDefinitions.ts (new file)

    Why this file: Single source of truth for Agents. Every later issue imports from here so the REST route, MCP schema, CLI parser and UI form validate identically.

    /**
     * Authoritative Agents contract shared by the API, MCP, worker, daemon, CLI and UI.
     * An Agent is a saved definition that spawns ordinary isolated task runs; this
     * module only describes and validates that definition, it never executes anything.
     */
    import { GOAL_REPOSITORY_PATTERN } from './goalCreation.js';
    import { validateAgentSchedule } from './cronSchedule.js';
    
    // Each capability is independently togglable so an operator can, for example,
    // allow market research (web) without granting repository code access.
    export const AGENT_CAPABILITIES = ['repository_read', 'web', 'propr_mcp'] as const;
    export type AgentCapability = typeof AGENT_CAPABILITIES[number];
    
    // One mechanism, three modes: autonomy only decides whether/when the separate
    // acting step runs. It never changes how the report itself is produced.
    export const AGENT_AUTONOMY_MODES = ['dry_run', 'preview', 'auto'] as const;
    export type AgentAutonomyMode = typeof AGENT_AUTONOMY_MODES[number];
    
    // v1 triggers only. External automation (GitHub Actions, webhooks, user cron)
    // gets event-driven behavior by calling the api/mcp/cli trigger primitive.
    export const AGENT_RUN_TRIGGERS = ['manual', 'schedule', 'api', 'mcp', 'cli'] as const;
    export type AgentRunTrigger = typeof AGENT_RUN_TRIGGERS[number];
    
    export const AGENT_RUN_STATES = [
      'queued', 'deferred', 'running', 'report_ready', 'awaiting_approval', 'acting',
      'completed', 'failed', 'skipped', 'rejected', 'cancelled',
    ] as const;
    export type AgentRunState = typeof AGENT_RUN_STATES[number];
    // Terminal states never transition again; the store (issue 3) enforces this.
    export const TERMINAL_AGENT_RUN_STATES: readonly AgentRunState[] = ['completed', 'failed', 'skipped', 'rejected', 'cancelled'];
    
    // Only runtimes that accept an MCP server config at launch can use the ProPR MCP
    // in v1. Validating here gives a clear error instead of a silently tool-less run.
    export const AGENT_TYPES_SUPPORTING_PROPR_MCP = ['claude', 'codex'] as const;
    
    export const AGENT_NAME_MAX_LENGTH = 120;
    export const AGENT_DESCRIPTION_MAX_LENGTH = 2_000;
    export const AGENT_PROMPT_MAX_LENGTH = 50_000; // same bound as create_task instructions
    export const AGENT_MAX_REPOSITORIES = 10;
    export const AGENT_MAX_ATTACHMENTS = 10;
    // Previous reports are bounded so a long-lived recurring agent cannot grow its
    // own prompt without limit (and its cost with it).
    export const AGENT_MAX_PREVIOUS_REPORTS = 5;
    export const AGENT_PREVIOUS_REPORT_MAX_CHARS = 20_000;
    export const AGENT_REPORT_MAX_CHARS = 100_000;
    
    export interface AgentRunAttachment {
      id: string;
      originalName: string;
      mimeType: string;
      sizeBytes: number;
    }
    
    export interface AgentDefinitionInput {
      name: string;
      description?: string;
      repositories: string[];
      prompt: string;
      agentAlias: string;
      model: string;
      capabilities: AgentCapability[];
      includePreviousReports?: boolean;
      previousReportsLimit?: number;
      schedule?: string | null;
      scheduleEnabled?: boolean;
      autonomyMode: AgentAutonomyMode;
      enabled?: boolean;
    }
    
    export interface AgentDefinition extends Required<Omit<AgentDefinitionInput, 'schedule'>> {
      id: string;
      ownerId: string;
      schedule: string | null;
      attachments: AgentRunAttachment[];
      nextRunAt: string | null;
      revision: number;
      createdAt: string;
      updatedAt: string;
    }
    
    export interface AgentRun {
      id: string;
      definitionId: string;
      ownerId: string;
      trigger: AgentRunTrigger;
      triggerSource: string | null;
      state: AgentRunState;
      reportTaskId: string | null;
      actionTaskId: string | null;
      report: string | null;
      reportTruncated: boolean;
      actionSummary: string | null;
      skipReason: string | null;
      failureReason: string | null;
      autonomyMode: AgentAutonomyMode;
      approvedBy: string | null;
      createdAt: string;
      startedAt: string | null;
      reportedAt: string | null;
      finishedAt: string | null;
    }
    
    /** Scheduled and externally-triggered runs happen without a human watching; they are cost-gated. */
    export function isUnattendedTrigger(trigger: AgentRunTrigger): boolean {
      return trigger !== 'manual';
    }
    
    function isMember<T extends string>(values: readonly T[], value: unknown): value is T {
      return typeof value === 'string' && (values as readonly string[]).includes(value);
    }
    
    /**
     * Validate definition fields. Returns a user-facing error or null. Agent/model
     * support is checked separately against the live agent catalog (API layer),
     * exactly like goal creation does.
     */
    // eslint-disable-next-line complexity -- one flat validator keeps every surface's rules identical
    export function validateAgentDefinitionInput(body: Record<string, unknown>, options: { partial?: boolean } = {}): string | null {
      const has = (key: string) => !options.partial || body[key] !== undefined;
      if (has('name') && (typeof body.name !== 'string' || !body.name.trim() || body.name.length > AGENT_NAME_MAX_LENGTH)) return `name is required (max ${AGENT_NAME_MAX_LENGTH} characters)`;
      if (body.description != null && (typeof body.description !== 'string' || body.description.length > AGENT_DESCRIPTION_MAX_LENGTH)) return `description must be at most ${AGENT_DESCRIPTION_MAX_LENGTH} characters`;
      if (has('repositories')) {
        const repos = body.repositories;
        if (!Array.isArray(repos) || repos.length < 1 || repos.length > AGENT_MAX_REPOSITORIES) return `repositories must list 1-${AGENT_MAX_REPOSITORIES} repositories`;
        if (repos.some(repo => typeof repo !== 'string' || !GOAL_REPOSITORY_PATTERN.test(repo))) return 'repositories must be in owner/repo format';
        if (new Set(repos.map(repo => String(repo).toLowerCase())).size !== repos.length) return 'repositories must not repeat';
      }
      if (has('prompt') && (typeof body.prompt !== 'string' || !body.prompt.trim() || body.prompt.length > AGENT_PROMPT_MAX_LENGTH)) return `prompt is required (max ${AGENT_PROMPT_MAX_LENGTH} characters)`;
      if (has('agentAlias') && (typeof body.agentAlias !== 'string' || !body.agentAlias)) return 'agentAlias is required';
      if (has('model') && (typeof body.model !== 'string' || !body.model)) return 'model is required';
      if (has('capabilities')) {
        const caps = body.capabilities;
        if (!Array.isArray(caps) || caps.some(cap => !isMember(AGENT_CAPABILITIES, cap))) return `capabilities must be a subset of: ${AGENT_CAPABILITIES.join(', ')}`;
      }
      if (has('autonomyMode') && !isMember(AGENT_AUTONOMY_MODES, body.autonomyMode)) return `autonomyMode must be one of: ${AGENT_AUTONOMY_MODES.join(', ')}`;
      if (body.previousReportsLimit != null && (!Number.isSafeInteger(body.previousReportsLimit) || Number(body.previousReportsLimit) < 0 || Number(body.previousReportsLimit) > AGENT_MAX_PREVIOUS_REPORTS)) {
        return `previousReportsLimit must be an integer from 0 to ${AGENT_MAX_PREVIOUS_REPORTS}`;
      }
      for (const flag of ['includePreviousReports', 'scheduleEnabled', 'enabled']) {
        if (body[flag] != null && typeof body[flag] !== 'boolean') return `${flag} must be a boolean`;
      }
      if (body.schedule != null && body.schedule !== '') {
        if (typeof body.schedule !== 'string') return 'schedule must be a cron expression';
        const scheduleError = validateAgentSchedule(body.schedule);
        if (scheduleError) return scheduleError;
      }
      return null;
    }
    
    /** Machine-readable contract for discovery (MCP, CLI help, UI). */
    export const AGENT_DEFINITION_CONTRACT = {
      executesAs: 'isolated-task-run',
      output: 'free-form-report',
      capabilities: AGENT_CAPABILITIES,
      autonomyModes: AGENT_AUTONOMY_MODES,
      triggers: AGENT_RUN_TRIGGERS,
      maxRepositories: AGENT_MAX_REPOSITORIES,
      maxPreviousReports: AGENT_MAX_PREVIOUS_REPORTS,
      schedule: { format: 'cron-5-field', timezone: 'UTC', minIntervalMinutes: 15 },
      proprMcpAgentTypes: AGENT_TYPES_SUPPORTING_PROPR_MCP,
    } as const;

    File: packages/shared/src/cronSchedule.ts (new file)

    Why this file: The scheduler, the API "next run" preview and the UI must compute the same next occurrence. A pure shared function guarantees that.

    /**
     * Minimal 5-field UTC cron evaluator for agent schedules.
     * Fields: minute hour day-of-month month day-of-week (0 = Sunday, 7 accepted as Sunday).
     */
    const MACROS: Record<string, string> = {
      '@hourly': '0 * * * *', '@daily': '0 0 * * *', '@weekly': '0 0 * * 0', '@monthly': '0 0 1 * *',
    };
    const RANGES: Array<[number, number]> = [[0, 59], [0, 23], [1, 31], [1, 12], [0, 7]];
    export const MIN_AGENT_SCHEDULE_INTERVAL_MINUTES = 15;
    // One year of minutes bounds the search so impossible dates (Feb 31) fail fast.
    const SEARCH_LIMIT_MINUTES = 366 * 24 * 60;
    
    export interface ParsedCron { minute: Set<number>; hour: Set<number>; dayOfMonth: Set<number>; month: Set<number>; dayOfWeek: Set<number>; domStar: boolean; dowStar: boolean }
    
    function parseField(field: string, [min, max]: [number, number]): Set<number> {
      const values = new Set<number>();
      for (const part of field.split(',')) {
        const [rangePart, stepPart] = part.split('/');
        const step = stepPart === undefined ? 1 : Number(stepPart);
        if (!Number.isInteger(step) || step < 1) throw new Error(`invalid step in "${field}"`);
        let [from, to] = [min, max];
        if (rangePart !== '*') {
          const [a, b] = rangePart.split('-');
          from = Number(a); to = b === undefined ? (stepPart ? max : from) : Number(b);
        }
        if (![from, to].every(Number.isInteger) || from < min || to > max || from > to) throw new Error(`invalid value in "${field}"`);
        for (let value = from; value <= to; value += step) values.add(value);
      }
      return values;
    }
    
    export function parseCronExpression(expression: string): ParsedCron {
      const normalized = MACROS[expression.trim()] ?? expression.trim();
      const fields = normalized.split(/\s+/);
      if (fields.length !== 5) throw new Error('cron must have 5 fields: minute hour day-of-month month day-of-week');
      const [minute, hour, dayOfMonth, month, dayOfWeek] = fields.map((field, index) => parseField(field, RANGES[index]));
      // 7 is an alias for Sunday in most cron dialects; normalize so getUTCDay() matches.
      if (dayOfWeek.has(7)) { dayOfWeek.delete(7); dayOfWeek.add(0); }
      return { minute, hour, dayOfMonth, month, dayOfWeek, domStar: fields[2] === '*', dowStar: fields[4] === '*' };
    }
    
    function matches(cron: ParsedCron, date: Date): boolean {
      if (!cron.minute.has(date.getUTCMinutes()) || !cron.hour.has(date.getUTCHours()) || !cron.month.has(date.getUTCMonth() + 1)) return false;
      const dom = cron.dayOfMonth.has(date.getUTCDate());
      const dow = cron.dayOfWeek.has(date.getUTCDay());
      // Classic cron semantics: when both day fields are restricted, either may match.
      if (!cron.domStar && !cron.dowStar) return dom || dow;
      return dom && dow;
    }
    
    /** First matching minute strictly after `after`, in UTC. */
    export function nextCronOccurrence(expression: string, after: Date): Date {
      const cron = parseCronExpression(expression);
      const candidate = new Date(after.getTime());
      candidate.setUTCSeconds(0, 0);
      for (let i = 0; i < SEARCH_LIMIT_MINUTES; i++) {
        candidate.setUTCMinutes(candidate.getUTCMinutes() + 1);
        if (matches(cron, candidate)) return new Date(candidate.getTime());
      }
      throw new Error('cron expression never matches within a year');
    }
    
    /** Returns a user-facing error, or null for a valid, not-too-frequent schedule. */
    export function validateAgentSchedule(expression: string): string | null {
      try {
        // Two consecutive occurrences give the effective interval; reject anything
        // denser than the minimum because unattended runs are the main cost risk.
        const first = nextCronOccurrence(expression, new Date(Date.UTC(2026, 0, 5, 0, 0)));
        const second = nextCronOccurrence(expression, first);
        if ((second.getTime() - first.getTime()) / 60_000 < MIN_AGENT_SCHEDULE_INTERVAL_MINUTES) {
          return `schedule must not run more often than every ${MIN_AGENT_SCHEDULE_INTERVAL_MINUTES} minutes`;
        }
        return null;
      } catch (error) {
        return `schedule is invalid: ${(error as Error).message}`;
      }
    }

    File: packages/shared/src/index.ts

    Why this file: The barrel is how core, API, CLI and UI import shared contracts.

    --- a/packages/shared/src/index.ts
    +++ b/packages/shared/src/index.ts
    @@
     export * from './goalCreation.js';
    +// Agents (saved definitions that spawn isolated runs producing free-form reports).
    +export * from './agentDefinitions.js';
    +export * from './cronSchedule.js';

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

    Why this file: Locks the contract down before five consumers depend on it.

    import assert from 'node:assert/strict';
    import { test } from 'node:test';
    import { isUnattendedTrigger, nextCronOccurrence, validateAgentDefinitionInput, validateAgentSchedule } from '@propr/shared';
    
    const valid = { name: 'Weekly bug triage', repositories: ['acme/web'], prompt: 'Review new bug reports.', agentAlias: 'claude', model: 'claude-opus-5-5', capabilities: ['repository_read'], autonomyMode: 'dry_run' };
    
    test('accepts a valid definition and rejects malformed fields', () => {
      assert.equal(validateAgentDefinitionInput(valid), null);
      assert.match(validateAgentDefinitionInput({ ...valid, name: ' ' })!, /name/);
      assert.match(validateAgentDefinitionInput({ ...valid, repositories: ['nope'] })!, /owner\/repo/);
      assert.match(validateAgentDefinitionInput({ ...valid, repositories: Array.from({ length: 11 }, (_, i) => `a/r${i}`) })!, /1-10/);
      assert.match(validateAgentDefinitionInput({ ...valid, capabilities: ['shell'] })!, /capabilities/);
      assert.match(validateAgentDefinitionInput({ ...valid, autonomyMode: 'yolo' })!, /autonomyMode/);
      assert.match(validateAgentDefinitionInput({ ...valid, schedule: '* * * * *' })!, /15 minutes/);
      // Partial updates only validate supplied fields.
      assert.equal(validateAgentDefinitionInput({ name: 'Renamed' }, { partial: true }), null);
    });
    
    test('evaluates cron expressions in UTC', () => {
      assert.equal(nextCronOccurrence('*/15 * * * *', new Date('2026-10-06T10:07:00Z')).toISOString(), '2026-10-06T10:15:00.000Z');
      assert.equal(nextCronOccurrence('@daily', new Date('2026-10-06T10:00:00Z')).toISOString(), '2026-10-07T00:00:00.000Z');
      // 2026-10-10 is a Saturday: weekday schedules skip to Monday.
      assert.equal(nextCronOccurrence('0 9 * * 1-5', new Date('2026-10-09T10:00:00Z')).toISOString(), '2026-10-12T09:00:00.000Z');
      assert.match(validateAgentSchedule('0 0 31 2 *')!, /never matches/);
      assert.match(validateAgentSchedule('0 0 * *')!, /5 fields/);
    });
    
    test('only UI run-now is attended', () => {
      assert.equal(isUnattendedTrigger('manual'), false);
      for (const trigger of ['schedule', 'api', 'mcp', 'cli'] as const) assert.equal(isUnattendedTrigger(trigger), true);
    });
  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: 2800/claude-opus-5-5-agents-v1-1-17-shared-con-20261006-1222-1c1
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2800-20261006-1222-claude-opus-5-5-1c1

    🔍 Track Task Execution

  3. 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: 2800/claude-opus-5-5-agents-v1-1-17-shared-con-20261006-1235-l6m
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2800-20261006-1235-claude-opus-5-5-l6m

    🔍 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