dsh-harness-reflex 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/README.md +20 -6
  2. package/client.js +3511 -185
  3. package/dist/attribution.d.ts +266 -0
  4. package/dist/attribution.js +238 -0
  5. package/dist/attribution.js.map +1 -0
  6. package/dist/bridge.d.ts +311 -13
  7. package/dist/bridge.js +714 -42
  8. package/dist/bridge.js.map +1 -1
  9. package/dist/client-bundle.js +4 -1
  10. package/dist/client-bundle.js.map +1 -1
  11. package/dist/command.js +10 -0
  12. package/dist/command.js.map +1 -1
  13. package/dist/config.d.ts +530 -22
  14. package/dist/config.js +808 -27
  15. package/dist/config.js.map +1 -1
  16. package/dist/delegation-dispatch.d.ts +132 -0
  17. package/dist/delegation-dispatch.js +186 -0
  18. package/dist/delegation-dispatch.js.map +1 -0
  19. package/dist/delegation-health.d.ts +131 -0
  20. package/dist/delegation-health.js +97 -0
  21. package/dist/delegation-health.js.map +1 -0
  22. package/dist/delegation.d.ts +148 -0
  23. package/dist/delegation.js +186 -0
  24. package/dist/delegation.js.map +1 -0
  25. package/dist/effort-delegation.d.ts +144 -0
  26. package/dist/effort-delegation.js +280 -0
  27. package/dist/effort-delegation.js.map +1 -0
  28. package/dist/effort.d.ts +141 -0
  29. package/dist/effort.js +251 -9
  30. package/dist/effort.js.map +1 -1
  31. package/dist/host-patch.d.ts +156 -0
  32. package/dist/host-patch.js +534 -0
  33. package/dist/host-patch.js.map +1 -0
  34. package/dist/index.d.ts +12 -3
  35. package/dist/index.js +99 -7
  36. package/dist/index.js.map +1 -1
  37. package/dist/interventions.d.ts +98 -373
  38. package/dist/interventions.js +442 -1702
  39. package/dist/interventions.js.map +1 -1
  40. package/dist/panel-api.d.ts +328 -4
  41. package/dist/panel-api.js +322 -15
  42. package/dist/panel-api.js.map +1 -1
  43. package/dist/panel-mount.d.ts +81 -22
  44. package/dist/panel-mount.js +228 -7
  45. package/dist/panel-mount.js.map +1 -1
  46. package/dist/routing.d.ts +23 -18
  47. package/dist/routing.js +471 -153
  48. package/dist/routing.js.map +1 -1
  49. package/dist/session-audit.d.ts +70 -0
  50. package/dist/session-audit.js +73 -0
  51. package/dist/session-audit.js.map +1 -1
  52. package/dist/systemone-probe.d.ts +114 -0
  53. package/dist/systemone-probe.js +383 -0
  54. package/dist/systemone-probe.js.map +1 -0
  55. package/dist/testing.d.ts +212 -7
  56. package/dist/testing.js +333 -27
  57. package/dist/testing.js.map +1 -1
  58. package/dist/tools.d.ts +109 -3
  59. package/dist/tools.js +103 -4
  60. package/dist/tools.js.map +1 -1
  61. package/dist/unconfigured-backend.d.ts +72 -0
  62. package/dist/unconfigured-backend.js +94 -0
  63. package/dist/unconfigured-backend.js.map +1 -0
  64. package/dist/vendor/harness-reflex/backend/factory.d.ts +31 -1
  65. package/dist/vendor/harness-reflex/backend/factory.js +18 -3
  66. package/dist/vendor/harness-reflex/backend/factory.js.map +1 -1
  67. package/dist/vendor/harness-reflex/backend/jev.d.ts +20 -0
  68. package/dist/vendor/harness-reflex/backend/jev.js +11 -4
  69. package/dist/vendor/harness-reflex/backend/jev.js.map +1 -1
  70. package/dist/vendor/harness-reflex/backend/simple-jev.d.ts +16 -0
  71. package/dist/vendor/harness-reflex/backend/simple-jev.js +17 -6
  72. package/dist/vendor/harness-reflex/backend/simple-jev.js.map +1 -1
  73. package/dist/vendor/harness-reflex/core/closing.d.ts +90 -0
  74. package/dist/vendor/harness-reflex/core/closing.js +111 -0
  75. package/dist/vendor/harness-reflex/core/closing.js.map +1 -0
  76. package/dist/vendor/harness-reflex/core/evidence.d.ts +119 -0
  77. package/dist/vendor/harness-reflex/core/evidence.js +209 -0
  78. package/dist/vendor/harness-reflex/core/evidence.js.map +1 -0
  79. package/dist/vendor/harness-reflex/core/judge.d.ts +221 -0
  80. package/dist/vendor/harness-reflex/core/judge.js +251 -0
  81. package/dist/vendor/harness-reflex/core/judge.js.map +1 -0
  82. package/dist/vendor/harness-reflex/core/orchestrate-closing.d.ts +237 -0
  83. package/dist/vendor/harness-reflex/core/orchestrate-closing.js +250 -0
  84. package/dist/vendor/harness-reflex/core/orchestrate-closing.js.map +1 -0
  85. package/dist/vendor/harness-reflex/core/orchestrate-correction.d.ts +209 -0
  86. package/dist/vendor/harness-reflex/core/orchestrate-correction.js +141 -0
  87. package/dist/vendor/harness-reflex/core/orchestrate-correction.js.map +1 -0
  88. package/dist/vendor/harness-reflex/core/orchestrate-host.d.ts +225 -0
  89. package/dist/vendor/harness-reflex/core/orchestrate-host.js +80 -0
  90. package/dist/vendor/harness-reflex/core/orchestrate-host.js.map +1 -0
  91. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.d.ts +259 -0
  92. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js +270 -0
  93. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js.map +1 -0
  94. package/dist/vendor/harness-reflex/core/orchestrate.d.ts +357 -0
  95. package/dist/vendor/harness-reflex/core/orchestrate.js +418 -0
  96. package/dist/vendor/harness-reflex/core/orchestrate.js.map +1 -0
  97. package/dist/vendor/harness-reflex/core/policy.d.ts +122 -0
  98. package/dist/vendor/harness-reflex/core/policy.js +102 -0
  99. package/dist/vendor/harness-reflex/core/policy.js.map +1 -0
  100. package/dist/vendor/harness-reflex/core/prune-plan.d.ts +141 -0
  101. package/dist/vendor/harness-reflex/core/prune-plan.js +390 -0
  102. package/dist/vendor/harness-reflex/core/prune-plan.js.map +1 -0
  103. package/dist/vendor/harness-reflex/core/text.d.ts +36 -0
  104. package/dist/vendor/harness-reflex/core/text.js +66 -0
  105. package/dist/vendor/harness-reflex/core/text.js.map +1 -0
  106. package/dist/vendor/harness-reflex/ports/audit.d.ts +18 -0
  107. package/dist/vendor/harness-reflex/ports/audit.js +11 -0
  108. package/dist/vendor/harness-reflex/ports/audit.js.map +1 -0
  109. package/dist/vendor/harness-reflex/ports/clock.d.ts +14 -0
  110. package/dist/vendor/harness-reflex/ports/clock.js +11 -0
  111. package/dist/vendor/harness-reflex/ports/clock.js.map +1 -0
  112. package/dist/vendor/harness-reflex/ports/decision.d.ts +75 -0
  113. package/dist/vendor/harness-reflex/ports/decision.js +2 -0
  114. package/dist/vendor/harness-reflex/ports/decision.js.map +1 -0
  115. package/dist/vendor/harness-reflex/ports/index.d.ts +14 -0
  116. package/dist/vendor/harness-reflex/ports/index.js +2 -0
  117. package/dist/vendor/harness-reflex/ports/index.js.map +1 -0
  118. package/dist/vendor/harness-reflex/ports/log.d.ts +22 -0
  119. package/dist/vendor/harness-reflex/ports/log.js +12 -0
  120. package/dist/vendor/harness-reflex/ports/log.js.map +1 -0
  121. package/dist/vendor/harness-reflex/ports/state.d.ts +46 -0
  122. package/dist/vendor/harness-reflex/ports/state.js +13 -0
  123. package/dist/vendor/harness-reflex/ports/state.js.map +1 -0
  124. package/package.json +25 -13
@@ -1 +1 @@
1
- {"version":3,"file":"jev.js","sourceRoot":"","sources":["../../../../src/vendor/harness-reflex/backend/jev.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAqF1E,4DAA4D;AAC5D,MAAM,CAAC,MAAM,uBAAuB,GAAG,eAAe,CAAC;AAEvD,gFAAgF;AAChF,MAAM,CAAC,MAAM,0BAA0B,GAAG,0BAA0B,uBAAuB,EAAE,CAAC;AAE9F,mEAAmE;AACnE,MAAM,CAAC,MAAM,sBAAsB,GAAG;IACpC,KAAK,EAAE,YAAY;IACnB,KAAK,EAAE,EAAE;IACT,SAAS,EAAE;QACT,CAAC,EAAE,EAAE,IAAI,EAAE,QAAQ,EAAE,YAAY,EAAE,yBAAyB,EAAE,QAAQ,EAAE,EAAE,CAAC,EAAE,kBAAkB,EAAE,CAAC,EAAE,mBAAmB,EAAE,EAAE;KAC5H;CACkC,CAAC;AAEtC,qEAAqE;AACrE,MAAM,CAAC,MAAM,kBAAkB,GAAG,QAAQ,CAAC;AA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MAAM,CAAC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CAAC,GAAG,GAAG,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;QACrE,MAAM,MAAM,GAAG,QAAQ;aACpB,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YACf,IAAI,EAAE,KAAK,CAAC,IAAI;YAChB,KAAK,EAAE,MAAM,CAAC,CAAC,KAAK,CAAC,MAAM,GAAG,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;YAChD,MAAM,EAAE,mBAAmB,MAAM,GAAG;SACrC,CAAC,CAAC;aACF,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;QACrC,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;IACjG,CAAC;CACF","sourcesContent":["import {\n ActionStep,\n BackendHealth,\n ChoiceOption,\n ChoiceRequest,\n ChoiceResponse,\n ClaimClassification,\n ClaimClassificationRequest,\n ClaimClassificationResponse,\n DecisionBackend,\n GateAssertion,\n GateRequest,\n GateResponse,\n GateResultItem,\n PruneDiagnostics,\n PruneRequest,\n PruneResponse,\n RouteCandidateItem,\n RouteRequest,\n RouteResponse,\n StagnationCheckRequest,\n StagnationCheckResponse\n} from './types.js';\nimport { CURRENT_MODEL_MARK, buildRouteContext } from './route-prompt.js';\n\nexport interface JevBackendConfig {\n baseUrl?: string;\n apiKey?: string;\n model?: string;\n timeoutMs?: number;\n /**\n * Character count from which `prune()` judges the payload segment by segment\n * through System One. Below it the deterministic local candidates are used and\n * no request is sent. Defaults to 10000 (or\n * `SYSTEM_ONE_PRUNE_JUDGE_MIN_CHARS`); mirrors\n * `interventions.pruneJudgeMinChars` of the plugin config.\n */\n pruneJudgeMinChars?: number;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Wire contract of the single endpoint */\n/* -------------------------------------------------------------------------- */\n\n/**\n * One `choice` question of `POST /v1/systemone`.\n *\n * The gateway decides *between criteria*: the dictionary keys are the answers\n * the model may name, the values the descriptions it reads. There is no\n * free-text answer, which is why a caller's option list becomes this dictionary\n * and comes back as `answers[id].probabilities`, keyed exactly like the\n * criteria.\n */\nexport interface SystemOneChoiceQuestion {\n type: 'choice';\n instructions: string;\n criteria: Record<string, string>;\n}\n\n/** One `score` question: `criteria` is a list, and the answer indexes it. */\nexport interface SystemOneScoreQuestion {\n type: 'score';\n instructions: string;\n criteria: string[];\n}\n\n/** A question of the single-endpoint contract; `type` discriminates the union. */\nexport type SystemOneQuestion = SystemOneChoiceQuestion | SystemOneScoreQuestion;\n\n/** Body of the one and only request this backend sends. */\nexport interface SystemOneRequest {\n model: string;\n state: Record<string, unknown>;\n questions: Record<string, SystemOneQuestion>;\n}\n\n/** Answer of a `choice` question: the named criterion plus its distribution. */\nexport interface SystemOneChoiceAnswer {\n type?: string;\n /** Criterion key the model named; equals the argmax of `probabilities`. */\n choice?: string;\n /** The gateway's own confidence, distinct from the argmax probability. */\n confidence?: number;\n probabilities?: Record<string, number>;\n}\n\n/**\n * Answer of a `score` question.\n *\n * `probabilities` is keyed by the *index* of the criteria list and `score` is\n * the probability-weighted mean index (measured against `jev-1.13.0`), so\n * `Math.round(score)` is the argmax index and `legend` names each index.\n */\nexport interface SystemOneScoreAnswer {\n type?: string;\n score?: number;\n confidence?: number;\n legend?: Record<string, string>;\n probabilities?: Record<string, number>;\n}\n\n/** Response envelope of `POST /v1/systemone`. */\nexport interface SystemOneResponse {\n model?: string;\n answers?: Record<string, SystemOneChoiceAnswer | SystemOneScoreAnswer>;\n usage?: { input_tokens?: number; output_tokens?: number };\n}\n\n/** Path of the one endpoint the current gateway exposes. */\nexport const SYSTEMONE_ENDPOINT_PATH = '/v1/systemone';\n\n/** Endpoint used when neither configuration nor environment supplies a base. */\nexport const DEFAULT_SYSTEMONE_ENDPOINT = `https://api.typesafe.ai${SYSTEMONE_ENDPOINT_PATH}`;\n\n/** Illustration of a choice request, for docs and drift checks. */\nexport const CHOICE_REQUEST_EXAMPLE = {\n model: 'jev-latest',\n state: {},\n questions: {\n q: { type: 'choice', instructions: 'Which option is better?', criteria: { a: 'the first option', b: 'the second option' } }\n }\n} as const satisfies SystemOneRequest;\n\n/** Question id of a plain {@link JevDecisionBackend.choice} call. */\nexport const CHOICE_QUESTION_ID = 'choice';\n/** Question id of a {@link JevDecisionBackend.route} call. */\nexport const ROUTE_QUESTION_ID = 'route';\n/** Question id of a {@link JevDecisionBackend.prune} call. */\nexport const PRUNE_QUESTION_ID = 'prune';\n/** Question id of a {@link JevDecisionBackend.checkStagnation} call. */\nexport const STAGNATION_QUESTION_ID = 'stagnation';\n/** Prefix of the per-assertion question ids of a {@link JevDecisionBackend.gate} call. */\nexport const GATE_QUESTION_PREFIX = 'assertion-';\n/** Prefix of the per-sentence question ids of a {@link JevDecisionBackend.classifyClaims} call. */\nexport const CLAIM_QUESTION_PREFIX = 'closing-claim-';\n/** Criterion pair of one claim question; index 1 (\"claims completion\") is the one read. */\nexport const CLAIM_CRITERIA: readonly string[] = [\n 'not a completion claim: describes work, plans, questions, or an incomplete/unsuccessful state',\n 'completion claim: asserts that the task, work, build, or tests are complete, successful, passing, or finished'\n];\n\n/* -------------------------------------------------------------------------- */\n/* Domain vocabularies expressed as criteria */\n/* -------------------------------------------------------------------------- */\n\n/** Verdicts the model may name for one gate assertion. Escalation is ours, never its. */\nexport type GateVerdict = 'verified' | 'contradicted' | 'not_addressed';\n\n/** Criteria of a gate assertion, in the order ties are broken. */\nexport const GATE_VERDICTS: readonly GateVerdict[] = ['verified', 'contradicted', 'not_addressed'];\n\n/** What each gate verdict means to the model. */\nexport const GATE_VERDICT_CRITERIA: Readonly<Record<GateVerdict, string>> = {\n verified: 'The evidence directly supports the assertion.',\n contradicted: 'The evidence contradicts the assertion.',\n not_addressed: 'The evidence neither supports nor contradicts the assertion.'\n};\n\n/**\n * Minimum probability on `verified` for a strictness level to claim success.\n * Anything below is escalated: a three-way choice at chance is 1/3, so the\n * lenient floor never accepts a distribution the model did not actually prefer.\n */\nexport const GATE_CONFIDENCE_FLOOR: Readonly<Record<'high' | 'normal' | 'lenient', number>> = {\n high: 0.7,\n normal: 0.5,\n lenient: 0.34\n};\n\n/** Patterns a run can be stuck in. */\nexport type StagnationPattern = 'repetition' | 'oscillation' | 'failing_retry' | 'zero_progress' | 'none';\n\n/** Pattern criteria, in the order ties are broken. */\nexport const STAGNATION_PATTERNS: readonly StagnationPattern[] = [\n 'repetition',\n 'oscillation',\n 'failing_retry',\n 'zero_progress',\n 'none'\n];\n\n/** What each stagnation pattern means to the model. */\nexport const STAGNATION_PATTERN_CRITERIA: Readonly<Record<StagnationPattern, string>> = {\n repetition: 'The same action with the same input repeats with no new information.',\n oscillation: 'Execution alternates between the same two actions or edits without progress.',\n failing_retry: 'Actions keep failing with recurring errors and are retried unchanged.',\n zero_progress: 'Actions run but nothing observable advances the goal.',\n none: 'The run is progressing; none of the stagnation patterns apply.'\n};\n\n/** One-line diagnosis of each pattern. */\nexport const STAGNATION_DIAGNOSIS: Readonly<Record<StagnationPattern, string>> = {\n repetition: 'Identical consecutive tool executions with unchanged input.',\n oscillation: 'The run alternates between two identical actions or edits.',\n failing_retry: 'Recent actions keep failing with recurring errors.',\n zero_progress: 'Actions run, but nothing observable advances the goal.',\n none: 'Execution flow appears progressive.'\n};\n\n/** Corrective action recommended for each stuck pattern. */\nexport const STAGNATION_INTERVENTION: Readonly<Record<StagnationPattern, string>> = {\n repetition: 'Interrupt execution. Change the approach or inspect the previous failure output.',\n oscillation: 'Break the loop: stop alternating, restate the requirement, verify independently.',\n failing_retry: 'Step back and diagnose the root cause before retrying the same action.',\n zero_progress: 'Re-read the goal and pick a step that produces observable evidence of progress.',\n none: 'Continue.'\n};\n\n/** Minimum probability for a stuck pattern to be reported as a real alert. */\nexport const STAGNATION_STUCK_FLOOR = 0.4;\n\n/* -------------------------------------------------------------------------- */\n/* Pure helpers (exported for tests) */\n/* -------------------------------------------------------------------------- */\n\n/** Elapsed milliseconds, rounded and never negative. */\nfunction elapsed(start: number): number {\n return Math.max(0, Math.round(performance.now() - start));\n}\n\n/** Message of an unknown thrown value. */\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** A probability, clamped into `[0, 1]`; anything unusable reads as 0. */\nfunction toProbability(value: unknown): number {\n const numeric = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(numeric) || numeric <= 0) return 0;\n return Math.min(1, numeric);\n}\n\n/** A probability rounded to the four decimals the decision surfaces report. */\nfunction round4(value: number): number {\n return Number(value.toFixed(4));\n}\n\n/** Comparison key for a criterion: the gateway echoes keys, but be forgiving. */\nfunction normalizeKey(key: string): string {\n return key.trim().toLowerCase();\n}\n\n/**\n * Resolve the endpoint the single request goes to.\n *\n * Every accepted spelling of the base — the full `…/v1/systemone` URL the docs\n * and `JEV_API_BASE` use, a `/v1` root, or a bare host — collapses onto exactly\n * one URL, so a retired per-capability sub-path can never be appended.\n * @param baseUrl - configured or environment base; empty selects the default.\n * @returns the absolute URL of `POST /v1/systemone`.\n */\nexport function normalizeSystemOneEndpoint(baseUrl?: string): string {\n const trimmed = (baseUrl ?? '').trim().replace(/\\/+$/, '');\n if (trimmed.length === 0) return DEFAULT_SYSTEMONE_ENDPOINT;\n if (trimmed.endsWith(SYSTEMONE_ENDPOINT_PATH)) return trimmed;\n if (trimmed.endsWith('/systemone')) return `${trimmed.slice(0, -'/systemone'.length)}${SYSTEMONE_ENDPOINT_PATH}`;\n if (trimmed.endsWith('/v1')) return `${trimmed}/systemone`;\n return `${trimmed}${SYSTEMONE_ENDPOINT_PATH}`;\n}\n\n/**\n * Turn a list of labels into the unique criteria keys of a choice question.\n *\n * Criteria keys are the option labels themselves, which is what makes the\n * answer's probability dictionary readable as option probabilities. Duplicates\n * (two pool entries with the same name) get a numeric suffix so no option can be\n * lost in the dictionary.\n * @param labels - the option labels, in caller order.\n * @returns one unique key per label, in the same order.\n */\nexport function uniqueCriteriaKeys(labels: readonly string[]): string[] {\n const used = new Set<string>();\n return labels.map((raw, index) => {\n const label = typeof raw === 'string' ? raw.trim() : '';\n let key = label.length > 0 ? label : `option ${String(index + 1)}`;\n if (used.has(key)) {\n let suffix = 2;\n while (used.has(`${key} (${String(suffix)})`)) suffix++;\n key = `${key} (${String(suffix)})`;\n }\n used.add(key);\n return key;\n });\n}\n\n/**\n * Read one answer's distribution against the criteria keys it was asked about.\n * @param probabilities - `answers[id].probabilities`, when present.\n * @param keys - criteria keys of the question, in declared order.\n * @returns every key mapped to its probability (missing keys read 0), or\n * `undefined` when the answer carries no usable distribution at all.\n */\nexport function readDistribution(\n probabilities: Record<string, number> | undefined,\n keys: readonly string[]\n): Map<string, number> | undefined {\n if (!probabilities || typeof probabilities !== 'object') return undefined;\n const declared = new Map<string, string>();\n for (const key of keys) declared.set(normalizeKey(key), key);\n\n const distribution = new Map<string, number>(keys.map((key) => [key, 0]));\n let matched = false;\n for (const [rawKey, rawValue] of Object.entries(probabilities)) {\n const key = declared.get(normalizeKey(rawKey));\n if (key === undefined) continue;\n distribution.set(key, (distribution.get(key) ?? 0) + toProbability(rawValue));\n matched = true;\n }\n return matched ? distribution : undefined;\n}\n\n/**\n * Highest-probability key of a distribution.\n * @param distribution - probabilities keyed by criteria key.\n * @param order - declared key order, used to break ties deterministically.\n * @returns the winning key, or `undefined` for an empty order.\n */\nexport function argmaxKey(distribution: Map<string, number>, order: readonly string[]): string | undefined {\n let best: string | undefined;\n let bestValue = -Infinity;\n for (const key of order) {\n const value = distribution.get(key) ?? 0;\n if (value > bestValue) {\n best = key;\n bestValue = value;\n }\n }\n return best;\n}\n\n/** Move `index` to the front when it ties the current leader. */\nfunction promoteTiedWinner<T>(entries: T[], index: number, scoreOf: (entry: T) => number): void {\n if (index <= 0 || entries.length <= index) return;\n const winner = entries[index] as T;\n const leader = entries[0] as T;\n if (scoreOf(winner) !== scoreOf(leader)) return;\n entries.splice(index, 1);\n entries.unshift(winner);\n}\n\n/**\n * Build the choice response options from one gateway answer.\n *\n * The distribution is authoritative; the gateway's discrete `choice` only\n * breaks a tie. When the gateway returns no distribution but does name a\n * criterion, the answer is reconstructed around that name and flagged\n * `uncalibrated`, because the probabilities are then ours, not the gateway's.\n * @param labels - option labels in caller order.\n * @param keys - criteria keys, aligned with `labels`.\n * @param distribution - parsed distribution, when the answer had one.\n * @param answer - the raw gateway answer.\n * @returns sorted options plus the uncalibrated flag, or `undefined` when the\n * answer cannot be turned into a distribution at all.\n */\nexport function toChoiceOptions(\n labels: readonly string[],\n keys: readonly string[],\n distribution: Map<string, number> | undefined,\n answer: SystemOneChoiceAnswer | undefined\n): { options: ChoiceOption[]; uncalibrated: boolean } | undefined {\n const declaredKey =\n typeof answer?.choice === 'string'\n ? keys.find((key) => normalizeKey(key) === normalizeKey(String(answer.choice)))\n : undefined;\n\n let resolved = distribution;\n let uncalibrated = false;\n if (resolved === undefined) {\n if (declaredKey === undefined) return undefined;\n resolved = new Map<string, number>(keys.map((key) => [key, 0]));\n const confidence = toProbability(answer?.confidence) || 1;\n resolved.set(declaredKey, confidence);\n const others = keys.filter((key) => key !== declaredKey);\n const share = others.length > 0 ? (1 - confidence) / others.length : 0;\n for (const key of others) resolved.set(key, share);\n uncalibrated = true;\n }\n\n const options: ChoiceOption[] = labels.map((rawLabel, index) => ({\n label: typeof rawLabel === 'string' ? rawLabel : String(rawLabel),\n probability: round4(resolved?.get(keys[index] ?? '') ?? 0)\n }));\n options.sort((a, b) => b.probability - a.probability);\n if (declaredKey !== undefined) {\n const declaredLabel = labels[keys.indexOf(declaredKey)] ?? '';\n promoteTiedWinner(options, options.findIndex((option) => option.label === declaredLabel), (option) => option.probability);\n }\n return { options, uncalibrated };\n}\n\n/**\n * Read the winning criteria index out of a `score` answer.\n * @param answer - the gateway's score answer.\n * @param count - number of criteria the question offered.\n * @returns the argmax index, or `undefined` when the answer is unusable.\n */\nexport function readScoreIndex(answer: SystemOneScoreAnswer | undefined, count: number): number | undefined {\n if (count <= 0) return undefined;\n const keys = Array.from({ length: count }, (_, index) => String(index));\n const distribution = readDistribution(answer?.probabilities, keys);\n if (distribution !== undefined) {\n const key = argmaxKey(distribution, keys);\n if (key === undefined || (distribution.get(key) ?? 0) <= 0) return undefined;\n return Number(key);\n }\n const raw = typeof answer?.score === 'number' ? answer.score : Number(answer?.score);\n if (!Number.isFinite(raw)) return undefined;\n return Math.min(count - 1, Math.max(0, Math.round(raw)));\n}\n\n/** Instruction block of one choice question. */\nfunction buildChoiceInstructions(question: string | undefined): string {\n const trimmed = (question ?? '').trim();\n return trimmed.length > 0 ? trimmed : 'Choose the criterion that best answers the task.';\n}\n\n/** Instruction block of one gate assertion. */\nfunction buildGateInstructions(assertion: GateAssertion, strictness: string): string {\n const rubric = (assertion.criteria ?? '').trim();\n return [\n 'Decide which criterion describes how the STATE evidence relates to the ASSERTION.',\n `ASSERTION: ${assertion.statement}`,\n ...(rubric.length > 0 ? [`ASSERTION RUBRIC: ${rubric}`] : []),\n `STRICTNESS: ${strictness}`\n ].join('\\n');\n}\n\n/** Instruction block of a stagnation classification. */\nfunction buildStagnationInstructions(): string {\n return [\n 'Classify the recent agent run in the STATE: choose the criterion that best describes the execution pattern.',\n 'Judge the action history itself, not the quality of the tool output.'\n ].join('\\n');\n}\n\n/** Sentences one closing classification may submit; the turn's tail, never its whole text. */\nexport const MAX_CLAIM_SENTENCES = 3;\n\n/**\n * Instruction block of one completion-claim question.\n *\n * The negation cases are spelled out because that is exactly where a word list\n * fails: \"not complete\" contains \"complete\", and \"没有通过\" contains \"通过\".\n */\nfunction buildClaimInstructions(statement: string, intent: string): string {\n return [\n 'Decide whether the SENTENCE claims that the task or its work is complete, successful, passing, or finished.',\n 'A negated or qualified outcome is NOT a completion claim: \"not complete\", \"not yet done\", \"failed\", \"没有通过\", \"尚未完成\", \"仍有失败\".',\n 'A sentence that only describes plans, asks a question, or reports an error is not a completion claim either.',\n ...(intent.trim().length > 0 ? [`TURN INTENT: ${intent}`] : []),\n `SENTENCE: ${statement}`\n ].join('\\n');\n}\n\n/**\n * Read one claim answer.\n * @param statement - the sentence the question was asked about.\n * @param answer - the gateway's score answer.\n * @returns the classification, or `undefined` when the answer is unusable.\n */\nfunction readClaimAnswer(\n statement: string,\n answer: SystemOneScoreAnswer | undefined\n): ClaimClassification | undefined {\n const index = readScoreIndex(answer, CLAIM_CRITERIA.length);\n if (index === undefined) return undefined;\n const distribution = readDistribution(answer?.probabilities, ['0', '1']);\n const confidence = distribution !== undefined ? round4(distribution.get('1') ?? 0) : index === 1 ? 1 : 0;\n return { statement, isClaim: index === 1, confidence };\n}\n\n/** Instruction block of a route decision; renders the same facts the logits backend scores. */\nexport function buildRouteInstructions(req: RouteRequest): string {\n return [\n buildRouteContext(req),\n 'Select the single criterion whose candidate best serves the goal.'\n ]\n .filter((line) => line.trim().length > 0)\n .join('\\n\\n');\n}\n\n/** Criterion description of one route candidate. */\nfunction candidateCriterion(candidate: RouteCandidateItem): string {\n const description = (candidate.description ?? '').trim() || candidate.name;\n const type = candidate.type ? `[${candidate.type}] ` : '';\n const mark = candidate.current ? ` ${CURRENT_MODEL_MARK}` : '';\n return `${type}${description}${mark}`;\n}\n\n/** Clamp a fragment carried into a decision prompt. */\nfunction clip(text: string | undefined, limit: number): string {\n const value = typeof text === 'string' ? text : '';\n return value.length <= limit ? value : `${value.slice(0, limit)}…`;\n}\n\n/** Words a line must share with the intent to count as relevant. */\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9_\\u4e00-\\u9fff]+/)\n .filter((word) => word.length > 2);\n}\n\n/* -------------------------------------------------------------------------- */\n/* Deterministic prune candidates */\n/* -------------------------------------------------------------------------- */\n\n/** One deterministic pruning of a raw output. */\nexport interface PruneCandidate {\n id: 'aggressive' | 'balanced' | 'conservative';\n /** Human-readable label including the reduction it achieved. */\n label: string;\n text: string;\n /** Segments this candidate kept whole; observability of the selection. */\n keptSegments?: number;\n}\n\nconst PROGRESS_ART = /\\[=+[>\\s]|█|^\\s*\\d+%\\s|\\[K/;\nconst NOISE_LINE = /^\\s*(?:npm (?:warn|notice)|Downloading|Fetching|Progress:|added \\d+ packages|audited \\d+ packages)\\b/i;\nconst DIAGNOSTIC_MARK =\n /(?:error|fail|exception|panic|traceback|assert|expected|actual|✗|✘|warn|not ok|denied|refused|cannot|undefined is not|stack)/i;\n\n/** Drop progress art, then collapse repeated lines and blank runs. */\nfunction condenseLines(lines: readonly string[]): string[] {\n const out: string[] = [];\n let blanks = 0;\n let previous: string | undefined;\n for (const line of lines) {\n if (PROGRESS_ART.test(line)) continue;\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n blanks++;\n if (blanks <= 1) out.push('');\n continue;\n }\n blanks = 0;\n if (trimmed === previous) continue;\n previous = trimmed;\n out.push(line.replace(/\\s+$/, ''));\n }\n return out;\n}\n\n/** Cap a candidate to a token budget, keeping its head and its tail. */\nfunction capToBudget(text: string, maxTokens?: number): string {\n if (typeof maxTokens !== 'number' || !Number.isFinite(maxTokens) || maxTokens <= 0) return text;\n const budget = Math.floor(maxTokens) * 4;\n if (text.length <= budget) return text;\n const head = Math.floor(budget * 0.7);\n const tail = Math.max(0, budget - head - 64);\n const dropped = text.length - head - tail;\n const marker = `\\n… [${String(dropped)} characters elided by the prune budget] …\\n`;\n return `${text.slice(0, head)}${marker}${tail > 0 ? text.slice(text.length - tail) : ''}`;\n}\n\n/** Label of one pruning, including its reduction. */\nfunction pruneLabel(id: PruneCandidate['id'], originalChars: number, prunedChars: number): string {\n const strategy: Record<PruneCandidate['id'], string> = {\n aggressive: 'keeps only diagnostic and intent-matching lines',\n balanced: 'drops progress noise and irrelevant dependency traces',\n conservative: 'collapses blank runs and repeated lines'\n };\n const reduction = originalChars > 0 ? Math.round(((originalChars - prunedChars) / originalChars) * 100) : 0;\n return `candidate \"${id}\" (${strategy[id]}, ${String(reduction)}% smaller)`;\n}\n\n/**\n * Build the deterministic prunings used below the judging threshold and as the\n * fallback when System One cannot judge the segments.\n *\n * These are the legacy line filters: {@link JevDecisionBackend.prune} no longer\n * uses them as its primary decision for large payloads — the per-segment scores\n * are — so `PROGRESS_ART`/`NOISE_LINE` are one input among two, never the sole\n * basis of a reduction.\n * @param rawOutput - the bulk output to reduce.\n * @param intent - what the caller is looking for.\n * @param maxTokens - optional token budget applied to every candidate.\n * @returns distinct candidates, most aggressive first; empty for empty input.\n */\nexport function buildPruneCandidates(rawOutput: string, intent: string, maxTokens?: number): PruneCandidate[] {\n if (rawOutput.length === 0) return [];\n const intentWords = tokenize(intent);\n const matchesIntent = (line: string): boolean => {\n const lower = line.toLowerCase();\n return intentWords.some((word) => lower.includes(word));\n };\n\n const condensed = condenseLines(rawOutput.split('\\n'));\n const balanced = condensed.filter((line) => {\n const trimmed = line.trim();\n if (trimmed.length === 0) return true;\n if (NOISE_LINE.test(trimmed) && !matchesIntent(trimmed)) return false;\n if (trimmed.includes('node_modules/') && !matchesIntent(trimmed)) return false;\n return true;\n });\n const aggressive = balanced.filter((line) => {\n const trimmed = line.trim();\n if (trimmed.length === 0) return true;\n return DIAGNOSTIC_MARK.test(trimmed) || matchesIntent(trimmed);\n });\n\n const drafts: Array<{ id: PruneCandidate['id']; text: string }> = [\n { id: 'aggressive', text: capToBudget(aggressive.join('\\n').trim(), maxTokens) },\n { id: 'balanced', text: capToBudget(balanced.join('\\n').trim(), maxTokens) },\n { id: 'conservative', text: capToBudget(condensed.join('\\n').trim(), maxTokens) }\n ];\n\n const seen = new Set<string>();\n return drafts\n .filter((draft) => {\n if (draft.text.length === 0 || seen.has(draft.text)) return false;\n seen.add(draft.text);\n return true;\n })\n .map((draft) => ({\n id: draft.id,\n label: pruneLabel(draft.id, rawOutput.length, draft.text.length),\n text: draft.text\n }));\n}\n\n/**\n * Candidate used when the ranking is unavailable: the balanced filter, which is\n * the safest reduction that still removes noise.\n * @param candidates - candidates of {@link buildPruneCandidates}.\n * @returns the local default, or `undefined` for an empty list.\n */\nexport function pickLocalPruneCandidate(candidates: readonly PruneCandidate[]): PruneCandidate | undefined {\n const balanced = candidates.find((candidate) => candidate.id === 'balanced');\n if (balanced !== undefined) return balanced;\n return candidates[Math.floor(candidates.length / 2)] ?? candidates[0];\n}\n\n/* -------------------------------------------------------------------------- */\n/* Format-independent template compression (fallback path only) */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Lines that always survive a template compression verbatim.\n *\n * A degraded run must not lose the line that explains why the run failed, so\n * these are forced anchors next to the first and last line of the output.\n */\nconst TEMPLATE_DIAGNOSTIC_LINE = /error|failed|FAIL|warn|exception|traceback|assert|exit code [1-9]|non-zero/i;\n\n/** One line standing in for a run of near-identical lines. */\nfunction templateOmittedMarker(omitted: number): string {\n return `… [${String(omitted)} similar lines omitted] …`;\n}\n\n/**\n * Reduce one line to the template later lines are compared against.\n *\n * Variable tokens (UUIDs, timestamps, IPs, hex ids, durations, percentages,\n * floats, plain numbers) become placeholders and runs of whitespace collapse,\n * so \"progress 001\" and \"progress 002\" share a template while two genuinely\n * different lines do not. The original line is what is printed, never this\n * string.\n * @param line - one line of the output.\n * @returns its shape, whitespace-normalized.\n */\nexport function templateOfLine(line: string): string {\n let template = line.trim();\n template = template.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '<uuid>');\n template = template.replace(/\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}:\\d{2}(?:[.,]\\d+)?(?:Z|[+-]\\d{2}:?\\d{2})?/g, '<time>');\n template = template.replace(/\\b\\d{1,3}(?:\\.\\d{1,3}){3}\\b/g, '<ip>');\n template = template.replace(/\\b0x[0-9a-f]+\\b/gi, '<hex>');\n template = template.replace(/\\b[0-9a-f]{8,}\\b/gi, '<hex>');\n template = template.replace(/\\b\\d{1,2}(?::\\d{2}){1,2}(?:[.,]\\d+)?\\b/g, '<time>');\n template = template.replace(/\\d+(?:\\.\\d+)?\\s?%/g, '<pct>');\n template = template.replace(/\\b\\d+(?:\\.\\d+)?\\s?(?:ms|secs?|seconds?|mins?|minutes?|hours?|h)\\b/gi, '<duration>');\n template = template.replace(/\\d+\\.\\d+/g, '<float>');\n template = template.replace(/\\d+/g, '<num>');\n return template.replace(/\\s+/g, ' ').trim();\n}\n\n/**\n * Compress a bulk output by its line templates, independent of any format.\n *\n * Consecutive lines whose templates match form a run: a run of four or more\n * keeps its first two and its last line and replaces the rest with one marker.\n * Consecutive blank lines collapse to one. The first line, the last line and\n * every diagnostic line survive verbatim. This is the fallback used when System\n * One cannot judge — it never replaces a real decision.\n * @param rawOutput - the bulk output to reduce.\n * @returns the reduced text; never longer than the input.\n */\nexport function compressByTemplate(rawOutput: string): string {\n if (rawOutput.length === 0) return rawOutput;\n const lines = rawOutput.split('\\n');\n if (lines.length <= 2) return rawOutput;\n\n const lastIndex = lines.length - 1;\n const out: string[] = [];\n let index = 0;\n\n while (index <= lastIndex) {\n const line = lines[index] as string;\n const blank = line.trim().length === 0;\n if (blank) {\n let end = index;\n while (end + 1 <= lastIndex && (lines[end + 1] as string).trim().length === 0) end++;\n out.push(index === 0 || end === lastIndex ? line : '');\n index = end + 1;\n continue;\n }\n\n if (index === 0 || index === lastIndex || TEMPLATE_DIAGNOSTIC_LINE.test(line)) {\n out.push(line);\n index += 1;\n continue;\n }\n\n const template = templateOfLine(line);\n let end = index;\n while (\n end + 1 < lastIndex &&\n (lines[end + 1] as string).trim().length > 0 &&\n !TEMPLATE_DIAGNOSTIC_LINE.test(lines[end + 1] as string) &&\n templateOfLine(lines[end + 1] as string) === template\n ) {\n end += 1;\n }\n\n const run = end - index + 1;\n if (run >= 4) {\n out.push(lines[index] as string, lines[index + 1] as string, templateOmittedMarker(run - 3), lines[end] as string);\n } else {\n for (let cursor = index; cursor <= end; cursor++) out.push(lines[cursor] as string);\n }\n index = end + 1;\n }\n\n const compressed = out.join('\\n');\n return compressed.length < rawOutput.length ? compressed : rawOutput;\n}\n\n/* -------------------------------------------------------------------------- */\n/* System One segment judging */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Character count from which {@link JevDecisionBackend.prune} judges segments\n * with System One. Kept in sync with `interventions.pruneJudgeMinChars`.\n */\nexport const PRUNE_JUDGE_MIN_CHARS_DEFAULT = 10000;\n\n/** A scored segment never exceeds this many characters (a single long line stays whole). */\nconst PRUNE_SEGMENT_MAX_CHARS = 1600;\n\n/** Upper bound on segments judged by one request; the rest are kept deterministically. */\nexport const PRUNE_MAX_JUDGED_SEGMENTS = 40;\n\n/** Prefix of the per-segment question ids of a pruning judgment. */\nexport const PRUNE_SEGMENT_QUESTION_PREFIX = 'prune-seg-';\n\n/** Criterion pair of one segment question; index 1 (keep) is the score we read. */\nconst PRUNE_KEEP_CRITERIA: readonly string[] = [\n 'omit: repetitive, irrelevant, or safe to drop',\n 'keep: unique, relevant, or diagnostic content'\n];\n\n/**\n * Share of the original characters each candidate may spend on scored\n * segments. Forced lines (anchors, diagnostics, intent matches) never compete\n * with this budget.\n */\nconst PRUNE_SCORED_BUDGET_RATIO: Readonly<Record<PruneCandidate['id'], number>> = {\n aggressive: 0.25,\n balanced: 0.5,\n conservative: 0.7\n};\n\n/**\n * Lines that must survive verbatim whatever the segment score says: diagnostic\n * evidence, plus the first and last content lines of the payload. Matched\n * case-insensitively.\n */\nconst PRUNE_FORCED_LINE =\n /error|failed|FAIL|warn|exception|traceback|assert|exit code [1-9]|non-zero/i;\n\n/**\n * Resolve the segment-judging character threshold from an explicit value, then\n * the environment, then the documented default.\n * @param value - explicit backend configuration, when supplied.\n * @returns a non-negative finite character count.\n */\nexport function resolvePruneJudgeMinChars(value?: number): number {\n const raw = value ?? process.env.SYSTEM_ONE_PRUNE_JUDGE_MIN_CHARS;\n const numeric = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim().length > 0 ? Number(raw) : NaN;\n if (Number.isFinite(numeric) && numeric >= 0) return Math.floor(numeric);\n return PRUNE_JUDGE_MIN_CHARS_DEFAULT;\n}\n\n/** One contiguous run of non-blank lines, the unit System One judges. */\ninterface PruneSegment {\n /** Position in the original output, oldest first. */\n index: number;\n /** 0-based inclusive line range in the original output. */\n startLine: number;\n endLine: number;\n /** The segment text exactly as it appears in the output. */\n text: string;\n chars: number;\n /** Absolute line indexes always kept, regardless of the score. */\n forcedLines: number[];\n}\n\n/** Whether one line carries diagnostic evidence or matches the intent. */\nfunction isForcedPruneLine(line: string, intentWords: readonly string[]): boolean {\n if (PRUNE_FORCED_LINE.test(line)) return true;\n const lower = line.toLowerCase();\n return intentWords.some((word) => lower.includes(word));\n}\n\n/**\n * Cut an output into the segments System One judges.\n *\n * Paragraphs are separated by blank lines; a paragraph longer than\n * {@link PRUNE_SEGMENT_MAX_CHARS} is split on line windows, so the model never\n * sees one oversized block and the local replay can reassemble the exact lines.\n * Line order and line numbers are preserved: every segment is a half-open view\n * of the original line array.\n * @param rawOutput - the bulk output.\n * @param intent - what the caller is looking for.\n * @returns segments in original order, with their forced line indexes.\n */\nexport function segmentPruneOutput(rawOutput: string, intent: string): PruneSegment[] {\n const lines = rawOutput.split('\\n');\n const intentWords = tokenize(intent);\n const segments: PruneSegment[] = [];\n\n let firstContent = -1;\n let lastContent = -1;\n for (let index = 0; index < lines.length; index++) {\n if ((lines[index] as string).trim().length === 0) continue;\n if (firstContent < 0) firstContent = index;\n lastContent = index;\n }\n\n const push = (startLine: number, endLine: number): void => {\n const forced: number[] = [];\n for (let line = startLine; line <= endLine; line++) {\n const text = lines[line] as string;\n if (line === firstContent || line === lastContent || isForcedPruneLine(text, intentWords)) {\n forced.push(line);\n }\n }\n const text = lines.slice(startLine, endLine + 1).join('\\n');\n segments.push({ index: segments.length, startLine, endLine, text, chars: text.length, forcedLines: forced });\n };\n\n let cursor = 0;\n while (cursor < lines.length) {\n while (cursor < lines.length && (lines[cursor] as string).trim().length === 0) cursor++;\n if (cursor >= lines.length) break;\n const blockStart = cursor;\n while (cursor < lines.length && (lines[cursor] as string).trim().length > 0) cursor++;\n const blockEnd = cursor - 1;\n\n let windowStart = blockStart;\n let windowChars = (lines[blockStart] as string).length;\n for (let line = blockStart + 1; line <= blockEnd; line++) {\n const length = (lines[line] as string).length + 1;\n if (windowChars + length > PRUNE_SEGMENT_MAX_CHARS) {\n push(windowStart, line - 1);\n windowStart = line;\n windowChars = (lines[line] as string).length;\n } else {\n windowChars += length;\n }\n }\n push(windowStart, blockEnd);\n }\n return segments;\n}\n\n/** Instruction block of one segment question. */\nfunction buildSegmentInstructions(intent: string, segment: PruneSegment, total: number): string {\n const trimmed = intent.trim() || 'extract diagnostics, relevant results and errors';\n return [\n 'Decide whether one segment of a tool output must be kept to serve the INTENT, or may be omitted as noise.',\n `INTENT: ${trimmed}`,\n `SEGMENT: ${String(segment.index + 1)} of ${String(total)} (lines ${String(segment.startLine + 1)}-${String(segment.endLine + 1)}).`,\n 'Score 0 when the segment is repetitive or irrelevant; score 1 when it carries information the INTENT needs.'\n ].join('\\n');\n}\n\n/**\n * Read one segment's keep score (0 = omit, 1 = keep) out of its `score` answer.\n * The distribution over the two criteria is authoritative; the weighted `score`\n * is the fallback, and nothing usable reads as `undefined`.\n * @param answer - the gateway's answer for this segment question.\n * @returns the keep score in `[0, 1]`, or `undefined` when unusable.\n */\nexport function readSegmentKeepScore(answer: SystemOneScoreAnswer | undefined): number | undefined {\n if (answer === undefined || answer === null) return undefined;\n const distribution = readDistribution(answer.probabilities, ['0', '1']);\n if (distribution !== undefined) return round4(toProbability(distribution.get('1')));\n const raw = typeof answer.score === 'number' ? answer.score : Number(answer.score);\n if (!Number.isFinite(raw)) return undefined;\n return round4(Math.min(1, Math.max(0, raw)));\n}\n\n/**\n * Pick the segments a budget keeps from their scores.\n *\n * Segments without a usable score are an unjudged safety margin and are always\n * kept; scored segments are taken from the highest score down until the\n * character budget is spent. Ties follow the original order.\n * @param segments - all segments of the output.\n * @param scores - keep score per segment index, absent for unjudged segments.\n * @param originalChars - character count of the unpruned output.\n * @param ratio - share of the original characters scored segments may use.\n * @returns indexes of the segments this candidate keeps in full.\n */\nexport function selectPruneSegments(\n segments: readonly PruneSegment[],\n scores: ReadonlyMap<number, number>,\n originalChars: number,\n ratio: number\n): Set<number> {\n const selected = new Set<number>();\n let used = 0;\n for (const segment of segments) {\n if (scores.has(segment.index)) continue;\n selected.add(segment.index);\n used += segment.chars;\n }\n const budget = Math.floor(originalChars * ratio);\n const ranked = segments\n .filter((segment) => scores.has(segment.index))\n .sort((left, right) => {\n const difference = (scores.get(right.index) ?? 0) - (scores.get(left.index) ?? 0);\n return difference !== 0 ? difference : left.index - right.index;\n });\n for (const segment of ranked) {\n // Stop at the budget instead of skipping ahead: a smaller low-score segment\n // must never slip into the space a higher-score one did not fit.\n if (used + segment.chars > budget) break;\n selected.add(segment.index);\n used += segment.chars;\n }\n return selected;\n}\n\n/** Build the marker of one run of omitted segments. */\nfunction omittedSegmentsMarker(count: number): string {\n return `… [${String(count)} segments omitted] …`;\n}\n\n/**\n * Reassemble one candidate in the original line order.\n *\n * A selected segment is kept whole; an unselected one keeps only its forced\n * lines (first/last anchors, diagnostics, intent matches). Consecutive fully\n * omitted segments collapse into one marker that names how many were dropped.\n * Blank runs between kept lines collapse to a single blank line.\n * @param rawOutput - the original output, for its lines.\n * @param segments - segments in original order.\n * @param selected - segment indexes kept whole.\n * @returns the reduced text.\n */\nexport function assemblePruneCandidate(\n rawOutput: string,\n segments: readonly PruneSegment[],\n selected: ReadonlySet<number>\n): string {\n const lines = rawOutput.split('\\n');\n const out: string[] = [];\n let omitted = 0;\n let lastEmitted = -1;\n\n const emitLine = (lineIndex: number): void => {\n if (lastEmitted >= 0 && lineIndex > lastEmitted + 1) out.push('');\n out.push(lines[lineIndex] as string);\n lastEmitted = lineIndex;\n };\n const flushOmitted = (): void => {\n if (omitted === 0) return;\n out.push(omittedSegmentsMarker(omitted));\n omitted = 0;\n };\n\n for (const segment of segments) {\n // A selected segment is kept whole; an unselected one keeps forced lines only.\n const keepWhole = selected.has(segment.index);\n const lineIndexes: number[] = [];\n if (keepWhole) {\n for (let line = segment.startLine; line <= segment.endLine; line++) lineIndexes.push(line);\n } else {\n lineIndexes.push(...segment.forcedLines);\n }\n if (lineIndexes.length === 0) {\n omitted++;\n continue;\n }\n flushOmitted();\n for (const lineIndex of lineIndexes) emitLine(lineIndex);\n }\n flushOmitted();\n return out.join('\\n').trim();\n}\n\n/** Label of one score-driven candidate, including its reduction. */\nfunction scoredPruneLabel(id: PruneCandidate['id'], originalChars: number, prunedChars: number): string {\n const strategy: Record<PruneCandidate['id'], string> = {\n aggressive: 'keeps the segments System One judged essential within a quarter of the original',\n balanced: 'keeps the segments System One judged essential within half of the original',\n conservative: 'keeps the segments System One judged essential within most of the original'\n };\n const reduction = originalChars > 0 ? Math.round(((originalChars - prunedChars) / originalChars) * 100) : 0;\n return `candidate \"${id}\" (${strategy[id]}, ${String(reduction)}% smaller)`;\n}\n\n/**\n * Build the three System One–scored prunings from one segment judgment.\n *\n * The segment keep/drop decision is the model's score; the three ids only\n * differ in their character budget, so the ranking the engine used to make is\n * now made per segment.\n * @param rawOutput - the original output.\n * @param segments - segments of that output in original order.\n * @param scores - keep score per segment index.\n * @param maxTokens - optional hard token ceiling applied to every candidate.\n * @returns candidates ordered from aggressive to conservative.\n */\nexport function buildScoredPruneCandidates(\n rawOutput: string,\n segments: readonly PruneSegment[],\n scores: ReadonlyMap<number, number>,\n maxTokens?: number\n): PruneCandidate[] {\n const ids: PruneCandidate['id'][] = ['aggressive', 'balanced', 'conservative'];\n return ids.map((id) => {\n const selected = selectPruneSegments(segments, scores, rawOutput.length, PRUNE_SCORED_BUDGET_RATIO[id]);\n const text = capToBudget(assemblePruneCandidate(rawOutput, segments, selected), maxTokens);\n return { id, label: scoredPruneLabel(id, rawOutput.length, text.length), text, keptSegments: selected.size };\n });\n}\n\n/** The scored candidate one segment judgment installs, and why it did. */\nexport interface ScoredPrunePick {\n /** The text the segmented path returns: a reducing candidate, or the raw output. */\n text: string;\n /** The candidate that reduced the payload; absent when none did. */\n candidate?: PruneCandidate;\n /** Why no scored candidate was used, when none was. */\n reason?: string;\n}\n\n/**\n * Pick the first scored candidate strictly smaller than the payload.\n *\n * The balanced budget is tried first because it is the documented default. A\n * payload whose forced lines (anchors, diagnostics, intent matches) already\n * reproduce it verbatim makes even the balanced candidate as large as the\n * original; the tighter and then the wider budget are tried before giving up,\n * so a smaller aggressive candidate is never thrown away by the balanced one.\n * A candidate that does not reduce the payload is never returned as the text:\n * the caller treats that outcome as a judgment that kept everything, unless the\n * judgment produced no usable score at all.\n * @param rawOutput - the original output the candidates were built from.\n * @param candidates - the scored candidates, in any order.\n * @returns the reducing text plus the candidate that produced it, or the raw\n * output plus the reason no candidate was usable.\n */\nexport function pickScoredPruneCandidate(\n rawOutput: string,\n candidates: readonly PruneCandidate[]\n): ScoredPrunePick {\n const order: PruneCandidate['id'][] = ['balanced', 'aggressive', 'conservative'];\n for (const id of order) {\n const candidate = candidates.find((entry) => entry.id === id);\n if (candidate !== undefined && candidate.text.length < rawOutput.length) return { text: candidate.text, candidate };\n }\n return { text: rawOutput, reason: 'no scored candidate is smaller than the payload' };\n}\n\n\n/* -------------------------------------------------------------------------- */\n/* Local fallbacks */\n/* -------------------------------------------------------------------------- */\n\n/** A local stagnation verdict, used when the gateway cannot supply one. */\nexport interface LocalStagnationVerdict {\n isStuck: boolean;\n patternType: StagnationPattern;\n confidence: number;\n diagnosis: string;\n recommendedIntervention?: string;\n}\n\n/**\n * Deterministic stagnation detector over a recent action window.\n *\n * It is the offline half of {@link JevDecisionBackend.checkStagnation}: the\n * gateway classifies the pattern, and this reads the same history with explicit\n * rules, so a dead gateway degrades the verdict instead of losing it.\n * @param recent - the recent action window, oldest first.\n * @returns the locally detected pattern.\n */\nexport function detectStagnationLocally(recent: readonly ActionStep[]): LocalStagnationVerdict {\n const stuck = (patternType: Exclude<StagnationPattern, 'none'>, confidence: number): LocalStagnationVerdict => ({\n isStuck: true,\n patternType,\n confidence,\n diagnosis: `${STAGNATION_DIAGNOSIS[patternType]} [local heuristic]`,\n recommendedIntervention: STAGNATION_INTERVENTION[patternType]\n });\n\n const signatures = recent.map((step) => `${step.tool}:${(step.input ?? '').trim()}`);\n let identical = 1;\n for (let index = signatures.length - 1; index > 0; index--) {\n if (signatures[index] === signatures[index - 1]) identical++;\n else break;\n }\n if (identical >= 3) return stuck('repetition', 0.95);\n\n const failing = recent.filter(\n (step) => Boolean(step.error) || /(?:error|fail|panic|not ok)/i.test(step.output ?? '')\n );\n if (failing.length >= 3 && recent.length >= 4) return stuck('failing_retry', 0.85);\n\n if (recent.length >= 4) {\n const last = recent.slice(-4);\n const alternates =\n last[0]?.tool === last[2]?.tool &&\n last[1]?.tool === last[3]?.tool &&\n last[0]?.input === last[2]?.input &&\n last[1]?.input === last[3]?.input;\n if (alternates) return stuck('oscillation', 0.9);\n }\n\n return {\n isStuck: false,\n patternType: 'none',\n confidence: 0.6,\n diagnosis: `${STAGNATION_DIAGNOSIS.none} [local heuristic]`\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* The adapter */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Jev System One Provider Adapter\n *\n * Speaks only the current gateway contract: one `POST /v1/systemone` carrying\n * `{ model, state, questions }`, where every question is a `choice` between\n * criteria or a `score` over a criteria list. The gateway returns discrete\n * distributions, never free text, so the four composite capabilities\n * (`gate`, `prune`, `checkStagnation`, `route`) are expressed as criteria\n * questions and backed by deterministic local fallbacks.\n */\nexport class JevDecisionBackend implements DecisionBackend {\n readonly name = 'system-one-jev';\n readonly model: string;\n /** Absolute URL of the single endpoint; no call appends a sub-path to it. */\n readonly endpoint: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n /** Character count from which pruning judges segments through System One. */\n private readonly pruneJudgeMinChars: number;\n /**\n * Health of the gateway conversation of this backend.\n *\n * Every request updates it; a success clears the failure fields and resets the\n * run. It lives in memory only, so a restarted Host starts healthy.\n */\n private healthState: BackendHealth = { available: true, consecutiveFailures: 0 };\n\n constructor(config?: JevBackendConfig) {\n this.endpoint = normalizeSystemOneEndpoint(\n config?.baseUrl ||\n process.env.SYSTEM_ONE_BASE_URL ||\n process.env.JEV_BASE_URL ||\n process.env.JEV_API_BASE ||\n DEFAULT_SYSTEMONE_ENDPOINT\n );\n this.apiKey =\n config?.apiKey ||\n process.env.SYSTEM_ONE_API_KEY ||\n process.env.JEV_API_KEY ||\n '';\n this.model =\n config?.model ||\n process.env.SYSTEM_ONE_MODEL ||\n process.env.JEV_MODEL ||\n 'jev-latest';\n this.timeoutMs = config?.timeoutMs || 10000;\n this.pruneJudgeMinChars = resolvePruneJudgeMinChars(config?.pruneJudgeMinChars);\n }\n\n /**\n * Health of the outbound gateway conversation.\n * @returns a copy of the counters, safe to hand to a panel snapshot.\n */\n health(): BackendHealth {\n return { ...this.healthState };\n }\n\n /** Record one successful request: the backend is available again. */\n private noteSuccess(): void {\n this.healthState = { available: true, consecutiveFailures: 0 };\n }\n\n /** Record one failed request and its reason. */\n private noteFailure(reason: string): void {\n this.healthState = {\n available: false,\n lastFailureReason: reason,\n lastFailureAt: new Date().toISOString(),\n consecutiveFailures: this.healthState.consecutiveFailures + 1\n };\n }\n\n /**\n * Send one request to the single endpoint.\n * @param questions - questions keyed by id; answers come back under the same ids.\n * @param state - machine-readable situation the questions reason about.\n * @returns the gateway's answer envelope.\n */\n private async postSystemOne(\n questions: Record<string, SystemOneQuestion>,\n state: Record<string, unknown>\n ): Promise<SystemOneResponse> {\n const body: SystemOneRequest = { model: this.model, state, questions };\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const resp = await fetch(this.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(this.apiKey.length > 0 ? { Authorization: `Bearer ${this.apiKey}` } : {})\n },\n body: JSON.stringify(body),\n signal: controller.signal\n });\n\n if (!resp.ok) {\n const text = await resp.text();\n throw new Error(`Jev API error (${resp.status} ${resp.statusText}): ${text.slice(0, 500)}`);\n }\n\n const data = (await resp.json()) as SystemOneResponse;\n if (!data || typeof data !== 'object' || typeof data.answers !== 'object' || data.answers === null) {\n throw new Error('Jev API response carries no answers object');\n }\n this.noteSuccess();\n return data;\n } catch (err) {\n this.noteFailure(errorMessage(err));\n throw err;\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * Classify one question into a probability distribution over the options.\n *\n * The options become the `criteria` dictionary (key = option label, value =\n * the description the model reads) and `answers[id].probabilities` — keyed by\n * criterion — becomes the returned option distribution. An answer without a\n * usable distribution fails loudly: the caller asked for a decision, and a\n * fabricated one would be worse than an error.\n * @param req - question, options, optional context.\n * @returns options sorted by probability, plus the winning option.\n */\n async choice(req: ChoiceRequest): Promise<ChoiceResponse> {\n const start = performance.now();\n try {\n const labels = Array.isArray(req.options) ? req.options : [];\n if (labels.length === 0) throw new Error('at least one option is required');\n\n const keys = uniqueCriteriaKeys(labels);\n const criteria: Record<string, string> = {};\n keys.forEach((key, index) => {\n criteria[key] = typeof labels[index] === 'string' ? (labels[index] as string) : key;\n });\n\n const context = (req.context ?? '').trim();\n const data = await this.postSystemOne(\n {\n [CHOICE_QUESTION_ID]: {\n type: 'choice',\n instructions: buildChoiceInstructions(req.question),\n criteria\n }\n },\n context.length > 0 ? { context } : {}\n );\n\n const answer = data.answers?.[CHOICE_QUESTION_ID] as SystemOneChoiceAnswer | undefined;\n const scored = toChoiceOptions(labels, keys, readDistribution(answer?.probabilities, keys), answer);\n if (scored === undefined) {\n throw new Error('the gateway returned neither a probability distribution nor a named criterion');\n }\n\n const options = scored.options;\n return {\n options,\n bestOption: options[0]?.label ?? '',\n confidence: options[0]?.probability ?? 0,\n uncalibrated: scored.uncalibrated,\n latencyMs: elapsed(start)\n };\n } catch (err) {\n throw new Error(`[JevBackend.choice] Failed: ${errorMessage(err)}`);\n }\n }\n\n /**\n * Verify assertions against evidence, fail-closed.\n *\n * Every assertion becomes one `choice` question in the same request, and the\n * answer's distribution over `verified` / `contradicted` / `not_addressed`\n * becomes the verdict. Anything unusable — a failed call, a missing answer, a\n * distribution below the strictness floor — escalates that assertion; the\n * method never returns a pass it could not observe.\n * @param req - assertions, evidence, strictness.\n * @returns one result per assertion plus the aggregate verdict.\n */\n async gate(req: GateRequest): Promise<GateResponse> {\n const start = performance.now();\n const assertions = Array.isArray(req.assertions) ? req.assertions : [];\n const strictness = req.strictness ?? 'normal';\n\n try {\n if (assertions.length === 0 || (req.evidence ?? '').trim().length === 0) {\n return this.failClosedGate(assertions, 'Evidence is empty or no assertions were supplied. Fail-closed.');\n }\n\n const ids = assertions.map((_, index) => `${GATE_QUESTION_PREFIX}${String(index)}`);\n const questions: Record<string, SystemOneQuestion> = {};\n assertions.forEach((assertion, index) => {\n questions[ids[index] as string] = {\n type: 'choice',\n instructions: buildGateInstructions(assertion, strictness),\n criteria: { ...GATE_VERDICT_CRITERIA }\n };\n });\n\n const context = (req.context ?? '').trim();\n const data = await this.postSystemOne(questions, {\n evidence: req.evidence,\n strictness,\n ...(context.length > 0 ? { context } : {})\n });\n\n const results: GateResultItem[] = assertions.map((assertion, index) =>\n this.gateItem(assertion, data.answers?.[ids[index] as string], strictness)\n );\n\n let passed = true;\n let needsEscalation = false;\n for (const item of results) {\n if (item.outcome === 'verified') continue;\n passed = false;\n if (item.outcome === 'escalate') needsEscalation = true;\n else if (item.outcome === 'not_addressed' && strictness !== 'lenient') needsEscalation = true;\n }\n\n return {\n passed: passed && !needsEscalation,\n results,\n needsEscalation,\n latencyMs: elapsed(start)\n };\n } catch (err) {\n return this.failClosedGate(\n assertions,\n `Jev API call failed: ${errorMessage(err)}. Fail-closed escalation triggered.`\n );\n }\n }\n\n /**\n * Classify whether each candidate sentence claims the task is complete.\n *\n * One `score` question per sentence, all in a single request. The two criteria\n * are ordered so index 1 is \"claims completion\"; the distribution over that\n * index is the answer. A sentence without a usable answer is left out of the\n * result rather than guessed, and the caller decides what an incomplete batch\n * means (the closing check fails open).\n * @param req - candidate sentences and the turn's intent.\n * @returns the classified sentences plus the request latency.\n */\n async classifyClaims(req: ClaimClassificationRequest): Promise<ClaimClassificationResponse> {\n const start = performance.now();\n const statements = Array.isArray(req.statements) ? req.statements.slice(0, MAX_CLAIM_SENTENCES) : [];\n if (statements.length === 0) return { results: [], latencyMs: elapsed(start) };\n\n try {\n const questions: Record<string, SystemOneQuestion> = {};\n const stateStatements: Record<string, string> = {};\n statements.forEach((statement, index) => {\n const id = `${CLAIM_QUESTION_PREFIX}${String(index)}`;\n questions[id] = {\n type: 'score',\n instructions: buildClaimInstructions(statement, req.intent),\n criteria: [...CLAIM_CRITERIA]\n };\n stateStatements[id] = statement;\n });\n\n const data = await this.postSystemOne(questions, {\n task: 'closing-claim',\n intent: req.intent,\n ...(req.context !== undefined && req.context.length > 0 ? { context: req.context } : {}),\n statements: stateStatements\n });\n\n const results: ClaimClassification[] = [];\n statements.forEach((statement, index) => {\n const id = `${CLAIM_QUESTION_PREFIX}${String(index)}`;\n const answer = data.answers?.[id] as SystemOneScoreAnswer | undefined;\n const classified = readClaimAnswer(statement, answer);\n if (classified !== undefined) results.push(classified);\n });\n return { results, latencyMs: elapsed(start) };\n } catch (err) {\n throw new Error(`[JevBackend.classifyClaims] Failed: ${errorMessage(err)}`);\n }\n }\n\n /** One assertion's outcome from its answer; unusable answers escalate. */\n private gateItem(\n assertion: GateAssertion,\n answer: SystemOneChoiceAnswer | SystemOneScoreAnswer | undefined,\n strictness: 'high' | 'normal' | 'lenient'\n ): GateResultItem {\n const statement = assertion?.statement ?? '';\n const choiceAnswer = answer as SystemOneChoiceAnswer | undefined;\n const distribution = readDistribution(choiceAnswer?.probabilities, GATE_VERDICTS);\n if (distribution === undefined) {\n return {\n statement,\n outcome: 'escalate',\n confidence: 0,\n explanation: 'The gateway returned no usable verdict distribution for this assertion. Fail-closed escalation.'\n };\n }\n\n const verdict = argmaxKey(distribution, GATE_VERDICTS) as GateVerdict;\n const confidence = round4(distribution.get(verdict) ?? 0);\n const floor = GATE_CONFIDENCE_FLOOR[strictness];\n if (confidence < floor) {\n return {\n statement,\n outcome: 'escalate',\n confidence,\n explanation: `System One named \"${verdict}\" at ${(confidence * 100).toFixed(1)}%, below the ${strictness} floor of ${(floor * 100).toFixed(0)}%. Fail-closed escalation.`\n };\n }\n\n return {\n statement,\n outcome: verdict,\n confidence,\n explanation: `System One named \"${verdict}\" at ${(confidence * 100).toFixed(1)}% (evidence supplied as state).`\n };\n }\n\n /** Every assertion escalated for one reason — the fail-closed shape. */\n private failClosedGate(assertions: readonly GateAssertion[], reason: string): GateResponse {\n const started = performance.now();\n return {\n passed: false,\n needsEscalation: true,\n results: assertions.map((assertion) => ({\n statement: assertion?.statement ?? '',\n outcome: 'escalate' as const,\n confidence: 0,\n explanation: reason\n })),\n latencyMs: elapsed(started)\n };\n }\n\n /**\n * Reduce a bulk output to the segments the intent needs, fail-open.\n *\n * Two paths share one contract. A payload below `pruneJudgeMinChars` is\n * reduced by the deterministic local candidates and sends no request at all.\n * A payload at/above it is cut into segments, and one `score` question per\n * segment lets System One decide what to keep; the three budgets only decide\n * how much of the top-scored material fits. Forced lines (first/last anchors,\n * diagnostics, intent matches) survive either way. Any failure — call,\n * transport, unusable answer — falls back to the local candidates, so pruning\n * never breaks the harness and never returns the raw blob just because the\n * network blinked.\n * @param req - raw output, intent, budget, shadow flag.\n * @returns the pruned text plus its reduction metrics and the path taken.\n */\n async prune(req: PruneRequest): Promise<PruneResponse> {\n const start = performance.now();\n const raw = typeof req.rawOutput === 'string' ? req.rawOutput : '';\n const intent = req.intent ?? '';\n if (raw.length === 0) return this.pruneResponse(raw, raw, req.shadowMode, start, { judgePath: 'local' });\n\n // The caller's resolved config is authoritative; the backend's own value\n // (explicit config, then environment, then default) is the fallback.\n const judgeMinChars = req.pruneJudgeMinChars ?? this.pruneJudgeMinChars;\n if (raw.length < judgeMinChars) {\n return this.pruneResponse(raw, this.localPruneText(raw, intent, req.maxTokens), req.shadowMode, start, {\n judgePath: 'local'\n });\n }\n return this.pruneWithSegments(req, raw, intent, start);\n }\n\n /** The deterministic candidate text, or the raw output when it does not shrink. */\n private localPruneText(raw: string, intent: string, maxTokens?: number): string {\n const candidates = buildPruneCandidates(raw, intent, maxTokens);\n const local = pickLocalPruneCandidate(candidates);\n if (local === undefined) return raw;\n return local.text.length < raw.length ? local.text : raw;\n }\n\n /**\n * Reduce the payload when System One cannot judge it.\n *\n * Template compression is format-independent, so it still shrinks output the\n * deterministic line filters cannot (progress art they would drop entirely, a\n * table whose rows differ only by a number). It is only ever used here, on the\n * degraded path, and the smaller of it and the local candidates wins.\n * @param raw - the original output.\n * @param intent - what the caller is looking for.\n * @param maxTokens - optional token budget.\n * @returns the reduced text and which strategy produced it.\n */\n private fallbackPruneText(\n raw: string,\n intent: string,\n maxTokens?: number\n ): { text: string; compression: 'template' | 'local' } {\n const local = this.localPruneText(raw, intent, maxTokens);\n const template = compressByTemplate(raw);\n if (template.length < local.length) return { text: template, compression: 'template' };\n return { text: local, compression: 'local' };\n }\n\n /** The per-segment System One path, with the local candidates as its fallback. */\n private async pruneWithSegments(\n req: PruneRequest,\n raw: string,\n intent: string,\n start: number\n ): Promise<PruneResponse> {\n const segments = segmentPruneOutput(raw, intent);\n if (segments.length <= 1) {\n // One segment has nothing to choose between; spending a judgment would\n // only reproduce the whole payload.\n return this.pruneResponse(raw, this.localPruneText(raw, intent, req.maxTokens), req.shadowMode, start, {\n judgePath: 'local',\n judgedSegments: 0,\n unjudgedSegments: segments.length\n });\n }\n\n const judged = segments.slice(0, PRUNE_MAX_JUDGED_SEGMENTS);\n const unjudgedSegments = segments.length - judged.length;\n const diagnostics = { judgedSegments: judged.length, unjudgedSegments };\n\n try {\n const { scores, unparsedScoreAnswers } = await this.scoreSegments(judged, segments.length, intent);\n // Every segment without a usable score is kept whole as the unjudged\n // safety margin, so its share of the payload is the first number to read\n // when a judgment \"ran\" but the candidate did not shrink.\n const observation = {\n ...diagnostics,\n scoredSegments: scores.size,\n autoKeptSegments: segments.length - scores.size,\n unparsedScoreAnswers\n };\n if (scores.size === 0) {\n const fallback = this.fallbackPruneText(raw, intent, req.maxTokens);\n return this.pruneResponse(raw, fallback.text, req.shadowMode, start, {\n judgePath: 'fallback',\n fallbackReason: 'System One returned no usable segment score',\n compression: fallback.compression,\n ...observation\n });\n }\n const candidates = buildScoredPruneCandidates(raw, segments, scores, req.maxTokens);\n const charsOf = (id: PruneCandidate['id']): number =>\n candidates.find((candidate) => candidate.id === id)?.text.length ?? raw.length;\n const sizes = {\n aggressiveChars: charsOf('aggressive'),\n balancedChars: charsOf('balanced'),\n conservativeChars: charsOf('conservative')\n };\n // The balanced candidate's selection answers \"did the judge keep too much\n // to shrink anything\"; when another budget was installed, its own count is\n // what survived, so report that one instead.\n const balanced = candidates.find((candidate) => candidate.id === 'balanced');\n const pick = pickScoredPruneCandidate(raw, candidates);\n if (pick.candidate !== undefined) {\n return this.pruneResponse(raw, pick.text, req.shadowMode, start, {\n judgePath: 'segmented',\n ...observation,\n ...sizes,\n keptSegments: pick.candidate.keptSegments\n });\n }\n // The judgment kept as much as the payload: every segment was scored and\n // kept whole. That is the model's decision, not a service failure, so the\n // payload is returned untouched instead of being template-compressed over\n // it. Only a judgment with no usable score at all (handled above) and a\n // failed call (below) fall back to template compression.\n return this.pruneResponse(raw, raw, req.shadowMode, start, {\n judgePath: 'segmented',\n fallbackReason: 'judged: every segment was kept',\n compression: 'none',\n ...observation,\n ...sizes,\n ...(balanced === undefined ? {} : { keptSegments: balanced.keptSegments })\n });\n } catch (err) {\n // FAIL-OPEN: template compression keeps the pruned output useful even when\n // the deterministic line filters have nothing to drop; the harness never\n // breaks and never returns the raw blob just because the gateway blinked.\n const fallback = this.fallbackPruneText(raw, intent, req.maxTokens);\n return this.pruneResponse(raw, fallback.text, req.shadowMode, start, {\n judgePath: 'fallback',\n fallbackReason: errorMessage(err),\n compression: fallback.compression,\n ...diagnostics\n });\n }\n }\n\n /**\n * Judge every segment in one request: one `score` question per segment, with\n * the segment text and the intent in the shared state.\n * @param judged - the segments selected for judging, in original order.\n * @param totalSegments - segment count of the whole output (for the prompt).\n * @param intent - what the caller is looking for.\n * @returns the keep score per segment index (segments without a usable answer\n * are absent) and how many answers were returned but could not be read.\n */\n private async scoreSegments(\n judged: readonly PruneSegment[],\n totalSegments: number,\n intent: string\n ): Promise<{ scores: Map<number, number>; unparsedScoreAnswers: number }> {\n const questions: Record<string, SystemOneQuestion> = {};\n const stateSegments: Record<string, string> = {};\n for (const segment of judged) {\n const id = `${PRUNE_SEGMENT_QUESTION_PREFIX}${String(segment.index)}`;\n questions[id] = {\n type: 'score',\n instructions: buildSegmentInstructions(intent, segment, totalSegments),\n criteria: [...PRUNE_KEEP_CRITERIA]\n };\n stateSegments[id] = segment.text;\n }\n\n const data = await this.postSystemOne(questions, {\n intent,\n segments: stateSegments,\n judgedSegments: judged.length,\n unjudgedSegments: totalSegments - judged.length,\n segmentMaxChars: PRUNE_SEGMENT_MAX_CHARS\n });\n\n const scores = new Map<number, number>();\n let unparsedScoreAnswers = 0;\n for (const segment of judged) {\n const id = `${PRUNE_SEGMENT_QUESTION_PREFIX}${String(segment.index)}`;\n const answer = data.answers?.[id] as SystemOneScoreAnswer | undefined;\n const score = readSegmentKeepScore(answer);\n if (score !== undefined) {\n scores.set(segment.index, score);\n } else if (answer !== undefined && answer !== null) {\n // An answer we cannot read is not a high score: it is counted, and the\n // segment falls into the unjudged safety margin with no answer at all.\n unparsedScoreAnswers += 1;\n }\n }\n return { scores, unparsedScoreAnswers };\n }\n\n /** Shape one pruning as the shared prune response. */\n private pruneResponse(\n raw: string,\n text: string,\n shadow: boolean | undefined,\n start: number,\n meta?: PruneDiagnostics\n ): PruneResponse {\n const originalChars = raw.length;\n const prunedChars = text.length;\n return {\n processedOutput: shadow ? raw : text,\n originalChars,\n prunedChars,\n estimatedTokensSaved: Math.max(0, Math.ceil((originalChars - prunedChars) / 4)),\n reductionPercentage:\n originalChars > 0 ? Number((((originalChars - prunedChars) / originalChars) * 100).toFixed(1)) : 0,\n shadow: Boolean(shadow),\n latencyMs: elapsed(start),\n ...meta\n };\n }\n\n /**\n * Classify the recent action window into one execution pattern.\n *\n * One `choice` question over the five patterns; the distribution decides the\n * verdict and its confidence. When the gateway cannot answer, the same window\n * is read by {@link detectStagnationLocally}, so a network failure lowers the\n * quality of the verdict instead of removing it.\n * @param req - action history and optional goal.\n * @returns the pattern, whether it is stuck, and the intervention.\n */\n async checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse> {\n const start = performance.now();\n const history = Array.isArray(req.history) ? req.history : [];\n const windowSize = typeof req.windowSize === 'number' && req.windowSize > 0 ? req.windowSize : 6;\n const recent = history.slice(-windowSize);\n\n if (recent.length < 3) {\n return {\n isStuck: false,\n patternType: 'none',\n confidence: 1,\n diagnosis: 'Action count below stagnation threshold (< 3).',\n latencyMs: elapsed(start)\n };\n }\n\n try {\n const criteria: Record<string, string> = {};\n for (const pattern of STAGNATION_PATTERNS) criteria[pattern] = STAGNATION_PATTERN_CRITERIA[pattern];\n\n const data = await this.postSystemOne(\n {\n [STAGNATION_QUESTION_ID]: {\n type: 'choice',\n instructions: buildStagnationInstructions(),\n criteria\n }\n },\n {\n goal: (req.goal ?? '').trim() || null,\n window: recent.length,\n actions: recent.map((step) => ({\n tool: step.tool,\n input: clip(step.input, 240),\n ...(step.output === undefined ? {} : { output: clip(step.output, 240) }),\n ...(step.error === undefined ? {} : { error: clip(step.error, 240) })\n }))\n }\n );\n\n const answer = data.answers?.[STAGNATION_QUESTION_ID] as SystemOneChoiceAnswer | undefined;\n const distribution = readDistribution(answer?.probabilities, STAGNATION_PATTERNS);\n if (distribution === undefined) {\n return this.localStagnation(recent, 'the gateway returned no usable pattern distribution', start);\n }\n\n const pattern = argmaxKey(distribution, STAGNATION_PATTERNS) as StagnationPattern;\n const confidence = round4(distribution.get(pattern) ?? 0);\n const isStuck = pattern !== 'none' && confidence >= STAGNATION_STUCK_FLOOR;\n return {\n isStuck,\n patternType: pattern,\n confidence,\n diagnosis: `${STAGNATION_DIAGNOSIS[pattern]} (System One p=${confidence.toFixed(3)})`,\n ...(isStuck ? { recommendedIntervention: STAGNATION_INTERVENTION[pattern] } : {}),\n latencyMs: elapsed(start)\n };\n } catch (err) {\n return this.localStagnation(recent, errorMessage(err), start);\n }\n }\n\n /** The local half of {@link checkStagnation}, annotated with why it ran. */\n private localStagnation(recent: readonly ActionStep[], reason: string, start: number): StagnationCheckResponse {\n const local = detectStagnationLocally(recent);\n return {\n isStuck: local.isStuck,\n patternType: local.patternType,\n confidence: local.confidence,\n diagnosis: `${local.diagnosis} [System One unavailable: ${reason}]`,\n ...(local.recommendedIntervention === undefined\n ? {}\n : { recommendedIntervention: local.recommendedIntervention }),\n latencyMs: elapsed(start)\n };\n }\n\n /**\n * Rank candidates for a goal with one `choice` question.\n *\n * The criteria are the candidate names carrying their descriptions and the\n * incumbent mark, and the answer's distribution is the ranking. The rendered\n * context block of {@link buildRouteContext} — the same facts the logits\n * backend scores — rides in the instructions, so cache-affinity facts and the\n * policy reach the model. A failing gateway falls back to a local keyword\n * ranking whose reasons say so, keeping routing alive.\n * @param req - goal, candidates, topK, session facts, policy.\n * @returns the ranked candidates, best first.\n */\n async route(req: RouteRequest): Promise<RouteResponse> {\n const start = performance.now();\n const candidates = Array.isArray(req.candidates) ? req.candidates : [];\n const topK = typeof req.topK === 'number' && req.topK > 0 ? req.topK : 3;\n if (candidates.length === 0) return { rankedCandidates: [], latencyMs: elapsed(start) };\n\n try {\n const keys = uniqueCriteriaKeys(candidates.map((candidate) => candidate.name));\n const criteria: Record<string, string> = {};\n keys.forEach((key, index) => {\n const candidate = candidates[index] as RouteCandidateItem;\n criteria[key] = candidateCriterion(candidate);\n });\n\n const data = await this.postSystemOne(\n {\n [ROUTE_QUESTION_ID]: {\n type: 'choice',\n instructions: buildRouteInstructions(req),\n criteria\n }\n },\n {\n goal: req.goal,\n ...(req.state === undefined ? {} : { session: req.state }),\n topK\n }\n );\n\n const answer = data.answers?.[ROUTE_QUESTION_ID] as SystemOneChoiceAnswer | undefined;\n const distribution = readDistribution(answer?.probabilities, keys);\n if (distribution === undefined) {\n return this.localRoute(candidates, req.goal, 'the gateway returned no usable candidate distribution', topK, start);\n }\n\n const ranked = candidates\n .map((candidate, index) => ({ name: candidate.name, score: round4(distribution.get(keys[index] as string) ?? 0) }))\n .sort((a, b) => b.score - a.score);\n\n const declaredKey =\n typeof answer?.choice === 'string'\n ? keys.find((key) => normalizeKey(key) === normalizeKey(String(answer.choice)))\n : undefined;\n if (declaredKey !== undefined) {\n const declaredName = candidates[keys.indexOf(declaredKey)]?.name ?? '';\n promoteTiedWinner(ranked, ranked.findIndex((entry) => entry.name === declaredName), (entry) => entry.score);\n }\n\n const sliced = ranked.slice(0, topK);\n return { rankedCandidates: sliced, bestCandidate: sliced[0]?.name, latencyMs: elapsed(start) };\n } catch (err) {\n return this.localRoute(candidates, req.goal, errorMessage(err), topK, start);\n }\n }\n\n /** Deterministic keyword ranking used when the gateway cannot rank. */\n private localRoute(\n candidates: readonly RouteCandidateItem[],\n goal: string,\n reason: string,\n topK: number,\n start: number\n ): RouteResponse {\n const goalWords = tokenize(goal ?? '');\n const weighted = candidates.map((candidate) => {\n const text = `${candidate.name} ${candidate.description ?? ''} ${candidate.type ?? ''}`.toLowerCase();\n const matches = goalWords.filter((word) => text.includes(word)).length;\n return { name: candidate.name, weight: 0.1 + matches };\n });\n const total = weighted.reduce((sum, entry) => sum + entry.weight, 0);\n const ranked = weighted\n .map((entry) => ({\n name: entry.name,\n score: Number((entry.weight / total).toFixed(4)),\n reason: `local fallback (${reason})`\n }))\n .sort((a, b) => b.score - a.score);\n const sliced = ranked.slice(0, topK);\n return { rankedCandidates: sliced, bestCandidate: sliced[0]?.name, latencyMs: elapsed(start) };\n }\n}\n"]}
1
+ {"version":3,"file":"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AC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC;QACrC,MAAM,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC;QACrC,OAAO,EAAE,gBAAgB,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;IACjG,CAAC;CACF","sourcesContent":["import {\n ActionStep,\n BackendHealth,\n ChoiceOption,\n ChoiceRequest,\n ChoiceResponse,\n ClaimClassification,\n ClaimClassificationRequest,\n ClaimClassificationResponse,\n DecisionBackend,\n GateAssertion,\n GateRequest,\n GateResponse,\n GateResultItem,\n PruneDiagnostics,\n PruneRequest,\n PruneResponse,\n RouteCandidateItem,\n RouteRequest,\n RouteResponse,\n StagnationCheckRequest,\n StagnationCheckResponse\n} from './types.js';\nimport { CURRENT_MODEL_MARK, buildRouteContext } from './route-prompt.js';\n\nexport interface JevBackendConfig {\n baseUrl?: string;\n apiKey?: string;\n /**\n * The caller has already resolved the credential (g-059).\n *\n * `true` means `apiKey` is used **verbatim**, including \"absent\": an omitted\n * or empty key means requests go out with no `Authorization` header at all,\n * and this class never consults `SYSTEM_ONE_API_KEY` / `JEV_API_KEY` itself.\n * Without this bit a caller that resolved \"no key\" (a naming that locks onto an\n * empty variable) would be silently served by the environment read below — the\n * panel would say the key is empty while requests actually authenticated,\n * which is the divergence `g-058` removed, pointing the other way.\n *\n * Default `false`: the environment chain stays exactly as it was for every\n * bare construction.\n *\n * **Plugin-only extension.** The vendored backends are a manual port verified\n * by behaviour (`vendor-contract.test.ts`), not a generated mirror, so this\n * field lives here first; the root adapter does not have it yet and is not\n * changed by this goal. Consolidating the two copies is g-060.\n */\n apiKeyResolved?: boolean;\n model?: string;\n timeoutMs?: number;\n /**\n * Character count from which `prune()` judges the payload segment by segment\n * through System One. Below it the deterministic local candidates are used and\n * no request is sent. Defaults to 10000 (or\n * `SYSTEM_ONE_PRUNE_JUDGE_MIN_CHARS`); mirrors\n * `interventions.pruneJudgeMinChars` of the plugin config.\n */\n pruneJudgeMinChars?: number;\n}\n\n/* -------------------------------------------------------------------------- */\n/* Wire contract of the single endpoint */\n/* -------------------------------------------------------------------------- */\n\n/**\n * One `choice` question of `POST /v1/systemone`.\n *\n * The gateway decides *between criteria*: the dictionary keys are the answers\n * the model may name, the values the descriptions it reads. There is no\n * free-text answer, which is why a caller's option list becomes this dictionary\n * and comes back as `answers[id].probabilities`, keyed exactly like the\n * criteria.\n */\nexport interface SystemOneChoiceQuestion {\n type: 'choice';\n instructions: string;\n criteria: Record<string, string>;\n}\n\n/** One `score` question: `criteria` is a list, and the answer indexes it. */\nexport interface SystemOneScoreQuestion {\n type: 'score';\n instructions: string;\n criteria: string[];\n}\n\n/** A question of the single-endpoint contract; `type` discriminates the union. */\nexport type SystemOneQuestion = SystemOneChoiceQuestion | SystemOneScoreQuestion;\n\n/** Body of the one and only request this backend sends. */\nexport interface SystemOneRequest {\n model: string;\n state: Record<string, unknown>;\n questions: Record<string, SystemOneQuestion>;\n}\n\n/** Answer of a `choice` question: the named criterion plus its distribution. */\nexport interface SystemOneChoiceAnswer {\n type?: string;\n /** Criterion key the model named; equals the argmax of `probabilities`. */\n choice?: string;\n /** The gateway's own confidence, distinct from the argmax probability. */\n confidence?: number;\n probabilities?: Record<string, number>;\n}\n\n/**\n * Answer of a `score` question.\n *\n * `probabilities` is keyed by the *index* of the criteria list and `score` is\n * the probability-weighted mean index (measured against `jev-1.13.0`), so\n * `Math.round(score)` is the argmax index and `legend` names each index.\n */\nexport interface SystemOneScoreAnswer {\n type?: string;\n score?: number;\n confidence?: number;\n legend?: Record<string, string>;\n probabilities?: Record<string, number>;\n}\n\n/** Response envelope of `POST /v1/systemone`. */\nexport interface SystemOneResponse {\n model?: string;\n answers?: Record<string, SystemOneChoiceAnswer | SystemOneScoreAnswer>;\n usage?: { input_tokens?: number; output_tokens?: number };\n}\n\n/** Path of the one endpoint the current gateway exposes. */\nexport const SYSTEMONE_ENDPOINT_PATH = '/v1/systemone';\n\n/** Endpoint used when neither configuration nor environment supplies a base. */\nexport const DEFAULT_SYSTEMONE_ENDPOINT = `https://api.typesafe.ai${SYSTEMONE_ENDPOINT_PATH}`;\n\n/** Illustration of a choice request, for docs and drift checks. */\nexport const CHOICE_REQUEST_EXAMPLE = {\n model: 'jev-latest',\n state: {},\n questions: {\n q: { type: 'choice', instructions: 'Which option is better?', criteria: { a: 'the first option', b: 'the second option' } }\n }\n} as const satisfies SystemOneRequest;\n\n/** Question id of a plain {@link JevDecisionBackend.choice} call. */\nexport const CHOICE_QUESTION_ID = 'choice';\n/** Question id of a {@link JevDecisionBackend.route} call. */\nexport const ROUTE_QUESTION_ID = 'route';\n/** Question id of a {@link JevDecisionBackend.prune} call. */\nexport const PRUNE_QUESTION_ID = 'prune';\n/** Question id of a {@link JevDecisionBackend.checkStagnation} call. */\nexport const STAGNATION_QUESTION_ID = 'stagnation';\n/** Prefix of the per-assertion question ids of a {@link JevDecisionBackend.gate} call. */\nexport const GATE_QUESTION_PREFIX = 'assertion-';\n/** Prefix of the per-sentence question ids of a {@link JevDecisionBackend.classifyClaims} call. */\nexport const CLAIM_QUESTION_PREFIX = 'closing-claim-';\n/** Criterion pair of one claim question; index 1 (\"claims completion\") is the one read. */\nexport const CLAIM_CRITERIA: readonly string[] = [\n 'not a completion claim: describes work, plans, questions, or an incomplete/unsuccessful state',\n 'completion claim: asserts that the task, work, build, or tests are complete, successful, passing, or finished'\n];\n\n/* -------------------------------------------------------------------------- */\n/* Domain vocabularies expressed as criteria */\n/* -------------------------------------------------------------------------- */\n\n/** Verdicts the model may name for one gate assertion. Escalation is ours, never its. */\nexport type GateVerdict = 'verified' | 'contradicted' | 'not_addressed';\n\n/** Criteria of a gate assertion, in the order ties are broken. */\nexport const GATE_VERDICTS: readonly GateVerdict[] = ['verified', 'contradicted', 'not_addressed'];\n\n/** What each gate verdict means to the model. */\nexport const GATE_VERDICT_CRITERIA: Readonly<Record<GateVerdict, string>> = {\n verified: 'The evidence directly supports the assertion.',\n contradicted: 'The evidence contradicts the assertion.',\n not_addressed: 'The evidence neither supports nor contradicts the assertion.'\n};\n\n/**\n * Minimum probability on `verified` for a strictness level to claim success.\n * Anything below is escalated: a three-way choice at chance is 1/3, so the\n * lenient floor never accepts a distribution the model did not actually prefer.\n */\nexport const GATE_CONFIDENCE_FLOOR: Readonly<Record<'high' | 'normal' | 'lenient', number>> = {\n high: 0.7,\n normal: 0.5,\n lenient: 0.34\n};\n\n/** Patterns a run can be stuck in. */\nexport type StagnationPattern = 'repetition' | 'oscillation' | 'failing_retry' | 'zero_progress' | 'none';\n\n/** Pattern criteria, in the order ties are broken. */\nexport const STAGNATION_PATTERNS: readonly StagnationPattern[] = [\n 'repetition',\n 'oscillation',\n 'failing_retry',\n 'zero_progress',\n 'none'\n];\n\n/** What each stagnation pattern means to the model. */\nexport const STAGNATION_PATTERN_CRITERIA: Readonly<Record<StagnationPattern, string>> = {\n repetition: 'The same action with the same input repeats with no new information.',\n oscillation: 'Execution alternates between the same two actions or edits without progress.',\n failing_retry: 'Actions keep failing with recurring errors and are retried unchanged.',\n zero_progress: 'Actions run but nothing observable advances the goal.',\n none: 'The run is progressing; none of the stagnation patterns apply.'\n};\n\n/** One-line diagnosis of each pattern. */\nexport const STAGNATION_DIAGNOSIS: Readonly<Record<StagnationPattern, string>> = {\n repetition: 'Identical consecutive tool executions with unchanged input.',\n oscillation: 'The run alternates between two identical actions or edits.',\n failing_retry: 'Recent actions keep failing with recurring errors.',\n zero_progress: 'Actions run, but nothing observable advances the goal.',\n none: 'Execution flow appears progressive.'\n};\n\n/** Corrective action recommended for each stuck pattern. */\nexport const STAGNATION_INTERVENTION: Readonly<Record<StagnationPattern, string>> = {\n repetition: 'Interrupt execution. Change the approach or inspect the previous failure output.',\n oscillation: 'Break the loop: stop alternating, restate the requirement, verify independently.',\n failing_retry: 'Step back and diagnose the root cause before retrying the same action.',\n zero_progress: 'Re-read the goal and pick a step that produces observable evidence of progress.',\n none: 'Continue.'\n};\n\n/** Minimum probability for a stuck pattern to be reported as a real alert. */\nexport const STAGNATION_STUCK_FLOOR = 0.4;\n\n/* -------------------------------------------------------------------------- */\n/* Pure helpers (exported for tests) */\n/* -------------------------------------------------------------------------- */\n\n/** Elapsed milliseconds, rounded and never negative. */\nfunction elapsed(start: number): number {\n return Math.max(0, Math.round(performance.now() - start));\n}\n\n/** Message of an unknown thrown value. */\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/** A probability, clamped into `[0, 1]`; anything unusable reads as 0. */\nfunction toProbability(value: unknown): number {\n const numeric = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(numeric) || numeric <= 0) return 0;\n return Math.min(1, numeric);\n}\n\n/** A probability rounded to the four decimals the decision surfaces report. */\nfunction round4(value: number): number {\n return Number(value.toFixed(4));\n}\n\n/** Comparison key for a criterion: the gateway echoes keys, but be forgiving. */\nfunction normalizeKey(key: string): string {\n return key.trim().toLowerCase();\n}\n\n/**\n * Resolve the endpoint the single request goes to.\n *\n * Every accepted spelling of the base — the full `…/v1/systemone` URL the docs\n * and `JEV_API_BASE` use, a `/v1` root, or a bare host — collapses onto exactly\n * one URL, so a retired per-capability sub-path can never be appended.\n * @param baseUrl - configured or environment base; empty selects the default.\n * @returns the absolute URL of `POST /v1/systemone`.\n */\nexport function normalizeSystemOneEndpoint(baseUrl?: string): string {\n const trimmed = (baseUrl ?? '').trim().replace(/\\/+$/, '');\n if (trimmed.length === 0) return DEFAULT_SYSTEMONE_ENDPOINT;\n if (trimmed.endsWith(SYSTEMONE_ENDPOINT_PATH)) return trimmed;\n if (trimmed.endsWith('/systemone')) return `${trimmed.slice(0, -'/systemone'.length)}${SYSTEMONE_ENDPOINT_PATH}`;\n if (trimmed.endsWith('/v1')) return `${trimmed}/systemone`;\n return `${trimmed}${SYSTEMONE_ENDPOINT_PATH}`;\n}\n\n/**\n * Turn a list of labels into the unique criteria keys of a choice question.\n *\n * Criteria keys are the option labels themselves, which is what makes the\n * answer's probability dictionary readable as option probabilities. Duplicates\n * (two pool entries with the same name) get a numeric suffix so no option can be\n * lost in the dictionary.\n * @param labels - the option labels, in caller order.\n * @returns one unique key per label, in the same order.\n */\nexport function uniqueCriteriaKeys(labels: readonly string[]): string[] {\n const used = new Set<string>();\n return labels.map((raw, index) => {\n const label = typeof raw === 'string' ? raw.trim() : '';\n let key = label.length > 0 ? label : `option ${String(index + 1)}`;\n if (used.has(key)) {\n let suffix = 2;\n while (used.has(`${key} (${String(suffix)})`)) suffix++;\n key = `${key} (${String(suffix)})`;\n }\n used.add(key);\n return key;\n });\n}\n\n/**\n * Read one answer's distribution against the criteria keys it was asked about.\n * @param probabilities - `answers[id].probabilities`, when present.\n * @param keys - criteria keys of the question, in declared order.\n * @returns every key mapped to its probability (missing keys read 0), or\n * `undefined` when the answer carries no usable distribution at all.\n */\nexport function readDistribution(\n probabilities: Record<string, number> | undefined,\n keys: readonly string[]\n): Map<string, number> | undefined {\n if (!probabilities || typeof probabilities !== 'object') return undefined;\n const declared = new Map<string, string>();\n for (const key of keys) declared.set(normalizeKey(key), key);\n\n const distribution = new Map<string, number>(keys.map((key) => [key, 0]));\n let matched = false;\n for (const [rawKey, rawValue] of Object.entries(probabilities)) {\n const key = declared.get(normalizeKey(rawKey));\n if (key === undefined) continue;\n distribution.set(key, (distribution.get(key) ?? 0) + toProbability(rawValue));\n matched = true;\n }\n return matched ? distribution : undefined;\n}\n\n/**\n * Highest-probability key of a distribution.\n * @param distribution - probabilities keyed by criteria key.\n * @param order - declared key order, used to break ties deterministically.\n * @returns the winning key, or `undefined` for an empty order.\n */\nexport function argmaxKey(distribution: Map<string, number>, order: readonly string[]): string | undefined {\n let best: string | undefined;\n let bestValue = -Infinity;\n for (const key of order) {\n const value = distribution.get(key) ?? 0;\n if (value > bestValue) {\n best = key;\n bestValue = value;\n }\n }\n return best;\n}\n\n/** Move `index` to the front when it ties the current leader. */\nfunction promoteTiedWinner<T>(entries: T[], index: number, scoreOf: (entry: T) => number): void {\n if (index <= 0 || entries.length <= index) return;\n const winner = entries[index] as T;\n const leader = entries[0] as T;\n if (scoreOf(winner) !== scoreOf(leader)) return;\n entries.splice(index, 1);\n entries.unshift(winner);\n}\n\n/**\n * Build the choice response options from one gateway answer.\n *\n * The distribution is authoritative; the gateway's discrete `choice` only\n * breaks a tie. When the gateway returns no distribution but does name a\n * criterion, the answer is reconstructed around that name and flagged\n * `uncalibrated`, because the probabilities are then ours, not the gateway's.\n * @param labels - option labels in caller order.\n * @param keys - criteria keys, aligned with `labels`.\n * @param distribution - parsed distribution, when the answer had one.\n * @param answer - the raw gateway answer.\n * @returns sorted options plus the uncalibrated flag, or `undefined` when the\n * answer cannot be turned into a distribution at all.\n */\nexport function toChoiceOptions(\n labels: readonly string[],\n keys: readonly string[],\n distribution: Map<string, number> | undefined,\n answer: SystemOneChoiceAnswer | undefined\n): { options: ChoiceOption[]; uncalibrated: boolean } | undefined {\n const declaredKey =\n typeof answer?.choice === 'string'\n ? keys.find((key) => normalizeKey(key) === normalizeKey(String(answer.choice)))\n : undefined;\n\n let resolved = distribution;\n let uncalibrated = false;\n if (resolved === undefined) {\n if (declaredKey === undefined) return undefined;\n resolved = new Map<string, number>(keys.map((key) => [key, 0]));\n const confidence = toProbability(answer?.confidence) || 1;\n resolved.set(declaredKey, confidence);\n const others = keys.filter((key) => key !== declaredKey);\n const share = others.length > 0 ? (1 - confidence) / others.length : 0;\n for (const key of others) resolved.set(key, share);\n uncalibrated = true;\n }\n\n const options: ChoiceOption[] = labels.map((rawLabel, index) => ({\n label: typeof rawLabel === 'string' ? rawLabel : String(rawLabel),\n probability: round4(resolved?.get(keys[index] ?? '') ?? 0)\n }));\n options.sort((a, b) => b.probability - a.probability);\n if (declaredKey !== undefined) {\n const declaredLabel = labels[keys.indexOf(declaredKey)] ?? '';\n promoteTiedWinner(options, options.findIndex((option) => option.label === declaredLabel), (option) => option.probability);\n }\n return { options, uncalibrated };\n}\n\n/**\n * Read the winning criteria index out of a `score` answer.\n * @param answer - the gateway's score answer.\n * @param count - number of criteria the question offered.\n * @returns the argmax index, or `undefined` when the answer is unusable.\n */\nexport function readScoreIndex(answer: SystemOneScoreAnswer | undefined, count: number): number | undefined {\n if (count <= 0) return undefined;\n const keys = Array.from({ length: count }, (_, index) => String(index));\n const distribution = readDistribution(answer?.probabilities, keys);\n if (distribution !== undefined) {\n const key = argmaxKey(distribution, keys);\n if (key === undefined || (distribution.get(key) ?? 0) <= 0) return undefined;\n return Number(key);\n }\n const raw = typeof answer?.score === 'number' ? answer.score : Number(answer?.score);\n if (!Number.isFinite(raw)) return undefined;\n return Math.min(count - 1, Math.max(0, Math.round(raw)));\n}\n\n/** Instruction block of one choice question. */\nfunction buildChoiceInstructions(question: string | undefined): string {\n const trimmed = (question ?? '').trim();\n return trimmed.length > 0 ? trimmed : 'Choose the criterion that best answers the task.';\n}\n\n/** Instruction block of one gate assertion. */\nfunction buildGateInstructions(assertion: GateAssertion, strictness: string): string {\n const rubric = (assertion.criteria ?? '').trim();\n return [\n 'Decide which criterion describes how the STATE evidence relates to the ASSERTION.',\n `ASSERTION: ${assertion.statement}`,\n ...(rubric.length > 0 ? [`ASSERTION RUBRIC: ${rubric}`] : []),\n `STRICTNESS: ${strictness}`\n ].join('\\n');\n}\n\n/** Instruction block of a stagnation classification. */\nfunction buildStagnationInstructions(): string {\n return [\n 'Classify the recent agent run in the STATE: choose the criterion that best describes the execution pattern.',\n 'Judge the action history itself, not the quality of the tool output.'\n ].join('\\n');\n}\n\n/** Sentences one closing classification may submit; the turn's tail, never its whole text. */\nexport const MAX_CLAIM_SENTENCES = 3;\n\n/**\n * Instruction block of one completion-claim question.\n *\n * The negation cases are spelled out because that is exactly where a word list\n * fails: \"not complete\" contains \"complete\", and \"没有通过\" contains \"通过\".\n */\nfunction buildClaimInstructions(statement: string, intent: string): string {\n return [\n 'Decide whether the SENTENCE claims that the task or its work is complete, successful, passing, or finished.',\n 'A negated or qualified outcome is NOT a completion claim: \"not complete\", \"not yet done\", \"failed\", \"没有通过\", \"尚未完成\", \"仍有失败\".',\n 'A sentence that only describes plans, asks a question, or reports an error is not a completion claim either.',\n ...(intent.trim().length > 0 ? [`TURN INTENT: ${intent}`] : []),\n `SENTENCE: ${statement}`\n ].join('\\n');\n}\n\n/**\n * Read one claim answer.\n * @param statement - the sentence the question was asked about.\n * @param answer - the gateway's score answer.\n * @returns the classification, or `undefined` when the answer is unusable.\n */\nfunction readClaimAnswer(\n statement: string,\n answer: SystemOneScoreAnswer | undefined\n): ClaimClassification | undefined {\n const index = readScoreIndex(answer, CLAIM_CRITERIA.length);\n if (index === undefined) return undefined;\n const distribution = readDistribution(answer?.probabilities, ['0', '1']);\n const confidence = distribution !== undefined ? round4(distribution.get('1') ?? 0) : index === 1 ? 1 : 0;\n return { statement, isClaim: index === 1, confidence };\n}\n\n/** Instruction block of a route decision; renders the same facts the logits backend scores. */\nexport function buildRouteInstructions(req: RouteRequest): string {\n return [\n buildRouteContext(req),\n 'Select the single criterion whose candidate best serves the goal.'\n ]\n .filter((line) => line.trim().length > 0)\n .join('\\n\\n');\n}\n\n/** Criterion description of one route candidate. */\nfunction candidateCriterion(candidate: RouteCandidateItem): string {\n const description = (candidate.description ?? '').trim() || candidate.name;\n const type = candidate.type ? `[${candidate.type}] ` : '';\n const mark = candidate.current ? ` ${CURRENT_MODEL_MARK}` : '';\n return `${type}${description}${mark}`;\n}\n\n/** Clamp a fragment carried into a decision prompt. */\nfunction clip(text: string | undefined, limit: number): string {\n const value = typeof text === 'string' ? text : '';\n return value.length <= limit ? value : `${value.slice(0, limit)}…`;\n}\n\n/** Words a line must share with the intent to count as relevant. */\nfunction tokenize(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9_\\u4e00-\\u9fff]+/)\n .filter((word) => word.length > 2);\n}\n\n/* -------------------------------------------------------------------------- */\n/* Deterministic prune candidates */\n/* -------------------------------------------------------------------------- */\n\n/** One deterministic pruning of a raw output. */\nexport interface PruneCandidate {\n id: 'aggressive' | 'balanced' | 'conservative';\n /** Human-readable label including the reduction it achieved. */\n label: string;\n text: string;\n /** Segments this candidate kept whole; observability of the selection. */\n keptSegments?: number;\n}\n\nconst PROGRESS_ART = /\\[=+[>\\s]|█|^\\s*\\d+%\\s|\\[K/;\nconst NOISE_LINE = /^\\s*(?:npm (?:warn|notice)|Downloading|Fetching|Progress:|added \\d+ packages|audited \\d+ packages)\\b/i;\nconst DIAGNOSTIC_MARK =\n /(?:error|fail|exception|panic|traceback|assert|expected|actual|✗|✘|warn|not ok|denied|refused|cannot|undefined is not|stack)/i;\n\n/** Drop progress art, then collapse repeated lines and blank runs. */\nfunction condenseLines(lines: readonly string[]): string[] {\n const out: string[] = [];\n let blanks = 0;\n let previous: string | undefined;\n for (const line of lines) {\n if (PROGRESS_ART.test(line)) continue;\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n blanks++;\n if (blanks <= 1) out.push('');\n continue;\n }\n blanks = 0;\n if (trimmed === previous) continue;\n previous = trimmed;\n out.push(line.replace(/\\s+$/, ''));\n }\n return out;\n}\n\n/** Cap a candidate to a token budget, keeping its head and its tail. */\nfunction capToBudget(text: string, maxTokens?: number): string {\n if (typeof maxTokens !== 'number' || !Number.isFinite(maxTokens) || maxTokens <= 0) return text;\n const budget = Math.floor(maxTokens) * 4;\n if (text.length <= budget) return text;\n const head = Math.floor(budget * 0.7);\n const tail = Math.max(0, budget - head - 64);\n const dropped = text.length - head - tail;\n const marker = `\\n… [${String(dropped)} characters elided by the prune budget] …\\n`;\n return `${text.slice(0, head)}${marker}${tail > 0 ? text.slice(text.length - tail) : ''}`;\n}\n\n/** Label of one pruning, including its reduction. */\nfunction pruneLabel(id: PruneCandidate['id'], originalChars: number, prunedChars: number): string {\n const strategy: Record<PruneCandidate['id'], string> = {\n aggressive: 'keeps only diagnostic and intent-matching lines',\n balanced: 'drops progress noise and irrelevant dependency traces',\n conservative: 'collapses blank runs and repeated lines'\n };\n const reduction = originalChars > 0 ? Math.round(((originalChars - prunedChars) / originalChars) * 100) : 0;\n return `candidate \"${id}\" (${strategy[id]}, ${String(reduction)}% smaller)`;\n}\n\n/**\n * Build the deterministic prunings used below the judging threshold and as the\n * fallback when System One cannot judge the segments.\n *\n * These are the legacy line filters: {@link JevDecisionBackend.prune} no longer\n * uses them as its primary decision for large payloads — the per-segment scores\n * are — so `PROGRESS_ART`/`NOISE_LINE` are one input among two, never the sole\n * basis of a reduction.\n * @param rawOutput - the bulk output to reduce.\n * @param intent - what the caller is looking for.\n * @param maxTokens - optional token budget applied to every candidate.\n * @returns distinct candidates, most aggressive first; empty for empty input.\n */\nexport function buildPruneCandidates(rawOutput: string, intent: string, maxTokens?: number): PruneCandidate[] {\n if (rawOutput.length === 0) return [];\n const intentWords = tokenize(intent);\n const matchesIntent = (line: string): boolean => {\n const lower = line.toLowerCase();\n return intentWords.some((word) => lower.includes(word));\n };\n\n const condensed = condenseLines(rawOutput.split('\\n'));\n const balanced = condensed.filter((line) => {\n const trimmed = line.trim();\n if (trimmed.length === 0) return true;\n if (NOISE_LINE.test(trimmed) && !matchesIntent(trimmed)) return false;\n if (trimmed.includes('node_modules/') && !matchesIntent(trimmed)) return false;\n return true;\n });\n const aggressive = balanced.filter((line) => {\n const trimmed = line.trim();\n if (trimmed.length === 0) return true;\n return DIAGNOSTIC_MARK.test(trimmed) || matchesIntent(trimmed);\n });\n\n const drafts: Array<{ id: PruneCandidate['id']; text: string }> = [\n { id: 'aggressive', text: capToBudget(aggressive.join('\\n').trim(), maxTokens) },\n { id: 'balanced', text: capToBudget(balanced.join('\\n').trim(), maxTokens) },\n { id: 'conservative', text: capToBudget(condensed.join('\\n').trim(), maxTokens) }\n ];\n\n const seen = new Set<string>();\n return drafts\n .filter((draft) => {\n if (draft.text.length === 0 || seen.has(draft.text)) return false;\n seen.add(draft.text);\n return true;\n })\n .map((draft) => ({\n id: draft.id,\n label: pruneLabel(draft.id, rawOutput.length, draft.text.length),\n text: draft.text\n }));\n}\n\n/**\n * Candidate used when the ranking is unavailable: the balanced filter, which is\n * the safest reduction that still removes noise.\n * @param candidates - candidates of {@link buildPruneCandidates}.\n * @returns the local default, or `undefined` for an empty list.\n */\nexport function pickLocalPruneCandidate(candidates: readonly PruneCandidate[]): PruneCandidate | undefined {\n const balanced = candidates.find((candidate) => candidate.id === 'balanced');\n if (balanced !== undefined) return balanced;\n return candidates[Math.floor(candidates.length / 2)] ?? candidates[0];\n}\n\n/* -------------------------------------------------------------------------- */\n/* Format-independent template compression (fallback path only) */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Lines that always survive a template compression verbatim.\n *\n * A degraded run must not lose the line that explains why the run failed, so\n * these are forced anchors next to the first and last line of the output.\n */\nconst TEMPLATE_DIAGNOSTIC_LINE = /error|failed|FAIL|warn|exception|traceback|assert|exit code [1-9]|non-zero/i;\n\n/** One line standing in for a run of near-identical lines. */\nfunction templateOmittedMarker(omitted: number): string {\n return `… [${String(omitted)} similar lines omitted] …`;\n}\n\n/**\n * Reduce one line to the template later lines are compared against.\n *\n * Variable tokens (UUIDs, timestamps, IPs, hex ids, durations, percentages,\n * floats, plain numbers) become placeholders and runs of whitespace collapse,\n * so \"progress 001\" and \"progress 002\" share a template while two genuinely\n * different lines do not. The original line is what is printed, never this\n * string.\n * @param line - one line of the output.\n * @returns its shape, whitespace-normalized.\n */\nexport function templateOfLine(line: string): string {\n let template = line.trim();\n template = template.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '<uuid>');\n template = template.replace(/\\d{4}-\\d{2}-\\d{2}[T ]\\d{2}:\\d{2}:\\d{2}(?:[.,]\\d+)?(?:Z|[+-]\\d{2}:?\\d{2})?/g, '<time>');\n template = template.replace(/\\b\\d{1,3}(?:\\.\\d{1,3}){3}\\b/g, '<ip>');\n template = template.replace(/\\b0x[0-9a-f]+\\b/gi, '<hex>');\n template = template.replace(/\\b[0-9a-f]{8,}\\b/gi, '<hex>');\n template = template.replace(/\\b\\d{1,2}(?::\\d{2}){1,2}(?:[.,]\\d+)?\\b/g, '<time>');\n template = template.replace(/\\d+(?:\\.\\d+)?\\s?%/g, '<pct>');\n template = template.replace(/\\b\\d+(?:\\.\\d+)?\\s?(?:ms|secs?|seconds?|mins?|minutes?|hours?|h)\\b/gi, '<duration>');\n template = template.replace(/\\d+\\.\\d+/g, '<float>');\n template = template.replace(/\\d+/g, '<num>');\n return template.replace(/\\s+/g, ' ').trim();\n}\n\n/**\n * Compress a bulk output by its line templates, independent of any format.\n *\n * Consecutive lines whose templates match form a run: a run of four or more\n * keeps its first two and its last line and replaces the rest with one marker.\n * Consecutive blank lines collapse to one. The first line, the last line and\n * every diagnostic line survive verbatim. This is the fallback used when System\n * One cannot judge — it never replaces a real decision.\n * @param rawOutput - the bulk output to reduce.\n * @returns the reduced text; never longer than the input.\n */\nexport function compressByTemplate(rawOutput: string): string {\n if (rawOutput.length === 0) return rawOutput;\n const lines = rawOutput.split('\\n');\n if (lines.length <= 2) return rawOutput;\n\n const lastIndex = lines.length - 1;\n const out: string[] = [];\n let index = 0;\n\n while (index <= lastIndex) {\n const line = lines[index] as string;\n const blank = line.trim().length === 0;\n if (blank) {\n let end = index;\n while (end + 1 <= lastIndex && (lines[end + 1] as string).trim().length === 0) end++;\n out.push(index === 0 || end === lastIndex ? line : '');\n index = end + 1;\n continue;\n }\n\n if (index === 0 || index === lastIndex || TEMPLATE_DIAGNOSTIC_LINE.test(line)) {\n out.push(line);\n index += 1;\n continue;\n }\n\n const template = templateOfLine(line);\n let end = index;\n while (\n end + 1 < lastIndex &&\n (lines[end + 1] as string).trim().length > 0 &&\n !TEMPLATE_DIAGNOSTIC_LINE.test(lines[end + 1] as string) &&\n templateOfLine(lines[end + 1] as string) === template\n ) {\n end += 1;\n }\n\n const run = end - index + 1;\n if (run >= 4) {\n out.push(lines[index] as string, lines[index + 1] as string, templateOmittedMarker(run - 3), lines[end] as string);\n } else {\n for (let cursor = index; cursor <= end; cursor++) out.push(lines[cursor] as string);\n }\n index = end + 1;\n }\n\n const compressed = out.join('\\n');\n return compressed.length < rawOutput.length ? compressed : rawOutput;\n}\n\n/* -------------------------------------------------------------------------- */\n/* System One segment judging */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Character count from which {@link JevDecisionBackend.prune} judges segments\n * with System One. Kept in sync with `interventions.pruneJudgeMinChars`.\n */\nexport const PRUNE_JUDGE_MIN_CHARS_DEFAULT = 10000;\n\n/** A scored segment never exceeds this many characters (a single long line stays whole). */\nconst PRUNE_SEGMENT_MAX_CHARS = 1600;\n\n/** Upper bound on segments judged by one request; the rest are kept deterministically. */\nexport const PRUNE_MAX_JUDGED_SEGMENTS = 40;\n\n/** Prefix of the per-segment question ids of a pruning judgment. */\nexport const PRUNE_SEGMENT_QUESTION_PREFIX = 'prune-seg-';\n\n/** Criterion pair of one segment question; index 1 (keep) is the score we read. */\nconst PRUNE_KEEP_CRITERIA: readonly string[] = [\n 'omit: repetitive, irrelevant, or safe to drop',\n 'keep: unique, relevant, or diagnostic content'\n];\n\n/**\n * Share of the original characters each candidate may spend on scored\n * segments. Forced lines (anchors, diagnostics, intent matches) never compete\n * with this budget.\n */\nconst PRUNE_SCORED_BUDGET_RATIO: Readonly<Record<PruneCandidate['id'], number>> = {\n aggressive: 0.25,\n balanced: 0.5,\n conservative: 0.7\n};\n\n/**\n * Lines that must survive verbatim whatever the segment score says: diagnostic\n * evidence, plus the first and last content lines of the payload. Matched\n * case-insensitively.\n */\nconst PRUNE_FORCED_LINE =\n /error|failed|FAIL|warn|exception|traceback|assert|exit code [1-9]|non-zero/i;\n\n/**\n * Resolve the segment-judging character threshold from an explicit value, then\n * the environment, then the documented default.\n * @param value - explicit backend configuration, when supplied.\n * @returns a non-negative finite character count.\n */\nexport function resolvePruneJudgeMinChars(value?: number): number {\n const raw = value ?? process.env.SYSTEM_ONE_PRUNE_JUDGE_MIN_CHARS;\n const numeric = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim().length > 0 ? Number(raw) : NaN;\n if (Number.isFinite(numeric) && numeric >= 0) return Math.floor(numeric);\n return PRUNE_JUDGE_MIN_CHARS_DEFAULT;\n}\n\n/** One contiguous run of non-blank lines, the unit System One judges. */\ninterface PruneSegment {\n /** Position in the original output, oldest first. */\n index: number;\n /** 0-based inclusive line range in the original output. */\n startLine: number;\n endLine: number;\n /** The segment text exactly as it appears in the output. */\n text: string;\n chars: number;\n /** Absolute line indexes always kept, regardless of the score. */\n forcedLines: number[];\n}\n\n/** Whether one line carries diagnostic evidence or matches the intent. */\nfunction isForcedPruneLine(line: string, intentWords: readonly string[]): boolean {\n if (PRUNE_FORCED_LINE.test(line)) return true;\n const lower = line.toLowerCase();\n return intentWords.some((word) => lower.includes(word));\n}\n\n/**\n * Cut an output into the segments System One judges.\n *\n * Paragraphs are separated by blank lines; a paragraph longer than\n * {@link PRUNE_SEGMENT_MAX_CHARS} is split on line windows, so the model never\n * sees one oversized block and the local replay can reassemble the exact lines.\n * Line order and line numbers are preserved: every segment is a half-open view\n * of the original line array.\n * @param rawOutput - the bulk output.\n * @param intent - what the caller is looking for.\n * @returns segments in original order, with their forced line indexes.\n */\nexport function segmentPruneOutput(rawOutput: string, intent: string): PruneSegment[] {\n const lines = rawOutput.split('\\n');\n const intentWords = tokenize(intent);\n const segments: PruneSegment[] = [];\n\n let firstContent = -1;\n let lastContent = -1;\n for (let index = 0; index < lines.length; index++) {\n if ((lines[index] as string).trim().length === 0) continue;\n if (firstContent < 0) firstContent = index;\n lastContent = index;\n }\n\n const push = (startLine: number, endLine: number): void => {\n const forced: number[] = [];\n for (let line = startLine; line <= endLine; line++) {\n const text = lines[line] as string;\n if (line === firstContent || line === lastContent || isForcedPruneLine(text, intentWords)) {\n forced.push(line);\n }\n }\n const text = lines.slice(startLine, endLine + 1).join('\\n');\n segments.push({ index: segments.length, startLine, endLine, text, chars: text.length, forcedLines: forced });\n };\n\n let cursor = 0;\n while (cursor < lines.length) {\n while (cursor < lines.length && (lines[cursor] as string).trim().length === 0) cursor++;\n if (cursor >= lines.length) break;\n const blockStart = cursor;\n while (cursor < lines.length && (lines[cursor] as string).trim().length > 0) cursor++;\n const blockEnd = cursor - 1;\n\n let windowStart = blockStart;\n let windowChars = (lines[blockStart] as string).length;\n for (let line = blockStart + 1; line <= blockEnd; line++) {\n const length = (lines[line] as string).length + 1;\n if (windowChars + length > PRUNE_SEGMENT_MAX_CHARS) {\n push(windowStart, line - 1);\n windowStart = line;\n windowChars = (lines[line] as string).length;\n } else {\n windowChars += length;\n }\n }\n push(windowStart, blockEnd);\n }\n return segments;\n}\n\n/** Instruction block of one segment question. */\nfunction buildSegmentInstructions(intent: string, segment: PruneSegment, total: number): string {\n const trimmed = intent.trim() || 'extract diagnostics, relevant results and errors';\n return [\n 'Decide whether one segment of a tool output must be kept to serve the INTENT, or may be omitted as noise.',\n `INTENT: ${trimmed}`,\n `SEGMENT: ${String(segment.index + 1)} of ${String(total)} (lines ${String(segment.startLine + 1)}-${String(segment.endLine + 1)}).`,\n 'Score 0 when the segment is repetitive or irrelevant; score 1 when it carries information the INTENT needs.'\n ].join('\\n');\n}\n\n/**\n * Read one segment's keep score (0 = omit, 1 = keep) out of its `score` answer.\n * The distribution over the two criteria is authoritative; the weighted `score`\n * is the fallback, and nothing usable reads as `undefined`.\n * @param answer - the gateway's answer for this segment question.\n * @returns the keep score in `[0, 1]`, or `undefined` when unusable.\n */\nexport function readSegmentKeepScore(answer: SystemOneScoreAnswer | undefined): number | undefined {\n if (answer === undefined || answer === null) return undefined;\n const distribution = readDistribution(answer.probabilities, ['0', '1']);\n if (distribution !== undefined) return round4(toProbability(distribution.get('1')));\n const raw = typeof answer.score === 'number' ? answer.score : Number(answer.score);\n if (!Number.isFinite(raw)) return undefined;\n return round4(Math.min(1, Math.max(0, raw)));\n}\n\n/**\n * Pick the segments a budget keeps from their scores.\n *\n * Segments without a usable score are an unjudged safety margin and are always\n * kept; scored segments are taken from the highest score down until the\n * character budget is spent. Ties follow the original order.\n * @param segments - all segments of the output.\n * @param scores - keep score per segment index, absent for unjudged segments.\n * @param originalChars - character count of the unpruned output.\n * @param ratio - share of the original characters scored segments may use.\n * @returns indexes of the segments this candidate keeps in full.\n */\nexport function selectPruneSegments(\n segments: readonly PruneSegment[],\n scores: ReadonlyMap<number, number>,\n originalChars: number,\n ratio: number\n): Set<number> {\n const selected = new Set<number>();\n let used = 0;\n for (const segment of segments) {\n if (scores.has(segment.index)) continue;\n selected.add(segment.index);\n used += segment.chars;\n }\n const budget = Math.floor(originalChars * ratio);\n const ranked = segments\n .filter((segment) => scores.has(segment.index))\n .sort((left, right) => {\n const difference = (scores.get(right.index) ?? 0) - (scores.get(left.index) ?? 0);\n return difference !== 0 ? difference : left.index - right.index;\n });\n for (const segment of ranked) {\n // Stop at the budget instead of skipping ahead: a smaller low-score segment\n // must never slip into the space a higher-score one did not fit.\n if (used + segment.chars > budget) break;\n selected.add(segment.index);\n used += segment.chars;\n }\n return selected;\n}\n\n/** Build the marker of one run of omitted segments. */\nfunction omittedSegmentsMarker(count: number): string {\n return `… [${String(count)} segments omitted] …`;\n}\n\n/**\n * Reassemble one candidate in the original line order.\n *\n * A selected segment is kept whole; an unselected one keeps only its forced\n * lines (first/last anchors, diagnostics, intent matches). Consecutive fully\n * omitted segments collapse into one marker that names how many were dropped.\n * Blank runs between kept lines collapse to a single blank line.\n * @param rawOutput - the original output, for its lines.\n * @param segments - segments in original order.\n * @param selected - segment indexes kept whole.\n * @returns the reduced text.\n */\nexport function assemblePruneCandidate(\n rawOutput: string,\n segments: readonly PruneSegment[],\n selected: ReadonlySet<number>\n): string {\n const lines = rawOutput.split('\\n');\n const out: string[] = [];\n let omitted = 0;\n let lastEmitted = -1;\n\n const emitLine = (lineIndex: number): void => {\n if (lastEmitted >= 0 && lineIndex > lastEmitted + 1) out.push('');\n out.push(lines[lineIndex] as string);\n lastEmitted = lineIndex;\n };\n const flushOmitted = (): void => {\n if (omitted === 0) return;\n out.push(omittedSegmentsMarker(omitted));\n omitted = 0;\n };\n\n for (const segment of segments) {\n // A selected segment is kept whole; an unselected one keeps forced lines only.\n const keepWhole = selected.has(segment.index);\n const lineIndexes: number[] = [];\n if (keepWhole) {\n for (let line = segment.startLine; line <= segment.endLine; line++) lineIndexes.push(line);\n } else {\n lineIndexes.push(...segment.forcedLines);\n }\n if (lineIndexes.length === 0) {\n omitted++;\n continue;\n }\n flushOmitted();\n for (const lineIndex of lineIndexes) emitLine(lineIndex);\n }\n flushOmitted();\n return out.join('\\n').trim();\n}\n\n/** Label of one score-driven candidate, including its reduction. */\nfunction scoredPruneLabel(id: PruneCandidate['id'], originalChars: number, prunedChars: number): string {\n const strategy: Record<PruneCandidate['id'], string> = {\n aggressive: 'keeps the segments System One judged essential within a quarter of the original',\n balanced: 'keeps the segments System One judged essential within half of the original',\n conservative: 'keeps the segments System One judged essential within most of the original'\n };\n const reduction = originalChars > 0 ? Math.round(((originalChars - prunedChars) / originalChars) * 100) : 0;\n return `candidate \"${id}\" (${strategy[id]}, ${String(reduction)}% smaller)`;\n}\n\n/**\n * Build the three System One–scored prunings from one segment judgment.\n *\n * The segment keep/drop decision is the model's score; the three ids only\n * differ in their character budget, so the ranking the engine used to make is\n * now made per segment.\n * @param rawOutput - the original output.\n * @param segments - segments of that output in original order.\n * @param scores - keep score per segment index.\n * @param maxTokens - optional hard token ceiling applied to every candidate.\n * @returns candidates ordered from aggressive to conservative.\n */\nexport function buildScoredPruneCandidates(\n rawOutput: string,\n segments: readonly PruneSegment[],\n scores: ReadonlyMap<number, number>,\n maxTokens?: number\n): PruneCandidate[] {\n const ids: PruneCandidate['id'][] = ['aggressive', 'balanced', 'conservative'];\n return ids.map((id) => {\n const selected = selectPruneSegments(segments, scores, rawOutput.length, PRUNE_SCORED_BUDGET_RATIO[id]);\n const text = capToBudget(assemblePruneCandidate(rawOutput, segments, selected), maxTokens);\n return { id, label: scoredPruneLabel(id, rawOutput.length, text.length), text, keptSegments: selected.size };\n });\n}\n\n/** The scored candidate one segment judgment installs, and why it did. */\nexport interface ScoredPrunePick {\n /** The text the segmented path returns: a reducing candidate, or the raw output. */\n text: string;\n /** The candidate that reduced the payload; absent when none did. */\n candidate?: PruneCandidate;\n /** Why no scored candidate was used, when none was. */\n reason?: string;\n}\n\n/**\n * Pick the first scored candidate strictly smaller than the payload.\n *\n * The balanced budget is tried first because it is the documented default. A\n * payload whose forced lines (anchors, diagnostics, intent matches) already\n * reproduce it verbatim makes even the balanced candidate as large as the\n * original; the tighter and then the wider budget are tried before giving up,\n * so a smaller aggressive candidate is never thrown away by the balanced one.\n * A candidate that does not reduce the payload is never returned as the text:\n * the caller treats that outcome as a judgment that kept everything, unless the\n * judgment produced no usable score at all.\n * @param rawOutput - the original output the candidates were built from.\n * @param candidates - the scored candidates, in any order.\n * @returns the reducing text plus the candidate that produced it, or the raw\n * output plus the reason no candidate was usable.\n */\nexport function pickScoredPruneCandidate(\n rawOutput: string,\n candidates: readonly PruneCandidate[]\n): ScoredPrunePick {\n const order: PruneCandidate['id'][] = ['balanced', 'aggressive', 'conservative'];\n for (const id of order) {\n const candidate = candidates.find((entry) => entry.id === id);\n if (candidate !== undefined && candidate.text.length < rawOutput.length) return { text: candidate.text, candidate };\n }\n return { text: rawOutput, reason: 'no scored candidate is smaller than the payload' };\n}\n\n\n/* -------------------------------------------------------------------------- */\n/* Local fallbacks */\n/* -------------------------------------------------------------------------- */\n\n/** A local stagnation verdict, used when the gateway cannot supply one. */\nexport interface LocalStagnationVerdict {\n isStuck: boolean;\n patternType: StagnationPattern;\n confidence: number;\n diagnosis: string;\n recommendedIntervention?: string;\n}\n\n/**\n * Deterministic stagnation detector over a recent action window.\n *\n * It is the offline half of {@link JevDecisionBackend.checkStagnation}: the\n * gateway classifies the pattern, and this reads the same history with explicit\n * rules, so a dead gateway degrades the verdict instead of losing it.\n * @param recent - the recent action window, oldest first.\n * @returns the locally detected pattern.\n */\nexport function detectStagnationLocally(recent: readonly ActionStep[]): LocalStagnationVerdict {\n const stuck = (patternType: Exclude<StagnationPattern, 'none'>, confidence: number): LocalStagnationVerdict => ({\n isStuck: true,\n patternType,\n confidence,\n diagnosis: `${STAGNATION_DIAGNOSIS[patternType]} [local heuristic]`,\n recommendedIntervention: STAGNATION_INTERVENTION[patternType]\n });\n\n const signatures = recent.map((step) => `${step.tool}:${(step.input ?? '').trim()}`);\n let identical = 1;\n for (let index = signatures.length - 1; index > 0; index--) {\n if (signatures[index] === signatures[index - 1]) identical++;\n else break;\n }\n if (identical >= 3) return stuck('repetition', 0.95);\n\n const failing = recent.filter(\n (step) => Boolean(step.error) || /(?:error|fail|panic|not ok)/i.test(step.output ?? '')\n );\n if (failing.length >= 3 && recent.length >= 4) return stuck('failing_retry', 0.85);\n\n if (recent.length >= 4) {\n const last = recent.slice(-4);\n const alternates =\n last[0]?.tool === last[2]?.tool &&\n last[1]?.tool === last[3]?.tool &&\n last[0]?.input === last[2]?.input &&\n last[1]?.input === last[3]?.input;\n if (alternates) return stuck('oscillation', 0.9);\n }\n\n return {\n isStuck: false,\n patternType: 'none',\n confidence: 0.6,\n diagnosis: `${STAGNATION_DIAGNOSIS.none} [local heuristic]`\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* The adapter */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Jev System One Provider Adapter\n *\n * Speaks only the current gateway contract: one `POST /v1/systemone` carrying\n * `{ model, state, questions }`, where every question is a `choice` between\n * criteria or a `score` over a criteria list. The gateway returns discrete\n * distributions, never free text, so the four composite capabilities\n * (`gate`, `prune`, `checkStagnation`, `route`) are expressed as criteria\n * questions and backed by deterministic local fallbacks.\n */\nexport class JevDecisionBackend implements DecisionBackend {\n readonly name = 'system-one-jev';\n readonly model: string;\n /** Absolute URL of the single endpoint; no call appends a sub-path to it. */\n readonly endpoint: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n /** Character count from which pruning judges segments through System One. */\n private readonly pruneJudgeMinChars: number;\n /**\n * Health of the gateway conversation of this backend.\n *\n * Every request updates it; a success clears the failure fields and resets the\n * run. It lives in memory only, so a restarted Host starts healthy.\n */\n private healthState: BackendHealth = { available: true, consecutiveFailures: 0 };\n\n constructor(config?: JevBackendConfig) {\n this.endpoint = normalizeSystemOneEndpoint(\n config?.baseUrl ||\n process.env.SYSTEM_ONE_BASE_URL ||\n process.env.JEV_BASE_URL ||\n process.env.JEV_API_BASE ||\n DEFAULT_SYSTEMONE_ENDPOINT\n );\n // A caller that resolved the credential owns the answer, empty included\n // (g-059): reading the environment here would resurrect a key that caller\n // deliberately decided not to send. See `JevBackendConfig.apiKeyResolved`.\n // `=== true` rather than truthiness: only an explicit opt-in may change the\n // historical chain, so any other value (including a stray `'false'`) keeps it.\n this.apiKey =\n config?.apiKeyResolved === true\n ? config.apiKey ?? ''\n : config?.apiKey ||\n process.env.SYSTEM_ONE_API_KEY ||\n process.env.JEV_API_KEY ||\n '';\n this.model =\n config?.model ||\n process.env.SYSTEM_ONE_MODEL ||\n process.env.JEV_MODEL ||\n 'jev-latest';\n this.timeoutMs = config?.timeoutMs || 10000;\n this.pruneJudgeMinChars = resolvePruneJudgeMinChars(config?.pruneJudgeMinChars);\n }\n\n /**\n * Health of the outbound gateway conversation.\n * @returns a copy of the counters, safe to hand to a panel snapshot.\n */\n health(): BackendHealth {\n return { ...this.healthState };\n }\n\n /** Record one successful request: the backend is available again. */\n private noteSuccess(): void {\n this.healthState = { available: true, consecutiveFailures: 0 };\n }\n\n /** Record one failed request and its reason. */\n private noteFailure(reason: string): void {\n this.healthState = {\n available: false,\n lastFailureReason: reason,\n lastFailureAt: new Date().toISOString(),\n consecutiveFailures: this.healthState.consecutiveFailures + 1\n };\n }\n\n /**\n * Send one request to the single endpoint.\n * @param questions - questions keyed by id; answers come back under the same ids.\n * @param state - machine-readable situation the questions reason about.\n * @returns the gateway's answer envelope.\n */\n private async postSystemOne(\n questions: Record<string, SystemOneQuestion>,\n state: Record<string, unknown>\n ): Promise<SystemOneResponse> {\n const body: SystemOneRequest = { model: this.model, state, questions };\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n try {\n const resp = await fetch(this.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n ...(this.apiKey.length > 0 ? { Authorization: `Bearer ${this.apiKey}` } : {})\n },\n body: JSON.stringify(body),\n signal: controller.signal\n });\n\n if (!resp.ok) {\n const text = await resp.text();\n throw new Error(`Jev API error (${resp.status} ${resp.statusText}): ${text.slice(0, 500)}`);\n }\n\n const data = (await resp.json()) as SystemOneResponse;\n if (!data || typeof data !== 'object' || typeof data.answers !== 'object' || data.answers === null) {\n throw new Error('Jev API response carries no answers object');\n }\n this.noteSuccess();\n return data;\n } catch (err) {\n this.noteFailure(errorMessage(err));\n throw err;\n } finally {\n clearTimeout(timer);\n }\n }\n\n /**\n * Classify one question into a probability distribution over the options.\n *\n * The options become the `criteria` dictionary (key = option label, value =\n * the description the model reads) and `answers[id].probabilities` — keyed by\n * criterion — becomes the returned option distribution. An answer without a\n * usable distribution fails loudly: the caller asked for a decision, and a\n * fabricated one would be worse than an error.\n * @param req - question, options, optional context.\n * @returns options sorted by probability, plus the winning option.\n */\n async choice(req: ChoiceRequest): Promise<ChoiceResponse> {\n const start = performance.now();\n try {\n const labels = Array.isArray(req.options) ? req.options : [];\n if (labels.length === 0) throw new Error('at least one option is required');\n\n const keys = uniqueCriteriaKeys(labels);\n const criteria: Record<string, string> = {};\n keys.forEach((key, index) => {\n criteria[key] = typeof labels[index] === 'string' ? (labels[index] as string) : key;\n });\n\n const context = (req.context ?? '').trim();\n const data = await this.postSystemOne(\n {\n [CHOICE_QUESTION_ID]: {\n type: 'choice',\n instructions: buildChoiceInstructions(req.question),\n criteria\n }\n },\n context.length > 0 ? { context } : {}\n );\n\n const answer = data.answers?.[CHOICE_QUESTION_ID] as SystemOneChoiceAnswer | undefined;\n const scored = toChoiceOptions(labels, keys, readDistribution(answer?.probabilities, keys), answer);\n if (scored === undefined) {\n throw new Error('the gateway returned neither a probability distribution nor a named criterion');\n }\n\n const options = scored.options;\n return {\n options,\n bestOption: options[0]?.label ?? '',\n confidence: options[0]?.probability ?? 0,\n uncalibrated: scored.uncalibrated,\n latencyMs: elapsed(start)\n };\n } catch (err) {\n throw new Error(`[JevBackend.choice] Failed: ${errorMessage(err)}`);\n }\n }\n\n /**\n * Verify assertions against evidence, fail-closed.\n *\n * Every assertion becomes one `choice` question in the same request, and the\n * answer's distribution over `verified` / `contradicted` / `not_addressed`\n * becomes the verdict. Anything unusable — a failed call, a missing answer, a\n * distribution below the strictness floor — escalates that assertion; the\n * method never returns a pass it could not observe.\n * @param req - assertions, evidence, strictness.\n * @returns one result per assertion plus the aggregate verdict.\n */\n async gate(req: GateRequest): Promise<GateResponse> {\n const start = performance.now();\n const assertions = Array.isArray(req.assertions) ? req.assertions : [];\n const strictness = req.strictness ?? 'normal';\n\n try {\n if (assertions.length === 0 || (req.evidence ?? '').trim().length === 0) {\n return this.failClosedGate(assertions, 'Evidence is empty or no assertions were supplied. Fail-closed.');\n }\n\n const ids = assertions.map((_, index) => `${GATE_QUESTION_PREFIX}${String(index)}`);\n const questions: Record<string, SystemOneQuestion> = {};\n assertions.forEach((assertion, index) => {\n questions[ids[index] as string] = {\n type: 'choice',\n instructions: buildGateInstructions(assertion, strictness),\n criteria: { ...GATE_VERDICT_CRITERIA }\n };\n });\n\n const context = (req.context ?? '').trim();\n const data = await this.postSystemOne(questions, {\n evidence: req.evidence,\n strictness,\n ...(context.length > 0 ? { context } : {})\n });\n\n const results: GateResultItem[] = assertions.map((assertion, index) =>\n this.gateItem(assertion, data.answers?.[ids[index] as string], strictness)\n );\n\n let passed = true;\n let needsEscalation = false;\n for (const item of results) {\n if (item.outcome === 'verified') continue;\n passed = false;\n if (item.outcome === 'escalate') needsEscalation = true;\n else if (item.outcome === 'not_addressed' && strictness !== 'lenient') needsEscalation = true;\n }\n\n return {\n passed: passed && !needsEscalation,\n results,\n needsEscalation,\n latencyMs: elapsed(start)\n };\n } catch (err) {\n return this.failClosedGate(\n assertions,\n `Jev API call failed: ${errorMessage(err)}. Fail-closed escalation triggered.`\n );\n }\n }\n\n /**\n * Classify whether each candidate sentence claims the task is complete.\n *\n * One `score` question per sentence, all in a single request. The two criteria\n * are ordered so index 1 is \"claims completion\"; the distribution over that\n * index is the answer. A sentence without a usable answer is left out of the\n * result rather than guessed, and the caller decides what an incomplete batch\n * means (the closing check fails open).\n * @param req - candidate sentences and the turn's intent.\n * @returns the classified sentences plus the request latency.\n */\n async classifyClaims(req: ClaimClassificationRequest): Promise<ClaimClassificationResponse> {\n const start = performance.now();\n const statements = Array.isArray(req.statements) ? req.statements.slice(0, MAX_CLAIM_SENTENCES) : [];\n if (statements.length === 0) return { results: [], latencyMs: elapsed(start) };\n\n try {\n const questions: Record<string, SystemOneQuestion> = {};\n const stateStatements: Record<string, string> = {};\n statements.forEach((statement, index) => {\n const id = `${CLAIM_QUESTION_PREFIX}${String(index)}`;\n questions[id] = {\n type: 'score',\n instructions: buildClaimInstructions(statement, req.intent),\n criteria: [...CLAIM_CRITERIA]\n };\n stateStatements[id] = statement;\n });\n\n const data = await this.postSystemOne(questions, {\n task: 'closing-claim',\n intent: req.intent,\n ...(req.context !== undefined && req.context.length > 0 ? { context: req.context } : {}),\n statements: stateStatements\n });\n\n const results: ClaimClassification[] = [];\n statements.forEach((statement, index) => {\n const id = `${CLAIM_QUESTION_PREFIX}${String(index)}`;\n const answer = data.answers?.[id] as SystemOneScoreAnswer | undefined;\n const classified = readClaimAnswer(statement, answer);\n if (classified !== undefined) results.push(classified);\n });\n return { results, latencyMs: elapsed(start) };\n } catch (err) {\n throw new Error(`[JevBackend.classifyClaims] Failed: ${errorMessage(err)}`);\n }\n }\n\n /** One assertion's outcome from its answer; unusable answers escalate. */\n private gateItem(\n assertion: GateAssertion,\n answer: SystemOneChoiceAnswer | SystemOneScoreAnswer | undefined,\n strictness: 'high' | 'normal' | 'lenient'\n ): GateResultItem {\n const statement = assertion?.statement ?? '';\n const choiceAnswer = answer as SystemOneChoiceAnswer | undefined;\n const distribution = readDistribution(choiceAnswer?.probabilities, GATE_VERDICTS);\n if (distribution === undefined) {\n return {\n statement,\n outcome: 'escalate',\n confidence: 0,\n explanation: 'The gateway returned no usable verdict distribution for this assertion. Fail-closed escalation.'\n };\n }\n\n const verdict = argmaxKey(distribution, GATE_VERDICTS) as GateVerdict;\n const confidence = round4(distribution.get(verdict) ?? 0);\n const floor = GATE_CONFIDENCE_FLOOR[strictness];\n if (confidence < floor) {\n return {\n statement,\n outcome: 'escalate',\n confidence,\n explanation: `System One named \"${verdict}\" at ${(confidence * 100).toFixed(1)}%, below the ${strictness} floor of ${(floor * 100).toFixed(0)}%. Fail-closed escalation.`\n };\n }\n\n return {\n statement,\n outcome: verdict,\n confidence,\n explanation: `System One named \"${verdict}\" at ${(confidence * 100).toFixed(1)}% (evidence supplied as state).`\n };\n }\n\n /** Every assertion escalated for one reason — the fail-closed shape. */\n private failClosedGate(assertions: readonly GateAssertion[], reason: string): GateResponse {\n const started = performance.now();\n return {\n passed: false,\n needsEscalation: true,\n results: assertions.map((assertion) => ({\n statement: assertion?.statement ?? '',\n outcome: 'escalate' as const,\n confidence: 0,\n explanation: reason\n })),\n latencyMs: elapsed(started)\n };\n }\n\n /**\n * Reduce a bulk output to the segments the intent needs, fail-open.\n *\n * Two paths share one contract. A payload below `pruneJudgeMinChars` is\n * reduced by the deterministic local candidates and sends no request at all.\n * A payload at/above it is cut into segments, and one `score` question per\n * segment lets System One decide what to keep; the three budgets only decide\n * how much of the top-scored material fits. Forced lines (first/last anchors,\n * diagnostics, intent matches) survive either way. Any failure — call,\n * transport, unusable answer — falls back to the local candidates, so pruning\n * never breaks the harness and never returns the raw blob just because the\n * network blinked.\n * @param req - raw output, intent, budget, shadow flag.\n * @returns the pruned text plus its reduction metrics and the path taken.\n */\n async prune(req: PruneRequest): Promise<PruneResponse> {\n const start = performance.now();\n const raw = typeof req.rawOutput === 'string' ? req.rawOutput : '';\n const intent = req.intent ?? '';\n if (raw.length === 0) return this.pruneResponse(raw, raw, req.shadowMode, start, { judgePath: 'local' });\n\n // The caller's resolved config is authoritative; the backend's own value\n // (explicit config, then environment, then default) is the fallback.\n const judgeMinChars = req.pruneJudgeMinChars ?? this.pruneJudgeMinChars;\n if (raw.length < judgeMinChars) {\n return this.pruneResponse(raw, this.localPruneText(raw, intent, req.maxTokens), req.shadowMode, start, {\n judgePath: 'local'\n });\n }\n return this.pruneWithSegments(req, raw, intent, start);\n }\n\n /** The deterministic candidate text, or the raw output when it does not shrink. */\n private localPruneText(raw: string, intent: string, maxTokens?: number): string {\n const candidates = buildPruneCandidates(raw, intent, maxTokens);\n const local = pickLocalPruneCandidate(candidates);\n if (local === undefined) return raw;\n return local.text.length < raw.length ? local.text : raw;\n }\n\n /**\n * Reduce the payload when System One cannot judge it.\n *\n * Template compression is format-independent, so it still shrinks output the\n * deterministic line filters cannot (progress art they would drop entirely, a\n * table whose rows differ only by a number). It is only ever used here, on the\n * degraded path, and the smaller of it and the local candidates wins.\n * @param raw - the original output.\n * @param intent - what the caller is looking for.\n * @param maxTokens - optional token budget.\n * @returns the reduced text and which strategy produced it.\n */\n private fallbackPruneText(\n raw: string,\n intent: string,\n maxTokens?: number\n ): { text: string; compression: 'template' | 'local' } {\n const local = this.localPruneText(raw, intent, maxTokens);\n const template = compressByTemplate(raw);\n if (template.length < local.length) return { text: template, compression: 'template' };\n return { text: local, compression: 'local' };\n }\n\n /** The per-segment System One path, with the local candidates as its fallback. */\n private async pruneWithSegments(\n req: PruneRequest,\n raw: string,\n intent: string,\n start: number\n ): Promise<PruneResponse> {\n const segments = segmentPruneOutput(raw, intent);\n if (segments.length <= 1) {\n // One segment has nothing to choose between; spending a judgment would\n // only reproduce the whole payload.\n return this.pruneResponse(raw, this.localPruneText(raw, intent, req.maxTokens), req.shadowMode, start, {\n judgePath: 'local',\n judgedSegments: 0,\n unjudgedSegments: segments.length\n });\n }\n\n const judged = segments.slice(0, PRUNE_MAX_JUDGED_SEGMENTS);\n const unjudgedSegments = segments.length - judged.length;\n const diagnostics = { judgedSegments: judged.length, unjudgedSegments };\n\n try {\n const { scores, unparsedScoreAnswers } = await this.scoreSegments(judged, segments.length, intent);\n // Every segment without a usable score is kept whole as the unjudged\n // safety margin, so its share of the payload is the first number to read\n // when a judgment \"ran\" but the candidate did not shrink.\n const observation = {\n ...diagnostics,\n scoredSegments: scores.size,\n autoKeptSegments: segments.length - scores.size,\n unparsedScoreAnswers\n };\n if (scores.size === 0) {\n const fallback = this.fallbackPruneText(raw, intent, req.maxTokens);\n return this.pruneResponse(raw, fallback.text, req.shadowMode, start, {\n judgePath: 'fallback',\n fallbackReason: 'System One returned no usable segment score',\n compression: fallback.compression,\n ...observation\n });\n }\n const candidates = buildScoredPruneCandidates(raw, segments, scores, req.maxTokens);\n const charsOf = (id: PruneCandidate['id']): number =>\n candidates.find((candidate) => candidate.id === id)?.text.length ?? raw.length;\n const sizes = {\n aggressiveChars: charsOf('aggressive'),\n balancedChars: charsOf('balanced'),\n conservativeChars: charsOf('conservative')\n };\n // The balanced candidate's selection answers \"did the judge keep too much\n // to shrink anything\"; when another budget was installed, its own count is\n // what survived, so report that one instead.\n const balanced = candidates.find((candidate) => candidate.id === 'balanced');\n const pick = pickScoredPruneCandidate(raw, candidates);\n if (pick.candidate !== undefined) {\n return this.pruneResponse(raw, pick.text, req.shadowMode, start, {\n judgePath: 'segmented',\n ...observation,\n ...sizes,\n keptSegments: pick.candidate.keptSegments\n });\n }\n // The judgment kept as much as the payload: every segment was scored and\n // kept whole. That is the model's decision, not a service failure, so the\n // payload is returned untouched instead of being template-compressed over\n // it. Only a judgment with no usable score at all (handled above) and a\n // failed call (below) fall back to template compression.\n return this.pruneResponse(raw, raw, req.shadowMode, start, {\n judgePath: 'segmented',\n fallbackReason: 'judged: every segment was kept',\n compression: 'none',\n ...observation,\n ...sizes,\n ...(balanced === undefined ? {} : { keptSegments: balanced.keptSegments })\n });\n } catch (err) {\n // FAIL-OPEN: template compression keeps the pruned output useful even when\n // the deterministic line filters have nothing to drop; the harness never\n // breaks and never returns the raw blob just because the gateway blinked.\n const fallback = this.fallbackPruneText(raw, intent, req.maxTokens);\n return this.pruneResponse(raw, fallback.text, req.shadowMode, start, {\n judgePath: 'fallback',\n fallbackReason: errorMessage(err),\n compression: fallback.compression,\n ...diagnostics\n });\n }\n }\n\n /**\n * Judge every segment in one request: one `score` question per segment, with\n * the segment text and the intent in the shared state.\n * @param judged - the segments selected for judging, in original order.\n * @param totalSegments - segment count of the whole output (for the prompt).\n * @param intent - what the caller is looking for.\n * @returns the keep score per segment index (segments without a usable answer\n * are absent) and how many answers were returned but could not be read.\n */\n private async scoreSegments(\n judged: readonly PruneSegment[],\n totalSegments: number,\n intent: string\n ): Promise<{ scores: Map<number, number>; unparsedScoreAnswers: number }> {\n const questions: Record<string, SystemOneQuestion> = {};\n const stateSegments: Record<string, string> = {};\n for (const segment of judged) {\n const id = `${PRUNE_SEGMENT_QUESTION_PREFIX}${String(segment.index)}`;\n questions[id] = {\n type: 'score',\n instructions: buildSegmentInstructions(intent, segment, totalSegments),\n criteria: [...PRUNE_KEEP_CRITERIA]\n };\n stateSegments[id] = segment.text;\n }\n\n const data = await this.postSystemOne(questions, {\n intent,\n segments: stateSegments,\n judgedSegments: judged.length,\n unjudgedSegments: totalSegments - judged.length,\n segmentMaxChars: PRUNE_SEGMENT_MAX_CHARS\n });\n\n const scores = new Map<number, number>();\n let unparsedScoreAnswers = 0;\n for (const segment of judged) {\n const id = `${PRUNE_SEGMENT_QUESTION_PREFIX}${String(segment.index)}`;\n const answer = data.answers?.[id] as SystemOneScoreAnswer | undefined;\n const score = readSegmentKeepScore(answer);\n if (score !== undefined) {\n scores.set(segment.index, score);\n } else if (answer !== undefined && answer !== null) {\n // An answer we cannot read is not a high score: it is counted, and the\n // segment falls into the unjudged safety margin with no answer at all.\n unparsedScoreAnswers += 1;\n }\n }\n return { scores, unparsedScoreAnswers };\n }\n\n /** Shape one pruning as the shared prune response. */\n private pruneResponse(\n raw: string,\n text: string,\n shadow: boolean | undefined,\n start: number,\n meta?: PruneDiagnostics\n ): PruneResponse {\n const originalChars = raw.length;\n const prunedChars = text.length;\n return {\n processedOutput: shadow ? raw : text,\n originalChars,\n prunedChars,\n estimatedTokensSaved: Math.max(0, Math.ceil((originalChars - prunedChars) / 4)),\n reductionPercentage:\n originalChars > 0 ? Number((((originalChars - prunedChars) / originalChars) * 100).toFixed(1)) : 0,\n shadow: Boolean(shadow),\n latencyMs: elapsed(start),\n ...meta\n };\n }\n\n /**\n * Classify the recent action window into one execution pattern.\n *\n * One `choice` question over the five patterns; the distribution decides the\n * verdict and its confidence. When the gateway cannot answer, the same window\n * is read by {@link detectStagnationLocally}, so a network failure lowers the\n * quality of the verdict instead of removing it.\n * @param req - action history and optional goal.\n * @returns the pattern, whether it is stuck, and the intervention.\n */\n async checkStagnation(req: StagnationCheckRequest): Promise<StagnationCheckResponse> {\n const start = performance.now();\n const history = Array.isArray(req.history) ? req.history : [];\n const windowSize = typeof req.windowSize === 'number' && req.windowSize > 0 ? req.windowSize : 6;\n const recent = history.slice(-windowSize);\n\n if (recent.length < 3) {\n return {\n isStuck: false,\n patternType: 'none',\n confidence: 1,\n diagnosis: 'Action count below stagnation threshold (< 3).',\n latencyMs: elapsed(start)\n };\n }\n\n try {\n const criteria: Record<string, string> = {};\n for (const pattern of STAGNATION_PATTERNS) criteria[pattern] = STAGNATION_PATTERN_CRITERIA[pattern];\n\n const data = await this.postSystemOne(\n {\n [STAGNATION_QUESTION_ID]: {\n type: 'choice',\n instructions: buildStagnationInstructions(),\n criteria\n }\n },\n {\n goal: (req.goal ?? '').trim() || null,\n window: recent.length,\n actions: recent.map((step) => ({\n tool: step.tool,\n input: clip(step.input, 240),\n ...(step.output === undefined ? {} : { output: clip(step.output, 240) }),\n ...(step.error === undefined ? {} : { error: clip(step.error, 240) })\n }))\n }\n );\n\n const answer = data.answers?.[STAGNATION_QUESTION_ID] as SystemOneChoiceAnswer | undefined;\n const distribution = readDistribution(answer?.probabilities, STAGNATION_PATTERNS);\n if (distribution === undefined) {\n return this.localStagnation(recent, 'the gateway returned no usable pattern distribution', start);\n }\n\n const pattern = argmaxKey(distribution, STAGNATION_PATTERNS) as StagnationPattern;\n const confidence = round4(distribution.get(pattern) ?? 0);\n const isStuck = pattern !== 'none' && confidence >= STAGNATION_STUCK_FLOOR;\n return {\n isStuck,\n patternType: pattern,\n confidence,\n diagnosis: `${STAGNATION_DIAGNOSIS[pattern]} (System One p=${confidence.toFixed(3)})`,\n ...(isStuck ? { recommendedIntervention: STAGNATION_INTERVENTION[pattern] } : {}),\n latencyMs: elapsed(start)\n };\n } catch (err) {\n return this.localStagnation(recent, errorMessage(err), start);\n }\n }\n\n /** The local half of {@link checkStagnation}, annotated with why it ran. */\n private localStagnation(recent: readonly ActionStep[], reason: string, start: number): StagnationCheckResponse {\n const local = detectStagnationLocally(recent);\n return {\n isStuck: local.isStuck,\n patternType: local.patternType,\n confidence: local.confidence,\n diagnosis: `${local.diagnosis} [System One unavailable: ${reason}]`,\n ...(local.recommendedIntervention === undefined\n ? {}\n : { recommendedIntervention: local.recommendedIntervention }),\n latencyMs: elapsed(start)\n };\n }\n\n /**\n * Rank candidates for a goal with one `choice` question.\n *\n * The criteria are the candidate names carrying their descriptions and the\n * incumbent mark, and the answer's distribution is the ranking. The rendered\n * context block of {@link buildRouteContext} — the same facts the logits\n * backend scores — rides in the instructions, so cache-affinity facts and the\n * policy reach the model. A failing gateway falls back to a local keyword\n * ranking whose reasons say so, keeping routing alive.\n * @param req - goal, candidates, topK, session facts, policy.\n * @returns the ranked candidates, best first.\n */\n async route(req: RouteRequest): Promise<RouteResponse> {\n const start = performance.now();\n const candidates = Array.isArray(req.candidates) ? req.candidates : [];\n const topK = typeof req.topK === 'number' && req.topK > 0 ? req.topK : 3;\n if (candidates.length === 0) return { rankedCandidates: [], latencyMs: elapsed(start) };\n\n try {\n const keys = uniqueCriteriaKeys(candidates.map((candidate) => candidate.name));\n const criteria: Record<string, string> = {};\n keys.forEach((key, index) => {\n const candidate = candidates[index] as RouteCandidateItem;\n criteria[key] = candidateCriterion(candidate);\n });\n\n const data = await this.postSystemOne(\n {\n [ROUTE_QUESTION_ID]: {\n type: 'choice',\n instructions: buildRouteInstructions(req),\n criteria\n }\n },\n {\n goal: req.goal,\n ...(req.state === undefined ? {} : { session: req.state }),\n topK\n }\n );\n\n const answer = data.answers?.[ROUTE_QUESTION_ID] as SystemOneChoiceAnswer | undefined;\n const distribution = readDistribution(answer?.probabilities, keys);\n if (distribution === undefined) {\n return this.localRoute(candidates, req.goal, 'the gateway returned no usable candidate distribution', topK, start);\n }\n\n const ranked = candidates\n .map((candidate, index) => ({ name: candidate.name, score: round4(distribution.get(keys[index] as string) ?? 0) }))\n .sort((a, b) => b.score - a.score);\n\n const declaredKey =\n typeof answer?.choice === 'string'\n ? keys.find((key) => normalizeKey(key) === normalizeKey(String(answer.choice)))\n : undefined;\n if (declaredKey !== undefined) {\n const declaredName = candidates[keys.indexOf(declaredKey)]?.name ?? '';\n promoteTiedWinner(ranked, ranked.findIndex((entry) => entry.name === declaredName), (entry) => entry.score);\n }\n\n const sliced = ranked.slice(0, topK);\n return { rankedCandidates: sliced, bestCandidate: sliced[0]?.name, latencyMs: elapsed(start) };\n } catch (err) {\n return this.localRoute(candidates, req.goal, errorMessage(err), topK, start);\n }\n }\n\n /** Deterministic keyword ranking used when the gateway cannot rank. */\n private localRoute(\n candidates: readonly RouteCandidateItem[],\n goal: string,\n reason: string,\n topK: number,\n start: number\n ): RouteResponse {\n const goalWords = tokenize(goal ?? '');\n const weighted = candidates.map((candidate) => {\n const text = `${candidate.name} ${candidate.description ?? ''} ${candidate.type ?? ''}`.toLowerCase();\n const matches = goalWords.filter((word) => text.includes(word)).length;\n return { name: candidate.name, weight: 0.1 + matches };\n });\n const total = weighted.reduce((sum, entry) => sum + entry.weight, 0);\n const ranked = weighted\n .map((entry) => ({\n name: entry.name,\n score: Number((entry.weight / total).toFixed(4)),\n reason: `local fallback (${reason})`\n }))\n .sort((a, b) => b.score - a.score);\n const sliced = ranked.slice(0, topK);\n return { rankedCandidates: sliced, bestCandidate: sliced[0]?.name, latencyMs: elapsed(start) };\n }\n}\n"]}