sdtk-code-kit 0.3.0 → 0.3.1

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 (56) hide show
  1. package/README.md +204 -204
  2. package/assets/manifest/toolkit-bundle.manifest.json +147 -147
  3. package/assets/manifest/toolkit-bundle.sha256.txt +5 -5
  4. package/bin/sdtk-code.js +14 -14
  5. package/package.json +44 -44
  6. package/src/commands/agent-team.js +425 -174
  7. package/src/commands/build.js +53 -53
  8. package/src/commands/doctor.js +51 -51
  9. package/src/commands/generate.js +11 -11
  10. package/src/commands/guardrails.js +215 -215
  11. package/src/commands/help.js +264 -257
  12. package/src/commands/init.js +98 -98
  13. package/src/commands/plan.js +53 -53
  14. package/src/commands/readiness.js +77 -77
  15. package/src/commands/resume.js +61 -61
  16. package/src/commands/runtime.js +224 -224
  17. package/src/commands/ship.js +59 -59
  18. package/src/commands/sleep.js +132 -132
  19. package/src/commands/start.js +89 -89
  20. package/src/commands/status.js +77 -77
  21. package/src/commands/update.js +11 -11
  22. package/src/commands/verify.js +71 -71
  23. package/src/index.js +112 -112
  24. package/src/lib/agent-team-author.js +521 -0
  25. package/src/lib/agent-team-evidence.js +302 -0
  26. package/src/lib/agent-team-execute.js +892 -0
  27. package/src/lib/agent-team-export.js +411 -409
  28. package/src/lib/agent-team-plan.js +514 -514
  29. package/src/lib/agent-team-readiness.js +161 -0
  30. package/src/lib/agent-team-report.js +165 -0
  31. package/src/lib/args.js +107 -107
  32. package/src/lib/errors.js +41 -41
  33. package/src/lib/model-provider.js +219 -0
  34. package/src/lib/powershell.js +65 -65
  35. package/src/lib/project-target-guard.js +53 -53
  36. package/src/lib/scope.js +72 -72
  37. package/src/lib/ship-readiness.js +281 -281
  38. package/src/lib/sleep-plan.js +175 -175
  39. package/src/lib/sleep-report.js +229 -229
  40. package/src/lib/toolkit-payload.js +72 -72
  41. package/src/lib/trust-events.js +252 -185
  42. package/src/lib/trust-file-scope.js +154 -154
  43. package/src/lib/trust-policy.js +212 -212
  44. package/src/lib/trust-redact.js +58 -35
  45. package/src/lib/trust-trace.js +179 -179
  46. package/src/lib/update.js +344 -344
  47. package/src/lib/workflow-artifact.js +503 -503
  48. package/src/lib/workflow-build.js +127 -127
  49. package/src/lib/workflow-doctor.js +83 -83
  50. package/src/lib/workflow-handoff.js +1029 -1029
  51. package/src/lib/workflow-intake.js +101 -101
  52. package/src/lib/workflow-plan.js +193 -193
  53. package/src/lib/workflow-review-packet.js +650 -650
  54. package/src/lib/workflow-ship.js +213 -213
  55. package/src/lib/workflow-state.js +438 -438
  56. package/src/lib/workflow-verify.js +393 -393
@@ -0,0 +1,521 @@
1
+ "use strict";
2
+
3
+ const crypto = require("crypto");
4
+ const fs = require("fs");
5
+ const path = require("path");
6
+ const { ValidationError } = require("./errors");
7
+ const { redact, containsSecretMaterial } = require("./trust-redact");
8
+ const {
9
+ MODEL_MAX_CALLS_PER_RUN,
10
+ MODEL_WALLCLOCK_TIMEOUT_MS,
11
+ MODEL_MAX_OUTPUT_TOKENS,
12
+ CONTEXT_MAX_FILES,
13
+ CONTEXT_MAX_BYTES,
14
+ MODEL_ID,
15
+ MODEL_MAX_COST_USD,
16
+ estimateTokensFromText,
17
+ assertCostWithinCap,
18
+ callModelProvider,
19
+ } = require("./model-provider");
20
+ const {
21
+ loadExecuteContext,
22
+ runControlledProcess,
23
+ buildRunAllowlist,
24
+ readPatchSummary,
25
+ guardPatchTargets,
26
+ applyPatch,
27
+ createWorktree,
28
+ cleanupWorktree,
29
+ buildExecuteEvidence,
30
+ writeAndSubmitExecuteEvidence,
31
+ writeReadinessAndReport,
32
+ runVerificationCommands,
33
+ commandLiteral,
34
+ targetPaths,
35
+ stopConditionFromError,
36
+ plannedCleanupCommand,
37
+ confirmExecute,
38
+ } = require("./agent-team-execute");
39
+
40
+ const GIT_LS_FILES_ARGV = Object.freeze(["git", "ls-files", "-z"]);
41
+ const AUTHOR_PATCH_NAME = "model-produced.patch";
42
+
43
+ function asArray(value) {
44
+ return Array.isArray(value) ? value : [];
45
+ }
46
+
47
+ function sha256(value) {
48
+ return crypto.createHash("sha256").update(String(value || "")).digest("hex");
49
+ }
50
+
51
+ function normalizeRelPath(value) {
52
+ return String(value || "").replace(/\\/g, "/").replace(/^\.\//, "");
53
+ }
54
+
55
+ function globToRegex(scope) {
56
+ const escaped = String(scope).replace(/[.+^${}()|[\]\\]/g, "\\$&")
57
+ .replace(/\*\*/g, "::DOUBLE_STAR::")
58
+ .replace(/\*/g, "[^/]*")
59
+ .replace(/::DOUBLE_STAR::/g, ".*");
60
+ return new RegExp(`^${escaped}$`);
61
+ }
62
+
63
+ function matchesScope(targetPath, scope) {
64
+ const normalized = normalizeRelPath(targetPath);
65
+ const normalizedScope = normalizeRelPath(scope);
66
+ if (normalizedScope === "**" || normalizedScope === "**/*") return true;
67
+ if (normalizedScope.endsWith("/**")) {
68
+ const prefix = normalizedScope.slice(0, -3);
69
+ return normalized === prefix || normalized.startsWith(`${prefix}/`);
70
+ }
71
+ if (normalizedScope.includes("*")) {
72
+ return globToRegex(normalizedScope).test(normalized);
73
+ }
74
+ return normalized === normalizedScope;
75
+ }
76
+
77
+ function scopeIsWholeRepo(scope) {
78
+ const normalized = normalizeRelPath(scope);
79
+ return normalized === "**" || normalized === "**/*" || normalized === "./**";
80
+ }
81
+
82
+ function inAllowedScopes(targetPath, allowedScopes) {
83
+ return asArray(allowedScopes).some((scope) => matchesScope(targetPath, scope));
84
+ }
85
+
86
+ function isDenyListedRelPath(relPath) {
87
+ const normalized = normalizeRelPath(relPath);
88
+ return normalized === ".env" ||
89
+ normalized.startsWith(".env.") ||
90
+ normalized.startsWith(".sdtk/") ||
91
+ normalized.startsWith("secrets/") ||
92
+ normalized.startsWith(".codex/") ||
93
+ normalized.startsWith(".claude/") ||
94
+ normalized.startsWith(".git/");
95
+ }
96
+
97
+ function assertInsideBase(candidate, base) {
98
+ const resolved = path.resolve(candidate);
99
+ const root = path.resolve(base);
100
+ if (resolved !== root && !resolved.startsWith(root + path.sep)) {
101
+ throw new ValidationError("FAIL_CONTEXT_EMPTY: context candidate escapes worktree root");
102
+ }
103
+ return resolved;
104
+ }
105
+
106
+ function listTrackedFiles(worktreeRoot, deps) {
107
+ const options = deps || {};
108
+ const runner = options.runControlledProcess || runControlledProcess;
109
+ const result = runner([...GIT_LS_FILES_ARGV], { cwd: worktreeRoot });
110
+ if (!result || result.exitCode !== 0) {
111
+ throw new ValidationError(`FAIL_CONTEXT_EMPTY: git ls-files failed: ${result ? result.stderr || result.stdout || "no output" : "no result"}`);
112
+ }
113
+ return String(result.stdout || "").split("\0").map(normalizeRelPath).filter(Boolean);
114
+ }
115
+
116
+ function taskPacketPath(projectPath, ctx) {
117
+ const roleName = String(ctx.role.role || "dev").toUpperCase();
118
+ const slug = String(ctx.role.task_slug || "IMPLEMENTATION");
119
+ return path.join(projectPath, ".sdtk", "agent-team", "tasks", ctx.featureKey, `${roleName}_${slug}.md`);
120
+ }
121
+
122
+ function readTaskPacket(projectPath, ctx) {
123
+ const packetPath = taskPacketPath(projectPath, ctx);
124
+ try {
125
+ return fs.readFileSync(packetPath, "utf8");
126
+ } catch (_error) {
127
+ return [
128
+ `# Agent Task Packet — ${ctx.featureKey} / ${ctx.role.role}`,
129
+ "",
130
+ ctx.role.objective || "Implement the approved bounded slice.",
131
+ "",
132
+ "## Allowed file scopes",
133
+ ...ctx.allowedFileScopes.map((scope) => `- ${scope}`),
134
+ ].join("\n");
135
+ }
136
+ }
137
+
138
+ function readCandidateSnapshot(base, relPath) {
139
+ const absolute = assertInsideBase(path.join(base, relPath), base);
140
+ const stat = fs.lstatSync(absolute);
141
+ if (!stat.isFile()) {
142
+ return null;
143
+ }
144
+ const real = fs.realpathSync(absolute);
145
+ assertInsideBase(real, base);
146
+ return fs.readFileSync(real, "utf8");
147
+ }
148
+
149
+ function buildPrompt(featureKey, role, packet, snapshots) {
150
+ const lines = [
151
+ "You are an author-only patch producer for SDTK Agent Team D-2b.",
152
+ "Return a single unified git patch and no prose.",
153
+ "Do not execute commands. Do not request tools. Do not include secrets.",
154
+ `Feature key: ${featureKey}`,
155
+ `Role: ${role.role}`,
156
+ "",
157
+ "## Task Packet",
158
+ packet,
159
+ "",
160
+ "## Context Snapshots",
161
+ ];
162
+ for (const snapshot of snapshots) {
163
+ lines.push(`\n### ${snapshot.path}\n`);
164
+ lines.push(snapshot.content);
165
+ }
166
+ return lines.join("\n");
167
+ }
168
+
169
+ function assembleContext(ctx, opts) {
170
+ const options = opts || {};
171
+ const base = path.resolve(options.worktreeRoot || ctx.worktreeRoot || ctx.projectPath);
172
+ const allowedScopes = asArray(ctx.allowedFileScopes || (ctx.role && ctx.role.allowed_file_scopes));
173
+ if (allowedScopes.length === 0 || allowedScopes.some(scopeIsWholeRepo)) {
174
+ throw new ValidationError("FAIL_CONTEXT_EMPTY: author context requires bounded allowed_file_scopes; whole-repo wildcard is denied");
175
+ }
176
+ const tracked = listTrackedFiles(base, options);
177
+ const snapshots = [];
178
+ let totalBytes = 0;
179
+ for (const relPath of tracked) {
180
+ if (isDenyListedRelPath(relPath)) continue;
181
+ if (!inAllowedScopes(relPath, allowedScopes)) continue;
182
+ let content;
183
+ try {
184
+ content = readCandidateSnapshot(base, relPath);
185
+ } catch (_error) {
186
+ continue;
187
+ }
188
+ if (content == null) continue;
189
+ const redactedContent = redact(content);
190
+ const size = Buffer.byteLength(redactedContent, "utf8");
191
+ totalBytes += size;
192
+ snapshots.push({
193
+ path: redact(relPath),
194
+ snapshot_sha256: sha256(redactedContent),
195
+ content: redactedContent,
196
+ bytes: size,
197
+ });
198
+ if (snapshots.length > CONTEXT_MAX_FILES || totalBytes > CONTEXT_MAX_BYTES) {
199
+ throw new ValidationError(`FAIL_CONTEXT_TOO_LARGE: context exceeds ceiling files=${snapshots.length}, bytes=${totalBytes}`);
200
+ }
201
+ }
202
+ if (snapshots.length === 0) {
203
+ throw new ValidationError("FAIL_CONTEXT_EMPTY: no tracked in-scope context files were available");
204
+ }
205
+ const packet = redact(readTaskPacket(ctx.projectPath, ctx));
206
+ const prompt = redact(buildPrompt(ctx.featureKey, ctx.role, packet, snapshots));
207
+ const promptSha = sha256(prompt);
208
+ const inputTokenEstimate = estimateTokensFromText(prompt);
209
+ const projectedCost = assertCostWithinCap(MODEL_ID, inputTokenEstimate, MODEL_MAX_OUTPUT_TOKENS);
210
+ return {
211
+ prompt,
212
+ prompt_sha256: promptSha,
213
+ context_manifest: snapshots.map((entry) => ({ path: entry.path, snapshot_sha256: entry.snapshot_sha256 })),
214
+ file_count: snapshots.length,
215
+ byte_count: totalBytes,
216
+ input_token_estimate: inputTokenEstimate,
217
+ projected_cost_usd: projectedCost,
218
+ model_id: MODEL_ID,
219
+ max_output_tokens: MODEL_MAX_OUTPUT_TOKENS,
220
+ model_max_cost_usd: MODEL_MAX_COST_USD,
221
+ };
222
+ }
223
+
224
+ function addedPatchContent(patchText) {
225
+ return String(patchText || "").split(/\r?\n/)
226
+ .filter((line) => line.startsWith("+") && !line.startsWith("+++"))
227
+ .map((line) => line.slice(1))
228
+ .join("\n");
229
+ }
230
+
231
+ function scanProducedPatchForSecrets(patchText) {
232
+ const added = addedPatchContent(patchText);
233
+ if (containsSecretMaterial(added)) {
234
+ return { stop_condition_hit: "secret_block", reason: "FAIL_PATCH_SECRET_CONTENT: model-produced patch adds secret-shaped content" };
235
+ }
236
+ return null;
237
+ }
238
+
239
+ function authorTempDir(projectPath, featureKey) {
240
+ const dir = path.join(path.resolve(projectPath || "."), ".sdtk", "agent-team", "tmp", featureKey, "author");
241
+ fs.mkdirSync(dir, { recursive: true });
242
+ return dir;
243
+ }
244
+
245
+ function writeProducedPatch(projectPath, featureKey, patchText) {
246
+ const out = path.join(authorTempDir(projectPath, featureKey), AUTHOR_PATCH_NAME);
247
+ fs.writeFileSync(out, String(patchText || ""), "utf8");
248
+ return out;
249
+ }
250
+
251
+ function renderDryRunAuthorPlan(ctx, context) {
252
+ return [
253
+ `Agent Team Author Plan: ${ctx.featureKey}`,
254
+ " mode: dry-run",
255
+ " network: disabled",
256
+ " credential: not required",
257
+ ` run_id: ${ctx.runId}`,
258
+ ` role: ${ctx.role.role}`,
259
+ ` model: ${context.model_id}`,
260
+ ` max_tokens: ${context.max_output_tokens}`,
261
+ ` projected_cost_usd: ${context.projected_cost_usd}`,
262
+ ` context_files: ${context.file_count}`,
263
+ ` context_bytes: ${context.byte_count}`,
264
+ ` prompt_sha256: ${context.prompt_sha256}`,
265
+ " context_manifest:",
266
+ ...context.context_manifest.map((entry) => ` - ${entry.path} ${entry.snapshot_sha256}`),
267
+ " dry-run only — no provider call, no API key lookup, no worktree mutation, no patch apply.",
268
+ ].join("\n");
269
+ }
270
+
271
+ function stopResult(ctx, data) {
272
+ const info = data || {};
273
+ return {
274
+ keepForReview: false,
275
+ exitCode: 1,
276
+ status: "NOT_READY",
277
+ feature_key: ctx.featureKey,
278
+ run_id: ctx.runId,
279
+ execution_mode: "execute",
280
+ workflow_type: ctx.workflowType,
281
+ worktree_path: ctx.worktreeRoot,
282
+ branch: ctx.branch,
283
+ actions_executed: Number(info.actions_executed || 0),
284
+ stop_condition_hit: info.stop_condition_hit || "unknown_risk_stop",
285
+ stop_reason: info.reason || info.stop_condition_hit || "unknown_risk_stop",
286
+ evidence_path: info.evidence_path || null,
287
+ readiness_path: info.readiness_path || null,
288
+ readiness_verdict: info.readiness_verdict || null,
289
+ report_path: info.report_path || null,
290
+ cleanup_command: null,
291
+ prompt_sha256: info.prompt_sha256 || null,
292
+ context_manifest: info.context_manifest || [],
293
+ produced_patch_sha256: info.produced_patch_sha256 || null,
294
+ model_provider: info.model_provider || null,
295
+ model_id: info.model_id || MODEL_ID,
296
+ model_call_count: info.model_call_count || 0,
297
+ tokens_used: info.tokens_used || null,
298
+ stdout: [
299
+ "Agent Team Author: STOPPED",
300
+ ` feature_key: ${ctx.featureKey}`,
301
+ ` run_id: ${ctx.runId}`,
302
+ ` stop: ${info.stop_condition_hit || "unknown_risk_stop"}`,
303
+ " cleanup: completed",
304
+ ].join("\n"),
305
+ };
306
+ }
307
+
308
+ function submitStopEvidence(ctx, patchSummary, data) {
309
+ const info = data || {};
310
+ const evidenceJson = buildExecuteEvidence(ctx, {
311
+ stop_condition_hit: info.stop_condition_hit || "unknown_risk_stop",
312
+ summary: `Author execution stopped: ${info.stop_condition_hit || "unknown_risk_stop"}`,
313
+ commands_run: [],
314
+ verification_evidence: "author flow stopped before allowed verification completed",
315
+ blockers: [info.reason || info.stop_condition_hit || "unknown_risk_stop"],
316
+ files_touched: targetPaths(patchSummary),
317
+ code_diff: `no patch applied — stopped at ${info.stop_condition_hit || "unknown_risk_stop"}`,
318
+ });
319
+ const evidenceResult = writeAndSubmitExecuteEvidence(ctx, evidenceJson);
320
+ const readinessBundle = writeReadinessAndReport(ctx);
321
+ return { evidenceResult, readinessBundle };
322
+ }
323
+
324
+ async function withTimeout(promise, timeoutMs) {
325
+ let timer;
326
+ try {
327
+ return await Promise.race([
328
+ promise,
329
+ new Promise((_, reject) => {
330
+ timer = setTimeout(() => reject(new ValidationError("FAIL_MODEL_TIMEOUT: model wall-clock timeout exceeded")), timeoutMs);
331
+ }),
332
+ ]);
333
+ } finally {
334
+ if (timer) clearTimeout(timer);
335
+ }
336
+ }
337
+
338
+ async function executeAuthor(projectPath, featureKey, opts) {
339
+ const options = opts || {};
340
+ const ctx = loadExecuteContext(projectPath, featureKey);
341
+ await confirmExecute(options.confirmInput || {}, ctx.featureKey, ctx.runId);
342
+ const allowlist = buildRunAllowlist(ctx.verificationCommands, options);
343
+ let created = null;
344
+ let keepForReview = false;
345
+ let patchPath = null;
346
+ try {
347
+ created = createWorktree(ctx.projectPath, ctx.featureKey, ctx.runId);
348
+ ctx.worktreeRoot = created.worktreeRoot;
349
+ ctx.branch = created.branch;
350
+ const context = assembleContext(ctx, { worktreeRoot: created.worktreeRoot, runControlledProcess: options.runControlledProcess });
351
+ let modelCallCount = 0;
352
+ const provider = options.callModelProvider || callModelProvider;
353
+ const modelResult = await withTimeout(Promise.resolve().then(() => {
354
+ modelCallCount += 1;
355
+ if (modelCallCount > MODEL_MAX_CALLS_PER_RUN) {
356
+ throw new ValidationError("FAIL_MODEL_CALL_LIMIT: only one model call is allowed per run");
357
+ }
358
+ return provider({
359
+ prompt: context.prompt,
360
+ model_id: MODEL_ID,
361
+ max_output_tokens: MODEL_MAX_OUTPUT_TOKENS,
362
+ input_token_estimate: context.input_token_estimate,
363
+ call_count: modelCallCount,
364
+ }, options.providerDeps || {});
365
+ }), MODEL_WALLCLOCK_TIMEOUT_MS);
366
+ const patchText = String(modelResult.patch || "");
367
+ const patchHash = sha256(patchText);
368
+ const contentStop = scanProducedPatchForSecrets(patchText);
369
+ patchPath = writeProducedPatch(ctx.projectPath, ctx.featureKey, patchText);
370
+ const patchSummary = readPatchSummary(patchPath);
371
+ if (contentStop) {
372
+ const bundle = submitStopEvidence(ctx, patchSummary, contentStop);
373
+ return stopResult(ctx, {
374
+ ...contentStop,
375
+ evidence_path: bundle.evidenceResult.outputPath,
376
+ readiness_path: bundle.readinessBundle.readinessPath,
377
+ readiness_verdict: bundle.readinessBundle.readiness.overall_verdict,
378
+ report_path: bundle.readinessBundle.reportPath,
379
+ prompt_sha256: context.prompt_sha256,
380
+ context_manifest: context.context_manifest,
381
+ produced_patch_sha256: patchHash,
382
+ model_provider: modelResult.provider,
383
+ model_id: modelResult.model_id,
384
+ model_call_count: modelResult.model_call_count,
385
+ tokens_used: modelResult.tokens_used,
386
+ });
387
+ }
388
+ const patchStop = guardPatchTargets(patchSummary, ctx.worktreeRoot, ctx.allowedFileScopes);
389
+ if (patchStop) {
390
+ const bundle = submitStopEvidence(ctx, patchSummary, patchStop);
391
+ return stopResult(ctx, {
392
+ ...patchStop,
393
+ evidence_path: bundle.evidenceResult.outputPath,
394
+ readiness_path: bundle.readinessBundle.readinessPath,
395
+ readiness_verdict: bundle.readinessBundle.readiness.overall_verdict,
396
+ report_path: bundle.readinessBundle.reportPath,
397
+ prompt_sha256: context.prompt_sha256,
398
+ context_manifest: context.context_manifest,
399
+ produced_patch_sha256: patchHash,
400
+ model_provider: modelResult.provider,
401
+ model_id: modelResult.model_id,
402
+ model_call_count: modelResult.model_call_count,
403
+ tokens_used: modelResult.tokens_used,
404
+ });
405
+ }
406
+ applyPatch(ctx.worktreeRoot, patchPath);
407
+ const verification = runVerificationCommands(ctx, allowlist);
408
+ const stopHit = verification.stop ? verification.stop.stop_condition_hit : null;
409
+ const stopReason = verification.stop ? verification.stop.reason : null;
410
+ const commandsRun = verification.commandResults.map((entry) => commandLiteral(entry.argv));
411
+ const evidenceJson = buildExecuteEvidence(ctx, {
412
+ stop_condition_hit: stopHit,
413
+ summary: stopHit ? `Author execution stopped: ${stopHit}` : "Model-authored docs patch applied and allowed verification completed.",
414
+ commands_run: commandsRun,
415
+ verification_evidence: verification.commandResults.map((entry) => `${commandLiteral(entry.argv)} exit=${entry.result.exitCode}`).join("; ") || "no commands run",
416
+ blockers: stopHit ? [stopReason || stopHit] : [],
417
+ files_touched: targetPaths(patchSummary),
418
+ code_diff: `Applied model-produced patch to worktree ${ctx.worktreeRoot}.`,
419
+ });
420
+ const evidenceResult = writeAndSubmitExecuteEvidence(ctx, evidenceJson);
421
+ const readinessBundle = writeReadinessAndReport(ctx);
422
+ keepForReview = !stopHit;
423
+ return {
424
+ keepForReview,
425
+ exitCode: stopHit ? 1 : 0,
426
+ status: stopHit ? "NOT_READY" : "READY_TO_REVIEW",
427
+ feature_key: ctx.featureKey,
428
+ run_id: ctx.runId,
429
+ execution_mode: "execute",
430
+ workflow_type: ctx.workflowType,
431
+ worktree_path: ctx.worktreeRoot,
432
+ branch: ctx.branch,
433
+ actions_executed: verification.actionsExecuted,
434
+ stop_condition_hit: stopHit,
435
+ stop_reason: stopReason,
436
+ evidence_path: evidenceResult.outputPath,
437
+ readiness_path: readinessBundle.readinessPath,
438
+ readiness_verdict: readinessBundle.readiness.overall_verdict,
439
+ report_path: readinessBundle.reportPath,
440
+ cleanup_command: plannedCleanupCommand(ctx),
441
+ prompt_sha256: context.prompt_sha256,
442
+ context_manifest: context.context_manifest,
443
+ produced_patch_sha256: patchHash,
444
+ model_provider: modelResult.provider,
445
+ model_id: modelResult.model_id,
446
+ model_call_count: modelResult.model_call_count,
447
+ tokens_used: modelResult.tokens_used,
448
+ stdout: [
449
+ `Agent Team Author: ${stopHit ? "STOPPED" : "COMPLETED"}`,
450
+ ` feature_key: ${ctx.featureKey}`,
451
+ ` run_id: ${ctx.runId}`,
452
+ ` worktree: ${ctx.worktreeRoot}`,
453
+ ` actions: ${verification.actionsExecuted}`,
454
+ ` stop: ${stopHit || "none"}`,
455
+ stopHit ? " cleanup: completed" : ` cleanup command: ${plannedCleanupCommand(ctx)}`,
456
+ ].join("\n"),
457
+ };
458
+ } catch (error) {
459
+ const stopHit = stopConditionFromError(error);
460
+ return stopResult(ctx, { stop_condition_hit: stopHit, reason: error && error.message ? error.message : String(error || stopHit) });
461
+ } finally {
462
+ if (patchPath) fs.rmSync(patchPath, { force: true });
463
+ if (!keepForReview && created) {
464
+ cleanupWorktree(ctx.projectPath, created.worktreeRoot, created.branch);
465
+ }
466
+ }
467
+ }
468
+
469
+ function dryRunAuthor(projectPath, featureKey, opts) {
470
+ const options = opts || {};
471
+ const ctx = loadExecuteContext(projectPath, featureKey);
472
+ const allowlist = buildRunAllowlist(ctx.verificationCommands, options);
473
+ void allowlist;
474
+ const context = assembleContext(ctx, { worktreeRoot: ctx.projectPath, runControlledProcess: options.runControlledProcess });
475
+ return {
476
+ exitCode: 0,
477
+ status: "PLANNED",
478
+ feature_key: ctx.featureKey,
479
+ run_id: ctx.runId,
480
+ execution_mode: "dry-run",
481
+ workflow_type: ctx.workflowType,
482
+ worktree_path: ctx.worktreeRoot,
483
+ branch: ctx.branch,
484
+ actions_executed: 0,
485
+ stop_condition_hit: null,
486
+ prompt_sha256: context.prompt_sha256,
487
+ context_manifest: context.context_manifest,
488
+ produced_patch_sha256: null,
489
+ model_provider: "claude",
490
+ model_id: MODEL_ID,
491
+ model_call_count: 0,
492
+ tokens_used: null,
493
+ projected_cost_usd: context.projected_cost_usd,
494
+ stdout: renderDryRunAuthorPlan(ctx, context),
495
+ cleanup_command: plannedCleanupCommand(ctx),
496
+ };
497
+ }
498
+
499
+ function runAuthor(projectPath, featureKey, opts) {
500
+ const options = opts || {};
501
+ if (options.mode === "execute") {
502
+ return executeAuthor(projectPath, featureKey, options);
503
+ }
504
+ return dryRunAuthor(projectPath, featureKey, options);
505
+ }
506
+
507
+ module.exports = {
508
+ GIT_LS_FILES_ARGV,
509
+ AUTHOR_PATCH_NAME,
510
+ sha256,
511
+ matchesScope,
512
+ isDenyListedRelPath,
513
+ listTrackedFiles,
514
+ assembleContext,
515
+ addedPatchContent,
516
+ scanProducedPatchForSecrets,
517
+ renderDryRunAuthorPlan,
518
+ dryRunAuthor,
519
+ executeAuthor,
520
+ runAuthor,
521
+ };