@hassangameryt/freeflow 0.7.1 → 0.7.2

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 (122) 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/README.md +28 -23
  6. package/capabilities/cognitive-routing/SKILL.md +94 -311
  7. package/command-surface.json +7 -1
  8. package/gemini-extension.json +1 -1
  9. package/package.json +4 -4
  10. package/pi-extension/dist/cognitive-routing-v2/budget.js +42 -0
  11. package/pi-extension/dist/cognitive-routing-v2/config.js +120 -0
  12. package/pi-extension/dist/cognitive-routing-v2/projection.js +321 -0
  13. package/pi-extension/dist/cognitive-routing-v2/render.js +231 -0
  14. package/pi-extension/dist/cognitive-routing-v2/runtime.js +1585 -0
  15. package/pi-extension/dist/cognitive-routing-v2/schemas.js +107 -0
  16. package/pi-extension/dist/cognitive-routing-v2/state.js +612 -0
  17. package/pi-extension/dist/cognitive-routing-v2/tools.js +91 -0
  18. package/pi-extension/dist/cognitive-routing-v2/types.js +44 -0
  19. package/pi-extension/dist/freeflow-context/tool.js +5 -0
  20. package/pi-extension/dist/index.js +279 -624
  21. package/pi-extension/dist/runtime/runtime-context.js +63 -13
  22. package/pi-extension/dist/session-sources/events.js +195 -0
  23. package/pi-extension/dist/session-sources/read-only-session.js +148 -0
  24. package/pi-extension/dist/session-sources/sources.js +233 -0
  25. package/pi-extension/dist/settings/settings-ui.js +44 -117
  26. package/pi-extension/src/cognitive-routing-v2/budget.ts +42 -0
  27. package/pi-extension/src/cognitive-routing-v2/config.ts +143 -0
  28. package/pi-extension/src/cognitive-routing-v2/projection.ts +365 -0
  29. package/pi-extension/src/cognitive-routing-v2/render.ts +256 -0
  30. package/pi-extension/src/cognitive-routing-v2/runtime.ts +1634 -0
  31. package/pi-extension/src/cognitive-routing-v2/schemas.ts +109 -0
  32. package/pi-extension/src/cognitive-routing-v2/state.ts +622 -0
  33. package/pi-extension/src/cognitive-routing-v2/tools.ts +93 -0
  34. package/pi-extension/src/cognitive-routing-v2/types.ts +222 -0
  35. package/pi-extension/src/freeflow-context/tool.ts +5 -0
  36. package/pi-extension/src/index.ts +285 -674
  37. package/pi-extension/src/runtime/runtime-context.ts +75 -14
  38. package/pi-extension/src/session-sources/events.ts +208 -0
  39. package/pi-extension/src/session-sources/read-only-session.ts +170 -0
  40. package/pi-extension/src/session-sources/sources.ts +263 -0
  41. package/pi-extension/src/settings/settings-ui.ts +54 -131
  42. package/pi-extension/tests/cognitive-routing-v2/communication.test.js +484 -0
  43. package/pi-extension/tests/cognitive-routing-v2/compaction-input.test.js +183 -0
  44. package/pi-extension/tests/cognitive-routing-v2/native.test.js +441 -0
  45. package/pi-extension/tests/cognitive-routing-v2/performance.test.js +87 -0
  46. package/pi-extension/tests/cognitive-routing-v2/persistence.test.js +245 -0
  47. package/pi-extension/tests/cognitive-routing-v2/projection.test.js +241 -0
  48. package/pi-extension/tests/cognitive-routing-v2/recovery.test.js +236 -0
  49. package/pi-extension/tests/cognitive-routing-v2/render.test.js +230 -0
  50. package/pi-extension/tests/cognitive-routing-v2/runtime.test.js +153 -0
  51. package/pi-extension/tests/cognitive-routing-v2/stabilization.test.js +521 -0
  52. package/pi-extension/tests/cognitive-routing-v2/state.test.js +275 -0
  53. package/pi-extension/tests/context-virtualization/extension.test.js +16 -0
  54. package/pi-extension/tests/fixtures/routing-native.js +188 -0
  55. package/pi-extension/tests/integration/mode-free-core.test.js +3 -2
  56. package/pi-extension/tests/integration/pi-extension.test.js +154 -37
  57. package/pi-extension/tests/integration/prompt-architecture.test.js +87 -6
  58. package/pi-extension/tests/integration/unaffected-regressions.test.js +77 -10
  59. package/plugin.json +1 -1
  60. package/runtime/prompts/cognitive-routing.md +4 -5
  61. package/runtime/prompts/core.md +51 -45
  62. package/runtime/prompts/interaction-contract.md +5 -5
  63. package/skills/action-selection/SKILL.md +57 -97
  64. package/skills/design-for-depth/SKILL.md +58 -193
  65. package/skills/design-for-depth/references/implementation-decisions.md +76 -0
  66. package/skills/diagnose-failure/SKILL.md +64 -196
  67. package/skills/discuss/SKILL.md +64 -123
  68. package/skills/discuss/references/discussion-continuity.md +7 -3
  69. package/skills/execute-work/SKILL.md +69 -88
  70. package/skills/execute-work/references/execute-work-edges.md +9 -3
  71. package/skills/handoff/SKILL.md +44 -54
  72. package/skills/handoff/references/handoff-templates.md +15 -6
  73. package/skills/review-artifact/SKILL.md +80 -127
  74. package/skills/review-artifact/references/independent-artifact-reviewer-contract.md +1 -1
  75. package/skills/review-work/SKILL.md +65 -115
  76. package/skills/review-work/references/independent-work-reviewer-contract.md +1 -1
  77. package/skills/simplify-code/SKILL.md +47 -100
  78. package/skills/track-work/SKILL.md +128 -119
  79. package/skills/track-work/references/working-record-format.md +14 -2
  80. package/skills/verify-work/SKILL.md +58 -62
  81. package/skills/verify-work/references/integration-evidence.md +4 -2
  82. package/skills/verify-work/references/test-design.md +89 -0
  83. package/skills/workflow/SKILL.md +73 -119
  84. package/skills/write-plan/SKILL.md +46 -77
  85. package/skills/write-plan/references/plan-shapes.md +5 -5
  86. package/skills/write-spec/SKILL.md +51 -63
  87. package/skills/write-spec/references/artifact-standards.md +2 -2
  88. package/skills/write-spec/references/decision-records.md +3 -2
  89. package/skills/write-spec/references/spec-shapes.md +15 -0
  90. package/pi-extension/dist/cognitive-routing/commands.js +0 -96
  91. package/pi-extension/dist/cognitive-routing/config.js +0 -232
  92. package/pi-extension/dist/cognitive-routing/controller.js +0 -1292
  93. package/pi-extension/dist/cognitive-routing/history.js +0 -451
  94. package/pi-extension/dist/cognitive-routing/host.js +0 -188
  95. package/pi-extension/dist/cognitive-routing/pi-routing-session.js +0 -414
  96. package/pi-extension/dist/cognitive-routing/pi-session-control.js +0 -320
  97. package/pi-extension/dist/cognitive-routing/runtime.js +0 -43
  98. package/pi-extension/dist/cognitive-routing/tool.js +0 -212
  99. package/pi-extension/dist/cognitive-routing/types.js +0 -6
  100. package/pi-extension/src/cognitive-routing/commands.ts +0 -129
  101. package/pi-extension/src/cognitive-routing/config.ts +0 -303
  102. package/pi-extension/src/cognitive-routing/controller.ts +0 -1628
  103. package/pi-extension/src/cognitive-routing/history.ts +0 -650
  104. package/pi-extension/src/cognitive-routing/host.ts +0 -266
  105. package/pi-extension/src/cognitive-routing/pi-routing-session.ts +0 -538
  106. package/pi-extension/src/cognitive-routing/pi-session-control.ts +0 -444
  107. package/pi-extension/src/cognitive-routing/runtime.ts +0 -57
  108. package/pi-extension/src/cognitive-routing/tool.ts +0 -273
  109. package/pi-extension/src/cognitive-routing/types.ts +0 -89
  110. package/pi-extension/tests/cognitive-routing/commands.test.js +0 -134
  111. package/pi-extension/tests/cognitive-routing/controller.test.js +0 -1128
  112. package/pi-extension/tests/cognitive-routing/extension-lifecycle.test.js +0 -1142
  113. package/pi-extension/tests/cognitive-routing/history.test.js +0 -274
  114. package/pi-extension/tests/cognitive-routing/host-identity.test.js +0 -63
  115. package/pi-extension/tests/cognitive-routing/pi-normal-lifecycle.test.js +0 -434
  116. package/pi-extension/tests/cognitive-routing/pi-session-control.test.js +0 -174
  117. package/pi-extension/tests/cognitive-routing/pi-session-history.test.js +0 -91
  118. package/pi-extension/tests/cognitive-routing/profile-resolution.test.js +0 -279
  119. package/pi-extension/tests/cognitive-routing/tool.test.js +0 -230
  120. package/skills/tdd/SKILL.md +0 -143
  121. package/skills/tdd/references/test-design.md +0 -96
  122. /package/pi-extension/tests/{cognitive-routing/host-fixture.js → fixtures/pi-host.js} +0 -0
@@ -0,0 +1,143 @@
1
+ import { EFFORTS, PROFILES, canonical, isObject, type Effort, type Pair, type Profile } from "./types.js";
2
+ export type CognitiveRoutingProfileName = Profile;
3
+ export type CognitiveRoutingThinkingLevel = Effort;
4
+ export interface CognitiveRoutingProfile {
5
+ provider: string;
6
+ model: string;
7
+ thinking: Effort;
8
+ }
9
+ export interface CognitiveRoutingCapabilityState {
10
+ configured: boolean;
11
+ configValid: boolean;
12
+ enabled: boolean;
13
+ effective: boolean;
14
+ enabledSource: string;
15
+ projection: boolean;
16
+ projectionSource: string;
17
+ profiles: Partial<Record<Profile, CognitiveRoutingProfile>>;
18
+ profileSources: Partial<Record<Profile, string>>;
19
+ blockingReason: { code: string; message: string };
20
+ }
21
+ export const supportsCognitiveRoutingModelRegistry = (host: any) =>
22
+ typeof host?.modelRegistry?.find === "function" && typeof host?.modelRegistry?.getApiKeyAndHeaders === "function";
23
+ export const pairFromProfile = (profile: CognitiveRoutingProfile): Pair => ({
24
+ provider: profile.provider,
25
+ modelId: profile.model,
26
+ thinking: profile.thinking,
27
+ });
28
+ function parseLayer(raw: any): any {
29
+ if (raw === undefined) return {};
30
+ if (!isObject(raw) || Object.keys(raw).some((k) => !["enabled", "projection", "profiles"].includes(k)))
31
+ throw new Error(
32
+ "Routing requires the new enabled/projection/profiles schema; experimental legacy configuration is not migrated.",
33
+ );
34
+ for (const key of ["enabled", "projection"])
35
+ if (raw[key] !== undefined && typeof raw[key] !== "boolean") throw new Error(`${key} must be boolean.`);
36
+ if (raw.profiles !== undefined) {
37
+ if (!isObject(raw.profiles) || Object.keys(raw.profiles).some((k) => !PROFILES.includes(k as Profile)))
38
+ throw new Error("Profiles must be coordinator/executor.");
39
+ for (const p of Object.values(raw.profiles) as any[]) {
40
+ if (
41
+ !isObject(p) ||
42
+ Object.keys(p).some((k) => !["provider", "model", "thinking"].includes(k)) ||
43
+ typeof p.provider !== "string" ||
44
+ !p.provider.trim() ||
45
+ typeof p.model !== "string" ||
46
+ !p.model.trim() ||
47
+ !EFFORTS.includes(p.thinking)
48
+ )
49
+ throw new Error("Each profile requires provider, model, and supported thinking.");
50
+ }
51
+ }
52
+ return raw;
53
+ }
54
+ export async function resolveCognitiveRoutingState(
55
+ repository: any,
56
+ personal: any,
57
+ ctx: any,
58
+ ): Promise<CognitiveRoutingCapabilityState> {
59
+ const state: CognitiveRoutingCapabilityState = {
60
+ configured: repository?.cognitiveRouting !== undefined || personal?.cognitiveRouting !== undefined,
61
+ configValid: true,
62
+ enabled: false,
63
+ effective: false,
64
+ enabledSource: "default",
65
+ projection: false,
66
+ projectionSource: "default",
67
+ profiles: {},
68
+ profileSources: {},
69
+ blockingReason: { code: "disabled", message: "Cognitive Routing is disabled." },
70
+ };
71
+ try {
72
+ for (const [source, raw] of [
73
+ ["repository", repository?.cognitiveRouting],
74
+ ["personal", personal?.cognitiveRouting],
75
+ ] as const) {
76
+ const layer = parseLayer(raw);
77
+ if (layer.enabled !== undefined) {
78
+ state.enabled = layer.enabled;
79
+ state.enabledSource = source;
80
+ }
81
+ if (layer.projection !== undefined) {
82
+ state.projection = layer.projection;
83
+ state.projectionSource = source;
84
+ }
85
+ for (const profile of PROFILES)
86
+ if (layer.profiles?.[profile]) {
87
+ state.profiles[profile] = layer.profiles[profile];
88
+ state.profileSources[profile] = source;
89
+ }
90
+ }
91
+ } catch (error) {
92
+ return {
93
+ ...state,
94
+ configValid: false,
95
+ blockingReason: { code: "config_invalid", message: error instanceof Error ? error.message : String(error) },
96
+ };
97
+ }
98
+ if (!state.enabled) return state;
99
+ if (!supportsCognitiveRoutingModelRegistry(ctx))
100
+ return {
101
+ ...state,
102
+ blockingReason: { code: "host_unsupported", message: "Required public Pi model registry is unavailable." },
103
+ };
104
+ for (const name of PROFILES) {
105
+ const profile = state.profiles[name];
106
+ if (!profile)
107
+ return { ...state, blockingReason: { code: "profile_missing", message: `Configure the ${name} profile.` } };
108
+ const model = ctx.modelRegistry.find(profile.provider, profile.model);
109
+ if (!model)
110
+ return { ...state, blockingReason: { code: "profile_unavailable", message: `Model unavailable for ${name}.` } };
111
+ const clamp = ctx.modelRegistry.clampThinkingLevel?.bind(ctx.modelRegistry);
112
+ const supported = !model.reasoning
113
+ ? profile.thinking === "off"
114
+ : clamp
115
+ ? clamp(model, profile.thinking) === profile.thinking
116
+ : model.thinkingLevelMap?.[profile.thinking] !== null &&
117
+ (!["xhigh", "max"].includes(profile.thinking) || model.thinkingLevelMap?.[profile.thinking] !== undefined);
118
+ if (!supported)
119
+ return {
120
+ ...state,
121
+ blockingReason: { code: "profile_clamped", message: `Requested ${name} effort is not supported exactly.` },
122
+ };
123
+ try {
124
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
125
+ if (!auth?.ok)
126
+ return {
127
+ ...state,
128
+ blockingReason: { code: "profile_unauthenticated", message: `Authentication unavailable for ${name}.` },
129
+ };
130
+ } catch {
131
+ return {
132
+ ...state,
133
+ blockingReason: { code: "profile_unauthenticated", message: `Authentication resolution failed for ${name}.` },
134
+ };
135
+ }
136
+ }
137
+ if (canonical(state.profiles.coordinator) === canonical(state.profiles.executor))
138
+ return {
139
+ ...state,
140
+ blockingReason: { code: "profiles_identical", message: "Configure distinct effective model/effort pairs." },
141
+ };
142
+ return { ...state, effective: true, blockingReason: { code: "", message: "" } };
143
+ }
@@ -0,0 +1,365 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { Sources, textRef, isTaskEvidence, type Source } from "../session-sources/sources.js";
3
+ import {
4
+ canonical,
5
+ emptySelection,
6
+ idFor,
7
+ requireCondition as check,
8
+ type Pair,
9
+ type Problem,
10
+ type Reservation,
11
+ type Selection,
12
+ type State,
13
+ type View,
14
+ } from "./types.js";
15
+
16
+ import { estimateRequest } from "./budget.js";
17
+
18
+ export interface PreparedView {
19
+ warnings: Problem[];
20
+ ready: boolean;
21
+ messages: any[];
22
+ problems: Problem[];
23
+ fullSources: Source[];
24
+ reservation?: Reservation;
25
+ estimatedTokens: number;
26
+ estimateMethod: string;
27
+ }
28
+ export function changeSelection(
29
+ prior: Selection,
30
+ input: { operation: "add" | "remove"; refs: string[]; reason?: string },
31
+ sources: Sources,
32
+ state: State,
33
+ ): Selection {
34
+ check(
35
+ Array.isArray(input.refs) &&
36
+ input.refs.length <= 64 &&
37
+ input.refs.every((r) => typeof r === "string" && r.length <= 512),
38
+ "invalid_refs",
39
+ );
40
+ if (input.operation === "remove")
41
+ check(
42
+ typeof input.reason === "string" && input.reason.trim() && input.reason.length <= 2048,
43
+ "withdrawal_reason_required",
44
+ );
45
+ const next = structuredClone(prior);
46
+
47
+ for (const ref of new Set(input.refs)) {
48
+ const existed = next.selected.includes(ref) || next.unresolved.some((p) => p.ref === ref);
49
+ if (input.operation === "remove") {
50
+ next.unresolved = next.unresolved.filter((p) => p.ref !== ref);
51
+ next.selected = next.selected.filter((r) => r !== ref);
52
+ if (existed) next.withdrawals.push({ ref, reason: input.reason! });
53
+ continue;
54
+ }
55
+ const problem = prior.selected.includes(ref) ? sources.eligible(ref, state) : sources.selectionProblem(ref, state);
56
+ const index = next.unresolved.findIndex((p) => p.ref === ref);
57
+ if (problem) {
58
+ if (index < 0) next.unresolved.push(problem);
59
+ else next.unresolved[index] = problem;
60
+ } else {
61
+ if (index >= 0) next.unresolved.splice(index, 1);
62
+ if (!next.selected.includes(ref)) next.selected.push(ref);
63
+ }
64
+ }
65
+ if (canonical(next) === canonical(prior)) return prior;
66
+ next.revision++;
67
+ return next;
68
+ }
69
+ export function representationProblems(source: Source, model: any, structural = false): Problem[] {
70
+ const message = source.original?.message ?? source.message,
71
+ content = Array.isArray(source.message.content) ? source.message.content : [];
72
+ if (message.role === "assistant" && ["error", "aborted"].includes(message.stopReason))
73
+ return [
74
+ {
75
+ ref: source.ref,
76
+ code: "target_representation",
77
+ detail:
78
+ "Native compatibility conversion may omit failed/aborted assistant output; exact delivery is not promised.",
79
+ },
80
+ ];
81
+ if (content.some((b: any) => b.type === "image") && !model?.input?.includes("image"))
82
+ return [
83
+ { ref: source.ref, code: "target_representation", detail: "The receiving model does not support image input." },
84
+ ];
85
+ if (
86
+ !structural &&
87
+ !source.original &&
88
+ content.some((b: any) => b.type === "thinking" && (b.redacted || b.thinkingSignature)) &&
89
+ (message.provider !== model?.provider || message.model !== model?.id || message.api !== model?.api)
90
+ )
91
+ return [
92
+ {
93
+ ref: source.ref,
94
+ code: "target_representation",
95
+ 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.`,
96
+ },
97
+ ];
98
+ return [];
99
+ }
100
+ export function prepareView(options: {
101
+ messages: readonly any[];
102
+ sources: Sources;
103
+ state: State;
104
+ view: View;
105
+ projection: boolean;
106
+ model: any;
107
+ pair: Pair;
108
+ systemPrompt: string;
109
+ tools: readonly any[];
110
+ runtimeMessage: any;
111
+ instance: string;
112
+ preparingReturn?: string;
113
+ restoring?: boolean;
114
+ }): PreparedView {
115
+ const { sources, state } = options;
116
+ const associated = sources.associate(options.messages);
117
+ const selective = options.projection && options.view === "coordinator";
118
+ const assessment = state.assessment;
119
+ const attention = selective && assessment?.view === "suspended" && !options.restoring && !options.preparingReturn;
120
+ const handoffId = options.preparingReturn ?? (!attention ? assessment?.handoffId : undefined);
121
+ const handoff = handoffId ? state.handoffs.get(handoffId) : undefined;
122
+ const assignmentId = handoff?.assignmentId ?? state.assignmentId;
123
+ const current = assignmentId ? (state.selections.get(assignmentId) ?? emptySelection()) : emptySelection();
124
+ const required = new Set(selective && !attention && assignmentId ? current.selected : []);
125
+ const promised = handoff && state.reservations.get(handoff.id);
126
+ const admitted = new Set<string>();
127
+ if (selective)
128
+ for (const selection of state.selections.values()) for (const ref of selection.selected) admitted.add(ref);
129
+ // Accepted return receipts are communication, independent of selected task evidence.
130
+ // Their ordinary active occurrence survives closure; compaction still owns its lifetime.
131
+
132
+ const full = new Map<string, Source>();
133
+ const structural = new Map<string, Source>();
134
+ const problems: Problem[] = selective && !attention && assignmentId ? [...current.unresolved] : [];
135
+ for (const item of associated) {
136
+ if (!item.source) continue;
137
+ if (
138
+ !selective ||
139
+ item.source.producer !== "executor" ||
140
+ admitted.has(item.source.ref) ||
141
+ (item.source.reportHandoff && state.handoffs.has(item.source.reportHandoff))
142
+ )
143
+ full.set(item.source.ref, item.source);
144
+ const visible = sources.byRef.get(textRef(item.source.ref));
145
+ if (selective && visible && admitted.has(visible.ref)) full.set(visible.ref, visible);
146
+ }
147
+ for (const ref of required) {
148
+ if (sources.ambiguous.has(ref)) {
149
+ problems.push({
150
+ ref,
151
+ code: "ambiguous_occurrence",
152
+ detail: "The active representation cannot be associated with one canonical occurrence.",
153
+ });
154
+ continue;
155
+ }
156
+ const source = sources.byRef.get(ref),
157
+ error = sources.eligible(ref, state);
158
+ if (error) {
159
+ problems.push(error);
160
+ continue;
161
+ }
162
+ const expected =
163
+ promised && promised.selectionRevision === current.revision
164
+ ? promised.sources.find((s) => s.ref === ref)
165
+ : undefined;
166
+ if (expected && expected.bodyHash !== source!.hash) {
167
+ problems.push({
168
+ ref,
169
+ code: "source_changed",
170
+ detail: "The captured source differs from the prepared reservation.",
171
+ });
172
+ continue;
173
+ }
174
+ full.set(ref, source!);
175
+ }
176
+ // A selected result carries its complete native call group; siblings may be structural only.
177
+ for (const source of full.values()) {
178
+ const exchange = sources.exchange(source);
179
+ if (required.has(source.ref)) problems.push(...exchange.problems, ...representationProblems(source, options.model));
180
+ for (const sibling of exchange.sources) if (!full.has(sibling.ref)) structural.set(sibling.ref, sibling);
181
+ }
182
+ for (const source of structural.values())
183
+ if (source.message.role === "assistant" && required.size)
184
+ problems.push(...representationProblems(source, options.model, true));
185
+ const render = (source: Source) => {
186
+ const message = structuredClone(source.message);
187
+ if (source.message.role === "assistant" && !full.has(source.ref) && full.has(textRef(source.ref)))
188
+ message.content = message.content.filter((b: any) => b.type !== "text");
189
+ if (full.has(source.ref) || source.message.role !== "toolResult") return message;
190
+ return {
191
+ ...structuredClone(source.message),
192
+ content: [{ type: "text", text: "[Executor result omitted from this view]" }],
193
+ details: undefined,
194
+ };
195
+ };
196
+ // Insert resolved historical occurrences before the first later native occurrence, retaining
197
+ // opaque/common messages in their original order rather than moving user input wholesale.
198
+ const ordered = sources.ordered(new Map([...structural, ...full]).values());
199
+ const rank = new Map(options.sources.entries.map((entry, index) => [entry.id, index]));
200
+ const activeRefs = new Set(associated.flatMap((i) => (i.source ? [i.source.ref] : [])));
201
+ const historical = ordered.filter((s) => !activeRefs.has(s.ref));
202
+ const emitted = new Set<string>();
203
+ let messages: any[] = [];
204
+ const renderedSources = new Map<any, Source>();
205
+ let cursor = 0;
206
+ const emit = (source: Source) => {
207
+ if (source.original && full.has(source.original.ref)) return;
208
+ if (!emitted.has(source.ref)) {
209
+ const message = render(source);
210
+ messages.push(message);
211
+ renderedSources.set(message, source);
212
+ emitted.add(source.ref);
213
+ }
214
+ };
215
+ for (const item of associated) {
216
+ if (item.source) {
217
+ while (
218
+ cursor < historical.length &&
219
+ (rank.get(historical[cursor].entry.id) ?? 0) < (rank.get(item.source.entry.id) ?? 0)
220
+ )
221
+ emit(historical[cursor++]);
222
+ const visible = full.get(textRef(item.source.ref));
223
+ if (visible) emit(visible);
224
+ if (full.has(item.source.ref) || structural.has(item.source.ref)) emit(item.source);
225
+ } else messages.push(item.message);
226
+ }
227
+ while (cursor < historical.length) emit(historical[cursor++]);
228
+ const fullSources = [...full.values()];
229
+ // Stable provenance belongs with every represented occurrence, not a rolling
230
+ // catalog. Insert before whole exchanges, never between native calls/results.
231
+ const annotated: any[] = [];
232
+ for (let i = 0; i < messages.length;) {
233
+ const group = [messages[i++]];
234
+ while (i < messages.length && messages[i].role === "toolResult") group.push(messages[i++]);
235
+ const rows = group.flatMap((message) => {
236
+ const s = renderedSources.get(message);
237
+ if (!s) return [];
238
+ const representation = full.has(s.ref) ? "full" : "structural only; omitted result bodies are not evidence";
239
+ const selection =
240
+ s.producer === "executor" && isTaskEvidence(s) && full.has(s.ref)
241
+ ? "task evidence; selection checks apply"
242
+ : "not offered for new evidence selection";
243
+ return [
244
+ `${s.ref} | producer: ${s.producer === "common" ? "unknown/common (no observed routing profile)" : s.producer} | ${s.original ? "assistant-text" : s.message.role}${s.message.toolName ? ` | ${s.message.toolName}` : ""}${s.assignmentId ? ` | assignment: ${s.assignmentId}` : ""} | ${representation} | ${selection}${!s.original && full.has(s.ref) && sources.byRef.has(textRef(s.ref)) ? ` | visible text: ${textRef(s.ref)}` : ""}`,
245
+ ];
246
+ });
247
+ if (rows.length)
248
+ annotated.push({
249
+ role: "custom",
250
+ customType: "freeflow-routing-v2-refs",
251
+ display: false,
252
+ content: `Source provenance for the following message/exchange:\n${rows.join("\n")}`,
253
+ details: { routingInstance: options.instance },
254
+ timestamp: 0,
255
+ });
256
+ annotated.push(...group);
257
+ }
258
+ messages = annotated;
259
+ // Restore exact current communication only when its accepted occurrence is absent.
260
+ const a = state.assignmentId ? state.assignments.get(state.assignmentId) : undefined;
261
+ const report = handoff?.kind === "return" ? handoff : undefined;
262
+ const hasCommunication = (h: any, field: string, value: string, metadata: Record<string, any> = {}) =>
263
+ messages.some((m) => {
264
+ const matches = (payload: any) =>
265
+ payload?.[field] === value &&
266
+ Object.entries(metadata).every(([key, expected]) => canonical(payload?.[key]) === canonical(expected));
267
+ if (m.role === "assistant")
268
+ return m.content?.some((b: any) => b.type === "toolCall" && b.id === h.toolCallId && matches(b.arguments));
269
+ if (m.role !== "toolResult" || m.toolCallId !== h.toolCallId) return false;
270
+ return m.content?.some((b: any) => {
271
+ if (b.type !== "text") return false;
272
+ try {
273
+ return matches(JSON.parse(b.text));
274
+ } catch {
275
+ return false;
276
+ }
277
+ });
278
+ });
279
+ const restore = (kind: string, id: string, body: string) =>
280
+ messages.push({
281
+ role: "custom",
282
+ customType: "freeflow-routing-communication",
283
+ display: false,
284
+ content: `${kind} ${id}:\n${body}`,
285
+ timestamp: 0,
286
+ details: { routingInstance: options.instance },
287
+ });
288
+ if (a) {
289
+ const accepted = state.handoffs.get(a.delegateHandoffId);
290
+ if (accepted && !hasCommunication(accepted, "contract", a.contract))
291
+ restore("Current exact assignment", a.id, a.contract);
292
+ }
293
+ if (report) {
294
+ const metadata = { outcome: report.outcome, limitations: report.limitations };
295
+ const hasBody = hasCommunication(report, "report", report.text);
296
+ // Tool arguments establish accepted content but do not carry harness-assigned
297
+ // revision/lineage. Old receipts and partially retained calls need metadata too.
298
+ const complete = hasCommunication(report, "report", report.text, {
299
+ ...metadata,
300
+ reportRevision: report.reportRevision,
301
+ assignmentRef: `assignment:${report.assignmentId}`,
302
+ reportRef: `report:${report.id}:${report.reportRevision}`,
303
+ });
304
+ if (!complete)
305
+ restore(
306
+ "Saved report",
307
+ report.id,
308
+ `Producer: executor\nAssignment: assignment:${report.assignmentId}\nReport ref: report:${report.id}:${report.reportRevision}\nRevision: ${report.reportRevision}\nOutcome: ${report.outcome}\nLimitations: ${JSON.stringify(report.limitations)}${hasBody ? "\nReport text is present in its accepted native occurrence above." : `\nReport:\n${report.text}`}`,
309
+ );
310
+ }
311
+ messages.push(options.runtimeMessage);
312
+ const { estimatedTokens, maximumInputTokens, outputReserve, estimateMethod, warnings } = estimateRequest(
313
+ options.systemPrompt,
314
+ options.tools,
315
+ messages,
316
+ options.model,
317
+ );
318
+ if (warnings.length)
319
+ messages.push({
320
+ role: "custom",
321
+ customType: "freeflow-routing-budget",
322
+ display: false,
323
+ content: warnings.map((w) => w.detail).join("\n"),
324
+ timestamp: 0,
325
+ details: { routingInstance: options.instance },
326
+ });
327
+ if (!options.model?.contextWindow)
328
+ problems.push({ ref: "", code: "delivery_budget", detail: "Receiving model context capacity is unavailable." });
329
+ const reservation: Reservation | undefined =
330
+ handoff && selective
331
+ ? {
332
+ id: randomUUID(),
333
+ selectionRevision: current.revision,
334
+ receiver: "coordinator",
335
+ target: options.pair,
336
+ qualification: `native-structural:${options.model?.api ?? "unknown"}; serialized receipt unobserved`,
337
+ sources: [...required].flatMap((ref) => {
338
+ const source = sources.byRef.get(ref);
339
+ return source ? [{ ref, bodyHash: source.hash }] : [];
340
+ }),
341
+ maximumInputTokens,
342
+ outputReserve,
343
+ estimateMethod,
344
+ }
345
+ : undefined;
346
+ return {
347
+ warnings,
348
+ ready: problems.length === 0,
349
+ // Recorded usage describes a prior provider view, which may belong to the
350
+ // other profile. Pi must estimate this assembled view when allocating output.
351
+ // Normalize request metadata only; canonical usage/billing records stay intact.
352
+ messages: messages.map((message) => ({
353
+ ...message,
354
+ timestamp: Number.isFinite(message.timestamp) ? message.timestamp : 0,
355
+ ...(message.role === "assistant"
356
+ ? { usage: { ...message.usage, input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 } }
357
+ : {}),
358
+ })),
359
+ problems,
360
+ fullSources,
361
+ reservation,
362
+ estimatedTokens,
363
+ estimateMethod,
364
+ };
365
+ }