@hassangameryt/freeflow 0.5.0 → 0.7.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 (301) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +2 -2
  3. package/.codex-plugin/plugin.json +4 -5
  4. package/README.md +141 -163
  5. package/capabilities/cognitive-routing/SKILL.md +387 -0
  6. package/capabilities/context-virtualization/SKILL.md +103 -0
  7. package/capabilities/conversation-history/SKILL.md +53 -0
  8. package/command-surface.json +6 -37
  9. package/hooks/freeflow-runtime-context.mjs +50 -541
  10. package/hooks/hooks.json +1 -26
  11. package/hooks/tests/check-runtime-context-hook.sh +114 -308
  12. package/package.json +27 -17
  13. package/pi-extension/dist/cognitive-routing/commands.js +96 -0
  14. package/pi-extension/dist/cognitive-routing/config.js +232 -0
  15. package/pi-extension/dist/cognitive-routing/controller.js +1292 -0
  16. package/pi-extension/dist/cognitive-routing/history.js +451 -0
  17. package/pi-extension/dist/cognitive-routing/host.js +188 -0
  18. package/pi-extension/dist/cognitive-routing/pi-routing-session.js +414 -0
  19. package/pi-extension/dist/cognitive-routing/pi-session-control.js +320 -0
  20. package/pi-extension/dist/cognitive-routing/runtime.js +43 -0
  21. package/pi-extension/dist/cognitive-routing/tool.js +212 -0
  22. package/pi-extension/dist/cognitive-routing/types.js +6 -0
  23. package/pi-extension/dist/context-virtualization/commands.js +89 -0
  24. package/pi-extension/dist/context-virtualization/projector.js +42 -0
  25. package/pi-extension/dist/context-virtualization/runtime.js +356 -0
  26. package/pi-extension/dist/context-virtualization/state.js +57 -0
  27. package/pi-extension/dist/context-virtualization/types.js +10 -0
  28. package/pi-extension/dist/conversation-history/passages.js +66 -0
  29. package/pi-extension/dist/conversation-history/ranking.js +105 -0
  30. package/pi-extension/dist/conversation-history/runtime.js +226 -0
  31. package/pi-extension/dist/conversation-history/search.js +56 -0
  32. package/pi-extension/dist/conversation-history/types.js +1 -0
  33. package/pi-extension/dist/freeflow-context/resolver.js +120 -0
  34. package/pi-extension/dist/freeflow-context/runtime.js +80 -0
  35. package/pi-extension/dist/freeflow-context/source-projector.js +95 -0
  36. package/pi-extension/dist/freeflow-context/tool.js +308 -0
  37. package/pi-extension/dist/freeflow-context/types.js +12 -0
  38. package/pi-extension/dist/freeflow-context/visibility.js +28 -0
  39. package/pi-extension/dist/index.js +564 -129
  40. package/pi-extension/dist/runtime/runtime-context.js +357 -470
  41. package/pi-extension/dist/runtime/runtime-identity.js +5 -0
  42. package/pi-extension/dist/settings/settings-tui.js +78 -0
  43. package/pi-extension/dist/settings/settings-ui.js +572 -826
  44. package/pi-extension/dist/ui/text-component.js +57 -0
  45. package/pi-extension/src/cognitive-routing/commands.ts +129 -0
  46. package/pi-extension/src/cognitive-routing/config.ts +303 -0
  47. package/pi-extension/src/cognitive-routing/controller.ts +1628 -0
  48. package/pi-extension/src/cognitive-routing/history.ts +650 -0
  49. package/pi-extension/src/cognitive-routing/host.ts +266 -0
  50. package/pi-extension/src/cognitive-routing/pi-routing-session.ts +538 -0
  51. package/pi-extension/src/cognitive-routing/pi-session-control.ts +444 -0
  52. package/pi-extension/src/cognitive-routing/runtime.ts +57 -0
  53. package/pi-extension/src/cognitive-routing/tool.ts +273 -0
  54. package/pi-extension/src/cognitive-routing/types.ts +89 -0
  55. package/pi-extension/src/context-virtualization/commands.ts +111 -0
  56. package/pi-extension/src/context-virtualization/projector.ts +62 -0
  57. package/pi-extension/src/context-virtualization/runtime.ts +406 -0
  58. package/pi-extension/src/context-virtualization/state.ts +79 -0
  59. package/pi-extension/src/context-virtualization/types.ts +92 -0
  60. package/pi-extension/src/conversation-history/passages.ts +81 -0
  61. package/pi-extension/src/conversation-history/ranking.ts +155 -0
  62. package/pi-extension/src/conversation-history/runtime.ts +250 -0
  63. package/pi-extension/src/conversation-history/search.ts +79 -0
  64. package/pi-extension/src/conversation-history/types.ts +31 -0
  65. package/pi-extension/src/freeflow-context/resolver.ts +139 -0
  66. package/pi-extension/src/freeflow-context/runtime.ts +100 -0
  67. package/pi-extension/src/freeflow-context/source-projector.ts +106 -0
  68. package/pi-extension/src/freeflow-context/tool.ts +360 -0
  69. package/pi-extension/src/freeflow-context/types.ts +70 -0
  70. package/pi-extension/src/freeflow-context/visibility.ts +53 -0
  71. package/pi-extension/src/index.ts +597 -135
  72. package/pi-extension/src/runtime/runtime-context.ts +373 -491
  73. package/pi-extension/src/runtime/runtime-identity.ts +8 -0
  74. package/pi-extension/src/settings/settings-tui.ts +93 -0
  75. package/pi-extension/src/settings/settings-ui.ts +679 -910
  76. package/pi-extension/src/ui/text-component.ts +66 -0
  77. package/pi-extension/tests/cognitive-routing/commands.test.js +134 -0
  78. package/pi-extension/tests/cognitive-routing/controller.test.js +1128 -0
  79. package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +1142 -0
  80. package/pi-extension/tests/cognitive-routing/history.test.js +274 -0
  81. package/pi-extension/tests/cognitive-routing/host-fixture.js +4 -0
  82. package/pi-extension/tests/cognitive-routing/host-identity.test.js +63 -0
  83. package/pi-extension/tests/cognitive-routing/pi-normal-lifecycle.test.js +434 -0
  84. package/pi-extension/tests/cognitive-routing/pi-session-control.test.js +174 -0
  85. package/pi-extension/tests/cognitive-routing/pi-session-history.test.js +91 -0
  86. package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +279 -0
  87. package/pi-extension/tests/cognitive-routing/tool.test.js +230 -0
  88. package/pi-extension/tests/context-virtualization/extension.test.js +749 -0
  89. package/pi-extension/tests/context-virtualization/projector.test.js +110 -0
  90. package/pi-extension/tests/context-virtualization/runtime.test.js +216 -0
  91. package/pi-extension/tests/conversation-history/runtime.test.js +98 -0
  92. package/pi-extension/tests/conversation-history/search.test.js +97 -0
  93. package/pi-extension/tests/integration/mode-free-core.test.js +218 -0
  94. package/pi-extension/tests/integration/pi-extension.test.js +532 -3701
  95. package/pi-extension/tests/integration/prompt-architecture.test.js +350 -0
  96. package/pi-extension/tests/integration/unaffected-regressions.test.js +411 -0
  97. package/runtime/prompts/cognitive-routing.md +10 -0
  98. package/runtime/prompts/context-virtualization.md +3 -0
  99. package/runtime/prompts/conversation-history.md +3 -0
  100. package/runtime/prompts/core.md +84 -0
  101. package/runtime/prompts/interaction-contract.md +11 -0
  102. package/skills/action-selection/SKILL.md +140 -0
  103. package/skills/action-selection/references/trajectory-stalls.md +71 -0
  104. package/skills/bypass/SKILL.md +109 -38
  105. package/skills/commit-work/SKILL.md +94 -55
  106. package/skills/commit-work/references/git-state-edges.md +94 -0
  107. package/skills/commit-work/references/simple-push.md +92 -0
  108. package/skills/commit-work/references/staging-decisions.md +79 -46
  109. package/skills/decision-gate/SKILL.md +80 -22
  110. package/skills/design-for-depth/SKILL.md +206 -60
  111. package/skills/design-for-depth/references/design-pressure-signals.md +108 -240
  112. package/skills/design-for-depth/references/interface-design-loop.md +77 -97
  113. package/skills/design-for-depth/references/module-and-dependency-design.md +147 -0
  114. package/skills/design-for-depth/references/software-design-philosophy.md +128 -174
  115. package/skills/design-for-depth/references/state-and-failure-boundaries.md +136 -0
  116. package/skills/diagnose-failure/SKILL.md +200 -48
  117. package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +18 -6
  118. package/skills/diagnose-failure/references/{flaky-and-performance.md → flaky-and-performance-diagnosis.md} +13 -5
  119. package/skills/discuss/SKILL.md +119 -65
  120. package/skills/discuss/references/discussion-continuity.md +123 -0
  121. package/skills/evaluate-skill/SKILL.md +166 -52
  122. package/skills/evaluate-skill/references/{definition-schema.md → evaluation-definition-schema.md} +43 -3
  123. package/skills/evaluate-skill/references/evaluation-design.md +56 -30
  124. package/skills/evaluate-skill/references/execution-and-evidence.md +8 -3
  125. package/skills/evaluate-skill/references/review-and-revision.md +62 -21
  126. package/skills/evaluate-skill/scripts/lib/definitions.mjs +114 -3
  127. package/skills/evaluate-skill/scripts/lib/grade-interaction.mjs +156 -1
  128. package/skills/evaluate-skill/scripts/lib/grade.mjs +9 -1
  129. package/skills/evaluate-skill/scripts/lib/pi.mjs +147 -32
  130. package/skills/evaluate-skill/scripts/lib/rpc.mjs +4 -4
  131. package/skills/evaluate-skill/scripts/lib/runner.mjs +36 -14
  132. package/skills/evaluate-skill/scripts/lib/sandbox.mjs +92 -0
  133. package/skills/evaluate-skill/scripts/pi-guard.mjs +1 -1
  134. package/skills/evaluate-skill/scripts/pi-observer.mjs +66 -0
  135. package/skills/evaluate-skill/scripts/skill-eval.mjs +6 -5
  136. package/skills/execute-work/SKILL.md +99 -57
  137. package/skills/execute-work/references/code-practices.md +4 -4
  138. package/skills/execute-work/references/execute-work-edges.md +62 -0
  139. package/skills/finish-branch/SKILL.md +2 -2
  140. package/skills/finish-branch/references/integration-options.md +1 -1
  141. package/skills/handoff/SKILL.md +3 -3
  142. package/skills/launch-work/SKILL.md +1 -1
  143. package/skills/launch-work/references/launch-readiness.md +2 -2
  144. package/skills/migration-work/SKILL.md +2 -2
  145. package/skills/migration-work/references/migration-lifecycle.md +1 -1
  146. package/skills/release-work/SKILL.md +1 -1
  147. package/skills/release-work/references/release-evidence.md +1 -1
  148. package/skills/review-artifact/SKILL.md +129 -66
  149. package/skills/review-artifact/references/adjudicate-artifact-review.md +101 -0
  150. package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +159 -0
  151. package/skills/review-work/SKILL.md +113 -68
  152. package/skills/review-work/references/adjudicate-work-review.md +97 -0
  153. package/skills/review-work/references/independent-work-reviewer-contract.md +139 -0
  154. package/skills/review-work/references/security-risk-lens.md +18 -16
  155. package/skills/setup-freeflow/SKILL.md +16 -17
  156. package/skills/setup-freeflow/references/activation-contract.md +24 -30
  157. package/skills/setup-freeflow/references/host-setup.md +6 -7
  158. package/skills/simplify-code/SKILL.md +97 -39
  159. package/skills/simplify-code/references/simplification-patterns.md +1 -1
  160. package/skills/tdd/SKILL.md +100 -53
  161. package/skills/tdd/references/test-design.md +3 -3
  162. package/skills/track-work/SKILL.md +195 -58
  163. package/skills/track-work/references/working-record-format.md +515 -0
  164. package/skills/track-work/scripts/lib/document.mjs +713 -0
  165. package/skills/track-work/scripts/lib/format.mjs +166 -0
  166. package/skills/track-work/scripts/lib/store.mjs +233 -0
  167. package/skills/track-work/scripts/lib/transitions.mjs +790 -0
  168. package/skills/track-work/scripts/lib/views.mjs +40 -0
  169. package/skills/track-work/scripts/working-record.mjs +316 -0
  170. package/skills/verify-work/SKILL.md +57 -19
  171. package/skills/verify-work/references/browser-runtime-evidence.md +2 -2
  172. package/skills/verify-work/references/integration-evidence.md +1 -7
  173. package/skills/verify-work/references/performance-evidence.md +2 -2
  174. package/skills/workflow/SKILL.md +137 -55
  175. package/skills/workflow/references/domain-skill-composition.md +26 -40
  176. package/skills/write-plan/SKILL.md +1 -1
  177. package/skills/write-skill/SKILL.md +218 -61
  178. package/skills/write-skill/references/activation-boundaries.md +63 -21
  179. package/skills/write-skill/references/agent-first-instructions.md +61 -27
  180. package/skills/write-skill/references/progressive-disclosure.md +97 -33
  181. package/skills/write-skill/references/skill-dependency-graphs.md +190 -0
  182. package/capabilities/output-router/SKILL.md +0 -206
  183. package/capabilities/output-router/references/safety-policy.md +0 -40
  184. package/capabilities/output-router/references/setup.md +0 -110
  185. package/pi-extension/dist/output-router/host-producer-identification.js +0 -232
  186. package/pi-extension/dist/output-router/native-safety-net.js +0 -216
  187. package/pi-extension/dist/output-router/observed-tool-routing.js +0 -122
  188. package/pi-extension/dist/output-router/renderers.js +0 -1023
  189. package/pi-extension/dist/output-router/router-tools.js +0 -554
  190. package/pi-extension/dist/output-router/schemas.js +0 -383
  191. package/pi-extension/dist/output-router/status.js +0 -744
  192. package/pi-extension/dist/output-router/utils.js +0 -502
  193. package/pi-extension/src/output-router/host-producer-identification.ts +0 -256
  194. package/pi-extension/src/output-router/native-safety-net.ts +0 -248
  195. package/pi-extension/src/output-router/observed-tool-routing.ts +0 -134
  196. package/pi-extension/src/output-router/renderers.ts +0 -1108
  197. package/pi-extension/src/output-router/router-tools.ts +0 -579
  198. package/pi-extension/src/output-router/schemas.ts +0 -387
  199. package/pi-extension/src/output-router/status.ts +0 -791
  200. package/pi-extension/src/output-router/utils.ts +0 -554
  201. package/pi-extension/tests/output-router/observed-producers.test.js +0 -132
  202. package/pi-extension/tests/output-router/search.test.js +0 -722
  203. package/router/dist/benchmarks/benchmark-harness.d.ts +0 -35
  204. package/router/dist/benchmarks/benchmark-harness.js +0 -92
  205. package/router/dist/benchmarks/benchmarks.d.ts +0 -109
  206. package/router/dist/benchmarks/benchmarks.js +0 -979
  207. package/router/dist/benchmarks/codex-qa-benchmarks.d.ts +0 -95
  208. package/router/dist/benchmarks/codex-qa-benchmarks.js +0 -500
  209. package/router/dist/benchmarks/command-benchmarks.d.ts +0 -143
  210. package/router/dist/benchmarks/command-benchmarks.js +0 -698
  211. package/router/dist/benchmarks/context-mode-normalized-benchmarks.d.ts +0 -82
  212. package/router/dist/benchmarks/context-mode-normalized-benchmarks.js +0 -773
  213. package/router/dist/benchmarks/context-mode-real-deep-benchmark.d.ts +0 -132
  214. package/router/dist/benchmarks/context-mode-real-deep-benchmark.js +0 -1380
  215. package/router/dist/benchmarks/context-saving-baseline.d.ts +0 -60
  216. package/router/dist/benchmarks/context-saving-baseline.js +0 -470
  217. package/router/dist/benchmarks/index-benchmarks.d.ts +0 -103
  218. package/router/dist/benchmarks/index-benchmarks.js +0 -862
  219. package/router/dist/benchmarks/storage-policy-benchmarks.d.ts +0 -101
  220. package/router/dist/benchmarks/storage-policy-benchmarks.js +0 -618
  221. package/router/dist/benchmarks/vault-index-benchmarks.d.ts +0 -56
  222. package/router/dist/benchmarks/vault-index-benchmarks.js +0 -322
  223. package/router/dist/config/config.d.ts +0 -103
  224. package/router/dist/config/config.js +0 -632
  225. package/router/dist/config/router-contract.d.ts +0 -10
  226. package/router/dist/config/router-contract.js +0 -54
  227. package/router/dist/config/schema.d.ts +0 -27
  228. package/router/dist/config/schema.js +0 -648
  229. package/router/dist/config/types.d.ts +0 -573
  230. package/router/dist/config/types.js +0 -41
  231. package/router/dist/evidence/bounded-evidence.d.ts +0 -40
  232. package/router/dist/evidence/bounded-evidence.js +0 -323
  233. package/router/dist/evidence/evidence-range-selector.d.ts +0 -24
  234. package/router/dist/evidence/evidence-range-selector.js +0 -232
  235. package/router/dist/evidence/evidence-search.d.ts +0 -27
  236. package/router/dist/evidence/evidence-search.js +0 -490
  237. package/router/dist/evidence/evidence.d.ts +0 -38
  238. package/router/dist/evidence/evidence.js +0 -200
  239. package/router/dist/evidence/failure-contracts.d.ts +0 -37
  240. package/router/dist/evidence/failure-contracts.js +0 -166
  241. package/router/dist/evidence/line-ranges.d.ts +0 -24
  242. package/router/dist/evidence/line-ranges.js +0 -22
  243. package/router/dist/experiments/local-index.d.ts +0 -64
  244. package/router/dist/experiments/local-index.js +0 -581
  245. package/router/dist/index.d.ts +0 -30
  246. package/router/dist/index.js +0 -32
  247. package/router/dist/local/local-traversal.d.ts +0 -18
  248. package/router/dist/local/local-traversal.js +0 -334
  249. package/router/dist/processing/engine.d.ts +0 -132
  250. package/router/dist/processing/engine.js +0 -533
  251. package/router/dist/processing/reducers.d.ts +0 -280
  252. package/router/dist/processing/reducers.js +0 -1673
  253. package/router/dist/processing/renderers.d.ts +0 -31
  254. package/router/dist/processing/renderers.js +0 -195
  255. package/router/dist/processing/scripts.d.ts +0 -91
  256. package/router/dist/processing/scripts.js +0 -386
  257. package/router/dist/repo/repo-traversal.d.ts +0 -18
  258. package/router/dist/repo/repo-traversal.js +0 -245
  259. package/router/dist/routing/observed-reducers.d.ts +0 -41
  260. package/router/dist/routing/observed-reducers.js +0 -661
  261. package/router/dist/routing/observed-routing.d.ts +0 -26
  262. package/router/dist/routing/observed-routing.js +0 -378
  263. package/router/dist/routing/parsers.d.ts +0 -16
  264. package/router/dist/routing/parsers.js +0 -521
  265. package/router/dist/routing/run-filters.d.ts +0 -60
  266. package/router/dist/routing/run-filters.js +0 -238
  267. package/router/dist/routing/run-reducers.d.ts +0 -49
  268. package/router/dist/routing/run-reducers.js +0 -122
  269. package/router/dist/sandbox/adapter-roots.d.ts +0 -46
  270. package/router/dist/sandbox/adapter-roots.js +0 -66
  271. package/router/dist/sandbox/eryx-python-adapter.d.ts +0 -13
  272. package/router/dist/sandbox/eryx-python-adapter.js +0 -868
  273. package/router/dist/sandbox/jq-wasm-adapter.d.ts +0 -9
  274. package/router/dist/sandbox/jq-wasm-adapter.js +0 -429
  275. package/router/dist/sandbox/quickjs-wasi-adapter.d.ts +0 -13
  276. package/router/dist/sandbox/quickjs-wasi-adapter.js +0 -384
  277. package/router/dist/sandbox/script-sandbox.d.ts +0 -134
  278. package/router/dist/sandbox/script-sandbox.js +0 -337
  279. package/router/dist/setup/script-transform-adapters.d.ts +0 -32
  280. package/router/dist/setup/script-transform-adapters.js +0 -278
  281. package/router/dist/tools/batch.d.ts +0 -33
  282. package/router/dist/tools/batch.js +0 -586
  283. package/router/dist/tools/run.d.ts +0 -62
  284. package/router/dist/tools/run.js +0 -1304
  285. package/router/dist/tools/search.d.ts +0 -66
  286. package/router/dist/tools/search.js +0 -1364
  287. package/router/dist/transform/engine.d.ts +0 -168
  288. package/router/dist/transform/engine.js +0 -2072
  289. package/router/dist/vault/vault-index.d.ts +0 -125
  290. package/router/dist/vault/vault-index.js +0 -416
  291. package/router/dist/vault/vault.d.ts +0 -138
  292. package/router/dist/vault/vault.js +0 -630
  293. package/runtime/interaction-contract.md +0 -16
  294. package/skills/discuss/references/checkpoints.md +0 -66
  295. package/skills/execute-work/references/execution-loop.md +0 -77
  296. package/skills/mode-contract/SKILL.md +0 -104
  297. package/skills/review-artifact/references/reviewer-prompt.md +0 -148
  298. package/skills/review-work/references/reviewer-prompt.md +0 -134
  299. package/skills/track-work/references/working-record-schema.md +0 -378
  300. package/skills/workflow/references/workflow-loop.md +0 -92
  301. /package/skills/handoff/references/{templates.md → handoff-templates.md} +0 -0
@@ -0,0 +1,1628 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ readCognitiveRoutingHistory,
4
+ type CognitiveRoutingHistoryCurrent,
5
+ type CognitiveRoutingHistoryOptions,
6
+ type CognitiveRoutingHistoryResult,
7
+ } from "./history.js";
8
+ import { PI_SESSION_MODEL_STATE_ENTRY, parsePiSessionModelStateCommit } from "./pi-session-control.js";
9
+ import type {
10
+ CognitiveRoutingCapabilityState,
11
+ CognitiveRoutingProfileName,
12
+ CognitiveRoutingSessionStart,
13
+ CognitiveRoutingThinkingLevel,
14
+ } from "./types.js";
15
+
16
+ export const COGNITIVE_ROUTING_INTENT_ENTRY = "freeflow-cognitive-routing-intent";
17
+ export const COGNITIVE_ROUTING_CONTROL_ENTRY = "freeflow-cognitive-routing-control";
18
+ export const COGNITIVE_ROUTING_INACTIVE_ENTRY = "freeflow-cognitive-routing-inactive";
19
+
20
+ export type CognitiveRoutingMechanism =
21
+ | "agent-tool"
22
+ | "profile-command"
23
+ | "profile-shortcut"
24
+ | "profile-settings"
25
+ | "session-tree"
26
+ | "session-compact"
27
+ | "activation"
28
+ | "reload-restore"
29
+ | "recovery"
30
+ | "shutdown-restore";
31
+
32
+ type CognitiveRoutingPair = {
33
+ provider: string;
34
+ modelId: string;
35
+ thinkingLevel: CognitiveRoutingThinkingLevel;
36
+ };
37
+
38
+ type CognitiveRoutingIntent = {
39
+ version: 1 | 2;
40
+ kind: "activation" | "profile" | "closing";
41
+ phase: "prepared" | "abandoned";
42
+ control: "automatic" | "manual";
43
+ source: "system" | "user" | "agent";
44
+ reason?: string;
45
+ branchId?: string | null;
46
+ epoch: string;
47
+ correlationId: string;
48
+ mechanism?: CognitiveRoutingMechanism;
49
+ decisionCorrelationId?: string;
50
+ fromPair?: CognitiveRoutingPair;
51
+ fromProfile?: CognitiveRoutingProfileName;
52
+ fromControl?: "automatic" | "manual";
53
+ profile?: CognitiveRoutingProfileName;
54
+ resumeProfile?: CognitiveRoutingProfileName;
55
+ resumeControl?: "automatic" | "manual";
56
+ resumeReason?: string;
57
+ target: CognitiveRoutingPair;
58
+ returnTarget: CognitiveRoutingPair;
59
+ };
60
+
61
+ type CognitiveRoutingControlEntry = {
62
+ version: 1 | 2;
63
+ control: "automatic";
64
+ source: "user";
65
+ mechanism?: CognitiveRoutingMechanism;
66
+ reason?: string;
67
+ branchId?: string | null;
68
+ epoch: string;
69
+ };
70
+
71
+ type CognitiveRoutingInactiveEntry = {
72
+ version: 1;
73
+ source: "user";
74
+ reason: string;
75
+ branchId?: string | null;
76
+ pair: CognitiveRoutingPair;
77
+ };
78
+
79
+ type CognitiveRoutingPersistedData =
80
+ CognitiveRoutingIntent | CognitiveRoutingControlEntry | CognitiveRoutingInactiveEntry;
81
+
82
+ type ModelStateLease = {
83
+ setState(request: CognitiveRoutingPair & { correlationId: string }): Promise<{ status: string }>;
84
+ release(): Promise<unknown>;
85
+ };
86
+
87
+ type ModelStateAcquisition =
88
+ { status: "acquired"; lease: ModelStateLease } | { status: "conflict"; owner: string } | { status: "busy" };
89
+
90
+ type ControllerPi = {
91
+ appendEntryDurable(customType: string, data: CognitiveRoutingPersistedData): void;
92
+ acquireModelStateControl(options: { label: string }): Promise<ModelStateAcquisition>;
93
+ recoverPreparedModelState?: (request: {
94
+ fromPair: CognitiveRoutingPair;
95
+ target: CognitiveRoutingPair;
96
+ correlationId: string;
97
+ }) => Promise<{ status: "restored" | "rollback-failed" | "rejected" }>;
98
+ };
99
+
100
+ type ControllerContext = {
101
+ model?: { provider?: string; id?: string };
102
+ thinkingLevel?: CognitiveRoutingThinkingLevel;
103
+ sessionManager?: {
104
+ getEntries?: () => readonly unknown[];
105
+ getBranch?: () => readonly unknown[];
106
+ getLeafId?: () => string | null;
107
+ };
108
+ };
109
+
110
+ type ControllerOptions = {
111
+ capabilityState: CognitiveRoutingCapabilityState;
112
+ pi: ControllerPi;
113
+ ctx: ControllerContext;
114
+ initialSessionStart?: CognitiveRoutingSessionStart;
115
+ label?: string;
116
+ idFactory?: () => string;
117
+ liveStateAuthoritative?: boolean;
118
+ };
119
+
120
+ export type CognitiveRoutingControlMode = "automatic" | "manual-standard" | "manual-reasoning";
121
+
122
+ export type CognitiveRoutingRuntimeStatus = "active" | "inactive" | "blocked";
123
+
124
+ export type CognitiveRoutingNativeChangeResult =
125
+ { status: "ignored" } | { status: "inactive"; reason: string } | { status: "blocked"; reason: string };
126
+
127
+ export type CognitiveRoutingControllerState = {
128
+ effective: boolean;
129
+ controlMode: CognitiveRoutingControlMode;
130
+ runtimeStatus?: CognitiveRoutingRuntimeStatus;
131
+ runtimeReason?: string;
132
+ activeProfile?: CognitiveRoutingProfileName;
133
+ epoch?: string;
134
+ returnTarget?: CognitiveRoutingPair;
135
+ };
136
+
137
+ export type CognitiveRoutingActivationResult =
138
+ { status: "active"; profile: CognitiveRoutingProfileName } | { status: "inactive"; reason: string };
139
+
140
+ export type CognitiveRoutingDeactivationResult = { status: "inactive"; reason: string };
141
+ export type CognitiveRoutingShutdownReason = "quit" | "reload" | "new" | "resume" | "fork" | undefined;
142
+
143
+ export type CognitiveRoutingManualResult =
144
+ { status: "active"; profile: CognitiveRoutingProfileName } | { status: "inactive"; reason: string };
145
+
146
+ export type CognitiveRoutingAutomaticResult = { status: "automatic" } | { status: "rejected"; reason: string };
147
+
148
+ export type CognitiveRoutingSwitchResult =
149
+ | {
150
+ status: "active";
151
+ changed: boolean;
152
+ from: CognitiveRoutingProfileName;
153
+ to: CognitiveRoutingProfileName;
154
+ profile: CognitiveRoutingProfileName;
155
+ }
156
+ | { status: "blocked"; reason: string }
157
+ | { status: "inactive"; reason: string };
158
+
159
+ type CognitiveRoutingProfileTransitionResult =
160
+ { status: "active"; profile: CognitiveRoutingProfileName } | { status: "inactive"; reason: string };
161
+
162
+ export type CognitiveRoutingRecoveryResult =
163
+ | { status: "active"; profile: CognitiveRoutingProfileName }
164
+ | { status: "pending"; reason: string }
165
+ | { status: "inactive"; reason: string };
166
+
167
+ export type CognitiveRoutingBranchResult =
168
+ | { status: "active"; profile: CognitiveRoutingProfileName }
169
+ | { status: "pending"; reason: string }
170
+ | { status: "inactive"; reason: string };
171
+
172
+ function isProfileName(value: unknown): value is CognitiveRoutingProfileName {
173
+ return value === "standard" || value === "reasoning";
174
+ }
175
+
176
+ function isMechanism(value: unknown): value is CognitiveRoutingMechanism {
177
+ return [
178
+ "agent-tool",
179
+ "profile-command",
180
+ "profile-shortcut",
181
+ "profile-settings",
182
+ "session-tree",
183
+ "session-compact",
184
+ "activation",
185
+ "reload-restore",
186
+ "recovery",
187
+ "shutdown-restore",
188
+ ].includes(value as CognitiveRoutingMechanism);
189
+ }
190
+
191
+ function asIntentSource(value: unknown): "system" | "user" | "agent" {
192
+ if (value === "user" || value === "agent") return value;
193
+ return "system";
194
+ }
195
+
196
+ function pairEquals(a: CognitiveRoutingPair | undefined, b: CognitiveRoutingPair | undefined): boolean {
197
+ return a?.provider === b?.provider && a?.modelId === b?.modelId && a?.thinkingLevel === b?.thinkingLevel;
198
+ }
199
+
200
+ function asPair(value: unknown): CognitiveRoutingPair | undefined {
201
+ if (!value || typeof value !== "object") return undefined;
202
+ const candidate = value as Record<string, unknown>;
203
+ if (
204
+ typeof candidate.provider !== "string" ||
205
+ typeof candidate.modelId !== "string" ||
206
+ typeof candidate.thinkingLevel !== "string"
207
+ ) {
208
+ return undefined;
209
+ }
210
+ return {
211
+ provider: candidate.provider,
212
+ modelId: candidate.modelId,
213
+ thinkingLevel: candidate.thinkingLevel as CognitiveRoutingThinkingLevel,
214
+ };
215
+ }
216
+
217
+ function hostPairFromEntry(entry: Record<string, unknown>): CognitiveRoutingPair | undefined {
218
+ if (entry.type === "model_state_change") {
219
+ return asPair({
220
+ provider: entry.provider,
221
+ modelId: entry.modelId,
222
+ thinkingLevel: entry.thinkingLevel,
223
+ });
224
+ }
225
+ if (entry.type !== "custom" || entry.customType !== PI_SESSION_MODEL_STATE_ENTRY) return undefined;
226
+ const commit = parsePiSessionModelStateCommit(entry.data);
227
+ if (!commit || commit.phase !== "committed" || commit.status !== "applied") return undefined;
228
+ return commit.target;
229
+ }
230
+
231
+ function hostCorrelationIdFromEntry(entry: Record<string, unknown>): string | undefined {
232
+ if (entry.type === "model_state_change") {
233
+ return typeof entry.correlationId === "string" ? entry.correlationId : undefined;
234
+ }
235
+ if (entry.type !== "custom" || entry.customType !== PI_SESSION_MODEL_STATE_ENTRY) return undefined;
236
+ const commit = parsePiSessionModelStateCommit(entry.data);
237
+ return commit?.phase === "committed" && commit.status === "applied" ? commit.correlationId : undefined;
238
+ }
239
+
240
+ function latestPiSessionCommit(entries: readonly unknown[], correlationId: string) {
241
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
242
+ const entry = entries[index];
243
+ if (!entry || typeof entry !== "object") continue;
244
+ const candidate = entry as Record<string, unknown>;
245
+ if (candidate.type !== "custom" || candidate.customType !== PI_SESSION_MODEL_STATE_ENTRY) continue;
246
+ const commit = parsePiSessionModelStateCommit(candidate.data);
247
+ if (commit?.correlationId === correlationId) return commit;
248
+ }
249
+ return undefined;
250
+ }
251
+
252
+ function latestHostPair(context: ControllerContext): CognitiveRoutingPair | undefined {
253
+ const entries = branchEntriesFrom(context);
254
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
255
+ const entry = entries[index];
256
+ if (!entry || typeof entry !== "object") continue;
257
+ const pair = hostPairFromEntry(entry as Record<string, unknown>);
258
+ if (pair) return pair;
259
+ }
260
+ return undefined;
261
+ }
262
+
263
+ function profileNameForPair(
264
+ capabilityState: CognitiveRoutingCapabilityState,
265
+ pair: CognitiveRoutingPair | undefined,
266
+ ): CognitiveRoutingProfileName | undefined {
267
+ if (!pair) return undefined;
268
+ for (const [name, profile] of Object.entries(capabilityState.resolvedProfiles)) {
269
+ if (!profile) continue;
270
+ if (
271
+ pairEquals(pair, {
272
+ provider: profile.provider,
273
+ modelId: profile.model,
274
+ thinkingLevel: profile.effectiveThinkingLevel,
275
+ })
276
+ ) {
277
+ return isProfileName(name) ? name : undefined;
278
+ }
279
+ }
280
+ return undefined;
281
+ }
282
+
283
+ function pairMatchesProfile(
284
+ capabilityState: CognitiveRoutingCapabilityState,
285
+ pair: CognitiveRoutingPair,
286
+ profileName: CognitiveRoutingProfileName,
287
+ ): boolean {
288
+ const profile = capabilityState.resolvedProfiles[profileName];
289
+ return Boolean(
290
+ profile &&
291
+ pairEquals(pair, {
292
+ provider: profile.provider,
293
+ modelId: profile.model,
294
+ thinkingLevel: profile.effectiveThinkingLevel,
295
+ }),
296
+ );
297
+ }
298
+
299
+ function asIntent(value: unknown): CognitiveRoutingIntent | undefined {
300
+ if (!value || typeof value !== "object") return undefined;
301
+ const candidate = value as Record<string, unknown>;
302
+ if (
303
+ (candidate.version !== 1 && candidate.version !== 2) ||
304
+ (candidate.kind !== "activation" && candidate.kind !== "profile" && candidate.kind !== "closing") ||
305
+ (candidate.phase !== "prepared" && candidate.phase !== "abandoned") ||
306
+ typeof candidate.epoch !== "string" ||
307
+ typeof candidate.correlationId !== "string"
308
+ ) {
309
+ return undefined;
310
+ }
311
+ const target = asPair(candidate.target);
312
+ const returnTarget = asPair(candidate.returnTarget);
313
+ const fromPair = asPair(candidate.fromPair);
314
+ if (!target || !returnTarget) return undefined;
315
+ return {
316
+ version: candidate.version,
317
+ kind: candidate.kind,
318
+ phase: candidate.phase,
319
+ control: candidate.control === "manual" ? "manual" : "automatic",
320
+ source: asIntentSource(candidate.source),
321
+ ...(isMechanism(candidate.mechanism) ? { mechanism: candidate.mechanism } : {}),
322
+ ...(typeof candidate.decisionCorrelationId === "string"
323
+ ? { decisionCorrelationId: candidate.decisionCorrelationId }
324
+ : {}),
325
+ ...(fromPair ? { fromPair } : {}),
326
+ ...(isProfileName(candidate.fromProfile) ? { fromProfile: candidate.fromProfile } : {}),
327
+ ...(candidate.fromControl === "automatic" || candidate.fromControl === "manual"
328
+ ? { fromControl: candidate.fromControl }
329
+ : {}),
330
+ ...(typeof candidate.reason === "string" ? { reason: candidate.reason } : {}),
331
+ ...(typeof candidate.branchId === "string" || candidate.branchId === null
332
+ ? { branchId: candidate.branchId as string | null }
333
+ : {}),
334
+ epoch: candidate.epoch,
335
+ correlationId: candidate.correlationId,
336
+ ...(isProfileName(candidate.profile) ? { profile: candidate.profile } : {}),
337
+ ...(isProfileName(candidate.resumeProfile) ? { resumeProfile: candidate.resumeProfile } : {}),
338
+ ...(candidate.resumeControl === "automatic" || candidate.resumeControl === "manual"
339
+ ? { resumeControl: candidate.resumeControl }
340
+ : {}),
341
+ ...(typeof candidate.resumeReason === "string" ? { resumeReason: candidate.resumeReason } : {}),
342
+ target,
343
+ returnTarget,
344
+ };
345
+ }
346
+
347
+ function asInactiveEntry(value: unknown): CognitiveRoutingInactiveEntry | undefined {
348
+ if (!value || typeof value !== "object") return undefined;
349
+ const candidate = value as Record<string, unknown>;
350
+ const pair = asPair(candidate.pair);
351
+ if (
352
+ candidate.version !== 1 ||
353
+ candidate.source !== "user" ||
354
+ typeof candidate.reason !== "string" ||
355
+ candidate.reason.length === 0 ||
356
+ !pair
357
+ ) {
358
+ return undefined;
359
+ }
360
+ return {
361
+ version: 1,
362
+ source: "user",
363
+ reason: candidate.reason,
364
+ ...(typeof candidate.branchId === "string" || candidate.branchId === null
365
+ ? { branchId: candidate.branchId as string | null }
366
+ : {}),
367
+ pair,
368
+ };
369
+ }
370
+
371
+ function latestInactiveEntry(
372
+ entries: readonly unknown[],
373
+ ): { entry: CognitiveRoutingInactiveEntry; position: number } | undefined {
374
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
375
+ const candidate = entries[index];
376
+ if (!candidate || typeof candidate !== "object") continue;
377
+ const record = candidate as Record<string, unknown>;
378
+ if (record.type !== "custom" || record.customType !== COGNITIVE_ROUTING_INACTIVE_ENTRY) continue;
379
+ const entry = asInactiveEntry(record.data);
380
+ if (entry) return { entry, position: index };
381
+ }
382
+ return undefined;
383
+ }
384
+
385
+ function entriesFrom(context: ControllerContext): readonly unknown[] {
386
+ try {
387
+ const entries = context.sessionManager?.getEntries?.();
388
+ return Array.isArray(entries) ? entries : [];
389
+ } catch {
390
+ return [];
391
+ }
392
+ }
393
+
394
+ function branchEntriesFrom(context: ControllerContext): readonly unknown[] {
395
+ try {
396
+ const entries = context.sessionManager?.getBranch?.();
397
+ return Array.isArray(entries) ? entries : entriesFrom(context);
398
+ } catch {
399
+ return entriesFrom(context);
400
+ }
401
+ }
402
+
403
+ function latestIntent(
404
+ entries: readonly unknown[],
405
+ predicate: (intent: CognitiveRoutingIntent) => boolean = () => true,
406
+ ): CognitiveRoutingIntent | undefined {
407
+ const abandonedCorrelations = new Set<string>();
408
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
409
+ const entry = entries[index];
410
+ if (!entry || typeof entry !== "object") continue;
411
+ const candidate = entry as Record<string, unknown>;
412
+ if (candidate.type !== "custom" || candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
413
+ const intent = asIntent(candidate.data);
414
+ if (!intent) continue;
415
+ if (intent.phase === "abandoned") {
416
+ abandonedCorrelations.add(intent.correlationId);
417
+ continue;
418
+ }
419
+ if (!abandonedCorrelations.has(intent.correlationId) && predicate(intent)) return intent;
420
+ }
421
+ return undefined;
422
+ }
423
+
424
+ function controlModeForIntent(intent: CognitiveRoutingIntent): CognitiveRoutingControlMode {
425
+ if (intent.control === "manual" && intent.profile) return `manual-${intent.profile}` as CognitiveRoutingControlMode;
426
+ return "automatic";
427
+ }
428
+
429
+ function decisionCorrelationForIntent(intent: CognitiveRoutingIntent): string | undefined {
430
+ if (intent.decisionCorrelationId) return intent.decisionCorrelationId;
431
+ return intent.source === "user" || intent.source === "agent" ? intent.correlationId : undefined;
432
+ }
433
+
434
+ function latestControlMode(entries: readonly unknown[], intent: CognitiveRoutingIntent): CognitiveRoutingControlMode {
435
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
436
+ const entry = entries[index];
437
+ if (!entry || typeof entry !== "object") continue;
438
+ const candidate = entry as Record<string, unknown>;
439
+ if (candidate.type !== "custom") continue;
440
+ if (candidate.customType === COGNITIVE_ROUTING_CONTROL_ENTRY) {
441
+ const data = candidate.data;
442
+ if (
443
+ data &&
444
+ typeof data === "object" &&
445
+ ((data as Record<string, unknown>).version === 1 || (data as Record<string, unknown>).version === 2) &&
446
+ (data as Record<string, unknown>).epoch === intent.epoch &&
447
+ (data as Record<string, unknown>).control === "automatic"
448
+ ) {
449
+ return "automatic";
450
+ }
451
+ }
452
+ if (candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
453
+ const candidateIntent = asIntent(candidate.data);
454
+ if (!candidateIntent || candidateIntent.epoch !== intent.epoch) continue;
455
+ if (candidateIntent.phase === "abandoned") {
456
+ if (candidateIntent.fromControl === "manual" && candidateIntent.fromProfile) {
457
+ return `manual-${candidateIntent.fromProfile}` as CognitiveRoutingControlMode;
458
+ }
459
+ if (candidateIntent.fromControl === "automatic") return "automatic";
460
+ continue;
461
+ }
462
+ if (candidateIntent.kind === "profile" || candidateIntent.kind === "activation") {
463
+ return controlModeForIntent(candidateIntent);
464
+ }
465
+ }
466
+ return "automatic";
467
+ }
468
+
469
+ function intentEntryIndex(entries: readonly unknown[], intent: CognitiveRoutingIntent): number {
470
+ for (let index = 0; index < entries.length; index += 1) {
471
+ const entry = entries[index];
472
+ if (!entry || typeof entry !== "object") continue;
473
+ const candidate = entry as Record<string, unknown>;
474
+ if (candidate.type !== "custom" || candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
475
+ const parsed = asIntent(candidate.data);
476
+ if (parsed?.correlationId === intent.correlationId && parsed.phase === "prepared") return index;
477
+ }
478
+ return entries.length;
479
+ }
480
+
481
+ function matchesBaseline(candidate: CognitiveRoutingIntent, failed: CognitiveRoutingIntent): boolean {
482
+ if (failed.fromPair && !pairEquals(candidate.target, failed.fromPair)) return false;
483
+ if (failed.fromProfile && candidate.profile !== failed.fromProfile) return false;
484
+ return true;
485
+ }
486
+
487
+ export function resolveControlBeforeIntent(
488
+ entries: readonly unknown[],
489
+ intent: CognitiveRoutingIntent,
490
+ ): CognitiveRoutingControlMode | undefined {
491
+ if (intent.fromControl === "automatic") return "automatic";
492
+ if (intent.fromControl === "manual") {
493
+ return intent.fromProfile ? (`manual-${intent.fromProfile}` as CognitiveRoutingControlMode) : undefined;
494
+ }
495
+
496
+ const priorEntries = entries.slice(0, intentEntryIndex(entries, intent));
497
+ const abandonedCorrelations = new Set<string>();
498
+ for (const entry of priorEntries) {
499
+ if (!entry || typeof entry !== "object") continue;
500
+ const candidate = entry as Record<string, unknown>;
501
+ if (candidate.type !== "custom" || candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
502
+ const parsed = asIntent(candidate.data);
503
+ if (parsed?.phase === "abandoned") abandonedCorrelations.add(parsed.correlationId);
504
+ }
505
+
506
+ let resolved: CognitiveRoutingControlMode | undefined;
507
+ for (const entry of priorEntries) {
508
+ if (!entry || typeof entry !== "object") continue;
509
+ const candidate = entry as Record<string, unknown>;
510
+ if (candidate.type !== "custom") continue;
511
+ if (candidate.customType === COGNITIVE_ROUTING_CONTROL_ENTRY) {
512
+ const data = candidate.data;
513
+ if (
514
+ data &&
515
+ typeof data === "object" &&
516
+ ((data as Record<string, unknown>).version === 1 || (data as Record<string, unknown>).version === 2) &&
517
+ (data as Record<string, unknown>).epoch === intent.epoch &&
518
+ (data as Record<string, unknown>).control === "automatic"
519
+ ) {
520
+ resolved = "automatic";
521
+ }
522
+ continue;
523
+ }
524
+ if (candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
525
+ const parsed = asIntent(candidate.data);
526
+ if (
527
+ !parsed ||
528
+ parsed.phase !== "prepared" ||
529
+ parsed.epoch !== intent.epoch ||
530
+ abandonedCorrelations.has(parsed.correlationId) ||
531
+ (parsed.kind !== "profile" && parsed.kind !== "activation") ||
532
+ !hasMatchingHostEntry(priorEntries, parsed) ||
533
+ !matchesBaseline(parsed, intent)
534
+ ) {
535
+ continue;
536
+ }
537
+ resolved = controlModeForIntent(parsed);
538
+ }
539
+ return resolved;
540
+ }
541
+
542
+ function hasMatchingHostEntry(entries: readonly unknown[], intent: CognitiveRoutingIntent): boolean {
543
+ return entries.some((entry) => {
544
+ if (!entry || typeof entry !== "object") return false;
545
+ const candidate = entry as Record<string, unknown>;
546
+ return (
547
+ hostCorrelationIdFromEntry(candidate) === intent.correlationId &&
548
+ pairEquals(hostPairFromEntry(candidate), intent.target)
549
+ );
550
+ });
551
+ }
552
+
553
+ export class CognitiveRoutingController {
554
+ private readonly capabilityState: CognitiveRoutingCapabilityState;
555
+ private readonly pi: ControllerPi;
556
+ private readonly ctx: ControllerContext;
557
+ private readonly initialSessionStart: CognitiveRoutingSessionStart | undefined;
558
+ private readonly label: string;
559
+ private readonly idFactory: () => string;
560
+ private readonly liveStateAuthoritative: boolean;
561
+ private lease: ModelStateLease | undefined;
562
+ private activeProfile: CognitiveRoutingProfileName | undefined;
563
+ private epoch: string | undefined;
564
+ private returnTarget: CognitiveRoutingPair | undefined;
565
+ private controlMode: CognitiveRoutingControlMode = "automatic";
566
+ private nativeInactiveReason: string | undefined;
567
+ private nativeBlockedReason: string | undefined;
568
+ private transitionInFlight = false;
569
+ private branchPending = false;
570
+ private operation: Promise<unknown> = Promise.resolve();
571
+
572
+ constructor(options: ControllerOptions) {
573
+ this.capabilityState = options.capabilityState;
574
+ this.pi = options.pi;
575
+ this.ctx = options.ctx;
576
+ this.initialSessionStart = options.initialSessionStart;
577
+ this.label = options.label ?? "Cognitive Routing";
578
+ this.idFactory = options.idFactory ?? randomUUID;
579
+ this.liveStateAuthoritative = options.liveStateAuthoritative === true;
580
+ }
581
+
582
+ state(): CognitiveRoutingControllerState {
583
+ const hostPair = this.liveStateAuthoritative ? undefined : latestHostPair(this.ctx);
584
+ const observedPair = this.liveStateAuthoritative ? this.currentPair() : (hostPair ?? this.currentPair());
585
+ const observedProfile = this.activeProfile ? profileNameForPair(this.capabilityState, observedPair) : undefined;
586
+ const activeProfile = this.liveStateAuthoritative
587
+ ? observedProfile
588
+ : hostPair
589
+ ? observedProfile
590
+ : (observedProfile ?? this.activeProfile);
591
+ const effective = this.lease !== undefined && activeProfile !== undefined && !this.branchPending;
592
+ return {
593
+ effective,
594
+ controlMode: this.controlMode,
595
+ ...(this.nativeBlockedReason
596
+ ? { runtimeStatus: "blocked" as const, runtimeReason: this.nativeBlockedReason }
597
+ : this.nativeInactiveReason
598
+ ? { runtimeStatus: "inactive" as const, runtimeReason: this.nativeInactiveReason }
599
+ : effective
600
+ ? { runtimeStatus: "active" as const }
601
+ : {}),
602
+ ...(activeProfile ? { activeProfile } : {}),
603
+ ...(this.epoch ? { epoch: this.epoch } : {}),
604
+ ...(this.returnTarget ? { returnTarget: { ...this.returnTarget } } : {}),
605
+ };
606
+ }
607
+
608
+ history(options: CognitiveRoutingHistoryOptions = {}): CognitiveRoutingHistoryResult {
609
+ const state = this.state();
610
+ const current: CognitiveRoutingHistoryCurrent = {
611
+ control: state.effective
612
+ ? state.controlMode === "automatic"
613
+ ? "automatic"
614
+ : "manual"
615
+ : ("unavailable" as const),
616
+ profile: state.effective && state.activeProfile ? state.activeProfile : ("unavailable" as const),
617
+ };
618
+ const profilePairs = {
619
+ ...(this.capabilityState.resolvedProfiles.standard
620
+ ? {
621
+ standard: {
622
+ provider: this.capabilityState.resolvedProfiles.standard.provider,
623
+ modelId: this.capabilityState.resolvedProfiles.standard.model,
624
+ thinkingLevel: this.capabilityState.resolvedProfiles.standard.effectiveThinkingLevel,
625
+ },
626
+ }
627
+ : {}),
628
+ ...(this.capabilityState.resolvedProfiles.reasoning
629
+ ? {
630
+ reasoning: {
631
+ provider: this.capabilityState.resolvedProfiles.reasoning.provider,
632
+ modelId: this.capabilityState.resolvedProfiles.reasoning.model,
633
+ thinkingLevel: this.capabilityState.resolvedProfiles.reasoning.effectiveThinkingLevel,
634
+ },
635
+ }
636
+ : {}),
637
+ };
638
+ return readCognitiveRoutingHistory(this.ctx, { ...options, current, profilePairs });
639
+ }
640
+
641
+ async activate(): Promise<CognitiveRoutingActivationResult> {
642
+ return this.enqueue(() => this._activate());
643
+ }
644
+
645
+ async deactivate(): Promise<CognitiveRoutingDeactivationResult> {
646
+ return this.enqueue(() => this._deactivate());
647
+ }
648
+
649
+ async shutdown(reason: CognitiveRoutingShutdownReason): Promise<CognitiveRoutingDeactivationResult> {
650
+ return this.enqueue(() =>
651
+ reason === "quit" ? this._releaseWithoutRestore() : this._deactivate(reason === "reload"),
652
+ );
653
+ }
654
+
655
+ async recover(): Promise<CognitiveRoutingRecoveryResult> {
656
+ return this.enqueue(() => this._recover());
657
+ }
658
+
659
+ async reconcileBranch(mechanism: CognitiveRoutingMechanism = "session-tree"): Promise<CognitiveRoutingBranchResult> {
660
+ return this.enqueue(() => this._reconcileBranch(mechanism));
661
+ }
662
+
663
+ async observeNativeChange(
664
+ reason: string,
665
+ source: "set" | "cycle" | "restore" | undefined = undefined,
666
+ ): Promise<CognitiveRoutingNativeChangeResult> {
667
+ if (this.transitionInFlight || source === "restore") return { status: "ignored" };
668
+ return this.enqueue(() => this._observeNativeChange(reason, source));
669
+ }
670
+
671
+ async reconcileLiveState(reason = "Pi model state diverged"): Promise<CognitiveRoutingNativeChangeResult> {
672
+ if (this.transitionInFlight) return { status: "ignored" };
673
+ return this.enqueue(() => this._observeNativeChange(reason));
674
+ }
675
+
676
+ private recordNativeInactive(reason: string, pair: CognitiveRoutingPair): CognitiveRoutingNativeChangeResult {
677
+ try {
678
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INACTIVE_ENTRY, {
679
+ version: 1,
680
+ source: "user",
681
+ reason,
682
+ branchId: this.currentBranchId(),
683
+ pair,
684
+ });
685
+ } catch {
686
+ this.nativeInactiveReason = undefined;
687
+ this.nativeBlockedReason = "inactive_state_persistence_failed";
688
+ return { status: "blocked", reason: this.nativeBlockedReason };
689
+ }
690
+
691
+ this.nativeInactiveReason = reason;
692
+ this.nativeBlockedReason = undefined;
693
+ return { status: "inactive", reason };
694
+ }
695
+
696
+ private async _observeNativeChange(
697
+ reason: string,
698
+ source: "set" | "cycle" | "restore" | undefined = undefined,
699
+ ): Promise<CognitiveRoutingNativeChangeResult> {
700
+ if (!this.lease || !this.activeProfile) return { status: "ignored" };
701
+
702
+ const profile = this.capabilityState.resolvedProfiles[this.activeProfile];
703
+ const current = this.currentPair();
704
+ const expected = profile
705
+ ? {
706
+ provider: profile.provider,
707
+ modelId: profile.model,
708
+ thinkingLevel: profile.effectiveThinkingLevel,
709
+ }
710
+ : undefined;
711
+ if (current && expected && pairEquals(current, expected) && source !== "set") return { status: "ignored" };
712
+ const lease = this.lease;
713
+ if (!current) {
714
+ await this.releaseLease(lease);
715
+ this.clearActiveState();
716
+ this.nativeBlockedReason = "native_state_unavailable";
717
+ return { status: "blocked", reason: this.nativeBlockedReason };
718
+ }
719
+
720
+ const result = this.recordNativeInactive(reason, current);
721
+ await this.releaseLease(lease);
722
+ this.clearActiveState();
723
+ return result;
724
+ }
725
+
726
+ private async _activate(
727
+ allowInactive = false,
728
+ requestedProfile?: CognitiveRoutingProfileName,
729
+ requestedControlMode?: CognitiveRoutingControlMode,
730
+ ): Promise<CognitiveRoutingActivationResult> {
731
+ if (this.state().effective && this.activeProfile) {
732
+ return { status: "active", profile: this.activeProfile };
733
+ }
734
+ if (!this.capabilityState.effective) {
735
+ return { status: "inactive", reason: "not_effective" };
736
+ }
737
+ if ((this.nativeInactiveReason || this.nativeBlockedReason) && !allowInactive) {
738
+ return {
739
+ status: "inactive",
740
+ reason: this.nativeBlockedReason ? "runtime_blocked" : "native_override",
741
+ };
742
+ }
743
+
744
+ const sessionEntries = entriesFrom(this.ctx);
745
+ const lifecycleIntent = latestIntent(
746
+ sessionEntries,
747
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
748
+ );
749
+ if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
750
+ return { status: "inactive", reason: "pending_intent" };
751
+ }
752
+ if (
753
+ lifecycleIntent?.kind === "activation" &&
754
+ !(allowInactive && (this.nativeInactiveReason || this.nativeBlockedReason))
755
+ ) {
756
+ return { status: "inactive", reason: "recover_required" };
757
+ }
758
+ const preservedReload = lifecycleIntent?.kind === "closing" && lifecycleIntent.resumeProfile !== undefined;
759
+ if (preservedReload && !lifecycleIntent.resumeControl) {
760
+ return { status: "inactive", reason: "resume_state_invalid" };
761
+ }
762
+ const returnTarget = this.currentPair();
763
+ if (!returnTarget) {
764
+ return { status: "inactive", reason: "current_state_unavailable" };
765
+ }
766
+ const epoch = this.epoch ?? this.idFactory();
767
+ const branchId = this.currentBranchId();
768
+ const sessionStart = this.initialSessionStart ??
769
+ this.capabilityState.sessionStart ?? {
770
+ control: "automatic" as const,
771
+ profile: "reasoning" as const,
772
+ };
773
+ let profileName: CognitiveRoutingProfileName;
774
+ if (requestedProfile) {
775
+ profileName = requestedProfile;
776
+ } else if (preservedReload) {
777
+ profileName = lifecycleIntent.resumeProfile;
778
+ } else if (sessionStart.control === "automatic") {
779
+ profileName = "reasoning";
780
+ } else {
781
+ profileName = sessionStart.profile;
782
+ }
783
+ const profile = this.capabilityState.resolvedProfiles[profileName];
784
+ if (!profile) {
785
+ return { status: "inactive", reason: preservedReload ? "resume_profile_unavailable" : "profile_unavailable" };
786
+ }
787
+ let controlMode: CognitiveRoutingControlMode;
788
+ if (requestedControlMode) {
789
+ controlMode = requestedControlMode;
790
+ } else if (preservedReload) {
791
+ controlMode = lifecycleIntent.resumeControl === "manual" ? `manual-${profileName}` : "automatic";
792
+ } else {
793
+ controlMode = sessionStart.control === "manual" ? `manual-${profileName}` : "automatic";
794
+ }
795
+ const target = {
796
+ provider: profile.provider,
797
+ modelId: profile.model,
798
+ thinkingLevel: profile.effectiveThinkingLevel,
799
+ };
800
+ return this.activatePrepared({
801
+ kind: "activation",
802
+ controlMode,
803
+ source: "system",
804
+ mechanism: preservedReload ? "reload-restore" : "activation",
805
+ ...(preservedReload && lifecycleIntent.resumeReason ? { reason: lifecycleIntent.resumeReason } : {}),
806
+ epoch,
807
+ branchId,
808
+ returnTarget,
809
+ target,
810
+ profile: profileName,
811
+ });
812
+ }
813
+
814
+ private async _releaseWithoutRestore(): Promise<CognitiveRoutingDeactivationResult> {
815
+ const lease = this.lease;
816
+ if (!lease) {
817
+ this.clearActiveState();
818
+ return { status: "inactive", reason: "not_active" };
819
+ }
820
+ await this.releaseLease(lease);
821
+ this.clearActiveState();
822
+ return { status: "inactive", reason: "released_on_quit" };
823
+ }
824
+
825
+ private async _deactivate(preserveSemanticState = false): Promise<CognitiveRoutingDeactivationResult> {
826
+ const lease = this.lease;
827
+ const returnTarget = this.returnTarget;
828
+ if (!lease || !returnTarget || !this.epoch) {
829
+ this.clearActiveState();
830
+ return { status: "inactive", reason: "not_active" };
831
+ }
832
+
833
+ const currentState = preserveSemanticState ? this.state() : undefined;
834
+ const resumeProfile = currentState?.effective ? currentState.activeProfile : undefined;
835
+ let resumeControl: "automatic" | "manual" | undefined;
836
+ if (resumeProfile && currentState?.controlMode === "automatic") {
837
+ resumeControl = "automatic";
838
+ } else if (resumeProfile && currentState?.controlMode === `manual-${resumeProfile}`) {
839
+ resumeControl = "manual";
840
+ }
841
+ const resumeIntent = resumeProfile
842
+ ? latestIntent(
843
+ branchEntriesFrom(this.ctx),
844
+ (candidate) => candidate.kind === "profile" && candidate.epoch === this.epoch,
845
+ )
846
+ : undefined;
847
+ const fromPair = this.observedHostPair();
848
+ const fromProfile = this.activeProfile ?? profileNameForPair(this.capabilityState, fromPair);
849
+ const intent = this.prepareIntent({
850
+ kind: "closing",
851
+ control: "automatic",
852
+ source: "system",
853
+ mechanism: "shutdown-restore",
854
+ ...(fromPair ? { fromPair } : {}),
855
+ ...(fromProfile ? { fromProfile } : {}),
856
+ ...(resumeProfile ? { resumeProfile } : {}),
857
+ ...(resumeControl ? { resumeControl } : {}),
858
+ ...(resumeIntent?.reason ? { resumeReason: resumeIntent.reason } : {}),
859
+ epoch: this.epoch,
860
+ correlationId: this.idFactory(),
861
+ branchId: this.currentBranchId(),
862
+ target: returnTarget,
863
+ returnTarget,
864
+ });
865
+ try {
866
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
867
+ } catch {
868
+ await this.releaseLease(lease);
869
+ this.clearActiveState();
870
+ return { status: "inactive", reason: "prepare_failed" };
871
+ }
872
+
873
+ this.clearActiveState(false);
874
+ try {
875
+ const result = await this.setState(lease, { ...returnTarget, correlationId: intent.correlationId });
876
+ if (result.status !== "applied" && result.status !== "unchanged") {
877
+ return { status: "inactive", reason: "restore_rejected" };
878
+ }
879
+ return { status: "inactive", reason: "restored" };
880
+ } catch {
881
+ return { status: "inactive", reason: "restore_failed" };
882
+ } finally {
883
+ await this.releaseLease(lease);
884
+ }
885
+ }
886
+
887
+ private async recoverTerminalIntent(
888
+ intent: CognitiveRoutingIntent,
889
+ ): Promise<CognitiveRoutingRecoveryResult | undefined> {
890
+ const commit = latestPiSessionCommit(branchEntriesFrom(this.ctx), intent.correlationId);
891
+ if (!commit) return undefined;
892
+ if (commit.phase === "prepared") {
893
+ if (!this.pi.recoverPreparedModelState) {
894
+ return { status: "pending", reason: "prepared_recovery_unsupported" };
895
+ }
896
+ let recovery: { status: "restored" | "rollback-failed" | "rejected" };
897
+ try {
898
+ recovery = await this.pi.recoverPreparedModelState({
899
+ fromPair: commit.fromPair,
900
+ target: commit.target,
901
+ correlationId: commit.correlationId,
902
+ });
903
+ } catch {
904
+ return { status: "pending", reason: "prepared_recovery_failed" };
905
+ }
906
+ if (recovery.status === "rollback-failed") {
907
+ return { status: "pending", reason: "rollback_failed" };
908
+ }
909
+ if (recovery.status !== "restored") {
910
+ return { status: "pending", reason: "prepared_recovery_failed" };
911
+ }
912
+ try {
913
+ this.abandonPreparedIntent(intent, "Pi session transition interrupted.");
914
+ } catch {
915
+ return { status: "pending", reason: "intent_abandon_failed" };
916
+ }
917
+ const recovered = await this._recover();
918
+ return recovered.status === "inactive" && recovered.reason === "no_pending_intent"
919
+ ? { status: "inactive", reason: "intent_abandoned" }
920
+ : recovered;
921
+ }
922
+ if (commit.phase !== "aborted") return undefined;
923
+ if (commit.status === "rollback-failed") {
924
+ return { status: "pending", reason: "rollback_failed" };
925
+ }
926
+
927
+ try {
928
+ this.abandonPreparedIntent(intent, "Pi session transition rolled back.");
929
+ } catch {
930
+ return { status: "pending", reason: "intent_abandon_failed" };
931
+ }
932
+ return this._recover();
933
+ }
934
+
935
+ private async recoverTerminalProfileIntent(
936
+ intent: CognitiveRoutingIntent,
937
+ ): Promise<CognitiveRoutingRecoveryResult | undefined> {
938
+ const commit = latestPiSessionCommit(branchEntriesFrom(this.ctx), intent.correlationId);
939
+ if (!commit || commit.phase === "committed") return undefined;
940
+ if (commit.phase === "aborted" && commit.status === "rollback-failed") {
941
+ return { status: "pending", reason: "rollback_failed" };
942
+ }
943
+
944
+ const controlMode = resolveControlBeforeIntent(branchEntriesFrom(this.ctx), intent);
945
+ if (
946
+ !controlMode ||
947
+ !intent.fromPair ||
948
+ !intent.fromProfile ||
949
+ !pairMatchesProfile(this.capabilityState, intent.fromPair, intent.fromProfile)
950
+ ) {
951
+ return { status: "pending", reason: "baseline_control_unknown" };
952
+ }
953
+
954
+ if (commit.phase === "prepared") {
955
+ if (!this.pi.recoverPreparedModelState) {
956
+ return { status: "pending", reason: "prepared_recovery_unsupported" };
957
+ }
958
+ let recovery: { status: "restored" | "rollback-failed" | "rejected" };
959
+ try {
960
+ recovery = await this.pi.recoverPreparedModelState({
961
+ fromPair: commit.fromPair,
962
+ target: commit.target,
963
+ correlationId: commit.correlationId,
964
+ });
965
+ } catch {
966
+ return { status: "pending", reason: "prepared_recovery_failed" };
967
+ }
968
+ if (recovery.status === "rollback-failed") {
969
+ return { status: "pending", reason: "rollback_failed" };
970
+ }
971
+ if (recovery.status !== "restored") {
972
+ return { status: "pending", reason: "prepared_recovery_failed" };
973
+ }
974
+ }
975
+
976
+ try {
977
+ this.abandonPreparedIntent(intent, "Pi session transition interrupted or rolled back.");
978
+ } catch {
979
+ return { status: "pending", reason: "intent_abandon_failed" };
980
+ }
981
+
982
+ const recovered = await this.activatePrepared({
983
+ kind: "profile",
984
+ controlMode,
985
+ source: "system",
986
+ mechanism: "recovery",
987
+ ...(decisionCorrelationForIntent(intent) ? { decisionCorrelationId: decisionCorrelationForIntent(intent) } : {}),
988
+ branchId: this.currentBranchId(),
989
+ epoch: intent.epoch,
990
+ returnTarget: intent.returnTarget,
991
+ target: intent.fromPair,
992
+ profile: intent.fromProfile,
993
+ });
994
+ return recovered.status === "active" ? recovered : { status: "pending", reason: "baseline_recovery_failed" };
995
+ }
996
+
997
+ private async _recover(): Promise<CognitiveRoutingRecoveryResult> {
998
+ const sessionEntries = entriesFrom(this.ctx);
999
+ const branchEntries = branchEntriesFrom(this.ctx);
1000
+ const inactive = latestInactiveEntry(branchEntries);
1001
+ const branchLifecycleIntent = latestIntent(
1002
+ branchEntries,
1003
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
1004
+ );
1005
+ if (
1006
+ inactive &&
1007
+ (!branchLifecycleIntent || intentEntryIndex(branchEntries, branchLifecycleIntent) <= inactive.position)
1008
+ ) {
1009
+ this.nativeInactiveReason = inactive.entry.reason;
1010
+ this.nativeBlockedReason = undefined;
1011
+ this.clearActiveState();
1012
+ return { status: "inactive", reason: "native_override" };
1013
+ }
1014
+ const lifecycleIntent = latestIntent(
1015
+ sessionEntries,
1016
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
1017
+ );
1018
+ if (!lifecycleIntent) {
1019
+ return { status: "inactive", reason: "no_pending_intent" };
1020
+ }
1021
+ if (lifecycleIntent.kind === "activation") {
1022
+ const lifecycleTerminal = await this.recoverTerminalIntent(lifecycleIntent);
1023
+ if (lifecycleTerminal) return lifecycleTerminal;
1024
+ }
1025
+ if (lifecycleIntent.kind === "closing") {
1026
+ return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
1027
+ ? { status: "inactive", reason: "closed" }
1028
+ : this.recoverClosingIntent(lifecycleIntent);
1029
+ }
1030
+
1031
+ const currentActivationProfile = this.capabilityState.resolvedProfiles[lifecycleIntent.profile ?? "standard"];
1032
+ if (!this.capabilityState.effective) {
1033
+ return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
1034
+ ? { status: "inactive", reason: "not_effective" }
1035
+ : this.abandonIntent(lifecycleIntent, "Cognitive Routing is not effective.");
1036
+ }
1037
+ if (!currentActivationProfile) {
1038
+ return this.abandonIntent(lifecycleIntent, "Prepared profile is unavailable.");
1039
+ }
1040
+ const activationTarget = {
1041
+ provider: currentActivationProfile.provider,
1042
+ modelId: currentActivationProfile.model,
1043
+ thinkingLevel: currentActivationProfile.effectiveThinkingLevel,
1044
+ };
1045
+ const activationMatched = hasMatchingHostEntry(sessionEntries, lifecycleIntent);
1046
+ if (this.liveStateAuthoritative && activationMatched) {
1047
+ const livePair = this.currentPair();
1048
+ if (!livePair) {
1049
+ this.clearActiveState();
1050
+ this.nativeBlockedReason = "native_state_unavailable";
1051
+ return { status: "inactive", reason: "native_override" };
1052
+ }
1053
+ if (!pairEquals(livePair, activationTarget)) {
1054
+ this.recordNativeInactive("Pi model state diverged during recovery", livePair);
1055
+ this.clearActiveState();
1056
+ return { status: "inactive", reason: "native_override" };
1057
+ }
1058
+ }
1059
+ if (activationMatched && !pairEquals(activationTarget, lifecycleIntent.target)) {
1060
+ return { status: "pending", reason: "applied_target_changed" };
1061
+ }
1062
+ if (!activationMatched && !pairEquals(activationTarget, lifecycleIntent.target)) {
1063
+ return this.abandonIntent(lifecycleIntent, "Prepared profile target changed.");
1064
+ }
1065
+ if (!activationMatched) {
1066
+ const retried = await this.activatePrepared({
1067
+ kind: "activation",
1068
+ controlMode: latestControlMode(branchEntries, lifecycleIntent),
1069
+ source: "system",
1070
+ mechanism: "recovery",
1071
+ branchId: this.currentBranchId(),
1072
+ epoch: lifecycleIntent.epoch,
1073
+ returnTarget: lifecycleIntent.returnTarget,
1074
+ target: lifecycleIntent.target,
1075
+ profile: lifecycleIntent.profile ?? "standard",
1076
+ });
1077
+ return retried.status === "active" ? retried : { status: "pending", reason: "activation_recovery_failed" };
1078
+ }
1079
+
1080
+ const profileIntent = latestIntent(
1081
+ branchEntries,
1082
+ (intent) => intent.kind === "profile" && intent.epoch === lifecycleIntent.epoch,
1083
+ );
1084
+ if (profileIntent) {
1085
+ const terminal = await this.recoverTerminalProfileIntent(profileIntent);
1086
+ if (terminal) return terminal;
1087
+ const currentProfile = this.capabilityState.resolvedProfiles[profileIntent.profile ?? "standard"];
1088
+ if (!currentProfile) {
1089
+ return this.abandonIntent(profileIntent, "Prepared profile is unavailable.");
1090
+ }
1091
+ const profileTarget = {
1092
+ provider: currentProfile.provider,
1093
+ modelId: currentProfile.model,
1094
+ thinkingLevel: currentProfile.effectiveThinkingLevel,
1095
+ };
1096
+ if (!pairEquals(profileTarget, profileIntent.target)) {
1097
+ return hasMatchingHostEntry(branchEntries, profileIntent)
1098
+ ? { status: "pending", reason: "applied_target_changed" }
1099
+ : this.abandonIntent(profileIntent, "Prepared profile target changed.");
1100
+ }
1101
+ const profileMatched = hasMatchingHostEntry(branchEntries, profileIntent);
1102
+ const retried = await this.activatePrepared({
1103
+ kind: "profile",
1104
+ controlMode: latestControlMode(branchEntries, profileIntent),
1105
+ source: "system",
1106
+ mechanism: "recovery",
1107
+ ...(decisionCorrelationForIntent(profileIntent)
1108
+ ? { decisionCorrelationId: decisionCorrelationForIntent(profileIntent) }
1109
+ : {}),
1110
+ branchId: this.currentBranchId(),
1111
+ epoch: lifecycleIntent.epoch,
1112
+ returnTarget: lifecycleIntent.returnTarget,
1113
+ target: profileMatched ? profileTarget : profileIntent.target,
1114
+ profile: profileIntent.profile ?? "standard",
1115
+ });
1116
+ return retried.status === "active" ? retried : { status: "pending", reason: "profile_recovery_failed" };
1117
+ }
1118
+
1119
+ return this.activatePrepared({
1120
+ kind: "activation",
1121
+ controlMode: latestControlMode(branchEntries, lifecycleIntent),
1122
+ source: "system",
1123
+ mechanism: "recovery",
1124
+ branchId: this.currentBranchId(),
1125
+ epoch: lifecycleIntent.epoch,
1126
+ returnTarget: lifecycleIntent.returnTarget,
1127
+ target: activationTarget,
1128
+ profile: lifecycleIntent.profile ?? "standard",
1129
+ });
1130
+ }
1131
+
1132
+ private async recoverClosingIntent(intent: CognitiveRoutingIntent): Promise<CognitiveRoutingRecoveryResult> {
1133
+ const fromPair = this.observedHostPair();
1134
+ const fromProfile = intent.fromProfile ?? profileNameForPair(this.capabilityState, fromPair);
1135
+ const retryIntent = this.prepareIntent({
1136
+ kind: "closing",
1137
+ control: "automatic",
1138
+ source: "system",
1139
+ mechanism: "shutdown-restore",
1140
+ ...(fromPair ? { fromPair } : {}),
1141
+ ...(fromProfile ? { fromProfile } : {}),
1142
+ reason: "Closing recovery",
1143
+ ...(intent.resumeProfile ? { resumeProfile: intent.resumeProfile } : {}),
1144
+ ...(intent.resumeControl ? { resumeControl: intent.resumeControl } : {}),
1145
+ ...(intent.resumeReason ? { resumeReason: intent.resumeReason } : {}),
1146
+ branchId: this.currentBranchId(),
1147
+ epoch: intent.epoch,
1148
+ correlationId: this.idFactory(),
1149
+ target: intent.target,
1150
+ returnTarget: intent.returnTarget,
1151
+ });
1152
+ try {
1153
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, retryIntent);
1154
+ } catch {
1155
+ return { status: "pending", reason: "closing_recovery_prepare_failed" };
1156
+ }
1157
+
1158
+ let acquisition: ModelStateAcquisition;
1159
+ try {
1160
+ acquisition = await this.pi.acquireModelStateControl({ label: this.label });
1161
+ } catch {
1162
+ return { status: "pending", reason: "closing_recovery_acquire_failed" };
1163
+ }
1164
+ if (acquisition.status !== "acquired") {
1165
+ return { status: "pending", reason: `closing_recovery_acquire_${acquisition.status}` };
1166
+ }
1167
+
1168
+ try {
1169
+ const result = await this.setState(acquisition.lease, {
1170
+ ...intent.target,
1171
+ correlationId: retryIntent.correlationId,
1172
+ });
1173
+ return result.status === "applied" || result.status === "unchanged"
1174
+ ? { status: "inactive", reason: "restored" }
1175
+ : { status: "pending", reason: "closing_recovery_rejected" };
1176
+ } catch {
1177
+ return { status: "pending", reason: "closing_recovery_failed" };
1178
+ } finally {
1179
+ await this.releaseLease(acquisition.lease);
1180
+ }
1181
+ }
1182
+
1183
+ private abandonPreparedIntent(intent: CognitiveRoutingIntent, reason: string): void {
1184
+ const fromPair = intent.fromPair ?? this.observedHostPair();
1185
+ const fromProfile = intent.fromProfile ?? profileNameForPair(this.capabilityState, fromPair);
1186
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, {
1187
+ ...intent,
1188
+ version: 2,
1189
+ phase: "abandoned",
1190
+ source: "system",
1191
+ mechanism: intent.mechanism ?? "recovery",
1192
+ ...(fromPair ? { fromPair } : {}),
1193
+ ...(fromProfile ? { fromProfile } : {}),
1194
+ reason,
1195
+ });
1196
+ }
1197
+
1198
+ private async abandonIntent(intent: CognitiveRoutingIntent, reason: string): Promise<CognitiveRoutingRecoveryResult> {
1199
+ try {
1200
+ this.abandonPreparedIntent(intent, reason);
1201
+ const recovered = await this._recover();
1202
+ return recovered.status === "inactive" && recovered.reason === "no_pending_intent"
1203
+ ? { status: "inactive", reason: "intent_abandoned" }
1204
+ : recovered;
1205
+ } catch {
1206
+ return { status: "pending", reason: "intent_abandon_failed" };
1207
+ }
1208
+ }
1209
+
1210
+ private async _reconcileBranch(mechanism: CognitiveRoutingMechanism): Promise<CognitiveRoutingBranchResult> {
1211
+ if (!this.capabilityState.effective) return { status: "inactive", reason: "not_effective" };
1212
+ if (!this.activeProfile || !this.lease) {
1213
+ return { status: "inactive", reason: "not_active" };
1214
+ }
1215
+
1216
+ const currentProfile = this.activeProfile;
1217
+ const sessionEntries = entriesFrom(this.ctx);
1218
+ const lifecycleIntent = latestIntent(
1219
+ sessionEntries,
1220
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
1221
+ );
1222
+ if (lifecycleIntent?.kind === "closing") {
1223
+ this.branchPending = true;
1224
+ return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
1225
+ ? { status: "inactive", reason: "closed" }
1226
+ : { status: "pending", reason: "closing_intent_unmatched" };
1227
+ }
1228
+ if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
1229
+ this.branchPending = true;
1230
+ return { status: "pending", reason: "activation_intent_unmatched" };
1231
+ }
1232
+
1233
+ const entries = branchEntriesFrom(this.ctx);
1234
+ const intent = latestIntent(
1235
+ entries,
1236
+ (candidate) => candidate.kind === "profile" && candidate.epoch === lifecycleIntent?.epoch,
1237
+ );
1238
+ if (!intent) {
1239
+ this.branchPending = false;
1240
+ return { status: "active", profile: currentProfile };
1241
+ }
1242
+ if (!hasMatchingHostEntry(entries, intent)) {
1243
+ this.branchPending = true;
1244
+ return { status: "pending", reason: "branch_intent_unmatched" };
1245
+ }
1246
+
1247
+ const decisionCorrelationId = decisionCorrelationForIntent(intent);
1248
+ if (intent.source === "system" && !decisionCorrelationId) {
1249
+ this.branchPending = false;
1250
+ return { status: "active", profile: currentProfile };
1251
+ }
1252
+ if (!intent.profile) {
1253
+ this.branchPending = false;
1254
+ return { status: "active", profile: currentProfile };
1255
+ }
1256
+
1257
+ const controlMode = latestControlMode(entries, intent);
1258
+ if (this.activeProfile === intent.profile && this.controlMode === controlMode) {
1259
+ this.branchPending = false;
1260
+ return { status: "active", profile: intent.profile };
1261
+ }
1262
+ const result = await this._setProfile(intent.profile, {
1263
+ controlMode,
1264
+ source: "system",
1265
+ mechanism,
1266
+ ...(decisionCorrelationId ? { decisionCorrelationId } : {}),
1267
+ reason: "Branch reconciliation",
1268
+ });
1269
+ this.branchPending = result.status !== "active";
1270
+ return result;
1271
+ }
1272
+
1273
+ async setManualProfile(
1274
+ profile: CognitiveRoutingProfileName,
1275
+ mechanism: CognitiveRoutingMechanism = "profile-command",
1276
+ ): Promise<CognitiveRoutingManualResult> {
1277
+ return this.enqueue(() => this._setManualProfile(profile, mechanism));
1278
+ }
1279
+
1280
+ async setAutomaticControl(
1281
+ mechanism: CognitiveRoutingMechanism = "profile-command",
1282
+ ): Promise<CognitiveRoutingAutomaticResult> {
1283
+ return this.enqueue(() => this._setAutomaticControl(mechanism));
1284
+ }
1285
+
1286
+ async switchAutomaticProfile(
1287
+ profile: CognitiveRoutingProfileName,
1288
+ reason: string,
1289
+ source: "agent" | "system" | "user" = "agent",
1290
+ mechanism: CognitiveRoutingMechanism = "agent-tool",
1291
+ ): Promise<CognitiveRoutingSwitchResult> {
1292
+ return this.enqueue(() => this._switchAutomaticProfile(profile, reason, source, mechanism));
1293
+ }
1294
+
1295
+ private async _setManualProfile(
1296
+ profile: CognitiveRoutingProfileName,
1297
+ mechanism: CognitiveRoutingMechanism,
1298
+ ): Promise<CognitiveRoutingManualResult> {
1299
+ if (!this.capabilityState.effective) {
1300
+ return { status: "inactive", reason: "not_effective" };
1301
+ }
1302
+
1303
+ if (!this.state().effective) {
1304
+ return this._activate(true, profile, `manual-${profile}`);
1305
+ }
1306
+ return this._setProfile(profile, {
1307
+ controlMode: `manual-${profile}`,
1308
+ source: "user",
1309
+ mechanism,
1310
+ reason: "manual profile command",
1311
+ });
1312
+ }
1313
+
1314
+ private async _switchAutomaticProfile(
1315
+ profile: CognitiveRoutingProfileName,
1316
+ reason: string,
1317
+ source: "agent" | "system" | "user",
1318
+ mechanism: CognitiveRoutingMechanism,
1319
+ ): Promise<CognitiveRoutingSwitchResult> {
1320
+ if (!this.capabilityState.effective) return { status: "blocked", reason: "not_effective" };
1321
+ const current = this.state();
1322
+ if (!current.effective) return { status: "blocked", reason: "not_active" };
1323
+ if (this.controlMode !== "automatic") return { status: "blocked", reason: "manual_hold" };
1324
+ const from = current.activeProfile;
1325
+ if (!from) return { status: "blocked", reason: "profile_unknown" };
1326
+ if (from === profile) return { status: "active", changed: false, from, to: profile, profile };
1327
+
1328
+ const transition = await this._setProfile(profile, { controlMode: "automatic", source, reason, mechanism });
1329
+ if (transition.status !== "active") return transition;
1330
+ return { status: "active", changed: true, from, to: transition.profile, profile: transition.profile };
1331
+ }
1332
+
1333
+ private async _setProfile(
1334
+ profile: CognitiveRoutingProfileName,
1335
+ options: {
1336
+ controlMode: CognitiveRoutingControlMode;
1337
+ source: "system" | "user" | "agent";
1338
+ mechanism: CognitiveRoutingMechanism;
1339
+ decisionCorrelationId?: string;
1340
+ reason: string;
1341
+ },
1342
+ ): Promise<CognitiveRoutingProfileTransitionResult> {
1343
+ const resolvedProfile = this.capabilityState.resolvedProfiles[profile];
1344
+ const lease = this.lease;
1345
+ if (!resolvedProfile || !lease || !this.epoch || !this.returnTarget) {
1346
+ return { status: "inactive", reason: "profile_unavailable" };
1347
+ }
1348
+ const target = {
1349
+ provider: resolvedProfile.provider,
1350
+ modelId: resolvedProfile.model,
1351
+ thinkingLevel: resolvedProfile.effectiveThinkingLevel,
1352
+ };
1353
+ const fromPair = this.observedHostPair();
1354
+ if (!fromPair) return { status: "inactive", reason: "current_state_unavailable" };
1355
+ const fromProfile = this.activeProfile ?? profileNameForPair(this.capabilityState, fromPair);
1356
+ const correlationId = this.idFactory();
1357
+ const decisionCorrelationId =
1358
+ options.decisionCorrelationId ??
1359
+ (options.source === "user" || options.source === "agent" ? correlationId : undefined);
1360
+ const intent = this.prepareIntent({
1361
+ kind: "profile",
1362
+ control: options.controlMode === "automatic" ? "automatic" : "manual",
1363
+ source: options.source,
1364
+ mechanism: options.mechanism,
1365
+ ...(decisionCorrelationId ? { decisionCorrelationId } : {}),
1366
+ ...(fromPair ? { fromPair } : {}),
1367
+ ...(fromProfile ? { fromProfile } : {}),
1368
+ fromControl: options.controlMode === "automatic" ? "automatic" : "manual",
1369
+ reason: options.reason,
1370
+ branchId: this.currentBranchId(),
1371
+ epoch: this.epoch,
1372
+ correlationId,
1373
+ profile,
1374
+ target,
1375
+ returnTarget: this.returnTarget,
1376
+ });
1377
+ const sessionEntries = entriesFrom(this.ctx);
1378
+ const lifecycleIntent = latestIntent(
1379
+ sessionEntries,
1380
+ (candidate) => candidate.kind === "activation" || candidate.kind === "closing",
1381
+ );
1382
+ if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
1383
+ return { status: "inactive", reason: "pending_intent" };
1384
+ }
1385
+ const entries = branchEntriesFrom(this.ctx);
1386
+ const latest = latestIntent(entries, (candidate) => candidate.kind === "profile" && candidate.epoch === this.epoch);
1387
+ if (latest && !hasMatchingHostEntry(entries, latest)) {
1388
+ return { status: "inactive", reason: "pending_intent" };
1389
+ }
1390
+ try {
1391
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
1392
+ this.branchPending = true;
1393
+ } catch {
1394
+ return { status: "inactive", reason: "prepare_failed" };
1395
+ }
1396
+
1397
+ try {
1398
+ const result = await this.setState(lease, { ...target, correlationId: intent.correlationId });
1399
+ if (result.status !== "applied" && result.status !== "unchanged") {
1400
+ const commit = latestPiSessionCommit(branchEntriesFrom(this.ctx), intent.correlationId);
1401
+ if (result.status === "rejected" && commit?.phase === "aborted" && commit.status === "rollback-failed") {
1402
+ try {
1403
+ this.abandonPreparedIntent(intent, "Pi session rollback failed.");
1404
+ } catch {
1405
+ // Fail closed even when the terminal abandonment cannot be persisted.
1406
+ }
1407
+ await this.releaseLease(lease);
1408
+ this.clearActiveState();
1409
+ return { status: "inactive", reason: "rollback_failed" };
1410
+ }
1411
+ if (result.status === "rejected" && commit?.phase === "aborted" && commit.status === "rolled-back") {
1412
+ try {
1413
+ this.abandonPreparedIntent(intent, "Pi session transition rolled back.");
1414
+ this.branchPending = false;
1415
+ } catch {
1416
+ // Preserve the pending boundary when the terminal abandonment cannot be persisted.
1417
+ }
1418
+ }
1419
+ return { status: "inactive", reason: "transition_rejected" };
1420
+ }
1421
+ this.activeProfile = profile;
1422
+ this.controlMode = options.controlMode;
1423
+ this.branchPending = false;
1424
+ return { status: "active", profile };
1425
+ } catch {
1426
+ return { status: "inactive", reason: "transition_failed" };
1427
+ }
1428
+ }
1429
+
1430
+ private async _setAutomaticControl(mechanism: CognitiveRoutingMechanism): Promise<CognitiveRoutingAutomaticResult> {
1431
+ if (!this.lease || !this.epoch) {
1432
+ if (!this.nativeInactiveReason && !this.nativeBlockedReason) return { status: "rejected", reason: "not_active" };
1433
+ const activation = await this._activate(true, this.profileForCurrentPair(), "automatic");
1434
+ return activation.status === "active"
1435
+ ? { status: "automatic" }
1436
+ : { status: "rejected", reason: activation.reason };
1437
+ }
1438
+ const current = this.state();
1439
+ if (!current.activeProfile) {
1440
+ return { status: "rejected", reason: "profile_unknown" };
1441
+ }
1442
+ if (current.activeProfile !== "reasoning") {
1443
+ const transition = await this._setProfile("reasoning", {
1444
+ controlMode: "automatic",
1445
+ source: "user",
1446
+ mechanism,
1447
+ reason: "automatic control selects the Reasoning profile",
1448
+ });
1449
+ if (transition.status !== "active") return { status: "rejected", reason: transition.reason };
1450
+ return { status: "automatic" };
1451
+ }
1452
+ if (this.controlMode === "automatic") return { status: "automatic" };
1453
+ try {
1454
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_CONTROL_ENTRY, {
1455
+ version: 2,
1456
+ control: "automatic",
1457
+ source: "user",
1458
+ mechanism,
1459
+ reason: "manual hold release",
1460
+ branchId: this.currentBranchId(),
1461
+ epoch: this.epoch,
1462
+ });
1463
+ } catch {
1464
+ return { status: "rejected", reason: "prepare_failed" };
1465
+ }
1466
+ this.controlMode = "automatic";
1467
+ return { status: "automatic" };
1468
+ }
1469
+
1470
+ private currentBranchId(): string | null | undefined {
1471
+ const leafId = this.ctx.sessionManager?.getLeafId?.();
1472
+ if (typeof leafId === "string" || leafId === null) return leafId;
1473
+ try {
1474
+ const branch = this.ctx.sessionManager?.getBranch?.();
1475
+ const last = Array.isArray(branch) ? branch.at(-1) : undefined;
1476
+ return last && typeof last === "object" && typeof (last as Record<string, unknown>).id === "string"
1477
+ ? ((last as Record<string, unknown>).id as string)
1478
+ : undefined;
1479
+ } catch {
1480
+ return undefined;
1481
+ }
1482
+ }
1483
+
1484
+ private observedHostPair(): CognitiveRoutingPair | undefined {
1485
+ const livePair = this.currentPair();
1486
+ return this.liveStateAuthoritative ? livePair : (latestHostPair(this.ctx) ?? livePair);
1487
+ }
1488
+
1489
+ private profileForCurrentPair(): CognitiveRoutingProfileName | undefined {
1490
+ return profileNameForPair(this.capabilityState, this.currentPair());
1491
+ }
1492
+
1493
+ private currentPair(): CognitiveRoutingPair | undefined {
1494
+ const model = this.ctx.model;
1495
+ if (
1496
+ !model ||
1497
+ typeof model.provider !== "string" ||
1498
+ typeof model.id !== "string" ||
1499
+ typeof this.ctx.thinkingLevel !== "string"
1500
+ ) {
1501
+ return undefined;
1502
+ }
1503
+ return {
1504
+ provider: model.provider,
1505
+ modelId: model.id,
1506
+ thinkingLevel: this.ctx.thinkingLevel,
1507
+ };
1508
+ }
1509
+
1510
+ private prepareIntent(input: Omit<CognitiveRoutingIntent, "version" | "phase">): CognitiveRoutingIntent {
1511
+ return { version: 2, phase: "prepared", ...input };
1512
+ }
1513
+
1514
+ private async activatePrepared(options: {
1515
+ kind: "activation" | "profile";
1516
+ controlMode: CognitiveRoutingControlMode;
1517
+ source: "system" | "user" | "agent";
1518
+ mechanism: CognitiveRoutingMechanism;
1519
+ decisionCorrelationId?: string;
1520
+ branchId?: string | null;
1521
+ reason?: string;
1522
+ epoch: string;
1523
+ returnTarget: CognitiveRoutingPair;
1524
+ target: CognitiveRoutingPair;
1525
+ profile: CognitiveRoutingProfileName;
1526
+ }): Promise<CognitiveRoutingActivationResult> {
1527
+ const fromPair = this.observedHostPair();
1528
+ if (!fromPair) return { status: "inactive", reason: "current_state_unavailable" };
1529
+ const fromProfile = profileNameForPair(this.capabilityState, fromPair);
1530
+ const correlationId = this.idFactory();
1531
+ const decisionCorrelationId =
1532
+ options.decisionCorrelationId ??
1533
+ (options.source === "user" || options.source === "agent" ? correlationId : undefined);
1534
+ const intent = this.prepareIntent({
1535
+ kind: options.kind,
1536
+ control: options.controlMode === "automatic" ? "automatic" : "manual",
1537
+ source: options.source,
1538
+ mechanism: options.mechanism,
1539
+ ...(decisionCorrelationId ? { decisionCorrelationId } : {}),
1540
+ ...(fromPair ? { fromPair } : {}),
1541
+ ...(fromProfile ? { fromProfile } : {}),
1542
+ ...(options.reason ? { reason: options.reason } : {}),
1543
+ ...(options.branchId === undefined ? {} : { branchId: options.branchId }),
1544
+ epoch: options.epoch,
1545
+ correlationId,
1546
+ profile: options.profile,
1547
+ target: options.target,
1548
+ returnTarget: options.returnTarget,
1549
+ });
1550
+ try {
1551
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
1552
+ } catch {
1553
+ return { status: "inactive", reason: "prepare_failed" };
1554
+ }
1555
+
1556
+ let acquisition: ModelStateAcquisition;
1557
+ try {
1558
+ acquisition = await this.pi.acquireModelStateControl({ label: this.label });
1559
+ } catch {
1560
+ return { status: "inactive", reason: "acquire_failed" };
1561
+ }
1562
+ if (acquisition.status !== "acquired") {
1563
+ return { status: "inactive", reason: `acquire_${acquisition.status}` };
1564
+ }
1565
+
1566
+ this.lease = acquisition.lease;
1567
+ try {
1568
+ const result = await this.setState(acquisition.lease, { ...options.target, correlationId: intent.correlationId });
1569
+ if (result.status !== "applied" && result.status !== "unchanged") {
1570
+ await this.releaseLease(acquisition.lease);
1571
+ this.clearActiveState();
1572
+ return { status: "inactive", reason: "transition_rejected" };
1573
+ }
1574
+ this.epoch = options.epoch;
1575
+ this.returnTarget = options.returnTarget;
1576
+ this.activeProfile = options.profile;
1577
+ this.controlMode = options.controlMode;
1578
+ this.nativeInactiveReason = undefined;
1579
+ this.nativeBlockedReason = undefined;
1580
+ return { status: "active", profile: options.profile };
1581
+ } catch {
1582
+ await this.releaseLease(acquisition.lease);
1583
+ this.clearActiveState();
1584
+ return { status: "inactive", reason: "transition_failed" };
1585
+ }
1586
+ }
1587
+
1588
+ private enqueue<T>(operation: () => Promise<T>): Promise<T> {
1589
+ const next = this.operation.then(operation, operation);
1590
+ this.operation = next.then(
1591
+ () => undefined,
1592
+ () => undefined,
1593
+ );
1594
+ return next;
1595
+ }
1596
+
1597
+ private async setState(
1598
+ lease: ModelStateLease,
1599
+ request: CognitiveRoutingPair & { correlationId: string },
1600
+ ): Promise<{ status: string }> {
1601
+ this.transitionInFlight = true;
1602
+ try {
1603
+ return await lease.setState(request);
1604
+ } finally {
1605
+ this.transitionInFlight = false;
1606
+ }
1607
+ }
1608
+
1609
+ private async releaseLease(lease: ModelStateLease): Promise<void> {
1610
+ try {
1611
+ await lease.release();
1612
+ } catch {
1613
+ // The host invalidates stale leases independently; do not retain local ownership after cleanup.
1614
+ }
1615
+ if (this.lease === lease) this.lease = undefined;
1616
+ }
1617
+
1618
+ private clearActiveState(clearReturnTarget = true): void {
1619
+ this.lease = undefined;
1620
+ this.activeProfile = undefined;
1621
+ this.controlMode = "automatic";
1622
+ this.branchPending = false;
1623
+ if (clearReturnTarget) {
1624
+ this.epoch = undefined;
1625
+ this.returnTarget = undefined;
1626
+ }
1627
+ }
1628
+ }