@rljson/fs-agent 0.0.85 → 0.1.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.
@@ -15,7 +15,7 @@ import { FsTree } from './fs-scanner.js';
15
15
  * deterministic: every peer resolving the same fork produces the identical D,
16
16
  * so resolution converges instead of forking again.
17
17
  *
18
- * See `doc/conflict-resolution-design.md`.
18
+ * See `README.architecture.md`, "Conflicts".
19
19
  */
20
20
  /** relativePath → blobId. Directories are recorded as {@link DIR_MARKER}. */
21
21
  export type ContentMap = Map<string, string>;
@@ -31,6 +31,31 @@ export declare const DIR_MARKER = "<dir>";
31
31
  export declare function fsTreeToContentMap(tree: FsTree): ContentMap;
32
32
  /** A branch tip's identity, used for deterministic winner selection. */
33
33
  export interface BranchTip {
34
+ /**
35
+ * The EDIT CHAIN's `timeId` for this tip, when the chain has an entry for
36
+ * it — `<millis>:<nanoid>`, minted by the authoring node and carried with
37
+ * the row, so it is identical on every node.
38
+ *
39
+ * This is the primary ordering key, and it has to be, because the two that
40
+ * used to be are not populated. Measured end to end on two nodes editing
41
+ * one file: the conflict copy came out named
42
+ *
43
+ * shared (conflicted copy db.insertTrees 1970-01-01 000000).txt
44
+ *
45
+ * `db.insertTrees` is the DB's label for its own operation, not a client, and
46
+ * the epoch is `clientTimestamp` never being set — `Db.insertTrees` accepts
47
+ * neither, so no caller can supply them. With `timestamp` equal at 0 and
48
+ * `clientId` equal for everybody, both top comparisons collapsed and the
49
+ * winner fell through to *whichever content hash sorts higher*. Deterministic,
50
+ * so the fleet converged; but unrelated to who edited last, which is what
51
+ * `§11.1` says decides.
52
+ *
53
+ * The chain's stamp is what the agent already mints for exactly this kind of
54
+ * question, so nothing new has to be transported. Absent only for a tip no
55
+ * chain entry covers (a peer on an older build), which is why it is optional
56
+ * and why the old keys stay below it as a fallback.
57
+ */
58
+ chainTimeId?: string;
34
59
  /** InsertHistory timeId of the tip (per-db; used only for local lookups). */
35
60
  timeId: string;
36
61
  /** Shared content ref of the tip — the cross-client deterministic tiebreak. */
@@ -42,10 +67,28 @@ export interface BranchTip {
42
67
  }
43
68
  /**
44
69
  * Total, deterministic order over two tips. Returns a positive number when `a`
45
- * outranks `b`. Greater timestamp wins; ties broken by greater clientId, then
46
- * greater **content ref**. The final tiebreak is the ref (not the timeId)
47
- * because timeIds are per-db — using them would make different peers pick
48
- * different winners and never converge; the ref is shared, so every peer agrees.
70
+ * outranks `b`.
71
+ *
72
+ * The keys, in order:
73
+ *
74
+ * 1. the EDIT CHAIN's `timeId` — the newer edit outranks the older. See
75
+ * {@link BranchTip.chainTimeId} for why this had to become the first key:
76
+ * the two below it are not populated by `Db.insertTrees`, so without it
77
+ * the decision fell through to a content hash comparison.
78
+ * 2. greater InsertHistory `clientTimestamp`;
79
+ * 3. greater `clientId`;
80
+ * 4. greater **content ref**.
81
+ *
82
+ * The last tiebreak is the ref rather than the InsertHistory timeId because
83
+ * timeIds are per-db — using one would make different peers pick different
84
+ * winners and never converge. The ref is shared, so every peer agrees; and
85
+ * that claim is only true now that mtime is out of the content identity, which
86
+ * is what made two peers derive different refs for identical content.
87
+ *
88
+ * `compareTimeId` is a total order over `<millis>:<nanoid>` and is identical
89
+ * on every node, so key 1 preserves the property the rest of this function
90
+ * exists for. A tip with no chain entry compares as "not comparable" and falls
91
+ * through, so a peer on an older build is ordered exactly as before.
49
92
  * @param a - First tip
50
93
  * @param b - Second tip
51
94
  * @returns Positive if `a` outranks `b`, negative if `b` outranks `a`, else 0
@@ -73,6 +116,46 @@ export declare function decideWinner(a: BranchTip, b: BranchTip): {
73
116
  * @returns The nearest common ancestor timeId, or null if none
74
117
  */
75
118
  export declare function findCommonAncestor(rows: InsertHistoryRow<string>[], tipA: string, tipB: string): string | null;
119
+ /**
120
+ * What `Db.insertTrees` writes into an InsertHistory row's `origin`: the name
121
+ * of its own operation, not an identity.
122
+ *
123
+ * `Db.insertTrees` accepts no `origin`, so every row this agent writes carries
124
+ * this, on every node. It is the reason a conflict copy came out named
125
+ * `shared (conflicted copy db.insertTrees 1970-01-01 000000).txt` — see
126
+ * {@link BranchTip.chainTimeId}.
127
+ */
128
+ export declare const DB_OPERATION_ORIGIN = "db.insertTrees";
129
+ /**
130
+ * The wall-clock millisecond a tip was authored, as well as it can be known.
131
+ *
132
+ * The chain's `timeId` is `<millis>:<nanoid>` and its millisecond half is the
133
+ * authoring node's clock at the moment of the edit — which is the only real
134
+ * time available here, because `clientTimestamp` is never set (see
135
+ * {@link BranchTip.chainTimeId}). Without this a conflict copy was dated
136
+ * `1970-01-01 000000`.
137
+ *
138
+ * Used ONLY for the copy's human-readable name. Ordering uses
139
+ * {@link compareTimeId} on the whole id, never this number, so two edits in
140
+ * the same millisecond are still totally ordered.
141
+ * @param tip - The tip to date.
142
+ * @returns Milliseconds since the epoch, or `0` when nothing knows.
143
+ */
144
+ export declare function tipTimestamp(tip: BranchTip): number;
145
+ /**
146
+ * An `origin` only when it identifies a client, else the empty string.
147
+ *
148
+ * A name in a filename a user has to read must be true or absent. Printing the
149
+ * DB's operation label as the machine that made the edit is worse than
150
+ * printing nothing: it reads as information and is not.
151
+ *
152
+ * Carrying the real author needs `Db.insertTrees` to accept an origin, which
153
+ * it does not — a follow-up outside this package. Until then the copy is named
154
+ * by its time alone.
155
+ * @param origin - The InsertHistory row's origin, if any.
156
+ * @returns A usable client id, or `''`.
157
+ */
158
+ export declare function usableClientId(origin: string | undefined): string;
76
159
  /**
77
160
  * Formats a timestamp as a stable UTC `YYYY-MM-DD HHMMSS` string. UTC keeps the
78
161
  * conflict-copy name identical across peers in different timezones.
@@ -90,19 +173,104 @@ export declare function formatConflictTimestamp(ms: number): string;
90
173
  * the same name (determinism).
91
174
  * - If the candidate name is already taken, a numeric ` (n)` is appended; the
92
175
  * chosen name is added to `taken`.
176
+ *
177
+ * **The name has to distinguish distinct losing CONTENT, and without an
178
+ * identity it did not.** `usableClientId` returns empty whenever the origin is
179
+ * the DB's own label, which is the ordinary case, and the timestamp has
180
+ * second granularity — so two nodes losing DIFFERENT content in the same
181
+ * second derived the same copy name. The copies then conflicted with each
182
+ * other, producing a copy of a copy:
183
+ *
184
+ * two (conflicted copy 2026-10-03 142610) (conflicted copy 2026-10-03 142611).txt
185
+ *
186
+ * Measured on the seeded fuzz run as up to 14 nested copies, and present
187
+ * before this session's work as well (0–5 on the same four runs). The losing
188
+ * revision's content ref is carried in only when there is no identity to use:
189
+ * it is identical on every peer for the same losing revision and differs
190
+ * whenever the content does, which is exactly the property that was missing.
191
+ * A name that is already readable stays readable.
93
192
  * @param relativePath - The original conflicting path
94
193
  * @param clientId - The losing revision's client id
95
194
  * @param timestamp - The losing revision's InsertHistory timestamp (ms)
96
195
  * @param taken - Set of already-used paths; the chosen name is added to it
196
+ * @param loserRef - The losing revision's content ref, used to tell two
197
+ * same-second losers apart when neither has a usable identity.
97
198
  * @returns A unique conflict-copy path
98
199
  */
99
- export declare function conflictCopyName(relativePath: string, clientId: string, timestamp: number, taken: Set<string>): string;
200
+ export declare function conflictCopyName(relativePath: string, clientId: string, timestamp: number, taken: Set<string>, loserRef?: string): string;
201
+ /**
202
+ * Derives the name a file is set aside under when the history DELETED its path.
203
+ *
204
+ * `document.txt` → `document (recovered).txt`.
205
+ *
206
+ * **Not a conflict copy, and the difference is who is told.** A conflict copy
207
+ * is live work on a live path and is announced, because the network needs it.
208
+ * A recovered file is content the fleet deliberately removed — a folder
209
+ * restored from last month's backup, or a client that was away while a
210
+ * directory was deleted — and announcing it would push every one of those
211
+ * deletions back to every node, under names nobody deleted. So it is kept
212
+ * where its owner can see it and nothing is said about it.
213
+ *
214
+ * That is a deliberate, visible local divergence, chosen over the two
215
+ * alternatives: resurrecting a deletion, or destroying a file somebody may
216
+ * still want. No timestamp and no identity, because unlike a conflict there is
217
+ * nothing to tell apart — the path is simply gone from the history, and one
218
+ * name per path is what a user can act on.
219
+ * @param relativePath - The path the history removed
220
+ * @param taken - Paths already used; the chosen name is added to it
221
+ * @returns A unique set-aside path
222
+ */
223
+ export declare function recoveredName(relativePath: string, taken: Set<string>): string;
224
+ /**
225
+ * One same-file conflict, in the terms a user needs to see it in.
226
+ *
227
+ * WHY THIS EXISTS. A fork on two DIFFERENT files is merged as a union and
228
+ * nobody should be asked about it. A fork on the SAME file is a real conflict,
229
+ * and until now resolving one produced a renamed file and silence: nothing was
230
+ * lost, but the only evidence was a strange filename appearing in a folder,
231
+ * with no statement of what happened, which version is live, or where the
232
+ * other one went.
233
+ *
234
+ * Deliberately NOT an error. Two people editing one document at the same time
235
+ * is ordinary, both versions are kept, and the folder converges. It is an event
236
+ * to report, which is why it does not go through `_writeSyncError`.
237
+ *
238
+ * And deliberately not a question. The winner is already decided — it has to
239
+ * be, or peers would not converge — so this says what was decided and leaves
240
+ * reversing it to whoever looks: the losing content is on disk under
241
+ * {@link copyPath}, so swapping the two files is all it takes.
242
+ */
243
+ export interface FsConflictReport {
244
+ /** The path both sides edited. The winner's content is here. */
245
+ path: string;
246
+ /** Where the losing version was kept, intact. */
247
+ copyPath: string;
248
+ /** Content ref of the branch that keeps {@link path}. */
249
+ winnerRef: string;
250
+ /** Content ref of the branch whose version moved to {@link copyPath}. */
251
+ loserRef: string;
252
+ /**
253
+ * When the losing edit was made, in epoch ms, or `0` when nothing knows —
254
+ * see {@link tipTimestamp} for why that is not always answerable.
255
+ */
256
+ loserAt: number;
257
+ /** When this node resolved the conflict, in epoch ms. */
258
+ resolvedAt: number;
259
+ }
100
260
  /** A conflict copy to materialise: the losing content under a renamed path. */
101
261
  export interface ConflictCopy {
102
262
  /** The renamed path the losing content is written to. */
103
263
  path: string;
104
264
  /** The losing blobId (content preserved, nothing lost). */
105
265
  blobId: string;
266
+ /**
267
+ * The path the two sides actually disagreed about.
268
+ *
269
+ * Recoverable from {@link path} only by un-parsing a filename, which is the
270
+ * kind of thing that works until somebody's document is called
271
+ * `report (conflicted copy ...).txt`.
272
+ */
273
+ originalPath: string;
106
274
  }
107
275
  /** The result of a three-way merge. */
108
276
  export interface MergePlan {
@@ -126,12 +294,23 @@ export interface MergePlan {
126
294
  * @param o - Ancestor content map
127
295
  * @param ours - Our branch content map
128
296
  * @param theirs - Their branch content map
129
- * @param winnerSide - Which side keeps the path on a real conflict
297
+ * @param winnerSide - Which side keeps the path on a real conflict, when
298
+ * nothing more specific is known. The BRANCH-level answer, and a fallback:
299
+ * see `winnerFor`.
130
300
  * @param loserClientId - The losing revision's client id (for copy names)
131
301
  * @param loserTimestamp - The losing revision's timestamp (for copy names)
302
+ * @param winnerFor - Per-path verdict, asked of the edit chain: *who last
303
+ * changed THIS path?* `undefined` for a path means the chain could not say
304
+ * and `winnerSide` decides it.
305
+ *
306
+ * **This is the difference between ordering a branch and ordering a file.**
307
+ * Without it one verdict covers every path the two branches disagree about,
308
+ * so a tip wins paths it never touched — measured as a node that came back
309
+ * from being offline, wrote one unrelated file, and took `doc.txt` with it,
310
+ * rolling the writer's own folder from v8 back to v5.
132
311
  * @returns The merge plan (merged set, conflict copies, conflicting paths)
133
312
  */
134
- export declare function threeWayMerge(o: ContentMap, ours: ContentMap, theirs: ContentMap, winnerSide: 'ours' | 'theirs', loserClientId: string, loserTimestamp: number): MergePlan;
313
+ export declare function threeWayMerge(o: ContentMap, ours: ContentMap, theirs: ContentMap, winnerSide: 'ours' | 'theirs', loserClientId: string, loserTimestamp: number, winnerFor?: (path: string) => 'ours' | 'theirs' | undefined): MergePlan;
135
314
  /**
136
315
  * The capabilities the resolver needs from its host FsAgent + Db. Injected so
137
316
  * the orchestration is unit-testable with in-memory fakes (no real db/fs).
@@ -143,6 +322,24 @@ export interface ConflictResolverDeps {
143
322
  getInsertHistory: (table: string) => Promise<InsertHistoryRow<string>[]>;
144
323
  /** Resolve a tip timeId to its tree root ref. */
145
324
  getRefOfTimeId: (table: string, timeId: string) => Promise<string | null>;
325
+ /**
326
+ * The edit chain's `timeId` for a tree ref, if the chain covers it.
327
+ *
328
+ * Optional: a host without a chain, or a tip authored by a peer on an older
329
+ * build, simply has no answer — and {@link compareTips} falls back to the
330
+ * keys it used before. See {@link BranchTip.chainTimeId}.
331
+ */
332
+ chainTimeIdOfRef?: (treeRef: string) => Promise<string | undefined>;
333
+ /**
334
+ * The `timeId` of the newest edit on `treeRef`'s lineage that touched `path`.
335
+ *
336
+ * Who last changed THIS file? — the question that decides a conflict per
337
+ * path instead of per branch. `undefined` means the chain cannot say: the
338
+ * lineage never named the path, or the walk could not be read to the end.
339
+ * Absent entirely means an older peer, and the branch order decides
340
+ * everything as before.
341
+ */
342
+ lastEditOfPath?: (treeRef: string, path: string) => Promise<string | undefined>;
146
343
  /** Fetch a full FsTree by its root ref. */
147
344
  fetchTree: (rootRef: string) => Promise<FsTree>;
148
345
  /** Read a blob's bytes by blobId. */
@@ -159,6 +356,13 @@ export interface ConflictResolverDeps {
159
356
  storeMerge: (tree: FsTree, previous: string[]) => Promise<string>;
160
357
  /** Notified with the stored merge ref so the host can suppress the echo. */
161
358
  onMergeStored?: (ref: string) => void;
359
+ /**
360
+ * Notified once per merge with every same-file conflict it resolved.
361
+ *
362
+ * Never called with an empty list, so a host can treat any call as "there is
363
+ * something to tell the user about".
364
+ */
365
+ onConflicts?: (reports: FsConflictReport[]) => void;
162
366
  /** Optional structured logger. */
163
367
  log?: (level: 'info' | 'warn' | 'error', msg: string) => void;
164
368
  }