agents-relay 2.0.211 → 2.0.213

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.
package/README.md CHANGED
@@ -87,7 +87,7 @@ npx agents-relay reconcile --repo OWNER/REPO --pr 12 --id job-1
87
87
  npx agents-relay job show --repo OWNER/REPO --pr 12 --id job-1
88
88
  ~~~
89
89
 
90
- Task readiness is explicit: `DRAFT` means the durable task exists but is not executable yet; `QUEUED` means Relay may execute it now; `RUNNING` means worker execution has started. Tasks created with dependencies start `DRAFT` and become `QUEUED` when those dependencies succeed. A dependency-free task created with `--draft` stays held until `task update --queue`. Once a task has run, external waiting is represented as `BLOCKED`, never by returning to `DRAFT`.
90
+ Task readiness is explicit: `DRAFT` means the durable task exists but is not executable yet; `QUEUED` means Relay may execute it now; `RUNNING` means worker execution has started. Tasks created with dependencies start `DRAFT` and become `QUEUED` when those dependencies succeed. A dependency-free task created with `--draft` stays held until `task update --queue`. After binding an interactive request, a running Task may enter `AWAITING_DECISION` and release its Worker. Approved or changes-requested decisions requeue the same Task; `BLOCKED` is reserved for Troubleshooter escalation. Ordinary `DRAFT` Tasks remain unstarted/dependency-held.
91
91
 
92
92
  Mutable draft/queued/retryable task fields can be changed in place without replacing the durable task identity. `task update` rejects `RUNNING`, `SUCCEEDED`, and `CANCELLED` tasks so active execution and terminal history cannot be rewritten. For example:
93
93
 
@@ -152,7 +152,7 @@ Use `job update` for partial mutable metadata changes on an already healthy Job
152
152
  npx agents-relay job update --repo OWNER/REPO --pr 6 --id job-6 --priority P0 --no-auto-merge
153
153
  ~~~
154
154
 
155
- Request an eligible new review with `npx agents-relay review request --repo OWNER/REPO --pr NUMBER --id JOB_ID`.
155
+ Request an eligible new review with `npx agents-relay review job --repo OWNER/REPO --pr NUMBER --id JOB_ID`.
156
156
  Pass optional `--thread-id THREAD_ID` to persist a reviewer-thread override for subsequent
157
157
  review routing. Without it, Relay uses the stored reviewer thread, then creator thread,
158
158
  or the legacy review path when neither exists. This request wakes graph-owned
@@ -135,6 +135,7 @@ export async function buildRelayWorkPrompt(input) {
135
135
  'START: After Bootstrap and the minimal event-contract preflight, publish `task.started` through the canonical events-bus before beginning Task work. Verify the publish response.',
136
136
  'PROGRESS: Publish `task.progress` with concrete progress/evidence during long-running work and before the inactivity timeout. Progress is not completion.',
137
137
  'TERMINAL: After verifying durable output, publish exactly ONE `task.completed`; if you cannot fulfill the Task, publish `task.failed` with phase, reason and evidence. Do not silently exit or treat a process/browser receipt as completion.',
138
+ 'INTERACTIVE PREVIEW: For human video review call Neo MCP `markcut.preview` once with `path` and `relay: {jobId,taskId,executionId}` using the exact execution IDs above. Neo binds the Invocation, suspends the Task, and sends the iPhone notification when the preview is ready. Do not emit `task.interactive_waiting` or a terminal event for this handoff. On resumption, read Task Context for the accepted decision and feedback.',
138
139
  'Every event MUST use the exact source above. Do not publish `task.blocked` or `task.unblocked`; those are Relay-owned states. Relay must accept the correlated event.',
139
140
  ]),
140
141
  '', '## Contexts',
package/dist/cli-help.js CHANGED
@@ -10,7 +10,8 @@ Usage:
10
10
  Commands:
11
11
  job create|update|show|list|run|shortcut-receipt|merge|unblock|cancel|pause|resume Manage SQLite-authoritative jobs with optional GitHub PRs
12
12
  task create|update|show|list|revise|classify|complete|retry|unblock|cancel Manage durable tasks
13
- review request Request graph-owned review (optional thread override)
13
+ review job Request graph-owned review (optional thread override)
14
+ review interactive Bind, wait, ready, fail or abort a host-owned human review
14
15
  artifact validate Check a JSON artifact against a project-owned JSON Schema
15
16
  plan Invoke the Planner for an existing managed Job
16
17
  plan apply Submit a validated Task Tree within one active Plan
@@ -87,16 +88,24 @@ not GitHub. Old completed Plans are reconstructed from recorded IDs and prior
87
88
  Task history; their original historical prompt bytes are not persisted. Only
88
89
  Codex currently has production Planner dispatch. Web Planner variants show the
89
90
  same Builder message targeting the other transports, not a live delivery.`,
90
- review: `Use review run for an Agent-owned outcome review, or request for the SHA-bound final review.
91
+ review: `Use review run for Agent-owned outcome review, review job for final review, or review interactive for host-owned human review.
91
92
 
92
93
  Outcome: agents-relay review run --prompt-file PATH --agents video-director,market --project-path DIR [--output PATH]
93
94
  The generic Outcome Reviewer is implicit. Exit 0=PASS, 10=CHANGE_REQUIRED, 20=BLOCKED. The caller owns repair and re-review.
94
95
 
95
96
  Request a new SHA-bound reviewer turn through the existing Relay lifecycle.
96
97
 
97
- Usage: npx agents-relay review request --repo OWNER/REPO --pr NUMBER --id JOB_ID [--thread-id THREAD_ID]
98
+ Usage: npx agents-relay review job --repo OWNER/REPO --pr NUMBER --id JOB_ID [--thread-id THREAD_ID]
98
99
 
99
- When provided, --thread-id persists a reviewer destination; otherwise the Job reviewer thread, then creator thread, then legacy review route is used. The command wakes Relay. Review Task creation, idempotency, routing and delivery remain graph/daemon-owned. Rejects in-flight/queued reviews; does not itself mark review delivered.`,
100
+ When provided, --thread-id persists a reviewer destination; otherwise the Job reviewer thread, then creator thread, then legacy review route is used. The command wakes Relay. Review Task creation, idempotency, routing and delivery remain graph/daemon-owned. Rejects in-flight/queued reviews; does not itself mark review delivered.
101
+
102
+ Managed host interaction (Node Wrapper normally calls these automatically):
103
+ agents-relay review interactive begin --id JOB --task-id TASK --execution-id EXEC
104
+ agents-relay review interactive wait --id JOB --task-id TASK --execution-id EXEC --invocation-id INV
105
+ agents-relay review interactive ready --id JOB --task-id TASK --execution-id EXEC --invocation-id INV --revision SHA256
106
+ agents-relay review interactive fail --id JOB --task-id TASK --execution-id EXEC --invocation-id INV --reason REASON
107
+ agents-relay review interactive abort --id JOB --task-id TASK --execution-id EXEC --invocation-id INV
108
+ The CLI controls the running Relay daemon; this is not a separate Worker step.`,
100
109
  artifact: `Check a JSON artifact against a project-owned JSON Schema. Read-only; does not affect Task state or planning.
101
110
 
102
111
  Usage: agents-relay artifact validate --artifact PATH --schema PATH
@@ -106,7 +115,7 @@ Exit 0 on PASS, 1 on schema mismatch or invalid input. Returns JSON { valid, err
106
115
  Usage: agents-relay review run (--prompt TEXT | --prompt-file PATH) [--project-path DIR] [--agents role,role] [--output PATH]
107
116
 
108
117
  Return codes: 0 PASS, 10 CHANGE_REQUIRED, 20 BLOCKED; CLI/worker errors fail separately.`,
109
- 'review request': `Request a review in an existing ChatGPT thread.
118
+ 'review job': `Request a review in an existing ChatGPT thread.
110
119
 
111
120
  Required: --repo OWNER/REPO --pr NUMBER --id JOB_ID.
112
121
  Optional: --thread-id THREAD_ID persists a reviewer override; omitted uses Job reviewer/creator thread or legacy route. Rejects pending reviews and wakes managed reconciliation.`,
@@ -7,14 +7,44 @@ export function reviewRequestThreadOverride(args) {
7
7
  ? normalizeThreadId(arg(values, '--thread-id'), '--thread-id')
8
8
  : undefined;
9
9
  }
10
+ /** Stable local CLI contract for Neo MCP's single-call interactive preview. */
11
+ export async function runInteractiveReviewCommand(argv) {
12
+ const [action, ...args] = argv;
13
+ const commands = ['begin', 'wait', 'ready', 'fail', 'abort'];
14
+ if (!action || !commands.includes(action))
15
+ throw new Error('review interactive requires begin|wait|ready|fail|abort');
16
+ const jobId = arg(args, '--id');
17
+ const taskId = arg(args, '--task-id');
18
+ const executionId = arg(args, '--execution-id');
19
+ const invocationId = arg(args, '--invocation-id');
20
+ if (!jobId || !taskId || !executionId)
21
+ throw new Error('review interactive requires --id --task-id --execution-id');
22
+ if (action !== 'begin' && !invocationId)
23
+ throw new Error('review interactive ' + action + ' requires --invocation-id');
24
+ const revision = arg(args, '--revision');
25
+ if (action === 'ready' && !/^[a-f0-9]{64}$/.test(revision))
26
+ throw new Error('review interactive ready requires --revision SHA256');
27
+ if (action === 'fail' && !arg(args, '--reason').trim())
28
+ throw new Error('review interactive fail requires --reason');
29
+ const body = { command: `review.interactive.${action}`, jobId, taskId, executionId };
30
+ if (action !== 'begin')
31
+ body.invocationId = invocationId;
32
+ if (action === 'ready')
33
+ body.revision = revision;
34
+ if (action === 'fail')
35
+ body.reason = arg(args, '--reason');
36
+ console.log(JSON.stringify(await relayControlCommand(args, body)));
37
+ }
10
38
  export async function runReviewCommand(action, reviewArgs) {
11
39
  if (action === 'run')
12
40
  return runOutcomeReview(reviewArgs);
13
- if (action !== 'request')
14
- throw new Error('review supports: request | run');
41
+ if (action === 'interactive')
42
+ return runInteractiveReviewCommand(reviewArgs);
43
+ if (action !== 'job')
44
+ throw new Error('review supports: job | run | interactive');
15
45
  const jobId = arg(reviewArgs, '--id');
16
46
  if (!arg(reviewArgs, '--repo') || !jobId)
17
- throw new Error('review request requires --repo and --id');
47
+ throw new Error('review job requires --repo and --id');
18
48
  const threadId = reviewRequestThreadOverride(reviewArgs);
19
49
  const job = await relayControlCommand(reviewArgs, { command: 'review.request', jobId, ...(threadId !== undefined ? { threadId } : {}) });
20
50
  console.log(JSON.stringify({ jobId: job.id, pr: job.prNumber ?? 0, reviewerThreadId: job.reviewerThreadId ?? null, status: 'requested', note: 'Relay graph will create the review Task once eligible; this is not a delivery receipt.' }, null, 2));
@@ -203,7 +203,7 @@ function shortManagedId(id,repository,kind){const parts=String(repository||'').s
203
203
  function jobForSelection(selection){return jobs.find(job=>jobSelectionKey(job)===selection)||jobs.find(job=>job.id===selection)||null;}
204
204
  function selected(){return jobForSelection(selectedJob)||jobs[0]||null;}
205
205
  function counts(tasks){const out={};for(const task of Array.isArray(tasks)?tasks:[])out[task.state]=(out[task.state]||0)+1;return out;}
206
- function compactCounts(input){const order=['RUNNING','BLOCKED','FAILED','QUEUED','DRAFT','SUCCEEDED','CANCELLED'];return order.filter(state=>input[state]).map(state=>input[state]+' '+state).join(', ')||'No tasks';}
206
+ function compactCounts(input){const order=['RUNNING','AWAITING_DECISION','BLOCKED','FAILED','QUEUED','DRAFT','SUCCEEDED','CANCELLED'];return order.filter(state=>input[state]).map(state=>input[state]+' '+state).join(', ')||'No tasks';}
207
207
  function relativeTime(timestamp){if(!timestamp)return '—';const parsed=Date.parse(timestamp);if(!Number.isFinite(parsed))return value(timestamp);const seconds=Math.max(0,Math.round((Date.now()-parsed)/1000));if(seconds<60)return 'just now';if(seconds<3600)return Math.floor(seconds/60)+'m ago';if(seconds<86400)return Math.floor(seconds/3600)+'h ago';return Math.floor(seconds/86400)+'d ago';}
208
208
  function safePrUrl(repository,prNumber){if(typeof repository!=='string'||!Number.isInteger(prNumber)||prNumber<=0)return null;const parts=repository.split('/');if(parts.length!==2)return null;const [owner,repo]=parts;if(!owner||!repo||owner==='.'||owner==='..'||repo==='.'||repo==='..')return null;if(!/^[A-Za-z0-9-]+$/.test(owner)||!/^[A-Za-z0-9._-]+$/.test(repo))return null;return 'https://github.com/'+owner+'/'+repo+'/pull/'+prNumber;}
209
209
  function safeCommitUrl(repository,sha){if(typeof repository!=='string'||typeof sha!=='string'||!/^[0-9a-f]{7,64}$/i.test(sha))return null;const parts=repository.split('/');if(parts.length!==2||!parts[0]||!parts[1])return null;return 'https://github.com/'+parts[0]+'/'+parts[1]+'/commit/'+sha;}
@@ -254,7 +254,7 @@ function attemptBudget(task){const attempt=Number(task?.attempt)||0;const max=Nu
254
254
  const JOB_STATES=['DRAFT','ACTIVE','COMPLETED','CANCELLED'];
255
255
  async function setJobState(job,state,select){if(!job||state===job.state)return;select.disabled=true;try{const params=new URLSearchParams({id:job.id,state,repo:job.repository,pr:String(job.prNumber)});const response=await fetch('/api/job-state?'+params.toString(),{method:'POST'});if(!response.ok)throw new Error(response.status+' '+response.statusText);const updated=await response.json();const index=jobs.findIndex(candidate=>jobSelectionKey(candidate)===jobSelectionKey(job));if(index>=0)jobs[index]=updated;else jobs.push(updated);renderAll();void loadEventHistory();}catch(error){select.title='Set job lifecycle state: '+error.message;select.value=job.state;}finally{select.disabled=false;}}
256
256
  function jobStateField(job){const box=element('div','detail-group');box.append(element('p','detail-label',text('Lifecycle state')));const select=document.createElement('select');select.className='job-filter job-state-select';select.dataset.state=job.state;select.setAttribute('aria-label','Job lifecycle state');for(const state of JOB_STATES)select.append(new Option(state,state));select.value=job.state;select.addEventListener('change',()=>void setJobState(job,select.value,select));box.append(select);return box;}
257
- const TASK_STATES=['DRAFT','QUEUED','RUNNING','BLOCKED','SUCCEEDED','FAILED','CANCELLED'];
257
+ const TASK_STATES=['DRAFT','QUEUED','RUNNING','AWAITING_DECISION','BLOCKED','SUCCEEDED','FAILED','CANCELLED'];
258
258
  async function setTaskState(task,state,select){const job=selected();if(!job||state===task.state)return;select.disabled=true;try{const params=new URLSearchParams({id:job.id,task:task.id,state,repo:job.repository,pr:String(job.prNumber)});const response=await fetch('/api/task-state?'+params.toString(),{method:'POST'});if(!response.ok)throw new Error(response.status+' '+response.statusText);const updated=await response.json();const index=jobs.findIndex(candidate=>jobSelectionKey(candidate)===jobSelectionKey(job));if(index>=0)jobs[index]=updated;else jobs.push(updated);renderAll();void loadEventHistory();}catch(error){select.title='Set task state: '+error.message;select.value=task.state;}finally{select.disabled=false;}}
259
259
  function taskStateField(task){const box=element('div','detail-group');box.append(element('p','detail-label',text('State')));const select=document.createElement('select');select.className='job-filter task-state-select';select.setAttribute('aria-label','Task state');for(const state of TASK_STATES)select.append(new Option(state,state));select.value=task.state;select.addEventListener('change',()=>void setTaskState(task,select.value,select));box.append(select);return box;}
260
260
  function manualOverrideField(task){const rows=Array.isArray(task.manualStateOverrides)?task.manualStateOverrides:[];const last=rows.at(-1);return field('Manual override',last?last.from+' → '+last.to+' · '+relativeTime(last.at):'—');}
@@ -77,7 +77,7 @@ export const dashboardStyles = ` <style>
77
77
  .job-status-line .badge { flex:0 0 auto; }
78
78
  .status-pill,.badge { display:inline-flex; align-items:center; border-radius:999px; padding:.06rem .42rem; min-height:1.35rem; font-size:.68rem; font-weight:800; }
79
79
  .status-pill.ok,.badge.ACTIVE,.badge.RUNNING,.badge.SUCCEEDED,.badge.COMPLETED,.badge.MERGED { background:#e5f3e9; color:var(--ok); }
80
- .status-pill.warn,.badge.BLOCKED,.badge.DRAFT,.badge.QUEUED,.badge.WAITING,.badge.OPEN { background:#fff1d2; color:var(--warn); }
80
+ .status-pill.warn,.badge.BLOCKED,.badge.DRAFT,.badge.QUEUED,.badge.WAITING,.badge.AWAITING_DECISION,.badge.OPEN { background:#fff1d2; color:var(--warn); }
81
81
  .status-pill.bad,.badge.FAILED { background:#ffe8e8; color:var(--bad); }
82
82
  .status-pill.neutral,.badge.IDLE,.badge.CANCELLED { background:#edf0f4; color:var(--muted); }
83
83
  .badge.DRAFT { background:#eef2ff; color:#3f51b5; }
package/dist/dashboard.js CHANGED
@@ -374,7 +374,7 @@ export function serveDashboard(store, port = 8787, bus, refreshMs = 300000, jobI
374
374
  const repository = url.searchParams.get('repo') ?? undefined;
375
375
  const parsedPr = Number(url.searchParams.get('pr'));
376
376
  const prNumber = Number.isInteger(parsedPr) && parsedPr > 0 ? parsedPr : undefined;
377
- const validState = ['DRAFT', 'QUEUED', 'RUNNING', 'BLOCKED', 'SUCCEEDED', 'FAILED', 'CANCELLED'].includes(requestedState);
377
+ const validState = ['DRAFT', 'QUEUED', 'RUNNING', 'AWAITING_DECISION', 'BLOCKED', 'SUCCEEDED', 'FAILED', 'CANCELLED'].includes(requestedState);
378
378
  if (req.method !== 'POST' || !/^[A-Za-z0-9_.-]+$/.test(requestedJobId) || !isTaskId(requestedTaskId) || !validState || !resolvedActions?.taskSetState) {
379
379
  res.writeHead(404);
380
380
  res.end('Task state override unavailable');
@@ -52,13 +52,13 @@ export function recordHostInvocationDecision(db, delivery, fingerprint, writeSna
52
52
  const job = snapshot?.json ? JSON.parse(snapshot.json) : null;
53
53
  const task = job?.tasks.find(item => item.id === delivery.taskId);
54
54
  const invocation = task?.interactiveInvocation;
55
- const bound = invocation && ['RUNNING', 'DRAFT'].includes(task?.state ?? '') &&
55
+ const bound = invocation && ['RUNNING', 'AWAITING_DECISION'].includes(task?.state ?? '') &&
56
56
  invocation.executionId === delivery.executionId &&
57
- (task?.executionId === delivery.executionId || task?.state === 'DRAFT') &&
57
+ (task?.executionId === delivery.executionId || task?.state === 'AWAITING_DECISION') &&
58
58
  invocation.status === 'awaiting_decision' && invocation.invocationId === delivery.invocationId &&
59
59
  invocation.revision === delivery.revision;
60
60
  // Event-only reviews are claims against an ACTIVE execution, not permission to
61
- // release an arbitrary DRAFT/failed/cancelled Task or replay an older revision.
61
+ // release an arbitrary waiting/failed/cancelled Task or replay an older revision.
62
62
  const active = job?.state === 'ACTIVE' && task?.state === 'RUNNING' &&
63
63
  task.executionId === delivery.executionId && eventOnlyReviewEligible(delivery);
64
64
  const seen = db.prepare('SELECT 1 FROM host_invocation_decision WHERE job_id=? AND task_id=? AND execution_id=? AND revision=?')
@@ -199,7 +199,7 @@ export class HostInteractiveInvocationCoordinator {
199
199
  const job = await this.options.store.loadJob(delivery.jobId);
200
200
  const task = job?.tasks.find((item) => item.id === delivery.taskId);
201
201
  if (!job || !task ||
202
- (task.executionId !== delivery.executionId && task.state !== 'DRAFT')) {
202
+ (task.executionId !== delivery.executionId && task.state !== 'AWAITING_DECISION')) {
203
203
  await this.options.store.recordHostInvocationEvent?.(delivery, 'stale', interactiveDecisionFingerprint(delivery));
204
204
  return { outcome: 'stale', reason: 'execution_not_bound' };
205
205
  }
@@ -0,0 +1,105 @@
1
+ /** Relay-owned admission/ready/failure for Neo-hosted interactive review requests. */
2
+ import { randomUUID } from 'node:crypto';
3
+ import { tryTransitionTaskEvent } from './task-transitions.js';
4
+ import { applyTaskUnblockRetrySnapshot } from './task-actions.js';
5
+ import { appendTaskComment } from './task-comments.js';
6
+ export function interactiveTemplate(jobId, taskId, executionId, invocationId) {
7
+ return { type: 'task.interactive_decision', source: `job/${jobId}/task/${taskId}/execution/${executionId}`,
8
+ data: { interactive: { jobId, taskId, executionId, invocationId } } };
9
+ }
10
+ export async function beginInteractiveReview(store, jobId, taskId, executionId) {
11
+ if (!store.mutateJob)
12
+ throw new Error('Interactive review requires atomic durable Job mutation');
13
+ const proposedId = randomUUID();
14
+ let invocationId = '';
15
+ let reused = false;
16
+ await store.mutateJob(jobId, (job) => {
17
+ const task = job.tasks.find((item) => item.id === taskId);
18
+ if (job.state !== 'ACTIVE' || !task || task.state !== 'RUNNING' || task.executionId !== executionId)
19
+ throw new Error('Interactive review requires current ACTIVE/RUNNING Task execution');
20
+ const existing = task.interactiveInvocation;
21
+ if (existing?.status === 'awaiting_decision' && existing.executionId === executionId) {
22
+ invocationId = existing.invocationId;
23
+ reused = true; // Wrapper rejects a second compile for this pending request.
24
+ }
25
+ else if (!existing || (existing.executionId !== executionId &&
26
+ (existing.status === 'changes_requested' || existing.status === 'awaiting_decision'))) {
27
+ // A new authoritative RUNNING execution replaces a stale undelivered
28
+ // invocation left behind by a crashed prior wrapper/worker. The old
29
+ // execution cannot still be current by the Task execution guard above.
30
+ // The prior decision remains in the durable decision ledger and Task
31
+ // comments. A fresh execution may start the next preview revision.
32
+ invocationId = proposedId;
33
+ task.interactiveInvocation = { invocationId, executionId, revision: `pending:${invocationId}`,
34
+ status: 'awaiting_decision', boundAt: new Date().toISOString() };
35
+ task.updatedAt = new Date().toISOString();
36
+ }
37
+ else {
38
+ throw new Error('Conflicting interactive invocation on Task');
39
+ }
40
+ return job;
41
+ });
42
+ return { jobId, taskId, executionId, invocationId, reused,
43
+ eventTemplate: interactiveTemplate(jobId, taskId, executionId, invocationId) };
44
+ }
45
+ export async function abortInteractiveReview(store, jobId, taskId, executionId, invocationId) {
46
+ if (!store.mutateJob)
47
+ throw new Error('Interactive review requires durable mutation');
48
+ await store.mutateJob(jobId, job => {
49
+ const task = job.tasks.find(t => t.id === taskId);
50
+ if (task?.state === 'RUNNING' && task.executionId === executionId &&
51
+ task.interactiveInvocation?.invocationId === invocationId &&
52
+ task.interactiveInvocation.status === 'awaiting_decision') {
53
+ task.interactiveInvocation = undefined;
54
+ task.updatedAt = new Date().toISOString();
55
+ }
56
+ return job;
57
+ });
58
+ }
59
+ export async function readyInteractiveReview(store, jobId, taskId, executionId, invocationId, revision) {
60
+ if (!/^[a-f0-9]{64}$/.test(revision))
61
+ throw new Error('Immutable revision must be SHA-256');
62
+ if (!store.mutateJob)
63
+ throw new Error('Interactive review requires durable mutation');
64
+ await store.mutateJob(jobId, job => {
65
+ const task = job.tasks.find(t => t.id === taskId);
66
+ const inv = task?.interactiveInvocation;
67
+ if (!task || task.state !== 'AWAITING_DECISION' || !inv || inv.executionId !== executionId ||
68
+ inv.invocationId !== invocationId || inv.status !== 'awaiting_decision')
69
+ throw new Error('Interactive review is not awaiting this execution/invocation');
70
+ if (inv.revision !== `pending:${invocationId}` && inv.revision !== revision)
71
+ throw new Error('Conflicting immutable review revision');
72
+ inv.revision = revision;
73
+ task.updatedAt = new Date().toISOString();
74
+ return job;
75
+ });
76
+ return { ready: true, invocationId, revision };
77
+ }
78
+ export async function failInteractiveReview(store, jobId, taskId, executionId, invocationId, reason) {
79
+ if (!store.mutateJob)
80
+ throw new Error('Interactive review requires durable mutation');
81
+ let requeued = false;
82
+ await store.mutateJob(jobId, job => {
83
+ const task = job.tasks.find(t => t.id === taskId);
84
+ const inv = task?.interactiveInvocation;
85
+ if (!task || !inv || inv.executionId !== executionId || inv.invocationId !== invocationId ||
86
+ inv.status !== 'awaiting_decision')
87
+ return job;
88
+ if (task.state === 'AWAITING_DECISION') {
89
+ if (!tryTransitionTaskEvent(task, 'interactive.resume').accepted)
90
+ throw new Error('Graph rejected review delivery failure recovery');
91
+ applyTaskUnblockRetrySnapshot(task);
92
+ task.interactiveInvocation = undefined;
93
+ task.error = null;
94
+ task.failureReason = undefined;
95
+ appendTaskComment(job, taskId, `Preview delivery failed; rerun preview request: ${reason.slice(0, 500)}`);
96
+ task.updatedAt = new Date().toISOString();
97
+ requeued = true;
98
+ }
99
+ else if (task.state === 'RUNNING' && task.executionId === executionId) {
100
+ task.interactiveInvocation = undefined;
101
+ }
102
+ return job;
103
+ });
104
+ return { requeued };
105
+ }
@@ -1,6 +1,7 @@
1
1
  import { shouldRecoverInteractiveDecision } from './interactive-invocation.js';
2
2
  import { tryTransitionTaskEvent } from './task-transitions.js';
3
3
  import { applyTaskUnblockRetrySnapshot } from './task-actions.js';
4
+ import { appendTaskComment } from './task-comments.js';
4
5
  export async function resumeInteractiveTask(store, jobId, taskId, invocationId, revision, decision) {
5
6
  if (!store.mutateJob)
6
7
  throw new Error('Interactive resume requires atomic SQLite Job mutation');
@@ -8,15 +9,20 @@ export async function resumeInteractiveTask(store, jobId, taskId, invocationId,
8
9
  await store.mutateJob(jobId, job => {
9
10
  const task = job.tasks.find(item => item.id === taskId);
10
11
  const invocation = task?.interactiveInvocation;
11
- if (!task || task.state !== 'DRAFT' || !invocation ||
12
+ if (!task || task.state !== 'AWAITING_DECISION' || !invocation ||
12
13
  invocation.invocationId !== invocationId || invocation.revision !== revision ||
13
14
  invocation.status !== decision || !invocation.decidedAt)
14
15
  return job;
15
- // Accepted interactive decisions release the same waiting Task from DRAFT.
16
- if (!tryTransitionTaskEvent(task, 'release').accepted) {
16
+ // Accepted interactive decisions requeue the same waiting Task through the canonical Graph.
17
+ if (!tryTransitionTaskEvent(task, 'interactive.resume').accepted) {
17
18
  throw new Error('Interactive Task release rejected by canonical lifecycle Graph');
18
19
  }
19
20
  applyTaskUnblockRetrySnapshot(task);
21
+ if (decision === 'changes_requested') {
22
+ // Preserve human feedback across the next Execution/Invocation binding.
23
+ const feedback = invocation.feedback?.trim() || 'Changes requested';
24
+ appendTaskComment(job, taskId, `Interactive review changes requested for revision ${revision}: ${feedback.slice(0, 1000)}`);
25
+ }
20
26
  task.error = null;
21
27
  task.failureReason = undefined;
22
28
  task.updatedAt = new Date().toISOString();
@@ -30,7 +36,7 @@ export async function recoverInteractiveDecisions(store, jobId) {
30
36
  const job = await store.load(jobId);
31
37
  let recovered = false;
32
38
  for (const task of job.tasks) {
33
- if (task.state !== 'DRAFT' || !task.interactiveInvocation?.decidedAt)
39
+ if (task.state !== 'AWAITING_DECISION' || !task.interactiveInvocation?.decidedAt)
34
40
  continue;
35
41
  const invocation = task.interactiveInvocation;
36
42
  if (invocation.status === 'awaiting_decision' || !await shouldRecoverInteractiveDecision(invocation.status))
@@ -15,7 +15,7 @@ export function jobHasActiveExecution(job, except = {}) {
15
15
  && task.leaseOwner === null && shortcut && typeof shortcut === 'object'
16
16
  && shortcut.waits
17
17
  && Object.keys(shortcut.waits).length > 0;
18
- return !durableWait && !delegatedWorker && (task.state === 'RUNNING' || (task.executionId !== null && !['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(task.state)));
18
+ return task.state !== 'AWAITING_DECISION' && !durableWait && !delegatedWorker && (task.state === 'RUNNING' || (task.executionId !== null && !['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(task.state)));
19
19
  });
20
20
  const planner = (job.plans ?? []).some(plan => plan.id !== except.planId
21
21
  && plan.executionId !== null && plan.status === 'PLANNING');
@@ -12,7 +12,7 @@ import { publishLocalCommit } from './local-commit-events.js';
12
12
  * not lifecycle storage. An explicit one-time import must use RelayStore directly.
13
13
  */
14
14
  const TASK_STATE_ORDER = {
15
- DRAFT: 0, QUEUED: 1, RUNNING: 2, BLOCKED: 3,
15
+ DRAFT: 0, QUEUED: 1, RUNNING: 2, AWAITING_DECISION: 3, BLOCKED: 4,
16
16
  SUCCEEDED: 5, FAILED: 5, CANCELLED: 5,
17
17
  };
18
18
  export class LocalAuthorityDurableStore {
@@ -102,7 +102,7 @@ export class ReconcilerRuntimeBase {
102
102
  if (normalized)
103
103
  return normalized.type === 'task.failed' ? this.applyTerminalEvent(normalized) : this.applyReviewEvent(normalized);
104
104
  }
105
- if (['task.completed', 'task.failed', 'task.blocked', 'task.cancelled'].includes(event.type)) {
105
+ if (['task.completed', 'task.failed', 'task.blocked', 'task.cancelled', 'task.interactive_waiting'].includes(event.type)) {
106
106
  const result = await this.applyTerminalEvent(event);
107
107
  if (event.type !== 'task.failed' || event.source?.watchdog !== true || event.data?.workflowEvent !== 'watchdog.failed' || result.reconcile)
108
108
  return result;
@@ -400,15 +400,17 @@ export class ReconcilerRuntimeBase {
400
400
  }
401
401
  const liveAtTerminal = this.live.get(event.task_id);
402
402
  const terminalEventExecutionId = executionIdFromSource(eventSourceId(event), event.job_id, event.task_id);
403
- const lifecycleEvent = event.type === 'task.blocked'
404
- ? (await this.store.load(event.job_id)).tasks.find(task => task.id === event.task_id)?.interactiveInvocation?.status === 'awaiting_decision'
405
- ? 'interactive.waiting' : event.type
406
- : event.type;
403
+ const lifecycleEvent = event.type;
407
404
  const transition = await withExecutionBoundary(event.job_id, event.task_id, () => this.taskTransitions.apply(event.job_id, event.task_id, lifecycleEvent, {
408
405
  eligible: (_job, task) => {
409
406
  if (!['codex', 'chatgpt', 'z', 'orchestrator'].includes(task.adapter))
410
407
  return false;
411
- if (event.type === 'task.blocked' && lifecycleEvent !== 'interactive.waiting' && (!trustedInternal || task.agentName !== 'troubleshooter'))
408
+ if (event.type === 'task.blocked' && (!trustedInternal || task.agentName !== 'troubleshooter'))
409
+ return false;
410
+ if (event.type === 'task.interactive_waiting' &&
411
+ (task.interactiveInvocation?.status !== 'awaiting_decision' ||
412
+ task.interactiveInvocation.executionId !== task.executionId ||
413
+ !isCorrelatedWorkerEvent(task, event)))
412
414
  return false;
413
415
  if (isFinalReviewAgent(task.agentName) && event.type === 'task.completed')
414
416
  return false;
@@ -427,7 +429,7 @@ export class ReconcilerRuntimeBase {
427
429
  facts: (_job, task) => {
428
430
  const processExitedAfterPublishedTerminal = task.failureReason === 'worker_exit_without_terminal_event';
429
431
  const freshEnough = processExitedAfterPublishedTerminal || isCorrelatedWorkerEvent(task, event);
430
- return { recoverableExecution: isRecoverableWatchdogFailure(task) && freshEnough, awaitingInteractiveDecision: lifecycleEvent === 'interactive.waiting' && task.interactiveInvocation?.status === 'awaiting_decision' };
432
+ return { recoverableExecution: isRecoverableWatchdogFailure(task) && freshEnough, awaitingInteractiveDecision: lifecycleEvent === 'task.interactive_waiting' && task.interactiveInvocation?.status === 'awaiting_decision' };
431
433
  },
432
434
  mutate: (job, task) => {
433
435
  const modelBacked = ['codex', 'chatgpt', 'z'].includes(task.adapter);
@@ -458,7 +460,7 @@ export class ReconcilerRuntimeBase {
458
460
  task.error = event.message || `Task ${task.id} failed`;
459
461
  task.failureReason = typeof event.data?.reason === 'string' ? event.data.reason : undefined;
460
462
  }
461
- else if (event.type === 'task.blocked' && lifecycleEvent !== 'interactive.waiting') {
463
+ else if (event.type === 'task.blocked') {
462
464
  task.error = event.message || `Task ${task.id} blocked`;
463
465
  const data = event.data ?? {};
464
466
  const head = ['candidate_head', 'candidate_head_sha', 'pr_head', 'head_sha']
@@ -478,7 +480,7 @@ export class ReconcilerRuntimeBase {
478
480
  }));
479
481
  if (!transition?.decision.accepted)
480
482
  return { applied: false, reconcile: false, reason: `${event.type}.ignored` };
481
- if (lifecycleEvent !== 'interactive.waiting')
483
+ if (lifecycleEvent !== 'task.interactive_waiting')
482
484
  await recordTerminalRouteOutcome(this.options.decisionAuditStore, transition.task, event, terminalEventExecutionId ?? null);
483
485
  if (transition.task.adapter === 'codex' && liveAtTerminal && !liveAtTerminal.processSettled && liveAtTerminal.jobId === event.job_id && (!terminalEventExecutionId || liveAtTerminal.executionId === terminalEventExecutionId)) {
484
486
  liveAtTerminal.controller.abort();
@@ -487,7 +489,7 @@ export class ReconcilerRuntimeBase {
487
489
  if (event.type === 'task.completed')
488
490
  await this.deliverContinuation(transition.job, transition.task);
489
491
  const reviewWorker = isFinalReviewAgent(transition.task.agentName);
490
- return { applied: true, reconcile: lifecycleEvent !== 'interactive.waiting' && (!reviewWorker || event.type === 'task.failed'), reason: reviewWorker ? `${event.type}.review-worker` : event.type, reconcileMode: reviewWorker || lifecycleEvent === 'interactive.waiting' ? undefined : 'detached' };
492
+ return { applied: true, reconcile: lifecycleEvent !== 'task.interactive_waiting' && (!reviewWorker || event.type === 'task.failed'), reason: reviewWorker ? `${event.type}.review-worker` : event.type, reconcileMode: reviewWorker || lifecycleEvent === 'task.interactive_waiting' ? undefined : 'detached' };
491
493
  }
492
494
  terminalWait(taskId, executionId, launchBarrier) {
493
495
  let resolve;
@@ -1,4 +1,5 @@
1
1
  import { submitTargetedRevisionRequest } from './review-revision-model.js';
2
+ import { beginInteractiveReview, abortInteractiveReview, readyInteractiveReview, failInteractiveReview } from './interactive-request.js';
2
3
  import { localSourceHead, localWorkingHead } from './local-git-merge.js';
3
4
  import { appendTaskComment } from './task-comments.js';
4
5
  import { InMemoryStore } from './store.js';
@@ -6,6 +7,7 @@ import { openLocalManagedStore } from './local-managed-store.js';
6
7
  import { relayStoreDirectory } from './relay-store.js';
7
8
  import { normalizeThreadId } from './reviewer-thread.js';
8
9
  import { publishTaskBlocked } from './cli-support.js';
10
+ import { eventFor } from './events.js';
9
11
  import { classifyFailedTask, supersedeCancelledTask } from './task-actions.js';
10
12
  import { requestTroubleshooterEscalation, resumeTroubleshooter } from './task-recovery.js';
11
13
  import { adoptExistingPullRequestJob } from './cli-job-create.js';
@@ -93,6 +95,57 @@ export function createWorkspaceControl(deps) {
93
95
  const binding = await requireLocalJobBinding(jobId);
94
96
  const store = binding.store;
95
97
  const job = await store.load(jobId);
98
+ if (command.startsWith('review.interactive.')) {
99
+ const taskId = typeof body.taskId === 'string' ? body.taskId : '';
100
+ const executionId = typeof body.executionId === 'string' ? body.executionId : '';
101
+ const invocationId = typeof body.invocationId === 'string' ? body.invocationId : '';
102
+ if (!taskId || !executionId)
103
+ throw new Error('Interactive review requires taskId and executionId');
104
+ if (command === 'review.interactive.begin')
105
+ return await beginInteractiveReview(store, jobId, taskId, executionId);
106
+ if (!invocationId)
107
+ throw new Error('Interactive review requires invocationId');
108
+ if (command === 'review.interactive.abort') {
109
+ await abortInteractiveReview(store, jobId, taskId, executionId, invocationId);
110
+ return { aborted: true };
111
+ }
112
+ if (command === 'review.interactive.wait') {
113
+ const current = (await store.load(jobId)).tasks.find((t) => t.id === taskId);
114
+ if (current?.state === 'AWAITING_DECISION' && current.interactiveInvocation?.invocationId === invocationId)
115
+ return { waiting: true, taskState: 'AWAITING_DECISION' };
116
+ if (current?.state !== 'RUNNING' || current.executionId !== executionId ||
117
+ current.interactiveInvocation?.invocationId !== invocationId)
118
+ throw new Error('Stale interactive waiting request');
119
+ const reconciler = makeReconciler(store, concurrency);
120
+ const event = eventFor(jobId, taskId, current.parentTaskId, 'task.interactive_waiting', 'waiting', 'Neo Preview requested interactive review', 'orchestrator', {}, { id: `job/${jobId}/task/${taskId}/execution/${executionId}`, component: 'neo-preview' });
121
+ try {
122
+ const outcome = await reconciler.applyEvent(event);
123
+ if (!outcome.applied)
124
+ throw new Error('Relay rejected interactive waiting event: ' + outcome.reason);
125
+ // The durable graph transition is authoritative. The ordinary bus
126
+ // records the handoff for event history; duplicate consumption is inert.
127
+ try {
128
+ await bus?.publish(event);
129
+ }
130
+ catch (error) {
131
+ process.stderr.write(`warning: interactive wait event transport: ${String(error)}\n`);
132
+ }
133
+ return { waiting: true, taskState: 'AWAITING_DECISION' };
134
+ }
135
+ finally {
136
+ await reconciler.close();
137
+ }
138
+ }
139
+ if (command === 'review.interactive.ready')
140
+ return await readyInteractiveReview(store, jobId, taskId, executionId, invocationId, typeof body.revision === 'string' ? body.revision : '');
141
+ if (command === 'review.interactive.fail') {
142
+ const result = await failInteractiveReview(store, jobId, taskId, executionId, invocationId, typeof body.reason === 'string' ? body.reason : 'Preview failed');
143
+ if (result.requeued)
144
+ await pool.reconcileLocalJob(jobId, 'interactive.preview-failed');
145
+ return result;
146
+ }
147
+ throw new Error('Unknown interactive review command');
148
+ }
96
149
  if (command === 'job.update') {
97
150
  const patch = (body.patch && typeof body.patch === 'object' ? body.patch : {});
98
151
  if ('executionMode' in patch || 'schedule' in patch)
@@ -61,7 +61,7 @@ export function deriveJobRuntimeStatus(job, _prState = 'OPEN') {
61
61
  const staleRevisions = staleTargetedRevisionTaskIds(job);
62
62
  if (job.tasks.some(task => task.state === 'FAILED' && !staleRevisions.has(task.id)))
63
63
  return 'FAILED';
64
- if (job.tasks.some(task => task.state === 'DRAFT'))
64
+ if (job.tasks.some(task => task.state === 'AWAITING_DECISION' || task.state === 'DRAFT'))
65
65
  return 'WAITING';
66
66
  if (plannerFailed)
67
67
  return 'FAILED';
@@ -59,7 +59,7 @@ export async function driveShortcutWorkers(options) {
59
59
  });
60
60
  return { status: 'COMPLETED', job };
61
61
  }
62
- if (job.tasks.some(task => task.state === 'BLOCKED'))
62
+ if (job.tasks.some(task => task.state === 'BLOCKED' || task.state === 'AWAITING_DECISION'))
63
63
  return { status: 'WAITING_EVENT', job };
64
64
  if (job.tasks.some(task => task.agentName === 'troubleshooter' && task.state === 'FAILED' && task.attempt >= task.maxAttempts))
65
65
  return { status: 'FAILED', job };
package/dist/types.js CHANGED
@@ -12,6 +12,15 @@ export function normalizeLegacyTaskLifecycle(task) {
12
12
  task.maxAttempts = Math.max(3, task.maxAttempts ?? 0, task.attempt + 1);
13
13
  task.unblock = task.unblock ? { ...task.unblock, event: 'task.unblocked' } : undefined;
14
14
  }
15
+ // Migrate persisted interactive waits from their former overloaded DRAFT state.
16
+ // Ordinary dependency-held DRAFT Tasks remain untouched.
17
+ if (legacy.state === 'DRAFT' && task.attempt > 0 && task.interactiveInvocation &&
18
+ !task.executionId && task.interactiveInvocation.boundAt && !task.unblock &&
19
+ (task.interactiveInvocation.status === 'awaiting_decision' ||
20
+ (Boolean(task.interactiveInvocation.decidedAt) &&
21
+ Date.parse(task.updatedAt) <= Date.parse(task.interactiveInvocation.decidedAt)))) {
22
+ legacy.state = 'AWAITING_DECISION';
23
+ }
15
24
  if (legacy.state === 'BLOCKED' && task.kind !== 'planner' && task.agentName !== 'troubleshooter') {
16
25
  legacy.state = 'FAILED';
17
26
  task.failureReason ??= task.failureReason === 'worker_outcome_unknown' ? task.failureReason : 'legacy_ordinary_blocked';
@@ -12,7 +12,7 @@ export const WORKFLOW_EVENT_NAMES = [
12
12
  'hold',
13
13
  'lease.expired',
14
14
  'implementation.completed',
15
- 'interactive.waiting',
15
+ 'task.interactive_waiting',
16
16
  'local.completed',
17
17
  'local.merge.requested',
18
18
  'effect.deliverLocalMerge.failed',
@@ -26,6 +26,7 @@ export const WORKFLOW_EVENT_NAMES = [
26
26
  'reconcile',
27
27
  'recovery.reopen',
28
28
  'release',
29
+ 'interactive.resume',
29
30
  'retry',
30
31
  'review.started',
31
32
  'review.approved',
@@ -45,7 +46,6 @@ export const WORKFLOW_EVENT_NAMES = [
45
46
  'effect.launchShortcut.failed',
46
47
  'effect.resumeShortcut.failed',
47
48
  'task.unblocked',
48
- 'interactive.waiting',
49
49
  'watchdog.failed',
50
50
  'worker.delivery_failed',
51
51
  'worker.start_ack_failed',
@@ -2,7 +2,7 @@ import { ConditionRegistry, booleanCondition } from './conditions.js';
2
2
  import { readFileSync } from 'node:fs';
3
3
  import { GraphRuntime } from './graph-v2.js';
4
4
  import { WORKFLOW_EFFECT_NAMES, WORKFLOW_EVENT_NAMES, WORKFLOW_MUTATION_NAMES, } from './contracts.js';
5
- const TASK_STATES = ['DRAFT', 'QUEUED', 'RUNNING', 'BLOCKED', 'SUCCEEDED', 'FAILED', 'CANCELLED'];
5
+ const TASK_STATES = ['DRAFT', 'QUEUED', 'RUNNING', 'AWAITING_DECISION', 'BLOCKED', 'SUCCEEDED', 'FAILED', 'CANCELLED'];
6
6
  const JOB_STATES = ['DRAFT', 'ACTIVE', 'COMPLETED', 'CANCELLED'];
7
7
  const conditionRegistry = new ConditionRegistry([
8
8
  ...new Set(['dependenciesSatisfied', 'dependenciesUnsatisfied', 'runnable', 'dispatchable', 'recoverableExecution', 'troubleshooterRecovery', 'troubleshooterTask', 'awaitingInteractiveDecision', 'retryAvailable', 'notMerged', 'autoMerge', 'prOpen', 'reviewDisabled', 'implementationComplete', 'headAvailable', 'mergeCapable', 'localCompletionAllowed', 'localMergeReady', 'shortcutCompletionAllowed'])
@@ -62,7 +62,7 @@ export function plannerOrchestrationFacts(job, recoverablePendingPlan) {
62
62
  hasSeedWork: !((job.plans?.length ?? 0) === 0 && job.tasks.filter(task => task.kind !== 'planner').length === 0),
63
63
  noActivePlanner: failedPlan?.manualPlanning ? false : unblockNeedsNewPlan(job) || !unconsumedUnblockTrigger(job) ? !scopedPlans.some(plan => plan.status === 'PLANNING') : false,
64
64
  noBlockedWork: Boolean(unconsumedUnblockTrigger(job)) || !scopedTasks.some(task => task.kind !== 'planner' && isEffectivelyBlocked(task)),
65
- noActiveImplementation: !scopedTasks.some(task => task.kind !== 'planner' && (['QUEUED', 'RUNNING'].includes(task.state) || (task.state === 'DRAFT' && !task.unblock))),
65
+ noActiveImplementation: !scopedTasks.some(task => task.kind !== 'planner' && (['QUEUED', 'RUNNING', 'AWAITING_DECISION'].includes(task.state) || (task.state === 'DRAFT' && !task.unblock))),
66
66
  resolutionOwnedByTroubleshooter: scopedTasks.some(task => task.kind !== 'planner' && task.resolution?.owner === 'troubleshooter' && ['active', 'waiting'].includes(task.resolution.state)),
67
67
  continuationMaterialized: Boolean(unconsumedUnblockTrigger(job)) || !(latestObjective === 'in_progress' && latestId && !job.tasks.some(task => task.kind !== 'planner' && task.planningDecisionId === latestId)),
68
68
  objectiveUnsatisfied: latestObjective !== 'satisfied',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agents-relay",
3
- "version": "2.0.211",
3
+ "version": "2.0.213",
4
4
  "description": "Durable async agent jobs coordinated through GitHub pull requests",
5
5
  "repository": {
6
6
  "type": "git",
@@ -38,7 +38,9 @@ These are alternative commands for Task and Planner executions. Both fail closed
38
38
 
39
39
  ## 3. Verify, review, and recover
40
40
 
41
- Use the pinned CLI to inspect authoritative status, Task events, comments, and review evidence. A worker's process exit, browser submission receipt, or emitted event is **not** proof of durable completion. Task agents publish `task.started`, optional `task.progress`, and exactly one correlated terminal `task.completed` or `task.failed` via the canonical `events-bus` capability. Never emit `task.blocked` as a worker terminal outcome. Read `contracts/event-contract.md` for exact identity, event semantics, and reviewer verdict payloads; implementation agents also follow `contracts/worker-self-review.md`.
41
+ Use the pinned CLI to inspect authoritative status, Task events, comments, and review evidence. For SHA-bound final Job review, use `agents-relay review job --repo OWNER/REPO --pr NUMBER --id JOB_ID [--thread-id THREAD_ID]`; for independent Agent-owned outcome review, use `agents-relay review run --prompt-file PATH --project-path DIR`.
42
+
43
+ A worker's process exit, browser submission receipt, or emitted event is **not** proof of durable completion. Task agents publish `task.started`, optional `task.progress`, and exactly one correlated terminal `task.completed` or `task.failed` via the canonical `events-bus` capability. Never emit `task.blocked` as a worker terminal outcome. Read `contracts/event-contract.md` for exact identity, event semantics, and reviewer verdict payloads; implementation agents also follow `contracts/worker-self-review.md`.
42
44
 
43
45
  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.
44
46
 
@@ -42,6 +42,34 @@ The automatically created `job-acceptance-reviewer` (historical `reviewer` recor
42
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
43
 
44
44
 
45
+ ## Interactive Task suspension
46
+
47
+ For **Neo-hosted Markcut Preview**, the Worker calls the federated `markcut.preview`
48
+ tool **once** with a video `path` and its authoritative
49
+ `relay: {jobId, taskId, executionId}` context. The Neo MCP wrapper obtains a
50
+ Relay-owned Invocation and Event Template, starts the independent Markcut
51
+ compiler, registers the Task wait, and sends the iPhone notification only after
52
+ the immutable preview is ready. The Worker does **not** publish a separate
53
+ waiting event or manage an Invocation ID. This contract applies only to Neo's
54
+ wrapped tool; standalone Markcut has no Relay or Notification dependency.
55
+
56
+ For other host adapters, after binding an Invocation a RUNNING Worker waiting
57
+ for human input publishes `task.interactive_waiting` with its exact
58
+ Job/Task/Execution source identity.
59
+ Relay checks the pending invocation, persists RUNNING -> AWAITING_DECISION,
60
+ clears the execution lease, and releases the Worker. This is a non-failure
61
+ handoff and is not a Task completion or a Troubleshooter block.
62
+ The Job stays ACTIVE; the Task does not requeue until a matching
63
+ `task.interactive_decision` is durably accepted and the Task Graph selects
64
+ `interactive.resume` -> QUEUED. Retries and daemon restarts must not create
65
+ another Task. Cancellation remains legal while awaiting a decision.
66
+
67
+ The invocation record holds immutable request/revision identity and the
68
+ decision outcome. Its status is not the authority for the Task execution
69
+ lifecycle; Task.state is. The older overloaded DRAFT waiting snapshots
70
+ are normalized to AWAITING_DECISION when the SQLite store starts.
71
+ Do not use `task.blocked` to suspend an interactive Task.
72
+
45
73
  ## Generic interactive decision event (human review)
46
74
 
47
75
  **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.
@@ -7,6 +7,7 @@ flowchart LR
7
7
  draft["state: DRAFT"]
8
8
  queued["state: QUEUED"]
9
9
  running["state: RUNNING"]
10
+ awaitingDecision["state: AWAITING_DECISION"]
10
11
  blocked["state: BLOCKED"]
11
12
  succeeded["state: SUCCEEDED"]
12
13
  failed["state: FAILED"]
@@ -168,12 +169,14 @@ leaseFailQueuedClearLease --> leaseFailQueuedClearExecution
168
169
  leaseFailQueuedClearExecution --> failed
169
170
  queued -->|on: cancel| cancelled
170
171
 
171
- running -->|on: interactive.waiting| interactiveWaitAllowed
172
+ running -->|on: task.interactive_waiting| interactiveWaitAllowed
172
173
  interactiveWaitAllowed -->|true| runningWaitClearLease
173
174
  runningWaitClearLease["action: mutation.clearLease"]
174
175
  runningWaitClearLease --> runningWaitClearExecution
175
176
  runningWaitClearExecution["action: mutation.clearExecution"]
176
- runningWaitClearExecution --> draft
177
+ runningWaitClearExecution --> awaitingDecision
178
+ awaitingDecision -->|on: interactive.resume| releaseClearError
179
+ awaitingDecision -->|on: cancel| cancelled
177
180
  running -->|on: task.blocked| runningBlockAllowed
178
181
  runningBlockAllowed -->|true| blocked
179
182
  runningBlockAllowed -->|false| failed