pi-fabric 0.109.4 → 0.109.5

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.
@@ -170,6 +170,7 @@ var createCustomMessage = (customType, content, display, details, timestamp) =>
170
170
  var sessionEntryToContextMessages = (entry) => {
171
171
  if (entry.type === "message") {
172
172
  const message = entry.message;
173
+ if (message.role === "system" && message.content == null) return [{ ...message, content: "" }];
173
174
  if ((message.role === "user" || message.role === "assistant" || message.role === "toolResult") && message.content == null) {
174
175
  return [{ ...message, content: [] }];
175
176
  }
@@ -184,7 +185,8 @@ var sessionEntryToContextMessages = (entry) => {
184
185
  return [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)];
185
186
  }
186
187
  if (entry.type === "compaction") {
187
- return [createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp)];
188
+ const summary = createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);
189
+ return entry.systemMessage ? [entry.systemMessage, summary] : [summary];
188
190
  }
189
191
  return [];
190
192
  };
@@ -213,17 +215,39 @@ var buildContextEntries = (entries, leafId, byId) => {
213
215
  if (entry.id === compaction.firstKeptEntryId) {
214
216
  foundFirstKept = true;
215
217
  }
216
- if (foundFirstKept) {
218
+ if (foundFirstKept && !(entry.type === "message" && entry.message.role === "system")) {
217
219
  contextEntries.push(entry);
218
220
  }
219
221
  }
220
222
  contextEntries.push(...path.slice(compactionIdx + 1));
221
223
  return contextEntries;
222
224
  };
225
+ var applyContextEdits = (entries) => {
226
+ const edits = /* @__PURE__ */ new Map();
227
+ for (const entry of entries) if (entry.type === "context_edit") edits.set(entry.targetId, entry);
228
+ return entries.map((entry) => {
229
+ const edit = edits.get(entry.id);
230
+ if (!edit) return entry;
231
+ const replacement = edit.replacement;
232
+ if (replacement === null) return {
233
+ type: "custom",
234
+ id: entry.id,
235
+ parentId: entry.parentId,
236
+ timestamp: entry.timestamp,
237
+ customType: "fabric.context-omission"
238
+ };
239
+ if (entry.type === "custom_message") return { ...entry, content: replacement.content };
240
+ if (entry.type !== "message") return entry;
241
+ const message = entry.message;
242
+ if (!["user", "assistant", "toolResult", "custom"].includes(message.role)) return entry;
243
+ const content = (message.role === "assistant" || message.role === "toolResult") && typeof replacement.content === "string" ? [{ type: "text", text: replacement.content }] : replacement.content;
244
+ return { ...entry, message: { ...message, content } };
245
+ });
246
+ };
223
247
  var buildSessionContext = (entries, leafId, byId) => {
224
248
  const path = buildSessionPath(entries, leafId, byId);
225
249
  const { thinkingLevel, model } = getSessionContextSettings(path);
226
- const messages = buildContextEntries(entries, leafId, byId).flatMap(sessionEntryToContextMessages);
250
+ const messages = applyContextEdits(buildContextEntries(entries, leafId, byId)).flatMap((entry, index) => entry.type === "compaction" && index > 0 ? [] : sessionEntryToContextMessages(entry));
227
251
  return { messages, thinkingLevel, model };
228
252
  };
229
253
 
@@ -1563,6 +1587,7 @@ var collectContextEntries = (entries, startIndex) => {
1563
1587
  for (let index = Math.max(0, startIndex); index < entries.length; index++) {
1564
1588
  const entry = entries[index];
1565
1589
  if (entry.type === "compaction") continue;
1590
+ if (isMessageEntry2(entry) && entry.message.role === "system") continue;
1566
1591
  if (entry.type === "custom_message" && !isPiCustomMessageEntry(entry)) continue;
1567
1592
  if (isMessageEntry2(entry) && isHiddenEmptyCustom(entry.message)) continue;
1568
1593
  const messages = contextMessages(entry);
@@ -1825,6 +1850,7 @@ var proposeCut = (branchEntries, options) => {
1825
1850
  );
1826
1851
  };
1827
1852
  var computeCut = (branchEntries, options) => {
1853
+ branchEntries = applyContextEdits(branchEntries);
1828
1854
  const proposed = proposeCut(branchEntries, options);
1829
1855
  if (!proposed.ok) return proposed;
1830
1856
  const live = collectLive(branchEntries);
@@ -1943,6 +1969,7 @@ var compileFabricSummary = (branchEntries, tokensBefore, enrichers = NO_BUILTIN_
1943
1969
  instructionError: instructions.error
1944
1970
  };
1945
1971
  }
1972
+ branchEntries = applyContextEdits(branchEntries);
1946
1973
  const cut = computeCut(
1947
1974
  branchEntries,
1948
1975
  budget ? { tokensBefore, budget } : void 0
@@ -2133,4 +2160,4 @@ export {
2133
2160
  compileFabricSummary,
2134
2161
  registerCompactionHook
2135
2162
  };
2136
- //# sourceMappingURL=chunk-I5ENWRUJ.js.map
2163
+ //# sourceMappingURL=chunk-2TJHOQGO.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/compaction/hook.ts", "../../src/core/token-math.ts", "../../src/core/session-context.ts", "../../src/compaction/threshold.ts", "../../src/compaction/enrichers.ts", "../../src/run-display.ts", "../../src/ui/fabric-title-hint.ts", "../../src/compaction/normalize.ts", "../../src/compaction/dialogue.ts", "../../src/compaction/projections.ts", "../../src/compaction/render.ts", "../../src/compaction/branch-summary.ts", "../../src/compaction/carry.ts"],
4
+ "sourcesContent": ["import {\n type CompactionResult,\n type ExtensionAPI,\n type ExtensionContext,\n type SessionBeforeCompactEvent,\n type SessionBeforeTreeEvent,\n type SessionEntry,\n} from \"@earendil-works/pi-coding-agent\";\nimport { acceptCompactionCut, acceptSummaryBounds } from \"../verified/policy.js\";\nimport { calculateContextTokens, DEFAULT_COMPACTION_SETTINGS, estimateTokens } from \"../core/token-math.js\";\nimport { applyContextEdits, buildSessionContext, sessionEntryToContextMessages } from \"../core/session-context.js\";\nimport { clipUtf8, MAX_SUMMARY_BYTES, utf8Bytes } from \"./bounds.js\";\nimport { modelCompactionKey } from \"./threshold.js\";\nimport { NO_BUILTIN_ENRICHERS, runEnrichers, type CompactionEnricher } from \"./enrichers.js\";\nimport { compileFabricBranchSummary } from \"./branch-summary.js\";\nimport {\n decodeCompactionInstructions,\n type CompactionInstructionDecodeError,\n type CompactionInstructionPolicy,\n} from \"./instructions.js\";\nimport { countErasedThinkingBlocks, isPiCustomMessageEntry, normalizeEntries } from \"./normalize.js\";\nimport {\n projectWithMetadata,\n type ProjectionOmittedCounts,\n type Sections,\n} from \"./projections.js\";\nimport { CARRY_FORWARD_HEADER, renderSummaryWithMetadata, SUMMARY_SECTIONS } from \"./render.js\";\nimport { carryRequestLines, latestCarryItems } from \"./carry.js\";\n\ntype CompactionEngine = \"pi\" | \"fabric\";\n\ninterface LiveEntry {\n entry: SessionEntry;\n branchIndex: number;\n turnBoundary: boolean;\n cutPoint: boolean;\n estimatedTokens: number;\n message?: {\n role?: unknown;\n content?: unknown;\n toolCallId?: unknown;\n };\n}\n\ninterface CallResultSpan {\n first: number;\n last: number;\n hasCall: boolean;\n hasResult: boolean;\n}\n\nexport interface FabricCompactionBudget {\n contextWindow?: number;\n targetContextRatio?: number;\n reserveTokens: number;\n keepRecentTokens: number;\n /** False for a new executor: source-model usage does not calibrate its context. */\n calibrateUsage?: boolean;\n}\n\ntype FabricCompactionBindingConstraint =\n | \"continuity\"\n | \"occupancy\"\n | \"reserve\"\n | \"reduction\";\n\nexport interface FabricCompactionBudgetDetails {\n strategy: \"adaptive\" | \"continuity\";\n contextWindow: number;\n targetContextRatio: number;\n targetContextTokens: number;\n reserveTokens: number;\n keepRecentTokens: number;\n rawTokensBefore: number;\n tokenScale: number;\n fixedOverheadTokens: number;\n retainedRawTokens: number;\n projectedTokensAfter: number;\n continuityTargetTokens?: number;\n occupancyCeilingTokens?: number;\n safeCeilingTokens?: number;\n reductionCeilingTokens?: number;\n rawTailTokenBudget?: number;\n bindingConstraint?: FabricCompactionBindingConstraint;\n}\n\ninterface ContinuityCutPlan {\n contextWindow: number;\n targetContextRatio: number;\n targetContextTokens: number;\n reserveTokens: number;\n keepRecentTokens: number;\n rawTokensBefore: number;\n tokenScale: number;\n fixedOverheadTokens: number;\n continuityTargetTokens: number;\n occupancyCeilingTokens: number;\n safeCeilingTokens: number;\n reductionCeilingTokens: number;\n rawTailTokenBudget: number;\n bindingConstraint: FabricCompactionBindingConstraint;\n}\n\nconst SUMMARY_RAW_TOKEN_BUDGET = Math.ceil(MAX_SUMMARY_BYTES / 4);\nconst HARD_CEILING_SAFETY_RATIO = 0.9;\nconst MAX_PRECOMPACTION_RATIO = 0.95;\n// An overflow rejection proves the provider's effective window is below the\n// failed request size, so the observation is stronger evidence than the\n// advertised (possibly proxy-inflated) model window. The haircut absorbs the\n// removed error message and estimator slop.\nconst OVERFLOW_WINDOW_EVIDENCE_RATIO = 0.9;\n\nconst isMessageEntry = (entry: SessionEntry): entry is Extract<SessionEntry, { type: \"message\" }> =>\n entry.type === \"message\";\n\nconst isHiddenEmptyCustom = (message: unknown): boolean => {\n if (!message || typeof message !== \"object\") return false;\n const candidate = message as { role?: unknown; display?: unknown; content?: unknown };\n if (candidate.role !== \"custom\" || candidate.display !== false) return false;\n const content = candidate.content;\n return content === \"\" || (Array.isArray(content) && content.length === 0);\n};\n\nconst toolCallIdsOf = (message: { content?: unknown }): string[] => {\n const content = message.content;\n if (!Array.isArray(content)) return [];\n const ids: string[] = [];\n for (const part of content) {\n if (!part || typeof part !== \"object\" || !(\"type\" in part) || part.type !== \"toolCall\") continue;\n const id = (part as { id?: unknown }).id;\n if (typeof id === \"string\") ids.push(id);\n }\n return ids;\n};\n\nconst contextMessages = (entry: SessionEntry): ReturnType<typeof sessionEntryToContextMessages> => {\n try {\n return sessionEntryToContextMessages(entry);\n } catch {\n return [];\n }\n};\n\nconst findLastCompaction = (entries: SessionEntry[]): { index: number; firstKeptEntryId: string } | undefined => {\n for (let index = entries.length - 1; index >= 0; index--) {\n const entry = entries[index]!;\n if (entry.type === \"compaction\") {\n return { index, firstKeptEntryId: entry.firstKeptEntryId };\n }\n }\n return undefined;\n};\n\nconst collectContextEntries = (entries: SessionEntry[], startIndex: number): LiveEntry[] => {\n const contextEntries: LiveEntry[] = [];\n for (let index = Math.max(0, startIndex); index < entries.length; index++) {\n const entry = entries[index]!;\n if (entry.type === \"compaction\") continue;\n // Prompt/tool checkpoints are replayed by Pi, not continuity content. They\n // must not create a fictitious prefix before the first user-message span.\n if (isMessageEntry(entry) && entry.message.role === \"system\") continue;\n if (entry.type === \"custom_message\" && !isPiCustomMessageEntry(entry)) continue;\n if (isMessageEntry(entry) && isHiddenEmptyCustom(entry.message)) continue;\n const messages = contextMessages(entry);\n if (messages.length === 0) continue;\n const roles = messages.map((message) => message.role);\n const rawMessage = isMessageEntry(entry)\n ? entry.message as NonNullable<LiveEntry[\"message\"]>\n : undefined;\n contextEntries.push({\n entry,\n branchIndex: index,\n turnBoundary: roles.some((role) =>\n role === \"user\"\n || role === \"custom\"\n || role === \"bashExecution\"\n || role === \"branchSummary\"\n || role === \"compactionSummary\"),\n cutPoint: roles.some((role) => role !== \"toolResult\"),\n estimatedTokens: messages.reduce((total, message) => total + estimateTokens(message), 0),\n ...(rawMessage ? { message: rawMessage } : {}),\n });\n }\n return contextEntries;\n};\n\nconst collectLive = (entries: SessionEntry[]): LiveEntry[] => {\n const last = findLastCompaction(entries);\n if (!last) return collectContextEntries(entries, 0);\n if (last.firstKeptEntryId) {\n const keptIndex = entries.findIndex((entry) => entry.id === last.firstKeptEntryId);\n if (keptIndex >= 0) return collectContextEntries(entries, keptIndex);\n }\n return collectContextEntries(entries, last.index + 1);\n};\n\nconst previousBoundaryAtOrBefore = (live: LiveEntry[], branchIndex: number): number => {\n for (let index = live.length - 1; index >= 0; index--) {\n const item = live[index]!;\n if (item.branchIndex <= branchIndex && item.turnBoundary) return index;\n }\n return -1;\n};\n\nconst lastBoundaryIndex = (live: LiveEntry[]): number => {\n for (let index = live.length - 1; index >= 0; index--) {\n if (live[index]!.turnBoundary) return index;\n }\n return -1;\n};\n\nconst callResultSpans = (entries: SessionEntry[]): Map<string, CallResultSpan> => {\n const spans = new Map<string, CallResultSpan>();\n const record = (id: string, index: number, kind: \"call\" | \"result\"): void => {\n if (!id) return;\n const span = spans.get(id) ?? {\n first: index,\n last: index,\n hasCall: false,\n hasResult: false,\n };\n span.first = Math.min(span.first, index);\n span.last = Math.max(span.last, index);\n if (kind === \"call\") span.hasCall = true;\n else span.hasResult = true;\n spans.set(id, span);\n };\n for (let index = 0; index < entries.length; index++) {\n const entry = entries[index]!;\n if (!isMessageEntry(entry)) continue;\n const message = entry.message as NonNullable<LiveEntry[\"message\"]>;\n for (const id of toolCallIdsOf(message)) record(id, index, \"call\");\n if (message.role === \"toolResult\" && typeof message.toolCallId === \"string\") {\n record(message.toolCallId, index, \"result\");\n }\n }\n return spans;\n};\n\nconst spanCrosses = (span: CallResultSpan, boundaryIndex: number): boolean =>\n span.hasCall\n && span.hasResult\n && span.first < boundaryIndex\n && span.last >= boundaryIndex;\n\nconst closureSafe = (spans: Map<string, CallResultSpan>, boundaryIndex: number): boolean =>\n [...spans.values()].every((span) => !spanCrosses(span, boundaryIndex));\n\nconst closeCut = (\n branchEntries: SessionEntry[],\n live: LiveEntry[],\n candidateLiveIndex: number,\n): number => {\n const spans = callResultSpans(branchEntries);\n let liveIndex = candidateLiveIndex;\n while (liveIndex > 0) {\n const boundaryIndex = live[liveIndex]!.branchIndex;\n let earliestCrossing = boundaryIndex;\n for (const span of spans.values()) {\n if (spanCrosses(span, boundaryIndex)) {\n earliestCrossing = Math.min(earliestCrossing, span.first);\n }\n }\n if (earliestCrossing === boundaryIndex) return liveIndex;\n const closed = previousBoundaryAtOrBefore(live, earliestCrossing);\n if (closed < 0 || closed >= liveIndex) return 0;\n liveIndex = closed;\n }\n return 0;\n};\n\nexport const rawContextTokens = (branchEntries: SessionEntry[]): number =>\n buildSessionContext(branchEntries).messages.reduce(\n (total, message) => total + estimateTokens(message),\n 0,\n );\n\ninterface UsageCheckpoint {\n rawTokens: number;\n contextTokens: number;\n}\n\nconst usageCheckpoints = (branchEntries: SessionEntry[]): UsageCheckpoint[] => {\n const lastCompaction = findLastCompaction(branchEntries);\n const startIndex = lastCompaction ? lastCompaction.index + 1 : 0;\n let rawTokens = lastCompaction\n ? rawContextTokens(branchEntries.slice(0, lastCompaction.index + 1))\n : 0;\n const checkpoints: UsageCheckpoint[] = [];\n for (let index = startIndex; index < branchEntries.length; index++) {\n for (const message of contextMessages(branchEntries[index]!)) {\n rawTokens += estimateTokens(message);\n if (message.role !== \"assistant\") continue;\n const contextTokens = calculateContextTokens(message.usage);\n if (Number.isFinite(contextTokens) && contextTokens > 0) {\n checkpoints.push({ rawTokens, contextTokens });\n }\n }\n }\n return checkpoints;\n};\n\n// Fit an upper affine envelope: context \u2248 fixed overhead + scale \u00D7 raw messages.\n// Only post-marker usage is comparable; the fallback treats all unexplained tokens as fixed.\nconst tokenCalibration = (\n branchEntries: SessionEntry[],\n tokensBefore: number,\n rawTokensBefore: number,\n): { tokenScale: number; fixedOverheadTokens: number } => {\n const minimumDelta = Math.max(4_096, Math.floor(rawTokensBefore * 0.1));\n const checkpoints = usageCheckpoints(branchEntries).filter(\n (checkpoint) => checkpoint.rawTokens < rawTokensBefore\n && checkpoint.contextTokens <= tokensBefore,\n );\n const slopes = checkpoints.flatMap((checkpoint) => {\n const rawDelta = rawTokensBefore - checkpoint.rawTokens;\n const contextDelta = tokensBefore - checkpoint.contextTokens;\n return rawDelta >= minimumDelta && contextDelta >= 0\n ? [contextDelta / rawDelta]\n : [];\n }).filter((slope) => Number.isFinite(slope) && slope >= 0);\n\n if (slopes.length === 0) {\n return {\n tokenScale: 1,\n fixedOverheadTokens: Math.max(0, tokensBefore - rawTokensBefore),\n };\n }\n\n const tokenScale = Math.max(1, ...slopes);\n const fixedOverheadTokens = Math.max(\n 0,\n tokensBefore - tokenScale * rawTokensBefore,\n ...checkpoints.map(\n (checkpoint) => checkpoint.contextTokens - tokenScale * checkpoint.rawTokens,\n ),\n );\n return { tokenScale, fixedOverheadTokens };\n};\n\nconst continuityTailLimit = (value: number | undefined): number =>\n value !== undefined && Number.isSafeInteger(value) && value >= 0\n ? value : DEFAULT_COMPACTION_SETTINGS.keepRecentTokens;\n\nconst continuityCutPlan = (\n branchEntries: SessionEntry[],\n tokensBefore: number,\n budget: FabricCompactionBudget,\n): ContinuityCutPlan | undefined => {\n if (typeof budget.contextWindow !== \"number\" || !Number.isFinite(budget.contextWindow) || budget.contextWindow <= 0\n || typeof budget.targetContextRatio !== \"number\" || !Number.isFinite(budget.targetContextRatio)) return undefined;\n const contextWindow = Math.floor(budget.contextWindow);\n const reserveTokens = Math.max(0, Math.floor(budget.reserveTokens));\n const keepRecentTokens = continuityTailLimit(budget.keepRecentTokens);\n const targetContextRatio = Math.max(0.25, Math.min(0.85, budget.targetContextRatio));\n const rawTokensBefore = rawContextTokens(branchEntries);\n const { tokenScale, fixedOverheadTokens } = budget.calibrateUsage === false\n ? { tokenScale: 1, fixedOverheadTokens: 0 }\n : tokenCalibration(branchEntries, tokensBefore, rawTokensBefore);\n const continuityTargetTokens = Math.max(1, Math.ceil(\n fixedOverheadTokens + (keepRecentTokens + SUMMARY_RAW_TOKEN_BUDGET) * tokenScale,\n ));\n const occupancyCeilingTokens = Math.max(1, Math.floor(contextWindow * targetContextRatio));\n const hardCeiling = Math.max(1, contextWindow - reserveTokens);\n const safeCeilingTokens = Math.max(1, Math.floor(hardCeiling * HARD_CEILING_SAFETY_RATIO));\n const reductionCeilingTokens = Math.max(1, Math.floor(tokensBefore * MAX_PRECOMPACTION_RATIO));\n const constraints: Array<{\n binding: FabricCompactionBindingConstraint;\n tokens: number;\n }> = [\n { binding: \"continuity\", tokens: continuityTargetTokens },\n { binding: \"occupancy\", tokens: occupancyCeilingTokens },\n { binding: \"reserve\", tokens: safeCeilingTokens },\n { binding: \"reduction\", tokens: reductionCeilingTokens },\n ];\n const targetContextTokens = Math.min(...constraints.map(({ tokens }) => tokens));\n const bindingConstraint = constraints.find(\n ({ tokens }) => tokens === targetContextTokens,\n )!.binding;\n const rawPostBudget = Math.max(\n 0,\n Math.floor((targetContextTokens - fixedOverheadTokens) / tokenScale),\n );\n return {\n contextWindow,\n targetContextRatio,\n targetContextTokens,\n reserveTokens,\n keepRecentTokens,\n rawTokensBefore,\n tokenScale,\n fixedOverheadTokens,\n continuityTargetTokens,\n occupancyCeilingTokens,\n safeCeilingTokens,\n reductionCeilingTokens,\n rawTailTokenBudget: Math.max(0, rawPostBudget - SUMMARY_RAW_TOKEN_BUDGET),\n bindingConstraint,\n };\n};\n\nexport type CutResult =\n | {\n ok: true;\n summarized: SessionEntry[];\n firstKeptEntryId: string;\n firstSummarizedEntryId: string;\n lastSummarizedEntryId: string;\n lastTimestamp: string;\n budget?: Omit<FabricCompactionBudgetDetails, \"projectedTokensAfter\">;\n }\n | { ok: false; reason: \"empty\" };\n\nconst boundary = (\n summarized: SessionEntry[],\n firstKeptEntryId: string,\n budget?: Omit<FabricCompactionBudgetDetails, \"projectedTokensAfter\">,\n): CutResult => {\n if (summarized.length === 0) return { ok: false, reason: \"empty\" };\n const first = summarized[0]!;\n const last = summarized.at(-1)!;\n return {\n ok: true,\n summarized,\n firstKeptEntryId,\n firstSummarizedEntryId: first.id,\n lastSummarizedEntryId: last.id,\n lastTimestamp: last.timestamp,\n ...(budget ? { budget } : {}),\n };\n};\n\nconst computeContinuityCut = (\n branchEntries: SessionEntry[],\n live: LiveEntry[],\n plan: ContinuityCutPlan | undefined,\n rawTailTokenBudget = plan?.rawTailTokenBudget ?? DEFAULT_COMPACTION_SETTINGS.keepRecentTokens,\n): CutResult => {\n const suffixTokens = new Array<number>(live.length + 1).fill(0);\n for (let index = live.length - 1; index >= 0; index--) {\n suffixTokens[index] = suffixTokens[index + 1]! + live[index]!.estimatedTokens;\n }\n const spans = callResultSpans(branchEntries);\n // Pi replays entries contiguously from firstKeptEntryId, including compaction markers.\n const previousCompactionIndex = findLastCompaction(branchEntries)?.index ?? -1;\n let cutIndex = live.length;\n for (let index = 1; index < live.length; index++) {\n const item = live[index]!;\n if (item.branchIndex <= previousCompactionIndex) continue;\n if (!item.cutPoint || suffixTokens[index]! > rawTailTokenBudget) continue;\n if (!closureSafe(spans, item.branchIndex)) continue;\n cutIndex = index;\n break;\n }\n const retainedRawTokens = suffixTokens[cutIndex] ?? 0;\n const details = plan ? {\n strategy: \"continuity\" as const,\n contextWindow: plan.contextWindow,\n targetContextRatio: plan.targetContextRatio,\n targetContextTokens: plan.targetContextTokens,\n reserveTokens: plan.reserveTokens,\n keepRecentTokens: plan.keepRecentTokens,\n rawTokensBefore: plan.rawTokensBefore,\n tokenScale: plan.tokenScale,\n fixedOverheadTokens: plan.fixedOverheadTokens,\n retainedRawTokens,\n continuityTargetTokens: plan.continuityTargetTokens,\n occupancyCeilingTokens: plan.occupancyCeilingTokens,\n safeCeilingTokens: plan.safeCeilingTokens,\n reductionCeilingTokens: plan.reductionCeilingTokens,\n rawTailTokenBudget: plan.rawTailTokenBudget,\n bindingConstraint: plan.bindingConstraint,\n } : undefined;\n if (cutIndex >= live.length) {\n return boundary(live.map((item) => item.entry), \"\", details);\n }\n return boundary(\n live.slice(0, cutIndex).map((item) => item.entry),\n live[cutIndex]!.entry.id,\n details,\n );\n};\n\nconst proposeCut = (\n branchEntries: SessionEntry[],\n options?: { tokensBefore: number; budget: FabricCompactionBudget },\n): CutResult => {\n const live = collectLive(branchEntries);\n if (live.length === 0) return { ok: false, reason: \"empty\" };\n\n if (options) {\n const plan = continuityCutPlan(branchEntries, options.tokensBefore, options.budget);\n if (plan) return computeContinuityCut(branchEntries, live, plan);\n }\n\n // Without a model window, retain legacy whole-turn continuity only when\n // it fits the raw-tail limit. Large autonomous turns use the same bounded,\n // closure-safe suffix selector without inventing provider budget metadata.\n const lastBoundary = lastBoundaryIndex(live);\n const closed = lastBoundary > 0 ? closeCut(branchEntries, live, lastBoundary) : 0;\n const keepRecentTokens = continuityTailLimit(options?.budget.keepRecentTokens);\n const tailTokens = live.slice(closed).reduce((sum, item) => sum + item.estimatedTokens, 0);\n if (tailTokens > keepRecentTokens) {\n return computeContinuityCut(branchEntries, live, undefined, keepRecentTokens);\n }\n const previousCompactionIndex = findLastCompaction(branchEntries)?.index ?? -1;\n if (closed <= 0 || live[closed]!.branchIndex <= previousCompactionIndex) {\n return boundary(live.map((item) => item.entry), \"\");\n }\n\n return boundary(\n live.slice(0, closed).map((item) => item.entry),\n live[closed]!.entry.id,\n );\n};\n\n/** Selection stays an optimized TypeScript producer. Every successful proposal,\n * including legacy and compact-all paths, passes the compiled acceptance gate. */\nexport const computeCut = (\n branchEntries: SessionEntry[],\n options?: { tokensBefore: number; budget: FabricCompactionBudget },\n): CutResult => {\n branchEntries = applyContextEdits(branchEntries);\n const proposed = proposeCut(branchEntries, options);\n if (!proposed.ok) return proposed;\n const live = collectLive(branchEntries);\n const kept = proposed.firstKeptEntryId\n ? live.findIndex((item) => item.entry.id === proposed.firstKeptEntryId)\n : live.length;\n if (kept < 0) return { ok: false, reason: \"empty\" };\n const boundaryIndex = live[kept]?.branchIndex ?? branchEntries.length;\n const retained = live.slice(kept).reduce((sum, item) => sum + item.estimatedTokens, 0);\n const budget = proposed.budget?.rawTailTokenBudget ?? continuityTailLimit(options?.budget.keepRecentTokens);\n if (!acceptCompactionCut({\n eligible: kept === live.length || live[kept]!.cutPoint,\n afterPrevious: boundaryIndex > (findLastCompaction(branchEntries)?.index ?? -1),\n retained, budget, boundary: boundaryIndex,\n }, callResultSpans(branchEntries).values())) return { ok: false, reason: \"empty\" };\n return proposed;\n};\n\ninterface FabricCompactionDetailsV1 {\n compactor: \"fabric\";\n version: 1;\n sections: string[];\n summarizedEntryRange: { first: string; last: string };\n sourceEntryCount: number;\n firstKeptEntryId: string;\n timestamp: string;\n}\n\ninterface EntryRange {\n first: string;\n last: string;\n}\n\nexport interface FabricCompactionDetailsV2 {\n compactor: \"fabric\";\n version: 2;\n sections: string[];\n coverage: {\n cumulativeSourceRange: EntryRange;\n liveCutRange: EntryRange;\n };\n counts: {\n branchEntries: number;\n cumulativeSourceEntries: number;\n sourceEvents: number;\n liveCutEntries: number;\n priorFabricV1: number;\n priorFabricV2: number;\n };\n omittedCounts: ProjectionOmittedCounts & { preserve: number; thinking?: number };\n instructionPolicy: CompactionInstructionPolicy;\n stableAddresses: {\n firstKeptEntryId: string;\n cumulativeSourceRange: EntryRange;\n recall: \"session-entry-id-range\";\n };\n budget?: FabricCompactionBudgetDetails;\n /** Carry-forward focus rendered into this summary (absent when the list is empty). */\n carry?: { count: number; renderedOmittedBytes: number };\n timestamp: string;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\nconst isEntryRange = (value: unknown): boolean =>\n isRecord(value) && typeof value.first === \"string\" && typeof value.last === \"string\";\n\nconst isStringArray = (value: unknown): boolean =>\n Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\nconst isFabricV1Details = (value: Record<string, unknown>): boolean =>\n isStringArray(value.sections)\n && isEntryRange(value.summarizedEntryRange)\n && typeof value.sourceEntryCount === \"number\"\n && Number.isFinite(value.sourceEntryCount)\n && typeof value.firstKeptEntryId === \"string\"\n && typeof value.timestamp === \"string\";\n\nconst hasFiniteNumbers = (value: Record<string, unknown>, keys: readonly string[]): boolean =>\n keys.every((key) => typeof value[key] === \"number\" && Number.isFinite(value[key]));\n\nconst isCompactionBudgetDetails = (value: unknown): boolean => {\n if (!isRecord(value) || (value.strategy !== \"adaptive\" && value.strategy !== \"continuity\")) {\n return false;\n }\n if (!hasFiniteNumbers(value, [\n \"contextWindow\",\n \"targetContextRatio\",\n \"targetContextTokens\",\n \"reserveTokens\",\n \"keepRecentTokens\",\n \"rawTokensBefore\",\n \"tokenScale\",\n \"fixedOverheadTokens\",\n \"retainedRawTokens\",\n \"projectedTokensAfter\",\n ])) {\n return false;\n }\n if (value.strategy === \"adaptive\") return true;\n return hasFiniteNumbers(value, [\n \"continuityTargetTokens\",\n \"occupancyCeilingTokens\",\n \"safeCeilingTokens\",\n \"reductionCeilingTokens\",\n \"rawTailTokenBudget\",\n ])\n && (\n value.bindingConstraint === \"continuity\"\n || value.bindingConstraint === \"occupancy\"\n || value.bindingConstraint === \"reserve\"\n || value.bindingConstraint === \"reduction\"\n );\n};\n\nconst isFabricV2Details = (value: Record<string, unknown>): boolean => {\n if (!isStringArray(value.sections) || !isRecord(value.coverage) || !isRecord(value.counts)) return false;\n if (!isRecord(value.omittedCounts) || !isRecord(value.instructionPolicy) || !isRecord(value.stableAddresses)) {\n return false;\n }\n const instructionModes = new Set([\"none\", \"plain\", \"typed-v1\", \"malformed-typed-prefix\"]);\n return isEntryRange(value.coverage.cumulativeSourceRange)\n && isEntryRange(value.coverage.liveCutRange)\n && hasFiniteNumbers(value.counts, [\n \"branchEntries\",\n \"cumulativeSourceEntries\",\n \"sourceEvents\",\n \"liveCutEntries\",\n \"priorFabricV1\",\n \"priorFabricV2\",\n ])\n && hasFiniteNumbers(value.omittedCounts, [\n \"goal\",\n \"files\",\n \"outstanding\",\n \"earlierTurns\",\n \"transcript\",\n \"preserve\",\n ])\n && (value.omittedCounts.activity === undefined\n || (typeof value.omittedCounts.activity === \"number\" && Number.isFinite(value.omittedCounts.activity)))\n && (value.omittedCounts.commits === undefined\n || (typeof value.omittedCounts.commits === \"number\" && Number.isFinite(value.omittedCounts.commits)))\n && (value.omittedCounts.thinking === undefined\n || (typeof value.omittedCounts.thinking === \"number\" && Number.isFinite(value.omittedCounts.thinking)))\n && (value.omittedCounts.dialogueBytes === undefined\n || (typeof value.omittedCounts.dialogueBytes === \"number\"\n && Number.isFinite(value.omittedCounts.dialogueBytes) && value.omittedCounts.dialogueBytes >= 0))\n && (value.instructionPolicy.renderedOmittedBytes === undefined\n || (typeof value.instructionPolicy.renderedOmittedBytes === \"number\"\n && Number.isFinite(value.instructionPolicy.renderedOmittedBytes) && value.instructionPolicy.renderedOmittedBytes >= 0))\n && typeof value.instructionPolicy.mode === \"string\"\n && instructionModes.has(value.instructionPolicy.mode)\n && typeof value.instructionPolicy.canonicalized === \"boolean\"\n && typeof value.instructionPolicy.truncated === \"boolean\"\n && hasFiniteNumbers(value.instructionPolicy, [\n \"sourceBytes\",\n \"preserveCount\",\n \"omittedPreserveCount\",\n ])\n && typeof value.stableAddresses.firstKeptEntryId === \"string\"\n && isEntryRange(value.stableAddresses.cumulativeSourceRange)\n && value.stableAddresses.recall === \"session-entry-id-range\"\n && (value.budget === undefined || isCompactionBudgetDetails(value.budget))\n && typeof value.timestamp === \"string\";\n};\n\nexport const fabricCompactionVersion = (details: unknown): 1 | 2 | undefined => {\n if (!isRecord(details) || details.compactor !== \"fabric\") return undefined;\n if (details.version === 1 && isFabricV1Details(details)) return 1;\n if (details.version === 2 && isFabricV2Details(details)) return 2;\n return undefined;\n};\n\nconst cumulativeSource = (\n branchEntries: SessionEntry[],\n firstKeptEntryId: string,\n): { entries: SessionEntry[]; prefixEntries: SessionEntry[]; events: ReturnType<typeof normalizeEntries>; range: EntryRange; timestamp: string } => {\n const boundaryIndex = firstKeptEntryId\n ? branchEntries.findIndex((entry) => entry.id === firstKeptEntryId)\n : branchEntries.length;\n const prefix = branchEntries.slice(0, boundaryIndex >= 0 ? boundaryIndex : branchEntries.length);\n const events = normalizeEntries(prefix);\n const contentEntryIds = new Set(events.map((event) => event.sourceEntryId));\n const entries = prefix.filter((entry) => contentEntryIds.has(entry.id));\n return {\n entries,\n prefixEntries: prefix,\n events,\n range: {\n first: entries[0]?.id ?? \"\",\n last: entries.at(-1)?.id ?? \"\",\n },\n timestamp: entries.at(-1)?.timestamp ?? \"\",\n };\n};\n\nconst priorFabricVersions = (entries: SessionEntry[]): { v1: number; v2: number } => {\n let v1 = 0;\n let v2 = 0;\n for (const entry of entries) {\n if (entry.type !== \"compaction\") continue;\n const version = fabricCompactionVersion((entry as SessionEntry & { details?: unknown }).details);\n if (version === 1) v1 += 1;\n if (version === 2) v2 += 1;\n }\n return { v1, v2 };\n};\n\nexport const compileFabricSummary = (\n branchEntries: SessionEntry[],\n tokensBefore: number,\n enrichers: readonly CompactionEnricher[] = NO_BUILTIN_ENRICHERS,\n customInstructions?: string,\n budget?: FabricCompactionBudget,\n): { compaction: CompactionResult<FabricCompactionDetailsV2> } | {\n cancel: true;\n reason: string;\n instructionError?: CompactionInstructionDecodeError;\n} => {\n const instructions = decodeCompactionInstructions(customInstructions);\n if (!instructions.ok) {\n return {\n cancel: true,\n reason: `fabric: ${instructions.error.code}: ${instructions.error.message}`,\n instructionError: instructions.error,\n };\n }\n // Native recovery appends context_edit omissions before invoking this hook.\n // Summaries and token/cut selection must use that same content-only view.\n branchEntries = applyContextEdits(branchEntries);\n const cut = computeCut(\n branchEntries,\n budget ? { tokensBefore, budget } : undefined,\n );\n if (!cut.ok) return { cancel: true, reason: \"fabric: nothing to compact\" };\n\n const source = cumulativeSource(branchEntries, cut.firstKeptEntryId);\n if (source.events.length === 0) return { cancel: true, reason: \"fabric: no raw cumulative source\" };\n // Only dialogue from the already-kept tail is needed to pair a summarized\n // proposal with its raw user reply. Never summarize the tail's tool history.\n const retainedDialogue = cut.firstKeptEntryId\n ? normalizeEntries(branchEntries.slice(source.prefixEntries.length).filter((entry) =>\n entry.type === \"message\" && (entry.message.role === \"user\" || entry.message.role === \"assistant\")))\n .filter((event) => event.kind === \"user\" || event.kind === \"assistantText\")\n : [];\n const projected = projectWithMetadata(source.events, retainedDialogue);\n const sections: Sections = projected.sections;\n runEnrichers(enrichers, source.events, sections);\n\n const carryLines = carryRequestLines(latestCarryItems(branchEntries));\n const rendered = renderSummaryWithMetadata(sections, {\n firstEntryId: source.range.first,\n lastEntryId: source.range.last,\n lastTimestamp: source.timestamp,\n requestLines: instructions.requestLines,\n ...(carryLines.length > 0 ? { carryLines } : {}),\n });\n const { summary } = rendered;\n const projectedTokensAfter = cut.budget\n ? Math.ceil(\n cut.budget.fixedOverheadTokens\n + (cut.budget.retainedRawTokens + Math.ceil(summary.length / 4))\n * cut.budget.tokenScale,\n )\n : undefined;\n const budgetDetails = cut.budget && projectedTokensAfter !== undefined\n ? { ...cut.budget, projectedTokensAfter }\n : undefined;\n // The maximum-summary reservation should make this unreachable unless fixed overhead alone\n // makes the target infeasible. Never persist an expanding or nominally unsafe result.\n if (!acceptSummaryBounds(\n utf8Bytes(summary), MAX_SUMMARY_BYTES,\n budgetDetails?.projectedTokensAfter ?? 0, budgetDetails?.targetContextTokens ?? 0,\n )) {\n return {\n cancel: true,\n reason: \"fabric: no deterministic summary fits the continuity context target\",\n };\n }\n const versions = priorFabricVersions(branchEntries);\n const sectionHeaders = SUMMARY_SECTIONS\n .filter(({ key }) => sections[key].length > 0)\n .map(({ header }) => header);\n const protectedHeaders = [\n ...(instructions.requestLines.length > 0 ? [\"[Compaction Request]\"] : []),\n ...(carryLines.length > 0 ? [CARRY_FORWARD_HEADER] : []),\n ];\n sectionHeaders.splice(sections.dialogue.length > 0 ? 1 : 0, 0, ...protectedHeaders);\n\n const details: FabricCompactionDetailsV2 = {\n compactor: \"fabric\",\n version: 2,\n sections: sectionHeaders,\n coverage: {\n cumulativeSourceRange: source.range,\n liveCutRange: {\n first: cut.firstSummarizedEntryId,\n last: cut.lastSummarizedEntryId,\n },\n },\n counts: {\n branchEntries: branchEntries.length,\n cumulativeSourceEntries: source.entries.length,\n sourceEvents: source.events.length,\n liveCutEntries: cut.summarized.length,\n priorFabricV1: versions.v1,\n priorFabricV2: versions.v2,\n },\n omittedCounts: {\n ...projected.omittedCounts,\n dialogueBytes: (projected.omittedCounts.dialogueBytes ?? 0) + rendered.dialogueOmittedBytes,\n preserve: instructions.policy.omittedPreserveCount,\n // Thinking parts never survive normalization into a rendered summary;\n // the structural count keeps that erasure auditable against the raw\n // prefix instead of letting deliberation vanish untracked.\n thinking: countErasedThinkingBlocks(source.prefixEntries),\n },\n instructionPolicy: {\n ...instructions.policy,\n truncated: instructions.policy.truncated || rendered.requestOmittedBytes > 0,\n renderedOmittedBytes: rendered.requestOmittedBytes,\n },\n stableAddresses: {\n firstKeptEntryId: cut.firstKeptEntryId,\n cumulativeSourceRange: source.range,\n recall: \"session-entry-id-range\",\n },\n ...(budgetDetails ? { budget: budgetDetails } : {}),\n ...(carryLines.length > 0\n ? { carry: { count: carryLines.length, renderedOmittedBytes: rendered.carryOmittedBytes } }\n : {}),\n timestamp: source.timestamp,\n };\n\n return {\n compaction: {\n summary,\n firstKeptEntryId: cut.firstKeptEntryId,\n tokensBefore,\n details,\n },\n };\n};\n\nexport interface CompactionHookOptions {\n getEngine: () => CompactionEngine;\n getTargetContextRatio?: () => number;\n getThresholdContextRatio?: (modelKey: string) => number | undefined;\n getThresholdTokens?: (modelKey: string) => number | undefined;\n /** `compaction.outputReserveTokens`; a breached reserve never defers Pi's threshold compaction. */\n getOutputReserveTokens?: () => number;\n /** Fabric deliberately left this compaction to another owner (pi-vcc sentinel/override). */\n onYield?: () => void;\n enrichers?: readonly CompactionEnricher[];\n}\n\nconst notifyInstructionError = (\n context: ExtensionContext | undefined,\n error: CompactionInstructionDecodeError,\n): void => {\n if (!context?.hasUI) return;\n context.ui.notify(clipUtf8(`Fabric compaction rejected: ${error.code}: ${error.message}`, 512), \"error\");\n};\n\nexport const registerCompactionHook = (pi: ExtensionAPI, options: CompactionHookOptions): void => {\n pi.on(\"session_before_compact\", (event: SessionBeforeCompactEvent, context: ExtensionContext) => {\n if (event.customInstructions === \"__pi_vcc__\") {\n options.onYield?.();\n return;\n }\n const { preparation, branchEntries } = event;\n const contextWindow = context?.model?.contextWindow;\n const modelKey = modelCompactionKey(context?.model);\n const outputReserveTokens = options.getOutputReserveTokens?.() ?? 0;\n // The headroom trigger is independent of model thresholds: once the\n // remaining window cannot hold the reserved output, Pi's threshold\n // compaction proceeds even below a configured Fabric threshold.\n const reserveBreached = event.reason === \"threshold\"\n && outputReserveTokens > 0\n && typeof contextWindow === \"number\"\n && contextWindow - preparation.tokensBefore < outputReserveTokens;\n const thresholdTokens = modelKey === undefined\n ? undefined\n : options.getThresholdTokens?.(modelKey);\n if (\n event.reason === \"threshold\"\n && !reserveBreached\n && typeof thresholdTokens === \"number\"\n && preparation.tokensBefore < thresholdTokens\n ) {\n return { cancel: true };\n }\n const threshold = modelKey === undefined || typeof thresholdTokens === \"number\"\n ? undefined\n : options.getThresholdContextRatio?.(modelKey);\n if (\n event.reason === \"threshold\"\n && !reserveBreached\n && typeof threshold === \"number\"\n && typeof contextWindow === \"number\"\n && preparation.tokensBefore / contextWindow < threshold\n ) {\n return { cancel: true };\n }\n if (options.getEngine() !== \"fabric\") return;\n const targetContextRatio = options.getTargetContextRatio?.();\n const settings = preparation.settings ?? DEFAULT_COMPACTION_SETTINGS;\n const tokensBefore = preparation.tokensBefore;\n const evidenceWindow = event.reason === \"overflow\"\n && typeof tokensBefore === \"number\"\n && Number.isFinite(tokensBefore)\n && tokensBefore > 0\n ? Math.max(1, Math.floor(tokensBefore * OVERFLOW_WINDOW_EVIDENCE_RATIO))\n : undefined;\n const advertisedWindow = typeof contextWindow === \"number\"\n && Number.isFinite(contextWindow)\n && contextWindow > 0\n ? contextWindow\n : undefined;\n const effectiveWindow = evidenceWindow === undefined\n ? advertisedWindow\n : advertisedWindow === undefined\n ? evidenceWindow\n : Math.min(advertisedWindow, evidenceWindow);\n const budget: FabricCompactionBudget = {\n ...(effectiveWindow !== undefined ? { contextWindow: effectiveWindow } : {}),\n ...(typeof targetContextRatio === \"number\" && Number.isFinite(targetContextRatio) ? { targetContextRatio } : {}),\n reserveTokens: settings.reserveTokens,\n keepRecentTokens: settings.keepRecentTokens,\n };\n const result = compileFabricSummary(\n branchEntries ?? [],\n preparation.tokensBefore,\n options.enrichers,\n event.customInstructions,\n budget,\n );\n if (\"cancel\" in result) {\n if (result.instructionError) {\n notifyInstructionError(context, result.instructionError);\n return { cancel: true };\n }\n if ((event as SessionBeforeCompactEvent & { _piVccOverriding?: unknown })._piVccOverriding) {\n options.onYield?.();\n return;\n }\n return { cancel: true };\n }\n (event as SessionBeforeCompactEvent & { _fabricCompaction?: boolean })._fabricCompaction = true;\n return { compaction: result.compaction };\n });\n\n pi.on(\"session_before_tree\", (event: SessionBeforeTreeEvent, context: ExtensionContext) => {\n if (options.getEngine() !== \"fabric\") return;\n const { preparation } = event;\n if (!preparation.userWantsSummary) return;\n // Pi's replacement mode delegates an arbitrary summarizer prompt. Fabric's\n // deterministic projections cannot execute it without pretending that it\n // is append-only context, so leave this explicit mode to the next/default handler.\n if (preparation.replaceInstructions === true) return;\n const instructions = decodeCompactionInstructions(preparation.customInstructions);\n if (!instructions.ok) {\n notifyInstructionError(context, instructions.error);\n return { cancel: true };\n }\n const compiled = compileFabricBranchSummary(\n preparation.entriesToSummarize,\n preparation.customInstructions,\n options.enrichers,\n preparation.oldLeafId,\n );\n if (!compiled) return;\n return { summary: compiled };\n });\n};\n", "// Local mirror of the token heuristics in pi 0.84.2\n// core/compaction/compaction.js. Kept identical so compaction projections\n// match the host's without importing the host package during extension load.\n\nconst ESTIMATED_IMAGE_CHARS = 4800;\n\nexport const DEFAULT_COMPACTION_SETTINGS = {\n enabled: true,\n reserveTokens: 16384,\n keepRecentTokens: 20000,\n} as const;\n\ninterface TokenContentPart {\n type: string;\n text?: string;\n thinking?: string;\n name?: string;\n arguments?: unknown;\n}\n\ntype TokenMessage = {\n role: string;\n content?: unknown;\n command?: unknown;\n output?: unknown;\n summary?: unknown;\n};\n\nconst contentParts = (content: unknown): readonly TokenContentPart[] => {\n if (typeof content !== \"string\") return (content ?? []) as readonly TokenContentPart[];\n return [];\n};\n\nconst estimateTextAndImageContentChars = (content: unknown): number => {\n if (typeof content === \"string\") {\n return content.length;\n }\n let chars = 0;\n for (const block of contentParts(content)) {\n if (block.type === \"text\" && block.text) {\n chars += block.text.length;\n } else if (block.type === \"image\") {\n chars += ESTIMATED_IMAGE_CHARS;\n }\n }\n return chars;\n};\n\nconst textLength = (value: unknown): number => (typeof value === \"string\" ? value.length : 0);\n\nexport const estimateTokens = (message: TokenMessage): number => {\n let chars = 0;\n switch (message.role) {\n case \"user\": {\n chars = estimateTextAndImageContentChars(message.content);\n return Math.ceil(chars / 4);\n }\n case \"assistant\": {\n for (const block of contentParts(message.content)) {\n if (block.type === \"text\") {\n chars += textLength(block.text);\n } else if (block.type === \"thinking\") {\n chars += textLength(block.thinking);\n } else if (block.type === \"toolCall\") {\n chars += textLength(block.name) + JSON.stringify(block.arguments).length;\n }\n }\n return Math.ceil(chars / 4);\n }\n case \"custom\":\n case \"toolResult\": {\n chars = estimateTextAndImageContentChars(message.content);\n return Math.ceil(chars / 4);\n }\n case \"bashExecution\": {\n chars = textLength(message.command) + textLength(message.output);\n return Math.ceil(chars / 4);\n }\n case \"branchSummary\":\n case \"compactionSummary\": {\n chars = textLength(message.summary);\n return Math.ceil(chars / 4);\n }\n }\n return 0;\n};\n\nexport const calculateContextTokens = (usage: unknown): number => {\n if (typeof usage !== \"object\" || usage === null) return 0;\n const record = usage as Record<string, unknown>;\n const totalTokens = record.totalTokens;\n // Host evaluates `usage.totalTokens || input + output + ...`; zero and\n // missing totals both fall through to the component sum.\n if (typeof totalTokens === \"number\" && totalTokens > 0) return totalTokens;\n const count = (value: unknown): number => (typeof value === \"number\" ? value : 0);\n return count(record.input) + count(record.output) + count(record.cacheRead) + count(record.cacheWrite);\n};\n", "import type { SessionEntry } from \"@earendil-works/pi-coding-agent\";\n\n// Local mirror of the context-projection helpers in pi 1.1.0\n// core/session-manager.js and core/messages.js. Kept identical so Fabric's\n// compaction projections match the host's without importing the host package\n// during extension load.\n\nexport type ContextMessage = { role: string } & Record<string, unknown>;\n\ntype PathEntry = SessionEntry & { parentId?: string };\n\nconst buildEntryIndex = (\n entries: readonly SessionEntry[],\n byId?: Map<string, SessionEntry>,\n): Map<string, SessionEntry> => {\n if (byId) return byId;\n const index = new Map<string, SessionEntry>();\n for (const entry of entries) {\n index.set(entry.id, entry);\n }\n return index;\n};\n\nconst buildSessionPath = (\n entries: readonly SessionEntry[],\n leafId: string | undefined,\n byId?: Map<string, SessionEntry>,\n): SessionEntry[] => {\n const index = buildEntryIndex(entries, byId);\n let leaf: SessionEntry | undefined = undefined;\n if (leafId !== undefined) {\n leaf = index.get(leafId);\n }\n leaf = leaf ?? entries[entries.length - 1];\n if (!leaf) {\n return [];\n }\n const path: SessionEntry[] = [];\n let current: SessionEntry | undefined = leaf;\n while (current) {\n path.push(current);\n const parent = current as PathEntry;\n current = parent.parentId ? index.get(parent.parentId) : undefined;\n }\n path.reverse();\n return path;\n};\n\nconst getSessionContextSettings = (path: readonly SessionEntry[]): {\n thinkingLevel: string;\n model: { provider: string; modelId: string } | null;\n} => {\n let thinkingLevel = \"off\";\n let model: { provider: string; modelId: string } | null = null;\n for (const entry of path) {\n if (entry.type === \"thinking_level_change\") {\n thinkingLevel = entry.thinkingLevel;\n } else if (entry.type === \"model_change\") {\n model = { provider: entry.provider, modelId: entry.modelId };\n } else if (entry.type === \"message\" && entry.message.role === \"assistant\") {\n model = { provider: entry.message.provider, modelId: entry.message.model };\n }\n }\n return { thinkingLevel, model };\n};\n\nconst createBranchSummaryMessage = (\n summary: string,\n fromId: string,\n timestamp: number | string,\n): ContextMessage => ({\n role: \"branchSummary\",\n summary,\n fromId,\n timestamp: new Date(timestamp).getTime(),\n});\n\nconst createCompactionSummaryMessage = (\n summary: string,\n tokensBefore: number,\n timestamp: number | string,\n): ContextMessage => ({\n role: \"compactionSummary\",\n summary,\n tokensBefore,\n timestamp: new Date(timestamp).getTime(),\n});\n\nconst createCustomMessage = (\n customType: string,\n content: unknown,\n display: unknown,\n details: unknown,\n timestamp: number | string,\n): ContextMessage => ({\n role: \"custom\",\n customType,\n content,\n display,\n details,\n timestamp: new Date(timestamp).getTime(),\n});\n\nexport const sessionEntryToContextMessages = (entry: SessionEntry): ContextMessage[] => {\n if (entry.type === \"message\") {\n const message = entry.message;\n if (message.role === \"system\" && message.content == null) return [{ ...message, content: \"\" }];\n if (\n (message.role === \"user\" || message.role === \"assistant\" || message.role === \"toolResult\")\n && message.content == null\n ) {\n return [{ ...message, content: [] }];\n }\n return [message] as unknown as ContextMessage[];\n }\n if (entry.type === \"custom_message\") {\n return [\n createCustomMessage(entry.customType, entry.content ?? [], entry.display, entry.details, entry.timestamp),\n ];\n }\n if (entry.type === \"branch_summary\" && entry.summary) {\n return [createBranchSummaryMessage(entry.summary, entry.fromId, entry.timestamp)];\n }\n if (entry.type === \"compaction\") {\n const summary = createCompactionSummaryMessage(entry.summary, entry.tokensBefore, entry.timestamp);\n return entry.systemMessage ? [entry.systemMessage as unknown as ContextMessage, summary] : [summary];\n }\n return [];\n};\n\nconst buildContextEntries = (\n entries: readonly SessionEntry[],\n leafId?: string,\n byId?: Map<string, SessionEntry>,\n): SessionEntry[] => {\n const path = buildSessionPath(entries, leafId, byId);\n let compaction: SessionEntry | undefined = undefined;\n for (const entry of path) {\n if (entry.type === \"compaction\") {\n compaction = entry;\n }\n }\n if (!compaction) {\n return path;\n }\n const compactionIdx = [...path].findIndex(\n (entry) => entry.id === compaction?.id,\n );\n if (compactionIdx < 0) {\n return path;\n }\n const contextEntries: SessionEntry[] = [compaction];\n let foundFirstKept = false;\n for (let i = 0; i < compactionIdx; i++) {\n const entry = path[i];\n if (!entry) continue;\n if (entry.id === compaction.firstKeptEntryId) {\n foundFirstKept = true;\n }\n if (foundFirstKept && !(entry.type === \"message\" && entry.message.role === \"system\")) {\n contextEntries.push(entry);\n }\n }\n contextEntries.push(...path.slice(compactionIdx + 1));\n return contextEntries;\n};\n\n/** Content-only view; preserve IDs/parent links even for omissions so cuts and\n * tree traversal still address the original branch. Never mutate raw history.\n * Also used over cumulative raw history by deterministic compaction: an omitted\n * recovery attempt must not be resurrected by a later summary. */\nexport const applyContextEdits = (entries: readonly SessionEntry[]): SessionEntry[] => {\n const edits = new Map<string, Extract<SessionEntry, { type: \"context_edit\" }>>();\n for (const entry of entries) if (entry.type === \"context_edit\") edits.set(entry.targetId, entry);\n return entries.map((entry) => {\n const edit = edits.get(entry.id);\n if (!edit) return entry;\n const replacement = edit.replacement;\n if (replacement === null) return {\n type: \"custom\", id: entry.id, parentId: entry.parentId, timestamp: entry.timestamp,\n customType: \"fabric.context-omission\",\n };\n if (entry.type === \"custom_message\") return { ...entry, content: replacement.content as typeof entry.content };\n if (entry.type !== \"message\") return entry;\n const message = entry.message;\n if (![\"user\", \"assistant\", \"toolResult\", \"custom\"].includes(message.role)) return entry;\n const content = (message.role === \"assistant\" || message.role === \"toolResult\") && typeof replacement.content === \"string\"\n ? [{ type: \"text\" as const, text: replacement.content }] : replacement.content;\n return { ...entry, message: { ...message, content } } as SessionEntry;\n });\n};\n\nexport const buildSessionContext = (\n entries: readonly SessionEntry[],\n leafId?: string,\n byId?: Map<string, SessionEntry>,\n): {\n messages: ContextMessage[];\n thinkingLevel: string;\n model: { provider: string; modelId: string } | null;\n} => {\n const path = buildSessionPath(entries, leafId, byId);\n const { thinkingLevel, model } = getSessionContextSettings(path);\n const messages = applyContextEdits(buildContextEntries(entries, leafId, byId))\n .flatMap((entry, index) => entry.type === \"compaction\" && index > 0 ? [] : sessionEntryToContextMessages(entry));\n return { messages, thinkingLevel, model };\n};\n", "import type { ExtensionContext } from \"@earendil-works/pi-coding-agent\";\nimport type { FabricConfig } from \"../config.js\";\n\nexport const modelCompactionKey = (\n model: Pick<NonNullable<ExtensionContext[\"model\"]>, \"provider\" | \"id\"> | undefined,\n): string | undefined => model ? `${model.provider}/${model.id}` : undefined;\n\n// A configured token threshold takes precedence over a ratio for the same\n// model; the settings UI keeps the maps mutually exclusive, and hand-written\n// configs resolve to the more explicit token value.\nconst configuredCompactionTokenThreshold = (\n config: FabricConfig,\n modelKey: string | undefined,\n): number | undefined =>\n modelKey === undefined ? undefined : config.compaction.tokenThresholds[modelKey];\n\nconst configuredCompactionThreshold = (\n config: FabricConfig,\n modelKey: string | undefined,\n): number | undefined =>\n modelKey === undefined ? undefined : config.compaction.thresholds[modelKey];\n\nconst runThresholdCompact = (\n context: ExtensionContext,\n): Promise<boolean> => new Promise<boolean>((resolve) => {\n context.compact({\n onComplete: () => resolve(true),\n onError: (error) => {\n if (context.hasUI) {\n context.ui.notify(`Fabric threshold compaction failed: ${error.message}`, \"warning\");\n }\n resolve(false);\n },\n });\n});\n\nexport type AutoCompactionTrigger = \"headroom\" | \"tokens\" | \"ratio\";\n\n// Headroom left in the window for the next response. `outputReserveTokens`\n// of 0 disables the trigger; unknown usage never triggers.\nexport const outputReserveBreached = (\n usage: { tokens: number | null; contextWindow: number } | undefined,\n outputReserveTokens: number,\n): boolean =>\n outputReserveTokens > 0\n && usage !== undefined\n && usage.tokens !== null\n && Number.isFinite(usage.contextWindow)\n && usage.contextWindow > 0\n && usage.contextWindow - usage.tokens < outputReserveTokens;\n\nconst autoCompactionTrigger = (\n context: ExtensionContext,\n config: FabricConfig,\n): AutoCompactionTrigger | undefined => {\n const modelKey = modelCompactionKey(context.model);\n const usage = context.getContextUsage();\n if (usage === undefined) return undefined;\n\n if (outputReserveBreached(usage, config.compaction.outputReserveTokens)) return \"headroom\";\n\n const tokenThreshold = configuredCompactionTokenThreshold(config, modelKey);\n if (tokenThreshold !== undefined) {\n return usage.tokens !== null && usage.tokens >= tokenThreshold ? \"tokens\" : undefined;\n }\n\n const threshold = configuredCompactionThreshold(config, modelKey);\n if (threshold === undefined || usage.percent === null) return undefined;\n return usage.percent / 100 >= threshold ? \"ratio\" : undefined;\n};\n\nexport const compactAtConfiguredThreshold = async (\n context: ExtensionContext,\n config: FabricConfig,\n onTrigger?: (trigger: AutoCompactionTrigger, committed: boolean) => void,\n): Promise<boolean> => {\n const trigger = autoCompactionTrigger(context, config);\n if (trigger === undefined) return false;\n const committed = await runThresholdCompact(context);\n onTrigger?.(trigger, committed);\n return committed;\n};\n", "import type { CompactionEvent } from \"./normalize.js\";\nimport type { Sections } from \"./projections.js\";\n\n// Optional, isolated, format-specific annotation. The deterministic core\n// never inspects prose (principle 2); anything that needs to \u2014 e.g. pulling a\n// TypeScript compiler line number out of a bash `tsc` result, or annotating a\n// test-failure section \u2014 plugs in here, behind this interface. The core ships\n// ZERO built-in enrichers on purpose: the redistilled core is the minimal clean\n// baseline, and prose understanding is an additive concern an extension can\n// register later without touching the projections.\n//\n// An enricher is called once per compaction, AFTER the structural sections are\n// computed. It may append to (or replace) any section. It must be deterministic:\n// the same event stream must yield the same contribution, so the overall\n// serialization stays byte-identical for a given input (principle 5).\nexport interface CompactionEnricher {\n readonly name: string;\n // Decide whether this enricher has anything to add for the given event\n // stream. Returning false lets the core skip contribute() cheaply.\n applies(events: CompactionEvent[]): boolean;\n // Mutate `sections` in place to add format-specific annotation. The full\n // event stream is available so the enricher can derive its own state without\n // re-walking the raw log differently from the core.\n contribute(events: CompactionEvent[], sections: Sections): void;\n}\n\n// No built-in enrichers. Kept explicit (and exported) so tests and docs can\n// reference the empty set and so the registration path stays exercised.\nexport const NO_BUILTIN_ENRICHERS: readonly CompactionEnricher[] = Object.freeze([]);\n\nexport const runEnrichers = (\n enrichers: readonly CompactionEnricher[],\n events: CompactionEvent[],\n sections: Sections,\n): void => {\n for (const enricher of enrichers) {\n if (!enricher.applies(events)) continue;\n enricher.contribute(events, sections);\n }\n};\n", "import type { FabricRunDisplay } from \"./activity/types.js\";\n\n// Silent repair for fabric_exec `display` near-misses. The declared shape is\n// the object { name?, description? }, but models reliably cold-start with a\n// bare objective string (or a JSON-stringified object) instead, which strict\n// schema validation used to reject at the cost of a zero-work round trip.\n// Both spellings carry identical intent, so coerce them. See the\n// flat-tool-schema note in fabric-exec-tool.ts.\n\nconst recordDisplay = (record: Record<string, unknown>): FabricRunDisplay | undefined => {\n const display: FabricRunDisplay = {};\n if (typeof record.name === \"string\") display.name = record.name;\n if (typeof record.description === \"string\") display.description = record.description;\n return display.name !== undefined || display.description !== undefined ? display : undefined;\n};\n\nconst parseObjectString = (text: string): Record<string, unknown> | undefined => {\n if (!text.startsWith(\"{\") || !text.endsWith(\"}\")) return undefined;\n try {\n const parsed: unknown = JSON.parse(text);\n return typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : undefined;\n } catch {\n return undefined;\n }\n};\n\nexport const normalizeRunDisplay = (input: unknown): FabricRunDisplay | undefined => {\n if (typeof input === \"string\") {\n const text = input.trim();\n if (!text) return undefined;\n const parsed = text.startsWith(\"{\") ? parseObjectString(text) : undefined;\n // Fall back to the raw string as the name: intent preservation beats shape\n // pedantry for a cosmetic label.\n return (parsed && recordDisplay(parsed)) ?? { name: input };\n }\n if (typeof input === \"object\" && input !== null && !Array.isArray(input)) {\n return recordDisplay(input as Record<string, unknown>);\n }\n return undefined;\n};\n", "import { fabricExecTitleHint } from \"./fabric-code-parser.js\";\nimport type { FabricKernel } from \"../runtime/kernel.js\";\n\n// The live card, activity feed and compaction share a bounded memo. Include\n// the kernel: identical source can mean different things in each language.\nconst TITLE_HINT_CACHE_MAX = 256;\nconst titleHintCache = new Map<string, string | undefined>();\n\nexport const fabricExecTitleHintCached = (\n code: string,\n kernel: FabricKernel = \"typescript\",\n): string | undefined => {\n const key = `${kernel}\\0${code}`;\n const hit = titleHintCache.get(key);\n if (hit !== undefined || titleHintCache.has(key)) return hit;\n const hint = fabricExecTitleHint(code, kernel);\n if (titleHintCache.size >= TITLE_HINT_CACHE_MAX) {\n const oldest = titleHintCache.keys().next().value;\n if (oldest !== undefined) titleHintCache.delete(oldest);\n }\n titleHintCache.set(key, hint);\n return hint;\n};\n", "import type { SessionEntry, SessionMessageEntry } from \"@earendil-works/pi-coding-agent\";\nimport type { FabricExecutionOutcomeV1, FabricTraceJsonValue } from \"../audit/trace.js\";\nimport { readFabricProjectionTrace, type FabricProjectionSource } from \"./trace-events.js\";\nimport {\n FABRIC_BRANCH_RUN_DESCRIPTION_MAX_BYTES,\n FABRIC_BRANCH_RUN_NAME_MAX_BYTES,\n readFabricBranchSummaryDetails,\n} from \"./branch-details.js\";\nimport { clipUtf8, utf8Bytes } from \"./bounds.js\";\nimport { normalizeRunDisplay } from \"../run-display.js\";\nimport { fabricExecTitleHintCached } from \"../ui/fabric-title-hint.js\";\n\n// A purely structural, typed view of one session window. Every event carries\n// the 1-based `index` it occupied in the normalized stream (stable, used by the\n// brief-transcript `(#N)` references), a stable fact `entryId`, and the actual\n// `sourceEntryId` that carried it. Normalization extracts ONLY\n// typed structure \u2014 roles, tool names, JSON arguments, isError flags, bash\n// commands and exit codes. It never inspects prose. See docs/compaction.md\n// principle 2.\n//\n// Assistant thinking parts are deliberate scratchpad, not commitments: they are\n// never normalized into events, so no summary section can leak truncated\n// deliberation that reads like fact. `countErasedThinkingBlocks` keeps that\n// erasure auditable in compaction details. See docs/compaction.md (Transcript).\n\ninterface EventBase {\n index: number;\n entryId: string;\n sourceEntryId: string;\n}\n\ninterface UserEvent extends EventBase {\n kind: \"user\";\n text: string;\n}\n\ninterface AssistantTextEvent extends EventBase {\n kind: \"assistantText\";\n text: string;\n}\n\ninterface CustomMessageEvent extends EventBase {\n kind: \"customMessage\";\n customType: string;\n text: string;\n display: boolean;\n details?: FabricTraceJsonValue;\n}\n\nexport interface ToolCallEvent extends EventBase {\n kind: \"toolCall\";\n toolCallId: string;\n name: string;\n args: Record<string, unknown>;\n}\n\ninterface ToolResultEvent extends EventBase {\n kind: \"toolResult\";\n toolCallId: string;\n toolName: string;\n isError: boolean;\n text: string;\n}\n\ninterface BashEvent extends EventBase {\n kind: \"bash\";\n toolCallId: string;\n command: string;\n isError: boolean;\n exitCode: number | null;\n error?: string;\n}\n\ninterface FabricPhaseEvent extends EventBase {\n kind: \"fabricPhase\";\n subordinal: string;\n address: string;\n phase: string;\n}\n\nexport interface FabricRunEvent extends EventBase {\n kind: \"fabricRun\";\n toolCallId: string;\n subordinal: string;\n address: string;\n name: string;\n description?: string;\n outcome: FabricExecutionOutcomeV1;\n source: FabricProjectionSource | \"result\" | \"branch\";\n}\n\ninterface FabricOperationEvent extends EventBase {\n kind: \"fabricOperation\";\n subordinal: string;\n address: string;\n ref: string;\n provider?: string;\n action?: string;\n tool: string;\n args: Record<string, FabricTraceJsonValue>;\n outcome: FabricExecutionOutcomeV1;\n error?: string;\n result?: FabricTraceJsonValue;\n source: FabricProjectionSource | \"branch\";\n}\n\nexport type CompactionEvent =\n | UserEvent\n | AssistantTextEvent\n | CustomMessageEvent\n | ToolCallEvent\n | ToolResultEvent\n | BashEvent\n | FabricPhaseEvent\n | FabricRunEvent\n | FabricOperationEvent;\n\nconst isMessageEntry = (entry: SessionEntry): entry is Extract<SessionEntry, { type: \"message\" }> =>\n entry.type === \"message\";\n\nconst MAX_CUSTOM_DETAILS_DEPTH = 12;\nconst MAX_CUSTOM_DETAILS_NODES = 256;\nconst MAX_CUSTOM_DETAILS_COLLECTION = 64;\nconst MAX_CUSTOM_DETAILS_STRING_BYTES = 1024;\nconst MAX_CUSTOM_DETAILS_BYTES = 8 * 1024;\n\ninterface JsonSanitizerState {\n nodes: number;\n ancestors: Set<object>;\n}\n\nconst boundedJsonValue = (\n value: unknown,\n state: JsonSanitizerState,\n depth = 0,\n): FabricTraceJsonValue | undefined => {\n state.nodes += 1;\n if (state.nodes > MAX_CUSTOM_DETAILS_NODES) return undefined;\n if (value === null || typeof value === \"boolean\") return value;\n if (typeof value === \"string\") return clipUtf8(value, MAX_CUSTOM_DETAILS_STRING_BYTES);\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined;\n if (typeof value !== \"object\" || depth > MAX_CUSTOM_DETAILS_DEPTH || state.ancestors.has(value)) return undefined;\n state.ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n const output: FabricTraceJsonValue[] = [];\n for (const item of value.slice(0, MAX_CUSTOM_DETAILS_COLLECTION)) {\n const sanitized = boundedJsonValue(item, state, depth + 1);\n if (sanitized === undefined) return undefined;\n output.push(sanitized);\n }\n return output;\n }\n const output = Object.create(null) as Record<string, FabricTraceJsonValue>;\n const keys = Object.keys(value).sort().slice(0, MAX_CUSTOM_DETAILS_COLLECTION);\n for (const key of keys) {\n const sanitized = boundedJsonValue((value as Record<string, unknown>)[key], state, depth + 1);\n if (sanitized === undefined) return undefined;\n output[key] = sanitized;\n }\n return output;\n } finally {\n state.ancestors.delete(value);\n }\n};\n\nconst customDetails = (value: unknown): FabricTraceJsonValue | undefined => {\n if (value === undefined) return undefined;\n try {\n const sanitized = boundedJsonValue(value, { nodes: 0, ancestors: new Set<object>() });\n if (sanitized === undefined || utf8Bytes(JSON.stringify(sanitized)) > MAX_CUSTOM_DETAILS_BYTES) return undefined;\n return sanitized;\n } catch {\n return undefined;\n }\n};\n\nconst isTypedCustomContent = (content: unknown): boolean => {\n if (typeof content === \"string\") return true;\n if (!Array.isArray(content)) return false;\n return content.every((part) => {\n if (part === null || typeof part !== \"object\") return false;\n const candidate = part as { type?: unknown; text?: unknown };\n if (candidate.type === \"text\") return typeof candidate.text === \"string\";\n return candidate.type === \"image\";\n });\n};\n\nexport const isPiCustomMessageEntry = (\n entry: SessionEntry,\n): entry is Extract<SessionEntry, { type: \"custom_message\" }> => {\n try {\n if (entry.type !== \"custom_message\") return false;\n const candidate = entry as SessionEntry & {\n customType?: unknown;\n content?: unknown;\n display?: unknown;\n };\n return typeof candidate.customType === \"string\"\n && typeof candidate.display === \"boolean\"\n && isTypedCustomContent(candidate.content);\n } catch {\n return false;\n }\n};\n\nconst textOfContent = (content: unknown): string => {\n if (typeof content === \"string\") return content;\n if (!Array.isArray(content)) return \"\";\n const parts: string[] = [];\n for (const part of content) {\n if (part && typeof part === \"object\" && \"type\" in part) {\n if (part.type === \"text\" && typeof part.text === \"string\") parts.push(part.text);\n }\n }\n return parts.join(\"\\n\");\n};\n\nconst firstLine = (text: string): string => {\n const trimmed = text.trimStart();\n const nl = trimmed.indexOf(\"\\n\");\n return nl < 0 ? trimmed : trimmed.slice(0, nl);\n};\n\ninterface PendingCall {\n entryId: string;\n name: string;\n args: Record<string, unknown>;\n}\n\ninterface FabricRunIntent {\n name: string;\n description?: string;\n}\n\nconst fabricRunIntent = (call: PendingCall | undefined, details: unknown): FabricRunIntent | undefined => {\n // Recorded kernel identity, not the current setting, governs historical runs.\n const python = typeof details === \"object\" && details !== null\n && \"kernel\" in details && details.kernel === \"python\";\n if (!call || call.name !== \"fabric_exec\") return undefined;\n const display = normalizeRunDisplay(call.args.display);\n // Fallback parity with the compact card header and the activity feed: when\n // no name is declared, derive one lexically from the recorded program so\n // intent continuity never depends on the live UI. A declared description is\n // preserved even when the name comes from the program.\n const intentName = display?.name?.trim()\n ? display.name\n : typeof call.args.code === \"string\"\n ? fabricExecTitleHintCached(call.args.code, python ? \"python\" : \"typescript\")\n ?? (python ? \"Python program\" : undefined)\n : undefined;\n if (intentName === undefined) return undefined;\n const name = clipUtf8(intentName.trim(), FABRIC_BRANCH_RUN_NAME_MAX_BYTES);\n if (!name) return undefined;\n const description = display?.description !== undefined\n ? clipUtf8(display.description.trim(), FABRIC_BRANCH_RUN_DESCRIPTION_MAX_BYTES)\n : \"\";\n return { name, ...(description ? { description } : {}) };\n};\n\ntype DistributiveOmit<T, K extends keyof any> = T extends T ? Omit<T, K> : never;\n\n// Normalize a SessionEntry source prefix into a flat, typed event stream.\n// The caller selects the cumulative raw active-branch prefix before the new\n// kept boundary. Tool results are paired back to their tool calls by\n// id so a bash result can carry the command from the originating call; this\n// pairing is structural (id match), never prose-based.\nexport const normalizeEntries = (entries: SessionEntry[]): CompactionEvent[] => {\n const events: CompactionEvent[] = [];\n const calls = new Map<string, PendingCall>();\n let index = 0;\n\n const push = (event: DistributiveOmit<CompactionEvent, \"index\">): void => {\n index += 1;\n events.push({ ...event, index } as CompactionEvent);\n };\n\n const pushBranchFacts = (entry: SessionEntry & { details?: unknown }): void => {\n const details = readFabricBranchSummaryDetails(entry.details);\n if (!details) return;\n for (const fact of details.facts) {\n if (fact.kind === \"user\") {\n push({ kind: \"user\", entryId: fact.entryId, sourceEntryId: entry.id, text: fact.text });\n } else if (fact.kind === \"customMessage\") {\n push({\n kind: \"customMessage\",\n entryId: fact.entryId,\n sourceEntryId: entry.id,\n customType: fact.customType,\n text: fact.text,\n display: fact.display,\n ...(fact.details !== undefined ? { details: fact.details } : {}),\n });\n } else if (fact.kind === \"phase\") {\n push({\n kind: \"fabricPhase\",\n entryId: fact.entryId,\n sourceEntryId: entry.id,\n subordinal: fact.subordinal,\n address: fact.address,\n phase: fact.phase,\n });\n } else if (fact.kind === \"fabricRun\") {\n push({\n kind: \"fabricRun\",\n entryId: fact.entryId,\n sourceEntryId: entry.id,\n toolCallId: fact.subordinal.startsWith(\"call:\")\n ? fact.subordinal.slice(\"call:\".length)\n : fact.subordinal,\n subordinal: fact.subordinal,\n address: fact.address,\n name: fact.name,\n ...(fact.description !== undefined ? { description: fact.description } : {}),\n outcome: fact.outcome,\n source: \"branch\",\n });\n } else {\n push({\n kind: \"fabricOperation\",\n entryId: fact.entryId,\n sourceEntryId: entry.id,\n subordinal: fact.subordinal,\n address: fact.address,\n ref: fact.ref,\n ...(fact.provider ? { provider: fact.provider } : {}),\n ...(fact.action ? { action: fact.action } : {}),\n tool: fact.tool,\n args: fact.args,\n outcome: fact.outcome,\n ...(fact.error !== undefined ? { error: fact.error } : {}),\n ...(fact.result !== undefined ? { result: fact.result } : {}),\n source: \"branch\",\n });\n }\n }\n };\n\n for (const entry of entries) {\n if (entry.type === \"branch_summary\") {\n pushBranchFacts(entry as SessionEntry & { details?: unknown });\n continue;\n }\n if (entry.type === \"custom_message\") {\n try {\n if (!isPiCustomMessageEntry(entry)) continue;\n const details = customDetails(entry.details);\n push({\n kind: \"customMessage\",\n entryId: entry.id,\n sourceEntryId: entry.id,\n customType: entry.customType,\n text: textOfContent(entry.content),\n display: entry.display,\n ...(details !== undefined ? { details } : {}),\n });\n } catch {\n // Malformed extension-owned entries are ignored without affecting later source.\n }\n continue;\n }\n if (!isMessageEntry(entry)) continue;\n const message = entry.message as SessionMessageEntry[\"message\"];\n if (!message || typeof message !== \"object\") continue;\n const role = (message as { role?: unknown }).role;\n const entryId = entry.id;\n\n if (role === \"user\") {\n push({ kind: \"user\", entryId, sourceEntryId: entryId, text: textOfContent((message as { content: unknown }).content) });\n continue;\n }\n\n if (role === \"assistant\") {\n const content = (message as { content: unknown }).content;\n if (!Array.isArray(content)) continue;\n for (const part of content) {\n if (!part || typeof part !== \"object\" || !(\"type\" in part)) continue;\n if (part.type === \"text\" && typeof part.text === \"string\") {\n push({ kind: \"assistantText\", entryId, sourceEntryId: entryId, text: part.text });\n } else if (part.type === \"toolCall\" && typeof part.id === \"string\" && typeof part.name === \"string\") {\n const args = (part.arguments ?? {}) as Record<string, unknown>;\n calls.set(part.id, { entryId, name: part.name, args });\n push({ kind: \"toolCall\", entryId, sourceEntryId: entryId, toolCallId: part.id, name: part.name, args });\n }\n }\n continue;\n }\n\n if (role === \"toolResult\") {\n const toolResult = message as {\n toolCallId?: string;\n toolName?: string;\n isError?: boolean;\n content?: unknown;\n details?: unknown;\n };\n const toolCallId = typeof toolResult.toolCallId === \"string\" ? toolResult.toolCallId : \"\";\n const toolName = typeof toolResult.toolName === \"string\" ? toolResult.toolName : \"\";\n const isError = toolResult.isError === true;\n const text = textOfContent(toolResult.content);\n const pending = toolCallId ? calls.get(toolCallId) : undefined;\n if (toolName === \"bash\") {\n const command =\n pending && typeof pending.args.command === \"string\"\n ? pending.args.command\n : \"\";\n push({\n kind: \"bash\",\n entryId,\n sourceEntryId: entryId,\n toolCallId,\n command,\n isError,\n exitCode: null,\n ...(isError && text ? { error: text } : {}),\n });\n } else {\n push({ kind: \"toolResult\", entryId, sourceEntryId: entryId, toolCallId, toolName, isError, text });\n }\n if (toolName === \"fabric_exec\") {\n const nested = readFabricProjectionTrace(toolResult.details);\n const intent = fabricRunIntent(pending, toolResult.details);\n if (intent && pending) {\n const subordinal = `call:${toolCallId}`;\n push({\n kind: \"fabricRun\",\n entryId: pending.entryId,\n sourceEntryId: entryId,\n toolCallId,\n subordinal,\n address: `${pending.entryId}/${subordinal}`,\n name: intent.name,\n ...(intent.description !== undefined ? { description: intent.description } : {}),\n outcome: nested?.outcome ?? (isError ? \"failed\" : \"succeeded\"),\n source: nested?.source ?? \"result\",\n });\n }\n if (nested) {\n for (let phaseIndex = 0; phaseIndex < nested.phases.length; phaseIndex++) {\n const subordinal = `phase:${phaseIndex}`;\n push({\n kind: \"fabricPhase\",\n entryId,\n sourceEntryId: entryId,\n subordinal,\n address: `${entryId}/${subordinal}`,\n phase: nested.phases[phaseIndex]!,\n });\n }\n for (const operation of nested.operations) {\n const subordinal = String(operation.sequence);\n push({\n kind: \"fabricOperation\",\n entryId,\n sourceEntryId: entryId,\n subordinal,\n address: `${entryId}/${subordinal}`,\n ref: operation.ref,\n ...(operation.provider ? { provider: operation.provider } : {}),\n ...(operation.action ? { action: operation.action } : {}),\n tool: operation.tool,\n args: operation.args,\n outcome: operation.outcome,\n ...(operation.error !== undefined ? { error: operation.error } : {}),\n ...(operation.result !== undefined ? { result: operation.result } : {}),\n source: operation.source,\n });\n }\n }\n }\n continue;\n }\n\n if (role === \"bashExecution\") {\n const bash = message as {\n command?: string;\n exitCode?: number | undefined;\n output?: string;\n };\n const exitCode = typeof bash.exitCode === \"number\" ? bash.exitCode : null;\n const isError = exitCode !== null && exitCode !== 0;\n push({\n kind: \"bash\",\n entryId,\n sourceEntryId: entryId,\n toolCallId: \"\",\n command: typeof bash.command === \"string\" ? bash.command : \"\",\n isError,\n exitCode,\n ...(isError && typeof bash.output === \"string\" && bash.output ? { error: bash.output } : {}),\n });\n continue;\n }\n\n // Message-role custom / branchSummary / compactionSummary and any other\n // roles are not top-level Pi custom_message entries and are skipped here.\n }\n\n return events;\n};\n\n// Structural count of assistant thinking parts erased by normalization. The\n// walk mirrors normalizeEntries selection (typed part, string payload) so the\n// details counter cannot disagree with what the summary silently dropped.\n// Entry-level ranges are unnecessary: erased blocks always lie inside the\n// cumulative source range recorded beside the count.\nexport const countErasedThinkingBlocks = (entries: SessionEntry[]): number => {\n let count = 0;\n for (const entry of entries) {\n if (!isMessageEntry(entry)) continue;\n const message = entry.message as { role?: unknown; content?: unknown };\n if (message.role !== \"assistant\" || !Array.isArray(message.content)) continue;\n for (const part of message.content) {\n if (!part || typeof part !== \"object\" || !(\"type\" in part)) continue;\n if (\n part.type === \"thinking\" &&\n typeof (part as { thinking?: unknown }).thinking === \"string\"\n ) count += 1;\n }\n }\n return count;\n};\n\nexport { firstLine };\n", "import { boundedExcerpt, utf8Bytes } from \"./bounds.js\";\nimport type { CompactionEvent } from \"./normalize.js\";\n\nexport const MAX_RECENT_EXCHANGES = 3;\n// Three exchanges plus the section heading fit inside the 12 KiB allocation.\nconst MAX_EXCHANGE_BYTES = 3968;\n\ninterface DialogueMessage {\n entryId: string;\n text: string;\n retained: boolean;\n}\n\nexport interface DialogueExchange {\n user: DialogueMessage;\n assistant?: DialogueMessage;\n}\n\n// Recency is measured in eligible user exchanges, not tool events or fully\n// retained raw exchanges. Text parts in one assistant entry are one response;\n// thinking never reaches here.\nexport const recentDialogue = (\n events: readonly CompactionEvent[],\n retainedTail: readonly CompactionEvent[] = [],\n): DialogueExchange[] => {\n const exchanges: DialogueExchange[] = [];\n let assistant: DialogueMessage | undefined;\n const visit = (source: readonly CompactionEvent[], retained: boolean): void => {\n for (const event of source) {\n if (event.kind === \"assistantText\" && event.text.trim()) {\n if (assistant?.entryId === event.entryId) assistant.text += `\\n${event.text}`;\n else assistant = { entryId: event.entryId, text: event.text, retained };\n } else if (event.kind === \"user\") {\n // Filter before limiting: raw-tail replies must not evict prefix\n // context. A crossing exchange still needs its summarized response.\n if (!retained || assistant?.retained === false) {\n exchanges.push({\n user: { entryId: event.entryId, text: event.text, retained },\n ...(assistant ? { assistant } : {}),\n });\n if (exchanges.length > MAX_RECENT_EXCHANGES) exchanges.shift();\n }\n assistant = undefined;\n }\n }\n };\n visit(events, false);\n visit(retainedTail, true);\n return exchanges;\n};\n\nexport interface DialogueExcerpt {\n heading: string;\n text: string;\n omittedBytes: number;\n}\n\nexport const dialogueExcerpts = (exchange: DialogueExchange): DialogueExcerpt[] => {\n const heading = (role: string, message: DialogueMessage): string =>\n `${role} [entry ${message.entryId}${message.retained ? \"; retained raw\" : \"\"}]:`;\n const userHeading = heading(\"User instruction\", exchange.user);\n const assistantHeading = exchange.assistant\n ? heading(\"Historical assistant response (not a verified outcome)\", exchange.assistant)\n : \"\";\n const available = Math.max(0, MAX_EXCHANGE_BYTES - utf8Bytes(userHeading + assistantHeading) - 8);\n const userText = exchange.user.retained ? \"\" : exchange.user.text;\n // Reserve at least half the exchange for the user's own words. Short replies\n // leave the remainder available for the preceding assistant response.\n const assistantBytes = exchange.assistant && !exchange.assistant.retained ? utf8Bytes(exchange.assistant.text) : 0;\n const userBudget = exchange.assistant ? Math.max(available / 2, available - assistantBytes) : available;\n const user = boundedExcerpt(userText, Math.floor(userBudget));\n const excerpts: DialogueExcerpt[] = [{ heading: userHeading, ...user }];\n if (exchange.assistant) {\n const assistant = boundedExcerpt(\n exchange.assistant.retained ? \"\" : exchange.assistant.text,\n available - utf8Bytes(user.text),\n );\n excerpts.unshift({ heading: assistantHeading, ...assistant });\n }\n return excerpts;\n};\n\nexport const projectDialogue = (exchanges: readonly DialogueExchange[]): { lines: string[]; omittedBytes: number } => {\n let omittedBytes = 0;\n const lines = exchanges.map((exchange) => dialogueExcerpts(exchange).map((excerpt) => {\n omittedBytes += excerpt.omittedBytes;\n return `${excerpt.heading}\\n${excerpt.text}`;\n }).join(\"\\n\\n\"));\n return { lines, omittedBytes };\n};\n", "import { clipUtf8, omissionLine, sampleAddressed, sampleAddressedFrom } from \"./bounds.js\";\nimport { projectDialogue, recentDialogue } from \"./dialogue.js\";\nimport {\n firstLine,\n type CompactionEvent,\n type FabricRunEvent,\n type ToolCallEvent,\n} from \"./normalize.js\";\n\n// Section folds: each projection is a pure function of the typed event stream.\n// Together they implement graded decay (principle 4): the oldest turns\n// collapse to one line, recent events stay as a collapsed transcript with\n// stable `(#N)` references, and the very last action is surfaced in Current\n// Status. Salience (principle 3) is *computed* from the event stream by the\n// outstanding fold's state machine \u2014 nothing is remembered, only re-derived.\n\nexport interface Sections {\n dialogue: string[];\n // Retain the internal key for v2 details compatibility; these are historical.\n goal: string[];\n files: string[];\n activity: string[];\n outstanding: string[];\n earlierTurns: string[];\n status: string[];\n transcript: string[];\n}\n\nconst MAX_LINE = 140;\nconst FILE_TOOLS = new Set([\"read\", \"edit\", \"write\", \"grep\", \"find\", \"ls\"]);\nconst MODIFYING_TOOLS = new Set([\"edit\", \"write\"]);\nconst MAX_USER_ONELINER = 120;\nconst MAX_EARLIER_USER = 80;\nconst MAX_STATUS_LINE = 140;\nconst MAX_TRANSCRIPT_LINE = 100;\nconst MAX_TRANSCRIPT_CMD = 80;\nconst MAX_FABRIC_RUN_NAME = 80;\nconst MAX_FABRIC_RUN_DESCRIPTION = 180;\nconst MAX_FABRIC_RUN_TRANSCRIPT_NAME = 60;\nconst MAX_FABRIC_RUN_EARLIER_NAME = 48;\nconst MAX_FABRIC_RUN_STATUS_NAME = 96;\nconst MAX_LATER_GOALS = 24;\nexport const MAX_FILES_PER_KIND = 24;\nconst MAX_OUTSTANDING = 32;\nconst MAX_ACTIVITY = 48;\nexport const MAX_UNRESOLVED = 24;\nconst MAX_RESOLVED = MAX_OUTSTANDING - MAX_UNRESOLVED;\nexport const MAX_EARLIER_TURNS = 32;\nconst TRANSCRIPT_WINDOW = 40;\n\nexport interface ProjectionOmittedCounts {\n goal: number;\n dialogueBytes?: number;\n files: number;\n activity: number;\n outstanding: number;\n earlierTurns: number;\n transcript: number;\n}\n\nexport interface ProjectionResult {\n sections: Sections;\n omittedCounts: ProjectionOmittedCounts;\n}\n\ninterface ProjectedSection {\n lines: string[];\n omitted: number;\n}\n\nconst truncate = (text: string, max: number): string => {\n const flat = text.replace(/\\s+/g, \" \").trim();\n return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;\n};\n\nconst quoted = (text: string, max: number): string => JSON.stringify(truncate(text, max));\n\nconst customDetailsSuffix = (details: unknown, max = 160): string => {\n if (details === undefined) return \"\";\n try {\n return ` details=${truncate(JSON.stringify(details), max)}`;\n } catch {\n return \"\";\n }\n};\n\nconst customMessageLine = (\n event: Extract<CompactionEvent, { kind: \"customMessage\" }>,\n maxText: number,\n): string => {\n const visibility = event.display ? \"visible\" : \"hidden\";\n return `custom ${quoted(event.customType, 80)} (${visibility}): ${quoted(event.text, maxText)}${customDetailsSuffix(event.details)}`;\n};\n\nconst pathOf = (args: Record<string, unknown>): string | undefined => {\n const value = args.path ?? args.file ?? args.dir;\n return typeof value === \"string\" && value.trim() ? value : undefined;\n};\n\ninterface StructuralOperation {\n index: number;\n entryId: string;\n address: string;\n tool: string;\n ref: string;\n provider?: string;\n action?: string;\n args: Record<string, unknown>;\n outcome: \"succeeded\" | \"failed\" | \"aborted\" | \"timed_out\";\n error?: string;\n result?: unknown;\n nested: boolean;\n}\n\nconst collectOperations = (events: CompactionEvent[]): StructuralOperation[] => {\n const calls = new Map<string, ToolCallEvent>();\n for (const event of events) {\n if (event.kind === \"toolCall\") calls.set(event.toolCallId, event);\n }\n const operations: StructuralOperation[] = [];\n for (const event of events) {\n if (event.kind === \"fabricOperation\") {\n operations.push({\n index: event.index,\n entryId: event.entryId,\n address: event.address,\n tool: event.tool,\n ref: event.ref,\n ...(event.provider ? { provider: event.provider } : {}),\n ...(event.action ? { action: event.action } : {}),\n args: event.args,\n outcome: event.outcome,\n ...(event.error !== undefined ? { error: event.error } : {}),\n ...(event.result !== undefined ? { result: event.result } : {}),\n nested: true,\n });\n continue;\n }\n if (event.kind === \"toolResult\" && event.toolName !== \"bash\") {\n const call = event.toolCallId ? calls.get(event.toolCallId) : undefined;\n if (!call) continue;\n operations.push({\n index: event.index,\n entryId: call.entryId,\n address: call.entryId,\n tool: call.name,\n ref: call.name,\n args: call.args,\n outcome: event.isError ? \"failed\" : \"succeeded\",\n ...(event.isError && event.text ? { error: event.text } : {}),\n nested: false,\n });\n continue;\n }\n if (event.kind === \"bash\") {\n operations.push({\n index: event.index,\n entryId: event.entryId,\n address: event.entryId,\n tool: \"bash\",\n ref: \"bash\",\n args: { command: event.command },\n outcome: event.isError ? \"failed\" : \"succeeded\",\n ...(event.error ? { error: event.error } : {}),\n nested: false,\n });\n }\n }\n return operations.sort((left, right) => left.index - right.index);\n};\n\nconst isFileOperation = (operation: StructuralOperation): boolean =>\n FILE_TOOLS.has(operation.tool)\n && (operation.ref === operation.tool || operation.ref === `pi.${operation.tool}`);\n\nconst isBashOperation = (operation: StructuralOperation): boolean =>\n operation.tool === \"bash\"\n && (operation.ref === \"bash\" || operation.ref === \"pi.bash\");\n\nconst resultProvesCreation = (result: unknown): boolean => {\n if (!result || typeof result !== \"object\" || Array.isArray(result)) return false;\n const record = result as Record<string, unknown>;\n if (record.created === true) return true;\n const details = record.details;\n return Boolean(details && typeof details === \"object\" && !Array.isArray(details)\n && (details as Record<string, unknown>).created === true);\n};\n\n// Longest common path prefix (by segment) across a set of paths, returned with\n// a trailing separator. Returns \"\" when there is none.\nconst commonRoot = (paths: string[]): string => {\n if (paths.length === 0) return \"\";\n const split = paths.map((p) => p.split(/[\\\\/]/).filter(Boolean));\n let common = 0;\n const first = split[0]!;\n loop: while (common < first.length) {\n const segment = first[common];\n for (let i = 1; i < split.length; i++) {\n if (split[i]!.length <= common || split[i]![common] !== segment) break loop;\n }\n common += 1;\n }\n if (common === 0) return \"\";\n return `${first.slice(0, common).join(\"/\")}/`;\n};\n\nconst stripRoot = (root: string, path: string): string =>\n root ? path.replace(root, \"\") : path;\n\n// Earlier requests are historical evidence, not an inferred active mandate.\nconst projectGoal = (events: CompactionEvent[], protectedUsers: ReadonlySet<string>): ProjectedSection => {\n const lines: string[] = [];\n function* historicalUsers(): Generator<Extract<CompactionEvent, { kind: \"user\" }>> {\n for (const event of events) {\n if (event.kind === \"user\" && !protectedUsers.has(event.entryId)) yield event;\n }\n }\n const sampled = sampleAddressedFrom(historicalUsers(), MAX_LATER_GOALS);\n for (let index = 0; index < sampled.values.length; index++) {\n if (sampled.omitted > 0 && index === sampled.splitIndex) {\n lines.push(omissionLine(\n sampled.omitted,\n sampled.omittedFirstEntryId,\n sampled.omittedLastEntryId,\n \"user scope changes\",\n ));\n }\n const user = sampled.values[index]!;\n const line = truncate(firstLine(user.text), MAX_USER_ONELINER);\n if (line) lines.push(`- ${line} [entry ${user.entryId}]`);\n }\n return { lines, omitted: sampled.omitted };\n};\n\n// [Files And Changes] uses only successful structural operations. Writes are\n// labelled Written unless a typed result explicitly proves creation.\ninterface FileAddress {\n path: string;\n entryId: string;\n}\n\nconst projectFiles = (events: CompactionEvent[]): ProjectedSection => {\n const read = new Map<string, FileAddress>();\n const modified = new Map<string, FileAddress>();\n const written = new Map<string, FileAddress>();\n const created = new Map<string, FileAddress>();\n\n for (const operation of collectOperations(events)) {\n if (!isFileOperation(operation) || operation.outcome !== \"succeeded\") continue;\n const path = pathOf(operation.args);\n if (!path) continue;\n const address = { path, entryId: operation.address };\n if (operation.tool === \"write\") {\n const target = resultProvesCreation(operation.result) ? created : written;\n if (!target.has(path)) target.set(path, address);\n } else if (operation.tool === \"edit\") {\n if (!modified.has(path)) modified.set(path, address);\n } else if (!read.has(path)) {\n read.set(path, address);\n }\n }\n\n const modifiedSet = new Set<string>();\n for (const path of modified.keys()) modifiedSet.add(path);\n for (const path of written.keys()) modifiedSet.add(path);\n for (const path of created.keys()) modifiedSet.add(path);\n function* filteredRead(): Generator<FileAddress> {\n for (const item of read.values()) {\n if (!modifiedSet.has(item.path)) yield item;\n }\n }\n const sampledCreated = sampleAddressedFrom(created.values(), MAX_FILES_PER_KIND);\n const sampledWritten = sampleAddressedFrom(written.values(), MAX_FILES_PER_KIND);\n const sampledModified = sampleAddressedFrom(modified.values(), MAX_FILES_PER_KIND);\n const sampledRead = sampleAddressedFrom(filteredRead(), MAX_FILES_PER_KIND);\n const allSampled = [\n ...sampledCreated.values,\n ...sampledWritten.values,\n ...sampledModified.values,\n ...sampledRead.values,\n ];\n if (allSampled.length === 0) return { lines: [], omitted: 0 };\n const root = commonRoot(allSampled.map((item) => item.path));\n const lines: string[] = [];\n let omitted = 0;\n if (root) lines.push(`(under ${root})`);\n\n const appendKind = (\n header: string,\n sampled: ReturnType<typeof sampleAddressed<FileAddress>>,\n ): void => {\n if (sampled.values.length === 0 && sampled.omitted === 0) return;\n lines.push(header);\n omitted += sampled.omitted;\n for (let index = 0; index < sampled.values.length; index++) {\n if (sampled.omitted > 0 && index === sampled.splitIndex) {\n lines.push(` ${omissionLine(\n sampled.omitted,\n sampled.omittedFirstEntryId,\n sampled.omittedLastEntryId,\n \"file addresses\",\n )}`);\n }\n const item = sampled.values[index]!;\n lines.push(` ${stripRoot(root, item.path)} [entry ${item.entryId}]`);\n }\n };\n\n appendKind(\"Created:\", sampledCreated);\n appendKind(\"Written:\", sampledWritten);\n appendKind(\"Modified:\", sampledModified);\n appendKind(\"Read:\", sampledRead);\n return { lines, omitted };\n};\n\ninterface ActivityItem {\n entryId: string;\n line: string;\n}\n\nconst fabricRunPointer = (event: FabricRunEvent): string =>\n event.source === \"branch\" ? event.address : event.entryId;\n\nconst projectActivity = (events: CompactionEvent[]): ProjectedSection => {\n const items: ActivityItem[] = [];\n for (const event of events) {\n if (event.kind === \"fabricRun\") {\n const name = clipUtf8(truncate(event.name, MAX_FABRIC_RUN_NAME), 192);\n const description = event.description\n ? clipUtf8(truncate(event.description, MAX_FABRIC_RUN_DESCRIPTION), 512)\n : \"\";\n items.push({\n entryId: fabricRunPointer(event),\n line: `- ${name}${description ? ` \u2014 ${description}` : \"\"} \u2192 ${event.outcome}`,\n });\n } else if (event.kind === \"fabricPhase\") {\n items.push({ entryId: event.address, line: `- Phase: ${truncate(event.phase, MAX_LINE)}` });\n } else if (event.kind === \"fabricOperation\") {\n if (FILE_TOOLS.has(event.tool)\n && (event.ref === event.tool || event.ref === `pi.${event.tool}`)) continue;\n const bash = event.tool === \"bash\"\n && (event.ref === \"bash\" || event.ref === \"pi.bash\");\n const primary = bash\n ? event.args.command\n : event.args.id ?? event.args.name ?? event.args.query ?? event.args.action;\n const detail = typeof primary === \"string\" && primary.trim()\n ? ` (${truncate(firstLine(primary), 72)})`\n : \"\";\n items.push({\n entryId: event.address,\n line: `- ${event.ref}${detail} \u2192 ${event.outcome}`,\n });\n }\n }\n const sampled = sampleAddressed(items, MAX_ACTIVITY);\n const lines: string[] = [];\n for (let index = 0; index < sampled.values.length; index++) {\n if (sampled.omitted > 0 && index === sampled.splitIndex) {\n lines.push(omissionLine(\n sampled.omitted,\n sampled.omittedFirstEntryId,\n sampled.omittedLastEntryId,\n \"Fabric activity records\",\n ));\n }\n const item = sampled.values[index]!;\n lines.push(`${item.line} [entry ${item.entryId}]`);\n }\n return { lines, omitted: sampled.omitted };\n};\n\ninterface ErrorItem {\n index: number;\n entryId: string;\n description: string;\n resolved: boolean;\n}\n\n// [Outstanding Context] is keyed only by typed operation identity. A later\n// success resolves a failure only when action+path, action+command, or the\n// generic ref+arguments identity is exactly equal.\nconst projectOutstandingWithMetadata = (events: CompactionEvent[]): ProjectedSection => {\n const operations = collectOperations(events);\n const keyOf = (operation: StructuralOperation): string => {\n const path = isFileOperation(operation) ? pathOf(operation.args) : undefined;\n if (path) return `file\\0${operation.tool}\\0${path}`;\n const command = isBashOperation(operation) && typeof operation.args.command === \"string\"\n ? operation.args.command\n : undefined;\n if (command !== undefined) return `bash\\0${operation.tool}\\0${command}`;\n return `generic\\0${operation.ref}\\0${JSON.stringify(operation.args)}`;\n };\n const successes = operations\n .filter((operation) => operation.outcome === \"succeeded\")\n .map((operation) => ({ index: operation.index, key: keyOf(operation) }));\n const items: ErrorItem[] = [];\n\n for (const operation of operations) {\n if (operation.outcome === \"succeeded\") continue;\n const path = isFileOperation(operation) ? pathOf(operation.args) : undefined;\n const command = isBashOperation(operation) && typeof operation.args.command === \"string\"\n ? operation.args.command\n : undefined;\n const subject = path\n ? `${operation.ref} ${path}`\n : command !== undefined\n ? `${operation.ref}: ${truncate(firstLine(command), MAX_LINE)}`\n : operation.ref;\n const error = operation.error ? `: ${truncate(firstLine(operation.error), MAX_LINE)}` : `: ${operation.outcome}`;\n const key = keyOf(operation);\n const resolved = successes.some((success) => success.index > operation.index && success.key === key);\n items.push({\n index: operation.index,\n entryId: operation.address,\n description: `${subject}${error}`,\n resolved,\n });\n }\n\n if (items.length === 0) return { lines: [], omitted: 0 };\n const unresolved = items.filter((i) => !i.resolved).sort((a, b) => a.index - b.index);\n const resolved = items.filter((i) => i.resolved).sort((a, b) => a.index - b.index);\n const sampledUnresolved = sampleAddressed(unresolved, MAX_UNRESOLVED);\n const sampledResolved = sampleAddressed(resolved, MAX_RESOLVED);\n const lines: string[] = [];\n const append = (sampled: ReturnType<typeof sampleAddressed<ErrorItem>>, noun: string): void => {\n for (let index = 0; index < sampled.values.length; index++) {\n if (sampled.omitted > 0 && index === sampled.splitIndex) {\n lines.push(omissionLine(\n sampled.omitted,\n sampled.omittedFirstEntryId,\n sampled.omittedLastEntryId,\n noun,\n ));\n }\n const item = sampled.values[index]!;\n lines.push(`- ${item.description}${item.resolved ? \" [RESOLVED]\" : \"\"} [entry ${item.entryId}]`);\n }\n };\n append(sampledUnresolved, \"open error records\");\n append(sampledResolved, \"resolved error records\");\n return { lines, omitted: sampledUnresolved.omitted + sampledResolved.omitted };\n};\n\nexport const projectOutstanding = (events: CompactionEvent[]): string[] =>\n projectOutstandingWithMetadata(events).lines;\n\ninterface EarlierTurnAddress {\n entryId: string;\n contextLine: string;\n tools: string;\n run: string;\n}\n\n// [Earlier Turns] \u2014 sampled one-liners for turns before the latest summarized\n// one (which Current Status surfaces), plus tool-name histograms and an\n// entry-range address for any omitted middle turns.\nconst projectEarlierTurns = (events: CompactionEvent[]): ProjectedSection => {\n function* earlierTurns(): Generator<EarlierTurnAddress> {\n let currentContext: Extract<CompactionEvent, { kind: \"user\" | \"customMessage\" }> | undefined;\n let counts = new Map<string, number>();\n let order: string[] = [];\n let lastRun: FabricRunEvent | undefined;\n const completed = (): EarlierTurnAddress | undefined => {\n if (!currentContext) return undefined;\n return {\n entryId: currentContext.entryId,\n contextLine: currentContext.kind === \"user\"\n ? quoted(firstLine(currentContext.text), MAX_EARLIER_USER)\n : customMessageLine(currentContext, MAX_EARLIER_USER),\n tools: order.map((name) => `${name}:${counts.get(name) ?? 0}`).join(\" \"),\n run: lastRun\n ? `fabric:${quoted(clipUtf8(lastRun.name, 128), MAX_FABRIC_RUN_EARLIER_NAME)}\u2192${lastRun.outcome}`\n : \"\",\n };\n };\n for (const event of events) {\n if (event.kind === \"user\" || event.kind === \"customMessage\") {\n const turn = completed();\n if (turn) yield turn;\n currentContext = event;\n counts = new Map<string, number>();\n order = [];\n lastRun = undefined;\n continue;\n }\n if (!currentContext) continue;\n if (event.kind === \"fabricRun\") lastRun = event;\n const name = event.kind === \"toolCall\"\n ? (event.name === \"fabric_exec\" ? undefined : event.name)\n : event.kind === \"bash\"\n ? \"bash\"\n : event.kind === \"fabricOperation\"\n ? event.tool\n : undefined;\n if (!name) continue;\n if (!counts.has(name)) order.push(name);\n counts.set(name, (counts.get(name) ?? 0) + 1);\n }\n }\n\n const sampled = sampleAddressedFrom(earlierTurns(), MAX_EARLIER_TURNS);\n const lines: string[] = [];\n for (let index = 0; index < sampled.values.length; index++) {\n if (sampled.omitted > 0 && index === sampled.splitIndex) {\n lines.push(omissionLine(\n sampled.omitted,\n sampled.omittedFirstEntryId,\n sampled.omittedLastEntryId,\n \"earlier turns\",\n ));\n }\n const turn = sampled.values[index]!;\n const metadata = [turn.tools, turn.run].filter(Boolean).join(\" | \");\n lines.push(`${turn.contextLine}${metadata ? ` | ${metadata}` : \"\"} [entry ${turn.entryId}]`);\n }\n return { lines, omitted: sampled.omitted };\n};\n\n// [Current Status] \u2014 a bridge from the summarized window into the kept tail:\n// the last summarized user request, the last file-modifying tool call, and the\n// last assistant line. Only non-empty fields are emitted.\nconst projectStatus = (events: CompactionEvent[]): string[] => {\n const lastContext = [...events].reverse().find(\n (event): event is Extract<CompactionEvent, { kind: \"user\" | \"customMessage\" }> =>\n event.kind === \"user\" || event.kind === \"customMessage\",\n );\n const lines: string[] = [];\n if (lastContext?.kind === \"user\") {\n lines.push(`Last request: ${truncate(firstLine(lastContext.text), MAX_STATUS_LINE)}`);\n } else if (lastContext) {\n lines.push(`Last context: ${customMessageLine(lastContext, MAX_STATUS_LINE)}`);\n }\n let lastModify: { tool: string; args: Record<string, unknown> } | undefined;\n for (const operation of collectOperations(events)) {\n if (isFileOperation(operation) && MODIFYING_TOOLS.has(operation.tool)) lastModify = operation;\n }\n if (lastModify) {\n const path = pathOf(lastModify.args) ?? \"\";\n lines.push(`Last change: ${lastModify.tool}${path ? ` ${path}` : \"\"}`);\n }\n const lastRun = [...events]\n .reverse()\n .find((event): event is FabricRunEvent => event.kind === \"fabricRun\");\n if (lastRun) {\n lines.push(\n `Last execution: ${clipUtf8(truncate(lastRun.name, MAX_FABRIC_RUN_STATUS_NAME), 256)} \u2192 ${lastRun.outcome} [entry ${fabricRunPointer(lastRun)}]`,\n );\n }\n const lastAssistant = [...events]\n .reverse()\n .find((e): e is Extract<CompactionEvent, { kind: \"assistantText\" }> => e.kind === \"assistantText\");\n if (lastAssistant) {\n const text = truncate(firstLine(lastAssistant.text), MAX_STATUS_LINE);\n if (text) lines.push(`Last note: ${text}`);\n }\n return lines;\n};\n\nconst summarizeArgs = (name: string, args: Record<string, unknown>): string => {\n if (name === \"fabric_exec\") return \"structured execution\";\n const primary =\n name === \"bash\" ? args.command ?? args.cmd ?? args.shell\n : name === \"grep\" ? args.pattern ?? args.query ?? args.regex\n : name === \"find\" ? args.pattern\n : pathOf(args);\n if (typeof primary === \"string\" && primary.trim()) {\n return truncate(firstLine(primary), MAX_TRANSCRIPT_CMD);\n }\n const entries = Object.entries(args).slice(0, 2);\n return entries.map(([key, value]) => `${key}=${truncate(String(value), 40)}`).join(\" \");\n};\n\n// Brief transcript \u2014 the \"collapsed transcript\" tier of graded decay. A\n// rolling window of the last 40 events rendered as one-liners, each prefixed\n// with its stable `(#N)` reference so the agent can point back at a specific\n// event without storing its content (principle 0).\nconst projectTranscript = (events: CompactionEvent[]): ProjectedSection => {\n const completedFabricCalls = new Set(\n events\n .filter((event): event is FabricRunEvent => event.kind === \"fabricRun\")\n .map((event) => event.toolCallId),\n );\n const transcriptEvents = events.filter((event) => {\n if (event.kind === \"toolCall\") {\n return event.name !== \"fabric_exec\" || !completedFabricCalls.has(event.toolCallId);\n }\n if (event.kind === \"toolResult\") {\n return event.toolName !== \"fabric_exec\" || !completedFabricCalls.has(event.toolCallId);\n }\n return true;\n });\n const window = transcriptEvents.slice(-TRANSCRIPT_WINDOW);\n const lines: string[] = [];\n const omitted = transcriptEvents.length - window.length;\n if (omitted > 0) {\n lines.push(omissionLine(\n omitted,\n transcriptEvents[0]?.entryId,\n transcriptEvents[omitted - 1]?.entryId,\n \"transcript events\",\n ));\n }\n for (const e of window) {\n const ref = `(#${e.index})`;\n if (e.kind === \"user\") {\n lines.push(`${ref} user: ${truncate(firstLine(e.text), MAX_TRANSCRIPT_LINE)}`);\n } else if (e.kind === \"assistantText\") {\n lines.push(`${ref} assistant: ${truncate(firstLine(e.text), MAX_TRANSCRIPT_LINE)}`);\n } else if (e.kind === \"customMessage\") {\n lines.push(`${ref} ${customMessageLine(e, MAX_TRANSCRIPT_LINE)}`);\n } else if (e.kind === \"toolCall\") {\n lines.push(`${ref} ${e.name}(${summarizeArgs(e.name, e.args)})`);\n } else if (e.kind === \"toolResult\") {\n const status = e.isError ? \"error\" : \"ok\";\n lines.push(`${ref} \u2192 ${status}: ${truncate(firstLine(e.text), MAX_TRANSCRIPT_LINE)}`);\n } else if (e.kind === \"bash\") {\n const status = e.isError ? \"error\" : \"ok\";\n lines.push(`${ref} bash(${truncate(firstLine(e.command), MAX_TRANSCRIPT_CMD)}) \u2192 ${status}`);\n } else if (e.kind === \"fabricRun\") {\n lines.push(\n `${ref} fabric_exec ${quoted(clipUtf8(e.name, 160), MAX_FABRIC_RUN_TRANSCRIPT_NAME)} \u2192 ${e.outcome} [entry ${fabricRunPointer(e)}]`,\n );\n } else if (e.kind === \"fabricPhase\") {\n lines.push(`${ref} phase(${truncate(e.phase, MAX_TRANSCRIPT_CMD)}) [${e.address}]`);\n } else if (e.kind === \"fabricOperation\") {\n lines.push(`${ref} ${e.ref}(${summarizeArgs(e.tool, e.args)}) \u2192 ${e.outcome} [${e.address}]`);\n }\n }\n return { lines, omitted };\n};\n\nexport const projectWithMetadata = (events: CompactionEvent[], retainedDialogue: CompactionEvent[] = []): ProjectionResult => {\n const exchanges = recentDialogue(events, retainedDialogue);\n const dialogue = projectDialogue(exchanges);\n const goal = projectGoal(events, new Set(exchanges.map(({ user }) => user.entryId)));\n const files = projectFiles(events);\n const activity = projectActivity(events);\n const outstanding = projectOutstandingWithMetadata(events);\n const earlierTurns = projectEarlierTurns(events);\n const transcript = projectTranscript(events);\n return {\n sections: {\n dialogue: dialogue.lines,\n goal: goal.lines,\n files: files.lines,\n activity: activity.lines,\n outstanding: outstanding.lines,\n earlierTurns: earlierTurns.lines,\n status: projectStatus(events),\n transcript: transcript.lines,\n },\n omittedCounts: {\n goal: goal.omitted,\n dialogueBytes: dialogue.omittedBytes,\n files: files.omitted,\n activity: activity.omitted,\n outstanding: outstanding.omitted,\n earlierTurns: earlierTurns.omitted,\n transcript: transcript.omitted,\n },\n };\n};\n\nexport const project = (events: CompactionEvent[]): Sections =>\n projectWithMetadata(events).sections;\n", "import { boundedExcerpt, clipUtf8, MAX_SUMMARY_BYTES, utf8Bytes } from \"./bounds.js\";\nimport type { Sections } from \"./projections.js\";\n\n// These are per-block ceilings, not reservations. Historical blocks share\n// the space left by actual protected content inside the global ceiling.\nexport const SUMMARY_SECTIONS: { key: keyof Sections; header: string; maxBytes: number }[] = [\n { key: \"dialogue\", header: \"[Recent user directions and discussion]\", maxBytes: 12288 },\n { key: \"goal\", header: \"[Historical requests]\", maxBytes: 4096 },\n { key: \"files\", header: \"[Files And Changes]\", maxBytes: 4608 },\n { key: \"activity\", header: \"[Fabric Activity]\", maxBytes: 2048 },\n { key: \"outstanding\", header: \"[Outstanding Context]\", maxBytes: 4608 },\n { key: \"earlierTurns\", header: \"[Earlier Turns]\", maxBytes: 3072 },\n { key: \"status\", header: \"[Current Status]\", maxBytes: 2048 },\n];\n\nexport const CARRY_FORWARD_HEADER = \"[Carry Forward]\";\n\nconst REQUEST_MAX_BYTES = 3072;\nconst CARRY_MAX_BYTES = 3072;\nconst TRANSCRIPT_MAX_BYTES = 5120;\nconst FOOTER_MAX_BYTES = 1536;\nconst MAX_INPUT_LINES_PER_SECTION = 128;\nconst MAX_RENDERED_LINE_BYTES = 1024;\n\nexport interface RenderOptions {\n firstEntryId: string;\n lastEntryId: string;\n lastTimestamp: string;\n requestLines?: string[];\n /** Persistent carry-forward focus; rendered in every summary until cleared. */\n carryLines?: string[];\n summaryKind?: \"compaction\" | \"branch\";\n}\n\nconst POINTER_LINE =\n \"For exact pre-summary history, use memory.recall on this range, then memory.expand by stable entry or operation address.\";\n\nconst sampledLines = (lines: readonly string[], keep: number): string[] => {\n if (lines.length <= keep) return [...lines];\n const earliest = Math.ceil(keep / 2);\n const latest = Math.floor(keep / 2);\n return [\n ...lines.slice(0, earliest),\n `\u2026 omitted ${lines.length - keep} rendered lines`,\n ...lines.slice(lines.length - latest),\n ];\n};\n\nconst boundedBlock = (header: string, sourceLines: readonly string[], maxBytes: number): string => {\n const clipped = sourceLines.map((line) => clipUtf8(line, MAX_RENDERED_LINE_BYTES));\n const capped = sampledLines(clipped, Math.min(clipped.length, MAX_INPUT_LINES_PER_SECTION));\n for (let keep = capped.length; keep >= 0; keep--) {\n const lines = sampledLines(capped, keep);\n const block = [header, ...lines].join(\"\\n\");\n if (utf8Bytes(block) <= maxBytes) return block;\n }\n return clipUtf8(header, maxBytes);\n};\n\ninterface HistoryBlock {\n header: string;\n lines: readonly string[];\n maxBytes: number;\n}\n\nconst boundedHistory = (blocks: HistoryBlock[], maxBytes: number): string[] => {\n const candidates = blocks.map((block) => {\n const text = boundedBlock(block.header, block.lines, block.maxBytes);\n const bytes = utf8Bytes(text);\n const minimum = block.lines.length === 1 ? bytes\n : Math.min(bytes, utf8Bytes([block.header, ...sampledLines(block.lines, 0)].join(\"\\n\")));\n return { ...block, text, bytes, minimum };\n });\n const total = candidates.reduce((sum, block) => sum + block.bytes, 0);\n if (total <= maxBytes) return candidates.map(({ text }) => text);\n\n // Reserve headers/omission markers (or complete single-line blocks), then divide\n // remaining space proportionally to capped demand. Sampling slack goes to\n // later blocks rather than being reserved for content we did not render.\n const minimum = candidates.reduce((sum, block) => sum + block.minimum, 0);\n let remaining = maxBytes - minimum;\n let demand = total - minimum;\n return candidates.map((block) => {\n const wanted = block.bytes - block.minimum;\n const extra = demand === 0 ? 0 : Math.min(wanted, Math.floor(remaining * wanted / demand));\n const text = boundedBlock(block.header, block.lines, block.minimum + extra);\n remaining -= utf8Bytes(text) - block.minimum;\n demand -= wanted;\n return text;\n });\n};\n\n// Dialogue and explicit requests are not historical line samples. Keep every\n// item; only shorten text when the entire block exceeds its byte allocation.\nconst protectedBlock = (header: string, items: readonly string[], maxBytes: number): { text: string; omittedBytes: number } => {\n const text = [header, ...items].join(\"\\n\\n\");\n if (utf8Bytes(text) <= maxBytes) return { text, omittedBytes: 0 };\n let remaining = Math.max(0, maxBytes - utf8Bytes(header) - 2 * items.length);\n const share = Math.floor(remaining / items.length);\n const budgets = items.map((item) => Math.min(utf8Bytes(item), share));\n remaining -= budgets.reduce((sum, bytes) => sum + bytes, 0);\n let omittedBytes = 0;\n const excerpts = items.map((item, index) => {\n const extra = Math.min(remaining, utf8Bytes(item) - budgets[index]!);\n remaining -= extra;\n const excerpt = boundedExcerpt(item, budgets[index]! + extra);\n omittedBytes += excerpt.omittedBytes;\n return excerpt.text;\n });\n return { text: [header, ...excerpts].join(\"\\n\\n\"), omittedBytes };\n};\n\nexport interface RenderedSummary {\n summary: string;\n requestOmittedBytes: number;\n dialogueOmittedBytes: number;\n carryOmittedBytes: number;\n}\n\nexport const renderSummaryWithMetadata = (sections: Sections, options: RenderOptions): RenderedSummary => {\n const blocks: string[] = [];\n const history: HistoryBlock[] = [];\n let requestOmittedBytes = 0;\n let dialogueOmittedBytes = 0;\n let carryOmittedBytes = 0;\n const request = (): void => {\n if (options.requestLines?.length) {\n const rendered = protectedBlock(\"[Compaction Request]\", options.requestLines, REQUEST_MAX_BYTES);\n blocks.push(rendered.text);\n requestOmittedBytes = rendered.omittedBytes;\n }\n if (options.carryLines?.length) {\n const rendered = protectedBlock(CARRY_FORWARD_HEADER, options.carryLines, CARRY_MAX_BYTES);\n blocks.push(rendered.text);\n carryOmittedBytes = rendered.omittedBytes;\n }\n };\n for (const { key, header, maxBytes } of SUMMARY_SECTIONS) {\n const lines = sections[key];\n if (key === \"dialogue\") {\n if (lines.length > 0) {\n const rendered = protectedBlock(header, lines, maxBytes);\n blocks.push(rendered.text);\n dialogueOmittedBytes = rendered.omittedBytes;\n }\n request();\n } else if (lines.length > 0) {\n history.push({ header, lines, maxBytes });\n }\n }\n\n if (sections.transcript.length > 0) {\n history.push({ header: \"---\", lines: sections.transcript, maxBytes: TRANSCRIPT_MAX_BYTES });\n }\n\n const timestamp = options.lastTimestamp || \"(unknown time)\";\n const range = options.firstEntryId || options.lastEntryId\n ? `${options.firstEntryId || \"(start)\"} \u2192 ${options.lastEntryId || \"(end)\"}`\n : \"(no entries)\";\n const footer = options.summaryKind === \"branch\"\n ? `[branch summarized ${timestamp}; structural source entries ${range}]`\n : `[compacted ${timestamp}; cumulative source entries ${range}]`;\n const footerBlock = boundedBlock(\"---\", [footer, POINTER_LINE], FOOTER_MAX_BYTES);\n // Count every separator plus the final newline before allocating history.\n const framingBytes = utf8Bytes(footerBlock) + 2 * (blocks.length + history.length) + 1;\n const protectedBytes = blocks.reduce((sum, block) => sum + utf8Bytes(block), 0);\n blocks.push(...boundedHistory(history, MAX_SUMMARY_BYTES - framingBytes - protectedBytes), footerBlock);\n\n const summary = `${blocks.join(\"\\n\\n\")}\\n`;\n return {\n summary: utf8Bytes(summary) <= MAX_SUMMARY_BYTES ? summary : `${clipUtf8(summary, MAX_SUMMARY_BYTES - 1, \"\")}\\n`,\n requestOmittedBytes,\n dialogueOmittedBytes,\n carryOmittedBytes,\n };\n};\n\nexport const renderSummary = (sections: Sections, options: RenderOptions): string =>\n renderSummaryWithMetadata(sections, options).summary;\n", "import type { SessionEntry } from \"@earendil-works/pi-coding-agent\";\nimport type { FabricTraceJsonValue } from \"../audit/trace.js\";\nimport { clipUtf8, sampleAddressed } from \"./bounds.js\";\nimport {\n FABRIC_BRANCH_SUMMARY_KIND,\n FABRIC_BRANCH_RUN_DESCRIPTION_MAX_BYTES,\n FABRIC_BRANCH_RUN_NAME_MAX_BYTES,\n FABRIC_BRANCH_SUMMARY_MAX_BYTES,\n FABRIC_BRANCH_SUMMARY_MAX_FACTS,\n FABRIC_BRANCH_SUMMARY_VERSION,\n type FabricBranchFactV2,\n type FabricBranchOperationFactV1,\n type FabricBranchSummaryDetailsV2,\n} from \"./branch-details.js\";\nimport { NO_BUILTIN_ENRICHERS, runEnrichers, type CompactionEnricher } from \"./enrichers.js\";\nimport { decodeCompactionInstructions } from \"./instructions.js\";\nimport { normalizeEntries, type CompactionEvent, type ToolCallEvent } from \"./normalize.js\";\nimport { projectWithMetadata } from \"./projections.js\";\nimport { renderSummaryWithMetadata, SUMMARY_SECTIONS } from \"./render.js\";\n\nconst asJsonObject = (value: Record<string, unknown>): Record<string, FabricTraceJsonValue> | undefined => {\n try {\n const cloned = JSON.parse(JSON.stringify(value)) as unknown;\n return cloned && typeof cloned === \"object\" && !Array.isArray(cloned)\n ? cloned as Record<string, FabricTraceJsonValue>\n : undefined;\n } catch {\n return undefined;\n }\n};\n\nconst directOperationFact = (\n call: ToolCallEvent,\n outcome: \"succeeded\" | \"failed\",\n error?: string,\n): FabricBranchOperationFactV1 | undefined => {\n if (call.name === \"fabric_exec\") return undefined;\n const args = asJsonObject(call.args);\n if (!args) return undefined;\n const subordinal = `call:${call.toolCallId}`;\n return {\n kind: \"operation\",\n entryId: call.entryId,\n subordinal,\n address: `${call.entryId}/${subordinal}`,\n ref: call.name,\n action: call.name,\n tool: call.name,\n args,\n outcome,\n ...(error ? { error: clipUtf8(error, 8 * 1024) } : {}),\n };\n};\n\nconst factsFromEvents = (events: CompactionEvent[]): FabricBranchFactV2[] => {\n const facts: FabricBranchFactV2[] = [];\n const calls = new Map<string, ToolCallEvent>();\n for (const event of events) {\n if (event.kind === \"toolCall\") calls.set(event.toolCallId, event);\n }\n for (const event of events) {\n if (event.kind === \"user\") {\n facts.push({\n kind: \"user\",\n entryId: event.entryId,\n subordinal: \"user\",\n address: `${event.entryId}/user`,\n text: clipUtf8(event.text, 2 * 1024),\n });\n } else if (event.kind === \"customMessage\") {\n facts.push({\n kind: \"customMessage\",\n entryId: event.entryId,\n subordinal: \"custom-message\",\n address: `${event.entryId}/custom-message`,\n customType: clipUtf8(event.customType, 256),\n text: clipUtf8(event.text, 4 * 1024),\n display: event.display,\n ...(event.details !== undefined ? { details: event.details } : {}),\n });\n } else if (event.kind === \"fabricPhase\") {\n facts.push({\n kind: \"phase\",\n entryId: event.entryId,\n subordinal: event.subordinal,\n address: event.address,\n phase: event.phase,\n });\n } else if (event.kind === \"fabricRun\") {\n facts.push({\n kind: \"fabricRun\",\n entryId: event.entryId,\n subordinal: event.subordinal,\n address: event.address,\n name: clipUtf8(event.name, FABRIC_BRANCH_RUN_NAME_MAX_BYTES),\n ...(event.description !== undefined\n ? { description: clipUtf8(event.description, FABRIC_BRANCH_RUN_DESCRIPTION_MAX_BYTES) }\n : {}),\n outcome: event.outcome,\n });\n } else if (event.kind === \"fabricOperation\") {\n facts.push({\n kind: \"operation\",\n entryId: event.entryId,\n subordinal: event.subordinal,\n address: event.address,\n ref: event.ref,\n ...(event.provider ? { provider: event.provider } : {}),\n ...(event.action ? { action: event.action } : {}),\n tool: event.tool,\n args: event.args,\n outcome: event.outcome,\n ...(event.error !== undefined ? { error: event.error } : {}),\n ...(event.result !== undefined ? { result: event.result } : {}),\n });\n } else if (event.kind === \"toolResult\" && event.toolName !== \"bash\") {\n const call = event.toolCallId ? calls.get(event.toolCallId) : undefined;\n if (!call) continue;\n const fact = directOperationFact(call, event.isError ? \"failed\" : \"succeeded\", event.isError ? event.text : undefined);\n if (fact) facts.push(fact);\n } else if (event.kind === \"bash\") {\n const call = event.toolCallId ? calls.get(event.toolCallId) : undefined;\n if (call) {\n const fact = directOperationFact(call, event.isError ? \"failed\" : \"succeeded\", event.error);\n if (fact) facts.push(fact);\n } else {\n const subordinal = \"bash\";\n facts.push({\n kind: \"operation\",\n entryId: event.entryId,\n subordinal,\n address: `${event.entryId}/${subordinal}`,\n ref: \"bash\",\n action: \"bash\",\n tool: \"bash\",\n args: { command: event.command },\n outcome: event.isError ? \"failed\" : \"succeeded\",\n ...(event.error ? { error: clipUtf8(event.error, 8 * 1024) } : {}),\n });\n }\n }\n }\n return facts;\n};\n\nconst serializedBytes = (value: unknown): number => Buffer.byteLength(JSON.stringify(value), \"utf8\");\n\nconst boundedDetails = (\n sourceEntries: SessionEntry[],\n facts: FabricBranchFactV2[],\n sections: string[],\n request: { text: string; sourceBytes: number; truncated: boolean },\n oldLeafId: string | null,\n): FabricBranchSummaryDetailsV2 => {\n const sampled = sampleAddressed(facts, FABRIC_BRANCH_SUMMARY_MAX_FACTS);\n const details: FabricBranchSummaryDetailsV2 = {\n kind: FABRIC_BRANCH_SUMMARY_KIND,\n version: FABRIC_BRANCH_SUMMARY_VERSION,\n source: {\n firstEntryId: sourceEntries[0]?.id ?? \"\",\n lastEntryId: sourceEntries.at(-1)?.id ?? \"\",\n entryCount: sourceEntries.length,\n oldLeafId,\n },\n facts: sampled.values,\n omittedFacts: sampled.omitted,\n sections,\n request: {\n text: request.text,\n sourceBytes: request.sourceBytes,\n truncated: request.truncated,\n },\n };\n for (let index = details.facts.length - 1; serializedBytes(details) > FABRIC_BRANCH_SUMMARY_MAX_BYTES && index >= 0; index--) {\n const fact = details.facts[index]!;\n if (fact.kind === \"operation\" && fact.result !== undefined) delete fact.result;\n }\n while (serializedBytes(details) > FABRIC_BRANCH_SUMMARY_MAX_BYTES && details.facts.length > 0) {\n const middle = Math.floor(details.facts.length / 2);\n details.facts.splice(middle, 1);\n details.omittedFacts += 1;\n }\n return details;\n};\n\nexport interface FabricBranchSummaryCompilation {\n summary: string;\n details: FabricBranchSummaryDetailsV2;\n}\n\nexport const compileFabricBranchSummary = (\n entriesToSummarize: SessionEntry[],\n customInstructions?: string,\n enrichers: readonly CompactionEnricher[] = NO_BUILTIN_ENRICHERS,\n oldLeafId: string | null = null,\n): FabricBranchSummaryCompilation | undefined => {\n const instructions = decodeCompactionInstructions(customInstructions);\n if (!instructions.ok) return undefined;\n const events = normalizeEntries(entriesToSummarize);\n if (events.length === 0) return undefined;\n const projected = projectWithMetadata(events);\n runEnrichers(enrichers, events, projected.sections);\n const sections = SUMMARY_SECTIONS\n .filter(({ key }) => projected.sections[key].length > 0)\n .map(({ header }) => header);\n if (instructions.requestLines.length > 0) {\n sections.splice(projected.sections.dialogue.length > 0 ? 1 : 0, 0, \"[Compaction Request]\");\n }\n const rendered = renderSummaryWithMetadata(projected.sections, {\n firstEntryId: entriesToSummarize[0]?.id ?? \"\",\n lastEntryId: entriesToSummarize.at(-1)?.id ?? \"\",\n lastTimestamp: entriesToSummarize.at(-1)?.timestamp ?? \"\",\n ...(instructions.requestLines.length > 0 ? { requestLines: instructions.requestLines } : {}),\n summaryKind: \"branch\",\n });\n const request = {\n text: instructions.requestLines.join(\"\\n\"),\n sourceBytes: instructions.policy.sourceBytes,\n truncated: instructions.policy.truncated || rendered.requestOmittedBytes > 0,\n };\n return {\n summary: rendered.summary,\n details: boundedDetails(entriesToSummarize, factsFromEvents(events), sections, request, oldLeafId),\n };\n};\n", "import type { SessionEntry } from \"@earendil-works/pi-coding-agent\";\nimport { canonicalizeText } from \"./bounds.js\";\nimport {\n compactionRequestBoundsError,\n MAX_PRESERVE_ITEM_CHARS,\n MAX_PRESERVE_ITEMS,\n} from \"./instructions.js\";\n\n// Carry-forward focus: a small, bounded list of facts the deterministic\n// compactor renders into EVERY summary until it is cleared. Unlike the\n// one-shot `preserve` of a compaction request, the list lives in the session\n// log as a custom entry, so the latest entry on the active branch is the\n// current value. Reload, restart and tree navigation replay it by reading the\n// branch; there is no in-memory copy to lose or to go stale.\n\nexport const COMPACTION_CARRY_ENTRY_TYPE = \"pi-fabric-compact-carry\";\nexport const MAX_CARRY_ITEMS = MAX_PRESERVE_ITEMS;\nexport const MAX_CARRY_ITEM_CHARS = MAX_PRESERVE_ITEM_CHARS;\n\nexport interface CompactionCarryEntryData {\n version: 1;\n items: string[];\n}\n\nexport interface CompactionCarryUpdate {\n items?: string[];\n add?: string[];\n remove?: string[];\n clear?: boolean;\n}\n\nconst isStringArray = (value: unknown): value is string[] =>\n Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\nconst carryBoundsError = (items: readonly string[]): string | undefined => {\n if (items.length > MAX_CARRY_ITEMS) return `compact carry exceeds ${MAX_CARRY_ITEMS} items`;\n if (items.some((item) => item.trim() === \"\")) return \"compact carry items must be non-empty\";\n return compactionRequestBoundsError({ preserve: [...items] })?.message.replace(\n \"typed compaction preserve\",\n \"compact carry\",\n );\n};\n\n/** Validates a persisted entry; a malformed one fails closed to no carry. */\nexport const decodeCarryEntryData = (data: unknown): string[] | undefined => {\n if (data === null || typeof data !== \"object\" || Array.isArray(data)) return undefined;\n const record = data as Record<string, unknown>;\n if (record.version !== 1 || !isStringArray(record.items)) return undefined;\n return carryBoundsError(record.items) === undefined ? [...record.items] : undefined;\n};\n\n// The latest carry entry on the branch is authoritative, including an empty\n// (cleared) list. A malformed latest entry yields an empty list rather than\n// resurrecting an older value the user may have replaced.\nexport const latestCarryItems = (entries: readonly SessionEntry[]): string[] => {\n for (let index = entries.length - 1; index >= 0; index--) {\n const entry = entries[index]!;\n if (entry.type !== \"custom\" || entry.customType !== COMPACTION_CARRY_ENTRY_TYPE) continue;\n return decodeCarryEntryData(entry.data) ?? [];\n }\n return [];\n};\n\n// Order: clear, replace, remove, then add. Exact-string removal; additions\n// skip items already present so repeated adds are idempotent.\nexport const applyCarryUpdate = (\n current: readonly string[],\n update: CompactionCarryUpdate,\n): string[] => {\n let next = update.clear === true ? [] : [...current];\n if (update.items !== undefined) next = [...update.items];\n if (update.remove !== undefined) {\n const removed = new Set(update.remove);\n next = next.filter((item) => !removed.has(item));\n }\n for (const item of update.add ?? []) {\n if (!next.includes(item)) next.push(item);\n }\n next = next.filter((item, index) => next.indexOf(item) === index);\n const error = carryBoundsError(next);\n if (error) throw new Error(error);\n return next;\n};\n\nexport const isCarryUpdate = (update: CompactionCarryUpdate): boolean =>\n update.clear === true\n || update.items !== undefined\n || update.add !== undefined\n || update.remove !== undefined;\n\nexport const sameCarryItems = (left: readonly string[], right: readonly string[]): boolean =>\n left.length === right.length && left.every((item, index) => item === right[index]);\n\n/** Summary lines for the protected `[Carry Forward]` block. */\nexport const carryRequestLines = (items: readonly string[]): string[] =>\n items.flatMap((item, index) => {\n const text = canonicalizeText(item, MAX_CARRY_ITEM_CHARS).text;\n return text ? [`- ${text} [carry:${index}]`] : [];\n });\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAOO;;;ACHP,IAAM,wBAAwB;AAEvB,IAAM,8BAA8B;AAAA,EACzC,SAAS;AAAA,EACT,eAAe;AAAA,EACf,kBAAkB;AACpB;AAkBA,IAAM,eAAe,CAAC,YAAkD;AACtE,MAAI,OAAO,YAAY,SAAU,QAAQ,WAAW,CAAC;AACrD,SAAO,CAAC;AACV;AAEA,IAAM,mCAAmC,CAAC,YAA6B;AACrE,MAAI,OAAO,YAAY,UAAU;AAC/B,WAAO,QAAQ;AAAA,EACjB;AACA,MAAI,QAAQ;AACZ,aAAW,SAAS,aAAa,OAAO,GAAG;AACzC,QAAI,MAAM,SAAS,UAAU,MAAM,MAAM;AACvC,eAAS,MAAM,KAAK;AAAA,IACtB,WAAW,MAAM,SAAS,SAAS;AACjC,eAAS;AAAA,IACX;AAAA,EACF;AACA,SAAO;AACT;AAEA,IAAM,aAAa,CAAC,UAA4B,OAAO,UAAU,WAAW,MAAM,SAAS;AAEpF,IAAM,iBAAiB,CAAC,YAAkC;AAC/D,MAAI,QAAQ;AACZ,UAAQ,QAAQ,MAAM;AAAA,IACpB,KAAK,QAAQ;AACX,cAAQ,iCAAiC,QAAQ,OAAO;AACxD,aAAO,KAAK,KAAK,QAAQ,CAAC;AAAA,IAC5B;AAAA,IACA,KAAK,aAAa;AAChB,iBAAW,SAAS,aAAa,QAAQ,OAAO,GAAG;AACjD,YAAI,MAAM,SAAS,QAAQ;AACzB,mBAAS,WAAW,MAAM,IAAI;AAAA,QAChC,WAAW,MAAM,S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