agents-relay 2.0.209 → 2.0.211

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 (50) hide show
  1. package/dist/cli-help.js +10 -4
  2. package/dist/cli-prompt.js +2 -1
  3. package/dist/cli-revision.js +49 -0
  4. package/dist/cli-worker-task.js +15 -0
  5. package/dist/cli.js +11 -2
  6. package/dist/dashboard-html.js +2 -2
  7. package/dist/dependency-revision-execution.js +152 -0
  8. package/dist/dependency-validity.js +17 -0
  9. package/dist/final-review-role.js +17 -0
  10. package/dist/force-restate-validation.js +3 -2
  11. package/dist/host-invocation-store.js +18 -4
  12. package/dist/interactive-invocation.js +37 -5
  13. package/dist/job-pr-number-migration.js +2 -1
  14. package/dist/managed-worker-input.js +2 -1
  15. package/dist/planner-agent-roles.js +18 -0
  16. package/dist/planner-runtime.js +7 -1
  17. package/dist/planner-task-ids.js +1 -0
  18. package/dist/planner.js +11 -6
  19. package/dist/reconciler-review.js +78 -96
  20. package/dist/reconciler-runtime.js +14 -5
  21. package/dist/reconciler.js +21 -11
  22. package/dist/relay-store.js +2 -0
  23. package/dist/relayd-control.js +31 -0
  24. package/dist/review-evidence.js +44 -0
  25. package/dist/review-generation-fence.js +2 -1
  26. package/dist/review-revision-execution.js +86 -0
  27. package/dist/review-revision-merge.js +15 -0
  28. package/dist/review-revision-model.js +191 -0
  29. package/dist/review-revision-policy.js +49 -0
  30. package/dist/review-revision-settlement.js +54 -0
  31. package/dist/review-revision-stale.js +57 -0
  32. package/dist/reviewer-thread.js +41 -1
  33. package/dist/runtime-status.js +13 -4
  34. package/dist/single-job-task-control.js +1 -1
  35. package/dist/task-context.js +3 -2
  36. package/dist/worker-failure-recovery.js +2 -1
  37. package/dist/workflow/dependency-revision-v2.js +16 -0
  38. package/dist/workflow/entity-creation.js +2 -0
  39. package/dist/workflow/review-v2.js +6 -2
  40. package/dist/workflow/revision-v2.js +32 -0
  41. package/dist/workflow/task-reconcile.js +3 -0
  42. package/package.json +1 -1
  43. package/skills/agents-relay/agents/job-acceptance-reviewer.agent.md +41 -0
  44. package/skills/agents-relay/agents/planner.agent.md +6 -3
  45. package/skills/agents-relay/contracts/event-contract.md +55 -1
  46. package/skills/agents-relay/contracts/task-job-contract.md +6 -0
  47. package/workflow/dependency-revision.mmd +30 -0
  48. package/workflow/interactive-invocation.mmd +8 -2
  49. package/workflow/review-lifecycle.mmd +40 -9
  50. package/workflow/revision-lifecycle.mmd +68 -0
@@ -0,0 +1,57 @@
1
+ import { tryTransitionTaskEvent } from './task-transitions.js';
2
+ import { decideRevisionLifecycle } from './workflow/revision-v2.js';
3
+ /** Revision Graph-authorized cleanup of requests whose head OR reviewer
4
+ * execution generation became stale. Request + child disposition are atomic.
5
+ * An old-generation receipt must never cancel a currently active generation.
6
+ */
7
+ export async function staleReviewRevisions(store, job, reviewTaskId, headSha, cancelExecution, activeExecutionId) {
8
+ if (!store.mutateJob)
9
+ return;
10
+ const cancelled = [];
11
+ await store.mutateJob(job.id, current => {
12
+ if (current.review?.taskId !== reviewTaskId || current.review.headSha !== headSha)
13
+ return current;
14
+ if (activeExecutionId && current.tasks.find(task => task.id === reviewTaskId)?.executionId !== activeExecutionId)
15
+ return current;
16
+ let changed = false;
17
+ for (const request of current.reviewRevisionRequests ?? []) {
18
+ if (request.reviewTaskId !== reviewTaskId || request.reviewHeadSha !== headSha)
19
+ continue;
20
+ if (activeExecutionId && request.reviewExecutionId === activeExecutionId)
21
+ continue;
22
+ const states = { requested: 'REQUESTED', queued: 'QUEUED', running: 'RUNNING', failed: 'FAILED' };
23
+ const state = states[request.status];
24
+ if (!state)
25
+ continue;
26
+ const event = activeExecutionId ? 'review.execution_changed' : 'review.head_changed';
27
+ const decision = decideRevisionLifecycle(state, event);
28
+ if (!decision.accepted || decision.target !== 'STALE' || !decision.actions.some(action => action.id === 'revision.markStale'))
29
+ continue;
30
+ const child = request.revisionTaskId ? current.tasks.find(task => task.id === request.revisionTaskId) : undefined;
31
+ if (child && ['DRAFT', 'QUEUED', 'RUNNING'].includes(child.state)) {
32
+ const executionId = child.executionId ?? child.executionHistory?.at(-1)?.id ?? null;
33
+ if (!tryTransitionTaskEvent(child, 'cancel').accepted)
34
+ continue;
35
+ child.error = activeExecutionId
36
+ ? 'Targeted revision evidence became stale after reviewer execution changed'
37
+ : 'Targeted revision evidence became stale after review head changed';
38
+ child.leaseOwner = null;
39
+ child.leaseExpiresAt = null;
40
+ child.executionId = null;
41
+ child.updatedAt = new Date().toISOString();
42
+ if (executionId)
43
+ cancelled.push({ taskId: child.id, executionId });
44
+ }
45
+ else if (child && child.state !== 'FAILED' && child.state !== 'SUCCEEDED' && child.state !== 'CANCELLED') {
46
+ continue;
47
+ }
48
+ request.status = 'stale';
49
+ changed = true;
50
+ }
51
+ if (changed)
52
+ current.updatedAt = new Date().toISOString();
53
+ return current;
54
+ });
55
+ for (const execution of cancelled)
56
+ cancelExecution(execution.taskId, execution.executionId);
57
+ }
@@ -1,3 +1,4 @@
1
+ import { isFinalReviewAgent } from './final-review-role.js';
1
2
  import { arg, hasArg } from './cli-support.js';
2
3
  export function resolveImplementationThreadDestination(job) {
3
4
  return job.implementationThreadId ? normalizeThreadId(job.implementationThreadId, 'Job implementation thread ID') ?? null : null;
@@ -24,11 +25,20 @@ export function resolveReviewerThreadDestination(job, override) {
24
25
  const reviewerThreadId = job.reviewerThreadId ? normalizeThreadId(job.reviewerThreadId, 'Job reviewer thread ID') : undefined;
25
26
  if (reviewerThreadId)
26
27
  return { threadId: reviewerThreadId, source: 'reviewer' };
28
+ // A prior SHA-bound Reviewer is an explicit historical destination only when
29
+ // its ChatGPT route, surviving durable thread ID and URL prove compatibility.
30
+ const previous = 'tasks' in job && Array.isArray(job.tasks)
31
+ ? [...job.tasks].reverse().find(task => isFinalReviewAgent(task.agentName) && task.state === 'SUCCEEDED'
32
+ && task.adapter === 'chatgpt' && task.routing?.provider === 'chatgpt'
33
+ && task.threadId && task.threadUrl?.startsWith('https://chatgpt.com/c/') && !task.threadDeletedAt)
34
+ : undefined;
35
+ if (previous?.threadId)
36
+ return { threadId: normalizeThreadId(previous.threadId), source: 'reviewer' };
27
37
  const creatorThreadId = job.creatorThreadId ? normalizeThreadId(job.creatorThreadId, 'Job creator thread ID') : undefined;
28
38
  return creatorThreadId ? { threadId: creatorThreadId, source: 'creator' } : null;
29
39
  }
30
40
  export function prepareReviewerThreadDelivery(job, task, override) {
31
- if (task.agentName !== 'reviewer')
41
+ if (!isFinalReviewAgent(task.agentName))
32
42
  return undefined;
33
43
  const destination = resolveReviewerThreadDestination(job, override);
34
44
  if (!destination)
@@ -82,3 +92,33 @@ export async function recordThreadDelivery(store, jobId, taskId, executionId, wo
82
92
  current.chatgptThreadDelivery = { ...current.chatgptThreadDelivery, executionId, deliveredAt: new Date().toISOString() };
83
93
  await store.saveTask(current);
84
94
  }
95
+ /** Persisted safety evidence for exact original-thread reuse or explicit fallback. */
96
+ export function prepareRevisionThreadDelivery(job, child) {
97
+ if (!child.revision || child.revision.kind !== 'targeted')
98
+ return undefined;
99
+ const original = job.tasks.find(item => item.id === child.revision?.originalTaskId);
100
+ if (!original)
101
+ throw new Error('revision original Task missing');
102
+ const compatible = child.adapter === 'chatgpt' && original.adapter === 'chatgpt'
103
+ && child.routing?.provider === original.routing?.provider && original.routing?.provider === 'chatgpt'
104
+ && child.routing?.projectId === original.routing?.projectId && Boolean(child.executionId)
105
+ && Boolean(original.threadId && original.threadUrl?.startsWith('https://chatgpt.com/c/') && !original.threadDeletedAt);
106
+ const existing = child.revision.threadContinuation;
107
+ const reason = compatible ? 'matched original ChatGPT provider/project and durable live-compatible thread provenance'
108
+ : 'original thread missing/deleted or adapter/provider/project incompatible; safe full-context new execution';
109
+ if (existing && existing.decision === 'reuse' && !compatible) {
110
+ throw new Error('revision original-thread affinity changed after being selected; refuse uncertain duplicate send');
111
+ }
112
+ child.revision.threadContinuation = {
113
+ decision: compatible ? 'reuse' : 'fallback', reason, decidedAt: existing?.decidedAt ?? new Date().toISOString(),
114
+ ...(compatible ? { originalThreadId: original.threadId } : {}),
115
+ };
116
+ if (!compatible)
117
+ return undefined;
118
+ return {
119
+ kind: 'new-turn', threadId: original.threadId, threadSource: 'original-task',
120
+ requestId: `${job.id}:${child.id}:${child.executionId}`, jobId: job.id,
121
+ repository: job.repository, taskId: child.id, prNumber: job.prNumber,
122
+ executionId: child.executionId, projectId: child.routing?.projectId ?? null, deliveredAt: null,
123
+ };
124
+ }
@@ -1,3 +1,4 @@
1
+ import { isFinalReviewAgent } from './final-review-role.js';
1
2
  export function isSuperseded(task, byId) {
2
3
  if (task.state === 'CANCELLED' && task.resolution?.path === 'cancel_supersede' && task.resolution.state === 'resolved')
3
4
  return true;
@@ -8,13 +9,20 @@ export function isSuperseded(task, byId) {
8
9
  && typeof classification.reason === 'string' && Boolean(classification.reason.trim())
9
10
  && byId.get(classification.targetTaskId)?.state === 'SUCCEEDED';
10
11
  }
12
+ function staleTargetedRevisionTaskIds(job) {
13
+ return new Set((job.reviewRevisionRequests ?? [])
14
+ .filter(request => request.status === 'stale' && request.revisionTaskId)
15
+ .map(request => request.revisionTaskId));
16
+ }
11
17
  export function implementationTasks(job) {
12
18
  const byId = new Map(job.tasks.map(task => [task.id, task]));
19
+ const staleRevisions = staleTargetedRevisionTaskIds(job);
13
20
  return job.tasks.filter(task => task.kind !== 'planner'
14
- && task.agentName !== 'reviewer'
21
+ && !isFinalReviewAgent(task.agentName)
15
22
  && task.agentName !== 'troubleshooter'
16
23
  && !isSuperseded(task, byId)
17
- && task.state !== 'DRAFT');
24
+ && !staleRevisions.has(task.id)
25
+ && (task.state !== 'DRAFT' || Boolean(task.revision)));
18
26
  }
19
27
  export function implementationComplete(job) {
20
28
  const tasks = implementationTasks(job);
@@ -39,7 +47,7 @@ export function deriveJobRuntimeStatus(job, _prState = 'OPEN') {
39
47
  return 'RUNNING';
40
48
  if (implementation.some(task => task.state === 'QUEUED'))
41
49
  return 'QUEUED';
42
- const reviewRunning = job.tasks.some(task => task.agentName === 'reviewer' && task.state === 'RUNNING');
50
+ const reviewRunning = job.tasks.some(task => isFinalReviewAgent(task.agentName) && task.state === 'RUNNING');
43
51
  if (job.review?.outcome === 'approved')
44
52
  return 'MERGE_PENDING';
45
53
  if (reviewRunning)
@@ -50,7 +58,8 @@ export function deriveJobRuntimeStatus(job, _prState = 'OPEN') {
50
58
  return 'QUEUED';
51
59
  if (job.tasks.some(task => task.state === 'BLOCKED'))
52
60
  return 'BLOCKED';
53
- if (job.tasks.some(task => task.state === 'FAILED'))
61
+ const staleRevisions = staleTargetedRevisionTaskIds(job);
62
+ if (job.tasks.some(task => task.state === 'FAILED' && !staleRevisions.has(task.id)))
54
63
  return 'FAILED';
55
64
  if (job.tasks.some(task => task.state === 'DRAFT'))
56
65
  return 'WAITING';
@@ -17,7 +17,7 @@ export async function createSingleJobTaskControl(jobId, store, reconciler, bus)
17
17
  unblockTask: unblock.unblockTask,
18
18
  publishTaskUnblocked, dispatchTaskAction,
19
19
  });
20
- const allowed = new Set(['task.unblock', 'task.recover', 'task.escalate', 'task.resume-troubleshooter', 'task.classify']);
20
+ const allowed = new Set(['task.unblock', 'task.recover', 'task.escalate', 'task.resume-troubleshooter', 'task.classify', 'task.revise']);
21
21
  return async (body) => {
22
22
  if (!allowed.has(String(body.command ?? '')))
23
23
  throw new Error('Single-Job control command not supported');
@@ -1,3 +1,4 @@
1
+ import { isFinalReviewAgent } from './final-review-role.js';
1
2
  /** Resolve the execution-scoped contract from the authoritative Job snapshot. */
2
3
  export function taskExecutionContext(job, taskId, executionId) {
3
4
  if (!executionId)
@@ -9,7 +10,7 @@ export function taskExecutionContext(job, taskId, executionId) {
9
10
  throw new Error(`Stale Task execution ${taskId}/${executionId}; current state ${task.state}`);
10
11
  const relevant = task.agentName === 'troubleshooter'
11
12
  ? job.tasks.filter(item => item.id === task.parentTaskId)
12
- : task.agentName === 'reviewer' ? task.dependencies.map(id => job.tasks.find(item => item.id === id)).filter((item) => Boolean(item)) : [];
13
+ : isFinalReviewAgent(task.agentName) ? task.dependencies.map(id => job.tasks.find(item => item.id === id)).filter((item) => Boolean(item)) : [];
13
14
  return { job: { id: job.id, repository: job.repository, title: job.title, objective: job.objective,
14
15
  projectPath: job.projectPath, state: job.state }, task, currentState: task.state, resolution: task.resolution ?? null, escalation: task.escalation ?? null,
15
16
  comments: task.comments ?? [], relevantTasks: relevant.map(item => ({ id: item.id, title: item.title, state: item.state, attempt: item.attempt, executionId: item.executionId, resolution: item.resolution ?? null, escalation: item.escalation ?? null, comments: item.comments ?? [], result: item.result, error: item.error, failureReason: item.failureReason })),
@@ -18,7 +19,7 @@ export function taskExecutionContext(job, taskId, executionId) {
18
19
  }
19
20
  /** Runtime-only task history; durable task.input remains the stable objective. */
20
21
  export function taskAgentHistoryContext(job, task) {
21
- if (task.agentName !== 'troubleshooter' && task.agentName !== 'reviewer')
22
+ if (task.agentName !== 'troubleshooter' && !isFinalReviewAgent(task.agentName))
22
23
  return '';
23
24
  const related = task.agentName === 'troubleshooter'
24
25
  ? job.tasks.filter(item => item.id === task.parentTaskId)
@@ -1,3 +1,4 @@
1
+ import { isFinalReviewAgent } from './final-review-role.js';
1
2
  import { hasSafeAlternativeWorker } from './browser-worker-routing.js';
2
3
  import { codexNoStartFallbackRoute, persistChatGptPlatformFailure } from './chatgpt-platform-fallback.js';
3
4
  import { classifyChatGptPlatformFailure } from './worker-rejection.js';
@@ -17,7 +18,7 @@ export async function handleWorkerLaunchFailure(ports, jobId, taskId, executionI
17
18
  && !activeExecution?.workerStarted;
18
19
  const canRetryNoStart = noStarted && currentJob.executionMode !== 'shortcut'
19
20
  && (currentTask?.adapter === 'chatgpt' || currentTask?.adapter === 'z')
20
- && currentTask.agentName !== 'reviewer'
21
+ && !isFinalReviewAgent(currentTask.agentName)
21
22
  && currentTask.agentName !== 'troubleshooter' && currentTask.kind !== 'planner'
22
23
  && !currentTask.noStartFallback && currentTask.attempt < currentTask.maxAttempts;
23
24
  const codexFallback = canRetryNoStart
@@ -0,0 +1,16 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { GraphRuntime } from './graph-v2.js';
3
+ import { dispatchWorkflowGraphSync } from './dispatcher.js';
4
+ const boolGuard = (key) => (context) => context.durableFacts[key] === true;
5
+ export const dependencyRevisionLifecycle = new GraphRuntime(readFileSync(new URL('../../workflow/dependency-revision.mmd', import.meta.url), 'utf8'), {
6
+ states: new Set(['NONE', 'PROPOSED', 'VERIFIED', 'STALE']),
7
+ guards: Object.fromEntries(['upstreamEvidenceChanged', 'explicitValidityPolicy', 'allInputsSettled', 'notAlreadyRecorded', 'rerunRequired'].map(key => [key, boolGuard(key)])),
8
+ actions: { 'dependencyRevision.createRerun': { id: 'dependencyRevision.createRerun' }, 'dependencyRevision.createRevalidation': { id: 'dependencyRevision.createRevalidation' }, 'dependencyRevision.markStale': { id: 'dependencyRevision.markStale' } },
9
+ events: { 'dependency.reconcile': { id: 'dependency.reconcile' }, 'dependency.verified': { id: 'dependency.verified' }, 'dependency.stale': { id: 'dependency.stale' } },
10
+ });
11
+ export function decideDependencyRevision(event, facts = {}, state = 'NONE') {
12
+ return dispatchWorkflowGraphSync(dependencyRevisionLifecycle, {
13
+ graphName: 'dependency-revision', initialState: state,
14
+ input: { transport: 'event', id: event, payload: {} }, durableFacts: facts,
15
+ });
16
+ }
@@ -1,5 +1,6 @@
1
1
  import { dispatchJobLifecycleSync, dispatchTaskLifecycleSync } from './lifecycle.js';
2
2
  import { deriveTaskTitle } from '../task-title.js';
3
+ import { validateDependencyValidity } from '../dependency-validity.js';
3
4
  function dependenciesSatisfied(job, dependencies) {
4
5
  if (dependencies.length === 0)
5
6
  return true;
@@ -13,6 +14,7 @@ function validateTaskRequirements(value) {
13
14
  if (value.workerRequirements && !Array.isArray(value.workerRequirements.capabilities)) {
14
15
  throw new Error(`Task ${value.id} workerRequirements.capabilities must be an array`);
15
16
  }
17
+ validateDependencyValidity(value.dependencies, value.dependencyValidity, `Task ${value.id} dependencyValidity`);
16
18
  }
17
19
  /**
18
20
  * Canonical creation boundary for new Task entities.
@@ -17,9 +17,13 @@ export const reviewLifecycleV2 = new GraphRuntime(source, {
17
17
  noApprovedCurrentReview: boolGuard('noApprovedCurrentReview'),
18
18
  autoMerge: boolGuard('autoMerge'),
19
19
  reviewUnblocked: boolGuard('reviewUnblocked'),
20
+ targetedRevisionRequestsReady: boolGuard('targetedRevisionRequestsReady'),
21
+ targetedRevisionsVerified: boolGuard('targetedRevisionsVerified'),
22
+ reviewRoundWithinLimit: boolGuard('reviewRoundWithinLimit'),
23
+ reviewNoProgressWithinLimit: boolGuard('reviewNoProgressWithinLimit'),
20
24
  },
21
- actions: Object.fromEntries(['review.create', 'review.cancelStale', 'review.createFix', 'review.requestMerge'].map(id => [id, { id }])),
22
- events: Object.fromEntries(['reconcile', 'review.started', 'review.approved', 'review.changes_required', 'review.legacy_blocked', 'review.retry', 'head.changed'].map(id => [id, { id }])),
25
+ actions: Object.fromEntries(['review.create', 'review.cancelStale', 'review.awaitTargetedRevisions', 'review.requireOwnerResolution', 'review.requestMerge', 'review.prepareRereview'].map(id => [id, { id }])),
26
+ events: Object.fromEntries(['reconcile', 'review.started', 'review.approved', 'review.changes_required', 'review.legacy_blocked', 'review.retry', 'head.changed', 'revision.settled'].map(id => [id, { id }])),
23
27
  });
24
28
  export function reviewGraphState(outcome) {
25
29
  if (!outcome)
@@ -0,0 +1,32 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { GraphRuntime } from './graph-v2.js';
3
+ import { dispatchWorkflowGraph, dispatchWorkflowGraphSync } from './dispatcher.js';
4
+ const source = readFileSync(new URL('../../workflow/revision-lifecycle.mmd', import.meta.url), 'utf8');
5
+ const boolGuard = (name) => (context) => context.durableFacts[name] === true;
6
+ export const revisionLifecycle = new GraphRuntime(source, {
7
+ states: new Set(['NONE', 'REQUESTED', 'QUEUED', 'RUNNING', 'VERIFIED', 'FAILED', 'STALE']),
8
+ guards: {
9
+ reviewerAuthorized: boolGuard('reviewerAuthorized'),
10
+ reviewHeadCurrent: boolGuard('reviewHeadCurrent'),
11
+ originalTaskSucceeded: boolGuard('originalTaskSucceeded'),
12
+ changesRequiredRecorded: boolGuard('changesRequiredRecorded'),
13
+ taskRetryQueued: boolGuard('taskRetryQueued'),
14
+ },
15
+ actions: Object.fromEntries([
16
+ 'revision.recordRequest', 'revision.queueTask', 'revision.recordVerified',
17
+ 'revision.recordFailed', 'revision.markStale',
18
+ ].map(id => [id, { id }])),
19
+ events: Object.fromEntries([
20
+ 'revision.submit', 'revision.queue', 'revision.started', 'revision.verified',
21
+ 'revision.failed', 'revision.retry', 'review.head_changed', 'review.execution_changed',
22
+ ].map(id => [id, { id }])),
23
+ });
24
+ function args(state, event, facts) {
25
+ return { initialState: state, input: { transport: 'event', id: event, payload: {} }, durableFacts: facts, graphName: 'revision-lifecycle' };
26
+ }
27
+ export function decideRevisionLifecycle(state, event, facts = {}) {
28
+ return dispatchWorkflowGraphSync(revisionLifecycle, args(state, event, facts));
29
+ }
30
+ export async function dispatchRevisionLifecycle(state, event, facts = {}, executeAction) {
31
+ return dispatchWorkflowGraph(revisionLifecycle, { ...args(state, event, facts), executeAction });
32
+ }
@@ -1,3 +1,4 @@
1
+ import { revisionRequestReady } from '../review-revision-execution.js';
1
2
  import { dispatchTaskLifecycleSync } from './lifecycle.js';
2
3
  export function dependencyReady(task, tasks) {
3
4
  return task.dependencies.every(id => tasks.get(id)?.state === 'SUCCEEDED');
@@ -27,6 +28,8 @@ export function reconcileTaskDependencies(job) {
27
28
  for (const task of scopedTasks) {
28
29
  if (task.kind === 'planner')
29
30
  continue;
31
+ if (!revisionRequestReady(job, task))
32
+ continue;
30
33
  if (task.state === 'DRAFT' && task.unblock)
31
34
  continue;
32
35
  const ready = dependencyReady(task, tasks);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agents-relay",
3
- "version": "2.0.209",
3
+ "version": "2.0.211",
4
4
  "description": "Durable async agent jobs coordinated through GitHub pull requests",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,41 @@
1
+ ---
2
+ name: job-acceptance-reviewer
3
+ description: Independently evaluate one immutable review target against the complete Job objective and acceptance criteria.
4
+ capabilities: [review, evidence-verification]
5
+ restrictions: [no-artifact-edits, no-merge, preserve-review-target]
6
+ ---
7
+
8
+ # Job Acceptance Reviewer
9
+
10
+ Review exactly the immutable target/version specified by the Review Task. Do not silently substitute newer content or a different commit, document, artifact, or SHA.
11
+
12
+ ## Review Scope
13
+
14
+ As the automatically scheduled Final Review gate for the **whole Job**, reconstruct all material acceptance requirements from the durable Job objective and Task, then evaluate each with direct evidence. Check correctness, completeness, provenance, quality, regressions, explicit approvals and externally observable outcomes where applicable. Missing evidence is not PASS. If validation cannot complete, report task.failed. Keep review independent of implementation work.
15
+
16
+ For spec-oriented delivery, select read-only `speckit-analyze` to check
17
+ `spec.md`, `plan.md`, and `tasks.md` consistency when those artifacts exist.
18
+ Use `speckit-checklist` only as requirements-quality guidance; do not create
19
+ or edit checklists in this read-only Reviewer role. A Spec Kit analysis never
20
+ replaces independent implementation and acceptance-evidence review.
21
+
22
+ ## Targeted revision ownership
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.
27
+
28
+ ## Review Decision
29
+
30
+ Return a concrete approved or changes-required verdict tied to the declared immutable target, with attributed findings, severity and remediation steps. Do not alter artifacts, generate approvals on behalf of users, or perform publication, merges or external actions. Relay owns the review lifecycle and Task/Job completion.
31
+
32
+ ## Unified execution event
33
+
34
+ After completing the review, publish **`task.completed`**, including `data.verdict`
35
+ (`approved` or `changes-required`), the **exact immutable**
36
+ `data.head_sha`, and actionable `data.findings` for changes required. A
37
+ negative verdict is a successful review, not `task.failed`. If review
38
+ execution fails or required validation evidence is unavailable, publish `task.failed`.
39
+ Never emit `review.*` as the agent's terminal event. The event source must
40
+ match the execution identity supplied by Relay. See
41
+ the independently referenced Event Contract in the Relay Prompt (the cached Agent snapshot is not the repository directory).
@@ -27,13 +27,16 @@ For every non-satisfied objective:
27
27
 
28
28
  1. Reconstruct the end-to-end execution flow from the current durable state to objective completion.
29
29
  2. Express that flow as a compact Mermaid graph in `assessment`.
30
- 3. Mark the points in that graph that deserve durable Task boundaries.
30
+ 3. Mark only the distinct Agent responsibilities and genuine independent approval/recovery boundaries in that graph.
31
31
  4. Create only the next useful executable Task batch from those boundaries.
32
32
 
33
33
  ### Objective decomposition and convergence
34
34
 
35
- - Group implementation, deterministic tests, and self-review under the responsible Agent Task when they share one owner. Create a separate durable Task only for a genuinely independent owner, externally meaningful approval boundary, or separately recoverable outcome; do not split checks by technical layer or require a live-service test before that service can be published.
36
- - Keep technical phases and review-fix iterations within one Agent Task whenever they share responsibility, including a large multi-area implementation. Split only when different Agent roles own independent durable outcomes or a real approval/ownership boundary requires it; preserve genuine dependencies.
35
+ - **Agent-responsibility-first:** for each Plan round create at most ONE new durable Task per effective Agent role. Group design, implementation, test layers, verification and self-review into that Agent's Task internal checklist. Missing or blank `agentName` is the same `implementation` role; it does not evade deduplication.
36
+ - Split Tasks only for genuinely distinct Agent ownership (such as an independent specialist, real human approval boundary, or recovery); technical subsystems and independently testable layers are not independently owned Agents by themselves. A later Plan round may reuse an Agent role for a real revision/recovery.
37
+ - The Relay Final Review gate auto-creates `job-acceptance-reviewer`. Do not emit it as a Planner Task. The independent Final Review validates the entire Job objective, immutable head and Design Principles; worker self-review remains inside implementation work.
38
+ - Recovery/revision work belongs beneath its original artifact Task tree; a future Plan round may assign the same implementation role again when justified by new evidence.
39
+ - Group implementation, deterministic tests, and self-review under the responsible Agent Task when they share one owner; do not require a live-service test before that service can be published.
37
40
  - For a failed Task with repeated deterministic acceptance gaps, do not reissue the identical broad assignment. Identify the *missing acceptance cases*, create focused same-Job repair Tasks with valid `same_job_dependency` resolutions, and specify how their evidence unblocks the original Task. Preserve the original failed Task and failure history.
38
41
  - For event-driven workflows, require deterministic ingress/persistence, negative-path, restart and no-false-completion evidence before publishing. Do not elevate tests that require the newly published live runtime/provider/device to release-blocking Tasks merely because they are independently observable.
39
42
  - In `assessment`, show the entire remaining objective as a dependency graph, clearly distinguishing already proven work, the executable batch, subsequent verification, and Relay-owned review/merge. Never report overall `satisfied` merely because one batch has passed.
@@ -35,6 +35,60 @@ Every Implementation, Reviewer, and Troubleshooter execution publishes `task.sta
35
35
 
36
36
  A Reviewer must **not** publish unstructured `task.completed`: missing verdict or immutable head is invalid. Relay validates the Reviewer verdict; read the accepted review outcome through the matching Relay CLI.
37
37
 
38
+ ### Targeted review findings and original Task revisions
39
+
40
+ The automatically created `job-acceptance-reviewer` (historical `reviewer` records remain valid) owns the integrated Job acceptance gate, not the Implementation Agent's self-review. For blocking findings with an unambiguous original succeeded Task owner, its *active execution* calls `agents-relay task revise --repo ... --id ... --task-id ORIGINAL --review-task-id REVIEW --execution-id REVIEW_EXEC --head-sha REVIEW_SHA --request-id STABLE_ID --findings-file PATH`. A findings file is a JSON array of identified `{id, summary, evidence?}` items. Relay rejects stale execution/head, unsupported owner or conflicting request ID, and transactionally appends `review.feedback` comments and one targeted child per owner/Review round. The CLI receipt is evidence of request persistence, **not** repair or completion. The Reviewer then publishes its single correlated `task.completed` verdict `changes-required` with matching `findings` and immutable `head_sha`; the Review Graph authorizes scheduling only when all blocking findings have durable owners. No direct `task.blocked`/`task.unblocked` event is emitted by the agent.
41
+
42
+ A fix child reports its **own** correlated completion after verified repair. Downstream `dependencyValidity` policy is `order-only` by default, or explicitly `revalidate`/`rerun` per declared input. All changed upstream generations must settle before a fan-in consumer can verify or rerun. Relay derives successful revision lineage from durable Task results, then creates another fresh immutable-head Job Acceptance Review. A partially submitted message, unverified terminal, historical result or stale source SHA does not count as a fix or approval.
43
+
44
+
45
+ ## Generic interactive decision event (human review)
46
+
47
+ **Canonical type:** `task.interactive_decision`. This is a human decision for an in-progress Task (video preview, document review, image approval, etc.), **not** an Implementation terminal event or a Job Final Reviewer verdict. A UI such as Markcut is a generic publisher: it receives a caller-supplied template and fills only the declared review-result fields. It must not invent Task/Execution/source identity or a new Relay-specific event type.
48
+
49
+ **Producer event template**, based on the exact managed Task execution context (illustrative identities only):
50
+
51
+ ```json
52
+ {
53
+ "type": "task.interactive_decision",
54
+ "source": "job/556/task/producer/execution/exec-abc",
55
+ "data": {
56
+ "interactive": {
57
+ "jobId": "556",
58
+ "taskId": "producer",
59
+ "executionId": "exec-abc",
60
+ "invocationId": "review-request-123"
61
+ }
62
+ }
63
+ }
64
+ ```
65
+
66
+ The caller provides this as `markcut.preview({path, review:{delivery:"event", eventTemplate}})` or the same metadata in a Neo Mobile review request. `source` and the four template identity fields are immutable. They must match the current Job/Task/Execution. An invocation ID is a stable unique identifier for the human review request; it is not a video revision, a new Task, or a generated execution ID.
67
+
68
+ **On human Submit**, the Preview UI fills the following fields under `data.interactive`, preserving every caller-owned field:
69
+
70
+ | Field | Rule |
71
+ | --- | --- |
72
+ | `decision` | **Required**: `approved` or `changes_requested`; only the human sets it. |
73
+ | `feedback` | **Required** string: plain-language feedback, or `""` on approval. |
74
+ | `comments` | Optional structured scene/timestamp comments; do not flatten or discard when available. |
75
+ | `revision` | **Required**: immutable content SHA-256 for the reviewed video in event-only mode. |
76
+ | `contentHash` | **Required** in event-only mode; equals `revision`, exact 64 lowercase hex. |
77
+ | `revisionId` | **Required** in event-only mode: human-visible immutable preview revision identifier. |
78
+ | `previewId`, `requestId` | Optional/required respectively in event-only mode; bind the original review request. |
79
+ | `idempotencyKey` | **Required** in event-only mode, stable across delivery retries. |
80
+
81
+ For a human clicking Approve or Request Changes, **one submitted decision generates one event**. Editing individual comments does not publish events. The Preview and Neo Mobile use the same field paths. Events Bus still accepts `{type,source,data}`; via Neo MCP `events`, call `{command:"publish",args:{type,source,data}}`. A successful publish is only a transport receipt, **not** an accepted Relay decision or a completed revision.
82
+
83
+ **Relay admission and Graph semantics:**
84
+
85
+ 1. Normalize the event, validate the source identity against the data and current Task, then consult the canonical `workflow/interactive-invocation.mmd` Graph. Reject stale executions, invalid decisions/versions, wrong identities, cancelled Jobs and duplicated/conflicting decisions; record the decision atomically in Relay-owned durable state.
86
+ 2. Legacy host-bound invocations remain supported. An event-only decision may arrive **without a preceding `bindInteractiveInvocation()`** when the Job is ACTIVE, the Task is RUNNING in the exact matching Execution, and the event carries complete immutable content identity. A later video revision may be submitted for the same execution only after `changes_requested`; already decided revisions may not be replayed as new ones.
87
+ 3. `changes_requested` records actionable feedback for the owning Task. `approved` passes only the human interaction gate for **that exact content**; it does not mark a Task or Job complete. Graph-selected continuation/recovery is separate from the Event Bus receipt. A RUNNING Worker that did not register a waiting Promise must consume the accepted decision via its event-driven workflow; accepting the event alone does not create a new Agent Turn.
88
+ 4. **Limitation of an entirely unbound event**: Relay cannot independently prove that a never-before-seen content hash is the *latest* Markcut preview solely from the Event payload. The Preview provider and mobile client must reject superseded revisions before publishing; a future trusted, durable preview-generation fact is necessary if Relay must independently reject every previously unreviewed stale version. Do not present client-declared revision fields as cryptographic authorization.
89
+
90
+ `review.approved` and `review.changes_required` belong to immutable-head Job Acceptance Review; do **not** emit those or `task.completed` from a Preview UI. Consumers outside Relay may use their own event type, but managed Relay review templates must use `task.interactive_decision`.
91
+
38
92
  ## Troubleshooter human escalation
39
93
 
40
94
  Only a real user action merits escalation. Troubleshooter invokes the Relay escalation operation, specifying the required action, resolution condition, and diagnostic context. Relay durably records the human action and blocks **the Troubleshooter Task**, leaving the original failed Task `FAILED`. This is a Relay state transition, not a third agent terminal event.
@@ -45,7 +99,7 @@ See [task-recovery-flows.md](task-recovery-flows.md) for unified architecture, o
45
99
 
46
100
  Reviewer unavailable evidence is an execution failure (`task.failed`), not a blocked Task. Legacy Reviewer verdict `blocked` is normalized to failure and must dispatch Troubleshooter. Only Relay blocks a Troubleshooter during human escalation.
47
101
 
48
- A host-mediated interactive invocation is a separate Relay-controlled wait. It requires an already-bound `interactiveInvocation` with status `awaiting_decision`. It is not permission for a Worker or Reviewer to choose a blocked terminal outcome.
102
+ A host-mediated interactive invocation remains a Relay-controlled wait when explicitly bound. The event-only path above accepts complete decisions from current active executions without requiring prior binding; neither route authorizes a Worker or Reviewer to choose a blocked terminal outcome.
49
103
 
50
104
  A legacy Job-level `review: blocked` gate is reset to `pending` only after authoritative `task.unblocked` metadata exists on its bound Reviewer Task and the immutable review head still matches. The same Reviewer Task then resumes without creating a duplicate.
51
105
 
@@ -26,10 +26,16 @@ Before Task decomposition, distinguish tests achievable before publishing from l
26
26
 
27
27
  `Task.timeoutMs` is the inactivity window. Only an accepted `task.started` or newer `task.progress` event for the exact current execution resets it; duplicate, stale, and out-of-order progress does not.
28
28
 
29
+ ### Planner role-first Task granularity
30
+
31
+ New Plan rounds assign at most one newly authored Task per effective Agent role. Group design, coding, Graph changes, CLI, testing, self-review, and internal phases in the same implementation worker Task instead of decomposing by technical subsystem. A missing/blank `agentName` is normalized to `implementation` for duplicate checks. PLAN_APPLY_VALIDATION_FAILED rejects duplicate effective roles atomically, with corrective detail. Distinct Agents may own truly independent work, and a later Plan round can reuse the same role for genuine revision/recovery. The automatic SHA-bound Final Review gate creates `job-acceptance-reviewer` itself; Planner does not emit that agent as an ordinary Task. Legacy review agents and historical Plans are read compatibly.
32
+
29
33
  ### Planning graph and semantic Task tree
30
34
 
31
35
  The planning graph expresses execution flow. The Task tree expresses semantic ownership. `dependencies` answer which durable outcomes must succeed before a Task can run; `parentTaskId` answers which durable artifact or milestone owns the Task. These are independent relationships.
32
36
 
37
+ Each dependency edge may also declare `dependencyValidity`: `order-only` (the default), `revalidate` (check downstream evidence against the latest successful upstream result), or `rerun` (produce downstream verification again). Set this policy explicitly when later upstream revisions can change the validity of downstream evidence. It is execution evidence policy; it does not change Task ownership or normal DAG ordering.
38
+
33
39
  A later Planner round must inspect the existing semantic tree and attach review, revision, re-review, validation rerun, release correction, or recovery work to the existing artifact subtree. Independent milestones remain roots. `plan-N` records are provenance/history and must never be semantic parents. Existing terminal Tasks remain immutable historical evidence and may continue to own later work.
34
40
 
35
41
  ### Task input vs result
@@ -0,0 +1,30 @@
1
+ ---
2
+ title: Dependency Revision
3
+ description: Authorizes a semantic downstream verification or rerun based on explicit edge policy and a settled dependency evidence vector.
4
+ ---
5
+ flowchart LR
6
+ %% relay: initial none
7
+ none["state: NONE"]
8
+ proposed["state: PROPOSED"]
9
+ verified["state: VERIFIED"]
10
+ stale["state: STALE"]
11
+ markStale["action: dependencyRevision.markStale"]
12
+ upstreamChanged["guard: upstreamEvidenceChanged"]
13
+ explicitPolicy["guard: explicitValidityPolicy"]
14
+ allSettled["guard: allInputsSettled"]
15
+ notDuplicated["guard: notAlreadyRecorded"]
16
+ rerunRequired["guard: rerunRequired"]
17
+ createRerun["action: dependencyRevision.createRerun"]
18
+ createRevalidation["action: dependencyRevision.createRevalidation"]
19
+ none -->|on: dependency.reconcile| upstreamChanged
20
+ upstreamChanged -->|true| explicitPolicy
21
+ explicitPolicy -->|true| allSettled
22
+ allSettled -->|true| notDuplicated
23
+ notDuplicated -->|true| rerunRequired
24
+ rerunRequired -->|true| createRerun
25
+ rerunRequired -->|false| createRevalidation
26
+ createRerun --> proposed
27
+ createRevalidation --> proposed
28
+ proposed -->|on: dependency.verified| verified
29
+ proposed -->|on: dependency.stale| markStale
30
+ markStale --> stale
@@ -10,6 +10,8 @@ approved["state: approved"]
10
10
  context["guard: currentInvocation"]
11
11
  awaiting["guard: awaitingDecision"]
12
12
  revision["guard: currentRevision"]
13
+ unbound["guard: eventOnlyCurrentExecution"]
14
+ newRevision["guard: eventOnlyNextRevision"]
13
15
  duplicateChanges["guard: duplicateDelivery"]
14
16
  duplicateApproved["guard: duplicateDelivery"]
15
17
  decisionKind["guard: changesRequested"]
@@ -22,11 +24,16 @@ awaiting_decision -->|on: task.interactive_decision| context
22
24
  changes -->|on: task.interactive_decision| duplicateChanges
23
25
  approved -->|on: task.interactive_decision| duplicateApproved
24
26
  context -->|true| awaiting
25
- context -->|false| awaiting_decision
27
+ context -->|false| unbound
28
+ unbound -->|true| decisionKind
29
+ unbound -->|false| awaiting_decision
26
30
  awaiting -->|true| revision
27
31
  awaiting -->|false| awaiting_decision
28
32
  revision -->|true| decisionKind
29
33
  revision -->|false| awaiting_decision
34
+ duplicateChanges -->|false| newRevision
35
+ newRevision -->|true| decisionKind
36
+ newRevision -->|false| changes
30
37
  decisionKind -->|true| requestChanges
31
38
  decisionKind -->|false| approve
32
39
  requestChanges --> wakeChanges
@@ -34,7 +41,6 @@ wakeChanges -->|to: changes_requested| changes
34
41
  approve --> wake
35
42
  wake -->|to: approved| approved
36
43
  duplicateChanges -->|true| wakeChanges
37
- duplicateChanges -->|false| changes
38
44
  duplicateApproved -->|true| wake
39
45
  duplicateApproved -->|false| approved
40
46
  changes -->|on: task.interactive_recover| wakeChanges