omp-fabric 1.2.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/dist/actors/global-registry.d.ts.map +1 -1
  3. package/dist/actors/manager.d.ts.map +1 -1
  4. package/dist/actors/types.d.ts +1 -0
  5. package/dist/actors/types.d.ts.map +1 -1
  6. package/dist/agents/manager.d.ts.map +1 -1
  7. package/dist/agents/types.d.ts +1 -0
  8. package/dist/agents/types.d.ts.map +1 -1
  9. package/dist/chunks/{chunk-3TWC6XOS.js → chunk-2WDZT27Q.js} +36 -13
  10. package/dist/chunks/chunk-2WDZT27Q.js.map +7 -0
  11. package/dist/chunks/{chunk-UOSJZXJV.js → chunk-3LI7YO4M.js} +1 -1
  12. package/dist/chunks/chunk-3LI7YO4M.js.map +7 -0
  13. package/dist/chunks/{chunk-TQL7FKMG.js → chunk-45URY66G.js} +15 -15
  14. package/dist/chunks/chunk-45URY66G.js.map +7 -0
  15. package/dist/chunks/{chunk-B2SQR2JY.js → chunk-BMIE4PIL.js} +2 -2
  16. package/dist/chunks/{chunk-NX4SNIMR.js → chunk-FX3XLQYI.js} +36 -7
  17. package/dist/chunks/chunk-FX3XLQYI.js.map +7 -0
  18. package/dist/chunks/{chunk-EQNNENN6.js → chunk-PYXBHMSL.js} +3 -3
  19. package/dist/chunks/{chunk-2GQC324T.js → chunk-TSU4AEPZ.js} +2 -2
  20. package/dist/chunks/{chunk-5YGOVBOZ.js → chunk-VSSC4IDU.js} +2 -2
  21. package/dist/chunks/{chunk-HDJBUXDX.js → chunk-WQUMHDOS.js} +2 -2
  22. package/dist/chunks/{chunk-XRJYPNTI.js → chunk-WZAH7BO2.js} +8 -1
  23. package/dist/chunks/chunk-WZAH7BO2.js.map +7 -0
  24. package/dist/chunks/{chunk-WGFHMECI.js → chunk-Z5AP4M6K.js} +24 -6
  25. package/dist/chunks/chunk-Z5AP4M6K.js.map +7 -0
  26. package/dist/codemap/symbols.d.ts.map +1 -1
  27. package/dist/codemap/types.d.ts +1 -0
  28. package/dist/codemap/types.d.ts.map +1 -1
  29. package/dist/config.d.ts +1 -0
  30. package/dist/config.d.ts.map +1 -1
  31. package/dist/entropy/index.js +2 -2
  32. package/dist/fabric-runtime-state.js +320 -123
  33. package/dist/fabric-runtime-state.js.map +3 -3
  34. package/dist/index.js +8 -8
  35. package/dist/memory/discovery.d.ts +10 -0
  36. package/dist/memory/discovery.d.ts.map +1 -1
  37. package/dist/memory/discovery.js +3 -1
  38. package/dist/providers/agents-actions.d.ts.map +1 -1
  39. package/dist/providers/agents-provider.d.ts.map +1 -1
  40. package/dist/providers/codemap-provider.d.ts.map +1 -1
  41. package/dist/providers/mcp-provider.d.ts.map +1 -1
  42. package/dist/providers/memory-provider.d.ts.map +1 -1
  43. package/dist/providers/memory-provider.js +2 -2
  44. package/dist/providers/mesh-provider.d.ts.map +1 -1
  45. package/dist/providers/omp-tools-provider.d.ts.map +1 -1
  46. package/dist/providers/write-preview.d.ts.map +1 -1
  47. package/dist/residency/host.js +4 -4
  48. package/dist/residency/omp-entry.js +4 -4
  49. package/dist/runtime/core-override-guest-types.js +1 -1
  50. package/dist/runtime/guest-types.d.ts +1 -1
  51. package/dist/runtime/guest-types.d.ts.map +1 -1
  52. package/dist/runtime/guest-types.js +1 -1
  53. package/dist/ui/dashboard.js +3 -3
  54. package/dist/ui/settings.d.ts.map +1 -1
  55. package/dist/ui/settings.js +10 -2
  56. package/dist/ui/settings.js.map +2 -2
  57. package/docs/codemap.md +9 -0
  58. package/docs/configuration.md +1 -1
  59. package/package.json +1 -1
  60. package/dist/chunks/chunk-3TWC6XOS.js.map +0 -7
  61. package/dist/chunks/chunk-NX4SNIMR.js.map +0 -7
  62. package/dist/chunks/chunk-TQL7FKMG.js.map +0 -7
  63. package/dist/chunks/chunk-UOSJZXJV.js.map +0 -7
  64. package/dist/chunks/chunk-WGFHMECI.js.map +0 -7
  65. package/dist/chunks/chunk-XRJYPNTI.js.map +0 -7
  66. /package/dist/chunks/{chunk-B2SQR2JY.js.map → chunk-BMIE4PIL.js.map} +0 -0
  67. /package/dist/chunks/{chunk-EQNNENN6.js.map → chunk-PYXBHMSL.js.map} +0 -0
  68. /package/dist/chunks/{chunk-2GQC324T.js.map → chunk-TSU4AEPZ.js.map} +0 -0
  69. /package/dist/chunks/{chunk-5YGOVBOZ.js.map → chunk-VSSC4IDU.js.map} +0 -0
  70. /package/dist/chunks/{chunk-HDJBUXDX.js.map → chunk-WQUMHDOS.js.map} +0 -0
@@ -0,0 +1,7 @@
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;AAC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alState", "finalLineage", "anchorIndex", "cursor"]
7
+ }
@@ -139,4 +139,4 @@ export {
139
139
  readJsonlPageFromDescriptor,
140
140
  readJsonlPage
141
141
  };
142
- //# sourceMappingURL=chunk-UOSJZXJV.js.map
142
+ //# sourceMappingURL=chunk-3LI7YO4M.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/actors/types.ts", "../../src/log-tail.ts"],
4
+ "sourcesContent": ["import type { ExtensionEvent } from \"@oh-my-pi/pi-coding-agent\";\nimport type { FabricAgentRunner, FabricAgentTransport } from \"../config.js\";\nimport type { FabricThinking } from \"../thinking.js\";\nimport type { FabricLogLine, AgentRunRecord, AgentUsage } from \"../agents/types.js\";\nimport type { FabricCapabilityRequirement } from \"../components/types.js\";\nimport type { FabricParticipantResidency } from \"../topology/types.js\";\n\nexport type FabricActorOmpHostEvent = Exclude<ExtensionEvent[\"type\"], \"project_trust\">;\n\nconst defineFabricActorOmpHostEvents = <const Events extends readonly FabricActorOmpHostEvent[]>(\n events: Events,\n): Events => events;\n\nexport const FABRIC_ACTOR_OMP_HOST_EVENTS = defineFabricActorOmpHostEvents([\n \"resources_discover\",\n \"session_start\",\n \"session_before_switch\",\n \"session_switch\",\n \"session_before_branch\",\n \"session_branch\",\n \"session_before_compact\",\n \"session.compacting\",\n \"session_compact\",\n \"session_shutdown\",\n \"session_before_tree\",\n \"session_tree\",\n \"goal_updated\",\n \"input\",\n \"before_agent_start\",\n \"agent_start\",\n \"agent_end\",\n \"session_stop\",\n \"turn_start\",\n \"turn_end\",\n \"message_start\",\n \"message_update\",\n \"message_end\",\n \"context\",\n \"before_provider_request\",\n \"after_provider_response\",\n \"tool_execution_start\",\n \"tool_call\",\n \"tool_execution_update\",\n \"tool_result\",\n \"tool_execution_end\",\n \"user_bash\",\n]);\nexport const FABRIC_ACTOR_HOST_EVENTS = [\n ...FABRIC_ACTOR_OMP_HOST_EVENTS,\n \"tool_error\",\n] as const;\n\nexport type FabricActorHostEvent = (typeof FABRIC_ACTOR_HOST_EVENTS)[number];\n\nconst FABRIC_ACTOR_HOST_EVENT_SET: ReadonlySet<string> = new Set(FABRIC_ACTOR_HOST_EVENTS);\n\nexport const isFabricActorHostEvent = (value: unknown): value is FabricActorHostEvent =>\n typeof value === \"string\" && FABRIC_ACTOR_HOST_EVENT_SET.has(value);\n\nexport type FabricActorDelivery = \"mailbox\" | \"steer\" | \"followUp\" | \"nextTurn\";\nexport type FabricActorResponseMode = \"text\" | \"directive\";\nexport type FabricActorStatus = \"idle\" | \"queued\" | \"running\" | \"stopped\";\nexport type FabricActorBindingScope = \"session\" | \"project\";\nexport type FabricActorStorageScope = \"session\" | \"project\";\n\nexport interface FabricActorRunBinding {\n model?: string;\n thinking?: FabricThinking;\n}\n\ninterface FabricActorBindingView extends FabricActorRunBinding {\n scope: \"session\";\n sessionId: string;\n updatedAt?: number;\n}\n\ninterface FabricActorProjectDefaults extends FabricActorRunBinding {\n scope: \"project\";\n}\n\nexport interface FabricActorValidWhileSource {\n version: 1;\n source: string;\n}\n\nexport interface FabricActorValidityDecision {\n valid: boolean;\n reason?: string;\n}\n\nexport type FabricActorActivation =\n | {\n kind: \"hostEvent\";\n id: string;\n source: string;\n sequence: number;\n createdAt: number;\n event: FabricActorHostEvent;\n mainRevision: number;\n taskRevision: number;\n signal?: unknown;\n }\n | {\n kind: \"direct\";\n id: string;\n source: string;\n sequence: number;\n createdAt: number;\n }\n | {\n kind: \"mesh\";\n id: string;\n source: string;\n sequence: number;\n createdAt: number;\n topic: string;\n };\n\nexport interface FabricActorValidityFacts {\n activation: FabricActorActivation;\n current: {\n latestActivationSequence: number;\n mainRevision: number;\n taskRevision: number;\n idle: boolean;\n now: number;\n };\n}\n\nexport interface FabricActorRequest {\n /** Storage and visibility boundary. Defaults to mesh.actorScope for compatibility. */\n scope?: FabricActorStorageScope;\n name: string;\n instructions: string;\n /** Asynchronous observations of session-bound OMP events plus synthetic tool_error. */\n events?: FabricActorHostEvent[];\n topics?: string[];\n /** Defaults to mailbox. steer/followUp require an explicit triggerTurn choice. */\n delivery?: FabricActorDelivery;\n responseMode?: FabricActorResponseMode;\n /** Required for steer/followUp; must be false or omitted for mailbox/nextTurn. */\n triggerTurn?: boolean;\n coalesce?: boolean;\n /** session actors stop with their OMP host; durable actors transfer to a resident host. */\n residency?: FabricParticipantResidency;\n runner?: FabricAgentRunner;\n model?: string;\n thinking?: FabricThinking;\n tools?: string[];\n transport?: FabricAgentTransport;\n cwd?: string;\n timeoutMs?: number;\n /**\n * Fabric capability for the actor. Defaults to true (today's behavior: an OMP\n * actor is recursively Fabric-equipped with the host-required fabric_exec\n * tool). Set false to disable Fabric for an OMP actor: the activation runs with\n * extensions:false and recursive:false so fabric_exec is not injected and the\n * actor cannot call agents.* or mesh.*; the host still manages its mailbox\n * and delivery (same model as a Claude actor). This does not restrict the\n * actor's ordinary tool allowlist. Fixed at creation.\n */\n extensions?: boolean;\n /** Exact Fabric actions committed before every actor run. Optional entries do not block a run. */\n requires?: readonly (string | FabricCapabilityRequirement)[];\n /** Serialized guest predicate evaluated before work and before delivery. */\n validWhile?: FabricActorValidWhileSource;\n}\n\nexport interface FabricActorInfo {\n id: string;\n scope: FabricActorStorageScope;\n name: string;\n rootId?: string;\n status: FabricActorStatus;\n runner: FabricAgentRunner;\n events: FabricActorHostEvent[];\n topics: string[];\n delivery: FabricActorDelivery;\n responseMode: FabricActorResponseMode;\n triggerTurn: boolean;\n coalesce: boolean;\n residency?: FabricParticipantResidency;\n /** Effective value for this caller after session bindings overlay project defaults. */\n model?: string;\n /** Effective value for this caller after session bindings overlay project defaults. */\n thinking?: FabricThinking;\n binding?: FabricActorBindingView;\n projectDefaults?: FabricActorProjectDefaults;\n tools?: string[];\n timeoutMs?: number;\n extensions?: boolean;\n requirements?: FabricCapabilityRequirement[];\n capabilityDigest?: string;\n missingCapabilities?: string[];\n validWhile?: FabricActorValidWhileSource;\n queued: number;\n messages: number;\n createdAt: number;\n updatedAt: number;\n lastRunId?: string;\n lastError?: string;\n sessionFile?: string;\n logDir?: string;\n}\n\nexport interface FabricActorLog {\n actorId: string;\n actorName: string;\n sessionFile: string;\n logDir: string;\n session: FabricLogLine[];\n sessionHasMore: boolean;\n sessionBefore?: number;\n run?: {\n runId: string;\n eventsFile: string;\n status?: AgentRunRecord;\n events: FabricLogLine[];\n hasMore: boolean;\n before?: number;\n };\n retainedRuns: string[];\n}\n\nexport interface FabricActorMessage {\n id: string;\n actorId: string;\n actorName: string;\n direction: \"in\" | \"out\";\n source: string;\n createdAt: number;\n text?: string;\n data?: unknown;\n action?: \"silent\" | \"message\" | \"stop\";\n runId?: string;\n usage?: AgentUsage;\n error?: string;\n stale?: boolean;\n reason?: string;\n}\n\nexport interface FabricActorDirective {\n action: \"silent\" | \"message\" | \"stop\";\n message?: string;\n data?: unknown;\n}\n\nexport interface FabricActorDeliveryRequest {\n actor: FabricActorInfo;\n message: FabricActorMessage;\n delivery: Exclude<FabricActorDelivery, \"mailbox\">;\n triggerTurn: boolean;\n}\n\n/**\n * A project-independent actor template stored in the global registry\n * (the user's agent dir, not a project mesh). It carries only the actor\n * definition (the same fields as FabricActorRequest) plus identity and\n * timestamps \u2014 never any history (messages, session transcript, or run logs).\n * Global actors are not live: they are stamped into a project via import,\n * which creates a fresh live actor with no inherited history.\n */\nexport interface GlobalActorDefinition extends FabricActorRequest {\n id: string;\n createdAt: number;\n updatedAt: number;\n // Redeclared required: the registry always materializes these (defaults\n // applied on create and load), so they are never undefined on a stored\n // template. Keeping them required avoids undefined creeping into merges and\n // spreads under exactOptionalPropertyTypes.\n events: FabricActorHostEvent[];\n topics: string[];\n delivery: FabricActorDelivery;\n responseMode: FabricActorResponseMode;\n triggerTurn: boolean;\n coalesce: boolean;\n residency?: FabricParticipantResidency;\n runner: FabricAgentRunner;\n}\n", "import fs from \"node:fs\";\nimport type { FabricLogLine } from \"./agents/types.js\";\n\nconst READ_CHUNK_BYTES = 64 * 1024;\nconst DEFAULT_READ_MAX_BYTES = 8 * 1024 * 1024;\n\nexport interface JsonlPage {\n lines: FabricLogLine[];\n hasMore: boolean;\n before?: number;\n}\n\nconst parseLine = (offset: number, raw: string): FabricLogLine => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return { offset, raw };\n }\n return { offset, raw, parsed };\n};\n\ninterface BufferedLine {\n offset: number;\n raw: string;\n}\n\nconst completeLines = (buffer: Buffer, bufferStart: number, fileEnd: number): BufferedLine[] => {\n const lines: BufferedLine[] = [];\n let start = 0;\n let first = true;\n for (let index = 0; index < buffer.length; index++) {\n if (buffer[index] !== 10) continue;\n if (!first || bufferStart === 0) {\n const raw = buffer.subarray(start, index).toString(\"utf8\").replace(/\\r$/, \"\");\n if (raw) lines.push({ offset: bufferStart + start, raw });\n }\n first = false;\n start = index + 1;\n }\n if (fileEnd === bufferStart + buffer.length && start < buffer.length) {\n if (!first || bufferStart === 0) {\n const raw = buffer.subarray(start).toString(\"utf8\").replace(/\\r$/, \"\");\n if (raw) lines.push({ offset: bufferStart + start, raw });\n }\n }\n return lines;\n};\n\n/** Read a bounded JSONL page backwards from an already validated descriptor. */\nexport const readJsonlPageFromDescriptor = (\n descriptor: number,\n limit: number,\n before?: number,\n knownSize?: number,\n maxBytes?: number,\n): JsonlPage => {\n try {\n const size = knownSize ?? fs.fstatSync(descriptor).size;\n const fileEnd = typeof before === \"number\" && Number.isSafeInteger(before)\n ? Math.max(0, Math.min(before, size))\n : size;\n const boundedLimit = Math.max(1, Math.trunc(limit));\n const boundedBytes = Math.max(\n 1,\n Math.trunc(maxBytes ?? DEFAULT_READ_MAX_BYTES),\n );\n const chunks: Buffer[] = [];\n let bufferStart = fileEnd;\n let bufferedBytes = 0;\n let newlineCount = 0;\n\n while (\n bufferStart > 0 &&\n newlineCount <= boundedLimit &&\n bufferedBytes < boundedBytes\n ) {\n const length = Math.min(READ_CHUNK_BYTES, bufferStart, boundedBytes - bufferedBytes);\n const chunkStart = bufferStart - length;\n const chunk = Buffer.allocUnsafe(length);\n const bytesRead = fs.readSync(descriptor, chunk, 0, length, chunkStart);\n if (bytesRead <= 0) break;\n const captured = chunk.subarray(0, bytesRead);\n chunks.push(captured);\n for (const byte of captured) {\n if (byte === 0x0a) newlineCount += 1;\n }\n bufferedBytes += bytesRead;\n bufferStart = chunkStart;\n }\n\n const buffer = Buffer.concat(chunks.reverse(), bufferedBytes);\n const records = completeLines(buffer, bufferStart, fileEnd);\n\n const selected = records.slice(-boundedLimit);\n const hasMore = selected.length > 0 && (records.length > selected.length || bufferStart > 0);\n return {\n lines: selected.map((line) => parseLine(line.offset, line.raw)),\n hasMore,\n ...(hasMore ? { before: selected[0]!.offset } : {}),\n };\n } catch {\n return { lines: [], hasMore: false };\n }\n};\n\n/** Read a bounded JSONL page backwards, touching only enough file chunks to fill it. */\nexport const readJsonlPage = (\n filePath: string,\n limit: number,\n before?: number,\n maxBytes?: number,\n): JsonlPage => {\n let descriptor: number | undefined;\n try {\n descriptor = fs.openSync(filePath, \"r\");\n return readJsonlPageFromDescriptor(descriptor, limit, before, undefined, maxBytes);\n } catch {\n return { lines: [], hasMore: false };\n } finally {\n if (descriptor !== undefined) {\n try { fs.closeSync(descriptor); } catch {}\n }\n }\n};\n"],
5
+ "mappings": ";AASA,IAAM,iCAAiC,CACrC,WACW;AAEN,IAAM,+BAA+B,+BAA+B;AAAA,EACzE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACM,IAAM,2BAA2B;AAAA,EACtC,GAAG;AAAA,EACH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,CAAC,GAAG,SAAS,MAAM;AAAA,EACrC;AACF;AAGO,IAAM,gBAAgB,CAC3B,UACA,OACA,QACA,aACc;AACd,MAAI;AACJ,MAAI;AACF,iBAAa,GAAG,SAAS,UAAU,GAAG;AACtC,WAAO,4BAA4B,YAAY,OAAO,QAAQ,QAAW,QAAQ;AAAA,EACnF,QAAQ;AACN,WAAO,EAAE,OAAO,CAAC,GAAG,SAAS,MAAM;AAAA,EACrC,UAAE;AACA,QAAI,eAAe,QAAW;AAC5B,UAAI;AAAE,WAAG,UAAU,UAAU;AAAA,MAAG,QAAQ;AAAA,MAAC;AAAA,IAC3C;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -27,11 +27,11 @@ import {
27
27
  MAX_AGENT_TIMEOUT_MS,
28
28
  MIN_AGENT_TIMEOUT_MS,
29
29
  resolveAgentDir
30
- } from "./chunk-XRJYPNTI.js";
30
+ } from "./chunk-WZAH7BO2.js";
31
31
  import {
32
32
  FABRIC_ACTOR_HOST_EVENTS,
33
33
  readJsonlPage
34
- } from "./chunk-UOSJZXJV.js";
34
+ } from "./chunk-3LI7YO4M.js";
35
35
  import {
36
36
  isFabricThinking
37
37
  } from "./chunk-JSBTB3P6.js";
@@ -1684,16 +1684,10 @@ var MAX_LOG_SUMMARY_CHARS = 7e3;
1684
1684
  var MAX_LOG_DETAIL_CHARS = 900;
1685
1685
  var RETENTION_SWEEP_INTERVAL_MS = 15 * 60 * 1e3;
1686
1686
  var effectiveAgentTimeoutMs = (configuredTimeoutMs, requestedTimeoutMs) => {
1687
- const configured = Math.max(
1688
- MIN_AGENT_TIMEOUT_MS,
1689
- Math.min(Math.floor(configuredTimeoutMs), MAX_AGENT_TIMEOUT_MS)
1690
- );
1691
- if (requestedTimeoutMs === void 0 || !Number.isFinite(requestedTimeoutMs)) {
1692
- return configured;
1693
- }
1687
+ const selected = requestedTimeoutMs === void 0 || !Number.isFinite(requestedTimeoutMs) ? configuredTimeoutMs : requestedTimeoutMs;
1694
1688
  return Math.max(
1695
- configured,
1696
- Math.min(Math.floor(requestedTimeoutMs), MAX_AGENT_TIMEOUT_MS)
1689
+ MIN_AGENT_TIMEOUT_MS,
1690
+ Math.min(Math.floor(selected), MAX_AGENT_TIMEOUT_MS)
1697
1691
  );
1698
1692
  };
1699
1693
  var validateAgentCwdRequest = (request) => {
@@ -2723,9 +2717,10 @@ var AgentManager = class {
2723
2717
  }
2724
2718
  }
2725
2719
  #childTools(request, runner) {
2726
- const tools = [...request.tools ?? this.config.defaultTools].filter(
2727
- (tool) => tool !== "fabric_exec"
2728
- );
2720
+ const tools = [
2721
+ ...request.tools ?? this.config.defaultTools,
2722
+ ...request.addTools ?? []
2723
+ ].filter((tool) => tool !== "fabric_exec");
2729
2724
  const extensions = request.recursive === true ? true : request.extensions ?? this.config.extensions;
2730
2725
  if (runner === "omp" && (request.recursive || this.#fullCodeMode && extensions)) {
2731
2726
  tools.push("fabric_exec");
@@ -3453,6 +3448,7 @@ var ActorManager = class {
3453
3448
  ...request.thinking ? { thinking: request.thinking } : {},
3454
3449
  ...request.tools ? { tools: [...new Set(request.tools)] } : {},
3455
3450
  ...request.transport ? { transport: request.transport } : {},
3451
+ ...request.cwd ? { cwd: request.cwd } : {},
3456
3452
  ...request.timeoutMs ? { timeoutMs: request.timeoutMs } : {},
3457
3453
  ...typeof request.extensions === "boolean" ? { extensions: request.extensions } : {},
3458
3454
  requirements,
@@ -3779,6 +3775,7 @@ var ActorManager = class {
3779
3775
  ...actor.thinking ? { thinking: actor.thinking } : {},
3780
3776
  ...actor.tools ? { tools: [...actor.tools] } : {},
3781
3777
  ...actor.transport ? { transport: actor.transport } : {},
3778
+ ...actor.cwd ? { cwd: actor.cwd } : {},
3782
3779
  ...actor.timeoutMs ? { timeoutMs: actor.timeoutMs } : {},
3783
3780
  ...typeof actor.extensions === "boolean" ? { extensions: actor.extensions } : {},
3784
3781
  ...actor.requirements.length > 0 ? { requires: actor.requirements.map((requirement) => ({ ...requirement })) } : {},
@@ -4334,6 +4331,7 @@ var ActorManager = class {
4334
4331
  ...item.binding.thinking ? { thinking: item.binding.thinking } : {},
4335
4332
  ...actor.tools ? { tools: actor.tools } : {},
4336
4333
  ...actor.transport ? { transport: actor.transport } : {},
4334
+ ...actor.cwd ? { cwd: actor.cwd } : {},
4337
4335
  ...actor.timeoutMs ? { timeoutMs: actor.timeoutMs } : {}
4338
4336
  };
4339
4337
  }
@@ -4701,6 +4699,7 @@ var ActorManager = class {
4701
4699
  ...actor.thinking ? { thinking: actor.thinking } : {},
4702
4700
  ...actor.tools ? { tools: actor.tools } : {},
4703
4701
  ...actor.transport ? { transport: actor.transport } : {},
4702
+ ...actor.cwd ? { cwd: actor.cwd } : {},
4704
4703
  ...actor.timeoutMs ? { timeoutMs: actor.timeoutMs } : {},
4705
4704
  ...typeof actor.extensions === "boolean" ? { extensions: actor.extensions } : {},
4706
4705
  requirements: actor.requirements,
@@ -4906,6 +4905,7 @@ ${Date.now()}
4906
4905
  ...isFabricThinking(record.thinking) ? { thinking: record.thinking } : {},
4907
4906
  ...Array.isArray(record.tools) ? { tools: record.tools.filter((tool) => typeof tool === "string") } : {},
4908
4907
  ...record.transport === "auto" || record.transport === "process" || record.transport === "tmux" || record.transport === "screen" || record.transport === "localterm" || record.transport === "herdr" ? { transport: record.transport } : {},
4908
+ ...typeof record.cwd === "string" ? { cwd: record.cwd } : {},
4909
4909
  ...typeof record.timeoutMs === "number" ? { timeoutMs: record.timeoutMs } : {},
4910
4910
  ...typeof record.extensions === "boolean" ? { extensions: record.extensions } : {},
4911
4911
  requirements,
@@ -6635,4 +6635,4 @@ export {
6635
6635
  agentParticipantRecords,
6636
6636
  actorParticipantRecord
6637
6637
  };
6638
- //# sourceMappingURL=chunk-TQL7FKMG.js.map
6638
+ //# sourceMappingURL=chunk-45URY66G.js.map