token-harness 0.1.22 → 0.1.24

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
@@ -759,6 +759,27 @@ function parseBoundaryPolicy(value3) {
759
759
  return void 0;
760
760
  return { model, reasoningEffort, verbosity, verification: "config-only" };
761
761
  }
762
+ function parseNativeRoutingObservation(value3) {
763
+ if (value3 === null)
764
+ return null;
765
+ const row2 = record(value3);
766
+ if (row2 === null)
767
+ return void 0;
768
+ const configured = row2["configured"];
769
+ const promptSubmissions = row2["promptSubmissions"];
770
+ const subagentsStarted = row2["subagentsStarted"];
771
+ const subagentsStopped = row2["subagentsStopped"];
772
+ const reportedModels = row2["reportedModels"];
773
+ if (!(configured === null || typeof configured === "boolean") || !Number.isSafeInteger(promptSubmissions) || typeof promptSubmissions !== "number" || promptSubmissions < 0 || !Number.isSafeInteger(subagentsStarted) || typeof subagentsStarted !== "number" || subagentsStarted < 0 || !Number.isSafeInteger(subagentsStopped) || typeof subagentsStopped !== "number" || subagentsStopped < 0 || !Array.isArray(reportedModels) || !reportedModels.every((model) => typeof model === "string" && model.length <= 80))
774
+ return void 0;
775
+ return {
776
+ configured,
777
+ promptSubmissions,
778
+ subagentsStarted,
779
+ subagentsStopped,
780
+ reportedModels: [...new Set(reportedModels)]
781
+ };
782
+ }
762
783
  function parseTaskBenchmarkCapture(value3) {
763
784
  const row2 = record(value3);
764
785
  if (row2 === null) {
@@ -785,7 +806,9 @@ function parseTaskBenchmarkCapture(value3) {
785
806
  const localSessionsBefore = parsedLocalSessions === void 0 ? null : parsedLocalSessions;
786
807
  const hasContextAtStart = Object.hasOwn(row2, "contextAtStart");
787
808
  const contextAtStart = hasContextAtStart ? parseTaskBenchmarkContextSnapshot(row2["contextAtStart"]) : void 0;
788
- if (typeof benchmarkId !== "string" || !isTaskBenchmarkId(benchmarkId) || typeof variant !== "string" || !isTaskBenchmarkVariant(variant) || typeof taskClass !== "string" || !isTaskClass(taskClass) || typeof harnessId2 !== "string" || !isHarnessId(harnessId2) || typeof projectId !== "string" || projectId === "" || model === void 0 || reasoningEffort === void 0 || verbosity === void 0 || !validInstant(startedAt) || usageBefore === null || parsedLocalSessions === void 0 || hasContextAtStart && contextAtStart === void 0) {
809
+ const hasNativeRoutingAtStart = Object.hasOwn(row2, "nativeRoutingAtStart");
810
+ const nativeRoutingAtStart = hasNativeRoutingAtStart ? parseNativeRoutingObservation(row2["nativeRoutingAtStart"]) : void 0;
811
+ if (typeof benchmarkId !== "string" || !isTaskBenchmarkId(benchmarkId) || typeof variant !== "string" || !isTaskBenchmarkVariant(variant) || typeof taskClass !== "string" || !isTaskClass(taskClass) || typeof harnessId2 !== "string" || !isHarnessId(harnessId2) || typeof projectId !== "string" || projectId === "" || model === void 0 || reasoningEffort === void 0 || verbosity === void 0 || !validInstant(startedAt) || usageBefore === null || parsedLocalSessions === void 0 || hasContextAtStart && contextAtStart === void 0 || hasNativeRoutingAtStart && nativeRoutingAtStart === void 0) {
789
812
  return {
790
813
  ok: false,
791
814
  reason: "invalid-shape",
@@ -807,6 +830,7 @@ function parseTaskBenchmarkCapture(value3) {
807
830
  startedAt,
808
831
  usageBefore,
809
832
  ...hasContextAtStart ? { contextAtStart: contextAtStart ?? null } : {},
833
+ ...hasNativeRoutingAtStart ? { nativeRoutingAtStart: nativeRoutingAtStart ?? null } : {},
810
834
  localSessionsBefore
811
835
  }
812
836
  };
@@ -842,7 +866,11 @@ function parseTaskBenchmarkReceipt(value3) {
842
866
  const contextAtStart = hasContextAtStart ? parseTaskBenchmarkContextSnapshot(row2["contextAtStart"]) : void 0;
843
867
  const hasContextAtFinish = Object.hasOwn(row2, "contextAtFinish");
844
868
  const contextAtFinish = hasContextAtFinish ? parseTaskBenchmarkContextSnapshot(row2["contextAtFinish"]) : void 0;
845
- if (typeof benchmarkId !== "string" || benchmarkId === "" || typeof variant !== "string" || !isTaskBenchmarkVariant(variant) || typeof taskClass !== "string" || !isTaskClass(taskClass) || typeof harnessId2 !== "string" || !isHarnessId(harnessId2) || model === void 0 || reasoningEffort === void 0 || verbosity === void 0 || !validInstant(startedAt) || !validInstant(completedAt) || Date.parse(completedAt) < Date.parse(startedAt) || usageBefore === null || usageAfter === null || localUsage === void 0 || outcome2 === null || hasBoundaryPolicy && policyAtFinish === void 0 || hasContextAtStart && contextAtStart === void 0 || hasContextAtFinish && contextAtFinish === void 0) {
869
+ const hasNativeRoutingAtStart = Object.hasOwn(row2, "nativeRoutingAtStart");
870
+ const nativeRoutingAtStart = hasNativeRoutingAtStart ? parseNativeRoutingObservation(row2["nativeRoutingAtStart"]) : void 0;
871
+ const hasNativeRoutingAtFinish = Object.hasOwn(row2, "nativeRoutingAtFinish");
872
+ const nativeRoutingAtFinish = hasNativeRoutingAtFinish ? parseNativeRoutingObservation(row2["nativeRoutingAtFinish"]) : void 0;
873
+ if (typeof benchmarkId !== "string" || benchmarkId === "" || typeof variant !== "string" || !isTaskBenchmarkVariant(variant) || typeof taskClass !== "string" || !isTaskClass(taskClass) || typeof harnessId2 !== "string" || !isHarnessId(harnessId2) || model === void 0 || reasoningEffort === void 0 || verbosity === void 0 || !validInstant(startedAt) || !validInstant(completedAt) || Date.parse(completedAt) < Date.parse(startedAt) || usageBefore === null || usageAfter === null || localUsage === void 0 || outcome2 === null || hasBoundaryPolicy && policyAtFinish === void 0 || hasContextAtStart && contextAtStart === void 0 || hasContextAtFinish && contextAtFinish === void 0 || hasNativeRoutingAtStart && nativeRoutingAtStart === void 0 || hasNativeRoutingAtFinish && nativeRoutingAtFinish === void 0) {
846
874
  return {
847
875
  ok: false,
848
876
  reason: "invalid-shape",
@@ -868,7 +896,9 @@ function parseTaskBenchmarkReceipt(value3) {
868
896
  outcome: outcome2,
869
897
  ...hasContextAtStart ? { contextAtStart: contextAtStart ?? null } : {},
870
898
  ...hasContextAtFinish ? { contextAtFinish: contextAtFinish ?? null } : {},
871
- ...hasBoundaryPolicy ? { policyAtFinish: policyAtFinish ?? null } : {}
899
+ ...hasBoundaryPolicy ? { policyAtFinish: policyAtFinish ?? null } : {},
900
+ ...hasNativeRoutingAtStart ? { nativeRoutingAtStart: nativeRoutingAtStart ?? null } : {},
901
+ ...hasNativeRoutingAtFinish ? { nativeRoutingAtFinish: nativeRoutingAtFinish ?? null } : {}
872
902
  }
873
903
  };
874
904
  }
@@ -888,7 +918,9 @@ function completeTaskBenchmarkCapture(capture, input) {
888
918
  usageAfter: input.usageAfter,
889
919
  localUsage: input.localUsage ?? null,
890
920
  ...capture.contextAtStart !== void 0 ? { contextAtStart: capture.contextAtStart } : {},
921
+ ...capture.nativeRoutingAtStart !== void 0 ? { nativeRoutingAtStart: capture.nativeRoutingAtStart } : {},
891
922
  ...input.contextAtFinish !== void 0 ? { contextAtFinish: input.contextAtFinish } : {},
923
+ ...input.nativeRoutingAtFinish !== void 0 ? { nativeRoutingAtFinish: input.nativeRoutingAtFinish } : {},
892
924
  ...input.policyAtFinish !== void 0 ? { policyAtFinish: input.policyAtFinish } : {},
893
925
  outcome: {
894
926
  qualityGate: input.qualityGate,
@@ -1096,7 +1128,8 @@ function buildTaskBenchmarkMatrix(pairs, selection = {
1096
1128
  baselineLocalTokens,
1097
1129
  optimizedLocalTokens,
1098
1130
  localTokenSavingPercent: !bothQualityPassed || baselineLocalTokens === null || optimizedLocalTokens === null ? null : roundedPercent(baselineLocalTokens - optimizedLocalTokens, baselineLocalTokens),
1099
- quota: comparison.quota
1131
+ quota: comparison.quota,
1132
+ ...nativeRoutingComparison(baseline, optimized)
1100
1133
  };
1101
1134
  }).sort((left, right) => TASK_CLASS_ORDER.indexOf(left.taskClass) - TASK_CLASS_ORDER.indexOf(right.taskClass) || left.benchmarkId.localeCompare(right.benchmarkId));
1102
1135
  const byTaskClass = TASK_CLASS_ORDER.map((taskClass) => ({
@@ -1110,6 +1143,36 @@ function buildTaskBenchmarkMatrix(pairs, selection = {
1110
1143
  selection
1111
1144
  };
1112
1145
  }
1146
+ function nativeRoutingComparison(baseline, optimized) {
1147
+ const bStart = baseline.nativeRoutingAtStart;
1148
+ const bFinish = baseline.nativeRoutingAtFinish;
1149
+ const oStart = optimized.nativeRoutingAtStart;
1150
+ const oFinish = optimized.nativeRoutingAtFinish;
1151
+ if (bStart === void 0 && bFinish === void 0 && oStart === void 0 && oFinish === void 0)
1152
+ return {};
1153
+ const qualityGatesPassed = baseline.outcome.qualityGate === "passed" && optimized.outcome.qualityGate === "passed";
1154
+ if (bStart == null || bFinish == null || oStart == null || oFinish == null || bStart.configured === null || oStart.configured === null) {
1155
+ return {
1156
+ nativeRouting: {
1157
+ verdict: "unknown",
1158
+ baselineSubagents: bFinish?.subagentsStarted ?? null,
1159
+ optimizedSubagents: oFinish?.subagentsStarted ?? null,
1160
+ optimizedReportedModels: oFinish?.reportedModels ?? [],
1161
+ qualityGatesPassed
1162
+ }
1163
+ };
1164
+ }
1165
+ const attributed = bStart.configured === false && bFinish.configured === false && bFinish.subagentsStarted === 0 && oStart.configured === true && oFinish.configured === true && oFinish.promptSubmissions > 0 && oFinish.subagentsStarted > 0;
1166
+ return {
1167
+ nativeRouting: {
1168
+ verdict: attributed ? "attributed" : "not-attributed",
1169
+ baselineSubagents: bFinish.subagentsStarted,
1170
+ optimizedSubagents: oFinish.subagentsStarted,
1171
+ optimizedReportedModels: [...oFinish.reportedModels],
1172
+ qualityGatesPassed
1173
+ }
1174
+ };
1175
+ }
1113
1176
  var TASK_BENCHMARK_RECEIPT_SCHEMA_VERSION, TASK_BENCHMARK_CAPTURE_SCHEMA_VERSION, BENCHMARK_ID, WINDOW_SCOPES, WINDOW_SOURCES, WINDOW_CONFIDENCES, WINDOW_KINDS, QUOTA_SCOPE_PRIORITY, TASK_CLASS_ORDER;
1114
1177
  var init_benchmark = __esm({
1115
1178
  "packages/core/dist/src/domain/benchmark.js"() {
@@ -4130,6 +4193,7 @@ function coversProviders(rule, providers) {
4130
4193
  return rule.providers.length === providers.length && providers.every((provider) => rule.providers.includes(provider));
4131
4194
  }
4132
4195
  function findCompatibilityRule(rules, query) {
4196
+ const candidates = [];
4133
4197
  for (const rule of rules) {
4134
4198
  if (!rule.capabilities.includes(query.capability))
4135
4199
  continue;
@@ -4137,9 +4201,28 @@ function findCompatibilityRule(rules, query) {
4137
4201
  continue;
4138
4202
  if (!coversProviders(rule, query.providers))
4139
4203
  continue;
4140
- return rule;
4204
+ if (rule.platforms !== void 0 && (query.platform === void 0 || !rule.platforms.some((platform) => platform.os === query.platform?.os && platform.wsl === query.platform?.wsl))) {
4205
+ continue;
4206
+ }
4207
+ candidates.push(rule);
4141
4208
  }
4142
- return null;
4209
+ if (query.observedVersions !== void 0) {
4210
+ const matchesObservedTuple = (rule) => {
4211
+ if (rule.providers.some((provider) => rule.testedVersions[provider] === void 0)) {
4212
+ return false;
4213
+ }
4214
+ const testedHarnessVersion = rule.testedHarnessVersions?.[query.harness];
4215
+ if (rule.outcome === "ordered" && testedHarnessVersion === void 0)
4216
+ return false;
4217
+ return Object.entries(rule.testedVersions).every(([provider, version3]) => query.observedVersions?.[provider] === version3) && (testedHarnessVersion === void 0 || query.observedHarnessVersions?.[query.harness] === testedHarnessVersion);
4218
+ };
4219
+ const exact = candidates.find(matchesObservedTuple);
4220
+ if (exact !== void 0)
4221
+ return exact;
4222
+ const matchingDimensions = (rule) => Object.entries(rule.testedVersions).filter(([provider, version3]) => query.observedVersions?.[provider] === version3).length + (rule.testedHarnessVersions?.[query.harness] !== void 0 && query.observedHarnessVersions?.[query.harness] === rule.testedHarnessVersions[query.harness] ? 1 : 0);
4223
+ candidates.sort((left, right) => matchingDimensions(right) - matchingDimensions(left));
4224
+ }
4225
+ return candidates[0] ?? null;
4143
4226
  }
4144
4227
  function coversVersion(recorded, observed) {
4145
4228
  if (recorded.major === 0 || observed.major === 0)
@@ -4148,17 +4231,25 @@ function coversVersion(recorded, observed) {
4148
4231
  }
4149
4232
  function staleRecordedVersions(rule, observed) {
4150
4233
  const stale2 = [];
4151
- for (const [provider, recorded] of Object.entries(rule.testedVersions)) {
4234
+ for (const provider of rule.providers) {
4235
+ const recorded = rule.testedVersions[provider];
4152
4236
  const seen = observed[provider] ?? null;
4153
- const recordedVersion = parseSemanticVersion(recorded);
4237
+ const recordedVersion = recorded === void 0 ? null : parseSemanticVersion(recorded);
4154
4238
  const seenVersion = seen === null ? null : parseSemanticVersion(seen);
4155
4239
  if (recordedVersion !== null && seenVersion !== null && coversVersion(recordedVersion, seenVersion)) {
4156
4240
  continue;
4157
4241
  }
4158
- stale2.push({ provider, recorded, observed: seen });
4242
+ stale2.push({ provider, recorded: recorded ?? null, observed: seen });
4159
4243
  }
4160
4244
  return stale2;
4161
4245
  }
4246
+ function staleRecordedHarnessVersions(rule, observed, harness) {
4247
+ const recorded = rule.testedHarnessVersions?.[harness];
4248
+ if (recorded === void 0 && rule.outcome !== "ordered")
4249
+ return [];
4250
+ const seen = observed[harness] ?? null;
4251
+ return recorded !== void 0 && seen === recorded ? [] : [{ harness, recorded: recorded ?? null, observed: seen }];
4252
+ }
4162
4253
  var init_compatibility = __esm({
4163
4254
  "packages/core/dist/src/domain/compatibility.js"() {
4164
4255
  "use strict";
@@ -4777,7 +4868,77 @@ function narrowChannelOverlaps(context) {
4777
4868
  if (first === void 0)
4778
4869
  continue;
4779
4870
  const { harness, toolFamily, capability } = first.scope;
4780
- const rule = findCompatibilityRule(input.rules, { providers: owners, harness, capability });
4871
+ const found = findCompatibilityRule(input.rules, {
4872
+ providers: owners,
4873
+ harness,
4874
+ capability,
4875
+ ...input.platform === void 0 ? {} : { platform: input.platform },
4876
+ observedVersions: input.observedVersions,
4877
+ ...input.observedHarnessVersions === void 0 ? {} : { observedHarnessVersions: input.observedHarnessVersions }
4878
+ });
4879
+ const staleProviders = found === null ? [] : staleRecordedVersions(found, input.observedVersions);
4880
+ const staleHarnesses = found === null ? [] : staleRecordedHarnessVersions(found, input.observedHarnessVersions ?? {}, harness);
4881
+ const stale2 = [...staleProviders, ...staleHarnesses];
4882
+ const rule = stale2.length > 0 ? null : found;
4883
+ if (found !== null && stale2.length > 0) {
4884
+ conflicts.push({
4885
+ code: "compatibility-rule-stale",
4886
+ scope: `${harness}/${toolFamily}/${capability}`,
4887
+ claimants: [...owners].sort(),
4888
+ detail: [
4889
+ `${owners.join(" and ")} both use ${capability} on ${harness}/${toolFamily} at different interception points`,
4890
+ `Rule ${found.id} was tested at ${[
4891
+ ...staleProviders.map((entry) => `${entry.provider} ${entry.recorded ?? "not recorded"}`),
4892
+ ...staleHarnesses.map((entry) => `${entry.harness} ${entry.recorded ?? "not recorded"}`)
4893
+ ].join(", ")}`,
4894
+ `Installed now: ${[
4895
+ ...staleProviders.map((entry) => `${entry.provider} ${entry.observed ?? "unknown"}`),
4896
+ ...staleHarnesses.map((entry) => `${entry.harness} ${entry.observed ?? "unknown"}`)
4897
+ ].join(", ")}`,
4898
+ "The compatibility rule does not authorize this provider tuple"
4899
+ ],
4900
+ remediation: `Re-test ${found.id} against the installed versions and platform, or assign one owner to ${harness}/${toolFamily}/${capability}`
4901
+ });
4902
+ for (const entry of group)
4903
+ dropped.add(entry);
4904
+ continue;
4905
+ }
4906
+ if (rule?.outcome === "ordered") {
4907
+ const conflictsBeforeOrdering = conflicts.length;
4908
+ const order = rule.order;
4909
+ if (order === void 0 || order.length !== owners.length) {
4910
+ conflicts.push({
4911
+ code: "compatibility-rule-malformed",
4912
+ scope: `${harness}/${toolFamily}/${capability}`,
4913
+ claimants: [...owners].sort(),
4914
+ detail: [`Rule ${rule.id} does not order every owner in this channel`],
4915
+ remediation: `Fix rule ${rule.id} so its order lists every provider on the channel`
4916
+ });
4917
+ for (const entry of group)
4918
+ dropped.add(entry);
4919
+ continue;
4920
+ }
4921
+ for (const entry of group) {
4922
+ const index = order.indexOf(entry.owner);
4923
+ if (index < 0) {
4924
+ conflicts.push({
4925
+ code: "compatibility-rule-malformed",
4926
+ scope: `${harness}/${toolFamily}/${capability}`,
4927
+ claimants: [...owners].sort(),
4928
+ detail: [`Rule ${rule.id} does not include ${entry.owner}`],
4929
+ remediation: `Fix rule ${rule.id} so its order lists every provider on the channel`
4930
+ });
4931
+ break;
4932
+ }
4933
+ entry.mode = "chainable";
4934
+ entry.order = index;
4935
+ }
4936
+ if (conflicts.length > conflictsBeforeOrdering) {
4937
+ for (const entry of group)
4938
+ dropped.add(entry);
4939
+ }
4940
+ continue;
4941
+ }
4781
4942
  if (rule === null || rule.outcome !== "narrowed" || rule.retains === void 0) {
4782
4943
  conflicts.push({
4783
4944
  code: "exclusive-scope-contested",
@@ -4823,10 +4984,15 @@ function resolveContested(context) {
4823
4984
  const found = findCompatibilityRule(input.rules, {
4824
4985
  providers: claimants,
4825
4986
  harness: scope.harness,
4826
- capability
4987
+ capability,
4988
+ ...input.platform === void 0 ? {} : { platform: input.platform },
4989
+ observedVersions: input.observedVersions,
4990
+ ...input.observedHarnessVersions === void 0 ? {} : { observedHarnessVersions: input.observedHarnessVersions }
4827
4991
  });
4828
4992
  const stale2 = found === null ? [] : staleRecordedVersions(found, input.observedVersions);
4829
- const rule = stale2.length > 0 ? null : found;
4993
+ const staleHarnesses = found === null ? [] : staleRecordedHarnessVersions(found, input.observedHarnessVersions ?? {}, scope.harness);
4994
+ const staleAll = [...stale2, ...staleHarnesses];
4995
+ const rule = staleAll.length > 0 ? null : found;
4830
4996
  if (rule === null) {
4831
4997
  if (found !== null) {
4832
4998
  conflicts.push({
@@ -4835,11 +5001,17 @@ function resolveContested(context) {
4835
5001
  claimants,
4836
5002
  detail: [
4837
5003
  `${claimants.join(" and ")} both claim ${capability} on ${formatCapabilityScope(scope)}`,
4838
- `Rule ${found.id} was tested at ${stale2.map((entry) => `${entry.provider} ${entry.recorded}`).join(", ")}`,
4839
- `Installed now: ${stale2.map((entry) => `${entry.provider} ${entry.observed ?? "unknown"}`).join(", ")}`,
5004
+ `Rule ${found.id} was tested at ${[
5005
+ ...stale2.map((entry) => `${entry.provider} ${entry.recorded ?? "not recorded"}`),
5006
+ ...staleHarnesses.map((entry) => `${entry.harness} ${entry.recorded ?? "not recorded"}`)
5007
+ ].join(", ")}`,
5008
+ `Installed now: ${[
5009
+ ...stale2.map((entry) => `${entry.provider} ${entry.observed ?? "unknown"}`),
5010
+ ...staleHarnesses.map((entry) => `${entry.harness} ${entry.observed ?? "unknown"}`)
5011
+ ].join(", ")}`,
4840
5012
  "A compatibility result covers the versions it records, so this one is withdrawn rather than applied outside them"
4841
5013
  ],
4842
- remediation: `Re-test ${found.id} against the installed versions and update its \`testedVersions\`, or assign the scope explicitly with \`profile: custom\``
5014
+ remediation: `Re-test ${found.id} against the installed provider and harness versions, record the evidence for ${scope.harness}, or assign the scope explicitly with \`profile: custom\``
4843
5015
  });
4844
5016
  return;
4845
5017
  }
@@ -5059,18 +5231,33 @@ var init_removal_order = __esm({
5059
5231
  });
5060
5232
 
5061
5233
  // packages/core/dist/src/planner/rules.js
5062
- var RTK, HARNESSTRIM, RTK_HARNESSTRIM_SHELL_OVERLAP, COMPATIBILITY_RULES;
5234
+ var RTK, HARNESSTRIM, CLAUDE, CODEX, RTK_HARNESSTRIM_ORDERED_LINUX, RTK_HARNESSTRIM_SHELL_OVERLAP, COMPATIBILITY_RULES;
5063
5235
  var init_rules = __esm({
5064
5236
  "packages/core/dist/src/planner/rules.js"() {
5065
5237
  "use strict";
5066
5238
  init_ids();
5067
5239
  RTK = providerId("rtk");
5068
5240
  HARNESSTRIM = providerId("harnesstrim");
5241
+ CLAUDE = harnessId("claude");
5242
+ CODEX = harnessId("codex");
5243
+ RTK_HARNESSTRIM_ORDERED_LINUX = {
5244
+ id: "rtk-harnesstrim-post-tool-chain-linux",
5245
+ providers: [RTK, HARNESSTRIM],
5246
+ harnesses: [CLAUDE, CODEX],
5247
+ capabilities: ["shell.output.reduce"],
5248
+ outcome: "ordered",
5249
+ order: [RTK, HARNESSTRIM],
5250
+ platforms: [{ os: "linux", wsl: false }],
5251
+ testedVersions: { rtk: "0.50.0", harnesstrim: "0.3.1" },
5252
+ testedHarnessVersions: { claude: "2.1.274", codex: "0.159.0" },
5253
+ rationale: "RTK rewrites the Bash command at PreToolUse; HarnessTrim processes the completed Bash result at PostToolUse. The harness lifecycle establishes RTK-before-HarnessTrim. Their telemetry remains separate because the providers do not expose comparable boundaries for one shared operation.",
5254
+ fixtures: ["tests/fixtures/rows/rtk-harnesstrim-chain-linux"]
5255
+ };
5069
5256
  RTK_HARNESSTRIM_SHELL_OVERLAP = {
5070
5257
  id: "rtk-harnesstrim-shell-output-overlap",
5071
5258
  providers: [RTK, HARNESSTRIM],
5072
- // Every harness: the RFC checked all three MVP adapters and found the same overlap on each,
5073
- // for different reasons. Listing them individually would imply a fourth harness is exempt.
5259
+ // Legacy providers retain the reviewed RTK-only narrowing. The resolver selects the exact
5260
+ // provider tuple above for the current Linux runtime chain.
5074
5261
  harnesses: "*",
5075
5262
  capabilities: ["shell.output.reduce"],
5076
5263
  outcome: "narrowed",
@@ -5079,7 +5266,10 @@ var init_rules = __esm({
5079
5266
  rationale: "RTK keeps shell output reduction: it rewrites the command, so the output arriving at any later point is already reduced, and reducing it again loses signal and counts the saving twice. HarnessTrim 0.1.0 no longer has to be excluded whole for that \u2014 `--no-hook` and `--no-instructions` produce a Claude install that adds skills and reduces nothing, and `--tools` confines its OpenCode reduction to a chosen tool family. So it is narrowed to the form that leaves this channel alone, rather than refused. At 0.0.5 no flag produced any of those states, which is why this rule read `conflict` and said no configuration narrows it.",
5080
5267
  fixtures: ["docs/rfcs/0003-capabilities-and-conflicts.md#the-table-is-an-intent"]
5081
5268
  };
5082
- COMPATIBILITY_RULES = [RTK_HARNESSTRIM_SHELL_OVERLAP];
5269
+ COMPATIBILITY_RULES = [
5270
+ RTK_HARNESSTRIM_ORDERED_LINUX,
5271
+ RTK_HARNESSTRIM_SHELL_OVERLAP
5272
+ ];
5083
5273
  }
5084
5274
  });
5085
5275
 
@@ -7160,6 +7350,14 @@ function ensureParent(document2, segments) {
7160
7350
  let current = document2;
7161
7351
  for (let index = 0; index < segments.length - 1; index += 1) {
7162
7352
  const segment = segments[index];
7353
+ if (Array.isArray(current)) {
7354
+ const itemIndex = arrayIndex(segment);
7355
+ if (itemIndex === null || itemIndex >= current.length) {
7356
+ return { ok: false, reason: "path crosses a missing or invalid array entry" };
7357
+ }
7358
+ current = current[itemIndex];
7359
+ continue;
7360
+ }
7163
7361
  if (!isJsonObject(current)) {
7164
7362
  return { ok: false, reason: `\`${segments.slice(0, index).join(".")}\` is not an object` };
7165
7363
  }
@@ -9663,7 +9861,7 @@ var TOOL_VERSION;
9663
9861
  var init_version2 = __esm({
9664
9862
  "apps/cli/dist/src/version.js"() {
9665
9863
  "use strict";
9666
- TOOL_VERSION = "0.1.22";
9864
+ TOOL_VERSION = "0.1.24";
9667
9865
  }
9668
9866
  });
9669
9867
 
@@ -14190,7 +14388,7 @@ async function detect(context) {
14190
14388
  const state = unparsed.length > 0 ? "broken" : configured.length > 0 && version3 !== null ? "configured" : version3 !== null || present.length > 0 ? "detected" : "absent";
14191
14389
  const primary = present.find((config) => config.declaration.primary) ?? present[0] ?? null;
14192
14390
  return {
14193
- harnessId: CLAUDE,
14391
+ harnessId: CLAUDE2,
14194
14392
  state,
14195
14393
  version: version3,
14196
14394
  versionVerdict: verdict,
@@ -14211,7 +14409,7 @@ async function inspect(context) {
14211
14409
  diagnostics.push(diagnostic({
14212
14410
  severity: "warning",
14213
14411
  code: "tool-family-not-covered",
14214
- subject: CLAUDE,
14412
+ subject: CLAUDE2,
14215
14413
  /**
14216
14414
  * Says whose gap it is, and that the tool is working.
14217
14415
  *
@@ -14228,7 +14426,7 @@ async function inspect(context) {
14228
14426
  }));
14229
14427
  }
14230
14428
  return {
14231
- harnessId: CLAUDE,
14429
+ harnessId: CLAUDE2,
14232
14430
  configs,
14233
14431
  activeToolFamilies,
14234
14432
  uncoveredToolFamilies,
@@ -14236,7 +14434,7 @@ async function inspect(context) {
14236
14434
  // settings.json runs. Codex is the one that needs the other answer.
14237
14435
  enabled: MANIFEST.requiresEnablement ? null : null,
14238
14436
  summaries: configs.filter((config) => config.configuredPoints.length > 0).map((config) => ({
14239
- harnessId: CLAUDE,
14437
+ harnessId: CLAUDE2,
14240
14438
  configPath: config.path,
14241
14439
  scope: config.declaration.scope,
14242
14440
  interceptionPoints: config.configuredPoints,
@@ -14300,7 +14498,7 @@ async function verify(context) {
14300
14498
  remediation: null
14301
14499
  });
14302
14500
  const achievedTier = checks.some((check) => check.achievedTier === "config-only") ? "config-only" : checks.some((check) => check.achievedTier === "presence") ? "presence" : null;
14303
- return { harnessId: CLAUDE, declaredTier: MANIFEST.verificationTier, achievedTier, checks };
14501
+ return { harnessId: CLAUDE2, declaredTier: MANIFEST.verificationTier, achievedTier, checks };
14304
14502
  }
14305
14503
  function cclimitsPercent(value3) {
14306
14504
  if (typeof value3 !== "string")
@@ -14326,7 +14524,7 @@ function cclimitsUsageWindow(value3, input) {
14326
14524
  return null;
14327
14525
  }
14328
14526
  return {
14329
- harnessId: CLAUDE,
14527
+ harnessId: CLAUDE2,
14330
14528
  bucketId: "claude-subscription",
14331
14529
  bucketName: "Claude subscription",
14332
14530
  window: input.window,
@@ -14350,7 +14548,7 @@ async function observeUsage(context, observedAt) {
14350
14548
  maxOutputBytes: 512 * 1024
14351
14549
  });
14352
14550
  const unavailable3 = (code, message, severity = "warning", remediation = null) => ({
14353
- harnessId: CLAUDE,
14551
+ harnessId: CLAUDE2,
14354
14552
  state: "unavailable",
14355
14553
  windows: [],
14356
14554
  planType: null,
@@ -14360,7 +14558,7 @@ async function observeUsage(context, observedAt) {
14360
14558
  diagnostic({
14361
14559
  severity,
14362
14560
  code,
14363
- subject: CLAUDE,
14561
+ subject: CLAUDE2,
14364
14562
  message,
14365
14563
  remediation: remediation ?? (severity === "info" ? "Install a cclimits build with cacheless Claude JSON support if you want this optional fallback" : "Run cclimits --claude --json --no-cache-write --no-stale-fallback directly and inspect its output")
14366
14564
  })
@@ -14426,13 +14624,13 @@ async function observeUsage(context, observedAt) {
14426
14624
  diagnostics.push(diagnostic({
14427
14625
  severity: "warning",
14428
14626
  code: "cclimits-claude-window-unrecognized",
14429
- subject: CLAUDE,
14627
+ subject: CLAUDE2,
14430
14628
  message: "One cclimits Claude quota window failed strict percentage validation",
14431
14629
  remediation: "Treat the omitted window as unknown and update the cclimits compatibility fixture"
14432
14630
  }));
14433
14631
  }
14434
14632
  return {
14435
- harnessId: CLAUDE,
14633
+ harnessId: CLAUDE2,
14436
14634
  state: "observed",
14437
14635
  windows,
14438
14636
  planType: typeof claude["plan"] === "string" ? claude["plan"] : null,
@@ -14465,7 +14663,7 @@ async function observeContext(context, _observedAt) {
14465
14663
  const nativeEffort = await readClaudeNativeEffort(context);
14466
14664
  const benchmarkPolicy = await readClaudeBenchmarkPolicy(context, nativeEffort);
14467
14665
  const empty2 = (state, diagnostics) => ({
14468
- harnessId: CLAUDE,
14666
+ harnessId: CLAUDE2,
14469
14667
  state,
14470
14668
  nativeEffort,
14471
14669
  benchmarkPolicy,
@@ -14492,7 +14690,7 @@ async function observeContext(context, _observedAt) {
14492
14690
  diagnostic({
14493
14691
  severity: "warning",
14494
14692
  code: "claude-mcp-inventory-unavailable",
14495
- subject: CLAUDE,
14693
+ subject: CLAUDE2,
14496
14694
  message: "Claude MCP inventory could not be read: " + outcome2.failure.message,
14497
14695
  remediation: "Run claude mcp list directly and verify the CLI installation"
14498
14696
  })
@@ -14503,7 +14701,7 @@ async function observeContext(context, _observedAt) {
14503
14701
  diagnostic({
14504
14702
  severity: "warning",
14505
14703
  code: "claude-mcp-inventory-unavailable",
14506
- subject: CLAUDE,
14704
+ subject: CLAUDE2,
14507
14705
  message: "claude mcp list exited " + String(outcome2.exitCode),
14508
14706
  remediation: "Run claude mcp list directly and fix the reported MCP configuration"
14509
14707
  })
@@ -14521,7 +14719,7 @@ async function observeContext(context, _observedAt) {
14521
14719
  if (name2 === void 0 || name2 === "")
14522
14720
  continue;
14523
14721
  servers.push({
14524
- harnessId: CLAUDE,
14722
+ harnessId: CLAUDE2,
14525
14723
  name: name2,
14526
14724
  toolCount: null,
14527
14725
  runtimeStatus: claudeMcpStatus(match[2] ?? ""),
@@ -14535,7 +14733,7 @@ async function observeContext(context, _observedAt) {
14535
14733
  mcpServers: servers
14536
14734
  };
14537
14735
  }
14538
- var CLAUDE, MANIFEST, VERSION_PATTERN, claudeAdapter;
14736
+ var CLAUDE2, MANIFEST, VERSION_PATTERN, claudeAdapter;
14539
14737
  var init_claude = __esm({
14540
14738
  "packages/adapters/dist/src/harnesses/claude.js"() {
14541
14739
  "use strict";
@@ -14543,20 +14741,23 @@ var init_claude = __esm({
14543
14741
  init_contract();
14544
14742
  init_claude_policy();
14545
14743
  init_claude_benchmark_policy();
14546
- CLAUDE = harnessId("claude");
14744
+ CLAUDE2 = harnessId("claude");
14547
14745
  MANIFEST = {
14548
14746
  schemaVersion: MANIFEST_SCHEMA_VERSION,
14549
- id: CLAUDE,
14747
+ id: CLAUDE2,
14550
14748
  displayName: "Claude Code",
14551
14749
  homepage: "https://claude.com/claude-code",
14552
- testedVersions: { minimum: "2.0.0", maximum: "2.1.212" },
14750
+ testedVersions: { minimum: "2.1.274", maximum: "2.1.274" },
14553
14751
  // RFC 0007 §Per-harness findings: tier 3 was reached on this harness, passively,
14554
14752
  // through the provider's receipt. The adapter alone reaches `config-only`.
14555
14753
  verificationTier: "canary",
14556
14754
  versionCommand: { executable: "claude", args: ["--version"] },
14557
14755
  interceptionPoints: [
14558
14756
  { scopeId: "pre-tool-use", eventName: "PreToolUse" },
14559
- { scopeId: "post-tool-use", eventName: "PostToolUse" }
14757
+ { scopeId: "post-tool-use", eventName: "PostToolUse" },
14758
+ { scopeId: "user-prompt-submit", eventName: "UserPromptSubmit" },
14759
+ { scopeId: "subagent-start", eventName: "SubagentStart" },
14760
+ { scopeId: "subagent-stop", eventName: "SubagentStop" }
14560
14761
  ],
14561
14762
  configFiles: [
14562
14763
  {
@@ -14565,7 +14766,13 @@ var init_claude = __esm({
14565
14766
  parser: "json",
14566
14767
  primary: true,
14567
14768
  interceptionFormat: "hooks-event-command-list",
14568
- interceptionPoints: ["pre-tool-use", "post-tool-use"]
14769
+ interceptionPoints: [
14770
+ "pre-tool-use",
14771
+ "post-tool-use",
14772
+ "user-prompt-submit",
14773
+ "subagent-start",
14774
+ "subagent-stop"
14775
+ ]
14569
14776
  },
14570
14777
  { path: ".claude/settings.json", scope: "project", parser: "json", primary: false },
14571
14778
  { path: ".claude/settings.local.json", scope: "project", parser: "json", primary: false }
@@ -14573,6 +14780,7 @@ var init_claude = __esm({
14573
14780
  toolFamilies: [
14574
14781
  {
14575
14782
  id: "Bash",
14783
+ matcher: "Bash",
14576
14784
  platforms: ["windows", "macos", "linux"],
14577
14785
  executesShellCommands: true
14578
14786
  },
@@ -14580,6 +14788,7 @@ var init_claude = __esm({
14580
14788
  // Observed in a Windows session: the harness offers a separate PowerShell tool,
14581
14789
  // and a hook matching `Bash` did not see commands routed through it.
14582
14790
  id: "PowerShell",
14791
+ matcher: "PowerShell",
14583
14792
  platforms: ["windows"],
14584
14793
  executesShellCommands: true
14585
14794
  }
@@ -14913,7 +15122,7 @@ async function detect2(context) {
14913
15122
  const configured = (hooks?.configuredPoints.length ?? 0) > 0;
14914
15123
  const primary = configs.find((config) => config.declaration.primary && config.exists) ?? present[0] ?? null;
14915
15124
  return {
14916
- harnessId: CODEX,
15125
+ harnessId: CODEX2,
14917
15126
  state: hooks?.exists && !hooks.parsed ? "broken" : configured && version3 !== null ? "configured" : version3 !== null || present.length > 0 ? "detected" : "absent",
14918
15127
  version: version3,
14919
15128
  versionVerdict: verdict,
@@ -14939,14 +15148,14 @@ async function inspect2(context) {
14939
15148
  diagnostic({
14940
15149
  severity: "info",
14941
15150
  code: "hook-enablement-unobservable",
14942
- subject: CODEX,
15151
+ subject: CODEX2,
14943
15152
  message: "This file declares hooks; run verify to query native enablement/trust where hooks/list is available",
14944
15153
  path: hook.path,
14945
15154
  remediation: "Open Codex and confirm the hook is enabled and trusted after any hook edit"
14946
15155
  })
14947
15156
  ] : [];
14948
15157
  return {
14949
- harnessId: CODEX,
15158
+ harnessId: CODEX2,
14950
15159
  configs,
14951
15160
  activeToolFamilies: familiesOnThisPlatform(MANIFEST2, context.facts),
14952
15161
  /**
@@ -14963,7 +15172,7 @@ async function inspect2(context) {
14963
15172
  uncoveredToolFamilies: familiesOnThisPlatform(MANIFEST2, context.facts).filter((family) => family.executesShellCommands).filter((family) => matchers.length > 0 && !matchers.some((matcher) => matcherCoversFamily(matcher, family.id))).map((family) => family.id),
14964
15173
  enabled: null,
14965
15174
  summaries: configs.filter((config) => config.configuredPoints.length > 0).map((config) => ({
14966
- harnessId: CODEX,
15175
+ harnessId: CODEX2,
14967
15176
  configPath: config.path,
14968
15177
  scope: config.declaration.scope,
14969
15178
  interceptionPoints: config.configuredPoints,
@@ -14983,11 +15192,15 @@ async function verify2(context) {
14983
15192
  const checks = [
14984
15193
  {
14985
15194
  id: "executable-resolves",
14986
- status: detection.version === null ? "fail" : "pass",
14987
- summary: detection.version === null ? "codex could not be run" : `Codex ${detection.version} resolves`,
15195
+ // Codex Desktop can run hooks from its own app process without exposing the optional
15196
+ // `codex` CLI to the shell that runs Token Harness. Missing CLI access therefore means
15197
+ // that CLI-based checks cannot be exercised; the provider rows remain responsible for
15198
+ // proving actual hook execution from RTK/HarnessTrim telemetry.
15199
+ status: detection.version === null ? "not-exercised" : "pass",
15200
+ summary: detection.version === null ? "Codex CLI is unavailable to this process; native CLI checks cannot run" : `Codex ${detection.version} resolves`,
14988
15201
  achievedTier: detection.version === null ? null : "presence",
14989
15202
  evidence: detection.evidence.filter((item) => item.kind === "version-output"),
14990
- remediation: detection.version === null ? "Install Codex CLI or add it to PATH" : null
15203
+ remediation: null
14991
15204
  },
14992
15205
  {
14993
15206
  id: "hooks-readable",
@@ -15010,15 +15223,15 @@ async function verify2(context) {
15010
15223
  {
15011
15224
  id: "hook-enablement",
15012
15225
  status: configured ? "info" : "not-exercised",
15013
- summary: configured ? "Native enablement/trust metadata was unavailable; the declared file alone does not prove activation" : "No declared hook has enablement to inspect",
15226
+ summary: configured ? "Native enablement/trust metadata is unavailable; configuration alone does not prove activation" : "No declared hook has enablement to inspect",
15014
15227
  achievedTier: null,
15015
15228
  evidence: [],
15016
- remediation: configured ? "Open Codex and manually enable and trust the hook; Token Harness cannot grant trust. Then run verify again." : null
15229
+ remediation: configured ? "Use Codex hook controls to enable and trust the declared hook, then run a provider canary; Token Harness cannot grant trust." : null
15017
15230
  },
15018
15231
  {
15019
15232
  id: "canary-intercepted",
15020
15233
  status: "not-exercised",
15021
- summary: "No positive event-stream receipt has been observed for this integration",
15234
+ summary: "No Codex CLI event-stream receipt is available from passive verification; provider-specific runtime receipts are checked separately",
15022
15235
  achievedTier: null,
15023
15236
  evidence: [],
15024
15237
  remediation: null
@@ -15033,7 +15246,7 @@ async function verify2(context) {
15033
15246
  }
15034
15247
  }
15035
15248
  return {
15036
- harnessId: CODEX,
15249
+ harnessId: CODEX2,
15037
15250
  declaredTier: MANIFEST2.verificationTier,
15038
15251
  achievedTier: detection.version !== null && readable && configured ? "config-only" : detection.version !== null ? "presence" : null,
15039
15252
  checks
@@ -15069,7 +15282,7 @@ function rateWindow(value3, input) {
15069
15282
  const duration2 = readNumber(value3, "windowDurationMins");
15070
15283
  const resetsAt = readNumber(value3, "resetsAt");
15071
15284
  return {
15072
- harnessId: CODEX,
15285
+ harnessId: CODEX2,
15073
15286
  bucketId: input.bucketId,
15074
15287
  bucketName: input.bucketName,
15075
15288
  window: input.window,
@@ -15171,7 +15384,7 @@ function cclimitsWindow(value3, input) {
15171
15384
  return null;
15172
15385
  }
15173
15386
  return {
15174
- harnessId: CODEX,
15387
+ harnessId: CODEX2,
15175
15388
  bucketId: "codex-subscription",
15176
15389
  bucketName: "Codex subscription",
15177
15390
  window: input.window,
@@ -15231,7 +15444,7 @@ async function observeUsageViaCclimits(context, observedAt, nativeDiagnostic) {
15231
15444
  if (outcome2.failure !== null || outcome2.exitCode !== 0 || outcome2.stdoutTruncated) {
15232
15445
  const reason3 = outcome2.failure !== null ? outcome2.failure.message : outcome2.stdoutTruncated ? "output exceeded the bounded capture" : `exited ${String(outcome2.exitCode)}`;
15233
15446
  return {
15234
- harnessId: CODEX,
15447
+ harnessId: CODEX2,
15235
15448
  state: "unavailable",
15236
15449
  windows: [],
15237
15450
  planType: null,
@@ -15242,7 +15455,7 @@ async function observeUsageViaCclimits(context, observedAt, nativeDiagnostic) {
15242
15455
  diagnostic({
15243
15456
  severity: outcome2.failure?.reason === "executable-not-found" ? "info" : "warning",
15244
15457
  code: "cclimits-codex-usage-unavailable",
15245
- subject: CODEX,
15458
+ subject: CODEX2,
15246
15459
  message: "Optional cclimits Codex quota fallback was unavailable: " + reason3,
15247
15460
  remediation: "Install a cclimits build with cacheless Codex JSON support, or treat Codex quota as unknown"
15248
15461
  })
@@ -15252,7 +15465,7 @@ async function observeUsageViaCclimits(context, observedAt, nativeDiagnostic) {
15252
15465
  const parsed = parseCclimitsCodexResponse(outcome2.stdout, observedAt);
15253
15466
  if (parsed === null) {
15254
15467
  return {
15255
- harnessId: CODEX,
15468
+ harnessId: CODEX2,
15256
15469
  state: "unavailable",
15257
15470
  windows: [],
15258
15471
  planType: null,
@@ -15263,7 +15476,7 @@ async function observeUsageViaCclimits(context, observedAt, nativeDiagnostic) {
15263
15476
  diagnostic({
15264
15477
  severity: "warning",
15265
15478
  code: "cclimits-codex-schema-unrecognized",
15266
- subject: CODEX,
15479
+ subject: CODEX2,
15267
15480
  message: "cclimits returned no strictly validated Codex quota window with an absolute reset time",
15268
15481
  remediation: "Update the cclimits Codex compatibility fixture before using it for benchmark quota"
15269
15482
  })
@@ -15271,14 +15484,14 @@ async function observeUsageViaCclimits(context, observedAt, nativeDiagnostic) {
15271
15484
  };
15272
15485
  }
15273
15486
  return {
15274
- harnessId: CODEX,
15487
+ harnessId: CODEX2,
15275
15488
  state: "observed",
15276
15489
  ...parsed,
15277
15490
  diagnostics: [
15278
15491
  diagnostic({
15279
15492
  severity: "info",
15280
15493
  code: "codex-rate-limits-companion-fallback",
15281
- subject: CODEX,
15494
+ subject: CODEX2,
15282
15495
  message: "Native Codex quota was unavailable, so cclimits supplied a read-only reported snapshot",
15283
15496
  remediation: null
15284
15497
  })
@@ -15315,7 +15528,7 @@ async function observeUsage2(context, observedAt) {
15315
15528
  return observeUsageViaCclimits(context, observedAt, diagnostic({
15316
15529
  severity: "warning",
15317
15530
  code: "codex-rate-limits-unavailable",
15318
- subject: CODEX,
15531
+ subject: CODEX2,
15319
15532
  message: "Codex rate limits could not be read natively: " + outcome2.failure.message,
15320
15533
  remediation: "Run Codex once, confirm ChatGPT authentication, then retry token-harness budget"
15321
15534
  }));
@@ -15324,7 +15537,7 @@ async function observeUsage2(context, observedAt) {
15324
15537
  return observeUsageViaCclimits(context, observedAt, diagnostic({
15325
15538
  severity: "warning",
15326
15539
  code: "codex-rate-limits-unavailable",
15327
- subject: CODEX,
15540
+ subject: CODEX2,
15328
15541
  message: "Codex app-server exited " + String(outcome2.exitCode) + " without a usable rate-limit snapshot",
15329
15542
  remediation: "Check codex app-server --help and the installed Codex authentication state"
15330
15543
  }));
@@ -15334,7 +15547,7 @@ async function observeUsage2(context, observedAt) {
15334
15547
  return observeUsageViaCclimits(context, observedAt, diagnostic({
15335
15548
  severity: "warning",
15336
15549
  code: "codex-rate-limits-schema-unrecognized",
15337
- subject: CODEX,
15550
+ subject: CODEX2,
15338
15551
  message: "Codex app-server returned no recognizable account/rateLimits/read response",
15339
15552
  remediation: "Refresh the Codex compatibility fixture before relying on this version"
15340
15553
  }));
@@ -15343,13 +15556,13 @@ async function observeUsage2(context, observedAt) {
15343
15556
  return observeUsageViaCclimits(context, observedAt, diagnostic({
15344
15557
  severity: "warning",
15345
15558
  code: "codex-rate-limits-empty",
15346
- subject: CODEX,
15559
+ subject: CODEX2,
15347
15560
  message: "Codex returned a rate-limit response without any readable usage windows",
15348
15561
  remediation: "Treat current Codex quota as unknown unless a strict companion snapshot succeeds"
15349
15562
  }));
15350
15563
  }
15351
15564
  return {
15352
- harnessId: CODEX,
15565
+ harnessId: CODEX2,
15353
15566
  state: "observed",
15354
15567
  ...parsed,
15355
15568
  diagnostics: []
@@ -15429,7 +15642,7 @@ async function observeContext2(context, _observedAt) {
15429
15642
  maxOutputBytes: 4 * 1024 * 1024
15430
15643
  });
15431
15644
  const unavailable3 = (state, code, message) => ({
15432
- harnessId: CODEX,
15645
+ harnessId: CODEX2,
15433
15646
  state,
15434
15647
  model: null,
15435
15648
  reasoningEffort: null,
@@ -15451,7 +15664,7 @@ async function observeContext2(context, _observedAt) {
15451
15664
  diagnostic({
15452
15665
  severity: "warning",
15453
15666
  code,
15454
- subject: CODEX,
15667
+ subject: CODEX2,
15455
15668
  message,
15456
15669
  remediation: "Update Codex and retry token-harness context"
15457
15670
  })
@@ -15518,7 +15731,7 @@ async function observeContext2(context, _observedAt) {
15518
15731
  if (path === null || version3 === null)
15519
15732
  continue;
15520
15733
  return {
15521
- harnessId: CODEX,
15734
+ harnessId: CODEX2,
15522
15735
  scope: "user",
15523
15736
  path,
15524
15737
  version: version3,
@@ -15542,7 +15755,7 @@ async function observeContext2(context, _observedAt) {
15542
15755
  const path = readString(source, "file");
15543
15756
  const profile = readString(source, "profile");
15544
15757
  managedConfigFieldOrigins.push({
15545
- harnessId: CODEX,
15758
+ harnessId: CODEX2,
15546
15759
  keyPath,
15547
15760
  sourceType,
15548
15761
  path,
@@ -15578,7 +15791,7 @@ async function observeContext2(context, _observedAt) {
15578
15791
  }
15579
15792
  }
15580
15793
  availableModels.push({
15581
- harnessId: CODEX,
15794
+ harnessId: CODEX2,
15582
15795
  id,
15583
15796
  model,
15584
15797
  displayName,
@@ -15602,7 +15815,7 @@ async function observeContext2(context, _observedAt) {
15602
15815
  continue;
15603
15816
  const tools = isRecord3(item["tools"]) ? item["tools"] : null;
15604
15817
  mcpServers.push({
15605
- harnessId: CODEX,
15818
+ harnessId: CODEX2,
15606
15819
  name: name2,
15607
15820
  toolCount: tools === null ? null : Object.keys(tools).length,
15608
15821
  runtimeStatus: readString(item, "runtimeStatus"),
@@ -15618,7 +15831,7 @@ async function observeContext2(context, _observedAt) {
15618
15831
  diagnostics.push(diagnostic({
15619
15832
  severity: "warning",
15620
15833
  code: "codex-config-read-unavailable",
15621
- subject: CODEX,
15834
+ subject: CODEX2,
15622
15835
  message: "Codex returned no recognizable config/read result",
15623
15836
  remediation: "Treat effective Codex configuration as unknown"
15624
15837
  }));
@@ -15627,7 +15840,7 @@ async function observeContext2(context, _observedAt) {
15627
15840
  diagnostics.push(diagnostic({
15628
15841
  severity: "warning",
15629
15842
  code: "codex-managed-config-target-unavailable",
15630
- subject: CODEX,
15843
+ subject: CODEX2,
15631
15844
  message: "Codex effective config was readable, but no versioned base user config layer was returned",
15632
15845
  remediation: "Keep native policy advisory; do not guess a config.toml path or expectedVersion"
15633
15846
  }));
@@ -15636,7 +15849,7 @@ async function observeContext2(context, _observedAt) {
15636
15849
  diagnostics.push(diagnostic({
15637
15850
  severity: "warning",
15638
15851
  code: "codex-model-catalog-unavailable",
15639
- subject: CODEX,
15852
+ subject: CODEX2,
15640
15853
  message: "Codex returned no recognizable model/list result",
15641
15854
  remediation: "Keep the current model; do not infer alternative model ids"
15642
15855
  }));
@@ -15645,7 +15858,7 @@ async function observeContext2(context, _observedAt) {
15645
15858
  diagnostics.push(diagnostic({
15646
15859
  severity: "warning",
15647
15860
  code: "codex-model-catalog-truncated",
15648
- subject: CODEX,
15861
+ subject: CODEX2,
15649
15862
  message: "Codex model catalog exceeded the one-shot page size",
15650
15863
  remediation: "Do not recommend a model absent from the returned catalog page"
15651
15864
  }));
@@ -15654,7 +15867,7 @@ async function observeContext2(context, _observedAt) {
15654
15867
  diagnostics.push(diagnostic({
15655
15868
  severity: "warning",
15656
15869
  code: "codex-mcp-inventory-unavailable",
15657
- subject: CODEX,
15870
+ subject: CODEX2,
15658
15871
  message: "Codex returned no recognizable mcpServerStatus/list result",
15659
15872
  remediation: "Treat Codex MCP overhead as unknown; config/model optimization remains available"
15660
15873
  }));
@@ -15663,14 +15876,14 @@ async function observeContext2(context, _observedAt) {
15663
15876
  diagnostics.push(diagnostic({
15664
15877
  severity: "warning",
15665
15878
  code: "codex-mcp-inventory-truncated",
15666
- subject: CODEX,
15879
+ subject: CODEX2,
15667
15880
  message: "Codex MCP inventory exceeded the one-shot page size",
15668
15881
  remediation: "Treat the reported MCP/tool counts as lower bounds"
15669
15882
  }));
15670
15883
  }
15671
15884
  const projectRootMarkers = config === null ? null : Array.isArray(config["project_root_markers"]) ? readStringArray(config, "project_root_markers") : null;
15672
15885
  return {
15673
- harnessId: CODEX,
15886
+ harnessId: CODEX2,
15674
15887
  state: config !== null && mcpResponse !== null && modelResponse !== null ? mcpInventoryTruncated || modelCatalogTruncated ? "partial" : "observed" : config !== null || mcpResponse !== null || modelResponse !== null ? "partial" : "unavailable",
15675
15888
  model: config === null ? null : readString(config, "model"),
15676
15889
  reasoningEffort: config === null ? null : readString(config, "model_reasoning_effort"),
@@ -15691,7 +15904,7 @@ async function observeContext2(context, _observedAt) {
15691
15904
  diagnostics
15692
15905
  };
15693
15906
  }
15694
- var CODEX, RATE_LIMIT_REQUEST_ID, CONTEXT_CONFIG_REQUEST_ID, CONTEXT_MCP_REQUEST_ID, CONTEXT_MODEL_REQUEST_ID, VERSION_PATTERN2, MANIFEST2, codexAdapter;
15907
+ var CODEX2, RATE_LIMIT_REQUEST_ID, CONTEXT_CONFIG_REQUEST_ID, CONTEXT_MCP_REQUEST_ID, CONTEXT_MODEL_REQUEST_ID, VERSION_PATTERN2, MANIFEST2, codexAdapter;
15695
15908
  var init_codex = __esm({
15696
15909
  "packages/adapters/dist/src/harnesses/codex.js"() {
15697
15910
  "use strict";
@@ -15699,7 +15912,7 @@ var init_codex = __esm({
15699
15912
  init_claude();
15700
15913
  init_codex_hooks();
15701
15914
  init_contract();
15702
- CODEX = harnessId("codex");
15915
+ CODEX2 = harnessId("codex");
15703
15916
  RATE_LIMIT_REQUEST_ID = "token-harness-rate-limits";
15704
15917
  CONTEXT_CONFIG_REQUEST_ID = "token-harness-context-config";
15705
15918
  CONTEXT_MCP_REQUEST_ID = "token-harness-context-mcp";
@@ -15707,10 +15920,10 @@ var init_codex = __esm({
15707
15920
  VERSION_PATTERN2 = /(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/;
15708
15921
  MANIFEST2 = {
15709
15922
  schemaVersion: MANIFEST_SCHEMA_VERSION,
15710
- id: CODEX,
15923
+ id: CODEX2,
15711
15924
  displayName: "Codex CLI",
15712
15925
  homepage: "https://developers.openai.com/codex",
15713
- testedVersions: { minimum: "0.146.0", maximum: "0.146.0" },
15926
+ testedVersions: { minimum: "0.159.0", maximum: "0.159.0" },
15714
15927
  verificationTier: "config-only",
15715
15928
  versionCommand: { executable: "codex", args: ["--version"] },
15716
15929
  /**
@@ -15727,7 +15940,10 @@ var init_codex = __esm({
15727
15940
  */
15728
15941
  interceptionPoints: [
15729
15942
  { scopeId: "pre-tool-use", eventName: "PreToolUse" },
15730
- { scopeId: "post-tool-use", eventName: "PostToolUse" }
15943
+ { scopeId: "post-tool-use", eventName: "PostToolUse" },
15944
+ { scopeId: "user-prompt-submit", eventName: "UserPromptSubmit" },
15945
+ { scopeId: "subagent-start", eventName: "SubagentStart" },
15946
+ { scopeId: "subagent-stop", eventName: "SubagentStop" }
15731
15947
  ],
15732
15948
  configFiles: [
15733
15949
  { path: ".codex/config.toml", scope: "user", parser: "toml", primary: true },
@@ -15737,11 +15953,22 @@ var init_codex = __esm({
15737
15953
  parser: "json",
15738
15954
  primary: false,
15739
15955
  interceptionFormat: "hooks-event-command-list",
15740
- interceptionPoints: ["pre-tool-use", "post-tool-use"]
15956
+ interceptionPoints: [
15957
+ "pre-tool-use",
15958
+ "post-tool-use",
15959
+ "user-prompt-submit",
15960
+ "subagent-start",
15961
+ "subagent-stop"
15962
+ ]
15741
15963
  }
15742
15964
  ],
15743
15965
  toolFamilies: [
15744
- { id: "Bash", platforms: ["windows", "macos", "linux"], executesShellCommands: true }
15966
+ {
15967
+ id: "Bash",
15968
+ matcher: "^Bash$",
15969
+ platforms: ["windows", "macos", "linux"],
15970
+ executesShellCommands: true
15971
+ }
15745
15972
  ],
15746
15973
  requiresEnablement: true,
15747
15974
  enablementNote: "Codex persists hook enablement and trust separately from hooks.json; verify reads hooks/list where available and otherwise keeps enablement unknown",
@@ -16500,10 +16727,49 @@ var init_pi = __esm({
16500
16727
  }
16501
16728
  });
16502
16729
 
16730
+ // packages/adapters/dist/src/harnesses/native-prompt-routing.js
16731
+ function nativePromptRoutingHookEntries(harness, executable = "token-harness") {
16732
+ return NATIVE_PROMPT_ROUTING_EVENTS.map(({ eventName, commandEvent }) => {
16733
+ if (harness === "codex") {
16734
+ const command = `${executable} __internal-prompt-router codex ${commandEvent}`;
16735
+ const handler2 = {
16736
+ type: "command",
16737
+ command,
16738
+ commandWindows: command,
16739
+ timeout: 10
16740
+ };
16741
+ if (commandEvent === "prompt-submit")
16742
+ handler2["additionalContextLimit"] = 500;
16743
+ return { eventName, value: { hooks: [handler2] } };
16744
+ }
16745
+ const handler = {
16746
+ type: "command",
16747
+ command: executable,
16748
+ args: ["__internal-prompt-router", "claude", commandEvent],
16749
+ timeout: 10
16750
+ };
16751
+ return { eventName, value: { hooks: [handler] } };
16752
+ });
16753
+ }
16754
+ var NATIVE_PROMPT_ROUTING_EVENTS;
16755
+ var init_native_prompt_routing = __esm({
16756
+ "packages/adapters/dist/src/harnesses/native-prompt-routing.js"() {
16757
+ "use strict";
16758
+ NATIVE_PROMPT_ROUTING_EVENTS = [
16759
+ { eventName: "UserPromptSubmit", commandEvent: "prompt-submit" },
16760
+ { eventName: "SubagentStart", commandEvent: "subagent-start" },
16761
+ { eventName: "SubagentStop", commandEvent: "subagent-stop" }
16762
+ ];
16763
+ }
16764
+ });
16765
+
16503
16766
  // packages/adapters/dist/src/harnesses/index.js
16504
16767
  function listHarnessAdapters() {
16505
16768
  return HARNESS_ADAPTERS;
16506
16769
  }
16770
+ function findHarnessAdapter(id) {
16771
+ return HARNESS_ADAPTERS.find((adapter) => adapter.manifest.id === id) ?? null;
16772
+ }
16507
16773
  var HARNESS_ADAPTERS;
16508
16774
  var init_harnesses = __esm({
16509
16775
  "packages/adapters/dist/src/harnesses/index.js"() {
@@ -16521,6 +16787,7 @@ var init_harnesses = __esm({
16521
16787
  init_opencode();
16522
16788
  init_pi();
16523
16789
  init_claude();
16790
+ init_native_prompt_routing();
16524
16791
  HARNESS_ADAPTERS = [
16525
16792
  claudeAdapter,
16526
16793
  codexAdapter,
@@ -16531,6 +16798,105 @@ var init_harnesses = __esm({
16531
16798
  }
16532
16799
  });
16533
16800
 
16801
+ // packages/adapters/dist/src/providers/hook-plan.js
16802
+ function hookListPointer(eventName) {
16803
+ return `hooks.${eventName.replace(/\./g, "\\.")}`;
16804
+ }
16805
+ function hookMatcherForFamily(harness, toolFamily) {
16806
+ const family = harness.toolFamilies.find((entry) => entry.id === toolFamily);
16807
+ return family?.matcher ?? toolFamily;
16808
+ }
16809
+ function commandHookTarget(context, harness, scopeId, toolFamily) {
16810
+ const point = harness.interceptionPoints.find((entry) => entry.scopeId === scopeId);
16811
+ const family = harness.toolFamilies.find((entry) => entry.id === toolFamily);
16812
+ const file = harness.configFiles.find((entry) => entry.interceptionFormat === "hooks-event-command-list" && entry.interceptionPoints?.includes(scopeId));
16813
+ if (point === void 0 || family === void 0 || file === void 0)
16814
+ return null;
16815
+ const base = file.scope === "user" ? context.paths.home : context.projectRoot;
16816
+ const configPath = context.fs.join(base, ...file.path.split("/"));
16817
+ return {
16818
+ harness,
16819
+ harnessId: harness.id,
16820
+ scopeId,
16821
+ toolFamily,
16822
+ eventName: point.eventName,
16823
+ matcher: family.matcher ?? family.id,
16824
+ configPath,
16825
+ pointer: hookListPointer(point.eventName)
16826
+ };
16827
+ }
16828
+ function commandHookEntry(matcher, command) {
16829
+ return {
16830
+ matcher,
16831
+ hooks: [{ type: "command", command }]
16832
+ };
16833
+ }
16834
+ function appendCommandHookAction(input) {
16835
+ const { target } = input;
16836
+ return {
16837
+ kind: "merge-json",
16838
+ id: input.actionId,
16839
+ riskClass: "reversible",
16840
+ requiresNetwork: false,
16841
+ requiresElevation: false,
16842
+ affectedPaths: [target.configPath],
16843
+ affectedProcesses: [],
16844
+ preconditions: [
16845
+ `${target.configPath} is absent or parses as JSON`,
16846
+ `no ${input.providerId} command hook already exists on ${target.eventName}/${target.toolFamily}`
16847
+ ],
16848
+ postconditions: [
16849
+ `${target.eventName} carries one ${input.providerId} command hook for ${target.toolFamily}`,
16850
+ "every other hook entry is unchanged"
16851
+ ],
16852
+ rollbackData: "file-snapshot",
16853
+ explanation: input.explanation,
16854
+ path: target.configPath,
16855
+ ownedPointers: [target.pointer],
16856
+ operations: [
16857
+ {
16858
+ kind: "append",
16859
+ pointer: target.pointer,
16860
+ value: commandHookEntry(target.matcher, input.command),
16861
+ expectedValueDigest: null
16862
+ }
16863
+ ],
16864
+ createIfMissing: true
16865
+ };
16866
+ }
16867
+ function removeCommandHookAction(input) {
16868
+ return {
16869
+ kind: "remove-owned-change",
16870
+ id: input.actionId,
16871
+ riskClass: "reversible",
16872
+ requiresNetwork: false,
16873
+ requiresElevation: false,
16874
+ affectedPaths: [input.target.configPath],
16875
+ affectedProcesses: [],
16876
+ preconditions: [`the ${input.providerId} hook still matches the entry Token Harness wrote`],
16877
+ postconditions: [
16878
+ `${input.target.eventName} no longer carries the Token Harness ${input.providerId} hook`
16879
+ ],
16880
+ rollbackData: "file-snapshot",
16881
+ explanation: `Remove the ${input.providerId} hook from ${input.target.harness.displayName}`,
16882
+ path: input.target.configPath,
16883
+ reverses: input.installActionId,
16884
+ target: {
16885
+ kind: "owned-json-entry",
16886
+ path: input.target.configPath,
16887
+ pointer: input.target.pointer,
16888
+ placement: "array-element",
16889
+ valueDigest: jsonValueDigest(commandHookEntry(input.target.matcher, input.command))
16890
+ }
16891
+ };
16892
+ }
16893
+ var init_hook_plan = __esm({
16894
+ "packages/adapters/dist/src/providers/hook-plan.js"() {
16895
+ "use strict";
16896
+ init_src();
16897
+ }
16898
+ });
16899
+
16534
16900
  // packages/adapters/dist/src/providers/harnesstrim.js
16535
16901
  function identifiesCommand(command) {
16536
16902
  return HOOK_COMMAND_PATTERN.test(command) || PLUGIN_MODULE_PATTERN2.test(command);
@@ -17037,22 +17403,27 @@ async function verify6(context) {
17037
17403
  continue;
17038
17404
  const text3 = new TextDecoder().decode(await context.fs.readFile(path));
17039
17405
  const lines = text3.split("\n").filter((line) => line.trim() !== "");
17040
- const last = lines.at(-1);
17041
- const parsed = last === void 0 ? null : parseTrimEvent(last);
17042
- if (parsed === null)
17406
+ const parsed = lines.map(parseTrimEvent).filter((event) => event !== null).filter((event) => event.harness === "codex" || event.harness === "claude");
17407
+ const latest = parsed.at(-1);
17408
+ if (latest === void 0)
17043
17409
  continue;
17044
- receipt = { observedAt: parsed.ts, operations: lines.length, source: path };
17410
+ const reductions = parsed.filter((event) => !event.reductionFailed && event.afterChars < event.beforeChars && event.changed !== false);
17411
+ receipt = {
17412
+ observedAt: latest.ts,
17413
+ operations: reductions.length,
17414
+ attempts: parsed.length,
17415
+ source: path
17416
+ };
17045
17417
  break;
17046
17418
  }
17047
17419
  checks.push({
17048
17420
  id: "canary-intercepted",
17049
- status: receipt === null ? "not-exercised" : "pass",
17050
- summary: receipt === null ? "no telemetry file yet, so nothing has been observed" : `${String(receipt.operations)} reductions recorded, most recently ${receipt.observedAt}`,
17051
- // A recorded reduction is the provider witnessing its own interception, which is what `canary`
17052
- // means in RFC 0007's tier table.
17053
- achievedTier: receipt === null ? null : "canary",
17421
+ status: receipt === null ? "not-exercised" : receipt.operations === 0 ? "info" : "pass",
17422
+ summary: receipt === null ? "no telemetry file yet, so nothing has been observed" : receipt.operations === 0 ? `HarnessTrim observed ${String(receipt.attempts ?? 0)} Claude/Codex outputs, but none was reduced; latest attempt ${receipt.observedAt}` : `${String(receipt.operations)} applied reductions recorded from ${String(receipt.attempts ?? receipt.operations)} Claude/Codex outputs, most recently ${receipt.observedAt}`,
17423
+ // Configured hooks and pass-through receipts do not prove that HarnessTrim shortened output.
17424
+ achievedTier: receipt === null || receipt.operations === 0 ? null : "canary",
17054
17425
  evidence: [],
17055
- remediation: receipt !== null ? null : runtimeConfigured.length > 0 ? "Enable telemetry on the runtime integration, then use it on an output it can reduce." : "A skills-only setup does not write reduction telemetry. Configure a compatible measurement path before expecting agent-attributed results."
17426
+ remediation: receipt !== null && receipt.operations > 0 ? null : receipt !== null ? "Run a canary that produces output the installed HarnessTrim reducer can shorten, then verify again." : runtimeConfigured.length > 0 ? "Enable telemetry on the runtime integration, then use it on an output it can reduce." : "A skills-only setup does not write reduction telemetry. Configure a compatible measurement path before expecting agent-attributed results."
17056
17427
  });
17057
17428
  const agents = context.fs.join(context.projectRoot, "AGENTS.md");
17058
17429
  if (await context.fs.stat(agents) !== null) {
@@ -17294,7 +17665,7 @@ async function harnessTrimSkillsConfigured(context, harness, capabilities) {
17294
17665
  }
17295
17666
  async function configuredHarnessesForHarnessTrim(context, capabilities) {
17296
17667
  const configured = new Set(harnessesWiredToHarnessTrim(context.harnessConfigs));
17297
- for (const harness of [CLAUDE2, CODEX2]) {
17668
+ for (const harness of [CLAUDE3, CODEX3]) {
17298
17669
  if (await harnessTrimSkillsConfigured(context, harness, capabilities))
17299
17670
  configured.add(harness);
17300
17671
  }
@@ -17338,6 +17709,28 @@ async function plan(context, request) {
17338
17709
  mode: null
17339
17710
  }
17340
17711
  })));
17712
+ for (const owned of request.ownership) {
17713
+ if (owned.owner !== HARNESSTRIM2 || owned.scope.capability !== "shell.output.reduce" || owned.scope.interceptionPoint !== "post-tool-use" || owned.scope.harness !== CLAUDE3 && owned.scope.harness !== CODEX3) {
17714
+ continue;
17715
+ }
17716
+ const harness = request.harnesses.find((entry) => entry.id === owned.scope.harness);
17717
+ if (harness === void 0)
17718
+ continue;
17719
+ const target = commandHookTarget(context, harness, owned.scope.interceptionPoint, owned.scope.toolFamily);
17720
+ if (target === null)
17721
+ continue;
17722
+ const existing = context.harnessConfigs.filter((config) => config.harnessId === harness.id && config.configPath === target.configPath && config.interceptionPoints.includes(target.scopeId)).flatMap((config) => config.hookCommands ?? []).find((entry) => entry.eventName === target.eventName && entry.matcher === target.matcher && isHarnessTrimHookFor(entry.command, harness.id));
17723
+ if (existing === void 0)
17724
+ continue;
17725
+ const actionKey = digestText(target.configPath).slice(7, 15);
17726
+ actions2.push(removeCommandHookAction({
17727
+ target,
17728
+ providerId: HARNESSTRIM2,
17729
+ actionId: `harnesstrim-${harness.id}-hook-remove-${actionKey}`,
17730
+ installActionId: `harnesstrim-${harness.id}-hook-${actionKey}`,
17731
+ command: existing.command
17732
+ }));
17733
+ }
17341
17734
  return {
17342
17735
  providerId: HARNESSTRIM2,
17343
17736
  desiredState: "absent",
@@ -17354,6 +17747,7 @@ async function plan(context, request) {
17354
17747
  };
17355
17748
  }
17356
17749
  const actions = [];
17750
+ const diagnostics = [];
17357
17751
  const plannedHarnesses = [];
17358
17752
  for (const harness of targets) {
17359
17753
  const review = reviews[harness];
@@ -17401,24 +17795,132 @@ async function plan(context, request) {
17401
17795
  });
17402
17796
  plannedHarnesses.push(harnessId(harness));
17403
17797
  }
17798
+ for (const owned of request.ownership) {
17799
+ if (owned.owner !== HARNESSTRIM2 || owned.scope.capability !== "shell.output.reduce" || owned.scope.interceptionPoint !== "post-tool-use" || owned.scope.harness !== CLAUDE3 && owned.scope.harness !== CODEX3) {
17800
+ continue;
17801
+ }
17802
+ const harness = request.harnesses.find((entry) => entry.id === owned.scope.harness);
17803
+ if (harness === void 0)
17804
+ continue;
17805
+ const target = commandHookTarget(context, harness, owned.scope.interceptionPoint, owned.scope.toolFamily);
17806
+ if (target === null)
17807
+ continue;
17808
+ const metricsPath = ".harnesstrim/metrics.jsonl";
17809
+ const command = `harnesstrim hook ${harness.id} --metrics ${metricsPath}`;
17810
+ 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));
17811
+ const correctlyMonitored = existing.some((entry) => commandHasMetricsPath(entry.command, metricsPath));
17812
+ if (correctlyMonitored) {
17813
+ plannedHarnesses.push(harness.id);
17814
+ continue;
17815
+ }
17816
+ const upgradable = existing.find((entry) => !hasMetricsArgument(entry.command));
17817
+ if (upgradable !== void 0) {
17818
+ const upgraded = `${upgradable.command.trim()} --metrics ${metricsPath}`;
17819
+ actions.push(replaceHookCommandAction({
17820
+ target,
17821
+ commandPointer: upgradable.commandPointer,
17822
+ currentCommand: upgradable.command,
17823
+ nextCommand: upgraded,
17824
+ actionId: `harnesstrim-${harness.id}-metrics-${digestText(target.configPath).slice(7, 15)}`
17825
+ }));
17826
+ plannedHarnesses.push(harness.id);
17827
+ continue;
17828
+ }
17829
+ if (existing.length > 0) {
17830
+ diagnostics.push(diagnostic({
17831
+ severity: "warning",
17832
+ code: "harnesstrim-metrics-path-needs-review",
17833
+ subject: harness.id,
17834
+ message: `An existing HarnessTrim hook on ${harness.displayName} uses a different telemetry path or custom command and was left unchanged`,
17835
+ path: target.configPath,
17836
+ remediation: `Set its --metrics path to ${metricsPath}, or review the command before changing it`
17837
+ }));
17838
+ continue;
17839
+ }
17840
+ const actionId2 = `harnesstrim-${harness.id}-hook-${digestText(target.configPath).slice(7, 15)}`;
17841
+ actions.push(appendCommandHookAction({
17842
+ target,
17843
+ providerId: HARNESSTRIM2,
17844
+ actionId: actionId2,
17845
+ command,
17846
+ explanation: `Register HarnessTrim after ${harness.displayName} Bash commands and record reductions in ${metricsPath}${codexActivationNote(harness.id)}`
17847
+ }));
17848
+ plannedHarnesses.push(harness.id);
17849
+ }
17404
17850
  return {
17405
17851
  providerId: HARNESSTRIM2,
17406
17852
  desiredState: "configured",
17407
17853
  actions,
17408
- targetHarnesses: plannedHarnesses
17854
+ diagnostics,
17855
+ targetHarnesses: [...new Set(plannedHarnesses)]
17856
+ };
17857
+ }
17858
+ function isHarnessTrimHookFor(command, harness) {
17859
+ const match = HARNESSTRIM_HOOK_COMMAND.exec(command.trim());
17860
+ return match?.[1]?.toLowerCase() === harness;
17861
+ }
17862
+ function hasMetricsArgument(command) {
17863
+ return /(?:^|\s)--metrics(?:\s|=)/i.test(command);
17864
+ }
17865
+ function commandHasMetricsPath(command, metricsPath) {
17866
+ const match = /(?:^|\s)--metrics(?:=|\s+)(?:"([^"]+)"|'([^']+)'|([^\s]+))/i.exec(command);
17867
+ const observed = match?.[1] ?? match?.[2] ?? match?.[3];
17868
+ return observed?.replaceAll("\\", "/") === metricsPath;
17869
+ }
17870
+ function matcherCoversFamily2(matcher, family) {
17871
+ if (matcher === family)
17872
+ return true;
17873
+ try {
17874
+ return new RegExp(matcher).test(family);
17875
+ } catch {
17876
+ return false;
17877
+ }
17878
+ }
17879
+ function replaceHookCommandAction(input) {
17880
+ return {
17881
+ kind: "merge-json",
17882
+ id: input.actionId,
17883
+ riskClass: "reversible",
17884
+ requiresNetwork: false,
17885
+ requiresElevation: false,
17886
+ affectedPaths: [input.target.configPath],
17887
+ affectedProcesses: [],
17888
+ preconditions: [
17889
+ `${input.commandPointer} still contains the HarnessTrim command Token Harness inspected`
17890
+ ],
17891
+ postconditions: [
17892
+ `${input.commandPointer} records HarnessTrim reductions to .harnesstrim/metrics.jsonl`
17893
+ ],
17894
+ rollbackData: "file-snapshot",
17895
+ explanation: `Enable per-harness HarnessTrim telemetry for ${input.target.harness.displayName}${codexActivationNote(input.target.harnessId)}`,
17896
+ path: input.target.configPath,
17897
+ ownedPointers: [input.commandPointer],
17898
+ operations: [
17899
+ {
17900
+ kind: "set",
17901
+ pointer: input.commandPointer,
17902
+ value: input.nextCommand,
17903
+ expectedValueDigest: jsonValueDigest(input.currentCommand)
17904
+ }
17905
+ ],
17906
+ createIfMissing: false
17409
17907
  };
17410
17908
  }
17411
- var HARNESSTRIM2, CLAUDE2, HERMES2, CODEX2, PI2, SKILLS_UPSTREAM, RUNTIME_SKILL_DIGESTS_MINIMUM, SKILL_ARTIFACT_DIGESTS, SKILL_ARTIFACTS, OPENCODE2, MODE_CARRYING_HARNESSES, HOOK_COMMAND_PATTERN, PLUGIN_MODULE_PATTERN2, PI_EXTENSION_PATTERN, MANIFEST6, SKILLS_INSTALL, TESTED_UPSTREAM, TESTED_VERSIONS, SURFACE_ANCHORS, VERSION_PATTERN6, harnesstrimAdapter;
17909
+ function codexActivationNote(harness) {
17910
+ return harness === CODEX3 ? ". Codex must enable and trust this hook in its native UI; Token Harness can register it but cannot grant trust" : "";
17911
+ }
17912
+ var HARNESSTRIM2, CLAUDE3, HERMES2, CODEX3, PI2, SKILLS_UPSTREAM, RUNTIME_SKILL_DIGESTS_MINIMUM, SKILL_ARTIFACT_DIGESTS, SKILL_ARTIFACTS, OPENCODE2, MODE_CARRYING_HARNESSES, HOOK_COMMAND_PATTERN, PLUGIN_MODULE_PATTERN2, PI_EXTENSION_PATTERN, MANIFEST6, SKILLS_INSTALL, TESTED_UPSTREAM, TESTED_VERSIONS, SURFACE_ANCHORS, VERSION_PATTERN6, HARNESSTRIM_HOOK_COMMAND, harnesstrimAdapter;
17412
17913
  var init_harnesstrim = __esm({
17413
17914
  "packages/adapters/dist/src/providers/harnesstrim.js"() {
17414
17915
  "use strict";
17415
17916
  init_src();
17917
+ init_hook_plan();
17416
17918
  HARNESSTRIM2 = providerId("harnesstrim");
17417
- CLAUDE2 = harnessId("claude");
17919
+ CLAUDE3 = harnessId("claude");
17418
17920
  HERMES2 = harnessId("hermes");
17419
- CODEX2 = harnessId("codex");
17921
+ CODEX3 = harnessId("codex");
17420
17922
  PI2 = harnessId("pi");
17421
- SKILLS_UPSTREAM = "0.0.7";
17923
+ SKILLS_UPSTREAM = "0.3.1";
17422
17924
  RUNTIME_SKILL_DIGESTS_MINIMUM = "0.2.0";
17423
17925
  SKILL_ARTIFACT_DIGESTS = {
17424
17926
  "compact-handoff/SKILL.md": "sha256:0efbf35581c559359e755b204778b64a289dab4d20dadc1cba3d5b5c995b5f01",
@@ -17452,7 +17954,7 @@ var init_harnesstrim = __esm({
17452
17954
  {
17453
17955
  capability: "shell.output.reduce",
17454
17956
  mode: "exclusive",
17455
- harnesses: [CLAUDE2, CODEX2],
17957
+ harnesses: [CLAUDE3, CODEX3],
17456
17958
  // `HOOK_MATCHER = "Bash"` and `CODEX_HOOK_MATCHER = "^Bash$"`, per RFC 0003 §The table is an
17457
17959
  // intent. One surface each, and no selector narrows it.
17458
17960
  surfaces: [{ toolFamily: "Bash", interceptionPoint: "post-tool-use" }],
@@ -17482,14 +17984,14 @@ var init_harnesstrim = __esm({
17482
17984
  ],
17483
17985
  harnesses: [
17484
17986
  {
17485
- harness: CLAUDE2,
17486
- testedVersions: { minimum: "2.0.0", maximum: "2.1.212" },
17487
- verificationTier: "config-only"
17987
+ harness: CLAUDE3,
17988
+ testedVersions: { minimum: "2.1.274", maximum: "2.1.274" },
17989
+ verificationTier: "canary"
17488
17990
  },
17489
17991
  {
17490
- harness: CODEX2,
17491
- testedVersions: { minimum: "0.146.0", maximum: "0.146.0" },
17492
- verificationTier: "config-only"
17992
+ harness: CODEX3,
17993
+ testedVersions: { minimum: "0.159.0", maximum: "0.159.0" },
17994
+ verificationTier: "canary"
17493
17995
  },
17494
17996
  {
17495
17997
  harness: OPENCODE2,
@@ -17531,11 +18033,9 @@ var init_harnesstrim = __esm({
17531
18033
  /**
17532
18034
  * One review per harness — PLAN §15 item 46b.
17533
18035
  *
17534
- * Codex was observed at `0.1.0`: `harnesstrim install codex <dir> --apply --no-instructions`
17535
- * writes the same seven skill artifacts as the Claude invocation, byte for byte — the digests
17536
- * below are shared because the files are the same files — under `.codex/skills/` instead, and
17537
- * skips `AGENTS.md` exactly as the Claude one skips `CLAUDE.md`. What differs is the boundary and
17538
- * the protected paths, which is precisely why one review could not describe both.
18036
+ * HarnessTrim 0.3.1 declares the same seven skill artifacts on Claude and Codex, byte for byte.
18037
+ * The delegated invocation omits runtime hooks and instructions; Token Harness adds the
18038
+ * versioned PostToolUse hook through the harness adapter and owns that exact JSON entry.
17539
18039
  *
17540
18040
  * OpenCode is absent on purpose. Its installer writes `.opencode/plugin/harnesstrim.ts` and
17541
18041
  * `.opencode/package.json` *and runs an npm install*, so the containment boundary would hold a
@@ -17570,13 +18070,14 @@ var init_harnesstrim = __esm({
17570
18070
  args: ["--no-instructions"]
17571
18071
  }
17572
18072
  };
17573
- TESTED_UPSTREAM = "0.2.1";
18073
+ TESTED_UPSTREAM = "0.3.1";
17574
18074
  TESTED_VERSIONS = { minimum: "0.0.5", maximum: TESTED_UPSTREAM };
17575
18075
  SURFACE_ANCHORS = {
17576
18076
  "post-tool-use": "PostToolUse",
17577
18077
  "tool-execute-after": "tool.execute.after"
17578
18078
  };
17579
18079
  VERSION_PATTERN6 = /(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?)/;
18080
+ HARNESSTRIM_HOOK_COMMAND = /^(?:"?[^"\n]*[\\/]?harnesstrim(?:\.cmd|\.exe)?"?|harnesstrim(?:\.cmd|\.exe)?)\s+hook\s+(claude|codex)(?:\s+(.*))?$/i;
17580
18081
  harnesstrimAdapter = {
17581
18082
  manifest: MANIFEST6,
17582
18083
  detect: detect6,
@@ -17590,7 +18091,7 @@ var init_harnesstrim = __esm({
17590
18091
  });
17591
18092
 
17592
18093
  // packages/adapters/dist/src/providers/rtk-plan.js
17593
- function hookListPointer(eventName) {
18094
+ function hookListPointer2(eventName) {
17594
18095
  return `hooks.${eventName.replace(/\./g, "\\.")}`;
17595
18096
  }
17596
18097
  function hookEntryFor(harnessId2, matcher, restoreNativeHookOnUninstall = false) {
@@ -17607,7 +18108,7 @@ function hookEntryFor(harnessId2, matcher, restoreNativeHookOnUninstall = false)
17607
18108
  function hookActivationNote(target) {
17608
18109
  return target.harness.id === "codex" ? ". After applying, manually enable and trust this hook in Codex; Token Harness writes hooks.json but cannot activate the hook or grant trust" : "";
17609
18110
  }
17610
- function matcherCoversFamily2(matcher, family) {
18111
+ function matcherCoversFamily3(matcher, family) {
17611
18112
  if (matcher === family)
17612
18113
  return true;
17613
18114
  try {
@@ -17637,12 +18138,13 @@ function planTargets(context, request) {
17637
18138
  scope: owned.scope,
17638
18139
  harness,
17639
18140
  eventName: point.eventName,
18141
+ matcher: hookMatcherForFamily(harness, owned.scope.toolFamily),
17640
18142
  configPath
17641
18143
  });
17642
18144
  }
17643
18145
  if (context.facts.os === "windows") {
17644
18146
  for (const target of [...targets.values()]) {
17645
- if (target.harness.id !== CLAUDE3 || target.scope.toolFamily !== BASH)
18147
+ if (target.harness.id !== CLAUDE4 || target.scope.toolFamily !== BASH)
17646
18148
  continue;
17647
18149
  if (!target.harness.toolFamilies.some((family) => family.id === POWERSHELL))
17648
18150
  continue;
@@ -17651,14 +18153,15 @@ function planTargets(context, request) {
17651
18153
  continue;
17652
18154
  targets.set(key, {
17653
18155
  ...target,
17654
- scope: { ...target.scope, toolFamily: POWERSHELL }
18156
+ scope: { ...target.scope, toolFamily: POWERSHELL },
18157
+ matcher: hookMatcherForFamily(target.harness, POWERSHELL)
17655
18158
  });
17656
18159
  }
17657
18160
  }
17658
18161
  return [...targets.values()];
17659
18162
  }
17660
18163
  function alreadyRegistered(context, target, allowRegexCoverage) {
17661
- return context.harnessConfigs.some((config) => config.harnessId === target.harness.id && config.configPath === target.configPath && config.interceptionPoints.includes(target.scope.interceptionPoint) && config.matchers.some((matcher) => allowRegexCoverage ? matcherCoversFamily2(matcher, target.scope.toolFamily) : matcher === target.scope.toolFamily) && (config.hookCommands ?? []).some((entry) => entry.eventName === target.eventName && entry.matcher !== null && (allowRegexCoverage ? matcherCoversFamily2(entry.matcher, target.scope.toolFamily) : entry.matcher === target.scope.toolFamily) && isRtkAttributionCommand(entry.command, target.harness.id)));
18164
+ return context.harnessConfigs.some((config) => config.harnessId === target.harness.id && config.configPath === target.configPath && config.interceptionPoints.includes(target.scope.interceptionPoint) && config.matchers.some((matcher) => allowRegexCoverage ? matcherCoversFamily3(matcher, target.scope.toolFamily) : matcher === target.scope.toolFamily) && (config.hookCommands ?? []).some((entry) => entry.eventName === target.eventName && entry.matcher !== null && (allowRegexCoverage ? matcherCoversFamily3(entry.matcher, target.scope.toolFamily) : entry.matcher === target.matcher) && isRtkAttributionCommand(entry.command, target.harness.id)));
17662
18165
  }
17663
18166
  function isRtkAttributionCommand(command, harness) {
17664
18167
  return new RegExp(`^token-harness __internal-rtk-hook ${harness}(?: --restore-rtk)?$`, "i").test(command.trim());
@@ -17671,7 +18174,7 @@ function deterministicId(parts) {
17671
18174
  return digest.slice(digest.indexOf(":") + 1, digest.indexOf(":") + 9);
17672
18175
  }
17673
18176
  function hookAction(target, entry) {
17674
- const pointer = hookListPointer(target.eventName);
18177
+ const pointer = hookListPointer2(target.eventName);
17675
18178
  return {
17676
18179
  kind: "merge-json",
17677
18180
  id: deterministicId([
@@ -17773,7 +18276,7 @@ function restoreNativeHookAction(target, current) {
17773
18276
  };
17774
18277
  }
17775
18278
  function removalAction(target, entry) {
17776
- const pointer = hookListPointer(target.eventName);
18279
+ const pointer = hookListPointer2(target.eventName);
17777
18280
  const reverses = deterministicId([
17778
18281
  "rtk",
17779
18282
  "hook",
@@ -17857,13 +18360,13 @@ function buildRtkPlan(input) {
17857
18360
  const targetHarnesses = [...new Set(targets.map((target) => target.harness.id))];
17858
18361
  if (request.desiredState === "absent") {
17859
18362
  for (const target of targets) {
17860
- const existing = context.harnessConfigs.flatMap((config) => config.hookCommands ?? []).find((entry) => entry.eventName === target.eventName && entry.matcher === target.scope.toolFamily && isRtkAttributionCommand(entry.command, target.harness.id));
18363
+ const existing = context.harnessConfigs.flatMap((config) => config.hookCommands ?? []).find((entry) => entry.eventName === target.eventName && entry.matcher === target.matcher && isRtkAttributionCommand(entry.command, target.harness.id));
17861
18364
  if (existing === void 0)
17862
18365
  continue;
17863
18366
  if (existing.command.endsWith(" --restore-rtk")) {
17864
18367
  actions.push(restoreNativeHookAction(target, existing));
17865
18368
  } else {
17866
- actions.push(removalAction(target, hookEntryFor(target.harness.id, target.scope.toolFamily)));
18369
+ actions.push(removalAction(target, hookEntryFor(target.harness.id, target.matcher)));
17867
18370
  }
17868
18371
  }
17869
18372
  return {
@@ -17899,7 +18402,7 @@ function buildRtkPlan(input) {
17899
18402
  for (const target of targets) {
17900
18403
  if (alreadyRegistered(context, target, true))
17901
18404
  continue;
17902
- const matchingEntries = context.harnessConfigs.filter((config) => config.harnessId === target.harness.id && config.configPath === target.configPath && config.interceptionPoints.includes(target.scope.interceptionPoint)).flatMap((config) => config.hookCommands ?? []).filter((entry) => entry.eventName === target.eventName && entry.matcher !== null && matcherCoversFamily2(entry.matcher, target.scope.toolFamily) && input.identifiesCommand(entry.command));
18405
+ const matchingEntries = context.harnessConfigs.filter((config) => config.harnessId === target.harness.id && config.configPath === target.configPath && config.interceptionPoints.includes(target.scope.interceptionPoint)).flatMap((config) => config.hookCommands ?? []).filter((entry) => entry.eventName === target.eventName && entry.matcher !== null && matcherCoversFamily3(entry.matcher, target.scope.toolFamily) && input.identifiesCommand(entry.command));
17903
18406
  const native = matchingEntries.find((entry) => isCanonicalNativeHook(entry.command, target.harness.id));
17904
18407
  if (native !== void 0) {
17905
18408
  if (!migratedPointers.has(native.commandPointer)) {
@@ -17931,7 +18434,7 @@ function buildRtkPlan(input) {
17931
18434
  }));
17932
18435
  continue;
17933
18436
  }
17934
- actions.push(hookAction(target, hookEntryFor(target.harness.id, target.scope.toolFamily)));
18437
+ actions.push(hookAction(target, hookEntryFor(target.harness.id, target.matcher)));
17935
18438
  }
17936
18439
  return {
17937
18440
  providerId: "rtk",
@@ -17941,14 +18444,15 @@ function buildRtkPlan(input) {
17941
18444
  targetHarnesses: actions.length === 0 ? [] : targetHarnesses
17942
18445
  };
17943
18446
  }
17944
- var RTK_HOOK_PROXY_COMMAND, RTK_NATIVE_HOOK_PREFIX, CLAUDE3, BASH, POWERSHELL;
18447
+ var RTK_HOOK_PROXY_COMMAND, RTK_NATIVE_HOOK_PREFIX, CLAUDE4, BASH, POWERSHELL;
17945
18448
  var init_rtk_plan = __esm({
17946
18449
  "packages/adapters/dist/src/providers/rtk-plan.js"() {
17947
18450
  "use strict";
17948
18451
  init_src();
18452
+ init_hook_plan();
17949
18453
  RTK_HOOK_PROXY_COMMAND = "token-harness __internal-rtk-hook";
17950
18454
  RTK_NATIVE_HOOK_PREFIX = "rtk hook";
17951
- CLAUDE3 = "claude";
18455
+ CLAUDE4 = "claude";
17952
18456
  BASH = "Bash";
17953
18457
  POWERSHELL = "PowerShell";
17954
18458
  }
@@ -18051,12 +18555,12 @@ async function detect7(context) {
18051
18555
  }));
18052
18556
  }
18053
18557
  const codexHookSupported = version3.version === RTK_CODEX_HOOK_VERSION;
18054
- const codexConfiguredWithoutHookSupport = configured.includes(CODEX3) && !codexHookSupported;
18558
+ const codexConfiguredWithoutHookSupport = configured.includes(CODEX4) && !codexHookSupported;
18055
18559
  if (codexConfiguredWithoutHookSupport) {
18056
18560
  warnings.push(diagnostic({
18057
18561
  severity: "error",
18058
18562
  code: "rtk-codex-hook-unsupported",
18059
- subject: CODEX3,
18563
+ subject: CODEX4,
18060
18564
  message: `RTK ${String(version3.version)} does not provide the Codex hook; its configuration entry cannot capture commands`,
18061
18565
  remediation: `Upgrade RTK to ${RTK_CODEX_HOOK_VERSION}, then refresh and apply the attribution plan`
18062
18566
  }));
@@ -18106,7 +18610,7 @@ async function detect7(context) {
18106
18610
  * its integration is a plugin module installed by `rtk init -g --opencode`, which this build
18107
18611
  * deliberately does not delegate without a reviewed write set.
18108
18612
  */
18109
- assignableHarnesses: version3.version === null || codexHookSupported ? [CLAUDE4, CODEX3] : [CLAUDE4],
18613
+ assignableHarnesses: version3.version === null || codexHookSupported ? [CLAUDE5, CODEX4] : [CLAUDE5],
18110
18614
  evidence: evidenceItems,
18111
18615
  warnings
18112
18616
  };
@@ -18124,7 +18628,7 @@ async function verify7(context) {
18124
18628
  remediation: version3.version === null ? "Install RTK, or add it to PATH" : null
18125
18629
  });
18126
18630
  const configured = harnessesWiredToRtk(context.harnessConfigs);
18127
- const configuredSupported = configured.filter((harness) => harness === CLAUDE4 || harness === CODEX3 && version3.version === RTK_CODEX_HOOK_VERSION);
18631
+ const configuredSupported = configured.filter((harness) => harness === CLAUDE5 || harness === CODEX4 && version3.version === RTK_CODEX_HOOK_VERSION);
18128
18632
  checks.push({
18129
18633
  id: "hook-registered",
18130
18634
  status: configuredSupported.length > 0 ? "pass" : configured.length > 0 ? "fail" : "not-exercised",
@@ -18138,8 +18642,8 @@ async function verify7(context) {
18138
18642
  for (const harness of TRACKED_HARNESSES) {
18139
18643
  if (!configured.includes(harness))
18140
18644
  continue;
18141
- const label = harness === CLAUDE4 ? "Claude Code" : "Codex";
18142
- const supported = harness !== CODEX3 || version3.version === RTK_CODEX_HOOK_VERSION;
18645
+ const label = harness === CLAUDE5 ? "Claude Code" : "Codex";
18646
+ const supported = harness !== CODEX4 || version3.version === RTK_CODEX_HOOK_VERSION;
18143
18647
  if (!supported) {
18144
18648
  checks.push({
18145
18649
  id: `rtk-attribution-${harness}`,
@@ -18566,17 +19070,17 @@ async function plan2(context, request) {
18566
19070
  hookProxyAvailable
18567
19071
  });
18568
19072
  }
18569
- var RTK2, CLAUDE4, CODEX3, OPENCODE3, TRACKED_HARNESSES, RTK_CODEX_HOOK_VERSION, MANIFEST7, TESTED_VERSIONS2, VERSION_PATTERN7, HOOK_COMMAND_PATTERN2, PLUGIN_MODULE_PATTERN3, HARNESS_ACTIVITY_QUERY, STALE_RECEIPT_DAYS, HISTORY_QUERY, GENERATION_QUERY, IMPORT_BATCH_SIZE, SOURCE_LABEL, rtkAdapter;
19073
+ var RTK2, CLAUDE5, CODEX4, OPENCODE3, TRACKED_HARNESSES, RTK_CODEX_HOOK_VERSION, MANIFEST7, TESTED_VERSIONS2, VERSION_PATTERN7, HOOK_COMMAND_PATTERN2, PLUGIN_MODULE_PATTERN3, HARNESS_ACTIVITY_QUERY, STALE_RECEIPT_DAYS, HISTORY_QUERY, GENERATION_QUERY, IMPORT_BATCH_SIZE, SOURCE_LABEL, rtkAdapter;
18570
19074
  var init_rtk = __esm({
18571
19075
  "packages/adapters/dist/src/providers/rtk.js"() {
18572
19076
  "use strict";
18573
19077
  init_src();
18574
19078
  init_rtk_plan();
18575
19079
  RTK2 = providerId("rtk");
18576
- CLAUDE4 = harnessId("claude");
18577
- CODEX3 = harnessId("codex");
19080
+ CLAUDE5 = harnessId("claude");
19081
+ CODEX4 = harnessId("codex");
18578
19082
  OPENCODE3 = harnessId("opencode");
18579
- TRACKED_HARNESSES = [CLAUDE4, CODEX3];
19083
+ TRACKED_HARNESSES = [CLAUDE5, CODEX4];
18580
19084
  RTK_CODEX_HOOK_VERSION = "0.50.0";
18581
19085
  MANIFEST7 = {
18582
19086
  schemaVersion: MANIFEST_SCHEMA_VERSION,
@@ -18590,7 +19094,7 @@ var init_rtk = __esm({
18590
19094
  {
18591
19095
  capability: "shell.command.rewrite",
18592
19096
  mode: "exclusive",
18593
- harnesses: [CLAUDE4],
19097
+ harnesses: [CLAUDE5],
18594
19098
  // The portable resolver surface remains Bash. Windows PowerShell coverage is added by
18595
19099
  // the planner only on Windows, because ProviderManifest capabilities are not platform-scoped.
18596
19100
  // The native processor and that Windows-only plan path are covered by the live fixture below.
@@ -18603,7 +19107,7 @@ var init_rtk = __esm({
18603
19107
  {
18604
19108
  capability: "shell.output.reduce",
18605
19109
  mode: "exclusive",
18606
- harnesses: [CLAUDE4],
19110
+ harnesses: [CLAUDE5],
18607
19111
  // Same portable Bash surface. On Windows the planner adds PowerShell as a platform-only
18608
19112
  // companion matcher; the live fixture below proves the same native processor handles both.
18609
19113
  surfaces: [{ toolFamily: "Bash", interceptionPoint: "pre-tool-use" }],
@@ -18622,7 +19126,7 @@ var init_rtk = __esm({
18622
19126
  {
18623
19127
  capability: "shell.command.rewrite",
18624
19128
  mode: "exclusive",
18625
- harnesses: [CODEX3],
19129
+ harnesses: [CODEX4],
18626
19130
  surfaces: [{ toolFamily: "Bash", interceptionPoint: "pre-tool-use" }],
18627
19131
  evidence: {
18628
19132
  sourceReference: "docs/spikes/rtk-codex-upstream-contract.md",
@@ -18632,7 +19136,7 @@ var init_rtk = __esm({
18632
19136
  {
18633
19137
  capability: "shell.output.reduce",
18634
19138
  mode: "exclusive",
18635
- harnesses: [CODEX3],
19139
+ harnesses: [CODEX4],
18636
19140
  surfaces: [{ toolFamily: "Bash", interceptionPoint: "pre-tool-use" }],
18637
19141
  evidence: {
18638
19142
  sourceReference: "docs/spikes/rtk-codex-upstream-contract.md",
@@ -18691,15 +19195,14 @@ var init_rtk = __esm({
18691
19195
  ],
18692
19196
  harnesses: [
18693
19197
  {
18694
- harness: CLAUDE4,
18695
- testedVersions: { minimum: "2.0.0", maximum: "2.1.251" },
19198
+ harness: CLAUDE5,
19199
+ testedVersions: { minimum: "2.1.274", maximum: "2.1.274" },
18696
19200
  verificationTier: "canary"
18697
19201
  },
18698
19202
  {
18699
- harness: CODEX3,
18700
- // RTK added its native Codex PreToolUse rewriter in 0.50.0. Earlier releases only wrote
18701
- // prompt instructions; a hooks.json entry alone did not activate it.
18702
- testedVersions: { minimum: "0.146.0", maximum: "0.146.0" },
19203
+ harness: CODEX4,
19204
+ // RTK 0.50.0's native hook was exercised against the installed Codex 0.159.0 schema.
19205
+ testedVersions: { minimum: "0.159.0", maximum: "0.159.0" },
18703
19206
  verificationTier: "canary"
18704
19207
  },
18705
19208
  {
@@ -20206,7 +20709,7 @@ async function mcptoonDetection(context) {
20206
20709
  const observation = await observeMcptoonManagedRuntime(context);
20207
20710
  const configuredHarnesses = [];
20208
20711
  if (observation.ready) {
20209
- for (const harness of [CLAUDE5, CODEX4]) {
20712
+ for (const harness of [CLAUDE6, CODEX5]) {
20210
20713
  const verification = await verifyMcptoonManagedActivation(context, harness);
20211
20714
  if (verification.state === "verified")
20212
20715
  configuredHarnesses.push(harness);
@@ -20239,7 +20742,7 @@ async function mcptoonDetection(context) {
20239
20742
  unmanagedHarnessesConfigured: [],
20240
20743
  supportsUnmanagedHarnesses: false,
20241
20744
  managedByTokenHarness: false,
20242
- assignableHarnesses: observation.ready || canInstall ? [CLAUDE5, CODEX4] : [],
20745
+ assignableHarnesses: observation.ready || canInstall ? [CLAUDE6, CODEX5] : [],
20243
20746
  evidence: [],
20244
20747
  warnings
20245
20748
  };
@@ -20248,7 +20751,7 @@ async function gitnexusDetection(context) {
20248
20751
  const observation = await observeGitNexusManagedRuntime(context);
20249
20752
  const configuredHarnesses = [];
20250
20753
  if (observation.ready) {
20251
- for (const harness of [CLAUDE5, CODEX4]) {
20754
+ for (const harness of [CLAUDE6, CODEX5]) {
20252
20755
  const verification = await verifyGitNexusManagedMcpActivation(context, harness);
20253
20756
  if (verification.state === "verified")
20254
20757
  configuredHarnesses.push(harness);
@@ -20281,7 +20784,7 @@ async function gitnexusDetection(context) {
20281
20784
  unmanagedHarnessesConfigured: [],
20282
20785
  supportsUnmanagedHarnesses: false,
20283
20786
  managedByTokenHarness: false,
20284
- assignableHarnesses: observation.ready || canInstall ? [CLAUDE5, CODEX4] : [],
20787
+ assignableHarnesses: observation.ready || canInstall ? [CLAUDE6, CODEX5] : [],
20285
20788
  evidence: [],
20286
20789
  warnings
20287
20790
  };
@@ -20289,7 +20792,7 @@ async function gitnexusDetection(context) {
20289
20792
  async function mcptoonVerify(context) {
20290
20793
  const checks = [];
20291
20794
  let achieved = null;
20292
- for (const harness of [CLAUDE5, CODEX4]) {
20795
+ for (const harness of [CLAUDE6, CODEX5]) {
20293
20796
  const result6 = await verifyMcptoonManagedActivation(context, harness);
20294
20797
  if (result6.state === "verified")
20295
20798
  achieved = "config-only";
@@ -20316,7 +20819,7 @@ async function mcptoonVerify(context) {
20316
20819
  async function gitnexusVerify(context) {
20317
20820
  const checks = [];
20318
20821
  let achieved = null;
20319
- for (const harness of [CLAUDE5, CODEX4]) {
20822
+ for (const harness of [CLAUDE6, CODEX5]) {
20320
20823
  const result6 = await verifyGitNexusManagedMcpActivation(context, harness);
20321
20824
  if (result6.state === "verified")
20322
20825
  achieved = "config-only";
@@ -20355,7 +20858,7 @@ async function mcptoonPlan(context, request) {
20355
20858
  const actions = [];
20356
20859
  const targets = [];
20357
20860
  for (const harness of request.harnesses.map((item) => item.id)) {
20358
- if (harness !== CLAUDE5 && harness !== CODEX4)
20861
+ if (harness !== CLAUDE6 && harness !== CODEX5)
20359
20862
  continue;
20360
20863
  const plan6 = await planMcptoonManagedActivation(context, harness);
20361
20864
  if (plan6.actions.length === 0)
@@ -20382,7 +20885,7 @@ async function gitnexusPlan(context, request) {
20382
20885
  const actions = [];
20383
20886
  const targets = [];
20384
20887
  for (const harness of request.harnesses.map((item) => item.id)) {
20385
- if (harness !== CLAUDE5 && harness !== CODEX4)
20888
+ if (harness !== CLAUDE6 && harness !== CODEX5)
20386
20889
  continue;
20387
20890
  const plan6 = await planGitNexusManagedMcpActivation(context, harness);
20388
20891
  if (plan6.actions.length === 0)
@@ -20397,7 +20900,7 @@ async function gitnexusPlan(context, request) {
20397
20900
  targetHarnesses: [...new Set(targets)]
20398
20901
  };
20399
20902
  }
20400
- var MCPTOON, GITNEXUS, HEADROOM, CLAUDE5, CODEX4, MCPTOON_MANIFEST, GITNEXUS_MANIFEST, HEADROOM_MANIFEST, mcptoonAdapter, gitnexusAdapter;
20903
+ var MCPTOON, GITNEXUS, HEADROOM, CLAUDE6, CODEX5, MCPTOON_MANIFEST, GITNEXUS_MANIFEST, HEADROOM_MANIFEST, mcptoonAdapter, gitnexusAdapter;
20401
20904
  var init_managed_optimization_tools = __esm({
20402
20905
  "packages/adapters/dist/src/providers/managed-optimization-tools.js"() {
20403
20906
  "use strict";
@@ -20410,8 +20913,8 @@ var init_managed_optimization_tools = __esm({
20410
20913
  MCPTOON = providerId("mcptoon");
20411
20914
  GITNEXUS = providerId("gitnexus");
20412
20915
  HEADROOM = providerId("headroom");
20413
- CLAUDE5 = harnessId("claude");
20414
- CODEX4 = harnessId("codex");
20916
+ CLAUDE6 = harnessId("claude");
20917
+ CODEX5 = harnessId("codex");
20415
20918
  MCPTOON_MANIFEST = {
20416
20919
  schemaVersion: MANIFEST_SCHEMA_VERSION,
20417
20920
  id: MCPTOON,
@@ -20424,12 +20927,12 @@ var init_managed_optimization_tools = __esm({
20424
20927
  platforms: platforms(),
20425
20928
  harnesses: [
20426
20929
  {
20427
- harness: CLAUDE5,
20930
+ harness: CLAUDE6,
20428
20931
  testedVersions: { minimum: "2.1.269", maximum: "2.1.269" },
20429
20932
  verificationTier: "config-only"
20430
20933
  },
20431
20934
  {
20432
- harness: CODEX4,
20935
+ harness: CODEX5,
20433
20936
  testedVersions: { minimum: "0.152.1", maximum: "0.153.0" },
20434
20937
  verificationTier: "config-only"
20435
20938
  }
@@ -20463,12 +20966,12 @@ var init_managed_optimization_tools = __esm({
20463
20966
  platforms: platforms(),
20464
20967
  harnesses: [
20465
20968
  {
20466
- harness: CLAUDE5,
20969
+ harness: CLAUDE6,
20467
20970
  testedVersions: { minimum: "2.1.269", maximum: "2.1.269" },
20468
20971
  verificationTier: "config-only"
20469
20972
  },
20470
20973
  {
20471
- harness: CODEX4,
20974
+ harness: CODEX5,
20472
20975
  testedVersions: { minimum: "0.153.0", maximum: "0.153.0" },
20473
20976
  verificationTier: "config-only"
20474
20977
  }
@@ -20542,7 +21045,7 @@ async function plan3(context, request) {
20542
21045
  const actions = [];
20543
21046
  const targets = [];
20544
21047
  for (const harness of request.harnesses.map((item) => item.id)) {
20545
- if (harness !== CLAUDE6 && harness !== CODEX5)
21048
+ if (harness !== CLAUDE7 && harness !== CODEX6)
20546
21049
  continue;
20547
21050
  const target = gitnexusOwnedArtifact(context, harness);
20548
21051
  if (target === null)
@@ -20559,15 +21062,15 @@ async function plan3(context, request) {
20559
21062
  targetHarnesses: [...new Set(targets)]
20560
21063
  };
20561
21064
  }
20562
- var CLAUDE6, CODEX5, gitnexusManagedProviderAdapter;
21065
+ var CLAUDE7, CODEX6, gitnexusManagedProviderAdapter;
20563
21066
  var init_gitnexus_provider = __esm({
20564
21067
  "packages/adapters/dist/src/providers/gitnexus-provider.js"() {
20565
21068
  "use strict";
20566
21069
  init_src();
20567
21070
  init_managed_optimization_tools();
20568
21071
  init_gitnexus_managed();
20569
- CLAUDE6 = harnessId("claude");
20570
- CODEX5 = harnessId("codex");
21072
+ CLAUDE7 = harnessId("claude");
21073
+ CODEX6 = harnessId("codex");
20571
21074
  gitnexusManagedProviderAdapter = {
20572
21075
  ...gitnexusAdapter,
20573
21076
  plan: plan3
@@ -21085,7 +21588,7 @@ async function detect8(context) {
21085
21588
  const runtime = await headroomManagedMcpRuntime(context);
21086
21589
  const configuredHarnesses = [];
21087
21590
  if (runtime.ok) {
21088
- for (const harness of [CLAUDE7, CODEX6]) {
21591
+ for (const harness of [CLAUDE8, CODEX7]) {
21089
21592
  const verification = await verifyHeadroomManagedMcpActivation(context, harness);
21090
21593
  if (verification.state === "verified")
21091
21594
  configuredHarnesses.push(harness);
@@ -21124,7 +21627,7 @@ async function detect8(context) {
21124
21627
  unmanagedHarnessesConfigured: [],
21125
21628
  supportsUnmanagedHarnesses: false,
21126
21629
  managedByTokenHarness: false,
21127
- assignableHarnesses: runtime.ok || canInstall ? [CLAUDE7, CODEX6] : [],
21630
+ assignableHarnesses: runtime.ok || canInstall ? [CLAUDE8, CODEX7] : [],
21128
21631
  evidence: [],
21129
21632
  warnings
21130
21633
  };
@@ -21156,7 +21659,7 @@ function dedupe(actions) {
21156
21659
  }
21157
21660
  async function plan4(context, request) {
21158
21661
  if (request.desiredState === "absent") {
21159
- const targets = request.harnesses.map((item) => item.id).filter((id) => id === CLAUDE7 || id === CODEX6);
21662
+ const targets = request.harnesses.map((item) => item.id).filter((id) => id === CLAUDE8 || id === CODEX7);
21160
21663
  return {
21161
21664
  providerId: HEADROOM2,
21162
21665
  desiredState: "absent",
@@ -21167,7 +21670,7 @@ async function plan4(context, request) {
21167
21670
  const actions = [];
21168
21671
  const targetHarnesses = [];
21169
21672
  for (const harness of request.harnesses.map((item) => item.id)) {
21170
- if (harness !== CLAUDE7 && harness !== CODEX6)
21673
+ if (harness !== CLAUDE8 && harness !== CODEX7)
21171
21674
  continue;
21172
21675
  const activation = await planHeadroomManagedMcpActivation(context, harness);
21173
21676
  if (activation.actions.length === 0)
@@ -21185,7 +21688,7 @@ async function plan4(context, request) {
21185
21688
  async function verify8(context) {
21186
21689
  const checks = [];
21187
21690
  let achieved = null;
21188
- for (const harness of [CLAUDE7, CODEX6]) {
21691
+ for (const harness of [CLAUDE8, CODEX7]) {
21189
21692
  const result6 = await verifyHeadroomManagedMcpActivation(context, harness);
21190
21693
  if (result6.state === "verified")
21191
21694
  achieved = "config-only";
@@ -21220,7 +21723,7 @@ function unavailableMetrics2() {
21220
21723
  diagnostics: []
21221
21724
  };
21222
21725
  }
21223
- var HEADROOM2, CLAUDE7, CODEX6, HEADROOM_MANIFEST2, headroomManagedProviderAdapter;
21726
+ var HEADROOM2, CLAUDE8, CODEX7, HEADROOM_MANIFEST2, headroomManagedProviderAdapter;
21224
21727
  var init_headroom_provider = __esm({
21225
21728
  "packages/adapters/dist/src/providers/headroom-provider.js"() {
21226
21729
  "use strict";
@@ -21228,8 +21731,8 @@ var init_headroom_provider = __esm({
21228
21731
  init_headroom_candidate();
21229
21732
  init_headroom_managed();
21230
21733
  HEADROOM2 = providerId("headroom");
21231
- CLAUDE7 = harnessId("claude");
21232
- CODEX6 = harnessId("codex");
21734
+ CLAUDE8 = harnessId("claude");
21735
+ CODEX7 = harnessId("codex");
21233
21736
  HEADROOM_MANIFEST2 = {
21234
21737
  schemaVersion: MANIFEST_SCHEMA_VERSION,
21235
21738
  id: HEADROOM2,
@@ -21246,12 +21749,12 @@ var init_headroom_provider = __esm({
21246
21749
  ],
21247
21750
  harnesses: [
21248
21751
  {
21249
- harness: CLAUDE7,
21752
+ harness: CLAUDE8,
21250
21753
  testedVersions: { minimum: "2.1.269", maximum: "2.1.269" },
21251
21754
  verificationTier: "config-only"
21252
21755
  },
21253
21756
  {
21254
- harness: CODEX6,
21757
+ harness: CODEX7,
21255
21758
  testedVersions: { minimum: "0.153.0", maximum: "0.153.0" },
21256
21759
  verificationTier: "config-only"
21257
21760
  }
@@ -21285,7 +21788,7 @@ var init_headroom_provider = __esm({
21285
21788
 
21286
21789
  // packages/adapters/dist/src/providers/mcptoon-provider.js
21287
21790
  function removalAction3(context, harness) {
21288
- if (harness === CLAUDE8) {
21791
+ if (harness === CLAUDE9) {
21289
21792
  const path = context.fs.join(context.paths.home, ".claude", "skills", "mcptoon", "SKILL.md");
21290
21793
  const target = {
21291
21794
  kind: "owned-file",
@@ -21310,7 +21813,7 @@ function removalAction3(context, harness) {
21310
21813
  target
21311
21814
  };
21312
21815
  }
21313
- if (harness === CODEX7) {
21816
+ if (harness === CODEX8) {
21314
21817
  const path = context.fs.join(context.projectRoot, "AGENTS.md");
21315
21818
  const target = {
21316
21819
  kind: "owned-marker-block",
@@ -21349,18 +21852,18 @@ async function plan5(context, request) {
21349
21852
  providerId: mcptoonAdapter.manifest.id,
21350
21853
  desiredState: "absent",
21351
21854
  actions,
21352
- targetHarnesses: request.harnesses.map((item) => item.id).filter((id) => id === CLAUDE8 || id === CODEX7)
21855
+ targetHarnesses: request.harnesses.map((item) => item.id).filter((id) => id === CLAUDE9 || id === CODEX8)
21353
21856
  };
21354
21857
  }
21355
- var CLAUDE8, CODEX7, mcptoonManagedProviderAdapter;
21858
+ var CLAUDE9, CODEX8, mcptoonManagedProviderAdapter;
21356
21859
  var init_mcptoon_provider = __esm({
21357
21860
  "packages/adapters/dist/src/providers/mcptoon-provider.js"() {
21358
21861
  "use strict";
21359
21862
  init_src();
21360
21863
  init_managed_optimization_tools();
21361
21864
  init_mcptoon_managed();
21362
- CLAUDE8 = harnessId("claude");
21363
- CODEX7 = harnessId("codex");
21865
+ CLAUDE9 = harnessId("claude");
21866
+ CODEX8 = harnessId("codex");
21364
21867
  mcptoonManagedProviderAdapter = {
21365
21868
  ...mcptoonAdapter,
21366
21869
  plan: plan5
@@ -21489,7 +21992,19 @@ function parseHarnessTrimReceiptEnvelope(line) {
21489
21992
  if (schemaVersion === 1 && (typeof record6["eventId"] !== "string" || record6["eventId"].length === 0)) {
21490
21993
  return null;
21491
21994
  }
21492
- return { ts: record6["ts"], harness: record6["harness"] };
21995
+ return {
21996
+ ts: record6["ts"],
21997
+ harness: record6["harness"],
21998
+ beforeChars: record6["beforeChars"],
21999
+ afterChars: record6["afterChars"],
22000
+ changed: typeof record6["changed"] === "boolean" ? record6["changed"] : null,
22001
+ reductionFailed: record6["reductionFailed"] === true
22002
+ };
22003
+ }
22004
+ function provesHarnessTrimReduction(event) {
22005
+ return !event.reductionFailed && event.afterChars < event.beforeChars && // Native receipts explicitly mark pass-throughs. Legacy receipts predate this bit, so a
22006
+ // strictly smaller after-size remains the only available evidence that the hook reduced it.
22007
+ event.changed !== false;
21493
22008
  }
21494
22009
  async function harnessTrimReceiptFor(context, harnessId2) {
21495
22010
  for (const path of metricsLocations(context)) {
@@ -21498,9 +22013,15 @@ async function harnessTrimReceiptFor(context, harnessId2) {
21498
22013
  continue;
21499
22014
  const text3 = new TextDecoder().decode(await context.fs.readFile(path));
21500
22015
  const matches = text3.split("\n").filter((line) => line.trim() !== "").map(parseHarnessTrimReceiptEnvelope).filter((event) => event !== null && event.harness === harnessId2);
21501
- const latest = matches.at(-1);
21502
- if (latest !== void 0) {
21503
- return { observedAt: latest.ts, operations: matches.length, source: path };
22016
+ const latestAttempt = matches.at(-1);
22017
+ if (latestAttempt !== void 0) {
22018
+ const reductions = matches.filter(provesHarnessTrimReduction);
22019
+ return {
22020
+ observedAt: latestAttempt.ts,
22021
+ operations: reductions.length,
22022
+ attempts: matches.length,
22023
+ source: path
22024
+ };
21504
22025
  }
21505
22026
  }
21506
22027
  return null;
@@ -21545,10 +22066,19 @@ function scopeCanaryCheck(check, input) {
21545
22066
  remediation: input.runtimeConfigured ? "Enable telemetry on this runtime integration and use it on an output it can reduce." : "Skills or instructions alone do not write reduction telemetry; a compatible measurement path is required."
21546
22067
  };
21547
22068
  }
22069
+ if (input.receipt.operations === 0) {
22070
+ return {
22071
+ ...check,
22072
+ status: "info",
22073
+ summary: `HarnessTrim observed ${String(input.receipt.attempts ?? 0)} ${input.harnessId} outputs, but none was reduced; latest attempt ${input.receipt.observedAt}`,
22074
+ achievedTier: null,
22075
+ remediation: "Run a canary that produces output the installed HarnessTrim reducer can shorten, then verify again."
22076
+ };
22077
+ }
21548
22078
  return {
21549
22079
  ...check,
21550
22080
  status: "pass",
21551
- summary: `${String(input.receipt.operations)} reductions recorded for ${input.harnessId}, most recently ${input.receipt.observedAt}`,
22081
+ summary: `${String(input.receipt.operations)} reductions recorded for ${input.harnessId} from ${String(input.receipt.attempts ?? input.receipt.operations)} observed outputs, most recently ${input.receipt.observedAt}`,
21552
22082
  achievedTier: "canary"
21553
22083
  };
21554
22084
  }
@@ -21597,9 +22127,13 @@ async function scopeProviderVerificationToHarness(context, verification, harness
21597
22127
  const harnessTrim = verification.providerId === HARNESSTRIM4;
21598
22128
  const runtimeConfigured = harnessTrim ? harnessesWiredToHarnessTrim(context.harnessConfigs).includes(harnessId2) : configured;
21599
22129
  const attributableByExclusion = configured && configuredHarnesses.length === 1 && configuredHarnesses[0] === harnessId2;
21600
- const receipt = !configured ? null : harnessTrim ? await harnessTrimReceiptFor(context, harnessId2) : attributableByExclusion ? verification.receipt : null;
22130
+ const receipt = !configured ? null : harnessTrim ? await harnessTrimReceiptFor(context, harnessId2) : verification.receipt?.harnessId !== void 0 ? verification.receipt.harnessId === harnessId2 ? verification.receipt : null : attributableByExclusion ? verification.receipt : null;
21601
22131
  const providerHasAttributableReceipt = harnessTrim || attributableByExclusion;
21602
- const checks = verification.checks.map((check) => scopeCanaryCheck(scopeIntegrationCheck(scopeHookCheck(check, harnessId2, harnessTrim ? runtimeConfigured : configured), { harnessId: harnessId2, configured, runtimeConfigured }), {
22132
+ const scopedSourceChecks = verification.providerId === RTK4 ? verification.checks.filter((check) => {
22133
+ const match = /^(?:rtk-attribution|receipt-freshness)-(claude|codex)$/.exec(check.id);
22134
+ return match === null || match[1] === harnessId2;
22135
+ }) : verification.checks;
22136
+ const checks = scopedSourceChecks.map((check) => scopeCanaryCheck(scopeIntegrationCheck(scopeHookCheck(check, harnessId2, harnessTrim ? runtimeConfigured : configured), { harnessId: harnessId2, configured, runtimeConfigured }), {
21603
22137
  harnessId: harnessId2,
21604
22138
  configured,
21605
22139
  runtimeConfigured,
@@ -21614,13 +22148,14 @@ async function scopeProviderVerificationToHarness(context, verification, harness
21614
22148
  checks
21615
22149
  };
21616
22150
  }
21617
- var HARNESSTRIM4;
22151
+ var HARNESSTRIM4, RTK4;
21618
22152
  var init_harness_verification = __esm({
21619
22153
  "packages/adapters/dist/src/providers/harness-verification.js"() {
21620
22154
  "use strict";
21621
22155
  init_src();
21622
22156
  init_harnesstrim();
21623
22157
  HARNESSTRIM4 = providerId("harnesstrim");
22158
+ RTK4 = providerId("rtk");
21624
22159
  }
21625
22160
  });
21626
22161
 
@@ -21787,15 +22322,15 @@ async function runBudget(context) {
21787
22322
  diagnostics: report.harnesses.flatMap((item) => item.diagnostics)
21788
22323
  });
21789
22324
  }
21790
- var CLAUDE9, CODEX8, BUDGET_HARNESSES;
22325
+ var CLAUDE10, CODEX9, BUDGET_HARNESSES;
21791
22326
  var init_budget2 = __esm({
21792
22327
  "apps/cli/dist/src/commands/budget.js"() {
21793
22328
  "use strict";
21794
22329
  init_src3();
21795
22330
  init_src();
21796
- CLAUDE9 = harnessId("claude");
21797
- CODEX8 = harnessId("codex");
21798
- BUDGET_HARNESSES = /* @__PURE__ */ new Set([CLAUDE9, CODEX8]);
22331
+ CLAUDE10 = harnessId("claude");
22332
+ CODEX9 = harnessId("codex");
22333
+ BUDGET_HARNESSES = /* @__PURE__ */ new Set([CLAUDE10, CODEX9]);
21799
22334
  }
21800
22335
  });
21801
22336
 
@@ -22053,6 +22588,8 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
22053
22588
  contextSnapshot: null,
22054
22589
  nativePolicy: false,
22055
22590
  agentSkill: false,
22591
+ agentRouting: false,
22592
+ disableAgentRouting: false,
22056
22593
  verbose: false,
22057
22594
  yes: false
22058
22595
  };
@@ -22091,6 +22628,10 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
22091
22628
  options.nativePolicy = true;
22092
22629
  if (name2 === "--agent-skill")
22093
22630
  options.agentSkill = true;
22631
+ if (name2 === "--agent-routing")
22632
+ options.agentRouting = true;
22633
+ if (name2 === "--disable-agent-routing")
22634
+ options.disableAgentRouting = true;
22094
22635
  if (name2 === "--verbose")
22095
22636
  options.verbose = true;
22096
22637
  continue;
@@ -22327,6 +22868,14 @@ function parseArgv(argv2, plannedCommands = PLANNED_COMMANDS) {
22327
22868
  }));
22328
22869
  return usageError(json, diagnostics);
22329
22870
  }
22871
+ if (options.agentRouting && options.disableAgentRouting) {
22872
+ diagnostics.push(diagnostic({
22873
+ severity: "error",
22874
+ code: "conflicting-prompt-routing-flags",
22875
+ message: "--agent-routing and --disable-agent-routing cannot be used together",
22876
+ remediation: "Choose one prompt-routing state to plan"
22877
+ }));
22878
+ }
22330
22879
  if (!isAvailableCommand(command)) {
22331
22880
  const planned = plannedCommands.includes(command);
22332
22881
  diagnostics.push(planned ? diagnostic({
@@ -22396,7 +22945,557 @@ var init_argv = __esm({
22396
22945
  "--tasks-left",
22397
22946
  "--context-snapshot"
22398
22947
  ]);
22399
- BOOLEAN_FLAGS = /* @__PURE__ */ new Set(["--json", "--native-policy", "--agent-skill", "--verbose", "--yes"]);
22948
+ BOOLEAN_FLAGS = /* @__PURE__ */ new Set([
22949
+ "--json",
22950
+ "--native-policy",
22951
+ "--agent-skill",
22952
+ "--agent-routing",
22953
+ "--disable-agent-routing",
22954
+ "--verbose",
22955
+ "--yes"
22956
+ ]);
22957
+ }
22958
+ });
22959
+
22960
+ // apps/cli/dist/src/prompt-router.js
22961
+ function isHarness(value3) {
22962
+ return value3 === "claude" || value3 === "codex";
22963
+ }
22964
+ function expectedVersions(harness) {
22965
+ return harness === "codex" ? ["0.159.0", "0.160.0"] : ["2.1.274", "2.1.288"];
22966
+ }
22967
+ function configTarget(input) {
22968
+ if (!isHarness(input.harness) || input.home === null)
22969
+ return null;
22970
+ const adapter = findHarnessAdapter(harnessId(input.harness));
22971
+ const declaration = adapter?.manifest.configFiles.find((file) => file.scope === "user" && file.parser === "json" && file.interceptionPoints?.includes("user-prompt-submit") === true);
22972
+ if (declaration === void 0 || adapter === null)
22973
+ return null;
22974
+ const fileContext = {
22975
+ fs: input.fs,
22976
+ runner: input.runner,
22977
+ facts: input.facts,
22978
+ paths: { ...input.paths, home: input.home },
22979
+ projectRoot: input.projectRoot
22980
+ };
22981
+ return {
22982
+ harness: input.harness,
22983
+ path: resolveConfigPath(declaration, fileContext),
22984
+ version: input.version,
22985
+ fileContext
22986
+ };
22987
+ }
22988
+ function hookEntries(harness) {
22989
+ return nativePromptRoutingHookEntries(harnessId(harness), "token-harness");
22990
+ }
22991
+ function asRecord(value3) {
22992
+ return typeof value3 === "object" && value3 !== null && !Array.isArray(value3) ? value3 : null;
22993
+ }
22994
+ function parseHookDocument(text3) {
22995
+ let decoded;
22996
+ try {
22997
+ decoded = JSON.parse(text3);
22998
+ } catch {
22999
+ return { ok: false, reason: "The hook settings file is malformed JSON or contains comments." };
23000
+ }
23001
+ const root = asRecord(decoded);
23002
+ if (root === null)
23003
+ return { ok: false, reason: "The hook settings root must be a JSON object." };
23004
+ const hooksValue = root["hooks"];
23005
+ if (hooksValue === void 0)
23006
+ return { ok: true, hooks: {} };
23007
+ const hooks = asRecord(hooksValue);
23008
+ if (hooks === null)
23009
+ return { ok: false, reason: "The settings hooks property must be an object." };
23010
+ for (const { eventName } of hookEntries("codex")) {
23011
+ const entries = hooks[eventName];
23012
+ if (entries !== void 0 && !Array.isArray(entries))
23013
+ return { ok: false, reason: `The ${eventName} hook property must be an array.` };
23014
+ }
23015
+ return { ok: true, hooks };
23016
+ }
23017
+ function containsRouterCommand(value3, harness) {
23018
+ const row2 = asRecord(value3);
23019
+ const hooks = row2?.["hooks"];
23020
+ if (!Array.isArray(hooks))
23021
+ return false;
23022
+ return hooks.some((hook) => {
23023
+ const handler = asRecord(hook);
23024
+ if (handler === null)
23025
+ return false;
23026
+ if (harness === "codex")
23027
+ return [handler["command"], handler["commandWindows"]].some((command) => typeof command === "string" && command.includes(ROUTE_MARKER));
23028
+ const args = handler["args"];
23029
+ return handler["command"] === "token-harness" && Array.isArray(args) && args[0] === ROUTE_MARKER;
23030
+ });
23031
+ }
23032
+ function configHasExactRouter(hooks, harness) {
23033
+ let exactCount = 0;
23034
+ let routeCount = 0;
23035
+ for (const expected of hookEntries(harness)) {
23036
+ const live = hooks[expected.eventName];
23037
+ const entries = Array.isArray(live) ? live : [];
23038
+ const routeEntries = entries.filter((entry) => containsRouterCommand(entry, harness));
23039
+ routeCount += routeEntries.length;
23040
+ if (routeEntries.some((entry) => jsonValueDigest(entry) === jsonValueDigest(expected.value)))
23041
+ exactCount += 1;
23042
+ }
23043
+ return {
23044
+ complete: exactCount === hookEntries(harness).length,
23045
+ partial: routeCount > 0 && exactCount !== hookEntries(harness).length,
23046
+ conflict: routeCount > exactCount
23047
+ };
23048
+ }
23049
+ function routerOwnedArtifacts(journals, path, harness) {
23050
+ const expected = hookEntries(harness);
23051
+ for (const journal of journals) {
23052
+ const disabledHere = journal.entries.some((entry) => entry.actionId.startsWith(`native-prompt-routing:${harness}:disable:`) && entry.snapshots.some((snapshot) => snapshot.path === path));
23053
+ if (disabledHere && journal.outcome === "committed")
23054
+ return [];
23055
+ const relevant = journal.ownership.filter((artifact) => artifact.kind === "owned-json-entry" && artifact.path === path && artifact.placement === "array-element" && expected.some((entry) => artifact.pointer === `hooks.${entry.eventName}` && artifact.valueDigest === jsonValueDigest(entry.value)));
23056
+ if (relevant.length > 0)
23057
+ return journal.outcome === "committed" ? relevant : [];
23058
+ }
23059
+ return [];
23060
+ }
23061
+ async function journalsFor(input) {
23062
+ if (input.stateRoot === null)
23063
+ return [];
23064
+ const journalRoot = input.fs.join(input.stateRoot, "journals");
23065
+ if ((await input.fs.stat(journalRoot))?.kind !== "directory")
23066
+ return [];
23067
+ return new FileJournalStore({
23068
+ fs: input.fs,
23069
+ journalRoot,
23070
+ backupRoot: input.fs.join(input.stateRoot, "backups")
23071
+ }).list();
23072
+ }
23073
+ function actionId(harness, intent, eventName) {
23074
+ return `native-prompt-routing:${harness}:${intent}:${eventName}`;
23075
+ }
23076
+ async function planNativePromptRoutingInstall(input) {
23077
+ const diagnostics = [];
23078
+ const target = configTarget(input);
23079
+ if (target === null) {
23080
+ diagnostics.push(diagnostic({
23081
+ severity: "warning",
23082
+ code: "prompt-routing-target-unavailable",
23083
+ subject: input.harness,
23084
+ message: "No supported user-scope native prompt hook target is available",
23085
+ remediation: "Resolve the user home and harness installation, then refresh Token Harness"
23086
+ }));
23087
+ return { target: null, actions: [], diagnostics };
23088
+ }
23089
+ if (!expectedVersions(target.harness).includes(target.version ?? "")) {
23090
+ diagnostics.push(diagnostic({
23091
+ severity: "warning",
23092
+ code: "prompt-routing-version-unverified",
23093
+ subject: target.harness,
23094
+ message: `Native prompt routing has no hook fixture for ${target.harness} ${target.version ?? "unknown"}`,
23095
+ path: target.path,
23096
+ remediation: "Refresh Token Harness after the installed harness hook schema is fixture-tested"
23097
+ }));
23098
+ return { target: target.path, actions: [], diagnostics };
23099
+ }
23100
+ const runtimeCheck = await input.runner.run({
23101
+ executable: "token-harness",
23102
+ args: ["__internal-prompt-router", target.harness, "--check"],
23103
+ cwd: input.projectRoot,
23104
+ timeoutMs: 3e3,
23105
+ maxOutputBytes: 256
23106
+ });
23107
+ if (runtimeCheck.failure !== null || runtimeCheck.exitCode !== 0 || runtimeCheck.stdout.trim() !== PROMPT_ROUTER_CHECK_MARKER) {
23108
+ diagnostics.push(diagnostic({
23109
+ severity: "error",
23110
+ code: "prompt-routing-runtime-unavailable",
23111
+ subject: target.harness,
23112
+ message: "The Token Harness executable found on PATH cannot serve the native prompt hook",
23113
+ path: target.path,
23114
+ remediation: "Install or update Token Harness so the same executable is available to the coding agent, then refresh and plan again"
23115
+ }));
23116
+ return { target: target.path, actions: [], diagnostics };
23117
+ }
23118
+ const stat3 = await input.fs.stat(target.path);
23119
+ if (stat3 !== null && stat3.kind !== "file") {
23120
+ diagnostics.push(diagnostic({
23121
+ severity: "error",
23122
+ code: "prompt-routing-target-not-file",
23123
+ subject: target.harness,
23124
+ message: "A non-file occupies the native hook settings path",
23125
+ path: target.path,
23126
+ remediation: "Move the conflicting path and refresh Token Harness"
23127
+ }));
23128
+ return { target: target.path, actions: [], diagnostics };
23129
+ }
23130
+ let hooks = {};
23131
+ if (stat3 !== null) {
23132
+ const parsed = parseHookDocument(DECODER4.decode(await input.fs.readFile(target.path)));
23133
+ if (!parsed.ok) {
23134
+ diagnostics.push(diagnostic({
23135
+ severity: "error",
23136
+ code: "prompt-routing-settings-unmergeable",
23137
+ subject: target.harness,
23138
+ message: parsed.reason,
23139
+ path: target.path,
23140
+ remediation: "Repair the JSON settings file or configure native prompt routing manually"
23141
+ }));
23142
+ return { target: target.path, actions: [], diagnostics };
23143
+ }
23144
+ hooks = parsed.hooks;
23145
+ }
23146
+ const existing = configHasExactRouter(hooks, target.harness);
23147
+ if (existing.complete) {
23148
+ diagnostics.push(diagnostic({
23149
+ severity: "info",
23150
+ code: "prompt-routing-already-configured",
23151
+ subject: target.harness,
23152
+ message: "Native prompt routing hooks are already present; no settings are changed",
23153
+ path: target.path,
23154
+ remediation: null
23155
+ }));
23156
+ return { target: target.path, actions: [], diagnostics };
23157
+ }
23158
+ if (existing.partial || existing.conflict) {
23159
+ diagnostics.push(diagnostic({
23160
+ severity: "error",
23161
+ code: "prompt-routing-existing-hook-conflict",
23162
+ subject: target.harness,
23163
+ message: "A partial or modified Token Harness prompt hook already exists and was left untouched",
23164
+ path: target.path,
23165
+ remediation: "Review the existing native routing entries before planning another change"
23166
+ }));
23167
+ return { target: target.path, actions: [], diagnostics };
23168
+ }
23169
+ const entries = hookEntries(target.harness);
23170
+ const action = {
23171
+ kind: "merge-json",
23172
+ id: actionId(target.harness, "enable", "all"),
23173
+ riskClass: "reversible",
23174
+ requiresNetwork: false,
23175
+ requiresElevation: false,
23176
+ affectedPaths: [target.path],
23177
+ affectedProcesses: [target.harness],
23178
+ preconditions: [
23179
+ "the harness hook settings remain absent or valid JSON",
23180
+ "no Token Harness native prompt-routing hooks are already present"
23181
+ ],
23182
+ postconditions: entries.map((entry) => `${entry.eventName} has one Token Harness-owned hook`),
23183
+ rollbackData: "file-snapshot",
23184
+ explanation: `Enable automatic native prompt routing for ${target.harness}` + (target.harness === "codex" ? "; manually enable and trust this hook in Codex after applying" : "; start a new Claude Code session after applying"),
23185
+ path: target.path,
23186
+ ownedPointers: entries.map((entry) => `hooks.${entry.eventName}`),
23187
+ operations: entries.map((entry) => ({
23188
+ kind: "append",
23189
+ pointer: `hooks.${entry.eventName}`,
23190
+ value: entry.value,
23191
+ expectedValueDigest: null
23192
+ })),
23193
+ createIfMissing: true
23194
+ };
23195
+ return { target: target.path, actions: [action], diagnostics };
23196
+ }
23197
+ async function planNativePromptRoutingRemoval(input) {
23198
+ const diagnostics = [];
23199
+ const target = configTarget(input);
23200
+ if (target === null || input.stateRoot === null) {
23201
+ diagnostics.push(diagnostic({
23202
+ severity: "warning",
23203
+ code: "prompt-routing-removal-unavailable",
23204
+ subject: input.harness,
23205
+ message: "The owned native prompt-routing configuration could not be located safely",
23206
+ remediation: "Refresh Token Harness from the signed-in user environment"
23207
+ }));
23208
+ return { target: target?.path ?? null, actions: [], diagnostics };
23209
+ }
23210
+ const expected = hookEntries(target.harness);
23211
+ const journals = await journalsFor({ fs: input.fs, stateRoot: input.stateRoot });
23212
+ const artifacts = routerOwnedArtifacts(journals, target.path, target.harness);
23213
+ const actions = expected.flatMap((entry) => {
23214
+ const pointer = `hooks.${entry.eventName}`;
23215
+ const targetArtifact = artifacts.find((artifact) => artifact.kind === "owned-json-entry" && artifact.pointer === pointer && artifact.valueDigest === jsonValueDigest(entry.value));
23216
+ if (targetArtifact === void 0)
23217
+ return [];
23218
+ const reverses = actionId(target.harness, "enable", "all");
23219
+ return [
23220
+ {
23221
+ kind: "remove-owned-change",
23222
+ id: actionId(target.harness, "disable", entry.eventName),
23223
+ riskClass: "reversible",
23224
+ requiresNetwork: false,
23225
+ requiresElevation: false,
23226
+ affectedPaths: [target.path],
23227
+ affectedProcesses: [target.harness],
23228
+ preconditions: [`${entry.eventName} still contains the exact Token Harness-owned hook`],
23229
+ postconditions: [`${entry.eventName} no longer contains the owned prompt-routing hook`],
23230
+ rollbackData: "file-snapshot",
23231
+ explanation: `Disable automatic native prompt routing for ${target.harness}`,
23232
+ path: target.path,
23233
+ reverses,
23234
+ target: targetArtifact
23235
+ }
23236
+ ];
23237
+ });
23238
+ if (actions.length === 0)
23239
+ diagnostics.push(diagnostic({
23240
+ severity: "info",
23241
+ code: "prompt-routing-not-owned",
23242
+ subject: target.harness,
23243
+ message: "Token Harness owns no native prompt-routing hooks here, so nothing is removed",
23244
+ path: target.path,
23245
+ remediation: null
23246
+ }));
23247
+ return { target: target.path, actions, diagnostics };
23248
+ }
23249
+ async function readEvents(input) {
23250
+ if (input.stateRoot === null)
23251
+ return { state: "unavailable", events: [] };
23252
+ const directory = input.fs.join(input.stateRoot, "prompt-routing");
23253
+ if ((await input.fs.stat(directory))?.kind !== "directory")
23254
+ return { state: "available", events: [] };
23255
+ const files = (await input.fs.readDirectory(directory)).filter((name2) => /^events-\d{4}-\d{2}\.jsonl$/.test(name2)).sort().reverse();
23256
+ const events = [];
23257
+ let scannedBytes = 0;
23258
+ try {
23259
+ for (const file of files) {
23260
+ const path = input.fs.join(directory, file);
23261
+ const stat3 = await input.fs.stat(path);
23262
+ if (stat3 === null || stat3.kind !== "file")
23263
+ continue;
23264
+ if (stat3.byteLength > MAX_EVENT_FILE_BYTES || scannedBytes + stat3.byteLength > MAX_EVENT_SCAN_BYTES)
23265
+ return { state: "limited", events };
23266
+ const bytes = await input.fs.readFile(path);
23267
+ if (bytes.byteLength !== stat3.byteLength)
23268
+ return { state: "limited", events };
23269
+ scannedBytes += bytes.byteLength;
23270
+ const text3 = DECODER4.decode(bytes);
23271
+ for (const line of text3.split("\n")) {
23272
+ if (line === "")
23273
+ continue;
23274
+ try {
23275
+ const value3 = JSON.parse(line);
23276
+ if (!isPromptRouterEvent(value3))
23277
+ continue;
23278
+ if (input.harness !== void 0 && value3.harness !== input.harness)
23279
+ continue;
23280
+ if (input.projectId !== void 0 && value3.projectId !== input.projectId)
23281
+ continue;
23282
+ if (input.since !== void 0 && value3.timestamp < input.since)
23283
+ continue;
23284
+ events.push(value3);
23285
+ } catch {
23286
+ }
23287
+ }
23288
+ if (input.since !== void 0 && file.slice(7, 14) < input.since.slice(0, 7))
23289
+ break;
23290
+ }
23291
+ return { state: "available", events };
23292
+ } catch {
23293
+ return { state: "unavailable", events: [] };
23294
+ }
23295
+ }
23296
+ function isPromptRouterEvent(value3) {
23297
+ const row2 = asRecord(value3);
23298
+ return row2?.["schemaVersion"] === 1 && typeof row2["timestamp"] === "string" && Number.isFinite(Date.parse(row2["timestamp"])) && (row2["harness"] === "claude" || row2["harness"] === "codex") && typeof row2["projectId"] === "string" && ["prompt-submit", "subagent-start", "subagent-stop"].includes(String(row2["type"])) && (row2["model"] === null || typeof row2["model"] === "string" && row2["model"].length <= 80) && (row2["agentType"] === null || typeof row2["agentType"] === "string" && row2["agentType"].length <= 80);
23299
+ }
23300
+ async function recordNativePromptRoutingHook(input) {
23301
+ if (input.fs === null || input.stateRoot === null || input.projectId === null)
23302
+ return;
23303
+ let payload = null;
23304
+ if (input.event !== "prompt-submit" && input.hookInput !== null) {
23305
+ try {
23306
+ payload = asRecord(JSON.parse(input.hookInput));
23307
+ } catch {
23308
+ payload = null;
23309
+ }
23310
+ }
23311
+ const agentTypeRaw = payload?.["agent_type"];
23312
+ const agentType = input.event !== "prompt-submit" && typeof agentTypeRaw === "string" && agentTypeRaw.length <= 80 ? agentTypeRaw : null;
23313
+ const timestamp = new Date(input.now).toISOString();
23314
+ const event = {
23315
+ schemaVersion: 1,
23316
+ timestamp,
23317
+ harness: input.harness,
23318
+ projectId: input.projectId,
23319
+ type: input.event,
23320
+ // Hook payload model fields can identify the root session, not the spawned child. Until an
23321
+ // adapter has a versioned child-model field, keep actual worker identity unknown.
23322
+ model: null,
23323
+ agentType
23324
+ };
23325
+ const partition = `events-${timestamp.slice(0, 7)}.jsonl`;
23326
+ const directory = input.fs.join(input.stateRoot, "prompt-routing");
23327
+ await input.fs.createDirectory(directory);
23328
+ await input.fs.appendFile(input.fs.join(directory, partition), UTF84.encode(`${JSON.stringify(event)}
23329
+ `));
23330
+ }
23331
+ function summarizeEvents(events) {
23332
+ return {
23333
+ promptSubmissions: events.filter((event) => event.type === "prompt-submit").length,
23334
+ subagentsStarted: events.filter((event) => event.type === "subagent-start").length,
23335
+ subagentsStopped: events.filter((event) => event.type === "subagent-stop").length,
23336
+ reportedModels: [
23337
+ ...new Set(events.filter((event) => event.type === "subagent-start" || event.type === "subagent-stop").flatMap((event) => event.model === null ? [] : [event.model]))
23338
+ ],
23339
+ lastObservedAt: events.map((event) => event.timestamp).sort().at(-1) ?? null
23340
+ };
23341
+ }
23342
+ async function observeNativePromptRouting(input) {
23343
+ const harness = isHarness(input.harness) ? input.harness : "codex";
23344
+ const base = {
23345
+ harness,
23346
+ state: "unavailable",
23347
+ label: "Not verified",
23348
+ detail: "Native prompt routing could not be checked on this harness.",
23349
+ configPath: null,
23350
+ configured: null,
23351
+ promptSubmissions: 0,
23352
+ subagentsStarted: 0,
23353
+ subagentsStopped: 0,
23354
+ reportedModels: [],
23355
+ lastObservedAt: null,
23356
+ receiptState: "unavailable"
23357
+ };
23358
+ const target = configTarget({ ...input, harness: input.harness });
23359
+ if (target === null)
23360
+ return base;
23361
+ const eventResult = await readEvents({
23362
+ fs: input.fs,
23363
+ stateRoot: input.stateRoot,
23364
+ harness,
23365
+ ...input.projectId === null ? {} : { projectId: input.projectId },
23366
+ since: new Date(Date.now() - 30 * 24 * 60 * 60 * 1e3).toISOString()
23367
+ });
23368
+ const summary = summarizeEvents(eventResult.events);
23369
+ const stat3 = await input.fs.stat(target.path);
23370
+ if (stat3 === null) {
23371
+ return {
23372
+ ...base,
23373
+ state: "absent",
23374
+ label: "Disabled",
23375
+ detail: "Automatic routing is off. No Token Harness native prompt hook is installed.",
23376
+ configPath: target.path,
23377
+ configured: false,
23378
+ ...summary,
23379
+ receiptState: eventResult.state
23380
+ };
23381
+ }
23382
+ if (stat3.kind !== "file")
23383
+ return {
23384
+ ...base,
23385
+ state: "conflict",
23386
+ label: "Path conflict",
23387
+ detail: "A non-file occupies the native hook settings path.",
23388
+ configPath: target.path,
23389
+ ...summary,
23390
+ receiptState: eventResult.state
23391
+ };
23392
+ let hooks;
23393
+ try {
23394
+ const parsed = parseHookDocument(DECODER4.decode(await input.fs.readFile(target.path)));
23395
+ if (!parsed.ok)
23396
+ return {
23397
+ ...base,
23398
+ state: "conflict",
23399
+ label: "Settings need review",
23400
+ detail: parsed.reason,
23401
+ configPath: target.path,
23402
+ ...summary,
23403
+ receiptState: eventResult.state
23404
+ };
23405
+ hooks = parsed.hooks;
23406
+ } catch {
23407
+ return {
23408
+ ...base,
23409
+ state: "unavailable",
23410
+ label: "Not verified",
23411
+ detail: "The hook settings file could not be read safely.",
23412
+ configPath: target.path,
23413
+ ...summary,
23414
+ receiptState: eventResult.state
23415
+ };
23416
+ }
23417
+ const match = configHasExactRouter(hooks, harness);
23418
+ if (match.conflict || match.partial) {
23419
+ return {
23420
+ ...base,
23421
+ state: "conflict",
23422
+ label: "Custom hook needs review",
23423
+ detail: "A partial or edited Token Harness prompt-routing hook was found and was not changed.",
23424
+ configPath: target.path,
23425
+ ...summary,
23426
+ receiptState: eventResult.state
23427
+ };
23428
+ }
23429
+ if (!match.complete) {
23430
+ return {
23431
+ ...base,
23432
+ state: "absent",
23433
+ label: "Disabled",
23434
+ detail: "Automatic routing is off. No Token Harness native prompt hook is installed.",
23435
+ configPath: target.path,
23436
+ configured: false,
23437
+ ...summary,
23438
+ receiptState: eventResult.state
23439
+ };
23440
+ }
23441
+ const artifacts = routerOwnedArtifacts(await journalsFor(input), target.path, harness);
23442
+ const state = artifacts.length === hookEntries(harness).length ? "managed" : "external";
23443
+ const hasRuntimeReceipt = summary.promptSubmissions > 0;
23444
+ const label = state === "external" ? hasRuntimeReceipt ? "Runtime observed \xB7 external" : "Enabled externally" : hasRuntimeReceipt ? "Runtime observed" : harness === "codex" ? "Configured \xB7 trust or runtime pending" : "Configured \xB7 runtime pending";
23445
+ const detail2 = summary.promptSubmissions > 0 ? `${String(summary.promptSubmissions)} prompt hook(s), ${String(summary.subagentsStarted)} native agent start(s), ${String(summary.subagentsStopped)} stop(s) observed in this project during the last 30 days.${eventResult.state === "limited" ? " Counts are partial because the local receipt scan reached its safety limit." : eventResult.state === "unavailable" ? " Local runtime receipts could not be read." : ""}` : harness === "codex" ? "The hook is configured. Review and trust it in Codex with /hooks, then submit a prompt to produce a runtime receipt." : "The hook is configured. Start a new Claude Code session, submit a prompt, and Token Harness will show the runtime receipt.";
23446
+ return {
23447
+ ...base,
23448
+ state,
23449
+ label,
23450
+ detail: detail2,
23451
+ configPath: target.path,
23452
+ configured: true,
23453
+ ...summary,
23454
+ receiptState: eventResult.state
23455
+ };
23456
+ }
23457
+ async function nativeRoutingObservationForBenchmark(input) {
23458
+ const observed = await observeNativePromptRouting({
23459
+ ...input,
23460
+ projectId: input.projectId
23461
+ });
23462
+ const configured = observed.configured;
23463
+ if (input.startedAt === void 0)
23464
+ return {
23465
+ configured,
23466
+ promptSubmissions: 0,
23467
+ subagentsStarted: 0,
23468
+ subagentsStopped: 0,
23469
+ reportedModels: []
23470
+ };
23471
+ const found = await readEvents({
23472
+ fs: input.fs,
23473
+ stateRoot: input.stateRoot,
23474
+ harness: observed.harness,
23475
+ projectId: input.projectId,
23476
+ since: input.startedAt
23477
+ });
23478
+ const summary = summarizeEvents(found.events);
23479
+ return {
23480
+ configured,
23481
+ promptSubmissions: summary.promptSubmissions,
23482
+ subagentsStarted: summary.subagentsStarted,
23483
+ subagentsStopped: summary.subagentsStopped,
23484
+ reportedModels: summary.reportedModels
23485
+ };
23486
+ }
23487
+ var UTF84, DECODER4, ROUTE_MARKER, MAX_EVENT_FILE_BYTES, MAX_EVENT_SCAN_BYTES, PROMPT_ROUTER_CHECK_MARKER;
23488
+ var init_prompt_router = __esm({
23489
+ "apps/cli/dist/src/prompt-router.js"() {
23490
+ "use strict";
23491
+ init_src();
23492
+ init_src3();
23493
+ UTF84 = new TextEncoder();
23494
+ DECODER4 = new TextDecoder("utf-8", { fatal: true });
23495
+ ROUTE_MARKER = "__internal-prompt-router";
23496
+ MAX_EVENT_FILE_BYTES = 4 * 1024 * 1024;
23497
+ MAX_EVENT_SCAN_BYTES = 16 * 1024 * 1024;
23498
+ PROMPT_ROUTER_CHECK_MARKER = "token-harness-prompt-router-v1";
22400
23499
  }
22401
23500
  });
22402
23501
 
@@ -23665,7 +24764,7 @@ var init_agent_skill = __esm({
23665
24764
  "apps/cli/dist/src/agent-skill.js"() {
23666
24765
  "use strict";
23667
24766
  init_src();
23668
- TOKEN_HARNESS_AGENT_SKILL = "---\nname: token-harness\ndescription: Optimizes local Claude Code or Codex work against observed subscription allowance, context pressure, quality floors, and project-local benchmark evidence using the Token Harness CLI. Use when the user asks to conserve or maximize coding-agent allowance, choose reasoning/model/verbosity deliberately, check whether a task fits current quota, or explicitly asks to use Token Harness.\n---\n\n# Token Harness\n\nUse Token Harness as a local deterministic policy engine. Do not reproduce its quota math or invent provider conversions yourself.\n\n## Default workflow\n\n1. Confirm `token-harness --version` works. If it is missing, do not install it silently. If the user asked to install or set up Token Harness, follow that request; otherwise explain that the local CLI is required.\n2. Identify the harness you are currently running as: `claude` for Claude Code or `codex` for Codex. Do not guess from repository files.\n3. Classify the current task conservatively:\n - `mechanical`: formatting, rename, lookup, simple edits, deterministic scaffolding.\n - `standard`: ordinary implementation, tests, focused bug fixes.\n - `hard`: multi-file reasoning, ambiguous failures, migrations, difficult reviews.\n - `critical`: architecture, security-sensitive work, releases, or high-regression-risk changes.\n If uncertain between two classes, use the higher class.\n4. For a substantial task, or whenever the user asks about allowance/efficiency, run:\n\n `token-harness optimize --harness <claude|codex> --task <class> --profile balanced --json`\n\n5. Treat the JSON result as evidence, not as permission to mutate configuration. Prefer recommendations that reduce avoidable context or session overhead before lowering a quality floor.\n6. Continue with the user's task. Mention Token Harness only when it materially changes the plan, recommends a user-visible action, or lacks enough evidence.\n\nDo not run Token Harness before every trivial tool call. One observation at a meaningful task boundary is normally enough; re-observe when the task class changes materially, after a quota reset, after a substantial session/context change, or when the user asks.\n\n## Active context evidence\n\nWhen the current conversation or your own tool results directly establish useful task-state evidence, you may pass a short-lived `--context-snapshot` file to `optimize`. This metadata is for the CLI; never ask the user to write or understand the JSON. Skip the snapshot when no actionable evidence is directly observable or a temporary file cannot be safely created and removed.\n\n- Set task boundary, validation and quality only from explicit task state and checks you observed. Use `unknown` when those facts are missing or ambiguous.\n- Mark material superseded or condensable only when its current state is directly clear. Include `byteLength` only when tooling measured the exact local bytes; otherwise use `null`. Never estimate bytes from tokens.\n- Set reducer attribution only when directly known; otherwise use `unknown`. Do not include transcript text, prompts, tool payloads, source text, paths, MCP names or schemas.\n- Add a checkpoint byte ceiling only when you will use that same ceiling for the existing bounded `token-harness handoff` command. Omit it when no artifact budget is configured.\n- Create the metadata file temporarily, run `optimize`, then remove it. Treat the decision as advice; do not mask, summarize, compact or start a session on the user's behalf.\n\n## Explicit workload\n\nOnly pass `--tasks-left N` when the remaining accepted-task count is explicit from the user or an explicit task list already in the conversation. Never infer it from token history, source files, GitHub issues, or a guessed backlog. When it is explicit, add it to the same advisory call:\n\n`token-harness optimize --harness <claude|codex> --task <class> --profile balanced --tasks-left <N> --json`\n\nFor multiple independent new tasks whose explicit list can be classified by task class, Token Harness can compare Claude and Codex with:\n\n`token-harness schedule --current <current> --candidate <other> --workload mechanical=N,standard=N,hard=N,critical=N --json`\n\nOmit zero-count classes. This is for queued new work, not an in-progress handoff. Never switch harnesses automatically from this result.\n\n## Persistent native changes\n\n`optimize` is advisory. If it recommends a persistent model/reasoning/verbosity change and the user wants it applied:\n\n1. Build a reviewed plan with `token-harness plan --harness <claude|codex> --native-policy --task <class> --profile balanced --json`.\n2. Summarize the exact proposed change, scope, and any limitations to the user.\n3. Apply only after the user explicitly approves the proposed mutation. Use the returned plan id with `token-harness apply --plan <id> --yes`.\n4. Do not treat a persisted preference as a live change to an already-running session. Follow the plan/result instructions about when it takes effect.\n\nNever silently change authentication, billing, provider, model routing, hooks, trust, or purchase/redeem credits.\n\n## Evidence rules\n\n- Never equate local token counts with subscription quota.\n- Never compare raw Claude and Codex percentages as if they were the same currency.\n- Unknown allowance or benchmark evidence stays unknown.\n- Preserve task quality floors; do not lower effort merely because a cheaper setting exists.\n- Prefer project-local measured outcomes and backend quota deltas when Token Harness exposes them.\n- Do not add an MCP server or background model just to use this skill. The local CLI is the tool surface.\n";
24767
+ TOKEN_HARNESS_AGENT_SKILL = "---\nname: token-harness\ndescription: Optimizes local Claude Code or Codex work against observed subscription allowance, context pressure, quality floors, and project-local benchmark evidence using the Token Harness CLI. Guides native subagent model routing for substantial bounded coding tasks. Use for substantial coding work where native delegation may apply, or when the user asks about allowance, model/effort/verbosity choices, quota fit, or Token Harness.\n---\n\n# Token Harness\n\nUse Token Harness as a local deterministic policy engine. Do not reproduce its quota math or invent provider conversions yourself.\n\n## Automatic routing\n\nWhen enabled in the Token Harness dashboard, a native prompt hook supplies the routing policy on every submitted prompt. This works without invoking this skill or prefixing the prompt with a command. The hook asks the coding agent to delegate only eligible bounded work; it does not change the root model or prove which child model ran. Use this skill when the user asks for explicit quota-aware advice or a benchmark.\n\n## Default workflow\n\n1. Confirm `token-harness --version` works. If it is missing, do not install it silently. If the user asked to install or set up Token Harness, follow that request; otherwise explain that the local CLI is required.\n2. Identify the harness you are currently running as: `claude` for Claude Code or `codex` for Codex. Do not guess from repository files.\n3. Classify the current task conservatively:\n - `mechanical`: formatting, rename, lookup, simple edits, deterministic scaffolding.\n - `standard`: ordinary implementation, tests, focused bug fixes.\n - `hard`: multi-file reasoning, ambiguous failures, migrations, difficult reviews.\n - `critical`: architecture, security-sensitive work, releases, or high-regression-risk changes.\n If uncertain between two classes, use the higher class.\n4. For a substantial task, or whenever the user asks about allowance/efficiency, run:\n\n `token-harness optimize --harness <claude|codex> --task <class> --profile balanced --json`\n\n5. Treat the JSON result as evidence, not as permission to mutate configuration. Prefer recommendations that reduce avoidable context or session overhead before lowering a quality floor.\n6. Continue with the user's task. Mention Token Harness only when it materially changes the plan, recommends a user-visible action, or lacks enough evidence.\n\nDo not run Token Harness before every trivial tool call. One observation at a meaningful task boundary is normally enough; re-observe when the task class changes materially, after a quota reset, after a substantial session/context change, or when the user asks.\n\n## Active context evidence\n\nWhen the current conversation or your own tool results directly establish useful task-state evidence, you may pass a short-lived `--context-snapshot` file to `optimize`. This metadata is for the CLI; never ask the user to write or understand the JSON. Skip the snapshot when no actionable evidence is directly observable or a temporary file cannot be safely created and removed.\n\n- Set task boundary, validation and quality only from explicit task state and checks you observed. Use `unknown` when those facts are missing or ambiguous.\n- Mark material superseded or condensable only when its current state is directly clear. Include `byteLength` only when tooling measured the exact local bytes; otherwise use `null`. Never estimate bytes from tokens.\n- Set reducer attribution only when directly known; otherwise use `unknown`. Do not include transcript text, prompts, tool payloads, source text, paths, MCP names or schemas.\n- Add a checkpoint byte ceiling only when you will use that same ceiling for the existing bounded `token-harness handoff` command. Omit it when no artifact budget is configured.\n- Create the metadata file temporarily, run `optimize`, then remove it. Treat the decision as advice; do not mask, summarize, compact or start a session on the user's behalf.\n\n## Explicit workload\n\nOnly pass `--tasks-left N` when the remaining accepted-task count is explicit from the user or an explicit task list already in the conversation. Never infer it from token history, source files, GitHub issues, or a guessed backlog. When it is explicit, add it to the same advisory call:\n\n`token-harness optimize --harness <claude|codex> --task <class> --profile balanced --tasks-left <N> --json`\n\nFor multiple independent new tasks whose explicit list can be classified by task class, Token Harness can compare Claude and Codex with:\n\n`token-harness schedule --current <current> --candidate <other> --workload mechanical=N,standard=N,hard=N,critical=N --json`\n\nOmit zero-count classes. This is for queued new work, not an in-progress handoff. Never switch harnesses automatically from this result.\n\n## Native subagent model routing\n\nUse native subagents as the only model-routing surface. This routes delegated work; it never changes the model already selected for the root conversation. Keep Codex as the first supported path.\n\nFor Codex, when the task is substantial and contains a complete, bounded implementation unit that can be handed off without duplicating work, delegate that unit to one native subagent with `model: gpt-6-luna` if Luna is present in the current Codex model picker/catalog. Set the model explicitly in the native spawn request: when it is omitted, Codex inherits the root model and reasoning effort, so a generic delegation is not a cost-routed delegation. If a higher-priority instruction forbids specifying the child model, skip cost routing and continue with the root model. Keep the root model responsible for task framing, integration, and acceptance review. Do not run the same implementation in both agents. Use at most one cost-routed worker at a time.\n\nSkip routing for trivial tasks, tightly coupled or shared-write work, architecture/security/release decisions, work that needs the root model's full context or judgment throughout, when the user asks not to delegate, when the root model is Luna or cannot be identified, or when the requested model is not currently available. Do not substitute an unverified model ID or silently fall back to another harness. If no supported route is available, continue with the current root model.\n\nFor Claude Code, apply the same bounded-task rules only when Claude Code is already configured and authenticated and native subagents are available. Request the current native `haiku` alias for an eligible worker; do not configure Claude Code or authenticate on the user's behalf.\n\nTreat the selected child model as a routing request until Codex or Claude Code visibly reports the worker's actual model. A skill instruction is not runtime telemetry. Subagents add context and coordination overhead and can consume more total tokens than single-agent work; do not claim token, quota, or cost savings without paired, quality-gated usage evidence for the same harness and task class.\n\n## Persistent native changes\n\n`optimize` is advisory. If it recommends a persistent model/reasoning/verbosity change and the user wants it applied:\n\n1. Build a reviewed plan with `token-harness plan --harness <claude|codex> --native-policy --task <class> --profile balanced --json`.\n2. Summarize the exact proposed change, scope, and any limitations to the user.\n3. Apply only after the user explicitly approves the proposed mutation. Use the returned plan id with `token-harness apply --plan <id> --yes`.\n4. Do not treat a persisted preference as a live change to an already-running session. Follow the plan/result instructions about when it takes effect.\n\nNever silently change authentication, billing, provider, model routing, hooks, trust, or purchase/redeem credits.\n\n## Evidence rules\n\n- Never equate local token counts with subscription quota.\n- Never compare raw Claude and Codex percentages as if they were the same currency.\n- Unknown allowance or benchmark evidence stays unknown.\n- Preserve task quality floors; do not lower effort merely because a cheaper setting exists.\n- Prefer project-local measured outcomes and backend quota deltas when Token Harness exposes them.\n- Do not add an MCP server or background model just to use this skill. The local CLI is the tool surface.\n";
23669
24768
  ENCODER = new TextEncoder();
23670
24769
  SKILL_DIGEST = digestBytes(ENCODER.encode(TOKEN_HARNESS_AGENT_SKILL));
23671
24770
  TARGETS = {
@@ -23883,12 +24982,12 @@ var init_context_owner_candidates = __esm({
23883
24982
  });
23884
24983
 
23885
24984
  // apps/cli/dist/src/commands/context-cost.js
23886
- function nativeToolDeferral(harness, version3, verdict) {
23887
- if (harness !== CODEX9)
24985
+ function nativeToolDeferral(harness, version3) {
24986
+ if (harness !== CODEX10)
23888
24987
  return null;
23889
- if (version3 === "0.146.0" && verdict === "in-range") {
24988
+ if (version3 === "0.146.0") {
23890
24989
  return {
23891
- harnessId: CODEX9,
24990
+ harnessId: CODEX10,
23892
24991
  mechanism: "native-tool-search",
23893
24992
  state: "available",
23894
24993
  scope: "mcp-tools",
@@ -23897,7 +24996,7 @@ function nativeToolDeferral(harness, version3, verdict) {
23897
24996
  };
23898
24997
  }
23899
24998
  return {
23900
- harnessId: CODEX9,
24999
+ harnessId: CODEX10,
23901
25000
  mechanism: "native-tool-search",
23902
25001
  state: "unknown",
23903
25002
  scope: "mcp-tools",
@@ -24014,7 +25113,7 @@ async function codexInstructionFiles(context, observation) {
24014
25113
  if (selected === null)
24015
25114
  continue;
24016
25115
  const item = await fileObservation(context, {
24017
- harnessId: CODEX9,
25116
+ harnessId: CODEX10,
24018
25117
  path: selected,
24019
25118
  scope: "project",
24020
25119
  loadedBytes: remaining2
@@ -24046,7 +25145,7 @@ async function claudeInstructionFiles(context) {
24046
25145
  const results = [];
24047
25146
  for (const candidate of candidates) {
24048
25147
  const item = await fileObservation(context, {
24049
- harnessId: CLAUDE10,
25148
+ harnessId: CLAUDE11,
24050
25149
  path: candidate.path,
24051
25150
  scope: candidate.scope,
24052
25151
  loadedBytes: null
@@ -24113,16 +25212,16 @@ async function runContext(context) {
24113
25212
  continue;
24114
25213
  }
24115
25214
  const observation = await adapter.observeContext(harnessContext, report.observedAt);
24116
- const deferral = nativeToolDeferral(adapter.manifest.id, detection.version, detection.versionVerdict);
25215
+ const deferral = nativeToolDeferral(adapter.manifest.id, detection.version);
24117
25216
  if (deferral !== null)
24118
25217
  observation.toolDeferral = deferral;
24119
25218
  report.harnesses.push(observation);
24120
25219
  }
24121
- const codex = report.harnesses.find((item) => item.harnessId === CODEX9);
25220
+ const codex = report.harnesses.find((item) => item.harnessId === CODEX10);
24122
25221
  if (codex !== void 0 && codex.state !== "absent") {
24123
25222
  report.instructions.push(...await codexInstructionFiles(context, codex));
24124
25223
  }
24125
- const claude = report.harnesses.find((item) => item.harnessId === CLAUDE10);
25224
+ const claude = report.harnesses.find((item) => item.harnessId === CLAUDE11);
24126
25225
  if (claude !== void 0 && claude.state !== "absent") {
24127
25226
  report.instructions.push(...await claudeInstructionFiles(context));
24128
25227
  }
@@ -24174,16 +25273,16 @@ async function runContext(context) {
24174
25273
  ]
24175
25274
  });
24176
25275
  }
24177
- var CLAUDE10, CODEX9, CONTEXT_HARNESSES;
25276
+ var CLAUDE11, CODEX10, CONTEXT_HARNESSES;
24178
25277
  var init_context_cost2 = __esm({
24179
25278
  "apps/cli/dist/src/commands/context-cost.js"() {
24180
25279
  "use strict";
24181
25280
  init_src3();
24182
25281
  init_src();
24183
25282
  init_context_owner_candidates();
24184
- CLAUDE10 = harnessId("claude");
24185
- CODEX9 = harnessId("codex");
24186
- CONTEXT_HARNESSES = /* @__PURE__ */ new Set([CLAUDE10, CODEX9]);
25283
+ CLAUDE11 = harnessId("claude");
25284
+ CODEX10 = harnessId("codex");
25285
+ CONTEXT_HARNESSES = /* @__PURE__ */ new Set([CLAUDE11, CODEX10]);
24187
25286
  }
24188
25287
  });
24189
25288
 
@@ -24204,7 +25303,7 @@ function stringArray(value3) {
24204
25303
  return array(value3).filter((item) => typeof item === "string");
24205
25304
  }
24206
25305
  function normalizedHarness(value3) {
24207
- return value3 === "claude" ? CLAUDE11 : value3 === "codex" ? CODEX10 : null;
25306
+ return value3 === "claude" ? CLAUDE12 : value3 === "codex" ? CODEX11 : null;
24208
25307
  }
24209
25308
  function totals(row2) {
24210
25309
  const inputTokens = number(row2["inputTokens"]);
@@ -24512,7 +25611,7 @@ async function runHistory(context) {
24512
25611
  const filterHarness = context.harness;
24513
25612
  const daily = dailyRows(payload).filter((row2) => filterHarness === null || row2.harnessId === filterHarness).sort((left, right) => left.period.localeCompare(right.period));
24514
25613
  const sessions = sessionRows(payload).filter((row2) => filterHarness === null || row2.harnessId === filterHarness).sort((left, right) => (left.lastActivity ?? "").localeCompare(right.lastActivity ?? ""));
24515
- const harnesses = [CLAUDE11, CODEX10].filter((harness) => filterHarness === null || harness === filterHarness).map((harness) => summarize(harness, daily, sessions, context.now()));
25614
+ const harnesses = [CLAUDE12, CODEX11].filter((harness) => filterHarness === null || harness === filterHarness).map((harness) => summarize(harness, daily, sessions, context.now()));
24516
25615
  const report = {
24517
25616
  ...blankReport(context, window.windowStart, window.windowEnd, "available", version3, []),
24518
25617
  daily,
@@ -24525,15 +25624,15 @@ async function runHistory(context) {
24525
25624
  data: report
24526
25625
  });
24527
25626
  }
24528
- var SUPPORTED_CCUSAGE_MAJOR, CLAUDE11, CODEX10, HISTORY_HARNESSES;
25627
+ var SUPPORTED_CCUSAGE_MAJOR, CLAUDE12, CODEX11, HISTORY_HARNESSES;
24529
25628
  var init_history2 = __esm({
24530
25629
  "apps/cli/dist/src/commands/history.js"() {
24531
25630
  "use strict";
24532
25631
  init_src();
24533
25632
  SUPPORTED_CCUSAGE_MAJOR = 20;
24534
- CLAUDE11 = harnessId("claude");
24535
- CODEX10 = harnessId("codex");
24536
- HISTORY_HARNESSES = /* @__PURE__ */ new Set([CLAUDE11, CODEX10]);
25633
+ CLAUDE12 = harnessId("claude");
25634
+ CODEX11 = harnessId("codex");
25635
+ HISTORY_HARNESSES = /* @__PURE__ */ new Set([CLAUDE12, CODEX11]);
24537
25636
  }
24538
25637
  });
24539
25638
 
@@ -25336,7 +26435,7 @@ function admitOutcomePolicy(advice, observation, diagnostics) {
25336
26435
  async function appendCodexNativePolicy(context, actions, diagnostics) {
25337
26436
  if (context.nativePolicy !== true)
25338
26437
  return;
25339
- if (context.harness !== null && context.harness !== CODEX11) {
26438
+ if (context.harness !== null && context.harness !== CODEX12) {
25340
26439
  diagnostics.push(diagnostic({
25341
26440
  severity: "warning",
25342
26441
  code: "native-policy-harness-unsupported",
@@ -25346,16 +26445,16 @@ async function appendCodexNativePolicy(context, actions, diagnostics) {
25346
26445
  }));
25347
26446
  return;
25348
26447
  }
25349
- const nativeContext = { ...context, harness: CODEX11 };
26448
+ const nativeContext = { ...context, harness: CODEX12 };
25350
26449
  const optimization = await runOptimize(nativeContext);
25351
26450
  const contextResult = await runContext(nativeContext);
25352
- const advice = optimization.data?.harnesses.find((item) => item.harnessId === CODEX11) ?? null;
25353
- const observation = contextResult.data?.harnesses.find((item) => item.harnessId === CODEX11) ?? null;
26451
+ const advice = optimization.data?.harnesses.find((item) => item.harnessId === CODEX12) ?? null;
26452
+ const observation = contextResult.data?.harnesses.find((item) => item.harnessId === CODEX12) ?? null;
25354
26453
  if (advice === null || observation === null || observation.managedConfigTarget === null) {
25355
26454
  diagnostics.push(diagnostic({
25356
26455
  severity: "warning",
25357
26456
  code: "codex-native-policy-unavailable",
25358
- subject: CODEX11,
26457
+ subject: CODEX12,
25359
26458
  message: "Codex optimizer advice could not be paired with a versioned native user-config target",
25360
26459
  remediation: "Run token-harness context --harness codex and keep native policy advisory until the target is observable"
25361
26460
  }));
@@ -25375,7 +26474,7 @@ async function appendCodexNativePolicy(context, actions, diagnostics) {
25375
26474
  diagnostics.push(diagnostic({
25376
26475
  severity: "warning",
25377
26476
  code: "codex-native-policy-observation-drift",
25378
- subject: CODEX11,
26477
+ subject: CODEX12,
25379
26478
  message: `${input.keyPath} changed between optimizer observation (${String(input.adviceCurrent)}) and native-plan observation (${String(input.observedCurrent)})`,
25380
26479
  remediation: "Re-run token-harness plan --native-policy so recommendation and config precondition come from a stable state"
25381
26480
  }));
@@ -25385,7 +26484,7 @@ async function appendCodexNativePolicy(context, actions, diagnostics) {
25385
26484
  diagnostics.push(diagnostic({
25386
26485
  severity: "warning",
25387
26486
  code: "codex-native-policy-origin-unavailable",
25388
- subject: CODEX11,
26487
+ subject: CODEX12,
25389
26488
  message: `Codex did not expose origin metadata for ${input.keyPath}, so it will not be managed`,
25390
26489
  remediation: "Keep this recommendation advisory rather than guessing config precedence"
25391
26490
  }));
@@ -25396,7 +26495,7 @@ async function appendCodexNativePolicy(context, actions, diagnostics) {
25396
26495
  diagnostics.push(diagnostic({
25397
26496
  severity: "warning",
25398
26497
  code: "codex-native-policy-shadowed",
25399
- subject: CODEX11,
26498
+ subject: CODEX12,
25400
26499
  message: `${input.keyPath} currently comes from Codex layer ${origin.sourceType}` + (origin.profile === null ? "" : ` profile ${origin.profile}`) + ", not from the writable base user layer",
25401
26500
  path: origin.path,
25402
26501
  remediation: "Leave the project/profile-owned value untouched; change that scope explicitly if desired"
@@ -25408,7 +26507,7 @@ async function appendCodexNativePolicy(context, actions, diagnostics) {
25408
26507
  diagnostics.push(diagnostic({
25409
26508
  severity: "warning",
25410
26509
  code: "codex-native-model-unproven",
25411
- subject: CODEX11,
26510
+ subject: CODEX12,
25412
26511
  message: "A managed Codex model change requires the learned model candidate and a complete native catalog",
25413
26512
  remediation: "Keep the model recommendation advisory until RFC 0018 evidence and the complete catalog agree"
25414
26513
  }));
@@ -25419,7 +26518,7 @@ async function appendCodexNativePolicy(context, actions, diagnostics) {
25419
26518
  diagnostics.push(diagnostic({
25420
26519
  severity: "warning",
25421
26520
  code: "codex-native-model-reference-ambiguous",
25422
- subject: CODEX11,
26521
+ subject: CODEX12,
25423
26522
  message: "The learned Codex model recommendation does not resolve uniquely in the current native catalog",
25424
26523
  remediation: "Re-run the plan after the Codex model catalog is stable"
25425
26524
  }));
@@ -25539,6 +26638,8 @@ async function computePlan(context) {
25539
26638
  providers,
25540
26639
  rules: [...COMPATIBILITY_RULES],
25541
26640
  observedVersions: versions.providers,
26641
+ observedHarnessVersions: versions.harnesses,
26642
+ platform: { os: context.platform.os, wsl: context.platform.isWsl },
25542
26643
  harness: context.harness
25543
26644
  });
25544
26645
  const actions = [];
@@ -25643,6 +26744,41 @@ async function computePlan(context) {
25643
26744
  }
25644
26745
  }
25645
26746
  }
26747
+ if (context.agentRouting === true || context.disableAgentRouting === true) {
26748
+ const harness = context.harness;
26749
+ if (harness !== harnessId("claude") && harness !== CODEX12) {
26750
+ diagnostics.push(diagnostic({
26751
+ severity: "warning",
26752
+ code: "prompt-routing-harness-required",
26753
+ subject: harness,
26754
+ message: "Automatic prompt routing requires an explicit Claude Code or Codex harness",
26755
+ remediation: "Choose the detected agent in the guided app, or pass --harness claude|codex"
26756
+ }));
26757
+ } else if (context.adapters === null) {
26758
+ diagnostics.push(diagnostic({
26759
+ severity: "warning",
26760
+ code: "prompt-routing-adapters-unavailable",
26761
+ subject: harness,
26762
+ message: "The native prompt hook could not be planned without filesystem adapters",
26763
+ remediation: "Refresh Token Harness from a supported local environment"
26764
+ }));
26765
+ } else {
26766
+ const input = {
26767
+ fs: context.adapters.fs,
26768
+ home: context.home,
26769
+ harness,
26770
+ version: versions.harnesses[harness] ?? null,
26771
+ runner: context.adapters.runner,
26772
+ facts: context.platform,
26773
+ paths: context.adapters.paths,
26774
+ projectRoot: context.projectRoot,
26775
+ stateRoot: context.stateRoot
26776
+ };
26777
+ const routingPlan = context.agentRouting ? await planNativePromptRoutingInstall(input) : await planNativePromptRoutingRemoval(input);
26778
+ actions.push(...routingPlan.actions);
26779
+ diagnostics.push(...routingPlan.diagnostics);
26780
+ }
26781
+ }
25646
26782
  if (context.nativePolicy === true && context.harness === harnessId("claude")) {
25647
26783
  if (context.taskClass === void 0 || context.taskClass === null) {
25648
26784
  diagnostics.push(diagnostic({
@@ -25818,18 +26954,19 @@ function planExitCode(counts) {
25818
26954
  return EXIT_CODES["blocked-by-conflict"];
25819
26955
  return EXIT_CODES.ok;
25820
26956
  }
25821
- var DEFAULT_PROFILE, CODEX11;
26957
+ var DEFAULT_PROFILE, CODEX12;
25822
26958
  var init_plan2 = __esm({
25823
26959
  "apps/cli/dist/src/commands/plan.js"() {
25824
26960
  "use strict";
25825
26961
  init_src3();
25826
26962
  init_src();
25827
26963
  init_agent_skill();
26964
+ init_prompt_router();
25828
26965
  init_apply();
25829
26966
  init_context_cost2();
25830
26967
  init_optimize();
25831
26968
  DEFAULT_PROFILE = "safe";
25832
- CODEX11 = harnessId("codex");
26969
+ CODEX12 = harnessId("codex");
25833
26970
  }
25834
26971
  });
25835
26972
 
@@ -25901,6 +27038,48 @@ async function verifyManagedIntegrationPostconditions(context, integrations) {
25901
27038
  }
25902
27039
  return diagnostics;
25903
27040
  }
27041
+ async function verifyNativePromptRoutingPostconditions(context, actions) {
27042
+ const routing = actions.filter((action) => action.id.startsWith("native-prompt-routing:"));
27043
+ if (routing.length === 0)
27044
+ return [];
27045
+ if (context.adapters === null || context.stateRoot === null || context.harness !== harnessId("claude") && context.harness !== harnessId("codex")) {
27046
+ return [
27047
+ diagnostic({
27048
+ severity: "error",
27049
+ code: "prompt-routing-postcondition-unavailable",
27050
+ subject: context.harness,
27051
+ message: "Native prompt-routing configuration could not be read after the change",
27052
+ remediation: "Keep the transaction rollback and review a fresh plan from the local agent environment"
27053
+ })
27054
+ ];
27055
+ }
27056
+ const observed = await observeNativePromptRouting({
27057
+ fs: context.adapters.fs,
27058
+ home: context.home,
27059
+ stateRoot: context.stateRoot,
27060
+ harness: context.harness,
27061
+ version: null,
27062
+ runner: context.adapters.runner,
27063
+ facts: context.platform,
27064
+ paths: context.adapters.paths,
27065
+ projectRoot: context.projectRoot,
27066
+ projectId: context.adapters.projectIdFor(context.projectRoot)
27067
+ });
27068
+ const shouldBeEnabled = routing.some((action) => action.id.includes(":enable:"));
27069
+ const satisfied = shouldBeEnabled ? observed.configured === true : observed.configured === false;
27070
+ if (satisfied)
27071
+ return [];
27072
+ return [
27073
+ diagnostic({
27074
+ severity: "error",
27075
+ code: "prompt-routing-postcondition-unmet",
27076
+ subject: context.harness,
27077
+ path: observed.configPath,
27078
+ message: `Native prompt-routing hooks were not observed in the requested state after the change: ${observed.label}`,
27079
+ remediation: "Review the hook settings and allow the transaction to restore its backup"
27080
+ })
27081
+ ];
27082
+ }
25904
27083
  function transactionIdFor(planId, at) {
25905
27084
  const digest = digestText(`${planId} ${at}`);
25906
27085
  return digest.slice(digest.indexOf(":") + 1, digest.indexOf(":") + 13);
@@ -25967,6 +27146,8 @@ async function runApply(context) {
25967
27146
  const diagnostics = [];
25968
27147
  let stored = null;
25969
27148
  let storedAgentSkill = false;
27149
+ let storedAgentRouting = false;
27150
+ let storedAgentRoutingRemoval = false;
25970
27151
  let planningContext = context;
25971
27152
  const rejectedReport = () => ({
25972
27153
  ...emptyReport3("rejected"),
@@ -26020,11 +27201,15 @@ async function runApply(context) {
26020
27201
  return finish3("rejected", EXIT_CODES["precondition-drift"], rejectedReport(), diagnostics);
26021
27202
  }
26022
27203
  storedAgentSkill = stored.actions.some((action) => action.id.startsWith("agent-skill:"));
27204
+ storedAgentRouting = stored.actions.some((action) => action.id.startsWith("native-prompt-routing:") && action.id.includes(":enable:"));
27205
+ storedAgentRoutingRemoval = stored.actions.some((action) => action.id.startsWith("native-prompt-routing:") && action.id.includes(":disable:"));
26023
27206
  planningContext = {
26024
27207
  ...context,
26025
27208
  harness: stored.harness,
26026
27209
  provider,
26027
- agentSkill: storedAgentSkill
27210
+ agentSkill: storedAgentSkill,
27211
+ agentRouting: storedAgentRouting,
27212
+ disableAgentRouting: storedAgentRoutingRemoval
26028
27213
  };
26029
27214
  } catch {
26030
27215
  diagnostics.push(diagnostic({
@@ -26048,6 +27233,16 @@ async function runApply(context) {
26048
27233
  }));
26049
27234
  return finish3("rejected", EXIT_CODES["precondition-drift"], rejectedReport(), diagnostics);
26050
27235
  }
27236
+ if (stored !== null && (storedAgentRouting || storedAgentRoutingRemoval) && computed.report.planId !== stored.planId) {
27237
+ diagnostics.push(diagnostic({
27238
+ severity: "error",
27239
+ code: "prompt-routing-plan-drift",
27240
+ subject: stored.harness,
27241
+ message: "The native prompt-routing target or ownership changed after the reviewed preview",
27242
+ remediation: "Review a fresh prompt-routing preview; nothing was written"
27243
+ }));
27244
+ return finish3("rejected", EXIT_CODES["precondition-drift"], rejectedReport(), diagnostics);
27245
+ }
26051
27246
  if (computed.blocked.length > 0 && computed.report.actions.length === 0) {
26052
27247
  return finish3("rejected", EXIT_CODES["unsupported-environment"], rejectedReport(), diagnostics);
26053
27248
  }
@@ -26151,7 +27346,10 @@ async function runApply(context) {
26151
27346
  // RFC 0004 §Process policy: an installer reaches the machine through the runner or not at all.
26152
27347
  runner: context.adapters.runner,
26153
27348
  now: context.now,
26154
- verifyPostconditions: async () => verifyManagedIntegrationPostconditions(context, computed.managedIntegrations)
27349
+ verifyPostconditions: async () => [
27350
+ ...await verifyManagedIntegrationPostconditions(context, computed.managedIntegrations),
27351
+ ...await verifyNativePromptRoutingPostconditions(context, actions)
27352
+ ]
26155
27353
  });
26156
27354
  diagnostics.push(...transaction.diagnostics);
26157
27355
  const report = {
@@ -26187,6 +27385,7 @@ var init_apply = __esm({
26187
27385
  "use strict";
26188
27386
  init_src();
26189
27387
  init_src3();
27388
+ init_prompt_router();
26190
27389
  init_candidate_lifecycle();
26191
27390
  init_plan2();
26192
27391
  init_snapshot_safety();
@@ -26486,6 +27685,18 @@ async function runBenchmarkStart(context) {
26486
27685
  runContext(observedContext),
26487
27686
  runHistory({ ...observedContext, since: "1d", until: null })
26488
27687
  ]);
27688
+ const nativeRoutingAtStart = context.adapters === null ? null : await nativeRoutingObservationForBenchmark({
27689
+ fs: context.adapters.fs,
27690
+ home: context.home,
27691
+ stateRoot: context.stateRoot,
27692
+ harness,
27693
+ version: null,
27694
+ runner: context.adapters.runner,
27695
+ facts: context.platform,
27696
+ paths: context.adapters.paths,
27697
+ projectRoot: context.projectRoot,
27698
+ projectId
27699
+ });
26489
27700
  const budget = budgetResult.data?.harnesses.find((item) => item.harnessId === harness);
26490
27701
  const contextObservation = contextResult.data?.harnesses.find((item) => item.harnessId === harness);
26491
27702
  const policy = benchmarkPolicySnapshot(contextObservation);
@@ -26504,7 +27715,8 @@ async function runBenchmarkStart(context) {
26504
27715
  startedAt,
26505
27716
  usageBefore: budget?.windows ?? [],
26506
27717
  contextAtStart,
26507
- localSessionsBefore
27718
+ localSessionsBefore,
27719
+ nativeRoutingAtStart
26508
27720
  };
26509
27721
  if (!await writeJson(context, paths.capturePath, capture)) {
26510
27722
  return commandResult({
@@ -26689,6 +27901,19 @@ async function runBenchmarkFinish(context) {
26689
27901
  runContext(completedContext),
26690
27902
  runHistory({ ...completedContext, since: "1d", until: null })
26691
27903
  ]);
27904
+ const nativeRoutingAtFinish = context.adapters === null ? null : await nativeRoutingObservationForBenchmark({
27905
+ fs: context.adapters.fs,
27906
+ home: context.home,
27907
+ stateRoot: context.stateRoot,
27908
+ harness: parsed.capture.harnessId,
27909
+ version: null,
27910
+ runner: context.adapters.runner,
27911
+ facts: context.platform,
27912
+ paths: context.adapters.paths,
27913
+ projectRoot: context.projectRoot,
27914
+ projectId,
27915
+ startedAt: parsed.capture.startedAt
27916
+ });
26692
27917
  const budget = budgetResult.data?.harnesses.find((item) => item.harnessId === parsed.capture.harnessId);
26693
27918
  const localUsage = parsed.capture.localSessionsBefore !== null && historyResult.data?.source.state === "available" ? deriveTaskLocalUsage(parsed.capture.localSessionsBefore, snapshotTaskLocalSessions(historyResult.data.sessions), parsed.capture.startedAt, completedAt) : null;
26694
27919
  const finishContextObservation = contextResult.data?.harnesses.find((item) => item.harnessId === parsed.capture.harnessId);
@@ -26700,7 +27925,8 @@ async function runBenchmarkFinish(context) {
26700
27925
  failedAttempts,
26701
27926
  localUsage,
26702
27927
  contextAtFinish: taskBenchmarkContextSnapshot(finishContextObservation),
26703
- policyAtFinish: benchmarkPolicySnapshot(finishContextObservation)
27928
+ policyAtFinish: benchmarkPolicySnapshot(finishContextObservation),
27929
+ nativeRoutingAtFinish
26704
27930
  });
26705
27931
  if (!completed.ok) {
26706
27932
  return commandResult({
@@ -26749,7 +27975,7 @@ async function runBenchmarkFinish(context) {
26749
27975
  ]
26750
27976
  });
26751
27977
  }
26752
- var CLAUDE12, CODEX12, CAPTURE_HARNESSES;
27978
+ var CLAUDE13, CODEX13, CAPTURE_HARNESSES;
26753
27979
  var init_benchmark_capture = __esm({
26754
27980
  "apps/cli/dist/src/commands/benchmark-capture.js"() {
26755
27981
  "use strict";
@@ -26757,9 +27983,10 @@ var init_benchmark_capture = __esm({
26757
27983
  init_budget2();
26758
27984
  init_context_cost2();
26759
27985
  init_history2();
26760
- CLAUDE12 = harnessId("claude");
26761
- CODEX12 = harnessId("codex");
26762
- CAPTURE_HARNESSES = /* @__PURE__ */ new Set([CLAUDE12, CODEX12]);
27986
+ init_prompt_router();
27987
+ CLAUDE13 = harnessId("claude");
27988
+ CODEX13 = harnessId("codex");
27989
+ CAPTURE_HARNESSES = /* @__PURE__ */ new Set([CLAUDE13, CODEX13]);
26763
27990
  }
26764
27991
  });
26765
27992
 
@@ -28546,10 +29773,12 @@ async function runStatus(context) {
28546
29773
  const harnessAdapters = listHarnessAdapters().filter((adapter) => context.harness === null || adapter.manifest.id === context.harness);
28547
29774
  const present = [];
28548
29775
  const configs = [];
29776
+ const observedHarnessVersions = {};
28549
29777
  for (const adapter of harnessAdapters) {
28550
29778
  const detection = await adapter.detect(detectionContext);
28551
29779
  if (detection.state === "absent")
28552
29780
  continue;
29781
+ observedHarnessVersions[adapter.manifest.id] = detection.version;
28553
29782
  present.push(adapter.manifest);
28554
29783
  const inspection = await adapter.inspect(detectionContext);
28555
29784
  configs.push(...inspection.summaries);
@@ -28580,6 +29809,8 @@ async function runStatus(context) {
28580
29809
  providers,
28581
29810
  rules: [...COMPATIBILITY_RULES],
28582
29811
  observedVersions,
29812
+ observedHarnessVersions,
29813
+ platform: { os: context.platform.os, wsl: context.platform.isWsl },
28583
29814
  harness: context.harness
28584
29815
  });
28585
29816
  if (context.stateRoot !== null) {
@@ -29189,6 +30420,38 @@ var init_rollback = __esm({
29189
30420
  }
29190
30421
  });
29191
30422
 
30423
+ // apps/cli/dist/src/commands/verify-status.js
30424
+ function harnessesForVerification(selected, configured, present) {
30425
+ if (selected !== null)
30426
+ return present.includes(selected) ? [selected] : [];
30427
+ return configured.length > 0 ? [...configured] : [...present];
30428
+ }
30429
+ function statusFor(achieved, declared, checks = []) {
30430
+ const canaryNotExercised = checks.some((check) => (check.id === "canary-intercepted" || check.id.startsWith("rtk-attribution-")) && (check.status === "not-exercised" || check.status === "info" && check.achievedTier === null));
30431
+ const noObservedOutcome = checks.length > 0 && checks.some((check) => check.status === "not-exercised") && checks.every((check) => check.status === "not-exercised" || check.status === "info");
30432
+ if (canaryNotExercised || noObservedOutcome)
30433
+ return "not-applicable";
30434
+ const order = ["presence", "config-only", "canary", "live-receipt"];
30435
+ if (achieved === null)
30436
+ return "not-applicable";
30437
+ const reached = order.indexOf(achieved);
30438
+ const promised = order.indexOf(declared);
30439
+ if (reached < 0 || promised < 0)
30440
+ return "not-applicable";
30441
+ return reached >= promised ? "healthy" : "degraded";
30442
+ }
30443
+ function allResultsAtDeclaredTier(results) {
30444
+ return results.every((result6) => result6.status === "healthy");
30445
+ }
30446
+ function verificationHasProblems(results, failedCheckCount) {
30447
+ return failedCheckCount > 0 || results.some((result6) => result6.status === "degraded" || result6.status === "failed");
30448
+ }
30449
+ var init_verify_status = __esm({
30450
+ "apps/cli/dist/src/commands/verify-status.js"() {
30451
+ "use strict";
30452
+ }
30453
+ });
30454
+
29192
30455
  // apps/cli/dist/src/commands/verify.js
29193
30456
  async function runVerify(context) {
29194
30457
  const diagnostics = [];
@@ -29256,18 +30519,14 @@ async function runVerify(context) {
29256
30519
  continue;
29257
30520
  const verification = await adapter.verify(providerContext4);
29258
30521
  diagnostics.push(...verification.diagnostics);
29259
- const harnesses = detection.configuredHarnesses.length > 0 ? detection.configuredHarnesses : (
29260
- // Installed but wired to nothing: still worth a row, on every present harness, because
29261
- // "installed and not connected here" is the finding.
29262
- presentHarnesses
29263
- );
30522
+ const harnesses = harnessesForVerification(context.harness, detection.configuredHarnesses, presentHarnesses);
29264
30523
  for (const harnessId2 of harnesses) {
29265
30524
  const declaredTier = adapter.manifest.harnesses.find((entry) => entry.harness === harnessId2)?.verificationTier ?? verification.declaredTier;
29266
30525
  const scopedVerification = await scopeProviderVerificationToHarness(providerContext4, verification, harnessId2, detection.configuredHarnesses);
29267
30526
  results.push({
29268
30527
  providerId: adapter.manifest.id,
29269
30528
  harnessId: harnessId2,
29270
- status: statusFor(scopedVerification.achievedTier, declaredTier),
30529
+ status: statusFor(scopedVerification.achievedTier, declaredTier, scopedVerification.checks),
29271
30530
  declaredTier,
29272
30531
  managedByTokenHarness: managedIntegrations.has(`${adapter.manifest.id}\0${harnessId2}`),
29273
30532
  providerManagedByTokenHarness: detection.managedByTokenHarness,
@@ -29278,15 +30537,16 @@ async function runVerify(context) {
29278
30537
  const receipts = context.metrics === null ? [] : await readReceipts(context);
29279
30538
  const latest = receipts[0] ?? null;
29280
30539
  const failures = results.flatMap((result6) => result6.checks.filter(contributesToProblems));
30540
+ const hasProblems = verificationHasProblems(results, failures.length);
29281
30541
  const report = {
29282
30542
  receiptId: latest?.receiptId ?? null,
29283
30543
  appliedAt: latest?.appliedAt ?? null,
29284
30544
  results,
29285
- healthyAtDeclaredTier: failures.length === 0
30545
+ healthyAtDeclaredTier: allResultsAtDeclaredTier(results)
29286
30546
  };
29287
30547
  return commandResult({
29288
30548
  command: "verify",
29289
- exitCode: failures.length === 0 ? EXIT_CODES.ok : EXIT_CODES["problems-found"],
30549
+ exitCode: hasProblems ? EXIT_CODES["problems-found"] : EXIT_CODES.ok,
29290
30550
  data: report,
29291
30551
  diagnostics
29292
30552
  });
@@ -29323,21 +30583,12 @@ async function readReceipts(context) {
29323
30583
  return [];
29324
30584
  }
29325
30585
  }
29326
- function statusFor(achieved, declared) {
29327
- const order = ["presence", "config-only", "canary", "live-receipt"];
29328
- if (achieved === null)
29329
- return "not-applicable";
29330
- const reached = order.indexOf(achieved);
29331
- const promised = order.indexOf(declared);
29332
- if (reached < 0 || promised < 0)
29333
- return "not-applicable";
29334
- return reached >= promised ? "healthy" : "degraded";
29335
- }
29336
30586
  var init_verify = __esm({
29337
30587
  "apps/cli/dist/src/commands/verify.js"() {
29338
30588
  "use strict";
29339
30589
  init_src3();
29340
30590
  init_src();
30591
+ init_verify_status();
29341
30592
  }
29342
30593
  });
29343
30594
 
@@ -32473,8 +33724,18 @@ function renderVerifyReport(report, _context) {
32473
33724
  if (report.healthyAtDeclaredTier) {
32474
33725
  lines.push("Healthy at the declared tier for every provider.");
32475
33726
  } else {
32476
- const failures = report.results.flatMap((result6) => result6.checks).filter((check) => check.status === "fail").length;
32477
- lines.push(`${String(failures)} ${pluralize(failures, "check")} below tier. Not proven.`);
33727
+ const belowTier = report.results.filter((result6) => result6.status === "degraded" || result6.status === "failed").length;
33728
+ const notProven = report.results.filter((result6) => result6.status === "not-applicable").length;
33729
+ const failedChecks = report.results.flatMap((result6) => result6.checks).filter((check) => check.status === "fail").length;
33730
+ if (belowTier > 0) {
33731
+ lines.push(`${String(belowTier)} ${pluralize(belowTier, "provider\u2013harness integration")} below declared tier.`);
33732
+ }
33733
+ if (failedChecks > 0) {
33734
+ lines.push(`${String(failedChecks)} ${pluralize(failedChecks, "check")} failed.`);
33735
+ }
33736
+ if (notProven > 0) {
33737
+ lines.push(`${String(notProven)} ${pluralize(notProven, "provider\u2013harness integration")} not proven yet.`);
33738
+ }
32478
33739
  }
32479
33740
  return document(lines);
32480
33741
  }
@@ -33338,12 +34599,19 @@ not-exercised, which is not a failure.`,
33338
34599
 
33339
34600
  Usage
33340
34601
  token-harness plan [--json] [--harness <id>] [--provider <id>] [--project <dir>]
34602
+ [--agent-routing | --disable-agent-routing]
33341
34603
  [--native-policy] [--task <class>] [--profile <name>]
33342
34604
  [--reserve <0-95>] [--tasks-left <n>]
33343
34605
 
33344
34606
  Read-only. Exits 0 when a plan was produced, and 4 when a hard conflict prevents
33345
34607
  apply. Nothing is changed either way.
33346
34608
 
34609
+ --agent-routing adds the native per-prompt hook for the selected Claude Code or Codex
34610
+ harness. --disable-agent-routing removes only exact hook entries owned by Token Harness.
34611
+ Both changes use the normal stored-plan, approval, verification and rollback path. Claude
34612
+ loads the change in a new session; Codex requires the user to review and trust the hook in
34613
+ /hooks. Configuration is shown separately from runtime callbacks in the guided app.
34614
+
33347
34615
  --native-policy adds reviewed Codex native settings derived from the same optimizer
33348
34616
  policy as token-harness optimize. This build manages reasoning effort and verbosity
33349
34617
  only. A field coming from project config or a selected profile is left untouched.
@@ -33562,6 +34830,8 @@ async function run(options) {
33562
34830
  nativePolicy: invocation.options.nativePolicy,
33563
34831
  env: options.env ?? {},
33564
34832
  agentSkill: invocation.options.agentSkill,
34833
+ agentRouting: invocation.options.agentRouting,
34834
+ disableAgentRouting: invocation.options.disableAgentRouting,
33565
34835
  since: invocation.options.since,
33566
34836
  until: invocation.options.until,
33567
34837
  planId: invocation.options.plan,
@@ -34052,6 +35322,48 @@ function allowanceEvidence(entries, scope, quality) {
34052
35322
  pairs: deltas.length
34053
35323
  };
34054
35324
  }
35325
+ function routedAllowanceEvidence(entries, scope) {
35326
+ const deltas = entries.flatMap((entry) => {
35327
+ const quota = entry.quota;
35328
+ if (quota === null || quota.scope !== scope || quota.confidence !== "authoritative")
35329
+ return [];
35330
+ return [quota.baselineDeltaUsedPercent - quota.optimizedDeltaUsedPercent];
35331
+ });
35332
+ const savedPercent = median2(deltas);
35333
+ return {
35334
+ state: savedPercent === null ? "not-measured" : "measured",
35335
+ scope,
35336
+ savedPercent: savedPercent === null ? null : roundOne(savedPercent),
35337
+ equivalentMinutes: scope === "five-hour" && savedPercent !== null ? roundOne(savedPercent * 3) : null,
35338
+ pairs: deltas.length
35339
+ };
35340
+ }
35341
+ function routingEvidence(entries) {
35342
+ const routed = entries.filter((entry) => entry.nativeRouting?.verdict === "attributed");
35343
+ const eligible = routed.filter((entry) => entry.nativeRouting?.qualityGatesPassed === true);
35344
+ const local = eligible.filter((entry) => entry.baselineLocalTokens !== null && entry.optimizedLocalTokens !== null);
35345
+ const baselineLocalTokens = local.length ? local.reduce((total, entry) => total + (entry.baselineLocalTokens ?? 0), 0) : null;
35346
+ const optimizedLocalTokens = local.length ? local.reduce((total, entry) => total + (entry.optimizedLocalTokens ?? 0), 0) : null;
35347
+ const savedLocalTokens = baselineLocalTokens === null || optimizedLocalTokens === null ? null : baselineLocalTokens - optimizedLocalTokens;
35348
+ const localTokenSavingPercent = baselineLocalTokens === null || optimizedLocalTokens === null || baselineLocalTokens <= 0 ? null : roundOne(savedLocalTokens / baselineLocalTokens * 100);
35349
+ const qualityBlockedPairs = routed.length - eligible.length;
35350
+ return {
35351
+ state: routed.length === 0 ? "not-measured" : eligible.length === 0 ? "blocked-by-quality" : "measured",
35352
+ pairs: eligible.length,
35353
+ qualityBlockedPairs,
35354
+ localPairs: local.length,
35355
+ baselineLocalTokens,
35356
+ optimizedLocalTokens,
35357
+ savedLocalTokens,
35358
+ localTokenSavingPercent,
35359
+ allowance5h: routedAllowanceEvidence(eligible, "five-hour"),
35360
+ allowance7d: routedAllowanceEvidence(eligible, "weekly"),
35361
+ reportedChildModels: [
35362
+ ...new Set(eligible.flatMap((entry) => entry.nativeRouting?.optimizedReportedModels ?? []))
35363
+ ],
35364
+ basis: routed.length === 0 ? "No paired benchmark currently proves that a native prompt hook ran and started a subagent." : eligible.length === 0 ? "Routing callbacks were observed, but all attributed pairs failed the quality gate; no savings are credited." : local.length > 0 || eligible.some((entry) => entry.quota?.confidence === "authoritative") ? "Exact local token counts and authoritative quota deltas are reported in separate units, only for attributed pairs that passed both quality gates." : "Routing was observed and both quality gates passed, but local token or authoritative quota usage was unavailable; no savings amount is inferred."
35365
+ };
35366
+ }
34055
35367
  function guidedValueEvidence(report) {
34056
35368
  const entries = report?.entries ?? [];
34057
35369
  const quality = qualityEvidence(entries);
@@ -34060,6 +35372,7 @@ function guidedValueEvidence(report) {
34060
35372
  allowance5h: allowanceEvidence(entries, "five-hour", quality),
34061
35373
  allowance7d: allowanceEvidence(entries, "weekly", quality),
34062
35374
  quality,
35375
+ routing: routingEvidence(entries),
34063
35376
  candidates: (report?.candidateEvidence ?? []).map((item) => ({ ...item })),
34064
35377
  apiCost: {
34065
35378
  state: "not-measured",
@@ -34304,7 +35617,7 @@ function guidanceView(id, observation) {
34304
35617
  ...observation.state === "absent" ? { action: { kind: "skill", label: "Enable in-session guidance", harness: id } } : {}
34305
35618
  };
34306
35619
  }
34307
- function agentRules(id, providers, context, guidance) {
35620
+ function agentRules(id, providers, context, guidance, promptRouting) {
34308
35621
  const observation = context?.harnesses.find((item) => item.harnessId === id);
34309
35622
  const reasoning = reasoningView(id, observation);
34310
35623
  return [
@@ -34354,6 +35667,29 @@ function agentRules(id, providers, context, guidance) {
34354
35667
  next: guidance?.state === "managed" ? "Keep coding normally. Ask the agent to use Token Harness when you want an explicit quota-aware check." : guidance?.state === "external" ? "The matching skill can be used as-is. Token Harness keeps it user-owned." : guidance?.state === "conflict" ? "Review the existing skill manually. Token Harness will not overwrite it." : "Enable this once, then keep coding normally. Ask the agent to use Token Harness for a task when you want an explicit check.",
34355
35668
  ...guidance?.action ? { action: guidance.action } : {}
34356
35669
  },
35670
+ {
35671
+ id: `${id}-prompt-routing`,
35672
+ title: "Automatic prompt routing",
35673
+ state: promptRouting?.label ?? "Not verified",
35674
+ mode: promptRouting?.state === "absent" ? "not-enabled" : promptRouting?.state === "managed" || promptRouting?.state === "external" ? "automatic" : "integration",
35675
+ what: promptRouting?.detail ?? "Adds a native prompt hook that supplies the routing policy on every submitted prompt.",
35676
+ why: "Eligible bounded work may use a cheaper native subagent. The root conversation model stays unchanged, and the model decides whether a native subagent is appropriate.",
35677
+ evidence: promptRouting?.promptSubmissions ? `${String(promptRouting.promptSubmissions)} prompt callback(s) and ${String(promptRouting.subagentsStarted)} subagent start(s) observed in the last 30 days. Actual child model is shown only when the harness reports it.` : promptRouting?.configured ? "The hook is configured, but no prompt callback has been observed yet. Configuration alone is not runtime proof." : "No runtime routing evidence has been recorded yet.",
35678
+ next: promptRouting?.state === "absent" ? "Enable routing once, restart or trust the hook if the harness requires it, then keep using prompts normally." : promptRouting?.state === "managed" ? "Routing is enabled. Disable it here if you want to stop injecting the policy on each prompt." : promptRouting?.state === "external" ? "This hook is user-owned. Token Harness can report it but will not remove it." : promptRouting?.detail ?? "Refresh to inspect the native prompt-hook state.",
35679
+ ...promptRouting?.state === "absent" ? {
35680
+ action: {
35681
+ kind: "routing-enable",
35682
+ label: "Enable automatic routing",
35683
+ harness: id
35684
+ }
35685
+ } : promptRouting?.state === "managed" ? {
35686
+ action: {
35687
+ kind: "routing-disable",
35688
+ label: "Disable automatic routing",
35689
+ harness: id
35690
+ }
35691
+ } : {}
35692
+ },
34357
35693
  {
34358
35694
  id: `${id}-mcp`,
34359
35695
  title: "Connected tools",
@@ -34587,11 +35923,13 @@ var init_guided = __esm({
34587
35923
  now;
34588
35924
  random;
34589
35925
  observeGuidance;
34590
- constructor(call, now, random, observeGuidance = null) {
35926
+ observeRouting;
35927
+ constructor(call, now, random, observeGuidance = null, observeRouting = null) {
34591
35928
  this.call = call;
34592
35929
  this.now = now;
34593
35930
  this.random = random;
34594
35931
  this.observeGuidance = observeGuidance;
35932
+ this.observeRouting = observeRouting;
34595
35933
  }
34596
35934
  status() {
34597
35935
  return {
@@ -34663,6 +36001,7 @@ var init_guided = __esm({
34663
36001
  const empty2 = () => ({ data: null, diagnostics: [], exitCode: 9 });
34664
36002
  let doctor = empty2(), budget = empty2(), context = empty2();
34665
36003
  let guidance;
36004
+ let promptRouting;
34666
36005
  const observe = async (id, args) => {
34667
36006
  let result6;
34668
36007
  try {
@@ -34680,7 +36019,7 @@ var init_guided = __esm({
34680
36019
  loading.agents = this.agentView(doctor, budget, context, {
34681
36020
  rules: loading.stages.find((item) => item.id === "rules")?.state !== "working",
34682
36021
  allowance: loading.stages.find((item) => item.id === "allowance")?.state !== "working"
34683
- }, guidance);
36022
+ }, guidance, promptRouting);
34684
36023
  };
34685
36024
  const [, , , metrics, status, benchmark] = await Promise.all([
34686
36025
  observe("agents", ["doctor"]).then((result6) => {
@@ -34707,6 +36046,29 @@ var init_guided = __esm({
34707
36046
  }
34708
36047
  }));
34709
36048
  }
36049
+ if (this.observeRouting !== null) {
36050
+ promptRouting = {};
36051
+ await Promise.all(["claude", "codex"].map(async (harness) => {
36052
+ try {
36053
+ promptRouting[harness] = await this.observeRouting(harness);
36054
+ } catch {
36055
+ promptRouting[harness] = {
36056
+ harness,
36057
+ state: "unavailable",
36058
+ label: "Not verified",
36059
+ detail: "Native prompt-hook status could not be checked.",
36060
+ configPath: null,
36061
+ configured: null,
36062
+ promptSubmissions: 0,
36063
+ subagentsStarted: 0,
36064
+ subagentsStopped: 0,
36065
+ reportedModels: [],
36066
+ lastObservedAt: null,
36067
+ receiptState: "unavailable"
36068
+ };
36069
+ }
36070
+ }));
36071
+ }
34710
36072
  updateAgents();
34711
36073
  }),
34712
36074
  observe("savings", [
@@ -34720,7 +36082,7 @@ var init_guided = __esm({
34720
36082
  observe("checks", ["status"]),
34721
36083
  observe("value", ["benchmark-matrix"])
34722
36084
  ]);
34723
- const agents = this.agentView(doctor, budget, context, { rules: true, allowance: true }, guidance);
36085
+ const agents = this.agentView(doctor, budget, context, { rules: true, allowance: true }, guidance, promptRouting);
34724
36086
  const notices = [];
34725
36087
  if (doctor.data === null)
34726
36088
  notices.push("The agent inventory could not be read. Check the local installation and refresh.");
@@ -34748,7 +36110,7 @@ var init_guided = __esm({
34748
36110
  notices
34749
36111
  };
34750
36112
  }
34751
- agentView(doctor, budget, context, complete2, guidance) {
36113
+ agentView(doctor, budget, context, complete2, guidance, promptRouting) {
34752
36114
  const present = (doctor.data?.harnesses ?? []).filter((item) => item.state !== "absent" && (item.harnessId === "claude" || item.harnessId === "codex"));
34753
36115
  return present.map((agent) => {
34754
36116
  const providers = (doctor.data?.providers ?? []).filter((provider) => provider.state === "configured" && provider.configuredHarnesses.includes(agent.harnessId)).map((p) => p.providerId);
@@ -34771,8 +36133,9 @@ var init_guided = __esm({
34771
36133
  effort: observed?.nativeEffort?.current ?? observed?.reasoningEffort ?? null,
34772
36134
  reasoning: reasoningView(agent.harnessId, observed),
34773
36135
  ...guidance?.[agent.harnessId] ? { guidance: guidance[agent.harnessId] } : {},
36136
+ ...promptRouting?.[agent.harnessId] ? { promptRouting: promptRouting[agent.harnessId] } : {},
34774
36137
  allowanceAction: allowanceAction(usage?.diagnostics ?? []),
34775
- rules: agentRules(agent.harnessId, providers, context.data, guidance?.[agent.harnessId]),
36138
+ rules: agentRules(agent.harnessId, providers, context.data, guidance?.[agent.harnessId], promptRouting?.[agent.harnessId]),
34776
36139
  allowance: (usage?.windows ?? []).map((window) => ({
34777
36140
  label: window.scope === "five-hour" ? "5-hour allowance" : `${window.scope} allowance`,
34778
36141
  remaining: window.remainingPercent,
@@ -34807,11 +36170,13 @@ var init_guided = __esm({
34807
36170
  "setup",
34808
36171
  "effort",
34809
36172
  "skill",
36173
+ "routing-enable",
36174
+ "routing-disable",
34810
36175
  "undo",
34811
36176
  "remove",
34812
36177
  "candidate-setup",
34813
36178
  "candidate-remove"
34814
- ].includes(action) || data["harness"] !== void 0 && !["claude", "codex"].includes(String(data["harness"])) || data["harnesses"] !== void 0 && !validHarnesses || data["harnesses"] !== void 0 && action !== "setup" || data["harnesses"] !== void 0 && data["harness"] !== void 0 || data["task"] !== void 0 && !TASKS.has(String(data["task"])) || data["provider"] !== void 0 && !["rtk", "harnesstrim", "mcptoon", "gitnexus", "headroom"].includes(String(data["provider"])) || data["candidate"] !== void 0 && !["mcptoon", "gitnexus"].includes(String(data["candidate"])) || action === "effort" && (data["harness"] === void 0 || data["task"] === void 0) || action === "skill" && data["harness"] === void 0 || action === "remove" && (data["provider"] === void 0 || data["harness"] !== void 0 || data["harnesses"] !== void 0 || data["task"] !== void 0 || data["candidate"] !== void 0) || data["provider"] !== void 0 && action !== "remove" && action !== "setup" || candidateAction && (data["candidate"] === void 0 || data["harness"] === void 0 || data["provider"] !== void 0 || data["task"] !== void 0) || !candidateAction && data["candidate"] !== void 0)
36179
+ ].includes(action) || data["harness"] !== void 0 && !["claude", "codex"].includes(String(data["harness"])) || data["harnesses"] !== void 0 && !validHarnesses || data["harnesses"] !== void 0 && action !== "setup" || data["harnesses"] !== void 0 && data["harness"] !== void 0 || data["task"] !== void 0 && !TASKS.has(String(data["task"])) || data["provider"] !== void 0 && !["rtk", "harnesstrim", "mcptoon", "gitnexus", "headroom"].includes(String(data["provider"])) || data["candidate"] !== void 0 && !["mcptoon", "gitnexus"].includes(String(data["candidate"])) || action === "effort" && (data["harness"] === void 0 || data["task"] === void 0) || action === "skill" && data["harness"] === void 0 || (action === "routing-enable" || action === "routing-disable") && data["harness"] === void 0 || action === "remove" && (data["provider"] === void 0 || data["harness"] !== void 0 || data["harnesses"] !== void 0 || data["task"] !== void 0 || data["candidate"] !== void 0) || data["provider"] !== void 0 && action !== "remove" && action !== "setup" || candidateAction && (data["candidate"] === void 0 || data["harness"] === void 0 || data["provider"] !== void 0 || data["task"] !== void 0) || !candidateAction && data["candidate"] !== void 0)
34815
36180
  throw new GuideError(400, "Choose a supported agent and action.");
34816
36181
  return this.exclusive(async () => {
34817
36182
  this.approval = null;
@@ -34999,13 +36364,17 @@ var init_guided = __esm({
34999
36364
  args.push("--provider", setupProvider);
35000
36365
  if (data["action"] === "skill") {
35001
36366
  args.push("--provider", "none", "--agent-skill");
36367
+ } else if (data["action"] === "routing-enable") {
36368
+ args.push("--provider", "none", "--agent-routing");
36369
+ } else if (data["action"] === "routing-disable") {
36370
+ args.push("--provider", "none", "--disable-agent-routing");
35002
36371
  } else if (data["action"] === "effort")
35003
36372
  args.push("--provider", "none", "--native-policy", "--task", String(data["task"]), "--profile", data["task"] === "mechanical" ? "economy" : data["task"] === "standard" ? "balanced" : "quality");
35004
36373
  const result6 = await this.call(args);
35005
36374
  const report = result6.data;
35006
36375
  if (report === null || result6.exitCode !== 0 || report.conflicts.length > 0 || report.actions.length === 0 || !report.persisted || report.planId === null) {
35007
36376
  const subject = setupProvider !== null ? `${name(agent.harnessId)} \xB7 ${name(setupProvider)}` : name(agent.harnessId);
35008
- notices.push(`${subject}: ${explainGuideIssue(result6.diagnostics, data["action"] === "effort" ? "No supported preference change is needed or available. Your current preference is kept." : data["action"] === "skill" ? "In-session guidance is already present, or an existing user-owned skill location was left untouched." : "No safe setup change is available for the current provider, agent version and platform.")}`);
36377
+ notices.push(`${subject}: ${explainGuideIssue(result6.diagnostics, data["action"] === "effort" ? "No supported preference change is needed or available. Your current preference is kept." : data["action"] === "skill" ? "In-session guidance is already present, or an existing user-owned skill location was left untouched." : data["action"] === "routing-enable" || data["action"] === "routing-disable" ? "No safe native prompt-routing change is available for the current harness, hook state and ownership evidence." : "No safe setup change is available for the current provider, agent version and platform.")}`);
35009
36378
  continue;
35010
36379
  }
35011
36380
  plans.push(report.planId);
@@ -35015,6 +36384,8 @@ var init_guided = __esm({
35015
36384
  description: "Installs one reviewed Token Harness Agent Skill in the standard user skill directory. It does not change model, login, billing, hooks, trust, or the current conversation.",
35016
36385
  files: 1
35017
36386
  });
36387
+ } else if (data["action"] === "routing-enable" || data["action"] === "routing-disable") {
36388
+ changes.push(...report.actions.map((action2) => describeChange(action2, agent.harnessId)));
35018
36389
  } else {
35019
36390
  changes.push(...report.actions.map((action2) => describeChange(action2, agent.harnessId)));
35020
36391
  }
@@ -35032,7 +36403,7 @@ var init_guided = __esm({
35032
36403
  plans,
35033
36404
  transactionId: null,
35034
36405
  provider: null,
35035
- description: data["action"] === "effort" ? "Task preference" : data["action"] === "skill" ? "In-session guidance" : "Integration setup",
36406
+ description: data["action"] === "effort" ? "Task preference" : data["action"] === "skill" ? "In-session guidance" : data["action"] === "routing-enable" || data["action"] === "routing-disable" ? "Automatic prompt routing" : "Integration setup",
35036
36407
  operation: "apply",
35037
36408
  network
35038
36409
  };
@@ -35044,7 +36415,7 @@ var init_guided = __esm({
35044
36415
  notices,
35045
36416
  expiresAt: id === null ? null : new Date(expires).toISOString(),
35046
36417
  network,
35047
- restart: data["action"] === "effort" || data["action"] === "skill"
36418
+ restart: data["action"] === "effort" || data["action"] === "skill" || data["action"] === "routing-enable" || data["action"] === "routing-disable"
35048
36419
  };
35049
36420
  });
35050
36421
  }
@@ -38034,6 +39405,31 @@ var init_guided_product_client = __esm({
38034
39405
  'caption',
38035
39406
  ),
38036
39407
  );
39408
+ const routing = agent.promptRouting;
39409
+ const routingCard = node('div', undefined, 'routing-feature');
39410
+ const routingHead = node('div', undefined, 'tool-head');
39411
+ routingHead.append(
39412
+ node('strong', 'Automatic prompt routing'),
39413
+ pill(routing?.label || 'Not verified', routing?.state === 'managed' ? 'good' : routing?.state === 'absent' ? '' : 'warn'),
39414
+ );
39415
+ routingCard.append(
39416
+ routingHead,
39417
+ node(
39418
+ 'p',
39419
+ routing?.detail || 'A native hook can inject the routing policy on every submitted prompt. Setup and runtime activity are tracked separately.',
39420
+ 'caption',
39421
+ ),
39422
+ );
39423
+ const routingActions = node('div', undefined, 'inline-actions');
39424
+ if (routing?.state === 'absent') {
39425
+ routingActions.append(actionButton('Enable routing', () => reviewPromptRouting(agent.id, true), 'secondary'));
39426
+ } else if (routing?.state === 'managed') {
39427
+ routingActions.append(actionButton('Disable routing', () => reviewPromptRouting(agent.id, false), 'secondary'));
39428
+ } else if (routing?.state === 'external') {
39429
+ routingActions.append(node('span', 'Managed elsewhere · left untouched', 'caption'));
39430
+ }
39431
+ if (routingActions.children.length) routingCard.append(routingActions);
39432
+ card.append(routingCard);
38037
39433
  if (baseline.unavailable.length) {
38038
39434
  const details = node('details', undefined, 'agent-details');
38039
39435
  details.append(node('summary', 'Connection limitations'));
@@ -38125,6 +39521,57 @@ var init_guided_product_client = __esm({
38125
39521
  });
38126
39522
  }
38127
39523
 
39524
+ function reviewPromptRouting(agentId, enabled) {
39525
+ if (busy) return;
39526
+ const run = modal((enabled ? 'Enable' : 'Disable') + ' automatic routing · ' + agentName(agentId));
39527
+ $('modal-content').append(
39528
+ messageBox(
39529
+ 'How this works',
39530
+ enabled
39531
+ ? 'Token Harness adds a native UserPromptSubmit hook that supplies a short routing policy on each prompt. The agent may delegate eligible bounded work to a lower-cost native subagent; the root model stays the same.'
39532
+ : 'Token Harness removes only the exact native routing entries it owns. User-edited or manually installed hooks remain untouched.',
39533
+ ),
39534
+ progress('Preparing a read-only plan', 'No harness settings change until you approve the exact preview.'),
39535
+ );
39536
+ $('modal-actions').append(modalClose('Cancel'));
39537
+ setBusy(true, false);
39538
+ ensureSession()
39539
+ .then(() => request('/api/preview', {
39540
+ action: enabled ? 'routing-enable' : 'routing-disable',
39541
+ harness: agentId,
39542
+ }))
39543
+ .then(data => {
39544
+ if (run !== modalRun || !$('modal').open) return;
39545
+ pendingTicket = data.ticket;
39546
+ $('modal-content').replaceChildren();
39547
+ for (const change of data.changes || []) {
39548
+ const item = node('article', undefined, 'preview-change');
39549
+ item.append(node('h3', change.title), node('p', change.description));
39550
+ $('modal-content').append(item);
39551
+ }
39552
+ if (!(data.changes || []).length)
39553
+ $('modal-content').append(messageBox('No change proposed', (data.notices || []).join(' ') || 'The current routing state or ownership evidence does not support a safe change.'));
39554
+ for (const notice of data.notices || []) $('modal-content').append(node('p', notice, 'notice-row'));
39555
+ $('modal-content').append(messageBox(
39556
+ agentId === 'codex' ? 'Codex trust step' : 'When it takes effect',
39557
+ agentId === 'codex'
39558
+ ? 'After Apply, review and trust the UserPromptSubmit hook in Codex using /hooks. Until a callback is observed, the dashboard will show it as configured but not runtime verified.'
39559
+ : 'After Apply, start a new Claude Code session. The dashboard will show configured state first and runtime activity after the next prompt callback.',
39560
+ 'safe',
39561
+ ));
39562
+ $('modal-actions').replaceChildren(modalClose(data.ticket ? 'Cancel' : 'Done'));
39563
+ if (data.ticket) $('modal-actions').append(actionButton(enabled ? 'Apply routing hook' : 'Remove owned routing hook', () => applyTicket(data.ticket)));
39564
+ })
39565
+ .catch(error => {
39566
+ if (run !== modalRun) return;
39567
+ $('modal-error').textContent = error.message;
39568
+ $('modal-error').hidden = false;
39569
+ })
39570
+ .finally(() => {
39571
+ if (run === modalRun) setBusy(false, false);
39572
+ });
39573
+ }
39574
+
38128
39575
  function reviewSetup(providerId = null) {
38129
39576
  if (busy) return;
38130
39577
  const choices = setupChoiceData(providerId);
@@ -38815,10 +40262,6 @@ var init_guided_product_client = __esm({
38815
40262
  node('strong', component?.configuredHarnesses?.length ? component.configuredHarnesses.map(agentName).join(', ') : 'No detected agent'),
38816
40263
  );
38817
40264
  const measured = rows.filter(row => row.providerId === id);
38818
- facts.append(
38819
- node('span', 'Recorded results'),
38820
- node('strong', measured.length ? measured.length + ' recorded result' + (measured.length === 1 ? '' : 's') : 'None in this period'),
38821
- );
38822
40265
  card.append(facts);
38823
40266
  if (!measured.length) {
38824
40267
  card.append(
@@ -38922,6 +40365,29 @@ var init_guided_product_client = __esm({
38922
40365
  metricCard('5h / 7d allowance', allowance.value, allowance.detail, allowance.cls),
38923
40366
  metricCard('Quality', quality.value, quality.detail, quality.cls),
38924
40367
  );
40368
+ const routed = current?.value?.routing;
40369
+ const quotaParts = [];
40370
+ if (routed?.allowance5h?.state === 'measured' && routed.allowance5h.savedPercent !== null)
40371
+ quotaParts.push(routed.allowance5h.savedPercent >= 0
40372
+ ? '5h saved ' + count(routed.allowance5h.savedPercent) + '%'
40373
+ : '5h use +' + count(Math.abs(routed.allowance5h.savedPercent)) + '%');
40374
+ if (routed?.allowance7d?.state === 'measured' && routed.allowance7d.savedPercent !== null)
40375
+ quotaParts.push(routed.allowance7d.savedPercent >= 0
40376
+ ? '7d saved ' + count(routed.allowance7d.savedPercent) + '%'
40377
+ : '7d use +' + count(Math.abs(routed.allowance7d.savedPercent)) + '%');
40378
+ const routingValue = routed?.state === 'blocked-by-quality'
40379
+ ? 'Not credited'
40380
+ : routed?.savedLocalTokens !== null && routed?.savedLocalTokens !== undefined
40381
+ ? (routed.savedLocalTokens >= 0
40382
+ ? count(routed.savedLocalTokens) + ' tokens saved' + (routed.localTokenSavingPercent === null ? '' : ' · ' + count(routed.localTokenSavingPercent) + '%')
40383
+ : count(Math.abs(routed.savedLocalTokens)) + ' tokens added' + (routed.localTokenSavingPercent === null ? '' : ' · ' + count(Math.abs(routed.localTokenSavingPercent)) + '%'))
40384
+ : quotaParts.length ? 'Allowance measured' : routed?.state === 'measured' ? 'Usage unavailable' : 'Not measured yet';
40385
+ const routingDetail = routed?.state === 'blocked-by-quality'
40386
+ ? routed.basis
40387
+ : (quotaParts.length ? quotaParts.join(' · ') + '. ' : '') +
40388
+ (routed?.pairs ? count(routed.pairs) + ' quality-passed routed pair(s). ' : '') +
40389
+ 'Local tokens and allowance percentages are separate measurements. Actual child model is not exposed by every harness hook.';
40390
+ $('result-summary').append(metricCard('Automatic routing', routingValue, routingDetail, routed?.state === 'measured' ? 'positive' : ''));
38925
40391
  renderResultOptimizers();
38926
40392
  renderResultAgents();
38927
40393
  renderSavings();
@@ -39069,6 +40535,7 @@ var init_guided_product_styles = __esm({
39069
40535
  .setup-step{margin:1.6rem 0}.step-heading{display:grid;grid-template-columns:34px 1fr;gap:.65rem;align-items:start;margin-bottom:.7rem}.step-number{display:grid;place-items:center;width:32px;height:32px;border-radius:9px;background:var(--accent);color:#fff;font-weight:900}.step-heading h2{margin:0}.step-heading p{margin:.2rem 0;color:var(--muted)}
39070
40536
  .connection-overview{display:grid;gap:.75rem}.connection-summary{display:flex;align-items:center;justify-content:space-between;gap:1rem;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:1rem}.connection-summary p{margin:.15rem 0 0}.connection-scroll{overflow-x:auto;border:1px solid var(--line);border-radius:var(--radius);background:var(--panel)}.connection-table{min-width:max(720px,100%)}.connection-row{display:grid;grid-template-columns:minmax(170px,1.25fr) repeat(var(--connection-columns),minmax(130px,1fr)) minmax(155px,.8fr);align-items:center;gap:.6rem;padding:.72rem .8rem;border-bottom:1px solid var(--line)}.connection-row:last-child{border-bottom:0}.connection-head{background:var(--panel-soft);color:var(--muted);font-size:.8rem}.connection-name{display:grid;gap:.12rem}.connection-cell,.connection-action{min-width:0}.connection-action{display:flex;justify-content:flex-end}.tool-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:.8rem}.candidate-comparison-toolbar{grid-column:1/-1;justify-content:flex-end;align-self:start}.tool-card{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:1rem;box-shadow:var(--shadow)}.tool-card.experimental{border-style:dashed}.tool-card.compact{box-shadow:none}.tool-card>p{color:var(--muted);margin:.65rem 0}.tool-head{display:flex;align-items:flex-start;justify-content:space-between;gap:.75rem}.tool-head h3{margin:0}.tool-facts{display:grid;grid-template-columns:auto 1fr;gap:.3rem .75rem;border-top:1px solid var(--line);border-bottom:1px solid var(--line);padding:.65rem 0;margin:.65rem 0}.tool-facts span{color:var(--muted);font-size:.8rem}.tool-facts strong{font-size:.85rem}
39071
40537
  .connection-role{max-width:28ch}.setup-choice-list{display:grid;gap:.55rem;margin:.9rem 0}.setup-choice-list h3{margin:.25rem 0 0}.setup-choice{display:grid;grid-template-columns:auto 1fr;align-items:start;gap:.7rem;padding:.8rem;border:1px solid var(--line);border-radius:12px;background:var(--panel);cursor:pointer}.setup-choice:hover{border-color:var(--accent);background:var(--accent-soft)}.setup-choice input{inline-size:1.1rem;block-size:1.1rem;margin:.15rem 0 0;accent-color:var(--accent)}.setup-choice-copy{display:grid;gap:.2rem}.setup-choice-limitation{color:var(--muted)}
40538
+ .routing-feature{margin:.8rem 0;padding:.8rem;border:1px solid var(--line);border-radius:12px;background:var(--panel-soft)}.routing-feature .tool-head{align-items:center}.routing-feature p{margin:.55rem 0;color:var(--muted)}
39072
40539
  .managed-action-box{margin-top:.8rem;background:var(--panel-soft);border:1px solid var(--line);border-radius:12px;padding:.85rem}.managed-action-box p{margin:.1rem 0 .65rem}
39073
40540
  .maintenance-list{display:grid;gap:.55rem}.maintenance-row{display:flex;align-items:center;justify-content:space-between;gap:1rem;background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:.8rem}.maintenance-row p{margin:.15rem 0}
39074
40541
  .explain-box{background:var(--panel-soft);border:1px solid var(--line);border-radius:12px;padding:.8rem;margin:.6rem 0}.explain-box p{margin:.25rem 0;color:var(--muted)}.explain-box.warn{background:var(--warn-soft);border-color:color-mix(in srgb,var(--warn) 35%,var(--line))}.explain-box.safe{background:var(--good-soft);border-color:color-mix(in srgb,var(--good) 30%,var(--line))}.operation-progress{margin:.75rem 0;padding:.8rem;border:1px solid var(--line);border-radius:12px}.operation-progress p{margin:.35rem 0 0}
@@ -39749,7 +41216,7 @@ ${GUIDE_CANDIDATE_READINESS_JS}`;
39749
41216
  </div>
39750
41217
 
39751
41218
  <section class="setup-step" id="coding-agents">
39752
- <div class="section-title"><div><h2>Coding agents</h2><p>Detected coding apps are shown here as status. Optimizer setup is managed centrally below; a detected setup does not prove that it ran or recorded results.</p></div></div>
41219
+ <div class="section-title"><div><h2>Coding agents</h2><p>Enable automatic per-prompt routing here for each detected coding app. The card distinguishes hook configuration from callbacks actually observed at runtime.</p></div></div>
39753
41220
  <div id="setup-agents" class="tool-grid"><article class="tool-card"><h3>Checking agents\u2026</h3></article></div>
39754
41221
  <details class="disclosure advanced-disclosure">
39755
41222
  <summary>Agent details and optional reasoning settings</summary>
@@ -40217,6 +41684,19 @@ async function runAsDatabaseReader(argv2) {
40217
41684
  process5.exitCode = 0;
40218
41685
  return true;
40219
41686
  }
41687
+ function parsePromptRouterEvent(value3) {
41688
+ if (value3 === "prompt-submit" || value3 === "subagent-start" || value3 === "subagent-stop")
41689
+ return value3;
41690
+ return null;
41691
+ }
41692
+ function emitPromptRouterContext(harness) {
41693
+ process5.stdout.write(JSON.stringify({
41694
+ hookSpecificOutput: {
41695
+ hookEventName: "UserPromptSubmit",
41696
+ additionalContext: ROUTING_CONTEXT[harness]
41697
+ }
41698
+ }) + "\n");
41699
+ }
40220
41700
  async function readStandardInput() {
40221
41701
  const chunks = [];
40222
41702
  let bytes = 0;
@@ -40241,6 +41721,16 @@ async function main(argv2) {
40241
41721
  }
40242
41722
  return;
40243
41723
  }
41724
+ if (argv2[0] === PROMPT_ROUTER_FLAG && argv2[2] === "--check") {
41725
+ if (argv2[1] === "claude" || argv2[1] === "codex") {
41726
+ process5.stdout.write(`${PROMPT_ROUTER_CHECK_MARKER2}
41727
+ `);
41728
+ process5.exitCode = EXIT_CODES.ok;
41729
+ } else {
41730
+ process5.exitCode = EXIT_CODES["usage-error"];
41731
+ }
41732
+ return;
41733
+ }
40244
41734
  const opensGuide = argv2.length === 0 || argv2[0] === "start" || argv2[0] === "ui";
40245
41735
  const readOnly = argv2.includes("--read-only");
40246
41736
  const uiInvocation = opensGuide ? parseUiArgs(argv2.slice(1).filter((arg) => arg !== "--read-only")) : null;
@@ -40310,6 +41800,34 @@ Run token-harness ui --help for usage.
40310
41800
  env: process5.env,
40311
41801
  stdoutIsTty: process5.stdout.isTTY === true
40312
41802
  };
41803
+ if (argv2[0] === PROMPT_ROUTER_FLAG) {
41804
+ const selected = argv2[1];
41805
+ const event = parsePromptRouterEvent(argv2[2]);
41806
+ if (selected !== "claude" && selected !== "codex" || event === null) {
41807
+ process5.exitCode = EXIT_CODES.ok;
41808
+ return;
41809
+ }
41810
+ const input = await readStandardInput();
41811
+ if (resolution.ok && fs !== null && input !== null) {
41812
+ try {
41813
+ const projectId = attribution.salt === null ? null : deriveProjectId(process5.cwd(), attribution.salt, resolution.environment.facts.os === "windows");
41814
+ await recordNativePromptRoutingHook({
41815
+ fs,
41816
+ stateRoot: resolution.environment.paths.state,
41817
+ harness: selected,
41818
+ event,
41819
+ projectId,
41820
+ now: (/* @__PURE__ */ new Date()).toISOString(),
41821
+ hookInput: input
41822
+ });
41823
+ } catch {
41824
+ }
41825
+ }
41826
+ if (event === "prompt-submit")
41827
+ emitPromptRouterContext(selected);
41828
+ process5.exitCode = EXIT_CODES.ok;
41829
+ return;
41830
+ }
40313
41831
  if (argv2[0] === RTK_HOOK_PROXY_FLAG) {
40314
41832
  const selected = argv2[1];
40315
41833
  if (selected !== "claude" && selected !== "codex") {
@@ -40532,6 +42050,35 @@ async function runGuidedUi(options, base) {
40532
42050
  stateRoot: base.stateRoot ?? null,
40533
42051
  harness
40534
42052
  });
42053
+ }, async (harness) => {
42054
+ if (base.adapters === null || base.adapters === void 0 || base.platform === null) {
42055
+ return {
42056
+ harness,
42057
+ state: "unavailable",
42058
+ label: "Not verified",
42059
+ detail: "The local filesystem is unavailable, so native prompt routing cannot be checked.",
42060
+ configPath: null,
42061
+ configured: null,
42062
+ promptSubmissions: 0,
42063
+ subagentsStarted: 0,
42064
+ subagentsStopped: 0,
42065
+ reportedModels: [],
42066
+ lastObservedAt: null,
42067
+ receiptState: "unavailable"
42068
+ };
42069
+ }
42070
+ return observeNativePromptRouting({
42071
+ fs: base.adapters.fs,
42072
+ home: base.home,
42073
+ stateRoot: base.stateRoot ?? null,
42074
+ harness: harnessId(harness),
42075
+ version: null,
42076
+ runner: base.adapters.runner,
42077
+ facts: base.platform,
42078
+ paths: base.adapters.paths,
42079
+ projectRoot: base.cwd,
42080
+ projectId: base.adapters.projectIdFor(base.cwd)
42081
+ });
40535
42082
  });
40536
42083
  const token = randomBytes2(32).toString("hex");
40537
42084
  let authority = "";
@@ -40632,7 +42179,7 @@ async function runSavingsView(args, base) {
40632
42179
  }
40633
42180
  return result6.exitCode;
40634
42181
  }
40635
- var RTK_HOOK_PROXY_FLAG, MAX_HOOK_INPUT_BYTES, UI_SECURITY_HEADERS;
42182
+ var RTK_HOOK_PROXY_FLAG, PROMPT_ROUTER_FLAG, PROMPT_ROUTER_CHECK_MARKER2, MAX_HOOK_INPUT_BYTES, ROUTING_CONTEXT, UI_SECURITY_HEADERS;
40636
42183
  var init_main = __esm({
40637
42184
  "apps/cli/dist/src/main.js"() {
40638
42185
  "use strict";
@@ -40643,11 +42190,19 @@ var init_main = __esm({
40643
42190
  init_version2();
40644
42191
  init_guided();
40645
42192
  init_agent_skill();
42193
+ init_prompt_router();
40646
42194
  init_guided_candidate_campaign_status();
40647
42195
  init_guided_http();
40648
42196
  init_rtk_hook_proxy();
42197
+ init_prompt_router();
40649
42198
  RTK_HOOK_PROXY_FLAG = "__internal-rtk-hook";
42199
+ PROMPT_ROUTER_FLAG = "__internal-prompt-router";
42200
+ PROMPT_ROUTER_CHECK_MARKER2 = "token-harness-prompt-router-v1";
40650
42201
  MAX_HOOK_INPUT_BYTES = 1024 * 1024;
42202
+ ROUTING_CONTEXT = {
42203
+ codex: "For substantial coding work, delegate at most one independent bounded subtask to a native subagent with gpt-6-luna if available and the root is not Luna. Keep trivial, coupled, security, architecture, release, and integration decisions on the root. Specify the model; if unavailable, stay on the root. The root reviews. Claim savings only from paired, quality-gated measurements.",
42204
+ claude: "For substantial coding work, delegate at most one independent bounded subtask to a native subagent with the current Haiku alias if available and cheaper than the root. Keep trivial, coupled, security, architecture, release, and integration decisions on the root. Specify the model; if unavailable, stay on the root. The root reviews. Claim savings only from paired, quality-gated measurements."
42205
+ };
40651
42206
  UI_SECURITY_HEADERS = {
40652
42207
  "Cache-Control": "no-store",
40653
42208
  "Content-Security-Policy": "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'",