@bonesofspring/ai-rules 0.2.35 → 0.2.37
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/lib/merged-config.js +9 -0
- package/bin/opencode-install.js +46 -1
- package/package.json +4 -1
- package/presets/_shared/hooks/README.md +137 -0
- package/presets/_shared/hooks/chain-team-phases.sh.tmpl +1288 -0
- package/presets/claude/android-kotlin/MCP.md +2 -2
- package/presets/claude/android-kotlin/hooks/chain-team-phases.sh +171 -10
- package/presets/claude/android-kotlin/mcp.json +1 -1
- package/presets/claude/android-kotlin/rules/tooling-and-review/agent-team-orchestrator.md +6 -153
- package/presets/claude/android-kotlin/team/README.md +2 -6
- package/presets/claude/android-kotlin/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/claude/go/MCP.md +2 -2
- package/presets/claude/go/hooks/chain-team-phases.sh +183 -16
- package/presets/claude/go/mcp.json +1 -1
- package/presets/claude/go/rules/tooling-and-review/agent-team-orchestrator.md +6 -11
- package/presets/claude/go/team/README.md +2 -6
- package/presets/claude/ios-swift/MCP.md +2 -2
- package/presets/claude/ios-swift/hooks/chain-team-phases.sh +178 -17
- package/presets/claude/ios-swift/mcp.json +1 -1
- package/presets/claude/ios-swift/rules/tooling-and-review/agent-team-orchestrator.md +6 -153
- package/presets/claude/ios-swift/team/README.md +2 -6
- package/presets/claude/ios-swift/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/claude/java/hooks/chain-team-phases.sh +183 -16
- package/presets/claude/java/rules/tooling-and-review/agent-team-orchestrator.md +6 -28
- package/presets/claude/java/team/README.md +2 -6
- package/presets/claude/mcp-ts/hooks/chain-team-phases.sh +182 -13
- package/presets/claude/mcp-ts/rules/tooling-and-review/agent-team-orchestrator.md +6 -14
- package/presets/claude/mcp-ts/team/README.md +2 -6
- package/presets/claude/next/MCP.md +2 -2
- package/presets/claude/next/commands/task.md +5 -3
- package/presets/claude/next/hooks/chain-team-phases.sh +102 -6
- package/presets/claude/next/mcp.json +1 -1
- package/presets/claude/next/rules/tooling-and-review/agent-team-orchestrator.md +6 -226
- package/presets/claude/next/team/README.md +2 -6
- package/presets/claude/next/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/claude/nuxt/MCP.md +2 -2
- package/presets/claude/nuxt/hooks/chain-team-phases.sh +148 -7
- package/presets/claude/nuxt/mcp.json +1 -1
- package/presets/claude/nuxt/rules/tooling-and-review/agent-team-orchestrator.md +6 -223
- package/presets/claude/nuxt/team/README.md +2 -6
- package/presets/claude/nuxt/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/claude/php-hexagonal/hooks/chain-team-phases.sh +183 -16
- package/presets/claude/php-hexagonal/rules/tooling-and-review/agent-team-orchestrator.md +6 -28
- package/presets/claude/php-hexagonal/team/README.md +2 -6
- package/presets/claude/php-laravel/hooks/chain-team-phases.sh +183 -16
- package/presets/claude/php-laravel/rules/tooling-and-review/agent-team-orchestrator.md +6 -29
- package/presets/claude/php-laravel/team/README.md +2 -6
- package/presets/claude/svelte/MCP.md +2 -2
- package/presets/claude/svelte/hooks/chain-team-phases.sh +148 -7
- package/presets/claude/svelte/mcp.json +1 -1
- package/presets/claude/svelte/rules/tooling-and-review/agent-team-orchestrator.md +6 -223
- package/presets/claude/svelte/team/README.md +2 -6
- package/presets/claude/svelte/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/cursor/android-kotlin/MCP.md +2 -2
- package/presets/cursor/android-kotlin/hooks/chain-team-phases.sh +150 -7
- package/presets/cursor/android-kotlin/mcp.json +1 -1
- package/presets/cursor/android-kotlin/team/README.md +2 -0
- package/presets/cursor/android-kotlin/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/cursor/go/MCP.md +2 -2
- package/presets/cursor/go/hooks/chain-team-phases.sh +175 -8
- package/presets/cursor/go/mcp.json +1 -1
- package/presets/cursor/go/team/README.md +2 -0
- package/presets/cursor/ios-swift/MCP.md +2 -2
- package/presets/cursor/ios-swift/hooks/chain-team-phases.sh +150 -7
- package/presets/cursor/ios-swift/mcp.json +1 -1
- package/presets/cursor/ios-swift/team/README.md +2 -0
- package/presets/cursor/ios-swift/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/cursor/java/hooks/chain-team-phases.sh +175 -8
- package/presets/cursor/java/team/README.md +2 -0
- package/presets/cursor/mcp-ts/hooks/chain-team-phases.sh +179 -10
- package/presets/cursor/mcp-ts/team/README.md +2 -0
- package/presets/cursor/next/MCP.md +2 -2
- package/presets/cursor/next/commands/task.md +5 -3
- package/presets/cursor/next/hooks/chain-team-phases.sh +99 -5
- package/presets/cursor/next/mcp.json +1 -1
- package/presets/cursor/next/team/README.md +2 -0
- package/presets/cursor/next/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/cursor/nuxt/MCP.md +2 -2
- package/presets/cursor/nuxt/hooks/chain-team-phases.sh +145 -6
- package/presets/cursor/nuxt/mcp.json +1 -1
- package/presets/cursor/nuxt/team/README.md +2 -0
- package/presets/cursor/nuxt/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/cursor/php-hexagonal/hooks/chain-team-phases.sh +175 -8
- package/presets/cursor/php-hexagonal/team/README.md +2 -0
- package/presets/cursor/php-laravel/hooks/chain-team-phases.sh +175 -8
- package/presets/cursor/php-laravel/team/README.md +2 -0
- package/presets/cursor/svelte/MCP.md +2 -2
- package/presets/cursor/svelte/hooks/chain-team-phases.sh +145 -6
- package/presets/cursor/svelte/mcp.json +1 -1
- package/presets/cursor/svelte/team/README.md +2 -0
- package/presets/cursor/svelte/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/mavis/android-kotlin/MCP.md +2 -2
- package/presets/mavis/android-kotlin/adapter-map.json +1 -1
- package/presets/mavis/android-kotlin/hooks/chain-team-phases.sh +150 -7
- package/presets/mavis/android-kotlin/mcp.json +1 -1
- package/presets/mavis/android-kotlin/team/README.md +2 -0
- package/presets/mavis/android-kotlin/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/mavis/go/MCP.md +2 -2
- package/presets/mavis/go/adapter-map.json +1 -1
- package/presets/mavis/go/hooks/chain-team-phases.sh +175 -8
- package/presets/mavis/go/mcp.json +1 -1
- package/presets/mavis/go/team/README.md +2 -0
- package/presets/mavis/ios-swift/MCP.md +2 -2
- package/presets/mavis/ios-swift/adapter-map.json +1 -1
- package/presets/mavis/ios-swift/hooks/chain-team-phases.sh +150 -7
- package/presets/mavis/ios-swift/mcp.json +1 -1
- package/presets/mavis/ios-swift/team/README.md +2 -0
- package/presets/mavis/ios-swift/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/mavis/java/adapter-map.json +1 -1
- package/presets/mavis/java/hooks/chain-team-phases.sh +175 -8
- package/presets/mavis/java/team/README.md +2 -0
- package/presets/mavis/mcp-ts/adapter-map.json +1 -1
- package/presets/mavis/mcp-ts/hooks/chain-team-phases.sh +179 -10
- package/presets/mavis/mcp-ts/team/README.md +2 -0
- package/presets/mavis/next/MCP.md +2 -2
- package/presets/mavis/next/adapter-map.json +1 -1
- package/presets/mavis/next/commands/task.md +5 -3
- package/presets/mavis/next/hooks/chain-team-phases.sh +99 -5
- package/presets/mavis/next/mcp.json +1 -1
- package/presets/mavis/next/team/README.md +2 -0
- package/presets/mavis/next/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/mavis/nuxt/MCP.md +2 -2
- package/presets/mavis/nuxt/adapter-map.json +1 -1
- package/presets/mavis/nuxt/hooks/chain-team-phases.sh +145 -6
- package/presets/mavis/nuxt/mcp.json +1 -1
- package/presets/mavis/nuxt/team/README.md +2 -0
- package/presets/mavis/nuxt/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/mavis/php-hexagonal/adapter-map.json +1 -1
- package/presets/mavis/php-hexagonal/hooks/chain-team-phases.sh +175 -8
- package/presets/mavis/php-hexagonal/team/README.md +2 -0
- package/presets/mavis/php-laravel/adapter-map.json +1 -1
- package/presets/mavis/php-laravel/hooks/chain-team-phases.sh +175 -8
- package/presets/mavis/php-laravel/team/README.md +2 -0
- package/presets/mavis/svelte/MCP.md +2 -2
- package/presets/mavis/svelte/adapter-map.json +1 -1
- package/presets/mavis/svelte/hooks/chain-team-phases.sh +145 -6
- package/presets/mavis/svelte/mcp.json +1 -1
- package/presets/mavis/svelte/team/README.md +2 -0
- package/presets/mavis/svelte/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/opencode/android-kotlin/MCP.md +2 -2
- package/presets/opencode/android-kotlin/OPENCODE.md +6 -4
- package/presets/opencode/android-kotlin/adapter-map.json +1 -1
- package/presets/opencode/android-kotlin/hooks/chain-team-phases.sh +150 -7
- package/presets/opencode/android-kotlin/opencode.json +13 -1
- package/presets/opencode/android-kotlin/team/README.md +2 -0
- package/presets/opencode/android-kotlin/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/opencode/go/MCP.md +2 -2
- package/presets/opencode/go/OPENCODE.md +6 -4
- package/presets/opencode/go/adapter-map.json +1 -1
- package/presets/opencode/go/hooks/chain-team-phases.sh +175 -8
- package/presets/opencode/go/opencode.json +13 -1
- package/presets/opencode/go/team/README.md +2 -0
- package/presets/opencode/ios-swift/MCP.md +2 -2
- package/presets/opencode/ios-swift/OPENCODE.md +6 -4
- package/presets/opencode/ios-swift/adapter-map.json +1 -1
- package/presets/opencode/ios-swift/hooks/chain-team-phases.sh +150 -7
- package/presets/opencode/ios-swift/opencode.json +13 -1
- package/presets/opencode/ios-swift/team/README.md +2 -0
- package/presets/opencode/ios-swift/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/opencode/java/OPENCODE.md +6 -4
- package/presets/opencode/java/adapter-map.json +1 -1
- package/presets/opencode/java/hooks/chain-team-phases.sh +175 -8
- package/presets/opencode/java/opencode.json +12 -0
- package/presets/opencode/java/team/README.md +2 -0
- package/presets/opencode/mcp-ts/OPENCODE.md +6 -4
- package/presets/opencode/mcp-ts/adapter-map.json +1 -1
- package/presets/opencode/mcp-ts/hooks/chain-team-phases.sh +179 -10
- package/presets/opencode/mcp-ts/opencode.json +12 -0
- package/presets/opencode/mcp-ts/team/README.md +2 -0
- package/presets/opencode/next/MCP.md +2 -2
- package/presets/opencode/next/OPENCODE.md +6 -4
- package/presets/opencode/next/adapter-map.json +1 -1
- package/presets/opencode/next/commands/task.md +5 -3
- package/presets/opencode/next/hooks/chain-team-phases.sh +99 -5
- package/presets/opencode/next/opencode.json +13 -1
- package/presets/opencode/next/team/README.md +2 -0
- package/presets/opencode/next/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/opencode/nuxt/MCP.md +2 -2
- package/presets/opencode/nuxt/OPENCODE.md +6 -4
- package/presets/opencode/nuxt/adapter-map.json +1 -1
- package/presets/opencode/nuxt/hooks/chain-team-phases.sh +145 -6
- package/presets/opencode/nuxt/opencode.json +13 -1
- package/presets/opencode/nuxt/team/README.md +2 -0
- package/presets/opencode/nuxt/team/fixtures/artifact-manifest.example.json +1 -0
- package/presets/opencode/php-hexagonal/OPENCODE.md +6 -4
- package/presets/opencode/php-hexagonal/adapter-map.json +1 -1
- package/presets/opencode/php-hexagonal/hooks/chain-team-phases.sh +175 -8
- package/presets/opencode/php-hexagonal/opencode.json +12 -0
- package/presets/opencode/php-hexagonal/team/README.md +2 -0
- package/presets/opencode/php-laravel/OPENCODE.md +6 -4
- package/presets/opencode/php-laravel/adapter-map.json +1 -1
- package/presets/opencode/php-laravel/hooks/chain-team-phases.sh +175 -8
- package/presets/opencode/php-laravel/opencode.json +12 -0
- package/presets/opencode/php-laravel/team/README.md +2 -0
- package/presets/opencode/svelte/MCP.md +2 -2
- package/presets/opencode/svelte/OPENCODE.md +6 -4
- package/presets/opencode/svelte/adapter-map.json +1 -1
- package/presets/opencode/svelte/hooks/chain-team-phases.sh +145 -6
- package/presets/opencode/svelte/opencode.json +13 -1
- package/presets/opencode/svelte/team/README.md +2 -0
- package/presets/opencode/svelte/team/fixtures/artifact-manifest.example.json +1 -0
|
@@ -0,0 +1,1288 @@
|
|
|
1
|
+
# <<<hook-slot:HEADER>>>
|
|
2
|
+
# <<<hook-slot:/HEADER>>>
|
|
3
|
+
|
|
4
|
+
set -euo pipefail
|
|
5
|
+
|
|
6
|
+
input=$(cat)
|
|
7
|
+
|
|
8
|
+
INPUT="$input" node <<'NODE'
|
|
9
|
+
const fs = require('fs');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const crypto = require('crypto');
|
|
12
|
+
|
|
13
|
+
const TEAM_ROOT = path.join(process.cwd(), '.ai.local', 'team');
|
|
14
|
+
|
|
15
|
+
const inputRaw = process.env.INPUT || '';
|
|
16
|
+
let hookInput;
|
|
17
|
+
try {
|
|
18
|
+
hookInput = JSON.parse(inputRaw);
|
|
19
|
+
} catch {
|
|
20
|
+
process.stdout.write('{}');
|
|
21
|
+
process.exit(0);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// <<<hook-slot:PLATFORM_PREAMBLE>>>
|
|
25
|
+
// <<<hook-slot:/PLATFORM_PREAMBLE>>>
|
|
26
|
+
|
|
27
|
+
if (hookInput.status !== 'completed') {
|
|
28
|
+
process.stdout.write('{}');
|
|
29
|
+
process.exit(0);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const activePath = path.join(TEAM_ROOT, 'active-task.json');
|
|
33
|
+
|
|
34
|
+
if (!fs.existsSync(activePath)) {
|
|
35
|
+
process.stdout.write('{}');
|
|
36
|
+
process.exit(0);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let active;
|
|
40
|
+
try {
|
|
41
|
+
active = JSON.parse(fs.readFileSync(activePath, 'utf8'));
|
|
42
|
+
} catch {
|
|
43
|
+
process.stdout.write('{}');
|
|
44
|
+
process.exit(0);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const slug = active.slug;
|
|
48
|
+
// Reject non-kebab / traversal slugs: the runtime writes status.json and
|
|
49
|
+
// metrics.json under tasks/<slug>, so an unchecked slug could escape the tree.
|
|
50
|
+
const SLUG_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
51
|
+
if (typeof slug !== 'string' || slug.length > 48 || !SLUG_RE.test(slug)) {
|
|
52
|
+
process.stdout.write('{}');
|
|
53
|
+
process.exit(0);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const taskDir = path.join(TEAM_ROOT, 'tasks', slug);
|
|
57
|
+
const statusPath = path.join(taskDir, 'status.json');
|
|
58
|
+
const pipelinePath = path.join(taskDir, 'pipeline.json');
|
|
59
|
+
const METRICS_PATH = path.join(taskDir, 'metrics.json');
|
|
60
|
+
const METRICS_LOCK = `${METRICS_PATH}.lock`;
|
|
61
|
+
// Pipeline step graph is assigned once pipeline.json is parsed; declared early so the
|
|
62
|
+
// gate-resume branch can schedule from the graph before the main parse point.
|
|
63
|
+
let steps = [];
|
|
64
|
+
|
|
65
|
+
if (!fs.existsSync(statusPath)) {
|
|
66
|
+
process.stdout.write('{}');
|
|
67
|
+
process.exit(0);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
let status;
|
|
71
|
+
const now = new Date().toISOString();
|
|
72
|
+
const STACK = '__STACK__';
|
|
73
|
+
const PLATFORM = '__PLATFORM__';
|
|
74
|
+
|
|
75
|
+
let metricsLockToken = null;
|
|
76
|
+
function readMetricsLockToken() {
|
|
77
|
+
try {
|
|
78
|
+
const content = fs.readFileSync(METRICS_LOCK, 'utf8').trim();
|
|
79
|
+
return content.length > 0 ? content : null;
|
|
80
|
+
} catch { return null; }
|
|
81
|
+
}
|
|
82
|
+
function pidFromToken(token) {
|
|
83
|
+
const match = /^(\d+):/.exec(token || '');
|
|
84
|
+
return match ? Number(match[1]) : null;
|
|
85
|
+
}
|
|
86
|
+
function isPidAlive(pid) {
|
|
87
|
+
try { process.kill(pid, 0); return true; } catch (error) { return Boolean(error && error.code === 'EPERM'); }
|
|
88
|
+
}
|
|
89
|
+
function waitForMetricsLock() {
|
|
90
|
+
// OD-1: advisory lock via create-exclusive (fs.openSync(_, 'wx')) carrying an
|
|
91
|
+
// ownership token, backported from .ai.local/scripts/lock.mjs. Two concurrent
|
|
92
|
+
// subagentStop events serialize; release unlinks only when the file still
|
|
93
|
+
// carries our token. A lock left behind by a killed process is reclaimed only
|
|
94
|
+
// once its mtime is older than STALE_LOCK_MS AND the recorded owner pid is no
|
|
95
|
+
// longer alive, so a slow-but-live owner is never stolen.
|
|
96
|
+
const STALE_LOCK_MS = 30000;
|
|
97
|
+
const token = `${process.pid}:${crypto.randomBytes(8).toString('hex')}`;
|
|
98
|
+
for (let attempt = 0; attempt < 200; attempt += 1) {
|
|
99
|
+
let fd;
|
|
100
|
+
try {
|
|
101
|
+
fd = fs.openSync(METRICS_LOCK, 'wx');
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (!error || error.code !== 'EEXIST') throw error;
|
|
104
|
+
let stat = null;
|
|
105
|
+
try { stat = fs.statSync(METRICS_LOCK); } catch { /* lock vanished; retry */ }
|
|
106
|
+
const stale = stat !== null && Date.now() - stat.mtimeMs > STALE_LOCK_MS;
|
|
107
|
+
if (stale) {
|
|
108
|
+
const ownerPid = pidFromToken(readMetricsLockToken());
|
|
109
|
+
if (ownerPid === null || !isPidAlive(ownerPid)) {
|
|
110
|
+
try { fs.unlinkSync(METRICS_LOCK); } catch { /* already reclaimed */ }
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const until = Date.now() + 10;
|
|
115
|
+
while (Date.now() < until) { /* 10 ms busy-wait */ }
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
fs.writeSync(fd, token);
|
|
120
|
+
try { fs.fsyncSync(fd); } catch {}
|
|
121
|
+
} finally {
|
|
122
|
+
try { fs.closeSync(fd); } catch {}
|
|
123
|
+
}
|
|
124
|
+
metricsLockToken = token;
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
throw new Error('metrics lock timeout');
|
|
128
|
+
}
|
|
129
|
+
function releaseMetricsLock() {
|
|
130
|
+
if (metricsLockToken != null && readMetricsLockToken() === metricsLockToken) {
|
|
131
|
+
try { fs.unlinkSync(METRICS_LOCK); } catch {}
|
|
132
|
+
}
|
|
133
|
+
metricsLockToken = null;
|
|
134
|
+
}
|
|
135
|
+
let taskLockHeld = false;
|
|
136
|
+
function releaseTaskLock() {
|
|
137
|
+
if (!taskLockHeld) return;
|
|
138
|
+
taskLockHeld = false;
|
|
139
|
+
releaseMetricsLock();
|
|
140
|
+
}
|
|
141
|
+
waitForMetricsLock();
|
|
142
|
+
taskLockHeld = true;
|
|
143
|
+
process.on('exit', releaseTaskLock);
|
|
144
|
+
try {
|
|
145
|
+
status = JSON.parse(fs.readFileSync(statusPath, 'utf8'));
|
|
146
|
+
} catch {
|
|
147
|
+
releaseTaskLock();
|
|
148
|
+
process.stdout.write('{}');
|
|
149
|
+
process.exit(0);
|
|
150
|
+
}
|
|
151
|
+
function mutateMetrics(mutator) {
|
|
152
|
+
const acquiredHere = !taskLockHeld;
|
|
153
|
+
if (acquiredHere) waitForMetricsLock();
|
|
154
|
+
try {
|
|
155
|
+
let metrics;
|
|
156
|
+
try { metrics = JSON.parse(fs.readFileSync(METRICS_PATH, 'utf8')); } catch {
|
|
157
|
+
const runId = status.metricsRunId || `${slug}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
158
|
+
status.metricsRunId = runId;
|
|
159
|
+
// Resolve profile from pipeline.json (preferred) or status.json, falling back to 'unknown'.
|
|
160
|
+
// The router/agent must never write profile into status.json — pipeline.json is the SoT.
|
|
161
|
+
let profile = 'unknown';
|
|
162
|
+
try {
|
|
163
|
+
if (fs.existsSync(pipelinePath)) {
|
|
164
|
+
const pipe = JSON.parse(fs.readFileSync(pipelinePath, 'utf8'));
|
|
165
|
+
if (pipe && (pipe.profile === 'light' || pipe.profile === 'standard' || pipe.profile === 'full')) {
|
|
166
|
+
profile = pipe.profile;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
} catch {}
|
|
170
|
+
if (profile === 'unknown' && (status.profile === 'light' || status.profile === 'standard' || status.profile === 'full')) {
|
|
171
|
+
profile = status.profile;
|
|
172
|
+
}
|
|
173
|
+
metrics = { schemaVersion: 1, task: { runId, slug, preset: 'ai-rules', stack: STACK, platform: PLATFORM, intent: status.intent || 'unknown', profile }, events: [] };
|
|
174
|
+
metrics.events.push({ eventId: `${runId}:task_started`, type: 'task_started', at: now, source: 'hook', attributionConfidence: 'high' });
|
|
175
|
+
}
|
|
176
|
+
mutator(metrics);
|
|
177
|
+
const temporary = `${METRICS_PATH}.${process.pid}.${Date.now()}.tmp`;
|
|
178
|
+
fs.writeFileSync(temporary, JSON.stringify(metrics, null, 2) + '\n');
|
|
179
|
+
fs.renameSync(temporary, METRICS_PATH);
|
|
180
|
+
} finally {
|
|
181
|
+
if (acquiredHere) releaseMetricsLock();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
function appendMetric(event) { mutateMetrics((metrics) => metrics.events.push({ eventId: `${metrics.task.runId}:${Date.now()}:${Math.random().toString(16).slice(2)}`, ...event })); }
|
|
185
|
+
function nextAttemptOrdinal(stepIndex, agent) {
|
|
186
|
+
try {
|
|
187
|
+
const metrics = JSON.parse(fs.readFileSync(METRICS_PATH, 'utf8'));
|
|
188
|
+
return metrics.events.reduce((highest, event) => event.type === 'attempt_started' && event.stepIndex === stepIndex && event.agent === agent ? Math.max(highest, Number(event.attempt) || 0) : highest, 0) + 1;
|
|
189
|
+
} catch { return 1; }
|
|
190
|
+
}
|
|
191
|
+
function roleFor(agent) {
|
|
192
|
+
if (/analyst|architect|router|migration/.test(agent || '')) return 'planning';
|
|
193
|
+
if (/verifier/.test(agent || '')) return 'validation';
|
|
194
|
+
if (/reviewer|auditor/.test(agent || '')) return 'review';
|
|
195
|
+
if (/test|qa/.test(agent || '')) return 'testing';
|
|
196
|
+
if (/writer/.test(agent || '')) return 'docs';
|
|
197
|
+
return 'implementation';
|
|
198
|
+
}
|
|
199
|
+
const DEFAULT_ARTIFACT_OUTPUT_IDS = {
|
|
200
|
+
// <<<hook-slot:ARTIFACT_OUTPUT_IDS>>>
|
|
201
|
+
// <<<hook-slot:/ARTIFACT_OUTPUT_IDS>>>
|
|
202
|
+
};
|
|
203
|
+
function artifactOutputIdFor(step, agent) {
|
|
204
|
+
if (step && typeof step.artifactOutputId === 'string') return step.artifactOutputId;
|
|
205
|
+
if (step?.artifactOutputIds && typeof step.artifactOutputIds[agent] === 'string') return step.artifactOutputIds[agent];
|
|
206
|
+
return DEFAULT_ARTIFACT_OUTPUT_IDS[agent] || agent;
|
|
207
|
+
}
|
|
208
|
+
function activateAttempts(step, stepIndex, waveId = null, agentsOverride = null) {
|
|
209
|
+
const active = { ...(status.activeAttempts || {}) };
|
|
210
|
+
const agents = Array.isArray(agentsOverride) && agentsOverride.length > 0 ? agentsOverride : getStepAgents(step);
|
|
211
|
+
const parallelGroupId = step.parallel && getStepAgents(step).length > 1 ? `${status.metricsRunId || slug}:step-${stepIndex}` : null;
|
|
212
|
+
for (const agent of agents) {
|
|
213
|
+
const attempt = nextAttemptOrdinal(stepIndex, agent); const runId = status.metricsRunId || `${slug}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
214
|
+
status.metricsRunId = runId; const attemptId = `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`;
|
|
215
|
+
if (active[attemptId]) continue;
|
|
216
|
+
active[attemptId] = { agent, stepIndex, attempt, startedAt: now, parallelGroupId, waveId: waveId || null };
|
|
217
|
+
appendMetric({ type: 'attempt_started', at: now, attemptId, stepIndex, stepLabel: step.label || null, agent, role: roleFor(agent), attempt, parallelGroupId, waveId: waveId || null, source: 'hook', attributionConfidence: 'high' });
|
|
218
|
+
}
|
|
219
|
+
status.activeAttempts = active;
|
|
220
|
+
}
|
|
221
|
+
function resolvedAttempt() {
|
|
222
|
+
const active = status.activeAttempts || {}; const entries = Object.entries(active);
|
|
223
|
+
const stableAttemptId = hookInput.attemptId;
|
|
224
|
+
if (stableAttemptId) {
|
|
225
|
+
return active[stableAttemptId]
|
|
226
|
+
? { attemptId: stableAttemptId, entry: active[stableAttemptId], confidence: 'high' }
|
|
227
|
+
: null;
|
|
228
|
+
}
|
|
229
|
+
if (entries.length === 1) return { attemptId: entries[0][0], entry: entries[0][1], confidence: 'high' };
|
|
230
|
+
try { const receipts = JSON.parse(fs.readFileSync(path.join(taskDir, '.metrics-receipts.json'), 'utf8')); const receipt = Array.isArray(receipts) ? receipts.find((item) => active[item.attemptId]) : null; if (receipt) return { attemptId: receipt.attemptId, entry: active[receipt.attemptId], confidence: 'fallback', source: 'agent' }; } catch {}
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
let artifactStallMessage = null;
|
|
234
|
+
|
|
235
|
+
// A1: seed the manifest a modern pipeline expects instead of advancing without
|
|
236
|
+
// one. Exclusive publish via hard link so a producer that wrote the file in the
|
|
237
|
+
// meantime is never overwritten; returns null on success (or when the file
|
|
238
|
+
// appeared) and the fs error otherwise.
|
|
239
|
+
function writeSkeletonManifest(manifestPath) {
|
|
240
|
+
const temporary = `${manifestPath}.${process.pid}.${Date.now()}.seed`;
|
|
241
|
+
const body = JSON.stringify({ schemaVersion: 1, slug, artifacts: [] }, null, 2) + '\n';
|
|
242
|
+
let descriptor = null;
|
|
243
|
+
try {
|
|
244
|
+
descriptor = fs.openSync(temporary, 'wx');
|
|
245
|
+
try { fs.writeSync(descriptor, body); try { fs.fsyncSync(descriptor); } catch {} } finally { fs.closeSync(descriptor); descriptor = null; }
|
|
246
|
+
fs.linkSync(temporary, manifestPath);
|
|
247
|
+
fs.unlinkSync(temporary);
|
|
248
|
+
return null;
|
|
249
|
+
} catch (error) {
|
|
250
|
+
if (descriptor !== null) { try { fs.closeSync(descriptor); } catch {} }
|
|
251
|
+
try { fs.unlinkSync(temporary); } catch {}
|
|
252
|
+
if (error && error.code === 'EEXIST' && fs.existsSync(manifestPath)) return null;
|
|
253
|
+
return String(error && error.message ? error.message : error);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// A2: a `completed` receipt must cite evidence the harness can inspect. Order is
|
|
258
|
+
// the message order — the first failing predicate wins, so the operator sees one
|
|
259
|
+
// actionable line. `authoritativePaths[]` stays task-dir-relative; external
|
|
260
|
+
// references belong in `evidencePaths[]`.
|
|
261
|
+
function validateCompletedArtifact(entry) {
|
|
262
|
+
const artifactId = entry && entry.id ? entry.id : '(unnamed)';
|
|
263
|
+
const entryStatus = entry && entry.status;
|
|
264
|
+
if (entryStatus !== 'completed') {
|
|
265
|
+
return `[chain-team-phases] ${slug}: receipt "${artifactId}" has receipt.outcome "completed" but entry status "${entryStatus}". Make entry.status and receipt.outcome agree, then resume with: /task-continue ${slug}`;
|
|
266
|
+
}
|
|
267
|
+
const authoritativePaths = entry && Array.isArray(entry.authoritativePaths) ? entry.authoritativePaths : [];
|
|
268
|
+
if (authoritativePaths.length === 0) {
|
|
269
|
+
return `[chain-team-phases] ${slug}: receipt "${artifactId}" is "completed" but authoritativePaths[] is empty. Record at least one file you produced under .ai.local/team/tasks/${slug}/, then resume with: /task-continue ${slug}`;
|
|
270
|
+
}
|
|
271
|
+
for (const cited of authoritativePaths) {
|
|
272
|
+
const value = typeof cited === 'string' ? cited.trim() : '';
|
|
273
|
+
const resolvedPath = value ? path.resolve(taskDir, value) : taskDir;
|
|
274
|
+
const relative = path.relative(taskDir, resolvedPath);
|
|
275
|
+
const escapes = !value || path.isAbsolute(value) || relative === '' || relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative);
|
|
276
|
+
if (escapes) {
|
|
277
|
+
return `[chain-team-phases] ${slug}: receipt "${artifactId}" cites "${value}", which resolves outside .ai.local/team/tasks/${slug}/ (relative: "${relative}"). Cite a task-relative path; keep external references in evidencePaths[]. Then resume with: /task-continue ${slug}`;
|
|
278
|
+
}
|
|
279
|
+
let stat = null;
|
|
280
|
+
try { stat = fs.statSync(resolvedPath); } catch {}
|
|
281
|
+
if (!stat || !stat.isFile()) {
|
|
282
|
+
return `[chain-team-phases] ${slug}: receipt "${artifactId}" cites "${value}" but no such file exists under .ai.local/team/tasks/${slug}/. Write the file, then resume with: /task-continue ${slug}`;
|
|
283
|
+
}
|
|
284
|
+
if (/\.md[c]?$/i.test(value)) {
|
|
285
|
+
let content = '';
|
|
286
|
+
try { content = fs.readFileSync(resolvedPath, 'utf8'); } catch {}
|
|
287
|
+
if (!/\S/.test(content)) {
|
|
288
|
+
return `[chain-team-phases] ${slug}: receipt "${artifactId}" is "completed" but authoritative path "${value}" has no non-whitespace content. Produce the artifact, then resume with: /task-continue ${slug}`;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
return null;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function readBoundReceiptOutcome(agent, step, resolved) {
|
|
296
|
+
if (!agent || !resolved) return { outcome: null, receiptRequired: false };
|
|
297
|
+
const manifestPath = path.join(taskDir, 'artifact-manifest.json');
|
|
298
|
+
const expectedOutputId = artifactOutputIdFor(step, agent);
|
|
299
|
+
if (!fs.existsSync(manifestPath)) {
|
|
300
|
+
// A1: absent manifest + a parsed modern pipeline denies silent advancement.
|
|
301
|
+
// Legacy/step-less pipelines keep their previous behaviour (legacyFlow owns them).
|
|
302
|
+
if (!(Array.isArray(steps) && steps.length > 0)) return { outcome: null, receiptRequired: false };
|
|
303
|
+
const seeded = writeSkeletonManifest(manifestPath);
|
|
304
|
+
const stepIndex = typeof resolved.entry.stepIndex === 'number' ? resolved.entry.stepIndex : 0;
|
|
305
|
+
if (seeded) {
|
|
306
|
+
return { outcome: null, receiptRequired: true, stallMessage: `[chain-team-phases] ${slug}: artifact-manifest.json is missing and the skeleton could not be written (${seeded}). Create .ai.local/team/tasks/${slug}/artifact-manifest.json with {schemaVersion:1, slug, artifacts:[]}, add the receipt for artifactOutputId "${expectedOutputId}", then resume with: /task-continue ${slug}` };
|
|
307
|
+
}
|
|
308
|
+
return { outcome: null, receiptRequired: true, stallMessage: `[chain-team-phases] ${slug}: no artifact-manifest.json for step ${stepIndex} (${agent}). Wrote a skeleton {schemaVersion:1, slug, artifacts:[]}. Expected artifactOutputId "${expectedOutputId}". Write the artifact and its receipt, then resume with: /task-continue ${slug}` };
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
|
312
|
+
// Guard: the schema key is `artifacts` (see agent-artifact-contracts.md). A top-level
|
|
313
|
+
// `entries` key is a silent bug — producer wrote to a wrong field, hook would not
|
|
314
|
+
// see the receipt, and the step hangs in `awaiting_artifact_receipt`. Warn loudly.
|
|
315
|
+
if (manifest && typeof manifest === 'object' && !Array.isArray(manifest.artifacts) && Array.isArray(manifest.entries)) {
|
|
316
|
+
process.stderr.write(`WARNING: ${manifestPath} has top-level "entries" but no "artifacts" array; reading only "artifacts" per schema. The producer likely upserted into the wrong key. See agent-artifact-contracts.md (Schema field name).` + '\n');
|
|
317
|
+
} else if (manifest && typeof manifest === 'object' && Array.isArray(manifest.entries) && Array.isArray(manifest.artifacts)) {
|
|
318
|
+
process.stderr.write(`WARNING: ${manifestPath} has both "artifacts" and "entries" keys; reading only "artifacts" per schema. Foreign "entries" content is ignored.` + '\n');
|
|
319
|
+
}
|
|
320
|
+
const artifacts = Array.isArray(manifest.artifacts) ? manifest.artifacts : [];
|
|
321
|
+
const attemptStartedAt = Date.parse(resolved.entry.startedAt);
|
|
322
|
+
// Pre-scan: warn on the silent-bug classes the filter below would otherwise drop.
|
|
323
|
+
// A receipt with a non-matching attemptId is dropped silently; without this warning,
|
|
324
|
+
// the step hangs in `awaiting_artifact_receipt` with no signal of why. Same for
|
|
325
|
+
// receipts whose terminal timestamp is older than the active attempt (stale retry).
|
|
326
|
+
const activeIds = new Set(Object.keys(status.activeAttempts || {}));
|
|
327
|
+
for (const entry of artifacts) {
|
|
328
|
+
if (!entry || entry.producer !== agent || !entry.receipt || typeof entry.receipt.outcome !== 'string') continue;
|
|
329
|
+
const rid = entry.receipt.attemptId;
|
|
330
|
+
if (typeof rid === 'string' && rid !== resolved.attemptId && !activeIds.has(rid)) {
|
|
331
|
+
process.stderr.write(`WARNING: ${manifestPath} receipt for producer "${agent}" id "${entry.id}" carries attemptId "${rid}" that does not match the active attempt "${resolved.attemptId}". The receipt is being dropped; step will hang in \`awaiting_artifact_receipt\` unless the producer retries. Common cause: agent reused an attemptId from a prior failed attempt. See agent-artifact-contracts.md (Receipt binding).` + '\n');
|
|
332
|
+
}
|
|
333
|
+
const terminalAt = Date.parse(entry.timestamps?.completedAt || entry.timestamps?.updatedAt || '');
|
|
334
|
+
if (Number.isFinite(attemptStartedAt) && Number.isFinite(terminalAt) && terminalAt < attemptStartedAt) {
|
|
335
|
+
process.stderr.write(`WARNING: ${manifestPath} receipt for producer "${agent}" id "${entry.id}" has timestamps.completedAt older than the active attempt's startedAt. Likely a stale receipt from a previous attempt; it is being dropped. See agent-artifact-contracts.md (Receipt binding).` + '\n');
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
const owned = artifacts
|
|
339
|
+
.filter((entry) => {
|
|
340
|
+
if (!entry || entry.producer !== agent || !entry.receipt || typeof entry.receipt.outcome !== 'string') return false;
|
|
341
|
+
const boundByAttempt = typeof entry.receipt.attemptId === 'string' && entry.receipt.attemptId === resolved.attemptId;
|
|
342
|
+
const boundByOutput = entry.receipt.attemptId == null && entry.id === expectedOutputId;
|
|
343
|
+
if (!boundByAttempt && !boundByOutput) return false;
|
|
344
|
+
const terminalAt = Date.parse(entry.timestamps?.completedAt || entry.timestamps?.updatedAt || '');
|
|
345
|
+
return Number.isFinite(terminalAt) && (!Number.isFinite(attemptStartedAt) || terminalAt >= attemptStartedAt);
|
|
346
|
+
})
|
|
347
|
+
.sort((a, b) => {
|
|
348
|
+
const ta = Date.parse(a.timestamps?.completedAt || a.timestamps?.updatedAt || 0) || 0;
|
|
349
|
+
const tb = Date.parse(b.timestamps?.completedAt || b.timestamps?.updatedAt || 0) || 0;
|
|
350
|
+
return tb - ta;
|
|
351
|
+
});
|
|
352
|
+
// Bonus: warn if the active attempt's receipts all lack attemptId in a non-parallel step.
|
|
353
|
+
// The orchestrator always provides attemptId, so a missing one means the agent dropped it
|
|
354
|
+
// (model output, JSON.stringify omission, etc.). boundByOutput still binds the receipt by
|
|
355
|
+
// expectedOutputId, so this is not fatal — but it is a contract violation worth flagging.
|
|
356
|
+
if (owned.length > 0 && owned[0].receipt.attemptId == null && !(step && step.parallel && Array.isArray(getStepAgents(step)) && getStepAgents(step).length > 1)) {
|
|
357
|
+
process.stderr.write(`WARNING: ${manifestPath} receipt for producer "${agent}" id "${owned[0].id}" lacks entry.receipt.attemptId on a non-parallel step. The receipt is bound by output-id fallback; the agent should always include the attemptId the orchestrator provides. See agent-artifact-contracts.md (Receipt binding).` + '\n');
|
|
358
|
+
}
|
|
359
|
+
const outcome = owned[0]?.receipt?.outcome || null;
|
|
360
|
+
if (outcome === 'completed') {
|
|
361
|
+
const stallMessage = validateCompletedArtifact(owned[0]);
|
|
362
|
+
if (stallMessage) return { outcome: null, receiptRequired: true, stallMessage };
|
|
363
|
+
}
|
|
364
|
+
return { outcome, receiptRequired: true };
|
|
365
|
+
} catch {
|
|
366
|
+
return { outcome: null, receiptRequired: false };
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
function reconcileStatusFromManifest(agent, step, resolved) {
|
|
370
|
+
const terminal = new Set(['completed', 'blocked', 'changes_requested', 'validation_failed']);
|
|
371
|
+
artifactStallMessage = null;
|
|
372
|
+
const { outcome, receiptRequired, stallMessage } = readBoundReceiptOutcome(agent, step, resolved);
|
|
373
|
+
if (terminal.has(outcome)) {
|
|
374
|
+
status.state = outcome;
|
|
375
|
+
return outcome;
|
|
376
|
+
}
|
|
377
|
+
if (receiptRequired) {
|
|
378
|
+
artifactStallMessage = stallMessage || null;
|
|
379
|
+
status.state = 'awaiting_artifact_receipt';
|
|
380
|
+
status.phase = 'blocked';
|
|
381
|
+
return status.state;
|
|
382
|
+
}
|
|
383
|
+
if (terminal.has(status.state)) return status.state;
|
|
384
|
+
// Host reported subagent completed and no blocking receipt → treat as completed for metrics/advance.
|
|
385
|
+
if (hookInput.status === 'completed') {
|
|
386
|
+
status.state = 'completed';
|
|
387
|
+
return 'completed';
|
|
388
|
+
}
|
|
389
|
+
return status.state;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
function finishActiveAttempt(forced) {
|
|
393
|
+
const resolved = forced || resolvedAttempt(); if (!resolved) return null;
|
|
394
|
+
const durationMs = Date.parse(now) - Date.parse(resolved.entry.startedAt);
|
|
395
|
+
const outcome = ['completed', 'blocked', 'changes_requested', 'validation_failed'].includes(status.state) ? status.state : 'unknown';
|
|
396
|
+
appendMetric({ type: 'attempt_finished', at: now, attemptId: resolved.attemptId, outcome, durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : null, retryAfterFix: status.retryAfterFix || null, source: resolved.source || 'hook', attributionConfidence: resolved.confidence });
|
|
397
|
+
const active = { ...(status.activeAttempts || {}) }; delete active[resolved.attemptId]; status.activeAttempts = active; status.lastCompletedAttempt = { attemptId: resolved.attemptId, completedAt: now }; return { ...resolved, outcome };
|
|
398
|
+
}
|
|
399
|
+
function beginHumanGate() { const eventId = `${status.metricsRunId || slug}:gate:${Date.now()}`; appendMetric({ eventId, type: 'human_gate_started', at: now, source: 'hook', attributionConfidence: 'high' }); status.activeHumanGateEventId = eventId; }
|
|
400
|
+
function endHumanGateIfResumed() {
|
|
401
|
+
if (!status.activeHumanGateEventId || status.awaitingHumanGate || status.state === 'awaiting_approval') return;
|
|
402
|
+
appendMetric({ type: 'human_gate_ended', at: now, gateStartedEventId: status.activeHumanGateEventId, source: 'hook', attributionConfidence: 'high' });
|
|
403
|
+
delete status.activeHumanGateEventId;
|
|
404
|
+
}
|
|
405
|
+
function completeTaskMetrics() { appendMetric({ type: 'task_completed', at: now, outcome: status.state === 'completed' ? 'completed' : 'unknown', source: 'hook', attributionConfidence: 'high' }); }
|
|
406
|
+
function recordSkippedStep(step, stepIndex) {
|
|
407
|
+
for (const agent of getStepAgents(step)) {
|
|
408
|
+
const runId = status.metricsRunId || `${slug}-${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
|
409
|
+
status.metricsRunId = runId;
|
|
410
|
+
const attempt = nextAttemptOrdinal(stepIndex, agent);
|
|
411
|
+
appendMetric({ type: 'attempt_skipped', at: now, attemptId: `${runId}:step-${stepIndex}:${agent}:attempt-${attempt}`, stepIndex, stepLabel: step.label || null, agent, role: roleFor(agent), attempt, outcome: 'skipped', source: 'hook', attributionConfidence: 'high' });
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
function writeStatus(next) {
|
|
417
|
+
status = { ...status, ...next, slug, updatedAt: now };
|
|
418
|
+
const temporary = `${statusPath}.${process.pid}.${Date.now()}.tmp`;
|
|
419
|
+
// Open + write + fsync + rename so the durable file lands on disk before
|
|
420
|
+
// the orchestrator reads it. Closes the race window where a subagent that
|
|
421
|
+
// completed milliseconds before writeStatus() could otherwise invoke the
|
|
422
|
+
// next step on a stale status (in particular the human-gate write).
|
|
423
|
+
const fd = fs.openSync(temporary, 'w');
|
|
424
|
+
try {
|
|
425
|
+
fs.writeSync(fd, JSON.stringify(status, null, 2) + '\n');
|
|
426
|
+
try { fs.fsyncSync(fd); } catch {}
|
|
427
|
+
} finally {
|
|
428
|
+
fs.closeSync(fd);
|
|
429
|
+
}
|
|
430
|
+
fs.renameSync(temporary, statusPath);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function out(message) {
|
|
434
|
+
process.stdout.write(JSON.stringify({ followup_message: message }));
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// The stall text always reaches stderr so a second, different rejection is never
|
|
438
|
+
// silent; `out()` fires only when the stop enters the stall, so the follow-up
|
|
439
|
+
// message cannot loop.
|
|
440
|
+
function emitArtifactStall(message, announce) {
|
|
441
|
+
if (message) process.stderr.write(message + '\n');
|
|
442
|
+
if (message && announce) out(message);
|
|
443
|
+
else process.stdout.write('{}');
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function readArtifact(name) {
|
|
447
|
+
const p = path.join(taskDir, name);
|
|
448
|
+
if (!fs.existsSync(p)) return '';
|
|
449
|
+
try {
|
|
450
|
+
return fs.readFileSync(p, 'utf8');
|
|
451
|
+
} catch {
|
|
452
|
+
return '';
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function getStepAgents(step) {
|
|
457
|
+
if (!step) return [];
|
|
458
|
+
return Array.isArray(step.agent) ? step.agent : [step.agent];
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function skipIfMatches(skipIf, dir) {
|
|
462
|
+
if (!skipIf) return false;
|
|
463
|
+
if (skipIf === 'debugger.fixed') {
|
|
464
|
+
const text = readArtifact('debug-report.md');
|
|
465
|
+
return /fixApplied:\s*true/i.test(text) || /\*\*Fix applied:\*\*\s*true/i.test(text);
|
|
466
|
+
}
|
|
467
|
+
if (skipIf === 'ci-investigator.resolved') {
|
|
468
|
+
const text = readArtifact('ci-report.md');
|
|
469
|
+
return /fixApplied:\s*true/i.test(text) || /## Verdict\s*\nPASS/i.test(text);
|
|
470
|
+
}
|
|
471
|
+
return false;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function findNextExecutableStep(steps, startIdx, dir) {
|
|
475
|
+
for (let i = startIdx; i < steps.length; i++) {
|
|
476
|
+
if (!skipIfMatches(steps[i].skipIf, dir)) return { step: steps[i], index: i };
|
|
477
|
+
recordSkippedStep(steps[i], i);
|
|
478
|
+
}
|
|
479
|
+
return null;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
// --- Parallel scheduling & conflict model (mirrors _shared/core/agent-team/plan-graph.md) ---
|
|
483
|
+
function isGraphMode() { return steps.some((step) => step && Array.isArray(step.dependsOn)); }
|
|
484
|
+
function graphSlotKey(stepIndex, agent) { return `${stepIndex}:${agent}`; }
|
|
485
|
+
function readJoinedSlots() { return { ...(status.joinedSlots || {}) }; }
|
|
486
|
+
function isSlotSatisfied(stepIndex, agent) { return Boolean((status.joinedSlots || {})[graphSlotKey(stepIndex, agent)]); }
|
|
487
|
+
function resolveStepIndex(dep) {
|
|
488
|
+
for (let i = 0; i < steps.length; i += 1) if (steps[i] && steps[i].id === dep) return i;
|
|
489
|
+
for (let i = 0; i < steps.length; i += 1) {
|
|
490
|
+
const ids = Array.isArray(steps[i]?.taskIds) ? steps[i].taskIds : [];
|
|
491
|
+
if (ids.includes(dep)) return i;
|
|
492
|
+
}
|
|
493
|
+
return -1;
|
|
494
|
+
}
|
|
495
|
+
function isStepSkipped(stepIndex) {
|
|
496
|
+
if (Array.isArray(status.skippedSteps) && status.skippedSteps.includes(stepIndex)) return true;
|
|
497
|
+
return skipIfMatches(steps[stepIndex]?.skipIf, taskDir);
|
|
498
|
+
}
|
|
499
|
+
function isStepSatisfied(stepIndex) {
|
|
500
|
+
const step = steps[stepIndex];
|
|
501
|
+
if (!step) return false;
|
|
502
|
+
if (isStepSkipped(stepIndex)) return true;
|
|
503
|
+
return getStepAgents(step).every((agent) => isSlotSatisfied(stepIndex, agent));
|
|
504
|
+
}
|
|
505
|
+
function pendingStepIndexes() { return steps.map((_, index) => index).filter((index) => !isStepSatisfied(index)); }
|
|
506
|
+
function unsatisfiedAgents(stepIndex) {
|
|
507
|
+
const step = steps[stepIndex];
|
|
508
|
+
if (!step) return [];
|
|
509
|
+
return getStepAgents(step).filter((agent) => !isSlotSatisfied(stepIndex, agent));
|
|
510
|
+
}
|
|
511
|
+
function declaredScopes(step) {
|
|
512
|
+
return Array.isArray(step?.writeScopes) ? step.writeScopes.filter((scope) => typeof scope === 'string' && scope.length > 0) : [];
|
|
513
|
+
}
|
|
514
|
+
function normalizeScope(scope) { return String(scope).replace(/\/+$/, ''); }
|
|
515
|
+
function scopesOverlap(left, right) {
|
|
516
|
+
const a = normalizeScope(left); const b = normalizeScope(right);
|
|
517
|
+
return a === b || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);
|
|
518
|
+
}
|
|
519
|
+
function stepsConflict(leftIndex, rightIndex) {
|
|
520
|
+
if (leftIndex === rightIndex) return true;
|
|
521
|
+
const leftStep = steps[leftIndex]; const rightStep = steps[rightIndex];
|
|
522
|
+
const leftAgents = getStepAgents(leftStep); const rightAgents = getStepAgents(rightStep);
|
|
523
|
+
if (leftAgents.some((agent) => rightAgents.includes(agent))) return true;
|
|
524
|
+
const leftOutputs = new Set(leftAgents.map((agent) => artifactOutputIdFor(leftStep, agent)));
|
|
525
|
+
if (rightAgents.some((agent) => leftOutputs.has(artifactOutputIdFor(rightStep, agent)))) return true;
|
|
526
|
+
// An undeclared scope is unknown, and an unknown unit conflicts with everything (safe default).
|
|
527
|
+
const leftScopes = declaredScopes(leftStep); const rightScopes = declaredScopes(rightStep);
|
|
528
|
+
if (leftScopes.length === 0 || rightScopes.length === 0) return true;
|
|
529
|
+
for (const a of leftScopes) for (const b of rightScopes) if (scopesOverlap(a, b)) return true;
|
|
530
|
+
return false;
|
|
531
|
+
}
|
|
532
|
+
function selectWave(candidates) {
|
|
533
|
+
const wave = []; const deferred = [];
|
|
534
|
+
for (const index of candidates) {
|
|
535
|
+
if (wave.every((chosen) => !stepsConflict(chosen, index))) wave.push(index);
|
|
536
|
+
else deferred.push(index);
|
|
537
|
+
}
|
|
538
|
+
return { wave, deferred };
|
|
539
|
+
}
|
|
540
|
+
function invalidateFrom(stepIndex, preserveStepIndex) {
|
|
541
|
+
const remove = new Set([stepIndex]);
|
|
542
|
+
let changed = true;
|
|
543
|
+
while (changed) {
|
|
544
|
+
changed = false;
|
|
545
|
+
for (let i = 0; i < steps.length; i += 1) {
|
|
546
|
+
if (remove.has(i)) continue;
|
|
547
|
+
const deps = Array.isArray(steps[i]?.dependsOn) ? steps[i].dependsOn : [];
|
|
548
|
+
if (deps.some((dep) => { const j = resolveStepIndex(dep); return j >= 0 && remove.has(j); })) { remove.add(i); changed = true; }
|
|
549
|
+
}
|
|
550
|
+
}
|
|
551
|
+
// Preserve the requesting step's satisfied slots so a sibling is never re-invoked.
|
|
552
|
+
if (Number.isInteger(preserveStepIndex)) remove.delete(preserveStepIndex);
|
|
553
|
+
const slots = readJoinedSlots();
|
|
554
|
+
const removedAgents = new Set();
|
|
555
|
+
for (const key of Object.keys(slots)) {
|
|
556
|
+
const index = Number(key.split(':')[0]);
|
|
557
|
+
if (remove.has(index)) { removedAgents.add(slots[key].agent); delete slots[key]; }
|
|
558
|
+
}
|
|
559
|
+
status.joinedSlots = slots;
|
|
560
|
+
status.parallelCompleted = (status.parallelCompleted || []).filter((agent) => !removedAgents.has(agent));
|
|
561
|
+
return remove;
|
|
562
|
+
}
|
|
563
|
+
function computeReadySteps() {
|
|
564
|
+
if (!isGraphMode()) return [];
|
|
565
|
+
const inFlight = new Set(Object.values(status.activeAttempts || {}).map((entry) => entry.stepIndex));
|
|
566
|
+
const blocked = new Set(Array.isArray(status.blockedSteps) ? status.blockedSteps : []);
|
|
567
|
+
const skipped = new Set(Array.isArray(status.skippedSteps) ? status.skippedSteps : []);
|
|
568
|
+
const ready = [];
|
|
569
|
+
for (let i = 0; i < steps.length; i += 1) {
|
|
570
|
+
if (blocked.has(i) || inFlight.has(i)) continue;
|
|
571
|
+
if (skipIfMatches(steps[i].skipIf, taskDir)) {
|
|
572
|
+
if (!skipped.has(i)) { recordSkippedStep(steps[i], i); skipped.add(i); }
|
|
573
|
+
continue;
|
|
574
|
+
}
|
|
575
|
+
if (isStepSatisfied(i)) continue;
|
|
576
|
+
const deps = Array.isArray(steps[i].dependsOn) ? steps[i].dependsOn : [];
|
|
577
|
+
if (deps.every((dep) => { const j = resolveStepIndex(dep); return j >= 0 && isStepSatisfied(j); })) ready.push(i);
|
|
578
|
+
}
|
|
579
|
+
status.skippedSteps = [...skipped];
|
|
580
|
+
return ready;
|
|
581
|
+
}
|
|
582
|
+
function handoffForWave(units, waveId) {
|
|
583
|
+
const labels = units.map((unit) => `${steps[unit.stepIndex].id || `step-${unit.stepIndex}`}=${unit.agent}`);
|
|
584
|
+
const attemptIds = Object.entries(status.activeAttempts || {})
|
|
585
|
+
.filter(([, entry]) => units.some((unit) => unit.stepIndex === entry.stepIndex && unit.agent === entry.agent))
|
|
586
|
+
.map(([attemptId, entry]) => `${entry.agent}=${attemptId}`);
|
|
587
|
+
const outputIds = units.map((unit) => `${unit.agent}=${artifactOutputIdFor(steps[unit.stepIndex], unit.agent)}`);
|
|
588
|
+
const inputIds = [...new Set(units.flatMap((unit) => (Array.isArray(steps[unit.stepIndex].artifactInputIds) ? steps[unit.stepIndex].artifactInputIds : [])))];
|
|
589
|
+
return (
|
|
590
|
+
`Invoke IN PARALLEL (one message, multiple Task calls): ${labels.join(' AND ')} for slug "${slug}"${waveId ? ` (waveId=${waveId})` : ''}. ` +
|
|
591
|
+
`Each agent writes its artifact and owned receipt; the hook records slot joins from stops. Do not mutate status.json lifecycle fields. ` +
|
|
592
|
+
`Artifact inputs: ${inputIds.length > 0 ? inputIds.join(', ') : 'manifest defaults'}; owned output IDs: ${outputIds.join('; ')}. ` +
|
|
593
|
+
`Metrics attemptIds: ${attemptIds.join('; ')}. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not calculate duration.`
|
|
594
|
+
);
|
|
595
|
+
}
|
|
596
|
+
function blockedNotice(blockedIndex, agent) {
|
|
597
|
+
const gated = [];
|
|
598
|
+
for (let i = 0; i < steps.length; i += 1) {
|
|
599
|
+
if (i === blockedIndex || isStepSatisfied(i)) continue;
|
|
600
|
+
const deps = Array.isArray(steps[i].dependsOn) ? steps[i].dependsOn : [];
|
|
601
|
+
if (deps.some((dep) => resolveStepIndex(dep) === blockedIndex)) gated.push(steps[i].id || `step-${i}`);
|
|
602
|
+
}
|
|
603
|
+
return `Step ${blockedIndex} (${agent}) is blocked for slug "${slug}"${gated.length > 0 ? ` and gates: ${gated.join(', ')}` : ''}. No independent ready step remains. Resume only via /task-continue ${slug}.`;
|
|
604
|
+
}
|
|
605
|
+
function noProgressNotice() {
|
|
606
|
+
const pending = pendingStepIndexes().map((index) => steps[index].id || `step-${index}`);
|
|
607
|
+
return `No schedulable step remains for slug "${slug}" (unsatisfied: ${pending.join(', ')}). Resume only via /task-continue ${slug}.`;
|
|
608
|
+
}
|
|
609
|
+
function dispatchReadyWave(prefixMessage) {
|
|
610
|
+
const ready = computeReadySteps();
|
|
611
|
+
if (ready.length === 0) return false;
|
|
612
|
+
const { wave, deferred } = selectWave(ready);
|
|
613
|
+
if (deferred.length > 0) {
|
|
614
|
+
appendMetric({ type: 'parallel_conflict_deferred', at: now, stepIndex: wave[0], deferredStepIndexes: deferred, reason: 'ready set not conflict-free or writeScopes undeclared', source: 'hook', attributionConfidence: 'fallback' });
|
|
615
|
+
}
|
|
616
|
+
// Slot-filtered dispatch: only unsatisfied (stepIndex, agent) slots are invoked.
|
|
617
|
+
const units = wave.flatMap((stepIndex) => unsatisfiedAgents(stepIndex).map((agent) => ({ stepIndex, agent })));
|
|
618
|
+
if (units.length === 0) return false;
|
|
619
|
+
const first = units[0].stepIndex;
|
|
620
|
+
const waveId = `${status.metricsRunId || slug}:wave-${first}`;
|
|
621
|
+
for (const unit of units) activateAttempts(steps[unit.stepIndex], unit.stepIndex, units.length > 1 ? waveId : null, [unit.agent]);
|
|
622
|
+
writeStatus({
|
|
623
|
+
pipelineIndex: first,
|
|
624
|
+
currentAgent: units[0].agent,
|
|
625
|
+
phase: 'executing',
|
|
626
|
+
state: 'in_progress',
|
|
627
|
+
awaitingHumanGate: false,
|
|
628
|
+
parallelCompleted: [],
|
|
629
|
+
parallelOutcomes: {},
|
|
630
|
+
waveSteps: wave,
|
|
631
|
+
waveId,
|
|
632
|
+
});
|
|
633
|
+
const stepIndexes = [...new Set(units.map((unit) => unit.stepIndex))];
|
|
634
|
+
appendMetric({ type: 'parallel_wave_started', at: now, waveId, stepIndexes, agents: units.map((unit) => unit.agent), source: 'hook', attributionConfidence: 'high' });
|
|
635
|
+
let message;
|
|
636
|
+
if (units.length === 1) message = handoffForAgent(units[0].agent, steps[first]?.scope, steps[first]);
|
|
637
|
+
else if (stepIndexes.length === 1 && steps[first].parallel && units.length === getStepAgents(steps[first]).length) message = handoffForParallelStep(steps[first]);
|
|
638
|
+
else message = handoffForWave(units, waveId);
|
|
639
|
+
out(prefixMessage ? `${prefixMessage} ${message}` : message);
|
|
640
|
+
return true;
|
|
641
|
+
}
|
|
642
|
+
function resolveProducerStepIndex(agent, fromIndex) {
|
|
643
|
+
const seen = new Set([fromIndex]);
|
|
644
|
+
const stack = [fromIndex];
|
|
645
|
+
let best = -1;
|
|
646
|
+
while (stack.length > 0) {
|
|
647
|
+
const node = stack.pop();
|
|
648
|
+
const deps = Array.isArray(steps[node]?.dependsOn) ? steps[node].dependsOn : [];
|
|
649
|
+
for (const dep of deps) {
|
|
650
|
+
const j = resolveStepIndex(dep);
|
|
651
|
+
if (j < 0 || seen.has(j)) continue;
|
|
652
|
+
seen.add(j);
|
|
653
|
+
if (getStepAgents(steps[j]).includes(agent)) best = Math.max(best, j);
|
|
654
|
+
stack.push(j);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
return best >= 0 ? best : -1;
|
|
658
|
+
}
|
|
659
|
+
function repairUnattributableStop() {
|
|
660
|
+
const entries = Object.entries(status.activeAttempts || {});
|
|
661
|
+
if (entries.length === 0) return null;
|
|
662
|
+
const bindByAgent = (agent) => {
|
|
663
|
+
if (!agent) return null;
|
|
664
|
+
const matches = entries.filter(([, entry]) => entry.agent === agent);
|
|
665
|
+
return matches.length === 1 ? { attemptId: matches[0][0], entry: matches[0][1], confidence: 'fallback', repaired: true } : null;
|
|
666
|
+
};
|
|
667
|
+
const payloadAgent = typeof hookInput.agentType === 'string' ? hookInput.agentType : (typeof hookInput.agent_type === 'string' ? hookInput.agent_type : null);
|
|
668
|
+
const byPayload = bindByAgent(payloadAgent);
|
|
669
|
+
if (byPayload) return byPayload;
|
|
670
|
+
if (Array.isArray(status.waveSteps) && status.waveSteps.length > 0) {
|
|
671
|
+
const outcomes = status.parallelOutcomes || {};
|
|
672
|
+
const unrecorded = status.waveSteps.flatMap((index) => getStepAgents(steps[index])).filter((agent) => !outcomes[agent]);
|
|
673
|
+
if (unrecorded.length === 1) { const bySole = bindByAgent(unrecorded[0]); if (bySole) return bySole; }
|
|
674
|
+
}
|
|
675
|
+
const byCurrent = bindByAgent(status.currentAgent);
|
|
676
|
+
if (byCurrent) return byCurrent;
|
|
677
|
+
return null;
|
|
678
|
+
}
|
|
679
|
+
function repairHandoffMessage() {
|
|
680
|
+
const listing = Object.entries(status.activeAttempts || {}).map(([attemptId, entry]) => `${entry.agent}=${attemptId}`).join('; ');
|
|
681
|
+
return `Parallel stop could not be attributed for slug "${slug}": in-flight attempts ${listing}; no payload attemptId and no bound receipt for the finished agent. Resume deterministically: append a minimal { attemptId, outcome } receipt for the agent that just finished to .ai.local/team/tasks/${slug}/.metrics-receipts.json, then re-run the installed hooks/chain-team-phases.sh with that attemptId. Do not edit status.json manually.`;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const AGENT_HANDOFF = {
|
|
685
|
+
// <<<hook-slot:AGENT_HANDOFF>>>
|
|
686
|
+
// <<<hook-slot:/AGENT_HANDOFF>>>
|
|
687
|
+
};
|
|
688
|
+
|
|
689
|
+
const REVIEW_AGENTS = new Set([
|
|
690
|
+
'code-reviewer',
|
|
691
|
+
'accessibility-reviewer',
|
|
692
|
+
'security-reviewer',
|
|
693
|
+
'api-contract-reviewer',
|
|
694
|
+
]);
|
|
695
|
+
|
|
696
|
+
function metricsHandoff(agent) {
|
|
697
|
+
const matches = Object.entries(status.activeAttempts || {}).filter(([, entry]) => entry.agent === agent);
|
|
698
|
+
if (matches.length === 1) {
|
|
699
|
+
return ` Metrics attemptId: ${matches[0][0]}; write owned artifact-manifest receipt outcome. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not mutate status.json or calculate duration.`;
|
|
700
|
+
}
|
|
701
|
+
return ' Metrics: use the supplied attemptId when available; for a parallel completion, write a minimal { attemptId, outcome } receipt to .metrics-receipts.json rather than relying on currentAgent. Do not calculate duration.';
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
function artifactHandoff(step, agent) {
|
|
705
|
+
const inputIds = Array.isArray(step?.artifactInputIds) ? step.artifactInputIds.join(', ') : 'manifest defaults';
|
|
706
|
+
return ` Artifact inputs: ${inputIds}; owned output ID: ${artifactOutputIdFor(step, agent)}. Bind the terminal receipt to the supplied attemptId.`;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
function handoffForAgent(agent, scope, step = null) {
|
|
710
|
+
const fn = AGENT_HANDOFF[agent];
|
|
711
|
+
const handoff = fn ? fn(slug, scope) : `Invoke ${agent} subagent for slug "${slug}". Upsert the owned terminal receipt in artifact-manifest.json; do not mutate status.json lifecycle fields.`;
|
|
712
|
+
return handoff + artifactHandoff(step, agent) + metricsHandoff(agent);
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
function handoffForParallelStep(step) {
|
|
716
|
+
const agents = getStepAgents(step);
|
|
717
|
+
const attemptIds = Object.entries(status.activeAttempts || {})
|
|
718
|
+
.filter(([, entry]) => agents.includes(entry.agent))
|
|
719
|
+
.map(([attemptId, entry]) => `${entry.agent}=${attemptId}`);
|
|
720
|
+
return (
|
|
721
|
+
`Invoke IN PARALLEL (one message, multiple Task calls): ${agents.join(' AND ')} for slug "${slug}". ` +
|
|
722
|
+
`Each agent writes its artifact and owned receipt; the hook records parallelCompleted from stops. Do not mutate status.json lifecycle fields. ` +
|
|
723
|
+
`Artifact inputs: ${Array.isArray(step.artifactInputIds) ? step.artifactInputIds.join(', ') : 'manifest defaults'}; owned output IDs: ${agents.map((agent) => `${agent}=${artifactOutputIdFor(step, agent)}`).join('; ')}. ` +
|
|
724
|
+
`Metrics attemptIds: ${attemptIds.join('; ')}. If the hook cannot identify a parallel stop, append a minimal { attemptId, outcome } receipt to .metrics-receipts.json; do not calculate duration.`
|
|
725
|
+
);
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
function hasGateAfter(agent, humanGates) {
|
|
729
|
+
return Array.isArray(humanGates) && humanGates.includes(`after:${agent}`);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
function hasGateAfterStep(step, humanGates) {
|
|
733
|
+
return getStepAgents(step).some((a) => hasGateAfter(a, humanGates));
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
function legacyFlow() {
|
|
737
|
+
// <<<hook-slot:LEGACY_FLOW>>>
|
|
738
|
+
// <<<hook-slot:/LEGACY_FLOW>>>
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
|
|
742
|
+
if (hookInput.action === 'end_human_gate') {
|
|
743
|
+
// Only advance when a gate was actually open. A duplicate or retried
|
|
744
|
+
// end_human_gate must be a no-op, not a silent pipeline skip.
|
|
745
|
+
const gateWasOpen = Boolean(status.activeHumanGateEventId) || status.awaitingHumanGate === true;
|
|
746
|
+
status.awaitingHumanGate = false;
|
|
747
|
+
// A2 (retro §8): pin a single runId per pipeline so subsequent events don't
|
|
748
|
+
// fragment the metrics ledger across multiple runId sequences. Prefer
|
|
749
|
+
// metrics.json.task.runId when metrics already exist, then status.metricsRunId,
|
|
750
|
+
// then mint a fresh seed only on first ever emit.
|
|
751
|
+
try {
|
|
752
|
+
if (fs.existsSync(METRICS_PATH)) {
|
|
753
|
+
const existing = JSON.parse(fs.readFileSync(METRICS_PATH, 'utf8'));
|
|
754
|
+
if (existing && existing.task && typeof existing.task.runId === 'string') {
|
|
755
|
+
status.metricsRunId = existing.task.runId;
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
} catch {}
|
|
759
|
+
if (status.state === 'awaiting_approval') {
|
|
760
|
+
status.state = 'in_progress';
|
|
761
|
+
status.phase = status.phase === 'human_gate' ? 'executing' : status.phase;
|
|
762
|
+
}
|
|
763
|
+
if (status.activeHumanGateEventId) {
|
|
764
|
+
appendMetric({
|
|
765
|
+
type: 'human_gate_ended',
|
|
766
|
+
at: now,
|
|
767
|
+
gateStartedEventId: status.activeHumanGateEventId,
|
|
768
|
+
source: 'orchestrator',
|
|
769
|
+
attributionConfidence: 'high',
|
|
770
|
+
});
|
|
771
|
+
delete status.activeHumanGateEventId;
|
|
772
|
+
}
|
|
773
|
+
if (gateWasOpen && hookInput.activateNext && fs.existsSync(pipelinePath)) {
|
|
774
|
+
let resumePipeline = null;
|
|
775
|
+
try { resumePipeline = JSON.parse(fs.readFileSync(pipelinePath, 'utf8')); } catch {}
|
|
776
|
+
if (resumePipeline) {
|
|
777
|
+
const resumeSteps = resumePipeline.steps || [];
|
|
778
|
+
if (resumeSteps.some((step) => step && Array.isArray(step.dependsOn))) {
|
|
779
|
+
steps = resumeSteps;
|
|
780
|
+
status.blockedSteps = [];
|
|
781
|
+
status.parallelCompleted = [];
|
|
782
|
+
status.parallelOutcomes = {};
|
|
783
|
+
status.waveSteps = [];
|
|
784
|
+
status.waveId = null;
|
|
785
|
+
if (dispatchReadyWave()) process.exit(0);
|
|
786
|
+
if (pendingStepIndexes().length === 0) {
|
|
787
|
+
status.state = 'completed';
|
|
788
|
+
completeTaskMetrics();
|
|
789
|
+
writeStatus({ pipelineIndex: resumeSteps.length, phase: 'done', state: 'completed', currentAgent: null, awaitingHumanGate: false });
|
|
790
|
+
out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);
|
|
791
|
+
process.exit(0);
|
|
792
|
+
}
|
|
793
|
+
out(noProgressNotice());
|
|
794
|
+
process.exit(0);
|
|
795
|
+
}
|
|
796
|
+
const resumeStart = (typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0) + 1;
|
|
797
|
+
const resumeNext = findNextExecutableStep(resumeSteps, resumeStart, taskDir);
|
|
798
|
+
if (resumeNext) {
|
|
799
|
+
const resumeAgents = getStepAgents(resumeNext.step);
|
|
800
|
+
activateAttempts(resumeNext.step, resumeNext.index);
|
|
801
|
+
writeStatus({
|
|
802
|
+
pipelineIndex: resumeNext.index,
|
|
803
|
+
currentAgent: resumeAgents[0],
|
|
804
|
+
phase: 'executing',
|
|
805
|
+
state: 'in_progress',
|
|
806
|
+
awaitingHumanGate: false,
|
|
807
|
+
parallelCompleted: [],
|
|
808
|
+
});
|
|
809
|
+
if (resumeNext.step.parallel && resumeAgents.length > 1) out(handoffForParallelStep(resumeNext.step));
|
|
810
|
+
else out(handoffForAgent(resumeAgents[0], resumeNext.step.scope, resumeNext.step));
|
|
811
|
+
process.exit(0);
|
|
812
|
+
}
|
|
813
|
+
// Gate on the final step: no executable step remains. Complete the
|
|
814
|
+
// pipeline instead of leaving it in_progress forever.
|
|
815
|
+
status.state = 'completed';
|
|
816
|
+
completeTaskMetrics();
|
|
817
|
+
writeStatus({
|
|
818
|
+
pipelineIndex: resumeSteps.length,
|
|
819
|
+
phase: 'done',
|
|
820
|
+
state: 'completed',
|
|
821
|
+
currentAgent: null,
|
|
822
|
+
awaitingHumanGate: false,
|
|
823
|
+
});
|
|
824
|
+
out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);
|
|
825
|
+
process.exit(0);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
// A2 (retro §8): if gate closes the final human gate of the pipeline
|
|
829
|
+
// (no resume happens, or current step's gate was the last), surface
|
|
830
|
+
// state="awaiting_approval" so a subsequent /task-continue doesn't misinterpret
|
|
831
|
+
// the post-gate idle state as "still in progress".
|
|
832
|
+
{
|
|
833
|
+
let gateWasTerminal = false;
|
|
834
|
+
if (!hookInput.activateNext && fs.existsSync(pipelinePath)) {
|
|
835
|
+
try {
|
|
836
|
+
const pipe = JSON.parse(fs.readFileSync(pipelinePath, 'utf8'));
|
|
837
|
+
const steps = pipe.steps || [];
|
|
838
|
+
const idx = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
|
|
839
|
+
const cur = steps[idx];
|
|
840
|
+
const gates = Array.isArray(pipe.humanGates) ? pipe.humanGates : [];
|
|
841
|
+
const hasGate = (step) => Array.isArray(gates) && gates.some((g) => typeof g === 'string' && getStepAgents(step).some((a) => g === `after:${a}`));
|
|
842
|
+
if (cur && hasGate(cur)) gateWasTerminal = true;
|
|
843
|
+
} catch {}
|
|
844
|
+
}
|
|
845
|
+
writeStatus({
|
|
846
|
+
awaitingHumanGate: false,
|
|
847
|
+
state: gateWasTerminal ? 'awaiting_approval' : status.state,
|
|
848
|
+
phase: status.phase,
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
process.stdout.write(JSON.stringify({ ok: true, action: 'end_human_gate', activeHumanGateEventId: status.activeHumanGateEventId || null }));
|
|
852
|
+
process.exit(0);
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
if (!fs.existsSync(pipelinePath)) {
|
|
856
|
+
legacyFlow();
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
let pipeline;
|
|
860
|
+
let pipelineParseError = null;
|
|
861
|
+
try {
|
|
862
|
+
pipeline = JSON.parse(fs.readFileSync(pipelinePath, 'utf8'));
|
|
863
|
+
} catch (error) {
|
|
864
|
+
pipelineParseError = error;
|
|
865
|
+
}
|
|
866
|
+
// Modern pipelines carry an `intent` field. If pipeline.json is present but
|
|
867
|
+
// unparseable, surface the error so the orchestrator can stop and report
|
|
868
|
+
// instead of falling back to legacyFlow() — which silently drops modern
|
|
869
|
+
// roles like `openspec-author`, `qa-tester`, and the test-planner trio.
|
|
870
|
+
if (pipelineParseError) {
|
|
871
|
+
if (fs.existsSync(pipelinePath)) {
|
|
872
|
+
const raw = fs.readFileSync(pipelinePath, 'utf8');
|
|
873
|
+
const hasModernIntent = /"intent"\s*:/.test(raw);
|
|
874
|
+
appendMetric({
|
|
875
|
+
eventId: `${status.metricsRunId || slug}:pipeline_parse_error:${Date.now()}`,
|
|
876
|
+
type: 'pipeline_parse_error',
|
|
877
|
+
at: now,
|
|
878
|
+
source: 'hook',
|
|
879
|
+
attributionConfidence: 'high',
|
|
880
|
+
error: String(pipelineParseError.message || pipelineParseError),
|
|
881
|
+
hasModernIntent,
|
|
882
|
+
});
|
|
883
|
+
if (hasModernIntent) {
|
|
884
|
+
writeStatus({ state: 'blocked', phase: 'blocked', currentAgent: 'task-router' });
|
|
885
|
+
process.stdout.write(JSON.stringify({
|
|
886
|
+
followup_message: `pipeline.json is malformed for slug "${slug}" — JSON parse error: ${pipelineParseError.message}. Re-run the task-router to regenerate pipeline.json, then resume via /task-continue ${slug}.`,
|
|
887
|
+
}));
|
|
888
|
+
process.exit(0);
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
legacyFlow();
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
steps = pipeline.steps || [];
|
|
895
|
+
const initialIdx = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
|
|
896
|
+
const initialStep = steps[initialIdx];
|
|
897
|
+
const activeAttemptCountBeforeFinish = Object.keys(status.activeAttempts || {}).length;
|
|
898
|
+
const completingAgentHint = (() => {
|
|
899
|
+
const resolved = resolvedAttempt();
|
|
900
|
+
if (resolved?.entry?.agent) return resolved.entry.agent;
|
|
901
|
+
if (status.currentAgent) return status.currentAgent;
|
|
902
|
+
return getStepAgents(initialStep)[0];
|
|
903
|
+
})();
|
|
904
|
+
const reconcilingAttempt = resolvedAttempt();
|
|
905
|
+
const wasWaitingForReceipt = status.state === 'awaiting_artifact_receipt';
|
|
906
|
+
reconcileStatusFromManifest(completingAgentHint, initialStep, reconcilingAttempt);
|
|
907
|
+
if (status.state === 'awaiting_artifact_receipt') {
|
|
908
|
+
writeStatus({});
|
|
909
|
+
emitArtifactStall(artifactStallMessage, !wasWaitingForReceipt);
|
|
910
|
+
process.exit(0);
|
|
911
|
+
}
|
|
912
|
+
let finishedAttempt = finishActiveAttempt();
|
|
913
|
+
if (!finishedAttempt && activeAttemptCountBeforeFinish > 0) {
|
|
914
|
+
if (!hookInput.attemptId) {
|
|
915
|
+
const repaired = repairUnattributableStop();
|
|
916
|
+
if (repaired) {
|
|
917
|
+
appendMetric({ type: 'parallel_attribution_repair', at: now, attemptIds: [repaired.attemptId], source: 'hook', attributionConfidence: 'fallback' });
|
|
918
|
+
reconcileStatusFromManifest(repaired.entry.agent, steps[repaired.entry.stepIndex], repaired);
|
|
919
|
+
if (status.state === 'awaiting_artifact_receipt') {
|
|
920
|
+
writeStatus({});
|
|
921
|
+
emitArtifactStall(artifactStallMessage, true);
|
|
922
|
+
process.exit(0);
|
|
923
|
+
}
|
|
924
|
+
finishedAttempt = finishActiveAttempt(repaired);
|
|
925
|
+
} else {
|
|
926
|
+
writeStatus({});
|
|
927
|
+
out(repairHandoffMessage());
|
|
928
|
+
process.exit(0);
|
|
929
|
+
}
|
|
930
|
+
} else {
|
|
931
|
+
process.stdout.write('{}');
|
|
932
|
+
process.exit(0);
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
endHumanGateIfResumed();
|
|
936
|
+
if (steps.length === 0 || pipeline.autoChain === false) {
|
|
937
|
+
writeStatus({});
|
|
938
|
+
process.stdout.write('{}');
|
|
939
|
+
process.exit(0);
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
if (status.awaitingHumanGate || status.state === 'awaiting_approval') {
|
|
943
|
+
process.stdout.write('{}');
|
|
944
|
+
process.exit(0);
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
function nearestPrecedingStepIndex(agent, fromIndex, fallback) {
|
|
948
|
+
for (let index = fromIndex - 1; index >= 0; index -= 1) {
|
|
949
|
+
if (getStepAgents(steps[index]).includes(agent)) return index;
|
|
950
|
+
}
|
|
951
|
+
const match = steps.findIndex((step) => getStepAgents(step).includes(agent));
|
|
952
|
+
return match >= 0 ? match : fallback;
|
|
953
|
+
}
|
|
954
|
+
function scheduleRetry(agent, retryAfterFix, predecessor, explicitStepIndex = null) {
|
|
955
|
+
const currentIndex = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
|
|
956
|
+
const explicitOk = Number.isInteger(explicitStepIndex) && getStepAgents(steps[explicitStepIndex]).includes(agent);
|
|
957
|
+
const stepIndex = explicitOk ? explicitStepIndex : nearestPrecedingStepIndex(agent, currentIndex, -1);
|
|
958
|
+
// Refuse to activate an agent the pipeline never planned; callers fall back to a human gate.
|
|
959
|
+
if (stepIndex < 0) return -1;
|
|
960
|
+
const predecessorAttemptId = predecessor?.attemptId || status.lastCompletedAttempt?.attemptId || null;
|
|
961
|
+
appendMetric({ type: 'retry_scheduled', at: now, attemptId: predecessorAttemptId, nextAgent: agent, retryAfterFix: retryAfterFix || null, source: 'hook', attributionConfidence: predecessor ? predecessor.confidence : 'unknown' });
|
|
962
|
+
activateAttempts(steps[stepIndex] || { agent }, stepIndex);
|
|
963
|
+
return stepIndex;
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
const idx = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
|
|
967
|
+
const currentStep = steps[idx];
|
|
968
|
+
const completedAgent = finishedAttempt?.entry?.agent || status.currentAgent || getStepAgents(currentStep)[0];
|
|
969
|
+
const completedStepIndex = Number.isInteger(finishedAttempt?.entry?.stepIndex) ? finishedAttempt.entry.stepIndex : idx;
|
|
970
|
+
const stepAgents = getStepAgents(currentStep);
|
|
971
|
+
const activeWave = isGraphMode() && Array.isArray(status.waveSteps) && status.waveSteps.filter((i) => Number.isInteger(i) && steps[i]).length > 0
|
|
972
|
+
? status.waveSteps.filter((i) => Number.isInteger(i) && steps[i])
|
|
973
|
+
: null;
|
|
974
|
+
const waveIndexes = activeWave
|
|
975
|
+
? activeWave
|
|
976
|
+
: (currentStep?.parallel && stepAgents.length > 1
|
|
977
|
+
? [idx]
|
|
978
|
+
: (isGraphMode() && finishedAttempt ? [completedStepIndex] : null));
|
|
979
|
+
|
|
980
|
+
|
|
981
|
+
if (waveIndexes) {
|
|
982
|
+
const waveAgents = waveIndexes.flatMap((i) => getStepAgents(steps[i]));
|
|
983
|
+
const done = [...(status.parallelCompleted || [])];
|
|
984
|
+
if (isGraphMode()) {
|
|
985
|
+
for (const waveStep of waveIndexes) {
|
|
986
|
+
for (const waveAgent of getStepAgents(steps[waveStep])) {
|
|
987
|
+
if (isSlotSatisfied(waveStep, waveAgent) && !done.includes(waveAgent)) done.push(waveAgent);
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
const outcomes = { ...(status.parallelOutcomes || {}) };
|
|
992
|
+
if (finishedAttempt && completedAgent) {
|
|
993
|
+
if (!done.includes(completedAgent)) done.push(completedAgent);
|
|
994
|
+
outcomes[completedAgent] = {
|
|
995
|
+
outcome: finishedAttempt.outcome || status.state,
|
|
996
|
+
attemptId: finishedAttempt.attemptId,
|
|
997
|
+
confidence: finishedAttempt.confidence,
|
|
998
|
+
};
|
|
999
|
+
}
|
|
1000
|
+
if (finishedAttempt && completedAgent && isGraphMode() && (finishedAttempt.outcome || status.state) === 'completed') {
|
|
1001
|
+
const completedSlots = readJoinedSlots();
|
|
1002
|
+
completedSlots[graphSlotKey(completedStepIndex, completedAgent)] = {
|
|
1003
|
+
agent: completedAgent,
|
|
1004
|
+
stepIndex: completedStepIndex,
|
|
1005
|
+
attemptId: finishedAttempt.attemptId,
|
|
1006
|
+
outcome: 'completed',
|
|
1007
|
+
};
|
|
1008
|
+
status.joinedSlots = completedSlots;
|
|
1009
|
+
appendMetric({ type: 'step_joined', at: now, stepIndex: completedStepIndex, slotKeys: [graphSlotKey(completedStepIndex, completedAgent)], attemptIds: [finishedAttempt.attemptId], source: 'hook', attributionConfidence: 'high' });
|
|
1010
|
+
}
|
|
1011
|
+
writeStatus({ parallelCompleted: done, parallelOutcomes: outcomes });
|
|
1012
|
+
const remaining = waveAgents.filter((agent) => !done.includes(agent));
|
|
1013
|
+
if (remaining.length > 0) {
|
|
1014
|
+
process.stdout.write('{}');
|
|
1015
|
+
process.exit(0);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
const blockedProducer = waveAgents.find((agent) => outcomes[agent]?.outcome === 'blocked');
|
|
1019
|
+
if (blockedProducer) {
|
|
1020
|
+
if (isGraphMode()) {
|
|
1021
|
+
const blockedStepIndex = waveIndexes.find((i) => getStepAgents(steps[i]).includes(blockedProducer));
|
|
1022
|
+
status.blockedSteps = [...new Set([...(status.blockedSteps || []), blockedStepIndex])];
|
|
1023
|
+
writeStatus({ state: 'blocked', phase: 'blocked', currentAgent: blockedProducer, parallelCompleted: [], parallelOutcomes: {}, waveSteps: [], waveId: null });
|
|
1024
|
+
if (!dispatchReadyWave(`Step ${blockedStepIndex} (${blockedProducer}) is blocked; proceeding with independent ready steps.`)) out(blockedNotice(blockedStepIndex, blockedProducer));
|
|
1025
|
+
process.exit(0);
|
|
1026
|
+
}
|
|
1027
|
+
writeStatus({ parallelCompleted: [], parallelOutcomes: {}, state: 'blocked', phase: 'blocked', currentAgent: blockedProducer });
|
|
1028
|
+
process.stdout.write('{}');
|
|
1029
|
+
process.exit(0);
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
const retryReviewer = waveAgents.find((agent) => outcomes[agent]?.outcome === 'changes_requested');
|
|
1033
|
+
if (retryReviewer === 'mockup-reviewer') {
|
|
1034
|
+
beginHumanGate();
|
|
1035
|
+
writeStatus({
|
|
1036
|
+
awaitingHumanGate: true,
|
|
1037
|
+
state: 'awaiting_approval',
|
|
1038
|
+
currentAgent: 'mockup-reviewer',
|
|
1039
|
+
parallelCompleted: [],
|
|
1040
|
+
parallelOutcomes: {},
|
|
1041
|
+
waveSteps: [],
|
|
1042
|
+
waveId: null,
|
|
1043
|
+
});
|
|
1044
|
+
out(`Mockup review FAIL for slug "${slug}". Read mockup-review.md. Resume only via /task-continue. Do not retry feature-developer.`);
|
|
1045
|
+
process.exit(0);
|
|
1046
|
+
}
|
|
1047
|
+
if (retryReviewer) {
|
|
1048
|
+
if (isGraphMode()) {
|
|
1049
|
+
const reviewerStepIndex = waveIndexes.find((i) => getStepAgents(steps[i]).includes(retryReviewer));
|
|
1050
|
+
const producerIndex = resolveProducerStepIndex('feature-developer', reviewerStepIndex);
|
|
1051
|
+
if (producerIndex < 0) {
|
|
1052
|
+
beginHumanGate();
|
|
1053
|
+
writeStatus({ awaitingHumanGate: true, state: 'awaiting_approval', currentAgent: retryReviewer, parallelCompleted: [], parallelOutcomes: {}, waveSteps: [], waveId: null });
|
|
1054
|
+
out(`${retryReviewer} requested changes for slug "${slug}" but no graph ancestor authors fixes. Read the review artifact. Resume only via /task-continue.`);
|
|
1055
|
+
process.exit(0);
|
|
1056
|
+
}
|
|
1057
|
+
const graphPredecessor = outcomes[retryReviewer]
|
|
1058
|
+
? { attemptId: outcomes[retryReviewer].attemptId, confidence: outcomes[retryReviewer].confidence }
|
|
1059
|
+
: finishedAttempt;
|
|
1060
|
+
appendMetric({ type: 'retry_scheduled', at: now, attemptId: graphPredecessor?.attemptId || status.lastCompletedAttempt?.attemptId || null, nextAgent: 'feature-developer', retryAfterFix: retryReviewer, source: 'hook', attributionConfidence: graphPredecessor ? graphPredecessor.confidence : 'unknown' });
|
|
1061
|
+
invalidateFrom(producerIndex, reviewerStepIndex);
|
|
1062
|
+
const siblingOutcomes = { ...(status.parallelOutcomes || {}) };
|
|
1063
|
+
delete siblingOutcomes[retryReviewer];
|
|
1064
|
+
status.parallelOutcomes = siblingOutcomes;
|
|
1065
|
+
writeStatus({ state: 'in_progress', phase: 'executing', waveSteps: [], waveId: null, retryAfterFix: null, retryAfterFixStepIndex: null });
|
|
1066
|
+
if (!dispatchReadyWave(`Step ${reviewerStepIndex} (${retryReviewer}) requested changes; re-dispatching unsatisfied steps.`)) out(noProgressNotice());
|
|
1067
|
+
process.exit(0);
|
|
1068
|
+
}
|
|
1069
|
+
const retryAfterFixStepIndex = idx;
|
|
1070
|
+
const predecessor = outcomes[retryReviewer]
|
|
1071
|
+
? {
|
|
1072
|
+
attemptId: outcomes[retryReviewer].attemptId,
|
|
1073
|
+
confidence: outcomes[retryReviewer].confidence,
|
|
1074
|
+
}
|
|
1075
|
+
: finishedAttempt;
|
|
1076
|
+
const developerIndex = scheduleRetry('feature-developer', retryReviewer, predecessor);
|
|
1077
|
+
if (developerIndex < 0) {
|
|
1078
|
+
beginHumanGate();
|
|
1079
|
+
writeStatus({
|
|
1080
|
+
awaitingHumanGate: true,
|
|
1081
|
+
state: 'awaiting_approval',
|
|
1082
|
+
currentAgent: retryReviewer,
|
|
1083
|
+
parallelCompleted: [],
|
|
1084
|
+
parallelOutcomes: {},
|
|
1085
|
+
});
|
|
1086
|
+
out(`${retryReviewer} requested changes for slug "${slug}" but this pipeline has no feature-developer step. Read the review artifact. Resume only via /task-continue.`);
|
|
1087
|
+
process.exit(0);
|
|
1088
|
+
}
|
|
1089
|
+
writeStatus({
|
|
1090
|
+
pipelineIndex: developerIndex,
|
|
1091
|
+
currentAgent: 'feature-developer',
|
|
1092
|
+
state: 'in_progress',
|
|
1093
|
+
phase: 'executing',
|
|
1094
|
+
retryAfterFix: retryReviewer,
|
|
1095
|
+
retryAfterFixStepIndex,
|
|
1096
|
+
parallelCompleted: [],
|
|
1097
|
+
parallelOutcomes: {},
|
|
1098
|
+
});
|
|
1099
|
+
out(handoffForAgent('feature-developer', steps[developerIndex]?.scope, steps[developerIndex]) + ` After fixes, re-run ${retryReviewer}.`);
|
|
1100
|
+
process.exit(0);
|
|
1101
|
+
}
|
|
1102
|
+
|
|
1103
|
+
if (isGraphMode()) {
|
|
1104
|
+
const validationProducer = waveAgents.find((agent) => outcomes[agent]?.outcome === 'validation_failed');
|
|
1105
|
+
if (validationProducer) {
|
|
1106
|
+
const verifierStepIndex = waveIndexes.find((i) => getStepAgents(steps[i]).includes(validationProducer));
|
|
1107
|
+
const producerIndex = resolveProducerStepIndex('feature-developer', verifierStepIndex);
|
|
1108
|
+
if (producerIndex >= 0) {
|
|
1109
|
+
appendMetric({ type: 'retry_scheduled', at: now, attemptId: outcomes[validationProducer]?.attemptId || null, nextAgent: 'feature-developer', retryAfterFix: validationProducer, source: 'hook', attributionConfidence: 'fallback' });
|
|
1110
|
+
invalidateFrom(producerIndex, verifierStepIndex);
|
|
1111
|
+
writeStatus({ state: 'in_progress', phase: 'executing', parallelCompleted: [], parallelOutcomes: {}, waveSteps: [], waveId: null });
|
|
1112
|
+
if (dispatchReadyWave(`Step ${verifierStepIndex} (${validationProducer}) failed validation; re-dispatching unsatisfied steps.`)) process.exit(0);
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
const gatedStep = waveIndexes.find((i) => hasGateAfterStep(steps[i], pipeline.humanGates));
|
|
1116
|
+
if (gatedStep !== undefined) {
|
|
1117
|
+
beginHumanGate();
|
|
1118
|
+
writeStatus({ awaitingHumanGate: true, state: 'awaiting_approval', currentAgent: completedAgent, pipelineIndex: gatedStep, parallelCompleted: [], parallelOutcomes: {}, waveSteps: [], waveId: null });
|
|
1119
|
+
process.stdout.write('{}');
|
|
1120
|
+
process.exit(0);
|
|
1121
|
+
}
|
|
1122
|
+
writeStatus({ parallelCompleted: [], parallelOutcomes: {}, waveSteps: [], waveId: null, state: 'completed' });
|
|
1123
|
+
if (dispatchReadyWave()) process.exit(0);
|
|
1124
|
+
if (Object.keys(status.activeAttempts || {}).length > 0) {
|
|
1125
|
+
process.stdout.write('{}');
|
|
1126
|
+
process.exit(0);
|
|
1127
|
+
}
|
|
1128
|
+
if (pendingStepIndexes().length === 0) {
|
|
1129
|
+
completeTaskMetrics();
|
|
1130
|
+
writeStatus({ pipelineIndex: steps.length, phase: 'done', state: 'completed', currentAgent: null, awaitingHumanGate: false });
|
|
1131
|
+
out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);
|
|
1132
|
+
process.exit(0);
|
|
1133
|
+
}
|
|
1134
|
+
out(noProgressNotice());
|
|
1135
|
+
process.exit(0);
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
writeStatus({ parallelCompleted: [], parallelOutcomes: {}, state: 'completed' });
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
if (status.state === 'blocked') {
|
|
1142
|
+
if (isGraphMode()) {
|
|
1143
|
+
status.blockedSteps = [...new Set([...(status.blockedSteps || []), idx])];
|
|
1144
|
+
writeStatus({ state: 'blocked', phase: 'blocked', currentAgent: completedAgent, waveSteps: [], waveId: null, parallelCompleted: [], parallelOutcomes: {} });
|
|
1145
|
+
if (!dispatchReadyWave(`Step ${idx} (${completedAgent}) is blocked; proceeding with independent ready steps.`)) out(blockedNotice(idx, completedAgent));
|
|
1146
|
+
process.exit(0);
|
|
1147
|
+
}
|
|
1148
|
+
writeStatus({ state: 'blocked', phase: 'blocked', currentAgent: completedAgent });
|
|
1149
|
+
process.stdout.write('{}');
|
|
1150
|
+
process.exit(0);
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
if (status.state === 'changes_requested' && (completedAgent === 'mockup-reviewer' || status.currentAgent === 'mockup-reviewer')) {
|
|
1154
|
+
beginHumanGate();
|
|
1155
|
+
writeStatus({
|
|
1156
|
+
awaitingHumanGate: true,
|
|
1157
|
+
state: 'awaiting_approval',
|
|
1158
|
+
currentAgent: 'mockup-reviewer',
|
|
1159
|
+
});
|
|
1160
|
+
out(`Mockup review FAIL for slug "${slug}". Read mockup-review.md. Resume only via /task-continue. Do not retry feature-developer.`);
|
|
1161
|
+
process.exit(0);
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
if (status.state === 'changes_requested') {
|
|
1165
|
+
const reviewer = status.currentAgent || finishedAttempt?.entry?.agent;
|
|
1166
|
+
if (!reviewer) {
|
|
1167
|
+
process.stdout.write('{}');
|
|
1168
|
+
process.exit(0);
|
|
1169
|
+
}
|
|
1170
|
+
const retryAfterFixStepIndex = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
|
|
1171
|
+
const developerIndex = scheduleRetry('feature-developer', reviewer, finishedAttempt);
|
|
1172
|
+
if (developerIndex < 0) {
|
|
1173
|
+
beginHumanGate();
|
|
1174
|
+
writeStatus({ awaitingHumanGate: true, state: 'awaiting_approval', currentAgent: reviewer });
|
|
1175
|
+
out(`${reviewer} requested changes for slug "${slug}" but this pipeline has no feature-developer step. Read the review artifact. Resume only via /task-continue.`);
|
|
1176
|
+
process.exit(0);
|
|
1177
|
+
}
|
|
1178
|
+
writeStatus({
|
|
1179
|
+
pipelineIndex: developerIndex,
|
|
1180
|
+
currentAgent: 'feature-developer',
|
|
1181
|
+
state: 'in_progress',
|
|
1182
|
+
phase: 'executing',
|
|
1183
|
+
retryAfterFix: reviewer,
|
|
1184
|
+
retryAfterFixStepIndex,
|
|
1185
|
+
});
|
|
1186
|
+
out(handoffForAgent('feature-developer', steps[developerIndex]?.scope, steps[developerIndex]) + ` After fixes, re-run ${reviewer}.`);
|
|
1187
|
+
process.exit(0);
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
if (status.state === 'validation_failed' && status.currentAgent === 'build-verifier') {
|
|
1191
|
+
const retryAfterFixStepIndex = typeof status.pipelineIndex === 'number' ? status.pipelineIndex : 0;
|
|
1192
|
+
const developerIndex = scheduleRetry('feature-developer', 'build-verifier', finishedAttempt);
|
|
1193
|
+
if (developerIndex < 0) {
|
|
1194
|
+
beginHumanGate();
|
|
1195
|
+
writeStatus({ awaitingHumanGate: true, state: 'awaiting_approval', currentAgent: 'build-verifier' });
|
|
1196
|
+
out(`Validation failed for slug "${slug}" but this pipeline has no feature-developer step. Read validation-report.md. Resume only via /task-continue.`);
|
|
1197
|
+
process.exit(0);
|
|
1198
|
+
}
|
|
1199
|
+
writeStatus({
|
|
1200
|
+
pipelineIndex: developerIndex,
|
|
1201
|
+
currentAgent: 'feature-developer',
|
|
1202
|
+
state: 'in_progress',
|
|
1203
|
+
phase: 'executing',
|
|
1204
|
+
retryAfterFix: 'build-verifier',
|
|
1205
|
+
retryAfterFixStepIndex,
|
|
1206
|
+
});
|
|
1207
|
+
out(handoffForAgent('feature-developer', steps[developerIndex]?.scope, steps[developerIndex]) + ' Read validation-report.md. After fixes, re-run build-verifier.');
|
|
1208
|
+
process.exit(0);
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
if (status.state === 'completed' && status.retryAfterFix) {
|
|
1212
|
+
const retry = status.retryAfterFix;
|
|
1213
|
+
const retryIndex = scheduleRetry(retry, null, finishedAttempt, status.retryAfterFixStepIndex);
|
|
1214
|
+
if (retryIndex >= 0) {
|
|
1215
|
+
writeStatus({ pipelineIndex: retryIndex, currentAgent: retry, state: 'in_progress', retryAfterFix: null, retryAfterFixStepIndex: null });
|
|
1216
|
+
out(handoffForAgent(retry, steps[retryIndex]?.scope, steps[retryIndex]));
|
|
1217
|
+
process.exit(0);
|
|
1218
|
+
}
|
|
1219
|
+
// The reviewer to re-run is no longer in steps[]; drop the marker and advance normally.
|
|
1220
|
+
writeStatus({ retryAfterFix: null, retryAfterFixStepIndex: null });
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
if (!currentStep) {
|
|
1224
|
+
writeStatus({ phase: 'done', state: 'completed', currentAgent: null });
|
|
1225
|
+
out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);
|
|
1226
|
+
process.exit(0);
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
if (hasGateAfterStep(currentStep, pipeline.humanGates)) {
|
|
1230
|
+
beginHumanGate();
|
|
1231
|
+
writeStatus({
|
|
1232
|
+
awaitingHumanGate: true,
|
|
1233
|
+
state: 'awaiting_approval',
|
|
1234
|
+
currentAgent: completedAgent,
|
|
1235
|
+
});
|
|
1236
|
+
process.stdout.write('{}');
|
|
1237
|
+
process.exit(0);
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
if (isGraphMode()) {
|
|
1241
|
+
if (Object.keys(status.activeAttempts || {}).length > 0) {
|
|
1242
|
+
process.stdout.write('{}');
|
|
1243
|
+
process.exit(0);
|
|
1244
|
+
}
|
|
1245
|
+
if (dispatchReadyWave()) process.exit(0);
|
|
1246
|
+
if (pendingStepIndexes().length === 0) {
|
|
1247
|
+
completeTaskMetrics();
|
|
1248
|
+
writeStatus({ pipelineIndex: steps.length, phase: 'done', state: 'completed', currentAgent: null, awaitingHumanGate: false });
|
|
1249
|
+
out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);
|
|
1250
|
+
process.exit(0);
|
|
1251
|
+
}
|
|
1252
|
+
out(noProgressNotice());
|
|
1253
|
+
process.exit(0);
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
const next = findNextExecutableStep(steps, idx + 1, taskDir);
|
|
1257
|
+
if (!next) {
|
|
1258
|
+
completeTaskMetrics();
|
|
1259
|
+
writeStatus({
|
|
1260
|
+
pipelineIndex: steps.length,
|
|
1261
|
+
phase: 'done',
|
|
1262
|
+
state: 'completed',
|
|
1263
|
+
currentAgent: null,
|
|
1264
|
+
awaitingHumanGate: false,
|
|
1265
|
+
});
|
|
1266
|
+
out(`Pipeline complete for "${slug}". Run /technical-retro ${slug}.`);
|
|
1267
|
+
process.exit(0);
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
const { step: nextStep, index: nextIdx } = next;
|
|
1271
|
+
const nextAgents = getStepAgents(nextStep);
|
|
1272
|
+
|
|
1273
|
+
activateAttempts(nextStep, nextIdx);
|
|
1274
|
+
writeStatus({
|
|
1275
|
+
pipelineIndex: nextIdx,
|
|
1276
|
+
currentAgent: nextAgents[0],
|
|
1277
|
+
phase: 'executing',
|
|
1278
|
+
state: 'in_progress',
|
|
1279
|
+
awaitingHumanGate: false,
|
|
1280
|
+
parallelCompleted: [],
|
|
1281
|
+
});
|
|
1282
|
+
|
|
1283
|
+
if (nextStep.parallel && nextAgents.length > 1) {
|
|
1284
|
+
out(handoffForParallelStep(nextStep));
|
|
1285
|
+
} else {
|
|
1286
|
+
out(handoffForAgent(nextAgents[0], nextStep.scope, nextStep));
|
|
1287
|
+
}
|
|
1288
|
+
NODE
|