@agent-inspect/viewer 6.26.0 → 6.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1594,1639 +1594,1639 @@ function buildSessionIndex(inputRuns, options = {}) {
1594
1594
  };
1595
1595
  }
1596
1596
 
1597
- // packages/core/src/exporters/helpers.ts
1598
- function sortKeysDeep(input) {
1599
- if (input === null || typeof input !== "object") return input;
1600
- if (Array.isArray(input)) return input.map(sortKeysDeep);
1601
- const o = input;
1602
- const out = {};
1603
- for (const k of Object.keys(o).sort()) {
1604
- out[k] = sortKeysDeep(o[k]);
1597
+ // packages/core/src/diagnostics/programmatic.ts
1598
+ var PROGRAMMATIC_DIAGNOSTIC_SPECS = Object.freeze({
1599
+ AI_TRACE_INPUT_INVALID: {
1600
+ code: "AI_TRACE_INPUT_INVALID",
1601
+ summary: 'Expected { type: "file", path }, { type: "directory", path }, { type: "string", content }, { type: "buffer", content }, or { type: "stdin" }.',
1602
+ remediation: "For a file path, use openTraceFile(path).",
1603
+ relatedCodes: ["invalid_input"]
1604
+ },
1605
+ AI_TRACE_FORMAT_UNSUPPORTED: {
1606
+ code: "AI_TRACE_FORMAT_UNSUPPORTED",
1607
+ summary: "No trace reader could detect the input format.",
1608
+ remediation: "Pass an AgentInspect JSONL file via openTraceFile, or set options.format to a registered reader.",
1609
+ relatedCodes: ["unsupported_format"]
1610
+ },
1611
+ AI_TRACE_FORMAT_AMBIGUOUS: {
1612
+ code: "AI_TRACE_FORMAT_AMBIGUOUS",
1613
+ summary: "Multiple trace readers matched the input with equal confidence.",
1614
+ remediation: "Set options.format explicitly to disambiguate the reader.",
1615
+ relatedCodes: ["ambiguous_format"]
1616
+ },
1617
+ AI_TRACE_FACTS_INPUT_NOT_NORMALIZED: {
1618
+ code: "AI_TRACE_FACTS_INPUT_NOT_NORMALIZED",
1619
+ summary: "TraceFacts requires TraceReadResult or PersistedInspectEvent[].",
1620
+ remediation: "Use openTraceFile() to normalize a JSONL trace first."
1621
+ },
1622
+ AI_TRACE_CONTRACT_RUN_SELECTION_REQUIRED: {
1623
+ code: "AI_TRACE_CONTRACT_RUN_SELECTION_REQUIRED",
1624
+ summary: "Multiple runs are available; select a run before executing checks.",
1625
+ remediation: "Pass options.runId or TraceCheckInput.selectedRun.",
1626
+ relatedCodes: ["AI_CHECK_RUN_SELECTION_REQUIRED"]
1627
+ },
1628
+ AI_TRACE_RELATIONSHIP_SELF_PARENT: {
1629
+ code: "AI_TRACE_RELATIONSHIP_SELF_PARENT",
1630
+ summary: "A parentId equals its own event/step id.",
1631
+ remediation: "Reject at capture (AI_LANGGRAPH_SELF_PARENT_REJECTED) or drop via logical projection; do not invent replacement parents.",
1632
+ relatedCodes: [
1633
+ "AI_LANGGRAPH_SELF_PARENT_REJECTED",
1634
+ "AI_LOGICAL_SELF_PARENT_REMOVED"
1635
+ ]
1636
+ },
1637
+ AI_TRACE_RELATIONSHIP_CYCLE: {
1638
+ code: "AI_TRACE_RELATIONSHIP_CYCLE",
1639
+ summary: "Trace contains a parentId cycle.",
1640
+ remediation: "Use visibility-first tree linking for legacy fixtures; prefer acyclic capture for new adapter output.",
1641
+ relatedCodes: ["structure.cycle"]
1605
1642
  }
1606
- return out;
1643
+ });
1644
+ function formatProgrammaticDiagnostic(code, detail) {
1645
+ const spec = PROGRAMMATIC_DIAGNOSTIC_SPECS[code];
1646
+ const summary = detail?.trim() ? detail.trim() : spec.summary;
1647
+ return `${code}: ${summary} Remediation: ${spec.remediation}`;
1607
1648
  }
1608
- function stableJson(value, pretty) {
1609
- const sorted = sortKeysDeep(value);
1610
- return JSON.stringify(sorted);
1649
+
1650
+ // packages/core/src/safety/sensitive-key.ts
1651
+ function normalizeSensitiveKey(value) {
1652
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
1611
1653
  }
1654
+ new Set(
1655
+ [
1656
+ "tokens",
1657
+ "max_tokens",
1658
+ "min_tokens",
1659
+ "ls_max_tokens",
1660
+ "token_count",
1661
+ "token_limit",
1662
+ "token_budget",
1663
+ "input_tokens",
1664
+ "output_tokens",
1665
+ "total_tokens",
1666
+ "cached_tokens",
1667
+ "prompt_tokens",
1668
+ "completion_tokens"
1669
+ ].map(normalizeSensitiveKey)
1670
+ );
1612
1671
 
1613
- // packages/core/src/diff/comparable.ts
1614
- function extractOutputPreview(meta) {
1615
- if (meta === void 0) return void 0;
1616
- if ("outputPreview" in meta) return meta.outputPreview;
1617
- if ("resultPreview" in meta) return meta.resultPreview;
1672
+ // packages/core/src/checks/logical-events.ts
1673
+ function isRecord5(value) {
1674
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1675
+ }
1676
+ function legacyEvent(event) {
1677
+ const value = event.attributes?.legacyEvent;
1678
+ return typeof value === "string" ? value : void 0;
1679
+ }
1680
+ function stepIdOf(event) {
1681
+ const value = event.attributes?.stepId;
1682
+ if (typeof value === "string" && value.trim() !== "") return value;
1618
1683
  return void 0;
1619
1684
  }
1620
- function mapStepStatus(s) {
1621
- if (s === void 0) return "running";
1622
- return s;
1685
+ function cloneEvent(event) {
1686
+ return {
1687
+ ...event,
1688
+ ...event.attributes !== void 0 ? { attributes: { ...event.attributes } } : {},
1689
+ ...event.error !== void 0 ? { error: { ...event.error } } : {},
1690
+ ...event.tokenUsage !== void 0 ? { tokenUsage: { ...event.tokenUsage } } : {},
1691
+ ...event.source !== void 0 ? { source: { ...event.source } } : {}
1692
+ };
1623
1693
  }
1624
- function manualTraceEventsToComparableRun(events) {
1625
- const started = events.find((e) => e.event === "run_started");
1626
- if (!started || started.event !== "run_started") {
1627
- throw new Error("Invalid trace: missing run_started");
1628
- }
1629
- const rs = started;
1630
- const runId = rs.runId;
1631
- const completedAll = events.filter((e) => e.event === "run_completed");
1632
- const lastCompleted = completedAll[completedAll.length - 1];
1633
- let runStatus;
1634
- if (lastCompleted === void 0) runStatus = "running";
1635
- else runStatus = lastCompleted.status;
1636
- const durationMs = lastCompleted !== void 0 && Number.isFinite(lastCompleted.durationMs) ? lastCompleted.durationMs : void 0;
1637
- const steps = /* @__PURE__ */ new Map();
1638
- let order = 0;
1639
- for (const e of events) {
1640
- if (e.event !== "step_started") continue;
1641
- const s = e;
1642
- const meta = s.metadata ? { ...s.metadata } : void 0;
1643
- steps.set(s.stepId, {
1644
- id: s.stepId,
1645
- parentId: s.parentId,
1646
- name: s.name,
1647
- type: s.type,
1648
- order: order++,
1649
- timestamp: s.timestamp,
1650
- metadata: meta
1651
- });
1652
- }
1653
- for (const e of events) {
1654
- if (e.event !== "step_completed") continue;
1655
- const acc = steps.get(e.stepId);
1656
- if (!acc) continue;
1657
- acc.status = e.status;
1658
- acc.durationMs = e.durationMs;
1659
- if (e.error?.message) acc.errorMsg = e.error.message;
1660
- const extra = e;
1661
- if (extra.metadata !== void 0 && typeof extra.metadata === "object") {
1662
- acc.metadata = { ...acc.metadata ?? {}, ...extra.metadata };
1663
- }
1664
- }
1665
- const nodes = /* @__PURE__ */ new Map();
1666
- for (const acc of steps.values()) {
1667
- let meta = acc.metadata ? { ...acc.metadata } : void 0;
1668
- if (acc.parentId !== void 0 && !steps.has(acc.parentId)) {
1669
- meta = { ...meta ?? {}, agent_inspect_diff_parent_missing: true };
1670
- }
1671
- const outputPreview = extractOutputPreview(meta);
1672
- if (meta !== void 0 && ("outputPreview" in meta || "resultPreview" in meta)) {
1673
- delete meta.outputPreview;
1674
- delete meta.resultPreview;
1675
- }
1676
- const sc = {
1677
- id: acc.id,
1678
- name: acc.name,
1679
- type: acc.type,
1680
- status: mapStepStatus(acc.status),
1681
- durationMs: acc.durationMs,
1682
- error: acc.errorMsg,
1683
- metadata: meta && Object.keys(meta).length > 0 ? meta : void 0,
1684
- outputPreview,
1685
- children: []
1686
- };
1687
- nodes.set(acc.id, sc);
1688
- }
1689
- const roots = [];
1690
- const sortByOrder = (a, b) => {
1691
- const oa = steps.get(a.id)?.order ?? 0;
1692
- const ob = steps.get(b.id)?.order ?? 0;
1693
- return oa - ob;
1694
+ function mergeAttributes(start, complete) {
1695
+ const merged = {
1696
+ ...isRecord5(complete.attributes) ? complete.attributes : {},
1697
+ ...isRecord5(start.attributes) ? start.attributes : {}
1694
1698
  };
1695
- for (const acc of steps.values()) {
1696
- const node = nodes.get(acc.id);
1697
- if (acc.parentId !== void 0 && nodes.has(acc.parentId)) {
1698
- nodes.get(acc.parentId).children.push(node);
1699
- } else {
1700
- roots.push(node);
1701
- }
1702
- }
1703
- roots.sort(sortByOrder);
1704
- for (const n of nodes.values()) {
1705
- n.children.sort(sortByOrder);
1699
+ merged.legacyEvent = start.attributes?.legacyEvent ?? complete.attributes?.legacyEvent;
1700
+ merged.legacyCompleteEvent = complete.attributes?.legacyEvent;
1701
+ if (complete.attributes?.errorStack !== void 0) {
1702
+ merged.errorStack = complete.attributes.errorStack;
1706
1703
  }
1704
+ return Object.keys(merged).length > 0 ? merged : void 0;
1705
+ }
1706
+ function pairStartComplete(start, complete) {
1707
+ const attributes = mergeAttributes(start, complete);
1708
+ const paired = {
1709
+ ...cloneEvent(start),
1710
+ status: complete.status,
1711
+ timestamp: complete.timestamp ?? start.timestamp,
1712
+ ...complete.endedAt !== void 0 ? { endedAt: complete.endedAt } : {},
1713
+ ...complete.durationMs !== void 0 ? { durationMs: complete.durationMs } : {},
1714
+ ...complete.error !== void 0 ? { error: { ...complete.error } } : {},
1715
+ ...complete.tokenUsage !== void 0 && start.tokenUsage === void 0 ? { tokenUsage: { ...complete.tokenUsage } } : {},
1716
+ ...attributes !== void 0 ? { attributes } : {}
1717
+ };
1707
1718
  return {
1708
- runId,
1709
- name: rs.name,
1710
- status: runStatus,
1711
- durationMs,
1712
- steps: roots
1719
+ ...paired,
1720
+ sourceEventIds: Object.freeze([start.eventId, complete.eventId]),
1721
+ projection: {
1722
+ paired: true,
1723
+ absorbedEventIds: Object.freeze([complete.eventId]),
1724
+ parentNormalized: false,
1725
+ ...start.parentId !== void 0 ? { originalParentId: start.parentId } : {}
1726
+ }
1713
1727
  };
1714
1728
  }
1715
-
1716
- // packages/core/src/diff/engine.ts
1717
- var DEFAULT_THRESHOLD_MS = 0;
1718
- function pathSeg(step, index) {
1719
- return { index, name: step.name, stepId: step.id };
1720
- }
1721
- function buildPath(segments) {
1722
- return { path: [...segments] };
1723
- }
1724
- function pairSteps(left, right) {
1725
- const usedRight = /* @__PURE__ */ new Set();
1726
- const pairs = [];
1727
- for (let i = 0; i < left.length; i++) {
1728
- const L = left[i];
1729
- let R = right.find((r) => !usedRight.has(r.id) && r.id === L.id);
1730
- if (R === void 0 && i < right.length && !usedRight.has(right[i].id)) {
1731
- const cand = right[i];
1732
- if (cand.name === L.name && (cand.type ?? "") === (L.type ?? "")) {
1733
- R = cand;
1734
- }
1729
+ function asLogical(event, extras) {
1730
+ return {
1731
+ ...cloneEvent(event),
1732
+ sourceEventIds: Object.freeze([event.eventId]),
1733
+ projection: {
1734
+ paired: false,
1735
+ absorbedEventIds: Object.freeze([]),
1736
+ parentNormalized: extras?.parentNormalized === true,
1737
+ ...{}
1735
1738
  }
1736
- if (R === void 0) {
1737
- R = right.find(
1738
- (r) => !usedRight.has(r.id) && r.name === L.name && (r.type ?? "") === (L.type ?? "")
1739
- );
1739
+ };
1740
+ }
1741
+ function projectLogicalEvents(events) {
1742
+ const diagnostics = [];
1743
+ const byRun = /* @__PURE__ */ new Map();
1744
+ for (const event of events) {
1745
+ const list = byRun.get(event.runId) ?? [];
1746
+ list.push(event);
1747
+ byRun.set(event.runId, list);
1748
+ }
1749
+ const absorbedIds = /* @__PURE__ */ new Set();
1750
+ const logicalByRawId = /* @__PURE__ */ new Map();
1751
+ const stepIdToLogicalId = /* @__PURE__ */ new Map();
1752
+ const logical = [];
1753
+ const orderedRuns = [...byRun.keys()].sort((a, b) => a.localeCompare(b));
1754
+ for (const runId of orderedRuns) {
1755
+ const runEvents = byRun.get(runId) ?? [];
1756
+ const starts = [];
1757
+ const completes = [];
1758
+ const others = [];
1759
+ for (const event of runEvents) {
1760
+ const legacy = legacyEvent(event);
1761
+ if (legacy === "step_started" || legacy === "run_started" && event.status === "running") {
1762
+ starts.push(event);
1763
+ } else if (legacy === "step_completed" || legacy === "run_completed") {
1764
+ completes.push(event);
1765
+ } else {
1766
+ others.push(event);
1767
+ }
1740
1768
  }
1741
- if (R !== void 0) {
1742
- usedRight.add(R.id);
1743
- pairs.push([L, R]);
1744
- } else {
1745
- pairs.push([L, void 0]);
1769
+ const usedCompletes = /* @__PURE__ */ new Set();
1770
+ for (const start of starts) {
1771
+ const stepId = stepIdOf(start);
1772
+ let match;
1773
+ if (legacyEvent(start) === "run_started") {
1774
+ const candidates = completes.filter(
1775
+ (c) => !usedCompletes.has(c.eventId) && legacyEvent(c) === "run_completed"
1776
+ );
1777
+ if (candidates.length > 1) {
1778
+ diagnostics.push({
1779
+ code: "AI_LOGICAL_PAIR_AMBIGUOUS",
1780
+ message: `Multiple run_completed rows for run ${runId}; using first by eventId.`,
1781
+ eventIds: candidates.map((c) => c.eventId)
1782
+ });
1783
+ candidates.sort((a, b) => a.eventId.localeCompare(b.eventId));
1784
+ }
1785
+ match = candidates[0];
1786
+ } else if (stepId) {
1787
+ const candidates = completes.filter(
1788
+ (c) => !usedCompletes.has(c.eventId) && legacyEvent(c) === "step_completed" && stepIdOf(c) === stepId
1789
+ );
1790
+ if (candidates.length > 1) {
1791
+ diagnostics.push({
1792
+ code: "AI_LOGICAL_PAIR_AMBIGUOUS",
1793
+ message: `Multiple step_completed rows for stepId ${stepId}; using first by eventId.`,
1794
+ eventIds: candidates.map((c) => c.eventId)
1795
+ });
1796
+ candidates.sort((a, b) => a.eventId.localeCompare(b.eventId));
1797
+ }
1798
+ match = candidates[0];
1799
+ }
1800
+ if (match) {
1801
+ usedCompletes.add(match.eventId);
1802
+ absorbedIds.add(match.eventId);
1803
+ const paired = pairStartComplete(start, match);
1804
+ logical.push(paired);
1805
+ logicalByRawId.set(start.eventId, paired);
1806
+ logicalByRawId.set(match.eventId, paired);
1807
+ if (stepId) stepIdToLogicalId.set(`${runId}:${stepId}`, paired.eventId);
1808
+ } else {
1809
+ diagnostics.push({
1810
+ code: "AI_LOGICAL_PAIR_UNMATCHED_START",
1811
+ message: `No matching complete for start ${start.eventId}.`,
1812
+ eventIds: [start.eventId]
1813
+ });
1814
+ const alone = asLogical(start);
1815
+ logical.push(alone);
1816
+ logicalByRawId.set(start.eventId, alone);
1817
+ if (stepId) stepIdToLogicalId.set(`${runId}:${stepId}`, alone.eventId);
1818
+ }
1746
1819
  }
1747
- }
1748
- for (const R of right) {
1749
- if (!usedRight.has(R.id)) {
1750
- pairs.push([void 0, R]);
1820
+ for (const complete of completes) {
1821
+ if (usedCompletes.has(complete.eventId)) continue;
1822
+ diagnostics.push({
1823
+ code: "AI_LOGICAL_PAIR_UNMATCHED_COMPLETE",
1824
+ message: `No matching start for complete ${complete.eventId}.`,
1825
+ eventIds: [complete.eventId]
1826
+ });
1827
+ const alone = asLogical(complete);
1828
+ logical.push(alone);
1829
+ logicalByRawId.set(complete.eventId, alone);
1830
+ const stepId = stepIdOf(complete);
1831
+ if (stepId && !stepIdToLogicalId.has(`${runId}:${stepId}`)) {
1832
+ stepIdToLogicalId.set(`${runId}:${stepId}`, alone.eventId);
1833
+ }
1834
+ }
1835
+ for (const event of others) {
1836
+ const alone = asLogical(event);
1837
+ logical.push(alone);
1838
+ logicalByRawId.set(event.eventId, alone);
1839
+ const stepId = stepIdOf(event);
1840
+ if (stepId && !stepIdToLogicalId.has(`${runId}:${stepId}`)) {
1841
+ stepIdToLogicalId.set(`${runId}:${stepId}`, alone.eventId);
1842
+ }
1751
1843
  }
1752
1844
  }
1753
- return pairs;
1754
- }
1755
- function compareLeafSteps(L, R, segments, opts, out) {
1756
- const path18 = buildPath(segments);
1757
- if (L.name !== R.name) {
1758
- out.push({
1759
- kind: "structure",
1760
- severity: "warning",
1761
- message: "Step name differs",
1762
- path: path18,
1763
- left: L.name,
1764
- right: R.name
1845
+ const logicalById = new Map(logical.map((e) => [e.eventId, e]));
1846
+ const normalized = [];
1847
+ for (const event of logical) {
1848
+ const originalParentId = event.parentId;
1849
+ if (!originalParentId) {
1850
+ normalized.push(event);
1851
+ continue;
1852
+ }
1853
+ let nextParent = originalParentId;
1854
+ let remapped = false;
1855
+ const viaAbsorbed = logicalByRawId.get(originalParentId);
1856
+ if (viaAbsorbed && viaAbsorbed.eventId !== originalParentId) {
1857
+ nextParent = viaAbsorbed.eventId;
1858
+ remapped = true;
1859
+ } else if (!logicalById.has(originalParentId)) {
1860
+ const viaStep = stepIdToLogicalId.get(`${event.runId}:${originalParentId}`);
1861
+ if (viaStep) {
1862
+ nextParent = viaStep;
1863
+ remapped = true;
1864
+ }
1865
+ }
1866
+ if (!remapped) {
1867
+ if (originalParentId === event.eventId) {
1868
+ diagnostics.push({
1869
+ code: "AI_LOGICAL_SELF_PARENT_REMOVED",
1870
+ message: formatProgrammaticDiagnostic(
1871
+ "AI_TRACE_RELATIONSHIP_SELF_PARENT",
1872
+ `Removed self-parent edge on ${event.eventId}.`
1873
+ ),
1874
+ eventIds: [event.eventId]
1875
+ });
1876
+ const { parentId: _drop, ...rest } = event;
1877
+ normalized.push({
1878
+ ...rest,
1879
+ projection: {
1880
+ ...event.projection,
1881
+ parentNormalized: true,
1882
+ originalParentId
1883
+ }
1884
+ });
1885
+ continue;
1886
+ }
1887
+ if (!logicalById.has(originalParentId) && !logicalByRawId.has(originalParentId)) {
1888
+ const mapping = event.attributes?.parentMapping;
1889
+ const unresolved = mapping === "unresolved" || event.attributes?.parentUnresolved === true || event.attributes?.unresolvedParent === true || // LangGraph/framework scaffolding sentinel labels are not event ids.
1890
+ /^LangGraph$/i.test(originalParentId) || originalParentId.startsWith("unresolved:");
1891
+ if (!unresolved) {
1892
+ diagnostics.push({
1893
+ code: "AI_LOGICAL_PARENT_UNRESOLVED",
1894
+ message: `Parent ${originalParentId} unresolved for ${event.eventId}.`,
1895
+ eventIds: [event.eventId]
1896
+ });
1897
+ }
1898
+ }
1899
+ normalized.push(event);
1900
+ continue;
1901
+ }
1902
+ if (nextParent === event.eventId) {
1903
+ diagnostics.push({
1904
+ code: "AI_LOGICAL_SELF_PARENT_REMOVED",
1905
+ message: formatProgrammaticDiagnostic(
1906
+ "AI_TRACE_RELATIONSHIP_SELF_PARENT",
1907
+ `Removed self-parent edge on ${event.eventId} (was ${originalParentId}).`
1908
+ ),
1909
+ eventIds: [event.eventId]
1910
+ });
1911
+ const { parentId: _drop, ...rest } = event;
1912
+ normalized.push({
1913
+ ...rest,
1914
+ projection: {
1915
+ ...event.projection,
1916
+ parentNormalized: true,
1917
+ originalParentId
1918
+ }
1919
+ });
1920
+ continue;
1921
+ }
1922
+ diagnostics.push({
1923
+ code: "AI_LOGICAL_PARENT_REMAPPED",
1924
+ message: `Remapped parent ${originalParentId} \u2192 ${nextParent} for ${event.eventId}.`,
1925
+ eventIds: [event.eventId]
1765
1926
  });
1766
- }
1767
- if ((L.type ?? "") !== (R.type ?? "")) {
1768
- out.push({
1769
- kind: "step-type",
1770
- severity: "warning",
1771
- message: "Step type differs",
1772
- path: path18,
1773
- left: L.type,
1774
- right: R.type
1927
+ normalized.push({
1928
+ ...event,
1929
+ parentId: nextParent,
1930
+ projection: {
1931
+ ...event.projection,
1932
+ parentNormalized: true,
1933
+ originalParentId
1934
+ }
1775
1935
  });
1776
1936
  }
1777
- if ((L.status ?? "") !== (R.status ?? "")) {
1778
- out.push({
1779
- kind: "step-status",
1780
- severity: "warning",
1781
- message: "Step status differs",
1782
- path: path18,
1783
- left: L.status,
1784
- right: R.status
1785
- });
1937
+ const rawIndex = new Map(events.map((e, i) => [e.eventId, i]));
1938
+ normalized.sort((a, b) => {
1939
+ const ai = rawIndex.get(a.sourceEventIds[0]) ?? 0;
1940
+ const bi = rawIndex.get(b.sourceEventIds[0]) ?? 0;
1941
+ return ai - bi || a.eventId.localeCompare(b.eventId);
1942
+ });
1943
+ return {
1944
+ logicalEvents: Object.freeze(normalized),
1945
+ diagnostics: Object.freeze(diagnostics)
1946
+ };
1947
+ }
1948
+ function resolveCanonicalToolName(event) {
1949
+ const attrs = event.attributes;
1950
+ const direct = pickString(attrs, ["toolName", "tool"]);
1951
+ if (direct) return direct;
1952
+ const metadata = attrs?.metadata;
1953
+ if (isRecord5(metadata)) {
1954
+ const nested = pickString(metadata, ["toolName", "tool"]);
1955
+ if (nested) return nested;
1786
1956
  }
1787
- const le = L.error ?? "";
1788
- const re = R.error ?? "";
1789
- if (le !== re) {
1790
- out.push({
1791
- kind: "error",
1792
- severity: "error",
1793
- message: "Step error message differs",
1794
- path: path18,
1795
- left: le || void 0,
1796
- right: re || void 0
1797
- });
1798
- }
1799
- if (!opts.ignoreDuration) {
1800
- const ld = L.durationMs;
1801
- const rd = R.durationMs;
1802
- const th = opts.durationThresholdMs;
1803
- let differs = false;
1804
- if (ld === void 0 && rd === void 0) differs = false;
1805
- else if (ld === void 0 || rd === void 0) differs = true;
1806
- else differs = Math.abs(ld - rd) > th;
1807
- if (differs) {
1808
- out.push({
1809
- kind: "duration",
1810
- severity: "info",
1811
- message: "Step duration differs",
1812
- path: path18,
1813
- left: ld,
1814
- right: rd
1815
- });
1816
- }
1817
- }
1818
- const lm = stableJson(L.metadata ?? {});
1819
- const rm2 = stableJson(R.metadata ?? {});
1820
- if (lm !== rm2) {
1821
- out.push({
1822
- kind: "metadata",
1823
- severity: "info",
1824
- message: "Step metadata differs",
1825
- path: path18,
1826
- left: L.metadata,
1827
- right: R.metadata
1828
- });
1829
- }
1830
- const lo = stableJson(L.outputPreview ?? null);
1831
- const ro = stableJson(R.outputPreview ?? null);
1832
- if (lo !== ro) {
1833
- out.push({
1834
- kind: "output",
1835
- severity: "info",
1836
- message: "Output preview differs",
1837
- path: path18,
1838
- left: L.outputPreview,
1839
- right: R.outputPreview
1840
- });
1957
+ for (const prefix of ["tool:", "function:", "mcp-tools:"]) {
1958
+ if (event.name.startsWith(prefix)) return event.name.slice(prefix.length);
1841
1959
  }
1960
+ return event.name;
1842
1961
  }
1843
- function compareRecursive(L, R, segments, opts, out) {
1844
- compareLeafSteps(L, R, segments, opts, out);
1845
- const pairs = pairSteps(L.children, R.children);
1846
- let ci = 0;
1847
- for (const [lch, rch] of pairs) {
1848
- if (lch !== void 0 && rch !== void 0) {
1849
- compareRecursive(lch, rch, [...segments, pathSeg(lch, ci)], opts, out);
1850
- } else if (lch !== void 0) {
1851
- out.push({
1852
- kind: "step-removed",
1853
- severity: "warning",
1854
- message: `Step only in left run: ${lch.name}`,
1855
- path: buildPath([...segments, pathSeg(lch, ci)]),
1856
- left: lch.id,
1857
- right: void 0
1858
- });
1859
- } else if (rch !== void 0) {
1860
- out.push({
1861
- kind: "step-added",
1862
- severity: "warning",
1863
- message: `Step only in right run: ${rch.name}`,
1864
- path: buildPath([...segments, pathSeg(rch, ci)]),
1865
- left: void 0,
1866
- right: rch.id
1867
- });
1868
- }
1869
- ci += 1;
1962
+ function pickString(record, keys) {
1963
+ if (!record) return void 0;
1964
+ for (const key of keys) {
1965
+ const value = record[key];
1966
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
1870
1967
  }
1968
+ return void 0;
1871
1969
  }
1872
- function mergeDiffDefaults(options) {
1970
+
1971
+ // packages/core/src/checks/trace-facts.ts
1972
+ formatProgrammaticDiagnostic(
1973
+ "AI_TRACE_FACTS_INPUT_NOT_NORMALIZED"
1974
+ );
1975
+
1976
+ // packages/core/src/checks/index.ts
1977
+ var SEVERITY_RANK = {
1978
+ error: 0,
1979
+ warning: 1,
1980
+ info: 2
1981
+ };
1982
+ var STATUS_RANK = {
1983
+ fail: 0,
1984
+ warning: 1,
1985
+ pass: 2
1986
+ };
1987
+ function compareStrings(a, b) {
1988
+ return (a ?? "").localeCompare(b ?? "");
1989
+ }
1990
+ function diagnostic(code, message, ruleId) {
1873
1991
  return {
1874
- ignoreDuration: false,
1875
- durationThresholdMs: DEFAULT_THRESHOLD_MS,
1876
- focus: "all",
1877
- check: "all"
1992
+ code,
1993
+ message,
1994
+ severity: "error",
1995
+ ...ruleId ? { ruleId } : {}
1878
1996
  };
1879
1997
  }
1880
- function kindMatchesFilter(kind, merged) {
1881
- return true;
1998
+ function emptySummary() {
1999
+ return {
2000
+ passed: 0,
2001
+ failed: 0,
2002
+ warnings: 0,
2003
+ errors: 0,
2004
+ rulesEvaluated: 0
2005
+ };
1882
2006
  }
1883
- function diffRuns(left, right, options) {
1884
- const merged = mergeDiffDefaults();
1885
- const opts = {
1886
- ignoreDuration: merged.ignoreDuration,
1887
- durationThresholdMs: merged.durationThresholdMs
2007
+ function errorResult(input, diagnostics, selectedRun, ruleExecutions = []) {
2008
+ return {
2009
+ ok: false,
2010
+ status: "error",
2011
+ format: input.read.format,
2012
+ ...selectedRun ? { runId: selectedRun.runId } : {},
2013
+ summary: {
2014
+ ...emptySummary(),
2015
+ errors: diagnostics.filter((item) => item.severity === "error").length,
2016
+ rulesEvaluated: ruleExecutions.length
2017
+ },
2018
+ findings: [],
2019
+ diagnostics: [...diagnostics],
2020
+ ruleExecutions: [...ruleExecutions]
1888
2021
  };
1889
- const raw = [];
1890
- if ((left.status ?? "") !== (right.status ?? "")) {
1891
- raw.push({
1892
- kind: "run-status",
1893
- severity: "warning",
1894
- message: "Run completion status differs",
1895
- left: left.status,
1896
- right: right.status
1897
- });
2022
+ }
2023
+ function flattenNodes(nodes) {
2024
+ return nodes.flatMap((node) => [node, ...flattenNodes(node.children)]);
2025
+ }
2026
+ function buildFacts(input, selectedRun) {
2027
+ const scopedRuns = selectedRun ? [selectedRun] : input.read.runs;
2028
+ const scopedRunIds = new Set(scopedRuns.map((run) => run.runId));
2029
+ const scopedEvents = selectedRun === void 0 ? input.read.events : input.read.events.filter((event) => scopedRunIds.has(event.runId));
2030
+ const nodes = flattenNodes(scopedRuns.flatMap((run) => run.children));
2031
+ const nodesByEventId = /* @__PURE__ */ new Map();
2032
+ const childrenByParentId = /* @__PURE__ */ new Map();
2033
+ for (const node of nodes) {
2034
+ nodesByEventId.set(node.event.eventId, node);
2035
+ const parentId = node.event.parentId;
2036
+ if (parentId) {
2037
+ const children = childrenByParentId.get(parentId) ?? [];
2038
+ children.push(node);
2039
+ childrenByParentId.set(parentId, children);
2040
+ }
1898
2041
  }
1899
- {
1900
- const ld = left.durationMs;
1901
- const rd = right.durationMs;
1902
- const th = merged.durationThresholdMs;
1903
- let differs = false;
1904
- if (ld === void 0 && rd === void 0) differs = false;
1905
- else if (ld === void 0 || rd === void 0) differs = true;
1906
- else differs = Math.abs(ld - rd) > th;
1907
- if (differs) {
1908
- raw.push({
1909
- kind: "duration",
1910
- severity: "info",
1911
- message: "Run duration differs",
1912
- left: ld,
1913
- right: rd
1914
- });
2042
+ const projection = projectLogicalEvents(scopedEvents);
2043
+ return {
2044
+ format: input.read.format,
2045
+ runs: Object.freeze([...input.read.runs]),
2046
+ events: Object.freeze([...scopedEvents]),
2047
+ logicalEvents: projection.logicalEvents,
2048
+ logicalProjectionDiagnostics: projection.diagnostics,
2049
+ readerWarnings: Object.freeze([...input.read.warnings]),
2050
+ unsupportedFields: Object.freeze([...input.read.unsupportedFields]),
2051
+ sourceFiles: Object.freeze([...input.read.sourceFiles]),
2052
+ nodesByEventId,
2053
+ childrenByParentId,
2054
+ rootNodes: Object.freeze(scopedRuns.flatMap((run) => run.children))
2055
+ };
2056
+ }
2057
+ function resolveSelectedRun(input, runId) {
2058
+ if (input.selectedRun) {
2059
+ if (runId && input.selectedRun.runId !== runId) {
2060
+ return {
2061
+ diagnostics: [
2062
+ diagnostic(
2063
+ "AI_CHECK_INVALID_ARGUMENTS",
2064
+ `Selected run ${input.selectedRun.runId} does not match requested run ${runId}.`
2065
+ )
2066
+ ]
2067
+ };
1915
2068
  }
2069
+ return { run: input.selectedRun, diagnostics: [] };
1916
2070
  }
1917
- const pairs = pairSteps(left.steps, right.steps);
1918
- let idx = 0;
1919
- for (const [ls, rs] of pairs) {
1920
- if (ls !== void 0 && rs !== void 0) {
1921
- compareRecursive(ls, rs, [pathSeg(ls, idx)], opts, raw);
1922
- idx += 1;
1923
- } else if (ls !== void 0) {
1924
- raw.push({
1925
- kind: "step-removed",
1926
- severity: "warning",
1927
- message: `Step only in left run: ${ls.name}`,
1928
- path: buildPath([pathSeg(ls, idx)]),
1929
- left: ls.id,
1930
- right: void 0
1931
- });
1932
- idx += 1;
1933
- } else if (rs !== void 0) {
1934
- raw.push({
1935
- kind: "step-added",
1936
- severity: "warning",
1937
- message: `Step only in right run: ${rs.name}`,
1938
- path: buildPath([pathSeg(rs, idx)]),
1939
- left: void 0,
1940
- right: rs.id
1941
- });
1942
- idx += 1;
2071
+ if (runId) {
2072
+ const run = input.read.runs.find((candidate) => candidate.runId === runId);
2073
+ if (!run) {
2074
+ return {
2075
+ diagnostics: [
2076
+ diagnostic("AI_CHECK_RUN_SELECTION_REQUIRED", `Run not found: ${runId}.`)
2077
+ ]
2078
+ };
1943
2079
  }
2080
+ return { run, diagnostics: [] };
1944
2081
  }
1945
- const differences = raw.filter((d) => kindMatchesFilter(d.kind));
1946
- let errors = 0;
1947
- let warnings = 0;
1948
- let info = 0;
1949
- for (const d of differences) {
1950
- if (d.severity === "error") errors += 1;
1951
- else if (d.severity === "warning") warnings += 1;
1952
- else info += 1;
1953
- }
1954
- const firstVisible = differences[0];
1955
- const firstDivergence = firstVisible !== void 0 ? {
1956
- kind: "first-divergence",
1957
- severity: firstVisible.severity,
1958
- message: `First divergence: ${firstVisible.message}`,
1959
- path: firstVisible.path,
1960
- left: firstVisible.left,
1961
- right: firstVisible.right
1962
- } : void 0;
1963
- const summary = {
1964
- leftRunId: left.runId,
1965
- rightRunId: right.runId,
1966
- totalDifferences: differences.length,
1967
- errors,
1968
- warnings,
1969
- info,
1970
- firstDivergence
1971
- };
1972
- return { summary, differences };
1973
- }
1974
-
1975
- // packages/core/src/evidence/zip.ts
1976
- (() => {
1977
- const table = new Uint32Array(256);
1978
- for (let n = 0; n < 256; n += 1) {
1979
- let c = n;
1980
- for (let k = 0; k < 8; k += 1) {
1981
- c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
1982
- }
1983
- table[n] = c >>> 0;
1984
- }
1985
- return table;
1986
- })();
1987
-
1988
- // packages/core/src/suite/types.ts
1989
- var DEFAULT_SUITE_CONFIG_NAMES = [
1990
- "agent-inspect.suite.json",
1991
- "agent-inspect.suite.js",
1992
- "agent-inspect.suite.mjs",
1993
- "agent-inspect.suite.cjs"
1994
- ];
1995
- function diagnostic(code, message, severity = "error", caseId) {
1996
- return { code, message, severity, ...{} };
1997
- }
1998
- function asString(value, label) {
1999
- if (value === void 0) return void 0;
2000
- if (typeof value !== "string" || value.trim() === "") {
2001
- throw new Error(`${label} must be a non-empty string.`);
2002
- }
2003
- return value.trim();
2004
- }
2005
- function asStringArray(value, label) {
2006
- if (value === void 0) return void 0;
2007
- if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
2008
- throw new Error(`${label} must be an array of strings.`);
2082
+ if (input.read.runs.length === 1) {
2083
+ return { run: input.read.runs[0], diagnostics: [] };
2009
2084
  }
2010
- return value;
2011
- }
2012
- function asPositiveNumber(value, label) {
2013
- if (value === void 0) return void 0;
2014
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
2015
- throw new Error(`${label} must be a non-negative number.`);
2085
+ if (input.read.runs.length === 0) {
2086
+ return {
2087
+ diagnostics: [
2088
+ diagnostic(
2089
+ "AI_CHECK_RUN_SELECTION_REQUIRED",
2090
+ formatProgrammaticDiagnostic(
2091
+ "AI_TRACE_CONTRACT_RUN_SELECTION_REQUIRED",
2092
+ "No runs are available for checks."
2093
+ )
2094
+ )
2095
+ ]
2096
+ };
2016
2097
  }
2017
- return value;
2098
+ return {
2099
+ diagnostics: [
2100
+ diagnostic(
2101
+ "AI_CHECK_RUN_SELECTION_REQUIRED",
2102
+ formatProgrammaticDiagnostic("AI_TRACE_CONTRACT_RUN_SELECTION_REQUIRED")
2103
+ )
2104
+ ]
2105
+ };
2018
2106
  }
2019
- function validateCaseConfig(value, index) {
2107
+ function selectRules(rules, selectedIds) {
2020
2108
  const diagnostics = [];
2021
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
2022
- diagnostics.push(
2023
- diagnostic("AI_SUITE_CONFIG_INVALID", `cases[${index}] must be an object.`)
2024
- );
2025
- return { diagnostics };
2026
- }
2027
- const raw = value;
2028
- try {
2029
- const id = asString(raw.id, `cases[${index}].id`);
2030
- if (id === void 0) {
2109
+ const byId = /* @__PURE__ */ new Map();
2110
+ for (const rule of rules) {
2111
+ if (byId.has(rule.id)) {
2031
2112
  diagnostics.push(
2032
- diagnostic("AI_SUITE_CONFIG_INVALID", `cases[${index}].id is required.`)
2113
+ diagnostic("AI_CHECK_INVALID_CONFIG", `Duplicate trace check rule id: ${rule.id}.`, rule.id)
2033
2114
  );
2034
- return { diagnostics };
2115
+ continue;
2116
+ }
2117
+ byId.set(rule.id, rule);
2118
+ }
2119
+ if (selectedIds && selectedIds.length > 0) {
2120
+ const selected = new Set(selectedIds);
2121
+ for (const id of selected) {
2122
+ if (!byId.has(id)) {
2123
+ diagnostics.push(
2124
+ diagnostic("AI_CHECK_INVALID_CONFIG", `Unknown trace check rule id: ${id}.`, id)
2125
+ );
2126
+ }
2035
2127
  }
2036
- const trace = asString(raw.trace, `cases[${index}].trace`);
2037
- const runId = asString(raw.runId, `cases[${index}].runId`);
2038
- const input = asString(raw.input, `cases[${index}].input`);
2039
2128
  return {
2040
- caseConfig: {
2041
- id,
2042
- ...trace !== void 0 ? { trace } : {},
2043
- ...runId !== void 0 ? { runId } : {},
2044
- ...input !== void 0 ? { input } : {},
2045
- ...asStringArray(raw.requireTools, `cases[${index}].requireTools`) !== void 0 ? { requireTools: asStringArray(raw.requireTools, `cases[${index}].requireTools`) } : {},
2046
- ...asStringArray(raw.forbidTools, `cases[${index}].forbidTools`) !== void 0 ? { forbidTools: asStringArray(raw.forbidTools, `cases[${index}].forbidTools`) } : {},
2047
- ...asPositiveNumber(raw.maxDurationMs, `cases[${index}].maxDurationMs`) !== void 0 ? {
2048
- maxDurationMs: asPositiveNumber(
2049
- raw.maxDurationMs,
2050
- `cases[${index}].maxDurationMs`
2051
- )
2052
- } : {},
2053
- ...asStringArray(
2054
- raw.expectedObservations,
2055
- `cases[${index}].expectedObservations`
2056
- ) !== void 0 ? {
2057
- expectedObservations: asStringArray(
2058
- raw.expectedObservations,
2059
- `cases[${index}].expectedObservations`
2060
- )
2061
- } : {}
2062
- },
2129
+ rules: [...byId.values()].filter((rule) => selected.has(rule.id)).sort(compareRules),
2063
2130
  diagnostics
2064
2131
  };
2065
- } catch (error) {
2066
- const message = error instanceof Error ? error.message : String(error);
2067
- diagnostics.push(diagnostic("AI_SUITE_CONFIG_INVALID", message));
2068
- return { diagnostics };
2069
2132
  }
2133
+ return { rules: [...byId.values()].sort(compareRules), diagnostics };
2070
2134
  }
2071
- function normalizeSuiteConfig(value) {
2072
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
2073
- throw new Error("Suite config must export an object.");
2074
- }
2075
- const raw = value;
2076
- const name = asString(raw.name, "name");
2077
- const traces = asString(raw.traces, "traces");
2078
- if (name === void 0) throw new Error("name is required.");
2079
- if (traces === void 0) throw new Error("traces is required.");
2080
- if (!Array.isArray(raw.cases) || raw.cases.length === 0) {
2081
- throw new Error("cases must be a non-empty array.");
2082
- }
2083
- const cases = [];
2084
- for (let index = 0; index < raw.cases.length; index += 1) {
2085
- const { caseConfig, diagnostics } = validateCaseConfig(raw.cases[index], index);
2086
- if (diagnostics.length > 0) {
2087
- throw new Error(diagnostics.map((item) => item.message).join("; "));
2135
+ function compareRules(a, b) {
2136
+ return a.id.localeCompare(b.id);
2137
+ }
2138
+ function eventTimestamp(finding, eventById) {
2139
+ const eventId = finding.evidence[0]?.eventId;
2140
+ return eventId ? eventById.get(eventId)?.timestamp ?? "" : "";
2141
+ }
2142
+ function compareFindings(eventById) {
2143
+ return (a, b) => {
2144
+ if (SEVERITY_RANK[a.severity] !== SEVERITY_RANK[b.severity]) {
2145
+ return SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity];
2088
2146
  }
2089
- if (caseConfig !== void 0) cases.push(caseConfig);
2090
- }
2091
- const ids = /* @__PURE__ */ new Set();
2092
- for (const suiteCase of cases) {
2093
- if (ids.has(suiteCase.id)) {
2094
- throw new Error(`Duplicate case id "${suiteCase.id}".`);
2147
+ const byRule = a.ruleId.localeCompare(b.ruleId);
2148
+ if (byRule !== 0) return byRule;
2149
+ if (STATUS_RANK[a.status] !== STATUS_RANK[b.status]) {
2150
+ return STATUS_RANK[a.status] - STATUS_RANK[b.status];
2095
2151
  }
2096
- ids.add(suiteCase.id);
2152
+ const byRun = compareStrings(a.evidence[0]?.runId, b.evidence[0]?.runId);
2153
+ if (byRun !== 0) return byRun;
2154
+ const byTime = eventTimestamp(a, eventById).localeCompare(eventTimestamp(b, eventById));
2155
+ if (byTime !== 0) return byTime;
2156
+ const byEvent = compareStrings(a.evidence[0]?.eventId, b.evidence[0]?.eventId);
2157
+ if (byEvent !== 0) return byEvent;
2158
+ return compareStrings(a.evidence[0]?.path, b.evidence[0]?.path);
2159
+ };
2160
+ }
2161
+ function normalizeFinding(rule, finding) {
2162
+ return {
2163
+ ruleId: finding.ruleId || rule.id,
2164
+ severity: finding.severity ?? rule.defaultSeverity,
2165
+ status: finding.status,
2166
+ message: finding.message,
2167
+ ...finding.expected !== void 0 ? { expected: finding.expected } : {},
2168
+ ...finding.actual !== void 0 ? { actual: finding.actual } : {},
2169
+ evidence: [...finding.evidence ?? []],
2170
+ ...finding.category !== void 0 ? { category: finding.category } : {},
2171
+ ...finding.confidence !== void 0 ? { confidence: finding.confidence } : {},
2172
+ ...finding.detector !== void 0 ? { detector: finding.detector } : {},
2173
+ ...finding.action !== void 0 ? { action: finding.action } : {}
2174
+ };
2175
+ }
2176
+ function summarize(findings, diagnostics, rulesEvaluated) {
2177
+ return {
2178
+ passed: findings.filter((finding) => finding.status === "pass").length,
2179
+ failed: findings.filter(
2180
+ (finding) => finding.status === "fail" && finding.severity === "error"
2181
+ ).length,
2182
+ warnings: findings.filter(
2183
+ (finding) => finding.status === "warning" || finding.severity === "warning"
2184
+ ).length,
2185
+ errors: diagnostics.filter((item) => item.severity === "error").length,
2186
+ rulesEvaluated
2187
+ };
2188
+ }
2189
+ function classifyRuleExecution(findings, threw) {
2190
+ if (findings.some((finding) => finding.status === "fail" && finding.severity === "error")) {
2191
+ return "fail";
2097
2192
  }
2098
- const redactionProfile = raw.redactionProfile === "local" || raw.redactionProfile === "share" || raw.redactionProfile === "strict" ? raw.redactionProfile : void 0;
2099
- if (raw.redactionProfile !== void 0 && redactionProfile === void 0) {
2100
- throw new Error('redactionProfile must be "local", "share", or "strict".');
2193
+ if (findings.some(
2194
+ (finding) => finding.status === "warning" || finding.severity === "warning"
2195
+ )) {
2196
+ return "warning";
2101
2197
  }
2102
- const config = { name, traces, cases };
2103
- if (raw.checks !== void 0) {
2104
- if (typeof raw.checks !== "object" || Array.isArray(raw.checks)) {
2105
- throw new Error("checks must be an object.");
2106
- }
2107
- config.checks = raw.checks;
2198
+ return "pass";
2199
+ }
2200
+ function stringAttr(event, keys) {
2201
+ for (const key of keys) {
2202
+ const value = event.attributes?.[key];
2203
+ if (typeof value === "string" && value.trim() !== "") return value;
2108
2204
  }
2109
- if (raw.eval !== void 0) {
2110
- if (typeof raw.eval !== "object" || Array.isArray(raw.eval)) {
2111
- throw new Error("eval must be an object.");
2112
- }
2113
- config.eval = raw.eval;
2205
+ return void 0;
2206
+ }
2207
+ function metadataStringAttr(event, keys) {
2208
+ const metadata = event.attributes?.metadata;
2209
+ if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) {
2210
+ return void 0;
2114
2211
  }
2115
- if (raw.artifacts !== void 0) {
2116
- if (typeof raw.artifacts !== "object" || Array.isArray(raw.artifacts)) {
2117
- throw new Error("artifacts must be an object.");
2118
- }
2119
- const outputDir = asString(
2120
- raw.artifacts.outputDir,
2121
- "artifacts.outputDir"
2122
- );
2123
- config.artifacts = outputDir !== void 0 ? { outputDir } : {};
2124
- }
2125
- if (raw.baseline !== void 0) {
2126
- const baseline = asString(raw.baseline, "baseline");
2127
- if (baseline !== void 0) config.baseline = baseline;
2128
- }
2129
- if (raw.candidate !== void 0) {
2130
- const candidate = asString(raw.candidate, "candidate");
2131
- if (candidate !== void 0) config.candidate = candidate;
2132
- }
2133
- if (redactionProfile !== void 0) config.redactionProfile = redactionProfile;
2134
- return config;
2135
- }
2136
-
2137
- // packages/core/src/suite/load.ts
2138
- var CONFIG_EXTENSIONS = /* @__PURE__ */ new Set([".json", ".js", ".mjs", ".cjs"]);
2139
- var TS_CONFIG_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".mts", ".cts"]);
2140
- function diagnostic2(code, message) {
2141
- return { code, message, severity: "error" };
2142
- }
2143
- async function fileExists(filePath) {
2144
- try {
2145
- await promises.access(filePath);
2146
- return true;
2147
- } catch {
2148
- return false;
2212
+ const record = metadata;
2213
+ for (const key of keys) {
2214
+ const value = record[key];
2215
+ if (typeof value === "string" && value.trim() !== "") return value;
2149
2216
  }
2217
+ return void 0;
2150
2218
  }
2151
- async function resolveSuiteConfigPath(options = {}) {
2152
- const cwd = path15__default.default.resolve(options.cwd ?? process.cwd());
2153
- if (options.configPath !== void 0 && options.configPath.trim() !== "") {
2154
- return path15__default.default.resolve(cwd, options.configPath.trim());
2155
- }
2156
- for (const name of DEFAULT_SUITE_CONFIG_NAMES) {
2157
- const candidate = path15__default.default.join(cwd, name);
2158
- if (await fileExists(candidate)) return candidate;
2219
+ function stripPrefix(name, prefixes) {
2220
+ for (const prefix of prefixes) {
2221
+ if (name.startsWith(prefix)) return name.slice(prefix.length);
2159
2222
  }
2160
- throw new Error(
2161
- `No suite config found. Create one with \`agent-inspect suite init\` or pass --config.`
2162
- );
2223
+ return name;
2163
2224
  }
2164
- async function loadSuiteConfig(options = {}) {
2165
- let configPath;
2166
- try {
2167
- configPath = await resolveSuiteConfigPath(options);
2168
- } catch (error) {
2169
- const message = error instanceof Error ? error.message : String(error);
2170
- throw Object.assign(new Error(message), {
2171
- diagnostics: [diagnostic2("AI_SUITE_CONFIG_LOAD_FAILED", message)]
2172
- });
2173
- }
2174
- const extension = path15__default.default.extname(configPath);
2175
- if (TS_CONFIG_EXTENSIONS.has(extension)) {
2176
- const message = "TypeScript suite configs require an explicit precompiled JavaScript config or future --config-loader support.";
2177
- throw Object.assign(new Error(message), {
2178
- diagnostics: [diagnostic2("AI_SUITE_CONFIG_LOAD_FAILED", message)]
2179
- });
2180
- }
2181
- if (!CONFIG_EXTENSIONS.has(extension)) {
2182
- const message = "Unsupported suite config extension. Use .json, .js, .mjs, or .cjs.";
2183
- throw Object.assign(new Error(message), {
2184
- diagnostics: [diagnostic2("AI_SUITE_CONFIG_LOAD_FAILED", message)]
2185
- });
2186
- }
2187
- try {
2188
- let raw;
2189
- if (extension === ".json") {
2190
- raw = JSON.parse(await promises.readFile(configPath, "utf-8"));
2191
- } else {
2192
- const mod = await import(url.pathToFileURL(configPath).href);
2193
- raw = "default" in mod ? mod.default : mod;
2194
- }
2195
- const config = normalizeSuiteConfig(raw);
2196
- return {
2197
- config,
2198
- configPath,
2199
- configDir: path15__default.default.dirname(configPath)
2200
- };
2201
- } catch (error) {
2202
- const message = error instanceof Error ? error.message : String(error);
2203
- throw Object.assign(new Error(message), {
2204
- diagnostics: [diagnostic2("AI_SUITE_CONFIG_LOAD_FAILED", message)]
2205
- });
2206
- }
2225
+ function eventEvidence(event, path18) {
2226
+ return {
2227
+ runId: event.runId,
2228
+ eventId: event.eventId,
2229
+ parentId: event.parentId,
2230
+ traceId: event.trace?.traceId,
2231
+ spanId: event.trace?.spanId,
2232
+ kind: event.kind,
2233
+ name: event.name,
2234
+ status: event.status,
2235
+ ...path18 ? { path: path18 } : {}
2236
+ };
2207
2237
  }
2208
- async function exists(filePath) {
2209
- try {
2210
- await promises.access(filePath);
2211
- return true;
2212
- } catch {
2213
- return false;
2214
- }
2238
+ function runEvidence(run) {
2239
+ return run ? [{ runId: run.runId, name: run.name, status: run.status }] : [];
2215
2240
  }
2216
- async function resolveSuiteCaseTrace(suiteCase, options) {
2217
- if (suiteCase.trace !== void 0) {
2218
- const tracePath = path15__default.default.resolve(options.configDir, suiteCase.trace);
2219
- if (await exists(tracePath)) {
2220
- return { caseId: suiteCase.id, tracePath, missing: false };
2221
- }
2222
- return {
2223
- caseId: suiteCase.id,
2224
- tracePath,
2225
- missing: true,
2226
- reason: `trace file not found: ${suiteCase.trace}`
2227
- };
2228
- }
2229
- const runKey = suiteCase.runId ?? suiteCase.id;
2230
- const directPath = getTraceFilePath(runKey, options.tracesDir);
2231
- if (await exists(directPath)) {
2232
- return { caseId: suiteCase.id, tracePath: directPath, runId: runKey, missing: false };
2233
- }
2234
- const nestedPath = path15__default.default.join(options.tracesDir, `${path15__default.default.basename(runKey)}.jsonl`);
2235
- if (await exists(nestedPath)) {
2236
- return { caseId: suiteCase.id, tracePath: nestedPath, runId: runKey, missing: false };
2237
- }
2241
+ function failFinding(ruleId, message, evidence, expected, actual, meta) {
2238
2242
  return {
2239
- caseId: suiteCase.id,
2240
- runId: runKey,
2241
- missing: true,
2242
- reason: `no trace found for run id "${runKey}" under ${options.tracesDir}`
2243
+ ruleId,
2244
+ severity: meta?.severity ?? "error",
2245
+ status: meta?.status ?? "fail",
2246
+ message,
2247
+ ...expected !== void 0 ? { expected } : {},
2248
+ ...actual !== void 0 ? { actual } : {},
2249
+ evidence: [...evidence],
2250
+ ...{},
2251
+ ...{},
2252
+ ...{},
2253
+ ...{}
2243
2254
  };
2244
2255
  }
2245
-
2246
- // packages/core/src/diagnostics/programmatic.ts
2247
- var PROGRAMMATIC_DIAGNOSTIC_SPECS = Object.freeze({
2248
- AI_TRACE_INPUT_INVALID: {
2249
- code: "AI_TRACE_INPUT_INVALID",
2250
- summary: 'Expected { type: "file", path }, { type: "directory", path }, { type: "string", content }, { type: "buffer", content }, or { type: "stdin" }.',
2251
- remediation: "For a file path, use openTraceFile(path).",
2252
- relatedCodes: ["invalid_input"]
2253
- },
2254
- AI_TRACE_FORMAT_UNSUPPORTED: {
2255
- code: "AI_TRACE_FORMAT_UNSUPPORTED",
2256
- summary: "No trace reader could detect the input format.",
2257
- remediation: "Pass an AgentInspect JSONL file via openTraceFile, or set options.format to a registered reader.",
2258
- relatedCodes: ["unsupported_format"]
2259
- },
2260
- AI_TRACE_FORMAT_AMBIGUOUS: {
2261
- code: "AI_TRACE_FORMAT_AMBIGUOUS",
2262
- summary: "Multiple trace readers matched the input with equal confidence.",
2263
- remediation: "Set options.format explicitly to disambiguate the reader.",
2264
- relatedCodes: ["ambiguous_format"]
2265
- },
2266
- AI_TRACE_FACTS_INPUT_NOT_NORMALIZED: {
2267
- code: "AI_TRACE_FACTS_INPUT_NOT_NORMALIZED",
2268
- summary: "TraceFacts requires TraceReadResult or PersistedInspectEvent[].",
2269
- remediation: "Use openTraceFile() to normalize a JSONL trace first."
2270
- },
2271
- AI_TRACE_CONTRACT_RUN_SELECTION_REQUIRED: {
2272
- code: "AI_TRACE_CONTRACT_RUN_SELECTION_REQUIRED",
2273
- summary: "Multiple runs are available; select a run before executing checks.",
2274
- remediation: "Pass options.runId or TraceCheckInput.selectedRun.",
2275
- relatedCodes: ["AI_CHECK_RUN_SELECTION_REQUIRED"]
2276
- },
2277
- AI_TRACE_RELATIONSHIP_SELF_PARENT: {
2278
- code: "AI_TRACE_RELATIONSHIP_SELF_PARENT",
2279
- summary: "A parentId equals its own event/step id.",
2280
- remediation: "Reject at capture (AI_LANGGRAPH_SELF_PARENT_REJECTED) or drop via logical projection; do not invent replacement parents.",
2281
- relatedCodes: [
2282
- "AI_LANGGRAPH_SELF_PARENT_REJECTED",
2283
- "AI_LOGICAL_SELF_PARENT_REMOVED"
2284
- ]
2285
- },
2286
- AI_TRACE_RELATIONSHIP_CYCLE: {
2287
- code: "AI_TRACE_RELATIONSHIP_CYCLE",
2288
- summary: "Trace contains a parentId cycle.",
2289
- remediation: "Use visibility-first tree linking for legacy fixtures; prefer acyclic capture for new adapter output.",
2290
- relatedCodes: ["structure.cycle"]
2291
- }
2292
- });
2293
- function formatProgrammaticDiagnostic(code, detail) {
2294
- const spec = PROGRAMMATIC_DIAGNOSTIC_SPECS[code];
2295
- const summary = detail?.trim() ? detail.trim() : spec.summary;
2296
- return `${code}: ${summary} Remediation: ${spec.remediation}`;
2256
+ function toolName(event) {
2257
+ return resolveCanonicalToolName(event);
2297
2258
  }
2298
-
2299
- // packages/core/src/safety/sensitive-key.ts
2300
- function normalizeSensitiveKey(value) {
2301
- return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
2259
+ function semanticEvents(context) {
2260
+ return context.logicalEvents ?? context.events;
2302
2261
  }
2303
- new Set(
2304
- [
2305
- "tokens",
2306
- "max_tokens",
2307
- "min_tokens",
2308
- "ls_max_tokens",
2309
- "token_count",
2310
- "token_limit",
2311
- "token_budget",
2312
- "input_tokens",
2313
- "output_tokens",
2314
- "total_tokens",
2315
- "cached_tokens",
2316
- "prompt_tokens",
2317
- "completion_tokens"
2318
- ].map(normalizeSensitiveKey)
2319
- );
2320
-
2321
- // packages/core/src/checks/logical-events.ts
2322
- function isRecord5(value) {
2323
- return typeof value === "object" && value !== null && !Array.isArray(value);
2262
+ function llmModel(event) {
2263
+ const keys = ["model", "modelId", "responseModelId", "modelName", "model_name"];
2264
+ return stringAttr(event, keys) ?? metadataStringAttr(event, keys) ?? stripPrefix(event.name, ["llm:", "generation:", "transcription:", "speech:"]);
2324
2265
  }
2325
- function legacyEvent(event) {
2326
- const value = event.attributes?.legacyEvent;
2327
- return typeof value === "string" ? value : void 0;
2266
+ function llmProvider(event) {
2267
+ const keys = ["provider", "providerName", "provider_name"];
2268
+ return stringAttr(event, keys) ?? metadataStringAttr(event, keys);
2328
2269
  }
2329
- function stepIdOf(event) {
2330
- const value = event.attributes?.stepId;
2331
- if (typeof value === "string" && value.trim() !== "") return value;
2332
- return void 0;
2270
+ function llmFinishReason(event) {
2271
+ const keys = ["finishReason", "rawFinishReason", "finish_reason"];
2272
+ return stringAttr(event, keys) ?? metadataStringAttr(event, keys);
2333
2273
  }
2334
- function cloneEvent(event) {
2335
- return {
2336
- ...event,
2337
- ...event.attributes !== void 0 ? { attributes: { ...event.attributes } } : {},
2338
- ...event.error !== void 0 ? { error: { ...event.error } } : {},
2339
- ...event.tokenUsage !== void 0 ? { tokenUsage: { ...event.tokenUsage } } : {},
2340
- ...event.source !== void 0 ? { source: { ...event.source } } : {}
2341
- };
2274
+ function finishedEvents(context, kind) {
2275
+ return semanticEvents(context).filter(
2276
+ (event) => (event.kind === kind) && event.status !== "running"
2277
+ );
2342
2278
  }
2343
- function mergeAttributes(start, complete) {
2344
- const merged = {
2345
- ...isRecord5(complete.attributes) ? complete.attributes : {},
2346
- ...isRecord5(start.attributes) ? start.attributes : {}
2347
- };
2348
- merged.legacyEvent = start.attributes?.legacyEvent ?? complete.attributes?.legacyEvent;
2349
- merged.legacyCompleteEvent = complete.attributes?.legacyEvent;
2350
- if (complete.attributes?.errorStack !== void 0) {
2351
- merged.errorStack = complete.attributes.errorStack;
2352
- }
2353
- return Object.keys(merged).length > 0 ? merged : void 0;
2279
+ function toolInvocationEvents(context) {
2280
+ return semanticEvents(context).filter((event) => event.kind === "TOOL");
2354
2281
  }
2355
- function pairStartComplete(start, complete) {
2356
- const attributes = mergeAttributes(start, complete);
2357
- const paired = {
2358
- ...cloneEvent(start),
2359
- status: complete.status,
2360
- timestamp: complete.timestamp ?? start.timestamp,
2361
- ...complete.endedAt !== void 0 ? { endedAt: complete.endedAt } : {},
2362
- ...complete.durationMs !== void 0 ? { durationMs: complete.durationMs } : {},
2363
- ...complete.error !== void 0 ? { error: { ...complete.error } } : {},
2364
- ...complete.tokenUsage !== void 0 && start.tokenUsage === void 0 ? { tokenUsage: { ...complete.tokenUsage } } : {},
2365
- ...attributes !== void 0 ? { attributes } : {}
2366
- };
2282
+ function createRunStatusRule(options = {}) {
2283
+ const expected = options.expected ?? "ok";
2284
+ const allowIncomplete = options.allowIncomplete === true;
2367
2285
  return {
2368
- ...paired,
2369
- sourceEventIds: Object.freeze([start.eventId, complete.eventId]),
2370
- projection: {
2371
- paired: true,
2372
- absorbedEventIds: Object.freeze([complete.eventId]),
2373
- parentNormalized: false,
2374
- ...start.parentId !== void 0 ? { originalParentId: start.parentId } : {}
2286
+ id: "run.status",
2287
+ category: "run",
2288
+ defaultSeverity: "error",
2289
+ evaluate(context) {
2290
+ const findings = [];
2291
+ const actual = context.selectedRun?.status ?? "unknown";
2292
+ if (actual !== expected) {
2293
+ findings.push(
2294
+ failFinding(
2295
+ "run.status",
2296
+ `Run status ${actual} did not match expected ${expected}.`,
2297
+ runEvidence(context.selectedRun),
2298
+ expected,
2299
+ actual
2300
+ )
2301
+ );
2302
+ }
2303
+ if (!allowIncomplete) {
2304
+ const running = semanticEvents(context).filter((event) => event.status === "running");
2305
+ if (running.length > 0) {
2306
+ findings.push(
2307
+ failFinding(
2308
+ "run.status",
2309
+ "Run contains incomplete running events.",
2310
+ running.map((event) => eventEvidence(event)),
2311
+ "no running events",
2312
+ running.length
2313
+ )
2314
+ );
2315
+ }
2316
+ }
2317
+ return findings;
2375
2318
  }
2376
2319
  };
2377
2320
  }
2378
- function asLogical(event, extras) {
2321
+ function createRunDurationRule(options) {
2379
2322
  return {
2380
- ...cloneEvent(event),
2381
- sourceEventIds: Object.freeze([event.eventId]),
2382
- projection: {
2383
- paired: false,
2384
- absorbedEventIds: Object.freeze([]),
2385
- parentNormalized: extras?.parentNormalized === true,
2386
- ...{}
2323
+ id: "run.duration",
2324
+ category: "run",
2325
+ defaultSeverity: "error",
2326
+ evaluate(context) {
2327
+ const actual = context.selectedRun?.durationMs;
2328
+ if (actual === void 0 || actual <= options.maxDurationMs) return [];
2329
+ return [
2330
+ failFinding(
2331
+ "run.duration",
2332
+ `Run duration ${actual}ms exceeded ${options.maxDurationMs}ms.`,
2333
+ runEvidence(context.selectedRun),
2334
+ { maxDurationMs: options.maxDurationMs },
2335
+ actual
2336
+ )
2337
+ ];
2387
2338
  }
2388
2339
  };
2389
2340
  }
2390
- function projectLogicalEvents(events) {
2391
- const diagnostics = [];
2392
- const byRun = /* @__PURE__ */ new Map();
2393
- for (const event of events) {
2394
- const list = byRun.get(event.runId) ?? [];
2395
- list.push(event);
2396
- byRun.set(event.runId, list);
2397
- }
2398
- const absorbedIds = /* @__PURE__ */ new Set();
2399
- const logicalByRawId = /* @__PURE__ */ new Map();
2400
- const stepIdToLogicalId = /* @__PURE__ */ new Map();
2401
- const logical = [];
2402
- const orderedRuns = [...byRun.keys()].sort((a, b) => a.localeCompare(b));
2403
- for (const runId of orderedRuns) {
2404
- const runEvents = byRun.get(runId) ?? [];
2405
- const starts = [];
2406
- const completes = [];
2407
- const others = [];
2408
- for (const event of runEvents) {
2409
- const legacy = legacyEvent(event);
2410
- if (legacy === "step_started" || legacy === "run_started" && event.status === "running") {
2411
- starts.push(event);
2412
- } else if (legacy === "step_completed" || legacy === "run_completed") {
2413
- completes.push(event);
2414
- } else {
2415
- others.push(event);
2341
+ function createToolUsageRule(options) {
2342
+ return {
2343
+ id: "tool.usage",
2344
+ category: "tool",
2345
+ defaultSeverity: "error",
2346
+ evaluate(context) {
2347
+ const tools = toolInvocationEvents(context);
2348
+ const names = tools.map(toolName);
2349
+ const nameSet = new Set(names);
2350
+ const findings = [];
2351
+ for (const required of options.required ?? []) {
2352
+ if (!nameSet.has(required)) {
2353
+ findings.push(
2354
+ failFinding("tool.usage", `Required tool ${required} did not appear.`, runEvidence(context.selectedRun), required, names)
2355
+ );
2356
+ }
2416
2357
  }
2417
- }
2418
- const usedCompletes = /* @__PURE__ */ new Set();
2419
- for (const start of starts) {
2420
- const stepId = stepIdOf(start);
2421
- let match;
2422
- if (legacyEvent(start) === "run_started") {
2423
- const candidates = completes.filter(
2424
- (c) => !usedCompletes.has(c.eventId) && legacyEvent(c) === "run_completed"
2425
- );
2426
- if (candidates.length > 1) {
2427
- diagnostics.push({
2428
- code: "AI_LOGICAL_PAIR_AMBIGUOUS",
2429
- message: `Multiple run_completed rows for run ${runId}; using first by eventId.`,
2430
- eventIds: candidates.map((c) => c.eventId)
2431
- });
2432
- candidates.sort((a, b) => a.eventId.localeCompare(b.eventId));
2358
+ const forbidden = new Set(options.forbidden ?? []);
2359
+ const allowed = options.allowed?.length ? new Set(options.allowed) : void 0;
2360
+ for (const event of tools) {
2361
+ const name = toolName(event);
2362
+ if (forbidden.has(name)) {
2363
+ findings.push(
2364
+ failFinding("tool.usage", `Forbidden tool ${name} appeared.`, [eventEvidence(event)], "tool absent", name)
2365
+ );
2433
2366
  }
2434
- match = candidates[0];
2435
- } else if (stepId) {
2436
- const candidates = completes.filter(
2437
- (c) => !usedCompletes.has(c.eventId) && legacyEvent(c) === "step_completed" && stepIdOf(c) === stepId
2438
- );
2439
- if (candidates.length > 1) {
2440
- diagnostics.push({
2441
- code: "AI_LOGICAL_PAIR_AMBIGUOUS",
2442
- message: `Multiple step_completed rows for stepId ${stepId}; using first by eventId.`,
2443
- eventIds: candidates.map((c) => c.eventId)
2444
- });
2445
- candidates.sort((a, b) => a.eventId.localeCompare(b.eventId));
2367
+ if (allowed && !allowed.has(name)) {
2368
+ findings.push(
2369
+ failFinding("tool.usage", `Tool ${name} is not in the allowed tool set.`, [eventEvidence(event)], [...allowed].sort(), name)
2370
+ );
2446
2371
  }
2447
- match = candidates[0];
2448
2372
  }
2449
- if (match) {
2450
- usedCompletes.add(match.eventId);
2451
- absorbedIds.add(match.eventId);
2452
- const paired = pairStartComplete(start, match);
2453
- logical.push(paired);
2454
- logicalByRawId.set(start.eventId, paired);
2455
- logicalByRawId.set(match.eventId, paired);
2456
- if (stepId) stepIdToLogicalId.set(`${runId}:${stepId}`, paired.eventId);
2457
- } else {
2458
- diagnostics.push({
2459
- code: "AI_LOGICAL_PAIR_UNMATCHED_START",
2460
- message: `No matching complete for start ${start.eventId}.`,
2461
- eventIds: [start.eventId]
2462
- });
2463
- const alone = asLogical(start);
2464
- logical.push(alone);
2465
- logicalByRawId.set(start.eventId, alone);
2466
- if (stepId) stepIdToLogicalId.set(`${runId}:${stepId}`, alone.eventId);
2373
+ if (options.minCount !== void 0 && tools.length < options.minCount) {
2374
+ findings.push(
2375
+ failFinding("tool.usage", `Tool count ${tools.length} was below minimum ${options.minCount}.`, runEvidence(context.selectedRun), { minCount: options.minCount }, tools.length)
2376
+ );
2467
2377
  }
2468
- }
2469
- for (const complete of completes) {
2470
- if (usedCompletes.has(complete.eventId)) continue;
2471
- diagnostics.push({
2472
- code: "AI_LOGICAL_PAIR_UNMATCHED_COMPLETE",
2473
- message: `No matching start for complete ${complete.eventId}.`,
2474
- eventIds: [complete.eventId]
2475
- });
2476
- const alone = asLogical(complete);
2477
- logical.push(alone);
2478
- logicalByRawId.set(complete.eventId, alone);
2479
- const stepId = stepIdOf(complete);
2480
- if (stepId && !stepIdToLogicalId.has(`${runId}:${stepId}`)) {
2481
- stepIdToLogicalId.set(`${runId}:${stepId}`, alone.eventId);
2378
+ if (options.maxCount !== void 0 && tools.length > options.maxCount) {
2379
+ findings.push(
2380
+ failFinding("tool.usage", `Tool count ${tools.length} exceeded maximum ${options.maxCount}.`, tools.map((event) => eventEvidence(event)), { maxCount: options.maxCount }, tools.length)
2381
+ );
2482
2382
  }
2383
+ return findings;
2483
2384
  }
2484
- for (const event of others) {
2485
- const alone = asLogical(event);
2486
- logical.push(alone);
2487
- logicalByRawId.set(event.eventId, alone);
2488
- const stepId = stepIdOf(event);
2489
- if (stepId && !stepIdToLogicalId.has(`${runId}:${stepId}`)) {
2490
- stepIdToLogicalId.set(`${runId}:${stepId}`, alone.eventId);
2385
+ };
2386
+ }
2387
+ function createLlmUsageRule(options) {
2388
+ return {
2389
+ id: "llm.usage",
2390
+ category: "llm",
2391
+ defaultSeverity: "error",
2392
+ evaluate(context) {
2393
+ const llms = finishedEvents(context, "LLM");
2394
+ const findings = [];
2395
+ const allowedModels = options.allowedModels?.length ? new Set(options.allowedModels) : void 0;
2396
+ const allowedProviders = options.allowedProviders?.length ? new Set(options.allowedProviders) : void 0;
2397
+ const finishReasons = options.finishReasons?.length ? new Set(options.finishReasons) : void 0;
2398
+ if (options.maxCalls !== void 0 && llms.length > options.maxCalls) {
2399
+ findings.push(
2400
+ failFinding(
2401
+ "llm.usage",
2402
+ `LLM call count ${llms.length} exceeded ${options.maxCalls}.`,
2403
+ llms.map((event) => eventEvidence(event)),
2404
+ { maxCalls: options.maxCalls },
2405
+ llms.length
2406
+ )
2407
+ );
2491
2408
  }
2492
- }
2493
- }
2494
- const logicalById = new Map(logical.map((e) => [e.eventId, e]));
2495
- const normalized = [];
2496
- for (const event of logical) {
2497
- const originalParentId = event.parentId;
2498
- if (!originalParentId) {
2499
- normalized.push(event);
2500
- continue;
2501
- }
2502
- let nextParent = originalParentId;
2503
- let remapped = false;
2504
- const viaAbsorbed = logicalByRawId.get(originalParentId);
2505
- if (viaAbsorbed && viaAbsorbed.eventId !== originalParentId) {
2506
- nextParent = viaAbsorbed.eventId;
2507
- remapped = true;
2508
- } else if (!logicalById.has(originalParentId)) {
2509
- const viaStep = stepIdToLogicalId.get(`${event.runId}:${originalParentId}`);
2510
- if (viaStep) {
2511
- nextParent = viaStep;
2512
- remapped = true;
2513
- }
2514
- }
2515
- if (!remapped) {
2516
- if (originalParentId === event.eventId) {
2517
- diagnostics.push({
2518
- code: "AI_LOGICAL_SELF_PARENT_REMOVED",
2519
- message: formatProgrammaticDiagnostic(
2520
- "AI_TRACE_RELATIONSHIP_SELF_PARENT",
2521
- `Removed self-parent edge on ${event.eventId}.`
2522
- ),
2523
- eventIds: [event.eventId]
2524
- });
2525
- const { parentId: _drop, ...rest } = event;
2526
- normalized.push({
2527
- ...rest,
2528
- projection: {
2529
- ...event.projection,
2530
- parentNormalized: true,
2531
- originalParentId
2532
- }
2533
- });
2534
- continue;
2535
- }
2536
- if (!logicalById.has(originalParentId) && !logicalByRawId.has(originalParentId)) {
2537
- const mapping = event.attributes?.parentMapping;
2538
- const unresolved = mapping === "unresolved" || event.attributes?.parentUnresolved === true || event.attributes?.unresolvedParent === true || // LangGraph/framework scaffolding sentinel labels are not event ids.
2539
- /^LangGraph$/i.test(originalParentId) || originalParentId.startsWith("unresolved:");
2540
- if (!unresolved) {
2541
- diagnostics.push({
2542
- code: "AI_LOGICAL_PARENT_UNRESOLVED",
2543
- message: `Parent ${originalParentId} unresolved for ${event.eventId}.`,
2544
- eventIds: [event.eventId]
2545
- });
2409
+ for (const event of llms) {
2410
+ const model = llmModel(event);
2411
+ const provider = llmProvider(event);
2412
+ const finishReason = llmFinishReason(event);
2413
+ if (allowedModels && (!model || !allowedModels.has(model))) {
2414
+ findings.push(
2415
+ failFinding("llm.usage", `LLM model ${model ?? "unknown"} is not allowed.`, [eventEvidence(event, "attributes.model")], [...allowedModels].sort(), model ?? "unknown")
2416
+ );
2417
+ }
2418
+ if (allowedProviders && (!provider || !allowedProviders.has(provider))) {
2419
+ findings.push(
2420
+ failFinding("llm.usage", `LLM provider ${provider ?? "unknown"} is not allowed.`, [eventEvidence(event, "attributes.provider")], [...allowedProviders].sort(), provider ?? "unknown")
2421
+ );
2422
+ }
2423
+ if (finishReasons && (!finishReason || !finishReasons.has(finishReason))) {
2424
+ findings.push(
2425
+ failFinding("llm.usage", `LLM finish reason ${finishReason ?? "unknown"} is not allowed.`, [eventEvidence(event, "attributes.finishReason")], [...finishReasons].sort(), finishReason ?? "unknown")
2426
+ );
2546
2427
  }
2547
2428
  }
2548
- normalized.push(event);
2549
- continue;
2550
- }
2551
- if (nextParent === event.eventId) {
2552
- diagnostics.push({
2553
- code: "AI_LOGICAL_SELF_PARENT_REMOVED",
2554
- message: formatProgrammaticDiagnostic(
2555
- "AI_TRACE_RELATIONSHIP_SELF_PARENT",
2556
- `Removed self-parent edge on ${event.eventId} (was ${originalParentId}).`
2557
- ),
2558
- eventIds: [event.eventId]
2559
- });
2560
- const { parentId: _drop, ...rest } = event;
2561
- normalized.push({
2562
- ...rest,
2563
- projection: {
2564
- ...event.projection,
2565
- parentNormalized: true,
2566
- originalParentId
2429
+ const tokenTotals = llms.reduce(
2430
+ (totals, event) => ({
2431
+ input: totals.input + (event.tokenUsage?.input ?? 0),
2432
+ output: totals.output + (event.tokenUsage?.output ?? 0),
2433
+ total: totals.total + (event.tokenUsage?.total ?? 0),
2434
+ cached: totals.cached + (event.tokenUsage?.cached ?? 0)
2435
+ }),
2436
+ { input: 0, output: 0, total: 0, cached: 0 }
2437
+ );
2438
+ const tokenLimits = [
2439
+ ["input", options.maxInputTokens],
2440
+ ["output", options.maxOutputTokens],
2441
+ ["total", options.maxTotalTokens],
2442
+ ["cached", options.maxCachedTokens]
2443
+ ];
2444
+ for (const [key, limit] of tokenLimits) {
2445
+ if (limit !== void 0 && tokenTotals[key] > limit) {
2446
+ findings.push(
2447
+ failFinding(
2448
+ "llm.usage",
2449
+ `LLM ${key} token count ${tokenTotals[key]} exceeded ${limit}.`,
2450
+ llms.map((event) => eventEvidence(event, `tokenUsage.${key}`)),
2451
+ { [`max${key[0].toUpperCase()}${key.slice(1)}Tokens`]: limit },
2452
+ tokenTotals[key]
2453
+ )
2454
+ );
2567
2455
  }
2568
- });
2569
- continue;
2570
- }
2571
- diagnostics.push({
2572
- code: "AI_LOGICAL_PARENT_REMAPPED",
2573
- message: `Remapped parent ${originalParentId} \u2192 ${nextParent} for ${event.eventId}.`,
2574
- eventIds: [event.eventId]
2575
- });
2576
- normalized.push({
2577
- ...event,
2578
- parentId: nextParent,
2579
- projection: {
2580
- ...event.projection,
2581
- parentNormalized: true,
2582
- originalParentId
2583
2456
  }
2584
- });
2585
- }
2586
- const rawIndex = new Map(events.map((e, i) => [e.eventId, i]));
2587
- normalized.sort((a, b) => {
2588
- const ai = rawIndex.get(a.sourceEventIds[0]) ?? 0;
2589
- const bi = rawIndex.get(b.sourceEventIds[0]) ?? 0;
2590
- return ai - bi || a.eventId.localeCompare(b.eventId);
2591
- });
2457
+ return findings;
2458
+ }
2459
+ };
2460
+ }
2461
+ function createObservedOutcomeRule(options = {}) {
2462
+ const failOn = options.failOn ?? ["failed"];
2463
+ const requireAny = options.requireAny === true;
2592
2464
  return {
2593
- logicalEvents: Object.freeze(normalized),
2594
- diagnostics: Object.freeze(diagnostics)
2465
+ id: "outcome.status",
2466
+ category: "run",
2467
+ defaultSeverity: "error",
2468
+ evaluate(context) {
2469
+ const outcomes = extractOutcomesFromPersistedEvents(context.events);
2470
+ if (requireAny && outcomes.length === 0) {
2471
+ return [
2472
+ failFinding(
2473
+ "outcome.status",
2474
+ "Expected at least one observed outcome.",
2475
+ runEvidence(context.selectedRun),
2476
+ { requireAny: true, expected: "at least one observed outcome" },
2477
+ { code: "outcome.missing", actual: 0 }
2478
+ )
2479
+ ];
2480
+ }
2481
+ const matching = outcomesMatchingStatus(outcomes, failOn);
2482
+ if (matching.length === 0) return [];
2483
+ return [
2484
+ failFinding(
2485
+ "outcome.status",
2486
+ `Observed outcome count ${matching.length} matched [${failOn.join(", ")}].`,
2487
+ matching.map((outcome) => ({
2488
+ runId: outcome.runId,
2489
+ eventId: outcome.outcomeId,
2490
+ ...outcome.parentId !== void 0 ? { parentId: outcome.parentId } : {},
2491
+ kind: "OUTCOME",
2492
+ name: outcome.name,
2493
+ status: outcome.status,
2494
+ path: `outcome.${outcome.name}`
2495
+ })),
2496
+ { failOn },
2497
+ matching.map((outcome) => ({
2498
+ name: outcome.name,
2499
+ status: outcome.status,
2500
+ expectation: outcome.expectation
2501
+ }))
2502
+ )
2503
+ ];
2504
+ }
2595
2505
  };
2596
2506
  }
2597
- function resolveCanonicalToolName(event) {
2598
- const attrs = event.attributes;
2599
- const direct = pickString(attrs, ["toolName", "tool"]);
2600
- if (direct) return direct;
2601
- const metadata = attrs?.metadata;
2602
- if (isRecord5(metadata)) {
2603
- const nested = pickString(metadata, ["toolName", "tool"]);
2604
- if (nested) return nested;
2507
+ function runTraceChecks(input, options = {}) {
2508
+ const selected = resolveSelectedRun(input, options.runId);
2509
+ if (selected.diagnostics.length > 0) {
2510
+ return errorResult(input, selected.diagnostics, selected.run);
2605
2511
  }
2606
- for (const prefix of ["tool:", "function:", "mcp-tools:"]) {
2607
- if (event.name.startsWith(prefix)) return event.name.slice(prefix.length);
2512
+ const rules = selectRules(options.rules ?? [], options.select);
2513
+ if (rules.diagnostics.length > 0) {
2514
+ return errorResult(input, rules.diagnostics, selected.run);
2608
2515
  }
2609
- return event.name;
2610
- }
2611
- function pickString(record, keys) {
2612
- if (!record) return void 0;
2613
- for (const key of keys) {
2614
- const value = record[key];
2615
- if (typeof value === "string" && value.trim() !== "") return value.trim();
2516
+ if (rules.rules.length === 0) {
2517
+ return errorResult(
2518
+ input,
2519
+ [
2520
+ diagnostic(
2521
+ "AI_CHECK_NO_RULES_EVALUATED",
2522
+ "No trace check rules were evaluated. Configure at least one rule, contract, or CLI check option."
2523
+ )
2524
+ ],
2525
+ selected.run
2526
+ );
2616
2527
  }
2617
- return void 0;
2618
- }
2619
-
2620
- // packages/core/src/checks/trace-facts.ts
2621
- formatProgrammaticDiagnostic(
2622
- "AI_TRACE_FACTS_INPUT_NOT_NORMALIZED"
2623
- );
2624
-
2625
- // packages/core/src/checks/contract.ts
2626
- new Set(OBSERVED_OUTCOME_METHODS);
2627
-
2628
- // packages/core/src/checks/index.ts
2629
- var SEVERITY_RANK = {
2630
- error: 0,
2631
- warning: 1,
2632
- info: 2
2633
- };
2634
- var STATUS_RANK = {
2635
- fail: 0,
2636
- warning: 1,
2637
- pass: 2
2638
- };
2639
- function compareStrings(a, b) {
2640
- return (a ?? "").localeCompare(b ?? "");
2641
- }
2642
- function diagnostic3(code, message, ruleId) {
2643
- return {
2644
- code,
2645
- message,
2646
- severity: "error",
2647
- ...ruleId ? { ruleId } : {}
2648
- };
2649
- }
2650
- function emptySummary() {
2651
- return {
2652
- passed: 0,
2653
- failed: 0,
2654
- warnings: 0,
2655
- errors: 0,
2656
- rulesEvaluated: 0
2528
+ const facts = buildFacts(input, selected.run);
2529
+ const context = {
2530
+ ...facts,
2531
+ ...selected.run ? { selectedRun: selected.run } : {},
2532
+ ...input.sourceLabel ? { sourceLabel: input.sourceLabel } : {}
2657
2533
  };
2658
- }
2659
- function errorResult(input, diagnostics, selectedRun, ruleExecutions = []) {
2660
- return {
2661
- ok: false,
2662
- status: "error",
2663
- format: input.read.format,
2664
- ...selectedRun ? { runId: selectedRun.runId } : {},
2665
- summary: {
2666
- ...emptySummary(),
2667
- errors: diagnostics.filter((item) => item.severity === "error").length,
2668
- rulesEvaluated: ruleExecutions.length
2669
- },
2670
- findings: [],
2671
- diagnostics: [...diagnostics],
2672
- ruleExecutions: [...ruleExecutions]
2673
- };
2674
- }
2675
- function flattenNodes(nodes) {
2676
- return nodes.flatMap((node) => [node, ...flattenNodes(node.children)]);
2677
- }
2678
- function buildFacts(input, selectedRun) {
2679
- const scopedRuns = selectedRun ? [selectedRun] : input.read.runs;
2680
- const scopedRunIds = new Set(scopedRuns.map((run) => run.runId));
2681
- const scopedEvents = selectedRun === void 0 ? input.read.events : input.read.events.filter((event) => scopedRunIds.has(event.runId));
2682
- const nodes = flattenNodes(scopedRuns.flatMap((run) => run.children));
2683
- const nodesByEventId = /* @__PURE__ */ new Map();
2684
- const childrenByParentId = /* @__PURE__ */ new Map();
2685
- for (const node of nodes) {
2686
- nodesByEventId.set(node.event.eventId, node);
2687
- const parentId = node.event.parentId;
2688
- if (parentId) {
2689
- const children = childrenByParentId.get(parentId) ?? [];
2690
- children.push(node);
2691
- childrenByParentId.set(parentId, children);
2534
+ const diagnostics = [];
2535
+ const findings = [];
2536
+ const ruleExecutions = [];
2537
+ for (const rule of rules.rules) {
2538
+ try {
2539
+ const ruleFindings = rule.evaluate(context).map((finding) => normalizeFinding(rule, finding));
2540
+ findings.push(...ruleFindings);
2541
+ ruleExecutions.push({
2542
+ ruleId: rule.id,
2543
+ category: rule.category,
2544
+ status: classifyRuleExecution(ruleFindings, false),
2545
+ findingCount: ruleFindings.length,
2546
+ ...selected.run ? { runId: selected.run.runId } : {}
2547
+ });
2548
+ } catch (error) {
2549
+ const message = error instanceof Error ? error.message : String(error);
2550
+ diagnostics.push(
2551
+ diagnostic("AI_CHECK_INTERNAL_ERROR", `Rule ${rule.id} failed: ${message}`, rule.id)
2552
+ );
2553
+ ruleExecutions.push({
2554
+ ruleId: rule.id,
2555
+ category: rule.category,
2556
+ status: "error",
2557
+ findingCount: 0,
2558
+ ...selected.run ? { runId: selected.run.runId } : {}
2559
+ });
2692
2560
  }
2693
2561
  }
2694
- const projection = projectLogicalEvents(scopedEvents);
2562
+ if (diagnostics.length > 0) {
2563
+ return errorResult(input, diagnostics, selected.run, ruleExecutions);
2564
+ }
2565
+ const eventById = new Map(input.read.events.map((event) => [event.eventId, event]));
2566
+ const sortedFindings = findings.sort(compareFindings(eventById));
2567
+ const summary = summarize(sortedFindings, diagnostics, ruleExecutions.length);
2568
+ const status = summary.failed > 0 ? "fail" : "pass";
2695
2569
  return {
2570
+ ok: status === "pass",
2571
+ status,
2696
2572
  format: input.read.format,
2697
- runs: Object.freeze([...input.read.runs]),
2698
- events: Object.freeze([...scopedEvents]),
2699
- logicalEvents: projection.logicalEvents,
2700
- logicalProjectionDiagnostics: projection.diagnostics,
2701
- readerWarnings: Object.freeze([...input.read.warnings]),
2702
- unsupportedFields: Object.freeze([...input.read.unsupportedFields]),
2703
- sourceFiles: Object.freeze([...input.read.sourceFiles]),
2704
- nodesByEventId,
2705
- childrenByParentId,
2706
- rootNodes: Object.freeze(scopedRuns.flatMap((run) => run.children))
2573
+ ...selected.run ? { runId: selected.run.runId } : {},
2574
+ summary,
2575
+ findings: sortedFindings,
2576
+ diagnostics,
2577
+ ruleExecutions
2707
2578
  };
2708
2579
  }
2709
- function resolveSelectedRun(input, runId) {
2710
- if (input.selectedRun) {
2711
- if (runId && input.selectedRun.runId !== runId) {
2712
- return {
2713
- diagnostics: [
2714
- diagnostic3(
2715
- "AI_CHECK_INVALID_ARGUMENTS",
2716
- `Selected run ${input.selectedRun.runId} does not match requested run ${runId}.`
2717
- )
2718
- ]
2719
- };
2720
- }
2721
- return { run: input.selectedRun, diagnostics: [] };
2580
+
2581
+ // packages/core/src/checks/contract.ts
2582
+ new Set(OBSERVED_OUTCOME_METHODS);
2583
+
2584
+ // packages/core/src/exporters/helpers.ts
2585
+ function sortKeysDeep(input) {
2586
+ if (input === null || typeof input !== "object") return input;
2587
+ if (Array.isArray(input)) return input.map(sortKeysDeep);
2588
+ const o = input;
2589
+ const out = {};
2590
+ for (const k of Object.keys(o).sort()) {
2591
+ out[k] = sortKeysDeep(o[k]);
2722
2592
  }
2723
- if (runId) {
2724
- const run = input.read.runs.find((candidate) => candidate.runId === runId);
2725
- if (!run) {
2726
- return {
2727
- diagnostics: [
2728
- diagnostic3("AI_CHECK_RUN_SELECTION_REQUIRED", `Run not found: ${runId}.`)
2729
- ]
2730
- };
2731
- }
2732
- return { run, diagnostics: [] };
2593
+ return out;
2594
+ }
2595
+ function stableJson(value, pretty) {
2596
+ const sorted = sortKeysDeep(value);
2597
+ return JSON.stringify(sorted);
2598
+ }
2599
+
2600
+ // packages/core/src/diff/comparable.ts
2601
+ function extractOutputPreview(meta) {
2602
+ if (meta === void 0) return void 0;
2603
+ if ("outputPreview" in meta) return meta.outputPreview;
2604
+ if ("resultPreview" in meta) return meta.resultPreview;
2605
+ return void 0;
2606
+ }
2607
+ function mapStepStatus(s) {
2608
+ if (s === void 0) return "running";
2609
+ return s;
2610
+ }
2611
+ function manualTraceEventsToComparableRun(events) {
2612
+ const started = events.find((e) => e.event === "run_started");
2613
+ if (!started || started.event !== "run_started") {
2614
+ throw new Error("Invalid trace: missing run_started");
2733
2615
  }
2734
- if (input.read.runs.length === 1) {
2735
- return { run: input.read.runs[0], diagnostics: [] };
2616
+ const rs = started;
2617
+ const runId = rs.runId;
2618
+ const completedAll = events.filter((e) => e.event === "run_completed");
2619
+ const lastCompleted = completedAll[completedAll.length - 1];
2620
+ let runStatus;
2621
+ if (lastCompleted === void 0) runStatus = "running";
2622
+ else runStatus = lastCompleted.status;
2623
+ const durationMs = lastCompleted !== void 0 && Number.isFinite(lastCompleted.durationMs) ? lastCompleted.durationMs : void 0;
2624
+ const steps = /* @__PURE__ */ new Map();
2625
+ let order = 0;
2626
+ for (const e of events) {
2627
+ if (e.event !== "step_started") continue;
2628
+ const s = e;
2629
+ const meta = s.metadata ? { ...s.metadata } : void 0;
2630
+ steps.set(s.stepId, {
2631
+ id: s.stepId,
2632
+ parentId: s.parentId,
2633
+ name: s.name,
2634
+ type: s.type,
2635
+ order: order++,
2636
+ timestamp: s.timestamp,
2637
+ metadata: meta
2638
+ });
2736
2639
  }
2737
- if (input.read.runs.length === 0) {
2738
- return {
2739
- diagnostics: [
2740
- diagnostic3(
2741
- "AI_CHECK_RUN_SELECTION_REQUIRED",
2742
- formatProgrammaticDiagnostic(
2743
- "AI_TRACE_CONTRACT_RUN_SELECTION_REQUIRED",
2744
- "No runs are available for checks."
2745
- )
2746
- )
2747
- ]
2640
+ for (const e of events) {
2641
+ if (e.event !== "step_completed") continue;
2642
+ const acc = steps.get(e.stepId);
2643
+ if (!acc) continue;
2644
+ acc.status = e.status;
2645
+ acc.durationMs = e.durationMs;
2646
+ if (e.error?.message) acc.errorMsg = e.error.message;
2647
+ const extra = e;
2648
+ if (extra.metadata !== void 0 && typeof extra.metadata === "object") {
2649
+ acc.metadata = { ...acc.metadata ?? {}, ...extra.metadata };
2650
+ }
2651
+ }
2652
+ const nodes = /* @__PURE__ */ new Map();
2653
+ for (const acc of steps.values()) {
2654
+ let meta = acc.metadata ? { ...acc.metadata } : void 0;
2655
+ if (acc.parentId !== void 0 && !steps.has(acc.parentId)) {
2656
+ meta = { ...meta ?? {}, agent_inspect_diff_parent_missing: true };
2657
+ }
2658
+ const outputPreview = extractOutputPreview(meta);
2659
+ if (meta !== void 0 && ("outputPreview" in meta || "resultPreview" in meta)) {
2660
+ delete meta.outputPreview;
2661
+ delete meta.resultPreview;
2662
+ }
2663
+ const sc = {
2664
+ id: acc.id,
2665
+ name: acc.name,
2666
+ type: acc.type,
2667
+ status: mapStepStatus(acc.status),
2668
+ durationMs: acc.durationMs,
2669
+ error: acc.errorMsg,
2670
+ metadata: meta && Object.keys(meta).length > 0 ? meta : void 0,
2671
+ outputPreview,
2672
+ children: []
2748
2673
  };
2674
+ nodes.set(acc.id, sc);
2749
2675
  }
2750
- return {
2751
- diagnostics: [
2752
- diagnostic3(
2753
- "AI_CHECK_RUN_SELECTION_REQUIRED",
2754
- formatProgrammaticDiagnostic("AI_TRACE_CONTRACT_RUN_SELECTION_REQUIRED")
2755
- )
2756
- ]
2676
+ const roots = [];
2677
+ const sortByOrder = (a, b) => {
2678
+ const oa = steps.get(a.id)?.order ?? 0;
2679
+ const ob = steps.get(b.id)?.order ?? 0;
2680
+ return oa - ob;
2757
2681
  };
2758
- }
2759
- function selectRules(rules, selectedIds) {
2760
- const diagnostics = [];
2761
- const byId = /* @__PURE__ */ new Map();
2762
- for (const rule of rules) {
2763
- if (byId.has(rule.id)) {
2764
- diagnostics.push(
2765
- diagnostic3("AI_CHECK_INVALID_CONFIG", `Duplicate trace check rule id: ${rule.id}.`, rule.id)
2766
- );
2767
- continue;
2682
+ for (const acc of steps.values()) {
2683
+ const node = nodes.get(acc.id);
2684
+ if (acc.parentId !== void 0 && nodes.has(acc.parentId)) {
2685
+ nodes.get(acc.parentId).children.push(node);
2686
+ } else {
2687
+ roots.push(node);
2768
2688
  }
2769
- byId.set(rule.id, rule);
2770
2689
  }
2771
- if (selectedIds && selectedIds.length > 0) {
2772
- const selected = new Set(selectedIds);
2773
- for (const id of selected) {
2774
- if (!byId.has(id)) {
2775
- diagnostics.push(
2776
- diagnostic3("AI_CHECK_INVALID_CONFIG", `Unknown trace check rule id: ${id}.`, id)
2777
- );
2778
- }
2779
- }
2780
- return {
2781
- rules: [...byId.values()].filter((rule) => selected.has(rule.id)).sort(compareRules),
2782
- diagnostics
2783
- };
2690
+ roots.sort(sortByOrder);
2691
+ for (const n of nodes.values()) {
2692
+ n.children.sort(sortByOrder);
2784
2693
  }
2785
- return { rules: [...byId.values()].sort(compareRules), diagnostics };
2694
+ return {
2695
+ runId,
2696
+ name: rs.name,
2697
+ status: runStatus,
2698
+ durationMs,
2699
+ steps: roots
2700
+ };
2786
2701
  }
2787
- function compareRules(a, b) {
2788
- return a.id.localeCompare(b.id);
2702
+
2703
+ // packages/core/src/diff/engine.ts
2704
+ var DEFAULT_THRESHOLD_MS = 0;
2705
+ function pathSeg(step, index) {
2706
+ return { index, name: step.name, stepId: step.id };
2789
2707
  }
2790
- function eventTimestamp(finding, eventById) {
2791
- const eventId = finding.evidence[0]?.eventId;
2792
- return eventId ? eventById.get(eventId)?.timestamp ?? "" : "";
2708
+ function buildPath(segments) {
2709
+ return { path: [...segments] };
2793
2710
  }
2794
- function compareFindings(eventById) {
2795
- return (a, b) => {
2796
- if (SEVERITY_RANK[a.severity] !== SEVERITY_RANK[b.severity]) {
2797
- return SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity];
2711
+ function pairSteps(left, right) {
2712
+ const usedRight = /* @__PURE__ */ new Set();
2713
+ const pairs = [];
2714
+ for (let i = 0; i < left.length; i++) {
2715
+ const L = left[i];
2716
+ let R = right.find((r) => !usedRight.has(r.id) && r.id === L.id);
2717
+ if (R === void 0 && i < right.length && !usedRight.has(right[i].id)) {
2718
+ const cand = right[i];
2719
+ if (cand.name === L.name && (cand.type ?? "") === (L.type ?? "")) {
2720
+ R = cand;
2721
+ }
2798
2722
  }
2799
- const byRule = a.ruleId.localeCompare(b.ruleId);
2800
- if (byRule !== 0) return byRule;
2801
- if (STATUS_RANK[a.status] !== STATUS_RANK[b.status]) {
2802
- return STATUS_RANK[a.status] - STATUS_RANK[b.status];
2723
+ if (R === void 0) {
2724
+ R = right.find(
2725
+ (r) => !usedRight.has(r.id) && r.name === L.name && (r.type ?? "") === (L.type ?? "")
2726
+ );
2727
+ }
2728
+ if (R !== void 0) {
2729
+ usedRight.add(R.id);
2730
+ pairs.push([L, R]);
2731
+ } else {
2732
+ pairs.push([L, void 0]);
2803
2733
  }
2804
- const byRun = compareStrings(a.evidence[0]?.runId, b.evidence[0]?.runId);
2805
- if (byRun !== 0) return byRun;
2806
- const byTime = eventTimestamp(a, eventById).localeCompare(eventTimestamp(b, eventById));
2807
- if (byTime !== 0) return byTime;
2808
- const byEvent = compareStrings(a.evidence[0]?.eventId, b.evidence[0]?.eventId);
2809
- if (byEvent !== 0) return byEvent;
2810
- return compareStrings(a.evidence[0]?.path, b.evidence[0]?.path);
2811
- };
2812
- }
2813
- function normalizeFinding(rule, finding) {
2814
- return {
2815
- ruleId: finding.ruleId || rule.id,
2816
- severity: finding.severity ?? rule.defaultSeverity,
2817
- status: finding.status,
2818
- message: finding.message,
2819
- ...finding.expected !== void 0 ? { expected: finding.expected } : {},
2820
- ...finding.actual !== void 0 ? { actual: finding.actual } : {},
2821
- evidence: [...finding.evidence ?? []],
2822
- ...finding.category !== void 0 ? { category: finding.category } : {},
2823
- ...finding.confidence !== void 0 ? { confidence: finding.confidence } : {},
2824
- ...finding.detector !== void 0 ? { detector: finding.detector } : {},
2825
- ...finding.action !== void 0 ? { action: finding.action } : {}
2826
- };
2827
- }
2828
- function summarize(findings, diagnostics, rulesEvaluated) {
2829
- return {
2830
- passed: findings.filter((finding) => finding.status === "pass").length,
2831
- failed: findings.filter(
2832
- (finding) => finding.status === "fail" && finding.severity === "error"
2833
- ).length,
2834
- warnings: findings.filter(
2835
- (finding) => finding.status === "warning" || finding.severity === "warning"
2836
- ).length,
2837
- errors: diagnostics.filter((item) => item.severity === "error").length,
2838
- rulesEvaluated
2839
- };
2840
- }
2841
- function classifyRuleExecution(findings, threw) {
2842
- if (findings.some((finding) => finding.status === "fail" && finding.severity === "error")) {
2843
- return "fail";
2844
2734
  }
2845
- if (findings.some(
2846
- (finding) => finding.status === "warning" || finding.severity === "warning"
2847
- )) {
2848
- return "warning";
2735
+ for (const R of right) {
2736
+ if (!usedRight.has(R.id)) {
2737
+ pairs.push([void 0, R]);
2738
+ }
2849
2739
  }
2850
- return "pass";
2740
+ return pairs;
2851
2741
  }
2852
- function stringAttr(event, keys) {
2853
- for (const key of keys) {
2854
- const value = event.attributes?.[key];
2855
- if (typeof value === "string" && value.trim() !== "") return value;
2742
+ function compareLeafSteps(L, R, segments, opts, out) {
2743
+ const path18 = buildPath(segments);
2744
+ if (L.name !== R.name) {
2745
+ out.push({
2746
+ kind: "structure",
2747
+ severity: "warning",
2748
+ message: "Step name differs",
2749
+ path: path18,
2750
+ left: L.name,
2751
+ right: R.name
2752
+ });
2856
2753
  }
2857
- return void 0;
2858
- }
2859
- function metadataStringAttr(event, keys) {
2860
- const metadata = event.attributes?.metadata;
2861
- if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) {
2862
- return void 0;
2754
+ if ((L.type ?? "") !== (R.type ?? "")) {
2755
+ out.push({
2756
+ kind: "step-type",
2757
+ severity: "warning",
2758
+ message: "Step type differs",
2759
+ path: path18,
2760
+ left: L.type,
2761
+ right: R.type
2762
+ });
2863
2763
  }
2864
- const record = metadata;
2865
- for (const key of keys) {
2866
- const value = record[key];
2867
- if (typeof value === "string" && value.trim() !== "") return value;
2764
+ if ((L.status ?? "") !== (R.status ?? "")) {
2765
+ out.push({
2766
+ kind: "step-status",
2767
+ severity: "warning",
2768
+ message: "Step status differs",
2769
+ path: path18,
2770
+ left: L.status,
2771
+ right: R.status
2772
+ });
2773
+ }
2774
+ const le = L.error ?? "";
2775
+ const re = R.error ?? "";
2776
+ if (le !== re) {
2777
+ out.push({
2778
+ kind: "error",
2779
+ severity: "error",
2780
+ message: "Step error message differs",
2781
+ path: path18,
2782
+ left: le || void 0,
2783
+ right: re || void 0
2784
+ });
2785
+ }
2786
+ if (!opts.ignoreDuration) {
2787
+ const ld = L.durationMs;
2788
+ const rd = R.durationMs;
2789
+ const th = opts.durationThresholdMs;
2790
+ let differs = false;
2791
+ if (ld === void 0 && rd === void 0) differs = false;
2792
+ else if (ld === void 0 || rd === void 0) differs = true;
2793
+ else differs = Math.abs(ld - rd) > th;
2794
+ if (differs) {
2795
+ out.push({
2796
+ kind: "duration",
2797
+ severity: "info",
2798
+ message: "Step duration differs",
2799
+ path: path18,
2800
+ left: ld,
2801
+ right: rd
2802
+ });
2803
+ }
2804
+ }
2805
+ const lm = stableJson(L.metadata ?? {});
2806
+ const rm2 = stableJson(R.metadata ?? {});
2807
+ if (lm !== rm2) {
2808
+ out.push({
2809
+ kind: "metadata",
2810
+ severity: "info",
2811
+ message: "Step metadata differs",
2812
+ path: path18,
2813
+ left: L.metadata,
2814
+ right: R.metadata
2815
+ });
2816
+ }
2817
+ const lo = stableJson(L.outputPreview ?? null);
2818
+ const ro = stableJson(R.outputPreview ?? null);
2819
+ if (lo !== ro) {
2820
+ out.push({
2821
+ kind: "output",
2822
+ severity: "info",
2823
+ message: "Output preview differs",
2824
+ path: path18,
2825
+ left: L.outputPreview,
2826
+ right: R.outputPreview
2827
+ });
2868
2828
  }
2869
- return void 0;
2870
2829
  }
2871
- function stripPrefix(name, prefixes) {
2872
- for (const prefix of prefixes) {
2873
- if (name.startsWith(prefix)) return name.slice(prefix.length);
2830
+ function compareRecursive(L, R, segments, opts, out) {
2831
+ compareLeafSteps(L, R, segments, opts, out);
2832
+ const pairs = pairSteps(L.children, R.children);
2833
+ let ci = 0;
2834
+ for (const [lch, rch] of pairs) {
2835
+ if (lch !== void 0 && rch !== void 0) {
2836
+ compareRecursive(lch, rch, [...segments, pathSeg(lch, ci)], opts, out);
2837
+ } else if (lch !== void 0) {
2838
+ out.push({
2839
+ kind: "step-removed",
2840
+ severity: "warning",
2841
+ message: `Step only in left run: ${lch.name}`,
2842
+ path: buildPath([...segments, pathSeg(lch, ci)]),
2843
+ left: lch.id,
2844
+ right: void 0
2845
+ });
2846
+ } else if (rch !== void 0) {
2847
+ out.push({
2848
+ kind: "step-added",
2849
+ severity: "warning",
2850
+ message: `Step only in right run: ${rch.name}`,
2851
+ path: buildPath([...segments, pathSeg(rch, ci)]),
2852
+ left: void 0,
2853
+ right: rch.id
2854
+ });
2855
+ }
2856
+ ci += 1;
2874
2857
  }
2875
- return name;
2876
2858
  }
2877
- function eventEvidence(event, path18) {
2859
+ function mergeDiffDefaults(options) {
2878
2860
  return {
2879
- runId: event.runId,
2880
- eventId: event.eventId,
2881
- parentId: event.parentId,
2882
- traceId: event.trace?.traceId,
2883
- spanId: event.trace?.spanId,
2884
- kind: event.kind,
2885
- name: event.name,
2886
- status: event.status,
2887
- ...path18 ? { path: path18 } : {}
2861
+ ignoreDuration: false,
2862
+ durationThresholdMs: DEFAULT_THRESHOLD_MS,
2863
+ focus: "all",
2864
+ check: "all"
2888
2865
  };
2889
2866
  }
2890
- function runEvidence(run) {
2891
- return run ? [{ runId: run.runId, name: run.name, status: run.status }] : [];
2867
+ function kindMatchesFilter(kind, merged) {
2868
+ return true;
2892
2869
  }
2893
- function failFinding(ruleId, message, evidence, expected, actual, meta) {
2894
- return {
2895
- ruleId,
2896
- severity: meta?.severity ?? "error",
2897
- status: meta?.status ?? "fail",
2898
- message,
2899
- ...expected !== void 0 ? { expected } : {},
2900
- ...actual !== void 0 ? { actual } : {},
2901
- evidence: [...evidence],
2902
- ...{},
2903
- ...{},
2904
- ...{},
2905
- ...{}
2870
+ function diffRuns(left, right, options) {
2871
+ const merged = mergeDiffDefaults();
2872
+ const opts = {
2873
+ ignoreDuration: merged.ignoreDuration,
2874
+ durationThresholdMs: merged.durationThresholdMs
2906
2875
  };
2907
- }
2908
- function toolName(event) {
2909
- return resolveCanonicalToolName(event);
2910
- }
2911
- function semanticEvents(context) {
2912
- return context.logicalEvents ?? context.events;
2913
- }
2914
- function llmModel(event) {
2915
- const keys = ["model", "modelId", "responseModelId", "modelName", "model_name"];
2916
- return stringAttr(event, keys) ?? metadataStringAttr(event, keys) ?? stripPrefix(event.name, ["llm:", "generation:", "transcription:", "speech:"]);
2917
- }
2918
- function llmProvider(event) {
2919
- const keys = ["provider", "providerName", "provider_name"];
2920
- return stringAttr(event, keys) ?? metadataStringAttr(event, keys);
2921
- }
2922
- function llmFinishReason(event) {
2923
- const keys = ["finishReason", "rawFinishReason", "finish_reason"];
2924
- return stringAttr(event, keys) ?? metadataStringAttr(event, keys);
2925
- }
2926
- function finishedEvents(context, kind) {
2927
- return semanticEvents(context).filter(
2928
- (event) => (event.kind === kind) && event.status !== "running"
2929
- );
2930
- }
2931
- function toolInvocationEvents(context) {
2932
- return semanticEvents(context).filter((event) => event.kind === "TOOL");
2933
- }
2934
- function createRunStatusRule(options = {}) {
2935
- const expected = options.expected ?? "ok";
2936
- const allowIncomplete = options.allowIncomplete === true;
2937
- return {
2938
- id: "run.status",
2939
- category: "run",
2940
- defaultSeverity: "error",
2941
- evaluate(context) {
2942
- const findings = [];
2943
- const actual = context.selectedRun?.status ?? "unknown";
2944
- if (actual !== expected) {
2945
- findings.push(
2946
- failFinding(
2947
- "run.status",
2948
- `Run status ${actual} did not match expected ${expected}.`,
2949
- runEvidence(context.selectedRun),
2950
- expected,
2951
- actual
2952
- )
2953
- );
2954
- }
2955
- if (!allowIncomplete) {
2956
- const running = semanticEvents(context).filter((event) => event.status === "running");
2957
- if (running.length > 0) {
2958
- findings.push(
2959
- failFinding(
2960
- "run.status",
2961
- "Run contains incomplete running events.",
2962
- running.map((event) => eventEvidence(event)),
2963
- "no running events",
2964
- running.length
2965
- )
2966
- );
2967
- }
2968
- }
2969
- return findings;
2876
+ const raw = [];
2877
+ if ((left.status ?? "") !== (right.status ?? "")) {
2878
+ raw.push({
2879
+ kind: "run-status",
2880
+ severity: "warning",
2881
+ message: "Run completion status differs",
2882
+ left: left.status,
2883
+ right: right.status
2884
+ });
2885
+ }
2886
+ {
2887
+ const ld = left.durationMs;
2888
+ const rd = right.durationMs;
2889
+ const th = merged.durationThresholdMs;
2890
+ let differs = false;
2891
+ if (ld === void 0 && rd === void 0) differs = false;
2892
+ else if (ld === void 0 || rd === void 0) differs = true;
2893
+ else differs = Math.abs(ld - rd) > th;
2894
+ if (differs) {
2895
+ raw.push({
2896
+ kind: "duration",
2897
+ severity: "info",
2898
+ message: "Run duration differs",
2899
+ left: ld,
2900
+ right: rd
2901
+ });
2970
2902
  }
2971
- };
2972
- }
2973
- function createRunDurationRule(options) {
2974
- return {
2975
- id: "run.duration",
2976
- category: "run",
2977
- defaultSeverity: "error",
2978
- evaluate(context) {
2979
- const actual = context.selectedRun?.durationMs;
2980
- if (actual === void 0 || actual <= options.maxDurationMs) return [];
2981
- return [
2982
- failFinding(
2983
- "run.duration",
2984
- `Run duration ${actual}ms exceeded ${options.maxDurationMs}ms.`,
2985
- runEvidence(context.selectedRun),
2986
- { maxDurationMs: options.maxDurationMs },
2987
- actual
2988
- )
2989
- ];
2903
+ }
2904
+ const pairs = pairSteps(left.steps, right.steps);
2905
+ let idx = 0;
2906
+ for (const [ls, rs] of pairs) {
2907
+ if (ls !== void 0 && rs !== void 0) {
2908
+ compareRecursive(ls, rs, [pathSeg(ls, idx)], opts, raw);
2909
+ idx += 1;
2910
+ } else if (ls !== void 0) {
2911
+ raw.push({
2912
+ kind: "step-removed",
2913
+ severity: "warning",
2914
+ message: `Step only in left run: ${ls.name}`,
2915
+ path: buildPath([pathSeg(ls, idx)]),
2916
+ left: ls.id,
2917
+ right: void 0
2918
+ });
2919
+ idx += 1;
2920
+ } else if (rs !== void 0) {
2921
+ raw.push({
2922
+ kind: "step-added",
2923
+ severity: "warning",
2924
+ message: `Step only in right run: ${rs.name}`,
2925
+ path: buildPath([pathSeg(rs, idx)]),
2926
+ left: void 0,
2927
+ right: rs.id
2928
+ });
2929
+ idx += 1;
2990
2930
  }
2931
+ }
2932
+ const differences = raw.filter((d) => kindMatchesFilter(d.kind));
2933
+ let errors = 0;
2934
+ let warnings = 0;
2935
+ let info = 0;
2936
+ for (const d of differences) {
2937
+ if (d.severity === "error") errors += 1;
2938
+ else if (d.severity === "warning") warnings += 1;
2939
+ else info += 1;
2940
+ }
2941
+ const firstVisible = differences[0];
2942
+ const firstDivergence = firstVisible !== void 0 ? {
2943
+ kind: "first-divergence",
2944
+ severity: firstVisible.severity,
2945
+ message: `First divergence: ${firstVisible.message}`,
2946
+ path: firstVisible.path,
2947
+ left: firstVisible.left,
2948
+ right: firstVisible.right
2949
+ } : void 0;
2950
+ const summary = {
2951
+ leftRunId: left.runId,
2952
+ rightRunId: right.runId,
2953
+ totalDifferences: differences.length,
2954
+ errors,
2955
+ warnings,
2956
+ info,
2957
+ firstDivergence
2991
2958
  };
2959
+ return { summary, differences };
2992
2960
  }
2993
- function createToolUsageRule(options) {
2994
- return {
2995
- id: "tool.usage",
2996
- category: "tool",
2997
- defaultSeverity: "error",
2998
- evaluate(context) {
2999
- const tools = toolInvocationEvents(context);
3000
- const names = tools.map(toolName);
3001
- const nameSet = new Set(names);
3002
- const findings = [];
3003
- for (const required of options.required ?? []) {
3004
- if (!nameSet.has(required)) {
3005
- findings.push(
3006
- failFinding("tool.usage", `Required tool ${required} did not appear.`, runEvidence(context.selectedRun), required, names)
3007
- );
3008
- }
3009
- }
3010
- const forbidden = new Set(options.forbidden ?? []);
3011
- const allowed = options.allowed?.length ? new Set(options.allowed) : void 0;
3012
- for (const event of tools) {
3013
- const name = toolName(event);
3014
- if (forbidden.has(name)) {
3015
- findings.push(
3016
- failFinding("tool.usage", `Forbidden tool ${name} appeared.`, [eventEvidence(event)], "tool absent", name)
3017
- );
3018
- }
3019
- if (allowed && !allowed.has(name)) {
3020
- findings.push(
3021
- failFinding("tool.usage", `Tool ${name} is not in the allowed tool set.`, [eventEvidence(event)], [...allowed].sort(), name)
3022
- );
3023
- }
3024
- }
3025
- if (options.minCount !== void 0 && tools.length < options.minCount) {
3026
- findings.push(
3027
- failFinding("tool.usage", `Tool count ${tools.length} was below minimum ${options.minCount}.`, runEvidence(context.selectedRun), { minCount: options.minCount }, tools.length)
3028
- );
3029
- }
3030
- if (options.maxCount !== void 0 && tools.length > options.maxCount) {
3031
- findings.push(
3032
- failFinding("tool.usage", `Tool count ${tools.length} exceeded maximum ${options.maxCount}.`, tools.map((event) => eventEvidence(event)), { maxCount: options.maxCount }, tools.length)
3033
- );
3034
- }
3035
- return findings;
2961
+
2962
+ // packages/core/src/evidence/zip.ts
2963
+ (() => {
2964
+ const table = new Uint32Array(256);
2965
+ for (let n = 0; n < 256; n += 1) {
2966
+ let c = n;
2967
+ for (let k = 0; k < 8; k += 1) {
2968
+ c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
3036
2969
  }
3037
- };
2970
+ table[n] = c >>> 0;
2971
+ }
2972
+ return table;
2973
+ })();
2974
+
2975
+ // packages/core/src/suite/types.ts
2976
+ var DEFAULT_SUITE_CONFIG_NAMES = [
2977
+ "agent-inspect.suite.json",
2978
+ "agent-inspect.suite.js",
2979
+ "agent-inspect.suite.mjs",
2980
+ "agent-inspect.suite.cjs"
2981
+ ];
2982
+ function diagnostic2(code, message, severity = "error", caseId) {
2983
+ return { code, message, severity, ...{} };
3038
2984
  }
3039
- function createLlmUsageRule(options) {
3040
- return {
3041
- id: "llm.usage",
3042
- category: "llm",
3043
- defaultSeverity: "error",
3044
- evaluate(context) {
3045
- const llms = finishedEvents(context, "LLM");
3046
- const findings = [];
3047
- const allowedModels = options.allowedModels?.length ? new Set(options.allowedModels) : void 0;
3048
- const allowedProviders = options.allowedProviders?.length ? new Set(options.allowedProviders) : void 0;
3049
- const finishReasons = options.finishReasons?.length ? new Set(options.finishReasons) : void 0;
3050
- if (options.maxCalls !== void 0 && llms.length > options.maxCalls) {
3051
- findings.push(
3052
- failFinding(
3053
- "llm.usage",
3054
- `LLM call count ${llms.length} exceeded ${options.maxCalls}.`,
3055
- llms.map((event) => eventEvidence(event)),
3056
- { maxCalls: options.maxCalls },
3057
- llms.length
3058
- )
3059
- );
3060
- }
3061
- for (const event of llms) {
3062
- const model = llmModel(event);
3063
- const provider = llmProvider(event);
3064
- const finishReason = llmFinishReason(event);
3065
- if (allowedModels && (!model || !allowedModels.has(model))) {
3066
- findings.push(
3067
- failFinding("llm.usage", `LLM model ${model ?? "unknown"} is not allowed.`, [eventEvidence(event, "attributes.model")], [...allowedModels].sort(), model ?? "unknown")
3068
- );
3069
- }
3070
- if (allowedProviders && (!provider || !allowedProviders.has(provider))) {
3071
- findings.push(
3072
- failFinding("llm.usage", `LLM provider ${provider ?? "unknown"} is not allowed.`, [eventEvidence(event, "attributes.provider")], [...allowedProviders].sort(), provider ?? "unknown")
3073
- );
3074
- }
3075
- if (finishReasons && (!finishReason || !finishReasons.has(finishReason))) {
3076
- findings.push(
3077
- failFinding("llm.usage", `LLM finish reason ${finishReason ?? "unknown"} is not allowed.`, [eventEvidence(event, "attributes.finishReason")], [...finishReasons].sort(), finishReason ?? "unknown")
3078
- );
3079
- }
3080
- }
3081
- const tokenTotals = llms.reduce(
3082
- (totals, event) => ({
3083
- input: totals.input + (event.tokenUsage?.input ?? 0),
3084
- output: totals.output + (event.tokenUsage?.output ?? 0),
3085
- total: totals.total + (event.tokenUsage?.total ?? 0),
3086
- cached: totals.cached + (event.tokenUsage?.cached ?? 0)
3087
- }),
3088
- { input: 0, output: 0, total: 0, cached: 0 }
3089
- );
3090
- const tokenLimits = [
3091
- ["input", options.maxInputTokens],
3092
- ["output", options.maxOutputTokens],
3093
- ["total", options.maxTotalTokens],
3094
- ["cached", options.maxCachedTokens]
3095
- ];
3096
- for (const [key, limit] of tokenLimits) {
3097
- if (limit !== void 0 && tokenTotals[key] > limit) {
3098
- findings.push(
3099
- failFinding(
3100
- "llm.usage",
3101
- `LLM ${key} token count ${tokenTotals[key]} exceeded ${limit}.`,
3102
- llms.map((event) => eventEvidence(event, `tokenUsage.${key}`)),
3103
- { [`max${key[0].toUpperCase()}${key.slice(1)}Tokens`]: limit },
3104
- tokenTotals[key]
3105
- )
3106
- );
3107
- }
3108
- }
3109
- return findings;
3110
- }
3111
- };
2985
+ function asString(value, label) {
2986
+ if (value === void 0) return void 0;
2987
+ if (typeof value !== "string" || value.trim() === "") {
2988
+ throw new Error(`${label} must be a non-empty string.`);
2989
+ }
2990
+ return value.trim();
3112
2991
  }
3113
- function createObservedOutcomeRule(options = {}) {
3114
- const failOn = options.failOn ?? ["failed"];
3115
- const requireAny = options.requireAny === true;
3116
- return {
3117
- id: "outcome.status",
3118
- category: "run",
3119
- defaultSeverity: "error",
3120
- evaluate(context) {
3121
- const outcomes = extractOutcomesFromPersistedEvents(context.events);
3122
- if (requireAny && outcomes.length === 0) {
3123
- return [
3124
- failFinding(
3125
- "outcome.status",
3126
- "Expected at least one observed outcome.",
3127
- runEvidence(context.selectedRun),
3128
- { requireAny: true, expected: "at least one observed outcome" },
3129
- { code: "outcome.missing", actual: 0 }
3130
- )
3131
- ];
3132
- }
3133
- const matching = outcomesMatchingStatus(outcomes, failOn);
3134
- if (matching.length === 0) return [];
3135
- return [
3136
- failFinding(
3137
- "outcome.status",
3138
- `Observed outcome count ${matching.length} matched [${failOn.join(", ")}].`,
3139
- matching.map((outcome) => ({
3140
- runId: outcome.runId,
3141
- eventId: outcome.outcomeId,
3142
- ...outcome.parentId !== void 0 ? { parentId: outcome.parentId } : {},
3143
- kind: "OUTCOME",
3144
- name: outcome.name,
3145
- status: outcome.status,
3146
- path: `outcome.${outcome.name}`
3147
- })),
3148
- { failOn },
3149
- matching.map((outcome) => ({
3150
- name: outcome.name,
3151
- status: outcome.status,
3152
- expectation: outcome.expectation
3153
- }))
3154
- )
3155
- ];
2992
+ function asStringArray(value, label) {
2993
+ if (value === void 0) return void 0;
2994
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
2995
+ throw new Error(`${label} must be an array of strings.`);
2996
+ }
2997
+ return value;
2998
+ }
2999
+ function asPositiveNumber(value, label) {
3000
+ if (value === void 0) return void 0;
3001
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
3002
+ throw new Error(`${label} must be a non-negative number.`);
3003
+ }
3004
+ return value;
3005
+ }
3006
+ function validateCaseConfig(value, index) {
3007
+ const diagnostics = [];
3008
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
3009
+ diagnostics.push(
3010
+ diagnostic2("AI_SUITE_CONFIG_INVALID", `cases[${index}] must be an object.`)
3011
+ );
3012
+ return { diagnostics };
3013
+ }
3014
+ const raw = value;
3015
+ try {
3016
+ const id = asString(raw.id, `cases[${index}].id`);
3017
+ if (id === void 0) {
3018
+ diagnostics.push(
3019
+ diagnostic2("AI_SUITE_CONFIG_INVALID", `cases[${index}].id is required.`)
3020
+ );
3021
+ return { diagnostics };
3156
3022
  }
3157
- };
3023
+ const trace = asString(raw.trace, `cases[${index}].trace`);
3024
+ const runId = asString(raw.runId, `cases[${index}].runId`);
3025
+ const input = asString(raw.input, `cases[${index}].input`);
3026
+ return {
3027
+ caseConfig: {
3028
+ id,
3029
+ ...trace !== void 0 ? { trace } : {},
3030
+ ...runId !== void 0 ? { runId } : {},
3031
+ ...input !== void 0 ? { input } : {},
3032
+ ...asStringArray(raw.requireTools, `cases[${index}].requireTools`) !== void 0 ? { requireTools: asStringArray(raw.requireTools, `cases[${index}].requireTools`) } : {},
3033
+ ...asStringArray(raw.forbidTools, `cases[${index}].forbidTools`) !== void 0 ? { forbidTools: asStringArray(raw.forbidTools, `cases[${index}].forbidTools`) } : {},
3034
+ ...asPositiveNumber(raw.maxDurationMs, `cases[${index}].maxDurationMs`) !== void 0 ? {
3035
+ maxDurationMs: asPositiveNumber(
3036
+ raw.maxDurationMs,
3037
+ `cases[${index}].maxDurationMs`
3038
+ )
3039
+ } : {},
3040
+ ...asStringArray(
3041
+ raw.expectedObservations,
3042
+ `cases[${index}].expectedObservations`
3043
+ ) !== void 0 ? {
3044
+ expectedObservations: asStringArray(
3045
+ raw.expectedObservations,
3046
+ `cases[${index}].expectedObservations`
3047
+ )
3048
+ } : {}
3049
+ },
3050
+ diagnostics
3051
+ };
3052
+ } catch (error) {
3053
+ const message = error instanceof Error ? error.message : String(error);
3054
+ diagnostics.push(diagnostic2("AI_SUITE_CONFIG_INVALID", message));
3055
+ return { diagnostics };
3056
+ }
3158
3057
  }
3159
- function runTraceChecks(input, options = {}) {
3160
- const selected = resolveSelectedRun(input, options.runId);
3161
- if (selected.diagnostics.length > 0) {
3162
- return errorResult(input, selected.diagnostics, selected.run);
3058
+ function normalizeSuiteConfig(value) {
3059
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
3060
+ throw new Error("Suite config must export an object.");
3163
3061
  }
3164
- const rules = selectRules(options.rules ?? [], options.select);
3165
- if (rules.diagnostics.length > 0) {
3166
- return errorResult(input, rules.diagnostics, selected.run);
3062
+ const raw = value;
3063
+ const name = asString(raw.name, "name");
3064
+ const traces = asString(raw.traces, "traces");
3065
+ if (name === void 0) throw new Error("name is required.");
3066
+ if (traces === void 0) throw new Error("traces is required.");
3067
+ if (!Array.isArray(raw.cases) || raw.cases.length === 0) {
3068
+ throw new Error("cases must be a non-empty array.");
3167
3069
  }
3168
- if (rules.rules.length === 0) {
3169
- return errorResult(
3170
- input,
3171
- [
3172
- diagnostic3(
3173
- "AI_CHECK_NO_RULES_EVALUATED",
3174
- "No trace check rules were evaluated. Configure at least one rule, contract, or CLI check option."
3175
- )
3176
- ],
3177
- selected.run
3070
+ const cases = [];
3071
+ for (let index = 0; index < raw.cases.length; index += 1) {
3072
+ const { caseConfig, diagnostics } = validateCaseConfig(raw.cases[index], index);
3073
+ if (diagnostics.length > 0) {
3074
+ throw new Error(diagnostics.map((item) => item.message).join("; "));
3075
+ }
3076
+ if (caseConfig !== void 0) cases.push(caseConfig);
3077
+ }
3078
+ const ids = /* @__PURE__ */ new Set();
3079
+ for (const suiteCase of cases) {
3080
+ if (ids.has(suiteCase.id)) {
3081
+ throw new Error(`Duplicate case id "${suiteCase.id}".`);
3082
+ }
3083
+ ids.add(suiteCase.id);
3084
+ }
3085
+ const redactionProfile = raw.redactionProfile === "local" || raw.redactionProfile === "share" || raw.redactionProfile === "strict" ? raw.redactionProfile : void 0;
3086
+ if (raw.redactionProfile !== void 0 && redactionProfile === void 0) {
3087
+ throw new Error('redactionProfile must be "local", "share", or "strict".');
3088
+ }
3089
+ const config = { name, traces, cases };
3090
+ if (raw.checks !== void 0) {
3091
+ if (typeof raw.checks !== "object" || Array.isArray(raw.checks)) {
3092
+ throw new Error("checks must be an object.");
3093
+ }
3094
+ config.checks = raw.checks;
3095
+ }
3096
+ if (raw.eval !== void 0) {
3097
+ if (typeof raw.eval !== "object" || Array.isArray(raw.eval)) {
3098
+ throw new Error("eval must be an object.");
3099
+ }
3100
+ config.eval = raw.eval;
3101
+ }
3102
+ if (raw.artifacts !== void 0) {
3103
+ if (typeof raw.artifacts !== "object" || Array.isArray(raw.artifacts)) {
3104
+ throw new Error("artifacts must be an object.");
3105
+ }
3106
+ const outputDir = asString(
3107
+ raw.artifacts.outputDir,
3108
+ "artifacts.outputDir"
3178
3109
  );
3110
+ config.artifacts = outputDir !== void 0 ? { outputDir } : {};
3179
3111
  }
3180
- const facts = buildFacts(input, selected.run);
3181
- const context = {
3182
- ...facts,
3183
- ...selected.run ? { selectedRun: selected.run } : {},
3184
- ...input.sourceLabel ? { sourceLabel: input.sourceLabel } : {}
3185
- };
3186
- const diagnostics = [];
3187
- const findings = [];
3188
- const ruleExecutions = [];
3189
- for (const rule of rules.rules) {
3190
- try {
3191
- const ruleFindings = rule.evaluate(context).map((finding) => normalizeFinding(rule, finding));
3192
- findings.push(...ruleFindings);
3193
- ruleExecutions.push({
3194
- ruleId: rule.id,
3195
- category: rule.category,
3196
- status: classifyRuleExecution(ruleFindings, false),
3197
- findingCount: ruleFindings.length,
3198
- ...selected.run ? { runId: selected.run.runId } : {}
3199
- });
3200
- } catch (error) {
3201
- const message = error instanceof Error ? error.message : String(error);
3202
- diagnostics.push(
3203
- diagnostic3("AI_CHECK_INTERNAL_ERROR", `Rule ${rule.id} failed: ${message}`, rule.id)
3204
- );
3205
- ruleExecutions.push({
3206
- ruleId: rule.id,
3207
- category: rule.category,
3208
- status: "error",
3209
- findingCount: 0,
3210
- ...selected.run ? { runId: selected.run.runId } : {}
3211
- });
3112
+ if (raw.baseline !== void 0) {
3113
+ const baseline = asString(raw.baseline, "baseline");
3114
+ if (baseline !== void 0) config.baseline = baseline;
3115
+ }
3116
+ if (raw.candidate !== void 0) {
3117
+ const candidate = asString(raw.candidate, "candidate");
3118
+ if (candidate !== void 0) config.candidate = candidate;
3119
+ }
3120
+ if (redactionProfile !== void 0) config.redactionProfile = redactionProfile;
3121
+ return config;
3122
+ }
3123
+
3124
+ // packages/core/src/suite/load.ts
3125
+ var CONFIG_EXTENSIONS = /* @__PURE__ */ new Set([".json", ".js", ".mjs", ".cjs"]);
3126
+ var TS_CONFIG_EXTENSIONS = /* @__PURE__ */ new Set([".ts", ".mts", ".cts"]);
3127
+ function diagnostic3(code, message) {
3128
+ return { code, message, severity: "error" };
3129
+ }
3130
+ async function fileExists(filePath) {
3131
+ try {
3132
+ await promises.access(filePath);
3133
+ return true;
3134
+ } catch {
3135
+ return false;
3136
+ }
3137
+ }
3138
+ async function resolveSuiteConfigPath(options = {}) {
3139
+ const cwd = path15__default.default.resolve(options.cwd ?? process.cwd());
3140
+ if (options.configPath !== void 0 && options.configPath.trim() !== "") {
3141
+ return path15__default.default.resolve(cwd, options.configPath.trim());
3142
+ }
3143
+ for (const name of DEFAULT_SUITE_CONFIG_NAMES) {
3144
+ const candidate = path15__default.default.join(cwd, name);
3145
+ if (await fileExists(candidate)) return candidate;
3146
+ }
3147
+ throw new Error(
3148
+ `No suite config found. Create one with \`agent-inspect suite init\` or pass --config.`
3149
+ );
3150
+ }
3151
+ async function loadSuiteConfig(options = {}) {
3152
+ let configPath;
3153
+ try {
3154
+ configPath = await resolveSuiteConfigPath(options);
3155
+ } catch (error) {
3156
+ const message = error instanceof Error ? error.message : String(error);
3157
+ throw Object.assign(new Error(message), {
3158
+ diagnostics: [diagnostic3("AI_SUITE_CONFIG_LOAD_FAILED", message)]
3159
+ });
3160
+ }
3161
+ const extension = path15__default.default.extname(configPath);
3162
+ if (TS_CONFIG_EXTENSIONS.has(extension)) {
3163
+ const message = "TypeScript suite configs require an explicit precompiled JavaScript config or future --config-loader support.";
3164
+ throw Object.assign(new Error(message), {
3165
+ diagnostics: [diagnostic3("AI_SUITE_CONFIG_LOAD_FAILED", message)]
3166
+ });
3167
+ }
3168
+ if (!CONFIG_EXTENSIONS.has(extension)) {
3169
+ const message = "Unsupported suite config extension. Use .json, .js, .mjs, or .cjs.";
3170
+ throw Object.assign(new Error(message), {
3171
+ diagnostics: [diagnostic3("AI_SUITE_CONFIG_LOAD_FAILED", message)]
3172
+ });
3173
+ }
3174
+ try {
3175
+ let raw;
3176
+ if (extension === ".json") {
3177
+ raw = JSON.parse(await promises.readFile(configPath, "utf-8"));
3178
+ } else {
3179
+ const mod = await import(url.pathToFileURL(configPath).href);
3180
+ raw = "default" in mod ? mod.default : mod;
3212
3181
  }
3182
+ const config = normalizeSuiteConfig(raw);
3183
+ return {
3184
+ config,
3185
+ configPath,
3186
+ configDir: path15__default.default.dirname(configPath)
3187
+ };
3188
+ } catch (error) {
3189
+ const message = error instanceof Error ? error.message : String(error);
3190
+ throw Object.assign(new Error(message), {
3191
+ diagnostics: [diagnostic3("AI_SUITE_CONFIG_LOAD_FAILED", message)]
3192
+ });
3213
3193
  }
3214
- if (diagnostics.length > 0) {
3215
- return errorResult(input, diagnostics, selected.run, ruleExecutions);
3194
+ }
3195
+ async function exists(filePath) {
3196
+ try {
3197
+ await promises.access(filePath);
3198
+ return true;
3199
+ } catch {
3200
+ return false;
3201
+ }
3202
+ }
3203
+ async function resolveSuiteCaseTrace(suiteCase, options) {
3204
+ if (suiteCase.trace !== void 0) {
3205
+ const tracePath = path15__default.default.resolve(options.configDir, suiteCase.trace);
3206
+ if (await exists(tracePath)) {
3207
+ return { caseId: suiteCase.id, tracePath, missing: false };
3208
+ }
3209
+ return {
3210
+ caseId: suiteCase.id,
3211
+ tracePath,
3212
+ missing: true,
3213
+ reason: `trace file not found: ${suiteCase.trace}`
3214
+ };
3215
+ }
3216
+ const runKey = suiteCase.runId ?? suiteCase.id;
3217
+ const directPath = getTraceFilePath(runKey, options.tracesDir);
3218
+ if (await exists(directPath)) {
3219
+ return { caseId: suiteCase.id, tracePath: directPath, runId: runKey, missing: false };
3220
+ }
3221
+ const nestedPath = path15__default.default.join(options.tracesDir, `${path15__default.default.basename(runKey)}.jsonl`);
3222
+ if (await exists(nestedPath)) {
3223
+ return { caseId: suiteCase.id, tracePath: nestedPath, runId: runKey, missing: false };
3216
3224
  }
3217
- const eventById = new Map(input.read.events.map((event) => [event.eventId, event]));
3218
- const sortedFindings = findings.sort(compareFindings(eventById));
3219
- const summary = summarize(sortedFindings, diagnostics, ruleExecutions.length);
3220
- const status = summary.failed > 0 ? "fail" : "pass";
3221
3225
  return {
3222
- ok: status === "pass",
3223
- status,
3224
- format: input.read.format,
3225
- ...selected.run ? { runId: selected.run.runId } : {},
3226
- summary,
3227
- findings: sortedFindings,
3228
- diagnostics,
3229
- ruleExecutions
3226
+ caseId: suiteCase.id,
3227
+ runId: runKey,
3228
+ missing: true,
3229
+ reason: `no trace found for run id "${runKey}" under ${options.tracesDir}`
3230
3230
  };
3231
3231
  }
3232
3232