sdtk-code-kit 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,7 +17,7 @@ For the full end-user guide, use:
17
17
  ## Public Package Truth
18
18
 
19
19
  - package: `sdtk-code-kit`
20
- - version in this source snapshot: `0.1.3`
20
+ - version in this source snapshot: `0.4.0`
21
21
  - command: `sdtk-code`
22
22
  - latest published version lookup: `npm view sdtk-code-kit version`
23
23
  - primary workflow-first surface:
@@ -194,6 +194,18 @@ Important boundary:
194
194
  - the review packet is an evidence package for downstream QA/controller review
195
195
  - it does not replace QA release authority and it is not a final approval artifact
196
196
 
197
+ ## Sleep Mode (free readiness gate + Pro unattended execution)
198
+
199
+ Free (dry-run, nothing is executed):
200
+ - `sdtk-code sleep plan --feature-key <KEY>` assembles a bounded plan from the CODE_HANDOFF. Declare the file scope the run may touch with `--allowed <glob>` / `--blocked <glob>` (repeatable) or `--scope-file <path>` (a JSON `{ "allowed_file_scopes": [...], "blocked_file_scopes": [...] }`).
201
+ - `sdtk-code sleep report --feature-key <KEY>` grades the plan `READY_TO_SLEEP` or `NOT_READY` with the blocker/warning list.
202
+
203
+ Pro (entitlement-gated, capability `code.sleep.execute`):
204
+ - `sdtk-code sleep authorize --feature-key <KEY>` is the attended consent step. It requires an active Pro entitlement, a `READY_TO_SLEEP` plan/report, a bounded declared scope, and an exact typed confirmation on an interactive TTY. It writes `.sdtk/trust/sleep-authorization.json`, cryptographically bound (sha256) to the exact sleep-plan bytes and pinned scope, with budget caps and a TTL (defaults: 3 iterations / $3.00 / 8h; per-authorization raisable up to 10 / $10.00 / 24h).
205
+ - `sdtk-code sleep execute --feature-key <KEY>` runs the bounded session headlessly against a valid, unexpired authorization — the actual "work while you are away" capability. It reuses the same stop conditions, budgets, and doc-class patch guards as the attended `agent-team sleep-execute` preview. Editing the plan, broadening the scope, or letting the authorization expire invalidates it and the run fails closed.
206
+
207
+ Boundaries: v1 authorizes doc-class patches only (`docs/**.md`, `governance/**.md`, `README.md`, `AGENTS.md`). The **CLI** exposes no unattended path without an active Pro entitlement and the installed `sleep-execute-pro` pack. The engine function itself ships in the public kit, so a caller who can already run arbitrary Node on the machine can invoke it directly — but any such call is still bounded by the same envelope every path enforces: doc-class patch guard, hard ceilings (10 iterations / $10.00 / 24h TTL), per-iteration readiness re-check, pinned scope, and worktree isolation with no auto-merge. Entitlement is a licensing/honesty boundary, not a defense against local code execution. Model/API cost is user-provided via your own provider key, not SDTK-hosted.
208
+
197
209
  ## References
198
210
 
199
211
  - Canonical end-user guide:
@@ -0,0 +1,9 @@
1
+ -----BEGIN PUBLIC KEY-----
2
+ MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuxpjOnU2tGqY4jqQIWWQ
3
+ mMTStgAAri8UguT+okkLEOjPav+bnHU2brobXadkVvsiX5P0cSjvjKSCdxjD97uM
4
+ MCRhCzhSJ27cHkWdXzlREpI2xUaQK78Mmv712zuCzoQbNp4cKcDTxXFsaAdJd5S8
5
+ 0S88lPdiWFv6DI+tN1t0U7Lv3v3iIEtHdzRkYNxX958tHHuZWIrvJ6oQushZLngy
6
+ /WpD9L3/ZraAtf+eBcK4bVc5nvcdvoQx+OEygr0tfRJlFqRp/cHkz/MyHSu7yXWa
7
+ NtUD/zYb9jnN/DmG5O3kTD8iIQYzBErAzQ9bfMGm0J4QgTctxZLdDCy9zpBeNXva
8
+ QwIDAQAB
9
+ -----END PUBLIC KEY-----
@@ -26,4 +26,4 @@ a85c93883197eef41f5392875b41a19b8cdeb3b14b3c6fb5a6dbfb6f21a1b825 toolkit/skills
26
26
  967ec7e8a0a7951e3423c4e0f92c7471912e3a03ea23dc572c392e5a37edc266 toolkit/skills/code-tdd/SKILL.md
27
27
  6df69cf2db69d13672b3e73a2c25aca48791e9ea912c1e1fbc3ce7734399c346 toolkit/skills/code-verify/SKILL.md
28
28
  194cf6ec70eae013c03d06f397d4bbaca73256ad69be681ad14812493a3d1962 toolkit/skills/code-worktree/SKILL.md
29
- 7b3e27b56153160b44b5813e63ee8f762ee6f4338157480934ec4860f4914884 toolkit/templates/CODE_WORKFLOW_TEMPLATE.md
29
+ 7b3e27b56153160b44b5813e63ee8f762ee6f4338157480934ec4860f4914884 toolkit/templates/CODE_WORKFLOW_TEMPLATE.md
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sdtk-code-kit",
3
- "version": "0.3.4",
3
+ "version": "0.4.0",
4
4
  "description": "Workflow-first coding process toolkit: start, plan, build, verify, ship, and runtime setup.",
5
5
  "bin": {
6
6
  "sdtk-code": "bin/sdtk-code.js"
@@ -20,6 +20,7 @@ function cmdHelp() {
20
20
  " init Initialize SDTK-CODE workspace",
21
21
  " runtime Manage runtime asset installation (install, uninstall, status)",
22
22
  " agent-team Plan/preview/export/evidence plus bounded docs/governance Markdown execute/author/sleep-execute",
23
+ " sleep Sleep Mode: plan/report readiness dry-run (free) + authorize/execute (Pro, entitlement-gated)",
23
24
  "",
24
25
  "Workflow status:",
25
26
  " Implemented now: start, plan, build, verify, ship, status, doctor, resume",
@@ -176,6 +177,15 @@ function cmdHelp() {
176
177
  " implementation correctness. Human review required before acting on this verdict.",
177
178
  " run is not available in this phase; execute never spawns LLM agents and never auto-merges.",
178
179
  " No .codex/agents or .claude files are written.",
180
+ "",
181
+ "Sleep Mode:",
182
+ " sdtk-code sleep plan --feature-key <KEY> [--allowed <glob>]... [--blocked <glob>]... [--scope-file <path>] [--max-actions <n>] [--max-iterations <n>] [--project-path <path>]",
183
+ " sdtk-code sleep report --feature-key <KEY> [--project-path <path>]",
184
+ " sdtk-code sleep authorize --feature-key <KEY> [--max-iterations <n>] [--max-cost-usd <x>] [--ttl-hours <h>] [--project-path <path>]",
185
+ " sdtk-code sleep execute --feature-key <KEY> [--session-id <id>] [--project-path <path>]",
186
+ " plan/report are the free dry-run readiness gate; nothing is executed by them.",
187
+ " authorize is the attended Pro step: an exact typed TTY confirmation writes a sha256-bound, TTL-limited sleep-authorization artifact (doc-class patches only in v1).",
188
+ " execute is Pro and entitlement-gated (capability code.sleep.execute): it runs the bounded Phase E session headlessly, ONLY against a valid unexpired authorization, inside the same stop conditions, budgets, and patch guards; editing the plan or scope after authorize invalidates the artifact.",
179
189
  "",
180
190
  "Runtime options:",
181
191
  " --runtime <codex|claude> Target runtime (required)",
@@ -1,6 +1,8 @@
1
1
  "use strict";
2
2
 
3
+ const fs = require("fs");
3
4
  const path = require("path");
5
+ const readline = require("readline");
4
6
  const { parseFlags, requireFlag } = require("../lib/args");
5
7
  const { ValidationError } = require("../lib/errors");
6
8
  const { assembleSleepPlan, writeSleepPlan } = require("../lib/sleep-plan");
@@ -11,6 +13,15 @@ const {
11
13
  renderSleepReportMarkdown,
12
14
  writeSleepReport,
13
15
  } = require("../lib/sleep-report");
16
+ const { createSleepAuthorization, authorizationPath } = require("../lib/sleep-authorization");
17
+ const {
18
+ checkSleepExecuteCapability,
19
+ loadSleepExecuteHandler,
20
+ SLEEP_EXECUTE_CAPABILITY,
21
+ } = require("../lib/code-premium-loader");
22
+ const { executeSleepSession } = require("../lib/agent-team-sleep-execute");
23
+ const { loadExecuteContext } = require("../lib/agent-team-execute");
24
+ const { pinScope } = require("../lib/agent-team-sleep-session");
14
25
  const { appendEvent } = require("../lib/trust-events");
15
26
 
16
27
  const FLAG_DEFS = {
@@ -18,8 +29,74 @@ const FLAG_DEFS = {
18
29
  "project-path": { type: "string" },
19
30
  "max-actions": { type: "string" },
20
31
  "max-iterations": { type: "string" },
32
+ // BK-340 W1: declare file scopes at plan time from the CLI (previously the
33
+ // only path was hand-editing optional CODE_HANDOFF JSON fields).
34
+ "allowed": { type: "string", multiple: true },
35
+ "blocked": { type: "string", multiple: true },
36
+ "scope-file": { type: "string" },
21
37
  };
22
38
 
39
+ const AUTHORIZE_FLAG_DEFS = {
40
+ "feature-key": { type: "string" },
41
+ "project-path": { type: "string" },
42
+ "max-iterations": { type: "string" },
43
+ "max-cost-usd": { type: "string" },
44
+ "ttl-hours": { type: "string" },
45
+ };
46
+
47
+ const EXECUTE_FLAG_DEFS = {
48
+ "feature-key": { type: "string" },
49
+ "project-path": { type: "string" },
50
+ "session-id": { type: "string" },
51
+ };
52
+
53
+ function readLineFromStdin(promptText) {
54
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
55
+ return new Promise((resolve) => {
56
+ rl.question(promptText, (answer) => {
57
+ rl.close();
58
+ resolve(answer);
59
+ });
60
+ });
61
+ }
62
+
63
+ // BK-340 W1: read declared scopes from --allowed/--blocked flags or a JSON
64
+ // --scope-file ({"allowed_file_scopes": [...], "blocked_file_scopes": [...]}).
65
+ // Returns undefined when neither is used so assembleSleepPlan falls back to
66
+ // the CODE_HANDOFF-declared scopes exactly as before.
67
+ function resolveScopeFlags(flags) {
68
+ const inlineAllowed = Array.isArray(flags.allowed) ? flags.allowed : [];
69
+ const inlineBlocked = Array.isArray(flags.blocked) ? flags.blocked : [];
70
+ const hasInline = inlineAllowed.length > 0 || inlineBlocked.length > 0;
71
+ const scopeFile = flags["scope-file"];
72
+
73
+ if (scopeFile && hasInline) {
74
+ throw new ValidationError(
75
+ "Use either --scope-file or inline --allowed/--blocked flags, not both."
76
+ );
77
+ }
78
+ if (scopeFile) {
79
+ let parsed;
80
+ try {
81
+ parsed = JSON.parse(fs.readFileSync(path.resolve(scopeFile), "utf8"));
82
+ } catch (err) {
83
+ throw new ValidationError(`--scope-file could not be read as JSON: ${err.message}`);
84
+ }
85
+ const allowed = Array.isArray(parsed.allowed_file_scopes) ? parsed.allowed_file_scopes : [];
86
+ const blocked = Array.isArray(parsed.blocked_file_scopes) ? parsed.blocked_file_scopes : [];
87
+ if (allowed.length === 0 && blocked.length === 0) {
88
+ throw new ValidationError(
89
+ "--scope-file must declare allowed_file_scopes and/or blocked_file_scopes arrays."
90
+ );
91
+ }
92
+ return { allowed, blocked };
93
+ }
94
+ if (hasInline) {
95
+ return { allowed: inlineAllowed, blocked: inlineBlocked };
96
+ }
97
+ return undefined;
98
+ }
99
+
23
100
  function cmdSleepPlan(args) {
24
101
  const { flags, positional } = parseFlags(args, FLAG_DEFS);
25
102
  if (positional.length > 0) {
@@ -40,6 +117,10 @@ function cmdSleepPlan(args) {
40
117
  if (flags["max-iterations"] !== undefined) {
41
118
  opts.maxIterations = flags["max-iterations"];
42
119
  }
120
+ const scopes = resolveScopeFlags(flags);
121
+ if (scopes !== undefined) {
122
+ opts.scopes = scopes;
123
+ }
43
124
 
44
125
  const plan = assembleSleepPlan(projectPath, featureKey, opts);
45
126
  const outPath = writeSleepPlan(projectPath, plan);
@@ -108,10 +189,140 @@ function cmdSleepReport(args) {
108
189
  return 0;
109
190
  }
110
191
 
192
+ // BK-340 — attended authorization step. Requires an active Pro entitlement
193
+ // (checked up front for honest UX), a READY_TO_SLEEP plan/report, a pinned
194
+ // bounded agent-team scope, and an exact typed TTY confirmation. Writes the
195
+ // sha256-bound, TTL'd sleep-authorization artifact that `sleep execute`
196
+ // (the Pro pack) validates headlessly.
197
+ async function cmdSleepAuthorize(args) {
198
+ const { flags, positional } = parseFlags(args, AUTHORIZE_FLAG_DEFS);
199
+ if (positional.length > 0) {
200
+ throw new ValidationError(
201
+ 'Unexpected positional arguments. Use flags only for "sleep authorize".'
202
+ );
203
+ }
204
+
205
+ const featureKey = requireFlag(flags, "feature-key", "feature-key");
206
+ const projectPath = flags["project-path"]
207
+ ? path.resolve(flags["project-path"])
208
+ : process.cwd();
209
+
210
+ const capabilityCheck = checkSleepExecuteCapability();
211
+ if (!capabilityCheck.ok) {
212
+ throw new ValidationError(capabilityCheck.message);
213
+ }
214
+
215
+ const { outPath, authorization } = await createSleepAuthorization(projectPath, featureKey, {
216
+ maxIterations: flags["max-iterations"],
217
+ maxCostUsd: flags["max-cost-usd"],
218
+ ttlHours: flags["ttl-hours"],
219
+ confirmInput: {
220
+ isTTY: process.stdin.isTTY === true,
221
+ readLine: readLineFromStdin,
222
+ },
223
+ });
224
+
225
+ appendEvent(projectPath, {
226
+ toolkit: "sdtk-code",
227
+ event_type: "sleep_authorize",
228
+ command: `sdtk-code sleep authorize --feature-key ${featureKey}`,
229
+ status: "ok",
230
+ feature_key: featureKey,
231
+ output_path: outPath,
232
+ expires_at: authorization.expires_at,
233
+ max_iterations: authorization.budgets.max_iterations,
234
+ max_cost_usd: authorization.budgets.max_cost_usd,
235
+ patch_class: authorization.patch_class,
236
+ });
237
+
238
+ console.log(`sleep-authorization written: ${outPath}`);
239
+ console.log(` feature_key: ${authorization.feature_key}`);
240
+ console.log(` expires_at: ${authorization.expires_at}`);
241
+ console.log(` max_iterations: ${authorization.budgets.max_iterations}`);
242
+ console.log(` max_cost_usd: $${authorization.budgets.max_cost_usd.toFixed(2)}`);
243
+ console.log(` patch_class: ${authorization.patch_class}`);
244
+ console.log(` plan_sha256: ${authorization.plan_sha256}`);
245
+ console.log("Next: sdtk-code sleep execute --feature-key " + featureKey);
246
+ return 0;
247
+ }
248
+
249
+ // BK-340 — Pro headless execution. The premium loader is the ONLY path to a
250
+ // non-TTY sleep session: it verifies the signed entitlement + pack integrity,
251
+ // and the pack validates the authorization artifact (expiry, plan/scope
252
+ // sha256 binding, budget ceilings) before driving the unchanged Phase E
253
+ // engine with a pre-authorized confirm strategy.
254
+ async function cmdSleepExecute(args) {
255
+ const { flags, positional } = parseFlags(args, EXECUTE_FLAG_DEFS);
256
+ if (positional.length > 0) {
257
+ throw new ValidationError(
258
+ 'Unexpected positional arguments. Use flags only for "sleep execute".'
259
+ );
260
+ }
261
+
262
+ const featureKey = requireFlag(flags, "feature-key", "feature-key");
263
+ const projectPath = flags["project-path"]
264
+ ? path.resolve(flags["project-path"])
265
+ : process.cwd();
266
+
267
+ const loaded = await loadSleepExecuteHandler();
268
+ if (!loaded.ok) {
269
+ appendEvent(projectPath, {
270
+ toolkit: "sdtk-code",
271
+ event_type: "sleep_execute",
272
+ command: `sdtk-code sleep execute --feature-key ${featureKey}`,
273
+ status: "blocked",
274
+ feature_key: featureKey,
275
+ capability: SLEEP_EXECUTE_CAPABILITY,
276
+ reason: loaded.message,
277
+ });
278
+ console.error(loaded.message);
279
+ return loaded.exitCode;
280
+ }
281
+
282
+ const result = await loaded.handler({
283
+ projectPath,
284
+ featureKey,
285
+ options: {
286
+ sessionId: flags["session-id"],
287
+ },
288
+ deps: {
289
+ executeSleepSession,
290
+ loadExecuteContext,
291
+ pinScope,
292
+ authorizationPath,
293
+ },
294
+ });
295
+
296
+ appendEvent(projectPath, {
297
+ toolkit: "sdtk-code",
298
+ event_type: "sleep_execute",
299
+ command: `sdtk-code sleep execute --feature-key ${featureKey}`,
300
+ status: result.status,
301
+ feature_key: result.feature_key,
302
+ run_id: result.run_id,
303
+ session_id: result.session_id,
304
+ readiness_verdict: result.readiness_verdict,
305
+ stop_condition_hit: result.stop_condition_hit,
306
+ worktree_path: result.worktree_path,
307
+ actions_executed: result.actions_executed,
308
+ execution_mode: result.execution_mode,
309
+ authorization_expires_at: result.authorization_expires_at,
310
+ session_cost_usd: result.session_cost_usd,
311
+ session_output_tokens: result.session_output_tokens,
312
+ });
313
+
314
+ console.log(result.stdout || `Sleep Execute: ${result.status}`);
315
+ return result.exitCode === undefined ? 0 : result.exitCode;
316
+ }
317
+
111
318
  function cmdSleep(args) {
112
319
  if (!args || args.length === 0) {
113
320
  throw new ValidationError(
114
- 'Usage: sdtk-code sleep <subcommand> [flags]\nSubcommands: plan, report'
321
+ 'Usage: sdtk-code sleep <subcommand> [flags]\nSubcommands: plan, report, authorize, execute\n' +
322
+ ' plan Assemble the dry-run sleep plan (free). Declare scope with --allowed/--blocked or --scope-file.\n' +
323
+ ' report Grade READY_TO_SLEEP / NOT_READY (free, dry-run preflight).\n' +
324
+ ' authorize Attended Pro step: typed TTY confirmation writes a sha256-bound, TTL-limited authorization artifact.\n' +
325
+ ' execute Pro, entitlement-gated: run the bounded sleep session headlessly against a valid authorization.'
115
326
  );
116
327
  }
117
328
 
@@ -122,9 +333,13 @@ function cmdSleep(args) {
122
333
  return cmdSleepPlan(rest);
123
334
  case "report":
124
335
  return cmdSleepReport(rest);
336
+ case "authorize":
337
+ return cmdSleepAuthorize(rest);
338
+ case "execute":
339
+ return cmdSleepExecute(rest);
125
340
  default:
126
341
  throw new ValidationError(
127
- `Unknown sleep subcommand: "${subcommand}". Available: plan, report`
342
+ `Unknown sleep subcommand: "${subcommand}". Available: plan, report, authorize, execute`
128
343
  );
129
344
  }
130
345
  }
@@ -290,13 +290,28 @@ async function executeSleepSession(projectPath, featureKey, opts) {
290
290
  const { plan: sleepPlan } = loadSleepPlan(ctx.projectPath, ctx.featureKey);
291
291
  const sessionId = options.sessionId ? safeSegment(options.sessionId, "session_id") : `${ctx.runId}_sleep`;
292
292
  const pinnedScope = pinScope(ctx);
293
+ // BK-340: custom budgets are only reachable through an authorization-backed
294
+ // confirm strategy (the Pro pack). The free TTY phrase pins the 3/$3.00
295
+ // defaults and must never silently understate a larger authorized budget.
296
+ if (options.budgets !== undefined && typeof options.confirmStrategy !== "function") {
297
+ throw new ValidationError("FAIL_BUDGET_REQUIRES_AUTHORIZATION: custom session budgets require an authorization-backed confirm strategy.");
298
+ }
293
299
  const session = createSleepSession({
294
300
  featureKey: ctx.featureKey,
295
301
  sessionId,
296
302
  pinnedScope,
297
303
  nowMs: options.nowMs,
304
+ budgets: options.budgets,
298
305
  });
299
- await confirmSleepExecute(options.confirmInput || {}, ctx.featureKey, session.session_id);
306
+ // BK-340 seam: an injected confirm strategy (supplied only by the Pro
307
+ // sleep-execute pack after validating a pre-declared attended authorization
308
+ // artifact) replaces the interactive TTY confirmation. Default behavior —
309
+ // the Phase E attended TTY phrase — is unchanged when no strategy is given.
310
+ if (typeof options.confirmStrategy === "function") {
311
+ await options.confirmStrategy({ featureKey: ctx.featureKey, sessionId: session.session_id });
312
+ } else {
313
+ await confirmSleepExecute(options.confirmInput || {}, ctx.featureKey, session.session_id);
314
+ }
300
315
 
301
316
  return withSessionLease(session.session_id, async () => {
302
317
  let created = null;
@@ -9,6 +9,13 @@ const SESSION_MAX_ITERATIONS = 3;
9
9
  const SESSION_MAX_COST_USD = 3.00;
10
10
  const SESSION_MAX_OUTPUT_TOKENS = 48000;
11
11
  const SESSION_WALLCLOCK_TIMEOUT_MS = 30 * 60 * 1000;
12
+ // BK-340: hard engine ceilings for authorization-backed sessions (OQ-3). A
13
+ // sleep-authorization artifact may raise the per-session budgets ABOVE the
14
+ // free-tier defaults but NEVER above these — the ceilings live here, in the
15
+ // engine, so no artifact content can widen them.
16
+ const AUTHORIZED_MAX_ITERATIONS = 10;
17
+ const AUTHORIZED_MAX_COST_USD = 10.00;
18
+ const AUTHORIZED_MAX_TTL_HOURS = 24;
12
19
  const SESSION_DOC_TARGET_PATTERNS = Object.freeze([
13
20
  "docs/**/*.md",
14
21
  "governance/**/*.md",
@@ -131,6 +138,32 @@ function projectedTokens(projectedNextCall) {
131
138
  return value;
132
139
  }
133
140
 
141
+ // BK-340: validate optional authorization-backed budgets against the hard
142
+ // engine ceilings. Absent budgets keep today's free-tier defaults untouched.
143
+ function resolveSessionBudgets(budgets) {
144
+ if (budgets === undefined || budgets === null) {
145
+ return { maxIterations: SESSION_MAX_ITERATIONS, maxCostUsd: SESSION_MAX_COST_USD };
146
+ }
147
+ if (typeof budgets !== "object" || Array.isArray(budgets)) {
148
+ throw new ValidationError("FAIL_BUDGET_CEILING: session budgets must be an object when provided.");
149
+ }
150
+ const iterations = budgets.max_iterations === undefined ? SESSION_MAX_ITERATIONS : budgets.max_iterations;
151
+ const costUsd = budgets.max_cost_usd === undefined ? SESSION_MAX_COST_USD : budgets.max_cost_usd;
152
+ if (!Number.isInteger(iterations) || iterations < 1) {
153
+ throw new ValidationError("FAIL_BUDGET_CEILING: budgets.max_iterations must be a positive integer.");
154
+ }
155
+ if (iterations > AUTHORIZED_MAX_ITERATIONS) {
156
+ throw new ValidationError(`FAIL_BUDGET_CEILING: budgets.max_iterations exceeds the engine ceiling (${AUTHORIZED_MAX_ITERATIONS}).`);
157
+ }
158
+ if (!Number.isFinite(costUsd) || costUsd <= 0) {
159
+ throw new ValidationError("FAIL_BUDGET_CEILING: budgets.max_cost_usd must be a positive number.");
160
+ }
161
+ if (costUsd > AUTHORIZED_MAX_COST_USD) {
162
+ throw new ValidationError(`FAIL_BUDGET_CEILING: budgets.max_cost_usd exceeds the engine ceiling ($${AUTHORIZED_MAX_COST_USD.toFixed(2)}).`);
163
+ }
164
+ return { maxIterations: iterations, maxCostUsd: costUsd };
165
+ }
166
+
134
167
  function createSleepSession(input) {
135
168
  const options = input || {};
136
169
  const featureKey = safeSegment(options.featureKey, "feature_key");
@@ -138,6 +171,7 @@ function createSleepSession(input) {
138
171
  const now = typeof options.nowMs === "function" ? options.nowMs : () => Date.now();
139
172
  const startedAtMs = Number(options.startedAtMs === undefined ? now() : options.startedAtMs);
140
173
  const pinnedScope = options.pinnedScope || null;
174
+ const { maxIterations, maxCostUsd } = resolveSessionBudgets(options.budgets);
141
175
  let iteration = 0;
142
176
  let sessionCostUsd = 0;
143
177
  let sessionOutputTokens = 0;
@@ -171,16 +205,16 @@ function createSleepSession(input) {
171
205
  if (killed) {
172
206
  throw new ValidationError("FAIL_SESSION_KILLED: sleep execute session was killed.");
173
207
  }
174
- if (iteration >= SESSION_MAX_ITERATIONS) {
175
- throw new ValidationError(`FAIL_SESSION_ITERATION_CAP: max iterations reached (${SESSION_MAX_ITERATIONS}).`);
208
+ if (iteration >= maxIterations) {
209
+ throw new ValidationError(`FAIL_SESSION_ITERATION_CAP: max iterations reached (${maxIterations}).`);
176
210
  }
177
211
  if (now() - startedAtMs >= SESSION_WALLCLOCK_TIMEOUT_MS) {
178
212
  throw new ValidationError("FAIL_SESSION_WALLCLOCK_CAP: 30-minute session wall-clock exceeded.");
179
213
  }
180
214
  const nextCost = projectedCost(projectedNextCall);
181
215
  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.");
216
+ if (sessionCostUsd + nextCost > maxCostUsd) {
217
+ throw new ValidationError(`FAIL_SESSION_COST_CAP: projected session cost exceeds $${maxCostUsd.toFixed(2)}.`);
184
218
  }
185
219
  if (sessionOutputTokens + nextTokens > SESSION_MAX_OUTPUT_TOKENS) {
186
220
  throw new ValidationError("FAIL_SESSION_TOKEN_CAP: projected session output tokens exceed 48000.");
@@ -264,6 +298,10 @@ function sessionStopConditionFromError(error) {
264
298
  module.exports = {
265
299
  SESSION_MAX_ITERATIONS,
266
300
  SESSION_MAX_COST_USD,
301
+ AUTHORIZED_MAX_ITERATIONS,
302
+ AUTHORIZED_MAX_COST_USD,
303
+ AUTHORIZED_MAX_TTL_HOURS,
304
+ resolveSessionBudgets,
267
305
  SESSION_MAX_OUTPUT_TOKENS,
268
306
  SESSION_WALLCLOCK_TIMEOUT_MS,
269
307
  SESSION_DOC_TARGET_PATTERNS,
@@ -0,0 +1,394 @@
1
+ "use strict";
2
+
3
+ // BK-340 — sdtk-code premium loader (the kit's FIRST premium seam).
4
+ //
5
+ // Mirrors the proven sdtk-wiki single-file loader chain byte-for-byte in
6
+ // behavior: signed entitlement manifest (~/.sdtk/entitlements.json, RSA-SHA256
7
+ // over the canonicalized payload, public key bundled or via
8
+ // SDTK_ENTITLEMENT_PUBLIC_KEY) -> capability check -> premium-pack cache
9
+ // verification (~/.sdtk/packs/<product>/<id>/<version>/, sha256 pinned by the
10
+ // signed manifest) -> handler load. Fail-closed at every step: without an
11
+ // active entitlement AND an intact sleep-execute-pro pack, no headless
12
+ // sleep-execution path exists on this machine.
13
+
14
+ const crypto = require("crypto");
15
+ const fs = require("fs");
16
+ const os = require("os");
17
+ const path = require("path");
18
+
19
+ const SAFE_PACK_PART_RE = /^[A-Za-z0-9._-]+$/;
20
+ const REQUIRED_ENTITLEMENT_FIELDS = [
21
+ "schema_version",
22
+ "customer_id",
23
+ "plan",
24
+ "products",
25
+ "capabilities",
26
+ "issued_at",
27
+ "expires_at",
28
+ "offline_grace_until",
29
+ ];
30
+ const REQUIRED_PACK_FIELDS = [
31
+ "id",
32
+ "product",
33
+ "version",
34
+ "capabilities",
35
+ "source",
36
+ "sha256",
37
+ ];
38
+
39
+ const SLEEP_EXECUTE_CAPABILITY = "code.sleep.execute";
40
+
41
+ function isSafePackPathPart(value) {
42
+ return (
43
+ typeof value === "string" &&
44
+ SAFE_PACK_PART_RE.test(value) &&
45
+ value !== "." &&
46
+ value !== ".."
47
+ );
48
+ }
49
+
50
+ function getSuiteRoot() {
51
+ return path.join(os.homedir(), ".sdtk");
52
+ }
53
+
54
+ function getEntitlementsFile() {
55
+ return path.join(getSuiteRoot(), "entitlements.json");
56
+ }
57
+
58
+ function getPacksRoot() {
59
+ return path.join(getSuiteRoot(), "packs");
60
+ }
61
+
62
+ function resolvePublicKey() {
63
+ if (process.env.SDTK_ENTITLEMENT_PUBLIC_KEY) {
64
+ return process.env.SDTK_ENTITLEMENT_PUBLIC_KEY;
65
+ }
66
+
67
+ const bundledKeyPath = path.join(
68
+ __dirname,
69
+ "..",
70
+ "..",
71
+ "assets",
72
+ "keys",
73
+ "sdtk-entitlement-public.pem"
74
+ );
75
+ if (fs.existsSync(bundledKeyPath)) {
76
+ return fs.readFileSync(bundledKeyPath, "utf8");
77
+ }
78
+ return null;
79
+ }
80
+
81
+ function canonicalize(value) {
82
+ if (Array.isArray(value)) {
83
+ return value.map(canonicalize);
84
+ }
85
+ if (value !== null && typeof value === "object") {
86
+ const sorted = {};
87
+ for (const key of Object.keys(value).sort()) {
88
+ sorted[key] = canonicalize(value[key]);
89
+ }
90
+ return sorted;
91
+ }
92
+ return value;
93
+ }
94
+
95
+ function buildCanonicalPayload(manifest) {
96
+ const { signature: _signature, ...rest } = manifest;
97
+ return Buffer.from(JSON.stringify(canonicalize(rest)), "utf8");
98
+ }
99
+
100
+ function evaluateManifestObject(manifest, nowMs) {
101
+ if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) {
102
+ return { state: "malformed", manifest: null };
103
+ }
104
+
105
+ for (const field of REQUIRED_ENTITLEMENT_FIELDS) {
106
+ if (!(field in manifest)) {
107
+ return { state: "malformed", manifest };
108
+ }
109
+ }
110
+
111
+ if (typeof manifest.schema_version !== "number") {
112
+ return { state: "malformed", manifest };
113
+ }
114
+ if (typeof manifest.customer_id !== "string" || !manifest.customer_id) {
115
+ return { state: "malformed", manifest };
116
+ }
117
+ if (typeof manifest.plan !== "string" || !manifest.plan) {
118
+ return { state: "malformed", manifest };
119
+ }
120
+ if (
121
+ !manifest.products ||
122
+ typeof manifest.products !== "object" ||
123
+ Array.isArray(manifest.products)
124
+ ) {
125
+ return { state: "malformed", manifest };
126
+ }
127
+ if (!Array.isArray(manifest.capabilities)) {
128
+ return { state: "malformed", manifest };
129
+ }
130
+ if (
131
+ typeof manifest.issued_at !== "string" ||
132
+ typeof manifest.expires_at !== "string" ||
133
+ typeof manifest.offline_grace_until !== "string"
134
+ ) {
135
+ return { state: "malformed", manifest };
136
+ }
137
+ if (
138
+ !("signature" in manifest) ||
139
+ !manifest.signature ||
140
+ typeof manifest.signature !== "string"
141
+ ) {
142
+ return { state: "unsigned", manifest };
143
+ }
144
+
145
+ const publicKeyPem = resolvePublicKey();
146
+ if (!publicKeyPem) {
147
+ return { state: "untrusted-key", manifest };
148
+ }
149
+
150
+ let verified = false;
151
+ try {
152
+ const verifier = crypto.createVerify("RSA-SHA256");
153
+ verifier.update(buildCanonicalPayload(manifest));
154
+ verified = verifier.verify(publicKeyPem, Buffer.from(manifest.signature, "base64"));
155
+ } catch (_err) {
156
+ return { state: "invalid-signature", manifest };
157
+ }
158
+
159
+ if (!verified) {
160
+ return { state: "invalid-signature", manifest };
161
+ }
162
+
163
+ const now = nowMs !== undefined ? nowMs : Date.now();
164
+ const expiresAt = new Date(manifest.expires_at).getTime();
165
+ const graceUntil = new Date(manifest.offline_grace_until).getTime();
166
+ if (Number.isNaN(expiresAt) || Number.isNaN(graceUntil)) {
167
+ return { state: "malformed", manifest };
168
+ }
169
+ if (now < expiresAt) {
170
+ return { state: "active", manifest };
171
+ }
172
+ if (now < graceUntil) {
173
+ return { state: "grace", manifest };
174
+ }
175
+ return { state: "expired", manifest };
176
+ }
177
+
178
+ function loadEntitlementState() {
179
+ const filePath = getEntitlementsFile();
180
+ if (!fs.existsSync(filePath)) {
181
+ return { state: "missing", manifest: null };
182
+ }
183
+ try {
184
+ return evaluateManifestObject(JSON.parse(fs.readFileSync(filePath, "utf8")));
185
+ } catch (_err) {
186
+ return { state: "malformed", manifest: null };
187
+ }
188
+ }
189
+
190
+ function checkCapability(capability, entitlementState) {
191
+ const state = entitlementState && entitlementState.state;
192
+ const manifest = entitlementState && entitlementState.manifest;
193
+
194
+ if (state === "active" || state === "grace") {
195
+ const capabilities = manifest && Array.isArray(manifest.capabilities)
196
+ ? manifest.capabilities
197
+ : [];
198
+ if (capabilities.includes(capability)) {
199
+ return { allowed: true };
200
+ }
201
+ return {
202
+ allowed: false,
203
+ exitCode: 1,
204
+ reason: `Capability "${capability}" is not included in the local entitlement.`,
205
+ };
206
+ }
207
+
208
+ const integrityStates = new Set(["malformed", "unsigned", "untrusted-key", "invalid-signature"]);
209
+ return {
210
+ allowed: false,
211
+ exitCode: integrityStates.has(state) ? 3 : 1,
212
+ reason: `Capability "${capability}" is blocked because local entitlement state is "${state || "missing"}".`,
213
+ };
214
+ }
215
+
216
+ function computeSha256(bytes) {
217
+ return crypto.createHash("sha256").update(bytes).digest("hex");
218
+ }
219
+
220
+ function validatePackMeta(meta) {
221
+ if (!meta || typeof meta !== "object" || Array.isArray(meta)) {
222
+ return { valid: false, reason: "pack metadata is not an object" };
223
+ }
224
+
225
+ for (const field of REQUIRED_PACK_FIELDS) {
226
+ if (!(field in meta)) {
227
+ return { valid: false, reason: `missing required field: ${field}` };
228
+ }
229
+ }
230
+
231
+ if (!isSafePackPathPart(meta.id)) {
232
+ return { valid: false, reason: "id must be a safe identifier" };
233
+ }
234
+ if (!isSafePackPathPart(meta.product)) {
235
+ return { valid: false, reason: "product must be a safe identifier" };
236
+ }
237
+ if (!isSafePackPathPart(meta.version)) {
238
+ return { valid: false, reason: "version must be a safe identifier" };
239
+ }
240
+ if (!Array.isArray(meta.capabilities)) {
241
+ return { valid: false, reason: "capabilities must be an array" };
242
+ }
243
+ if (
244
+ !meta.source ||
245
+ typeof meta.source !== "object" ||
246
+ Array.isArray(meta.source) ||
247
+ meta.source.type !== "github-content" ||
248
+ typeof meta.source.path !== "string" ||
249
+ !meta.source.path
250
+ ) {
251
+ return { valid: false, reason: 'source.type must be "github-content" with a path' };
252
+ }
253
+ if (typeof meta.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(meta.sha256)) {
254
+ return { valid: false, reason: "sha256 must be a 64-character lowercase hex string" };
255
+ }
256
+ return { valid: true };
257
+ }
258
+
259
+ function getPackDir(packEntry) {
260
+ return path.join(getPacksRoot(), packEntry.product, packEntry.id, packEntry.version);
261
+ }
262
+
263
+ function getPackFile(packEntry) {
264
+ return path.join(getPackDir(packEntry), "pack.js");
265
+ }
266
+
267
+ function resolvePackState(packEntry) {
268
+ const validation = validatePackMeta(packEntry);
269
+ if (!validation.valid) {
270
+ return { state: "malformed", reason: validation.reason };
271
+ }
272
+
273
+ const packFile = getPackFile(packEntry);
274
+ const metaFile = path.join(getPackDir(packEntry), "pack.json");
275
+ if (!fs.existsSync(packFile) || !fs.existsSync(metaFile)) {
276
+ return {
277
+ state: "missing",
278
+ reason:
279
+ `Premium pack "${packEntry.id}@${packEntry.version}" is not installed for capability ${SLEEP_EXECUTE_CAPABILITY}.`,
280
+ };
281
+ }
282
+
283
+ let cachedMeta;
284
+ try {
285
+ cachedMeta = JSON.parse(fs.readFileSync(metaFile, "utf8"));
286
+ } catch (_err) {
287
+ return { state: "malformed", reason: "pack.json could not be parsed" };
288
+ }
289
+
290
+ if (!cachedMeta || cachedMeta.sha256 !== packEntry.sha256) {
291
+ return { state: "stale", reason: "pack.json hash does not match signed manifest" };
292
+ }
293
+
294
+ let bytes;
295
+ try {
296
+ bytes = fs.readFileSync(packFile);
297
+ } catch (err) {
298
+ return { state: "malformed", reason: `pack.js could not be read: ${err.message}` };
299
+ }
300
+ if (computeSha256(bytes) !== packEntry.sha256) {
301
+ return { state: "stale", reason: "pack.js hash does not match signed manifest" };
302
+ }
303
+ return { state: "present" };
304
+ }
305
+
306
+ // Capability pre-check only (no pack load) — used by `sleep authorize` so a
307
+ // user without entitlement is told up front instead of after typing the
308
+ // confirmation phrase.
309
+ function checkSleepExecuteCapability() {
310
+ const entitlementState = loadEntitlementState();
311
+ const check = checkCapability(SLEEP_EXECUTE_CAPABILITY, entitlementState);
312
+ if (!check.allowed) {
313
+ return {
314
+ ok: false,
315
+ exitCode: check.exitCode,
316
+ message:
317
+ `${check.reason} Run SDTK activation (sdtk activate --license <KEY>) to install ` +
318
+ `the Sleep Execute Pro runtime.`,
319
+ };
320
+ }
321
+ return { ok: true, entitlementState };
322
+ }
323
+
324
+ async function loadSleepExecuteHandler() {
325
+ const capability = SLEEP_EXECUTE_CAPABILITY;
326
+ const preCheck = checkSleepExecuteCapability();
327
+ if (!preCheck.ok) {
328
+ return preCheck;
329
+ }
330
+
331
+ const manifest = preCheck.entitlementState.manifest;
332
+ const packs = Array.isArray(manifest.premium_packs) ? manifest.premium_packs : [];
333
+ const packEntry = packs.find(
334
+ (pack) =>
335
+ pack &&
336
+ pack.product === "code" &&
337
+ Array.isArray(pack.capabilities) &&
338
+ pack.capabilities.includes(capability)
339
+ );
340
+ if (!packEntry) {
341
+ return {
342
+ ok: false,
343
+ exitCode: 1,
344
+ message:
345
+ `Premium pack providing "${capability}" is not available. Run SDTK activation ` +
346
+ `to install the Sleep Execute Pro runtime.`,
347
+ };
348
+ }
349
+
350
+ const packState = resolvePackState(packEntry);
351
+ if (packState.state !== "present") {
352
+ return {
353
+ ok: false,
354
+ exitCode: packState.state === "malformed" ? 3 : 1,
355
+ message:
356
+ `Premium pack for "${capability}" is not ready (${packState.state}). ` +
357
+ (packState.reason || "Refresh the local entitlement/runtime cache."),
358
+ };
359
+ }
360
+
361
+ let packModule;
362
+ try {
363
+ packModule = require(getPackFile(packEntry));
364
+ } catch (err) {
365
+ return {
366
+ ok: false,
367
+ exitCode: 4,
368
+ message: `Failed to load Sleep Execute Pro runtime pack: ${err.message}`,
369
+ };
370
+ }
371
+
372
+ const handler = typeof packModule.sleepExecute === "function" ? packModule.sleepExecute : packModule.run;
373
+ if (typeof handler !== "function") {
374
+ return {
375
+ ok: false,
376
+ exitCode: 3,
377
+ message: 'Sleep Execute Pro runtime pack must export "sleepExecute" or "run".',
378
+ };
379
+ }
380
+
381
+ return { ok: true, handler, packEntry };
382
+ }
383
+
384
+ module.exports = {
385
+ SLEEP_EXECUTE_CAPABILITY,
386
+ buildCanonicalPayload,
387
+ canonicalize,
388
+ checkCapability,
389
+ checkSleepExecuteCapability,
390
+ evaluateManifestObject,
391
+ loadEntitlementState,
392
+ loadSleepExecuteHandler,
393
+ resolvePackState,
394
+ };
@@ -0,0 +1,220 @@
1
+ "use strict";
2
+
3
+ // BK-340 — sleep-authorization WRITER (attended side).
4
+ //
5
+ // `sdtk-code sleep authorize` moves the human's deliberate consent from the
6
+ // Phase E in-session TTY confirm to a pre-declared artifact created while the
7
+ // operator is still present. The artifact binds — by sha256 — to the exact
8
+ // sleep-plan bytes and the exact pinned agent-team scope it authorizes, carries
9
+ // budget caps validated against the hard engine ceilings, and expires after a
10
+ // bounded TTL. VALIDATION of the artifact at execute time deliberately lives in
11
+ // the Pro pack (see the BK-340 spec §W4): this module only creates it.
12
+
13
+ const crypto = require("crypto");
14
+ const fs = require("fs");
15
+ const path = require("path");
16
+ const { ValidationError } = require("./errors");
17
+ const { loadSleepPlan, gatherReportSignals, projectSleepReport } = require("./sleep-report");
18
+ const { loadExecuteContext } = require("./agent-team-execute");
19
+ const { loadReadiness } = require("./agent-team-readiness");
20
+ const {
21
+ pinScope,
22
+ AUTHORIZED_MAX_ITERATIONS,
23
+ AUTHORIZED_MAX_COST_USD,
24
+ AUTHORIZED_MAX_TTL_HOURS,
25
+ SESSION_MAX_ITERATIONS,
26
+ SESSION_MAX_COST_USD,
27
+ resolveSessionBudgets,
28
+ } = require("./agent-team-sleep-session");
29
+
30
+ const AUTHORIZATION_SCHEMA = "sdtk.sleep-authorization.v1";
31
+ const DEFAULT_TTL_HOURS = 8;
32
+
33
+ function sha256Hex(bytes) {
34
+ return crypto.createHash("sha256").update(bytes).digest("hex");
35
+ }
36
+
37
+ // BK-340 F2/F3 integrity binding. Every security-relevant field is folded into
38
+ // one digest so a naive single-field edit (budgets 1->9 within ceiling, or
39
+ // expires_at -> 2099) no longer round-trips: the pack recomputes this digest at
40
+ // execute time and fail-closes on any mismatch.
41
+ //
42
+ // NOTE (honest scope, not tamper-PROOF): the artifact carries no client secret,
43
+ // so a determined local forger who understands this canonical form can recompute
44
+ // the digest and craft a valid artifact within the engine ceilings. That residual
45
+ // is accepted and documented — the digest is tamper-EVIDENCE against naive edits
46
+ // and co-resident processes that do not know the format, and the engine envelope
47
+ // (doc-class guard, hard ceilings, per-iteration readiness re-check, pinned scope,
48
+ // worktree isolation) bounds the blast radius regardless. The pack keeps a
49
+ // byte-identical copy of this function; `test_sdtk_code_sleep_execute_pro.py`
50
+ // asserts the two agree so they cannot drift.
51
+ function authorizationDigestPayload(auth) {
52
+ const a = auth || {};
53
+ const b = a.budgets || {};
54
+ return JSON.stringify([
55
+ AUTHORIZATION_SCHEMA,
56
+ a.feature_key,
57
+ a.plan_sha256,
58
+ a.pinned_scope_sha256,
59
+ b.max_iterations,
60
+ b.max_cost_usd,
61
+ a.patch_class,
62
+ a.created_at,
63
+ a.expires_at,
64
+ ]);
65
+ }
66
+
67
+ function computeAuthorizationDigest(auth) {
68
+ return sha256Hex(Buffer.from(authorizationDigestPayload(auth), "utf8"));
69
+ }
70
+
71
+ function authorizationPath(projectPath) {
72
+ return path.join(path.resolve(projectPath || "."), ".sdtk", "trust", "sleep-authorization.json");
73
+ }
74
+
75
+ function sleepPlanPath(projectPath) {
76
+ return path.join(path.resolve(projectPath || "."), ".sdtk", "trust", "sleep-plan.json");
77
+ }
78
+
79
+ function buildAuthorizationPhrase(featureKey, budgets, ttlHours) {
80
+ return (
81
+ `AUTHORIZE ${featureKey} max_iterations=${budgets.maxIterations} ` +
82
+ `cost_cap=$${budgets.maxCostUsd.toFixed(2)} ttl_hours=${ttlHours} unit=Path2-author-only`
83
+ );
84
+ }
85
+
86
+ function resolveTtlHours(value) {
87
+ const ttl = value === undefined ? DEFAULT_TTL_HOURS : Number(value);
88
+ if (!Number.isFinite(ttl) || ttl <= 0) {
89
+ throw new ValidationError("SLEEP_AUTH_TTL_INVALID: --ttl-hours must be a positive number.");
90
+ }
91
+ if (ttl > AUTHORIZED_MAX_TTL_HOURS) {
92
+ throw new ValidationError(
93
+ `SLEEP_AUTH_TTL_INVALID: --ttl-hours exceeds the engine ceiling (${AUTHORIZED_MAX_TTL_HOURS}h).`
94
+ );
95
+ }
96
+ return ttl;
97
+ }
98
+
99
+ // The attended typed confirmation. Mirrors the Phase E confirm contract:
100
+ // requires a real TTY and the exact phrase — no --yes path exists.
101
+ async function confirmAuthorization(input, phrase) {
102
+ const source = input || {};
103
+ if (source.isTTY !== true) {
104
+ throw new ValidationError(
105
+ "SLEEP_AUTH_REQUIRES_TTY: sleep authorize requires an interactive TTY confirmation."
106
+ );
107
+ }
108
+ if (typeof source.readLine !== "function") {
109
+ throw new ValidationError("SLEEP_AUTH_REQUIRES_TTY: confirmation reader is not available.");
110
+ }
111
+ const answer = await source.readLine(`Type ${phrase} to authorize: `);
112
+ if (String(answer || "") !== phrase) {
113
+ throw new ValidationError(
114
+ "SLEEP_AUTH_CONFIRMATION_MISMATCH: exact sleep-authorize confirmation phrase was not provided."
115
+ );
116
+ }
117
+ return { confirmed: true };
118
+ }
119
+
120
+ /**
121
+ * Create the sleep-authorization artifact (attended).
122
+ *
123
+ * Preconditions (each fail-closed with a typed error):
124
+ * 1. sleep plan exists and matches the feature key;
125
+ * 2. a FRESH sleep report computes READY_TO_SLEEP;
126
+ * 3. the agent-team execute context loads and its scope pins (bounded);
127
+ * 4. the agent-team readiness artifact is READY_TO_SLEEP;
128
+ * 5. budgets/TTL are within the hard engine ceilings;
129
+ * 6. the operator types the exact confirmation phrase on a TTY.
130
+ */
131
+ async function createSleepAuthorization(projectPath, featureKey, opts) {
132
+ const options = opts || {};
133
+ const resolved = path.resolve(projectPath || ".");
134
+
135
+ // 1. Sleep plan (throws NEEDS_PLAN when absent) + feature match.
136
+ const plan = loadSleepPlan(resolved);
137
+ if (plan.feature_key !== featureKey) {
138
+ throw new ValidationError(
139
+ `SLEEP_AUTH_PLAN_MISMATCH: sleep-plan feature_key "${plan.feature_key}" does not match --feature-key "${featureKey}".`
140
+ );
141
+ }
142
+
143
+ // 2. Fresh sleep-report verdict must be READY_TO_SLEEP.
144
+ const signals = gatherReportSignals(resolved, featureKey);
145
+ const report = projectSleepReport(plan, signals);
146
+ if (report.verdict !== "READY_TO_SLEEP") {
147
+ throw new ValidationError(
148
+ `SLEEP_AUTH_NOT_READY: sleep report verdict is "${report.verdict}" — ${report.reason}`
149
+ );
150
+ }
151
+
152
+ // 3. Agent-team execute context + pinned scope (pinScope enforces bounded,
153
+ // non-whole-repo allowed_file_scopes and an allowlisted verification set).
154
+ const ctx = loadExecuteContext(resolved, featureKey);
155
+ const pinnedScope = pinScope(ctx);
156
+
157
+ // 4. Agent-team readiness gate (the engine re-asserts authenticity per
158
+ // iteration; authorize checks the verdict up front for honest UX).
159
+ const readiness = loadReadiness(resolved, featureKey);
160
+ if (!readiness || readiness.overall_verdict !== "READY_TO_SLEEP") {
161
+ throw new ValidationError(
162
+ `SLEEP_AUTH_NOT_READY: agent-team readiness verdict is "${readiness ? readiness.overall_verdict : "absent"}".`
163
+ );
164
+ }
165
+
166
+ // 5. Budgets + TTL within engine ceilings (resolveSessionBudgets throws
167
+ // FAIL_BUDGET_CEILING above the hard caps).
168
+ const budgets = resolveSessionBudgets({
169
+ max_iterations: options.maxIterations === undefined ? SESSION_MAX_ITERATIONS : Number(options.maxIterations),
170
+ max_cost_usd: options.maxCostUsd === undefined ? SESSION_MAX_COST_USD : Number(options.maxCostUsd),
171
+ });
172
+ const ttlHours = resolveTtlHours(options.ttlHours);
173
+
174
+ // 6. Attended typed confirmation.
175
+ const phrase = buildAuthorizationPhrase(featureKey, budgets, ttlHours);
176
+ await confirmAuthorization(options.confirmInput || {}, phrase);
177
+
178
+ const planBytes = fs.readFileSync(sleepPlanPath(resolved));
179
+ const nowMs = typeof options.nowMs === "function" ? options.nowMs() : Date.now();
180
+ const createdAt = new Date(nowMs);
181
+ const expiresAt = new Date(nowMs + ttlHours * 60 * 60 * 1000);
182
+
183
+ const authorization = {
184
+ schema_version: AUTHORIZATION_SCHEMA,
185
+ feature_key: featureKey,
186
+ plan_sha256: sha256Hex(planBytes),
187
+ pinned_scope_sha256: sha256Hex(Buffer.from(JSON.stringify(pinnedScope), "utf8")),
188
+ budgets: {
189
+ max_iterations: budgets.maxIterations,
190
+ max_cost_usd: budgets.maxCostUsd,
191
+ },
192
+ patch_class: "doc",
193
+ created_at: createdAt.toISOString(),
194
+ expires_at: expiresAt.toISOString(),
195
+ confirmation: {
196
+ phrase_sha256: sha256Hex(Buffer.from(phrase, "utf8")),
197
+ confirmed_at: createdAt.toISOString(),
198
+ tty: true,
199
+ },
200
+ };
201
+ // Bind all security-relevant fields (F2/F3). Computed last, over the fields above.
202
+ authorization.authorization_sha256 = computeAuthorizationDigest(authorization);
203
+
204
+ const outPath = authorizationPath(resolved);
205
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
206
+ const tmpPath = `${outPath}.tmp`;
207
+ fs.writeFileSync(tmpPath, JSON.stringify(authorization, null, 2), "utf8");
208
+ fs.renameSync(tmpPath, outPath);
209
+ return { outPath, authorization };
210
+ }
211
+
212
+ module.exports = {
213
+ AUTHORIZATION_SCHEMA,
214
+ DEFAULT_TTL_HOURS,
215
+ authorizationPath,
216
+ buildAuthorizationPhrase,
217
+ authorizationDigestPayload,
218
+ computeAuthorizationDigest,
219
+ createSleepAuthorization,
220
+ };
@@ -26,7 +26,16 @@ function readinessComponentNotes(readiness) {
26
26
  }
27
27
  return readiness.components
28
28
  .filter((component) => component && typeof component.note === "string" && component.note.length > 0)
29
- .map((component) => `${component.name}: ${component.note}`);
29
+ .map((component) => {
30
+ // BK-340 W1: in a pre-flight dry run there are no changed files yet, so
31
+ // the FILE_SCOPE checker reports "absent" — clarify that this is the
32
+ // expected pre-flight state rather than a contradiction next to a
33
+ // READY_TO_SLEEP verdict.
34
+ if (component.name === "FILE_SCOPE" && component.note === "file-scope verdict: absent") {
35
+ return `${component.name}: ${component.note} (no changed files to evaluate yet — expected in a pre-flight dry run)`;
36
+ }
37
+ return `${component.name}: ${component.note}`;
38
+ });
30
39
  }
31
40
 
32
41
  function failingComponentNames(readiness) {