agents-relay 2.0.263 → 2.0.264

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +57 -52
  2. package/bin/migrate-task-ids.mjs +12 -0
  3. package/dist/blocker-recovery.js +9 -16
  4. package/dist/cli-blocker.js +2 -1
  5. package/dist/cli-coordinator.js +19 -7
  6. package/dist/cli-foreground.js +82 -0
  7. package/dist/cli-help.js +61 -72
  8. package/dist/cli-job-create.js +15 -9
  9. package/dist/cli-prompt.js +9 -5
  10. package/dist/cli-support.js +21 -8
  11. package/dist/cli-worker-task.js +9 -3
  12. package/dist/cli.js +50 -36
  13. package/dist/dag-task-runtime.js +16 -12
  14. package/dist/dashboard-html.js +28 -14
  15. package/dist/dashboard-jel.js +87 -31
  16. package/dist/dashboard-style.js +2 -8
  17. package/dist/dependency-revision-execution.js +15 -6
  18. package/dist/final-review-role.js +0 -12
  19. package/dist/job-local-repository-migration.js +137 -0
  20. package/dist/job-pr-number-migration.js +0 -4
  21. package/dist/job-task-id-sequence.js +18 -9
  22. package/dist/job-worktree-cleanup.js +3 -3
  23. package/dist/local-job-registry.js +2 -2
  24. package/dist/local-managed-store.js +2 -2
  25. package/dist/local-merge-delivery.js +16 -3
  26. package/dist/local-merge-projection.js +192 -49
  27. package/dist/no-github.js +2 -1
  28. package/dist/planner-recovery.js +8 -3
  29. package/dist/planner.js +5 -5
  30. package/dist/pool.js +3 -3
  31. package/dist/projection-failure-recovery.js +6 -46
  32. package/dist/reconciler-context.js +5 -5
  33. package/dist/reconciler-review.js +12 -37
  34. package/dist/reconciler-runtime.js +1 -4
  35. package/dist/reconciler.js +5 -5
  36. package/dist/relay-job-merge.js +33 -0
  37. package/dist/relay-store.js +8 -30
  38. package/dist/relay-workflow-operations.js +2 -0
  39. package/dist/relayd-control.js +22 -25
  40. package/dist/relayd-dashboard-actions.js +4 -5
  41. package/dist/relayd-utilities.js +15 -20
  42. package/dist/relayd.js +59 -299
  43. package/dist/review-generation-fence.js +1 -1
  44. package/dist/review-replan.js +6 -1
  45. package/dist/review-revision-model.js +11 -6
  46. package/dist/task-context.js +1 -1
  47. package/dist/task-id-migration.js +229 -0
  48. package/dist/task-transitions.js +1 -1
  49. package/dist/troubleshooter.js +13 -16
  50. package/dist/unified-job-registry.js +9 -0
  51. package/dist/workflow/projection-conflict-v2.js +30 -26
  52. package/dist/workflow/task-related-action-v2.js +1 -2
  53. package/dist/workspace.js +52 -56
  54. package/package.json +4 -2
  55. package/skills/agents-relay/SKILL.md +35 -60
  56. package/skills/agents-relay/agents/planner.agent.md +5 -5
  57. package/skills/agents-relay/bin/services.mjs +21 -3
  58. package/skills/agents-relay/contracts/task-job-contract.md +11 -2
  59. package/skills/agents-relay/evals/capabilities.json +6 -1
  60. package/workflow/projection-conflict.mmd +59 -56
  61. package/workflow/projection-outbox-conflict.mmd +20 -0
  62. package/dist/cli-projection.js +0 -29
  63. package/dist/projection-recovery-runtime.js +0 -121
  64. package/dist/projection-recovery.js +0 -101
@@ -1,60 +1,203 @@
1
- import { execFileSync } from 'node:child_process';
1
+ import { randomUUID } from 'node:crypto';
2
+ import { validateProjectRoot } from './workspace.js';
3
+ import { spawnOwnedProcess } from './owned-process.js';
4
+ import { dispatchWorkflowGraph } from './workflow/dispatcher.js';
5
+ import { projectionConflictV2 } from './workflow/projection-conflict-v2.js';
6
+ const MAX_ATTEMPTS = 5;
7
+ const LEASE_MS = 120_000;
2
8
  function git(cwd, ...args) {
3
- return execFileSync('git', ['-C', cwd, ...args], {
4
- encoding: 'utf8', timeout: 120000, maxBuffer: 1024 * 1024,
5
- env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
6
- }).trim();
9
+ return new Promise((resolve, reject) => {
10
+ const child = spawnOwnedProcess('git', ['-C', cwd, ...args], {
11
+ invocation: 'remote.delivery.git', timeoutMs: LEASE_MS,
12
+ spawn: { stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } },
13
+ });
14
+ let stdout = '', stderr = '';
15
+ child.stdout?.on('data', chunk => { stdout += String(chunk); });
16
+ child.stderr?.on('data', chunk => { stderr += String(chunk); });
17
+ child.once('error', reject);
18
+ child.once('close', code => code === 0 ? resolve(stdout.trim()) : reject(new Error((stderr.trim() || `git exited ${code}`).replace(/(https?:\/\/)[^/@\s]+@/g, '$1[redacted]@'))));
19
+ });
7
20
  }
8
- function branchRef(name) {
9
- if (!/^refs\/heads\/[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(name) || name.includes('..') || name.endsWith('.lock'))
10
- throw new Error('Local merge projection requires explicit refs/heads/ target');
11
- return name;
12
- }
13
- function validSha(value, label) {
14
- if (!value || !/^[0-9a-f]{40,64}$/.test(value))
15
- throw new Error(`Local merge projection requires valid ${label} SHA`);
16
- return value;
17
- }
18
- /**
19
- * Publish SQLite-authoritative local main using a normal fast-forward push.
20
- * GitHub never performs a second merge. Divergence is retried only after
21
- * an operator or a separate Git synchronization workflow resolves it.
22
- */
23
- export function projectAuthoritativeLocalMerge(repoPath, job) {
24
- const receipt = job.localMerge;
25
- if (job.state !== 'COMPLETED' || receipt?.status !== 'succeeded')
26
- throw new Error('Authoritative local merge projection requires COMPLETED Job with succeeded merge receipt');
27
- const targetRef = branchRef(receipt.targetRef);
28
- if (targetRef !== 'refs/heads/main')
29
- throw new Error('Local Git target must always be refs/heads/main');
30
- const sourceSha = validSha(receipt.sourceSha, 'source');
31
- const mergedCommitSha = validSha(receipt.mergedCommitSha, 'merged commit');
32
- const localTargetSha = git(repoPath, 'rev-parse', '--verify', targetRef);
33
- if (localTargetSha !== mergedCommitSha) {
21
+ async function inspectRemoteMain(repoPath, mergedCommitSha) {
22
+ // Do not publish a moved/reset main that omits the Job's merged evidence.
23
+ const expected = await git(repoPath, 'rev-parse', '--verify', mergedCommitSha);
24
+ if (expected !== mergedCommitSha)
25
+ throw new Error('Completed Job merged commit no longer resolves');
26
+ const inspectedMainSha = await git(repoPath, 'rev-parse', '--verify', 'refs/heads/main');
27
+ try {
28
+ await git(repoPath, 'merge-base', '--is-ancestor', mergedCommitSha, inspectedMainSha);
29
+ }
30
+ catch {
31
+ throw new Error('Local main no longer contains completed Job merged commit');
32
+ }
33
+ const lines = (await git(repoPath, 'ls-remote', '--heads', 'origin', 'refs/heads/main')).split(/\s+/);
34
+ const remoteHead = lines[0] || '';
35
+ if (!remoteHead)
36
+ return { remoteMainPresent: false, remoteContainsMain: false, inspectedMainSha };
37
+ await git(repoPath, 'fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main');
38
+ try {
39
+ await git(repoPath, 'merge-base', '--is-ancestor', inspectedMainSha, 'refs/remotes/origin/main');
40
+ return { remoteMainPresent: true, remoteContainsMain: true, inspectedMainSha };
41
+ }
42
+ catch {
34
43
  try {
35
- git(repoPath, 'merge-base', '--is-ancestor', mergedCommitSha, localTargetSha);
44
+ await git(repoPath, 'merge-base', '--is-ancestor', 'refs/remotes/origin/main', inspectedMainSha);
45
+ return { remoteMainPresent: true, remoteContainsMain: false, inspectedMainSha };
36
46
  }
37
47
  catch {
38
- throw new Error(`Local merge target ${targetRef} diverged after authoritative delivery for ${job.id}`);
48
+ throw new Error(`origin/main diverged from local main (${remoteHead}); refusing non-fast-forward push`);
39
49
  }
40
50
  }
41
- const branch = targetRef.slice('refs/heads/'.length);
42
- const remoteTracking = `refs/remotes/origin/${branch}`;
43
- git(repoPath, 'fetch', '--no-tags', 'origin', `+${targetRef}:${remoteTracking}`);
44
- const remoteTargetSha = git(repoPath, 'rev-parse', '--verify', remoteTracking);
45
- try {
46
- git(repoPath, 'merge-base', '--is-ancestor', localTargetSha, remoteTargetSha);
47
- return { targetRef, localMergedCommitSha: mergedCommitSha, remoteTargetSha, projectedCommitSha: remoteTargetSha, status: 'already_projected' };
48
- }
49
- catch { /* remote projection required */ }
50
- // GitHub mirrors the SQLite-authoritative local main; it must never synthesize
51
- // a second merge or rewrite the tree when the remote has diverged.
51
+ }
52
+ /** Run Graph-selected, bounded optional delivery for one already-completed local merge. */
53
+ export async function reconcileCompletedLocalDelivery(store, job, repoPath, now = Date.now) {
54
+ const sha = job.localMerge?.mergedCommitSha;
55
+ if (job.state !== 'COMPLETED' || job.localMerge?.status !== 'succeeded' || !sha
56
+ || job.localMerge.targetRef !== 'refs/heads/main' || job.remoteDelivery?.mergedCommitSha !== sha)
57
+ return;
58
+ const delivery = job.remoteDelivery;
59
+ if (['skipped', 'succeeded', 'exhausted'].includes(delivery.status))
60
+ return;
61
+ if (delivery.status === 'processing' && delivery.leaseUntil && Date.parse(delivery.leaseUntil) > now())
62
+ return;
63
+ const run = (state, event, facts, perform) => dispatchWorkflowGraph(projectionConflictV2, {
64
+ initialState: state, input: { transport: 'event', id: event, payload: {} },
65
+ durableFacts: facts, graphName: 'projection-conflict', maxSteps: 1, executeAction: perform,
66
+ });
67
+ // A single SQLite lease protects the entire inspection + push, not just the
68
+ // last Git command. An expired lease is safely reconciled against remote HEAD.
69
+ let leaseToken;
70
+ let attempts = delivery.attempts;
71
+ let claimed = false;
72
+ const state = delivery.status === 'pending' ? 'classify' : 'waiting';
73
+ const opening = await run(state, state === 'classify' ? 'job.completed' : 'delivery.retry_due', {
74
+ retryDue: delivery.status === 'processing' || !delivery.nextRetryAt || Date.parse(delivery.nextRetryAt) <= now(),
75
+ claimAvailable: delivery.attempts < MAX_ATTEMPTS,
76
+ }, async (actionId) => {
77
+ if (actionId === 'delivery.recordExhausted') {
78
+ await store.mutateJob?.(job.id, current => {
79
+ const currentDelivery = current.remoteDelivery;
80
+ if (current.state !== 'COMPLETED' || currentDelivery?.mergedCommitSha !== sha
81
+ || !['failed', 'pending', 'processing'].includes(currentDelivery.status)
82
+ || currentDelivery.attempts < MAX_ATTEMPTS
83
+ || (currentDelivery.leaseUntil && Date.parse(currentDelivery.leaseUntil) > now()))
84
+ return current;
85
+ return { ...current, remoteDelivery: { ...currentDelivery, status: 'exhausted', leaseUntil: undefined,
86
+ leaseToken: undefined, nextRetryAt: undefined, updatedAt: new Date(now()).toISOString() } };
87
+ });
88
+ return { ok: true };
89
+ }
90
+ if (actionId !== 'delivery.claimInspection')
91
+ throw new Error(`Unexpected delivery action before inspection: ${actionId}`);
92
+ const token = randomUUID();
93
+ await store.mutateJob?.(job.id, current => {
94
+ const currentDelivery = current.remoteDelivery;
95
+ if (current.state !== 'COMPLETED' || current.localMerge?.mergedCommitSha !== sha
96
+ || currentDelivery?.mergedCommitSha !== sha
97
+ || !['pending', 'failed', 'processing'].includes(currentDelivery.status)
98
+ || currentDelivery.attempts >= MAX_ATTEMPTS)
99
+ return current;
100
+ if (currentDelivery.status === 'processing' && currentDelivery.leaseUntil && Date.parse(currentDelivery.leaseUntil) > now())
101
+ return current;
102
+ if (currentDelivery.status === 'failed' && currentDelivery.nextRetryAt && Date.parse(currentDelivery.nextRetryAt) > now())
103
+ return current;
104
+ attempts = currentDelivery.attempts + 1;
105
+ leaseToken = token;
106
+ claimed = true;
107
+ return { ...current, remoteDelivery: { ...currentDelivery, status: 'processing', attempts,
108
+ leaseToken: token, leaseUntil: new Date(now() + LEASE_MS).toISOString(), updatedAt: new Date(now()).toISOString() } };
109
+ });
110
+ return { ok: true };
111
+ });
112
+ if (!opening.accepted || opening.target !== 'inspect' || !claimed || !leaseToken)
113
+ return;
114
+ const token = leaseToken;
115
+ const updateOwned = async (status, error, delayMs) => {
116
+ await store.mutateJob?.(job.id, current => {
117
+ const currentDelivery = current.remoteDelivery;
118
+ if (current.state !== 'COMPLETED' || current.localMerge?.mergedCommitSha !== sha
119
+ || currentDelivery?.mergedCommitSha !== sha || currentDelivery.leaseToken !== token)
120
+ return current;
121
+ return { ...current, remoteDelivery: { ...currentDelivery, status, error,
122
+ leaseUntil: undefined, leaseToken: undefined,
123
+ nextRetryAt: delayMs === undefined ? undefined : new Date(now() + delayMs).toISOString(),
124
+ updatedAt: new Date(now()).toISOString() } };
125
+ });
126
+ };
127
+ const recordFailure = async (from, error) => {
128
+ const failure = error instanceof Error ? error.message : String(error);
129
+ const failed = await run(from, 'delivery.failed', { attempts, maxAttempts: MAX_ATTEMPTS }, async (actionId) => {
130
+ const exhausted = actionId === 'delivery.recordExhausted';
131
+ if (!exhausted && actionId !== 'delivery.scheduleRetry')
132
+ throw new Error(`Unexpected delivery action ${actionId}`);
133
+ const delayMs = Math.min(300_000, 1000 * (2 ** Math.min(attempts, 8)));
134
+ await updateOwned(exhausted ? 'exhausted' : 'failed', failure, exhausted ? undefined : delayMs);
135
+ return { ok: true };
136
+ });
137
+ if (!failed.accepted)
138
+ throw new Error(`Delivery failure had no graph transition: ${failure}`);
139
+ };
140
+ let originUsable = false;
141
+ let remoteMainPresent = false;
142
+ let inspected = false;
143
+ let inspectedMainSha;
52
144
  try {
53
- git(repoPath, 'merge-base', '--is-ancestor', remoteTargetSha, localTargetSha);
145
+ // Re-validate the immutable Git root after claiming the effect. If the
146
+ // checkout disappeared or is now a linked worktree, persist a retry.
147
+ await validateProjectRoot(repoPath, job.repository);
148
+ originUsable = (await git(repoPath, 'remote')).split(/\r?\n/).includes('origin');
149
+ if (originUsable) {
150
+ // Do not read or persist a GitHub repository binding. The actual local
151
+ // Git origin is resolved only after authoritative COMPLETED.
152
+ const fetchUrl = await git(repoPath, 'remote', 'get-url', 'origin');
153
+ const pushUrl = await git(repoPath, 'remote', 'get-url', '--push', '--all', 'origin');
154
+ // We inspect origin/main before writing. An alternate pushURL (including
155
+ // multiple push targets) must not send data to an unverified endpoint.
156
+ if (fetchUrl !== pushUrl)
157
+ throw new Error('Origin push URL differs from verified fetch URL');
158
+ const result = await inspectRemoteMain(repoPath, sha);
159
+ remoteMainPresent = result.remoteMainPresent;
160
+ inspected = result.remoteContainsMain;
161
+ inspectedMainSha = result.inspectedMainSha;
162
+ }
54
163
  }
55
- catch {
56
- throw new Error(`GitHub sync deferred: origin/${branch} diverged from authoritative local main; resolve the remote conflict without force push`);
164
+ catch (error) {
165
+ await recordFailure('inspect', error);
166
+ return;
57
167
  }
58
- git(repoPath, 'push', 'origin', `${targetRef}:${targetRef}`);
59
- return { targetRef, localMergedCommitSha: mergedCommitSha, remoteTargetSha, projectedCommitSha: localTargetSha, status: 'projected' };
168
+ let pushSucceeded = false;
169
+ const inspectedDecision = await run('inspect', 'inspect.completed', { originUsable, remoteMainPresent, remoteContainsMain: inspected }, async (actionId) => {
170
+ if (actionId === 'delivery.skip') {
171
+ await updateOwned('skipped');
172
+ return { ok: true };
173
+ }
174
+ if (actionId === 'delivery.recordDelivered') {
175
+ await updateOwned('succeeded');
176
+ return { ok: true };
177
+ }
178
+ if (actionId !== 'delivery.pushMain')
179
+ throw new Error(`Unexpected delivery action ${actionId}`);
180
+ if (!inspectedMainSha)
181
+ throw new Error('Remote delivery cannot push without a verified local main SHA');
182
+ try {
183
+ // Git's normal refspec push is non-force. Remote-side FF race rejection
184
+ // is persisted separately without mutating Job/Task lifecycle.
185
+ await git(repoPath, 'push', 'origin', `${inspectedMainSha}:refs/heads/main`);
186
+ pushSucceeded = true;
187
+ }
188
+ catch (error) {
189
+ await recordFailure('push', error);
190
+ }
191
+ return { ok: true };
192
+ });
193
+ if (!inspectedDecision.accepted || inspectedDecision.target !== 'push' || !pushSucceeded)
194
+ return;
195
+ const finished = await run('push', 'delivery.pushed', {}, async (actionId) => {
196
+ if (actionId !== 'delivery.recordDelivered')
197
+ throw new Error(`Unexpected delivery action ${actionId}`);
198
+ await updateOwned('succeeded');
199
+ return { ok: true };
200
+ });
201
+ if (!finished.accepted)
202
+ throw new Error('Delivery push had no graph transition');
60
203
  }
package/dist/no-github.js CHANGED
@@ -7,5 +7,6 @@ export class DisabledGitHubClient extends GhApiClient {
7
7
  async currentLogin() { throw new Error('GitHub disabled by --no-github'); }
8
8
  }
9
9
  export function noGitHubMode(args = process.argv.slice(2)) {
10
- return args.includes('--no-github') || process.argv.includes('--no-github') || process.env.AGENTS_RELAY_NO_GITHUB === '1';
10
+ void args;
11
+ return true;
11
12
  }
@@ -1,15 +1,20 @@
1
1
  import { taskOverallTimeoutMs } from './types.js';
2
2
  import { createTaskEntity } from './workflow/entity-creation.js';
3
+ import { allocateEntityId } from './job-task-id-sequence.js';
4
+ import { relayStoreDirectory } from './relay-store.js';
3
5
  /** Only the Planner orchestration Graph may select this durable recovery effect. */
4
6
  export function createFailedPlanRecovery(job, plan) {
5
7
  if (plan.status !== 'FAILED')
6
8
  throw Error('Plan recovery requires a terminal FAILED Plan');
7
- const id = 'recover-' + plan.id;
8
- if (job.tasks.some(task => task.id === id || task.recoveryPlanId === plan.id))
9
+ const existing = job.tasks.find(task => task.recoveryPlanId === plan.id);
10
+ if (existing)
11
+ return existing;
12
+ const id = allocateEntityId(relayStoreDirectory(), job.repository, 'task', `planner-recovery:${job.id}:${plan.id}`);
13
+ if (job.tasks.some(task => task.recoveryPlanId === plan.id))
9
14
  throw Error('Plan recovery identity already exists');
10
15
  const now = new Date().toISOString();
11
16
  return createTaskEntity(job, {
12
- jobId: job.id, id, title: 'Troubleshoot',
17
+ jobId: job.id, id, title: 'Troubleshooter',
13
18
  recoveryPlanId: plan.id,
14
19
  kind: 'work', priority: 'P0', storySize: 'M', projectName: job.title,
15
20
  agentName: 'troubleshooter', parentTaskId: null, dependencies: [],
package/dist/planner.js CHANGED
@@ -254,15 +254,15 @@ export function parsePlannerResult(value) {
254
254
  const repository = optionalString(unblock.repository, `unblocks[${index}].repository`);
255
255
  const jobId = optionalString(unblock.jobId, `unblocks[${index}].jobId`);
256
256
  const taskId = optionalString(unblock.taskId, `unblocks[${index}].taskId`);
257
- if (!repository || !/^[^/\s]+\/[^/\s]+$/.test(repository))
258
- throw new Error(`Planner unblocks[${index}].repository must be OWNER/REPO`);
257
+ if (!repository || !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(repository) || repository.includes('..'))
258
+ throw new Error(`Planner unblocks[${index}].repository must be a local Git root identity`);
259
259
  if (!jobId)
260
260
  throw new Error(`Planner unblocks[${index}].jobId is required`);
261
261
  if (!taskId)
262
262
  throw new Error(`Planner unblocks[${index}].taskId is required`);
263
- const prNumber = unblock.prNumber;
264
- if (!Number.isInteger(prNumber) || Number(prNumber) <= 0)
265
- throw new Error(`Planner unblocks[${index}].prNumber must be a positive integer`);
263
+ const prNumber = unblock.prNumber ?? 0; // Historical PR metadata is optional for local Git unblock relations.
264
+ if (!Number.isInteger(prNumber) || Number(prNumber) < 0)
265
+ throw new Error(`Planner unblocks[${index}].prNumber must be a non-negative integer`);
266
266
  const resolutionMode = unblock.resolutionMode === undefined ? undefined : String(unblock.resolutionMode);
267
267
  if (resolutionMode !== undefined && resolutionMode !== 'merge' && resolutionMode !== 'verified')
268
268
  throw new Error(`Planner unblocks[${index}].resolutionMode must be merge or verified`);
package/dist/pool.js CHANGED
@@ -12,7 +12,7 @@ import { decideReviewLifecycle } from './workflow/review-v2.js';
12
12
  import { isFinalReviewAgent } from './final-review-role.js';
13
13
  const RANK = { P0: 0, P1: 1, P2: 2, P3: 3 };
14
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); }
15
- export function runnableManagedJobs(items) { return items.filter(item => item.job.state === 'ACTIVE' || item.job.projectionRecovery?.status === 'repairing').map(item => item.job).sort(compareJobPriority); }
15
+ export function runnableManagedJobs(items) { return items.filter(item => item.job.state === 'ACTIVE').map(item => item.job).sort(compareJobPriority); }
16
16
  export function needsLifecycleReconciliation(job, now = Date.now()) {
17
17
  if (job.pause)
18
18
  return job.tasks.some(task => Boolean(task.pausedExecution)) || Boolean(job.plans?.some(plan => Boolean(plan.pausedExecutionId)));
@@ -32,7 +32,7 @@ export function needsLifecycleReconciliation(job, now = Date.now()) {
32
32
  // A persisted Coordinator may finish before the local Git head is captured.
33
33
  // Wake once to bind that head through Reconciler rather than leaving the
34
34
  // completed DAG permanently ACTIVE/IDLE without a Final Review.
35
- if (job.state === 'ACTIVE' && !job.headSha && job.graphStartContext?.projectPath &&
35
+ if (job.state === 'ACTIVE' && !job.headSha && job.projectRoot &&
36
36
  job.reviewEnabled !== false && reviewWorkSettled(job))
37
37
  return true;
38
38
  if (job.state === 'ACTIVE' && job.headSha && job.reviewEnabled !== false) {
@@ -75,7 +75,7 @@ export function activeWorkerSlots(job) {
75
75
  }
76
76
  function remainingWorkerSlots(concurrency, jobs) {
77
77
  const unique = new Map(jobs.map(job => [job.id, job]));
78
- return Math.max(0, concurrency - [...unique.values()].reduce((used, job) => used + (job.state === 'ACTIVE' || job.projectionRecovery?.status === 'repairing' ? activeWorkerSlots(job) : 0), 0));
78
+ return Math.max(0, concurrency - [...unique.values()].reduce((used, job) => used + (job.state === 'ACTIVE' ? activeWorkerSlots(job) : 0), 0));
79
79
  }
80
80
  export class RepositoryWorkerPool {
81
81
  concurrency;
@@ -1,52 +1,12 @@
1
1
  import { eventFor } from './events.js';
2
- import { beginProjectionRecovery } from './projection-recovery.js';
3
- import { reconcileProjectionRecovery } from './projection-recovery-runtime.js';
4
- import { SQLiteRelayStore } from './relay-store.js';
5
2
  import { classifyFailure, errorMessage, observability } from './observability.js';
6
- import { resolveManagedProjectPath } from './workspace.js';
7
- export async function reconcileBindingProjectionRecovery(job, store, options) {
8
- const recovery = await reconcileProjectionRecovery(job, store, options);
9
- if (recovery && recovery.state === 'escalated')
10
- return { skip: true };
11
- if (recovery && !['retry', 'projected'].includes(recovery.state))
12
- return { skip: true };
13
- if (recovery?.state === 'retry' && !recovery.projectedMerge)
14
- return { skip: true };
15
- return { skip: false, projectedMerge: recovery?.projectedMerge };
16
- }
17
- export async function projectBindingLocalMerge(job, store, options) {
18
- const recovery = await reconcileBindingProjectionRecovery(job, store, options);
19
- if (recovery.skip)
20
- return recovery;
21
- return { skip: false, projectedMerge: recovery.projectedMerge ?? await options.project(job) };
22
- }
23
- export async function handleGitHubProjectionFailure(error, job, snapshotPath, options) {
3
+ /** Historical compatibility hook: remote delivery failures are observational only. */
4
+ export async function handleGitHubProjectionFailure(error, job, _snapshotPath, options) {
24
5
  const reason = errorMessage(error), classification = classifyFailure(error).classification;
25
- if (job.state === 'COMPLETED' && job.localMerge?.status === 'succeeded') {
26
- const recoveryStore = options.relayStores.get(`${snapshotPath}#${job.id}`)
27
- ?? new SQLiteRelayStore(snapshotPath, job.id);
28
- options.relayStores.set(`${snapshotPath}#${job.id}`, recoveryStore);
29
- const recoveryPath = options.repositoryPaths.get(job.repository)
30
- ?? await resolveManagedProjectPath(job.repository, options.explicitProjectPath, options.workspaceRoot);
31
- const remoteSha = await options.gitText(recoveryPath, ['fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main'])
32
- .then(() => options.gitText(recoveryPath, ['rev-parse', '--verify', 'refs/remotes/origin/main']))
33
- .catch(() => '');
34
- const recovery = await beginProjectionRecovery(recoveryStore, job.id, remoteSha, reason);
35
- if (recovery === 'created') {
36
- await options.reconcileLocalJob(job.id, 'projection.delivery_failed');
37
- await options.eventBus?.publish(eventFor(job.id, 'projection', null, 'projection.recovery_requested', 'queued', `Projection recovery task created for origin/main ${remoteSha}`, 'orchestrator', { remoteSha, idempotencyKey: `${job.id}:${remoteSha}` }, { agent: 'relay', component: 'projection-conflict' })).catch(() => { });
38
- }
39
- else if (recovery === 'escalated') {
40
- await options.eventBus?.publish(eventFor(job.id, 'projection', null, 'projection.recovery_escalated', 'failed', 'Projection recovery exhausted its bounded task retry budget', 'user', { idempotencyKey: `${job.id}:${remoteSha}` }, { agent: 'relay', component: 'projection-conflict' })).catch(() => { });
41
- }
42
- }
43
6
  if (!options.deduplicator.shouldReport(job.id, job.updatedAt, reason, classification))
44
7
  return;
45
- await options.eventBus?.publish(eventFor(job.id, 'projection', null, 'projection.delivery_failed', 'failed', `GitHub projection failed: ${errorMessage(error)}`, 'orchestrator', { operation: 'github.projectLocalMerge', error: reason }, { agent: 'relay', component: 'github-projection' }))?.catch(() => { });
46
- observability().record({
47
- stage: 'projection', event: 'github.binding_job_failed', level: 'warn', outcome: 'failed',
48
- message: `GitHub binding/projection failed for ${job.id}: ${reason}`,
49
- correlation: { repository: job.repository, prNumber: job.prNumber, jobId: job.id },
50
- data: { classification, reason },
51
- });
8
+ await options.eventBus?.publish(eventFor(job.id, 'projection', null, 'projection.delivery_failed', 'failed', `Optional remote delivery failed: ${reason}`, 'orchestrator', { operation: 'remote.deliverLocalMain', error: reason }, { agent: 'relay', component: 'remote-delivery' })).catch(() => { });
9
+ observability().record({ stage: 'projection', event: 'remote.delivery_failed', level: 'warn', outcome: 'failed',
10
+ message: `Optional remote delivery failed for ${job.id}: ${reason}`,
11
+ correlation: { repository: job.repository, jobId: job.id }, data: { classification, reason } });
52
12
  }
@@ -7,10 +7,10 @@ export async function agentModelPreferenceForJob(options, job, agentName, task)
7
7
  if (!agentName)
8
8
  return undefined;
9
9
  try {
10
- // Do not call projectPathForJob here: production providers may create a
10
+ // Do not call cwdForJob here: production providers may create a
11
11
  // worktree or mutate Job state when that execution locator is evaluated.
12
- const projectPath = options.agentPreferenceContextPathForJob
13
- ? await options.agentPreferenceContextPathForJob(job, task)
12
+ const projectPath = options.agentPreferenceRootForJob
13
+ ? await options.agentPreferenceRootForJob(job, task)
14
14
  : task?.routing?.cwd;
15
15
  return projectPath ? await resolveAgentModelPreference(projectPath, agentName, options.executionContextRoots ?? {}) : undefined;
16
16
  }
@@ -19,7 +19,7 @@ export async function agentModelPreferenceForJob(options, job, agentName, task)
19
19
  }
20
20
  }
21
21
  export async function resolveTaskContext(store, options, job, task, role, projectPathOverride) {
22
- const projectPath = projectPathOverride ?? (options.projectPathForJob ? await options.projectPathForJob(job) : task.routing?.cwd ?? process.cwd());
22
+ const projectPath = projectPathOverride ?? (options.cwdForJob ? await options.cwdForJob(job) : task.routing?.cwd ?? process.cwd());
23
23
  return resolveExecutionContext(projectPath, role, {
24
24
  ...(options.executionContextRoots ?? {}),
25
25
  registeredAgents: await store.listAgents(),
@@ -28,7 +28,7 @@ export async function resolveTaskContext(store, options, job, task, role, projec
28
28
  }
29
29
  export async function resolvePlannerContext(store, options, job, planning) {
30
30
  const routingCwd = 'routing' in planning ? planning.routing?.cwd : undefined;
31
- const projectPath = options.projectPathForJob ? await options.projectPathForJob(job) : routingCwd ?? process.cwd();
31
+ const projectPath = options.cwdForJob ? await options.cwdForJob(job) : routingCwd ?? process.cwd();
32
32
  return resolveExecutionContext(projectPath, 'planner', {
33
33
  ...(options.executionContextRoots ?? {}),
34
34
  registeredAgents: await store.listAgents(),
@@ -1,5 +1,7 @@
1
1
  import { settleReviewRevisionRound } from './review-revision-settlement.js';
2
- import { isFinalReviewAgent, FINAL_REVIEW_AGENT, nextFinalReviewTaskId } from './final-review-role.js';
2
+ import { isFinalReviewAgent, FINAL_REVIEW_AGENT } from './final-review-role.js';
3
+ import { allocateEntityId } from './job-task-id-sequence.js';
4
+ import { relayStoreDirectory } from './relay-store.js';
3
5
  import { normalizeReviewEvidence } from './review-evidence.js';
4
6
  import { browserWorkerPool } from './browser-worker-runtime.js';
5
7
  import { storySizeTimeoutMs, taskOverallTimeoutMs } from './types.js';
@@ -30,22 +32,11 @@ export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
30
32
  return job.headSha ?? job.review?.headSha ?? null;
31
33
  if (this.options.headShaProvider)
32
34
  return this.options.headShaProvider(job);
33
- // Plan-free Coordinator Jobs execute in their explicitly bound project Git root.
34
- // Local-only repository aliases (e.g. local/vlog) may not resolve through
35
- // the managed repository inventory. Use the durable DAG start context.
36
- if (job.graphStartContext?.projectPath && !job.localMerge?.sourceRef) {
37
- try {
38
- return localWorkingHead(job.graphStartContext.projectPath);
39
- }
40
- catch {
41
- return job.headSha ?? job.review?.headSha ?? null;
42
- }
43
- }
44
35
  // GitHub PR head facts are audit-only. Source identity is local Git.
45
- if (!this.options.projectPathForJob)
36
+ if (!this.options.cwdForJob)
46
37
  return job.headSha ?? job.review?.headSha ?? null;
47
38
  try {
48
- const project = await this.options.projectPathForJob(job);
39
+ const project = await this.options.cwdForJob(job);
49
40
  if (job.localMerge?.sourceRef)
50
41
  return localSourceHead(project, job.localMerge.sourceRef);
51
42
  return localWorkingHead(project);
@@ -59,7 +50,7 @@ export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
59
50
  const currentReviewTask = job.review?.taskId ? job.tasks.find(task => task.id === job.review?.taskId) : undefined;
60
51
  return {
61
52
  reviewEnabled: job.reviewEnabled !== false,
62
- jobActive: job.state === 'ACTIVE' || job.projectionRecovery?.status === 'repairing',
53
+ jobActive: job.state === 'ACTIVE',
63
54
  reviewWorkSettled: reviewWorkSettled(job),
64
55
  headAvailable: Boolean(headSha),
65
56
  reviewPlanReady: reviewPlanReady(job),
@@ -115,8 +106,8 @@ export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
115
106
  }
116
107
  }
117
108
  async createFinalReviewTask(job, headSha) {
118
- const id = nextFinalReviewTaskId(job, headSha);
119
- const reviewPrNumber = job.prNumber;
109
+ const reviewRound = job.tasks.filter(task => task.reviewHeadSha === headSha && isFinalReviewAgent(task.agentName)).length + 1;
110
+ const id = allocateEntityId(relayStoreDirectory(), job.repository, 'task', `final-review:${job.id}:${headSha}:${reviewRound}`);
120
111
  const now = new Date().toISOString();
121
112
  const reviewGateTasks = implementationTasks(job);
122
113
  const reviewThread = resolveReviewerThreadDestination(job, this.options.reviewer?.threadId);
@@ -126,19 +117,19 @@ export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
126
117
  }, this.options.reviewer?.threadId);
127
118
  const input = [
128
119
  `Job ID: ${job.id}`,
129
- reviewPrNumber > 0 ? `Review PR #${reviewPrNumber} at exactly head SHA ${headSha}.` : `Review the local Job artifact at exactly head SHA ${headSha}.`,
120
+ `Review the local Git Job artifact at exactly head SHA ${headSha}.`,
130
121
  `Review head SHA: ${headSha}`,
131
122
  'Job objective: ' + (job.objective ?? job.description ?? job.title),
132
- 'Review the complete PR diff at this exact immutable head SHA, not only the dependency Tasks.',
123
+ 'Review the complete local Git diff at this exact immutable head SHA, not only the dependency Tasks.',
133
124
  'Use the selected reviewer agent contract as the authoritative review protocol.',
134
- 'This is a PRE-MERGE artifact approval gate: inspect exact PR head, requirements, tests and genuine blocking defects.',
125
+ 'This is a PRE-MERGE artifact approval gate: inspect the exact local Git head, requirements, tests and genuine blocking defects.',
135
126
  'Do not block approval because automatic merge, Job COMPLETED, or post-merge validation has not occurred yet.',
136
127
  'All non-review Tasks have terminal outcomes. Examine FAILED and CANCELLED Tasks and their recovery evidence; never approve an unresolved required outcome.',
137
128
  'The Final Review is the Job completion check. Persist concrete, owner-attributed findings with a changes-required verdict. A Job without an explicit Planner remains plan-free; request targeted revisions rather than assuming Relay creates a Planner round.',
138
129
  'Do not treat historical failed attempts as current artifact defects; distinguish preserved baseline files from implementation.',
139
130
  ].join('\n\n');
140
131
  const task = createTaskEntity(job, {
141
- jobId: job.id, id, title: 'Review', kind: 'work', priority: job.priority, storySize: 'M', projectName: job.title, agentName: FINAL_REVIEW_AGENT,
132
+ jobId: job.id, id, title: 'Final Review', kind: 'work', priority: job.priority, storySize: 'M', projectName: job.title, agentName: FINAL_REVIEW_AGENT,
142
133
  parentTaskId: null, dependencies: [], capabilities: ['review'],
143
134
  workerSelection: reviewerRouting.selection, adapter: reviewerRouting.candidate.adapter,
144
135
  input,
@@ -152,23 +143,7 @@ export class ReconcilerReviewBase extends ReconcilerRuntimeBase {
152
143
  await this.emit(eventFor(job.id, id, task.parentTaskId, 'review.created', 'queued', 'Final review task ' + id + ' created for ' + headSha + ' using ' + reviewerRouting.reason, 'orchestrator', { headSha, agentName: FINAL_REVIEW_AGENT, reviewerRouting: { workerId: reviewerRouting.selection.workerId, reason: reviewerRouting.reason, selectedBy: reviewerRouting.selection.selectedBy } }));
153
144
  return id;
154
145
  }
155
- async projectedReviewHeadReady(job, headSha) {
156
- // Local-first Jobs may expose a review-only GitHub PR. Once such a PR is
157
- // bound, its projected head must match the authoritative local head before
158
- // a reviewer is asked to review that immutable PR identity.
159
- if (!job.localMerge?.sourceRef || job.prNumber <= 0 || !this.store.pullRequestHead)
160
- return true;
161
- try {
162
- const projected = await this.store.pullRequestHead();
163
- return projected?.sha === headSha;
164
- }
165
- catch {
166
- return false;
167
- }
168
- }
169
146
  async ensureFinalReview(job, headSha) {
170
- if (headSha && !(await this.projectedReviewHeadReady(job, headSha)))
171
- return;
172
147
  job = await settleReviewRevisionRound(this.store, job);
173
148
  // Restore the review gate only after an authoritative unblock of the original reviewer.
174
149
  const priorReviewTask = job.tasks.find(task => task.id === job.review?.taskId);
@@ -94,10 +94,7 @@ export class ReconcilerRuntimeBase {
94
94
  const latest = await this.store.load(event.job_id);
95
95
  const task = latest.tasks.find(item => item.id === event.task_id);
96
96
  if (task?.dagNode) {
97
- // Use the Coordinator's durable checkout for DAG stage validation.
98
- // An independent local repo need not resolve through generic workspace lookup.
99
- const projectPath = latest.graphStartContext?.projectPath ??
100
- (this.options.projectPathForJob ? await this.options.projectPathForJob(latest, task) : undefined);
97
+ const projectPath = this.options.cwdForJob ? await this.options.cwdForJob(latest, task) : undefined;
101
98
  const invalid = await dagCompletionError(task, projectPath);
102
99
  if (invalid)
103
100
  return this.applyTerminalEvent({ ...event, type: 'task.failed',
@@ -57,7 +57,7 @@ export class Reconciler extends ReconcilerReviewBase {
57
57
  await this.launch(job, task);
58
58
  }, context => `effect.launchTask:${context.jobId}:${context.taskId ?? 'task'}:${String(context.data?.attempt ?? 0)}:${String(context.data?.reviewInvocationId ?? 'initial')}`));
59
59
  this.workflowEffects.register(new CallbackWorkflowEffectHandler('effect.cancelActiveTasks', async (context) => this.cancelActiveTasks(context.jobId, String(context.data?.reason ?? 'Job terminated'))));
60
- this.workflowEffects.register(new CallbackWorkflowEffectHandler('effect.cleanupJobWorktree', async (context) => cleanupMergedJobWorktree(await this.store.load(context.jobId), this.options.projectPathForJob), context => `effect.cleanupJobWorktree:${context.jobId}`));
60
+ this.workflowEffects.register(new CallbackWorkflowEffectHandler('effect.cleanupJobWorktree', async (context) => cleanupMergedJobWorktree(await this.store.load(context.jobId), this.options.cwdForJob), context => `effect.cleanupJobWorktree:${context.jobId}`));
61
61
  }
62
62
  async dispatchExecutableTasks(jobId) {
63
63
  const scheduled = refreshTaskDependencies(await this.store.load(jobId));
@@ -118,7 +118,7 @@ export class Reconciler extends ReconcilerReviewBase {
118
118
  } });
119
119
  return job;
120
120
  }
121
- if (job.state !== 'ACTIVE' && job.projectionRecovery?.status !== 'repairing')
121
+ if (job.state !== 'ACTIVE')
122
122
  return job;
123
123
  await recoverExpiredExecutions(job, now, this.executionRecoveryPorts(job));
124
124
  await repairLegacyOrchestrators(jobId, now, { store: this.store, owner: this.options.owner, emit: event => this.emit(event) });
@@ -195,7 +195,7 @@ export class Reconciler extends ReconcilerReviewBase {
195
195
  scheduled = refreshTaskDependencies(await this.store.load(jobId));
196
196
  }
197
197
  scheduled = refreshTaskDependencies(await this.maybeCreatePlanner(scheduled));
198
- scheduled = refreshTaskDependencies(await reconcileDAGSchedule({ store: this.store, jobId, job: scheduled, projectPathForTask: async (j, t) => j.graphStartContext?.projectPath ?? (this.options.projectPathForJob ? this.options.projectPathForJob(j, t) : t.routing?.cwd ?? process.cwd()), roots: this.options.executionContextRoots }));
198
+ scheduled = refreshTaskDependencies(await reconcileDAGSchedule({ store: this.store, jobId, job: scheduled, cwdForTask: async (j, t) => this.options.cwdForJob ? this.options.cwdForJob(j, t) : t.routing?.cwd ?? process.cwd(), roots: this.options.executionContextRoots }));
199
199
  if (scheduled.state !== previousState || scheduled.updatedAt !== job.updatedAt)
200
200
  await this.store.saveJob(scheduled);
201
201
  scheduled = await this.dispatchExecutableTasks(jobId);
@@ -205,7 +205,7 @@ export class Reconciler extends ReconcilerReviewBase {
205
205
  await this.ensureFinalReview(finalState, headSha);
206
206
  await this.dispatchExecutableTasks(jobId);
207
207
  finalState = await this.store.load(jobId);
208
- const localMergeCompleted = await reconcileLocalGitCompletion(this.store, finalState, headSha, this.options.noGitHub === true, this.options.projectPathForJob, event => this.emit(event), this.options.localMergeEffect ?? this.options.localMergeDelivery, () => (this.options.now ?? new Date()).getTime());
208
+ const localMergeCompleted = await reconcileLocalGitCompletion(this.store, finalState, headSha, this.options.noGitHub === true, this.options.cwdForJob, event => this.emit(event), this.options.localMergeEffect ?? this.options.localMergeDelivery, () => (this.options.now ?? new Date()).getTime());
209
209
  await drainProductionWorkflowOutbox(this.store, this.options);
210
210
  if (localMergeCompleted)
211
211
  return this.store.load(jobId);
@@ -447,7 +447,7 @@ export class Reconciler extends ReconcilerReviewBase {
447
447
  try {
448
448
  const role = isFinalReviewAgent(task.agentName) ? 'reviewer' : task.agentName === 'troubleshooter' ? 'troubleshooter' : task.parentTaskId ? 'nested-worker' : 'worker';
449
449
  const graphChild = Boolean(task.dagNode) || job.tasks.some(parent => parent.id === task.parentTaskId && Boolean(parent.dagNode));
450
- const projectPath = graphChild && job.graphStartContext?.projectPath ? job.graphStartContext.projectPath : this.options.projectPathForJob ? await this.options.projectPathForJob(job, task) : task.routing?.cwd ?? process.cwd();
450
+ const projectPath = this.options.cwdForJob ? await this.options.cwdForJob(job, task) : task.routing?.cwd ?? process.cwd();
451
451
  executionContext = await this.resolvedContext(job, task, role, projectPath);
452
452
  }
453
453
  catch (error) {