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