@rljson/fs-agent 0.0.85 → 0.2.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.
@@ -1,146 +0,0 @@
1
- /** Tuning for {@link FsAntiEntropy}. */
2
- export interface AntiEntropyOptions {
3
- /** Whether divergence is repaired at all. Default: true. */
4
- enabled?: boolean;
5
- /**
6
- * How long one divergence must persist before it is repaired, in ms.
7
- *
8
- * Live traffic produces short divergences constantly — a push in flight is
9
- * one. Only a divergence that outlives it is a lost message. Default: 10 000.
10
- */
11
- graceMs?: number;
12
- /**
13
- * Upper bound of the backoff between repeated repairs of the SAME
14
- * divergence, in ms. Each attempt doubles the wait from `graceMs`, so a
15
- * repair that cannot succeed (a refusal, an unreachable blob) costs a
16
- * message every few minutes rather than one per heartbeat. Default: 300 000.
17
- */
18
- maxBackoffMs?: number;
19
- }
20
- /** Defaults for {@link AntiEntropyOptions}. */
21
- export declare const DEFAULT_ANTI_ENTROPY: Required<AntiEntropyOptions>;
22
- /** What a repair does. See the header of this file. */
23
- export type AntiEntropyAction = 'pull' | 'push' | 'merge';
24
- /** What {@link antiEntropyDecision} concluded. */
25
- export type AntiEntropyDecision = 'in-sync' | 'unknown' | AntiEntropyAction;
26
- /** The part of an agent's state the decision reads. */
27
- export interface AntiEntropyView {
28
- /** The origin this agent's connector announces under. */
29
- origin: string;
30
- /** The state the folder is in. */
31
- currentRef: string | undefined;
32
- /** The incoming state most recently applied. */
33
- lastAppliedRef: string | undefined;
34
- /**
35
- * The state this agent last pushed as its OWN work.
36
- *
37
- * Only such a state may be re-announced. An apply can leave the folder
38
- * short of the tree it applied — a node still catching up — and announcing
39
- * that is how a burst turns into a rollback.
40
- */
41
- lastPushedRef: string | undefined;
42
- }
43
- /** A hub announcement, as the heartbeat carries it. */
44
- export interface HubAnnouncement {
45
- /** The state the hub holds. */
46
- ref: string;
47
- /** Who produced that state. */
48
- origin?: string;
49
- /** What that state declares it descends from. */
50
- predecessors?: readonly string[];
51
- }
52
- /**
53
- * Decides who is behind, from the hub's announcement and our own state.
54
- * @param hub - What the hub announced.
55
- * @param view - This agent's state.
56
- * @returns What to do about it.
57
- */
58
- export declare function antiEntropyDecision(hub: HubAnnouncement, view: AntiEntropyView): AntiEntropyDecision;
59
- /** What {@link FsAntiEntropy} can report about itself. */
60
- export interface AntiEntropyStatus {
61
- /** Whether the last announcement differed from our state. */
62
- diverged: boolean;
63
- /** Since when the current divergence has lasted, epoch ms. */
64
- divergedSince: number | null;
65
- /** The state the hub last announced. */
66
- hubRef: string | null;
67
- /** Our state at that moment. */
68
- localRef: string | null;
69
- /** How many repairs were started over this agent's lifetime. */
70
- repairs: number;
71
- /** The most recent repair. */
72
- lastRepair: {
73
- action: AntiEntropyAction;
74
- at: number;
75
- hubRef: string;
76
- localRef: string;
77
- attempt: number;
78
- } | null;
79
- }
80
- /** What {@link FsAntiEntropy} needs from the agent it runs in. */
81
- export interface AntiEntropyDeps {
82
- /** This agent's state, read fresh at every announcement. */
83
- view: () => AntiEntropyView;
84
- /**
85
- * Whether anything is already applying or queued — a repair then waits.
86
- * @param hubRef - The state the hub is announcing right now.
87
- */
88
- busy: (hubRef: string) => boolean;
89
- /**
90
- * Starts a repair.
91
- * @param action - What to do.
92
- * @param hubRef - The state the hub announced.
93
- * @param hubPredecessors - What that state descends from.
94
- * @param attempt - 1 for the first repair of this divergence, then 2, 3, …
95
- */
96
- repair: (action: AntiEntropyAction, hubRef: string, hubPredecessors: string[], attempt: number) => void;
97
- /** Clock, for tests. */
98
- now?: () => number;
99
- /** Log sink. */
100
- log?: (message: string) => void;
101
- }
102
- /**
103
- * Notices a divergence between this agent and the hub, and repairs it.
104
- *
105
- * Fed with every hub announcement; decides nothing while this node's own state
106
- * is still moving, only once it has sat still and out of step with the hub for
107
- * {@link AntiEntropyOptions.graceMs} — however often the hub's state changed
108
- * meanwhile.
109
- */
110
- export declare class FsAntiEntropy {
111
- private readonly _deps;
112
- private readonly _options;
113
- private readonly _now;
114
- private readonly _log;
115
- /**
116
- * Identifies the divergence being watched: OUR state, and only ours.
117
- *
118
- * It used to include the hub's state, so every change on the hub restarted
119
- * the grace period — and a node that missed every forward while another
120
- * machine wrote every few seconds never got a repair at all, showing "weicht
121
- * ab, noch kein Reparaturversuch" for good (review, ONE-446). What makes a
122
- * divergence a lost message is that THIS node is not moving: a node keeping
123
- * up with the traffic changes its own state with every forward it applies.
124
- * Which hub state the repair answers is read from the latest announcement.
125
- */
126
- private _key;
127
- private _divergedSince;
128
- /** Earliest moment the next repair of {@link _key} may start. */
129
- private _nextRepairAt;
130
- /** Repairs started for {@link _key}. */
131
- private _attempts;
132
- private _hubRef;
133
- private _localRef;
134
- private _repairs;
135
- private _lastRepair;
136
- constructor(options: AntiEntropyOptions | undefined, _deps: AntiEntropyDeps);
137
- /** Whether repairs are switched on. */
138
- get enabled(): boolean;
139
- /** A snapshot of what this instance has seen and done. */
140
- get status(): AntiEntropyStatus;
141
- /**
142
- * Takes one hub announcement into account.
143
- * @param hub - What the hub announced.
144
- */
145
- observe(hub: HubAnnouncement): void;
146
- }
@@ -1,181 +0,0 @@
1
- import { Conflict } from '@rljson/db';
2
- import { InsertHistoryRow } from '@rljson/rljson';
3
- import { FsTree } from './fs-scanner.js';
4
- /**
5
- * Nextcloud-style conflict resolution for forked FS-tree DAGs.
6
- *
7
- * When two peers edit a shared tree while one is offline, the InsertHistory
8
- * DAG forks into two tips (B and C, both descending from a common ancestor A).
9
- * `@rljson/db` fires a `dagBranch` conflict. This module resolves it on the
10
- * **client** by performing a deterministic three-way file-level merge and
11
- * writing a single **merge revision D** whose `InsertHistory.previous`
12
- * references *both* tips — collapsing the fork back to one tip.
13
- *
14
- * The pure functions (merge, naming, ancestor walk, winner selection) are
15
- * deterministic: every peer resolving the same fork produces the identical D,
16
- * so resolution converges instead of forking again.
17
- *
18
- * See `doc/conflict-resolution-design.md`.
19
- */
20
- /** relativePath → blobId. Directories are recorded as {@link DIR_MARKER}. */
21
- export type ContentMap = Map<string, string>;
22
- /** Sentinel blobId used for directory entries in a {@link ContentMap}. */
23
- export declare const DIR_MARKER = "<dir>";
24
- /**
25
- * Builds a {@link ContentMap} (relativePath → blobId) from an FsTree, ignoring
26
- * mtime so two trees with identical content compare equal regardless of when
27
- * they were written.
28
- * @param tree - The FsTree to flatten
29
- * @returns A map of relativePath → blobId (directories use {@link DIR_MARKER})
30
- */
31
- export declare function fsTreeToContentMap(tree: FsTree): ContentMap;
32
- /** A branch tip's identity, used for deterministic winner selection. */
33
- export interface BranchTip {
34
- /** InsertHistory timeId of the tip (per-db; used only for local lookups). */
35
- timeId: string;
36
- /** Shared content ref of the tip — the cross-client deterministic tiebreak. */
37
- ref: string;
38
- /** Originating client id (InsertHistory `origin`). Empty string if unknown. */
39
- clientId: string;
40
- /** InsertHistory client timestamp (ms). 0 if unknown. */
41
- timestamp: number;
42
- }
43
- /**
44
- * 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.
49
- * @param a - First tip
50
- * @param b - Second tip
51
- * @returns Positive if `a` outranks `b`, negative if `b` outranks `a`, else 0
52
- */
53
- export declare function compareTips(a: BranchTip, b: BranchTip): number;
54
- /**
55
- * Picks the path-owning winner of a conflict. Per design decision §11.1 the
56
- * revision with the greater InsertHistory timestamp keeps the original path;
57
- * the loser's content is preserved under a renamed conflict copy.
58
- * @param a - First tip
59
- * @param b - Second tip
60
- * @returns The winning and losing tips
61
- */
62
- export declare function decideWinner(a: BranchTip, b: BranchTip): {
63
- winner: BranchTip;
64
- loser: BranchTip;
65
- };
66
- /**
67
- * Finds the nearest common ancestor timeId of two tips by walking the
68
- * InsertHistory `previous` chains. Returns null when the tips share no
69
- * ancestor (treat as an empty ancestor — everything is an add/add).
70
- * @param rows - All InsertHistory rows for the table
71
- * @param tipA - First tip timeId
72
- * @param tipB - Second tip timeId
73
- * @returns The nearest common ancestor timeId, or null if none
74
- */
75
- export declare function findCommonAncestor(rows: InsertHistoryRow<string>[], tipA: string, tipB: string): string | null;
76
- /**
77
- * Formats a timestamp as a stable UTC `YYYY-MM-DD HHMMSS` string. UTC keeps the
78
- * conflict-copy name identical across peers in different timezones.
79
- * @param ms - Milliseconds since the epoch
80
- * @returns The formatted UTC timestamp
81
- */
82
- export declare function formatConflictTimestamp(ms: number): string;
83
- /**
84
- * Derives a Nextcloud-style conflict-copy path:
85
- * `document.txt` → `document (conflicted copy <clientId> <ts>).txt`.
86
- *
87
- * - The suffix is inserted before the final extension; dotfiles / extensionless
88
- * names get it appended.
89
- * - Identity + timestamp come from the *losing* revision, so every peer derives
90
- * the same name (determinism).
91
- * - If the candidate name is already taken, a numeric ` (n)` is appended; the
92
- * chosen name is added to `taken`.
93
- * @param relativePath - The original conflicting path
94
- * @param clientId - The losing revision's client id
95
- * @param timestamp - The losing revision's InsertHistory timestamp (ms)
96
- * @param taken - Set of already-used paths; the chosen name is added to it
97
- * @returns A unique conflict-copy path
98
- */
99
- export declare function conflictCopyName(relativePath: string, clientId: string, timestamp: number, taken: Set<string>): string;
100
- /** A conflict copy to materialise: the losing content under a renamed path. */
101
- export interface ConflictCopy {
102
- /** The renamed path the losing content is written to. */
103
- path: string;
104
- /** The losing blobId (content preserved, nothing lost). */
105
- blobId: string;
106
- }
107
- /** The result of a three-way merge. */
108
- export interface MergePlan {
109
- /** Final tree content (winner-resolved): relativePath → blobId. */
110
- merged: ContentMap;
111
- /** Extra files to write beside the merged set (the renamed losers). */
112
- copies: ConflictCopy[];
113
- /** Original paths that genuinely conflicted (both sides changed differently). */
114
- conflictPaths: string[];
115
- }
116
- /**
117
- * Three-way file-level merge of ancestor `o`, branch `ours`, branch `theirs`.
118
- * `winnerSide` decides who keeps the path on a real conflict; the loser's
119
- * content is preserved under a {@link conflictCopyName}. Pure & deterministic.
120
- *
121
- * Per relative path (see design §4.4):
122
- * - both sides equal → keep it (covers unchanged + add-same + delete-both)
123
- * - only theirs changed (`ours === o`) → take theirs
124
- * - only ours changed (`theirs === o`) → take ours
125
- * - both changed differently → CONFLICT: winner keeps path, loser renamed
126
- * @param o - Ancestor content map
127
- * @param ours - Our branch content map
128
- * @param theirs - Their branch content map
129
- * @param winnerSide - Which side keeps the path on a real conflict
130
- * @param loserClientId - The losing revision's client id (for copy names)
131
- * @param loserTimestamp - The losing revision's timestamp (for copy names)
132
- * @returns The merge plan (merged set, conflict copies, conflicting paths)
133
- */
134
- export declare function threeWayMerge(o: ContentMap, ours: ContentMap, theirs: ContentMap, winnerSide: 'ours' | 'theirs', loserClientId: string, loserTimestamp: number): MergePlan;
135
- /**
136
- * The capabilities the resolver needs from its host FsAgent + Db. Injected so
137
- * the orchestration is unit-testable with in-memory fakes (no real db/fs).
138
- */
139
- export interface ConflictResolverDeps {
140
- /** The tree table key (route is `/${treeKey}`). */
141
- treeKey: string;
142
- /** All InsertHistory rows for `treeKey`. */
143
- getInsertHistory: (table: string) => Promise<InsertHistoryRow<string>[]>;
144
- /** Resolve a tip timeId to its tree root ref. */
145
- getRefOfTimeId: (table: string, timeId: string) => Promise<string | null>;
146
- /** Fetch a full FsTree by its root ref. */
147
- fetchTree: (rootRef: string) => Promise<FsTree>;
148
- /** Read a blob's bytes by blobId. */
149
- getBlobContent: (blobId: string) => Promise<Buffer>;
150
- /** Restore an FsTree onto the working dir, pruning extraneous entries. */
151
- restoreTree: (tree: FsTree) => Promise<void>;
152
- /** Write bytes to a relative path under the working dir (mkdir -p). */
153
- writeFileAt: (relativePath: string, content: Buffer) => Promise<void>;
154
- /** Remove a relative path under the working dir (best effort). */
155
- deleteFileAt: (relativePath: string) => Promise<void>;
156
- /** Re-scan the working dir into a fresh, hashed FsTree. */
157
- scan: () => Promise<FsTree>;
158
- /** Store the merge revision with explicit predecessors; returns its root ref. */
159
- storeMerge: (tree: FsTree, previous: string[]) => Promise<string>;
160
- /** Notified with the stored merge ref so the host can suppress the echo. */
161
- onMergeStored?: (ref: string) => void;
162
- /** Optional structured logger. */
163
- log?: (level: 'info' | 'warn' | 'error', msg: string) => void;
164
- }
165
- /**
166
- * Resolves a single `dagBranch` conflict into a merge revision. For more than
167
- * two tips it merges the two lowest-identity tips per call; the resulting
168
- * smaller fork re-fires the observer and converges in further rounds.
169
- */
170
- export declare class FsConflictResolver {
171
- private readonly deps;
172
- constructor(deps: ConflictResolverDeps);
173
- private _log;
174
- /**
175
- * Resolves the conflict, returning the stored merge ref, or null when the
176
- * conflict is not ours / not actionable.
177
- * @param conflict - The detected DAG-branch conflict
178
- * @returns The stored merge revision's root ref, or null
179
- */
180
- resolve(conflict: Conflict): Promise<string | null>;
181
- }