token-harness 0.1.27 → 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.
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.27";
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
  (() => {
@@ -39128,36 +39668,7 @@ var init_guided_product_client = __esm({
39128
39668
  dashboard: ['Overview', 'Your setup, results and next steps.'],
39129
39669
  results: ['Results', 'See what changed and the evidence behind it.'],
39130
39670
  };
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
- },
39160
- };
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) };
@@ -39321,6 +39832,58 @@ var init_guided_product_client = __esm({
39321
39832
  return box;
39322
39833
  }
39323
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
+
39324
39887
  function activeAgents() {
39325
39888
  return current?.agents || [];
39326
39889
  }
@@ -39668,6 +40231,7 @@ var init_guided_product_client = __esm({
39668
40231
  );
39669
40232
  routingCard.append(
39670
40233
  routingHead,
40234
+ node('p', 'Lets your agent delegate suitable work to a smaller native helper while your main model stays in charge.', 'caption'),
39671
40235
  node(
39672
40236
  'p',
39673
40237
  routing?.detail || (routing?.enablement === 'untrusted'
@@ -39682,6 +40246,7 @@ var init_guided_product_client = __esm({
39682
40246
  'caption',
39683
40247
  ),
39684
40248
  );
40249
+ routingCard.append(routingExplanation(agent.id));
39685
40250
  const routingActions = node('div', undefined, 'inline-actions');
39686
40251
  if (routing?.needsRepair) {
39687
40252
  routingActions.append(actionButton('Repair routing', () => reviewPromptRouting(agent.id, true), 'secondary'));
@@ -40025,8 +40590,7 @@ var init_guided_product_client = __esm({
40025
40590
  const agents = activeAgents();
40026
40591
  const ids = optimizerIds();
40027
40592
  if (!agents.length) {
40028
- root.append(sectionEmpty('Optimizer setup will appear when a supported coding app is detected.'));
40029
- return;
40593
+ root.append(sectionEmpty('Explore the optimizers below. Connections become available when a supported coding app is detected.'));
40030
40594
  }
40031
40595
 
40032
40596
  const summary = node('div', undefined, 'connection-summary');
@@ -40042,12 +40606,14 @@ var init_guided_product_client = __esm({
40042
40606
  if (baselineActionable)
40043
40607
  summary.append(actionButton('Set up recommended stack', () => reviewSetup(), ''));
40044
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'));
40045
40610
 
40046
40611
  const scroll = node('div', undefined, 'connection-scroll');
40047
40612
  const table = node('div', undefined, 'connection-table');
40048
- 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)');
40049
40614
  const header = node('div', undefined, 'connection-row connection-head');
40050
40615
  header.append(node('strong', 'Optimizer', 'connection-name'));
40616
+ header.append(node('strong', 'Project-reported impact', 'optimizer-claim'));
40051
40617
  for (const agent of agents) header.append(node('strong', agent.name, 'connection-cell'));
40052
40618
  header.append(node('strong', 'Action', 'connection-action'));
40053
40619
  table.append(header);
@@ -40055,15 +40621,28 @@ var init_guided_product_client = __esm({
40055
40621
  for (const id of ids) {
40056
40622
  const info = optimizerInfo(id);
40057
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);
40058
40627
  const row = node('div', undefined, 'connection-row');
40059
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'));
40060
40632
  nameCell.append(
40061
- node('strong', info.name),
40633
+ identity,
40062
40634
  node('span', info.optional ? 'Optional optimizer' : 'Recommended baseline', 'caption'),
40063
40635
  node('span', info.role, 'caption connection-role'),
40064
40636
  node('span', component?.version ? 'v' + component.version : 'Not installed', 'caption'),
40065
40637
  );
40066
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);
40067
40646
  let actionable = false;
40068
40647
  for (const agent of agents) {
40069
40648
  const target = setupTarget(agent.id, id);
@@ -40094,7 +40673,8 @@ var init_guided_product_client = __esm({
40094
40673
  }
40095
40674
  if (!action.children.length) action.append(node('span', 'No action', 'caption'));
40096
40675
  row.append(action);
40097
- table.append(row);
40676
+ item.append(row, optimizerExplanation(id, info));
40677
+ table.append(item);
40098
40678
  }
40099
40679
  scroll.append(table);
40100
40680
  root.append(scroll);
@@ -40759,16 +41339,6 @@ var init_guided_product_client = __esm({
40759
41339
  }
40760
41340
  }
40761
41341
 
40762
- function reviewUpdate(result) {
40763
- if (!result?.ticket || busy) return;
40764
- modal('Review Token Harness update');
40765
- $('modal-content').append(
40766
- messageBox('Update available', (result.messages || []).join(' ') || result.title || 'A reviewed Token Harness update is ready.'),
40767
- messageBox('Health re-check', 'After installation, Token Harness will re-check optimizer health automatically.'),
40768
- );
40769
- $('modal-actions').append(modalClose('Cancel'), actionButton('Install updates', () => applyTicket(result.ticket)));
40770
- }
40771
-
40772
41342
  async function checkUpdatesOnStartup() {
40773
41343
  if (updateCheckStarted) return;
40774
41344
  if ($('modal').open) {
@@ -40782,14 +41352,13 @@ var init_guided_product_client = __esm({
40782
41352
  updateCheckStarted = true;
40783
41353
  try {
40784
41354
  await ensureSession();
40785
- const result = await request('/api/update-check', { period: $('period').value });
41355
+ const result = await request('/api/update-check', { period: $('period').value, background: true });
40786
41356
  if (busy || reading || $('modal').open) {
40787
41357
  updateCheckStarted = false;
40788
41358
  if ($('modal').open) $('modal').addEventListener('close', checkUpdatesOnStartup, { once: true });
40789
41359
  else setTimeout(checkUpdatesOnStartup, 1000);
40790
41360
  return;
40791
41361
  }
40792
- latestUpdateCheck = result;
40793
41362
  if (result.stack && current) {
40794
41363
  current = { ...current, stack: result.stack };
40795
41364
  renderDashboard();
@@ -40798,13 +41367,13 @@ var init_guided_product_client = __esm({
40798
41367
  }
40799
41368
  const root = $('update-notice');
40800
41369
  root.replaceChildren();
40801
- if (!result.ticket) {
41370
+ if (!result.updatesAvailable) {
40802
41371
  root.hidden = true;
40803
41372
  return;
40804
41373
  }
40805
41374
  const copy = node('div');
40806
41375
  copy.append(node('strong', result.title || 'Token Harness update available'), node('p', (result.messages || []).join(' ') || 'Review and install the available update.', 'caption'));
40807
- root.append(copy, actionButton('Review update', () => reviewUpdate(latestUpdateCheck), 'secondary'));
41376
+ root.append(copy, actionButton('Review update', () => readOnlyOperation('update-check'), 'secondary'));
40808
41377
  root.hidden = false;
40809
41378
  } catch {
40810
41379
  // The startup version check is supplementary; Refresh and Health and updates remain available.
@@ -40983,11 +41552,11 @@ var init_guided_product_styles = __esm({
40983
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}
40984
41553
  .connection-summary p{margin:.15rem 0 0}
40985
41554
  .connection-scroll{overflow-x:auto;border:1px solid var(--line);border-radius:var(--radius);background:var(--panel)}
40986
- .connection-table{min-width:max(720px,100%)}
40987
- .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)}
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)}
40988
41557
  .connection-row:last-child{border-bottom:0}
40989
41558
  .connection-head{background:var(--panel-soft);color:var(--muted);font-size:.8rem}
40990
- .connection-name{display:grid;gap:.12rem}
41559
+ .connection-name{display:grid;gap:.25rem;min-width:0}
40991
41560
  .connection-cell,.connection-action{min-width:0}
40992
41561
  .connection-action{display:flex;justify-content:flex-end}
40993
41562
  .tool-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.8rem}
@@ -41001,7 +41570,29 @@ var init_guided_product_styles = __esm({
41001
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}
41002
41571
  .tool-facts span{color:var(--muted);font-size:.8rem}
41003
41572
  .tool-facts strong{font-size:.85rem}
41004
- .connection-role{max-width:28ch}
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)}
41005
41596
  .setup-choice-list{display:grid;gap:.55rem;margin:.9rem 0}
41006
41597
  .setup-choice-list h3{margin:.25rem 0 0}
41007
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}
@@ -41130,16 +41721,22 @@ main,.setup-step{scroll-margin-top:7rem}
41130
41721
  @media(max-width:800px){.evidence-summary{grid-template-columns:minmax(130px,.8fr) minmax(0,1.4fr);gap:1rem}
41131
41722
  .evidence-cue{grid-column:2}
41132
41723
  .evidence-controls{grid-template-columns:repeat(2,minmax(0,1fr))}
41133
- .evidence-search{grid-column:1/-1}
41724
+ .evidence-search{grid-column:1/-1}}
41725
+ @media(max-width:1000px){
41134
41726
  .connection-scroll{overflow:visible;border:0;background:transparent}
41135
41727
  .connection-table{min-width:0;display:grid;gap:.75rem}
41136
- .connection-row{display:flex;flex-wrap:wrap;gap:.75rem;border:1px solid var(--line);border-radius:12px;background:var(--panel);padding:1rem}
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}
41137
41731
  .connection-head{display:none}
41138
41732
  .connection-name{width:100%;gap:.25rem}
41139
41733
  .connection-role{max-width:none}
41140
41734
  .connection-cell{display:flex;align-items:center;gap:.5rem}
41141
41735
  .connection-app-label{display:inline;color:var(--muted);font-size:.8rem}
41142
- .connection-action{width:100%;justify-content:flex-start;padding-top:.65rem;border-top:1px solid var(--line)}}
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}}
41143
41740
  @media(max-width:640px){.evidence-summary{grid-template-columns:1fr auto;gap:.85rem;padding:1rem}
41144
41741
  .evidence-identity{grid-column:1}
41145
41742
  .evidence-cue{grid-column:2;grid-row:1;align-self:start}
@@ -41149,6 +41746,7 @@ main,.setup-step{scroll-margin-top:7rem}
41149
41746
  .evidence-controls{gap:.65rem;padding:.85rem}
41150
41747
  .evidence-controls input,.evidence-controls select{font-size:.85rem}
41151
41748
  .maintenance-list{grid-template-columns:1fr}
41749
+ .explanation-grid{grid-template-columns:1fr}
41152
41750
  .dashboard-status{align-items:flex-start}
41153
41751
  .brand small{display:none}
41154
41752
  .section-title{align-items:center}
@@ -42126,9 +42724,9 @@ function createGuideHandler(input) {
42126
42724
  if (body === null || typeof body !== "object" || Array.isArray(body))
42127
42725
  throw new GuideError(400, "Only an optional reporting period is accepted.");
42128
42726
  const data = body;
42129
- 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"])))
42130
42728
  throw new GuideError(400, "Only an optional reporting period is accepted.");
42131
- const result6 = await input.service.checkUpdates();
42729
+ const result6 = await input.service.checkUpdates(data["background"] === true);
42132
42730
  const requested = data["period"];
42133
42731
  let responseResult = result6;
42134
42732
  if (result6.stack !== void 0 && requested !== void 0) {
@@ -42209,6 +42807,10 @@ function shellQuote(value3) {
42209
42807
  function powershellQuote(value3) {
42210
42808
  return `'${value3.replace(/'/g, "''")}'`;
42211
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
+ }
42212
42814
  function toolNameFromInput(input, harness) {
42213
42815
  try {
42214
42816
  const parsed = JSON.parse(input);
@@ -42233,7 +42835,7 @@ function withDatabaseEnvironment(command, databasePath, toolName) {
42233
42835
  }
42234
42836
  return null;
42235
42837
  }
42236
- function attributeRtkHookResponse(stdout, input, databasePath, harness) {
42838
+ function attributeRtkHookResponse(stdout, input, databasePath, harness, os, launcher) {
42237
42839
  let response;
42238
42840
  try {
42239
42841
  response = JSON.parse(stdout.trim());
@@ -42248,7 +42850,8 @@ function attributeRtkHookResponse(stdout, input, databasePath, harness) {
42248
42850
  const updatedInput = hookOutput["updatedInput"];
42249
42851
  if (!isRecord5(updatedInput) || typeof updatedInput["command"] !== "string")
42250
42852
  return stdout;
42251
- 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));
42252
42855
  if (attributed === null)
42253
42856
  return stdout;
42254
42857
  return `${JSON.stringify({
@@ -42278,10 +42881,20 @@ async function runRtkHookProxy(input) {
42278
42881
  };
42279
42882
  }
42280
42883
  return {
42281
- 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),
42282
42885
  stderr: outcome2.stderr
42283
42886
  };
42284
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
+ }
42285
42898
  var MAX_HOOK_OUTPUT_BYTES, HOOK_TIMEOUT_MS;
42286
42899
  var init_rtk_hook_proxy = __esm({
42287
42900
  "apps/cli/dist/src/commands/rtk-hook-proxy.js"() {
@@ -42475,7 +43088,9 @@ Run token-harness ui --help for usage.
42475
43088
  cwd: process5.cwd(),
42476
43089
  harness: harnessId(selected),
42477
43090
  databasePath: fs.join(resolution.environment.paths.state, `rtk-${selected}.db`),
42478
- 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] } : {}
42479
43094
  });
42480
43095
  if (result6.stdout.length > 0)
42481
43096
  process5.stdout.write(result6.stdout);
@@ -42484,6 +43099,28 @@ Run token-harness ui --help for usage.
42484
43099
  process5.exitCode = 0;
42485
43100
  return;
42486
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
+ }
42487
43124
  if (uiInvocation?.ok === true) {
42488
43125
  process5.exitCode = readOnly || uiInvocation.options.json ? await runUi(uiInvocation.options, baseOptions) : await runGuidedUi(uiInvocation.options, baseOptions);
42489
43126
  return;