@hassangameryt/freeflow 0.5.0 → 0.6.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 (284) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/README.md +148 -154
  5. package/capabilities/cognitive-routing/SKILL.md +229 -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 -13
  9. package/hooks/freeflow-runtime-context.mjs +35 -91
  10. package/hooks/tests/check-runtime-context-hook.sh +56 -39
  11. package/package.json +24 -16
  12. package/pi-extension/dist/cognitive-routing/commands.js +96 -0
  13. package/pi-extension/dist/cognitive-routing/config.js +236 -0
  14. package/pi-extension/dist/cognitive-routing/controller.js +862 -0
  15. package/pi-extension/dist/cognitive-routing/history.js +439 -0
  16. package/pi-extension/dist/cognitive-routing/host.js +126 -0
  17. package/pi-extension/dist/cognitive-routing/runtime.js +43 -0
  18. package/pi-extension/dist/cognitive-routing/tool.js +211 -0
  19. package/pi-extension/dist/cognitive-routing/types.js +6 -0
  20. package/pi-extension/dist/context-virtualization/commands.js +89 -0
  21. package/pi-extension/dist/context-virtualization/projector.js +42 -0
  22. package/pi-extension/dist/context-virtualization/runtime.js +356 -0
  23. package/pi-extension/dist/context-virtualization/state.js +57 -0
  24. package/pi-extension/dist/context-virtualization/types.js +10 -0
  25. package/pi-extension/dist/conversation-history/passages.js +66 -0
  26. package/pi-extension/dist/conversation-history/ranking.js +105 -0
  27. package/pi-extension/dist/conversation-history/runtime.js +226 -0
  28. package/pi-extension/dist/conversation-history/search.js +56 -0
  29. package/pi-extension/dist/conversation-history/types.js +1 -0
  30. package/pi-extension/dist/freeflow-context/resolver.js +120 -0
  31. package/pi-extension/dist/freeflow-context/runtime.js +80 -0
  32. package/pi-extension/dist/freeflow-context/source-projector.js +95 -0
  33. package/pi-extension/dist/freeflow-context/tool.js +308 -0
  34. package/pi-extension/dist/freeflow-context/types.js +12 -0
  35. package/pi-extension/dist/freeflow-context/visibility.js +28 -0
  36. package/pi-extension/dist/index.js +516 -98
  37. package/pi-extension/dist/runtime/runtime-context.js +318 -271
  38. package/pi-extension/dist/runtime/runtime-identity.js +5 -0
  39. package/pi-extension/dist/settings/settings-tui.js +78 -0
  40. package/pi-extension/dist/settings/settings-ui.js +593 -563
  41. package/pi-extension/dist/ui/text-component.js +57 -0
  42. package/pi-extension/src/cognitive-routing/commands.ts +119 -0
  43. package/pi-extension/src/cognitive-routing/config.ts +307 -0
  44. package/pi-extension/src/cognitive-routing/controller.ts +1118 -0
  45. package/pi-extension/src/cognitive-routing/history.ts +638 -0
  46. package/pi-extension/src/cognitive-routing/host.ts +172 -0
  47. package/pi-extension/src/cognitive-routing/runtime.ts +57 -0
  48. package/pi-extension/src/cognitive-routing/tool.ts +272 -0
  49. package/pi-extension/src/cognitive-routing/types.ts +89 -0
  50. package/pi-extension/src/context-virtualization/commands.ts +111 -0
  51. package/pi-extension/src/context-virtualization/projector.ts +62 -0
  52. package/pi-extension/src/context-virtualization/runtime.ts +406 -0
  53. package/pi-extension/src/context-virtualization/state.ts +79 -0
  54. package/pi-extension/src/context-virtualization/types.ts +92 -0
  55. package/pi-extension/src/conversation-history/passages.ts +81 -0
  56. package/pi-extension/src/conversation-history/ranking.ts +155 -0
  57. package/pi-extension/src/conversation-history/runtime.ts +250 -0
  58. package/pi-extension/src/conversation-history/search.ts +79 -0
  59. package/pi-extension/src/conversation-history/types.ts +31 -0
  60. package/pi-extension/src/freeflow-context/resolver.ts +139 -0
  61. package/pi-extension/src/freeflow-context/runtime.ts +100 -0
  62. package/pi-extension/src/freeflow-context/source-projector.ts +106 -0
  63. package/pi-extension/src/freeflow-context/tool.ts +360 -0
  64. package/pi-extension/src/freeflow-context/types.ts +70 -0
  65. package/pi-extension/src/freeflow-context/visibility.ts +53 -0
  66. package/pi-extension/src/index.ts +553 -101
  67. package/pi-extension/src/runtime/runtime-context.ts +339 -281
  68. package/pi-extension/src/runtime/runtime-identity.ts +8 -0
  69. package/pi-extension/src/settings/settings-tui.ts +93 -0
  70. package/pi-extension/src/settings/settings-ui.ts +700 -613
  71. package/pi-extension/src/ui/text-component.ts +66 -0
  72. package/pi-extension/tests/cognitive-routing/commands.test.js +134 -0
  73. package/pi-extension/tests/cognitive-routing/controller.test.js +1099 -0
  74. package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +1071 -0
  75. package/pi-extension/tests/cognitive-routing/history.test.js +274 -0
  76. package/pi-extension/tests/cognitive-routing/host-fixture.js +4 -0
  77. package/pi-extension/tests/cognitive-routing/host-identity.test.js +63 -0
  78. package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +236 -0
  79. package/pi-extension/tests/cognitive-routing/tool.test.js +230 -0
  80. package/pi-extension/tests/context-virtualization/extension.test.js +749 -0
  81. package/pi-extension/tests/context-virtualization/projector.test.js +110 -0
  82. package/pi-extension/tests/context-virtualization/runtime.test.js +216 -0
  83. package/pi-extension/tests/conversation-history/runtime.test.js +98 -0
  84. package/pi-extension/tests/conversation-history/search.test.js +97 -0
  85. package/pi-extension/tests/integration/pi-extension.test.js +927 -2048
  86. package/pi-extension/tests/integration/prompt-architecture.test.js +305 -0
  87. package/runtime/prompts/cognitive-routing.md +9 -0
  88. package/runtime/prompts/context-virtualization.md +3 -0
  89. package/runtime/prompts/conversation-history.md +3 -0
  90. package/runtime/prompts/core.md +13 -0
  91. package/runtime/prompts/interaction-contract.md +7 -0
  92. package/runtime/prompts/skills.md +65 -0
  93. package/skills/action-selection/SKILL.md +91 -0
  94. package/skills/bypass/SKILL.md +3 -2
  95. package/skills/commit-work/SKILL.md +1 -1
  96. package/skills/commit-work/references/staging-decisions.md +1 -1
  97. package/skills/decision-gate/SKILL.md +1 -1
  98. package/skills/design-for-depth/SKILL.md +14 -33
  99. package/skills/design-for-depth/references/design-pressure-signals.md +1 -1
  100. package/skills/design-for-depth/references/interface-design-loop.md +1 -1
  101. package/skills/design-for-depth/references/software-design-philosophy.md +1 -1
  102. package/skills/diagnose-failure/SKILL.md +20 -14
  103. package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +1 -3
  104. package/skills/diagnose-failure/references/{flaky-and-performance.md → flaky-and-performance-diagnosis.md} +1 -1
  105. package/skills/discuss/SKILL.md +34 -22
  106. package/skills/discuss/references/discussion-continuity.md +71 -0
  107. package/skills/evaluate-skill/SKILL.md +5 -5
  108. package/skills/evaluate-skill/references/{definition-schema.md → evaluation-definition-schema.md} +42 -2
  109. package/skills/evaluate-skill/references/execution-and-evidence.md +8 -3
  110. package/skills/evaluate-skill/scripts/lib/definitions.mjs +114 -3
  111. package/skills/evaluate-skill/scripts/lib/grade-interaction.mjs +156 -1
  112. package/skills/evaluate-skill/scripts/lib/grade.mjs +9 -1
  113. package/skills/evaluate-skill/scripts/lib/pi.mjs +147 -32
  114. package/skills/evaluate-skill/scripts/lib/rpc.mjs +4 -4
  115. package/skills/evaluate-skill/scripts/lib/runner.mjs +36 -14
  116. package/skills/evaluate-skill/scripts/lib/sandbox.mjs +92 -0
  117. package/skills/evaluate-skill/scripts/pi-guard.mjs +1 -1
  118. package/skills/evaluate-skill/scripts/pi-observer.mjs +66 -0
  119. package/skills/evaluate-skill/scripts/skill-eval.mjs +6 -5
  120. package/skills/execute-work/SKILL.md +18 -15
  121. package/skills/execute-work/references/code-practices.md +1 -1
  122. package/skills/execute-work/references/execute-work-edges.md +42 -0
  123. package/skills/finish-branch/SKILL.md +2 -2
  124. package/skills/finish-branch/references/integration-options.md +1 -1
  125. package/skills/handoff/SKILL.md +3 -3
  126. package/skills/launch-work/SKILL.md +1 -1
  127. package/skills/launch-work/references/launch-readiness.md +2 -2
  128. package/skills/migration-work/SKILL.md +2 -2
  129. package/skills/migration-work/references/migration-lifecycle.md +1 -1
  130. package/skills/mode-contract/SKILL.md +4 -4
  131. package/skills/release-work/SKILL.md +1 -1
  132. package/skills/release-work/references/release-evidence.md +1 -1
  133. package/skills/review-artifact/SKILL.md +28 -26
  134. package/skills/review-work/SKILL.md +28 -26
  135. package/skills/review-work/references/{reviewer-prompt.md → independent-work-reviewer-contract.md} +1 -1
  136. package/skills/review-work/references/security-risk-lens.md +1 -1
  137. package/skills/setup-freeflow/SKILL.md +3 -1
  138. package/skills/setup-freeflow/references/activation-contract.md +2 -2
  139. package/skills/setup-freeflow/references/host-setup.md +2 -2
  140. package/skills/simplify-code/SKILL.md +1 -1
  141. package/skills/simplify-code/references/simplification-patterns.md +1 -1
  142. package/skills/tdd/SKILL.md +18 -38
  143. package/skills/tdd/references/test-design.md +2 -2
  144. package/skills/track-work/SKILL.md +362 -58
  145. package/skills/track-work/scripts/lib/codec.mjs +570 -0
  146. package/skills/track-work/scripts/lib/commands.mjs +568 -0
  147. package/skills/track-work/scripts/lib/contract.mjs +303 -0
  148. package/skills/track-work/scripts/lib/model.mjs +506 -0
  149. package/skills/track-work/scripts/lib/operations.mjs +965 -0
  150. package/skills/track-work/scripts/lib/record-store.mjs +264 -0
  151. package/skills/track-work/scripts/lib/result.mjs +37 -0
  152. package/skills/track-work/scripts/lib/rewrites.mjs +740 -0
  153. package/skills/track-work/scripts/lib/schema.mjs +277 -0
  154. package/skills/track-work/scripts/lib/source-inventory.mjs +162 -0
  155. package/skills/track-work/scripts/lib/views.mjs +443 -0
  156. package/skills/track-work/scripts/lib/workspace.mjs +134 -0
  157. package/skills/track-work/scripts/working-record.mjs +122 -0
  158. package/skills/verify-work/SKILL.md +14 -2
  159. package/skills/verify-work/references/browser-runtime-evidence.md +1 -1
  160. package/skills/verify-work/references/integration-evidence.md +1 -1
  161. package/skills/verify-work/references/performance-evidence.md +1 -1
  162. package/skills/workflow/SKILL.md +105 -53
  163. package/skills/workflow/references/domain-skill-composition.md +22 -42
  164. package/skills/write-plan/SKILL.md +1 -1
  165. package/skills/write-skill/SKILL.md +3 -2
  166. package/skills/write-skill/references/progressive-disclosure.md +17 -3
  167. package/capabilities/output-router/SKILL.md +0 -206
  168. package/capabilities/output-router/references/safety-policy.md +0 -40
  169. package/capabilities/output-router/references/setup.md +0 -110
  170. package/pi-extension/dist/output-router/host-producer-identification.js +0 -232
  171. package/pi-extension/dist/output-router/native-safety-net.js +0 -216
  172. package/pi-extension/dist/output-router/observed-tool-routing.js +0 -122
  173. package/pi-extension/dist/output-router/renderers.js +0 -1023
  174. package/pi-extension/dist/output-router/router-tools.js +0 -554
  175. package/pi-extension/dist/output-router/schemas.js +0 -383
  176. package/pi-extension/dist/output-router/status.js +0 -744
  177. package/pi-extension/dist/output-router/utils.js +0 -502
  178. package/pi-extension/src/output-router/host-producer-identification.ts +0 -256
  179. package/pi-extension/src/output-router/native-safety-net.ts +0 -248
  180. package/pi-extension/src/output-router/observed-tool-routing.ts +0 -134
  181. package/pi-extension/src/output-router/renderers.ts +0 -1108
  182. package/pi-extension/src/output-router/router-tools.ts +0 -579
  183. package/pi-extension/src/output-router/schemas.ts +0 -387
  184. package/pi-extension/src/output-router/status.ts +0 -791
  185. package/pi-extension/src/output-router/utils.ts +0 -554
  186. package/pi-extension/tests/output-router/observed-producers.test.js +0 -132
  187. package/pi-extension/tests/output-router/search.test.js +0 -722
  188. package/router/dist/benchmarks/benchmark-harness.d.ts +0 -35
  189. package/router/dist/benchmarks/benchmark-harness.js +0 -92
  190. package/router/dist/benchmarks/benchmarks.d.ts +0 -109
  191. package/router/dist/benchmarks/benchmarks.js +0 -979
  192. package/router/dist/benchmarks/codex-qa-benchmarks.d.ts +0 -95
  193. package/router/dist/benchmarks/codex-qa-benchmarks.js +0 -500
  194. package/router/dist/benchmarks/command-benchmarks.d.ts +0 -143
  195. package/router/dist/benchmarks/command-benchmarks.js +0 -698
  196. package/router/dist/benchmarks/context-mode-normalized-benchmarks.d.ts +0 -82
  197. package/router/dist/benchmarks/context-mode-normalized-benchmarks.js +0 -773
  198. package/router/dist/benchmarks/context-mode-real-deep-benchmark.d.ts +0 -132
  199. package/router/dist/benchmarks/context-mode-real-deep-benchmark.js +0 -1380
  200. package/router/dist/benchmarks/context-saving-baseline.d.ts +0 -60
  201. package/router/dist/benchmarks/context-saving-baseline.js +0 -470
  202. package/router/dist/benchmarks/index-benchmarks.d.ts +0 -103
  203. package/router/dist/benchmarks/index-benchmarks.js +0 -862
  204. package/router/dist/benchmarks/storage-policy-benchmarks.d.ts +0 -101
  205. package/router/dist/benchmarks/storage-policy-benchmarks.js +0 -618
  206. package/router/dist/benchmarks/vault-index-benchmarks.d.ts +0 -56
  207. package/router/dist/benchmarks/vault-index-benchmarks.js +0 -322
  208. package/router/dist/config/config.d.ts +0 -103
  209. package/router/dist/config/config.js +0 -632
  210. package/router/dist/config/router-contract.d.ts +0 -10
  211. package/router/dist/config/router-contract.js +0 -54
  212. package/router/dist/config/schema.d.ts +0 -27
  213. package/router/dist/config/schema.js +0 -648
  214. package/router/dist/config/types.d.ts +0 -573
  215. package/router/dist/config/types.js +0 -41
  216. package/router/dist/evidence/bounded-evidence.d.ts +0 -40
  217. package/router/dist/evidence/bounded-evidence.js +0 -323
  218. package/router/dist/evidence/evidence-range-selector.d.ts +0 -24
  219. package/router/dist/evidence/evidence-range-selector.js +0 -232
  220. package/router/dist/evidence/evidence-search.d.ts +0 -27
  221. package/router/dist/evidence/evidence-search.js +0 -490
  222. package/router/dist/evidence/evidence.d.ts +0 -38
  223. package/router/dist/evidence/evidence.js +0 -200
  224. package/router/dist/evidence/failure-contracts.d.ts +0 -37
  225. package/router/dist/evidence/failure-contracts.js +0 -166
  226. package/router/dist/evidence/line-ranges.d.ts +0 -24
  227. package/router/dist/evidence/line-ranges.js +0 -22
  228. package/router/dist/experiments/local-index.d.ts +0 -64
  229. package/router/dist/experiments/local-index.js +0 -581
  230. package/router/dist/index.d.ts +0 -30
  231. package/router/dist/index.js +0 -32
  232. package/router/dist/local/local-traversal.d.ts +0 -18
  233. package/router/dist/local/local-traversal.js +0 -334
  234. package/router/dist/processing/engine.d.ts +0 -132
  235. package/router/dist/processing/engine.js +0 -533
  236. package/router/dist/processing/reducers.d.ts +0 -280
  237. package/router/dist/processing/reducers.js +0 -1673
  238. package/router/dist/processing/renderers.d.ts +0 -31
  239. package/router/dist/processing/renderers.js +0 -195
  240. package/router/dist/processing/scripts.d.ts +0 -91
  241. package/router/dist/processing/scripts.js +0 -386
  242. package/router/dist/repo/repo-traversal.d.ts +0 -18
  243. package/router/dist/repo/repo-traversal.js +0 -245
  244. package/router/dist/routing/observed-reducers.d.ts +0 -41
  245. package/router/dist/routing/observed-reducers.js +0 -661
  246. package/router/dist/routing/observed-routing.d.ts +0 -26
  247. package/router/dist/routing/observed-routing.js +0 -378
  248. package/router/dist/routing/parsers.d.ts +0 -16
  249. package/router/dist/routing/parsers.js +0 -521
  250. package/router/dist/routing/run-filters.d.ts +0 -60
  251. package/router/dist/routing/run-filters.js +0 -238
  252. package/router/dist/routing/run-reducers.d.ts +0 -49
  253. package/router/dist/routing/run-reducers.js +0 -122
  254. package/router/dist/sandbox/adapter-roots.d.ts +0 -46
  255. package/router/dist/sandbox/adapter-roots.js +0 -66
  256. package/router/dist/sandbox/eryx-python-adapter.d.ts +0 -13
  257. package/router/dist/sandbox/eryx-python-adapter.js +0 -868
  258. package/router/dist/sandbox/jq-wasm-adapter.d.ts +0 -9
  259. package/router/dist/sandbox/jq-wasm-adapter.js +0 -429
  260. package/router/dist/sandbox/quickjs-wasi-adapter.d.ts +0 -13
  261. package/router/dist/sandbox/quickjs-wasi-adapter.js +0 -384
  262. package/router/dist/sandbox/script-sandbox.d.ts +0 -134
  263. package/router/dist/sandbox/script-sandbox.js +0 -337
  264. package/router/dist/setup/script-transform-adapters.d.ts +0 -32
  265. package/router/dist/setup/script-transform-adapters.js +0 -278
  266. package/router/dist/tools/batch.d.ts +0 -33
  267. package/router/dist/tools/batch.js +0 -586
  268. package/router/dist/tools/run.d.ts +0 -62
  269. package/router/dist/tools/run.js +0 -1304
  270. package/router/dist/tools/search.d.ts +0 -66
  271. package/router/dist/tools/search.js +0 -1364
  272. package/router/dist/transform/engine.d.ts +0 -168
  273. package/router/dist/transform/engine.js +0 -2072
  274. package/router/dist/vault/vault-index.d.ts +0 -125
  275. package/router/dist/vault/vault-index.js +0 -416
  276. package/router/dist/vault/vault.d.ts +0 -138
  277. package/router/dist/vault/vault.js +0 -630
  278. package/runtime/interaction-contract.md +0 -16
  279. package/skills/discuss/references/checkpoints.md +0 -66
  280. package/skills/execute-work/references/execution-loop.md +0 -77
  281. package/skills/track-work/references/working-record-schema.md +0 -378
  282. package/skills/workflow/references/workflow-loop.md +0 -92
  283. /package/skills/handoff/references/{templates.md → handoff-templates.md} +0 -0
  284. /package/skills/review-artifact/references/{reviewer-prompt.md → independent-artifact-reviewer-contract.md} +0 -0
@@ -0,0 +1,1118 @@
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 type {
9
+ CognitiveRoutingCapabilityState,
10
+ CognitiveRoutingProfileName,
11
+ CognitiveRoutingThinkingLevel,
12
+ } from "./types.js";
13
+
14
+ export const COGNITIVE_ROUTING_INTENT_ENTRY = "freeflow-cognitive-routing-intent";
15
+ export const COGNITIVE_ROUTING_CONTROL_ENTRY = "freeflow-cognitive-routing-control";
16
+
17
+ export type CognitiveRoutingMechanism =
18
+ | "agent-tool"
19
+ | "profile-command"
20
+ | "profile-shortcut"
21
+ | "profile-settings"
22
+ | "session-tree"
23
+ | "session-compact"
24
+ | "activation"
25
+ | "reload-restore"
26
+ | "recovery"
27
+ | "shutdown-restore";
28
+
29
+ type CognitiveRoutingPair = {
30
+ provider: string;
31
+ modelId: string;
32
+ thinkingLevel: CognitiveRoutingThinkingLevel;
33
+ };
34
+
35
+ type CognitiveRoutingIntent = {
36
+ version: 1 | 2;
37
+ kind: "activation" | "profile" | "closing";
38
+ phase: "prepared" | "abandoned";
39
+ control: "automatic" | "manual";
40
+ source: "system" | "user" | "agent";
41
+ reason?: string;
42
+ branchId?: string | null;
43
+ epoch: string;
44
+ correlationId: string;
45
+ mechanism?: CognitiveRoutingMechanism;
46
+ decisionCorrelationId?: string;
47
+ fromPair?: CognitiveRoutingPair;
48
+ fromProfile?: CognitiveRoutingProfileName;
49
+ profile?: CognitiveRoutingProfileName;
50
+ resumeProfile?: CognitiveRoutingProfileName;
51
+ resumeControl?: "automatic" | "manual";
52
+ resumeReason?: string;
53
+ target: CognitiveRoutingPair;
54
+ returnTarget: CognitiveRoutingPair;
55
+ };
56
+
57
+ type CognitiveRoutingControlEntry = {
58
+ version: 1 | 2;
59
+ control: "automatic";
60
+ source: "user";
61
+ mechanism?: CognitiveRoutingMechanism;
62
+ reason?: string;
63
+ branchId?: string | null;
64
+ epoch: string;
65
+ };
66
+
67
+ type CognitiveRoutingPersistedData = CognitiveRoutingIntent | CognitiveRoutingControlEntry;
68
+
69
+ type ModelStateLease = {
70
+ setState(request: CognitiveRoutingPair & { correlationId: string }): Promise<{ status: string }>;
71
+ release(): Promise<unknown>;
72
+ };
73
+
74
+ type ModelStateAcquisition =
75
+ { status: "acquired"; lease: ModelStateLease } | { status: "conflict"; owner: string } | { status: "busy" };
76
+
77
+ type ControllerPi = {
78
+ appendEntryDurable(customType: string, data: CognitiveRoutingPersistedData): void;
79
+ acquireModelStateControl(options: { label: string }): Promise<ModelStateAcquisition>;
80
+ };
81
+
82
+ type ControllerContext = {
83
+ model?: { provider?: string; id?: string };
84
+ thinkingLevel?: CognitiveRoutingThinkingLevel;
85
+ sessionManager?: {
86
+ getEntries?: () => readonly unknown[];
87
+ getBranch?: () => readonly unknown[];
88
+ getLeafId?: () => string | null;
89
+ };
90
+ };
91
+
92
+ type ControllerOptions = {
93
+ capabilityState: CognitiveRoutingCapabilityState;
94
+ pi: ControllerPi;
95
+ ctx: ControllerContext;
96
+ label?: string;
97
+ idFactory?: () => string;
98
+ };
99
+
100
+ export type CognitiveRoutingControlMode = "automatic" | "manual-standard" | "manual-reasoning";
101
+
102
+ export type CognitiveRoutingControllerState = {
103
+ effective: boolean;
104
+ controlMode: CognitiveRoutingControlMode;
105
+ activeProfile?: CognitiveRoutingProfileName;
106
+ epoch?: string;
107
+ returnTarget?: CognitiveRoutingPair;
108
+ };
109
+
110
+ export type CognitiveRoutingActivationResult =
111
+ { status: "active"; profile: CognitiveRoutingProfileName } | { status: "inactive"; reason: string };
112
+
113
+ export type CognitiveRoutingDeactivationResult = { status: "inactive"; reason: string };
114
+ export type CognitiveRoutingShutdownReason = "quit" | "reload" | "new" | "resume" | "fork" | undefined;
115
+
116
+ export type CognitiveRoutingManualResult =
117
+ { status: "active"; profile: CognitiveRoutingProfileName } | { status: "inactive"; reason: string };
118
+
119
+ export type CognitiveRoutingAutomaticResult = { status: "automatic" } | { status: "rejected"; reason: string };
120
+
121
+ export type CognitiveRoutingSwitchResult =
122
+ | {
123
+ status: "active";
124
+ changed: boolean;
125
+ from: CognitiveRoutingProfileName;
126
+ to: CognitiveRoutingProfileName;
127
+ profile: CognitiveRoutingProfileName;
128
+ }
129
+ | { status: "blocked"; reason: string }
130
+ | { status: "inactive"; reason: string };
131
+
132
+ type CognitiveRoutingProfileTransitionResult =
133
+ { status: "active"; profile: CognitiveRoutingProfileName } | { status: "inactive"; reason: string };
134
+
135
+ export type CognitiveRoutingRecoveryResult =
136
+ | { status: "active"; profile: CognitiveRoutingProfileName }
137
+ | { status: "pending"; reason: string }
138
+ | { status: "inactive"; reason: string };
139
+
140
+ export type CognitiveRoutingBranchResult =
141
+ | { status: "active"; profile: CognitiveRoutingProfileName }
142
+ | { status: "pending"; reason: string }
143
+ | { status: "inactive"; reason: string };
144
+
145
+ function isProfileName(value: unknown): value is CognitiveRoutingProfileName {
146
+ return value === "standard" || value === "reasoning";
147
+ }
148
+
149
+ function isMechanism(value: unknown): value is CognitiveRoutingMechanism {
150
+ return [
151
+ "agent-tool",
152
+ "profile-command",
153
+ "profile-shortcut",
154
+ "profile-settings",
155
+ "session-tree",
156
+ "session-compact",
157
+ "activation",
158
+ "reload-restore",
159
+ "recovery",
160
+ "shutdown-restore",
161
+ ].includes(value as CognitiveRoutingMechanism);
162
+ }
163
+
164
+ function asIntentSource(value: unknown): "system" | "user" | "agent" {
165
+ if (value === "user" || value === "agent") return value;
166
+ return "system";
167
+ }
168
+
169
+ function pairEquals(a: CognitiveRoutingPair | undefined, b: CognitiveRoutingPair | undefined): boolean {
170
+ return a?.provider === b?.provider && a?.modelId === b?.modelId && a?.thinkingLevel === b?.thinkingLevel;
171
+ }
172
+
173
+ function asPair(value: unknown): CognitiveRoutingPair | undefined {
174
+ if (!value || typeof value !== "object") return undefined;
175
+ const candidate = value as Record<string, unknown>;
176
+ if (
177
+ typeof candidate.provider !== "string" ||
178
+ typeof candidate.modelId !== "string" ||
179
+ typeof candidate.thinkingLevel !== "string"
180
+ ) {
181
+ return undefined;
182
+ }
183
+ return {
184
+ provider: candidate.provider,
185
+ modelId: candidate.modelId,
186
+ thinkingLevel: candidate.thinkingLevel as CognitiveRoutingThinkingLevel,
187
+ };
188
+ }
189
+
190
+ function latestHostPair(context: ControllerContext): CognitiveRoutingPair | undefined {
191
+ const entries = branchEntriesFrom(context);
192
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
193
+ const entry = entries[index];
194
+ if (!entry || typeof entry !== "object") continue;
195
+ const candidate = entry as Record<string, unknown>;
196
+ if (candidate.type !== "model_state_change") continue;
197
+ const pair = asPair({
198
+ provider: candidate.provider,
199
+ modelId: candidate.modelId,
200
+ thinkingLevel: candidate.thinkingLevel,
201
+ });
202
+ if (pair) return pair;
203
+ }
204
+ return undefined;
205
+ }
206
+
207
+ function profileNameForPair(
208
+ capabilityState: CognitiveRoutingCapabilityState,
209
+ pair: CognitiveRoutingPair | undefined,
210
+ ): CognitiveRoutingProfileName | undefined {
211
+ if (!pair) return undefined;
212
+ for (const [name, profile] of Object.entries(capabilityState.resolvedProfiles)) {
213
+ if (!profile) continue;
214
+ if (
215
+ pairEquals(pair, {
216
+ provider: profile.provider,
217
+ modelId: profile.model,
218
+ thinkingLevel: profile.effectiveThinkingLevel,
219
+ })
220
+ ) {
221
+ return isProfileName(name) ? name : undefined;
222
+ }
223
+ }
224
+ return undefined;
225
+ }
226
+
227
+ function asIntent(value: unknown): CognitiveRoutingIntent | undefined {
228
+ if (!value || typeof value !== "object") return undefined;
229
+ const candidate = value as Record<string, unknown>;
230
+ if (
231
+ (candidate.version !== 1 && candidate.version !== 2) ||
232
+ (candidate.kind !== "activation" && candidate.kind !== "profile" && candidate.kind !== "closing") ||
233
+ (candidate.phase !== "prepared" && candidate.phase !== "abandoned") ||
234
+ typeof candidate.epoch !== "string" ||
235
+ typeof candidate.correlationId !== "string"
236
+ ) {
237
+ return undefined;
238
+ }
239
+ const target = asPair(candidate.target);
240
+ const returnTarget = asPair(candidate.returnTarget);
241
+ const fromPair = asPair(candidate.fromPair);
242
+ if (!target || !returnTarget) return undefined;
243
+ return {
244
+ version: candidate.version,
245
+ kind: candidate.kind,
246
+ phase: candidate.phase,
247
+ control: candidate.control === "manual" ? "manual" : "automatic",
248
+ source: asIntentSource(candidate.source),
249
+ ...(isMechanism(candidate.mechanism) ? { mechanism: candidate.mechanism } : {}),
250
+ ...(typeof candidate.decisionCorrelationId === "string"
251
+ ? { decisionCorrelationId: candidate.decisionCorrelationId }
252
+ : {}),
253
+ ...(fromPair ? { fromPair } : {}),
254
+ ...(isProfileName(candidate.fromProfile) ? { fromProfile: candidate.fromProfile } : {}),
255
+ ...(typeof candidate.reason === "string" ? { reason: candidate.reason } : {}),
256
+ ...(typeof candidate.branchId === "string" || candidate.branchId === null
257
+ ? { branchId: candidate.branchId as string | null }
258
+ : {}),
259
+ epoch: candidate.epoch,
260
+ correlationId: candidate.correlationId,
261
+ ...(isProfileName(candidate.profile) ? { profile: candidate.profile } : {}),
262
+ ...(isProfileName(candidate.resumeProfile) ? { resumeProfile: candidate.resumeProfile } : {}),
263
+ ...(candidate.resumeControl === "automatic" || candidate.resumeControl === "manual"
264
+ ? { resumeControl: candidate.resumeControl }
265
+ : {}),
266
+ ...(typeof candidate.resumeReason === "string" ? { resumeReason: candidate.resumeReason } : {}),
267
+ target,
268
+ returnTarget,
269
+ };
270
+ }
271
+
272
+ function entriesFrom(context: ControllerContext): readonly unknown[] {
273
+ try {
274
+ const entries = context.sessionManager?.getEntries?.();
275
+ return Array.isArray(entries) ? entries : [];
276
+ } catch {
277
+ return [];
278
+ }
279
+ }
280
+
281
+ function branchEntriesFrom(context: ControllerContext): readonly unknown[] {
282
+ try {
283
+ const entries = context.sessionManager?.getBranch?.();
284
+ return Array.isArray(entries) ? entries : entriesFrom(context);
285
+ } catch {
286
+ return entriesFrom(context);
287
+ }
288
+ }
289
+
290
+ function latestIntent(
291
+ entries: readonly unknown[],
292
+ predicate: (intent: CognitiveRoutingIntent) => boolean = () => true,
293
+ ): CognitiveRoutingIntent | undefined {
294
+ const abandonedCorrelations = new Set<string>();
295
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
296
+ const entry = entries[index];
297
+ if (!entry || typeof entry !== "object") continue;
298
+ const candidate = entry as Record<string, unknown>;
299
+ if (candidate.type !== "custom" || candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
300
+ const intent = asIntent(candidate.data);
301
+ if (!intent) continue;
302
+ if (intent.phase === "abandoned") {
303
+ abandonedCorrelations.add(intent.correlationId);
304
+ continue;
305
+ }
306
+ if (!abandonedCorrelations.has(intent.correlationId) && predicate(intent)) return intent;
307
+ }
308
+ return undefined;
309
+ }
310
+
311
+ function controlModeForIntent(intent: CognitiveRoutingIntent): CognitiveRoutingControlMode {
312
+ if (intent.control === "manual" && intent.profile) return `manual-${intent.profile}` as CognitiveRoutingControlMode;
313
+ return "automatic";
314
+ }
315
+
316
+ function decisionCorrelationForIntent(intent: CognitiveRoutingIntent): string | undefined {
317
+ if (intent.decisionCorrelationId) return intent.decisionCorrelationId;
318
+ return intent.source === "user" || intent.source === "agent" ? intent.correlationId : undefined;
319
+ }
320
+
321
+ function latestControlMode(entries: readonly unknown[], intent: CognitiveRoutingIntent): CognitiveRoutingControlMode {
322
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
323
+ const entry = entries[index];
324
+ if (!entry || typeof entry !== "object") continue;
325
+ const candidate = entry as Record<string, unknown>;
326
+ if (candidate.type !== "custom") continue;
327
+ if (candidate.customType === COGNITIVE_ROUTING_CONTROL_ENTRY) {
328
+ const data = candidate.data;
329
+ if (
330
+ data &&
331
+ typeof data === "object" &&
332
+ ((data as Record<string, unknown>).version === 1 || (data as Record<string, unknown>).version === 2) &&
333
+ (data as Record<string, unknown>).epoch === intent.epoch &&
334
+ (data as Record<string, unknown>).control === "automatic"
335
+ ) {
336
+ return "automatic";
337
+ }
338
+ }
339
+ if (candidate.customType !== COGNITIVE_ROUTING_INTENT_ENTRY) continue;
340
+ const candidateIntent = asIntent(candidate.data);
341
+ if (!candidateIntent || candidateIntent.phase !== "prepared" || candidateIntent.epoch !== intent.epoch) continue;
342
+ if (candidateIntent.kind === "profile" || candidateIntent.kind === "activation") {
343
+ return controlModeForIntent(candidateIntent);
344
+ }
345
+ }
346
+ return "automatic";
347
+ }
348
+
349
+ function hasMatchingHostEntry(entries: readonly unknown[], intent: CognitiveRoutingIntent): boolean {
350
+ return entries.some((entry) => {
351
+ if (!entry || typeof entry !== "object") return false;
352
+ const candidate = entry as Record<string, unknown>;
353
+ return (
354
+ candidate.type === "model_state_change" &&
355
+ candidate.correlationId === intent.correlationId &&
356
+ pairEquals(asPair(candidate), intent.target)
357
+ );
358
+ });
359
+ }
360
+
361
+ export class CognitiveRoutingController {
362
+ private readonly capabilityState: CognitiveRoutingCapabilityState;
363
+ private readonly pi: ControllerPi;
364
+ private readonly ctx: ControllerContext;
365
+ private readonly label: string;
366
+ private readonly idFactory: () => string;
367
+ private lease: ModelStateLease | undefined;
368
+ private activeProfile: CognitiveRoutingProfileName | undefined;
369
+ private epoch: string | undefined;
370
+ private returnTarget: CognitiveRoutingPair | undefined;
371
+ private controlMode: CognitiveRoutingControlMode = "automatic";
372
+ private branchPending = false;
373
+ private operation: Promise<unknown> = Promise.resolve();
374
+
375
+ constructor(options: ControllerOptions) {
376
+ this.capabilityState = options.capabilityState;
377
+ this.pi = options.pi;
378
+ this.ctx = options.ctx;
379
+ this.label = options.label ?? "Cognitive Routing";
380
+ this.idFactory = options.idFactory ?? randomUUID;
381
+ }
382
+
383
+ state(): CognitiveRoutingControllerState {
384
+ const hostPair = latestHostPair(this.ctx);
385
+ const observedPair = hostPair ?? this.currentPair();
386
+ const observedProfile = this.activeProfile ? profileNameForPair(this.capabilityState, observedPair) : undefined;
387
+ const activeProfile = hostPair ? observedProfile : (observedProfile ?? this.activeProfile);
388
+ return {
389
+ effective: this.lease !== undefined && activeProfile !== undefined && !this.branchPending,
390
+ controlMode: this.controlMode,
391
+ ...(activeProfile ? { activeProfile } : {}),
392
+ ...(this.epoch ? { epoch: this.epoch } : {}),
393
+ ...(this.returnTarget ? { returnTarget: { ...this.returnTarget } } : {}),
394
+ };
395
+ }
396
+
397
+ history(options: CognitiveRoutingHistoryOptions = {}): CognitiveRoutingHistoryResult {
398
+ const state = this.state();
399
+ const current: CognitiveRoutingHistoryCurrent = {
400
+ control: state.effective
401
+ ? state.controlMode === "automatic"
402
+ ? "automatic"
403
+ : "manual"
404
+ : ("unavailable" as const),
405
+ profile: state.effective && state.activeProfile ? state.activeProfile : ("unavailable" as const),
406
+ };
407
+ const profilePairs = {
408
+ ...(this.capabilityState.resolvedProfiles.standard
409
+ ? {
410
+ standard: {
411
+ provider: this.capabilityState.resolvedProfiles.standard.provider,
412
+ modelId: this.capabilityState.resolvedProfiles.standard.model,
413
+ thinkingLevel: this.capabilityState.resolvedProfiles.standard.effectiveThinkingLevel,
414
+ },
415
+ }
416
+ : {}),
417
+ ...(this.capabilityState.resolvedProfiles.reasoning
418
+ ? {
419
+ reasoning: {
420
+ provider: this.capabilityState.resolvedProfiles.reasoning.provider,
421
+ modelId: this.capabilityState.resolvedProfiles.reasoning.model,
422
+ thinkingLevel: this.capabilityState.resolvedProfiles.reasoning.effectiveThinkingLevel,
423
+ },
424
+ }
425
+ : {}),
426
+ };
427
+ return readCognitiveRoutingHistory(this.ctx, { ...options, current, profilePairs });
428
+ }
429
+
430
+ async activate(): Promise<CognitiveRoutingActivationResult> {
431
+ return this.enqueue(() => this._activate());
432
+ }
433
+
434
+ async deactivate(): Promise<CognitiveRoutingDeactivationResult> {
435
+ return this.enqueue(() => this._deactivate());
436
+ }
437
+
438
+ async shutdown(reason: CognitiveRoutingShutdownReason): Promise<CognitiveRoutingDeactivationResult> {
439
+ return this.enqueue(() =>
440
+ reason === "quit" ? this._releaseWithoutRestore() : this._deactivate(reason === "reload"),
441
+ );
442
+ }
443
+
444
+ async recover(): Promise<CognitiveRoutingRecoveryResult> {
445
+ return this.enqueue(() => this._recover());
446
+ }
447
+
448
+ async reconcileBranch(mechanism: CognitiveRoutingMechanism = "session-tree"): Promise<CognitiveRoutingBranchResult> {
449
+ return this.enqueue(() => this._reconcileBranch(mechanism));
450
+ }
451
+
452
+ private async _activate(): Promise<CognitiveRoutingActivationResult> {
453
+ if (this.state().effective && this.activeProfile) {
454
+ return { status: "active", profile: this.activeProfile };
455
+ }
456
+ if (!this.capabilityState.effective) {
457
+ return { status: "inactive", reason: "not_effective" };
458
+ }
459
+
460
+ const sessionEntries = entriesFrom(this.ctx);
461
+ const lifecycleIntent = latestIntent(
462
+ sessionEntries,
463
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
464
+ );
465
+ if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
466
+ return { status: "inactive", reason: "pending_intent" };
467
+ }
468
+ if (lifecycleIntent?.kind === "activation") {
469
+ return { status: "inactive", reason: "recover_required" };
470
+ }
471
+ const preservedReload = lifecycleIntent?.kind === "closing" && lifecycleIntent.resumeProfile !== undefined;
472
+ if (preservedReload && !lifecycleIntent.resumeControl) {
473
+ return { status: "inactive", reason: "resume_state_invalid" };
474
+ }
475
+ const returnTarget = this.currentPair();
476
+ if (!returnTarget) {
477
+ return { status: "inactive", reason: "current_state_unavailable" };
478
+ }
479
+ const epoch = this.epoch ?? this.idFactory();
480
+ const branchId = this.currentBranchId();
481
+ const sessionStart = this.capabilityState.sessionStart ?? {
482
+ control: "automatic" as const,
483
+ profile: "standard" as const,
484
+ };
485
+ const profileName: CognitiveRoutingProfileName = preservedReload
486
+ ? lifecycleIntent.resumeProfile
487
+ : sessionStart.profile;
488
+ const profile = this.capabilityState.resolvedProfiles[profileName];
489
+ if (!profile) {
490
+ return { status: "inactive", reason: preservedReload ? "resume_profile_unavailable" : "profile_unavailable" };
491
+ }
492
+ let controlMode: CognitiveRoutingControlMode;
493
+ if (preservedReload) {
494
+ controlMode = lifecycleIntent.resumeControl === "manual" ? `manual-${profileName}` : "automatic";
495
+ } else {
496
+ controlMode = sessionStart.control === "manual" ? `manual-${profileName}` : "automatic";
497
+ }
498
+ const target = {
499
+ provider: profile.provider,
500
+ modelId: profile.model,
501
+ thinkingLevel: profile.effectiveThinkingLevel,
502
+ };
503
+ return this.activatePrepared({
504
+ kind: "activation",
505
+ controlMode,
506
+ source: "system",
507
+ mechanism: preservedReload ? "reload-restore" : "activation",
508
+ ...(preservedReload && lifecycleIntent.resumeReason ? { reason: lifecycleIntent.resumeReason } : {}),
509
+ epoch,
510
+ branchId,
511
+ returnTarget,
512
+ target,
513
+ profile: profileName,
514
+ });
515
+ }
516
+
517
+ private async _releaseWithoutRestore(): Promise<CognitiveRoutingDeactivationResult> {
518
+ const lease = this.lease;
519
+ if (!lease) {
520
+ this.clearActiveState();
521
+ return { status: "inactive", reason: "not_active" };
522
+ }
523
+ await this.releaseLease(lease);
524
+ this.clearActiveState();
525
+ return { status: "inactive", reason: "released_on_quit" };
526
+ }
527
+
528
+ private async _deactivate(preserveSemanticState = false): Promise<CognitiveRoutingDeactivationResult> {
529
+ const lease = this.lease;
530
+ const returnTarget = this.returnTarget;
531
+ if (!lease || !returnTarget || !this.epoch) {
532
+ this.clearActiveState();
533
+ return { status: "inactive", reason: "not_active" };
534
+ }
535
+
536
+ const currentState = preserveSemanticState ? this.state() : undefined;
537
+ const resumeProfile = currentState?.effective ? currentState.activeProfile : undefined;
538
+ let resumeControl: "automatic" | "manual" | undefined;
539
+ if (resumeProfile && currentState?.controlMode === "automatic") {
540
+ resumeControl = "automatic";
541
+ } else if (resumeProfile && currentState?.controlMode === `manual-${resumeProfile}`) {
542
+ resumeControl = "manual";
543
+ }
544
+ const resumeIntent = resumeProfile
545
+ ? latestIntent(
546
+ branchEntriesFrom(this.ctx),
547
+ (candidate) => candidate.kind === "profile" && candidate.epoch === this.epoch,
548
+ )
549
+ : undefined;
550
+ const fromPair = latestHostPair(this.ctx) ?? this.currentPair();
551
+ const fromProfile = this.activeProfile ?? profileNameForPair(this.capabilityState, fromPair);
552
+ const intent = this.prepareIntent({
553
+ kind: "closing",
554
+ control: "automatic",
555
+ source: "system",
556
+ mechanism: "shutdown-restore",
557
+ ...(fromPair ? { fromPair } : {}),
558
+ ...(fromProfile ? { fromProfile } : {}),
559
+ ...(resumeProfile ? { resumeProfile } : {}),
560
+ ...(resumeControl ? { resumeControl } : {}),
561
+ ...(resumeIntent?.reason ? { resumeReason: resumeIntent.reason } : {}),
562
+ epoch: this.epoch,
563
+ correlationId: this.idFactory(),
564
+ branchId: this.currentBranchId(),
565
+ target: returnTarget,
566
+ returnTarget,
567
+ });
568
+ try {
569
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
570
+ } catch {
571
+ await this.releaseLease(lease);
572
+ this.clearActiveState();
573
+ return { status: "inactive", reason: "prepare_failed" };
574
+ }
575
+
576
+ this.clearActiveState(false);
577
+ try {
578
+ const result = await lease.setState({ ...returnTarget, correlationId: intent.correlationId });
579
+ if (result.status !== "applied" && result.status !== "unchanged") {
580
+ return { status: "inactive", reason: "restore_rejected" };
581
+ }
582
+ return { status: "inactive", reason: "restored" };
583
+ } catch {
584
+ return { status: "inactive", reason: "restore_failed" };
585
+ } finally {
586
+ await this.releaseLease(lease);
587
+ }
588
+ }
589
+
590
+ private async _recover(): Promise<CognitiveRoutingRecoveryResult> {
591
+ const sessionEntries = entriesFrom(this.ctx);
592
+ const branchEntries = branchEntriesFrom(this.ctx);
593
+ const lifecycleIntent = latestIntent(
594
+ sessionEntries,
595
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
596
+ );
597
+ if (!lifecycleIntent) {
598
+ return { status: "inactive", reason: "no_pending_intent" };
599
+ }
600
+ if (lifecycleIntent.kind === "closing") {
601
+ return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
602
+ ? { status: "inactive", reason: "closed" }
603
+ : this.recoverClosingIntent(lifecycleIntent);
604
+ }
605
+
606
+ const currentActivationProfile = this.capabilityState.resolvedProfiles[lifecycleIntent.profile ?? "standard"];
607
+ if (!this.capabilityState.effective) {
608
+ return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
609
+ ? { status: "inactive", reason: "not_effective" }
610
+ : this.abandonIntent(lifecycleIntent, "Cognitive Routing is not effective.");
611
+ }
612
+ if (!currentActivationProfile) {
613
+ return this.abandonIntent(lifecycleIntent, "Prepared profile is unavailable.");
614
+ }
615
+ const activationTarget = {
616
+ provider: currentActivationProfile.provider,
617
+ modelId: currentActivationProfile.model,
618
+ thinkingLevel: currentActivationProfile.effectiveThinkingLevel,
619
+ };
620
+ const activationMatched = hasMatchingHostEntry(sessionEntries, lifecycleIntent);
621
+ if (activationMatched && !pairEquals(activationTarget, lifecycleIntent.target)) {
622
+ return { status: "pending", reason: "applied_target_changed" };
623
+ }
624
+ if (!activationMatched && !pairEquals(activationTarget, lifecycleIntent.target)) {
625
+ return this.abandonIntent(lifecycleIntent, "Prepared profile target changed.");
626
+ }
627
+ if (!activationMatched) {
628
+ const retried = await this.activatePrepared({
629
+ kind: "activation",
630
+ controlMode: "automatic",
631
+ source: "system",
632
+ mechanism: "recovery",
633
+ branchId: this.currentBranchId(),
634
+ epoch: lifecycleIntent.epoch,
635
+ returnTarget: lifecycleIntent.returnTarget,
636
+ target: lifecycleIntent.target,
637
+ profile: lifecycleIntent.profile ?? "standard",
638
+ });
639
+ return retried.status === "active" ? retried : { status: "pending", reason: "activation_recovery_failed" };
640
+ }
641
+
642
+ const profileIntent = latestIntent(
643
+ branchEntries,
644
+ (intent) => intent.kind === "profile" && intent.epoch === lifecycleIntent.epoch,
645
+ );
646
+ if (profileIntent) {
647
+ const currentProfile = this.capabilityState.resolvedProfiles[profileIntent.profile ?? "standard"];
648
+ if (!currentProfile) {
649
+ return this.abandonIntent(profileIntent, "Prepared profile is unavailable.");
650
+ }
651
+ const profileTarget = {
652
+ provider: currentProfile.provider,
653
+ modelId: currentProfile.model,
654
+ thinkingLevel: currentProfile.effectiveThinkingLevel,
655
+ };
656
+ if (!pairEquals(profileTarget, profileIntent.target)) {
657
+ return hasMatchingHostEntry(branchEntries, profileIntent)
658
+ ? { status: "pending", reason: "applied_target_changed" }
659
+ : this.abandonIntent(profileIntent, "Prepared profile target changed.");
660
+ }
661
+ const profileMatched = hasMatchingHostEntry(branchEntries, profileIntent);
662
+ const retried = await this.activatePrepared({
663
+ kind: "profile",
664
+ controlMode: latestControlMode(branchEntries, profileIntent),
665
+ source: "system",
666
+ mechanism: "recovery",
667
+ ...(decisionCorrelationForIntent(profileIntent)
668
+ ? { decisionCorrelationId: decisionCorrelationForIntent(profileIntent) }
669
+ : {}),
670
+ branchId: this.currentBranchId(),
671
+ epoch: lifecycleIntent.epoch,
672
+ returnTarget: lifecycleIntent.returnTarget,
673
+ target: profileMatched ? profileTarget : profileIntent.target,
674
+ profile: profileIntent.profile ?? "standard",
675
+ });
676
+ return retried.status === "active" ? retried : { status: "pending", reason: "profile_recovery_failed" };
677
+ }
678
+
679
+ return this.activatePrepared({
680
+ kind: "activation",
681
+ controlMode: "automatic",
682
+ source: "system",
683
+ mechanism: "recovery",
684
+ branchId: this.currentBranchId(),
685
+ epoch: lifecycleIntent.epoch,
686
+ returnTarget: lifecycleIntent.returnTarget,
687
+ target: activationTarget,
688
+ profile: lifecycleIntent.profile ?? "standard",
689
+ });
690
+ }
691
+
692
+ private async recoverClosingIntent(intent: CognitiveRoutingIntent): Promise<CognitiveRoutingRecoveryResult> {
693
+ const fromPair = latestHostPair(this.ctx) ?? this.currentPair();
694
+ const fromProfile = intent.fromProfile ?? profileNameForPair(this.capabilityState, fromPair);
695
+ const retryIntent = this.prepareIntent({
696
+ kind: "closing",
697
+ control: "automatic",
698
+ source: "system",
699
+ mechanism: "shutdown-restore",
700
+ ...(fromPair ? { fromPair } : {}),
701
+ ...(fromProfile ? { fromProfile } : {}),
702
+ reason: "Closing recovery",
703
+ ...(intent.resumeProfile ? { resumeProfile: intent.resumeProfile } : {}),
704
+ ...(intent.resumeControl ? { resumeControl: intent.resumeControl } : {}),
705
+ ...(intent.resumeReason ? { resumeReason: intent.resumeReason } : {}),
706
+ branchId: this.currentBranchId(),
707
+ epoch: intent.epoch,
708
+ correlationId: this.idFactory(),
709
+ target: intent.target,
710
+ returnTarget: intent.returnTarget,
711
+ });
712
+ try {
713
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, retryIntent);
714
+ } catch {
715
+ return { status: "pending", reason: "closing_recovery_prepare_failed" };
716
+ }
717
+
718
+ let acquisition: ModelStateAcquisition;
719
+ try {
720
+ acquisition = await this.pi.acquireModelStateControl({ label: this.label });
721
+ } catch {
722
+ return { status: "pending", reason: "closing_recovery_acquire_failed" };
723
+ }
724
+ if (acquisition.status !== "acquired") {
725
+ return { status: "pending", reason: `closing_recovery_acquire_${acquisition.status}` };
726
+ }
727
+
728
+ try {
729
+ const result = await acquisition.lease.setState({ ...intent.target, correlationId: retryIntent.correlationId });
730
+ return result.status === "applied" || result.status === "unchanged"
731
+ ? { status: "inactive", reason: "restored" }
732
+ : { status: "pending", reason: "closing_recovery_rejected" };
733
+ } catch {
734
+ return { status: "pending", reason: "closing_recovery_failed" };
735
+ } finally {
736
+ await this.releaseLease(acquisition.lease);
737
+ }
738
+ }
739
+
740
+ private async abandonIntent(intent: CognitiveRoutingIntent, reason: string): Promise<CognitiveRoutingRecoveryResult> {
741
+ try {
742
+ const fromPair = intent.fromPair ?? latestHostPair(this.ctx) ?? this.currentPair();
743
+ const fromProfile = intent.fromProfile ?? profileNameForPair(this.capabilityState, fromPair);
744
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, {
745
+ ...intent,
746
+ version: 2,
747
+ phase: "abandoned",
748
+ source: "system",
749
+ mechanism: intent.mechanism ?? "recovery",
750
+ ...(fromPair ? { fromPair } : {}),
751
+ ...(fromProfile ? { fromProfile } : {}),
752
+ reason,
753
+ });
754
+ const recovered = await this._recover();
755
+ return recovered.status === "inactive" && recovered.reason === "no_pending_intent"
756
+ ? { status: "inactive", reason: "intent_abandoned" }
757
+ : recovered;
758
+ } catch {
759
+ return { status: "pending", reason: "intent_abandon_failed" };
760
+ }
761
+ }
762
+
763
+ private async _reconcileBranch(mechanism: CognitiveRoutingMechanism): Promise<CognitiveRoutingBranchResult> {
764
+ if (!this.capabilityState.effective) return { status: "inactive", reason: "not_effective" };
765
+ if (!this.activeProfile || !this.lease) {
766
+ return { status: "inactive", reason: "not_active" };
767
+ }
768
+
769
+ const currentProfile = this.activeProfile;
770
+ const sessionEntries = entriesFrom(this.ctx);
771
+ const lifecycleIntent = latestIntent(
772
+ sessionEntries,
773
+ (intent) => intent.kind === "activation" || intent.kind === "closing",
774
+ );
775
+ if (lifecycleIntent?.kind === "closing") {
776
+ this.branchPending = true;
777
+ return hasMatchingHostEntry(sessionEntries, lifecycleIntent)
778
+ ? { status: "inactive", reason: "closed" }
779
+ : { status: "pending", reason: "closing_intent_unmatched" };
780
+ }
781
+ if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
782
+ this.branchPending = true;
783
+ return { status: "pending", reason: "activation_intent_unmatched" };
784
+ }
785
+
786
+ const entries = branchEntriesFrom(this.ctx);
787
+ const intent = latestIntent(
788
+ entries,
789
+ (candidate) => candidate.kind === "profile" && candidate.epoch === lifecycleIntent?.epoch,
790
+ );
791
+ if (!intent) {
792
+ this.branchPending = false;
793
+ return { status: "active", profile: currentProfile };
794
+ }
795
+ if (!hasMatchingHostEntry(entries, intent)) {
796
+ this.branchPending = true;
797
+ return { status: "pending", reason: "branch_intent_unmatched" };
798
+ }
799
+
800
+ const decisionCorrelationId = decisionCorrelationForIntent(intent);
801
+ if (intent.source === "system" && !decisionCorrelationId) {
802
+ this.branchPending = false;
803
+ return { status: "active", profile: currentProfile };
804
+ }
805
+ if (!intent.profile) {
806
+ this.branchPending = false;
807
+ return { status: "active", profile: currentProfile };
808
+ }
809
+
810
+ const controlMode = latestControlMode(entries, intent);
811
+ if (this.activeProfile === intent.profile && this.controlMode === controlMode) {
812
+ this.branchPending = false;
813
+ return { status: "active", profile: intent.profile };
814
+ }
815
+ const result = await this._setProfile(intent.profile, {
816
+ controlMode,
817
+ source: "system",
818
+ mechanism,
819
+ ...(decisionCorrelationId ? { decisionCorrelationId } : {}),
820
+ reason: "Branch reconciliation",
821
+ });
822
+ this.branchPending = result.status !== "active";
823
+ return result;
824
+ }
825
+
826
+ async setManualProfile(
827
+ profile: CognitiveRoutingProfileName,
828
+ mechanism: CognitiveRoutingMechanism = "profile-command",
829
+ ): Promise<CognitiveRoutingManualResult> {
830
+ return this.enqueue(() => this._setManualProfile(profile, mechanism));
831
+ }
832
+
833
+ async setAutomaticControl(
834
+ mechanism: CognitiveRoutingMechanism = "profile-command",
835
+ ): Promise<CognitiveRoutingAutomaticResult> {
836
+ return this.enqueue(() => this._setAutomaticControl(mechanism));
837
+ }
838
+
839
+ async switchAutomaticProfile(
840
+ profile: CognitiveRoutingProfileName,
841
+ reason: string,
842
+ source: "agent" | "system" | "user" = "agent",
843
+ mechanism: CognitiveRoutingMechanism = "agent-tool",
844
+ ): Promise<CognitiveRoutingSwitchResult> {
845
+ return this.enqueue(() => this._switchAutomaticProfile(profile, reason, source, mechanism));
846
+ }
847
+
848
+ private async _setManualProfile(
849
+ profile: CognitiveRoutingProfileName,
850
+ mechanism: CognitiveRoutingMechanism,
851
+ ): Promise<CognitiveRoutingManualResult> {
852
+ if (!this.capabilityState.effective) {
853
+ return { status: "inactive", reason: "not_effective" };
854
+ }
855
+
856
+ const activation = this.state().effective ? { status: "active" as const } : await this._activate();
857
+ if (activation.status !== "active") return activation;
858
+ return this._setProfile(profile, {
859
+ controlMode: `manual-${profile}`,
860
+ source: "user",
861
+ mechanism,
862
+ reason: "manual profile command",
863
+ });
864
+ }
865
+
866
+ private async _switchAutomaticProfile(
867
+ profile: CognitiveRoutingProfileName,
868
+ reason: string,
869
+ source: "agent" | "system" | "user",
870
+ mechanism: CognitiveRoutingMechanism,
871
+ ): Promise<CognitiveRoutingSwitchResult> {
872
+ if (!this.capabilityState.effective) return { status: "blocked", reason: "not_effective" };
873
+ const current = this.state();
874
+ if (!current.effective) return { status: "blocked", reason: "not_active" };
875
+ if (this.controlMode !== "automatic") return { status: "blocked", reason: "manual_hold" };
876
+ const from = current.activeProfile;
877
+ if (!from) return { status: "blocked", reason: "profile_unknown" };
878
+ if (from === profile) return { status: "active", changed: false, from, to: profile, profile };
879
+
880
+ const transition = await this._setProfile(profile, { controlMode: "automatic", source, reason, mechanism });
881
+ if (transition.status !== "active") return transition;
882
+ return { status: "active", changed: true, from, to: transition.profile, profile: transition.profile };
883
+ }
884
+
885
+ private async _setProfile(
886
+ profile: CognitiveRoutingProfileName,
887
+ options: {
888
+ controlMode: CognitiveRoutingControlMode;
889
+ source: "system" | "user" | "agent";
890
+ mechanism: CognitiveRoutingMechanism;
891
+ decisionCorrelationId?: string;
892
+ reason: string;
893
+ },
894
+ ): Promise<CognitiveRoutingProfileTransitionResult> {
895
+ const resolvedProfile = this.capabilityState.resolvedProfiles[profile];
896
+ const lease = this.lease;
897
+ if (!resolvedProfile || !lease || !this.epoch || !this.returnTarget) {
898
+ return { status: "inactive", reason: "profile_unavailable" };
899
+ }
900
+ const target = {
901
+ provider: resolvedProfile.provider,
902
+ modelId: resolvedProfile.model,
903
+ thinkingLevel: resolvedProfile.effectiveThinkingLevel,
904
+ };
905
+ const fromPair = latestHostPair(this.ctx) ?? this.currentPair();
906
+ if (!fromPair) return { status: "inactive", reason: "current_state_unavailable" };
907
+ const fromProfile = this.activeProfile ?? profileNameForPair(this.capabilityState, fromPair);
908
+ const correlationId = this.idFactory();
909
+ const decisionCorrelationId =
910
+ options.decisionCorrelationId ??
911
+ (options.source === "user" || options.source === "agent" ? correlationId : undefined);
912
+ const intent = this.prepareIntent({
913
+ kind: "profile",
914
+ control: options.controlMode === "automatic" ? "automatic" : "manual",
915
+ source: options.source,
916
+ mechanism: options.mechanism,
917
+ ...(decisionCorrelationId ? { decisionCorrelationId } : {}),
918
+ ...(fromPair ? { fromPair } : {}),
919
+ ...(fromProfile ? { fromProfile } : {}),
920
+ reason: options.reason,
921
+ branchId: this.currentBranchId(),
922
+ epoch: this.epoch,
923
+ correlationId,
924
+ profile,
925
+ target,
926
+ returnTarget: this.returnTarget,
927
+ });
928
+ const sessionEntries = entriesFrom(this.ctx);
929
+ const lifecycleIntent = latestIntent(
930
+ sessionEntries,
931
+ (candidate) => candidate.kind === "activation" || candidate.kind === "closing",
932
+ );
933
+ if (lifecycleIntent && !hasMatchingHostEntry(sessionEntries, lifecycleIntent)) {
934
+ return { status: "inactive", reason: "pending_intent" };
935
+ }
936
+ const entries = branchEntriesFrom(this.ctx);
937
+ const latest = latestIntent(entries, (candidate) => candidate.kind === "profile" && candidate.epoch === this.epoch);
938
+ if (latest && !hasMatchingHostEntry(entries, latest)) {
939
+ return { status: "inactive", reason: "pending_intent" };
940
+ }
941
+ try {
942
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
943
+ this.branchPending = true;
944
+ } catch {
945
+ return { status: "inactive", reason: "prepare_failed" };
946
+ }
947
+
948
+ try {
949
+ const result = await lease.setState({ ...target, correlationId: intent.correlationId });
950
+ if (result.status !== "applied" && result.status !== "unchanged") {
951
+ return { status: "inactive", reason: "transition_rejected" };
952
+ }
953
+ this.activeProfile = profile;
954
+ this.controlMode = options.controlMode;
955
+ this.branchPending = false;
956
+ return { status: "active", profile };
957
+ } catch {
958
+ return { status: "inactive", reason: "transition_failed" };
959
+ }
960
+ }
961
+
962
+ private async _setAutomaticControl(mechanism: CognitiveRoutingMechanism): Promise<CognitiveRoutingAutomaticResult> {
963
+ if (!this.lease || !this.epoch) {
964
+ return { status: "rejected", reason: "not_active" };
965
+ }
966
+ try {
967
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_CONTROL_ENTRY, {
968
+ version: 2,
969
+ control: "automatic",
970
+ source: "user",
971
+ mechanism,
972
+ reason: "manual hold release",
973
+ branchId: this.currentBranchId(),
974
+ epoch: this.epoch,
975
+ });
976
+ } catch {
977
+ return { status: "rejected", reason: "prepare_failed" };
978
+ }
979
+ this.controlMode = "automatic";
980
+ return { status: "automatic" };
981
+ }
982
+
983
+ private currentBranchId(): string | null | undefined {
984
+ const leafId = this.ctx.sessionManager?.getLeafId?.();
985
+ if (typeof leafId === "string" || leafId === null) return leafId;
986
+ try {
987
+ const branch = this.ctx.sessionManager?.getBranch?.();
988
+ const last = Array.isArray(branch) ? branch.at(-1) : undefined;
989
+ return last && typeof last === "object" && typeof (last as Record<string, unknown>).id === "string"
990
+ ? ((last as Record<string, unknown>).id as string)
991
+ : undefined;
992
+ } catch {
993
+ return undefined;
994
+ }
995
+ }
996
+
997
+ private currentPair(): CognitiveRoutingPair | undefined {
998
+ const model = this.ctx.model;
999
+ if (
1000
+ !model ||
1001
+ typeof model.provider !== "string" ||
1002
+ typeof model.id !== "string" ||
1003
+ typeof this.ctx.thinkingLevel !== "string"
1004
+ ) {
1005
+ return undefined;
1006
+ }
1007
+ return {
1008
+ provider: model.provider,
1009
+ modelId: model.id,
1010
+ thinkingLevel: this.ctx.thinkingLevel,
1011
+ };
1012
+ }
1013
+
1014
+ private prepareIntent(input: Omit<CognitiveRoutingIntent, "version" | "phase">): CognitiveRoutingIntent {
1015
+ return { version: 2, phase: "prepared", ...input };
1016
+ }
1017
+
1018
+ private async activatePrepared(options: {
1019
+ kind: "activation" | "profile";
1020
+ controlMode: CognitiveRoutingControlMode;
1021
+ source: "system" | "user" | "agent";
1022
+ mechanism: CognitiveRoutingMechanism;
1023
+ decisionCorrelationId?: string;
1024
+ branchId?: string | null;
1025
+ reason?: string;
1026
+ epoch: string;
1027
+ returnTarget: CognitiveRoutingPair;
1028
+ target: CognitiveRoutingPair;
1029
+ profile: CognitiveRoutingProfileName;
1030
+ }): Promise<CognitiveRoutingActivationResult> {
1031
+ const fromPair = latestHostPair(this.ctx) ?? this.currentPair();
1032
+ if (!fromPair) return { status: "inactive", reason: "current_state_unavailable" };
1033
+ const fromProfile = profileNameForPair(this.capabilityState, fromPair);
1034
+ const correlationId = this.idFactory();
1035
+ const decisionCorrelationId =
1036
+ options.decisionCorrelationId ??
1037
+ (options.source === "user" || options.source === "agent" ? correlationId : undefined);
1038
+ const intent = this.prepareIntent({
1039
+ kind: options.kind,
1040
+ control: options.controlMode === "automatic" ? "automatic" : "manual",
1041
+ source: options.source,
1042
+ mechanism: options.mechanism,
1043
+ ...(decisionCorrelationId ? { decisionCorrelationId } : {}),
1044
+ ...(fromPair ? { fromPair } : {}),
1045
+ ...(fromProfile ? { fromProfile } : {}),
1046
+ ...(options.reason ? { reason: options.reason } : {}),
1047
+ ...(options.branchId === undefined ? {} : { branchId: options.branchId }),
1048
+ epoch: options.epoch,
1049
+ correlationId,
1050
+ profile: options.profile,
1051
+ target: options.target,
1052
+ returnTarget: options.returnTarget,
1053
+ });
1054
+ try {
1055
+ this.pi.appendEntryDurable(COGNITIVE_ROUTING_INTENT_ENTRY, intent);
1056
+ } catch {
1057
+ return { status: "inactive", reason: "prepare_failed" };
1058
+ }
1059
+
1060
+ let acquisition: ModelStateAcquisition;
1061
+ try {
1062
+ acquisition = await this.pi.acquireModelStateControl({ label: this.label });
1063
+ } catch {
1064
+ return { status: "inactive", reason: "acquire_failed" };
1065
+ }
1066
+ if (acquisition.status !== "acquired") {
1067
+ return { status: "inactive", reason: `acquire_${acquisition.status}` };
1068
+ }
1069
+
1070
+ this.lease = acquisition.lease;
1071
+ try {
1072
+ const result = await acquisition.lease.setState({ ...options.target, correlationId: intent.correlationId });
1073
+ if (result.status !== "applied" && result.status !== "unchanged") {
1074
+ await this.releaseLease(acquisition.lease);
1075
+ this.clearActiveState();
1076
+ return { status: "inactive", reason: "transition_rejected" };
1077
+ }
1078
+ this.epoch = options.epoch;
1079
+ this.returnTarget = options.returnTarget;
1080
+ this.activeProfile = options.profile;
1081
+ this.controlMode = options.controlMode;
1082
+ return { status: "active", profile: options.profile };
1083
+ } catch {
1084
+ await this.releaseLease(acquisition.lease);
1085
+ this.clearActiveState();
1086
+ return { status: "inactive", reason: "transition_failed" };
1087
+ }
1088
+ }
1089
+
1090
+ private enqueue<T>(operation: () => Promise<T>): Promise<T> {
1091
+ const next = this.operation.then(operation, operation);
1092
+ this.operation = next.then(
1093
+ () => undefined,
1094
+ () => undefined,
1095
+ );
1096
+ return next;
1097
+ }
1098
+
1099
+ private async releaseLease(lease: ModelStateLease): Promise<void> {
1100
+ try {
1101
+ await lease.release();
1102
+ } catch {
1103
+ // The host invalidates stale leases independently; do not retain local ownership after cleanup.
1104
+ }
1105
+ if (this.lease === lease) this.lease = undefined;
1106
+ }
1107
+
1108
+ private clearActiveState(clearReturnTarget = true): void {
1109
+ this.lease = undefined;
1110
+ this.activeProfile = undefined;
1111
+ this.controlMode = "automatic";
1112
+ this.branchPending = false;
1113
+ if (clearReturnTarget) {
1114
+ this.epoch = undefined;
1115
+ this.returnTarget = undefined;
1116
+ }
1117
+ }
1118
+ }