@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,1099 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import {
4
+ CognitiveRoutingController,
5
+ COGNITIVE_ROUTING_CONTROL_ENTRY,
6
+ COGNITIVE_ROUTING_INTENT_ENTRY,
7
+ } from "../../dist/cognitive-routing/controller.js";
8
+
9
+ const capabilityState = {
10
+ configured: true,
11
+ configValid: true,
12
+ enabled: true,
13
+ effective: true,
14
+ enabledSource: "repository",
15
+ profiles: {},
16
+ profileSources: { standard: "repository", reasoning: "repository" },
17
+ resolvedProfiles: {
18
+ standard: { provider: "faux", model: "standard", thinkingLevel: "high", effectiveThinkingLevel: "high" },
19
+ reasoning: { provider: "faux", model: "reasoning", thinkingLevel: "max", effectiveThinkingLevel: "max" },
20
+ },
21
+ blockingReason: { code: "disabled", message: "not blocked" },
22
+ };
23
+
24
+ function createHost({
25
+ onAcquire,
26
+ entries = [],
27
+ branchEntries,
28
+ currentModel = { provider: "faux", id: "return" },
29
+ } = {}) {
30
+ const calls = [];
31
+ const sessionEntries = [...entries];
32
+ const ctx = {
33
+ model: currentModel,
34
+ thinkingLevel: "medium",
35
+ sessionManager: {
36
+ getEntries: () => sessionEntries,
37
+ getBranch: () => branchEntries ?? sessionEntries,
38
+ getLeafId: () => (branchEntries ?? sessionEntries).at(-1)?.id ?? null,
39
+ },
40
+ };
41
+ const pi = {
42
+ appendEntryDurable(customType, data) {
43
+ calls.push(["prepare", customType, data]);
44
+ if (customType !== COGNITIVE_ROUTING_INTENT_ENTRY && customType !== COGNITIVE_ROUTING_CONTROL_ENTRY) {
45
+ throw new Error(`unexpected entry ${customType}`);
46
+ }
47
+ sessionEntries.push({ type: "custom", customType, data });
48
+ },
49
+ async acquireModelStateControl(options) {
50
+ calls.push(["acquire", options]);
51
+ return onAcquire({ calls, sessionEntries });
52
+ },
53
+ };
54
+ return { calls, ctx, pi, sessionEntries };
55
+ }
56
+
57
+ function appliedLease({ calls, sessionEntries }) {
58
+ return {
59
+ status: "acquired",
60
+ lease: {
61
+ async setState(request) {
62
+ calls.push(["setState", request]);
63
+ sessionEntries.push({
64
+ type: "model_state_change",
65
+ provider: request.provider,
66
+ modelId: request.modelId,
67
+ thinkingLevel: request.thinkingLevel,
68
+ correlationId: request.correlationId,
69
+ });
70
+ return { status: "applied" };
71
+ },
72
+ async release() {
73
+ calls.push(["release"]);
74
+ return { status: "released" };
75
+ },
76
+ },
77
+ };
78
+ }
79
+
80
+ test("prepares activation before acquiring and applying the host pair", async () => {
81
+ const host = createHost({ onAcquire: appliedLease });
82
+ const controller = new CognitiveRoutingController({
83
+ capabilityState,
84
+ pi: host.pi,
85
+ ctx: host.ctx,
86
+ idFactory: (() => {
87
+ const ids = ["epoch-1", "correlation-1"];
88
+ return () => ids.shift();
89
+ })(),
90
+ });
91
+
92
+ const result = await controller.activate();
93
+
94
+ assert.equal(result.status, "active");
95
+ assert.deepEqual(
96
+ host.calls.map(([kind]) => kind),
97
+ ["prepare", "acquire", "setState"],
98
+ );
99
+ assert.deepEqual(host.calls[0][2].returnTarget, {
100
+ provider: "faux",
101
+ modelId: "return",
102
+ thinkingLevel: "medium",
103
+ });
104
+ assert.deepEqual(host.calls[0][2].target, {
105
+ provider: "faux",
106
+ modelId: "standard",
107
+ thinkingLevel: "high",
108
+ });
109
+ assert.equal(controller.state().activeProfile, "standard");
110
+ });
111
+
112
+ test("activates each configured session-start control and profile combination", async () => {
113
+ const combinations = [
114
+ ["automatic", "standard", "automatic"],
115
+ ["automatic", "reasoning", "automatic"],
116
+ ["manual", "standard", "manual-standard"],
117
+ ["manual", "reasoning", "manual-reasoning"],
118
+ ];
119
+
120
+ for (const [control, profile, expectedControlMode] of combinations) {
121
+ const host = createHost({ onAcquire: appliedLease });
122
+ const controller = new CognitiveRoutingController({
123
+ capabilityState: {
124
+ ...capabilityState,
125
+ sessionStart: { control, profile },
126
+ sessionStartSources: { control: "repository", profile: "repository" },
127
+ },
128
+ pi: host.pi,
129
+ ctx: host.ctx,
130
+ idFactory: (() => {
131
+ const ids = ["epoch-1", "correlation-1"];
132
+ return () => ids.shift();
133
+ })(),
134
+ });
135
+
136
+ const result = await controller.activate();
137
+
138
+ assert.equal(result.status, "active");
139
+ assert.equal(controller.state().activeProfile, profile);
140
+ assert.equal(controller.state().controlMode, expectedControlMode);
141
+ assert.equal(host.calls[2][1].modelId, profile);
142
+ }
143
+ });
144
+
145
+ test("applies a durable manual profile hold through the owned transition", async () => {
146
+ const host = createHost({ onAcquire: appliedLease });
147
+ const controller = new CognitiveRoutingController({
148
+ capabilityState,
149
+ pi: host.pi,
150
+ ctx: host.ctx,
151
+ idFactory: (() => {
152
+ const ids = ["epoch-1", "correlation-1", "correlation-2"];
153
+ return () => ids.shift();
154
+ })(),
155
+ });
156
+ await controller.activate();
157
+
158
+ const result = await controller.setManualProfile("reasoning");
159
+
160
+ assert.equal(result.status, "active");
161
+ assert.equal(controller.state().activeProfile, "reasoning");
162
+ assert.equal(controller.state().controlMode, "manual-reasoning");
163
+ assert.deepEqual(
164
+ host.calls.map(([kind]) => kind),
165
+ ["prepare", "acquire", "setState", "prepare", "setState"],
166
+ );
167
+ });
168
+
169
+ test("reports the latest persisted host pair when cached controller state is stale", async () => {
170
+ const host = createHost({ onAcquire: appliedLease });
171
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
172
+ await controller.activate();
173
+ host.sessionEntries.push({
174
+ type: "model_state_change",
175
+ provider: "faux",
176
+ modelId: "reasoning",
177
+ thinkingLevel: "max",
178
+ });
179
+
180
+ assert.equal(controller.state().activeProfile, "reasoning");
181
+ });
182
+
183
+ test("does not report a stale active profile after an unmatched host pair", async () => {
184
+ const host = createHost({ onAcquire: appliedLease });
185
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
186
+ await controller.activate();
187
+ host.sessionEntries.push({
188
+ type: "model_state_change",
189
+ provider: "faux",
190
+ modelId: "outside-routing",
191
+ thinkingLevel: "medium",
192
+ });
193
+
194
+ assert.equal(controller.state().activeProfile, undefined);
195
+ assert.equal(controller.state().effective, false);
196
+ });
197
+
198
+ test("does not persist or reapply an automatic request for the active profile", async () => {
199
+ const host = createHost({ onAcquire: appliedLease });
200
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
201
+ await controller.activate();
202
+ const callsBefore = host.calls.length;
203
+
204
+ const result = await controller.switchAutomaticProfile("standard", "Keep the current profile.");
205
+
206
+ assert.deepEqual(result, {
207
+ status: "active",
208
+ changed: false,
209
+ from: "standard",
210
+ to: "standard",
211
+ profile: "standard",
212
+ });
213
+ assert.equal(host.calls.length, callsBefore);
214
+ });
215
+
216
+ test("switches profiles through the automatic owner with bounded agent evidence", async () => {
217
+ const host = createHost({ onAcquire: appliedLease });
218
+ const controller = new CognitiveRoutingController({
219
+ capabilityState,
220
+ pi: host.pi,
221
+ ctx: host.ctx,
222
+ idFactory: (() => {
223
+ const ids = ["epoch-1", "correlation-1", "correlation-2"];
224
+ return () => ids.shift();
225
+ })(),
226
+ });
227
+ await controller.activate();
228
+
229
+ const result = await controller.switchAutomaticProfile("reasoning", "Need a deeper analysis.");
230
+
231
+ assert.deepEqual(result, {
232
+ status: "active",
233
+ changed: true,
234
+ from: "standard",
235
+ to: "reasoning",
236
+ profile: "reasoning",
237
+ });
238
+ assert.equal(controller.state().controlMode, "automatic");
239
+ assert.equal(host.calls.at(-1)[0], "setState");
240
+ assert.equal(host.calls[3][2].source, "agent");
241
+ assert.equal(host.calls[3][2].reason, "Need a deeper analysis.");
242
+ });
243
+
244
+ test("blocks an automatic switch while a manual hold owns the controller", async () => {
245
+ const host = createHost({ onAcquire: appliedLease });
246
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
247
+ await controller.activate();
248
+ await controller.setManualProfile("reasoning");
249
+ const callsBefore = host.calls.length;
250
+
251
+ const result = await controller.switchAutomaticProfile("standard", "Return to a lighter pass.");
252
+
253
+ assert.deepEqual(result, { status: "blocked", reason: "manual_hold" });
254
+ assert.equal(host.calls.length, callsBefore);
255
+ });
256
+
257
+ test("releases manual control as a durable control-only entry without switching the model", async () => {
258
+ const host = createHost({ onAcquire: appliedLease });
259
+ const controller = new CognitiveRoutingController({
260
+ capabilityState,
261
+ pi: host.pi,
262
+ ctx: host.ctx,
263
+ idFactory: (() => {
264
+ const ids = ["epoch-1", "correlation-1", "correlation-2"];
265
+ return () => ids.shift();
266
+ })(),
267
+ });
268
+ await controller.activate();
269
+ await controller.setManualProfile("reasoning");
270
+ const modelStateEntriesBefore = host.sessionEntries.filter((entry) => entry.type === "model_state_change").length;
271
+
272
+ const result = await controller.setAutomaticControl();
273
+
274
+ assert.equal(result.status, "automatic");
275
+ assert.equal(controller.state().activeProfile, "reasoning");
276
+ assert.equal(controller.state().controlMode, "automatic");
277
+ assert.equal(
278
+ host.sessionEntries.filter((entry) => entry.type === "model_state_change").length,
279
+ modelStateEntriesBefore,
280
+ );
281
+ assert.equal(host.sessionEntries.at(-1).customType, "freeflow-cognitive-routing-control");
282
+ assert.deepEqual(
283
+ host.calls.map(([kind]) => kind),
284
+ ["prepare", "acquire", "setState", "prepare", "setState", "prepare"],
285
+ );
286
+ });
287
+
288
+ test("does not acquire or switch when durable activation preparation fails", async () => {
289
+ let acquireCalls = 0;
290
+ const host = createHost({
291
+ onAcquire: async () => {
292
+ acquireCalls += 1;
293
+ throw new Error("must not acquire");
294
+ },
295
+ });
296
+ host.pi.appendEntryDurable = () => {
297
+ throw new Error("persist failed");
298
+ };
299
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
300
+
301
+ const result = await controller.activate();
302
+
303
+ assert.equal(result.status, "inactive");
304
+ assert.equal(result.reason, "prepare_failed");
305
+ assert.equal(acquireCalls, 0);
306
+ assert.equal(controller.state().effective, false);
307
+ });
308
+
309
+ test("releases the lease when the prepared activation transition is rejected", async () => {
310
+ const host = createHost({
311
+ onAcquire: async ({ calls }) => ({
312
+ status: "acquired",
313
+ lease: {
314
+ async setState() {
315
+ calls.push(["setState"]);
316
+ return { status: "rejected" };
317
+ },
318
+ async release() {
319
+ calls.push(["release"]);
320
+ return { status: "released" };
321
+ },
322
+ },
323
+ }),
324
+ });
325
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
326
+
327
+ const result = await controller.activate();
328
+
329
+ assert.equal(result.status, "inactive");
330
+ assert.equal(result.reason, "transition_rejected");
331
+ assert.deepEqual(
332
+ host.calls.map(([kind]) => kind),
333
+ ["prepare", "acquire", "setState", "release"],
334
+ );
335
+ assert.equal(controller.state().effective, false);
336
+ });
337
+
338
+ test("prepares closing before restoring the return target and releasing ownership", async () => {
339
+ const host = createHost({ onAcquire: appliedLease });
340
+ const controller = new CognitiveRoutingController({
341
+ capabilityState,
342
+ pi: host.pi,
343
+ ctx: host.ctx,
344
+ idFactory: (() => {
345
+ const ids = ["epoch-1", "correlation-1", "correlation-2"];
346
+ return () => ids.shift();
347
+ })(),
348
+ });
349
+ await controller.activate();
350
+ host.ctx.model = { provider: "faux", id: "standard" };
351
+ host.ctx.thinkingLevel = "high";
352
+
353
+ const result = await controller.deactivate();
354
+
355
+ assert.equal(result.status, "inactive");
356
+ assert.deepEqual(
357
+ host.calls.map(([kind]) => kind),
358
+ ["prepare", "acquire", "setState", "prepare", "setState", "release"],
359
+ );
360
+ assert.deepEqual(host.calls[3][2].target, {
361
+ provider: "faux",
362
+ modelId: "return",
363
+ thinkingLevel: "medium",
364
+ });
365
+ assert.equal(controller.state().effective, false);
366
+ });
367
+
368
+ test("releases ownership on quit without starting a restore transition", async () => {
369
+ const host = createHost({ onAcquire: appliedLease });
370
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
371
+ await controller.activate();
372
+
373
+ const result = await controller.shutdown("quit");
374
+
375
+ assert.deepEqual(result, { status: "inactive", reason: "released_on_quit" });
376
+ assert.deepEqual(
377
+ host.calls.map(([kind]) => kind),
378
+ ["prepare", "acquire", "setState", "release"],
379
+ );
380
+ assert.equal(host.sessionEntries.filter((entry) => entry.type === "model_state_change").length, 1);
381
+ assert.equal(controller.state().effective, false);
382
+ });
383
+
384
+ test("does not start a new activation while a prior intent is unresolved", async () => {
385
+ let acquireCalls = 0;
386
+ const host = createHost({
387
+ onAcquire: async ({ calls }) => {
388
+ acquireCalls += 1;
389
+ return {
390
+ status: "acquired",
391
+ lease: {
392
+ async setState() {
393
+ calls.push(["setState"]);
394
+ return { status: "rejected" };
395
+ },
396
+ async release() {
397
+ calls.push(["release"]);
398
+ },
399
+ },
400
+ };
401
+ },
402
+ });
403
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
404
+
405
+ await controller.activate();
406
+ const result = await controller.activate();
407
+
408
+ assert.equal(result.status, "inactive");
409
+ assert.equal(result.reason, "pending_intent");
410
+ assert.equal(acquireCalls, 1);
411
+ });
412
+
413
+ test("serializes deactivation behind an in-flight activation", async () => {
414
+ let releaseTransition;
415
+ let resolveTransition;
416
+ const transitionStarted = new Promise((resolve) => {
417
+ resolveTransition = resolve;
418
+ });
419
+ const host = createHost({
420
+ onAcquire: async ({ calls, sessionEntries }) => ({
421
+ status: "acquired",
422
+ lease: {
423
+ async setState(request) {
424
+ calls.push(["setState", request]);
425
+ if (request.modelId === "standard") {
426
+ resolveTransition();
427
+ await new Promise((resolve) => {
428
+ releaseTransition = resolve;
429
+ });
430
+ }
431
+ sessionEntries.push({
432
+ type: "model_state_change",
433
+ provider: request.provider,
434
+ modelId: request.modelId,
435
+ thinkingLevel: request.thinkingLevel,
436
+ correlationId: request.correlationId,
437
+ });
438
+ return { status: "applied" };
439
+ },
440
+ async release() {
441
+ calls.push(["release"]);
442
+ },
443
+ },
444
+ }),
445
+ });
446
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
447
+
448
+ const activation = controller.activate();
449
+ await transitionStarted;
450
+ const deactivation = controller.deactivate();
451
+ await new Promise((resolve) => setTimeout(resolve, 0));
452
+ assert.deepEqual(
453
+ host.calls.map(([kind]) => kind),
454
+ ["prepare", "acquire", "setState"],
455
+ );
456
+ releaseTransition();
457
+
458
+ assert.equal((await activation).status, "active");
459
+ assert.equal((await deactivation).status, "inactive");
460
+ assert.deepEqual(
461
+ host.calls.map(([kind]) => kind),
462
+ ["prepare", "acquire", "setState", "prepare", "setState", "release"],
463
+ );
464
+ });
465
+
466
+ test("recovers the applied profile while preserving the latest automatic control entry", async () => {
467
+ const entries = [
468
+ {
469
+ type: "custom",
470
+ customType: COGNITIVE_ROUTING_INTENT_ENTRY,
471
+ data: {
472
+ version: 1,
473
+ kind: "activation",
474
+ phase: "prepared",
475
+ control: "automatic",
476
+ source: "system",
477
+ epoch: "epoch-1",
478
+ correlationId: "correlation-1",
479
+ profile: "standard",
480
+ target: { provider: "faux", modelId: "standard", thinkingLevel: "high" },
481
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
482
+ },
483
+ },
484
+ {
485
+ type: "model_state_change",
486
+ provider: "faux",
487
+ modelId: "standard",
488
+ thinkingLevel: "high",
489
+ correlationId: "correlation-1",
490
+ },
491
+ {
492
+ type: "custom",
493
+ customType: COGNITIVE_ROUTING_INTENT_ENTRY,
494
+ data: {
495
+ version: 1,
496
+ kind: "profile",
497
+ phase: "prepared",
498
+ control: "manual",
499
+ source: "user",
500
+ epoch: "epoch-1",
501
+ correlationId: "correlation-2",
502
+ profile: "reasoning",
503
+ target: { provider: "faux", modelId: "reasoning", thinkingLevel: "max" },
504
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
505
+ },
506
+ },
507
+ {
508
+ type: "model_state_change",
509
+ provider: "faux",
510
+ modelId: "reasoning",
511
+ thinkingLevel: "max",
512
+ correlationId: "correlation-2",
513
+ },
514
+ {
515
+ type: "custom",
516
+ customType: COGNITIVE_ROUTING_CONTROL_ENTRY,
517
+ data: { version: 1, control: "automatic", source: "user", epoch: "epoch-1" },
518
+ },
519
+ ];
520
+ const host = createHost({ entries, onAcquire: appliedLease });
521
+ const controller = new CognitiveRoutingController({
522
+ capabilityState,
523
+ pi: host.pi,
524
+ ctx: host.ctx,
525
+ idFactory: () => "recovery-correlation",
526
+ });
527
+
528
+ const result = await controller.recover();
529
+
530
+ assert.deepEqual(result, { status: "active", profile: "reasoning" });
531
+ assert.equal(controller.state().controlMode, "automatic");
532
+ assert.deepEqual(
533
+ host.calls.map(([kind]) => kind),
534
+ ["prepare", "acquire", "setState"],
535
+ );
536
+ });
537
+
538
+ test("session-wide unmatched cleanup blocks recovery from a divergent branch", async () => {
539
+ const activationIntent = {
540
+ version: 1,
541
+ kind: "activation",
542
+ phase: "prepared",
543
+ control: "automatic",
544
+ source: "system",
545
+ epoch: "epoch-1",
546
+ correlationId: "activation-correlation",
547
+ profile: "standard",
548
+ target: { provider: "faux", modelId: "standard", thinkingLevel: "high" },
549
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
550
+ };
551
+ const activationHostEntry = {
552
+ type: "model_state_change",
553
+ provider: "faux",
554
+ modelId: "standard",
555
+ thinkingLevel: "high",
556
+ correlationId: "activation-correlation",
557
+ };
558
+ const closingIntent = {
559
+ version: 1,
560
+ kind: "closing",
561
+ phase: "prepared",
562
+ control: "automatic",
563
+ source: "system",
564
+ branchId: "other-branch",
565
+ epoch: "epoch-1",
566
+ correlationId: "closing-correlation",
567
+ target: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
568
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
569
+ };
570
+ const host = createHost({
571
+ entries: [
572
+ { type: "custom", customType: COGNITIVE_ROUTING_INTENT_ENTRY, data: activationIntent },
573
+ activationHostEntry,
574
+ { type: "custom", customType: COGNITIVE_ROUTING_INTENT_ENTRY, data: closingIntent },
575
+ ],
576
+ branchEntries: [
577
+ { type: "custom", customType: COGNITIVE_ROUTING_INTENT_ENTRY, data: activationIntent },
578
+ activationHostEntry,
579
+ ],
580
+ onAcquire: async () => {
581
+ throw new Error("unmatched cleanup must remain pending");
582
+ },
583
+ });
584
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
585
+
586
+ const recovered = await controller.recover();
587
+ const activated = await controller.activate();
588
+
589
+ assert.deepEqual(recovered, { status: "pending", reason: "closing_recovery_acquire_failed" });
590
+ assert.deepEqual(activated, { status: "inactive", reason: "pending_intent" });
591
+ assert.equal(controller.state().effective, false);
592
+ });
593
+
594
+ test("session-wide matched cleanup prevents revival from a divergent branch", async () => {
595
+ const activationIntent = {
596
+ version: 1,
597
+ kind: "activation",
598
+ phase: "prepared",
599
+ control: "automatic",
600
+ source: "system",
601
+ epoch: "epoch-1",
602
+ correlationId: "activation-correlation",
603
+ profile: "standard",
604
+ target: { provider: "faux", modelId: "standard", thinkingLevel: "high" },
605
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
606
+ };
607
+ const closingIntent = {
608
+ version: 1,
609
+ kind: "closing",
610
+ phase: "prepared",
611
+ control: "automatic",
612
+ source: "system",
613
+ branchId: "other-branch",
614
+ epoch: "epoch-1",
615
+ correlationId: "closing-correlation",
616
+ target: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
617
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
618
+ };
619
+ const activationHostEntry = {
620
+ type: "model_state_change",
621
+ provider: "faux",
622
+ modelId: "standard",
623
+ thinkingLevel: "high",
624
+ correlationId: "activation-correlation",
625
+ };
626
+ const closingHostEntry = {
627
+ type: "model_state_change",
628
+ provider: "faux",
629
+ modelId: "return",
630
+ thinkingLevel: "medium",
631
+ correlationId: "closing-correlation",
632
+ };
633
+ const host = createHost({
634
+ entries: [
635
+ { type: "custom", customType: COGNITIVE_ROUTING_INTENT_ENTRY, data: activationIntent },
636
+ activationHostEntry,
637
+ { type: "custom", customType: COGNITIVE_ROUTING_INTENT_ENTRY, data: closingIntent },
638
+ closingHostEntry,
639
+ ],
640
+ branchEntries: [
641
+ { type: "custom", customType: COGNITIVE_ROUTING_INTENT_ENTRY, data: activationIntent },
642
+ activationHostEntry,
643
+ ],
644
+ onAcquire: appliedLease,
645
+ });
646
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
647
+
648
+ const recovered = await controller.recover();
649
+
650
+ assert.deepEqual(recovered, { status: "inactive", reason: "closed" });
651
+ assert.deepEqual(host.calls, []);
652
+ });
653
+
654
+ test("reconciles the active branch through the owned lease", async () => {
655
+ const host = createHost({ onAcquire: appliedLease });
656
+ const controller = new CognitiveRoutingController({
657
+ capabilityState,
658
+ pi: host.pi,
659
+ ctx: host.ctx,
660
+ idFactory: (() => {
661
+ const ids = ["epoch-1", "correlation-1", "correlation-2"];
662
+ return () => ids.shift();
663
+ })(),
664
+ });
665
+ await controller.activate();
666
+ const branchEntries = [
667
+ {
668
+ id: "intent-profile",
669
+ type: "custom",
670
+ customType: COGNITIVE_ROUTING_INTENT_ENTRY,
671
+ data: {
672
+ version: 1,
673
+ kind: "profile",
674
+ phase: "prepared",
675
+ control: "manual",
676
+ source: "user",
677
+ branchId: "branch-parent",
678
+ epoch: "epoch-1",
679
+ correlationId: "branch-correlation",
680
+ profile: "reasoning",
681
+ target: { provider: "faux", modelId: "reasoning", thinkingLevel: "max" },
682
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
683
+ },
684
+ },
685
+ {
686
+ id: "state-reasoning",
687
+ type: "model_state_change",
688
+ provider: "faux",
689
+ modelId: "reasoning",
690
+ thinkingLevel: "max",
691
+ correlationId: "branch-correlation",
692
+ },
693
+ ];
694
+ host.ctx.sessionManager.getBranch = () => branchEntries;
695
+ host.ctx.sessionManager.getLeafId = () => "state-reasoning";
696
+
697
+ const result = await controller.reconcileBranch();
698
+
699
+ assert.deepEqual(result, { status: "active", profile: "reasoning" });
700
+ assert.equal(controller.state().controlMode, "manual-reasoning");
701
+ assert.deepEqual(
702
+ host.calls.map(([kind]) => kind),
703
+ ["prepare", "acquire", "setState", "prepare", "setState"],
704
+ );
705
+ });
706
+
707
+ test("recovers the active branch instead of importing a divergent branch hold", async () => {
708
+ const activationIntent = {
709
+ version: 1,
710
+ kind: "activation",
711
+ phase: "prepared",
712
+ control: "automatic",
713
+ source: "system",
714
+ epoch: "epoch-1",
715
+ correlationId: "correlation-1",
716
+ profile: "standard",
717
+ target: { provider: "faux", modelId: "standard", thinkingLevel: "high" },
718
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
719
+ };
720
+ const profileIntent = {
721
+ version: 1,
722
+ kind: "profile",
723
+ phase: "prepared",
724
+ control: "manual",
725
+ source: "user",
726
+ epoch: "epoch-1",
727
+ correlationId: "correlation-2",
728
+ profile: "reasoning",
729
+ target: { provider: "faux", modelId: "reasoning", thinkingLevel: "max" },
730
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
731
+ };
732
+ const activationEntry = {
733
+ id: "intent-activation",
734
+ type: "custom",
735
+ customType: COGNITIVE_ROUTING_INTENT_ENTRY,
736
+ data: activationIntent,
737
+ };
738
+ const activationHostEntry = {
739
+ id: "state-standard",
740
+ type: "model_state_change",
741
+ provider: "faux",
742
+ modelId: "standard",
743
+ thinkingLevel: "high",
744
+ correlationId: "correlation-1",
745
+ };
746
+ const profileEntry = {
747
+ id: "intent-profile",
748
+ type: "custom",
749
+ customType: COGNITIVE_ROUTING_INTENT_ENTRY,
750
+ data: profileIntent,
751
+ };
752
+ const profileHostEntry = {
753
+ id: "state-reasoning",
754
+ type: "model_state_change",
755
+ provider: "faux",
756
+ modelId: "reasoning",
757
+ thinkingLevel: "max",
758
+ correlationId: "correlation-2",
759
+ };
760
+ const host = createHost({
761
+ entries: [activationEntry, activationHostEntry, profileEntry, profileHostEntry],
762
+ branchEntries: [activationEntry, activationHostEntry],
763
+ onAcquire: appliedLease,
764
+ });
765
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
766
+
767
+ const result = await controller.recover();
768
+
769
+ assert.deepEqual(result, { status: "active", profile: "standard" });
770
+ assert.equal(controller.state().activeProfile, "standard");
771
+ assert.equal(host.calls[0][2].branchId, "state-standard");
772
+ });
773
+
774
+ test("retries an unmatched prepared activation when its target still resolves", async () => {
775
+ const entries = [
776
+ {
777
+ type: "custom",
778
+ customType: COGNITIVE_ROUTING_INTENT_ENTRY,
779
+ data: {
780
+ version: 1,
781
+ kind: "activation",
782
+ phase: "prepared",
783
+ control: "automatic",
784
+ source: "system",
785
+ epoch: "epoch-1",
786
+ correlationId: "correlation-1",
787
+ profile: "standard",
788
+ target: { provider: "faux", modelId: "standard", thinkingLevel: "high" },
789
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
790
+ },
791
+ },
792
+ ];
793
+ const host = createHost({ entries, onAcquire: appliedLease });
794
+ const controller = new CognitiveRoutingController({
795
+ capabilityState,
796
+ pi: host.pi,
797
+ ctx: host.ctx,
798
+ idFactory: () => "recovery-correlation",
799
+ });
800
+
801
+ const result = await controller.recover();
802
+
803
+ assert.deepEqual(result, { status: "active", profile: "standard" });
804
+ assert.deepEqual(
805
+ host.calls.map(([kind]) => kind),
806
+ ["prepare", "acquire", "setState"],
807
+ );
808
+ assert.equal(host.calls[0][2].epoch, "epoch-1");
809
+ assert.deepEqual(host.calls[2][1], {
810
+ provider: "faux",
811
+ modelId: "standard",
812
+ thinkingLevel: "high",
813
+ correlationId: "recovery-correlation",
814
+ });
815
+ });
816
+
817
+ test("abandons an unmatched intent when its prepared target is no longer valid", async () => {
818
+ const entries = [
819
+ {
820
+ type: "custom",
821
+ customType: COGNITIVE_ROUTING_INTENT_ENTRY,
822
+ data: {
823
+ version: 1,
824
+ kind: "activation",
825
+ phase: "prepared",
826
+ control: "automatic",
827
+ source: "system",
828
+ epoch: "epoch-1",
829
+ correlationId: "correlation-1",
830
+ profile: "standard",
831
+ target: { provider: "faux", modelId: "standard", thinkingLevel: "high" },
832
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
833
+ },
834
+ },
835
+ ];
836
+ const changedCapabilityState = {
837
+ ...capabilityState,
838
+ resolvedProfiles: {
839
+ ...capabilityState.resolvedProfiles,
840
+ standard: { ...capabilityState.resolvedProfiles.standard, model: "replacement" },
841
+ },
842
+ };
843
+ const host = createHost({ entries, onAcquire: appliedLease });
844
+ const controller = new CognitiveRoutingController({
845
+ capabilityState: changedCapabilityState,
846
+ pi: host.pi,
847
+ ctx: host.ctx,
848
+ });
849
+
850
+ const result = await controller.recover();
851
+
852
+ assert.deepEqual(result, { status: "inactive", reason: "intent_abandoned" });
853
+ assert.equal(host.calls.filter(([kind]) => kind === "acquire").length, 0);
854
+ assert.equal(host.sessionEntries.at(-1).data.phase, "abandoned");
855
+ });
856
+
857
+ test("abandons a stale branch intent without recapturing the epoch return target", async () => {
858
+ const entries = [
859
+ {
860
+ type: "custom",
861
+ customType: COGNITIVE_ROUTING_INTENT_ENTRY,
862
+ data: {
863
+ version: 1,
864
+ kind: "activation",
865
+ phase: "prepared",
866
+ control: "automatic",
867
+ source: "system",
868
+ epoch: "epoch-1",
869
+ correlationId: "activation-correlation",
870
+ profile: "standard",
871
+ target: { provider: "faux", modelId: "standard", thinkingLevel: "high" },
872
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
873
+ },
874
+ },
875
+ {
876
+ type: "model_state_change",
877
+ provider: "faux",
878
+ modelId: "standard",
879
+ thinkingLevel: "high",
880
+ correlationId: "activation-correlation",
881
+ },
882
+ {
883
+ type: "custom",
884
+ customType: COGNITIVE_ROUTING_INTENT_ENTRY,
885
+ data: {
886
+ version: 1,
887
+ kind: "profile",
888
+ phase: "prepared",
889
+ control: "manual",
890
+ source: "user",
891
+ epoch: "epoch-1",
892
+ correlationId: "stale-profile-correlation",
893
+ profile: "reasoning",
894
+ target: { provider: "faux", modelId: "reasoning", thinkingLevel: "max" },
895
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
896
+ },
897
+ },
898
+ ];
899
+ const changedCapabilityState = {
900
+ ...capabilityState,
901
+ resolvedProfiles: {
902
+ ...capabilityState.resolvedProfiles,
903
+ reasoning: { ...capabilityState.resolvedProfiles.reasoning, model: "replacement" },
904
+ },
905
+ };
906
+ const host = createHost({ entries, onAcquire: appliedLease });
907
+ const controller = new CognitiveRoutingController({
908
+ capabilityState: changedCapabilityState,
909
+ pi: host.pi,
910
+ ctx: host.ctx,
911
+ idFactory: (() => {
912
+ const ids = ["reconciled-correlation"];
913
+ return () => ids.shift() ?? "fallback-correlation";
914
+ })(),
915
+ });
916
+
917
+ const result = await controller.recover();
918
+
919
+ assert.deepEqual(result, { status: "active", profile: "standard" });
920
+ assert.equal(host.calls[0][2].phase, "abandoned");
921
+ assert.equal(host.calls[1][2].returnTarget.modelId, "return");
922
+ assert.equal(controller.state().returnTarget.modelId, "return");
923
+ });
924
+
925
+ test("retries an unmatched closing intent and releases after restoring its exact target", async () => {
926
+ const entries = [
927
+ {
928
+ type: "custom",
929
+ customType: COGNITIVE_ROUTING_INTENT_ENTRY,
930
+ data: {
931
+ version: 1,
932
+ kind: "closing",
933
+ phase: "prepared",
934
+ control: "automatic",
935
+ source: "system",
936
+ epoch: "epoch-1",
937
+ correlationId: "correlation-1",
938
+ target: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
939
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
940
+ },
941
+ },
942
+ ];
943
+ const host = createHost({ entries, onAcquire: appliedLease });
944
+ const controller = new CognitiveRoutingController({
945
+ capabilityState,
946
+ pi: host.pi,
947
+ ctx: host.ctx,
948
+ idFactory: () => "closing-recovery-correlation",
949
+ });
950
+
951
+ const result = await controller.recover();
952
+
953
+ assert.deepEqual(result, { status: "inactive", reason: "restored" });
954
+ assert.deepEqual(
955
+ host.calls.map(([kind]) => kind),
956
+ ["prepare", "acquire", "setState", "release"],
957
+ );
958
+ assert.deepEqual(host.calls[2][1], {
959
+ provider: "faux",
960
+ modelId: "return",
961
+ thinkingLevel: "medium",
962
+ correlationId: "closing-recovery-correlation",
963
+ });
964
+ });
965
+
966
+ test("keeps an unmatched prepared activation pending when recovery retry fails", async () => {
967
+ const entries = [
968
+ {
969
+ type: "custom",
970
+ customType: COGNITIVE_ROUTING_INTENT_ENTRY,
971
+ data: {
972
+ version: 1,
973
+ kind: "activation",
974
+ phase: "prepared",
975
+ epoch: "epoch-1",
976
+ correlationId: "correlation-1",
977
+ target: { provider: "faux", modelId: "standard", thinkingLevel: "high" },
978
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
979
+ },
980
+ },
981
+ ];
982
+ let acquireCalls = 0;
983
+ const host = createHost({
984
+ entries,
985
+ onAcquire: async () => {
986
+ acquireCalls += 1;
987
+ throw new Error("recovery must not guess success");
988
+ },
989
+ });
990
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
991
+
992
+ const result = await controller.recover();
993
+
994
+ assert.equal(result.status, "pending");
995
+ assert.equal(controller.state().effective, false);
996
+ assert.equal(acquireCalls, 1);
997
+ });
998
+
999
+ test("writes v2 mechanism, causal, and baseline metadata before transitions", async () => {
1000
+ const host = createHost({ onAcquire: appliedLease });
1001
+ const controller = new CognitiveRoutingController({
1002
+ capabilityState,
1003
+ pi: host.pi,
1004
+ ctx: host.ctx,
1005
+ idFactory: (() => {
1006
+ const ids = ["epoch-1", "activation-correlation", "profile-correlation"];
1007
+ return () => ids.shift();
1008
+ })(),
1009
+ });
1010
+
1011
+ await controller.activate();
1012
+ await controller.switchAutomaticProfile("reasoning", "Need a deeper analysis.");
1013
+ await controller.setAutomaticControl();
1014
+
1015
+ const intents = host.sessionEntries.filter(
1016
+ (entry) => entry.type === "custom" && entry.customType === COGNITIVE_ROUTING_INTENT_ENTRY,
1017
+ );
1018
+ assert.deepEqual(intents[0].data, {
1019
+ version: 2,
1020
+ phase: "prepared",
1021
+ kind: "activation",
1022
+ control: "automatic",
1023
+ source: "system",
1024
+ mechanism: "activation",
1025
+ branchId: null,
1026
+ epoch: "epoch-1",
1027
+ correlationId: "activation-correlation",
1028
+ target: { provider: "faux", modelId: "standard", thinkingLevel: "high" },
1029
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
1030
+ fromPair: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
1031
+ profile: "standard",
1032
+ });
1033
+ assert.deepEqual(intents[1].data, {
1034
+ version: 2,
1035
+ phase: "prepared",
1036
+ kind: "profile",
1037
+ control: "automatic",
1038
+ source: "agent",
1039
+ mechanism: "agent-tool",
1040
+ decisionCorrelationId: "profile-correlation",
1041
+ branchId: null,
1042
+ epoch: "epoch-1",
1043
+ correlationId: "profile-correlation",
1044
+ profile: "reasoning",
1045
+ target: { provider: "faux", modelId: "reasoning", thinkingLevel: "max" },
1046
+ returnTarget: { provider: "faux", modelId: "return", thinkingLevel: "medium" },
1047
+ fromPair: { provider: "faux", modelId: "standard", thinkingLevel: "high" },
1048
+ fromProfile: "standard",
1049
+ reason: "Need a deeper analysis.",
1050
+ });
1051
+
1052
+ const control = host.sessionEntries.find(
1053
+ (entry) => entry.type === "custom" && entry.customType === COGNITIVE_ROUTING_CONTROL_ENTRY,
1054
+ );
1055
+ assert.deepEqual(control.data, {
1056
+ version: 2,
1057
+ control: "automatic",
1058
+ source: "user",
1059
+ mechanism: "profile-command",
1060
+ reason: "manual hold release",
1061
+ branchId: null,
1062
+ epoch: "epoch-1",
1063
+ });
1064
+ });
1065
+
1066
+ test("fails closed before a profile transition when no current baseline is observable", async () => {
1067
+ const host = createHost({ onAcquire: appliedLease });
1068
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
1069
+ await controller.activate();
1070
+ const callsBefore = host.calls.length;
1071
+ host.sessionEntries.length = 0;
1072
+ host.ctx.model = undefined;
1073
+ host.ctx.thinkingLevel = undefined;
1074
+
1075
+ const result = await controller.switchAutomaticProfile("reasoning", "Need a deeper analysis.");
1076
+
1077
+ assert.deepEqual(result, { status: "inactive", reason: "current_state_unavailable" });
1078
+ assert.equal(host.calls.length, callsBefore);
1079
+ assert.deepEqual(host.sessionEntries, []);
1080
+ });
1081
+
1082
+ test("restores the return target without guessing a missing closing baseline", async () => {
1083
+ const host = createHost({ onAcquire: appliedLease });
1084
+ const controller = new CognitiveRoutingController({ capabilityState, pi: host.pi, ctx: host.ctx });
1085
+ await controller.activate();
1086
+ host.sessionEntries.length = 0;
1087
+ host.ctx.model = undefined;
1088
+ host.ctx.thinkingLevel = undefined;
1089
+
1090
+ const result = await controller.deactivate();
1091
+
1092
+ assert.deepEqual(result, { status: "inactive", reason: "restored" });
1093
+ const closingIntent = host.sessionEntries.find(
1094
+ (entry) => entry.type === "custom" && entry.customType === COGNITIVE_ROUTING_INTENT_ENTRY,
1095
+ );
1096
+ assert.equal(closingIntent.data.fromPair, undefined);
1097
+ assert.equal(closingIntent.data.fromProfile, "standard");
1098
+ assert.equal(host.sessionEntries.at(-1).type, "model_state_change");
1099
+ });