sdtk-code-kit 0.3.1 → 0.3.3

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.
@@ -0,0 +1,278 @@
1
+ "use strict";
2
+
3
+ const crypto = require("crypto");
4
+ const { ValidationError } = require("./errors");
5
+ const { safeSegment } = require("./agent-team-export");
6
+ const { redact } = require("./trust-redact");
7
+
8
+ const SESSION_MAX_ITERATIONS = 3;
9
+ const SESSION_MAX_COST_USD = 3.00;
10
+ const SESSION_MAX_OUTPUT_TOKENS = 48000;
11
+ const SESSION_WALLCLOCK_TIMEOUT_MS = 30 * 60 * 1000;
12
+ const SESSION_DOC_TARGET_PATTERNS = Object.freeze([
13
+ "docs/**/*.md",
14
+ "governance/**/*.md",
15
+ "README.md",
16
+ "AGENTS.md",
17
+ ]);
18
+ const SESSION_ALLOWED_COMMANDS = Object.freeze([
19
+ "python3 scripts/ci/docs_lint.py",
20
+ "python3 scripts/ci/path_check.py",
21
+ ]);
22
+
23
+ const activeSessionIds = new Set();
24
+
25
+ function asArray(value) {
26
+ return Array.isArray(value) ? value : [];
27
+ }
28
+
29
+ function sha256(value) {
30
+ return crypto.createHash("sha256").update(String(value || "")).digest("hex");
31
+ }
32
+
33
+ function makeSessionId(featureKey, seed) {
34
+ if (seed) return safeSegment(seed, "session_id");
35
+ const stamp = Date.now().toString(36);
36
+ const rand = crypto.randomUUID().replace(/-/g, "").slice(0, 12);
37
+ return safeSegment(`${featureKey}_${stamp}_${rand}`, "session_id");
38
+ }
39
+
40
+ function normalizeCommand(value) {
41
+ return String(value || "").trim();
42
+ }
43
+
44
+ function pinAllowedCommands(commands) {
45
+ const seen = new Set();
46
+ const out = [];
47
+ for (const command of asArray(commands).map(normalizeCommand)) {
48
+ if (SESSION_ALLOWED_COMMANDS.includes(command) && !seen.has(command)) {
49
+ seen.add(command);
50
+ out.push(command);
51
+ }
52
+ }
53
+ if (out.length === 0) {
54
+ throw new ValidationError("FAIL_NO_ALLOWED_COMMANDS: no role verification command matches the Phase E session allowlist.");
55
+ }
56
+ return Object.freeze(out);
57
+ }
58
+
59
+ function pinAllowedScopes(ctx) {
60
+ const scopes = asArray(ctx && ctx.allowedFileScopes).map((scope) => String(scope || "").trim()).filter(Boolean);
61
+ if (scopes.length === 0) {
62
+ throw new ValidationError("FAIL_EXECUTE_SCOPE: Phase E requires pinned allowed_file_scopes.");
63
+ }
64
+ return Object.freeze(scopes);
65
+ }
66
+
67
+ function collectTaskList(plan) {
68
+ const items = [];
69
+ for (const value of asArray(plan && plan.implementation_slices)) {
70
+ if (value) items.push(String(value));
71
+ }
72
+ for (const role of asArray(plan && plan.roles)) {
73
+ if (role && role.objective) items.push(String(role.objective));
74
+ for (const value of asArray(role && role.evidence_required)) {
75
+ items.push(`evidence_required:${role.role}:${value}`);
76
+ }
77
+ }
78
+ return items;
79
+ }
80
+
81
+ function pinScope(ctx) {
82
+ const source = ctx || {};
83
+ return Object.freeze({
84
+ feature_key: source.featureKey,
85
+ run_id: source.runId,
86
+ role: source.role && source.role.role ? String(source.role.role) : "dev",
87
+ allowed_file_scopes: pinAllowedScopes(source),
88
+ doc_target_patterns: SESSION_DOC_TARGET_PATTERNS,
89
+ verification_commands: pinAllowedCommands(source.verificationCommands),
90
+ });
91
+ }
92
+
93
+ function redactedTaskList(plan) {
94
+ return collectTaskList(plan).map((item) => redact(item));
95
+ }
96
+
97
+ function enumerateCarriedState(data) {
98
+ const source = data || {};
99
+ const priorPatchHashes = asArray(source.priorPatchHashes).map((hash) => String(hash));
100
+ return Object.freeze({
101
+ cumulativeWorktreePath: source.cumulativeWorktreePath ? redact(String(source.cumulativeWorktreePath)) : null,
102
+ taskListFromPinnedPlan: redactedTaskList(source.plan),
103
+ priorPatchHashes: Object.freeze(priorPatchHashes),
104
+ accumulators: Object.freeze({
105
+ iteration: Number(source.iteration || 0),
106
+ session_cost_usd: Number(source.session_cost_usd || 0),
107
+ session_output_tokens: Number(source.session_output_tokens || 0),
108
+ }),
109
+ });
110
+ }
111
+
112
+ function projectedCost(projectedNextCall) {
113
+ const call = projectedNextCall || {};
114
+ if (call.pricing_unknown === true || call.model_id_unknown === true) {
115
+ throw new ValidationError("FAIL_MODEL_PRICING_UNKNOWN: model pricing is not pinned for this session iteration.");
116
+ }
117
+ const value = call.projected_cost_usd === undefined ? 0 : Number(call.projected_cost_usd);
118
+ if (!Number.isFinite(value) || value < 0) {
119
+ throw new ValidationError("FAIL_MODEL_PRICING_UNKNOWN: model pricing is not pinned for this session iteration.");
120
+ }
121
+ return value;
122
+ }
123
+
124
+ function projectedTokens(projectedNextCall) {
125
+ const value = projectedNextCall && projectedNextCall.projected_output_tokens !== undefined
126
+ ? Number(projectedNextCall.projected_output_tokens)
127
+ : 0;
128
+ if (!Number.isFinite(value) || value < 0) {
129
+ throw new ValidationError("FAIL_SESSION_TOKEN_CAP: projected output tokens are not evaluable.");
130
+ }
131
+ return value;
132
+ }
133
+
134
+ function createSleepSession(input) {
135
+ const options = input || {};
136
+ const featureKey = safeSegment(options.featureKey, "feature_key");
137
+ const sessionId = makeSessionId(featureKey, options.sessionId);
138
+ const now = typeof options.nowMs === "function" ? options.nowMs : () => Date.now();
139
+ const startedAtMs = Number(options.startedAtMs === undefined ? now() : options.startedAtMs);
140
+ const pinnedScope = options.pinnedScope || null;
141
+ let iteration = 0;
142
+ let sessionCostUsd = 0;
143
+ let sessionOutputTokens = 0;
144
+ let killed = false;
145
+ const priorPatchHashes = [];
146
+
147
+ function snapshot(extra) {
148
+ const info = extra || {};
149
+ return {
150
+ session_id: sessionId,
151
+ feature_key: featureKey,
152
+ iteration,
153
+ session_cost_usd: sessionCostUsd,
154
+ session_output_tokens: sessionOutputTokens,
155
+ killed,
156
+ started_at_ms: startedAtMs,
157
+ pinned_scope: pinnedScope,
158
+ prior_patch_hashes: priorPatchHashes.slice(),
159
+ carried_state: enumerateCarriedState({
160
+ cumulativeWorktreePath: info.cumulativeWorktreePath,
161
+ plan: info.plan,
162
+ priorPatchHashes,
163
+ iteration,
164
+ session_cost_usd: sessionCostUsd,
165
+ session_output_tokens: sessionOutputTokens,
166
+ }),
167
+ };
168
+ }
169
+
170
+ function assertCanStartIteration(projectedNextCall) {
171
+ if (killed) {
172
+ throw new ValidationError("FAIL_SESSION_KILLED: sleep execute session was killed.");
173
+ }
174
+ if (iteration >= SESSION_MAX_ITERATIONS) {
175
+ throw new ValidationError(`FAIL_SESSION_ITERATION_CAP: max iterations reached (${SESSION_MAX_ITERATIONS}).`);
176
+ }
177
+ if (now() - startedAtMs >= SESSION_WALLCLOCK_TIMEOUT_MS) {
178
+ throw new ValidationError("FAIL_SESSION_WALLCLOCK_CAP: 30-minute session wall-clock exceeded.");
179
+ }
180
+ const nextCost = projectedCost(projectedNextCall);
181
+ const nextTokens = projectedTokens(projectedNextCall);
182
+ if (sessionCostUsd + nextCost > SESSION_MAX_COST_USD) {
183
+ throw new ValidationError("FAIL_SESSION_COST_CAP: projected session cost exceeds $3.00.");
184
+ }
185
+ if (sessionOutputTokens + nextTokens > SESSION_MAX_OUTPUT_TOKENS) {
186
+ throw new ValidationError("FAIL_SESSION_TOKEN_CAP: projected session output tokens exceed 48000.");
187
+ }
188
+ return true;
189
+ }
190
+
191
+ function recordIteration(usage) {
192
+ const info = usage || {};
193
+ const cost = Number(info.cost_usd === undefined ? 0 : info.cost_usd);
194
+ const tokens = Number(info.output_tokens === undefined ? 0 : info.output_tokens);
195
+ if (!Number.isFinite(cost) || cost < 0 || !Number.isFinite(tokens) || tokens < 0) {
196
+ throw new ValidationError("unknown_risk_stop: session usage must be non-negative and evaluable.");
197
+ }
198
+ const patchHash = info.produced_patch_sha256 ? String(info.produced_patch_sha256) : null;
199
+ sessionCostUsd += cost;
200
+ sessionOutputTokens += tokens;
201
+ iteration += 1;
202
+ if (patchHash) priorPatchHashes.push(patchHash);
203
+ return snapshot(info);
204
+ }
205
+
206
+ function killSession(reason) {
207
+ killed = true;
208
+ return { killed: true, reason: reason || "killed" };
209
+ }
210
+
211
+ return Object.freeze({
212
+ session_id: sessionId,
213
+ feature_key: featureKey,
214
+ started_at_ms: startedAtMs,
215
+ pinned_scope: pinnedScope,
216
+ assertCanStartIteration,
217
+ recordIteration,
218
+ killSession,
219
+ snapshot,
220
+ });
221
+ }
222
+
223
+ function assertPinnedScope(session, ctx) {
224
+ if (!session || !session.pinned_scope) {
225
+ throw new ValidationError("scope_lock: Phase E session scope is not pinned.");
226
+ }
227
+ const current = pinScope(ctx);
228
+ const pinned = session.pinned_scope;
229
+ const sameScopes = JSON.stringify(current.allowed_file_scopes) === JSON.stringify(pinned.allowed_file_scopes);
230
+ const sameCommands = JSON.stringify(current.verification_commands) === JSON.stringify(pinned.verification_commands);
231
+ const sameRole = current.role === pinned.role;
232
+ if (!sameScopes || !sameCommands || !sameRole) {
233
+ throw new ValidationError("scope_lock: pinned Phase E session scope changed during the session.");
234
+ }
235
+ return true;
236
+ }
237
+
238
+ async function withSessionLease(sessionId, fn) {
239
+ const safeSessionId = safeSegment(sessionId, "session_id");
240
+ if (activeSessionIds.has(safeSessionId)) {
241
+ throw new ValidationError("FAIL_SESSION_REENTRY: sleep execute session is already active; resume/reentry is not available in Preview.");
242
+ }
243
+ activeSessionIds.add(safeSessionId);
244
+ try {
245
+ return await fn();
246
+ } finally {
247
+ activeSessionIds.delete(safeSessionId);
248
+ }
249
+ }
250
+
251
+ function sessionStopConditionFromError(error) {
252
+ const message = error && error.message ? String(error.message) : String(error || "unknown_risk_stop");
253
+ if (message.includes("FAIL_SESSION_COST_CAP")) return "FAIL_SESSION_COST_CAP";
254
+ if (message.includes("FAIL_SESSION_TOKEN_CAP")) return "FAIL_SESSION_TOKEN_CAP";
255
+ if (message.includes("FAIL_SESSION_ITERATION_CAP")) return "action_count_cap";
256
+ if (message.includes("FAIL_SESSION_WALLCLOCK_CAP")) return "action_count_cap";
257
+ if (message.includes("FAIL_MODEL_PRICING_UNKNOWN")) return "FAIL_MODEL_PRICING_UNKNOWN";
258
+ if (message.includes("scope_lock")) return "scope_lock";
259
+ if (message.includes("FAIL_SESSION_KILLED")) return "unknown_risk_stop";
260
+ if (message.includes("FAIL_SESSION_REENTRY")) return "unknown_risk_stop";
261
+ return "unknown_risk_stop";
262
+ }
263
+
264
+ module.exports = {
265
+ SESSION_MAX_ITERATIONS,
266
+ SESSION_MAX_COST_USD,
267
+ SESSION_MAX_OUTPUT_TOKENS,
268
+ SESSION_WALLCLOCK_TIMEOUT_MS,
269
+ SESSION_DOC_TARGET_PATTERNS,
270
+ SESSION_ALLOWED_COMMANDS,
271
+ sha256,
272
+ pinScope,
273
+ assertPinnedScope,
274
+ enumerateCarriedState,
275
+ createSleepSession,
276
+ withSessionLease,
277
+ sessionStopConditionFromError,
278
+ };
@@ -132,6 +132,14 @@ function buildEvent(raw) {
132
132
  ? String(source.execution_mode) : null;
133
133
  const workflowType = source.workflow_type != null
134
134
  ? String(source.workflow_type) : null;
135
+ const iterationIndex = typeof source.iteration_index === "number"
136
+ ? source.iteration_index : null;
137
+ const readinessVerdict = source.readiness_verdict != null
138
+ ? String(source.readiness_verdict) : null;
139
+ const sessionCostUsd = typeof source.session_cost_usd === "number"
140
+ ? source.session_cost_usd : null;
141
+ const sessionOutputTokens = typeof source.session_output_tokens === "number"
142
+ ? source.session_output_tokens : null;
135
143
  const modelProvider = source.model_provider != null ? redact(String(source.model_provider)) : null;
136
144
  const modelId = source.model_id != null ? redact(String(source.model_id)) : null;
137
145
  const promptSha256 = source.prompt_sha256 != null ? String(source.prompt_sha256) : null;
@@ -172,6 +180,10 @@ function buildEvent(raw) {
172
180
  ...(Object.prototype.hasOwnProperty.call(source, "actions_executed") ? { actions_executed: actionsExecuted } : {}),
173
181
  ...(Object.prototype.hasOwnProperty.call(source, "execution_mode") ? { execution_mode: executionMode } : {}),
174
182
  ...(Object.prototype.hasOwnProperty.call(source, "workflow_type") ? { workflow_type: workflowType } : {}),
183
+ ...(Object.prototype.hasOwnProperty.call(source, "iteration_index") ? { iteration_index: iterationIndex } : {}),
184
+ ...(Object.prototype.hasOwnProperty.call(source, "readiness_verdict") ? { readiness_verdict: readinessVerdict } : {}),
185
+ ...(Object.prototype.hasOwnProperty.call(source, "session_cost_usd") ? { session_cost_usd: sessionCostUsd } : {}),
186
+ ...(Object.prototype.hasOwnProperty.call(source, "session_output_tokens") ? { session_output_tokens: sessionOutputTokens } : {}),
175
187
  ...(Object.prototype.hasOwnProperty.call(source, "model_provider") ? { model_provider: modelProvider } : {}),
176
188
  ...(Object.prototype.hasOwnProperty.call(source, "model_id") ? { model_id: modelId } : {}),
177
189
  ...(Object.prototype.hasOwnProperty.call(source, "prompt_sha256") ? { prompt_sha256: promptSha256 } : {}),