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
package/dist/relayd.js CHANGED
@@ -1,32 +1,22 @@
1
1
  #!/usr/bin/env node
2
2
  import { escalationNotifierFromEnvironment } from './escalation-notifier.js';
3
3
  import { once } from 'node:events';
4
- import { spawnOwnedProcess } from './owned-process.js';
5
- import { readFile } from 'node:fs/promises';
6
4
  import { homedir } from 'node:os';
7
- import { join, basename } from 'node:path';
5
+ import { join } from 'node:path';
8
6
  import { ChatGptAdapter, CodexAdapter, ensureChatGptWebHelmReady } from './adapters.js';
9
7
  import { ZAdapter } from './z-adapter.js';
10
8
  import { CodexThreadContinuation, CommandContinuation, WebhookContinuation } from './continuation.js';
11
9
  import { serveDashboard } from './dashboard.js';
12
10
  import { RepositoryWorkerPool } from './pool.js';
13
11
  import { Reconciler } from './reconciler.js';
14
- import { dashboardManagedJobs, GitHubStore, InMemoryStore, resolvePullRequest } from './store.js';
15
- import { GitHubProjectionWriter } from './projected-store.js';
12
+ import { dashboardManagedJobs, GitHubStore, InMemoryStore } from './store.js';
16
13
  import { LocalAuthorityDurableStore } from './local-authority-store.js';
17
14
  import { discoverLocalRelayStoreSnapshots, relayStoreDirectory, relayUnifiedStorePath, resolveUnifiedJobScope, SQLiteRelayStore } from './relay-store.js';
18
15
  import { createJobIdRegistryResolver } from './local-job-registry.js';
19
- import { projectAuthoritativeLocalMerge } from './local-merge-projection.js';
20
- import { archiveDisplayPullRequest } from './github-pr-archive.js';
21
- import { orderGitHubBindingCandidates } from './github-binding-order.js';
22
- import { ProjectionFailureDeduplicator } from './projection-failure-dedupe.js';
23
- import { handleGitHubProjectionFailure, projectBindingLocalMerge } from './projection-failure-recovery.js';
24
- import { authoritativeBranchPushArgs } from './github-branch-projection.js';
25
- import { githubAuthContext } from './github-auth.js';
26
- import { DisabledGitHubClient, noGitHubMode } from './no-github.js';
27
- import { dashboardJobAction, isEntrypoint, runtimePlanner, runtimeReviewer, startService, SERVICE_DEFAULTS } from './cli.js';
16
+ import { reconcileCompletedLocalDelivery } from './local-merge-projection.js';
17
+ import { DisabledGitHubClient } from './no-github.js';
18
+ import { dashboardJobAction, isEntrypoint, runtimePlanner, runtimeReviewer, SERVICE_DEFAULTS } from './cli.js';
28
19
  import { eventBusResolutionMessage, publishTaskUnblocked, resolveEventBus } from './cli-support.js';
29
- import { eventFor } from './events.js';
30
20
  import { dispatchTaskAction } from './task-actions.js';
31
21
  import { isEffectivelyBlocked, unblockTask } from './unblock.js';
32
22
  import { registerBlockerDependency } from './blockers.js';
@@ -35,7 +25,7 @@ import { applyJobActivateAction } from './job-actions.js';
35
25
  import { managedTaskUpdateHandler } from './task-update.js';
36
26
  import { dashboardJobSetState, dashboardTaskAction, dashboardTaskSetState } from './dashboard-actions.js';
37
27
  import { codexAndZaiUsageRegistry } from './usage.js';
38
- import { discoverWorkspaceRepositories, ensureLocalJobSourceBranch, prepareLocalJobExecutionWorktree, resolveManagedProjectPath, resolveRepositoryProjectPath, resolveWorkspaceRoot, taskRequiresManagedWorktree } from './workspace.js';
28
+ import { defaultWorkspaceRoot, ensureLocalJobSourceBranch, prepareLocalJobExecutionWorktree, resolveJobProjectRoot, taskRequiresManagedWorktree } from './workspace.js';
39
29
  import { deriveJobRuntimeStatus } from './runtime-status.js';
40
30
  import { createRuntimeStatusPublisher } from './runtime-status-events.js';
41
31
  import { subscribeLocalCommits } from './local-commit-events.js';
@@ -52,6 +42,7 @@ import { createDashboardActions } from './relayd-dashboard-actions.js';
52
42
  export { daemonHelp, normalizeDaemonArguments, overlayOperationalOverviews, mergeOperationalInventory, recoveryScanRepositories, shouldCoalescePullRequestRefresh, configureExecutionRouterRulesPath } from './relayd-utilities.js';
53
43
  import { configureDaemonObservability, firstStageChoices, value, daemonHelp, normalizeDaemonArguments, configureExecutionRouterRulesPath } from './relayd-utilities.js';
54
44
  export async function runDaemon(argv) {
45
+ const normalized = normalizeDaemonArguments(argv);
55
46
  if (argv.includes('--help') || argv.includes('-h')) {
56
47
  console.log(daemonHelp);
57
48
  return;
@@ -64,57 +55,29 @@ export async function runDaemon(argv) {
64
55
  catch (error) {
65
56
  process.stderr.write(`WebHelm readiness check skipped: ${errorMessage(error)}\n`);
66
57
  }
67
- const noGitHub = noGitHubMode(argv);
68
- if (noGitHub)
69
- process.env.AGENTS_RELAY_NO_GITHUB = '1';
70
- const normalized = normalizeDaemonArguments(argv);
71
- if (normalized.pullRequest && normalized.jobId) {
72
- await startService([...argv]);
73
- return;
74
- }
75
- // Local authority never depends on GitHub availability, but every enabled
76
- // GitHub transport must use the same authenticated context as the CLI. Probe
77
- // identity separately so an auth outage is observable without blocking startup.
78
- const auth = noGitHub ? null : await githubAuthContext(argv, undefined, false);
79
- const client = noGitHub ? new DisabledGitHubClient() : auth.client;
80
- const trusted = noGitHub ? new Set() : auth.trustedAuthors;
81
- let githubAuthenticated = noGitHub ? false : null;
58
+ const noGitHub = true;
59
+ const auth = null;
60
+ const client = new DisabledGitHubClient();
61
+ const trusted = new Set();
62
+ let githubAuthenticated = false;
82
63
  let githubAuthError = null;
83
- if (!noGitHub) {
84
- try {
85
- const login = auth?.appAuth ? await client.currentLogin() : await client.localLogin();
86
- if (!login)
87
- throw new Error('gh authentication did not return a healthy login');
88
- trusted.add(login);
89
- githubAuthenticated = true;
90
- }
91
- catch (error) {
92
- githubAuthenticated = false;
93
- githubAuthError = errorMessage(error);
94
- }
95
- }
96
64
  const concurrency = Number(value(argv, '--concurrency', '4'));
97
65
  const eventResolution = await resolveEventBus([...argv]);
98
66
  const bus = eventResolution.bus;
99
67
  const stopRuntimeStatusEvents = bus ? subscribeLocalCommits(createRuntimeStatusPublisher(bus)) : () => { };
100
68
  process.stderr.write(`${eventBusResolutionMessage(eventResolution)}\n`);
101
- const workspaceRoot = await resolveWorkspaceRoot(normalized.workspaceRoot ?? undefined);
102
- const explicitProjectPath = value(argv, '--project-path');
103
- const localProjectPath = noGitHub && !explicitProjectPath && !argv.includes('--workspace') && !argv.includes('--workspace-root') && !process.env.AGENTS_RELAY_WORKSPACE_ROOT
104
- ? process.cwd() : explicitProjectPath || workspaceRoot;
105
- const discoveredRepositories = normalized.repository || noGitHub ? [] : await discoverWorkspaceRepositories(workspaceRoot).catch(() => []);
106
- const repositories = noGitHub && !normalized.repository ? [`local/${basename(localProjectPath)}`] : normalized.repository ? [normalized.repository] : discoveredRepositories.map(item => item.repository);
107
- const repositoryPaths = new Map(discoveredRepositories.map(item => [item.repository, item.path]));
108
- if (noGitHub)
109
- for (const repo of repositories)
110
- repositoryPaths.set(repo, localProjectPath);
69
+ // Workspace is an optional execution/worktree placement hint, never a Job
70
+ // discovery source. Do not stat, recursively scan, or infer a repository from
71
+ // cwd / Workspace at daemon startup: only durable SQLite bindings select Jobs.
72
+ const workspaceRoot = normalized.workspaceRoot ?? defaultWorkspaceRoot();
73
+ const repositories = normalized.repository ? [normalized.repository] : [];
74
+ const repositoryPaths = new Map();
111
75
  const usageRegistry = codexAndZaiUsageRegistry();
112
76
  const decisionAuditStore = new JsonlDecisionAuditStore(process.env.AGENTS_RELAY_DECISION_AUDIT_PATH ?? join(homedir(), '.agents-relay', 'decision-audit.jsonl'));
113
77
  let cachedOverviews = [];
114
78
  const githubReadPaths = { workspaceScans: 0, prRefreshes: 0, prRefreshesByTrigger: {}, prRefreshCoalesced: 0, prRefreshCoalescedByTrigger: {} };
115
79
  let dormantProbeIndex = 0;
116
80
  const relayStores = new Map();
117
- const projectionWriters = new Map();
118
81
  const runtimeStore = (repository, prNumber, seed) => {
119
82
  const key = `${repository}#${prNumber}`;
120
83
  let relay = relayStores.get(key);
@@ -126,8 +89,6 @@ export async function runDaemon(argv) {
126
89
  const github = new GitHubStore(client, repository, prNumber, trusted, seed);
127
90
  const projected = new LocalAuthorityDurableStore(relay, github, (relatedRepository, relatedPrNumber) => runtimeStore(relatedRepository, relatedPrNumber), noGitHub);
128
91
  // SQLite PR facts are written through awaited webhook/action handlers; never seed detached remote snapshots.
129
- if (!noGitHub)
130
- projectionWriters.set(key, projected.projection);
131
92
  return projected;
132
93
  };
133
94
  const existingInventory = await discoverLocalRelayStoreSnapshots(relayStoreDirectory());
@@ -135,9 +96,11 @@ export async function runDaemon(argv) {
135
96
  for (const job of snapshot.jobs) {
136
97
  if (!repositories.includes(job.repository))
137
98
  repositories.push(job.repository);
99
+ // Blocker recovery needs a path for an existing repository: use the saved
100
+ // immutable projectRoot, never a guessed Workspace-relative directory.
101
+ if (job.projectRoot && !repositoryPaths.has(job.repository))
102
+ repositoryPaths.set(job.repository, job.projectRoot);
138
103
  }
139
- if (repositories.length === 0)
140
- repositories.push('local/' + basename(workspaceRoot));
141
104
  const inventoryFromLocal = async (limitHistory = true) => {
142
105
  const snapshots = await discoverLocalRelayStoreSnapshots(relayStoreDirectory());
143
106
  const known = new Set(repositories);
@@ -155,10 +118,10 @@ export async function runDaemon(argv) {
155
118
  return limitHistory ? dashboardManagedJobs(visible) : visible;
156
119
  };
157
120
  cachedOverviews = await inventoryFromLocal();
158
- const makeReconciler = (store, maxConcurrent) => new Reconciler(store, { noGitHub, owner: `relayd-${process.pid}`, maxConcurrent, leaseMs: Number(value(argv, '--lease-ms', '300000')), adapters: [new CodexAdapter(value(argv, '--codex', 'codex')), new ChatGptAdapter(), new ZAdapter()], continuations: [new CodexThreadContinuation(value(argv, '--codex', 'codex')), new CommandContinuation(), new WebhookContinuation()], planner: runtimePlanner(argv), usageSnapshotProvider: () => usageRegistry.snapshot(), runtimeSummaryProvider: () => ({ chatgptRunning: summarizeRuntime(cachedOverviews.map(item => item.job)).workers.chatgpt }), decisionEngine: executionDecisionEngine(), decisionMode: decisionMode(), decisionAuditStore, eventBus: bus, escalationNotifier: escalationNotifierFromEnvironment(), reviewer: runtimeReviewer(argv), executionContextRoots: { workspaceRoot }, agentPreferenceContextPathForJob: async (job) => resolveRepositoryProjectPath(repositoryPaths.get(job.repository) ?? await resolveManagedProjectPath(job.repository, explicitProjectPath, workspaceRoot), job.projectPath), projectPathForJob: async (job, task) => {
159
- const canonical = repositoryPaths.get(job.repository) ?? await resolveManagedProjectPath(job.repository, explicitProjectPath, workspaceRoot);
121
+ const makeReconciler = (store, maxConcurrent) => new Reconciler(store, { noGitHub, owner: `relayd-${process.pid}`, maxConcurrent, leaseMs: Number(value(argv, '--lease-ms', '300000')), adapters: [new CodexAdapter(value(argv, '--codex', 'codex')), new ChatGptAdapter(), new ZAdapter()], continuations: [new CodexThreadContinuation(value(argv, '--codex', 'codex')), new CommandContinuation(), new WebhookContinuation()], planner: runtimePlanner(argv), usageSnapshotProvider: () => usageRegistry.snapshot(), runtimeSummaryProvider: () => ({ chatgptRunning: summarizeRuntime(cachedOverviews.map(item => item.job)).workers.chatgpt }), decisionEngine: executionDecisionEngine(), decisionMode: decisionMode(), decisionAuditStore, eventBus: bus, escalationNotifier: escalationNotifierFromEnvironment(), reviewer: runtimeReviewer(argv), executionContextRoots: { workspaceRoot }, agentPreferenceRootForJob: async (job) => resolveJobProjectRoot(job), cwdForJob: async (job, task) => {
122
+ const canonical = await resolveJobProjectRoot(job);
160
123
  if (!(task ? taskRequiresManagedWorktree(job, task) : Boolean(job.localMerge?.sourceRef)))
161
- return resolveRepositoryProjectPath(canonical, job.projectPath);
124
+ return canonical;
162
125
  const sourceRef = job.localMerge?.sourceRef ?? await ensureLocalJobSourceBranch(canonical, job);
163
126
  if (!job.localMerge?.sourceRef) {
164
127
  if (!task || !store.mutateJob)
@@ -195,241 +158,55 @@ export async function runDaemon(argv) {
195
158
  throw new Error('Local Job ' + jobId + ' not found or ambiguous in SQLite registry');
196
159
  return binding;
197
160
  };
198
- const gitText = async (cwd, args) => await new Promise((resolve, reject) => {
199
- const child = spawnOwnedProcess('git', ['-C', cwd, ...args], { invocation: 'workspace.git', timeoutMs: 120000, spawn: { stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, GIT_TERMINAL_PROMPT: '0' } } });
200
- let stdout = '';
201
- let stderr = '';
202
- child.stdout?.on('data', chunk => { stdout += chunk.toString(); });
203
- child.stderr?.on('data', chunk => { stderr += chunk.toString(); });
204
- child.once('error', reject);
205
- child.once('close', code => code === 0 ? resolve(stdout.trim()) : reject(new Error(stderr.trim() || `git exited ${code}`)));
206
- });
207
- const refreshGitHubAuthentication = async () => {
208
- if (noGitHub)
209
- return;
210
- try {
211
- const login = auth?.appAuth ? await client.currentLogin() : await client.localLogin();
212
- if (!login)
213
- throw new Error('gh authentication did not return a healthy login');
214
- trusted.add(login);
215
- githubAuthenticated = true;
216
- githubAuthError = null;
217
- }
218
- catch (error) {
219
- githubAuthenticated = false;
220
- githubAuthError = errorMessage(error);
221
- }
222
- };
223
- const projectionFailureDeduplicator = new ProjectionFailureDeduplicator();
224
- const syncGitHubBindings = async () => {
225
- if (noGitHub)
226
- return;
227
- await refreshGitHubAuthentication();
228
- if (githubAuthenticated !== true)
229
- return;
230
- if (client.rateLimitStatus().limited)
231
- return;
161
+ const deliverCompletedJobs = async () => {
232
162
  const snapshots = await discoverLocalRelayStoreSnapshots(relayStoreDirectory());
233
- const bindingCandidates = orderGitHubBindingCandidates(snapshots.flatMap(snapshot => snapshot.jobs.map(job => ({ snapshotPath: snapshot.path, job }))));
234
- for (const candidate of bindingCandidates) {
235
- const snapshot = { path: candidate.snapshotPath };
236
- const discovered = candidate.job;
237
- try {
238
- if (!repositoryPaths.has(discovered.repository) || !discovered.localMerge?.sourceRef || !discovered.localMerge?.targetRef)
163
+ for (const snapshot of snapshots)
164
+ for (const discovered of snapshot.jobs) {
165
+ const delivery = discovered.remoteDelivery;
166
+ // Historic COMPLETED records have no delivery marker. Avoid even opening
167
+ // their writable SQLite scope during an optional delivery scan.
168
+ if (discovered.state !== 'COMPLETED' || discovered.localMerge?.status !== 'succeeded'
169
+ || !delivery || delivery.mergedCommitSha !== discovered.localMerge.mergedCommitSha
170
+ || !['pending', 'failed', 'processing'].includes(delivery.status))
239
171
  continue;
240
- const sourceRef = discovered.localMerge.sourceRef, targetRef = discovered.localMerge.targetRef;
241
- if (!sourceRef.startsWith('refs/heads/') || !targetRef.startsWith('refs/heads/'))
242
- continue;
243
- if (targetRef !== 'refs/heads/main')
244
- throw new Error('GitHub sync only supports local main as merge target');
245
- const branch = sourceRef.slice('refs/heads/'.length), base = targetRef.slice('refs/heads/'.length);
246
172
  const scopedKey = `${snapshot.path}#${discovered.id}`;
247
173
  let relay = relayStores.get(scopedKey);
248
174
  if (!relay) {
249
175
  relay = new SQLiteRelayStore(snapshot.path, discovered.id);
250
176
  relayStores.set(scopedKey, relay);
251
177
  }
252
- const canonical = repositoryPaths.get(discovered.repository) ?? await resolveManagedProjectPath(discovered.repository, explicitProjectPath, workspaceRoot);
253
- // A completed local Job may never have had a display PR. Publish main
254
- // regardless: GitHub availability cannot determine SQLite completion.
255
- if (discovered.state === 'COMPLETED' && discovered.localMerge?.status === 'succeeded'
256
- && discovered.prNumber <= 0) {
257
- const published = projectAuthoritativeLocalMerge(canonical, discovered);
258
- if (relay.mutateJob && (discovered.githubProjection?.status !== 'merged_without_pr' || discovered.githubProjection.sourceSha !== published.localMergedCommitSha))
259
- await relay.mutateJob(discovered.id, current => ({ ...current, githubProjection: { status: 'merged_without_pr', sourceSha: published.localMergedCommitSha, observedAt: new Date().toISOString() } }));
260
- if (published.status === 'projected')
261
- await bus?.publish(eventFor(discovered.id, 'projection', null, 'projection.delivered', 'succeeded', `GitHub main synchronization ${published.status}`, 'orchestrator', { operation: 'github.syncMain', deliveryStatus: published.status, mergedCommitSha: published.localMergedCommitSha }, { agent: 'relay', component: 'github-projection' }));
178
+ const current = await relay.loadJob(discovered.id);
179
+ if (!current || current.state !== 'COMPLETED' || !current.remoteDelivery)
262
180
  continue;
181
+ // Validation and Git inspection occur inside the claimed delivery action:
182
+ // an inaccessible/moved checkout becomes a durable SQLite retry instead
183
+ // of being lost as a daemon-only warning before the claim.
184
+ try {
185
+ await reconcileCompletedLocalDelivery(relay, current, current.projectRoot);
263
186
  }
264
- const terminal = ['COMPLETED', 'CANCELLED'].includes(discovered.state);
265
- const sourceSha = await gitText(canonical, ['rev-parse', '--verify', sourceRef]).catch(() => '');
266
- if (!sourceSha)
267
- continue;
268
- let job = (await relay.loadJob(discovered.id)) ?? discovered;
269
- let prNumber = job.prNumber > 0 ? job.prNumber : 0;
270
- // The callback is part of the durable create intent, not daemon memory.
271
- // Rebuild it on every scan so a reclaimed row remains executable after a
272
- // crash, including when the binding mutation committed first.
273
- const effect = async (item) => {
274
- const payload = item.payload;
275
- await gitText(canonical, ['fetch', '--no-tags', 'origin', `+refs/heads/${payload.base}:refs/remotes/origin/${payload.base}`]);
276
- const remoteRef = `refs/remotes/origin/${payload.head}`;
277
- const remoteHeadSha = await gitText(canonical, ['rev-parse', '--verify', remoteRef]).catch(() => '');
278
- const remoteTreeMatchesBase = remoteHeadSha ? await gitText(canonical, ['diff', '--quiet', `refs/remotes/origin/${payload.base}`, remoteRef]).then(() => true, () => false) : false;
279
- await gitText(canonical, authoritativeBranchPushArgs({ sourceRef: payload.sourceRef, branch: payload.head, remoteHeadSha: remoteHeadSha || null, remoteTreeMatchesBase }));
280
- // Lookup by head/base first: a crash after GitHub created the PR must
281
- // bind the existing collaboration projection rather than create one.
282
- const pr = await resolvePullRequest(client, payload.repository, { head: payload.head, base: payload.base, title: payload.title, body: payload.body });
283
- if (!relay.mutateJob)
284
- throw new Error('Atomic SQLite mutation is required for GitHub PR binding');
285
- await relay.mutateJob(job.id, current => ({ ...current, prNumber: pr.number, githubProjection: { status: 'pr_bound', sourceSha, observedAt: new Date().toISOString() }, updatedAt: new Date().toISOString() }));
286
- observability().record({ stage: 'projection', event: 'github.pr_bound', outcome: 'succeeded', message: `Bound local Job ${job.id} to GitHub PR #${pr.number}`, correlation: { repository: job.repository, prNumber: pr.number, jobId: job.id }, data: { head: branch, base } });
287
- };
288
- projectionWriters.set(`job:${job.id}`, new GitHubProjectionWriter(relay, prNumber > 0 ? new GitHubStore(client, job.repository, prNumber, trusted) : new InMemoryStore(job), undefined, true, effect));
289
- if (job.state === 'CANCELLED')
290
- continue; // Drain committed effects only; never push.
291
- if (prNumber === 0) {
292
- // Do not bootstrap an empty remote-only PR commit: it would diverge from
293
- // the real local Job branch before its first Worker commit. Publish the
294
- // review-only PR when there is an actual diff against main.
295
- const ahead = Number(await gitText(canonical, ['rev-list', '--count', `${targetRef}..${sourceRef}`]));
296
- if (!Number.isFinite(ahead) || ahead <= 0) {
297
- if (terminal && relay.mutateJob && job.githubProjection?.sourceSha !== sourceSha)
298
- await relay.mutateJob(job.id, current => ({ ...current, githubProjection: { status: current.localMerge?.status === 'succeeded' ? 'merged_without_pr' : 'no_diff', sourceSha, observedAt: new Date().toISOString() } }));
299
- continue;
300
- }
301
- // GitHub compares origin/main, not local main. Do not invoke the legacy
302
- // empty-PR bootstrap path when the published base already contains the
303
- // source head (for example when main was pushed by another Job).
304
- await gitText(canonical, ['fetch', '--no-tags', 'origin', `+refs/heads/main:refs/remotes/origin/main`]);
305
- const remoteAhead = Number(await gitText(canonical, ['rev-list', '--count', `refs/remotes/origin/main..${sourceRef}`]));
306
- if (!Number.isFinite(remoteAhead) || remoteAhead <= 0) {
307
- if (terminal && relay.mutateJob && job.githubProjection?.sourceSha !== sourceSha)
308
- await relay.mutateJob(job.id, current => ({ ...current, githubProjection: { status: 'merged_without_pr', sourceSha, observedAt: new Date().toISOString() } }));
309
- continue;
310
- }
311
- // A terminal Job may drain an already-committed intent, but terminal
312
- // state is never permission to create a new external PR intent.
313
- if (!terminal && relay.enqueueExternalActionOnce)
314
- await relay.enqueueExternalActionOnce({ idempotencyKey: `create_pull_request:${job.id}:${sourceSha}`, operation: 'create_pull_request', payload: { operation: 'create_pull_request', repository: job.repository, head: branch, base, title: job.title, body: job.objective ?? job.description ?? '', sourceRef, targetRef }, priority: 100 });
315
- if (terminal)
316
- continue;
317
- continue;
318
- }
319
- if (prNumber <= 0)
320
- continue;
321
- if ((await relay.loadPullRequestFacts())?.head?.sha !== sourceSha) {
322
- await gitText(canonical, ['fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main']);
323
- const remoteRef = `refs/remotes/origin/${branch}`;
324
- await gitText(canonical, ['fetch', '--no-tags', 'origin', `+refs/heads/${branch}:${remoteRef}`]).catch(() => '');
325
- const remoteHeadSha = await gitText(canonical, ['rev-parse', '--verify', remoteRef]).catch(() => '');
326
- const sameTree = remoteHeadSha ? await gitText(canonical, ['diff', '--quiet', 'refs/remotes/origin/main', remoteRef]).then(() => true, () => false) : false;
327
- await gitText(canonical, authoritativeBranchPushArgs({ sourceRef, branch, remoteHeadSha: remoteHeadSha || null, remoteTreeMatchesBase: sameTree }));
328
- }
329
- const latestFacts = await relay.loadPullRequestFacts();
330
- if (latestFacts?.state !== 'MERGED' && (latestFacts?.head?.sha !== sourceSha || latestFacts?.head?.ref !== branch)) {
331
- await relay.savePullRequestFacts({ state: latestFacts?.state === 'CLOSED' ? 'CLOSED' : 'OPEN', head: { ref: branch, sha: sourceSha }, observedAt: new Date().toISOString() });
332
- }
333
- const github = new GitHubStore(client, job.repository, prNumber, trusted);
334
- projectionWriters.set(`job:${job.id}`, new GitHubProjectionWriter(relay, github, undefined, true, effect));
335
- if (job.state === 'COMPLETED' && job.localMerge?.status === 'succeeded' && job.localMerge.projectionStrategy === 'target_ref_push') {
336
- const projection = await projectBindingLocalMerge(job, relay, {
337
- projectPath: canonical,
338
- project: async (projectedJob) => projectAuthoritativeLocalMerge(canonical, projectedJob),
339
- verifyObservedRemote: async (sha) => {
340
- try {
341
- await gitText(canonical, ['merge-base', '--is-ancestor', sha, 'refs/heads/main']);
342
- }
343
- catch {
344
- throw new Error(`Projection recovery did not preserve observed origin/main ${sha} in local main`);
345
- }
346
- }, eventBus: bus,
347
- });
348
- if (projection.skip)
349
- continue;
350
- const projectedMerge = projection.projectedMerge;
351
- if (!projectedMerge)
352
- continue;
353
- await bus?.publish(eventFor(job.id, 'projection', null, 'projection.delivered', 'succeeded', `GitHub local merge projection ${projectedMerge.status}`, 'orchestrator', { operation: 'github.projectLocalMerge', deliveryStatus: projectedMerge.status, mergedCommitSha: projectedMerge.localMergedCommitSha }, { agent: 'relay', component: 'github-projection' }));
354
- // A review-only PR is never merged by GitHub. Close it after local main
355
- // has been safely published, retaining the diff, comments and commit link.
356
- const remotePr = await github.pullRequestState();
357
- await archiveDisplayPullRequest(client, job.repository, prNumber, job.id, projectedMerge.projectedCommitSha, remotePr);
358
- const projectedState = await github.pullRequestState();
359
- const projectedHead = await github.pullRequestHead();
360
- await relay.savePullRequestFacts({ state: projectedState, head: projectedHead, observedAt: new Date().toISOString() });
361
- observability().record({
362
- stage: 'projection', event: 'github.local_merge_projected', outcome: 'succeeded',
363
- message: `Projected authoritative local merge ${projectedMerge.localMergedCommitSha} to ${projectedMerge.targetRef}`,
364
- correlation: { repository: job.repository, prNumber, jobId: job.id },
365
- data: { ...projectedMerge, githubState: projectedState },
366
- });
187
+ catch (error) {
188
+ observability().record({ stage: 'projection', event: 'remote.delivery_scan_failed', level: 'warn', outcome: 'failed', message: errorMessage(error), correlation: { repository: current.repository, jobId: current.id }, data: { reason: errorMessage(error) } });
367
189
  }
368
190
  }
369
- catch (error) {
370
- await handleGitHubProjectionFailure(error, discovered, snapshot.path, { relayStores, repositoryPaths,
371
- explicitProjectPath, workspaceRoot, gitText, reconcileLocalJob: (jobId, reason) => pool.reconcileLocalJob(jobId, reason),
372
- eventBus: bus, deduplicator: projectionFailureDeduplicator });
373
- }
374
- }
375
191
  cachedOverviews = await inventoryFromLocal();
376
192
  };
377
- let githubBindingSyncInFlight = null;
378
- const syncGitHubBindingsSafely = async () => {
379
- if (githubBindingSyncInFlight)
380
- return githubBindingSyncInFlight;
381
- githubBindingSyncInFlight = (async () => {
382
- try {
383
- await syncGitHubBindings();
384
- }
385
- catch (error) {
386
- observability().record({ stage: 'projection', event: 'github.binding_sync_failed', level: 'warn', outcome: 'failed', message: `GitHub Job binding sync failed: ${errorMessage(error)}`, data: { classification: classifyFailure(error).classification, reason: errorMessage(error) } });
387
- }
388
- finally {
389
- githubBindingSyncInFlight = null;
390
- }
391
- })();
392
- return githubBindingSyncInFlight;
193
+ let remoteDeliveryInFlight = null;
194
+ const deliverCompletedJobsSafely = async () => {
195
+ if (remoteDeliveryInFlight)
196
+ return remoteDeliveryInFlight;
197
+ remoteDeliveryInFlight = deliverCompletedJobs().catch(error => {
198
+ observability().record({ stage: 'projection', event: 'remote.delivery_scan_failed', level: 'warn', outcome: 'failed',
199
+ message: `Optional remote delivery scan failed: ${errorMessage(error)}` });
200
+ }).finally(() => { remoteDeliveryInFlight = null; });
201
+ return remoteDeliveryInFlight;
393
202
  };
394
203
  const pool = new RepositoryWorkerPool(concurrency, makeReconciler, inventoryFromLocal, localJobBinding);
395
204
  const initial = cachedOverviews;
396
205
  const fallback = initial[0]?.job;
397
206
  const dashboardStore = fallback ? (await requireLocalJobBinding(fallback.id)).store : new InMemoryStore();
398
207
  const { dashboardOverview, workspaceJobAction, workspaceJobSetState, workspaceTaskCreate, workspaceTaskAction, workspaceTaskSetState } = createDashboardActions({ getOverviews: () => cachedOverviews, requireLocalJobBinding, pool, dashboardJobAction, makeReconciler, concurrency, dashboardJobSetState, refreshAll, applyJobActivateAction, bus, dashboardTaskAction, dashboardTaskSetState });
399
- const workspaceControl = createWorkspaceControl({ client, trusted, noGitHub, repositories, refreshAll, requireLocalJobBinding, makeReconciler, concurrency, pool, bus, isEffectivelyBlocked, unblockTask, publishTaskUnblocked, dispatchTaskAction, registerBlockerDependency, discoverAgents, ensureManagedGitHubJob });
400
- const secretFile = value(argv, '--github-webhook-secret-file');
401
- const secret = noGitHub ? '' : value(argv, '--github-webhook-secret') || process.env.AGENTS_RELAY_GITHUB_WEBHOOK_SECRET || (secretFile ? (await readFile(secretFile, 'utf8')).trim() : '');
402
- const webhook = secret ? {
403
- secret,
404
- repositories: new Set(repositories),
405
- wake: async (event) => {
406
- const targets = cachedOverviews.filter(item => item.job.repository === event.repository && (event.jobId ? item.job.id === event.jobId : item.job.prNumber === event.pullRequest));
407
- if (targets.length === 0)
408
- return;
409
- for (const target of targets) {
410
- const binding = await requireLocalJobBinding(target.job.id);
411
- const store = binding.store;
412
- if (event.pullRequestFacts && store.applyPullRequestFacts) {
413
- await store.applyPullRequestFacts({ ...event.pullRequestFacts,
414
- observedAt: event.pullRequestFacts.observedAt ?? new Date().toISOString() });
415
- target.githubState = await store.pullRequestState?.() ?? target.githubState;
416
- }
417
- if (event.publication || event.publishFailure) {
418
- const relay = binding.relay;
419
- try {
420
- const inserted = await relay.recordPublication(target.job.id, event.deliveryId, event.publication, event.publishFailure ?? null, event.publicationObservedAt);
421
- // Replayed webhook deliveries may retry EventBus delivery; SQLite state remains idempotent.
422
- const state = await relay.loadPublication(target.job.id);
423
- target.publication = state?.latest ?? null;
424
- target.publicationFailure = state?.failure ?? null;
425
- }
426
- finally { /* The SQLite registry owns the shared connection. */ }
427
- }
428
- // GitHub is an audit input only: no workflow or reconcile wake.
429
- }
430
- cachedOverviews = dashboardManagedJobs(cachedOverviews);
431
- }
432
- } : undefined;
208
+ const workspaceControl = createWorkspaceControl({ client, trusted, noGitHub, repositories, repositoryPaths, refreshAll, requireLocalJobBinding, makeReconciler, concurrency, pool, bus, isEffectivelyBlocked, unblockTask, publishTaskUnblocked, dispatchTaskAction, registerBlockerDependency, discoverAgents, ensureManagedGitHubJob });
209
+ const webhook = undefined;
433
210
  const exactJob = async (jobId, target) => {
434
211
  let cached = dashboardOverview(jobId, target);
435
212
  if (!cached)
@@ -541,21 +318,7 @@ export async function runDaemon(argv) {
541
318
  observability().record({ stage: 'daemon', event: 'daemon.reconcile_failed', level: 'warn', outcome: 'failed', message: `Workspace reconcile unavailable: ${errorMessage(error)}`, data: { classification: classifyFailure(error).classification, reason: errorMessage(error) } });
542
319
  }
543
320
  };
544
- const flushProjectionsSafely = async () => {
545
- let externalActionsCompleted = 0;
546
- for (const writer of projectionWriters.values()) {
547
- try {
548
- externalActionsCompleted += (await writer.flushOnce()).projected;
549
- }
550
- catch (error) {
551
- observability().record({ stage: 'daemon', event: 'daemon.projection_flush_failed', level: 'warn', outcome: 'failed', message: `GitHub external action unavailable: ${errorMessage(error)}`, data: { classification: classifyFailure(error).classification, reason: errorMessage(error) } });
552
- }
553
- }
554
- // GitHub external acknowledgements are audit-only. Never wake local Graphs.
555
- if (externalActionsCompleted > 0)
556
- observability().record({ stage: 'daemon', event: 'github.external_actions_recorded', level: 'info', outcome: 'succeeded', message: String(externalActionsCompleted) + ' external actions acknowledged without lifecycle reconciliation' });
557
- };
558
- const watchdogDefault = webhook ? SERVICE_DEFAULTS.webhookWatchdogMs : SERVICE_DEFAULTS.watchdogMs;
321
+ const watchdogDefault = SERVICE_DEFAULTS.watchdogMs;
559
322
  let interval;
560
323
  let projectionInterval;
561
324
  const stop = () => { stopRuntimeStatusEvents(); if (interval)
@@ -564,15 +327,12 @@ export async function runDaemon(argv) {
564
327
  store.close(); server.close(() => process.exit(0)); }); };
565
328
  process.once('SIGINT', stop);
566
329
  process.once('SIGTERM', stop);
567
- await syncGitHubBindingsSafely();
330
+ // Start local reconciliation before optional remote effects; a slow/unreachable
331
+ // origin must not delay the SQLite-authoritative Scheduler after daemon launch.
568
332
  await pool.reconcileKnown(cachedOverviews);
569
- await flushProjectionsSafely();
570
- interval = setInterval(() => void reconcileSafely().finally(flushProjectionsSafely), Number(value(argv, '--interval', String(watchdogDefault))));
333
+ void deliverCompletedJobsSafely();
334
+ interval = setInterval(() => void reconcileSafely().finally(deliverCompletedJobsSafely), Number(value(argv, '--interval', String(watchdogDefault))));
571
335
  interval.unref();
572
- if (!noGitHub) {
573
- projectionInterval = setInterval(() => void syncGitHubBindingsSafely().then(flushProjectionsSafely), Number(value(argv, '--projection-ms', String(SERVICE_DEFAULTS.projectionFlushMs))));
574
- projectionInterval.unref();
575
- }
576
336
  console.log('Dashboard listening; repository worker pool active');
577
337
  void refreshAll(true)
578
338
  .then(items => pool.reconcileKnown(items))
@@ -3,7 +3,7 @@ import { isFinalReviewAgent } from './final-review-role.js';
3
3
  export function reviewGenerationMatches(current, original, task, headSha) {
4
4
  const fresh = current.tasks.find(item => item.id === task.id);
5
5
  if (!fresh || fresh.reviewHeadSha !== headSha
6
- || (current.state !== 'ACTIVE' && current.projectionRecovery?.status !== 'repairing')
6
+ || current.state !== 'ACTIVE'
7
7
  || (current.headSha && current.headSha !== headSha)
8
8
  || fresh.executionId !== task.executionId)
9
9
  return false;
@@ -38,6 +38,11 @@ export function reviewPlanReady(job) {
38
38
  || (review.outcome === 'stale' && (job.reviewRevisionRounds ?? []).some(round => round.reviewTaskId === review.taskId && round.status === 'changes_required'));
39
39
  if (!requiresRevision)
40
40
  return true;
41
+ // A Review-driven Plan with no actual fix cannot authorize another Review at
42
+ // the same immutable head. Otherwise satisfied/empty Planner responses loop
43
+ // indefinitely through Final Review -> Plan -> Final Review.
41
44
  return (job.plans ?? []).some(plan => plan.status === 'SUCCEEDED'
42
- && plan.trigger.source === 'review' && plan.trigger.reviewTaskId === review.taskId);
45
+ && plan.trigger.source === 'review' && plan.trigger.reviewTaskId === review.taskId
46
+ && plan.generatedTaskIds.length > 0
47
+ && plan.generatedTaskIds.every(id => job.tasks.some(task => task.id === id && task.state === 'SUCCEEDED')));
43
48
  }
@@ -1,14 +1,12 @@
1
1
  import { isFinalReviewAgent } from './final-review-role.js';
2
2
  import { appendTaskComment } from './task-comments.js';
3
- import { createHash } from 'node:crypto';
4
3
  import { createTaskEntity } from './workflow/entity-creation.js';
5
4
  import { decideRevisionLifecycle } from './workflow/revision-v2.js';
5
+ import { allocateEntityId } from './job-task-id-sequence.js';
6
+ import { relayStoreDirectory } from './relay-store.js';
6
7
  /** A stable child identity per immutable review round and responsible owner.
7
8
  * The request IDs are append-only feedback attached to this single child.
8
9
  */
9
- export function targetedRevisionTaskId(reviewTaskId, ownerTaskId) {
10
- return 'revision-' + createHash('sha256').update(JSON.stringify([reviewTaskId, ownerTaskId])).digest('hex').slice(0, 24);
11
- }
12
10
  /** A request and its source Task comment are one atomic SQLite Job snapshot mutation.
13
11
  * The caller MUST execute this reducer inside RelayStore.mutateJob. It is never
14
12
  * an out-of-band Task write and never reopens the original result.
@@ -57,7 +55,9 @@ export function recordTargetedRevisionRequest(job, input) {
57
55
  throw new Error('revision rejected: reviewer, head, execution or original owner is not current/eligible');
58
56
  }
59
57
  const now = new Date().toISOString();
60
- const childId = targetedRevisionTaskId(input.reviewTaskId, input.originalTaskId);
58
+ const childId = input.allocatedTaskId;
59
+ if (!childId || !/^[1-9][0-9]*$/.test(childId))
60
+ throw new Error('targeted revision requires a Relay-allocated Task ID');
61
61
  const request = {
62
62
  requestId: input.requestId,
63
63
  reviewTaskId: input.reviewTaskId,
@@ -119,9 +119,14 @@ export function recordTargetedRevisionRequest(job, input) {
119
119
  export async function submitTargetedRevisionRequest(store, jobId, input) {
120
120
  if (!store.mutateJob)
121
121
  throw new Error('targeted revision requires an authoritative atomic Job store');
122
+ const snapshot = store.loadJob ? await store.loadJob(jobId) : store.load ? await store.load(jobId) : null;
123
+ if (!snapshot)
124
+ throw new Error(`Job ${jobId} not found`);
125
+ const allocatedTaskId = allocateEntityId(relayStoreDirectory(), snapshot.repository, 'task', `targeted-revision:${jobId}:${input.reviewTaskId}:${input.originalTaskId}:${input.headSha}`);
126
+ const assigned = { ...input, allocatedTaskId };
122
127
  let created = false;
123
128
  const committed = await store.mutateJob(jobId, current => {
124
- created = recordTargetedRevisionRequest(current, input).created;
129
+ created = recordTargetedRevisionRequest(current, assigned).created;
125
130
  return current;
126
131
  });
127
132
  const request = committed.reviewRevisionRequests?.find(item => item.requestId === input.requestId);
@@ -12,7 +12,7 @@ export function taskExecutionContext(job, taskId, executionId) {
12
12
  ? job.tasks.filter(item => item.id === task.parentTaskId)
13
13
  : isFinalReviewAgent(task.agentName) ? task.dependencies.map(id => job.tasks.find(item => item.id === id)).filter((item) => Boolean(item)) : [];
14
14
  return { job: { id: job.id, repository: job.repository, title: job.title, objective: job.objective,
15
- projectPath: job.projectPath, state: job.state }, task, currentState: task.state, resolution: task.resolution ?? null, escalation: task.escalation ?? null,
15
+ state: job.state }, task, currentState: task.state, resolution: task.resolution ?? null, escalation: task.escalation ?? null,
16
16
  comments: task.comments ?? [], relevantTasks: relevant.map(item => ({ id: item.id, title: item.title, state: item.state, attempt: item.attempt, executionId: item.executionId, resolution: item.resolution ?? null, escalation: item.escalation ?? null, comments: item.comments ?? [], result: item.result, error: item.error, failureReason: item.failureReason })),
17
17
  dependencies: task.dependencies.map(id => job.tasks.find(item => item.id === id) ?? { id, missing: true }),
18
18
  plan: job.plans?.find(plan => plan.id === task.planningDecisionId) ?? null };