token-harness 0.1.26 → 0.1.28

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.
Files changed (4) hide show
  1. package/README.md +132 -443
  2. package/package.json +1 -1
  3. package/sbom.json +3 -3
  4. package/token-harness.mjs +1176 -269
package/token-harness.mjs CHANGED
@@ -70,7 +70,7 @@ function assessMcpServer(server) {
70
70
  const status = [server.runtimeStatus, server.authStatus].filter((value3) => value3 !== null).join(" ").toLowerCase();
71
71
  const usability = status.includes("disabled") ? "disabled" : /fail|error|needs authentication|authenticationrequired|unauthenticated/.test(status) ? "attention" : /connected|running|ready/.test(status) ? "usable" : "unknown";
72
72
  const action = usability === "attention" ? "fix-or-disable-if-unneeded" : exposure === "high" ? "review-exposure" : "none";
73
- const reason3 = usability === "attention" ? "the server is not currently usable; task relevance is still unknown" : exposure === "high" ? "the server exposes at least 20 known tools; usage and task relevance are not observed" : exposure === "moderate" ? "the server exposes 10-19 known tools; usage and task relevance are not observed" : exposure === "low" ? "the server exposes fewer than 10 known tools; usage and task relevance are not observed" : "tool exposure is unknown; usage and task relevance are not observed";
73
+ const reason4 = usability === "attention" ? "the server is not currently usable; task relevance is still unknown" : exposure === "high" ? "the server exposes at least 20 known tools; usage and task relevance are not observed" : exposure === "moderate" ? "the server exposes 10-19 known tools; usage and task relevance are not observed" : exposure === "low" ? "the server exposes fewer than 10 known tools; usage and task relevance are not observed" : "tool exposure is unknown; usage and task relevance are not observed";
74
74
  return {
75
75
  harnessId: server.harnessId,
76
76
  name: server.name,
@@ -79,7 +79,7 @@ function assessMcpServer(server) {
79
79
  usability,
80
80
  action,
81
81
  hasRemovalEvidence: false,
82
- reason: reason3
82
+ reason: reason4
83
83
  };
84
84
  }
85
85
  function benchmarkPolicySnapshot(observation) {
@@ -434,12 +434,12 @@ function assessWindowPace(window, now, reservePercent) {
434
434
  spendableRemainingPercent: null,
435
435
  spendablePercentPerHour: null
436
436
  };
437
- const unknown = (reason3) => ({
437
+ const unknown = (reason4) => ({
438
438
  ...base,
439
439
  state: "unknown",
440
440
  targetUsedPercent: null,
441
441
  minutesToReset: null,
442
- reason: reason3
442
+ reason: reason4
443
443
  });
444
444
  if (window.confidence === "cached" || window.confidence === "estimated") {
445
445
  return unknown("cached or estimated usage is displayed but not used for live pacing");
@@ -1531,6 +1531,264 @@ var init_context_governor = __esm({
1531
1531
  });
1532
1532
 
1533
1533
  // packages/core/dist/src/domain/efficiency-decision.js
1534
+ function reason(code, summary) {
1535
+ return { code, summary };
1536
+ }
1537
+ function isEfficiencyHarness(value3) {
1538
+ return value3 === "claude" || value3 === "codex";
1539
+ }
1540
+ function uniqueSorted(items) {
1541
+ const unique = /* @__PURE__ */ new Map();
1542
+ for (const item of items)
1543
+ unique.set(`${item.code}\0${item.summary}`, item);
1544
+ return [...unique.values()].sort((left, right) => left.code.localeCompare(right.code) || left.summary.localeCompare(right.summary));
1545
+ }
1546
+ function uniqueSortedEvidence(items) {
1547
+ const unique = /* @__PURE__ */ new Map();
1548
+ for (const item of items) {
1549
+ unique.set(`${item.source}\0${item.code}\0${item.summary}`, item);
1550
+ }
1551
+ return [...unique.values()].sort((left, right) => left.source.localeCompare(right.source) || left.code.localeCompare(right.code) || left.summary.localeCompare(right.summary));
1552
+ }
1553
+ function addEvidence(target, source, items) {
1554
+ for (const item of items)
1555
+ target.push({ source, ...item });
1556
+ }
1557
+ function chooseHarness(input, evidence4, reasons) {
1558
+ const scheduler = input.scheduler;
1559
+ if (scheduler === null || scheduler === void 0) {
1560
+ reasons.push(reason("efficiency-harness-kept", "No compatible scheduler decision was supplied; keep the current harness"));
1561
+ return input.currentHarness;
1562
+ }
1563
+ addEvidence(evidence4, "scheduler", scheduler.reasons);
1564
+ if (scheduler.taskClass !== input.taskClass || scheduler.currentHarness !== input.currentHarness || !isEfficiencyHarness(scheduler.candidateHarness)) {
1565
+ reasons.push(reason("efficiency-scheduler-mismatch", "Scheduler evidence does not match this harness and task-class snapshot; keep the current harness"));
1566
+ return input.currentHarness;
1567
+ }
1568
+ if (scheduler.decision !== "switch") {
1569
+ reasons.push(reason(scheduler.decision === "stay" ? "efficiency-scheduler-stay" : "efficiency-scheduler-unknown", scheduler.decision === "stay" ? "The existing scheduler recommends keeping the current harness" : "The existing scheduler lacks evidence for a cross-harness recommendation"));
1570
+ return input.currentHarness;
1571
+ }
1572
+ const candidate = scheduler.candidateHarness;
1573
+ const advice = input.optimization.filter((item) => item.harnessId === candidate);
1574
+ if (advice.length !== 1 || advice[0].state === "absent" || advice[0].state === "unavailable") {
1575
+ reasons.push(reason("efficiency-candidate-policy-unavailable", "The scheduler recommends the candidate, but one usable candidate policy snapshot is not available; keep the current harness"));
1576
+ return input.currentHarness;
1577
+ }
1578
+ reasons.push(reason("efficiency-scheduler-switch-advised", "The evidence-backed scheduler recommends the candidate harness; this decision remains read-only"));
1579
+ return candidate;
1580
+ }
1581
+ function chooseContextAction(advice, contextGovernorAction) {
1582
+ if (advice.state === "absent" || advice.state === "unavailable")
1583
+ return "unknown";
1584
+ if (advice.budgetDecision?.state === "wait-for-reset" && advice.budgetDecision.reasons.length > 0 || advice.workloadCoverage?.state === "exhausted" && advice.workloadCoverage.reasons.length > 0 || advice.workloadCoverage?.state === "shortfall" && advice.workloadCoverage.reasons.length > 0) {
1585
+ return "checkpoint";
1586
+ }
1587
+ if (contextGovernorAction !== null)
1588
+ return contextGovernorAction;
1589
+ if (advice.contextPressure === "low")
1590
+ return "keep";
1591
+ return "unknown";
1592
+ }
1593
+ function contextGovernorForHarness(input, harness, reasons) {
1594
+ const snapshot = input.contextGovernor;
1595
+ if (snapshot === null || snapshot === void 0)
1596
+ return null;
1597
+ if (snapshot.harnessId !== harness) {
1598
+ reasons.push(reason("efficiency-context-governor-harness-mismatch", "Ignore context material evidence because it belongs to a different harness snapshot"));
1599
+ return null;
1600
+ }
1601
+ return decideContextGovernor(snapshot);
1602
+ }
1603
+ function contextActionSummary(action) {
1604
+ switch (action) {
1605
+ case "keep":
1606
+ return "Keep the observed context because no safer item-level reduction is supported";
1607
+ case "mask":
1608
+ return "Deterministically mask explicitly superseded tool or repository output";
1609
+ case "summarize":
1610
+ return "Condense durable material only where no reducer has already summarized it";
1611
+ case "compact":
1612
+ return "Compact durable state for the continuing task within its configured byte budget";
1613
+ case "checkpoint":
1614
+ return "Preserve durable task state before an observed allowance, reset or task boundary";
1615
+ case "fresh-session":
1616
+ return "Start a fresh session at the evidenced task boundary";
1617
+ case "unknown":
1618
+ return "Context evidence is incomplete; do not invent a cleanup action";
1619
+ }
1620
+ }
1621
+ function recommendationEvidence(advice, area, target) {
1622
+ return advice.recommendations.filter((item) => item.area === area && item.target === target).flatMap((item) => item.evidence);
1623
+ }
1624
+ function hasLearnedControlEvidence(advice, area, current, recommended, support) {
1625
+ const codes = new Set(support.map((item) => item.code));
1626
+ if (area === "model") {
1627
+ const learning2 = advice.modelLearning;
1628
+ return learning2?.state === "learned" && learning2.baseModel === current && learning2.candidateModel === recommended && learning2.recommendedModel === recommended && learning2.policy.reasoningEffort === advice.currentEffort && learning2.policy.verbosity === advice.currentVerbosity && (codes.has("model-allowance-throughput-improved") || codes.has("model-quality-recovery-with-capacity"));
1629
+ }
1630
+ const learning = advice.verbosityLearning;
1631
+ return learning?.state === "learned" && learning.baseVerbosity === current && learning.candidateVerbosity === recommended && learning.recommendedVerbosity === recommended && learning.policy.model === advice.currentModel && learning.policy.reasoningEffort === advice.currentEffort && (codes.has("verbosity-allowance-throughput-improved") || codes.has("verbosity-quality-recovery-with-capacity") || codes.has("verbosity-quality-recovery-capacity-unproven"));
1632
+ }
1633
+ function choosePolicy(advice, choices, taskClass, contextAction, evidence4, reasons) {
1634
+ const selected = Object.fromEntries(choices.map((choice) => [choice.area, choice.current]));
1635
+ if (choices.filter((choice) => choice.recommended !== null && choice.recommended !== choice.current).length > 1) {
1636
+ reasons.push(reason("efficiency-single-control-guard", "Keep the observed policy because more than one native control would change at once"));
1637
+ return selected;
1638
+ }
1639
+ const supportedChanges = choices.filter((choice) => {
1640
+ if (choice.recommended === null || choice.recommended === choice.current)
1641
+ return false;
1642
+ const support = recommendationEvidence(advice, choice.area, choice.recommended);
1643
+ if (support.length === 0) {
1644
+ reasons.push(reason(`efficiency-${choice.area}-evidence-missing`, `Keep the current ${choice.area} because the recommendation has no attributable evidence`));
1645
+ return false;
1646
+ }
1647
+ if ((choice.area === "model" || choice.area === "verbosity") && !hasLearnedControlEvidence(advice, choice.area, choice.current, choice.recommended, support)) {
1648
+ reasons.push(reason(`efficiency-${choice.area}-learning-unproven`, `Keep the current ${choice.area} because the exact single-control learning gate is not evidenced`));
1649
+ return false;
1650
+ }
1651
+ addEvidence(evidence4, "optimizer", support);
1652
+ return true;
1653
+ });
1654
+ const change = supportedChanges[0];
1655
+ if (change === void 0)
1656
+ return selected;
1657
+ if (change.area === "reasoning") {
1658
+ const recommendedRank = effortRank(change.recommended);
1659
+ const floorRank = effortRank(taskEffortFloor(taskClass));
1660
+ if (recommendedRank !== null && floorRank !== null && recommendedRank < floorRank) {
1661
+ reasons.push(reason("efficiency-quality-floor-protected", "Keep the observed reasoning effort because the recommendation falls below the task quality floor"));
1662
+ return selected;
1663
+ }
1664
+ const currentRank = effortRank(change.current);
1665
+ if (contextAction !== "keep" && currentRank !== null && recommendedRank !== null && recommendedRank > currentRank && advice.budgetDecision?.allowEffortIncrease === true) {
1666
+ reasons.push(reason("efficiency-context-before-quota-escalation", "Keep the observed reasoning effort until the recommended context action is completed"));
1667
+ return selected;
1668
+ }
1669
+ }
1670
+ selected[change.area] = change.recommended;
1671
+ reasons.push(reason(`efficiency-${change.area}-selected`, `Use the existing evidence-backed ${change.area} recommendation as the single policy change`));
1672
+ return selected;
1673
+ }
1674
+ function exactCapacityBudget(input, harness, policy, evidence4, reasons) {
1675
+ const empty2 = { fiveHourPercent: null, weeklyPercent: null };
1676
+ const matches = (input.capacities ?? []).filter((item) => item.harnessId === harness && item.taskClass === input.taskClass && item.policy !== void 0 && item.policy.model === policy.model && item.policy.reasoningEffort === policy.reasoningEffort && item.policy.verbosity === policy.verbosity);
1677
+ if (matches.length !== 1) {
1678
+ reasons.push(reason(matches.length === 0 ? "efficiency-task-budget-unknown" : "efficiency-task-budget-ambiguous", matches.length === 0 ? "Exact-policy accepted-task capacity is unavailable; task allowance budgets remain unknown" : "Multiple exact-policy capacity estimates were supplied; task allowance budgets remain unknown"));
1679
+ return empty2;
1680
+ }
1681
+ const capacity = matches[0];
1682
+ const fiveHour = capacity.fiveHour.p75UsedPercentPerAcceptedTask;
1683
+ const weekly = capacity.weekly.p75UsedPercentPerAcceptedTask;
1684
+ const valid = (value3) => value3 !== null && Number.isFinite(value3) && value3 > 0 && value3 <= 100;
1685
+ const fiveHourSpendable = capacity.fiveHour.spendableRemainingPercent;
1686
+ const weeklySpendable = capacity.weekly.spendableRemainingPercent;
1687
+ if (capacity.status !== "estimated" || !valid(fiveHour) || !valid(weekly) || fiveHourSpendable === null || !Number.isFinite(fiveHourSpendable) || fiveHourSpendable < fiveHour || weeklySpendable === null || !Number.isFinite(weeklySpendable) || weeklySpendable < weekly) {
1688
+ addEvidence(evidence4, "capacity", capacity.reasons.map((summary, index) => ({
1689
+ code: `capacity-reason-${String(index + 1)}`,
1690
+ summary
1691
+ })));
1692
+ reasons.push(reason("efficiency-task-budget-unknown", "Complete exact-policy task cost must fit within both observed spendable allowances after reserve"));
1693
+ return empty2;
1694
+ }
1695
+ evidence4.push({
1696
+ source: "capacity",
1697
+ code: "exact-policy-task-cost",
1698
+ summary: `Accepted-task p75 cost is ${String(fiveHour)}% five-hour and ${String(weekly)}% weekly at the selected model/effort/verbosity policy`
1699
+ });
1700
+ for (const window of [capacity.fiveHour, capacity.weekly]) {
1701
+ for (const receiptId of window.receiptIds ?? [])
1702
+ evidence4.push({
1703
+ source: "capacity",
1704
+ code: `capacity-receipt-${window.scope}`,
1705
+ summary: receiptId
1706
+ });
1707
+ }
1708
+ reasons.push(reason("efficiency-task-budget-evidenced", "Keep five-hour and weekly task budgets separate at their exact-policy empirical p75 costs"));
1709
+ return { fiveHourPercent: fiveHour, weeklyPercent: weekly };
1710
+ }
1711
+ function attemptBudget(input, evidence4, reasons) {
1712
+ const budget = input.attemptBudget;
1713
+ if (budget === null || budget === void 0 || !Number.isSafeInteger(budget.maxAttempts) || budget.maxAttempts < 1 || !Number.isSafeInteger(budget.premiumEscalations) || budget.premiumEscalations < 0 || budget.premiumEscalations >= budget.maxAttempts || budget.evidence.length === 0) {
1714
+ reasons.push(reason("efficiency-attempt-budget-unknown", "No reviewed evidence-backed attempt and premium-escalation budget is available"));
1715
+ return { maxAttempts: null, premiumEscalationBudget: null };
1716
+ }
1717
+ addEvidence(evidence4, "attempt-budget", budget.evidence);
1718
+ reasons.push(reason("efficiency-attempt-budget-evidenced", "Use the supplied evidence-backed attempt and premium-escalation ceilings"));
1719
+ return {
1720
+ maxAttempts: budget.maxAttempts,
1721
+ premiumEscalationBudget: budget.premiumEscalations
1722
+ };
1723
+ }
1724
+ function decideEfficiency(input) {
1725
+ const evidence4 = [];
1726
+ const reasons = [];
1727
+ const harness = chooseHarness(input, evidence4, reasons);
1728
+ const matchingAdvice = input.optimization.filter((item) => item.harnessId === harness);
1729
+ const advice = matchingAdvice.length === 1 ? matchingAdvice[0] : null;
1730
+ const contextGovernor = contextGovernorForHarness(input, harness, reasons);
1731
+ if (contextGovernor !== null)
1732
+ addEvidence(evidence4, "context", contextGovernor.evidence);
1733
+ if (advice === null || advice.state === "absent" || advice.state === "unavailable") {
1734
+ reasons.push(reason(advice !== null ? "efficiency-optimizer-evidence-unavailable" : matchingAdvice.length === 0 ? "efficiency-optimizer-evidence-missing" : "efficiency-optimizer-evidence-ambiguous", "One optimizer snapshot is required for the selected harness; policy remains unknown and context uses only its separate evidence"));
1735
+ const contextAction2 = contextGovernor?.action ?? "unknown";
1736
+ reasons.push(reason(`efficiency-context-${contextAction2}`, contextActionSummary(contextAction2)));
1737
+ const attempts2 = attemptBudget(input, evidence4, reasons);
1738
+ return {
1739
+ harness,
1740
+ taskClass: input.taskClass,
1741
+ model: null,
1742
+ reasoningEffort: null,
1743
+ verbosity: null,
1744
+ contextAction: contextAction2,
1745
+ contextGovernor,
1746
+ allowanceBudget: { fiveHourPercent: null, weeklyPercent: null },
1747
+ ...attempts2,
1748
+ evidence: uniqueSortedEvidence(evidence4),
1749
+ reasons: uniqueSorted(reasons)
1750
+ };
1751
+ }
1752
+ addEvidence(evidence4, "budget", advice.budgetDecision?.reasons ?? []);
1753
+ addEvidence(evidence4, "capacity", advice.workloadCoverage?.reasons ?? []);
1754
+ const contextEvidence2 = advice.recommendations.filter((item) => item.area === "context" || item.area === "session").flatMap((item) => item.evidence);
1755
+ const contextAction = chooseContextAction(advice, contextGovernor?.action ?? null);
1756
+ addEvidence(evidence4, "context", contextEvidence2);
1757
+ reasons.push(reason(`efficiency-context-${contextAction}`, contextActionSummary(contextAction)));
1758
+ const policy = choosePolicy(advice, [
1759
+ { area: "model", current: advice.currentModel, recommended: advice.recommendedModel },
1760
+ { area: "reasoning", current: advice.currentEffort, recommended: advice.recommendedEffort },
1761
+ {
1762
+ area: "verbosity",
1763
+ current: advice.currentVerbosity,
1764
+ recommended: advice.recommendedVerbosity
1765
+ }
1766
+ ], input.taskClass, contextAction, evidence4, reasons);
1767
+ const selectedRank = effortRank(policy.reasoning);
1768
+ const floorRank = effortRank(taskEffortFloor(input.taskClass));
1769
+ if (selectedRank !== null && floorRank !== null && selectedRank < floorRank) {
1770
+ policy.reasoning = null;
1771
+ reasons.push(reason("efficiency-observed-effort-below-floor", "Neither the observed effort nor a supported recommendation establishes the task quality floor"));
1772
+ }
1773
+ const selectedPolicy = {
1774
+ model: policy.model,
1775
+ reasoningEffort: policy.reasoning,
1776
+ verbosity: policy.verbosity
1777
+ };
1778
+ const allowanceBudget = exactCapacityBudget(input, harness, selectedPolicy, evidence4, reasons);
1779
+ const attempts = attemptBudget(input, evidence4, reasons);
1780
+ return {
1781
+ harness,
1782
+ taskClass: input.taskClass,
1783
+ ...selectedPolicy,
1784
+ contextAction,
1785
+ contextGovernor,
1786
+ allowanceBudget,
1787
+ ...attempts,
1788
+ evidence: uniqueSortedEvidence(evidence4),
1789
+ reasons: uniqueSorted(reasons)
1790
+ };
1791
+ }
1534
1792
  var init_efficiency_decision = __esm({
1535
1793
  "packages/core/dist/src/domain/efficiency-decision.js"() {
1536
1794
  "use strict";
@@ -1708,7 +1966,7 @@ var init_cross_harness_quality = __esm({
1708
1966
  });
1709
1967
 
1710
1968
  // packages/core/dist/src/domain/cross-harness-scheduler.js
1711
- function reason(code, summary) {
1969
+ function reason2(code, summary) {
1712
1970
  return { code, summary };
1713
1971
  }
1714
1972
  function hasPressure(evidence4, tasksRemaining) {
@@ -1720,24 +1978,24 @@ function hasSafeHeadroom(evidence4, tasksRemaining) {
1720
1978
  }
1721
1979
  function validateTransfer(transfer) {
1722
1980
  if (!Number.isInteger(transfer.handoffBytes) || transfer.handoffBytes < 0 || !Number.isInteger(transfer.maxHandoffBytes) || transfer.maxHandoffBytes <= 0) {
1723
- return reason("invalid-transfer-evidence", "handoff byte evidence is invalid");
1981
+ return reason2("invalid-transfer-evidence", "handoff byte evidence is invalid");
1724
1982
  }
1725
1983
  if (transfer.handoffBytes > transfer.maxHandoffBytes) {
1726
- return reason("handoff-over-budget", `compact handoff is ${transfer.handoffBytes} bytes, above the ${transfer.maxHandoffBytes}-byte transfer budget`);
1984
+ return reason2("handoff-over-budget", `compact handoff is ${transfer.handoffBytes} bytes, above the ${transfer.maxHandoffBytes}-byte transfer budget`);
1727
1985
  }
1728
1986
  return null;
1729
1987
  }
1730
1988
  function validateQuality(evidence4, taskClass) {
1731
1989
  if (!Number.isInteger(evidence4.qualitySamples) || evidence4.qualitySamples < 0) {
1732
- return reason("invalid-quality-evidence", "quality sample count is invalid");
1990
+ return reason2("invalid-quality-evidence", "quality sample count is invalid");
1733
1991
  }
1734
1992
  if (evidence4.quality === "unknown")
1735
1993
  return null;
1736
1994
  if (evidence4.qualitySamples < 1 || evidence4.qualityTaskClass === null) {
1737
- return reason("candidate-quality-unattributed", "candidate quality evidence is not attributable to a measured task class");
1995
+ return reason2("candidate-quality-unattributed", "candidate quality evidence is not attributable to a measured task class");
1738
1996
  }
1739
1997
  if (evidence4.qualityTaskClass !== taskClass) {
1740
- return reason("candidate-quality-task-mismatch", `candidate quality evidence covers ${evidence4.qualityTaskClass}, not ${taskClass}`);
1998
+ return reason2("candidate-quality-task-mismatch", `candidate quality evidence covers ${evidence4.qualityTaskClass}, not ${taskClass}`);
1741
1999
  }
1742
2000
  return null;
1743
2001
  }
@@ -1746,7 +2004,7 @@ function validateCapacity(evidence4, subject) {
1746
2004
  if (value3 === void 0 || value3 === null)
1747
2005
  return null;
1748
2006
  if (!Number.isInteger(value3) || value3 < 0) {
1749
- return reason("invalid-capacity-evidence", `${subject} accepted-task capacity must be a non-negative whole number when present`);
2007
+ return reason2("invalid-capacity-evidence", `${subject} accepted-task capacity must be a non-negative whole number when present`);
1750
2008
  }
1751
2009
  return null;
1752
2010
  }
@@ -1762,7 +2020,7 @@ function scheduleCrossHarness(input) {
1762
2020
  return {
1763
2021
  ...base,
1764
2022
  decision: "stay",
1765
- reasons: [reason("same-harness", "the candidate is the current harness")]
2023
+ reasons: [reason2("same-harness", "the candidate is the current harness")]
1766
2024
  };
1767
2025
  }
1768
2026
  const transferProblem = validateTransfer(input.transfer);
@@ -1777,7 +2035,7 @@ function scheduleCrossHarness(input) {
1777
2035
  return {
1778
2036
  ...base,
1779
2037
  decision: "stay",
1780
- reasons: [reason("candidate-unavailable", "the candidate harness is not currently usable")]
2038
+ reasons: [reason2("candidate-unavailable", "the candidate harness is not currently usable")]
1781
2039
  };
1782
2040
  }
1783
2041
  if (tasksRemaining !== null && (!Number.isSafeInteger(tasksRemaining) || tasksRemaining <= 0)) {
@@ -1785,7 +2043,7 @@ function scheduleCrossHarness(input) {
1785
2043
  ...base,
1786
2044
  decision: "insufficient-evidence",
1787
2045
  reasons: [
1788
- reason("invalid-workload-target", "remaining workload must be a positive whole number of accepted tasks")
2046
+ reason2("invalid-workload-target", "remaining workload must be a positive whole number of accepted tasks")
1789
2047
  ]
1790
2048
  };
1791
2049
  }
@@ -1811,7 +2069,7 @@ function scheduleCrossHarness(input) {
1811
2069
  ...base,
1812
2070
  decision: "stay",
1813
2071
  reasons: [
1814
- reason("candidate-quality-failed", "quality-gated evidence rejects the candidate for this task class")
2072
+ reason2("candidate-quality-failed", "quality-gated evidence rejects the candidate for this task class")
1815
2073
  ]
1816
2074
  };
1817
2075
  }
@@ -1821,7 +2079,7 @@ function scheduleCrossHarness(input) {
1821
2079
  ...base,
1822
2080
  decision: "insufficient-evidence",
1823
2081
  reasons: [
1824
- reason("current-workload-capacity-unknown", "current harness capacity for the stated remaining workload is unknown")
2082
+ reason2("current-workload-capacity-unknown", "current harness capacity for the stated remaining workload is unknown")
1825
2083
  ]
1826
2084
  };
1827
2085
  }
@@ -1830,14 +2088,14 @@ function scheduleCrossHarness(input) {
1830
2088
  ...base,
1831
2089
  decision: "insufficient-evidence",
1832
2090
  reasons: [
1833
- reason("current-quota-unknown", "current harness allowance pressure is not known well enough to justify a switch")
2091
+ reason2("current-quota-unknown", "current harness allowance pressure is not known well enough to justify a switch")
1834
2092
  ]
1835
2093
  };
1836
2094
  }
1837
2095
  return {
1838
2096
  ...base,
1839
2097
  decision: "stay",
1840
- reasons: [reason("current-headroom-healthy", "the current harness is not over pace")]
2098
+ reasons: [reason2("current-headroom-healthy", "the current harness is not over pace")]
1841
2099
  };
1842
2100
  }
1843
2101
  if (!hasSafeHeadroom(input.candidate, tasksRemaining)) {
@@ -1846,7 +2104,7 @@ function scheduleCrossHarness(input) {
1846
2104
  ...base,
1847
2105
  decision: "insufficient-evidence",
1848
2106
  reasons: [
1849
- reason("candidate-workload-capacity-unknown", "candidate capacity for the stated remaining workload is unknown")
2107
+ reason2("candidate-workload-capacity-unknown", "candidate capacity for the stated remaining workload is unknown")
1850
2108
  ]
1851
2109
  };
1852
2110
  }
@@ -1855,7 +2113,7 @@ function scheduleCrossHarness(input) {
1855
2113
  ...base,
1856
2114
  decision: "stay",
1857
2115
  reasons: [
1858
- reason("candidate-capacity-below-workload", `candidate has ${String(input.candidate.acceptedTasksRemaining)} accepted-task equivalents for ${String(tasksRemaining)} stated task(s)`)
2116
+ reason2("candidate-capacity-below-workload", `candidate has ${String(input.candidate.acceptedTasksRemaining)} accepted-task equivalents for ${String(tasksRemaining)} stated task(s)`)
1859
2117
  ]
1860
2118
  };
1861
2119
  }
@@ -1864,7 +2122,7 @@ function scheduleCrossHarness(input) {
1864
2122
  ...base,
1865
2123
  decision: "stay",
1866
2124
  reasons: [
1867
- reason("candidate-capacity-below-one", "candidate safe allowance is below one empirical accepted-task equivalent")
2125
+ reason2("candidate-capacity-below-one", "candidate safe allowance is below one empirical accepted-task equivalent")
1868
2126
  ]
1869
2127
  };
1870
2128
  }
@@ -1873,7 +2131,7 @@ function scheduleCrossHarness(input) {
1873
2131
  ...base,
1874
2132
  decision: "insufficient-evidence",
1875
2133
  reasons: [
1876
- reason("candidate-quota-unknown", "candidate allowance headroom is not known well enough to justify a switch")
2134
+ reason2("candidate-quota-unknown", "candidate allowance headroom is not known well enough to justify a switch")
1877
2135
  ]
1878
2136
  };
1879
2137
  }
@@ -1881,7 +2139,7 @@ function scheduleCrossHarness(input) {
1881
2139
  ...base,
1882
2140
  decision: "stay",
1883
2141
  reasons: [
1884
- reason("candidate-over-pace", "the candidate is already over pace in an observed allowance window")
2142
+ reason2("candidate-over-pace", "the candidate is already over pace in an observed allowance window")
1885
2143
  ]
1886
2144
  };
1887
2145
  }
@@ -1890,7 +2148,7 @@ function scheduleCrossHarness(input) {
1890
2148
  ...base,
1891
2149
  decision: "insufficient-evidence",
1892
2150
  reasons: [
1893
- reason("candidate-quality-unknown", "no quality-gated empirical result proves the candidate for this task class")
2151
+ reason2("candidate-quality-unknown", "no quality-gated empirical result proves the candidate for this task class")
1894
2152
  ]
1895
2153
  };
1896
2154
  }
@@ -1899,7 +2157,7 @@ function scheduleCrossHarness(input) {
1899
2157
  ...base,
1900
2158
  decision: "stay",
1901
2159
  reasons: [
1902
- reason("transfer-cost-not-worth-it", "comparable evidence says the expected switch benefit does not exceed handoff cost")
2160
+ reason2("transfer-cost-not-worth-it", "comparable evidence says the expected switch benefit does not exceed handoff cost")
1903
2161
  ]
1904
2162
  };
1905
2163
  }
@@ -1908,18 +2166,18 @@ function scheduleCrossHarness(input) {
1908
2166
  ...base,
1909
2167
  decision: "insufficient-evidence",
1910
2168
  reasons: [
1911
- reason("transfer-benefit-unknown", "no comparable evidence proves that the expected switch benefit exceeds handoff cost")
2169
+ reason2("transfer-benefit-unknown", "no comparable evidence proves that the expected switch benefit exceeds handoff cost")
1912
2170
  ]
1913
2171
  };
1914
2172
  }
1915
2173
  const reasons = [
1916
- tasksRemaining !== null && input.current.acceptedTasksRemaining !== void 0 && input.current.acceptedTasksRemaining !== null && input.current.acceptedTasksRemaining < tasksRemaining ? reason("current-capacity-below-workload", `current harness has ${String(input.current.acceptedTasksRemaining)} accepted-task equivalents for ${String(tasksRemaining)} stated task(s)`) : input.current.acceptedTasksRemaining === 0 ? reason("current-capacity-below-one", "current safe allowance is below one empirical accepted-task equivalent") : reason("current-over-pace", "the current harness is over pace in at least one observed allowance window"),
1917
- reason("candidate-headroom", "the candidate is on pace or under pace in its observed allowance windows")
2174
+ tasksRemaining !== null && input.current.acceptedTasksRemaining !== void 0 && input.current.acceptedTasksRemaining !== null && input.current.acceptedTasksRemaining < tasksRemaining ? reason2("current-capacity-below-workload", `current harness has ${String(input.current.acceptedTasksRemaining)} accepted-task equivalents for ${String(tasksRemaining)} stated task(s)`) : input.current.acceptedTasksRemaining === 0 ? reason2("current-capacity-below-one", "current safe allowance is below one empirical accepted-task equivalent") : reason2("current-over-pace", "the current harness is over pace in at least one observed allowance window"),
2175
+ reason2("candidate-headroom", "the candidate is on pace or under pace in its observed allowance windows")
1918
2176
  ];
1919
2177
  if (input.candidate.acceptedTasksRemaining !== void 0 && input.candidate.acceptedTasksRemaining !== null) {
1920
- reasons.push(tasksRemaining !== null ? reason("candidate-workload-covered", `candidate has ${String(input.candidate.acceptedTasksRemaining)} accepted-task equivalents for ${String(tasksRemaining)} stated task(s)`) : reason("candidate-capacity-sufficient", `candidate has ${String(input.candidate.acceptedTasksRemaining)} conservative accepted-task equivalents remaining`));
2178
+ reasons.push(tasksRemaining !== null ? reason2("candidate-workload-covered", `candidate has ${String(input.candidate.acceptedTasksRemaining)} accepted-task equivalents for ${String(tasksRemaining)} stated task(s)`) : reason2("candidate-capacity-sufficient", `candidate has ${String(input.candidate.acceptedTasksRemaining)} conservative accepted-task equivalents remaining`));
1921
2179
  }
1922
- reasons.push(reason("candidate-quality-passed", "quality-gated empirical evidence passes for this task class"), reason("transfer-benefit-positive", "comparable evidence says expected switch benefit exceeds handoff cost"));
2180
+ reasons.push(reason2("candidate-quality-passed", "quality-gated empirical evidence passes for this task class"), reason2("transfer-benefit-positive", "comparable evidence says expected switch benefit exceeds handoff cost"));
1923
2181
  return {
1924
2182
  ...base,
1925
2183
  decision: "switch",
@@ -2164,7 +2422,7 @@ function parseCrossHarnessTransferReceipt(value3) {
2164
2422
  const basis = row2["basis"];
2165
2423
  const reasons = row2["reasons"];
2166
2424
  const recordedAt = row2["recordedAt"];
2167
- if (typeof benchmarkId !== "string" || !isTaskBenchmarkId(benchmarkId) || typeof projectId !== "string" || projectId === "" || typeof taskClass !== "string" || !isTaskClass(taskClass) || typeof currentHarness !== "string" || !isHarnessId(currentHarness) || typeof candidateHarness !== "string" || !isHarnessId(candidateHarness) || currentHarness === candidateHarness || typeof handoffBytes !== "number" || !Number.isInteger(handoffBytes) || handoffBytes < 0 || typeof handoffDigest !== "string" || !isDigest(handoffDigest) || typeof maxHandoffBytes !== "number" || !Number.isInteger(maxHandoffBytes) || maxHandoffBytes <= 0 || typeof benefit !== "string" || !BENEFITS.has(benefit) || typeof basis !== "string" || !BASES.has(basis) || !Array.isArray(reasons) || reasons.length < 1 || !reasons.every((reason3) => typeof reason3 === "string" && reason3.length > 0) || !validInstant2(recordedAt)) {
2425
+ if (typeof benchmarkId !== "string" || !isTaskBenchmarkId(benchmarkId) || typeof projectId !== "string" || projectId === "" || typeof taskClass !== "string" || !isTaskClass(taskClass) || typeof currentHarness !== "string" || !isHarnessId(currentHarness) || typeof candidateHarness !== "string" || !isHarnessId(candidateHarness) || currentHarness === candidateHarness || typeof handoffBytes !== "number" || !Number.isInteger(handoffBytes) || handoffBytes < 0 || typeof handoffDigest !== "string" || !isDigest(handoffDigest) || typeof maxHandoffBytes !== "number" || !Number.isInteger(maxHandoffBytes) || maxHandoffBytes <= 0 || typeof benefit !== "string" || !BENEFITS.has(benefit) || typeof basis !== "string" || !BASES.has(basis) || !Array.isArray(reasons) || reasons.length < 1 || !reasons.every((reason4) => typeof reason4 === "string" && reason4.length > 0) || !validInstant2(recordedAt)) {
2168
2426
  return {
2169
2427
  ok: false,
2170
2428
  reason: "invalid-shape",
@@ -2270,6 +2528,9 @@ function estimateScope(input) {
2270
2528
  });
2271
2529
  return {
2272
2530
  scope: input.scope,
2531
+ receiptIds: [
2532
+ ...new Set(input.receipts.filter((receipt) => quotaCosts([receipt], input.scope).length === 1).map((receipt) => `${receipt.benchmarkId}/${receipt.variant}`))
2533
+ ].sort(),
2273
2534
  sampleCount: costs.length,
2274
2535
  p75UsedPercentPerAcceptedTask: cost,
2275
2536
  spendableRemainingPercent: spendable,
@@ -2458,7 +2719,7 @@ var init_workload_coverage = __esm({
2458
2719
  });
2459
2720
 
2460
2721
  // packages/core/dist/src/domain/mixed-workload.js
2461
- function reason2(code, summary) {
2722
+ function reason3(code, summary) {
2462
2723
  return { code, summary };
2463
2724
  }
2464
2725
  function validDemand(demand) {
@@ -2579,7 +2840,7 @@ function allocateMixedWorkload(input) {
2579
2840
  currentUsage: usageReport(input.current.harnessId, input.current.capacities, zero),
2580
2841
  candidateUsage: usageReport(input.candidate.harnessId, input.candidate.capacities, zero),
2581
2842
  reasons: [
2582
- reason2("mixed-workload-invalid", "mixed workload must contain unique task classes with positive whole-number counts")
2843
+ reason3("mixed-workload-invalid", "mixed workload must contain unique task classes with positive whole-number counts")
2583
2844
  ]
2584
2845
  };
2585
2846
  }
@@ -2591,7 +2852,7 @@ function allocateMixedWorkload(input) {
2591
2852
  currentUsage: usageReport(input.current.harnessId, input.current.capacities, zero),
2592
2853
  candidateUsage: usageReport(input.candidate.harnessId, input.candidate.capacities, zero),
2593
2854
  reasons: [
2594
- reason2("mixed-workload-same-harness", "mixed workload allocation requires two distinct harnesses")
2855
+ reason3("mixed-workload-same-harness", "mixed workload allocation requires two distinct harnesses")
2595
2856
  ]
2596
2857
  };
2597
2858
  }
@@ -2654,20 +2915,20 @@ function allocateMixedWorkload(input) {
2654
2915
  const unknownClasses = allocationRows.filter((row2) => row2.unallocated > 0 && evidenceUnknown.has(row2.taskClass)).map((row2) => row2.taskClass);
2655
2916
  if (unknownClasses.length > 0) {
2656
2917
  decision = "insufficient-evidence";
2657
- reasons.push(reason2("mixed-workload-capacity-unproven", `Could not allocate ${String(unallocated)} task(s); evidence is incomplete for ${unknownClasses.join(", ")}`));
2918
+ reasons.push(reason3("mixed-workload-capacity-unproven", `Could not allocate ${String(unallocated)} task(s); evidence is incomplete for ${unknownClasses.join(", ")}`));
2658
2919
  } else {
2659
2920
  decision = "shortfall";
2660
- reasons.push(reason2("mixed-workload-capacity-shortfall", `Conservative five-hour/weekly capacity leaves ${String(unallocated)} of ${String(requestedTasks)} requested task(s) unallocated`));
2921
+ reasons.push(reason3("mixed-workload-capacity-shortfall", `Conservative five-hour/weekly capacity leaves ${String(unallocated)} of ${String(requestedTasks)} requested task(s) unallocated`));
2661
2922
  }
2662
2923
  } else if (candidateTasks === 0) {
2663
2924
  decision = "stay";
2664
- reasons.push(reason2("mixed-workload-current-covers", "The current harness can cover the full evidenced workload"));
2925
+ reasons.push(reason3("mixed-workload-current-covers", "The current harness can cover the full evidenced workload"));
2665
2926
  } else if (currentTasks === 0) {
2666
2927
  decision = "switch";
2667
- reasons.push(reason2("mixed-workload-candidate-covers", "The candidate harness can cover the full evidenced workload with quality-gated capacity"));
2928
+ reasons.push(reason3("mixed-workload-candidate-covers", "The candidate harness can cover the full evidenced workload with quality-gated capacity"));
2668
2929
  } else {
2669
2930
  decision = "split";
2670
- reasons.push(reason2("mixed-workload-split", `A conservative split covers all ${String(requestedTasks)} task(s): ${String(currentTasks)} current and ${String(candidateTasks)} candidate`));
2931
+ reasons.push(reason3("mixed-workload-split", `A conservative split covers all ${String(requestedTasks)} task(s): ${String(currentTasks)} current and ${String(candidateTasks)} candidate`));
2671
2932
  }
2672
2933
  return {
2673
2934
  ...base,
@@ -3200,6 +3461,8 @@ function truncateUtf8(value3, maxBytes) {
3200
3461
  else
3201
3462
  high = middle - 1;
3202
3463
  }
3464
+ if (low > 0 && /[\uD800-\uDBFF]/.test(value3[low - 1]) && /[\uDC00-\uDFFF]/.test(value3[low] ?? ""))
3465
+ low--;
3203
3466
  return `${value3.slice(0, low).trimEnd()}${suffix}`;
3204
3467
  }
3205
3468
  function renderList(title2, values, omitted) {
@@ -3212,16 +3475,21 @@ function renderList(title2, values, omitted) {
3212
3475
  lines.push(`- \u2026 ${omitted} more omitted`);
3213
3476
  return lines;
3214
3477
  }
3215
- function render(objective, nextAction2, lists, omitted) {
3478
+ function render(objective, nextAction2, lists, omitted, compactOmissions = false) {
3479
+ const section = (title2, key) => renderList(title2, lists[key], compactOmissions ? 0 : omitted[key]);
3480
+ const omittedTotal = Object.values(omitted).reduce((sum, count) => sum + count, 0);
3216
3481
  const sections = [
3217
3482
  ["# Compact handoff", "", "## Objective", objective],
3218
- renderList("Decisions", lists.decisions, omitted.decisions),
3219
- renderList("Changed files", lists.changedFiles, omitted.changedFiles),
3220
- renderList("Validation", lists.validation, omitted.validation),
3221
- renderList("Unresolved", lists.unresolved, omitted.unresolved),
3483
+ section("Acceptance criteria", "acceptanceCriteria"),
3484
+ section("Costly facts", "costlyFacts"),
3485
+ section("Decisions", "decisions"),
3486
+ section("Changed files", "changedFiles"),
3487
+ section("Validation", "validation"),
3488
+ section("Unresolved", "unresolved"),
3489
+ compactOmissions && omittedTotal > 0 ? [`\u2026 ${omittedTotal} optional items omitted`] : [],
3222
3490
  ["## Next action", nextAction2]
3223
- ].filter((section) => section.length > 0);
3224
- return sections.map((section) => section.join("\n")).join("\n\n");
3491
+ ].filter((section2) => section2.length > 0);
3492
+ return sections.map((section2) => section2.join("\n")).join("\n\n");
3225
3493
  }
3226
3494
  function largestOptionalList(lists) {
3227
3495
  const entries = Object.keys(lists).filter((key) => lists[key].length > 0).map((key) => ({ key, bytes: lists[key].reduce((sum, item) => sum + byteLength(item), 0) })).sort((left, right) => right.bytes - left.bytes || left.key.localeCompare(right.key));
@@ -3238,12 +3506,16 @@ function buildCompactHandoff(input) {
3238
3506
  if (!nextAction2)
3239
3507
  throw new Error("nextAction must not be empty");
3240
3508
  const lists = {
3509
+ acceptanceCriteria: uniqueClean(input.acceptanceCriteria),
3510
+ costlyFacts: uniqueClean(input.costlyFacts),
3241
3511
  decisions: uniqueClean(input.decisions),
3242
3512
  changedFiles: uniqueClean(input.changedFiles),
3243
3513
  validation: uniqueClean(input.validation),
3244
3514
  unresolved: uniqueClean(input.unresolved)
3245
3515
  };
3246
3516
  const omitted = {
3517
+ acceptanceCriteria: 0,
3518
+ costlyFacts: 0,
3247
3519
  decisions: 0,
3248
3520
  changedFiles: 0,
3249
3521
  validation: 0,
@@ -3260,15 +3532,18 @@ function buildCompactHandoff(input) {
3260
3532
  truncated = true;
3261
3533
  markdown = render(objective, nextAction2, lists, omitted);
3262
3534
  }
3535
+ const compactOmissions = byteLength(render("", "", lists, omitted)) + 32 > input.maxBytes;
3536
+ if (compactOmissions)
3537
+ markdown = render(objective, nextAction2, lists, omitted, true);
3263
3538
  if (byteLength(markdown) > input.maxBytes) {
3264
- const skeleton = render("", "", lists, omitted);
3539
+ const skeleton = render("", "", lists, omitted, compactOmissions);
3265
3540
  const available = Math.max(32, input.maxBytes - byteLength(skeleton));
3266
3541
  const objectiveBudget = Math.floor(available * 0.6);
3267
3542
  const nextBudget = available - objectiveBudget;
3268
3543
  objective = truncateUtf8(objective, objectiveBudget);
3269
3544
  nextAction2 = truncateUtf8(nextAction2, nextBudget);
3270
3545
  truncated = true;
3271
- markdown = render(objective, nextAction2, lists, omitted);
3546
+ markdown = render(objective, nextAction2, lists, omitted, compactOmissions);
3272
3547
  }
3273
3548
  if (byteLength(markdown) > input.maxBytes) {
3274
3549
  markdown = truncateUtf8(markdown, input.maxBytes);
@@ -5774,14 +6049,14 @@ function providerList(events) {
5774
6049
  }
5775
6050
  return providers;
5776
6051
  }
5777
- function incomparable(events, reason3) {
6052
+ function incomparable(events, reason4) {
5778
6053
  const pipelineIds = new Set(events.map((event) => event.context.pipelineId));
5779
6054
  const operationIds = new Set(events.map((event) => event.context.operationId));
5780
6055
  return {
5781
6056
  status: "incomparable",
5782
6057
  pipelineId: pipelineIds.size === 1 ? events[0]?.context.pipelineId ?? null : null,
5783
6058
  operationId: operationIds.size === 1 ? events[0]?.context.operationId ?? null : null,
5784
- reason: reason3,
6059
+ reason: reason4,
5785
6060
  providers: providerList(events),
5786
6061
  stages: events.length
5787
6062
  };
@@ -9862,7 +10137,7 @@ var TOOL_VERSION;
9862
10137
  var init_version2 = __esm({
9863
10138
  "apps/cli/dist/src/version.js"() {
9864
10139
  "use strict";
9865
- TOOL_VERSION = "0.1.26";
10140
+ TOOL_VERSION = "0.1.28";
9866
10141
  }
9867
10142
  });
9868
10143
 
@@ -9885,6 +10160,8 @@ function parseValue(argv2, index) {
9885
10160
  }
9886
10161
  function parseArgs(argv2) {
9887
10162
  const args = {
10163
+ acceptanceCriteria: [],
10164
+ costlyFacts: [],
9888
10165
  objective: null,
9889
10166
  decisions: [],
9890
10167
  changedFiles: [],
@@ -9923,6 +10200,8 @@ function parseArgs(argv2) {
9923
10200
  continue;
9924
10201
  }
9925
10202
  const valueFlags = /* @__PURE__ */ new Set([
10203
+ "--acceptance",
10204
+ "--fact",
9926
10205
  "--objective",
9927
10206
  "--decision",
9928
10207
  "--changed-file",
@@ -9952,6 +10231,12 @@ function parseArgs(argv2) {
9952
10231
  }
9953
10232
  index += parsed.consumed;
9954
10233
  switch (name2) {
10234
+ case "--acceptance":
10235
+ args.acceptanceCriteria.push(parsed.value);
10236
+ break;
10237
+ case "--fact":
10238
+ args.costlyFacts.push(parsed.value);
10239
+ break;
9955
10240
  case "--objective":
9956
10241
  args.objective = parsed.value;
9957
10242
  break;
@@ -10067,6 +10352,8 @@ async function handoffMain(argv2, streams) {
10067
10352
  return EXIT_CODES["usage-error"];
10068
10353
  }
10069
10354
  const handoff = buildCompactHandoff({
10355
+ acceptanceCriteria: parsed.args.acceptanceCriteria,
10356
+ costlyFacts: parsed.args.costlyFacts,
10070
10357
  objective: parsed.args.objective,
10071
10358
  decisions: parsed.args.decisions,
10072
10359
  changedFiles: parsed.args.changedFiles,
@@ -10097,6 +10384,8 @@ Usage
10097
10384
  token-harness handoff --objective <text> --next-action <text> [flags]
10098
10385
 
10099
10386
  Flags
10387
+ --acceptance <text> Repeatable acceptance criterion to preserve
10388
+ --fact <text> Repeatable costly path/symbol/config fact to preserve
10100
10389
  --decision <text> Repeatable decision to preserve
10101
10390
  --changed-file <path> Repeatable changed file to preserve
10102
10391
  --validation <text> Repeatable validation result to preserve
@@ -10190,7 +10479,7 @@ function render2(report) {
10190
10479
  `Basis: ${a.basis}`,
10191
10480
  `Handoff: ${String(a.handoffBytes)} / ${String(a.maxHandoffBytes)} bytes`,
10192
10481
  "Reasons:",
10193
- ...a.reasons.map((reason3) => `- ${reason3}`),
10482
+ ...a.reasons.map((reason4) => `- ${reason4}`),
10194
10483
  ""
10195
10484
  ].join("\n");
10196
10485
  }
@@ -11993,7 +12282,7 @@ function boundedCapture(limit) {
11993
12282
  };
11994
12283
  return capture;
11995
12284
  }
11996
- function failureOutcome(base, reason3, message, durationMs) {
12285
+ function failureOutcome(base, reason4, message, durationMs) {
11997
12286
  return {
11998
12287
  ...base,
11999
12288
  exitCode: null,
@@ -12003,8 +12292,8 @@ function failureOutcome(base, reason3, message, durationMs) {
12003
12292
  stdoutTruncated: false,
12004
12293
  stderrTruncated: false,
12005
12294
  durationMs,
12006
- timedOut: reason3 === "timed-out",
12007
- failure: { reason: reason3, message }
12295
+ timedOut: reason4 === "timed-out",
12296
+ failure: { reason: reason4, message }
12008
12297
  };
12009
12298
  }
12010
12299
  function spawnFailureReason(code) {
@@ -13938,10 +14227,10 @@ async function readClaudeNativeEffort(context) {
13938
14227
  files: [],
13939
14228
  environment
13940
14229
  };
13941
- const block = (code, reason3) => {
14230
+ const block = (code, reason4) => {
13942
14231
  if (observation.writeBlock === null) {
13943
14232
  observation.writeBlock = code;
13944
- observation.reason = reason3;
14233
+ observation.reason = reason4;
13945
14234
  }
13946
14235
  };
13947
14236
  if (version3 === void 0) {
@@ -15502,7 +15791,7 @@ async function observeUsageViaCclimits(context, observedAt, nativeDiagnostic) {
15502
15791
  maxOutputBytes: 512 * 1024
15503
15792
  });
15504
15793
  if (outcome2.failure !== null || outcome2.exitCode !== 0 || outcome2.stdoutTruncated) {
15505
- const reason3 = outcome2.failure !== null ? outcome2.failure.message : outcome2.stdoutTruncated ? "output exceeded the bounded capture" : `exited ${String(outcome2.exitCode)}`;
15794
+ const reason4 = outcome2.failure !== null ? outcome2.failure.message : outcome2.stdoutTruncated ? "output exceeded the bounded capture" : `exited ${String(outcome2.exitCode)}`;
15506
15795
  return {
15507
15796
  harnessId: CODEX2,
15508
15797
  state: "unavailable",
@@ -15516,7 +15805,7 @@ async function observeUsageViaCclimits(context, observedAt, nativeDiagnostic) {
15516
15805
  severity: outcome2.failure?.reason === "executable-not-found" ? "info" : "warning",
15517
15806
  code: "cclimits-codex-usage-unavailable",
15518
15807
  subject: CODEX2,
15519
- message: "Optional cclimits Codex quota fallback was unavailable: " + reason3,
15808
+ message: "Optional cclimits Codex quota fallback was unavailable: " + reason4,
15520
15809
  remediation: "Install a cclimits build with cacheless Codex JSON support, or treat Codex quota as unknown"
15521
15810
  })
15522
15811
  ]
@@ -16792,7 +17081,7 @@ function nativePromptRoutingVersionSupported(harness, version3) {
16792
17081
  const parsed = version3 === null ? null : parseSemanticVersion(version3);
16793
17082
  if (parsed === null || parsed.prerelease !== null)
16794
17083
  return false;
16795
- return harness === "codex" ? parsed.major === 0 && (parsed.minor === 159 && parsed.patch <= 1 || parsed.minor === 160 && parsed.patch === 0) : harness === "claude" && parsed.major === 2 && parsed.minor === 1 && parsed.patch >= 274 && parsed.patch <= 288;
17084
+ return harness === "codex" ? parsed.major === 0 && (parsed.minor === 146 && parsed.patch === 0 || parsed.minor === 159 && parsed.patch <= 1 || parsed.minor === 160 && parsed.patch === 0) : harness === "claude" && parsed.major === 2 && parsed.minor === 1 && parsed.patch >= 274 && parsed.patch <= 288;
16796
17085
  }
16797
17086
  function nativePromptRoutingHookEntries(harness, executable = "token-harness", platform = "linux") {
16798
17087
  return NATIVE_PROMPT_ROUTING_EVENTS.map(({ eventName, commandEvent }) => {
@@ -17460,6 +17749,30 @@ async function verify6(context) {
17460
17749
  const configured = await configuredHarnessesForHarnessTrim(context, currentCapabilities?.capabilities ?? null);
17461
17750
  const runtimeConfigured = harnessesWiredToHarnessTrim(context.harnessConfigs);
17462
17751
  const skillsOnly = configured.filter((harness) => !runtimeConfigured.includes(harness));
17752
+ if (context.facts.os === "windows" && !context.facts.isWsl) {
17753
+ for (const config of context.harnessConfigs) {
17754
+ for (const hook of config.hookCommands ?? []) {
17755
+ const binary = windowsHookExecutable(hook.command);
17756
+ if (binary === null || (await context.fs.stat(binary))?.kind === "file")
17757
+ continue;
17758
+ checks.push({
17759
+ id: `hook-executable-${config.harnessId}-${digestText(hook.commandPointer).slice(7, 15)}`,
17760
+ status: "fail",
17761
+ summary: `${config.harnessId} HarnessTrim hook executable is missing or not a file`,
17762
+ achievedTier: null,
17763
+ evidence: [
17764
+ evidence3({
17765
+ kind: "config-entry",
17766
+ source: "HarnessTrim hook",
17767
+ path: config.configPath,
17768
+ detail: `${hook.commandPointer}: ${binary}`
17769
+ })
17770
+ ],
17771
+ remediation: "Preview a HarnessTrim setup repair; custom commands require manual review."
17772
+ });
17773
+ }
17774
+ }
17775
+ }
17463
17776
  checks.push({
17464
17777
  id: "integration-configured",
17465
17778
  status: runtimeConfigured.length > 0 ? "pass" : skillsOnly.length > 0 ? "info" : "not-exercised",
@@ -17881,6 +18194,42 @@ async function plan(context, request) {
17881
18194
  const command = `harnesstrim hook ${harness.id} --metrics ${metricsPath}`;
17882
18195
  const existing = context.harnessConfigs.filter((config) => config.harnessId === harness.id && config.configPath === target.configPath && config.interceptionPoints.includes(target.scopeId)).flatMap((config) => config.hookCommands ?? []).filter((entry) => entry.eventName === target.eventName && entry.matcher !== null && matcherCoversFamily2(entry.matcher, target.toolFamily) && isHarnessTrimHookFor(entry.command, harness.id));
17883
18196
  const correctlyMonitored = existing.some((entry) => commandHasMetricsPath(entry.command, metricsPath));
18197
+ const missingExecutables = [];
18198
+ if (context.facts.os === "windows" && !context.facts.isWsl) {
18199
+ for (const entry of existing) {
18200
+ const binary = windowsHookExecutable(entry.command);
18201
+ if (binary !== null && (await context.fs.stat(binary))?.kind !== "file")
18202
+ missingExecutables.push(entry);
18203
+ }
18204
+ }
18205
+ if (existing.length === 1 && missingExecutables.length === 1) {
18206
+ const entry = missingExecutables[0];
18207
+ const binary = windowsHookExecutable(entry.command);
18208
+ const standardTail = entry.command.trim().slice(entry.command.indexOf(" hook ") + 1);
18209
+ if (binary !== null && (standardTail === `hook ${harness.id}` || standardTail === `hook ${harness.id} --metrics ${metricsPath}`)) {
18210
+ actions.push(replaceHookCommandAction({
18211
+ target,
18212
+ commandPointer: entry.commandPointer,
18213
+ currentCommand: entry.command,
18214
+ nextCommand: command,
18215
+ actionId: `harnesstrim-${harness.id}-executable-${digestText(target.configPath).slice(7, 15)}`,
18216
+ explanation: `Repair the missing HarnessTrim hook executable on ${harness.displayName}`
18217
+ }));
18218
+ plannedHarnesses.push(harness.id);
18219
+ continue;
18220
+ }
18221
+ }
18222
+ if (missingExecutables.length > 0) {
18223
+ diagnostics.push(diagnostic({
18224
+ severity: "warning",
18225
+ code: "harnesstrim-hook-executable-needs-review",
18226
+ subject: harness.id,
18227
+ path: target.configPath,
18228
+ message: "An absolute HarnessTrim hook executable is missing; its custom or ambiguous command was left unchanged",
18229
+ remediation: "Review the executable and arguments before replacing this hook."
18230
+ }));
18231
+ continue;
18232
+ }
17884
18233
  if (correctlyMonitored) {
17885
18234
  plannedHarnesses.push(harness.id);
17886
18235
  continue;
@@ -17927,6 +18276,11 @@ async function plan(context, request) {
17927
18276
  targetHarnesses: [...new Set(plannedHarnesses)]
17928
18277
  };
17929
18278
  }
18279
+ function windowsHookExecutable(command) {
18280
+ const match = /^(?:"([a-z]:[\\/][^"\r\n]+)"|([a-z]:[\\/][^\s"\r\n]+))\s+hook\s+(?:claude|codex)(?:\s|$)/i.exec(command.trim());
18281
+ const binary = match?.[1] ?? match?.[2];
18282
+ return binary !== void 0 && /[\\/]harnesstrim(?:\.cmd|\.exe)?$/i.test(binary) ? binary : null;
18283
+ }
17930
18284
  function isHarnessTrimHookFor(command, harness) {
17931
18285
  const match = HARNESSTRIM_HOOK_COMMAND.exec(command.trim());
17932
18286
  return match?.[1]?.toLowerCase() === harness;
@@ -17964,7 +18318,7 @@ function replaceHookCommandAction(input) {
17964
18318
  `${input.commandPointer} records HarnessTrim reductions to .harnesstrim/metrics.jsonl`
17965
18319
  ],
17966
18320
  rollbackData: "file-snapshot",
17967
- explanation: `Enable per-harness HarnessTrim telemetry for ${input.target.harness.displayName}${codexActivationNote(input.target.harnessId)}`,
18321
+ explanation: `${input.explanation ?? `Enable per-harness HarnessTrim telemetry for ${input.target.harness.displayName}`}${codexActivationNote(input.target.harnessId)}`,
17968
18322
  path: input.target.configPath,
17969
18323
  ownedPointers: [input.commandPointer],
17970
18324
  operations: [
@@ -20185,7 +20539,7 @@ ${wrapOutcome.stderr}`) : { claude: false, codex: false };
20185
20539
  };
20186
20540
  }
20187
20541
  if (version3 !== HEADROOM_REVIEWED_BENCHMARK_VERSION) {
20188
- const reason3 = headroomVersionAtLeast(version3, HEADROOM_REVIEWED_BENCHMARK_VERSION) ? `Headroom ${version3} is newer than the reviewed ${HEADROOM_REVIEWED_BENCHMARK_VERSION} benchmark build; review it before benchmarking` : `Headroom ${version3} predates the reviewed ${HEADROOM_REVIEWED_BENCHMARK_VERSION} benchmark build`;
20542
+ const reason4 = headroomVersionAtLeast(version3, HEADROOM_REVIEWED_BENCHMARK_VERSION) ? `Headroom ${version3} is newer than the reviewed ${HEADROOM_REVIEWED_BENCHMARK_VERSION} benchmark build; review it before benchmarking` : `Headroom ${version3} predates the reviewed ${HEADROOM_REVIEWED_BENCHMARK_VERSION} benchmark build`;
20189
20543
  return {
20190
20544
  state: "unsupported-version",
20191
20545
  version: version3,
@@ -20193,7 +20547,7 @@ ${wrapOutcome.stderr}`) : { claude: false, codex: false };
20193
20547
  supportsClaudeWrap: targets.claude,
20194
20548
  supportsCodexWrap: targets.codex,
20195
20549
  minimumBenchmarkVersion: HEADROOM_MINIMUM_BENCHMARK_VERSION,
20196
- reasons: [reason3]
20550
+ reasons: [reason4]
20197
20551
  };
20198
20552
  }
20199
20553
  if (!targets.claude || !targets.codex) {
@@ -24960,7 +25314,7 @@ function providerContext3(context) {
24960
25314
  function headroomDiagnostics(observation) {
24961
25315
  const version3 = observation.version === null ? "" : ` ${observation.version}`;
24962
25316
  const baseline = observation.minimumBenchmarkVersion;
24963
- const reason3 = observation.reasons[0] ?? "Keep the candidate disabled until it is proven safe";
25317
+ const reason4 = observation.reasons[0] ?? "Keep the candidate disabled until it is proven safe";
24964
25318
  if (observation.state === "absent") {
24965
25319
  return [
24966
25320
  diagnostic({
@@ -24990,7 +25344,7 @@ function headroomDiagnostics(observation) {
24990
25344
  code: "context-owner-candidate-installed",
24991
25345
  subject: "headroom",
24992
25346
  message: `Headroom${version3} is installed but is not benchmark-ready`,
24993
- remediation: reason3
25347
+ remediation: reason4
24994
25348
  })
24995
25349
  ];
24996
25350
  }
@@ -25007,7 +25361,7 @@ function headroomDiagnostics(observation) {
25007
25361
  function mcptoonDiagnostics(observation) {
25008
25362
  const version3 = observation.version === null ? "" : ` ${observation.version}`;
25009
25363
  const baseline = observation.minimumBenchmarkVersion;
25010
- const reason3 = observation.reasons[0] ?? "Keep mcptoon disabled until benchmark evidence is available";
25364
+ const reason4 = observation.reasons[0] ?? "Keep mcptoon disabled until benchmark evidence is available";
25011
25365
  if (observation.state === "absent") {
25012
25366
  return [
25013
25367
  diagnostic({
@@ -25037,7 +25391,7 @@ function mcptoonDiagnostics(observation) {
25037
25391
  code: "context-optimizer-mcptoon-installed",
25038
25392
  subject: "mcptoon",
25039
25393
  message: `mcptoon${version3} is installed but is not benchmark-ready`,
25040
- remediation: reason3
25394
+ remediation: reason4
25041
25395
  })
25042
25396
  ];
25043
25397
  }
@@ -25053,7 +25407,7 @@ function mcptoonDiagnostics(observation) {
25053
25407
  }
25054
25408
  function gitNexusDiagnostics(observation) {
25055
25409
  const version3 = observation.version === null ? "" : ` ${observation.version}`;
25056
- const reason3 = observation.reasons[0] ?? "Keep GitNexus disabled until paired repository-exploration evidence is available";
25410
+ const reason4 = observation.reasons[0] ?? "Keep GitNexus disabled until paired repository-exploration evidence is available";
25057
25411
  if (observation.state === "absent") {
25058
25412
  return [
25059
25413
  diagnostic({
@@ -25083,7 +25437,7 @@ function gitNexusDiagnostics(observation) {
25083
25437
  code: "context-optimizer-gitnexus-installed",
25084
25438
  subject: "gitnexus",
25085
25439
  message: `GitNexus${version3} is installed but is not benchmark-ready`,
25086
- remediation: reason3
25440
+ remediation: reason4
25087
25441
  })
25088
25442
  ];
25089
25443
  }
@@ -25405,7 +25759,7 @@ async function runContext(context) {
25405
25759
  const usesMostOfCodexBudget = harness.projectDocMaxBytes !== null && harness.projectDocMaxBytes > 0 && knownLoadedProjectBytes / harness.projectDocMaxBytes >= 0.75;
25406
25760
  const largeSingleCandidate = projectFiles.length === 1 && largestProjectFileBytes !== null && largestProjectFileBytes >= 32 * 1024;
25407
25761
  const monolithicProjectInstructions = projectFiles.length === 1 && (usesMostOfCodexBudget || largeSingleCandidate);
25408
- const reason3 = monolithicProjectInstructions ? usesMostOfCodexBudget ? "one project instruction file consumes at least 75% of the harness project-doc byte budget" : "one project instruction candidate is at least 32 KiB" : null;
25762
+ const reason4 = monolithicProjectInstructions ? usesMostOfCodexBudget ? "one project instruction file consumes at least 75% of the harness project-doc byte budget" : "one project instruction candidate is at least 32 KiB" : null;
25409
25763
  report.instructionHierarchy.push({
25410
25764
  harnessId: harness.harnessId,
25411
25765
  projectFileCount: projectFiles.length,
@@ -25414,7 +25768,7 @@ async function runContext(context) {
25414
25768
  nestedProjectHierarchy: projectDirectories.size > 1,
25415
25769
  largestProjectFileBytes,
25416
25770
  monolithicProjectInstructions,
25417
- reason: reason3
25771
+ reason: reason4
25418
25772
  });
25419
25773
  if (monolithicProjectInstructions) {
25420
25774
  hierarchyDiagnostics.push(diagnostic({
@@ -26457,7 +26811,8 @@ async function runOptimize(context) {
26457
26811
  profile,
26458
26812
  reservePercent,
26459
26813
  tasksRemaining: context.tasksRemaining ?? null,
26460
- harnesses: []
26814
+ harnesses: [],
26815
+ efficiencyDecisions: []
26461
26816
  };
26462
26817
  if (contextReport === null || budgetReport === null) {
26463
26818
  return commandResult({
@@ -26502,6 +26857,35 @@ async function runOptimize(context) {
26502
26857
  ...contextGovernor === void 0 ? {} : { contextGovernor }
26503
26858
  }));
26504
26859
  }
26860
+ for (const advice of report.harnesses) {
26861
+ if (advice.harnessId !== "claude" && advice.harnessId !== "codex")
26862
+ continue;
26863
+ const snapshotObservation = contextReport.harnesses.find((item) => item.harnessId === contextSnapshot?.harnessId);
26864
+ const input = {
26865
+ currentHarness: advice.harnessId === "claude" ? "claude" : "codex",
26866
+ taskClass,
26867
+ optimization: report.harnesses,
26868
+ scheduler: context.efficiencyScheduler ?? null,
26869
+ contextGovernor: contextSnapshot === null || snapshotObservation === void 0 ? null : {
26870
+ ...contextSnapshot,
26871
+ pressure: contextEvidence(contextReport, snapshotObservation).pressure
26872
+ }
26873
+ };
26874
+ const selected = decideEfficiency(input);
26875
+ const capacity = outcomeHistory.receipts === null ? null : estimateAcceptedTaskCapacityForPolicy({
26876
+ report: budgetReport,
26877
+ receipts: outcomeHistory.receipts,
26878
+ harnessId: harnessId(selected.harness),
26879
+ taskClass,
26880
+ reservePercent,
26881
+ policy: {
26882
+ model: selected.model,
26883
+ reasoningEffort: selected.reasoningEffort,
26884
+ verbosity: selected.verbosity
26885
+ }
26886
+ });
26887
+ report.efficiencyDecisions.push(decideEfficiency({ ...input, capacities: capacity === null ? [] : [capacity] }));
26888
+ }
26505
26889
  return commandResult({
26506
26890
  command: "optimize",
26507
26891
  exitCode: EXIT_CODES.ok,
@@ -32533,8 +32917,8 @@ function renderBenchmarkReport(report, _context) {
32533
32917
  if (comparison.reasons.length > 0) {
32534
32918
  lines.push("");
32535
32919
  lines.push("Why");
32536
- for (const reason3 of comparison.reasons)
32537
- lines.push(...wrap(reason3, 2));
32920
+ for (const reason4 of comparison.reasons)
32921
+ lines.push(...wrap(reason4, 2));
32538
32922
  }
32539
32923
  lines.push("", ...wrap("Context reduction is reported separately and is not converted into Claude/Codex subscription quota.", 0));
32540
32924
  return document(lines);
@@ -32684,8 +33068,8 @@ function renderCampaign(lines, campaign) {
32684
33068
  const assessment2 = campaign.assessment;
32685
33069
  lines.push("", " Selection assessment");
32686
33070
  lines.push(...wrap(`Signal: ${assessment2.signal}; ${assessment2.decisionReady ? "decision-ready" : "not decision-ready"}. Evidence ${String(assessment2.evidencePairs)}/${String(assessment2.minimumEvidencePairs)} minimum; task classes ${String(assessment2.coveredTaskClasses.length)}/${String(assessment2.minimumTaskClasses)} minimum.`, 4));
32687
- for (const reason3 of assessment2.reasons)
32688
- lines.push(...wrap(`Reason: ${reason3}.`, 4));
33071
+ for (const reason4 of assessment2.reasons)
33072
+ lines.push(...wrap(`Reason: ${reason4}.`, 4));
32689
33073
  lines.push(...wrap(`Promotion: blocked. ${assessment2.promotionBlockers.join("; ")}.`, 4));
32690
33074
  lines.push(...wrap("Campaign evidence stays separate by evidence class. The selection signal is not a composite score, and promotion remains a separate lifecycle decision.", 2));
32691
33075
  }
@@ -33444,6 +33828,31 @@ var init_metrics2 = __esm({
33444
33828
  }
33445
33829
  });
33446
33830
 
33831
+ // apps/cli/dist/src/render/efficiency.js
33832
+ function efficiencyDecisionLines(decision, verbose = false) {
33833
+ const value3 = (input) => input === null ? "unknown" : String(input);
33834
+ const percent5 = (input) => input === null ? "unknown" : String(input) + "%";
33835
+ const lines = [
33836
+ ...wrap(`${decision.harness}/${decision.taskClass}: context ${decision.contextAction}`, 2),
33837
+ ...wrap(`model=${value3(decision.model)} effort=${value3(decision.reasoningEffort)} verbosity=${value3(decision.verbosity)}`, 4),
33838
+ ...wrap(`Task allowance: five-hour ${percent5(decision.allowanceBudget.fiveHourPercent)}; weekly ${percent5(decision.allowanceBudget.weeklyPercent)}`, 4),
33839
+ ...wrap(`Attempts=${value3(decision.maxAttempts)}; premium escalations=${value3(decision.premiumEscalationBudget)}`, 4)
33840
+ ];
33841
+ if (verbose) {
33842
+ for (const item of decision.evidence)
33843
+ lines.push(...wrap(`[${item.source}/${item.code}] ${item.summary}`, 4));
33844
+ for (const item of decision.reasons)
33845
+ lines.push(...wrap(`[${item.code}] ${item.summary}`, 4));
33846
+ }
33847
+ return lines.map((line) => truncate(line, 78));
33848
+ }
33849
+ var init_efficiency = __esm({
33850
+ "apps/cli/dist/src/render/efficiency.js"() {
33851
+ "use strict";
33852
+ init_layout();
33853
+ }
33854
+ });
33855
+
33447
33856
  // apps/cli/dist/src/render/optimize.js
33448
33857
  function value2(input) {
33449
33858
  return input ?? "-";
@@ -33474,6 +33883,11 @@ function renderOptimizeReport(report, _context) {
33474
33883
  [harness.contextPressure, 0]
33475
33884
  ]), 78));
33476
33885
  }
33886
+ if (report.efficiencyDecisions?.length) {
33887
+ lines.push("", "EFFICIENCY DECISION (advisory)");
33888
+ for (const decision of report.efficiencyDecisions)
33889
+ lines.push(...efficiencyDecisionLines(decision, true));
33890
+ }
33477
33891
  lines.push("", "PACE");
33478
33892
  let paceRows = 0;
33479
33893
  for (const harness of report.harnesses) {
@@ -33540,6 +33954,7 @@ var init_optimize2 = __esm({
33540
33954
  "apps/cli/dist/src/render/optimize.js"() {
33541
33955
  "use strict";
33542
33956
  init_layout();
33957
+ init_efficiency();
33543
33958
  HARNESS_WIDTH5 = 9;
33544
33959
  STATE_WIDTH4 = 9;
33545
33960
  MODEL_WIDTH2 = 18;
@@ -34130,6 +34545,11 @@ function renderSimpleOptimize(report) {
34130
34545
  if (governor !== void 0)
34131
34546
  lines.push(truncate(` Context governor: ${governor.action}; ${governor.actionableBytes}B actionable local bytes`, MAX_WIDTH));
34132
34547
  }
34548
+ if (report.efficiencyDecisions?.length) {
34549
+ lines.push("", "EFFICIENCY DECISION (advisory)");
34550
+ for (const decision of report.efficiencyDecisions)
34551
+ lines.push(...efficiencyDecisionLines(decision));
34552
+ }
34133
34553
  lines.push(...changeLine(false));
34134
34554
  const candidate = advice.find((item) => item.recommendedEffort !== item.currentEffort || item.recommendedVerbosity !== item.currentVerbosity);
34135
34555
  const canPlan = candidate !== void 0;
@@ -34267,6 +34687,7 @@ var init_simple = __esm({
34267
34687
  "use strict";
34268
34688
  init_src();
34269
34689
  init_layout();
34690
+ init_efficiency();
34270
34691
  }
34271
34692
  });
34272
34693
 
@@ -34994,6 +35415,7 @@ async function run(options) {
34994
35415
  reservePercent: invocation.options.reservePercent,
34995
35416
  tasksRemaining: invocation.options.tasksLeft,
34996
35417
  contextSnapshotPath: invocation.options.contextSnapshot,
35418
+ efficiencyScheduler: options.efficiencyScheduler ?? null,
34997
35419
  nativePolicy: invocation.options.nativePolicy,
34998
35420
  env: options.env ?? {},
34999
35421
  agentSkill: invocation.options.agentSkill,
@@ -36086,6 +36508,8 @@ var init_guided = __esm({
36086
36508
  loading = null;
36087
36509
  readSequence = 0;
36088
36510
  busy = false;
36511
+ operationSequence = 0;
36512
+ backgroundUpdates = null;
36089
36513
  restartVersion = null;
36090
36514
  restartApplication;
36091
36515
  lastApplied = null;
@@ -36327,6 +36751,7 @@ var init_guided = __esm({
36327
36751
  if (this.busy)
36328
36752
  throw new GuideError(409, "Another operation is running. No second change was started.");
36329
36753
  this.busy = true;
36754
+ this.operationSequence++;
36330
36755
  try {
36331
36756
  if (this.reading !== null)
36332
36757
  await this.reading;
@@ -36963,12 +37388,29 @@ var init_guided = __esm({
36963
37388
  return { url };
36964
37389
  });
36965
37390
  }
36966
- async checkUpdates() {
36967
- return this.exclusive(async () => {
36968
- this.approval = null;
37391
+ async checkUpdates(background = false) {
37392
+ if (background && this.backgroundUpdates !== null)
37393
+ return this.backgroundUpdates;
37394
+ const sequence = this.operationSequence;
37395
+ const startedDuringOperation = this.busy;
37396
+ const operation = async () => {
37397
+ if (!background)
37398
+ this.approval = null;
36969
37399
  this.record("Checking Token Harness and optimizer update channels without changing software.", "working");
36970
37400
  const updateResult = await this.call(["update"]);
36971
37401
  const inventory = await this.call(["doctor"]);
37402
+ if (background && (startedDuringOperation || sequence !== this.operationSequence)) {
37403
+ this.record("Background update evidence discarded after another operation started.", "attention");
37404
+ return {
37405
+ ok: false,
37406
+ title: "Update check needs refreshing",
37407
+ messages: [
37408
+ "Another action started during the update check. Check updates again for current versions."
37409
+ ],
37410
+ appliedPlans: 0,
37411
+ ticket: null
37412
+ };
37413
+ }
36972
37414
  if (inventory.data === null) {
36973
37415
  this.updates = null;
36974
37416
  const message = "The current optimizer versions could not be re-read, so update evidence was not attached to the stack. No software changed.";
@@ -37048,7 +37490,7 @@ var init_guided = __esm({
37048
37490
  const upgradableCount = available.length + (applicationUpgradable ? 1 : 0);
37049
37491
  if (upgradableCount > updateTargets.length) {
37050
37492
  messages.push("An update channel reported an update without a concrete target version. No install approval was created.");
37051
- } else if (updateTargets.length > 0) {
37493
+ } else if (updateTargets.length > 0 && !background) {
37052
37494
  ticket = this.random();
37053
37495
  const expires = this.now() + 10 * 6e4;
37054
37496
  this.approval = {
@@ -37076,9 +37518,18 @@ var init_guided = __esm({
37076
37518
  messages,
37077
37519
  appliedPlans: 0,
37078
37520
  stack,
37079
- ticket
37521
+ ticket,
37522
+ ...background ? { updatesAvailable: updateTargets.length > 0 } : {}
37080
37523
  };
37081
- });
37524
+ };
37525
+ if (!background)
37526
+ return this.exclusive(operation);
37527
+ this.backgroundUpdates = operation();
37528
+ try {
37529
+ return await this.backgroundUpdates;
37530
+ } finally {
37531
+ this.backgroundUpdates = null;
37532
+ }
37082
37533
  }
37083
37534
  async verify() {
37084
37535
  return this.exclusive(() => this.verifyIntegrations());
@@ -39107,11 +39558,100 @@ var init_guided_modal_guard_client = __esm({
39107
39558
  }
39108
39559
  });
39109
39560
 
39561
+ // apps/cli/dist/src/guided-optimizer-info.js
39562
+ var GUIDE_OPTIMIZER_INFO;
39563
+ var init_guided_optimizer_info = __esm({
39564
+ "apps/cli/dist/src/guided-optimizer-info.js"() {
39565
+ "use strict";
39566
+ GUIDE_OPTIMIZER_INFO = {
39567
+ rtk: {
39568
+ name: "RTK",
39569
+ role: "Keeps test, build and Git output short so your agent spends less context on noise.",
39570
+ project: "https://github.com/rtk-ai/rtk",
39571
+ managed: true,
39572
+ useful: "A good baseline when your agent runs many shell commands, especially verbose tests, builds and repository searches.",
39573
+ mechanism: "A command proxy filters supported CLI output before the agent reads it, keeping the useful summary and errors.",
39574
+ limitation: "Only supported command output is affected. Prompts, conversation history and model responses are outside this figure; total-session impact depends on your workload.",
39575
+ claim: {
39576
+ headline: "Up to 90% less",
39577
+ scope: "Supported shell-command output",
39578
+ context: "The project headline compares raw and filtered Bash output. Absolute token counts use bytes \xF7 4 estimates; the headline is not a fixed-suite result or a whole-session saving.",
39579
+ source: "https://github.com/rtk-ai/rtk#how-savings-work"
39580
+ }
39581
+ },
39582
+ harnesstrim: {
39583
+ name: "HarnessTrim",
39584
+ role: "Trims repetitive logs and adds guidance that helps agents keep context lean.",
39585
+ project: "https://github.com/giuliastro/HarnessTrim",
39586
+ managed: true,
39587
+ useful: "Useful for long test logs, lint warnings, large diffs, JSON and file listings, with agent guidance across supported coding apps.",
39588
+ mechanism: "Deterministic reducers remove repetitive output while retaining required signals. Harness integrations and skills help agents use those reducers.",
39589
+ limitation: "Only output sent through a reducer is shortened. The reviewed integration can use instructions or hooks depending on the app and version; setup does not prove every tool is intercepted.",
39590
+ claim: {
39591
+ headline: "75.8% less",
39592
+ scope: "Output tokens \xB7 10 fixed fixtures",
39593
+ context: "The published suite goes from 7,747 to 1,876 cl100k_base tokens, retaining 48/48 required signals. Fixture signal retention does not establish live coding-task quality.",
39594
+ source: "https://github.com/giuliastro/HarnessTrim#measured-evidence-with-boundaries"
39595
+ }
39596
+ },
39597
+ mcptoon: {
39598
+ name: "mcptoon",
39599
+ role: "Loads MCP tool definitions on demand instead of keeping the full catalog in context.",
39600
+ project: "https://github.com/activeing123/mcptoon",
39601
+ managed: true,
39602
+ optional: true,
39603
+ useful: "Consider it when many MCP tools make discovery expensive. Compare it with your app\u2019s native deferred tool loading first; small catalogs may gain little.",
39604
+ mechanism: "A compact tool-name index supports discovery; the agent retrieves detailed schemas when needed. Actual tool calls remain JSON.",
39605
+ limitation: "The headline measures a name index, not full schemas or tool results. On-demand schema reads add context; native tool search and your current stack change the marginal benefit.",
39606
+ claim: {
39607
+ headline: "99.2% less",
39608
+ scope: "Discovery index \xB7 255 tools",
39609
+ context: "Published Sample B: 71,929 full-schema tokens \u2192 581 name-index tokens. The richer SLIM schema format is 8,282 tokens (88.5% less), measured with tiktoken.",
39610
+ source: "https://github.com/activeing123/mcptoon/blob/main/docs/tiktoken-benchmarks.md"
39611
+ }
39612
+ },
39613
+ gitnexus: {
39614
+ name: "GitNexus",
39615
+ role: "Maps code relationships so your agent can find symbols, dependencies and affected code.",
39616
+ project: "https://github.com/abhigyanpatwari/GitNexus",
39617
+ managed: true,
39618
+ optional: true,
39619
+ useful: "Consider it for unfamiliar or large repositories, call-chain tracing and change-impact analysis where repeated searches miss relationships.",
39620
+ mechanism: "Builds a local code knowledge graph and exposes focused repository queries through MCP.",
39621
+ limitation: "Needs an up-to-date repository index; Token Harness registers the integration but does not create or refresh that index. The reviewed version has PolyForm Noncommercial terms: check that they fit your use.",
39622
+ claim: {
39623
+ headline: "No published %",
39624
+ scope: "Repository exploration",
39625
+ context: "The project describes more focused code navigation but publishes no comparable token-reduction benchmark in the reviewed README. Evaluate indexing cost and task quality on your repository.",
39626
+ source: "https://github.com/abhigyanpatwari/GitNexus#why-a-knowledge-graph"
39627
+ }
39628
+ },
39629
+ headroom: {
39630
+ name: "Headroom",
39631
+ role: "Compresses large tool payloads and retrieves relevant context through local MCP tools.",
39632
+ project: "https://github.com/headroomlabs-ai/headroom",
39633
+ managed: true,
39634
+ optional: true,
39635
+ useful: "Consider it for large, repetitive JSON, search results or logs. Compact prose and already-trimmed outputs offer less room for improvement.",
39636
+ mechanism: "Compression and retrieval tools help keep bulky payloads out of context. Token Harness manages the local MCP integration.",
39637
+ limitation: "The managed MCP path does not enable the project\u2019s broader proxy features. Library benchmarks do not establish savings from this integration or added value on top of existing reducers.",
39638
+ claim: {
39639
+ headline: "21\u201357% less",
39640
+ scope: "Input tokens \xB7 4 offline scenarios",
39641
+ context: "Published seeded compress() scenarios report 21%, 57%, 42% and 30% reductions. Codebase exploration goes from 58,801 to 33,895 provider-tokenizer tokens; results depend on payload repetition.",
39642
+ source: "https://github.com/headroomlabs-ai/headroom#proof"
39643
+ }
39644
+ }
39645
+ };
39646
+ }
39647
+ });
39648
+
39110
39649
  // apps/cli/dist/src/guided-product-client.js
39111
39650
  var GUIDE_PRODUCT_JS;
39112
39651
  var init_guided_product_client = __esm({
39113
39652
  "apps/cli/dist/src/guided-product-client.js"() {
39114
39653
  "use strict";
39654
+ init_guided_optimizer_info();
39115
39655
  GUIDE_PRODUCT_JS = String.raw`
39116
39656
  'use strict';
39117
39657
  (() => {
@@ -39125,39 +39665,10 @@ var init_guided_product_client = __esm({
39125
39665
  const count = value => new Intl.NumberFormat(undefined, { maximumFractionDigits: 1 }).format(value);
39126
39666
  const date = value => value ? new Date(value).toLocaleString() : 'not recorded';
39127
39667
  const VIEWS = {
39128
- dashboard: ['Overview', 'Your coding agents, optimization stack, health and measured results in one place.'],
39129
- results: ['Results', 'Measured evidence by optimizer, routing and coding app.'],
39130
- };
39131
- const TOOL_INFO = {
39132
- rtk: {
39133
- name: 'RTK',
39134
- role: 'Reduces noisy command output before it reaches the model.',
39135
- managed: true,
39136
- },
39137
- harnesstrim: {
39138
- name: 'HarnessTrim',
39139
- role: 'Adds version-aware instructions that help coding agents keep tool output and context lean.',
39140
- managed: true,
39141
- },
39142
- mcptoon: {
39143
- name: 'mcptoon',
39144
- role: 'Provides compact MCP discovery integration and verifies the resulting setup.',
39145
- managed: true,
39146
- optional: true,
39147
- },
39148
- gitnexus: {
39149
- name: 'GitNexus',
39150
- role: 'Registers GitNexus as a narrow MCP integration for Claude Code and Codex and verifies the result.',
39151
- managed: true,
39152
- optional: true,
39153
- },
39154
- headroom: {
39155
- name: 'Headroom',
39156
- role: 'Provides local MCP compression and retrieval through the installed Headroom server.',
39157
- managed: true,
39158
- optional: true,
39159
- },
39668
+ dashboard: ['Overview', 'Your setup, results and next steps.'],
39669
+ results: ['Results', 'See what changed and the evidence behind it.'],
39160
39670
  };
39671
+ const TOOL_INFO = ${JSON.stringify(GUIDE_OPTIMIZER_INFO)};
39161
39672
  const EXPERIMENTAL = [];
39162
39673
  const CATEGORY = {
39163
39674
  'command-output-reduction': 'Command output',
@@ -39176,8 +39687,8 @@ var init_guided_product_client = __esm({
39176
39687
  let modalRun = 0;
39177
39688
  let pendingTicket = null;
39178
39689
  let updateCheckStarted = false;
39179
- let latestUpdateCheck = null;
39180
39690
  const periodCache = new Map();
39691
+ const openExplanations = new Set();
39181
39692
 
39182
39693
  async function request(path, body) {
39183
39694
  const options = { cache: 'no-store', signal: AbortSignal.timeout(120000) };
@@ -39229,7 +39740,10 @@ var init_guided_product_client = __esm({
39229
39740
  $('view-title').textContent = VIEWS[view][0];
39230
39741
  $('view-description').textContent = VIEWS[view][1];
39231
39742
  if (view === 'results') loadActivity();
39232
- if (focus) $('tab-' + view).focus();
39743
+ if (focus) {
39744
+ $('tab-' + view).focus();
39745
+ $('main').scrollIntoView({ block: 'start' });
39746
+ }
39233
39747
  }
39234
39748
 
39235
39749
  function navigateButton(label, view, cls = 'secondary') {
@@ -39318,6 +39832,58 @@ var init_guided_product_client = __esm({
39318
39832
  return box;
39319
39833
  }
39320
39834
 
39835
+ function projectLink(label, url, accessibleLabel) {
39836
+ const link = node('a', label, 'project-link');
39837
+ link.href = url;
39838
+ link.target = '_blank';
39839
+ link.rel = 'noopener noreferrer';
39840
+ link.setAttribute('aria-label', accessibleLabel + ' (opens in a new tab)');
39841
+ const icon = node('span', '↗', 'external-link-icon');
39842
+ icon.setAttribute('aria-hidden', 'true');
39843
+ link.append(icon);
39844
+ return link;
39845
+ }
39846
+
39847
+ function explanation(key, label, cls = '') {
39848
+ const details = node('details', undefined, 'feature-explanation ' + cls);
39849
+ details.dataset.key = key;
39850
+ details.open = openExplanations.has(key);
39851
+ details.append(node('summary', label));
39852
+ details.addEventListener('toggle', () => {
39853
+ if (details.open) openExplanations.add(key);
39854
+ else openExplanations.delete(key);
39855
+ });
39856
+ return details;
39857
+ }
39858
+
39859
+ function optimizerExplanation(id, info) {
39860
+ const details = explanation('optimizer:' + id, 'When is ' + info.name + ' useful?', 'optimizer-explanation');
39861
+ const body = node('div', undefined, 'explanation-grid');
39862
+ body.append(
39863
+ messageBox('When to consider it', info.useful || info.role),
39864
+ messageBox('How it works', info.mechanism || 'Review the project documentation for this optimizer’s mechanism.'),
39865
+ messageBox('Before you install', info.limitation || 'Check compatibility and measure the benefit on your own workload.'),
39866
+ );
39867
+ const claim = messageBox('What the project reports', info.claim?.context || 'No published benchmark is included for this optimizer.');
39868
+ if (info.claim?.source)
39869
+ claim.append(projectLink('Benchmark & methodology', info.claim.source, info.name + ' benchmark and methodology'));
39870
+ body.append(claim);
39871
+ details.append(body);
39872
+ return details;
39873
+ }
39874
+
39875
+ function routingExplanation(agentId) {
39876
+ const details = explanation('routing:' + agentId, 'How routing works', 'routing-explanation');
39877
+ const model = agentId === 'codex' ? 'gpt-6-luna' : 'Haiku';
39878
+ details.append(
39879
+ messageBox('One prompt, a focused helper', 'On each submitted prompt, a local hook asks your coding agent to consider one native subagent for a substantial, independent piece of work. For example, the helper can research a module while the main agent implements the change.'),
39880
+ messageBox('The main agent stays in charge', 'The policy requests ' + model + ' when available. Your main model reviews and integrates the result. Trivial edits, tightly coupled work, architecture, security and release decisions stay with the main agent.'),
39881
+ messageBox('When it helps', 'Useful when a bounded task can run independently. Delegation can also add overhead and increase total usage; a cheaper helper alone does not prove token or subscription savings.'),
39882
+ messageBox('How to verify it', (agentId === 'codex' ? 'After enabling, review and trust the hook in Codex /hooks. ' : 'After enabling, start a new session so the hook is loaded. ') + 'A callback proves the hook ran; it does not prove delegation or savings. Results credit savings only from paired runs that pass the quality gate.'),
39883
+ );
39884
+ return details;
39885
+ }
39886
+
39321
39887
  function activeAgents() {
39322
39888
  return current?.agents || [];
39323
39889
  }
@@ -39432,7 +39998,7 @@ var init_guided_product_client = __esm({
39432
39998
  const quality = current?.value?.quality;
39433
39999
  if (quality?.state === 'regressed') return { value: 'Regression detected', detail: 'Savings claims are blocked until quality is recovered.', cls: 'warn' };
39434
40000
  if (quality?.state === 'preserved') return { value: 'Preserved', detail: count(quality.pairs) + ' paired benchmark(s) support this result.', cls: 'good' };
39435
- return { value: 'Not measured yet', detail: 'Quality is never inferred from token savings alone.', cls: '' };
40001
+ return { value: 'Not measured yet', detail: 'Quality needs paired benchmarks; output savings alone are not proof.', cls: '' };
39436
40002
  }
39437
40003
 
39438
40004
  function allowanceSummary() {
@@ -39444,7 +40010,7 @@ var init_guided_product_client = __esm({
39444
40010
  if (five?.state === 'measured' && five.savedPercent !== null) parts.push('5h ' + count(five.savedPercent) + '%');
39445
40011
  if (weekly?.state === 'measured' && weekly.savedPercent !== null) parts.push('7d ' + count(weekly.savedPercent) + '%');
39446
40012
  if (parts.length) return { value: parts.join(' · '), detail: 'Based only on authoritative paired allowance evidence.', cls: 'good' };
39447
- return { value: 'Not measured yet', detail: 'Plan savings appear only when before/after allowance evidence exists.', cls: '' };
40013
+ return { value: 'Not measured yet', detail: 'Needs paired before/after allowance readings.', cls: '' };
39448
40014
  }
39449
40015
 
39450
40016
  function metricCard(title, value, detail, cls = '') {
@@ -39470,7 +40036,7 @@ var init_guided_product_client = __esm({
39470
40036
  label: 'Needs attention',
39471
40037
  cls: 'warn',
39472
40038
  title: 'Measured quality needs attention',
39473
- detail: 'A paired benchmark favored the baseline. Token Harness is not crediting the affected savings.',
40039
+ detail: 'A paired benchmark favored the baseline. Affected savings are not credited.',
39474
40040
  action: 'results',
39475
40041
  };
39476
40042
  const routingAttention = agents.filter(agent => agent.promptRouting?.needsRepair ||
@@ -39480,7 +40046,8 @@ var init_guided_product_client = __esm({
39480
40046
  label: 'Routing action required',
39481
40047
  cls: 'warn',
39482
40048
  title: 'Automatic routing needs attention',
39483
- detail: routingAttention.map(agent => agent.name + ': ' + agent.promptRouting.detail).join(' '),
40049
+ detail: routingAttention.map(agent => agent.name + ': ' + (agent.promptRouting.detail ||
40050
+ (agent.promptRouting.enablement === 'untrusted' ? 'Trust the hook in /hooks, then submit a prompt.' : 'Review the hook status in the coding app.'))).join(' '),
39484
40051
  action: 'routing',
39485
40052
  };
39486
40053
  if (stack?.state === 'attention')
@@ -39495,8 +40062,8 @@ var init_guided_product_client = __esm({
39495
40062
  return {
39496
40063
  label: 'Setup available',
39497
40064
  cls: 'warn',
39498
- title: 'Your optimization stack has available setup options',
39499
- detail: 'Choose an optimizer and the coding apps to set it up for. Token Harness shows measured results separately from detected setup.',
40065
+ title: 'Connect your optimization stack',
40066
+ detail: 'Review the recommended optimizers for your coding apps.',
39500
40067
  action: 'configure',
39501
40068
  };
39502
40069
  const unavailable = baselineUnavailableAgents();
@@ -39505,7 +40072,7 @@ var init_guided_product_client = __esm({
39505
40072
  label: 'Setup unavailable',
39506
40073
  cls: '',
39507
40074
  title: 'No automatic optimizer setup is currently available',
39508
- detail: 'The installed providers do not currently expose a compatible managed connection for these coding agents. This is a capability limitation, not unfinished setup.',
40075
+ detail: 'The installed optimizers do not offer a compatible managed connection for these apps.',
39509
40076
  action: 'none',
39510
40077
  };
39511
40078
  if (!(current?.savings?.rows || []).length)
@@ -39513,14 +40080,14 @@ var init_guided_product_client = __esm({
39513
40080
  label: 'Setup detected',
39514
40081
  cls: 'good',
39515
40082
  title: 'Recommended setup is complete',
39516
- detail: 'Setup has been detected. This does not prove an optimizer ran or recorded a result; check the Results page for evidence linked to each agent.',
40083
+ detail: 'Use your coding apps normally. Results will show recorded activity; setup alone is not runtime proof.',
39517
40084
  action: 'results',
39518
40085
  };
39519
40086
  return {
39520
40087
  label: 'Ready',
39521
40088
  cls: 'good',
39522
40089
  title: 'Your setup has been checked',
39523
- detail: 'No setup action is required. The summary below shows which results Token Harness has actually recorded.',
40090
+ detail: 'No setup action required. Open Results to inspect recorded changes.',
39524
40091
  action: 'results',
39525
40092
  };
39526
40093
  }
@@ -39543,9 +40110,12 @@ var init_guided_product_client = __esm({
39543
40110
  if (assessment.action === 'verify') {
39544
40111
  actions.append(actionButton('Re-check health', () => readOnlyOperation('verify')));
39545
40112
  } else if (assessment.action === 'routing') {
39546
- actions.append(actionButton('Review routing', () => $('coding-agents').scrollIntoView({ block: 'start', behavior: 'smooth' })));
40113
+ actions.append(actionButton('Review routing', () => $('coding-agents').scrollIntoView({ block: 'start' })));
39547
40114
  } else if (assessment.action === 'results') {
39548
- actions.append(navigateButton('View detailed results', 'results'));
40115
+ if (current?.value?.quality?.state === 'regressed')
40116
+ actions.append(navigateButton('Review quality evidence', 'results', ''));
40117
+ } else if (assessment.action === 'configure') {
40118
+ actions.append(actionButton('Review recommended setup', () => reviewSetup()));
39549
40119
  }
39550
40120
  if (actions.children.length) main.append(actions);
39551
40121
  $('dashboard-status').append(main, pill(assessment.label, assessment.cls));
@@ -39555,10 +40125,9 @@ var init_guided_product_client = __esm({
39555
40125
  const quality = qualitySummary();
39556
40126
  $('dashboard-metrics').replaceChildren(
39557
40127
  reduction
39558
- ? metricCard('Measured output', reduction.impact.headline, reduction.provider + ' · ' + reduction.measurement, 'positive')
39559
- : metricCard('Measured output', 'No result yet', 'Missing measurements are not reported as zero savings.'),
40128
+ ? metricCard('Recorded output', reduction.impact.headline, reduction.provider + ' · ' + reduction.measurement + ' · changed outputs only', 'positive')
40129
+ : metricCard('Recorded output', 'No result yet', 'Use a connected app to start recording results.'),
39560
40130
  metricCard('5h / 7d allowance', allowance.value, allowance.detail, allowance.cls),
39561
- metricCard('API cost', 'Not measured yet', 'Requires billed-token evidence and a verified price basis.'),
39562
40131
  metricCard('Quality', quality.value, quality.detail, quality.cls),
39563
40132
  );
39564
40133
  }
@@ -39639,7 +40208,7 @@ var init_guided_product_client = __esm({
39639
40208
  ' can be set up from the Optimization stack below.'
39640
40209
  : baseline.state === 'unavailable'
39641
40210
  ? 'No managed baseline connection is currently available for this agent.'
39642
- : 'This card shows detected setup. It does not confirm that an optimizer ran or recorded results.';
40211
+ : 'Optimizer setup detected. Recorded activity appears in Results.';
39643
40212
  card.append(head, node('p', detail));
39644
40213
  card.append(
39645
40214
  node(
@@ -39662,6 +40231,7 @@ var init_guided_product_client = __esm({
39662
40231
  );
39663
40232
  routingCard.append(
39664
40233
  routingHead,
40234
+ node('p', 'Lets your agent delegate suitable work to a smaller native helper while your main model stays in charge.', 'caption'),
39665
40235
  node(
39666
40236
  'p',
39667
40237
  routing?.detail || (routing?.enablement === 'untrusted'
@@ -39676,6 +40246,7 @@ var init_guided_product_client = __esm({
39676
40246
  'caption',
39677
40247
  ),
39678
40248
  );
40249
+ routingCard.append(routingExplanation(agent.id));
39679
40250
  const routingActions = node('div', undefined, 'inline-actions');
39680
40251
  if (routing?.needsRepair) {
39681
40252
  routingActions.append(actionButton('Repair routing', () => reviewPromptRouting(agent.id, true), 'secondary'));
@@ -40019,15 +40590,14 @@ var init_guided_product_client = __esm({
40019
40590
  const agents = activeAgents();
40020
40591
  const ids = optimizerIds();
40021
40592
  if (!agents.length) {
40022
- root.append(sectionEmpty('Optimizer setup will appear when a supported coding app is detected.'));
40023
- return;
40593
+ root.append(sectionEmpty('Explore the optimizers below. Connections become available when a supported coding app is detected.'));
40024
40594
  }
40025
40595
 
40026
40596
  const summary = node('div', undefined, 'connection-summary');
40027
40597
  const summaryText = node('div');
40028
40598
  summaryText.append(
40029
40599
  node('strong', ids.length + ' optimizer' + (ids.length === 1 ? '' : 's') + ' · ' + agents.length + ' coding agent' + (agents.length === 1 ? '' : 's')),
40030
- node('p', 'This matrix shows where setup was detected, not proof that an optimizer ran. Measured results are shown separately on the Results page.', 'caption'),
40600
+ node('p', 'RTK + HarnessTrim are the recommended baseline. Other optimizers are optional.', 'caption'),
40031
40601
  );
40032
40602
  summary.append(summaryText);
40033
40603
  const baselineActionable = ['rtk', 'harnesstrim'].some(id =>
@@ -40036,12 +40606,14 @@ var init_guided_product_client = __esm({
40036
40606
  if (baselineActionable)
40037
40607
  summary.append(actionButton('Set up recommended stack', () => reviewSetup(), ''));
40038
40608
  root.append(summary);
40609
+ root.append(node('p', 'Project-reported figures describe different workloads, not expected savings on your machine. Your measured results stay in Results.', 'caption optimizer-claims-note'));
40039
40610
 
40040
40611
  const scroll = node('div', undefined, 'connection-scroll');
40041
40612
  const table = node('div', undefined, 'connection-table');
40042
- table.style.setProperty('--connection-columns', String(agents.length));
40613
+ table.style.setProperty('--connection-template', 'minmax(240px,1.5fr) minmax(165px,1fr) ' + agents.map(() => 'minmax(110px,.7fr)').join(' ') + ' minmax(150px,.9fr)');
40043
40614
  const header = node('div', undefined, 'connection-row connection-head');
40044
40615
  header.append(node('strong', 'Optimizer', 'connection-name'));
40616
+ header.append(node('strong', 'Project-reported impact', 'optimizer-claim'));
40045
40617
  for (const agent of agents) header.append(node('strong', agent.name, 'connection-cell'));
40046
40618
  header.append(node('strong', 'Action', 'connection-action'));
40047
40619
  table.append(header);
@@ -40049,21 +40621,34 @@ var init_guided_product_client = __esm({
40049
40621
  for (const id of ids) {
40050
40622
  const info = optimizerInfo(id);
40051
40623
  const component = managedComponent(id);
40624
+ const item = node('article', undefined, 'connection-item');
40625
+ item.dataset.optimizer = id;
40626
+ item.setAttribute('aria-label', info.name);
40052
40627
  const row = node('div', undefined, 'connection-row');
40053
40628
  const nameCell = node('div', undefined, 'connection-name');
40629
+ const identity = node('div', undefined, 'optimizer-identity');
40630
+ identity.append(node('strong', info.name));
40631
+ if (info.project) identity.append(projectLink('Source project', info.project, info.name + ' source project'));
40054
40632
  nameCell.append(
40055
- node('strong', info.name),
40633
+ identity,
40056
40634
  node('span', info.optional ? 'Optional optimizer' : 'Recommended baseline', 'caption'),
40057
40635
  node('span', info.role, 'caption connection-role'),
40058
40636
  node('span', component?.version ? 'v' + component.version : 'Not installed', 'caption'),
40059
40637
  );
40060
40638
  row.append(nameCell);
40639
+ const claimCell = node('div', undefined, 'optimizer-claim');
40640
+ claimCell.append(
40641
+ node('span', 'Project-reported impact', 'connection-app-label'),
40642
+ node('strong', info.claim?.headline || 'No published KPI'),
40643
+ node('span', info.claim?.scope || 'No comparable benchmark available', 'caption'),
40644
+ );
40645
+ row.append(claimCell);
40061
40646
  let actionable = false;
40062
40647
  for (const agent of agents) {
40063
40648
  const target = setupTarget(agent.id, id);
40064
40649
  const state = connectionPresentation(target);
40065
40650
  const cell = node('div', undefined, 'connection-cell');
40066
- cell.append(pill(state.label, state.cls));
40651
+ cell.append(node('span', agent.name, 'connection-app-label'), pill(state.label, state.cls));
40067
40652
  row.append(cell);
40068
40653
  actionable ||= target?.state === 'actionable';
40069
40654
  }
@@ -40082,13 +40667,14 @@ var init_guided_product_client = __esm({
40082
40667
  if (component?.managedByTokenHarness || component?.configured) {
40083
40668
  const remove = actionButton('Remove managed setup', () => {
40084
40669
  window.tokenHarnessReviewRemoval?.(id, info.name);
40085
- }, 'secondary');
40670
+ }, 'text-button');
40086
40671
  remove.disabled = busy || typeof window.tokenHarnessReviewRemoval !== 'function';
40087
40672
  action.append(remove);
40088
40673
  }
40089
40674
  if (!action.children.length) action.append(node('span', 'No action', 'caption'));
40090
40675
  row.append(action);
40091
- table.append(row);
40676
+ item.append(row, optimizerExplanation(id, info));
40677
+ table.append(item);
40092
40678
  }
40093
40679
  scroll.append(table);
40094
40680
  root.append(scroll);
@@ -40435,7 +41021,7 @@ var init_guided_product_client = __esm({
40435
41021
  'p',
40436
41022
  current?.stack?.state === 'attention'
40437
41023
  ? 'Something changed or could not be verified. Re-check the configured integrations for details.'
40438
- : 'Setup is already complete. Re-check only when troubleshooting or after external changes.',
41024
+ : 'Re-check integrations after external changes or when troubleshooting.',
40439
41025
  'caption',
40440
41026
  ),
40441
41027
  );
@@ -40459,7 +41045,7 @@ var init_guided_product_client = __esm({
40459
41045
  'p',
40460
41046
  available.length
40461
41047
  ? available.map(component => (TOOL_INFO[component.providerId]?.name || component.providerId) + ' has an update ready.').join(' ')
40462
- : 'Checks Token Harness and installed optimizer versions. If an update is available, install it from the same dialog; restart this app after updating Token Harness.',
41048
+ : 'Check available versions and review updates before installing.',
40463
41049
  'caption',
40464
41050
  ),
40465
41051
  );
@@ -40489,36 +41075,76 @@ var init_guided_product_client = __esm({
40489
41075
  renderMaintenance();
40490
41076
  }
40491
41077
 
40492
- function addEvidenceRow(body, type, name, scope, summary, amount, details) {
40493
- const row = node('tr');
41078
+ function addEvidenceRow(body, type, name, scope, signals, amount, sections) {
41079
+ const row = node('li', undefined, 'evidence-item');
40494
41080
  row.dataset.type = type;
40495
41081
  row.dataset.name = name.toLocaleLowerCase();
40496
- row.dataset.search = [type, name, scope, summary].join(' ').toLocaleLowerCase();
40497
41082
  row.dataset.amount = String(amount || 0);
40498
- const systemCell = node('th');
40499
- systemCell.scope = 'row';
40500
- systemCell.append(node('strong', name), node('span', type[0].toUpperCase() + type.slice(1), 'caption'));
40501
- row.append(systemCell, node('td', scope), node('td', summary));
40502
- const detailCell = node('td');
40503
- const disclosure = node('details');
40504
- disclosure.append(node('summary', 'Details'));
40505
- for (const detail of details) disclosure.append(node('p', detail, 'caption'));
40506
- detailCell.append(disclosure);
40507
- row.append(detailCell);
41083
+ const disclosure = node('details', undefined, 'evidence-disclosure');
41084
+ disclosure.dataset.key = type + ':' + name;
41085
+ const summary = node('summary', undefined, 'evidence-summary');
41086
+ const identity = node('span', undefined, 'evidence-identity');
41087
+ const types = { optimizer: 'Optimizer', routing: 'Routing', harness: 'Coding app', candidate: 'Experiment' };
41088
+ identity.append(node('span', types[type], 'evidence-kind'), node('strong', name), node('span', scope, 'caption'));
41089
+ const results = node('span', undefined, 'evidence-signals');
41090
+ for (const signal of signals) {
41091
+ const result = node('span', undefined, 'evidence-signal ' + (signal.tone || ''));
41092
+ result.append(node('strong', signal.value), node('span', signal.label, 'caption'));
41093
+ results.append(result);
41094
+ }
41095
+ const cue = node('span', 'Details', 'evidence-cue');
41096
+ const chevron = node('span', '›', 'evidence-chevron');
41097
+ chevron.setAttribute('aria-hidden', 'true');
41098
+ cue.append(chevron);
41099
+ summary.append(identity, results, cue);
41100
+ const detailBody = node('div', undefined, 'evidence-detail-body');
41101
+ detailBody.append(...sections);
41102
+ disclosure.append(summary, detailBody);
41103
+ row.append(disclosure);
41104
+ // Search includes provenance, so a class/unit or linked app can be found while collapsed.
41105
+ row.dataset.search = [type, types[type], name, scope, row.textContent].join(' ').toLocaleLowerCase();
40508
41106
  body.append(row);
40509
41107
  return row;
40510
41108
  }
40511
41109
 
40512
- function optimizerEvidenceDetail(row) {
40513
- const unit = row.unit ? ' ' + row.unit : '';
40514
- const change = row.before !== null && row.before !== undefined && row.after !== null && row.after !== undefined
40515
- ? count(row.before) + ' → ' + count(row.after) + unit
40516
- : count(row.saved) + unit;
40517
- return [
40518
- row.impact?.detail || 'Recorded optimizer evidence.',
40519
- 'Recorded change: ' + change,
40520
- count(row.operations) + ' operation(s)' + (row.agents?.length ? ' · ' + row.agents.join(', ') : ' · no harness attribution'),
40521
- ];
41110
+ function evidenceSection(title, facts = [], note = '') {
41111
+ const section = node('section', undefined, 'evidence-section');
41112
+ section.append(node('h3', title));
41113
+ if (facts.length) {
41114
+ const list = node('dl', undefined, 'evidence-fact-grid');
41115
+ for (const [label, value] of facts) {
41116
+ const fact = node('div');
41117
+ fact.append(node('dt', label), node('dd', value));
41118
+ list.append(fact);
41119
+ }
41120
+ section.append(list);
41121
+ }
41122
+ if (note) section.append(node('p', note, 'caption'));
41123
+ return section;
41124
+ }
41125
+
41126
+ function optimizerSignal(row, includeProvider = false) {
41127
+ const impact = row.impact;
41128
+ const value = impact && impact.kind !== 'unavailable'
41129
+ ? impact.headline
41130
+ : count(Math.abs(row.saved)) + ' ' + row.unit + (row.saved < 0 ? ' added' : row.saved > 0 ? ' saved' : ' net change');
41131
+ return {
41132
+ value,
41133
+ label: (includeProvider ? row.provider + ' · ' : '') + row.measurement + ' · ' + row.unit,
41134
+ tone: impact?.kind === 'growth' ? 'warn' : impact?.kind === 'reduction' ? 'good' : '',
41135
+ };
41136
+ }
41137
+
41138
+ function optimizerEvidenceDetail(row, includeProvider = false) {
41139
+ const volume = value => value === null || value === undefined ? 'Not recorded' : count(value) + ' ' + row.unit;
41140
+ return evidenceSection((includeProvider ? row.provider + ' · ' : '') + row.measurement + ' · ' + row.unit, [
41141
+ ['Before', volume(row.before)],
41142
+ ['After', volume(row.after)],
41143
+ [row.saved < 0 ? 'Added' : 'Saved', volume(Math.abs(row.saved))],
41144
+ ['Changed outputs', count(row.operations)],
41145
+ ['Recorded app', row.agents?.length ? row.agents.join(', ') : 'Not attributed'],
41146
+ ], (row.impact?.detail || 'A comparable before/after pair is needed to report a percentage.') +
41147
+ (!row.agents?.length ? ' These records do not identify which coding app ran the command.' : ''));
40522
41148
  }
40523
41149
 
40524
41150
  function routingDetails(agent) {
@@ -40532,16 +41158,18 @@ var init_guided_product_client = __esm({
40532
41158
  else if (routing.enablement === 'enabled' || (!routing.enablement && routing.state === 'managed')) lines.push('Configured; waiting for the first runtime callback after a prompt.');
40533
41159
  else if (routing.state === 'external') lines.push('Routing is managed elsewhere; Token Harness leaves it unchanged.');
40534
41160
  else lines.push('Automatic routing is not enabled for this coding app.');
40535
- if (Number.isFinite(routing.promptSubmissions)) lines.push('Prompt callbacks: ' + count(routing.promptSubmissions));
40536
- if (Number.isFinite(routing.subagentsStarted)) lines.push('Subagents started: ' + count(routing.subagentsStarted));
40537
- if (Number.isFinite(routing.subagentsStopped)) lines.push('Subagents stopped: ' + count(routing.subagentsStopped));
40538
- if (routing.reportedModels?.length) lines.push('Reported models: ' + routing.reportedModels.join(', '));
40539
- if (routing.lastObservedAt) lines.push('Last callback: ' + date(routing.lastObservedAt));
40540
- return lines;
41161
+ const facts = [['Verification', tier === 'runtime-observed' ? 'Runtime callback observed' : tier === 'config-only' ? 'Configuration only' : 'Not verified']];
41162
+ if (Number.isFinite(routing.promptSubmissions)) facts.push(['Prompt callbacks', count(routing.promptSubmissions)]);
41163
+ if (Number.isFinite(routing.subagentsStarted)) facts.push(['Subagents started', count(routing.subagentsStarted)]);
41164
+ if (Number.isFinite(routing.subagentsStopped)) facts.push(['Subagents stopped', count(routing.subagentsStopped)]);
41165
+ if (routing.reportedModels?.length) facts.push(['Reported models', routing.reportedModels.join(', ')]);
41166
+ if (routing.lastObservedAt) facts.push(['Last callback', date(routing.lastObservedAt)]);
41167
+ return evidenceSection(agent.name + ' · routing activity', facts, lines[0]);
40541
41168
  }
40542
41169
 
40543
41170
  function renderEvidence() {
40544
41171
  const body = $('result-evidence');
41172
+ const openKeys = new Set([...body.querySelectorAll('details[open]')].map(item => item.dataset.key));
40545
41173
  body.replaceChildren();
40546
41174
  const savings = current?.savings?.rows || [];
40547
41175
  for (const id of optimizerIds()) {
@@ -40549,58 +41177,69 @@ var init_guided_product_client = __esm({
40549
41177
  const component = managedComponent(id);
40550
41178
  const measured = savings.filter(row => row.providerId === id);
40551
41179
  const scope = component?.configuredHarnesses?.length
40552
- ? component.configuredHarnesses.map(agentName).join(', ')
41180
+ ? 'Setup: ' + component.configuredHarnesses.map(agentName).join(', ')
40553
41181
  : 'No setup detected';
40554
- const summary = measured.length
40555
- ? measured.map(row => row.measurement + ' · ' + count(row.saved) + (row.unit ? ' ' + row.unit : '')).join(' · ')
40556
- : 'No measured evidence';
40557
- const details = measured.length
40558
- ? measured.flatMap(optimizerEvidenceDetail)
40559
- : [component?.configured ? 'Setup is detected, but no result was recorded for this period.' : 'No result was recorded for this optimizer in this period.'];
40560
- addEvidenceRow(body, 'optimizer', info.name, scope, summary, measured.length, details);
41182
+ const signals = measured.length
41183
+ ? measured.map(row => optimizerSignal(row))
41184
+ : [{ value: 'No results yet', label: 'No output recorded for this period' }];
41185
+ const sections = measured.map(row => optimizerEvidenceDetail(row));
41186
+ if (!measured.length) {
41187
+ const nextStep = evidenceSection('Start recording results', [], component?.configured
41188
+ ? 'Use a connected coding app normally, then Refresh. Detected setup alone does not prove that the optimizer ran.'
41189
+ : 'Review this optimizer in Overview to see available connections.');
41190
+ nextStep.append(navigateButton('Open Overview', 'dashboard'));
41191
+ sections.push(nextStep);
41192
+ }
41193
+ addEvidenceRow(body, 'optimizer', info.name, scope, signals, measured.length, sections);
40561
41194
  }
40562
41195
 
40563
41196
  const routing = current?.value?.routing;
40564
41197
  const routingAgents = activeAgents();
40565
- const routingDetailsList = routingAgents.flatMap(agent => [agent.name + ':', ...routingDetails(agent)]);
40566
- if (routing?.state === 'measured' || routing?.pairs > 0) {
40567
- routingDetailsList.push((routing.pairs ? count(routing.pairs) + ' quality-passed routed pair(s).' : ''));
40568
- if (routing.savedLocalTokens !== null && routing.savedLocalTokens !== undefined)
40569
- routingDetailsList.push(routing.savedLocalTokens >= 0
40570
- ? count(routing.savedLocalTokens) + ' local tokens saved · end-to-end local usage'
40571
- : count(Math.abs(routing.savedLocalTokens)) + ' local tokens added · end-to-end local usage');
40572
- if (routing.allowance5h?.savedPercent !== null && routing.allowance5h?.savedPercent !== undefined)
40573
- routingDetailsList.push('5h allowance change: ' + count(routing.allowance5h.savedPercent) + '%');
40574
- if (routing.allowance7d?.savedPercent !== null && routing.allowance7d?.savedPercent !== undefined)
40575
- routingDetailsList.push('7d allowance change: ' + count(routing.allowance7d.savedPercent) + '%');
40576
- }
40577
- const routingSummary = routing?.state === 'blocked-by-quality'
40578
- ? 'Not credited · quality gate'
40579
- : routing?.savedLocalTokens !== null && routing?.savedLocalTokens !== undefined
40580
- ? count(routing.savedLocalTokens) + ' local tokens · end-to-end paired evidence'
40581
- : routing?.state === 'measured' ? 'Allowance evidence measured' : 'Not measured yet';
40582
- addEvidenceRow(body, 'routing', 'Automatic prompt routing', routingAgents.map(agent => agent.name).join(', ') || 'No coding app detected', routingSummary, routing?.pairs || 0, routingDetailsList.length ? routingDetailsList : ['No routing measurement has been recorded.']);
41198
+ const blocked = routing?.state === 'blocked-by-quality';
41199
+ const routeSignals = [];
41200
+ if (blocked) routeSignals.push({ value: 'Not credited', label: 'Quality gate did not pass', tone: 'warn' });
41201
+ else {
41202
+ if (routing?.savedLocalTokens !== null && routing?.savedLocalTokens !== undefined)
41203
+ routeSignals.push({
41204
+ value: count(Math.abs(routing.savedLocalTokens)) + (routing.savedLocalTokens < 0 ? ' tokens added' : ' tokens saved'),
41205
+ label: 'Paired end-to-end local usage',
41206
+ tone: routing.savedLocalTokens < 0 ? 'warn' : routing.savedLocalTokens > 0 ? 'good' : '',
41207
+ });
41208
+ for (const [key, label] of [['allowance5h', '5h allowance'], ['allowance7d', '7d allowance']]) {
41209
+ const evidence = routing?.[key];
41210
+ if (evidence?.state === 'measured' && evidence.savedPercent !== null && evidence.savedPercent !== undefined)
41211
+ routeSignals.push({ value: count(evidence.savedPercent) + '%', label: label + ' saved · paired evidence', tone: evidence.savedPercent < 0 ? 'warn' : 'good' });
41212
+ }
41213
+ if (!routeSignals.length) routeSignals.push({ value: 'Not measured yet', label: 'Needs paired, quality-passed runs' });
41214
+ }
41215
+ const routingSections = [evidenceSection('Savings verification', [['Quality-passed pairs', count(routing?.pairs || 0)]],
41216
+ blocked ? 'A quality regression blocks the savings claim.' : 'Callback activity proves the hook ran. Savings require paired runs with a passing quality gate.')];
41217
+ for (const agent of routingAgents)
41218
+ routingSections.push(routingDetails(agent));
41219
+ addEvidenceRow(body, 'routing', 'Automatic prompt routing', routingAgents.map(agent => agent.name).join(', ') || 'No coding app detected', routeSignals, routing?.pairs || 0, routingSections);
40583
41220
 
40584
41221
  for (const agent of routingAgents) {
40585
41222
  const linked = savings.filter(row => row.harnesses?.includes(agent.id));
40586
41223
  const configured = configuredProviders().filter(component => component.configuredHarnesses?.includes(agent.id)).map(component => optimizerInfo(component.providerId).name);
40587
- const details = [
40588
- 'Detected optimizer setup: ' + (configured.join(', ') || 'none'),
40589
- ...routingDetails(agent),
40590
- ...(linked.length ? linked.flatMap(optimizerEvidenceDetail) : ['No optimizer measurement is directly linked to this coding app.']),
40591
- ];
40592
- addEvidenceRow(body, 'harness', agent.name, agent.version ? 'v' + agent.version : 'Version unavailable', linked.length ? linked.map(row => row.provider + ': ' + row.measurement + ' · ' + count(row.saved) + (row.unit ? ' ' + row.unit : '')).join(' · ') : 'No linked measured evidence', linked.length, details);
41224
+ const sections = [evidenceSection('App attribution', [['Detected setup', configured.join(', ') || 'None']],
41225
+ linked.length ? 'These are the same optimizer records shown above, linked to this app. They are not additional savings.' : 'No optimizer record identifies this app for the selected period. Unattributed records stay under their optimizer.')];
41226
+ sections.push(...linked.map(row => optimizerEvidenceDetail(row, true)));
41227
+ addEvidenceRow(body, 'harness', agent.name, agent.version ? 'v' + agent.version : 'Version unavailable',
41228
+ linked.length ? linked.map(row => optimizerSignal(row, true)) : [{ value: 'No linked results', label: 'No output attributed to this app' }], linked.length, sections);
40593
41229
  }
40594
41230
 
40595
41231
  for (const item of current?.value?.candidates || []) {
40596
41232
  if (!(item.pairs > 0)) continue;
40597
41233
  const candidate = (current?.optimizationCandidates || []).find(entry => entry.id === item.candidateId);
40598
41234
  const name = candidate?.name || item.candidateId;
40599
- addEvidenceRow(body, 'candidate', name, 'Experimental', count(item.pairs) + ' paired result(s)', item.pairs, [
40600
- count(item.optimizedBetter || 0) + ' optimized better · ' + count(item.baselineBetter || 0) + ' baseline better.',
40601
- 'Evaluation evidence only; this does not automatically promote or activate the candidate.',
41235
+ addEvidenceRow(body, 'candidate', name, 'Experimental', [{ value: count(item.pairs) + ' paired results', label: 'Evaluation evidence' }], item.pairs, [
41236
+ evidenceSection('Paired evaluation', [
41237
+ ['Optimized better', count(item.optimizedBetter || 0)],
41238
+ ['Baseline better', count(item.baselineBetter || 0)],
41239
+ ], 'Evaluation does not automatically promote or activate this optimizer.'),
40602
41240
  ]);
40603
41241
  }
41242
+ for (const details of body.querySelectorAll('details')) details.open = openKeys.has(details.dataset.key);
40604
41243
  applyEvidenceFilters();
40605
41244
  }
40606
41245
 
@@ -40610,18 +41249,23 @@ var init_guided_product_client = __esm({
40610
41249
  const filter = $('evidence-filter').value.trim().toLocaleLowerCase();
40611
41250
  const type = $('evidence-type').value;
40612
41251
  const sort = $('evidence-sort').value;
40613
- const rows = [...body.querySelectorAll('tr')];
41252
+ const rows = [...body.children].filter(row => row.dataset.type);
41253
+ const sourceOrder = { optimizer: 0, routing: 1, harness: 2, candidate: 3 };
40614
41254
  rows.sort((a, b) => sort === 'evidence'
40615
- ? Number(b.dataset.amount) - Number(a.dataset.amount) || a.dataset.name.localeCompare(b.dataset.name)
41255
+ ? Number(Number(b.dataset.amount) > 0) - Number(Number(a.dataset.amount) > 0)
41256
+ || sourceOrder[a.dataset.type] - sourceOrder[b.dataset.type]
41257
+ || Number(b.dataset.amount) - Number(a.dataset.amount) || a.dataset.name.localeCompare(b.dataset.name)
40616
41258
  : sort === 'type'
40617
41259
  ? a.dataset.type.localeCompare(b.dataset.type) || a.dataset.name.localeCompare(b.dataset.name)
40618
41260
  : a.dataset.name.localeCompare(b.dataset.name));
40619
41261
  for (const row of rows) {
40620
- const shown = (type === 'all' || row.dataset.type === type) && (!filter || row.dataset.search.includes(filter));
40621
- row.hidden = !shown;
41262
+ row.hidden = !((type === 'all' || row.dataset.type === type) && (!filter || row.dataset.search.includes(filter)));
40622
41263
  body.append(row);
40623
41264
  }
40624
- $('evidence-empty').hidden = rows.some(row => !row.hidden);
41265
+ const visible = rows.filter(row => !row.hidden).length;
41266
+ $('evidence-count').textContent = visible + ' of ' + rows.length + ' sources';
41267
+ $('evidence-empty').hidden = visible > 0;
41268
+ $('evidence-reset').hidden = !filter && type === 'all';
40625
41269
  }
40626
41270
 
40627
41271
  function measurementHelp() {
@@ -40640,8 +41284,11 @@ var init_guided_product_client = __esm({
40640
41284
  const allowance = allowanceSummary();
40641
41285
  const quality = qualitySummary();
40642
41286
  const savings = current?.savings?.rows || [];
41287
+ const reduction = bestReduction();
40643
41288
  $('result-summary').replaceChildren(
40644
- metricCard('Measured output', savings.length ? count(savings.length) + ' evidence record(s)' : 'No records yet', 'Exact, estimated and other measurement classes remain separate.'),
41289
+ reduction
41290
+ ? metricCard('Recorded output', reduction.impact.headline, reduction.provider + ' · ' + reduction.measurement + ' · changed outputs only', 'positive')
41291
+ : metricCard('Recorded output', savings.length ? count(savings.length) + ' measurement groups' : 'No records yet', savings.length ? 'Open Evidence for each source and unit.' : 'Use a connected app, then Refresh.'),
40645
41292
  metricCard('5h / 7d allowance', allowance.value, allowance.detail, allowance.cls),
40646
41293
  metricCard('Quality', quality.value, quality.detail, quality.cls),
40647
41294
  );
@@ -40649,13 +41296,14 @@ var init_guided_product_client = __esm({
40649
41296
  const routeStatus = routed?.state === 'blocked-by-quality'
40650
41297
  ? 'Not credited'
40651
41298
  : routed?.savedLocalTokens !== null && routed?.savedLocalTokens !== undefined
40652
- ? count(routed.savedLocalTokens) + ' local tokens'
41299
+ ? count(Math.abs(routed.savedLocalTokens)) + (routed.savedLocalTokens < 0 ? ' tokens added' : ' tokens saved')
40653
41300
  : routed?.state === 'measured' ? 'Allowance measured' : 'Not measured yet';
40654
- $('result-summary').append(metricCard('Automatic routing', routeStatus, routed?.pairs ? count(routed.pairs) + ' quality-passed pair(s). Allowance and local tokens are separate.' : 'Routing savings need paired, quality-gated evidence.', routed?.state === 'measured' ? 'positive' : ''));
41301
+ $('result-summary').append(metricCard('Automatic routing', routeStatus, routed?.pairs ? count(routed.pairs) + ' quality-passed pairs · local usage' : 'Needs paired runs with a passing quality gate.', routed?.state === 'blocked-by-quality' || routed?.savedLocalTokens < 0 ? 'warn' : routed?.state === 'measured' ? 'positive' : ''));
40655
41302
  renderEvidence();
40656
41303
  $('results-period-note').textContent = current?.savings?.firstRecordedAt
40657
- ? 'Recorded from ' + date(current.savings.firstRecordedAt) + ' through ' + date(current.savings.lastRecordedAt)
40658
- : 'No recorded result dates for this period.';
41304
+ ? 'All locally recorded projects · ' + new Date(current.savings.firstRecordedAt).toLocaleDateString() + ' – ' + new Date(current.savings.lastRecordedAt).toLocaleDateString()
41305
+ : 'All locally recorded projects · no results for this period.';
41306
+ if (current?.savings?.errors) $('results-period-note').textContent += ' · ' + count(current.savings.errors) + ' records could not be read';
40659
41307
  }
40660
41308
 
40661
41309
  function renderActivity() {
@@ -40691,16 +41339,6 @@ var init_guided_product_client = __esm({
40691
41339
  }
40692
41340
  }
40693
41341
 
40694
- function reviewUpdate(result) {
40695
- if (!result?.ticket || busy) return;
40696
- modal('Review Token Harness update');
40697
- $('modal-content').append(
40698
- messageBox('Update available', (result.messages || []).join(' ') || result.title || 'A reviewed Token Harness update is ready.'),
40699
- messageBox('Health re-check', 'After installation, Token Harness will re-check optimizer health automatically.'),
40700
- );
40701
- $('modal-actions').append(modalClose('Cancel'), actionButton('Install updates', () => applyTicket(result.ticket)));
40702
- }
40703
-
40704
41342
  async function checkUpdatesOnStartup() {
40705
41343
  if (updateCheckStarted) return;
40706
41344
  if ($('modal').open) {
@@ -40714,14 +41352,13 @@ var init_guided_product_client = __esm({
40714
41352
  updateCheckStarted = true;
40715
41353
  try {
40716
41354
  await ensureSession();
40717
- const result = await request('/api/update-check', { period: $('period').value });
41355
+ const result = await request('/api/update-check', { period: $('period').value, background: true });
40718
41356
  if (busy || reading || $('modal').open) {
40719
41357
  updateCheckStarted = false;
40720
41358
  if ($('modal').open) $('modal').addEventListener('close', checkUpdatesOnStartup, { once: true });
40721
41359
  else setTimeout(checkUpdatesOnStartup, 1000);
40722
41360
  return;
40723
41361
  }
40724
- latestUpdateCheck = result;
40725
41362
  if (result.stack && current) {
40726
41363
  current = { ...current, stack: result.stack };
40727
41364
  renderDashboard();
@@ -40730,13 +41367,13 @@ var init_guided_product_client = __esm({
40730
41367
  }
40731
41368
  const root = $('update-notice');
40732
41369
  root.replaceChildren();
40733
- if (!result.ticket) {
41370
+ if (!result.updatesAvailable) {
40734
41371
  root.hidden = true;
40735
41372
  return;
40736
41373
  }
40737
41374
  const copy = node('div');
40738
41375
  copy.append(node('strong', result.title || 'Token Harness update available'), node('p', (result.messages || []).join(' ') || 'Review and install the available update.', 'caption'));
40739
- root.append(copy, actionButton('Review update', () => reviewUpdate(latestUpdateCheck), 'secondary'));
41376
+ root.append(copy, actionButton('Review update', () => readOnlyOperation('update-check'), 'secondary'));
40740
41377
  root.hidden = false;
40741
41378
  } catch {
40742
41379
  // The startup version check is supplementary; Refresh and Health and updates remain available.
@@ -40791,7 +41428,7 @@ var init_guided_product_client = __esm({
40791
41428
  $('stale-state').textContent = '';
40792
41429
  render();
40793
41430
  await loadActivity();
40794
- setStatus('Checked at ' + new Date(current.generatedAt).toLocaleTimeString() + '. Full checks run again only when you choose Refresh.', false);
41431
+ setStatus('Updated at ' + new Date(current.generatedAt).toLocaleTimeString(), false);
40795
41432
  } catch (error) {
40796
41433
  setError(error.name === 'TimeoutError' ? 'The check took too long. Existing results were kept; choose Refresh to try again.' : error.message);
40797
41434
  setStatus('Check needs attention.', false);
@@ -40838,11 +41475,28 @@ var init_guided_product_client = __esm({
40838
41475
  document.querySelectorAll('[data-view]').forEach(button => {
40839
41476
  button.addEventListener('click', () => selectView(button.dataset.view, true));
40840
41477
  });
41478
+ document.querySelector('.view-tabs').addEventListener('keydown', event => {
41479
+ const views = Object.keys(VIEWS);
41480
+ const index = views.indexOf(selectedView);
41481
+ const next = event.key === 'Home' ? 0 : event.key === 'End' ? views.length - 1
41482
+ : event.key === 'ArrowRight' ? (index + 1) % views.length
41483
+ : event.key === 'ArrowLeft' ? (index + views.length - 1) % views.length : null;
41484
+ if (next === null) return;
41485
+ event.preventDefault();
41486
+ selectView(views[next], true);
41487
+ });
41488
+ $('overview-results').addEventListener('click', () => selectView('results', true));
40841
41489
  $('refresh').addEventListener('click', () => refresh(true));
40842
41490
  $('period').addEventListener('change', changePeriod);
40843
41491
  $('evidence-filter').addEventListener('input', applyEvidenceFilters);
40844
41492
  $('evidence-type').addEventListener('change', applyEvidenceFilters);
40845
41493
  $('evidence-sort').addEventListener('change', applyEvidenceFilters);
41494
+ $('evidence-reset').addEventListener('click', () => {
41495
+ $('evidence-filter').value = '';
41496
+ $('evidence-type').value = 'all';
41497
+ applyEvidenceFilters();
41498
+ $('evidence-filter').focus();
41499
+ });
40846
41500
  $('measurement-help').addEventListener('click', measurementHelp);
40847
41501
  $('theme').addEventListener('change', () => {
40848
41502
  const value = $('theme').value;
@@ -40873,26 +41527,237 @@ var init_guided_product_styles = __esm({
40873
41527
  GUIDE_PRODUCT_CSS = String.raw`
40874
41528
  [hidden]{display:none!important}
40875
41529
  .eyebrow{display:block;color:var(--muted);font-size:.72rem;font-weight:900;letter-spacing:.08em;margin-bottom:.35rem}
40876
- .dashboard-status{display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;background:linear-gradient(145deg,var(--panel),var(--panel-soft));border:1px solid var(--line);border-radius:var(--radius);padding:1.35rem;box-shadow:var(--shadow);margin:1rem 0}.dashboard-status h2{margin:.15rem 0 .45rem;font-size:1.35rem}.dashboard-status p{color:var(--muted);margin:.25rem 0 1rem;max-width:720px}
40877
- .dashboard-columns{display:grid;grid-template-columns:minmax(0,1fr) minmax(300px,.55fr);gap:.9rem;margin:1rem 0}.dashboard-columns>.panel h2{margin-top:0}.status-list{display:grid;gap:.15rem}.status-row{display:flex;justify-content:space-between;gap:1rem;align-items:center;padding:.72rem 0;border-bottom:1px solid var(--line)}.status-row:last-child{border-bottom:0}
40878
- .checklist{display:grid;gap:.25rem}.check-row{display:grid;grid-template-columns:28px 1fr;gap:.5rem;padding:.55rem 0}.check-row p{margin:.15rem 0}.check-icon{display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--line);border-radius:999px;color:var(--muted);font-weight:900}.check-icon.done{background:var(--good-soft);border-color:color-mix(in srgb,var(--good) 35%,var(--line));color:var(--good)}
40879
- .setup-intro{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:1rem;align-items:start;background:var(--accent-soft);border:1px solid color-mix(in srgb,var(--accent) 30%,var(--line));border-radius:var(--radius);padding:1rem 1.15rem;margin:1rem 0}.setup-intro h2{margin:.1rem 0 .3rem}.setup-intro p{margin:.2rem 0;color:var(--muted)}
40880
- .setup-step{margin:1.6rem 0}.step-heading{display:grid;grid-template-columns:34px 1fr;gap:.65rem;align-items:start;margin-bottom:.7rem}.step-number{display:grid;place-items:center;width:32px;height:32px;border-radius:9px;background:var(--accent);color:#fff;font-weight:900}.step-heading h2{margin:0}.step-heading p{margin:.2rem 0;color:var(--muted)}
40881
- .connection-overview{display:grid;gap:.75rem}.connection-summary{display:flex;align-items:center;justify-content:space-between;gap:1rem;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:1rem}.connection-summary p{margin:.15rem 0 0}.connection-scroll{overflow-x:auto;border:1px solid var(--line);border-radius:var(--radius);background:var(--panel)}.connection-table{min-width:max(720px,100%)}.connection-row{display:grid;grid-template-columns:minmax(170px,1.25fr) repeat(var(--connection-columns),minmax(130px,1fr)) minmax(155px,.8fr);align-items:center;gap:.6rem;padding:.72rem .8rem;border-bottom:1px solid var(--line)}.connection-row:last-child{border-bottom:0}.connection-head{background:var(--panel-soft);color:var(--muted);font-size:.8rem}.connection-name{display:grid;gap:.12rem}.connection-cell,.connection-action{min-width:0}.connection-action{display:flex;justify-content:flex-end}.tool-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.8rem}.candidate-comparison-toolbar{grid-column:1/-1;justify-content:flex-end;align-self:start}.tool-card{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:1rem;box-shadow:var(--shadow)}.tool-card.experimental{border-style:dashed}.tool-card.compact{box-shadow:none}.tool-card>p{color:var(--muted);margin:.65rem 0}.tool-head{display:flex;align-items:flex-start;justify-content:space-between;gap:.75rem}.tool-head h3{margin:0}.tool-facts{display:grid;grid-template-columns:auto 1fr;gap:.3rem .75rem;border-top:1px solid var(--line);border-bottom:1px solid var(--line);padding:.65rem 0;margin:.65rem 0}.tool-facts span{color:var(--muted);font-size:.8rem}.tool-facts strong{font-size:.85rem}
40882
- .connection-role{max-width:28ch}.setup-choice-list{display:grid;gap:.55rem;margin:.9rem 0}.setup-choice-list h3{margin:.25rem 0 0}.setup-choice{display:grid;grid-template-columns:auto 1fr;align-items:start;gap:.7rem;padding:.8rem;border:1px solid var(--line);border-radius:12px;background:var(--panel);cursor:pointer}.setup-choice:hover{border-color:var(--accent);background:var(--accent-soft)}.setup-choice input{inline-size:1.1rem;block-size:1.1rem;margin:.15rem 0 0;accent-color:var(--accent)}.setup-choice-copy{display:grid;gap:.2rem}.setup-choice-limitation{color:var(--muted)}
40883
- .routing-feature{margin:.8rem 0;padding:.8rem;border:1px solid var(--line);border-radius:12px;background:var(--panel-soft)}.routing-feature .tool-head{align-items:center}.routing-feature p{margin:.55rem 0;color:var(--muted)}
40884
- .managed-action-box{margin-top:.8rem;background:var(--panel-soft);border:1px solid var(--line);border-radius:12px;padding:.85rem}.managed-action-box p{margin:.1rem 0 .65rem}
40885
- .maintenance-list{display:grid;gap:.55rem}.maintenance-row{display:flex;align-items:center;justify-content:space-between;gap:1rem;background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:.8rem}.maintenance-row p{margin:.15rem 0}
40886
- .explain-box{background:var(--panel-soft);border:1px solid var(--line);border-radius:12px;padding:.8rem;margin:.6rem 0}.explain-box p{margin:.25rem 0;color:var(--muted)}.explain-box.warn{background:var(--warn-soft);border-color:color-mix(in srgb,var(--warn) 35%,var(--line))}.explain-box.safe{background:var(--good-soft);border-color:color-mix(in srgb,var(--good) 30%,var(--line))}.operation-progress{margin:.75rem 0;padding:.8rem;border:1px solid var(--line);border-radius:12px}.operation-progress p{margin:.35rem 0 0}
40887
- .choice-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.6rem;margin:.8rem 0}.choice-button{display:flex;flex-direction:column;align-items:flex-start;text-align:left;gap:.25rem;background:var(--panel);color:var(--text);border:1px solid var(--line);padding:.8rem}.choice-button:hover:not(:disabled){border-color:var(--accent);background:var(--accent-soft)}.choice-button .caption{font-weight:500}
40888
- .result-signal{display:grid;gap:.2rem;border-top:1px solid var(--line);padding:.65rem 0}.result-signal strong{font-size:1rem}.results-header{display:flex;justify-content:space-between;gap:1rem;align-items:end;margin:1rem 0}.results-header h2{margin:0}.results-header p{margin:.2rem 0;color:var(--muted)}
40889
- .update-notice{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:.8rem 1rem;margin:.8rem 0;border:1px solid color-mix(in srgb,var(--accent) 40%,var(--line));border-radius:var(--radius);background:var(--accent-soft)}.update-notice p{margin:.2rem 0 0;color:var(--muted)}
41530
+ .dashboard-status{display:flex;align-items:flex-start;justify-content:space-between;gap:1rem;background:linear-gradient(145deg,var(--panel),var(--panel-soft));border:1px solid var(--line);border-radius:var(--radius);padding:1.35rem;box-shadow:var(--shadow);margin:1rem 0}
41531
+ .dashboard-status h2{margin:.15rem 0 .45rem;font-size:1.35rem}
41532
+ .dashboard-status p{color:var(--muted);margin:.25rem 0 1rem;max-width:720px}
41533
+ .dashboard-columns{display:grid;grid-template-columns:minmax(0,1fr) minmax(300px,.55fr);gap:.9rem;margin:1rem 0}
41534
+ .dashboard-columns>.panel h2{margin-top:0}
41535
+ .status-list{display:grid;gap:.15rem}
41536
+ .status-row{display:flex;justify-content:space-between;gap:1rem;align-items:center;padding:.72rem 0;border-bottom:1px solid var(--line)}
41537
+ .status-row:last-child{border-bottom:0}
41538
+ .checklist{display:grid;gap:.25rem}
41539
+ .check-row{display:grid;grid-template-columns:28px 1fr;gap:.5rem;padding:.55rem 0}
41540
+ .check-row p{margin:.15rem 0}
41541
+ .check-icon{display:grid;place-items:center;width:24px;height:24px;border:1px solid var(--line);border-radius:999px;color:var(--muted);font-weight:900}
41542
+ .check-icon.done{background:var(--good-soft);border-color:color-mix(in srgb,var(--good) 35%,var(--line));color:var(--good)}
41543
+ .setup-intro{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:1rem;align-items:start;background:var(--accent-soft);border:1px solid color-mix(in srgb,var(--accent) 30%,var(--line));border-radius:var(--radius);padding:1rem 1.15rem;margin:1rem 0}
41544
+ .setup-intro h2{margin:.1rem 0 .3rem}
41545
+ .setup-intro p{margin:.2rem 0;color:var(--muted)}
41546
+ .setup-step{margin:1.6rem 0}
41547
+ .step-heading{display:grid;grid-template-columns:34px 1fr;gap:.65rem;align-items:start;margin-bottom:.7rem}
41548
+ .step-number{display:grid;place-items:center;width:32px;height:32px;border-radius:9px;background:var(--accent);color:#fff;font-weight:900}
41549
+ .step-heading h2{margin:0}
41550
+ .step-heading p{margin:.2rem 0;color:var(--muted)}
41551
+ .connection-overview{display:grid;gap:.75rem}
41552
+ .connection-summary{display:flex;align-items:center;justify-content:space-between;gap:1rem;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:1rem}
41553
+ .connection-summary p{margin:.15rem 0 0}
41554
+ .connection-scroll{overflow-x:auto;border:1px solid var(--line);border-radius:var(--radius);background:var(--panel)}
41555
+ .connection-table{min-width:100%}
41556
+ .connection-row{display:grid;grid-template-columns:var(--connection-template);align-items:center;gap:.8rem;padding:1rem;border-bottom:1px solid var(--line)}
41557
+ .connection-row:last-child{border-bottom:0}
41558
+ .connection-head{background:var(--panel-soft);color:var(--muted);font-size:.8rem}
41559
+ .connection-name{display:grid;gap:.25rem;min-width:0}
41560
+ .connection-cell,.connection-action{min-width:0}
41561
+ .connection-action{display:flex;justify-content:flex-end}
41562
+ .tool-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.8rem}
41563
+ .candidate-comparison-toolbar{grid-column:1/-1;justify-content:flex-end;align-self:start}
41564
+ .tool-card{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:1rem;box-shadow:var(--shadow)}
41565
+ .tool-card.experimental{border-style:dashed}
41566
+ .tool-card.compact{box-shadow:none}
41567
+ .tool-card>p{color:var(--muted);margin:.65rem 0}
41568
+ .tool-head{display:flex;align-items:flex-start;justify-content:space-between;gap:.75rem}
41569
+ .tool-head h3{margin:0}
41570
+ .tool-facts{display:grid;grid-template-columns:auto 1fr;gap:.3rem .75rem;border-top:1px solid var(--line);border-bottom:1px solid var(--line);padding:.65rem 0;margin:.65rem 0}
41571
+ .tool-facts span{color:var(--muted);font-size:.8rem}
41572
+ .tool-facts strong{font-size:.85rem}
41573
+ .connection-role{max-width:45ch;line-height:1.5}
41574
+ .connection-item{border-bottom:1px solid var(--line)}
41575
+ .connection-item:last-child{border-bottom:0}
41576
+ .connection-item>.connection-row{border:0}
41577
+ .optimizer-identity{display:flex;align-items:center;gap:.6rem;flex-wrap:wrap}
41578
+ .optimizer-identity>strong{font-size:.95rem}
41579
+ .project-link{display:inline-flex;align-items:center;gap:.3rem;min-height:32px;color:var(--accent);font-size:.78rem;font-weight:600;text-decoration:underline;text-underline-offset:3px;border-radius:4px}
41580
+ .project-link:hover{color:var(--text)}
41581
+ .external-link-icon{font-size:.9rem;text-decoration:none}
41582
+ .optimizer-claim{display:grid;gap:.3rem;min-width:0;align-content:start}
41583
+ .optimizer-claim>strong{font-size:1.05rem;font-variant-numeric:tabular-nums}
41584
+ .connection-head .optimizer-claim{font-size:inherit}
41585
+ .optimizer-claims-note{margin:0 .15rem;max-width:90ch;line-height:1.55}
41586
+ .feature-explanation>summary{min-height:44px;align-content:center;font-size:.8rem;color:var(--accent);border-radius:6px}
41587
+ .feature-explanation>summary:hover{color:var(--text)}
41588
+ .feature-explanation[open]>summary{color:var(--text)}
41589
+ .optimizer-explanation{padding:0 1rem .35rem}
41590
+ .explanation-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.75rem;padding:.25rem 0 .8rem}
41591
+ .explanation-grid>.explain-box{margin:0;min-width:0}
41592
+ .feature-explanation .explain-box{font-size:.85rem;line-height:1.6}
41593
+ .feature-explanation .explain-box>strong{font-size:.82rem}
41594
+ .routing-explanation{border-top:1px solid var(--line);margin-top:.6rem}
41595
+ .routing-explanation .explain-box{background:var(--panel)}
41596
+ .setup-choice-list{display:grid;gap:.55rem;margin:.9rem 0}
41597
+ .setup-choice-list h3{margin:.25rem 0 0}
41598
+ .setup-choice{display:grid;grid-template-columns:auto 1fr;align-items:start;gap:.7rem;padding:.8rem;border:1px solid var(--line);border-radius:12px;background:var(--panel);cursor:pointer}
41599
+ .setup-choice:hover{border-color:var(--accent);background:var(--accent-soft)}
41600
+ .setup-choice input{inline-size:1.1rem;block-size:1.1rem;margin:.15rem 0 0;accent-color:var(--accent)}
41601
+ .setup-choice-copy{display:grid;gap:.2rem}
41602
+ .setup-choice-limitation{color:var(--muted)}
41603
+ .routing-feature{margin:.8rem 0;padding:.8rem;border:1px solid var(--line);border-radius:12px;background:var(--panel-soft)}
41604
+ .routing-feature .tool-head{align-items:center}
41605
+ .routing-feature p{margin:.55rem 0;color:var(--muted)}
41606
+ .managed-action-box{margin-top:.8rem;background:var(--panel-soft);border:1px solid var(--line);border-radius:12px;padding:.85rem}
41607
+ .managed-action-box p{margin:.1rem 0 .65rem}
41608
+ .maintenance-list{display:grid;gap:.55rem}
41609
+ .maintenance-row{display:flex;align-items:center;justify-content:space-between;gap:1rem;background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:.8rem}
41610
+ .maintenance-row p{margin:.15rem 0}
41611
+ .explain-box{background:var(--panel-soft);border:1px solid var(--line);border-radius:12px;padding:.8rem;margin:.6rem 0}
41612
+ .explain-box p{margin:.25rem 0;color:var(--muted)}
41613
+ .explain-box.warn{background:var(--warn-soft);border-color:color-mix(in srgb,var(--warn) 35%,var(--line))}
41614
+ .explain-box.safe{background:var(--good-soft);border-color:color-mix(in srgb,var(--good) 30%,var(--line))}
41615
+ .operation-progress{margin:.75rem 0;padding:.8rem;border:1px solid var(--line);border-radius:12px}
41616
+ .operation-progress p{margin:.35rem 0 0}
41617
+ .choice-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.6rem;margin:.8rem 0}
41618
+ .choice-button{display:flex;flex-direction:column;align-items:flex-start;text-align:left;gap:.25rem;background:var(--panel);color:var(--text);border:1px solid var(--line);padding:.8rem}
41619
+ .choice-button:hover:not(:disabled){border-color:var(--accent);background:var(--accent-soft)}
41620
+ .choice-button .caption{font-weight:500}
41621
+ .result-signal{display:grid;gap:.2rem;border-top:1px solid var(--line);padding:.65rem 0}
41622
+ .result-signal strong{font-size:1rem}
41623
+ .results-header{display:flex;justify-content:space-between;gap:1rem;align-items:end;margin:1rem 0}
41624
+ .results-header h2{margin:0}
41625
+ .results-header p{margin:.2rem 0;color:var(--muted)}
41626
+ .update-notice{display:flex;align-items:center;justify-content:space-between;gap:1rem;padding:.8rem 1rem;margin:.8rem 0;border:1px solid color-mix(in srgb,var(--accent) 40%,var(--line));border-radius:var(--radius);background:var(--accent-soft)}
41627
+ .update-notice p{margin:.2rem 0 0;color:var(--muted)}
40890
41628
  .inline-actions a.secondary{display:inline-flex;align-items:center;padding:.68rem 1rem;border-radius:10px;text-decoration:none;font-weight:700}
40891
- .evidence-panel{padding:0}.evidence-controls{display:flex;align-items:end;gap:.7rem;flex-wrap:wrap;padding:.8rem;border-bottom:1px solid var(--line)}.evidence-controls label{display:grid;gap:.25rem;color:var(--muted);font-size:.82rem}.evidence-controls input,.evidence-controls select{min-width:150px}.evidence-controls input{min-width:min(260px,70vw)}.evidence-table-scroll{overflow-x:auto}.evidence-table{width:100%;border-collapse:collapse;min-width:760px}.evidence-table th,.evidence-table td{padding:.75rem .85rem;text-align:left;vertical-align:top;border-bottom:1px solid var(--line)}.evidence-table thead{background:var(--panel-soft);color:var(--muted);font-size:.8rem}.evidence-table tbody th{min-width:175px;font-weight:600}.evidence-table tbody th span{display:block;margin-top:.2rem}.evidence-table td:nth-child(2){min-width:150px}.evidence-table td:nth-child(3){min-width:240px}.evidence-table td:last-child{min-width:110px}.evidence-table details summary{cursor:pointer;color:var(--accent);font-weight:700}.evidence-table details p{margin:.45rem 0}.evidence-table tr[hidden]{display:none}.activity-scroll{max-height:24rem;overflow-y:auto;overscroll-behavior:contain}.activity-scroll .activity-row{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:.75rem;padding:.65rem 0;border-bottom:1px solid var(--line)}
40892
- #modal{width:min(720px,calc(100vw - 2rem));max-height:calc(100vh - 2rem);overflow:auto}#modal-content h3{margin:1rem 0 .4rem}#modal-actions{display:flex;justify-content:flex-end;gap:.5rem;flex-wrap:wrap;margin-top:1rem}
40893
- @media(max-width:900px){.dashboard-columns{grid-template-columns:1fr}.tool-grid{grid-template-columns:1fr}.setup-intro{grid-template-columns:1fr}}
40894
- @media(max-width:640px){.dashboard-status{flex-direction:column}.choice-grid{grid-template-columns:1fr}.connection-summary{align-items:flex-start;flex-direction:column}.connection-action{justify-content:flex-start}.maintenance-row{align-items:flex-start;flex-direction:column}.results-header{align-items:flex-start;flex-direction:column}.update-notice{align-items:flex-start;flex-direction:column}.activity-scroll .activity-row{grid-template-columns:auto minmax(0,1fr)}.activity-scroll .activity-row time{grid-column:2}}
40895
- @media(max-width:800px){.evidence-table{min-width:0}.evidence-table thead{display:none}.evidence-table tbody{display:block}.evidence-table tr{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);padding:.65rem;border-bottom:1px solid var(--line)}.evidence-table tbody th,.evidence-table td:nth-child(n){min-width:0;padding:.3rem;border:0;overflow-wrap:anywhere}.evidence-table td:nth-child(3),.evidence-table td:last-child{grid-column:1/-1}}
41629
+ /* Shared form controls, including search, use the same sizing and theme tokens. */
41630
+ input:not([type="checkbox"]):not([type="radio"]),select,textarea{font:inherit;color:var(--text);background:var(--panel);border:1px solid var(--control-line);border-radius:10px;padding:.65rem .75rem;min-height:44px;max-width:100%}input::placeholder{color:var(--muted);opacity:1}input:focus-visible,select:focus-visible,button:focus-visible,summary:focus-visible,a:focus-visible{outline:2px solid var(--accent);outline-offset:3px}button{min-height:44px}h2,h3{line-height:1.25;text-wrap:balance}p{overflow-wrap:anywhere}
41631
+ :root{--on-accent:#fff;--control-line:#8190a5;--muted:#596579;--shadow:0 2px 8px rgba(28,39,61,.03)}:root[data-theme="dark"]{--on-accent:#101a30;--control-line:#5f7088;--muted:#a6b0c0;--shadow:none}
41632
+ @media(prefers-color-scheme:dark){:root:not([data-theme="light"]){--on-accent:#101a30;--control-line:#5f7088;--muted:#a6b0c0;--shadow:none}}button:not(.secondary):not(.text-button):not(.choice-button):not([role="tab"]),.brand-mark{color:var(--on-accent)}
41633
+ .page-heading h1{font-size:1.8rem}
41634
+ .page-heading p{font-size:.95rem}
41635
+ .status-line{font-size:.8rem}
41636
+ .dashboard-status{background:var(--panel);padding:1.15rem;align-items:center;box-shadow:none}
41637
+ .dashboard-status>div{min-width:0}
41638
+ .dashboard-status h2{font-size:1.2rem}
41639
+ .dashboard-status p{max-width:64ch;margin:.35rem 0 .8rem}
41640
+ .dashboard-status>.pill{flex-shrink:0}
41641
+ .section-title h2,.results-header h2{font-size:1.15rem}
41642
+ .section-title p,.results-header p{font-size:.88rem;max-width:75ch}
41643
+ .metric-card{min-height:132px;box-shadow:none;padding:1rem}
41644
+ .metric-value{font-size:1.25rem;line-height:1.3;overflow-wrap:anywhere}
41645
+ .metric-card.positive .metric-value,.metric-card.good .metric-value{color:var(--good)}
41646
+ .metric-card.warn .metric-value{color:var(--warn)}
41647
+ .metric-help{font-size:.8rem}
41648
+ .advanced-disclosure{border:1px solid var(--line);border-radius:12px;background:var(--panel);padding:.8rem 1rem}
41649
+ .advanced-disclosure>summary{font-size:.88rem}
41650
+ .advanced-disclosure[open]>summary{margin-bottom:1rem}
41651
+ main,.setup-step{scroll-margin-top:7rem}
41652
+ .connection-summary{padding:.8rem 1rem}
41653
+ .connection-action{gap:.4rem;flex-wrap:wrap}
41654
+ .connection-action .text-button{font-size:.78rem}
41655
+ .connection-app-label{display:none}
41656
+ .tool-card{box-shadow:none}
41657
+ .tool-head{flex-wrap:wrap}
41658
+ .routing-feature .tool-head{gap:.4rem}
41659
+ .routing-feature .tool-head strong{font-size:.88rem}
41660
+ .routing-feature{background:var(--panel-soft)}
41661
+ .maintenance-row{padding:1rem}
41662
+ .maintenance-row>div{min-width:0}
41663
+ .maintenance-row button{flex-shrink:0}
41664
+ .maintenance-list{grid-template-columns:repeat(2,minmax(0,1fr))}
41665
+ .maintenance-row{align-items:flex-start;flex-direction:column}
41666
+ .brand small{font-weight:400}
41667
+ .evidence-panel{padding:0;overflow:hidden;box-shadow:none}
41668
+ .evidence-controls{display:grid;grid-template-columns:minmax(220px,1fr) minmax(150px,.4fr) minmax(150px,.4fr);gap:.75rem;padding:1rem;background:var(--panel-soft);border-bottom:1px solid var(--line)}
41669
+ .evidence-field{display:grid;gap:.4rem;min-width:0}
41670
+ .evidence-controls label{color:var(--muted);font-size:.78rem;font-weight:600}
41671
+ .evidence-controls input,.evidence-controls select{width:100%;font-size:.9rem}
41672
+ .evidence-list-meta{display:flex;align-items:center;justify-content:space-between;gap:.75rem;padding:.5rem 1rem;min-height:48px;border-bottom:1px solid var(--line)}
41673
+ .evidence-list-meta p{margin:0}
41674
+ .evidence-list-meta button{font-size:.8rem}
41675
+ .result-evidence{list-style:none;margin:0;padding:0}
41676
+ .evidence-item{border-bottom:1px solid var(--line)}
41677
+ .evidence-item:last-child{border-bottom:0}
41678
+ .evidence-summary{display:grid;grid-template-columns:minmax(180px,.8fr) minmax(0,1.6fr) auto;align-items:center;gap:1.5rem;padding:1.15rem 1rem;list-style:none;font-weight:400}
41679
+ .evidence-summary::-webkit-details-marker{display:none}
41680
+ .evidence-summary:hover{background:var(--panel-soft)}
41681
+ .evidence-identity{display:grid;gap:.3rem;min-width:0}
41682
+ .evidence-identity>strong{font-size:.98rem;line-height:1.3}
41683
+ .evidence-kind{font-size:.7rem;color:var(--muted);font-weight:700;text-transform:uppercase;letter-spacing:.05em}
41684
+ .evidence-signals{display:grid;gap:.75rem;min-width:0}
41685
+ .evidence-signal{display:grid;gap:.2rem;line-height:1.4}
41686
+ .evidence-signal strong{font-size:1rem;font-weight:650}
41687
+ .evidence-signal.good strong{color:var(--good)}
41688
+ .evidence-signal.warn strong{color:var(--warn)}
41689
+ .evidence-cue{display:flex;align-items:center;gap:.6rem;font-size:.8rem;color:var(--accent);font-weight:700;white-space:nowrap}
41690
+ .evidence-chevron{font-size:1.5rem;font-weight:400;line-height:1}
41691
+ .evidence-disclosure[open]>.evidence-summary{background:var(--panel-soft)}
41692
+ .evidence-disclosure[open] .evidence-chevron{transform:rotate(90deg)}
41693
+ .evidence-detail-body{display:grid;gap:1rem;padding:0 1rem 1.15rem;background:var(--panel-soft)}
41694
+ .evidence-section{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:1rem}
41695
+ .evidence-section h3{margin:0 0 .7rem;font-size:.88rem}
41696
+ .evidence-section button{margin-top:.75rem}
41697
+ .evidence-section p{margin:.75rem 0 0;max-width:90ch;line-height:1.6}
41698
+ .evidence-fact-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(125px,1fr));gap:1rem;margin:0}
41699
+ .evidence-fact-grid dt{color:var(--muted);font-size:.75rem}
41700
+ .evidence-fact-grid dd{margin:.25rem 0 0;font-size:.88rem;font-weight:600;overflow-wrap:anywhere}
41701
+ .evidence-empty{padding:2rem 1rem;text-align:center}
41702
+ .evidence-empty p{margin:.5rem 0 0;color:var(--muted);font-size:.9rem}
41703
+ .result-evidence>.empty{padding:1rem}
41704
+ .activity-scroll{max-height:24rem;overflow-y:auto;overscroll-behavior:contain}
41705
+ .activity-scroll .activity-row{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:.75rem;padding:.65rem 0;border-bottom:1px solid var(--line)}
41706
+ #modal{width:min(720px,calc(100vw - 2rem));max-height:calc(100vh - 2rem);overflow:auto}
41707
+ #modal-content h3{margin:1rem 0 .4rem}
41708
+ #modal-actions{display:flex;justify-content:flex-end;gap:.5rem;flex-wrap:wrap;margin-top:1rem}
41709
+ @media(max-width:900px){.dashboard-columns{grid-template-columns:1fr}
41710
+ .tool-grid{grid-template-columns:1fr}
41711
+ .setup-intro{grid-template-columns:1fr}}
41712
+ @media(max-width:640px){.dashboard-status{flex-direction:column}
41713
+ .choice-grid{grid-template-columns:1fr}
41714
+ .connection-summary{align-items:flex-start;flex-direction:column}
41715
+ .connection-action{justify-content:flex-start}
41716
+ .maintenance-row{align-items:flex-start;flex-direction:column}
41717
+ .results-header{align-items:flex-start;flex-direction:column}
41718
+ .update-notice{align-items:flex-start;flex-direction:column}
41719
+ .activity-scroll .activity-row{grid-template-columns:auto minmax(0,1fr)}
41720
+ .activity-scroll .activity-row time{grid-column:2}}
41721
+ @media(max-width:800px){.evidence-summary{grid-template-columns:minmax(130px,.8fr) minmax(0,1.4fr);gap:1rem}
41722
+ .evidence-cue{grid-column:2}
41723
+ .evidence-controls{grid-template-columns:repeat(2,minmax(0,1fr))}
41724
+ .evidence-search{grid-column:1/-1}}
41725
+ @media(max-width:1000px){
41726
+ .connection-scroll{overflow:visible;border:0;background:transparent}
41727
+ .connection-table{min-width:0;display:grid;gap:.75rem}
41728
+ .connection-item{border:1px solid var(--line);border-radius:12px;background:var(--panel)}
41729
+ .connection-item:last-child{border-bottom:1px solid var(--line)}
41730
+ .connection-row{display:flex;flex-wrap:wrap;gap:.85rem;padding:1rem}
41731
+ .connection-head{display:none}
41732
+ .connection-name{width:100%;gap:.25rem}
41733
+ .connection-role{max-width:none}
41734
+ .connection-cell{display:flex;align-items:center;gap:.5rem}
41735
+ .connection-app-label{display:inline;color:var(--muted);font-size:.8rem}
41736
+ .connection-action{width:100%;justify-content:flex-start;padding-top:.65rem;border-top:1px solid var(--line)}
41737
+ .optimizer-claim{width:100%;background:var(--panel-soft);border:1px solid var(--line);border-radius:10px;padding:.75rem}
41738
+ .optimizer-claim .connection-app-label{font-size:.72rem}
41739
+ .optimizer-explanation{padding-top:0}}
41740
+ @media(max-width:640px){.evidence-summary{grid-template-columns:1fr auto;gap:.85rem;padding:1rem}
41741
+ .evidence-identity{grid-column:1}
41742
+ .evidence-cue{grid-column:2;grid-row:1;align-self:start}
41743
+ .evidence-signals{grid-column:1/-1}
41744
+ .evidence-fact-grid{grid-template-columns:repeat(2,minmax(0,1fr))}
41745
+ .evidence-section{padding:.8rem}
41746
+ .evidence-controls{gap:.65rem;padding:.85rem}
41747
+ .evidence-controls input,.evidence-controls select{font-size:.85rem}
41748
+ .maintenance-list{grid-template-columns:1fr}
41749
+ .explanation-grid{grid-template-columns:1fr}
41750
+ .dashboard-status{align-items:flex-start}
41751
+ .brand small{display:none}
41752
+ .section-title{align-items:center}
41753
+ .section-title>button{flex-shrink:0}
41754
+ .impact-grid{grid-template-columns:1fr}
41755
+ .metric-card{min-height:0}
41756
+ .header-tools select{display:block;max-width:90px;font-size:.8rem}
41757
+ .header-tools{gap:.35rem}
41758
+ .brand{gap:.5rem;font-size:.9rem}
41759
+ .header-inner{gap:.6rem}
41760
+ .header-tools button{padding:.65rem .65rem;font-size:.85rem}}
40896
41761
  `;
40897
41762
  }
40898
41763
  });
@@ -41549,7 +42414,7 @@ ${GUIDE_CANDIDATE_READINESS_JS}`;
41549
42414
  <div class="header-tools"><label><span class="sr-only">Appearance</span><select id="theme" aria-label="Appearance"><option value="system">System</option><option value="light">Light</option><option value="dark">Dark</option></select></label><button id="refresh" class="secondary" type="button">Refresh</button></div>
41550
42415
  </div></header>
41551
42416
  <main id="main">
41552
- <div class="page-heading"><div><h1 id="view-title">Overview</h1><p id="view-description">Your coding agents, optimization stack, health and measured results in one place.</p></div></div>
42417
+ <div class="page-heading"><div><h1 id="view-title">Overview</h1><p id="view-description">Your setup, results and next steps.</p></div></div>
41553
42418
  <div class="status-line"><span class="read-status" role="status"><span id="reading-spinner" class="spinner" aria-hidden="true"></span><span id="updated">Checking your setup\u2026</span></span><span id="live-status" class="caption">Nothing changes without your approval</span></div>
41554
42419
  <div id="stale-state" class="stale-state" hidden></div><div id="error" class="error" role="alert" hidden></div><div id="notices"></div>
41555
42420
  <div id="update-notice" class="update-notice" role="status" hidden></div>
@@ -41557,20 +42422,18 @@ ${GUIDE_CANDIDATE_READINESS_JS}`;
41557
42422
  <section id="view-dashboard" role="tabpanel" aria-labelledby="tab-dashboard" tabindex="0">
41558
42423
  <section id="dashboard-status" class="dashboard-status"><div><span class="eyebrow">CURRENT STATUS</span><h2>Checking your machine\u2026</h2><p>Finding Claude Code, Codex, recommended optimizers and measured results.</p></div><span class="pill">Checking</span></section>
41559
42424
 
41560
- <div class="section-title"><div><h2>Measured impact</h2><p>A summary of what Token Harness can actually prove. Open Results for the detailed evidence.</p></div></div>
42425
+ <div class="section-title"><div><h2>Measured impact</h2><p>Recorded output, allowance and quality.</p></div><button id="overview-results" class="secondary" type="button">View results</button></div>
41561
42426
  <div id="dashboard-metrics" class="impact-grid" aria-label="Efficiency summary">
41562
- <article class="metric-card"><span class="metric-label">Measured output</span><strong class="metric-value">Checking\u2026</strong><p class="metric-help">Recorded optimizer output.</p></article>
42427
+ <article class="metric-card"><span class="metric-label">Recorded output</span><strong class="metric-value">Checking\u2026</strong><p class="metric-help">Recorded optimizer output.</p></article>
41563
42428
  <article class="metric-card"><span class="metric-label">5h / 7d allowance</span><strong class="metric-value">Checking\u2026</strong><p class="metric-help">Shown only when measured.</p></article>
41564
- <article class="metric-card"><span class="metric-label">API cost</span><strong class="metric-value">Checking\u2026</strong><p class="metric-help">Shown only from billing evidence.</p></article>
41565
42429
  <article class="metric-card"><span class="metric-label">Quality</span><strong class="metric-value">Checking\u2026</strong><p class="metric-help">Measured separately from savings.</p></article>
41566
42430
  </div>
41567
42431
 
41568
42432
  <section class="setup-step" id="coding-agents">
41569
- <div class="section-title"><div><h2>Coding agents</h2><p>Enable automatic per-prompt routing here for each detected coding app. The card distinguishes hook configuration from callbacks actually observed at runtime.</p></div></div>
42433
+ <div class="section-title"><div><h2>Coding agents</h2><p>Manage automatic routing for each app.</p></div></div>
41570
42434
  <div id="setup-agents" class="tool-grid"><article class="tool-card"><h3>Checking agents\u2026</h3></article></div>
41571
42435
  <details class="disclosure advanced-disclosure">
41572
- <summary>Agent details and optional reasoning settings</summary>
41573
- <p class="caption">Allowance, tool observations and reasoning preferences are advanced information. They are not required to finish optimizer setup.</p>
42436
+ <summary>Agent details &amp; reasoning settings</summary>
41574
42437
  <div id="agent-capabilities" class="tool-grid"><article class="tool-card"><h3>Checking agent details\u2026</h3></article></div>
41575
42438
  <div class="subsection-heading"><h3>Optional reasoning settings</h3><p class="caption">Persistent agent preferences are separate from optimizer setup.</p></div>
41576
42439
  <div id="agent-tuning" class="tool-grid"><article class="tool-card"><h3>Checking reasoning controls\u2026</h3></article></div>
@@ -41578,29 +42441,34 @@ ${GUIDE_CANDIDATE_READINESS_JS}`;
41578
42441
  </section>
41579
42442
 
41580
42443
  <section class="setup-step" id="optimizers">
41581
- <div class="section-title"><div><h2>Optimizer setup</h2><p>This matrix shows which optimizer setup Token Harness detected for each coding app. It does not confirm runtime activity; measured results appear separately when evidence is recorded.</p></div></div>
42444
+ <div class="section-title"><div><h2>Optimizer setup</h2><p>Connections detected for each app. Setup alone does not prove runtime activity.</p></div></div>
41582
42445
  <div id="connection-overview" class="connection-overview"><p class="empty">Checking optimizer connections\u2026</p></div>
41583
42446
  </section>
41584
42447
 
41585
42448
  <section class="setup-step" id="maintenance">
41586
- <div class="section-title"><div><h2>Health and updates</h2><p>These are maintenance actions, not onboarding steps. Setup already performs its own safety checks.</p></div></div>
42449
+ <div class="section-title"><div><h2>Health and updates</h2></div></div>
41587
42450
  <div id="maintenance-actions" class="maintenance-list"><p class="empty">Checking\u2026</p></div>
41588
42451
  </section>
41589
42452
  </section>
41590
42453
 
41591
42454
  <section id="view-results" role="tabpanel" aria-labelledby="tab-results" tabindex="0" hidden>
41592
- <div class="results-header"><div><h2>Results dashboard</h2><p>Measured evidence by optimizer, routing and coding app. Different classes and units stay separate.</p></div><div class="filter-row"><label for="period">Period</label><select id="period"><option value="all">All</option><option value="7d">7 days</option><option value="30d">30 days</option></select><button id="measurement-help" class="secondary" type="button">How results are recorded</button></div></div>
42455
+ <div class="results-header"><div><h2>Measured impact</h2><p>Each result keeps its source and measurement type.</p></div><div class="filter-row"><label for="period" class="sr-only">Results period</label><select id="period"><option value="all">All recorded history</option><option value="7d">Last 7 days</option><option value="30d">Last 30 days</option></select><button id="measurement-help" class="secondary" type="button">How to read results</button></div></div>
41593
42456
  <div id="result-summary" class="impact-grid" aria-label="Results overview"><article class="metric-card"><span class="metric-label">Measured evidence</span><strong class="metric-value">Checking\u2026</strong></article></div>
41594
42457
  <div class="section-title"><div><h2>Evidence</h2><p id="results-period-note">Checking recorded dates\u2026</p></div></div>
41595
42458
  <section class="panel evidence-panel">
41596
- <div class="evidence-controls"><label>Filter <input id="evidence-filter" type="search" placeholder="Optimizer, harness, class\u2026" autocomplete="off"></label><label>Type <select id="evidence-type"><option value="all">All</option><option value="optimizer">Optimizers</option><option value="routing">Routing</option><option value="harness">Coding apps</option><option value="candidate">Experiments</option></select></label><label>Sort <select id="evidence-sort"><option value="name">Name</option><option value="evidence">Evidence count</option><option value="type">Type</option></select></label></div>
41597
- <div class="evidence-table-scroll"><table class="evidence-table"><thead><tr><th scope="col">System</th><th scope="col">Scope</th><th scope="col">Measured evidence</th><th scope="col">Details</th></tr></thead><tbody id="result-evidence"><tr><td colspan="4">Checking recorded results\u2026</td></tr></tbody></table></div>
41598
- <p id="evidence-empty" class="empty" hidden>No evidence matches these filters.</p>
42459
+ <div class="evidence-controls">
42460
+ <div class="evidence-field evidence-search"><label for="evidence-filter">Search evidence</label><input id="evidence-filter" type="search" placeholder="Search sources, apps or measurements" autocomplete="off"></div>
42461
+ <div class="evidence-field"><label for="evidence-type">Source type</label><select id="evidence-type"><option value="all">All sources</option><option value="optimizer">Optimizers</option><option value="routing">Routing</option><option value="harness">Coding apps</option><option value="candidate">Experiments</option></select></div>
42462
+ <div class="evidence-field"><label for="evidence-sort">Sort by</label><select id="evidence-sort"><option value="evidence">With results first</option><option value="name">Name</option><option value="type">Source type</option></select></div>
42463
+ </div>
42464
+ <div class="evidence-list-meta"><p id="evidence-count" class="caption" role="status"></p><button id="evidence-reset" class="text-button" type="button" hidden>Clear filters</button></div>
42465
+ <ul id="result-evidence" class="result-evidence" aria-label="Evidence by source"><li class="empty">Checking recorded results\u2026</li></ul>
42466
+ <div id="evidence-empty" class="evidence-empty" hidden><strong>No matching sources</strong><p>Try a different search or clear the filters.</p></div>
41599
42467
  </section>
41600
42468
  <div class="section-title"><div><h2>Recent activity</h2><p>Latest checks and changes from this app session.</p></div></div><section class="panel"><div id="activity" class="activity-scroll"><p class="empty">No activity yet.</p></div></section>
41601
42469
  </section>
41602
42470
 
41603
- <footer><span>Local data. No account required.</span><span>Full overview refresh runs only when you choose Refresh.</span></footer>
42471
+ <footer><span>Local data. No account required.</span></footer>
41604
42472
  </main>
41605
42473
  <dialog id="modal" aria-labelledby="modal-title"><div class="dialog-body"><div class="dialog-heading"><h2 id="modal-title">Review</h2></div><div id="modal-content"></div><div id="modal-error" class="error" role="alert" hidden></div><div id="modal-actions" class="dialog-actions"></div></div></dialog>
41606
42474
  <script src="/guide.js" defer></script></body></html>`;
@@ -41856,9 +42724,9 @@ function createGuideHandler(input) {
41856
42724
  if (body === null || typeof body !== "object" || Array.isArray(body))
41857
42725
  throw new GuideError(400, "Only an optional reporting period is accepted.");
41858
42726
  const data = body;
41859
- if (Object.keys(data).some((key) => key !== "period") || data["period"] !== void 0 && !["all", "7d", "30d"].includes(String(data["period"])))
42727
+ if (Object.keys(data).some((key) => key !== "period" && key !== "background") || data["background"] !== void 0 && typeof data["background"] !== "boolean" || data["period"] !== void 0 && !["all", "7d", "30d"].includes(String(data["period"])))
41860
42728
  throw new GuideError(400, "Only an optional reporting period is accepted.");
41861
- const result6 = await input.service.checkUpdates();
42729
+ const result6 = await input.service.checkUpdates(data["background"] === true);
41862
42730
  const requested = data["period"];
41863
42731
  let responseResult = result6;
41864
42732
  if (result6.stack !== void 0 && requested !== void 0) {
@@ -41939,6 +42807,10 @@ function shellQuote(value3) {
41939
42807
  function powershellQuote(value3) {
41940
42808
  return `'${value3.replace(/'/g, "''")}'`;
41941
42809
  }
42810
+ function windowsLauncher(entryScript, rtkExecutable) {
42811
+ const paths = Buffer.from(JSON.stringify({ entryScript, rtkExecutable })).toString("base64");
42812
+ return `node.exe --eval "const p=JSON.parse(Buffer.from('${paths}','base64').toString());process.argv.splice(1,0,p.entryScript,'__internal-rtk-run','codex','--rtk-executable',p.rtkExecutable);import(require('node:url').pathToFileURL(p.entryScript).href)" --`;
42813
+ }
41942
42814
  function toolNameFromInput(input, harness) {
41943
42815
  try {
41944
42816
  const parsed = JSON.parse(input);
@@ -41963,7 +42835,7 @@ function withDatabaseEnvironment(command, databasePath, toolName) {
41963
42835
  }
41964
42836
  return null;
41965
42837
  }
41966
- function attributeRtkHookResponse(stdout, input, databasePath, harness) {
42838
+ function attributeRtkHookResponse(stdout, input, databasePath, harness, os, launcher) {
41967
42839
  let response;
41968
42840
  try {
41969
42841
  response = JSON.parse(stdout.trim());
@@ -41978,7 +42850,8 @@ function attributeRtkHookResponse(stdout, input, databasePath, harness) {
41978
42850
  const updatedInput = hookOutput["updatedInput"];
41979
42851
  if (!isRecord5(updatedInput) || typeof updatedInput["command"] !== "string")
41980
42852
  return stdout;
41981
- const attributed = withDatabaseEnvironment(updatedInput["command"], databasePath, toolNameFromInput(input, harness));
42853
+ const command = updatedInput["command"];
42854
+ const attributed = harness === "codex" && os === "windows" ? launcher !== void 0 && /^\s*rtk(?:\.exe)?(?:\s|$)/i.test(command) ? command.replace(/^\s*rtk(?:\.exe)?/i, windowsLauncher(launcher.entryScript, launcher.rtkExecutable)) : null : withDatabaseEnvironment(updatedInput["command"], databasePath, toolNameFromInput(input, harness));
41982
42855
  if (attributed === null)
41983
42856
  return stdout;
41984
42857
  return `${JSON.stringify({
@@ -42008,10 +42881,20 @@ async function runRtkHookProxy(input) {
42008
42881
  };
42009
42882
  }
42010
42883
  return {
42011
- stdout: attributeRtkHookResponse(outcome2.stdout, input.stdin, input.databasePath, input.harness),
42884
+ stdout: attributeRtkHookResponse(outcome2.stdout, input.stdin, input.databasePath, input.harness, input.os, input.entryScript !== void 0 && outcome2.executablePath !== null ? { entryScript: input.entryScript, rtkExecutable: outcome2.executablePath } : void 0),
42012
42885
  stderr: outcome2.stderr
42013
42886
  };
42014
42887
  }
42888
+ function runAttributedRtkCommand(input) {
42889
+ return input.runner.run({
42890
+ executable: input.executable ?? "rtk",
42891
+ args: [...input.args],
42892
+ cwd: input.cwd,
42893
+ env: { RTK_DB_PATH: input.databasePath },
42894
+ timeoutMs: 0,
42895
+ maxOutputBytes: 32 * 1024 * 1024
42896
+ });
42897
+ }
42015
42898
  var MAX_HOOK_OUTPUT_BYTES, HOOK_TIMEOUT_MS;
42016
42899
  var init_rtk_hook_proxy = __esm({
42017
42900
  "apps/cli/dist/src/commands/rtk-hook-proxy.js"() {
@@ -42205,7 +43088,9 @@ Run token-harness ui --help for usage.
42205
43088
  cwd: process5.cwd(),
42206
43089
  harness: harnessId(selected),
42207
43090
  databasePath: fs.join(resolution.environment.paths.state, `rtk-${selected}.db`),
42208
- stdin: input
43091
+ stdin: input,
43092
+ os: resolution.environment.facts.os,
43093
+ ...process5.argv[1] !== void 0 && (await fs.stat(process5.argv[1]))?.kind === "file" ? { entryScript: process5.argv[1] } : {}
42209
43094
  });
42210
43095
  if (result6.stdout.length > 0)
42211
43096
  process5.stdout.write(result6.stdout);
@@ -42214,6 +43099,28 @@ Run token-harness ui --help for usage.
42214
43099
  process5.exitCode = 0;
42215
43100
  return;
42216
43101
  }
43102
+ if (argv2[0] === "__internal-rtk-run") {
43103
+ const pinnedExecutable = argv2[2] === "--rtk-executable" ? argv2[3] ?? null : null;
43104
+ const commandArgs = argv2.slice(pinnedExecutable === null ? 2 : 4);
43105
+ if (argv2[1] !== "codex" || commandArgs.length === 0 || !resolution.ok || fs === null || attribution.salt === null || pinnedExecutable !== null && (await fs.stat(pinnedExecutable))?.kind !== "file") {
43106
+ process5.stderr.write("[Token Harness] Cannot prepare attributed RTK execution.\n");
43107
+ process5.exitCode = 1;
43108
+ return;
43109
+ }
43110
+ const result6 = await runAttributedRtkCommand({
43111
+ runner: resolution.environment.runner,
43112
+ cwd: process5.cwd(),
43113
+ databasePath: fs.join(resolution.environment.paths.state, "rtk-codex.db"),
43114
+ args: commandArgs,
43115
+ ...pinnedExecutable === null ? {} : { executable: pinnedExecutable }
43116
+ });
43117
+ process5.stdout.write(result6.stdout);
43118
+ process5.stderr.write(result6.stderr);
43119
+ if (result6.stdoutTruncated || result6.stderrTruncated)
43120
+ process5.stderr.write("[Token Harness] RTK output exceeded the 32 MiB capture limit.\n");
43121
+ process5.exitCode = result6.failure !== null || result6.stdoutTruncated || result6.stderrTruncated ? 1 : result6.exitCode ?? 1;
43122
+ return;
43123
+ }
42217
43124
  if (uiInvocation?.ok === true) {
42218
43125
  process5.exitCode = readOnly || uiInvocation.options.json ? await runUi(uiInvocation.options, baseOptions) : await runGuidedUi(uiInvocation.options, baseOptions);
42219
43126
  return;