agents-relay 2.0.231 → 2.0.232
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.
- package/dist/blocker-recovery.js +325 -0
- package/dist/blockers.js +7 -1
- package/dist/cli-blocker.js +35 -2
- package/dist/cli-help.js +6 -0
- package/dist/dashboard-data.js +17 -12
- package/dist/dashboard-html.js +1 -1
- package/dist/dashboard-workflow-inspection.js +1 -1
- package/dist/managed-worker-input.js +4 -0
- package/dist/planner.js +4 -1
- package/dist/relayd-control.js +87 -1
- package/dist/workflow/blocker-recovery.js +32 -0
- package/dist/workflow/blocker-resolution-v2.js +1 -1
- package/package.json +1 -1
- package/skills/agents-relay/SKILL.md +1 -1
- package/skills/agents-relay/agents/planner.agent.md +1 -0
- package/skills/agents-relay/agents/troubleshooter.agent.md +2 -1
- package/skills/agents-relay/contracts/blocker-job-recovery.md +23 -0
- package/skills/agents-relay/contracts/task-recovery-flows.md +2 -1
- package/workflow/blocker-recovery.mmd +51 -0
- package/workflow/blocker-resolution.mmd +5 -5
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { ensureManagedGitHubJob } from './cli-job-create.js';
|
|
3
|
+
import { DisabledGitHubClient } from './no-github.js';
|
|
4
|
+
import { openLocalManagedStore } from './local-managed-store.js';
|
|
5
|
+
import { discoverLocalRelayStoreSnapshots, relayStoreDirectory } from './relay-store.js';
|
|
6
|
+
import { registerBlockerDependency } from './blockers.js';
|
|
7
|
+
import { dispatchBlockerRecovery } from './workflow/blocker-recovery.js';
|
|
8
|
+
function normalizeRepository(value) {
|
|
9
|
+
const trimmed = value.trim().replace(/\.git$/, '');
|
|
10
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9_.-]*\/[A-Za-z0-9_.-]+$/.test(trimmed) || trimmed.includes('..')) {
|
|
11
|
+
throw new Error(`Invalid repository identity: ${value}`);
|
|
12
|
+
}
|
|
13
|
+
return trimmed;
|
|
14
|
+
}
|
|
15
|
+
function repositoryOwner(value) {
|
|
16
|
+
return value.split('/')[0].toLowerCase();
|
|
17
|
+
}
|
|
18
|
+
function normalizedIntent(value) {
|
|
19
|
+
return value.trim().replace(/\s+/g, ' ');
|
|
20
|
+
}
|
|
21
|
+
function intentFingerprint(input, blockedAttempt) {
|
|
22
|
+
const stable = {
|
|
23
|
+
targetRepository: normalizeRepository(input.targetRepository),
|
|
24
|
+
dependentRepository: normalizeRepository(input.dependentRepository),
|
|
25
|
+
dependentJobId: input.dependentJobId,
|
|
26
|
+
dependentTaskId: input.dependentTaskId,
|
|
27
|
+
blockedAttempt,
|
|
28
|
+
reason: normalizedIntent(input.reason),
|
|
29
|
+
title: normalizedIntent(input.title),
|
|
30
|
+
objective: normalizedIntent(input.objective),
|
|
31
|
+
projectPath: input.projectPath ?? null,
|
|
32
|
+
resolutionMode: input.resolutionMode,
|
|
33
|
+
};
|
|
34
|
+
return createHash('sha256').update(JSON.stringify(stable)).digest('hex');
|
|
35
|
+
}
|
|
36
|
+
function validateInput(input) {
|
|
37
|
+
const requestId = input.requestId.trim();
|
|
38
|
+
const title = input.title.trim();
|
|
39
|
+
const objective = input.objective.trim();
|
|
40
|
+
const reason = normalizedIntent(input.reason);
|
|
41
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:-]{7,199}$/.test(requestId))
|
|
42
|
+
throw new Error('Blocker recovery requestId must be 8-200 safe identity characters');
|
|
43
|
+
if (title.length < 10 || title.length > 200)
|
|
44
|
+
throw new Error('Blocker recovery title must be 10-200 characters');
|
|
45
|
+
if (reason.length < 20 || reason.length > 1000)
|
|
46
|
+
throw new Error('Blocker recovery reason must be 20-1000 characters');
|
|
47
|
+
const normalizedObjective = normalizedIntent(objective);
|
|
48
|
+
const targetRepository = normalizeRepository(input.targetRepository);
|
|
49
|
+
const dependentRepository = normalizeRepository(input.dependentRepository);
|
|
50
|
+
if (normalizedObjective.length < 120 || normalizedObjective.length > 20000)
|
|
51
|
+
throw new Error('Blocker recovery objective must contain 120-20000 characters of standalone context');
|
|
52
|
+
if (input.origin !== 'planner' && input.origin !== 'troubleshooter')
|
|
53
|
+
throw new Error('Blocker recovery origin must be planner or troubleshooter');
|
|
54
|
+
if (input.resolutionMode !== 'merge' && input.resolutionMode !== 'verified')
|
|
55
|
+
throw new Error('Blocker recovery resolutionMode must be merge or verified');
|
|
56
|
+
if (!normalizedObjective.includes(targetRepository))
|
|
57
|
+
throw new Error(`Blocker recovery objective must identify target repository ${targetRepository}`);
|
|
58
|
+
if (!normalizedObjective.includes(input.dependentTaskId))
|
|
59
|
+
throw new Error(`Blocker recovery objective must identify dependent Task ${input.dependentTaskId}`);
|
|
60
|
+
if (input.projectPath && (input.projectPath.startsWith('/') || input.projectPath.includes('\\')
|
|
61
|
+
|| input.projectPath.split('/').some(segment => segment === '' || segment === '.' || segment === '..'))) {
|
|
62
|
+
throw new Error('Blocker recovery projectPath must be a normalized repository-relative path');
|
|
63
|
+
}
|
|
64
|
+
if (targetRepository === dependentRepository)
|
|
65
|
+
throw new Error('Blocker recovery requires a distinct target repository');
|
|
66
|
+
if (repositoryOwner(targetRepository) !== repositoryOwner(dependentRepository)) {
|
|
67
|
+
throw new Error('Blocker recovery target and dependent repositories must share one owner/workspace trust boundary');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function receipt(input, blockerJobId, outcome, planningRecoveryRequired, request, now) {
|
|
71
|
+
return {
|
|
72
|
+
requestId: input.requestId,
|
|
73
|
+
reason: request.reason,
|
|
74
|
+
status: planningRecoveryRequired ? 'planning_required' : request.status === 'planned' ? 'planned' : 'registered',
|
|
75
|
+
blockerJobId,
|
|
76
|
+
blockerRepository: request.targetRepository,
|
|
77
|
+
dependentRepository: request.dependentRepository,
|
|
78
|
+
dependentJobId: request.dependentJobId,
|
|
79
|
+
dependentTaskId: request.dependentTaskId,
|
|
80
|
+
resolutionMode: request.resolutionMode,
|
|
81
|
+
outcome,
|
|
82
|
+
planningRecoveryRequired,
|
|
83
|
+
createdAt: request.createdAt,
|
|
84
|
+
updatedAt: now,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
function makeRequest(input, now, blockedAttempt) {
|
|
88
|
+
return {
|
|
89
|
+
requestId: input.requestId.trim(),
|
|
90
|
+
intentFingerprint: intentFingerprint(input, blockedAttempt),
|
|
91
|
+
reason: normalizedIntent(input.reason),
|
|
92
|
+
status: 'created',
|
|
93
|
+
targetRepository: normalizeRepository(input.targetRepository),
|
|
94
|
+
dependentRepository: normalizeRepository(input.dependentRepository),
|
|
95
|
+
dependentJobId: input.dependentJobId,
|
|
96
|
+
dependentTaskId: input.dependentTaskId,
|
|
97
|
+
blockedAttempt,
|
|
98
|
+
title: input.title.trim(),
|
|
99
|
+
objective: input.objective.trim(),
|
|
100
|
+
projectPath: input.projectPath,
|
|
101
|
+
resolutionMode: input.resolutionMode,
|
|
102
|
+
origin: input.origin,
|
|
103
|
+
authorized: input.authorized,
|
|
104
|
+
createdAt: now,
|
|
105
|
+
updatedAt: now,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function planningRequired(job) {
|
|
109
|
+
if (job.state === 'COMPLETED' || job.state === 'CANCELLED')
|
|
110
|
+
return false;
|
|
111
|
+
const latestPlan = [...(job.plans ?? [])].sort((left, right) => right.round - left.round)[0];
|
|
112
|
+
return job.state === 'DRAFT' || latestPlan?.status !== 'SUCCEEDED';
|
|
113
|
+
}
|
|
114
|
+
function requestStatus(job, planningRecoveryRequired) {
|
|
115
|
+
if (planningRecoveryRequired)
|
|
116
|
+
return 'planning_required';
|
|
117
|
+
if ((job.plans ?? []).some(plan => plan.status === 'SUCCEEDED'))
|
|
118
|
+
return 'planned';
|
|
119
|
+
return 'registered';
|
|
120
|
+
}
|
|
121
|
+
async function loadKnownCandidate(directory, input, request) {
|
|
122
|
+
const snapshots = await discoverLocalRelayStoreSnapshots(directory);
|
|
123
|
+
const matchingRequests = snapshots.flatMap(snapshot => snapshot.jobs.filter(job => job.blockerRecoveryRequest?.requestId === request.requestId));
|
|
124
|
+
if (matchingRequests.length > 1)
|
|
125
|
+
throw new Error(`Ambiguous blocker recovery requestId ${request.requestId}`);
|
|
126
|
+
const summary = matchingRequests[0];
|
|
127
|
+
if (!summary)
|
|
128
|
+
return null;
|
|
129
|
+
const store = openLocalManagedStore(summary.repository, 0, { directory, jobId: summary.id, noGitHub: true });
|
|
130
|
+
const job = await store.store.load(summary.id);
|
|
131
|
+
const stored = job.blockerRecoveryRequest;
|
|
132
|
+
if (!stored
|
|
133
|
+
|| stored.intentFingerprint !== request.intentFingerprint
|
|
134
|
+
|| stored.targetRepository !== request.targetRepository
|
|
135
|
+
|| stored.dependentRepository !== request.dependentRepository
|
|
136
|
+
|| stored.dependentJobId !== request.dependentJobId
|
|
137
|
+
|| stored.dependentTaskId !== request.dependentTaskId) {
|
|
138
|
+
throw new Error(`Blocker recovery requestId ${request.requestId} is already bound to a different durable intent`);
|
|
139
|
+
}
|
|
140
|
+
return { store, job, request: stored };
|
|
141
|
+
}
|
|
142
|
+
async function loadAuthoritativeCandidate(directory, request) {
|
|
143
|
+
const snapshots = await discoverLocalRelayStoreSnapshots(directory);
|
|
144
|
+
const candidates = snapshots.flatMap(snapshot => snapshot.jobs.filter(job => normalizeRepository(job.repository) === request.targetRepository
|
|
145
|
+
&& (job.unblocks ?? []).some(relation => normalizeRepository(relation.repository) === request.dependentRepository
|
|
146
|
+
&& relation.jobId === request.dependentJobId
|
|
147
|
+
&& relation.taskId === request.dependentTaskId
|
|
148
|
+
&& relation.blockedAttempt === request.blockedAttempt)));
|
|
149
|
+
if (candidates.length > 1)
|
|
150
|
+
throw new Error(`Ambiguous authoritative blocker dependency for ${request.dependentJobId}/${request.dependentTaskId}`);
|
|
151
|
+
const summary = candidates[0];
|
|
152
|
+
if (!summary)
|
|
153
|
+
return null;
|
|
154
|
+
const store = openLocalManagedStore(request.targetRepository, 0, { directory, jobId: summary.id, noGitHub: true });
|
|
155
|
+
const job = await store.store.load(summary.id);
|
|
156
|
+
return { store, job, request };
|
|
157
|
+
}
|
|
158
|
+
function adoptionValid(candidate, request) {
|
|
159
|
+
if (candidate.job.state === 'CANCELLED')
|
|
160
|
+
return false;
|
|
161
|
+
if (candidate.job.repository !== request.targetRepository)
|
|
162
|
+
return false;
|
|
163
|
+
if (candidate.job.blockerResolutionMode && candidate.job.blockerResolutionMode !== request.resolutionMode)
|
|
164
|
+
return false;
|
|
165
|
+
const stored = candidate.job.blockerRecoveryRequest;
|
|
166
|
+
return !stored || (stored.intentFingerprint === request.intentFingerprint && stored.targetRepository === request.targetRepository
|
|
167
|
+
&& stored.dependentRepository === request.dependentRepository && stored.dependentJobId === request.dependentJobId
|
|
168
|
+
&& stored.dependentTaskId === request.dependentTaskId);
|
|
169
|
+
}
|
|
170
|
+
async function closeStores(stores) {
|
|
171
|
+
for (const store of stores)
|
|
172
|
+
store.relay.close();
|
|
173
|
+
}
|
|
174
|
+
export async function ensureBlockerRecovery(input) {
|
|
175
|
+
validateInput(input);
|
|
176
|
+
const directory = input.storeDirectory ?? relayStoreDirectory();
|
|
177
|
+
const now = input.now ?? new Date().toISOString();
|
|
178
|
+
const dependentRepository = normalizeRepository(input.dependentRepository);
|
|
179
|
+
const dependentStore = openLocalManagedStore(dependentRepository, 0, { directory, jobId: input.dependentJobId, noGitHub: true });
|
|
180
|
+
const opened = [dependentStore];
|
|
181
|
+
let candidate = null;
|
|
182
|
+
let finalStore = null;
|
|
183
|
+
let outcome = 'created';
|
|
184
|
+
try {
|
|
185
|
+
const dependentJob = await dependentStore.store.load(input.dependentJobId);
|
|
186
|
+
const task = dependentJob.tasks.find(item => item.id === input.dependentTaskId);
|
|
187
|
+
if (!task)
|
|
188
|
+
throw new Error(`Dependent Task ${input.dependentTaskId} not found`);
|
|
189
|
+
if (!['FAILED', 'BLOCKED'].includes(task.state))
|
|
190
|
+
throw new Error(`Dependent Task ${task.id} must be failed or blocked before blocker recovery (${task.state})`);
|
|
191
|
+
const request = makeRequest(input, now, task.attempt);
|
|
192
|
+
const known = await loadKnownCandidate(directory, input, request);
|
|
193
|
+
if (known) {
|
|
194
|
+
opened.push(known.store);
|
|
195
|
+
candidate = known;
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
const authoritative = await loadAuthoritativeCandidate(directory, request);
|
|
199
|
+
if (authoritative) {
|
|
200
|
+
opened.push(authoritative.store);
|
|
201
|
+
candidate = authoritative;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
const authorizedRepositories = input.authorizedRepositories.map(normalizeRepository);
|
|
205
|
+
const targetResolvable = authorizedRepositories.includes(request.targetRepository);
|
|
206
|
+
const trustBoundaryValid = repositoryOwner(request.targetRepository) === repositoryOwner(request.dependentRepository);
|
|
207
|
+
const knownRequest = known !== null;
|
|
208
|
+
const authoritativeDependency = !knownRequest && candidate !== null;
|
|
209
|
+
const validAdoption = candidate ? adoptionValid(candidate, request) : false;
|
|
210
|
+
let blockerJobId = candidate?.job.id;
|
|
211
|
+
let planningRecovery = false;
|
|
212
|
+
const decision = await dispatchBlockerRecovery({
|
|
213
|
+
authorized: input.authorized,
|
|
214
|
+
knownRequest,
|
|
215
|
+
authoritativeDependency,
|
|
216
|
+
adoptionValid: validAdoption,
|
|
217
|
+
targetValid: targetResolvable,
|
|
218
|
+
trustBoundaryValid,
|
|
219
|
+
}, async (actionId) => {
|
|
220
|
+
if (actionId === 'recovery.createBlocker') {
|
|
221
|
+
const created = await ensureManagedGitHubJob(new DisabledGitHubClient(), request.targetRepository, new Set(), {
|
|
222
|
+
idempotencyKey: `blocker-recovery:${request.requestId}`,
|
|
223
|
+
title: request.title,
|
|
224
|
+
objective: request.objective,
|
|
225
|
+
projectPath: request.projectPath,
|
|
226
|
+
noGitHub: true,
|
|
227
|
+
storeDirectory: directory,
|
|
228
|
+
});
|
|
229
|
+
blockerJobId = created.job.id;
|
|
230
|
+
outcome = 'created';
|
|
231
|
+
planningRecovery = true;
|
|
232
|
+
const createdStore = openLocalManagedStore(request.targetRepository, 0, { directory, jobId: created.job.id, noGitHub: true });
|
|
233
|
+
opened.push(createdStore);
|
|
234
|
+
finalStore = createdStore;
|
|
235
|
+
if (!createdStore.store.mutateJob)
|
|
236
|
+
throw new Error('Blocker recovery requires atomic durable Job mutation');
|
|
237
|
+
await createdStore.store.mutateJob(created.job.id, current => ({
|
|
238
|
+
...current,
|
|
239
|
+
blockerRecoveryRequest: { ...request, blockedAttempt: task.attempt, updatedAt: now },
|
|
240
|
+
blockerResolutionMode: request.resolutionMode,
|
|
241
|
+
}));
|
|
242
|
+
return {};
|
|
243
|
+
}
|
|
244
|
+
if (actionId !== 'recovery.adoptExistingBlocker' && actionId !== 'recovery.registerDependency') {
|
|
245
|
+
throw new Error(`Unsupported blocker recovery action ${actionId}`);
|
|
246
|
+
}
|
|
247
|
+
if (actionId === 'recovery.adoptExistingBlocker') {
|
|
248
|
+
if (!candidate)
|
|
249
|
+
throw new Error('Graph selected adoption without a verified blocker Job');
|
|
250
|
+
blockerJobId = candidate.job.id;
|
|
251
|
+
finalStore = candidate.store;
|
|
252
|
+
outcome = 'reused';
|
|
253
|
+
}
|
|
254
|
+
if (actionId === 'recovery.registerDependency') {
|
|
255
|
+
if (!blockerJobId)
|
|
256
|
+
throw new Error('Graph selected dependency registration without a blocker Job');
|
|
257
|
+
const targetStore = finalStore ?? openLocalManagedStore(request.targetRepository, 0, { directory, jobId: blockerJobId, noGitHub: true });
|
|
258
|
+
finalStore = targetStore;
|
|
259
|
+
if (!opened.includes(targetStore))
|
|
260
|
+
opened.push(targetStore);
|
|
261
|
+
const before = await targetStore.store.load(blockerJobId);
|
|
262
|
+
if (before.blockerResolutionMode && before.blockerResolutionMode !== request.resolutionMode) {
|
|
263
|
+
throw new Error(`Blocker ${blockerJobId} already uses ${before.blockerResolutionMode} resolution`);
|
|
264
|
+
}
|
|
265
|
+
const relation = await registerBlockerDependency({
|
|
266
|
+
blockerStore: targetStore.store,
|
|
267
|
+
blockerJobId,
|
|
268
|
+
dependentStore: dependentStore.store,
|
|
269
|
+
dependentJobId: request.dependentJobId,
|
|
270
|
+
dependentTaskId: request.dependentTaskId,
|
|
271
|
+
resolutionMode: request.resolutionMode,
|
|
272
|
+
expectedAttempt: task.attempt,
|
|
273
|
+
now,
|
|
274
|
+
});
|
|
275
|
+
if (!targetStore.store.mutateJob)
|
|
276
|
+
throw new Error('Blocker recovery requires atomic durable Job mutation');
|
|
277
|
+
const current = await targetStore.store.load(blockerJobId);
|
|
278
|
+
const prior = current.blockerRecoveryRequest;
|
|
279
|
+
if (prior && prior.intentFingerprint !== request.intentFingerprint) {
|
|
280
|
+
throw new Error(`Blocker Job ${blockerJobId} is already bound to a different recovery intent`);
|
|
281
|
+
}
|
|
282
|
+
planningRecovery = planningRequired(current);
|
|
283
|
+
const status = requestStatus(current, planningRecovery);
|
|
284
|
+
await targetStore.store.mutateJob(blockerJobId, job => ({
|
|
285
|
+
...job,
|
|
286
|
+
blockerRecoveryRequest: {
|
|
287
|
+
...(prior ?? request), blockedAttempt: relation.blockedAttempt,
|
|
288
|
+
status, updatedAt: now,
|
|
289
|
+
},
|
|
290
|
+
blockerResolutionMode: request.resolutionMode,
|
|
291
|
+
}));
|
|
292
|
+
if (outcome !== 'created')
|
|
293
|
+
outcome = before.unblocks?.some(item => item.jobId === request.dependentJobId && item.taskId === request.dependentTaskId) ? 'reused' : 'registered';
|
|
294
|
+
}
|
|
295
|
+
return {};
|
|
296
|
+
});
|
|
297
|
+
if (!decision.accepted)
|
|
298
|
+
throw new Error(`Blocker recovery graph rejected request ${request.requestId}: ${decision.reason}`);
|
|
299
|
+
if (decision.target !== 'ready' || !blockerJobId)
|
|
300
|
+
throw new Error(`Blocker recovery graph did not produce ready state for ${request.requestId}`);
|
|
301
|
+
finalStore ??= openLocalManagedStore(request.targetRepository, 0, { directory, jobId: blockerJobId, noGitHub: true });
|
|
302
|
+
if (!opened.includes(finalStore))
|
|
303
|
+
opened.push(finalStore);
|
|
304
|
+
const finalJob = await finalStore.store.load(blockerJobId);
|
|
305
|
+
planningRecovery = planningRequired(finalJob);
|
|
306
|
+
const receiptNow = now;
|
|
307
|
+
const final = await finalStore.store.load(blockerJobId);
|
|
308
|
+
await dependentStore.store.mutateJob(request.dependentJobId, current => {
|
|
309
|
+
const index = current.tasks.findIndex(item => item.id === request.dependentTaskId);
|
|
310
|
+
if (index < 0)
|
|
311
|
+
throw new Error(`Dependent Task ${request.dependentTaskId} disappeared`);
|
|
312
|
+
const updated = {
|
|
313
|
+
...current.tasks[index],
|
|
314
|
+
blockerRecoveryReceipt: receipt(input, blockerJobId, outcome, planningRecovery, final.blockerRecoveryRequest ?? request, receiptNow),
|
|
315
|
+
};
|
|
316
|
+
current.tasks[index] = updated;
|
|
317
|
+
current.updatedAt = receiptNow;
|
|
318
|
+
return current;
|
|
319
|
+
});
|
|
320
|
+
return receipt(input, blockerJobId, outcome, planningRecovery, final.blockerRecoveryRequest ?? request, now);
|
|
321
|
+
}
|
|
322
|
+
finally {
|
|
323
|
+
await closeStores(new Set(opened));
|
|
324
|
+
}
|
|
325
|
+
}
|
package/dist/blockers.js
CHANGED
|
@@ -14,6 +14,11 @@ export async function registerBlockerDependency(options) {
|
|
|
14
14
|
const task = dependentJob.tasks.find(item => item.id === options.dependentTaskId);
|
|
15
15
|
if (!task)
|
|
16
16
|
throw new Error(`Dependent task ${options.dependentTaskId} not found`);
|
|
17
|
+
if (task.jobId && task.jobId !== dependentJob.id)
|
|
18
|
+
throw new Error(`Dependent task ${task.id} is bound to another Job`);
|
|
19
|
+
if (options.expectedAttempt !== undefined && task.attempt !== options.expectedAttempt) {
|
|
20
|
+
throw new Error(`Dependent task ${task.id} advanced from expected attempt ${options.expectedAttempt} to ${task.attempt}`);
|
|
21
|
+
}
|
|
17
22
|
if (!['DRAFT', 'FAILED', 'BLOCKED'].includes(task.state))
|
|
18
23
|
throw new Error(`Dependent task ${task.id} is not waiting/blocked/failed (${task.state})`);
|
|
19
24
|
const now = options.now ?? new Date().toISOString();
|
|
@@ -101,7 +106,8 @@ export async function resolveBlockerDependencies(options) {
|
|
|
101
106
|
const targetMatches = !!task && ['DRAFT', 'FAILED', 'BLOCKED', 'QUEUED'].includes(task.state) && task.attempt === relation.blockedAttempt;
|
|
102
107
|
let note = 'dependent task released from dependency wait';
|
|
103
108
|
const decision = await dispatchBlockerResolution({
|
|
104
|
-
|
|
109
|
+
resolutionConditionMet: blocker.state === 'COMPLETED'
|
|
110
|
+
&& (mode === 'verified' ? options.resolution === 'verified' : options.resolution === 'merge'),
|
|
105
111
|
targetMatches,
|
|
106
112
|
effectivelyBlocked: !!task && isEffectivelyBlocked(task),
|
|
107
113
|
alreadyUnblocked: Boolean(task?.unblock && ['DRAFT', 'QUEUED'].includes(task.state)),
|
package/dist/cli-blocker.js
CHANGED
|
@@ -1,8 +1,41 @@
|
|
|
1
|
-
import { arg, relayControlCommand, relayControlJob, repository } from './cli-support.js';
|
|
1
|
+
import { arg, hasArg, relayControlCommand, relayControlJob, repository, textOption } from './cli-support.js';
|
|
2
2
|
import { usage } from './cli-help.js';
|
|
3
3
|
export async function runBlockerCommand(action, args) {
|
|
4
|
-
if (!['add', 'resolve', 'show'].includes(action))
|
|
4
|
+
if (!['add', 'ensure', 'resolve', 'show'].includes(action))
|
|
5
5
|
throw new Error(usage);
|
|
6
|
+
if (action === 'ensure') {
|
|
7
|
+
const dependentRepository = repository(args);
|
|
8
|
+
const dependentJobId = arg(args, '--id');
|
|
9
|
+
const targetRepository = arg(args, '--target-repo');
|
|
10
|
+
const requestId = arg(args, '--request-id');
|
|
11
|
+
const dependentTaskId = arg(args, '--dependent-task');
|
|
12
|
+
const reason = arg(args, '--reason');
|
|
13
|
+
const title = arg(args, '--title');
|
|
14
|
+
const objective = await textOption(args, '--objective', '--objective-file');
|
|
15
|
+
const origin = arg(args, '--origin', 'troubleshooter');
|
|
16
|
+
const modeValue = arg(args, '--resolution', 'merge');
|
|
17
|
+
if (!dependentJobId || !targetRepository || !requestId || !dependentTaskId || !title || !reason) {
|
|
18
|
+
throw new Error('blocker ensure requires --id, --target-repo, --request-id, --dependent-task, --title, and --reason');
|
|
19
|
+
}
|
|
20
|
+
if (!objective.trim())
|
|
21
|
+
throw new Error('blocker ensure requires --objective-file PATH|- or --objective MARKDOWN');
|
|
22
|
+
if (!hasArg(args, '--authorized'))
|
|
23
|
+
throw new Error('blocker ensure requires explicit --authorized');
|
|
24
|
+
if (!['planner', 'troubleshooter'].includes(origin))
|
|
25
|
+
throw new Error('--origin must be planner or troubleshooter');
|
|
26
|
+
if (!['merge', 'verified'].includes(modeValue))
|
|
27
|
+
throw new Error('--resolution must be merge or verified');
|
|
28
|
+
console.log(JSON.stringify(await relayControlCommand(args, {
|
|
29
|
+
command: 'blocker.ensure',
|
|
30
|
+
jobId: dependentJobId,
|
|
31
|
+
request: {
|
|
32
|
+
requestId, targetRepository, dependentRepository, dependentJobId, dependentTaskId, reason,
|
|
33
|
+
title, objective, resolutionMode: modeValue, origin, authorized: true,
|
|
34
|
+
projectPath: arg(args, '--project-path') || undefined,
|
|
35
|
+
},
|
|
36
|
+
}), null, 2));
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
6
39
|
repository(args);
|
|
7
40
|
const id = arg(args, '--id');
|
|
8
41
|
if (!id)
|
package/dist/cli-help.js
CHANGED
|
@@ -258,6 +258,12 @@ The blocker Job owns reverse \`unblocks\` references. \`add\` registers a failed
|
|
|
258
258
|
Blocker: --repo OWNER/REPO --id JOB_ID.
|
|
259
259
|
Dependent: --dependent-repo OWNER/REPO --dependent-pr NUMBER --dependent-job JOB_ID --dependent-task TASK_ID.
|
|
260
260
|
Common: --resolution merge|verified (default merge).`,
|
|
261
|
+
'blocker ensure': `Create or reuse an authorized cross-repository blocker Job and register its reverse relation.
|
|
262
|
+
|
|
263
|
+
Dependent: --repo OWNER/REPO --id DEPENDENT_JOB_ID --dependent-task TASK_ID.
|
|
264
|
+
Target: --target-repo OWNER/REPO --title TITLE --reason TEXT --objective-file PATH|-.
|
|
265
|
+
Identity: --request-id STABLE_REQUEST_ID --origin planner|troubleshooter --resolution merge|verified --authorized.
|
|
266
|
+
Target repositories must be configured in the current trusted workspace; target projects must use a normalized repository-relative path.`,
|
|
261
267
|
'blocker resolve': `Resolve a verified blocker and safely requeue matching dependents.
|
|
262
268
|
|
|
263
269
|
Required: --repo OWNER/REPO --id JOB_ID. This explicit path is required for blockers configured with --resolution verified.`,
|
package/dist/dashboard-data.js
CHANGED
|
@@ -6,18 +6,23 @@ const repositoryPattern = /^([A-Za-z0-9](?:[A-Za-z0-9-]{0,36}[A-Za-z0-9])?)\/([A
|
|
|
6
6
|
const workflowDirectory = fileURLToPath(new URL('../workflow/', import.meta.url));
|
|
7
7
|
export const DASHBOARD_JOB_RESULT_LIMIT = 20;
|
|
8
8
|
export const DEFAULT_DASHBOARD_JOB_STATUSES = ['DRAFT', 'ACTIVE', 'COMPLETED'];
|
|
9
|
-
function
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
return
|
|
9
|
+
function dashboardJobTimestamp(job) {
|
|
10
|
+
const updated = Date.parse(job.updatedAt ?? '');
|
|
11
|
+
if (Number.isFinite(updated))
|
|
12
|
+
return updated;
|
|
13
|
+
const created = Date.parse(job.createdAt ?? '');
|
|
14
|
+
return Number.isFinite(created) ? created : 0;
|
|
15
|
+
}
|
|
16
|
+
function compareDashboardJobInventory(a, b) {
|
|
17
|
+
return dashboardJobTimestamp(b) - dashboardJobTimestamp(a)
|
|
18
18
|
|| a.repository.localeCompare(b.repository)
|
|
19
19
|
|| a.id.localeCompare(b.id);
|
|
20
20
|
}
|
|
21
|
+
function compareDashboardJobs(a, b) {
|
|
22
|
+
const lifecycleGroup = (job) => job.state === 'COMPLETED' || job.state === 'CANCELLED' ? 1 : 0;
|
|
23
|
+
return lifecycleGroup(a) - lifecycleGroup(b)
|
|
24
|
+
|| compareDashboardJobInventory(a, b);
|
|
25
|
+
}
|
|
21
26
|
export async function dashboardWorkflowGraphs() {
|
|
22
27
|
const names = (await readdir(workflowDirectory)).filter(name => name.endsWith('.mmd')).sort();
|
|
23
28
|
return Promise.all(names.map(async (name) => {
|
|
@@ -59,7 +64,7 @@ export async function eventHistory(jobId, taskId, limit) {
|
|
|
59
64
|
}
|
|
60
65
|
/** CLI inventory is complete, including CANCELLED; only the dashboard list is capped. */
|
|
61
66
|
export function listDashboardJobInventory(jobs, repository = '') {
|
|
62
|
-
const selected = jobs.filter(job => !repository || job.repository === repository).sort(
|
|
67
|
+
const selected = jobs.filter(job => !repository || job.repository === repository).sort(compareDashboardJobInventory);
|
|
63
68
|
return {
|
|
64
69
|
jobs: selected,
|
|
65
70
|
repositories: [...new Set(jobs.map(job => job.repository).filter(Boolean))].sort(),
|
|
@@ -85,9 +90,9 @@ export function searchDashboardJobs(jobs, query) {
|
|
|
85
90
|
|| String(job.id || '').toLowerCase().includes(search)
|
|
86
91
|
|| Boolean(normalizedPr) && String(job.prNumber || '').includes(normalizedPr);
|
|
87
92
|
};
|
|
88
|
-
const matching = jobs.filter(job => matchesStatus(job) && matchesRepository(job) && matchesSearch(job)).sort(
|
|
93
|
+
const matching = jobs.filter(job => matchesStatus(job) && matchesRepository(job) && matchesSearch(job)).sort(compareDashboardJobInventory);
|
|
89
94
|
return {
|
|
90
|
-
jobs: matching.slice(0, DASHBOARD_JOB_RESULT_LIMIT),
|
|
95
|
+
jobs: matching.slice(0, DASHBOARD_JOB_RESULT_LIMIT).sort(compareDashboardJobs),
|
|
91
96
|
repositories: [...new Set(jobs.map(job => job.repository).filter(Boolean))].sort(),
|
|
92
97
|
total: matching.length,
|
|
93
98
|
};
|
package/dist/dashboard-html.js
CHANGED
|
@@ -262,7 +262,7 @@ function iconSvg(name){const paths={close:'M5 5l14 14M19 5 5 19',detail:'M7 3h7l
|
|
|
262
262
|
function showDetailsDialog(title,sections){const dialog=element('dialog','details-dialog');dialog.setAttribute('aria-label',title);const head=element('div','details-dialog-head');const name=element('strong','',text(title));const close=element('button','icon-button');close.append(iconSvg('close'));close.type='button';close.setAttribute('aria-label','Close details');close.title='Close details';close.addEventListener('click',()=>dialog.close());head.append(name,close);dialog.append(head);for(const [label,value] of sections){if(value===undefined||value===null||value==='')continue;dialog.append(element('h3','',text(label)));const content=element('pre');content.textContent=typeof value==='string'?value:JSON.stringify(value,null,2);dialog.append(content);}dialog.addEventListener('close',()=>dialog.remove());document.body.append(dialog);dialog.showModal();}function openJobDetails(){const job=selected();if(!job)return;showDetailsDialog('Job '+job.id+' · '+value(job.title),[['Objective',job.objective],['Description',job.description],['State',job.state],['Plans',job.plans?.map(p=>({id:p.id,status:p.status,assessment:p.assessment,error:p.error,generatedTaskIds:p.generatedTaskIds}))],['Review',job.review],['Outcome',job.result],['Publication',job.publication],['Failure',job.error]]);}function openTaskDetails(task){const result=task.result?.data??task.result;showDetailsDialog('Task '+task.id+' · '+value(task.title),[['Input / task objective',task.input],['State',task.state],['Conclusion',result],['Result summary',task.result?.summary],['Planner assessment',task.plannerResult?.assessment],['Resolution',task.resolution],['Resolution classification',task.resolutionClassification],['Failure',task.failureReason||task.error],['Dependencies',task.dependencies]]);}document.querySelector('#job-content-open').addEventListener('click',openJobDetails);function renderTaskDetail(task){taskDetailRoot.replaceChildren();if(!task){taskDetailRoot.append(element('p','empty',text('Select a task to inspect execution details.')));return;}const routing=task.routing||{};const groups=element('div','detail-groups');groups.append(field('Title',task.title||'—'),field('Task ID',task.id),field('Kind',task.kind||'work'),taskStateField(task),...(task.state==='FAILED'&&task.resolution?.state?[field('Resolution state',task.resolution.state),field('Resolution path',task.resolution.path||'—'),field('Resolution target',task.resolution.targetTaskId||'—')]:[]),manualOverrideField(task),field('Planning decision',task.planningDecisionId||'—'),field('Planning source',task.planningSource||'—'),field('Planning round',task.planningRound===undefined?'—':String(task.planningRound)),field('Project / agent',value(task.projectName)+' / '+value(task.agentName)),field('Parent task',task.parentTaskId||'root'),...(task.resolutionClassification?[field('Resolution classification',task.resolutionClassification.kind),field('Resolution target',task.resolutionClassification.targetTaskId),field('Resolution evidence',task.resolutionClassification.evidence),field('Resolution reason',task.resolutionClassification.reason)]:[]),field('Adapter',task.adapter),field('Provider / model',value(routing.provider)+' / '+value(routing.model)),field('Reasoning / profile',value(routing.reasoning||routing.profile)),field('Attempt',attemptBudget(task)),field('Dependencies',Array.isArray(task.dependencies)&&task.dependencies.length?task.dependencies.join(', '):'none'),taskCommentField(task),chatField(task));const job=selected();if(task.reviewHeadSha&&job)groups.append(commitField('HEAD commit',job,task.reviewHeadSha));const graph=agentGraphField(task);if(graph)groups.append(graph);if(task.plannerResult)groups.append(field('Objective status',task.plannerResult.objective_status),markdownField('Assessment',task.plannerResult.assessment));if(task.error)groups.append(field('Error',task.error));const result=task.result?.data??task.result;if(result){groups.append(field('Conclusion',result.verdict||result.outcome?.verdict||task.result?.summary||'Available'));}taskDetailRoot.append(groups);const details=element('button','icon-button');details.append(iconSvg('detail'));details.type='button';details.setAttribute('aria-label','Task details and conclusion');details.title='Task details and conclusion';details.addEventListener('click',()=>openTaskDetails(task));taskDetailRoot.append(details);}
|
|
263
263
|
function reviewStatus(job){const review=job?.review;if(!review)return 'Not started';if(review.outcome==='approved'&&review.headSha===job.headSha)return 'MERGE READY · approved';const stale=Array.isArray(job?.tasks)&&job.tasks.some(task=>['reviewer','job-acceptance-reviewer'].includes(task.agentName)&&task.reviewHeadSha&&job.headSha&&task.reviewHeadSha!==job.headSha);if(stale)return 'STALE · awaiting review';return String(review.outcome||'pending').replace('_',' ').toUpperCase();}function renderSelectedJob(){jobDetail.replaceChildren();const job=selected();if(!job){selectedJobTitle.textContent='';jobContentButton.disabled=true;jobContentButton.dataset.state='IDLE';jobDetail.append(element('div','empty',text('No durable jobs discovered.')));buildTree([]);renderTaskDetail(null);return;}selectedJobTitle.textContent=value(job.title||job.id);jobContentButton.disabled=false;jobContentButton.dataset.state=JOB_STATES.includes(job.state)?job.state:'IDLE';jobContentButton.setAttribute('aria-label','Job details · '+value(job.state));jobContentButton.title='Job details · '+value(job.state);if(jobSelectionKey(job)!==selectedJob){selectedJob=jobSelectionKey(job);selectedTaskId=null;eventTaskId=null;clearEvents();rememberSelection();}const summary=element('div','job-summary');summary.append(field('PR state',job.githubState||'UNKNOWN'),jobStateField(job),field('Runtime status',job.runtimeStatus||'IDLE'),field('Review',reviewStatus(job)),field('Creator thread',job.creatorThreadId||'—'),threadField('Implementation thread',job.implementationThreadId),threadField('Reviewer thread',job.reviewerThreadId),commitField('Review head SHA',job,job.review?.headSha||job.headSha||''),prField(job),field('Repository',job.repository||'—'),field('Last activity',relativeTime(job.updatedAt)),field('Task states',compactCounts(job.tasks)),chatShortcutField(job));jobDetail.append(summary);const selectedTask=(job.tasks||[]).find(task=>task.id===selectedTaskId)||null;if(selectedTaskId&&!selectedTask){selectedTaskId=null;eventTaskId=null;clearEvents();rememberSelection();}buildTree(job.tasks||[]);renderTaskDetail(selectedTask);renderEventScope();}function renderAll(){jobs.sort(compareJobs);syncFilters();renderJobList();renderSelectedJob();syncMobileJobsView();}
|
|
264
264
|
function isCompleteUnmerged(job){return job.runtimeStatus==='MERGE_PENDING';}
|
|
265
|
-
function compareJobs(a,b){const timestamp=job=>{const updated=Date.parse(job.updatedAt||'');if(Number.isFinite(updated))return updated;const created=Date.parse(job.createdAt||'');return Number.isFinite(created)?created:0;};return timestamp(b)-timestamp(a)||String(a.repository||'').localeCompare(String(b.repository||''))||String(a.id||'').localeCompare(String(b.id||''));}
|
|
265
|
+
function compareJobs(a,b){const lifecycleGroup=job=>job.state==='COMPLETED'||job.state==='CANCELLED'?1:0;const timestamp=job=>{const updated=Date.parse(job.updatedAt||'');if(Number.isFinite(updated))return updated;const created=Date.parse(job.createdAt||'');return Number.isFinite(created)?created:0;};return lifecycleGroup(a)-lifecycleGroup(b)||timestamp(b)-timestamp(a)||String(a.repository||'').localeCompare(String(b.repository||''))||String(a.id||'').localeCompare(String(b.id||''));}
|
|
266
266
|
async function loadJSON(url){const response=await fetch(url);if(!response.ok)throw new Error(response.status+' '+response.statusText);return response.json();}
|
|
267
267
|
async function refreshVersion(){try{const live=await loadJSON('/api/version');if(live?.version&&live.version!==DASHBOARD_VERSION)location.reload();}catch{}}
|
|
268
268
|
function renderRateLimitStatus(status){
|
|
@@ -64,7 +64,7 @@ export async function inspectWorkflowSymbol(graphId, kind, name) {
|
|
|
64
64
|
const matchingLine = source.split('\n').findIndex(line => pattern.test(line));
|
|
65
65
|
if (matchingLine < 0)
|
|
66
66
|
return null;
|
|
67
|
-
const contracts = ['skills/agents-relay/contracts/event-contract.md', 'skills/agents-relay/contracts/task-recovery-flows.md'];
|
|
67
|
+
const contracts = ['skills/agents-relay/contracts/event-contract.md', 'skills/agents-relay/contracts/task-recovery-flows.md', 'skills/agents-relay/contracts/blocker-job-recovery.md'];
|
|
68
68
|
const contractRefs = (await Promise.all(contracts.map(async (path) => {
|
|
69
69
|
try {
|
|
70
70
|
return matches(await readFile(join(ROOT, path), 'utf8'), name, path, 2);
|
|
@@ -43,6 +43,10 @@ export async function managedWorkerInput(job, task, context, mode = 'production'
|
|
|
43
43
|
...(eventProtocol && existsSync(eventProtocol) ? [eventProtocol] : []),
|
|
44
44
|
join(packageRoot, 'skills/agents-relay/contracts/task-job-contract.md'),
|
|
45
45
|
join(packageRoot, 'skills/agents-relay/contracts/event-contract.md'),
|
|
46
|
+
...(role === 'troubleshooter' ? [
|
|
47
|
+
join(packageRoot, 'skills/agents-relay/contracts/task-recovery-flows.md'),
|
|
48
|
+
join(packageRoot, 'skills/agents-relay/contracts/blocker-job-recovery.md'),
|
|
49
|
+
] : []),
|
|
46
50
|
...(role === 'worker' && !task.review && task.agentName !== 'review-chair'
|
|
47
51
|
? [join(packageRoot, 'skills/agents-relay/contracts/worker-self-review.md')] : []),
|
|
48
52
|
],
|
package/dist/planner.js
CHANGED
|
@@ -496,7 +496,10 @@ export async function buildPlannerExecutionPrompt(context, agentFile = DEFAULT_P
|
|
|
496
496
|
throw new Error('Planner execution is missing its durable Plan and execution identity');
|
|
497
497
|
const ctx = context.executionContext, selected = ctx ? await resolveAgentMarkdown('planner', BUNDLED_AGENTS_ROOT, ctx.project.path, ctx.project.sharedRoot, agentSourceLayers(ctx.project.path, ctx.project)) : undefined;
|
|
498
498
|
return buildRelayWorkPrompt({ agentName: 'planner', agentContent: selected?.content ?? await readFile(agentFile, 'utf8'), adapter,
|
|
499
|
-
contracts: [
|
|
499
|
+
contracts: [
|
|
500
|
+
join(dirname(fileURLToPath(import.meta.url)), '..', 'skills/agents-relay/contracts/task-job-contract.md'),
|
|
501
|
+
join(dirname(fileURLToPath(import.meta.url)), '..', 'skills/agents-relay/contracts/blocker-job-recovery.md'),
|
|
502
|
+
],
|
|
500
503
|
contexts: ctx?.instructions.filter(item => item.path.endsWith('/AGENTS.md')) ?? [],
|
|
501
504
|
projectPath: ctx?.project.gitRoot ?? ctx?.project.path ?? process.cwd(), providerInstructions: ctx?.providerInstructions?.[adapter], skillPath: join(dirname(fileURLToPath(import.meta.url)), '..', 'skills/agents-relay/SKILL.md'), jobId: context.job.id,
|
|
502
505
|
taskId: context.planExecution.planId, executionId: context.planExecution.executionId,
|
package/dist/relayd-control.js
CHANGED
|
@@ -9,10 +9,11 @@ import { normalizeThreadId } from './reviewer-thread.js';
|
|
|
9
9
|
import { publishTaskBlocked } from './cli-support.js';
|
|
10
10
|
import { classifyFailedTask, supersedeCancelledTask } from './task-actions.js';
|
|
11
11
|
import { requestTroubleshooterEscalation, resumeTroubleshooter } from './task-recovery.js';
|
|
12
|
+
import { ensureBlockerRecovery } from './blocker-recovery.js';
|
|
12
13
|
import { adoptExistingPullRequestJob } from './cli-job-create.js';
|
|
13
14
|
import { resolveManagedProjectPath, resolveRepositoryProjectPath } from './workspace.js';
|
|
14
15
|
export function createWorkspaceControl(deps) {
|
|
15
|
-
const { client, trusted, noGitHub, repositories, refreshAll, requireLocalJobBinding, makeReconciler, concurrency, pool, bus, isEffectivelyBlocked, unblockTask, publishTaskUnblocked, dispatchTaskAction, registerBlockerDependency, discoverAgents, ensureManagedGitHubJob } = deps;
|
|
16
|
+
const { client, trusted, noGitHub, repositories, refreshAll, requireLocalJobBinding, makeReconciler, concurrency, pool, bus, isEffectivelyBlocked, unblockTask, publishTaskUnblocked, dispatchTaskAction, registerBlockerDependency, discoverAgents, ensureManagedGitHubJob, ensureBlockerRecovery: runBlockerRecovery = ensureBlockerRecovery } = deps;
|
|
16
17
|
const workspaceControl = async (body) => {
|
|
17
18
|
const command = typeof body.command === 'string' ? body.command : '';
|
|
18
19
|
const jobId = typeof body.jobId === 'string' ? body.jobId : '';
|
|
@@ -316,6 +317,91 @@ export function createWorkspaceControl(deps) {
|
|
|
316
317
|
await refreshAll();
|
|
317
318
|
return relation;
|
|
318
319
|
}
|
|
320
|
+
if (command === 'blocker.ensure') {
|
|
321
|
+
const request = body.request && typeof body.request === 'object' ? body.request : {};
|
|
322
|
+
const readText = (field) => typeof request[field] === 'string' ? request[field] : '';
|
|
323
|
+
if (request.origin !== 'planner' && request.origin !== 'troubleshooter')
|
|
324
|
+
throw new Error('blocker.ensure origin must be planner or troubleshooter');
|
|
325
|
+
if (request.resolutionMode !== 'merge' && request.resolutionMode !== 'verified')
|
|
326
|
+
throw new Error('blocker.ensure resolutionMode must be merge or verified');
|
|
327
|
+
const recoveryInput = {
|
|
328
|
+
requestId: readText('requestId'),
|
|
329
|
+
targetRepository: readText('targetRepository'),
|
|
330
|
+
dependentRepository: readText('dependentRepository'),
|
|
331
|
+
dependentJobId: readText('dependentJobId'),
|
|
332
|
+
dependentTaskId: readText('dependentTaskId'),
|
|
333
|
+
reason: readText('reason'),
|
|
334
|
+
title: readText('title'),
|
|
335
|
+
objective: readText('objective'),
|
|
336
|
+
projectPath: typeof request.projectPath === 'string' && request.projectPath ? request.projectPath : undefined,
|
|
337
|
+
resolutionMode: request.resolutionMode,
|
|
338
|
+
origin: request.origin,
|
|
339
|
+
authorized: request.authorized === true,
|
|
340
|
+
authorizedRepositories: repositories,
|
|
341
|
+
};
|
|
342
|
+
const recovered = await runBlockerRecovery(recoveryInput);
|
|
343
|
+
if (!repositories.includes(recoveryInput.targetRepository))
|
|
344
|
+
repositories.push(recoveryInput.targetRepository);
|
|
345
|
+
let planningRecoveryRequired = recovered.planningRecoveryRequired;
|
|
346
|
+
let status = recovered.status;
|
|
347
|
+
if (recovered.planningRecoveryRequired) {
|
|
348
|
+
const blocker = openLocalManagedStore(recoveryInput.targetRepository, 0, {
|
|
349
|
+
directory: relayStoreDirectory(), jobId: recovered.blockerJobId, noGitHub: true,
|
|
350
|
+
});
|
|
351
|
+
const planner = makeReconciler(blocker.store, concurrency);
|
|
352
|
+
try {
|
|
353
|
+
await planner.planJob(recovered.blockerJobId);
|
|
354
|
+
planningRecoveryRequired = false;
|
|
355
|
+
status = 'planned';
|
|
356
|
+
if (blocker.store.mutateJob) {
|
|
357
|
+
await blocker.store.mutateJob(recovered.blockerJobId, (current) => ({
|
|
358
|
+
...current,
|
|
359
|
+
blockerRecoveryRequest: current.blockerRecoveryRequest
|
|
360
|
+
? { ...current.blockerRecoveryRequest, status: 'planned', updatedAt: new Date().toISOString() }
|
|
361
|
+
: undefined,
|
|
362
|
+
}));
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
catch (error) {
|
|
366
|
+
const current = await blocker.store.load(recovered.blockerJobId);
|
|
367
|
+
const latestPlan = [...(current.plans ?? [])].sort((left, right) => right.round - left.round)[0];
|
|
368
|
+
if (latestPlan?.status !== 'PLANNING')
|
|
369
|
+
throw error;
|
|
370
|
+
}
|
|
371
|
+
finally {
|
|
372
|
+
await planner.close();
|
|
373
|
+
blocker.relay.close();
|
|
374
|
+
}
|
|
375
|
+
if (!planningRecoveryRequired && store.mutateJob) {
|
|
376
|
+
await store.mutateJob(recovered.dependentJobId, (current) => {
|
|
377
|
+
const task = current.tasks.find((item) => item.id === recovered.dependentTaskId);
|
|
378
|
+
const receipt = task?.blockerRecoveryReceipt;
|
|
379
|
+
if (task && receipt && receipt.requestId === recovered.requestId) {
|
|
380
|
+
task.blockerRecoveryReceipt = { ...receipt, status: 'planned', planningRecoveryRequired: false, updatedAt: new Date().toISOString() };
|
|
381
|
+
}
|
|
382
|
+
current.updatedAt = new Date().toISOString();
|
|
383
|
+
return current;
|
|
384
|
+
});
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
const blockerSnapshot = openLocalManagedStore(recoveryInput.targetRepository, 0, {
|
|
388
|
+
directory: relayStoreDirectory(), jobId: recovered.blockerJobId, noGitHub: true,
|
|
389
|
+
});
|
|
390
|
+
try {
|
|
391
|
+
if (blockerSnapshot.store.resolveBlockerDependents) {
|
|
392
|
+
const released = await blockerSnapshot.store.resolveBlockerDependents(recovered.blockerJobId, 'merge');
|
|
393
|
+
for (const target of released.unblocked)
|
|
394
|
+
await pool.reconcileLocalJob(target.jobId, 'control.blocker.ensure.resolution');
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
finally {
|
|
398
|
+
blockerSnapshot.relay.close();
|
|
399
|
+
}
|
|
400
|
+
await pool.reconcileLocalJob(recovered.dependentJobId, 'control.blocker.ensure.dependent');
|
|
401
|
+
await pool.reconcileLocalJob(recovered.blockerJobId, 'control.blocker.ensure.blocker');
|
|
402
|
+
await refreshAll();
|
|
403
|
+
return { ...recovered, status: planningRecoveryRequired ? 'planning_required' : status, planningRecoveryRequired };
|
|
404
|
+
}
|
|
319
405
|
if (command === 'blocker.resolve') {
|
|
320
406
|
if (!store.resolveBlockerDependents)
|
|
321
407
|
throw new Error('Blocker resolution unavailable');
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { GraphRuntime } from './graph-v2.js';
|
|
3
|
+
import { dispatchWorkflowGraph } from './dispatcher.js';
|
|
4
|
+
const source = readFileSync(new URL('../../workflow/blocker-recovery.mmd', import.meta.url), 'utf8');
|
|
5
|
+
export const blockerRecoveryGraph = new GraphRuntime(source, {
|
|
6
|
+
states: new Set(['entry', 'check_authorization', 'check_known_request', 'check_dependency', 'validate_adoption', 'validate_target', 'validate_trust_boundary', 'register', 'ready', 'rejected']),
|
|
7
|
+
guards: {
|
|
8
|
+
authorized: facts => facts.durableFacts.authorized === true,
|
|
9
|
+
knownRequest: facts => facts.durableFacts.knownRequest === true,
|
|
10
|
+
authoritativeDependency: facts => facts.durableFacts.authoritativeDependency === true,
|
|
11
|
+
adoptionValid: facts => facts.durableFacts.adoptionValid === true,
|
|
12
|
+
targetValid: facts => facts.durableFacts.targetValid === true,
|
|
13
|
+
trustBoundaryValid: facts => facts.durableFacts.trustBoundaryValid === true,
|
|
14
|
+
},
|
|
15
|
+
actions: Object.fromEntries([
|
|
16
|
+
'recovery.createBlocker',
|
|
17
|
+
'recovery.adoptExistingBlocker',
|
|
18
|
+
'recovery.registerDependency',
|
|
19
|
+
].map(id => [id, { id }])),
|
|
20
|
+
events: { 'blocker.recovery.ensure': { id: 'blocker.recovery.ensure' } },
|
|
21
|
+
});
|
|
22
|
+
export async function dispatchBlockerRecovery(facts, executeAction) {
|
|
23
|
+
return dispatchWorkflowGraph(blockerRecoveryGraph, {
|
|
24
|
+
initialState: 'entry',
|
|
25
|
+
input: { transport: 'event', id: 'blocker.recovery.ensure', payload: {} },
|
|
26
|
+
durableFacts: facts,
|
|
27
|
+
isTransientState: state => state.startsWith('check_') || state.startsWith('validate_') || state === 'register',
|
|
28
|
+
graphName: 'blocker-recovery',
|
|
29
|
+
maxSteps: 16,
|
|
30
|
+
executeAction,
|
|
31
|
+
});
|
|
32
|
+
}
|
|
@@ -9,7 +9,7 @@ export const blockerResolutionV2 = new GraphRuntime(source, {
|
|
|
9
9
|
'check_draft', 'check_blocked', 'check_failed', 'check_unblocked', 'wait', 'obsolete', 'resumed',
|
|
10
10
|
]),
|
|
11
11
|
guards: {
|
|
12
|
-
|
|
12
|
+
resolutionConditionMet: boolGuard('resolutionConditionMet'),
|
|
13
13
|
targetMatches: boolGuard('targetMatches'),
|
|
14
14
|
effectivelyBlocked: boolGuard('effectivelyBlocked'),
|
|
15
15
|
alreadyUnblocked: boolGuard('alreadyUnblocked'),
|
package/package.json
CHANGED
|
@@ -44,7 +44,7 @@ A worker's process exit, browser submission receipt, or emitted event is **not**
|
|
|
44
44
|
|
|
45
45
|
A Reviewer finding defects in a known immutable head emits `task.completed` with `data.verdict: changes-required`, `data.head_sha`, and actionable findings—not `task.failed`. If the Reviewer cannot establish the required head or produce a valid review, it reports an execution failure with `task.failed`, not an invented verdict.
|
|
46
46
|
|
|
47
|
-
For a failed Task, diagnose before retrying. Read `contracts/task-recovery-flows.md` for recovery and human escalation boundaries. Troubleshooter inspects the original Task via `task show` and paginated `task events`, verifies the root cause, then uses the pinned CLI `task recover --task-id ORIGINAL --recovery-task-id TROUBLESHOOTER` only after proving the repair.
|
|
47
|
+
For a failed Task, diagnose before retrying. Read `contracts/task-recovery-flows.md` for recovery and human escalation boundaries. For authorized technical prerequisites in another repository, use `contracts/blocker-job-recovery.md` and the pinned `blocker ensure` CLI action; repository boundaries alone do not justify escalation. Troubleshooter inspects the original Task via `task show` and paginated `task events`, verifies the root cause, then uses the pinned CLI `task recover --task-id ORIGINAL --recovery-task-id TROUBLESHOOTER` only after proving the repair. Only a genuinely human-required decision justifies the **pinned CLI** `task escalate --task-id TROUBLESHOOTER --required-action ... --resolution-condition ...`; this is a Relay operation, **not** an Events Bus event. Never invent or publish an escalation event, and never escalate a browser-readiness failure as a login request without authentication evidence. Only Relay can block/unblock a Troubleshooter; after a human response, recheck the blocker before recovering the original Task. Do not silently treat missing or stale evidence as success.
|
|
48
48
|
|
|
49
49
|
## 4. Configured escalation and host-owned Interactive Review
|
|
50
50
|
|
|
@@ -135,6 +135,7 @@ If evidence is absent or execution outcome is unknown, disposition that historic
|
|
|
135
135
|
- When a Job needs multi-perspective review, use the visible `review-chair` agent or an Agent Graph to select specialist roles dynamically. Keep specialist Tasks as independent siblings against the same immutable target/version, and leave worker/model/provider routing to Relay.
|
|
136
136
|
- A Task describes what an agent must accomplish; never emit a shell command as a worker Task.
|
|
137
137
|
- Use dependencies only for Task IDs inside the current Job, and only when execution order actually matters. Never encode cross-Job or cross-repository dependencies in `dependencies`.
|
|
138
|
+
- Do not label authorized technical work in another repository as an owner action or request human escalation just because it crosses a repository boundary. Assign executable work that uses the pinned `blocker ensure` action under `contracts/blocker-job-recovery.md`; preserve escalation for a real owner-only decision.
|
|
138
139
|
- When the current Job is a prerequisite for another durable Job/Task, emit that dependent in top-level `unblocks`. The current blocker Job owns this authoritative reverse relation. Dependent-side `blockedBy` is optional observability metadata and is not the source of truth. Use `resolutionMode: "merge"` when blocker PR merge is sufficient; use `"verified"` when publication, deployment, runtime health, human approval, or another post-merge fact must be verified.
|
|
139
140
|
- Describe each child Task precisely enough for worker-router to decide from the Task itself. Do not invent Codex/ChatGPT capability labels. workerRequirements is optional and should normally be omitted; use an explicit runtime only when the objective already requires that runtime.
|
|
140
141
|
- Do not choose codex/chatgpt, provider/model, or usage probes.
|
|
@@ -20,6 +20,7 @@ durable Relay Tasks. For runtime or lifecycle failures, use Relay recovery
|
|
|
20
20
|
instead of Spec Kit.
|
|
21
21
|
|
|
22
22
|
Read the independently pinned Task/Job Contract from the Relay Prompt. Only when a shared defect requires a P0/self-job, load `contracts/orchestrator-workflows.md` relative to the Prompt-pinned Relay Skill; do not add it to ordinary recovery startup Context.
|
|
23
|
+
For cross-repository blocker creation or reuse, follow `contracts/blocker-job-recovery.md` relative to the Prompt-pinned Relay Skill.
|
|
23
24
|
|
|
24
25
|
Read `troubleshooter-qa.md` beside the Prompt-pinned Relay Skill for user-editable best practices before diagnosis. Treat its answers as guidance only, below current evidence and authoritative contracts. After a verified recovery, add or refine a concise Q&A entry when it provides reusable knowledge; never include secrets or unverified claims.
|
|
25
26
|
|
|
@@ -38,7 +39,7 @@ Read `troubleshooter-qa.md` beside the Prompt-pinned Relay Skill for user-editab
|
|
|
38
39
|
6. Repair:
|
|
39
40
|
- For a transient failure, verify the transient condition is gone.
|
|
40
41
|
- For task-local failure, make the smallest durable repair in the original Job/PR when that is within scope.
|
|
41
|
-
- For
|
|
42
|
+
- For authorized technical work in another repository, use the pinned Relay CLI `blocker ensure` with the stable request identity and exact failed Task; do not classify that work as an owner action or escalate only because the repository differs. For an existing shared P0/self-job, reuse it. Complete this Troubleshooter after verifying the durable reverse relation; Relay owns later release.
|
|
42
43
|
- For a suspected genuine human/external blocker, invoke `agents-relay escalation` with the original intent, blocker, and relevant context. Handle the CLI-reported `resolved`, `failed`, and `needs_user` outcomes. When it returns `needs_user`, call Relay's `task escalate` operation with the concrete required action, resolution condition, and diagnostic context. Relay records the escalation and blocks this Troubleshooter; no worker remains running while waiting.
|
|
43
44
|
- After unblock, this same Troubleshooter must run with a new execution ID, re-check the blocking condition, and produce a fresh resolution bound to that execution. A previously resolved resolution record never authorizes retrying a new attempt.
|
|
44
45
|
- Unknown worker execution outcomes fail closed. Do not automatically reroute or retry the original task, and do not block the original task; diagnose it through the Troubleshooter.
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Cross-Repository Blocker Job Recovery
|
|
2
|
+
|
|
3
|
+
Use this contract when an authorized technical prerequisite must be completed in another repository before a failed Task can safely resume.
|
|
4
|
+
|
|
5
|
+
## Decision boundary
|
|
6
|
+
|
|
7
|
+
- Missing cross-repository capability is technical work. When it is within the parent Job's authorized objective and the target repository is within the same owner/workspace trust boundary, create or reuse a blocker Job; do not ask the owner to create it and do not escalate merely because the repository differs.
|
|
8
|
+
- Escalate only for a concrete owner-only action such as human approval, account consent, or a destructive/public/billing decision outside the existing authorization.
|
|
9
|
+
- The blocker Job owns a reverse `unblocks` relation to the exact dependent Job, Task, and attempt. Never create a cross-Job Task dependency or mark the original Task successful.
|
|
10
|
+
|
|
11
|
+
## Supported action
|
|
12
|
+
|
|
13
|
+
Use the version-matched Relay CLI `blocker ensure` action. It accepts the dependent `--repo` and `--id`, target `--target-repo`, exact `--dependent-task`, stable `--request-id`, short `--reason`, standalone `--title` and `--objective-file`, `--origin planner|troubleshooter`, `--resolution merge|verified`, and explicit `--authorized`. Include `--project-path` only when a validated repository-relative project path is known. The stable request ID must be reused unchanged after uncertainty or retry.
|
|
14
|
+
|
|
15
|
+
The objective must stand alone, identify the target repository and dependent Task, and stay within the parent authorization. Do not include secrets, arbitrary commands, path traversal, additional billing, public publication, destructive actions, or new sensitive access. The target repository must be normalized, configured in the trusted workspace, and share the dependent repository's owner/workspace boundary.
|
|
16
|
+
|
|
17
|
+
## Durable result and recovery
|
|
18
|
+
|
|
19
|
+
The action returns the blocker Job ID, repository, dependent Job/Task, reason, resolution mode, outcome, status, and whether planning recovery remains. Relay creates or adopts one durable Job, persists the request identity, and registers the reverse relation. A repeated request with the same identity and scope reuses that Job; reuse of the identity with different scope fails closed. If creation succeeded but planning or registration failed, retry the same request to recover the existing Job and continue the missing step. Never create a second Job to recover planning.
|
|
20
|
+
|
|
21
|
+
`merge` releases the dependent after the blocker Job's verified merge. `verified` releases it only after an explicit `blocker resolve` operation records the required post-merge evidence. The dependent Task stays failed/waiting until Relay verifies the configured condition and matching attempt. A blocker creation, planning, registration, or CLI receipt alone does not prove the original Task succeeded.
|
|
22
|
+
|
|
23
|
+
After the action, inspect the blocker Job and dependent Task through the pinned Relay CLI. A Troubleshooter may complete its own Task only after the handoff and exact reverse relation are durable. An immediate repair instead requires a fresh `task recover` receipt and confirmation that the original Task is queued for the expected recovery attempt.
|
|
@@ -18,6 +18,7 @@ cannot assume Neo exists. Never pass arbitrary Task text as a Shell command.
|
|
|
18
18
|
- **One agent Task event contract** applies to Implementation, Reviewer, and Troubleshooter: `task.started`, optional `task.progress`, then exactly one agent terminal event, `task.completed` or `task.failed`. Role-specific results belong in `data`. A review with findings is a *completed* review, not a failed agent execution.
|
|
19
19
|
- **`task.blocked` and `task.unblocked` are authoritative Relay lifecycle transitions**, not ordinary agent terminal events. A human may authorize unblocking a Troubleshooter but does not directly unblock the failed original Task.
|
|
20
20
|
- **Troubleshooter owns diagnosis and recovery decisions.** It chooses technical repair/retry, blocker-Job dependency, or human escalation. There is no separate Escalator agent.
|
|
21
|
+
- For an authorized technical prerequisite in another repository, use the create-or-reuse action in [`blocker-job-recovery.md`](blocker-job-recovery.md); repository boundaries alone never justify human escalation.
|
|
21
22
|
- **Relay owns transitions and dispatch.** Troubleshooter requests authorized operations through Relay CLI, then checks the CLI response and fresh Task Context. Event transport acceptance alone is not confirmation of a Task transition.
|
|
22
23
|
- Preserve the original failure, exact execution correlation, evidence, and idempotency throughout retries and resumes.
|
|
23
24
|
|
|
@@ -43,7 +44,7 @@ flowchart TD
|
|
|
43
44
|
E --> F{"Recovery decision"}
|
|
44
45
|
F -->|Technical recovery| G["Fix and verify; request retry"]
|
|
45
46
|
G --> H["Original Task resumes"]
|
|
46
|
-
F -->|
|
|
47
|
+
F -->|Authorized cross-repository technical work| I["Create or reuse blocker Job"]
|
|
47
48
|
I --> J["Dependency resolution"]
|
|
48
49
|
J --> K["Original Task resumes after verification"]
|
|
49
50
|
F -->|Human required| L["Troubleshooter requests escalation"]
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Blocker Recovery
|
|
3
|
+
description: Authorizes and idempotently creates or adopts a cross-repository blocker Job before registering its reverse dependency.
|
|
4
|
+
---
|
|
5
|
+
flowchart LR
|
|
6
|
+
%% relay: initial entry
|
|
7
|
+
entry["state: entry"]
|
|
8
|
+
check_authorization["state: check_authorization"]
|
|
9
|
+
check_known_request["state: check_known_request"]
|
|
10
|
+
check_dependency["state: check_dependency"]
|
|
11
|
+
validate_adoption["state: validate_adoption"]
|
|
12
|
+
validate_target["state: validate_target"]
|
|
13
|
+
validate_trust_boundary["state: validate_trust_boundary"]
|
|
14
|
+
register["state: register"]
|
|
15
|
+
ready["state: ready"]
|
|
16
|
+
rejected["state: rejected"]
|
|
17
|
+
|
|
18
|
+
authorized["guard: authorized"]
|
|
19
|
+
known_request["guard: knownRequest"]
|
|
20
|
+
authoritative_dependency["guard: authoritativeDependency"]
|
|
21
|
+
adoption_valid["guard: adoptionValid"]
|
|
22
|
+
target_valid["guard: targetValid"]
|
|
23
|
+
trust_boundary_valid["guard: trustBoundaryValid"]
|
|
24
|
+
|
|
25
|
+
create_blocker["action: recovery.createBlocker"]
|
|
26
|
+
adopt_blocker["action: recovery.adoptExistingBlocker"]
|
|
27
|
+
register_dependency["action: recovery.registerDependency"]
|
|
28
|
+
|
|
29
|
+
entry -->|on: blocker.recovery.ensure| check_authorization
|
|
30
|
+
check_authorization -->|on: blocker.recovery.ensure| authorized
|
|
31
|
+
authorized -->|false| rejected
|
|
32
|
+
authorized -->|true| validate_target
|
|
33
|
+
check_known_request -->|on: blocker.recovery.ensure| known_request
|
|
34
|
+
known_request -->|true| validate_adoption
|
|
35
|
+
known_request -->|false| check_dependency
|
|
36
|
+
check_dependency -->|on: blocker.recovery.ensure| authoritative_dependency
|
|
37
|
+
authoritative_dependency -->|true| validate_adoption
|
|
38
|
+
authoritative_dependency -->|false| create_blocker
|
|
39
|
+
validate_adoption -->|on: blocker.recovery.ensure| adoption_valid
|
|
40
|
+
adoption_valid -->|false| rejected
|
|
41
|
+
adoption_valid -->|true| adopt_blocker
|
|
42
|
+
adopt_blocker -->|to: register| register
|
|
43
|
+
validate_target -->|on: blocker.recovery.ensure| target_valid
|
|
44
|
+
target_valid -->|false| rejected
|
|
45
|
+
target_valid -->|true| validate_trust_boundary
|
|
46
|
+
validate_trust_boundary -->|on: blocker.recovery.ensure| trust_boundary_valid
|
|
47
|
+
trust_boundary_valid -->|false| rejected
|
|
48
|
+
trust_boundary_valid -->|true| check_known_request
|
|
49
|
+
create_blocker -->|to: register| register
|
|
50
|
+
register -->|on: blocker.recovery.ensure| register_dependency
|
|
51
|
+
register_dependency -->|to: ready| ready
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
title: Blocker Resolution
|
|
3
|
-
description: Releases dependency-waiting work; failed work and blocked Troubleshooters require their own fresh recovery flow.
|
|
3
|
+
description: Releases dependency-waiting work only after the blocker Job and configured resolution condition are verified; failed work and blocked Troubleshooters require their own fresh recovery flow.
|
|
4
4
|
---
|
|
5
5
|
flowchart LR
|
|
6
6
|
%% relay: initial waiting
|
|
@@ -16,7 +16,7 @@ wait["state: wait"]
|
|
|
16
16
|
obsolete["state: obsolete"]
|
|
17
17
|
resumed["state: resumed"]
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
resolutionConditionMet["guard: resolutionConditionMet"]
|
|
20
20
|
targetMatches["guard: targetMatches"]
|
|
21
21
|
effectivelyBlocked["guard: effectivelyBlocked"]
|
|
22
22
|
alreadyUnblocked["guard: alreadyUnblocked"]
|
|
@@ -27,9 +27,9 @@ isUnblocked["guard: isUnblocked"]
|
|
|
27
27
|
|
|
28
28
|
releaseDraft["action: blocker.releaseDraft"]
|
|
29
29
|
|
|
30
|
-
waiting -->|on: blocker.resolved|
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
waiting -->|on: blocker.resolved| resolutionConditionMet
|
|
31
|
+
resolutionConditionMet -->|false| wait
|
|
32
|
+
resolutionConditionMet -->|true| checkTarget
|
|
33
33
|
|
|
34
34
|
checkTarget -->|on: blocker.resolved| targetMatches
|
|
35
35
|
targetMatches -->|false| obsolete
|