agents-relay 2.0.208 → 2.0.210

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 (72) hide show
  1. package/dist/adapters.js +2 -1
  2. package/dist/agent-shortcut.js +113 -41
  3. package/dist/browser-worker-runtime.js +7 -2
  4. package/dist/chatgpt-platform-fallback.js +30 -0
  5. package/dist/cli-help.js +10 -4
  6. package/dist/cli-prompt.js +2 -1
  7. package/dist/cli-revision.js +49 -0
  8. package/dist/cli-shortcut-local.js +49 -0
  9. package/dist/cli-shortcut.js +81 -19
  10. package/dist/cli-worker-task.js +15 -0
  11. package/dist/cli.js +19 -5
  12. package/dist/dashboard-html.js +2 -2
  13. package/dist/dependency-revision-execution.js +152 -0
  14. package/dist/dependency-validity.js +17 -0
  15. package/dist/final-review-role.js +17 -0
  16. package/dist/force-restate-validation.js +6 -3
  17. package/dist/job-execution-slot.js +4 -1
  18. package/dist/job-pr-number-migration.js +2 -1
  19. package/dist/managed-worker-input.js +2 -1
  20. package/dist/model-routing.js +8 -0
  21. package/dist/planner-agent-roles.js +18 -0
  22. package/dist/planner-runtime.js +7 -1
  23. package/dist/planner-task-ids.js +1 -0
  24. package/dist/planner.js +11 -6
  25. package/dist/reconciler-review.js +110 -109
  26. package/dist/reconciler-runtime.js +56 -58
  27. package/dist/reconciler.js +33 -13
  28. package/dist/relay-job-snapshot-reads.js +5 -2
  29. package/dist/relay-store.js +2 -0
  30. package/dist/relay-workflow-operations.js +1 -1
  31. package/dist/relayd-control.js +31 -0
  32. package/dist/review-evidence.js +44 -0
  33. package/dist/review-generation-fence.js +2 -1
  34. package/dist/review-revision-execution.js +86 -0
  35. package/dist/review-revision-merge.js +15 -0
  36. package/dist/review-revision-model.js +191 -0
  37. package/dist/review-revision-policy.js +49 -0
  38. package/dist/review-revision-settlement.js +54 -0
  39. package/dist/review-revision-stale.js +57 -0
  40. package/dist/reviewer-thread.js +41 -1
  41. package/dist/runtime-status.js +24 -8
  42. package/dist/shortcut-node-worker.js +128 -0
  43. package/dist/shortcut-stage-contract.js +50 -0
  44. package/dist/shortcut-worker-runner.js +73 -0
  45. package/dist/single-job-task-control.js +1 -1
  46. package/dist/task-actions.js +4 -13
  47. package/dist/task-context.js +3 -2
  48. package/dist/task-inactivity-watchdog.js +7 -0
  49. package/dist/terminal-event-recovery.js +13 -0
  50. package/dist/worker-failure-recovery.js +90 -0
  51. package/dist/workflow/contracts.js +4 -0
  52. package/dist/workflow/definitions-v2.js +2 -0
  53. package/dist/workflow/dependency-revision-v2.js +16 -0
  54. package/dist/workflow/entity-creation.js +2 -0
  55. package/dist/workflow/review-v2.js +6 -2
  56. package/dist/workflow/revision-v2.js +32 -0
  57. package/dist/workflow/runtime.js +30 -0
  58. package/dist/workflow/task-reconcile.js +3 -0
  59. package/dist/workflow/task-resolution.js +1 -4
  60. package/package.json +4 -3
  61. package/skills/agents-relay/agents/job-acceptance-reviewer.agent.md +41 -0
  62. package/skills/agents-relay/agents/planner.agent.md +18 -5
  63. package/skills/agents-relay/agents/reviewer.agent.md +2 -0
  64. package/skills/agents-relay/contracts/event-contract.md +7 -0
  65. package/skills/agents-relay/contracts/orchestrator-workflows.md +6 -0
  66. package/skills/agents-relay/contracts/task-job-contract.md +10 -0
  67. package/workflow/dependency-revision.mmd +30 -0
  68. package/workflow/force-restate-validation.mmd +1 -1
  69. package/workflow/review-lifecycle.mmd +41 -10
  70. package/workflow/revision-lifecycle.mmd +68 -0
  71. package/workflow/task-lifecycle.mmd +13 -12
  72. package/workflow/task-resolution.mmd +1 -6
@@ -0,0 +1,191 @@
1
+ import { isFinalReviewAgent } from './final-review-role.js';
2
+ import { appendTaskComment } from './task-comments.js';
3
+ import { createHash } from 'node:crypto';
4
+ import { createTaskEntity } from './workflow/entity-creation.js';
5
+ import { decideRevisionLifecycle } from './workflow/revision-v2.js';
6
+ /** A stable child identity per immutable review round and responsible owner.
7
+ * The request IDs are append-only feedback attached to this single child.
8
+ */
9
+ export function targetedRevisionTaskId(reviewTaskId, ownerTaskId) {
10
+ return 'revision-' + createHash('sha256').update(JSON.stringify([reviewTaskId, ownerTaskId])).digest('hex').slice(0, 24);
11
+ }
12
+ /** A request and its source Task comment are one atomic SQLite Job snapshot mutation.
13
+ * The caller MUST execute this reducer inside RelayStore.mutateJob. It is never
14
+ * an out-of-band Task write and never reopens the original result.
15
+ */
16
+ export function recordTargetedRevisionRequest(job, input) {
17
+ if (!input.requestId?.trim() || input.requestId.length > 160)
18
+ throw new Error('revision request requires stable request ID (max 160)');
19
+ if (!input.headSha?.trim() || !input.reviewExecutionId?.trim())
20
+ throw new Error('revision requires exact reviewer execution and immutable head');
21
+ if (!input.findings?.length || input.findings.some(item => !item.id?.trim() || !item.summary?.trim() || item.summary.length > 4000))
22
+ throw new Error('revision requires identified, nonempty findings');
23
+ if (new Set(input.findings.map(item => item.id)).size !== input.findings.length)
24
+ throw new Error('duplicate finding IDs in revision request');
25
+ const existing = job.reviewRevisionRequests?.find(item => item.requestId === input.requestId);
26
+ if (existing) {
27
+ const same = existing.reviewTaskId === input.reviewTaskId
28
+ && existing.reviewExecutionId === input.reviewExecutionId
29
+ && existing.reviewHeadSha === input.headSha
30
+ && existing.originalTaskId === input.originalTaskId
31
+ && JSON.stringify(existing.findings) === JSON.stringify(input.findings);
32
+ if (!same)
33
+ throw new Error('revision request ID reused with different immutable feedback');
34
+ return { request: existing, created: false };
35
+ }
36
+ const reviewer = job.tasks.find(item => item.id === input.reviewTaskId);
37
+ const owner = job.tasks.find(item => item.id === input.originalTaskId);
38
+ const facts = {
39
+ reviewerAuthorized: job.state === 'ACTIVE'
40
+ && isFinalReviewAgent(reviewer?.agentName)
41
+ && reviewer?.state === 'RUNNING'
42
+ && reviewer?.executionId === input.reviewExecutionId,
43
+ reviewHeadCurrent: reviewer?.reviewHeadSha === input.headSha
44
+ && job.headSha === input.headSha
45
+ && (!job.review || (job.review.headSha === input.headSha
46
+ && job.review.taskId === input.reviewTaskId
47
+ && ['pending', 'started'].includes(job.review.outcome))),
48
+ originalTaskSucceeded: owner?.state === 'SUCCEEDED'
49
+ && owner.kind !== 'planner'
50
+ && !isFinalReviewAgent(owner.agentName)
51
+ && owner.id !== reviewer?.id
52
+ && !owner.revision,
53
+ };
54
+ const decision = decideRevisionLifecycle('NONE', 'revision.submit', facts);
55
+ if (!decision.accepted || decision.target !== 'REQUESTED'
56
+ || decision.actions.map(item => item.id).join(',') !== 'revision.recordRequest') {
57
+ throw new Error('revision rejected: reviewer, head, execution or original owner is not current/eligible');
58
+ }
59
+ const now = new Date().toISOString();
60
+ const childId = targetedRevisionTaskId(input.reviewTaskId, input.originalTaskId);
61
+ const request = {
62
+ requestId: input.requestId,
63
+ reviewTaskId: input.reviewTaskId,
64
+ reviewExecutionId: input.reviewExecutionId,
65
+ reviewHeadSha: input.headSha,
66
+ originalTaskId: input.originalTaskId,
67
+ findings: structuredClone(input.findings),
68
+ createdAt: now,
69
+ status: 'requested', revisionTaskId: childId,
70
+ feedbackOrigin: 'final-review',
71
+ };
72
+ job.reviewRevisionRequests = [...(job.reviewRevisionRequests ?? []), request];
73
+ appendTaskComment(job, input.originalTaskId, 'Final Review ' + input.reviewTaskId + ' requested revision at ' + input.headSha + ':\n'
74
+ + input.findings.map(f => '- ' + f.id + ': ' + f.summary).join('\n'), { author: 'reviewer', kind: 'review.feedback', executionId: input.reviewExecutionId,
75
+ transition: 'revision.requested', idempotencyKey: 'review-revision/' + input.requestId });
76
+ // Child creation and finding association are committed together with the
77
+ // request and owner comment: a crash cannot orphan an accepted request.
78
+ const existingChild = job.tasks.find(item => item.id === childId);
79
+ if (existingChild) {
80
+ if (existingChild.revision?.kind !== 'targeted' || existingChild.revision.originalTaskId !== input.originalTaskId
81
+ || existingChild.revision.reviewTaskId !== input.reviewTaskId || existingChild.revision.basedOnHeadSha !== input.headSha
82
+ || existingChild.state !== 'DRAFT')
83
+ throw new Error('revision child no longer accepts feedback in this immutable review round');
84
+ existingChild.revision.requestIds = [...new Set([...existingChild.revision.requestIds, input.requestId])];
85
+ }
86
+ else {
87
+ if (!owner || !reviewer)
88
+ throw new Error('review revision owner/reviewer missing');
89
+ const originalEvidence = owner.result ? JSON.stringify(owner.result) : 'No original result';
90
+ const child = createTaskEntity(job, {
91
+ jobId: job.id, id: childId, kind: 'work', title: 'Revise ' + (owner.title ?? owner.id),
92
+ priority: owner.priority ?? job.priority, storySize: owner.storySize ?? 'M', projectName: owner.projectName,
93
+ agentName: owner.agentName, parentTaskId: owner.id, dependencies: [reviewer.id],
94
+ capabilities: [...owner.capabilities], workerRequirements: owner.workerRequirements,
95
+ adapter: owner.adapter, input: [
96
+ `Revision of original Task ${owner.id} for Job ${job.id}; Final Review ${reviewer.id}, immutable reviewed head ${input.headSha}.`,
97
+ 'Retrieve the authoritative Task Context; follow ALL append-only review.feedback comments and associated request IDs. Repair the original result without changing the historical succeeded Task. Review the full current Job objective and repository head, implement and verify the correction, and include root cause, solution, validation and self-review evidence in the durable result.',
98
+ 'Original Task input:\n' + owner.input,
99
+ 'Original completed evidence:\n' + originalEvidence,
100
+ ].join('\n\n'), output: owner.output ?? { kind: 'task_pr' },
101
+ revision: { kind: 'targeted', originalTaskId: owner.id, requestIds: [input.requestId],
102
+ reviewTaskId: reviewer.id, basedOnHeadSha: input.headSha },
103
+ attempt: 0, maxAttempts: Math.max(3, owner.maxAttempts),
104
+ leaseOwner: null, leaseExpiresAt: null, executionId: null, threadId: null,
105
+ result: null, error: null, continuation: null, continuationDeliveredAt: null,
106
+ timeoutMs: owner.timeoutMs, createdAt: now, updatedAt: now,
107
+ }, { defer: true });
108
+ job.tasks.push(child);
109
+ }
110
+ appendTaskComment(job, childId, 'Review feedback request ' + input.requestId + ' for owner ' + input.originalTaskId + ' at ' + input.headSha + ':\n'
111
+ + input.findings.map(f => '- ' + f.id + ': ' + f.summary + (f.evidence ? '\n Evidence: ' + f.evidence : '')).join('\n'), { author: 'reviewer', kind: 'review.feedback', executionId: input.reviewExecutionId,
112
+ transition: 'revision.requested', idempotencyKey: 'review-revision-child/' + input.requestId });
113
+ return { request, created: true };
114
+ }
115
+ /** Transaction-safe public intake boundary for the later reviewer CLI.
116
+ * No caller can publish a request or its owner comment outside one SQLite
117
+ * authoritative Job mutation. The store is responsible for rollback.
118
+ */
119
+ export async function submitTargetedRevisionRequest(store, jobId, input) {
120
+ if (!store.mutateJob)
121
+ throw new Error('targeted revision requires an authoritative atomic Job store');
122
+ let created = false;
123
+ const committed = await store.mutateJob(jobId, current => {
124
+ created = recordTargetedRevisionRequest(current, input).created;
125
+ return current;
126
+ });
127
+ const request = committed.reviewRevisionRequests?.find(item => item.requestId === input.requestId);
128
+ if (!request)
129
+ throw new Error('targeted revision mutation did not persist the request');
130
+ return { request, created };
131
+ }
132
+ /** Only exact current-generation targeted requests count for the Review Graph.
133
+ * The record is not a worker success and does not itself authorize dispatch.
134
+ */
135
+ export function targetedRequestsForReview(job, reviewTask, headSha) {
136
+ return (job.reviewRevisionRequests ?? []).filter(request => request.reviewTaskId === reviewTask.id
137
+ && request.reviewExecutionId === reviewTask.executionId
138
+ && request.reviewHeadSha === headSha
139
+ && request.status !== 'stale'
140
+ && job.tasks.some(task => task.id === request.originalTaskId && task.state === 'SUCCEEDED'));
141
+ }
142
+ /** Full finding coverage is a fact supplied to the Review Graph, not a
143
+ * second procedural review policy. Unknown findings fail closed to ownership
144
+ * resolution rather than silently disappearing behind a partial request.
145
+ */
146
+ export function targetedRequestsCoverReview(job, reviewTask, headSha, verdictIssues) {
147
+ if (!verdictIssues.length || verdictIssues.some(issue => issue.trim() === '[unparseable blocking finding]'))
148
+ return false;
149
+ const requests = targetedRequestsForReview(job, reviewTask, headSha);
150
+ if (!requests.length)
151
+ return false;
152
+ const covered = new Set(requests.flatMap(request => request.findings.flatMap(finding => [finding.id.trim(), finding.summary.trim()])));
153
+ return verdictIssues.every(issue => covered.has(issue.trim()));
154
+ }
155
+ export function dependencyValidity(task, dependencyTaskId) {
156
+ if (!task.dependencies.includes(dependencyTaskId))
157
+ throw new Error('dependency is not declared on Task');
158
+ const mode = task.dependencyValidity?.[dependencyTaskId] ?? 'order-only';
159
+ if (mode !== 'order-only' && mode !== 'revalidate' && mode !== 'rerun')
160
+ throw new Error('invalid dependency validity policy');
161
+ return mode;
162
+ }
163
+ /** Deterministic semantic evidence vector; never infer validity from filenames.
164
+ * Historical successful owners remain immutable. The latest successful child
165
+ * is new evidence; pending/failed children must be gated by the future scheduler.
166
+ */
167
+ export function dependencyRevisionVector(job, task) {
168
+ const vector = {};
169
+ for (const dependencyId of [...new Set(task.dependencies)].sort()) {
170
+ if (dependencyValidity(task, dependencyId) === 'order-only')
171
+ continue;
172
+ const original = job.tasks.find(item => item.id === dependencyId);
173
+ if (!original)
174
+ throw new Error('dependency Task not found: ' + dependencyId);
175
+ // Task-array order is not provenance: inbound snapshots and restarts may
176
+ // reorder historical children. Creation time plus ID gives stable ordering.
177
+ const latest = job.tasks.filter(item => item.revision?.originalTaskId === dependencyId && item.state === 'SUCCEEDED').sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)).at(-1);
178
+ const selected = latest ?? original;
179
+ if (selected.state !== 'SUCCEEDED')
180
+ throw new Error('dependency has no successful evidence: ' + dependencyId);
181
+ // The successful Task ID and attempt identify the generation. Revision
182
+ // children are distinct and never rewrite a successful parent.
183
+ vector[dependencyId] = selected.id + ':' + selected.attempt;
184
+ }
185
+ return vector;
186
+ }
187
+ export function sameDependencyRevisionVector(a, b) {
188
+ const keysA = Object.keys(a).sort(), keysB = Object.keys(b).sort();
189
+ return keysA.length === keysB.length
190
+ && keysA.every((key, index) => key === keysB[index] && a[key] === b[key]);
191
+ }
@@ -0,0 +1,49 @@
1
+ import { createHash } from 'node:crypto';
2
+ function positiveIntegerSetting(env, name, fallback) {
3
+ const raw = env[name];
4
+ if (raw === undefined || raw.trim() === '')
5
+ return fallback;
6
+ const value = Number(raw);
7
+ if (!Number.isSafeInteger(value) || value < 1 || value > 100) {
8
+ throw new Error(`${name} must be an integer from 1 to 100`);
9
+ }
10
+ return value;
11
+ }
12
+ /** Operator-controlled loop bounds; defaults preserve the existing five-round gate. */
13
+ export function reviewRevisionLimits(env = process.env) {
14
+ return {
15
+ maxRounds: positiveIntegerSetting(env, 'AGENTS_RELAY_REVIEW_MAX_ROUNDS', 5),
16
+ maxNoProgressRounds: positiveIntegerSetting(env, 'AGENTS_RELAY_REVIEW_NO_PROGRESS_LIMIT', 1),
17
+ };
18
+ }
19
+ /** Stable identity for the review findings, independent of ordering and whitespace. */
20
+ export function reviewFindingFingerprint(findings) {
21
+ const normalized = [...new Set(findings.map(finding => finding.trim().replace(/\s+/g, ' ').toLocaleLowerCase('en-US')).filter(Boolean))].sort();
22
+ if (!normalized.length)
23
+ return undefined;
24
+ return createHash('sha256').update(JSON.stringify(normalized)).digest('hex');
25
+ }
26
+ /** Derive the fingerprint for pre-field rounds from their durable request evidence. */
27
+ export function reviewRoundFindingFingerprint(job, round) {
28
+ if (round.findingFingerprint)
29
+ return round.findingFingerprint;
30
+ const findings = (job.reviewRevisionRequests ?? [])
31
+ .filter(request => round.requestIds.includes(request.requestId))
32
+ .flatMap(request => request.findings.map(finding => finding.summary));
33
+ return reviewFindingFingerprint(findings);
34
+ }
35
+ export function repeatedFindingRounds(job, currentRound) {
36
+ const currentFingerprint = reviewRoundFindingFingerprint(job, currentRound);
37
+ if (!currentFingerprint || currentRound.status !== 'changes_required')
38
+ return 0;
39
+ let count = 0;
40
+ const previousRounds = (job.reviewRevisionRounds ?? [])
41
+ .filter(round => round.reviewTaskId !== currentRound.reviewTaskId && round.status === 'changes_required')
42
+ .sort((a, b) => a.recordedAt.localeCompare(b.recordedAt) || a.reviewTaskId.localeCompare(b.reviewTaskId));
43
+ for (let index = previousRounds.length - 1; index >= 0; index -= 1) {
44
+ if (reviewRoundFindingFingerprint(job, previousRounds[index]) !== currentFingerprint)
45
+ break;
46
+ count += 1;
47
+ }
48
+ return count;
49
+ }
@@ -0,0 +1,54 @@
1
+ import { appendTaskComment } from './task-comments.js';
2
+ import { dispatchReviewLifecycle } from './workflow/review-v2.js';
3
+ import { repeatedFindingRounds, reviewRevisionLimits } from './review-revision-policy.js';
4
+ /** Pure durable facts for the canonical Review Graph, not an alternate decision engine. */
5
+ function settlementFacts(job, taskId, limits) {
6
+ const requests = (job.reviewRevisionRequests ?? []).filter(item => item.reviewTaskId === taskId);
7
+ const targetedRevisionsVerified = requests.length > 0 && requests.every(request => request.status === 'verified' && job.tasks.some(task => task.id === request.revisionTaskId && task.state === 'SUCCEEDED'));
8
+ const rounds = (job.reviewRevisionRounds ?? []).filter(item => item.status === 'changes_required');
9
+ const currentRound = rounds.find(item => item.reviewTaskId === taskId);
10
+ return {
11
+ targetedRevisionsVerified,
12
+ reviewRoundWithinLimit: rounds.length < limits.maxRounds,
13
+ reviewNoProgressWithinLimit: !currentRound || repeatedFindingRounds(job, currentRound) < limits.maxNoProgressRounds,
14
+ };
15
+ }
16
+ /** The Graph alone decides whether the verified round can proceed or must escalate. */
17
+ export async function settleReviewRevisionRound(store, job) {
18
+ if (!store.mutateJob)
19
+ return job;
20
+ const review = job.review;
21
+ if (review?.outcome !== 'changes_required' || review.revisionDisposition !== 'targeted' || !review.taskId)
22
+ return job;
23
+ const limits = reviewRevisionLimits();
24
+ const facts = settlementFacts(job, review.taskId, limits);
25
+ const decision = await dispatchReviewLifecycle(review.outcome, 'revision.settled', facts);
26
+ if (!decision.accepted)
27
+ return job;
28
+ const action = decision.actions.map(item => item.id);
29
+ const prepare = decision.accepted && decision.target === 'STALE' && action.includes('review.prepareRereview');
30
+ const exhausted = decision.accepted && decision.target === 'CHANGES_REQUIRED' && action.includes('review.requireOwnerResolution');
31
+ if (!prepare && !exhausted)
32
+ return job;
33
+ return store.mutateJob(job.id, current => {
34
+ const latest = current.review;
35
+ if (latest?.outcome !== 'changes_required' || latest.revisionDisposition !== 'targeted'
36
+ || latest.taskId !== review.taskId || latest.headSha !== review.headSha)
37
+ return current;
38
+ const currentFacts = settlementFacts(current, review.taskId, limits);
39
+ if (Object.keys(facts).some(key => currentFacts[key] !== facts[key]))
40
+ return current;
41
+ const at = new Date().toISOString();
42
+ if (exhausted) {
43
+ current.review = { ...latest, revisionDisposition: 'needs-ownership', updatedAt: at };
44
+ const reason = !currentFacts.reviewRoundWithinLimit
45
+ ? `Targeted review loop reached its configured ${limits.maxRounds}-round limit`
46
+ : `The same blocking findings recurred without progress ${limits.maxNoProgressRounds} time(s)`;
47
+ appendTaskComment(current, review.taskId, `${reason}; explicit Planner/owner recovery required. No approval or merge authorized.`, { author: 'relay', idempotencyKey: 'review-round-limit/' + review.taskId });
48
+ }
49
+ else {
50
+ current.review = { ...latest, outcome: 'stale', updatedAt: at };
51
+ }
52
+ return current;
53
+ });
54
+ }
@@ -0,0 +1,57 @@
1
+ import { tryTransitionTaskEvent } from './task-transitions.js';
2
+ import { decideRevisionLifecycle } from './workflow/revision-v2.js';
3
+ /** Revision Graph-authorized cleanup of requests whose head OR reviewer
4
+ * execution generation became stale. Request + child disposition are atomic.
5
+ * An old-generation receipt must never cancel a currently active generation.
6
+ */
7
+ export async function staleReviewRevisions(store, job, reviewTaskId, headSha, cancelExecution, activeExecutionId) {
8
+ if (!store.mutateJob)
9
+ return;
10
+ const cancelled = [];
11
+ await store.mutateJob(job.id, current => {
12
+ if (current.review?.taskId !== reviewTaskId || current.review.headSha !== headSha)
13
+ return current;
14
+ if (activeExecutionId && current.tasks.find(task => task.id === reviewTaskId)?.executionId !== activeExecutionId)
15
+ return current;
16
+ let changed = false;
17
+ for (const request of current.reviewRevisionRequests ?? []) {
18
+ if (request.reviewTaskId !== reviewTaskId || request.reviewHeadSha !== headSha)
19
+ continue;
20
+ if (activeExecutionId && request.reviewExecutionId === activeExecutionId)
21
+ continue;
22
+ const states = { requested: 'REQUESTED', queued: 'QUEUED', running: 'RUNNING', failed: 'FAILED' };
23
+ const state = states[request.status];
24
+ if (!state)
25
+ continue;
26
+ const event = activeExecutionId ? 'review.execution_changed' : 'review.head_changed';
27
+ const decision = decideRevisionLifecycle(state, event);
28
+ if (!decision.accepted || decision.target !== 'STALE' || !decision.actions.some(action => action.id === 'revision.markStale'))
29
+ continue;
30
+ const child = request.revisionTaskId ? current.tasks.find(task => task.id === request.revisionTaskId) : undefined;
31
+ if (child && ['DRAFT', 'QUEUED', 'RUNNING'].includes(child.state)) {
32
+ const executionId = child.executionId ?? child.executionHistory?.at(-1)?.id ?? null;
33
+ if (!tryTransitionTaskEvent(child, 'cancel').accepted)
34
+ continue;
35
+ child.error = activeExecutionId
36
+ ? 'Targeted revision evidence became stale after reviewer execution changed'
37
+ : 'Targeted revision evidence became stale after review head changed';
38
+ child.leaseOwner = null;
39
+ child.leaseExpiresAt = null;
40
+ child.executionId = null;
41
+ child.updatedAt = new Date().toISOString();
42
+ if (executionId)
43
+ cancelled.push({ taskId: child.id, executionId });
44
+ }
45
+ else if (child && child.state !== 'FAILED' && child.state !== 'SUCCEEDED' && child.state !== 'CANCELLED') {
46
+ continue;
47
+ }
48
+ request.status = 'stale';
49
+ changed = true;
50
+ }
51
+ if (changed)
52
+ current.updatedAt = new Date().toISOString();
53
+ return current;
54
+ });
55
+ for (const execution of cancelled)
56
+ cancelExecution(execution.taskId, execution.executionId);
57
+ }
@@ -1,3 +1,4 @@
1
+ import { isFinalReviewAgent } from './final-review-role.js';
1
2
  import { arg, hasArg } from './cli-support.js';
2
3
  export function resolveImplementationThreadDestination(job) {
3
4
  return job.implementationThreadId ? normalizeThreadId(job.implementationThreadId, 'Job implementation thread ID') ?? null : null;
@@ -24,11 +25,20 @@ export function resolveReviewerThreadDestination(job, override) {
24
25
  const reviewerThreadId = job.reviewerThreadId ? normalizeThreadId(job.reviewerThreadId, 'Job reviewer thread ID') : undefined;
25
26
  if (reviewerThreadId)
26
27
  return { threadId: reviewerThreadId, source: 'reviewer' };
28
+ // A prior SHA-bound Reviewer is an explicit historical destination only when
29
+ // its ChatGPT route, surviving durable thread ID and URL prove compatibility.
30
+ const previous = 'tasks' in job && Array.isArray(job.tasks)
31
+ ? [...job.tasks].reverse().find(task => isFinalReviewAgent(task.agentName) && task.state === 'SUCCEEDED'
32
+ && task.adapter === 'chatgpt' && task.routing?.provider === 'chatgpt'
33
+ && task.threadId && task.threadUrl?.startsWith('https://chatgpt.com/c/') && !task.threadDeletedAt)
34
+ : undefined;
35
+ if (previous?.threadId)
36
+ return { threadId: normalizeThreadId(previous.threadId), source: 'reviewer' };
27
37
  const creatorThreadId = job.creatorThreadId ? normalizeThreadId(job.creatorThreadId, 'Job creator thread ID') : undefined;
28
38
  return creatorThreadId ? { threadId: creatorThreadId, source: 'creator' } : null;
29
39
  }
30
40
  export function prepareReviewerThreadDelivery(job, task, override) {
31
- if (task.agentName !== 'reviewer')
41
+ if (!isFinalReviewAgent(task.agentName))
32
42
  return undefined;
33
43
  const destination = resolveReviewerThreadDestination(job, override);
34
44
  if (!destination)
@@ -82,3 +92,33 @@ export async function recordThreadDelivery(store, jobId, taskId, executionId, wo
82
92
  current.chatgptThreadDelivery = { ...current.chatgptThreadDelivery, executionId, deliveredAt: new Date().toISOString() };
83
93
  await store.saveTask(current);
84
94
  }
95
+ /** Persisted safety evidence for exact original-thread reuse or explicit fallback. */
96
+ export function prepareRevisionThreadDelivery(job, child) {
97
+ if (!child.revision || child.revision.kind !== 'targeted')
98
+ return undefined;
99
+ const original = job.tasks.find(item => item.id === child.revision?.originalTaskId);
100
+ if (!original)
101
+ throw new Error('revision original Task missing');
102
+ const compatible = child.adapter === 'chatgpt' && original.adapter === 'chatgpt'
103
+ && child.routing?.provider === original.routing?.provider && original.routing?.provider === 'chatgpt'
104
+ && child.routing?.projectId === original.routing?.projectId && Boolean(child.executionId)
105
+ && Boolean(original.threadId && original.threadUrl?.startsWith('https://chatgpt.com/c/') && !original.threadDeletedAt);
106
+ const existing = child.revision.threadContinuation;
107
+ const reason = compatible ? 'matched original ChatGPT provider/project and durable live-compatible thread provenance'
108
+ : 'original thread missing/deleted or adapter/provider/project incompatible; safe full-context new execution';
109
+ if (existing && existing.decision === 'reuse' && !compatible) {
110
+ throw new Error('revision original-thread affinity changed after being selected; refuse uncertain duplicate send');
111
+ }
112
+ child.revision.threadContinuation = {
113
+ decision: compatible ? 'reuse' : 'fallback', reason, decidedAt: existing?.decidedAt ?? new Date().toISOString(),
114
+ ...(compatible ? { originalThreadId: original.threadId } : {}),
115
+ };
116
+ if (!compatible)
117
+ return undefined;
118
+ return {
119
+ kind: 'new-turn', threadId: original.threadId, threadSource: 'original-task',
120
+ requestId: `${job.id}:${child.id}:${child.executionId}`, jobId: job.id,
121
+ repository: job.repository, taskId: child.id, prNumber: job.prNumber,
122
+ executionId: child.executionId, projectId: child.routing?.projectId ?? null, deliveredAt: null,
123
+ };
124
+ }
@@ -1,13 +1,28 @@
1
- function isSuperseded(task) {
2
- return task.state === 'CANCELLED' && ((task.resolution?.path === 'cancel_supersede' && task.resolution.state === 'resolved')
3
- || (typeof task.error === 'string' && task.error.startsWith('Superseded ')));
1
+ import { isFinalReviewAgent } from './final-review-role.js';
2
+ export function isSuperseded(task, byId) {
3
+ if (task.state === 'CANCELLED' && task.resolution?.path === 'cancel_supersede' && task.resolution.state === 'resolved')
4
+ return true;
5
+ const classification = task.resolutionClassification;
6
+ return task.state === 'FAILED' && classification?.kind === 'superseded'
7
+ && typeof classification.targetTaskId === 'string' && Boolean(classification.targetTaskId.trim())
8
+ && typeof classification.evidence === 'string' && Boolean(classification.evidence.trim())
9
+ && typeof classification.reason === 'string' && Boolean(classification.reason.trim())
10
+ && byId.get(classification.targetTaskId)?.state === 'SUCCEEDED';
11
+ }
12
+ function staleTargetedRevisionTaskIds(job) {
13
+ return new Set((job.reviewRevisionRequests ?? [])
14
+ .filter(request => request.status === 'stale' && request.revisionTaskId)
15
+ .map(request => request.revisionTaskId));
4
16
  }
5
17
  export function implementationTasks(job) {
18
+ const byId = new Map(job.tasks.map(task => [task.id, task]));
19
+ const staleRevisions = staleTargetedRevisionTaskIds(job);
6
20
  return job.tasks.filter(task => task.kind !== 'planner'
7
- && task.agentName !== 'reviewer'
21
+ && !isFinalReviewAgent(task.agentName)
8
22
  && task.agentName !== 'troubleshooter'
9
- && !isSuperseded(task)
10
- && task.state !== 'DRAFT');
23
+ && !isSuperseded(task, byId)
24
+ && !staleRevisions.has(task.id)
25
+ && (task.state !== 'DRAFT' || Boolean(task.revision)));
11
26
  }
12
27
  export function implementationComplete(job) {
13
28
  const tasks = implementationTasks(job);
@@ -32,7 +47,7 @@ export function deriveJobRuntimeStatus(job, _prState = 'OPEN') {
32
47
  return 'RUNNING';
33
48
  if (implementation.some(task => task.state === 'QUEUED'))
34
49
  return 'QUEUED';
35
- const reviewRunning = job.tasks.some(task => task.agentName === 'reviewer' && task.state === 'RUNNING');
50
+ const reviewRunning = job.tasks.some(task => isFinalReviewAgent(task.agentName) && task.state === 'RUNNING');
36
51
  if (job.review?.outcome === 'approved')
37
52
  return 'MERGE_PENDING';
38
53
  if (reviewRunning)
@@ -43,7 +58,8 @@ export function deriveJobRuntimeStatus(job, _prState = 'OPEN') {
43
58
  return 'QUEUED';
44
59
  if (job.tasks.some(task => task.state === 'BLOCKED'))
45
60
  return 'BLOCKED';
46
- if (job.tasks.some(task => task.state === 'FAILED'))
61
+ const staleRevisions = staleTargetedRevisionTaskIds(job);
62
+ if (job.tasks.some(task => task.state === 'FAILED' && !staleRevisions.has(task.id)))
47
63
  return 'FAILED';
48
64
  if (job.tasks.some(task => task.state === 'DRAFT'))
49
65
  return 'WAITING';
@@ -0,0 +1,128 @@
1
+ import { mkdir, readFile } from 'node:fs/promises';
2
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
3
+ import { createTaskEntity } from './workflow/entity-creation.js';
4
+ /** A model node stays within its original Shortcut Job. Its durable child Task
5
+ * uses the existing Relay Worker adapter, lifecycle Graph and Troubleshooter.
6
+ * The parent Shortcut Graph, not the Worker Reconciler, selects DAG readiness. */
7
+ export async function runShortcutModelNode(options) {
8
+ const { store, reconciler, jobId, parentTaskId, node } = options;
9
+ if (!store.mutateJob)
10
+ throw new Error('Model nodes require the durable Relay SQLite store');
11
+ if (!/^[A-Za-z_][\w.-]*$/.test(node.id))
12
+ throw new Error('Invalid shortcut model node ID');
13
+ const taskId = `shortcut-${parentTaskId}-${node.id}`;
14
+ const initial = await store.load(jobId);
15
+ const parent = initial.tasks.find(t => t.id === parentTaskId);
16
+ if (!parent || parent.state !== 'RUNNING' || parent.executionId !== node.executionId || !parent.leaseOwner)
17
+ throw new Error('Model node parent execution is not leased by Shortcut Runner');
18
+ if (parent.output?.kind !== 'file' || !isAbsolute(parent.output.path))
19
+ throw new Error('Model nodes require a canonical absolute Task output directory');
20
+ const runRoot = dirname(parent.output.path);
21
+ const declaredRun = parent.input.match(/^- Canonical run:\s*(\/[^\r\n]+)$/m)?.[1]?.trim();
22
+ if (declaredRun && resolve(declaredRun) !== resolve(runRoot))
23
+ throw new Error('Shortcut Worker declared canonical run does not match the bound parent Task output directory');
24
+ const sourceRef = parent.input.match(/^- Private input evidence:\s*(\/[^\r\n]+)$/m)?.[1]?.trim();
25
+ if (sourceRef && (!declaredRun || dirname(resolve(sourceRef)) !== resolve(runRoot)))
26
+ throw new Error('Shortcut Worker source evidence is not confined to the declared canonical run');
27
+ const outputPath = join(runRoot, '.shortcut-node-results', `${taskId}.json`);
28
+ const started = initial.shortcutExecutionStartedAt && Date.parse(initial.shortcutExecutionStartedAt);
29
+ if (!started || !Number.isFinite(started))
30
+ throw new Error('Model node has no immutable Shortcut deadline origin');
31
+ const deadline = started + 20 * 60_000;
32
+ if (initial.shortcutExecutionDeadlineAt && Date.parse(initial.shortcutExecutionDeadlineAt) !== deadline)
33
+ throw new Error('Model node deadline differs from the original execution budget');
34
+ if (Date.now() >= deadline)
35
+ throw new Error('Shortcut execution budget exceeded before model node dispatch');
36
+ await mkdir(dirname(outputPath), { recursive: true, mode: 0o700 });
37
+ await store.mutateJob(jobId, current => {
38
+ const active = current.tasks.find(t => t.id === parentTaskId);
39
+ if (current.state !== 'ACTIVE' || current.executionMode !== 'shortcut' || current.contentOnly !== true || current.pause ||
40
+ !active || active.executionId !== node.executionId || active.state !== 'RUNNING' || !active.leaseOwner)
41
+ throw new Error('Shortcut model worker claim invalidated by Job lifecycle');
42
+ const cp = active.result?.data?.shortcut;
43
+ if (!cp || typeof cp !== 'object')
44
+ throw new Error('Shortcut model worker requires a persisted Graph checkpoint');
45
+ const state = cp;
46
+ if (state.nodes?.[node.id] || state.inFlight?.[node.id] !== node.executionId)
47
+ throw new Error('Model node is no longer pending in the current Graph execution');
48
+ state.workerNodes ??= {};
49
+ if (state.workerNodes[node.id] && state.workerNodes[node.id] !== taskId)
50
+ throw new Error('Conflicting durable Worker node mapping');
51
+ state.workerNodes[node.id] = taskId;
52
+ const existing = current.tasks.find(t => t.id === taskId);
53
+ if (existing) {
54
+ if (existing.parentTaskId !== parentTaskId || existing.agentName !== node.agent || existing.output?.kind !== 'file' || existing.output.path !== outputPath)
55
+ throw new Error('Durable Worker node identity mismatch');
56
+ }
57
+ else {
58
+ const now = new Date().toISOString();
59
+ const body = JSON.stringify({
60
+ source: 'shortcut-graph-node', jobId, parentTaskId, nodeId: node.id, agent: node.agent,
61
+ predecessorOutputs: node.predecessorOutputs,
62
+ originalInput: active.input,
63
+ ...(declaredRun ? { canonicalRunPath: declaredRun } : {}),
64
+ ...(sourceRef ? { sourceEvidencePath: sourceRef } : {}),
65
+ requiredResult: { status: 'COMPLETED', output: {}, artifacts: [] },
66
+ outputPath,
67
+ instruction: 'Execute only this Agent role for this DAG node. The ONLY structured DAG predecessor values are predecessorOutputs; never infer an undeclared sibling dependency. If canonicalRunPath is declared, read the authorized original source manifest and prior stage artifact files there as required by the project Agent/Stage contract; inspect and validate their real contents, source provenance, hashes and use rights. These files are allowed canonical run evidence, not an alternative DAG predecessor result and not proof of human approval. Do not claim they are absent merely because they are not repeated in predecessorOutputs. Write {status:"COMPLETED",output:{...},artifacts:[]} to outputPath only after meeting stage acceptance and send a correlated task.completed event. If a real prerequisite is unavailable, report the specific verified blocker and task.failed; do not fabricate, publish, approve or infer new permissions.'
68
+ });
69
+ current.tasks.push(createTaskEntity(current, {
70
+ jobId, id: taskId, title: `Shortcut model node ${node.id}`, kind: 'work', parentTaskId,
71
+ agentName: node.agent, dependencies: [], capabilities: ['model'], workerRequirements: { capabilities: ['model'] },
72
+ adapter: 'codex', input: body, output: { kind: 'file', path: outputPath },
73
+ attempt: 0, maxAttempts: 3, leaseOwner: null, leaseExpiresAt: null, executionId: null, threadId: null,
74
+ result: null, error: null, timeoutMs: Math.max(1, deadline - Date.now()), createdAt: now, updatedAt: now,
75
+ }));
76
+ }
77
+ return current;
78
+ });
79
+ while (true) {
80
+ if (node.signal.aborted)
81
+ throw node.signal.reason ?? new Error('Shortcut Worker node interrupted');
82
+ if (Date.now() >= deadline)
83
+ throw new Error('Shortcut execution budget exceeded while waiting for model node');
84
+ const current = await store.load(jobId);
85
+ if (current.state !== 'ACTIVE' || current.pause)
86
+ throw new Error('Shortcut Job cancelled/paused while Worker node was pending');
87
+ const task = current.tasks.find(t => t.id === taskId);
88
+ if (!task)
89
+ throw new Error('Worker node disappeared from the durable Job');
90
+ if (task.state === 'SUCCEEDED') {
91
+ const buffer = await readFile(outputPath);
92
+ const value = JSON.parse(buffer.toString('utf8'));
93
+ if (!value || typeof value !== 'object' || Array.isArray(value))
94
+ throw new Error('Worker Task reported success without contract-valid node output');
95
+ const record = value;
96
+ if (record.status !== 'COMPLETED' || !record.output || typeof record.output !== 'object' || Array.isArray(record.output))
97
+ throw new Error('Worker Task reported success without contract-valid node output');
98
+ // Some existing Worker roles report artifact records as {path,type}.
99
+ // Convert ONLY exact file records to the Shortcut contract's path list;
100
+ // the Graph executor still verifies realpath containment and SHA-256.
101
+ if (Array.isArray(record.artifacts)) {
102
+ const files = record.artifacts.map((item) => {
103
+ if (typeof item === 'string' && item.trim())
104
+ return item;
105
+ if (item && typeof item === 'object' && !Array.isArray(item)) {
106
+ const ref = item;
107
+ const fields = Object.keys(ref);
108
+ if (fields.length === 2 && fields.includes('path')
109
+ && ((fields.includes('type') && ref.type === 'file') || (fields.includes('kind') && ref.kind === 'file'))
110
+ && typeof ref.path === 'string' && ref.path.trim())
111
+ return ref.path;
112
+ }
113
+ throw new Error('Worker node returned unsupported artifact entry; expected a file path, {type:"file",path} or {kind:"file",path}');
114
+ });
115
+ return { ...record, artifacts: files };
116
+ }
117
+ if (!record.artifacts || typeof record.artifacts !== 'object')
118
+ throw new Error('Worker Task reported success without contract-valid artifact output');
119
+ return record;
120
+ }
121
+ if (task.state === 'CANCELLED')
122
+ throw new Error('Worker node cancelled');
123
+ if (task.state === 'BLOCKED')
124
+ throw new Error(`Worker node requires escalation: ${task.failureReason ?? task.error ?? task.id}`);
125
+ await reconciler.reconcile(jobId);
126
+ await new Promise(resolve => setTimeout(resolve, 100));
127
+ }
128
+ }