@gmickel/gno 2.15.0 → 2.17.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 (218) hide show
  1. package/README.md +1 -1
  2. package/assets/skill/SKILL.md +27 -0
  3. package/assets/skill/cli-reference.md +24 -15
  4. package/assets/spa-production.json.gz +0 -0
  5. package/browser-extension/artifacts/{gno-browser-clipper-v2.15.0.zip → gno-browser-clipper-v2.17.0.zip} +0 -0
  6. package/browser-extension/artifacts/gno-browser-clipper-v2.17.0.zip.sha256 +1 -0
  7. package/browser-extension/dist/manifest.json +1 -1
  8. package/package.json +1 -1
  9. package/spec/cli.md +43 -3
  10. package/spec/db/schema.sql +53 -1
  11. package/spec/mcp.md +9 -3
  12. package/spec/output-schemas/doctor.schema.json +27 -0
  13. package/spec/output-schemas/retrieval-trace-payloads.schema.json +14 -0
  14. package/spec/output-schemas/search-results.schema.json +14 -0
  15. package/spec/output-schemas/status.schema.json +22 -0
  16. package/src/cli/commands/agents/commands.ts +1 -1
  17. package/src/cli/commands/ask.ts +1 -1
  18. package/src/cli/commands/context-build.ts +1 -1
  19. package/src/cli/commands/doctor.ts +101 -29
  20. package/src/cli/commands/embed.ts +2 -2
  21. package/src/cli/commands/links.ts +30 -6
  22. package/src/cli/commands/mcp/install.ts +2 -2
  23. package/src/cli/commands/mcp/status.ts +1 -1
  24. package/src/cli/commands/mcp/uninstall.ts +1 -1
  25. package/src/cli/commands/query.ts +1 -1
  26. package/src/cli/commands/shared.ts +4 -4
  27. package/src/cli/commands/skill/install.ts +1 -1
  28. package/src/cli/commands/skill/paths-cmd.ts +1 -1
  29. package/src/cli/commands/skill/uninstall.ts +1 -1
  30. package/src/cli/commands/status.ts +75 -58
  31. package/src/cli/commands/vec.ts +180 -8
  32. package/src/cli/config-cache.ts +86 -0
  33. package/src/cli/globals.ts +64 -0
  34. package/src/cli/program.ts +63 -36
  35. package/src/cli/run.ts +121 -67
  36. package/src/cli/runtime-health.ts +132 -122
  37. package/src/cli/session-binding.ts +11 -2
  38. package/src/config/saver.ts +8 -0
  39. package/src/config/types.ts +6 -0
  40. package/src/converters/adapters/browser-export/formats.ts +25 -15
  41. package/src/converters/adapters/email/adapter.ts +37 -53
  42. package/src/converters/adapters/email/html.ts +37 -20
  43. package/src/converters/adapters/email/mime.ts +71 -39
  44. package/src/converters/adapters/ical/adapter.ts +20 -12
  45. package/src/converters/adapters/jsonl/adapter.ts +8 -6
  46. package/src/converters/adapters/shared/html-text.ts +55 -37
  47. package/src/converters/adapters/shared/ooxml-protection.ts +5 -13
  48. package/src/converters/adapters/shared/utf8-lines.ts +69 -31
  49. package/src/converters/adapters/transcript/adapter.ts +12 -7
  50. package/src/converters/adapters/xlsx/adapter.ts +10 -7
  51. package/src/converters/adapters/xlsx/sheet-markdown.ts +93 -50
  52. package/src/converters/canonicalize.ts +17 -3
  53. package/src/converters/native/markdown.ts +24 -17
  54. package/src/converters/native/plaintext.ts +5 -6
  55. package/src/converters/registry.ts +130 -8
  56. package/src/core/activation-status.ts +4 -8
  57. package/src/core/change-diff.ts +38 -11
  58. package/src/core/context-compiler.ts +17 -18
  59. package/src/core/context-evidence.ts +116 -25
  60. package/src/core/context-verifier.ts +70 -31
  61. package/src/core/file-lock.ts +10 -2
  62. package/src/core/graph-analysis.ts +3 -3
  63. package/src/core/link-inventory-markdown.ts +2 -2
  64. package/src/core/links.ts +20 -87
  65. package/src/core/memory-fence.ts +16 -9
  66. package/src/core/memory-recall.ts +168 -34
  67. package/src/core/path-rules.ts +143 -0
  68. package/src/core/retrieval-trace-session.ts +3 -0
  69. package/src/core/retrieval-trace.ts +9 -0
  70. package/src/core/section-parse.ts +16 -6
  71. package/src/core/typed-metadata.ts +68 -0
  72. package/src/core/vector-partition-status.ts +13 -0
  73. package/src/core/wiki-link-syntax.ts +88 -0
  74. package/src/embed/backlog.ts +142 -60
  75. package/src/embed/retry.ts +39 -33
  76. package/src/embed/variant-backlog.ts +582 -116
  77. package/src/embed/variant-retry.ts +157 -48
  78. package/src/index.ts +3 -3
  79. package/src/ingestion/budget-error-codes.ts +13 -0
  80. package/src/ingestion/chunker.ts +60 -49
  81. package/src/ingestion/compiled-context.ts +4 -5
  82. package/src/ingestion/convert-file.ts +1 -1
  83. package/src/ingestion/document-metadata.ts +16 -9
  84. package/src/ingestion/excluded-ranges.ts +97 -0
  85. package/src/ingestion/file-processor.ts +122 -37
  86. package/src/ingestion/frontmatter.ts +35 -7
  87. package/src/ingestion/graph-reconciliation.ts +187 -51
  88. package/src/ingestion/language.ts +66 -61
  89. package/src/ingestion/position.ts +5 -5
  90. package/src/ingestion/prepare-file.ts +50 -29
  91. package/src/ingestion/record-adapter-canonical.ts +37 -26
  92. package/src/ingestion/record-adapter.ts +46 -26
  93. package/src/ingestion/record-container.ts +121 -53
  94. package/src/ingestion/record-path.ts +5 -2
  95. package/src/ingestion/source-availability/darwin-io.ts +10 -7
  96. package/src/ingestion/source-availability/darwin-path.ts +21 -3
  97. package/src/ingestion/source-availability/readers.ts +51 -0
  98. package/src/ingestion/strip.ts +39 -105
  99. package/src/ingestion/sync.ts +692 -386
  100. package/src/ingestion/typed-metadata.ts +10 -4
  101. package/src/ingestion/walker.ts +485 -158
  102. package/src/llm/cache.ts +128 -84
  103. package/src/llm/http-inference.ts +112 -35
  104. package/src/llm/http-policy.ts +101 -0
  105. package/src/llm/httpEmbedding.ts +8 -1
  106. package/src/llm/httpGeneration.ts +5 -1
  107. package/src/llm/httpRerank.ts +5 -1
  108. package/src/llm/inference-scope.ts +15 -2
  109. package/src/llm/lazy-ports.ts +33 -3
  110. package/src/llm/lockfile.ts +34 -7
  111. package/src/llm/model-cleanup.ts +24 -0
  112. package/src/llm/native-worker/client.ts +23 -12
  113. package/src/llm/native-worker/dispatcher.ts +19 -9
  114. package/src/llm/native-worker/embedding-identity.ts +42 -16
  115. package/src/llm/native-worker/entry.ts +2 -1
  116. package/src/llm/native-worker/owner.ts +1 -0
  117. package/src/llm/native-worker/ports.ts +86 -23
  118. package/src/llm/native-worker/protocol.ts +386 -55
  119. package/src/llm/nodeLlamaCpp/adapter.ts +46 -29
  120. package/src/llm/nodeLlamaCpp/embedding.ts +93 -40
  121. package/src/llm/nodeLlamaCpp/generation.ts +194 -30
  122. package/src/llm/nodeLlamaCpp/lifecycle.ts +2 -0
  123. package/src/llm/nodeLlamaCpp/rerank-capacity.ts +101 -23
  124. package/src/llm/nodeLlamaCpp/rerank.ts +253 -44
  125. package/src/llm/types.ts +14 -0
  126. package/src/mcp/context.ts +342 -23
  127. package/src/mcp/http-transport.ts +21 -3
  128. package/src/mcp/tool-profile-types.ts +62 -0
  129. package/src/mcp/tool-profile.ts +32 -56
  130. package/src/mcp/tools/context.ts +5 -1
  131. package/src/mcp/tools/index.ts +269 -191
  132. package/src/mcp/tools/links.ts +14 -6
  133. package/src/mcp/tools/query.ts +60 -37
  134. package/src/mcp/tools/vsearch.ts +25 -14
  135. package/src/pipeline/answer.ts +133 -40
  136. package/src/pipeline/claim-verification.ts +293 -189
  137. package/src/pipeline/claim-verifier.ts +6 -7
  138. package/src/pipeline/egress-lineage.ts +37 -26
  139. package/src/pipeline/exclude.ts +34 -11
  140. package/src/pipeline/expansion.ts +233 -19
  141. package/src/pipeline/explain.ts +17 -2
  142. package/src/pipeline/filters.ts +169 -33
  143. package/src/pipeline/graph-retrieval.ts +117 -61
  144. package/src/pipeline/hybrid.ts +626 -330
  145. package/src/pipeline/hydration.ts +86 -24
  146. package/src/pipeline/intent.ts +15 -7
  147. package/src/pipeline/owner-fusion.ts +61 -19
  148. package/src/pipeline/query-language.ts +15 -2
  149. package/src/pipeline/rerank.ts +15 -22
  150. package/src/pipeline/search.ts +193 -72
  151. package/src/pipeline/snippet.ts +15 -2
  152. package/src/pipeline/temporal.ts +51 -10
  153. package/src/pipeline/types.ts +7 -0
  154. package/src/pipeline/vsearch.ts +269 -154
  155. package/src/publish/attachment-raster.ts +2 -16
  156. package/src/publish/encrypted-export.ts +15 -5
  157. package/src/serve/browse-tree.ts +50 -42
  158. package/src/serve/connectors.ts +2 -1
  159. package/src/serve/context.ts +13 -4
  160. package/src/serve/doc-events.ts +3 -0
  161. package/src/serve/public/app.tsx +49 -21
  162. package/src/serve/public/components/BrowseTreeSidebar.tsx +163 -23
  163. package/src/serve/public/components/CaptureModal.tsx +14 -10
  164. package/src/serve/public/components/ai-elements/code-block.tsx +87 -50
  165. package/src/serve/public/components/editor/MarkdownPreview.tsx +99 -67
  166. package/src/serve/public/globals.built.css +1 -1
  167. package/src/serve/public/globals.css +19 -0
  168. package/src/serve/public/hooks/useCaptureModal.tsx +23 -10
  169. package/src/serve/public/lib/metadata-filter.ts +234 -9
  170. package/src/serve/public/pages/Browse.tsx +61 -27
  171. package/src/serve/public/pages/DocView.tsx +44 -25
  172. package/src/serve/public/pages/GraphView.tsx +8 -3
  173. package/src/serve/resident-runtime.ts +199 -48
  174. package/src/serve/routes/api.ts +98 -67
  175. package/src/serve/routes/links.ts +25 -5
  176. package/src/serve/server.ts +1370 -1180
  177. package/src/serve/spa-bundle-source.ts +52 -27
  178. package/src/serve/status.ts +101 -52
  179. package/src/serve/watch-reconciliation-fallback.ts +11 -7
  180. package/src/serve/watch-reconciliation-shared.ts +42 -4
  181. package/src/serve/watch-reconciliation.ts +21 -8
  182. package/src/serve/watch-service-events.ts +7 -1
  183. package/src/serve/watch-service-hosts.ts +3 -1
  184. package/src/serve/watch-service.ts +46 -21
  185. package/src/serve/watch-snapshot-scan.ts +6 -15
  186. package/src/sessions/archive.ts +20 -8
  187. package/src/sessions/sanitize.ts +38 -18
  188. package/src/sessions/service.ts +180 -102
  189. package/src/store/migrations/037-performance-indexes.ts +56 -0
  190. package/src/store/migrations/038-vector-mirror-null-cosine.ts +47 -0
  191. package/src/store/migrations/039-vector-mirror-v2.ts +94 -0
  192. package/src/store/migrations/index.ts +6 -0
  193. package/src/store/sqlite/adapter.ts +1260 -651
  194. package/src/store/sqlite/chunking-policy.ts +15 -1
  195. package/src/store/sqlite/eligibility.ts +110 -70
  196. package/src/store/sqlite/graph-neighbors.ts +71 -46
  197. package/src/store/sqlite/graph-reference-state.ts +27 -3
  198. package/src/store/sqlite/graph-similarity.ts +59 -12
  199. package/src/store/sqlite/metadata-predicate.ts +123 -28
  200. package/src/store/sqlite/retrieval-trace-management-store.ts +126 -33
  201. package/src/store/sqlite/retrieval-trace-retention.ts +88 -76
  202. package/src/store/sqlite/retrieval-trace-rows.ts +7 -3
  203. package/src/store/types.ts +32 -0
  204. package/src/store/vector/coarse-router.ts +312 -0
  205. package/src/store/vector/eligibility.ts +39 -0
  206. package/src/store/vector/lazy.ts +17 -0
  207. package/src/store/vector/partition-index.ts +333 -59
  208. package/src/store/vector/proof-cache.ts +209 -0
  209. package/src/store/vector/runtime-compat.ts +6 -0
  210. package/src/store/vector/sqlite-vec.ts +270 -162
  211. package/src/store/vector/stats.ts +37 -73
  212. package/src/store/vector/status.ts +169 -53
  213. package/src/store/vector/stored-vectors.ts +131 -45
  214. package/src/store/vector/types.ts +19 -0
  215. package/src/store/vector/v2-mirror.ts +669 -0
  216. package/src/store/vector/variant-search.ts +1187 -111
  217. package/src/store/vector/variants.ts +964 -160
  218. package/browser-extension/artifacts/gno-browser-clipper-v2.15.0.zip.sha256 +0 -1
@@ -343,11 +343,20 @@ export const safeFailure = (
343
343
  };
344
344
  };
345
345
 
346
+ export interface PrecomputedAdapterIdentity {
347
+ adapterIdentity: RecordAdapterIdentity;
348
+ adapterFingerprint: string;
349
+ }
350
+
346
351
  export const canonicalRecord = (
347
352
  adapter: RecordAdapter,
348
- record: RecordAdapterRecord
353
+ record: RecordAdapterRecord,
354
+ precomputed?: PrecomputedAdapterIdentity
349
355
  ): AccountedCanonicalRecord => {
350
- const adapterIdentity = normalizeRecordAdapterIdentity(adapter);
356
+ const adapterIdentity =
357
+ precomputed?.adapterIdentity ?? normalizeRecordAdapterIdentity(adapter);
358
+ const adapterFingerprint =
359
+ precomputed?.adapterFingerprint ?? recordAdapterFingerprint(adapter);
351
360
  const stableId = normalizeStableId(record.stableId);
352
361
  const sourceLocator = normalizeLocator(record.sourceLocator);
353
362
  const markdown = canonicalize(record.markdown);
@@ -362,29 +371,31 @@ export const canonicalRecord = (
362
371
  record.languageHint,
363
372
  RECORD_METADATA_LIMITS.maxLanguageHintChars
364
373
  );
365
- const derivedSource = JSON.stringify(
366
- canonicalJsonValue({
367
- anchors,
368
- languageHint,
369
- markdown,
370
- metadata,
371
- ...custom,
372
- sourceLocator,
373
- stableId,
374
- title,
375
- })
376
- );
377
- const metadataChars = JSON.stringify(
378
- canonicalJsonValue({
379
- anchors,
380
- languageHint,
381
- metadata,
382
- ...custom,
383
- sourceLocator,
384
- stableId,
385
- title,
386
- })
387
- ).length;
374
+ // Canonicalize the metadata envelope once and reuse its sorted entries for
375
+ // derivedSource so canonicalJsonValue never walks metadata/anchors twice.
376
+ const canonicalMeta = canonicalJsonValue({
377
+ anchors,
378
+ languageHint,
379
+ metadata,
380
+ ...custom,
381
+ sourceLocator,
382
+ stableId,
383
+ title,
384
+ }) as Record<string, unknown>;
385
+ const metadataChars = JSON.stringify(canonicalMeta).length;
386
+ const canonicalWithMarkdown: Record<string, unknown> = {};
387
+ let insertedMarkdown = false;
388
+ for (const key of Object.keys(canonicalMeta)) {
389
+ if (!insertedMarkdown && key > "markdown") {
390
+ canonicalWithMarkdown.markdown = markdown;
391
+ insertedMarkdown = true;
392
+ }
393
+ canonicalWithMarkdown[key] = canonicalMeta[key];
394
+ }
395
+ if (!insertedMarkdown) {
396
+ canonicalWithMarkdown.markdown = markdown;
397
+ }
398
+ const derivedSource = JSON.stringify(canonicalWithMarkdown);
388
399
  if (
389
400
  record.sourceHash !== undefined &&
390
401
  !HASH_PATTERN.test(record.sourceHash)
@@ -401,7 +412,7 @@ export const canonicalRecord = (
401
412
  markdown,
402
413
  adapterId: adapterIdentity.id,
403
414
  adapterVersion: adapterIdentity.version,
404
- adapterFingerprint: recordAdapterFingerprint(adapter),
415
+ adapterFingerprint,
405
416
  title,
406
417
  languageHint,
407
418
  metadata,
@@ -51,29 +51,6 @@ class SourceLimitError extends Error {
51
51
 
52
52
  const TIMEOUT = Symbol("record-adapter-timeout");
53
53
 
54
- const nextBeforeDeadline = async <T>(
55
- iterator: AsyncIterator<T>,
56
- deadlineMs: number
57
- ): Promise<IteratorResult<T> | typeof TIMEOUT> => {
58
- const remainingMs = deadlineMs - Date.now();
59
- if (remainingMs <= 0) return TIMEOUT;
60
- return await new Promise<IteratorResult<T> | typeof TIMEOUT>(
61
- (resolve, reject) => {
62
- const timer = setTimeout(() => resolve(TIMEOUT), remainingMs);
63
- void iterator.next().then(
64
- (value) => {
65
- clearTimeout(timer);
66
- resolve(value);
67
- },
68
- (error: unknown) => {
69
- clearTimeout(timer);
70
- reject(error);
71
- }
72
- );
73
- }
74
- );
75
- };
76
-
77
54
  const closeIterator = async (
78
55
  iterator: AsyncIterator<unknown>
79
56
  ): Promise<boolean> => {
@@ -94,6 +71,7 @@ export async function runRecordAdapter(
94
71
  ): Promise<RecordAdapterRunResult> {
95
72
  const adapterIdentity = normalizeRecordAdapterIdentity(adapter);
96
73
  const adapterFingerprint = recordAdapterFingerprint(adapter);
74
+ const precomputedAdapter = { adapterIdentity, adapterFingerprint };
97
75
  const egressLineage = egressLineageSchema.parse(
98
76
  options.egressLineage ?? legacyLocalOnlyEgressLineage(input.collection)
99
77
  );
@@ -113,7 +91,45 @@ export async function runRecordAdapter(
113
91
  let stoppedByFailureLimit = false;
114
92
  let timedOut = false;
115
93
  const abortController = new AbortController();
116
- const deadlineMs = Date.now() + (input.limits.timeoutMs ?? 60_000);
94
+ // Single shared deadline timer for the entire container with a replaceable
95
+ // waiter slot (avoids per-record setTimeout overhead and handler accumulation)
96
+ // plus an absolute wall-clock check before every iterator advance so synchronous
97
+ // adapter work exceeding timeoutMs cannot slip through microtasks.
98
+ const timeoutMs = input.limits.timeoutMs ?? 60_000;
99
+ const deadlineMs = Date.now() + timeoutMs;
100
+ let deadlineExpired = timeoutMs <= 0;
101
+ let onDeadline: (() => void) | undefined;
102
+ const deadlineTimer = deadlineExpired
103
+ ? undefined
104
+ : setTimeout(() => {
105
+ deadlineExpired = true;
106
+ const cb = onDeadline;
107
+ onDeadline = undefined;
108
+ cb?.();
109
+ }, timeoutMs);
110
+ const nextBeforeDeadline = <T>(
111
+ iter: AsyncIterator<T>
112
+ ): Promise<IteratorResult<T> | typeof TIMEOUT> => {
113
+ if (deadlineExpired || Date.now() >= deadlineMs) {
114
+ deadlineExpired = true;
115
+ return Promise.resolve(TIMEOUT);
116
+ }
117
+ return new Promise<IteratorResult<T> | typeof TIMEOUT>(
118
+ (resolve, reject) => {
119
+ onDeadline = () => resolve(TIMEOUT);
120
+ void iter.next().then(
121
+ (value) => {
122
+ onDeadline = undefined;
123
+ resolve(value);
124
+ },
125
+ (error: unknown) => {
126
+ onDeadline = undefined;
127
+ reject(error);
128
+ }
129
+ );
130
+ }
131
+ );
132
+ };
117
133
 
118
134
  const appendFailure = (failure: RecordAdapterFailure): boolean => {
119
135
  if (stoppedByFailureLimit) return true;
@@ -180,7 +196,7 @@ export async function runRecordAdapter(
180
196
  })
181
197
  [Symbol.asyncIterator]();
182
198
  while (true) {
183
- const next = await nextBeforeDeadline(iterator, deadlineMs);
199
+ const next = await nextBeforeDeadline(iterator);
184
200
  if (next === TIMEOUT) {
185
201
  timedOut = true;
186
202
  stoppedByCap = true;
@@ -240,7 +256,7 @@ export async function runRecordAdapter(
240
256
  } else {
241
257
  let record: AccountedCanonicalRecord;
242
258
  try {
243
- record = canonicalRecord(adapter, event.record);
259
+ record = canonicalRecord(adapter, event.record, precomputedAdapter);
244
260
  } catch (error) {
245
261
  const code: RecordAdapterFailureCode =
246
262
  error instanceof Error && error.message === "invalid source locator"
@@ -344,6 +360,10 @@ export async function runRecordAdapter(
344
360
  );
345
361
  stoppedByCap ||= error instanceof SourceLimitError;
346
362
  } finally {
363
+ if (deadlineTimer !== undefined) {
364
+ clearTimeout(deadlineTimer);
365
+ }
366
+ onDeadline = undefined;
347
367
  if (iterator) {
348
368
  if (timedOut) {
349
369
  void closeIterator(iterator);
@@ -26,7 +26,7 @@ import { createEgressLineage } from "../core/egress-provenance";
26
26
  import { normalizeTag, validateTag } from "../core/tags";
27
27
  import { persistChunkLayout } from "./chunking";
28
28
  import { runRecordAdapter } from "./record-adapter";
29
- import { recordVirtualPath } from "./record-path";
29
+ import { recordVirtualPathPrefix } from "./record-path";
30
30
  import { reconcileRecordSnapshot, type RecordSyncPlan } from "./record-sync";
31
31
  import { DEFAULT_CHUNK_PARAMS, MAX_RECORD_IMPORT_RECEIPT_ITEMS } from "./types";
32
32
 
@@ -67,6 +67,10 @@ interface RecordContainerInput {
67
67
  * When set, record import streams from this buffer and never reopens the path.
68
68
  */
69
69
  sourceBytes?: Uint8Array;
70
+ /** Optional preloaded record rows for `entry.relPath` (avoids per-file query). */
71
+ preloadedPriorDocuments?: DocumentRow[];
72
+ /** Optional preloaded primary document row for `entry.relPath`. */
73
+ preloadedSourceDocument?: DocumentRow | null;
70
74
  }
71
75
 
72
76
  interface AppliedRecordReconciliation {
@@ -103,12 +107,16 @@ const OFFSET_DATE_TIME_PATTERN =
103
107
  const TZID_DATE_TIME_PATTERN =
104
108
  /^TZID=([^:]{1,128}):(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})$/;
105
109
 
106
- const timeZoneParts = (
107
- epochMs: number,
110
+ const MAX_TZ_FORMATTERS = 64;
111
+ const TZ_FORMATTERS = new Map<string, Intl.DateTimeFormat>();
112
+
113
+ const getTimeZoneFormatter = (
108
114
  timeZone: string
109
- ): [number, number, number, number, number, number] | undefined => {
115
+ ): Intl.DateTimeFormat | undefined => {
116
+ const cached = TZ_FORMATTERS.get(timeZone);
117
+ if (cached) return cached;
110
118
  try {
111
- const parts = new Intl.DateTimeFormat("en-CA", {
119
+ const formatter = new Intl.DateTimeFormat("en-CA", {
112
120
  timeZone,
113
121
  calendar: "iso8601",
114
122
  numberingSystem: "latn",
@@ -119,20 +127,53 @@ const timeZoneParts = (
119
127
  minute: "2-digit",
120
128
  second: "2-digit",
121
129
  hourCycle: "h23",
122
- }).formatToParts(new Date(epochMs));
123
- const values = new Map(
124
- parts.map((part) => [part.type, Number(part.value)])
125
- );
126
- const tuple = [
127
- values.get("year"),
128
- values.get("month"),
129
- values.get("day"),
130
- values.get("hour"),
131
- values.get("minute"),
132
- values.get("second"),
133
- ];
134
- if (tuple.some((value) => !Number.isInteger(value))) return undefined;
135
- return tuple as [number, number, number, number, number, number];
130
+ });
131
+ if (TZ_FORMATTERS.size >= MAX_TZ_FORMATTERS) {
132
+ const oldest = TZ_FORMATTERS.keys().next().value;
133
+ if (oldest !== undefined) TZ_FORMATTERS.delete(oldest);
134
+ }
135
+ TZ_FORMATTERS.set(timeZone, formatter);
136
+ return formatter;
137
+ } catch {
138
+ return undefined;
139
+ }
140
+ };
141
+
142
+ const timeZoneParts = (
143
+ epochMs: number,
144
+ timeZone: string
145
+ ): [number, number, number, number, number, number] | undefined => {
146
+ const formatter = getTimeZoneFormatter(timeZone);
147
+ if (!formatter) return undefined;
148
+ try {
149
+ const parts = formatter.formatToParts(new Date(epochMs));
150
+ let year = Number.NaN;
151
+ let month = Number.NaN;
152
+ let day = Number.NaN;
153
+ let hour = Number.NaN;
154
+ let minute = Number.NaN;
155
+ let second = Number.NaN;
156
+ for (const part of parts) {
157
+ if (part.type === "year") year = Number(part.value);
158
+ else if (part.type === "month") month = Number(part.value);
159
+ else if (part.type === "day") day = Number(part.value);
160
+ else if (part.type === "hour") hour = Number(part.value);
161
+ else if (part.type === "minute") minute = Number(part.value);
162
+ else if (part.type === "second") second = Number(part.value);
163
+ }
164
+ if (
165
+ !(
166
+ Number.isInteger(year) &&
167
+ Number.isInteger(month) &&
168
+ Number.isInteger(day) &&
169
+ Number.isInteger(hour) &&
170
+ Number.isInteger(minute) &&
171
+ Number.isInteger(second)
172
+ )
173
+ ) {
174
+ return undefined;
175
+ }
176
+ return [year, month, day, hour, minute, second];
136
177
  } catch {
137
178
  return undefined;
138
179
  }
@@ -330,11 +371,12 @@ const loadPreviousStructure = async (
330
371
  const persistRecord = async (
331
372
  input: RecordContainerInput,
332
373
  record: Awaited<ReturnType<typeof runRecordAdapter>>["records"][number],
374
+ virtualPathPrefix: string,
333
375
  existing: DocumentRow | undefined,
334
376
  wrapInTransaction = true,
335
377
  rebuildEvidence = true
336
378
  ): Promise<void> => {
337
- const virtualPath = recordVirtualPath(input.entry.relPath, record.recordKey);
379
+ const virtualPath = `${virtualPathPrefix}${record.recordKey}.md`;
338
380
  const inferred = input.extractMetadata(
339
381
  record.markdown,
340
382
  virtualPath,
@@ -508,18 +550,27 @@ export async function processRecordContainer(
508
550
  }
509
551
  );
510
552
 
553
+ const virtualPathPrefix = recordVirtualPathPrefix(input.entry.relPath);
511
554
  const reconcileAndApply = async (): Promise<AppliedRecordReconciliation> => {
512
- const priorDocuments = mustOk(
513
- await input.store.listRecordDocuments(
514
- input.collection.name,
515
- input.entry.relPath
516
- ),
517
- "listRecordDocuments"
518
- );
519
- const sourceDocument = mustOk(
520
- await input.store.getDocument(input.collection.name, input.entry.relPath),
521
- "getDocument"
522
- );
555
+ const priorDocuments =
556
+ input.preloadedPriorDocuments ??
557
+ mustOk(
558
+ await input.store.listRecordDocuments(
559
+ input.collection.name,
560
+ input.entry.relPath
561
+ ),
562
+ "listRecordDocuments"
563
+ );
564
+ const sourceDocument =
565
+ input.preloadedSourceDocument !== undefined
566
+ ? input.preloadedSourceDocument
567
+ : mustOk(
568
+ await input.store.getDocument(
569
+ input.collection.name,
570
+ input.entry.relPath
571
+ ),
572
+ "getDocument"
573
+ );
523
574
  const priorByKey = new Map(
524
575
  priorDocuments
525
576
  .filter((document) => document.recordKey)
@@ -540,6 +591,7 @@ export async function processRecordContainer(
540
591
  );
541
592
 
542
593
  let changed = false;
594
+ const deactivatePaths: string[] = [];
543
595
  for (const action of plan.actions) {
544
596
  if (
545
597
  action.type === "add" ||
@@ -549,6 +601,7 @@ export async function processRecordContainer(
549
601
  await persistRecord(
550
602
  input,
551
603
  action.record,
604
+ virtualPathPrefix,
552
605
  priorByKey.get(action.record.recordKey),
553
606
  false
554
607
  );
@@ -562,33 +615,41 @@ export async function processRecordContainer(
562
615
  existing.contentTypeRulesFingerprint !==
563
616
  input.contentTypeRulesFingerprint;
564
617
  if (projectionChanged) {
565
- await persistRecord(input, action.record, existing, false);
618
+ await persistRecord(
619
+ input,
620
+ action.record,
621
+ virtualPathPrefix,
622
+ existing,
623
+ false
624
+ );
566
625
  changed = true;
567
626
  } else if (
568
627
  existing &&
569
628
  recordProvenanceChanged(input, action.record, existing)
570
629
  ) {
571
- await persistRecord(input, action.record, existing, false, false);
630
+ await persistRecord(
631
+ input,
632
+ action.record,
633
+ virtualPathPrefix,
634
+ existing,
635
+ false,
636
+ false
637
+ );
572
638
  changed = true;
573
639
  }
574
640
  continue;
575
641
  }
576
642
  if (action.type === "deactivate") {
577
- const result = mustOk(
578
- await input.store.markInactive(input.collection.name, [
579
- action.previous.relativePath,
580
- ]),
581
- "markInactive"
582
- );
583
- changed ||= result > 0;
643
+ deactivatePaths.push(action.previous.relativePath);
584
644
  }
585
645
  }
586
646
 
587
647
  if (sourceDocument?.active && snapshot.authoritative) {
648
+ deactivatePaths.push(input.entry.relPath);
649
+ }
650
+ if (deactivatePaths.length > 0) {
588
651
  const result = mustOk(
589
- await input.store.markInactive(input.collection.name, [
590
- input.entry.relPath,
591
- ]),
652
+ await input.store.markInactive(input.collection.name, deactivatePaths),
592
653
  "markInactive"
593
654
  );
594
655
  changed ||= result > 0;
@@ -607,10 +668,17 @@ export async function processRecordContainer(
607
668
  "reconcileRecordSnapshot"
608
669
  )
609
670
  : await reconcileAndApply();
610
- const actionCount = (
611
- type: (typeof applied.plan.actions)[number]["type"]
612
- ): number =>
613
- applied.plan.actions.filter((action) => action.type === type).length;
671
+ const actionCounts = {
672
+ add: 0,
673
+ update: 0,
674
+ reactivate: 0,
675
+ unchanged: 0,
676
+ deactivate: 0,
677
+ preserve: 0,
678
+ };
679
+ for (const action of applied.plan.actions) {
680
+ actionCounts[action.type] += 1;
681
+ }
614
682
  const receiptItems = applied.plan.actions
615
683
  .map((action): RecordImportItemReceipt => {
616
684
  const record = "record" in action ? action.record : undefined;
@@ -674,12 +742,12 @@ export async function processRecordContainer(
674
742
  sourceBytesRead: snapshot.sourceBytesRead,
675
743
  records: {
676
744
  accepted: snapshot.records.length,
677
- added: actionCount("add"),
678
- updated: actionCount("update"),
679
- reactivated: actionCount("reactivate"),
680
- unchanged: actionCount("unchanged"),
681
- deactivated: actionCount("deactivate"),
682
- preserved: actionCount("preserve"),
745
+ added: actionCounts.add,
746
+ updated: actionCounts.update,
747
+ reactivated: actionCounts.reactivate,
748
+ unchanged: actionCounts.unchanged,
749
+ deactivated: actionCounts.deactivate,
750
+ preserved: actionCounts.preserve,
683
751
  failed: snapshot.failures.length,
684
752
  },
685
753
  items: boundedReceiptItems,
@@ -3,12 +3,15 @@ const RECORD_VIRTUAL_ROOT = ".gno/records";
3
3
  const sha256 = (value: string): string =>
4
4
  new Bun.CryptoHasher("sha256").update(value).digest("hex");
5
5
 
6
+ /** Precomputed virtual path prefix for one container source path. */
7
+ export const recordVirtualPathPrefix = (sourcePath: string): string =>
8
+ `${RECORD_VIRTUAL_ROOT}/${sha256(sourcePath).slice(0, 16)}/`;
9
+
6
10
  /** Stable internal path for one logical record inside an export container. */
7
11
  export const recordVirtualPath = (
8
12
  sourcePath: string,
9
13
  recordKey: string
10
- ): string =>
11
- `${RECORD_VIRTUAL_ROOT}/${sha256(sourcePath).slice(0, 16)}/${recordKey}.md`;
14
+ ): string => `${recordVirtualPathPrefix(sourcePath)}${recordKey}.md`;
12
15
 
13
16
  /** Physical files may never occupy GNO's virtual-record namespace. */
14
17
  export const isRecordVirtualPath = (relativePath: string): boolean => {
@@ -176,6 +176,14 @@ export function loadDarwinIo(): DarwinIoBundle | null {
176
176
  }
177
177
  const { symbols } = loaded;
178
178
  const readErrno = (): number => readErrnoFrom(symbols);
179
+ // Reuse one 144-byte stat buffer + DataView across synchronous lstat calls.
180
+ const statBuf = new Uint8Array(DARWIN_STAT_BUF_SIZE);
181
+ const statPtr = ptr(statBuf);
182
+ const statView = new DataView(
183
+ statBuf.buffer,
184
+ statBuf.byteOffset,
185
+ statBuf.byteLength
186
+ );
179
187
  cachedBundle = {
180
188
  policy: {
181
189
  get: symbols.getiopolicy_np,
@@ -192,16 +200,11 @@ export function loadDarwinIo(): DarwinIoBundle | null {
192
200
  },
193
201
  stat: {
194
202
  lstatFlags: (absPath: string) => {
195
- const buf = new Uint8Array(DARWIN_STAT_BUF_SIZE);
196
- const rc = symbols.lstat(ptr(cstr(absPath)), ptr(buf));
203
+ const rc = symbols.lstat(ptr(cstr(absPath)), statPtr);
197
204
  if (rc !== 0) {
198
205
  return { ok: false as const, errno: readErrno() };
199
206
  }
200
- const stFlags = new DataView(
201
- buf.buffer,
202
- buf.byteOffset,
203
- buf.byteLength
204
- ).getUint32(DARWIN_ST_FLAGS_OFFSET, true);
207
+ const stFlags = statView.getUint32(DARWIN_ST_FLAGS_OFFSET, true);
205
208
  return { ok: true as const, stFlags };
206
209
  },
207
210
  },
@@ -17,14 +17,32 @@ export type DarwinFileProviderPathSupport =
17
17
  | "unsupported"
18
18
  | "unknown";
19
19
 
20
+ let cachedHomeRaw: string | undefined;
21
+ let cachedHomeResolved: string | undefined;
22
+
23
+ function resolveHomeDir(home?: string): string {
24
+ const raw = home ?? homedir();
25
+ if (raw === cachedHomeRaw && cachedHomeResolved !== undefined) {
26
+ return cachedHomeResolved;
27
+ }
28
+ const resolved = resolve(raw);
29
+ if (home === undefined) {
30
+ cachedHomeRaw = raw;
31
+ cachedHomeResolved = resolved;
32
+ }
33
+ return resolved;
34
+ }
35
+
20
36
  export function classifyDarwinFileProviderPath(
21
37
  absPath: string,
22
- home: string = homedir()
38
+ home?: string
23
39
  ): DarwinFileProviderPathSupport {
24
- if (!isAbsolute(absPath) || !isAbsolute(home)) {
40
+ const homeRaw = home ?? homedir();
41
+ if (!isAbsolute(absPath) || !isAbsolute(homeRaw)) {
25
42
  return "unknown";
26
43
  }
27
- const relativeHomePath = relative(resolve(home), resolve(absPath));
44
+ const resolvedHome = home === undefined ? resolveHomeDir() : resolve(homeRaw);
45
+ const relativeHomePath = relative(resolvedHome, resolve(absPath));
28
46
  if (
29
47
  relativeHomePath === ".." ||
30
48
  relativeHomePath.startsWith(`..${sep}`) ||
@@ -173,6 +173,8 @@ export class LocalSourceContentReader implements SourceContentReaderPort {
173
173
  }
174
174
  }
175
175
 
176
+ const MAX_PREALLOC_BYTES = 16 * 1024 * 1024;
177
+
176
178
  function readAllNative(
177
179
  absPath: string,
178
180
  file: DarwinFileIoPort,
@@ -183,6 +185,55 @@ function readAllNative(
183
185
  return mapErrno(file.readErrno(), 0);
184
186
  }
185
187
  try {
188
+ // Fast path: preallocate exact buffer when expectedSize is known and bounded
189
+ // to avoid per-chunk slice copies and concatChunks reallocation.
190
+ if (
191
+ expectedSize !== undefined &&
192
+ expectedSize > 0 &&
193
+ expectedSize <= MAX_PREALLOC_BYTES
194
+ ) {
195
+ const prealloc = new Uint8Array(expectedSize);
196
+ let total = 0;
197
+ while (total < expectedSize) {
198
+ const n = file.read(fd, prealloc.subarray(total));
199
+ if (n < 0) {
200
+ return mapErrno(file.readErrno(), total);
201
+ }
202
+ if (n === 0) {
203
+ return {
204
+ ok: false,
205
+ code: "IO_ERROR",
206
+ message: sourceAvailabilityMessage(
207
+ "IO_ERROR",
208
+ `short_read expected=${expectedSize} read=${total}`
209
+ ),
210
+ };
211
+ }
212
+ total += n;
213
+ }
214
+ // Probe once for EOF or trailing bytes if the file grew after stat().
215
+ const overflowBuf = new Uint8Array(READ_CHUNK_BYTES);
216
+ const extra = file.read(fd, overflowBuf);
217
+ if (extra < 0) {
218
+ return mapErrno(file.readErrno(), total);
219
+ }
220
+ if (extra === 0) {
221
+ return { ok: true, bytes: prealloc };
222
+ }
223
+ const chunks: Uint8Array[] = [prealloc, overflowBuf.slice(0, extra)];
224
+ total += extra;
225
+ for (;;) {
226
+ const n = file.read(fd, overflowBuf);
227
+ if (n < 0) {
228
+ return mapErrno(file.readErrno(), total);
229
+ }
230
+ if (n === 0) break;
231
+ chunks.push(overflowBuf.slice(0, n));
232
+ total += n;
233
+ }
234
+ return { ok: true, bytes: concatChunks(chunks, total) };
235
+ }
236
+
186
237
  const chunks: Uint8Array[] = [];
187
238
  let total = 0;
188
239
  const buf = new Uint8Array(READ_CHUNK_BYTES);