@hassangameryt/freeflow 0.7.3 → 0.8.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 (276) 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/.cursor-plugin/plugin.json +1 -1
  5. package/NOTICE +14 -0
  6. package/README.md +26 -31
  7. package/capabilities/cognitive-routing/SKILL.md +106 -161
  8. package/capabilities/cognitive-routing/references/both-mode.md +36 -0
  9. package/capabilities/cognitive-routing/references/executor-mode.md +48 -0
  10. package/capabilities/cognitive-routing/references/helper-mode.md +47 -0
  11. package/capabilities/compaction/SKILL.md +49 -0
  12. package/capabilities/compaction/references/summary-format.md +239 -0
  13. package/command-surface.json +4 -0
  14. package/gemini-extension.json +1 -1
  15. package/hooks/shared/runtime-context.mjs +28 -30
  16. package/licenses/Apache-2.0.txt +55 -0
  17. package/package.json +22 -9
  18. package/pi-extension/README.md +41 -0
  19. package/pi-extension/dist/cognitive-routing/assembler.js +393 -0
  20. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/config.js +5 -2
  21. package/pi-extension/dist/cognitive-routing/economics.js +45 -0
  22. package/pi-extension/dist/cognitive-routing/event-schema.js +388 -0
  23. package/pi-extension/dist/{session-sources/events.js → cognitive-routing/event-store.js} +103 -40
  24. package/pi-extension/dist/cognitive-routing/gate.js +241 -0
  25. package/pi-extension/dist/cognitive-routing/handlers.js +899 -0
  26. package/pi-extension/dist/cognitive-routing/handoffs.js +350 -0
  27. package/pi-extension/dist/cognitive-routing/model-control.js +467 -0
  28. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/projection.js +229 -56
  29. package/pi-extension/dist/cognitive-routing/provenance.js +81 -0
  30. package/pi-extension/dist/cognitive-routing/runtime.js +396 -0
  31. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/schemas.js +43 -7
  32. package/pi-extension/dist/cognitive-routing/session.js +221 -0
  33. package/pi-extension/dist/{session-sources → cognitive-routing}/sources.js +99 -85
  34. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/state.js +37 -378
  35. package/pi-extension/dist/cognitive-routing/status.js +80 -0
  36. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/tools.js +12 -12
  37. package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/types.js +5 -11
  38. package/pi-extension/dist/compaction/carry.js +191 -0
  39. package/pi-extension/dist/compaction/config.js +22 -0
  40. package/pi-extension/dist/compaction/controller.js +471 -0
  41. package/pi-extension/dist/compaction/harness.js +77 -0
  42. package/pi-extension/dist/compaction/results.js +158 -0
  43. package/pi-extension/dist/compaction/thresholds.js +35 -0
  44. package/pi-extension/dist/compaction/tool.js +57 -0
  45. package/pi-extension/dist/host/branch.js +13 -0
  46. package/pi-extension/dist/host/canonical.js +12 -0
  47. package/pi-extension/dist/host/catalog.js +77 -0
  48. package/pi-extension/dist/host/config.js +374 -0
  49. package/pi-extension/dist/host/projection-tags.js +60 -0
  50. package/pi-extension/dist/host/prompts.js +82 -0
  51. package/pi-extension/dist/{session-sources → host}/read-only-session.js +112 -1
  52. package/pi-extension/dist/{runtime → host}/request-history.js +121 -39
  53. package/pi-extension/dist/host/runtime-state.js +189 -0
  54. package/pi-extension/dist/{settings/settings-ui.js → host/settings/freeflow-command.js} +620 -410
  55. package/pi-extension/dist/{settings/settings-tui.js → host/settings/settings-view.js} +186 -73
  56. package/pi-extension/dist/host/staging.js +28 -0
  57. package/pi-extension/dist/host/status.js +101 -0
  58. package/pi-extension/dist/index.js +423 -173
  59. package/pi-extension/dist/provider-support/cache/anchor.js +21 -0
  60. package/pi-extension/dist/provider-support/cache/anthropic.js +102 -0
  61. package/pi-extension/dist/provider-support/cache/health.js +73 -0
  62. package/pi-extension/dist/provider-support/cache/index.js +58 -0
  63. package/pi-extension/dist/provider-support/cache/keepalive.js +210 -0
  64. package/pi-extension/dist/provider-support/cache/monitor.js +17 -0
  65. package/pi-extension/dist/provider-support/cache/openai-responses.js +48 -0
  66. package/pi-extension/dist/provider-support/effort.js +13 -0
  67. package/pi-extension/dist/provider-support/index.js +44 -3
  68. package/pi-extension/dist/provider-support/{astra → openai}/adapter.js +46 -29
  69. package/pi-extension/dist/provider-support/{astra → openai}/history.js +10 -8
  70. package/pi-extension/dist/provider-support/{astra → openai}/index.js +8 -4
  71. package/pi-extension/dist/provider-support/{astra → openai}/session-state.js +29 -38
  72. package/pi-extension/dist/provider-support/routes.js +17 -0
  73. package/pi-extension/dist/tool-execution/apply-patch/grammar.js +23 -0
  74. package/pi-extension/dist/tool-execution/apply-patch/match.js +38 -0
  75. package/pi-extension/dist/tool-execution/apply-patch/parser.js +177 -0
  76. package/pi-extension/dist/tool-execution/apply-patch/plan.js +201 -0
  77. package/pi-extension/dist/tool-execution/apply-patch/tool.js +84 -0
  78. package/pi-extension/dist/tool-execution/background.js +238 -0
  79. package/pi-extension/dist/tool-execution/bash-guard.js +23 -0
  80. package/pi-extension/dist/tool-execution/config.js +22 -0
  81. package/pi-extension/dist/tool-execution/edit-messages.js +120 -0
  82. package/pi-extension/dist/tool-execution/file-state.js +138 -0
  83. package/pi-extension/dist/tool-execution/file-tracking.js +143 -0
  84. package/pi-extension/dist/tool-execution/prompt.js +54 -0
  85. package/pi-extension/dist/tool-execution/tools.js +16 -0
  86. package/pi-extension/freeflow/README.md +9 -0
  87. package/plugin.json +1 -1
  88. package/runtime/prompts/cognitive-routing.md +4 -4
  89. package/runtime/prompts/core.md +22 -75
  90. package/runtime/prompts/interaction-contract.md +15 -8
  91. package/runtime/prompts/tool-execution.md +38 -0
  92. package/runtime/prompts/working-method.md +108 -0
  93. package/skills/action-selection/SKILL.md +39 -47
  94. package/skills/action-selection/references/trajectory-stalls.md +2 -0
  95. package/skills/bypass/SKILL.md +2 -2
  96. package/skills/commit-work/SKILL.md +31 -83
  97. package/skills/commit-work/references/git-state-edges.md +1 -1
  98. package/skills/commit-work/references/simple-push.md +2 -0
  99. package/skills/commit-work/references/staging-decisions.md +1 -1
  100. package/skills/decision-gate/SKILL.md +31 -50
  101. package/skills/design-for-depth/SKILL.md +44 -53
  102. package/skills/design-for-depth/references/design-pressure-signals.md +46 -144
  103. package/skills/design-for-depth/references/implementation-decisions.md +1 -1
  104. package/skills/design-for-depth/references/interface-design-loop.md +5 -36
  105. package/skills/design-for-depth/references/module-and-dependency-design.md +2 -32
  106. package/skills/design-for-depth/references/state-and-failure-boundaries.md +2 -13
  107. package/skills/diagnose-failure/SKILL.md +39 -24
  108. package/skills/diagnose-failure/references/diagnostic-loop-catalog.md +2 -0
  109. package/skills/diagnose-failure/references/flaky-and-performance-diagnosis.md +2 -2
  110. package/skills/discuss/SKILL.md +35 -11
  111. package/skills/discuss/references/discussion-continuity.md +7 -27
  112. package/skills/evaluate-skill/SKILL.md +49 -80
  113. package/skills/evaluate-skill/references/evaluation-definition-schema.md +35 -5
  114. package/skills/evaluate-skill/references/evaluation-design.md +14 -14
  115. package/skills/evaluate-skill/references/execution-and-evidence.md +26 -5
  116. package/skills/evaluate-skill/references/review-and-revision.md +3 -1
  117. package/skills/evaluate-skill/scripts/lib/definitions.mjs +49 -8
  118. package/skills/evaluate-skill/scripts/lib/pi.mjs +14 -7
  119. package/skills/evaluate-skill/scripts/lib/review.mjs +196 -0
  120. package/skills/evaluate-skill/scripts/lib/runner.mjs +45 -8
  121. package/skills/evaluate-skill/scripts/lib/sandbox.mjs +2 -0
  122. package/skills/evaluate-skill/scripts/lib/trials.mjs +103 -0
  123. package/skills/evaluate-skill/scripts/lib/view.mjs +67 -1
  124. package/skills/evaluate-skill/scripts/pi-command-tool.mjs +144 -0
  125. package/skills/evaluate-skill/scripts/pi-guard.mjs +30 -13
  126. package/skills/evaluate-skill/scripts/skill-eval.mjs +114 -34
  127. package/skills/execute-work/SKILL.md +41 -9
  128. package/skills/execute-work/references/code-practices.md +2 -0
  129. package/skills/execute-work/references/execute-work-edges.md +11 -1
  130. package/skills/handoff/SKILL.md +1 -1
  131. package/skills/handoff/references/handoff-templates.md +1 -1
  132. package/skills/review-artifact/SKILL.md +42 -41
  133. package/skills/review-artifact/references/adjudicate-artifact-review.md +1 -1
  134. package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +1 -1
  135. package/skills/review-work/SKILL.md +38 -32
  136. package/skills/review-work/references/adjudicate-work-review.md +1 -1
  137. package/skills/review-work/references/independent-work-reviewer-contract.md +1 -1
  138. package/skills/review-work/references/security-risk-lens.md +2 -4
  139. package/skills/setup-freeflow/SKILL.md +3 -1
  140. package/skills/setup-freeflow/references/activation-contract.md +7 -13
  141. package/skills/setup-freeflow/references/host-setup.md +3 -3
  142. package/skills/track-work/SKILL.md +113 -161
  143. package/skills/track-work/references/working-record-format.md +189 -350
  144. package/skills/track-work/scripts/lib/document.mjs +62 -6
  145. package/skills/track-work/scripts/lib/format.mjs +16 -1
  146. package/skills/track-work/scripts/lib/store.mjs +9 -8
  147. package/skills/track-work/scripts/lib/transitions.mjs +79 -4
  148. package/skills/track-work/scripts/working-record.mjs +34 -12
  149. package/skills/verify-work/SKILL.md +29 -20
  150. package/skills/verify-work/references/browser-runtime-evidence.md +1 -5
  151. package/skills/verify-work/references/integration-evidence.md +2 -0
  152. package/skills/verify-work/references/performance-evidence.md +3 -1
  153. package/skills/verify-work/references/test-design.md +3 -1
  154. package/skills/workflow/SKILL.md +65 -21
  155. package/skills/workflow/references/domain-skill-composition.md +5 -3
  156. package/skills/write-docs/SKILL.md +83 -0
  157. package/skills/write-docs/references/documentation-shapes.md +119 -0
  158. package/skills/write-docs/scripts/docs-check.mjs +139 -0
  159. package/skills/write-plan/SKILL.md +40 -40
  160. package/skills/write-plan/references/plan-shapes.md +1 -1
  161. package/skills/write-skill/SKILL.md +107 -147
  162. package/skills/write-skill/references/activation-boundaries.md +2 -0
  163. package/skills/write-skill/references/agent-first-instructions.md +22 -10
  164. package/skills/write-skill/references/progressive-disclosure.md +4 -2
  165. package/skills/write-skill/references/skill-dependency-graphs.md +2 -0
  166. package/skills/write-skill/scripts/lib/similarity.mjs +56 -0
  167. package/skills/write-skill/scripts/skill-author.mjs +18 -2
  168. package/skills/write-spec/SKILL.md +34 -41
  169. package/skills/write-spec/references/artifact-standards.md +1 -1
  170. package/skills/write-spec/references/decision-records.md +2 -0
  171. package/skills/write-spec/references/spec-shapes.md +1 -1
  172. package/capabilities/context-virtualization/SKILL.md +0 -103
  173. package/capabilities/conversation-history/SKILL.md +0 -53
  174. package/hooks/tests/check-host-adapters.test.mjs +0 -82
  175. package/hooks/tests/check-runtime-context-hook.sh +0 -212
  176. package/pi-extension/dist/cognitive-routing-v2/runtime.js +0 -2181
  177. package/pi-extension/dist/context-virtualization/commands.js +0 -89
  178. package/pi-extension/dist/context-virtualization/projector.js +0 -42
  179. package/pi-extension/dist/context-virtualization/runtime.js +0 -378
  180. package/pi-extension/dist/context-virtualization/state.js +0 -57
  181. package/pi-extension/dist/context-virtualization/types.js +0 -10
  182. package/pi-extension/dist/conversation-history/passages.js +0 -66
  183. package/pi-extension/dist/conversation-history/ranking.js +0 -105
  184. package/pi-extension/dist/conversation-history/runtime.js +0 -226
  185. package/pi-extension/dist/conversation-history/search.js +0 -56
  186. package/pi-extension/dist/conversation-history/types.js +0 -1
  187. package/pi-extension/dist/freeflow-context/resolver.js +0 -120
  188. package/pi-extension/dist/freeflow-context/runtime.js +0 -80
  189. package/pi-extension/dist/freeflow-context/source-projector.js +0 -95
  190. package/pi-extension/dist/freeflow-context/tool.js +0 -314
  191. package/pi-extension/dist/freeflow-context/types.js +0 -12
  192. package/pi-extension/dist/freeflow-context/visibility.js +0 -28
  193. package/pi-extension/dist/integrations/mcp-config.js +0 -29
  194. package/pi-extension/dist/runtime/runtime-context.js +0 -754
  195. package/pi-extension/dist/runtime/runtime-identity.js +0 -5
  196. package/pi-extension/dist/session-sources/provenance.js +0 -32
  197. package/pi-extension/dist/ui/text-component.js +0 -57
  198. package/pi-extension/src/cognitive-routing-v2/budget.ts +0 -42
  199. package/pi-extension/src/cognitive-routing-v2/config.ts +0 -173
  200. package/pi-extension/src/cognitive-routing-v2/projection.ts +0 -375
  201. package/pi-extension/src/cognitive-routing-v2/render.ts +0 -277
  202. package/pi-extension/src/cognitive-routing-v2/runtime.ts +0 -2241
  203. package/pi-extension/src/cognitive-routing-v2/schemas.ts +0 -180
  204. package/pi-extension/src/cognitive-routing-v2/state.ts +0 -839
  205. package/pi-extension/src/cognitive-routing-v2/tools.ts +0 -62
  206. package/pi-extension/src/cognitive-routing-v2/types.ts +0 -254
  207. package/pi-extension/src/context-virtualization/commands.ts +0 -111
  208. package/pi-extension/src/context-virtualization/projector.ts +0 -62
  209. package/pi-extension/src/context-virtualization/runtime.ts +0 -428
  210. package/pi-extension/src/context-virtualization/state.ts +0 -79
  211. package/pi-extension/src/context-virtualization/types.ts +0 -92
  212. package/pi-extension/src/conversation-history/passages.ts +0 -81
  213. package/pi-extension/src/conversation-history/ranking.ts +0 -155
  214. package/pi-extension/src/conversation-history/runtime.ts +0 -250
  215. package/pi-extension/src/conversation-history/search.ts +0 -79
  216. package/pi-extension/src/conversation-history/types.ts +0 -31
  217. package/pi-extension/src/freeflow-context/resolver.ts +0 -139
  218. package/pi-extension/src/freeflow-context/runtime.ts +0 -100
  219. package/pi-extension/src/freeflow-context/source-projector.ts +0 -106
  220. package/pi-extension/src/freeflow-context/tool.ts +0 -366
  221. package/pi-extension/src/freeflow-context/types.ts +0 -70
  222. package/pi-extension/src/freeflow-context/visibility.ts +0 -53
  223. package/pi-extension/src/index.ts +0 -390
  224. package/pi-extension/src/integrations/mcp-config.ts +0 -32
  225. package/pi-extension/src/provider-support/astra/adapter.ts +0 -108
  226. package/pi-extension/src/provider-support/astra/history.ts +0 -145
  227. package/pi-extension/src/provider-support/astra/index.ts +0 -12
  228. package/pi-extension/src/provider-support/astra/session-state.ts +0 -113
  229. package/pi-extension/src/provider-support/index.ts +0 -5
  230. package/pi-extension/src/runtime/request-history.ts +0 -243
  231. package/pi-extension/src/runtime/runtime-context.ts +0 -860
  232. package/pi-extension/src/runtime/runtime-identity.ts +0 -8
  233. package/pi-extension/src/session-sources/events.ts +0 -230
  234. package/pi-extension/src/session-sources/provenance.ts +0 -39
  235. package/pi-extension/src/session-sources/read-only-session.ts +0 -170
  236. package/pi-extension/src/session-sources/sources.ts +0 -334
  237. package/pi-extension/src/settings/settings-tui.ts +0 -501
  238. package/pi-extension/src/settings/settings-ui.ts +0 -1652
  239. package/pi-extension/src/ui/text-component.ts +0 -66
  240. package/pi-extension/tests/cache-reuse/history.test.js +0 -117
  241. package/pi-extension/tests/cache-reuse/native.test.js +0 -91
  242. package/pi-extension/tests/cache-reuse/settings.test.js +0 -211
  243. package/pi-extension/tests/cognitive-routing-v2/communication.test.js +0 -577
  244. package/pi-extension/tests/cognitive-routing-v2/compaction-input.test.js +0 -183
  245. package/pi-extension/tests/cognitive-routing-v2/delegation.test.js +0 -557
  246. package/pi-extension/tests/cognitive-routing-v2/native.test.js +0 -474
  247. package/pi-extension/tests/cognitive-routing-v2/performance.test.js +0 -87
  248. package/pi-extension/tests/cognitive-routing-v2/persistence.test.js +0 -300
  249. package/pi-extension/tests/cognitive-routing-v2/projection.test.js +0 -241
  250. package/pi-extension/tests/cognitive-routing-v2/recovery.test.js +0 -1034
  251. package/pi-extension/tests/cognitive-routing-v2/render.test.js +0 -244
  252. package/pi-extension/tests/cognitive-routing-v2/runtime.test.js +0 -423
  253. package/pi-extension/tests/cognitive-routing-v2/stabilization.test.js +0 -521
  254. package/pi-extension/tests/cognitive-routing-v2/state.test.js +0 -586
  255. package/pi-extension/tests/context-virtualization/extension.test.js +0 -775
  256. package/pi-extension/tests/context-virtualization/projector.test.js +0 -110
  257. package/pi-extension/tests/context-virtualization/runtime.test.js +0 -230
  258. package/pi-extension/tests/conversation-history/runtime.test.js +0 -98
  259. package/pi-extension/tests/conversation-history/search.test.js +0 -97
  260. package/pi-extension/tests/fixtures/pi-host.js +0 -4
  261. package/pi-extension/tests/fixtures/routing-native.js +0 -191
  262. package/pi-extension/tests/integration/mode-free-core.test.js +0 -220
  263. package/pi-extension/tests/integration/pi-extension.test.js +0 -1447
  264. package/pi-extension/tests/integration/prompt-architecture.test.js +0 -447
  265. package/pi-extension/tests/integration/unaffected-regressions.test.js +0 -478
  266. package/pi-extension/tests/provider-support/astra-boundaries.test.js +0 -75
  267. package/pi-extension/tests/provider-support/astra.test.js +0 -306
  268. package/pi-extension/tests/provider-support/cli.test.js +0 -92
  269. package/pi-extension/tests/provider-support/native.test.js +0 -183
  270. package/pi-extension/tests/settings/settings-tui.test.js +0 -243
  271. package/pi-extension/tsconfig.json +0 -16
  272. package/runtime/prompts/context-virtualization.md +0 -3
  273. package/runtime/prompts/conversation-history.md +0 -3
  274. package/skills/design-for-depth/references/software-design-philosophy.md +0 -202
  275. /package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/budget.js +0 -0
  276. /package/pi-extension/dist/{cognitive-routing-v2 → cognitive-routing}/render.js +0 -0
@@ -1,8 +1,9 @@
1
- import { annotateSources } from "../session-sources/provenance.js";
1
+ import { annotateSources } from "./provenance.js";
2
2
  import { randomUUID } from "node:crypto";
3
- import { textRef } from "../session-sources/sources.js";
4
- import { canonical, emptySelection, isWorkerProfile, requireCondition as check } from "./types.js";
3
+ import { bodyHash, deliveredSelection } from "./sources.js";
4
+ import { canonical, emptySelection, isWorkerProfile, PROFILES, requireCondition as check } from "./types.js";
5
5
  import { estimateRequest } from "./budget.js";
6
+ import { occurrenceIdentity, tagDerived } from "../host/projection-tags.js";
6
7
  export function changeSelection(prior, input, sources, state) {
7
8
  check(
8
9
  Array.isArray(input.refs) &&
@@ -38,9 +39,41 @@ export function changeSelection(prior, input, sources, state) {
38
39
  next.revision++;
39
40
  return next;
40
41
  }
41
- export function representationProblems(source, model, structural = false) {
42
- const message = source.original?.message ?? source.message,
43
- content = Array.isArray(source.message.content) ? source.message.content : [];
42
+ /**
43
+ * Profiles share history, not private reasoning, except where they would otherwise send the same request: the
44
+ * same model under the same view (projection off, or Helper and Executor on worker history). There shared
45
+ * reasoning keeps one prompt cache across effort switches and stays valid for providers that bind reasoning to
46
+ * its conversation. Unknown and pre-routing history keeps its native form.
47
+ */
48
+ function privateReasoning(source, view, projection, model) {
49
+ const producer = source.producer;
50
+ if (!PROFILES.includes(producer) || producer === view) return false;
51
+ const message = source.message;
52
+ const sameModel = message.provider === model?.provider && message.api === model?.api && message.model === model?.id;
53
+ const viewOf = (profile) => (!projection ? "shared" : isWorkerProfile(profile) ? "worker" : profile);
54
+ return !(sameModel && viewOf(producer) === viewOf(view));
55
+ }
56
+ /**
57
+ * Remove reasoning from another profile's turn. A provider may pair a call with the reasoning that produced
58
+ * it (OpenAI Responses `fc_` ids pair with `rs_` items), so such calls keep only their call id, as the host
59
+ * already does for another model's turns; `unpaired` carries the rename to the matching results.
60
+ */
61
+ function withoutReasoning(message, unpaired) {
62
+ if (!message.content.some((b) => b.type === "thinking")) return message;
63
+ return {
64
+ ...message,
65
+ content: message.content.flatMap((b) => {
66
+ if (b.type === "thinking") return [];
67
+ if (b.type !== "toolCall" || typeof b.id !== "string" || !b.id.includes("|")) return [b];
68
+ const id = b.id.split("|")[0];
69
+ unpaired.set(b.id, id);
70
+ return [{ ...b, id }];
71
+ }),
72
+ };
73
+ }
74
+ export function representationProblems(source, model) {
75
+ const message = source.message,
76
+ content = Array.isArray(message.content) ? message.content : [];
44
77
  if (message.role === "assistant" && ["error", "aborted"].includes(message.stopReason))
45
78
  return [
46
79
  {
@@ -54,22 +87,49 @@ export function representationProblems(source, model, structural = false) {
54
87
  return [
55
88
  { ref: source.ref, code: "target_representation", detail: "The receiving model does not support image input." },
56
89
  ];
57
- if (
58
- !structural &&
59
- !source.original &&
60
- content.some((b) => b.type === "thinking" && (b.redacted || b.thinkingSignature)) &&
61
- (message.provider !== model?.provider || message.model !== model?.id || message.api !== model?.api)
62
- )
63
- return [
64
- {
65
- ref: source.ref,
66
- code: "target_representation",
67
- detail: `Whole native signed content is not qualified across this model boundary. Inspect the explicit assistant-text source ${textRef(source.ref)} when visible text is the intended evidence.`,
68
- },
69
- ];
70
90
  return [];
71
91
  }
92
+ /**
93
+ * Renderings reused across requests, so each view message keeps one identity (request history then fingerprints it
94
+ * once) and nothing is cloned per request. Entries are immutable, so a rendering keyed by its entry object and variant
95
+ * never goes stale; a replaced entry is a different object. Cached messages are shared and must never be mutated.
96
+ */
97
+ export class ViewCache {
98
+ renderings = new WeakMap();
99
+ notes = new Map();
100
+ coordinatorVersions = new WeakMap();
101
+ }
102
+ /** Tests set FREEFLOW_FREEZE_VIEWS to make any later mutation of a shared rendering throw. */
103
+ const FREEZE = !!process.env.FREEFLOW_FREEZE_VIEWS;
104
+ function deepFreeze(value) {
105
+ if (value && typeof value === "object" && !Object.isFrozen(value)) {
106
+ Object.freeze(value);
107
+ for (const child of Object.values(value)) deepFreeze(child);
108
+ }
109
+ return value;
110
+ }
111
+ /** Messages normalized() produced, so normalizing a shared rendering again keeps it (and its identity) as it is. */
112
+ const NORMALIZED = new WeakSet();
113
+ /** Request metadata as Pi must see it in a routed view: a finite timestamp, and no recorded usage on assistants. */
114
+ function normalized(message) {
115
+ const finite = Number.isFinite(message?.timestamp);
116
+ if ((finite && message?.role !== "assistant") || NORMALIZED.has(message)) return message;
117
+ const result = {
118
+ ...message,
119
+ timestamp: finite ? message.timestamp : 0,
120
+ ...(message.role === "assistant"
121
+ ? { usage: { ...message.usage, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 } }
122
+ : {}),
123
+ };
124
+ NORMALIZED.add(result);
125
+ return result;
126
+ }
127
+ function shareRendering(message, identity) {
128
+ tagDerived(message, identity);
129
+ return FREEZE ? deepFreeze(message) : message;
130
+ }
72
131
  export function prepareView(options) {
132
+ const cache = options.cache ?? new ViewCache();
73
133
  const { sources, state } = options;
74
134
  const associated = sources.associate(options.messages);
75
135
  const selective = options.projection && options.view === "coordinator";
@@ -79,16 +139,19 @@ export function prepareView(options) {
79
139
  const handoff = handoffId ? state.handoffs.get(handoffId) : undefined;
80
140
  const assignmentId = handoff?.assignmentId ?? state.assignmentId;
81
141
  const current = assignmentId ? (state.selections.get(assignmentId) ?? emptySelection()) : emptySelection();
82
- const required = new Set(selective && !attention && assignmentId ? current.selected : []);
142
+ // Assistant messages (whole or `#text`) that older sessions selected are not delivered.
143
+ const delivered = (ref) => deliveredSelection(sources, ref);
144
+ const required = new Set(selective && !attention && assignmentId ? current.selected.filter(delivered) : []);
83
145
  const promised = handoff && state.reservations.get(handoff.id);
84
146
  const admitted = new Set();
85
147
  if (selective)
86
- for (const selection of state.selections.values()) for (const ref of selection.selected) admitted.add(ref);
148
+ for (const selection of state.selections.values())
149
+ for (const ref of selection.selected) if (delivered(ref)) admitted.add(ref);
87
150
  // Accepted return receipts are communication, independent of selected task evidence.
88
151
  // Their ordinary active occurrence survives closure; compaction still owns its lifetime.
89
152
  const full = new Map();
90
153
  const structural = new Map();
91
- const problems = selective && !attention && assignmentId ? [...current.unresolved] : [];
154
+ const problems = selective && !attention && assignmentId ? current.unresolved.filter((p) => delivered(p.ref)) : [];
92
155
  for (const item of associated) {
93
156
  if (!item.source) continue;
94
157
  if (
@@ -98,8 +161,6 @@ export function prepareView(options) {
98
161
  (item.source.reportHandoff && state.handoffs.has(item.source.reportHandoff))
99
162
  )
100
163
  full.set(item.source.ref, item.source);
101
- const visible = sources.byRef.get(textRef(item.source.ref));
102
- if (selective && visible && admitted.has(visible.ref)) full.set(visible.ref, visible);
103
164
  }
104
165
  for (const ref of required) {
105
166
  if (sources.ambiguous.has(ref)) {
@@ -130,6 +191,15 @@ export function prepareView(options) {
130
191
  }
131
192
  full.set(ref, source);
132
193
  }
194
+ // After a compaction, selected evidence is rebuilt from history only while it is required. Evidence the
195
+ // Coordinator already received this cycle stays once that ends, so its later requests extend the earlier ones.
196
+ if (selective)
197
+ for (const id of options.assessedSinceCompaction ?? [])
198
+ for (const ref of state.selections.get(id)?.selected ?? []) {
199
+ const source = sources.byRef.get(ref);
200
+ if (!full.has(ref) && source && delivered(ref) && !sources.ambiguous.has(ref) && !sources.eligible(ref, state))
201
+ full.set(ref, source);
202
+ }
133
203
  // A selected result carries its complete native call group; siblings may be structural only.
134
204
  for (const source of full.values()) {
135
205
  const exchange = sources.exchange(source);
@@ -138,30 +208,74 @@ export function prepareView(options) {
138
208
  }
139
209
  for (const source of structural.values())
140
210
  if (source.message.role === "assistant" && required.size)
141
- problems.push(...representationProblems(source, options.model, true));
211
+ problems.push(...representationProblems(source, options.model));
212
+ const unpaired = new Map();
213
+ // Rendering depends only on the entry and these facts, so a rendering is reused for the same variant.
142
214
  const render = (source) => {
143
- const message = structuredClone(source.message);
144
- if (source.message.role === "assistant" && !full.has(source.ref) && full.has(textRef(source.ref)))
145
- message.content = message.content.filter((b) => b.type !== "text");
146
- if (full.has(source.ref) || source.message.role !== "toolResult") return message;
147
- return {
148
- ...structuredClone(source.message),
149
- content: [{ type: "text", text: "[Worker result omitted from this view]" }],
150
- details: undefined,
151
- };
215
+ const role = source.message.role;
216
+ const withheld = role === "assistant" && privateReasoning(source, options.view, options.projection, options.model);
217
+ // A structural worker envelope keeps only its calls for the selected results; worker narration is never evidence.
218
+ const structuralWorker =
219
+ role === "assistant" && selective && isWorkerProfile(source.producer) && !full.has(source.ref);
220
+ const omitted = role === "toolResult" && !full.has(source.ref);
221
+ const renamed = role === "toolResult" ? unpaired.get(source.message.toolCallId) : undefined;
222
+ const variant = `${withheld ? 1 : 0}${structuralWorker ? 1 : 0}${omitted ? 1 : 0}${renamed === undefined ? "" : `:${renamed}`}`;
223
+ let variants = cache.renderings.get(source.entry);
224
+ if (!variants) cache.renderings.set(source.entry, (variants = new Map()));
225
+ let rendering = variants.get(variant);
226
+ if (!rendering) {
227
+ const renames = new Map();
228
+ let message = structuredClone(source.message);
229
+ if (withheld) message = withoutReasoning(message, renames);
230
+ if (structuralWorker) message.content = message.content.filter((b) => b.type === "toolCall");
231
+ if (omitted)
232
+ message = {
233
+ ...message,
234
+ content: [{ type: "text", text: "[Worker result omitted from this view]" }],
235
+ details: undefined,
236
+ };
237
+ if (renamed !== undefined) message = { ...message, toolCallId: renamed };
238
+ rendering = {
239
+ message: shareRendering(normalized(message), `${source.entry.id}#${variant}`),
240
+ ...(renames.size ? { renames: [...renames] } : {}),
241
+ };
242
+ variants.set(variant, rendering);
243
+ }
244
+ // A reused assistant rendering still tells its results which call ids it unpaired.
245
+ for (const [from, to] of rendering.renames ?? []) unpaired.set(from, to);
246
+ return rendering.message;
152
247
  };
153
248
  // Insert resolved historical occurrences before the first later native occurrence, retaining
154
249
  // opaque/common messages in their original order rather than moving user input wholesale.
155
250
  const ordered = sources.ordered(new Map([...structural, ...full]).values());
156
- const rank = new Map(options.sources.entries.map((entry, index) => [entry.id, index]));
251
+ const rank = sources.rank;
252
+ // Worker evidence admitted after the Coordinator has seen later content is delivered where it was admitted,
253
+ // with its whole call group, so the Coordinator's already-sent prefix is extended rather than rewritten.
254
+ const shared = sources.nonWorkerBefore;
157
255
  const activeRefs = new Set(associated.flatMap((i) => (i.source ? [i.source.ref] : [])));
256
+ const deferredAt = new Map();
257
+ if (selective && (options.admissions || options.resumedAt !== undefined))
258
+ for (const source of full.values()) {
259
+ // An attention view omitted required evidence that is no longer in the active context, so after a
260
+ // resume that evidence is new to the Coordinator: deliver it where the assessment resumed.
261
+ const resumed =
262
+ options.resumedAt !== undefined && required.has(source.ref) && !activeRefs.has(source.ref)
263
+ ? options.resumedAt
264
+ : undefined;
265
+ const admitted = options.admissions?.get(source.ref);
266
+ const at = admitted === undefined ? resumed : Math.max(admitted, resumed ?? 0),
267
+ own = rank.get(source.entry.id) ?? 0;
268
+ if (at === undefined || at <= own || !isWorkerProfile(source.producer) || shared[at] <= shared[own + 1]) continue;
269
+ const group = sources.exchange(source).sources;
270
+ for (const member of group.length ? group : [source])
271
+ deferredAt.set(member.ref, Math.max(deferredAt.get(member.ref) ?? 0, at));
272
+ }
158
273
  const historical = ordered.filter((s) => !activeRefs.has(s.ref));
159
274
  const emitted = new Set();
160
275
  let messages = [];
161
276
  const renderedSources = new Map();
162
277
  let cursor = 0;
163
278
  const emit = (source) => {
164
- if (source.original && full.has(source.original.ref)) return;
165
279
  if (!emitted.has(source.ref)) {
166
280
  const message = render(source);
167
281
  messages.push(message);
@@ -169,21 +283,51 @@ export function prepareView(options) {
169
283
  emitted.add(source.ref);
170
284
  }
171
285
  };
286
+ const pending = [];
287
+ const place = (source) => (deferredAt.has(source.ref) ? pending.push(source) : emit(source));
288
+ const deliver = (limit) => {
289
+ pending.sort(
290
+ (a, b) =>
291
+ deferredAt.get(a.ref) - deferredAt.get(b.ref) || (rank.get(a.entry.id) ?? 0) - (rank.get(b.entry.id) ?? 0),
292
+ );
293
+ while (pending.length && deferredAt.get(pending[0].ref) <= limit) emit(pending.shift());
294
+ };
172
295
  for (const item of associated) {
173
296
  if (item.source) {
174
- while (
175
- cursor < historical.length &&
176
- (rank.get(historical[cursor].entry.id) ?? 0) < (rank.get(item.source.entry.id) ?? 0)
177
- )
178
- emit(historical[cursor++]);
179
- const visible = full.get(textRef(item.source.ref));
180
- if (visible) emit(visible);
181
- if (full.has(item.source.ref) || structural.has(item.source.ref)) emit(item.source);
297
+ const at = rank.get(item.source.entry.id) ?? 0;
298
+ deliver(at);
299
+ while (cursor < historical.length && (rank.get(historical[cursor].entry.id) ?? 0) < at)
300
+ place(historical[cursor++]);
301
+ if (full.has(item.source.ref) || structural.has(item.source.ref)) place(item.source);
182
302
  } else messages.push(item.message);
183
303
  }
184
- while (cursor < historical.length) emit(historical[cursor++]);
304
+ while (cursor < historical.length) place(historical[cursor++]);
305
+ deliver(Infinity);
185
306
  const fullSources = [...full.values()];
186
- messages = annotateSources(messages, renderedSources, new Set(full.keys()), sources, options.instance);
307
+ // The Coordinator only sees completed worker runs, so one note per run keeps its prefix stable.
308
+ messages = annotateSources(
309
+ messages,
310
+ renderedSources,
311
+ new Set(full.keys()),
312
+ sources,
313
+ options.instance,
314
+ selective,
315
+ cache.notes,
316
+ );
317
+ // A message may hold its own version for the Coordinator's selective view: Freeflow's carried context names the
318
+ // worker's copies there instead of repeating them, since the Coordinator receives evidence by selection.
319
+ if (selective)
320
+ messages = messages.map((message) => {
321
+ if (message?.role !== "custom" || typeof message.details?.coordinatorContent !== "string") return message;
322
+ let version = cache.coordinatorVersions.get(message);
323
+ if (!version) {
324
+ version = { ...message, content: message.details.coordinatorContent };
325
+ const identity = occurrenceIdentity(message);
326
+ if (identity) shareRendering(version, `${identity}#coordinator`);
327
+ cache.coordinatorVersions.set(message, version);
328
+ }
329
+ return version;
330
+ });
187
331
  // Restore exact current communication only when its accepted occurrence is absent.
188
332
  const a = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
189
333
  const baseReport = assessment
@@ -222,6 +366,30 @@ export function prepareView(options) {
222
366
  }
223
367
  });
224
368
  });
369
+ // Current receipts carry metadata plus a text hash, while the text itself stays in the call arguments.
370
+ const hashedCommunication = (h, field, value, metadata) =>
371
+ messages.some(
372
+ (m) =>
373
+ m.role === "assistant" &&
374
+ m.content?.some((b) => b.type === "toolCall" && b.id === h.toolCallId && b.arguments?.[field] === value),
375
+ ) &&
376
+ messages.some(
377
+ (m) =>
378
+ m.role === "toolResult" &&
379
+ m.toolCallId === h.toolCallId &&
380
+ m.content?.some((b) => {
381
+ if (b.type !== "text") return false;
382
+ try {
383
+ const payload = JSON.parse(b.text);
384
+ return (
385
+ payload?.[`${field}Sha256`] === bodyHash(value) &&
386
+ Object.entries(metadata).every(([key, expected]) => canonical(payload?.[key]) === canonical(expected))
387
+ );
388
+ } catch {
389
+ return false;
390
+ }
391
+ }),
392
+ );
225
393
  const restore = (kind, id, body) =>
226
394
  messages.push({
227
395
  role: "custom",
@@ -234,19 +402,29 @@ export function prepareView(options) {
234
402
  if (a) {
235
403
  const accepted = state.handoffs.get(a.delegateHandoffId);
236
404
  if (accepted && !hasCommunication(accepted, "contract", a.contract))
237
- restore("Current exact assignment", a.id, a.contract);
405
+ // Directly after the contract, so a contract asking for compaction does not read as still undone.
406
+ restore(
407
+ "Current exact assignment",
408
+ a.id,
409
+ options.compactedInAssignment === undefined
410
+ ? a.contract
411
+ : `${a.contract}\n\nCompaction: you compacted during this assignment, and cycle ${options.compactedInAssignment} began then. A compaction this contract asks for is done: continue with the rest of the contract, or return it with freeflow_return if compacting was all it asked.`,
412
+ );
238
413
  }
239
414
  if (baseReport) {
240
415
  const metadata = { outcome: baseReport.outcome, limitations: baseReport.limitations };
241
416
  const hasBody = hasCommunication(baseReport, "report", baseReport.text);
242
417
  // Tool arguments establish accepted content but do not carry harness-assigned
243
418
  // revision/lineage. Old receipts and partially retained calls need metadata too.
244
- const complete = hasCommunication(baseReport, "report", baseReport.text, {
419
+ const lineage = {
245
420
  ...metadata,
246
421
  reportRevision: baseReport.reportRevision,
247
422
  assignmentRef: `assignment:${baseReport.assignmentId}`,
248
423
  reportRef: `report:${baseReport.id}:${baseReport.reportRevision}`,
249
- });
424
+ };
425
+ const complete =
426
+ hasCommunication(baseReport, "report", baseReport.text, lineage) ||
427
+ hashedCommunication(baseReport, "report", baseReport.text, lineage);
250
428
  if (!complete)
251
429
  restore(
252
430
  "Saved report",
@@ -314,13 +492,8 @@ export function prepareView(options) {
314
492
  // Recorded usage describes a prior provider view, which may belong to the
315
493
  // other profile. Pi must estimate this assembled view when allocating output.
316
494
  // Normalize request metadata only; canonical usage/billing records stay intact.
317
- messages: messages.map((message) => ({
318
- ...message,
319
- timestamp: Number.isFinite(message.timestamp) ? message.timestamp : 0,
320
- ...(message.role === "assistant"
321
- ? { usage: { ...message.usage, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 } }
322
- : {}),
323
- })),
495
+ // Renderings are already normalized; other messages are copied only when they need it.
496
+ messages: messages.map(normalized),
324
497
  problems,
325
498
  fullSources,
326
499
  reservation,
@@ -0,0 +1,81 @@
1
+ import { isWorkerProfile } from "./types.js";
2
+ import { tagDerived } from "../host/projection-tags.js";
3
+ import { isTaskEvidence } from "./sources.js";
4
+ /**
5
+ * Follow each exchange with a note naming its attributed sources. With `mergeWorkerRuns`, consecutive
6
+ * exchanges from one worker assignment share a single note after the run. Use it only for a view that
7
+ * never sees a run still growing, or the note would move on every appended exchange.
8
+ */
9
+ export function annotateSources(
10
+ messages,
11
+ renderedSources,
12
+ full,
13
+ sources,
14
+ instance,
15
+ mergeWorkerRuns = false,
16
+ /** Notes kept across requests by content, so an unchanged note keeps one identity and is fingerprinted once. */
17
+ notes,
18
+ ) {
19
+ const annotated = [];
20
+ let pending;
21
+ const flush = () => {
22
+ if (pending?.rows.length) {
23
+ const content = `Source provenance for the preceding ${pending.exchanges > 1 ? "worker run" : "message/exchange"}:\n${pending.rows.join("\n")}`;
24
+ const key = `${instance}\u0000${content}`;
25
+ let note = notes?.get(key);
26
+ if (!note) {
27
+ note = {
28
+ role: "custom",
29
+ customType: "freeflow-routing-v2-refs",
30
+ display: false,
31
+ content,
32
+ details: { routingInstance: instance },
33
+ timestamp: 0,
34
+ };
35
+ if (notes) {
36
+ tagDerived(note, `refs:${key}`);
37
+ notes.set(key, note);
38
+ }
39
+ }
40
+ annotated.push(note);
41
+ }
42
+ pending = undefined;
43
+ };
44
+ for (let i = 0; i < messages.length;) {
45
+ const group = [messages[i++]];
46
+ while (i < messages.length && messages[i].role === "toolResult") group.push(messages[i++]);
47
+ const attributed = [];
48
+ const rows = group.flatMap((message) => {
49
+ const s = renderedSources.get(message);
50
+ // Only observed routing attribution is informative; unattributed rows would repeat "unknown" on
51
+ // every exchange, and omitting them keeps the prefix identical whether routing is on or off.
52
+ if (!s || s.producer === "common") return [];
53
+ attributed.push(s);
54
+ const representation = full.has(s.ref) ? "full" : "structural only; omitted result bodies are not evidence";
55
+ const selection =
56
+ isWorkerProfile(s.producer) && isTaskEvidence(s) && full.has(s.ref)
57
+ ? "task evidence; selection checks apply"
58
+ : "not offered for new evidence selection";
59
+ return [
60
+ `${s.ref} | producer: ${s.producer} | ${s.message.role}${s.message.toolName ? ` | ${s.message.toolName}` : ""}${s.assignmentId ? ` | assignment: ${s.assignmentId}` : ""} | ${representation} | ${selection}`,
61
+ ];
62
+ });
63
+ const keys = new Set(attributed.map((s) => `${s.producer}\u0000${s.assignmentId ?? ""}`));
64
+ const key =
65
+ mergeWorkerRuns && attributed.length && keys.size === 1 && attributed.every((s) => isWorkerProfile(s.producer))
66
+ ? [...keys][0]
67
+ : undefined;
68
+ if (key !== undefined && pending?.key === key) {
69
+ annotated.push(...group);
70
+ pending.rows.push(...rows);
71
+ pending.exchanges++;
72
+ continue;
73
+ }
74
+ flush();
75
+ annotated.push(...group);
76
+ pending = { key, rows, exchanges: 1 };
77
+ if (key === undefined) flush();
78
+ }
79
+ flush();
80
+ return annotated;
81
+ }