sdtk-code-kit 0.3.1 → 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/assets/manifest/toolkit-bundle.manifest.json +1 -1
- package/package.json +1 -1
- package/src/commands/agent-team.js +57 -3
- package/src/commands/help.js +3 -1
- package/src/lib/agent-team-author.js +71 -40
- package/src/lib/agent-team-sleep-execute.js +524 -0
- package/src/lib/agent-team-sleep-session.js +278 -0
- package/src/lib/trust-events.js +12 -0
package/package.json
CHANGED
|
@@ -35,6 +35,7 @@ const {
|
|
|
35
35
|
confirmExecute,
|
|
36
36
|
} = require("../lib/agent-team-execute");
|
|
37
37
|
const { runAuthor } = require("../lib/agent-team-author");
|
|
38
|
+
const { runSleepExecute } = require("../lib/agent-team-sleep-execute");
|
|
38
39
|
const { appendEvent } = require("../lib/trust-events");
|
|
39
40
|
|
|
40
41
|
const FLAG_DEFS = {
|
|
@@ -75,6 +76,14 @@ const AUTHOR_FLAG_DEFS = {
|
|
|
75
76
|
"dry-run": { type: "boolean" },
|
|
76
77
|
};
|
|
77
78
|
|
|
79
|
+
const SLEEP_EXECUTE_FLAG_DEFS = {
|
|
80
|
+
"feature-key": { type: "string" },
|
|
81
|
+
"project-path": { type: "string" },
|
|
82
|
+
"patch-file": { type: "string" },
|
|
83
|
+
execute: { type: "boolean" },
|
|
84
|
+
"dry-run": { type: "boolean" },
|
|
85
|
+
};
|
|
86
|
+
|
|
78
87
|
function resolveProjectPath(flags) {
|
|
79
88
|
return flags["project-path"] ? path.resolve(flags["project-path"]) : process.cwd();
|
|
80
89
|
}
|
|
@@ -382,10 +391,53 @@ async function cmdAgentTeamAuthor(args) {
|
|
|
382
391
|
return result.exitCode;
|
|
383
392
|
}
|
|
384
393
|
|
|
394
|
+
async function cmdAgentTeamSleepExecute(args) {
|
|
395
|
+
const { flags, positional } = parseFlags(args, SLEEP_EXECUTE_FLAG_DEFS);
|
|
396
|
+
if (positional.length > 0) {
|
|
397
|
+
throw new ValidationError('Unexpected positional arguments. Use flags only for "agent-team sleep-execute".');
|
|
398
|
+
}
|
|
399
|
+
if (flags.execute && flags["dry-run"]) {
|
|
400
|
+
throw new ValidationError('Use either --execute or --dry-run, not both.');
|
|
401
|
+
}
|
|
402
|
+
const featureKey = requireFlag(flags, "feature-key", "feature-key");
|
|
403
|
+
const projectPath = resolveProjectPath(flags);
|
|
404
|
+
const mode = flags.execute ? "execute" : "dry-run";
|
|
405
|
+
|
|
406
|
+
const result = await runSleepExecute(projectPath, featureKey, {
|
|
407
|
+
mode,
|
|
408
|
+
patchFile: flags["patch-file"],
|
|
409
|
+
confirmInput: {
|
|
410
|
+
isTTY: process.stdin.isTTY === true,
|
|
411
|
+
readLine: readLineFromStdin,
|
|
412
|
+
},
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
appendEvent(projectPath, {
|
|
416
|
+
toolkit: "sdtk-code",
|
|
417
|
+
event_type: mode === "execute" ? "agent_team_sleep_session" : "agent_team_sleep_planned",
|
|
418
|
+
command: `sdtk-code agent-team sleep-execute --feature-key ${featureKey}${flags["patch-file"] ? ` --patch-file ${flags["patch-file"]}` : ""}${mode === "execute" ? " --execute" : ""}`,
|
|
419
|
+
status: result.status,
|
|
420
|
+
feature_key: result.feature_key,
|
|
421
|
+
run_id: result.run_id,
|
|
422
|
+
session_id: result.session_id,
|
|
423
|
+
readiness_verdict: result.readiness_verdict,
|
|
424
|
+
stop_condition_hit: result.stop_condition_hit,
|
|
425
|
+
worktree_path: result.worktree_path,
|
|
426
|
+
actions_executed: result.actions_executed,
|
|
427
|
+
execution_mode: result.execution_mode,
|
|
428
|
+
workflow_type: result.workflow_type,
|
|
429
|
+
session_cost_usd: result.session_cost_usd,
|
|
430
|
+
session_output_tokens: result.session_output_tokens,
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
console.log(result.stdout || `Agent Team Sleep Execute: ${result.status}`);
|
|
434
|
+
return result.exitCode;
|
|
435
|
+
}
|
|
436
|
+
|
|
385
437
|
function cmdAgentTeam(args) {
|
|
386
438
|
if (!args || args.length === 0) {
|
|
387
439
|
throw new ValidationError(
|
|
388
|
-
"Usage: sdtk-code agent-team <subcommand> [flags]\nSubcommands: plan, preview, export, evidence, readiness, report, execute, author\n(run is not available; execute is bounded docs-only; author is attended D-2b.)"
|
|
440
|
+
"Usage: sdtk-code agent-team <subcommand> [flags]\nSubcommands: plan, preview, export, evidence, readiness, report, execute, author, sleep-execute\n(run is not available; execute is bounded docs-only; author is attended D-2b; sleep-execute is attended Phase E Preview.)"
|
|
389
441
|
);
|
|
390
442
|
}
|
|
391
443
|
|
|
@@ -411,13 +463,15 @@ function cmdAgentTeam(args) {
|
|
|
411
463
|
return cmdAgentTeamExecute(rest);
|
|
412
464
|
case "author":
|
|
413
465
|
return cmdAgentTeamAuthor(rest);
|
|
466
|
+
case "sleep-execute":
|
|
467
|
+
return cmdAgentTeamSleepExecute(rest);
|
|
414
468
|
case "run":
|
|
415
469
|
throw new ValidationError(
|
|
416
|
-
`"agent-team run" is not available in this phase. Supported: plan, preview, export, evidence, readiness, report, execute (bounded docs-only), author (attended D-2b).`
|
|
470
|
+
`"agent-team run" is not available in this phase. Supported: plan, preview, export, evidence, readiness, report, execute (bounded docs-only), author (attended D-2b), sleep-execute (attended Phase E Preview).`
|
|
417
471
|
);
|
|
418
472
|
default:
|
|
419
473
|
throw new ValidationError(
|
|
420
|
-
`Unknown agent-team subcommand: "${subcommand}". Available: plan, preview, export, evidence, readiness, report, execute, author`
|
|
474
|
+
`Unknown agent-team subcommand: "${subcommand}". Available: plan, preview, export, evidence, readiness, report, execute, author, sleep-execute`
|
|
421
475
|
);
|
|
422
476
|
}
|
|
423
477
|
}
|
package/src/commands/help.js
CHANGED
|
@@ -19,7 +19,7 @@ function cmdHelp() {
|
|
|
19
19
|
" update Refresh the npm package and optionally re-apply managed project/runtime assets",
|
|
20
20
|
" init Initialize SDTK-CODE workspace",
|
|
21
21
|
" runtime Manage runtime asset installation (install, uninstall, status)",
|
|
22
|
-
" agent-team Plan/preview/export/evidence plus bounded docs/governance Markdown execute/author",
|
|
22
|
+
" agent-team Plan/preview/export/evidence plus bounded docs/governance Markdown execute/author/sleep-execute",
|
|
23
23
|
"",
|
|
24
24
|
"Workflow status:",
|
|
25
25
|
" Implemented now: start, plan, build, verify, ship, status, doctor, resume",
|
|
@@ -165,11 +165,13 @@ function cmdHelp() {
|
|
|
165
165
|
" sdtk-code agent-team report --feature-key <KEY> [--project-path <path>]",
|
|
166
166
|
" sdtk-code agent-team execute --feature-key <KEY> --patch-file <path> [--dry-run|--execute] [--project-path <path>]",
|
|
167
167
|
" sdtk-code agent-team author --feature-key <KEY> [--dry-run|--execute] [--project-path <path>]",
|
|
168
|
+
" sdtk-code agent-team sleep-execute --feature-key <KEY> [--patch-file <path>] [--dry-run|--execute] [--project-path <path>]",
|
|
168
169
|
" evidence submit validates and stores agent-submitted evidence under .sdtk/agent-team/evidence/<KEY>/",
|
|
169
170
|
" readiness scores all roles and declares READY_TO_SLEEP or NOT_READY",
|
|
170
171
|
" report writes morning_report.md from evidence + readiness",
|
|
171
172
|
" execute is docs/governance Markdown Flow B: dry-run default; --execute requires exact TTY confirmation",
|
|
172
173
|
" author is attended D-2b: dry-run makes no model call; --execute makes one model call then uses the same bounded harness; no auto-merge",
|
|
174
|
+
" sleep-execute is attended single-session Phase E Preview: free/MIT; model/API cost is user-provided via your own provider key, not SDTK-hosted; bounded to <=3 author iterations into one worktree for one human review; not unattended autonomy",
|
|
173
175
|
" READY_TO_SLEEP indicates evidence is present and well-formed — it does NOT verify",
|
|
174
176
|
" implementation correctness. Human review required before acting on this verdict.",
|
|
175
177
|
" run is not available in this phase; execute never spawns LLM agents and never auto-merges.",
|
|
@@ -335,6 +335,49 @@ async function withTimeout(promise, timeoutMs) {
|
|
|
335
335
|
}
|
|
336
336
|
}
|
|
337
337
|
|
|
338
|
+
async function produceAuthorPatch(projectPath, featureKey, opts) {
|
|
339
|
+
const options = opts || {};
|
|
340
|
+
const ctx = loadExecuteContext(projectPath, featureKey);
|
|
341
|
+
const worktreeRoot = options.worktreeRoot;
|
|
342
|
+
if (!worktreeRoot) {
|
|
343
|
+
throw new ValidationError("FAIL_CONTEXT_EMPTY: produceAuthorPatch requires a provided worktreeRoot");
|
|
344
|
+
}
|
|
345
|
+
const context = assembleContext(ctx, {
|
|
346
|
+
worktreeRoot,
|
|
347
|
+
runControlledProcess: options.runControlledProcess,
|
|
348
|
+
});
|
|
349
|
+
let modelCallCount = 0;
|
|
350
|
+
const provider = options.callModelProvider || callModelProvider;
|
|
351
|
+
const modelResult = await withTimeout(Promise.resolve().then(() => {
|
|
352
|
+
modelCallCount += 1;
|
|
353
|
+
if (modelCallCount > MODEL_MAX_CALLS_PER_RUN) {
|
|
354
|
+
throw new ValidationError("FAIL_MODEL_CALL_LIMIT: only one model call is allowed per run");
|
|
355
|
+
}
|
|
356
|
+
return provider({
|
|
357
|
+
prompt: context.prompt,
|
|
358
|
+
model_id: MODEL_ID,
|
|
359
|
+
max_output_tokens: MODEL_MAX_OUTPUT_TOKENS,
|
|
360
|
+
input_token_estimate: context.input_token_estimate,
|
|
361
|
+
call_count: modelCallCount,
|
|
362
|
+
}, options.providerDeps || {});
|
|
363
|
+
}), MODEL_WALLCLOCK_TIMEOUT_MS);
|
|
364
|
+
const patchText = String(modelResult.patch || "");
|
|
365
|
+
const patchHash = sha256(patchText);
|
|
366
|
+
const contentStop = scanProducedPatchForSecrets(patchText);
|
|
367
|
+
return {
|
|
368
|
+
patchText,
|
|
369
|
+
patchHash,
|
|
370
|
+
prompt_sha256: context.prompt_sha256,
|
|
371
|
+
context_manifest: context.context_manifest,
|
|
372
|
+
model_provider: modelResult.provider,
|
|
373
|
+
model_id: modelResult.model_id,
|
|
374
|
+
model_call_count: modelResult.model_call_count || modelCallCount,
|
|
375
|
+
tokens_used: modelResult.tokens_used || null,
|
|
376
|
+
projected_cost_usd: modelResult.projected_cost_usd,
|
|
377
|
+
...(contentStop ? { stop: contentStop } : {}),
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
338
381
|
async function executeAuthor(projectPath, featureKey, opts) {
|
|
339
382
|
const options = opts || {};
|
|
340
383
|
const ctx = loadExecuteContext(projectPath, featureKey);
|
|
@@ -347,42 +390,29 @@ async function executeAuthor(projectPath, featureKey, opts) {
|
|
|
347
390
|
created = createWorktree(ctx.projectPath, ctx.featureKey, ctx.runId);
|
|
348
391
|
ctx.worktreeRoot = created.worktreeRoot;
|
|
349
392
|
ctx.branch = created.branch;
|
|
350
|
-
const
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
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);
|
|
393
|
+
const produced = await produceAuthorPatch(projectPath, featureKey, {
|
|
394
|
+
...options,
|
|
395
|
+
worktreeRoot: created.worktreeRoot,
|
|
396
|
+
});
|
|
397
|
+
const patchText = produced.patchText;
|
|
398
|
+
const patchHash = produced.patchHash;
|
|
369
399
|
patchPath = writeProducedPatch(ctx.projectPath, ctx.featureKey, patchText);
|
|
370
400
|
const patchSummary = readPatchSummary(patchPath);
|
|
371
|
-
if (
|
|
372
|
-
const bundle = submitStopEvidence(ctx, patchSummary,
|
|
401
|
+
if (produced.stop) {
|
|
402
|
+
const bundle = submitStopEvidence(ctx, patchSummary, produced.stop);
|
|
373
403
|
return stopResult(ctx, {
|
|
374
|
-
...
|
|
404
|
+
...produced.stop,
|
|
375
405
|
evidence_path: bundle.evidenceResult.outputPath,
|
|
376
406
|
readiness_path: bundle.readinessBundle.readinessPath,
|
|
377
407
|
readiness_verdict: bundle.readinessBundle.readiness.overall_verdict,
|
|
378
408
|
report_path: bundle.readinessBundle.reportPath,
|
|
379
|
-
prompt_sha256:
|
|
380
|
-
context_manifest:
|
|
409
|
+
prompt_sha256: produced.prompt_sha256,
|
|
410
|
+
context_manifest: produced.context_manifest,
|
|
381
411
|
produced_patch_sha256: patchHash,
|
|
382
|
-
model_provider:
|
|
383
|
-
model_id:
|
|
384
|
-
model_call_count:
|
|
385
|
-
tokens_used:
|
|
412
|
+
model_provider: produced.model_provider,
|
|
413
|
+
model_id: produced.model_id,
|
|
414
|
+
model_call_count: produced.model_call_count,
|
|
415
|
+
tokens_used: produced.tokens_used,
|
|
386
416
|
});
|
|
387
417
|
}
|
|
388
418
|
const patchStop = guardPatchTargets(patchSummary, ctx.worktreeRoot, ctx.allowedFileScopes);
|
|
@@ -394,13 +424,13 @@ async function executeAuthor(projectPath, featureKey, opts) {
|
|
|
394
424
|
readiness_path: bundle.readinessBundle.readinessPath,
|
|
395
425
|
readiness_verdict: bundle.readinessBundle.readiness.overall_verdict,
|
|
396
426
|
report_path: bundle.readinessBundle.reportPath,
|
|
397
|
-
prompt_sha256:
|
|
398
|
-
context_manifest:
|
|
427
|
+
prompt_sha256: produced.prompt_sha256,
|
|
428
|
+
context_manifest: produced.context_manifest,
|
|
399
429
|
produced_patch_sha256: patchHash,
|
|
400
|
-
model_provider:
|
|
401
|
-
model_id:
|
|
402
|
-
model_call_count:
|
|
403
|
-
tokens_used:
|
|
430
|
+
model_provider: produced.model_provider,
|
|
431
|
+
model_id: produced.model_id,
|
|
432
|
+
model_call_count: produced.model_call_count,
|
|
433
|
+
tokens_used: produced.tokens_used,
|
|
404
434
|
});
|
|
405
435
|
}
|
|
406
436
|
applyPatch(ctx.worktreeRoot, patchPath);
|
|
@@ -438,13 +468,13 @@ async function executeAuthor(projectPath, featureKey, opts) {
|
|
|
438
468
|
readiness_verdict: readinessBundle.readiness.overall_verdict,
|
|
439
469
|
report_path: readinessBundle.reportPath,
|
|
440
470
|
cleanup_command: plannedCleanupCommand(ctx),
|
|
441
|
-
prompt_sha256:
|
|
442
|
-
context_manifest:
|
|
471
|
+
prompt_sha256: produced.prompt_sha256,
|
|
472
|
+
context_manifest: produced.context_manifest,
|
|
443
473
|
produced_patch_sha256: patchHash,
|
|
444
|
-
model_provider:
|
|
445
|
-
model_id:
|
|
446
|
-
model_call_count:
|
|
447
|
-
tokens_used:
|
|
474
|
+
model_provider: produced.model_provider,
|
|
475
|
+
model_id: produced.model_id,
|
|
476
|
+
model_call_count: produced.model_call_count,
|
|
477
|
+
tokens_used: produced.tokens_used,
|
|
448
478
|
stdout: [
|
|
449
479
|
`Agent Team Author: ${stopHit ? "STOPPED" : "COMPLETED"}`,
|
|
450
480
|
` feature_key: ${ctx.featureKey}`,
|
|
@@ -515,6 +545,7 @@ module.exports = {
|
|
|
515
545
|
addedPatchContent,
|
|
516
546
|
scanProducedPatchForSecrets,
|
|
517
547
|
renderDryRunAuthorPlan,
|
|
548
|
+
produceAuthorPatch,
|
|
518
549
|
dryRunAuthor,
|
|
519
550
|
executeAuthor,
|
|
520
551
|
runAuthor,
|
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const crypto = require("crypto");
|
|
4
|
+
const { ValidationError } = require("./errors");
|
|
5
|
+
const { safeSegment } = require("./agent-team-export");
|
|
6
|
+
const { redact } = require("./trust-redact");
|
|
7
|
+
|
|
8
|
+
const SESSION_MAX_ITERATIONS = 3;
|
|
9
|
+
const SESSION_MAX_COST_USD = 3.00;
|
|
10
|
+
const SESSION_MAX_OUTPUT_TOKENS = 48000;
|
|
11
|
+
const SESSION_WALLCLOCK_TIMEOUT_MS = 30 * 60 * 1000;
|
|
12
|
+
const SESSION_DOC_TARGET_PATTERNS = Object.freeze([
|
|
13
|
+
"docs/**/*.md",
|
|
14
|
+
"governance/**/*.md",
|
|
15
|
+
"README.md",
|
|
16
|
+
"AGENTS.md",
|
|
17
|
+
]);
|
|
18
|
+
const SESSION_ALLOWED_COMMANDS = Object.freeze([
|
|
19
|
+
"python3 scripts/ci/docs_lint.py",
|
|
20
|
+
"python3 scripts/ci/path_check.py",
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
const activeSessionIds = new Set();
|
|
24
|
+
|
|
25
|
+
function asArray(value) {
|
|
26
|
+
return Array.isArray(value) ? value : [];
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function sha256(value) {
|
|
30
|
+
return crypto.createHash("sha256").update(String(value || "")).digest("hex");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function makeSessionId(featureKey, seed) {
|
|
34
|
+
if (seed) return safeSegment(seed, "session_id");
|
|
35
|
+
const stamp = Date.now().toString(36);
|
|
36
|
+
const rand = crypto.randomUUID().replace(/-/g, "").slice(0, 12);
|
|
37
|
+
return safeSegment(`${featureKey}_${stamp}_${rand}`, "session_id");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function normalizeCommand(value) {
|
|
41
|
+
return String(value || "").trim();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function pinAllowedCommands(commands) {
|
|
45
|
+
const seen = new Set();
|
|
46
|
+
const out = [];
|
|
47
|
+
for (const command of asArray(commands).map(normalizeCommand)) {
|
|
48
|
+
if (SESSION_ALLOWED_COMMANDS.includes(command) && !seen.has(command)) {
|
|
49
|
+
seen.add(command);
|
|
50
|
+
out.push(command);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
if (out.length === 0) {
|
|
54
|
+
throw new ValidationError("FAIL_NO_ALLOWED_COMMANDS: no role verification command matches the Phase E session allowlist.");
|
|
55
|
+
}
|
|
56
|
+
return Object.freeze(out);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function pinAllowedScopes(ctx) {
|
|
60
|
+
const scopes = asArray(ctx && ctx.allowedFileScopes).map((scope) => String(scope || "").trim()).filter(Boolean);
|
|
61
|
+
if (scopes.length === 0) {
|
|
62
|
+
throw new ValidationError("FAIL_EXECUTE_SCOPE: Phase E requires pinned allowed_file_scopes.");
|
|
63
|
+
}
|
|
64
|
+
return Object.freeze(scopes);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function collectTaskList(plan) {
|
|
68
|
+
const items = [];
|
|
69
|
+
for (const value of asArray(plan && plan.implementation_slices)) {
|
|
70
|
+
if (value) items.push(String(value));
|
|
71
|
+
}
|
|
72
|
+
for (const role of asArray(plan && plan.roles)) {
|
|
73
|
+
if (role && role.objective) items.push(String(role.objective));
|
|
74
|
+
for (const value of asArray(role && role.evidence_required)) {
|
|
75
|
+
items.push(`evidence_required:${role.role}:${value}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return items;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function pinScope(ctx) {
|
|
82
|
+
const source = ctx || {};
|
|
83
|
+
return Object.freeze({
|
|
84
|
+
feature_key: source.featureKey,
|
|
85
|
+
run_id: source.runId,
|
|
86
|
+
role: source.role && source.role.role ? String(source.role.role) : "dev",
|
|
87
|
+
allowed_file_scopes: pinAllowedScopes(source),
|
|
88
|
+
doc_target_patterns: SESSION_DOC_TARGET_PATTERNS,
|
|
89
|
+
verification_commands: pinAllowedCommands(source.verificationCommands),
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function redactedTaskList(plan) {
|
|
94
|
+
return collectTaskList(plan).map((item) => redact(item));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function enumerateCarriedState(data) {
|
|
98
|
+
const source = data || {};
|
|
99
|
+
const priorPatchHashes = asArray(source.priorPatchHashes).map((hash) => String(hash));
|
|
100
|
+
return Object.freeze({
|
|
101
|
+
cumulativeWorktreePath: source.cumulativeWorktreePath ? redact(String(source.cumulativeWorktreePath)) : null,
|
|
102
|
+
taskListFromPinnedPlan: redactedTaskList(source.plan),
|
|
103
|
+
priorPatchHashes: Object.freeze(priorPatchHashes),
|
|
104
|
+
accumulators: Object.freeze({
|
|
105
|
+
iteration: Number(source.iteration || 0),
|
|
106
|
+
session_cost_usd: Number(source.session_cost_usd || 0),
|
|
107
|
+
session_output_tokens: Number(source.session_output_tokens || 0),
|
|
108
|
+
}),
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function projectedCost(projectedNextCall) {
|
|
113
|
+
const call = projectedNextCall || {};
|
|
114
|
+
if (call.pricing_unknown === true || call.model_id_unknown === true) {
|
|
115
|
+
throw new ValidationError("FAIL_MODEL_PRICING_UNKNOWN: model pricing is not pinned for this session iteration.");
|
|
116
|
+
}
|
|
117
|
+
const value = call.projected_cost_usd === undefined ? 0 : Number(call.projected_cost_usd);
|
|
118
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
119
|
+
throw new ValidationError("FAIL_MODEL_PRICING_UNKNOWN: model pricing is not pinned for this session iteration.");
|
|
120
|
+
}
|
|
121
|
+
return value;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function projectedTokens(projectedNextCall) {
|
|
125
|
+
const value = projectedNextCall && projectedNextCall.projected_output_tokens !== undefined
|
|
126
|
+
? Number(projectedNextCall.projected_output_tokens)
|
|
127
|
+
: 0;
|
|
128
|
+
if (!Number.isFinite(value) || value < 0) {
|
|
129
|
+
throw new ValidationError("FAIL_SESSION_TOKEN_CAP: projected output tokens are not evaluable.");
|
|
130
|
+
}
|
|
131
|
+
return value;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function createSleepSession(input) {
|
|
135
|
+
const options = input || {};
|
|
136
|
+
const featureKey = safeSegment(options.featureKey, "feature_key");
|
|
137
|
+
const sessionId = makeSessionId(featureKey, options.sessionId);
|
|
138
|
+
const now = typeof options.nowMs === "function" ? options.nowMs : () => Date.now();
|
|
139
|
+
const startedAtMs = Number(options.startedAtMs === undefined ? now() : options.startedAtMs);
|
|
140
|
+
const pinnedScope = options.pinnedScope || null;
|
|
141
|
+
let iteration = 0;
|
|
142
|
+
let sessionCostUsd = 0;
|
|
143
|
+
let sessionOutputTokens = 0;
|
|
144
|
+
let killed = false;
|
|
145
|
+
const priorPatchHashes = [];
|
|
146
|
+
|
|
147
|
+
function snapshot(extra) {
|
|
148
|
+
const info = extra || {};
|
|
149
|
+
return {
|
|
150
|
+
session_id: sessionId,
|
|
151
|
+
feature_key: featureKey,
|
|
152
|
+
iteration,
|
|
153
|
+
session_cost_usd: sessionCostUsd,
|
|
154
|
+
session_output_tokens: sessionOutputTokens,
|
|
155
|
+
killed,
|
|
156
|
+
started_at_ms: startedAtMs,
|
|
157
|
+
pinned_scope: pinnedScope,
|
|
158
|
+
prior_patch_hashes: priorPatchHashes.slice(),
|
|
159
|
+
carried_state: enumerateCarriedState({
|
|
160
|
+
cumulativeWorktreePath: info.cumulativeWorktreePath,
|
|
161
|
+
plan: info.plan,
|
|
162
|
+
priorPatchHashes,
|
|
163
|
+
iteration,
|
|
164
|
+
session_cost_usd: sessionCostUsd,
|
|
165
|
+
session_output_tokens: sessionOutputTokens,
|
|
166
|
+
}),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function assertCanStartIteration(projectedNextCall) {
|
|
171
|
+
if (killed) {
|
|
172
|
+
throw new ValidationError("FAIL_SESSION_KILLED: sleep execute session was killed.");
|
|
173
|
+
}
|
|
174
|
+
if (iteration >= SESSION_MAX_ITERATIONS) {
|
|
175
|
+
throw new ValidationError(`FAIL_SESSION_ITERATION_CAP: max iterations reached (${SESSION_MAX_ITERATIONS}).`);
|
|
176
|
+
}
|
|
177
|
+
if (now() - startedAtMs >= SESSION_WALLCLOCK_TIMEOUT_MS) {
|
|
178
|
+
throw new ValidationError("FAIL_SESSION_WALLCLOCK_CAP: 30-minute session wall-clock exceeded.");
|
|
179
|
+
}
|
|
180
|
+
const nextCost = projectedCost(projectedNextCall);
|
|
181
|
+
const nextTokens = projectedTokens(projectedNextCall);
|
|
182
|
+
if (sessionCostUsd + nextCost > SESSION_MAX_COST_USD) {
|
|
183
|
+
throw new ValidationError("FAIL_SESSION_COST_CAP: projected session cost exceeds $3.00.");
|
|
184
|
+
}
|
|
185
|
+
if (sessionOutputTokens + nextTokens > SESSION_MAX_OUTPUT_TOKENS) {
|
|
186
|
+
throw new ValidationError("FAIL_SESSION_TOKEN_CAP: projected session output tokens exceed 48000.");
|
|
187
|
+
}
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function recordIteration(usage) {
|
|
192
|
+
const info = usage || {};
|
|
193
|
+
const cost = Number(info.cost_usd === undefined ? 0 : info.cost_usd);
|
|
194
|
+
const tokens = Number(info.output_tokens === undefined ? 0 : info.output_tokens);
|
|
195
|
+
if (!Number.isFinite(cost) || cost < 0 || !Number.isFinite(tokens) || tokens < 0) {
|
|
196
|
+
throw new ValidationError("unknown_risk_stop: session usage must be non-negative and evaluable.");
|
|
197
|
+
}
|
|
198
|
+
const patchHash = info.produced_patch_sha256 ? String(info.produced_patch_sha256) : null;
|
|
199
|
+
sessionCostUsd += cost;
|
|
200
|
+
sessionOutputTokens += tokens;
|
|
201
|
+
iteration += 1;
|
|
202
|
+
if (patchHash) priorPatchHashes.push(patchHash);
|
|
203
|
+
return snapshot(info);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function killSession(reason) {
|
|
207
|
+
killed = true;
|
|
208
|
+
return { killed: true, reason: reason || "killed" };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return Object.freeze({
|
|
212
|
+
session_id: sessionId,
|
|
213
|
+
feature_key: featureKey,
|
|
214
|
+
started_at_ms: startedAtMs,
|
|
215
|
+
pinned_scope: pinnedScope,
|
|
216
|
+
assertCanStartIteration,
|
|
217
|
+
recordIteration,
|
|
218
|
+
killSession,
|
|
219
|
+
snapshot,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function assertPinnedScope(session, ctx) {
|
|
224
|
+
if (!session || !session.pinned_scope) {
|
|
225
|
+
throw new ValidationError("scope_lock: Phase E session scope is not pinned.");
|
|
226
|
+
}
|
|
227
|
+
const current = pinScope(ctx);
|
|
228
|
+
const pinned = session.pinned_scope;
|
|
229
|
+
const sameScopes = JSON.stringify(current.allowed_file_scopes) === JSON.stringify(pinned.allowed_file_scopes);
|
|
230
|
+
const sameCommands = JSON.stringify(current.verification_commands) === JSON.stringify(pinned.verification_commands);
|
|
231
|
+
const sameRole = current.role === pinned.role;
|
|
232
|
+
if (!sameScopes || !sameCommands || !sameRole) {
|
|
233
|
+
throw new ValidationError("scope_lock: pinned Phase E session scope changed during the session.");
|
|
234
|
+
}
|
|
235
|
+
return true;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function withSessionLease(sessionId, fn) {
|
|
239
|
+
const safeSessionId = safeSegment(sessionId, "session_id");
|
|
240
|
+
if (activeSessionIds.has(safeSessionId)) {
|
|
241
|
+
throw new ValidationError("FAIL_SESSION_REENTRY: sleep execute session is already active; resume/reentry is not available in Preview.");
|
|
242
|
+
}
|
|
243
|
+
activeSessionIds.add(safeSessionId);
|
|
244
|
+
try {
|
|
245
|
+
return await fn();
|
|
246
|
+
} finally {
|
|
247
|
+
activeSessionIds.delete(safeSessionId);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function sessionStopConditionFromError(error) {
|
|
252
|
+
const message = error && error.message ? String(error.message) : String(error || "unknown_risk_stop");
|
|
253
|
+
if (message.includes("FAIL_SESSION_COST_CAP")) return "FAIL_SESSION_COST_CAP";
|
|
254
|
+
if (message.includes("FAIL_SESSION_TOKEN_CAP")) return "FAIL_SESSION_TOKEN_CAP";
|
|
255
|
+
if (message.includes("FAIL_SESSION_ITERATION_CAP")) return "action_count_cap";
|
|
256
|
+
if (message.includes("FAIL_SESSION_WALLCLOCK_CAP")) return "action_count_cap";
|
|
257
|
+
if (message.includes("FAIL_MODEL_PRICING_UNKNOWN")) return "FAIL_MODEL_PRICING_UNKNOWN";
|
|
258
|
+
if (message.includes("scope_lock")) return "scope_lock";
|
|
259
|
+
if (message.includes("FAIL_SESSION_KILLED")) return "unknown_risk_stop";
|
|
260
|
+
if (message.includes("FAIL_SESSION_REENTRY")) return "unknown_risk_stop";
|
|
261
|
+
return "unknown_risk_stop";
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
module.exports = {
|
|
265
|
+
SESSION_MAX_ITERATIONS,
|
|
266
|
+
SESSION_MAX_COST_USD,
|
|
267
|
+
SESSION_MAX_OUTPUT_TOKENS,
|
|
268
|
+
SESSION_WALLCLOCK_TIMEOUT_MS,
|
|
269
|
+
SESSION_DOC_TARGET_PATTERNS,
|
|
270
|
+
SESSION_ALLOWED_COMMANDS,
|
|
271
|
+
sha256,
|
|
272
|
+
pinScope,
|
|
273
|
+
assertPinnedScope,
|
|
274
|
+
enumerateCarriedState,
|
|
275
|
+
createSleepSession,
|
|
276
|
+
withSessionLease,
|
|
277
|
+
sessionStopConditionFromError,
|
|
278
|
+
};
|
package/src/lib/trust-events.js
CHANGED
|
@@ -132,6 +132,14 @@ function buildEvent(raw) {
|
|
|
132
132
|
? String(source.execution_mode) : null;
|
|
133
133
|
const workflowType = source.workflow_type != null
|
|
134
134
|
? String(source.workflow_type) : null;
|
|
135
|
+
const iterationIndex = typeof source.iteration_index === "number"
|
|
136
|
+
? source.iteration_index : null;
|
|
137
|
+
const readinessVerdict = source.readiness_verdict != null
|
|
138
|
+
? String(source.readiness_verdict) : null;
|
|
139
|
+
const sessionCostUsd = typeof source.session_cost_usd === "number"
|
|
140
|
+
? source.session_cost_usd : null;
|
|
141
|
+
const sessionOutputTokens = typeof source.session_output_tokens === "number"
|
|
142
|
+
? source.session_output_tokens : null;
|
|
135
143
|
const modelProvider = source.model_provider != null ? redact(String(source.model_provider)) : null;
|
|
136
144
|
const modelId = source.model_id != null ? redact(String(source.model_id)) : null;
|
|
137
145
|
const promptSha256 = source.prompt_sha256 != null ? String(source.prompt_sha256) : null;
|
|
@@ -172,6 +180,10 @@ function buildEvent(raw) {
|
|
|
172
180
|
...(Object.prototype.hasOwnProperty.call(source, "actions_executed") ? { actions_executed: actionsExecuted } : {}),
|
|
173
181
|
...(Object.prototype.hasOwnProperty.call(source, "execution_mode") ? { execution_mode: executionMode } : {}),
|
|
174
182
|
...(Object.prototype.hasOwnProperty.call(source, "workflow_type") ? { workflow_type: workflowType } : {}),
|
|
183
|
+
...(Object.prototype.hasOwnProperty.call(source, "iteration_index") ? { iteration_index: iterationIndex } : {}),
|
|
184
|
+
...(Object.prototype.hasOwnProperty.call(source, "readiness_verdict") ? { readiness_verdict: readinessVerdict } : {}),
|
|
185
|
+
...(Object.prototype.hasOwnProperty.call(source, "session_cost_usd") ? { session_cost_usd: sessionCostUsd } : {}),
|
|
186
|
+
...(Object.prototype.hasOwnProperty.call(source, "session_output_tokens") ? { session_output_tokens: sessionOutputTokens } : {}),
|
|
175
187
|
...(Object.prototype.hasOwnProperty.call(source, "model_provider") ? { model_provider: modelProvider } : {}),
|
|
176
188
|
...(Object.prototype.hasOwnProperty.call(source, "model_id") ? { model_id: modelId } : {}),
|
|
177
189
|
...(Object.prototype.hasOwnProperty.call(source, "prompt_sha256") ? { prompt_sha256: promptSha256 } : {}),
|