sdtk-code-kit 0.3.3 → 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 +13 -1
- package/assets/keys/sdtk-entitlement-public.pem +9 -0
- package/assets/manifest/toolkit-bundle.manifest.json +9 -9
- package/assets/manifest/toolkit-bundle.sha256.txt +3 -3
- package/assets/toolkit/toolkit/AGENTS.md +31 -0
- package/assets/toolkit/toolkit/sdtk-spec.config.json +36 -4
- package/assets/toolkit/toolkit/sdtk-spec.config.profiles.example.json +44 -6
- package/package.json +1 -1
- package/src/commands/help.js +10 -0
- package/src/commands/sleep.js +217 -2
- package/src/lib/agent-team-sleep-execute.js +16 -1
- package/src/lib/agent-team-sleep-session.js +42 -4
- package/src/lib/code-premium-loader.js +394 -0
- package/src/lib/sleep-authorization.js +220 -0
- package/src/lib/sleep-report.js +10 -1
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.
|
|
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-----
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "0.3.
|
|
3
|
-
"sourceCommit": "
|
|
2
|
+
"version": "0.3.4",
|
|
3
|
+
"sourceCommit": "375b27555f8dfc0ac32a3f6479b7158c17ca03cc",
|
|
4
4
|
"fileCount": 29,
|
|
5
5
|
"files": [
|
|
6
6
|
{
|
|
7
7
|
"path": "toolkit/AGENTS.md",
|
|
8
|
-
"sha256": "
|
|
9
|
-
"size":
|
|
8
|
+
"sha256": "0871c6d46c64a093fc5f9d06af373db8143943cd27f144957dad0cc86893dc62",
|
|
9
|
+
"size": 15069
|
|
10
10
|
},
|
|
11
11
|
{
|
|
12
12
|
"path": "toolkit/install.ps1",
|
|
@@ -35,13 +35,13 @@
|
|
|
35
35
|
},
|
|
36
36
|
{
|
|
37
37
|
"path": "toolkit/sdtk-spec.config.json",
|
|
38
|
-
"sha256": "
|
|
39
|
-
"size":
|
|
38
|
+
"sha256": "ce760f639a09913b236be6dde6c692ea19ee92eb1d9e63d10dcdeb398e7ed2fb",
|
|
39
|
+
"size": 1209
|
|
40
40
|
},
|
|
41
41
|
{
|
|
42
42
|
"path": "toolkit/sdtk-spec.config.profiles.example.json",
|
|
43
|
-
"sha256": "
|
|
44
|
-
"size":
|
|
43
|
+
"sha256": "e04ea5e3f72510e569ab849ebef3dea4a8728c2996c485e997d3e13a6c4f1f86",
|
|
44
|
+
"size": 1495
|
|
45
45
|
},
|
|
46
46
|
{
|
|
47
47
|
"path": "toolkit/SDTKCODE_TOOLKIT.md",
|
|
@@ -149,4 +149,4 @@
|
|
|
149
149
|
"size": 3668
|
|
150
150
|
}
|
|
151
151
|
]
|
|
152
|
-
}
|
|
152
|
+
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
|
|
1
|
+
0871c6d46c64a093fc5f9d06af373db8143943cd27f144957dad0cc86893dc62 toolkit/AGENTS.md
|
|
2
2
|
dd7ffbd69c29f76d67f65c3e857ba241e92908931b2e93a9b9c503542e43f35c toolkit/install.ps1
|
|
3
3
|
720990cc979cdbca776bbe21eaeee0a73c5dd698ac6c8df430c7f22826ec9219 toolkit/scripts/install-claude-skills.ps1
|
|
4
4
|
7d61249db7eee6185e5454f7427b808c79d5e564e0d2214ee5f92fa105effb04 toolkit/scripts/install-codex-skills.ps1
|
|
5
5
|
148ddfc5a79a9dd6d7fa5b926c5511a5e4d458fa31003217cdc2eefcbe966cc2 toolkit/scripts/uninstall-claude-skills.ps1
|
|
6
6
|
0fd11650bd445fad37c728471872b99bfb8bd17dfb95e62431ceccfad7f0852f toolkit/scripts/uninstall-codex-skills.ps1
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
ce760f639a09913b236be6dde6c692ea19ee92eb1d9e63d10dcdeb398e7ed2fb toolkit/sdtk-spec.config.json
|
|
8
|
+
e04ea5e3f72510e569ab849ebef3dea4a8728c2996c485e997d3e13a6c4f1f86 toolkit/sdtk-spec.config.profiles.example.json
|
|
9
9
|
9269a5afe88ce97885d054f5a78d496c1aafa50097f581d070e34dceb597c8fe toolkit/SDTKCODE_TOOLKIT.md
|
|
10
10
|
d797d707dc34d299dbac13f09f3bc8cc42759cb69a9fa5b2cb2269e4c246061e toolkit/skills/code-brainstorm/SKILL.md
|
|
11
11
|
698c89de9a0586e83ee52147adf345fa2ab813a06b454ca50e9c69e423f0a910 toolkit/skills/code-debug/references/root-cause-tracing.md
|
|
@@ -32,6 +32,8 @@ When starting a new session, read context in this order when the files exist:
|
|
|
32
32
|
|
|
33
33
|
Do not read the entire historical session archive by default. Use `SDTK_SESSION_MEMORY_*.md` only when chronology or past acceptance details are required.
|
|
34
34
|
|
|
35
|
+
Active orchestration check: if `.sdtk/agent-runtime/runs/` holds a run whose state is not terminal (`running` or `waiting_for_approval`), surface it in one line (run id plus the blocking gate, if any) and offer `sdtk-agent run continue` before starting unrelated work, the same way `.sdtk/handoff/` items are surfaced.
|
|
36
|
+
|
|
35
37
|
## 3) Orchestrator-First Intake Protocol
|
|
36
38
|
For every unprefixed user request:
|
|
37
39
|
1. Classify the request intent before selecting PM/BA/ARCH/DEV/QA or a downstream product lane.
|
|
@@ -63,6 +65,7 @@ Use this compact matrix during intake so the agent picks the smallest sufficient
|
|
|
63
65
|
| Atlas graph build or viewer work | `sdtk-spec atlas` compatibility workflow or `sdtk-wiki atlas` for canonical SDTK-WIKI work | Local `.sdtk/atlas` compatibility graph or `.sdtk/wiki` SDTK-WIKI result |
|
|
64
66
|
| SDTK-WIKI Ask | `sdtk-wiki ask` | Grounded answer when `.sdtk/wiki/graph` plus `wiki.ask` entitlement/runtime preconditions are present, otherwise explicit blocker |
|
|
65
67
|
| Existing project scan: project ingest, project refresh, or project audit | Matching premium project workflow | Project-local foundation, refresh, or audit result without overclaiming entitlement |
|
|
68
|
+
| Multi-step durable workflow: 3+ dependent steps, human gates between steps, must survive a pause, or spans multiple lanes/sessions | Propose `sdtk-agent` orchestration (opt-in, token-aware, see the orchestration cost gate in section 5) | `.sdtk/agent-runtime/runs/<run_id>/` ledger plus `reports/final_report.md` |
|
|
66
69
|
| "what should we do next" | Orchestrator state review | Recommended next action with rationale and lane choice |
|
|
67
70
|
|
|
68
71
|
Guardrails:
|
|
@@ -78,6 +81,7 @@ Ask clarification when:
|
|
|
78
81
|
3. the target repo, project, or path is missing
|
|
79
82
|
4. implementation is requested without an acceptance boundary
|
|
80
83
|
5. the next command could mutate external state
|
|
84
|
+
6. the next step would spawn multiple sub-agents or incur significant token cost, such as dispatching an `sdtk-agent` run
|
|
81
85
|
|
|
82
86
|
Proceed when:
|
|
83
87
|
1. the intent and target are clear
|
|
@@ -85,6 +89,16 @@ Proceed when:
|
|
|
85
89
|
3. the user already approved the relevant plan or spec
|
|
86
90
|
4. the requested change is bounded and verifiable
|
|
87
91
|
|
|
92
|
+
### 5.1) Orchestration Cost Gate (sdtk-agent)
|
|
93
|
+
`sdtk-agent` chains multiple steps and dispatches each ready task through an adapter, so a single run can spawn many sub-agents and consume significant token budget. Because of that cost, orchestration is always opt-in:
|
|
94
|
+
|
|
95
|
+
1. Never auto-start an `sdtk-agent` run on the user's behalf. Only propose it.
|
|
96
|
+
2. Propose only when a routing trigger is hit (the multi-step row in section 4) and the workflow clears the minimum size (default: 3 dependent steps). One- or two-step bounded tasks route straight to a lane instead of orchestration.
|
|
97
|
+
3. When proposing, state the trade-off concretely and let the user decide, defaulting to "no / run inline". Run `sdtk-agent workflow validate` first (it does not spawn anything) to count tasks, human gates, and adapter dispatches, then quote a cost band: dispatch count 3 or fewer is Low, 4-8 is Medium, more than 8 or any loop/retry is High. Example:
|
|
98
|
+
> This request fits sdtk-agent: durable, resumable, with hard approval gates, but it will spawn several agents and cost more tokens than an inline run. Estimate: 9 steps, 3 gates, 11 dispatches (token cost: HIGH). Use sdtk-agent for this, or run it inline? (default: inline)
|
|
99
|
+
4. `run start` only creates the ledger and never spawns; treat it as the safe preview point. Dispatch happens on `run continue`, which is an explicit user action. Before a `run continue` that would dispatch several ready tasks at once, report how many tasks and which adapters are about to run, and let the user confirm or step through one task at a time.
|
|
100
|
+
5. Honor `.sdtk/agent-runtime/config.json` `orchestration.confirmationMode` (`always` by default): no mode ever allows dispatch without at least one confirmation per run.
|
|
101
|
+
|
|
88
102
|
## 6) Clarification Protocol
|
|
89
103
|
Apply for all roles (`/pm`, `/ba`, `/arch`, `/dev`, `/qa`):
|
|
90
104
|
1. If there is ambiguity or missing data, log `Open Questions` as `OQ-xx` in the current phase artifact.
|
|
@@ -122,6 +136,9 @@ Use the suite products according to task intent:
|
|
|
122
136
|
- requirements, BA, PRD, backlog, architecture, QA artifacts
|
|
123
137
|
- handoff generation and release-gate traceability
|
|
124
138
|
- entry: `/orchestrator` (recommended), `/pm`, `/ba`, `/arch`, `/dev`, `/qa`
|
|
139
|
+
- `SDTK-DESIGN`
|
|
140
|
+
- screen/layout design, visual tokens, prototype evidence, design handoff before coding
|
|
141
|
+
- use before `SDTK-CODE` when implementation needs reviewable screens or a design handoff
|
|
125
142
|
- `SDTK-CODE`
|
|
126
143
|
- build a feature
|
|
127
144
|
- fix a bug
|
|
@@ -138,6 +155,18 @@ Use the suite products according to task intent:
|
|
|
138
155
|
- monitoring, incident response, security-infra, backup, compliance
|
|
139
156
|
- entry: `ops-discover` (when boundary is unclear), `ops-plan`, `ops-deploy`, `ops-incident`, `ops-monitor`, `ops-backup`, `ops-verify`, `ops-debug`
|
|
140
157
|
|
|
158
|
+
Cross-cutting capabilities (not a linear lane; usable across every phase):
|
|
159
|
+
|
|
160
|
+
- `SDTK-WIKI` (memory)
|
|
161
|
+
- project knowledge graph, docs view, and grounded `sdtk-wiki ask`
|
|
162
|
+
- any lane may read from it for recall; build with `sdtk-wiki atlas build`
|
|
163
|
+
- `SDTK-AGENT` (orchestration)
|
|
164
|
+
- a durable, file-driven DAG controller that sits above `sdtk-code` agent-team; it does not own a phase, it chains steps across lanes
|
|
165
|
+
- surface: `sdtk-agent run start|continue|status|report`, `gate approve|reject`, `workflow validate`, `adapter hermes-kanban plan`
|
|
166
|
+
- use only when a workflow has 3+ dependent steps, needs human gates between steps, or must survive a pause; otherwise route straight to a lane
|
|
167
|
+
- opt-in and token-aware: always propose-then-confirm before dispatch (see the orchestration cost gate in section 5)
|
|
168
|
+
- the CLI is runtime-neutral and installs no skills; the engine is Free, and live external dispatch is not part of this release (hermes-kanban is dry-run only)
|
|
169
|
+
|
|
141
170
|
If the current project only has `SDTK-SPEC` runtime assets installed:
|
|
142
171
|
- keep `/dev` bounded to planning and `CODE_HANDOFF`
|
|
143
172
|
- do not overclaim that SDTK-CODE or SDTK-OPS runtime assets are already installed
|
|
@@ -156,6 +185,8 @@ If the current project only has `SDTK-SPEC` runtime assets installed:
|
|
|
156
185
|
- For SDTK-SPEC-only installs: keep `/dev` bounded to planning and `CODE_HANDOFF`; do not claim SDTK-CODE or SDTK-OPS are installed.
|
|
157
186
|
- For Codex runtimes: project-local skills require the explicit local `CODEX_HOME=<project>/.codex` contract; native `.codex/skills` auto-discovery is not claimed.
|
|
158
187
|
- Use `ops-parallel` or `code-parallel` only for truly independent slices. If parallel dispatch is unavailable in the active runtime, execute them sequentially in one controller session.
|
|
188
|
+
- `SDTK-AGENT` is runtime-neutral: it installs no skills and behaves identically on Claude and Codex. It is CLI-only, so do not invent a slash command for it.
|
|
189
|
+
- The `sdtk-agent` hermes-kanban adapter is dry-run only in this release; it never calls a live gateway or creates a real card. Live dispatch is a future Pro capability, so do not claim it.
|
|
159
190
|
|
|
160
191
|
## 11) Discovery And PM Readiness
|
|
161
192
|
- PM initiation starts only after `docs/discovery/REQUIREMENT_[FEATURE_KEY].md` is marked `READY_FOR_PM_INITIATION`.
|
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
|
-
"
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
"docs": {
|
|
3
|
+
"artifactsLanguage": "EN",
|
|
4
|
+
"guidanceLanguage": "VI",
|
|
5
|
+
"preserveOriginalInput": true,
|
|
6
|
+
"appendixIncludeEnglishTranslation": true,
|
|
7
|
+
"aiPeerReviewAllowed": true
|
|
8
|
+
},
|
|
9
|
+
"orchestration": {
|
|
10
|
+
"apiDesignDetailMode": "auto",
|
|
11
|
+
"testCaseSpecMode": "auto"
|
|
12
|
+
},
|
|
13
|
+
"stack": {
|
|
14
|
+
"backend": "Set your backend stack (example: Python Django REST Framework)",
|
|
15
|
+
"frontend": "Set your frontend stack (example: React + Vite)",
|
|
16
|
+
"mobile": "N/A",
|
|
17
|
+
"database": "Set your database (example: PostgreSQL 15)",
|
|
18
|
+
"auth": "Set your auth strategy (example: JWT/OAuth2)",
|
|
19
|
+
"detection": {
|
|
20
|
+
"language": null,
|
|
21
|
+
"framework": null,
|
|
22
|
+
"frameworkVersion": null,
|
|
23
|
+
"packageManager": null,
|
|
24
|
+
"confidence": "low",
|
|
25
|
+
"evidence": [],
|
|
26
|
+
"detectedAt": null,
|
|
27
|
+
"method": "static"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"commands": {
|
|
31
|
+
"backendTests": "UPDATE_ME: set backend test command",
|
|
32
|
+
"backendTypecheck": "UPDATE_ME: set backend typecheck command",
|
|
33
|
+
"backendLint": "UPDATE_ME: set backend lint command",
|
|
34
|
+
"frontendTests": "UPDATE_ME: set frontend test command",
|
|
35
|
+
"frontendLint": "UPDATE_ME: set frontend lint command",
|
|
36
|
+
"e2eTests": "UPDATE_ME: set e2e test command"
|
|
37
|
+
}
|
|
6
38
|
}
|
|
@@ -1,12 +1,50 @@
|
|
|
1
1
|
{
|
|
2
|
-
"$comment": "SCAFFOLD: Example profiles config for SDTKCODE. Copy to sdtk-spec.config.profiles.json and customize.",
|
|
3
2
|
"profiles": {
|
|
4
|
-
"
|
|
3
|
+
"django-react": {
|
|
4
|
+
"orchestration": {
|
|
5
|
+
"apiDesignDetailMode": "auto",
|
|
6
|
+
"testCaseSpecMode": "auto"
|
|
7
|
+
},
|
|
5
8
|
"stack": {
|
|
6
|
-
"backend": "
|
|
7
|
-
"frontend": "
|
|
8
|
-
"
|
|
9
|
+
"backend": "Python 3.11 + Django 4.x + Django REST Framework",
|
|
10
|
+
"frontend": "React 18 + Vite",
|
|
11
|
+
"mobile": "N/A",
|
|
12
|
+
"database": "PostgreSQL 15",
|
|
13
|
+
"auth": "JWT"
|
|
14
|
+
},
|
|
15
|
+
"commands": {
|
|
16
|
+
"backendTests": "python -m pytest",
|
|
17
|
+
"backendTypecheck": "python -m mypy src/backend",
|
|
18
|
+
"backendLint": "python -m ruff check src/backend",
|
|
19
|
+
"frontendTests": "npm run test",
|
|
20
|
+
"frontendLint": "npm run lint",
|
|
21
|
+
"e2eTests": "npm run e2e"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"node-nextjs": {
|
|
25
|
+
"orchestration": {
|
|
26
|
+
"apiDesignDetailMode": "auto",
|
|
27
|
+
"testCaseSpecMode": "auto"
|
|
28
|
+
},
|
|
29
|
+
"stack": {
|
|
30
|
+
"backend": "Node.js 20 + Express/Fastify",
|
|
31
|
+
"frontend": "Next.js 14",
|
|
32
|
+
"mobile": "N/A",
|
|
33
|
+
"database": "PostgreSQL 15",
|
|
34
|
+
"auth": "OAuth2 + JWT"
|
|
35
|
+
},
|
|
36
|
+
"commands": {
|
|
37
|
+
"backendTests": "npm run test:api",
|
|
38
|
+
"backendTypecheck": "npm run typecheck:api",
|
|
39
|
+
"backendLint": "npm run lint:api",
|
|
40
|
+
"frontendTests": "npm run test:web",
|
|
41
|
+
"frontendLint": "npm run lint:web",
|
|
42
|
+
"e2eTests": "npm run test:e2e"
|
|
9
43
|
}
|
|
10
44
|
}
|
|
11
|
-
}
|
|
45
|
+
},
|
|
46
|
+
"notes": [
|
|
47
|
+
"Copy one profile into sdtk-spec.config.json and adjust for your project.",
|
|
48
|
+
"Do not keep UPDATE_ME placeholders before running real delivery gates."
|
|
49
|
+
]
|
|
12
50
|
}
|
package/package.json
CHANGED
package/src/commands/help.js
CHANGED
|
@@ -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)",
|
package/src/commands/sleep.js
CHANGED
|
@@ -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
|
-
|
|
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 >=
|
|
175
|
-
throw new ValidationError(`FAIL_SESSION_ITERATION_CAP: max iterations reached (${
|
|
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 >
|
|
183
|
-
throw new ValidationError(
|
|
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
|
+
};
|
package/src/lib/sleep-report.js
CHANGED
|
@@ -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) =>
|
|
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) {
|