pi-fabric 0.56.0 → 0.58.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +1 -1
  2. package/dist/activity/store.d.ts +1 -1
  3. package/dist/activity/store.d.ts.map +1 -1
  4. package/dist/audit/details.d.ts +34 -3
  5. package/dist/audit/details.d.ts.map +1 -1
  6. package/dist/chunks/{chunk-SDE4YZSA.js → chunk-2SF432HH.js} +24 -4
  7. package/dist/chunks/chunk-2SF432HH.js.map +7 -0
  8. package/dist/chunks/chunk-4VEGQHZO.js +354 -0
  9. package/dist/chunks/chunk-4VEGQHZO.js.map +7 -0
  10. package/dist/chunks/{chunk-EP3NGVLI.js → chunk-6B5TUG4G.js} +3 -3
  11. package/dist/chunks/{chunk-2FRLLBX5.js → chunk-HJ22TAZK.js} +2 -2
  12. package/dist/chunks/{chunk-2FRLLBX5.js.map → chunk-HJ22TAZK.js.map} +1 -1
  13. package/dist/chunks/{chunk-KNFENYPO.js → chunk-IPOARFXT.js} +13 -160
  14. package/dist/chunks/chunk-IPOARFXT.js.map +7 -0
  15. package/dist/chunks/{chunk-HED3CMLD.js → chunk-PCTZDCIV.js} +2 -2
  16. package/dist/chunks/{chunk-4MLY2Z7C.js → chunk-UGSIRJSH.js} +4 -4
  17. package/dist/chunks/{chunk-4MLY2Z7C.js.map → chunk-UGSIRJSH.js.map} +2 -2
  18. package/dist/chunks/{dashboard-VRYP7LCL.js → dashboard-ZDUPQUYD.js} +3 -2
  19. package/dist/chunks/{dashboard-VRYP7LCL.js.map → dashboard-ZDUPQUYD.js.map} +1 -1
  20. package/dist/chunks/{fabric-runtime-state-S5HUGAMJ.js → fabric-runtime-state-MRKNCHG2.js} +14 -8
  21. package/dist/chunks/fabric-runtime-state-MRKNCHG2.js.map +7 -0
  22. package/dist/chunks/{settings-4TNPIKSY.js → settings-ZHGNXFDA.js} +7 -4
  23. package/dist/chunks/settings-ZHGNXFDA.js.map +7 -0
  24. package/dist/compaction/hook.js +2 -1
  25. package/dist/compaction/normalize.d.ts.map +1 -1
  26. package/dist/execution-service.d.ts.map +1 -1
  27. package/dist/fabric-exec-tool.d.ts.map +1 -1
  28. package/dist/index.js +48 -19
  29. package/dist/index.js.map +3 -3
  30. package/dist/residency/host.js +5 -4
  31. package/dist/residency/host.js.map +1 -1
  32. package/dist/ui/core-tool-render.d.ts.map +1 -1
  33. package/dist/ui/fabric-code-parser.d.ts +1 -0
  34. package/dist/ui/fabric-code-parser.d.ts.map +1 -1
  35. package/dist/ui/fabric-render.d.ts +2 -0
  36. package/dist/ui/fabric-render.d.ts.map +1 -1
  37. package/dist/ui/fabric-title-hint.d.ts +2 -0
  38. package/dist/ui/fabric-title-hint.d.ts.map +1 -0
  39. package/dist/ui/settings.d.ts.map +1 -1
  40. package/docs/audit-trace.md +6 -3
  41. package/docs/configuration.md +2 -2
  42. package/package.json +1 -1
  43. package/dist/chunks/chunk-KNFENYPO.js.map +0 -7
  44. package/dist/chunks/chunk-SDE4YZSA.js.map +0 -7
  45. package/dist/chunks/fabric-runtime-state-S5HUGAMJ.js.map +0 -7
  46. package/dist/chunks/settings-4TNPIKSY.js.map +0 -7
  47. /package/dist/chunks/{chunk-EP3NGVLI.js.map → chunk-6B5TUG4G.js.map} +0 -0
  48. /package/dist/chunks/{chunk-HED3CMLD.js.map → chunk-PCTZDCIV.js.map} +0 -0
package/README.md CHANGED
@@ -119,7 +119,7 @@ Fabric includes a live activity surface in Pi:
119
119
  - A compact widget above the chat (like `pi-supervisor`) whose header follows the current phase while its rows show active/completed agents, active actors, and their recent nested tool or code-change activity.
120
120
  - `/fabric` (or `/fabric dashboard`): opens the **Activity** and **Topology** views. The user-facing Pi session appears as **Main**. You can queue or steer participants and inspect the project topology.
121
121
  - `/fabric settings`: mirrors Pi's `/settings` and writes changes to `fabric.json`.
122
- - `Tool display` (`full` or `compact`) is configured under `/fabric settings` → **UI**; compact elevates the declared display intent, hides the outer TypeScript, and applies to the current transcript immediately.
122
+ - `Tool display` (`compact` by default, or `full`) is configured under `/fabric settings` → **UI**; compact elevates the declared display intent, hides the outer TypeScript, and applies to the current transcript immediately. Pi's tool-expand keybinding (`ctrl+o` by default) expands a compact card to the full transcript.
123
123
 
124
124
  See the [interface & commands reference](docs/interface.md) for every view, keybinding, and slash command.
125
125
 
@@ -5,7 +5,7 @@ export declare class FabricActivityStore {
5
5
  revision(): number;
6
6
  subscribe(listener: () => void): () => void;
7
7
  reset(): void;
8
- start(id: string, display?: FabricRunDisplay): FabricActivityRun;
8
+ start(id: string, display?: FabricRunDisplay, nameHint?: string): FabricActivityRun;
9
9
  resume(runId: string): void;
10
10
  configure(runId: string, display: FabricRunDisplay): FabricActivityRun;
11
11
  phase(runId: string, input: FabricPhaseInput): FabricActivityPhase;
@@ -1 +1 @@
1
- {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/activity/store.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,KAAK,EAEV,wBAAwB,EACxB,kBAAkB,EAClB,uBAAuB,EAGvB,mBAAmB,EACnB,iBAAiB,EAEjB,gBAAgB,EAChB,gBAAgB,EACjB,MAAM,YAAY,CAAC;AAiHpB,qBAAa,mBAAmB;;IAM9B,QAAQ,IAAI,MAAM;IAIlB,SAAS,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI;IAK3C,KAAK,IAAI,IAAI;IAOb,KAAK,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB,GAAG,iBAAiB;IAwBpE,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAS3B,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,gBAAgB,GAAG,iBAAiB;IAWtE,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB,GAAG,mBAAmB;IAyDlE,UAAU,CAAC,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AC,EAAE,OAAO,CAAC;QAAC,OAAO,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAC/E,IAAI;IAsCP,MAAM,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI;IAgC7D,IAAI,IAAI,iBAAiB,EAAE;IAQ3B,YAAY,IAAI,iBAAiB,EAAE;IAInC,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,iBAAiB,GAAG,SAAS;CA6C/C"}
@@ -3,10 +3,32 @@ export declare const FABRIC_EXECUTION_DETAILS_MAX_BYTES: number;
3
3
  export interface FabricPersistedExecutionDetailsV1 {
4
4
  success: boolean;
5
5
  trace: FabricExecutionTraceV1;
6
+ /** Rich render audits persisted verbatim (minus in-memory media) so a resumed transcript re-renders — and expands — exactly like the live one. */
7
+ audits: FabricLegacyRenderAudit[];
8
+ phases: string[];
9
+ error?: string;
6
10
  outputFormat?: "yaml" | "json";
7
11
  outputFormatStartLine?: number;
8
12
  outputFormatLines?: number;
9
13
  }
14
+ /**
15
+ * The audit fields that cross into the session record; read back by
16
+ * {@link legacyAudit}. In-memory-only payloads (image blocks, media notes,
17
+ * correlation ids) never persist.
18
+ */
19
+ export interface FabricPersistableAuditInput {
20
+ ref: string;
21
+ tool?: string;
22
+ provider?: string;
23
+ success?: boolean;
24
+ error?: string;
25
+ args?: Record<string, unknown>;
26
+ result?: unknown;
27
+ resultTruncated?: boolean;
28
+ preview?: unknown;
29
+ startedAt?: number;
30
+ endedAt?: number;
31
+ }
10
32
  export interface FabricLegacyRenderAudit {
11
33
  ref: string;
12
34
  tool?: string;
@@ -17,6 +39,8 @@ export interface FabricLegacyRenderAudit {
17
39
  result?: unknown;
18
40
  resultTruncated?: boolean;
19
41
  preview?: unknown;
42
+ /** Set only when reconstructed from the durable trace: args are privacy-projected and results/previews are not retained. */
43
+ fromTrace?: boolean;
20
44
  startedAt?: number;
21
45
  endedAt?: number;
22
46
  }
@@ -31,13 +55,20 @@ export interface FabricExecutionRenderDetails {
31
55
  audits: FabricLegacyRenderAudit[];
32
56
  }
33
57
  /**
34
- * Creates the only object stored in final fabric_exec details. Rich call
35
- * audits remain available to live partial rendering but are deliberately not
36
- * copied here. The aggregate object, not each member independently, is bound.
58
+ * Creates the only object stored in final fabric_exec details. The
59
+ * privacy-projected trace stays the functional record for compaction and tool
60
+ * ownership; rich call audits persist verbatim (minus in-memory media) so a
61
+ * resumed transcript re-renders and expands exactly like the live one — the
62
+ * collapsed display, not the session record, is the visual boundary. The
63
+ * aggregate object, not each member independently, is bound; display-only
64
+ * audits trim before the functional trace.
37
65
  */
38
66
  export declare const createFabricPersistedExecutionDetails: (input: {
39
67
  success: boolean;
40
68
  trace: FabricExecutionTraceV1;
69
+ audits?: readonly FabricPersistableAuditInput[];
70
+ phases?: readonly string[];
71
+ error?: string;
41
72
  outputFormat?: "yaml" | "json";
42
73
  outputFormatStartLine?: number;
43
74
  outputFormatLines?: number;
@@ -1 +1 @@
1
- {"version":3,"file":"details.d.ts","sourceRoot":"","sources":["../../src/audit/details.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,sBAAsB,EAC5B,MAAM,YAAY,CAAC;AAEpB,eAAO,MAAM,kCAAkC,QAAa,CAAC;AAE7D,MAAM,WAAW,iCAAiC;IAChD,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,sBAAsB,CAAC;IAC9B,YAAY,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC/B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED,MAAM,WAAW,uBAAuB;IACtC,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,E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;AAED,MAAM,WAAW,4BAA4B;IAC3C,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC/B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,MAAM,EAAE,uBAAuB,EAAE,CAAC;CACnC;AAuBD;;;;;;;;GAQG;AACH,eAAO,MAAM,qCAAqC,GAAI,OAAO;IAC3D,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,sBAAsB,CAAC;IAC9B,MAAM,CAAC,EAAE,SAAS,2BAA2B,EAAE,CAAC;IAChD,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,YAAY,CAAC,EAAE,MAAM,GAAG,MAAM,CAAC;IAC/B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAC/B,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B,KAAG,iCA8CH,CAAC;AAsCF;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,GAC3C,OAAO,OAAO,KACb,4BAqCF,CAAC"}
@@ -1,3 +1,6 @@
1
+ import {
2
+ fabricExecTitleHint
3
+ } from "./chunk-4VEGQHZO.js";
1
4
  import {
2
5
  FABRIC_BRANCH_RUN_DESCRIPTION_MAX_BYTES,
3
6
  FABRIC_BRANCH_RUN_NAME_MAX_BYTES,
@@ -538,6 +541,21 @@ var normalizeRunDisplay = (input) => {
538
541
  return void 0;
539
542
  };
540
543
 
544
+ // src/ui/fabric-title-hint.ts
545
+ var TITLE_HINT_CACHE_MAX = 256;
546
+ var titleHintCache = /* @__PURE__ */ new Map();
547
+ var fabricExecTitleHintCached = (code) => {
548
+ const hit = titleHintCache.get(code);
549
+ if (hit !== void 0 || titleHintCache.has(code)) return hit;
550
+ const hint = fabricExecTitleHint(code);
551
+ if (titleHintCache.size >= TITLE_HINT_CACHE_MAX) {
552
+ const oldest = titleHintCache.keys().next().value;
553
+ if (oldest !== void 0) titleHintCache.delete(oldest);
554
+ }
555
+ titleHintCache.set(code, hint);
556
+ return hint;
557
+ };
558
+
541
559
  // src/compaction/normalize.ts
542
560
  var isMessageEntry = (entry) => entry.type === "message";
543
561
  var MAX_CUSTOM_DETAILS_DEPTH = 12;
@@ -623,10 +641,11 @@ var firstLine = (text) => {
623
641
  var fabricRunIntent = (call) => {
624
642
  if (!call || call.name !== "fabric_exec") return void 0;
625
643
  const display = normalizeRunDisplay(call.args.display);
626
- if (!display || display.name === void 0) return void 0;
627
- const name = clipUtf8(display.name.trim(), FABRIC_BRANCH_RUN_NAME_MAX_BYTES);
644
+ const intentName = display?.name?.trim() ? display.name : typeof call.args.code === "string" ? fabricExecTitleHintCached(call.args.code) : void 0;
645
+ if (intentName === void 0) return void 0;
646
+ const name = clipUtf8(intentName.trim(), FABRIC_BRANCH_RUN_NAME_MAX_BYTES);
628
647
  if (!name) return void 0;
629
- const description = display.description !== void 0 ? clipUtf8(display.description.trim(), FABRIC_BRANCH_RUN_DESCRIPTION_MAX_BYTES) : "";
648
+ const description = display?.description !== void 0 ? clipUtf8(display.description.trim(), FABRIC_BRANCH_RUN_DESCRIPTION_MAX_BYTES) : "";
630
649
  return { name, ...description ? { description } : {} };
631
650
  };
632
651
  var normalizeEntries = (entries) => {
@@ -2153,10 +2172,11 @@ export {
2153
2172
  compactionRequestBoundsError,
2154
2173
  encodeCompactionRequest,
2155
2174
  normalizeRunDisplay,
2175
+ fabricExecTitleHintCached,
2156
2176
  rawContextTokens,
2157
2177
  computeCut,
2158
2178
  fabricCompactionVersion,
2159
2179
  compileFabricSummary,
2160
2180
  registerCompactionHook
2161
2181
  };
2162
- //# sourceMappingURL=chunk-SDE4YZSA.js.map
2182
+ //# sourceMappingURL=chunk-2SF432HH.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/compaction/hook.ts", "../../src/compaction/bounds.ts", "../../src/compaction/threshold.ts", "../../src/compaction/enrichers.ts", "../../src/compaction/instructions.ts", "../../src/run-display.ts", "../../src/ui/fabric-title-hint.ts", "../../src/compaction/normalize.ts", "../../src/compaction/projections.ts", "../../src/compaction/render.ts", "../../src/compaction/branch-summary.ts"],
4
+ "sourcesContent": ["import {\n buildSessionContext,\n calculateContextTokens,\n DEFAULT_COMPACTION_SETTINGS,\n estimateTokens,\n sessionEntryToContextMessages,\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 { clipUtf8, MAX_SUMMARY_BYTES } 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 { renderSummary } from \"./render.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}\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 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 continuityCutPlan = (\n branchEntries: SessionEntry[],\n tokensBefore: number,\n budget: FabricCompactionBudget,\n): ContinuityCutPlan | undefined => {\n if (!Number.isFinite(budget.contextWindow) || budget.contextWindow <= 0) return undefined;\n const contextWindow = Math.floor(budget.contextWindow);\n const reserveTokens = Math.max(0, Math.floor(budget.reserveTokens));\n const keepRecentTokens = Math.max(0, Math.floor(budget.keepRecentTokens));\n const targetContextRatio = Math.max(0.25, Math.min(0.85, budget.targetContextRatio));\n const rawTokensBefore = rawContextTokens(branchEntries);\n const { tokenScale, fixedOverheadTokens } = tokenCalibration(\n branchEntries,\n tokensBefore,\n rawTokensBefore,\n );\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,\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]! > plan.rawTailTokenBudget) continue;\n if (!closureSafe(spans, item.branchIndex)) continue;\n cutIndex = index;\n break;\n }\n const retainedRawTokens = suffixTokens[cutIndex] ?? 0;\n const details = {\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 };\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\nexport const computeCut = (\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 const lastBoundary = lastBoundaryIndex(live);\n if (lastBoundary <= 0) return boundary(live.map((item) => item.entry), \"\");\n const closed = closeCut(branchEntries, live, lastBoundary);\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\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 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 && 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 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 const projected = projectWithMetadata(source.events);\n const sections: Sections = projected.sections;\n runEnrichers(enrichers, source.events, sections);\n\n const summary = renderSummary(sections, {\n firstEntryId: source.range.first,\n lastEntryId: source.range.last,\n lastTimestamp: source.timestamp,\n requestLines: instructions.requestLines,\n });\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 (budgetDetails && budgetDetails.projectedTokensAfter > budgetDetails.targetContextTokens) {\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 = SECTION_HEADERS\n .filter(({ key }) => sections[key].length > 0)\n .map(({ header }) => header);\n if (instructions.requestLines.length > 0) sectionHeaders.splice(1, 0, \"[Compaction Request]\");\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 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: instructions.policy,\n stableAddresses: {\n firstKeptEntryId: cut.firstKeptEntryId,\n cumulativeSourceRange: source.range,\n recall: \"session-entry-id-range\",\n },\n ...(budgetDetails ? { budget: budgetDetails } : {}),\n timestamp: source.timestamp,\n };\n\n return {\n compaction: {\n summary,\n firstKeptEntryId: cut.firstKeptEntryId,\n tokensBefore,\n details,\n },\n };\n};\n\nconst SECTION_HEADERS: { key: keyof Sections; header: string }[] = [\n { key: \"goal\", header: \"[Session Goal]\" },\n { key: \"files\", header: \"[Files And Changes]\" },\n { key: \"activity\", header: \"[Fabric Activity]\" },\n { key: \"outstanding\", header: \"[Outstanding Context]\" },\n { key: \"earlierTurns\", header: \"[Earlier Turns]\" },\n { key: \"status\", header: \"[Current Status]\" },\n];\n\nexport interface CompactionHookOptions {\n getEngine: () => CompactionEngine;\n getTargetContextRatio?: () => number;\n getThresholdContextRatio?: (modelKey: string) => number | undefined;\n getThresholdTokens?: (modelKey: string) => number | undefined;\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__\") return;\n const { preparation, branchEntries } = event;\n const contextWindow = context?.model?.contextWindow;\n const modelKey = modelCompactionKey(context?.model);\n const thresholdTokens = modelKey === undefined\n ? undefined\n : options.getThresholdTokens?.(modelKey);\n if (\n event.reason === \"threshold\"\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 && 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 = effectiveWindow !== undefined\n && typeof targetContextRatio === \"number\"\n && Number.isFinite(targetContextRatio)\n ? {\n contextWindow: effectiveWindow,\n targetContextRatio,\n reserveTokens: settings.reserveTokens,\n keepRecentTokens: settings.keepRecentTokens,\n }\n : undefined;\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 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", "export const MAX_SUMMARY_BYTES = 32 * 1024;\nconst MAX_REQUEST_SOURCE_BYTES = 8 * 1024;\n\nconst encoder = new TextEncoder();\n\nexport const utf8Bytes = (text: string): number => encoder.encode(text).byteLength;\n\nexport const clipUtf8 = (text: string, maxBytes: number, suffix = \"\u2026\"): string => {\n if (maxBytes <= 0) return \"\";\n if (utf8Bytes(text) <= maxBytes) return text;\n const suffixBytes = utf8Bytes(suffix);\n if (suffixBytes >= maxBytes) return \"\";\n let output = \"\";\n let used = 0;\n const available = maxBytes - suffixBytes;\n for (const character of text) {\n const bytes = utf8Bytes(character);\n if (used + bytes > available) break;\n output += character;\n used += bytes;\n }\n return `${output}${suffix}`;\n};\n\nexport interface CanonicalText {\n text: string;\n truncated: boolean;\n sourceBytes: number;\n}\n\nexport const canonicalizeText = (input: string, maxBytes = MAX_REQUEST_SOURCE_BYTES): CanonicalText => {\n const canonical = input.trim().split(/\\s+/u).filter(Boolean).join(\" \");\n const sourceBytes = utf8Bytes(canonical);\n return {\n text: clipUtf8(canonical, maxBytes),\n truncated: sourceBytes > maxBytes,\n sourceBytes,\n };\n};\n\nexport interface AddressedValue {\n entryId: string;\n}\n\nexport interface AddressedSample<T extends AddressedValue> {\n values: T[];\n omitted: number;\n omittedFirstEntryId?: string;\n omittedLastEntryId?: string;\n splitIndex: number;\n}\n\nexport const sampleAddressedFrom = <T extends AddressedValue>(\n source: Iterable<T>,\n maxValues: number,\n): AddressedSample<T> => {\n const earliestLimit = Math.ceil(maxValues / 2);\n const latestLimit = Math.floor(maxValues / 2);\n const earliest: T[] = [];\n const latest: T[] = [];\n let omitted = 0;\n let omittedFirstEntryId: string | undefined;\n let omittedLastEntryId: string | undefined;\n\n for (const value of source) {\n if (earliest.length < earliestLimit) {\n earliest.push(value);\n continue;\n }\n latest.push(value);\n if (latest.length <= latestLimit) continue;\n const displaced = latest.shift()!;\n omitted += 1;\n omittedFirstEntryId ??= displaced.entryId;\n omittedLastEntryId = displaced.entryId;\n }\n\n return {\n values: [...earliest, ...latest],\n omitted,\n ...(omittedFirstEntryId !== undefined ? { omittedFirstEntryId } : {}),\n ...(omittedLastEntryId !== undefined ? { omittedLastEntryId } : {}),\n splitIndex: earliest.length,\n };\n};\n\nexport const sampleAddressed = <T extends AddressedValue>(\n values: readonly T[],\n maxValues: number,\n): AddressedSample<T> => sampleAddressedFrom(values, maxValues);\n\nexport const omissionLine = (\n count: number,\n firstEntryId: string | undefined,\n lastEntryId: string | undefined,\n noun: string,\n): string => {\n const range = firstEntryId || lastEntryId\n ? `${firstEntryId || \"(start)\"} \u2192 ${lastEntryId || \"(end)\"}`\n : \"(unknown range)\";\n return `\u2026 omitted ${count} ${noun}; source entries ${range}`;\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 const compactAtConfiguredThreshold = async (\n context: ExtensionContext,\n config: FabricConfig,\n): Promise<boolean> => {\n const modelKey = modelCompactionKey(context.model);\n const usage = context.getContextUsage();\n if (usage === undefined) return false;\n\n const tokenThreshold = configuredCompactionTokenThreshold(config, modelKey);\n if (tokenThreshold !== undefined) {\n if (usage.tokens === null || usage.tokens < tokenThreshold) return false;\n return runThresholdCompact(context);\n }\n\n const threshold = configuredCompactionThreshold(config, modelKey);\n if (threshold === undefined || usage.percent === null) return false;\n if (usage.percent / 100 < threshold) return false;\n\n return runThresholdCompact(context);\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 { canonicalizeText, utf8Bytes } from \"./bounds.js\";\n\nexport const FABRIC_COMPACTION_REQUEST_PREFIX = \"__pi_fabric_compact_request_v1__:\";\nexport const MAX_COMPACTION_INSTRUCTIONS_CHARS = 8 * 1024;\nconst MAX_COMPACTION_INSTRUCTIONS_BYTES = 8 * 1024;\nexport const MAX_PRESERVE_ITEMS = 16;\nexport const MAX_PRESERVE_ITEM_CHARS = 2 * 1024;\nconst MAX_PRESERVE_ITEM_BYTES = 2 * 1024;\nexport const MAX_TYPED_COMPACTION_SOURCE_BYTES = 16 * 1024;\n\nexport interface TypedCompactionRequest {\n version: 1;\n instructions?: string;\n preserve?: string[];\n}\n\nexport interface CompactionInstructionPolicy {\n mode: \"none\" | \"plain\" | \"typed-v1\";\n canonicalized: boolean;\n sourceBytes: number;\n truncated: boolean;\n preserveCount: number;\n omittedPreserveCount: number;\n}\n\ntype CompactionInstructionErrorCode =\n | \"encoded-source-too-large\"\n | \"malformed-json\"\n | \"duplicate-field\"\n | \"invalid-unicode\"\n | \"structure-too-complex\"\n | \"invalid-object\"\n | \"unknown-field\"\n | \"unsupported-version\"\n | \"invalid-type\"\n | \"instructions-too-large\"\n | \"preserve-too-many\"\n | \"preserve-item-too-large\";\n\nexport interface CompactionInstructionDecodeError {\n code: CompactionInstructionErrorCode;\n message: string;\n sourceBytes: number;\n}\n\nexport type DecodedCompactionInstructions =\n | {\n ok: true;\n requestLines: string[];\n policy: CompactionInstructionPolicy;\n }\n | {\n ok: false;\n requestLines: [];\n error: CompactionInstructionDecodeError;\n };\n\nconst rejection = (\n code: CompactionInstructionErrorCode,\n message: string,\n sourceBytes: number,\n): DecodedCompactionInstructions => ({\n ok: false,\n requestLines: [],\n error: { code, message, sourceBytes },\n});\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n value !== null && typeof value === \"object\" && !Array.isArray(value);\n\nconst hasPairedSurrogates = (value: string): boolean => {\n for (let index = 0; index < value.length; index++) {\n const unit = value.charCodeAt(index);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n const next = value.charCodeAt(index + 1);\n if (!(next >= 0xdc00 && next <= 0xdfff)) return false;\n index += 1;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n return false;\n }\n }\n return true;\n};\n\nexport const compactionRequestBoundsError = (\n request: Omit<TypedCompactionRequest, \"version\">,\n): Omit<CompactionInstructionDecodeError, \"sourceBytes\"> | undefined => {\n if (request.instructions !== undefined) {\n if (!hasPairedSurrogates(request.instructions)) {\n return {\n code: \"invalid-unicode\",\n message: \"typed compaction instructions contain an unpaired UTF-16 surrogate\",\n };\n }\n if (request.instructions.length > MAX_COMPACTION_INSTRUCTIONS_CHARS\n || utf8Bytes(request.instructions) > MAX_COMPACTION_INSTRUCTIONS_BYTES) {\n return {\n code: \"instructions-too-large\",\n message: `typed compaction instructions exceed ${MAX_COMPACTION_INSTRUCTIONS_CHARS} characters or ${MAX_COMPACTION_INSTRUCTIONS_BYTES} UTF-8 bytes`,\n };\n }\n }\n if (request.preserve !== undefined) {\n if (request.preserve.length > MAX_PRESERVE_ITEMS) {\n return {\n code: \"preserve-too-many\",\n message: `typed compaction preserve exceeds ${MAX_PRESERVE_ITEMS} items`,\n };\n }\n for (const item of request.preserve) {\n if (!hasPairedSurrogates(item)) {\n return {\n code: \"invalid-unicode\",\n message: \"typed compaction preserve item contains an unpaired UTF-16 surrogate\",\n };\n }\n if (item.length > MAX_PRESERVE_ITEM_CHARS || utf8Bytes(item) > MAX_PRESERVE_ITEM_BYTES) {\n return {\n code: \"preserve-item-too-large\",\n message: `typed compaction preserve item exceeds ${MAX_PRESERVE_ITEM_CHARS} characters or ${MAX_PRESERVE_ITEM_BYTES} UTF-8 bytes`,\n };\n }\n }\n }\n return undefined;\n};\n\nexport const encodeCompactionRequest = (request: Omit<TypedCompactionRequest, \"version\">): string => {\n const boundsError = compactionRequestBoundsError(request);\n if (boundsError) throw new Error(boundsError.message);\n const payload: TypedCompactionRequest = {\n version: 1,\n ...(request.instructions !== undefined ? { instructions: request.instructions } : {}),\n ...(request.preserve !== undefined ? { preserve: request.preserve } : {}),\n };\n const encoded = `${FABRIC_COMPACTION_REQUEST_PREFIX}${JSON.stringify(payload)}`;\n if (utf8Bytes(encoded) > MAX_TYPED_COMPACTION_SOURCE_BYTES) {\n throw new Error(`typed compaction request exceeds ${MAX_TYPED_COMPACTION_SOURCE_BYTES} encoded UTF-8 bytes`);\n }\n return encoded;\n};\n\nconst plainInstructions = (source: string): DecodedCompactionInstructions => {\n const canonical = canonicalizeText(source);\n return {\n ok: true,\n requestLines: canonical.text ? [canonical.text] : [],\n policy: {\n mode: \"plain\",\n canonicalized: canonical.text !== source,\n sourceBytes: canonical.sourceBytes,\n truncated: canonical.truncated,\n preserveCount: 0,\n omittedPreserveCount: 0,\n },\n };\n};\n\nclass StrictJsonError extends Error {\n constructor(\n readonly code: \"malformed-json\" | \"duplicate-field\" | \"invalid-unicode\" | \"structure-too-complex\",\n message: string,\n ) {\n super(message);\n }\n}\n\nconst MAX_TYPED_JSON_DEPTH = 32;\nconst MAX_TYPED_JSON_NODES = 4096;\n\nclass StrictJsonParser {\n private index = 0;\n private nodes = 0;\n\n constructor(private readonly source: string) {}\n\n parse(): unknown {\n this.skipWhitespace();\n const value = this.parseValue(0);\n this.skipWhitespace();\n if (this.index !== this.source.length) this.malformed();\n return value;\n }\n\n private parseValue(depth: number): unknown {\n if (depth > MAX_TYPED_JSON_DEPTH) {\n throw new StrictJsonError(\"structure-too-complex\", \"typed compaction JSON exceeds the structural depth limit\");\n }\n this.nodes += 1;\n if (this.nodes > MAX_TYPED_JSON_NODES) {\n throw new StrictJsonError(\"structure-too-complex\", \"typed compaction JSON exceeds the structural node limit\");\n }\n const character = this.source[this.index];\n if (character === \"{\") return this.parseObject(depth + 1);\n if (character === \"[\") return this.parseArray(depth + 1);\n if (character === \"\\\"\") return this.parseString();\n if (character === \"t\") return this.parseLiteral(\"true\", true);\n if (character === \"f\") return this.parseLiteral(\"false\", false);\n if (character === \"n\") return this.parseLiteral(\"null\", null);\n if (character === \"-\" || (character !== undefined && character >= \"0\" && character <= \"9\")) {\n return this.parseNumber();\n }\n return this.malformed();\n }\n\n private parseObject(depth: number): Record<string, unknown> {\n this.index += 1;\n this.skipWhitespace();\n const output = Object.create(null) as Record<string, unknown>;\n const keys = new Set<string>();\n if (this.source[this.index] === \"}\") {\n this.index += 1;\n return output;\n }\n while (this.index < this.source.length) {\n if (this.source[this.index] !== \"\\\"\") this.malformed();\n const key = this.parseString();\n if (keys.has(key)) {\n throw new StrictJsonError(\"duplicate-field\", `typed compaction request contains duplicate field ${JSON.stringify(key)}`);\n }\n keys.add(key);\n this.skipWhitespace();\n if (this.source[this.index] !== \":\") this.malformed();\n this.index += 1;\n this.skipWhitespace();\n output[key] = this.parseValue(depth);\n this.skipWhitespace();\n const delimiter = this.source[this.index];\n if (delimiter === \"}\") {\n this.index += 1;\n return output;\n }\n if (delimiter !== \",\") this.malformed();\n this.index += 1;\n this.skipWhitespace();\n }\n return this.malformed();\n }\n\n private parseArray(depth: number): unknown[] {\n this.index += 1;\n this.skipWhitespace();\n const output: unknown[] = [];\n if (this.source[this.index] === \"]\") {\n this.index += 1;\n return output;\n }\n while (this.index < this.source.length) {\n output.push(this.parseValue(depth));\n this.skipWhitespace();\n const delimiter = this.source[this.index];\n if (delimiter === \"]\") {\n this.index += 1;\n return output;\n }\n if (delimiter !== \",\") this.malformed();\n this.index += 1;\n this.skipWhitespace();\n }\n return this.malformed();\n }\n\n private parseString(): string {\n this.index += 1;\n let output = \"\";\n while (this.index < this.source.length) {\n const unit = this.source.charCodeAt(this.index);\n if (unit === 0x22) {\n this.index += 1;\n if (!hasPairedSurrogates(output)) {\n throw new StrictJsonError(\"invalid-unicode\", \"typed compaction JSON string contains an unpaired UTF-16 surrogate\");\n }\n return output;\n }\n if (unit <= 0x1f) this.malformed();\n if (unit !== 0x5c) {\n output += this.source[this.index]!;\n this.index += 1;\n continue;\n }\n this.index += 1;\n const escape = this.source[this.index];\n this.index += 1;\n if (escape === \"\\\"\" || escape === \"\\\\\" || escape === \"/\") output += escape;\n else if (escape === \"b\") output += \"\\b\";\n else if (escape === \"f\") output += \"\\f\";\n else if (escape === \"n\") output += \"\\n\";\n else if (escape === \"r\") output += \"\\r\";\n else if (escape === \"t\") output += \"\\t\";\n else if (escape === \"u\") {\n let value = 0;\n for (let offset = 0; offset < 4; offset++) {\n const digit = this.hexValue(this.source.charCodeAt(this.index + offset));\n if (digit < 0) this.malformed();\n value = value * 16 + digit;\n }\n this.index += 4;\n output += String.fromCharCode(value);\n } else {\n this.malformed();\n }\n }\n return this.malformed();\n }\n\n private parseNumber(): number {\n const start = this.index;\n if (this.source[this.index] === \"-\") this.index += 1;\n if (this.source[this.index] === \"0\") {\n this.index += 1;\n if (this.isDigit(this.source.charCodeAt(this.index))) this.malformed();\n } else {\n if (!this.isDigitOneToNine(this.source.charCodeAt(this.index))) this.malformed();\n while (this.isDigit(this.source.charCodeAt(this.index))) this.index += 1;\n }\n if (this.source[this.index] === \".\") {\n this.index += 1;\n if (!this.isDigit(this.source.charCodeAt(this.index))) this.malformed();\n while (this.isDigit(this.source.charCodeAt(this.index))) this.index += 1;\n }\n const exponent = this.source[this.index];\n if (exponent === \"e\" || exponent === \"E\") {\n this.index += 1;\n const sign = this.source[this.index];\n if (sign === \"+\" || sign === \"-\") this.index += 1;\n if (!this.isDigit(this.source.charCodeAt(this.index))) this.malformed();\n while (this.isDigit(this.source.charCodeAt(this.index))) this.index += 1;\n }\n const value = Number(this.source.slice(start, this.index));\n if (!Number.isFinite(value)) this.malformed();\n return value;\n }\n\n private parseLiteral<T>(literal: string, value: T): T {\n if (!this.source.startsWith(literal, this.index)) this.malformed();\n this.index += literal.length;\n return value;\n }\n\n private skipWhitespace(): void {\n while (this.index < this.source.length) {\n const unit = this.source.charCodeAt(this.index);\n if (unit !== 0x20 && unit !== 0x09 && unit !== 0x0a && unit !== 0x0d) return;\n this.index += 1;\n }\n }\n\n private hexValue(unit: number): number {\n if (unit >= 0x30 && unit <= 0x39) return unit - 0x30;\n if (unit >= 0x41 && unit <= 0x46) return unit - 0x41 + 10;\n if (unit >= 0x61 && unit <= 0x66) return unit - 0x61 + 10;\n return -1;\n }\n\n private isDigit(unit: number): boolean {\n return unit >= 0x30 && unit <= 0x39;\n }\n\n private isDigitOneToNine(unit: number): boolean {\n return unit >= 0x31 && unit <= 0x39;\n }\n\n private malformed(): never {\n throw new StrictJsonError(\"malformed-json\", \"typed compaction request contains malformed JSON\");\n }\n}\n\nexport const decodeCompactionInstructions = (\n source: string | undefined,\n): DecodedCompactionInstructions => {\n if (source === undefined || source === \"\") {\n return {\n ok: true,\n requestLines: [],\n policy: {\n mode: \"none\",\n canonicalized: false,\n sourceBytes: 0,\n truncated: false,\n preserveCount: 0,\n omittedPreserveCount: 0,\n },\n };\n }\n if (!source.startsWith(FABRIC_COMPACTION_REQUEST_PREFIX)) return plainInstructions(source);\n\n const encodedSourceBytes = utf8Bytes(source);\n if (encodedSourceBytes > MAX_TYPED_COMPACTION_SOURCE_BYTES) {\n return rejection(\n \"encoded-source-too-large\",\n `typed compaction request exceeds ${MAX_TYPED_COMPACTION_SOURCE_BYTES} encoded UTF-8 bytes`,\n encodedSourceBytes,\n );\n }\n\n let parsed: unknown;\n try {\n parsed = new StrictJsonParser(source.slice(FABRIC_COMPACTION_REQUEST_PREFIX.length)).parse();\n } catch (error) {\n if (error instanceof StrictJsonError) {\n return rejection(error.code, error.message, encodedSourceBytes);\n }\n return rejection(\"malformed-json\", \"typed compaction request contains malformed JSON\", encodedSourceBytes);\n }\n if (!isRecord(parsed)) {\n return rejection(\"invalid-object\", \"typed compaction request must be a JSON object\", encodedSourceBytes);\n }\n\n const keys = Object.keys(parsed);\n const unknownField = keys.find((key) => key !== \"version\" && key !== \"instructions\" && key !== \"preserve\");\n if (unknownField !== undefined) {\n return rejection(\"unknown-field\", `typed compaction request contains unknown field ${JSON.stringify(unknownField)}`, encodedSourceBytes);\n }\n if (parsed.version !== 1) {\n return rejection(\"unsupported-version\", \"typed compaction request version must be 1\", encodedSourceBytes);\n }\n if (parsed.instructions !== undefined && typeof parsed.instructions !== \"string\") {\n return rejection(\"invalid-type\", \"typed compaction request instructions must be a string\", encodedSourceBytes);\n }\n if (parsed.preserve !== undefined && !Array.isArray(parsed.preserve)) {\n return rejection(\"invalid-type\", \"typed compaction request preserve must be an array\", encodedSourceBytes);\n }\n\n const preserve = parsed.preserve as unknown[] | undefined;\n if (preserve !== undefined && preserve.length > MAX_PRESERVE_ITEMS) {\n return rejection(\n \"preserve-too-many\",\n `typed compaction preserve exceeds ${MAX_PRESERVE_ITEMS} items`,\n encodedSourceBytes,\n );\n }\n if (preserve !== undefined && !preserve.every((item) => typeof item === \"string\")) {\n return rejection(\"invalid-type\", \"typed compaction preserve items must be strings\", encodedSourceBytes);\n }\n\n const request: Omit<TypedCompactionRequest, \"version\"> = {\n ...(parsed.instructions !== undefined ? { instructions: parsed.instructions } : {}),\n ...(preserve !== undefined ? { preserve: preserve as string[] } : {}),\n };\n const boundsError = compactionRequestBoundsError(request);\n if (boundsError) return rejection(boundsError.code, boundsError.message, encodedSourceBytes);\n\n const requestLines: string[] = [];\n let valueSourceBytes = 0;\n let truncated = false;\n let canonicalized = false;\n if (request.instructions !== undefined) {\n const instructions = canonicalizeText(request.instructions, MAX_COMPACTION_INSTRUCTIONS_BYTES);\n valueSourceBytes += instructions.sourceBytes;\n truncated ||= instructions.truncated;\n canonicalized ||= instructions.text !== request.instructions;\n if (instructions.text) requestLines.push(instructions.text);\n }\n\n for (let index = 0; index < (request.preserve?.length ?? 0); index++) {\n const sourceItem = request.preserve![index]!;\n const item = canonicalizeText(sourceItem, MAX_PRESERVE_ITEM_BYTES);\n valueSourceBytes += item.sourceBytes;\n truncated ||= item.truncated;\n canonicalized ||= item.text !== sourceItem;\n if (item.text) requestLines.push(`- ${item.text} [preserve:${index}]`);\n }\n\n return {\n ok: true,\n requestLines,\n policy: {\n mode: \"typed-v1\",\n canonicalized,\n sourceBytes: valueSourceBytes,\n truncated,\n preserveCount: request.preserve?.length ?? 0,\n omittedPreserveCount: 0,\n },\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\";\n\n// Session-wide memo for the lexical fallback title, keyed by the exact program\n// string. The same key recurs in three places \u2014 the compact renderCall card\n// (re-rendered on every streaming tick), the activity store start, and\n// compaction normalization over recorded arguments \u2014 so one tokenize pass per\n// unique program covers all three. Bounded with insertion-order eviction: run\n// names stay cheap for arbitrarily long sessions without retention growth.\nconst TITLE_HINT_CACHE_MAX = 256;\n\nconst titleHintCache = new Map<string, string | undefined>();\n\nexport const fabricExecTitleHintCached = (code: string): string | undefined => {\n const hit = titleHintCache.get(code);\n if (hit !== undefined || titleHintCache.has(code)) return hit;\n const hint = fabricExecTitleHint(code);\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(code, hint);\n return hint;\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): FabricRunIntent | undefined => {\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)\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);\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 { clipUtf8, omissionLine, sampleAddressed, sampleAddressedFrom } from \"./bounds.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 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\"]);\nexport const MAX_USER_GOAL_LINES = 3;\nexport const MAX_USER_GOAL_LINE = 1024;\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 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 trailingEllipsis = (lines: string[], max: number): string[] => {\n if (lines.length <= max) return lines;\n return [...lines.slice(0, max), \"\u2026\"];\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// [Session Goal] keeps up to three mechanically normalized, bounded lines\n// from the first user message. Later scope changes use bounded one-liners and\n// deterministic earliest/latest sampling with source addresses.\nconst projectGoal = (events: CompactionEvent[]): ProjectedSection => {\n const first = events.find(\n (event): event is Extract<CompactionEvent, { kind: \"user\" }> => event.kind === \"user\",\n );\n if (!first) return { lines: [], omitted: 0 };\n const firstLines = first.text.split(\"\\n\").filter((line, i, arr) =>\n line.trim() !== \"\" || (i === 0 && arr.length === 1),\n ).map((line) => truncate(line, MAX_USER_GOAL_LINE));\n const lines: string[] = [...trailingEllipsis(firstLines, MAX_USER_GOAL_LINES)];\n function* laterUsers(): Generator<Extract<CompactionEvent, { kind: \"user\" }>> {\n let skippedFirst = false;\n for (const event of events) {\n if (event.kind !== \"user\") continue;\n if (!skippedFirst) {\n skippedFirst = true;\n continue;\n }\n yield event;\n }\n }\n const sampled = sampleAddressedFrom(laterUsers(), 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[]): ProjectionResult => {\n const goal = projectGoal(events);\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 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 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 { clipUtf8, MAX_SUMMARY_BYTES, utf8Bytes } from \"./bounds.js\";\nimport type { Sections } from \"./projections.js\";\n\nconst SECTION_ORDER: { key: keyof Sections; header: string; maxBytes: number }[] = [\n { key: \"goal\", header: \"[Session Goal]\", 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\nconst REQUEST_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 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\nexport const renderSummary = (sections: Sections, options: RenderOptions): string => {\n const blocks: string[] = [];\n for (const { key, header, maxBytes } of SECTION_ORDER) {\n const lines = sections[key];\n if (lines.length === 0) continue;\n blocks.push(boundedBlock(header, lines, maxBytes));\n if (key === \"goal\" && options.requestLines && options.requestLines.length > 0) {\n blocks.push(boundedBlock(\"[Compaction Request]\", options.requestLines, REQUEST_MAX_BYTES));\n }\n }\n if (sections.goal.length === 0 && options.requestLines && options.requestLines.length > 0) {\n blocks.unshift(boundedBlock(\"[Compaction Request]\", options.requestLines, REQUEST_MAX_BYTES));\n }\n\n if (sections.transcript.length > 0) {\n blocks.push(boundedBlock(\"---\", sections.transcript, 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 blocks.push(boundedBlock(\"---\", [footer, POINTER_LINE], FOOTER_MAX_BYTES));\n\n const summary = `${blocks.join(\"\\n\\n\")}\\n`;\n if (utf8Bytes(summary) <= MAX_SUMMARY_BYTES) return summary;\n return `${clipUtf8(summary, MAX_SUMMARY_BYTES - 1, \"\")}\\n`;\n};\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, type Sections } from \"./projections.js\";\nimport { renderSummary } from \"./render.js\";\n\nconst SECTION_HEADERS: { key: keyof Sections; header: string }[] = [\n { key: \"goal\", header: \"[Session Goal]\" },\n { key: \"files\", header: \"[Files And Changes]\" },\n { key: \"activity\", header: \"[Fabric Activity]\" },\n { key: \"outstanding\", header: \"[Outstanding Context]\" },\n { key: \"earlierTurns\", header: \"[Earlier Turns]\" },\n { key: \"status\", header: \"[Current Status]\" },\n];\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 request = {\n text: instructions.requestLines.join(\"\\n\"),\n sourceBytes: instructions.policy.sourceBytes,\n truncated: instructions.policy.truncated,\n };\n const sections = SECTION_HEADERS\n .filter(({ key }) => projected.sections[key].length > 0)\n .map(({ header }) => header);\n if (request.text) sections.splice(1, 0, \"[Compaction Request]\");\n const summary = renderSummary(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 return {\n summary,\n details: boundedDetails(entriesToSummarize, factsFromEvents(events), sections, request, oldLeafId),\n };\n};\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;;;ACZA,IAAM,oBAAoB,KAAK;AACtC,IAAM,2BAA2B,IAAI;AAErC,IAAM,UAAU,IAAI,YAAY;AAEzB,IAAM,YAAY,CAAC,SAAyB,QAAQ,OAAO,IAAI,EAAE;AAEjE,IAAM,WAAW,CAAC,MAAc,UAAkB,SAAS,aAAgB;AAChF,MAAI,YAAY,EAAG,QAAO;AAC1B,MAAI,UAAU,IAAI,KAAK,SAAU,QAAO;AAC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