@koreanhole/kandev 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +367 -2
  2. package/bin/codex-acp.js +16 -0
  3. package/bin/kandev-auto-sync.mjs +101 -0
  4. package/bin/kandev-config.js +53 -0
  5. package/bin/kandev.js +35 -0
  6. package/config/config.yaml +6 -0
  7. package/config/docker/projects/opencodex-cli.json +79 -0
  8. package/config/docker/projects/samsung-bus-tracker.json +91 -0
  9. package/config/gateways.json +14 -0
  10. package/config/pipeline.json +150 -0
  11. package/config/workflows/sdlc.yaml +1019 -0
  12. package/docker/Dockerfile +68 -0
  13. package/docker/Dockerfile.opencodex-cli +44 -0
  14. package/docker/Dockerfile.samsung-bus-tracker +75 -0
  15. package/package.json +61 -4
  16. package/scripts/agent-tools-docker.mjs +223 -0
  17. package/scripts/baseline.mjs +20 -0
  18. package/scripts/codex-medium +2 -0
  19. package/scripts/codex-stage +22 -0
  20. package/scripts/gate.mjs +909 -0
  21. package/scripts/gateways/docker.mjs +64 -0
  22. package/scripts/gateways/speckit.mjs +78 -0
  23. package/scripts/install-prerequisites.mjs +48 -0
  24. package/scripts/lib/artifacts.mjs +990 -0
  25. package/scripts/lib/bugfix.mjs +325 -0
  26. package/scripts/lib/checksum.mjs +166 -0
  27. package/scripts/lib/docker-workspace.mjs +1209 -0
  28. package/scripts/lib/gateways.mjs +79 -0
  29. package/scripts/lib/kandev.mjs +273 -0
  30. package/scripts/lib/mcp.mjs +111 -0
  31. package/scripts/lib/pipeline.mjs +548 -0
  32. package/scripts/lib/planning-replan.mjs +103 -0
  33. package/scripts/lib/resume.mjs +207 -0
  34. package/scripts/lib/review-history.mjs +260 -0
  35. package/scripts/lib/stage-boundary.mjs +146 -0
  36. package/scripts/lib/stage-model.mjs +23 -0
  37. package/scripts/lib/task-worktree.mjs +40 -0
  38. package/scripts/measure-tokens.mjs +121 -0
  39. package/scripts/planning-tools.mjs +166 -0
  40. package/scripts/replan-planning.mjs +82 -0
  41. package/scripts/review-digest.mjs +240 -0
  42. package/scripts/run-android-e2e.mjs +116 -0
  43. package/scripts/run-code-review.mjs +281 -0
  44. package/scripts/run-detached.mjs +163 -0
  45. package/scripts/run-doc-review.mjs +155 -0
  46. package/scripts/run-gateways.mjs +138 -0
  47. package/scripts/sync.mjs +588 -0
  48. package/scripts/verify-change.mjs +252 -0
  49. package/scripts/verify-node.mjs +288 -0
  50. package/scripts/verify.mjs +442 -0
  51. package/scripts/wait-status.mjs +88 -0
@@ -0,0 +1,909 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * External completion gate. Kandev never advances a stage by itself: this daemon
4
+ * watches tasks whose agent turn ended, validates the stage artifact, and only then
5
+ * moves the task to the next step. Any missing or invalid artifact keeps the task
6
+ * in place (fail-fast) and is recorded in .cache/gate-log.jsonl.
7
+ */
8
+ import { spawnSync } from "node:child_process";
9
+ import fs from "node:fs";
10
+ import os from "node:os";
11
+ import path from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ import { connect } from "./lib/mcp.mjs";
14
+ import {
15
+ getTaskConversation,
16
+ listSteps,
17
+ listTaskSessions,
18
+ listTasks,
19
+ listToolNames,
20
+ listWorkspaces,
21
+ listWorkflows,
22
+ messageTask,
23
+ moveTask,
24
+ spawnSession,
25
+ updateTaskState,
26
+ } from "./lib/kandev.mjs";
27
+ import { loadEnv, loadPipeline } from "./lib/pipeline.mjs";
28
+ import {
29
+ buildResumePrompt,
30
+ decideResume,
31
+ latestMessageTime,
32
+ resumePolicy,
33
+ resumeStats,
34
+ stageNameOf,
35
+ } from "./lib/resume.mjs";
36
+ import { gateCodeHash } from "./lib/checksum.mjs";
37
+ import { PLANNING_STAGE, STAGE_ARTIFACTS, readStageArtifact, validateArtifact } from "./lib/artifacts.mjs";
38
+ import { pinProblems, pinsFor, readJson } from "./lib/bugfix.mjs";
39
+ import { enabledGatewayIds } from "./lib/gateways.mjs";
40
+ import { clearReplanRequest, readReplanRequest } from "./lib/planning-replan.mjs";
41
+ import { repoDirFor, taskDirs } from "./lib/task-worktree.mjs";
42
+ import {
43
+ boundaryViolations,
44
+ diffSnapshots,
45
+ gitStatusChanges,
46
+ readBoundary,
47
+ snapshotWorktree,
48
+ writeBoundary,
49
+ } from "./lib/stage-boundary.mjs";
50
+
51
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
52
+ const CACHE = path.join(ROOT, ".cache");
53
+ const HEARTBEAT = path.join(CACHE, "gate-heartbeat.json");
54
+ const LOG = path.join(CACHE, "gate-log.jsonl");
55
+ const CODE_HASH = gateCodeHash(ROOT);
56
+ const SETTLED = new Set(["REVIEW"]);
57
+ const REWORK_STAGE = 2;
58
+ const REWORK_ARTIFACTS = new Set([3, 4]);
59
+
60
+ function reworkAttempts(logPath, taskId) {
61
+ if (!fs.existsSync(logPath)) return 0;
62
+ return fs.readFileSync(logPath, "utf8").trim().split("\n").reduce((count, line) => {
63
+ try {
64
+ const entry = JSON.parse(line);
65
+ return entry.task === taskId && entry.decision === "rework" ? count + 1 : count;
66
+ } catch {
67
+ return count;
68
+ }
69
+ }, 0);
70
+ }
71
+
72
+ /** A valid FAIL artifact is a rework signal only when it belongs to this run. */
73
+ function failureData(repoDir, stageIndex, spec, boundary, problems = []) {
74
+ if (!REWORK_ARTIFACTS.has(stageIndex)) return null;
75
+ if (validateArtifact(PLANNING_STAGE, spec).length) return null;
76
+ if (problems.some((problem) => /^(spec\.json|spec-review\.json|bugfix):/.test(problem))) return null;
77
+ const file = stageIndex === 3 ? "review.json" : "e2e.json";
78
+ const data = readJson(path.join(repoDir, ".agentic", file));
79
+ if (!data || data.verdict !== "FAIL" || data.task !== spec?.task) return null;
80
+ if (stageIndex === 3 && data.stage !== "review") return null;
81
+ if (stageIndex === 4 && (data.stage !== "e2e" || data.platform !== spec?.platform)) return null;
82
+ const at = Date.parse(data.timestamp);
83
+ const since = Date.parse(boundary?.at || "");
84
+ if (!Number.isFinite(at) || (Number.isFinite(since) && at < since)) return null;
85
+ return data;
86
+ }
87
+
88
+ /** Keep the prior artifact for audit, then remove it so a failed rework cannot advance. */
89
+ function archiveArtifact(repoDir, name, attempt) {
90
+ const file = path.join(repoDir, ".agentic", name);
91
+ if (!fs.existsSync(file)) return;
92
+ const dir = path.join(repoDir, ".agentic", "rework");
93
+ fs.mkdirSync(dir, { recursive: true });
94
+ fs.copyFileSync(file, path.join(dir, `${name.replace(/\.json$/, "")}-attempt-${attempt}.json`));
95
+ fs.unlinkSync(file);
96
+ }
97
+
98
+ function appendLog(entry, logPath = LOG) {
99
+ fs.mkdirSync(path.dirname(logPath), { recursive: true });
100
+ fs.appendFileSync(logPath, `${JSON.stringify({ at: new Date().toISOString(), ...entry })}\n`);
101
+ }
102
+
103
+ function latestLogEntry(logPath, taskId) {
104
+ if (!fs.existsSync(logPath)) return null;
105
+ const lines = fs.readFileSync(logPath, "utf8").trim().split("\n");
106
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
107
+ try {
108
+ const entry = JSON.parse(lines[i]);
109
+ if (entry.task === taskId && entry.at) return entry;
110
+ } catch {
111
+ // Ignore a partial line and keep looking for the previous task entry.
112
+ }
113
+ }
114
+ return null;
115
+ }
116
+
117
+ function readLogEntries(logPath) {
118
+ if (!fs.existsSync(logPath)) return [];
119
+ return fs.readFileSync(logPath, "utf8").trim().split("\n").flatMap((line) => {
120
+ try {
121
+ return [JSON.parse(line)];
122
+ } catch {
123
+ return [];
124
+ }
125
+ });
126
+ }
127
+
128
+ async function latestActivityAt(task, impl, mcp) {
129
+ const fallback = Date.parse(task.updated_at || task.updatedAt || task.created_at || "");
130
+ if (typeof impl.getTaskConversation !== "function") return fallback;
131
+ try {
132
+ const messages = await impl.getTaskConversation(mcp, { taskId: task.id, limit: 1, sort: "desc" });
133
+ const latest = latestMessageTime(messages);
134
+ if (!Number.isFinite(latest)) return fallback;
135
+ return Number.isFinite(fallback) ? Math.max(fallback, latest) : latest;
136
+ } catch {
137
+ return fallback;
138
+ }
139
+ }
140
+
141
+ const DETACHED_STATUS_FILES = [
142
+ "doc-review.status.json",
143
+ "code-review.status.json",
144
+ "android-e2e.status.json",
145
+ ];
146
+
147
+ function isPidAlive(pid, data = null) {
148
+ if (!Number.isInteger(pid) || pid <= 0) return false;
149
+ if (data?.inContainer && data?.containerName) {
150
+ const res = spawnSync("docker", ["exec", data.containerName, "kill", "-0", String(pid)], {
151
+ encoding: "utf8",
152
+ timeout: 5000,
153
+ });
154
+ return res.status === 0;
155
+ }
156
+ try {
157
+ process.kill(pid, 0);
158
+ return true;
159
+ } catch {
160
+ return false;
161
+ }
162
+ }
163
+
164
+ function hasRunningDetachedJob(repoDir) {
165
+ const agentic = path.join(repoDir, ".agentic");
166
+ for (const name of DETACHED_STATUS_FILES) {
167
+ const data = readJson(path.join(agentic, name));
168
+ if (data?.status === "running" && isPidAlive(data.pid, data)) {
169
+ return name;
170
+ }
171
+ }
172
+ return null;
173
+ }
174
+
175
+ async function evaluateResume({
176
+ task,
177
+ index,
178
+ stage,
179
+ artifactFile,
180
+ artifactMissing,
181
+ artifactOk,
182
+ problems,
183
+ repoDir,
184
+ cacheDir,
185
+ logPath,
186
+ policy,
187
+ impl,
188
+ mcp,
189
+ now,
190
+ live,
191
+ currentStep,
192
+ approvalStep,
193
+ }) {
194
+ if (!policy.enabled) return { action: "none", reason: "resume disabled" };
195
+ if (!["REVIEW", "IN_PROGRESS"].includes(task.state)) {
196
+ return { action: "none", reason: `task state ${task.state}` };
197
+ }
198
+ if (index === PLANNING_STAGE) {
199
+ if (fs.existsSync(path.join(repoDir, ".agentic", "planning-blocked.json"))) {
200
+ return { action: "none", reason: "planning is blocked" };
201
+ }
202
+ if (fs.existsSync(path.join(repoDir, ".agentic", "replan.json"))) {
203
+ return { action: "none", reason: "planning replan is pending" };
204
+ }
205
+ }
206
+ const runningJob = hasRunningDetachedJob(repoDir);
207
+ if (runningJob) {
208
+ return { action: "wait", reason: `detached runner ${runningJob} is still running` };
209
+ }
210
+ if (typeof impl.listTaskSessions !== "function") {
211
+ return { action: "none", reason: "session lookup unavailable" };
212
+ }
213
+
214
+ const boundary = index > 0 ? readBoundary(cacheDir, task.id) : null;
215
+ const cycleAt = boundary && boundary.stage === index - 1 ? boundary.at : task.created_at;
216
+ const stats = resumeStats(readLogEntries(logPath), { taskId: task.id, stageIndex: index, since: cycleAt });
217
+ if (Number.isFinite(stats.lastAttemptAt) && now - stats.lastAttemptAt < policy.cooldown_ms) {
218
+ return { action: "none", reason: "resume cooldown", stats };
219
+ }
220
+
221
+ let sessions;
222
+ try {
223
+ sessions = await impl.listTaskSessions(mcp, { taskId: task.id });
224
+ } catch (err) {
225
+ return { action: "blocked", reason: `session lookup failed: ${err.message}` };
226
+ }
227
+ const lastActivityAt = task.state === "IN_PROGRESS"
228
+ ? await latestActivityAt(task, impl, mcp)
229
+ : now;
230
+ const decision = decideResume({
231
+ task,
232
+ stage,
233
+ artifactFile,
234
+ artifactMissing,
235
+ artifactOk,
236
+ sessions,
237
+ lastActivityAt,
238
+ now,
239
+ policy,
240
+ stats,
241
+ });
242
+ if (decision.action === "none") return { ...decision, stats };
243
+ if (decision.action === "exhausted") {
244
+ return { action: "exhausted", reason: decision.reason, attempts: stats.attempts, stats };
245
+ }
246
+ if (decision.action === "wait") return { ...decision, stats };
247
+
248
+ let useReenter = false;
249
+ if (typeof impl.listToolNames === "function") {
250
+ let tools;
251
+ try {
252
+ tools = await impl.listToolNames(mcp);
253
+ } catch (err) {
254
+ return { action: "none", reason: `resume tool discovery failed: ${err.message}`, stats };
255
+ }
256
+ const tool = decision.action === "spawn" ? "spawn_session_kandev" : "message_task_kandev";
257
+ if (!tools.includes(tool)) {
258
+ if (
259
+ decision.kind !== "stalled"
260
+ && tools.includes("move_task_kandev")
261
+ && typeof impl.moveTask === "function"
262
+ && live?.id
263
+ && currentStep?.id
264
+ && approvalStep?.id
265
+ && currentStep.id !== approvalStep.id
266
+ ) {
267
+ useReenter = true;
268
+ } else {
269
+ return { action: "none", reason: `${tool} unavailable in this Kandev build`, stats };
270
+ }
271
+ }
272
+ }
273
+
274
+ const stageName = stageNameOf(stage);
275
+ const prompt = buildResumePrompt({
276
+ stageName,
277
+ artifactFile,
278
+ artifactOk,
279
+ problems,
280
+ kind: decision.kind,
281
+ attempt: decision.attempt,
282
+ maxAttempts: policy.max_attempts,
283
+ });
284
+ let via = decision.action === "spawn" ? "spawn" : "message";
285
+ let result;
286
+ if (useReenter) {
287
+ via = "reenter";
288
+ try {
289
+ await impl.moveTask(mcp, {
290
+ taskId: task.id,
291
+ workflowId: live.id,
292
+ stepId: approvalStep.id,
293
+ });
294
+ if (policy?.reenter_settle_ms > 0) {
295
+ await new Promise((resolve) => setTimeout(resolve, policy.reenter_settle_ms));
296
+ }
297
+ result = await impl.moveTask(mcp, {
298
+ taskId: task.id,
299
+ workflowId: live.id,
300
+ stepId: currentStep.id,
301
+ entryOptions: { instructions: prompt },
302
+ });
303
+ if (typeof impl.updateTaskState === "function") {
304
+ await impl.updateTaskState(mcp, { taskId: task.id, state: "IN_PROGRESS" });
305
+ }
306
+ } catch (err) {
307
+ return { action: "blocked", reason: `resume reenter failed: ${err.message}` };
308
+ }
309
+ } else {
310
+ try {
311
+ if (via === "spawn") {
312
+ result = await impl.spawnSession(mcp, {
313
+ taskId: task.id,
314
+ prompt,
315
+ name: `resume-${index}-${decision.attempt}`,
316
+ });
317
+ } else {
318
+ result = await impl.messageTask(mcp, {
319
+ taskId: task.id,
320
+ sessionId: decision.sessionId || undefined,
321
+ prompt,
322
+ });
323
+ }
324
+ } catch (err) {
325
+ if (via === "message" && /terminal|no .*session|failed|cancelled/i.test(String(err.message))) {
326
+ try {
327
+ via = "spawn";
328
+ result = await impl.spawnSession(mcp, {
329
+ taskId: task.id,
330
+ prompt,
331
+ name: `resume-${index}-${decision.attempt}`,
332
+ });
333
+ } catch (spawnErr) {
334
+ return { action: "blocked", reason: `resume message failed: ${err.message}; spawn failed: ${spawnErr.message}` };
335
+ }
336
+ } else {
337
+ return { action: "blocked", reason: `resume message failed: ${err.message}` };
338
+ }
339
+ }
340
+ }
341
+ const resultSession = result && typeof result === "object"
342
+ ? result.session_id || result.sessionId
343
+ : undefined;
344
+ return {
345
+ action: "resumed",
346
+ task: task.id,
347
+ stage: index,
348
+ artifact: artifactFile,
349
+ decision: "resumed",
350
+ attempt: decision.attempt,
351
+ max_attempts: policy.max_attempts,
352
+ kind: decision.kind,
353
+ via,
354
+ session_id: resultSession || decision.sessionId || undefined,
355
+ reason: decision.reason,
356
+ result: typeof result === "string" ? result : undefined,
357
+ };
358
+ }
359
+
360
+ function artifactMetadata(stageIndex, repoDir, data) {
361
+ const metadata = {};
362
+ if (Number.isInteger(data?.rounds)) metadata.rounds = data.rounds;
363
+ if (stageIndex === 1) {
364
+ try {
365
+ const review = JSON.parse(fs.readFileSync(path.join(repoDir, ".agentic", "spec-review.json"), "utf8"));
366
+ if (Number.isInteger(review.rounds)) metadata.rounds = review.rounds;
367
+ if (["blockers", "majors", "minors"].every((key) => Number.isInteger(review[key]))) {
368
+ metadata.findings = {
369
+ blocker: review.blockers,
370
+ major: review.majors,
371
+ minor: review.minors,
372
+ };
373
+ }
374
+ } catch {
375
+ // The artifact validator reports unreadable review metadata separately.
376
+ }
377
+ }
378
+ if (Array.isArray(data?.findings)) {
379
+ const findings = { blocker: 0, major: 0, minor: 0 };
380
+ for (const finding of data.findings) {
381
+ if (["blocker", "bug"].includes(finding?.severity)) findings.blocker += 1;
382
+ else if (finding?.severity === "major") findings.major += 1;
383
+ else findings.minor += 1;
384
+ }
385
+ metadata.findings = findings;
386
+ }
387
+ return metadata;
388
+ }
389
+
390
+ function heartbeat(detail, heartbeatPath = HEARTBEAT) {
391
+ fs.mkdirSync(path.dirname(heartbeatPath), { recursive: true });
392
+ fs.writeFileSync(
393
+ heartbeatPath,
394
+ JSON.stringify({ at: new Date().toISOString(), pid: process.pid, ...detail }, null, 2),
395
+ );
396
+ }
397
+
398
+ function checkStageBoundary(stageIndex, repoDir, taskId, cacheDir) {
399
+ if (stageIndex === 0) {
400
+ const changes = gitStatusChanges(repoDir);
401
+ if (changes === null) {
402
+ return { ok: false, problems: ["cannot read git status for Gateway stage isolation"] };
403
+ }
404
+ const violations = boundaryViolations(0, changes);
405
+ return {
406
+ ok: violations.length === 0,
407
+ problems: violations.map((file) => `stage 1 (gateway) changed out-of-scope path ${file}`),
408
+ snapshot: snapshotWorktree(repoDir),
409
+ };
410
+ }
411
+ const boundary = readBoundary(cacheDir, taskId);
412
+ if (!boundary || boundary.stage !== stageIndex - 1) {
413
+ return {
414
+ ok: false,
415
+ problems: [`stage boundary missing or stale; expected completed stage ${stageIndex - 1}`],
416
+ };
417
+ }
418
+ const current = snapshotWorktree(repoDir);
419
+ const pinned = pinProblems(repoDir, boundary.pins);
420
+ if (pinned.length) {
421
+ return {
422
+ ok: false,
423
+ problems: pinned.map((problem) => `stage ${stageIndex + 1} ${problem}`),
424
+ snapshot: current,
425
+ };
426
+ }
427
+ const changes = diffSnapshots(boundary.snapshot, current);
428
+ const violations = boundaryViolations(stageIndex, changes);
429
+ return {
430
+ ok: violations.length === 0,
431
+ problems: violations.map((file) => `stage ${stageIndex + 1} changed out-of-scope path ${file}`),
432
+ snapshot: current,
433
+ };
434
+ }
435
+
436
+ export async function runGate({ once = false, intervalMs = 5000, deps = null, cacheDir = CACHE } = {}) {
437
+ loadEnv(ROOT);
438
+ const heartbeatPath = path.join(cacheDir, "gate-heartbeat.json");
439
+ const logPath = path.join(cacheDir, "gate-log.jsonl");
440
+ const { pipeline, workflow, stages } = loadPipeline(ROOT);
441
+ const requiredGateways = enabledGatewayIds(ROOT);
442
+ const resumeOptions = resumePolicy(pipeline);
443
+ const maxRework = Number.isInteger(pipeline.rework?.max_attempts)
444
+ ? pipeline.rework.max_attempts
445
+ : 0;
446
+ const homeDir = process.env.KANDEV_HOME || path.join(os.homedir(), ".kandev");
447
+ const impl = deps || {
448
+ connect,
449
+ listWorkspaces,
450
+ listSteps,
451
+ listTasks,
452
+ listTaskSessions,
453
+ listToolNames,
454
+ getTaskConversation,
455
+ listWorkflows,
456
+ messageTask,
457
+ moveTask,
458
+ spawnSession,
459
+ updateTaskState,
460
+ };
461
+ const mcp = deps ? {} : await impl.connect();
462
+
463
+ const workspaces = await impl.listWorkspaces(mcp);
464
+ const workspace = workspaces.find(
465
+ (w) => w.name === (process.env.KANDEV_WORKSPACE || pipeline.workspace),
466
+ );
467
+ if (!workspace) throw new Error(`Workspace "${pipeline.workspace}" not found`);
468
+ const workflows = await impl.listWorkflows(mcp, workspace.id);
469
+ const live = workflows.find((w) => w.name === workflow.name);
470
+ if (!live) throw new Error(`Workflow "${workflow.name}" not found; run npm run sync first`);
471
+
472
+ const seen = new Map();
473
+ const stageByName = new Map(stages.map((stage, index) => [stage.stepDefinition.name, index]));
474
+ let lastResumeScan = 0;
475
+ const tick = async () => {
476
+ const steps = (await impl.listSteps(mcp, live.id))
477
+ .slice()
478
+ .sort((a, b) => Number(a.position) - Number(b.position));
479
+ const stepName = new Map(steps.map((step) => [step.id, step.name]));
480
+ const tasks = await impl.listTasks(mcp, live.id);
481
+ const terminalName = workflow.steps.at(-1).name;
482
+ const approvalStage = stages.find((stage) => stage.human_approval === true);
483
+ const approvalStep = approvalStage
484
+ ? steps.find((step) => step.name === approvalStage.stepDefinition.name)
485
+ : null;
486
+ const dirs = taskDirs(homeDir);
487
+ const actions = [];
488
+ const now = Date.now();
489
+ const scanResume = once || now - lastResumeScan >= resumeOptions.scan_interval_ms;
490
+ if (scanResume) lastResumeScan = now;
491
+
492
+ for (const task of tasks) {
493
+ if (task.state === "COMPLETED") continue;
494
+ try {
495
+ const name = stepName.get(task.workflow_step_id);
496
+ if (name === terminalName) continue;
497
+ const index = name === undefined ? undefined : stageByName.get(name);
498
+ if (index === undefined || index >= stages.length) {
499
+ const key = `${task.id}:unknown-step:${name ?? "?"}`;
500
+ if (!seen.has(key)) {
501
+ seen.set(key, true);
502
+ actions.push({ task: task.id, stage: null, artifact: "n/a", decision: "blocked", reason: `unknown step ${name ?? "?"}` });
503
+ }
504
+ continue;
505
+ }
506
+ if (stages[index].human_approval === true) continue;
507
+ const settled = SETTLED.has(task.state);
508
+ const resumable = task.state === "IN_PROGRESS";
509
+ if (!settled && !resumable) continue;
510
+ if (!task.created_at || Number.isNaN(Date.parse(task.created_at))) {
511
+ const key = `${task.id}:${index}:created-at`;
512
+ if (!seen.has(key)) {
513
+ seen.set(key, true);
514
+ actions.push({
515
+ task: task.id,
516
+ stage: index,
517
+ artifact: STAGE_ARTIFACTS[index].file,
518
+ decision: "blocked",
519
+ reason: "task created_at is missing or invalid; cannot reject stale artifacts",
520
+ });
521
+ }
522
+ continue;
523
+ }
524
+ const currentStep = steps.find((step) => step.id === task.workflow_step_id);
525
+ if (!currentStep || Number(currentStep.position) !== index) {
526
+ const key = `${task.id}:${index}:position:${currentStep?.position ?? "missing"}`;
527
+ if (!seen.has(key)) {
528
+ seen.set(key, true);
529
+ actions.push({
530
+ task: task.id,
531
+ stage: index,
532
+ artifact: STAGE_ARTIFACTS[index].file,
533
+ decision: "blocked",
534
+ reason: `current step ${name} is at position ${currentStep?.position ?? "?"}, expected ${index}`,
535
+ });
536
+ }
537
+ continue;
538
+ }
539
+
540
+ const taskDir = dirs.get(task.id);
541
+ const repoDir = taskDir ? repoDirFor(taskDir) : null;
542
+ if (!repoDir) {
543
+ const key = `${task.id}:${index}:worktree`;
544
+ if (!seen.has(key)) {
545
+ seen.set(key, true);
546
+ actions.push({
547
+ task: task.id,
548
+ stage: index,
549
+ artifact: STAGE_ARTIFACTS[index].file,
550
+ decision: "blocked",
551
+ reason: "worktree not found",
552
+ });
553
+ }
554
+ continue;
555
+ }
556
+
557
+ if (index === PLANNING_STAGE) {
558
+ const replan = readReplanRequest(repoDir);
559
+ if (replan) {
560
+ const gatewayStep = steps.find((step) => step.name === stages[0].stepDefinition.name);
561
+ const key = `${task.id}:${index}:replan:${replan.requestedAt}`;
562
+ if (!gatewayStep || Number(gatewayStep.position) !== 0) {
563
+ if (!seen.has(key)) {
564
+ seen.set(key, true);
565
+ actions.push({
566
+ task: task.id,
567
+ stage: index,
568
+ artifact: "replan.json",
569
+ decision: "blocked",
570
+ reason: "cannot replan: Gateway step is missing or not at position 0",
571
+ });
572
+ }
573
+ continue;
574
+ }
575
+ try {
576
+ await impl.moveTask(mcp, { taskId: task.id, workflowId: live.id, stepId: gatewayStep.id });
577
+ clearReplanRequest(repoDir);
578
+ actions.push({
579
+ task: task.id,
580
+ stage: index,
581
+ artifact: "replan.json",
582
+ decision: "replan",
583
+ from: name,
584
+ to: gatewayStep.name,
585
+ reason: replan.reason,
586
+ archivedTo: replan.archivedTo,
587
+ });
588
+ } catch (err) {
589
+ const errorKey = `${key}:${err.message}`;
590
+ if (!seen.has(errorKey)) {
591
+ seen.set(errorKey, true);
592
+ actions.push({
593
+ task: task.id,
594
+ stage: index,
595
+ artifact: "replan.json",
596
+ decision: "blocked",
597
+ reason: `cannot replan: ${err.message}`,
598
+ });
599
+ }
600
+ }
601
+ continue;
602
+ }
603
+ }
604
+
605
+ let artifact = readStageArtifact(repoDir, index, {
606
+ notBefore: task.created_at,
607
+ requiredGateways,
608
+ });
609
+ if (
610
+ index === 0 &&
611
+ !artifact.missing &&
612
+ !artifact.ok &&
613
+ artifact.problems.some((p) => p.includes("is missing from gateway.json"))
614
+ ) {
615
+ try {
616
+ fs.unlinkSync(path.join(repoDir, ".agentic", STAGE_ARTIFACTS[0].file));
617
+ } catch {}
618
+ artifact = { ...artifact, missing: true };
619
+ }
620
+ const spec = readJson(path.join(repoDir, ".agentic", "spec.json"));
621
+ const artifactFile = STAGE_ARTIFACTS[index].file;
622
+ if ((scanResume && task.state === "IN_PROGRESS") || (task.state === "REVIEW" && !artifact.ok)) {
623
+ const resume = await evaluateResume({
624
+ task,
625
+ index,
626
+ stage: stages[index],
627
+ artifactFile,
628
+ artifactMissing: artifact.missing,
629
+ artifactOk: artifact.ok,
630
+ problems: artifact.problems,
631
+ repoDir,
632
+ cacheDir,
633
+ logPath,
634
+ policy: resumeOptions,
635
+ impl,
636
+ mcp,
637
+ now,
638
+ live,
639
+ currentStep,
640
+ approvalStep,
641
+ });
642
+ if (resume.action === "resumed") {
643
+ actions.push(resume);
644
+ continue;
645
+ }
646
+ if (resume.action === "wait") continue;
647
+ if (resume.action === "blocked" || resume.action === "exhausted") {
648
+ const reason = resume.action === "exhausted"
649
+ ? `resume exhausted after ${resume.attempts} attempt(s); ${artifact.problems.join("; ") || `${artifactFile} is missing`}`
650
+ : resume.reason;
651
+ const key = `${task.id}:${index}:resume:${reason}`;
652
+ if (!seen.has(key)) {
653
+ seen.set(key, true);
654
+ actions.push({
655
+ task: task.id,
656
+ stage: index,
657
+ artifact: artifactFile,
658
+ decision: "blocked",
659
+ reason,
660
+ resume: {
661
+ attempts: resume.attempts ?? resume.stats?.attempts ?? 0,
662
+ max: resumeOptions.max_attempts,
663
+ exhausted: resume.action === "exhausted",
664
+ },
665
+ });
666
+ }
667
+ continue;
668
+ }
669
+ }
670
+ if (task.state === "IN_PROGRESS") continue;
671
+ if (maxRework > 0 && !artifact.missing && !artifact.ok && spec) {
672
+ const boundary = readBoundary(cacheDir, task.id);
673
+ const failure = failureData(repoDir, index, spec, boundary, artifact.problems);
674
+ if (failure) {
675
+ const attempts = reworkAttempts(logPath, task.id);
676
+ const target = steps.find((step) => step.name === stages[REWORK_STAGE].stepDefinition.name);
677
+ if (attempts >= maxRework) {
678
+ const key = `${task.id}:${index}:rework-limit:${attempts}`;
679
+ if (!seen.has(key)) {
680
+ seen.set(key, true);
681
+ actions.push({
682
+ task: task.id,
683
+ stage: index,
684
+ artifact: STAGE_ARTIFACTS[index].file,
685
+ decision: "blocked",
686
+ reason: `rework limit reached (${maxRework}); manual review required`,
687
+ });
688
+ }
689
+ continue;
690
+ }
691
+ if (!boundary || !target || Number(target.position) !== REWORK_STAGE) {
692
+ const key = `${task.id}:${index}:rework-target`;
693
+ if (!seen.has(key)) {
694
+ seen.set(key, true);
695
+ actions.push({
696
+ task: task.id,
697
+ stage: index,
698
+ artifact: STAGE_ARTIFACTS[index].file,
699
+ decision: "blocked",
700
+ reason: "cannot route rework: boundary or implementation step is missing",
701
+ });
702
+ }
703
+ continue;
704
+ }
705
+ try {
706
+ archiveArtifact(repoDir, "implementation.json", attempts + 1);
707
+ if (index >= 3) archiveArtifact(repoDir, "review.json", attempts + 1);
708
+ if (index === 4) archiveArtifact(repoDir, "e2e.json", attempts + 1);
709
+ } catch (err) {
710
+ const key = `${task.id}:${index}:rework-archive:${err.message}`;
711
+ if (!seen.has(key)) {
712
+ seen.set(key, true);
713
+ actions.push({
714
+ task: task.id,
715
+ stage: index,
716
+ artifact: STAGE_ARTIFACTS[index].file,
717
+ decision: "blocked",
718
+ reason: `cannot invalidate the prior stage artifact: ${err.message}`,
719
+ });
720
+ }
721
+ continue;
722
+ }
723
+ await impl.moveTask(mcp, { taskId: task.id, workflowId: live.id, stepId: target.id });
724
+ try {
725
+ writeBoundary(cacheDir, task.id, REWORK_STAGE - 1, snapshotWorktree(repoDir), boundary.pins ?? pinsFor(repoDir, spec));
726
+ } catch (err) {
727
+ appendLog({ task: task.id, stage: index, decision: "boundary-write-error", reason: err.message }, logPath);
728
+ }
729
+ actions.push({
730
+ task: task.id,
731
+ stage: index,
732
+ artifact: STAGE_ARTIFACTS[index].file,
733
+ decision: "rework",
734
+ from: name,
735
+ to: target.name,
736
+ attempt: attempts + 1,
737
+ ...artifactMetadata(index, repoDir, failure),
738
+ });
739
+ continue;
740
+ }
741
+ }
742
+ if (artifact.missing) {
743
+ let reason = artifact.problems.join("; ");
744
+ if (index === PLANNING_STAGE) {
745
+ const blocked = readJson(path.join(repoDir, ".agentic", "planning-blocked.json"));
746
+ if (blocked?.reason) reason = `planning blocked: ${blocked.reason}`;
747
+ }
748
+ const key = `${task.id}:${index}:missing:${reason}`;
749
+ if (!seen.has(key)) {
750
+ seen.set(key, true);
751
+ actions.push({
752
+ task: task.id,
753
+ stage: index,
754
+ artifact: STAGE_ARTIFACTS[index].file,
755
+ decision: "blocked",
756
+ reason,
757
+ });
758
+ }
759
+ continue;
760
+ }
761
+ if (!artifact.ok) {
762
+ const key = `${task.id}:${index}:${artifact.problems.join("|")}`;
763
+ if (!seen.has(key)) {
764
+ seen.set(key, true);
765
+ actions.push({
766
+ task: task.id,
767
+ stage: index,
768
+ artifact: STAGE_ARTIFACTS[index].file,
769
+ decision: "blocked",
770
+ reason: artifact.problems.join("; "),
771
+ });
772
+ }
773
+ continue;
774
+ }
775
+
776
+ const targetName = index + 1 < stages.length
777
+ ? stages[index + 1].stepDefinition.name
778
+ : terminalName;
779
+ const target = steps.find((step) => step.name === targetName);
780
+ if (!target || Number(target.position) !== index + 1) {
781
+ const key = `${task.id}:${index}:target:${targetName}:${target?.position ?? "missing"}`;
782
+ if (!seen.has(key)) {
783
+ seen.set(key, true);
784
+ actions.push({
785
+ task: task.id,
786
+ stage: index,
787
+ artifact: STAGE_ARTIFACTS[index].file,
788
+ decision: "blocked",
789
+ reason: `expected next step ${targetName} at position ${index + 1}`,
790
+ });
791
+ }
792
+ continue;
793
+ }
794
+ const boundary = checkStageBoundary(index, repoDir, task.id, cacheDir);
795
+ if (!boundary.ok) {
796
+ const key = `${task.id}:${index}:boundary:${boundary.problems.join("|")}`;
797
+ if (!seen.has(key)) {
798
+ seen.set(key, true);
799
+ actions.push({
800
+ task: task.id,
801
+ stage: index,
802
+ artifact: STAGE_ARTIFACTS[index].file,
803
+ decision: "blocked",
804
+ reason: boundary.problems.join("; "),
805
+ });
806
+ }
807
+ continue;
808
+ }
809
+ let pins = null;
810
+ if (index >= 1) {
811
+ try {
812
+ const previous = readBoundary(cacheDir, task.id);
813
+ pins = previous?.pins ?? pinsFor(repoDir, artifact.data);
814
+ } catch (err) {
815
+ const key = `${task.id}:${index}:pins:${err.message}`;
816
+ if (!seen.has(key)) {
817
+ seen.set(key, true);
818
+ actions.push({
819
+ task: task.id,
820
+ stage: index,
821
+ artifact: STAGE_ARTIFACTS[index].file,
822
+ decision: "blocked",
823
+ reason: `cannot pin stage contract: ${err.message}`,
824
+ });
825
+ }
826
+ continue;
827
+ }
828
+ }
829
+ await impl.moveTask(mcp, { taskId: task.id, workflowId: live.id, stepId: target.id });
830
+ try {
831
+ writeBoundary(cacheDir, task.id, index, boundary.snapshot, pins);
832
+ } catch (err) {
833
+ appendLog({ task: task.id, stage: index, decision: "boundary-write-error", reason: err.message }, logPath);
834
+ }
835
+ actions.push({
836
+ task: task.id,
837
+ stage: index,
838
+ decision: "advanced",
839
+ to: target.name,
840
+ artifact: STAGE_ARTIFACTS[index].file,
841
+ ...artifactMetadata(index, repoDir, artifact.data),
842
+ });
843
+ } catch (err) {
844
+ actions.push({ task: task.id, stage: null, artifact: "n/a", decision: "blocked", reason: `gate error: ${err.message}` });
845
+ }
846
+ }
847
+
848
+ for (const action of actions) {
849
+ if (Number.isInteger(action.stage)) {
850
+ const task = tasks.find((item) => item.id === action.task);
851
+ const since = latestLogEntry(logPath, action.task)?.at || task?.created_at;
852
+ const started = Date.parse(since);
853
+ if (Number.isFinite(started)) action.duration_ms = Math.max(0, Date.now() - started);
854
+ }
855
+ appendLog(action, logPath);
856
+ }
857
+ heartbeat({
858
+ healthy: true,
859
+ workflow: live.name,
860
+ tasks: tasks.length,
861
+ actions: actions.length,
862
+ blocked: actions.filter((action) => action.decision === "blocked").length,
863
+ resumed: actions.filter((action) => action.decision === "resumed").length,
864
+ stalled: actions.filter((action) => action.decision === "resumed" && action.kind === "stalled").length,
865
+ resume_exhausted: actions.filter((action) =>
866
+ action.decision === "blocked" && action.resume?.exhausted === true,
867
+ ).length,
868
+ code_hash: CODE_HASH,
869
+ }, heartbeatPath);
870
+ return actions;
871
+ };
872
+
873
+ const first = await tick();
874
+ if (once) return { actions: first, once: true };
875
+ // eslint-disable-next-line no-constant-condition
876
+ while (true) {
877
+ await new Promise((resolve) => setTimeout(resolve, intervalMs));
878
+ try {
879
+ await tick();
880
+ } catch (err) {
881
+ appendLog({ decision: "error", reason: err.message }, logPath);
882
+ heartbeat({ healthy: false, error: err.message, code_hash: CODE_HASH }, heartbeatPath);
883
+ }
884
+ }
885
+ }
886
+
887
+ async function main() {
888
+ const argv = process.argv.slice(2);
889
+ if (argv.includes("--help")) {
890
+ console.log("Usage: node scripts/gate.mjs [--once] [--interval <ms>] [--json]");
891
+ return;
892
+ }
893
+ const once = argv.includes("--once");
894
+ const intervalIndex = argv.indexOf("--interval");
895
+ const intervalMs = intervalIndex >= 0 ? Number(argv[intervalIndex + 1]) : 5000;
896
+ try {
897
+ const out = await runGate({ once, intervalMs });
898
+ if (argv.includes("--json")) console.log(JSON.stringify(out, null, 2));
899
+ else if (once) console.log(`gate tick: ${out.actions.length} action(s)`);
900
+ else console.log("gate running");
901
+ } catch (err) {
902
+ console.error(`FAIL gate: ${err.message}`);
903
+ process.exit(1);
904
+ }
905
+ }
906
+
907
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
908
+ main();
909
+ }