agents-relay 2.0.209 → 2.0.211
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/cli-help.js +10 -4
- package/dist/cli-prompt.js +2 -1
- package/dist/cli-revision.js +49 -0
- package/dist/cli-worker-task.js +15 -0
- package/dist/cli.js +11 -2
- package/dist/dashboard-html.js +2 -2
- package/dist/dependency-revision-execution.js +152 -0
- package/dist/dependency-validity.js +17 -0
- package/dist/final-review-role.js +17 -0
- package/dist/force-restate-validation.js +3 -2
- package/dist/host-invocation-store.js +18 -4
- package/dist/interactive-invocation.js +37 -5
- package/dist/job-pr-number-migration.js +2 -1
- package/dist/managed-worker-input.js +2 -1
- package/dist/planner-agent-roles.js +18 -0
- package/dist/planner-runtime.js +7 -1
- package/dist/planner-task-ids.js +1 -0
- package/dist/planner.js +11 -6
- package/dist/reconciler-review.js +78 -96
- package/dist/reconciler-runtime.js +14 -5
- package/dist/reconciler.js +21 -11
- package/dist/relay-store.js +2 -0
- package/dist/relayd-control.js +31 -0
- package/dist/review-evidence.js +44 -0
- package/dist/review-generation-fence.js +2 -1
- package/dist/review-revision-execution.js +86 -0
- package/dist/review-revision-merge.js +15 -0
- package/dist/review-revision-model.js +191 -0
- package/dist/review-revision-policy.js +49 -0
- package/dist/review-revision-settlement.js +54 -0
- package/dist/review-revision-stale.js +57 -0
- package/dist/reviewer-thread.js +41 -1
- package/dist/runtime-status.js +13 -4
- package/dist/single-job-task-control.js +1 -1
- package/dist/task-context.js +3 -2
- package/dist/worker-failure-recovery.js +2 -1
- package/dist/workflow/dependency-revision-v2.js +16 -0
- package/dist/workflow/entity-creation.js +2 -0
- package/dist/workflow/review-v2.js +6 -2
- package/dist/workflow/revision-v2.js +32 -0
- package/dist/workflow/task-reconcile.js +3 -0
- package/package.json +1 -1
- package/skills/agents-relay/agents/job-acceptance-reviewer.agent.md +41 -0
- package/skills/agents-relay/agents/planner.agent.md +6 -3
- package/skills/agents-relay/contracts/event-contract.md +55 -1
- package/skills/agents-relay/contracts/task-job-contract.md +6 -0
- package/workflow/dependency-revision.mmd +30 -0
- package/workflow/interactive-invocation.mmd +8 -2
- package/workflow/review-lifecycle.mmd +40 -9
- package/workflow/revision-lifecycle.mmd +68 -0
package/dist/cli-help.js
CHANGED
|
@@ -9,7 +9,7 @@ Usage:
|
|
|
9
9
|
|
|
10
10
|
Commands:
|
|
11
11
|
job create|update|show|list|run|shortcut-receipt|merge|unblock|cancel|pause|resume Manage SQLite-authoritative jobs with optional GitHub PRs
|
|
12
|
-
task create|update|show|list|classify|complete|retry|unblock|cancel Manage durable tasks
|
|
12
|
+
task create|update|show|list|revise|classify|complete|retry|unblock|cancel Manage durable tasks
|
|
13
13
|
review request Request graph-owned review (optional thread override)
|
|
14
14
|
artifact validate Check a JSON artifact against a project-owned JSON Schema
|
|
15
15
|
plan Invoke the Planner for an existing managed Job
|
|
@@ -164,13 +164,14 @@ Returns the same summary used by the dashboard header plus a running array with
|
|
|
164
164
|
task: `Manage durable tasks.
|
|
165
165
|
|
|
166
166
|
Usage:
|
|
167
|
-
npx agents-relay task <create|update|show|events|list|retry|unblock|cancel> [options]
|
|
167
|
+
npx agents-relay task <create|update|show|events|list|revise|retry|unblock|cancel> [options]
|
|
168
168
|
|
|
169
169
|
Actions:
|
|
170
170
|
create Create one durable Task under an existing Job
|
|
171
171
|
update Update mutable Task fields
|
|
172
172
|
show Show one Task
|
|
173
173
|
list List Tasks for a Job
|
|
174
|
+
revise Submit an immutable-head targeted reviewer fix request
|
|
174
175
|
retry Retry a FAILED Task
|
|
175
176
|
unblock Authoritatively invalidate a BLOCKED decision
|
|
176
177
|
complete Complete an orchestrator-owned Task
|
|
@@ -178,7 +179,7 @@ Actions:
|
|
|
178
179
|
'task create': `Create one durable Task under an existing Job.
|
|
179
180
|
|
|
180
181
|
Required: normal Job storage options plus --input-file PATH|- (preferred) or --input MARKDOWN, and --output task-pr|file. --input and --input-file are mutually exclusive.
|
|
181
|
-
Common: --task-id ID (optional; Relay auto-assigns a global increasing integer Task ID), --title TITLE (optional; otherwise derived from the first non-empty input line), --idempotency-key KEY, --priority P0|P1|P2|P3, --story-size S|M|L, --agent NAME, --agent-graph-file PATH|-, --deps a,b, --parent ID, --draft. Normal model-backed Tasks omit adapter/provider/model so Relay runs one Execution Router decision over complete worker+model routes. New Tasks are worker-routed; legacy adapter=orchestrator records are recovery-only and cannot be created or manually executed.\nTasks with dependencies start DRAFT; tasks without dependencies start QUEUED unless --draft is given.
|
|
182
|
+
Common: --task-id ID (optional; Relay auto-assigns a global increasing integer Task ID), --title TITLE (optional; otherwise derived from the first non-empty input line), --idempotency-key KEY, --priority P0|P1|P2|P3, --story-size S|M|L, --agent NAME, --agent-graph-file PATH|-, --deps a,b, --dependency-validity JSON, --parent ID, --draft. The JSON maps declared dependency Task IDs to order-only, revalidate, or rerun. Normal model-backed Tasks omit adapter/provider/model so Relay runs one Execution Router decision over complete worker+model routes. New Tasks are worker-routed; legacy adapter=orchestrator records are recovery-only and cannot be created or manually executed.\nTasks with dependencies start DRAFT; tasks without dependencies start QUEUED unless --draft is given.
|
|
182
183
|
Directly-created Tasks are not wrapped in a synthetic Plan. Planner-generated Tasks are created internally by Relay from planner output.
|
|
183
184
|
|
|
184
185
|
Example:
|
|
@@ -186,12 +187,17 @@ Example:
|
|
|
186
187
|
'task update': `Update mutable durable Task fields in place.
|
|
187
188
|
|
|
188
189
|
Required: --id JOB_ID --task-id ID. Optional --repo OWNER/REPO fences the Job identity.
|
|
189
|
-
Mutable while not RUNNING/SUCCEEDED/CANCELLED: --title, --adapter, --priority, --story-size, --input-file PATH|- or --input MARKDOWN, --project, --agent, --agent-graph-file PATH|-, --parent, --deps, --capabilities, --timeout (inactivity window), --max-attempts, --provider, --model, --profile, --reasoning, --cwd, --chatgpt-project, --chatgpt-tab-close-policy, --draft, --queue.
|
|
190
|
+
Mutable while not RUNNING/SUCCEEDED/CANCELLED: --title, --adapter, --priority, --story-size, --input-file PATH|- or --input MARKDOWN, --project, --agent, --agent-graph-file PATH|-, --parent, --deps, --dependency-validity JSON, --capabilities, --timeout (inactivity window), --max-attempts, --provider, --model, --profile, --reasoning, --cwd, --chatgpt-project, --chatgpt-tab-close-policy, --draft, --queue.
|
|
190
191
|
Accepted task.started and newer current-execution task.progress events reset --timeout.
|
|
191
192
|
Use --clear-routing to remove routing metadata.
|
|
192
193
|
|
|
193
194
|
Example:
|
|
194
195
|
npx agents-relay task update --repo OWNER/REPO --pr 12 --id 101 --task-id build --adapter chatgpt --provider chatgpt --model gpt-5.6-sol --reasoning high`,
|
|
196
|
+
'task revise': `Authenticated immutable-head targeted revision request from the active Final Reviewer.
|
|
197
|
+
|
|
198
|
+
Required: --repo OWNER/REPO --id JOB --task-id ORIGINAL --review-task-id FINAL_REVIEW --execution-id CURRENT_REVIEW_EXECUTION --head-sha EXACT_SHA --request-id STABLE_ID --findings-file PATH. The findings file contains a nonempty JSON array [{"id":"F-1","summary":"...","evidence":"..."}].
|
|
199
|
+
|
|
200
|
+
The Relay service verifies the current Reviewer generation and local Git head, atomically records immutable owner feedback and a semantic child revision. Repeating an identical request ID is idempotent; it does not finish a Reviewer or revision Task. Reviewer must subsequently report its canonical changes-required verdict.`,
|
|
195
201
|
'task comment': `Append an immutable Task comment. Does not retry or change Task state.
|
|
196
202
|
|
|
197
203
|
Required: --repo OWNER/REPO --id JOB_ID --task-id TASK_ID and --message TEXT or --message-file FILE.`,
|
package/dist/cli-prompt.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isFinalReviewAgent } from './final-review-role.js';
|
|
1
2
|
import { readFile, writeFile } from 'node:fs/promises';
|
|
2
3
|
import { plannerInput } from './planner.js';
|
|
3
4
|
import { arg, storeFor } from './cli-support.js';
|
|
@@ -89,7 +90,7 @@ export async function runPromptCommand(args) {
|
|
|
89
90
|
throw new Error(`Task ${taskId} not found in Job ${job.id}`);
|
|
90
91
|
if (!task.executionId)
|
|
91
92
|
throw new Error(`Task ${taskId} has no execution ID`);
|
|
92
|
-
const context = await resolveExecutionContext(projectPath, task.agentName === 'troubleshooter' ? 'troubleshooter' : task.agentName
|
|
93
|
+
const context = await resolveExecutionContext(projectPath, task.agentName === 'troubleshooter' ? 'troubleshooter' : isFinalReviewAgent(task.agentName) ? 'reviewer' : 'worker');
|
|
93
94
|
prompt = await managedWorkerInput(job, { ...task, adapter }, context);
|
|
94
95
|
}
|
|
95
96
|
const output = arg(args, '--output');
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { arg, relayControlCommand } from './cli-support.js';
|
|
3
|
+
/** Reviewer-controlled file intake; findings are structured immutable evidence. */
|
|
4
|
+
export function parseRevisionFindings(source) {
|
|
5
|
+
let value;
|
|
6
|
+
try {
|
|
7
|
+
value = JSON.parse(source);
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
throw new Error('findings-file must contain a JSON array of {id,summary,evidence?}');
|
|
11
|
+
}
|
|
12
|
+
if (!Array.isArray(value) || !value.length || value.length > 200)
|
|
13
|
+
throw new Error('findings-file requires 1..200 identified findings');
|
|
14
|
+
const findings = value.map((item, index) => {
|
|
15
|
+
if (!item || typeof item !== 'object' || Array.isArray(item))
|
|
16
|
+
throw new Error(`finding ${index} must be an object`);
|
|
17
|
+
const entry = item;
|
|
18
|
+
if (typeof entry.id !== 'string' || !entry.id.trim() || entry.id.length > 160
|
|
19
|
+
|| typeof entry.summary !== 'string' || !entry.summary.trim() || entry.summary.length > 4000
|
|
20
|
+
|| (entry.evidence !== undefined && (typeof entry.evidence !== 'string' || entry.evidence.length > 10000))) {
|
|
21
|
+
throw new Error(`finding ${index} requires valid id, summary, optional evidence`);
|
|
22
|
+
}
|
|
23
|
+
if (Object.keys(entry).some(key => !['id', 'summary', 'evidence'].includes(key)))
|
|
24
|
+
throw new Error(`finding ${index} contains unsupported fields`);
|
|
25
|
+
return { id: entry.id.trim(), summary: entry.summary.trim(), ...(typeof entry.evidence === 'string' ? { evidence: entry.evidence } : {}) };
|
|
26
|
+
});
|
|
27
|
+
if (new Set(findings.map(item => item.id)).size !== findings.length)
|
|
28
|
+
throw new Error('findings-file contains duplicate IDs');
|
|
29
|
+
return findings;
|
|
30
|
+
}
|
|
31
|
+
export async function runTaskReviseCommand(args) {
|
|
32
|
+
const jobId = arg(args, '--id');
|
|
33
|
+
const repository = arg(args, '--repo');
|
|
34
|
+
const taskId = arg(args, '--task-id');
|
|
35
|
+
const reviewTaskId = arg(args, '--review-task-id');
|
|
36
|
+
const reviewExecutionId = arg(args, '--execution-id');
|
|
37
|
+
const headSha = arg(args, '--head-sha');
|
|
38
|
+
const requestId = arg(args, '--request-id');
|
|
39
|
+
const findingsFile = arg(args, '--findings-file');
|
|
40
|
+
if ([jobId, repository, taskId, reviewTaskId, reviewExecutionId, headSha, requestId, findingsFile].some(value => !value || value.startsWith('--')))
|
|
41
|
+
throw new Error('task revise requires --repo --id --task-id --review-task-id --execution-id --head-sha --request-id --findings-file');
|
|
42
|
+
const findings = parseRevisionFindings(await readFile(findingsFile, 'utf8'));
|
|
43
|
+
const response = await relayControlCommand(args, {
|
|
44
|
+
command: 'task.revise', jobId, repository, taskId, reviewTaskId, reviewExecutionId, headSha, requestId, findings,
|
|
45
|
+
});
|
|
46
|
+
if (!response.request || response.request.requestId !== requestId || response.request.originalTaskId !== taskId || !response.request.revisionTaskId)
|
|
47
|
+
throw new Error('Relay targeted revision receipt has unexpected request or Task identity');
|
|
48
|
+
console.log(JSON.stringify({ status: 'durable', ...response }, null, 2));
|
|
49
|
+
}
|
package/dist/cli-worker-task.js
CHANGED
|
@@ -2,6 +2,7 @@ import { taskOverallTimeoutMs } from './types.js';
|
|
|
2
2
|
import { arg, hasArg, textOption, integerArg, chatGptTabClosePolicy, storySize, priority, continuation } from './cli-support.js';
|
|
3
3
|
import { parseAgentGraph } from './agent-graph.js';
|
|
4
4
|
import { createTaskEntity } from './workflow/entity-creation.js';
|
|
5
|
+
import { validateDependencyValidity } from './dependency-validity.js';
|
|
5
6
|
export function recoveryDiagnosisFromArgs(args) {
|
|
6
7
|
const failureKind = arg(args, '--failure-kind');
|
|
7
8
|
if (!failureKind)
|
|
@@ -13,6 +14,18 @@ export function recoveryDiagnosisFromArgs(args) {
|
|
|
13
14
|
throw new Error('Invalid --failure-kind');
|
|
14
15
|
return { failureKind, reason, evidence: arg(args, '--evidence') || undefined, reroute: hasArg(args, '--reroute'), excludeCurrentRoute: hasArg(args, '--exclude-current-route') };
|
|
15
16
|
}
|
|
17
|
+
export function dependencyValidityFromArgs(args, dependencies) {
|
|
18
|
+
if (!hasArg(args, '--dependency-validity'))
|
|
19
|
+
return undefined;
|
|
20
|
+
let parsed;
|
|
21
|
+
try {
|
|
22
|
+
parsed = JSON.parse(arg(args, '--dependency-validity'));
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
throw new Error('--dependency-validity must be valid JSON');
|
|
26
|
+
}
|
|
27
|
+
return validateDependencyValidity(dependencies, parsed, '--dependency-validity');
|
|
28
|
+
}
|
|
16
29
|
export async function workerTaskFromArgs(job, args, now) {
|
|
17
30
|
const model = arg(args, '--model');
|
|
18
31
|
const adapterValue = arg(args, '--adapter');
|
|
@@ -38,6 +51,7 @@ export async function workerTaskFromArgs(job, args, now) {
|
|
|
38
51
|
const closePolicy = hasArg(args, '--chatgpt-tab-close-policy') ? chatGptTabClosePolicy(args) : undefined;
|
|
39
52
|
const size = storySize(args);
|
|
40
53
|
const dependencies = arg(args, '--deps').split(',').filter(Boolean);
|
|
54
|
+
const dependencyValidity = dependencyValidityFromArgs(args, dependencies);
|
|
41
55
|
const timeoutMs = hasArg(args, '--timeout') ? integerArg(args, '--timeout', taskOverallTimeoutMs(size, routing?.reasoning)) : routing ? taskOverallTimeoutMs(size, routing.reasoning) : 0;
|
|
42
56
|
return createTaskEntity(job, {
|
|
43
57
|
jobId: job.id,
|
|
@@ -50,6 +64,7 @@ export async function workerTaskFromArgs(job, args, now) {
|
|
|
50
64
|
agentGraph,
|
|
51
65
|
parentTaskId: arg(args, '--parent') || null,
|
|
52
66
|
dependencies,
|
|
67
|
+
dependencyValidity,
|
|
53
68
|
capabilities: arg(args, '--capabilities').split(',').filter(Boolean),
|
|
54
69
|
workerRequirements,
|
|
55
70
|
adapter,
|
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { runTaskReviseCommand } from './cli-revision.js';
|
|
2
3
|
import { runArtifactCommand } from './cli-artifact.js';
|
|
3
4
|
import { runWorkflowAction } from './cli-workflow-action.js';
|
|
4
5
|
import { workflowCliResult } from './cli-workflow.js';
|
|
@@ -45,7 +46,7 @@ import { normalizeThreadId, runtimeReviewer } from './reviewer-thread.js';
|
|
|
45
46
|
export { runtimeReviewer } from './reviewer-thread.js';
|
|
46
47
|
import { SERVICE_DEFAULTS, ServiceEventBus, arg, hasArg, textOption, integerArg, repository, storeFor, saveLocal, eventBus, publishWake, priority, storySize, chatGptTabClosePolicy, continuation, rejectRemovedJobOptions, jobTagFromArgs, requestManagedReconciliation, relayControlJob, relayControlCommand, relayJobList, relayJobStateCommand, relayTaskCommand, withEventBus } from './cli-support.js';
|
|
47
48
|
export { SERVICE_DEFAULTS, eventBus, chatGptTabClosePolicy } from './cli-support.js';
|
|
48
|
-
import { recoveryDiagnosisFromArgs, workerTaskFromArgs } from './cli-worker-task.js';
|
|
49
|
+
import { dependencyValidityFromArgs, recoveryDiagnosisFromArgs, workerTaskFromArgs } from './cli-worker-task.js';
|
|
49
50
|
import { requestTroubleshooterEscalation, resumeTroubleshooter } from './task-recovery.js';
|
|
50
51
|
import { pauseJob, resumeJob } from './job-pause.js';
|
|
51
52
|
export { ensureManagedGitHubJob } from './cli-job-create.js';
|
|
@@ -82,8 +83,12 @@ async function runManagedTaskCommand(action, args) {
|
|
|
82
83
|
async function runTaskCommand(action, args) {
|
|
83
84
|
if (hasArg(args, '--shortcut-local'))
|
|
84
85
|
return runLocalShortcutBinding('task', action, args);
|
|
85
|
-
if (!['create', 'update', 'show', 'context', 'events', 'comment', 'comments', 'list', 'retry', 'recover', 'unblock', 'escalate', 'resume-troubleshooter', 'cancel', 'supersede', 'classify'].includes(action))
|
|
86
|
+
if (!['create', 'update', 'show', 'context', 'events', 'comment', 'comments', 'list', 'retry', 'recover', 'unblock', 'escalate', 'resume-troubleshooter', 'cancel', 'supersede', 'classify', 'revise'].includes(action))
|
|
86
87
|
throw new Error(usage);
|
|
88
|
+
if (action === 'revise') {
|
|
89
|
+
await runTaskReviseCommand(args);
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
87
92
|
if (action === 'context' || action === 'events') {
|
|
88
93
|
await (action === 'context' ? runTaskContextCommand(args) : runTaskEventsCommand(args));
|
|
89
94
|
return;
|
|
@@ -200,6 +205,10 @@ async function runTaskCommand(action, args) {
|
|
|
200
205
|
task.parentTaskId = arg(args, '--parent') || null;
|
|
201
206
|
if (hasArg(args, '--deps'))
|
|
202
207
|
task.dependencies = arg(args, '--deps').split(',').filter(Boolean);
|
|
208
|
+
if (hasArg(args, '--dependency-validity'))
|
|
209
|
+
task.dependencyValidity = dependencyValidityFromArgs(args, task.dependencies);
|
|
210
|
+
else if (task.dependencyValidity)
|
|
211
|
+
task.dependencyValidity = dependencyValidityFromArgs(['--dependency-validity', JSON.stringify(task.dependencyValidity)], task.dependencies);
|
|
203
212
|
if (hasArg(args, '--capabilities'))
|
|
204
213
|
task.capabilities = arg(args, '--capabilities').split(',').filter(Boolean);
|
|
205
214
|
task.timeoutMs = integerArg(args, '--timeout', task.timeoutMs);
|
package/dist/dashboard-html.js
CHANGED
|
@@ -246,7 +246,7 @@ const CHAT_SHORTCUT_TARGET='agents-relay-shortcut';
|
|
|
246
246
|
function chatShortcutField(job){const box=element('div','detail-group');box.append(element('p','detail-label',text('ChatGPT shortcut')));const select=document.createElement('select');select.className='job-filter job-chat-shortcut-select';select.setAttribute('aria-label','ChatGPT shortcut');select.append(new Option('',''));for(const item of parseChatShortcuts(chatShortcutText()))select.append(new Option(item.name,item.prompt));select.value='';select.addEventListener('change',()=>{if(!select.value)return;const prompt=select.value.replaceAll('%1',jobChatRef(job));window.open(chatShortcutUrl(prompt),CHAT_SHORTCUT_TARGET,'noopener');select.value='';});box.append(select);return box;}
|
|
247
247
|
function renderJobList(){jobList.replaceChildren();const visible=filteredJobs();if(!jobs.length){jobList.append(element('li','empty',text('No durable jobs discovered.')));return;}if(!visible.length){jobList.append(element('li','empty',text('No jobs match the selected filters.')));return;}for(const job of visible){const row=element('div','job-row'+(isCompleteUnmerged(job)?' complete-unmerged':''));row.setAttribute('aria-current',String(jobSelectionKey(job)===selectedJob));row.addEventListener('click',()=>selectJob(job));const content=element('div','job-content');const select=document.createElement('button');select.type='button';select.className='job-button';select.setAttribute('aria-current',String(jobSelectionKey(job)===selectedJob));select.title=job.title||job.id;select.addEventListener('click',event=>{event.stopPropagation();selectJob(job);});select.append(element('span','job-title',text(repoName(job.repository)+'/'+value(job.id)+(Number(job.prNumber||0)>0?'/PR#'+value(job.prNumber):'')+': '+value(job.title||job.id))));const states=element('span','job-status-line');states.append(element('span','badge '+value(job.state),text(value(job.state))),element('span','badge '+value(job.runtimeStatus||'IDLE'),text(value(job.runtimeStatus||'IDLE'))));if(job.publicationFailure)states.append(element('span','badge FAILED',text('PUBLISH FAILED: '+value(job.publicationFailure.stage))));else if(job.publication?.version)states.append(element('span','badge SUCCEEDED',text('v'+job.publication.version)));else if(Number(job.prNumber||0)>0&&job.githubState==='MERGED')states.append(element('span','badge MERGED',text('PR Merged')));else if(job.state==='COMPLETED'&&job.githubState==='CLOSED')states.append(element('span','badge SUCCEEDED',text('PR Archived')));if(job.state==='ACTIVE'&&job.reviewEnabled!==false)states.append(element('span','badge flag-review',text('REVIEW REQUIRED')));if(job.localMerge?.status==='failed')states.append(element('span','badge FAILED',text('MERGE FAILED: '+value(job.localMerge.error||'Unknown error'))));else if(isCompleteUnmerged(job))states.append(element('span','badge MERGE_PENDING',text('MERGE PENDING')));const primary=element('div','job-primary');primary.append(states);const lastLine=element('div','job-last-line');lastLine.append(element('span','subtle',text(compactCounts(counts(job.tasks)))),element('span','subtle',text(relativeTime(job.updatedAt))));content.append(select,primary,lastLine);row.append(content);jobList.append(element('li','',row));}}
|
|
248
248
|
function taskTagDisplay(job,task){const display=task.tag&&job?.tag?.values?.[task.tag];return typeof display==='string'&&display?display:null;}
|
|
249
|
-
function taskVerdict(job,task){if(task.state!=="SUCCEEDED")return null;const data=task.result?.data||{};if(task.agentName
|
|
249
|
+
function taskVerdict(job,task){if(task.state!=="SUCCEEDED")return null;const data=task.result?.data||{};if(["reviewer","job-acceptance-reviewer"].includes(task.agentName)){const verdict=data.verdict||((job?.review?.taskId===task.id)?job.review.outcome:null);return ({approved:"APPROVED",pass:"APPROVED","changes-required":"CHANGES REQUIRED",changes_required:"CHANGES REQUIRED"})[verdict]||null;}if(task.agentName==="troubleshooter"){const original=job?.tasks?.find(t=>t.id===task.parentTaskId);const resolution=original?.resolution;if(resolution?.state!=="resolved"||resolution.owner!=="troubleshooter")return null;return ({exact_original_retry:"RETRY VERIFIED",same_job_dependency:"DEPENDENCY REGISTERED",blocker_job_dependency:"BLOCKER REGISTERED",cancel_supersede:"SUPERSEDED"})[resolution.path]||null;}return null;}function taskSubtreeComplete(task,children){return ['SUCCEEDED','CANCELLED'].includes(task.state)&&(children.get(task.id)||[]).every(child=>taskSubtreeComplete(child,children));}
|
|
250
250
|
function taskStateLabel(task){const resolution=task?.resolution?.state;return task?.state==='FAILED'&&typeof resolution==='string'&&resolution.trim()?task.state+' / '+resolution:task.state;}
|
|
251
251
|
function taskNode(task,children,depth){const li=element('li');const nested=children.get(task.id)||[];const line=element('div','task-line');if(nested.length){const key=(selectedJob||'')+':'+task.id;const collapsed=collapsedTasks.has(key)||(!expandedTasks.has(key)&&taskSubtreeComplete(task,children));const fold=document.createElement('button');fold.type='button';fold.className='task-fold';fold.setAttribute('aria-expanded',String(!collapsed));fold.setAttribute('aria-label',(collapsed?'Expand ':'Collapse ')+task.id);fold.textContent=collapsed?'▸':'▾';line.append(fold);const ul=element('ul','tree');ul.hidden=collapsed;for(const child of nested)ul.append(taskNode(child,children,depth+1));fold.addEventListener('click',()=>{const next=!ul.hidden;ul.hidden=next;fold.setAttribute('aria-expanded',String(!next));fold.setAttribute('aria-label',(next?'Expand ':'Collapse ')+task.id);fold.textContent=next?'▸':'▾';if(next){collapsedTasks.add(key);expandedTasks.delete(key);}else{collapsedTasks.delete(key);expandedTasks.add(key);}});li.append(line,ul);}else li.append(line);const row=document.createElement('button');row.type='button';row.className='task-row';row.setAttribute('aria-current',String(task.id===selectedTaskId));row.title=task.id;row.addEventListener('click',()=>{const deselect=selectedTaskId===task.id;selectedTaskId=deselect?null:task.id;eventTaskId=deselect?null:task.id;rememberSelection();clearEvents();renderAll();void loadEventHistory();});const label=element('span','task-id',text(value(task.id)+': '+value(task.title||task.input?.split(/\\r?\\n/).find(line=>line.trim())?.trim()||shortManagedId(task.id,selected()?.repository,'t'))));label.style.paddingLeft=Math.min(depth,4)*6+'px';const verdict=taskVerdict(selected(),task);row.append(label,element('span','badge '+(verdict==='APPROVED'||verdict==='RESOLVED'?'SUCCEEDED':verdict==='CHANGES REQUIRED'||verdict==='WAITING'?'BLOCKED':value(task.state)),text(task.state==='FAILED'?taskStateLabel(task):(verdict||task.state))));const tag=taskTagDisplay(selected(),task);if(tag){const badge=element('span','task-tag',text(tag));badge.title=(selected()?.tag?.description||'Task tag')+': '+task.tag;row.append(badge);}line.append(row);return li;}
|
|
252
252
|
function buildTree(tasks){taskTree.replaceChildren();if(!Array.isArray(tasks)||!tasks.length){taskTree.append(element('li','empty',text('No tasks in durable state.')));return;}const work=tasks.filter(task=>task.kind!=='planner');if(!work.length){taskTree.append(element('li','empty',text('No work tasks in durable state.')));return;}const known=new Set(work.map(task=>task.id));const children=new Map();const roots=[];for(const task of work){if(!task.parentTaskId||!known.has(task.parentTaskId))roots.push(task);else{const siblings=children.get(task.parentTaskId)||[];siblings.push(task);children.set(task.parentTaskId,siblings);}}for(const task of roots)taskTree.append(taskNode(task,children,0));}
|
|
@@ -260,7 +260,7 @@ function taskStateField(task){const box=element('div','detail-group');box.append
|
|
|
260
260
|
function manualOverrideField(task){const rows=Array.isArray(task.manualStateOverrides)?task.manualStateOverrides:[];const last=rows.at(-1);return field('Manual override',last?last.from+' → '+last.to+' · '+relativeTime(last.at):'—');}
|
|
261
261
|
function iconSvg(name){const paths={close:'M5 5l14 14M19 5 5 19',detail:'M7 3h7l4 4v14H7zM14 3v5h4M10 12h5m-5 4h5'};const ns='http://www.w3.org/2000/svg';const svg=document.createElementNS(ns,'svg');svg.setAttribute('viewBox','0 0 24 24');svg.setAttribute('aria-hidden','true');const path=document.createElementNS(ns,'path');path.setAttribute('d',paths[name]);svg.append(path);return svg;}
|
|
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
|
-
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=>task.agentName
|
|
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
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||''));}
|
|
266
266
|
async function loadJSON(url){const response=await fetch(url);if(!response.ok)throw new Error(response.status+' '+response.statusText);return response.json();}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { createTaskEntity } from './workflow/entity-creation.js';
|
|
3
|
+
import { tryApplyTaskCancelAction } from './task-actions.js';
|
|
4
|
+
import { decideDependencyRevision } from './workflow/dependency-revision-v2.js';
|
|
5
|
+
import { dependencyRevisionVector, dependencyValidity, sameDependencyRevisionVector } from './review-revision-model.js';
|
|
6
|
+
import { isFinalReviewAgent } from './final-review-role.js';
|
|
7
|
+
function latestDirectRevision(job, original) {
|
|
8
|
+
return job.tasks.filter(task => task.revision?.originalTaskId === original.id && task.state === 'SUCCEEDED')
|
|
9
|
+
.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id)).at(-1);
|
|
10
|
+
}
|
|
11
|
+
/** Original results have baseline upstream evidence; subsequent descendants
|
|
12
|
+
* carry their checked vector. No external path, Git diff or filename inference. */
|
|
13
|
+
function priorVector(job, original) {
|
|
14
|
+
return latestDirectRevision(job, original)?.revision?.dependencyVector
|
|
15
|
+
?? Object.fromEntries(original.dependencies.filter(id => dependencyValidity(original, id) !== 'order-only')
|
|
16
|
+
.map(id => {
|
|
17
|
+
const dependency = job.tasks.find(task => task.id === id);
|
|
18
|
+
if (!dependency)
|
|
19
|
+
throw new Error(`missing original dependency ${id}`);
|
|
20
|
+
return [id, `${id}:${dependency.attempt}`];
|
|
21
|
+
}));
|
|
22
|
+
}
|
|
23
|
+
/** Last-minute execution and terminal fence: never accept verification of a
|
|
24
|
+
* superseded upstream evidence generation, including after process restart. */
|
|
25
|
+
export function dependencyRevisionStillCurrent(job, task) {
|
|
26
|
+
const revision = task.revision;
|
|
27
|
+
if (!revision || (revision.kind !== 'rerun' && revision.kind !== 'revalidate'))
|
|
28
|
+
return true;
|
|
29
|
+
const original = job.tasks.find(item => item.id === revision.originalTaskId);
|
|
30
|
+
if (!original || !revision.dependencyVector)
|
|
31
|
+
return false;
|
|
32
|
+
try {
|
|
33
|
+
if (!sameDependencyRevisionVector(dependencyRevisionVector(job, original), revision.dependencyVector))
|
|
34
|
+
return false;
|
|
35
|
+
const explicit = original.dependencies.filter(id => dependencyValidity(original, id) !== 'order-only');
|
|
36
|
+
return explicit.every(id => !job.tasks.some(candidate => candidate.id !== task.id
|
|
37
|
+
&& candidate.revision?.originalTaskId === id && !['SUCCEEDED', 'CANCELLED'].includes(candidate.state)));
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
export function reconcileDependencyRevisionFacts(job) {
|
|
44
|
+
const created = [];
|
|
45
|
+
const changedStale = [];
|
|
46
|
+
const originals = job.tasks.filter(task => task.kind !== 'planner' && !isFinalReviewAgent(task.agentName)
|
|
47
|
+
&& task.agentName !== 'troubleshooter' && task.state === 'SUCCEEDED' && !task.revision);
|
|
48
|
+
// Stable topological order ensures dependent Tasks wait for intermediate
|
|
49
|
+
// scheduled work and never bypass a changed ancestor at multi-input fan-in.
|
|
50
|
+
const visited = new Set();
|
|
51
|
+
const sorted = [];
|
|
52
|
+
const visit = (task) => {
|
|
53
|
+
if (visited.has(task.id))
|
|
54
|
+
return;
|
|
55
|
+
visited.add(task.id);
|
|
56
|
+
for (const id of task.dependencies) {
|
|
57
|
+
const dependency = originals.find(candidate => candidate.id === id);
|
|
58
|
+
if (dependency)
|
|
59
|
+
visit(dependency);
|
|
60
|
+
}
|
|
61
|
+
sorted.push(task);
|
|
62
|
+
};
|
|
63
|
+
originals.forEach(visit);
|
|
64
|
+
for (const original of sorted) {
|
|
65
|
+
// A queued/DRAFT child whose upstream evidence moved is superseded by the
|
|
66
|
+
// authoritative Task cancellation graph. Running work is settled via the
|
|
67
|
+
// correlated terminal-generation fence in reconciler-runtime.
|
|
68
|
+
for (const stale of job.tasks.filter(task => task.revision?.originalTaskId === original.id
|
|
69
|
+
&& (task.revision.kind === 'revalidate' || task.revision.kind === 'rerun')
|
|
70
|
+
&& ['DRAFT', 'QUEUED'].includes(task.state) && !dependencyRevisionStillCurrent(job, task))) {
|
|
71
|
+
const decision = decideDependencyRevision('dependency.stale', {}, 'PROPOSED');
|
|
72
|
+
if (decision.accepted && decision.target === 'STALE' && decision.actions.some(action => action.id === 'dependencyRevision.markStale')) {
|
|
73
|
+
tryApplyTaskCancelAction(stale, 'Superseded upstream dependency evidence vector changed before execution');
|
|
74
|
+
changedStale.push(stale.id);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const policies = original.dependencies.filter(id => dependencyValidity(original, id) !== 'order-only');
|
|
78
|
+
if (!policies.length)
|
|
79
|
+
continue;
|
|
80
|
+
const inputsSettled = policies.every(id => !job.tasks.some(task => task.revision?.originalTaskId === id
|
|
81
|
+
&& !['SUCCEEDED', 'CANCELLED'].includes(task.state)))
|
|
82
|
+
&& !job.tasks.some(task => task.revision?.originalTaskId === original.id && !['SUCCEEDED', 'CANCELLED'].includes(task.state));
|
|
83
|
+
if (!inputsSettled)
|
|
84
|
+
continue;
|
|
85
|
+
const vector = dependencyRevisionVector(job, original);
|
|
86
|
+
const previous = priorVector(job, original);
|
|
87
|
+
const changed = !sameDependencyRevisionVector(vector, previous);
|
|
88
|
+
const rerunRequired = policies.some(id => vector[id] !== previous[id] && dependencyValidity(original, id) === 'rerun');
|
|
89
|
+
const stableKey = JSON.stringify([original.id, vector]);
|
|
90
|
+
const id = 'dependency-revision-' + createHash('sha256').update(stableKey).digest('hex').slice(0, 24);
|
|
91
|
+
const duplicate = job.tasks.some(task => task.id === id || task.revision?.originalTaskId === original.id
|
|
92
|
+
&& task.revision.kind !== 'targeted' && sameDependencyRevisionVector(task.revision.dependencyVector ?? {}, vector));
|
|
93
|
+
const decision = decideDependencyRevision('dependency.reconcile', {
|
|
94
|
+
upstreamEvidenceChanged: changed, explicitValidityPolicy: policies.length > 0,
|
|
95
|
+
allInputsSettled: inputsSettled, notAlreadyRecorded: !duplicate, rerunRequired,
|
|
96
|
+
});
|
|
97
|
+
if (!decision.accepted || decision.target !== 'PROPOSED')
|
|
98
|
+
continue;
|
|
99
|
+
// The canonical Dependency Revision Graph owns rerun vs revalidate.
|
|
100
|
+
// Facts supply evidence, but never select the workflow action here.
|
|
101
|
+
const selectedActions = decision.actions.map(action => action.id);
|
|
102
|
+
if (selectedActions.length !== 1 || !['dependencyRevision.createRerun', 'dependencyRevision.createRevalidation'].includes(selectedActions[0])) {
|
|
103
|
+
throw new Error('Dependency Revision Graph did not select exactly one child action');
|
|
104
|
+
}
|
|
105
|
+
const mode = selectedActions[0] === 'dependencyRevision.createRerun' ? 'rerun' : 'revalidate';
|
|
106
|
+
const inputs = policies.map(id => {
|
|
107
|
+
const originalDependency = job.tasks.find(task => task.id === id);
|
|
108
|
+
return latestDirectRevision(job, originalDependency) ?? originalDependency;
|
|
109
|
+
});
|
|
110
|
+
const upstreamRequests = inputs.flatMap(task => task.revision?.requestIds ?? []);
|
|
111
|
+
const ancestorReview = inputs.find(task => task.revision)?.revision?.reviewTaskId ?? job.review?.taskId ?? '';
|
|
112
|
+
const current = new Date().toISOString();
|
|
113
|
+
const child = createTaskEntity(job, {
|
|
114
|
+
jobId: job.id, id, title: `${mode === 'rerun' ? 'Rerun' : 'Revalidate'} ${original.title ?? original.id}`,
|
|
115
|
+
kind: 'work', parentTaskId: original.id, agentName: original.agentName,
|
|
116
|
+
priority: original.priority ?? job.priority, storySize: original.storySize ?? 'M', projectName: original.projectName,
|
|
117
|
+
dependencies: [...new Set([original.id, ...inputs.map(task => task.id)])],
|
|
118
|
+
capabilities: [...original.capabilities], workerRequirements: original.workerRequirements,
|
|
119
|
+
adapter: original.adapter, output: original.output ?? { kind: 'task_pr' },
|
|
120
|
+
input: [
|
|
121
|
+
`${mode === 'rerun' ? 'MANDATORY RERUN' : 'EXPLICIT REVALIDATION'} of original Task ${original.id}.`,
|
|
122
|
+
`Semantic dependency evidence vector (all inputs must be validated): ${JSON.stringify(vector)}.`,
|
|
123
|
+
mode === 'rerun' ? 'Re-execute the original deliverable from the current upstream evidence; do not merely sign off the old output.'
|
|
124
|
+
: 'Verify whether the original delivered result remains valid against every new upstream generation. Update code/output if required and report exact verification evidence.',
|
|
125
|
+
'Original durable Task objective: ' + original.input,
|
|
126
|
+
'Original result: ' + JSON.stringify(original.result),
|
|
127
|
+
].join('\n\n'),
|
|
128
|
+
revision: { kind: mode, originalTaskId: original.id,
|
|
129
|
+
requestIds: [...new Set(upstreamRequests)], reviewTaskId: ancestorReview,
|
|
130
|
+
basedOnHeadSha: job.headSha ?? '', dependencyVector: vector },
|
|
131
|
+
attempt: 0, maxAttempts: Math.max(3, original.maxAttempts),
|
|
132
|
+
leaseOwner: null, leaseExpiresAt: null, executionId: null, threadId: null,
|
|
133
|
+
result: null, error: null, timeoutMs: original.timeoutMs,
|
|
134
|
+
createdAt: current, updatedAt: current, continuation: null, continuationDeliveredAt: null,
|
|
135
|
+
});
|
|
136
|
+
job.tasks.push(child);
|
|
137
|
+
created.push(id);
|
|
138
|
+
}
|
|
139
|
+
if (created.length || changedStale.length)
|
|
140
|
+
job.updatedAt = new Date().toISOString();
|
|
141
|
+
return created;
|
|
142
|
+
}
|
|
143
|
+
export async function reconcileDependencyRevisions(store, jobId) {
|
|
144
|
+
if (!store.mutateJob)
|
|
145
|
+
return [];
|
|
146
|
+
let created = [];
|
|
147
|
+
await store.mutateJob(jobId, job => {
|
|
148
|
+
created = reconcileDependencyRevisionFacts(job);
|
|
149
|
+
return job;
|
|
150
|
+
});
|
|
151
|
+
return created;
|
|
152
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export function validateDependencyValidity(dependencies, value, field = 'dependencyValidity') {
|
|
2
|
+
if (value === undefined || value === null)
|
|
3
|
+
return undefined;
|
|
4
|
+
if (typeof value !== 'object' || Array.isArray(value))
|
|
5
|
+
throw new Error(`${field} must be an object`);
|
|
6
|
+
const allowed = new Set(dependencies);
|
|
7
|
+
const result = {};
|
|
8
|
+
for (const [taskId, policy] of Object.entries(value)) {
|
|
9
|
+
if (!allowed.has(taskId))
|
|
10
|
+
throw new Error(`${field} key ${taskId} must identify a declared dependency`);
|
|
11
|
+
if (policy !== 'order-only' && policy !== 'revalidate' && policy !== 'rerun') {
|
|
12
|
+
throw new Error(`${field}[${taskId}] must be order-only, revalidate, or rerun`);
|
|
13
|
+
}
|
|
14
|
+
result[taskId] = policy;
|
|
15
|
+
}
|
|
16
|
+
return result;
|
|
17
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Stable internal review lifecycle role with a new externally visible Agent identity. */
|
|
2
|
+
export const FINAL_REVIEW_AGENT = 'job-acceptance-reviewer';
|
|
3
|
+
export function isFinalReviewAgent(name) {
|
|
4
|
+
return name === FINAL_REVIEW_AGENT || name === 'reviewer';
|
|
5
|
+
}
|
|
6
|
+
export function nextFinalReviewTaskId(job, headSha) {
|
|
7
|
+
const base = 'final-review-' + headSha.slice(0, 12);
|
|
8
|
+
const ids = new Set(job.tasks.filter(task => task.reviewHeadSha === headSha && isFinalReviewAgent(task.agentName)).map(task => task.id));
|
|
9
|
+
if (!ids.has(base))
|
|
10
|
+
return base;
|
|
11
|
+
for (let round = 2; round < 1000; round += 1) {
|
|
12
|
+
const candidate = base + '-r' + round;
|
|
13
|
+
if (!ids.has(candidate))
|
|
14
|
+
return candidate;
|
|
15
|
+
}
|
|
16
|
+
throw new Error('Too many final review rounds for ' + headSha);
|
|
17
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isFinalReviewAgent } from './final-review-role.js';
|
|
1
2
|
import { classifyTaskResolution } from './workflow/task-resolution.js';
|
|
2
3
|
import { tryTransitionTaskEvent } from './task-transitions.js';
|
|
3
4
|
import { satisfiesWorker } from './worker-routing.js';
|
|
@@ -76,7 +77,7 @@ export function objectiveSatisfiedForReview(job) {
|
|
|
76
77
|
if (latest?.status !== 'SUCCEEDED' || latest.objectiveStatus !== 'satisfied')
|
|
77
78
|
return false;
|
|
78
79
|
const byId = new Map(job.tasks.map(task => [task.id, task]));
|
|
79
|
-
const implementation = job.tasks.filter(task => task.kind !== 'planner' && task.agentName
|
|
80
|
+
const implementation = job.tasks.filter(task => task.kind !== 'planner' && !isFinalReviewAgent(task.agentName) && task.agentName !== 'troubleshooter'
|
|
80
81
|
&& !isSuperseded(task, byId));
|
|
81
82
|
return implementation.length > 0 && implementation.every(task => task.state === 'SUCCEEDED');
|
|
82
83
|
}
|
|
@@ -102,7 +103,7 @@ export function applyPlannerHistoryCleanup(job, expectedTaskIds, cleanup, now) {
|
|
|
102
103
|
if (item.outcome === 'unresolved')
|
|
103
104
|
continue;
|
|
104
105
|
if (item.outcome === 'cancelled_review') {
|
|
105
|
-
if (task.agentName
|
|
106
|
+
if (!isFinalReviewAgent(task.agentName) || !tryTransitionTaskEvent(task, 'cancel').accepted) {
|
|
106
107
|
issues.push(`Task ${item.taskId} cannot be cancelled as a failed review. Only a FAILED reviewer Task can use cancelled_review.`);
|
|
107
108
|
continue;
|
|
108
109
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { eventOnlyReviewEligible } from './interactive-invocation.js';
|
|
1
2
|
export const hostInvocationTablesSql = `
|
|
2
3
|
CREATE TABLE IF NOT EXISTS host_invocation_event (
|
|
3
4
|
job_id TEXT NOT NULL,
|
|
@@ -51,9 +52,21 @@ export function recordHostInvocationDecision(db, delivery, fingerprint, writeSna
|
|
|
51
52
|
const job = snapshot?.json ? JSON.parse(snapshot.json) : null;
|
|
52
53
|
const task = job?.tasks.find(item => item.id === delivery.taskId);
|
|
53
54
|
const invocation = task?.interactiveInvocation;
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
55
|
+
const bound = invocation && ['RUNNING', 'DRAFT'].includes(task?.state ?? '') &&
|
|
56
|
+
invocation.executionId === delivery.executionId &&
|
|
57
|
+
(task?.executionId === delivery.executionId || task?.state === 'DRAFT') &&
|
|
58
|
+
invocation.status === 'awaiting_decision' && invocation.invocationId === delivery.invocationId &&
|
|
59
|
+
invocation.revision === delivery.revision;
|
|
60
|
+
// Event-only reviews are claims against an ACTIVE execution, not permission to
|
|
61
|
+
// release an arbitrary DRAFT/failed/cancelled Task or replay an older revision.
|
|
62
|
+
const active = job?.state === 'ACTIVE' && task?.state === 'RUNNING' &&
|
|
63
|
+
task.executionId === delivery.executionId && eventOnlyReviewEligible(delivery);
|
|
64
|
+
const seen = db.prepare('SELECT 1 FROM host_invocation_decision WHERE job_id=? AND task_id=? AND execution_id=? AND revision=?')
|
|
65
|
+
.get(delivery.jobId, delivery.taskId, delivery.executionId, delivery.revision);
|
|
66
|
+
const eventOnly = active && !seen && (!invocation ||
|
|
67
|
+
(invocation.status === 'changes_requested' && invocation.executionId === delivery.executionId &&
|
|
68
|
+
invocation.revision !== delivery.revision));
|
|
69
|
+
if (!job || !task || job.state !== 'ACTIVE' || (!bound && !eventOnly)) {
|
|
57
70
|
recordHostInvocationEvent(db, delivery, 'stale', fingerprint);
|
|
58
71
|
db.exec('COMMIT');
|
|
59
72
|
return { outcome: 'stale', reason: 'invocation_or_revision_mismatch' };
|
|
@@ -65,7 +78,8 @@ export function recordHostInvocationDecision(db, delivery, fingerprint, writeSna
|
|
|
65
78
|
const decidedInvocation = {
|
|
66
79
|
invocationId: delivery.invocationId, revision: delivery.revision, executionId: delivery.executionId,
|
|
67
80
|
status: delivery.decision === 'approved' ? 'approved' : 'changes_requested',
|
|
68
|
-
boundAt: invocation.boundAt
|
|
81
|
+
boundAt: bound ? invocation.boundAt : delivery.deliveredAt, decidedAt: delivery.deliveredAt,
|
|
82
|
+
feedback: delivery.feedback, comments: delivery.comments, idempotencyKey: delivery.idempotencyKey,
|
|
69
83
|
};
|
|
70
84
|
task.interactiveInvocation = decidedInvocation;
|
|
71
85
|
const candidate = Date.parse(delivery.deliveredAt);
|
|
@@ -9,6 +9,8 @@ export const interactiveInvocationGraph = new GraphRuntime(graphSource, {
|
|
|
9
9
|
currentInvocation: facts => facts.durableFacts.currentInvocation === true,
|
|
10
10
|
awaitingDecision: facts => facts.durableFacts.awaitingDecision === true,
|
|
11
11
|
currentRevision: facts => facts.durableFacts.currentRevision === true,
|
|
12
|
+
eventOnlyCurrentExecution: facts => facts.durableFacts.eventOnlyCurrentExecution === true,
|
|
13
|
+
eventOnlyNextRevision: facts => facts.durableFacts.eventOnlyNextRevision === true,
|
|
12
14
|
duplicateDelivery: facts => facts.durableFacts.duplicateDelivery === true,
|
|
13
15
|
changesRequested: facts => facts.durableFacts.changesRequested === true,
|
|
14
16
|
},
|
|
@@ -50,10 +52,26 @@ export function normalizeInteractiveDecision(event) {
|
|
|
50
52
|
const decision = value.decision === 'approved' || value.decision === 'changes_requested' ? value.decision : null;
|
|
51
53
|
if (!jobId || !taskId || !executionId || !invocationId || !revision || !decision)
|
|
52
54
|
return null;
|
|
53
|
-
|
|
55
|
+
if (event.source?.id !== `job/${jobId}/task/${taskId}/execution/${executionId}`)
|
|
56
|
+
return null;
|
|
57
|
+
if (value.contentHash !== undefined && typeof value.feedback !== 'string')
|
|
58
|
+
return null;
|
|
59
|
+
const feedback = typeof value.feedback === 'string' ? value.feedback : null;
|
|
60
|
+
const contentHash = string('contentHash');
|
|
61
|
+
if (contentHash && contentHash !== revision)
|
|
62
|
+
return null;
|
|
63
|
+
const comments = value.comments;
|
|
64
|
+
if (comments !== undefined && (!Array.isArray(comments) || comments.length > 100 ||
|
|
65
|
+
comments.some(comment => !comment || typeof comment !== 'object' || Array.isArray(comment) ||
|
|
66
|
+
typeof comment.text !== 'string')))
|
|
67
|
+
return null;
|
|
54
68
|
return {
|
|
55
69
|
jobId, taskId, executionId, invocationId, revision, decision,
|
|
56
70
|
feedback: feedback ?? undefined,
|
|
71
|
+
contentHash: contentHash ?? undefined, revisionId: string('revisionId') ?? undefined,
|
|
72
|
+
previewId: string('previewId') ?? undefined, requestId: string('requestId') ?? undefined,
|
|
73
|
+
idempotencyKey: string('idempotencyKey') ?? undefined,
|
|
74
|
+
comments: comments,
|
|
57
75
|
eventId: event.event_id,
|
|
58
76
|
deliveredAt: event.timestamp,
|
|
59
77
|
};
|
|
@@ -67,12 +85,20 @@ export function interactiveDecisionFingerprint(decision) {
|
|
|
67
85
|
revision: decision.revision,
|
|
68
86
|
decision: decision.decision,
|
|
69
87
|
feedback: decision.feedback ?? null,
|
|
88
|
+
comments: decision.comments ?? null,
|
|
70
89
|
})).digest('hex');
|
|
71
90
|
}
|
|
91
|
+
/** First event for an unbound interaction must carry immutable video identity. */
|
|
92
|
+
export function eventOnlyReviewEligible(delivery) {
|
|
93
|
+
return Boolean(delivery.contentHash && /^[a-f0-9]{64}$/.test(delivery.contentHash) &&
|
|
94
|
+
delivery.revision === delivery.contentHash && delivery.feedback !== undefined &&
|
|
95
|
+
[delivery.revisionId, delivery.requestId, delivery.idempotencyKey, delivery.invocationId]
|
|
96
|
+
.every(value => typeof value === 'string' && value.length > 0 && value.length <= 128));
|
|
97
|
+
}
|
|
72
98
|
function invocationState(invocation) {
|
|
73
99
|
return invocation?.status ?? 'awaiting_decision';
|
|
74
100
|
}
|
|
75
|
-
async function decideInteractiveInvocation(task, delivery, duplicateDelivery) {
|
|
101
|
+
async function decideInteractiveInvocation(task, delivery, duplicateDelivery, jobActive) {
|
|
76
102
|
const invocation = task.interactiveInvocation;
|
|
77
103
|
const result = await dispatchWorkflowGraph(interactiveInvocationGraph, {
|
|
78
104
|
initialState: invocationState(invocation),
|
|
@@ -81,6 +107,12 @@ async function decideInteractiveInvocation(task, delivery, duplicateDelivery) {
|
|
|
81
107
|
currentInvocation: invocation?.invocationId === delivery.invocationId,
|
|
82
108
|
awaitingDecision: invocation?.status === 'awaiting_decision',
|
|
83
109
|
currentRevision: invocation?.revision === delivery.revision,
|
|
110
|
+
eventOnlyCurrentExecution: jobActive && !invocation && task.state === 'RUNNING' &&
|
|
111
|
+
task.executionId === delivery.executionId && eventOnlyReviewEligible(delivery),
|
|
112
|
+
eventOnlyNextRevision: jobActive && invocation?.status === 'changes_requested' &&
|
|
113
|
+
invocation.executionId === delivery.executionId && task.state === 'RUNNING' &&
|
|
114
|
+
task.executionId === delivery.executionId && invocation.revision !== delivery.revision &&
|
|
115
|
+
eventOnlyReviewEligible(delivery),
|
|
84
116
|
duplicateDelivery,
|
|
85
117
|
changesRequested: delivery.decision === 'changes_requested',
|
|
86
118
|
},
|
|
@@ -166,13 +198,13 @@ export class HostInteractiveInvocationCoordinator {
|
|
|
166
198
|
}
|
|
167
199
|
const job = await this.options.store.loadJob(delivery.jobId);
|
|
168
200
|
const task = job?.tasks.find((item) => item.id === delivery.taskId);
|
|
169
|
-
if (!job || !task ||
|
|
201
|
+
if (!job || !task ||
|
|
170
202
|
(task.executionId !== delivery.executionId && task.state !== 'DRAFT')) {
|
|
171
203
|
await this.options.store.recordHostInvocationEvent?.(delivery, 'stale', interactiveDecisionFingerprint(delivery));
|
|
172
204
|
return { outcome: 'stale', reason: 'execution_not_bound' };
|
|
173
205
|
}
|
|
174
206
|
const duplicate = await this.options.store.hasHostInvocationDecision?.(delivery.jobId, delivery.taskId, delivery.invocationId, interactiveDecisionFingerprint(delivery)) ?? false;
|
|
175
|
-
const graphDecision = await decideInteractiveInvocation(task, delivery, duplicate);
|
|
207
|
+
const graphDecision = await decideInteractiveInvocation(task, delivery, duplicate, job.state === 'ACTIVE');
|
|
176
208
|
const selected = graphDecision.actions.some(action => action === 'interactive.requestChanges' || action === 'interactive.approve');
|
|
177
209
|
if (!graphDecision.accepted || !selected || duplicate) {
|
|
178
210
|
const outcome = duplicate ? 'duplicate' : 'stale';
|
|
@@ -187,7 +219,7 @@ export class HostInteractiveInvocationCoordinator {
|
|
|
187
219
|
const accepted = {
|
|
188
220
|
jobId: delivery.jobId, taskId: delivery.taskId, executionId: delivery.executionId,
|
|
189
221
|
invocationId: delivery.invocationId, revision: delivery.revision, decision: delivery.decision,
|
|
190
|
-
feedback: delivery.feedback, event,
|
|
222
|
+
feedback: delivery.feedback, comments: delivery.comments, idempotencyKey: delivery.idempotencyKey, event,
|
|
191
223
|
};
|
|
192
224
|
const key = `${accepted.jobId}:${accepted.taskId}:${accepted.executionId}:${accepted.invocationId}`;
|
|
193
225
|
const waiter = this.waiters.get(key);
|