@vrtmrz/livesync-commonlib 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +4 -0
  2. package/dist/common/models/diff.definition.d.ts +4 -0
  3. package/dist/common/utils.d.ts +1 -1
  4. package/dist/common/utils.doc.d.ts +5 -0
  5. package/dist/common/utils.doc.js +8 -0
  6. package/dist/common/utils.js +1 -3
  7. package/dist/conflicts/filenameCaseConflict.d.ts +8 -0
  8. package/dist/conflicts/filenameCaseConflict.js +26 -0
  9. package/dist/conflicts.d.ts +1 -0
  10. package/dist/conflicts.js +9 -1
  11. package/dist/interfaces/DatabaseFileAccess.d.ts +12 -1
  12. package/dist/interfaces/FileReflectionProvenance.js +1 -0
  13. package/dist/interfaces/KeyValueDatabase.d.ts +1 -1
  14. package/dist/managers/ConflictManager.d.ts +6 -2
  15. package/dist/managers/ConflictManager.js +73 -22
  16. package/dist/managers/EntryManager/EntryManager.d.ts +5 -0
  17. package/dist/managers/EntryManager/EntryManager.js +5 -0
  18. package/dist/managers/EntryManager/EntryManagerImpls.d.ts +5 -1
  19. package/dist/managers/EntryManager/EntryManagerImpls.js +92 -6
  20. package/dist/managers/LiveSyncManagers.js +2 -1
  21. package/dist/managers/StorageEventManager/admission.d.ts +15 -3
  22. package/dist/managers/StorageEventManager/admission.js +13 -3
  23. package/dist/managers/StorageEventManager/processing.d.ts +2 -2
  24. package/dist/managers/StorageEventManager/processing.js +3 -3
  25. package/dist/managers/StorageEventManager/queue.d.ts +23 -14
  26. package/dist/managers/StorageEventManager/queue.js +70 -30
  27. package/dist/managers/StorageEventManager/snapshot.d.ts +12 -1
  28. package/dist/managers/StorageEventManager/snapshot.js +74 -0
  29. package/dist/managers/StorageEventManager/state.d.ts +27 -5
  30. package/dist/managers/StorageEventManager/state.js +9 -7
  31. package/dist/managers/StorageEventManager.d.ts +6 -0
  32. package/dist/managers/StorageEventManager.js +135 -18
  33. package/dist/managers/adapters/IStorageEventManagerAdapter.d.ts +3 -1
  34. package/dist/managers/adapters/IStorageEventPersistenceAdapter.d.ts +16 -0
  35. package/dist/managers/adapters/index.d.ts +1 -1
  36. package/dist/pouchdb/LiveSyncLocalDB.js +3 -4
  37. package/dist/replication/index.d.ts +2 -0
  38. package/dist/replication/index.js +2 -0
  39. package/dist/replication/replicationResultQueueStore.d.ts +101 -0
  40. package/dist/replication/replicationResultQueueStore.js +140 -0
  41. package/dist/serviceFeatures/offlineScanner/files.js +15 -3
  42. package/dist/serviceFeatures/offlineScanner/scan.js +1 -4
  43. package/dist/serviceModules/ServiceDatabaseFileAccessBase.d.ts +5 -4
  44. package/dist/serviceModules/ServiceDatabaseFileAccessBase.js +28 -7
  45. package/dist/serviceModules/ServiceFileHandlerBase/protection.d.ts +8 -2
  46. package/dist/serviceModules/ServiceFileHandlerBase/protection.js +52 -9
  47. package/dist/serviceModules/ServiceFileHandlerBase/provenance.d.ts +30 -0
  48. package/dist/serviceModules/ServiceFileHandlerBase/provenance.js +82 -10
  49. package/dist/serviceModules/ServiceFileHandlerBase/reflection.js +118 -12
  50. package/dist/serviceModules/ServiceFileHandlerBase/saving.js +32 -8
  51. package/dist/serviceModules/ServiceFileHandlerBase/storage.d.ts +2 -8
  52. package/dist/serviceModules/ServiceFileHandlerBase/storage.js +4 -5
  53. package/dist/services/base/KeyValueDBService.d.ts +6 -6
  54. package/dist/worker/WorkerPushStreamProducer.d.ts +45 -0
  55. package/dist/worker/WorkerPushStreamProducer.js +299 -0
  56. package/dist/worker/WorkerPushStreamReader.d.ts +28 -0
  57. package/dist/worker/WorkerPushStreamReader.js +179 -0
  58. package/dist/worker/backgroundWorkerRpcContract.d.ts +18 -0
  59. package/dist/worker/backgroundWorkerRpcContract.js +24 -0
  60. package/dist/worker/bg.worker.js +2 -16
  61. package/dist/worker/bg.worker.splitting.d.ts +3 -7
  62. package/dist/worker/bg.worker.splitting.js +46 -47
  63. package/dist/worker/bgWorker.d.ts +8 -14
  64. package/dist/worker/bgWorker.direct.d.ts +5 -28
  65. package/dist/worker/bgWorker.direct.js +32 -2
  66. package/dist/worker/bgWorker.errors.d.ts +1 -0
  67. package/dist/worker/bgWorker.errors.js +12 -0
  68. package/dist/worker/bgWorker.js +716 -296
  69. package/dist/worker/bgWorker.splitting.d.ts +12 -26
  70. package/dist/worker/bgWorker.splitting.js +115 -107
  71. package/dist/worker/outOfBandCancelIterator.d.ts +2 -0
  72. package/dist/worker/outOfBandCancelIterator.js +8 -0
  73. package/dist/worker/serveBackgroundWorker.d.ts +3 -0
  74. package/dist/worker/serveBackgroundWorker.js +35 -0
  75. package/dist/worker/splitConnectionTracker.d.ts +25 -0
  76. package/dist/worker/splitConnectionTracker.js +73 -0
  77. package/dist/worker/splitGate.d.ts +19 -0
  78. package/dist/worker/splitGate.js +71 -0
  79. package/dist/worker/universalTypes.d.ts +0 -30
  80. package/dist/worker/universalTypes.js +0 -4
  81. package/dist/worker/workerPushStreamProtocol.d.ts +68 -0
  82. package/dist/worker/workerPushStreamProtocol.js +143 -0
  83. package/docs/conflict-resolution.md +22 -8
  84. package/docs/development.md +6 -0
  85. package/docs/offline-scanner.md +2 -0
  86. package/docs/storage-events-and-reflection.md +171 -2
  87. package/package.json +1 -1
  88. package/dist/worker/bg.common.d.ts +0 -2
  89. package/dist/worker/bg.common.js +0 -6
  90. package/dist/worker/bg.worker.encryption.d.ts +0 -7
  91. package/dist/worker/bg.worker.encryption.js +0 -30
  92. package/dist/worker/bgWorker.encryption.d.ts +0 -22
  93. package/dist/worker/bgWorker.encryption.js +0 -40
@@ -6,7 +6,7 @@ import {
6
6
  LOG_LEVEL_NOTICE,
7
7
  LOG_LEVEL_VERBOSE
8
8
  } from "../../common/types.js";
9
- import { compareMTime } from "../../common/utils.js";
9
+ import { compareMTime, isDeletedEntry } from "../../common/utils.js";
10
10
  import { BASE_IS_NEW, EVEN, TARGET_IS_NEW } from "../../common/models/shared.const.symbols.js";
11
11
  import { stripAllPrefixes } from "../../string_and_binary/path.js";
12
12
  import { VaultScanResults } from "../../services/base/VaultScanResult.js";
@@ -32,9 +32,6 @@ import {
32
32
  ExtraOnRemote,
33
33
  FilePairProcessResults
34
34
  } from "./types.js";
35
- function isDeletedEntry(entry) {
36
- return entry.deleted || entry._deleted || false;
37
- }
38
35
  function getFilePairState(pair) {
39
36
  const { file, doc } = pair;
40
37
  if (file && doc) {
@@ -1,5 +1,5 @@
1
- import type { UXFileInfoStub, FilePathWithPrefix, UXFileInfo, MetaEntry, LoadedEntry, FilePath } from "../common/types.js";
2
- import type { DatabaseFileAccess } from "../interfaces/DatabaseFileAccess.js";
1
+ import type { UXFileInfoStub, FilePathWithPrefix, UXFileInfo, DocumentID, MetaEntry, LoadedEntry, FilePath } from "../common/types.js";
2
+ import type { DatabaseFileAccess, LiveContentFilename } from "../interfaces/DatabaseFileAccess.js";
3
3
  import type { StorageAccess } from "../interfaces/StorageAccess.js";
4
4
  import type { APIService } from "../services/base/APIService.js";
5
5
  import type { DatabaseService } from "../services/base/DatabaseService.js";
@@ -64,16 +64,17 @@ export declare class ServiceDatabaseFileAccessBase extends ServiceModuleBase<Ser
64
64
  * A read failure yields no confirmed match. Callers decide whether the result identifies a
65
65
  * unique origin; this method does not mutate provenance or hold the revision tree stable.
66
66
  */
67
- findLiveContentRevisions(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer): Promise<string[]>;
67
+ findLiveContentRevisions(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer, filename?: LiveContentFilename): Promise<string[]>;
68
68
  /** Select current live leaves, independently of historical ancestor lookup. */
69
69
  private selectLiveContentLeaves;
70
70
  /** Compare selected leaves using local Chunks only; unreadable content rejects. */
71
- readLiveContentRevisions(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer): Promise<string[]>;
71
+ readLiveContentRevisions(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer, filename?: LiveContentFilename): Promise<string[]>;
72
72
  hasContentInRevisionHistory(file: UXFileInfoStub | FilePathWithPrefix, content: string | string[] | Blob | ArrayBuffer, currentRev?: string): Promise<boolean>;
73
73
  getConflictedRevs(file: UXFileInfoStub | FilePathWithPrefix): Promise<string[]>;
74
74
  readConflictedRevs(file: UXFileInfoStub | FilePathWithPrefix): Promise<string[]>;
75
75
  fetch(file: UXFileInfoStub | FilePathWithPrefix, rev?: string, waitForReady?: boolean, skipCheck?: boolean): Promise<UXFileInfo | false>;
76
76
  fetchEntryMeta(file: UXFileInfoStub | FilePathWithPrefix, rev?: string, skipCheck?: boolean): Promise<MetaEntry | false>;
77
+ readRevisionPath(documentId: DocumentID, revision: string): Promise<string | undefined>;
77
78
  readEntryMeta(file: UXFileInfoStub | FilePathWithPrefix, rev?: string, skipCheck?: boolean): Promise<MetaEntry | false>;
78
79
  fetchEntryFromMeta(meta: MetaEntry, waitForReady?: boolean, skipCheck?: boolean, localOnly?: boolean): Promise<LoadedEntry | false>;
79
80
  readEntryFromMeta(meta: MetaEntry, waitForReady?: boolean, skipCheck?: boolean, localOnly?: boolean): Promise<LoadedEntry | false>;
@@ -7,6 +7,9 @@ import { EVENT_FILE_SAVED } from "../events/coreEvents.js";
7
7
  import { getDatabasePathFromUXFileInfo, getStoragePathFromUXFileInfo, isInternalMetadata } from "../common/typeUtils.js";
8
8
  import { createBlob, createTextBlob, determineTypeFromBlob, isDocContentSame, readContent } from "../common/utils.js";
9
9
  import { ICHeader } from "../common/models/fileaccess.const.js";
10
+ import { isDeletedEntry, tryGetFilePath } from "../common/utils.doc.js";
11
+ import { haveMatchingRevisionPaths } from "../conflicts/filenameCaseConflict.js";
12
+ import { isErrorOfMissingDoc } from "../pouchdb/utils_couchdb.js";
10
13
  class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
11
14
  events;
12
15
  vault;
@@ -349,16 +352,16 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
349
352
  * A read failure yields no confirmed match. Callers decide whether the result identifies a
350
353
  * unique origin; this method does not mutate provenance or hold the revision tree stable.
351
354
  */
352
- async findLiveContentRevisions(file, content) {
355
+ async findLiveContentRevisions(file, content, filename) {
353
356
  try {
354
- return await this.readLiveContentRevisions(file, content);
357
+ return await this.readLiveContentRevisions(file, content, filename);
355
358
  } catch (error) {
356
359
  this._log(error, LOG_LEVEL_VERBOSE);
357
360
  return [];
358
361
  }
359
362
  }
360
363
  /** Select current live leaves, independently of historical ancestor lookup. */
361
- async selectLiveContentLeaves(file) {
364
+ async selectLiveContentLeaves(file, filenameFilter) {
362
365
  const filename = getDatabasePathFromUXFileInfo(file);
363
366
  const current = await this.readEntryMeta(file, void 0, true);
364
367
  if (!current) {
@@ -379,14 +382,22 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
379
382
  cause: new Error(`Invalid live revision response for ${filename}`)
380
383
  });
381
384
  }
382
- return leaves.flatMap(({ ok }) => ok?._rev && !ok.deleted && !ok._deleted ? [ok._rev] : []);
385
+ return leaves.flatMap(({ ok }) => {
386
+ if (!ok?._rev || isDeletedEntry(ok)) {
387
+ return [];
388
+ }
389
+ if (filenameFilter && !haveMatchingRevisionPaths(tryGetFilePath(ok), filenameFilter.path, filenameFilter.normalizationVersion)) {
390
+ return [];
391
+ }
392
+ return [ok._rev];
393
+ });
383
394
  }
384
395
  /** Compare selected leaves using local Chunks only; unreadable content rejects. */
385
- async readLiveContentRevisions(file, content) {
396
+ async readLiveContentRevisions(file, content, filename) {
386
397
  if (!await this.checkIsTargetFile(file)) {
387
398
  return [];
388
399
  }
389
- const revisions = await this.selectLiveContentLeaves(file);
400
+ const revisions = await this.selectLiveContentLeaves(file, filename);
390
401
  const matches = [];
391
402
  for (const revision of revisions) {
392
403
  const entry = await this.database.localDatabase.readDBEntry(
@@ -397,7 +408,7 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
397
408
  true,
398
409
  true
399
410
  );
400
- if (entry && !entry.deleted && !entry._deleted && await isDocContentSame(readContent(entry), content)) {
411
+ if (entry && !isDeletedEntry(entry) && await isDocContentSame(readContent(entry), content)) {
401
412
  matches.push(revision);
402
413
  }
403
414
  }
@@ -450,6 +461,16 @@ class ServiceDatabaseFileAccessBase extends ServiceModuleBase {
450
461
  async fetchEntryMeta(file, rev, skipCheck = false) {
451
462
  return await this.readEntryMeta(file, rev, skipCheck);
452
463
  }
464
+ async readRevisionPath(documentId, revision) {
465
+ try {
466
+ return tryGetFilePath(await this.database.localDatabase.getRaw(documentId, { rev: revision }));
467
+ } catch (error) {
468
+ if (isErrorOfMissingDoc(error)) {
469
+ return void 0;
470
+ }
471
+ throw new ContentReadError({ documentId, revision, resources: ["local-database"], cause: error });
472
+ }
473
+ }
453
474
  async readEntryMeta(file, rev, skipCheck = false) {
454
475
  const filename = getDatabasePathFromUXFileInfo(file);
455
476
  if (skipCheck && !await this.checkIsTargetFile(file)) {
@@ -1,5 +1,8 @@
1
1
  import type { FilePathWithPrefix, MetaEntry, UXFileInfoStub } from "../../common/types.js";
2
2
  import type { FileHandlerContext, PreservationResult } from "./context.js";
3
+ import type { FileReflectionProvenanceRecord } from "../../interfaces/FileReflectionProvenance.js";
4
+ /** Decoded incoming file body supplied for live-write protection (absent for deletions). */
5
+ type IncomingContent = string | string[] | Blob | ArrayBuffer;
3
6
  /**
4
7
  * Preserve changed storage before an incoming write can replace its bytes.
5
8
  *
@@ -11,7 +14,9 @@ import type { FileHandlerContext, PreservationResult } from "./context.js";
11
14
  * @returns A PreservationResult: preserved:true stops the incoming effect; preserved:false without a snapshot means no safe candidate was established.
12
15
  * @remarks The caller holds the document lock. preserved:true also covers a refused preservation write that must still stop overwrite; any returned snapshot requires later revalidation.
13
16
  */
14
- export declare function preserveUnsyncedStorageAsConflict(ctx: FileHandlerContext, path: FilePathWithPrefix, existDoc: UXFileInfoStub, incomingEntry: MetaEntry, incomingContent?: string | string[] | Blob | ArrayBuffer): Promise<PreservationResult>;
17
+ export declare function preserveUnsyncedStorageAsConflict(ctx: FileHandlerContext, path: FilePathWithPrefix, existDoc: UXFileInfoStub, incomingEntry: MetaEntry, incomingContent?: IncomingContent): Promise<PreservationResult>;
18
+ /** Preserve an unobserved filename and its bytes before an incoming rename. */
19
+ export declare function preserveUnobservedFilename(ctx: FileHandlerContext, path: FilePathWithPrefix, existDoc: UXFileInfoStub, observedProvenance: FileReflectionProvenanceRecord | undefined): Promise<PreservationResult>;
15
20
  /**
16
21
  * Repeat overwrite protection after a previous storage observation became stale.
17
22
  *
@@ -23,4 +28,5 @@ export declare function preserveUnsyncedStorageAsConflict(ctx: FileHandlerContex
23
28
  * @returns A PreservationResult that either stops the incoming effect or supplies a candidate; missing evidence can leave preserved:false without a snapshot.
24
29
  * @remarks The caller holds the document lock. This does not authorise overwrite; callers must validate any candidate at the established final check.
25
30
  */
26
- export declare function recheckIncomingStorage(ctx: FileHandlerContext, path: FilePathWithPrefix, incomingEntry: MetaEntry, incomingContent: string | string[] | Blob | ArrayBuffer | undefined, allowExistingConflicts: boolean): Promise<PreservationResult>;
31
+ export declare function recheckIncomingStorage(ctx: FileHandlerContext, path: FilePathWithPrefix, incomingEntry: MetaEntry, incomingContent: IncomingContent | undefined, allowExistingConflicts: boolean): Promise<PreservationResult>;
32
+ export {};
@@ -1,8 +1,10 @@
1
1
  import { ContentReadError } from "../../common/LSError.js";
2
2
  import {
3
+ getProvenancePath,
3
4
  readProvenanceSnapshot,
4
5
  currentStorageSnapshotMatches,
5
6
  classifyStorageContent,
7
+ classifyMatchingFilenameLeaf,
6
8
  rememberMatchingLeaf,
7
9
  finaliseStoredRevision
8
10
  } from "./provenance.js";
@@ -10,28 +12,56 @@ import { queueConflictCheckFor } from "./locking.js";
10
12
  import { isFolderInfo } from "./storage.js";
11
13
  import { LOG_LEVEL_NOTICE } from "octagonal-wheels/common/logger";
12
14
  import { isDocContentSame } from "../../common/utils.js";
15
+ function hasIncomingContent(content) {
16
+ return content !== void 0;
17
+ }
13
18
  async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEntry, incomingContent) {
14
- const observedProvenance = await readProvenanceSnapshot(ctx, path);
19
+ const observedPath = existDoc.path;
20
+ const observedProvenance = await readProvenanceSnapshot(ctx, observedPath);
15
21
  const readFile = await ctx.host.readFileFromStub(existDoc);
22
+ if (readFile.path !== observedPath) {
23
+ return { preserved: false };
24
+ }
16
25
  const snapshot = { file: readFile, revision: observedProvenance };
17
- if (incomingContent && await isDocContentSame(incomingContent, readFile.body)) {
26
+ if (hasIncomingContent(incomingContent) && await isDocContentSame(incomingContent, readFile.body)) {
18
27
  return await currentStorageSnapshotMatches(ctx, readFile, observedProvenance) ? { preserved: false, snapshot } : { preserved: false };
19
28
  }
20
29
  if (!incomingEntry._rev) {
21
30
  return { preserved: false };
22
31
  }
23
- let classification;
24
- let unavailableRead;
25
- try {
26
- classification = await classifyStorageContent(
32
+ return await preserveStorageSnapshot(
33
+ ctx,
34
+ path,
35
+ snapshot,
36
+ () => classifyStorageContent(
27
37
  ctx,
28
38
  readFile,
29
39
  incomingEntry,
30
40
  void 0,
31
41
  observedProvenance,
32
- incomingContent ? { _rev: incomingEntry._rev, data: incomingContent } : void 0,
42
+ hasIncomingContent(incomingContent) ? { _rev: incomingEntry._rev, data: incomingContent } : void 0,
33
43
  false
34
- );
44
+ )
45
+ );
46
+ }
47
+ async function preserveUnobservedFilename(ctx, path, existDoc, observedProvenance) {
48
+ const file = await ctx.host.readFileFromStub(existDoc);
49
+ if (file.path !== existDoc.path) {
50
+ return { preserved: false };
51
+ }
52
+ return await preserveStorageSnapshot(
53
+ ctx,
54
+ path,
55
+ { file, revision: observedProvenance },
56
+ () => classifyMatchingFilenameLeaf(ctx, file)
57
+ );
58
+ }
59
+ async function preserveStorageSnapshot(ctx, path, snapshot, classify) {
60
+ const { file: readFile, revision: observedProvenance } = snapshot;
61
+ let classification;
62
+ let unavailableRead;
63
+ try {
64
+ classification = await classify();
35
65
  } catch (error) {
36
66
  if (!(error instanceof ContentReadError)) {
37
67
  throw error;
@@ -46,7 +76,7 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
46
76
  return { preserved: false, snapshot };
47
77
  }
48
78
  if (classification.kind === "matching-leaf") {
49
- await rememberMatchingLeaf(ctx, path, classification.revision, readFile.stat.mtime, readFile.body);
79
+ await rememberMatchingLeaf(ctx, readFile.path, classification.revision, readFile.stat.mtime, readFile.body);
50
80
  await queueConflictCheckFor(ctx, path);
51
81
  return { preserved: true };
52
82
  }
@@ -68,6 +98,18 @@ async function preserveUnsyncedStorageAsConflict(ctx, path, existDoc, incomingEn
68
98
  async function recheckIncomingStorage(ctx, path, incomingEntry, incomingContent, allowExistingConflicts) {
69
99
  const current = await ctx.host.storage().getStub(path);
70
100
  if (!current || isFolderInfo(current)) return { preserved: false };
101
+ if (current.path !== path) {
102
+ const [currentDocumentId, targetDocumentId] = await Promise.all([
103
+ ctx.path.path2id(current.path),
104
+ ctx.path.path2id(path)
105
+ ]);
106
+ if (currentDocumentId !== targetDocumentId) {
107
+ return { preserved: false };
108
+ }
109
+ if (hasIncomingContent(incomingContent) && getProvenancePath(ctx, current.path) !== getProvenancePath(ctx, path)) {
110
+ return { preserved: false };
111
+ }
112
+ }
71
113
  const protection = await preserveUnsyncedStorageAsConflict(ctx, path, current, incomingEntry, incomingContent);
72
114
  if (protection.preserved || !protection.snapshot) return protection;
73
115
  if (!allowExistingConflicts && !ctx.setting.currentSettings().writeDocumentsIfConflicted && (await ctx.host.db().readConflictedRevs(path)).length > 0) {
@@ -77,6 +119,7 @@ async function recheckIncomingStorage(ctx, path, incomingEntry, incomingContent,
77
119
  return protection;
78
120
  }
79
121
  export {
122
+ preserveUnobservedFilename,
80
123
  preserveUnsyncedStorageAsConflict,
81
124
  recheckIncomingStorage
82
125
  };
@@ -50,6 +50,34 @@ export declare function setProvenance(ctx: FileHandlerContext, path: FilePathWit
50
50
  * @remarks No document lock is acquired here. The caller's database or storage effect is not rolled back if device-local cleanup fails.
51
51
  */
52
52
  export declare function deleteProvenance(ctx: FileHandlerContext, path: FilePathWithPrefix): Promise<void>;
53
+ /** Pre-rename provenance snapshot for source and target spellings under the same document lock. */
54
+ export interface RenameProvenanceSnapshot {
55
+ readonly oldPath: FilePathWithPrefix;
56
+ readonly oldKey: FilePathWithPrefix;
57
+ readonly expectedNewKey: FilePathWithPrefix;
58
+ readonly sourceRecord: FileReflectionProvenanceRecord | undefined;
59
+ readonly destinationBefore: FileReflectionProvenanceRecord | undefined;
60
+ }
61
+ /**
62
+ * Capture source and destination provenance strictly before a physical case-only rename.
63
+ *
64
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
65
+ * @param oldPath - The physical path observed before renaming.
66
+ * @param targetPath - The incoming canonical path requested for the rename.
67
+ * @returns The captured snapshot, or undefined when provenance is disabled or keys already match; returns false on a read or pre-rename stale-destination cleanup failure.
68
+ * @remarks When the source has no provenance and a stale record already occupies the destination key, that stale record is removed before mutating storage so a post-rename retry cannot inherit it.
69
+ */
70
+ export declare function captureRenameProvenance(ctx: FileHandlerContext, oldPath: FilePathWithPrefix, targetPath: FilePathWithPrefix): Promise<RenameProvenanceSnapshot | undefined | false>;
71
+ /**
72
+ * Transfer or reconcile destination provenance after a verified physical case-only rename.
73
+ *
74
+ * @param ctx - The captured services, per-instance state, and dynamic host seams.
75
+ * @param snapshot - The pre-rename source and destination provenance observations.
76
+ * @param newPath - The physical path returned by the storage rename.
77
+ * @returns True if provenance is now consistent with the renamed file; false if an intervening host update or store error prevents safe continuation.
78
+ * @remarks Performs an optimistic check against the pre-rename destination snapshot (read and write are separate operations) to preserve concurrent out-of-lock destination updates. Deletes the old key best-effort only after the new key write succeeds.
79
+ */
80
+ export declare function commitRenamedProvenance(ctx: FileHandlerContext, snapshot: RenameProvenanceSnapshot, newPath: FilePathWithPrefix): Promise<boolean>;
53
81
  /**
54
82
  * Find one unambiguous database revision containing the observed storage bytes.
55
83
  *
@@ -171,6 +199,8 @@ export type StorageContentClassification = RecordedStorageClassification | {
171
199
  } | {
172
200
  kind: "unknown";
173
201
  };
202
+ /** Use existing live-content matches only when the same filename is also recorded. */
203
+ export declare function classifyMatchingFilenameLeaf(ctx: FileHandlerContext, file: UXFileInfo): Promise<StorageContentClassification>;
174
204
  /**
175
205
  * Confirm the exact displayed revision from current bytes and device-local evidence.
176
206
  * @param ctx - Borrowed file-handler capabilities and provenance.
@@ -1,7 +1,7 @@
1
1
  import { withFileEventPaths } from "./locking.js";
2
- import { isFolderInfo } from "./storage.js";
2
+ import { isFileAtExactPath, isFolderInfo } from "./storage.js";
3
3
  import { LOG_LEVEL_VERBOSE } from "octagonal-wheels/common/logger";
4
- import { displayRev, isDocContentSame, readContent } from "../../common/utils.js";
4
+ import { displayRev, isDeletedEntry, isDocContentSame, readContent } from "../../common/utils.js";
5
5
  import { computeFileContentHash } from "../../common/fileContentHash.js";
6
6
  import { getPathNormalizationVersion, normalisePathForIdentity } from "../../common/pathNormalization.js";
7
7
  function getProvenancePath(ctx, path) {
@@ -16,7 +16,7 @@ async function getProvenance(ctx, path) {
16
16
  const record = await ctx.provenance.get(getProvenancePath(ctx, path));
17
17
  if (!record) return void 0;
18
18
  const entry = await ctx.host.db().readEntryMeta(path, record.revision, true);
19
- if (entry && !entry._deleted && !entry.deleted) {
19
+ if (entry && !isDeletedEntry(entry)) {
20
20
  return record;
21
21
  }
22
22
  if (!hasContentHash(record)) await ctx.provenance.delete(getProvenancePath(ctx, path));
@@ -64,6 +64,57 @@ async function deleteProvenance(ctx, path) {
64
64
  ctx.host.log(ex, LOG_LEVEL_VERBOSE);
65
65
  }
66
66
  }
67
+ async function captureRenameProvenance(ctx, oldPath, targetPath) {
68
+ if (!ctx.provenance) return void 0;
69
+ const oldKey = getProvenancePath(ctx, oldPath);
70
+ const expectedNewKey = getProvenancePath(ctx, targetPath);
71
+ if (oldKey === expectedNewKey) return void 0;
72
+ try {
73
+ const sourceRecord = await readProvenanceSnapshot(ctx, oldPath, true);
74
+ let destinationBefore = await readProvenanceSnapshot(ctx, targetPath, true);
75
+ if (!sourceRecord && destinationBefore !== void 0) {
76
+ await ctx.provenance.delete(expectedNewKey);
77
+ destinationBefore = void 0;
78
+ }
79
+ return { oldPath, oldKey, expectedNewKey, sourceRecord, destinationBefore };
80
+ } catch (ex) {
81
+ ctx.host.log(
82
+ `Could not prepare file reflection provenance before renaming ${oldPath} -> ${targetPath}`,
83
+ LOG_LEVEL_VERBOSE
84
+ );
85
+ ctx.host.log(ex, LOG_LEVEL_VERBOSE);
86
+ return false;
87
+ }
88
+ }
89
+ async function commitRenamedProvenance(ctx, snapshot, newPath) {
90
+ if (!ctx.provenance) return true;
91
+ const newKey = getProvenancePath(ctx, newPath);
92
+ if (newKey !== snapshot.expectedNewKey) return false;
93
+ if (snapshot.oldKey === newKey) return true;
94
+ try {
95
+ const destinationAfter = await readProvenanceSnapshot(ctx, newPath, true);
96
+ if (!sameProvenance(destinationAfter, snapshot.destinationBefore)) {
97
+ ctx.host.log(
98
+ `Preserving concurrent file reflection provenance update for ${newPath} after rename from ${snapshot.oldPath}`,
99
+ LOG_LEVEL_VERBOSE
100
+ );
101
+ return false;
102
+ }
103
+ if (snapshot.sourceRecord) {
104
+ await ctx.provenance.set(newKey, snapshot.sourceRecord);
105
+ await deleteProvenance(ctx, snapshot.oldPath);
106
+ return true;
107
+ }
108
+ return true;
109
+ } catch (ex) {
110
+ ctx.host.log(
111
+ `Could not update file reflection provenance after renaming ${snapshot.oldPath} -> ${newPath}`,
112
+ LOG_LEVEL_VERBOSE
113
+ );
114
+ ctx.host.log(ex, LOG_LEVEL_VERBOSE);
115
+ return false;
116
+ }
117
+ }
67
118
  async function findUniqueContentRevision(ctx, file) {
68
119
  try {
69
120
  const revisions = await ctx.host.db().findContentRevisions(file, file.body);
@@ -118,9 +169,9 @@ async function readProvenanceSnapshot(ctx, path, requireReadable = false) {
118
169
  }
119
170
  async function currentStorageSnapshotMatches(ctx, file, revision, requireReadableProvenance = false) {
120
171
  const current = await ctx.host.storage().getStub(file.path);
121
- if (!current || isFolderInfo(current) || current.path !== file.path) return false;
172
+ if (!isFileAtExactPath(current, file.path)) return false;
122
173
  const readCurrent = await ctx.host.readFileFromStub(current);
123
- return readCurrent.stat.mtime === file.stat.mtime && await isDocContentSame(readCurrent.body, file.body) && sameProvenance(await readProvenanceSnapshot(ctx, file.path, requireReadableProvenance), revision);
174
+ return readCurrent.path === file.path && readCurrent.stat.mtime === file.stat.mtime && await isDocContentSame(readCurrent.body, file.body) && sameProvenance(await readProvenanceSnapshot(ctx, file.path, requireReadableProvenance), revision);
124
175
  }
125
176
  async function finaliseStoredRevision(ctx, file, observedProvenance, storedRevision, requireReadableProvenance = false) {
126
177
  const evidence = await contentEvidence(ctx, file.body);
@@ -149,18 +200,36 @@ async function classifyRecordedStorageContent(ctx, file, path, recorded, recorde
149
200
  }
150
201
  if (!base) {
151
202
  const meta = await ctx.host.db().readEntryMeta(file, recordedRevision, true);
152
- if (requireReadableContent && meta && !meta.deleted && !meta._deleted) {
203
+ if (requireReadableContent && meta && !isDeletedEntry(meta)) {
153
204
  throw new Error(
154
205
  `Could not read the recorded file revision ${displayRev(recordedRevision)} for ${file.path}`
155
206
  );
156
207
  }
157
- if ((!meta || meta.deleted || meta._deleted) && !hasContentHash(recorded)) await deleteProvenance(ctx, path);
208
+ if ((!meta || isDeletedEntry(meta)) && !hasContentHash(recorded)) await deleteProvenance(ctx, path);
158
209
  }
159
210
  return void 0;
160
211
  }
161
212
  async function classifyLiveStorageContent(ctx, file, currentEntry) {
162
- const matches = currentEntry ? await ctx.host.db().readLiveContentRevisions(file, file.body) : [];
163
- if (matches.length) {
213
+ const db = ctx.host.db();
214
+ if (currentEntry && !isDeletedEntry(currentEntry) && !ctx.setting.currentSettings().handleFilenameCaseSensitive && db.readRevisionPath) {
215
+ return await classifyMatchingFilenameLeaf(ctx, file);
216
+ }
217
+ const matches = currentEntry ? await db.readLiveContentRevisions(file, file.body) : [];
218
+ return classifyMatchingLeaves(matches);
219
+ }
220
+ async function classifyMatchingFilenameLeaf(ctx, file) {
221
+ const db = ctx.host.db();
222
+ if (!db.readRevisionPath) {
223
+ return { kind: "unknown" };
224
+ }
225
+ const matches = await db.readLiveContentRevisions(file, file.body, {
226
+ path: file.path,
227
+ normalizationVersion: getPathNormalizationVersion(ctx.setting.currentSettings())
228
+ });
229
+ return classifyMatchingLeaves(matches);
230
+ }
231
+ function classifyMatchingLeaves(matches) {
232
+ if (matches.length > 0) {
164
233
  return { kind: "matching-leaf", revision: matches.length === 1 ? matches[0] : void 0 };
165
234
  }
166
235
  return { kind: "unknown" };
@@ -184,11 +253,14 @@ async function inspectCurrentFileProvenance(ctx, path, revision) {
184
253
  return false;
185
254
  }
186
255
  const current = await ctx.host.db().readEntryMeta(path, void 0, true);
187
- return !!current && current._rev === revision && !current.deleted && !current._deleted && await currentStorageSnapshotMatches(ctx, file, recorded, true);
256
+ return !!current && current._rev === revision && !isDeletedEntry(current) && await currentStorageSnapshotMatches(ctx, file, recorded, true);
188
257
  });
189
258
  }
190
259
  export {
260
+ captureRenameProvenance,
261
+ classifyMatchingFilenameLeaf,
191
262
  classifyStorageContent,
263
+ commitRenamedProvenance,
192
264
  contentEvidence,
193
265
  currentStorageSnapshotMatches,
194
266
  deleteProvenance,