@gmickel/gno 2.15.0 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/cli-reference.md +4 -2
  3. package/assets/spa-production.json.gz +0 -0
  4. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.16.0.zip} +0 -0
  5. package/browser-extension/artifacts/gno-browser-clipper-v2.16.0.zip.sha256 +1 -0
  6. package/browser-extension/dist/manifest.json +1 -1
  7. package/package.json +1 -1
  8. package/spec/cli.md +1 -1
  9. package/src/cli/commands/agents/commands.ts +1 -1
  10. package/src/cli/commands/ask.ts +1 -1
  11. package/src/cli/commands/context-build.ts +1 -1
  12. package/src/cli/commands/embed.ts +2 -2
  13. package/src/cli/commands/links.ts +1 -1
  14. package/src/cli/commands/mcp/install.ts +2 -2
  15. package/src/cli/commands/mcp/status.ts +1 -1
  16. package/src/cli/commands/mcp/uninstall.ts +1 -1
  17. package/src/cli/commands/query.ts +1 -1
  18. package/src/cli/commands/shared.ts +4 -4
  19. package/src/cli/commands/skill/install.ts +1 -1
  20. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  21. package/src/cli/commands/skill/uninstall.ts +1 -1
  22. package/src/cli/commands/status.ts +75 -58
  23. package/src/cli/config-cache.ts +86 -0
  24. package/src/cli/globals.ts +64 -0
  25. package/src/cli/program.ts +20 -36
  26. package/src/cli/run.ts +121 -67
  27. package/src/cli/runtime-health.ts +132 -122
  28. package/src/cli/session-binding.ts +11 -2
  29. package/src/config/saver.ts +8 -0
  30. package/src/converters/adapters/browser-export/formats.ts +25 -15
  31. package/src/converters/adapters/email/adapter.ts +37 -53
  32. package/src/converters/adapters/email/html.ts +37 -20
  33. package/src/converters/adapters/email/mime.ts +71 -39
  34. package/src/converters/adapters/ical/adapter.ts +20 -12
  35. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  36. package/src/converters/adapters/shared/html-text.ts +55 -37
  37. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  38. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  39. package/src/converters/adapters/transcript/adapter.ts +12 -7
  40. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  41. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  42. package/src/converters/canonicalize.ts +17 -3
  43. package/src/converters/native/markdown.ts +24 -17
  44. package/src/converters/native/plaintext.ts +5 -6
  45. package/src/converters/registry.ts +130 -8
  46. package/src/core/activation-status.ts +4 -8
  47. package/src/core/change-diff.ts +38 -11
  48. package/src/core/context-compiler.ts +17 -18
  49. package/src/core/context-evidence.ts +116 -25
  50. package/src/core/context-verifier.ts +70 -31
  51. package/src/core/file-lock.ts +10 -2
  52. package/src/core/graph-analysis.ts +3 -3
  53. package/src/core/link-inventory-markdown.ts +2 -2
  54. package/src/core/links.ts +20 -87
  55. package/src/core/memory-fence.ts +16 -9
  56. package/src/core/memory-recall.ts +168 -34
  57. package/src/core/path-rules.ts +143 -0
  58. package/src/core/section-parse.ts +16 -6
  59. package/src/core/typed-metadata.ts +68 -0
  60. package/src/core/wiki-link-syntax.ts +88 -0
  61. package/src/embed/backlog.ts +142 -60
  62. package/src/embed/retry.ts +39 -33
  63. package/src/embed/variant-backlog.ts +546 -114
  64. package/src/embed/variant-retry.ts +157 -48
  65. package/src/index.ts +3 -3
  66. package/src/ingestion/budget-error-codes.ts +13 -0
  67. package/src/ingestion/chunker.ts +60 -49
  68. package/src/ingestion/compiled-context.ts +4 -5
  69. package/src/ingestion/convert-file.ts +1 -1
  70. package/src/ingestion/document-metadata.ts +16 -9
  71. package/src/ingestion/excluded-ranges.ts +97 -0
  72. package/src/ingestion/file-processor.ts +122 -37
  73. package/src/ingestion/frontmatter.ts +35 -7
  74. package/src/ingestion/graph-reconciliation.ts +187 -51
  75. package/src/ingestion/language.ts +66 -61
  76. package/src/ingestion/position.ts +5 -5
  77. package/src/ingestion/prepare-file.ts +50 -29
  78. package/src/ingestion/record-adapter-canonical.ts +37 -26
  79. package/src/ingestion/record-adapter.ts +46 -26
  80. package/src/ingestion/record-container.ts +121 -53
  81. package/src/ingestion/record-path.ts +5 -2
  82. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  83. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  84. package/src/ingestion/source-availability/readers.ts +51 -0
  85. package/src/ingestion/strip.ts +39 -105
  86. package/src/ingestion/sync.ts +692 -386
  87. package/src/ingestion/typed-metadata.ts +10 -4
  88. package/src/ingestion/walker.ts +485 -158
  89. package/src/llm/cache.ts +128 -84
  90. package/src/llm/http-inference.ts +112 -35
  91. package/src/llm/http-policy.ts +101 -0
  92. package/src/llm/httpEmbedding.ts +8 -1
  93. package/src/llm/httpGeneration.ts +5 -1
  94. package/src/llm/httpRerank.ts +5 -1
  95. package/src/llm/inference-scope.ts +15 -2
  96. package/src/llm/lazy-ports.ts +33 -3
  97. package/src/llm/lockfile.ts +34 -7
  98. package/src/llm/model-cleanup.ts +24 -0
  99. package/src/llm/native-worker/client.ts +23 -12
  100. package/src/llm/native-worker/dispatcher.ts +19 -9
  101. package/src/llm/native-worker/embedding-identity.ts +42 -16
  102. package/src/llm/native-worker/entry.ts +2 -1
  103. package/src/llm/native-worker/owner.ts +1 -0
  104. package/src/llm/native-worker/ports.ts +86 -23
  105. package/src/llm/native-worker/protocol.ts +386 -55
  106. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  107. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  108. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  109. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  110. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  111. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  112. package/src/llm/types.ts +14 -0
  113. package/src/mcp/context.ts +342 -23
  114. package/src/mcp/http-transport.ts +21 -3
  115. package/src/mcp/tool-profile-types.ts +62 -0
  116. package/src/mcp/tool-profile.ts +32 -56
  117. package/src/mcp/tools/context.ts +5 -1
  118. package/src/mcp/tools/index.ts +269 -191
  119. package/src/mcp/tools/links.ts +7 -5
  120. package/src/mcp/tools/query.ts +60 -37
  121. package/src/mcp/tools/vsearch.ts +25 -14
  122. package/src/pipeline/answer.ts +133 -40
  123. package/src/pipeline/claim-verification.ts +293 -189
  124. package/src/pipeline/claim-verifier.ts +6 -7
  125. package/src/pipeline/egress-lineage.ts +37 -26
  126. package/src/pipeline/exclude.ts +34 -11
  127. package/src/pipeline/expansion.ts +233 -19
  128. package/src/pipeline/filters.ts +169 -33
  129. package/src/pipeline/graph-retrieval.ts +117 -61
  130. package/src/pipeline/hybrid.ts +598 -329
  131. package/src/pipeline/hydration.ts +86 -24
  132. package/src/pipeline/intent.ts +15 -7
  133. package/src/pipeline/owner-fusion.ts +61 -19
  134. package/src/pipeline/query-language.ts +15 -2
  135. package/src/pipeline/rerank.ts +15 -22
  136. package/src/pipeline/search.ts +193 -72
  137. package/src/pipeline/snippet.ts +15 -2
  138. package/src/pipeline/temporal.ts +51 -10
  139. package/src/pipeline/vsearch.ts +250 -152
  140. package/src/publish/attachment-raster.ts +2 -16
  141. package/src/publish/encrypted-export.ts +15 -5
  142. package/src/serve/browse-tree.ts +50 -42
  143. package/src/serve/connectors.ts +2 -1
  144. package/src/serve/context.ts +13 -4
  145. package/src/serve/doc-events.ts +3 -0
  146. package/src/serve/public/app.tsx +49 -21
  147. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  148. package/src/serve/public/components/CaptureModal.tsx +14 -10
  149. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  150. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  151. package/src/serve/public/globals.built.css +1 -1
  152. package/src/serve/public/globals.css +19 -0
  153. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  154. package/src/serve/public/lib/metadata-filter.ts +234 -9
  155. package/src/serve/public/pages/Browse.tsx +61 -27
  156. package/src/serve/public/pages/DocView.tsx +44 -25
  157. package/src/serve/public/pages/GraphView.tsx +8 -3
  158. package/src/serve/resident-runtime.ts +199 -48
  159. package/src/serve/routes/api.ts +98 -67
  160. package/src/serve/routes/links.ts +18 -4
  161. package/src/serve/server.ts +1370 -1180
  162. package/src/serve/spa-bundle-source.ts +52 -27
  163. package/src/serve/status.ts +101 -52
  164. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  165. package/src/serve/watch-reconciliation-shared.ts +42 -4
  166. package/src/serve/watch-reconciliation.ts +21 -8
  167. package/src/serve/watch-service-events.ts +7 -1
  168. package/src/serve/watch-service-hosts.ts +3 -1
  169. package/src/serve/watch-service.ts +46 -21
  170. package/src/serve/watch-snapshot-scan.ts +6 -15
  171. package/src/sessions/archive.ts +20 -8
  172. package/src/sessions/sanitize.ts +38 -18
  173. package/src/sessions/service.ts +180 -102
  174. package/src/store/migrations/037-performance-indexes.ts +56 -0
  175. package/src/store/migrations/index.ts +2 -0
  176. package/src/store/sqlite/adapter.ts +1217 -651
  177. package/src/store/sqlite/chunking-policy.ts +15 -1
  178. package/src/store/sqlite/eligibility.ts +110 -70
  179. package/src/store/sqlite/graph-neighbors.ts +71 -46
  180. package/src/store/sqlite/graph-reference-state.ts +27 -3
  181. package/src/store/sqlite/graph-similarity.ts +59 -12
  182. package/src/store/sqlite/metadata-predicate.ts +123 -28
  183. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  184. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  185. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  186. package/src/store/types.ts +32 -0
  187. package/src/store/vector/eligibility.ts +39 -0
  188. package/src/store/vector/lazy.ts +17 -0
  189. package/src/store/vector/partition-index.ts +28 -45
  190. package/src/store/vector/proof-cache.ts +103 -0
  191. package/src/store/vector/sqlite-vec.ts +230 -139
  192. package/src/store/vector/stats.ts +29 -73
  193. package/src/store/vector/status.ts +151 -52
  194. package/src/store/vector/stored-vectors.ts +131 -45
  195. package/src/store/vector/types.ts +10 -0
  196. package/src/store/vector/variant-search.ts +771 -109
  197. package/src/store/vector/variants.ts +495 -139
  198. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -70,36 +70,47 @@ export const attachSearchResultEgressLineage = async (
70
70
  },
71
71
  ])
72
72
  );
73
+ const collectionsByHash = new Map<string, Set<string>>();
74
+ const addOwnerCollection = (hash: string, collection: string): void => {
75
+ let set = collectionsByHash.get(hash);
76
+ if (!set) {
77
+ set = new Set();
78
+ collectionsByHash.set(hash, set);
79
+ }
80
+ set.add(collection);
81
+ };
82
+ for (const document of ownershipDocuments) {
83
+ if (document.mirrorHash) {
84
+ addOwnerCollection(document.mirrorHash, document.collection);
85
+ }
86
+ }
87
+ for (const result of results) {
88
+ const hash = result.conversion?.mirrorHash;
89
+ if (!hash) continue;
90
+ const collection = parseUri(result.uri)?.collection;
91
+ if (collection) {
92
+ addOwnerCollection(hash, collection);
93
+ }
94
+ }
95
+
73
96
  const lineageByMirrorHash = new Map<string, EgressLineage>();
74
97
  for (const mirrorHash of mirrorHashes) {
75
- const ownerCollections = [
76
- ...new Set([
77
- ...ownershipDocuments
78
- .filter((document) => document.mirrorHash === mirrorHash)
79
- .map((owner) => owner.collection),
80
- ...results
81
- .filter((result) => result.conversion?.mirrorHash === mirrorHash)
82
- .map((result) => parseUri(result.uri)?.collection)
83
- .filter((collection): collection is string => Boolean(collection)),
84
- ]),
85
- ];
86
- const policies = ownerCollections.map((collection) =>
87
- policyByCollection.get(collection)
88
- );
89
- if (policies.some((policy) => policy === undefined)) {
90
- return err(
91
- "INVALID_INPUT",
92
- "Search result policy lineage references an unknown collection"
93
- );
98
+ const ownerCollections = collectionsByHash.get(mirrorHash);
99
+ if (!ownerCollections || ownerCollections.size === 0) continue;
100
+ const policies: NonNullable<ReturnType<typeof policyByCollection.get>>[] =
101
+ [];
102
+ for (const collection of ownerCollections) {
103
+ const policy = policyByCollection.get(collection);
104
+ if (policy === undefined) {
105
+ return err(
106
+ "INVALID_INPUT",
107
+ "Search result policy lineage references an unknown collection"
108
+ );
109
+ }
110
+ policies.push(policy);
94
111
  }
95
- if (policies.length === 0) continue;
96
112
  try {
97
- lineageByMirrorHash.set(
98
- mirrorHash,
99
- createEgressLineage(
100
- policies as NonNullable<(typeof policies)[number]>[]
101
- )
102
- );
113
+ lineageByMirrorHash.set(mirrorHash, createEgressLineage(policies));
103
114
  } catch (error) {
104
115
  return err(
105
116
  "INVALID_INPUT",
@@ -28,24 +28,34 @@ export function normalizeExcludeTerms(values: string[]): string[] {
28
28
  return out;
29
29
  }
30
30
 
31
- function includesTerm(haystack: string, term: string): boolean {
32
- return haystack.toLowerCase().includes(term.toLowerCase());
31
+ export function compileExcludeTerms(
32
+ excludeTerms: string[] | undefined
33
+ ): string[] | undefined {
34
+ if (!excludeTerms?.length) {
35
+ return undefined;
36
+ }
37
+ return excludeTerms.map((term) => term.toLowerCase());
33
38
  }
34
39
 
35
40
  export function matchesExcludedText(
36
41
  haystacks: string[],
37
- excludeTerms: string[] | undefined
42
+ excludeTerms: string[] | undefined,
43
+ preLowercased = false
38
44
  ): boolean {
39
45
  if (!excludeTerms?.length) {
40
46
  return false;
41
47
  }
48
+ const lowerTerms = preLowercased
49
+ ? excludeTerms
50
+ : excludeTerms.map((term) => term.toLowerCase());
42
51
 
43
52
  for (const haystack of haystacks) {
44
53
  if (!haystack) {
45
54
  continue;
46
55
  }
47
- for (const term of excludeTerms) {
48
- if (includesTerm(haystack, term)) {
56
+ const lowerHaystack = haystack.toLowerCase();
57
+ for (const term of lowerTerms) {
58
+ if (lowerHaystack.includes(term)) {
49
59
  return true;
50
60
  }
51
61
  }
@@ -55,15 +65,28 @@ export function matchesExcludedText(
55
65
  }
56
66
 
57
67
  export function matchesExcludedChunks(
58
- chunks: ChunkRow[],
59
- excludeTerms: string[] | undefined
68
+ chunks: readonly ChunkRow[],
69
+ excludeTerms: string[] | undefined,
70
+ preLowercased = false
60
71
  ): boolean {
61
72
  if (!excludeTerms?.length || chunks.length === 0) {
62
73
  return false;
63
74
  }
75
+ const lowerTerms = preLowercased
76
+ ? excludeTerms
77
+ : excludeTerms.map((term) => term.toLowerCase());
64
78
 
65
- return matchesExcludedText(
66
- chunks.map((chunk) => chunk.text),
67
- excludeTerms
68
- );
79
+ for (const chunk of chunks) {
80
+ if (!chunk.text) {
81
+ continue;
82
+ }
83
+ const lowerText = chunk.text.toLowerCase();
84
+ for (const term of lowerTerms) {
85
+ if (lowerText.includes(term)) {
86
+ return true;
87
+ }
88
+ }
89
+ }
90
+
91
+ return false;
69
92
  }
@@ -1,4 +1,6 @@
1
1
  import { createHash } from "node:crypto"; // No Bun alternative for hashing
2
+ import { statSync } from "node:fs"; // No Bun sync stat alternative for local model file mtime/size
3
+ import { fileURLToPath } from "node:url"; // No Bun alternative for file:// URL decoding
2
4
 
3
5
  import type { InferenceOptions } from "../llm/types";
4
6
  /**
@@ -65,12 +67,68 @@ const STOPWORDS = new Set([
65
67
  // Cache Key Generation
66
68
  // ─────────────────────────────────────────────────────────────────────────────
67
69
 
68
- /**
69
- * Generate cache key for expansion results.
70
- * Key = SHA256(promptVersion || modelUri || query || lang)
71
- */
72
- export function generateCacheKey(
70
+ export interface ExpansionCacheKeyOptions {
71
+ /** Effective context size used for expansion generation. */
72
+ contextSize?: number;
73
+ /** Optional explicit model fingerprint; falls back to local file mtime/size. */
74
+ modelFingerprint?: string;
75
+ /** Resolved local model file path (e.g. cached GGUF for `hf:` or `file:` URIs). */
76
+ modelPath?: string;
77
+ }
78
+
79
+ function statFileFingerprint(filePath: string): string | null {
80
+ try {
81
+ const stat = statSync(filePath);
82
+ return `file:${stat.size}:${Math.trunc(stat.mtimeMs)}`;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ function resolveLocalModelPath(
73
89
  modelUri: string,
90
+ options?: ExpansionCacheKeyOptions
91
+ ): string | null {
92
+ if (options?.modelPath) return options.modelPath;
93
+ if (modelUri.startsWith("file:")) {
94
+ try {
95
+ return modelUri.startsWith("file://")
96
+ ? fileURLToPath(modelUri)
97
+ : modelUri.slice("file:".length);
98
+ } catch {
99
+ return null;
100
+ }
101
+ }
102
+ return null;
103
+ }
104
+
105
+ function resolveModelIdentityFingerprint(
106
+ modelUri: string,
107
+ options?: ExpansionCacheKeyOptions
108
+ ): string | null {
109
+ if (options?.modelFingerprint) {
110
+ if (options.modelPath) {
111
+ const diskFp = statFileFingerprint(options.modelPath);
112
+ if (diskFp !== options.modelFingerprint) {
113
+ return null;
114
+ }
115
+ }
116
+ return options.modelFingerprint;
117
+ }
118
+ const localPath = resolveLocalModelPath(modelUri, options);
119
+ if (localPath) {
120
+ return statFileFingerprint(localPath);
121
+ }
122
+ if (modelUri.startsWith("http://") || modelUri.startsWith("https://")) {
123
+ return `uri:${modelUri}`;
124
+ }
125
+ return null;
126
+ }
127
+
128
+ function hashExpansionCacheKey(
129
+ modelUri: string,
130
+ fingerprint: string,
131
+ contextSize: number | undefined,
74
132
  query: string,
75
133
  lang: string,
76
134
  intent?: string
@@ -78,6 +136,8 @@ export function generateCacheKey(
78
136
  const data = [
79
137
  EXPANSION_PROMPT_VERSION,
80
138
  modelUri,
139
+ fingerprint,
140
+ contextSize !== undefined ? String(contextSize) : "",
81
141
  query,
82
142
  lang,
83
143
  intent?.trim() ?? "",
@@ -85,6 +145,28 @@ export function generateCacheKey(
85
145
  return createHash("sha256").update(data).digest("hex");
86
146
  }
87
147
 
148
+ /**
149
+ * Generate cache key for expansion results.
150
+ * Key = SHA256(promptVersion || modelUri || modelFingerprint || contextSize || query || lang || intent)
151
+ */
152
+ export function generateCacheKey(
153
+ modelUri: string,
154
+ query: string,
155
+ lang: string,
156
+ intent?: string,
157
+ options?: ExpansionCacheKeyOptions
158
+ ): string {
159
+ const fingerprint = resolveModelIdentityFingerprint(modelUri, options) ?? "";
160
+ return hashExpansionCacheKey(
161
+ modelUri,
162
+ fingerprint,
163
+ options?.contextSize,
164
+ query,
165
+ lang,
166
+ intent
167
+ );
168
+ }
169
+
88
170
  // ─────────────────────────────────────────────────────────────────────────────
89
171
  // Prompt Templates
90
172
  // ─────────────────────────────────────────────────────────────────────────────
@@ -519,6 +601,54 @@ export interface CachedExpansionDeps {
519
601
  genPort: GenerationPort;
520
602
  getCache: (key: string) => Promise<string | null>;
521
603
  setCache: (key: string, value: string) => Promise<void>;
604
+ modelFingerprint?: string;
605
+ modelPath?: string;
606
+ onCacheLookup?: () => void;
607
+ onCacheHit?: () => void;
608
+ }
609
+
610
+ /**
611
+ * Strictly validate persisted expansion cache JSON written by expandQueryCached.
612
+ * Rejects structurally corrupt entries (e.g. non-string array items or missing fields)
613
+ * so they degrade cleanly to a cache miss and live generation.
614
+ */
615
+ function parseCachedExpansionResult(raw: string): ExpansionResult | null {
616
+ try {
617
+ const parsed: unknown = JSON.parse(raw);
618
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
619
+ return null;
620
+ }
621
+ const obj = parsed as Record<string, unknown>;
622
+ if (
623
+ !Array.isArray(obj.lexicalQueries) ||
624
+ !Array.isArray(obj.vectorQueries)
625
+ ) {
626
+ return null;
627
+ }
628
+ const lexicalQueries: string[] = [];
629
+ for (const item of obj.lexicalQueries) {
630
+ if (typeof item !== "string" || item.trim().length === 0) return null;
631
+ lexicalQueries.push(item.trim());
632
+ }
633
+ const vectorQueries: string[] = [];
634
+ for (const item of obj.vectorQueries) {
635
+ if (typeof item !== "string" || item.trim().length === 0) return null;
636
+ vectorQueries.push(item.trim());
637
+ }
638
+ let hyde: string | undefined;
639
+ if (obj.hyde !== undefined) {
640
+ if (typeof obj.hyde !== "string" || obj.hyde.trim().length === 0) {
641
+ return null;
642
+ }
643
+ hyde = obj.hyde.trim();
644
+ }
645
+ if (lexicalQueries.length === 0 && vectorQueries.length === 0 && !hyde) {
646
+ return null;
647
+ }
648
+ return { lexicalQueries, vectorQueries, hyde };
649
+ } catch {
650
+ return null;
651
+ }
522
652
  }
523
653
 
524
654
  /**
@@ -529,20 +659,63 @@ export async function expandQueryCached(
529
659
  query: string,
530
660
  options: ExpansionOptions = {}
531
661
  ): Promise<StoreResult<ExpansionResult | null>> {
662
+ const resolveIdentity = (): string | null =>
663
+ resolveModelIdentityFingerprint(deps.genPort.modelUri, {
664
+ contextSize: options.contextSize,
665
+ modelFingerprint: deps.modelFingerprint ?? deps.genPort.modelFingerprint,
666
+ modelPath: deps.modelPath ?? deps.genPort.modelPath,
667
+ });
668
+
532
669
  const lang = options.lang ?? "auto";
533
- const cacheKey = generateCacheKey(
534
- deps.genPort.modelUri,
535
- query,
536
- lang,
537
- options.intent
538
- );
670
+ const initialIdentity = resolveIdentity();
671
+ // On a cold lazy port, probe cached local model identity read-only so
672
+ // persistent cache hits skip worker initialization and generation.
673
+ let lookupIdentity = initialIdentity;
674
+ if (
675
+ lookupIdentity === null &&
676
+ typeof deps.genPort.resolveModelIdentity === "function"
677
+ ) {
678
+ try {
679
+ const probed = await deps.genPort.resolveModelIdentity();
680
+ if (probed) {
681
+ lookupIdentity = resolveModelIdentityFingerprint(
682
+ deps.genPort.modelUri,
683
+ {
684
+ contextSize: options.contextSize,
685
+ modelFingerprint: deps.modelFingerprint ?? probed.modelFingerprint,
686
+ modelPath: deps.modelPath ?? probed.modelPath,
687
+ }
688
+ );
689
+ }
690
+ } catch {
691
+ lookupIdentity = null;
692
+ }
693
+ }
694
+ let cacheKey: string | null = null;
695
+ if (lookupIdentity !== null) {
696
+ cacheKey = hashExpansionCacheKey(
697
+ deps.genPort.modelUri,
698
+ lookupIdentity,
699
+ options.contextSize,
700
+ query,
701
+ lang,
702
+ options.intent
703
+ );
539
704
 
540
- // Check cache
541
- const cached = await deps.getCache(cacheKey);
542
- if (cached) {
543
- const parsed = parseExpansionResult(cached);
544
- if (parsed) {
545
- return ok(applyExpansionGuardrails(query, parsed));
705
+ // Check cache (corrupt entries or read errors degrade cleanly to live expansion)
706
+ deps.onCacheLookup?.();
707
+ let cached: string | null = null;
708
+ try {
709
+ cached = await deps.getCache(cacheKey);
710
+ } catch {
711
+ cached = null;
712
+ }
713
+ if (cached) {
714
+ const parsed = parseCachedExpansionResult(cached);
715
+ if (parsed) {
716
+ deps.onCacheHit?.();
717
+ return ok(applyExpansionGuardrails(query, parsed));
718
+ }
546
719
  }
547
720
  }
548
721
 
@@ -552,9 +725,50 @@ export async function expandQueryCached(
552
725
  return result;
553
726
  }
554
727
 
555
- // Cache result
728
+ // Cache result (write failures never fail retrieval).
729
+ // - Warm path (initialIdentity !== null): verify the on-disk file did not
730
+ // change mid-flight before persisting under initialIdentity.
731
+ // - Cold lazy path (initialIdentity === null): only persist when the
732
+ // initialized port supplies a pre-generation modelFingerprint AND any
733
+ // associated local file still matches it, preventing a mid-flight model
734
+ // replacement from caching model A's output under model B's fingerprint.
556
735
  if (result.value) {
557
- await deps.setCache(cacheKey, JSON.stringify(result.value));
736
+ let writeIdentity: string | null = null;
737
+ if (initialIdentity !== null) {
738
+ const currentIdentity = resolveIdentity();
739
+ if (currentIdentity === initialIdentity) {
740
+ writeIdentity = initialIdentity;
741
+ }
742
+ } else {
743
+ const postFingerprint =
744
+ deps.modelFingerprint ?? deps.genPort.modelFingerprint;
745
+ if (postFingerprint) {
746
+ const postPath = resolveLocalModelPath(deps.genPort.modelUri, {
747
+ modelPath: deps.modelPath ?? deps.genPort.modelPath,
748
+ });
749
+ if (!postPath || statFileFingerprint(postPath) === postFingerprint) {
750
+ writeIdentity = postFingerprint;
751
+ }
752
+ }
753
+ }
754
+ if (writeIdentity !== null) {
755
+ const writeKey =
756
+ writeIdentity === lookupIdentity && cacheKey
757
+ ? cacheKey
758
+ : hashExpansionCacheKey(
759
+ deps.genPort.modelUri,
760
+ writeIdentity,
761
+ options.contextSize,
762
+ query,
763
+ lang,
764
+ options.intent
765
+ );
766
+ try {
767
+ await deps.setCache(writeKey, JSON.stringify(result.value));
768
+ } catch {
769
+ // Ignore cache persistence errors (e.g. read-only store or busy lock)
770
+ }
771
+ }
558
772
  }
559
773
 
560
774
  return result;