agents-relay 2.0.202 → 2.0.204

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.
@@ -0,0 +1,93 @@
1
+ import { join } from 'node:path';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { recordShortcutReceipt, runAgentShortcut, shortcutResumeEvent } from './agent-shortcut.js';
4
+ import { parseAgentGraph } from './agent-graph.js';
5
+ import { noGitHubMode } from './no-github.js';
6
+ import { dispatchTaskAction } from './task-actions.js';
7
+ import { resolveManagedProjectPath, resolveRepositoryProjectPath, resolveWorkspaceRoot } from './workspace.js';
8
+ import { arg, hasArg, integerArg, publishWake, saveLocal, storeFor, textOption, withEventBus } from './cli-support.js';
9
+ function assertSqliteShortcutArgs(args) {
10
+ if (args.some(value => value === '--file' || value.startsWith('--file=')))
11
+ throw new Error('Shortcut commands require the authoritative SQLite Relay store; --file is unsupported');
12
+ }
13
+ export async function runShortcutJobCommand(args, id, repo) {
14
+ assertSqliteShortcutArgs(args);
15
+ if (arg(args, '--mode') !== 'shortcut')
16
+ throw new Error('job run requires --mode shortcut');
17
+ const loaded = await storeFor(args);
18
+ if (loaded.localFile !== null || !loaded.store.mutateJob || !loaded.store.reserveWorkflowLaunch)
19
+ throw new Error('Shortcut execution requires the authoritative SQLite Relay store');
20
+ const job = loaded.job;
21
+ if (job.executionMode !== 'shortcut' || job.contentOnly !== true)
22
+ throw new Error('job run shortcut mode must be durably selected at Job creation with --shortcut-execution before Tasks are materialized');
23
+ const taskId = arg(args, '--task-id');
24
+ if (!taskId)
25
+ throw new Error('job run requires --task-id');
26
+ let task = job.tasks.find(item => item.id === taskId);
27
+ if (!task)
28
+ throw new Error(`Task ${taskId} not found`);
29
+ if (task.result?.data?.shortcut && typeof task.result.data.shortcut === 'object'
30
+ && task.result.data.shortcut.workerFallback === true)
31
+ throw new Error('Task is durably routed to the original Worker; let the Reconciler dispatch it instead of running shortcut mode');
32
+ if (!task.agentGraph && !hasArg(args, '--agent-graph-file'))
33
+ throw new Error(`Task ${taskId} has no Agent Graph; set it on the Task or pass --agent-graph-file`);
34
+ const graphOverride = hasArg(args, '--agent-graph-file') ? await textOption(args, '--agent-graph', '--agent-graph-file') : undefined;
35
+ if (graphOverride) {
36
+ parseAgentGraph(graphOverride);
37
+ if (!loaded.store.mutateJob)
38
+ throw new Error('Persisting an Agent Graph override requires atomic SQLite mutation');
39
+ await loaded.store.mutateJob(id, current => {
40
+ const durable = current.tasks.find(item => item.id === taskId);
41
+ if (!durable)
42
+ throw new Error(`Task ${taskId} not found`);
43
+ if (durable.agentGraph && durable.agentGraph !== graphOverride)
44
+ throw new Error('Cannot replace a durable Task Agent Graph');
45
+ if (!durable.agentGraph && durable.state !== 'QUEUED')
46
+ throw new Error('Agent Graph must be persisted before Task execution starts');
47
+ durable.agentGraph = graphOverride;
48
+ return current;
49
+ });
50
+ loaded.job = await loaded.store.load(id);
51
+ task = loaded.job.tasks.find(item => item.id === taskId);
52
+ if (!task)
53
+ throw new Error(`Task ${taskId} disappeared`);
54
+ }
55
+ const workspaceRoot = await resolveWorkspaceRoot(arg(args, '--workspace-root') || undefined);
56
+ const projectRoot = await resolveManagedProjectPath(noGitHubMode(args) ? undefined : repo, arg(args, '--project-path') || loaded.job.projectPath || '', workspaceRoot);
57
+ const projectPath = resolveRepositoryProjectPath(projectRoot, loaded.job.projectPath);
58
+ if (hasArg(args, '--event-json'))
59
+ shortcutResumeEvent(arg(args, '--event-json'));
60
+ const result = await runAgentShortcut({ store: loaded.store, job: loaded.job, task, projectPath,
61
+ neoRoot: arg(args, '--neo-root') || join(workspaceRoot, 'neo'), concurrency: integerArg(args, '--concurrency', 4) });
62
+ let outputTask = result.task;
63
+ if (result.fallback) {
64
+ await dispatchTaskAction(loaded.store, { id: 'task.retry', jobId: id, taskId });
65
+ const queued = await loaded.store.load(id);
66
+ outputTask = queued.tasks.find(item => item.id === taskId) ?? outputTask;
67
+ await withEventBus(args, bus => publishWake(bus, queued, taskId, 'Shortcut unavailable or invalid; handed to normal Worker execution'));
68
+ }
69
+ else if (result.outcome.status === 'FAILED') {
70
+ await withEventBus(args, bus => publishWake(bus, loaded.job, taskId, 'Shortcut stopped after possible effects; reconcile its durable Troubleshooter recovery'));
71
+ }
72
+ console.log(JSON.stringify({ outcome: result.outcome, fallbackQueued: result.fallback, task: outputTask }, null, 2));
73
+ }
74
+ export async function recordShortcutReceiptCommand(args, id) {
75
+ assertSqliteShortcutArgs(args);
76
+ const taskId = arg(args, '--task-id'), nodeId = arg(args, '--node-id'), waitId = arg(args, '--wait-id');
77
+ const revision = arg(args, '--revision'), executionId = arg(args, '--execution-id'), outputFile = arg(args, '--output-file');
78
+ const contentSha256 = arg(args, '--content-sha256');
79
+ if (!taskId || !nodeId || !waitId || !revision || !executionId || !outputFile || !contentSha256)
80
+ throw new Error('job shortcut-receipt requires --task-id --node-id --wait-id --revision --execution-id --output-file --content-sha256');
81
+ if (outputFile === '-')
82
+ throw new Error('--output-file requires a local file path');
83
+ const { store, localFile } = await storeFor(args);
84
+ if (localFile !== null || !store.mutateJob || !store.reserveWorkflowLaunch)
85
+ throw new Error('Shortcut receipts require the authoritative SQLite Relay store');
86
+ const bytes = await readFile(outputFile);
87
+ const output = JSON.parse(bytes.toString('utf8'));
88
+ const receipt = await recordShortcutReceipt(store, { jobId: id, taskId, nodeId, waitId, revision, executionId, contentSha256, output });
89
+ const updated = await store.load(id);
90
+ await saveLocal(localFile, updated);
91
+ await withEventBus(args, bus => publishWake(bus, updated, taskId, 'Shortcut receipt recorded in Relay SQLite'));
92
+ console.log(JSON.stringify({ receipt: { ...receipt, output: undefined }, jobId: id, taskId }, null, 2));
93
+ }
package/dist/cli.js CHANGED
@@ -26,7 +26,6 @@ import { AgentObjectivePlanner, CommandObjectivePlanner } from './planner.js';
26
26
  import { applyTaskHoldAction, applyTaskQueueAction, dispatchTaskAction } from './task-actions.js';
27
27
  import { applyJobActivateAction, applyJobCancelAction } from './job-actions.js';
28
28
  import { classifyFailedTask } from './task-actions.js';
29
- import { resolveExecutionContext } from './execution-context.js';
30
29
  import { startServiceExternalActionFlusher } from './service-external-actions.js';
31
30
  import { handleServicePublication } from './service-publication.js';
32
31
  import { ensureLocalJobSourceBranch, prepareLocalJobExecutionWorktree, resolveManagedProjectPath, resolveRepositoryProjectPath, resolveWorkspaceRoot, taskRequiresManagedWorktree } from './workspace.js';
@@ -50,6 +49,8 @@ import { recoveryDiagnosisFromArgs, workerTaskFromArgs } from './cli-worker-task
50
49
  import { requestTroubleshooterEscalation, resumeTroubleshooter } from './task-recovery.js';
51
50
  import { pauseJob, resumeJob } from './job-pause.js';
52
51
  export { ensureManagedGitHubJob } from './cli-job-create.js';
52
+ import { recordShortcutReceiptCommand, runShortcutJobCommand } from './cli-shortcut.js';
53
+ import { runContextCommand } from './cli-context.js';
53
54
  async function runManagedTaskCommand(action, args) {
54
55
  const jobId = arg(args, '--id');
55
56
  if (!jobId)
@@ -59,6 +60,8 @@ async function runManagedTaskCommand(action, args) {
59
60
  throw new Error(`task ${action} requires --task-id`);
60
61
  let result;
61
62
  if (action === 'create') {
63
+ if (hasArg(args, '--shortcut-execution') && hasArg(args, '--initial-plan'))
64
+ throw new Error('--shortcut-execution currently requires create-only job creation; materialize Graph Tasks after the durable shortcut policy is stored');
62
65
  const job = await relayControlJob(args, jobId);
63
66
  if (['COMPLETED', 'CANCELLED'].includes(job.state))
64
67
  throw new Error(`Cannot create task on terminal job ${job.id} (${job.state})`);
@@ -377,26 +380,8 @@ async function runTaskCommand(action, args) {
377
380
  await saveLocal(localFile, job);
378
381
  console.log(JSON.stringify(task, null, 2));
379
382
  }
380
- async function runContextCommand(action, args) {
381
- if (action !== 'resolve')
382
- throw new Error(usage);
383
- const projectPath = arg(args, '--project-path');
384
- if (!projectPath)
385
- throw new Error('context resolve requires --project-path');
386
- const roleValue = arg(args, '--role', 'orchestrator');
387
- const roles = ['orchestrator', 'planner', 'reviewer', 'worker', 'nested-worker'];
388
- if (!roles.includes(roleValue))
389
- throw new Error('--role must be orchestrator, planner, reviewer, worker, or nested-worker');
390
- const context = await resolveExecutionContext(projectPath, roleValue, {
391
- workspaceRoot: arg(args, '--workspace-root') || undefined,
392
- globalRoot: arg(args, '--global-root') || undefined,
393
- explicitSkills: arg(args, '--skills').split(',').filter(Boolean),
394
- explicitAgents: arg(args, '--agents').split(',').filter(Boolean),
395
- });
396
- console.log(JSON.stringify(context, null, 2));
397
- }
398
383
  async function runJobCommand(action, args) {
399
- if (!['create', 'adopt', 'update', 'show', 'list', 'merge', 'unblock', 'cancel', 'pause', 'resume'].includes(action))
384
+ if (!['create', 'adopt', 'update', 'show', 'list', 'merge', 'unblock', 'cancel', 'pause', 'resume', 'run', 'shortcut-receipt'].includes(action))
400
385
  throw new Error(usage);
401
386
  const repo = repository(args);
402
387
  let createObjective;
@@ -451,6 +436,8 @@ async function runJobCommand(action, args) {
451
436
  if (prValue && (!Number.isInteger(prNumber) || (prNumber ?? 0) <= 0))
452
437
  throw new Error('--pr must be a positive integer');
453
438
  if (action === 'create') {
439
+ if (hasArg(args, '--shortcut-execution') && hasArg(args, '--initial-plan'))
440
+ throw new Error('--shortcut-execution requires create-only Job creation; materialize Agent Graph Tasks only after durable shortcut policy is stored');
454
441
  rejectRemovedJobOptions(args);
455
442
  const objective = createObjective ?? '';
456
443
  if (hasArg(args, '--local-merge-source') !== hasArg(args, '--local-merge-target'))
@@ -458,11 +445,20 @@ async function runJobCommand(action, args) {
458
445
  const result = await relayControlCommand(args, { command: 'job.create', repository: repo, initialPlan: hasArg(args, '--initial-plan'), options: {
459
446
  id: id || undefined, idempotencyKey: arg(args, '--idempotency-key') || undefined, title: arg(args, '--title') || undefined, objective: objective || undefined, projectPath: arg(args, '--project-path') || undefined,
460
447
  priority: priority(args), tag: jobTagFromArgs(args), reviewEnabled: !hasArg(args, '--no-review'), continuation: continuation(args),
448
+ executionMode: hasArg(args, '--shortcut-execution') ? 'shortcut' : undefined,
461
449
  reviewerThreadId: hasArg(args, '--reviewer-thread-id') ? arg(args, '--reviewer-thread-id') : undefined, creatorThreadId: hasArg(args, '--creator-thread-id') ? arg(args, '--creator-thread-id') : undefined, implementationThreadId: hasArg(args, '--implementation-thread-id') ? arg(args, '--implementation-thread-id') : undefined,
462
450
  } });
463
451
  console.log(JSON.stringify(result, null, 2));
464
452
  return;
465
453
  }
454
+ if (action === 'run') {
455
+ await runShortcutJobCommand(args, id, repo);
456
+ return;
457
+ }
458
+ if (action === 'shortcut-receipt') {
459
+ await recordShortcutReceiptCommand(args, id);
460
+ return;
461
+ }
466
462
  const job = await relayControlJob(args, id);
467
463
  if (action === 'unblock') {
468
464
  const reason = arg(args, '--reason');
@@ -517,6 +513,15 @@ async function runJobCommand(action, args) {
517
513
  job.reviewEnabled = true;
518
514
  if (hasArg(args, '--no-review'))
519
515
  job.reviewEnabled = false;
516
+ if (hasArg(args, '--content-only')) {
517
+ if (hasArg(args, '--no-content-only'))
518
+ throw new Error('choose only one of --content-only or --no-content-only');
519
+ if (job.prNumber !== 0 || job.localMerge || job.autoMerge === true || job.reviewEnabled === true || job.review)
520
+ throw new Error('--content-only requires a Job with no PR, merge, or review requirements; set --no-auto-merge --no-review first');
521
+ job.contentOnly = true;
522
+ }
523
+ if (hasArg(args, '--no-content-only'))
524
+ job.contentOnly = false;
520
525
  if (hasArg(args, '--reviewer-thread-id'))
521
526
  job.reviewerThreadId = normalizeThreadId(arg(args, '--reviewer-thread-id'), '--reviewer-thread-id');
522
527
  if (hasArg(args, '--creator-thread-id'))
@@ -530,7 +535,7 @@ async function runJobCommand(action, args) {
530
535
  job.continuation = next;
531
536
  }
532
537
  const patch = {};
533
- for (const key of ['title', 'objective', 'projectPath', 'priority', 'tag', 'autoMerge', 'reviewEnabled', 'reviewerThreadId', 'creatorThreadId', 'implementationThreadId', 'continuation', 'localMerge'])
538
+ for (const key of ['title', 'objective', 'projectPath', 'priority', 'tag', 'autoMerge', 'reviewEnabled', 'contentOnly', 'reviewerThreadId', 'creatorThreadId', 'implementationThreadId', 'continuation', 'localMerge'])
534
539
  patch[key] = job[key];
535
540
  console.log(JSON.stringify(await relayControlCommand(args, { command: 'job.update', jobId: id, patch }), null, 2));
536
541
  }
@@ -63,6 +63,7 @@ export async function eventsBusHistoryPage(jobId, taskId, limit, options = {}, e
63
63
  body.events.length > boundedLimit)
64
64
  throw new Error('events-bus history returned an unexpected Job, order, or events payload');
65
65
  const events = [];
66
+ const rows = [];
66
67
  let previous = order === 'asc' ? after : Number.POSITIVE_INFINITY;
67
68
  for (const row of body.events) {
68
69
  const cursor = row?.cursor;
@@ -73,6 +74,7 @@ export async function eventsBusHistoryPage(jobId, taskId, limit, options = {}, e
73
74
  throw new Error('events-bus history returned invalid, out-of-order, or cross-Task event data');
74
75
  previous = cursor;
75
76
  events.push(event);
77
+ rows.push({ cursor, event });
76
78
  }
77
79
  const nextCursor = body.next_cursor;
78
80
  const expectedCursor = body.events.length
@@ -81,7 +83,7 @@ export async function eventsBusHistoryPage(jobId, taskId, limit, options = {}, e
81
83
  if (typeof nextCursor !== 'number' || !Number.isSafeInteger(nextCursor) || nextCursor !== expectedCursor ||
82
84
  (order === 'asc' && events.length > 0 && nextCursor <= after))
83
85
  throw new Error('events-bus history returned an invalid or non-advancing cursor');
84
- return { events, nextCursor };
86
+ return { events, rows, nextCursor };
85
87
  }
86
88
  /** Existing newest-first reader for dashboard and runtime summaries. */
87
89
  export async function eventsBusHistory(jobId, taskId, limit, env = process.env) {
@@ -4,8 +4,16 @@
4
4
  * occupies it by its RUNNING state even though it has no execution UUID.
5
5
  */
6
6
  export function jobHasActiveExecution(job, except = {}) {
7
- const worker = job.tasks.some(task => task.id !== except.taskId
8
- && (task.state === 'RUNNING' || (task.executionId !== null && !['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(task.state))));
7
+ const worker = job.tasks.some(task => {
8
+ if (task.id === except.taskId)
9
+ return false;
10
+ const shortcut = task.result?.data?.shortcut;
11
+ const durableWait = job.executionMode === 'shortcut' && job.contentOnly === true && task.state === 'RUNNING'
12
+ && task.leaseOwner === null && shortcut && typeof shortcut === 'object'
13
+ && shortcut.waits
14
+ && Object.keys(shortcut.waits).length > 0;
15
+ return !durableWait && (task.state === 'RUNNING' || (task.executionId !== null && !['SUCCEEDED', 'FAILED', 'CANCELLED'].includes(task.state)));
16
+ });
9
17
  const planner = (job.plans ?? []).some(plan => plan.id !== except.planId
10
18
  && plan.executionId !== null && plan.status === 'PLANNING');
11
19
  return worker || planner;
package/dist/pool.js CHANGED
@@ -221,7 +221,7 @@ export class RepositoryWorkerPool {
221
221
  // GitHub transport is observational. It must never wake lifecycle execution.
222
222
  if (event.type === 'github.webhook')
223
223
  return;
224
- const wake = event.type === 'job.wake' || event.type === 'review.created' || event.type === 'planner.completed';
224
+ const wake = event.type === 'job.wake' || event.type === 'review.created' || event.type === 'planner.completed' || event.type === 'shortcut.result';
225
225
  if (!lifecycle && !wake)
226
226
  return;
227
227
  await this.coordinator.acceptTransport({
@@ -0,0 +1,18 @@
1
+ import { resolveExecutionContext } from './execution-context.js';
2
+ export async function resolveTaskContext(store, options, job, task, role, projectPathOverride) {
3
+ const projectPath = projectPathOverride ?? (options.projectPathForJob ? await options.projectPathForJob(job) : task.routing?.cwd ?? process.cwd());
4
+ return resolveExecutionContext(projectPath, role, {
5
+ ...(options.executionContextRoots ?? {}),
6
+ registeredAgents: await store.listAgents(),
7
+ runtimes: options.adapters.map(adapter => ({ name: adapter.name, id: adapter.id, capabilities: [...adapter.capabilities] })),
8
+ });
9
+ }
10
+ export async function resolvePlannerContext(store, options, job, planning) {
11
+ const routingCwd = 'routing' in planning ? planning.routing?.cwd : undefined;
12
+ const projectPath = options.projectPathForJob ? await options.projectPathForJob(job) : routingCwd ?? process.cwd();
13
+ return resolveExecutionContext(projectPath, 'planner', {
14
+ ...(options.executionContextRoots ?? {}),
15
+ registeredAgents: await store.listAgents(),
16
+ runtimes: options.adapters.map(adapter => ({ name: adapter.name, id: adapter.id, capabilities: [...adapter.capabilities] })),
17
+ });
18
+ }
@@ -0,0 +1,66 @@
1
+ import { eventFor } from './events.js';
2
+ import { runAgentShortcut } from './agent-shortcut.js';
3
+ import { applyTaskRetryAction } from './task-actions.js';
4
+ import { resolveExecutionContext } from './execution-context.js';
5
+ async function executeShortcut(store, options, job, task, emit) {
6
+ const projectPath = options.projectPathForJob ? await options.projectPathForJob(job, task) : task.routing?.cwd ?? process.cwd();
7
+ const context = await resolveExecutionContext(projectPath, 'worker', options.executionContextRoots ?? {});
8
+ const result = await runAgentShortcut({ store, job, task, projectPath, neoRoot: context.project.neoRoot ?? undefined, concurrency: options.maxConcurrent,
9
+ ...(task.state === 'RUNNING' && task.leaseOwner === null ? { resumeReceiptSelected: true } : {}) });
10
+ if (result.fallback) {
11
+ await applyTaskRetryAction(result.task);
12
+ await store.saveTask(result.task);
13
+ }
14
+ else if (result.outcome.status === 'FAILED') {
15
+ const message = 'Shortcut stopped after possible effects; reconcile its durable Troubleshooter recovery';
16
+ await emit(eventFor(job.id, task.id, task.parentTaskId, 'job.wake', 'queued', message, 'orchestrator', { failureReason: 'shortcut_requires_recovery' }));
17
+ }
18
+ }
19
+ export async function launchShortcutEffect(store, options, jobId, taskId, emit) {
20
+ if (!taskId)
21
+ throw new Error('Shortcut launch requires a Task ID');
22
+ const job = await store.load(jobId);
23
+ const task = job.tasks.find(item => item.id === taskId);
24
+ if (!task || task.state !== 'QUEUED' || task.executionId !== null)
25
+ return;
26
+ if (!task.agentGraph)
27
+ throw new Error('Task Graph selected shortcut launch without a persisted Agent Graph');
28
+ await executeShortcut(store, options, job, task, emit);
29
+ }
30
+ export async function resumeShortcutEffect(store, options, jobId, taskId, _data, emit) {
31
+ if (!taskId)
32
+ throw new Error('Shortcut result action requires a Task ID');
33
+ const job = await store.load(jobId);
34
+ const task = job.tasks.find(item => item.id === taskId);
35
+ if (!task)
36
+ throw new Error(`Task ${taskId} not found`);
37
+ // The runner reads only the atomically persisted receipt from this Task's SQLite checkpoint.
38
+ if (task.state !== 'RUNNING' || task.leaseOwner !== null)
39
+ return;
40
+ try {
41
+ await executeShortcut(store, options, job, task, emit);
42
+ }
43
+ catch (error) {
44
+ const message = error instanceof Error ? error.message : String(error);
45
+ if (message === 'Shortcut wait claim was fenced by another execution' || message === `Task ${task.id} has an active or unreconciled execution lease`)
46
+ return;
47
+ throw error;
48
+ }
49
+ }
50
+ export async function resumeShortcutEventWaits(store, _options, jobId, dispatchResume, _emit) {
51
+ const job = await store.load(jobId);
52
+ if (job.executionMode !== 'shortcut' || job.contentOnly !== true || job.state !== 'ACTIVE' || job.pause)
53
+ return;
54
+ for (const task of job.tasks.filter(item => item.state === 'RUNNING' && item.leaseOwner === null && item.executionId !== null)) {
55
+ const checkpoint = task.result?.data?.shortcut;
56
+ for (const [nodeId, wait] of Object.entries(checkpoint?.waits ?? {})) {
57
+ const receipt = checkpoint?.receipts?.[nodeId];
58
+ if (!receipt || wait.kind !== 'nonhuman_result' || !wait.id || !wait.revision || !wait.contentHash || wait.executionId !== task.executionId
59
+ || receipt.nodeId !== nodeId || receipt.waitId !== wait.id || receipt.revision !== wait.revision || receipt.contentSha256 !== wait.contentHash
60
+ || receipt.executionId !== task.executionId)
61
+ continue;
62
+ await dispatchResume(job, task, receipt);
63
+ break;
64
+ }
65
+ }
66
+ }
@@ -16,7 +16,6 @@ import { PreSubmissionRejection } from './worker-rejection.js';
16
16
  import { createPlanRound, pendingPlan } from './planner.js';
17
17
  import { retryPendingPlannerUnblocks } from './planner-runtime.js';
18
18
  import { dispatchPlannerOrchestration, plannerOrchestrationFacts } from './workflow/planner-orchestration-v2.js';
19
- import { resolveExecutionContext } from './execution-context.js';
20
19
  import { ReconcilerReviewBase } from './reconciler-review.js';
21
20
  import { executeForceRestate } from './force-restate.js';
22
21
  import { recordThreadDelivery, resolveImplementationTaskThreadDestination, prepareReviewerThreadDelivery, resolveReviewerThreadDestination } from './reviewer-thread.js';
@@ -29,9 +28,11 @@ import { fallbackFailedTroubleshooters, escalateExhaustedTroubleshooters } from
29
28
  import { cleanupMergedJobWorktree } from './job-worktree-cleanup.js';
30
29
  import { jobHasActiveExecution } from './job-execution-slot.js';
31
30
  import { managedWorkerInput } from './managed-worker-input.js';
31
+ import { launchShortcutEffect, resumeShortcutEffect, resumeShortcutEventWaits } from './reconciler-shortcut.js';
32
32
  export { managedWorkerInput } from './managed-worker-input.js';
33
33
  import { recoverExpiredExecutions, recoverStartupOrphans as recoverStartupExecutionOrphans } from './execution-recovery.js';
34
34
  import { dispatchJobReconcile } from './workflow/job-reconcile-v2.js';
35
+ import { resolvePlannerContext, resolveTaskContext } from './reconciler-context.js';
35
36
  import { reconcileLocalGitCompletion } from './local-merge-delivery.js';
36
37
  import { repairLegacyOrchestrators } from './legacy-orchestrator-repair.js';
37
38
  import { launchPlanExecution } from './planner-runtime.js';
@@ -50,6 +51,8 @@ export class Reconciler extends ReconcilerReviewBase {
50
51
  if (task.kind !== 'planner' && task.adapter !== 'orchestrator')
51
52
  await this.launch(job, task);
52
53
  }, context => `effect.launchTask:${context.jobId}:${context.taskId ?? 'task'}:${String(context.data?.attempt ?? 0)}`));
54
+ this.workflowEffects.register(new CallbackWorkflowEffectHandler('effect.launchShortcut', async (context) => launchShortcutEffect(this.store, this.options, context.jobId, context.taskId, event => this.emit(event)), context => `effect.launchShortcut:${context.jobId}:${context.taskId ?? 'task'}:${String(context.data?.attempt ?? 0)}`));
55
+ this.workflowEffects.register(new CallbackWorkflowEffectHandler('effect.resumeShortcut', async (context) => resumeShortcutEffect(this.store, this.options, context.jobId, context.taskId, context.data, event => this.emit(event)), context => `effect.resumeShortcut:${context.jobId}:${context.taskId ?? 'task'}:${String(context.data?.executionId ?? '')}:${String(context.data?.nodeId ?? '')}:${String(context.data?.waitId ?? '')}`));
53
56
  this.workflowEffects.register(new CallbackWorkflowEffectHandler('effect.cancelActiveTasks', async (context) => this.cancelActiveTasks(context.jobId, String(context.data?.reason ?? 'Job terminated'))));
54
57
  this.workflowEffects.register(new CallbackWorkflowEffectHandler('effect.cleanupJobWorktree', async (context) => cleanupMergedJobWorktree(await this.store.load(context.jobId), this.options.projectPathForJob), context => `effect.cleanupJobWorktree:${context.jobId}`));
55
58
  }
@@ -70,7 +73,8 @@ export class Reconciler extends ReconcilerReviewBase {
70
73
  .sort((a, b) => compareTaskPriority(a, b, scheduled.priority ?? 'P2'))
71
74
  .slice(0, Math.min(capacity, 1));
72
75
  for (const task of dispatchable) {
73
- await transitionTaskEvent(task, 'dispatch', { dispatchable: true }, async (actionId) => {
76
+ const shortcut = task.result?.data?.shortcut;
77
+ await transitionTaskEvent(task, 'dispatch', { dispatchable: true, shortcutExecution: scheduled.executionMode === 'shortcut' && scheduled.contentOnly === true, shortcutFallback: shortcut?.workerFallback === true, shortcutHasGraph: Boolean(task.agentGraph) }, async (actionId) => {
74
78
  const outcomes = await this.workflowEffects.execute([actionId], { jobId: scheduled.id, taskId: task.id, transitionKey: `dispatch:${task.attempt}`, data: { attempt: task.attempt } });
75
79
  await this.applyTaskEffectOutcomes(scheduled, task, outcomes);
76
80
  }, async () => { await this.store.saveTask(task); });
@@ -117,6 +121,7 @@ export class Reconciler extends ReconcilerReviewBase {
117
121
  await recoverExpiredExecutions(job, now, this.executionRecoveryPorts(job));
118
122
  await repairLegacyOrchestrators(jobId, now, { store: this.store, owner: this.options.owner, emit: event => this.emit(event) });
119
123
  await recoverInteractiveDecisions(this.store, jobId);
124
+ await this.resumeShortcutEventWaits(jobId);
120
125
  await this.recoverPlannerChildren(job);
121
126
  await retryPendingPlannerUnblocks({
122
127
  store: this.store,
@@ -235,6 +240,17 @@ export class Reconciler extends ReconcilerReviewBase {
235
240
  this.reconciling = false;
236
241
  }
237
242
  }
243
+ async resumeShortcutEventWaits(jobId) {
244
+ await resumeShortcutEventWaits(this.store, this.options, jobId, async (job, task, matched) => {
245
+ await transitionTaskEvent(task, 'shortcut.result', { shortcutResultCorrelated: true }, async (actionId) => {
246
+ if (actionId !== 'effect.resumeShortcut')
247
+ throw new Error(`Unexpected action ${actionId} for a correlated shortcut result`);
248
+ const outcomes = await this.workflowEffects.execute([actionId], { jobId, taskId: task.id,
249
+ transitionKey: `shortcut-result:${matched.executionId}:${matched.nodeId}:${matched.waitId}`, data: { ...matched } });
250
+ await this.applyTaskEffectOutcomes(job, task, outcomes);
251
+ }, async () => this.store.saveTask(task));
252
+ }, event => this.emit(event));
253
+ }
238
254
  async cancelActiveTasks(jobId, reason) {
239
255
  return cancelActiveTasks(this.store, jobId, reason, taskId => { const live = this.plannerLive.get(taskId); if (live) {
240
256
  clearTimeout(live.timer);
@@ -274,6 +290,8 @@ export class Reconciler extends ReconcilerReviewBase {
274
290
  // Terminal Jobs can repair projections and re-review, but must not reopen planning.
275
291
  if (job.state !== 'ACTIVE')
276
292
  return job;
293
+ if (job.executionMode === 'shortcut')
294
+ return job;
277
295
  const pending = pendingPlan(job);
278
296
  const recoverable = pending && !this.plannerLive.has(pending.id)
279
297
  && (!pending.executionId || pending.leaseOwner !== this.options.owner || !pending.leaseExpiresAt || Date.parse(pending.leaseExpiresAt) <= (this.options.now ?? new Date()).getTime())
@@ -312,23 +330,8 @@ export class Reconciler extends ReconcilerReviewBase {
312
330
  return this.store.load(job.id);
313
331
  }
314
332
  async recoverPlannerChildren(job) { return recoverPlannerChildren(this.store, job, (j, p) => this.plannerContext(j, p)); }
315
- async resolvedContext(job, task, role, projectPathOverride) {
316
- const projectPath = projectPathOverride ?? (this.options.projectPathForJob ? await this.options.projectPathForJob(job) : task.routing?.cwd ?? process.cwd());
317
- return resolveExecutionContext(projectPath, role, {
318
- ...(this.options.executionContextRoots ?? {}),
319
- registeredAgents: await this.store.listAgents(),
320
- runtimes: this.options.adapters.map(adapter => ({ name: adapter.name, id: adapter.id, capabilities: [...adapter.capabilities] })),
321
- });
322
- }
323
- async plannerContext(job, planning) {
324
- const routingCwd = 'routing' in planning ? planning.routing?.cwd : undefined;
325
- let projectPath = this.options.projectPathForJob ? await this.options.projectPathForJob(job) : routingCwd ?? process.cwd();
326
- return resolveExecutionContext(projectPath, 'planner', {
327
- ...(this.options.executionContextRoots ?? {}),
328
- registeredAgents: await this.store.listAgents(),
329
- runtimes: this.options.adapters.map(adapter => ({ name: adapter.name, id: adapter.id, capabilities: [...adapter.capabilities] })),
330
- });
331
- }
333
+ async resolvedContext(job, task, role, projectPathOverride) { return resolveTaskContext(this.store, this.options, job, task, role, projectPathOverride); }
334
+ async plannerContext(job, planning) { return resolvePlannerContext(this.store, this.options, job, planning); }
332
335
  async launch(job, task) {
333
336
  return withObservabilityCorrelation({ repository: job.repository, prNumber: job.prNumber, jobId: job.id, taskId: task.id }, () => this.launchCorrelated(job, task));
334
337
  }
@@ -1,7 +1,7 @@
1
1
  import { normalizeLegacyTaskLifecycle } from './types.js';
2
2
  import { normalizeLegacyJobPrNumber } from './job-pr-number-migration.js';
3
3
  export function currentJobMetadata(job) {
4
- const { executionMode: _mode, schedule: _schedule, ...current } = job;
4
+ const { schedule: _schedule, ...current } = job;
5
5
  return current;
6
6
  }
7
7
  export function normalizeRelayJob(json) {
@@ -80,11 +80,20 @@ export class SQLiteWorkflowOperations {
80
80
  }, emitted);
81
81
  }
82
82
  async reserveWorkflowLaunch(identity) {
83
- const decision = dispatchWorkflowGraphSync(taskLifecycleV2, { initialState: 'QUEUED', input: { transport: 'event', id: 'dispatch', payload: {} }, durableFacts: { dispatchable: true } });
84
- if (!decision.accepted || !decision.actions.some(action => action.id === 'effect.launchTask'))
83
+ const row = this.db.prepare('SELECT json FROM job_snapshot WHERE job_id=?').get(identity.jobId);
84
+ if (!row?.json)
85
+ throw new Error('authoritative job snapshot unavailable');
86
+ const job = JSON.parse(row.json);
87
+ const task = job.tasks.find(item => item.id === identity.taskId);
88
+ const shortcut = task?.result?.data?.shortcut;
89
+ const decision = dispatchWorkflowGraphSync(taskLifecycleV2, { initialState: 'QUEUED', input: { transport: 'event', id: 'dispatch', payload: {} }, durableFacts: { dispatchable: true, shortcutExecution: job.executionMode === 'shortcut' && job.contentOnly === true, shortcutFallback: shortcut?.workerFallback === true, shortcutHasGraph: Boolean(task?.agentGraph) } });
90
+ if (!decision.accepted)
91
+ throw new Error('canonical Task Graph did not authorize launch');
92
+ const actionId = decision.actions.find(action => action.id === 'effect.launchTask' || action.id === 'effect.launchShortcut')?.id;
93
+ if (!actionId)
85
94
  throw new Error('canonical Task Graph did not authorize launch');
86
95
  return new WorkflowActionLedger(this.db).reserveForClaimedDispatch({
87
- ...identity, generation: identity.attempt, graph: 'task-lifecycle.mmd', actionId: 'effect.launchTask',
96
+ ...identity, generation: identity.attempt, graph: 'task-lifecycle.mmd', actionId,
88
97
  attemptKey: `${identity.jobId}/${identity.taskId}/${identity.executionId}/launch`,
89
98
  }, decision, 'worker.started');
90
99
  }
@@ -19,8 +19,8 @@ export function createWorkspaceControl(deps) {
19
19
  const options = (body.options && typeof body.options === 'object' ? body.options : {});
20
20
  if (!repository)
21
21
  throw new Error('job.create requires repository');
22
- if ('executionMode' in options || 'schedule' in options)
23
- throw new Error('Job execution modes and schedules are unsupported');
22
+ if ('schedule' in options)
23
+ throw new Error('Job schedules are unsupported');
24
24
  const result = await ensureManagedGitHubJob(client, repository, trusted, {
25
25
  id: typeof options.id === 'string' && options.id ? options.id : undefined,
26
26
  idempotencyKey: typeof options.idempotencyKey === 'string' ? options.idempotencyKey : undefined,
@@ -30,6 +30,7 @@ export function createWorkspaceControl(deps) {
30
30
  priority: options.priority,
31
31
  tag: options.tag,
32
32
  reviewEnabled: typeof options.reviewEnabled === 'boolean' ? options.reviewEnabled : undefined,
33
+ executionMode: options.executionMode === 'shortcut' ? 'shortcut' : undefined,
33
34
  continuation: options.continuation,
34
35
  reviewerThreadId: typeof options.reviewerThreadId === 'string' ? options.reviewerThreadId : undefined,
35
36
  creatorThreadId: typeof options.creatorThreadId === 'string' ? options.creatorThreadId : undefined,
@@ -93,7 +94,7 @@ export function createWorkspaceControl(deps) {
93
94
  const patch = (body.patch && typeof body.patch === 'object' ? body.patch : {});
94
95
  if ('executionMode' in patch || 'schedule' in patch)
95
96
  throw new Error('Job execution modes and schedules are unsupported');
96
- const mutable = ['title', 'objective', 'projectPath', 'priority', 'tag', 'autoMerge', 'reviewEnabled', 'reviewerThreadId', 'creatorThreadId', 'implementationThreadId', 'continuation', 'localMerge'];
97
+ const mutable = ['title', 'objective', 'projectPath', 'priority', 'tag', 'autoMerge', 'reviewEnabled', 'contentOnly', 'reviewerThreadId', 'creatorThreadId', 'implementationThreadId', 'continuation', 'localMerge'];
97
98
  for (const key of mutable)
98
99
  if (Object.prototype.hasOwnProperty.call(patch, key)) {
99
100
  const value = patch[key];
@@ -103,6 +104,8 @@ export function createWorkspaceControl(deps) {
103
104
  else
104
105
  job[key] = value;
105
106
  }
107
+ if (job.contentOnly === true && (job.prNumber !== 0 || job.localMerge || job.autoMerge === true || job.reviewEnabled === true || job.review))
108
+ throw new Error('Content-only policy requires no PR, merge, or review requirements');
106
109
  job.updatedAt = new Date().toISOString();
107
110
  await store.saveJob(job);
108
111
  await refreshAll();
@@ -47,6 +47,11 @@ function clearExecution(task) {
47
47
  task.leaseExpiresAt = null;
48
48
  task.executionId = null;
49
49
  }
50
+ function markShortcutWorkerFallback(task) {
51
+ const data = task.result?.data ?? {};
52
+ const shortcut = data.shortcut && typeof data.shortcut === 'object' ? data.shortcut : {};
53
+ task.result = { summary: task.result?.summary ?? 'Troubleshooter selected original Worker recovery', data: { ...data, shortcut: { ...shortcut, workerFallback: true } } };
54
+ }
50
55
  function applyTaskRetrySnapshot(task, policy = {}) {
51
56
  if (task.kind === 'planner')
52
57
  throw new Error(`Legacy planner Task ${task.id} is read-only; retry the Plan instead`);
@@ -222,7 +227,12 @@ export async function dispatchTaskAction(store, request) {
222
227
  if (!recovery.executionId)
223
228
  throw new Error(`Troubleshooter ${recovery.id} has no current execution for a fresh resolution`);
224
229
  const proposal = { path: 'exact_original_retry', targetTaskId: task.id, recoveryExecutionId: recovery.executionId, rootCause: task.failureReason ?? task.error ?? 'durable failure', solution: `Recover exact original Task via ${request.recoveryTaskId}` };
225
- const decision = dispatchTaskResolutionSync(task, proposal, 'troubleshooter', { activateRecovery: () => { applyTaskRetrySnapshot(task, { extendBudget: true }); recordRecoveryRouting(task, request); task.resolution = { ...materializeResolution(task, proposal, 'troubleshooter'), state: 'resolved' }; } });
230
+ const activateRecovery = (workerFallback) => { applyTaskRetrySnapshot(task, { extendBudget: true }); if (workerFallback)
231
+ markShortcutWorkerFallback(task); recordRecoveryRouting(task, request); task.resolution = { ...materializeResolution(task, proposal, 'troubleshooter'), state: 'resolved' }; };
232
+ const decision = dispatchTaskResolutionSync(task, proposal, 'troubleshooter', {
233
+ activateRecovery: () => activateRecovery(false),
234
+ activateShortcutWorkerFallback: () => activateRecovery(true),
235
+ });
226
236
  if (!decision.accepted)
227
237
  throw new Error(`Task resolution graph rejected exact-original recovery for ${task.id}`);
228
238
  }
@@ -258,7 +268,12 @@ export async function dispatchTaskAction(store, request) {
258
268
  if (!recovery.executionId)
259
269
  throw new Error(`Troubleshooter ${recovery.id} has no current execution for a fresh resolution`);
260
270
  const proposal = { path: 'exact_original_retry', targetTaskId: task.id, recoveryExecutionId: recovery.executionId, rootCause: task.failureReason ?? task.error ?? 'durable failure', solution: `Recover exact original Task via ${request.recoveryTaskId}` };
261
- const decision = dispatchTaskResolutionSync(task, proposal, 'troubleshooter', { activateRecovery: () => { applyTaskRetrySnapshot(task, { extendBudget: true }); recordRecoveryRouting(task, request); task.resolution = { ...materializeResolution(task, proposal, 'troubleshooter'), state: 'resolved' }; } });
271
+ const activateRecovery = (workerFallback) => { applyTaskRetrySnapshot(task, { extendBudget: true }); if (workerFallback)
272
+ markShortcutWorkerFallback(task); recordRecoveryRouting(task, request); task.resolution = { ...materializeResolution(task, proposal, 'troubleshooter'), state: 'resolved' }; };
273
+ const decision = dispatchTaskResolutionSync(task, proposal, 'troubleshooter', {
274
+ activateRecovery: () => activateRecovery(false),
275
+ activateShortcutWorkerFallback: () => activateRecovery(true),
276
+ });
262
277
  if (!decision.accepted)
263
278
  throw new Error(`Task resolution graph rejected exact-original recovery for ${task.id}`);
264
279
  }
@@ -50,7 +50,7 @@ export class WorkflowActionLedger {
50
50
  * execution lease; task.started later transitions it to RUNNING. */
51
51
  reserveForClaimedDispatch(identity, decision, conditionId) {
52
52
  if (!decision.accepted || decision.source !== 'QUEUED' || decision.target !== 'QUEUED'
53
- || identity.actionId !== 'effect.launchTask')
53
+ || !['effect.launchTask', 'effect.launchShortcut'].includes(identity.actionId))
54
54
  throw Error('dispatch reservation requires canonical QUEUED Graph launch decision');
55
55
  return this.reserveForRunningTask(identity, decision, conditionId, new Date().toISOString(), 'QUEUED');
56
56
  }
@@ -38,6 +38,12 @@ export const WORKFLOW_EVENT_NAMES = [
38
38
  'task.failed',
39
39
  'task.progress',
40
40
  'task.started',
41
+ 'shortcut.waiting',
42
+ 'shortcut.completed',
43
+ 'shortcut.failed',
44
+ 'shortcut.result',
45
+ 'effect.launchShortcut.failed',
46
+ 'effect.resumeShortcut.failed',
41
47
  'task.unblocked',
42
48
  'interactive.waiting',
43
49
  'watchdog.failed',
@@ -50,6 +56,11 @@ export const WORKFLOW_FACT_NAMES = [
50
56
  'dependenciesUnsatisfied',
51
57
  'runnable',
52
58
  'dispatchable',
59
+ 'shortcutExecution',
60
+ 'shortcutFallback',
61
+ 'shortcutHasGraph',
62
+ 'shortcutEffectsSafe',
63
+ 'shortcutResultCorrelated',
53
64
  'notMerged',
54
65
  'autoMerge',
55
66
  'recoverableExecution',
@@ -73,11 +84,15 @@ export const WORKFLOW_MUTATION_NAMES = [
73
84
  'mutation.markStartupOrphanedExhausted',
74
85
  'mutation.markUnknownOutcome',
75
86
  'mutation.markPlannerUnavailable',
87
+ 'mutation.markShortcutWorkerFallback',
88
+ 'mutation.markShortcutRecoveryRequired',
76
89
  'mutation.preparePlatformFallback',
77
90
  'mutation.quarantinePlatformFailure',
78
91
  ];
79
92
  export const WORKFLOW_EFFECT_NAMES = [
80
93
  'effect.launchTask',
94
+ 'effect.launchShortcut',
95
+ 'effect.resumeShortcut',
81
96
  'effect.cancelActiveTasks',
82
97
  'effect.mergePullRequest',
83
98
  'effect.deliverLocalMerge',
@@ -90,6 +105,18 @@ export const WORKFLOW_EFFECT_POLICIES = {
90
105
  retry: 'workflow',
91
106
  observability: 'workflow.effect',
92
107
  },
108
+ 'effect.launchShortcut': {
109
+ idempotency: 'job-task-attempt',
110
+ failureEvent: 'effect.launchShortcut.failed',
111
+ retry: 'workflow',
112
+ observability: 'workflow.effect',
113
+ },
114
+ 'effect.resumeShortcut': {
115
+ idempotency: 'job-task-attempt',
116
+ failureEvent: 'effect.resumeShortcut.failed',
117
+ retry: 'workflow',
118
+ observability: 'workflow.effect',
119
+ },
93
120
  'effect.cancelActiveTasks': {
94
121
  idempotency: 'job-transition',
95
122
  failureEvent: 'effect.cancelActiveTasks.failed',