@hassangameryt/freeflow 0.7.3 → 0.9.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 (426) hide show
  1. package/.agents/plugins/marketplace.json +2 -2
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +2 -2
  4. package/.codex-plugin/plugin.json +3 -3
  5. package/.cursor-plugin/plugin.json +1 -1
  6. package/NOTICE +14 -0
  7. package/README.md +101 -159
  8. package/capabilities/cognitive-routing/SKILL.md +47 -210
  9. package/capabilities/cognitive-routing/references/coordinator.md +163 -0
  10. package/capabilities/cognitive-routing/references/worker.md +38 -0
  11. package/capabilities/compaction/SKILL.md +49 -0
  12. package/capabilities/compaction/references/summary-format.md +250 -0
  13. package/capabilities/messaging/SKILL.md +49 -0
  14. package/capabilities/task-memory/SKILL.md +87 -0
  15. package/command-surface.json +8 -52
  16. package/gemini-extension.json +1 -1
  17. package/hooks/claude/hooks.json +13 -3
  18. package/hooks/codex/hooks.json +2 -1
  19. package/hooks/shared/runtime-context.mjs +73 -83
  20. package/licenses/Apache-2.0.txt +55 -0
  21. package/package.json +42 -12
  22. package/pi-extension/README.md +41 -0
  23. package/pi-extension/dist/ask-user/ask.js +108 -0
  24. package/pi-extension/dist/ask-user/form.js +250 -0
  25. package/pi-extension/dist/ask-user/questions.js +66 -0
  26. package/pi-extension/dist/ask-user/tool.js +124 -0
  27. package/pi-extension/dist/cognitive-routing/assembler.js +417 -0
  28. package/pi-extension/dist/cognitive-routing/bootstrap.js +90 -0
  29. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/config.js +8 -6
  30. package/pi-extension/dist/cognitive-routing/economics.js +45 -0
  31. package/pi-extension/dist/cognitive-routing/event-schema.js +388 -0
  32. package/pi-extension/dist/{session-sources/events.js → cognitive-routing/event-store.js} +107 -41
  33. package/pi-extension/dist/cognitive-routing/gate.js +256 -0
  34. package/pi-extension/dist/cognitive-routing/handlers.js +901 -0
  35. package/pi-extension/dist/cognitive-routing/handoffs.js +350 -0
  36. package/pi-extension/dist/cognitive-routing/model-control.js +476 -0
  37. package/pi-extension/dist/cognitive-routing/projection.js +520 -0
  38. package/pi-extension/dist/cognitive-routing/provenance.js +83 -0
  39. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/render.js +15 -15
  40. package/pi-extension/dist/cognitive-routing/runtime.js +398 -0
  41. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/schemas.js +47 -11
  42. package/pi-extension/dist/cognitive-routing/session.js +223 -0
  43. package/pi-extension/dist/{session-sources → cognitive-routing}/sources.js +126 -87
  44. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/state.js +55 -386
  45. package/pi-extension/dist/cognitive-routing/status.js +81 -0
  46. package/pi-extension/dist/cognitive-routing/tools.js +74 -0
  47. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/types.js +14 -11
  48. package/pi-extension/dist/compaction/carry.js +205 -0
  49. package/pi-extension/dist/compaction/config.js +24 -0
  50. package/pi-extension/dist/compaction/controller.js +494 -0
  51. package/pi-extension/dist/compaction/harness.js +93 -0
  52. package/pi-extension/dist/compaction/results.js +159 -0
  53. package/pi-extension/dist/compaction/thresholds.js +35 -0
  54. package/pi-extension/dist/compaction/tool.js +57 -0
  55. package/pi-extension/dist/host/branch.js +13 -0
  56. package/pi-extension/dist/host/canonical.js +12 -0
  57. package/pi-extension/dist/host/catalog.js +62 -0
  58. package/pi-extension/dist/host/config-validation.js +233 -0
  59. package/pi-extension/dist/host/config.js +361 -0
  60. package/pi-extension/dist/host/inbound.js +142 -0
  61. package/pi-extension/dist/host/projection-tags.js +60 -0
  62. package/pi-extension/dist/host/prompts.js +93 -0
  63. package/pi-extension/dist/{session-sources → host}/read-only-session.js +117 -1
  64. package/pi-extension/dist/{runtime → host}/request-history.js +125 -39
  65. package/pi-extension/dist/host/rows.js +25 -0
  66. package/pi-extension/dist/host/runtime-state.js +204 -0
  67. package/pi-extension/dist/host/section-keeper.js +85 -0
  68. package/pi-extension/dist/host/settings/freeflow-command.js +2323 -0
  69. package/pi-extension/dist/{settings/settings-tui.js → host/settings/settings-view.js} +205 -73
  70. package/pi-extension/dist/host/staging.js +28 -0
  71. package/pi-extension/dist/host/status.js +115 -0
  72. package/pi-extension/dist/index.js +1004 -188
  73. package/pi-extension/dist/messaging/config.js +27 -0
  74. package/pi-extension/dist/messaging/messaging.js +398 -0
  75. package/pi-extension/dist/messaging/registry.js +57 -0
  76. package/pi-extension/dist/messaging/render.js +90 -0
  77. package/pi-extension/dist/messaging/tools.js +109 -0
  78. package/pi-extension/dist/messaging/transport.js +101 -0
  79. package/pi-extension/dist/provider-support/cache/anchor.js +21 -0
  80. package/pi-extension/dist/provider-support/cache/anthropic.js +102 -0
  81. package/pi-extension/dist/provider-support/cache/health.js +73 -0
  82. package/pi-extension/dist/provider-support/cache/index.js +58 -0
  83. package/pi-extension/dist/provider-support/cache/keepalive.js +222 -0
  84. package/pi-extension/dist/provider-support/cache/monitor.js +17 -0
  85. package/pi-extension/dist/provider-support/cache/openai-responses.js +48 -0
  86. package/pi-extension/dist/provider-support/effort.js +13 -0
  87. package/pi-extension/dist/provider-support/index.js +44 -3
  88. package/pi-extension/dist/provider-support/{astra → openai}/adapter.js +46 -29
  89. package/pi-extension/dist/provider-support/{astra → openai}/history.js +10 -8
  90. package/pi-extension/dist/provider-support/{astra → openai}/index.js +8 -4
  91. package/pi-extension/dist/provider-support/{astra → openai}/session-state.js +29 -38
  92. package/pi-extension/dist/provider-support/routes.js +17 -0
  93. package/pi-extension/dist/task-memory/config.js +49 -0
  94. package/pi-extension/dist/task-memory/registry.js +119 -0
  95. package/pi-extension/dist/task-memory/render.js +107 -0
  96. package/pi-extension/dist/task-memory/runtime.js +994 -0
  97. package/pi-extension/dist/task-memory/tool.js +233 -0
  98. package/pi-extension/dist/tool-execution/apply-patch/grammar.js +23 -0
  99. package/pi-extension/dist/tool-execution/apply-patch/match.js +38 -0
  100. package/pi-extension/dist/tool-execution/apply-patch/parser.js +177 -0
  101. package/pi-extension/dist/tool-execution/apply-patch/plan.js +201 -0
  102. package/pi-extension/dist/tool-execution/apply-patch/tool.js +84 -0
  103. package/pi-extension/dist/tool-execution/background.js +430 -0
  104. package/pi-extension/dist/tool-execution/bash-guard.js +23 -0
  105. package/pi-extension/dist/tool-execution/config.js +33 -0
  106. package/pi-extension/dist/tool-execution/edit-messages.js +120 -0
  107. package/pi-extension/dist/tool-execution/file-state.js +138 -0
  108. package/pi-extension/dist/tool-execution/file-tracking.js +163 -0
  109. package/pi-extension/dist/tool-execution/guidance-notices.js +124 -0
  110. package/pi-extension/dist/tool-execution/prompt.js +54 -0
  111. package/pi-extension/dist/tool-execution/skill-reads.js +143 -0
  112. package/pi-extension/dist/tool-execution/tools.js +16 -0
  113. package/pi-extension/freeflow/README.md +9 -0
  114. package/runtime/prompts/cognitive-routing.md +4 -4
  115. package/runtime/prompts/core.md +29 -72
  116. package/runtime/prompts/interaction-contract.md +18 -8
  117. package/runtime/prompts/tool-execution.md +25 -0
  118. package/runtime/prompts/working-method.md +25 -0
  119. package/skills/deliver-work/SKILL.md +76 -0
  120. package/skills/deliver-work/references/branch-closeout.md +134 -0
  121. package/skills/deliver-work/references/commit.md +83 -0
  122. package/skills/deliver-work/references/launch.md +94 -0
  123. package/skills/deliver-work/references/release.md +85 -0
  124. package/skills/deliver-work/scripts/commit-state.mjs +139 -0
  125. package/skills/deliver-work/scripts/delivery-state.mjs +107 -0
  126. package/skills/deliver-work/scripts/lib/git-state.mjs +178 -0
  127. package/skills/deliver-work/scripts/push-route.mjs +122 -0
  128. package/skills/deliver-work/scripts/release-preflight.mjs +177 -0
  129. package/skills/discuss-work/SKILL.md +148 -0
  130. package/skills/{discuss → discuss-work}/references/discussion-continuity.md +13 -50
  131. package/skills/discuss-work/references/learning-action.md +36 -0
  132. package/skills/discuss-work/scripts/choices.mjs +101 -0
  133. package/skills/discuss-work/scripts/lib/choices.mjs +159 -0
  134. package/skills/evaluate-behavior/SKILL.md +107 -0
  135. package/skills/evaluate-behavior/references/authoring.md +381 -0
  136. package/skills/evaluate-behavior/references/coding-tasks.md +145 -0
  137. package/skills/evaluate-behavior/references/conversations-pipelines-judges.md +177 -0
  138. package/skills/evaluate-behavior/references/design-and-measurement.md +273 -0
  139. package/skills/evaluate-behavior/references/running-and-evidence.md +245 -0
  140. package/skills/evaluate-behavior/scripts/claude-guard.mjs +76 -0
  141. package/skills/evaluate-behavior/scripts/guard-rules.mjs +309 -0
  142. package/skills/evaluate-behavior/scripts/lib/agreement.mjs +90 -0
  143. package/skills/evaluate-behavior/scripts/lib/arms.mjs +55 -0
  144. package/skills/evaluate-behavior/scripts/lib/budget.mjs +87 -0
  145. package/skills/evaluate-behavior/scripts/lib/build-source.mjs +287 -0
  146. package/skills/evaluate-behavior/scripts/lib/clear.mjs +74 -0
  147. package/skills/evaluate-behavior/scripts/lib/container.mjs +395 -0
  148. package/skills/evaluate-behavior/scripts/lib/decision.mjs +418 -0
  149. package/skills/evaluate-behavior/scripts/lib/definitions.mjs +1072 -0
  150. package/skills/evaluate-behavior/scripts/lib/freeflow.mjs +103 -0
  151. package/skills/evaluate-behavior/scripts/lib/grade-command.mjs +591 -0
  152. package/skills/evaluate-behavior/scripts/lib/grade-comparison.mjs +90 -0
  153. package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/grade-interaction.mjs +19 -18
  154. package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/grade-support.mjs +32 -5
  155. package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/grade-workspace.mjs +28 -12
  156. package/skills/evaluate-behavior/scripts/lib/grade.mjs +101 -0
  157. package/skills/evaluate-behavior/scripts/lib/hooks.mjs +98 -0
  158. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/confinement.mjs +196 -0
  159. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/constraints.mjs +111 -0
  160. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/index.mjs +48 -0
  161. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/isolation.mjs +74 -0
  162. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/launch.mjs +123 -0
  163. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/model-call.mjs +73 -0
  164. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/recorder.mjs +178 -0
  165. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/session.mjs +494 -0
  166. package/skills/evaluate-behavior/scripts/lib/hosts/claude-code/skills.mjs +81 -0
  167. package/skills/evaluate-behavior/scripts/lib/hosts/index.mjs +31 -0
  168. package/skills/evaluate-behavior/scripts/lib/hosts/names.mjs +3 -0
  169. package/skills/evaluate-behavior/scripts/lib/hosts/pi/confinement.mjs +173 -0
  170. package/skills/evaluate-behavior/scripts/lib/hosts/pi/host.mjs +148 -0
  171. package/skills/evaluate-behavior/scripts/lib/hosts/pi/index.mjs +70 -0
  172. package/skills/evaluate-behavior/scripts/lib/hosts/pi/isolation.mjs +81 -0
  173. package/skills/evaluate-behavior/scripts/lib/hosts/pi/model-call.mjs +79 -0
  174. package/skills/evaluate-behavior/scripts/lib/hosts/pi/process.mjs +241 -0
  175. package/skills/{evaluate-skill/scripts/lib → evaluate-behavior/scripts/lib/hosts/pi}/rpc.mjs +144 -26
  176. package/skills/evaluate-behavior/scripts/lib/identity.mjs +82 -0
  177. package/skills/evaluate-behavior/scripts/lib/judge.mjs +688 -0
  178. package/skills/evaluate-behavior/scripts/lib/metrics.mjs +332 -0
  179. package/skills/evaluate-behavior/scripts/lib/model-call.mjs +17 -0
  180. package/skills/evaluate-behavior/scripts/lib/participants.mjs +616 -0
  181. package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/process.mjs +22 -0
  182. package/skills/evaluate-behavior/scripts/lib/queue.mjs +54 -0
  183. package/skills/evaluate-behavior/scripts/lib/reference.mjs +343 -0
  184. package/skills/evaluate-behavior/scripts/lib/reuse.mjs +277 -0
  185. package/skills/evaluate-behavior/scripts/lib/review.mjs +933 -0
  186. package/skills/evaluate-behavior/scripts/lib/runner.mjs +732 -0
  187. package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/sandbox.mjs +121 -14
  188. package/skills/evaluate-behavior/scripts/lib/scan-shell.mjs +457 -0
  189. package/skills/evaluate-behavior/scripts/lib/scan.mjs +479 -0
  190. package/skills/evaluate-behavior/scripts/lib/seal.mjs +91 -0
  191. package/skills/evaluate-behavior/scripts/lib/shell.mjs +560 -0
  192. package/skills/evaluate-behavior/scripts/lib/source-override.mjs +64 -0
  193. package/skills/evaluate-behavior/scripts/lib/subject-file.mjs +88 -0
  194. package/skills/{evaluate-skill/scripts/lib/pi.mjs → evaluate-behavior/scripts/lib/subject.mjs} +239 -262
  195. package/skills/evaluate-behavior/scripts/lib/task-copy.mjs +124 -0
  196. package/skills/evaluate-behavior/scripts/lib/trials.mjs +524 -0
  197. package/skills/evaluate-behavior/scripts/lib/validity.mjs +68 -0
  198. package/skills/evaluate-behavior/scripts/lib/view-html.mjs +454 -0
  199. package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/view.mjs +218 -11
  200. package/skills/evaluate-behavior/scripts/pi-command-tool.mjs +159 -0
  201. package/skills/evaluate-behavior/scripts/pi-container-route.mjs +23 -0
  202. package/skills/evaluate-behavior/scripts/pi-guard.mjs +77 -0
  203. package/skills/evaluate-behavior/scripts/pi-login-refresh.mjs +31 -0
  204. package/skills/evaluate-behavior/scripts/skill-eval.mjs +586 -0
  205. package/skills/execute-work/SKILL.md +96 -72
  206. package/skills/execute-work/references/code-practices.md +27 -49
  207. package/skills/execute-work/references/design.md +271 -0
  208. package/skills/execute-work/references/diagnose.md +117 -0
  209. package/skills/execute-work/references/migration.md +108 -0
  210. package/skills/execute-work/references/simplify.md +65 -0
  211. package/skills/execute-work/scripts/self-review.mjs +422 -0
  212. package/skills/execute-work/scripts/touch-map.mjs +290 -0
  213. package/skills/review-work/SKILL.md +94 -64
  214. package/skills/review-work/references/adjudication.md +94 -0
  215. package/skills/review-work/references/artifact.md +198 -0
  216. package/skills/review-work/references/evals-and-judges.md +66 -0
  217. package/skills/review-work/references/work.md +177 -0
  218. package/skills/review-work/scripts/check-brief.mjs +128 -0
  219. package/skills/review-work/scripts/review-packet.mjs +233 -0
  220. package/skills/setup-freeflow/SKILL.md +69 -16
  221. package/skills/track-work/SKILL.md +135 -151
  222. package/skills/track-work/references/handoff.md +190 -0
  223. package/skills/track-work/references/projects.md +51 -0
  224. package/skills/track-work/references/working-record-format.md +201 -344
  225. package/skills/track-work/scripts/lib/document.mjs +79 -19
  226. package/skills/track-work/scripts/lib/format.mjs +18 -1
  227. package/skills/track-work/scripts/lib/recover.mjs +254 -0
  228. package/skills/track-work/scripts/lib/registry.mjs +656 -0
  229. package/skills/track-work/scripts/lib/search.mjs +40 -0
  230. package/skills/track-work/scripts/lib/store.mjs +53 -21
  231. package/skills/track-work/scripts/lib/transitions.mjs +79 -4
  232. package/skills/track-work/scripts/lib/views.mjs +50 -1
  233. package/skills/track-work/scripts/working-record.mjs +263 -22
  234. package/skills/verify-work/SKILL.md +64 -47
  235. package/skills/verify-work/references/feature-map.md +120 -0
  236. package/skills/verify-work/references/runtime-evidence.md +203 -0
  237. package/skills/verify-work/references/test-design.md +27 -6
  238. package/skills/verify-work/scripts/test-changes.mjs +246 -0
  239. package/skills/write-docs/SKILL.md +171 -0
  240. package/skills/write-docs/references/documentation-shapes.md +184 -0
  241. package/skills/write-docs/references/spec-and-plan-shapes.md +308 -0
  242. package/skills/write-docs/scripts/artifact-check.mjs +148 -0
  243. package/skills/write-docs/scripts/docs-check.mjs +229 -0
  244. package/skills/write-docs/scripts/plan-lint.mjs +123 -0
  245. package/skills/write-skill/SKILL.md +165 -165
  246. package/skills/write-skill/references/activation-and-wording.md +143 -0
  247. package/skills/write-skill/references/placement-and-dependencies.md +154 -0
  248. package/skills/write-skill/scripts/lib/compare.mjs +701 -0
  249. package/skills/write-skill/scripts/lib/similarity.mjs +56 -0
  250. package/skills/write-skill/scripts/lib/skill-author.mjs +197 -3
  251. package/skills/write-skill/scripts/skill-author.mjs +67 -8
  252. package/capabilities/context-virtualization/SKILL.md +0 -103
  253. package/capabilities/conversation-history/SKILL.md +0 -53
  254. package/hooks/tests/check-host-adapters.test.mjs +0 -82
  255. package/hooks/tests/check-runtime-context-hook.sh +0 -212
  256. package/pi-extension/dist/cognitive-routing-v2/projection.js +0 -330
  257. package/pi-extension/dist/cognitive-routing-v2/runtime.js +0 -2181
  258. package/pi-extension/dist/cognitive-routing-v2/tools.js +0 -60
  259. package/pi-extension/dist/context-virtualization/commands.js +0 -89
  260. package/pi-extension/dist/context-virtualization/projector.js +0 -42
  261. package/pi-extension/dist/context-virtualization/runtime.js +0 -378
  262. package/pi-extension/dist/context-virtualization/state.js +0 -57
  263. package/pi-extension/dist/context-virtualization/types.js +0 -10
  264. package/pi-extension/dist/conversation-history/passages.js +0 -66
  265. package/pi-extension/dist/conversation-history/ranking.js +0 -105
  266. package/pi-extension/dist/conversation-history/runtime.js +0 -226
  267. package/pi-extension/dist/conversation-history/search.js +0 -56
  268. package/pi-extension/dist/conversation-history/types.js +0 -1
  269. package/pi-extension/dist/freeflow-context/resolver.js +0 -120
  270. package/pi-extension/dist/freeflow-context/runtime.js +0 -80
  271. package/pi-extension/dist/freeflow-context/source-projector.js +0 -95
  272. package/pi-extension/dist/freeflow-context/tool.js +0 -314
  273. package/pi-extension/dist/freeflow-context/types.js +0 -12
  274. package/pi-extension/dist/freeflow-context/visibility.js +0 -28
  275. package/pi-extension/dist/integrations/mcp-config.js +0 -29
  276. package/pi-extension/dist/runtime/runtime-context.js +0 -754
  277. package/pi-extension/dist/runtime/runtime-identity.js +0 -5
  278. package/pi-extension/dist/session-sources/provenance.js +0 -32
  279. package/pi-extension/dist/settings/settings-ui.js +0 -1360
  280. package/pi-extension/dist/ui/text-component.js +0 -57
  281. package/pi-extension/src/cognitive-routing-v2/budget.ts +0 -42
  282. package/pi-extension/src/cognitive-routing-v2/config.ts +0 -173
  283. package/pi-extension/src/cognitive-routing-v2/projection.ts +0 -375
  284. package/pi-extension/src/cognitive-routing-v2/render.ts +0 -277
  285. package/pi-extension/src/cognitive-routing-v2/runtime.ts +0 -2241
  286. package/pi-extension/src/cognitive-routing-v2/schemas.ts +0 -180
  287. package/pi-extension/src/cognitive-routing-v2/state.ts +0 -839
  288. package/pi-extension/src/cognitive-routing-v2/tools.ts +0 -62
  289. package/pi-extension/src/cognitive-routing-v2/types.ts +0 -254
  290. package/pi-extension/src/context-virtualization/commands.ts +0 -111
  291. package/pi-extension/src/context-virtualization/projector.ts +0 -62
  292. package/pi-extension/src/context-virtualization/runtime.ts +0 -428
  293. package/pi-extension/src/context-virtualization/state.ts +0 -79
  294. package/pi-extension/src/context-virtualization/types.ts +0 -92
  295. package/pi-extension/src/conversation-history/passages.ts +0 -81
  296. package/pi-extension/src/conversation-history/ranking.ts +0 -155
  297. package/pi-extension/src/conversation-history/runtime.ts +0 -250
  298. package/pi-extension/src/conversation-history/search.ts +0 -79
  299. package/pi-extension/src/conversation-history/types.ts +0 -31
  300. package/pi-extension/src/freeflow-context/resolver.ts +0 -139
  301. package/pi-extension/src/freeflow-context/runtime.ts +0 -100
  302. package/pi-extension/src/freeflow-context/source-projector.ts +0 -106
  303. package/pi-extension/src/freeflow-context/tool.ts +0 -366
  304. package/pi-extension/src/freeflow-context/types.ts +0 -70
  305. package/pi-extension/src/freeflow-context/visibility.ts +0 -53
  306. package/pi-extension/src/index.ts +0 -390
  307. package/pi-extension/src/integrations/mcp-config.ts +0 -32
  308. package/pi-extension/src/provider-support/astra/adapter.ts +0 -108
  309. package/pi-extension/src/provider-support/astra/history.ts +0 -145
  310. package/pi-extension/src/provider-support/astra/index.ts +0 -12
  311. package/pi-extension/src/provider-support/astra/session-state.ts +0 -113
  312. package/pi-extension/src/provider-support/index.ts +0 -5
  313. package/pi-extension/src/runtime/request-history.ts +0 -243
  314. package/pi-extension/src/runtime/runtime-context.ts +0 -860
  315. package/pi-extension/src/runtime/runtime-identity.ts +0 -8
  316. package/pi-extension/src/session-sources/events.ts +0 -230
  317. package/pi-extension/src/session-sources/provenance.ts +0 -39
  318. package/pi-extension/src/session-sources/read-only-session.ts +0 -170
  319. package/pi-extension/src/session-sources/sources.ts +0 -334
  320. package/pi-extension/src/settings/settings-tui.ts +0 -501
  321. package/pi-extension/src/settings/settings-ui.ts +0 -1652
  322. package/pi-extension/src/ui/text-component.ts +0 -66
  323. package/pi-extension/tests/cache-reuse/history.test.js +0 -117
  324. package/pi-extension/tests/cache-reuse/native.test.js +0 -91
  325. package/pi-extension/tests/cache-reuse/settings.test.js +0 -211
  326. package/pi-extension/tests/cognitive-routing-v2/communication.test.js +0 -577
  327. package/pi-extension/tests/cognitive-routing-v2/compaction-input.test.js +0 -183
  328. package/pi-extension/tests/cognitive-routing-v2/delegation.test.js +0 -557
  329. package/pi-extension/tests/cognitive-routing-v2/native.test.js +0 -474
  330. package/pi-extension/tests/cognitive-routing-v2/performance.test.js +0 -87
  331. package/pi-extension/tests/cognitive-routing-v2/persistence.test.js +0 -300
  332. package/pi-extension/tests/cognitive-routing-v2/projection.test.js +0 -241
  333. package/pi-extension/tests/cognitive-routing-v2/recovery.test.js +0 -1034
  334. package/pi-extension/tests/cognitive-routing-v2/render.test.js +0 -244
  335. package/pi-extension/tests/cognitive-routing-v2/runtime.test.js +0 -423
  336. package/pi-extension/tests/cognitive-routing-v2/stabilization.test.js +0 -521
  337. package/pi-extension/tests/cognitive-routing-v2/state.test.js +0 -586
  338. package/pi-extension/tests/context-virtualization/extension.test.js +0 -775
  339. package/pi-extension/tests/context-virtualization/projector.test.js +0 -110
  340. package/pi-extension/tests/context-virtualization/runtime.test.js +0 -230
  341. package/pi-extension/tests/conversation-history/runtime.test.js +0 -98
  342. package/pi-extension/tests/conversation-history/search.test.js +0 -97
  343. package/pi-extension/tests/fixtures/pi-host.js +0 -4
  344. package/pi-extension/tests/fixtures/routing-native.js +0 -191
  345. package/pi-extension/tests/integration/mode-free-core.test.js +0 -220
  346. package/pi-extension/tests/integration/pi-extension.test.js +0 -1447
  347. package/pi-extension/tests/integration/prompt-architecture.test.js +0 -447
  348. package/pi-extension/tests/integration/unaffected-regressions.test.js +0 -478
  349. package/pi-extension/tests/provider-support/astra-boundaries.test.js +0 -75
  350. package/pi-extension/tests/provider-support/astra.test.js +0 -306
  351. package/pi-extension/tests/provider-support/cli.test.js +0 -92
  352. package/pi-extension/tests/provider-support/native.test.js +0 -183
  353. package/pi-extension/tests/settings/settings-tui.test.js +0 -243
  354. package/pi-extension/tsconfig.json +0 -16
  355. package/plugin.json +0 -33
  356. package/runtime/prompts/context-virtualization.md +0 -3
  357. package/runtime/prompts/conversation-history.md +0 -3
  358. package/skills/action-selection/SKILL.md +0 -100
  359. package/skills/action-selection/references/trajectory-stalls.md +0 -71
  360. package/skills/bypass/SKILL.md +0 -153
  361. package/skills/commit-work/SKILL.md +0 -145
  362. package/skills/commit-work/references/git-state-edges.md +0 -94
  363. package/skills/commit-work/references/simple-push.md +0 -92
  364. package/skills/commit-work/references/staging-decisions.md +0 -106
  365. package/skills/decision-gate/SKILL.md +0 -106
  366. package/skills/design-for-depth/SKILL.md +0 -117
  367. package/skills/design-for-depth/references/design-pressure-signals.md +0 -182
  368. package/skills/design-for-depth/references/implementation-decisions.md +0 -76
  369. package/skills/design-for-depth/references/interface-design-loop.md +0 -136
  370. package/skills/design-for-depth/references/module-and-dependency-design.md +0 -147
  371. package/skills/design-for-depth/references/software-design-philosophy.md +0 -202
  372. package/skills/design-for-depth/references/state-and-failure-boundaries.md +0 -136
  373. package/skills/diagnose-failure/SKILL.md +0 -125
  374. package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +0 -48
  375. package/skills/diagnose-failure/references/flaky-and-performance-diagnosis.md +0 -51
  376. package/skills/discuss/SKILL.md +0 -116
  377. package/skills/evaluate-skill/SKILL.md +0 -219
  378. package/skills/evaluate-skill/references/evaluation-definition-schema.md +0 -385
  379. package/skills/evaluate-skill/references/evaluation-design.md +0 -112
  380. package/skills/evaluate-skill/references/execution-and-evidence.md +0 -90
  381. package/skills/evaluate-skill/references/review-and-revision.md +0 -92
  382. package/skills/evaluate-skill/scripts/lib/definitions.mjs +0 -407
  383. package/skills/evaluate-skill/scripts/lib/grade-comparison.mjs +0 -60
  384. package/skills/evaluate-skill/scripts/lib/grade.mjs +0 -64
  385. package/skills/evaluate-skill/scripts/lib/runner.mjs +0 -368
  386. package/skills/evaluate-skill/scripts/pi-guard.mjs +0 -164
  387. package/skills/evaluate-skill/scripts/skill-eval.mjs +0 -102
  388. package/skills/execute-work/references/execute-work-edges.md +0 -68
  389. package/skills/finish-branch/SKILL.md +0 -117
  390. package/skills/finish-branch/references/integration-options.md +0 -80
  391. package/skills/handoff/SKILL.md +0 -82
  392. package/skills/handoff/references/handoff-templates.md +0 -150
  393. package/skills/launch-work/SKILL.md +0 -116
  394. package/skills/launch-work/references/launch-readiness.md +0 -85
  395. package/skills/migration-work/SKILL.md +0 -115
  396. package/skills/migration-work/references/migration-lifecycle.md +0 -82
  397. package/skills/release-work/SKILL.md +0 -118
  398. package/skills/release-work/references/release-evidence.md +0 -78
  399. package/skills/review-artifact/SKILL.md +0 -142
  400. package/skills/review-artifact/references/adjudicate-artifact-review.md +0 -101
  401. package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +0 -159
  402. package/skills/review-work/references/adjudicate-work-review.md +0 -97
  403. package/skills/review-work/references/independent-work-reviewer-contract.md +0 -139
  404. package/skills/review-work/references/security-risk-lens.md +0 -69
  405. package/skills/setup-freeflow/references/activation-contract.md +0 -109
  406. package/skills/setup-freeflow/references/host-setup.md +0 -67
  407. package/skills/simplify-code/SKILL.md +0 -85
  408. package/skills/simplify-code/references/simplification-patterns.md +0 -70
  409. package/skills/verify-work/references/browser-runtime-evidence.md +0 -55
  410. package/skills/verify-work/references/integration-evidence.md +0 -47
  411. package/skills/verify-work/references/performance-evidence.md +0 -57
  412. package/skills/workflow/SKILL.md +0 -127
  413. package/skills/workflow/references/domain-skill-composition.md +0 -43
  414. package/skills/write-plan/SKILL.md +0 -92
  415. package/skills/write-plan/references/plan-shapes.md +0 -156
  416. package/skills/write-skill/references/activation-boundaries.md +0 -104
  417. package/skills/write-skill/references/agent-first-instructions.md +0 -121
  418. package/skills/write-skill/references/progressive-disclosure.md +0 -127
  419. package/skills/write-skill/references/skill-dependency-graphs.md +0 -190
  420. package/skills/write-spec/SKILL.md +0 -92
  421. package/skills/write-spec/references/artifact-standards.md +0 -86
  422. package/skills/write-spec/references/decision-records.md +0 -78
  423. package/skills/write-spec/references/spec-shapes.md +0 -143
  424. /package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/budget.js +0 -0
  425. /package/skills/{evaluate-skill → evaluate-behavior}/scripts/lib/evidence.mjs +0 -0
  426. /package/skills/{evaluate-skill → evaluate-behavior}/scripts/pi-observer.mjs +0 -0
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
- import { open, stat } from "node:fs/promises";
2
+ import { statSync } from "node:fs";
3
+ import { lstat, open, stat } from "node:fs/promises";
3
4
  import { TextDecoder } from "node:util";
4
5
  export class ReadOnlySessionError extends Error {
5
6
  code;
@@ -50,7 +51,10 @@ export function parseReadOnlySessionText(text) {
50
51
  const seen = new Set();
51
52
  return lines.map((line, i) => decodeEntry(line, i + 1, seen));
52
53
  }
54
+ /** Whole-file snapshots read so far; tests check that a verified startup reads none. */
55
+ export const readOnlySessionCounters = { snapshots: 0 };
53
56
  export async function readOnlySessionSnapshot(path, options = {}) {
57
+ readOnlySessionCounters.snapshots++;
54
58
  const limits = { ...SESSION_READ_LIMITS, ...options };
55
59
  if (Object.values(limits).some((n) => !Number.isSafeInteger(n) || n <= 0))
56
60
  throw new ReadOnlySessionError("invalid_limit", "Invalid snapshot limit.");
@@ -146,3 +150,115 @@ export function activeReadOnlySessionBranch(snapshot, leafId) {
146
150
  }
147
151
  return path.reverse();
148
152
  }
153
+ // Byte offset and entry count up to which a session file is known to equal Pi's in-memory entries.
154
+ const verified = new Map();
155
+ /** Pi just parsed this file into memory, so its current bytes are the verified prefix. */
156
+ export function trustLoadedSession(reader) {
157
+ const path = reader.getSessionFile?.();
158
+ if (!path) return;
159
+ try {
160
+ verified.set(path, { size: statSync(path).size, count: reader.getEntries().length });
161
+ } catch {
162
+ verified.delete(path);
163
+ }
164
+ }
165
+ /**
166
+ * At `session_start`, trust the file only when Pi just parsed it. A reload keeps Pi's session in memory without
167
+ * re-reading the file, so it establishes nothing: after a failed write, memory could hold an entry the file lacks.
168
+ * The previous trust point, or a full check, still applies after a reload.
169
+ */
170
+ export function trustStartedSession(reason, reader) {
171
+ if (reason !== "reload") trustLoadedSession(reader);
172
+ }
173
+ async function tailMatches(path, reader) {
174
+ const point = verified.get(path);
175
+ if (!point) return false;
176
+ const entries = reader.getEntries();
177
+ let file;
178
+ try {
179
+ file = await open(path, "r");
180
+ const { size } = await file.stat();
181
+ if (size < point.size || entries.length < point.count) return false;
182
+ const buffer = Buffer.alloc(size - point.size);
183
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, point.size);
184
+ if (bytesRead !== buffer.length) return false;
185
+ const lines = new TextDecoder("utf-8", { fatal: true }).decode(buffer).split("\n");
186
+ if (lines.pop() !== "") return false;
187
+ const appended = entries.slice(point.count);
188
+ // Pi appends each entry as its JSON serialization, in memory order.
189
+ if (lines.length !== appended.length || lines.some((line, i) => line !== JSON.stringify(appended[i]))) return false;
190
+ verified.set(path, { size, count: entries.length });
191
+ return true;
192
+ } catch {
193
+ return false;
194
+ } finally {
195
+ await file?.close();
196
+ }
197
+ }
198
+ /**
199
+ * Whether every entry Pi holds is persisted, judged only by the bytes appended since the trust point: true when the
200
+ * file grew by exactly those entries. False when there is no trust point or anything differs; callers then fall back
201
+ * to a full snapshot.
202
+ */
203
+ export async function persistedTailMatches(reader) {
204
+ const path = reader.getSessionFile?.();
205
+ return !!path && (await tailMatches(path, reader));
206
+ }
207
+ /** Verify one newly appended native anchor without re-reading the historical session. */
208
+ export async function persistedLastEntryMatches(path, entry) {
209
+ if (!path) return false;
210
+ let file;
211
+ try {
212
+ const expected = Buffer.from(`${JSON.stringify(entry)}\n`, "utf8");
213
+ if (!expected.length || expected.length > 1024 * 1024) return false;
214
+ const named = await lstat(path, { bigint: true });
215
+ if (!named.isFile() || named.isSymbolicLink() || named.size < BigInt(expected.length)) return false;
216
+ file = await open(path, "r");
217
+ const before = await file.stat({ bigint: true });
218
+ if (before.size > BigInt(Number.MAX_SAFE_INTEGER)) return false;
219
+ const actual = Buffer.alloc(expected.length);
220
+ let offset = 0;
221
+ while (offset < actual.length) {
222
+ const read = await file.read(
223
+ actual,
224
+ offset,
225
+ actual.length - offset,
226
+ Number(before.size) - actual.length + offset,
227
+ );
228
+ if (!read.bytesRead) return false;
229
+ offset += read.bytesRead;
230
+ }
231
+ const after = await file.stat({ bigint: true });
232
+ const current = await lstat(path, { bigint: true });
233
+ const signature = (value) => [value.dev, value.ino, value.size, value.mtimeNs, value.ctimeNs].join(":");
234
+ return (
235
+ before.isFile() &&
236
+ signature(named) === signature(before) &&
237
+ signature(before) === signature(after) &&
238
+ signature(after) === signature(current) &&
239
+ actual.equals(expected)
240
+ );
241
+ } catch {
242
+ return false;
243
+ } finally {
244
+ await file?.close();
245
+ }
246
+ }
247
+ /** Whether the persisted session holds exactly this branch: tail-only after a trust point, else a full comparison. */
248
+ export async function persistedBranchMatches(reader, leaf, branch) {
249
+ const path = reader.getSessionFile?.();
250
+ if (!path) return false;
251
+ if (await tailMatches(path, reader)) return true;
252
+ const snapshot = await readOnlySessionSnapshot(path);
253
+ const matches =
254
+ snapshot.sessionId === reader.getSessionId() &&
255
+ JSON.stringify(activeReadOnlySessionBranch(snapshot, leaf)) === JSON.stringify(branch);
256
+ // The trust point covers every entry Pi holds, so it is set only when the file holds them all: a match on this
257
+ // branch says nothing of an entry on another branch that was never written.
258
+ const onDisk = new Set(snapshot.entries.slice(1).map((entry) => entry.id));
259
+ const inMemory = reader.getEntries();
260
+ const complete = inMemory.length === onDisk.size && inMemory.every((entry) => onDisk.has(entry.id));
261
+ if (matches && complete) trustLoadedSession(reader);
262
+ else verified.delete(path);
263
+ return matches;
264
+ }
@@ -1,23 +1,26 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { activeReadOnlySessionBranch, readOnlySessionSnapshot } from "../session-sources/read-only-session.js";
2
+ import { persistedBranchMatches } from "./read-only-session.js";
3
+ import { occurrenceIdentity } from "./projection-tags.js";
4
+ import { cachedBranch as activeBranch } from "./branch.js";
3
5
  const ENTRY = "freeflow-request-history-v1";
4
6
  const TRANSIENT = new Set([
5
7
  "freeflow-runtime-state",
6
8
  "freeflow-cognitive-routing-runtime-state",
7
9
  "freeflow-routing-v2-state",
10
+ "freeflow-routing-attention",
8
11
  "freeflow-routing-budget",
9
12
  "freeflow-routing-communication",
10
13
  ]);
14
+ // Situational notices describe a condition, not standing state; once absent, the next occurrence is new.
15
+ const SITUATIONAL = new Set(["freeflow-routing-attention"]);
11
16
  const hash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
17
+ /** Whole-message fingerprints computed so far; the request-path budget test counts them per request. */
18
+ export const requestHistoryCounters = { fingerprints: 0 };
12
19
  function fingerprint(message) {
20
+ requestHistoryCounters.fingerprints++;
13
21
  const { usage: _usage, timestamp: _timestamp, details: _details, ...body } = message;
14
22
  return hash(body);
15
23
  }
16
- function prefixes(messages) {
17
- const result = [hash([])];
18
- for (const message of messages) result.push(hash([result.at(-1), fingerprint(message)]));
19
- return result;
20
- }
21
24
  function owned(message) {
22
25
  return message?.role === "custom" && TRANSIENT.has(message.customType);
23
26
  }
@@ -50,17 +53,60 @@ function parse(value) {
50
53
  /** Preserve only Freeflow-generated occurrences. Native content remains owned by Pi and its projectors. */
51
54
  export class RequestHistory {
52
55
  pi;
56
+ monitor;
53
57
  acknowledged = new Map();
58
+ // Pi reuses immutable native entry objects across requests. A replacement object with the
59
+ // same ID must be validated again; a known entry need not be rehashed and reparsed.
60
+ validatedFrames = new Map();
61
+ prefixCache;
62
+ branchCache;
63
+ frameHash = (entry) => {
64
+ const cached = this.validatedFrames.get(entry.id);
65
+ return cached !== undefined && cached.entry === entry ? cached.hash : hash(entry);
66
+ };
67
+ // Unedited native entries and Freeflow's renderings of them never change under their identity, so their
68
+ // fingerprints are computed once per session.
69
+ fingerprints = new Map();
70
+ fingerprintOf = (message) => {
71
+ const id = occurrenceIdentity(message);
72
+ if (id === undefined) return fingerprint(message);
73
+ let value = this.fingerprints.get(id);
74
+ if (value === undefined) this.fingerprints.set(id, (value = fingerprint(message)));
75
+ return value;
76
+ };
77
+ prefixes(messages) {
78
+ const previous = this.prefixCache;
79
+ const identities = [];
80
+ const values = [hash([])];
81
+ let samePrefix = true;
82
+ for (let i = 0; i < messages.length; i++) {
83
+ const message = messages[i];
84
+ const entryId = occurrenceIdentity(message);
85
+ // Generated and host-edited messages have no stable identity and must be hashed anew.
86
+ const body = entryId === undefined ? fingerprint(message) : undefined;
87
+ const identity = entryId === undefined ? `body:${body}` : `entry:${entryId}`;
88
+ identities.push(identity);
89
+ samePrefix = samePrefix && previous?.identities[i] === identity;
90
+ values.push(samePrefix ? previous.values[i + 1] : hash([values[i], body ?? this.fingerprintOf(message)]));
91
+ }
92
+ this.prefixCache = { identities, values };
93
+ return values;
94
+ }
54
95
  identity;
55
96
  fault = false;
56
97
  serial = Promise.resolve();
57
98
  revision = 0;
58
- constructor(pi) {
99
+ constructor(pi, monitor) {
59
100
  this.pi = pi;
101
+ this.monitor = monitor;
60
102
  }
61
103
  reset() {
62
104
  this.revision++;
63
105
  this.acknowledged.clear();
106
+ this.validatedFrames.clear();
107
+ this.prefixCache = undefined;
108
+ this.branchCache = undefined;
109
+ this.fingerprints.clear();
64
110
  this.identity = undefined;
65
111
  this.fault = false;
66
112
  }
@@ -71,9 +117,7 @@ export class RequestHistory {
71
117
  try {
72
118
  return await this.prepare(messages, view, ctx, revision, notice);
73
119
  } catch {
74
- try {
75
- ctx.ui?.setStatus?.("freeflow-cache", "Freeflow context replay unavailable · current view retained");
76
- } catch {}
120
+ this.monitor?.set("context-replay", "Freeflow context replay unavailable · current view retained");
77
121
  // Keep the already-qualified projected view on failure, never raw hidden history.
78
122
  return messages;
79
123
  }
@@ -87,42 +131,62 @@ export class RequestHistory {
87
131
  const identity = `${reader.getSessionId()}:${reader.getSessionFile?.() ?? "memory"}`;
88
132
  if (this.identity !== identity) {
89
133
  this.acknowledged.clear();
134
+ this.validatedFrames.clear();
135
+ this.prefixCache = undefined;
136
+ this.branchCache = undefined;
137
+ this.fingerprints.clear();
90
138
  this.fault = false;
91
139
  this.identity = identity;
92
140
  }
93
141
  if (this.fault) throw new Error("Uncertain Freeflow context append");
94
- const branch = reader.getBranch(),
142
+ const branch = activeBranch(reader),
95
143
  leaf = reader.getLeafId();
96
- let parent = null,
97
- generation = "root";
98
- const ids = new Set();
99
- for (const entry of branch) {
100
- if (entry.parentId !== parent || ids.has(entry.id)) throw new Error("Invalid context ancestry");
144
+ const cachedBranch = this.branchCache;
145
+ // Pi appends immutable native entry objects. A sibling/edited branch breaks this exact prefix.
146
+ const extendsCache =
147
+ !!cachedBranch &&
148
+ cachedBranch.length <= branch.length &&
149
+ (cachedBranch.length === 0 ||
150
+ (branch[0] === cachedBranch.first && branch[cachedBranch.length - 1] === cachedBranch.last));
151
+ const start = extendsCache ? cachedBranch.length : 0;
152
+ let parent = extendsCache ? cachedBranch.leaf : null;
153
+ let generation = extendsCache ? cachedBranch.generation : "root";
154
+ const ids = extendsCache ? cachedBranch.ids : new Set();
155
+ const newIds = new Set();
156
+ for (let i = start; i < branch.length; i++) {
157
+ const entry = branch[i];
158
+ if (entry.parentId !== parent || ids.has(entry.id) || newIds.has(entry.id))
159
+ throw new Error("Invalid context ancestry");
101
160
  parent = entry.id;
102
- ids.add(entry.id);
103
- if (entry.type === "compaction" || entry.type === "branch_summary") generation = entry.id;
161
+ newIds.add(entry.id);
162
+ // Compaction replaces earlier history. A branch summary follows its branch point and keeps the path
163
+ // before it intact, so generated state there keeps its positions (frames on the abandoned path are
164
+ // not ancestors and drop out on their own).
165
+ if (entry.type === "compaction") generation = entry.id;
104
166
  }
105
167
  if (parent !== leaf) throw new Error("Context leaf changed");
106
- const entries = branch.filter((e) => e.type === "custom" && e.customType === ENTRY);
168
+ const newEntries = branch.slice(start).filter((e) => e.type === "custom" && e.customType === ENTRY);
107
169
  if (
108
- entries.some((e) => this.acknowledged.get(e.id) !== hash(e)) &&
170
+ newEntries.some((e) => this.acknowledged.get(e.id) !== this.frameHash(e)) &&
109
171
  reader.getSessionFile?.() &&
110
172
  branch.some((e) => e.message?.role === "assistant")
111
173
  ) {
112
- const snapshot = await readOnlySessionSnapshot(reader.getSessionFile());
113
- if (
114
- snapshot.sessionId !== reader.getSessionId() ||
115
- JSON.stringify(activeReadOnlySessionBranch(snapshot, leaf)) !== JSON.stringify(branch)
116
- )
117
- throw new Error("Context history readback differs");
174
+ if (!(await persistedBranchMatches(reader, leaf, branch))) throw new Error("Context history readback differs");
118
175
  }
119
176
  if (revision !== this.revision || reader.getLeafId() !== leaf) throw new Error("Context changed while preparing");
120
- const frames = [],
121
- byId = new Map();
122
- for (const entry of entries) {
123
- const frame = parse(entry.data);
177
+ const frames = extendsCache ? (newEntries.length ? [...cachedBranch.frames] : cachedBranch.frames) : [];
178
+ const byId = extendsCache ? (newEntries.length ? new Map(cachedBranch.byId) : cachedBranch.byId) : new Map();
179
+ for (const entry of newEntries) {
180
+ const cached = this.validatedFrames.get(entry.id);
181
+ const same = cached !== undefined && cached.entry === entry;
182
+ const frame = same ? cached.frame : parse(entry.data);
124
183
  if (
125
- (frame.basis !== entry.parentId && !(reader.getHeader?.()?.parentSession && !ids.has(frame.basis))) ||
184
+ (frame.basis !== entry.parentId &&
185
+ // A null basis is in neither set, so it counts as outside the parent session's branch.
186
+ !(
187
+ reader.getHeader?.()?.parentSession &&
188
+ (frame.basis === null || (!ids.has(frame.basis) && !newIds.has(frame.basis)))
189
+ )) ||
126
190
  byId.has(frame.id)
127
191
  )
128
192
  throw new Error("Context frame anchor differs");
@@ -131,13 +195,26 @@ export class RequestHistory {
131
195
  throw new Error("Context frame parent missing");
132
196
  frames.push(frame);
133
197
  byId.set(frame.id, frame);
134
- this.acknowledged.set(entry.id, hash(entry));
198
+ const entryHash = same ? cached.hash : hash(entry);
199
+ this.acknowledged.set(entry.id, entryHash);
200
+ if (!same) this.validatedFrames.set(entry.id, { entry, hash: entryHash, frame });
135
201
  }
202
+ for (const id of newIds) ids.add(id);
203
+ this.branchCache = {
204
+ first: branch[0],
205
+ last: branch.at(-1),
206
+ length: branch.length,
207
+ leaf,
208
+ generation,
209
+ ids,
210
+ frames,
211
+ byId,
212
+ };
136
213
  const base = messages.filter((m) => !owned(m));
137
214
  const current = messages
138
215
  .filter(owned)
139
216
  .filter((message) => !notice || message.customType !== "freeflow-routing-budget");
140
- const hashes = prefixes(base);
217
+ const hashes = this.prefixes(base);
141
218
  const candidates = frames.filter((f) => f.generation === generation && hashes[f.length] === f.prefix);
142
219
  const prior = candidates.reduce((best, f) => (!best || f.length >= best.length ? f : best), undefined);
143
220
  const states = { ...prior?.states },
@@ -152,6 +229,13 @@ export class RequestHistory {
152
229
  if (kind === "freeflow-routing-communication") seenRetained.add(signature);
153
230
  else states[kind] = signature;
154
231
  }
232
+ const present = new Set(current.map((message) => message.customType));
233
+ let cleared = false;
234
+ for (const kind of SITUATIONAL)
235
+ if (states[kind] && !present.has(kind)) {
236
+ delete states[kind];
237
+ cleared = true;
238
+ }
155
239
  const injections = [];
156
240
  const chain = [];
157
241
  for (let cursor = prior; cursor; cursor = cursor.parent ? byId.get(cursor.parent) : undefined)
@@ -183,7 +267,9 @@ export class RequestHistory {
183
267
  }
184
268
  }
185
269
  }
186
- if (!prior || prior.length !== base.length || additions.length) {
270
+ // A frame that only advances the length adds no injection its parent lacks and matches no
271
+ // branch its parent does not, so frames are written only when generated state changes.
272
+ if (!prior || additions.length || cleared) {
187
273
  const frame = {
188
274
  version: 1,
189
275
  id: randomUUID(),
@@ -199,18 +285,18 @@ export class RequestHistory {
199
285
  };
200
286
  try {
201
287
  this.pi.appendEntry(ENTRY, frame);
202
- const entry = reader.getBranch().find((e) => e.customType === ENTRY && e.data?.id === frame.id);
288
+ const entry = activeBranch(reader).find((e) => e.customType === ENTRY && e.data?.id === frame.id);
203
289
  if (!entry || entry.parentId !== leaf || JSON.stringify(entry.data) !== JSON.stringify(frame))
204
290
  throw new Error("Context append not acknowledged");
205
- this.acknowledged.set(entry.id, hash(entry));
291
+ const entryHash = hash(entry);
292
+ this.acknowledged.set(entry.id, entryHash);
293
+ this.validatedFrames.set(entry.id, { entry, hash: entryHash, frame });
206
294
  } catch (error) {
207
295
  this.fault = true;
208
296
  throw error;
209
297
  }
210
298
  }
211
- try {
212
- ctx.ui?.setStatus?.("freeflow-cache", undefined);
213
- } catch {}
299
+ this.monitor?.set("context-replay", undefined);
214
300
  return result;
215
301
  }
216
302
  }
@@ -0,0 +1,25 @@
1
+ import { Text } from "@earendil-works/pi-tui";
2
+ /**
3
+ * A transcript row the way Pi draws its own: a one-line head, then the body. A short body (a few lines) shows in both
4
+ * views; a long one shows only when the row is expanded (ctrl+o), with a count of what is hidden.
5
+ */
6
+ export const SHORT_LINES = 4;
7
+ const SHORT_CHARS = 400;
8
+ export function paint(theme, color, text) {
9
+ return theme?.fg ? theme.fg(color, text) : text;
10
+ }
11
+ export function firstLine(text, max = 100) {
12
+ const line =
13
+ String(text ?? "")
14
+ .split("\n")
15
+ .find((each) => each.trim()) ?? "";
16
+ const clean = line.trim();
17
+ return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
18
+ }
19
+ export function foldRow(head, body, expanded, theme) {
20
+ const lines = body.flatMap((each) => String(each).split("\n"));
21
+ const short = lines.length <= SHORT_LINES && lines.join("\n").length <= SHORT_CHARS;
22
+ if (!lines.length) return new Text(head, 0, 0);
23
+ if (expanded || short) return new Text(`${head}\n${lines.map((line) => ` ${line}`).join("\n")}`, 0, 0);
24
+ return new Text(`${head} ${paint(theme, "dim", `(${lines.length} lines, ctrl+o to expand)`)}`, 0, 0);
25
+ }
@@ -0,0 +1,204 @@
1
+ import { reviewStateLine, skillsStateLine } from "./config-validation.js";
2
+ import { hasUsableMandatoryPrompts } from "./prompts.js";
3
+ /**
4
+ * The Freeflow Runtime State message: what is active this request, placed so unchanged state keeps its cached
5
+ * position and changed state never rewrites earlier input. Also drops bootstrap messages that older Freeflow
6
+ * versions saved in sessions.
7
+ */
8
+ const FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE = "freeflow-runtime-state";
9
+ const COGNITIVE_ROUTING_RUNTIME_STATE_MESSAGE_TYPE = "freeflow-cognitive-routing-runtime-state";
10
+ const WORKFLOW_BOOTSTRAP_MESSAGE_TYPE = "freeflow-workflow-bootstrap";
11
+ const COGNITIVE_ROUTING_BOOTSTRAP_MESSAGE_TYPE = "freeflow-cognitive-routing-bootstrap";
12
+ const FREEFLOW_BOOTSTRAP_MESSAGE_TYPE = "freeflow-bootstrap";
13
+ const BOOTSTRAP_COMPONENTS = Object.freeze({
14
+ workflow: "workflow",
15
+ cognitiveRouting: "cognitive-routing",
16
+ });
17
+ function bootstrapEntryComponents(entry) {
18
+ const isCustomMessage = entry?.role === "custom" || entry?.type === "custom_message" || entry?.type === "custom";
19
+ if (!isCustomMessage) return [];
20
+ if (entry.customType === FREEFLOW_BOOTSTRAP_MESSAGE_TYPE) {
21
+ if (Array.isArray(entry.details?.components)) return entry.details.components;
22
+ return [
23
+ ...(entry.content?.includes("<!-- freeflow-bootstrap:workflow -->") ? [BOOTSTRAP_COMPONENTS.workflow] : []),
24
+ ...(entry.content?.includes("<!-- freeflow-bootstrap:cognitive-routing -->")
25
+ ? [BOOTSTRAP_COMPONENTS.cognitiveRouting]
26
+ : []),
27
+ ];
28
+ }
29
+ if (entry.customType === WORKFLOW_BOOTSTRAP_MESSAGE_TYPE) {
30
+ return [BOOTSTRAP_COMPONENTS.workflow];
31
+ }
32
+ if (entry.customType === COGNITIVE_ROUTING_BOOTSTRAP_MESSAGE_TYPE) {
33
+ return [BOOTSTRAP_COMPONENTS.cognitiveRouting];
34
+ }
35
+ return [];
36
+ }
37
+ export function filterBootstrapMessage(message) {
38
+ return bootstrapEntryComponents(message).length === 0 ? message : undefined;
39
+ }
40
+ function publicCognitiveRoutingControl(controlMode) {
41
+ if (controlMode === "automatic") return "automatic";
42
+ if (["manual-helper", "manual-executor", "manual-coordinator"].includes(String(controlMode))) return "manual";
43
+ return "unavailable";
44
+ }
45
+ function publicCognitiveRoutingProfile(activeProfile, effective) {
46
+ if (effective !== true) return "unavailable";
47
+ return typeof activeProfile === "string" && ["helper", "executor", "coordinator"].includes(activeProfile)
48
+ ? activeProfile
49
+ : "unavailable";
50
+ }
51
+ function publicCapabilityStatus(capability) {
52
+ if (capability?.effective === true) return "active";
53
+ if (!capability) return "unavailable";
54
+ const blockingCode = capability.blockingReason?.code;
55
+ if (blockingCode && blockingCode !== "disabled") return "unavailable";
56
+ return "inactive";
57
+ }
58
+ function publicCognitiveRoutingStatus(capability, runtime) {
59
+ if (runtime?.runtimeStatus === "inactive") return "inactive";
60
+ return publicCapabilityStatus(capability);
61
+ }
62
+ function publicCognitiveRoutingProjectionMode(capability, runtime, projectionFailure) {
63
+ if (capability?.projection !== true) return "disabled";
64
+ if (capability?.effective !== true) return "unavailable";
65
+ if (String(runtime?.controlMode).startsWith("manual-")) return "manual-bypass";
66
+ if (projectionFailure) return "blocked";
67
+ if (runtime?.runtimeStatus === "inactive" || runtime?.runtimeStatus === "blocked") return "unavailable";
68
+ if (runtime?.effective === true && runtime.controlMode === "automatic") return "enabled";
69
+ return "pending";
70
+ }
71
+ export function freeflowRuntimeStateMessage(
72
+ capabilityState,
73
+ cognitiveRoutingRuntime = undefined,
74
+ freeflowContext = undefined,
75
+ options = {},
76
+ ) {
77
+ const cognitiveRoutingEffective = capabilityState?.cognitiveRouting?.effective === true;
78
+ const profile = publicCognitiveRoutingProfile(
79
+ cognitiveRoutingRuntime?.activeProfile,
80
+ cognitiveRoutingEffective && cognitiveRoutingRuntime?.effective === true,
81
+ );
82
+ const control =
83
+ profile === "unavailable" ? "unavailable" : publicCognitiveRoutingControl(cognitiveRoutingRuntime?.controlMode);
84
+ const projectionMode = publicCognitiveRoutingProjectionMode(
85
+ capabilityState?.cognitiveRouting,
86
+ cognitiveRoutingRuntime,
87
+ options.projectionFailure,
88
+ );
89
+ const mandatoryPromptAvailable = capabilityState?.enabled !== true || hasUsableMandatoryPrompts(freeflowContext);
90
+ const freeflowStatus = capabilityState?.configured
91
+ ? capabilityState.enabled
92
+ ? mandatoryPromptAvailable
93
+ ? "active"
94
+ : "unavailable"
95
+ : "inactive"
96
+ : capabilityState?.configExists
97
+ ? "config error"
98
+ : "setup needed";
99
+ // Only a choice the user made: the default adds nothing, so most users' state stays as it was.
100
+ const review = freeflowStatus === "active" ? reviewStateLine(capabilityState?.review) : null;
101
+ const skillsOff = freeflowStatus === "active" ? skillsStateLine(capabilityState?.skills?.off) : null;
102
+ return {
103
+ role: "custom",
104
+ customType: FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE,
105
+ content: [
106
+ "# Freeflow Runtime State",
107
+ "",
108
+ "This is extension-generated runtime state. Use it to interpret the stable Freeflow guidance.",
109
+ "",
110
+ `Freeflow: ${freeflowStatus}`,
111
+ ...(review ? [review] : []),
112
+ ...(skillsOff ? [skillsOff] : []),
113
+ "",
114
+ "Capabilities:",
115
+ `- Cognitive Routing: ${publicCognitiveRoutingStatus(capabilityState?.cognitiveRouting, cognitiveRoutingRuntime)}`,
116
+ `- Tool Execution: ${publicCapabilityStatus(capabilityState?.toolExecution)}`,
117
+ ...(capabilityState?.messaging?.enabled
118
+ ? [`- Messaging: ${publicCapabilityStatus(capabilityState.messaging)}`]
119
+ : []),
120
+ "",
121
+ "Cognitive Routing:",
122
+ `- Control: \`${control}\``,
123
+ // Under Automatic control the routing Runtime State owns the active profile, so switches do not churn this state.
124
+ ...(control === "automatic" ? [] : [`- Profile: \`${profile}\``]),
125
+ `- Delegation: \`${cognitiveRoutingRuntime?.delegation ?? capabilityState?.cognitiveRouting?.delegation ?? "executor"}\``,
126
+ `- Projection: \`${projectionMode}\``,
127
+ ...(options.skills?.length ? ["", `Freeflow skills read in this context: ${options.skills.join(", ")}`] : []),
128
+ ...(options.taskMemory?.length ? ["", ...options.taskMemory] : []),
129
+ ].join("\n"),
130
+ display: false,
131
+ details: { source: "provider-request-runtime-state" },
132
+ };
133
+ }
134
+ function withoutFreeflowRuntimeState(messages) {
135
+ return (Array.isArray(messages) ? messages : []).filter(
136
+ (message) =>
137
+ message?.customType !== FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE &&
138
+ message?.customType !== COGNITIVE_ROUTING_RUNTIME_STATE_MESSAGE_TYPE,
139
+ );
140
+ }
141
+ function firstUserMessageIndex(messages) {
142
+ for (let index = 0; index < messages.length; index += 1) {
143
+ if (messages[index]?.role === "user") return index;
144
+ }
145
+ return -1;
146
+ }
147
+ function insertRuntimeStateBeforeFirstUser(messages, runtimeState) {
148
+ const firstUserIndex = firstUserMessageIndex(messages);
149
+ if (firstUserIndex < 0) return [...messages, runtimeState];
150
+ return [...messages.slice(0, firstUserIndex), runtimeState, ...messages.slice(firstUserIndex)];
151
+ }
152
+ export function withFreeflowRuntimeState(
153
+ messages,
154
+ capabilityState,
155
+ cognitiveRoutingRuntime = undefined,
156
+ freeflowContext = undefined,
157
+ options = {},
158
+ ) {
159
+ const source = Array.isArray(messages) ? messages : [];
160
+ const runtimeState = freeflowRuntimeStateMessage(capabilityState, cognitiveRoutingRuntime, freeflowContext, {
161
+ projectionFailure: options.projectionFailure,
162
+ taskMemory: options.taskMemory,
163
+ skills: options.skills,
164
+ });
165
+ const runtimeStateMessages = source.filter(
166
+ (message) =>
167
+ message?.customType === FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE ||
168
+ message?.customType === COGNITIVE_ROUTING_RUNTIME_STATE_MESSAGE_TYPE,
169
+ );
170
+ const withoutRuntimeState = withoutFreeflowRuntimeState(source);
171
+ const expectedRuntimeStateIndex = firstUserMessageIndex(withoutRuntimeState);
172
+ const runtimeStateIndex = source.findIndex((message) => message?.customType === FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE);
173
+ const unchanged =
174
+ options.force !== true &&
175
+ runtimeStateMessages.length === 1 &&
176
+ runtimeStateMessages[0]?.customType === FREEFLOW_RUNTIME_STATE_MESSAGE_TYPE &&
177
+ runtimeStateMessages[0]?.content === runtimeState.content &&
178
+ runtimeStateIndex === (expectedRuntimeStateIndex < 0 ? withoutRuntimeState.length : expectedRuntimeStateIndex);
179
+ if (unchanged) return source;
180
+ if (options.anchor) return insertAnchoredRuntimeState(withoutRuntimeState, runtimeState, options.anchor);
181
+ return insertRuntimeStateBeforeFirstUser(withoutRuntimeState, runtimeState);
182
+ }
183
+ // Unchanged state keeps its position so the cached prefix survives; changed state is placed before the
184
+ // latest user message so earlier input is not rewritten, and then stays at that position.
185
+ function insertAnchoredRuntimeState(messages, runtimeState, anchor) {
186
+ let index;
187
+ if (anchor.content === runtimeState.content && anchor.index !== undefined && anchor.index <= messages.length)
188
+ index = anchor.index;
189
+ else if (anchor.content === undefined) {
190
+ const first = firstUserMessageIndex(messages);
191
+ index = first < 0 ? messages.length : first;
192
+ } else {
193
+ let latest = messages.length;
194
+ for (let i = messages.length - 1; i >= 0; i -= 1)
195
+ if (messages[i]?.role === "user") {
196
+ latest = i;
197
+ break;
198
+ }
199
+ index = latest;
200
+ }
201
+ anchor.content = runtimeState.content;
202
+ anchor.index = index;
203
+ return [...messages.slice(0, index), runtimeState, ...messages.slice(index)];
204
+ }