opencastle 0.27.0 → 0.27.2
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/bin/cli.mjs +6 -0
- package/dist/cli/agents.d.ts +3 -0
- package/dist/cli/agents.d.ts.map +1 -0
- package/dist/cli/agents.js +161 -0
- package/dist/cli/agents.js.map +1 -0
- package/dist/cli/baselines.d.ts +3 -0
- package/dist/cli/baselines.d.ts.map +1 -0
- package/dist/cli/baselines.js +128 -0
- package/dist/cli/baselines.js.map +1 -0
- package/dist/cli/convoy/dashboard-types.d.ts +146 -0
- package/dist/cli/convoy/dashboard-types.d.ts.map +1 -0
- package/dist/cli/convoy/dashboard-types.js +2 -0
- package/dist/cli/convoy/dashboard-types.js.map +1 -0
- package/dist/cli/convoy/engine.d.ts +67 -2
- package/dist/cli/convoy/engine.d.ts.map +1 -1
- package/dist/cli/convoy/engine.js +2036 -28
- package/dist/cli/convoy/engine.js.map +1 -1
- package/dist/cli/convoy/engine.test.js +1659 -70
- package/dist/cli/convoy/engine.test.js.map +1 -1
- package/dist/cli/convoy/event-schemas.d.ts +9 -0
- package/dist/cli/convoy/event-schemas.d.ts.map +1 -0
- package/dist/cli/convoy/event-schemas.js +185 -0
- package/dist/cli/convoy/event-schemas.js.map +1 -0
- package/dist/cli/convoy/events.d.ts +12 -1
- package/dist/cli/convoy/events.d.ts.map +1 -1
- package/dist/cli/convoy/events.js +186 -13
- package/dist/cli/convoy/events.js.map +1 -1
- package/dist/cli/convoy/events.test.js +325 -28
- package/dist/cli/convoy/events.test.js.map +1 -1
- package/dist/cli/convoy/expertise.d.ts +16 -0
- package/dist/cli/convoy/expertise.d.ts.map +1 -0
- package/dist/cli/convoy/expertise.js +121 -0
- package/dist/cli/convoy/expertise.js.map +1 -0
- package/dist/cli/convoy/expertise.test.d.ts +2 -0
- package/dist/cli/convoy/expertise.test.d.ts.map +1 -0
- package/dist/cli/convoy/expertise.test.js +96 -0
- package/dist/cli/convoy/expertise.test.js.map +1 -0
- package/dist/cli/convoy/export.test.js +1 -0
- package/dist/cli/convoy/export.test.js.map +1 -1
- package/dist/cli/convoy/formula.d.ts +19 -0
- package/dist/cli/convoy/formula.d.ts.map +1 -0
- package/dist/cli/convoy/formula.js +142 -0
- package/dist/cli/convoy/formula.js.map +1 -0
- package/dist/cli/convoy/formula.test.d.ts +2 -0
- package/dist/cli/convoy/formula.test.d.ts.map +1 -0
- package/dist/cli/convoy/formula.test.js +342 -0
- package/dist/cli/convoy/formula.test.js.map +1 -0
- package/dist/cli/convoy/gates.d.ts +128 -0
- package/dist/cli/convoy/gates.d.ts.map +1 -0
- package/dist/cli/convoy/gates.js +606 -0
- package/dist/cli/convoy/gates.js.map +1 -0
- package/dist/cli/convoy/gates.test.d.ts +2 -0
- package/dist/cli/convoy/gates.test.d.ts.map +1 -0
- package/dist/cli/convoy/gates.test.js +976 -0
- package/dist/cli/convoy/gates.test.js.map +1 -0
- package/dist/cli/convoy/health.d.ts +11 -0
- package/dist/cli/convoy/health.d.ts.map +1 -1
- package/dist/cli/convoy/health.js +54 -0
- package/dist/cli/convoy/health.js.map +1 -1
- package/dist/cli/convoy/health.test.js +56 -1
- package/dist/cli/convoy/health.test.js.map +1 -1
- package/dist/cli/convoy/issues.d.ts +8 -0
- package/dist/cli/convoy/issues.d.ts.map +1 -0
- package/dist/cli/convoy/issues.js +98 -0
- package/dist/cli/convoy/issues.js.map +1 -0
- package/dist/cli/convoy/issues.test.d.ts +2 -0
- package/dist/cli/convoy/issues.test.d.ts.map +1 -0
- package/dist/cli/convoy/issues.test.js +107 -0
- package/dist/cli/convoy/issues.test.js.map +1 -0
- package/dist/cli/convoy/knowledge.d.ts +5 -0
- package/dist/cli/convoy/knowledge.d.ts.map +1 -0
- package/dist/cli/convoy/knowledge.js +116 -0
- package/dist/cli/convoy/knowledge.js.map +1 -0
- package/dist/cli/convoy/knowledge.test.d.ts +2 -0
- package/dist/cli/convoy/knowledge.test.d.ts.map +1 -0
- package/dist/cli/convoy/knowledge.test.js +87 -0
- package/dist/cli/convoy/knowledge.test.js.map +1 -0
- package/dist/cli/convoy/lessons.d.ts +17 -0
- package/dist/cli/convoy/lessons.d.ts.map +1 -0
- package/dist/cli/convoy/lessons.js +149 -0
- package/dist/cli/convoy/lessons.js.map +1 -0
- package/dist/cli/convoy/lessons.test.d.ts +2 -0
- package/dist/cli/convoy/lessons.test.d.ts.map +1 -0
- package/dist/cli/convoy/lessons.test.js +135 -0
- package/dist/cli/convoy/lessons.test.js.map +1 -0
- package/dist/cli/convoy/lock.d.ts +13 -0
- package/dist/cli/convoy/lock.d.ts.map +1 -0
- package/dist/cli/convoy/lock.js +88 -0
- package/dist/cli/convoy/lock.js.map +1 -0
- package/dist/cli/convoy/lock.test.d.ts +2 -0
- package/dist/cli/convoy/lock.test.d.ts.map +1 -0
- package/dist/cli/convoy/lock.test.js +136 -0
- package/dist/cli/convoy/lock.test.js.map +1 -0
- package/dist/cli/convoy/log-merge.test.d.ts +2 -0
- package/dist/cli/convoy/log-merge.test.d.ts.map +1 -0
- package/dist/cli/convoy/log-merge.test.js +147 -0
- package/dist/cli/convoy/log-merge.test.js.map +1 -0
- package/dist/cli/convoy/merge.d.ts +4 -0
- package/dist/cli/convoy/merge.d.ts.map +1 -1
- package/dist/cli/convoy/merge.js +18 -1
- package/dist/cli/convoy/merge.js.map +1 -1
- package/dist/cli/convoy/merge.test.js +6 -7
- package/dist/cli/convoy/merge.test.js.map +1 -1
- package/dist/cli/convoy/partition.d.ts +51 -0
- package/dist/cli/convoy/partition.d.ts.map +1 -0
- package/dist/cli/convoy/partition.js +186 -0
- package/dist/cli/convoy/partition.js.map +1 -0
- package/dist/cli/convoy/partition.test.d.ts +2 -0
- package/dist/cli/convoy/partition.test.d.ts.map +1 -0
- package/dist/cli/convoy/partition.test.js +315 -0
- package/dist/cli/convoy/partition.test.js.map +1 -0
- package/dist/cli/convoy/pipeline.test.js +6 -0
- package/dist/cli/convoy/pipeline.test.js.map +1 -1
- package/dist/cli/convoy/store.d.ts +99 -7
- package/dist/cli/convoy/store.d.ts.map +1 -1
- package/dist/cli/convoy/store.js +764 -31
- package/dist/cli/convoy/store.js.map +1 -1
- package/dist/cli/convoy/store.test.js +1810 -18
- package/dist/cli/convoy/store.test.js.map +1 -1
- package/dist/cli/convoy/types.d.ts +427 -5
- package/dist/cli/convoy/types.d.ts.map +1 -1
- package/dist/cli/convoy/types.js +42 -1
- package/dist/cli/convoy/types.js.map +1 -1
- package/dist/cli/log.d.ts +11 -0
- package/dist/cli/log.d.ts.map +1 -1
- package/dist/cli/log.js +114 -2
- package/dist/cli/log.js.map +1 -1
- package/dist/cli/run/adapters/claude.d.ts +2 -0
- package/dist/cli/run/adapters/claude.d.ts.map +1 -1
- package/dist/cli/run/adapters/claude.js +89 -49
- package/dist/cli/run/adapters/claude.js.map +1 -1
- package/dist/cli/run/adapters/claude.test.d.ts +2 -0
- package/dist/cli/run/adapters/claude.test.d.ts.map +1 -0
- package/dist/cli/run/adapters/claude.test.js +205 -0
- package/dist/cli/run/adapters/claude.test.js.map +1 -0
- package/dist/cli/run/adapters/copilot.d.ts +1 -0
- package/dist/cli/run/adapters/copilot.d.ts.map +1 -1
- package/dist/cli/run/adapters/copilot.js +84 -46
- package/dist/cli/run/adapters/copilot.js.map +1 -1
- package/dist/cli/run/adapters/copilot.test.d.ts +2 -0
- package/dist/cli/run/adapters/copilot.test.d.ts.map +1 -0
- package/dist/cli/run/adapters/copilot.test.js +195 -0
- package/dist/cli/run/adapters/copilot.test.js.map +1 -0
- package/dist/cli/run/adapters/cursor.d.ts +1 -0
- package/dist/cli/run/adapters/cursor.d.ts.map +1 -1
- package/dist/cli/run/adapters/cursor.js +83 -47
- package/dist/cli/run/adapters/cursor.js.map +1 -1
- package/dist/cli/run/adapters/cursor.test.d.ts +2 -0
- package/dist/cli/run/adapters/cursor.test.d.ts.map +1 -0
- package/dist/cli/run/adapters/cursor.test.js +129 -0
- package/dist/cli/run/adapters/cursor.test.js.map +1 -0
- package/dist/cli/run/adapters/opencode.d.ts +1 -0
- package/dist/cli/run/adapters/opencode.d.ts.map +1 -1
- package/dist/cli/run/adapters/opencode.js +81 -47
- package/dist/cli/run/adapters/opencode.js.map +1 -1
- package/dist/cli/run/adapters/opencode.test.d.ts +2 -0
- package/dist/cli/run/adapters/opencode.test.d.ts.map +1 -0
- package/dist/cli/run/adapters/opencode.test.js +119 -0
- package/dist/cli/run/adapters/opencode.test.js.map +1 -0
- package/dist/cli/run/executor.js +1 -1
- package/dist/cli/run/executor.js.map +1 -1
- package/dist/cli/run/schema.d.ts.map +1 -1
- package/dist/cli/run/schema.js +245 -4
- package/dist/cli/run/schema.js.map +1 -1
- package/dist/cli/run/schema.test.js +669 -0
- package/dist/cli/run/schema.test.js.map +1 -1
- package/dist/cli/run.d.ts.map +1 -1
- package/dist/cli/run.js +362 -22
- package/dist/cli/run.js.map +1 -1
- package/dist/cli/types.d.ts +85 -2
- package/dist/cli/types.d.ts.map +1 -1
- package/dist/cli/types.js.map +1 -1
- package/dist/cli/watch.d.ts +15 -0
- package/dist/cli/watch.d.ts.map +1 -0
- package/dist/cli/watch.js +279 -0
- package/dist/cli/watch.js.map +1 -0
- package/package.json +5 -1
- package/src/cli/agents.ts +177 -0
- package/src/cli/baselines.ts +143 -0
- package/src/cli/convoy/TELEMETRY.md +203 -0
- package/src/cli/convoy/dashboard-types.ts +141 -0
- package/src/cli/convoy/engine.test.ts +1937 -70
- package/src/cli/convoy/engine.ts +2350 -40
- package/src/cli/convoy/event-schemas.ts +195 -0
- package/src/cli/convoy/events.test.ts +384 -39
- package/src/cli/convoy/events.ts +202 -16
- package/src/cli/convoy/expertise.test.ts +128 -0
- package/src/cli/convoy/expertise.ts +163 -0
- package/src/cli/convoy/export.test.ts +1 -0
- package/src/cli/convoy/formula.test.ts +405 -0
- package/src/cli/convoy/formula.ts +174 -0
- package/src/cli/convoy/gates.test.ts +1169 -0
- package/src/cli/convoy/gates.ts +774 -0
- package/src/cli/convoy/health.test.ts +64 -2
- package/src/cli/convoy/health.ts +80 -2
- package/src/cli/convoy/issues.test.ts +143 -0
- package/src/cli/convoy/issues.ts +136 -0
- package/src/cli/convoy/knowledge.test.ts +101 -0
- package/src/cli/convoy/knowledge.ts +132 -0
- package/src/cli/convoy/lessons.test.ts +188 -0
- package/src/cli/convoy/lessons.ts +164 -0
- package/src/cli/convoy/lock.test.ts +181 -0
- package/src/cli/convoy/lock.ts +103 -0
- package/src/cli/convoy/log-merge.test.ts +179 -0
- package/src/cli/convoy/merge.test.ts +6 -7
- package/src/cli/convoy/merge.ts +19 -1
- package/src/cli/convoy/partition.test.ts +423 -0
- package/src/cli/convoy/partition.ts +232 -0
- package/src/cli/convoy/pipeline.test.ts +6 -0
- package/src/cli/convoy/store.test.ts +2041 -20
- package/src/cli/convoy/store.ts +945 -46
- package/src/cli/convoy/types.ts +278 -4
- package/src/cli/log.ts +120 -2
- package/src/cli/run/adapters/claude.test.ts +234 -0
- package/src/cli/run/adapters/claude.ts +45 -5
- package/src/cli/run/adapters/copilot.test.ts +224 -0
- package/src/cli/run/adapters/copilot.ts +34 -4
- package/src/cli/run/adapters/cursor.test.ts +144 -0
- package/src/cli/run/adapters/cursor.ts +33 -2
- package/src/cli/run/adapters/opencode.test.ts +135 -0
- package/src/cli/run/adapters/opencode.ts +30 -2
- package/src/cli/run/executor.ts +1 -1
- package/src/cli/run/schema.test.ts +758 -0
- package/src/cli/run/schema.ts +300 -25
- package/src/cli/run.ts +341 -21
- package/src/cli/types.ts +86 -1
- package/src/cli/watch.ts +298 -0
- package/src/dashboard/dist/_astro/{index.DtnyD8a5.css → index.6L3_HsPT.css} +1 -1
- package/src/dashboard/dist/data/.gitkeep +0 -0
- package/src/dashboard/dist/data/convoy-list.json +1 -0
- package/src/dashboard/dist/data/overall-stats.json +24 -0
- package/src/dashboard/dist/index.html +701 -3
- package/src/dashboard/node_modules/.vite/deps/_metadata.json +6 -6
- package/src/dashboard/public/data/.gitkeep +0 -0
- package/src/dashboard/public/data/convoy-list.json +1 -0
- package/src/dashboard/public/data/overall-stats.json +24 -0
- package/src/dashboard/scripts/etl.test.ts +210 -0
- package/src/dashboard/scripts/etl.ts +108 -0
- package/src/dashboard/scripts/integration-test.ts +504 -0
- package/src/dashboard/src/pages/index.astro +854 -15
- package/src/dashboard/src/styles/dashboard.css +557 -1
- package/src/orchestrator/prompts/generate-convoy.prompt.md +212 -13
|
@@ -1,20 +1,248 @@
|
|
|
1
1
|
import { execFile as execFileCb } from 'node:child_process';
|
|
2
2
|
import { createHash } from 'node:crypto';
|
|
3
|
-
import { mkdirSync } from 'node:fs';
|
|
3
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, } from 'node:fs';
|
|
4
4
|
import { dirname, join, resolve } from 'node:path';
|
|
5
|
+
import { DatabaseSync } from 'node:sqlite';
|
|
5
6
|
import { promisify } from 'node:util';
|
|
6
|
-
import { createConvoyStore } from './store.js';
|
|
7
|
-
import {
|
|
7
|
+
import { createConvoyStore, ConvoyArtifactLimitError } from './store.js';
|
|
8
|
+
import { acquireEngineLock } from './lock.js';
|
|
9
|
+
import { createEventEmitter, ndjsonPathForConvoy, recoverNdjson } from './events.js';
|
|
8
10
|
import { createWorktreeManager } from './worktree.js';
|
|
9
|
-
import { createMergeQueue } from './merge.js';
|
|
10
|
-
import { createHealthMonitor } from './health.js';
|
|
11
|
+
import { createMergeQueue, MergeConflictError } from './merge.js';
|
|
12
|
+
import { createHealthMonitor, detectDrift } from './health.js';
|
|
11
13
|
import { exportConvoyToNdjson } from './export.js';
|
|
12
14
|
import { buildPhases, formatDuration } from '../run/executor.js';
|
|
13
|
-
import { parseTimeout } from '../run/schema.js';
|
|
15
|
+
import { parseTimeout, parseYaml } from '../run/schema.js';
|
|
14
16
|
import { getAdapter, detectAdapter } from '../run/adapters/index.js';
|
|
15
17
|
import { c } from '../prompt.js';
|
|
18
|
+
import { validateFilePartitions, scanSymlinks, scanNewSymlinks, normalizePath, pathsOverlap } from './partition.js';
|
|
19
|
+
import { scanForSecrets, runSecretScanGate, runBlastRadiusGate, browserTestGate } from './gates.js';
|
|
20
|
+
import { readLessons, captureLessons, consolidateLessons } from './lessons.js';
|
|
21
|
+
import { updateExpertise, feedCircuitBreaker } from './expertise.js';
|
|
22
|
+
import { buildKnowledgeGraph } from './knowledge.js';
|
|
23
|
+
import { injectDiscoveredIssuesInstruction, checkDiscoveredIssues, consolidateIssues } from './issues.js';
|
|
16
24
|
const execFile = promisify(execFileCb);
|
|
17
|
-
|
|
25
|
+
export class CircuitBreakerManager {
|
|
26
|
+
states = new Map();
|
|
27
|
+
threshold;
|
|
28
|
+
cooldownMs;
|
|
29
|
+
fallbackAgent;
|
|
30
|
+
constructor(config, initialState) {
|
|
31
|
+
this.threshold = config?.threshold ?? 3;
|
|
32
|
+
this.cooldownMs = config?.cooldown_ms ?? 300_000;
|
|
33
|
+
this.fallbackAgent = config?.fallback_agent ?? null;
|
|
34
|
+
if (initialState) {
|
|
35
|
+
for (const [agent, state] of Object.entries(initialState)) {
|
|
36
|
+
this.states.set(agent, state);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
getState(agent) {
|
|
41
|
+
return this.states.get(agent) ?? { status: 'closed', failures: 0, last_failure_at: null, opened_at: null };
|
|
42
|
+
}
|
|
43
|
+
recordFailure(agent) {
|
|
44
|
+
const state = this.getState(agent);
|
|
45
|
+
const now = new Date().toISOString();
|
|
46
|
+
if (state.status === 'half-open') {
|
|
47
|
+
// Probe failed — back to open, reset cooldown
|
|
48
|
+
state.status = 'open';
|
|
49
|
+
state.opened_at = now;
|
|
50
|
+
state.last_failure_at = now;
|
|
51
|
+
this.states.set(agent, state);
|
|
52
|
+
return { tripped: true, state };
|
|
53
|
+
}
|
|
54
|
+
state.failures += 1;
|
|
55
|
+
state.last_failure_at = now;
|
|
56
|
+
if (state.failures >= this.threshold) {
|
|
57
|
+
state.status = 'open';
|
|
58
|
+
state.opened_at = now;
|
|
59
|
+
this.states.set(agent, state);
|
|
60
|
+
return { tripped: true, state };
|
|
61
|
+
}
|
|
62
|
+
this.states.set(agent, state);
|
|
63
|
+
return { tripped: false, state };
|
|
64
|
+
}
|
|
65
|
+
recordSuccess(agent) {
|
|
66
|
+
const state = this.getState(agent);
|
|
67
|
+
if (state.status === 'half-open') {
|
|
68
|
+
// Probe succeeded — close circuit
|
|
69
|
+
state.status = 'closed';
|
|
70
|
+
state.failures = 0;
|
|
71
|
+
state.opened_at = null;
|
|
72
|
+
}
|
|
73
|
+
else if (state.status === 'closed') {
|
|
74
|
+
state.failures = 0;
|
|
75
|
+
}
|
|
76
|
+
this.states.set(agent, state);
|
|
77
|
+
return state;
|
|
78
|
+
}
|
|
79
|
+
canAssign(agent) {
|
|
80
|
+
const state = this.getState(agent);
|
|
81
|
+
if (state.status === 'closed')
|
|
82
|
+
return true;
|
|
83
|
+
if (state.status === 'half-open')
|
|
84
|
+
return true; // allow 1 probe
|
|
85
|
+
// Open — check cooldown
|
|
86
|
+
if (state.opened_at) {
|
|
87
|
+
const elapsed = Date.now() - new Date(state.opened_at).getTime();
|
|
88
|
+
if (elapsed >= this.cooldownMs) {
|
|
89
|
+
state.status = 'half-open';
|
|
90
|
+
this.states.set(agent, state);
|
|
91
|
+
return true;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return false;
|
|
95
|
+
}
|
|
96
|
+
get fallback() {
|
|
97
|
+
return this.fallbackAgent;
|
|
98
|
+
}
|
|
99
|
+
serialize() {
|
|
100
|
+
return JSON.stringify(Object.fromEntries(this.states));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
// ── Branch management ───────────────────────────────────────────────────────
|
|
104
|
+
/**
|
|
105
|
+
* Ensure the given branch exists and is checked out.
|
|
106
|
+
* Creates the branch from HEAD if it does not yet exist.
|
|
107
|
+
* Fails fast if there are uncommitted changes.
|
|
108
|
+
*/
|
|
109
|
+
export async function ensureBranch(branchName, basePath) {
|
|
110
|
+
// Validate refspec — reject shell metacharacters
|
|
111
|
+
if (!/^[a-zA-Z0-9\-/_\.]+$/.test(branchName)) {
|
|
112
|
+
throw new Error(`Invalid branch name "${branchName}": only alphanumeric, -, /, _, and . are allowed`);
|
|
113
|
+
}
|
|
114
|
+
// Refuse to switch branches with uncommitted changes
|
|
115
|
+
const { stdout: statusOut } = await execFile('git', ['status', '--porcelain'], {
|
|
116
|
+
cwd: basePath,
|
|
117
|
+
});
|
|
118
|
+
if (statusOut.trim()) {
|
|
119
|
+
throw new Error(`Uncommitted changes detected in "${basePath}". Commit or stash before switching branches.`);
|
|
120
|
+
}
|
|
121
|
+
// Check if branch already exists
|
|
122
|
+
try {
|
|
123
|
+
await execFile('git', ['rev-parse', '--verify', branchName], { cwd: basePath });
|
|
124
|
+
// Branch exists — check it out
|
|
125
|
+
await execFile('git', ['checkout', branchName], { cwd: basePath });
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
// Branch does not exist — create from current HEAD
|
|
129
|
+
await execFile('git', ['checkout', '-b', branchName], { cwd: basePath });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
export function runConvoyGuard(store, convoyId, _wtManager, ndjsonPath, guardConfig) {
|
|
133
|
+
// If guard is explicitly disabled, skip all checks
|
|
134
|
+
if (guardConfig?.enabled === false) {
|
|
135
|
+
return { passed: true, warnings: [] };
|
|
136
|
+
}
|
|
137
|
+
const warnings = [];
|
|
138
|
+
const tasks = store.getTasksByConvoy(convoyId);
|
|
139
|
+
// Check 1: All task statuses are terminal
|
|
140
|
+
const terminalStatuses = new Set(['done', 'failed', 'skipped', 'timed-out', 'gate-failed', 'review-blocked', 'hook-failed', 'disputed']);
|
|
141
|
+
const nonTerminal = tasks.filter(t => !terminalStatuses.has(t.status));
|
|
142
|
+
if (nonTerminal.length > 0) {
|
|
143
|
+
warnings.push(`Non-terminal tasks: ${nonTerminal.map(t => `${t.id}(${t.status})`).join(', ')}`);
|
|
144
|
+
}
|
|
145
|
+
// Check 2: NDJSON file exists and record count >= completed task count
|
|
146
|
+
const completedTasks = tasks.filter(t => t.status === 'done');
|
|
147
|
+
try {
|
|
148
|
+
const content = readFileSync(ndjsonPath, 'utf8');
|
|
149
|
+
const lines = content.split('\n').filter(l => l.trim());
|
|
150
|
+
// Per-convoy file — all records belong to this convoy, no need to filter by convoy_id
|
|
151
|
+
if (lines.length < completedTasks.length) {
|
|
152
|
+
warnings.push(`NDJSON record count (${lines.length}) < completed tasks (${completedTasks.length})`);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
if (completedTasks.length > 0) {
|
|
157
|
+
warnings.push(`NDJSON file not found at ${ndjsonPath} but ${completedTasks.length} tasks completed`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// Check 3: Every retried task has events for each attempt
|
|
161
|
+
const retriedTasks = tasks.filter(t => t.retries > 0);
|
|
162
|
+
const events = store.getEvents(convoyId);
|
|
163
|
+
for (const task of retriedTasks) {
|
|
164
|
+
const taskEvents = events.filter(e => e.task_id === task.id && e.type === 'task_started');
|
|
165
|
+
if (taskEvents.length < task.retries) {
|
|
166
|
+
warnings.push(`Task ${task.id} has ${task.retries} retries but only ${taskEvents.length} task_started events`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
// Check 4: Gate results recorded for all gates that ran
|
|
170
|
+
const gateEvents = events.filter(e => {
|
|
171
|
+
if (e.type === 'built_in_gate_result')
|
|
172
|
+
return true;
|
|
173
|
+
if (e.data == null)
|
|
174
|
+
return false;
|
|
175
|
+
try {
|
|
176
|
+
const parsed = JSON.parse(e.data);
|
|
177
|
+
return 'gate' in parsed;
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
const tasksWithGates = tasks.filter(t => t.gates);
|
|
184
|
+
if (tasksWithGates.length > 0 && gateEvents.length === 0) {
|
|
185
|
+
warnings.push('Tasks have gates configured but no gate result events found');
|
|
186
|
+
}
|
|
187
|
+
// Check 5: Token/cost totals computed
|
|
188
|
+
const convoy = store.getConvoy(convoyId);
|
|
189
|
+
if (convoy && convoy.total_tokens == null) {
|
|
190
|
+
const totalTokens = tasks.reduce((sum, t) => sum + (t.total_tokens ?? 0), 0);
|
|
191
|
+
if (totalTokens > 0) {
|
|
192
|
+
warnings.push('Convoy total_tokens not persisted despite tasks having token data');
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
// Check 6: No orphaned worktrees — engine already calls removeAll() during cleanup.
|
|
196
|
+
// Synchronous check is not possible; the engine handles this.
|
|
197
|
+
return { passed: warnings.length === 0, warnings };
|
|
198
|
+
}
|
|
199
|
+
export function evaluateReviewLevel(task, diff, heuristics, allGatesPassed) {
|
|
200
|
+
const panelPaths = heuristics?.panel_paths ?? ['auth/', 'security/', 'migrations/', 'rls/'];
|
|
201
|
+
const panelAgents = heuristics?.panel_agents ?? ['security-expert', 'database-engineer'];
|
|
202
|
+
const autoPassAgents = heuristics?.auto_pass_agents ?? ['documentation-writer', 'copywriter'];
|
|
203
|
+
const autoPassMaxLines = heuristics?.auto_pass_max_lines ?? 10;
|
|
204
|
+
const autoPassMaxFiles = heuristics?.auto_pass_max_files ?? 2;
|
|
205
|
+
// Panel: sensitive paths or agents
|
|
206
|
+
if (panelPaths.some(p => diff.filePaths.some(fp => fp.startsWith(p) || fp.includes('/' + p))))
|
|
207
|
+
return 'panel';
|
|
208
|
+
if (panelAgents.includes(task.agent))
|
|
209
|
+
return 'panel';
|
|
210
|
+
// Auto-pass: documentation/copy agents
|
|
211
|
+
if (autoPassAgents.includes(task.agent))
|
|
212
|
+
return 'auto-pass';
|
|
213
|
+
// Auto-pass: small diffs with all gates passing
|
|
214
|
+
if (diff.linesChanged <= autoPassMaxLines && diff.filesChanged <= autoPassMaxFiles && allGatesPassed !== false)
|
|
215
|
+
return 'auto-pass';
|
|
216
|
+
// Large diffs → fast review
|
|
217
|
+
if (diff.linesChanged > 200 || diff.filesChanged > 5)
|
|
218
|
+
return 'fast';
|
|
219
|
+
// Default → fast review
|
|
220
|
+
return 'fast';
|
|
221
|
+
}
|
|
222
|
+
class ReviewSemaphore {
|
|
223
|
+
max;
|
|
224
|
+
current = 0;
|
|
225
|
+
queue = [];
|
|
226
|
+
constructor(max) {
|
|
227
|
+
this.max = max;
|
|
228
|
+
}
|
|
229
|
+
async acquire() {
|
|
230
|
+
if (this.current < this.max) {
|
|
231
|
+
this.current++;
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
return new Promise(resolve => {
|
|
235
|
+
this.queue.push(() => { this.current++; resolve(); });
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
release() {
|
|
239
|
+
this.current--;
|
|
240
|
+
if (this.queue.length > 0) {
|
|
241
|
+
const next = this.queue.shift();
|
|
242
|
+
next();
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
18
246
|
function msToTimeout(ms) {
|
|
19
247
|
if (ms >= 3_600_000 && ms % 3_600_000 === 0)
|
|
20
248
|
return `${ms / 3_600_000}h`;
|
|
@@ -22,6 +250,58 @@ function msToTimeout(ms) {
|
|
|
22
250
|
return `${ms / 60_000}m`;
|
|
23
251
|
return `${ms / 1_000}s`;
|
|
24
252
|
}
|
|
253
|
+
// ── DLQ markdown dual-write ───────────────────────────────────────────────────
|
|
254
|
+
// Builds the DLQ markdown entry text (no I/O, no scanning).
|
|
255
|
+
function buildDlqMarkdownEntry(dlqId, task, failureType, errorOutput) {
|
|
256
|
+
const marker = `<!-- dlq:${dlqId} -->`;
|
|
257
|
+
const entry = `\n${marker}\n### ${dlqId}\n\n| Field | Value |\n|-------|-------|\n| Task | ${task.id} |\n| Agent | ${task.agent} |\n| Type | ${failureType} |\n| Attempts | ${task.retries + 1} |\n| Date | ${new Date().toISOString()} |\n\n**Error:**\n\`\`\`\n${(errorOutput ?? '(no output)').slice(0, 2000)}\n\`\`\`\n`;
|
|
258
|
+
return { marker, entry };
|
|
259
|
+
}
|
|
260
|
+
// Appends a pre-scanned DLQ entry to AGENT-FAILURES.md. The caller must have
|
|
261
|
+
// already verified the entry is clean via scanForSecrets — no re-scan here.
|
|
262
|
+
function appendDlqMarkdownClean(marker, entry) {
|
|
263
|
+
const mdPath = join(resolve(process.cwd()), '.opencastle', 'AGENT-FAILURES.md');
|
|
264
|
+
try {
|
|
265
|
+
const existing = readFileSync(mdPath, 'utf8');
|
|
266
|
+
if (existing.includes(marker))
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
catch {
|
|
270
|
+
// File doesn't exist yet — will create
|
|
271
|
+
}
|
|
272
|
+
mkdirSync(dirname(mdPath), { recursive: true });
|
|
273
|
+
appendFileSync(mdPath, entry);
|
|
274
|
+
}
|
|
275
|
+
function writeDisputeToMarkdown(disputeId, convoyId, task, panelResults, events) {
|
|
276
|
+
const mdPath = join(resolve(process.cwd()), 'DISPUTES.md');
|
|
277
|
+
const marker = `<!-- dispute:${disputeId} -->`;
|
|
278
|
+
try {
|
|
279
|
+
const existing = readFileSync(mdPath, 'utf8');
|
|
280
|
+
if (existing.includes(marker))
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
catch {
|
|
284
|
+
// File doesn't exist yet
|
|
285
|
+
}
|
|
286
|
+
const blockingReasons = panelResults
|
|
287
|
+
.filter(r => r.verdict === 'block')
|
|
288
|
+
.map(r => r.feedback)
|
|
289
|
+
.join('\n\n');
|
|
290
|
+
const entry = `\n${marker}\n## Dispute: ${task.id}\n\n| Field | Value |\n|-------|-------|\n| Convoy | ${convoyId} |\n| Task | ${task.id} |\n| Date | ${new Date().toISOString()} |\n| Panel attempts | ${task.panel_attempts + 1} |\n| Agent | ${task.agent} |\n| Status | Open |\n\n**Blocking reasons:**\n\n${blockingReasons}\n`;
|
|
291
|
+
const scanResult = scanForSecrets(entry, 'DISPUTES.md');
|
|
292
|
+
if (!scanResult.clean) {
|
|
293
|
+
if (events) {
|
|
294
|
+
events.emit('secret_leak_prevented', {
|
|
295
|
+
task_id: task.id,
|
|
296
|
+
findings_count: scanResult.findings.length,
|
|
297
|
+
patterns: scanResult.findings.map((f) => f.pattern),
|
|
298
|
+
context: 'dispute_markdown_write',
|
|
299
|
+
}, { convoy_id: convoyId, task_id: task.id });
|
|
300
|
+
}
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
303
|
+
appendFileSync(mdPath, entry);
|
|
304
|
+
}
|
|
25
305
|
function taskRecordToTask(record) {
|
|
26
306
|
return {
|
|
27
307
|
id: record.id,
|
|
@@ -34,6 +314,7 @@ function taskRecordToTask(record) {
|
|
|
34
314
|
model: record.model ?? undefined,
|
|
35
315
|
max_retries: record.max_retries,
|
|
36
316
|
adapter: record.adapter ?? undefined,
|
|
317
|
+
gates: record.gates ? JSON.parse(record.gates) : undefined,
|
|
37
318
|
};
|
|
38
319
|
}
|
|
39
320
|
function makeTimeoutPromise(ms) {
|
|
@@ -44,11 +325,322 @@ function makeTimeoutPromise(ms) {
|
|
|
44
325
|
return { promise, clear: () => { if (timerId !== undefined)
|
|
45
326
|
clearTimeout(timerId); } };
|
|
46
327
|
}
|
|
328
|
+
// ── Step condition evaluation ─────────────────────────────────────────────────
|
|
329
|
+
function evaluateStepCondition(condition, stepResults, worktreePath, basePath) {
|
|
330
|
+
if (!condition)
|
|
331
|
+
return true;
|
|
332
|
+
if (condition.exitCode) {
|
|
333
|
+
const prevResult = stepResults.get(condition.step);
|
|
334
|
+
if (!prevResult)
|
|
335
|
+
return false;
|
|
336
|
+
const code = prevResult.exitCode;
|
|
337
|
+
const ec = condition.exitCode;
|
|
338
|
+
if (ec.eq !== undefined && code !== ec.eq)
|
|
339
|
+
return false;
|
|
340
|
+
if (ec.ne !== undefined && code === ec.ne)
|
|
341
|
+
return false;
|
|
342
|
+
if (ec.gt !== undefined && !(code > ec.gt))
|
|
343
|
+
return false;
|
|
344
|
+
if (ec.lt !== undefined && !(code < ec.lt))
|
|
345
|
+
return false;
|
|
346
|
+
}
|
|
347
|
+
if (condition.fileExists) {
|
|
348
|
+
const base = worktreePath ?? basePath;
|
|
349
|
+
if (condition.fileExists.path.startsWith('/')) {
|
|
350
|
+
return false; // Absolute paths not allowed in step conditions
|
|
351
|
+
}
|
|
352
|
+
const filePath = join(base, condition.fileExists.path);
|
|
353
|
+
const resolved = resolve(filePath);
|
|
354
|
+
const resolvedBase = resolve(base);
|
|
355
|
+
if (!resolved.startsWith(resolvedBase + '/') && resolved !== resolvedBase) {
|
|
356
|
+
return false; // path escapes the worktree — treat as "file doesn't exist"
|
|
357
|
+
}
|
|
358
|
+
if (!existsSync(filePath))
|
|
359
|
+
return false;
|
|
360
|
+
}
|
|
361
|
+
return true;
|
|
362
|
+
}
|
|
363
|
+
async function executeSteps(taskRecord, steps, adapter, worktreePath, basePath, store, convoyId, verbose) {
|
|
364
|
+
const now = () => new Date().toISOString();
|
|
365
|
+
const stepResults = new Map();
|
|
366
|
+
let combinedOutput = '';
|
|
367
|
+
let lastExitCode = 0;
|
|
368
|
+
// Track total_steps in DB
|
|
369
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'running', {});
|
|
370
|
+
for (let i = 0; i < steps.length; i++) {
|
|
371
|
+
const step = steps[i];
|
|
372
|
+
// Evaluate condition — skip step if condition is not met
|
|
373
|
+
if (step.if) {
|
|
374
|
+
const condMet = evaluateStepCondition(step.if, stepResults, worktreePath, basePath);
|
|
375
|
+
if (!condMet) {
|
|
376
|
+
const stepId = store.insertTaskStep({
|
|
377
|
+
task_id: taskRecord.id,
|
|
378
|
+
step_index: i,
|
|
379
|
+
prompt: step.prompt,
|
|
380
|
+
gates: step.gates ? JSON.stringify(step.gates) : null,
|
|
381
|
+
status: 'skipped',
|
|
382
|
+
exit_code: null,
|
|
383
|
+
output: 'Skipped: condition not met',
|
|
384
|
+
started_at: now(),
|
|
385
|
+
finished_at: now(),
|
|
386
|
+
});
|
|
387
|
+
if (step.id) {
|
|
388
|
+
stepResults.set(step.id, { exitCode: 0 });
|
|
389
|
+
}
|
|
390
|
+
combinedOutput += `\n[Step ${i + 1} skipped: condition not met]`;
|
|
391
|
+
continue;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
// Insert step record as running
|
|
395
|
+
const stepDbId = store.insertTaskStep({
|
|
396
|
+
task_id: taskRecord.id,
|
|
397
|
+
step_index: i,
|
|
398
|
+
prompt: step.prompt,
|
|
399
|
+
gates: step.gates ? JSON.stringify(step.gates) : null,
|
|
400
|
+
status: 'running',
|
|
401
|
+
exit_code: null,
|
|
402
|
+
output: null,
|
|
403
|
+
started_at: now(),
|
|
404
|
+
finished_at: null,
|
|
405
|
+
});
|
|
406
|
+
// Update current_step on the task record
|
|
407
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'running', {});
|
|
408
|
+
const stepMaxRetries = step.max_retries ?? taskRecord.max_retries;
|
|
409
|
+
let stepResult = { success: false, output: '', exitCode: -1 };
|
|
410
|
+
let stepAttempt = 0;
|
|
411
|
+
while (stepAttempt <= stepMaxRetries) {
|
|
412
|
+
// Prepend prior failure context on retries
|
|
413
|
+
let stepPrompt = step.prompt;
|
|
414
|
+
if (stepAttempt > 0 && stepResult) {
|
|
415
|
+
const failedOutput = stepResult.output || '(no output)';
|
|
416
|
+
stepPrompt = `Previous attempt failed.\nExit code: ${stepResult.exitCode}\nError output:\n${failedOutput}\n\nFix the issues and try again.\n\n` + step.prompt;
|
|
417
|
+
}
|
|
418
|
+
const stepTask = {
|
|
419
|
+
id: taskRecord.id,
|
|
420
|
+
prompt: stepPrompt,
|
|
421
|
+
agent: taskRecord.agent,
|
|
422
|
+
timeout: `${taskRecord.timeout_ms}ms`,
|
|
423
|
+
depends_on: [],
|
|
424
|
+
files: taskRecord.files ? JSON.parse(taskRecord.files) : [],
|
|
425
|
+
description: `step ${i + 1}`,
|
|
426
|
+
max_retries: stepMaxRetries,
|
|
427
|
+
};
|
|
428
|
+
try {
|
|
429
|
+
stepResult = await adapter.execute(stepTask, { verbose, cwd: worktreePath ?? basePath });
|
|
430
|
+
}
|
|
431
|
+
catch (err) {
|
|
432
|
+
stepResult = { success: false, output: err.message, exitCode: -1 };
|
|
433
|
+
}
|
|
434
|
+
if (stepResult.success)
|
|
435
|
+
break;
|
|
436
|
+
stepAttempt++;
|
|
437
|
+
if (stepAttempt <= stepMaxRetries) {
|
|
438
|
+
process.stdout.write(` ↺ step ${i + 1}/${steps.length} failed, retry ${stepAttempt}/${stepMaxRetries}\n`);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
lastExitCode = stepResult.exitCode;
|
|
442
|
+
combinedOutput += `\n[Step ${i + 1}]\n${stepResult.output}`;
|
|
443
|
+
if (step.id) {
|
|
444
|
+
stepResults.set(step.id, { exitCode: stepResult.exitCode });
|
|
445
|
+
}
|
|
446
|
+
// Run step-level gates if present
|
|
447
|
+
if (step.gates && step.gates.length > 0 && stepResult.success) {
|
|
448
|
+
let gateFailure = null;
|
|
449
|
+
const execFileCb = (await import('node:child_process')).execFile;
|
|
450
|
+
const execFileP = (await import('node:util')).promisify(execFileCb);
|
|
451
|
+
for (const command of step.gates) {
|
|
452
|
+
try {
|
|
453
|
+
// SECURITY: Gate/hook commands come from the .convoy.yml spec file, which is operator-controlled.
|
|
454
|
+
// They are NOT user-supplied and are part of the trusted build configuration.
|
|
455
|
+
await execFileP('sh', ['-c', command], { cwd: worktreePath ?? basePath });
|
|
456
|
+
}
|
|
457
|
+
catch (gateErr) {
|
|
458
|
+
const ge = gateErr;
|
|
459
|
+
const code = typeof ge.code === 'number' ? ge.code : 1;
|
|
460
|
+
const output = ge.stderr || ge.stdout || ge.message || '';
|
|
461
|
+
gateFailure = { command, exitCode: code, output };
|
|
462
|
+
break;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
if (gateFailure !== null) {
|
|
466
|
+
stepResult = { success: false, output: `Gate failed: ${gateFailure.command}\nExit code: ${gateFailure.exitCode}\n${gateFailure.output}`, exitCode: gateFailure.exitCode };
|
|
467
|
+
lastExitCode = gateFailure.exitCode;
|
|
468
|
+
combinedOutput += `\n[Step ${i + 1} gate failed: ${gateFailure.command}]`;
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
// Update step record
|
|
472
|
+
store.updateTaskStep(stepDbId, {
|
|
473
|
+
status: stepResult.success ? 'done' : 'failed',
|
|
474
|
+
exit_code: stepResult.exitCode,
|
|
475
|
+
output: stepResult.output,
|
|
476
|
+
finished_at: now(),
|
|
477
|
+
});
|
|
478
|
+
if (!stepResult.success) {
|
|
479
|
+
return {
|
|
480
|
+
success: false,
|
|
481
|
+
output: combinedOutput.trim(),
|
|
482
|
+
exitCode: lastExitCode,
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return {
|
|
487
|
+
success: true,
|
|
488
|
+
output: combinedOutput.trim(),
|
|
489
|
+
exitCode: lastExitCode,
|
|
490
|
+
};
|
|
491
|
+
}
|
|
492
|
+
// ── File-based injection ──────────────────────────────────────────────────────
|
|
493
|
+
const INJECT_DIR = '.opencastle/convoy-inject';
|
|
494
|
+
const CONVOY_ID_RE = /^[a-zA-Z0-9-]+$/;
|
|
495
|
+
const MAX_FILE_INJECTED_TASKS = 10;
|
|
496
|
+
function pollInjectFile(convoyId, store, events, basePath) {
|
|
497
|
+
// Path traversal guard: convoy_id must be alphanumeric + hyphens only
|
|
498
|
+
if (!CONVOY_ID_RE.test(convoyId))
|
|
499
|
+
return 0;
|
|
500
|
+
const injectDir = join(basePath, INJECT_DIR, convoyId);
|
|
501
|
+
const injectPath = join(injectDir, 'inject.yml');
|
|
502
|
+
if (!existsSync(injectPath))
|
|
503
|
+
return 0;
|
|
504
|
+
// Atomic rename to prevent double-read
|
|
505
|
+
const processingPath = injectPath + '.processing';
|
|
506
|
+
try {
|
|
507
|
+
renameSync(injectPath, processingPath);
|
|
508
|
+
}
|
|
509
|
+
catch {
|
|
510
|
+
return 0; // Another process may have grabbed it
|
|
511
|
+
}
|
|
512
|
+
let raw;
|
|
513
|
+
try {
|
|
514
|
+
raw = readFileSync(processingPath, 'utf8');
|
|
515
|
+
}
|
|
516
|
+
catch {
|
|
517
|
+
return 0;
|
|
518
|
+
}
|
|
519
|
+
finally {
|
|
520
|
+
try {
|
|
521
|
+
unlinkSync(processingPath);
|
|
522
|
+
}
|
|
523
|
+
catch { /* ignore */ }
|
|
524
|
+
}
|
|
525
|
+
let parsed;
|
|
526
|
+
try {
|
|
527
|
+
parsed = parseYaml(raw);
|
|
528
|
+
if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.tasks)) {
|
|
529
|
+
process.stderr.write(`Warning: inject file has invalid format (expected { tasks: [...] })\n`);
|
|
530
|
+
return 0;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
catch (err) {
|
|
534
|
+
process.stderr.write(`Warning: failed to parse inject file: ${err.message}\n`);
|
|
535
|
+
return 0;
|
|
536
|
+
}
|
|
537
|
+
const tasks = parsed.tasks;
|
|
538
|
+
const allExisting = store.getTasksByConvoy(convoyId);
|
|
539
|
+
const existingFileInjected = allExisting.filter(t => t.provenance === 'file-injection').length;
|
|
540
|
+
const remaining = MAX_FILE_INJECTED_TASKS - existingFileInjected;
|
|
541
|
+
let injectedCount = 0;
|
|
542
|
+
for (const rawTask of tasks) {
|
|
543
|
+
if (injectedCount >= remaining) {
|
|
544
|
+
process.stderr.write(`Warning: file injection limit reached (${MAX_FILE_INJECTED_TASKS}), skipping remaining tasks\n`);
|
|
545
|
+
break;
|
|
546
|
+
}
|
|
547
|
+
// Validate required fields
|
|
548
|
+
if (!rawTask.id || typeof rawTask.id !== 'string') {
|
|
549
|
+
process.stderr.write(`Warning: skipping injected task with missing/invalid id\n`);
|
|
550
|
+
continue;
|
|
551
|
+
}
|
|
552
|
+
if (!rawTask.prompt || typeof rawTask.prompt !== 'string') {
|
|
553
|
+
process.stderr.write(`Warning: skipping injected task "${rawTask.id}": missing prompt\n`);
|
|
554
|
+
continue;
|
|
555
|
+
}
|
|
556
|
+
if (!rawTask.agent || typeof rawTask.agent !== 'string') {
|
|
557
|
+
process.stderr.write(`Warning: skipping injected task "${rawTask.id}": missing agent\n`);
|
|
558
|
+
continue;
|
|
559
|
+
}
|
|
560
|
+
// Check ID uniqueness
|
|
561
|
+
if (allExisting.some(t => t.id === rawTask.id)) {
|
|
562
|
+
process.stderr.write(`Warning: skipping injected task "${rawTask.id}": ID already exists\n`);
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
// Determine phase — inject into last scheduled phase
|
|
566
|
+
const maxPhase = allExisting.reduce((max, t) => Math.max(max, t.phase), 0);
|
|
567
|
+
// Validate file paths before building the record
|
|
568
|
+
let validatedFiles = null;
|
|
569
|
+
if (rawTask.files && Array.isArray(rawTask.files)) {
|
|
570
|
+
try {
|
|
571
|
+
validatedFiles = JSON.stringify(rawTask.files.map(f => normalizePath(f)));
|
|
572
|
+
}
|
|
573
|
+
catch (err) {
|
|
574
|
+
process.stderr.write(`Warning: skipping injected task "${rawTask.id}": invalid file path: ${err.message}\n`);
|
|
575
|
+
continue;
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
const record = {
|
|
579
|
+
id: rawTask.id,
|
|
580
|
+
convoy_id: convoyId,
|
|
581
|
+
phase: maxPhase,
|
|
582
|
+
prompt: rawTask.prompt,
|
|
583
|
+
agent: rawTask.agent,
|
|
584
|
+
adapter: null,
|
|
585
|
+
model: null,
|
|
586
|
+
timeout_ms: typeof rawTask.timeout_ms === 'number' ? rawTask.timeout_ms : 1_800_000,
|
|
587
|
+
status: 'pending',
|
|
588
|
+
worker_id: null,
|
|
589
|
+
worktree: null,
|
|
590
|
+
output: null,
|
|
591
|
+
exit_code: null,
|
|
592
|
+
started_at: null,
|
|
593
|
+
finished_at: null,
|
|
594
|
+
retries: 0,
|
|
595
|
+
max_retries: typeof rawTask.max_retries === 'number' ? rawTask.max_retries : 1,
|
|
596
|
+
files: validatedFiles,
|
|
597
|
+
depends_on: null,
|
|
598
|
+
prompt_tokens: null,
|
|
599
|
+
completion_tokens: null,
|
|
600
|
+
total_tokens: null,
|
|
601
|
+
cost_usd: null,
|
|
602
|
+
gates: null,
|
|
603
|
+
on_exhausted: 'dlq',
|
|
604
|
+
injected: 1,
|
|
605
|
+
provenance: 'file-injection',
|
|
606
|
+
idempotency_key: null,
|
|
607
|
+
current_step: null,
|
|
608
|
+
total_steps: null,
|
|
609
|
+
review_level: null,
|
|
610
|
+
review_verdict: null,
|
|
611
|
+
review_tokens: null,
|
|
612
|
+
review_model: null,
|
|
613
|
+
panel_attempts: 0,
|
|
614
|
+
dispute_id: null,
|
|
615
|
+
drift_score: null,
|
|
616
|
+
drift_retried: 0,
|
|
617
|
+
outputs: null,
|
|
618
|
+
inputs: null,
|
|
619
|
+
discovered_issues: null,
|
|
620
|
+
};
|
|
621
|
+
try {
|
|
622
|
+
store.insertInjectedTask(record);
|
|
623
|
+
injectedCount++;
|
|
624
|
+
}
|
|
625
|
+
catch (err) {
|
|
626
|
+
process.stderr.write(`Warning: failed to inject task "${rawTask.id}": ${err.message}\n`);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
if (injectedCount > 0) {
|
|
630
|
+
events.emit('file_injection_received', {
|
|
631
|
+
task_count: injectedCount,
|
|
632
|
+
source: injectPath,
|
|
633
|
+
}, { convoy_id: convoyId });
|
|
634
|
+
}
|
|
635
|
+
return injectedCount;
|
|
636
|
+
}
|
|
47
637
|
// ── Core convoy execution ─────────────────────────────────────────────────────
|
|
48
|
-
async function runConvoy(convoyId, spec, adapter, store, events, wtManager, mergeQueue, basePath, baseBranch, verbose, startTime) {
|
|
638
|
+
async function runConvoy(convoyId, spec, adapter, store, events, wtManager, mergeQueue, basePath, baseBranch, verbose, startTime, ndjsonPath, reviewRunner) {
|
|
49
639
|
const totalTasks = spec.tasks?.length ?? 0;
|
|
50
640
|
let completedCount = 0;
|
|
51
641
|
const activeTaskMap = new Map();
|
|
642
|
+
const reviewSemaphore = new ReviewSemaphore(spec.defaults?.max_concurrent_reviews ?? 3);
|
|
643
|
+
let reviewTokensTotal = 0;
|
|
52
644
|
const taskAdapterMap = new Map();
|
|
53
645
|
const healthMonitor = createHealthMonitor({
|
|
54
646
|
store,
|
|
@@ -65,6 +657,17 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
65
657
|
},
|
|
66
658
|
});
|
|
67
659
|
healthMonitor.start();
|
|
660
|
+
// ── Circuit breaker ────────────────────────────────────────────────────────
|
|
661
|
+
const circuitBreakerConfig = spec.defaults?.circuit_breaker;
|
|
662
|
+
const convoyRecord = store.getConvoy(convoyId);
|
|
663
|
+
const initialCircuitState = convoyRecord?.circuit_state ? JSON.parse(convoyRecord.circuit_state) : undefined;
|
|
664
|
+
const circuitBreaker = new CircuitBreakerManager(circuitBreakerConfig, initialCircuitState);
|
|
665
|
+
// ── Trust model ────────────────────────────────────────────────────────────
|
|
666
|
+
// Gate commands, hook commands, and step commands in .convoy.yml are treated
|
|
667
|
+
// as operator-controlled build configuration (analogous to Makefiles, CI
|
|
668
|
+
// configs, or package.json scripts). They are executed via sh -c and must
|
|
669
|
+
// NOT contain user-supplied input. The spec file itself is the trust boundary.
|
|
670
|
+
// ──────────────────────────────────────────────────────────────────────────
|
|
68
671
|
// ── Task skipping ─────────────────────────────────────────────────────────
|
|
69
672
|
function skipTask(taskId, reason, visited = new Set()) {
|
|
70
673
|
if (visited.has(taskId))
|
|
@@ -101,6 +704,134 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
101
704
|
}
|
|
102
705
|
}
|
|
103
706
|
}
|
|
707
|
+
function handleExhaustion(taskRecord, failureType, errorOutput) {
|
|
708
|
+
const exhausted = taskRecord.on_exhausted ?? 'dlq';
|
|
709
|
+
if (exhausted === 'dlq' || exhausted === 'stop') {
|
|
710
|
+
const dlqId = `dlq-${taskRecord.id}-${Date.now()}`;
|
|
711
|
+
// Pre-scan: build the markdown entry and check for secrets BEFORE any
|
|
712
|
+
// writes. This keeps the SQLite DLQ row and the Markdown file in sync —
|
|
713
|
+
// either both are written or neither is (MF-2 dual-write atomicity).
|
|
714
|
+
const { marker: dlqMarker, entry: dlqMdEntry } = buildDlqMarkdownEntry(dlqId, taskRecord, failureType, errorOutput);
|
|
715
|
+
const dlqScanResult = scanForSecrets(dlqMdEntry, 'AGENT-FAILURES.md');
|
|
716
|
+
if (!dlqScanResult.clean) {
|
|
717
|
+
// Block BOTH writes to maintain consistent state
|
|
718
|
+
events.emit('secret_leak_prevented', {
|
|
719
|
+
task_id: taskRecord.id,
|
|
720
|
+
findings_count: dlqScanResult.findings.length,
|
|
721
|
+
patterns: dlqScanResult.findings.map((f) => f.pattern),
|
|
722
|
+
context: 'dlq_dual_write',
|
|
723
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
724
|
+
}
|
|
725
|
+
else {
|
|
726
|
+
// Clean — proceed with both writes atomically
|
|
727
|
+
store.insertDlqEntry({
|
|
728
|
+
id: dlqId,
|
|
729
|
+
convoy_id: convoyId,
|
|
730
|
+
task_id: taskRecord.id,
|
|
731
|
+
agent: taskRecord.agent,
|
|
732
|
+
failure_type: failureType,
|
|
733
|
+
error_output: errorOutput,
|
|
734
|
+
attempts: taskRecord.retries + 1,
|
|
735
|
+
tokens_spent: taskRecord.total_tokens,
|
|
736
|
+
escalation_task_id: null,
|
|
737
|
+
resolved: 0,
|
|
738
|
+
resolution: null,
|
|
739
|
+
created_at: new Date().toISOString(),
|
|
740
|
+
resolved_at: null,
|
|
741
|
+
});
|
|
742
|
+
appendDlqMarkdownClean(dlqMarker, dlqMdEntry);
|
|
743
|
+
events.emit('dlq_entry_created', {
|
|
744
|
+
dlq_id: dlqId,
|
|
745
|
+
task_id: taskRecord.id,
|
|
746
|
+
agent: taskRecord.agent,
|
|
747
|
+
failure_type: failureType,
|
|
748
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
if (exhausted === 'stop') {
|
|
752
|
+
// Skip all remaining pending tasks + set convoy to failed
|
|
753
|
+
const allPending = store.getTasksByConvoy(convoyId).filter(t => t.status === 'pending');
|
|
754
|
+
for (const t of allPending) {
|
|
755
|
+
skipTask(t.id, `on_exhausted: stop — task "${taskRecord.id}" exhausted retries`);
|
|
756
|
+
}
|
|
757
|
+
store.updateConvoyStatus(convoyId, 'failed');
|
|
758
|
+
events.emit('convoy_failed', { status: 'failed', reason: `on_exhausted: stop — task "${taskRecord.id}" exhausted retries` }, { convoy_id: convoyId });
|
|
759
|
+
}
|
|
760
|
+
else if (exhausted === 'dlq' || exhausted === 'skip') {
|
|
761
|
+
// Default behavior: cascade failure to dependents only
|
|
762
|
+
cascadeFailure(taskRecord.id);
|
|
763
|
+
}
|
|
764
|
+
// ── Circuit breaker: record exhaustion failure ──────────────────────────
|
|
765
|
+
if (circuitBreakerConfig) {
|
|
766
|
+
const { tripped } = circuitBreaker.recordFailure(taskRecord.agent);
|
|
767
|
+
try {
|
|
768
|
+
store.updateConvoyCircuitState(convoyId, circuitBreaker.serialize());
|
|
769
|
+
}
|
|
770
|
+
catch { /* non-critical */ }
|
|
771
|
+
if (tripped) {
|
|
772
|
+
events.emit('circuit_breaker_tripped', {
|
|
773
|
+
agent: taskRecord.agent,
|
|
774
|
+
state: circuitBreaker.getState(taskRecord.agent),
|
|
775
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
// ── Hook execution ────────────────────────────────────────────────────────
|
|
780
|
+
async function runHooks(hooks, lifecycle, context) {
|
|
781
|
+
const filtered = hooks.filter(h => (h.on ?? 'post_task') === lifecycle);
|
|
782
|
+
for (const hook of filtered) {
|
|
783
|
+
if (hook.type === 'command' || hook.type === 'guard' || hook.type === 'validate') {
|
|
784
|
+
const cmd = hook.command;
|
|
785
|
+
if (!cmd)
|
|
786
|
+
continue;
|
|
787
|
+
try {
|
|
788
|
+
// SECURITY: Gate/hook commands come from the .convoy.yml spec file, which is operator-controlled.
|
|
789
|
+
// They are NOT user-supplied and are part of the trusted build configuration.
|
|
790
|
+
await execFile('sh', ['-c', cmd], { cwd: context.cwd });
|
|
791
|
+
}
|
|
792
|
+
catch (err) {
|
|
793
|
+
const execErr = err;
|
|
794
|
+
const errorMsg = execErr.stderr || execErr.stdout || execErr.message || '';
|
|
795
|
+
return { passed: false, failedHook: hook, error: errorMsg };
|
|
796
|
+
}
|
|
797
|
+
}
|
|
798
|
+
else if (hook.type === 'agent') {
|
|
799
|
+
if (!hook.prompt)
|
|
800
|
+
continue;
|
|
801
|
+
const hookTask = {
|
|
802
|
+
id: `hook-${lifecycle}-${context.taskId ?? 'convoy'}-${Date.now()}`,
|
|
803
|
+
prompt: hook.prompt,
|
|
804
|
+
agent: hook.name ?? 'developer',
|
|
805
|
+
timeout: '10m',
|
|
806
|
+
depends_on: [],
|
|
807
|
+
files: [],
|
|
808
|
+
description: `Hook: ${hook.name ?? hook.type}`,
|
|
809
|
+
max_retries: 0,
|
|
810
|
+
};
|
|
811
|
+
try {
|
|
812
|
+
const hookResult = await adapter.execute(hookTask, { verbose, cwd: context.cwd });
|
|
813
|
+
if (!hookResult.success) {
|
|
814
|
+
return { passed: false, failedHook: hook, error: hookResult.output };
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
catch (err) {
|
|
818
|
+
return { passed: false, failedHook: hook, error: err.message };
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
else if (hook.type === 'review') {
|
|
822
|
+
if (!context.taskId || !reviewRunner)
|
|
823
|
+
continue;
|
|
824
|
+
const reviewTaskRecord = store.getTask(context.taskId, context.convoyId);
|
|
825
|
+
if (reviewTaskRecord) {
|
|
826
|
+
const reviewResult = await reviewRunner(reviewTaskRecord, 'fast', spec.defaults?.reviewer_model ?? 'default');
|
|
827
|
+
if (reviewResult.verdict !== 'pass') {
|
|
828
|
+
return { passed: false, failedHook: hook, error: reviewResult.feedback };
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
return { passed: true };
|
|
834
|
+
}
|
|
104
835
|
// ── Single-task executor ──────────────────────────────────────────────────
|
|
105
836
|
async function executeOneTask(taskRecord) {
|
|
106
837
|
const workerId = `worker-${taskRecord.id}-${Date.now()}`;
|
|
@@ -119,6 +850,65 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
119
850
|
}
|
|
120
851
|
}
|
|
121
852
|
taskAdapterMap.set(taskRecord.id, taskAdapter);
|
|
853
|
+
// ── Check inputs availability ────────────────────────────────────────────
|
|
854
|
+
if (taskRecord.inputs) {
|
|
855
|
+
const inputs = JSON.parse(taskRecord.inputs);
|
|
856
|
+
for (const input of inputs) {
|
|
857
|
+
const artifact = store.getArtifact(convoyId, input.name);
|
|
858
|
+
if (!artifact) {
|
|
859
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'wait-for-input');
|
|
860
|
+
events.emit('task_waiting_input', {
|
|
861
|
+
task_id: taskRecord.id,
|
|
862
|
+
missing_artifact: input.name,
|
|
863
|
+
from_task: input.from,
|
|
864
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
865
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
866
|
+
return;
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
// ── Circuit breaker check ──────────────────────────────────────────────
|
|
871
|
+
if (circuitBreakerConfig) {
|
|
872
|
+
if (!circuitBreaker.canAssign(taskRecord.agent)) {
|
|
873
|
+
const fallback = circuitBreaker.fallback;
|
|
874
|
+
if (fallback) {
|
|
875
|
+
events.emit('circuit_breaker_fallback', {
|
|
876
|
+
original_agent: taskRecord.agent,
|
|
877
|
+
fallback_agent: fallback,
|
|
878
|
+
state: circuitBreaker.getState(taskRecord.agent),
|
|
879
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
880
|
+
}
|
|
881
|
+
else {
|
|
882
|
+
events.emit('circuit_breaker_blocked', {
|
|
883
|
+
agent: taskRecord.agent,
|
|
884
|
+
state: circuitBreaker.getState(taskRecord.agent),
|
|
885
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
886
|
+
}
|
|
887
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'skipped', {
|
|
888
|
+
output: `Circuit breaker open for agent "${taskRecord.agent}". ${fallback ? `No fallback available.` : `No fallback configured.`}`,
|
|
889
|
+
});
|
|
890
|
+
completedCount++;
|
|
891
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
892
|
+
cascadeFailure(taskRecord.id);
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
// ── Intelligence: circuit breaker weak-area avoidance (Phase 18.2) ─────
|
|
897
|
+
if (spec.defaults?.avoid_weak_agents) {
|
|
898
|
+
try {
|
|
899
|
+
const weakAreas = feedCircuitBreaker(taskRecord.agent, basePath);
|
|
900
|
+
const taskFiles = taskRecord.files ? JSON.parse(taskRecord.files) : [];
|
|
901
|
+
const matchesWeakArea = weakAreas.some(area => taskFiles.some(f => f.toLowerCase().includes(area.toLowerCase())));
|
|
902
|
+
if (matchesWeakArea && taskRecord.retries === 0) {
|
|
903
|
+
events.emit('weak_area_skipped', { agent: taskRecord.agent, weak_areas: weakAreas, task_files: taskFiles }, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
904
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'skipped', { output: `Agent "${taskRecord.agent}" has weak-area match for task files. Skipped by avoid_weak_agents policy.` });
|
|
905
|
+
completedCount++;
|
|
906
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
907
|
+
return;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
catch { /* non-critical */ }
|
|
911
|
+
}
|
|
122
912
|
// Create worktree (skip for copilot adapter)
|
|
123
913
|
let worktreePath = null;
|
|
124
914
|
if (taskAdapter.name !== 'copilot') {
|
|
@@ -150,16 +940,149 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
150
940
|
store.updateWorkerStatus(workerId, 'running');
|
|
151
941
|
const task = taskRecordToTask(taskRecord);
|
|
152
942
|
activeTaskMap.set(taskRecord.id, task);
|
|
943
|
+
// ── Inject inputs into prompt ────────────────────────────────────────────
|
|
944
|
+
if (taskRecord.inputs) {
|
|
945
|
+
const inputs = JSON.parse(taskRecord.inputs);
|
|
946
|
+
for (const input of inputs) {
|
|
947
|
+
const artifact = store.getArtifact(convoyId, input.name);
|
|
948
|
+
const templateVar = input.as ?? input.name;
|
|
949
|
+
task.prompt = task.prompt.replaceAll(`{{input.${templateVar}}}`, artifact.content);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
// ── Scratchpad template substitution (Phase 17.1) ───────────────────────
|
|
953
|
+
const scratchpadRe = /\{\{scratchpad\.([a-zA-Z0-9_.-]+)\}\}/g;
|
|
954
|
+
let scratchpadMatch;
|
|
955
|
+
while ((scratchpadMatch = scratchpadRe.exec(task.prompt)) !== null) {
|
|
956
|
+
const spKey = scratchpadMatch[1];
|
|
957
|
+
const spVal = store.getScratchpadValue(spKey);
|
|
958
|
+
if (spVal !== null) {
|
|
959
|
+
task.prompt = task.prompt.replaceAll(`{{scratchpad.${spKey}}}`, spVal);
|
|
960
|
+
scratchpadRe.lastIndex = 0; // reset after replaceAll
|
|
961
|
+
}
|
|
962
|
+
}
|
|
153
963
|
process.stdout.write(` ${c.cyan('▶')} ${c.bold(`[${taskRecord.id}]`)} ${taskRecord.agent}${worktreePath ? c.dim(' (worktree)') : ''}\n`);
|
|
154
964
|
events.emit('task_started', { worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
155
965
|
const taskStartTime = Date.now();
|
|
966
|
+
// ── Outbound prompt scan — NEVER send a prompt containing secrets ─────────
|
|
967
|
+
const promptScan = scanForSecrets(taskRecord.prompt, `task:${taskRecord.id}`);
|
|
968
|
+
if (!promptScan.clean) {
|
|
969
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'failed', {
|
|
970
|
+
finished_at: now(),
|
|
971
|
+
output: `Secret detected in prompt — task blocked before execution.\nFindings:\n${promptScan.findings
|
|
972
|
+
.map((f) => ` ${f.pattern} at line ${f.line}: ${f.snippet}`)
|
|
973
|
+
.join('\n')}`,
|
|
974
|
+
});
|
|
975
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: now() });
|
|
976
|
+
completedCount++;
|
|
977
|
+
events.emit('secret_leak_prevented', {
|
|
978
|
+
task_id: taskRecord.id,
|
|
979
|
+
findings_count: promptScan.findings.length,
|
|
980
|
+
patterns: promptScan.findings.map((f) => f.pattern),
|
|
981
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
982
|
+
cascadeFailure(taskRecord.id);
|
|
983
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
156
986
|
const timeout = makeTimeoutPromise(taskRecord.timeout_ms);
|
|
157
987
|
let result;
|
|
988
|
+
// Retrieve steps from spec if defined
|
|
989
|
+
const specTask = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
|
|
990
|
+
const steps = specTask?.steps;
|
|
991
|
+
const taskHooks = specTask?.hooks ?? [];
|
|
992
|
+
// ── Intelligence: inject lessons (Phase 18.1) ─────────────────────────
|
|
993
|
+
if (spec.defaults?.inject_lessons !== false) {
|
|
994
|
+
try {
|
|
995
|
+
const taskFiles = taskRecord.files ? JSON.parse(taskRecord.files) : [];
|
|
996
|
+
const lessons = readLessons(taskRecord.agent, taskFiles, basePath);
|
|
997
|
+
if (lessons.length > 0) {
|
|
998
|
+
const lessonsBlock = '\n\n---\nRelevant lessons from previous sessions:\n'
|
|
999
|
+
+ lessons.join('\n\n')
|
|
1000
|
+
+ '\n---\n\n';
|
|
1001
|
+
task.prompt = lessonsBlock + task.prompt;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
catch { /* non-critical */ }
|
|
1005
|
+
}
|
|
1006
|
+
// ── Intelligence: inject persistent agent identity (Phase 17.2) ────────
|
|
1007
|
+
const specTaskForPersistent = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
|
|
1008
|
+
if (specTaskForPersistent?.persistent) {
|
|
1009
|
+
try {
|
|
1010
|
+
const identities = store.getAgentIdentities(taskRecord.agent, 3);
|
|
1011
|
+
if (identities.length > 0) {
|
|
1012
|
+
const contextBlock = '\n\n[Previous work context]\n'
|
|
1013
|
+
+ identities.map(id => id.summary).join('\n\n')
|
|
1014
|
+
+ '\n[End previous context]\n\n';
|
|
1015
|
+
task.prompt = contextBlock + task.prompt;
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
catch { /* non-critical */ }
|
|
1019
|
+
}
|
|
1020
|
+
// ── Intelligence: inject discovered issues instruction (Phase 18.4) ────
|
|
1021
|
+
if (spec.defaults?.track_discovered_issues) {
|
|
1022
|
+
task.prompt = injectDiscoveredIssuesInstruction(task.prompt);
|
|
1023
|
+
}
|
|
1024
|
+
// ── pre_task hooks ────────────────────────────────────────────────────────
|
|
1025
|
+
if (taskHooks.length > 0) {
|
|
1026
|
+
const preResult = await runHooks(taskHooks, 'pre_task', {
|
|
1027
|
+
taskId: taskRecord.id,
|
|
1028
|
+
convoyId,
|
|
1029
|
+
cwd: worktreePath ?? basePath,
|
|
1030
|
+
});
|
|
1031
|
+
if (!preResult.passed) {
|
|
1032
|
+
await removeWorktree();
|
|
1033
|
+
const hookLabel = preResult.failedHook?.name ?? preResult.failedHook?.type ?? 'unknown';
|
|
1034
|
+
store.withTransaction(() => {
|
|
1035
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'hook-failed', {
|
|
1036
|
+
finished_at: now(),
|
|
1037
|
+
output: `pre_task hook "${hookLabel}" failed: ${preResult.error ?? ''}`,
|
|
1038
|
+
exit_code: 1,
|
|
1039
|
+
});
|
|
1040
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: now() });
|
|
1041
|
+
});
|
|
1042
|
+
completedCount++;
|
|
1043
|
+
process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} pre_task hook failed ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
|
|
1044
|
+
events.emit('task_failed', { reason: 'hook-failed', hook: hookLabel, worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
1045
|
+
cascadeFailure(taskRecord.id);
|
|
1046
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1047
|
+
return;
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
// ── Symlink security scan (pre-execution) ────────────────────────────────
|
|
1051
|
+
const taskFiles = taskRecord.files ? JSON.parse(taskRecord.files) : [];
|
|
1052
|
+
if (taskFiles.length > 0 && worktreePath) {
|
|
1053
|
+
try {
|
|
1054
|
+
scanSymlinks(taskFiles, worktreePath);
|
|
1055
|
+
}
|
|
1056
|
+
catch (err) {
|
|
1057
|
+
await removeWorktree();
|
|
1058
|
+
store.withTransaction(() => {
|
|
1059
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'failed', {
|
|
1060
|
+
finished_at: now(),
|
|
1061
|
+
output: `Symlink security check failed: ${err.message}`,
|
|
1062
|
+
exit_code: 1,
|
|
1063
|
+
});
|
|
1064
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: now() });
|
|
1065
|
+
});
|
|
1066
|
+
completedCount++;
|
|
1067
|
+
events.emit('task_failed', { reason: 'symlink-escape', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
1068
|
+
cascadeFailure(taskRecord.id);
|
|
1069
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1070
|
+
return;
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
158
1073
|
try {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
1074
|
+
if (steps && steps.length > 0) {
|
|
1075
|
+
result = await Promise.race([
|
|
1076
|
+
executeSteps(taskRecord, steps, taskAdapter, worktreePath, basePath, store, convoyId, verbose),
|
|
1077
|
+
timeout.promise,
|
|
1078
|
+
]);
|
|
1079
|
+
}
|
|
1080
|
+
else {
|
|
1081
|
+
result = await Promise.race([
|
|
1082
|
+
taskAdapter.execute(task, { verbose, cwd: worktreePath ?? basePath }),
|
|
1083
|
+
timeout.promise,
|
|
1084
|
+
]);
|
|
1085
|
+
}
|
|
163
1086
|
timeout.clear();
|
|
164
1087
|
}
|
|
165
1088
|
catch (err) {
|
|
@@ -184,12 +1107,14 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
184
1107
|
await removeWorktree();
|
|
185
1108
|
const freshRecord = store.getTask(taskRecord.id, convoyId);
|
|
186
1109
|
if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
|
|
1110
|
+
const contextPrefix = `Previous attempt timed out.\n\nFix the issues and try again.\n\n`;
|
|
187
1111
|
store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
|
|
188
1112
|
retries: freshRecord.retries + 1,
|
|
189
1113
|
worker_id: null,
|
|
190
1114
|
worktree: null,
|
|
191
1115
|
started_at: null,
|
|
192
1116
|
finished_at: null,
|
|
1117
|
+
prompt: contextPrefix + taskRecord.prompt,
|
|
193
1118
|
});
|
|
194
1119
|
store.updateWorkerStatus(workerId, 'killed', { finished_at: finishedAt });
|
|
195
1120
|
process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} timed out, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
|
|
@@ -226,23 +1151,654 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
226
1151
|
phase: taskRecord.phase,
|
|
227
1152
|
convoy_id: convoyId,
|
|
228
1153
|
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
229
|
-
|
|
1154
|
+
handleExhaustion(freshRecord, 'timeout', result.output || null);
|
|
230
1155
|
}
|
|
231
1156
|
taskAdapterMap.delete(taskRecord.id);
|
|
232
1157
|
return;
|
|
233
1158
|
}
|
|
234
1159
|
// ── Success ─────────────────────────────────────────────────────────────
|
|
235
|
-
if (result.success) {
|
|
236
|
-
|
|
1160
|
+
if (result.success) { // ── Per-task gates ─────────────────────────────────────────────────────
|
|
1161
|
+
const taskGates = taskRecord.gates ? JSON.parse(taskRecord.gates) : [];
|
|
1162
|
+
if (taskGates.length > 0) {
|
|
1163
|
+
let gateFailure = null;
|
|
1164
|
+
for (const command of taskGates) {
|
|
1165
|
+
try {
|
|
1166
|
+
// SECURITY: Gate/hook commands come from the .convoy.yml spec file, which is operator-controlled.
|
|
1167
|
+
// They are NOT user-supplied and are part of the trusted build configuration.
|
|
1168
|
+
await execFile('sh', ['-c', command], { cwd: worktreePath ?? basePath });
|
|
1169
|
+
}
|
|
1170
|
+
catch (err) {
|
|
1171
|
+
const execErr = err;
|
|
1172
|
+
const code = typeof execErr.code === 'number' ? execErr.code : 1;
|
|
1173
|
+
const output = execErr.stderr || execErr.stdout || execErr.message || '';
|
|
1174
|
+
gateFailure = { command, exitCode: code, output };
|
|
1175
|
+
break;
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
if (gateFailure !== null) {
|
|
1179
|
+
await removeWorktree();
|
|
1180
|
+
const freshRecord = store.getTask(taskRecord.id, convoyId);
|
|
1181
|
+
if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
|
|
1182
|
+
const contextPrefix = `Previous attempt's gate check failed.\nGate: ${gateFailure.command}\nExit code: ${gateFailure.exitCode}\nOutput:\n${gateFailure.output || '(no output)'}\n\nFix the issues and try again.\n\n`;
|
|
1183
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
|
|
1184
|
+
retries: freshRecord.retries + 1,
|
|
1185
|
+
worker_id: null,
|
|
1186
|
+
worktree: null,
|
|
1187
|
+
started_at: null,
|
|
1188
|
+
finished_at: null,
|
|
1189
|
+
prompt: contextPrefix + taskRecord.prompt,
|
|
1190
|
+
});
|
|
1191
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1192
|
+
process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} gate failed, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
|
|
1193
|
+
}
|
|
1194
|
+
else {
|
|
1195
|
+
store.withTransaction(() => {
|
|
1196
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'gate-failed', {
|
|
1197
|
+
finished_at: finishedAt,
|
|
1198
|
+
output: `Gate failed: ${gateFailure.command}\nExit code: ${gateFailure.exitCode}\n${gateFailure.output}`,
|
|
1199
|
+
exit_code: gateFailure.exitCode,
|
|
1200
|
+
});
|
|
1201
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1202
|
+
});
|
|
1203
|
+
completedCount++;
|
|
1204
|
+
process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} gate failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
|
|
1205
|
+
events.emit('task_failed', { reason: 'gate-failed', gate: gateFailure.command, exit_code: gateFailure.exitCode, worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
1206
|
+
events.emit('session', {
|
|
1207
|
+
agent: taskRecord.agent,
|
|
1208
|
+
model: taskRecord.model ?? taskAdapter.name,
|
|
1209
|
+
task: taskRecord.id,
|
|
1210
|
+
outcome: 'failed',
|
|
1211
|
+
duration_min: Math.round((Date.now() - taskStartTime) / 60_000),
|
|
1212
|
+
files_changed: 0,
|
|
1213
|
+
retries: freshRecord.retries,
|
|
1214
|
+
convoy_id: convoyId,
|
|
1215
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1216
|
+
events.emit('delegation', {
|
|
1217
|
+
session_id: convoyId,
|
|
1218
|
+
agent: taskRecord.agent,
|
|
1219
|
+
model: taskRecord.model ?? taskAdapter.name,
|
|
1220
|
+
tier: 'standard',
|
|
1221
|
+
mechanism: 'convoy',
|
|
1222
|
+
outcome: 'failed',
|
|
1223
|
+
retries: freshRecord.retries,
|
|
1224
|
+
phase: taskRecord.phase,
|
|
1225
|
+
convoy_id: convoyId,
|
|
1226
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1227
|
+
handleExhaustion(freshRecord, 'gate-failed', gateFailure.output || null);
|
|
1228
|
+
}
|
|
1229
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
}
|
|
1233
|
+
// ── Built-in gates ────────────────────────────────────────────────────
|
|
1234
|
+
const builtInGates = spec.defaults?.built_in_gates;
|
|
1235
|
+
if (builtInGates && worktreePath) {
|
|
1236
|
+
if (builtInGates.browser_test) {
|
|
1237
|
+
const specTask = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
|
|
1238
|
+
const taskBrowserConfig = specTask?.browser_test ?? spec.defaults?.browser_test;
|
|
1239
|
+
if (!taskBrowserConfig) {
|
|
1240
|
+
process.stderr.write(`Warning: browser_test gate enabled but no browser_test config (urls) found — skipping\n`);
|
|
1241
|
+
}
|
|
1242
|
+
else {
|
|
1243
|
+
const browserResult = await browserTestGate({
|
|
1244
|
+
mcpServers: spec.defaults?.mcp_servers ?? [],
|
|
1245
|
+
taskConfig: taskBrowserConfig,
|
|
1246
|
+
worktreePath,
|
|
1247
|
+
approvalTimeout: spec.defaults?.mcp_server_approval_timeout,
|
|
1248
|
+
});
|
|
1249
|
+
events.emit('built_in_gate_result', { gate: 'browser_test', passed: browserResult.passed, output: browserResult.output }, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1250
|
+
if (!browserResult.passed) {
|
|
1251
|
+
await removeWorktree();
|
|
1252
|
+
const freshRecord = store.getTask(taskRecord.id, convoyId);
|
|
1253
|
+
if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
|
|
1254
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
|
|
1255
|
+
retries: freshRecord.retries + 1,
|
|
1256
|
+
worker_id: null,
|
|
1257
|
+
worktree: null,
|
|
1258
|
+
started_at: null,
|
|
1259
|
+
finished_at: null,
|
|
1260
|
+
});
|
|
1261
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1262
|
+
process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} browser test gate failed, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
|
|
1263
|
+
}
|
|
1264
|
+
else {
|
|
1265
|
+
store.withTransaction(() => {
|
|
1266
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'gate-failed', {
|
|
1267
|
+
finished_at: finishedAt,
|
|
1268
|
+
output: `Built-in gate (browser_test) failed:\n${browserResult.output}`,
|
|
1269
|
+
exit_code: 1,
|
|
1270
|
+
});
|
|
1271
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1272
|
+
});
|
|
1273
|
+
completedCount++;
|
|
1274
|
+
process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} browser test gate failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
|
|
1275
|
+
events.emit('task_failed', { reason: 'gate-failed', gate: 'browser_test', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
1276
|
+
handleExhaustion(freshRecord, 'browser-test', browserResult.output);
|
|
1277
|
+
}
|
|
1278
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
let changedFiles = [];
|
|
1284
|
+
let diff = '';
|
|
237
1285
|
try {
|
|
238
|
-
await
|
|
1286
|
+
const { stdout: filesOut } = await execFile('git', ['diff', '--name-only', `${baseBranch}..HEAD`], { cwd: worktreePath });
|
|
1287
|
+
changedFiles = filesOut.split('\n').filter(Boolean);
|
|
1288
|
+
const { stdout: diffOut } = await execFile('git', ['diff', `${baseBranch}..HEAD`], { cwd: worktreePath });
|
|
1289
|
+
diff = diffOut;
|
|
1290
|
+
}
|
|
1291
|
+
catch { /* no commits in worktree yet — skip */ }
|
|
1292
|
+
// Secret scan gate
|
|
1293
|
+
if (builtInGates.secret_scan && changedFiles.length > 0) {
|
|
1294
|
+
const scanResult = await runSecretScanGate(changedFiles, worktreePath);
|
|
1295
|
+
events.emit('built_in_gate_result', { gate: 'secret_scan', passed: scanResult.passed, output: scanResult.output }, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1296
|
+
if (!scanResult.passed) {
|
|
1297
|
+
await removeWorktree();
|
|
1298
|
+
const freshRecord = store.getTask(taskRecord.id, convoyId);
|
|
1299
|
+
if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
|
|
1300
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
|
|
1301
|
+
retries: freshRecord.retries + 1,
|
|
1302
|
+
worker_id: null,
|
|
1303
|
+
worktree: null,
|
|
1304
|
+
started_at: null,
|
|
1305
|
+
finished_at: null,
|
|
1306
|
+
prompt: `Secret scan gate failed.\n${scanResult.output}\n\nFix the issues and try again.\n\n${taskRecord.prompt}`,
|
|
1307
|
+
});
|
|
1308
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1309
|
+
process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} secret scan gate failed, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
|
|
1310
|
+
}
|
|
1311
|
+
else {
|
|
1312
|
+
store.withTransaction(() => {
|
|
1313
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'gate-failed', {
|
|
1314
|
+
finished_at: finishedAt,
|
|
1315
|
+
output: `Built-in gate (secret_scan) failed:\n${scanResult.output}`,
|
|
1316
|
+
exit_code: 1,
|
|
1317
|
+
});
|
|
1318
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1319
|
+
});
|
|
1320
|
+
completedCount++;
|
|
1321
|
+
process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} secret scan gate failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
|
|
1322
|
+
events.emit('task_failed', { reason: 'gate-failed', gate: 'secret_scan', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
1323
|
+
handleExhaustion(freshRecord, 'secret-scan', scanResult.output);
|
|
1324
|
+
}
|
|
1325
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1326
|
+
return;
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
// Blast radius gate
|
|
1330
|
+
if (builtInGates.blast_radius && diff) {
|
|
1331
|
+
const blastResult = runBlastRadiusGate(diff);
|
|
1332
|
+
events.emit('built_in_gate_result', { gate: 'blast_radius', level: blastResult.level, passed: blastResult.passed, output: blastResult.output }, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1333
|
+
if (!blastResult.passed) {
|
|
1334
|
+
await removeWorktree();
|
|
1335
|
+
const freshRecord = store.getTask(taskRecord.id, convoyId);
|
|
1336
|
+
if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
|
|
1337
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
|
|
1338
|
+
retries: freshRecord.retries + 1,
|
|
1339
|
+
worker_id: null,
|
|
1340
|
+
worktree: null,
|
|
1341
|
+
started_at: null,
|
|
1342
|
+
finished_at: null,
|
|
1343
|
+
prompt: `Blast radius gate failed.\n${blastResult.output}\n\nFix the issues and try again.\n\n${taskRecord.prompt}`,
|
|
1344
|
+
});
|
|
1345
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1346
|
+
process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} blast radius gate failed, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
|
|
1347
|
+
}
|
|
1348
|
+
else {
|
|
1349
|
+
store.withTransaction(() => {
|
|
1350
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'gate-failed', {
|
|
1351
|
+
finished_at: finishedAt,
|
|
1352
|
+
output: `Built-in gate (blast_radius) failed:\n${blastResult.output}`,
|
|
1353
|
+
exit_code: 1,
|
|
1354
|
+
});
|
|
1355
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1356
|
+
});
|
|
1357
|
+
completedCount++;
|
|
1358
|
+
process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} blast radius gate failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
|
|
1359
|
+
events.emit('task_failed', { reason: 'gate-failed', gate: 'blast_radius', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
1360
|
+
handleExhaustion(freshRecord, 'gate-failed', blastResult.output);
|
|
1361
|
+
}
|
|
1362
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1363
|
+
return;
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
// ── Drift detection ──────────────────────────────────────────────────
|
|
1368
|
+
const specTaskForDrift = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
|
|
1369
|
+
const isDriftEnabled = specTaskForDrift?.detect_drift ?? spec.defaults?.detect_drift ?? false;
|
|
1370
|
+
if (isDriftEnabled && taskRecord.drift_retried === 0) {
|
|
1371
|
+
const driftResult = await detectDrift(taskRecord, taskAdapter);
|
|
1372
|
+
events.emit('drift_check_result', {
|
|
1373
|
+
task_id: taskRecord.id,
|
|
1374
|
+
score: driftResult.score,
|
|
1375
|
+
threshold: driftResult.threshold,
|
|
1376
|
+
explanation: driftResult.explanation,
|
|
1377
|
+
drifted: driftResult.drifted,
|
|
1378
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1379
|
+
store.updateTaskDrift(taskRecord.id, convoyId, { drift_score: driftResult.score });
|
|
1380
|
+
if (driftResult.drifted) {
|
|
1381
|
+
events.emit('drift_detected', {
|
|
1382
|
+
task_id: taskRecord.id,
|
|
1383
|
+
score: driftResult.score,
|
|
1384
|
+
threshold: driftResult.threshold,
|
|
1385
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1386
|
+
await removeWorktree();
|
|
1387
|
+
store.updateTaskDrift(taskRecord.id, convoyId, { drift_retried: 1 });
|
|
1388
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
|
|
1389
|
+
worker_id: null,
|
|
1390
|
+
worktree: null,
|
|
1391
|
+
started_at: null,
|
|
1392
|
+
finished_at: null,
|
|
1393
|
+
});
|
|
1394
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1395
|
+
process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} drift detected (score: ${driftResult.score.toFixed(2)}), retrying\n`);
|
|
1396
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1397
|
+
return;
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
// ── Review pipeline ──────────────────────────────────────────────────
|
|
1401
|
+
const specTaskForReview = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
|
|
1402
|
+
const taskReviewSetting = specTaskForReview?.review ?? spec.defaults?.review ?? 'auto';
|
|
1403
|
+
if (taskReviewSetting !== 'none') {
|
|
1404
|
+
// Compute diff stats from worktree
|
|
1405
|
+
let reviewChangedFiles = [];
|
|
1406
|
+
let reviewDiffLines = 0;
|
|
1407
|
+
if (worktreePath) {
|
|
1408
|
+
try {
|
|
1409
|
+
const { stdout: filesOut } = await execFile('git', ['diff', '--name-only', `${baseBranch}..HEAD`], { cwd: worktreePath });
|
|
1410
|
+
reviewChangedFiles = filesOut.split('\n').filter(Boolean);
|
|
1411
|
+
const { stdout: diffOut } = await execFile('git', ['diff', `${baseBranch}..HEAD`], { cwd: worktreePath });
|
|
1412
|
+
reviewDiffLines = diffOut.split('\n').filter(l => l.startsWith('+') || l.startsWith('-')).filter(l => !l.startsWith('+++') && !l.startsWith('---')).length;
|
|
1413
|
+
}
|
|
1414
|
+
catch { /* no commits yet */ }
|
|
1415
|
+
}
|
|
1416
|
+
const diffStats = {
|
|
1417
|
+
linesChanged: reviewDiffLines,
|
|
1418
|
+
filesChanged: reviewChangedFiles.length,
|
|
1419
|
+
filePaths: reviewChangedFiles,
|
|
1420
|
+
};
|
|
1421
|
+
// Determine review level
|
|
1422
|
+
let reviewLevel;
|
|
1423
|
+
if (taskReviewSetting === 'fast') {
|
|
1424
|
+
reviewLevel = 'fast';
|
|
1425
|
+
}
|
|
1426
|
+
else if (taskReviewSetting === 'panel') {
|
|
1427
|
+
reviewLevel = 'panel';
|
|
1428
|
+
}
|
|
1429
|
+
else {
|
|
1430
|
+
reviewLevel = evaluateReviewLevel(taskRecord, diffStats, spec.defaults?.review_heuristics, true);
|
|
1431
|
+
}
|
|
1432
|
+
const reviewerModel = spec.defaults?.reviewer_model ?? 'default';
|
|
1433
|
+
events.emit('review_started', { level: reviewLevel, task_id: taskRecord.id, model: reviewerModel }, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1434
|
+
if (reviewLevel === 'auto-pass') {
|
|
1435
|
+
store.updateTaskReview(taskRecord.id, convoyId, {
|
|
1436
|
+
review_level: 'auto-pass',
|
|
1437
|
+
review_verdict: 'pass',
|
|
1438
|
+
review_tokens: 0,
|
|
1439
|
+
review_model: reviewerModel,
|
|
1440
|
+
});
|
|
1441
|
+
events.emit('review_verdict', { level: 'auto-pass', verdict: 'pass', tokens: 0, model: reviewerModel, feedback_length: 0 }, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1442
|
+
}
|
|
1443
|
+
else if (reviewLevel === 'fast') {
|
|
1444
|
+
// Check review budget
|
|
1445
|
+
const reviewBudget = spec.defaults?.review_budget;
|
|
1446
|
+
const onBudgetExceeded = spec.defaults?.on_review_budget_exceeded ?? 'skip';
|
|
1447
|
+
if (reviewBudget != null && reviewTokensTotal >= reviewBudget) {
|
|
1448
|
+
if (onBudgetExceeded === 'stop') {
|
|
1449
|
+
const allPending = store.getTasksByConvoy(convoyId).filter(t => t.status === 'pending');
|
|
1450
|
+
for (const t of allPending)
|
|
1451
|
+
skipTask(t.id, 'review_budget exceeded with on_review_budget_exceeded: stop');
|
|
1452
|
+
store.withTransaction(() => {
|
|
1453
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'review-blocked', { finished_at: finishedAt, output: 'Review budget exceeded', exit_code: 1 });
|
|
1454
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1455
|
+
});
|
|
1456
|
+
completedCount++;
|
|
1457
|
+
process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} review budget exceeded (stop) ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
|
|
1458
|
+
events.emit('review_verdict', { level: 'fast', verdict: 'skip', tokens: 0, model: reviewerModel, feedback_length: 0, budget_exceeded: true }, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1459
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1460
|
+
return;
|
|
1461
|
+
}
|
|
1462
|
+
else if (onBudgetExceeded === 'downgrade') {
|
|
1463
|
+
store.updateTaskReview(taskRecord.id, convoyId, { review_level: 'fast', review_verdict: 'pass', review_tokens: 0, review_model: reviewerModel });
|
|
1464
|
+
events.emit('review_verdict', { level: 'fast', verdict: 'pass', tokens: 0, model: reviewerModel, feedback_length: 0, budget_downgrade: true }, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1465
|
+
}
|
|
1466
|
+
else {
|
|
1467
|
+
// 'skip': treat as passed
|
|
1468
|
+
events.emit('review_verdict', { level: 'fast', verdict: 'pass', tokens: 0, model: reviewerModel, feedback_length: 0, budget_skip: true }, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1469
|
+
}
|
|
1470
|
+
}
|
|
1471
|
+
else {
|
|
1472
|
+
await reviewSemaphore.acquire();
|
|
1473
|
+
let reviewResult;
|
|
1474
|
+
try {
|
|
1475
|
+
if (reviewRunner) {
|
|
1476
|
+
reviewResult = await reviewRunner(taskRecord, 'fast', reviewerModel);
|
|
1477
|
+
}
|
|
1478
|
+
else {
|
|
1479
|
+
reviewResult = { verdict: 'pass', feedback: '', tokens: 0, model: reviewerModel };
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
finally {
|
|
1483
|
+
reviewSemaphore.release();
|
|
1484
|
+
}
|
|
1485
|
+
reviewTokensTotal += reviewResult.tokens;
|
|
1486
|
+
store.updateTaskReview(taskRecord.id, convoyId, {
|
|
1487
|
+
review_level: 'fast',
|
|
1488
|
+
review_verdict: reviewResult.verdict,
|
|
1489
|
+
review_tokens: reviewResult.tokens,
|
|
1490
|
+
review_model: reviewResult.model,
|
|
1491
|
+
});
|
|
1492
|
+
store.updateConvoyReviewTokens(convoyId, reviewTokensTotal);
|
|
1493
|
+
events.emit('review_verdict', { level: 'fast', verdict: reviewResult.verdict, tokens: reviewResult.tokens, model: reviewResult.model, feedback_length: reviewResult.feedback.length }, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1494
|
+
if (reviewResult.verdict === 'block') {
|
|
1495
|
+
await removeWorktree();
|
|
1496
|
+
const freshRecord = store.getTask(taskRecord.id, convoyId);
|
|
1497
|
+
if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
|
|
1498
|
+
const contextPrefix = `Previous attempt was blocked by review.\nFeedback:\n${reviewResult.feedback}\n\nFix the issues and try again.\n\n`;
|
|
1499
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
|
|
1500
|
+
retries: freshRecord.retries + 1,
|
|
1501
|
+
worker_id: null,
|
|
1502
|
+
worktree: null,
|
|
1503
|
+
started_at: null,
|
|
1504
|
+
finished_at: null,
|
|
1505
|
+
prompt: contextPrefix + taskRecord.prompt,
|
|
1506
|
+
});
|
|
1507
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1508
|
+
process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} review blocked, retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
|
|
1509
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1510
|
+
return;
|
|
1511
|
+
}
|
|
1512
|
+
else {
|
|
1513
|
+
store.withTransaction(() => {
|
|
1514
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'review-blocked', {
|
|
1515
|
+
finished_at: finishedAt,
|
|
1516
|
+
output: `Review blocked: ${reviewResult.feedback}`,
|
|
1517
|
+
exit_code: 1,
|
|
1518
|
+
});
|
|
1519
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1520
|
+
});
|
|
1521
|
+
completedCount++;
|
|
1522
|
+
process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} review blocked ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
|
|
1523
|
+
events.emit('task_failed', { reason: 'review-blocked', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
1524
|
+
handleExhaustion(freshRecord, 'review-blocked', reviewResult.feedback || null);
|
|
1525
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1526
|
+
return;
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
else {
|
|
1532
|
+
// panel: 3 concurrent reviewer calls, majority vote
|
|
1533
|
+
await reviewSemaphore.acquire();
|
|
1534
|
+
let panelResults;
|
|
1535
|
+
try {
|
|
1536
|
+
const noopRunner = (_t, _l, m) => Promise.resolve({ verdict: 'pass', feedback: '', tokens: 0, model: m });
|
|
1537
|
+
const runner = reviewRunner ?? noopRunner;
|
|
1538
|
+
panelResults = await Promise.all([
|
|
1539
|
+
runner(taskRecord, 'panel', reviewerModel),
|
|
1540
|
+
runner(taskRecord, 'panel', reviewerModel),
|
|
1541
|
+
runner(taskRecord, 'panel', reviewerModel),
|
|
1542
|
+
]);
|
|
1543
|
+
}
|
|
1544
|
+
finally {
|
|
1545
|
+
reviewSemaphore.release();
|
|
1546
|
+
}
|
|
1547
|
+
const panelPasses = panelResults.filter(r => r.verdict === 'pass').length;
|
|
1548
|
+
const panelBlocks = panelResults.filter(r => r.verdict === 'block').length;
|
|
1549
|
+
const totalPanelTokens = panelResults.reduce((sum, r) => sum + r.tokens, 0);
|
|
1550
|
+
reviewTokensTotal += totalPanelTokens;
|
|
1551
|
+
const freshForPanel = store.getTask(taskRecord.id, convoyId);
|
|
1552
|
+
store.updateTaskReview(taskRecord.id, convoyId, {
|
|
1553
|
+
review_level: 'panel',
|
|
1554
|
+
review_verdict: panelPasses >= 2 ? 'pass' : 'block',
|
|
1555
|
+
review_tokens: totalPanelTokens,
|
|
1556
|
+
review_model: reviewerModel,
|
|
1557
|
+
panel_attempts: freshForPanel.panel_attempts + 1,
|
|
1558
|
+
});
|
|
1559
|
+
if (totalPanelTokens > 0)
|
|
1560
|
+
store.updateConvoyReviewTokens(convoyId, reviewTokensTotal);
|
|
1561
|
+
events.emit('review_verdict', { level: 'panel', verdict: panelPasses >= 2 ? 'pass' : 'block', tokens: totalPanelTokens, model: reviewerModel, feedback_length: panelResults.map(r => r.feedback).join('').length, passes: panelPasses, blocks: panelBlocks }, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1562
|
+
if (panelBlocks >= 2) {
|
|
1563
|
+
const blockFeedback = panelResults.filter(r => r.verdict === 'block').map(r => r.feedback).join('\n\n---\n\n');
|
|
1564
|
+
await removeWorktree();
|
|
1565
|
+
// Check for dispute trigger
|
|
1566
|
+
const updatedTask = store.getTask(taskRecord.id, convoyId);
|
|
1567
|
+
if (updatedTask.panel_attempts >= 3) {
|
|
1568
|
+
const disputeId = `dispute-${taskRecord.id}-${Date.now()}`;
|
|
1569
|
+
const onDispute = spec.defaults?.on_dispute ?? 'stop';
|
|
1570
|
+
store.updateTaskDisputeStatus(taskRecord.id, convoyId, 'disputed', disputeId);
|
|
1571
|
+
writeDisputeToMarkdown(disputeId, convoyId, taskRecord, panelResults, events);
|
|
1572
|
+
events.emit('dispute_opened', {
|
|
1573
|
+
dispute_id: disputeId,
|
|
1574
|
+
task_id: taskRecord.id,
|
|
1575
|
+
agent: taskRecord.agent,
|
|
1576
|
+
panel_attempts: updatedTask.panel_attempts,
|
|
1577
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1578
|
+
if (onDispute === 'stop') {
|
|
1579
|
+
const allPending = store.getTasksByConvoy(convoyId).filter(t => t.status === 'pending');
|
|
1580
|
+
for (const t of allPending) {
|
|
1581
|
+
skipTask(t.id, `on_dispute: stop — task "${taskRecord.id}" disputed`);
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1584
|
+
completedCount++;
|
|
1585
|
+
process.stdout.write(` ${c.red('⚡')} ${c.bold(`[${taskRecord.id}]`)} disputed after ${updatedTask.panel_attempts} panel attempts\n`);
|
|
1586
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1587
|
+
return;
|
|
1588
|
+
}
|
|
1589
|
+
const freshRecord = store.getTask(taskRecord.id, convoyId);
|
|
1590
|
+
if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
|
|
1591
|
+
const contextPrefix = `Previous attempt was blocked by panel review (${panelBlocks}/3 reviewers).\nMUST-FIX:\n${blockFeedback}\n\nFix the issues and try again.\n\n`;
|
|
1592
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
|
|
1593
|
+
retries: freshRecord.retries + 1,
|
|
1594
|
+
worker_id: null,
|
|
1595
|
+
worktree: null,
|
|
1596
|
+
started_at: null,
|
|
1597
|
+
finished_at: null,
|
|
1598
|
+
prompt: contextPrefix + taskRecord.prompt,
|
|
1599
|
+
});
|
|
1600
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1601
|
+
process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} panel blocked (${panelBlocks}/3), retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
|
|
1602
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1603
|
+
return;
|
|
1604
|
+
}
|
|
1605
|
+
else {
|
|
1606
|
+
store.withTransaction(() => {
|
|
1607
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'review-blocked', {
|
|
1608
|
+
finished_at: finishedAt,
|
|
1609
|
+
output: `Panel review blocked (${panelBlocks}/3): ${blockFeedback}`,
|
|
1610
|
+
exit_code: 1,
|
|
1611
|
+
});
|
|
1612
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1613
|
+
});
|
|
1614
|
+
completedCount++;
|
|
1615
|
+
process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} panel blocked ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
|
|
1616
|
+
events.emit('task_failed', { reason: 'review-blocked', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
1617
|
+
handleExhaustion(freshRecord, 'review-blocked', blockFeedback || null);
|
|
1618
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1619
|
+
return;
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
// ── Intelligence: check discovered issues (Phase 18.4) ─────────────
|
|
1625
|
+
if (spec.defaults?.track_discovered_issues) {
|
|
1626
|
+
try {
|
|
1627
|
+
checkDiscoveredIssues(taskRecord.id, events, convoyId, worktreePath ?? basePath);
|
|
1628
|
+
}
|
|
1629
|
+
catch { /* non-critical */ }
|
|
1630
|
+
}
|
|
1631
|
+
// ── post_task hooks ───────────────────────────────────────────────────
|
|
1632
|
+
if (taskHooks.length > 0) {
|
|
1633
|
+
const postResult = await runHooks(taskHooks, 'post_task', {
|
|
1634
|
+
taskId: taskRecord.id,
|
|
1635
|
+
convoyId,
|
|
1636
|
+
cwd: worktreePath ?? basePath,
|
|
1637
|
+
});
|
|
1638
|
+
if (!postResult.passed) {
|
|
1639
|
+
await removeWorktree();
|
|
1640
|
+
const hookLabel = postResult.failedHook?.name ?? postResult.failedHook?.type ?? 'unknown';
|
|
1641
|
+
store.withTransaction(() => {
|
|
1642
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'hook-failed', {
|
|
1643
|
+
finished_at: finishedAt,
|
|
1644
|
+
output: `post_task hook "${hookLabel}" failed: ${postResult.error ?? ''}`,
|
|
1645
|
+
exit_code: 1,
|
|
1646
|
+
});
|
|
1647
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1648
|
+
});
|
|
1649
|
+
completedCount++;
|
|
1650
|
+
process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} post_task hook failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
|
|
1651
|
+
events.emit('task_failed', { reason: 'hook-failed', hook: hookLabel, worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
1652
|
+
cascadeFailure(taskRecord.id);
|
|
1653
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1654
|
+
return;
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
// ── Symlink security scan (post-execution) ───────────────────────────
|
|
1658
|
+
if (taskFiles.length > 0 && worktreePath) {
|
|
1659
|
+
try {
|
|
1660
|
+
scanNewSymlinks(worktreePath, taskFiles);
|
|
239
1661
|
}
|
|
240
1662
|
catch (err) {
|
|
241
|
-
|
|
242
|
-
|
|
1663
|
+
await removeWorktree();
|
|
1664
|
+
store.withTransaction(() => {
|
|
1665
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'failed', {
|
|
1666
|
+
finished_at: finishedAt,
|
|
1667
|
+
output: `Post-execution symlink security check failed: ${err.message}`,
|
|
1668
|
+
exit_code: 1,
|
|
1669
|
+
});
|
|
1670
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
1671
|
+
});
|
|
1672
|
+
completedCount++;
|
|
1673
|
+
events.emit('task_failed', { reason: 'symlink-escape-post', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
1674
|
+
cascadeFailure(taskRecord.id);
|
|
1675
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1676
|
+
return;
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
if (worktreePath) {
|
|
1680
|
+
let mergeAttempt = 0;
|
|
1681
|
+
const maxMergeAttempts = 2;
|
|
1682
|
+
let merged = false;
|
|
1683
|
+
while (mergeAttempt < maxMergeAttempts && !merged) {
|
|
1684
|
+
try {
|
|
1685
|
+
await mergeQueue.merge(worktreePath, `convoy-${workerId}`, baseBranch);
|
|
1686
|
+
merged = true;
|
|
1687
|
+
}
|
|
1688
|
+
catch (err) {
|
|
1689
|
+
if (err instanceof MergeConflictError) {
|
|
1690
|
+
mergeAttempt++;
|
|
1691
|
+
events.emit('merge_conflict_detected', {
|
|
1692
|
+
attempt: mergeAttempt,
|
|
1693
|
+
conflicting_files: err.conflictingFiles,
|
|
1694
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1695
|
+
if (mergeAttempt >= maxMergeAttempts) {
|
|
1696
|
+
events.emit('merge_conflict_failed', {
|
|
1697
|
+
attempts: mergeAttempt,
|
|
1698
|
+
conflicting_files: err.conflictingFiles,
|
|
1699
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1700
|
+
const freshRecord = store.getTask(taskRecord.id, convoyId);
|
|
1701
|
+
store.withTransaction(() => {
|
|
1702
|
+
store.updateTaskStatus(taskRecord.id, convoyId, 'failed', {
|
|
1703
|
+
finished_at: now(),
|
|
1704
|
+
output: `Merge conflict could not be resolved after ${mergeAttempt} attempts. Files: ${err.conflictingFiles.join(', ')}`,
|
|
1705
|
+
exit_code: 1,
|
|
1706
|
+
});
|
|
1707
|
+
store.updateWorkerStatus(workerId, 'failed', { finished_at: now() });
|
|
1708
|
+
});
|
|
1709
|
+
completedCount++;
|
|
1710
|
+
process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} merge conflict unresolved ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
|
|
1711
|
+
events.emit('task_failed', { reason: 'merge-conflict', worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
1712
|
+
cascadeFailure(taskRecord.id);
|
|
1713
|
+
handleExhaustion(freshRecord, 'merge-conflict', err.conflictingFiles.join(', '));
|
|
1714
|
+
break;
|
|
1715
|
+
}
|
|
1716
|
+
// Per spec: backoff on second attempt (unreachable with maxMergeAttempts=2 but follows spec)
|
|
1717
|
+
if (mergeAttempt === 2) {
|
|
1718
|
+
await new Promise(resolve => setTimeout(resolve, 30_000));
|
|
1719
|
+
}
|
|
1720
|
+
// Inject a resolution task
|
|
1721
|
+
const fileHash = createHash('sha256')
|
|
1722
|
+
.update(err.conflictingFiles.sort().join(','))
|
|
1723
|
+
.digest('hex')
|
|
1724
|
+
.slice(0, 12);
|
|
1725
|
+
const idempotencyKey = `merge-conflict:${taskRecord.phase}:${fileHash}`;
|
|
1726
|
+
const resolutionTaskId = `merge-fix-${taskRecord.id}-${mergeAttempt}`;
|
|
1727
|
+
const conflictPrompt = `Resolve merge conflicts in: ${err.conflictingFiles.join(', ')}. Ensure no conflict markers remain (<<<<<<<, =======, >>>>>>>), syntax is valid, no duplicate imports.`;
|
|
1728
|
+
const resolutionRecord = {
|
|
1729
|
+
id: resolutionTaskId,
|
|
1730
|
+
convoy_id: convoyId,
|
|
1731
|
+
phase: taskRecord.phase,
|
|
1732
|
+
prompt: conflictPrompt,
|
|
1733
|
+
agent: taskRecord.agent,
|
|
1734
|
+
adapter: null,
|
|
1735
|
+
model: null,
|
|
1736
|
+
timeout_ms: 600_000,
|
|
1737
|
+
status: 'pending',
|
|
1738
|
+
worker_id: null,
|
|
1739
|
+
worktree: null,
|
|
1740
|
+
output: null,
|
|
1741
|
+
exit_code: null,
|
|
1742
|
+
started_at: null,
|
|
1743
|
+
finished_at: null,
|
|
1744
|
+
retries: 0,
|
|
1745
|
+
max_retries: 1,
|
|
1746
|
+
files: JSON.stringify(err.conflictingFiles),
|
|
1747
|
+
depends_on: null,
|
|
1748
|
+
prompt_tokens: null,
|
|
1749
|
+
completion_tokens: null,
|
|
1750
|
+
total_tokens: null,
|
|
1751
|
+
cost_usd: null,
|
|
1752
|
+
gates: null,
|
|
1753
|
+
on_exhausted: 'dlq',
|
|
1754
|
+
injected: 1,
|
|
1755
|
+
provenance: 'merge-conflict',
|
|
1756
|
+
idempotency_key: idempotencyKey,
|
|
1757
|
+
current_step: null,
|
|
1758
|
+
total_steps: null,
|
|
1759
|
+
review_level: null,
|
|
1760
|
+
review_verdict: null,
|
|
1761
|
+
review_tokens: null,
|
|
1762
|
+
review_model: null,
|
|
1763
|
+
panel_attempts: 0,
|
|
1764
|
+
dispute_id: null,
|
|
1765
|
+
drift_score: null,
|
|
1766
|
+
drift_retried: 0,
|
|
1767
|
+
outputs: null,
|
|
1768
|
+
inputs: null,
|
|
1769
|
+
discovered_issues: null,
|
|
1770
|
+
};
|
|
1771
|
+
store.insertInjectedTask(resolutionRecord);
|
|
1772
|
+
const storedResolutionRecord = store.getTask(resolutionTaskId, convoyId);
|
|
1773
|
+
await executeOneTask(storedResolutionRecord);
|
|
1774
|
+
// Next loop iteration will retry the merge
|
|
1775
|
+
}
|
|
1776
|
+
else {
|
|
1777
|
+
// Non-conflict merge error — log warning and continue to done path
|
|
1778
|
+
if (verbose) {
|
|
1779
|
+
process.stderr.write(`Warning: merge failed for ${taskRecord.id}: ${err.message}\n`);
|
|
1780
|
+
}
|
|
1781
|
+
merged = true; // Preserve original behavior: continue despite error
|
|
1782
|
+
break;
|
|
1783
|
+
}
|
|
243
1784
|
}
|
|
244
1785
|
}
|
|
245
1786
|
await removeWorktree();
|
|
1787
|
+
if (!merged) {
|
|
1788
|
+
taskAdapterMap.delete(taskRecord.id);
|
|
1789
|
+
return;
|
|
1790
|
+
}
|
|
1791
|
+
// ── Intelligence: update expertise post-merge (Phase 18.2) ─────────
|
|
1792
|
+
try {
|
|
1793
|
+
updateExpertise(taskRecord.agent, { taskId: taskRecord.id, success: true, retries: taskRecord.retries, files: taskRecord.files ? JSON.parse(taskRecord.files) : [] }, basePath);
|
|
1794
|
+
}
|
|
1795
|
+
catch { /* non-critical */ }
|
|
1796
|
+
// ── Intelligence: build knowledge graph post-merge (Phase 18.3) ────
|
|
1797
|
+
try {
|
|
1798
|
+
const { stdout: diffOut } = await execFile('git', ['diff', 'HEAD~1'], { cwd: basePath });
|
|
1799
|
+
buildKnowledgeGraph(diffOut, convoyId, basePath);
|
|
1800
|
+
}
|
|
1801
|
+
catch { /* non-critical */ }
|
|
246
1802
|
}
|
|
247
1803
|
const usageExtra = {};
|
|
248
1804
|
if (result.usage) {
|
|
@@ -253,6 +1809,80 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
253
1809
|
if (result.usage.total_tokens != null)
|
|
254
1810
|
usageExtra.total_tokens = result.usage.total_tokens;
|
|
255
1811
|
}
|
|
1812
|
+
// ── Capture outputs as artifacts ────────────────────────────────────────
|
|
1813
|
+
if (taskRecord.outputs) {
|
|
1814
|
+
const outputs = JSON.parse(taskRecord.outputs);
|
|
1815
|
+
for (const output of outputs) {
|
|
1816
|
+
let content;
|
|
1817
|
+
if (output.type === 'summary') {
|
|
1818
|
+
content = result.output.slice(-4096);
|
|
1819
|
+
}
|
|
1820
|
+
else if (output.type === 'json') {
|
|
1821
|
+
const jsonMatch = result.output.match(/```json\n([\s\S]*?)```/);
|
|
1822
|
+
content = jsonMatch ? jsonMatch[1].trim() : result.output;
|
|
1823
|
+
}
|
|
1824
|
+
else {
|
|
1825
|
+
content = result.output;
|
|
1826
|
+
}
|
|
1827
|
+
try {
|
|
1828
|
+
store.insertArtifact({
|
|
1829
|
+
id: `artifact-${taskRecord.id}-${output.name}-${Date.now()}`,
|
|
1830
|
+
convoy_id: convoyId,
|
|
1831
|
+
task_id: taskRecord.id,
|
|
1832
|
+
name: output.name,
|
|
1833
|
+
type: output.type,
|
|
1834
|
+
content,
|
|
1835
|
+
created_at: new Date().toISOString(),
|
|
1836
|
+
});
|
|
1837
|
+
}
|
|
1838
|
+
catch (err) {
|
|
1839
|
+
if (err instanceof ConvoyArtifactLimitError) {
|
|
1840
|
+
events.emit('artifact_limit_reached', {
|
|
1841
|
+
task_id: taskRecord.id,
|
|
1842
|
+
artifact_name: output.name,
|
|
1843
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1844
|
+
}
|
|
1845
|
+
else {
|
|
1846
|
+
throw err;
|
|
1847
|
+
}
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
// ── Intelligence: capture persistent agent identity (Phase 17.2) ─────
|
|
1852
|
+
const specTaskForCapture = (spec.tasks ?? []).find(t => t.id === taskRecord.id);
|
|
1853
|
+
if (specTaskForCapture?.persistent && result.output) {
|
|
1854
|
+
try {
|
|
1855
|
+
// Extract last 300 words, cap at 4KB
|
|
1856
|
+
const words = result.output.split(/\s+/);
|
|
1857
|
+
const lastWords = words.slice(-300).join(' ');
|
|
1858
|
+
let summary = lastWords.length > 4096 ? lastWords.slice(-4096) : lastWords;
|
|
1859
|
+
// Secret-scan the summary before storing
|
|
1860
|
+
const summaryScan = scanForSecrets(summary, `identity:${taskRecord.id}`);
|
|
1861
|
+
if (summaryScan.clean) {
|
|
1862
|
+
store.insertAgentIdentity({
|
|
1863
|
+
id: `identity-${taskRecord.id}-${Date.now()}`,
|
|
1864
|
+
agent: taskRecord.agent,
|
|
1865
|
+
convoy_id: convoyId,
|
|
1866
|
+
task_id: taskRecord.id,
|
|
1867
|
+
summary,
|
|
1868
|
+
created_at: new Date().toISOString(),
|
|
1869
|
+
retention_days: 90,
|
|
1870
|
+
});
|
|
1871
|
+
events.emit('agent_identity_captured', {
|
|
1872
|
+
agent: taskRecord.agent,
|
|
1873
|
+
summary_length: summary.length,
|
|
1874
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1875
|
+
}
|
|
1876
|
+
else {
|
|
1877
|
+
events.emit('agent_identity_rejected', {
|
|
1878
|
+
agent: taskRecord.agent,
|
|
1879
|
+
reason: 'secrets_detected',
|
|
1880
|
+
findings_count: summaryScan.findings.length,
|
|
1881
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1882
|
+
}
|
|
1883
|
+
}
|
|
1884
|
+
catch { /* non-critical */ }
|
|
1885
|
+
}
|
|
256
1886
|
store.withTransaction(() => {
|
|
257
1887
|
store.updateTaskStatus(taskRecord.id, convoyId, 'done', {
|
|
258
1888
|
finished_at: finishedAt,
|
|
@@ -262,6 +1892,28 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
262
1892
|
});
|
|
263
1893
|
store.updateWorkerStatus(workerId, 'done', { finished_at: finishedAt });
|
|
264
1894
|
});
|
|
1895
|
+
// ── Circuit breaker: record success ────────────────────────────────────
|
|
1896
|
+
if (circuitBreakerConfig) {
|
|
1897
|
+
circuitBreaker.recordSuccess(taskRecord.agent);
|
|
1898
|
+
try {
|
|
1899
|
+
store.updateConvoyCircuitState(convoyId, circuitBreaker.serialize());
|
|
1900
|
+
}
|
|
1901
|
+
catch { /* non-critical */ }
|
|
1902
|
+
}
|
|
1903
|
+
// ── Intelligence: capture retry lesson (Phase 18.1) ─────────────────
|
|
1904
|
+
if (taskRecord.retries > 0 && spec.defaults?.inject_lessons !== false) {
|
|
1905
|
+
try {
|
|
1906
|
+
captureLessons({
|
|
1907
|
+
title: `Retry success for ${taskRecord.agent} on ${taskRecord.id}`,
|
|
1908
|
+
category: 'convoy',
|
|
1909
|
+
agent: taskRecord.agent,
|
|
1910
|
+
problem: `Task ${taskRecord.id} required ${taskRecord.retries} retries`,
|
|
1911
|
+
solution: 'Succeeded after retry with adjusted approach',
|
|
1912
|
+
files: taskRecord.files ? JSON.parse(taskRecord.files) : undefined,
|
|
1913
|
+
}, basePath);
|
|
1914
|
+
}
|
|
1915
|
+
catch { /* non-critical */ }
|
|
1916
|
+
}
|
|
265
1917
|
completedCount++;
|
|
266
1918
|
process.stdout.write(` ${c.green('✓')} ${c.bold(`[${taskRecord.id}]`)} ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
|
|
267
1919
|
events.emit('task_done', { exit_code: result.exitCode, worker_id: workerId }, { convoy_id: convoyId, task_id: taskRecord.id, worker_id: workerId });
|
|
@@ -295,12 +1947,15 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
295
1947
|
await removeWorktree();
|
|
296
1948
|
const freshRecord = store.getTask(taskRecord.id, convoyId);
|
|
297
1949
|
if (freshRecord.retries < freshRecord.max_retries && spec.on_failure !== 'stop') {
|
|
1950
|
+
const failedOutput = result.output || '(no output)';
|
|
1951
|
+
const contextPrefix = `Previous attempt failed.\nExit code: ${result.exitCode}\nError output:\n${failedOutput}\n\nFix the issues and try again.\n\n`;
|
|
298
1952
|
store.updateTaskStatus(taskRecord.id, convoyId, 'pending', {
|
|
299
1953
|
retries: freshRecord.retries + 1,
|
|
300
1954
|
worker_id: null,
|
|
301
1955
|
worktree: null,
|
|
302
1956
|
started_at: null,
|
|
303
1957
|
finished_at: null,
|
|
1958
|
+
prompt: contextPrefix + taskRecord.prompt,
|
|
304
1959
|
});
|
|
305
1960
|
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
306
1961
|
process.stdout.write(` ${c.yellow('⟳')} ${c.bold(`[${taskRecord.id}]`)} retry ${freshRecord.retries + 1}/${freshRecord.max_retries}\n`);
|
|
@@ -314,6 +1969,25 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
314
1969
|
});
|
|
315
1970
|
store.updateWorkerStatus(workerId, 'failed', { finished_at: finishedAt });
|
|
316
1971
|
});
|
|
1972
|
+
// ── Intelligence: record failure in expertise (Phase 18.2) ──────────
|
|
1973
|
+
try {
|
|
1974
|
+
updateExpertise(taskRecord.agent, { taskId: taskRecord.id, success: false, retries: freshRecord.retries, files: taskRecord.files ? JSON.parse(taskRecord.files) : [] }, basePath);
|
|
1975
|
+
}
|
|
1976
|
+
catch { /* non-critical */ }
|
|
1977
|
+
// ── Circuit breaker: record failure ────────────────────────────────────
|
|
1978
|
+
if (circuitBreakerConfig) {
|
|
1979
|
+
const { tripped } = circuitBreaker.recordFailure(taskRecord.agent);
|
|
1980
|
+
try {
|
|
1981
|
+
store.updateConvoyCircuitState(convoyId, circuitBreaker.serialize());
|
|
1982
|
+
}
|
|
1983
|
+
catch { /* non-critical */ }
|
|
1984
|
+
if (tripped) {
|
|
1985
|
+
events.emit('circuit_breaker_tripped', {
|
|
1986
|
+
agent: taskRecord.agent,
|
|
1987
|
+
state: circuitBreaker.getState(taskRecord.agent),
|
|
1988
|
+
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
317
1991
|
completedCount++;
|
|
318
1992
|
process.stdout.write(` ${c.red('✗')} ${c.bold(`[${taskRecord.id}]`)} failed ${elapsed} ${c.dim(`[${completedCount}/${totalTasks}]`)}\n`);
|
|
319
1993
|
if (verbose) {
|
|
@@ -342,26 +2016,52 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
342
2016
|
phase: taskRecord.phase,
|
|
343
2017
|
convoy_id: convoyId,
|
|
344
2018
|
}, { convoy_id: convoyId, task_id: taskRecord.id });
|
|
345
|
-
|
|
2019
|
+
handleExhaustion(freshRecord, 'error', result.output || null);
|
|
346
2020
|
}
|
|
347
2021
|
taskAdapterMap.delete(taskRecord.id);
|
|
348
2022
|
}
|
|
349
2023
|
// ── Main execution loop ───────────────────────────────────────────────────
|
|
350
2024
|
let lastPhase = -1;
|
|
2025
|
+
const isSwarmMode = spec.concurrency === 'auto';
|
|
2026
|
+
const maxSwarmConcurrency = spec.defaults?.max_swarm_concurrency ?? 8;
|
|
2027
|
+
let lastInjectPoll = 0;
|
|
2028
|
+
const INJECT_POLL_INTERVAL = 2000; // 2 seconds
|
|
351
2029
|
try {
|
|
352
2030
|
let ready = store.getReadyTasks(convoyId);
|
|
353
|
-
const concurrency = spec.concurrency ?? 1;
|
|
354
2031
|
while (ready.length > 0) {
|
|
2032
|
+
// Compute effective concurrency for this phase
|
|
2033
|
+
const effectiveConcurrency = isSwarmMode
|
|
2034
|
+
? Math.min(ready.length, maxSwarmConcurrency)
|
|
2035
|
+
: (typeof spec.concurrency === 'number' ? spec.concurrency : 1);
|
|
355
2036
|
for (const t of ready) {
|
|
356
2037
|
if (t.phase !== lastPhase) {
|
|
357
2038
|
lastPhase = t.phase;
|
|
358
2039
|
const tasksInPhase = ready.filter(r => r.phase === t.phase);
|
|
359
2040
|
const ids = tasksInPhase.map(r => r.id).join(', ');
|
|
360
2041
|
process.stdout.write(`\n ${c.bold(`Phase ${t.phase + 1}:`)} ${c.dim(ids)}\n`);
|
|
2042
|
+
if (isSwarmMode) {
|
|
2043
|
+
events.emit('swarm_concurrency_update', {
|
|
2044
|
+
phase: t.phase,
|
|
2045
|
+
pending_count: ready.length,
|
|
2046
|
+
effective_concurrency: effectiveConcurrency,
|
|
2047
|
+
}, { convoy_id: convoyId });
|
|
2048
|
+
}
|
|
361
2049
|
}
|
|
362
2050
|
}
|
|
363
|
-
for (let i = 0; i < ready.length; i +=
|
|
364
|
-
|
|
2051
|
+
for (let i = 0; i < ready.length; i += effectiveConcurrency) {
|
|
2052
|
+
// Poll for file-based injection between batches
|
|
2053
|
+
const now = Date.now();
|
|
2054
|
+
if (now - lastInjectPoll >= INJECT_POLL_INTERVAL) {
|
|
2055
|
+
pollInjectFile(convoyId, store, events, basePath);
|
|
2056
|
+
lastInjectPoll = now;
|
|
2057
|
+
}
|
|
2058
|
+
await Promise.all(ready.slice(i, i + effectiveConcurrency).map(t => executeOneTask(t)));
|
|
2059
|
+
}
|
|
2060
|
+
// Reset wait-for-input tasks to pending so they are re-evaluated after
|
|
2061
|
+
// upstream artifacts may have been captured in this batch
|
|
2062
|
+
const waitingTasks = store.getTasksByConvoy(convoyId).filter(t => t.status === 'wait-for-input');
|
|
2063
|
+
for (const wt of waitingTasks) {
|
|
2064
|
+
store.updateTaskStatus(wt.id, convoyId, 'pending');
|
|
365
2065
|
}
|
|
366
2066
|
ready = store.getReadyTasks(convoyId);
|
|
367
2067
|
}
|
|
@@ -380,6 +2080,8 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
380
2080
|
process.stdout.write(`\n ${c.bold(gateAttempt === 0 ? 'Gates:' : `Gates (retry ${gateAttempt}/${maxGateRetries}):`)}\n`);
|
|
381
2081
|
for (const command of spec.gates) {
|
|
382
2082
|
try {
|
|
2083
|
+
// SECURITY: Gate/hook commands come from the .convoy.yml spec file, which is operator-controlled.
|
|
2084
|
+
// They are NOT user-supplied and are part of the trusted build configuration.
|
|
383
2085
|
await execFile('sh', ['-c', command], { cwd: basePath });
|
|
384
2086
|
gateResults.push({ command, exitCode: 0, passed: true });
|
|
385
2087
|
process.stdout.write(` ${c.green('✓')} ${c.dim(command)}\n`);
|
|
@@ -425,12 +2127,41 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
425
2127
|
break; // Don't retry if the fix task itself fails
|
|
426
2128
|
}
|
|
427
2129
|
}
|
|
2130
|
+
// ── post_convoy hooks ─────────────────────────────────────────────────────
|
|
2131
|
+
const specLevelHooks = spec.hooks ?? [];
|
|
2132
|
+
if (specLevelHooks.length > 0) {
|
|
2133
|
+
const postConvoyResult = await runHooks(specLevelHooks, 'post_convoy', {
|
|
2134
|
+
convoyId,
|
|
2135
|
+
cwd: basePath,
|
|
2136
|
+
});
|
|
2137
|
+
if (!postConvoyResult.passed) {
|
|
2138
|
+
const hookLabel = postConvoyResult.failedHook?.name ?? postConvoyResult.failedHook?.type ?? 'unknown';
|
|
2139
|
+
events.emit('post_convoy_hook_failed', {
|
|
2140
|
+
hook: hookLabel,
|
|
2141
|
+
error: postConvoyResult.error,
|
|
2142
|
+
}, { convoy_id: convoyId });
|
|
2143
|
+
process.stdout.write(` ${c.red('✗')} post_convoy hook "${hookLabel}" failed\n`);
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
// ── Intelligence: post-convoy consolidation ──────────────────────────────
|
|
2147
|
+
if (spec.defaults?.inject_lessons !== false) {
|
|
2148
|
+
try {
|
|
2149
|
+
consolidateLessons(basePath);
|
|
2150
|
+
}
|
|
2151
|
+
catch { /* non-critical */ }
|
|
2152
|
+
}
|
|
2153
|
+
if (spec.defaults?.track_discovered_issues) {
|
|
2154
|
+
try {
|
|
2155
|
+
consolidateIssues(basePath);
|
|
2156
|
+
}
|
|
2157
|
+
catch { /* non-critical */ }
|
|
2158
|
+
}
|
|
428
2159
|
// ── Final status & summary ────────────────────────────────────────────────
|
|
429
2160
|
const allTasksFinal = store.getTasksByConvoy(convoyId);
|
|
430
2161
|
const summary = {
|
|
431
2162
|
total: allTasksFinal.length,
|
|
432
2163
|
done: allTasksFinal.filter(t => t.status === 'done').length,
|
|
433
|
-
failed: allTasksFinal.filter(t => t.status === 'failed').length,
|
|
2164
|
+
failed: allTasksFinal.filter(t => t.status === 'failed' || t.status === 'gate-failed' || t.status === 'review-blocked' || t.status === 'disputed').length,
|
|
434
2165
|
skipped: allTasksFinal.filter(t => t.status === 'skipped').length,
|
|
435
2166
|
timedOut: allTasksFinal.filter(t => t.status === 'timed-out').length,
|
|
436
2167
|
};
|
|
@@ -451,6 +2182,24 @@ async function runConvoy(convoyId, spec, adapter, store, events, wtManager, merg
|
|
|
451
2182
|
finished_at: new Date().toISOString(),
|
|
452
2183
|
total_tokens: convoyTotalTokens,
|
|
453
2184
|
});
|
|
2185
|
+
if (finalStatus === 'done') {
|
|
2186
|
+
events.emit('convoy_finished', { status: 'done' }, { convoy_id: convoyId });
|
|
2187
|
+
}
|
|
2188
|
+
else {
|
|
2189
|
+
events.emit('convoy_failed', { status: finalStatus, reason: finalStatus === 'gate-failed' ? 'Gate check failed' : 'One or more tasks failed' }, { convoy_id: convoyId });
|
|
2190
|
+
}
|
|
2191
|
+
// Run convoy guard checks
|
|
2192
|
+
const guardResult = runConvoyGuard(store, convoyId, wtManager, ndjsonPath, spec.guard);
|
|
2193
|
+
if (guardResult.warnings.length > 0) {
|
|
2194
|
+
process.stdout.write(`\n ${c.yellow('Guard warnings:')}\n`);
|
|
2195
|
+
for (const w of guardResult.warnings) {
|
|
2196
|
+
process.stdout.write(` ${c.dim('⚠')} ${w}\n`);
|
|
2197
|
+
}
|
|
2198
|
+
events.emit('convoy_guard', {
|
|
2199
|
+
passed: guardResult.passed,
|
|
2200
|
+
warnings: guardResult.warnings,
|
|
2201
|
+
}, { convoy_id: convoyId });
|
|
2202
|
+
}
|
|
454
2203
|
return {
|
|
455
2204
|
convoyId,
|
|
456
2205
|
status: finalStatus,
|
|
@@ -481,9 +2230,44 @@ export function createConvoyEngine(options) {
|
|
|
481
2230
|
const convoyId = `convoy-${startTime}`;
|
|
482
2231
|
const specHash = createHash('sha256').update(specYaml).digest('hex');
|
|
483
2232
|
const baseBranch = spec.branch ?? (await getCurrentBranch());
|
|
2233
|
+
// Ensure target branch exists before acquiring any locks.
|
|
2234
|
+
// Uses _ensureBranch injection so callers/tests can override.
|
|
2235
|
+
if (spec.branch !== undefined) {
|
|
2236
|
+
const branchFn = options._ensureBranch ?? ensureBranch;
|
|
2237
|
+
await branchFn(spec.branch, basePath);
|
|
2238
|
+
}
|
|
484
2239
|
mkdirSync(dirname(dbPath), { recursive: true });
|
|
2240
|
+
const lockDb = new DatabaseSync(dbPath);
|
|
2241
|
+
lockDb.exec('PRAGMA journal_mode = WAL');
|
|
2242
|
+
lockDb.exec(`CREATE TABLE IF NOT EXISTS engine_lock (
|
|
2243
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
2244
|
+
pid INTEGER NOT NULL,
|
|
2245
|
+
hostname TEXT NOT NULL,
|
|
2246
|
+
started_at TEXT NOT NULL,
|
|
2247
|
+
last_heartbeat TEXT NOT NULL
|
|
2248
|
+
)`);
|
|
2249
|
+
const lock = (() => {
|
|
2250
|
+
try {
|
|
2251
|
+
return acquireEngineLock(lockDb, dbPath);
|
|
2252
|
+
}
|
|
2253
|
+
catch (err) {
|
|
2254
|
+
lockDb.close();
|
|
2255
|
+
throw err;
|
|
2256
|
+
}
|
|
2257
|
+
})();
|
|
2258
|
+
const versionRow = lockDb.prepare('SELECT sqlite_version() as v').get();
|
|
2259
|
+
const [major, minor] = versionRow.v.split('.').map(Number);
|
|
2260
|
+
if (major < 3 || (major === 3 && minor < 35)) {
|
|
2261
|
+
lock.release();
|
|
2262
|
+
lockDb.close();
|
|
2263
|
+
throw new Error(`SQLite version ${versionRow.v} is too old. Requires >= 3.35.0`);
|
|
2264
|
+
}
|
|
2265
|
+
lock.startHeartbeat();
|
|
485
2266
|
const store = createConvoyStore(dbPath);
|
|
486
|
-
const
|
|
2267
|
+
const ndjsonPath = options.logsDir
|
|
2268
|
+
? join(options.logsDir, 'convoys', `${convoyId}.ndjson`)
|
|
2269
|
+
: ndjsonPathForConvoy(convoyId, basePath);
|
|
2270
|
+
const events = createEventEmitter(store, { ndjsonPath });
|
|
487
2271
|
const wtManager = options._worktreeManager ?? createWorktreeManager(basePath);
|
|
488
2272
|
const mergeQueue = options._mergeQueue ?? createMergeQueue(basePath);
|
|
489
2273
|
let result;
|
|
@@ -500,6 +2284,15 @@ export function createConvoyEngine(options) {
|
|
|
500
2284
|
});
|
|
501
2285
|
const tasks = spec.tasks ?? [];
|
|
502
2286
|
const phases = buildPhases(tasks);
|
|
2287
|
+
// Validate file partitions before inserting tasks
|
|
2288
|
+
const partitionResult = validateFilePartitions(tasks, phases);
|
|
2289
|
+
if (!partitionResult.valid) {
|
|
2290
|
+
const conflictSummary = partitionResult.conflicts
|
|
2291
|
+
.map((cf) => `Phase ${cf.phase}: tasks "${cf.taskA}" and "${cf.taskB}" overlap on [${cf.overlapping.join(', ')}]`)
|
|
2292
|
+
.join('\n');
|
|
2293
|
+
events.emit('file_partition_conflict', { conflicts: partitionResult.conflicts }, { convoy_id: convoyId });
|
|
2294
|
+
throw new Error(`File partition conflicts detected:\n${conflictSummary}`);
|
|
2295
|
+
}
|
|
503
2296
|
for (let phaseIdx = 0; phaseIdx < phases.length; phaseIdx++) {
|
|
504
2297
|
for (const task of phases[phaseIdx]) {
|
|
505
2298
|
store.insertTask({
|
|
@@ -516,27 +2309,62 @@ export function createConvoyEngine(options) {
|
|
|
516
2309
|
max_retries: task.max_retries,
|
|
517
2310
|
files: task.files.length > 0 ? JSON.stringify(task.files) : null,
|
|
518
2311
|
depends_on: task.depends_on.length > 0 ? JSON.stringify(task.depends_on) : null,
|
|
2312
|
+
gates: task.gates && task.gates.length > 0 ? JSON.stringify(task.gates) : null,
|
|
2313
|
+
outputs: task.outputs && task.outputs.length > 0 ? JSON.stringify(task.outputs) : null,
|
|
2314
|
+
inputs: task.inputs && task.inputs.length > 0 ? JSON.stringify(task.inputs) : null,
|
|
519
2315
|
});
|
|
520
2316
|
}
|
|
521
2317
|
}
|
|
522
2318
|
store.updateConvoyStatus(convoyId, 'running', { started_at: new Date().toISOString() });
|
|
523
2319
|
events.emit('convoy_started', { name: spec.name }, { convoy_id: convoyId });
|
|
524
|
-
result = await runConvoy(convoyId, spec, adapter, store, events, wtManager, mergeQueue, basePath, baseBranch, verbose, startTime);
|
|
2320
|
+
result = await runConvoy(convoyId, spec, adapter, store, events, wtManager, mergeQueue, basePath, baseBranch, verbose, startTime, ndjsonPath, options._reviewRunner);
|
|
525
2321
|
}
|
|
526
2322
|
finally {
|
|
527
2323
|
try {
|
|
528
2324
|
await exportConvoyToNdjson(store, convoyId, options.logsDir);
|
|
529
2325
|
}
|
|
530
2326
|
catch { /* silent */ }
|
|
2327
|
+
events.close();
|
|
531
2328
|
store.close();
|
|
2329
|
+
lock.release();
|
|
2330
|
+
lockDb.close();
|
|
532
2331
|
}
|
|
533
2332
|
return result;
|
|
534
2333
|
}
|
|
535
2334
|
async function resume(convoyId) {
|
|
536
2335
|
const startTime = Date.now();
|
|
537
2336
|
mkdirSync(dirname(dbPath), { recursive: true });
|
|
2337
|
+
const lockDb = new DatabaseSync(dbPath);
|
|
2338
|
+
lockDb.exec('PRAGMA journal_mode = WAL');
|
|
2339
|
+
lockDb.exec(`CREATE TABLE IF NOT EXISTS engine_lock (
|
|
2340
|
+
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
2341
|
+
pid INTEGER NOT NULL,
|
|
2342
|
+
hostname TEXT NOT NULL,
|
|
2343
|
+
started_at TEXT NOT NULL,
|
|
2344
|
+
last_heartbeat TEXT NOT NULL
|
|
2345
|
+
)`);
|
|
2346
|
+
const lock = (() => {
|
|
2347
|
+
try {
|
|
2348
|
+
return acquireEngineLock(lockDb, dbPath);
|
|
2349
|
+
}
|
|
2350
|
+
catch (err) {
|
|
2351
|
+
lockDb.close();
|
|
2352
|
+
throw err;
|
|
2353
|
+
}
|
|
2354
|
+
})();
|
|
2355
|
+
const versionRow = lockDb.prepare('SELECT sqlite_version() as v').get();
|
|
2356
|
+
const [major, minor] = versionRow.v.split('.').map(Number);
|
|
2357
|
+
if (major < 3 || (major === 3 && minor < 35)) {
|
|
2358
|
+
lock.release();
|
|
2359
|
+
lockDb.close();
|
|
2360
|
+
throw new Error(`SQLite version ${versionRow.v} is too old. Requires >= 3.35.0`);
|
|
2361
|
+
}
|
|
2362
|
+
lock.startHeartbeat();
|
|
538
2363
|
const store = createConvoyStore(dbPath);
|
|
539
|
-
const
|
|
2364
|
+
const ndjsonPath = options.logsDir
|
|
2365
|
+
? join(options.logsDir, 'convoys', `${convoyId}.ndjson`)
|
|
2366
|
+
: ndjsonPathForConvoy(convoyId, basePath);
|
|
2367
|
+
const events = createEventEmitter(store, { ndjsonPath });
|
|
540
2368
|
const wtManager = options._worktreeManager ?? createWorktreeManager(basePath);
|
|
541
2369
|
const mergeQueue = options._mergeQueue ?? createMergeQueue(basePath);
|
|
542
2370
|
let result;
|
|
@@ -570,18 +2398,198 @@ export function createConvoyEngine(options) {
|
|
|
570
2398
|
}
|
|
571
2399
|
// Remove all orphaned worktrees from the crashed run
|
|
572
2400
|
await wtManager.removeAll();
|
|
2401
|
+
// NDJSON recovery: truncate partial lines, replay missing events
|
|
2402
|
+
recoverNdjson(store, convoyId, ndjsonPath);
|
|
573
2403
|
events.emit('convoy_resumed', { original_created_at: convoy.created_at }, { convoy_id: convoyId });
|
|
574
|
-
result = await runConvoy(convoyId, spec, adapter, store, events, wtManager, mergeQueue, basePath, baseBranch, verbose, startTime);
|
|
2404
|
+
result = await runConvoy(convoyId, spec, adapter, store, events, wtManager, mergeQueue, basePath, baseBranch, verbose, startTime, ndjsonPath, options._reviewRunner);
|
|
575
2405
|
}
|
|
576
2406
|
finally {
|
|
577
2407
|
try {
|
|
578
2408
|
await exportConvoyToNdjson(store, convoyId, options.logsDir);
|
|
579
2409
|
}
|
|
580
2410
|
catch { /* silent */ }
|
|
2411
|
+
events.close();
|
|
581
2412
|
store.close();
|
|
2413
|
+
lock.release();
|
|
2414
|
+
lockDb.close();
|
|
582
2415
|
}
|
|
583
2416
|
return result;
|
|
584
2417
|
}
|
|
585
|
-
|
|
2418
|
+
async function retryFailed(convoyId, taskIds) {
|
|
2419
|
+
mkdirSync(dirname(dbPath), { recursive: true });
|
|
2420
|
+
const store = createConvoyStore(dbPath);
|
|
2421
|
+
const ndjsonPath = options.logsDir
|
|
2422
|
+
? join(options.logsDir, 'convoys', `${convoyId}.ndjson`)
|
|
2423
|
+
: ndjsonPathForConvoy(convoyId, basePath);
|
|
2424
|
+
const events = createEventEmitter(store, { ndjsonPath });
|
|
2425
|
+
try {
|
|
2426
|
+
const allTasks = store.getTasksByConvoy(convoyId);
|
|
2427
|
+
const retryableStatuses = ['failed', 'gate-failed', 'timed-out', 'review-blocked', 'disputed'];
|
|
2428
|
+
const tasksToRetry = allTasks.filter(t => {
|
|
2429
|
+
if (!retryableStatuses.includes(t.status))
|
|
2430
|
+
return false;
|
|
2431
|
+
if (taskIds && taskIds.length > 0)
|
|
2432
|
+
return taskIds.includes(t.id);
|
|
2433
|
+
return true;
|
|
2434
|
+
});
|
|
2435
|
+
for (const task of tasksToRetry) {
|
|
2436
|
+
store.updateTaskStatus(task.id, convoyId, 'pending', {
|
|
2437
|
+
worker_id: null,
|
|
2438
|
+
worktree: null,
|
|
2439
|
+
started_at: null,
|
|
2440
|
+
finished_at: null,
|
|
2441
|
+
});
|
|
2442
|
+
events.emit('task_retried', { previous_status: task.status }, { convoy_id: convoyId, task_id: task.id });
|
|
2443
|
+
}
|
|
2444
|
+
// Reset convoy status to running so resume can pick it up
|
|
2445
|
+
store.updateConvoyStatus(convoyId, 'running', {});
|
|
2446
|
+
}
|
|
2447
|
+
finally {
|
|
2448
|
+
events.close();
|
|
2449
|
+
store.close();
|
|
2450
|
+
}
|
|
2451
|
+
}
|
|
2452
|
+
function injectTask(convoyId, task) {
|
|
2453
|
+
mkdirSync(dirname(dbPath), { recursive: true });
|
|
2454
|
+
const store = createConvoyStore(dbPath);
|
|
2455
|
+
try {
|
|
2456
|
+
// Idempotency check
|
|
2457
|
+
if (task.idempotency_key) {
|
|
2458
|
+
const existing = store.getTaskByIdempotencyKey(convoyId, task.idempotency_key);
|
|
2459
|
+
if (existing)
|
|
2460
|
+
return existing;
|
|
2461
|
+
}
|
|
2462
|
+
const allTasks = store.getTasksByConvoy(convoyId);
|
|
2463
|
+
// Check max injectable tasks (10)
|
|
2464
|
+
const injectedCount = allTasks.filter(t => t.injected === 1).length;
|
|
2465
|
+
if (injectedCount >= 10) {
|
|
2466
|
+
throw new Error(`Max injectable tasks (10) reached for convoy ${convoyId}`);
|
|
2467
|
+
}
|
|
2468
|
+
// Validate ID uniqueness
|
|
2469
|
+
if (allTasks.some(t => t.id === task.id)) {
|
|
2470
|
+
throw new Error(`Task ID "${task.id}" already exists in convoy ${convoyId}`);
|
|
2471
|
+
}
|
|
2472
|
+
// Validate depends_on references exist
|
|
2473
|
+
const deps = task.depends_on ?? [];
|
|
2474
|
+
for (const dep of deps) {
|
|
2475
|
+
if (!allTasks.some(t => t.id === dep)) {
|
|
2476
|
+
throw new Error(`Dependency "${dep}" not found in convoy ${convoyId}`);
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
// Validate no file partition overlap with pending/running tasks
|
|
2480
|
+
const taskFiles = task.files ?? [];
|
|
2481
|
+
if (taskFiles.length > 0) {
|
|
2482
|
+
// Normalize injected task file paths
|
|
2483
|
+
const normalizedTaskFiles = taskFiles.map(normalizePath);
|
|
2484
|
+
// Symlink pre-scan on injected files
|
|
2485
|
+
const basePath = options.basePath ?? process.cwd();
|
|
2486
|
+
try {
|
|
2487
|
+
scanSymlinks(normalizedTaskFiles, basePath);
|
|
2488
|
+
}
|
|
2489
|
+
catch (err) {
|
|
2490
|
+
throw new Error(`Injected task "${task.id}" failed symlink check: ${err.message}`);
|
|
2491
|
+
}
|
|
2492
|
+
// Full partition validation against active tasks
|
|
2493
|
+
const activeTasks = allTasks.filter(t => t.status === 'pending' || t.status === 'running' || t.status === 'assigned');
|
|
2494
|
+
for (const other of activeTasks) {
|
|
2495
|
+
const otherFiles = other.files ? JSON.parse(other.files) : [];
|
|
2496
|
+
if (otherFiles.length === 0)
|
|
2497
|
+
continue;
|
|
2498
|
+
const normalizedOther = otherFiles.map(normalizePath);
|
|
2499
|
+
const overlapping = [];
|
|
2500
|
+
for (const fileA of normalizedTaskFiles) {
|
|
2501
|
+
for (const fileB of normalizedOther) {
|
|
2502
|
+
if (pathsOverlap(fileA, fileB) && !overlapping.includes(fileA)) {
|
|
2503
|
+
overlapping.push(fileA);
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
}
|
|
2507
|
+
if (overlapping.length > 0) {
|
|
2508
|
+
throw new Error(`File partition overlap with task "${other.id}": ${overlapping.join(', ')}`);
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
}
|
|
2512
|
+
// Detect dependency cycles
|
|
2513
|
+
const depGraph = new Map();
|
|
2514
|
+
for (const t of allTasks) {
|
|
2515
|
+
depGraph.set(t.id, t.depends_on ? JSON.parse(t.depends_on) : []);
|
|
2516
|
+
}
|
|
2517
|
+
depGraph.set(task.id, deps);
|
|
2518
|
+
function hasCycle(nodeId, visited, stack) {
|
|
2519
|
+
visited.add(nodeId);
|
|
2520
|
+
stack.add(nodeId);
|
|
2521
|
+
for (const dep of depGraph.get(nodeId) ?? []) {
|
|
2522
|
+
if (!visited.has(dep)) {
|
|
2523
|
+
if (hasCycle(dep, visited, stack))
|
|
2524
|
+
return true;
|
|
2525
|
+
}
|
|
2526
|
+
else if (stack.has(dep)) {
|
|
2527
|
+
return true;
|
|
2528
|
+
}
|
|
2529
|
+
}
|
|
2530
|
+
stack.delete(nodeId);
|
|
2531
|
+
return false;
|
|
2532
|
+
}
|
|
2533
|
+
const visited = new Set();
|
|
2534
|
+
const stack = new Set();
|
|
2535
|
+
for (const nodeId of depGraph.keys()) {
|
|
2536
|
+
if (!visited.has(nodeId)) {
|
|
2537
|
+
if (hasCycle(nodeId, visited, stack)) {
|
|
2538
|
+
throw new Error(`Dependency cycle detected when injecting task "${task.id}"`);
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
}
|
|
2542
|
+
// Insert the task
|
|
2543
|
+
const record = {
|
|
2544
|
+
id: task.id,
|
|
2545
|
+
convoy_id: convoyId,
|
|
2546
|
+
phase: task.phase,
|
|
2547
|
+
prompt: task.prompt,
|
|
2548
|
+
agent: task.agent,
|
|
2549
|
+
adapter: null,
|
|
2550
|
+
model: null,
|
|
2551
|
+
timeout_ms: task.timeout_ms ?? 1_800_000,
|
|
2552
|
+
status: 'pending',
|
|
2553
|
+
worker_id: null,
|
|
2554
|
+
worktree: null,
|
|
2555
|
+
output: null,
|
|
2556
|
+
exit_code: null,
|
|
2557
|
+
started_at: null,
|
|
2558
|
+
finished_at: null,
|
|
2559
|
+
retries: 0,
|
|
2560
|
+
max_retries: task.max_retries ?? 1,
|
|
2561
|
+
files: taskFiles.length > 0 ? JSON.stringify(taskFiles) : null,
|
|
2562
|
+
depends_on: deps.length > 0 ? JSON.stringify(deps) : null,
|
|
2563
|
+
prompt_tokens: null,
|
|
2564
|
+
completion_tokens: null,
|
|
2565
|
+
total_tokens: null,
|
|
2566
|
+
cost_usd: null,
|
|
2567
|
+
gates: null,
|
|
2568
|
+
on_exhausted: task.on_exhausted ?? 'dlq',
|
|
2569
|
+
injected: 1,
|
|
2570
|
+
provenance: task.provenance ?? null,
|
|
2571
|
+
idempotency_key: task.idempotency_key ?? null,
|
|
2572
|
+
current_step: null,
|
|
2573
|
+
total_steps: null,
|
|
2574
|
+
review_level: null,
|
|
2575
|
+
review_verdict: null,
|
|
2576
|
+
review_tokens: null,
|
|
2577
|
+
review_model: null,
|
|
2578
|
+
panel_attempts: 0,
|
|
2579
|
+
dispute_id: null,
|
|
2580
|
+
drift_score: null,
|
|
2581
|
+
drift_retried: 0,
|
|
2582
|
+
outputs: null,
|
|
2583
|
+
inputs: null,
|
|
2584
|
+
discovered_issues: null,
|
|
2585
|
+
};
|
|
2586
|
+
store.insertInjectedTask(record);
|
|
2587
|
+
return record;
|
|
2588
|
+
}
|
|
2589
|
+
finally {
|
|
2590
|
+
store.close();
|
|
2591
|
+
}
|
|
2592
|
+
}
|
|
2593
|
+
return { run, resume, retryFailed, injectTask };
|
|
586
2594
|
}
|
|
587
2595
|
//# sourceMappingURL=engine.js.map
|