agents-relay 2.0.262 → 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 +8 -2
  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
@@ -0,0 +1,229 @@
1
+ import { DatabaseSync, backup } from 'node:sqlite';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { existsSync, mkdirSync } from 'node:fs';
4
+ const META_KEY = 'task_id_numeric_migration';
5
+ const REFERENCES = new Set([
6
+ 'taskId', 'task_id', 'parentTaskId', 'parent_task_id', 'originalTaskId',
7
+ 'targetTaskId', 'recoveryTaskId', 'reviewTaskId', 'revisionTaskId', 'coordinatorTaskId',
8
+ ]);
9
+ const ID_LISTS = new Set(['dependencies', 'generatedTaskIds', 'restateTaskIds']);
10
+ const ID_KEYED_OBJECTS = new Set(['dependencyValidity', 'dependencyVector']);
11
+ function rewriteJson(value, ids, parentKey = '', taskRecord = false) {
12
+ if (typeof value === 'string' && parentKey === 'input' && value.trim().startsWith('{')) {
13
+ try {
14
+ return JSON.stringify(rewriteJson(JSON.parse(value), ids));
15
+ }
16
+ catch {
17
+ return value;
18
+ }
19
+ }
20
+ if (Array.isArray(value)) {
21
+ return value.map(item => ID_LISTS.has(parentKey) && typeof item === 'string'
22
+ ? ids.get(item) ?? item : rewriteJson(item, ids));
23
+ }
24
+ if (!value || typeof value !== 'object') {
25
+ if ((REFERENCES.has(parentKey) || parentKey === 'nodes') && typeof value === 'string')
26
+ return ids.get(value) ?? value;
27
+ return value;
28
+ }
29
+ const output = {};
30
+ for (const [key, item] of Object.entries(value)) {
31
+ const rewrittenKey = ID_KEYED_OBJECTS.has(parentKey) ? ids.get(key) ?? key : key;
32
+ if ((taskRecord && key === 'id') || REFERENCES.has(key) || (parentKey === 'nodes' && typeof item === 'string')) {
33
+ output[rewrittenKey] = typeof item === 'string' ? ids.get(item) ?? item : item;
34
+ }
35
+ else if (key === 'tasks' || key === 'next_tasks') {
36
+ output[rewrittenKey] = Array.isArray(item)
37
+ ? item.map(task => rewriteJson(task, ids, '', true)) : item;
38
+ }
39
+ else if (parentKey === 'dependencyVector' && typeof item === 'string') {
40
+ const separator = item.indexOf(':');
41
+ output[rewrittenKey] = separator >= 0 && ids.has(item.slice(0, separator))
42
+ ? ids.get(item.slice(0, separator)) + item.slice(separator) : item;
43
+ }
44
+ else if (key === 'value' && item && typeof item === 'object' && !Array.isArray(item)
45
+ && 'jobId' in item && 'dependencies' in item && 'parentTaskId' in item) {
46
+ output[rewrittenKey] = rewriteJson(item, ids, key, true);
47
+ }
48
+ else {
49
+ output[rewrittenKey] = rewriteJson(item, ids, key);
50
+ }
51
+ }
52
+ return output;
53
+ }
54
+ /** Explicit one-time offline migration. Caller must stop Relay writers first.
55
+ * A verified SQLite backup precedes the single atomic transaction. */
56
+ export async function migrateTaskIds(databasePath, backupPath) {
57
+ const target = resolve(databasePath), backupFile = resolve(backupPath);
58
+ if (target === backupFile)
59
+ throw new Error('Backup path must differ from database path');
60
+ const db = new DatabaseSync(target);
61
+ try {
62
+ db.exec('PRAGMA busy_timeout=10000');
63
+ const marker = db.prepare("SELECT value FROM migration_metadata WHERE key=?").get(META_KEY);
64
+ const existing = db.prepare('SELECT job_id,json FROM job_snapshot').all();
65
+ for (const row of existing) {
66
+ const job = JSON.parse(row.json);
67
+ if (job.state === 'ACTIVE')
68
+ throw new Error('Preflight failed: Job ' + row.job_id + ' is ACTIVE');
69
+ }
70
+ const currentSeq = Number(db.prepare("SELECT value FROM sequences WHERE repository='*' AND kind='task'").get()?.value ?? 0);
71
+ if (marker?.value === 'complete')
72
+ return { backupPath: backupFile, taskCount: 0, duplicateTaskRecords: 0, maxId: currentSeq, alreadyMigrated: true };
73
+ if (existsSync(backupFile))
74
+ throw new Error('Backup already exists: ' + backupFile);
75
+ mkdirSync(dirname(backupFile), { recursive: true });
76
+ await backup(db, backupFile);
77
+ const copy = new DatabaseSync(backupFile, { readOnly: true });
78
+ try {
79
+ const integrity = copy.prepare('PRAGMA integrity_check').get();
80
+ if (Object.values(integrity)[0] !== 'ok')
81
+ throw new Error('Migration backup failed integrity_check');
82
+ if (Number(copy.prepare('SELECT COUNT(*) AS n FROM job_snapshot').get().n) !== existing.length)
83
+ throw new Error('Migration backup Job count mismatch');
84
+ }
85
+ finally {
86
+ copy.close();
87
+ }
88
+ db.exec('BEGIN IMMEDIATE');
89
+ try {
90
+ const rows = db.prepare('SELECT job_id,json FROM job_snapshot ORDER BY CAST(job_id AS INTEGER),job_id').all();
91
+ if (rows.length !== existing.length || rows.some((row, index) => {
92
+ const previous = existing.find(item => item.job_id === row.job_id);
93
+ return !previous || previous.json !== row.json;
94
+ }))
95
+ throw new Error('Job data changed after backup; migration refused');
96
+ const mappings = new Map();
97
+ const assigned = new Map();
98
+ let taskCount = 0, duplicateTaskRecords = 0;
99
+ for (const row of rows) {
100
+ const tasks = JSON.parse(row.json).tasks ?? [];
101
+ const aliases = new Map(), individual = [];
102
+ for (const task of tasks) {
103
+ if (!task.id || typeof task.id !== 'string')
104
+ throw new Error('Invalid Task ID in Job ' + row.job_id);
105
+ const id = String(++taskCount);
106
+ individual.push(id);
107
+ if (aliases.has(task.id))
108
+ duplicateTaskRecords++;
109
+ else
110
+ aliases.set(task.id, id);
111
+ }
112
+ mappings.set(row.job_id, aliases);
113
+ assigned.set(row.job_id, individual);
114
+ }
115
+ // Historical Job 90 has five duplicate Planner records. Preserve every
116
+ // record with a distinct new ID; legacy ambiguous references point to
117
+ // the first chronological owner, never to an invented Task.
118
+ const updateJob = db.prepare('UPDATE job_snapshot SET json=? WHERE job_id=?');
119
+ for (const row of rows) {
120
+ const aliases = mappings.get(row.job_id);
121
+ const job = rewriteJson(JSON.parse(row.json), aliases);
122
+ job.tasks.forEach((task, index) => {
123
+ task.id = assigned.get(row.job_id)[index];
124
+ if (task.parentTaskId === 'orchestrator')
125
+ task.parentTaskId = null;
126
+ if (task.agentGraph)
127
+ task.title = 'Coordinator';
128
+ else if (task.agentName === 'troubleshooter')
129
+ task.title = 'Troubleshooter';
130
+ else if (task.agentName === 'job-acceptance-reviewer' || task.agentName === 'reviewer')
131
+ task.title = 'Final Review';
132
+ else if (task.dagNode && task.agentName)
133
+ task.title = task.agentName;
134
+ });
135
+ updateJob.run(JSON.stringify(job), row.job_id);
136
+ }
137
+ const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all();
138
+ for (const { name } of tables) {
139
+ const escaped = '"' + name.replaceAll('"', '""') + '"';
140
+ const columns = db.prepare('PRAGMA table_info(' + escaped + ')').all();
141
+ const names = new Set(columns.map(column => column.name));
142
+ const jobColumn = names.has('job_id') ? 'job_id' : names.has('scope_job_id') ? 'scope_job_id' : null;
143
+ if (!jobColumn || name === 'job_snapshot')
144
+ continue;
145
+ // Update foreign Task IDs without intermediate UNIQUE/PK collisions.
146
+ if (names.has('task_id')) {
147
+ const rows = db.prepare('SELECT rowid,' + jobColumn + ' AS owner,task_id FROM ' + escaped).all();
148
+ const update = db.prepare('UPDATE ' + escaped + ' SET task_id=? WHERE rowid=?');
149
+ const changed = rows.filter(row => mappings.get(row.owner)?.has(row.task_id));
150
+ for (const row of changed)
151
+ update.run('__task_id_migration_' + row.rowid + '__', row.rowid);
152
+ for (const row of changed)
153
+ update.run(mappings.get(row.owner).get(row.task_id), row.rowid);
154
+ }
155
+ for (const column of columns.filter(column => column.name === 'json' || column.name.endsWith('_json'))) {
156
+ const field = '"' + column.name.replaceAll('"', '""') + '"';
157
+ const records = db.prepare('SELECT rowid,' + jobColumn + ' AS owner,' + field + ' AS payload FROM ' + escaped + ' WHERE ' + field + ' IS NOT NULL').all();
158
+ const update = db.prepare('UPDATE ' + escaped + ' SET ' + field + '=? WHERE rowid=?');
159
+ for (const record of records) {
160
+ const ids = mappings.get(record.owner);
161
+ if (!ids)
162
+ continue;
163
+ let parsed;
164
+ try {
165
+ parsed = JSON.parse(record.payload);
166
+ }
167
+ catch {
168
+ continue;
169
+ }
170
+ const changed = JSON.stringify(rewriteJson(parsed, ids));
171
+ if (changed !== record.payload)
172
+ update.run(changed, record.rowid);
173
+ }
174
+ }
175
+ }
176
+ // Workflow event outbox has no job_id column. Correlate each event's own
177
+ // durable job_id before rewriting its structured Task references.
178
+ if (tables.some(table => table.name === 'workflow_event_outbox')) {
179
+ const events = db.prepare('SELECT rowid,payload_json FROM workflow_event_outbox').all();
180
+ const update = db.prepare('UPDATE workflow_event_outbox SET payload_json=? WHERE rowid=?');
181
+ for (const row of events) {
182
+ let event;
183
+ try {
184
+ event = JSON.parse(row.payload_json);
185
+ }
186
+ catch {
187
+ continue;
188
+ }
189
+ const jobId = event?.job_id;
190
+ const ids = jobId ? mappings.get(jobId) : undefined;
191
+ if (!ids)
192
+ continue;
193
+ const payload = JSON.stringify(rewriteJson(event, ids));
194
+ if (payload !== row.payload_json)
195
+ update.run(payload, row.rowid);
196
+ }
197
+ }
198
+ // Old idempotency reservations may refer to Tasks that were deleted.
199
+ // Never allow such a reservation to resurrect an unknown numeric ID.
200
+ if (tables.some(table => table.name === 'idempotency')) {
201
+ const items = db.prepare("SELECT rowid,request_key,entity_id FROM idempotency WHERE kind='task'").all();
202
+ const update = db.prepare('UPDATE idempotency SET entity_id=? WHERE rowid=?');
203
+ const remove = db.prepare('DELETE FROM idempotency WHERE rowid=?');
204
+ for (const row of items) {
205
+ const candidates = [...mappings].filter(([, map]) => map.has(row.entity_id))
206
+ .map(([jobId, map]) => ({ jobId, id: map.get(row.entity_id) }));
207
+ const resolved = candidates.length === 1 ? candidates[0] :
208
+ candidates.find(candidate => row.request_key.includes(':' + candidate.jobId + ':'));
209
+ if (resolved)
210
+ update.run(resolved.id, row.rowid);
211
+ else
212
+ remove.run(row.rowid);
213
+ }
214
+ }
215
+ const next = Math.max(taskCount, currentSeq);
216
+ db.prepare("INSERT INTO sequences(repository,kind,value) VALUES('*','task',?) ON CONFLICT(repository,kind) DO UPDATE SET value=excluded.value").run(next);
217
+ db.prepare("INSERT INTO migration_metadata(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(META_KEY, 'complete');
218
+ db.exec('COMMIT');
219
+ return { backupPath: backupFile, taskCount, duplicateTaskRecords, maxId: next, alreadyMigrated: false };
220
+ }
221
+ catch (error) {
222
+ db.exec('ROLLBACK');
223
+ throw error;
224
+ }
225
+ }
226
+ finally {
227
+ db.close();
228
+ }
229
+ }
@@ -10,7 +10,7 @@ export function completionGateSatisfied(job) {
10
10
  // Plan-free Coordinator Graph Jobs have a durable Coordinator Task instead of a Planner.
11
11
  // Do not let unrelated successful work or an incomplete Coordinator satisfy this gate.
12
12
  const coordinatorSatisfied = (job.plans?.length ?? 0) === 0
13
- && job.tasks.some(task => task.id === 'coordinator' && task.state === 'SUCCEEDED');
13
+ && job.tasks.some(task => task.title === 'Coordinator' && Boolean(task.agentGraph) && task.state === 'SUCCEEDED');
14
14
  const implementation = implementationTasks(job);
15
15
  return (planSatisfied || legacySatisfied || coordinatorSatisfied)
16
16
  && implementation.length > 0 && implementation.every(task => task.state === 'SUCCEEDED');
@@ -1,17 +1,16 @@
1
1
  import { taskOverallTimeoutMs } from './types.js';
2
2
  import { dispatchTroubleshooter } from './workflow/troubleshooter-v2.js';
3
3
  import { createTaskEntity } from './workflow/entity-creation.js';
4
- function slug(value) {
5
- return value.replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 72) || 'task';
4
+ import { allocateEntityId } from './job-task-id-sequence.js';
5
+ import { relayStoreDirectory } from './relay-store.js';
6
+ export function troubleshooterTaskId(task, repository = 'relay') {
7
+ return allocateEntityId(relayStoreDirectory(), repository, 'task', `troubleshooter:${task.jobId}:${task.id}`);
6
8
  }
7
- export function troubleshooterTaskId(task) {
8
- return `troubleshoot-${slug(task.id)}`;
9
- }
10
- function failureInput(job, task, recoveryId = troubleshooterTaskId(task)) {
9
+ function failureInput(job, task) {
11
10
  return `Recover the failed/blocked task below and make it move again if technically safe.
12
11
 
13
12
  Original repository: ${job.repository}
14
- Original PR: #${job.prNumber}
13
+ Local Git root: ${job.projectRoot}
15
14
  Original job: ${job.id}
16
15
  Original task: ${task.id}
17
16
  Original task URL: ${task.taskUrl ?? 'unknown'}
@@ -33,16 +32,14 @@ const ACTIVE_RECOVERY_STATES = new Set(['DRAFT', 'QUEUED', 'RUNNING', 'BLOCKED']
33
32
  function recoveryTargetsTask(recovery, original) {
34
33
  if (recovery.agentName !== 'troubleshooter')
35
34
  return false;
36
- if (recovery.parentTaskId)
37
- return recovery.parentTaskId === original.id;
38
- return recovery.id === troubleshooterTaskId(original) || recovery.id.startsWith(`troubleshoot-${slug(original.id)}-a`);
35
+ return recovery.parentTaskId === original.id;
39
36
  }
40
37
  function hasRecoveryBarrier(job, original) {
41
38
  // Exactly one durable recovery identity per original Task, across all failures.
42
39
  return job.tasks.some(task => recoveryTargetsTask(task, original));
43
40
  }
44
41
  function recoveryEpisode(recovery) {
45
- return recovery.recoveryForAttempt ?? Number(/-a(\d+)$/.exec(recovery.id)?.[1] ?? -1);
42
+ return recovery.recoveryForAttempt ?? -1;
46
43
  }
47
44
  /** Reuse the existing recovery rather than creating one child per worker retry. */
48
45
  export function pendingTroubleshooterReopens(job) {
@@ -71,33 +68,33 @@ export function pendingTroubleshooterRetries(job) {
71
68
  });
72
69
  }
73
70
  export function refreshTroubleshooterInput(job, original, recovery) {
74
- recovery.input = failureInput(job, original, recovery.id);
71
+ recovery.input = failureInput(job, original);
75
72
  recovery.recoveryForAttempt = original.attempt;
76
73
  recovery.maxAttempts = Math.max(recovery.maxAttempts, recovery.attempt + 3);
77
74
  recovery.routing = undefined;
78
75
  recovery.workerSelection = undefined;
79
76
  }
80
77
  export function pendingTroubleshooterTasks(job) {
81
- const existing = new Set(job.tasks.filter(task => task.agentName === 'troubleshooter').map(task => task.id));
82
78
  const recoveries = [];
83
79
  for (const task of job.tasks) {
84
- const id = troubleshooterTaskId(task);
80
+ const existingForTask = job.tasks.some(candidate => candidate.agentName === 'troubleshooter' && candidate.parentTaskId === task.id);
85
81
  let create = false;
86
82
  const decision = dispatchTroubleshooter({
87
83
  failedWork: task.state === 'FAILED',
88
84
  ordinaryWork: task.kind !== 'planner' && task.agentName !== 'troubleshooter',
89
85
  currentRun: belongsToCurrentRun(job, task),
90
86
  needsRecovery: !(task.state === 'BLOCKED' && (Boolean(task.unblock) || Boolean(task.interactiveInvocation))),
91
- idUnused: !existing.has(id),
87
+ idUnused: !existingForTask,
92
88
  noRecoveryBarrier: !hasRecoveryBarrier(job, task),
93
89
  }, () => { create = true; });
94
90
  if (!decision.accepted || !create)
95
91
  continue;
92
+ const id = troubleshooterTaskId(task, job.repository);
96
93
  const now = new Date().toISOString();
97
94
  recoveries.push(createTaskEntity(job, {
98
95
  jobId: job.id,
99
96
  id,
100
- title: 'Troubleshoot',
97
+ title: 'Troubleshooter',
101
98
  recoveryForAttempt: task.attempt,
102
99
  kind: 'work',
103
100
  priority: 'P0',
@@ -22,6 +22,15 @@ export function createUnifiedJobIfAbsent(db, job, writeSnapshot) {
22
22
  db.exec('COMMIT');
23
23
  return JSON.parse(existing.json);
24
24
  }
25
+ // Repository names are local identities, not freely reused GitHub labels.
26
+ // Across Jobs they must always resolve to the same immutable canonical root.
27
+ const siblings = db.prepare("SELECT job_id,json FROM job_snapshot WHERE job_id<>? AND json_extract(json,'$.repository')=?")
28
+ .all(job.id, job.repository);
29
+ for (const sibling of siblings) {
30
+ const registered = JSON.parse(sibling.json);
31
+ if (!registered.projectRoot || registered.projectRoot !== job.projectRoot)
32
+ throw new Error(`Local repository identity collision: ${job.repository} belongs to ${registered.projectRoot ?? 'unmigrated Job ' + sibling.job_id}, not ${job.projectRoot}`);
33
+ }
25
34
  writeSnapshot(new Date().toISOString());
26
35
  db.exec('COMMIT');
27
36
  return structuredClone(job);
@@ -4,40 +4,44 @@ import { dispatchWorkflowGraphSync } from './dispatcher.js';
4
4
  const source = readFileSync(new URL('../../workflow/projection-conflict.mmd', import.meta.url), 'utf8');
5
5
  const boolGuard = (name) => (facts) => facts.durableFacts[name] === true;
6
6
  const guards = {
7
- deterministicDefinitionConflict: boolGuard('deterministicDefinitionConflict'),
8
- 'projection.recoveryInProgress': boolGuard('recoveryInProgress'),
9
- 'projection.recoveryEligible': (facts) => {
10
- const values = facts.durableFacts;
11
- return values.jobState === 'COMPLETED' && values.mergeSucceeded === true
12
- && values.projectionStrategy === 'target_ref_push' && values.divergenceConfirmed === true
13
- && values.remoteShaAvailable === true
14
- && values.sameIdempotencyKey !== true && values.recoveryInProgress !== true
15
- && Number(values.attempts ?? 0) < Number(values.maxAttempts ?? 0);
16
- },
17
- 'projection.recoveryExhausted': (facts) => {
18
- const values = facts.durableFacts;
19
- return values.jobState === 'COMPLETED' && values.divergenceConfirmed === true && values.remoteShaAvailable === true
20
- && values.sameIdempotencyKey !== true && values.recoveryInProgress !== true
21
- && Number(values.attempts ?? 0) >= Number(values.maxAttempts ?? 0);
22
- },
23
- 'projection.retryAvailable': (facts) => facts.durableFacts.taskRetryAvailable === true
24
- && Number(facts.durableFacts.attempts ?? 0) < Number(facts.durableFacts.maxAttempts ?? 0),
25
- 'projection.repairReviewed': (facts) => facts.durableFacts.repairTaskState === 'SUCCEEDED' && facts.durableFacts.reviewOutcome === 'approved',
26
- 'projection.repairFailed': (facts) => facts.durableFacts.repairTaskState === 'FAILED' || facts.durableFacts.repairTaskState === 'BLOCKED'
27
- || facts.durableFacts.reviewOutcome === 'blocked' || facts.durableFacts.reviewTaskState === 'FAILED',
7
+ 'delivery.originUsable': boolGuard('originUsable'),
8
+ 'delivery.claimAvailable': boolGuard('claimAvailable'),
9
+ 'delivery.remoteMainPresent': boolGuard('remoteMainPresent'),
10
+ 'delivery.remoteContainsMain': boolGuard('remoteContainsMain'),
11
+ 'delivery.retryDue': boolGuard('retryDue'),
12
+ 'delivery.retryAvailable': (facts) => Number(facts.durableFacts.attempts ?? 0) < Number(facts.durableFacts.maxAttempts ?? 0),
28
13
  };
29
14
  export const projectionConflictV2 = new GraphRuntime(source, {
30
- states: new Set(['classify', 'repairing', 'retry', 'conflict', 'escalated', 'projected']),
15
+ states: new Set(['classify', 'inspect', 'push', 'waiting', 'delivered', 'skipped', 'exhausted']),
31
16
  guards,
32
- actions: Object.fromEntries(['projection.createRecoveryTask', 'effect.projectLocalMerge', 'projection.escalate'].map(id => [id, { id }])),
33
- events: Object.fromEntries(['projection.failed', 'projection.delivery_failed', 'projection.delivered', 'reconcile'].map(id => [id, { id }])),
17
+ actions: Object.fromEntries(['delivery.claimInspection', 'delivery.skip', 'delivery.pushMain', 'delivery.recordDelivered', 'delivery.scheduleRetry', 'delivery.recordExhausted'].map(id => [id, { id }])),
18
+ events: Object.fromEntries(['job.completed', 'inspect.completed', 'delivery.pushed', 'delivery.failed', 'delivery.retry_due'].map(id => [id, { id }])),
34
19
  });
35
- /** The decision is graph-owned; callers supply SQLite and inspected Git facts. */
20
+ // A separate Graph preserves historical SQLite projection-outbox conflict
21
+ // classification without confusing it with optional post-COMPLETED Git delivery.
22
+ const outboxSource = readFileSync(new URL('../../workflow/projection-outbox-conflict.mmd', import.meta.url), 'utf8');
23
+ export const projectionOutboxConflictV2 = new GraphRuntime(outboxSource, {
24
+ states: new Set(['classify', 'conflict', 'retry']),
25
+ guards: { deterministicDefinitionConflict: boolGuard('deterministicDefinitionConflict') },
26
+ actions: {},
27
+ events: { 'projection.failed': { id: 'projection.failed' } },
28
+ });
29
+ /** Graph-owned historical outbox classification; no Job lifecycle mutation. */
36
30
  export function decideProjectionFailure(facts) {
37
- return dispatchWorkflowGraphSync(projectionConflictV2, {
31
+ return dispatchWorkflowGraphSync(projectionOutboxConflictV2, {
38
32
  initialState: 'classify',
39
33
  input: { transport: 'event', id: 'projection.failed', payload: {} },
40
34
  durableFacts: facts,
35
+ graphName: 'projection-outbox-conflict',
36
+ maxSteps: 1,
37
+ });
38
+ }
39
+ export function decideProjectionDelivery(state, event, facts) {
40
+ return dispatchWorkflowGraphSync(projectionConflictV2, {
41
+ initialState: state,
42
+ input: { transport: 'event', id: event, payload: {} },
43
+ durableFacts: facts,
44
+ graphName: 'projection-conflict',
41
45
  maxSteps: 1,
42
46
  });
43
47
  }
@@ -26,8 +26,7 @@ export function relatedTaskActionFacts(task, candidate) {
26
26
  return {
27
27
  otherTask: candidate.id !== task.id,
28
28
  recoveryForTask: candidate.agentName === 'troubleshooter'
29
- && (candidate.parentTaskId === task.id
30
- || (!candidate.parentTaskId && candidate.id.startsWith(`troubleshoot-${task.id}-a`))),
29
+ && (candidate.parentTaskId === task.id),
31
30
  candidateCancellable: decideTaskLifecycle(candidate, 'cancel').accepted,
32
31
  };
33
32
  }
package/dist/workspace.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { lstat, mkdir, readdir, realpath, stat } from 'node:fs/promises';
2
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
2
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
3
3
  import { homedir } from 'node:os';
4
4
  import { createHash } from 'node:crypto';
5
5
  import { spawnOwnedProcess } from './owned-process.js';
@@ -14,6 +14,31 @@ async function gitOutput(args) {
14
14
  child.once('close', code => code === 0 ? resolve(stdout) : reject(new Error(stderr.trim() || `git exited ${code}`)));
15
15
  });
16
16
  }
17
+ /** Canonical local identity is the Git root directory name; GitHub is a separate optional remote. */
18
+ export async function validateProjectRoot(projectRoot, repository) {
19
+ if (!isAbsolute(projectRoot))
20
+ throw new Error('Job projectRoot must be absolute');
21
+ const canonical = await realpath(projectRoot);
22
+ const root = await git(canonical, ['rev-parse', '--show-toplevel']);
23
+ const realRoot = await realpath(root);
24
+ if (canonical !== realRoot)
25
+ throw new Error(`Job projectRoot must be the canonical Git root: ${realRoot}`);
26
+ const gitDir = await realpath(await git(canonical, ['rev-parse', '--absolute-git-dir']));
27
+ const gitCommonDir = await realpath(await git(canonical, ['rev-parse', '--path-format=absolute', '--git-common-dir']));
28
+ if (gitDir !== gitCommonDir)
29
+ throw new Error('Job projectRoot must be the primary Git checkout, not a linked worktree');
30
+ if (basename(realRoot) !== repository)
31
+ throw new Error(`Local repository identity ${repository} does not match Git root name ${basename(realRoot)}`);
32
+ return realRoot;
33
+ }
34
+ export async function optionalGitHubRepository(projectRoot) {
35
+ try {
36
+ return githubRepositoryFromRemote(await git(projectRoot, ['remote', 'get-url', 'origin'])) ?? undefined;
37
+ }
38
+ catch {
39
+ return undefined;
40
+ }
41
+ }
17
42
  export function defaultWorkspaceRoot() {
18
43
  return join(homedir(), 'Workspace');
19
44
  }
@@ -74,24 +99,20 @@ async function origin(path) {
74
99
  }
75
100
  export async function discoverWorkspaceRepositories(root) {
76
101
  const paths = await discoverGitRepositories(root);
77
- const discovered = await Promise.all(paths.map(async (path) => {
78
- const repository = githubRepositoryFromRemote(await origin(path) ?? '');
79
- return repository ? { path, repository } : null;
80
- }));
81
- const unique = new Map();
102
+ const discovered = await Promise.all(paths.map(async (path) => ({ path: await realpath(path), repository: basename(path), githubRepo: githubRepositoryFromRemote(await origin(path) ?? '') })));
103
+ const identities = new Map();
82
104
  for (const item of discovered) {
83
- if (!item)
84
- continue;
85
- const current = unique.get(item.repository);
86
- if (!current || repositoryPathRank(item.path, root) < repositoryPathRank(current.path, root))
87
- unique.set(item.repository, item);
105
+ const previous = identities.get(item.repository);
106
+ if (previous && previous !== item.path)
107
+ throw new Error(`Local repository identity collision ${item.repository}: ${previous} and ${item.path}`);
108
+ identities.set(item.repository, item.path);
88
109
  }
89
- return [...unique.values()].sort((a, b) => a.repository.localeCompare(b.repository));
110
+ return discovered.map(({ path, repository }) => ({ path, repository })).sort((a, b) => a.repository.localeCompare(b.repository));
90
111
  }
91
112
  export async function resolveWorkspaceRepositoryPath(repository, root = defaultWorkspaceRoot()) {
92
113
  const match = (await discoverWorkspaceRepositories(root)).find(item => item.repository === repository);
93
114
  if (!match)
94
- throw new Error(`Repository ${repository} not found under workspace ${resolve(root)}; pass --project-path explicitly`);
115
+ throw new Error(`Repository ${repository} not found under workspace ${resolve(root)}; provide the canonical Git root explicitly`);
95
116
  return match.path;
96
117
  }
97
118
  export async function resolveManagedProjectPath(repository, explicitProjectPath = '', root = defaultWorkspaceRoot(), cwd = process.cwd()) {
@@ -99,22 +120,10 @@ export async function resolveManagedProjectPath(repository, explicitProjectPath
99
120
  return resolve(explicitProjectPath);
100
121
  return repository ? resolveWorkspaceRepositoryPath(repository, root) : resolve(cwd);
101
122
  }
102
- export function resolveRepositoryProjectPath(repositoryRoot, projectPath) {
103
- const root = resolve(repositoryRoot);
104
- if (!projectPath)
105
- return root;
106
- if (isAbsolute(projectPath))
107
- throw new Error('Job projectPath must be repository-relative');
108
- // Legacy Jobs sometimes stored the repository folder name itself (for example
109
- // projectPath='agents-relay' for the agents-relay repository). Interpret that
110
- // historical form as the repository root instead of appending it twice.
111
- if (projectPath === basename(root))
112
- return root;
113
- const target = resolve(root, projectPath);
114
- const rel = relative(root, target);
115
- if (rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel))
116
- throw new Error('Job projectPath escapes repository root');
117
- return target;
123
+ export async function resolveJobProjectRoot(job) {
124
+ if (!job.projectRoot)
125
+ throw new Error(`Job ${job.id} is missing its immutable local projectRoot`);
126
+ return validateProjectRoot(job.projectRoot, job.repository);
118
127
  }
119
128
  export function isProjectRunPath(path) {
120
129
  if (!path)
@@ -197,15 +206,15 @@ export function managedJobWorktreePath(repository, prNumber, workspaceRoot = def
197
206
  return join(workspaceRoot, '.worktrees', 'agents-relay', `${repository.replace('/', '-')}-pr-${prNumber}`, 'job');
198
207
  }
199
208
  export function managedLocalJobWorktreePath(repository, jobId, workspaceRoot = defaultWorkspaceRoot()) {
200
- if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) || !jobId.trim())
209
+ if (!/^[A-Za-z0-9_.-]+$/.test(repository) || !jobId.trim())
201
210
  throw new Error('Invalid local Job checkout identity');
202
211
  const safeJob = jobId.replace(/[^A-Za-z0-9_.-]+/g, '-').slice(0, 72) || 'job';
203
212
  const digest = createHash('sha256').update(jobId).digest('hex').slice(0, 12);
204
- return join(workspaceRoot, '.worktrees', 'agents-relay', `${repository.replace('/', '-')}-job-${safeJob}-${digest}`, 'job');
213
+ return join(workspaceRoot, '.worktrees', 'agents-relay', `${repository}-job-${safeJob}-${digest}`, 'job');
205
214
  }
206
215
  /** Only code artifacts need an isolated Git source branch and worktree. */
207
216
  export function jobRequiresManagedWorktree(job) {
208
- return !(job.prNumber > 0) && (Boolean(job.localMerge?.sourceRef) || job.tasks.some(task => task.output?.kind === 'task_pr'));
217
+ return Boolean(job.localMerge?.sourceRef) || job.tasks.some(task => task.output?.kind === 'task_pr');
209
218
  }
210
219
  export function taskRequiresManagedWorktree(job, task) {
211
220
  return jobRequiresManagedWorktree(job) && !(task && taskUsesCanonicalProjectRun(task, job.tasks));
@@ -224,6 +233,8 @@ export async function ensureLocalJobSourceBranch(projectPath, job) {
224
233
  const digest = createHash('sha256').update(job.id).digest('hex').slice(0, 12);
225
234
  const sourceRef = `refs/heads/relay/job-${safe}-${digest}`;
226
235
  const primary = (await git(projectPath, ['rev-parse', '--show-toplevel'])).trim();
236
+ if (await realpath(primary) !== await realpath(job.projectRoot) || basename(primary) !== job.repository)
237
+ throw new Error(`Job ${job.id} projectRoot identity mismatch`);
227
238
  await git(primary, ['rev-parse', '--verify', 'refs/heads/main']);
228
239
  const exists = await gitOutput(['-C', primary, 'show-ref', '--verify', '--quiet', sourceRef]).then(() => true, () => false);
229
240
  if (!exists) {
@@ -239,23 +250,14 @@ export async function ensureLocalJobSourceBranch(projectPath, job) {
239
250
  }
240
251
  export async function prepareLocalJobExecutionWorktree(projectPath, job, workspaceRoot = defaultWorkspaceRoot()) {
241
252
  if (!job.localMerge?.sourceRef)
242
- return resolveRepositoryProjectPath(projectPath, job.projectPath);
253
+ return resolveJobProjectRoot(job);
243
254
  const sourceRef = job.localMerge.sourceRef;
244
255
  if (!/^refs\/heads\/[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(sourceRef) || sourceRef.includes('..') || sourceRef.endsWith('.lock'))
245
256
  throw new Error('Local Job execution requires a valid refs/heads sourceRef');
246
257
  const primary = await git(projectPath, ['rev-parse', '--show-toplevel']);
247
- const projectRelative = (await git(projectPath, ['rev-parse', '--show-prefix'])).replace(/\/$/, '');
248
- const effectiveProject = (checkoutRoot) => job.projectPath
249
- ? resolveRepositoryProjectPath(checkoutRoot, job.projectPath)
250
- : (projectRelative ? join(checkoutRoot, projectRelative) : checkoutRoot);
251
- let remote = '';
252
- try {
253
- remote = await git(primary, ['config', '--get', 'remote.origin.url']);
254
- }
255
- catch { /* Local-only repositories may have no origin. */ }
256
- const remoteRepository = remote ? githubRepositoryFromRemote(remote) : null;
257
- if (remoteRepository && remoteRepository !== job.repository)
258
- throw new Error(`Primary checkout ${primary} does not match ${job.repository}`);
258
+ if (await realpath(primary) !== await realpath(job.projectRoot) || basename(primary) !== job.repository)
259
+ throw new Error(`Job ${job.id} projectRoot identity mismatch`);
260
+ // Every Job is bound directly to its own canonical Git root.
259
261
  const sourceSha = await git(primary, ['rev-parse', '--verify', sourceRef]);
260
262
  // If the canonical checkout already owns this exact source branch, Git
261
263
  // cannot create a second worktree for it. Reuse the canonical checkout
@@ -266,7 +268,7 @@ export async function prepareLocalJobExecutionWorktree(projectPath, job, workspa
266
268
  const primaryHead = await git(primary, ['rev-parse', 'HEAD']);
267
269
  if (primaryHead !== sourceSha)
268
270
  throw new Error(`Canonical source branch ${sourceRef} changed while preparing execution checkout`);
269
- return effectiveProject(primary);
271
+ return primary;
270
272
  }
271
273
  const worktree = managedLocalJobWorktreePath(job.repository, job.id, workspaceRoot);
272
274
  await mkdir(dirname(worktree), { recursive: true });
@@ -286,7 +288,7 @@ export async function prepareLocalJobExecutionWorktree(projectPath, job, workspa
286
288
  throw new Error(`Local Job worktree has non-fast-forward history; preserve commits: ${worktree}`);
287
289
  await git(worktree, ['merge', '--ff-only', sourceSha]);
288
290
  }
289
- return effectiveProject(worktree);
291
+ return worktree;
290
292
  }
291
293
  catch (error) {
292
294
  try {
@@ -294,7 +296,7 @@ export async function prepareLocalJobExecutionWorktree(projectPath, job, workspa
294
296
  }
295
297
  catch {
296
298
  await git(primary, ['worktree', 'add', worktree, sourceRef.slice('refs/heads/'.length)]);
297
- return effectiveProject(worktree);
299
+ return worktree;
298
300
  }
299
301
  throw error;
300
302
  }
@@ -327,14 +329,8 @@ export async function cleanupCompletedJobWorktree(projectPath, job, workspaceRoo
327
329
  if (!metadata.isDirectory() || metadata.isSymbolicLink())
328
330
  return { status: 'blocked', reason: 'Worktree path is not an owned directory' };
329
331
  const primary = await git(projectPath, ['rev-parse', '--show-toplevel']);
330
- let origin = '';
331
- try {
332
- origin = await git(primary, ['config', '--get', 'remote.origin.url']);
333
- }
334
- catch { /* Local-only repositories may have no origin. */ }
335
- const originRepository = origin ? githubRepositoryFromRemote(origin) : null;
336
- if ((job.prNumber > 0 && !isLocalJob && originRepository !== job.repository) || (isLocalJob && originRepository && originRepository !== job.repository))
337
- return { status: 'blocked', reason: 'Canonical repository identity mismatch' };
332
+ if (await realpath(primary) !== await realpath(job.projectRoot) || basename(primary) !== job.repository)
333
+ return { status: 'blocked', reason: 'Canonical local repository identity mismatch' };
338
334
  const registered = await git(primary, ['worktree', 'list', '--porcelain']);
339
335
  const ownedRoot = await realpath(worktree);
340
336
  const registeredPaths = registered.split('\n').filter(line => line.startsWith('worktree '));