@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.
- package/README.md +367 -2
- package/bin/codex-acp.js +16 -0
- package/bin/kandev-auto-sync.mjs +101 -0
- package/bin/kandev-config.js +53 -0
- package/bin/kandev.js +35 -0
- package/config/config.yaml +6 -0
- package/config/docker/projects/opencodex-cli.json +79 -0
- package/config/docker/projects/samsung-bus-tracker.json +91 -0
- package/config/gateways.json +14 -0
- package/config/pipeline.json +150 -0
- package/config/workflows/sdlc.yaml +1019 -0
- package/docker/Dockerfile +68 -0
- package/docker/Dockerfile.opencodex-cli +44 -0
- package/docker/Dockerfile.samsung-bus-tracker +75 -0
- package/package.json +61 -4
- package/scripts/agent-tools-docker.mjs +223 -0
- package/scripts/baseline.mjs +20 -0
- package/scripts/codex-medium +2 -0
- package/scripts/codex-stage +22 -0
- package/scripts/gate.mjs +909 -0
- package/scripts/gateways/docker.mjs +64 -0
- package/scripts/gateways/speckit.mjs +78 -0
- package/scripts/install-prerequisites.mjs +48 -0
- package/scripts/lib/artifacts.mjs +990 -0
- package/scripts/lib/bugfix.mjs +325 -0
- package/scripts/lib/checksum.mjs +166 -0
- package/scripts/lib/docker-workspace.mjs +1209 -0
- package/scripts/lib/gateways.mjs +79 -0
- package/scripts/lib/kandev.mjs +273 -0
- package/scripts/lib/mcp.mjs +111 -0
- package/scripts/lib/pipeline.mjs +548 -0
- package/scripts/lib/planning-replan.mjs +103 -0
- package/scripts/lib/resume.mjs +207 -0
- package/scripts/lib/review-history.mjs +260 -0
- package/scripts/lib/stage-boundary.mjs +146 -0
- package/scripts/lib/stage-model.mjs +23 -0
- package/scripts/lib/task-worktree.mjs +40 -0
- package/scripts/measure-tokens.mjs +121 -0
- package/scripts/planning-tools.mjs +166 -0
- package/scripts/replan-planning.mjs +82 -0
- package/scripts/review-digest.mjs +240 -0
- package/scripts/run-android-e2e.mjs +116 -0
- package/scripts/run-code-review.mjs +281 -0
- package/scripts/run-detached.mjs +163 -0
- package/scripts/run-doc-review.mjs +155 -0
- package/scripts/run-gateways.mjs +138 -0
- package/scripts/sync.mjs +588 -0
- package/scripts/verify-change.mjs +252 -0
- package/scripts/verify-node.mjs +288 -0
- package/scripts/verify.mjs +442 -0
- package/scripts/wait-status.mjs +88 -0
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/** Bounded stage resume decisions for the external completion gate. */
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_RESUME = {
|
|
4
|
+
enabled: false,
|
|
5
|
+
max_attempts: 3,
|
|
6
|
+
cooldown_ms: 120_000,
|
|
7
|
+
idle_ms: 900_000,
|
|
8
|
+
stage_idle_ms: {},
|
|
9
|
+
running_nudge_max: 1,
|
|
10
|
+
scan_interval_ms: 60_000,
|
|
11
|
+
reenter_settle_ms: 0,
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export const SETTLED_SESSION_STATES = new Set(["COMPLETED", "WAITING_FOR_INPUT"]);
|
|
15
|
+
export const TERMINAL_SESSION_STATES = new Set(["FAILED", "CANCELLED"]);
|
|
16
|
+
export const ACTIVE_SESSION_STATES = new Set(["RUNNING", "STARTING"]);
|
|
17
|
+
|
|
18
|
+
export const STAGE_HINTS = {
|
|
19
|
+
"1. Agent Gateway":
|
|
20
|
+
"Run the gateway runner in one shot using sh from the stage prompt, then verify .agentic/gateway.json.",
|
|
21
|
+
"2. Planning":
|
|
22
|
+
"Continue from the existing .specify/feature.json and specs/ directory; finish the bounded review loop and write .agentic/spec.json.",
|
|
23
|
+
"3. Implementation":
|
|
24
|
+
"Continue from .agentic/spec.json; do not re-plan; run the implementation and the deterministic verifier.",
|
|
25
|
+
"4. Code Review":
|
|
26
|
+
"Run the code review wrapper from the stage prompt and write .agentic/review.json.",
|
|
27
|
+
"5. E2E":
|
|
28
|
+
"Run the E2E driver or verify-node wrapper and write .agentic/e2e.json.",
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export function resumePolicy(pipeline = {}) {
|
|
32
|
+
const raw = pipeline?.resume;
|
|
33
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
34
|
+
return { ...DEFAULT_RESUME, stage_idle_ms: {} };
|
|
35
|
+
}
|
|
36
|
+
return {
|
|
37
|
+
...DEFAULT_RESUME,
|
|
38
|
+
...raw,
|
|
39
|
+
stage_idle_ms: { ...(raw.stage_idle_ms || {}) },
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function stageNameOf(stage = {}) {
|
|
44
|
+
return stage?.stepDefinition?.name || stage?.step || stage?.name || "unknown stage";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function idleMsFor(policy, stageName) {
|
|
48
|
+
return policy?.stage_idle_ms?.[stageName] ?? policy?.idle_ms ?? DEFAULT_RESUME.idle_ms;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function normalizedSessions(sessions = []) {
|
|
52
|
+
return sessions.map((session) => ({
|
|
53
|
+
...session,
|
|
54
|
+
state: String(session?.state || "").toUpperCase(),
|
|
55
|
+
}));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function sessionIdOf(session) {
|
|
59
|
+
return session?.session_id || session?.sessionId || null;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function pickSession(sessions = []) {
|
|
63
|
+
const list = normalizedSessions(sessions);
|
|
64
|
+
const primary = list.find((session) => session.is_primary === true || session.isPrimary === true);
|
|
65
|
+
const live = list.find((session) => !TERMINAL_SESSION_STATES.has(session.state));
|
|
66
|
+
return live || primary || list[0] || null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function latestMessageTime(messages) {
|
|
70
|
+
const list = Array.isArray(messages)
|
|
71
|
+
? messages
|
|
72
|
+
: messages?.messages || messages?.items || [];
|
|
73
|
+
let latest = Number.NaN;
|
|
74
|
+
for (const message of list) {
|
|
75
|
+
const at = Date.parse(message?.updated_at || message?.updatedAt || message?.created_at || message?.createdAt || message?.at || "");
|
|
76
|
+
if (Number.isFinite(at) && (!Number.isFinite(latest) || at > latest)) latest = at;
|
|
77
|
+
}
|
|
78
|
+
return latest;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function resumeStats(entries = [], { taskId, stageIndex, since }) {
|
|
82
|
+
const sinceMs = Date.parse(since || "");
|
|
83
|
+
let attempts = 0;
|
|
84
|
+
let runningNudges = 0;
|
|
85
|
+
let lastAttemptAt = Number.NaN;
|
|
86
|
+
for (const entry of entries) {
|
|
87
|
+
if (entry?.task !== taskId || entry?.stage !== stageIndex) continue;
|
|
88
|
+
if (entry.decision !== "resumed") continue;
|
|
89
|
+
const at = Date.parse(entry.at || "");
|
|
90
|
+
if (Number.isFinite(sinceMs) && (!Number.isFinite(at) || at < sinceMs)) continue;
|
|
91
|
+
attempts += 1;
|
|
92
|
+
if (entry.kind === "stalled") runningNudges += 1;
|
|
93
|
+
if (Number.isFinite(at) && (!Number.isFinite(lastAttemptAt) || at > lastAttemptAt)) lastAttemptAt = at;
|
|
94
|
+
}
|
|
95
|
+
return { attempts, runningNudges, lastAttemptAt };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function decideResume({
|
|
99
|
+
task,
|
|
100
|
+
stage,
|
|
101
|
+
artifactFile,
|
|
102
|
+
artifactMissing,
|
|
103
|
+
artifactOk,
|
|
104
|
+
sessions = [],
|
|
105
|
+
lastActivityAt,
|
|
106
|
+
now = Date.now(),
|
|
107
|
+
policy,
|
|
108
|
+
stats = { attempts: 0, runningNudges: 0 },
|
|
109
|
+
}) {
|
|
110
|
+
if (!policy?.enabled) return { action: "none", reason: "resume disabled" };
|
|
111
|
+
if (!task || !stage) return { action: "none", reason: "task or stage missing" };
|
|
112
|
+
if (stage.human_approval === true) return { action: "none", reason: "human approval stage" };
|
|
113
|
+
|
|
114
|
+
const state = String(task.state || "").toUpperCase();
|
|
115
|
+
if (!["REVIEW", "IN_PROGRESS"].includes(state)) {
|
|
116
|
+
return { action: "none", reason: `task state ${state || "unknown"}` };
|
|
117
|
+
}
|
|
118
|
+
if (stats.attempts >= policy.max_attempts) {
|
|
119
|
+
return {
|
|
120
|
+
action: "exhausted",
|
|
121
|
+
reason: `resume attempts ${stats.attempts}/${policy.max_attempts}`,
|
|
122
|
+
attempt: stats.attempts,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const stageName = stageNameOf(stage);
|
|
127
|
+
const list = normalizedSessions(sessions);
|
|
128
|
+
const active = list.some((session) => ACTIVE_SESSION_STATES.has(session.state));
|
|
129
|
+
const allTerminal = list.length > 0 && list.every((session) => TERMINAL_SESSION_STATES.has(session.state));
|
|
130
|
+
const allSettled = list.length > 0 && list.every((session) =>
|
|
131
|
+
SETTLED_SESSION_STATES.has(session.state) || TERMINAL_SESSION_STATES.has(session.state),
|
|
132
|
+
);
|
|
133
|
+
const fallbackAt = Date.parse(task.updated_at || task.updatedAt || task.created_at || "");
|
|
134
|
+
const lastAt = Number.isFinite(lastActivityAt) ? lastActivityAt : fallbackAt;
|
|
135
|
+
const idleFor = Number.isFinite(lastAt) ? Math.max(0, now - lastAt) : Number.NaN;
|
|
136
|
+
const idleMs = idleMsFor(policy, stageName);
|
|
137
|
+
const chosen = pickSession(list);
|
|
138
|
+
|
|
139
|
+
if (state === "IN_PROGRESS" && active) {
|
|
140
|
+
if (!Number.isFinite(idleFor)) return { action: "none", reason: "active session has no activity timestamp" };
|
|
141
|
+
if (idleFor < idleMs) return { action: "none", reason: `active session idle ${idleFor}ms < ${idleMs}ms` };
|
|
142
|
+
if (stats.runningNudges >= policy.running_nudge_max) {
|
|
143
|
+
return { action: "none", reason: "running nudge budget exhausted" };
|
|
144
|
+
}
|
|
145
|
+
return {
|
|
146
|
+
action: "message",
|
|
147
|
+
kind: "stalled",
|
|
148
|
+
sessionId: sessionIdOf(chosen),
|
|
149
|
+
reason: `no activity for ${idleFor}ms`,
|
|
150
|
+
attempt: stats.attempts + 1,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (state === "IN_PROGRESS" && !allSettled) {
|
|
155
|
+
return { action: "none", reason: "session state is not settled" };
|
|
156
|
+
}
|
|
157
|
+
if (state === "REVIEW" && active) {
|
|
158
|
+
return { action: "wait", reason: "active session is still running" };
|
|
159
|
+
}
|
|
160
|
+
if (state === "REVIEW" && !allSettled) {
|
|
161
|
+
return { action: "none", reason: "session state is not settled" };
|
|
162
|
+
}
|
|
163
|
+
if (state === "REVIEW" && !artifactMissing && artifactOk) {
|
|
164
|
+
return { action: "none", reason: "existing artifact is handled by the gate" };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const kind = artifactMissing ? "produce" : "signal";
|
|
168
|
+
const reason = artifactMissing
|
|
169
|
+
? `artifact ${artifactFile} is missing`
|
|
170
|
+
: `artifact ${artifactFile} exists but the stage was not signaled`;
|
|
171
|
+
return {
|
|
172
|
+
action: allTerminal ? "spawn" : "message",
|
|
173
|
+
kind,
|
|
174
|
+
artifactOk,
|
|
175
|
+
sessionId: sessionIdOf(chosen),
|
|
176
|
+
reason,
|
|
177
|
+
attempt: stats.attempts + 1,
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
export function buildResumePrompt({
|
|
182
|
+
stageName,
|
|
183
|
+
artifactFile,
|
|
184
|
+
artifactOk,
|
|
185
|
+
problems = [],
|
|
186
|
+
kind,
|
|
187
|
+
attempt,
|
|
188
|
+
maxAttempts,
|
|
189
|
+
}) {
|
|
190
|
+
const label = String(artifactFile || "artifact");
|
|
191
|
+
const target = label.startsWith(".agentic/") ? label : `.agentic/${label}`;
|
|
192
|
+
const reason = problems.filter(Boolean).join("; ") || `${target} is not ready`;
|
|
193
|
+
const hint = STAGE_HINTS[stageName] || "Continue the current stage from the existing worktree and conversation.";
|
|
194
|
+
const body = kind === "signal"
|
|
195
|
+
? `The stage artifact \`${target}\` already exists${artifactOk ? "" : " but is not valid"}. Do not rewrite it from scratch. If it is invalid, fix only the reported problem; otherwise just signal completion.`
|
|
196
|
+
: kind === "stalled"
|
|
197
|
+
? "This session has been idle past the stage threshold. If the stage is already complete, do not repeat work. Otherwise continue from the current worktree and conversation."
|
|
198
|
+
: `The previous turn ended before the stage produced \`${target}\`. Continue the current stage from the existing worktree and conversation.`;
|
|
199
|
+
return [
|
|
200
|
+
`[Kandev resume ${attempt}/${maxAttempts}]`,
|
|
201
|
+
`Stage: ${stageName}.`,
|
|
202
|
+
body,
|
|
203
|
+
`Hint: ${hint}`,
|
|
204
|
+
`Gate reason: ${reason}.`,
|
|
205
|
+
`Do not change scope, do not restart completed work, and do not move the workflow step. Produce or signal \`${target}\` and call \`step_complete_kandev\`. If the stage cannot pass, write the stage FAIL artifact with the exact blocker and signal it so the gate can record it.`,
|
|
206
|
+
].join("\n");
|
|
207
|
+
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/** Stop a planning review loop that has already run out of budget or is diverging. */
|
|
2
|
+
import crypto from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
const RUN_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
7
|
+
|
|
8
|
+
export function readReviewRuns(cwd, outDir = path.join(path.resolve(cwd), ".agentic", "doc-review-runs")) {
|
|
9
|
+
if (!fs.existsSync(outDir)) return [];
|
|
10
|
+
const runs = [];
|
|
11
|
+
for (const entry of fs.readdirSync(outDir, { withFileTypes: true })) {
|
|
12
|
+
if (!entry.isDirectory()) continue;
|
|
13
|
+
try {
|
|
14
|
+
const data = JSON.parse(fs.readFileSync(path.join(outDir, entry.name, "run.json"), "utf8"));
|
|
15
|
+
// A failed run is infrastructure recovery, not a review round, so it must
|
|
16
|
+
// not consume the three-round budget or move the reviewed snapshot.
|
|
17
|
+
if (data.status !== "completed") continue;
|
|
18
|
+
runs.push({
|
|
19
|
+
id: entry.name,
|
|
20
|
+
dir: path.join(outDir, entry.name),
|
|
21
|
+
startedAt: data.startedAt || entry.name,
|
|
22
|
+
major: data.counts?.findingsBySeverity?.major ?? 0,
|
|
23
|
+
});
|
|
24
|
+
} catch {
|
|
25
|
+
// Ignore a partial run directory; the next round retries it.
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return runs.sort((a, b) => (
|
|
29
|
+
String(a.startedAt).localeCompare(String(b.startedAt)) || a.id.localeCompare(b.id)
|
|
30
|
+
));
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function reviewHistoryProblems(cwd, outDir) {
|
|
34
|
+
const runs = readReviewRuns(cwd, outDir);
|
|
35
|
+
if (runs.length >= 3) {
|
|
36
|
+
return ["three review rounds already completed; stop reviewing and write PASS only if the latest round is clean, otherwise block"];
|
|
37
|
+
}
|
|
38
|
+
return [];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function runDocument(run, name) {
|
|
42
|
+
try {
|
|
43
|
+
const context = JSON.parse(fs.readFileSync(path.join(run.dir, "context.json"), "utf8"));
|
|
44
|
+
const document = (context.documents || []).find((entry) => entry.path === name);
|
|
45
|
+
return document && !document.truncated ? document.text : null;
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function runSnapshot(run) {
|
|
52
|
+
try {
|
|
53
|
+
const snapshot = JSON.parse(fs.readFileSync(path.join(run.dir, "snapshot.json"), "utf8"));
|
|
54
|
+
return Array.isArray(snapshot) ? snapshot : [];
|
|
55
|
+
} catch {
|
|
56
|
+
return [];
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function runFindings(run) {
|
|
61
|
+
try {
|
|
62
|
+
const findings = JSON.parse(fs.readFileSync(path.join(run.dir, "findings.json"), "utf8"));
|
|
63
|
+
return Array.isArray(findings) ? findings : null;
|
|
64
|
+
} catch {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function requirementIds(text) {
|
|
70
|
+
return new Set(String(text || "").match(/\b(?:FR|AC|SC)-\d+\b/g) || []);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Load the exact file snapshot used by one completed review run. */
|
|
74
|
+
export function readReviewRun(cwd, runId, outDir) {
|
|
75
|
+
const base = outDir
|
|
76
|
+
? path.resolve(cwd, outDir)
|
|
77
|
+
: path.join(path.resolve(cwd), ".agentic", "doc-review-runs");
|
|
78
|
+
if (typeof runId !== "string" || !RUN_ID_RE.test(runId)) {
|
|
79
|
+
throw new Error(`invalid review run id: ${String(runId)}`);
|
|
80
|
+
}
|
|
81
|
+
const dir = path.join(base, runId);
|
|
82
|
+
let run;
|
|
83
|
+
try {
|
|
84
|
+
run = JSON.parse(fs.readFileSync(path.join(dir, "run.json"), "utf8"));
|
|
85
|
+
} catch {
|
|
86
|
+
throw new Error(`review run ${runId} is missing`);
|
|
87
|
+
}
|
|
88
|
+
if (run.status !== "completed") throw new Error(`review run ${runId} is not completed`);
|
|
89
|
+
let snapshot;
|
|
90
|
+
try {
|
|
91
|
+
snapshot = JSON.parse(fs.readFileSync(path.join(dir, "snapshot.json"), "utf8"));
|
|
92
|
+
} catch {
|
|
93
|
+
throw new Error(`review run ${runId} has no snapshot`);
|
|
94
|
+
}
|
|
95
|
+
if (!Array.isArray(snapshot)) throw new Error(`review run ${runId} snapshot is not an array`);
|
|
96
|
+
return { id: runId, dir, run, snapshot };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function snapshotHashes(snapshot) {
|
|
100
|
+
const hashes = new Map();
|
|
101
|
+
for (const entry of snapshot) {
|
|
102
|
+
if (!entry || entry.type === "directory") continue;
|
|
103
|
+
if (typeof entry.path !== "string" || typeof entry.sha256 !== "string") continue;
|
|
104
|
+
if (!/^[0-9a-f]{64}$/.test(entry.sha256)) continue;
|
|
105
|
+
hashes.set(entry.path, entry.sha256);
|
|
106
|
+
}
|
|
107
|
+
return hashes;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function fileHash(file) {
|
|
111
|
+
return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Prove the final documents are byte-identical to the latest completed review. */
|
|
115
|
+
export function reviewSnapshotProblems(cwd, featureDir, documents, review, outDir) {
|
|
116
|
+
const problems = [];
|
|
117
|
+
const docs = Array.isArray(documents) ? documents : [];
|
|
118
|
+
const runId = review?.reviewers?.requirement_agent?.run_id;
|
|
119
|
+
if (typeof runId !== "string" || !runId.trim()) {
|
|
120
|
+
return ["requirement_agent.run_id is missing; review is not bound to a snapshot"];
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const runs = readReviewRuns(cwd, outDir);
|
|
124
|
+
if (runs.length === 0) {
|
|
125
|
+
problems.push("no completed review runs exist");
|
|
126
|
+
} else if (runs.at(-1).id !== runId) {
|
|
127
|
+
problems.push(`review run ${runId} is not the latest completed run ${runs.at(-1).id}`);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
let run;
|
|
131
|
+
try {
|
|
132
|
+
run = readReviewRun(cwd, runId, outDir);
|
|
133
|
+
} catch (error) {
|
|
134
|
+
return [...problems, error.message];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (runs.length) {
|
|
138
|
+
const history = review.major_history;
|
|
139
|
+
if (Array.isArray(history)) {
|
|
140
|
+
if (history.length !== runs.length) {
|
|
141
|
+
problems.push(`major_history has ${history.length} entries, expected ${runs.length} completed runs`);
|
|
142
|
+
} else {
|
|
143
|
+
for (const [index, entry] of runs.entries()) {
|
|
144
|
+
if (history[index] !== entry.major) {
|
|
145
|
+
problems.push(`major_history[${index}] is ${history[index]}, expected ${entry.major} from ${entry.id}`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (Number.isInteger(review.rounds) && review.rounds !== runs.length) {
|
|
151
|
+
problems.push(`rounds is ${review.rounds}, expected ${runs.length} completed runs`);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const counts = run.run.counts?.findingsBySeverity;
|
|
156
|
+
if (!counts) {
|
|
157
|
+
problems.push(`review run ${runId} has no severity counts`);
|
|
158
|
+
} else {
|
|
159
|
+
const pairs = [
|
|
160
|
+
["blockers", "blocker", "blockers"],
|
|
161
|
+
["majors", "major", "majors"],
|
|
162
|
+
["minors", "minor", "minors"],
|
|
163
|
+
];
|
|
164
|
+
for (const [key, severity, nestedKey] of pairs) {
|
|
165
|
+
const expected = counts[severity] ?? 0;
|
|
166
|
+
if (review[key] !== expected) problems.push(`${key} is ${review[key]}, expected ${expected} from ${runId}`);
|
|
167
|
+
const nested = review?.reviewers?.requirement_agent?.[nestedKey];
|
|
168
|
+
if (nested !== expected) {
|
|
169
|
+
problems.push(`reviewers.requirement_agent.${nestedKey} is ${nested}, expected ${expected} from ${runId}`);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const findings = runFindings(run);
|
|
175
|
+
if (!findings) {
|
|
176
|
+
problems.push(`review run ${runId} has no findings`);
|
|
177
|
+
} else {
|
|
178
|
+
const expectedIds = findings.filter((entry) => entry?.severity === "major").map((entry) => entry.stableId ?? entry.id).sort();
|
|
179
|
+
const actualIds = [...(review.major_ids || [])].sort();
|
|
180
|
+
if (JSON.stringify(expectedIds) !== JSON.stringify(actualIds)) {
|
|
181
|
+
problems.push(`major_ids do not match ${runId} findings (use stableId when present)`);
|
|
182
|
+
}
|
|
183
|
+
if (Number(review.blockers) > 0 && Array.isArray(review.blocker_ids)) {
|
|
184
|
+
const expectedBlockerIds = findings
|
|
185
|
+
.filter((entry) => entry?.severity === "blocker")
|
|
186
|
+
.map((entry) => entry.stableId ?? entry.id)
|
|
187
|
+
.sort();
|
|
188
|
+
const actualBlockerIds = [...(review.blocker_ids || [])].sort();
|
|
189
|
+
if (JSON.stringify(expectedBlockerIds) !== JSON.stringify(actualBlockerIds)) {
|
|
190
|
+
problems.push(`blocker_ids do not match ${runId} findings (use stableId when present)`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const expected = snapshotHashes(run.snapshot);
|
|
196
|
+
const reviewed = new Map((review.reviewed_documents || []).map((entry) => [entry.path, entry.sha256]));
|
|
197
|
+
const feature = path.resolve(featureDir);
|
|
198
|
+
for (const file of docs) {
|
|
199
|
+
if (typeof file !== "string" || !file) continue;
|
|
200
|
+
if (!expected.has(file)) {
|
|
201
|
+
problems.push(`reviewed snapshot is missing ${file}`);
|
|
202
|
+
continue;
|
|
203
|
+
}
|
|
204
|
+
const expectedHash = expected.get(file);
|
|
205
|
+
if (reviewed.get(file) !== expectedHash) {
|
|
206
|
+
problems.push(`reviewed_documents does not match review snapshot: ${file}`);
|
|
207
|
+
}
|
|
208
|
+
const abs = path.resolve(feature, file);
|
|
209
|
+
if (!abs.startsWith(`${feature}${path.sep}`)) {
|
|
210
|
+
problems.push(`planning document escapes feature_dir: ${file}`);
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
|
|
214
|
+
problems.push(`planning document missing: ${file}`);
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (fileHash(abs) !== expectedHash) {
|
|
218
|
+
problems.push(`reviewed document hash changed since review: ${file}`);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
for (const file of reviewed.keys()) {
|
|
222
|
+
if (!docs.includes(file)) problems.push(`reviewed_documents contains unreferenced ${file}`);
|
|
223
|
+
}
|
|
224
|
+
return problems;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** Keep remediation from adding new scope after the design has had one repair round. */
|
|
228
|
+
export function reviewScopeProblems(cwd, inputDir, outDir) {
|
|
229
|
+
const runs = readReviewRuns(cwd, outDir);
|
|
230
|
+
if (runs.length < 2) return [];
|
|
231
|
+
const baseline = runs.at(-1);
|
|
232
|
+
const root = path.resolve(inputDir);
|
|
233
|
+
const problems = [];
|
|
234
|
+
|
|
235
|
+
const before = runDocument(baseline, "spec.md");
|
|
236
|
+
const specFile = path.join(root, "spec.md");
|
|
237
|
+
if (before && fs.existsSync(specFile)) {
|
|
238
|
+
const previous = requirementIds(before);
|
|
239
|
+
const current = requirementIds(fs.readFileSync(specFile, "utf8"));
|
|
240
|
+
const added = [...current].filter((id) => !previous.has(id)).sort();
|
|
241
|
+
if (added.length) {
|
|
242
|
+
problems.push(`review remediation added requirement ids ${added.join(", ")}; keep the ${baseline.id} requirement set stable and block/replan for new scope`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
for (const entry of runSnapshot(baseline)) {
|
|
247
|
+
if (!entry?.path?.endsWith(".md")) continue;
|
|
248
|
+
if (entry.path === "analysis.md" || entry.path.startsWith("checklists/")) continue;
|
|
249
|
+
const file = path.join(root, entry.path);
|
|
250
|
+
if (!fs.existsSync(file)) continue;
|
|
251
|
+
const size = fs.statSync(file).size;
|
|
252
|
+
const budget = Math.max(500, Math.round((entry.size || 0) * 0.2));
|
|
253
|
+
if (size - (entry.size || 0) > budget) {
|
|
254
|
+
problems.push(`${entry.path} grew from ${entry.size} to ${size} bytes since ${baseline.id}; edit only cited passages`);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return problems;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export { runSnapshot };
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/** Stage isolation: snapshot the worktree and reject out-of-stage changes. */
|
|
2
|
+
import crypto from "node:crypto";
|
|
3
|
+
import fs from "node:fs";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
6
|
+
|
|
7
|
+
const IGNORED_DIRS = new Set([
|
|
8
|
+
".git",
|
|
9
|
+
"node_modules",
|
|
10
|
+
".agentic",
|
|
11
|
+
".codex",
|
|
12
|
+
".cache",
|
|
13
|
+
".state",
|
|
14
|
+
"dist",
|
|
15
|
+
"build",
|
|
16
|
+
"target",
|
|
17
|
+
"coverage",
|
|
18
|
+
".next",
|
|
19
|
+
"out",
|
|
20
|
+
"obj",
|
|
21
|
+
"bin",
|
|
22
|
+
".gradle",
|
|
23
|
+
"test-results",
|
|
24
|
+
"playwright-report",
|
|
25
|
+
".pytest_cache",
|
|
26
|
+
"__pycache__",
|
|
27
|
+
".venv",
|
|
28
|
+
"venv",
|
|
29
|
+
".review-runs",
|
|
30
|
+
".review-worktrees",
|
|
31
|
+
".review-clones",
|
|
32
|
+
"superpower_reports",
|
|
33
|
+
]);
|
|
34
|
+
|
|
35
|
+
function ignoredPath(rel) {
|
|
36
|
+
if (!rel) return false;
|
|
37
|
+
const parts = rel.split("/");
|
|
38
|
+
if (parts.some((part) => IGNORED_DIRS.has(part))) return true;
|
|
39
|
+
if (parts.some((part) => part.startsWith(".review-"))) return true;
|
|
40
|
+
if (rel.endsWith(".log")) return true;
|
|
41
|
+
if (rel === "app_ui_map.json" || rel === "test_scenarios.json") return true;
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function hashFile(file) {
|
|
46
|
+
return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Deterministic path -> content hash map for the worktree. */
|
|
50
|
+
export function snapshotWorktree(cwd) {
|
|
51
|
+
const root = path.resolve(cwd);
|
|
52
|
+
const snapshot = {};
|
|
53
|
+
const walk = (dir, rel) => {
|
|
54
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
55
|
+
const relPath = rel ? `${rel}/${entry.name}` : entry.name;
|
|
56
|
+
if (ignoredPath(relPath)) continue;
|
|
57
|
+
const abs = path.join(dir, entry.name);
|
|
58
|
+
const stat = fs.lstatSync(abs);
|
|
59
|
+
if (stat.isSymbolicLink()) {
|
|
60
|
+
snapshot[relPath] = `symlink:${fs.readlinkSync(abs)}`;
|
|
61
|
+
} else if (stat.isDirectory()) {
|
|
62
|
+
walk(abs, relPath);
|
|
63
|
+
} else if (stat.isFile()) {
|
|
64
|
+
snapshot[relPath] = hashFile(abs);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
walk(root, "");
|
|
69
|
+
return snapshot;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function diffSnapshots(before, after) {
|
|
73
|
+
const paths = new Set([...Object.keys(before || {}), ...Object.keys(after || {})]);
|
|
74
|
+
return [...paths].filter((file) => before?.[file] !== after?.[file]).sort();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function gitStatusChanges(cwd) {
|
|
78
|
+
const result = spawnSync("git", ["-C", cwd, "status", "--porcelain", "--untracked-files=all"], {
|
|
79
|
+
encoding: "utf8",
|
|
80
|
+
timeout: 30_000,
|
|
81
|
+
});
|
|
82
|
+
if (result.status !== 0) return null;
|
|
83
|
+
const files = [];
|
|
84
|
+
for (const line of String(result.stdout || "").split("\n")) {
|
|
85
|
+
if (!line.trim()) continue;
|
|
86
|
+
let file = line.slice(3).trim();
|
|
87
|
+
if (file.includes(" -> ")) file = file.split(" -> ").pop().trim();
|
|
88
|
+
file = file.replace(/^"|"$/g, "");
|
|
89
|
+
if (file && !ignoredPath(file)) files.push(file);
|
|
90
|
+
}
|
|
91
|
+
return [...new Set(files)].sort();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Paths a stage is allowed to change. Everything else is a violation. */
|
|
95
|
+
export function boundaryViolations(stageIndex, changes) {
|
|
96
|
+
const allowed = (file) => {
|
|
97
|
+
if (stageIndex === 0) {
|
|
98
|
+
return file === ".agentic/gateway.json"
|
|
99
|
+
|| file === ".agentic/docker.json"
|
|
100
|
+
|| file.startsWith(".specify/")
|
|
101
|
+
|| file.startsWith(".agents/");
|
|
102
|
+
}
|
|
103
|
+
if (stageIndex === 1) {
|
|
104
|
+
return file.startsWith("specs/") || file === ".specify/feature.json";
|
|
105
|
+
}
|
|
106
|
+
if (stageIndex === 2) {
|
|
107
|
+
if (file.startsWith(".specify/") || file.startsWith(".agents/")) return false;
|
|
108
|
+
if (file.startsWith("specs/")) return /(^|\/)tasks\.md$/.test(file);
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
return false;
|
|
112
|
+
};
|
|
113
|
+
return (changes || []).filter((file) => !allowed(file));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function boundaryFile(cacheDir, taskId) {
|
|
117
|
+
return path.join(cacheDir, "stage-boundaries", `${taskId}.json`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function readBoundary(cacheDir, taskId) {
|
|
121
|
+
try {
|
|
122
|
+
const data = JSON.parse(fs.readFileSync(boundaryFile(cacheDir, taskId), "utf8"));
|
|
123
|
+
if (!Number.isInteger(data?.stage) || !data.snapshot || typeof data.snapshot !== "object") return null;
|
|
124
|
+
return {
|
|
125
|
+
...data,
|
|
126
|
+
pins: data.pins && typeof data.pins === "object" ? data.pins : null,
|
|
127
|
+
};
|
|
128
|
+
} catch {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function writeBoundary(cacheDir, taskId, stageIndex, snapshot, pins = null) {
|
|
134
|
+
const file = boundaryFile(cacheDir, taskId);
|
|
135
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
136
|
+
const temp = `${file}.tmp-${process.pid}`;
|
|
137
|
+
fs.writeFileSync(temp, `${JSON.stringify({
|
|
138
|
+
stage: stageIndex,
|
|
139
|
+
snapshot,
|
|
140
|
+
pins,
|
|
141
|
+
at: new Date().toISOString(),
|
|
142
|
+
})}\n`);
|
|
143
|
+
fs.renameSync(temp, file);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export const STAGE_NAMES = ["gateway", "planning", "implementation", "review", "e2e"];
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Read the stage model injected by the Kandev profile's agent-tools environment. */
|
|
2
|
+
const MODEL_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,119}$/;
|
|
3
|
+
|
|
4
|
+
export function requireStageModel(env = process.env) {
|
|
5
|
+
const value = String(env.KANDEV_STAGE_MODEL || "").trim();
|
|
6
|
+
if (!value) {
|
|
7
|
+
throw new Error(
|
|
8
|
+
"KANDEV_STAGE_MODEL is not set; launch this wrapper from a Kandev stage with the stage model injected",
|
|
9
|
+
);
|
|
10
|
+
}
|
|
11
|
+
if (!MODEL_PATTERN.test(value)) {
|
|
12
|
+
throw new Error(`KANDEV_STAGE_MODEL is not a valid model id: ${value}`);
|
|
13
|
+
}
|
|
14
|
+
return value;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Resolve the sub-agent CLI id ("codex" or "gemini") from KANDEV_STAGE_AGENT. */
|
|
18
|
+
export function resolveStageAgent(env = process.env) {
|
|
19
|
+
const raw = String(env.KANDEV_STAGE_AGENT || "").trim().toLowerCase();
|
|
20
|
+
if (!raw || raw === "codex" || raw === "codex-acp") return "codex";
|
|
21
|
+
if (raw === "gemini" || raw === "gemini-cli") return "gemini";
|
|
22
|
+
throw new Error(`KANDEV_STAGE_AGENT is not a supported agent: ${raw}`);
|
|
23
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/** Resolve a Kandev task id to its worktree without touching the Kandev install. */
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
export function kandevHome(env = process.env) {
|
|
7
|
+
return env.KANDEV_HOME || path.join(os.homedir(), ".kandev");
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function taskDirs(homeDir = kandevHome()) {
|
|
11
|
+
const root = path.join(homeDir, "tasks");
|
|
12
|
+
const map = new Map();
|
|
13
|
+
if (!fs.existsSync(root)) return map;
|
|
14
|
+
for (const entry of fs.readdirSync(root, { withFileTypes: true })) {
|
|
15
|
+
if (!entry.isDirectory()) continue;
|
|
16
|
+
const marker = path.join(root, entry.name, ".kandev-workspace.json");
|
|
17
|
+
if (!fs.existsSync(marker)) continue;
|
|
18
|
+
try {
|
|
19
|
+
const data = JSON.parse(fs.readFileSync(marker, "utf8"));
|
|
20
|
+
if (data.task_id) map.set(data.task_id, path.join(root, entry.name));
|
|
21
|
+
} catch {
|
|
22
|
+
// Ignore an unreadable marker; the next tick retries.
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return map;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function repoDirFor(taskDir) {
|
|
29
|
+
const candidates = fs.readdirSync(taskDir, { withFileTypes: true })
|
|
30
|
+
.filter((entry) => entry.isDirectory())
|
|
31
|
+
.map((entry) => path.join(taskDir, entry.name));
|
|
32
|
+
return candidates.find((dir) => fs.existsSync(path.join(dir, "package.json"))) || candidates[0] || null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function findTaskRepo(taskId, homeDir = kandevHome()) {
|
|
36
|
+
const taskDir = taskDirs(homeDir).get(taskId);
|
|
37
|
+
if (!taskDir) return null;
|
|
38
|
+
const repoDir = repoDirFor(taskDir);
|
|
39
|
+
return repoDir ? { taskDir, repoDir } : null;
|
|
40
|
+
}
|