@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
@@ -29,8 +29,6 @@ import type {
29
29
  } from "./types";
30
30
 
31
31
  import { fingerprintContentTypeMetadataRules } from "../config";
32
- import { createJsonlAdapter } from "../converters/adapters/jsonl/adapter";
33
- import { createTranscriptAdapter } from "../converters/adapters/transcript/adapter";
34
32
  import { getDefaultMimeDetector, type MimeDetector } from "../converters/mime";
35
33
  import { markdownConverter } from "../converters/native/markdown";
36
34
  import {
@@ -101,6 +99,29 @@ interface FileBudget extends FileBudgetLimits {
101
99
  startedAt: number;
102
100
  }
103
101
 
102
+ interface ConfiguredRecordAdapters {
103
+ transcript?: RecordAdapter;
104
+ jsonl?: RecordAdapter;
105
+ }
106
+
107
+ interface ProcessFileContext {
108
+ configuredRecordAdapters?: ConfiguredRecordAdapters;
109
+ preloaded?: {
110
+ existing: DocumentRow | null;
111
+ priorRecordDocuments: DocumentRow[];
112
+ };
113
+ preloadedStat?: {
114
+ sourceSize: number;
115
+ sourceMtime: string;
116
+ sourceCtime: string;
117
+ };
118
+ }
119
+
120
+ type PreparedFileSync =
121
+ | { kind: "done"; result: FileSyncResult }
122
+ | { kind: "write"; persist: () => Promise<FileSyncResult> }
123
+ | { kind: "record-container"; run: () => Promise<FileSyncResult> };
124
+
104
125
  /** A file still being indexed this long (or half its budget) is reported. */
105
126
  export const SLOW_CONVERSION_NOTICE_MS = 10_000;
106
127
  const BYTES_PER_MB = 1_048_576;
@@ -456,21 +477,36 @@ export class SyncService {
456
477
  ((mode) => createDirectoryAvailability(mode));
457
478
  }
458
479
 
459
- private async selectRecordAdapter(
460
- collection: Collection,
461
- mime: string,
462
- ext: string
463
- ): Promise<RecordAdapter | undefined> {
480
+ private async resolveConfiguredRecordAdapters(
481
+ collection: Collection
482
+ ): Promise<ConfiguredRecordAdapters> {
464
483
  const transcriptConfig = collection.recordAdapters?.transcript;
484
+ const jsonlConfig = collection.recordAdapters?.jsonl;
485
+ if (!transcriptConfig && !jsonlConfig) return {};
486
+ const resolved: ConfiguredRecordAdapters = {};
465
487
  if (transcriptConfig) {
466
- const adapter = createTranscriptAdapter(transcriptConfig);
467
- if (adapter.canHandle(mime, ext)) return adapter;
488
+ const { createTranscriptAdapter } =
489
+ await import("../converters/adapters/transcript/adapter");
490
+ resolved.transcript = createTranscriptAdapter(transcriptConfig);
468
491
  }
469
- const jsonlConfig = collection.recordAdapters?.jsonl;
470
492
  if (jsonlConfig) {
471
- const adapter = createJsonlAdapter(jsonlConfig.fieldMapping);
472
- if (adapter.canHandle(mime, ext)) return adapter;
493
+ const { createJsonlAdapter } =
494
+ await import("../converters/adapters/jsonl/adapter");
495
+ resolved.jsonl = createJsonlAdapter(jsonlConfig.fieldMapping);
473
496
  }
497
+ return resolved;
498
+ }
499
+
500
+ private async selectRecordAdapter(
501
+ collection: Collection,
502
+ mime: string,
503
+ ext: string,
504
+ configured?: ConfiguredRecordAdapters
505
+ ): Promise<RecordAdapter | undefined> {
506
+ const adapters =
507
+ configured ?? (await this.resolveConfiguredRecordAdapters(collection));
508
+ if (adapters.transcript?.canHandle(mime, ext)) return adapters.transcript;
509
+ if (adapters.jsonl?.canHandle(mime, ext)) return adapters.jsonl;
474
510
  const selectDefault = (
475
511
  this.pipeline as ConversionPipeline & {
476
512
  selectRecordAdapter?: ConversionPipeline["selectRecordAdapter"];
@@ -480,17 +516,68 @@ export class SyncService {
480
516
  return selectDefault.call(this.pipeline, mime, ext);
481
517
  }
482
518
 
519
+ private async recordUnexpectedFileError(
520
+ collection: Collection,
521
+ entry: WalkEntry,
522
+ store: StorePort,
523
+ error: unknown
524
+ ): Promise<FileSyncResult> {
525
+ const message = error instanceof Error ? error.message : "Unknown error";
526
+ // Distinguish store errors from other internal errors
527
+ const isStoreError =
528
+ message.startsWith("Store operation failed:") ||
529
+ (error instanceof Error &&
530
+ (error as Error & { context?: unknown }).context !== undefined);
531
+ const code = isStoreError ? "STORE_ERROR" : "INTERNAL";
532
+
533
+ // Record internal error to store (best-effort)
534
+ try {
535
+ await store.recordError({
536
+ collection: collection.name,
537
+ relPath: entry.relPath,
538
+ code,
539
+ message,
540
+ details: {
541
+ stack: error instanceof Error ? error.stack : undefined,
542
+ },
543
+ });
544
+
545
+ // Also update document with error info if it exists
546
+ const existingResult = await store.getDocument(
547
+ collection.name,
548
+ entry.relPath
549
+ );
550
+ if (existingResult.ok && existingResult.value?.active) {
551
+ await store.upsertDocument(
552
+ preserveDocumentWithError(existingResult.value, code, message)
553
+ );
554
+ }
555
+ } catch {
556
+ // Best-effort error recording
557
+ }
558
+
559
+ return {
560
+ relPath: entry.relPath,
561
+ status: "error",
562
+ errorCode: code,
563
+ errorMessage: message,
564
+ };
565
+ }
566
+
483
567
  /**
484
- * Process a single file through the ingestion pipeline.
485
- * All store operations are checked and errors are propagated.
568
+ * Prepare a single file outside any SQLite write transaction, returning either
569
+ * a completed no-write result or a `persist` closure that writes to the store.
570
+ * Record containers manage their own streaming + single transaction and return
571
+ * `kind: "done"` once committed.
486
572
  */
487
573
  // oxlint-disable-next-line max-lines-per-function -- file processing with multiple extraction paths
488
- private async processFile(
574
+ private async prepareFileForSync(
489
575
  collection: Collection,
490
576
  entry: WalkEntry,
491
577
  store: StorePort,
492
- options: SyncOptions
493
- ): Promise<FileSyncResult> {
578
+ options: SyncOptions,
579
+ context?: ProcessFileContext
580
+ ): Promise<PreparedFileSync> {
494
581
  const generatedResult: FileSyncResult = {
495
582
  relPath: entry.relPath,
496
583
  status: "skipped",
@@ -498,7 +585,9 @@ export class SyncService {
498
585
  errorMessage:
499
586
  "Compiled context is derived material; index original sources instead",
500
587
  };
501
- if (isCompiledContextPath(entry.relPath)) return generatedResult;
588
+ if (isCompiledContextPath(entry.relPath)) {
589
+ return { kind: "done", result: generatedResult };
590
+ }
502
591
  tracePhase(`sync: file ${entry.relPath}`);
503
592
  const limits = {
504
593
  maxBytes: options.limits?.maxBytes ?? DEFAULT_LIMITS.maxBytes,
@@ -510,50 +599,68 @@ export class SyncService {
510
599
 
511
600
  try {
512
601
  // 1. Re-stat before read to enforce maxBytes on current file size
602
+ // unless syncPaths just statted the canonical path.
513
603
  let sourceSize = entry.size;
514
604
  let sourceMtime = entry.mtime;
515
605
  let sourceCtime = entry.ctime;
516
- try {
517
- const sourceStat = await stat(entry.absPath);
518
- if (!sourceStat.isFile()) {
606
+ if (context?.preloadedStat) {
607
+ sourceSize = context.preloadedStat.sourceSize;
608
+ sourceMtime = context.preloadedStat.sourceMtime;
609
+ sourceCtime = context.preloadedStat.sourceCtime;
610
+ } else {
611
+ try {
612
+ const sourceStat = await stat(entry.absPath);
613
+ if (!sourceStat.isFile()) {
614
+ return {
615
+ kind: "done",
616
+ result: {
617
+ relPath: entry.relPath,
618
+ status: "error",
619
+ errorCode: "NOT_FILE",
620
+ errorMessage: "Path is not a file",
621
+ },
622
+ };
623
+ }
624
+ sourceSize = sourceStat.size;
625
+ sourceMtime = sourceStat.mtime.toISOString();
626
+ sourceCtime = (
627
+ sourceStat.birthtime ??
628
+ sourceStat.ctime ??
629
+ sourceStat.mtime
630
+ ).toISOString();
631
+ } catch {
519
632
  return {
520
- relPath: entry.relPath,
521
- status: "error",
522
- errorCode: "NOT_FILE",
523
- errorMessage: "Path is not a file",
633
+ kind: "done",
634
+ result: {
635
+ relPath: entry.relPath,
636
+ status: "error",
637
+ errorCode: "NOT_FOUND",
638
+ errorMessage: "File not found",
639
+ },
524
640
  };
525
641
  }
526
- sourceSize = sourceStat.size;
527
- sourceMtime = sourceStat.mtime.toISOString();
528
- sourceCtime = (
529
- sourceStat.birthtime ??
530
- sourceStat.ctime ??
531
- sourceStat.mtime
532
- ).toISOString();
533
- } catch {
534
- return {
535
- relPath: entry.relPath,
536
- status: "error",
537
- errorCode: "NOT_FOUND",
538
- errorMessage: "File not found",
539
- };
540
642
  }
541
643
 
542
644
  if (sourceSize > limits.maxBytes) {
543
645
  const message = `File size ${sourceSize} exceeds limit ${limits.maxBytes}`;
544
- await store
545
- .recordError({
546
- collection: collection.name,
547
- relPath: entry.relPath,
548
- code: "TOO_LARGE",
549
- message,
550
- })
551
- .catch(() => undefined);
552
646
  return {
553
- relPath: entry.relPath,
554
- status: "skipped",
555
- errorCode: "TOO_LARGE",
556
- errorMessage: message,
647
+ kind: "write",
648
+ persist: async () => {
649
+ await store
650
+ .recordError({
651
+ collection: collection.name,
652
+ relPath: entry.relPath,
653
+ code: "TOO_LARGE",
654
+ message,
655
+ })
656
+ .catch(() => undefined);
657
+ return {
658
+ relPath: entry.relPath,
659
+ status: "skipped",
660
+ errorCode: "TOO_LARGE",
661
+ errorMessage: message,
662
+ };
663
+ },
557
664
  };
558
665
  }
559
666
 
@@ -564,7 +671,8 @@ export class SyncService {
564
671
  const recordAdapter = await this.selectRecordAdapter(
565
672
  collection,
566
673
  extensionMime.mime,
567
- extensionMime.ext
674
+ extensionMime.ext,
675
+ context?.configuredRecordAdapters
568
676
  );
569
677
  tracePhase("sync: record adapter selected");
570
678
  const contentTypeRules = options.contentTypeRules ?? [];
@@ -572,9 +680,9 @@ export class SyncService {
572
680
  options.contentTypeRulesFingerprint ??
573
681
  fingerprintContentTypeMetadataRules(contentTypeRules);
574
682
 
575
- // 2. Local mode performs one guarded content-boundary read. `any` keeps
576
- // the legacy record-stream and sniff/read paths byte-for-byte unchanged.
577
- // No availability syscall is added during discovery.
683
+ // 2. Local mode performs one guarded content-boundary read. In `any` mode,
684
+ // record containers keep streaming reads (4 KiB prefix slice + stream),
685
+ // while regular files perform a single full read and slice views from it.
578
686
  const availabilityMode = resolveSourceAvailability(collection, options);
579
687
  let guardedBytes: Uint8Array | undefined;
580
688
  if (availabilityMode === "local") {
@@ -583,54 +691,82 @@ export class SyncService {
583
691
  sourceSize
584
692
  );
585
693
  if (!sourceRead.ok) {
586
- return await this.finishSourceAvailabilityFailure(
587
- collection,
588
- entry,
589
- store,
590
- sourceRead
591
- );
694
+ return {
695
+ kind: "write",
696
+ persist: () =>
697
+ this.finishSourceAvailabilityFailure(
698
+ collection,
699
+ entry,
700
+ store,
701
+ sourceRead
702
+ ),
703
+ };
592
704
  }
593
705
  guardedBytes = sourceRead.bytes;
594
706
  }
595
707
 
596
- const generatedPrefix =
597
- guardedBytes?.subarray(0, 4096) ??
598
- new Uint8Array(
599
- await Bun.file(entry.absPath).slice(0, 4096).arrayBuffer()
600
- );
601
- if (isCompiledContextContent(generatedPrefix)) return generatedResult;
602
-
603
708
  if (recordAdapter) {
604
- return await processRecordContainer({
605
- adapter: recordAdapter,
606
- chunker: this.chunker,
607
- collection,
608
- contentTypeRules,
609
- contentTypeRulesFingerprint,
610
- entry,
611
- ext: extensionMime.ext,
612
- extractMetadata: extractDocumentMetadata,
613
- ingestVersion: INGEST_VERSION,
614
- mime: extensionMime.mime,
615
- options,
616
- sourceCtime,
617
- sourceMtime,
618
- sourceSize,
619
- sourceBytes: guardedBytes,
620
- store,
621
- });
709
+ const generatedPrefix =
710
+ guardedBytes?.subarray(0, 4096) ??
711
+ new Uint8Array(
712
+ await Bun.file(entry.absPath).slice(0, 4096).arrayBuffer()
713
+ );
714
+ if (isCompiledContextContent(generatedPrefix)) {
715
+ return { kind: "done", result: generatedResult };
716
+ }
717
+ return {
718
+ kind: "record-container",
719
+ run: async () => {
720
+ try {
721
+ return await processRecordContainer({
722
+ adapter: recordAdapter,
723
+ chunker: this.chunker,
724
+ collection,
725
+ contentTypeRules,
726
+ contentTypeRulesFingerprint,
727
+ entry,
728
+ ext: extensionMime.ext,
729
+ extractMetadata: extractDocumentMetadata,
730
+ ingestVersion: INGEST_VERSION,
731
+ mime: extensionMime.mime,
732
+ options,
733
+ sourceCtime,
734
+ sourceMtime,
735
+ sourceSize,
736
+ sourceBytes: guardedBytes,
737
+ preloadedPriorDocuments:
738
+ context?.preloaded?.priorRecordDocuments,
739
+ preloadedSourceDocument: context?.preloaded?.existing,
740
+ store,
741
+ });
742
+ } catch (error) {
743
+ return await this.recordUnexpectedFileError(
744
+ collection,
745
+ entry,
746
+ store,
747
+ error
748
+ );
749
+ }
750
+ },
751
+ };
752
+ }
753
+
754
+ const bytes = guardedBytes ?? (await Bun.file(entry.absPath).bytes());
755
+ const generatedPrefix = bytes.subarray(0, 4096);
756
+ if (isCompiledContextContent(generatedPrefix)) {
757
+ return { kind: "done", result: generatedResult };
622
758
  }
623
759
 
624
760
  const sniffBytes = generatedPrefix.subarray(0, 512);
625
761
  const mime = this.mimeDetector.detect(entry.relPath, sniffBytes);
626
762
 
627
- const priorRecordDocuments = mustOk(
628
- await store.listRecordDocuments(collection.name, entry.relPath),
629
- "listRecordDocuments",
630
- { collection: collection.name, relPath: entry.relPath }
631
- );
632
-
633
- const bytes = guardedBytes ?? (await Bun.file(entry.absPath).bytes());
763
+ const priorRecordDocuments =
764
+ context?.preloaded?.priorRecordDocuments ??
765
+ mustOk(
766
+ await store.listRecordDocuments(collection.name, entry.relPath),
767
+ "listRecordDocuments",
768
+ { collection: collection.name, relPath: entry.relPath }
769
+ );
634
770
 
635
771
  // 3. Compute sourceHash from source bytes. Local mode cannot reopen.
636
772
  const hasher = new Bun.CryptoHasher("sha256");
@@ -638,13 +774,18 @@ export class SyncService {
638
774
  const sourceHash = hasher.digest("hex");
639
775
 
640
776
  // 4. Check existing doc for skip/repair decision
641
- const existingResult = await store.getDocument(
642
- collection.name,
643
- entry.relPath
644
- );
645
- const existing = existingResult.ok ? existingResult.value : null;
777
+ let resolvedExisting: DocumentRow | null;
778
+ if (context?.preloaded !== undefined) {
779
+ resolvedExisting = context.preloaded.existing;
780
+ } else {
781
+ const existingResult = await store.getDocument(
782
+ collection.name,
783
+ entry.relPath
784
+ );
785
+ resolvedExisting = existingResult.ok ? existingResult.value : null;
786
+ }
646
787
  const decision = decideAction(
647
- existing,
788
+ resolvedExisting,
648
789
  sourceHash,
649
790
  contentTypeRulesFingerprint
650
791
  );
@@ -654,14 +795,31 @@ export class SyncService {
654
795
  .filter((document) => document.active)
655
796
  .map((document) => document.relPath);
656
797
  if (activeRecordPaths.length > 0) {
657
- mustOk(
658
- await store.markInactive(collection.name, activeRecordPaths),
659
- "markInactive",
660
- { collection: collection.name, relPath: entry.relPath }
661
- );
662
- return { relPath: entry.relPath, status: "updated" };
798
+ return {
799
+ kind: "write",
800
+ persist: async () => {
801
+ try {
802
+ mustOk(
803
+ await store.markInactive(collection.name, activeRecordPaths),
804
+ "markInactive",
805
+ { collection: collection.name, relPath: entry.relPath }
806
+ );
807
+ return { relPath: entry.relPath, status: "updated" };
808
+ } catch (error) {
809
+ return await this.recordUnexpectedFileError(
810
+ collection,
811
+ entry,
812
+ store,
813
+ error
814
+ );
815
+ }
816
+ },
817
+ };
663
818
  }
664
- return { relPath: entry.relPath, status: "unchanged" };
819
+ return {
820
+ kind: "done",
821
+ result: { relPath: entry.relPath, status: "unchanged" },
822
+ };
665
823
  }
666
824
 
667
825
  // 6. Prepare the file (convert, then everything CPU-bound before the
@@ -673,74 +831,83 @@ export class SyncService {
673
831
  failure: PrepareFailure,
674
832
  previousStructure: DocumentStructureSnapshot | null | undefined
675
833
  ): Promise<FileSyncResult> => {
676
- // Record error (checked)
677
- const errorInput: IngestErrorInput = {
678
- collection: collection.name,
679
- relPath: entry.relPath,
680
- code: failure.code,
681
- message: failure.message,
682
- details: failure.details,
683
- };
684
- const recordResult = await store.recordError(errorInput);
685
- if (!recordResult.ok) {
686
- // Log but continue - error recording is best-effort
687
- }
834
+ try {
835
+ // Record error (checked)
836
+ const errorInput: IngestErrorInput = {
837
+ collection: collection.name,
838
+ relPath: entry.relPath,
839
+ code: failure.code,
840
+ message: failure.message,
841
+ details: failure.details,
842
+ };
843
+ const recordResult = await store.recordError(errorInput);
844
+ if (!recordResult.ok) {
845
+ // Log but continue - error recording is best-effort
846
+ }
688
847
 
689
- const hadRetrievableEvidence = Boolean(existing?.mirrorHash);
690
- const structureDelta = hadRetrievableEvidence
691
- ? diffDocumentStructure(previousStructure, {
692
- headings: [],
693
- links: [],
694
- typedEdges: [],
695
- dates: {},
696
- }).delta
697
- : undefined;
698
-
699
- // Upsert document with error info, explicitly clear mirrorHash. This
700
- // transition is journaled only when retrievable evidence previously
701
- // existed; initial/repeated error placeholders are not evidence
702
- // creates. Real evidence disappearance stays in the same transaction
703
- // so saved Capsule freshness checks cannot miss it.
704
- const upsertResult = await store.upsertDocument({
705
- collection: collection.name,
706
- relPath: entry.relPath,
707
- sourceHash,
708
- sourceMime: mime.mime,
709
- sourceExt: mime.ext,
710
- sourceSize,
711
- sourceMtime,
712
- sourceCtime,
713
- lastErrorCode: failure.code,
714
- lastErrorMessage: failure.message,
715
- ingestVersion: INGEST_VERSION,
716
- contentTypeRulesFingerprint,
717
- changeJournal: structureDelta ? { structureDelta } : false,
718
- // mirrorHash intentionally omitted (will be null)
719
- });
848
+ const hadRetrievableEvidence = Boolean(resolvedExisting?.mirrorHash);
849
+ const structureDelta = hadRetrievableEvidence
850
+ ? diffDocumentStructure(previousStructure, {
851
+ headings: [],
852
+ links: [],
853
+ typedEdges: [],
854
+ dates: {},
855
+ }).delta
856
+ : undefined;
857
+
858
+ // Upsert document with error info, explicitly clear mirrorHash. This
859
+ // transition is journaled only when retrievable evidence previously
860
+ // existed; initial/repeated error placeholders are not evidence
861
+ // creates. Real evidence disappearance stays in the same transaction
862
+ // so saved Capsule freshness checks cannot miss it.
863
+ const upsertResult = await store.upsertDocument({
864
+ collection: collection.name,
865
+ relPath: entry.relPath,
866
+ sourceHash,
867
+ sourceMime: mime.mime,
868
+ sourceExt: mime.ext,
869
+ sourceSize,
870
+ sourceMtime,
871
+ sourceCtime,
872
+ lastErrorCode: failure.code,
873
+ lastErrorMessage: failure.message,
874
+ ingestVersion: INGEST_VERSION,
875
+ contentTypeRulesFingerprint,
876
+ changeJournal: structureDelta ? { structureDelta } : false,
877
+ // mirrorHash intentionally omitted (will be null)
878
+ });
879
+
880
+ if (!upsertResult.ok) {
881
+ return {
882
+ relPath: entry.relPath,
883
+ status: "error",
884
+ errorCode: "STORE_ERROR",
885
+ errorMessage: upsertResult.error.message,
886
+ };
887
+ }
720
888
 
721
- if (!upsertResult.ok) {
722
889
  return {
723
890
  relPath: entry.relPath,
724
891
  status: "error",
725
- errorCode: "STORE_ERROR",
726
- errorMessage: upsertResult.error.message,
892
+ errorCode: failure.code,
893
+ errorMessage: failure.message,
727
894
  };
895
+ } catch (error) {
896
+ return await this.recordUnexpectedFileError(
897
+ collection,
898
+ entry,
899
+ store,
900
+ error
901
+ );
728
902
  }
729
-
730
- return {
731
- relPath: entry.relPath,
732
- status: "error",
733
- errorCode: failure.code,
734
- errorMessage: failure.message,
735
- };
736
903
  };
737
904
 
738
905
  // No previous revision: null (a new document). A previous revision whose
739
906
  // structure was not computed before a stop: undefined (history
740
907
  // unavailable), as for a missing mirror.
741
908
  let previousStructure: DocumentStructureSnapshot | null | undefined =
742
- existing ? undefined : null;
743
- const previous = await this.readPreviousRevision(store, existing);
909
+ resolvedExisting ? undefined : null;
910
+ const previous = await this.readPreviousRevision(store, resolvedExisting);
744
911
  tracePhase("sync: preparing file");
745
912
  const prepared = await this.prepare(
746
913
  {
@@ -777,10 +944,15 @@ export class SyncService {
777
944
  budget
778
945
  );
779
946
  },
947
+ // Sync never reads `bytes` again after hashing above.
948
+ transferInputBytes: true,
780
949
  }
781
950
  );
782
951
  if (!prepared.ok) {
783
- return await recordFailure(prepared.error, previousStructure);
952
+ return {
953
+ kind: "write",
954
+ persist: () => recordFailure(prepared.error, previousStructure),
955
+ };
784
956
  }
785
957
  const {
786
958
  artifact,
@@ -902,7 +1074,9 @@ export class SyncService {
902
1074
  }
903
1075
 
904
1076
  const status =
905
- existing || priorRecordDocuments.length > 0 ? "updated" : "added";
1077
+ resolvedExisting || priorRecordDocuments.length > 0
1078
+ ? "updated"
1079
+ : "added";
906
1080
  return {
907
1081
  relPath: entry.relPath,
908
1082
  status,
@@ -912,60 +1086,66 @@ export class SyncService {
912
1086
  contentTypeSource: extractedMetadata.contentTypeSource,
913
1087
  };
914
1088
  };
915
- if (!store.withTransaction) {
916
- return await persistSuccessfulFile();
917
- }
918
- const persisted = await store.withTransaction(persistSuccessfulFile);
919
- return mustOk(persisted, "persistSuccessfulFile", {
920
- collection: collection.name,
921
- relPath: entry.relPath,
922
- });
923
- } catch (error) {
924
- const message = error instanceof Error ? error.message : "Unknown error";
925
- // Distinguish store errors from other internal errors
926
- const isStoreError =
927
- message.startsWith("Store operation failed:") ||
928
- (error instanceof Error &&
929
- (error as Error & { context?: unknown }).context !== undefined);
930
- const code = isStoreError ? "STORE_ERROR" : "INTERNAL";
931
-
932
- // Record internal error to store (best-effort)
933
- try {
934
- await store.recordError({
935
- collection: collection.name,
936
- relPath: entry.relPath,
937
- code,
938
- message,
939
- details: {
940
- stack: error instanceof Error ? error.stack : undefined,
941
- },
942
- });
943
-
944
- // Also update document with error info if it exists
945
- const existingResult = await store.getDocument(
946
- collection.name,
947
- entry.relPath
948
- );
949
- if (existingResult.ok && existingResult.value?.active) {
950
- await store.upsertDocument(
951
- preserveDocumentWithError(existingResult.value, code, message)
952
- );
953
- }
954
- } catch {
955
- // Best-effort error recording
956
- }
957
1089
 
958
1090
  return {
959
- relPath: entry.relPath,
960
- status: "error",
961
- errorCode: code,
962
- errorMessage: message,
1091
+ kind: "write",
1092
+ persist: async () => {
1093
+ try {
1094
+ if (!store.withTransaction) {
1095
+ return await persistSuccessfulFile();
1096
+ }
1097
+ // Per-file transaction/savepoint rolls back partial document/journal
1098
+ // writes atomically if a downstream write (content/chunks/tags/links) fails.
1099
+ const persisted = await store.withTransaction(
1100
+ persistSuccessfulFile
1101
+ );
1102
+ return mustOk(persisted, "persistSuccessfulFile", {
1103
+ collection: collection.name,
1104
+ relPath: entry.relPath,
1105
+ });
1106
+ } catch (error) {
1107
+ return await this.recordUnexpectedFileError(
1108
+ collection,
1109
+ entry,
1110
+ store,
1111
+ error
1112
+ );
1113
+ }
1114
+ },
1115
+ };
1116
+ } catch (error) {
1117
+ return {
1118
+ kind: "write",
1119
+ persist: () =>
1120
+ this.recordUnexpectedFileError(collection, entry, store, error),
963
1121
  };
964
1122
  } finally {
965
1123
  clearTimeout(slowNotice);
966
1124
  }
967
1125
  }
968
1126
 
1127
+ /**
1128
+ * Process a single file through the ingestion pipeline.
1129
+ */
1130
+ private async processFile(
1131
+ collection: Collection,
1132
+ entry: WalkEntry,
1133
+ store: StorePort,
1134
+ options: SyncOptions,
1135
+ context?: ProcessFileContext
1136
+ ): Promise<FileSyncResult> {
1137
+ const prepared = await this.prepareFileForSync(
1138
+ collection,
1139
+ entry,
1140
+ store,
1141
+ options,
1142
+ context
1143
+ );
1144
+ if (prepared.kind === "done") return prepared.result;
1145
+ if (prepared.kind === "record-container") return await prepared.run();
1146
+ return await prepared.persist();
1147
+ }
1148
+
969
1149
  /**
970
1150
  * Translate guarded-read failures into skip (cloud placeholder/partial) or
971
1151
  * fail-closed error outcomes. Never surfaces materialization refusal as a
@@ -1046,7 +1226,10 @@ export class SyncService {
1046
1226
  private prepare(
1047
1227
  request: PrepareFileRequest,
1048
1228
  budget: FileBudget,
1049
- hooks: Required<FileProcessorHooks>
1229
+ hooks: FileProcessorHooks & {
1230
+ onPrevious: NonNullable<FileProcessorHooks["onPrevious"]>;
1231
+ onStarted: NonNullable<FileProcessorHooks["onStarted"]>;
1232
+ }
1050
1233
  ): Promise<PrepareOutcome> {
1051
1234
  if (this.defaultPreparation) {
1052
1235
  return prepareInProcessor(request, budget, hooks);
@@ -1177,34 +1360,16 @@ export class SyncService {
1177
1360
  const directoryAvailability = memoizeDirectoryAvailability(
1178
1361
  this.directoryAvailabilityFactory(availabilityMode)
1179
1362
  );
1363
+ const configuredRecordAdapters =
1364
+ await this.resolveConfiguredRecordAdapters(collection);
1365
+ let cachedCollectionRoot: string | undefined;
1180
1366
  let rootUnavailable: string | null = null;
1181
1367
 
1182
- for (const relPath of relPaths) {
1183
- const recordDocumentsResult = await store.listRecordDocuments(
1184
- collection.name,
1185
- relPath
1186
- );
1187
- if (!recordDocumentsResult.ok) {
1188
- results.push({
1189
- relPath,
1190
- status: "error",
1191
- errorCode: recordDocumentsResult.error.code,
1192
- errorMessage: recordDocumentsResult.error.message,
1193
- });
1194
- continue;
1195
- }
1196
- const recordDocuments = recordDocumentsResult.value;
1197
- const existingResult = await store.getDocument(collection.name, relPath);
1198
- if (!existingResult.ok) {
1199
- results.push({
1200
- relPath,
1201
- status: "error",
1202
- errorCode: existingResult.error.code,
1203
- errorMessage: existingResult.error.message,
1204
- });
1205
- continue;
1206
- }
1207
- const existingDoc = existingResult.value;
1368
+ const collectPreWriteSources = async (
1369
+ relPath: string,
1370
+ existingDoc: DocumentRow | null,
1371
+ recordDocuments: DocumentRow[]
1372
+ ): Promise<FileSyncResult | null> => {
1208
1373
  if (existingDoc) {
1209
1374
  const collectError = await this.collectProjectionSourceIds(
1210
1375
  store,
@@ -1212,16 +1377,14 @@ export class SyncService {
1212
1377
  projectionSourceIds
1213
1378
  );
1214
1379
  if (collectError) {
1215
- results.push({
1380
+ return {
1216
1381
  relPath,
1217
1382
  status: "error",
1218
1383
  errorCode: collectError.code,
1219
1384
  errorMessage: collectError.message,
1220
- });
1221
- continue;
1385
+ };
1222
1386
  }
1223
1387
  }
1224
- let recordCollectFailed: FileSyncResult | null = null;
1225
1388
  for (const recordDocument of recordDocuments) {
1226
1389
  const collectError = await this.collectProjectionSourceIds(
1227
1390
  store,
@@ -1229,19 +1392,43 @@ export class SyncService {
1229
1392
  projectionSourceIds
1230
1393
  );
1231
1394
  if (collectError) {
1232
- recordCollectFailed = {
1395
+ return {
1233
1396
  relPath,
1234
1397
  status: "error",
1235
1398
  errorCode: collectError.code,
1236
1399
  errorMessage: collectError.message,
1237
1400
  };
1238
- break;
1239
1401
  }
1240
1402
  }
1241
- if (recordCollectFailed) {
1242
- results.push(recordCollectFailed);
1403
+ return null;
1404
+ };
1405
+
1406
+ for (const relPath of relPaths) {
1407
+ const recordDocumentsResult = await store.listRecordDocuments(
1408
+ collection.name,
1409
+ relPath
1410
+ );
1411
+ if (!recordDocumentsResult.ok) {
1412
+ results.push({
1413
+ relPath,
1414
+ status: "error",
1415
+ errorCode: recordDocumentsResult.error.code,
1416
+ errorMessage: recordDocumentsResult.error.message,
1417
+ });
1243
1418
  continue;
1244
1419
  }
1420
+ const recordDocuments = recordDocumentsResult.value;
1421
+ const existingResult = await store.getDocument(collection.name, relPath);
1422
+ if (!existingResult.ok) {
1423
+ results.push({
1424
+ relPath,
1425
+ status: "error",
1426
+ errorCode: existingResult.error.code,
1427
+ errorMessage: existingResult.error.message,
1428
+ });
1429
+ continue;
1430
+ }
1431
+ const existingDoc = existingResult.value;
1245
1432
 
1246
1433
  // Direct syncPaths must not bypass directory-availability guards.
1247
1434
  const unprovenPrefix = await findUnprovenAvailabilityPrefix(
@@ -1302,6 +1489,15 @@ export class SyncService {
1302
1489
  });
1303
1490
  continue;
1304
1491
  }
1492
+ const preCollectFailed = await collectPreWriteSources(
1493
+ relPath,
1494
+ existingDoc,
1495
+ recordDocuments
1496
+ );
1497
+ if (preCollectFailed) {
1498
+ results.push(preCollectFailed);
1499
+ continue;
1500
+ }
1305
1501
  const inactive = await this.inactivateOneAbsentSource(
1306
1502
  collection,
1307
1503
  store,
@@ -1326,11 +1522,11 @@ export class SyncService {
1326
1522
 
1327
1523
  let canonicalSourcePath: string;
1328
1524
  try {
1329
- const [collectionRoot, sourcePath] = await Promise.all([
1330
- realpath(collection.path),
1331
- realpath(absPath),
1332
- ]);
1333
- const sourceRelative = relative(collectionRoot, sourcePath);
1525
+ if (cachedCollectionRoot === undefined) {
1526
+ cachedCollectionRoot = await realpath(collection.path);
1527
+ }
1528
+ const sourcePath = await realpath(absPath);
1529
+ const sourceRelative = relative(cachedCollectionRoot, sourcePath);
1334
1530
  if (
1335
1531
  sourceRelative === ".." ||
1336
1532
  sourceRelative.startsWith(`..${sep}`) ||
@@ -1355,36 +1551,90 @@ export class SyncService {
1355
1551
  continue;
1356
1552
  }
1357
1553
 
1554
+ const sourceMtime = stats.mtime.toISOString();
1555
+ const sourceCtime = (
1556
+ stats.birthtime ??
1557
+ stats.ctime ??
1558
+ stats.mtime
1559
+ ).toISOString();
1358
1560
  const entry: WalkEntry = {
1359
1561
  absPath: canonicalSourcePath,
1360
1562
  relPath,
1361
1563
  size: stats.size,
1362
- mtime: stats.mtime.toISOString(),
1363
- ctime: (stats.birthtime ?? stats.ctime ?? stats.mtime).toISOString(),
1564
+ mtime: sourceMtime,
1565
+ ctime: sourceCtime,
1364
1566
  };
1365
1567
 
1366
- const result = await this.processFile(
1568
+ const preparedFile = await this.prepareFileForSync(
1367
1569
  collection,
1368
1570
  entry,
1369
1571
  store,
1370
- syncOptions
1572
+ syncOptions,
1573
+ {
1574
+ configuredRecordAdapters,
1575
+ preloaded: {
1576
+ existing: existingDoc,
1577
+ priorRecordDocuments: recordDocuments,
1578
+ },
1579
+ preloadedStat: {
1580
+ sourceSize: stats.size,
1581
+ sourceMtime,
1582
+ sourceCtime,
1583
+ },
1584
+ }
1371
1585
  );
1372
- if (result.errorCode === "GENERATED_CONTEXT") {
1373
- const inactive = await this.inactivateOneAbsentSource(
1374
- collection,
1375
- store,
1376
- relPath,
1377
- projectionSourceIds,
1378
- { existingDoc, recordDocuments }
1379
- );
1380
- markedInactive += inactive.markedInactive;
1381
- results.push(
1382
- inactive.result.status === "error" ? inactive.result : result
1383
- );
1586
+ if (preparedFile.kind === "done") {
1587
+ const result = preparedFile.result;
1588
+ if (result.errorCode === "GENERATED_CONTEXT") {
1589
+ const preCollectFailed = await collectPreWriteSources(
1590
+ relPath,
1591
+ existingDoc,
1592
+ recordDocuments
1593
+ );
1594
+ if (preCollectFailed) {
1595
+ results.push(preCollectFailed);
1596
+ continue;
1597
+ }
1598
+ const inactive = await this.inactivateOneAbsentSource(
1599
+ collection,
1600
+ store,
1601
+ relPath,
1602
+ projectionSourceIds,
1603
+ { existingDoc, recordDocuments }
1604
+ );
1605
+ markedInactive += inactive.markedInactive;
1606
+ results.push(
1607
+ inactive.result.status === "error" ? inactive.result : result
1608
+ );
1609
+ continue;
1610
+ }
1611
+ // Unchanged (or read-only NOT_FILE/NOT_FOUND): skip backlink & post-write queries.
1612
+ results.push(result);
1384
1613
  continue;
1385
1614
  }
1615
+
1616
+ // Collect pre-write projection sources BEFORE persisting any change so a
1617
+ // backlink lookup failure never leaves a committed partial update.
1618
+ const preCollectFailed = await collectPreWriteSources(
1619
+ relPath,
1620
+ existingDoc,
1621
+ recordDocuments
1622
+ );
1623
+ if (preCollectFailed) {
1624
+ results.push(preCollectFailed);
1625
+ continue;
1626
+ }
1627
+
1628
+ const result =
1629
+ preparedFile.kind === "record-container"
1630
+ ? await preparedFile.run()
1631
+ : await preparedFile.persist();
1386
1632
  results.push(result);
1387
- if (result.status === "error" || result.status === "skipped") {
1633
+ if (
1634
+ result.status === "unchanged" ||
1635
+ result.status === "error" ||
1636
+ result.status === "skipped"
1637
+ ) {
1388
1638
  continue;
1389
1639
  }
1390
1640
  // Post-write projection identity must succeed so typed-edge cleanup can run.
@@ -1812,143 +2062,199 @@ export class SyncService {
1812
2062
  }
1813
2063
  }
1814
2064
 
1815
- // 4. Process files with bounded concurrency
2065
+ // 4. Preload collection documents once (eliminates 2N per-file lookups) and
2066
+ // decouple CPU/IO preparation from batched SQLite commit transactions.
2067
+ const configuredRecordAdapters =
2068
+ await this.resolveConfiguredRecordAdapters(collection);
2069
+ const existingDocsResult = await store.listDocuments(collection.name);
2070
+ let docByRelPath: Map<string, DocumentRow> | undefined;
2071
+ let recordsBySourcePath: Map<string, DocumentRow[]> | undefined;
2072
+ if (existingDocsResult.ok) {
2073
+ docByRelPath = new Map<string, DocumentRow>();
2074
+ recordsBySourcePath = new Map<string, DocumentRow[]>();
2075
+ for (const document of existingDocsResult.value) {
2076
+ docByRelPath.set(document.relPath, document);
2077
+ if (document.recordSourcePath) {
2078
+ let list = recordsBySourcePath.get(document.recordSourcePath);
2079
+ if (!list) {
2080
+ list = [];
2081
+ recordsBySourcePath.set(document.recordSourcePath, list);
2082
+ }
2083
+ list.push(document);
2084
+ }
2085
+ }
2086
+ }
2087
+
2088
+ const recordFileResult = (
2089
+ entry: WalkEntry,
2090
+ result: FileSyncResult
2091
+ ): void => {
2092
+ if (result.errorCode === "GENERATED_CONTEXT") {
2093
+ seenPaths.delete(entry.relPath);
2094
+ }
2095
+ fileResults.push(result);
2096
+ switch (result.status) {
2097
+ case "added":
2098
+ added += 1;
2099
+ break;
2100
+ case "updated":
2101
+ updated += 1;
2102
+ break;
2103
+ case "unchanged":
2104
+ unchanged += 1;
2105
+ break;
2106
+ case "error":
2107
+ errored += 1;
2108
+ if (result.errorCode && result.errorMessage) {
2109
+ errors.push({
2110
+ relPath: result.relPath,
2111
+ code: result.errorCode,
2112
+ message: result.errorMessage,
2113
+ });
2114
+ }
2115
+ break;
2116
+ case "skipped":
2117
+ dynamicSkipped += 1;
2118
+ if (result.errorCode && result.errorMessage) {
2119
+ errors.push({
2120
+ relPath: result.relPath,
2121
+ code: result.errorCode,
2122
+ message: result.errorMessage,
2123
+ });
2124
+ }
2125
+ break;
2126
+ }
2127
+ };
2128
+
2129
+ const buildContext = (entry: WalkEntry): ProcessFileContext => ({
2130
+ configuredRecordAdapters,
2131
+ ...(docByRelPath && recordsBySourcePath
2132
+ ? {
2133
+ preloaded: {
2134
+ existing: docByRelPath.get(entry.relPath) ?? null,
2135
+ priorRecordDocuments:
2136
+ recordsBySourcePath.get(entry.relPath) ?? [],
2137
+ },
2138
+ }
2139
+ : {}),
2140
+ });
2141
+
1816
2142
  const concurrency = Math.max(
1817
2143
  1,
1818
2144
  Math.min(MAX_CONCURRENCY, options.concurrency ?? DEFAULT_CONCURRENCY)
1819
2145
  );
1820
- if (concurrency === 1) {
1821
- // Sequential processing with batched transactions (Windows perf)
1822
- for (let i = 0; i < entries.length; i += TX_BATCH_SIZE) {
1823
- const batch = entries.slice(i, i + TX_BATCH_SIZE);
1824
-
1825
- const runBatch = async (): Promise<void> => {
1826
- for (const entry of batch) {
1827
- seenPaths.add(entry.relPath);
1828
- const result = await this.processFile(
1829
- collection,
1830
- entry,
1831
- store,
1832
- syncOptions
1833
- );
1834
- if (result.errorCode === "GENERATED_CONTEXT")
1835
- seenPaths.delete(entry.relPath);
1836
- fileResults.push(result);
1837
- switch (result.status) {
1838
- case "added":
1839
- added += 1;
1840
- break;
1841
- case "updated":
1842
- updated += 1;
1843
- break;
1844
- case "unchanged":
1845
- unchanged += 1;
1846
- break;
1847
- case "error":
1848
- errored += 1;
1849
- if (result.errorCode && result.errorMessage) {
1850
- errors.push({
1851
- relPath: result.relPath,
1852
- code: result.errorCode,
1853
- message: result.errorMessage,
1854
- });
1855
- }
1856
- break;
1857
- case "skipped":
1858
- dynamicSkipped += 1;
1859
- if (result.errorCode && result.errorMessage) {
1860
- errors.push({
1861
- relPath: result.relPath,
1862
- code: result.errorCode,
1863
- message: result.errorMessage,
1864
- });
1865
- }
1866
- break;
2146
+ const semaphore = concurrency > 1 ? new Semaphore(concurrency) : undefined;
2147
+
2148
+ for (let i = 0; i < entries.length; i += TX_BATCH_SIZE) {
2149
+ const batch = entries.slice(i, i + TX_BATCH_SIZE);
2150
+ for (const entry of batch) {
2151
+ seenPaths.add(entry.relPath);
2152
+ }
2153
+
2154
+ // Prepare batch outside any SQLite write transaction (sequentially or
2155
+ // with bounded concurrency), preserving deterministic `batch` order.
2156
+ // Record containers run their own streaming + single transaction outside
2157
+ // the batch BEGIN IMMEDIATE so they never hold a write lock while parsing.
2158
+ const prepareBatchEntry = async (
2159
+ entry: WalkEntry
2160
+ ): Promise<PreparedFileSync> => {
2161
+ const item = await this.prepareFileForSync(
2162
+ collection,
2163
+ entry,
2164
+ store,
2165
+ syncOptions,
2166
+ buildContext(entry)
2167
+ );
2168
+ if (item.kind === "record-container") {
2169
+ return { kind: "done", result: await item.run() };
2170
+ }
2171
+ return item;
2172
+ };
2173
+ let preparedBatch: PreparedFileSync[];
2174
+ if (!semaphore) {
2175
+ preparedBatch = [];
2176
+ for (const entry of batch) {
2177
+ preparedBatch.push(await prepareBatchEntry(entry));
2178
+ }
2179
+ } else {
2180
+ preparedBatch = await Promise.all(
2181
+ batch.map(async (entry) => {
2182
+ await semaphore.acquire();
2183
+ try {
2184
+ return await prepareBatchEntry(entry);
2185
+ } finally {
2186
+ semaphore.release();
1867
2187
  }
1868
- }
1869
- };
2188
+ })
2189
+ );
2190
+ }
1870
2191
 
1871
- // Wrap batch in single transaction when supported (reduces commits)
1872
- if (store.withTransaction) {
1873
- const txResult = await store.withTransaction(runBatch);
1874
- if (!txResult.ok) {
1875
- errors.push({
1876
- relPath: "(transaction batch)",
1877
- code: txResult.error.code,
1878
- message: txResult.error.message,
1879
- });
1880
- break; // Abort on transaction failure
1881
- }
1882
- } else {
1883
- await runBatch();
2192
+ let hasWrites = false;
2193
+ for (const item of preparedBatch) {
2194
+ if (item.kind === "write") {
2195
+ hasWrites = true;
2196
+ break;
1884
2197
  }
1885
2198
  }
1886
- } else {
1887
- // Concurrent processing with semaphore
1888
- const semaphore = new Semaphore(concurrency);
1889
- const results: FileSyncResult[] = [];
1890
-
1891
- await Promise.all(
1892
- entries.map(async (entry) => {
1893
- seenPaths.add(entry.relPath);
1894
- await semaphore.acquire();
1895
- try {
1896
- const result = await this.processFile(
1897
- collection,
1898
- entry,
1899
- store,
1900
- syncOptions
1901
- );
1902
- if (result.errorCode === "GENERATED_CONTEXT")
1903
- seenPaths.delete(entry.relPath);
1904
- fileResults.push(result);
1905
- results.push(result);
1906
- } finally {
1907
- semaphore.release();
2199
+
2200
+ if (!hasWrites) {
2201
+ for (let idx = 0; idx < batch.length; idx += 1) {
2202
+ const item = preparedBatch[idx];
2203
+ const entry = batch[idx];
2204
+ if (item && item.kind === "done" && entry) {
2205
+ recordFileResult(entry, item.result);
1908
2206
  }
1909
- })
1910
- );
2207
+ }
2208
+ continue;
2209
+ }
1911
2210
 
1912
- // Aggregate results
1913
- for (const result of results) {
1914
- switch (result.status) {
1915
- case "added":
1916
- added += 1;
1917
- break;
1918
- case "updated":
1919
- updated += 1;
1920
- break;
1921
- case "unchanged":
1922
- unchanged += 1;
1923
- break;
1924
- case "error":
1925
- errored += 1;
1926
- if (result.errorCode && result.errorMessage) {
1927
- errors.push({
1928
- relPath: result.relPath,
1929
- code: result.errorCode,
1930
- message: result.errorMessage,
1931
- });
1932
- }
1933
- break;
1934
- case "skipped":
1935
- dynamicSkipped += 1;
1936
- if (result.errorCode && result.errorMessage) {
1937
- errors.push({
1938
- relPath: result.relPath,
1939
- code: result.errorCode,
1940
- message: result.errorMessage,
1941
- });
1942
- }
1943
- break;
2211
+ const commitBatch = async (): Promise<FileSyncResult[]> => {
2212
+ const batchResults: FileSyncResult[] = [];
2213
+ for (let idx = 0; idx < batch.length; idx += 1) {
2214
+ const item = preparedBatch[idx];
2215
+ if (!item) continue;
2216
+ const result =
2217
+ item.kind === "done"
2218
+ ? item.result
2219
+ : item.kind === "record-container"
2220
+ ? await item.run()
2221
+ : await item.persist();
2222
+ batchResults.push(result);
2223
+ }
2224
+ return batchResults;
2225
+ };
2226
+
2227
+ if (store.withTransaction) {
2228
+ const txResult = await store.withTransaction(commitBatch);
2229
+ if (!txResult.ok) {
2230
+ errors.push({
2231
+ relPath: "(transaction batch)",
2232
+ code: txResult.error.code,
2233
+ message: txResult.error.message,
2234
+ });
2235
+ break; // Abort on transaction failure
2236
+ }
2237
+ for (let idx = 0; idx < batch.length; idx += 1) {
2238
+ const entry = batch[idx];
2239
+ const result = txResult.value[idx];
2240
+ if (entry && result) recordFileResult(entry, result);
2241
+ }
2242
+ } else {
2243
+ const batchResults = await commitBatch();
2244
+ for (let idx = 0; idx < batch.length; idx += 1) {
2245
+ const entry = batch[idx];
2246
+ const result = batchResults[idx];
2247
+ if (entry && result) recordFileResult(entry, result);
1944
2248
  }
1945
2249
  }
1946
2250
  }
1947
2251
 
1948
2252
  // 5. Mark missing files as inactive (inventory failures are hard errors).
2253
+ // Reuses the preloaded collection inventory from step 4 (every file
2254
+ // added/updated in step 4 has its sourcePath in seenPaths unless it was
2255
+ // a compiled-context path that must be inactivated).
1949
2256
  let markedInactive = 0;
1950
2257
  let inventoryErrored = 0;
1951
- const existingDocsResult = await store.listDocuments(collection.name);
1952
2258
  if (!existingDocsResult.ok) {
1953
2259
  inventoryErrored += 1;
1954
2260
  errors.push({