open-multi-agent-kit 1.0.0 → 1.2.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 (244) hide show
  1. package/CHANGELOG.md +6 -1
  2. package/README.md +2 -2
  3. package/dist/cli/help.d.ts.map +1 -1
  4. package/dist/cli/help.js +1 -0
  5. package/dist/cli/help.js.map +1 -1
  6. package/dist/coordination/awareness.d.ts +32 -0
  7. package/dist/coordination/awareness.d.ts.map +1 -0
  8. package/dist/coordination/awareness.js +55 -0
  9. package/dist/coordination/awareness.js.map +1 -0
  10. package/dist/coordination/broker.d.ts +79 -0
  11. package/dist/coordination/broker.d.ts.map +1 -0
  12. package/dist/coordination/broker.js +195 -0
  13. package/dist/coordination/broker.js.map +1 -0
  14. package/dist/coordination/index.d.ts +16 -0
  15. package/dist/coordination/index.d.ts.map +1 -0
  16. package/dist/coordination/index.js +16 -0
  17. package/dist/coordination/index.js.map +1 -0
  18. package/dist/coordination/integration.d.ts +59 -0
  19. package/dist/coordination/integration.d.ts.map +1 -0
  20. package/dist/coordination/integration.js +126 -0
  21. package/dist/coordination/integration.js.map +1 -0
  22. package/dist/coordination/operation.d.ts +106 -0
  23. package/dist/coordination/operation.d.ts.map +1 -0
  24. package/dist/coordination/operation.js +179 -0
  25. package/dist/coordination/operation.js.map +1 -0
  26. package/dist/coordination/resource.d.ts +33 -0
  27. package/dist/coordination/resource.d.ts.map +1 -0
  28. package/dist/coordination/resource.js +89 -0
  29. package/dist/coordination/resource.js.map +1 -0
  30. package/dist/coordination/session.d.ts +74 -0
  31. package/dist/coordination/session.d.ts.map +1 -0
  32. package/dist/coordination/session.js +143 -0
  33. package/dist/coordination/session.js.map +1 -0
  34. package/dist/coordination/types.d.ts +68 -0
  35. package/dist/coordination/types.d.ts.map +1 -0
  36. package/dist/coordination/types.js +26 -0
  37. package/dist/coordination/types.js.map +1 -0
  38. package/dist/core/agent-session.d.ts.map +1 -1
  39. package/dist/core/agent-session.js +28 -7
  40. package/dist/core/agent-session.js.map +1 -1
  41. package/dist/core/compaction/control-state.d.ts +41 -0
  42. package/dist/core/compaction/control-state.d.ts.map +1 -0
  43. package/dist/core/compaction/control-state.js +85 -0
  44. package/dist/core/compaction/control-state.js.map +1 -0
  45. package/dist/core/compaction/fallback.d.ts +60 -0
  46. package/dist/core/compaction/fallback.d.ts.map +1 -0
  47. package/dist/core/compaction/fallback.js +117 -0
  48. package/dist/core/compaction/fallback.js.map +1 -0
  49. package/dist/core/compaction/index.d.ts +2 -0
  50. package/dist/core/compaction/index.d.ts.map +1 -1
  51. package/dist/core/compaction/index.js +2 -0
  52. package/dist/core/compaction/index.js.map +1 -1
  53. package/dist/core/context-budget-headroom-candidates.d.ts +16 -1
  54. package/dist/core/context-budget-headroom-candidates.d.ts.map +1 -1
  55. package/dist/core/context-budget-headroom-candidates.js +31 -13
  56. package/dist/core/context-budget-headroom-candidates.js.map +1 -1
  57. package/dist/core/context-budget-headroom-types.d.ts +7 -1
  58. package/dist/core/context-budget-headroom-types.d.ts.map +1 -1
  59. package/dist/core/context-budget-headroom-types.js +0 -1
  60. package/dist/core/context-budget-headroom-types.js.map +1 -1
  61. package/dist/core/context-budget-headroom.d.ts +10 -0
  62. package/dist/core/context-budget-headroom.d.ts.map +1 -1
  63. package/dist/core/context-budget-headroom.js +11 -2
  64. package/dist/core/context-budget-headroom.js.map +1 -1
  65. package/dist/core/context-budget-v2-global-pass.d.ts +21 -0
  66. package/dist/core/context-budget-v2-global-pass.d.ts.map +1 -0
  67. package/dist/core/context-budget-v2-global-pass.js +203 -0
  68. package/dist/core/context-budget-v2-global-pass.js.map +1 -0
  69. package/dist/core/context-budget-v2-planned-items.d.ts +12 -0
  70. package/dist/core/context-budget-v2-planned-items.d.ts.map +1 -1
  71. package/dist/core/context-budget-v2-planned-items.js +21 -2
  72. package/dist/core/context-budget-v2-planned-items.js.map +1 -1
  73. package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
  74. package/dist/core/context-budget-v2-planner.js +18 -19
  75. package/dist/core/context-budget-v2-planner.js.map +1 -1
  76. package/dist/core/context-budget-v2-scoring.d.ts +7 -1
  77. package/dist/core/context-budget-v2-scoring.d.ts.map +1 -1
  78. package/dist/core/context-budget-v2-scoring.js.map +1 -1
  79. package/dist/core/context-budget-v2-selection.d.ts +3 -0
  80. package/dist/core/context-budget-v2-selection.d.ts.map +1 -1
  81. package/dist/core/context-budget-v2-selection.js +6 -2
  82. package/dist/core/context-budget-v2-selection.js.map +1 -1
  83. package/dist/core/context-budget-v2-types.d.ts +6 -1
  84. package/dist/core/context-budget-v2-types.d.ts.map +1 -1
  85. package/dist/core/context-budget-v2-types.js +6 -1
  86. package/dist/core/context-budget-v2-types.js.map +1 -1
  87. package/dist/core/provider-default-models.d.ts +1 -0
  88. package/dist/core/provider-default-models.d.ts.map +1 -1
  89. package/dist/core/provider-default-models.js +1 -0
  90. package/dist/core/provider-default-models.js.map +1 -1
  91. package/dist/core/provider-display-names.d.ts.map +1 -1
  92. package/dist/core/provider-display-names.js +1 -0
  93. package/dist/core/provider-display-names.js.map +1 -1
  94. package/dist/core/reasoning-router-resolver.d.ts +7 -0
  95. package/dist/core/reasoning-router-resolver.d.ts.map +1 -1
  96. package/dist/core/reasoning-router-resolver.js +21 -3
  97. package/dist/core/reasoning-router-resolver.js.map +1 -1
  98. package/dist/core/reasoning-router-v4.d.ts +8 -5
  99. package/dist/core/reasoning-router-v4.d.ts.map +1 -1
  100. package/dist/core/reasoning-router-v4.js +8 -5
  101. package/dist/core/reasoning-router-v4.js.map +1 -1
  102. package/dist/core/session-compaction-service.d.ts +15 -0
  103. package/dist/core/session-compaction-service.d.ts.map +1 -1
  104. package/dist/core/session-compaction-service.js +17 -4
  105. package/dist/core/session-compaction-service.js.map +1 -1
  106. package/dist/core/todo-runtime-state.d.ts +12 -0
  107. package/dist/core/todo-runtime-state.d.ts.map +1 -1
  108. package/dist/core/todo-runtime-state.js +23 -0
  109. package/dist/core/todo-runtime-state.js.map +1 -1
  110. package/dist/index.d.ts +2 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +2 -0
  113. package/dist/index.js.map +1 -1
  114. package/dist/metacognition/calibration-selective.d.ts +78 -0
  115. package/dist/metacognition/calibration-selective.d.ts.map +1 -0
  116. package/dist/metacognition/calibration-selective.js +161 -0
  117. package/dist/metacognition/calibration-selective.js.map +1 -0
  118. package/dist/metacognition/calibration.d.ts +62 -0
  119. package/dist/metacognition/calibration.d.ts.map +1 -0
  120. package/dist/metacognition/calibration.js +122 -0
  121. package/dist/metacognition/calibration.js.map +1 -0
  122. package/dist/metacognition/checkpoint.d.ts +60 -0
  123. package/dist/metacognition/checkpoint.d.ts.map +1 -0
  124. package/dist/metacognition/checkpoint.js +57 -0
  125. package/dist/metacognition/checkpoint.js.map +1 -0
  126. package/dist/metacognition/context7.d.ts +48 -0
  127. package/dist/metacognition/context7.d.ts.map +1 -0
  128. package/dist/metacognition/context7.js +154 -0
  129. package/dist/metacognition/context7.js.map +1 -0
  130. package/dist/metacognition/decision.d.ts +44 -0
  131. package/dist/metacognition/decision.d.ts.map +1 -0
  132. package/dist/metacognition/decision.js +111 -0
  133. package/dist/metacognition/decision.js.map +1 -0
  134. package/dist/metacognition/evaluation.d.ts +73 -0
  135. package/dist/metacognition/evaluation.d.ts.map +1 -0
  136. package/dist/metacognition/evaluation.js +97 -0
  137. package/dist/metacognition/evaluation.js.map +1 -0
  138. package/dist/metacognition/index.d.ts +31 -0
  139. package/dist/metacognition/index.d.ts.map +1 -0
  140. package/dist/metacognition/index.js +31 -0
  141. package/dist/metacognition/index.js.map +1 -0
  142. package/dist/metacognition/knowledge-action.d.ts +43 -0
  143. package/dist/metacognition/knowledge-action.d.ts.map +1 -0
  144. package/dist/metacognition/knowledge-action.js +60 -0
  145. package/dist/metacognition/knowledge-action.js.map +1 -0
  146. package/dist/metacognition/knowledge.d.ts +84 -0
  147. package/dist/metacognition/knowledge.d.ts.map +1 -0
  148. package/dist/metacognition/knowledge.js +165 -0
  149. package/dist/metacognition/knowledge.js.map +1 -0
  150. package/dist/metacognition/obligations.d.ts +82 -0
  151. package/dist/metacognition/obligations.d.ts.map +1 -0
  152. package/dist/metacognition/obligations.js +139 -0
  153. package/dist/metacognition/obligations.js.map +1 -0
  154. package/dist/metacognition/observation-validity.d.ts +83 -0
  155. package/dist/metacognition/observation-validity.d.ts.map +1 -0
  156. package/dist/metacognition/observation-validity.js +118 -0
  157. package/dist/metacognition/observation-validity.js.map +1 -0
  158. package/dist/metacognition/observe.d.ts +45 -0
  159. package/dist/metacognition/observe.d.ts.map +1 -0
  160. package/dist/metacognition/observe.js +59 -0
  161. package/dist/metacognition/observe.js.map +1 -0
  162. package/dist/metacognition/policy.d.ts +53 -0
  163. package/dist/metacognition/policy.d.ts.map +1 -0
  164. package/dist/metacognition/policy.js +155 -0
  165. package/dist/metacognition/policy.js.map +1 -0
  166. package/dist/metacognition/predictions.d.ts +78 -0
  167. package/dist/metacognition/predictions.d.ts.map +1 -0
  168. package/dist/metacognition/predictions.js +181 -0
  169. package/dist/metacognition/predictions.js.map +1 -0
  170. package/dist/metacognition/retrieval.d.ts +53 -0
  171. package/dist/metacognition/retrieval.d.ts.map +1 -0
  172. package/dist/metacognition/retrieval.js +170 -0
  173. package/dist/metacognition/retrieval.js.map +1 -0
  174. package/dist/metacognition/risk.d.ts +48 -0
  175. package/dist/metacognition/risk.d.ts.map +1 -0
  176. package/dist/metacognition/risk.js +165 -0
  177. package/dist/metacognition/risk.js.map +1 -0
  178. package/dist/metacognition/route-economics.d.ts +95 -0
  179. package/dist/metacognition/route-economics.d.ts.map +1 -0
  180. package/dist/metacognition/route-economics.js +110 -0
  181. package/dist/metacognition/route-economics.js.map +1 -0
  182. package/dist/metacognition/runtime-bridge.d.ts +54 -0
  183. package/dist/metacognition/runtime-bridge.d.ts.map +1 -0
  184. package/dist/metacognition/runtime-bridge.js +140 -0
  185. package/dist/metacognition/runtime-bridge.js.map +1 -0
  186. package/dist/metacognition/skills.d.ts +42 -0
  187. package/dist/metacognition/skills.d.ts.map +1 -0
  188. package/dist/metacognition/skills.js +220 -0
  189. package/dist/metacognition/skills.js.map +1 -0
  190. package/dist/metacognition/state.d.ts +110 -0
  191. package/dist/metacognition/state.d.ts.map +1 -0
  192. package/dist/metacognition/state.js +52 -0
  193. package/dist/metacognition/state.js.map +1 -0
  194. package/dist/metacognition/validation.d.ts +19 -0
  195. package/dist/metacognition/validation.d.ts.map +1 -0
  196. package/dist/metacognition/validation.js +58 -0
  197. package/dist/metacognition/validation.js.map +1 -0
  198. package/dist/metacognition/verification.d.ts +93 -0
  199. package/dist/metacognition/verification.d.ts.map +1 -0
  200. package/dist/metacognition/verification.js +132 -0
  201. package/dist/metacognition/verification.js.map +1 -0
  202. package/dist/metacognition/verifier.d.ts +49 -0
  203. package/dist/metacognition/verifier.d.ts.map +1 -0
  204. package/dist/metacognition/verifier.js +88 -0
  205. package/dist/metacognition/verifier.js.map +1 -0
  206. package/dist/observation/identity.d.ts +14 -0
  207. package/dist/observation/identity.d.ts.map +1 -0
  208. package/dist/observation/identity.js +29 -0
  209. package/dist/observation/identity.js.map +1 -0
  210. package/dist/observation/index.d.ts +13 -0
  211. package/dist/observation/index.d.ts.map +1 -0
  212. package/dist/observation/index.js +13 -0
  213. package/dist/observation/index.js.map +1 -0
  214. package/dist/observation/observe-mode.d.ts +46 -0
  215. package/dist/observation/observe-mode.d.ts.map +1 -0
  216. package/dist/observation/observe-mode.js +83 -0
  217. package/dist/observation/observe-mode.js.map +1 -0
  218. package/dist/observation/store.d.ts +53 -0
  219. package/dist/observation/store.d.ts.map +1 -0
  220. package/dist/observation/store.js +126 -0
  221. package/dist/observation/store.js.map +1 -0
  222. package/dist/observation/types.d.ts +72 -0
  223. package/dist/observation/types.d.ts.map +1 -0
  224. package/dist/observation/types.js +9 -0
  225. package/dist/observation/types.js.map +1 -0
  226. package/dist/observation/view.d.ts +39 -0
  227. package/dist/observation/view.d.ts.map +1 -0
  228. package/dist/observation/view.js +173 -0
  229. package/dist/observation/view.js.map +1 -0
  230. package/docs/metacognition.md +51 -0
  231. package/docs/model-catalog-refresh.md +59 -0
  232. package/docs/providers.md +53 -0
  233. package/docs/runtime-algorithms.md +107 -3
  234. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  235. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  236. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  237. package/examples/extensions/gondolin/package-lock.json +2 -2
  238. package/examples/extensions/gondolin/package.json +1 -1
  239. package/examples/extensions/sandbox/package-lock.json +2 -2
  240. package/examples/extensions/sandbox/package.json +1 -1
  241. package/examples/extensions/with-deps/package-lock.json +2 -2
  242. package/examples/extensions/with-deps/package.json +1 -1
  243. package/npm-shrinkwrap.json +18 -18
  244. package/package.json +6 -6
@@ -1 +1 @@
1
- {"version":3,"file":"reasoning-router-v4.js","sourceRoot":"","sources":["../../src/core/reasoning-router-v4.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,EACN,kBAAkB,EAGlB,eAAe,GAEf,MAAM,kCAAkC,CAAC;AAI1C,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAEvF,OAAO,EAAE,wBAAwB,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AACtG,OAAO,EAAE,kCAAkC,EAAE,MAAM,oCAAoC,CAAC;AAExF,+FAA+F;AAC/F,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,6FAA6F;AAC7F,MAAM,0BAA0B,GAAG,IAAI,CAAC;AACxC,uGAAuG;AACvG,MAAM,uBAAuB,GAAG,GAAG,CAAC;AACpC,sHAAsH;AACtH,MAAM,2BAA2B,GAAG,GAAG,CAAC;AACxC,qGAAqG;AACrG,MAAM,mCAAmC,GAAG,CAAC,CAAC;AAC9C,2HAA2H;AAC3H,MAAM,oCAAoC,GAAG,GAAG,CAAC;AAEjD,2F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;GAIG;AACH,MAAM,UAAU,6BAA6B,CAC5C,SAAsB,EACtB,eAAyC,EACzC,QAAyC,EACzB;IAChB,OAAO,wBAAwB,CAAC,SAAS,EAAE,eAAe,EAAE,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;AAAA,CAClF;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,qCAAqC,CACpD,OAA4B,EAC5B,eAAyC,EACzC,QAAyC,EACzC,IAAI,GAAG,CAAC,EACR,IAAI,GAAwD,IAAI,EAChD;IAChB,MAAM,eAAe,GACpB,OAAO,CAAC,cAAc,KAAK,KAAK,IAAI,OAAO,CAAC,cAAc,KAAK,IAAI,CAAC,CAAC,CAAC,kCAAkC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9G,OAAO,wBAAwB,CAAC,OAAO,CAAC,SAAS,EAAE,eAAe,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,eAAe,CAAC,CAAC;AAAA,CAC3G","sourcesContent":["/**\n * Reasoning-router v4 — the sole `/think auto` classifier/resolver.\n *\n * Deterministic by construction: same (input, weights) -> same\n * ClassifierVerdictV4; same (verdict, availableLevels, laneType, bias, hint) ->\n * same ThinkingLevel. No clock, randomness, I/O, model calls, network access,\n * or state mutation anywhere in this file (ThinkingLevel is a type-only import\n * and is erased).\n *\n * `classifyTaskV4` returns a confidence-bearing verdict: task class, per-class\n * scores, runner-up, margin, confidence band, tie-break flag, fallback reason,\n * bounded-negation audit ids, and compound-intent metadata. None of this carries\n * prompt text — every field is a bounded enum, number, boolean, or a closed set\n * of short diagnostic-id strings.\n *\n * `resolveThinkingLevelV4WithUncertainty` starts from the canonical task-class\n * rule table, applies lane/bias/hint adjustments, and only adds non-negative\n * confidence escalation. A prompt cannot lower its own effort by asking the\n * router to \"think less\"; low confidence or fallback routing can only hold or\n * raise the resolved level.\n */\n\nimport type { ThinkingLevel } from \"omk-agent-core\";\nimport {\n\tDEFAULT_WEIGHTS_V4,\n\ttype ReasoningLaneTypeV4,\n\ttype RouterWeightsV4,\n\tTASK_CLASSES_V4,\n\ttype TaskClassV4,\n} from \"./reasoning-router-v4-weights.ts\";\nimport type { RouterFeedbackLenBucket } from \"./router-feedback-collector.ts\";\n\nexport type { ReasoningLaneTypeV4, RouterWeightsV4, TaskClassV4 } from \"./reasoning-router-v4-weights.ts\";\nexport { DEFAULT_WEIGHTS_V4, TASK_CLASSES_V4 } from \"./reasoning-router-v4-weights.ts\";\n\nimport { resolveThinkingLevelCore, TASK_CLASS_THINKING_LEVELS } from \"./reasoning-router-resolver.ts\";\nimport { extractGeneralizedIntentEvidenceV4 } from \"./reasoning-router-v4-normalize.ts\";\n\n/** Prompts shorter than this (trimmed) fall back to trivial when no real signal scores > 0. */\nconst TRIVIAL_MAX_CHARS_V4 = 40;\n/** Prompts at/above this length with no real signal fall back to plan (long prose brief). */\nconst COMPLEX_PROSE_MIN_CHARS_V4 = 2400;\n/** Plan-brief prompts at/above this length count as a \"long brief\" even without PLAN_BRIEF_PATTERN. */\nconst LONG_BRIEF_MIN_CHARS_V4 = 512;\n/** Compound-clause split only applies within this many leading characters (short direct commands, not long prose). */\nconst COMPOUND_SPLIT_MAX_INDEX_V4 = 300;\n/** Minimum trimmed length of a candidate second clause to be worth checking for a leading intent. */\nconst COMPOUND_SECOND_CLAUSE_MIN_CHARS_V4 = 3;\n/** Bounded look-ahead cap when checking a second clause's leading intent (defense in depth; independent of regex cost). */\nconst COMPOUND_SECOND_CLAUSE_SCAN_CHARS_V4 = 200;\n\n/** Lane fallback class, used only when every scored class is <= 0 (zero-score cascade). */\nconst LANE_FALLBACK_CLASS_V4: Readonly<Record<ReasoningLaneTypeV4, TaskClassV4>> = {\n\tplanner: \"plan\",\n\tsecurity: \"review\",\n\texplorer: \"review\",\n\tcoder: \"code-gen\",\n\treviewer: \"review\",\n\ttester: \"code-gen\",\n};\n\ntype IntentLexemeClusterRoleV4 = \"leading-intent\" | \"whole-prompt\" | \"object-shape\" | \"korean-morphology\";\n\ntype IntentLexemeClusterV4 = {\n\treadonly id: string;\n\treadonly taskClass: TaskClassV4;\n\treadonly role: IntentLexemeClusterRoleV4;\n\treadonly surfaces: readonly string[];\n\treadonly phrases: readonly RegExp[];\n\treadonly negativeControlIds: readonly string[];\n};\n\nconst INTENT_LEXEME_CLUSTERS_V4: readonly IntentLexemeClusterV4[] = [\n\t{\n\t\tid: \"debug-leading-actions\",\n\t\ttaskClass: \"debug\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\"debug\", \"investigate why\", \"reproduce\", \"trace\", \"fix this traceback/panic/error\"],\n\t\tphrases: [/^(?:debug|investigate\\s+why|reproduce|trace\\b)|^fix\\s+this\\s+(?:traceback|panic|error)\\b/i],\n\t\tnegativeControlIds: [\"negated-debug-action\", \"generic-error-handling\"],\n\t},\n\t{\n\t\tid: \"review-leading-actions\",\n\t\ttaskClass: \"review\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\"review\", \"audit\", \"critique\", \"inspect\", \"assess\", \"approve\", \"double-check\", \"lgtm\"],\n\t\tphrases: [/^(?:review|audit(?!\\s+log\\b)|critique|inspect|assess|approve|double-?check|lgtm)\\b/i],\n\t\tnegativeControlIds: [\"audit-log-not-review\", \"review-negated-before-code-gen\"],\n\t},\n\t{\n\t\tid: \"review-leading-synonyms\",\n\t\ttaskClass: \"review\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\n\t\t\t\"give this PR a once-over\",\n\t\t\t\"look over\",\n\t\t\t\"sanity-check\",\n\t\t\t\"eyeball\",\n\t\t\t\"poke holes\",\n\t\t\t\"pressure-test\",\n\t\t\t\"tell me whether/if\",\n\t\t\t\"what could go wrong\",\n\t\t],\n\t\tphrases: [\n\t\t\t/^(?:give\\s+(?:this|the|my)?\\s*(?:pr|pull\\s+request|diff|code|change|branch)?\\s*(?:a\\s+)?once-?over|look\\s+over|sanity[-\\s]?check|eyeball|poke\\s+holes(?:\\s+in)?|pressure[-\\s]?test|sign\\s+off|tell\\s+me\\s+(?:if|whether)|tell\\s+me\\s+what\\s+could\\s+go\\s+wrong|where\\s+would\\b[^.!?;\\n]{0,100}\\bfall\\s+apart|what\\s+am\\s+i\\s+missing|check\\s+whether|look\\s+for\\s+(?:edge\\s+cases|risks?|flaws?)|find\\s+(?:flaws|risks?|issues?)|validate\\s+(?:the\\s+)?reasoning|give\\s+me\\s+a\\s+thumbs[-\\s]?up\\/?down|read\\s+(?:this|the|my)\\b[^.!?;\\n]{0,80}\\bchallenge|(?:is|are|does|do|can|could|would|should)\\s+(?:this|these|my|the)\\b[^.!?;\\n]{0,100}\\b(?:right\\s+way|handle|cover|safe|sane|clean|overkill|prove|leak|ship|concurrent|hidden\\s+coupling)|(?:at\\s+architecture\\s+level|architecture[-\\s]?level)\\b[^.!?;\\n]{0,80}\\bhidden\\s+coupling)\\b/i,\n\t\t],\n\t\tnegativeControlIds: [\"sanity-check-setup-script\", \"future-self-review-context\", \"check-whether-implementation\"],\n\t},\n\t{\n\t\tid: \"plan-leading-actions\",\n\t\ttaskClass: \"plan\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\"plan\", \"design\", \"architect\", \"decompose\", \"map out\", \"draw up\", \"think through\"],\n\t\tphrases: [\n\t\t\t/^(?:let(?:'|’)s\\s+)?(?:plan|design|architect|decompose|map\\s+out|draw\\s+up|think\\s+through)\\b/i,\n\t\t\t/^(?:write|create)\\s+(?:a\\s+)?(?:technical\\s+)?(?:spec|roadmap|strategy|plan)\\b/i,\n\t\t],\n\t\tnegativeControlIds: [\"design-token-edit\", \"draw-up-implementation-only\"],\n\t},\n\t{\n\t\tid: \"refactor-leading-actions\",\n\t\ttaskClass: \"refactor\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\"refactor\", \"extract\", \"rename\", \"deduplicate\", \"simplify\", \"clean up\", \"untangle\"],\n\t\tphrases: [\n\t\t\t/^(?:refactor(?:ing|ed)?|extract|rename|deduplicate|consolidate|modularize|reorganize|simplify|restructure|untangle)\\b|^clean\\s+up\\b|^split\\s+(?:the\\s+)?module\\b|^move\\s+logic\\b/i,\n\t\t],\n\t\tnegativeControlIds: [\"negated-refactor\", \"future-self-refactor\"],\n\t},\n\t{\n\t\tid: \"simple-edit-leading-actions\",\n\t\ttaskClass: \"simple-edit\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\"correct\", \"update\", \"swap\", \"remove\", \"adjust\", \"fix\", \"add\", \"change\", \"trim\", \"reword\"],\n\t\tphrases: [/^(?:correct|update|swap|remove|adjust|fix|add|change|trim|reword|tweak|bump)\\b/i],\n\t\tnegativeControlIds: [\"add-feature-not-simple-edit\", \"fix-crash-not-simple-edit\"],\n\t},\n\t{\n\t\tid: \"code-gen-leading-actions\",\n\t\ttaskClass: \"code-gen\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\n\t\t\t\"implement\",\n\t\t\t\"write\",\n\t\t\t\"create\",\n\t\t\t\"build\",\n\t\t\t\"generate\",\n\t\t\t\"scaffold\",\n\t\t\t\"prototype\",\n\t\t\t\"add\",\n\t\t\t\"whip up\",\n\t\t\t\"cook me\",\n\t\t],\n\t\tphrases: [/^(?:implement|write|create|build|generate|scaffold|prototype|add|whip\\s+up|cook\\s+me)\\b/i],\n\t\tnegativeControlIds: [\"write-a-plan\", \"create-a-review\"],\n\t},\n\t{\n\t\tid: \"debug-whole-prompt\",\n\t\ttaskClass: \"debug\",\n\t\trole: \"whole-prompt\",\n\t\tsurfaces: [\"debug\", \"investigate why\", \"reproduce\", \"track down\", \"figure out why\", \"get to the bottom\"],\n\t\tphrases: [\n\t\t\t/^(?:debug|investigate\\s+why|reproduce|trace\\b)|\\bfix\\s+this\\s+(?:traceback|panic|error)\\b|\\btrack\\s+down\\b|\\bfigure\\s+out\\s+why\\b|\\bget\\s+to\\s+the\\s+bottom\\b|디버깅|디버그|재현|원인\\s*분석/i,\n\t\t],\n\t\tnegativeControlIds: [\"not-a-bug-report\", \"error-handling-feature\"],\n\t},\n\t{\n\t\tid: \"review-whole-prompt\",\n\t\ttaskClass: \"review\",\n\t\trole: \"whole-prompt\",\n\t\tsurfaces: [\n\t\t\t\"review\",\n\t\t\t\"critique\",\n\t\t\t\"assess\",\n\t\t\t\"inspect\",\n\t\t\t\"once-over\",\n\t\t\t\"look over\",\n\t\t\t\"sanity-check\",\n\t\t\t\"eyeball\",\n\t\t\t\"poke holes\",\n\t\t\t\"pressure-test\",\n\t\t\t\"tell me whether correct\",\n\t\t],\n\t\tphrases: [\n\t\t\t/\\b(review|critique|assess|inspect|approve|lgtm|double-?check|sanity[-\\s]?check|once-?over|look\\s+over|eyeball|poke\\s+holes|pressure[-\\s]?test|sign\\s+off|thumbs[-\\s]?up\\/?down|what\\s+could\\s+go\\s+wrong|what\\s+am\\s+i\\s+missing|challenge\\s+the\\s+assumptions|hidden\\s+coupling|tell\\s+me\\s+(?:if|whether)[^.!?;\\n]{0,80}\\bcorrect|audit(?!\\s+log\\b))\\b|리뷰|검토|점검|괜찮은지\\s*봐\\s*줘|맞는지\\s*봐\\s*줘|처리되는지\\s*확인|허점.{0,10}찾|문제\\s*없는지/i,\n\t\t],\n\t\tnegativeControlIds: [\"review-free-implementation\", \"audit-log\"],\n\t},\n\t{\n\t\tid: \"plan-whole-prompt\",\n\t\ttaskClass: \"plan\",\n\t\trole: \"whole-prompt\",\n\t\tsurfaces: [\"plan\", \"design\", \"architecture\", \"roadmap\", \"map out\", \"draw up\", \"think through\"],\n\t\tphrases: [\n\t\t\t/\\b(plan|design|architect|architecture|roadmap|spec(?:ification)?|strategy|decompose|milestones?|map\\s+out|phases|draw\\s+up|think\\s+through|write\\s+a\\s+(?:technical\\s+)?spec|create\\s+a\\s+(?:roadmap|strategy|plan))\\b|설계|로드맵|아키텍처|계획.{0,6}세워|기획/i,\n\t\t],\n\t\tnegativeControlIds: [\"rather-than-design\", \"design-token-edit\"],\n\t},\n\t{\n\t\tid: \"code-gen-whole-prompt\",\n\t\ttaskClass: \"code-gen\",\n\t\trole: \"whole-prompt\",\n\t\tsurfaces: [\"implement\", \"write\", \"create\", \"build\", \"generate\", \"scaffold\", \"prototype\", \"whip up\", \"cook me\"],\n\t\tphrases: [\n\t\t\t/\\b(implement|write|create|build|generate|scaffold|prototype|whip\\s+up|cook\\s+me)\\b|구현|만들어\\s*줘|생성|작성|추가해/i,\n\t\t],\n\t\tnegativeControlIds: [\"write-plan\", \"create-roadmap\"],\n\t},\n\t{\n\t\tid: \"code-gen-artifact-request\",\n\t\ttaskClass: \"code-gen\",\n\t\trole: \"object-shape\",\n\t\tsurfaces: [\"I need a script\", \"we need a utility\", \"I need an endpoint\", \"we need a test\"],\n\t\tphrases: [\n\t\t\t/\\b(?:i|we)\\s+need\\s+(?:a|an|the|some)?\\s*(?:small\\s+|quick\\s+|new\\s+)?(?:script|utility|helper|component|endpoint|migration|test|tool|function|service)\\b(?!\\s+(?:plan|strategy|review|audit|roadmap|spec))/i,\n\t\t],\n\t\tnegativeControlIds: [\"need-a-plan\", \"need-a-review\", \"need-help-debugging\"],\n\t},\n\t{\n\t\tid: \"evaluative-review-object\",\n\t\ttaskClass: \"review\",\n\t\trole: \"object-shape\",\n\t\tsurfaces: [\"holes\", \"looks off\", \"correct\", \"safe\", \"risky\", \"issues\", \"regressions\"],\n\t\tphrases: [/\\b(holes?|looks?\\s+off|correct|safe|risky|issues?|regressions?)\\b/i],\n\t\tnegativeControlIds: [\"fix-holes\", \"implement-issue-fix\"],\n\t},\n\t{\n\t\tid: \"korean-debug-morphology\",\n\t\ttaskClass: \"debug\",\n\t\trole: \"korean-morphology\",\n\t\tsurfaces: [\n\t\t\t\"오류\",\n\t\t\t\"에러\",\n\t\t\t\"실패\",\n\t\t\t\"원인 찾아줘\",\n\t\t\t\"원인 파악\",\n\t\t\t\"숫자가 이상해\",\n\t\t\t\"합계가 안 맞아\",\n\t\t\t\"빈 파일\",\n\t\t\t\"CI가 빨개\",\n\t\t\t\"디버깅\",\n\t\t],\n\t\tphrases: [\n\t\t\t/오류|에러|실패|안\\s*돼|안\\s*됨|깨졌|깨짐|고장|디버깅|디버그|재현|원인\\s*(?:분석|파악|찾(?:아|기)?|찾아\\s*줘)?|숫자.{0,12}(?:이상|틀려|안\\s*맞)|합계.{0,12}(?:안\\s*맞|틀려|이상)|빈\\s*파일|(?:CI|러너).{0,12}빨개/i,\n\t\t],\n\t\tnegativeControlIds: [\"korean-error-handling-feature\", \"korean-greeting\"],\n\t},\n\t{\n\t\tid: \"korean-simple-edit-morphology\",\n\t\ttaskClass: \"simple-edit\",\n\t\trole: \"korean-morphology\",\n\t\tsurfaces: [\n\t\t\t\"오타\",\n\t\t\t\"맞춤법\",\n\t\t\t\"띄어쓰기\",\n\t\t\t\"문구\",\n\t\t\t\"제목\",\n\t\t\t\"바꿔\",\n\t\t\t\"바꾸\",\n\t\t\t\"수정\",\n\t\t\t\"변경\",\n\t\t\t\"고쳐\",\n\t\t\t\"고치\",\n\t\t\t\"삭제\",\n\t\t\t\"제거\",\n\t\t\t\"옮겨\",\n\t\t\t\"옮기\",\n\t\t],\n\t\tphrases: [\n\t\t\t// Typo/copy nouns plus modification verbs. Creation verbs live in\n\t\t\t// korean-code-gen-morphology; modifying an existing artifact is an edit,\n\t\t\t// not a generation. (016: moved from code-gen after hard-negative mining.)\n\t\t\t/오타|맞춤법|띄어쓰기|문구|제목|바꿔|바꾸|수정|변경|고쳐|고치|삭제|지워|지우|제거|옮겨|옮기|넣어/i,\n\t\t],\n\t\tnegativeControlIds: [\"korean-feature-edit\"],\n\t},\n\t{\n\t\tid: \"korean-review-morphology\",\n\t\ttaskClass: \"review\",\n\t\trole: \"korean-morphology\",\n\t\tsurfaces: [\"리뷰\", \"검토\", \"점검\", \"괜찮은지 봐줘\", \"맞는지 봐줘\", \"허점 찾아줘\"],\n\t\tphrases: [/리뷰|검토|점검|괜찮은지\\s*봐\\s*줘|맞는지\\s*봐\\s*줘|처리되는지\\s*확인|허점.{0,10}찾|문제\\s*없는지/i],\n\t\tnegativeControlIds: [\"korean-review-negated\"],\n\t},\n\t{\n\t\tid: \"korean-plan-morphology\",\n\t\ttaskClass: \"plan\",\n\t\trole: \"korean-morphology\",\n\t\tsurfaces: [\"설계\", \"로드맵\", \"아키텍처\", \"계획 세워\", \"계획 짜\", \"계획 수립\", \"계획 정리\"],\n\t\tphrases: [/설계|로드맵|아키텍처|계획.{0,8}(?:세워|짜|수립|정리)|기획/i],\n\t\tnegativeControlIds: [\"korean-plan-negated\"],\n\t},\n\t{\n\t\tid: \"korean-refactor-morphology\",\n\t\ttaskClass: \"refactor\",\n\t\trole: \"korean-morphology\",\n\t\tsurfaces: [\"리팩토링\", \"리팩터링\", \"구조 개선\"],\n\t\tphrases: [/리팩토링|리팩터링|구조\\s*개선/i],\n\t\tnegativeControlIds: [\"korean-refactor-negated\"],\n\t},\n\t{\n\t\tid: \"korean-code-gen-morphology\",\n\t\ttaskClass: \"code-gen\",\n\t\trole: \"korean-morphology\",\n\t\tsurfaces: [\"구현\", \"만들\", \"생성\", \"작성\", \"추가\", \"테스트\"],\n\t\tphrases: [/구현|만들|생성|작성|추가|테스트/i],\n\t\tnegativeControlIds: [\"korean-greeting\", \"korean-codegen-negated\"],\n\t},\n] as const;\n\nfunction clusterMatchesRoleV4(text: string, taskClass: TaskClassV4, role: IntentLexemeClusterRoleV4): boolean {\n\treturn INTENT_LEXEME_CLUSTERS_V4.some(\n\t\t(cluster) =>\n\t\t\tcluster.taskClass === taskClass &&\n\t\t\tcluster.role === role &&\n\t\t\tcluster.phrases.some((pattern) => pattern.test(text)),\n\t);\n}\n\n// ============================================================================\n// Whole-prompt / leading-clause patterns used by the v4 scorer.\n// ============================================================================\n\nconst LOCAL_EDIT_OBJECT_PATTERN =\n\t/\\b(spelling|grammar|capitalization|date\\s+format|author\\s+e-?mail|copyright\\s+year|headline|title|tooltip|placeholder|punctuation|comma|period|semicolon|closing\\s+html\\s+tag|closing\\s+tag|double\\s+space|whitespace|indentation|table\\s+alignment|typos?|one-?liner?|single\\s+line|sentence|stray|trailing)\\b|오타|맞춤법|띄어쓰기|문구|제목/i;\nconst LOCAL_EDIT_ACTION_OBJECT_PATTERN =\n\t/\\b(update|change|swap|remove|correct|fix|add|adjust|trim)\\s+(?:the\\s+|a\\s+|an\\s+)?(?:missing\\s+|stray\\s+|author\\s+|two\\s+)?(?:e-?mail|comma|period|semicolon|tag|word|words|headline|title|copyright|spelling|grammar)\\b/i;\nconst IMPLEMENTATION_OBJECT_PATTERN =\n\t/\\b(error\\s+handling|input\\s+validation|validation|auth(?:entication)?|retry|endpoint|migration|component|function|utility|helper|module|service|database|schema|column|middleware|rate\\s+limiter|cache|caching|oauth|jwt|webhook)\\b|에러\\s*처리|오류\\s*처리|입력\\s*검증|인증|재시도|엔드포인트|마이그레이션|컴포넌트|함수|유틸|헬퍼|모듈|서비스|데이터베이스|스키마|미들웨어|레이트\\s*리미터|캐시|웹훅|기능/i;\nconst HARD_DIAGNOSTIC_PATTERN =\n\t/\\b(stack\\s*trace|traceback|panic|segfault|crash(?:es|ing|ed)?|throws?|fails?|failing|flaky|hangs?|timeout|500|EADDRINUSE|silently\\s+(?:fails?|produces?|returns?|creates?)|(?:ci|build)\\s+(?:is\\s+)?red|runner\\s+(?:goes|went|is)\\s+red|comes?\\s+out\\s+wrong|totals?\\s+(?:are\\s+)?off|drift(?:ed|ing)?|mismatch(?:ed|es)?|mismatched|no\\s+longer\\s+matches|says\\s+success\\s+but|exits?\\s+0\\s+but|empty\\s+file|opens?\\s+blank|black\\s+image|zero[-\\s]?byte\\s+files?|headers\\s+only|rows?\\s+are\\s+missing|missing\\s+rows|stale\\s+(?:index|prices?|cache|results?)|search\\s+index\\s+(?:is\\s+)?stale|duplicate\\s+rows|NaN|never\\s+(?:send|sends|appear|appears|land|lands|writes?|written|updates?)|works\\s+locally\\s+and\\s+breaks|worked\\s+yesterday|settings\\s+revert|side\\s+effect\\s+never|stops?\\s+updating|data\\s+disappears)\\b|\\b(?:TypeError|ReferenceError|RangeError|Error):|크래시|스택\\s*트레이스|세그폴트|먹통|멈춰|타임아웃|숫자.{0,12}(?:이상|틀려|안\\s*맞)|합계.{0,12}(?:안\\s*맞|틀려|이상)|빈\\s*파일|(?:CI|러너).{0,12}빨개/i;\nconst BUG_OBJECT_PATTERN =\n\t/\\b(null\\s+pointer|null\\s+deref|race(?:\\s+condition)?|heap(?:\\s+overflow)?|use-after-free|memory\\s+leak|leaks?|deadlock|data\\s+corruption|stale\\s+data|off-by-one|encoding\\s+bug|regression\\s+(?:was\\s+)?introduced|exceptions?|assertion\\s+error|bugs?)\\b|버그|예외|메모리\\s*누수|데드락|무한\\s*루프/i;\nconst NON_DIAGNOSTIC_DEBUG_CONTEXT_PATTERN = /\\berror\\s+(?:handling|messages?|budgets?)\\b|에러\\s*처리|오류\\s*처리/i;\nconst GENERIC_DIAGNOSTIC_PATTERN = /\\b(errors?|broken|wrong\\s+results|rolls?\\s+back|rollback)\\b/i;\nconst PLAN_BRIEF_PATTERN =\n\t/\\b(context\\s+and\\s+constraints|starting\\s+state|target\\s+state|cross-cutting|deliver:|deliverables?|roadmap|migration\\s+wave|top\\s+(?:ten\\s+)?risks|component\\s+diagram|data\\s+model|architecture|go\\/no-go|phased\\s+(?:delivery|rollout)|bounded\\s+contexts?|strangler\\s+fig|event-driven|quarter-by-quarter|milestone)\\b/i;\nconst OPERATIONAL_RUNBOOK_SIGNAL_PATTERNS: readonly { pattern: RegExp; critical: boolean }[] = [\n\t{ pattern: /\\b(?:commit|commits|committed|committing)\\b|커밋/i, critical: false },\n\t{ pattern: /\\b(?:push|pushed|pushing)\\b|푸시|푸쉬/i, critical: true },\n\t{\n\t\tpattern: /\\b(?:release|releases|tag|version\\s+bump|bump\\s+(?:the\\s+)?version)\\b|릴리즈|태그|버전/i,\n\t\tcritical: true,\n\t},\n\t{ pattern: /\\bnpm\\s+publish\\b|\\bpublish(?:ing|ed)?\\b|퍼블리시|배포/i, critical: true },\n\t{ pattern: /\\b(?:CHANGELOG\\.md|changelog|release\\s+notes?)\\b|채널로그|체인지로그/i, critical: false },\n\t{ pattern: /\\bREADME\\.md\\b|\\breadme\\b/i, critical: false },\n\t{ pattern: /\\bci\\s*\\/\\s*cd\\b|\\bgithub\\s+actions?\\b|\\bworkflow\\b|깃허브\\s*액션|깃헙\\s*액션/i, critical: false },\n];\nconst EXPLICIT_RELEASE_RUNBOOK_PATTERN =\n\t/\\bnpm\\s+publish\\b|\\brelease\\b[^\\n]{0,80}\\bv?\\d+\\.\\d+\\.\\d+\\b|릴리즈[^\\n]{0,80}\\d+\\.\\d+\\.\\d+/i;\nconst REVIEW_SCOPE_PATTERN =\n\t/\\b(pr|pull\\s+request|diff|codebase|approach|structure|module\\s+boundary|locking\\s+strategy|abstraction|assumptions?|parser\\s+change|rollback\\s+strategy|concurrent\\s+case|concurrency\\s+plan|hidden\\s+coupling|failure\\s+mode|test\\s+quality|implementation\\s+details|strategy|plan|spec|schema|design|api|coverage|security\\s+posture|licensing|risks?|edge\\s+cases|clarity|consistency|dependencies|third-party|ci\\s+pipeline|threat\\s+model|retry\\s+logic|error\\s+handling\\s+strategy|error\\s+messages?)\\b/i;\nconst REFACTOR_CUE_PATTERN =\n\t/\\b(refactor(?:ing|ed)?|extract|rename|deduplicate|consolidate|modularize|reorganize|simplify|clean\\s*up|tidy\\s+up|restructure|split\\s+module|move\\s+logic|untangle|merge\\s+duplicate)\\b|리팩토링(?!하지\\s*마|하지\\s*말)|리팩터링(?!하지\\s*마|하지\\s*말)|구조\\s*개선/i;\nconst ADD_KEYWORD_PATTERN = /\\badd\\b/i;\nconst LOW_RISK_EDIT_ACTION_PATTERN = /^(?:correct|update|swap|remove|reword|tweak|bump|trim)\\b/i;\n\n/** Short-range compound-clause conjunction boundary. Only bare/compound \"then\"/\"and also\"/\";\" — never bare \"and\". */\nconst COMPOUND_SPLIT_PATTERN = /\\band\\s+then\\b|\\bthen\\b|\\band\\s+also\\b|;/i;\n\n/**\n * Bounded negation-cue vocabulary (spec 008 plan.md \"bounded negation window\").\n * Deliberately excludes bare \"not\" (too broad; verified against the current\n * GOLD_SET that every listed cue here is either absent or occurs AFTER, not\n * before, a tracked keyword — see this lane's evidence file for the audit).\n */\nconst NEGATION_CUE_PATTERN =\n\t/\\b(?:don't|do\\s+not|doesn't|does\\s+not|didn't|did\\s+not|won't|will\\s+not|shouldn't|should\\s+not|wouldn't|would\\s+not|can't|cannot|isn't|is\\s+not|aren't|are\\s+not|never|avoid|skip|without|instead\\s+of|rather\\s+than|no\\s+need\\s+(?:to|for)|no\\s+longer\\s+need(?:\\s+(?:to|for))?)\\b/i;\nconst DIRECT_NOT_OBJECT_CUE_PATTERN_V4 = /\\b(?:not|no)\\s+(?:a\\s+|an\\s+|the\\s+)?$/i;\nconst DOUBLE_NEGATION_RESCUE_PATTERN_V4 =\n\t/\\b(?:don't|do\\s+not|doesn't|does\\s+not|didn't|did\\s+not|won't|will\\s+not|shouldn't|should\\s+not|wouldn't|would\\s+not|can't|cannot)\\s+(?:skip|avoid)\\s+(?:the\\s+|a\\s+|an\\s+)?$/i;\nconst DELIBERATIVE_QUESTION_RESCUE_PATTERN_V4 =\n\t/\\b(?:shouldn't|should\\s+not|wouldn't|would\\s+not|can't|cannot)\\s+(?:we|i|you)\\s*$/i;\nconst POSTPOSITIONED_NEGATION_CUE_PATTERN_V4 =\n\t/^\\s*(?:-\\s*free\\b|(?:is|are|was|were)?\\s*(?:not\\s+(?:needed|required|desired)|unnecessary|not\\s+necessary)|(?:[은는이가을를도만]\\s*)?(?:하지\\s*(?:마(?:라|세요|십시오)?|말(?:고|아|라)?|않(?:아|는|고|을|게)?)|말고|금지))/i;\n\n/** A closed set of clause-boundary characters; a negation cue never reaches across one of these into a prior clause. */\nconst CLAUSE_BOUNDARY_CHARS = [\".\", \"!\", \"?\", \";\", \",\"] as const;\n\nfunction hasCodeFence(text: string): boolean {\n\treturn text.includes(\"```\");\n}\n\n/** Explicit hunk headers or `diff --git` count alone; bare +/- only count together. */\nfunction hasDiffMarkers(text: string): boolean {\n\tif (/^@@[^\\n]*@@/m.test(text) || /^diff --git /m.test(text)) return true;\n\treturn /^\\+(?!\\+)/m.test(text) && /^-(?!-)/m.test(text);\n}\n\nexport interface RouterFeedbackFeaturesV4 {\n\treadonly lenBucket: RouterFeedbackLenBucket;\n\treadonly hadFence: boolean;\n\treadonly hadDiff: boolean;\n}\n\n/** Derive the exact bounded feature tuple used by both classification and learning. */\nexport function deriveRouterFeedbackFeaturesV4(promptText: string): RouterFeedbackFeaturesV4 {\n\tconst prompt = promptText.trim();\n\tlet lenBucket = 0;\n\tlet remaining = prompt.length + 1;\n\twhile (remaining > 1 && lenBucket < 7) {\n\t\tremaining >>= 1;\n\t\tlenBucket++;\n\t}\n\treturn {\n\t\tlenBucket: lenBucket as RouterFeedbackLenBucket,\n\t\thadFence: hasCodeFence(prompt),\n\t\thadDiff: hasDiffMarkers(prompt),\n\t};\n}\n\n/** First line (after stripping one polite prefix), capped at 180 chars. */\n// Non-imperative preamble shapes stripped before ^-anchored intent tests\n// (goal 016/M3+M5): quoted-speech attribution (my teammate said \"...\" but\n// actually: ...) and labeled filler lines (background:/context:/note:).\n// Bounded to 3 repetitions so a wall of filler cannot loop the classifier.\nconst QUOTED_SPEECH_PREFIX_V4 = /^.{0,60}?\\bsaid\\s+\"[^\"]*\"[,.]?\\s*(?:but\\s+actually[,:]?\\s*)?/i;\nconst LABELED_FILLER_PREFIX_V4 = /^(?:background|context|note)\\s*:[^.!?\\n]*[.!?]?\\s*/i;\n\nfunction stripNonImperativePrefixV4(text: string): string {\n\tlet result = text;\n\tfor (let i = 0; i < 3; i++) {\n\t\tconst stripped = result.replace(QUOTED_SPEECH_PREFIX_V4, \"\").replace(LABELED_FILLER_PREFIX_V4, \"\");\n\t\tif (stripped === result) break;\n\t\tresult = stripped;\n\t}\n\treturn result;\n}\n\nfunction firstClause(prompt: string): string {\n\tconst firstLine =\n\t\tstripNonImperativePrefixV4(\n\t\t\tprompt.replace(/^(?:please|pls|can you|could you|would you|help me|i need you to)\\s+/i, \"\"),\n\t\t).split(\"\\n\")[0] ?? \"\";\n\treturn firstLine.slice(0, 180);\n}\n\n// --- Leading-clause intent tests. All are `^`-anchored against the LEADING\n// clause text only, so a negation cue at the start (\"don't refactor...\") can\n// never match one of these: none of the alternations include \"don't\"/\"never\"/\n// etc, so they are negation-immune by construction.\n\nfunction hasLeadingReviewIntent(text: string): boolean {\n\treturn clusterMatchesRoleV4(text, \"review\", \"leading-intent\");\n}\n\nfunction hasLeadingPlanIntent(text: string): boolean {\n\treturn clusterMatchesRoleV4(text, \"plan\", \"leading-intent\");\n}\n\nfunction hasLeadingRefactorIntent(text: string): boolean {\n\treturn clusterMatchesRoleV4(text, \"refactor\", \"leading-intent\");\n}\n\nfunction hasLeadingDebugAction(text: string): boolean {\n\treturn clusterMatchesRoleV4(text, \"debug\", \"leading-intent\");\n}\n\nfunction hasLeadingCodeGenIntent(text: string): boolean {\n\treturn clusterMatchesRoleV4(text, \"code-gen\", \"leading-intent\");\n}\n\nfunction hasLeadingSimpleEditIntent(text: string): boolean {\n\treturn clusterMatchesRoleV4(text, \"simple-edit\", \"leading-intent\");\n}\n\n// --- Quoted-speech masking (goal 016/M3) ---------------------------------\n// A double-quoted span that itself reads as an imperative (\"my teammate said\n// 'implement it'\") is reported speech, not the requester's intent: mask it so\n// it cannot fire whole-prompt evidence. Quoted nouns/objects are preserved\n// (\"fix the 'undefined' error\" keeps its debug signal).\n\nconst QUOTED_SPAN_PATTERN_V4 = /\"([^\"\\n]{1,80})\"/g;\n\nfunction quotedSpanIsImperativeV4(span: string): boolean {\n\tconst text = span.trim();\n\treturn (\n\t\thasLeadingDebugAction(text) ||\n\t\thasLeadingReviewIntent(text) ||\n\t\thasLeadingPlanIntent(text) ||\n\t\thasLeadingRefactorIntent(text) ||\n\t\thasLeadingCodeGenIntent(text) ||\n\t\thasLeadingSimpleEditIntent(text)\n\t);\n}\n\nfunction maskQuotedImperativesV4(text: string): string {\n\treturn text.replace(QUOTED_SPAN_PATTERN_V4, (whole: string, inner: string) =>\n\t\tquotedSpanIsImperativeV4(inner) ? \" \".repeat(whole.length) : whole,\n\t);\n}\n\n// ============================================================================\n// Bounded negation gating\n// ============================================================================\n\ninterface UnnegatedMatchResultV4 {\n\t/** True when the pattern matched at least once and at least one occurrence was NOT preceded by a negation cue. */\n\treadonly matched: boolean;\n\t/** True when the pattern matched at least once but EVERY occurrence was negated (useful for suppressedFeatureIds). */\n\treadonly suppressed: boolean;\n}\n\nconst NO_MATCH_RESULT_V4: UnnegatedMatchResultV4 = { matched: false, suppressed: false };\n\nfunction matchOperationalRunbookV4(prompt: string, windowChars: number): UnnegatedMatchResultV4 {\n\tlet distinctSignals = 0;\n\tlet criticalSignals = 0;\n\tlet sawSuppressed = false;\n\tfor (const { pattern, critical } of OPERATIONAL_RUNBOOK_SIGNAL_PATTERNS) {\n\t\tconst result = matchUnnegated(prompt, pattern, windowChars);\n\t\tif (result.matched) {\n\t\t\tdistinctSignals += 1;\n\t\t\tif (critical) criticalSignals += 1;\n\t\t}\n\t\tif (result.suppressed) sawSuppressed = true;\n\t}\n\tconst explicitRelease = matchUnnegated(prompt, EXPLICIT_RELEASE_RUNBOOK_PATTERN, windowChars).matched;\n\tconst matched = explicitRelease || distinctSignals >= 3 || (criticalSignals >= 2 && distinctSignals >= 2);\n\treturn { matched, suppressed: !matched && sawSuppressed };\n}\n\n/**\n * Negation-aware whole-prompt pattern scan. Finds every occurrence of `pattern`\n * in `prompt`; for each, looks back up to\n * `windowChars` characters (never crossing a `.,;!?` boundary into a prior\n * clause) for a `NEGATION_CUE_PATTERN` hit, and looks forward inside the same\n * bounded window for Hangul-only post-positioned negation cues such as\n * \"하지 말고\". `matched` is true iff at least one occurrence survives\n * un-negated. Deterministic, single pass per pattern, no shared regex state (a\n * fresh global-flag RegExp is constructed per call).\n */\nfunction hasPrePositionedNegationCueV4(scoped: string): boolean {\n\tif (!NEGATION_CUE_PATTERN.test(scoped) && !DIRECT_NOT_OBJECT_CUE_PATTERN_V4.test(scoped)) return false;\n\treturn !DOUBLE_NEGATION_RESCUE_PATTERN_V4.test(scoped) && !DELIBERATIVE_QUESTION_RESCUE_PATTERN_V4.test(scoped);\n}\n\nfunction hasPostPositionedNegationCueV4(prompt: string, matchEnd: number, windowChars: number): boolean {\n\tconst scoped = prompt.slice(matchEnd, Math.min(prompt.length, matchEnd + windowChars));\n\treturn POSTPOSITIONED_NEGATION_CUE_PATTERN_V4.test(scoped);\n}\n\nfunction matchUnnegated(prompt: string, pattern: RegExp, windowChars: number): UnnegatedMatchResultV4 {\n\tconst flags = pattern.flags.includes(\"g\") ? pattern.flags : `${pattern.flags}g`;\n\tconst globalPattern = new RegExp(pattern.source, flags);\n\tlet sawMatch = false;\n\tlet sawUnnegated = false;\n\tlet match = globalPattern.exec(prompt);\n\twhile (match !== null) {\n\t\tsawMatch = true;\n\t\tconst matchStart = match.index;\n\t\tconst windowStart = Math.max(0, matchStart - windowChars);\n\t\tconst windowText = prompt.slice(windowStart, matchStart);\n\t\tlet boundary = -1;\n\t\tfor (const boundaryChar of CLAUSE_BOUNDARY_CHARS) {\n\t\t\tconst idx = windowText.lastIndexOf(boundaryChar);\n\t\t\tif (idx > boundary) boundary = idx;\n\t\t}\n\t\tconst scoped = boundary >= 0 ? windowText.slice(boundary + 1) : windowText;\n\t\tconst preNegated = hasPrePositionedNegationCueV4(scoped);\n\t\tconst postNegated =\n\t\t\t!preNegated && hasPostPositionedNegationCueV4(prompt, matchStart + match[0].length, windowChars);\n\t\tif (!preNegated && !postNegated) sawUnnegated = true;\n\t\tif (match[0].length === 0) globalPattern.lastIndex += 1;\n\t\tmatch = globalPattern.exec(prompt);\n\t}\n\treturn { matched: sawUnnegated, suppressed: sawMatch && !sawUnnegated };\n}\n\nfunction matchClusterUnnegatedV4(\n\tprompt: string,\n\ttaskClass: TaskClassV4,\n\trole: IntentLexemeClusterRoleV4,\n\twindowChars: number,\n): UnnegatedMatchResultV4 {\n\tlet sawSuppressed = false;\n\tfor (const cluster of INTENT_LEXEME_CLUSTERS_V4) {\n\t\tif (cluster.taskClass !== taskClass || cluster.role !== role) continue;\n\t\tfor (const pattern of cluster.phrases) {\n\t\t\tconst result = matchUnnegated(prompt, pattern, windowChars);\n\t\t\tif (result.matched) return { matched: true, suppressed: false };\n\t\t\tif (result.suppressed) sawSuppressed = true;\n\t\t}\n\t}\n\treturn { matched: false, suppressed: sawSuppressed };\n}\n\n// ============================================================================\n// Bounded compound-intent detection\n// ============================================================================\n\ninterface CompoundSecondClauseV4 {\n\treadonly text: string;\n\treadonly startIndex: number;\n}\n\n/**\n * Splits off a bounded second clause after a short-range conjunction\n * (\"then\"/\"and then\"/\"and also\"/\";\"), only when the split point is within the\n * first `COMPOUND_SPLIT_MAX_INDEX_V4` characters (short direct commands, not\n * long prose briefs — verified this never fires inside the GOLD_SET's\n * >=2400-char plan entries). Returns null when no qualifying split exists.\n */\nfunction splitCompoundClauseV4(prompt: string): CompoundSecondClauseV4 | null {\n\tconst match = COMPOUND_SPLIT_PATTERN.exec(prompt);\n\tif (match === null || match.index > COMPOUND_SPLIT_MAX_INDEX_V4) return null;\n\tconst startIndex = match.index + match[0].length;\n\tconst second = prompt.slice(startIndex).trim();\n\tif (second.length < COMPOUND_SECOND_CLAUSE_MIN_CHARS_V4) return null;\n\treturn { text: second, startIndex };\n}\n\nfunction hasFutureSelfClauseV4(clause: string): boolean {\n\treturn /^(?:(?:i|we)(?:'|’)ll\\b|(?:i|we)\\s+will\\b|(?:i|we)(?:'|’)m\\s+going\\s+to\\b|before\\s+(?:i|we)\\b|after\\s+(?:i|we)\\b)/i.test(\n\t\tclause,\n\t);\n}\n\nfunction agentDirectedSecondClauseV4(clause: string): string | null {\n\tif (hasFutureSelfClauseV4(clause)) return null;\n\treturn clause.replace(/^(?:please|pls|also|then|can\\s+you|could\\s+you|would\\s+you|help\\s+me(?:\\s+to)?)\\s+/i, \"\");\n}\n\n/**\n * Leading-intent test for a compound prompt's SECOND clause. Reuses the same\n * `^`-anchored leading-intent tests as the primary clause (so it is equally\n * negation-immune), without the primary clause's diagnosticEvidence/localEdit\n * gating (a short second-clause fragment carries no such context of its own).\n * First-person future/context clauses (\"I'll...\", \"we will...\", \"before I...\")\n * are user context, not an agent-directed second task.\n */\nfunction secondClauseLeadingIntentV4(clause: string): TaskClassV4 | null {\n\tconst agentDirectedClause = agentDirectedSecondClauseV4(clause);\n\tif (agentDirectedClause === null) return null;\n\tconst bounded = agentDirectedClause.slice(0, COMPOUND_SECOND_CLAUSE_SCAN_CHARS_V4);\n\treturn leadingIntentFromLeadingClauseV4(bounded);\n}\n\nfunction leadingIntentFromLeadingClauseV4(leading: string): TaskClassV4 | null {\n\tif (hasLeadingDebugAction(leading)) return \"debug\";\n\tif (hasLeadingReviewIntent(leading)) return \"review\";\n\tif (hasLeadingPlanIntent(leading)) return \"plan\";\n\tif (hasLeadingRefactorIntent(leading)) return \"refactor\";\n\tif (hasLeadingSimpleEditIntent(leading)) return \"simple-edit\";\n\tif (hasLeadingCodeGenIntent(leading)) return \"code-gen\";\n\treturn null;\n}\n\nfunction leadingIntentIsPostNegatedV4(leading: string, windowChars: number): boolean {\n\tconst leadingIntentMatch =\n\t\t/^(?:debug|investigate\\s+why|reproduce|trace\\b|fix\\s+this\\s+(?:traceback|panic|error)|review|audit(?!\\s+log\\b)|critique|inspect|assess|approve|double-?check|lgtm|plan|design|architect|decompose|write\\s+(?:a\\s+)?(?:technical\\s+)?(?:spec|roadmap|strategy|plan)|create\\s+(?:a\\s+)?(?:technical\\s+)?(?:spec|roadmap|strategy|plan)|refactor(?:ing|ed)?|extract|rename|deduplicate|consolidate|modularize|reorganize|simplify|restructure|untangle|clean\\s+up|split\\s+(?:the\\s+)?module|move\\s+logic|correct|update|swap|remove|adjust|fix|add|change|trim|reword|tweak|bump|implement|build|generate|scaffold|prototype)\\b/i.exec(\n\t\t\tleading,\n\t\t);\n\treturn (\n\t\tleadingIntentMatch !== null && hasPostPositionedNegationCueV4(leading, leadingIntentMatch[0].length, windowChars)\n\t);\n}\n\nfunction classifyShortKoreanZeroScoreTaskV4(prompt: string, windowChars: number): TaskClassV4 | null {\n\tconst generalizedEvidence = extractGeneralizedIntentEvidenceV4(prompt);\n\tfor (const taskClass of TASK_CLASSES_V4) {\n\t\tif (generalizedEvidence.skeletonMatch[taskClass]) return taskClass;\n\t}\n\tif (matchClusterUnnegatedV4(prompt, \"debug\", \"korean-morphology\", windowChars).matched) return \"debug\";\n\tif (matchClusterUnnegatedV4(prompt, \"simple-edit\", \"korean-morphology\", windowChars).matched) return \"simple-edit\";\n\tif (matchClusterUnnegatedV4(prompt, \"review\", \"korean-morphology\", windowChars).matched) return \"review\";\n\tif (matchClusterUnnegatedV4(prompt, \"plan\", \"korean-morphology\", windowChars).matched) return \"plan\";\n\tif (matchClusterUnnegatedV4(prompt, \"refactor\", \"korean-morphology\", windowChars).matched) return \"refactor\";\n\tif (matchClusterUnnegatedV4(prompt, \"code-gen\", \"korean-morphology\", windowChars).matched) return \"code-gen\";\n\tfor (const taskClass of TASK_CLASSES_V4) {\n\t\tif (generalizedEvidence.clusterMatch[taskClass]) return taskClass;\n\t}\n\treturn null;\n}\n\n// ============================================================================\n// Feature extraction\n// ============================================================================\n\ninterface ContextualFeaturesV4 {\n\treadonly firstClause: string;\n\treadonly codeFence: boolean;\n\treadonly diffHunk: boolean;\n\treadonly localEdit: boolean;\n\treadonly diagnosticEvidence: boolean;\n\treadonly reviewScope: boolean;\n\treadonly planBrief: boolean;\n\treadonly operationalRunbook: boolean;\n\treadonly refactorCue: boolean;\n\treadonly implementationObject: boolean;\n\treadonly codeGenArtifactRequest: boolean;\n\treadonly evaluativeReviewObject: boolean;\n\treadonly leadingIntent: TaskClassV4 | null;\n\treadonly secondClauseIntent: TaskClassV4 | null;\n\treadonly compoundIntent: boolean;\n\treadonly keywordFamilyMatch: Readonly<Record<TaskClassV4, boolean>>;\n\treadonly normalizedIntentClusterMatch: Readonly<Record<TaskClassV4, boolean>>;\n\treadonly intentSkeletonMatch: Readonly<Record<TaskClassV4, boolean>>;\n\treadonly generalizedEvidenceCount: Readonly<Record<TaskClassV4, number>>;\n\treadonly addKeywordMatch: boolean;\n}\n\ninterface LeadingIntentInputV4 {\n\treadonly firstClause: string;\n\treadonly localEdit: boolean;\n\treadonly diagnosticEvidence: boolean;\n}\n\n/** Decision order for the leading intent classifier. */\nfunction leadingIntentV4(input: LeadingIntentInputV4): TaskClassV4 | null {\n\tif (\n\t\tinput.diagnosticEvidence &&\n\t\t(hasLeadingDebugAction(input.firstClause) || hasLeadingSimpleEditIntent(input.firstClause))\n\t)\n\t\treturn \"debug\";\n\tif (hasLeadingReviewIntent(input.firstClause)) return \"review\";\n\tif (hasLeadingPlanIntent(input.firstClause)) return \"plan\";\n\tif (hasLeadingRefactorIntent(input.firstClause)) return \"refactor\";\n\tif (input.localEdit && hasLeadingSimpleEditIntent(input.firstClause)) return \"simple-edit\";\n\tif (!input.localEdit && hasLeadingCodeGenIntent(input.firstClause)) return \"code-gen\";\n\treturn null;\n}\n\n/** Diagnostic-evidence decision structure, parameterized over precomputed negation-aware matches. */\nfunction hasDiagnosticEvidenceV4(\n\tleading: string,\n\thardDiagnosticMatched: boolean,\n\tbugObjectMatched: boolean,\n\tgenericDiagnosticMatched: boolean,\n\tnonDiagnosticContext: boolean,\n): boolean {\n\tif (hasLeadingDebugAction(leading) || hardDiagnosticMatched) return true;\n\tconst hasContextualDiagnostic = bugObjectMatched || (genericDiagnosticMatched && !nonDiagnosticContext);\n\tif (!hasContextualDiagnostic) return false;\n\treturn !hasLeadingReviewIntent(leading) && !hasLeadingPlanIntent(leading) && !hasLeadingRefactorIntent(leading);\n}\n\ntype GeneralizedIntentEvidenceV4 = ReturnType<typeof extractGeneralizedIntentEvidenceV4>;\n\nfunction isDeferredClassV4(evidence: GeneralizedIntentEvidenceV4, taskClass: TaskClassV4): boolean {\n\treturn evidence.deferredClasses.includes(taskClass);\n}\n\nfunction suppressGeneralizedClassesV4(\n\tevidence: GeneralizedIntentEvidenceV4,\n\tsuppressedClasses: readonly TaskClassV4[],\n): GeneralizedIntentEvidenceV4 {\n\tif (suppressedClasses.length === 0) return evidence;\n\tconst clusterMatch = { ...evidence.clusterMatch };\n\tconst skeletonMatch = { ...evidence.skeletonMatch };\n\tfor (const taskClass of suppressedClasses) {\n\t\tclusterMatch[taskClass] = false;\n\t\tskeletonMatch[taskClass] = false;\n\t}\n\treturn { ...evidence, clusterMatch, skeletonMatch };\n}\n\nfunction countGeneralizedEvidenceV4(evidence: GeneralizedIntentEvidenceV4): Record<TaskClassV4, number> {\n\tconst counts = emptyScoresV4();\n\tfor (const taskClass of TASK_CLASSES_V4) {\n\t\tcounts[taskClass] = (evidence.clusterMatch[taskClass] ? 1 : 0) + (evidence.skeletonMatch[taskClass] ? 1 : 0);\n\t}\n\treturn counts;\n}\n\n/**\n * Extracts every v4 feature from one prompt, negation-gating every\n * whole-prompt scan exactly once and recording a `negation:<channel>` id in\n * `suppressed` whenever a match existed but every occurrence was negated.\n */\nfunction extractFeaturesV4(\n\tprompt: string,\n\tweights: RouterWeightsV4,\n\tsuppressed: string[],\n\tfeedbackFeatures: RouterFeedbackFeaturesV4 = deriveRouterFeedbackFeaturesV4(prompt),\n): ContextualFeaturesV4 {\n\tconst leading = firstClause(prompt);\n\tconst window = weights.negationWindowChars;\n\tconst secondClause = splitCompoundClauseV4(prompt);\n\tconst agentSignalPrompt = maskQuotedImperativesV4(\n\t\tsecondClause !== null && hasFutureSelfClauseV4(secondClause.text)\n\t\t\t? prompt.slice(0, secondClause.startIndex).trim()\n\t\t\t: prompt,\n\t);\n\tconst generalizedEvidence = extractGeneralizedIntentEvidenceV4(agentSignalPrompt);\n\tconst shortKoreanPrompt = prompt.length < TRIVIAL_MAX_CHARS_V4 && /[가-힣]/.test(prompt);\n\tconst shortKoreanDebugFallbackOnly =\n\t\tshortKoreanPrompt &&\n\t\t(generalizedEvidence.clusterMatch.debug || generalizedEvidence.skeletonMatch.debug) &&\n\t\t!generalizedEvidence.clusterMatch.refactor &&\n\t\t!generalizedEvidence.skeletonMatch.refactor &&\n\t\t!generalizedEvidence.clusterMatch.review &&\n\t\t!generalizedEvidence.skeletonMatch.review;\n\tconst scoredGeneralizedEvidence = suppressGeneralizedClassesV4(\n\t\tgeneralizedEvidence,\n\t\tshortKoreanDebugFallbackOnly\n\t\t\t? [...generalizedEvidence.deferredClasses, \"debug\"]\n\t\t\t: generalizedEvidence.deferredClasses,\n\t);\n\tfor (const taskClass of generalizedEvidence.deferredClasses) suppressed.push(`deferral:${taskClass}`);\n\n\tconst implementationObjectResult = matchUnnegated(agentSignalPrompt, IMPLEMENTATION_OBJECT_PATTERN, window);\n\tif (implementationObjectResult.suppressed) suppressed.push(\"negation:implementation-object\");\n\tconst implementationObject = !shortKoreanDebugFallbackOnly && implementationObjectResult.matched;\n\n\tconst codeGenArtifactResult = matchClusterUnnegatedV4(agentSignalPrompt, \"code-gen\", \"object-shape\", window);\n\tif (codeGenArtifactResult.suppressed) suppressed.push(\"negation:code-gen-artifact-request\");\n\tconst codeGenArtifactRequest = codeGenArtifactResult.matched;\n\n\tconst lowRiskEditAction = LOW_RISK_EDIT_ACTION_PATTERN.test(leading);\n\tconst localEditObjectResult = matchUnnegated(agentSignalPrompt, LOCAL_EDIT_OBJECT_PATTERN, window);\n\tif (localEditObjectResult.suppressed) suppressed.push(\"negation:local-edit-object\");\n\tconst localEditActionResult = matchUnnegated(agentSignalPrompt, LOCAL_EDIT_ACTION_OBJECT_PATTERN, window);\n\tif (localEditActionResult.suppressed) suppressed.push(\"negation:local-edit-action-object\");\n\tconst localEdit =\n\t\t!implementationObject &&\n\t\t!scoredGeneralizedEvidence.clusterMatch.review &&\n\t\t!scoredGeneralizedEvidence.skeletonMatch.review &&\n\t\t(lowRiskEditAction || localEditObjectResult.matched || localEditActionResult.matched);\n\n\tconst hardDiagnosticResult = matchUnnegated(agentSignalPrompt, HARD_DIAGNOSTIC_PATTERN, window);\n\tif (hardDiagnosticResult.suppressed) suppressed.push(\"negation:hard-diagnostic\");\n\tconst bugObjectResult = matchUnnegated(agentSignalPrompt, BUG_OBJECT_PATTERN, window);\n\tif (bugObjectResult.suppressed) suppressed.push(\"negation:bug-object\");\n\tconst genericDiagnosticResult = matchUnnegated(agentSignalPrompt, GENERIC_DIAGNOSTIC_PATTERN, window);\n\tconst nonDiagnosticContext = NON_DIAGNOSTIC_DEBUG_CONTEXT_PATTERN.test(agentSignalPrompt);\n\tif (genericDiagnosticResult.suppressed && !nonDiagnosticContext) suppressed.push(\"negation:generic-diagnostic\");\n\tconst diagnosticEvidence =\n\t\t!isDeferredClassV4(generalizedEvidence, \"debug\") &&\n\t\thasDiagnosticEvidenceV4(\n\t\t\tleading,\n\t\t\thardDiagnosticResult.matched,\n\t\t\tbugObjectResult.matched,\n\t\t\tgenericDiagnosticResult.matched,\n\t\t\tnonDiagnosticContext,\n\t\t);\n\n\tconst reviewScopeResult = matchUnnegated(agentSignalPrompt, REVIEW_SCOPE_PATTERN, window);\n\tif (reviewScopeResult.suppressed) suppressed.push(\"negation:review-scope\");\n\tconst reviewScope =\n\t\t!isDeferredClassV4(generalizedEvidence, \"review\") && hasLeadingReviewIntent(leading) && reviewScopeResult.matched;\n\n\tconst planBriefResult = matchUnnegated(agentSignalPrompt, PLAN_BRIEF_PATTERN, window);\n\tif (planBriefResult.suppressed) suppressed.push(\"negation:plan-brief\");\n\tconst planBrief =\n\t\t!isDeferredClassV4(generalizedEvidence, \"plan\") &&\n\t\thasLeadingPlanIntent(leading) &&\n\t\t(planBriefResult.matched || prompt.length >= LONG_BRIEF_MIN_CHARS_V4);\n\n\tconst operationalRunbookResult = matchOperationalRunbookV4(agentSignalPrompt, window);\n\tif (operationalRunbookResult.suppressed) suppressed.push(\"negation:operational-runbook\");\n\tconst operationalRunbook = operationalRunbookResult.matched;\n\n\tconst refactorCueResult = matchUnnegated(agentSignalPrompt, REFACTOR_CUE_PATTERN, window);\n\tif (refactorCueResult.suppressed) suppressed.push(\"negation:refactor-cue\");\n\tconst refactorCue = !isDeferredClassV4(generalizedEvidence, \"refactor\") && refactorCueResult.matched;\n\n\tconst rawPrimaryIntent = leadingIntentV4({ firstClause: leading, localEdit, diagnosticEvidence });\n\tconst primaryIntent =\n\t\trawPrimaryIntent !== null &&\n\t\t(leadingIntentIsPostNegatedV4(leading, window) || isDeferredClassV4(generalizedEvidence, rawPrimaryIntent))\n\t\t\t? null\n\t\t\t: rawPrimaryIntent;\n\n\tconst secondClauseIntent = secondClause === null ? null : secondClauseLeadingIntentV4(secondClause.text);\n\tconst compoundIntent = secondClauseIntent !== null && secondClauseIntent !== primaryIntent;\n\n\tconst debugKeywordResult = diagnosticEvidence\n\t\t? matchClusterUnnegatedV4(agentSignalPrompt, \"debug\", \"whole-prompt\", window)\n\t\t: NO_MATCH_RESULT_V4;\n\tif (debugKeywordResult.suppressed) suppressed.push(\"negation:keyword-debug\");\n\n\tconst reviewKeywordResult = isDeferredClassV4(generalizedEvidence, \"review\")\n\t\t? NO_MATCH_RESULT_V4\n\t\t: matchClusterUnnegatedV4(agentSignalPrompt, \"review\", \"whole-prompt\", window);\n\tif (reviewKeywordResult.suppressed) suppressed.push(\"negation:keyword-review\");\n\n\tconst planKeywordResult = isDeferredClassV4(generalizedEvidence, \"plan\")\n\t\t? NO_MATCH_RESULT_V4\n\t\t: matchClusterUnnegatedV4(agentSignalPrompt, \"plan\", \"whole-prompt\", window);\n\tif (planKeywordResult.suppressed) suppressed.push(\"negation:keyword-plan\");\n\n\tconst codeGenKeywordResult = matchClusterUnnegatedV4(agentSignalPrompt, \"code-gen\", \"whole-prompt\", window);\n\tif (codeGenKeywordResult.suppressed) suppressed.push(\"negation:keyword-code-gen\");\n\n\tconst evaluativeReviewResult =\n\t\t!isDeferredClassV4(generalizedEvidence, \"review\") && hasLeadingReviewIntent(leading)\n\t\t\t? matchClusterUnnegatedV4(agentSignalPrompt, \"review\", \"object-shape\", window)\n\t\t\t: NO_MATCH_RESULT_V4;\n\tif (evaluativeReviewResult.suppressed) suppressed.push(\"negation:evaluative-review-object\");\n\tconst evaluativeReviewObject = evaluativeReviewResult.matched;\n\n\tconst addKeywordResult = localEdit\n\t\t? NO_MATCH_RESULT_V4\n\t\t: matchUnnegated(agentSignalPrompt, ADD_KEYWORD_PATTERN, window);\n\tif (addKeywordResult.suppressed) suppressed.push(\"negation:add-keyword\");\n\n\treturn {\n\t\tfirstClause: leading,\n\t\tcodeFence: feedbackFeatures.hadFence,\n\t\tdiffHunk: feedbackFeatures.hadDiff,\n\t\tlocalEdit,\n\t\tdiagnosticEvidence,\n\t\treviewScope,\n\t\tplanBrief,\n\t\toperationalRunbook,\n\t\trefactorCue,\n\t\timplementationObject,\n\t\tcodeGenArtifactRequest,\n\t\tevaluativeReviewObject,\n\t\tleadingIntent: primaryIntent,\n\t\tsecondClauseIntent,\n\t\tcompoundIntent,\n\t\tkeywordFamilyMatch: {\n\t\t\ttrivial: false,\n\t\t\tdebug: debugKeywordResult.matched,\n\t\t\trefactor: refactorCue,\n\t\t\treview: reviewKeywordResult.matched,\n\t\t\tplan: planKeywordResult.matched,\n\t\t\t\"simple-edit\": localEditObjectResult.matched,\n\t\t\t\"code-gen\": codeGenKeywordResult.matched,\n\t\t},\n\t\tnormalizedIntentClusterMatch: scoredGeneralizedEvidence.clusterMatch,\n\t\tintentSkeletonMatch: scoredGeneralizedEvidence.skeletonMatch,\n\t\tgeneralizedEvidenceCount: countGeneralizedEvidenceV4(scoredGeneralizedEvidence),\n\t\taddKeywordMatch: addKeywordResult.matched,\n\t};\n}\n\n// ============================================================================\n// Scoring\n// ============================================================================\n\nfunction emptyScoresV4(): Record<TaskClassV4, number> {\n\treturn {\n\t\ttrivial: 0,\n\t\t\"simple-edit\": 0,\n\t\t\"code-gen\": 0,\n\t\tdebug: 0,\n\t\trefactor: 0,\n\t\treview: 0,\n\t\tplan: 0,\n\t};\n}\n\nfunction computeScoresV4(features: ContextualFeaturesV4, weights: RouterWeightsV4): Record<TaskClassV4, number> {\n\tconst scores = emptyScoresV4();\n\tif (features.codeFence || features.diffHunk) scores[\"code-gen\"] += weights.codeFenceOrDiff;\n\tif (features.leadingIntent !== null) scores[features.leadingIntent] += weights.leadingIntent;\n\tif (features.secondClauseIntent !== null) scores[features.secondClauseIntent] += weights.secondClauseIntent;\n\tif (features.localEdit) scores[\"simple-edit\"] += weights.localEdit;\n\tif (features.diagnosticEvidence) scores.debug += weights.diagnosticEvidence;\n\tif (features.reviewScope) scores.review += weights.reviewScope;\n\tif (features.planBrief) scores.plan += weights.planBrief;\n\tif (features.operationalRunbook) scores.plan += weights.operationalRunbook;\n\tif (features.refactorCue) scores.refactor += weights.refactorCue;\n\tif (features.implementationObject) scores[\"code-gen\"] += weights.implementationObject;\n\tif (features.codeGenArtifactRequest) scores[\"code-gen\"] += weights.codeGenArtifactRequest;\n\tif (features.evaluativeReviewObject) scores.review += weights.evaluativeReviewObject;\n\n\tfor (const taskClass of TASK_CLASSES_V4) {\n\t\tif (features.keywordFamilyMatch[taskClass]) scores[taskClass] += weights.keywordFamily[taskClass];\n\t\tif (features.normalizedIntentClusterMatch[taskClass]) scores[taskClass] += weights.normalizedIntentCluster;\n\t\tif (features.intentSkeletonMatch[taskClass]) scores[taskClass] += weights.intentSkeleton;\n\t}\n\tif (features.addKeywordMatch) scores[\"code-gen\"] += weights.addKeyword;\n\n\treturn scores;\n}\n\n/**\n * Extension signals (history / context-pressure / judge vote). The released\n * default coefficients are bounded and nonzero, but apply only after the base\n * scorer finds prompt evidence. This keeps zero-score fallback decisions under\n * the fallback cascade rather than an unrelated prior or vote.\n */\nfunction applyExtensionSignalsV4(\n\tscores: Record<TaskClassV4, number>,\n\tinput: TaskClassifierInputV4,\n\tweights: RouterWeightsV4,\n): void {\n\t// Gate (goal 016/L2): extension votes apply only when a real signal already\n\t// exists. On a zero-score state the fallback cascade (trivial-length,\n\t// ko-short, long-prose, lane) owns the verdict — a stray history/judge vote\n\t// must not hijack it (measured: any weight >= 1 flips gold-0001 \"hi\" to the\n\t// voted class otherwise). The gate keeps the bounded nonzero defaults from\n\t// taking authority over an evidence-free fallback.\n\tlet topScore = 0;\n\tfor (const c of TASK_CLASSES_V4) topScore = Math.max(topScore, scores[c]);\n\tif (topScore <= 0) return;\n\n\tconst priorClass = input.history !== undefined && input.history.length > 0 ? input.history[0] : null;\n\tif (priorClass !== null && weights.multiTurnPrior !== 0) scores[priorClass] += weights.multiTurnPrior;\n\n\tconst judgeVote = input.judgeVote ?? null;\n\tif (judgeVote !== null && weights.judgeVote !== 0) scores[judgeVote] += weights.judgeVote;\n\n\tconst pressureBucket = input.pressureBucket ?? 0;\n\tif (pressureBucket > 0 && weights.pressureBucket !== 0) {\n\t\tconst bump = pressureBucket * weights.pressureBucket;\n\t\tscores.debug += bump;\n\t\tscores.review += bump;\n\t\tscores.plan += bump;\n\t}\n}\n\nfunction clampConfidenceV4(value: number): number {\n\treturn Math.max(0, Math.min(1, value));\n}\n\nfunction confidenceEvidenceStrengthV4(topScore: number, margin: number, weights: RouterWeightsV4): number {\n\tif (topScore <= 0) return 0;\n\tconst separation = clampConfidenceV4(margin / topScore);\n\tconst evidenceFloor = weights.leadingIntent > 0 ? weights.leadingIntent : 1;\n\treturn Math.min(separation, clampConfidenceV4(topScore / evidenceFloor));\n}\n\n// ============================================================================\n// Public types\n// ============================================================================\n\n/**\n * Caller-supplied turn input. Identical shape to `TaskClassifierInputV3` /\n * `TaskClassifierInputV2` (prompt + optional lane/history/pressure/judge\n * slots), so existing callers can switch versions without reshaping data.\n */\nexport interface TaskClassifierInputV4 {\n\tprompt: string;\n\tlaneType?: ReasoningLaneTypeV4;\n\thistory?: readonly TaskClassV4[];\n\tpressureBucket?: number;\n\tjudgeVote?: TaskClassV4 | null;\n}\n\n/** Confidence band derived from score separation plus absolute evidence strength. */\nexport type ConfidenceBandV4 = \"low\" | \"medium\" | \"high\";\n\n/** Which branch of the zero-score fallback cascade decided `taskClass`; null when a real weighted signal decided it. */\nexport type FallbackReasonV4 =\n\t| \"code-fence-or-diff\"\n\t| \"trivial-length\"\n\t| \"ko-short-task-signal\"\n\t| \"long-prose\"\n\t| \"lane-fallback\"\n\t| \"default\";\n\n/**\n * The full, privacy-safe classification verdict (spec 008 Req 2). Every field\n * is a bounded enum, number, boolean, or a closed set of short diagnostic-id\n * strings (`suppressedFeatureIds`) — never raw prompt text, so this value is\n * safe to pass to evaluation, learning, and Adaptorch-advisory code.\n */\nexport interface ClassifierVerdictV4 {\n\t/** The decided task class (post zero-score-cascade if one fired). */\n\treadonly taskClass: TaskClassV4;\n\t/** Raw per-class score map from the weighted signals (pre-cascade; audit-only). */\n\treadonly scores: Readonly<Record<TaskClassV4, number>>;\n\t/** Second-highest-scoring class by the argmax, or null if every other class tied at the bottom. */\n\treadonly runnerUp: TaskClassV4 | null;\n\t/** `scores[argmaxClass] - scores[runnerUp]` (pre-cascade); 0 or negative-margin-free by construction (weights are non-negative). */\n\treadonly margin: number;\n\t/** Normalized confidence in [0, 1], combining `margin / topScore` with absolute evidence strength. */\n\treadonly confidence: number;\n\t/** Confidence bucketed by `weights.lowConfidenceThreshold` / `highConfidenceThreshold`. */\n\treadonly confidenceBand: ConfidenceBandV4;\n\t/** True when the argmax class won only via precedence-order tie-break over an exact score tie with the runner-up. */\n\treadonly tieBreak: boolean;\n\t/** Non-null exactly when the zero-score cascade (not a real weighted signal) decided `taskClass`. */\n\treadonly fallbackReason: FallbackReasonV4 | null;\n\t/** Audit trail of `negation:<channel>` ids for every whole-prompt signal that had a match but was fully negated. */\n\treadonly suppressedFeatureIds: readonly string[];\n\t/** True when a distinct second-clause leading intent was detected (bounded compound-intent detection). */\n\treadonly compoundIntent: boolean;\n\t/** The second clause's own leading intent, or null when no compound structure (or no distinct intent) was found. */\n\treadonly secondClauseIntent: TaskClassV4 | null;\n}\n\n// ============================================================================\n// Classifier\n// ============================================================================\n\n/**\n * Deterministic confidence-bearing classifier (spec 008 Req 2).\n *\n * Pipeline: extract negation/compound-aware contextual features -> score every\n * class from `weights` -> argmax with `TASK_CLASSES_V4` precedence tie-break,\n * tracking the runner-up -> compute margin/confidence/confidenceBand/tieBreak\n * from RAW score separation plus evidence strength -> if `topScore <= 0`, replace `taskClass` (and record\n * `fallbackReason`) via the zero-score cascade (fence/diff -> code-gen;\n * length < 40 -> trivial; length >= 2400 -> plan; lane fallback; default\n * code-gen) — the raw scores/margin/runnerUp/tieBreak fields still reflect the\n * pre-cascade computation, for audit purposes.\n *\n * Pure: same (input, weights) -> same ClassifierVerdictV4.\n */\nexport function classifyTaskV4(\n\tinput: TaskClassifierInputV4,\n\tweights: RouterWeightsV4 = DEFAULT_WEIGHTS_V4,\n\tfeedbackFeatures?: RouterFeedbackFeaturesV4,\n): ClassifierVerdictV4 {\n\tconst prompt = input.prompt.trim();\n\tconst suppressed: string[] = [];\n\tconst features = extractFeaturesV4(prompt, weights, suppressed, feedbackFeatures);\n\tconst scores = computeScoresV4(features, weights);\n\tapplyExtensionSignalsV4(scores, input, weights);\n\n\tlet top: TaskClassV4 = TASK_CLASSES_V4[0];\n\tfor (const c of TASK_CLASSES_V4) {\n\t\tif (scores[c] > scores[top]) top = c;\n\t}\n\tlet runnerUp: TaskClassV4 | null = null;\n\tfor (const c of TASK_CLASSES_V4) {\n\t\tif (c === top) continue;\n\t\tif (runnerUp === null || scores[c] > scores[runnerUp]) runnerUp = c;\n\t}\n\n\tconst topScore = scores[top];\n\tconst runnerUpScore = runnerUp !== null ? scores[runnerUp] : 0;\n\tconst margin = topScore - runnerUpScore;\n\tconst tieBreak = runnerUp !== null && topScore === runnerUpScore;\n\tconst rawConfidence = confidenceEvidenceStrengthV4(topScore, margin, weights);\n\tconst singleGeneralizedEvidence =\n\t\tfeatures.generalizedEvidenceCount[top] === 1 &&\n\t\ttopScore <= Math.max(weights.normalizedIntentCluster, weights.intentSkeleton);\n\tconst confidence = singleGeneralizedEvidence\n\t\t? Math.min(rawConfidence, Math.max(0, weights.highConfidenceThreshold - 0.01))\n\t\t: rawConfidence;\n\tconst confidenceBand: ConfidenceBandV4 =\n\t\tconfidence <= weights.lowConfidenceThreshold\n\t\t\t? \"low\"\n\t\t\t: confidence >= weights.highConfidenceThreshold\n\t\t\t\t? \"high\"\n\t\t\t\t: \"medium\";\n\n\tlet taskClass: TaskClassV4 = top;\n\tlet fallbackReason: FallbackReasonV4 | null = null;\n\tif (topScore <= 0) {\n\t\tif (features.codeFence || features.diffHunk) {\n\t\t\ttaskClass = \"code-gen\";\n\t\t\tfallbackReason = \"code-fence-or-diff\";\n\t\t} else {\n\t\t\t// Hangul zero-score prompts route by morphology at ANY length, not just\n\t\t\t// short ones: previously a >40-char Korean edit request fell through to\n\t\t\t// the code-gen default even when a morphology cluster matched. (016)\n\t\t\tconst koreanTaskClass = /[가-힣]/.test(prompt)\n\t\t\t\t? classifyShortKoreanZeroScoreTaskV4(prompt, weights.negationWindowChars)\n\t\t\t\t: null;\n\t\t\tif (koreanTaskClass !== null) {\n\t\t\t\ttaskClass = koreanTaskClass;\n\t\t\t\tfallbackReason = \"ko-short-task-signal\";\n\t\t\t} else if (prompt.length < TRIVIAL_MAX_CHARS_V4) {\n\t\t\t\ttaskClass = \"trivial\";\n\t\t\t\tfallbackReason = \"trivial-length\";\n\t\t\t} else if (prompt.length >= COMPLEX_PROSE_MIN_CHARS_V4) {\n\t\t\t\ttaskClass = \"plan\";\n\t\t\t\tfallbackReason = \"long-prose\";\n\t\t\t} else if (input.laneType !== undefined) {\n\t\t\t\ttaskClass = LANE_FALLBACK_CLASS_V4[input.laneType];\n\t\t\t\tfallbackReason = \"lane-fallback\";\n\t\t\t} else {\n\t\t\t\ttaskClass = \"code-gen\";\n\t\t\t\tfallbackReason = \"default\";\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\ttaskClass,\n\t\tscores,\n\t\trunnerUp,\n\t\tmargin,\n\t\tconfidence,\n\t\tconfidenceBand,\n\t\ttieBreak,\n\t\tfallbackReason,\n\t\tsuppressedFeatureIds: suppressed,\n\t\tcompoundIntent: features.compoundIntent,\n\t\tsecondClauseIntent: features.secondClauseIntent,\n\t};\n}\n\n// ============================================================================\n// Resolver\n// ============================================================================\n\n/**\n * Static rule table: task class -> recommended ThinkingLevel. Re-exported\n * from the shared resolver core (byte-identical values; previously a\n * duplicated literal here — see reasoning-router-resolver.ts).\n */\nexport const TASK_CLASS_THINKING_LEVELS_V4 = TASK_CLASS_THINKING_LEVELS;\n\n/**\n * Bounded, strictly non-negative escalation applied when the verdict's own\n * confidence is low or a fallback (not a real signal) decided the class. This\n * is the ONLY place confidence touches the target index, and it can only add:\n * confidence can never lower effort (spec 008 Req 2 acceptance criterion).\n */\nconst LOW_CONFIDENCE_ESCALATION_STEPS_V4 = 1;\n\n/**\n * Thin auto-mode wrapper with no uncertainty adjustment: base rule table ->\n * lane step -> clamp to availableLevels. This is v4's \"confident\" path and\n * delegates to the shared resolver core with bias=0, hint=null, escalationSteps=0.\n */\nexport function resolveThinkingLevelV4ForAuto(\n\ttaskClass: TaskClassV4,\n\tavailableLevels: readonly ThinkingLevel[],\n\tlaneType: ReasoningLaneTypeV4 | undefined,\n): ThinkingLevel {\n\treturn resolveThinkingLevelCore(taskClass, availableLevels, laneType, 0, null, 0);\n}\n\n/**\n * Uncertainty-aware resolver (spec 008 Req 2 / plan.md step 5).\n *\n * Pipeline: base rule table for `verdict.taskClass` -> lane step -> bounded\n * bias [-2,+2] -> optional hint fusion (±2 bounded) -> bounded\n * non-negative confidence escalation (+1 ladder step exactly when\n * `verdict.confidenceBand === \"low\"` or `verdict.fallbackReason !== null`) ->\n * clamp to `availableLevels`.\n *\n * The confidence-escalation term is strictly `>= 0`: low confidence can only\n * hold the base+lane+bias+hint target or push it one step higher, never lower\n * it. This guarantees a low-confidence verdict never resolves BELOW what\n * `resolveThinkingLevelV4ForAuto` would give the same class (with bias=0,\n * hint=null) — text alone cannot talk the resolver down.\n */\nexport function resolveThinkingLevelV4WithUncertainty(\n\tverdict: ClassifierVerdictV4,\n\tavailableLevels: readonly ThinkingLevel[],\n\tlaneType: ReasoningLaneTypeV4 | undefined,\n\tbias = 0,\n\thint: { level: ThinkingLevel; confidence: number } | null = null,\n): ThinkingLevel {\n\tconst escalationSteps =\n\t\tverdict.confidenceBand === \"low\" || verdict.fallbackReason !== null ? LOW_CONFIDENCE_ESCALATION_STEPS_V4 : 0;\n\treturn resolveThinkingLevelCore(verdict.taskClass, availableLevels, laneType, bias, hint, escalationSteps);\n}\n"]}
1
+ {"version":3,"file":"reasoning-router-v4.js","sourceRoot":"","sources":["../../src/core/reasoning-router-v4.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,EACN,kBAAkB,EAGlB,eAAe,GAEf,MAAM,kCAAkC,CAAC;AAI1C,OAAO,EAAE,kBAAkB,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAEvF,OAAO,EAAE,wBAAwB,EAAE,0BAA0B,EAAE,MAAM,gCAAgC,CAAC;AACtG,OAAO,EAAE,kCAAkC,EAAE,MAAM,oCAAoC,CAAC;AAExF,+FAA+F;AAC/F,MAAM,oBAAoB,GAAG,EAAE,CAAC;AAChC,6FAA6F;AAC7F,MAAM,0BAA0B,GAAG,IAAI,CAAC;AACxC,uGAAuG;AACvG,MAAM,uBAAuB,GAAG,GAAG,CAAC;AACpC,sHAAsH;AACtH,MAAM,2BAA2B,GAAG,GAAG,CAAC;AACxC,qGAAqG;AACrG,MAAM,mCAAmC,GAAG,CAAC,CAAC;AAC9C,2HAA2H;AAC3H,MAAM,oCAAoC,GAAG,GAAG,CAAC;AAEjD,2FAA2F;AAC3F,MAAM,sBAAsB,GAAuD;IAClF,OAAO,EAAE,MAAM;IACf,QAAQ,EAAE,QAAQ;IAClB,QAAQ,EAAE,QAAQ;IAClB,KAAK,EAAE,UAAU;IACjB,QAAQ,EAAE,QAAQ;IAClB,MAAM,EAAE,UAAU;CAClB,CAAC;AAaF,MAAM,yBAAyB,GAAqC;IACnE;QACC,EAAE,EAAE,uBAAuB;QAC3B,SAAS,EAAE,OAAO;QAClB,IAAI,EA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ACzC,IAAI,GAAG,CAAC,EACR,IAAI,GAAwD,IAAI,EAChD;IAChB,MAAM,eAAe,GACpB,OAAO,CAAC,cAAc,KAAK,KAAK,IAAI,OAAO,CAAC,cAAc,KAAK,IAAI,CAAC,CAAC,CAAC,kCAAkC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC9G,OAAO,wBAAwB,CAAC,OAAO,CAAC,SAAS,EAAE,eAAe,EAAE,QAAQ,EAAE,IAAI,EAAE,IAAI,EAAE,eAAe,CAAC,CAAC;AAAA,CAC3G","sourcesContent":["/**\n * Reasoning-router v4 — the sole `/think auto` classifier/resolver.\n *\n * Deterministic by construction: same (input, weights) -> same\n * ClassifierVerdictV4; same (verdict, availableLevels, laneType, bias, hint) ->\n * same ThinkingLevel. No clock, randomness, I/O, model calls, network access,\n * or state mutation anywhere in this file (ThinkingLevel is a type-only import\n * and is erased).\n *\n * `classifyTaskV4` returns a confidence-bearing verdict: task class, per-class\n * scores, runner-up, margin, confidence band, tie-break flag, fallback reason,\n * bounded-negation audit ids, and compound-intent metadata. None of this carries\n * prompt text — every field is a bounded enum, number, boolean, or a closed set\n * of short diagnostic-id strings.\n *\n * `resolveThinkingLevelV4WithUncertainty` starts from the canonical task-class\n * rule table, applies lane/bias/hint adjustments, and only adds non-negative\n * confidence escalation. A prompt cannot lower its own effort by asking the\n * router to \"think less\"; low confidence or fallback routing can only hold or\n * raise the resolved level.\n */\n\nimport type { ThinkingLevel } from \"omk-agent-core\";\nimport {\n\tDEFAULT_WEIGHTS_V4,\n\ttype ReasoningLaneTypeV4,\n\ttype RouterWeightsV4,\n\tTASK_CLASSES_V4,\n\ttype TaskClassV4,\n} from \"./reasoning-router-v4-weights.ts\";\nimport type { RouterFeedbackLenBucket } from \"./router-feedback-collector.ts\";\n\nexport type { ReasoningLaneTypeV4, RouterWeightsV4, TaskClassV4 } from \"./reasoning-router-v4-weights.ts\";\nexport { DEFAULT_WEIGHTS_V4, TASK_CLASSES_V4 } from \"./reasoning-router-v4-weights.ts\";\n\nimport { resolveThinkingLevelCore, TASK_CLASS_THINKING_LEVELS } from \"./reasoning-router-resolver.ts\";\nimport { extractGeneralizedIntentEvidenceV4 } from \"./reasoning-router-v4-normalize.ts\";\n\n/** Prompts shorter than this (trimmed) fall back to trivial when no real signal scores > 0. */\nconst TRIVIAL_MAX_CHARS_V4 = 40;\n/** Prompts at/above this length with no real signal fall back to plan (long prose brief). */\nconst COMPLEX_PROSE_MIN_CHARS_V4 = 2400;\n/** Plan-brief prompts at/above this length count as a \"long brief\" even without PLAN_BRIEF_PATTERN. */\nconst LONG_BRIEF_MIN_CHARS_V4 = 512;\n/** Compound-clause split only applies within this many leading characters (short direct commands, not long prose). */\nconst COMPOUND_SPLIT_MAX_INDEX_V4 = 300;\n/** Minimum trimmed length of a candidate second clause to be worth checking for a leading intent. */\nconst COMPOUND_SECOND_CLAUSE_MIN_CHARS_V4 = 3;\n/** Bounded look-ahead cap when checking a second clause's leading intent (defense in depth; independent of regex cost). */\nconst COMPOUND_SECOND_CLAUSE_SCAN_CHARS_V4 = 200;\n\n/** Lane fallback class, used only when every scored class is <= 0 (zero-score cascade). */\nconst LANE_FALLBACK_CLASS_V4: Readonly<Record<ReasoningLaneTypeV4, TaskClassV4>> = {\n\tplanner: \"plan\",\n\tsecurity: \"review\",\n\texplorer: \"review\",\n\tcoder: \"code-gen\",\n\treviewer: \"review\",\n\ttester: \"code-gen\",\n};\n\ntype IntentLexemeClusterRoleV4 = \"leading-intent\" | \"whole-prompt\" | \"object-shape\" | \"korean-morphology\";\n\ntype IntentLexemeClusterV4 = {\n\treadonly id: string;\n\treadonly taskClass: TaskClassV4;\n\treadonly role: IntentLexemeClusterRoleV4;\n\treadonly surfaces: readonly string[];\n\treadonly phrases: readonly RegExp[];\n\treadonly negativeControlIds: readonly string[];\n};\n\nconst INTENT_LEXEME_CLUSTERS_V4: readonly IntentLexemeClusterV4[] = [\n\t{\n\t\tid: \"debug-leading-actions\",\n\t\ttaskClass: \"debug\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\"debug\", \"investigate why\", \"reproduce\", \"trace\", \"fix this traceback/panic/error\"],\n\t\tphrases: [/^(?:debug|investigate\\s+why|reproduce|trace\\b)|^fix\\s+this\\s+(?:traceback|panic|error)\\b/i],\n\t\tnegativeControlIds: [\"negated-debug-action\", \"generic-error-handling\"],\n\t},\n\t{\n\t\tid: \"review-leading-actions\",\n\t\ttaskClass: \"review\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\"review\", \"audit\", \"critique\", \"inspect\", \"assess\", \"approve\", \"double-check\", \"lgtm\"],\n\t\tphrases: [/^(?:review|audit(?!\\s+log\\b)|critique|inspect|assess|approve|double-?check|lgtm)\\b/i],\n\t\tnegativeControlIds: [\"audit-log-not-review\", \"review-negated-before-code-gen\"],\n\t},\n\t{\n\t\tid: \"review-leading-synonyms\",\n\t\ttaskClass: \"review\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\n\t\t\t\"give this PR a once-over\",\n\t\t\t\"look over\",\n\t\t\t\"sanity-check\",\n\t\t\t\"eyeball\",\n\t\t\t\"poke holes\",\n\t\t\t\"pressure-test\",\n\t\t\t\"tell me whether/if\",\n\t\t\t\"what could go wrong\",\n\t\t],\n\t\tphrases: [\n\t\t\t/^(?:give\\s+(?:this|the|my)?\\s*(?:pr|pull\\s+request|diff|code|change|branch)?\\s*(?:a\\s+)?once-?over|look\\s+over|sanity[-\\s]?check|eyeball|poke\\s+holes(?:\\s+in)?|pressure[-\\s]?test|sign\\s+off|tell\\s+me\\s+(?:if|whether)|tell\\s+me\\s+what\\s+could\\s+go\\s+wrong|where\\s+would\\b[^.!?;\\n]{0,100}\\bfall\\s+apart|what\\s+am\\s+i\\s+missing|check\\s+whether|look\\s+for\\s+(?:edge\\s+cases|risks?|flaws?)|find\\s+(?:flaws|risks?|issues?)|validate\\s+(?:the\\s+)?reasoning|give\\s+me\\s+a\\s+thumbs[-\\s]?up\\/?down|read\\s+(?:this|the|my)\\b[^.!?;\\n]{0,80}\\bchallenge|(?:is|are|does|do|can|could|would|should)\\s+(?:this|these|my|the)\\b[^.!?;\\n]{0,100}\\b(?:right\\s+way|handle|cover|safe|sane|clean|overkill|prove|leak|ship|concurrent|hidden\\s+coupling)|(?:at\\s+architecture\\s+level|architecture[-\\s]?level)\\b[^.!?;\\n]{0,80}\\bhidden\\s+coupling)\\b/i,\n\t\t],\n\t\tnegativeControlIds: [\"sanity-check-setup-script\", \"future-self-review-context\", \"check-whether-implementation\"],\n\t},\n\t{\n\t\tid: \"plan-leading-actions\",\n\t\ttaskClass: \"plan\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\"plan\", \"design\", \"architect\", \"decompose\", \"map out\", \"draw up\", \"think through\"],\n\t\tphrases: [\n\t\t\t/^(?:let(?:'|’)s\\s+)?(?:plan|design|architect|decompose|map\\s+out|draw\\s+up|think\\s+through)\\b/i,\n\t\t\t/^(?:write|create)\\s+(?:a\\s+)?(?:technical\\s+)?(?:spec|roadmap|strategy|plan)\\b/i,\n\t\t],\n\t\tnegativeControlIds: [\"design-token-edit\", \"draw-up-implementation-only\"],\n\t},\n\t{\n\t\tid: \"refactor-leading-actions\",\n\t\ttaskClass: \"refactor\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\"refactor\", \"extract\", \"rename\", \"deduplicate\", \"simplify\", \"clean up\", \"untangle\"],\n\t\tphrases: [\n\t\t\t/^(?:refactor(?:ing|ed)?|extract|rename|deduplicate|consolidate|modularize|reorganize|simplify|restructure|untangle)\\b|^clean\\s+up\\b|^split\\s+(?:the\\s+)?module\\b|^move\\s+logic\\b/i,\n\t\t],\n\t\tnegativeControlIds: [\"negated-refactor\", \"future-self-refactor\"],\n\t},\n\t{\n\t\tid: \"simple-edit-leading-actions\",\n\t\ttaskClass: \"simple-edit\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\"correct\", \"update\", \"swap\", \"remove\", \"adjust\", \"fix\", \"add\", \"change\", \"trim\", \"reword\"],\n\t\tphrases: [/^(?:correct|update|swap|remove|adjust|fix|add|change|trim|reword|tweak|bump)\\b/i],\n\t\tnegativeControlIds: [\"add-feature-not-simple-edit\", \"fix-crash-not-simple-edit\"],\n\t},\n\t{\n\t\tid: \"code-gen-leading-actions\",\n\t\ttaskClass: \"code-gen\",\n\t\trole: \"leading-intent\",\n\t\tsurfaces: [\n\t\t\t\"implement\",\n\t\t\t\"write\",\n\t\t\t\"create\",\n\t\t\t\"build\",\n\t\t\t\"generate\",\n\t\t\t\"scaffold\",\n\t\t\t\"prototype\",\n\t\t\t\"add\",\n\t\t\t\"whip up\",\n\t\t\t\"cook me\",\n\t\t],\n\t\tphrases: [/^(?:implement|write|create|build|generate|scaffold|prototype|add|whip\\s+up|cook\\s+me)\\b/i],\n\t\tnegativeControlIds: [\"write-a-plan\", \"create-a-review\"],\n\t},\n\t{\n\t\tid: \"debug-whole-prompt\",\n\t\ttaskClass: \"debug\",\n\t\trole: \"whole-prompt\",\n\t\tsurfaces: [\"debug\", \"investigate why\", \"reproduce\", \"track down\", \"figure out why\", \"get to the bottom\"],\n\t\tphrases: [\n\t\t\t/^(?:debug|investigate\\s+why|reproduce|trace\\b)|\\bfix\\s+this\\s+(?:traceback|panic|error)\\b|\\btrack\\s+down\\b|\\bfigure\\s+out\\s+why\\b|\\bget\\s+to\\s+the\\s+bottom\\b|디버깅|디버그|재현|원인\\s*분석/i,\n\t\t],\n\t\tnegativeControlIds: [\"not-a-bug-report\", \"error-handling-feature\"],\n\t},\n\t{\n\t\tid: \"review-whole-prompt\",\n\t\ttaskClass: \"review\",\n\t\trole: \"whole-prompt\",\n\t\tsurfaces: [\n\t\t\t\"review\",\n\t\t\t\"critique\",\n\t\t\t\"assess\",\n\t\t\t\"inspect\",\n\t\t\t\"once-over\",\n\t\t\t\"look over\",\n\t\t\t\"sanity-check\",\n\t\t\t\"eyeball\",\n\t\t\t\"poke holes\",\n\t\t\t\"pressure-test\",\n\t\t\t\"tell me whether correct\",\n\t\t],\n\t\tphrases: [\n\t\t\t/\\b(review|critique|assess|inspect|approve|lgtm|double-?check|sanity[-\\s]?check|once-?over|look\\s+over|eyeball|poke\\s+holes|pressure[-\\s]?test|sign\\s+off|thumbs[-\\s]?up\\/?down|what\\s+could\\s+go\\s+wrong|what\\s+am\\s+i\\s+missing|challenge\\s+the\\s+assumptions|hidden\\s+coupling|tell\\s+me\\s+(?:if|whether)[^.!?;\\n]{0,80}\\bcorrect|audit(?!\\s+log\\b))\\b|리뷰|검토|점검|괜찮은지\\s*봐\\s*줘|맞는지\\s*봐\\s*줘|처리되는지\\s*확인|허점.{0,10}찾|문제\\s*없는지/i,\n\t\t],\n\t\tnegativeControlIds: [\"review-free-implementation\", \"audit-log\"],\n\t},\n\t{\n\t\tid: \"plan-whole-prompt\",\n\t\ttaskClass: \"plan\",\n\t\trole: \"whole-prompt\",\n\t\tsurfaces: [\"plan\", \"design\", \"architecture\", \"roadmap\", \"map out\", \"draw up\", \"think through\"],\n\t\tphrases: [\n\t\t\t/\\b(plan|design|architect|architecture|roadmap|spec(?:ification)?|strategy|decompose|milestones?|map\\s+out|phases|draw\\s+up|think\\s+through|write\\s+a\\s+(?:technical\\s+)?spec|create\\s+a\\s+(?:roadmap|strategy|plan))\\b|설계|로드맵|아키텍처|계획.{0,6}세워|기획/i,\n\t\t],\n\t\tnegativeControlIds: [\"rather-than-design\", \"design-token-edit\"],\n\t},\n\t{\n\t\tid: \"code-gen-whole-prompt\",\n\t\ttaskClass: \"code-gen\",\n\t\trole: \"whole-prompt\",\n\t\tsurfaces: [\"implement\", \"write\", \"create\", \"build\", \"generate\", \"scaffold\", \"prototype\", \"whip up\", \"cook me\"],\n\t\tphrases: [\n\t\t\t/\\b(implement|write|create|build|generate|scaffold|prototype|whip\\s+up|cook\\s+me)\\b|구현|만들어\\s*줘|생성|작성|추가해/i,\n\t\t],\n\t\tnegativeControlIds: [\"write-plan\", \"create-roadmap\"],\n\t},\n\t{\n\t\tid: \"code-gen-artifact-request\",\n\t\ttaskClass: \"code-gen\",\n\t\trole: \"object-shape\",\n\t\tsurfaces: [\"I need a script\", \"we need a utility\", \"I need an endpoint\", \"we need a test\"],\n\t\tphrases: [\n\t\t\t/\\b(?:i|we)\\s+need\\s+(?:a|an|the|some)?\\s*(?:small\\s+|quick\\s+|new\\s+)?(?:script|utility|helper|component|endpoint|migration|test|tool|function|service)\\b(?!\\s+(?:plan|strategy|review|audit|roadmap|spec))/i,\n\t\t],\n\t\tnegativeControlIds: [\"need-a-plan\", \"need-a-review\", \"need-help-debugging\"],\n\t},\n\t{\n\t\tid: \"evaluative-review-object\",\n\t\ttaskClass: \"review\",\n\t\trole: \"object-shape\",\n\t\tsurfaces: [\"holes\", \"looks off\", \"correct\", \"safe\", \"risky\", \"issues\", \"regressions\"],\n\t\tphrases: [/\\b(holes?|looks?\\s+off|correct|safe|risky|issues?|regressions?)\\b/i],\n\t\tnegativeControlIds: [\"fix-holes\", \"implement-issue-fix\"],\n\t},\n\t{\n\t\tid: \"korean-debug-morphology\",\n\t\ttaskClass: \"debug\",\n\t\trole: \"korean-morphology\",\n\t\tsurfaces: [\n\t\t\t\"오류\",\n\t\t\t\"에러\",\n\t\t\t\"실패\",\n\t\t\t\"원인 찾아줘\",\n\t\t\t\"원인 파악\",\n\t\t\t\"숫자가 이상해\",\n\t\t\t\"합계가 안 맞아\",\n\t\t\t\"빈 파일\",\n\t\t\t\"CI가 빨개\",\n\t\t\t\"디버깅\",\n\t\t],\n\t\tphrases: [\n\t\t\t/오류|에러|실패|안\\s*돼|안\\s*됨|깨졌|깨짐|고장|디버깅|디버그|재현|원인\\s*(?:분석|파악|찾(?:아|기)?|찾아\\s*줘)?|숫자.{0,12}(?:이상|틀려|안\\s*맞)|합계.{0,12}(?:안\\s*맞|틀려|이상)|빈\\s*파일|(?:CI|러너).{0,12}빨개/i,\n\t\t],\n\t\tnegativeControlIds: [\"korean-error-handling-feature\", \"korean-greeting\"],\n\t},\n\t{\n\t\tid: \"korean-simple-edit-morphology\",\n\t\ttaskClass: \"simple-edit\",\n\t\trole: \"korean-morphology\",\n\t\tsurfaces: [\n\t\t\t\"오타\",\n\t\t\t\"맞춤법\",\n\t\t\t\"띄어쓰기\",\n\t\t\t\"문구\",\n\t\t\t\"제목\",\n\t\t\t\"바꿔\",\n\t\t\t\"바꾸\",\n\t\t\t\"수정\",\n\t\t\t\"변경\",\n\t\t\t\"고쳐\",\n\t\t\t\"고치\",\n\t\t\t\"삭제\",\n\t\t\t\"제거\",\n\t\t\t\"옮겨\",\n\t\t\t\"옮기\",\n\t\t],\n\t\tphrases: [\n\t\t\t// Typo/copy nouns plus modification verbs. Creation verbs live in\n\t\t\t// korean-code-gen-morphology; modifying an existing artifact is an edit,\n\t\t\t// not a generation. (016: moved from code-gen after hard-negative mining.)\n\t\t\t/오타|맞춤법|띄어쓰기|문구|제목|바꿔|바꾸|수정|변경|고쳐|고치|삭제|지워|지우|제거|옮겨|옮기|넣어/i,\n\t\t],\n\t\tnegativeControlIds: [\"korean-feature-edit\"],\n\t},\n\t{\n\t\tid: \"korean-review-morphology\",\n\t\ttaskClass: \"review\",\n\t\trole: \"korean-morphology\",\n\t\tsurfaces: [\"리뷰\", \"검토\", \"점검\", \"괜찮은지 봐줘\", \"맞는지 봐줘\", \"허점 찾아줘\"],\n\t\tphrases: [/리뷰|검토|점검|괜찮은지\\s*봐\\s*줘|맞는지\\s*봐\\s*줘|처리되는지\\s*확인|허점.{0,10}찾|문제\\s*없는지/i],\n\t\tnegativeControlIds: [\"korean-review-negated\"],\n\t},\n\t{\n\t\tid: \"korean-plan-morphology\",\n\t\ttaskClass: \"plan\",\n\t\trole: \"korean-morphology\",\n\t\tsurfaces: [\"설계\", \"로드맵\", \"아키텍처\", \"계획 세워\", \"계획 짜\", \"계획 수립\", \"계획 정리\"],\n\t\tphrases: [/설계|로드맵|아키텍처|계획.{0,8}(?:세워|짜|수립|정리)|기획/i],\n\t\tnegativeControlIds: [\"korean-plan-negated\"],\n\t},\n\t{\n\t\tid: \"korean-refactor-morphology\",\n\t\ttaskClass: \"refactor\",\n\t\trole: \"korean-morphology\",\n\t\tsurfaces: [\"리팩토링\", \"리팩터링\", \"구조 개선\"],\n\t\tphrases: [/리팩토링|리팩터링|구조\\s*개선/i],\n\t\tnegativeControlIds: [\"korean-refactor-negated\"],\n\t},\n\t{\n\t\tid: \"korean-code-gen-morphology\",\n\t\ttaskClass: \"code-gen\",\n\t\trole: \"korean-morphology\",\n\t\tsurfaces: [\"구현\", \"만들\", \"생성\", \"작성\", \"추가\", \"테스트\"],\n\t\tphrases: [/구현|만들|생성|작성|추가|테스트/i],\n\t\tnegativeControlIds: [\"korean-greeting\", \"korean-codegen-negated\"],\n\t},\n] as const;\n\nfunction clusterMatchesRoleV4(text: string, taskClass: TaskClassV4, role: IntentLexemeClusterRoleV4): boolean {\n\treturn INTENT_LEXEME_CLUSTERS_V4.some(\n\t\t(cluster) =>\n\t\t\tcluster.taskClass === taskClass &&\n\t\t\tcluster.role === role &&\n\t\t\tcluster.phrases.some((pattern) => pattern.test(text)),\n\t);\n}\n\n// ============================================================================\n// Whole-prompt / leading-clause patterns used by the v4 scorer.\n// ============================================================================\n\nconst LOCAL_EDIT_OBJECT_PATTERN =\n\t/\\b(spelling|grammar|capitalization|date\\s+format|author\\s+e-?mail|copyright\\s+year|headline|title|tooltip|placeholder|punctuation|comma|period|semicolon|closing\\s+html\\s+tag|closing\\s+tag|double\\s+space|whitespace|indentation|table\\s+alignment|typos?|one-?liner?|single\\s+line|sentence|stray|trailing)\\b|오타|맞춤법|띄어쓰기|문구|제목/i;\nconst LOCAL_EDIT_ACTION_OBJECT_PATTERN =\n\t/\\b(update|change|swap|remove|correct|fix|add|adjust|trim)\\s+(?:the\\s+|a\\s+|an\\s+)?(?:missing\\s+|stray\\s+|author\\s+|two\\s+)?(?:e-?mail|comma|period|semicolon|tag|word|words|headline|title|copyright|spelling|grammar)\\b/i;\nconst IMPLEMENTATION_OBJECT_PATTERN =\n\t/\\b(error\\s+handling|input\\s+validation|validation|auth(?:entication)?|retry|endpoint|migration|component|function|utility|helper|module|service|database|schema|column|middleware|rate\\s+limiter|cache|caching|oauth|jwt|webhook)\\b|에러\\s*처리|오류\\s*처리|입력\\s*검증|인증|재시도|엔드포인트|마이그레이션|컴포넌트|함수|유틸|헬퍼|모듈|서비스|데이터베이스|스키마|미들웨어|레이트\\s*리미터|캐시|웹훅|기능/i;\nconst HARD_DIAGNOSTIC_PATTERN =\n\t/\\b(stack\\s*trace|traceback|panic|segfault|crash(?:es|ing|ed)?|throws?|fails?|failing|flaky|hangs?|timeout|500|EADDRINUSE|silently\\s+(?:fails?|produces?|returns?|creates?)|(?:ci|build)\\s+(?:is\\s+)?red|runner\\s+(?:goes|went|is)\\s+red|comes?\\s+out\\s+wrong|totals?\\s+(?:are\\s+)?off|drift(?:ed|ing)?|mismatch(?:ed|es)?|mismatched|no\\s+longer\\s+matches|says\\s+success\\s+but|exits?\\s+0\\s+but|empty\\s+file|opens?\\s+blank|black\\s+image|zero[-\\s]?byte\\s+files?|headers\\s+only|rows?\\s+are\\s+missing|missing\\s+rows|stale\\s+(?:index|prices?|cache|results?)|search\\s+index\\s+(?:is\\s+)?stale|duplicate\\s+rows|NaN|never\\s+(?:send|sends|appear|appears|land|lands|writes?|written|updates?)|works\\s+locally\\s+and\\s+breaks|worked\\s+yesterday|settings\\s+revert|side\\s+effect\\s+never|stops?\\s+updating|data\\s+disappears)\\b|\\b(?:TypeError|ReferenceError|RangeError|Error):|크래시|스택\\s*트레이스|세그폴트|먹통|멈춰|타임아웃|숫자.{0,12}(?:이상|틀려|안\\s*맞)|합계.{0,12}(?:안\\s*맞|틀려|이상)|빈\\s*파일|(?:CI|러너).{0,12}빨개/i;\nconst BUG_OBJECT_PATTERN =\n\t/\\b(null\\s+pointer|null\\s+deref|race(?:\\s+condition)?|heap(?:\\s+overflow)?|use-after-free|memory\\s+leak|leaks?|deadlock|data\\s+corruption|stale\\s+data|off-by-one|encoding\\s+bug|regression\\s+(?:was\\s+)?introduced|exceptions?|assertion\\s+error|bugs?)\\b|버그|예외|메모리\\s*누수|데드락|무한\\s*루프/i;\nconst NON_DIAGNOSTIC_DEBUG_CONTEXT_PATTERN = /\\berror\\s+(?:handling|messages?|budgets?)\\b|에러\\s*처리|오류\\s*처리/i;\nconst GENERIC_DIAGNOSTIC_PATTERN = /\\b(errors?|broken|wrong\\s+results|rolls?\\s+back|rollback)\\b/i;\nconst PLAN_BRIEF_PATTERN =\n\t/\\b(context\\s+and\\s+constraints|starting\\s+state|target\\s+state|cross-cutting|deliver:|deliverables?|roadmap|migration\\s+wave|top\\s+(?:ten\\s+)?risks|component\\s+diagram|data\\s+model|architecture|go\\/no-go|phased\\s+(?:delivery|rollout)|bounded\\s+contexts?|strangler\\s+fig|event-driven|quarter-by-quarter|milestone)\\b/i;\nconst OPERATIONAL_RUNBOOK_SIGNAL_PATTERNS: readonly { pattern: RegExp; critical: boolean }[] = [\n\t{ pattern: /\\b(?:commit|commits|committed|committing)\\b|커밋/i, critical: false },\n\t{ pattern: /\\b(?:push|pushed|pushing)\\b|푸시|푸쉬/i, critical: true },\n\t{\n\t\tpattern: /\\b(?:release|releases|tag|version\\s+bump|bump\\s+(?:the\\s+)?version)\\b|릴리즈|태그|버전/i,\n\t\tcritical: true,\n\t},\n\t{ pattern: /\\bnpm\\s+publish\\b|\\bpublish(?:ing|ed)?\\b|퍼블리시|배포/i, critical: true },\n\t{ pattern: /\\b(?:CHANGELOG\\.md|changelog|release\\s+notes?)\\b|채널로그|체인지로그/i, critical: false },\n\t{ pattern: /\\bREADME\\.md\\b|\\breadme\\b/i, critical: false },\n\t{ pattern: /\\bci\\s*\\/\\s*cd\\b|\\bgithub\\s+actions?\\b|\\bworkflow\\b|깃허브\\s*액션|깃헙\\s*액션/i, critical: false },\n];\nconst EXPLICIT_RELEASE_RUNBOOK_PATTERN =\n\t/\\bnpm\\s+publish\\b|\\brelease\\b[^\\n]{0,80}\\bv?\\d+\\.\\d+\\.\\d+\\b|릴리즈[^\\n]{0,80}\\d+\\.\\d+\\.\\d+/i;\nconst REVIEW_SCOPE_PATTERN =\n\t/\\b(pr|pull\\s+request|diff|codebase|approach|structure|module\\s+boundary|locking\\s+strategy|abstraction|assumptions?|parser\\s+change|rollback\\s+strategy|concurrent\\s+case|concurrency\\s+plan|hidden\\s+coupling|failure\\s+mode|test\\s+quality|implementation\\s+details|strategy|plan|spec|schema|design|api|coverage|security\\s+posture|licensing|risks?|edge\\s+cases|clarity|consistency|dependencies|third-party|ci\\s+pipeline|threat\\s+model|retry\\s+logic|error\\s+handling\\s+strategy|error\\s+messages?)\\b/i;\nconst REFACTOR_CUE_PATTERN =\n\t/\\b(refactor(?:ing|ed)?|extract|rename|deduplicate|consolidate|modularize|reorganize|simplify|clean\\s*up|tidy\\s+up|restructure|split\\s+module|move\\s+logic|untangle|merge\\s+duplicate)\\b|리팩토링(?!하지\\s*마|하지\\s*말)|리팩터링(?!하지\\s*마|하지\\s*말)|구조\\s*개선/i;\nconst ADD_KEYWORD_PATTERN = /\\badd\\b/i;\nconst LOW_RISK_EDIT_ACTION_PATTERN = /^(?:correct|update|swap|remove|reword|tweak|bump|trim)\\b/i;\n\n/** Short-range compound-clause conjunction boundary. Only bare/compound \"then\"/\"and also\"/\";\" — never bare \"and\". */\nconst COMPOUND_SPLIT_PATTERN = /\\band\\s+then\\b|\\bthen\\b|\\band\\s+also\\b|;/i;\n\n/**\n * Bounded negation-cue vocabulary (spec 008 plan.md \"bounded negation window\").\n * Deliberately excludes bare \"not\" (too broad; verified against the current\n * GOLD_SET that every listed cue here is either absent or occurs AFTER, not\n * before, a tracked keyword — see this lane's evidence file for the audit).\n */\nconst NEGATION_CUE_PATTERN =\n\t/\\b(?:don't|do\\s+not|doesn't|does\\s+not|didn't|did\\s+not|won't|will\\s+not|shouldn't|should\\s+not|wouldn't|would\\s+not|can't|cannot|isn't|is\\s+not|aren't|are\\s+not|never|avoid|skip|without|instead\\s+of|rather\\s+than|no\\s+need\\s+(?:to|for)|no\\s+longer\\s+need(?:\\s+(?:to|for))?)\\b/i;\nconst DIRECT_NOT_OBJECT_CUE_PATTERN_V4 = /\\b(?:not|no)\\s+(?:a\\s+|an\\s+|the\\s+)?$/i;\nconst DOUBLE_NEGATION_RESCUE_PATTERN_V4 =\n\t/\\b(?:don't|do\\s+not|doesn't|does\\s+not|didn't|did\\s+not|won't|will\\s+not|shouldn't|should\\s+not|wouldn't|would\\s+not|can't|cannot)\\s+(?:skip|avoid)\\s+(?:the\\s+|a\\s+|an\\s+)?$/i;\nconst DELIBERATIVE_QUESTION_RESCUE_PATTERN_V4 =\n\t/\\b(?:shouldn't|should\\s+not|wouldn't|would\\s+not|can't|cannot)\\s+(?:we|i|you)\\s*$/i;\nconst POSTPOSITIONED_NEGATION_CUE_PATTERN_V4 =\n\t/^\\s*(?:-\\s*free\\b|(?:is|are|was|were)?\\s*(?:not\\s+(?:needed|required|desired)|unnecessary|not\\s+necessary)|(?:[은는이가을를도만]\\s*)?(?:하지\\s*(?:마(?:라|세요|십시오)?|말(?:고|아|라)?|않(?:아|는|고|을|게)?)|말고|금지))/i;\n\n/** A closed set of clause-boundary characters; a negation cue never reaches across one of these into a prior clause. */\nconst CLAUSE_BOUNDARY_CHARS = [\".\", \"!\", \"?\", \";\", \",\"] as const;\n\nfunction hasCodeFence(text: string): boolean {\n\treturn text.includes(\"```\");\n}\n\n/** Explicit hunk headers or `diff --git` count alone; bare +/- only count together. */\nfunction hasDiffMarkers(text: string): boolean {\n\tif (/^@@[^\\n]*@@/m.test(text) || /^diff --git /m.test(text)) return true;\n\treturn /^\\+(?!\\+)/m.test(text) && /^-(?!-)/m.test(text);\n}\n\nexport interface RouterFeedbackFeaturesV4 {\n\treadonly lenBucket: RouterFeedbackLenBucket;\n\treadonly hadFence: boolean;\n\treadonly hadDiff: boolean;\n}\n\n/** Derive the exact bounded feature tuple used by both classification and learning. */\nexport function deriveRouterFeedbackFeaturesV4(promptText: string): RouterFeedbackFeaturesV4 {\n\tconst prompt = promptText.trim();\n\tlet lenBucket = 0;\n\tlet remaining = prompt.length + 1;\n\twhile (remaining > 1 && lenBucket < 7) {\n\t\tremaining >>= 1;\n\t\tlenBucket++;\n\t}\n\treturn {\n\t\tlenBucket: lenBucket as RouterFeedbackLenBucket,\n\t\thadFence: hasCodeFence(prompt),\n\t\thadDiff: hasDiffMarkers(prompt),\n\t};\n}\n\n/** First line (after stripping one polite prefix), capped at 180 chars. */\n// Non-imperative preamble shapes stripped before ^-anchored intent tests\n// (goal 016/M3+M5): quoted-speech attribution (my teammate said \"...\" but\n// actually: ...) and labeled filler lines (background:/context:/note:).\n// Bounded to 3 repetitions so a wall of filler cannot loop the classifier.\nconst QUOTED_SPEECH_PREFIX_V4 = /^.{0,60}?\\bsaid\\s+\"[^\"]*\"[,.]?\\s*(?:but\\s+actually[,:]?\\s*)?/i;\nconst LABELED_FILLER_PREFIX_V4 = /^(?:background|context|note)\\s*:[^.!?\\n]*[.!?]?\\s*/i;\n\nfunction stripNonImperativePrefixV4(text: string): string {\n\tlet result = text;\n\tfor (let i = 0; i < 3; i++) {\n\t\tconst stripped = result.replace(QUOTED_SPEECH_PREFIX_V4, \"\").replace(LABELED_FILLER_PREFIX_V4, \"\");\n\t\tif (stripped === result) break;\n\t\tresult = stripped;\n\t}\n\treturn result;\n}\n\nfunction firstClause(prompt: string): string {\n\tconst firstLine =\n\t\tstripNonImperativePrefixV4(\n\t\t\tprompt.replace(/^(?:please|pls|can you|could you|would you|help me|i need you to)\\s+/i, \"\"),\n\t\t).split(\"\\n\")[0] ?? \"\";\n\treturn firstLine.slice(0, 180);\n}\n\n// --- Leading-clause intent tests. All are `^`-anchored against the LEADING\n// clause text only, so a negation cue at the start (\"don't refactor...\") can\n// never match one of these: none of the alternations include \"don't\"/\"never\"/\n// etc, so they are negation-immune by construction.\n\nfunction hasLeadingReviewIntent(text: string): boolean {\n\treturn clusterMatchesRoleV4(text, \"review\", \"leading-intent\");\n}\n\nfunction hasLeadingPlanIntent(text: string): boolean {\n\treturn clusterMatchesRoleV4(text, \"plan\", \"leading-intent\");\n}\n\nfunction hasLeadingRefactorIntent(text: string): boolean {\n\treturn clusterMatchesRoleV4(text, \"refactor\", \"leading-intent\");\n}\n\nfunction hasLeadingDebugAction(text: string): boolean {\n\treturn clusterMatchesRoleV4(text, \"debug\", \"leading-intent\");\n}\n\nfunction hasLeadingCodeGenIntent(text: string): boolean {\n\treturn clusterMatchesRoleV4(text, \"code-gen\", \"leading-intent\");\n}\n\nfunction hasLeadingSimpleEditIntent(text: string): boolean {\n\treturn clusterMatchesRoleV4(text, \"simple-edit\", \"leading-intent\");\n}\n\n// --- Quoted-speech masking (goal 016/M3) ---------------------------------\n// A double-quoted span that itself reads as an imperative (\"my teammate said\n// 'implement it'\") is reported speech, not the requester's intent: mask it so\n// it cannot fire whole-prompt evidence. Quoted nouns/objects are preserved\n// (\"fix the 'undefined' error\" keeps its debug signal).\n\nconst QUOTED_SPAN_PATTERN_V4 = /\"([^\"\\n]{1,80})\"/g;\n\nfunction quotedSpanIsImperativeV4(span: string): boolean {\n\tconst text = span.trim();\n\treturn (\n\t\thasLeadingDebugAction(text) ||\n\t\thasLeadingReviewIntent(text) ||\n\t\thasLeadingPlanIntent(text) ||\n\t\thasLeadingRefactorIntent(text) ||\n\t\thasLeadingCodeGenIntent(text) ||\n\t\thasLeadingSimpleEditIntent(text)\n\t);\n}\n\nfunction maskQuotedImperativesV4(text: string): string {\n\treturn text.replace(QUOTED_SPAN_PATTERN_V4, (whole: string, inner: string) =>\n\t\tquotedSpanIsImperativeV4(inner) ? \" \".repeat(whole.length) : whole,\n\t);\n}\n\n// ============================================================================\n// Bounded negation gating\n// ============================================================================\n\ninterface UnnegatedMatchResultV4 {\n\t/** True when the pattern matched at least once and at least one occurrence was NOT preceded by a negation cue. */\n\treadonly matched: boolean;\n\t/** True when the pattern matched at least once but EVERY occurrence was negated (useful for suppressedFeatureIds). */\n\treadonly suppressed: boolean;\n}\n\nconst NO_MATCH_RESULT_V4: UnnegatedMatchResultV4 = { matched: false, suppressed: false };\n\nfunction matchOperationalRunbookV4(prompt: string, windowChars: number): UnnegatedMatchResultV4 {\n\tlet distinctSignals = 0;\n\tlet criticalSignals = 0;\n\tlet sawSuppressed = false;\n\tfor (const { pattern, critical } of OPERATIONAL_RUNBOOK_SIGNAL_PATTERNS) {\n\t\tconst result = matchUnnegated(prompt, pattern, windowChars);\n\t\tif (result.matched) {\n\t\t\tdistinctSignals += 1;\n\t\t\tif (critical) criticalSignals += 1;\n\t\t}\n\t\tif (result.suppressed) sawSuppressed = true;\n\t}\n\tconst explicitRelease = matchUnnegated(prompt, EXPLICIT_RELEASE_RUNBOOK_PATTERN, windowChars).matched;\n\tconst matched = explicitRelease || distinctSignals >= 3 || (criticalSignals >= 2 && distinctSignals >= 2);\n\treturn { matched, suppressed: !matched && sawSuppressed };\n}\n\n/**\n * Negation-aware whole-prompt pattern scan. Finds every occurrence of `pattern`\n * in `prompt`; for each, looks back up to\n * `windowChars` characters (never crossing a `.,;!?` boundary into a prior\n * clause) for a `NEGATION_CUE_PATTERN` hit, and looks forward inside the same\n * bounded window for Hangul-only post-positioned negation cues such as\n * \"하지 말고\". `matched` is true iff at least one occurrence survives\n * un-negated. Deterministic, single pass per pattern, no shared regex state (a\n * fresh global-flag RegExp is constructed per call).\n */\nfunction hasPrePositionedNegationCueV4(scoped: string): boolean {\n\tif (!NEGATION_CUE_PATTERN.test(scoped) && !DIRECT_NOT_OBJECT_CUE_PATTERN_V4.test(scoped)) return false;\n\treturn !DOUBLE_NEGATION_RESCUE_PATTERN_V4.test(scoped) && !DELIBERATIVE_QUESTION_RESCUE_PATTERN_V4.test(scoped);\n}\n\nfunction hasPostPositionedNegationCueV4(prompt: string, matchEnd: number, windowChars: number): boolean {\n\tconst scoped = prompt.slice(matchEnd, Math.min(prompt.length, matchEnd + windowChars));\n\treturn POSTPOSITIONED_NEGATION_CUE_PATTERN_V4.test(scoped);\n}\n\nfunction matchUnnegated(prompt: string, pattern: RegExp, windowChars: number): UnnegatedMatchResultV4 {\n\tconst flags = pattern.flags.includes(\"g\") ? pattern.flags : `${pattern.flags}g`;\n\tconst globalPattern = new RegExp(pattern.source, flags);\n\tlet sawMatch = false;\n\tlet sawUnnegated = false;\n\tlet match = globalPattern.exec(prompt);\n\twhile (match !== null) {\n\t\tsawMatch = true;\n\t\tconst matchStart = match.index;\n\t\tconst windowStart = Math.max(0, matchStart - windowChars);\n\t\tconst windowText = prompt.slice(windowStart, matchStart);\n\t\tlet boundary = -1;\n\t\tfor (const boundaryChar of CLAUSE_BOUNDARY_CHARS) {\n\t\t\tconst idx = windowText.lastIndexOf(boundaryChar);\n\t\t\tif (idx > boundary) boundary = idx;\n\t\t}\n\t\tconst scoped = boundary >= 0 ? windowText.slice(boundary + 1) : windowText;\n\t\tconst preNegated = hasPrePositionedNegationCueV4(scoped);\n\t\tconst postNegated =\n\t\t\t!preNegated && hasPostPositionedNegationCueV4(prompt, matchStart + match[0].length, windowChars);\n\t\tif (!preNegated && !postNegated) sawUnnegated = true;\n\t\tif (match[0].length === 0) globalPattern.lastIndex += 1;\n\t\tmatch = globalPattern.exec(prompt);\n\t}\n\treturn { matched: sawUnnegated, suppressed: sawMatch && !sawUnnegated };\n}\n\nfunction matchClusterUnnegatedV4(\n\tprompt: string,\n\ttaskClass: TaskClassV4,\n\trole: IntentLexemeClusterRoleV4,\n\twindowChars: number,\n): UnnegatedMatchResultV4 {\n\tlet sawSuppressed = false;\n\tfor (const cluster of INTENT_LEXEME_CLUSTERS_V4) {\n\t\tif (cluster.taskClass !== taskClass || cluster.role !== role) continue;\n\t\tfor (const pattern of cluster.phrases) {\n\t\t\tconst result = matchUnnegated(prompt, pattern, windowChars);\n\t\t\tif (result.matched) return { matched: true, suppressed: false };\n\t\t\tif (result.suppressed) sawSuppressed = true;\n\t\t}\n\t}\n\treturn { matched: false, suppressed: sawSuppressed };\n}\n\n// ============================================================================\n// Bounded compound-intent detection\n// ============================================================================\n\ninterface CompoundSecondClauseV4 {\n\treadonly text: string;\n\treadonly startIndex: number;\n}\n\n/**\n * Splits off a bounded second clause after a short-range conjunction\n * (\"then\"/\"and then\"/\"and also\"/\";\"), only when the split point is within the\n * first `COMPOUND_SPLIT_MAX_INDEX_V4` characters (short direct commands, not\n * long prose briefs — verified this never fires inside the GOLD_SET's\n * >=2400-char plan entries). Returns null when no qualifying split exists.\n */\nfunction splitCompoundClauseV4(prompt: string): CompoundSecondClauseV4 | null {\n\tconst match = COMPOUND_SPLIT_PATTERN.exec(prompt);\n\tif (match === null || match.index > COMPOUND_SPLIT_MAX_INDEX_V4) return null;\n\tconst startIndex = match.index + match[0].length;\n\tconst second = prompt.slice(startIndex).trim();\n\tif (second.length < COMPOUND_SECOND_CLAUSE_MIN_CHARS_V4) return null;\n\treturn { text: second, startIndex };\n}\n\nfunction hasFutureSelfClauseV4(clause: string): boolean {\n\treturn /^(?:(?:i|we)(?:'|’)ll\\b|(?:i|we)\\s+will\\b|(?:i|we)(?:'|’)m\\s+going\\s+to\\b|before\\s+(?:i|we)\\b|after\\s+(?:i|we)\\b)/i.test(\n\t\tclause,\n\t);\n}\n\nfunction agentDirectedSecondClauseV4(clause: string): string | null {\n\tif (hasFutureSelfClauseV4(clause)) return null;\n\treturn clause.replace(/^(?:please|pls|also|then|can\\s+you|could\\s+you|would\\s+you|help\\s+me(?:\\s+to)?)\\s+/i, \"\");\n}\n\n/**\n * Leading-intent test for a compound prompt's SECOND clause. Reuses the same\n * `^`-anchored leading-intent tests as the primary clause (so it is equally\n * negation-immune), without the primary clause's diagnosticEvidence/localEdit\n * gating (a short second-clause fragment carries no such context of its own).\n * First-person future/context clauses (\"I'll...\", \"we will...\", \"before I...\")\n * are user context, not an agent-directed second task.\n */\nfunction secondClauseLeadingIntentV4(clause: string): TaskClassV4 | null {\n\tconst agentDirectedClause = agentDirectedSecondClauseV4(clause);\n\tif (agentDirectedClause === null) return null;\n\tconst bounded = agentDirectedClause.slice(0, COMPOUND_SECOND_CLAUSE_SCAN_CHARS_V4);\n\treturn leadingIntentFromLeadingClauseV4(bounded);\n}\n\nfunction leadingIntentFromLeadingClauseV4(leading: string): TaskClassV4 | null {\n\tif (hasLeadingDebugAction(leading)) return \"debug\";\n\tif (hasLeadingReviewIntent(leading)) return \"review\";\n\tif (hasLeadingPlanIntent(leading)) return \"plan\";\n\tif (hasLeadingRefactorIntent(leading)) return \"refactor\";\n\tif (hasLeadingSimpleEditIntent(leading)) return \"simple-edit\";\n\tif (hasLeadingCodeGenIntent(leading)) return \"code-gen\";\n\treturn null;\n}\n\nfunction leadingIntentIsPostNegatedV4(leading: string, windowChars: number): boolean {\n\tconst leadingIntentMatch =\n\t\t/^(?:debug|investigate\\s+why|reproduce|trace\\b|fix\\s+this\\s+(?:traceback|panic|error)|review|audit(?!\\s+log\\b)|critique|inspect|assess|approve|double-?check|lgtm|plan|design|architect|decompose|write\\s+(?:a\\s+)?(?:technical\\s+)?(?:spec|roadmap|strategy|plan)|create\\s+(?:a\\s+)?(?:technical\\s+)?(?:spec|roadmap|strategy|plan)|refactor(?:ing|ed)?|extract|rename|deduplicate|consolidate|modularize|reorganize|simplify|restructure|untangle|clean\\s+up|split\\s+(?:the\\s+)?module|move\\s+logic|correct|update|swap|remove|adjust|fix|add|change|trim|reword|tweak|bump|implement|build|generate|scaffold|prototype)\\b/i.exec(\n\t\t\tleading,\n\t\t);\n\treturn (\n\t\tleadingIntentMatch !== null && hasPostPositionedNegationCueV4(leading, leadingIntentMatch[0].length, windowChars)\n\t);\n}\n\nfunction classifyShortKoreanZeroScoreTaskV4(prompt: string, windowChars: number): TaskClassV4 | null {\n\tconst generalizedEvidence = extractGeneralizedIntentEvidenceV4(prompt);\n\tfor (const taskClass of TASK_CLASSES_V4) {\n\t\tif (generalizedEvidence.skeletonMatch[taskClass]) return taskClass;\n\t}\n\tif (matchClusterUnnegatedV4(prompt, \"debug\", \"korean-morphology\", windowChars).matched) return \"debug\";\n\tif (matchClusterUnnegatedV4(prompt, \"simple-edit\", \"korean-morphology\", windowChars).matched) return \"simple-edit\";\n\tif (matchClusterUnnegatedV4(prompt, \"review\", \"korean-morphology\", windowChars).matched) return \"review\";\n\tif (matchClusterUnnegatedV4(prompt, \"plan\", \"korean-morphology\", windowChars).matched) return \"plan\";\n\tif (matchClusterUnnegatedV4(prompt, \"refactor\", \"korean-morphology\", windowChars).matched) return \"refactor\";\n\tif (matchClusterUnnegatedV4(prompt, \"code-gen\", \"korean-morphology\", windowChars).matched) return \"code-gen\";\n\tfor (const taskClass of TASK_CLASSES_V4) {\n\t\tif (generalizedEvidence.clusterMatch[taskClass]) return taskClass;\n\t}\n\treturn null;\n}\n\n// ============================================================================\n// Feature extraction\n// ============================================================================\n\ninterface ContextualFeaturesV4 {\n\treadonly firstClause: string;\n\treadonly codeFence: boolean;\n\treadonly diffHunk: boolean;\n\treadonly localEdit: boolean;\n\treadonly diagnosticEvidence: boolean;\n\treadonly reviewScope: boolean;\n\treadonly planBrief: boolean;\n\treadonly operationalRunbook: boolean;\n\treadonly refactorCue: boolean;\n\treadonly implementationObject: boolean;\n\treadonly codeGenArtifactRequest: boolean;\n\treadonly evaluativeReviewObject: boolean;\n\treadonly leadingIntent: TaskClassV4 | null;\n\treadonly secondClauseIntent: TaskClassV4 | null;\n\treadonly compoundIntent: boolean;\n\treadonly keywordFamilyMatch: Readonly<Record<TaskClassV4, boolean>>;\n\treadonly normalizedIntentClusterMatch: Readonly<Record<TaskClassV4, boolean>>;\n\treadonly intentSkeletonMatch: Readonly<Record<TaskClassV4, boolean>>;\n\treadonly generalizedEvidenceCount: Readonly<Record<TaskClassV4, number>>;\n\treadonly addKeywordMatch: boolean;\n}\n\ninterface LeadingIntentInputV4 {\n\treadonly firstClause: string;\n\treadonly localEdit: boolean;\n\treadonly diagnosticEvidence: boolean;\n}\n\n/** Decision order for the leading intent classifier. */\nfunction leadingIntentV4(input: LeadingIntentInputV4): TaskClassV4 | null {\n\tif (\n\t\tinput.diagnosticEvidence &&\n\t\t(hasLeadingDebugAction(input.firstClause) || hasLeadingSimpleEditIntent(input.firstClause))\n\t)\n\t\treturn \"debug\";\n\tif (hasLeadingReviewIntent(input.firstClause)) return \"review\";\n\tif (hasLeadingPlanIntent(input.firstClause)) return \"plan\";\n\tif (hasLeadingRefactorIntent(input.firstClause)) return \"refactor\";\n\tif (input.localEdit && hasLeadingSimpleEditIntent(input.firstClause)) return \"simple-edit\";\n\tif (!input.localEdit && hasLeadingCodeGenIntent(input.firstClause)) return \"code-gen\";\n\treturn null;\n}\n\n/** Diagnostic-evidence decision structure, parameterized over precomputed negation-aware matches. */\nfunction hasDiagnosticEvidenceV4(\n\tleading: string,\n\thardDiagnosticMatched: boolean,\n\tbugObjectMatched: boolean,\n\tgenericDiagnosticMatched: boolean,\n\tnonDiagnosticContext: boolean,\n): boolean {\n\tif (hasLeadingDebugAction(leading) || hardDiagnosticMatched) return true;\n\tconst hasContextualDiagnostic = bugObjectMatched || (genericDiagnosticMatched && !nonDiagnosticContext);\n\tif (!hasContextualDiagnostic) return false;\n\treturn !hasLeadingReviewIntent(leading) && !hasLeadingPlanIntent(leading) && !hasLeadingRefactorIntent(leading);\n}\n\ntype GeneralizedIntentEvidenceV4 = ReturnType<typeof extractGeneralizedIntentEvidenceV4>;\n\nfunction isDeferredClassV4(evidence: GeneralizedIntentEvidenceV4, taskClass: TaskClassV4): boolean {\n\treturn evidence.deferredClasses.includes(taskClass);\n}\n\nfunction suppressGeneralizedClassesV4(\n\tevidence: GeneralizedIntentEvidenceV4,\n\tsuppressedClasses: readonly TaskClassV4[],\n): GeneralizedIntentEvidenceV4 {\n\tif (suppressedClasses.length === 0) return evidence;\n\tconst clusterMatch = { ...evidence.clusterMatch };\n\tconst skeletonMatch = { ...evidence.skeletonMatch };\n\tfor (const taskClass of suppressedClasses) {\n\t\tclusterMatch[taskClass] = false;\n\t\tskeletonMatch[taskClass] = false;\n\t}\n\treturn { ...evidence, clusterMatch, skeletonMatch };\n}\n\nfunction countGeneralizedEvidenceV4(evidence: GeneralizedIntentEvidenceV4): Record<TaskClassV4, number> {\n\tconst counts = emptyScoresV4();\n\tfor (const taskClass of TASK_CLASSES_V4) {\n\t\tcounts[taskClass] = (evidence.clusterMatch[taskClass] ? 1 : 0) + (evidence.skeletonMatch[taskClass] ? 1 : 0);\n\t}\n\treturn counts;\n}\n\n/**\n * Extracts every v4 feature from one prompt, negation-gating every\n * whole-prompt scan exactly once and recording a `negation:<channel>` id in\n * `suppressed` whenever a match existed but every occurrence was negated.\n */\nfunction extractFeaturesV4(\n\tprompt: string,\n\tweights: RouterWeightsV4,\n\tsuppressed: string[],\n\tfeedbackFeatures: RouterFeedbackFeaturesV4 = deriveRouterFeedbackFeaturesV4(prompt),\n): ContextualFeaturesV4 {\n\tconst leading = firstClause(prompt);\n\tconst window = weights.negationWindowChars;\n\tconst secondClause = splitCompoundClauseV4(prompt);\n\tconst agentSignalPrompt = maskQuotedImperativesV4(\n\t\tsecondClause !== null && hasFutureSelfClauseV4(secondClause.text)\n\t\t\t? prompt.slice(0, secondClause.startIndex).trim()\n\t\t\t: prompt,\n\t);\n\tconst generalizedEvidence = extractGeneralizedIntentEvidenceV4(agentSignalPrompt);\n\tconst shortKoreanPrompt = prompt.length < TRIVIAL_MAX_CHARS_V4 && /[가-힣]/.test(prompt);\n\tconst shortKoreanDebugFallbackOnly =\n\t\tshortKoreanPrompt &&\n\t\t(generalizedEvidence.clusterMatch.debug || generalizedEvidence.skeletonMatch.debug) &&\n\t\t!generalizedEvidence.clusterMatch.refactor &&\n\t\t!generalizedEvidence.skeletonMatch.refactor &&\n\t\t!generalizedEvidence.clusterMatch.review &&\n\t\t!generalizedEvidence.skeletonMatch.review;\n\tconst scoredGeneralizedEvidence = suppressGeneralizedClassesV4(\n\t\tgeneralizedEvidence,\n\t\tshortKoreanDebugFallbackOnly\n\t\t\t? [...generalizedEvidence.deferredClasses, \"debug\"]\n\t\t\t: generalizedEvidence.deferredClasses,\n\t);\n\tfor (const taskClass of generalizedEvidence.deferredClasses) suppressed.push(`deferral:${taskClass}`);\n\n\tconst implementationObjectResult = matchUnnegated(agentSignalPrompt, IMPLEMENTATION_OBJECT_PATTERN, window);\n\tif (implementationObjectResult.suppressed) suppressed.push(\"negation:implementation-object\");\n\tconst implementationObject = !shortKoreanDebugFallbackOnly && implementationObjectResult.matched;\n\n\tconst codeGenArtifactResult = matchClusterUnnegatedV4(agentSignalPrompt, \"code-gen\", \"object-shape\", window);\n\tif (codeGenArtifactResult.suppressed) suppressed.push(\"negation:code-gen-artifact-request\");\n\tconst codeGenArtifactRequest = codeGenArtifactResult.matched;\n\n\tconst lowRiskEditAction = LOW_RISK_EDIT_ACTION_PATTERN.test(leading);\n\tconst localEditObjectResult = matchUnnegated(agentSignalPrompt, LOCAL_EDIT_OBJECT_PATTERN, window);\n\tif (localEditObjectResult.suppressed) suppressed.push(\"negation:local-edit-object\");\n\tconst localEditActionResult = matchUnnegated(agentSignalPrompt, LOCAL_EDIT_ACTION_OBJECT_PATTERN, window);\n\tif (localEditActionResult.suppressed) suppressed.push(\"negation:local-edit-action-object\");\n\tconst localEdit =\n\t\t!implementationObject &&\n\t\t!scoredGeneralizedEvidence.clusterMatch.review &&\n\t\t!scoredGeneralizedEvidence.skeletonMatch.review &&\n\t\t(lowRiskEditAction || localEditObjectResult.matched || localEditActionResult.matched);\n\n\tconst hardDiagnosticResult = matchUnnegated(agentSignalPrompt, HARD_DIAGNOSTIC_PATTERN, window);\n\tif (hardDiagnosticResult.suppressed) suppressed.push(\"negation:hard-diagnostic\");\n\tconst bugObjectResult = matchUnnegated(agentSignalPrompt, BUG_OBJECT_PATTERN, window);\n\tif (bugObjectResult.suppressed) suppressed.push(\"negation:bug-object\");\n\tconst genericDiagnosticResult = matchUnnegated(agentSignalPrompt, GENERIC_DIAGNOSTIC_PATTERN, window);\n\tconst nonDiagnosticContext = NON_DIAGNOSTIC_DEBUG_CONTEXT_PATTERN.test(agentSignalPrompt);\n\tif (genericDiagnosticResult.suppressed && !nonDiagnosticContext) suppressed.push(\"negation:generic-diagnostic\");\n\tconst diagnosticEvidence =\n\t\t!isDeferredClassV4(generalizedEvidence, \"debug\") &&\n\t\thasDiagnosticEvidenceV4(\n\t\t\tleading,\n\t\t\thardDiagnosticResult.matched,\n\t\t\tbugObjectResult.matched,\n\t\t\tgenericDiagnosticResult.matched,\n\t\t\tnonDiagnosticContext,\n\t\t);\n\n\tconst reviewScopeResult = matchUnnegated(agentSignalPrompt, REVIEW_SCOPE_PATTERN, window);\n\tif (reviewScopeResult.suppressed) suppressed.push(\"negation:review-scope\");\n\tconst reviewScope =\n\t\t!isDeferredClassV4(generalizedEvidence, \"review\") && hasLeadingReviewIntent(leading) && reviewScopeResult.matched;\n\n\tconst planBriefResult = matchUnnegated(agentSignalPrompt, PLAN_BRIEF_PATTERN, window);\n\tif (planBriefResult.suppressed) suppressed.push(\"negation:plan-brief\");\n\tconst planBrief =\n\t\t!isDeferredClassV4(generalizedEvidence, \"plan\") &&\n\t\thasLeadingPlanIntent(leading) &&\n\t\t(planBriefResult.matched || prompt.length >= LONG_BRIEF_MIN_CHARS_V4);\n\n\tconst operationalRunbookResult = matchOperationalRunbookV4(agentSignalPrompt, window);\n\tif (operationalRunbookResult.suppressed) suppressed.push(\"negation:operational-runbook\");\n\tconst operationalRunbook = operationalRunbookResult.matched;\n\n\tconst refactorCueResult = matchUnnegated(agentSignalPrompt, REFACTOR_CUE_PATTERN, window);\n\tif (refactorCueResult.suppressed) suppressed.push(\"negation:refactor-cue\");\n\tconst refactorCue = !isDeferredClassV4(generalizedEvidence, \"refactor\") && refactorCueResult.matched;\n\n\tconst rawPrimaryIntent = leadingIntentV4({ firstClause: leading, localEdit, diagnosticEvidence });\n\tconst primaryIntent =\n\t\trawPrimaryIntent !== null &&\n\t\t(leadingIntentIsPostNegatedV4(leading, window) || isDeferredClassV4(generalizedEvidence, rawPrimaryIntent))\n\t\t\t? null\n\t\t\t: rawPrimaryIntent;\n\n\tconst secondClauseIntent = secondClause === null ? null : secondClauseLeadingIntentV4(secondClause.text);\n\tconst compoundIntent = secondClauseIntent !== null && secondClauseIntent !== primaryIntent;\n\n\tconst debugKeywordResult = diagnosticEvidence\n\t\t? matchClusterUnnegatedV4(agentSignalPrompt, \"debug\", \"whole-prompt\", window)\n\t\t: NO_MATCH_RESULT_V4;\n\tif (debugKeywordResult.suppressed) suppressed.push(\"negation:keyword-debug\");\n\n\tconst reviewKeywordResult = isDeferredClassV4(generalizedEvidence, \"review\")\n\t\t? NO_MATCH_RESULT_V4\n\t\t: matchClusterUnnegatedV4(agentSignalPrompt, \"review\", \"whole-prompt\", window);\n\tif (reviewKeywordResult.suppressed) suppressed.push(\"negation:keyword-review\");\n\n\tconst planKeywordResult = isDeferredClassV4(generalizedEvidence, \"plan\")\n\t\t? NO_MATCH_RESULT_V4\n\t\t: matchClusterUnnegatedV4(agentSignalPrompt, \"plan\", \"whole-prompt\", window);\n\tif (planKeywordResult.suppressed) suppressed.push(\"negation:keyword-plan\");\n\n\tconst codeGenKeywordResult = matchClusterUnnegatedV4(agentSignalPrompt, \"code-gen\", \"whole-prompt\", window);\n\tif (codeGenKeywordResult.suppressed) suppressed.push(\"negation:keyword-code-gen\");\n\n\tconst evaluativeReviewResult =\n\t\t!isDeferredClassV4(generalizedEvidence, \"review\") && hasLeadingReviewIntent(leading)\n\t\t\t? matchClusterUnnegatedV4(agentSignalPrompt, \"review\", \"object-shape\", window)\n\t\t\t: NO_MATCH_RESULT_V4;\n\tif (evaluativeReviewResult.suppressed) suppressed.push(\"negation:evaluative-review-object\");\n\tconst evaluativeReviewObject = evaluativeReviewResult.matched;\n\n\tconst addKeywordResult = localEdit\n\t\t? NO_MATCH_RESULT_V4\n\t\t: matchUnnegated(agentSignalPrompt, ADD_KEYWORD_PATTERN, window);\n\tif (addKeywordResult.suppressed) suppressed.push(\"negation:add-keyword\");\n\n\treturn {\n\t\tfirstClause: leading,\n\t\tcodeFence: feedbackFeatures.hadFence,\n\t\tdiffHunk: feedbackFeatures.hadDiff,\n\t\tlocalEdit,\n\t\tdiagnosticEvidence,\n\t\treviewScope,\n\t\tplanBrief,\n\t\toperationalRunbook,\n\t\trefactorCue,\n\t\timplementationObject,\n\t\tcodeGenArtifactRequest,\n\t\tevaluativeReviewObject,\n\t\tleadingIntent: primaryIntent,\n\t\tsecondClauseIntent,\n\t\tcompoundIntent,\n\t\tkeywordFamilyMatch: {\n\t\t\ttrivial: false,\n\t\t\tdebug: debugKeywordResult.matched,\n\t\t\trefactor: refactorCue,\n\t\t\treview: reviewKeywordResult.matched,\n\t\t\tplan: planKeywordResult.matched,\n\t\t\t\"simple-edit\": localEditObjectResult.matched,\n\t\t\t\"code-gen\": codeGenKeywordResult.matched,\n\t\t},\n\t\tnormalizedIntentClusterMatch: scoredGeneralizedEvidence.clusterMatch,\n\t\tintentSkeletonMatch: scoredGeneralizedEvidence.skeletonMatch,\n\t\tgeneralizedEvidenceCount: countGeneralizedEvidenceV4(scoredGeneralizedEvidence),\n\t\taddKeywordMatch: addKeywordResult.matched,\n\t};\n}\n\n// ============================================================================\n// Scoring\n// ============================================================================\n\nfunction emptyScoresV4(): Record<TaskClassV4, number> {\n\treturn {\n\t\ttrivial: 0,\n\t\t\"simple-edit\": 0,\n\t\t\"code-gen\": 0,\n\t\tdebug: 0,\n\t\trefactor: 0,\n\t\treview: 0,\n\t\tplan: 0,\n\t};\n}\n\nfunction computeScoresV4(features: ContextualFeaturesV4, weights: RouterWeightsV4): Record<TaskClassV4, number> {\n\tconst scores = emptyScoresV4();\n\tif (features.codeFence || features.diffHunk) scores[\"code-gen\"] += weights.codeFenceOrDiff;\n\tif (features.leadingIntent !== null) scores[features.leadingIntent] += weights.leadingIntent;\n\tif (features.secondClauseIntent !== null) scores[features.secondClauseIntent] += weights.secondClauseIntent;\n\tif (features.localEdit) scores[\"simple-edit\"] += weights.localEdit;\n\tif (features.diagnosticEvidence) scores.debug += weights.diagnosticEvidence;\n\tif (features.reviewScope) scores.review += weights.reviewScope;\n\tif (features.planBrief) scores.plan += weights.planBrief;\n\tif (features.operationalRunbook) scores.plan += weights.operationalRunbook;\n\tif (features.refactorCue) scores.refactor += weights.refactorCue;\n\tif (features.implementationObject) scores[\"code-gen\"] += weights.implementationObject;\n\tif (features.codeGenArtifactRequest) scores[\"code-gen\"] += weights.codeGenArtifactRequest;\n\tif (features.evaluativeReviewObject) scores.review += weights.evaluativeReviewObject;\n\n\tfor (const taskClass of TASK_CLASSES_V4) {\n\t\tif (features.keywordFamilyMatch[taskClass]) scores[taskClass] += weights.keywordFamily[taskClass];\n\t\tif (features.normalizedIntentClusterMatch[taskClass]) scores[taskClass] += weights.normalizedIntentCluster;\n\t\tif (features.intentSkeletonMatch[taskClass]) scores[taskClass] += weights.intentSkeleton;\n\t}\n\tif (features.addKeywordMatch) scores[\"code-gen\"] += weights.addKeyword;\n\n\treturn scores;\n}\n\n/**\n * Extension signals (history / context-pressure / judge vote). The released\n * default coefficients are bounded and nonzero, but apply only after the base\n * scorer finds prompt evidence. This keeps zero-score fallback decisions under\n * the fallback cascade rather than an unrelated prior or vote.\n */\nfunction applyExtensionSignalsV4(\n\tscores: Record<TaskClassV4, number>,\n\tinput: TaskClassifierInputV4,\n\tweights: RouterWeightsV4,\n): void {\n\t// Gate (goal 016/L2): extension votes apply only when a real signal already\n\t// exists. On a zero-score state the fallback cascade (trivial-length,\n\t// ko-short, long-prose, lane) owns the verdict — a stray history/judge vote\n\t// must not hijack it (measured: any weight >= 1 flips gold-0001 \"hi\" to the\n\t// voted class otherwise). The gate keeps the bounded nonzero defaults from\n\t// taking authority over an evidence-free fallback.\n\tlet topScore = 0;\n\tfor (const c of TASK_CLASSES_V4) topScore = Math.max(topScore, scores[c]);\n\tif (topScore <= 0) return;\n\n\tconst priorClass = input.history !== undefined && input.history.length > 0 ? input.history[0] : null;\n\tif (priorClass !== null && weights.multiTurnPrior !== 0) scores[priorClass] += weights.multiTurnPrior;\n\n\tconst judgeVote = input.judgeVote ?? null;\n\tif (judgeVote !== null && weights.judgeVote !== 0) scores[judgeVote] += weights.judgeVote;\n\n\tconst pressureBucket = input.pressureBucket ?? 0;\n\tif (pressureBucket > 0 && weights.pressureBucket !== 0) {\n\t\tconst bump = pressureBucket * weights.pressureBucket;\n\t\tscores.debug += bump;\n\t\tscores.review += bump;\n\t\tscores.plan += bump;\n\t}\n}\n\nfunction clampConfidenceV4(value: number): number {\n\treturn Math.max(0, Math.min(1, value));\n}\n\nfunction confidenceEvidenceStrengthV4(topScore: number, margin: number, weights: RouterWeightsV4): number {\n\tif (topScore <= 0) return 0;\n\tconst separation = clampConfidenceV4(margin / topScore);\n\tconst evidenceFloor = weights.leadingIntent > 0 ? weights.leadingIntent : 1;\n\treturn Math.min(separation, clampConfidenceV4(topScore / evidenceFloor));\n}\n\n// ============================================================================\n// Public types\n// ============================================================================\n\n/**\n * Caller-supplied turn input. Identical shape to `TaskClassifierInputV3` /\n * `TaskClassifierInputV2` (prompt + optional lane/history/pressure/judge\n * slots), so existing callers can switch versions without reshaping data.\n */\nexport interface TaskClassifierInputV4 {\n\tprompt: string;\n\tlaneType?: ReasoningLaneTypeV4;\n\thistory?: readonly TaskClassV4[];\n\tpressureBucket?: number;\n\tjudgeVote?: TaskClassV4 | null;\n}\n\n/** Confidence band derived from score separation plus absolute evidence strength. */\nexport type ConfidenceBandV4 = \"low\" | \"medium\" | \"high\";\n\n/** Which branch of the zero-score fallback cascade decided `taskClass`; null when a real weighted signal decided it. */\nexport type FallbackReasonV4 =\n\t| \"code-fence-or-diff\"\n\t| \"trivial-length\"\n\t| \"ko-short-task-signal\"\n\t| \"long-prose\"\n\t| \"lane-fallback\"\n\t| \"default\";\n\n/**\n * The full, privacy-safe classification verdict (spec 008 Req 2). Every field\n * is a bounded enum, number, boolean, or a closed set of short diagnostic-id\n * strings (`suppressedFeatureIds`) — never raw prompt text, so this value is\n * safe to pass to evaluation, learning, and Adaptorch-advisory code.\n */\nexport interface ClassifierVerdictV4 {\n\t/** The decided task class (post zero-score-cascade if one fired). */\n\treadonly taskClass: TaskClassV4;\n\t/** Raw per-class score map from the weighted signals (pre-cascade; audit-only). */\n\treadonly scores: Readonly<Record<TaskClassV4, number>>;\n\t/** Second-highest-scoring class by the argmax, or null if every other class tied at the bottom. */\n\treadonly runnerUp: TaskClassV4 | null;\n\t/** `scores[argmaxClass] - scores[runnerUp]` (pre-cascade); 0 or negative-margin-free by construction (weights are non-negative). */\n\treadonly margin: number;\n\t/** Normalized confidence in [0, 1], combining `margin / topScore` with absolute evidence strength. */\n\treadonly confidence: number;\n\t/** Confidence bucketed by `weights.lowConfidenceThreshold` / `highConfidenceThreshold`. */\n\treadonly confidenceBand: ConfidenceBandV4;\n\t/** True when the argmax class won only via precedence-order tie-break over an exact score tie with the runner-up. */\n\treadonly tieBreak: boolean;\n\t/** Non-null exactly when the zero-score cascade (not a real weighted signal) decided `taskClass`. */\n\treadonly fallbackReason: FallbackReasonV4 | null;\n\t/** Audit trail of `negation:<channel>` ids for every whole-prompt signal that had a match but was fully negated. */\n\treadonly suppressedFeatureIds: readonly string[];\n\t/** True when a distinct second-clause leading intent was detected (bounded compound-intent detection). */\n\treadonly compoundIntent: boolean;\n\t/** The second clause's own leading intent, or null when no compound structure (or no distinct intent) was found. */\n\treadonly secondClauseIntent: TaskClassV4 | null;\n}\n\n// ============================================================================\n// Classifier\n// ============================================================================\n\n/**\n * Deterministic confidence-bearing classifier (spec 008 Req 2).\n *\n * Pipeline: extract negation/compound-aware contextual features -> score every\n * class from `weights` -> argmax with `TASK_CLASSES_V4` precedence tie-break,\n * tracking the runner-up -> compute margin/confidence/confidenceBand/tieBreak\n * from RAW score separation plus evidence strength -> if `topScore <= 0`, replace `taskClass` (and record\n * `fallbackReason`) via the zero-score cascade (fence/diff -> code-gen;\n * length < 40 -> trivial; length >= 2400 -> plan; lane fallback; default\n * code-gen) — the raw scores/margin/runnerUp/tieBreak fields still reflect the\n * pre-cascade computation, for audit purposes.\n *\n * Pure: same (input, weights) -> same ClassifierVerdictV4.\n */\nexport function classifyTaskV4(\n\tinput: TaskClassifierInputV4,\n\tweights: RouterWeightsV4 = DEFAULT_WEIGHTS_V4,\n\tfeedbackFeatures?: RouterFeedbackFeaturesV4,\n): ClassifierVerdictV4 {\n\tconst prompt = input.prompt.trim();\n\tconst suppressed: string[] = [];\n\tconst features = extractFeaturesV4(prompt, weights, suppressed, feedbackFeatures);\n\tconst scores = computeScoresV4(features, weights);\n\tapplyExtensionSignalsV4(scores, input, weights);\n\n\tlet top: TaskClassV4 = TASK_CLASSES_V4[0];\n\tfor (const c of TASK_CLASSES_V4) {\n\t\tif (scores[c] > scores[top]) top = c;\n\t}\n\tlet runnerUp: TaskClassV4 | null = null;\n\tfor (const c of TASK_CLASSES_V4) {\n\t\tif (c === top) continue;\n\t\tif (runnerUp === null || scores[c] > scores[runnerUp]) runnerUp = c;\n\t}\n\n\tconst topScore = scores[top];\n\tconst runnerUpScore = runnerUp !== null ? scores[runnerUp] : 0;\n\tconst margin = topScore - runnerUpScore;\n\tconst tieBreak = runnerUp !== null && topScore === runnerUpScore;\n\tconst rawConfidence = confidenceEvidenceStrengthV4(topScore, margin, weights);\n\tconst singleGeneralizedEvidence =\n\t\tfeatures.generalizedEvidenceCount[top] === 1 &&\n\t\ttopScore <= Math.max(weights.normalizedIntentCluster, weights.intentSkeleton);\n\tconst confidence = singleGeneralizedEvidence\n\t\t? Math.min(rawConfidence, Math.max(0, weights.highConfidenceThreshold - 0.01))\n\t\t: rawConfidence;\n\tconst confidenceBand: ConfidenceBandV4 =\n\t\tconfidence <= weights.lowConfidenceThreshold\n\t\t\t? \"low\"\n\t\t\t: confidence >= weights.highConfidenceThreshold\n\t\t\t\t? \"high\"\n\t\t\t\t: \"medium\";\n\n\tlet taskClass: TaskClassV4 = top;\n\tlet fallbackReason: FallbackReasonV4 | null = null;\n\tif (topScore <= 0) {\n\t\tif (features.codeFence || features.diffHunk) {\n\t\t\ttaskClass = \"code-gen\";\n\t\t\tfallbackReason = \"code-fence-or-diff\";\n\t\t} else {\n\t\t\t// Hangul zero-score prompts route by morphology at ANY length, not just\n\t\t\t// short ones: previously a >40-char Korean edit request fell through to\n\t\t\t// the code-gen default even when a morphology cluster matched. (016)\n\t\t\tconst koreanTaskClass = /[가-힣]/.test(prompt)\n\t\t\t\t? classifyShortKoreanZeroScoreTaskV4(prompt, weights.negationWindowChars)\n\t\t\t\t: null;\n\t\t\tif (koreanTaskClass !== null) {\n\t\t\t\ttaskClass = koreanTaskClass;\n\t\t\t\tfallbackReason = \"ko-short-task-signal\";\n\t\t\t} else if (prompt.length < TRIVIAL_MAX_CHARS_V4) {\n\t\t\t\ttaskClass = \"trivial\";\n\t\t\t\tfallbackReason = \"trivial-length\";\n\t\t\t} else if (prompt.length >= COMPLEX_PROSE_MIN_CHARS_V4) {\n\t\t\t\ttaskClass = \"plan\";\n\t\t\t\tfallbackReason = \"long-prose\";\n\t\t\t} else if (input.laneType !== undefined) {\n\t\t\t\ttaskClass = LANE_FALLBACK_CLASS_V4[input.laneType];\n\t\t\t\tfallbackReason = \"lane-fallback\";\n\t\t\t} else {\n\t\t\t\ttaskClass = \"code-gen\";\n\t\t\t\tfallbackReason = \"default\";\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\ttaskClass,\n\t\tscores,\n\t\trunnerUp,\n\t\tmargin,\n\t\tconfidence,\n\t\tconfidenceBand,\n\t\ttieBreak,\n\t\tfallbackReason,\n\t\tsuppressedFeatureIds: suppressed,\n\t\tcompoundIntent: features.compoundIntent,\n\t\tsecondClauseIntent: features.secondClauseIntent,\n\t};\n}\n\n// ============================================================================\n// Resolver\n// ============================================================================\n\n/**\n * Static rule table: task class -> recommended ThinkingLevel. Re-exported\n * from the shared resolver core (byte-identical values; previously a\n * duplicated literal here — see reasoning-router-resolver.ts).\n */\nexport const TASK_CLASS_THINKING_LEVELS_V4 = TASK_CLASS_THINKING_LEVELS;\n\n/**\n * Bounded, strictly non-negative escalation applied when the verdict's own\n * confidence is low or a fallback (not a real signal) decided the class. This\n * is the ONLY place confidence touches the target index, and it can only add:\n * confidence can never lower effort (spec 008 Req 2 acceptance criterion).\n */\nconst LOW_CONFIDENCE_ESCALATION_STEPS_V4 = 1;\n\n/**\n * Thin auto-mode wrapper with no uncertainty adjustment: base rule table ->\n * lane step -> clamp to availableLevels. This is v4's \"confident\" path and\n * delegates to the shared resolver core with bias=0, hint=null, escalationSteps=0.\n */\nexport function resolveThinkingLevelV4ForAuto(\n\ttaskClass: TaskClassV4,\n\tavailableLevels: readonly ThinkingLevel[],\n\tlaneType: ReasoningLaneTypeV4 | undefined,\n): ThinkingLevel {\n\treturn resolveThinkingLevelCore(taskClass, availableLevels, laneType, 0, null, 0);\n}\n\n/**\n * Uncertainty-aware resolver (spec 008 Req 2 / plan.md step 5).\n *\n * Pipeline: base rule table for `verdict.taskClass` -> lane step -> bounded\n * bias [-2,+2] -> optional hint fusion (±2 bounded) -> bounded\n * non-negative confidence escalation (+1 ladder step exactly when\n * `verdict.confidenceBand === \"low\"` or `verdict.fallbackReason !== null`) ->\n * clamp to `availableLevels`.\n *\n * The confidence-escalation term is strictly `>= 0`: at a fixed bias and\n * hint, a low-confidence verdict resolves at or above the same verdict at\n * high confidence — text alone cannot talk the resolver down. That is the\n * whole guarantee. It is not a floor at the class base level: a negative\n * learning bias is applied before the +1 escalation, so `debug` with\n * `bias=-2` still resolves to `medium`, below the `high` that\n * `resolveThinkingLevelV4ForAuto` returns. A policy that must never drop\n * below the base level needs an explicit safety floor, not this term.\n */\nexport function resolveThinkingLevelV4WithUncertainty(\n\tverdict: ClassifierVerdictV4,\n\tavailableLevels: readonly ThinkingLevel[],\n\tlaneType: ReasoningLaneTypeV4 | undefined,\n\tbias = 0,\n\thint: { level: ThinkingLevel; confidence: number } | null = null,\n): ThinkingLevel {\n\tconst escalationSteps =\n\t\tverdict.confidenceBand === \"low\" || verdict.fallbackReason !== null ? LOW_CONFIDENCE_ESCALATION_STEPS_V4 : 0;\n\treturn resolveThinkingLevelCore(verdict.taskClass, availableLevels, laneType, bias, hint, escalationSteps);\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  import type { Api, Message, Model } from "omk-ai";
2
+ import { type CompactionControlState } from "./compaction/control-state.ts";
2
3
  import type { CompactionResult } from "./compaction/index.ts";
3
4
  import { type CompactionBarrierResult, type CompactionEnvelope, type CompactionPreservedProvenanceInput, type CompactionSourceIdentity, type CompactionTransaction } from "./compaction/transaction.ts";
4
5
  import type { SessionIntegrityReport } from "./session-integrity.ts";
@@ -8,6 +9,13 @@ export interface CapturedCompactionState {
8
9
  readonly branchEntries: readonly SessionEntry[];
9
10
  readonly revision: CompactionTransaction["baseRevision"];
10
11
  readonly source: CompactionSourceIdentity;
12
+ /**
13
+ * Digest of the host control-state snapshot captured under the same commit
14
+ * lock as `source`. `null` when no control authority is attached. A change
15
+ * between capture and commit discards the summary like a source mismatch.
16
+ */
17
+ readonly controlStateDigest: string | null;
18
+ readonly controlState: CompactionControlState | null;
11
19
  }
12
20
  export interface BegunCompaction {
13
21
  readonly capture: CapturedCompactionState;
@@ -22,6 +30,13 @@ export interface SessionCompactionServiceDeps {
22
30
  readonly pendingToolCallIds: () => ReadonlySet<string>;
23
31
  readonly getUserMessageText: (message: Message) => string;
24
32
  readonly cwd: string;
33
+ /**
34
+ * Optional host control authority. Called inside the compaction commit lock
35
+ * so the snapshot is bound to the same captured source as the summary. Must
36
+ * be deterministic for unchanged state — a changed snapshot discards the
37
+ * in-flight summary at commit. Return `null` only when no authority exists.
38
+ */
39
+ readonly controlState?: () => CompactionControlState | null;
25
40
  readonly invalidateContextBudget: () => void;
26
41
  /** Refresh agent messages from the session manager after tail repair/commit. */
27
42
  readonly refreshAgentMessages: () => void;
@@ -1 +1 @@
1
- {"version":3,"file":"session-compaction-service.d.ts","sourceRoot":"","sources":["../../src/core/session-compaction-service.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,KAAK,EAAqB,MAAM,QAAQ,CAAC;AAErE,OAAO,KAAK,EAAE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,EAAE,MAAM,IAAI,CAAC;CAClC;AAED,qBAAa,wBAAwB;IACpC,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA+B;IAEpD,YAAY,IAAI,EAAE,4BAA4B,EAE7C;IAED,YAAY,IAAI,uBAAuB,CAEtC;IAED,OAAO,CAAC,kBAAkB;IAmD1B,YAAY,CAAC,OAAO,EAAE,uBAAuB,GAAG,KAAK,CAOpD;IAED,eAAe,CACd,OAAO,EAAE,uBAAuB,EAChC,2BAA2B,EAAE,OAAO,EACpC,kBAAkB,GAAE,WAAW,CAAC,MAAM,CAAa,GACjD,uBAAuB,CAQzB;IAED,mBAAmB,CAAC,OAAO,EAAE,uBAAuB,GAAG;QACtD,QAAQ,CAAC,OAAO,EAAE,uBAAuB,CAAC;QAC1C,QAAQ,CAAC,mBAAmB,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;KAClD,CA+BA;IAED,2BAA2B,IAAI,MAAM,EAAE,CAYtC;IAED,gBAAgB,CAAC,eAAe,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,SAAS,EAAE,OAAO,GAAG,eAAe,CAoBjF;IAED,iBAAiB,CAAC,OAAO,EAAE,uBAAuB,GAAG,kCAAkC,CA4CtF;IAED,mBAAmB,CAAC,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,kBAAkB,GAAG,OAAO,CAQ3E;IAED,MAAM,CAAC,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,gBAAgB,EAAE,aAAa,EAAE,OAAO,GAAG,mBAAmB,CAgDpG;CACD","sourcesContent":["/**\n * Session compaction service: capture / barrier / repair / transaction / commit.\n *\n * Extracted from AgentSession so the session keeps lifecycle orchestration\n * (abort controllers, extension events, auth, model resolution) while this\n * owns the integrity-critical compaction state machine. Every method preserves\n * the exact semantics of the original session implementation — the\n * compaction-transaction / session-integrity suites pin them.\n */\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { repairTranscriptIntegrity } from \"omk-agent-core\";\nimport type { Api, Message, Model, ToolResultMessage } from \"omk-ai\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport type { CompactionResult } from \"./compaction/index.ts\";\nimport {\n\ttype CompactionBarrierResult,\n\ttype CompactionEnvelope,\n\ttype CompactionPreservedProvenanceInput,\n\ttype CompactionSourceIdentity,\n\ttype CompactionTransaction,\n\tcreateCompactionEnvelope,\n\tcreateCompactionSourceIdentity,\n\tcreateCompactionTransaction,\n\tdecideCompactionCommit,\n\tevaluateCompactionBarrier,\n\tredactCredentialShapedContent,\n\tvalidateCompactionEnvelope,\n} from \"./compaction/transaction.ts\";\nimport { redactSensitiveTextForced } from \"./redaction.ts\";\nimport type { SessionIntegrityReport } from \"./session-integrity.ts\";\nimport { inspectSessionIntegrity } from \"./session-integrity.ts\";\nimport type { CompactionEntry, SessionEntry, SessionManager } from \"./session-manager.ts\";\n\nexport interface CapturedCompactionState {\n\treadonly report: SessionIntegrityReport;\n\treadonly branchEntries: readonly SessionEntry[];\n\treadonly revision: CompactionTransaction[\"baseRevision\"];\n\treadonly source: CompactionSourceIdentity;\n}\n\nexport interface BegunCompaction {\n\treadonly capture: CapturedCompactionState;\n\treadonly transaction: CompactionTransaction;\n}\n\nexport interface CommittedCompaction {\n\treadonly entry: CompactionEntry;\n\treadonly envelope: CompactionEnvelope;\n}\n\nexport interface SessionCompactionServiceDeps {\n\treadonly sessionManager: SessionManager;\n\treadonly pendingToolCallIds: () => ReadonlySet<string>;\n\treadonly getUserMessageText: (message: Message) => string;\n\treadonly cwd: string;\n\treadonly invalidateContextBudget: () => void;\n\t/** Refresh agent messages from the session manager after tail repair/commit. */\n\treadonly refreshAgentMessages: () => void;\n\t/** Hysteresis bookkeeping after a successful commit. */\n\treadonly recordCommit: () => void;\n}\n\nexport class SessionCompactionService {\n\tprivate readonly deps: SessionCompactionServiceDeps;\n\n\tconstructor(deps: SessionCompactionServiceDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tcaptureState(): CapturedCompactionState {\n\t\treturn this.deps.sessionManager.withCompactionCommitLock(() => this.captureStateLocked());\n\t}\n\n\tprivate captureStateLocked(): CapturedCompactionState {\n\t\tconst { sessionManager } = this.deps;\n\t\tconst sessionFile = sessionManager.getSessionFile();\n\t\tconst bytes =\n\t\t\tsessionFile && existsSync(sessionFile)\n\t\t\t\t? new Uint8Array(readFileSync(sessionFile))\n\t\t\t\t: new TextEncoder().encode(\n\t\t\t\t\t\t`${[sessionManager.getHeader(), ...sessionManager.getEntries()]\n\t\t\t\t\t\t\t.filter((entry) => entry !== null)\n\t\t\t\t\t\t\t.map((entry) => JSON.stringify(entry))\n\t\t\t\t\t\t\t.join(\"\\n\")}\\n`,\n\t\t\t\t\t);\n\t\tconst report = inspectSessionIntegrity(bytes, { activeLeafId: sessionManager.getLeafId() });\n\t\tconst branchEntries = report.activeBranch;\n\t\tlet latestCompactionIndex = -1;\n\t\tfor (let index = branchEntries.length - 1; index >= 0; index -= 1) {\n\t\t\tif (branchEntries[index]?.type === \"compaction\") {\n\t\t\t\tlatestCompactionIndex = index;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tconst latestCompaction = branchEntries[latestCompactionIndex];\n\t\tconst firstKeptIndex =\n\t\t\tlatestCompaction?.type === \"compaction\"\n\t\t\t\t? branchEntries.findIndex((entry) => entry.id === latestCompaction.firstKeptEntryId)\n\t\t\t\t: -1;\n\t\tconst sourceEntries = branchEntries.slice(\n\t\t\tlatestCompactionIndex < 0 ? 0 : firstKeptIndex < 0 ? latestCompactionIndex : firstKeptIndex,\n\t\t);\n\t\tconst firstEntry = sourceEntries[0];\n\t\tconst lastEntry = sourceEntries[sourceEntries.length - 1];\n\t\tif (!firstEntry || !lastEntry || report.activeLeafId === null) {\n\t\t\tconst barrier = evaluateCompactionBarrier(report, [...this.deps.pendingToolCallIds()]);\n\t\t\tif (barrier.status !== \"ready\") throw this.barrierError(barrier);\n\t\t\tthrow new Error(\"Nothing to compact: the active session branch is empty\");\n\t\t}\n\t\tconst revision = sessionManager.getDurableHeadToken();\n\t\tconst source = createCompactionSourceIdentity({\n\t\t\tsessionId: revision.sessionId,\n\t\t\tentryIds: sourceEntries.map((entry) => entry.id),\n\t\t\tfirstEntryId: firstEntry.id,\n\t\t\tlastEntryId: lastEntry.id,\n\t\t\tsourceSha256: createHash(\"sha256\")\n\t\t\t\t.update(sourceEntries.map((entry) => JSON.stringify(entry)).join(\"\\n\"), \"utf8\")\n\t\t\t\t.digest(\"hex\"),\n\t\t\tactiveLeafId: report.activeLeafId,\n\t\t\tmessageCount: report.activeMessages.length,\n\t\t});\n\t\treturn { report, branchEntries, revision, source };\n\t}\n\n\tbarrierError(barrier: CompactionBarrierResult): Error {\n\t\tif (barrier.status === \"defer\") {\n\t\t\treturn new Error(`Compaction deferred until the transcript closes (${barrier.reason})`);\n\t\t}\n\t\treturn new Error(\n\t\t\t`Compaction failed closed on transcript integrity (${barrier.reason}). Run the session doctor before retrying.`,\n\t\t);\n\t}\n\n\tevaluateBarrier(\n\t\tcapture: CapturedCompactionState,\n\t\tincludeMissingTailAsPending: boolean,\n\t\texcludedPendingIds: ReadonlySet<string> = new Set(),\n\t): CompactionBarrierResult {\n\t\tconst pending = new Set([...this.deps.pendingToolCallIds()].filter((id) => !excludedPendingIds.has(id)));\n\t\tif (includeMissingTailAsPending) {\n\t\t\tfor (const issue of capture.report.transcript?.issues ?? []) {\n\t\t\t\tif (issue.kind === \"missing_result\") pending.add(issue.toolCallId);\n\t\t\t}\n\t\t}\n\t\treturn evaluateCompactionBarrier(capture.report, [...pending]);\n\t}\n\n\trepairEmergencyTail(capture: CapturedCompactionState): {\n\t\treadonly capture: CapturedCompactionState;\n\t\treadonly repairedToolCallIds: ReadonlySet<string>;\n\t} {\n\t\tconst { sessionManager } = this.deps;\n\t\tconst barrier = this.evaluateBarrier(capture, true);\n\t\tif (barrier.status !== \"defer\" || barrier.reason !== \"missing_active_tail_results\") {\n\t\t\tif (barrier.status !== \"ready\") throw this.barrierError(barrier);\n\t\t\treturn { capture, repairedToolCallIds: new Set() };\n\t\t}\n\t\tconst repairedMessages = repairTranscriptIntegrity(\n\t\t\t[...capture.report.activeMessages],\n\t\t\t\"Tool result missing; synthesized to close an emergency compaction barrier\",\n\t\t);\n\t\tconst inserted = repairedMessages.slice(capture.report.activeMessages.length);\n\t\tconst repairedToolCallIds = new Set<string>();\n\t\tfor (const message of inserted) {\n\t\t\tif (message.role !== \"toolResult\") {\n\t\t\t\tthrow new Error(\"Emergency compaction repair produced a non-tool result\");\n\t\t\t}\n\t\t\tconst toolResult: ToolResultMessage = message;\n\t\t\trepairedToolCallIds.add(toolResult.toolCallId);\n\t\t\tsessionManager.appendMessage(toolResult);\n\t\t}\n\t\tsessionManager.appendCustomEntry(\"compaction_transcript_repaired\", {\n\t\t\tinsertedToolCallIds: [...repairedToolCallIds],\n\t\t\treason: \"emergency_compaction\",\n\t\t});\n\t\tthis.deps.invalidateContextBudget();\n\t\tconst closedCapture = this.captureState();\n\t\tconst closedBarrier = this.evaluateBarrier(closedCapture, false, repairedToolCallIds);\n\t\tif (closedBarrier.status !== \"ready\") throw this.barrierError(closedBarrier);\n\t\tthis.deps.refreshAgentMessages();\n\t\treturn { capture: closedCapture, repairedToolCallIds };\n\t}\n\n\tpriorCommittedSourceDigests(): string[] {\n\t\tconst digests: string[] = [];\n\t\tfor (const entry of this.deps.sessionManager.getEntries()) {\n\t\t\tif (entry.type !== \"compaction\" || typeof entry.details !== \"object\" || entry.details === null) continue;\n\t\t\tif (Object.getOwnPropertyDescriptor(entry.details, \"compactionEnvelope\") === undefined) continue;\n\t\t\tconst envelope = validateCompactionEnvelope(Reflect.get(entry.details, \"compactionEnvelope\"));\n\t\t\tif (envelope.summary !== entry.summary) {\n\t\t\t\tthrow new Error(`Compaction entry ${entry.id} has invalid provenance. Run the session doctor.`);\n\t\t\t}\n\t\t\tdigests.push(envelope.source.sourceSha256);\n\t\t}\n\t\treturn digests;\n\t}\n\n\tbeginTransaction(compactionModel: Model<Api>, emergency: boolean): BegunCompaction {\n\t\tlet capture = this.captureState();\n\t\tif (emergency) {\n\t\t\tcapture = this.repairEmergencyTail(capture).capture;\n\t\t} else {\n\t\t\tconst barrier = this.evaluateBarrier(capture, false);\n\t\t\tif (barrier.status !== \"ready\") throw this.barrierError(barrier);\n\t\t}\n\t\tconst transaction = createCompactionTransaction({\n\t\t\ttransactionId: randomUUID(),\n\t\t\tbaseRevision: capture.revision,\n\t\t\tsource: capture.source,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\tmodel: { provider: compactionModel.provider, id: compactionModel.id },\n\t\t\tpreserved: this.captureProvenance(capture),\n\t\t});\n\t\tif (this.priorCommittedSourceDigests().includes(transaction.source.sourceSha256)) {\n\t\t\tthrow new Error(\"This exact compaction source was already compacted\");\n\t\t}\n\t\treturn { capture, transaction };\n\t}\n\n\tcaptureProvenance(capture: CapturedCompactionState): CompactionPreservedProvenanceInput {\n\t\tlet latestIntent = \"Continue the current session\";\n\t\tfor (let index = capture.report.activeMessages.length - 1; index >= 0; index -= 1) {\n\t\t\tconst message = capture.report.activeMessages[index];\n\t\t\tif (message?.role !== \"user\") continue;\n\t\t\tconst candidate = redactCredentialShapedContent(\n\t\t\t\tsanitizeBinaryOutput(redactSensitiveTextForced(this.deps.getUserMessageText(message)).trim())\n\t\t\t\t\t.replace(/[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/gu, \"\")\n\t\t\t\t\t.slice(0, 16_384),\n\t\t\t);\n\t\t\tif (candidate.length > 0) latestIntent = candidate;\n\t\t\tbreak;\n\t\t}\n\t\tconst modelHistory = capture.branchEntries\n\t\t\t.flatMap((entry) => {\n\t\t\t\tif (entry.type === \"model_change\") {\n\t\t\t\t\treturn [{ entryId: entry.id, provider: entry.provider, modelId: entry.modelId }];\n\t\t\t\t}\n\t\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\t\treturn [{ entryId: entry.id, provider: entry.message.provider, modelId: entry.message.model }];\n\t\t\t\t}\n\t\t\t\treturn [];\n\t\t\t})\n\t\t\t.slice(-256);\n\t\tconst customEntryIds = (customType: string): string[] =>\n\t\t\tcapture.branchEntries\n\t\t\t\t.filter((entry) => entry.type === \"custom\" && entry.customType === customType)\n\t\t\t\t.map((entry) => entry.id);\n\t\treturn {\n\t\t\tlatestIntent,\n\t\t\topenTasks: [],\n\t\t\tlaneIds: customEntryIds(\"lane\"),\n\t\t\tacceptancePredicateIds: customEntryIds(\"acceptance_predicate\"),\n\t\t\tevidenceReceiptIds: customEntryIds(\"evidence_receipt\"),\n\t\t\tblockerReasons: [],\n\t\t\trepairEventIds: [\n\t\t\t\t...customEntryIds(\"transcript_repaired\"),\n\t\t\t\t...customEntryIds(\"compaction_transcript_repaired\"),\n\t\t\t],\n\t\t\tbranch: null,\n\t\t\tworktree: this.deps.cwd,\n\t\t\tmodelHistory,\n\t\t\tnextAction: redactCredentialShapedContent(latestIntent.slice(0, 4096)) || \"Continue the current session\",\n\t\t};\n\t}\n\n\tdetailsWithEnvelope(details: unknown, envelope: CompactionEnvelope): unknown {\n\t\tif (typeof details === \"object\" && details !== null && !Array.isArray(details)) {\n\t\t\treturn { ...details, compactionEnvelope: envelope };\n\t\t}\n\t\treturn {\n\t\t\tcompactionEnvelope: envelope,\n\t\t\t...(details === undefined ? {} : { resultDetails: details }),\n\t\t};\n\t}\n\n\tcommit(begun: BegunCompaction, result: CompactionResult, fromExtension: boolean): CommittedCompaction {\n\t\tif (!begun.transaction.source.entryIds.includes(result.firstKeptEntryId)) {\n\t\t\tthrow new Error(\"Compaction first-kept entry is outside the captured source\");\n\t\t}\n\t\tconst committed = this.deps.sessionManager.withCompactionCommitLock(() => {\n\t\t\tconst current = this.captureState();\n\t\t\tconst barrier = this.evaluateBarrier(current, false);\n\t\t\tconst decision = decideCompactionCommit({\n\t\t\t\ttransaction: begun.transaction,\n\t\t\t\tcurrentRevision: current.revision,\n\t\t\t\tcurrentSource: current.source,\n\t\t\t\tbarrier,\n\t\t\t\tpriorCommittedSourceDigests: this.priorCommittedSourceDigests(),\n\t\t\t});\n\t\t\tswitch (decision.decision) {\n\t\t\t\tcase \"duplicate\":\n\t\t\t\t\tthrow new Error(\"This exact compaction source was already compacted\");\n\t\t\t\tcase \"stale\":\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Session changed during compaction (${decision.reason}); generated summary was discarded`,\n\t\t\t\t\t);\n\t\t\t\tcase \"defer\":\n\t\t\t\tcase \"fail_closed\":\n\t\t\t\t\tthrow this.barrierError(barrier);\n\t\t\t\tcase \"commit\": {\n\t\t\t\t\tconst envelope = createCompactionEnvelope({\n\t\t\t\t\t\ttransaction: begun.transaction,\n\t\t\t\t\t\tdecision,\n\t\t\t\t\t\tsummary: result.summary,\n\t\t\t\t\t\tsummarySha256: createHash(\"sha256\").update(result.summary, \"utf8\").digest(\"hex\"),\n\t\t\t\t\t});\n\t\t\t\t\tconst entryId = this.deps.sessionManager.appendCompaction(\n\t\t\t\t\t\tresult.summary,\n\t\t\t\t\t\tresult.firstKeptEntryId,\n\t\t\t\t\t\tresult.tokensBefore,\n\t\t\t\t\t\tthis.detailsWithEnvelope(result.details, envelope),\n\t\t\t\t\t\tfromExtension,\n\t\t\t\t\t);\n\t\t\t\t\tconst entry = this.deps.sessionManager.getEntry(entryId);\n\t\t\t\t\tif (!entry || entry.type !== \"compaction\") {\n\t\t\t\t\t\tthrow new Error(\"Compaction commit did not produce a compaction entry\");\n\t\t\t\t\t}\n\t\t\t\t\treturn { entry, envelope };\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tthis.deps.recordCommit();\n\t\treturn committed;\n\t}\n}\n"]}
1
+ {"version":3,"file":"session-compaction-service.d.ts","sourceRoot":"","sources":["../../src/core/session-compaction-service.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,EAAE,GAAG,EAAE,OAAO,EAAE,KAAK,EAAqB,MAAM,QAAQ,CAAC;AAErE,OAAO,EACN,KAAK,sBAAsB,E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\n * Session compaction service: capture / barrier / repair / transaction / commit.\n *\n * Extracted from AgentSession so the session keeps lifecycle orchestration\n * (abort controllers, extension events, auth, model resolution) while this\n * owns the integrity-critical compaction state machine. Every method preserves\n * the exact semantics of the original session implementation — the\n * compaction-transaction / session-integrity suites pin them.\n */\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { repairTranscriptIntegrity } from \"omk-agent-core\";\nimport type { Api, Message, Model, ToolResultMessage } from \"omk-ai\";\nimport { sanitizeBinaryOutput } from \"../utils/shell.ts\";\nimport {\n\ttype CompactionControlState,\n\tcontrolStateDigest,\n\tcontrolStateProvenance,\n\tvalidateControlState,\n} from \"./compaction/control-state.ts\";\nimport type { CompactionResult } from \"./compaction/index.ts\";\nimport {\n\ttype CompactionBarrierResult,\n\ttype CompactionEnvelope,\n\ttype CompactionPreservedProvenanceInput,\n\ttype CompactionSourceIdentity,\n\ttype CompactionTransaction,\n\tcreateCompactionEnvelope,\n\tcreateCompactionSourceIdentity,\n\tcreateCompactionTransaction,\n\tdecideCompactionCommit,\n\tevaluateCompactionBarrier,\n\tredactCredentialShapedContent,\n\tvalidateCompactionEnvelope,\n} from \"./compaction/transaction.ts\";\nimport { redactSensitiveTextForced } from \"./redaction.ts\";\nimport type { SessionIntegrityReport } from \"./session-integrity.ts\";\nimport { inspectSessionIntegrity } from \"./session-integrity.ts\";\nimport type { CompactionEntry, SessionEntry, SessionManager } from \"./session-manager.ts\";\n\nexport interface CapturedCompactionState {\n\treadonly report: SessionIntegrityReport;\n\treadonly branchEntries: readonly SessionEntry[];\n\treadonly revision: CompactionTransaction[\"baseRevision\"];\n\treadonly source: CompactionSourceIdentity;\n\t/**\n\t * Digest of the host control-state snapshot captured under the same commit\n\t * lock as `source`. `null` when no control authority is attached. A change\n\t * between capture and commit discards the summary like a source mismatch.\n\t */\n\treadonly controlStateDigest: string | null;\n\treadonly controlState: CompactionControlState | null;\n}\n\nexport interface BegunCompaction {\n\treadonly capture: CapturedCompactionState;\n\treadonly transaction: CompactionTransaction;\n}\n\nexport interface CommittedCompaction {\n\treadonly entry: CompactionEntry;\n\treadonly envelope: CompactionEnvelope;\n}\n\nexport interface SessionCompactionServiceDeps {\n\treadonly sessionManager: SessionManager;\n\treadonly pendingToolCallIds: () => ReadonlySet<string>;\n\treadonly getUserMessageText: (message: Message) => string;\n\treadonly cwd: string;\n\t/**\n\t * Optional host control authority. Called inside the compaction commit lock\n\t * so the snapshot is bound to the same captured source as the summary. Must\n\t * be deterministic for unchanged state — a changed snapshot discards the\n\t * in-flight summary at commit. Return `null` only when no authority exists.\n\t */\n\treadonly controlState?: () => CompactionControlState | null;\n\treadonly invalidateContextBudget: () => void;\n\t/** Refresh agent messages from the session manager after tail repair/commit. */\n\treadonly refreshAgentMessages: () => void;\n\t/** Hysteresis bookkeeping after a successful commit. */\n\treadonly recordCommit: () => void;\n}\n\nexport class SessionCompactionService {\n\tprivate readonly deps: SessionCompactionServiceDeps;\n\n\tconstructor(deps: SessionCompactionServiceDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tcaptureState(): CapturedCompactionState {\n\t\treturn this.deps.sessionManager.withCompactionCommitLock(() => this.captureStateLocked());\n\t}\n\n\tprivate captureStateLocked(): CapturedCompactionState {\n\t\tconst { sessionManager } = this.deps;\n\t\tconst sessionFile = sessionManager.getSessionFile();\n\t\tconst bytes =\n\t\t\tsessionFile && existsSync(sessionFile)\n\t\t\t\t? new Uint8Array(readFileSync(sessionFile))\n\t\t\t\t: new TextEncoder().encode(\n\t\t\t\t\t\t`${[sessionManager.getHeader(), ...sessionManager.getEntries()]\n\t\t\t\t\t\t\t.filter((entry) => entry !== null)\n\t\t\t\t\t\t\t.map((entry) => JSON.stringify(entry))\n\t\t\t\t\t\t\t.join(\"\\n\")}\\n`,\n\t\t\t\t\t);\n\t\tconst report = inspectSessionIntegrity(bytes, { activeLeafId: sessionManager.getLeafId() });\n\t\tconst branchEntries = report.activeBranch;\n\t\tlet latestCompactionIndex = -1;\n\t\tfor (let index = branchEntries.length - 1; index >= 0; index -= 1) {\n\t\t\tif (branchEntries[index]?.type === \"compaction\") {\n\t\t\t\tlatestCompactionIndex = index;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tconst latestCompaction = branchEntries[latestCompactionIndex];\n\t\tconst firstKeptIndex =\n\t\t\tlatestCompaction?.type === \"compaction\"\n\t\t\t\t? branchEntries.findIndex((entry) => entry.id === latestCompaction.firstKeptEntryId)\n\t\t\t\t: -1;\n\t\tconst sourceEntries = branchEntries.slice(\n\t\t\tlatestCompactionIndex < 0 ? 0 : firstKeptIndex < 0 ? latestCompactionIndex : firstKeptIndex,\n\t\t);\n\t\tconst firstEntry = sourceEntries[0];\n\t\tconst lastEntry = sourceEntries[sourceEntries.length - 1];\n\t\tif (!firstEntry || !lastEntry || report.activeLeafId === null) {\n\t\t\tconst barrier = evaluateCompactionBarrier(report, [...this.deps.pendingToolCallIds()]);\n\t\t\tif (barrier.status !== \"ready\") throw this.barrierError(barrier);\n\t\t\tthrow new Error(\"Nothing to compact: the active session branch is empty\");\n\t\t}\n\t\tconst revision = sessionManager.getDurableHeadToken();\n\t\tconst source = createCompactionSourceIdentity({\n\t\t\tsessionId: revision.sessionId,\n\t\t\tentryIds: sourceEntries.map((entry) => entry.id),\n\t\t\tfirstEntryId: firstEntry.id,\n\t\t\tlastEntryId: lastEntry.id,\n\t\t\tsourceSha256: createHash(\"sha256\")\n\t\t\t\t.update(sourceEntries.map((entry) => JSON.stringify(entry)).join(\"\\n\"), \"utf8\")\n\t\t\t\t.digest(\"hex\"),\n\t\t\tactiveLeafId: report.activeLeafId,\n\t\t\tmessageCount: report.activeMessages.length,\n\t\t});\n\t\tconst controlState = validateControlState(this.deps.controlState?.() ?? null);\n\t\treturn {\n\t\t\treport,\n\t\t\tbranchEntries,\n\t\t\trevision,\n\t\t\tsource,\n\t\t\tcontrolStateDigest: controlStateDigest(controlState),\n\t\t\tcontrolState,\n\t\t};\n\t}\n\n\tbarrierError(barrier: CompactionBarrierResult): Error {\n\t\tif (barrier.status === \"defer\") {\n\t\t\treturn new Error(`Compaction deferred until the transcript closes (${barrier.reason})`);\n\t\t}\n\t\treturn new Error(\n\t\t\t`Compaction failed closed on transcript integrity (${barrier.reason}). Run the session doctor before retrying.`,\n\t\t);\n\t}\n\n\tevaluateBarrier(\n\t\tcapture: CapturedCompactionState,\n\t\tincludeMissingTailAsPending: boolean,\n\t\texcludedPendingIds: ReadonlySet<string> = new Set(),\n\t): CompactionBarrierResult {\n\t\tconst pending = new Set([...this.deps.pendingToolCallIds()].filter((id) => !excludedPendingIds.has(id)));\n\t\tif (includeMissingTailAsPending) {\n\t\t\tfor (const issue of capture.report.transcript?.issues ?? []) {\n\t\t\t\tif (issue.kind === \"missing_result\") pending.add(issue.toolCallId);\n\t\t\t}\n\t\t}\n\t\treturn evaluateCompactionBarrier(capture.report, [...pending]);\n\t}\n\n\trepairEmergencyTail(capture: CapturedCompactionState): {\n\t\treadonly capture: CapturedCompactionState;\n\t\treadonly repairedToolCallIds: ReadonlySet<string>;\n\t} {\n\t\tconst { sessionManager } = this.deps;\n\t\tconst barrier = this.evaluateBarrier(capture, true);\n\t\tif (barrier.status !== \"defer\" || barrier.reason !== \"missing_active_tail_results\") {\n\t\t\tif (barrier.status !== \"ready\") throw this.barrierError(barrier);\n\t\t\treturn { capture, repairedToolCallIds: new Set() };\n\t\t}\n\t\tconst repairedMessages = repairTranscriptIntegrity(\n\t\t\t[...capture.report.activeMessages],\n\t\t\t\"Tool result missing; synthesized to close an emergency compaction barrier\",\n\t\t);\n\t\tconst inserted = repairedMessages.slice(capture.report.activeMessages.length);\n\t\tconst repairedToolCallIds = new Set<string>();\n\t\tfor (const message of inserted) {\n\t\t\tif (message.role !== \"toolResult\") {\n\t\t\t\tthrow new Error(\"Emergency compaction repair produced a non-tool result\");\n\t\t\t}\n\t\t\tconst toolResult: ToolResultMessage = message;\n\t\t\trepairedToolCallIds.add(toolResult.toolCallId);\n\t\t\tsessionManager.appendMessage(toolResult);\n\t\t}\n\t\tsessionManager.appendCustomEntry(\"compaction_transcript_repaired\", {\n\t\t\tinsertedToolCallIds: [...repairedToolCallIds],\n\t\t\treason: \"emergency_compaction\",\n\t\t});\n\t\tthis.deps.invalidateContextBudget();\n\t\tconst closedCapture = this.captureState();\n\t\tconst closedBarrier = this.evaluateBarrier(closedCapture, false, repairedToolCallIds);\n\t\tif (closedBarrier.status !== \"ready\") throw this.barrierError(closedBarrier);\n\t\tthis.deps.refreshAgentMessages();\n\t\treturn { capture: closedCapture, repairedToolCallIds };\n\t}\n\n\tpriorCommittedSourceDigests(): string[] {\n\t\tconst digests: string[] = [];\n\t\tfor (const entry of this.deps.sessionManager.getEntries()) {\n\t\t\tif (entry.type !== \"compaction\" || typeof entry.details !== \"object\" || entry.details === null) continue;\n\t\t\tif (Object.getOwnPropertyDescriptor(entry.details, \"compactionEnvelope\") === undefined) continue;\n\t\t\tconst envelope = validateCompactionEnvelope(Reflect.get(entry.details, \"compactionEnvelope\"));\n\t\t\tif (envelope.summary !== entry.summary) {\n\t\t\t\tthrow new Error(`Compaction entry ${entry.id} has invalid provenance. Run the session doctor.`);\n\t\t\t}\n\t\t\tdigests.push(envelope.source.sourceSha256);\n\t\t}\n\t\treturn digests;\n\t}\n\n\tbeginTransaction(compactionModel: Model<Api>, emergency: boolean): BegunCompaction {\n\t\tlet capture = this.captureState();\n\t\tif (emergency) {\n\t\t\tcapture = this.repairEmergencyTail(capture).capture;\n\t\t} else {\n\t\t\tconst barrier = this.evaluateBarrier(capture, false);\n\t\t\tif (barrier.status !== \"ready\") throw this.barrierError(barrier);\n\t\t}\n\t\tconst transaction = createCompactionTransaction({\n\t\t\ttransactionId: randomUUID(),\n\t\t\tbaseRevision: capture.revision,\n\t\t\tsource: capture.source,\n\t\t\tcreatedAt: new Date().toISOString(),\n\t\t\tmodel: { provider: compactionModel.provider, id: compactionModel.id },\n\t\t\tpreserved: this.captureProvenance(capture),\n\t\t});\n\t\tif (this.priorCommittedSourceDigests().includes(transaction.source.sourceSha256)) {\n\t\t\tthrow new Error(\"This exact compaction source was already compacted\");\n\t\t}\n\t\treturn { capture, transaction };\n\t}\n\n\tcaptureProvenance(capture: CapturedCompactionState): CompactionPreservedProvenanceInput {\n\t\tlet latestIntent = \"Continue the current session\";\n\t\tfor (let index = capture.report.activeMessages.length - 1; index >= 0; index -= 1) {\n\t\t\tconst message = capture.report.activeMessages[index];\n\t\t\tif (message?.role !== \"user\") continue;\n\t\t\tconst candidate = redactCredentialShapedContent(\n\t\t\t\tsanitizeBinaryOutput(redactSensitiveTextForced(this.deps.getUserMessageText(message)).trim())\n\t\t\t\t\t.replace(/[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]/gu, \"\")\n\t\t\t\t\t.slice(0, 16_384),\n\t\t\t);\n\t\t\tif (candidate.length > 0) latestIntent = candidate;\n\t\t\tbreak;\n\t\t}\n\t\tconst modelHistory = capture.branchEntries\n\t\t\t.flatMap((entry) => {\n\t\t\t\tif (entry.type === \"model_change\") {\n\t\t\t\t\treturn [{ entryId: entry.id, provider: entry.provider, modelId: entry.modelId }];\n\t\t\t\t}\n\t\t\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\t\t\treturn [{ entryId: entry.id, provider: entry.message.provider, modelId: entry.message.model }];\n\t\t\t\t}\n\t\t\t\treturn [];\n\t\t\t})\n\t\t\t.slice(-256);\n\t\tconst customEntryIds = (customType: string): string[] =>\n\t\t\tcapture.branchEntries\n\t\t\t\t.filter((entry) => entry.type === \"custom\" && entry.customType === customType)\n\t\t\t\t.map((entry) => entry.id);\n\t\tconst control = controlStateProvenance(capture.controlState);\n\t\treturn {\n\t\t\tlatestIntent,\n\t\t\topenTasks: control.openTasks,\n\t\t\tlaneIds: customEntryIds(\"lane\"),\n\t\t\tacceptancePredicateIds: customEntryIds(\"acceptance_predicate\"),\n\t\t\tevidenceReceiptIds: customEntryIds(\"evidence_receipt\"),\n\t\t\tblockerReasons: control.blockerReasons,\n\t\t\trepairEventIds: [\n\t\t\t\t...customEntryIds(\"transcript_repaired\"),\n\t\t\t\t...customEntryIds(\"compaction_transcript_repaired\"),\n\t\t\t],\n\t\t\tbranch: control.branch,\n\t\t\tworktree: this.deps.cwd,\n\t\t\tmodelHistory,\n\t\t\tnextAction: redactCredentialShapedContent(latestIntent.slice(0, 4096)) || \"Continue the current session\",\n\t\t};\n\t}\n\n\tdetailsWithEnvelope(details: unknown, envelope: CompactionEnvelope): unknown {\n\t\tif (typeof details === \"object\" && details !== null && !Array.isArray(details)) {\n\t\t\treturn { ...details, compactionEnvelope: envelope };\n\t\t}\n\t\treturn {\n\t\t\tcompactionEnvelope: envelope,\n\t\t\t...(details === undefined ? {} : { resultDetails: details }),\n\t\t};\n\t}\n\n\tcommit(begun: BegunCompaction, result: CompactionResult, fromExtension: boolean): CommittedCompaction {\n\t\tif (!begun.transaction.source.entryIds.includes(result.firstKeptEntryId)) {\n\t\t\tthrow new Error(\"Compaction first-kept entry is outside the captured source\");\n\t\t}\n\t\tconst committed = this.deps.sessionManager.withCompactionCommitLock(() => {\n\t\t\tconst current = this.captureState();\n\t\t\tconst barrier = this.evaluateBarrier(current, false);\n\t\t\tconst decision = decideCompactionCommit({\n\t\t\t\ttransaction: begun.transaction,\n\t\t\t\tcurrentRevision: current.revision,\n\t\t\t\tcurrentSource: current.source,\n\t\t\t\tbarrier,\n\t\t\t\tpriorCommittedSourceDigests: this.priorCommittedSourceDigests(),\n\t\t\t});\n\t\t\tswitch (decision.decision) {\n\t\t\t\tcase \"duplicate\":\n\t\t\t\t\tthrow new Error(\"This exact compaction source was already compacted\");\n\t\t\t\tcase \"stale\":\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Session changed during compaction (${decision.reason}); generated summary was discarded`,\n\t\t\t\t\t);\n\t\t\t\tcase \"defer\":\n\t\t\t\tcase \"fail_closed\":\n\t\t\t\t\tthrow this.barrierError(barrier);\n\t\t\t\tcase \"commit\": {\n\t\t\t\t\tif (current.controlStateDigest !== begun.capture.controlStateDigest) {\n\t\t\t\t\t\tthrow new Error(\"Control state changed during compaction; generated summary was discarded\");\n\t\t\t\t\t}\n\t\t\t\t\tconst envelope = createCompactionEnvelope({\n\t\t\t\t\t\ttransaction: begun.transaction,\n\t\t\t\t\t\tdecision,\n\t\t\t\t\t\tsummary: result.summary,\n\t\t\t\t\t\tsummarySha256: createHash(\"sha256\").update(result.summary, \"utf8\").digest(\"hex\"),\n\t\t\t\t\t});\n\t\t\t\t\tconst entryId = this.deps.sessionManager.appendCompaction(\n\t\t\t\t\t\tresult.summary,\n\t\t\t\t\t\tresult.firstKeptEntryId,\n\t\t\t\t\t\tresult.tokensBefore,\n\t\t\t\t\t\tthis.detailsWithEnvelope(result.details, envelope),\n\t\t\t\t\t\tfromExtension,\n\t\t\t\t\t);\n\t\t\t\t\tconst entry = this.deps.sessionManager.getEntry(entryId);\n\t\t\t\t\tif (!entry || entry.type !== \"compaction\") {\n\t\t\t\t\t\tthrow new Error(\"Compaction commit did not produce a compaction entry\");\n\t\t\t\t\t}\n\t\t\t\t\treturn { entry, envelope };\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tthis.deps.recordCommit();\n\t\treturn committed;\n\t}\n}\n"]}