sdtk-code-kit 0.3.0 → 0.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +204 -204
- package/assets/manifest/toolkit-bundle.manifest.json +147 -147
- package/assets/manifest/toolkit-bundle.sha256.txt +5 -5
- package/bin/sdtk-code.js +14 -14
- package/package.json +44 -44
- package/src/commands/agent-team.js +479 -174
- package/src/commands/build.js +53 -53
- package/src/commands/doctor.js +51 -51
- package/src/commands/generate.js +11 -11
- package/src/commands/guardrails.js +215 -215
- package/src/commands/help.js +266 -257
- package/src/commands/init.js +98 -98
- package/src/commands/plan.js +53 -53
- package/src/commands/readiness.js +77 -77
- package/src/commands/resume.js +61 -61
- package/src/commands/runtime.js +224 -224
- package/src/commands/ship.js +59 -59
- package/src/commands/sleep.js +132 -132
- package/src/commands/start.js +89 -89
- package/src/commands/status.js +77 -77
- package/src/commands/update.js +11 -11
- package/src/commands/verify.js +71 -71
- package/src/index.js +112 -112
- package/src/lib/agent-team-author.js +552 -0
- package/src/lib/agent-team-evidence.js +302 -0
- package/src/lib/agent-team-execute.js +892 -0
- package/src/lib/agent-team-export.js +411 -409
- package/src/lib/agent-team-plan.js +514 -514
- package/src/lib/agent-team-readiness.js +161 -0
- package/src/lib/agent-team-report.js +165 -0
- package/src/lib/agent-team-sleep-execute.js +524 -0
- package/src/lib/agent-team-sleep-session.js +278 -0
- package/src/lib/args.js +107 -107
- package/src/lib/errors.js +41 -41
- package/src/lib/model-provider.js +219 -0
- package/src/lib/powershell.js +65 -65
- package/src/lib/project-target-guard.js +53 -53
- package/src/lib/scope.js +72 -72
- package/src/lib/ship-readiness.js +281 -281
- package/src/lib/sleep-plan.js +175 -175
- package/src/lib/sleep-report.js +229 -229
- package/src/lib/toolkit-payload.js +72 -72
- package/src/lib/trust-events.js +264 -185
- package/src/lib/trust-file-scope.js +154 -154
- package/src/lib/trust-policy.js +212 -212
- package/src/lib/trust-redact.js +58 -35
- package/src/lib/trust-trace.js +179 -179
- package/src/lib/update.js +344 -344
- package/src/lib/workflow-artifact.js +503 -503
- package/src/lib/workflow-build.js +127 -127
- package/src/lib/workflow-doctor.js +83 -83
- package/src/lib/workflow-handoff.js +1029 -1029
- package/src/lib/workflow-intake.js +101 -101
- package/src/lib/workflow-plan.js +193 -193
- package/src/lib/workflow-review-packet.js +650 -650
- package/src/lib/workflow-ship.js +213 -213
- package/src/lib/workflow-state.js +438 -438
- package/src/lib/workflow-verify.js +393 -393
|
@@ -0,0 +1,892 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("fs");
|
|
4
|
+
const path = require("path");
|
|
5
|
+
const { spawnSync } = require("child_process");
|
|
6
|
+
const { ValidationError } = require("./errors");
|
|
7
|
+
const { safeSegment } = require("./agent-team-export");
|
|
8
|
+
const { loadAgentTeamPlan } = require("./agent-team-plan");
|
|
9
|
+
const { STOP_CONDITIONS } = require("./sleep-plan");
|
|
10
|
+
const { redact } = require("./trust-redact");
|
|
11
|
+
const { submitEvidence } = require("./agent-team-evidence");
|
|
12
|
+
const { computeReadiness, writeReadiness } = require("./agent-team-readiness");
|
|
13
|
+
const { buildMorningReport, writeReport } = require("./agent-team-report");
|
|
14
|
+
|
|
15
|
+
const WORKFLOW_TYPES = Object.freeze(["docs"]);
|
|
16
|
+
const ACTION_CAP_DEFAULT = 20;
|
|
17
|
+
const COMMAND_TIMEOUT_MS = 120000;
|
|
18
|
+
const PATCH_MAX_FILES = 50;
|
|
19
|
+
const PATCH_MAX_LINES = 20000;
|
|
20
|
+
const EXECUTE_EVIDENCE_SCHEMA = "sdtk.agent-team-evidence.v1";
|
|
21
|
+
const EXECUTE_BRANCH_PREFIX = "sdtk/agent-team";
|
|
22
|
+
const A1_LITERAL = "python3 scripts/ci/docs_lint.py";
|
|
23
|
+
const A2_LITERAL = "python3 scripts/ci/path_check.py";
|
|
24
|
+
const A1_ARGV = Object.freeze(["python3", "scripts/ci/docs_lint.py"]);
|
|
25
|
+
const A2_ARGV = Object.freeze(["python3", "scripts/ci/path_check.py"]);
|
|
26
|
+
const ALLOWED_COMMANDS = Object.freeze([
|
|
27
|
+
Object.freeze({ literal: A1_LITERAL, argv: A1_ARGV }),
|
|
28
|
+
Object.freeze({ literal: A2_LITERAL, argv: A2_ARGV }),
|
|
29
|
+
]);
|
|
30
|
+
const STOP_CONDITION_IDS = Object.freeze(
|
|
31
|
+
STOP_CONDITIONS.map((condition) => condition && condition.id).filter(Boolean)
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
function asArray(value) {
|
|
35
|
+
return Array.isArray(value) ? value : [];
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function assertPathUnderBase(resolvedPath, expectedBase) {
|
|
39
|
+
const resolved = path.resolve(resolvedPath);
|
|
40
|
+
const base = path.resolve(expectedBase);
|
|
41
|
+
if (resolved !== base && !resolved.startsWith(base + path.sep)) {
|
|
42
|
+
throw new ValidationError("FAIL_UNSAFE_EXPORT_PATH: resolved path outside expected base");
|
|
43
|
+
}
|
|
44
|
+
return resolved;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function worktreesBaseDir(projectPath) {
|
|
48
|
+
return path.resolve(projectPath || ".", ".sdtk", "agent-team", "worktrees");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function resolveWorktreeRoot(projectPath, runId) {
|
|
52
|
+
const safeRunId = safeSegment(runId, "run_id");
|
|
53
|
+
const base = worktreesBaseDir(projectPath);
|
|
54
|
+
return assertPathUnderBase(path.join(base, safeRunId), base);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function writerRole(plan) {
|
|
58
|
+
const writers = asArray(plan && plan.roles).filter((role) => role && role.can_write === true);
|
|
59
|
+
if (writers.length !== 1) {
|
|
60
|
+
throw new ValidationError(`FAIL_EXECUTE_SCOPE: expected exactly one writer role, found ${writers.length}.`);
|
|
61
|
+
}
|
|
62
|
+
const role = writers[0];
|
|
63
|
+
if (!role.role) {
|
|
64
|
+
throw new ValidationError("FAIL_EXECUTE_SCOPE: writer role is missing role name.");
|
|
65
|
+
}
|
|
66
|
+
if (!Array.isArray(role.allowed_file_scopes) || role.allowed_file_scopes.length === 0) {
|
|
67
|
+
throw new ValidationError("FAIL_EXECUTE_SCOPE: writer role has no allowed_file_scopes.");
|
|
68
|
+
}
|
|
69
|
+
return role;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function loadExecuteContext(projectPath, featureKey) {
|
|
73
|
+
const safeFeatureKey = safeSegment(featureKey, "feature_key");
|
|
74
|
+
const plan = loadAgentTeamPlan(projectPath, safeFeatureKey);
|
|
75
|
+
if (plan.feature_key !== safeFeatureKey) {
|
|
76
|
+
throw new ValidationError(
|
|
77
|
+
`NEEDS_AGENT_TEAM_PLAN: agent-team plan feature_key "${plan.feature_key}" does not match --feature-key "${safeFeatureKey}".`
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
const role = writerRole(plan);
|
|
81
|
+
const runId = safeSegment(plan.run_id, "run_id");
|
|
82
|
+
return {
|
|
83
|
+
projectPath: path.resolve(projectPath || "."),
|
|
84
|
+
featureKey: safeFeatureKey,
|
|
85
|
+
runId,
|
|
86
|
+
plan,
|
|
87
|
+
role,
|
|
88
|
+
workflowType: "docs",
|
|
89
|
+
worktreeRoot: resolveWorktreeRoot(projectPath, runId),
|
|
90
|
+
branch: `${EXECUTE_BRANCH_PREFIX}/${safeFeatureKey}/${runId}`,
|
|
91
|
+
allowedFileScopes: asArray(role.allowed_file_scopes),
|
|
92
|
+
verificationCommands: asArray(role.verification_commands),
|
|
93
|
+
actionCap: ACTION_CAP_DEFAULT,
|
|
94
|
+
stopConditions: activeStopConditionIds(plan),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
function stripPatchPrefix(rawPath) {
|
|
101
|
+
if (!rawPath || rawPath === "/dev/null") return null;
|
|
102
|
+
let value = String(rawPath).trim();
|
|
103
|
+
if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
|
|
104
|
+
value = value.slice(1, -1);
|
|
105
|
+
}
|
|
106
|
+
if (value.startsWith("a/") || value.startsWith("b/")) {
|
|
107
|
+
return value.slice(2);
|
|
108
|
+
}
|
|
109
|
+
return value;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function changedLineCount(patchText) {
|
|
113
|
+
let count = 0;
|
|
114
|
+
for (const line of String(patchText || "").split(/\r?\n/)) {
|
|
115
|
+
if ((line.startsWith("+") && !line.startsWith("+++")) || (line.startsWith("-") && !line.startsWith("---"))) {
|
|
116
|
+
count++;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return count;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function extractPatchTargets(patchText) {
|
|
123
|
+
const targets = [];
|
|
124
|
+
let current = null;
|
|
125
|
+
for (const line of String(patchText || "").split(/\r?\n/)) {
|
|
126
|
+
const diff = line.match(/^diff --git\s+(\S+)\s+(\S+)$/);
|
|
127
|
+
if (diff) {
|
|
128
|
+
current = {
|
|
129
|
+
oldPath: stripPatchPrefix(diff[1]),
|
|
130
|
+
newPath: stripPatchPrefix(diff[2]),
|
|
131
|
+
isDelete: false,
|
|
132
|
+
};
|
|
133
|
+
targets.push(current);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
if (!current) continue;
|
|
137
|
+
if (line.startsWith("deleted file mode")) {
|
|
138
|
+
current.isDelete = true;
|
|
139
|
+
} else if (line.startsWith("rename from ")) {
|
|
140
|
+
const oldPath = stripPatchPrefix(line.slice("rename from ".length));
|
|
141
|
+
if (oldPath) current.oldPath = oldPath;
|
|
142
|
+
} else if (line.startsWith("rename to ")) {
|
|
143
|
+
const newPath = stripPatchPrefix(line.slice("rename to ".length));
|
|
144
|
+
if (newPath) current.newPath = newPath;
|
|
145
|
+
} else if (line.startsWith("--- ")) {
|
|
146
|
+
const oldPath = stripPatchPrefix(line.slice(4).split(/\t/)[0]);
|
|
147
|
+
if (oldPath) current.oldPath = oldPath;
|
|
148
|
+
} else if (line.startsWith("+++ ")) {
|
|
149
|
+
const newPath = stripPatchPrefix(line.slice(4).split(/\t/)[0]);
|
|
150
|
+
if (newPath) current.newPath = newPath;
|
|
151
|
+
else current.isDelete = true;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const unique = new Map();
|
|
155
|
+
for (const target of targets) {
|
|
156
|
+
const key = `${target.oldPath || ""}|${target.newPath || ""}|${target.isDelete ? "D" : "M"}`;
|
|
157
|
+
unique.set(key, target);
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
targets: Array.from(unique.values()),
|
|
161
|
+
file_count: new Set(Array.from(unique.values()).map((target) => target.newPath || target.oldPath).filter(Boolean)).size,
|
|
162
|
+
changed_lines: changedLineCount(patchText),
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function pathSegments(value) {
|
|
167
|
+
return String(value || "").split(/[\\/]+/).filter(Boolean);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function isTraversalOrAbsolute(targetPath) {
|
|
171
|
+
if (!targetPath || path.isAbsolute(targetPath)) return true;
|
|
172
|
+
return pathSegments(targetPath).includes("..");
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function isSecretPath(targetPath) {
|
|
176
|
+
const normalized = String(targetPath || "").replace(/\\/g, "/");
|
|
177
|
+
return normalized === ".env" ||
|
|
178
|
+
normalized.startsWith(".env.") ||
|
|
179
|
+
normalized.startsWith("secrets/") ||
|
|
180
|
+
normalized.startsWith(".codex/") ||
|
|
181
|
+
normalized.startsWith(".claude/");
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function isAllowedDocTarget(targetPath) {
|
|
185
|
+
const normalized = String(targetPath || "").replace(/\\/g, "/");
|
|
186
|
+
if (normalized === "README.md" || normalized === "AGENTS.md") return true;
|
|
187
|
+
if (normalized.startsWith("docs/") && normalized.endsWith(".md")) return true;
|
|
188
|
+
if (normalized.startsWith("governance/") && normalized.endsWith(".md")) return true;
|
|
189
|
+
return false;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function globToRegex(scope) {
|
|
193
|
+
const escaped = String(scope).replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
194
|
+
.replace(/\*\*/g, "::DOUBLE_STAR::")
|
|
195
|
+
.replace(/\*/g, "[^/]*")
|
|
196
|
+
.replace(/::DOUBLE_STAR::/g, ".*");
|
|
197
|
+
return new RegExp(`^${escaped}$`);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function matchesScope(targetPath, scope) {
|
|
201
|
+
const normalized = String(targetPath || "").replace(/\\/g, "/");
|
|
202
|
+
const normalizedScope = String(scope || "").replace(/\\/g, "/");
|
|
203
|
+
if (normalizedScope.endsWith("/**")) {
|
|
204
|
+
const prefix = normalizedScope.slice(0, -3);
|
|
205
|
+
return normalized === prefix || normalized.startsWith(`${prefix}/`);
|
|
206
|
+
}
|
|
207
|
+
if (normalizedScope.includes("*")) {
|
|
208
|
+
return globToRegex(normalizedScope).test(normalized);
|
|
209
|
+
}
|
|
210
|
+
return normalized === normalizedScope;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function targetInAllowedScopes(targetPath, allowedScopes) {
|
|
214
|
+
return asArray(allowedScopes).some((scope) => matchesScope(targetPath, scope));
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function stop(stopConditionHit, reason) {
|
|
218
|
+
return { stop_condition_hit: stopConditionHit, reason };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function guardPatchTargets(summary, worktreeRoot, allowedScopes) {
|
|
222
|
+
if (!summary || !Array.isArray(summary.targets) || summary.targets.length === 0) {
|
|
223
|
+
return stop("unknown_risk_stop", "patch has no evaluable targets");
|
|
224
|
+
}
|
|
225
|
+
if (summary.file_count > PATCH_MAX_FILES || summary.changed_lines > PATCH_MAX_LINES) {
|
|
226
|
+
return stop("unknown_risk_stop", `patch exceeds ceiling: files=${summary.file_count}, lines=${summary.changed_lines}`);
|
|
227
|
+
}
|
|
228
|
+
const base = path.resolve(worktreeRoot);
|
|
229
|
+
for (const target of summary.targets) {
|
|
230
|
+
const rawTarget = target.newPath || target.oldPath;
|
|
231
|
+
const oldPath = target.oldPath || "";
|
|
232
|
+
const newPath = target.newPath || "";
|
|
233
|
+
// D-2a intentionally keeps rename support blocked. If a future BK enables
|
|
234
|
+
// renames, both source and destination sides must be guarded explicitly.
|
|
235
|
+
if (!target.isDelete && oldPath && newPath && oldPath !== newPath) {
|
|
236
|
+
return stop("destructive_deny", `patch renames are not allowed in Phase D R1: ${oldPath} -> ${newPath}`);
|
|
237
|
+
}
|
|
238
|
+
if (target.isDelete) {
|
|
239
|
+
return stop("destructive_deny", `patch deletes ${rawTarget}`);
|
|
240
|
+
}
|
|
241
|
+
if (isTraversalOrAbsolute(rawTarget)) {
|
|
242
|
+
return stop("scope_lock", `patch target escapes safe path segment: ${rawTarget}`);
|
|
243
|
+
}
|
|
244
|
+
if (isSecretPath(rawTarget)) {
|
|
245
|
+
return stop("secret_block", `patch target touches protected path: ${rawTarget}`);
|
|
246
|
+
}
|
|
247
|
+
const resolved = path.resolve(base, rawTarget);
|
|
248
|
+
if (resolved !== base && !resolved.startsWith(base + path.sep)) {
|
|
249
|
+
return stop("scope_lock", `patch target resolves outside worktree: ${rawTarget}`);
|
|
250
|
+
}
|
|
251
|
+
if (!isAllowedDocTarget(rawTarget)) {
|
|
252
|
+
return stop("unknown_risk_stop", `patch target is not in the Phase D-2a doc-class allowlist: ${rawTarget}`);
|
|
253
|
+
}
|
|
254
|
+
if (!targetInAllowedScopes(rawTarget, allowedScopes)) {
|
|
255
|
+
return stop("scope_lock", `patch target outside allowed_file_scopes: ${rawTarget}`);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function readPatchSummary(patchFile) {
|
|
262
|
+
const patchText = fs.readFileSync(patchFile, "utf8");
|
|
263
|
+
return extractPatchTargets(patchText);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function applyPatch(worktreeRoot, patchFile) {
|
|
267
|
+
const patchPath = path.resolve(patchFile);
|
|
268
|
+
const checked = runGit(["apply", "--check", patchPath], { cwd: worktreeRoot, timeoutMs: COMMAND_TIMEOUT_MS });
|
|
269
|
+
if (checked.exitCode !== 0) {
|
|
270
|
+
throw new ValidationError(`unknown_risk_stop: git apply --check failed: ${checked.stderr || checked.stdout || "no output"}`);
|
|
271
|
+
}
|
|
272
|
+
const applied = runGit(["apply", patchPath], { cwd: worktreeRoot, timeoutMs: COMMAND_TIMEOUT_MS });
|
|
273
|
+
if (applied.exitCode !== 0) {
|
|
274
|
+
throw new ValidationError(`unknown_risk_stop: git apply failed: ${applied.stderr || applied.stdout || "no output"}`);
|
|
275
|
+
}
|
|
276
|
+
return applied;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const SHELL_META_RE = /(?:;|&&|\|\||\||`|\$\(|>|<|\n|\r|&)/;
|
|
280
|
+
|
|
281
|
+
function rejectShellMetacharacters(cmdArgv) {
|
|
282
|
+
for (const token of cmdArgv) {
|
|
283
|
+
if (SHELL_META_RE.test(String(token))) {
|
|
284
|
+
throw new ValidationError(`unknown_risk_stop: shell metacharacter rejected in token "${token}"`);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function networkMutationReason(cmdArgv) {
|
|
290
|
+
const head = String(cmdArgv[0] || "");
|
|
291
|
+
const sub = String(cmdArgv[1] || "");
|
|
292
|
+
if (head === "git" && sub === "push") return "git push";
|
|
293
|
+
if (head === "gh") return "gh";
|
|
294
|
+
if (head === "npm" && ["publish", "install", "ci"].includes(sub)) return `npm ${sub}`;
|
|
295
|
+
if (head === "npx") return "npx";
|
|
296
|
+
if (head === "curl" || head === "wget") return head;
|
|
297
|
+
if (head === "pip" && sub === "install") return "pip install";
|
|
298
|
+
if (head === "python3" && sub === "-m" && cmdArgv[2] === "pip" && cmdArgv[3] === "install") return "python3 -m pip install";
|
|
299
|
+
if (head === "yarn" && sub === "add") return "yarn add";
|
|
300
|
+
return null;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function runControlledProcess(cmdArgv, opts) {
|
|
304
|
+
const options = opts || {};
|
|
305
|
+
if (!Array.isArray(cmdArgv) || cmdArgv.length === 0) {
|
|
306
|
+
throw new ValidationError("unknown_risk_stop: command argv is empty or invalid");
|
|
307
|
+
}
|
|
308
|
+
const argv = cmdArgv.map((token) => String(token));
|
|
309
|
+
rejectShellMetacharacters(argv);
|
|
310
|
+
const networkMutation = networkMutationReason(argv);
|
|
311
|
+
if (networkMutation) {
|
|
312
|
+
throw new ValidationError(`unknown_risk_stop: network mutation command rejected: ${networkMutation}`);
|
|
313
|
+
}
|
|
314
|
+
const result = spawnSync(argv[0], argv.slice(1), {
|
|
315
|
+
cwd: options.cwd || process.cwd(),
|
|
316
|
+
encoding: "utf8",
|
|
317
|
+
shell: false,
|
|
318
|
+
timeout: options.timeoutMs || COMMAND_TIMEOUT_MS,
|
|
319
|
+
maxBuffer: 1024 * 1024 * 8,
|
|
320
|
+
env: options.env || process.env,
|
|
321
|
+
});
|
|
322
|
+
if (result.error) {
|
|
323
|
+
if (result.error.code === "ENOENT" && argv[0] === "python3") {
|
|
324
|
+
// No interpreter fallback in D-2a; Windows parity requires a future CI-backed BK.
|
|
325
|
+
throw new ValidationError("FAIL_EXECUTE_UNSUPPORTED_PLATFORM: python3 is not resolvable on PATH; Phase D R1 is Linux-first.");
|
|
326
|
+
}
|
|
327
|
+
if (result.error.code === "ETIMEDOUT") {
|
|
328
|
+
return { exitCode: 124, stdout: redact(result.stdout || ""), stderr: redact(result.stderr || "command timed out") };
|
|
329
|
+
}
|
|
330
|
+
throw result.error;
|
|
331
|
+
}
|
|
332
|
+
return {
|
|
333
|
+
exitCode: typeof result.status === "number" ? result.status : 1,
|
|
334
|
+
stdout: redact(result.stdout || ""),
|
|
335
|
+
stderr: redact(result.stderr || ""),
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// Routes allowed git maintenance/apply subcommands into runControlledProcess;
|
|
340
|
+
// this is not the security boundary. The gateway owns network-mutation deny,
|
|
341
|
+
// and `git push` is routed on purpose so that deny path is exercised.
|
|
342
|
+
function gitArgvRouted(argv) {
|
|
343
|
+
if (argv[0] === "push") return true; // route to gateway so network deny is proven there.
|
|
344
|
+
if (argv[0] === "worktree" && ["add", "remove"].includes(argv[1])) return true;
|
|
345
|
+
if (argv[0] === "branch" && argv[1] === "-D") return true;
|
|
346
|
+
if (argv[0] === "apply") return true;
|
|
347
|
+
return false;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function runGit(argv, opts) {
|
|
351
|
+
if (!Array.isArray(argv) || argv.length === 0 || !gitArgvRouted(argv.map(String))) {
|
|
352
|
+
throw new ValidationError("unknown_risk_stop: git subcommand is not allowed in Phase D R1");
|
|
353
|
+
}
|
|
354
|
+
return runControlledProcess(["git", ...argv], opts || {});
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function sameArgv(left, right) {
|
|
358
|
+
return Array.isArray(left) && Array.isArray(right) &&
|
|
359
|
+
left.length === right.length && left.every((value, index) => value === right[index]);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function normalizeVerificationCommand(command) {
|
|
363
|
+
const literal = String(command || "").trim();
|
|
364
|
+
if (literal === A1_LITERAL) return [...A1_ARGV];
|
|
365
|
+
if (literal === A2_LITERAL) return [...A2_ARGV];
|
|
366
|
+
return null;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function resolveExecutable(name, pathEnv) {
|
|
370
|
+
const paths = String(pathEnv === undefined ? process.env.PATH || "" : pathEnv).split(path.delimiter).filter(Boolean);
|
|
371
|
+
for (const dir of paths) {
|
|
372
|
+
const candidate = path.join(dir, name);
|
|
373
|
+
try {
|
|
374
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
375
|
+
return candidate;
|
|
376
|
+
} catch (_error) {
|
|
377
|
+
// try next PATH entry
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
return null;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function ensurePython3Resolvable(pathEnv) {
|
|
384
|
+
// Linux-first D-2a contract: python3 must be present. Do not auto-guess
|
|
385
|
+
// python/py/venv fallbacks; missing python3 fails closed.
|
|
386
|
+
if (!resolveExecutable("python3", pathEnv)) {
|
|
387
|
+
throw new ValidationError("FAIL_EXECUTE_UNSUPPORTED_PLATFORM: python3 is not resolvable on PATH; Phase D R1 is Linux-first.");
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function buildRunAllowlist(roleCommands, opts) {
|
|
392
|
+
const options = opts || {};
|
|
393
|
+
const mapped = [];
|
|
394
|
+
for (const command of asArray(roleCommands)) {
|
|
395
|
+
const argv = normalizeVerificationCommand(command);
|
|
396
|
+
if (argv) mapped.push(argv);
|
|
397
|
+
}
|
|
398
|
+
const unique = [];
|
|
399
|
+
for (const argv of mapped) {
|
|
400
|
+
if (!unique.some((existing) => sameArgv(existing, argv))) {
|
|
401
|
+
unique.push(argv);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
if (unique.length === 0) {
|
|
405
|
+
throw new ValidationError("FAIL_NO_ALLOWED_COMMANDS: no role verification command matches the Phase D R1 docs allowlist.");
|
|
406
|
+
}
|
|
407
|
+
if (unique.some((argv) => argv[0] === "python3")) {
|
|
408
|
+
ensurePython3Resolvable(options.pathEnv);
|
|
409
|
+
}
|
|
410
|
+
return unique;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
function runAllowedCommand(argv, opts) {
|
|
414
|
+
const isAllowed = sameArgv(argv, A1_ARGV) || sameArgv(argv, A2_ARGV);
|
|
415
|
+
if (!isAllowed) {
|
|
416
|
+
throw new ValidationError("unknown_risk_stop: command is not on the Phase D R1 allowlist");
|
|
417
|
+
}
|
|
418
|
+
return runControlledProcess(argv, opts || {});
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
function createWorktree(projectPath, key, runId) {
|
|
422
|
+
const safeKey = safeSegment(key, "feature_key");
|
|
423
|
+
const safeRunId = safeSegment(runId, "run_id");
|
|
424
|
+
const worktreeRoot = resolveWorktreeRoot(projectPath, safeRunId);
|
|
425
|
+
const branch = `${EXECUTE_BRANCH_PREFIX}/${safeKey}/${safeRunId}`;
|
|
426
|
+
runGit(["worktree", "add", worktreeRoot, "-b", branch, "HEAD"], {
|
|
427
|
+
cwd: path.resolve(projectPath || "."),
|
|
428
|
+
timeoutMs: COMMAND_TIMEOUT_MS,
|
|
429
|
+
});
|
|
430
|
+
return { worktreeRoot, branch };
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function cleanupWorktree(projectPath, worktreeRoot, branch) {
|
|
434
|
+
const cwd = path.resolve(projectPath || ".");
|
|
435
|
+
try {
|
|
436
|
+
runGit(["worktree", "remove", "--force", worktreeRoot], { cwd, timeoutMs: COMMAND_TIMEOUT_MS });
|
|
437
|
+
} catch (_error) {
|
|
438
|
+
// Cleanup must be idempotent; a missing or half-created worktree is handled by rmSync below.
|
|
439
|
+
}
|
|
440
|
+
try {
|
|
441
|
+
runGit(["branch", "-D", branch], { cwd, timeoutMs: COMMAND_TIMEOUT_MS });
|
|
442
|
+
} catch (_error) {
|
|
443
|
+
// Branch may not exist if worktree creation failed before branch creation.
|
|
444
|
+
}
|
|
445
|
+
fs.rmSync(worktreeRoot, { recursive: true, force: true });
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
function withAbortCleanup(ctx, fn) {
|
|
449
|
+
let keepForReview = false;
|
|
450
|
+
let created = null;
|
|
451
|
+
try {
|
|
452
|
+
created = createWorktree(ctx.projectPath, ctx.featureKey, ctx.runId);
|
|
453
|
+
const result = fn(created);
|
|
454
|
+
keepForReview = Boolean(result && result.keepForReview);
|
|
455
|
+
return result;
|
|
456
|
+
} finally {
|
|
457
|
+
if (!keepForReview && created) {
|
|
458
|
+
cleanupWorktree(ctx.projectPath, created.worktreeRoot, created.branch);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
function activeStopConditionIds(plan) {
|
|
465
|
+
const ids = asArray(plan && plan.stop_conditions)
|
|
466
|
+
.map((condition) => {
|
|
467
|
+
if (condition && typeof condition === "object") return condition.id;
|
|
468
|
+
return condition;
|
|
469
|
+
})
|
|
470
|
+
.filter((id) => typeof id === "string" && id.length > 0);
|
|
471
|
+
return ids.length > 0 ? ids : STOP_CONDITION_IDS;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function stopConditionActive(ctx, id) {
|
|
475
|
+
return asArray(ctx && ctx.stopConditions).includes(id);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function enforceKnownStopCondition(ctx, id, reason) {
|
|
479
|
+
if (!STOP_CONDITION_IDS.includes(id)) {
|
|
480
|
+
return stop("unknown_risk_stop", `unrecognized stop condition: ${id}`);
|
|
481
|
+
}
|
|
482
|
+
if (!stopConditionActive(ctx, id)) {
|
|
483
|
+
return stop("unknown_risk_stop", `${id} is not active in the execution plan`);
|
|
484
|
+
}
|
|
485
|
+
return stop(id, reason);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
function commandLooksLikeDeploy(argv) {
|
|
489
|
+
const joined = asArray(argv).map((token) => String(token).toLowerCase()).join(" ");
|
|
490
|
+
return /(^|\s)(deploy|release|publish|terraform|kubectl|vercel|flyctl|railway)(\s|$)/.test(joined);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
function actionNeedsTestEvidence(action) {
|
|
494
|
+
if (!action || typeof action !== "object") return false;
|
|
495
|
+
if (action.requires_test_evidence === true) return true;
|
|
496
|
+
const kind = String(action.kind || action.type || "").toLowerCase();
|
|
497
|
+
return kind === "verification" || kind === "test";
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function enforcePerActionStopConditions(ctx, action, state) {
|
|
501
|
+
const status = state || {};
|
|
502
|
+
const nextActionCount = Number(status.actionsExecuted || 0) + 1;
|
|
503
|
+
const actionCap = Number(ctx && ctx.actionCap || ACTION_CAP_DEFAULT);
|
|
504
|
+
if (nextActionCount > actionCap) {
|
|
505
|
+
return enforceKnownStopCondition(ctx, "action_count_cap", `action cap exceeded: ${nextActionCount} > ${actionCap}`);
|
|
506
|
+
}
|
|
507
|
+
if (!action || typeof action !== "object") {
|
|
508
|
+
return enforceKnownStopCondition(ctx, "unknown_risk_stop", "action is missing or not evaluable");
|
|
509
|
+
}
|
|
510
|
+
if (commandLooksLikeDeploy(action.argv || action.command)) {
|
|
511
|
+
return enforceKnownStopCondition(ctx, "deploy_confirm", "deployment-shaped command requires controller confirmation");
|
|
512
|
+
}
|
|
513
|
+
if (actionNeedsTestEvidence(action) && action.test_evidence_present !== true) {
|
|
514
|
+
return enforceKnownStopCondition(ctx, "test_evidence_required", "verification action lacks test evidence marker");
|
|
515
|
+
}
|
|
516
|
+
if (Number(status.failedAttempts || 0) >= 3) {
|
|
517
|
+
return enforceKnownStopCondition(ctx, "three_fix_escalation", "three failed attempts reached for the same failure");
|
|
518
|
+
}
|
|
519
|
+
return null;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function executeAction(ctx, action, state) {
|
|
523
|
+
const blocked = enforcePerActionStopConditions(ctx, action, state);
|
|
524
|
+
if (blocked) return { blocked };
|
|
525
|
+
if (!Array.isArray(action.argv)) {
|
|
526
|
+
return { blocked: enforceKnownStopCondition(ctx, "unknown_risk_stop", "action argv is missing") };
|
|
527
|
+
}
|
|
528
|
+
const result = runAllowedCommand(action.argv, {
|
|
529
|
+
cwd: action.cwd,
|
|
530
|
+
timeoutMs: action.timeoutMs || COMMAND_TIMEOUT_MS,
|
|
531
|
+
env: action.env,
|
|
532
|
+
});
|
|
533
|
+
return { result };
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
|
|
537
|
+
function stopConditionFromError(error) {
|
|
538
|
+
const message = error && error.message ? String(error.message) : String(error || "unknown error");
|
|
539
|
+
for (const id of STOP_CONDITION_IDS) {
|
|
540
|
+
if (message.includes(id)) return id;
|
|
541
|
+
}
|
|
542
|
+
if (message.includes("FAIL_NO_ALLOWED_COMMANDS")) return "unknown_risk_stop";
|
|
543
|
+
if (message.includes("FAIL_EXECUTE_UNSUPPORTED_PLATFORM")) return "unknown_risk_stop";
|
|
544
|
+
return "unknown_risk_stop";
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function targetPaths(summary) {
|
|
548
|
+
return asArray(summary && summary.targets).map((target) => target.newPath || target.oldPath).filter(Boolean);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function evidenceTempDir(projectPath, featureKey) {
|
|
552
|
+
const safeFeatureKey = safeSegment(featureKey, "feature_key");
|
|
553
|
+
const base = path.resolve(projectPath || ".", ".sdtk", "agent-team", "tmp", safeFeatureKey);
|
|
554
|
+
fs.mkdirSync(base, { recursive: true });
|
|
555
|
+
return base;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
function buildExecuteEvidence(ctx, data) {
|
|
559
|
+
const info = data || {};
|
|
560
|
+
const stopConditionHit = info.stop_condition_hit === undefined ? null : info.stop_condition_hit;
|
|
561
|
+
const commandsRun = asArray(info.commands_run);
|
|
562
|
+
const blockers = asArray(info.blockers);
|
|
563
|
+
const filesTouched = asArray(info.files_touched);
|
|
564
|
+
const verificationEvidence = info.verification_evidence ||
|
|
565
|
+
(commandsRun.length > 0 ? commandsRun.map((command) => `${command}: recorded`).join("; ") : "no verification commands were run");
|
|
566
|
+
return {
|
|
567
|
+
schema_version: EXECUTE_EVIDENCE_SCHEMA,
|
|
568
|
+
feature_key: ctx.featureKey,
|
|
569
|
+
role: String(ctx.role.role || "dev").toLowerCase(),
|
|
570
|
+
run_id: ctx.runId,
|
|
571
|
+
submitted_at: new Date().toISOString(),
|
|
572
|
+
summary: info.summary || (stopConditionHit ? `Execution stopped: ${stopConditionHit}` : "Bounded docs-only execute completed."),
|
|
573
|
+
commands_run: commandsRun,
|
|
574
|
+
verification_evidence: verificationEvidence,
|
|
575
|
+
blockers,
|
|
576
|
+
stop_condition_hit: stopConditionHit,
|
|
577
|
+
files_touched: filesTouched,
|
|
578
|
+
evidence: {
|
|
579
|
+
code_diff: info.code_diff || `Applied supplied patch to worktree ${ctx.worktreeRoot}.`,
|
|
580
|
+
test_evidence: verificationEvidence,
|
|
581
|
+
},
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function writeAndSubmitExecuteEvidence(ctx, evidenceJson) {
|
|
586
|
+
const dir = evidenceTempDir(ctx.projectPath, ctx.featureKey);
|
|
587
|
+
const evidencePath = path.join(dir, `${ctx.runId}-${String(ctx.role.role || "dev").toLowerCase()}-execute.json`);
|
|
588
|
+
fs.writeFileSync(evidencePath, JSON.stringify(evidenceJson, null, 2), "utf8");
|
|
589
|
+
try {
|
|
590
|
+
return submitEvidence(ctx.projectPath, ctx.featureKey, String(ctx.role.role || "dev").toLowerCase(), evidencePath);
|
|
591
|
+
} finally {
|
|
592
|
+
fs.rmSync(evidencePath, { force: true });
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
function writeReadinessAndReport(ctx) {
|
|
597
|
+
const readiness = computeReadiness(ctx.projectPath, ctx.featureKey);
|
|
598
|
+
const readinessPath = writeReadiness(ctx.projectPath, ctx.featureKey, readiness);
|
|
599
|
+
const built = buildMorningReport(ctx.projectPath, ctx.featureKey);
|
|
600
|
+
const reportPath = writeReport(ctx.projectPath, ctx.featureKey, built.markdown);
|
|
601
|
+
return { readiness, readinessPath, reportPath };
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
function commandLiteral(argv) {
|
|
605
|
+
return asArray(argv).map((token) => String(token)).join(" ");
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function runVerificationCommands(ctx, allowlist) {
|
|
609
|
+
const commandResults = [];
|
|
610
|
+
let actionsExecuted = 0;
|
|
611
|
+
for (const argv of allowlist) {
|
|
612
|
+
const action = {
|
|
613
|
+
kind: "verification",
|
|
614
|
+
argv,
|
|
615
|
+
cwd: ctx.worktreeRoot,
|
|
616
|
+
timeoutMs: COMMAND_TIMEOUT_MS,
|
|
617
|
+
test_evidence_present: true,
|
|
618
|
+
};
|
|
619
|
+
const executed = executeAction(ctx, action, { actionsExecuted });
|
|
620
|
+
if (executed.blocked) {
|
|
621
|
+
return { stop: executed.blocked, commandResults, actionsExecuted };
|
|
622
|
+
}
|
|
623
|
+
actionsExecuted += 1;
|
|
624
|
+
const result = executed.result;
|
|
625
|
+
commandResults.push({ argv, result });
|
|
626
|
+
if (!result || result.exitCode !== 0) {
|
|
627
|
+
return {
|
|
628
|
+
stop: stop("unknown_risk_stop", `${commandLiteral(argv)} failed with exit ${result ? result.exitCode : "unknown"}`),
|
|
629
|
+
commandResults,
|
|
630
|
+
actionsExecuted,
|
|
631
|
+
};
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
return { stop: null, commandResults, actionsExecuted };
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
function dryRunExecute(projectPath, featureKey, opts) {
|
|
638
|
+
const options = opts || {};
|
|
639
|
+
const ctx = loadExecuteContext(projectPath, featureKey);
|
|
640
|
+
const patchSummary = readPatchSummary(options.patchFile);
|
|
641
|
+
const patchStop = guardPatchTargets(patchSummary, ctx.worktreeRoot, ctx.allowedFileScopes);
|
|
642
|
+
const allowlist = buildRunAllowlist(ctx.verificationCommands, options);
|
|
643
|
+
const stdout = renderDryRunPlan(ctx, patchSummary, allowlist) +
|
|
644
|
+
(patchStop ? `\n would_stop: ${patchStop.stop_condition_hit} — ${patchStop.reason}` : "");
|
|
645
|
+
return {
|
|
646
|
+
exitCode: 0,
|
|
647
|
+
status: patchStop ? "WOULD_STOP" : "PLANNED",
|
|
648
|
+
feature_key: ctx.featureKey,
|
|
649
|
+
run_id: ctx.runId,
|
|
650
|
+
execution_mode: "dry-run",
|
|
651
|
+
workflow_type: ctx.workflowType,
|
|
652
|
+
worktree_path: ctx.worktreeRoot,
|
|
653
|
+
branch: ctx.branch,
|
|
654
|
+
actions_executed: 0,
|
|
655
|
+
stop_condition_hit: patchStop ? patchStop.stop_condition_hit : null,
|
|
656
|
+
stdout,
|
|
657
|
+
cleanup_command: plannedCleanupCommand(ctx),
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
function executeWithWorktree(projectPath, featureKey, opts) {
|
|
662
|
+
const options = opts || {};
|
|
663
|
+
const ctx = loadExecuteContext(projectPath, featureKey);
|
|
664
|
+
const allowlist = buildRunAllowlist(ctx.verificationCommands, options);
|
|
665
|
+
const patchSummary = readPatchSummary(options.patchFile);
|
|
666
|
+
return withAbortCleanup(ctx, () => {
|
|
667
|
+
let actionsExecuted = 0;
|
|
668
|
+
let stopHit = null;
|
|
669
|
+
let stopReason = null;
|
|
670
|
+
let evidenceResult = null;
|
|
671
|
+
let readinessBundle = null;
|
|
672
|
+
let keepForReview = false;
|
|
673
|
+
let patchApplied = false;
|
|
674
|
+
|
|
675
|
+
const patchStop = guardPatchTargets(patchSummary, ctx.worktreeRoot, ctx.allowedFileScopes);
|
|
676
|
+
if (patchStop) {
|
|
677
|
+
stopHit = patchStop.stop_condition_hit;
|
|
678
|
+
stopReason = patchStop.reason;
|
|
679
|
+
} else {
|
|
680
|
+
try {
|
|
681
|
+
applyPatch(ctx.worktreeRoot, options.patchFile);
|
|
682
|
+
patchApplied = true;
|
|
683
|
+
const verification = runVerificationCommands(ctx, allowlist);
|
|
684
|
+
actionsExecuted = verification.actionsExecuted;
|
|
685
|
+
if (verification.stop) {
|
|
686
|
+
stopHit = verification.stop.stop_condition_hit;
|
|
687
|
+
stopReason = verification.stop.reason;
|
|
688
|
+
}
|
|
689
|
+
const commandsRun = verification.commandResults.map((entry) => commandLiteral(entry.argv));
|
|
690
|
+
const evidenceJson = buildExecuteEvidence(ctx, {
|
|
691
|
+
stop_condition_hit: stopHit,
|
|
692
|
+
summary: stopHit ? `Execution stopped: ${stopHit}` : "Applied supplied docs patch and completed allowed verification commands.",
|
|
693
|
+
commands_run: commandsRun,
|
|
694
|
+
verification_evidence: verification.commandResults.map((entry) => `${commandLiteral(entry.argv)} exit=${entry.result.exitCode}`).join("; ") || "no commands run",
|
|
695
|
+
blockers: stopHit ? [stopReason || stopHit] : [],
|
|
696
|
+
files_touched: targetPaths(patchSummary),
|
|
697
|
+
code_diff: `Applied supplied patch to worktree ${ctx.worktreeRoot}.`,
|
|
698
|
+
});
|
|
699
|
+
evidenceResult = writeAndSubmitExecuteEvidence(ctx, evidenceJson);
|
|
700
|
+
readinessBundle = writeReadinessAndReport(ctx);
|
|
701
|
+
keepForReview = !stopHit;
|
|
702
|
+
return {
|
|
703
|
+
keepForReview,
|
|
704
|
+
exitCode: stopHit ? 1 : 0,
|
|
705
|
+
status: stopHit ? "NOT_READY" : "READY_TO_REVIEW",
|
|
706
|
+
feature_key: ctx.featureKey,
|
|
707
|
+
run_id: ctx.runId,
|
|
708
|
+
execution_mode: "execute",
|
|
709
|
+
workflow_type: ctx.workflowType,
|
|
710
|
+
worktree_path: ctx.worktreeRoot,
|
|
711
|
+
branch: ctx.branch,
|
|
712
|
+
actions_executed: actionsExecuted,
|
|
713
|
+
stop_condition_hit: stopHit,
|
|
714
|
+
stop_reason: stopReason,
|
|
715
|
+
evidence_path: evidenceResult ? evidenceResult.outputPath : null,
|
|
716
|
+
readiness_path: readinessBundle ? readinessBundle.readinessPath : null,
|
|
717
|
+
readiness_verdict: readinessBundle ? readinessBundle.readiness.overall_verdict : null,
|
|
718
|
+
report_path: readinessBundle ? readinessBundle.reportPath : null,
|
|
719
|
+
cleanup_command: plannedCleanupCommand(ctx),
|
|
720
|
+
stdout: [
|
|
721
|
+
`Agent Team Execute: ${stopHit ? "STOPPED" : "COMPLETED"}`,
|
|
722
|
+
` feature_key: ${ctx.featureKey}`,
|
|
723
|
+
` run_id: ${ctx.runId}`,
|
|
724
|
+
` worktree: ${ctx.worktreeRoot}`,
|
|
725
|
+
` actions: ${actionsExecuted}`,
|
|
726
|
+
` stop: ${stopHit || "none"}`,
|
|
727
|
+
stopHit ? " cleanup: completed" : ` cleanup command: ${plannedCleanupCommand(ctx)}`,
|
|
728
|
+
].join("\n"),
|
|
729
|
+
};
|
|
730
|
+
} catch (error) {
|
|
731
|
+
stopHit = stopConditionFromError(error);
|
|
732
|
+
stopReason = error && error.message ? error.message : String(error || stopHit);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
const evidenceJson = buildExecuteEvidence(ctx, {
|
|
737
|
+
stop_condition_hit: stopHit,
|
|
738
|
+
summary: `Execution stopped: ${stopHit || "unknown_risk_stop"}`,
|
|
739
|
+
commands_run: [],
|
|
740
|
+
verification_evidence: "execution stopped before allowed verification completed",
|
|
741
|
+
blockers: [stopReason || stopHit || "unknown_risk_stop"],
|
|
742
|
+
files_touched: targetPaths(patchSummary),
|
|
743
|
+
code_diff: patchApplied
|
|
744
|
+
? `Applied supplied patch to worktree ${ctx.worktreeRoot}.`
|
|
745
|
+
: `no patch applied — stopped at ${stopHit || "unknown_risk_stop"}`,
|
|
746
|
+
});
|
|
747
|
+
try {
|
|
748
|
+
evidenceResult = writeAndSubmitExecuteEvidence(ctx, evidenceJson);
|
|
749
|
+
readinessBundle = writeReadinessAndReport(ctx);
|
|
750
|
+
} catch (error) {
|
|
751
|
+
stopHit = stopConditionFromError(error);
|
|
752
|
+
stopReason = error && error.message ? error.message : String(error || stopHit);
|
|
753
|
+
}
|
|
754
|
+
return {
|
|
755
|
+
keepForReview: false,
|
|
756
|
+
exitCode: 1,
|
|
757
|
+
status: "NOT_READY",
|
|
758
|
+
feature_key: ctx.featureKey,
|
|
759
|
+
run_id: ctx.runId,
|
|
760
|
+
execution_mode: "execute",
|
|
761
|
+
workflow_type: ctx.workflowType,
|
|
762
|
+
worktree_path: ctx.worktreeRoot,
|
|
763
|
+
branch: ctx.branch,
|
|
764
|
+
actions_executed: actionsExecuted,
|
|
765
|
+
stop_condition_hit: stopHit || "unknown_risk_stop",
|
|
766
|
+
stop_reason: stopReason,
|
|
767
|
+
evidence_path: evidenceResult ? evidenceResult.outputPath : null,
|
|
768
|
+
readiness_path: readinessBundle ? readinessBundle.readinessPath : null,
|
|
769
|
+
readiness_verdict: readinessBundle ? readinessBundle.readiness.overall_verdict : null,
|
|
770
|
+
report_path: readinessBundle ? readinessBundle.reportPath : null,
|
|
771
|
+
cleanup_command: null,
|
|
772
|
+
stdout: [
|
|
773
|
+
"Agent Team Execute: STOPPED",
|
|
774
|
+
` feature_key: ${ctx.featureKey}`,
|
|
775
|
+
` run_id: ${ctx.runId}`,
|
|
776
|
+
` worktree: ${ctx.worktreeRoot}`,
|
|
777
|
+
` actions: ${actionsExecuted}`,
|
|
778
|
+
` stop: ${stopHit || "unknown_risk_stop"}`,
|
|
779
|
+
" cleanup: completed",
|
|
780
|
+
].join("\n"),
|
|
781
|
+
};
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
function runExecute(projectPath, featureKey, opts) {
|
|
786
|
+
const options = opts || {};
|
|
787
|
+
if (!options.patchFile) {
|
|
788
|
+
throw new ValidationError("FAIL_EXECUTE_PATCH_REQUIRED: --patch-file is required for Phase D R1 Flow B.");
|
|
789
|
+
}
|
|
790
|
+
if (options.mode === "execute") {
|
|
791
|
+
return executeWithWorktree(projectPath, featureKey, options);
|
|
792
|
+
}
|
|
793
|
+
return dryRunExecute(projectPath, featureKey, options);
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
|
|
797
|
+
async function confirmExecute(input, featureKey, runId) {
|
|
798
|
+
const source = input || {};
|
|
799
|
+
const expected = `EXECUTE ${safeSegment(featureKey, "feature_key")} ${safeSegment(runId, "run_id")}`;
|
|
800
|
+
if (source.isTTY !== true) {
|
|
801
|
+
throw new ValidationError("FAIL_EXECUTE_REQUIRES_TTY: --execute requires an interactive TTY confirmation.");
|
|
802
|
+
}
|
|
803
|
+
if (typeof source.readLine !== "function") {
|
|
804
|
+
throw new ValidationError("FAIL_EXECUTE_REQUIRES_TTY: confirmation reader is not available.");
|
|
805
|
+
}
|
|
806
|
+
const answer = await source.readLine(`Type ${expected} to continue: `);
|
|
807
|
+
if (String(answer || "") !== expected) {
|
|
808
|
+
throw new ValidationError("FAIL_EXECUTE_CONFIRMATION_MISMATCH: exact execute confirmation phrase was not provided.");
|
|
809
|
+
}
|
|
810
|
+
return { confirmed: true, phrase: expected };
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
function plannedCleanupCommand(ctx) {
|
|
814
|
+
return `git worktree remove --force ${ctx.worktreeRoot} && git branch -D ${ctx.branch}`;
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
function renderDryRunPlan(ctx, patchSummary, allowlist) {
|
|
818
|
+
return [
|
|
819
|
+
`Agent Team Execute Plan: ${ctx.featureKey}`,
|
|
820
|
+
` mode: dry-run`,
|
|
821
|
+
` workflow: ${ctx.workflowType}`,
|
|
822
|
+
` run_id: ${ctx.runId}`,
|
|
823
|
+
` role: ${ctx.role.role}`,
|
|
824
|
+
` worktree: ${ctx.worktreeRoot}`,
|
|
825
|
+
` branch: ${ctx.branch}`,
|
|
826
|
+
` patch_files: ${patchSummary ? patchSummary.file_count : 0}`,
|
|
827
|
+
` patch_lines: ${patchSummary ? patchSummary.changed_lines : 0}`,
|
|
828
|
+
` allowlist: ${allowlist.map((argv) => argv.join(" ")).join("; ") || "(none)"}`,
|
|
829
|
+
` allowed scope: ${ctx.allowedFileScopes.join(", ")}`,
|
|
830
|
+
` stop: ${ctx.stopConditions.join(", ")}`,
|
|
831
|
+
` action cap: ${ctx.actionCap}`,
|
|
832
|
+
" dry-run only — no worktree is created, no patch is applied, and no command is run.",
|
|
833
|
+
].join("\n");
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
module.exports = {
|
|
837
|
+
WORKFLOW_TYPES,
|
|
838
|
+
ACTION_CAP_DEFAULT,
|
|
839
|
+
COMMAND_TIMEOUT_MS,
|
|
840
|
+
PATCH_MAX_FILES,
|
|
841
|
+
PATCH_MAX_LINES,
|
|
842
|
+
EXECUTE_EVIDENCE_SCHEMA,
|
|
843
|
+
A1_LITERAL,
|
|
844
|
+
A2_LITERAL,
|
|
845
|
+
A1_ARGV,
|
|
846
|
+
A2_ARGV,
|
|
847
|
+
ALLOWED_COMMANDS,
|
|
848
|
+
STOP_CONDITION_IDS,
|
|
849
|
+
asArray,
|
|
850
|
+
assertPathUnderBase,
|
|
851
|
+
worktreesBaseDir,
|
|
852
|
+
resolveWorktreeRoot,
|
|
853
|
+
loadExecuteContext,
|
|
854
|
+
plannedCleanupCommand,
|
|
855
|
+
renderDryRunPlan,
|
|
856
|
+
rejectShellMetacharacters,
|
|
857
|
+
networkMutationReason,
|
|
858
|
+
runControlledProcess,
|
|
859
|
+
runGit,
|
|
860
|
+
normalizeVerificationCommand,
|
|
861
|
+
resolveExecutable,
|
|
862
|
+
ensurePython3Resolvable,
|
|
863
|
+
buildRunAllowlist,
|
|
864
|
+
runAllowedCommand,
|
|
865
|
+
stripPatchPrefix,
|
|
866
|
+
changedLineCount,
|
|
867
|
+
extractPatchTargets,
|
|
868
|
+
guardPatchTargets,
|
|
869
|
+
readPatchSummary,
|
|
870
|
+
applyPatch,
|
|
871
|
+
createWorktree,
|
|
872
|
+
cleanupWorktree,
|
|
873
|
+
withAbortCleanup,
|
|
874
|
+
activeStopConditionIds,
|
|
875
|
+
stopConditionActive,
|
|
876
|
+
enforceKnownStopCondition,
|
|
877
|
+
commandLooksLikeDeploy,
|
|
878
|
+
actionNeedsTestEvidence,
|
|
879
|
+
enforcePerActionStopConditions,
|
|
880
|
+
executeAction,
|
|
881
|
+
stopConditionFromError,
|
|
882
|
+
targetPaths,
|
|
883
|
+
buildExecuteEvidence,
|
|
884
|
+
writeAndSubmitExecuteEvidence,
|
|
885
|
+
writeReadinessAndReport,
|
|
886
|
+
commandLiteral,
|
|
887
|
+
runVerificationCommands,
|
|
888
|
+
dryRunExecute,
|
|
889
|
+
executeWithWorktree,
|
|
890
|
+
runExecute,
|
|
891
|
+
confirmExecute,
|
|
892
|
+
};
|