agents-relay 2.0.245 → 2.0.247

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.
@@ -2,7 +2,7 @@ import { createHash, randomUUID } from 'node:crypto';
2
2
  import { readFile, realpath, stat } from 'node:fs/promises';
3
3
  import { resolve, relative, isAbsolute, sep, dirname, basename, join } from 'node:path';
4
4
  import { once } from 'node:events';
5
- import { pathToFileURL } from 'node:url';
5
+ import { runShortcutRevisionNode } from './shortcut-node-revision.js';
6
6
  import { spawnOwnedProcess } from './owned-process.js';
7
7
  import { validateShortcutStageGate } from './shortcut-stage-contract.js';
8
8
  import { parseAgentGraph } from './agent-graph.js';
@@ -77,6 +77,12 @@ function taskShortcutInput(input) {
77
77
  catch { /* plain Task text remains available */ }
78
78
  return { taskInput: input };
79
79
  }
80
+ /** Task input is untrusted; only Relay may inject accepted review provenance. */
81
+ function safeShortcutTaskInput(input) {
82
+ const data = taskShortcutInput(input);
83
+ delete data.reviewDecision;
84
+ return data;
85
+ }
80
86
  function shortcutJobCompletionAllowed(job) {
81
87
  const graphs = job.tasks.filter(task => task.agentGraph);
82
88
  return job.state === 'ACTIVE' && job.executionMode === 'shortcut' && job.contentOnly === true && job.prNumber === 0 && !job.localMerge && job.autoMerge === false
@@ -222,8 +228,18 @@ export async function runAgentShortcut(options) {
222
228
  throw new Error(`Durable shortcut receipt ${nodeId} no longer matches its wait, execution, or content fingerprint`);
223
229
  }
224
230
  state.inFlight ??= {};
225
- if (currentTask.state === 'QUEUED' && Object.keys(state.inFlight).length > 0)
226
- throw new Error('Shortcut checkpoint contains an interrupted module execution; refusing automatic replay');
231
+ // An accepted human invocation authorizes replay of only its in-flight node.
232
+ let resumedReview = null;
233
+ if (currentTask.state === 'QUEUED' && Object.keys(state.inFlight).length > 0) {
234
+ const pending = Object.entries(state.inFlight);
235
+ const inv = currentTask.interactiveInvocation;
236
+ if (pending.length !== 1 || !inv?.decidedAt || !['approved', 'changes_requested'].includes(inv.status) ||
237
+ inv.executionId !== pending[0][1] || !/^[a-f0-9]{40}$/.test(inv.revision))
238
+ throw new Error('Shortcut checkpoint contains an interrupted module execution; refusing automatic replay');
239
+ resumedReview = { nodeId: pending[0][0], status: inv.status,
240
+ revision: inv.revision, invocationId: inv.invocationId, feedback: inv.feedback, comments: inv.comments };
241
+ delete state.inFlight[pending[0][0]];
242
+ }
227
243
  state.artifactHashes ??= {};
228
244
  for (const [nodeId, hashes] of Object.entries(state.artifactHashes ?? {}))
229
245
  for (const [artifact, expected] of Object.entries(hashes)) {
@@ -339,6 +355,11 @@ export async function runAgentShortcut(options) {
339
355
  heartbeatInFlight = true;
340
356
  void store.mutateJob(job.id, fresh => {
341
357
  const t = fresh.tasks.find(item => item.id === task.id);
358
+ // A managed Preview has already suspended this exact Task and released
359
+ // its lease. Do not reinterpret that authorized handoff as lease loss.
360
+ if (t?.state === 'AWAITING_DECISION' && t.interactiveInvocation?.status === 'awaiting_decision' &&
361
+ t.interactiveInvocation.executionId === currentTask.executionId)
362
+ return fresh;
342
363
  if (fresh.state !== 'ACTIVE' || fresh.pause || !t || t.state !== 'RUNNING' || t.executionId !== currentTask.executionId || t.leaseOwner !== owner) {
343
364
  throw new Error('Shortcut execution lease was fenced during module execution');
344
365
  }
@@ -350,9 +371,7 @@ export async function runAgentShortcut(options) {
350
371
  const stopHeartbeat = () => { clearInterval(heartbeat); options.signal?.removeEventListener('abort', abortFromCaller); };
351
372
  const emit = (event) => options.onNodeEvent?.({ ...event, timestamp: new Date().toISOString() });
352
373
  try {
353
- // The existing Graph executor owns node readiness for both code and model
354
- // nodes. Model nodes execute using Relay's existing durable Worker adapter,
355
- // never by routing the entire Agent Graph to one Worker.
374
+ // Graph executor runs Script and model nodes through their respective adapters.
356
375
  const missing = shortcuts.filter(item => !item.path);
357
376
  if (missing.length && !options.runModelNode)
358
377
  return await fail(`Incomplete Agent Graph shortcut coverage: ${missing.map(item => item.nodeId).join(', ')}`);
@@ -380,11 +399,13 @@ export async function runAgentShortcut(options) {
380
399
  return runCommand(args, cwd, executionAbort.signal);
381
400
  };
382
401
  emit({ nodeId: id, type: 'progress', data: { phase: shortcut ? 'shortcut.invoke' : 'worker.invoke' } });
402
+ const review = resumedReview?.nodeId === id ? resumedReview : null;
383
403
  const raw = await raceAbort(shortcut
384
- ? (async () => {
385
- const module = await import(pathToFileURL(shortcut).href);
386
- return module.run({ input: { ...taskShortcutInput(task.input), projectPath, jobId: job.id, taskId: task.id, nodeId: id, agent: node.agent, predecessorOutputs }, signal: executionAbort.signal, runCommand: trackedRunCommand });
387
- })()
404
+ ? runShortcutRevisionNode({ path: shortcut, signal: executionAbort.signal,
405
+ input: { ...safeShortcutTaskInput(task.input), projectPath, jobId: job.id, taskId: task.id, nodeId: id,
406
+ agent: node.agent, predecessorOutputs }, runCommand: trackedRunCommand,
407
+ modelNode: { id, agent: node.agent, predecessorOutputs, executionId: currentTask.executionId, signal: executionAbort.signal },
408
+ review, runModelNode: options.runModelNode, validOutput })
388
409
  : options.runModelNode({ id, agent: node.agent, predecessorOutputs, executionId: currentTask.executionId, signal: executionAbort.signal }), executionAbort.signal);
389
410
  if (leaseHeartbeatError)
390
411
  throw new Error(`Shortcut lease renewal failed: ${String(leaseHeartbeatError)}`);
@@ -393,6 +414,8 @@ export async function runAgentShortcut(options) {
393
414
  const result = raw;
394
415
  if (result.status === 'WAITING_EVENT' && result.event && typeof result.event === 'object')
395
416
  return { id, value: result };
417
+ if (result.status === 'WAITING_REVIEW')
418
+ return { id, value: result };
396
419
  if (!validOutput(result))
397
420
  throw new Error('shortcut returned an invalid COMPLETED result contract');
398
421
  const artifactPaths = Array.isArray(result.artifacts) ? result.artifacts
@@ -447,6 +470,23 @@ export async function runAgentShortcut(options) {
447
470
  return { id, value: null, error: error instanceof Error ? error.message : String(error) };
448
471
  }
449
472
  }));
473
+ const reviewWait = outcomes.find(result => result.value?.status === 'WAITING_REVIEW');
474
+ if (reviewWait) {
475
+ // The wrapper already persisted RUNNING -> AWAITING_DECISION and
476
+ // released the lease. Keep inFlight as a durable fence until the
477
+ // approved/changes-requested invocation requeues this same Task.
478
+ if (batch.length !== 1)
479
+ return await fail('Interactive Shortcut Review requires a single in-flight node');
480
+ const durable = await findTask();
481
+ if (durable.state !== 'AWAITING_DECISION' || durable.interactiveInvocation?.status !== 'awaiting_decision' ||
482
+ durable.interactiveInvocation.executionId !== currentTask.executionId)
483
+ return await fail('Shortcut Review did not bind the current Task through hostInvocation');
484
+ emit({ nodeId: reviewWait.id, type: 'waiting', data: { invocationId: durable.interactiveInvocation.invocationId,
485
+ executionId: durable.interactiveInvocation.executionId } });
486
+ stopHeartbeat();
487
+ return { outcome: { status: 'WAITING_REVIEW', nodeId: reviewWait.id,
488
+ invocationId: durable.interactiveInvocation.invocationId }, task: durable, fallback: false };
489
+ }
450
490
  const failed = outcomes.find(result => !result.value);
451
491
  for (const result of outcomes) {
452
492
  if (!result.value) {
@@ -87,7 +87,25 @@ export async function runShortcutJobCommand(args, id, makeRunner) {
87
87
  const projectRoot = await resolveManagedProjectPath(noGitHubMode(args) ? undefined : loaded.job.repository, arg(args, '--project-path') || loaded.job.projectPath || '', workspaceRoot);
88
88
  const projectPath = resolveRepositoryProjectPath(projectRoot, loaded.job.projectPath);
89
89
  const globalRoot = arg(args, '--global-root') || process.env.AGENTS_HOME || undefined;
90
- const missing = await missingShortcutNodes(task.agentGraph, projectPath, arg(args, '--shared-root') || process.env.AGENTS_RELAY_SHARED_ROOT || undefined, workspaceRoot, globalRoot);
90
+ const sharedRoot = arg(args, '--shared-root') || process.env.AGENTS_RELAY_SHARED_ROOT || undefined;
91
+ // The first trusted *explicit* invocation binds only resolved directories,
92
+ // not a command. Daemon recovery must never guess a Project path or execute
93
+ // argv serialized by an untrusted Task.
94
+ if (!loaded.store.mutateJob)
95
+ throw new Error('Shortcut Runner requires atomic context binding');
96
+ await loaded.store.mutateJob(id, current => {
97
+ if (current.executionMode !== 'shortcut' || current.state !== 'ACTIVE')
98
+ throw Error('Cannot bind context to an inactive Shortcut');
99
+ const ctx = { projectPath, workspaceRoot, ...(sharedRoot ? { sharedRoot } : {}), ...(globalRoot ? { globalRoot } : {}), noGitHub: noGitHubMode(args) };
100
+ const old = current.shortcutRunnerContext;
101
+ if (old && (old.projectPath !== ctx.projectPath || old.workspaceRoot !== ctx.workspaceRoot ||
102
+ old.sharedRoot !== ctx.sharedRoot || old.globalRoot !== ctx.globalRoot || old.noGitHub !== ctx.noGitHub))
103
+ throw Error('Shortcut context changed from its original trusted launch; refusing inconsistent resume');
104
+ if (!old)
105
+ current.shortcutRunnerContext = ctx;
106
+ return current;
107
+ });
108
+ const missing = await missingShortcutNodes(task.agentGraph, projectPath, sharedRoot, workspaceRoot, globalRoot);
91
109
  const previous = task.result?.data?.shortcut;
92
110
  if (previous?.workerFallback === true)
93
111
  throw new Error('Legacy whole-Graph Worker fallback is not compatible with per-node Shortcut execution; retain its original recovery ownership');
@@ -96,15 +114,18 @@ export async function runShortcutJobCommand(args, id, makeRunner) {
96
114
  process.once('SIGINT', onInterrupt);
97
115
  process.once('SIGTERM', onInterrupt);
98
116
  const execute = async (bus) => {
99
- const workerReconciler = missing.length && bus && makeRunner ? makeRunner(loaded.store, bus) : undefined;
117
+ const hasSemanticRevision = task?.state === 'QUEUED' && task.interactiveInvocation?.status === 'changes_requested' &&
118
+ Boolean(task.interactiveInvocation.decidedAt) &&
119
+ Object.values(task.result?.data?.shortcut?.inFlight ?? {}).includes(task.interactiveInvocation.executionId);
120
+ const workerReconciler = (missing.length || hasSemanticRevision) && bus && makeRunner ? makeRunner(loaded.store, bus) : undefined;
100
121
  const unwatch = workerReconciler ? await workerReconciler.watch(id) : undefined;
101
122
  try {
102
123
  const result = await runAgentShortcut({ store: loaded.store, job: loaded.job, task, projectPath,
103
- sharedRoot: arg(args, '--shared-root') || process.env.AGENTS_RELAY_SHARED_ROOT || undefined,
124
+ sharedRoot,
104
125
  workspaceRoot, globalRoot,
105
126
  concurrency: integerArg(args, '--concurrency', 4), signal: controller.signal,
106
127
  ...(resumeReceiptSelected ? { resumeReceiptSelected: true } : {}),
107
- ...(missing.length ? { runModelNode: node => {
128
+ ...((missing.length || hasSemanticRevision) ? { runModelNode: node => {
108
129
  if (!workerReconciler)
109
130
  throw new Error('Model-backed node requires a reachable EventBus and existing Relay Worker Adapter');
110
131
  return runShortcutModelNode({ store: loaded.store, reconciler: workerReconciler, jobId: id, parentTaskId: task.id, node });
@@ -115,7 +136,7 @@ export async function runShortcutJobCommand(args, id, makeRunner) {
115
136
  const checkpoint = result.task.result?.data?.shortcut;
116
137
  process.exitCode = checkpoint?.terminal?.status === 'TIMED_OUT' ? 4 : checkpoint?.terminal?.status === 'INTERRUPTED' ? 5 : 1;
117
138
  }
118
- else if (result.outcome.status === 'WAITING_EVENT')
139
+ else if (result.outcome.status === 'WAITING_EVENT' || result.outcome.status === 'WAITING_REVIEW')
119
140
  process.exitCode = 3;
120
141
  }
121
142
  finally {
@@ -124,7 +145,7 @@ export async function runShortcutJobCommand(args, id, makeRunner) {
124
145
  }
125
146
  };
126
147
  try {
127
- if (missing.length)
148
+ if (missing.length || (task?.state === 'QUEUED' && task.interactiveInvocation?.status === 'changes_requested' && Boolean(task.interactiveInvocation.decidedAt)))
128
149
  await withEventBus(args, execute);
129
150
  else
130
151
  await execute(undefined);
package/dist/pool.js CHANGED
@@ -9,6 +9,7 @@ import { pendingTroubleshooterTasks, pendingTroubleshooterReopens, pendingTroubl
9
9
  import { reviewPlanReady, reviewWorkSettled } from './review-replan.js';
10
10
  import { decideReviewLifecycle } from './workflow/review-v2.js';
11
11
  import { isFinalReviewAgent } from './final-review-role.js';
12
+ import { shortcutAutoResumeTask } from './shortcut-auto-resume.js';
12
13
  const RANK = { P0: 0, P1: 1, P2: 2, P3: 3 };
13
14
  export function compareJobPriority(a, b) { return RANK[a.priority ?? 'P2'] - RANK[b.priority ?? 'P2'] || a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id); }
14
15
  export function runnableManagedJobs(items) { return items.filter(item => item.job.state === 'ACTIVE' || item.job.projectionRecovery?.status === 'repairing').map(item => item.job).sort(compareJobPriority); }
@@ -58,17 +59,21 @@ export class RepositoryWorkerPool {
58
59
  makeReconciler;
59
60
  localInventory;
60
61
  resolveLocalJob;
62
+ resumeShortcut;
61
63
  running = false;
62
64
  pending = false;
63
65
  reconcileLocks = new Map();
64
66
  coordinator;
65
67
  dispatchTail = Promise.resolve();
66
68
  watchedBus;
67
- constructor(concurrency, makeReconciler, localInventory, resolveLocalJob) {
69
+ shortcutResumes = new Set();
70
+ shortcutResumeFailures = new Map();
71
+ constructor(concurrency, makeReconciler, localInventory, resolveLocalJob, resumeShortcut) {
68
72
  this.concurrency = concurrency;
69
73
  this.makeReconciler = makeReconciler;
70
74
  this.localInventory = localInventory;
71
75
  this.resolveLocalJob = resolveLocalJob;
76
+ this.resumeShortcut = resumeShortcut;
72
77
  const reportCoordinatorError = (error, signal) => {
73
78
  observability().record({
74
79
  stage: 'reconcile', event: 'reconcile.coordinator_failed', level: 'error', outcome: 'failed',
@@ -149,17 +154,42 @@ export class RepositoryWorkerPool {
149
154
  if (signal.event.type === 'github.webhook')
150
155
  continue;
151
156
  const outcome = await reconciler.applyEvent(signal.event);
152
- shouldReconcile ||= outcome.reconcile;
157
+ // A host may commit an accepted decision to SQLite before publishing its
158
+ // durable EventBus wake. Its replay is idempotently ignored by the Task
159
+ // reducer, but the shared Pool must still inspect QUEUED Shortcut work.
160
+ shouldReconcile ||= outcome.reconcile || signal.event.type === 'task.interactive_decision';
153
161
  }
154
162
  if (shouldReconcile)
155
163
  await this.reconcileLocalJob(jobId, 'local.signal');
156
164
  }
157
165
  async reconcileDiscovered(discovered) {
158
166
  const jobs = runnableManagedJobs(discovered);
159
- let capacity = Math.max(0, this.concurrency - jobs.filter(job => jobHasActiveExecution(job)).length);
167
+ let capacity = Math.max(0, this.concurrency - jobs.filter(job => jobHasActiveExecution(job)).length - this.shortcutResumes.size);
160
168
  for (const job of jobs) {
161
169
  if (capacity <= 0)
162
170
  break;
171
+ // The shared Pool resumes only previously launched human-reviewed
172
+ // Shortcut Tasks. A Shortcut created but never explicitly run is inert.
173
+ if (job.executionMode === 'shortcut') {
174
+ const resume = shortcutAutoResumeTask(job);
175
+ if (resume && this.resumeShortcut && !this.shortcutResumes.has(job.id)) {
176
+ const invocationId = resume.interactiveInvocation.invocationId;
177
+ const old = this.shortcutResumeFailures.get(job.id);
178
+ const previous = old?.invocationId === invocationId ? old : undefined;
179
+ if (!previous || (previous.attempts < 3 && previous.retryAfter <= Date.now())) {
180
+ this.shortcutResumes.add(job.id);
181
+ void this.resumeShortcut(job, resume).then(() => this.shortcutResumeFailures.delete(job.id)).catch(error => {
182
+ const attempts = (previous?.attempts ?? 0) + 1;
183
+ this.shortcutResumeFailures.set(job.id, { invocationId, attempts, retryAfter: Date.now() + Math.min(120000, 10000 * 2 ** (attempts - 1)) });
184
+ observability().record({ stage: 'reconcile', event: 'shortcut.resume_failed', level: 'warn', outcome: 'failed',
185
+ message: 'Shortcut automatic resume failed (' + attempts + '/3): ' + errorMessage(error),
186
+ correlation: { jobId: job.id, repository: job.repository, taskId: resume.id } });
187
+ }).finally(() => this.shortcutResumes.delete(job.id));
188
+ capacity--;
189
+ }
190
+ }
191
+ continue;
192
+ }
163
193
  const store = await this.requireLocalStore(job.id);
164
194
  await store.hydrate?.(job);
165
195
  const ready = job.tasks.filter(task => (task.state === 'QUEUED' && task.executionId === null) || (task.state === 'DRAFT' && task.dependencies.length > 0)).length;
package/dist/relayd.js CHANGED
@@ -10,6 +10,7 @@ import { ZAdapter } from './z-adapter.js';
10
10
  import { CodexThreadContinuation, CommandContinuation, WebhookContinuation } from './continuation.js';
11
11
  import { serveDashboard } from './dashboard.js';
12
12
  import { RepositoryWorkerPool } from './pool.js';
13
+ import { resumeShortcutInOwnedProcess } from './shortcut-auto-resume-process.js';
13
14
  import { Reconciler } from './reconciler.js';
14
15
  import { dashboardManagedJobs, GitHubStore, InMemoryStore, resolvePullRequest } from './store.js';
15
16
  import { GitHubProjectionWriter } from './projected-store.js';
@@ -391,7 +392,7 @@ export async function runDaemon(argv) {
391
392
  })();
392
393
  return githubBindingSyncInFlight;
393
394
  };
394
- const pool = new RepositoryWorkerPool(concurrency, makeReconciler, inventoryFromLocal, localJobBinding);
395
+ const pool = new RepositoryWorkerPool(concurrency, makeReconciler, inventoryFromLocal, localJobBinding, resumeShortcutInOwnedProcess);
395
396
  const initial = cachedOverviews;
396
397
  const fallback = initial[0]?.job;
397
398
  const dashboardStore = fallback ? (await requireLocalJobBinding(fallback.id)).store : new InMemoryStore();
@@ -0,0 +1,27 @@
1
+ import { once } from 'node:events';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { spawnOwnedProcess } from './owned-process.js';
4
+ /** The shared Scheduler launches only the trusted current Relay CLI. Paths are
5
+ * bound during the first explicit Shortcut run, never parsed from Task text. */
6
+ export async function resumeShortcutInOwnedProcess(job, task) {
7
+ const ctx = job.shortcutRunnerContext;
8
+ if (!ctx?.projectPath || !ctx.workspaceRoot)
9
+ throw Error('Unbound Shortcut launch context');
10
+ const args = [fileURLToPath(new URL('./cli.js', import.meta.url)),
11
+ 'job', 'run', '--mode', 'shortcut', '--repo', job.repository, '--id', job.id, '--task-id', task.id,
12
+ '--project-path', ctx.projectPath, '--workspace-root', ctx.workspaceRoot,
13
+ ...(ctx.sharedRoot ? ['--shared-root', ctx.sharedRoot] : []),
14
+ ...(ctx.globalRoot ? ['--global-root', ctx.globalRoot] : []),
15
+ ...(ctx.noGitHub ? ['--no-github', '--shortcut-local'] : [])];
16
+ const child = spawnOwnedProcess(process.execPath, args, { invocation: 'shortcut.auto-resume',
17
+ correlation: { jobId: job.id, repository: job.repository, taskId: task.id },
18
+ spawn: { cwd: ctx.projectPath, stdio: ['ignore', 'pipe', 'pipe'], env: process.env } });
19
+ const errors = [];
20
+ child.stderr?.on('data', chunk => { const text = String(chunk); if (errors.join('').length < 4000)
21
+ errors.push(text.slice(0, 500)); });
22
+ child.stdout?.resume();
23
+ const [code, signal] = await once(child, 'close');
24
+ // Exit 3 is a persisted WAITING_REVIEW/WAITING_EVENT, not worker failure.
25
+ if (signal || (code !== 0 && code !== 3))
26
+ throw Error(`Shortcut runner stopped (${signal ?? code}): ${errors.join('').slice(-1500)}`);
27
+ }
@@ -0,0 +1,24 @@
1
+ /** The first Shortcut launch is ALWAYS explicit. Only a previously suspended,
2
+ * human-decided node may be auto-resumed through the shared Relay Worker Pool.
3
+ * No separate queue, timer, or scheduler owns these Task transitions.
4
+ */
5
+ export function shortcutAutoResumeTask(job) {
6
+ if (job.executionMode !== 'shortcut' || job.contentOnly !== true || job.state !== 'ACTIVE' ||
7
+ job.pause || !job.shortcutRunnerContext || !job.shortcutRunnerContext.projectPath || !job.shortcutRunnerContext.workspaceRoot ||
8
+ !job.shortcutExecutionStartedAt || !Number.isFinite(Date.parse(job.shortcutExecutionStartedAt)))
9
+ return null;
10
+ for (const task of job.tasks) {
11
+ if (!task.agentGraph || task.state !== 'QUEUED' || task.executionId !== null || task.leaseOwner !== null)
12
+ continue;
13
+ const review = task.interactiveInvocation;
14
+ const cp = task.result?.data?.shortcut;
15
+ const pending = Object.entries(cp?.inFlight ?? {});
16
+ if (pending.length !== 1 || !review?.decidedAt ||
17
+ !['approved', 'changes_requested'].includes(review.status) ||
18
+ review.executionId !== pending[0][1] || !/^[a-f0-9]{40}$/.test(review.revision) ||
19
+ typeof review.invocationId !== 'string' || !review.invocationId)
20
+ continue;
21
+ return task;
22
+ }
23
+ return null;
24
+ }
@@ -0,0 +1,21 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ /** Preserve Script determinism: semantic owner feedback is resolved by its
3
+ * existing Agent Worker before the Script validates and requests re-review. */
4
+ export async function runShortcutRevisionNode(options) {
5
+ const { review } = options;
6
+ const module = await import(pathToFileURL(options.path).href);
7
+ let revisionWork;
8
+ if (review?.status === 'changes_requested') {
9
+ if (!options.runModelNode)
10
+ throw Error('Request Changes requires a bound Agent Worker; Shortcut script cannot perform a semantic revision');
11
+ revisionWork = await options.runModelNode({ ...options.modelNode, reviewDecision: { status: 'changes_requested',
12
+ revision: review.revision, invocationId: review.invocationId, feedback: review.feedback, comments: review.comments } });
13
+ if (!options.validOutput(revisionWork))
14
+ throw Error('Revision Worker did not return a completed Artifact result');
15
+ }
16
+ return module.run({ input: { ...options.input,
17
+ ...(review ? { reviewDecision: { status: review.status, revision: review.revision, invocationId: review.invocationId,
18
+ feedback: review.feedback, comments: review.comments } } : {}),
19
+ ...(revisionWork ? { reviewRevision: revisionWork } : {}) },
20
+ signal: options.signal, runCommand: options.runCommand });
21
+ }
@@ -11,13 +11,22 @@ export async function runShortcutModelNode(options) {
11
11
  throw new Error('Model nodes require the durable Relay SQLite store');
12
12
  if (!/^[A-Za-z_][\w.-]*$/.test(node.id))
13
13
  throw new Error('Invalid shortcut model node ID');
14
- const taskId = `shortcut-${parentTaskId}-${node.id}`;
14
+ const review = node.reviewDecision;
15
+ if (review && (!/^[a-f0-9]{40}$/.test(review.revision) || !/^[0-9a-f-]{36}$/i.test(review.invocationId)))
16
+ throw new Error('Invalid semantic Revision identity');
17
+ const taskId = `shortcut-${parentTaskId}-${node.id}${review ? '-revision-' + review.invocationId : ''}`;
15
18
  const initial = await store.load(jobId);
16
19
  const parent = initial.tasks.find(t => t.id === parentTaskId);
17
20
  if (!parent || parent.state !== 'RUNNING' || parent.executionId !== node.executionId || !parent.leaseOwner)
18
21
  throw new Error('Model node parent execution is not leased by Shortcut Runner');
19
22
  if (parent.output?.kind !== 'file' || !isAbsolute(parent.output.path))
20
23
  throw new Error('Model nodes require a canonical absolute Task output directory');
24
+ if (review) {
25
+ const recorded = parent.interactiveInvocation;
26
+ if (!recorded?.decidedAt || recorded.status !== 'changes_requested' ||
27
+ recorded.invocationId !== review.invocationId || recorded.revision !== review.revision)
28
+ throw new Error('Revision Worker requires the actual accepted Relay review');
29
+ }
21
30
  const runRoot = dirname(parent.output.path);
22
31
  const declaredRun = parent.input.match(/^- Canonical run:\s*(\/[^\r\n]+)$/m)?.[1]?.trim();
23
32
  if (declaredRun && resolve(declaredRun) !== resolve(runRoot))
@@ -44,9 +53,10 @@ export async function runShortcutModelNode(options) {
44
53
  if (state.nodes?.[node.id] || state.inFlight?.[node.id] !== node.executionId)
45
54
  throw new Error('Model node is no longer pending in the current Graph execution');
46
55
  state.workerNodes ??= {};
47
- if (state.workerNodes[node.id] && state.workerNodes[node.id] !== taskId)
56
+ const workerKey = review ? `${node.id}:revision:${review.invocationId}` : node.id;
57
+ if (state.workerNodes[workerKey] && state.workerNodes[workerKey] !== taskId)
48
58
  throw new Error('Conflicting durable Worker node mapping');
49
- state.workerNodes[node.id] = taskId;
59
+ state.workerNodes[workerKey] = taskId;
50
60
  const existing = current.tasks.find(t => t.id === taskId);
51
61
  if (existing) {
52
62
  if (existing.parentTaskId !== parentTaskId || existing.agentName !== node.agent || existing.output?.kind !== 'file' || existing.output.path !== outputPath)
@@ -57,12 +67,13 @@ export async function runShortcutModelNode(options) {
57
67
  const body = JSON.stringify({
58
68
  source: 'shortcut-graph-node', jobId, parentTaskId, nodeId: node.id, agent: node.agent,
59
69
  predecessorOutputs: node.predecessorOutputs,
70
+ ...(review ? { reviewDecision: review, revisionOf: { nodeId: node.id, commitSha: review.revision } } : {}),
60
71
  originalInput: active.input,
61
72
  ...(declaredRun ? { canonicalRunPath: declaredRun } : {}),
62
73
  ...(sourceRef ? { sourceEvidencePath: sourceRef } : {}),
63
74
  requiredResult: { status: 'COMPLETED', output: {}, artifacts: [] },
64
75
  outputPath,
65
- instruction: 'Execute only this Agent role for this DAG node. The ONLY structured DAG predecessor values are predecessorOutputs; never infer an undeclared sibling dependency. If canonicalRunPath is declared, read the authorized original source manifest and prior stage artifact files there as required by the project Agent/Stage contract; inspect and validate their real contents, source provenance, hashes and use rights. These files are allowed canonical run evidence, not an alternative DAG predecessor result and not proof of human approval. Do not claim they are absent merely because they are not repeated in predecessorOutputs. Write {status:"COMPLETED",output:{...},artifacts:[]} to outputPath only after meeting stage acceptance and send a correlated task.completed event. If a real prerequisite is unavailable, report the specific verified blocker and task.failed; do not fabricate, publish, approve or infer new permissions.'
76
+ instruction: review ? 'Revise only the existing Stage Artifact according to the human feedback within the Agent role, preserving source provenance; never invent evidence, approve, or publish. The parent Shortcut re-verifies and re-previews.' : 'Execute only this Agent role for this DAG node. The ONLY structured DAG predecessor values are predecessorOutputs; never infer an undeclared sibling dependency. If canonicalRunPath is declared, read the authorized original source manifest and prior stage artifact files there as required by the project Agent/Stage contract; inspect and validate their real contents, source provenance, hashes and use rights. These files are allowed canonical run evidence, not an alternative DAG predecessor result and not proof of human approval. Do not claim they are absent merely because they are not repeated in predecessorOutputs. Write {status:"COMPLETED",output:{...},artifacts:[]} to outputPath only after meeting stage acceptance and send a correlated task.completed event. If a real prerequisite is unavailable, report the specific verified blocker and task.failed; do not fabricate, publish, approve or infer new permissions.'
66
77
  });
67
78
  current.tasks.push(createTaskEntity(current, {
68
79
  jobId, id: taskId, title: `Shortcut model node ${node.id}`, kind: 'work', parentTaskId,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agents-relay",
3
- "version": "2.0.245",
3
+ "version": "2.0.247",
4
4
  "description": "Durable async agent jobs coordinated through GitHub pull requests",
5
5
  "repository": {
6
6
  "type": "git",
@@ -63,16 +63,14 @@ configuration returns `technical_failure`; it must never be treated as
63
63
  `resolved` or `needs_user`. This direct escalation command is distinct from
64
64
  `task escalate`, which is the durable Troubleshooter/human-blocker transition.
65
65
 
66
- For human Preview/Review, use the **existing** Relay
67
- `review.interactive.begin/wait/ready/fail/abort` lifecycle. Relay provides the
68
- execution-bound invocation and decision contract and emits a provider-neutral
69
- `task.interactive_waiting` with `source.component: interactive-review`.
70
- Preview media compilation, delivery (for example Markcut to Neo Mobile),
71
- notifications, and UI are owned by the calling project/provider. Never invent
72
- an approval from a compile receipt or a preview handoff, never replace the
73
- exact event template with a provider-specific event, and never create an
74
- unnecessary separate Preview Provider framework. Consult the project's own
75
- Review/Preview contract for delivery and version binding.
66
+ Human Preview uses `review.interactive.begin/wait/ready/fail/abort` and the
67
+ canonical `task.interactive_waiting` contract. The provider owns media and
68
+ notifications; a delivery receipt is **not approval**. Never forge event
69
+ identity or create a separate Review Provider. For Shortcut Preview, invoke
70
+ the tool with the **original Task identity**, return `WAITING_REVIEW` after
71
+ Relay durably suspends it, then resume that Task after an authenticated
72
+ decision. Neo Preview commits the Run Git revision automatically; no separate
73
+ checkpoint CLI. See `contracts/event-contract.md` for details.
76
74
 
77
75
  ## 5. Manage services when needed
78
76
 
@@ -58,6 +58,8 @@ Job/Task/Execution source identity.
58
58
  Relay checks the pending invocation, persists RUNNING -> AWAITING_DECISION,
59
59
  clears the execution lease, and releases the Worker. This is a non-failure
60
60
  handoff and is not a Task completion or a Troubleshooter block.
61
+ For Shortcut modules, a host-wrapped `markcut.preview` call uses the **original Shortcut Task identity**, not a reviewer child. The module returns `WAITING_REVIEW` only after the host has durably transitioned that Task to `AWAITING_DECISION`. The foreground runner exits with waiting status, keeping the in-flight node as a durable replay fence. After an authenticated accepted decision, the lifecycle requeues that same Task. The existing Relay Worker Pool automatically re-enters the trusted Shortcut Runner only for Jobs with a prior explicit launch and an exact accepted review/in-flight execution. It never auto-starts draft or unlaunched Shortcut Jobs and does not add a separate Scheduler. On `changes_requested`, a Script node invokes its Agent's normal durable model Worker to revise existing Artifacts, then re-verifies and opens a new human Preview. `approved` continues the Graph. Nonhuman `WAITING_EVENT` receipts are a different mechanism.
62
+
61
63
  The Job stays ACTIVE; the Task does not requeue until a matching
62
64
  `task.interactive_decision` is durably accepted and the Task Graph selects
63
65
  `interactive.resume` -> QUEUED. Retries and daemon restarts must not create