@openclaw/tokenjuice 2026.9.5 → 2026.9.6

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.
@@ -1,5 +1,5 @@
1
1
  // src/hosts/opencode/extension/runtime.ts
2
- import { readFile as readFile3, stat } from "node:fs/promises";
2
+ import { readFile as readFile4, stat as stat2 } from "node:fs/promises";
3
3
 
4
4
  // src/core/command-identity.ts
5
5
  import { basename } from "node:path";
@@ -1283,6 +1283,315 @@ function readNoOmissionFromEnv(env = process.env) {
1283
1283
  return NO_OMISSION_TRUTHY_VALUES.has(env[NO_OMISSION_ENV] ?? "");
1284
1284
  }
1285
1285
 
1286
+ // src/core/artifacts.ts
1287
+ import { mkdir as mkdir2, readFile as readFile2, readdir, writeFile as writeFile2 } from "node:fs/promises";
1288
+ import { randomUUID as randomUUID2 } from "node:crypto";
1289
+ import { homedir } from "node:os";
1290
+ import { join as join2 } from "node:path";
1291
+
1292
+ // src/core/bounded-jsonl.ts
1293
+ import { appendFile, lstat, mkdir, open, opendir, readFile, rm, rmdir, stat, unlink, writeFile } from "node:fs/promises";
1294
+ import { createHash, randomUUID } from "node:crypto";
1295
+ import { join } from "node:path";
1296
+ var DAY_MS = 24 * 60 * 60 * 1e3;
1297
+ var LOCK_RETRIES = 8;
1298
+ var LOCK_RETRY_MS = 10;
1299
+ var MAX_RETENTION_DAYS = 365;
1300
+ var MAX_SHARD_COUNT = 100;
1301
+ var MAX_STORE_FILES = 1e4;
1302
+ var MAX_SEGMENT_BYTES = 64 * 1024 * 1024;
1303
+ var DIRECTORY_ENTRY_SLACK = 256;
1304
+ var DEFAULT_RETENTION_DAYS = 14;
1305
+ var DEFAULT_SHARD_COUNT = 8;
1306
+ var DEFAULT_MAX_SEGMENT_BYTES = 1024 * 1024;
1307
+ function wait(ms) {
1308
+ return new Promise((resolvePromise) => {
1309
+ setTimeout(resolvePromise, ms);
1310
+ });
1311
+ }
1312
+ function positiveInteger(value, fallback, name, maximum) {
1313
+ const resolved = value ?? fallback;
1314
+ if (!Number.isSafeInteger(resolved) || resolved <= 0 || resolved > maximum) {
1315
+ throw new RangeError(`${name} must be a positive integer no greater than ${maximum}`);
1316
+ }
1317
+ return resolved;
1318
+ }
1319
+ function resolveStoreOptions(options) {
1320
+ const retentionDays = positiveInteger(
1321
+ options.retentionDays,
1322
+ DEFAULT_RETENTION_DAYS,
1323
+ "retentionDays",
1324
+ MAX_RETENTION_DAYS
1325
+ );
1326
+ const shardCount = positiveInteger(
1327
+ options.shardCount,
1328
+ DEFAULT_SHARD_COUNT,
1329
+ "shardCount",
1330
+ MAX_SHARD_COUNT
1331
+ );
1332
+ if (retentionDays * shardCount > MAX_STORE_FILES) {
1333
+ throw new RangeError(`retentionDays * shardCount must not exceed ${MAX_STORE_FILES}`);
1334
+ }
1335
+ return {
1336
+ retentionDays,
1337
+ shardCount,
1338
+ maxSegmentBytes: positiveInteger(
1339
+ options.maxSegmentBytes,
1340
+ DEFAULT_MAX_SEGMENT_BYTES,
1341
+ "maxSegmentBytes",
1342
+ MAX_SEGMENT_BYTES
1343
+ )
1344
+ };
1345
+ }
1346
+ function formatDay(date) {
1347
+ return date.toISOString().slice(0, 10);
1348
+ }
1349
+ function shardFor(id, shardCount) {
1350
+ const digest = createHash("sha256").update(id).digest();
1351
+ return digest[0] % shardCount;
1352
+ }
1353
+ function segmentName(prefix, day, shard) {
1354
+ return `${prefix}-${day}-${String(shard).padStart(2, "0")}.jsonl`;
1355
+ }
1356
+ function parseSegmentDay(name, prefix) {
1357
+ const escapedPrefix = prefix.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
1358
+ return new RegExp(`^${escapedPrefix}-(\\d{4}-\\d{2}-\\d{2})-\\d{2}\\.jsonl$`, "u").exec(name)?.[1];
1359
+ }
1360
+ async function tryCreateLock(lockPath) {
1361
+ try {
1362
+ await mkdir(lockPath, { mode: 448 });
1363
+ } catch (error) {
1364
+ if (error.code === "EEXIST") {
1365
+ return void 0;
1366
+ }
1367
+ throw error;
1368
+ }
1369
+ const owner = `${process.pid}:${randomUUID()}`;
1370
+ try {
1371
+ await writeFile(join(lockPath, "owner"), owner, { encoding: "utf8", flag: "wx", mode: 384 });
1372
+ return owner;
1373
+ } catch {
1374
+ return void 0;
1375
+ }
1376
+ }
1377
+ async function releaseLock(lockPath, owner) {
1378
+ try {
1379
+ const ownerPath = join(lockPath, "owner");
1380
+ if (await readFile(ownerPath, "utf8") === owner) {
1381
+ await unlink(ownerPath);
1382
+ await rmdir(lockPath);
1383
+ }
1384
+ } catch {
1385
+ }
1386
+ }
1387
+ async function acquireLock(lockPath) {
1388
+ for (let attempt = 0; attempt <= LOCK_RETRIES; attempt += 1) {
1389
+ const owner = await tryCreateLock(lockPath);
1390
+ if (owner) {
1391
+ return owner;
1392
+ }
1393
+ if (attempt < LOCK_RETRIES) {
1394
+ await wait(LOCK_RETRY_MS);
1395
+ }
1396
+ }
1397
+ return void 0;
1398
+ }
1399
+ async function pruneExpiredSegments(directory, prefix, retentionDays, maxFiles, now) {
1400
+ const oldestDay = formatDay(new Date(now.getTime() - (retentionDays - 1) * DAY_MS));
1401
+ const directoryHandle = await opendir(directory);
1402
+ let inspected = 0;
1403
+ try {
1404
+ for await (const entry of directoryHandle) {
1405
+ inspected += 1;
1406
+ if (inspected > maxFiles * 2 + DIRECTORY_ENTRY_SLACK) {
1407
+ break;
1408
+ }
1409
+ if (!entry.isFile()) {
1410
+ continue;
1411
+ }
1412
+ const day = parseSegmentDay(entry.name, prefix);
1413
+ if (day && day < oldestDay) {
1414
+ const path = join(directory, entry.name);
1415
+ const lockPath = `${path}.lock`;
1416
+ const owner = await tryCreateLock(lockPath);
1417
+ if (!owner) {
1418
+ continue;
1419
+ }
1420
+ try {
1421
+ await rm(path, { force: true });
1422
+ } finally {
1423
+ await releaseLock(lockPath, owner);
1424
+ }
1425
+ }
1426
+ }
1427
+ } finally {
1428
+ await directoryHandle.close().catch(() => {
1429
+ });
1430
+ }
1431
+ }
1432
+ async function countOwnedSegments(directory, prefix, maxFiles) {
1433
+ const directoryHandle = await opendir(directory);
1434
+ let count = 0;
1435
+ let inspected = 0;
1436
+ try {
1437
+ for await (const entry of directoryHandle) {
1438
+ inspected += 1;
1439
+ if (inspected > maxFiles * 2 + DIRECTORY_ENTRY_SLACK) {
1440
+ return { count, complete: false };
1441
+ }
1442
+ if (entry.isFile() && parseSegmentDay(entry.name, prefix)) {
1443
+ count += 1;
1444
+ if (count >= maxFiles) {
1445
+ return { count, complete: true };
1446
+ }
1447
+ }
1448
+ }
1449
+ } finally {
1450
+ await directoryHandle.close().catch(() => {
1451
+ });
1452
+ }
1453
+ return { count, complete: true };
1454
+ }
1455
+ async function appendBoundedJsonl(directory, prefix, id, value, options = {}) {
1456
+ const { retentionDays, shardCount, maxSegmentBytes } = resolveStoreOptions(options);
1457
+ const now = options.now ?? /* @__PURE__ */ new Date();
1458
+ if (!Number.isFinite(now.getTime())) {
1459
+ throw new RangeError("now must be a valid Date");
1460
+ }
1461
+ const line = `${JSON.stringify(value)}
1462
+ `;
1463
+ const lineBytes = Buffer.byteLength(line, "utf8");
1464
+ if (lineBytes > maxSegmentBytes) {
1465
+ return void 0;
1466
+ }
1467
+ await mkdir(directory, { recursive: true, mode: 448 });
1468
+ const maxFiles = retentionDays * shardCount;
1469
+ const path = join(directory, segmentName(prefix, formatDay(now), shardFor(id, shardCount)));
1470
+ const lockPath = `${path}.lock`;
1471
+ const admissionLockPath = join(directory, `.${prefix}.admission.lock`);
1472
+ const admissionOwner = await acquireLock(admissionLockPath);
1473
+ if (!admissionOwner) {
1474
+ return void 0;
1475
+ }
1476
+ let owner;
1477
+ try {
1478
+ await pruneExpiredSegments(directory, prefix, retentionDays, maxFiles, now);
1479
+ let targetExists = false;
1480
+ try {
1481
+ targetExists = (await lstat(path)).isFile();
1482
+ if (!targetExists) {
1483
+ return void 0;
1484
+ }
1485
+ } catch (error) {
1486
+ if (error.code !== "ENOENT") {
1487
+ throw error;
1488
+ }
1489
+ }
1490
+ if (!targetExists) {
1491
+ const segmentCount = await countOwnedSegments(directory, prefix, maxFiles);
1492
+ if (!segmentCount.complete || segmentCount.count >= maxFiles) {
1493
+ return void 0;
1494
+ }
1495
+ }
1496
+ owner = await acquireLock(lockPath);
1497
+ if (!owner) {
1498
+ return void 0;
1499
+ }
1500
+ if (!targetExists) {
1501
+ try {
1502
+ const file = await open(path, "wx", 384);
1503
+ await file.close();
1504
+ } catch (error) {
1505
+ await releaseLock(lockPath, owner);
1506
+ owner = void 0;
1507
+ if (error.code === "EEXIST") {
1508
+ return void 0;
1509
+ }
1510
+ throw error;
1511
+ }
1512
+ }
1513
+ } catch (error) {
1514
+ if (owner) {
1515
+ await releaseLock(lockPath, owner);
1516
+ owner = void 0;
1517
+ }
1518
+ throw error;
1519
+ } finally {
1520
+ await releaseLock(admissionLockPath, admissionOwner);
1521
+ }
1522
+ if (!owner) {
1523
+ return void 0;
1524
+ }
1525
+ try {
1526
+ let currentBytes = 0;
1527
+ try {
1528
+ currentBytes = (await stat(path)).size;
1529
+ } catch (error) {
1530
+ if (error.code !== "ENOENT") {
1531
+ throw error;
1532
+ }
1533
+ }
1534
+ if (currentBytes + lineBytes > maxSegmentBytes) {
1535
+ return void 0;
1536
+ }
1537
+ await appendFile(path, line, { encoding: "utf8", mode: 384 });
1538
+ return path;
1539
+ } finally {
1540
+ await releaseLock(lockPath, owner);
1541
+ }
1542
+ }
1543
+
1544
+ // src/core/execution-input.ts
1545
+ function normalizeExecutionInput(input) {
1546
+ const shellWrapped = unwrapShellRunner(input);
1547
+ if (shellWrapped) {
1548
+ const effectiveCommand2 = stripLeadingCdPrefix(shellWrapped);
1549
+ if (isCompoundShellCommand(effectiveCommand2)) {
1550
+ const { argv: _argv, ...restInput } = input;
1551
+ return {
1552
+ ...restInput,
1553
+ command: effectiveCommand2
1554
+ };
1555
+ }
1556
+ const argv2 = resolveEffectiveCommand({ command: effectiveCommand2 })?.argv ?? tokenizeCommand(effectiveCommand2);
1557
+ if (argv2.length === 0) {
1558
+ return {
1559
+ ...input,
1560
+ command: effectiveCommand2
1561
+ };
1562
+ }
1563
+ return {
1564
+ ...input,
1565
+ command: argv2.join(" "),
1566
+ argv: argv2
1567
+ };
1568
+ }
1569
+ const effective = resolveEffectiveCommand(input);
1570
+ if (effective?.argv.length) {
1571
+ return {
1572
+ ...input,
1573
+ ...effective.command ? { command: effective.command } : {},
1574
+ argv: effective.argv
1575
+ };
1576
+ }
1577
+ if (input.argv?.length || !input.command) {
1578
+ return input;
1579
+ }
1580
+ const effectiveCommand = stripLeadingCdPrefix(input.command);
1581
+ if (isCompoundShellCommand(effectiveCommand)) {
1582
+ return input;
1583
+ }
1584
+ const argv = tokenizeCommand(effectiveCommand);
1585
+ if (argv.length === 0) {
1586
+ return input;
1587
+ }
1588
+ return {
1589
+ ...input,
1590
+ command: argv.join(" "),
1591
+ argv
1592
+ };
1593
+ }
1594
+
1286
1595
  // src/core/compaction-metadata.ts
1287
1596
  var NO_COMPACTION_METADATA = {
1288
1597
  authoritative: false,
@@ -1312,9 +1621,6 @@ function mergeCompactionMetadata(...values) {
1312
1621
  return buildCompactionMetadata(presentValues.every((value) => value.authoritative), ...kinds);
1313
1622
  }
1314
1623
 
1315
- // src/core/reduce-utils.ts
1316
- import { createHash } from "node:crypto";
1317
-
1318
1624
  // src/core/text.ts
1319
1625
  var ANSI_CSI_PATTERN = new RegExp(String.raw`\u001B\[[0-?]*[ -/]*[@-~]`, "g");
1320
1626
  var ANSI_OSC_PATTERN = new RegExp(String.raw`\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)`, "g");
@@ -1488,452 +1794,508 @@ function pluralize(count, noun) {
1488
1794
  return `${count} ${noun}s`;
1489
1795
  }
1490
1796
 
1491
- // src/core/reduce-utils.ts
1492
- function compactWhitespace(text) {
1493
- return text.replace(/\s+/gu, " ").trim();
1494
- }
1495
- function shortHash(text) {
1496
- return createHash("sha256").update(text).digest("hex").slice(0, 12);
1497
- }
1498
- function clipMiddleWithHashStrict(text, maxChars, noOmit = false) {
1499
- if (countTextChars(text) <= maxChars) {
1500
- return { text };
1501
- }
1502
- if (noOmit) {
1503
- return {
1504
- text,
1505
- compaction: createPassthroughCompactionMetadata("no-omit-char-clip-passthrough")
1506
- };
1797
+ // src/core/source.ts
1798
+ var DEFAULT_CLI_ARTIFACT_SOURCE = "cli";
1799
+ function normalizeArtifactSource(value) {
1800
+ if (typeof value !== "string") {
1801
+ return null;
1507
1802
  }
1508
- const omitted = countTextChars(text) - maxChars;
1509
- const marker = `...[${omitted} chars omitted, sha256:${shortHash(text)}]...`;
1510
- const markerChars = countTextChars(marker);
1511
- if (maxChars <= markerChars) {
1512
- return {
1513
- text: sliceTextChars(marker, 0, maxChars),
1514
- compaction: createCompactionMetadata("hashed-middle-clip")
1515
- };
1803
+ const source = value.trim().toLowerCase().replace(/[_\s]+/gu, "-").replace(/[^a-z0-9.-]+/gu, "-").replace(/^-+|-+$/gu, "");
1804
+ if (!source) {
1805
+ return null;
1516
1806
  }
1517
- const bodyChars = maxChars - markerChars;
1518
- const headChars = Math.ceil(bodyChars * 0.7);
1519
- const tailChars = Math.max(0, bodyChars - headChars);
1520
- return {
1521
- text: `${sliceTextChars(text, 0, headChars)}${marker}${tailChars > 0 ? sliceTextChars(text, -tailChars) : ""}`,
1522
- compaction: createCompactionMetadata("hashed-middle-clip")
1523
- };
1524
- }
1525
- function minifyJsonLexically(rawText) {
1526
- const text = rawText.trim();
1527
- let output = "";
1528
- let inString = false;
1529
- let escaped = false;
1530
- for (const char of text) {
1531
- if (inString) {
1532
- output += char;
1533
- if (escaped) {
1534
- escaped = false;
1535
- } else if (char === "\\") {
1536
- escaped = true;
1537
- } else if (char === '"') {
1538
- inString = false;
1539
- }
1540
- continue;
1541
- }
1542
- if (char === '"') {
1543
- inString = true;
1544
- output += char;
1545
- continue;
1546
- }
1547
- if (/\s/u.test(char)) {
1548
- continue;
1549
- }
1550
- output += char;
1807
+ if (source.startsWith("amazon-q") || source.startsWith("amazonq") || source.startsWith("aws-q")) {
1808
+ return "amazon-q";
1551
1809
  }
1552
- return output;
1553
- }
1554
- function clipMiddleWithHash(text, maxChars, noOmit = false) {
1555
- if (countTextChars(text) <= maxChars) {
1556
- return { text };
1810
+ if (source.startsWith("claude-code") || source === "claude") {
1811
+ return "claude-code";
1557
1812
  }
1558
- if (noOmit) {
1559
- return {
1560
- text,
1561
- compaction: createPassthroughCompactionMetadata("no-omit-char-clip-passthrough")
1562
- };
1813
+ if (source.startsWith("cline")) {
1814
+ return "cline";
1563
1815
  }
1564
- const omitted = countTextChars(text) - maxChars;
1565
- const headChars = Math.max(20, Math.floor(maxChars * 0.55));
1566
- const tailChars = Math.max(20, maxChars - headChars);
1567
- return {
1568
- text: `${sliceTextChars(text, 0, headChars)} ...[${omitted} chars omitted, sha256:${shortHash(text)}]... ${sliceTextChars(text, -tailChars)}`,
1569
- compaction: createCompactionMetadata("hashed-middle-clip")
1570
- };
1571
- }
1572
- function compactWholeJsonText(rawText, maxChars, noOmit = false) {
1573
- return parseJsonValue(rawText) === null ? null : clipMiddleWithHashStrict(minifyJsonLexically(rawText), maxChars, noOmit);
1574
- }
1575
- function parseJsonObjectLine(line) {
1576
- const trimmed = line.trim();
1577
- if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) {
1578
- return null;
1816
+ if (source.startsWith("codex")) {
1817
+ return "codex";
1579
1818
  }
1580
- try {
1581
- const parsed = JSON.parse(trimmed);
1582
- return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
1583
- } catch {
1584
- return null;
1819
+ if (source.startsWith("command-code") || source.startsWith("commandcode")) {
1820
+ return "command-code";
1585
1821
  }
1586
- }
1587
- function parseJsonValue(text) {
1588
- const trimmed = text.trim();
1589
- if (!(trimmed.startsWith("{") || trimmed.startsWith("["))) {
1590
- return null;
1822
+ if (source.startsWith("copilot-agent") || source.startsWith("github-copilot-agent")) {
1823
+ return "copilot-agent";
1591
1824
  }
1592
- try {
1593
- return JSON.parse(trimmed);
1594
- } catch {
1595
- return null;
1825
+ if (source.startsWith("copilot-cli") || source.startsWith("github-copilot-cli")) {
1826
+ return "copilot-cli";
1596
1827
  }
1597
- }
1598
-
1599
- // src/core/reduce-inspection-summary.ts
1600
- var LARGE_INSPECTION_MIN_CHARS = 4e3;
1601
- var LARGE_INSPECTION_MIN_LINES = 40;
1602
- var PACKAGE_LOCK_RE = /\bpackage-lock\.json\b/u;
1603
- function buildPackageLockSummary(value, noOmit = false) {
1604
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
1605
- return [];
1828
+ if (source.startsWith("crush")) {
1829
+ return "crush";
1606
1830
  }
1607
- const record = value;
1608
- const packages = typeof record.packages === "object" && record.packages !== null && !Array.isArray(record.packages) ? Object.keys(record.packages) : [];
1609
- const dependencies = typeof record.dependencies === "object" && record.dependencies !== null && !Array.isArray(record.dependencies) ? Object.keys(record.dependencies) : [];
1610
- const lines = [
1611
- "package-lock summary",
1612
- typeof record.name === "string" ? `name: ${record.name}` : null,
1613
- typeof record.version === "string" ? `version: ${record.version}` : null,
1614
- typeof record.lockfileVersion === "number" ? `lockfileVersion: ${record.lockfileVersion}` : null,
1615
- `packages: ${packages.length}`,
1616
- `dependencies: ${dependencies.length}`
1617
- ].filter((line) => line !== null);
1618
- const packageSamples = noOmit ? packages.filter(Boolean) : packages.filter(Boolean).slice(0, 12);
1619
- if (packageSamples.length > 0) {
1620
- lines.push(`sample packages: ${packageSamples.join(", ")}`);
1831
+ if (source.startsWith("cursor")) {
1832
+ return "cursor";
1621
1833
  }
1622
- return lines;
1623
- }
1624
- function buildLargeDocumentSummary(lines, rawText, noOmit = false) {
1625
- const headings = lines.map((line) => line.trim()).filter((line) => /^#{1,6}\s+\S/u.test(line)).slice(0, 24);
1626
- const excerpt = headTail(lines, 6, 6, noOmit);
1627
- const clippedHeadingCompactions = [];
1628
- const clippedHeadings = headings.map((line) => {
1629
- const clipped = clipMiddleWithHash(line, 180, noOmit);
1630
- if (clipped.compaction) {
1631
- clippedHeadingCompactions.push(clipped.compaction);
1632
- }
1633
- return `- ${clipped.text}`;
1634
- });
1635
- const clippedExcerptCompactions = [];
1636
- const excerptLines = excerpt.lines.map((line) => {
1637
- const clipped = clipMiddleWithHash(line, 180, noOmit);
1638
- if (clipped.compaction) {
1639
- clippedExcerptCompactions.push(clipped.compaction);
1640
- }
1641
- return clipped.text;
1642
- });
1643
- return {
1644
- lines: [
1645
- `large document summary: ${lines.length} lines, ${countTextChars(rawText)} chars`,
1646
- ...clippedHeadings.length > 0 ? ["headings:", ...clippedHeadings] : [],
1647
- "excerpt:",
1648
- ...excerptLines
1649
- ],
1650
- compaction: mergeCompactionMetadata(
1651
- createCompactionMetadata("inspection-large-document-summary"),
1652
- excerpt.compaction,
1653
- ...clippedHeadingCompactions,
1654
- ...clippedExcerptCompactions
1655
- )
1656
- };
1657
- }
1658
- function isLikelyDocumentLine(line) {
1659
- const trimmed = line.trim();
1660
- if (trimmed.length < 50) {
1661
- return false;
1834
+ if (source.startsWith("droid") || source.startsWith("factory-droid")) {
1835
+ return "droid";
1662
1836
  }
1663
- if (/^(?:import|export|const|let|var|function|class|interface|type|return|if|for|while|switch|case|try|catch)\b/u.test(trimmed)) {
1664
- return false;
1837
+ if (source.startsWith("gemini")) {
1838
+ return "gemini-cli";
1665
1839
  }
1666
- if (/^[{}()[\].,;:]/u.test(trimmed) || /[{};]$/u.test(trimmed)) {
1667
- return false;
1840
+ if (source.startsWith("grok-build") || source.startsWith("grokbuild") || source.startsWith("xai-grok-build")) {
1841
+ return "grok-build";
1668
1842
  }
1669
- return /\s/u.test(trimmed);
1670
- }
1671
- function isLikelyCodeLine(line) {
1672
- const trimmed = line.trim();
1673
- if (!trimmed) {
1674
- return false;
1843
+ if (source.startsWith("grok")) {
1844
+ return "grok-cli";
1675
1845
  }
1676
- return /^(?:import|export|const|let|var|function|class|interface|type|return|if|for|while|switch|case|try|catch|\}|\{|\)|\])/u.test(trimmed) || /[{};]$/u.test(trimmed);
1677
- }
1678
- function isLargeDocumentOutput(lines, rawChars) {
1679
- if (rawChars < LARGE_INSPECTION_MIN_CHARS) {
1680
- return false;
1846
+ if (source.startsWith("goose")) {
1847
+ return "goose";
1681
1848
  }
1682
- if (lines.length < LARGE_INSPECTION_MIN_LINES) {
1683
- return false;
1849
+ if (source.startsWith("antigravity") || source === "google-antigravity") {
1850
+ return "antigravity";
1684
1851
  }
1685
- const nonEmptyLines = lines.filter((line) => line.trim() !== "");
1686
- const headingCount = nonEmptyLines.filter((line) => /^#{1,6}\s+\S/u.test(line.trim())).length;
1687
- const hasFrontmatter = nonEmptyLines[0]?.trim() === "---" && nonEmptyLines.slice(1, 20).some((line) => line.trim() === "---");
1688
- if (headingCount >= 2 || hasFrontmatter && headingCount >= 1) {
1689
- return true;
1852
+ if (source.startsWith("augment") || source.startsWith("auggie")) {
1853
+ return "augment";
1690
1854
  }
1691
- const documentLines = nonEmptyLines.filter(isLikelyDocumentLine).length;
1692
- const codeLines = nonEmptyLines.filter(isLikelyCodeLine).length;
1693
- return documentLines >= 20 && documentLines / nonEmptyLines.length >= 0.5 && codeLines / nonEmptyLines.length < 0.25;
1855
+ if (source.startsWith("openclaw")) {
1856
+ return "openclaw";
1857
+ }
1858
+ if (source.startsWith("openhands")) {
1859
+ return "openhands";
1860
+ }
1861
+ if (source.startsWith("openinterpreter") || source.startsWith("open-interpreter")) {
1862
+ return "open-interpreter";
1863
+ }
1864
+ if (source.startsWith("openwebui") || source.startsWith("open-webui")) {
1865
+ return "openwebui";
1866
+ }
1867
+ if (source.startsWith("opencode") || source.startsWith("open-code")) {
1868
+ return "opencode";
1869
+ }
1870
+ if (source.startsWith("pi")) {
1871
+ return "pi";
1872
+ }
1873
+ if (source.startsWith("plandex")) {
1874
+ return "plandex";
1875
+ }
1876
+ if (source.startsWith("qoder")) {
1877
+ return "qoder";
1878
+ }
1879
+ if (source.startsWith("qwen")) {
1880
+ return "qwen-code";
1881
+ }
1882
+ if (source.startsWith("kimi")) {
1883
+ return "kimi";
1884
+ }
1885
+ if (source.startsWith("mux")) {
1886
+ return "mux";
1887
+ }
1888
+ if (source.startsWith("ruler")) {
1889
+ return "ruler";
1890
+ }
1891
+ if (source.startsWith("vscode-copilot") || source.startsWith("vs-code-copilot")) {
1892
+ return "vscode-copilot";
1893
+ }
1894
+ if (source === "direct" || source === "tokenjuice" || source === "wrap") {
1895
+ return DEFAULT_CLI_ARTIFACT_SOURCE;
1896
+ }
1897
+ return source;
1694
1898
  }
1695
- function buildInspectionSummary(input, rawText, noOmit = false) {
1696
- const command = input.command ?? "";
1697
- if (PACKAGE_LOCK_RE.test(command)) {
1698
- const lines2 = buildPackageLockSummary(parseJsonValue(rawText), noOmit);
1699
- return lines2.length > 0 ? { lines: lines2, matchedReducer: "generic/package-lock-summary", compaction: createCompactionMetadata("inspection-package-lock-summary") } : null;
1899
+ function resolveArtifactSource(input) {
1900
+ return normalizeArtifactSource(input.metadata?.source) ?? DEFAULT_CLI_ARTIFACT_SOURCE;
1901
+ }
1902
+
1903
+ // src/core/artifacts.ts
1904
+ var ARTIFACT_ID_PATTERN = /^tj_[0-9a-f-]{12}$/iu;
1905
+ var ARTIFACT_DIR_ENV = "TOKENJUICE_ARTIFACT_DIR";
1906
+ var STATS_ENABLED_ENV = "TOKENJUICE_STATS";
1907
+ var METADATA_SEGMENT_DIRECTORY = "metadata-v1";
1908
+ var METADATA_SEGMENT_PREFIX = "events";
1909
+ var OPTIONAL_METADATA_STORAGE_ERROR_CODES = /* @__PURE__ */ new Set([
1910
+ "EACCES",
1911
+ "EDQUOT",
1912
+ "EEXIST",
1913
+ "EFBIG",
1914
+ "EIO",
1915
+ "EISDIR",
1916
+ "ELOOP",
1917
+ "EMFILE",
1918
+ "ENAMETOOLONG",
1919
+ "ENFILE",
1920
+ "ENOENT",
1921
+ "ENOSPC",
1922
+ "ENOTDIR",
1923
+ "EPERM",
1924
+ "EROFS"
1925
+ ]);
1926
+ function extractCaptureTruncatedFlag(input) {
1927
+ const value = input.metadata?.tokenjuiceCaptureTruncated;
1928
+ return typeof value === "boolean" ? value : void 0;
1929
+ }
1930
+ function getDefaultArtifactDir() {
1931
+ const artifactDir = process.env[ARTIFACT_DIR_ENV];
1932
+ if (typeof artifactDir === "string" && artifactDir.trim()) {
1933
+ return artifactDir.trim();
1700
1934
  }
1701
- const rawChars = countTextChars(rawText);
1702
- const lines = trimEmptyEdges(normalizeLines(stripAnsi(rawText)));
1703
- if (!isFileContentInspectionCommand(input) || !isLargeDocumentOutput(lines, rawChars)) {
1704
- return null;
1935
+ return join2(homedir(), ".tokenjuice", "artifacts");
1936
+ }
1937
+ function resolveArtifactBaseDir(storeDir) {
1938
+ return storeDir ?? getDefaultArtifactDir();
1939
+ }
1940
+ function isValidArtifactId(id) {
1941
+ return ARTIFACT_ID_PATTERN.test(id);
1942
+ }
1943
+ function buildArtifactPaths(id, storeDir) {
1944
+ if (!isValidArtifactId(id)) {
1945
+ throw new Error(`invalid artifact id: ${id}`);
1705
1946
  }
1706
- const summary = buildLargeDocumentSummary(lines, rawText, noOmit);
1947
+ const base = resolveArtifactBaseDir(storeDir);
1707
1948
  return {
1708
- lines: summary.lines,
1709
- matchedReducer: "generic/large-document-summary",
1710
- compaction: summary.compaction
1949
+ id,
1950
+ storage: "file",
1951
+ path: join2(base, `${id}.txt`),
1952
+ metadataPath: join2(base, `${id}.json`)
1711
1953
  };
1712
1954
  }
1713
-
1714
- // src/core/rules.ts
1715
- import { readdir, readFile, realpath } from "node:fs/promises";
1716
- import { homedir } from "node:os";
1717
- import { isAbsolute, join, relative, resolve } from "node:path";
1718
- import { fileURLToPath } from "node:url";
1719
-
1720
- // src/rules/archive/tar.json
1721
- var tar_default = {
1722
- id: "archive/tar",
1723
- family: "archive-cli",
1724
- description: "Compact tar output while preserving archive paths and error lines.",
1725
- match: {
1726
- toolNames: ["exec"],
1727
- argv0: ["tar"]
1728
- },
1729
- transforms: {
1730
- stripAnsi: true,
1731
- dedupeAdjacent: true,
1732
- trimEmptyEdges: true
1733
- },
1734
- summarize: {
1735
- head: 10,
1736
- tail: 8
1737
- },
1738
- failure: {
1739
- preserveOnFailure: true,
1740
- head: 14,
1741
- tail: 14
1742
- },
1743
- counters: [
1955
+ function metadataSegmentDir(storeDir) {
1956
+ return join2(resolveArtifactBaseDir(storeDir), METADATA_SEGMENT_DIRECTORY);
1957
+ }
1958
+ var SAFE_COMMAND_FAMILY = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/u;
1959
+ function getTelemetryCommandFamily(input) {
1960
+ try {
1961
+ const family = getCommandName(getEffectiveCommandArgv(input));
1962
+ return family && SAFE_COMMAND_FAMILY.test(family) ? family : void 0;
1963
+ } catch {
1964
+ return void 0;
1965
+ }
1966
+ }
1967
+ function buildTelemetryMetadata(metadata, input) {
1968
+ const retainedMetadata = { ...metadata };
1969
+ delete retainedMetadata.command;
1970
+ const family = getTelemetryCommandFamily(input);
1971
+ return {
1972
+ ...retainedMetadata,
1973
+ ...family ? { commandFamily: family } : {}
1974
+ };
1975
+ }
1976
+ async function appendMetadataEvent(id, metadata, input, hasRaw, storeDir) {
1977
+ return await appendBoundedJsonl(
1978
+ metadataSegmentDir(storeDir),
1979
+ METADATA_SEGMENT_PREFIX,
1980
+ id,
1744
1981
  {
1745
- name: "error",
1746
- pattern: "error|failed|cannot",
1747
- flags: "i"
1982
+ id,
1983
+ hasRaw,
1984
+ metadata: buildTelemetryMetadata(metadata, input)
1748
1985
  }
1749
- ]
1750
- };
1751
-
1752
- // src/rules/archive/unzip.json
1753
- var unzip_default = {
1754
- id: "archive/unzip",
1755
- family: "archive-cli",
1756
- description: "Compact unzip output while preserving extracted paths and conflict lines.",
1757
- match: {
1758
- toolNames: ["exec"],
1759
- argv0: ["unzip"]
1760
- },
1761
- transforms: {
1762
- stripAnsi: true,
1763
- dedupeAdjacent: true,
1764
- trimEmptyEdges: true
1765
- },
1766
- summarize: {
1767
- head: 10,
1768
- tail: 8
1769
- },
1770
- failure: {
1771
- preserveOnFailure: true,
1772
- head: 14,
1773
- tail: 14
1774
- },
1775
- counters: [
1776
- {
1777
- name: "warning",
1778
- pattern: "inflating|extracting|replace|error",
1779
- flags: "i"
1986
+ );
1987
+ }
1988
+ function shouldRecordStats(env = process.env) {
1989
+ const value = env[STATS_ENABLED_ENV]?.trim().toLowerCase();
1990
+ return value !== "0" && value !== "false" && value !== "no" && value !== "off";
1991
+ }
1992
+ async function storeArtifact(input, storeDir) {
1993
+ const id = `tj_${randomUUID2().slice(0, 12)}`;
1994
+ const ref = buildArtifactPaths(id, storeDir);
1995
+ await mkdir2(resolveArtifactBaseDir(storeDir), { recursive: true, mode: 448 });
1996
+ const captureTruncated = extractCaptureTruncatedFlag(input.input);
1997
+ const artifact = {
1998
+ id,
1999
+ rawText: input.rawText,
2000
+ metadata: {
2001
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2002
+ source: resolveArtifactSource(input.input),
2003
+ classification: input.classification,
2004
+ rawChars: input.stats?.rawChars ?? countTextChars(stripAnsi(input.rawText)),
2005
+ ...input.input.toolName ? { toolName: input.input.toolName } : {},
2006
+ ...input.input.command ? { command: input.input.command } : {},
2007
+ ...typeof input.input.exitCode === "number" ? { exitCode: input.input.exitCode } : {},
2008
+ ...captureTruncated !== void 0 ? { captureTruncated } : {},
2009
+ ...input.stats ? { reducedChars: input.stats.reducedChars, ratio: input.stats.ratio } : {}
1780
2010
  }
1781
- ]
1782
- };
1783
-
1784
- // src/rules/archive/zip.json
1785
- var zip_default = {
1786
- id: "archive/zip",
1787
- family: "archive-cli",
1788
- description: "Compact zip output while preserving archived paths and warnings.",
1789
- match: {
1790
- toolNames: ["exec"],
1791
- argv0: ["zip"]
1792
- },
1793
- transforms: {
1794
- stripAnsi: true,
1795
- dedupeAdjacent: true,
1796
- trimEmptyEdges: true
1797
- },
1798
- summarize: {
1799
- head: 10,
1800
- tail: 8
1801
- },
1802
- failure: {
1803
- preserveOnFailure: true,
1804
- head: 14,
1805
- tail: 14
1806
- },
1807
- counters: [
1808
- {
1809
- name: "warning",
1810
- pattern: "adding|updating|warning|error",
1811
- flags: "i"
2011
+ };
2012
+ await Promise.all([
2013
+ writeFile2(ref.path, input.rawText, { encoding: "utf8", mode: 384 }),
2014
+ writeFile2(ref.metadataPath, JSON.stringify(artifact.metadata, null, 2), { encoding: "utf8", mode: 384 })
2015
+ ]);
2016
+ if (input.recordStats ?? shouldRecordStats()) {
2017
+ await appendMetadataEvent(id, artifact.metadata, input.input, true, storeDir).catch(() => void 0);
2018
+ }
2019
+ return ref;
2020
+ }
2021
+ async function storeArtifactMetadata(input, storeDir) {
2022
+ const id = `tj_${randomUUID2().slice(0, 12)}`;
2023
+ const captureTruncated = extractCaptureTruncatedFlag(input.input);
2024
+ const metadata = {
2025
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2026
+ source: resolveArtifactSource(input.input),
2027
+ classification: input.classification,
2028
+ rawChars: input.stats?.rawChars ?? countTextChars(stripAnsi(input.rawText)),
2029
+ ...input.input.toolName ? { toolName: input.input.toolName } : {},
2030
+ ...input.input.command ? { command: input.input.command } : {},
2031
+ ...typeof input.input.exitCode === "number" ? { exitCode: input.input.exitCode } : {},
2032
+ ...captureTruncated !== void 0 ? { captureTruncated } : {},
2033
+ ...input.stats ? { reducedChars: input.stats.reducedChars, ratio: input.stats.ratio } : {}
2034
+ };
2035
+ const telemetryMetadata = buildTelemetryMetadata(metadata, input.input);
2036
+ const metadataPath = await appendMetadataEvent(id, telemetryMetadata, input.input, false, storeDir);
2037
+ if (!metadataPath) {
2038
+ throw Object.assign(new Error("metadata segment is full or busy"), { code: "EFBIG" });
2039
+ }
2040
+ return {
2041
+ id,
2042
+ storage: "file",
2043
+ metadataPath,
2044
+ metadataFormat: "jsonl-segment",
2045
+ metadataRecordId: id,
2046
+ metadata: telemetryMetadata
2047
+ };
2048
+ }
2049
+ async function tryStoreArtifactMetadata(input, storeDir) {
2050
+ try {
2051
+ return await storeArtifactMetadata(input, storeDir);
2052
+ } catch (error) {
2053
+ const code = error.code;
2054
+ if (typeof code !== "string" || !OPTIONAL_METADATA_STORAGE_ERROR_CODES.has(code)) {
2055
+ throw error;
1812
2056
  }
1813
- ]
1814
- };
2057
+ return void 0;
2058
+ }
2059
+ }
1815
2060
 
1816
- // src/rules/build/cmake.json
1817
- var cmake_default = {
1818
- id: "build/cmake",
1819
- family: "build-native",
1820
- description: "Compact cmake output while preserving configure errors, build failures, and final status.",
1821
- match: {
1822
- toolNames: ["exec"],
1823
- argv0: ["cmake"]
1824
- },
1825
- transforms: {
1826
- stripAnsi: true,
1827
- dedupeAdjacent: true,
1828
- trimEmptyEdges: true
1829
- },
1830
- summarize: {
1831
- head: 12,
1832
- tail: 10
1833
- },
1834
- failure: {
1835
- preserveOnFailure: true,
1836
- head: 18,
1837
- tail: 18
1838
- },
1839
- counters: [
1840
- {
1841
- name: "error",
1842
- pattern: "CMake Error|error:|failed|FAILED",
1843
- flags: "i"
1844
- },
1845
- {
1846
- name: "warning",
1847
- pattern: "CMake Warning|warning:",
1848
- flags: "i"
2061
+ // src/core/reduce-utils.ts
2062
+ import { createHash as createHash2 } from "node:crypto";
2063
+ function compactWhitespace(text) {
2064
+ return text.replace(/\s+/gu, " ").trim();
2065
+ }
2066
+ function shortHash(text) {
2067
+ return createHash2("sha256").update(text).digest("hex").slice(0, 12);
2068
+ }
2069
+ function clipMiddleWithHashStrict(text, maxChars, noOmit = false) {
2070
+ if (countTextChars(text) <= maxChars) {
2071
+ return { text };
2072
+ }
2073
+ if (noOmit) {
2074
+ return {
2075
+ text,
2076
+ compaction: createPassthroughCompactionMetadata("no-omit-char-clip-passthrough")
2077
+ };
2078
+ }
2079
+ const omitted = countTextChars(text) - maxChars;
2080
+ const marker = `...[${omitted} chars omitted, sha256:${shortHash(text)}]...`;
2081
+ const markerChars = countTextChars(marker);
2082
+ if (maxChars <= markerChars) {
2083
+ return {
2084
+ text: sliceTextChars(marker, 0, maxChars),
2085
+ compaction: createCompactionMetadata("hashed-middle-clip")
2086
+ };
2087
+ }
2088
+ const bodyChars = maxChars - markerChars;
2089
+ const headChars = Math.ceil(bodyChars * 0.7);
2090
+ const tailChars = Math.max(0, bodyChars - headChars);
2091
+ return {
2092
+ text: `${sliceTextChars(text, 0, headChars)}${marker}${tailChars > 0 ? sliceTextChars(text, -tailChars) : ""}`,
2093
+ compaction: createCompactionMetadata("hashed-middle-clip")
2094
+ };
2095
+ }
2096
+ function minifyJsonLexically(rawText) {
2097
+ const text = rawText.trim();
2098
+ let output = "";
2099
+ let inString = false;
2100
+ let escaped = false;
2101
+ for (const char of text) {
2102
+ if (inString) {
2103
+ output += char;
2104
+ if (escaped) {
2105
+ escaped = false;
2106
+ } else if (char === "\\") {
2107
+ escaped = true;
2108
+ } else if (char === '"') {
2109
+ inString = false;
2110
+ }
2111
+ continue;
1849
2112
  }
1850
- ]
1851
- };
1852
-
1853
- // src/rules/build/dotnet.json
1854
- var dotnet_default = {
1855
- id: "build/dotnet",
1856
- family: "build-dotnet",
1857
- description: "Compact dotnet build and restore output while preserving diagnostics and final summaries.",
1858
- match: {
1859
- toolNames: ["exec"],
1860
- argv0: ["dotnet"],
1861
- argvIncludesAny: [["build"], ["restore"], ["publish"]]
1862
- },
1863
- transforms: {
1864
- stripAnsi: true,
1865
- dedupeAdjacent: true,
1866
- trimEmptyEdges: true
1867
- },
1868
- summarize: {
1869
- head: 12,
1870
- tail: 12
1871
- },
1872
- failure: {
1873
- preserveOnFailure: true,
1874
- head: 18,
1875
- tail: 18
1876
- },
1877
- counters: [
1878
- {
1879
- name: "error",
1880
- pattern: "error [A-Z]+\\d+|Build FAILED|failed",
1881
- flags: "i"
1882
- },
1883
- {
1884
- name: "warning",
1885
- pattern: "warning [A-Z]+\\d+|warning",
1886
- flags: "i"
2113
+ if (char === '"') {
2114
+ inString = true;
2115
+ output += char;
2116
+ continue;
1887
2117
  }
1888
- ]
1889
- };
1890
-
1891
- // src/rules/build/esbuild.json
1892
- var esbuild_default = {
1893
- id: "build/esbuild",
1894
- family: "build-bundler",
1895
- description: "Compact esbuild and tsdown-like output while preserving actual errors.",
1896
- match: {
1897
- toolNames: ["exec"],
1898
- commandIncludes: ["esbuild"]
1899
- },
1900
- transforms: {
1901
- stripAnsi: true,
1902
- dedupeAdjacent: true,
1903
- trimEmptyEdges: true
1904
- },
1905
- summarize: {
1906
- head: 12,
1907
- tail: 8
1908
- },
1909
- failure: {
1910
- preserveOnFailure: true,
1911
- head: 16,
1912
- tail: 14
1913
- },
1914
- counters: [
1915
- {
1916
- name: "error",
1917
- pattern: "error",
1918
- flags: "i"
1919
- },
1920
- {
1921
- name: "warning",
1922
- pattern: "warning",
1923
- flags: "i"
2118
+ if (/\s/u.test(char)) {
2119
+ continue;
1924
2120
  }
1925
- ]
1926
- };
2121
+ output += char;
2122
+ }
2123
+ return output;
2124
+ }
2125
+ function clipMiddleWithHash(text, maxChars, noOmit = false) {
2126
+ if (countTextChars(text) <= maxChars) {
2127
+ return { text };
2128
+ }
2129
+ if (noOmit) {
2130
+ return {
2131
+ text,
2132
+ compaction: createPassthroughCompactionMetadata("no-omit-char-clip-passthrough")
2133
+ };
2134
+ }
2135
+ const omitted = countTextChars(text) - maxChars;
2136
+ const headChars = Math.max(20, Math.floor(maxChars * 0.55));
2137
+ const tailChars = Math.max(20, maxChars - headChars);
2138
+ return {
2139
+ text: `${sliceTextChars(text, 0, headChars)} ...[${omitted} chars omitted, sha256:${shortHash(text)}]... ${sliceTextChars(text, -tailChars)}`,
2140
+ compaction: createCompactionMetadata("hashed-middle-clip")
2141
+ };
2142
+ }
2143
+ function compactWholeJsonText(rawText, maxChars, noOmit = false) {
2144
+ return parseJsonValue(rawText) === null ? null : clipMiddleWithHashStrict(minifyJsonLexically(rawText), maxChars, noOmit);
2145
+ }
2146
+ function parseJsonObjectLine(line) {
2147
+ const trimmed = line.trim();
2148
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) {
2149
+ return null;
2150
+ }
2151
+ try {
2152
+ const parsed = JSON.parse(trimmed);
2153
+ return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
2154
+ } catch {
2155
+ return null;
2156
+ }
2157
+ }
2158
+ function parseJsonValue(text) {
2159
+ const trimmed = text.trim();
2160
+ if (!(trimmed.startsWith("{") || trimmed.startsWith("["))) {
2161
+ return null;
2162
+ }
2163
+ try {
2164
+ return JSON.parse(trimmed);
2165
+ } catch {
2166
+ return null;
2167
+ }
2168
+ }
1927
2169
 
1928
- // src/rules/build/go-build.json
1929
- var go_build_default = {
1930
- id: "build/go-build",
1931
- family: "build-go",
1932
- description: "Compact go build output while preserving compiler diagnostics and package failures.",
2170
+ // src/core/reduce-inspection-summary.ts
2171
+ var LARGE_INSPECTION_MIN_CHARS = 4e3;
2172
+ var LARGE_INSPECTION_MIN_LINES = 40;
2173
+ var PACKAGE_LOCK_RE = /\bpackage-lock\.json\b/u;
2174
+ function buildPackageLockSummary(value, noOmit = false) {
2175
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
2176
+ return [];
2177
+ }
2178
+ const record = value;
2179
+ const packages = typeof record.packages === "object" && record.packages !== null && !Array.isArray(record.packages) ? Object.keys(record.packages) : [];
2180
+ const dependencies = typeof record.dependencies === "object" && record.dependencies !== null && !Array.isArray(record.dependencies) ? Object.keys(record.dependencies) : [];
2181
+ const lines = [
2182
+ "package-lock summary",
2183
+ typeof record.name === "string" ? `name: ${record.name}` : null,
2184
+ typeof record.version === "string" ? `version: ${record.version}` : null,
2185
+ typeof record.lockfileVersion === "number" ? `lockfileVersion: ${record.lockfileVersion}` : null,
2186
+ `packages: ${packages.length}`,
2187
+ `dependencies: ${dependencies.length}`
2188
+ ].filter((line) => line !== null);
2189
+ const packageSamples = noOmit ? packages.filter(Boolean) : packages.filter(Boolean).slice(0, 12);
2190
+ if (packageSamples.length > 0) {
2191
+ lines.push(`sample packages: ${packageSamples.join(", ")}`);
2192
+ }
2193
+ return lines;
2194
+ }
2195
+ function buildLargeDocumentSummary(lines, rawText, noOmit = false) {
2196
+ const headings = lines.map((line) => line.trim()).filter((line) => /^#{1,6}\s+\S/u.test(line)).slice(0, 24);
2197
+ const excerpt = headTail(lines, 6, 6, noOmit);
2198
+ const clippedHeadingCompactions = [];
2199
+ const clippedHeadings = headings.map((line) => {
2200
+ const clipped = clipMiddleWithHash(line, 180, noOmit);
2201
+ if (clipped.compaction) {
2202
+ clippedHeadingCompactions.push(clipped.compaction);
2203
+ }
2204
+ return `- ${clipped.text}`;
2205
+ });
2206
+ const clippedExcerptCompactions = [];
2207
+ const excerptLines = excerpt.lines.map((line) => {
2208
+ const clipped = clipMiddleWithHash(line, 180, noOmit);
2209
+ if (clipped.compaction) {
2210
+ clippedExcerptCompactions.push(clipped.compaction);
2211
+ }
2212
+ return clipped.text;
2213
+ });
2214
+ return {
2215
+ lines: [
2216
+ `large document summary: ${lines.length} lines, ${countTextChars(rawText)} chars`,
2217
+ ...clippedHeadings.length > 0 ? ["headings:", ...clippedHeadings] : [],
2218
+ "excerpt:",
2219
+ ...excerptLines
2220
+ ],
2221
+ compaction: mergeCompactionMetadata(
2222
+ createCompactionMetadata("inspection-large-document-summary"),
2223
+ excerpt.compaction,
2224
+ ...clippedHeadingCompactions,
2225
+ ...clippedExcerptCompactions
2226
+ )
2227
+ };
2228
+ }
2229
+ function isLikelyDocumentLine(line) {
2230
+ const trimmed = line.trim();
2231
+ if (trimmed.length < 50) {
2232
+ return false;
2233
+ }
2234
+ if (/^(?:import|export|const|let|var|function|class|interface|type|return|if|for|while|switch|case|try|catch)\b/u.test(trimmed)) {
2235
+ return false;
2236
+ }
2237
+ if (/^[{}()[\].,;:]/u.test(trimmed) || /[{};]$/u.test(trimmed)) {
2238
+ return false;
2239
+ }
2240
+ return /\s/u.test(trimmed);
2241
+ }
2242
+ function isLikelyCodeLine(line) {
2243
+ const trimmed = line.trim();
2244
+ if (!trimmed) {
2245
+ return false;
2246
+ }
2247
+ return /^(?:import|export|const|let|var|function|class|interface|type|return|if|for|while|switch|case|try|catch|\}|\{|\)|\])/u.test(trimmed) || /[{};]$/u.test(trimmed);
2248
+ }
2249
+ function isLargeDocumentOutput(lines, rawChars) {
2250
+ if (rawChars < LARGE_INSPECTION_MIN_CHARS) {
2251
+ return false;
2252
+ }
2253
+ if (lines.length < LARGE_INSPECTION_MIN_LINES) {
2254
+ return false;
2255
+ }
2256
+ const nonEmptyLines = lines.filter((line) => line.trim() !== "");
2257
+ const headingCount = nonEmptyLines.filter((line) => /^#{1,6}\s+\S/u.test(line.trim())).length;
2258
+ const hasFrontmatter = nonEmptyLines[0]?.trim() === "---" && nonEmptyLines.slice(1, 20).some((line) => line.trim() === "---");
2259
+ if (headingCount >= 2 || hasFrontmatter && headingCount >= 1) {
2260
+ return true;
2261
+ }
2262
+ const documentLines = nonEmptyLines.filter(isLikelyDocumentLine).length;
2263
+ const codeLines = nonEmptyLines.filter(isLikelyCodeLine).length;
2264
+ return documentLines >= 20 && documentLines / nonEmptyLines.length >= 0.5 && codeLines / nonEmptyLines.length < 0.25;
2265
+ }
2266
+ function buildInspectionSummary(input, rawText, noOmit = false) {
2267
+ const command = input.command ?? "";
2268
+ if (PACKAGE_LOCK_RE.test(command)) {
2269
+ const lines2 = buildPackageLockSummary(parseJsonValue(rawText), noOmit);
2270
+ return lines2.length > 0 ? { lines: lines2, matchedReducer: "generic/package-lock-summary", compaction: createCompactionMetadata("inspection-package-lock-summary") } : null;
2271
+ }
2272
+ const rawChars = countTextChars(rawText);
2273
+ const lines = trimEmptyEdges(normalizeLines(stripAnsi(rawText)));
2274
+ if (!isFileContentInspectionCommand(input) || !isLargeDocumentOutput(lines, rawChars)) {
2275
+ return null;
2276
+ }
2277
+ const summary = buildLargeDocumentSummary(lines, rawText, noOmit);
2278
+ return {
2279
+ lines: summary.lines,
2280
+ matchedReducer: "generic/large-document-summary",
2281
+ compaction: summary.compaction
2282
+ };
2283
+ }
2284
+
2285
+ // src/core/rules.ts
2286
+ import { readdir as readdir2, readFile as readFile3, realpath } from "node:fs/promises";
2287
+ import { homedir as homedir2 } from "node:os";
2288
+ import { isAbsolute, join as join3, relative, resolve } from "node:path";
2289
+ import { fileURLToPath } from "node:url";
2290
+
2291
+ // src/rules/archive/tar.json
2292
+ var tar_default = {
2293
+ id: "archive/tar",
2294
+ family: "archive-cli",
2295
+ description: "Compact tar output while preserving archive paths and error lines.",
1933
2296
  match: {
1934
2297
  toolNames: ["exec"],
1935
- argv0: ["go"],
1936
- argvIncludes: [["build"]]
2298
+ argv0: ["tar"]
1937
2299
  },
1938
2300
  transforms: {
1939
2301
  stripAnsi: true,
@@ -1942,30 +2304,30 @@ var go_build_default = {
1942
2304
  },
1943
2305
  summarize: {
1944
2306
  head: 10,
1945
- tail: 10
2307
+ tail: 8
1946
2308
  },
1947
2309
  failure: {
1948
2310
  preserveOnFailure: true,
1949
- head: 16,
1950
- tail: 16
2311
+ head: 14,
2312
+ tail: 14
1951
2313
  },
1952
2314
  counters: [
1953
2315
  {
1954
2316
  name: "error",
1955
- pattern: "^# |\\.go:\\d+:\\d+:|cannot|undefined|failed",
1956
- flags: "im"
2317
+ pattern: "error|failed|cannot",
2318
+ flags: "i"
1957
2319
  }
1958
2320
  ]
1959
2321
  };
1960
2322
 
1961
- // src/rules/build/gradle.json
1962
- var gradle_default = {
1963
- id: "build/gradle",
1964
- family: "build-jvm",
1965
- description: "Compact Gradle output while preserving task failures, test failures, and build status.",
2323
+ // src/rules/archive/unzip.json
2324
+ var unzip_default = {
2325
+ id: "archive/unzip",
2326
+ family: "archive-cli",
2327
+ description: "Compact unzip output while preserving extracted paths and conflict lines.",
1966
2328
  match: {
1967
2329
  toolNames: ["exec"],
1968
- argv0: ["gradle", "gradlew", "./gradlew"]
2330
+ argv0: ["unzip"]
1969
2331
  },
1970
2332
  transforms: {
1971
2333
  stripAnsi: true,
@@ -1973,36 +2335,31 @@ var gradle_default = {
1973
2335
  trimEmptyEdges: true
1974
2336
  },
1975
2337
  summarize: {
1976
- head: 12,
1977
- tail: 12
2338
+ head: 10,
2339
+ tail: 8
1978
2340
  },
1979
2341
  failure: {
1980
2342
  preserveOnFailure: true,
1981
- head: 18,
1982
- tail: 18
2343
+ head: 14,
2344
+ tail: 14
1983
2345
  },
1984
2346
  counters: [
1985
- {
1986
- name: "failed task",
1987
- pattern: "FAILURE: Build failed|Execution failed for task|FAILED",
1988
- flags: "i"
1989
- },
1990
2347
  {
1991
2348
  name: "warning",
1992
- pattern: "Deprecated Gradle features|warning",
2349
+ pattern: "inflating|extracting|replace|error",
1993
2350
  flags: "i"
1994
2351
  }
1995
2352
  ]
1996
2353
  };
1997
2354
 
1998
- // src/rules/build/maven.json
1999
- var maven_default = {
2000
- id: "build/maven",
2001
- family: "build-jvm",
2002
- description: "Compact Maven output while preserving errors, failed goals, and reactor summaries.",
2355
+ // src/rules/archive/zip.json
2356
+ var zip_default = {
2357
+ id: "archive/zip",
2358
+ family: "archive-cli",
2359
+ description: "Compact zip output while preserving archived paths and warnings.",
2003
2360
  match: {
2004
2361
  toolNames: ["exec"],
2005
- argv0: ["mvn", "mvnw", "./mvnw"]
2362
+ argv0: ["zip"]
2006
2363
  },
2007
2364
  transforms: {
2008
2365
  stripAnsi: true,
@@ -2010,13 +2367,227 @@ var maven_default = {
2010
2367
  trimEmptyEdges: true
2011
2368
  },
2012
2369
  summarize: {
2013
- head: 12,
2014
- tail: 12
2370
+ head: 10,
2371
+ tail: 8
2015
2372
  },
2016
2373
  failure: {
2017
2374
  preserveOnFailure: true,
2018
- head: 18,
2019
- tail: 18
2375
+ head: 14,
2376
+ tail: 14
2377
+ },
2378
+ counters: [
2379
+ {
2380
+ name: "warning",
2381
+ pattern: "adding|updating|warning|error",
2382
+ flags: "i"
2383
+ }
2384
+ ]
2385
+ };
2386
+
2387
+ // src/rules/build/cmake.json
2388
+ var cmake_default = {
2389
+ id: "build/cmake",
2390
+ family: "build-native",
2391
+ description: "Compact cmake output while preserving configure errors, build failures, and final status.",
2392
+ match: {
2393
+ toolNames: ["exec"],
2394
+ argv0: ["cmake"]
2395
+ },
2396
+ transforms: {
2397
+ stripAnsi: true,
2398
+ dedupeAdjacent: true,
2399
+ trimEmptyEdges: true
2400
+ },
2401
+ summarize: {
2402
+ head: 12,
2403
+ tail: 10
2404
+ },
2405
+ failure: {
2406
+ preserveOnFailure: true,
2407
+ head: 18,
2408
+ tail: 18
2409
+ },
2410
+ counters: [
2411
+ {
2412
+ name: "error",
2413
+ pattern: "CMake Error|error:|failed|FAILED",
2414
+ flags: "i"
2415
+ },
2416
+ {
2417
+ name: "warning",
2418
+ pattern: "CMake Warning|warning:",
2419
+ flags: "i"
2420
+ }
2421
+ ]
2422
+ };
2423
+
2424
+ // src/rules/build/dotnet.json
2425
+ var dotnet_default = {
2426
+ id: "build/dotnet",
2427
+ family: "build-dotnet",
2428
+ description: "Compact dotnet build and restore output while preserving diagnostics and final summaries.",
2429
+ match: {
2430
+ toolNames: ["exec"],
2431
+ argv0: ["dotnet"],
2432
+ argvIncludesAny: [["build"], ["restore"], ["publish"]]
2433
+ },
2434
+ transforms: {
2435
+ stripAnsi: true,
2436
+ dedupeAdjacent: true,
2437
+ trimEmptyEdges: true
2438
+ },
2439
+ summarize: {
2440
+ head: 12,
2441
+ tail: 12
2442
+ },
2443
+ failure: {
2444
+ preserveOnFailure: true,
2445
+ head: 18,
2446
+ tail: 18
2447
+ },
2448
+ counters: [
2449
+ {
2450
+ name: "error",
2451
+ pattern: "error [A-Z]+\\d+|Build FAILED|failed",
2452
+ flags: "i"
2453
+ },
2454
+ {
2455
+ name: "warning",
2456
+ pattern: "warning [A-Z]+\\d+|warning",
2457
+ flags: "i"
2458
+ }
2459
+ ]
2460
+ };
2461
+
2462
+ // src/rules/build/esbuild.json
2463
+ var esbuild_default = {
2464
+ id: "build/esbuild",
2465
+ family: "build-bundler",
2466
+ description: "Compact esbuild and tsdown-like output while preserving actual errors.",
2467
+ match: {
2468
+ toolNames: ["exec"],
2469
+ commandIncludes: ["esbuild"]
2470
+ },
2471
+ transforms: {
2472
+ stripAnsi: true,
2473
+ dedupeAdjacent: true,
2474
+ trimEmptyEdges: true
2475
+ },
2476
+ summarize: {
2477
+ head: 12,
2478
+ tail: 8
2479
+ },
2480
+ failure: {
2481
+ preserveOnFailure: true,
2482
+ head: 16,
2483
+ tail: 14
2484
+ },
2485
+ counters: [
2486
+ {
2487
+ name: "error",
2488
+ pattern: "error",
2489
+ flags: "i"
2490
+ },
2491
+ {
2492
+ name: "warning",
2493
+ pattern: "warning",
2494
+ flags: "i"
2495
+ }
2496
+ ]
2497
+ };
2498
+
2499
+ // src/rules/build/go-build.json
2500
+ var go_build_default = {
2501
+ id: "build/go-build",
2502
+ family: "build-go",
2503
+ description: "Compact go build output while preserving compiler diagnostics and package failures.",
2504
+ match: {
2505
+ toolNames: ["exec"],
2506
+ argv0: ["go"],
2507
+ argvIncludes: [["build"]]
2508
+ },
2509
+ transforms: {
2510
+ stripAnsi: true,
2511
+ dedupeAdjacent: true,
2512
+ trimEmptyEdges: true
2513
+ },
2514
+ summarize: {
2515
+ head: 10,
2516
+ tail: 10
2517
+ },
2518
+ failure: {
2519
+ preserveOnFailure: true,
2520
+ head: 16,
2521
+ tail: 16
2522
+ },
2523
+ counters: [
2524
+ {
2525
+ name: "error",
2526
+ pattern: "^# |\\.go:\\d+:\\d+:|cannot|undefined|failed",
2527
+ flags: "im"
2528
+ }
2529
+ ]
2530
+ };
2531
+
2532
+ // src/rules/build/gradle.json
2533
+ var gradle_default = {
2534
+ id: "build/gradle",
2535
+ family: "build-jvm",
2536
+ description: "Compact Gradle output while preserving task failures, test failures, and build status.",
2537
+ match: {
2538
+ toolNames: ["exec"],
2539
+ argv0: ["gradle", "gradlew", "./gradlew"]
2540
+ },
2541
+ transforms: {
2542
+ stripAnsi: true,
2543
+ dedupeAdjacent: true,
2544
+ trimEmptyEdges: true
2545
+ },
2546
+ summarize: {
2547
+ head: 12,
2548
+ tail: 12
2549
+ },
2550
+ failure: {
2551
+ preserveOnFailure: true,
2552
+ head: 18,
2553
+ tail: 18
2554
+ },
2555
+ counters: [
2556
+ {
2557
+ name: "failed task",
2558
+ pattern: "FAILURE: Build failed|Execution failed for task|FAILED",
2559
+ flags: "i"
2560
+ },
2561
+ {
2562
+ name: "warning",
2563
+ pattern: "Deprecated Gradle features|warning",
2564
+ flags: "i"
2565
+ }
2566
+ ]
2567
+ };
2568
+
2569
+ // src/rules/build/maven.json
2570
+ var maven_default = {
2571
+ id: "build/maven",
2572
+ family: "build-jvm",
2573
+ description: "Compact Maven output while preserving errors, failed goals, and reactor summaries.",
2574
+ match: {
2575
+ toolNames: ["exec"],
2576
+ argv0: ["mvn", "mvnw", "./mvnw"]
2577
+ },
2578
+ transforms: {
2579
+ stripAnsi: true,
2580
+ dedupeAdjacent: true,
2581
+ trimEmptyEdges: true
2582
+ },
2583
+ summarize: {
2584
+ head: 12,
2585
+ tail: 12
2586
+ },
2587
+ failure: {
2588
+ preserveOnFailure: true,
2589
+ head: 18,
2590
+ tail: 18
2020
2591
  },
2021
2592
  counters: [
2022
2593
  {
@@ -7028,820 +7599,540 @@ var BUNDLED_BUILTIN_RULES = [
7028
7599
  playwright_default,
7029
7600
  // rules/tests/playwright.json
7030
7601
  pnpm_test_default,
7031
- // rules/tests/pnpm-test.json
7032
- pytest_default,
7033
- // rules/tests/pytest.json
7034
- rspec_default,
7035
- // rules/tests/rspec.json
7036
- swift_test_default,
7037
- // rules/tests/swift-test.json
7038
- vitest_default,
7039
- // rules/tests/vitest.json
7040
- yarn_test_default,
7041
- // rules/tests/yarn-test.json
7042
- wc_default,
7043
- // rules/text/wc.json
7044
- rsync_default,
7045
- // rules/transfer/rsync.json
7046
- scp_default
7047
- // rules/transfer/scp.json
7048
- ];
7049
-
7050
- // src/core/validate-rules.ts
7051
- function hasNulByte(value) {
7052
- return value.includes("\0");
7053
- }
7054
- function validateSafeString(value, path, errors, { allowEmpty = false } = {}) {
7055
- if (typeof value !== "string") {
7056
- errors.push(`${path} must be a string`);
7057
- return;
7058
- }
7059
- if (!allowEmpty && value.length === 0) {
7060
- errors.push(`${path} must be a non-empty string`);
7061
- }
7062
- if (hasNulByte(value)) {
7063
- errors.push(`${path} must not contain NUL bytes`);
7064
- }
7065
- }
7066
- function validatePositiveInteger(value, path, errors) {
7067
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
7068
- errors.push(`${path} must be a non-negative integer`);
7069
- }
7070
- }
7071
- function isRecord(value) {
7072
- return typeof value === "object" && value !== null && !Array.isArray(value);
7073
- }
7074
- function isStringArray(value) {
7075
- return Array.isArray(value) && value.every((entry) => typeof entry === "string");
7076
- }
7077
- function validateMatch(value, path) {
7078
- if (!isRecord(value)) {
7079
- return [`${path} must be an object`];
7080
- }
7081
- const errors = [];
7082
- if ("toolNames" in value && !isStringArray(value.toolNames)) {
7083
- errors.push(`${path}.toolNames must be an array of strings`);
7084
- }
7085
- if ("argv0" in value && !isStringArray(value.argv0)) {
7086
- errors.push(`${path}.argv0 must be an array of strings`);
7087
- }
7088
- if ("gitSubcommands" in value && !isStringArray(value.gitSubcommands)) {
7089
- errors.push(`${path}.gitSubcommands must be an array of strings`);
7090
- }
7091
- if ("commandIncludes" in value && !isStringArray(value.commandIncludes)) {
7092
- errors.push(`${path}.commandIncludes must be an array of strings`);
7093
- }
7094
- if ("commandIncludesAny" in value && !isStringArray(value.commandIncludesAny)) {
7095
- errors.push(`${path}.commandIncludesAny must be an array of strings`);
7096
- }
7097
- if ("argvIncludes" in value) {
7098
- if (!Array.isArray(value.argvIncludes) || !value.argvIncludes.every(isStringArray)) {
7099
- errors.push(`${path}.argvIncludes must be an array of string arrays`);
7100
- }
7101
- }
7102
- if ("argvIncludesAny" in value) {
7103
- if (!Array.isArray(value.argvIncludesAny) || !value.argvIncludesAny.every(isStringArray)) {
7104
- errors.push(`${path}.argvIncludesAny must be an array of string arrays`);
7105
- }
7106
- }
7107
- return errors;
7108
- }
7109
- function validateCounter(value, path) {
7110
- if (!isRecord(value)) {
7111
- return [`${path} must be an object`];
7112
- }
7113
- const errors = [];
7114
- validateSafeString(value.name, `${path}.name`, errors);
7115
- validateSafeString(value.pattern, `${path}.pattern`, errors);
7116
- if ("flags" in value) {
7117
- validateSafeString(value.flags, `${path}.flags`, errors, { allowEmpty: true });
7118
- }
7119
- return errors;
7120
- }
7121
- function validateOutputMatch(value, path) {
7122
- if (!isRecord(value)) {
7123
- return [`${path} must be an object`];
7124
- }
7125
- const errors = [];
7126
- validateSafeString(value.pattern, `${path}.pattern`, errors);
7127
- validateSafeString(value.message, `${path}.message`, errors);
7128
- if ("flags" in value) {
7129
- validateSafeString(value.flags, `${path}.flags`, errors, { allowEmpty: true });
7130
- }
7131
- return errors;
7132
- }
7133
- function validateOptionalStringArrayObject(value, path, keys) {
7134
- if (!isRecord(value)) {
7135
- return [`${path} must be an object`];
7136
- }
7137
- const errors = [];
7138
- for (const key of keys) {
7139
- if (key in value && !isStringArray(value[key])) {
7140
- errors.push(`${path}.${key} must be an array of strings`);
7141
- }
7142
- }
7143
- return errors;
7144
- }
7145
- function validateOptionalNumberObject(value, path, keys) {
7146
- if (!isRecord(value)) {
7147
- return [`${path} must be an object`];
7148
- }
7149
- const errors = [];
7150
- for (const key of keys) {
7151
- if (key in value) {
7152
- validatePositiveInteger(value[key], `${path}.${key}`, errors);
7153
- }
7154
- }
7155
- return errors;
7156
- }
7157
- function validateOptionalBooleanObject(value, path, keys) {
7158
- if (!isRecord(value)) {
7159
- return [`${path} must be an object`];
7160
- }
7161
- const errors = [];
7162
- for (const key of keys) {
7163
- if (key in value && typeof value[key] !== "boolean") {
7164
- errors.push(`${path}.${key} must be a boolean`);
7165
- }
7166
- }
7167
- return errors;
7168
- }
7169
- function validateRule(raw) {
7170
- if (!isRecord(raw)) {
7171
- return {
7172
- ok: false,
7173
- errors: ["rule must be an object"]
7174
- };
7175
- }
7176
- const errors = [];
7177
- validateSafeString(raw.id, "id", errors);
7178
- validateSafeString(raw.family, "family", errors);
7179
- if ("description" in raw) {
7180
- validateSafeString(raw.description, "description", errors, { allowEmpty: true });
7181
- }
7182
- if ("onEmpty" in raw) {
7183
- validateSafeString(raw.onEmpty, "onEmpty", errors);
7184
- }
7185
- if ("counterSource" in raw && raw.counterSource !== "postKeep" && raw.counterSource !== "preKeep") {
7186
- errors.push("counterSource must be one of: postKeep, preKeep");
7187
- }
7188
- if ("priority" in raw && (typeof raw.priority !== "number" || !Number.isFinite(raw.priority))) {
7189
- errors.push("priority must be a finite number");
7190
- }
7191
- if (!("match" in raw)) {
7192
- errors.push("match is required");
7193
- } else {
7194
- errors.push(...validateMatch(raw.match, "match"));
7195
- }
7196
- if ("filters" in raw) {
7197
- errors.push(...validateOptionalStringArrayObject(raw.filters, "filters", ["skipPatterns", "keepPatterns"]));
7198
- }
7199
- if ("transforms" in raw) {
7200
- errors.push(...validateOptionalBooleanObject(raw.transforms, "transforms", [
7201
- "stripAnsi",
7202
- "prettyPrintJson",
7203
- "dedupeAdjacent",
7204
- "trimEmptyEdges"
7205
- ]));
7206
- }
7207
- if ("summarize" in raw) {
7208
- errors.push(...validateOptionalNumberObject(raw.summarize, "summarize", ["head", "tail"]));
7209
- }
7210
- if ("failure" in raw) {
7211
- errors.push(...validateOptionalBooleanObject(raw.failure, "failure", ["preserveOnFailure"]));
7212
- errors.push(...validateOptionalNumberObject(raw.failure, "failure", ["head", "tail"]));
7213
- }
7214
- if ("counters" in raw) {
7215
- if (!Array.isArray(raw.counters)) {
7216
- errors.push("counters must be an array");
7217
- } else {
7218
- raw.counters.forEach((counter, index) => {
7219
- errors.push(...validateCounter(counter, `counters[${index}]`));
7220
- });
7221
- }
7222
- }
7223
- if ("matchOutput" in raw) {
7224
- if (!Array.isArray(raw.matchOutput)) {
7225
- errors.push("matchOutput must be an array");
7226
- } else {
7227
- raw.matchOutput.forEach((entry, index) => {
7228
- errors.push(...validateOutputMatch(entry, `matchOutput[${index}]`));
7229
- });
7230
- }
7231
- }
7232
- if (errors.length > 0) {
7233
- return {
7234
- ok: false,
7235
- errors
7236
- };
7237
- }
7238
- return { ok: true };
7239
- }
7240
- function assertValidRule(raw) {
7241
- const validation = validateRule(raw);
7242
- if (!validation.ok) {
7243
- throw new Error(`invalid rule:
7244
- - ${validation.errors.join("\n- ")}`);
7245
- }
7246
- }
7247
-
7248
- // src/core/rules.ts
7249
- var ruleCache = /* @__PURE__ */ new Map();
7250
- function builtinRulesRoot() {
7251
- return resolve(fileURLToPath(new URL("../rules", import.meta.url)));
7252
- }
7253
- function mergeRegexFlags(flags) {
7254
- return [...new Set(`u${flags ?? ""}`.split(""))].join("");
7255
- }
7256
- function compileRule(descriptor) {
7257
- return {
7258
- rule: descriptor.rule,
7259
- source: descriptor.source,
7260
- path: descriptor.path,
7261
- compiled: {
7262
- skipPatterns: (descriptor.rule.filters?.skipPatterns ?? []).map((pattern) => new RegExp(pattern, "u")),
7263
- keepPatterns: (descriptor.rule.filters?.keepPatterns ?? []).map((pattern) => new RegExp(pattern, "u")),
7264
- counters: (descriptor.rule.counters ?? []).map((counter) => ({
7265
- name: counter.name,
7266
- pattern: new RegExp(counter.pattern, mergeRegexFlags(counter.flags))
7267
- })),
7268
- outputMatches: (descriptor.rule.matchOutput ?? []).map((entry) => ({
7269
- pattern: new RegExp(entry.pattern, mergeRegexFlags(entry.flags)),
7270
- message: entry.message
7271
- }))
7272
- }
7273
- };
7274
- }
7275
- async function listRuleFiles(root) {
7276
- const resolvedRoot = await realpath(root).catch(() => null);
7277
- if (!resolvedRoot) {
7278
- return [];
7279
- }
7280
- const rootRealPath = resolvedRoot;
7281
- async function walk(currentDir) {
7282
- const entries = (await readdir(currentDir, { withFileTypes: true })).sort((left, right) => left.name.localeCompare(right.name));
7283
- const files = await Promise.all(
7284
- entries.map(async (entry) => {
7285
- const fullPath = join(currentDir, entry.name);
7286
- if (entry.isSymbolicLink()) {
7287
- return [];
7288
- }
7289
- if (entry.isDirectory()) {
7290
- return await walk(fullPath);
7291
- }
7292
- if (!entry.isFile() || !entry.name.endsWith(".json") || entry.name.endsWith(".schema.json") || entry.name.endsWith(".fixture.json")) {
7293
- return [];
7294
- }
7295
- const realFilePath = await realpath(fullPath).catch(() => null);
7296
- if (!realFilePath) {
7297
- return [];
7298
- }
7299
- const relativePath = relative(rootRealPath, realFilePath);
7300
- if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
7301
- return [];
7302
- }
7303
- return [realFilePath];
7304
- })
7305
- );
7306
- return files.flat();
7307
- }
7308
- try {
7309
- return await walk(root);
7310
- } catch {
7311
- return [];
7312
- }
7313
- }
7314
- function userRulesRoot(customDir) {
7315
- return customDir ?? join(homedir(), ".config", "tokenjuice", "rules");
7316
- }
7317
- function projectRulesRoot(cwd, customDir) {
7318
- return customDir ?? join(cwd ?? process.cwd(), ".tokenjuice", "rules");
7319
- }
7320
- function sortRules(rules) {
7321
- return [...rules].sort((left, right) => {
7322
- if (left.rule.id === "generic/fallback") {
7323
- return 1;
7324
- }
7325
- if (right.rule.id === "generic/fallback") {
7326
- return -1;
7327
- }
7328
- return left.rule.id.localeCompare(right.rule.id);
7329
- });
7330
- }
7331
- async function loadRuleDescriptorsFromRoot(root, source) {
7332
- const files = await listRuleFiles(root);
7333
- return await Promise.all(
7334
- files.map(async (fullPath) => {
7335
- const parsed = JSON.parse(await readFile(fullPath, "utf8"));
7336
- assertValidRule(parsed);
7337
- return {
7338
- source,
7339
- path: fullPath,
7340
- relativePath: relative(root, fullPath),
7341
- rule: parsed
7342
- };
7343
- })
7344
- );
7345
- }
7346
- function loadBundledBuiltinRuleDescriptors() {
7347
- return BUNDLED_BUILTIN_RULES.map((rule) => {
7348
- assertValidRule(rule);
7349
- return {
7350
- source: "builtin",
7351
- path: `bundled:${rule.id}`,
7352
- relativePath: rule.id,
7353
- rule
7354
- };
7355
- });
7356
- }
7357
- function cacheKey(options) {
7358
- return JSON.stringify({
7359
- cwd: options.cwd ?? process.cwd(),
7360
- includeUser: options.includeUser ?? true,
7361
- includeProject: options.includeProject ?? true,
7362
- userRulesDir: options.userRulesDir ?? null,
7363
- projectRulesDir: options.projectRulesDir ?? null
7364
- });
7365
- }
7366
- function overlayRules(descriptors) {
7367
- const byId = /* @__PURE__ */ new Map();
7368
- for (const descriptor of descriptors) {
7369
- byId.set(descriptor.rule.id, descriptor);
7370
- }
7371
- return sortRules([...byId.values()].map((descriptor) => compileRule(descriptor)));
7372
- }
7373
- async function loadRules(options = {}) {
7374
- const key = cacheKey(options);
7375
- const cached = ruleCache.get(key);
7376
- if (cached) {
7377
- return cached;
7378
- }
7379
- const descriptors = [];
7380
- const builtinDescriptors = await loadRuleDescriptorsFromRoot(builtinRulesRoot(), "builtin");
7381
- descriptors.push(...builtinDescriptors.length > 0 ? builtinDescriptors : loadBundledBuiltinRuleDescriptors());
7382
- if (options.includeUser ?? true) {
7383
- descriptors.push(...await loadRuleDescriptorsFromRoot(userRulesRoot(options.userRulesDir), "user"));
7384
- }
7385
- if (options.includeProject ?? true) {
7386
- descriptors.push(...await loadRuleDescriptorsFromRoot(projectRulesRoot(options.cwd, options.projectRulesDir), "project"));
7387
- }
7388
- const compiled = overlayRules(descriptors);
7389
- ruleCache.set(key, compiled);
7390
- return compiled;
7391
- }
7392
-
7393
- // src/core/classify.ts
7394
- function includesAll(argv, expected) {
7395
- return expected.every((part) => argv.includes(part));
7396
- }
7397
- function isWordLikeChar(char) {
7398
- return typeof char === "string" && /[A-Za-z0-9_]/u.test(char);
7399
- }
7400
- function includesCommandPart(command, part) {
7401
- if (!part) {
7402
- return true;
7403
- }
7404
- let fromIndex = 0;
7405
- while (fromIndex <= command.length) {
7406
- const index = command.indexOf(part, fromIndex);
7407
- if (index === -1) {
7408
- return false;
7409
- }
7410
- const end = index + part.length;
7411
- const partStartsWord = isWordLikeChar(part[0]);
7412
- const partEndsWord = isWordLikeChar(part.at(-1));
7413
- const prev = index > 0 ? command[index - 1] : void 0;
7414
- const next = end < command.length ? command[end] : void 0;
7415
- const leftBoundaryOk = !partStartsWord || !isWordLikeChar(prev);
7416
- const rightBoundaryOk = !partEndsWord || !isWordLikeChar(next);
7417
- if (leftBoundaryOk && rightBoundaryOk) {
7418
- return true;
7419
- }
7420
- fromIndex = index + 1;
7421
- }
7422
- return false;
7423
- }
7424
- function getJsonRule(rule) {
7425
- return "rule" in rule ? rule.rule : rule;
7426
- }
7427
- function usesCommandTextMatcher(ruleLike) {
7428
- const rule = getJsonRule(ruleLike);
7429
- return Boolean(rule.match.commandIncludes || rule.match.commandIncludesAny);
7430
- }
7431
- function isBuiltinRule(ruleLike) {
7432
- return "source" in ruleLike && ruleLike.source === "builtin";
7433
- }
7434
- function getCandidatePriority(candidate) {
7435
- switch (candidate.source) {
7436
- case "effective":
7437
- return 2;
7438
- case "shell-body":
7439
- return 1;
7440
- case "original":
7441
- default:
7442
- return 0;
7443
- }
7444
- }
7445
- function applyCommandMatchCandidate(input, candidate) {
7446
- const { command: _command, ...rest } = input;
7447
- return {
7448
- ...rest,
7449
- ...candidate.command ? { command: candidate.command } : {},
7450
- argv: candidate.argv
7451
- };
7602
+ // rules/tests/pnpm-test.json
7603
+ pytest_default,
7604
+ // rules/tests/pytest.json
7605
+ rspec_default,
7606
+ // rules/tests/rspec.json
7607
+ swift_test_default,
7608
+ // rules/tests/swift-test.json
7609
+ vitest_default,
7610
+ // rules/tests/vitest.json
7611
+ yarn_test_default,
7612
+ // rules/tests/yarn-test.json
7613
+ wc_default,
7614
+ // rules/text/wc.json
7615
+ rsync_default,
7616
+ // rules/transfer/rsync.json
7617
+ scp_default
7618
+ // rules/transfer/scp.json
7619
+ ];
7620
+
7621
+ // src/core/validate-rules.ts
7622
+ function hasNulByte(value) {
7623
+ return value.includes("\0");
7452
7624
  }
7453
- function matchesRule(ruleLike, input) {
7454
- const rule = getJsonRule(ruleLike);
7455
- const argv = input.argv ?? [];
7456
- const command = input.command ?? "";
7457
- const toolName = input.toolName;
7458
- if (rule.match.toolNames && !rule.match.toolNames.includes(toolName)) {
7459
- return false;
7460
- }
7461
- if (rule.match.argv0 && !rule.match.argv0.includes(argv[0] ?? "")) {
7462
- return false;
7463
- }
7464
- if (rule.match.gitSubcommands && !rule.match.gitSubcommands.includes(getGitSubcommand(argv) ?? "")) {
7465
- return false;
7466
- }
7467
- if (rule.match.argvIncludes && !rule.match.argvIncludes.every((parts) => includesAll(argv, parts))) {
7468
- return false;
7469
- }
7470
- if (rule.match.argvIncludesAny && !rule.match.argvIncludesAny.some((parts) => includesAll(argv, parts))) {
7471
- return false;
7625
+ function validateSafeString(value, path, errors, { allowEmpty = false } = {}) {
7626
+ if (typeof value !== "string") {
7627
+ errors.push(`${path} must be a string`);
7628
+ return;
7472
7629
  }
7473
- if (rule.match.commandIncludes && !rule.match.commandIncludes.every((part) => includesCommandPart(command, part))) {
7474
- return false;
7630
+ if (!allowEmpty && value.length === 0) {
7631
+ errors.push(`${path} must be a non-empty string`);
7475
7632
  }
7476
- if (rule.match.commandIncludesAny && !rule.match.commandIncludesAny.some((part) => includesCommandPart(command, part))) {
7477
- return false;
7633
+ if (hasNulByte(value)) {
7634
+ errors.push(`${path} must not contain NUL bytes`);
7478
7635
  }
7479
- return true;
7480
- }
7481
- function scoreRule(ruleLike) {
7482
- const rule = getJsonRule(ruleLike);
7483
- return (rule.priority ?? 0) * 1e3 + (rule.match.argv0?.length ?? 0) * 100 + (rule.match.gitSubcommands?.length ?? 0) * 60 + (rule.match.argvIncludes?.reduce((sum, parts) => sum + parts.length, 0) ?? 0) * 40 + (rule.match.argvIncludesAny?.reduce((sum, parts) => sum + parts.length, 0) ?? 0) * 35 + (rule.match.commandIncludes?.length ?? 0) * 25 + (rule.match.commandIncludesAny?.length ?? 0) * 20 + (rule.match.toolNames?.length ?? 0) * 10;
7484
7636
  }
7485
- function compareSelections(left, right) {
7486
- const scoreDiff = scoreRule(right.rule) - scoreRule(left.rule);
7487
- if (scoreDiff !== 0) {
7488
- return scoreDiff;
7489
- }
7490
- const candidateDiff = getCandidatePriority(right.candidate) - getCandidatePriority(left.candidate);
7491
- if (candidateDiff !== 0) {
7492
- return candidateDiff;
7637
+ function validatePositiveInteger(value, path, errors) {
7638
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
7639
+ errors.push(`${path} must be a non-negative integer`);
7493
7640
  }
7494
- return getJsonRule(left.rule).id.localeCompare(getJsonRule(right.rule).id);
7495
7641
  }
7496
- function findBestRuleMatch(input, rules) {
7497
- const candidates = deriveCommandMatchCandidates(input);
7498
- const highestCandidatePriority = Math.max(...candidates.map(getCandidatePriority));
7499
- const specificMatches = [];
7500
- let fallbackSelection;
7501
- for (const candidate of candidates) {
7502
- const candidateInput = applyCommandMatchCandidate(input, candidate);
7503
- for (const rule of rules) {
7504
- if (!matchesRule(rule, candidateInput)) {
7505
- continue;
7506
- }
7507
- if (getJsonRule(rule).id === "generic/fallback") {
7508
- fallbackSelection ??= { rule, candidate };
7509
- continue;
7510
- }
7511
- if (isBuiltinRule(rule) && usesCommandTextMatcher(rule) && getCandidatePriority(candidate) < highestCandidatePriority) {
7512
- continue;
7513
- }
7514
- specificMatches.push({ rule, candidate });
7515
- }
7516
- }
7517
- if (specificMatches.length > 0) {
7518
- return [...specificMatches].sort(compareSelections)[0];
7519
- }
7520
- return fallbackSelection;
7642
+ function isRecord(value) {
7643
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7521
7644
  }
7522
- function buildClassificationResult(ruleLike, candidate) {
7523
- const rule = getJsonRule(ruleLike);
7524
- return {
7525
- family: rule.family,
7526
- confidence: rule.id === "generic/fallback" ? 0.2 : 0.9,
7527
- matchedReducer: rule.id,
7528
- matchedVia: candidate.source,
7529
- matchedCommand: candidate.command ?? candidate.argv.join(" ")
7530
- };
7645
+ function isStringArray(value) {
7646
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
7531
7647
  }
7532
- function resolveRuleMatch(input, rules) {
7533
- const match = findBestRuleMatch(input, rules);
7534
- if (!match) {
7535
- return void 0;
7648
+ function validateMatch(value, path) {
7649
+ if (!isRecord(value)) {
7650
+ return [`${path} must be an object`];
7536
7651
  }
7537
- const candidateInput = applyCommandMatchCandidate(input, match.candidate);
7538
- return {
7539
- rule: match.rule,
7540
- candidate: match.candidate,
7541
- candidateInput,
7542
- classification: buildClassificationResult(match.rule, match.candidate)
7543
- };
7544
- }
7545
- function classifyExecution(input, rules, forcedRuleId) {
7546
- if (forcedRuleId) {
7547
- const forcedRule = rules.find((rule) => getJsonRule(rule).id === forcedRuleId);
7548
- if (forcedRule) {
7549
- const forced = getJsonRule(forcedRule);
7550
- return {
7551
- family: forced.family,
7552
- confidence: 1,
7553
- matchedReducer: forced.id
7554
- };
7555
- }
7652
+ const errors = [];
7653
+ if ("toolNames" in value && !isStringArray(value.toolNames)) {
7654
+ errors.push(`${path}.toolNames must be an array of strings`);
7556
7655
  }
7557
- const resolved = resolveRuleMatch(input, rules);
7558
- if (!resolved) {
7559
- return {
7560
- family: "generic",
7561
- confidence: 0.2
7562
- };
7656
+ if ("argv0" in value && !isStringArray(value.argv0)) {
7657
+ errors.push(`${path}.argv0 must be an array of strings`);
7563
7658
  }
7564
- return resolved.classification;
7565
- }
7566
-
7567
- // src/core/execution-input.ts
7568
- function normalizeExecutionInput(input) {
7569
- const shellWrapped = unwrapShellRunner(input);
7570
- if (shellWrapped) {
7571
- const effectiveCommand2 = stripLeadingCdPrefix(shellWrapped);
7572
- if (isCompoundShellCommand(effectiveCommand2)) {
7573
- const { argv: _argv, ...restInput } = input;
7574
- return {
7575
- ...restInput,
7576
- command: effectiveCommand2
7577
- };
7578
- }
7579
- const argv2 = resolveEffectiveCommand({ command: effectiveCommand2 })?.argv ?? tokenizeCommand(effectiveCommand2);
7580
- if (argv2.length === 0) {
7581
- return {
7582
- ...input,
7583
- command: effectiveCommand2
7584
- };
7585
- }
7586
- return {
7587
- ...input,
7588
- command: argv2.join(" "),
7589
- argv: argv2
7590
- };
7659
+ if ("gitSubcommands" in value && !isStringArray(value.gitSubcommands)) {
7660
+ errors.push(`${path}.gitSubcommands must be an array of strings`);
7591
7661
  }
7592
- const effective = resolveEffectiveCommand(input);
7593
- if (effective?.argv.length) {
7594
- return {
7595
- ...input,
7596
- ...effective.command ? { command: effective.command } : {},
7597
- argv: effective.argv
7598
- };
7662
+ if ("commandIncludes" in value && !isStringArray(value.commandIncludes)) {
7663
+ errors.push(`${path}.commandIncludes must be an array of strings`);
7599
7664
  }
7600
- if (input.argv?.length || !input.command) {
7601
- return input;
7665
+ if ("commandIncludesAny" in value && !isStringArray(value.commandIncludesAny)) {
7666
+ errors.push(`${path}.commandIncludesAny must be an array of strings`);
7602
7667
  }
7603
- const effectiveCommand = stripLeadingCdPrefix(input.command);
7604
- if (isCompoundShellCommand(effectiveCommand)) {
7605
- return input;
7668
+ if ("argvIncludes" in value) {
7669
+ if (!Array.isArray(value.argvIncludes) || !value.argvIncludes.every(isStringArray)) {
7670
+ errors.push(`${path}.argvIncludes must be an array of string arrays`);
7671
+ }
7606
7672
  }
7607
- const argv = tokenizeCommand(effectiveCommand);
7608
- if (argv.length === 0) {
7609
- return input;
7673
+ if ("argvIncludesAny" in value) {
7674
+ if (!Array.isArray(value.argvIncludesAny) || !value.argvIncludesAny.every(isStringArray)) {
7675
+ errors.push(`${path}.argvIncludesAny must be an array of string arrays`);
7676
+ }
7610
7677
  }
7611
- return {
7612
- ...input,
7613
- command: argv.join(" "),
7614
- argv
7615
- };
7678
+ return errors;
7616
7679
  }
7617
-
7618
- // src/core/artifacts.ts
7619
- import { mkdir, readFile as readFile2, readdir as readdir2, writeFile } from "node:fs/promises";
7620
- import { homedir as homedir2 } from "node:os";
7621
- import { join as join2 } from "node:path";
7622
- import { randomUUID } from "node:crypto";
7623
-
7624
- // src/core/source.ts
7625
- var DEFAULT_CLI_ARTIFACT_SOURCE = "cli";
7626
- function normalizeArtifactSource(value) {
7627
- if (typeof value !== "string") {
7628
- return null;
7629
- }
7630
- const source = value.trim().toLowerCase().replace(/[_\s]+/gu, "-").replace(/[^a-z0-9.-]+/gu, "-").replace(/^-+|-+$/gu, "");
7631
- if (!source) {
7632
- return null;
7680
+ function validateCounter(value, path) {
7681
+ if (!isRecord(value)) {
7682
+ return [`${path} must be an object`];
7633
7683
  }
7634
- if (source.startsWith("amazon-q") || source.startsWith("amazonq") || source.startsWith("aws-q")) {
7635
- return "amazon-q";
7684
+ const errors = [];
7685
+ validateSafeString(value.name, `${path}.name`, errors);
7686
+ validateSafeString(value.pattern, `${path}.pattern`, errors);
7687
+ if ("flags" in value) {
7688
+ validateSafeString(value.flags, `${path}.flags`, errors, { allowEmpty: true });
7636
7689
  }
7637
- if (source.startsWith("claude-code") || source === "claude") {
7638
- return "claude-code";
7690
+ return errors;
7691
+ }
7692
+ function validateOutputMatch(value, path) {
7693
+ if (!isRecord(value)) {
7694
+ return [`${path} must be an object`];
7639
7695
  }
7640
- if (source.startsWith("cline")) {
7641
- return "cline";
7696
+ const errors = [];
7697
+ validateSafeString(value.pattern, `${path}.pattern`, errors);
7698
+ validateSafeString(value.message, `${path}.message`, errors);
7699
+ if ("flags" in value) {
7700
+ validateSafeString(value.flags, `${path}.flags`, errors, { allowEmpty: true });
7642
7701
  }
7643
- if (source.startsWith("codex")) {
7644
- return "codex";
7702
+ return errors;
7703
+ }
7704
+ function validateOptionalStringArrayObject(value, path, keys) {
7705
+ if (!isRecord(value)) {
7706
+ return [`${path} must be an object`];
7645
7707
  }
7646
- if (source.startsWith("command-code") || source.startsWith("commandcode")) {
7647
- return "command-code";
7708
+ const errors = [];
7709
+ for (const key of keys) {
7710
+ if (key in value && !isStringArray(value[key])) {
7711
+ errors.push(`${path}.${key} must be an array of strings`);
7712
+ }
7648
7713
  }
7649
- if (source.startsWith("copilot-agent") || source.startsWith("github-copilot-agent")) {
7650
- return "copilot-agent";
7714
+ return errors;
7715
+ }
7716
+ function validateOptionalNumberObject(value, path, keys) {
7717
+ if (!isRecord(value)) {
7718
+ return [`${path} must be an object`];
7651
7719
  }
7652
- if (source.startsWith("copilot-cli") || source.startsWith("github-copilot-cli")) {
7653
- return "copilot-cli";
7720
+ const errors = [];
7721
+ for (const key of keys) {
7722
+ if (key in value) {
7723
+ validatePositiveInteger(value[key], `${path}.${key}`, errors);
7724
+ }
7654
7725
  }
7655
- if (source.startsWith("crush")) {
7656
- return "crush";
7726
+ return errors;
7727
+ }
7728
+ function validateOptionalBooleanObject(value, path, keys) {
7729
+ if (!isRecord(value)) {
7730
+ return [`${path} must be an object`];
7657
7731
  }
7658
- if (source.startsWith("cursor")) {
7659
- return "cursor";
7732
+ const errors = [];
7733
+ for (const key of keys) {
7734
+ if (key in value && typeof value[key] !== "boolean") {
7735
+ errors.push(`${path}.${key} must be a boolean`);
7736
+ }
7660
7737
  }
7661
- if (source.startsWith("droid") || source.startsWith("factory-droid")) {
7662
- return "droid";
7738
+ return errors;
7739
+ }
7740
+ function validateRule(raw) {
7741
+ if (!isRecord(raw)) {
7742
+ return {
7743
+ ok: false,
7744
+ errors: ["rule must be an object"]
7745
+ };
7663
7746
  }
7664
- if (source.startsWith("gemini")) {
7665
- return "gemini-cli";
7747
+ const errors = [];
7748
+ validateSafeString(raw.id, "id", errors);
7749
+ validateSafeString(raw.family, "family", errors);
7750
+ if ("description" in raw) {
7751
+ validateSafeString(raw.description, "description", errors, { allowEmpty: true });
7666
7752
  }
7667
- if (source.startsWith("grok-build") || source.startsWith("grokbuild") || source.startsWith("xai-grok-build")) {
7668
- return "grok-build";
7753
+ if ("onEmpty" in raw) {
7754
+ validateSafeString(raw.onEmpty, "onEmpty", errors);
7669
7755
  }
7670
- if (source.startsWith("grok")) {
7671
- return "grok-cli";
7756
+ if ("counterSource" in raw && raw.counterSource !== "postKeep" && raw.counterSource !== "preKeep") {
7757
+ errors.push("counterSource must be one of: postKeep, preKeep");
7672
7758
  }
7673
- if (source.startsWith("goose")) {
7674
- return "goose";
7759
+ if ("priority" in raw && (typeof raw.priority !== "number" || !Number.isFinite(raw.priority))) {
7760
+ errors.push("priority must be a finite number");
7675
7761
  }
7676
- if (source.startsWith("antigravity") || source === "google-antigravity") {
7677
- return "antigravity";
7762
+ if (!("match" in raw)) {
7763
+ errors.push("match is required");
7764
+ } else {
7765
+ errors.push(...validateMatch(raw.match, "match"));
7678
7766
  }
7679
- if (source.startsWith("augment") || source.startsWith("auggie")) {
7680
- return "augment";
7767
+ if ("filters" in raw) {
7768
+ errors.push(...validateOptionalStringArrayObject(raw.filters, "filters", ["skipPatterns", "keepPatterns"]));
7681
7769
  }
7682
- if (source.startsWith("openclaw")) {
7683
- return "openclaw";
7770
+ if ("transforms" in raw) {
7771
+ errors.push(...validateOptionalBooleanObject(raw.transforms, "transforms", [
7772
+ "stripAnsi",
7773
+ "prettyPrintJson",
7774
+ "dedupeAdjacent",
7775
+ "trimEmptyEdges"
7776
+ ]));
7684
7777
  }
7685
- if (source.startsWith("openhands")) {
7686
- return "openhands";
7778
+ if ("summarize" in raw) {
7779
+ errors.push(...validateOptionalNumberObject(raw.summarize, "summarize", ["head", "tail"]));
7687
7780
  }
7688
- if (source.startsWith("openinterpreter") || source.startsWith("open-interpreter")) {
7689
- return "open-interpreter";
7781
+ if ("failure" in raw) {
7782
+ errors.push(...validateOptionalBooleanObject(raw.failure, "failure", ["preserveOnFailure"]));
7783
+ errors.push(...validateOptionalNumberObject(raw.failure, "failure", ["head", "tail"]));
7690
7784
  }
7691
- if (source.startsWith("openwebui") || source.startsWith("open-webui")) {
7692
- return "openwebui";
7785
+ if ("counters" in raw) {
7786
+ if (!Array.isArray(raw.counters)) {
7787
+ errors.push("counters must be an array");
7788
+ } else {
7789
+ raw.counters.forEach((counter, index) => {
7790
+ errors.push(...validateCounter(counter, `counters[${index}]`));
7791
+ });
7792
+ }
7693
7793
  }
7694
- if (source.startsWith("opencode") || source.startsWith("open-code")) {
7695
- return "opencode";
7794
+ if ("matchOutput" in raw) {
7795
+ if (!Array.isArray(raw.matchOutput)) {
7796
+ errors.push("matchOutput must be an array");
7797
+ } else {
7798
+ raw.matchOutput.forEach((entry, index) => {
7799
+ errors.push(...validateOutputMatch(entry, `matchOutput[${index}]`));
7800
+ });
7801
+ }
7696
7802
  }
7697
- if (source.startsWith("pi")) {
7698
- return "pi";
7803
+ if (errors.length > 0) {
7804
+ return {
7805
+ ok: false,
7806
+ errors
7807
+ };
7699
7808
  }
7700
- if (source.startsWith("plandex")) {
7701
- return "plandex";
7809
+ return { ok: true };
7810
+ }
7811
+ function assertValidRule(raw) {
7812
+ const validation = validateRule(raw);
7813
+ if (!validation.ok) {
7814
+ throw new Error(`invalid rule:
7815
+ - ${validation.errors.join("\n- ")}`);
7702
7816
  }
7703
- if (source.startsWith("qoder")) {
7704
- return "qoder";
7817
+ }
7818
+
7819
+ // src/core/rules.ts
7820
+ var ruleCache = /* @__PURE__ */ new Map();
7821
+ function builtinRulesRoot() {
7822
+ return resolve(fileURLToPath(new URL("../rules", import.meta.url)));
7823
+ }
7824
+ function mergeRegexFlags(flags) {
7825
+ return [...new Set(`u${flags ?? ""}`.split(""))].join("");
7826
+ }
7827
+ function compileRule(descriptor) {
7828
+ return {
7829
+ rule: descriptor.rule,
7830
+ source: descriptor.source,
7831
+ path: descriptor.path,
7832
+ compiled: {
7833
+ skipPatterns: (descriptor.rule.filters?.skipPatterns ?? []).map((pattern) => new RegExp(pattern, "u")),
7834
+ keepPatterns: (descriptor.rule.filters?.keepPatterns ?? []).map((pattern) => new RegExp(pattern, "u")),
7835
+ counters: (descriptor.rule.counters ?? []).map((counter) => ({
7836
+ name: counter.name,
7837
+ pattern: new RegExp(counter.pattern, mergeRegexFlags(counter.flags))
7838
+ })),
7839
+ outputMatches: (descriptor.rule.matchOutput ?? []).map((entry) => ({
7840
+ pattern: new RegExp(entry.pattern, mergeRegexFlags(entry.flags)),
7841
+ message: entry.message
7842
+ }))
7843
+ }
7844
+ };
7845
+ }
7846
+ async function listRuleFiles(root) {
7847
+ const resolvedRoot = await realpath(root).catch(() => null);
7848
+ if (!resolvedRoot) {
7849
+ return [];
7705
7850
  }
7706
- if (source.startsWith("qwen")) {
7707
- return "qwen-code";
7851
+ const rootRealPath = resolvedRoot;
7852
+ async function walk(currentDir) {
7853
+ const entries = (await readdir2(currentDir, { withFileTypes: true })).sort((left, right) => left.name.localeCompare(right.name));
7854
+ const files = await Promise.all(
7855
+ entries.map(async (entry) => {
7856
+ const fullPath = join3(currentDir, entry.name);
7857
+ if (entry.isSymbolicLink()) {
7858
+ return [];
7859
+ }
7860
+ if (entry.isDirectory()) {
7861
+ return await walk(fullPath);
7862
+ }
7863
+ if (!entry.isFile() || !entry.name.endsWith(".json") || entry.name.endsWith(".schema.json") || entry.name.endsWith(".fixture.json")) {
7864
+ return [];
7865
+ }
7866
+ const realFilePath = await realpath(fullPath).catch(() => null);
7867
+ if (!realFilePath) {
7868
+ return [];
7869
+ }
7870
+ const relativePath = relative(rootRealPath, realFilePath);
7871
+ if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
7872
+ return [];
7873
+ }
7874
+ return [realFilePath];
7875
+ })
7876
+ );
7877
+ return files.flat();
7708
7878
  }
7709
- if (source.startsWith("kimi")) {
7710
- return "kimi";
7879
+ try {
7880
+ return await walk(root);
7881
+ } catch {
7882
+ return [];
7711
7883
  }
7712
- if (source.startsWith("mux")) {
7713
- return "mux";
7884
+ }
7885
+ function userRulesRoot(customDir) {
7886
+ return customDir ?? join3(homedir2(), ".config", "tokenjuice", "rules");
7887
+ }
7888
+ function projectRulesRoot(cwd, customDir) {
7889
+ return customDir ?? join3(cwd ?? process.cwd(), ".tokenjuice", "rules");
7890
+ }
7891
+ function sortRules(rules) {
7892
+ return [...rules].sort((left, right) => {
7893
+ if (left.rule.id === "generic/fallback") {
7894
+ return 1;
7895
+ }
7896
+ if (right.rule.id === "generic/fallback") {
7897
+ return -1;
7898
+ }
7899
+ return left.rule.id.localeCompare(right.rule.id);
7900
+ });
7901
+ }
7902
+ async function loadRuleDescriptorsFromRoot(root, source) {
7903
+ const files = await listRuleFiles(root);
7904
+ return await Promise.all(
7905
+ files.map(async (fullPath) => {
7906
+ const parsed = JSON.parse(await readFile3(fullPath, "utf8"));
7907
+ assertValidRule(parsed);
7908
+ return {
7909
+ source,
7910
+ path: fullPath,
7911
+ relativePath: relative(root, fullPath),
7912
+ rule: parsed
7913
+ };
7914
+ })
7915
+ );
7916
+ }
7917
+ function loadBundledBuiltinRuleDescriptors() {
7918
+ return BUNDLED_BUILTIN_RULES.map((rule) => {
7919
+ assertValidRule(rule);
7920
+ return {
7921
+ source: "builtin",
7922
+ path: `bundled:${rule.id}`,
7923
+ relativePath: rule.id,
7924
+ rule
7925
+ };
7926
+ });
7927
+ }
7928
+ function cacheKey(options) {
7929
+ return JSON.stringify({
7930
+ cwd: options.cwd ?? process.cwd(),
7931
+ includeUser: options.includeUser ?? true,
7932
+ includeProject: options.includeProject ?? true,
7933
+ userRulesDir: options.userRulesDir ?? null,
7934
+ projectRulesDir: options.projectRulesDir ?? null
7935
+ });
7936
+ }
7937
+ function overlayRules(descriptors) {
7938
+ const byId = /* @__PURE__ */ new Map();
7939
+ for (const descriptor of descriptors) {
7940
+ byId.set(descriptor.rule.id, descriptor);
7714
7941
  }
7715
- if (source.startsWith("ruler")) {
7716
- return "ruler";
7942
+ return sortRules([...byId.values()].map((descriptor) => compileRule(descriptor)));
7943
+ }
7944
+ async function loadRules(options = {}) {
7945
+ const key = cacheKey(options);
7946
+ const cached = ruleCache.get(key);
7947
+ if (cached) {
7948
+ return cached;
7717
7949
  }
7718
- if (source.startsWith("vscode-copilot") || source.startsWith("vs-code-copilot")) {
7719
- return "vscode-copilot";
7950
+ const descriptors = [];
7951
+ const builtinDescriptors = await loadRuleDescriptorsFromRoot(builtinRulesRoot(), "builtin");
7952
+ descriptors.push(...builtinDescriptors.length > 0 ? builtinDescriptors : loadBundledBuiltinRuleDescriptors());
7953
+ if (options.includeUser ?? true) {
7954
+ descriptors.push(...await loadRuleDescriptorsFromRoot(userRulesRoot(options.userRulesDir), "user"));
7720
7955
  }
7721
- if (source === "direct" || source === "tokenjuice" || source === "wrap") {
7722
- return DEFAULT_CLI_ARTIFACT_SOURCE;
7956
+ if (options.includeProject ?? true) {
7957
+ descriptors.push(...await loadRuleDescriptorsFromRoot(projectRulesRoot(options.cwd, options.projectRulesDir), "project"));
7723
7958
  }
7724
- return source;
7725
- }
7726
- function resolveArtifactSource(input) {
7727
- return normalizeArtifactSource(input.metadata?.source) ?? DEFAULT_CLI_ARTIFACT_SOURCE;
7959
+ const compiled = overlayRules(descriptors);
7960
+ ruleCache.set(key, compiled);
7961
+ return compiled;
7728
7962
  }
7729
7963
 
7730
- // src/core/artifacts.ts
7731
- var ARTIFACT_ID_PATTERN = /^tj_[0-9a-f-]{12}$/iu;
7732
- var ARTIFACT_DIR_ENV = "TOKENJUICE_ARTIFACT_DIR";
7733
- var OPTIONAL_METADATA_STORAGE_ERROR_CODES = /* @__PURE__ */ new Set([
7734
- "EACCES",
7735
- "EDQUOT",
7736
- "EEXIST",
7737
- "EFBIG",
7738
- "EIO",
7739
- "EISDIR",
7740
- "ELOOP",
7741
- "EMFILE",
7742
- "ENAMETOOLONG",
7743
- "ENFILE",
7744
- "ENOENT",
7745
- "ENOSPC",
7746
- "ENOTDIR",
7747
- "EPERM",
7748
- "EROFS"
7749
- ]);
7750
- function extractCaptureTruncatedFlag(input) {
7751
- const value = input.metadata?.tokenjuiceCaptureTruncated;
7752
- return typeof value === "boolean" ? value : void 0;
7964
+ // src/core/classify.ts
7965
+ function includesAll(argv, expected) {
7966
+ return expected.every((part) => argv.includes(part));
7753
7967
  }
7754
- function getDefaultArtifactDir() {
7755
- const artifactDir = process.env[ARTIFACT_DIR_ENV];
7756
- if (typeof artifactDir === "string" && artifactDir.trim()) {
7757
- return artifactDir.trim();
7968
+ function isWordLikeChar(char) {
7969
+ return typeof char === "string" && /[A-Za-z0-9_]/u.test(char);
7970
+ }
7971
+ function includesCommandPart(command, part) {
7972
+ if (!part) {
7973
+ return true;
7974
+ }
7975
+ let fromIndex = 0;
7976
+ while (fromIndex <= command.length) {
7977
+ const index = command.indexOf(part, fromIndex);
7978
+ if (index === -1) {
7979
+ return false;
7980
+ }
7981
+ const end = index + part.length;
7982
+ const partStartsWord = isWordLikeChar(part[0]);
7983
+ const partEndsWord = isWordLikeChar(part.at(-1));
7984
+ const prev = index > 0 ? command[index - 1] : void 0;
7985
+ const next = end < command.length ? command[end] : void 0;
7986
+ const leftBoundaryOk = !partStartsWord || !isWordLikeChar(prev);
7987
+ const rightBoundaryOk = !partEndsWord || !isWordLikeChar(next);
7988
+ if (leftBoundaryOk && rightBoundaryOk) {
7989
+ return true;
7990
+ }
7991
+ fromIndex = index + 1;
7758
7992
  }
7759
- return join2(homedir2(), ".tokenjuice", "artifacts");
7993
+ return false;
7760
7994
  }
7761
- function resolveArtifactBaseDir(storeDir) {
7762
- return storeDir ?? getDefaultArtifactDir();
7995
+ function getJsonRule(rule) {
7996
+ return "rule" in rule ? rule.rule : rule;
7763
7997
  }
7764
- function isValidArtifactId(id) {
7765
- return ARTIFACT_ID_PATTERN.test(id);
7998
+ function usesCommandTextMatcher(ruleLike) {
7999
+ const rule = getJsonRule(ruleLike);
8000
+ return Boolean(rule.match.commandIncludes || rule.match.commandIncludesAny);
7766
8001
  }
7767
- function buildArtifactPaths(id, storeDir) {
7768
- if (!isValidArtifactId(id)) {
7769
- throw new Error(`invalid artifact id: ${id}`);
8002
+ function isBuiltinRule(ruleLike) {
8003
+ return "source" in ruleLike && ruleLike.source === "builtin";
8004
+ }
8005
+ function getCandidatePriority(candidate) {
8006
+ switch (candidate.source) {
8007
+ case "effective":
8008
+ return 2;
8009
+ case "shell-body":
8010
+ return 1;
8011
+ case "original":
8012
+ default:
8013
+ return 0;
7770
8014
  }
7771
- const base = resolveArtifactBaseDir(storeDir);
8015
+ }
8016
+ function applyCommandMatchCandidate(input, candidate) {
8017
+ const { command: _command, ...rest } = input;
7772
8018
  return {
7773
- id,
7774
- storage: "file",
7775
- path: join2(base, `${id}.txt`),
7776
- metadataPath: join2(base, `${id}.json`)
8019
+ ...rest,
8020
+ ...candidate.command ? { command: candidate.command } : {},
8021
+ argv: candidate.argv
7777
8022
  };
7778
8023
  }
7779
- function buildMetadataOnlyPath(id, storeDir) {
7780
- if (!isValidArtifactId(id)) {
7781
- throw new Error(`invalid artifact id: ${id}`);
8024
+ function matchesRule(ruleLike, input) {
8025
+ const rule = getJsonRule(ruleLike);
8026
+ const argv = input.argv ?? [];
8027
+ const command = input.command ?? "";
8028
+ const toolName = input.toolName;
8029
+ if (rule.match.toolNames && !rule.match.toolNames.includes(toolName)) {
8030
+ return false;
8031
+ }
8032
+ if (rule.match.argv0 && !rule.match.argv0.includes(argv[0] ?? "")) {
8033
+ return false;
8034
+ }
8035
+ if (rule.match.gitSubcommands && !rule.match.gitSubcommands.includes(getGitSubcommand(argv) ?? "")) {
8036
+ return false;
8037
+ }
8038
+ if (rule.match.argvIncludes && !rule.match.argvIncludes.every((parts) => includesAll(argv, parts))) {
8039
+ return false;
8040
+ }
8041
+ if (rule.match.argvIncludesAny && !rule.match.argvIncludesAny.some((parts) => includesAll(argv, parts))) {
8042
+ return false;
8043
+ }
8044
+ if (rule.match.commandIncludes && !rule.match.commandIncludes.every((part) => includesCommandPart(command, part))) {
8045
+ return false;
8046
+ }
8047
+ if (rule.match.commandIncludesAny && !rule.match.commandIncludesAny.some((part) => includesCommandPart(command, part))) {
8048
+ return false;
7782
8049
  }
7783
- return join2(resolveArtifactBaseDir(storeDir), `${id}.meta.json`);
8050
+ return true;
7784
8051
  }
7785
- async function storeArtifact(input, storeDir) {
7786
- const id = `tj_${randomUUID().slice(0, 12)}`;
7787
- const ref = buildArtifactPaths(id, storeDir);
7788
- await mkdir(resolveArtifactBaseDir(storeDir), { recursive: true, mode: 448 });
7789
- const captureTruncated = extractCaptureTruncatedFlag(input.input);
7790
- const artifact = {
7791
- id,
7792
- rawText: input.rawText,
7793
- metadata: {
7794
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
7795
- source: resolveArtifactSource(input.input),
7796
- classification: input.classification,
7797
- rawChars: input.stats?.rawChars ?? countTextChars(stripAnsi(input.rawText)),
7798
- ...input.input.toolName ? { toolName: input.input.toolName } : {},
7799
- ...input.input.command ? { command: input.input.command } : {},
7800
- ...typeof input.input.exitCode === "number" ? { exitCode: input.input.exitCode } : {},
7801
- ...captureTruncated !== void 0 ? { captureTruncated } : {},
7802
- ...input.stats ? { reducedChars: input.stats.reducedChars, ratio: input.stats.ratio } : {}
8052
+ function scoreRule(ruleLike) {
8053
+ const rule = getJsonRule(ruleLike);
8054
+ return (rule.priority ?? 0) * 1e3 + (rule.match.argv0?.length ?? 0) * 100 + (rule.match.gitSubcommands?.length ?? 0) * 60 + (rule.match.argvIncludes?.reduce((sum, parts) => sum + parts.length, 0) ?? 0) * 40 + (rule.match.argvIncludesAny?.reduce((sum, parts) => sum + parts.length, 0) ?? 0) * 35 + (rule.match.commandIncludes?.length ?? 0) * 25 + (rule.match.commandIncludesAny?.length ?? 0) * 20 + (rule.match.toolNames?.length ?? 0) * 10;
8055
+ }
8056
+ function compareSelections(left, right) {
8057
+ const scoreDiff = scoreRule(right.rule) - scoreRule(left.rule);
8058
+ if (scoreDiff !== 0) {
8059
+ return scoreDiff;
8060
+ }
8061
+ const candidateDiff = getCandidatePriority(right.candidate) - getCandidatePriority(left.candidate);
8062
+ if (candidateDiff !== 0) {
8063
+ return candidateDiff;
8064
+ }
8065
+ return getJsonRule(left.rule).id.localeCompare(getJsonRule(right.rule).id);
8066
+ }
8067
+ function findBestRuleMatch(input, rules) {
8068
+ const candidates = deriveCommandMatchCandidates(input);
8069
+ const highestCandidatePriority = Math.max(...candidates.map(getCandidatePriority));
8070
+ const specificMatches = [];
8071
+ let fallbackSelection;
8072
+ for (const candidate of candidates) {
8073
+ const candidateInput = applyCommandMatchCandidate(input, candidate);
8074
+ for (const rule of rules) {
8075
+ if (!matchesRule(rule, candidateInput)) {
8076
+ continue;
8077
+ }
8078
+ if (getJsonRule(rule).id === "generic/fallback") {
8079
+ fallbackSelection ??= { rule, candidate };
8080
+ continue;
8081
+ }
8082
+ if (isBuiltinRule(rule) && usesCommandTextMatcher(rule) && getCandidatePriority(candidate) < highestCandidatePriority) {
8083
+ continue;
8084
+ }
8085
+ specificMatches.push({ rule, candidate });
7803
8086
  }
7804
- };
7805
- await Promise.all([
7806
- writeFile(ref.path, input.rawText, { encoding: "utf8", mode: 384 }),
7807
- writeFile(ref.metadataPath, JSON.stringify(artifact.metadata, null, 2), { encoding: "utf8", mode: 384 })
7808
- ]);
7809
- return ref;
8087
+ }
8088
+ if (specificMatches.length > 0) {
8089
+ return [...specificMatches].sort(compareSelections)[0];
8090
+ }
8091
+ return fallbackSelection;
7810
8092
  }
7811
- async function storeArtifactMetadata(input, storeDir) {
7812
- const id = `tj_${randomUUID().slice(0, 12)}`;
7813
- const metadataPath = buildMetadataOnlyPath(id, storeDir);
7814
- const captureTruncated = extractCaptureTruncatedFlag(input.input);
7815
- const metadata = {
7816
- createdAt: (/* @__PURE__ */ new Date()).toISOString(),
7817
- source: resolveArtifactSource(input.input),
7818
- classification: input.classification,
7819
- rawChars: input.stats?.rawChars ?? countTextChars(stripAnsi(input.rawText)),
7820
- ...input.input.toolName ? { toolName: input.input.toolName } : {},
7821
- ...input.input.command ? { command: input.input.command } : {},
7822
- ...typeof input.input.exitCode === "number" ? { exitCode: input.input.exitCode } : {},
7823
- ...captureTruncated !== void 0 ? { captureTruncated } : {},
7824
- ...input.stats ? { reducedChars: input.stats.reducedChars, ratio: input.stats.ratio } : {}
8093
+ function buildClassificationResult(ruleLike, candidate) {
8094
+ const rule = getJsonRule(ruleLike);
8095
+ return {
8096
+ family: rule.family,
8097
+ confidence: rule.id === "generic/fallback" ? 0.2 : 0.9,
8098
+ matchedReducer: rule.id,
8099
+ matchedVia: candidate.source,
8100
+ matchedCommand: candidate.command ?? candidate.argv.join(" ")
7825
8101
  };
7826
- await mkdir(resolveArtifactBaseDir(storeDir), { recursive: true, mode: 448 });
7827
- await writeFile(metadataPath, JSON.stringify(metadata, null, 2), { encoding: "utf8", mode: 384 });
8102
+ }
8103
+ function resolveRuleMatch(input, rules) {
8104
+ const match = findBestRuleMatch(input, rules);
8105
+ if (!match) {
8106
+ return void 0;
8107
+ }
8108
+ const candidateInput = applyCommandMatchCandidate(input, match.candidate);
7828
8109
  return {
7829
- id,
7830
- storage: "file",
7831
- metadataPath,
7832
- metadata
8110
+ rule: match.rule,
8111
+ candidate: match.candidate,
8112
+ candidateInput,
8113
+ classification: buildClassificationResult(match.rule, match.candidate)
7833
8114
  };
7834
8115
  }
7835
- async function tryStoreArtifactMetadata(input, storeDir) {
7836
- try {
7837
- return await storeArtifactMetadata(input, storeDir);
7838
- } catch (error) {
7839
- const code = error.code;
7840
- if (typeof code !== "string" || !OPTIONAL_METADATA_STORAGE_ERROR_CODES.has(code)) {
7841
- throw error;
8116
+ function classifyExecution(input, rules, forcedRuleId) {
8117
+ if (forcedRuleId) {
8118
+ const forcedRule = rules.find((rule) => getJsonRule(rule).id === forcedRuleId);
8119
+ if (forcedRule) {
8120
+ const forced = getJsonRule(forcedRule);
8121
+ return {
8122
+ family: forced.family,
8123
+ confidence: 1,
8124
+ matchedReducer: forced.id
8125
+ };
7842
8126
  }
7843
- return void 0;
7844
8127
  }
8128
+ const resolved = resolveRuleMatch(input, rules);
8129
+ if (!resolved) {
8130
+ return {
8131
+ family: "generic",
8132
+ confidence: 0.2
8133
+ };
8134
+ }
8135
+ return resolved.classification;
7845
8136
  }
7846
8137
 
7847
8138
  // src/core/github-actions-summary.ts
@@ -8786,6 +9077,7 @@ async function reduceExecutionWithRules(input, rules, opts = {}) {
8786
9077
  input: normalizedInput,
8787
9078
  rawText,
8788
9079
  classification,
9080
+ ...opts.recordStats !== void 0 ? { recordStats: opts.recordStats } : {},
8789
9081
  stats: {
8790
9082
  rawChars: measuredRawChars,
8791
9083
  reducedChars: measuredRawChars,
@@ -8842,6 +9134,7 @@ async function reduceExecutionWithRules(input, rules, opts = {}) {
8842
9134
  input: normalizedInput,
8843
9135
  rawText,
8844
9136
  classification: summaryClassification,
9137
+ ...opts.recordStats !== void 0 ? { recordStats: opts.recordStats } : {},
8845
9138
  stats: stats2
8846
9139
  },
8847
9140
  opts.storeDir
@@ -8913,6 +9206,7 @@ async function reduceExecutionWithRules(input, rules, opts = {}) {
8913
9206
  input: normalizedInput,
8914
9207
  rawText,
8915
9208
  classification,
9209
+ ...opts.recordStats !== void 0 ? { recordStats: opts.recordStats } : {},
8916
9210
  stats: stats2
8917
9211
  },
8918
9212
  opts.storeDir
@@ -8959,6 +9253,7 @@ async function reduceExecutionWithRules(input, rules, opts = {}) {
8959
9253
  input: normalizedInput,
8960
9254
  rawText,
8961
9255
  classification: jsonClassification,
9256
+ ...opts.recordStats !== void 0 ? { recordStats: opts.recordStats } : {},
8962
9257
  stats: stats2
8963
9258
  },
8964
9259
  opts.storeDir
@@ -9006,6 +9301,7 @@ async function reduceExecutionWithRules(input, rules, opts = {}) {
9006
9301
  input: normalizedInput,
9007
9302
  rawText,
9008
9303
  classification,
9304
+ ...opts.recordStats !== void 0 ? { recordStats: opts.recordStats } : {},
9009
9305
  stats
9010
9306
  },
9011
9307
  opts.storeDir
@@ -9118,7 +9414,7 @@ async function compactBashResult(input) {
9118
9414
  ...typeof input.cwd === "string" && input.cwd.trim() ? { cwd: input.cwd } : {},
9119
9415
  ...typeof input.maxInlineChars === "number" ? { maxInlineChars: input.maxInlineChars } : {},
9120
9416
  ...input.noOmit || !input.allowOmit && readNoOmissionFromEnv() ? { noOmit: true } : {},
9121
- recordStats: true,
9417
+ recordStats: input.recordStats ?? shouldRecordStats(),
9122
9418
  ...input.storeRaw ? { store: true } : {}
9123
9419
  };
9124
9420
  const result = await reduceExecution(executionInput, options);
@@ -9204,7 +9500,7 @@ function extractFullOutputPath(metadata) {
9204
9500
  async function loadFullOutputText(fullOutputPath) {
9205
9501
  let details;
9206
9502
  try {
9207
- details = await stat(fullOutputPath);
9503
+ details = await stat2(fullOutputPath);
9208
9504
  } catch (error) {
9209
9505
  throw new Error(
9210
9506
  `tokenjuice failed to stat bash full output file ${fullOutputPath}: ${formatErrorMessage(error)}`
@@ -9214,7 +9510,7 @@ async function loadFullOutputText(fullOutputPath) {
9214
9510
  return null;
9215
9511
  }
9216
9512
  try {
9217
- return await readFile3(fullOutputPath, "utf8");
9513
+ return await readFile4(fullOutputPath, "utf8");
9218
9514
  } catch (error) {
9219
9515
  throw new Error(
9220
9516
  `tokenjuice failed to read bash full output file ${fullOutputPath}: ${formatErrorMessage(error)}`