agents-relay 2.0.231 → 2.0.233

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/dist/blocker-recovery.js +325 -0
  2. package/dist/blockers.js +7 -1
  3. package/dist/cli-blocker.js +35 -2
  4. package/dist/cli-help.js +6 -0
  5. package/dist/dashboard-data.js +17 -12
  6. package/dist/dashboard-html.js +1 -1
  7. package/dist/dashboard-workflow-inspection.js +1 -1
  8. package/dist/managed-worker-input.js +6 -0
  9. package/dist/planner.js +12 -3
  10. package/dist/pool.js +19 -2
  11. package/dist/reconciler-review.js +9 -6
  12. package/dist/relayd-control.js +87 -1
  13. package/dist/review-replan.js +39 -0
  14. package/dist/task-transitions.js +2 -2
  15. package/dist/workflow/blocker-recovery.js +32 -0
  16. package/dist/workflow/blocker-resolution-v2.js +1 -1
  17. package/dist/workflow/planner-orchestration-v2.js +7 -3
  18. package/dist/workflow/planner-trigger-v2.js +3 -2
  19. package/dist/workflow/review-v2.js +2 -2
  20. package/package.json +1 -1
  21. package/skills/agents-relay/SKILL.md +5 -1
  22. package/skills/agents-relay/agents/job-acceptance-reviewer.agent.md +2 -4
  23. package/skills/agents-relay/agents/planner.agent.md +7 -0
  24. package/skills/agents-relay/agents/troubleshooter.agent.md +2 -1
  25. package/skills/agents-relay/contracts/blocker-job-recovery.md +23 -0
  26. package/skills/agents-relay/contracts/orchestrator-workflows.md +6 -0
  27. package/skills/agents-relay/contracts/task-recovery-flows.md +2 -1
  28. package/workflow/blocker-recovery.mmd +51 -0
  29. package/workflow/blocker-resolution.mmd +5 -5
  30. package/workflow/planner-orchestration.mmd +6 -6
  31. package/workflow/planner-trigger.mmd +8 -1
  32. package/workflow/review-lifecycle.mmd +31 -17
@@ -3,8 +3,9 @@ import { isFinalReviewAgent, FINAL_REVIEW_AGENT, nextFinalReviewTaskId } from '.
3
3
  import { normalizeReviewEvidence } from './review-evidence.js';
4
4
  import { browserWorkerPool } from './browser-worker-runtime.js';
5
5
  import { storySizeTimeoutMs, taskOverallTimeoutMs } from './types.js';
6
- import { completionGateSatisfied, refreshTaskDependencies, transitionTaskEvent, tryTransitionTaskEvent } from './task-transitions.js';
7
- import { implementationComplete, implementationTasks } from './runtime-status.js';
6
+ import { refreshTaskDependencies, transitionTaskEvent, tryTransitionTaskEvent } from './task-transitions.js';
7
+ import { implementationTasks } from './runtime-status.js';
8
+ import { reviewPlanReady, reviewWorkSettled } from './review-replan.js';
8
9
  import { eventFor } from './events.js';
9
10
  import { workerCandidates } from './worker-routing.js';
10
11
  import { routeExecution } from './execution-routing.js';
@@ -47,9 +48,9 @@ export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
47
48
  return {
48
49
  reviewEnabled: job.reviewEnabled !== false,
49
50
  jobActive: job.state === 'ACTIVE' || job.projectionRecovery?.status === 'repairing',
50
- implementationComplete: implementationComplete(job),
51
+ reviewWorkSettled: reviewWorkSettled(job),
51
52
  headAvailable: Boolean(headSha),
52
- completionGateSatisfied: completionGateSatisfied(job),
53
+ reviewPlanReady: reviewPlanReady(job),
53
54
  noActiveReviewTask: !reviewTasks.some(task => ['DRAFT', 'QUEUED', 'RUNNING'].includes(task.state)),
54
55
  currentReviewCancelled: currentReviewTask?.reviewHeadSha === headSha && currentReviewTask.state === 'CANCELLED',
55
56
  noApprovedCurrentReview: !reviewTasks.some(task => task.state === 'SUCCEEDED' && job.review?.headSha === headSha && job.review.outcome === 'approved'),
@@ -120,11 +121,13 @@ export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
120
121
  'Use the selected reviewer agent contract as the authoritative review protocol.',
121
122
  'This is a PRE-MERGE artifact approval gate: inspect exact PR head, requirements, tests and genuine blocking defects.',
122
123
  'Do not block approval because automatic merge, Job COMPLETED, or post-merge validation has not occurred yet.',
124
+ 'All non-review Tasks have terminal outcomes. Examine FAILED and CANCELLED Tasks and their recovery evidence; never approve an unresolved required outcome.',
125
+ 'The Final Review is the Job completion check. Persist concrete, owner-attributed findings with a changes-required verdict; Relay starts a new Planner round for revisions.',
123
126
  'Do not treat historical failed attempts as current artifact defects; distinguish preserved baseline files from implementation.',
124
127
  ].join('\n\n');
125
128
  const task = createTaskEntity(job, {
126
129
  jobId: job.id, id, title: 'Review', kind: 'work', priority: job.priority, storySize: 'M', projectName: job.title, agentName: FINAL_REVIEW_AGENT,
127
- parentTaskId: null, dependencies: reviewGateTasks.map(item => item.id), capabilities: ['review'],
130
+ parentTaskId: null, dependencies: [], capabilities: ['review'],
128
131
  workerSelection: reviewerRouting.selection, adapter: reviewerRouting.candidate.adapter,
129
132
  input,
130
133
  output: { kind: 'task_pr' }, routing: reviewerRouting.candidate.routing, continuation: null, continuationDeliveredAt: null,
@@ -489,7 +492,7 @@ export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
489
492
  }
490
493
  // Review approval records evidence only. The subsequent Graph reconcile
491
494
  // drives durable local Git merge delivery and terminalization.
492
- if (outcome === 'approved')
495
+ if (outcome === 'approved' || outcome === 'changes_required')
493
496
  needsReconcile = true;
494
497
  return { applied: true, reconcile: needsReconcile, reason: 'review.' + outcome, reconcileMode: needsReconcile ? 'detached' : undefined };
495
498
  }
@@ -9,10 +9,11 @@ import { normalizeThreadId } from './reviewer-thread.js';
9
9
  import { publishTaskBlocked } from './cli-support.js';
10
10
  import { classifyFailedTask, supersedeCancelledTask } from './task-actions.js';
11
11
  import { requestTroubleshooterEscalation, resumeTroubleshooter } from './task-recovery.js';
12
+ import { ensureBlockerRecovery } from './blocker-recovery.js';
12
13
  import { adoptExistingPullRequestJob } from './cli-job-create.js';
13
14
  import { resolveManagedProjectPath, resolveRepositoryProjectPath } from './workspace.js';
14
15
  export function createWorkspaceControl(deps) {
15
- const { client, trusted, noGitHub, repositories, refreshAll, requireLocalJobBinding, makeReconciler, concurrency, pool, bus, isEffectivelyBlocked, unblockTask, publishTaskUnblocked, dispatchTaskAction, registerBlockerDependency, discoverAgents, ensureManagedGitHubJob } = deps;
16
+ const { client, trusted, noGitHub, repositories, refreshAll, requireLocalJobBinding, makeReconciler, concurrency, pool, bus, isEffectivelyBlocked, unblockTask, publishTaskUnblocked, dispatchTaskAction, registerBlockerDependency, discoverAgents, ensureManagedGitHubJob, ensureBlockerRecovery: runBlockerRecovery = ensureBlockerRecovery } = deps;
16
17
  const workspaceControl = async (body) => {
17
18
  const command = typeof body.command === 'string' ? body.command : '';
18
19
  const jobId = typeof body.jobId === 'string' ? body.jobId : '';
@@ -316,6 +317,91 @@ export function createWorkspaceControl(deps) {
316
317
  await refreshAll();
317
318
  return relation;
318
319
  }
320
+ if (command === 'blocker.ensure') {
321
+ const request = body.request && typeof body.request === 'object' ? body.request : {};
322
+ const readText = (field) => typeof request[field] === 'string' ? request[field] : '';
323
+ if (request.origin !== 'planner' && request.origin !== 'troubleshooter')
324
+ throw new Error('blocker.ensure origin must be planner or troubleshooter');
325
+ if (request.resolutionMode !== 'merge' && request.resolutionMode !== 'verified')
326
+ throw new Error('blocker.ensure resolutionMode must be merge or verified');
327
+ const recoveryInput = {
328
+ requestId: readText('requestId'),
329
+ targetRepository: readText('targetRepository'),
330
+ dependentRepository: readText('dependentRepository'),
331
+ dependentJobId: readText('dependentJobId'),
332
+ dependentTaskId: readText('dependentTaskId'),
333
+ reason: readText('reason'),
334
+ title: readText('title'),
335
+ objective: readText('objective'),
336
+ projectPath: typeof request.projectPath === 'string' && request.projectPath ? request.projectPath : undefined,
337
+ resolutionMode: request.resolutionMode,
338
+ origin: request.origin,
339
+ authorized: request.authorized === true,
340
+ authorizedRepositories: repositories,
341
+ };
342
+ const recovered = await runBlockerRecovery(recoveryInput);
343
+ if (!repositories.includes(recoveryInput.targetRepository))
344
+ repositories.push(recoveryInput.targetRepository);
345
+ let planningRecoveryRequired = recovered.planningRecoveryRequired;
346
+ let status = recovered.status;
347
+ if (recovered.planningRecoveryRequired) {
348
+ const blocker = openLocalManagedStore(recoveryInput.targetRepository, 0, {
349
+ directory: relayStoreDirectory(), jobId: recovered.blockerJobId, noGitHub: true,
350
+ });
351
+ const planner = makeReconciler(blocker.store, concurrency);
352
+ try {
353
+ await planner.planJob(recovered.blockerJobId);
354
+ planningRecoveryRequired = false;
355
+ status = 'planned';
356
+ if (blocker.store.mutateJob) {
357
+ await blocker.store.mutateJob(recovered.blockerJobId, (current) => ({
358
+ ...current,
359
+ blockerRecoveryRequest: current.blockerRecoveryRequest
360
+ ? { ...current.blockerRecoveryRequest, status: 'planned', updatedAt: new Date().toISOString() }
361
+ : undefined,
362
+ }));
363
+ }
364
+ }
365
+ catch (error) {
366
+ const current = await blocker.store.load(recovered.blockerJobId);
367
+ const latestPlan = [...(current.plans ?? [])].sort((left, right) => right.round - left.round)[0];
368
+ if (latestPlan?.status !== 'PLANNING')
369
+ throw error;
370
+ }
371
+ finally {
372
+ await planner.close();
373
+ blocker.relay.close();
374
+ }
375
+ if (!planningRecoveryRequired && store.mutateJob) {
376
+ await store.mutateJob(recovered.dependentJobId, (current) => {
377
+ const task = current.tasks.find((item) => item.id === recovered.dependentTaskId);
378
+ const receipt = task?.blockerRecoveryReceipt;
379
+ if (task && receipt && receipt.requestId === recovered.requestId) {
380
+ task.blockerRecoveryReceipt = { ...receipt, status: 'planned', planningRecoveryRequired: false, updatedAt: new Date().toISOString() };
381
+ }
382
+ current.updatedAt = new Date().toISOString();
383
+ return current;
384
+ });
385
+ }
386
+ }
387
+ const blockerSnapshot = openLocalManagedStore(recoveryInput.targetRepository, 0, {
388
+ directory: relayStoreDirectory(), jobId: recovered.blockerJobId, noGitHub: true,
389
+ });
390
+ try {
391
+ if (blockerSnapshot.store.resolveBlockerDependents) {
392
+ const released = await blockerSnapshot.store.resolveBlockerDependents(recovered.blockerJobId, 'merge');
393
+ for (const target of released.unblocked)
394
+ await pool.reconcileLocalJob(target.jobId, 'control.blocker.ensure.resolution');
395
+ }
396
+ }
397
+ finally {
398
+ blockerSnapshot.relay.close();
399
+ }
400
+ await pool.reconcileLocalJob(recovered.dependentJobId, 'control.blocker.ensure.dependent');
401
+ await pool.reconcileLocalJob(recovered.blockerJobId, 'control.blocker.ensure.blocker');
402
+ await refreshAll();
403
+ return { ...recovered, status: planningRecoveryRequired ? 'planning_required' : status, planningRecoveryRequired };
404
+ }
319
405
  if (command === 'blocker.resolve') {
320
406
  if (!store.resolveBlockerDependents)
321
407
  throw new Error('Blocker resolution unavailable');
@@ -0,0 +1,39 @@
1
+ import { isFinalReviewAgent } from './final-review-role.js';
2
+ import { pendingTroubleshooterTasks, pendingTroubleshooterReopens, pendingTroubleshooterRetries } from './troubleshooter.js';
3
+ const terminal = new Set(['SUCCEEDED', 'FAILED', 'CANCELLED']);
4
+ /** A Final Reviewer reads all terminal outcomes, including failures, not just successes. */
5
+ export function reviewWorkSettled(job) {
6
+ const work = job.tasks.filter(task => task.kind !== 'planner' && !isFinalReviewAgent(task.agentName));
7
+ return work.some(task => task.agentName !== 'troubleshooter')
8
+ && work.every(task => terminal.has(task.state) && !['active', 'waiting'].includes(task.resolution?.state ?? ''))
9
+ && !pendingTroubleshooterTasks(job).length
10
+ && !pendingTroubleshooterReopens(job).length
11
+ && !pendingTroubleshooterRetries(job).length;
12
+ }
13
+ /** New reviews use Review -> Replan; older persisted targeted revisions remain recoverable. */
14
+ export function reviewNeedsReplan(job) {
15
+ const review = job.review;
16
+ if (!review?.taskId || review.revisionDisposition === 'targeted')
17
+ return false;
18
+ const changes = review.outcome === 'changes_required'
19
+ || (review.outcome === 'stale' && (job.reviewRevisionRounds ?? []).some(round => round.reviewTaskId === review.taskId && round.status === 'changes_required'));
20
+ return changes && !(job.plans ?? []).some(plan => plan.trigger.source === 'review' && plan.trigger.reviewTaskId === review.taskId && plan.status !== 'FAILED');
21
+ }
22
+ /** An immutable re-review must wait for the finding-driven Plan and its work to settle. */
23
+ export function reviewPlanReady(job) {
24
+ if ((job.plans ?? []).some(plan => plan.status === 'PLANNING'))
25
+ return false;
26
+ const latest = (job.plans ?? []).at(-1);
27
+ const legacy = !latest && job.tasks.some(task => task.kind === 'planner' && task.state === 'SUCCEEDED');
28
+ if (!legacy && (latest?.status !== 'SUCCEEDED' || !job.tasks.some(task => task.kind !== 'planner' && !isFinalReviewAgent(task.agentName))))
29
+ return false;
30
+ const review = job.review;
31
+ if (!review?.taskId || review.revisionDisposition === 'targeted')
32
+ return true;
33
+ const requiresRevision = review.outcome === 'changes_required'
34
+ || (review.outcome === 'stale' && (job.reviewRevisionRounds ?? []).some(round => round.reviewTaskId === review.taskId && round.status === 'changes_required'));
35
+ if (!requiresRevision)
36
+ return true;
37
+ return (job.plans ?? []).some(plan => plan.status === 'SUCCEEDED'
38
+ && plan.trigger.source === 'review' && plan.trigger.reviewTaskId === review.taskId);
39
+ }
@@ -5,8 +5,8 @@ export { dependencyReady, detectCycles } from './workflow/task-reconcile.js';
5
5
  import { observability } from './observability.js';
6
6
  export function completionGateSatisfied(job) {
7
7
  const latest = [...(job.plans ?? [])].sort((a, b) => a.round - b.round).at(-1);
8
- const planSatisfied = latest?.status === 'SUCCEEDED' && latest.objectiveStatus === 'satisfied';
9
- const legacySatisfied = (job.plans?.length ?? 0) === 0 && job.tasks.some(task => task.kind === 'planner' && task.state === 'SUCCEEDED' && task.plannerResult?.objective_status === 'satisfied');
8
+ const planSatisfied = latest?.status === 'SUCCEEDED' && (job.reviewEnabled !== false || latest.objectiveStatus === 'satisfied');
9
+ const legacySatisfied = (job.plans?.length ?? 0) === 0 && job.tasks.some(task => task.kind === 'planner' && task.state === 'SUCCEEDED' && (job.reviewEnabled !== false || task.plannerResult?.objective_status === 'satisfied'));
10
10
  const implementation = implementationTasks(job);
11
11
  return (planSatisfied || legacySatisfied) && implementation.length > 0 && implementation.every(task => task.state === 'SUCCEEDED');
12
12
  }
@@ -0,0 +1,32 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { GraphRuntime } from './graph-v2.js';
3
+ import { dispatchWorkflowGraph } from './dispatcher.js';
4
+ const source = readFileSync(new URL('../../workflow/blocker-recovery.mmd', import.meta.url), 'utf8');
5
+ export const blockerRecoveryGraph = new GraphRuntime(source, {
6
+ states: new Set(['entry', 'check_authorization', 'check_known_request', 'check_dependency', 'validate_adoption', 'validate_target', 'validate_trust_boundary', 'register', 'ready', 'rejected']),
7
+ guards: {
8
+ authorized: facts => facts.durableFacts.authorized === true,
9
+ knownRequest: facts => facts.durableFacts.knownRequest === true,
10
+ authoritativeDependency: facts => facts.durableFacts.authoritativeDependency === true,
11
+ adoptionValid: facts => facts.durableFacts.adoptionValid === true,
12
+ targetValid: facts => facts.durableFacts.targetValid === true,
13
+ trustBoundaryValid: facts => facts.durableFacts.trustBoundaryValid === true,
14
+ },
15
+ actions: Object.fromEntries([
16
+ 'recovery.createBlocker',
17
+ 'recovery.adoptExistingBlocker',
18
+ 'recovery.registerDependency',
19
+ ].map(id => [id, { id }])),
20
+ events: { 'blocker.recovery.ensure': { id: 'blocker.recovery.ensure' } },
21
+ });
22
+ export async function dispatchBlockerRecovery(facts, executeAction) {
23
+ return dispatchWorkflowGraph(blockerRecoveryGraph, {
24
+ initialState: 'entry',
25
+ input: { transport: 'event', id: 'blocker.recovery.ensure', payload: {} },
26
+ durableFacts: facts,
27
+ isTransientState: state => state.startsWith('check_') || state.startsWith('validate_') || state === 'register',
28
+ graphName: 'blocker-recovery',
29
+ maxSteps: 16,
30
+ executeAction,
31
+ });
32
+ }
@@ -9,7 +9,7 @@ export const blockerResolutionV2 = new GraphRuntime(source, {
9
9
  'check_draft', 'check_blocked', 'check_failed', 'check_unblocked', 'wait', 'obsolete', 'resumed',
10
10
  ]),
11
11
  guards: {
12
- resolutionAllowed: boolGuard('resolutionAllowed'),
12
+ resolutionConditionMet: boolGuard('resolutionConditionMet'),
13
13
  targetMatches: boolGuard('targetMatches'),
14
14
  effectivelyBlocked: boolGuard('effectivelyBlocked'),
15
15
  alreadyUnblocked: boolGuard('alreadyUnblocked'),
@@ -1,13 +1,14 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { GraphRuntime } from './graph-v2.js';
3
3
  import { dispatchWorkflowGraph, dispatchWorkflowGraphSync } from './dispatcher.js';
4
+ import { reviewNeedsReplan } from '../review-replan.js';
4
5
  import { isEffectivelyBlocked, unblockNeedsNewPlan, unconsumedUnblockTrigger } from '../unblock.js';
5
6
  const source = readFileSync(new URL('../../workflow/planner-orchestration.mmd', import.meta.url), 'utf8');
6
7
  const boolGuard = (name) => (facts) => facts.durableFacts[name] === true;
7
8
  export const plannerOrchestrationV2 = new GraphRuntime(source, {
8
9
  states: new Set([
9
10
  'idle', 'check_legacy_pending', 'check_recover', 'check_plan_failure', 'check_plan_recovery', 'check_plan_recovery_exists', 'check_seed', 'check_planner', 'check_resolution_ownership',
10
- 'check_blocked', 'check_work', 'check_materialized', 'check_objective', 'wait', 'recovered', 'created',
11
+ 'check_blocked', 'check_work', 'check_materialized', 'check_review', 'wait', 'recovered', 'created',
11
12
  ]),
12
13
  guards: {
13
14
  legacyPlanningPending: boolGuard('legacyPlanningPending'),
@@ -21,7 +22,7 @@ export const plannerOrchestrationV2 = new GraphRuntime(source, {
21
22
  noBlockedWork: boolGuard('noBlockedWork'),
22
23
  noActiveImplementation: boolGuard('noActiveImplementation'),
23
24
  continuationMaterialized: boolGuard('continuationMaterialized'),
24
- objectiveUnsatisfied: boolGuard('objectiveUnsatisfied'),
25
+ reviewNeedsReplan: boolGuard('reviewNeedsReplan'),
25
26
  },
26
27
  actions: {
27
28
  'planner.createRecovery': { id: 'planner.createRecovery' },
@@ -65,6 +66,9 @@ export function plannerOrchestrationFacts(job, recoverablePendingPlan) {
65
66
  noActiveImplementation: !scopedTasks.some(task => task.kind !== 'planner' && (['QUEUED', 'RUNNING', 'AWAITING_DECISION'].includes(task.state) || (task.state === 'DRAFT' && !task.unblock))),
66
67
  resolutionOwnedByTroubleshooter: scopedTasks.some(task => task.kind !== 'planner' && task.resolution?.owner === 'troubleshooter' && ['active', 'waiting'].includes(task.resolution.state)),
67
68
  continuationMaterialized: Boolean(unconsumedUnblockTrigger(job)) || !(latestObjective === 'in_progress' && latestId && !job.tasks.some(task => task.kind !== 'planner' && task.planningDecisionId === latestId)),
68
- objectiveUnsatisfied: latestObjective !== 'satisfied',
69
+ reviewNeedsReplan: reviewNeedsReplan(job) || Boolean(unconsumedUnblockTrigger(job))
70
+ || (job.reviewEnabled === false && latestObjective !== 'satisfied')
71
+ || (!scopedPlans.some(plan => plan.status === 'SUCCEEDED')
72
+ && !scopedTasks.some(task => task.kind === 'planner' && task.state === 'SUCCEEDED')),
69
73
  };
70
74
  }
@@ -4,11 +4,12 @@ import { dispatchWorkflowGraphSync } from './dispatcher.js';
4
4
  const source = readFileSync(new URL('../../workflow/planner-trigger.mmd', import.meta.url), 'utf8');
5
5
  const boolGuard = (name) => (facts) => facts.durableFacts[name] === true;
6
6
  export const plannerTriggerV2 = new GraphRuntime(source, {
7
- states: new Set(['idle', 'check_unblock', 'check_initial', 'manual', 'unblock', 'initial', 'continuation']),
7
+ states: new Set(['idle', 'check_unblock', 'check_initial', 'check_review', 'manual', 'unblock', 'initial', 'review', 'continuation']),
8
8
  guards: {
9
9
  manualPlan: boolGuard('manualPlan'),
10
10
  hasUnblock: boolGuard('hasUnblock'),
11
11
  initialPlan: boolGuard('initialPlan'),
12
+ reviewRequired: boolGuard('reviewRequired'),
12
13
  },
13
14
  actions: {},
14
15
  events: { 'plan.requested': { id: 'plan.requested' } },
@@ -16,7 +17,7 @@ export const plannerTriggerV2 = new GraphRuntime(source, {
16
17
  export function dispatchPlannerTrigger(facts) {
17
18
  return dispatchWorkflowGraphSync(plannerTriggerV2, {
18
19
  initialState: 'idle', input: { transport: 'event', id: 'plan.requested', payload: {} }, durableFacts: facts, graphName: 'planner-trigger',
19
- isTransientState: state => state.startsWith('check_'), maxSteps: 4,
20
+ isTransientState: state => state.startsWith('check_'), maxSteps: 5,
20
21
  });
21
22
  }
22
23
  /** Compatibility/testing alias. Production callers use dispatchPlannerTrigger. */
@@ -9,9 +9,9 @@ export const reviewLifecycleV2 = new GraphRuntime(source, {
9
9
  reviewEnabled: boolGuard('reviewEnabled'),
10
10
  prOpen: boolGuard('prOpen'),
11
11
  jobActive: boolGuard('jobActive'),
12
- implementationComplete: boolGuard('implementationComplete'),
12
+ reviewWorkSettled: boolGuard('reviewWorkSettled'),
13
13
  headAvailable: boolGuard('headAvailable'),
14
- completionGateSatisfied: boolGuard('completionGateSatisfied'),
14
+ reviewPlanReady: boolGuard('reviewPlanReady'),
15
15
  noActiveReviewTask: boolGuard('noActiveReviewTask'),
16
16
  currentReviewCancelled: boolGuard('currentReviewCancelled'),
17
17
  noApprovedCurrentReview: boolGuard('noApprovedCurrentReview'),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agents-relay",
3
- "version": "2.0.231",
3
+ "version": "2.0.233",
4
4
  "description": "Durable async agent jobs coordinated through GitHub pull requests",
5
5
  "repository": {
6
6
  "type": "git",
@@ -7,6 +7,10 @@ description: Use Agents Relay for durable multi-step or multi-agent work that ne
7
7
 
8
8
  Agents Relay manages durable Jobs and Tasks. Use its CLI for Job/Task state and actions; do not read its private storage, GitHub projections, or internal service APIs. Prefer completing simple, non-delegated work directly without Relay.
9
9
 
10
+ ## Job Execution Lifecycle (JEL)
11
+
12
+ Explain **JEL** to the user: **Create → Plan → Execute → Final Review → Merge → Completed**. After work/recovery Tasks terminate (SUCCEEDED/FAILED/CANCELLED), Final Review judges completion: PASS merges; CHANGES_REQUIRED persists findings, starts Planner N+1 for minimal fixes, then re-reviews. No automatic post-success Plan. Planner/Workers use discovered **ponytail** Skill (YAGNI, reuse, minimal Tasks); preserve mandatory safeguards.
13
+
10
14
  ## 1. Choose and start a Job
11
15
 
12
16
  Use Relay when the objective requires independent Tasks, durable progress, retries, review, or cross-session handoffs. Capture the full user objective, decisions, constraints, acceptance checks, and delivery expectations in standalone Markdown before creating a Job. A fresh agent must be able to act without the originating conversation. Put a Mermaid diagram before its explanation only when it clarifies a real workflow.
@@ -44,7 +48,7 @@ A worker's process exit, browser submission receipt, or emitted event is **not**
44
48
 
45
49
  A Reviewer finding defects in a known immutable head emits `task.completed` with `data.verdict: changes-required`, `data.head_sha`, and actionable findings—not `task.failed`. If the Reviewer cannot establish the required head or produce a valid review, it reports an execution failure with `task.failed`, not an invented verdict.
46
50
 
47
- For a failed Task, diagnose before retrying. Read `contracts/task-recovery-flows.md` for recovery and human escalation boundaries. Troubleshooter inspects the original Task via `task show` and paginated `task events`, verifies the root cause, then uses the pinned CLI `task recover --task-id ORIGINAL --recovery-task-id TROUBLESHOOTER` only after proving the repair. If a shared defect cannot be repaired in this execution, register it via `blocker add` on the owning P0/self Job and complete the recovery handoff; do not leave a worker running indefinitely. Only a genuinely human-required decision justifies the **pinned CLI** `task escalate --task-id TROUBLESHOOTER --required-action ... --resolution-condition ...`; this is a Relay operation, **not** an Events Bus event. Never invent or publish an escalation event, and never escalate a browser-readiness failure as a login request without authentication evidence. Only Relay can block/unblock a Troubleshooter; after a human response, recheck the blocker before recovering the original Task. Do not silently treat missing or stale evidence as success.
51
+ For a failed Task, diagnose before retrying. Read `contracts/task-recovery-flows.md` for recovery and human escalation boundaries. For authorized technical prerequisites in another repository, use `contracts/blocker-job-recovery.md` and the pinned `blocker ensure` CLI action; repository boundaries alone do not justify escalation. Troubleshooter inspects the original Task via `task show` and paginated `task events`, verifies the root cause, then uses the pinned CLI `task recover --task-id ORIGINAL --recovery-task-id TROUBLESHOOTER` only after proving the repair. Only a genuinely human-required decision justifies the **pinned CLI** `task escalate --task-id TROUBLESHOOTER --required-action ... --resolution-condition ...`; this is a Relay operation, **not** an Events Bus event. Never invent or publish an escalation event, and never escalate a browser-readiness failure as a login request without authentication evidence. Only Relay can block/unblock a Troubleshooter; after a human response, recheck the blocker before recovering the original Task. Do not silently treat missing or stale evidence as success.
48
52
 
49
53
  ## 4. Configured escalation and host-owned Interactive Review
50
54
 
@@ -19,11 +19,9 @@ Use `speckit-checklist` only as requirements-quality guidance; do not create
19
19
  or edit checklists in this read-only Reviewer role. A Spec Kit analysis never
20
20
  replaces independent implementation and acceptance-evidence review.
21
21
 
22
- ## Targeted revision ownership
22
+ ## Findings and re-planning ownership
23
23
 
24
- For actionable findings, identify the original responsible durable Task ID. When the **execution-pinned Relay CLI supports** `task revise`, submit each owner's findings with a stable request ID, the exact active Reviewer execution identity, immutable head SHA and findings file; check the durable receipt. An ambiguous owner must be reported, not guessed. Do not edit artifacts, invoke Planner for every issue, or claim CLI submission completed a revision.
25
-
26
- **Bootstrap compatibility:** During a managed rollout that is itself introducing `task revise`, the execution-pinned CLI may not yet expose the command. Verify genuine command unavailability via its help/usage output. In that one case, **do not fail a completed review solely because the CLI does not exist**. Publish the canonical `task.completed` verdict `changes-required` with exact `head_sha`, complete actionable `data.findings` (including owner Task IDs where known), and `data.revision_submission: "cli-unavailable"`. Relay owns fallback remediation through its existing Review Graph. Never claim targeted requests were persisted. This fallback is NOT permission to ignore an available CLI's validation error, stale execution, authorization failure or missing evidence; those remain fail-closed.
24
+ Final Review is the sole whole-Job completion check. Examine all terminal Tasks, including FAILED and CANCELLED; these may be historically superseded by verified replacement work, but an unresolved required outcome is **CHANGES_REQUIRED**, never PASS. For each blocking finding, provide its concrete evidence, minimum remediation and responsible original Task ID when known. Put the **complete actionable findings in the `task.completed` verdict** (`data.findings`) at the immutable head SHA. Relay records this verdict in the Job and starts the next Planner round to assign the minimal fix Tasks. Do not call `task revise`, create Tasks, or initiate a separate Planner from this Reviewer; the JEL owns the handoff. Existing persisted targeted-revision requests remain supported by the runtime for backward compatibility.
27
25
 
28
26
  ## Review Decision
29
27
 
@@ -19,6 +19,12 @@ A CLI rejection (`PLAN_APPLY_VALIDATION_FAILED`) is distinct from a missing appl
19
19
 
20
20
  Read current Plan, prior rounds, and Task history through the execution-bound Relay `plan context` CLI response. Do not infer Plan status from GitHub or PR comments. A Plan records its trigger/context (including unblock/change facts), assessment, and generated Task IDs; Plan records are not semantic parents for work Tasks.
21
21
 
22
+ ## Ponytail — keep Plans and Tasks lean
23
+
24
+ Apply the installed `ponytail` Skill (`full`) when resolved in the execution context. Its ladder is mandatory: question if the extra Task is needed (YAGNI), reuse existing helpers/tests, keep scope minimal, and only split by truly independent Agent responsibility. Never add a Task solely to repeat successful checks or because some optional test could exist; do not defer mandatory security or correctness checks. The Final Reviewer—not a second completion Planner—decides whether the Job objective is satisfied.
25
+
26
+ For `plan_trigger.source = review`, consume the persisted Final Reviewer findings and propose **only minimal revision Tasks** that close them, keeping original Task history. Do not create a fresh Final Reviewer Task; Relay creates it when all Tasks are terminal. Never claim earlier failures succeeded or leave an unresolved required failure without a proper resolution.
27
+
22
28
  ## Planning contract
23
29
 
24
30
  **Plan the whole objective before choosing Task boundaries.**
@@ -135,6 +141,7 @@ If evidence is absent or execution outcome is unknown, disposition that historic
135
141
  - When a Job needs multi-perspective review, use the visible `review-chair` agent or an Agent Graph to select specialist roles dynamically. Keep specialist Tasks as independent siblings against the same immutable target/version, and leave worker/model/provider routing to Relay.
136
142
  - A Task describes what an agent must accomplish; never emit a shell command as a worker Task.
137
143
  - Use dependencies only for Task IDs inside the current Job, and only when execution order actually matters. Never encode cross-Job or cross-repository dependencies in `dependencies`.
144
+ - Do not label authorized technical work in another repository as an owner action or request human escalation just because it crosses a repository boundary. Assign executable work that uses the pinned `blocker ensure` action under `contracts/blocker-job-recovery.md`; preserve escalation for a real owner-only decision.
138
145
  - When the current Job is a prerequisite for another durable Job/Task, emit that dependent in top-level `unblocks`. The current blocker Job owns this authoritative reverse relation. Dependent-side `blockedBy` is optional observability metadata and is not the source of truth. Use `resolutionMode: "merge"` when blocker PR merge is sufficient; use `"verified"` when publication, deployment, runtime health, human approval, or another post-merge fact must be verified.
139
146
  - Describe each child Task precisely enough for worker-router to decide from the Task itself. Do not invent Codex/ChatGPT capability labels. workerRequirements is optional and should normally be omitted; use an explicit runtime only when the objective already requires that runtime.
140
147
  - Do not choose codex/chatgpt, provider/model, or usage probes.
@@ -20,6 +20,7 @@ durable Relay Tasks. For runtime or lifecycle failures, use Relay recovery
20
20
  instead of Spec Kit.
21
21
 
22
22
  Read the independently pinned Task/Job Contract from the Relay Prompt. Only when a shared defect requires a P0/self-job, load `contracts/orchestrator-workflows.md` relative to the Prompt-pinned Relay Skill; do not add it to ordinary recovery startup Context.
23
+ For cross-repository blocker creation or reuse, follow `contracts/blocker-job-recovery.md` relative to the Prompt-pinned Relay Skill.
23
24
 
24
25
  Read `troubleshooter-qa.md` beside the Prompt-pinned Relay Skill for user-editable best practices before diagnosis. Treat its answers as guidance only, below current evidence and authoritative contracts. After a verified recovery, add or refine a concise Q&A entry when it provides reusable knowledge; never include secrets or unverified claims.
25
26
 
@@ -38,7 +39,7 @@ Read `troubleshooter-qa.md` beside the Prompt-pinned Relay Skill for user-editab
38
39
  6. Repair:
39
40
  - For a transient failure, verify the transient condition is gone.
40
41
  - For task-local failure, make the smallest durable repair in the original Job/PR when that is within scope.
41
- - For a shared platform/runtime defect, first create or reuse the owning blocker P0/self-job. If it can be completed inside this recovery execution, fix/verify it and retry the original Task. If it cannot be completed now, register the original Task with `agents-relay blocker add` on that blocker Job and finish this Troubleshooter task; do not stay running while waiting for another Job.
42
+ - For authorized technical work in another repository, use the pinned Relay CLI `blocker ensure` with the stable request identity and exact failed Task; do not classify that work as an owner action or escalate only because the repository differs. For an existing shared P0/self-job, reuse it. Complete this Troubleshooter after verifying the durable reverse relation; Relay owns later release.
42
43
  - For a suspected genuine human/external blocker, invoke `agents-relay escalation` with the original intent, blocker, and relevant context. Handle the CLI-reported `resolved`, `failed`, and `needs_user` outcomes. When it returns `needs_user`, call Relay's `task escalate` operation with the concrete required action, resolution condition, and diagnostic context. Relay records the escalation and blocks this Troubleshooter; no worker remains running while waiting.
43
44
  - After unblock, this same Troubleshooter must run with a new execution ID, re-check the blocking condition, and produce a fresh resolution bound to that execution. A previously resolved resolution record never authorizes retrying a new attempt.
44
45
  - Unknown worker execution outcomes fail closed. Do not automatically reroute or retry the original task, and do not block the original task; diagnose it through the Troubleshooter.
@@ -0,0 +1,23 @@
1
+ # Cross-Repository Blocker Job Recovery
2
+
3
+ Use this contract when an authorized technical prerequisite must be completed in another repository before a failed Task can safely resume.
4
+
5
+ ## Decision boundary
6
+
7
+ - Missing cross-repository capability is technical work. When it is within the parent Job's authorized objective and the target repository is within the same owner/workspace trust boundary, create or reuse a blocker Job; do not ask the owner to create it and do not escalate merely because the repository differs.
8
+ - Escalate only for a concrete owner-only action such as human approval, account consent, or a destructive/public/billing decision outside the existing authorization.
9
+ - The blocker Job owns a reverse `unblocks` relation to the exact dependent Job, Task, and attempt. Never create a cross-Job Task dependency or mark the original Task successful.
10
+
11
+ ## Supported action
12
+
13
+ Use the version-matched Relay CLI `blocker ensure` action. It accepts the dependent `--repo` and `--id`, target `--target-repo`, exact `--dependent-task`, stable `--request-id`, short `--reason`, standalone `--title` and `--objective-file`, `--origin planner|troubleshooter`, `--resolution merge|verified`, and explicit `--authorized`. Include `--project-path` only when a validated repository-relative project path is known. The stable request ID must be reused unchanged after uncertainty or retry.
14
+
15
+ The objective must stand alone, identify the target repository and dependent Task, and stay within the parent authorization. Do not include secrets, arbitrary commands, path traversal, additional billing, public publication, destructive actions, or new sensitive access. The target repository must be normalized, configured in the trusted workspace, and share the dependent repository's owner/workspace boundary.
16
+
17
+ ## Durable result and recovery
18
+
19
+ The action returns the blocker Job ID, repository, dependent Job/Task, reason, resolution mode, outcome, status, and whether planning recovery remains. Relay creates or adopts one durable Job, persists the request identity, and registers the reverse relation. A repeated request with the same identity and scope reuses that Job; reuse of the identity with different scope fails closed. If creation succeeded but planning or registration failed, retry the same request to recover the existing Job and continue the missing step. Never create a second Job to recover planning.
20
+
21
+ `merge` releases the dependent after the blocker Job's verified merge. `verified` releases it only after an explicit `blocker resolve` operation records the required post-merge evidence. The dependent Task stays failed/waiting until Relay verifies the configured condition and matching attempt. A blocker creation, planning, registration, or CLI receipt alone does not prove the original Task succeeded.
22
+
23
+ After the action, inspect the blocker Job and dependent Task through the pinned Relay CLI. A Troubleshooter may complete its own Task only after the handoff and exact reverse relation are durable. An immediate repair instead requires a fresh `task recover` receipt and confirmation that the original Task is queued for the expected recovery attempt.
@@ -6,6 +6,12 @@ Before `job create`, the orchestrator converts the relevant discussion into a st
6
6
 
7
7
  This contract defines orchestrator-owned exception workflows that sit above normal Agents Relay task/job execution.
8
8
 
9
+ ## Review-driven JEL continuation
10
+
11
+ After the Initial Plan materializes its Tasks, Relay waits for **all non-review Tasks to be terminal**, including Troubleshooter recoveries. The Final Reviewer reads every Task result (including FAILED and CANCELLED), the original Job objective, the immutable head and test evidence. An outstanding required failure must be reported as a finding and cannot pass the merge gate. The Final Review is the **completion check**; do not schedule a second Planner merely to ask whether the objective is satisfied.
12
+
13
+ `review.approved` with valid durable evidence permits Relay-owned merge/delivery. `review.changes_required` persists the immutable Reviewer's findings in the Job and initiates a **new Planner round**, whose sole automatic objective is to address those findings with the minimum necessary revision Tasks. Once those Tasks terminate, repeat Final Review. No speculative verification Task or separate completion-check Planner is allowed. Preserve older targeted-revision histories for restart compatibility; new Review rounds should use the Review → Replan path. A real blocker/recovery may use its separate canonical trigger without pretending to be a Review finding.
14
+
9
15
  ## Normal managed Job start workflow
10
16
 
11
17
  For a normal managed Job, the preferred bootstrap is one command:
@@ -18,6 +18,7 @@ cannot assume Neo exists. Never pass arbitrary Task text as a Shell command.
18
18
  - **One agent Task event contract** applies to Implementation, Reviewer, and Troubleshooter: `task.started`, optional `task.progress`, then exactly one agent terminal event, `task.completed` or `task.failed`. Role-specific results belong in `data`. A review with findings is a *completed* review, not a failed agent execution.
19
19
  - **`task.blocked` and `task.unblocked` are authoritative Relay lifecycle transitions**, not ordinary agent terminal events. A human may authorize unblocking a Troubleshooter but does not directly unblock the failed original Task.
20
20
  - **Troubleshooter owns diagnosis and recovery decisions.** It chooses technical repair/retry, blocker-Job dependency, or human escalation. There is no separate Escalator agent.
21
+ - For an authorized technical prerequisite in another repository, use the create-or-reuse action in [`blocker-job-recovery.md`](blocker-job-recovery.md); repository boundaries alone never justify human escalation.
21
22
  - **Relay owns transitions and dispatch.** Troubleshooter requests authorized operations through Relay CLI, then checks the CLI response and fresh Task Context. Event transport acceptance alone is not confirmation of a Task transition.
22
23
  - Preserve the original failure, exact execution correlation, evidence, and idempotency throughout retries and resumes.
23
24
 
@@ -43,7 +44,7 @@ flowchart TD
43
44
  E --> F{"Recovery decision"}
44
45
  F -->|Technical recovery| G["Fix and verify; request retry"]
45
46
  G --> H["Original Task resumes"]
46
- F -->|Other Job required| I["Create/link blocker Job"]
47
+ F -->|Authorized cross-repository technical work| I["Create or reuse blocker Job"]
47
48
  I --> J["Dependency resolution"]
48
49
  J --> K["Original Task resumes after verification"]
49
50
  F -->|Human required| L["Troubleshooter requests escalation"]
@@ -0,0 +1,51 @@
1
+ ---
2
+ title: Blocker Recovery
3
+ description: Authorizes and idempotently creates or adopts a cross-repository blocker Job before registering its reverse dependency.
4
+ ---
5
+ flowchart LR
6
+ %% relay: initial entry
7
+ entry["state: entry"]
8
+ check_authorization["state: check_authorization"]
9
+ check_known_request["state: check_known_request"]
10
+ check_dependency["state: check_dependency"]
11
+ validate_adoption["state: validate_adoption"]
12
+ validate_target["state: validate_target"]
13
+ validate_trust_boundary["state: validate_trust_boundary"]
14
+ register["state: register"]
15
+ ready["state: ready"]
16
+ rejected["state: rejected"]
17
+
18
+ authorized["guard: authorized"]
19
+ known_request["guard: knownRequest"]
20
+ authoritative_dependency["guard: authoritativeDependency"]
21
+ adoption_valid["guard: adoptionValid"]
22
+ target_valid["guard: targetValid"]
23
+ trust_boundary_valid["guard: trustBoundaryValid"]
24
+
25
+ create_blocker["action: recovery.createBlocker"]
26
+ adopt_blocker["action: recovery.adoptExistingBlocker"]
27
+ register_dependency["action: recovery.registerDependency"]
28
+
29
+ entry -->|on: blocker.recovery.ensure| check_authorization
30
+ check_authorization -->|on: blocker.recovery.ensure| authorized
31
+ authorized -->|false| rejected
32
+ authorized -->|true| validate_target
33
+ check_known_request -->|on: blocker.recovery.ensure| known_request
34
+ known_request -->|true| validate_adoption
35
+ known_request -->|false| check_dependency
36
+ check_dependency -->|on: blocker.recovery.ensure| authoritative_dependency
37
+ authoritative_dependency -->|true| validate_adoption
38
+ authoritative_dependency -->|false| create_blocker
39
+ validate_adoption -->|on: blocker.recovery.ensure| adoption_valid
40
+ adoption_valid -->|false| rejected
41
+ adoption_valid -->|true| adopt_blocker
42
+ adopt_blocker -->|to: register| register
43
+ validate_target -->|on: blocker.recovery.ensure| target_valid
44
+ target_valid -->|false| rejected
45
+ target_valid -->|true| validate_trust_boundary
46
+ validate_trust_boundary -->|on: blocker.recovery.ensure| trust_boundary_valid
47
+ trust_boundary_valid -->|false| rejected
48
+ trust_boundary_valid -->|true| check_known_request
49
+ create_blocker -->|to: register| register
50
+ register -->|on: blocker.recovery.ensure| register_dependency
51
+ register_dependency -->|to: ready| ready
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  title: Blocker Resolution
3
- description: Releases dependency-waiting work; failed work and blocked Troubleshooters require their own fresh recovery flow.
3
+ description: Releases dependency-waiting work only after the blocker Job and configured resolution condition are verified; failed work and blocked Troubleshooters require their own fresh recovery flow.
4
4
  ---
5
5
  flowchart LR
6
6
  %% relay: initial waiting
@@ -16,7 +16,7 @@ wait["state: wait"]
16
16
  obsolete["state: obsolete"]
17
17
  resumed["state: resumed"]
18
18
 
19
- resolutionAllowed["guard: resolutionAllowed"]
19
+ resolutionConditionMet["guard: resolutionConditionMet"]
20
20
  targetMatches["guard: targetMatches"]
21
21
  effectivelyBlocked["guard: effectivelyBlocked"]
22
22
  alreadyUnblocked["guard: alreadyUnblocked"]
@@ -27,9 +27,9 @@ isUnblocked["guard: isUnblocked"]
27
27
 
28
28
  releaseDraft["action: blocker.releaseDraft"]
29
29
 
30
- waiting -->|on: blocker.resolved| resolutionAllowed
31
- resolutionAllowed -->|false| wait
32
- resolutionAllowed -->|true| checkTarget
30
+ waiting -->|on: blocker.resolved| resolutionConditionMet
31
+ resolutionConditionMet -->|false| wait
32
+ resolutionConditionMet -->|true| checkTarget
33
33
 
34
34
  checkTarget -->|on: blocker.resolved| targetMatches
35
35
  targetMatches -->|false| obsolete
@@ -16,7 +16,7 @@ checkResolution["state: check_resolution_ownership"]
16
16
  checkBlocked["state: check_blocked"]
17
17
  checkWork["state: check_work"]
18
18
  checkMaterialized["state: check_materialized"]
19
- checkObjective["state: check_objective"]
19
+ checkReview["state: check_review"]
20
20
  wait["state: wait"]
21
21
  recovered["state: recovered"]
22
22
  created["state: created"]
@@ -32,7 +32,7 @@ resolutionOwned["guard: resolutionOwnedByTroubleshooter"]
32
32
  noBlocked["guard: noBlockedWork"]
33
33
  noActiveWork["guard: noActiveImplementation"]
34
34
  materialized["guard: continuationMaterialized"]
35
- unsatisfied["guard: objectiveUnsatisfied"]
35
+ reviewRequired["guard: reviewNeedsReplan"]
36
36
 
37
37
  recoverAction["action: planner.recoverPending"]
38
38
  createRecovery["action: planner.createRecovery"]
@@ -84,9 +84,9 @@ noActiveWork -->|true| checkMaterialized
84
84
 
85
85
  checkMaterialized -->|on: planner.reconcile| materialized
86
86
  materialized -->|false| wait
87
- materialized -->|true| checkObjective
87
+ materialized -->|true| checkReview
88
88
 
89
- checkObjective -->|on: planner.reconcile| unsatisfied
90
- unsatisfied -->|false| wait
91
- unsatisfied -->|true| createAction
89
+ checkReview -->|on: planner.reconcile| reviewRequired
90
+ reviewRequired -->|false| wait
91
+ reviewRequired -->|true| createAction
92
92
  createAction --> created