@qwen-code/qwen-harness 0.1.9 → 0.1.11-yjk.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.
@@ -0,0 +1,786 @@
1
+ // src/verifiers/scaling/constraints-cli.ts
2
+ import { readFile, writeFile } from "node:fs/promises";
3
+ import path4 from "node:path";
4
+
5
+ // src/verifiers/scaling/constraints.ts
6
+ import path3 from "node:path";
7
+
8
+ // src/harnesses/scaling/experiments/config.ts
9
+ import path from "node:path";
10
+ var CONSTRAINT_IDS = ["A02", "A05", "A01", "U02", "U07", "A07"];
11
+ function record(value) {
12
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Experiment fields must be objects");
13
+ return value;
14
+ }
15
+ function keys(value, allowed) {
16
+ for (const key of Object.keys(value)) if (!allowed.includes(key)) throw new Error(`Unknown experiment field: ${key}`);
17
+ }
18
+ function parseExperiment(input, cwd, config) {
19
+ const value = record(input);
20
+ keys(value, ["version", "toolProfile", "processFile", "constraints"]);
21
+ if (value.version !== 1) throw new Error("scaling experiment version must be 1");
22
+ const profile = record(value.toolProfile ?? {});
23
+ keys(profile, ["readFileAlias", "appendFile", "prepareProcessFile"]);
24
+ for (const flag of Object.values(profile)) if (typeof flag !== "boolean") throw new Error("Tool profile flags must be booleans");
25
+ if (profile.readFileAlias && config.TS !== "TS2") throw new Error("readFileAlias requires TS2, which already provides read; no implicit TS1/TS3 capability change");
26
+ const constraints = record(value.constraints ?? {});
27
+ keys(constraints, CONSTRAINT_IDS);
28
+ const result = {
29
+ version: 1,
30
+ toolProfile: { readFileAlias: profile.readFileAlias === true, appendFile: profile.appendFile === true, prepareProcessFile: profile.prepareProcessFile === true },
31
+ processFile: typeof value.processFile === "string" ? value.processFile : path.resolve(cwd, ".scaling-progress.jsonl"),
32
+ constraints: {}
33
+ };
34
+ if (value.processFile !== void 0 && typeof value.processFile !== "string" || !path.isAbsolute(result.processFile)) throw new Error("processFile must be an absolute path");
35
+ result.processFile = path.normalize(result.processFile);
36
+ for (const id of CONSTRAINT_IDS) {
37
+ if (constraints[id] === void 0) continue;
38
+ const options = record(constraints[id]);
39
+ if (id === "U02" || id === "U07") {
40
+ keys(options, ["every"]);
41
+ if (!Number.isSafeInteger(options.every) || Number(options.every) < 1) throw new Error(`${id}.every must be a positive integer`);
42
+ if (config.C === "C2" && Number(options.every) < 3) throw new Error(`${id}.every must be at least 3 with C2's two exclusive handoff responses`);
43
+ result.constraints[id] = { every: Number(options.every) };
44
+ } else if (id === "A01") {
45
+ keys(options, ["forbiddenTools", "mode"]);
46
+ if (!Array.isArray(options.forbiddenTools) || !options.forbiddenTools.length || !options.forbiddenTools.every((name) => typeof name === "string" && /^[a-zA-Z_][\w.-]*$/u.test(name))) throw new Error("A01.forbiddenTools must contain registered tool IDs");
47
+ if (options.mode !== void 0 && options.mode !== "audit" && options.mode !== "block") throw new Error("A01.mode must be audit or block");
48
+ result.constraints.A01 = { forbiddenTools: [...new Set(options.forbiddenTools)].sort(), mode: options.mode ?? "audit" };
49
+ } else {
50
+ keys(options, []);
51
+ result.constraints[id] = {};
52
+ }
53
+ }
54
+ return result;
55
+ }
56
+
57
+ // src/harnesses/scaling/config.ts
58
+ var SCALING_AXES = ["S", "TS", "TC", "O", "C", "W"];
59
+ var ROWS = [
60
+ [1, 1, 1, 1, 1, 1],
61
+ [1, 2, 3, 2, 2, 2],
62
+ [1, 3, 1, 3, 3, 3],
63
+ [2, 1, 1, 1, 2, 2],
64
+ [2, 2, 1, 2, 3, 3],
65
+ [2, 3, 3, 3, 1, 1],
66
+ [3, 1, 3, 2, 1, 3],
67
+ [3, 2, 1, 3, 2, 1],
68
+ [3, 3, 2, 1, 3, 2],
69
+ [1, 1, 3, 3, 3, 2],
70
+ [1, 2, 2, 1, 1, 3],
71
+ [1, 3, 2, 2, 2, 1],
72
+ [2, 1, 2, 2, 3, 1],
73
+ [2, 2, 2, 3, 1, 2],
74
+ [2, 3, 3, 1, 2, 3],
75
+ [3, 1, 2, 3, 2, 3],
76
+ [3, 2, 3, 1, 3, 1],
77
+ [3, 3, 1, 2, 1, 2]
78
+ ];
79
+ var SCALING_PRESETS = Object.freeze(
80
+ Object.fromEntries(ROWS.map((row, index) => [
81
+ `H${String(index + 1).padStart(2, "0")}`,
82
+ Object.freeze(Object.fromEntries(SCALING_AXES.map((axis, i) => [axis, `${axis}${row[i]}`])))
83
+ ]))
84
+ );
85
+ function parseScalingConfig(value) {
86
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
87
+ throw new Error("Scaling config must be an object with S, TS, TC, O, C, W.");
88
+ }
89
+ const record2 = value;
90
+ for (const key of Object.keys(record2)) {
91
+ if (!SCALING_AXES.includes(key)) throw new Error(`Unknown scaling axis: ${key}`);
92
+ }
93
+ for (const axis of SCALING_AXES) {
94
+ if (![`${axis}1`, `${axis}2`, `${axis}3`].includes(String(record2[axis]))) {
95
+ throw new Error(`Invalid ${axis} design: ${String(record2[axis])}. Choose ${axis}1\u2013${axis}3; TC4 is excluded.`);
96
+ }
97
+ }
98
+ return Object.fromEntries(SCALING_AXES.map((axis) => [axis, record2[axis]]));
99
+ }
100
+ var DEFAULT_SCALING_LIMITS = Object.freeze({
101
+ previewChars: 8e3,
102
+ hardOutputChars: 64e3,
103
+ contextTriggerRatio: 0.75,
104
+ contextHardRatio: 0.9,
105
+ keepRecentTokens: 8e3,
106
+ summaryTokens: 1024,
107
+ rollupFanout: 3
108
+ });
109
+
110
+ // src/harnesses/scaling/experiments/events.ts
111
+ var AUDIT_ENTRY = "scaling-constraint-event";
112
+
113
+ // src/harnesses/scaling/experiments/paths.ts
114
+ import path2 from "node:path";
115
+ import { createHash } from "node:crypto";
116
+
117
+ // src/utils/filesystem/apply_patch.ts
118
+ var BEGIN_PATCH_MARKER = "*** Begin Patch";
119
+ var END_PATCH_MARKER = "*** End Patch";
120
+ var ADD_FILE_MARKER = "*** Add File: ";
121
+ var DELETE_FILE_MARKER = "*** Delete File: ";
122
+ var UPDATE_FILE_MARKER = "*** Update File: ";
123
+ var MOVE_TO_MARKER = "*** Move to: ";
124
+ var END_OF_FILE_MARKER = "*** End of File";
125
+ function patchError(message) {
126
+ return new Error(`Invalid patch: ${message}`);
127
+ }
128
+ function hunkError(lineNumber, message) {
129
+ return new Error(`Invalid patch hunk on line ${lineNumber}: ${message}`);
130
+ }
131
+ function parsePatchLines(patch) {
132
+ const trimmed = patch.trim();
133
+ const lines = trimmed ? trimmed.split("\n") : [];
134
+ return lines.map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
135
+ }
136
+ function parsePath(header, marker, lineNumber) {
137
+ const value = header.slice(marker.length);
138
+ if (!value) throw hunkError(lineNumber, `Missing path after '${marker.trimEnd()}'`);
139
+ return value;
140
+ }
141
+ function newChunk(changeContext) {
142
+ return {
143
+ ...changeContext === void 0 ? {} : { changeContext },
144
+ oldLines: [],
145
+ newLines: [],
146
+ contextLineIndices: [],
147
+ isEndOfFile: false
148
+ };
149
+ }
150
+ function chunkIsEmpty(chunk) {
151
+ return chunk.oldLines.length === 0 && chunk.newLines.length === 0;
152
+ }
153
+ function pushContextLine(chunk, line) {
154
+ chunk.contextLineIndices.push([chunk.oldLines.length, chunk.newLines.length]);
155
+ chunk.oldLines.push(line);
156
+ chunk.newLines.push(line);
157
+ }
158
+ function isHunkHeader(line) {
159
+ return line.startsWith(ADD_FILE_MARKER) || line.startsWith(DELETE_FILE_MARKER) || line.startsWith(UPDATE_FILE_MARKER);
160
+ }
161
+ function parseApplyPatch(patch) {
162
+ const lines = parsePatchLines(patch);
163
+ const first = lines[0]?.trim();
164
+ const last = lines.at(-1)?.trim();
165
+ if (first !== BEGIN_PATCH_MARKER) {
166
+ throw patchError(`The first line of the patch must be '${BEGIN_PATCH_MARKER}'`);
167
+ }
168
+ if (last !== END_PATCH_MARKER) {
169
+ throw patchError(`The last line of the patch must be '${END_PATCH_MARKER}'`);
170
+ }
171
+ const hunks = [];
172
+ let index = 1;
173
+ const endIndex = lines.length - 1;
174
+ while (index < endIndex) {
175
+ const rawHeader = lines[index] ?? "";
176
+ const header = rawHeader.trim();
177
+ const lineNumber = index + 1;
178
+ if (header.startsWith(ADD_FILE_MARKER)) {
179
+ const filePath = parsePath(header, ADD_FILE_MARKER, lineNumber);
180
+ index += 1;
181
+ const content = [];
182
+ while (index < endIndex) {
183
+ const line = lines[index] ?? "";
184
+ if (isHunkHeader(line.trim())) break;
185
+ if (!line.startsWith("+")) {
186
+ throw hunkError(
187
+ index + 1,
188
+ `Invalid Add File line for '${filePath}': '${line}'. Every added line must start with '+'`
189
+ );
190
+ }
191
+ content.push(line.slice(1));
192
+ index += 1;
193
+ }
194
+ if (content.length === 0) {
195
+ throw hunkError(lineNumber, `Add file hunk for path '${filePath}' is empty`);
196
+ }
197
+ hunks.push({ type: "add", path: filePath, contents: `${content.join("\n")}
198
+ ` });
199
+ continue;
200
+ }
201
+ if (header.startsWith(DELETE_FILE_MARKER)) {
202
+ hunks.push({
203
+ type: "delete",
204
+ path: parsePath(header, DELETE_FILE_MARKER, lineNumber)
205
+ });
206
+ index += 1;
207
+ continue;
208
+ }
209
+ if (header.startsWith(UPDATE_FILE_MARKER)) {
210
+ const filePath = parsePath(header, UPDATE_FILE_MARKER, lineNumber);
211
+ index += 1;
212
+ let movePath;
213
+ const possibleMove = lines[index]?.trim();
214
+ if (possibleMove?.startsWith(MOVE_TO_MARKER)) {
215
+ movePath = parsePath(possibleMove, MOVE_TO_MARKER, index + 1);
216
+ index += 1;
217
+ }
218
+ const chunks = [];
219
+ let active;
220
+ while (index < endIndex) {
221
+ const line = lines[index] ?? "";
222
+ const updateLine = line.trimEnd();
223
+ if (isHunkHeader(updateLine)) break;
224
+ const currentLineNumber = index + 1;
225
+ if (active?.isEndOfFile) {
226
+ if (!updateLine) {
227
+ index += 1;
228
+ continue;
229
+ }
230
+ if (updateLine !== "@@" && !updateLine.startsWith("@@ ")) {
231
+ throw hunkError(
232
+ currentLineNumber,
233
+ `Expected update hunk to start with a @@ context marker, got: '${line}'`
234
+ );
235
+ }
236
+ }
237
+ if (updateLine === "@@" || updateLine.startsWith("@@ ")) {
238
+ if (active && chunkIsEmpty(active)) {
239
+ throw hunkError(currentLineNumber, "Update hunk does not contain any lines");
240
+ }
241
+ active = newChunk(updateLine === "@@" ? void 0 : updateLine.slice(3));
242
+ chunks.push(active);
243
+ index += 1;
244
+ continue;
245
+ }
246
+ if (updateLine === END_OF_FILE_MARKER) {
247
+ if (!active || chunkIsEmpty(active)) {
248
+ throw hunkError(currentLineNumber, "Update hunk does not contain any lines");
249
+ }
250
+ active.isEndOfFile = true;
251
+ index += 1;
252
+ continue;
253
+ }
254
+ active ??= newChunk();
255
+ if (!chunks.includes(active)) chunks.push(active);
256
+ if (line === "") {
257
+ pushContextLine(active, "");
258
+ } else if (line.startsWith(" ")) {
259
+ pushContextLine(active, line.slice(1));
260
+ } else if (line.startsWith("+")) {
261
+ active.newLines.push(line.slice(1));
262
+ } else if (line.startsWith("-")) {
263
+ active.oldLines.push(line.slice(1));
264
+ } else {
265
+ throw hunkError(
266
+ currentLineNumber,
267
+ `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`
268
+ );
269
+ }
270
+ index += 1;
271
+ }
272
+ if (active && chunkIsEmpty(active)) {
273
+ throw hunkError(lineNumber, `Update file hunk for path '${filePath}' is empty`);
274
+ }
275
+ if (chunks.length === 0 && movePath === void 0) {
276
+ throw hunkError(lineNumber, `Update file hunk for path '${filePath}' is empty`);
277
+ }
278
+ hunks.push({
279
+ type: "update",
280
+ path: filePath,
281
+ ...movePath === void 0 ? {} : { movePath },
282
+ chunks
283
+ });
284
+ continue;
285
+ }
286
+ throw hunkError(
287
+ lineNumber,
288
+ `'${rawHeader}' is not a valid hunk header. Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'`
289
+ );
290
+ }
291
+ return hunks;
292
+ }
293
+
294
+ // src/harnesses/scaling/experiments/paths.ts
295
+ var sha256 = (value) => createHash("sha256").update(value).digest("hex");
296
+ var object = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
297
+ function literalShell(command) {
298
+ const words = [];
299
+ let word = "";
300
+ let quote = "";
301
+ let started = false;
302
+ const flush = () => {
303
+ if (started) words.push(word);
304
+ word = "";
305
+ started = false;
306
+ };
307
+ for (let i = 0; i < command.length; i++) {
308
+ const ch = command[i];
309
+ if (quote) {
310
+ if (ch === quote) quote = "";
311
+ else if (quote === '"' && /[$`\\]/u.test(ch)) return;
312
+ else word += ch;
313
+ continue;
314
+ }
315
+ if (/[;|&<`$(){}*?\[\]\\\n\r]/u.test(ch)) return;
316
+ if (ch === "'" || ch === '"') {
317
+ quote = ch;
318
+ started = true;
319
+ } else if (/\s/u.test(ch)) flush();
320
+ else if (ch === ">") {
321
+ flush();
322
+ words.push(command[i + 1] === ">" ? (i++, ">>") : ">");
323
+ } else {
324
+ word += ch;
325
+ started = true;
326
+ }
327
+ }
328
+ if (quote) return;
329
+ flush();
330
+ return words;
331
+ }
332
+ function operationPlan(name, input, cwd) {
333
+ const args = object(input);
334
+ const operations = [];
335
+ const paths = [];
336
+ let opaque = false;
337
+ const target = (raw, kind, predicted, independent = false) => {
338
+ if (typeof raw !== "string") {
339
+ opaque = true;
340
+ return;
341
+ }
342
+ paths.push(raw);
343
+ if (name === "bash" && (/^~/u.test(raw) || raw.split("/").includes(".."))) opaque = true;
344
+ if (["read", "read_file", "write", "edit", "grep", "glob"].includes(name) && (!raw || /^[@~]/u.test(raw) || /[\u00a0\u2000-\u200a\u202f\u205f\u3000]/u.test(raw))) opaque = true;
345
+ if (kind) operations.push({ path: path2.resolve(cwd, raw), rawPath: raw, kind, predicted, independent });
346
+ };
347
+ if (["read", "read_file"].includes(name)) target(args.path, "read");
348
+ else if (name === "write") target(args.path, "modify", typeof args.content === "string" ? sha256(args.content) : void 0, true);
349
+ else if (["edit", "append_file"].includes(name)) target(args.path, "modify");
350
+ else if (name === "grep" || name === "glob") target(args.path ?? ".");
351
+ else if (name === "apply_patch") {
352
+ try {
353
+ for (const hunk of parseApplyPatch(String(args.patch))) {
354
+ target(hunk.path, "modify", hunk.type === "add" ? sha256(hunk.contents) : void 0, hunk.type === "add");
355
+ if (hunk.type === "update" && hunk.movePath) target(hunk.movePath, "modify");
356
+ }
357
+ } catch {
358
+ opaque = true;
359
+ }
360
+ if (new Set(operations.map((op) => op.path)).size !== operations.length) opaque = true;
361
+ } else if (name === "bash") {
362
+ const argv = literalShell(String(args.command));
363
+ if (!argv?.length) return { operations, paths, opaque: true };
364
+ const [command, ...rest] = argv;
365
+ const redirect = rest.findIndex((s) => s === ">" || s === ">>");
366
+ if (redirect >= 0) {
367
+ const raw = rest[redirect + 1];
368
+ const params = rest.slice(0, redirect);
369
+ let content;
370
+ if (command === "printf" && params.length === 2 && ["%s", "%s\\n"].includes(params[0])) content = params[1] + (params[0] === "%s\\n" ? "\n" : "");
371
+ if (rest.length !== redirect + 2 || content === void 0) opaque = true;
372
+ target(raw, "modify", rest[redirect] === ">" && content !== void 0 ? sha256(content) : void 0, rest[redirect] === ">");
373
+ } else if (command === "cat" && rest.length === 1 && !rest[0].startsWith("-")) target(rest[0], "read");
374
+ else if (command === "pwd" && rest.length === 0) {
375
+ } else if (["cp", "mv", "rm", "touch", "truncate"].includes(command)) {
376
+ if (rest.every((arg) => !arg.startsWith("-") || /^(?:--|-[finvrRpa]+|--(?:force|recursive|verbose|no-clobber))$/u.test(arg))) {
377
+ for (const arg of rest) if (!arg.startsWith("-")) target(arg);
378
+ }
379
+ opaque = true;
380
+ } else if (["ls", "cat", "head", "tail", "wc", "sha256sum", "grep", "rg", "sed"].includes(command)) {
381
+ let skip = false;
382
+ let pattern = ["grep", "rg", "sed"].includes(command);
383
+ let options = true;
384
+ for (const arg of rest) {
385
+ if (skip) {
386
+ skip = false;
387
+ continue;
388
+ }
389
+ if (arg === "--" && options) {
390
+ options = false;
391
+ continue;
392
+ }
393
+ if (options && arg.startsWith("-")) {
394
+ if (["-n", "-c", "--lines", "--bytes"].includes(arg) && ["head", "tail"].includes(command)) skip = true;
395
+ else if (["-e", "--regexp"].includes(arg) && ["grep", "rg"].includes(command)) {
396
+ skip = true;
397
+ pattern = false;
398
+ } else if (["-g", "--glob", "--iglob", "-t", "--type", "--type-not", "-m", "--max-count", "-A", "-B", "-C"].includes(arg)) skip = true;
399
+ else if (arg === "--files" && command === "rg") pattern = false;
400
+ else if (!/^(?:-[alhRnriHvc]+|--(?:hidden|no-heading|line-number))$/u.test(arg)) opaque = true;
401
+ continue;
402
+ }
403
+ if (pattern) {
404
+ pattern = false;
405
+ continue;
406
+ }
407
+ target(arg);
408
+ }
409
+ if (["ls", "rg"].includes(command) && !paths.length) target(".");
410
+ if (command === "sed" || rest.some((arg) => /^--(?:pre|hostname-bin)/u.test(arg))) opaque = true;
411
+ } else opaque = true;
412
+ } else if (!["exec", "run_code", "submit_plan", "session_notes", "new_context", "session_history", "memory_lookup", "get_context_remaining", "subagent"].includes(name)) opaque = true;
413
+ return { operations, paths, opaque };
414
+ }
415
+
416
+ // src/verifiers/scaling/session.ts
417
+ var object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
418
+ var array = (value) => Array.isArray(value) ? value : [];
419
+ function parseSession(source, leafId) {
420
+ const entries = [];
421
+ const byId = /* @__PURE__ */ new Map();
422
+ let header;
423
+ for (const [index, line] of source.split(/\r?\n/u).entries()) {
424
+ if (!line.trim()) continue;
425
+ let value;
426
+ try {
427
+ value = object2(JSON.parse(line));
428
+ } catch {
429
+ throw new Error(`Invalid session JSON at line ${index + 1}`);
430
+ }
431
+ if (value.type === "session") {
432
+ if (header || entries.length) throw new Error("Expected one session header before entries");
433
+ header = value;
434
+ continue;
435
+ }
436
+ if (typeof value.id !== "string" || typeof value.type !== "string" || !(value.parentId === null || typeof value.parentId === "string")) throw new Error(`Invalid session entry at line ${index + 1}`);
437
+ if (byId.has(value.id)) throw new Error(`Duplicate entry ID at line ${index + 1}`);
438
+ const entry = { id: value.id, parentId: value.parentId, type: value.type, line: index + 1, value };
439
+ entries.push(entry);
440
+ byId.set(entry.id, entry);
441
+ }
442
+ if (!header || !entries.length) throw new Error("Expected a Pi session header and entries");
443
+ const leaf = byId.get(leafId ?? entries.at(-1).id);
444
+ if (!leaf) throw new Error("Requested leaf was not found");
445
+ const issues = [];
446
+ const branch = [];
447
+ const seen = /* @__PURE__ */ new Set();
448
+ let current = leaf;
449
+ while (current) {
450
+ if (seen.has(current.id)) throw new Error("Cycle in session ancestry");
451
+ seen.add(current.id);
452
+ branch.push(current);
453
+ if (current.parentId === null) break;
454
+ const parent = byId.get(current.parentId);
455
+ if (!parent) {
456
+ issues.push(`missing_parent:line_${current.line}`);
457
+ break;
458
+ }
459
+ if (parent.line >= current.line) throw new Error("Session parent must precede child");
460
+ current = parent;
461
+ }
462
+ branch.reverse();
463
+ const outerCalls = [];
464
+ const calls = [];
465
+ const byCallId = /* @__PURE__ */ new Map();
466
+ for (const entry of branch) {
467
+ if (entry.type !== "message") continue;
468
+ const message = object2(entry.value.message);
469
+ if (message.role === "assistant") for (const raw of array(message.content)) {
470
+ const part = object2(raw);
471
+ if (part.type !== "toolCall") continue;
472
+ if (typeof part.id !== "string" || typeof part.name !== "string" || byCallId.has(part.id)) throw new Error(`Invalid tool call at line ${entry.line}`);
473
+ const call = { id: part.id, name: part.name, args: part.arguments === void 0 ? void 0 : object2(part.arguments), turn: entry, status: "unknown" };
474
+ outerCalls.push(call);
475
+ calls.push(call);
476
+ byCallId.set(call.id, call);
477
+ }
478
+ if (message.role !== "toolResult") continue;
479
+ const outer = byCallId.get(String(message.toolCallId));
480
+ if (!outer || outer.outerId || outer.result) {
481
+ issues.push(`unmatched_result:line_${entry.line}`);
482
+ continue;
483
+ }
484
+ outer.result = entry;
485
+ outer.status = message.isError === true ? "error" : message.isError === false ? "ok" : "unknown";
486
+ if (message.toolName !== outer.name) issues.push(`mismatched_tool:line_${entry.line}`);
487
+ const nested = object2(message.nestedCalls);
488
+ if (message.nestedCalls !== void 0 && nested.complete !== true) issues.push(`incomplete_nested_calls:line_${entry.line}`);
489
+ for (const raw of array(nested.calls)) {
490
+ const item = object2(raw);
491
+ if (typeof item.id !== "string" || typeof item.name !== "string" || byCallId.has(item.id)) throw new Error(`Invalid nested call at line ${entry.line}`);
492
+ const call = {
493
+ id: item.id,
494
+ name: item.name,
495
+ args: item.arguments === void 0 ? void 0 : object2(item.arguments),
496
+ turn: outer.turn,
497
+ result: entry,
498
+ outerId: outer.id,
499
+ status: item.status === "ok" || item.status === "error" ? item.status : "unknown"
500
+ };
501
+ calls.push(call);
502
+ byCallId.set(call.id, call);
503
+ if (!call.args) issues.push(`missing_nested_arguments:line_${entry.line}`);
504
+ }
505
+ }
506
+ for (const call of calls) if (call.status === "unknown") issues.push(`unknown_call_outcome:line_${call.result?.line ?? call.turn.line}`);
507
+ for (const entry of branch) if (entry.value.customType === "scaling-observation") {
508
+ const id = object2(entry.value.data).callId;
509
+ if (typeof id === "string" && !byCallId.has(id)) issues.push(`unrecorded_observation:line_${entry.line}`);
510
+ }
511
+ const lastMessage = branch.findLast((entry) => entry.type === "message");
512
+ const last = object2(lastMessage?.value.message);
513
+ const pendingInput = branch.some((entry) => entry.line > (lastMessage?.line ?? 0) && entry.type === "custom_message");
514
+ const finished = last.role === "assistant" && last.stopReason === "stop" && !array(last.content).some((part) => object2(part).type === "toolCall") && !pendingInput;
515
+ if (!finished) issues.push("no_final_response_observed");
516
+ const metadataEntries = branch.filter((entry) => entry.value.customType === "scaling-config");
517
+ if (!metadataEntries.length) throw new Error("No scaling-config entry on the selected branch");
518
+ const metadata = object2(metadataEntries[0].value.data);
519
+ if (metadataEntries.some((entry) => JSON.stringify(entry.value.data) !== JSON.stringify(metadata))) throw new Error("Mixed scaling metadata on one branch; split the experiment before auditing");
520
+ return { header, entries: branch, leafId: leaf.id, issues: [...new Set(issues)], finished, calls, outerCalls, metadata };
521
+ }
522
+
523
+ // src/verifiers/scaling/constraints.ts
524
+ function progressRecord(value) {
525
+ const record2 = object(value);
526
+ return Object.keys(record2).sort().join(",") === "blockers,done,next" && ["done", "next", "blockers"].every((key) => Array.isArray(record2[key]) && record2[key].every((part) => typeof part === "string" && !!part.trim())) && ["done", "next", "blockers"].some((key) => record2[key].length > 0);
527
+ }
528
+ function heartbeat(text) {
529
+ let fence;
530
+ for (const line of text.split("\n")) {
531
+ const marker = line.match(/^\s*(`{3,}|~{3,})/u)?.[1];
532
+ if (marker) {
533
+ if (!fence) fence = marker;
534
+ else if (marker[0] === fence[0] && marker.length >= fence.length) fence = void 0;
535
+ continue;
536
+ }
537
+ if (fence) continue;
538
+ const payload = line.match(/^<heartbeat>([^\n]+)<\/heartbeat>\s*$/u)?.[1];
539
+ if (!payload) continue;
540
+ try {
541
+ if (progressRecord(JSON.parse(payload))) return true;
542
+ } catch {
543
+ }
544
+ }
545
+ return false;
546
+ }
547
+ function savedProgress(suffix) {
548
+ if (!suffix?.endsWith("\n")) return false;
549
+ return suffix.split("\n").some((line) => {
550
+ try {
551
+ return progressRecord(JSON.parse(line));
552
+ } catch {
553
+ return false;
554
+ }
555
+ });
556
+ }
557
+ var same = (a, b) => !!a?.sha256 && a.sha256 === b.sha256 && a.identity === b.identity;
558
+ function verifyConstraintEvents(events, experiment, cwd, depth = 0, evaluatedConstraints = experiment.constraints) {
559
+ const evidence = [];
560
+ const c = evaluatedConstraints;
561
+ const known = /* @__PURE__ */ new Map();
562
+ const uncertain = /* @__PURE__ */ new Set();
563
+ const pages = /* @__PURE__ */ new Map();
564
+ const ends = /* @__PURE__ */ new Map();
565
+ const starts = /* @__PURE__ */ new Map();
566
+ const executing = /* @__PURE__ */ new Set();
567
+ const persistenceAttempts = [];
568
+ let round = 0;
569
+ let lastHeartbeat = 0;
570
+ let lastSaved = 0;
571
+ let heartbeatMiss = -1;
572
+ let saveMiss = -1;
573
+ let previousSeq = 0;
574
+ let reset = false;
575
+ let settled = false;
576
+ const add = (module, event, status, reason, extra = {}) => {
577
+ if (c[module] && (!depth || !module.startsWith("U"))) evidence.push({ module, seq: event.seq, round: event.round, depth, status, reason, ...extra });
578
+ };
579
+ const coverage = (event, reason, ids = CONSTRAINT_IDS) => {
580
+ for (const id of ids) add(id, event, "insufficient_evidence", reason);
581
+ };
582
+ for (const event of events) {
583
+ if (event.version !== 1 || event.seq !== previousSeq + 1) coverage(event, "Audit event sequence is missing or unsupported");
584
+ previousSeq = event.seq;
585
+ switch (event.kind) {
586
+ case "init":
587
+ if (JSON.stringify(event.experiment) !== JSON.stringify(experiment)) coverage(event, "Audit configuration mismatch");
588
+ break;
589
+ case "response":
590
+ settled = false;
591
+ if (event.round !== round + 1) coverage(event, "Accepted response counter is discontinuous", ["U02", "U07"]);
592
+ round = event.round;
593
+ if (heartbeat(event.text)) {
594
+ lastHeartbeat = round;
595
+ add("U02", event, "pass", "Structured model heartbeat observed");
596
+ }
597
+ if (c.U02 && round >= lastHeartbeat + c.U02.every && heartbeatMiss !== lastHeartbeat) {
598
+ heartbeatMiss = lastHeartbeat;
599
+ add("U02", event, "fail", `Heartbeat due by response ${lastHeartbeat + c.U02.every}`);
600
+ }
601
+ break;
602
+ case "attempt": {
603
+ add("A01", event, c.A01?.forbiddenTools.includes(event.name) ? "fail" : "pass", c.A01?.forbiddenTools.includes(event.name) ? "Forbidden registered tool attempted (including rejected attempts)" : "Allowed registered tool attempted", { callId: event.callId });
604
+ const plan = operationPlan(event.name, event.args, cwd);
605
+ for (const raw of plan.paths) add("A07", event, path3.isAbsolute(raw) ? "pass" : "fail", "Checked the submitted path before normalization", { callId: event.callId, path: raw });
606
+ if (plan.opaque) add("A07", event, "insufficient_evidence", "Some path operands cannot be established from this call", { callId: event.callId });
607
+ break;
608
+ }
609
+ case "start": {
610
+ executing.add(event.callId);
611
+ const bases = /* @__PURE__ */ new Map();
612
+ starts.set(event.callId, bases);
613
+ if (event.opaque) coverage(event, "Opaque operation: intermediate file effects are not completely observed", ["A02", "A05"]);
614
+ for (const { operation: op, before } of event.operations) {
615
+ if (op.kind !== "modify") continue;
616
+ const prior = [...known.values()].find((value) => same(value.state, before)) ?? known.get(op.path);
617
+ bases.set(op.path, prior);
618
+ const status = before.exists === false || same(prior?.state, before) ? "pass" : before.error || before.exists === void 0 || prior ? "insufficient_evidence" : !reset && same(pages.get(op.path)?.state, before) ? "fail" : reset || uncertain.has(op.path) ? "insufficient_evidence" : "fail";
619
+ const reason = before.exists === false ? "New target; no previous contents to read" : same(prior?.state, before) ? "Current file matches contents established in the active context" : prior ? "Version conflict: file changed outside the established context; intent is not inferred" : status === "fail" ? "Existing file modified without a delivered complete read or known full contents" : "Exact current-content knowledge cannot be established";
620
+ add("A05", event, status, reason, { callId: event.callId, path: op.path });
621
+ }
622
+ break;
623
+ }
624
+ case "end":
625
+ executing.delete(event.callId);
626
+ ends.set(event.callId, event);
627
+ for (const change of event.changes) {
628
+ const op = change.operation;
629
+ if (change.concurrent) coverage(event, `Overlapping operations on ${op.path}`, ["A02", "A05"]);
630
+ if (op.kind === "read" && (change.completeRead || change.readRange)) uncertain.add(op.path);
631
+ if (op.kind === "modify" && !same(change.before, change.after)) {
632
+ known.delete(op.path);
633
+ uncertain.add(op.path);
634
+ }
635
+ if (op.path === experiment.processFile && op.kind !== "read") {
636
+ if (!depth && op.kind === "modify") persistenceAttempts.push({ callId: event.callId, round: event.round, completed: !change.after.error, toolError: event.isError, saved: !change.concurrent && !!change.prefixPreserved && savedProgress(change.suffix) });
637
+ const changed = change.before.sha256 !== change.after.sha256 || change.before.exists !== change.after.exists;
638
+ if (op.kind === "modify" || changed) add("A02", event, change.concurrent || change.prefixPreserved === void 0 ? "insufficient_evidence" : change.prefixPreserved ? "pass" : "fail", change.prefixPreserved ? "Logical modification preserved every previous byte" : "Process history was removed/changed, or its preservation could not be established", { callId: event.callId, path: op.path });
639
+ if (!depth && !change.concurrent && change.prefixPreserved && savedProgress(change.suffix)) {
640
+ lastSaved = event.round;
641
+ add("U07", event, "pass", `Progress exists in the readable process file at response ${event.round}${event.isError ? "; tool also reported an error" : ""}`, { callId: event.callId, path: op.path });
642
+ }
643
+ }
644
+ }
645
+ if (event.opaque) {
646
+ for (const key of known.keys()) uncertain.add(key);
647
+ known.clear();
648
+ reset = true;
649
+ }
650
+ break;
651
+ case "delivery": {
652
+ const end = ends.get(event.callId);
653
+ if (!end || end.isError || end.opaque) break;
654
+ for (const change of end.changes) {
655
+ const op = change.operation;
656
+ if (change.concurrent || !change.after.sha256) continue;
657
+ if (op.kind === "read" && change.completeRead) {
658
+ known.set(op.path, { state: change.after, sources: /* @__PURE__ */ new Set([event.callId]) });
659
+ uncertain.delete(op.path);
660
+ }
661
+ if (op.kind === "read" && change.readRange) {
662
+ const range = change.readRange;
663
+ let page = pages.get(op.path);
664
+ if (!page || !same(page.state, change.after) || page.total !== range.total) {
665
+ page = { state: change.after, total: range.total, ranges: [], sources: /* @__PURE__ */ new Set() };
666
+ pages.set(op.path, page);
667
+ }
668
+ page.ranges.push([range.start, range.end]);
669
+ page.sources.add(event.callId);
670
+ let covered = 0;
671
+ for (const [start, end2] of page.ranges.sort((a, b) => a[0] - b[0])) {
672
+ if (start > covered) break;
673
+ covered = Math.max(covered, end2);
674
+ }
675
+ if (covered === page.total) {
676
+ known.set(op.path, { state: page.state, sources: new Set(page.sources) });
677
+ uncertain.delete(op.path);
678
+ }
679
+ }
680
+ if (op.kind === "modify" && op.predicted === change.after.sha256) {
681
+ const prior = starts.get(event.callId)?.get(op.path);
682
+ if (op.independent || change.before.exists === false || same(prior?.state, change.before)) {
683
+ known.set(op.path, { state: change.after, sources: /* @__PURE__ */ new Set([...op.independent ? [] : prior?.sources ?? [], event.callId]) });
684
+ uncertain.delete(op.path);
685
+ }
686
+ }
687
+ }
688
+ break;
689
+ }
690
+ case "context": {
691
+ const present = new Set(event.deliveredCalls);
692
+ for (const [key, value] of known) if ([...value.sources].some((id) => !present.has(id))) {
693
+ known.delete(key);
694
+ uncertain.add(key);
695
+ }
696
+ for (const [key, value] of pages) if ([...value.sources].some((id) => !present.has(id))) pages.delete(key);
697
+ break;
698
+ }
699
+ case "reset":
700
+ known.clear();
701
+ pages.clear();
702
+ reset = true;
703
+ break;
704
+ case "boundary":
705
+ if (c.U07 && event.round >= lastSaved + c.U07.every && saveMiss !== lastSaved) {
706
+ saveMiss = lastSaved;
707
+ add("U07", event, "fail", `No completed readable progress record by response ${lastSaved + c.U07.every}; inspect tool errors for environmental failures`);
708
+ }
709
+ break;
710
+ case "settle":
711
+ settled = !event.aborted;
712
+ break;
713
+ case "child": {
714
+ if (!event.events.length) coverage(event, "Child execution has no constraint audit evidence", ["A01", "A02", "A05", "A07"]);
715
+ else evidence.push(...verifyConstraintEvents(event.events, experiment, cwd, 1, evaluatedConstraints).evidence.map((row) => ({ ...row, sessionFile: event.sessionFile })));
716
+ known.clear();
717
+ reset = true;
718
+ break;
719
+ }
720
+ }
721
+ }
722
+ const last = events.at(-1);
723
+ if (last && (!settled || !events.some((event) => event.kind === "init"))) coverage(last, "Audit session is unfinished or initialization is missing");
724
+ if (last && executing.size) coverage(last, `File/tool executions have no completion evidence: ${[...executing].join(", ")}`);
725
+ const rules = CONSTRAINT_IDS.filter((id) => c[id] && (!depth || !id.startsWith("U"))).map((id) => {
726
+ const items = evidence.filter((item) => item.module === id);
727
+ const counts = { pass: 0, fail: 0, insufficient_evidence: 0 };
728
+ for (const item of items) counts[item.status]++;
729
+ const status = counts.fail ? "fail" : counts.insufficient_evidence || !events.length ? "insufficient_evidence" : counts.pass ? "pass" : "not_applicable";
730
+ return { id, status, counts, opportunities: items.length };
731
+ });
732
+ return {
733
+ version: 1,
734
+ verifier: "scaling-constraints-v1",
735
+ evaluatedConstraints,
736
+ rules,
737
+ evidence,
738
+ persistenceAttempts,
739
+ clock: { round, lastHeartbeat, lastSaved },
740
+ limitations: ["Trusted runtime audit, not tamper-proof sandboxing.", "File snapshots are bounded to 2 MiB and are not atomic against external writers.", "Opaque shell effects and unsupported delivery formats have incomplete coverage.", "Heartbeats verify structure and timing, not truthfulness."]
741
+ };
742
+ }
743
+ function verifyConstraintSession(source, leafId, evaluate) {
744
+ const trace = parseSession(source, leafId);
745
+ const experiment = trace.metadata.experiment;
746
+ if (!experiment) throw new Error("This session has no scaling experiment metadata; historical traces cannot prove the new constraints");
747
+ const events = trace.entries.filter((entry) => entry.type === "custom" && entry.value.customType === AUDIT_ENTRY).map((entry) => entry.value.data);
748
+ const requested = evaluate === void 0 ? experiment : parseExperiment(evaluate, String(trace.header.cwd), parseScalingConfig(trace.metadata.config));
749
+ if (requested.processFile !== experiment.processFile || JSON.stringify(requested.toolProfile) !== JSON.stringify(experiment.toolProfile)) throw new Error("Counterfactual rules require the same toolProfile and processFile as the recorded experiment");
750
+ const report = verifyConstraintEvents(events, experiment, String(trace.header.cwd), Number(trace.metadata.depth ?? 0), requested.constraints);
751
+ if (trace.issues.some((issue) => issue.startsWith("missing_parent:"))) {
752
+ for (const rule of report.rules) if (rule.status !== "fail") rule.status = "insufficient_evidence";
753
+ }
754
+ return { ...report, session: { id: trace.header.id, leafId: trace.leafId }, experiment };
755
+ }
756
+
757
+ // src/verifiers/scaling/constraints-cli.ts
758
+ async function main() {
759
+ const args = process.argv.slice(2);
760
+ if (args[0] === "--help") {
761
+ process.stdout.write("Usage: npm run verify:scaling-constraints -- SESSION.jsonl [--leaf ID] [--rules EXPERIMENT.json] [--out NEW_REPORT.json]\n--rules evaluates a baseline using the same tool profile and different prompt constraints.\nExit: 0 no detected violations; 1 violations; 2 invalid input; 3 incomplete evidence.\n");
762
+ return;
763
+ }
764
+ const source = args.shift();
765
+ if (!source || source.startsWith("--")) throw new Error("Expected a session JSONL file; use --help");
766
+ const flags = /* @__PURE__ */ new Map();
767
+ while (args.length) {
768
+ const key = args.shift();
769
+ const value = args.shift();
770
+ if (!["--out", "--leaf", "--rules"].includes(key) || flags.has(key) || !value || value.startsWith("--")) throw new Error(`Invalid argument ${key}`);
771
+ flags.set(key, value);
772
+ }
773
+ const evaluate = flags.has("--rules") ? JSON.parse(await readFile(flags.get("--rules"), "utf8")) : void 0;
774
+ const report = verifyConstraintSession(await readFile(source, "utf8"), flags.get("--leaf"), evaluate);
775
+ const output = JSON.stringify({ ...report, source: path4.resolve(source) }, null, 2) + "\n";
776
+ if (flags.has("--out")) await writeFile(flags.get("--out"), output, { flag: "wx", mode: 384 });
777
+ else process.stdout.write(output);
778
+ process.stderr.write(report.rules.map((rule) => `${rule.id}: ${rule.status}`).join("; ") + "\n");
779
+ process.exitCode = report.rules.some((rule) => rule.status === "fail") ? 1 : report.rules.some((rule) => rule.status === "insufficient_evidence") ? 3 : 0;
780
+ }
781
+ main().catch((error) => {
782
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}
783
+ `);
784
+ process.exitCode = 2;
785
+ });
786
+ //# sourceMappingURL=verify-scaling-constraints.js.map