omp-fabric 1.3.3 → 1.4.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.
- package/CHANGELOG.md +19 -0
- package/dist/agents/handoff.d.ts.map +1 -1
- package/dist/chunks/{chunk-WZAH7BO2.js → chunk-2J2GOB4A.js} +30 -11
- package/dist/chunks/chunk-2J2GOB4A.js.map +7 -0
- package/dist/chunks/{chunk-2WDZT27Q.js → chunk-3H5LZWAG.js} +253 -4
- package/dist/chunks/chunk-3H5LZWAG.js.map +7 -0
- package/dist/chunks/{chunk-PYXBHMSL.js → chunk-IMSGR6OW.js} +3 -3
- package/dist/chunks/chunk-IY3IQPRQ.js +308 -0
- package/dist/chunks/chunk-IY3IQPRQ.js.map +7 -0
- package/dist/chunks/{chunk-VSSC4IDU.js → chunk-RTDJFHGH.js} +2 -2
- package/dist/chunks/{chunk-45URY66G.js → chunk-S4I7RMR5.js} +3 -3
- package/dist/chunks/{chunk-ZP3S74LW.js → chunk-SG4GVSWX.js} +49 -26
- package/dist/chunks/chunk-SG4GVSWX.js.map +7 -0
- package/dist/chunks/{chunk-JOWMM3EX.js → chunk-WPU4PKXQ.js} +135 -24
- package/dist/chunks/chunk-WPU4PKXQ.js.map +7 -0
- package/dist/chunks/{chunk-Z5AP4M6K.js → chunk-YOAZ5SO7.js} +12 -2
- package/dist/chunks/{chunk-Z5AP4M6K.js.map → chunk-YOAZ5SO7.js.map} +2 -2
- package/dist/compaction/branch-summary.d.ts +1 -1
- package/dist/compaction/branch-summary.d.ts.map +1 -1
- package/dist/compaction/hook.d.ts +21 -1
- package/dist/compaction/hook.d.ts.map +1 -1
- package/dist/compaction/hook.js +1 -1
- package/dist/compaction/lcm-maintenance.d.ts +103 -0
- package/dist/compaction/lcm-maintenance.d.ts.map +1 -0
- package/dist/compaction/lcm-model.d.ts +41 -0
- package/dist/compaction/lcm-model.d.ts.map +1 -0
- package/dist/compaction/lcm-runtime.d.ts +106 -0
- package/dist/compaction/lcm-runtime.d.ts.map +1 -0
- package/dist/config-migrations.d.ts +1 -1
- package/dist/config-migrations.d.ts.map +1 -1
- package/dist/config.d.ts +7 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/fabric-runtime-state.d.ts +2 -0
- package/dist/fabric-runtime-state.d.ts.map +1 -1
- package/dist/fabric-runtime-state.js +12 -7
- package/dist/fabric-runtime-state.js.map +2 -2
- package/dist/fabric-state.d.ts +2 -1
- package/dist/fabric-state.d.ts.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1030 -108
- package/dist/index.js.map +4 -4
- package/dist/memory/lcm-adapter.d.ts +97 -0
- package/dist/memory/lcm-adapter.d.ts.map +1 -0
- package/dist/providers/memory-provider.d.ts +8 -0
- package/dist/providers/memory-provider.d.ts.map +1 -1
- package/dist/providers/memory-provider.js +2 -1
- package/dist/residency/host.js +6 -5
- package/dist/residency/omp-entry.js +6 -5
- package/dist/residency/omp-entry.js.map +1 -1
- package/dist/runtime/core-override-guest-types.js +1 -1
- package/dist/runtime/guest-types.d.ts +1 -1
- package/dist/runtime/guest-types.d.ts.map +1 -1
- package/dist/runtime/guest-types.js +1 -1
- package/dist/storage/lcm-ledger.d.ts +107 -0
- package/dist/storage/lcm-ledger.d.ts.map +1 -0
- package/dist/storage/lcm-migration.d.ts +67 -0
- package/dist/storage/lcm-migration.d.ts.map +1 -0
- package/dist/ui/settings.js +5 -5
- package/dist/ui/settings.js.map +2 -2
- package/docs/adr/0001-lcm-durable-context-ledger.md +6 -0
- package/docs/agents/domain.md +25 -0
- package/docs/agents/issue-tracker.md +25 -0
- package/docs/agents/triage-labels.md +11 -0
- package/docs/compaction.md +78 -312
- package/docs/configuration.md +3 -3
- package/package.json +1 -1
- package/dist/chunks/chunk-2WDZT27Q.js.map +0 -7
- package/dist/chunks/chunk-JOWMM3EX.js.map +0 -7
- package/dist/chunks/chunk-WZAH7BO2.js.map +0 -7
- package/dist/chunks/chunk-ZP3S74LW.js.map +0 -7
- /package/dist/chunks/{chunk-PYXBHMSL.js.map → chunk-IMSGR6OW.js.map} +0 -0
- /package/dist/chunks/{chunk-VSSC4IDU.js.map → chunk-RTDJFHGH.js.map} +0 -0
- /package/dist/chunks/{chunk-45URY66G.js.map → chunk-S4I7RMR5.js.map} +0 -0
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"version": 3,
|
|
3
|
-
"sources": ["../../src/providers/memory-provider.ts", "../../src/memory/context.ts", "../../src/providers/arg-normalization.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n FabricActionDescriptor,\n FabricInvocationContext,\n FabricProvider,\n FabricProviderListRequest,\n} from \"../protocol.js\";\nimport type { FabricMemoryConfig } from \"../config.js\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n AmbiguousSessionError,\n InvalidProjectScopeError,\n enumerateAllSessions,\n overrideSessionDir,\n PROJECT_SESSION_DIR_MISSING,\n resolveScope,\n resolveSessionTarget,\n type ResolveScopeInput,\n type ScopeResolution,\n type SessionRef,\n} from \"../memory/discovery.js\";\nimport {\n presentRecall,\n RECALL_DEFAULT_PAGE_SIZE,\n RECALL_DEFAULT_SNIPPET_CHARS,\n RECALL_MAX_PAGE_SIZE,\n RECALL_MAX_RESPONSE_CHARS,\n RECALL_MAX_SNIPPET_CHARS,\n type MemoryRecallCallArgs,\n} from \"../memory/context.js\";\nimport type { LiveSessionBranch, MemoryBranches } from \"../memory/lineage.js\";\nimport { reconstructSessionLineage } from \"../memory/lineage.js\";\nimport {\n expandSessionEntriesChecked,\n normalizeSession,\n type ExpandedSessionEntry,\n type ExpandSessionSelection,\n type NormalizedEntry,\n} from \"../memory/normalize.js\";\nimport {\n DEFAULT_HOT_SESSIONS,\n fingerprintSource,\n loadTieredIndex,\n type EntryRange,\n type MemoryCoverage,\n type MemoryIndexOptions,\n type SearchFilters,\n} from \"../memory/index.js\";\nimport {\n DEFAULT_REGEX_MAX_HAYSTACK_BYTES,\n DEFAULT_REGEX_MAX_HAYSTACK_TERMS,\n DEFAULT_REGEX_MAX_PATTERN_BYTES,\n DEFAULT_REGEX_TIMEOUT_MS,\n searchMemoryIndex,\n type SearchResult,\n} from \"../memory/search.js\";\nimport type { MemoryQueryMatch, MemoryQueryMode } from \"../memory/tokenize.js\";\nimport { actionArgNormalizer, type ArgNormalizationSpec } from \"./arg-normalization.js\";\n\nconst EXPAND_DEFAULT_MAX_CHARS = 20_000;\nconst EXPAND_MAX_CHARS = 24_000;\nconst EXPAND_DEFAULT_MAX_ENTRIES = 10;\nconst EXPAND_MAX_ENTRIES = 20;\nconst EXPAND_MAX_CONTEXT = 100;\nconst EXPAND_MAX_EXACT_SELECTORS = 100;\nconst SESSIONS_MAX = 500;\nconst CONTINUATION_CACHE_TTL_MS = 5 * 60_000;\nconst EXPANSION_SNAPSHOT_LIMIT = 2;\nconst EXPANSION_SELECTION_LIMIT = 16;\n\ninterface SourceIdentity {\n device: bigint;\n inode: bigint;\n size: bigint;\n modifiedAt: bigint;\n changedAt: bigint;\n}\n\ninterface SourceObservation {\n file: string;\n identity: SourceIdentity;\n liveBranchSignature: string | null;\n}\n\ntype LiveBranchResolver = MemoryIndexOptions[\"liveBranchForFile\"];\n\ntype CanonicalExpansionSelection = ExpandSessionSelection & {\n before?: number;\n after?: number;\n};\n\ninterface ResolvedExpansionSelection {\n entries: ExpandedSessionEntry[];\n canonical: CanonicalExpansionSelection;\n anchorIndex: number | null;\n}\n\ninterface ExpansionSnapshot {\n file: string;\n branches: MemoryBranches;\n sourceHash: string;\n lineageFingerprint: string;\n observation: SourceObservation;\n entries: readonly NormalizedEntry[];\n selections: Map<string, ResolvedExpansionSelection>;\n touchedAt: number;\n}\n\ninterface RecallContinuationCache {\n key: string;\n result: SearchResult;\n coverage: MemoryCoverage;\n requestArgs: MemoryRecallCallArgs;\n observations: SourceObservation[];\n touchedAt: number;\n}\n\nconst sourceIdentity = (file: string): SourceIdentity | null => {\n try {\n const stat = fs.statSync(file, { bigint: true });\n if (!stat.isFile()) return null;\n return {\n device: stat.dev,\n inode: stat.ino,\n size: stat.size,\n modifiedAt: stat.mtimeNs,\n changedAt: stat.ctimeNs,\n };\n } catch {\n return null;\n }\n};\n\nconst sameSourceIdentity = (left: SourceIdentity, right: SourceIdentity): boolean =>\n left.device === right.device &&\n left.inode === right.inode &&\n left.size === right.size &&\n left.modifiedAt === right.modifiedAt &&\n left.changedAt === right.changedAt;\n\nconst liveBranchSignature = (branch: LiveSessionBranch | undefined): string | null =>\n branch ? `${branch.leafId ?? \"\"}\\0${branch.entries.length}` : null;\n\nconst observeSource = (\n file: string,\n branches: MemoryBranches,\n liveBranch: LiveSessionBranch | undefined,\n): SourceObservation | null => {\n const identity = sourceIdentity(file);\n if (!identity) return null;\n return {\n file: path.resolve(file),\n identity,\n liveBranchSignature: branches === \"active\" ? liveBranchSignature(liveBranch) : null,\n };\n};\n\nconst observeSources = (\n refs: readonly SessionRef[],\n branches: MemoryBranches,\n liveResolver: LiveBranchResolver,\n): SourceObservation[] | null => {\n const observations: SourceObservation[] = [];\n for (const ref of refs) {\n const liveBranch = branches === \"active\" ? liveResolver?.(ref.file) : undefined;\n const observation = observeSource(ref.file, branches, liveBranch);\n if (!observation) return null;\n observations.push(observation);\n }\n return observations;\n};\n\nconst sameSourceObservation = (left: SourceObservation, right: SourceObservation): boolean =>\n left.file === right.file &&\n sameSourceIdentity(left.identity, right.identity) &&\n left.liveBranchSignature === right.liveBranchSignature;\n\nconst sameSourceObservations = (\n left: readonly SourceObservation[],\n right: readonly SourceObservation[],\n): boolean => left.length === right.length && left.every((item, index) =>\n sameSourceObservation(item, right[index]!)\n);\n\nconst recallContinuationKey = (args: MemoryRecallCallArgs): string => JSON.stringify([\n args.query ?? null,\n args.queryMode ?? \"literal\",\n args.queryMatch ?? null,\n args.expectedSourceHash ?? null,\n args.expectedLineageFingerprint ?? null,\n args.branches ?? \"active\",\n args.scope ?? \"session\",\n args.pageSize ?? RECALL_DEFAULT_PAGE_SIZE,\n args.snippetChars ?? RECALL_DEFAULT_SNIPPET_CHARS,\n args.role ?? null,\n args.tool ?? null,\n args.ref ?? null,\n args.provider ?? null,\n args.action ?? null,\n args.outcome ?? null,\n args.since ?? null,\n args.until ?? null,\n args.entryRange ? [args.entryRange.first, args.entryRange.last] : null,\n]);\n\nconst expansionSnapshotKey = (file: string, branches: MemoryBranches): string =>\n `${path.resolve(file)}\\0${branches}`;\n\nconst expansionSelectionKey = (selection: CanonicalExpansionSelection): string => JSON.stringify([\n selection.indices ?? null,\n selection.entryIds ?? null,\n selection.operationAddresses ?? null,\n selection.entryRange ? [selection.entryRange.first, selection.entryRange.last] : null,\n selection.before ?? 0,\n selection.after ?? 0,\n]);\n\nconst errorOutputSchema = {\n type: \"object\",\n properties: {\n code: { type: \"string\" },\n message: { type: \"string\" },\n },\n required: [\"code\", \"message\"],\n};\n\nconst coverageOutputSchema = {\n type: \"object\",\n properties: {\n complete: { type: \"boolean\" },\n indexedSessions: { type: \"number\" },\n eligibleSessions: { type: \"number\" },\n staleSessions: { type: \"number\" },\n incompleteSessions: { type: \"number\" },\n reasons: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"Stable machine-readable incompleteness codes; empty when complete is true.\",\n },\n error: errorOutputSchema,\n },\n required: [\n \"complete\",\n \"indexedSessions\",\n \"eligibleSessions\",\n \"staleSessions\",\n \"incompleteSessions\",\n \"reasons\",\n ],\n};\n\nconst callOutputSchema = (ref: \"memory.recall\" | \"memory.expand\") => ({\n type: \"object\",\n properties: {\n ref: { const: ref },\n args: { type: \"object\" },\n },\n required: [\"ref\", \"args\"],\n});\n\nconst recallEntryOutputSchema = {\n type: \"object\",\n properties: {\n kind: { const: \"entry\" },\n sessionId: { type: \"string\" },\n tier: { type: \"string\", enum: [\"hot\", \"cold\"] },\n index: { type: \"number\" },\n entryId: { type: [\"string\", \"null\"] },\n parentId: { type: [\"string\", \"null\"] },\n operationAddress: { type: [\"string\", \"null\"] },\n type: { type: \"string\" },\n role: { type: [\"string\", \"null\"] },\n tool: { type: [\"string\", \"null\"] },\n ref: { type: [\"string\", \"null\"] },\n provider: { type: [\"string\", \"null\"] },\n action: { type: [\"string\", \"null\"] },\n timestamp: { type: [\"number\", \"null\"] },\n isError: { type: \"boolean\" },\n outcome: { type: \"string\", enum: [\"succeeded\", \"failed\", \"aborted\", \"timed_out\"] },\n score: { type: \"number\" },\n snippet: { type: \"string\" },\n truncated: { type: \"boolean\" },\n follow: callOutputSchema(\"memory.expand\"),\n },\n required: [\n \"kind\",\n \"sessionId\",\n \"tier\",\n \"index\",\n \"entryId\",\n \"parentId\",\n \"operationAddress\",\n \"type\",\n \"role\",\n \"tool\",\n \"ref\",\n \"provider\",\n \"action\",\n \"timestamp\",\n \"isError\",\n \"score\",\n \"snippet\",\n \"truncated\",\n \"follow\",\n ],\n};\n\nconst recallSessionOutputSchema = {\n type: \"object\",\n properties: {\n kind: { const: \"session\" },\n sessionId: { type: \"string\" },\n tier: { const: \"cold\" },\n cwd: { type: \"string\" },\n lastTimestamp: { type: [\"number\", \"null\"] },\n score: { type: \"number\" },\n matchedTerms: { type: \"number\" },\n matchedStructuralEntries: { type: \"number\" },\n follow: callOutputSchema(\"memory.recall\"),\n },\n required: [\n \"kind\",\n \"sessionId\",\n \"tier\",\n \"cwd\",\n \"lastTimestamp\",\n \"score\",\n \"matchedTerms\",\n \"matchedStructuralEntries\",\n \"follow\",\n ],\n};\n\nconst recallOutputSchema: Record<string, unknown> = {\n type: \"object\",\n description: \"Bounded ranked memory hits with uniform follow and pagination calls.\",\n properties: {\n total: { type: \"number\" },\n hits: {\n type: \"array\",\n description: \"Call tools.call(hit.follow) to expand an entry or resolve a cold session.\",\n items: { oneOf: [recallEntryOutputSchema, recallSessionOutputSchema] },\n },\n next: {\n oneOf: [callOutputSchema(\"memory.recall\"), { type: \"null\" }],\n description: \"When non-null, call tools.call(next).\",\n },\n coverage: coverageOutputSchema,\n error: errorOutputSchema,\n },\n required: [\"total\", \"hits\", \"next\", \"coverage\"],\n};\n\nconst expandOutputSchema: Record<string, unknown> = {\n type: \"object\",\n description: \"Integrity-bound session entries returned as lossless bounded text chunks.\",\n properties: {\n session: { type: \"string\" },\n sourceHash: { type: \"string\" },\n branches: { type: \"string\", enum: [\"active\", \"all\"] },\n lineageFingerprint: { type: \"string\" },\n entryCount: { type: \"number\" },\n entries: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n index: { type: \"number\" },\n entryId: { type: [\"string\", \"null\"] },\n parentId: { type: [\"string\", \"null\"] },\n type: { type: [\"string\", \"null\"] },\n role: { type: [\"string\", \"null\"] },\n timestamp: { type: [\"number\", \"null\"] },\n isError: { type: \"boolean\" },\n text: { type: \"string\" },\n textRange: {\n type: \"object\",\n properties: {\n start: { type: \"number\" },\n end: { type: \"number\" },\n total: { type: \"number\" },\n complete: { type: \"boolean\" },\n },\n required: [\"start\", \"end\", \"total\", \"complete\"],\n },\n anchor: { type: \"boolean\" },\n parentEntryId: { type: [\"string\", \"null\"] },\n operationAddress: { type: [\"string\", \"null\"] },\n tool: { type: [\"string\", \"null\"] },\n ref: { type: [\"string\", \"null\"] },\n provider: { type: [\"string\", \"null\"] },\n action: { type: [\"string\", \"null\"] },\n outcome: { type: \"string\", enum: [\"succeeded\", \"failed\", \"aborted\", \"timed_out\"] },\n filesTouched: { type: \"array\", items: { type: [\"string\", \"null\"] } },\n operation: { type: \"object\" },\n branchFact: { type: \"object\" },\n structuredTruncated: { type: \"boolean\" },\n factAddress: { type: [\"string\", \"null\"] },\n carrierEntryId: { type: [\"string\", \"null\"] },\n carrierParentId: { type: [\"string\", \"null\"] },\n carrierFromId: { type: [\"string\", \"null\"] },\n },\n required: [\"index\", \"entryId\", \"parentId\", \"type\", \"role\", \"timestamp\", \"isError\", \"text\", \"textRange\"],\n },\n },\n next: {\n oneOf: [callOutputSchema(\"memory.expand\"), { type: \"null\" }],\n description: \"When non-null, call tools.call(next).\",\n },\n error: errorOutputSchema,\n },\n required: [\"entries\"],\n};\n\nconst sessionsOutputSchema: Record<string, unknown> = {\n type: \"object\",\n properties: {\n scope: { type: \"string\" },\n branches: { type: \"string\", enum: [\"active\", \"all\"] },\n offset: { type: \"number\" },\n total: { type: \"number\" },\n truncated: { type: \"boolean\" },\n sessions: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n id: { type: \"string\" },\n file: { type: \"string\" },\n cwd: { type: \"string\" },\n mtime: { type: \"number\" },\n entryCount: { type: \"number\" },\n tier: { type: \"string\", enum: [\"hot\", \"cold\"] },\n branches: { type: \"string\", enum: [\"active\", \"all\"] },\n lineageFingerprint: { type: [\"string\", \"null\"] },\n },\n required: [\n \"id\",\n \"file\",\n \"cwd\",\n \"mtime\",\n \"entryCount\",\n \"tier\",\n \"branches\",\n \"lineageFingerprint\",\n ],\n },\n },\n error: errorOutputSchema,\n },\n};\n\nconst descriptors: FabricActionDescriptor[] = [\n {\n name: \"recall\",\n description:\n \"Search session memory as bounded ranked snippets. Literal queries rank any matching term by default; queryMatch all narrows to co-located terms. Call tools.call(hit.follow) for either an exact entry or a cold-session candidate, and tools.call(next) to continue.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: { type: \"string\", maxLength: 4096 },\n queryMode: {\n type: \"string\",\n enum: [\"literal\", \"phrase\", \"regex\"],\n default: \"literal\",\n description: \"Canonical tokens (default), one case-insensitive exact phrase, or explicitly bounded regex.\",\n },\n queryMatch: {\n type: \"string\",\n enum: [\"all\", \"any\"],\n default: \"any\",\n description: \"For literal mode, accept any term (default) or require all terms in one hot entry.\",\n },\n expectedSourceHash: {\n type: \"string\",\n description: \"SHA-256 from a prior pointer; stale sources are refused.\",\n },\n expectedLineageFingerprint: {\n type: \"string\",\n description: \"Active-lineage fingerprint from a prior pointer; changed leaves are refused.\",\n },\n branches: {\n type: \"string\",\n enum: [\"active\", \"all\"],\n description: \"Search the active parent-linked path (default) or every branch.\",\n },\n scope: {\n type: \"string\",\n description:\n \"session | project | project:<path> | global | session:<id-or-path>. Defaults to session.\",\n },\n offset: {\n type: \"number\",\n minimum: 0,\n description: \"Exact ranked-hit offset, normally copied from next.args.\",\n },\n pageSize: { type: \"number\", minimum: 1, maximum: RECALL_MAX_PAGE_SIZE, default: RECALL_DEFAULT_PAGE_SIZE },\n snippetChars: {\n type: \"number\",\n minimum: 80,\n maximum: RECALL_MAX_SNIPPET_CHARS,\n default: RECALL_DEFAULT_SNIPPET_CHARS,\n description: \"Maximum indexed-text characters shown per hit; full text remains in memory.expand.\",\n },\n role: {\n type: \"string\",\n enum: [\n \"assistant\",\n \"bashExecution\",\n \"branchCustomMessage\",\n \"branchSummary\",\n \"branchUser\",\n \"compaction\",\n \"compactionSummary\",\n \"custom\",\n \"fabricOperation\",\n \"fabricPhase\",\n \"fabricRun\",\n \"toolResult\",\n \"user\",\n ],\n description:\n \"Exact normalized entry role to filter by: the closed set the session normalizer can produce.\",\n },\n tool: { type: \"string\" },\n ref: {\n type: \"string\",\n minLength: 1,\n description: \"Exact persisted Fabric action ref, such as omp.grep. This is structural selection, not lexical expansion.\",\n },\n provider: {\n type: \"string\",\n minLength: 1,\n description: \"Exact persisted Fabric provider identity.\",\n },\n action: {\n type: \"string\",\n minLength: 1,\n description: \"Exact persisted Fabric action name.\",\n },\n outcome: {\n type: \"string\",\n enum: [\"succeeded\", \"failed\", \"aborted\", \"timed_out\"],\n description: \"Exact persisted Fabric execution outcome.\",\n },\n since: { type: \"number\" },\n until: { type: \"number\" },\n entryRange: {\n type: \"object\",\n description:\n \"Inclusive normalized-entry range for an explicit session:<id> resolution.\",\n properties: {\n first: { type: \"number\", minimum: 0 },\n last: { type: \"number\", minimum: 0 },\n },\n required: [\"first\", \"last\"],\n additionalProperties: false,\n },\n },\n additionalProperties: false,\n },\n outputSchema: recallOutputSchema,\n risk: \"read\",\n namespace: \"memory\",\n },\n {\n name: \"expand\",\n description:\n \"Read exact normalized session entries and nearby context as bounded lossless chunks. Call tools.call(next) to continue, or use guest-side memory.walk(args, visitor) to traverse complete reassembled entries.\",\n inputSchema: {\n type: \"object\",\n properties: {\n session: { type: \"string\", description: \"Exact session file path or unambiguous id.\" },\n expectedSourceHash: {\n type: \"string\",\n description: \"SHA-256 from a prior pointer; stale sources are refused.\",\n },\n expectedLineageFingerprint: {\n type: \"string\",\n description: \"Active-lineage fingerprint from a prior pointer; changed leaves are refused.\",\n },\n branches: {\n type: \"string\",\n enum: [\"active\", \"all\"],\n description: \"Expand on the active parent-linked path (default) or across every branch.\",\n },\n indices: { type: \"array\", maxItems: EXPAND_MAX_EXACT_SELECTORS, items: { type: \"number\", minimum: 0 } },\n entryIds: { type: \"array\", maxItems: EXPAND_MAX_EXACT_SELECTORS, items: { type: \"string\", maxLength: 512 } },\n operationAddresses: { type: \"array\", maxItems: EXPAND_MAX_EXACT_SELECTORS, items: { type: \"string\", maxLength: 512 } },\n entryRange: {\n type: \"object\",\n properties: {\n first: { type: \"number\", minimum: 0 },\n last: { type: \"number\", minimum: 0 },\n },\n required: [\"first\", \"last\"],\n additionalProperties: false,\n },\n before: {\n type: \"number\",\n minimum: 0,\n maximum: EXPAND_MAX_CONTEXT,\n default: 0,\n description: \"Entries before one exact selected anchor.\",\n },\n after: {\n type: \"number\",\n minimum: 0,\n maximum: EXPAND_MAX_CONTEXT,\n default: 0,\n description: \"Entries after one exact selected anchor.\",\n },\n entryOffset: {\n type: \"number\",\n minimum: 0,\n description: \"Continuation offset within the resolved selection; copy from next.args.\",\n },\n textOffset: {\n type: \"number\",\n minimum: 0,\n description: \"Continuation offset within the first returned entry; copy from next.args.\",\n },\n maxChars: {\n type: \"number\",\n minimum: 256,\n maximum: EXPAND_MAX_CHARS,\n default: EXPAND_DEFAULT_MAX_CHARS,\n description: \"Total entry-text characters returned in this chunk.\",\n },\n maxEntries: {\n type: \"number\",\n minimum: 1,\n maximum: EXPAND_MAX_ENTRIES,\n default: EXPAND_DEFAULT_MAX_ENTRIES,\n description: \"Maximum complete or partial entries returned in this chunk.\",\n },\n },\n required: [\"session\"],\n additionalProperties: false,\n },\n outputSchema: expandOutputSchema,\n risk: \"read\",\n namespace: \"memory\",\n },\n {\n name: \"sessions\",\n description: \"List known sessions in scope with id, file, cwd, mtime, entry count, and hot/cold tier.\",\n inputSchema: {\n type: \"object\",\n properties: {\n scope: {\n type: \"string\",\n description:\n \"session | project | project:<path> | global | session:<id-or-path>. Defaults to session.\",\n },\n branches: {\n type: \"string\",\n enum: [\"active\", \"all\"],\n description: \"Count the active parent-linked path (default) or every branch.\",\n },\n limit: {\n type: \"number\",\n minimum: 1,\n description: \"Maximum sessions returned; capped at the internal session ceiling.\",\n },\n offset: {\n type: \"number\",\n minimum: 0,\n description: \"Number of sessions to skip; advance it by limit to page through total.\",\n },\n },\n additionalProperties: false,\n },\n outputSchema: sessionsOutputSchema,\n risk: \"read\",\n namespace: \"memory\",\n },\n];\n\n// Value spellings models reliably substitute for the documented memory scopes,\n// e.g. scope \"cwd\" for \"project\". Same discipline as the key aliases below:\n// identical intent only. Unknown scopes still fall through to resolveScope's\n// default \"session\" handling.\nconst MEMORY_SCOPE_VALUE_ALIASES: Record<string, string> = {\n cwd: \"project\",\n repo: \"project\",\n directory: \"project\",\n folder: \"project\",\n all: \"global\",\n current: \"session\",\n};\n\nconst MEMORY_ARG_NORMALIZATION: Record<string, ArgNormalizationSpec> = {\n recall: { values: { scope: MEMORY_SCOPE_VALUE_ALIASES } },\n sessions: { values: { scope: MEMORY_SCOPE_VALUE_ALIASES } },\n};\n\n// Argument repair derives from the action schemas plus the shared synonym\n// lexicon; only scope value spellings stay table-bound because the schema\n// spells scope as a free string rather than an enum.\nexport const normalizeMemoryArgs = actionArgNormalizer(\n () => descriptors,\n MEMORY_ARG_NORMALIZATION,\n);\n\nexport interface MemoryProviderContext {\n agentDir: string;\n cwd: string;\n config: FabricMemoryConfig;\n sessionId?: string;\n sessionFile?: string;\n getLiveBranch?: () => LiveSessionBranch;\n}\n\nconst parseBranches = (value: unknown, action: string): MemoryBranches => {\n if (value === undefined) return \"active\";\n if (value === \"active\" || value === \"all\") return value;\n throw new Error(`${action} branches must be \"active\" or \"all\"`);\n};\n\nconst resolveIndexOptions = (\n config: FabricMemoryConfig,\n agentDir: string,\n branches: MemoryBranches,\n liveBranchForFile?: MemoryIndexOptions[\"liveBranchForFile\"],\n): MemoryIndexOptions => ({\n indexDir: config.indexDir ?? `${agentDir}/fabric/memory-index`,\n maxEntryChars: config.maxEntryChars,\n branches,\n indexThinking: config.indexThinking ?? false,\n indexToolOutput: config.indexToolOutput ?? true,\n ...(liveBranchForFile ? { liveBranchForFile } : {}),\n hotSessions: config.hotSessions ?? DEFAULT_HOT_SESSIONS,\n digestTerms: config.digestTerms ?? 200,\n ...(config.maxColdVocabularyBytes === undefined\n ? {} : { maxColdVocabularyBytes: config.maxColdVocabularyBytes }),\n ...(config.maxColdCacheBytes === undefined ? {} : { maxColdCacheBytes: config.maxColdCacheBytes }),\n ...(config.maxSyncSessions === undefined ? {} : { maxSyncSessions: config.maxSyncSessions }),\n ...(config.maxSyncSourceBytes === undefined ? {} : { maxSyncSourceBytes: config.maxSyncSourceBytes }),\n ...(config.maxCacheCleanupFiles === undefined\n ? {} : { maxCacheCleanupFiles: config.maxCacheCleanupFiles }),\n});\n\nconst resolveTierRefs = (refs: SessionRef[], context: MemoryProviderContext): SessionRef[] => {\n const all = enumerateAllSessions(\n context.agentDir,\n Number.MAX_SAFE_INTEGER,\n overrideSessionDir(context.sessionFile),\n );\n const known = new Set(all.map((ref) => ref.file));\n for (const ref of refs) {\n if (!known.has(ref.file)) all.push(ref);\n }\n return all;\n};\n\nconst resolveRefs = (\n scope: string | undefined,\n context: MemoryProviderContext,\n boundedBrowse: boolean,\n): ScopeResolution => {\n const effectiveScope = scope ?? \"session\";\n const input: ResolveScopeInput = {\n agentDir: context.agentDir,\n cwd: context.cwd,\n scope: effectiveScope,\n maxSessions: boundedBrowse ? context.config.maxSessions : Number.MAX_SAFE_INTEGER,\n };\n if (context.sessionId) input.sessionId = context.sessionId;\n if (context.sessionFile) input.sessionFile = context.sessionFile;\n return resolveScope(input);\n};\n\nconst liveBranchResolver = (\n context: MemoryProviderContext,\n): MemoryIndexOptions[\"liveBranchForFile\"] | undefined => {\n if (!context.sessionFile || !context.getLiveBranch) return undefined;\n const current = path.resolve(context.sessionFile);\n return (sessionFile) => path.resolve(sessionFile) === current\n ? context.getLiveBranch?.()\n : undefined;\n};\n\nconst stalePointerError = (\n sessionFile: string,\n expectedSourceHash: string | undefined,\n actualSourceHash: string,\n expectedLineageFingerprint?: string,\n actualLineageFingerprint?: string,\n) => ({\n code: \"stale_pointer\",\n message: expectedLineageFingerprint !== undefined &&\n expectedLineageFingerprint !== actualLineageFingerprint\n ? \"Session active lineage changed after the pointer was issued.\"\n : \"Session source changed after the pointer was issued.\",\n sessionFile,\n ...(expectedSourceHash === undefined ? {} : { expectedSourceHash }),\n actualSourceHash,\n ...(expectedLineageFingerprint === undefined ? {} : { expectedLineageFingerprint }),\n ...(actualLineageFingerprint === undefined ? {} : { actualLineageFingerprint }),\n});\n\nconst addressError = (message: string, entryCount?: number) => ({\n code: \"index_out_of_bounds\",\n message,\n ...(entryCount === undefined ? {} : { entryCount }),\n});\n\nconst unresolvedScopeError = (resolution: ScopeResolution) => ({\n code: resolution.reasons[0] ?? PROJECT_SESSION_DIR_MISSING,\n message:\n \"No session directory exists for this scope, so an empty result is unverified rather than an empty corpus.\",\n candidateDirectories: resolution.candidateDirs,\n});\n\nconst recallFailure = (error: { code: string; message: string; [key: string]: unknown }) => ({\n total: 0,\n hits: [],\n next: null,\n coverage: {\n complete: false,\n indexedSessions: 0,\n eligibleSessions: 0,\n staleSessions: 0,\n incompleteSessions: 0,\n reasons: [error.code],\n },\n error,\n});\n\nexport class MemoryProvider implements FabricProvider {\n readonly name = \"memory\";\n readonly description =\n \"Cross-session memory: a search engine over every OMP session timeline on this machine\";\n\n private recallContinuation: RecallContinuationCache | undefined;\n private readonly expansionSnapshots = new Map<string, ExpansionSnapshot>();\n\n constructor(private readonly context: MemoryProviderContext) {}\n\n private cachedRecallContinuation(\n key: string,\n observations: SourceObservation[] | null,\n ): RecallContinuationCache | undefined {\n const cached = this.recallContinuation;\n if (!cached || cached.key !== key) return undefined;\n if (\n !observations ||\n Date.now() - cached.touchedAt > CONTINUATION_CACHE_TTL_MS ||\n !sameSourceObservations(cached.observations, observations)\n ) {\n this.recallContinuation = undefined;\n return undefined;\n }\n cached.touchedAt = Date.now();\n return cached;\n }\n\n private rememberRecallContinuation(cached: RecallContinuationCache): void {\n this.recallContinuation = cached;\n }\n\n private forgetRecallContinuation(cached: RecallContinuationCache): void {\n if (this.recallContinuation === cached) this.recallContinuation = undefined;\n }\n\n private cachedExpansionSnapshot(\n file: string,\n branches: MemoryBranches,\n observation: SourceObservation | null,\n ): ExpansionSnapshot | undefined {\n const key = expansionSnapshotKey(file, branches);\n const cached = this.expansionSnapshots.get(key);\n if (!cached) return undefined;\n if (\n !observation ||\n Date.now() - cached.touchedAt > CONTINUATION_CACHE_TTL_MS ||\n !sameSourceObservation(cached.observation, observation)\n ) {\n this.expansionSnapshots.delete(key);\n return undefined;\n }\n cached.touchedAt = Date.now();\n this.expansionSnapshots.delete(key);\n this.expansionSnapshots.set(key, cached);\n return cached;\n }\n\n private rememberExpansionSnapshot(snapshot: ExpansionSnapshot): void {\n const key = expansionSnapshotKey(snapshot.file, snapshot.branches);\n this.expansionSnapshots.delete(key);\n this.expansionSnapshots.set(key, snapshot);\n while (this.expansionSnapshots.size > EXPANSION_SNAPSHOT_LIMIT) {\n const oldest = this.expansionSnapshots.keys().next().value;\n if (oldest === undefined) break;\n this.expansionSnapshots.delete(oldest);\n }\n }\n\n private rememberExpansionSelection(\n snapshot: ExpansionSnapshot,\n keys: readonly string[],\n selection: ResolvedExpansionSelection,\n ): void {\n for (const key of new Set(keys)) {\n snapshot.selections.delete(key);\n snapshot.selections.set(key, selection);\n }\n while (snapshot.selections.size > EXPANSION_SELECTION_LIMIT) {\n const oldest = snapshot.selections.keys().next().value;\n if (oldest === undefined) break;\n snapshot.selections.delete(oldest);\n }\n }\n\n private forgetExpansionSnapshot(snapshot: ExpansionSnapshot): void {\n const key = expansionSnapshotKey(snapshot.file, snapshot.branches);\n if (this.expansionSnapshots.get(key) === snapshot) this.expansionSnapshots.delete(key);\n }\n\n async list(\n request: FabricProviderListRequest,\n _context: FabricInvocationContext,\n ): Promise<FabricActionDescriptor[]> {\n const query = request.query?.toLowerCase();\n return query\n ? descriptors.filter((descriptor) =>\n `${descriptor.name} ${descriptor.description}`.toLowerCase().includes(query),\n )\n : descriptors;\n }\n\n async describe(\n actionName: string,\n _context: FabricInvocationContext,\n ): Promise<FabricActionDescriptor | undefined> {\n return descriptors.find((descriptor) => descriptor.name === actionName);\n }\n\n prepareArguments(\n actionName: string,\n args: Record<string, unknown>,\n ): Record<string, unknown> {\n return normalizeMemoryArgs(actionName, args);\n }\n\n async invoke(\n actionName: string,\n args: Record<string, unknown>,\n invocationContext: FabricInvocationContext,\n ): Promise<unknown> {\n try {\n switch (actionName) {\n case \"recall\":\n return await this.recall(args, invocationContext);\n case \"expand\":\n return await this.expand(args);\n case \"sessions\":\n return await this.sessions(args);\n default:\n throw new Error(`Unknown memory action: ${actionName}`);\n }\n } catch (error) {\n const detail =\n error instanceof AmbiguousSessionError\n ? {\n code: error.code,\n message: error.message,\n session: error.session,\n candidates: error.candidates,\n }\n : error instanceof InvalidProjectScopeError\n ? {\n code: error.code,\n message: error.message,\n project: error.project,\n projectPath: error.projectPath,\n reason: error.reason,\n }\n : undefined;\n if (detail) {\n if (actionName === \"recall\") return recallFailure(detail);\n if (actionName === \"expand\") return { entries: [], next: null, error: detail };\n return { error: detail };\n }\n throw error;\n }\n }\n\n private async recall(\n args: Record<string, unknown>,\n invocationContext: FabricInvocationContext,\n ): Promise<unknown> {\n const query = typeof args.query === \"string\" ? args.query : undefined;\n const rawQueryMode = args.queryMode;\n if (\n rawQueryMode !== undefined &&\n rawQueryMode !== \"literal\" &&\n rawQueryMode !== \"phrase\" &&\n rawQueryMode !== \"regex\"\n ) {\n throw new Error('memory.recall queryMode must be \"literal\", \"phrase\", or \"regex\"');\n }\n const queryMode: MemoryQueryMode = rawQueryMode === \"phrase\"\n ? \"phrase\"\n : rawQueryMode === \"regex\"\n ? \"regex\"\n : \"literal\";\n const rawQueryMatch = args.queryMatch;\n if (rawQueryMatch !== undefined && rawQueryMatch !== \"all\" && rawQueryMatch !== \"any\") {\n throw new Error('memory.recall queryMatch must be \"all\" or \"any\"');\n }\n if (queryMode !== \"literal\" && rawQueryMatch !== undefined) {\n throw new Error(\"memory.recall queryMatch is only valid with literal queryMode\");\n }\n const queryMatch: MemoryQueryMatch = rawQueryMatch === \"all\" ? \"all\" : \"any\";\n const expectedSourceHash = typeof args.expectedSourceHash === \"string\"\n ? args.expectedSourceHash\n : undefined;\n const expectedLineageFingerprint = typeof args.expectedLineageFingerprint === \"string\"\n ? args.expectedLineageFingerprint\n : undefined;\n const branches = parseBranches(args.branches, \"memory.recall\");\n const scope = typeof args.scope === \"string\" ? args.scope : undefined;\n const role = typeof args.role === \"string\" ? args.role : undefined;\n const tool = typeof args.tool === \"string\" ? args.tool : undefined;\n const ref = typeof args.ref === \"string\" ? args.ref : undefined;\n const provider = typeof args.provider === \"string\" ? args.provider : undefined;\n const action = typeof args.action === \"string\" ? args.action : undefined;\n const rawOutcome = args.outcome;\n if (\n rawOutcome !== undefined &&\n rawOutcome !== \"succeeded\" &&\n rawOutcome !== \"failed\" &&\n rawOutcome !== \"aborted\" &&\n rawOutcome !== \"timed_out\"\n ) {\n throw new Error(\"memory.recall outcome must be succeeded, failed, aborted, or timed_out\");\n }\n const outcome = rawOutcome as SearchFilters[\"outcome\"];\n const since = typeof args.since === \"number\" ? args.since : undefined;\n const until = typeof args.until === \"number\" ? args.until : undefined;\n const offset = typeof args.offset === \"number\" && args.offset >= 0\n ? Math.floor(args.offset)\n : undefined;\n const pageSize =\n typeof args.pageSize === \"number\" && args.pageSize >= 1\n ? Math.min(Math.floor(args.pageSize), RECALL_MAX_PAGE_SIZE)\n : RECALL_DEFAULT_PAGE_SIZE;\n const snippetChars =\n typeof args.snippetChars === \"number\" && args.snippetChars >= 80\n ? Math.min(Math.floor(args.snippetChars), RECALL_MAX_SNIPPET_CHARS)\n : RECALL_DEFAULT_SNIPPET_CHARS;\n\n const resolution = resolveRefs(scope, this.context, false);\n const refs = resolution.refs;\n const liveResolver = liveBranchResolver(this.context);\n const options = resolveIndexOptions(\n this.context.config,\n this.context.agentDir,\n branches,\n liveResolver,\n );\n const hydrate = scope?.trim().startsWith(\"session:\") ?? false;\n if ((expectedSourceHash !== undefined || expectedLineageFingerprint !== undefined) && !hydrate) {\n throw new Error(\"memory.recall integrity expectations require scope session:<id-or-path>\");\n }\n\n const rawRange = args.entryRange;\n const entryRange = rawRange && typeof rawRange === \"object\" && !Array.isArray(rawRange)\n ? rawRange as Record<string, unknown>\n : undefined;\n const first = entryRange?.first;\n const last = entryRange?.last;\n if ((first === undefined) !== (last === undefined)) {\n throw new Error(\"memory.recall entryRange requires both first and last\");\n }\n if ((first !== undefined || last !== undefined) && !hydrate) {\n throw new Error(\"memory.recall entryRange requires scope session:<id-or-path>\");\n }\n if (first !== undefined && (\n typeof first !== \"number\" ||\n typeof last !== \"number\" ||\n !Number.isSafeInteger(first) ||\n !Number.isSafeInteger(last) ||\n first < 0 ||\n last < first\n )) {\n return recallFailure(addressError(\"Entry range requires safe integers with 0 <= first <= last.\"));\n }\n const selectedRange: EntryRange | undefined =\n typeof first === \"number\" && typeof last === \"number\" ? { first, last } : undefined;\n const filters: SearchFilters = {};\n if (role) filters.role = role;\n if (tool) filters.tool = tool;\n if (ref) filters.ref = ref;\n if (provider) filters.provider = provider;\n if (action) filters.action = action;\n if (outcome) filters.outcome = outcome;\n if (since !== undefined) filters.since = since;\n if (until !== undefined) filters.until = until;\n const baseRequestArgs: MemoryRecallCallArgs = {\n ...(query === undefined ? {} : { query }),\n queryMode,\n ...(queryMode === \"literal\" ? { queryMatch } : {}),\n ...(expectedSourceHash ? { expectedSourceHash } : {}),\n ...(expectedLineageFingerprint ? { expectedLineageFingerprint } : {}),\n branches,\n scope: scope ?? \"session\",\n ...(offset === undefined ? {} : { offset }),\n pageSize,\n snippetChars,\n ...(role ? { role } : {}),\n ...(tool ? { tool } : {}),\n ...(ref ? { ref } : {}),\n ...(provider ? { provider } : {}),\n ...(action ? { action } : {}),\n ...(outcome ? { outcome } : {}),\n ...(since !== undefined ? { since } : {}),\n ...(until !== undefined ? { until } : {}),\n ...(selectedRange ? { entryRange: selectedRange } : {}),\n };\n const updateProgress = (searchResult: SearchResult): void => {\n invocationContext.update(\n searchResult.matchMode === \"structural\"\n ? `memory.recall: ${searchResult.matchedCount} structural matches`\n : searchResult.matchMode === \"combined\"\n ? `memory.recall: ${searchResult.matchedCount} filtered matches`\n : query\n ? `memory.recall: ${searchResult.matchedCount} matches`\n : `memory.recall: ${searchResult.matchedCount} recent entries`,\n );\n };\n const observationsBefore = observeSources(refs, branches, liveResolver);\n const cached = offset === undefined\n ? undefined\n : this.cachedRecallContinuation(\n recallContinuationKey(baseRequestArgs),\n observationsBefore,\n );\n if (cached) {\n const response = presentRecall({\n result: cached.result,\n ...(query === undefined ? {} : { query }),\n queryMode,\n coverage: cached.coverage,\n ...(offset === undefined ? {} : { offset }),\n pageSize,\n snippetChars,\n requestArgs: cached.requestArgs,\n });\n const observationsAfterCachedPage = observeSources(refs, branches, liveResolver);\n if (\n observationsBefore &&\n observationsAfterCachedPage &&\n sameSourceObservations(observationsBefore, observationsAfterCachedPage)\n ) {\n if (response.next === null) this.forgetRecallContinuation(cached);\n updateProgress(cached.result);\n return response;\n }\n this.forgetRecallContinuation(cached);\n }\n\n if (hydrate && refs[0]) {\n const state = fingerprintSource(refs[0].file);\n const lineage = reconstructSessionLineage(\n refs[0].file,\n branches,\n liveResolver?.(refs[0].file),\n );\n const sourceChanged = expectedSourceHash !== undefined &&\n state?.sourceHash !== expectedSourceHash;\n const lineageChanged = expectedLineageFingerprint !== undefined &&\n lineage.fingerprint !== expectedLineageFingerprint;\n if (state && (sourceChanged || lineageChanged)) {\n return recallFailure(stalePointerError(\n refs[0].file,\n expectedSourceHash,\n state.sourceHash,\n expectedLineageFingerprint,\n lineage.fingerprint,\n ));\n }\n }\n\n const index = loadTieredIndex(\n refs,\n resolveTierRefs(refs, this.context),\n options,\n hydrate,\n selectedRange,\n );\n const hydratedShard = index.shards[0];\n const hydratedSourceChanged = expectedSourceHash !== undefined &&\n hydratedShard?.sourceHash !== expectedSourceHash;\n const hydratedLineageChanged = expectedLineageFingerprint !== undefined &&\n hydratedShard?.lineageFingerprint !== expectedLineageFingerprint;\n if (hydrate && hydratedShard && (hydratedSourceChanged || hydratedLineageChanged)) {\n return recallFailure(stalePointerError(\n hydratedShard.sessionFile,\n expectedSourceHash,\n hydratedShard.sourceHash,\n expectedLineageFingerprint,\n hydratedShard.lineageFingerprint,\n ));\n }\n if (\n hydrate &&\n selectedRange &&\n index.shards[0] &&\n selectedRange.last >= index.shards[0].totalEntryCount\n ) {\n return recallFailure(addressError(\n `Entry range ends at ${selectedRange.last}, but the session has ${index.shards[0].totalEntryCount} entries.`,\n index.shards[0].totalEntryCount,\n ));\n }\n\n const searchQuery = {\n ...(query === undefined ? {} : { query }),\n queryMode,\n queryMatch,\n filters,\n regexLimits: {\n maxPatternBytes: this.context.config.regexMaxPatternBytes\n ?? DEFAULT_REGEX_MAX_PATTERN_BYTES,\n maxHaystackTerms: this.context.config.regexMaxHaystackTerms\n ?? DEFAULT_REGEX_MAX_HAYSTACK_TERMS,\n maxHaystackBytes: this.context.config.regexMaxHaystackBytes\n ?? DEFAULT_REGEX_MAX_HAYSTACK_BYTES,\n timeoutMs: this.context.config.regexTimeoutMs ?? DEFAULT_REGEX_TIMEOUT_MS,\n },\n };\n const result = await searchMemoryIndex(index.shards, index.digests, searchQuery);\n const coverage = {\n ...index.coverage,\n complete: index.coverage.complete && result.queryCoverage.complete\n && resolution.reasons.length === 0,\n reasons: [\n ...new Set([\n ...index.coverage.reasons,\n ...result.queryCoverage.reasons,\n ...resolution.reasons,\n ]),\n ].sort(),\n ...(result.queryCoverage.error ? { error: result.queryCoverage.error } : {}),\n };\n const soleRef = refs.length === 1 ? refs[0] : undefined;\n const soleShard = soleRef\n ? index.shards.find((candidate) => candidate.sessionFile === soleRef.file)\n : undefined;\n const soleDigest = soleRef\n ? index.digests.find((candidate) => candidate.file === soleRef.file)\n : undefined;\n const continuationBinding = soleRef && (soleShard?.sourceHash || soleDigest?.sourceHash)\n ? {\n file: soleRef.file,\n sourceHash: soleShard?.sourceHash ?? soleDigest!.sourceHash,\n lineageFingerprint: soleShard?.lineageFingerprint ?? soleDigest!.lineageFingerprint,\n }\n : undefined;\n const requestArgs: MemoryRecallCallArgs = {\n ...baseRequestArgs,\n ...((expectedSourceHash ?? continuationBinding?.sourceHash)\n ? { expectedSourceHash: expectedSourceHash ?? continuationBinding!.sourceHash }\n : {}),\n ...((expectedLineageFingerprint ?? continuationBinding?.lineageFingerprint)\n ? {\n expectedLineageFingerprint:\n expectedLineageFingerprint ?? continuationBinding!.lineageFingerprint,\n }\n : {}),\n scope: continuationBinding\n ? `session:${continuationBinding.file}`\n : baseRequestArgs.scope ?? \"session\",\n };\n const response = presentRecall({\n result,\n ...(query === undefined ? {} : { query }),\n queryMode,\n coverage,\n ...(offset === undefined ? {} : { offset }),\n pageSize,\n snippetChars,\n requestArgs,\n });\n const observationsAfter = observeSources(refs, branches, liveResolver);\n if (\n response.next !== null &&\n observationsBefore &&\n observationsAfter &&\n sameSourceObservations(observationsBefore, observationsAfter)\n ) {\n this.rememberRecallContinuation({\n key: recallContinuationKey(requestArgs),\n result,\n coverage,\n requestArgs,\n observations: observationsAfter,\n touchedAt: Date.now(),\n });\n }\n updateProgress(result);\n return response;\n }\n\n private async expand(args: Record<string, unknown>): Promise<unknown> {\n const session = typeof args.session === \"string\" ? args.session : \"\";\n const expectedSourceHash = typeof args.expectedSourceHash === \"string\"\n ? args.expectedSourceHash\n : undefined;\n const expectedLineageFingerprint = typeof args.expectedLineageFingerprint === \"string\"\n ? args.expectedLineageFingerprint\n : undefined;\n const branches = parseBranches(args.branches, \"memory.expand\");\n const rawIndices = args.indices;\n if (rawIndices !== undefined && !Array.isArray(rawIndices)) {\n throw new Error(\"memory.expand indices must be an array\");\n }\n if (Array.isArray(rawIndices) && !rawIndices.every((index) =>\n typeof index === \"number\" && Number.isSafeInteger(index) && index >= 0)) {\n return { session, error: addressError(\"Every entry index must be a non-negative safe integer.\"), entries: [] };\n }\n const indices = (rawIndices as number[] | undefined) ?? [];\n const entryIds = Array.isArray(args.entryIds)\n ? args.entryIds.filter(\n (entryId): entryId is string => typeof entryId === \"string\" && entryId.length > 0,\n )\n : [];\n const operationAddresses = Array.isArray(args.operationAddresses)\n ? args.operationAddresses.filter(\n (address): address is string => typeof address === \"string\" && address.length > 0,\n )\n : [];\n if (indices.length + entryIds.length + operationAddresses.length > EXPAND_MAX_EXACT_SELECTORS) {\n throw new Error(`memory.expand accepts at most ${EXPAND_MAX_EXACT_SELECTORS} exact selectors per call`);\n }\n const rawRange = args.entryRange;\n const rangeRecord = rawRange && typeof rawRange === \"object\" && !Array.isArray(rawRange)\n ? rawRange as Record<string, unknown>\n : undefined;\n const first = rangeRecord?.first;\n const last = rangeRecord?.last;\n if (!session) throw new Error(\"memory.expand requires a session\");\n if ((first === undefined) !== (last === undefined)) {\n throw new Error(\"memory.expand entryRange requires both first and last\");\n }\n if (first !== undefined && (\n typeof first !== \"number\" ||\n typeof last !== \"number\" ||\n !Number.isSafeInteger(first) ||\n !Number.isSafeInteger(last) ||\n first < 0 ||\n last < first\n )) {\n return { session, error: addressError(\"Entry range requires safe integers with 0 <= first <= last.\"), entries: [] };\n }\n const numeric = (value: unknown, fallback: number, maximum: number): number =>\n typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0\n ? Math.min(value, maximum)\n : fallback;\n const before = numeric(args.before, 0, EXPAND_MAX_CONTEXT);\n const after = numeric(args.after, 0, EXPAND_MAX_CONTEXT);\n const entryOffset = numeric(args.entryOffset, 0, Number.MAX_SAFE_INTEGER);\n const textOffset = numeric(args.textOffset, 0, Number.MAX_SAFE_INTEGER);\n const maxChars = Math.max(256, numeric(args.maxChars, EXPAND_DEFAULT_MAX_CHARS, EXPAND_MAX_CHARS));\n const maxEntries = Math.max(1, numeric(args.maxEntries, EXPAND_DEFAULT_MAX_ENTRIES, EXPAND_MAX_ENTRIES));\n\n const ref = resolveSessionTarget(\n this.context.agentDir,\n session,\n overrideSessionDir(this.context.sessionFile),\n );\n if (!ref) {\n return {\n session,\n error: { code: \"session_not_found\", message: `Session not found: ${session}` },\n entries: [],\n };\n }\n const liveResolver = liveBranchResolver(this.context);\n const observedLiveBranch = branches === \"active\" ? liveResolver?.(ref.file) : undefined;\n const observedSource = observeSource(ref.file, branches, observedLiveBranch);\n let snapshot = this.cachedExpansionSnapshot(ref.file, branches, observedSource);\n if (snapshot) {\n const sourceChanged = expectedSourceHash !== undefined &&\n snapshot.sourceHash !== expectedSourceHash;\n const lineageChanged = expectedLineageFingerprint !== undefined &&\n snapshot.lineageFingerprint !== expectedLineageFingerprint;\n if (sourceChanged || lineageChanged) {\n return {\n session: ref.file,\n branches,\n error: stalePointerError(\n ref.file,\n expectedSourceHash,\n snapshot.sourceHash,\n expectedLineageFingerprint,\n snapshot.lineageFingerprint,\n ),\n entries: [],\n };\n }\n }\n\n if (!snapshot) {\n const initialState = fingerprintSource(ref.file);\n if (!initialState) {\n return {\n session: ref.file,\n error: { code: \"source_unavailable\", message: `Session source is unavailable: ${ref.file}` },\n entries: [],\n };\n }\n const initialLiveBranch = branches === \"active\" ? liveResolver?.(ref.file) : undefined;\n const initialLineage = reconstructSessionLineage(\n ref.file,\n branches,\n initialLiveBranch,\n );\n const sourceChanged = expectedSourceHash !== undefined &&\n initialState.sourceHash !== expectedSourceHash;\n const lineageChanged = expectedLineageFingerprint !== undefined &&\n initialLineage.fingerprint !== expectedLineageFingerprint;\n if (sourceChanged || lineageChanged) {\n return {\n session: ref.file,\n branches,\n error: stalePointerError(\n ref.file,\n expectedSourceHash,\n initialState.sourceHash,\n expectedLineageFingerprint,\n initialLineage.fingerprint,\n ),\n entries: [],\n };\n }\n\n const normalized = normalizeSession(\n ref.file,\n Number.MAX_SAFE_INTEGER,\n {\n lineage: initialLineage,\n indexThinking: true,\n indexToolOutput: true,\n },\n ).entries;\n const finalState = fingerprintSource(ref.file);\n const finalLiveBranch = branches === \"active\" ? liveResolver?.(ref.file) : undefined;\n const finalLineage = reconstructSessionLineage(\n ref.file,\n branches,\n finalLiveBranch,\n );\n const finalObservation = observeSource(ref.file, branches, finalLiveBranch);\n if (\n !finalState ||\n !finalObservation ||\n finalState.sourceHash !== initialState.sourceHash ||\n finalLineage.fingerprint !== initialLineage.fingerprint\n ) {\n return {\n session: ref.file,\n error: stalePointerError(\n ref.file,\n expectedSourceHash ?? initialState.sourceHash,\n finalState?.sourceHash ?? \"\",\n expectedLineageFingerprint ?? initialLineage.fingerprint,\n finalLineage.fingerprint,\n ),\n entries: [],\n };\n }\n snapshot = {\n file: ref.file,\n branches,\n sourceHash: finalState.sourceHash,\n lineageFingerprint: finalLineage.fingerprint,\n observation: finalObservation,\n entries: normalized,\n selections: new Map(),\n touchedAt: Date.now(),\n };\n }\n\n const entryCount = snapshot.entries.length;\n const outOfBounds = indices.find((index) => index >= entryCount);\n if (outOfBounds !== undefined) {\n return {\n session: ref.file,\n error: addressError(`Entry index ${outOfBounds} is outside 0..${Math.max(0, entryCount - 1)}.`, entryCount),\n entries: [],\n };\n }\n if (typeof last === \"number\" && last >= entryCount) {\n return {\n session: ref.file,\n error: addressError(`Entry range ends at ${last}, but the session has ${entryCount} entries.`, entryCount),\n entries: [],\n };\n }\n if (\n indices.length === 0 &&\n entryIds.length === 0 &&\n operationAddresses.length === 0 &&\n (first === undefined || last === undefined)\n ) {\n if (before > 0 || after > 0) {\n throw new Error(\"memory.expand before/after requires one selected anchor\");\n }\n this.forgetExpansionSnapshot(snapshot);\n return {\n session: ref.file,\n sourceHash: snapshot.sourceHash,\n branches,\n lineageFingerprint: snapshot.lineageFingerprint,\n entryCount,\n entries: [],\n next: null,\n };\n }\n\n const requestedSelection: ExpandSessionSelection = {};\n if (indices.length > 0) requestedSelection.indices = indices;\n if (entryIds.length > 0) requestedSelection.entryIds = entryIds;\n if (operationAddresses.length > 0) requestedSelection.operationAddresses = operationAddresses;\n if (typeof first === \"number\" && typeof last === \"number\") {\n requestedSelection.entryRange = { first, last };\n }\n const requestedWithContext: CanonicalExpansionSelection = {\n ...requestedSelection,\n ...(before > 0 ? { before } : {}),\n ...(after > 0 ? { after } : {}),\n };\n const requestedKey = expansionSelectionKey(requestedWithContext);\n let resolved = snapshot.selections.get(requestedKey);\n if (!resolved) {\n let expansion = expandSessionEntriesChecked(snapshot.entries, requestedSelection);\n if (\"error\" in expansion) {\n return {\n session: ref.file,\n sourceHash: snapshot.sourceHash,\n branches,\n lineageFingerprint: snapshot.lineageFingerprint,\n error: expansion.error,\n entries: [],\n };\n }\n\n let anchorIndex: number | null = null;\n let canonical: CanonicalExpansionSelection;\n if (before > 0 || after > 0) {\n if (expansion.expanded.length !== 1) {\n throw new Error(\"memory.expand before/after requires exactly one resolved anchor\");\n }\n anchorIndex = expansion.expanded[0]!.index;\n const contextRange = {\n first: Math.max(0, anchorIndex - before),\n last: Math.min(Math.max(0, entryCount - 1), anchorIndex + after),\n };\n canonical = requestedWithContext;\n expansion = expandSessionEntriesChecked(snapshot.entries, { entryRange: contextRange });\n if (\"error\" in expansion) {\n return {\n session: ref.file,\n sourceHash: snapshot.sourceHash,\n branches,\n lineageFingerprint: snapshot.lineageFingerprint,\n error: expansion.error,\n entries: [],\n };\n }\n } else if (requestedSelection.entryRange) {\n canonical = { entryRange: requestedSelection.entryRange };\n } else {\n canonical = { indices: expansion.expanded.map((entry) => entry.index) };\n }\n resolved = { entries: expansion.expanded, canonical, anchorIndex };\n this.rememberExpansionSelection(\n snapshot,\n [requestedKey, expansionSelectionKey(canonical)],\n resolved,\n );\n }\n\n const selected = resolved.entries;\n const canonicalSelection = resolved.canonical;\n const anchorIndex = resolved.anchorIndex;\n const finalState = snapshot;\n const finalLineage = { fingerprint: snapshot.lineageFingerprint };\n if (entryOffset > selected.length) {\n return {\n session: ref.file,\n error: addressError(`Entry offset ${entryOffset} is outside 0..${selected.length}.`, selected.length),\n entries: [],\n };\n }\n if (entryOffset < selected.length && textOffset > selected[entryOffset]!.text.length) {\n return {\n session: ref.file,\n error: {\n code: \"text_offset_out_of_bounds\",\n message: `Text offset ${textOffset} exceeds entry #${selected[entryOffset]!.index} length ${selected[entryOffset]!.text.length}.`,\n textLength: selected[entryOffset]!.text.length,\n },\n entries: [],\n };\n }\n\n const bounded = (value: string | null, maximum = 512): string | null =>\n value === null || value.length <= maximum\n ? value\n : `${value.slice(0, Math.max(1, maximum - 1))}\u2026`;\n const compactStructure = (value: unknown): unknown => {\n if (value === undefined) return undefined;\n const serialized = JSON.stringify(value);\n return serialized.length <= 2_000 ? value : undefined;\n };\n const output: Array<Record<string, unknown>> = [];\n const cursors: Array<{ position: number; textOffset: number }> = [];\n let position = entryOffset;\n let currentTextOffset = textOffset;\n let remainingChars = maxChars;\n while (position < selected.length && output.length < maxEntries && remainingChars > 0) {\n const entry = selected[position]!;\n let end = Math.min(entry.text.length, currentTextOffset + remainingChars);\n if (\n end < entry.text.length &&\n end > currentTextOffset &&\n entry.text.charCodeAt(end) >= 0xdc00 &&\n entry.text.charCodeAt(end) <= 0xdfff\n ) {\n end -= 1;\n }\n if (end === currentTextOffset && currentTextOffset < entry.text.length) {\n end = Math.min(entry.text.length, currentTextOffset + 2);\n }\n const chunk = entry.text.slice(currentTextOffset, end);\n const textComplete = end >= entry.text.length;\n const operation = compactStructure(entry.operation);\n const branchFact = compactStructure(entry.branchFact);\n output.push({\n index: entry.index,\n entryId: bounded(entry.entryId),\n parentId: bounded(entry.parentId),\n type: bounded(entry.type),\n role: bounded(entry.role),\n timestamp: entry.timestamp,\n isError: entry.isError,\n ...(anchorIndex !== null ? { anchor: entry.index === anchorIndex } : {}),\n text: chunk,\n textRange: {\n start: currentTextOffset,\n end,\n total: entry.text.length,\n complete: textComplete,\n },\n ...(entry.parentEntryId !== undefined ? { parentEntryId: bounded(entry.parentEntryId) } : {}),\n ...(entry.operationAddress ? { operationAddress: bounded(entry.operationAddress) } : {}),\n ...(entry.toolName ? { tool: bounded(entry.toolName) } : {}),\n ...(entry.ref ? { ref: bounded(entry.ref) } : {}),\n ...(entry.provider ? { provider: bounded(entry.provider) } : {}),\n ...(entry.action ? { action: bounded(entry.action) } : {}),\n ...(entry.outcome ? { outcome: entry.outcome } : {}),\n ...(entry.filesTouched\n ? { filesTouched: entry.filesTouched.slice(0, 20).map((file) => bounded(file, 1_024)) }\n : {}),\n ...(operation !== undefined ? { operation } : {}),\n ...(branchFact !== undefined ? { branchFact } : {}),\n ...((entry.operation !== undefined && operation === undefined) ||\n (entry.branchFact !== undefined && branchFact === undefined)\n ? { structuredTruncated: true }\n : {}),\n ...(entry.factAddress ? { factAddress: bounded(entry.factAddress) } : {}),\n ...(entry.carrierEntryId ? { carrierEntryId: bounded(entry.carrierEntryId) } : {}),\n ...(entry.carrierParentId !== undefined ? { carrierParentId: bounded(entry.carrierParentId) } : {}),\n ...(entry.carrierFromId !== undefined ? { carrierFromId: bounded(entry.carrierFromId) } : {}),\n });\n remainingChars -= chunk.length;\n if (!textComplete) {\n currentTextOffset = end;\n cursors.push({ position, textOffset: currentTextOffset });\n break;\n }\n position += 1;\n currentTextOffset = 0;\n cursors.push({ position, textOffset: 0 });\n }\n\n const responseAt = (\n records: Array<Record<string, unknown>>,\n cursor: { position: number; textOffset: number },\n ): Record<string, unknown> => {\n const hasNext = cursor.position < selected.length;\n const nextArgs = hasNext\n ? {\n session: ref.file,\n expectedSourceHash: finalState.sourceHash,\n expectedLineageFingerprint: finalLineage.fingerprint,\n branches,\n ...canonicalSelection,\n entryOffset: cursor.position,\n ...(cursor.textOffset > 0 ? { textOffset: cursor.textOffset } : {}),\n maxChars,\n maxEntries,\n }\n : null;\n return {\n session: ref.file,\n sourceHash: finalState.sourceHash,\n branches,\n lineageFingerprint: finalLineage.fingerprint,\n entryCount,\n entries: records,\n next: nextArgs ? { ref: \"memory.expand\", args: nextArgs } : null,\n };\n };\n\n let cursor = { position, textOffset: currentTextOffset };\n let response = responseAt(output, cursor);\n while (output.length > 1 && JSON.stringify(response).length > RECALL_MAX_RESPONSE_CHARS) {\n output.pop();\n cursors.pop();\n cursor = cursors.at(-1) ?? { position: entryOffset, textOffset };\n response = responseAt(output, cursor);\n }\n if (output.length === 1 && JSON.stringify(response).length > RECALL_MAX_RESPONSE_CHARS) {\n const record = output[0]!;\n const range = record.textRange as { start: number; end: number; total: number; complete: boolean };\n const chunk = record.text as string;\n const excess = JSON.stringify(response).length - RECALL_MAX_RESPONSE_CHARS;\n let keep = Math.max(1, chunk.length - excess - 256);\n if (\n keep < chunk.length &&\n keep > 0 &&\n chunk.charCodeAt(keep) >= 0xdc00 &&\n chunk.charCodeAt(keep) <= 0xdfff\n ) {\n keep -= 1;\n }\n if (keep > 0 && keep < chunk.length) {\n record.text = chunk.slice(0, keep);\n range.end = range.start + keep;\n range.complete = false;\n cursor = { position: entryOffset, textOffset: range.end };\n response = responseAt(output, cursor);\n }\n if (JSON.stringify(response).length > RECALL_MAX_RESPONSE_CHARS) {\n delete record.operation;\n delete record.branchFact;\n if (Array.isArray(record.filesTouched)) {\n record.filesTouched = record.filesTouched.slice(0, 4).map((file) => bounded(String(file), 256));\n }\n record.structuredTruncated = true;\n response = responseAt(output, cursor);\n }\n if (JSON.stringify(response).length > RECALL_MAX_RESPONSE_CHARS) {\n const current = String(record.text);\n const firstCodePointChars = (current.codePointAt(0) ?? 0) > 0xffff ? 2 : 1;\n const minimalText = current.slice(0, Math.min(current.length, firstCodePointChars));\n const minimalRange = record.textRange as { start: number; end: number; total: number; complete: boolean };\n minimalRange.end = minimalRange.start + minimalText.length;\n minimalRange.complete = minimalRange.end >= minimalRange.total;\n output[0] = {\n index: record.index,\n entryId: record.entryId,\n parentId: record.parentId,\n type: record.type,\n role: record.role,\n timestamp: record.timestamp,\n isError: record.isError,\n ...(record.anchor !== undefined ? { anchor: record.anchor } : {}),\n text: minimalText,\n textRange: minimalRange,\n structuredTruncated: true,\n };\n cursor = minimalRange.complete\n ? { position: entryOffset + 1, textOffset: 0 }\n : { position: entryOffset, textOffset: minimalRange.end };\n response = responseAt(output, cursor);\n }\n }\n\n const endingLiveBranch = branches === \"active\" ? liveResolver?.(ref.file) : undefined;\n const endingObservation = observeSource(ref.file, branches, endingLiveBranch);\n if (!endingObservation || !sameSourceObservation(snapshot.observation, endingObservation)) {\n this.forgetExpansionSnapshot(snapshot);\n const actualState = fingerprintSource(ref.file);\n const actualLineage = reconstructSessionLineage(ref.file, branches, endingLiveBranch);\n if (\n !actualState ||\n !endingObservation ||\n actualState.sourceHash !== snapshot.sourceHash ||\n actualLineage.fingerprint !== snapshot.lineageFingerprint\n ) {\n return {\n session: ref.file,\n error: stalePointerError(\n ref.file,\n expectedSourceHash ?? snapshot.sourceHash,\n actualState?.sourceHash ?? \"\",\n expectedLineageFingerprint ?? snapshot.lineageFingerprint,\n actualLineage.fingerprint,\n ),\n entries: [],\n };\n }\n snapshot.observation = endingObservation;\n }\n if (response.next === null) {\n this.forgetExpansionSnapshot(snapshot);\n } else {\n snapshot.touchedAt = Date.now();\n this.rememberExpansionSnapshot(snapshot);\n }\n return response;\n }\n\n private async sessions(args: Record<string, unknown>): Promise<unknown> {\n const scope = typeof args.scope === \"string\" ? args.scope : undefined;\n const branches = parseBranches(args.branches, \"memory.sessions\");\n const limit =\n typeof args.limit === \"number\" && Number.isSafeInteger(args.limit) && args.limit >= 1\n ? Math.min(args.limit, SESSIONS_MAX)\n : SESSIONS_MAX;\n const offset =\n typeof args.offset === \"number\" && Number.isSafeInteger(args.offset) && args.offset >= 0\n ? args.offset\n : 0;\n const resolution = resolveRefs(scope, this.context, false);\n const total = resolution.refs.length;\n const refs = resolution.refs.slice(offset, offset + limit);\n const options = resolveIndexOptions(\n this.context.config,\n this.context.agentDir,\n branches,\n liveBranchResolver(this.context),\n );\n const index = loadTieredIndex(refs, resolveTierRefs(refs, this.context), options);\n const shards = new Map(index.shards.map((shard) => [shard.sessionFile, shard]));\n const digests = new Map(index.digests.map((digest) => [digest.file, digest]));\n const sessions = refs.map((ref) => {\n const tier = index.tiers.get(ref.file) ?? \"cold\";\n const shard = shards.get(ref.file);\n const digest = digests.get(ref.file);\n return {\n id: shard?.sessionId ?? digest?.sessionId ?? ref.id,\n file: ref.file,\n cwd: digest?.cwd ?? ref.cwd,\n mtime: ref.mtime,\n entryCount: shard?.entries.length ?? digest?.entryCount ?? 0,\n tier,\n branches,\n lineageFingerprint: shard?.lineageFingerprint ?? digest?.lineageFingerprint ?? null,\n };\n });\n return {\n scope: scope ?? \"session\",\n branches,\n offset,\n total,\n truncated: offset + sessions.length < total,\n sessions,\n ...(resolution.reasons.length > 0\n ? { error: unresolvedScopeError(resolution) }\n : {}),\n };\n }\n}\n", "import type { FabricExecutionOutcomeV1 } from \"../audit/trace.js\";\nimport type { EntryRange, MemoryCoverage } from \"./index.js\";\nimport type { MemoryBranches } from \"./lineage.js\";\nimport type {\n DigestHit,\n SearchResult,\n SearchSegment,\n SearchSegmentEntry,\n} from \"./search.js\";\nimport {\n compareLexical,\n normalizeMemoryPhrase,\n tokenizeLexical,\n type MemoryQueryMatch,\n type MemoryQueryMode,\n} from \"./tokenize.js\";\n\nexport const RECALL_DEFAULT_PAGE_SIZE = 10;\nexport const RECALL_MAX_PAGE_SIZE = 50;\nexport const RECALL_DEFAULT_SNIPPET_CHARS = 480;\nexport const RECALL_MAX_SNIPPET_CHARS = 2_000;\nexport const RECALL_MAX_RESPONSE_CHARS = 30_000;\n\nexport interface MemoryRecallCallArgs {\n query?: string;\n queryMode?: MemoryQueryMode;\n queryMatch?: MemoryQueryMatch;\n expectedSourceHash?: string;\n expectedLineageFingerprint?: string;\n branches?: MemoryBranches;\n scope?: string;\n offset?: number;\n pageSize?: number;\n snippetChars?: number;\n role?: string;\n tool?: string;\n ref?: string;\n provider?: string;\n action?: string;\n outcome?: FabricExecutionOutcomeV1;\n since?: number;\n until?: number;\n entryRange?: EntryRange;\n}\n\ninterface MemoryExpandCallArgs {\n session: string;\n expectedSourceHash?: string;\n expectedLineageFingerprint?: string;\n branches?: MemoryBranches;\n indices?: number[];\n entryIds?: string[];\n operationAddresses?: string[];\n entryRange?: EntryRange;\n before?: number;\n after?: number;\n entryOffset?: number;\n textOffset?: number;\n maxChars?: number;\n maxEntries?: number;\n}\n\ninterface MemorySourceBinding {\n sessionId: string;\n sessionFile: string;\n sourceHash: string;\n branches: MemoryBranches;\n lineageFingerprint: string;\n tier: \"hot\" | \"cold\";\n}\n\ninterface MemoryExpandFollow {\n ref: \"memory.expand\";\n args: MemoryExpandCallArgs;\n}\n\ninterface MemoryRecallFollow {\n ref: \"memory.recall\";\n args: MemoryRecallCallArgs;\n}\n\ninterface MemoryRecallEntryHit {\n kind: \"entry\";\n sessionId: string;\n tier: \"hot\" | \"cold\";\n index: number;\n entryId: string | null;\n parentId: string | null;\n operationAddress: string | null;\n type: string;\n role: string | null;\n tool: string | null;\n ref: string | null;\n provider: string | null;\n action: string | null;\n timestamp: number | null;\n isError: boolean;\n outcome?: FabricExecutionOutcomeV1;\n score: number;\n snippet: string;\n truncated: boolean;\n follow: MemoryExpandFollow;\n}\n\ninterface MemoryRecallSessionHit {\n kind: \"session\";\n sessionId: string;\n tier: \"cold\";\n cwd: string;\n lastTimestamp: number | null;\n score: number;\n matchedTerms: number;\n matchedStructuralEntries: number;\n follow: MemoryRecallFollow;\n}\n\ntype MemoryRecallHit = MemoryRecallEntryHit | MemoryRecallSessionHit;\n\ninterface MemoryRecallContinuation {\n ref: \"memory.recall\";\n args: MemoryRecallCallArgs;\n}\n\nexport interface MemoryRecallResponse {\n total: number;\n hits: MemoryRecallHit[];\n next: MemoryRecallContinuation | null;\n coverage: MemoryCoverage;\n}\n\ninterface RecallPresentationInput {\n result: SearchResult;\n query?: string;\n queryMode: MemoryQueryMode;\n coverage: MemoryCoverage;\n offset?: number;\n pageSize: number;\n snippetChars: number;\n requestArgs: MemoryRecallCallArgs;\n}\n\ninterface Snippet {\n text: string;\n truncated: boolean;\n}\n\nconst boundedMetadata = (value: string | null | undefined, max = 512): string | null => {\n if (value === undefined || value === null) return null;\n return value.length <= max ? value : `${value.slice(0, Math.max(1, max - 1))}\u2026`;\n};\n\nconst safeSlice = (text: string, start: number, end: number): string => {\n let safeStart = Math.max(0, start);\n let safeEnd = Math.min(text.length, end);\n const startCode = text.charCodeAt(safeStart);\n if (safeStart > 0 && startCode >= 0xdc00 && startCode <= 0xdfff) safeStart += 1;\n const endCode = text.charCodeAt(safeEnd - 1);\n if (safeEnd < text.length && endCode >= 0xd800 && endCode <= 0xdbff) safeEnd -= 1;\n return text.slice(safeStart, safeEnd);\n};\n\nconst snippetAnchor = (\n text: string,\n query: string | undefined,\n queryMode: MemoryQueryMode,\n): number => {\n if (!query) return 0;\n const normalized = normalizeMemoryPhrase(text);\n if (queryMode === \"phrase\") {\n const phrase = normalizeMemoryPhrase(query.trim());\n return Math.max(0, normalized.indexOf(phrase));\n }\n if (queryMode === \"literal\") {\n const terms = [...new Set(tokenizeLexical(query))].sort((left, right) =>\n right.length - left.length || left.localeCompare(right)\n );\n for (const term of terms) {\n const index = normalized.indexOf(term);\n if (index >= 0) return index;\n }\n }\n return 0;\n};\n\nconst makeSnippet = (\n text: string,\n query: string | undefined,\n queryMode: MemoryQueryMode,\n maxChars: number,\n): Snippet => {\n if (text.length <= maxChars) return { text, truncated: false };\n const anchor = snippetAnchor(text, query, queryMode);\n const leadingContext = Math.floor(maxChars / 3);\n let start = Math.max(0, anchor - leadingContext);\n let end = Math.min(text.length, start + maxChars);\n if (end - start < maxChars) start = Math.max(0, end - maxChars);\n const body = safeSlice(text, start, end);\n return {\n text: `${start > 0 ? \"\u2026\" : \"\"}${body}${end < text.length ? \"\u2026\" : \"\"}`,\n truncated: true,\n };\n};\n\nconst sourceFromSegment = (segment: SearchSegment): MemorySourceBinding => ({\n sessionId: boundedMetadata(segment.sessionId) ?? \"\",\n sessionFile: segment.sessionFile,\n sourceHash: segment.sourceHash,\n branches: segment.branches,\n lineageFingerprint: segment.lineageFingerprint,\n tier: segment.tier,\n});\n\nconst sourceFromDigest = (digest: DigestHit): MemorySourceBinding => ({\n sessionId: boundedMetadata(digest.sessionId) ?? \"\",\n sessionFile: digest.sessionFile,\n sourceHash: digest.sourceHash,\n branches: digest.branches,\n lineageFingerprint: digest.lineageFingerprint,\n tier: \"cold\",\n});\n\nconst expandArgs = (\n source: MemorySourceBinding,\n entry: SearchSegmentEntry[\"entry\"],\n): MemoryExpandCallArgs => ({\n session: source.sessionFile,\n expectedSourceHash: source.sourceHash,\n expectedLineageFingerprint: source.lineageFingerprint,\n branches: source.branches,\n indices: [entry.index],\n});\n\nconst entryHit = (\n segment: SearchSegment,\n item: SearchSegmentEntry,\n query: string | undefined,\n queryMode: MemoryQueryMode,\n snippetChars: number,\n): MemoryRecallEntryHit => {\n const entry = item.entry;\n const source = sourceFromSegment(segment);\n const snippet = makeSnippet(entry.text, query, queryMode, snippetChars);\n return {\n kind: \"entry\",\n sessionId: source.sessionId,\n tier: source.tier,\n index: entry.index,\n entryId: boundedMetadata(entry.entryId),\n parentId: boundedMetadata(entry.parentId),\n operationAddress: boundedMetadata(entry.operationAddress),\n type: boundedMetadata(entry.type) ?? \"entry\",\n role: boundedMetadata(entry.role),\n tool: boundedMetadata(entry.toolName),\n ref: boundedMetadata(entry.ref),\n provider: boundedMetadata(entry.provider),\n action: boundedMetadata(entry.action),\n timestamp: entry.timestamp,\n isError: entry.isError,\n ...(entry.outcome ? { outcome: entry.outcome } : {}),\n score: item.score,\n snippet: snippet.text,\n truncated: snippet.truncated || entry.truncated,\n follow: { ref: \"memory.expand\", args: expandArgs(source, entry) },\n };\n};\n\nconst hydrationArgs = (\n digest: DigestHit,\n request: MemoryRecallCallArgs,\n): MemoryRecallCallArgs => {\n const { offset: _offset, entryRange: _entryRange, ...base } = request;\n return {\n ...base,\n scope: `session:${digest.sessionFile}`,\n branches: digest.branches,\n expectedSourceHash: digest.sourceHash,\n expectedLineageFingerprint: digest.lineageFingerprint,\n };\n};\n\nconst sessionHit = (\n digest: DigestHit,\n request: MemoryRecallCallArgs,\n): MemoryRecallSessionHit => {\n const source = sourceFromDigest(digest);\n return {\n kind: \"session\",\n sessionId: source.sessionId,\n tier: \"cold\",\n cwd: boundedMetadata(digest.cwd, 2_048) ?? \"\",\n lastTimestamp: digest.lastTs,\n score: digest.score,\n matchedTerms: digest.matchedTerms,\n matchedStructuralEntries: digest.matchedStructuralEntries,\n follow: { ref: \"memory.recall\", args: hydrationArgs(digest, request) },\n };\n};\n\ntype RecallCandidate =\n | { kind: \"entry\"; segment: SearchSegment; item: SearchSegmentEntry }\n | { kind: \"session\"; digest: DigestHit };\n\nconst recallCandidateCache = new WeakMap<SearchResult, RecallCandidate[]>();\n\nconst flattenCandidates = (result: SearchResult): RecallCandidate[] => {\n const cached = recallCandidateCache.get(result);\n if (cached) return cached;\n const candidates: RecallCandidate[] = [];\n for (const item of result.items) {\n if (item.kind === \"digest\") {\n candidates.push({ kind: \"session\", digest: item.digest });\n continue;\n }\n for (const entry of item.segment.entries) {\n if (entry.matched) candidates.push({ kind: \"entry\", segment: item.segment, item: entry });\n }\n }\n candidates.sort((left, right) => {\n const leftScore = left.kind === \"entry\" ? left.item.score : left.digest.score;\n const rightScore = right.kind === \"entry\" ? right.item.score : right.digest.score;\n if (rightScore !== leftScore) return rightScore - leftScore;\n const leftMtime = left.kind === \"entry\" ? left.segment.sessionMtime : left.digest.sessionMtime;\n const rightMtime = right.kind === \"entry\" ? right.segment.sessionMtime : right.digest.sessionMtime;\n if (rightMtime !== leftMtime) return rightMtime - leftMtime;\n if (left.kind !== right.kind) return left.kind === \"entry\" ? -1 : 1;\n if (left.kind === \"entry\" && right.kind === \"entry\") {\n if (left.item.entry.index !== right.item.entry.index) {\n return left.item.entry.index - right.item.entry.index;\n }\n return compareLexical(left.segment.sessionFile, right.segment.sessionFile);\n }\n if (left.kind === \"session\" && right.kind === \"session\") {\n return compareLexical(left.digest.sessionFile, right.digest.sessionFile);\n }\n return 0;\n });\n recallCandidateCache.set(result, candidates);\n return candidates;\n};\n\nconst materializeCandidate = (\n candidate: RecallCandidate,\n query: string | undefined,\n queryMode: MemoryQueryMode,\n snippetChars: number,\n request: MemoryRecallCallArgs,\n): MemoryRecallHit => candidate.kind === \"session\"\n ? sessionHit(candidate.digest, request)\n : entryHit(candidate.segment, candidate.item, query, queryMode, snippetChars);\n\nconst canonicalNextArgs = (\n request: MemoryRecallCallArgs,\n offset: number,\n): MemoryRecallCallArgs => {\n const { offset: _offset, ...base } = request;\n return { ...base, offset };\n};\n\nexport const presentRecall = (input: RecallPresentationInput): MemoryRecallResponse => {\n const candidates = flattenCandidates(input.result);\n const start = input.offset ?? 0;\n let selected = candidates.slice(start, start + input.pageSize);\n\n const build = (pageCandidates: RecallCandidate[]): MemoryRecallResponse => {\n const hits = pageCandidates.map((candidate) =>\n materializeCandidate(\n candidate,\n input.query,\n input.queryMode,\n input.snippetChars,\n input.requestArgs,\n )\n );\n return {\n total: candidates.length,\n hits,\n next: start + hits.length < candidates.length\n ? { ref: \"memory.recall\", args: canonicalNextArgs(input.requestArgs, start + hits.length) }\n : null,\n coverage: input.coverage,\n };\n };\n\n let response = build(selected);\n while (selected.length > 1 && JSON.stringify(response).length > RECALL_MAX_RESPONSE_CHARS) {\n selected = selected.slice(0, -1);\n response = build(selected);\n }\n return response;\n};\n", "import type { FabricActionDescriptor } from \"../protocol.js\";\n\n// Argument-shape normalization shared by the stable Fabric providers,\n// mirroring the OMP core tool architecture:\n//\n// 1. prepareArguments canonicalizes near-miss argument spellings at the\n// registry prepare stage \u2014 aliases resolve to the canonical key (which\n// wins on conflict), value spellings repair, numeric strings coerce for\n// schema-declared numeric fields, and nullish values of declared\n// optionals are stripped.\n// 2. validateArguments then owns the didactic failure tier: required\n// canonical keys are enforced and unknown keys fail\n// additionalProperties: false validation with the offending path named.\n//\n// Most of the repair surface is derived from each action's inputSchema\n// rather than maintained by hand: key casing/spacing variants and\n// singular/plural near-misses come from the declared property names,\n// numeric coercion from the declared property types, and enum-value\n// repairs (casing variants plus the shared synonym classes below) from the\n// declared enum members. Only genuinely semantic synonyms need explicit\n// vocabulary: the shared KEY_SYNONYM_CLASSES / ENUM_VALUE_CLASSES classes\n// here, and provider-local `values` tables where the schema spells a\n// concept as a free string instead of an enum (memory scope).\n\ninterface JsonSchemaObject {\n type?: unknown;\n properties?: unknown;\n enum?: unknown;\n items?: unknown;\n oneOf?: unknown;\n anyOf?: unknown;\n}\n\nexport interface ArgNormalizationSpec {\n // Explicit escape-hatch rows. Prefer derivation or a shared synonym\n // class; keep entries here only for action-local semantics.\n aliases?: Readonly<Record<string, string>>;\n numerics?: readonly string[];\n numericArrays?: readonly string[];\n values?: Readonly<Record<string, Readonly<Record<string, unknown>>>>;\n // Declared property names whose nullish values are stripped before\n // validation. Derived from the descriptor schema when omitted.\n knownKeys?: readonly string[];\n}\n\nexport type ActionArgNormalizer = (\n actionName: string,\n args: Record<string, unknown>,\n) => Record<string, unknown>;\n\n// Casing/spacing/underscore-insensitive key and value form, e.g.\n// \"requested_by\", \"requestedBy\", and \"REQUESTED-BY\" all share one form.\nconst normalizeForm = (key: string): string =>\n key.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n\n// Semantic near-miss vocabulary shared by every stable provider. A spilled\n// key belonging to a class repairs to a declared canonical key only when\n// exactly one member of that class is declared by the action's schema \u2014\n// ambiguity (or absence) leaves the key untouched so the validate stage\n// owns its failure. `id` deliberately appears in several classes: the\n// declared members of each action's schema disambiguate which repair fires\n// (memory.expand takes a session id; agents.wait takes an agent id).\nconst KEY_SYNONYM_CLASSES: ReadonlyArray<ReadonlyArray<string>> = [\n [\"session\", \"sessionId\", \"id\", \"file\", \"path\"],\n [\"hypothesisId\", \"id\"],\n [\"id\", \"agentId\", \"actorId\", \"runId\"],\n [\"query\", \"q\"],\n [\"limit\", \"max\", \"pageSize\"],\n [\"task\", \"prompt\", \"instructions\"],\n [\"label\", \"labels\", \"name\", \"title\"],\n [\"summary\", \"description\"],\n [\"text\", \"message\", \"body\"],\n [\"check\", \"command\", \"cmd\", \"script\", \"predicate\"],\n [\"files\", \"paths\"],\n [\"ifVersion\", \"versionRef\", \"version\"],\n [\"indices\", \"index\"],\n];\n\nconst KEY_CLASS_FORMS = KEY_SYNONYM_CLASSES.map(\n (cls) => new Set(cls.map(normalizeForm)),\n);\n\n// Synonym classes for schema enum values, applied only when the declared\n// enum contains exactly one class member. Scope spellings such as `cwd` \u2192\n// \"project\" repair wherever an enum spells that concept this way; a schema\n// whose enum lacks the concept keeps the value untouched for validation.\nconst ENUM_VALUE_CLASSES: ReadonlyArray<ReadonlyArray<string>> = [\n [\"project\", \"cwd\", \"repo\", \"repository\", \"workspace\", \"checkout\", \"tree\"],\n [\"global\", \"all\"],\n [\"permanent\", \"pinned\", \"sticky\", \"durable\"],\n];\n\nconst VALUE_CLASS_FORMS = ENUM_VALUE_CLASSES.map(\n (cls) => new Set(cls.map(normalizeForm)),\n);\n\ntype NumericKind = \"scalar\" | \"array\" | undefined;\n\nconst numericKind = (property: unknown): NumericKind => {\n if (!property || typeof property !== \"object\") return undefined;\n const schema = property as JsonSchemaObject;\n if (schema.type === \"number\" || schema.type === \"integer\") return \"scalar\";\n if (schema.type === \"array\") {\n const items = schema.items;\n if (\n items &&\n typeof items === \"object\" &&\n ((items as JsonSchemaObject).type === \"number\" ||\n (items as JsonSchemaObject).type === \"integer\")\n ) {\n return \"array\";\n }\n }\n return undefined;\n};\n\nconst stringEnumValues = (property: unknown): readonly string[] | undefined => {\n if (!property || typeof property !== \"object\") return undefined;\n const schema = property as JsonSchemaObject;\n if (Array.isArray(schema.enum)) {\n const values = schema.enum.filter(\n (entry): entry is string => typeof entry === \"string\",\n );\n return values.length > 0 ? values : undefined;\n }\n for (const branch of [schema.oneOf, schema.anyOf]) {\n if (!Array.isArray(branch)) continue;\n const consts = branch\n .map((entry) =>\n entry && typeof entry === \"object\"\n ? (entry as { const?: unknown }).const\n : undefined,\n )\n .filter((entry): entry is string => typeof entry === \"string\");\n if (consts.length > 0) return consts;\n }\n return undefined;\n};\n\n// form \u2192 enum value. Exact forms of declared members win; class synonyms\n// fill in only when exactly one declared member belongs to the class.\nconst deriveEnumValueMap = (\n values: readonly string[],\n): Map<string, string> => {\n const map = new Map<string, string>();\n const seen = new Map<string, string | undefined>();\n for (const value of values) {\n const form = normalizeForm(value);\n seen.set(form, seen.has(form) ? undefined : value);\n }\n for (const [form, value] of seen) if (value !== undefined) map.set(form, value);\n for (const classForms of VALUE_CLASS_FORMS) {\n const members = values.filter((value) => classForms.has(normalizeForm(value)));\n if (members.length !== 1) continue;\n const [hit] = members as [string];\n for (const form of classForms) {\n if (form !== normalizeForm(hit) && !map.has(form)) map.set(form, hit);\n }\n }\n return map;\n};\n\ntype DerivedAction = {\n declared: Set<string>;\n declaredForms: Map<string, string>;\n singulars: Map<string, string>;\n numerics: Set<string>;\n numericArrays: Set<string>;\n values: Map<string, Map<string, unknown>>;\n aliases?: Readonly<Record<string, string>> | undefined;\n};\n\n// The value-column meaning of the schema, precomputed once per action.\nconst deriveAction = (\n inputSchema: JsonSchemaObject | undefined,\n explicit: ArgNormalizationSpec | undefined,\n): DerivedAction => {\n const properties =\n inputSchema && typeof inputSchema === \"object\" &&\n inputSchema.properties &&\n typeof inputSchema.properties === \"object\"\n ? (inputSchema.properties as Record<string, unknown>)\n : undefined;\n const declared = new Set(Object.keys(properties ?? {}));\n const declaredForms = new Map<string, string>();\n const ambiguousForms = new Set<string>();\n for (const key of declared) {\n const form = normalizeForm(key);\n if (declaredForms.has(form)) {\n ambiguousForms.add(form);\n declaredForms.delete(form);\n } else if (!ambiguousForms.has(form)) {\n declaredForms.set(form, key);\n }\n }\n const singulars = new Map<string, string>();\n for (const key of declared) {\n const form = normalizeForm(key);\n if (!form.endsWith(\"s\")) continue;\n const singular = form.slice(0, -1);\n if (!singular || declaredForms.has(singular) || singular === form) continue;\n if (singulars.get(singular) !== undefined) singulars.delete(singular);\n else singulars.set(singular, key);\n }\n for (const form of ambiguousForms) singulars.delete(form);\n\n const numerics = new Set(explicit?.numerics ?? []);\n const numericArrays = new Set(explicit?.numericArrays ?? []);\n const values = new Map<string, Map<string, unknown>>();\n if (properties) {\n for (const [key, property] of Object.entries(properties)) {\n const kind = numericKind(property);\n if (kind === \"scalar\") numerics.add(key);\n else if (kind === \"array\") numericArrays.add(key);\n const enumValues = stringEnumValues(property);\n if (enumValues) values.set(key, new Map(deriveEnumValueMap(enumValues)));\n }\n }\n for (const [key, remaps] of Object.entries(explicit?.values ?? {})) {\n const map = values.get(key) ?? new Map<string, unknown>();\n for (const [spelling, target] of Object.entries(remaps)) {\n map.set(normalizeForm(spelling), target);\n }\n values.set(key, map);\n }\n return { declared, declaredForms, singulars, numerics, numericArrays, values, aliases: explicit?.aliases };\n};\n\nconst lexiconRepair = (\n form: string,\n declaredForms: Map<string, string>,\n): string | undefined => {\n const candidates = new Set<string>();\n for (const classForms of KEY_CLASS_FORMS) {\n if (!classForms.has(form)) continue;\n for (const [declaredForm, declaredKey] of declaredForms) {\n if (declaredForm !== form && classForms.has(declaredForm)) {\n candidates.add(declaredKey);\n }\n }\n }\n return candidates.size === 1 ? [...candidates][0] : undefined;\n};\n\n/** Unique declared key for a spilled spelling, or undefined when already\n * canonical / ambiguous / unmatched. Used by the catalog repair compiler. */\nexport const uniqueDeclaredKeyForSpelling = (\n spilled: string,\n declared: readonly string[],\n): string | undefined => {\n if (declared.includes(spilled)) return undefined;\n const derived = deriveAction(\n {\n type: \"object\",\n properties: Object.fromEntries(declared.map((key) => [key, {}])),\n },\n undefined,\n );\n const form = normalizeForm(spilled);\n const canonical =\n derived.declaredForms.get(form) ??\n derived.singulars.get(form) ??\n lexiconRepair(form, derived.declaredForms);\n return canonical && canonical !== spilled ? canonical : undefined;\n};\n\nconst applyDerived = (\n args: Record<string, unknown>,\n derived: DerivedAction,\n): Record<string, unknown> => {\n const out: Record<string, unknown> = { ...args };\n\n // Explicit action-local aliases first, then derived repairs. Both obey\n // canonical-wins: the canonical key keeps an already-supplied value and\n // the spelling variant is dropped either way.\n const repair = (alias: string, canonical: string) => {\n if (!(alias in out) || alias === canonical) return;\n if (!(canonical in out)) out[canonical] = out[alias];\n delete out[alias];\n };\n for (const [alias, canonical] of Object.entries(derived.aliases ?? {})) {\n repair(alias, canonical);\n }\n for (const key of [...Object.keys(out)]) {\n if (derived.declared.has(key)) continue;\n const form = normalizeForm(key);\n const canonical =\n derived.declaredForms.get(form) ??\n derived.singulars.get(form) ??\n lexiconRepair(form, derived.declaredForms);\n if (canonical && canonical !== key) repair(key, canonical);\n }\n\n for (const key of derived.numerics) {\n const value = out[key];\n if (typeof value === \"string\" && value.trim() !== \"\" && !Number.isNaN(Number(value))) {\n out[key] = Number(value);\n }\n }\n for (const key of derived.numericArrays) {\n const value = out[key];\n if (Array.isArray(value)) {\n out[key] = value.map((entry) =>\n typeof entry === \"string\" && entry.trim() !== \"\" && !Number.isNaN(Number(entry))\n ? Number(entry)\n : entry,\n );\n }\n }\n for (const [key, remaps] of derived.values) {\n const value = out[key];\n if (typeof value === \"string\") {\n const next = remaps.get(normalizeForm(value));\n if (next !== undefined) out[key] = next;\n }\n }\n if (derived.declared.size > 0) {\n for (const key of Object.keys(out)) {\n if (derived.declared.has(key) && (out[key] === null || out[key] === undefined)) {\n delete out[key];\n }\n }\n }\n return out;\n};\n\n// Low-level explicit-spec normalizer. Used directly by tests and as the\n// shared mechanics for per-key aliases, value spellings, numeric strings,\n// and nullish stripping; actionArgNormalizer layers schema derivation and\n// the shared synonym lexicon on top.\nexport const normalizeActionArgs = (\n args: Record<string, unknown>,\n spec: ArgNormalizationSpec,\n): Record<string, unknown> => {\n const derived: DerivedAction = {\n // The low-level path strips nullish values only for explicit knownKeys;\n // schema-derived declared keys come from actionArgNormalizer.\n declared: new Set(spec.knownKeys ?? []),\n declaredForms: new Map(),\n singulars: new Map(),\n numerics: new Set(spec.numerics ?? []),\n numericArrays: new Set(spec.numericArrays ?? []),\n values: new Map(\n Object.entries(spec.values ?? {}).map(([key, remaps]) => [\n key,\n new Map(\n Object.entries(remaps).map(([spelling, target]) => [normalizeForm(spelling), target]),\n ),\n ]),\n ),\n aliases: spec.aliases,\n };\n if (!args || typeof args !== \"object\" || Array.isArray(args)) return args;\n return applyDerived(args, derived);\n};\n\n// Build a provider prepareArguments hook. Repair behavior derives from each\n// action's inputSchema (declared key forms, singular/plural variants,\n// numeric property types, enum value spellings) plus the shared synonym\n// lexicon; the residual table holds only action-local semantics the schema\n// cannot express.\nexport const actionArgNormalizer = (\n describeActions: () => ReadonlyArray<Pick<FabricActionDescriptor, \"name\" | \"inputSchema\">>,\n table: Record<string, ArgNormalizationSpec> = {},\n): ActionArgNormalizer => {\n const derived = new Map<string, DerivedAction>();\n for (const descriptor of describeActions()) {\n derived.set(\n descriptor.name,\n deriveAction(\n descriptor.inputSchema as JsonSchemaObject | undefined,\n table[descriptor.name],\n ),\n );\n }\n return (actionName, args) => {\n if (!args || typeof args !== \"object\" || Array.isArray(args)) return args;\n const action = derived.get(actionName);\n return action ? applyDerived(args, action) : args;\n };\n};\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,OAAO,QAAQ;AACf,OAAO,UAAU;;;ACSV,IAAM,2BAA2B;AACjC,IAAM,uBAAuB;AAC7B,IAAM,+BAA+B;AACrC,IAAM,2BAA2B;AACjC,IAAM,4BAA4B;AA6HzC,IAAM,kBAAkB,CAAC,OAAkC,MAAM,QAAuB;AACtF,MAAI,UAAU,UAAa,UAAU,KAAM,QAAO;AAClD,SAAO,MAAM,UAAU,MAAM,QAAQ,GAAG,MAAM,MAAM,GAAG,KAAK,IAAI,GAAG,MAAM,CAAC,CAAC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/agents/thinking-transfer.ts", "../../src/agents/handoff.ts", "../../src/topology/peer-settle.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n SessionEntry,\n SessionMessageEntry,\n} from \"@oh-my-pi/pi-coding-agent\";\n\n// Cross-model thinking transfer for trajectory handoffs.\n//\n// OMP replays stored thinking blocks verbatim per provider: a Codex Responses\n// reasoning item rides as a provider-shaped `thinkingSignature` blob, and the\n// OpenAI-completions transform (pi-ai) uses that blob as the *request field\n// name* when the history is handed to a different provider \u2014 landing prior\n// deliberation in a junk field while the real `reasoning_content` stays\n// empty. Signature-sensitive families (Anthropic) reject foreign signatures\n// outright. This module applies a family-aware policy to the fabric-owned\n// child session at the handoff boundary, where rewriting is safe because the\n// source session (ground truth) is never touched:\n//\n// preserved \u2014 same provider and api family: native replay already works.\n// re-signed \u2014 openai-completions reasoning targets: thinking text is kept\n// and the signature normalized to \"reasoning_content\" so preserve-thinking\n// servers (Kimi, DeepSeek, \u2026) actually receive prior reasoning.\n// stripped \u2014 everything else: thinking blocks and foreign thought\n// signatures are removed so no bogus field or invalid signature is sent;\n// a bounded, entry-id-cited digest keeps continuity instead.\n\ninterface ThinkingTransferSource {\n provider: string;\n modelId: string;\n /** pi-ai transport api of the source model, when the registry resolves it. */\n api?: string | undefined;\n}\n\ninterface ThinkingTransferTarget {\n provider: string;\n modelId: string;\n api?: string | undefined;\n reasoning?: boolean | undefined;\n /** Model replays thinking as visible text; deliberation must not leak there. */\n requiresThinkingAsText?: boolean | undefined;\n}\n\nexport interface ThinkingTransferInput {\n source?: ThinkingTransferSource;\n target: ThinkingTransferTarget;\n}\n\nexport type ThinkingTransferPolicy = \"preserved\" | \"re-signed\" | \"stripped\";\n\nexport interface ThinkingTransferReport {\n policy: ThinkingTransferPolicy;\n translated: number;\n dropped: number;\n}\n\n// Field name pi-ai emits when a thinking block's signature is exactly this\n// string (the opencode-go \"reasoning\" \u2192 \"reasoning_content\" remap proves the\n// convention): the request then carries real prior reasoning content.\nexport const REASONING_CONTENT_SIGNATURE = \"reasoning_content\";\n\nconst OPENAI_COMPLETIONS_API = \"openai-completions\";\n\nexport const thinkingTransferPolicy = (\n input: ThinkingTransferInput,\n): ThinkingTransferPolicy => {\n const { source, target } = input;\n // Same provider with equal or unknown apis: native replay is provider-shipped\n // and the default experience; only an api-proof mismatch transfers.\n if (\n source &&\n source.provider === target.provider &&\n (source.api === undefined || target.api === undefined || source.api === target.api)\n ) {\n return \"preserved\";\n }\n if (\n target.api === OPENAI_COMPLETIONS_API &&\n target.reasoning === true &&\n target.requiresThinkingAsText !== true\n ) {\n return \"re-signed\";\n }\n return \"stripped\";\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isThinkingPart = (part: unknown): part is Record<string, unknown> =>\n isRecord(part) && part.type === \"thinking\";\n\n// Clone-and-rewrite walk over assistant content parts. Also clears foreign\n// `thoughtSignature` artifacts (Google-style reasoning_details), which are as\n// provider-bound as thinking signatures. Callers own the input; the original\n// entries are never mutated.\nexport const translateThinkingForExecutor = (\n entries: SessionEntry[],\n policy: ThinkingTransferPolicy,\n): { entries: SessionEntry[]; report: ThinkingTransferReport } => {\n if (policy === \"preserved\") {\n return { entries, report: { policy, translated: 0, dropped: 0 } };\n }\n const clone = structuredClone(entries);\n let translated = 0;\n let dropped = 0;\n for (const entry of clone) {\n if (entry.type !== \"message\") continue;\n const message = (entry as SessionMessageEntry).message as {\n role?: unknown;\n content?: unknown;\n };\n if (message.role !== \"assistant\" || !Array.isArray(message.content)) continue;\n const kept: unknown[] = [];\n for (const part of message.content as unknown[]) {\n if (isRecord(part) && part.type === \"toolCall\") {\n delete part.thoughtSignature;\n kept.push(part);\n continue;\n }\n if (!isThinkingPart(part)) {\n kept.push(part);\n continue;\n }\n const text = typeof part.thinking === \"string\" ? part.thinking : \"\";\n if (policy === \"re-signed\" && part.redacted !== true && text.trim().length > 0) {\n part.thinkingSignature = REASONING_CONTENT_SIGNATURE;\n translated += 1;\n kept.push(part);\n continue;\n }\n dropped += 1;\n }\n message.content = kept;\n }\n return { entries: clone, report: { policy, translated, dropped } };\n};\n\nexport const THINKING_DIGEST_CUSTOM_TYPE = \"omp-fabric-handoff-thinking\";\n\nconst MAX_DIGEST_BLOCKS = 8;\nconst MAX_DIGEST_LINE = 80;\nconst MAX_DIGEST_BYTES = 2048;\n\nexport interface ThinkingDigest {\n content: string;\n citedBlocks: number;\n}\n\nconst firstLineOf = (text: string): string => {\n const end = text.indexOf(\"\\n\");\n return end === -1 ? text : text.slice(0, end);\n};\n\nconst truncate = (text: string, max: number): string =>\n text.length > max ? text.slice(0, max) : text;\n\nconst clipUtf8 = (text: string, maxBytes: number): string => {\n if (Buffer.byteLength(text, \"utf8\") <= maxBytes) return text;\n let out = \"\";\n let bytes = 0;\n for (const char of text) {\n const size = Buffer.byteLength(char, \"utf8\");\n if (bytes + size > maxBytes) break;\n out += char;\n bytes += size;\n }\n return out;\n};\n\n// Bounded continuity bridge for executors whose reasoning channel cannot\n// accept prior thinking: the newest few first-lines, cited by stable entry id,\n// explicitly labeled as deliberation so they read as context, not style. The\n// full scratchpad remains addressable in the source session.\nexport const buildThinkingDigest = (\n entries: SessionEntry[],\n input: ThinkingTransferInput,\n): ThinkingDigest | undefined => {\n const blocks: Array<{ entryId: string; line: string }> = [];\n for (const entry of entries) {\n if (entry.type !== \"message\") continue;\n const message = (entry as SessionMessageEntry).message as {\n role?: unknown;\n content?: unknown;\n };\n if (message.role !== \"assistant\" || !Array.isArray(message.content)) continue;\n for (const part of message.content as unknown[]) {\n if (!isThinkingPart(part)) continue;\n const text = typeof part.thinking === \"string\" ? part.thinking : \"\";\n const line = truncate(firstLineOf(text).trim(), MAX_DIGEST_LINE);\n if (line) blocks.push({ entryId: entry.id, line });\n }\n }\n if (blocks.length === 0) return undefined;\n const recent = blocks.slice(-MAX_DIGEST_BLOCKS);\n const omitted = blocks.length - recent.length;\n const sourceId = input.source\n ? `${input.source.provider}/${input.source.modelId}`\n : \"the prior model\";\n const targetId = `${input.target.provider}/${input.target.modelId}`;\n const lines = [\n \"Prewalk handoff continuity digest (deliberation, not commitments).\",\n `Thinking from ${sourceId} was not transferred: ${targetId} cannot replay it (incompatible reasoning channels). Most recent lines:`,\n ...recent.map((block) => `- [entry ${block.entryId}] ${block.line}`),\n ];\n if (omitted > 0) lines.push(`(omitted ${omitted} older thinking blocks)`);\n lines.push(\"Full thinking remains addressable in the source session by entry id.\");\n return {\n content: clipUtf8(lines.join(\"\\n\"), MAX_DIGEST_BYTES),\n citedBlocks: recent.length,\n };\n};\n", "import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n CURRENT_SESSION_VERSION,\n SessionManager,\n type SessionEntry,\n type SessionMessageEntry,\n} from \"@oh-my-pi/pi-coding-agent\";\nimport { compileFabricSummary, rawContextTokens } from \"../compaction/hook.js\";\nimport {\n compactionRequestBoundsError,\n encodeCompactionRequest,\n} from \"../compaction/instructions.js\";\nimport type {\n AgentSessionSeed,\n AgentToolResultMessage,\n HandoffCompactionRequest,\n} from \"./types.js\";\nimport {\n buildThinkingDigest,\n THINKING_DIGEST_CUSTOM_TYPE,\n thinkingTransferPolicy,\n translateThinkingForExecutor,\n type ThinkingTransferInput,\n type ThinkingTransferReport,\n} from \"./thinking-transfer.js\";\n\ninterface HandoffSessionSource {\n getBranch(): SessionEntry[];\n getEntry(id: string): SessionEntry | undefined;\n getLeafId(): string | null;\n getSessionFile(): string | undefined;\n getSessionId(): string;\n}\n\ninterface CurrentModel {\n provider: string;\n id: string;\n}\n\ntype NativeAssistantMessage = Extract<\n SessionMessageEntry[\"message\"],\n { role: \"assistant\" }\n>;\ntype NativeAssistantEntry = SessionMessageEntry & {\n message: NativeAssistantMessage;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\ninterface HandoffCompactionOutcome {\n applied: boolean;\n reason?: string;\n sections?: string[];\n tokensBefore?: number;\n firstKeptEntryId?: string;\n}\n\n// Validate the model-facing agents.handoff `compact` option against the same\n// bounds as compact.request. Called both when the request is scheduled (inside\n// the guest) and when the boundary runner replays it.\nexport const checkedHandoffCompaction = (\n value: unknown,\n): HandoffCompactionRequest | undefined => {\n if (value === undefined || value === false) return undefined;\n const input = value === true ? {} : value;\n if (!isRecord(input)) {\n throw new Error(\n \"Invalid agents.handoff compact arguments: compact must be true or an object with instructions/preserve\",\n );\n }\n if (input.instructions !== undefined && typeof input.instructions !== \"string\") {\n throw new Error(\"Invalid agents.handoff compact arguments: instructions must be a string\");\n }\n if (\n input.preserve !== undefined &&\n (!Array.isArray(input.preserve) || input.preserve.some((item) => typeof item !== \"string\"))\n ) {\n throw new Error(\n \"Invalid agents.handoff compact arguments: preserve must be an array of strings\",\n );\n }\n const request: HandoffCompactionRequest = {\n ...(typeof input.instructions === \"string\" ? { instructions: input.instructions } : {}),\n ...(input.preserve !== undefined ? { preserve: input.preserve as string[] } : {}),\n };\n const boundsError = compactionRequestBoundsError(request);\n if (boundsError) {\n throw new Error(`Invalid agents.handoff compact arguments: ${boundsError.message}`);\n }\n return request;\n};\n\nconst isToolCall = (value: unknown): value is {\n type: \"toolCall\";\n id: string;\n name: string;\n arguments: Record<string, unknown>;\n} =>\n isRecord(value) &&\n value.type === \"toolCall\" &&\n typeof value.id === \"string\" &&\n typeof value.name === \"string\" &&\n isRecord(value.arguments);\n\nconst activeFabricTurn = (\n source: HandoffSessionSource,\n outerToolCallId: string,\n): NativeAssistantEntry => {\n const leafId = source.getLeafId();\n const entry = leafId ? source.getEntry(leafId) : undefined;\n if (entry?.type !== \"message\" || entry.message.role !== \"assistant\") {\n throw new Error(\n \"Trajectory handoff requires the active fabric_exec assistant turn to be the session leaf\",\n );\n }\n const content = Array.isArray(entry.message.content) ? entry.message.content : [];\n const toolCalls = content.filter(isToolCall);\n if (!toolCalls.some((call) => call.id === outerToolCallId)) {\n throw new Error(\n \"Trajectory handoff could not find the active fabric_exec assistant turn in the OMP session\",\n );\n }\n if (toolCalls.length !== 1 || toolCalls[0]?.name !== \"fabric_exec\") {\n throw new Error(\n \"Trajectory handoff requires fabric_exec to be the only top-level tool call in its assistant turn\",\n );\n }\n return entry as NativeAssistantEntry;\n};\n\nexport const snapshotHandoffSession = (\n source: HandoffSessionSource,\n currentModel: CurrentModel | undefined,\n outerToolResult: AgentToolResultMessage,\n outerToolCallId: string,\n carryBranch = false,\n): AgentSessionSeed => {\n if (\n outerToolResult.toolCallId !== outerToolCallId ||\n outerToolResult.toolName !== \"fabric_exec\"\n ) {\n throw new Error(\"Trajectory handoff requires the finalized outer fabric_exec result\");\n }\n const active = activeFabricTurn(source, outerToolCallId);\n const sourceSessionFile = source.getSessionFile();\n const branch = source.getBranch();\n let model = currentModel\n ? { provider: currentModel.provider, modelId: currentModel.id }\n : undefined;\n let thinkingLevel: string | undefined;\n for (let index = branch.length - 1; index >= 0; index--) {\n const entry = branch[index];\n if (!thinkingLevel && entry?.type === \"thinking_level_change\") {\n thinkingLevel = entry.thinkingLevel ?? undefined;\n }\n if (!model && entry?.type === \"model_change\") {\n const separator = entry.model.indexOf(\"/\");\n if (separator > 0 && separator < entry.model.length - 1) {\n model = { provider: entry.model.slice(0, separator), modelId: entry.model.slice(separator + 1) };\n }\n }\n if (model && thinkingLevel) break;\n }\n return {\n sourceSessionId: source.getSessionId(),\n ...(sourceSessionFile ? { sourceSessionFile } : {}),\n sourceBranchLeafId: active.id,\n ...(!sourceSessionFile || carryBranch ? { sourceBranch: structuredClone(branch) } : {}),\n ...(model ? { sourceModel: model } : {}),\n ...(thinkingLevel ? { sourceThinkingLevel: thinkingLevel } : {}),\n outerToolResult: structuredClone(outerToolResult),\n };\n};\n\nconst materializeBranch = async (\n seed: AgentSessionSeed,\n cwd: string,\n directory: string,\n): Promise<SessionManager> => {\n if (!seed.sourceBranch) {\n throw new Error(\"In-memory trajectory handoff is missing its source branch\");\n }\n const id = randomUUID();\n const sessionFile = path.join(directory, `handoff-${id}.jsonl`);\n const header = {\n type: \"session\" as const,\n version: CURRENT_SESSION_VERSION,\n id,\n timestamp: new Date().toISOString(),\n cwd,\n ...(seed.sourceSessionFile ? { parentSession: seed.sourceSessionFile } : {}),\n };\n fs.writeFileSync(\n sessionFile,\n `${[header, ...seed.sourceBranch].map((entry) => JSON.stringify(entry)).join(\"\\n\")}\\n`,\n { encoding: \"utf8\", mode: 0o600, flag: \"wx\" },\n );\n return SessionManager.open(sessionFile, directory, undefined, { initialCwd: cwd });\n};\n\nconst forkBranch = async (\n seed: AgentSessionSeed,\n cwd: string,\n directory: string,\n): Promise<SessionManager> => {\n if (!seed.sourceSessionFile) return materializeBranch(seed, cwd, directory);\n const fork = await SessionManager.open(seed.sourceSessionFile, directory, undefined, { initialCwd: cwd });\n if (!fork.getEntry(seed.sourceBranchLeafId)) {\n throw new Error(\n `Trajectory handoff branch point ${seed.sourceBranchLeafId} is missing from the persisted OMP session`,\n );\n }\n fork.createBranchedSession(seed.sourceBranchLeafId);\n const sessionFile = fork.getSessionFile();\n if (!sessionFile) {\n throw new Error(\"Trajectory handoff could not create a persisted OMP session branch\");\n }\n return SessionManager.open(sessionFile, directory, undefined, { initialCwd: cwd });\n};\n\n// File-backed read of the exact branch prefix, cloned so transfer translation\n// never mutates the source session's live entries. Used instead of\n// forkBranch when the executor's reasoning channel differs: createBranchedSession\n// copies raw lines and cannot rewrite foreign thinking signatures.\nconst persistedBranch = async (\n seed: AgentSessionSeed,\n cwd: string,\n directory: string,\n): Promise<SessionEntry[]> => {\n if (!seed.sourceSessionFile) {\n throw new Error(\"Persisted trajectory handoff is missing its source session file\");\n }\n const source = await SessionManager.open(seed.sourceSessionFile, directory, undefined, { initialCwd: cwd });\n if (!source.getEntry(seed.sourceBranchLeafId)) {\n throw new Error(\n `Trajectory handoff branch point ${seed.sourceBranchLeafId} is missing from the persisted OMP session`,\n );\n }\n return structuredClone(source.getBranch(seed.sourceBranchLeafId));\n};\n\nconst synchronizeSourceSettings = (\n session: SessionManager,\n seed: AgentSessionSeed,\n): void => {\n const context = session.buildSessionContext();\n const currentModel = context.models.default;\n const sourceModel = seed.sourceModel\n ? `${seed.sourceModel.provider}/${seed.sourceModel.modelId}`\n : undefined;\n if (sourceModel && currentModel !== sourceModel) session.appendModelChange(sourceModel);\n if (seed.sourceThinkingLevel && context.thinkingLevel !== seed.sourceThinkingLevel) {\n session.appendThinkingLevelChange(seed.sourceThinkingLevel);\n }\n};\n\nexport const writeHandoffSession = async (\n seed: AgentSessionSeed,\n cwd: string,\n directory: string,\n transfer?: ThinkingTransferInput,\n compaction?: HandoffCompactionRequest,\n): Promise<string> => {\n fs.mkdirSync(directory, { recursive: true, mode: 0o700 });\n const policy = transfer ? thinkingTransferPolicy(transfer) : \"preserved\";\n let session: SessionManager;\n let report: ThinkingTransferReport | undefined;\n let digest: { content: string; citedBlocks: number } | undefined;\n if (!transfer || policy === \"preserved\") {\n session = seed.sourceBranchRetired && seed.sourceBranch\n ? await materializeBranch(seed, cwd, directory)\n : await forkBranch(seed, cwd, directory);\n } else {\n const rawBranch = seed.sourceBranchRetired && seed.sourceBranch\n ? structuredClone(seed.sourceBranch)\n : seed.sourceSessionFile\n ? await persistedBranch(seed, cwd, directory)\n : structuredClone(seed.sourceBranch ?? (() => {\n throw new Error(\"Trajectory handoff transfer is missing its source branch\");\n })());\n if (policy === \"stripped\") digest = buildThinkingDigest(rawBranch, transfer);\n const translated = translateThinkingForExecutor(rawBranch, policy);\n report = translated.report;\n session = await materializeBranch({ ...seed, sourceBranch: translated.entries }, cwd, directory);\n }\n // Append the compaction entry before settings sync and the outer tool result\n // so the executor's context opens with the deterministic summary, followed\n // by the kept tail, then the boundary artifacts appended afterwards. The\n // file retains the full raw branch, mirroring OMP's append-only compaction.\n let compactionOutcome: HandoffCompactionOutcome | undefined;\n if (compaction) {\n const branchEntries = session.getBranch();\n const customInstructions = compaction.preserve\n ? encodeCompactionRequest({\n ...(compaction.instructions !== undefined\n ? { instructions: compaction.instructions }\n : {}),\n preserve: compaction.preserve,\n })\n : compaction.instructions;\n const tokensBefore = rawContextTokens(branchEntries);\n const compiled = compileFabricSummary(branchEntries, tokensBefore, undefined, customInstructions);\n if (\"cancel\" in compiled) {\n compactionOutcome = { applied: false, reason: compiled.reason };\n } else {\n session.appendCompaction(\n compiled.compaction.summary,\n undefined,\n compiled.compaction.firstKeptEntryId,\n tokensBefore,\n compiled.compaction.details\n ? { details: compiled.compaction.details, fromExtension: true }\n : { fromExtension: true },\n );\n compactionOutcome = {\n applied: true,\n sections: compiled.compaction.details?.sections ?? [],\n tokensBefore,\n firstKeptEntryId: compiled.compaction.firstKeptEntryId,\n };\n }\n }\n synchronizeSourceSettings(session, seed);\n session.appendMessage(seed.outerToolResult);\n if (digest) {\n session.appendCustomMessageEntry(THINKING_DIGEST_CUSTOM_TYPE, digest.content, false, {\n policy,\n citedBlocks: digest.citedBlocks,\n });\n }\n session.appendCustomEntry(\"omp-fabric-handoff\", {\n sourceSessionId: seed.sourceSessionId,\n boundary: \"fabric_exec_end\",\n ...(compactionOutcome\n ? {\n compaction: compactionOutcome.applied\n ? {\n applied: true,\n sections: compactionOutcome.sections,\n tokensBefore: compactionOutcome.tokensBefore,\n firstKeptEntryId: compactionOutcome.firstKeptEntryId,\n }\n : { applied: false, reason: compactionOutcome.reason },\n }\n : {}),\n ...(transfer && report\n ? {\n thinkingTransfer: {\n policy: report.policy,\n translated: report.translated,\n dropped: report.dropped,\n target: `${transfer.target.provider}/${transfer.target.modelId}`,\n },\n }\n : {}),\n });\n const sessionFile = session.getSessionFile();\n if (!sessionFile) throw new Error(\"Trajectory handoff did not produce an OMP session file\");\n fs.chmodSync(sessionFile, 0o600);\n return sessionFile;\n};\n", "import type { FabricPeerInfo } from \"./types.js\";\n\n/** Quiet window after a peer's last observed activity before it counts as settled. */\nconst DEFAULT_PEER_SETTLED_FOR_MS = 3_000;\nconst PEER_SETTLE_POLL_MS = 500;\n\n/**\n * Derive a Linear-style label prefix from a project path's basename:\n * \"pi-queue-steer\" -> \"PQS\", \"fabric\" -> \"FAB\". Falls back to \"P\".\n */\nexport const peerLabelPrefix = (cwd: string | undefined): string => {\n\tconst base = cwd?.split(/[\\\\/]/).filter(Boolean).at(-1) ?? \"\";\n\tconst words = base.split(/[^A-Za-z0-9]+/).filter(Boolean);\n\tif (words.length === 0) return \"P\";\n\t// Single-word projects borrow the first letters (\"fabric\" -> \"FAB\"),\n\t// multi-word projects take word initials (\"pi-queue-steer\" -> \"PQS\").\n\tif (words.length === 1) return words[0]!.slice(0, 3).toUpperCase();\n\treturn words\n\t\t.slice(0, 4)\n\t\t.map((word) => word[0]!.toUpperCase())\n\t\t.join(\"\");\n};\n\n/** Snapshot of one root peer session for pickers and status lines. */\nexport interface FabricPeerCard {\n\tid: string;\n\tlabel: string;\n\tstatus: \"idle\" | \"running\";\n\tmodel?: string;\n\tcwd?: string;\n\tstartedAt: number;\n\tupdatedAt: number;\n\tpendingMessages: boolean;\n}\n\n/** Labels are chronological, so creation order is simply label minting order. */\nexport const buildPeerCards = (peers: readonly FabricPeerInfo[]): FabricPeerCard[] =>\n\t[...peers]\n\t\t.sort((left, right) => left.startedAt - right.startedAt || left.id.localeCompare(right.id))\n\t\t.map((peer) => ({\n\t\t\tid: peer.id,\n\t\t\tlabel: peer.label ?? peer.name,\n\t\t\tstatus: peer.status,\n\t\t\t...(peer.model ? { model: peer.model } : {}),\n\t\t\t...(peer.cwd ? { cwd: peer.cwd } : {}),\n\t\t\tstartedAt: peer.startedAt,\n\t\t\tupdatedAt: peer.updatedAt,\n\t\t\tpendingMessages: peer.pendingMessages,\n\t\t}));\n\ninterface PeerSettleProgress {\n\twaiting: Array<{ label: string; status: \"idle\" | \"running\" }>;\n}\n\nexport type PeerSettleResult = { ok: true } | { ok: false; error: string };\n\nexport interface AwaitPeerSettleOptions {\n\t/** Fresh peer snapshot source (typically FabricRuntimeState.peerInfos()). */\n\tpoll: () => FabricPeerInfo[];\n\t/** Peer label (case-insensitive) or exact participant id. Omitted means all peers. */\n\tselector?: string;\n\tsettledForMs?: number;\n\tpollMs?: number;\n\tnow?: () => number;\n\tsignal?: AbortSignal;\n\tonUpdate?: (progress: PeerSettleProgress) => void;\n}\n\nconst matchesSelector = (peer: FabricPeerInfo, selector: string): boolean => {\n\tconst target = selector.trim().toLowerCase();\n\tif (!target) return false;\n\treturn (\n\t\tpeer.id.toLowerCase() === target ||\n\t\t(peer.label ?? \"\").toLowerCase() === target ||\n\t\tpeer.name.toLowerCase() === target\n\t);\n};\n\ninterface WatchedPeer {\n\tid: string;\n\tlabel: string;\n\trunning: boolean;\n\t/** Last time the peer was observed running; undefined when quiet since arming. */\n\tlastRunningAt: number | undefined;\n\tsettled: boolean;\n}\n\n/**\n * Wait until every watched peer has settled: only runs that started after\n * arming delay it (an idle-at-arm peer satisfies once the quiet window\n * passes), and a peer vanishing from the mesh counts as settled since it can\n * no longer conflict.\n */\nexport const awaitPeerSettle = (options: AwaitPeerSettleOptions): Promise<PeerSettleResult> => {\n\tconst now = options.now ?? (() => Date.now());\n\tconst settledFor = Math.max(0, options.settledForMs ?? DEFAULT_PEER_SETTLED_FOR_MS);\n\tconst pollMs = Math.max(10, options.pollMs ?? PEER_SETTLE_POLL_MS);\n\tconst armedAt = now();\n\tconst initial = options.poll();\n\tconst targets =\n\t\toptions.selector !== undefined\n\t\t\t? initial.filter((peer) => matchesSelector(peer, options.selector ?? \"\"))\n\t\t\t: [...initial];\n\tif (options.selector !== undefined && targets.length === 0) {\n\t\treturn Promise.resolve({\n\t\t\tok: false,\n\t\t\terror: `No Fabric peer matches \"${options.selector}\" on this project mesh`,\n\t\t});\n\t}\n\tif (targets.length === 0) return Promise.resolve({ ok: true });\n\n\tconst watched = new Map<string, WatchedPeer>();\n\tfor (const peer of targets) {\n\t\twatched.set(peer.id, {\n\t\t\tid: peer.id,\n\t\t\tlabel: peer.label ?? peer.name,\n\t\t\trunning: peer.status === \"running\",\n\t\t\tlastRunningAt: peer.status === \"running\" ? armedAt : undefined,\n\t\t\tsettled: false,\n\t\t});\n\t}\n\n\treturn new Promise<PeerSettleResult>((resolve) => {\n\t\tlet timer: ReturnType<typeof setInterval> | undefined;\n\t\tlet done = false;\n\t\tconst finish = (result: PeerSettleResult): void => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tif (timer) clearInterval(timer);\n\t\t\toptions.signal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve(result);\n\t\t};\n\t\tconst onAbort = (): void => finish({ ok: false, error: \"cancelled\" });\n\t\tconst tick = (): void => {\n\t\t\tconst snapshot = options.poll();\n\t\t\tconst byId = new Map(snapshot.map((peer) => [peer.id, peer] as const));\n\t\t\tconst current = now();\n\t\t\tfor (const entry of watched.values()) {\n\t\t\t\tif (entry.settled) continue;\n\t\t\t\tconst peer = byId.get(entry.id);\n\t\t\t\tif (!peer) {\n\t\t\t\t\tentry.settled = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tentry.label = peer.label ?? peer.name;\n\t\t\t\tconst running = peer.status === \"running\";\n\t\t\t\tif (running) {\n\t\t\t\t\tentry.lastRunningAt = current;\n\t\t\t\t\tentry.running = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tentry.running = false;\n\t\t\t\tconst quietSince = entry.lastRunningAt ?? armedAt;\n\t\t\t\tif (current - quietSince >= settledFor) entry.settled = true;\n\t\t\t}\n\t\t\tconst waiting = [...watched.values()]\n\t\t\t\t.filter((entry) => !entry.settled)\n\t\t\t\t.map((entry) => ({ label: entry.label, status: entry.running ? \"running\" : \"idle\" }) as const);\n\t\t\tif (waiting.length === 0) {\n\t\t\t\toptions.onUpdate?.({ waiting });\n\t\t\t\tfinish({ ok: true });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\toptions.onUpdate?.({ waiting });\n\t\t};\n\t\tif (options.signal) {\n\t\t\tif (options.signal.aborted) {\n\t\t\t\tfinish({ ok: false, error: \"cancelled\" });\n\t\t\t\treturn;\n\t\t\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