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.
Files changed (58) 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 +479 -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 +266 -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 +552 -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/agent-team-sleep-execute.js +524 -0
  32. package/src/lib/agent-team-sleep-session.js +278 -0
  33. package/src/lib/args.js +107 -107
  34. package/src/lib/errors.js +41 -41
  35. package/src/lib/model-provider.js +219 -0
  36. package/src/lib/powershell.js +65 -65
  37. package/src/lib/project-target-guard.js +53 -53
  38. package/src/lib/scope.js +72 -72
  39. package/src/lib/ship-readiness.js +281 -281
  40. package/src/lib/sleep-plan.js +175 -175
  41. package/src/lib/sleep-report.js +229 -229
  42. package/src/lib/toolkit-payload.js +72 -72
  43. package/src/lib/trust-events.js +264 -185
  44. package/src/lib/trust-file-scope.js +154 -154
  45. package/src/lib/trust-policy.js +212 -212
  46. package/src/lib/trust-redact.js +58 -35
  47. package/src/lib/trust-trace.js +179 -179
  48. package/src/lib/update.js +344 -344
  49. package/src/lib/workflow-artifact.js +503 -503
  50. package/src/lib/workflow-build.js +127 -127
  51. package/src/lib/workflow-doctor.js +83 -83
  52. package/src/lib/workflow-handoff.js +1029 -1029
  53. package/src/lib/workflow-intake.js +101 -101
  54. package/src/lib/workflow-plan.js +193 -193
  55. package/src/lib/workflow-review-packet.js +650 -650
  56. package/src/lib/workflow-ship.js +213 -213
  57. package/src/lib/workflow-state.js +438 -438
  58. package/src/lib/workflow-verify.js +393 -393
@@ -0,0 +1,524 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const path = require("path");
5
+ const { ValidationError } = require("./errors");
6
+ const { safeSegment } = require("./agent-team-export");
7
+ const { produceAuthorPatch, sha256 } = require("./agent-team-author");
8
+ const {
9
+ MODEL_MAX_COST_USD,
10
+ MODEL_MAX_OUTPUT_TOKENS,
11
+ } = require("./model-provider");
12
+ const {
13
+ loadExecuteContext,
14
+ createWorktree,
15
+ cleanupWorktree,
16
+ buildRunAllowlist,
17
+ readPatchSummary,
18
+ guardPatchTargets,
19
+ applyPatch,
20
+ runVerificationCommands,
21
+ buildExecuteEvidence,
22
+ writeAndSubmitExecuteEvidence,
23
+ writeReadinessAndReport,
24
+ commandLiteral,
25
+ targetPaths,
26
+ plannedCleanupCommand,
27
+ stopConditionFromError,
28
+ } = require("./agent-team-execute");
29
+ const { loadReadiness } = require("./agent-team-readiness");
30
+ const {
31
+ atomicWriteJson,
32
+ resolveEvidencePath,
33
+ } = require("./agent-team-evidence");
34
+ const { appendEvent } = require("./trust-events");
35
+ const {
36
+ SESSION_MAX_ITERATIONS,
37
+ SESSION_MAX_COST_USD,
38
+ SESSION_MAX_OUTPUT_TOKENS,
39
+ pinScope,
40
+ assertPinnedScope,
41
+ createSleepSession,
42
+ withSessionLease,
43
+ sessionStopConditionFromError,
44
+ } = require("./agent-team-sleep-session");
45
+
46
+ const SLEEP_EXECUTE_SCHEMA = "sdtk.agent-team-sleep-execute.preview.v1";
47
+ const SLEEP_PATH2_PROJECTED = Object.freeze({
48
+ projected_cost_usd: MODEL_MAX_COST_USD,
49
+ projected_output_tokens: MODEL_MAX_OUTPUT_TOKENS,
50
+ });
51
+ const SLEEP_PATH1_PROJECTED = Object.freeze({
52
+ projected_cost_usd: 0,
53
+ projected_output_tokens: 0,
54
+ });
55
+
56
+ function readJson(file) {
57
+ return JSON.parse(fs.readFileSync(file, "utf8"));
58
+ }
59
+
60
+ function loadSleepPlan(projectPath, featureKey) {
61
+ const safeFeatureKey = safeSegment(featureKey, "feature_key");
62
+ const planPath = path.resolve(projectPath || ".", ".sdtk", "trust", "sleep-plan.json");
63
+ let plan;
64
+ try {
65
+ plan = readJson(planPath);
66
+ } catch (_error) {
67
+ throw new ValidationError(`NEEDS_SLEEP_PLAN: no sleep plan at ${planPath}. Run \`sdtk-code sleep plan\` first.`);
68
+ }
69
+ if (plan.feature_key !== safeFeatureKey) {
70
+ throw new ValidationError(`NEEDS_SLEEP_PLAN: sleep-plan feature_key "${plan.feature_key}" does not match --feature-key "${safeFeatureKey}".`);
71
+ }
72
+ return { plan, planPath };
73
+ }
74
+
75
+ function hasRemainingPlannedWork(plan, completedIterations) {
76
+ const steps = Array.isArray(plan && plan.ordered_steps) ? plan.ordered_steps : [];
77
+ return completedIterations < steps.length;
78
+ }
79
+
80
+ function tokenOutput(tokensUsed) {
81
+ return tokensUsed && typeof tokensUsed.output_tokens === "number" ? tokensUsed.output_tokens : 0;
82
+ }
83
+
84
+ function sleepConfirmPhrase(featureKey, sessionId) {
85
+ return `EXECUTE ${safeSegment(featureKey, "feature_key")} ${safeSegment(sessionId, "session_id")} max_iterations=3 cost_cap=$3.00 unit=Path2-author-only`;
86
+ }
87
+
88
+ async function confirmSleepExecute(input, featureKey, sessionId) {
89
+ const source = input || {};
90
+ const expected = sleepConfirmPhrase(featureKey, sessionId);
91
+ if (source.isTTY !== true) {
92
+ throw new ValidationError("FAIL_EXECUTE_REQUIRES_TTY: --execute requires an interactive TTY confirmation.");
93
+ }
94
+ if (typeof source.readLine !== "function") {
95
+ throw new ValidationError("FAIL_EXECUTE_REQUIRES_TTY: confirmation reader is not available.");
96
+ }
97
+ const answer = await source.readLine(`Type ${expected} to continue: `);
98
+ if (String(answer || "") !== expected) {
99
+ throw new ValidationError("FAIL_EXECUTE_CONFIRMATION_MISMATCH: exact sleep-execute confirmation phrase was not provided.");
100
+ }
101
+ return { confirmed: true, phrase: expected };
102
+ }
103
+
104
+ function tempPatchPath(projectPath, featureKey, sessionId, iterationIndex) {
105
+ const dir = path.resolve(projectPath || ".", ".sdtk", "agent-team", "tmp", safeSegment(featureKey, "feature_key"), "sleep-execute");
106
+ fs.mkdirSync(dir, { recursive: true });
107
+ return path.join(dir, `${safeSegment(sessionId, "session_id")}-${iterationIndex}.patch`);
108
+ }
109
+
110
+ function writeTempPatch(projectPath, featureKey, sessionId, iterationIndex, patchText) {
111
+ const out = tempPatchPath(projectPath, featureKey, sessionId, iterationIndex);
112
+ fs.writeFileSync(out, String(patchText || ""), "utf8");
113
+ return out;
114
+ }
115
+
116
+ function evidenceBaseDir(projectPath) {
117
+ return path.resolve(projectPath || ".", ".sdtk", "agent-team", "evidence");
118
+ }
119
+
120
+ function safeSubmitEvidence(ctx, evidenceJson) {
121
+ try {
122
+ return writeAndSubmitExecuteEvidence(ctx, evidenceJson);
123
+ } catch (error) {
124
+ const message = error && error.message ? String(error.message) : String(error || "");
125
+ if (!message.includes("FAIL_EVIDENCE_ALREADY_SUBMITTED")) {
126
+ throw error;
127
+ }
128
+ const outputPath = resolveEvidencePath(ctx.projectPath, ctx.featureKey, String(ctx.role.role || "dev").toLowerCase());
129
+ atomicWriteJson(outputPath, evidenceJson, evidenceBaseDir(ctx.projectPath));
130
+ return { outputPath, updatedExisting: true };
131
+ }
132
+ }
133
+
134
+ function assertReadinessArtifactAuthentic(ctx, readiness) {
135
+ if (!readiness || typeof readiness !== "object") {
136
+ throw new ValidationError("NEEDS_READINESS: readiness.json is not an object.");
137
+ }
138
+ if (readiness.feature_key !== ctx.featureKey || readiness.run_id !== ctx.runId) {
139
+ throw new ValidationError("NEEDS_READINESS: readiness.json does not match the active agent-team plan.");
140
+ }
141
+ if (readiness.overall_verdict === "READY_TO_SLEEP") {
142
+ for (const roleSpec of Array.isArray(ctx.plan.roles) ? ctx.plan.roles : []) {
143
+ const role = roleSpec && roleSpec.role;
144
+ if (!role) continue;
145
+ const evidencePath = resolveEvidencePath(ctx.projectPath, ctx.featureKey, String(role).toLowerCase());
146
+ if (!fs.existsSync(evidencePath)) {
147
+ throw new ValidationError(`NEEDS_READINESS: READY_TO_SLEEP is not backed by ${String(role).toUpperCase()} evidence.`);
148
+ }
149
+ }
150
+ }
151
+ return readiness;
152
+ }
153
+
154
+ function refreshReadinessAndLoad(ctx) {
155
+ const refreshed = writeReadinessAndReport(ctx);
156
+ const loaded = loadReadiness(ctx.projectPath, ctx.featureKey);
157
+ return { ...refreshed, loaded };
158
+ }
159
+
160
+ function buildStopEvidence(ctx, patchSummary, stopHit, reason, codeDiff) {
161
+ return buildExecuteEvidence(ctx, {
162
+ stop_condition_hit: stopHit || "unknown_risk_stop",
163
+ summary: `Sleep execute stopped: ${stopHit || "unknown_risk_stop"}`,
164
+ commands_run: [],
165
+ verification_evidence: "sleep execute stopped before allowed verification completed",
166
+ blockers: [reason || stopHit || "unknown_risk_stop"],
167
+ files_touched: targetPaths(patchSummary),
168
+ code_diff: codeDiff || `no patch applied — stopped at ${stopHit || "unknown_risk_stop"}`,
169
+ });
170
+ }
171
+
172
+ function sessionTrace(projectPath, result, extra) {
173
+ const info = extra || {};
174
+ return appendEvent(projectPath, {
175
+ toolkit: "sdtk-code",
176
+ event_type: info.event_type || "agent_team_sleep_iteration",
177
+ command: info.command || `sdtk-code agent-team sleep-execute --feature-key ${result.feature_key}`,
178
+ status: result.status,
179
+ feature_key: result.feature_key,
180
+ run_id: result.run_id,
181
+ session_id: result.session_id,
182
+ iteration_index: info.iteration_index,
183
+ readiness_verdict: info.readiness_verdict || result.readiness_verdict,
184
+ stop_condition_hit: info.stop_condition_hit || result.stop_condition_hit,
185
+ session_cost_usd: result.session_cost_usd,
186
+ session_output_tokens: result.session_output_tokens,
187
+ worktree_path: result.worktree_path,
188
+ actions_executed: result.actions_executed,
189
+ execution_mode: result.execution_mode,
190
+ workflow_type: result.workflow_type,
191
+ model_provider: info.model_provider,
192
+ model_id: info.model_id,
193
+ prompt_sha256: info.prompt_sha256,
194
+ context_manifest: info.context_manifest,
195
+ produced_patch_sha256: info.produced_patch_sha256,
196
+ model_call_count: info.model_call_count,
197
+ tokens_used: info.tokens_used,
198
+ });
199
+ }
200
+
201
+ function renderDryRunPlan(ctx, sessionId, pinnedScope, readiness) {
202
+ return [
203
+ `Agent Team Sleep Execute Plan: ${ctx.featureKey}`,
204
+ " mode: dry-run",
205
+ " network: disabled",
206
+ " credential: not required",
207
+ ` session_id: ${sessionId}`,
208
+ ` run_id: ${ctx.runId}`,
209
+ ` max_iters: ${SESSION_MAX_ITERATIONS}`,
210
+ ` cost_cap_usd: ${SESSION_MAX_COST_USD}`,
211
+ ` output_cap: ${SESSION_MAX_OUTPUT_TOKENS}`,
212
+ ` readiness: ${readiness ? readiness.overall_verdict : "not loaded"}`,
213
+ ` allowed scope: ${pinnedScope.allowed_file_scopes.join(", ")}`,
214
+ ` allowlist: ${pinnedScope.verification_commands.join("; ")}`,
215
+ " dry-run only — no provider call, no API key lookup, no worktree mutation, no patch apply.",
216
+ ].join("\n");
217
+ }
218
+
219
+ function dryRunSleepExecute(projectPath, featureKey, opts) {
220
+ const options = opts || {};
221
+ const ctx = loadExecuteContext(projectPath, featureKey);
222
+ const sessionId = options.sessionId ? safeSegment(options.sessionId, "session_id") : `${ctx.runId}_sleep`;
223
+ const pinnedScope = pinScope(ctx);
224
+ let readiness = null;
225
+ try {
226
+ readiness = loadReadiness(ctx.projectPath, ctx.featureKey);
227
+ } catch (_error) {
228
+ readiness = null;
229
+ }
230
+ return {
231
+ exitCode: 0,
232
+ status: "PLANNED",
233
+ feature_key: ctx.featureKey,
234
+ run_id: ctx.runId,
235
+ session_id: sessionId,
236
+ execution_mode: "dry-run",
237
+ workflow_type: ctx.workflowType,
238
+ worktree_path: ctx.worktreeRoot,
239
+ branch: ctx.branch,
240
+ actions_executed: 0,
241
+ stop_condition_hit: null,
242
+ readiness_verdict: readiness ? readiness.overall_verdict : null,
243
+ session_cost_usd: 0,
244
+ session_output_tokens: 0,
245
+ stdout: renderDryRunPlan(ctx, sessionId, pinnedScope, readiness),
246
+ };
247
+ }
248
+
249
+ function stopResult(ctx, session, data) {
250
+ const info = data || {};
251
+ const snap = session.snapshot({ cumulativeWorktreePath: ctx.worktreeRoot, plan: ctx.plan });
252
+ return {
253
+ keepForReview: info.keepForReview !== false,
254
+ exitCode: info.exitCode === undefined ? 1 : info.exitCode,
255
+ status: info.status || "NOT_READY",
256
+ feature_key: ctx.featureKey,
257
+ run_id: ctx.runId,
258
+ session_id: session.session_id,
259
+ execution_mode: "execute",
260
+ workflow_type: ctx.workflowType,
261
+ worktree_path: ctx.worktreeRoot,
262
+ branch: ctx.branch,
263
+ actions_executed: Number(info.actions_executed || 0),
264
+ stop_condition_hit: info.stop_condition_hit || "unknown_risk_stop",
265
+ stop_reason: info.reason || info.stop_condition_hit || "unknown_risk_stop",
266
+ evidence_path: info.evidence_path || null,
267
+ readiness_path: info.readiness_path || null,
268
+ readiness_verdict: info.readiness_verdict || null,
269
+ report_path: info.report_path || null,
270
+ cleanup_command: info.cleanup_command || plannedCleanupCommand(ctx),
271
+ session_cost_usd: snap.session_cost_usd,
272
+ session_output_tokens: snap.session_output_tokens,
273
+ iteration_count: snap.iteration,
274
+ stdout: [
275
+ `Agent Team Sleep Execute: ${info.status || "STOPPED"}`,
276
+ ` feature_key: ${ctx.featureKey}`,
277
+ ` run_id: ${ctx.runId}`,
278
+ ` session_id: ${session.session_id}`,
279
+ ` worktree: ${ctx.worktreeRoot}`,
280
+ ` iterations: ${snap.iteration}`,
281
+ ` stop: ${info.stop_condition_hit || "unknown_risk_stop"}`,
282
+ ` cleanup command: ${plannedCleanupCommand(ctx)}`,
283
+ ].join("\n"),
284
+ };
285
+ }
286
+
287
+ async function executeSleepSession(projectPath, featureKey, opts) {
288
+ const options = opts || {};
289
+ const ctx = loadExecuteContext(projectPath, featureKey);
290
+ const { plan: sleepPlan } = loadSleepPlan(ctx.projectPath, ctx.featureKey);
291
+ const sessionId = options.sessionId ? safeSegment(options.sessionId, "session_id") : `${ctx.runId}_sleep`;
292
+ const pinnedScope = pinScope(ctx);
293
+ const session = createSleepSession({
294
+ featureKey: ctx.featureKey,
295
+ sessionId,
296
+ pinnedScope,
297
+ nowMs: options.nowMs,
298
+ });
299
+ await confirmSleepExecute(options.confirmInput || {}, ctx.featureKey, session.session_id);
300
+
301
+ return withSessionLease(session.session_id, async () => {
302
+ let created = null;
303
+ let keepForReview = false;
304
+ const tempPatches = [];
305
+ let lastResult = null;
306
+ try {
307
+ created = createWorktree(ctx.projectPath, ctx.featureKey, session.session_id);
308
+ ctx.worktreeRoot = created.worktreeRoot;
309
+ ctx.branch = created.branch;
310
+ const allowlist = buildRunAllowlist(ctx.verificationCommands, options);
311
+ while (true) {
312
+ const iterationIndex = session.snapshot().iteration;
313
+ const pathMode = options.patchFile ? "path1" : "path2";
314
+ session.assertCanStartIteration(pathMode === "path1" ? SLEEP_PATH1_PROJECTED : SLEEP_PATH2_PROJECTED);
315
+ const readinessBefore = assertReadinessArtifactAuthentic(ctx, loadReadiness(ctx.projectPath, ctx.featureKey));
316
+ if (readinessBefore.overall_verdict !== "READY_TO_SLEEP") {
317
+ keepForReview = true;
318
+ lastResult = stopResult(ctx, session, {
319
+ stop_condition_hit: readinessBefore.overall_verdict,
320
+ reason: `readiness gate is ${readinessBefore.overall_verdict}`,
321
+ readiness_verdict: readinessBefore.overall_verdict,
322
+ status: "NOT_READY",
323
+ });
324
+ sessionTrace(ctx.projectPath, lastResult, { iteration_index: iterationIndex, readiness_verdict: readinessBefore.overall_verdict });
325
+ return lastResult;
326
+ }
327
+ assertPinnedScope(session, ctx);
328
+
329
+ let patchPath;
330
+ let patchSummary;
331
+ let patchHash = null;
332
+ let produced = null;
333
+ if (pathMode === "path1") {
334
+ patchPath = path.resolve(options.patchFile);
335
+ patchSummary = readPatchSummary(patchPath);
336
+ patchHash = sha256(fs.readFileSync(patchPath, "utf8"));
337
+ } else {
338
+ produced = await produceAuthorPatch(ctx.projectPath, ctx.featureKey, {
339
+ worktreeRoot: ctx.worktreeRoot,
340
+ callModelProvider: options.callModelProvider,
341
+ providerDeps: options.providerDeps,
342
+ runControlledProcess: options.runControlledProcess,
343
+ });
344
+ patchHash = produced.patchHash;
345
+ patchPath = writeTempPatch(ctx.projectPath, ctx.featureKey, session.session_id, iterationIndex, produced.patchText);
346
+ tempPatches.push(patchPath);
347
+ patchSummary = readPatchSummary(patchPath);
348
+ if (produced.stop) {
349
+ const evidence = buildStopEvidence(ctx, patchSummary, produced.stop.stop_condition_hit, produced.stop.reason);
350
+ const evidenceResult = safeSubmitEvidence(ctx, evidence);
351
+ const refreshed = refreshReadinessAndLoad(ctx);
352
+ session.recordIteration({
353
+ cost_usd: Number(produced.projected_cost_usd || 0),
354
+ output_tokens: tokenOutput(produced.tokens_used),
355
+ produced_patch_sha256: patchHash,
356
+ cumulativeWorktreePath: ctx.worktreeRoot,
357
+ plan: ctx.plan,
358
+ });
359
+ keepForReview = true;
360
+ lastResult = stopResult(ctx, session, {
361
+ stop_condition_hit: produced.stop.stop_condition_hit,
362
+ reason: produced.stop.reason,
363
+ evidence_path: evidenceResult.outputPath,
364
+ readiness_path: refreshed.readinessPath,
365
+ readiness_verdict: refreshed.loaded.overall_verdict,
366
+ report_path: refreshed.reportPath,
367
+ status: "NOT_READY",
368
+ });
369
+ sessionTrace(ctx.projectPath, lastResult, {
370
+ iteration_index: iterationIndex,
371
+ readiness_verdict: refreshed.loaded.overall_verdict,
372
+ stop_condition_hit: produced.stop.stop_condition_hit,
373
+ model_provider: produced.model_provider,
374
+ model_id: produced.model_id,
375
+ prompt_sha256: produced.prompt_sha256,
376
+ context_manifest: produced.context_manifest,
377
+ produced_patch_sha256: patchHash,
378
+ model_call_count: produced.model_call_count,
379
+ tokens_used: produced.tokens_used,
380
+ });
381
+ return lastResult;
382
+ }
383
+ }
384
+
385
+ const patchStop = guardPatchTargets(patchSummary, ctx.worktreeRoot, ctx.allowedFileScopes);
386
+ if (patchStop) {
387
+ const evidence = buildStopEvidence(ctx, patchSummary, patchStop.stop_condition_hit, patchStop.reason);
388
+ const evidenceResult = safeSubmitEvidence(ctx, evidence);
389
+ const refreshed = refreshReadinessAndLoad(ctx);
390
+ session.recordIteration({
391
+ cost_usd: produced ? Number(produced.projected_cost_usd || 0) : 0,
392
+ output_tokens: produced ? tokenOutput(produced.tokens_used) : 0,
393
+ produced_patch_sha256: patchHash,
394
+ cumulativeWorktreePath: ctx.worktreeRoot,
395
+ plan: ctx.plan,
396
+ });
397
+ keepForReview = true;
398
+ lastResult = stopResult(ctx, session, {
399
+ stop_condition_hit: patchStop.stop_condition_hit,
400
+ reason: patchStop.reason,
401
+ evidence_path: evidenceResult.outputPath,
402
+ readiness_path: refreshed.readinessPath,
403
+ readiness_verdict: refreshed.loaded.overall_verdict,
404
+ report_path: refreshed.reportPath,
405
+ status: "NOT_READY",
406
+ });
407
+ sessionTrace(ctx.projectPath, lastResult, { iteration_index: iterationIndex, readiness_verdict: refreshed.loaded.overall_verdict, stop_condition_hit: patchStop.stop_condition_hit });
408
+ return lastResult;
409
+ }
410
+
411
+ applyPatch(ctx.worktreeRoot, patchPath);
412
+ const verification = runVerificationCommands(ctx, allowlist);
413
+ const stopHit = verification.stop ? verification.stop.stop_condition_hit : null;
414
+ const stopReason = verification.stop ? verification.stop.reason : null;
415
+ const commandsRun = verification.commandResults.map((entry) => commandLiteral(entry.argv));
416
+ const evidenceJson = buildExecuteEvidence(ctx, {
417
+ stop_condition_hit: stopHit,
418
+ summary: stopHit ? `Sleep execute stopped: ${stopHit}` : "Sleep execute iteration applied patch and completed allowed verification commands.",
419
+ commands_run: commandsRun,
420
+ verification_evidence: verification.commandResults.map((entry) => `${commandLiteral(entry.argv)} exit=${entry.result.exitCode}`).join("; ") || "no commands run",
421
+ blockers: stopHit ? [stopReason || stopHit] : [],
422
+ files_touched: targetPaths(patchSummary),
423
+ code_diff: `Applied sleep-execute patch to cumulative worktree ${ctx.worktreeRoot}.`,
424
+ });
425
+ const evidenceResult = safeSubmitEvidence(ctx, evidenceJson);
426
+ const refreshed = refreshReadinessAndLoad(ctx);
427
+ const snap = session.recordIteration({
428
+ cost_usd: produced ? Number(produced.projected_cost_usd || 0) : 0,
429
+ output_tokens: produced ? tokenOutput(produced.tokens_used) : 0,
430
+ produced_patch_sha256: patchHash,
431
+ cumulativeWorktreePath: ctx.worktreeRoot,
432
+ plan: ctx.plan,
433
+ });
434
+ lastResult = stopResult(ctx, session, {
435
+ exitCode: stopHit ? 1 : 0,
436
+ status: stopHit ? "NOT_READY" : "READY_TO_REVIEW",
437
+ stop_condition_hit: stopHit,
438
+ reason: stopReason,
439
+ actions_executed: verification.actionsExecuted,
440
+ evidence_path: evidenceResult.outputPath,
441
+ readiness_path: refreshed.readinessPath,
442
+ readiness_verdict: refreshed.loaded.overall_verdict,
443
+ report_path: refreshed.reportPath,
444
+ });
445
+ lastResult.iteration_count = snap.iteration;
446
+ sessionTrace(ctx.projectPath, lastResult, {
447
+ iteration_index: iterationIndex,
448
+ readiness_verdict: refreshed.loaded.overall_verdict,
449
+ stop_condition_hit: stopHit,
450
+ model_provider: produced ? produced.model_provider : null,
451
+ model_id: produced ? produced.model_id : null,
452
+ prompt_sha256: produced ? produced.prompt_sha256 : null,
453
+ context_manifest: produced ? produced.context_manifest : [],
454
+ produced_patch_sha256: patchHash,
455
+ model_call_count: produced ? produced.model_call_count : 0,
456
+ tokens_used: produced ? produced.tokens_used : null,
457
+ });
458
+ if (stopHit || refreshed.loaded.overall_verdict !== "READY_TO_SLEEP") {
459
+ keepForReview = true;
460
+ return lastResult;
461
+ }
462
+ if (!hasRemainingPlannedWork(sleepPlan, snap.iteration)) {
463
+ keepForReview = true;
464
+ lastResult.status = "READY_TO_REVIEW";
465
+ lastResult.exitCode = 0;
466
+ lastResult.stop_condition_hit = null;
467
+ lastResult.stop_reason = null;
468
+ lastResult.stdout = [
469
+ "Agent Team Sleep Execute: READY_TO_REVIEW",
470
+ ` feature_key: ${ctx.featureKey}`,
471
+ ` run_id: ${ctx.runId}`,
472
+ ` session_id: ${session.session_id}`,
473
+ ` worktree: ${ctx.worktreeRoot}`,
474
+ ` iterations: ${snap.iteration}`,
475
+ " stop: none",
476
+ ` cleanup command: ${plannedCleanupCommand(ctx)}`,
477
+ ].join("\n");
478
+ sessionTrace(ctx.projectPath, lastResult, { event_type: "agent_team_sleep_session", readiness_verdict: refreshed.loaded.overall_verdict });
479
+ return lastResult;
480
+ }
481
+ }
482
+ } catch (error) {
483
+ const stopHit = sessionStopConditionFromError(error) || stopConditionFromError(error);
484
+ if (session && typeof session.killSession === "function") {
485
+ session.killSession(stopHit);
486
+ }
487
+ lastResult = stopResult(ctx, session, {
488
+ stop_condition_hit: stopHit,
489
+ reason: error && error.message ? error.message : String(error || stopHit),
490
+ status: "NOT_READY",
491
+ keepForReview: false,
492
+ });
493
+ sessionTrace(ctx.projectPath, lastResult, { stop_condition_hit: stopHit });
494
+ return lastResult;
495
+ } finally {
496
+ for (const patch of tempPatches) fs.rmSync(patch, { force: true });
497
+ if (!keepForReview && created) {
498
+ cleanupWorktree(ctx.projectPath, created.worktreeRoot, created.branch);
499
+ }
500
+ }
501
+ });
502
+ }
503
+
504
+ function runSleepExecute(projectPath, featureKey, opts) {
505
+ const options = opts || {};
506
+ if (options.mode === "execute") {
507
+ return executeSleepSession(projectPath, featureKey, options);
508
+ }
509
+ return dryRunSleepExecute(projectPath, featureKey, options);
510
+ }
511
+
512
+ module.exports = {
513
+ SLEEP_EXECUTE_SCHEMA,
514
+ SLEEP_PATH2_PROJECTED,
515
+ SLEEP_PATH1_PROJECTED,
516
+ loadSleepPlan,
517
+ hasRemainingPlannedWork,
518
+ sleepConfirmPhrase,
519
+ confirmSleepExecute,
520
+ dryRunSleepExecute,
521
+ executeSleepSession,
522
+ assertReadinessArtifactAuthentic,
523
+ runSleepExecute,
524
+ };