@xsok/dsh-enhanced 0.0.0-stage → 0.2.2-11

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.
@@ -0,0 +1,4 @@
1
+ - insert:
2
+ - id: dsh-enhanced
3
+ name: '@xsok/dsh-enhanced'
4
+ config: {}
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Archive / unarchive event propagation.
3
+ *
4
+ * `workspace.json` only carries the current archived set, so "unarchive" cannot
5
+ * travel: the other machine still holds the old archive list and would keep the
6
+ * session archived forever. Two small documents fix that:
7
+ *
8
+ * archive-events.json session id -> { state: 'archived'|'active', at, by }
9
+ * archive-<machine>.json the archived set this machine had after its last run
10
+ *
11
+ * A run diffs its own set against its snapshot to emit events, merges the event
12
+ * table (newest `at` wins), then applies it: a session whose latest event is
13
+ * `active` is dropped from the archived list even if another document lists it.
14
+ */
15
+ import { promises as fsp } from 'node:fs';
16
+ import { randomUUID } from 'node:crypto';
17
+ import path from 'node:path';
18
+
19
+ async function readJson(file, fallback) {
20
+ try {
21
+ return JSON.parse(await fsp.readFile(file, 'utf8'));
22
+ } catch {
23
+ return fallback;
24
+ }
25
+ }
26
+
27
+ async function writeJson(file, value) {
28
+ await fsp.mkdir(path.dirname(file), { recursive: true });
29
+ const temporary = `${file}.${randomUUID()}.tmp`;
30
+ await fsp.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
31
+ await fsp.rename(temporary, file);
32
+ }
33
+
34
+ /** Read the shared event table. */
35
+ export async function readArchiveEvents(stateDir) {
36
+ const doc = await readJson(path.join(stateDir, 'archive-events.json'), { version: 1, events: {} });
37
+ const events = doc?.events;
38
+ return events !== null && typeof events === 'object' ? { ...events } : {};
39
+ }
40
+
41
+ /** Persist the event table, sorted for a stable diff. */
42
+ export async function writeArchiveEvents(stateDir, events) {
43
+ const rows = {};
44
+ for (const id of Object.keys(events).sort()) {
45
+ rows[id] = { state: events[id].state, at: events[id].at, by: events[id].by };
46
+ }
47
+ await writeJson(path.join(stateDir, 'archive-events.json'), {
48
+ version: 1,
49
+ note: '归档/取消归档事件表:同步脚本据此让取消归档也能跨机生效,请勿手改',
50
+ events: rows,
51
+ });
52
+ }
53
+
54
+ /** The archived set this machine had after its last run. */
55
+ export async function readArchiveSnapshot(stateDir, machineId) {
56
+ const doc = await readJson(path.join(stateDir, `archive-${machineId}.json`), { ids: [] });
57
+ return new Set(Array.isArray(doc?.ids) ? doc.ids : []);
58
+ }
59
+
60
+ export async function writeArchiveSnapshot(stateDir, machineId, ids) {
61
+ await writeJson(path.join(stateDir, `archive-${machineId}.json`), {
62
+ version: 1,
63
+ machine: machineId,
64
+ updatedAt: new Date().toISOString(),
65
+ ids: [...ids].sort(),
66
+ });
67
+ }
68
+
69
+ /** Events for the ids that entered or left the archived set since the snapshot. */
70
+ export function diffArchiveEvents(localArchived, previousArchived, machineId, at = new Date().toISOString()) {
71
+ const current = localArchived instanceof Set ? localArchived : new Set(localArchived);
72
+ const events = {};
73
+ for (const id of current) {
74
+ if (!previousArchived.has(id)) events[id] = { state: 'archived', at, by: machineId };
75
+ }
76
+ for (const id of previousArchived) {
77
+ if (!localArchived.has(id)) events[id] = { state: 'active', at, by: machineId };
78
+ }
79
+ return events;
80
+ }
81
+
82
+ /** Merge incoming events; the newest `at` wins per session. */
83
+ export function mergeArchiveEvents(existing, incoming) {
84
+ const merged = { ...existing };
85
+ for (const [id, event] of Object.entries(incoming)) {
86
+ const current = merged[id];
87
+ if (current === undefined || String(event.at) > String(current.at)) merged[id] = event;
88
+ }
89
+ return merged;
90
+ }
91
+
92
+ /** Snapshot of every machine's last recorded archived set, for the pruner. */
93
+ export async function readAllArchiveSnapshots(stateDir) {
94
+ const snapshots = [];
95
+ let names = [];
96
+ try {
97
+ names = await fsp.readdir(stateDir);
98
+ } catch {
99
+ return snapshots;
100
+ }
101
+ for (const name of names) {
102
+ if (!/^archive-.+\.json$/u.test(name)) continue;
103
+ if (name === 'archive-events.json') continue;
104
+ const doc = await readJson(path.join(stateDir, name), { ids: [] });
105
+ if (Array.isArray(doc?.ids)) snapshots.push(new Set(doc.ids));
106
+ }
107
+ return snapshots;
108
+ }
109
+
110
+ /**
111
+ * Keep only events that still matter.
112
+ *
113
+ * An event must survive until **every** machine has observed it: a machine that
114
+ * has not synced yet still holds the old set, and its next merge would undo the
115
+ * change if the intent were already gone. Snapshots are exactly that record —
116
+ * dropping an `active` event early is what let an unarchived session reappear.
117
+ *
118
+ * A grace window keeps recent intent even when snapshots look converged, so a
119
+ * machine that has never synced (no snapshot yet) still receives it.
120
+ */
121
+ export function pruneArchiveEvents(events, keepIds, options = {}) {
122
+ const snapshots = Array.isArray(options.snapshots) ? options.snapshots : [];
123
+ const now = Number.isFinite(options.now) ? options.now : Date.now();
124
+ const graceMs = Math.max(0, Number(options.graceDays ?? 30)) * 24 * 60 * 60 * 1000;
125
+ const kept = {};
126
+ let removed = 0;
127
+ for (const [id, event] of Object.entries(events)) {
128
+ const at = Date.parse(event?.at ?? '');
129
+ const fresh = !Number.isFinite(at) || now - at < graceMs;
130
+ // With no snapshots at all we cannot prove every machine has seen it, so the
131
+ // event stays; otherwise old intents would vanish before a new machine synced.
132
+ const unknownMachines = snapshots.length === 0;
133
+ let keep;
134
+ if (event?.state === 'archived') {
135
+ const learned = !unknownMachines && snapshots.every((snapshot) => snapshot.has(id));
136
+ keep = fresh || !learned;
137
+ } else {
138
+ const stillHeld = unknownMachines || keepIds.has(id) || snapshots.some((snapshot) => snapshot.has(id));
139
+ keep = fresh || stillHeld;
140
+ }
141
+ if (keep) kept[id] = event;
142
+ else removed += 1;
143
+ }
144
+ return { events: kept, removed };
145
+ }
146
+
147
+ /**
148
+ * Apply the merged event table to this machine's archived set.
149
+ *
150
+ * An `active` event releases a local entry; an `archived` event from another
151
+ * machine adds one, so archiving propagates in both directions.
152
+ */
153
+ export function applyArchiveEvents(archived, events) {
154
+ const own = archived instanceof Set ? archived : new Set(archived ?? []);
155
+ const kept = new Set();
156
+ const released = [];
157
+ const added = [];
158
+ for (const id of own) {
159
+ const event = events[id];
160
+ if (event !== undefined && event.state === 'active') released.push(id);
161
+ else kept.add(id);
162
+ }
163
+ for (const [id, event] of Object.entries(events)) {
164
+ if (event?.state !== 'archived') continue;
165
+ if (own.has(id)) continue;
166
+ if (kept.has(id)) continue;
167
+ kept.add(id);
168
+ added.push(id);
169
+ }
170
+ return { kept: [...kept], released, added };
171
+ }
172
+
173
+ /**
174
+ * Fold the archive result into both workspace documents.
175
+ *
176
+ * Exported so the whole rule can be exercised without a running Harness: this is
177
+ * where "archived elsewhere" and "unarchived here" are decided.
178
+ *
179
+ * @returns the ids that were released and how many entries the local document
180
+ * gained or lost compared with `archivedBefore`.
181
+ */
182
+ export function mergeArchivedIntoDocuments(deps) {
183
+ const { localDoc, sharedDoc, archivedBefore, archive, events } = deps;
184
+ const released = new Set(archive?.released ?? []);
185
+ // An active event must also release ids this machine no longer lists: the local
186
+ // document dropped them when the reader unarchived, and without this the union
187
+ // below would add them straight back from the shared document.
188
+ for (const [id, event] of Object.entries(events ?? {})) {
189
+ if (event?.state === 'active') released.add(id);
190
+ }
191
+ const effective = Array.isArray(archive?.archived) ? archive.archived : [];
192
+ for (const doc of [localDoc, sharedDoc]) {
193
+ if (doc === null || doc === undefined) continue;
194
+ doc.global = doc.global ?? {};
195
+ const own = Array.isArray(doc.global.archivedSessionIds) ? doc.global.archivedSessionIds : [];
196
+ const merged = new Set([...own, ...effective].filter((id) => id && !released.has(id)));
197
+ doc.global.archivedSessionIds = [...merged].sort();
198
+ }
199
+ const finalLocal = new Set(localDoc?.global?.archivedSessionIds ?? []);
200
+ let changed = 0;
201
+ for (const id of finalLocal) if (!archivedBefore.has(id)) changed += 1;
202
+ for (const id of archivedBefore) if (!finalLocal.has(id)) changed += 1;
203
+ return { changed, released, finalLocal };
204
+ }
205
+
206
+ /**
207
+ * Run the archive half of a sync.
208
+ * @returns the effective archived list plus what changed.
209
+ */
210
+ export async function syncArchiveState(deps) {
211
+ const { stateDir, machineId, apply = true } = deps;
212
+ const localArchived = deps.localArchived instanceof Set ? deps.localArchived : new Set(deps.localArchived ?? []);
213
+ const previous = await readArchiveSnapshot(stateDir, machineId);
214
+ const existing = await readArchiveEvents(stateDir);
215
+ const incoming = diffArchiveEvents(localArchived, previous, machineId);
216
+ const merged = mergeArchiveEvents(existing, incoming);
217
+ if (apply && Object.keys(incoming).length > 0) await writeArchiveEvents(stateDir, merged);
218
+ const { kept, released, added } = applyArchiveEvents(localArchived, merged);
219
+ if (apply) await writeArchiveSnapshot(stateDir, machineId, kept);
220
+ // Any difference against the local set came from the share, so it needs a
221
+ // restart to show; a purely local change does not.
222
+ return { archived: kept, released, added, changed: released.length + added.length, emitted: incoming, events: merged };
223
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Atomic write helper.
3
+ *
4
+ * Windows rename replaces an existing file, so there is no need to delete the
5
+ * target first — doing that only opens a window where the file does not exist.
6
+ * The temporary name carries a random suffix so two writers can never collide.
7
+ */
8
+ import { promises as fsp } from 'node:fs';
9
+ import { randomUUID } from 'node:crypto';
10
+
11
+ export async function writeFileAtomic(file, data, encoding) {
12
+ const temporary = `${file}.${randomUUID()}.tmp`;
13
+ await fsp.writeFile(temporary, data, encoding);
14
+ try {
15
+ await fsp.rename(temporary, file);
16
+ } catch (error) {
17
+ // Some filesystems refuse to replace; fall back to delete+rename once.
18
+ if (error?.code !== 'EEXIST' && error?.code !== 'EPERM' && error?.code !== 'EACCES') throw error;
19
+ await fsp.rm(file, { force: true }).catch(() => {});
20
+ await fsp.rename(temporary, file);
21
+ }
22
+ return file;
23
+ }
24
+
25
+ export async function writeJsonAtomic(file, value) {
26
+ return writeFileAtomic(file, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
27
+ }
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Attachment store sync for the pure-JS engine.
3
+ *
4
+ * Attachment objects are content-addressed and immutable: the same sha256 means
5
+ * the same bytes, and a session log only references them. So the sync is a pure
6
+ * "fill the gaps" pass in both directions — never a delete. `request-images/`
7
+ * (rebuildable cache) and `tmp/` are deliberately out of scope.
8
+ */
9
+ import { promises as fsp } from 'node:fs';
10
+ import { randomUUID } from 'node:crypto';
11
+ import path from 'node:path';
12
+
13
+ const SUBTREES = ['objects', 'file-objects', 'files'];
14
+
15
+ async function readDirSafe(dir) {
16
+ try {
17
+ return await fsp.readdir(dir, { withFileTypes: true });
18
+ } catch {
19
+ return [];
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Index one attachments root.
25
+ * `files/` nests one more level (bucket/sha/<name>) than the other two.
26
+ */
27
+ export async function indexAttachments(root) {
28
+ const map = new Map();
29
+ for (const subtree of SUBTREES) {
30
+ const base = path.join(root, subtree);
31
+ for (const bucket of await readDirSafe(base)) {
32
+ if (!bucket.isDirectory()) continue;
33
+ const bucketDir = path.join(base, bucket.name);
34
+ for (const entry of await readDirSafe(bucketDir)) {
35
+ if (entry.isDirectory()) {
36
+ if (subtree !== 'files') continue;
37
+ const inner = path.join(bucketDir, entry.name);
38
+ for (const file of await readDirSafe(inner)) {
39
+ if (!file.isFile()) continue;
40
+ const full = path.join(inner, file.name);
41
+ const stat = await fsp.stat(full).catch(() => undefined);
42
+ if (stat !== undefined) map.set(`${subtree}/${bucket.name}/${entry.name}/${file.name}`, { file: full, mtime: stat.mtimeMs, size: stat.size });
43
+ }
44
+ continue;
45
+ }
46
+ const full = path.join(bucketDir, entry.name);
47
+ const stat = await fsp.stat(full).catch(() => undefined);
48
+ if (stat !== undefined) map.set(`${subtree}/${bucket.name}/${entry.name}`, { file: full, mtime: stat.mtimeMs, size: stat.size });
49
+ }
50
+ }
51
+ }
52
+ return map;
53
+ }
54
+
55
+ async function copyObject(source, target, mtimeMs) {
56
+ await fsp.mkdir(path.dirname(target), { recursive: true });
57
+ const temporary = `${target}.${randomUUID()}.tmp`;
58
+ await fsp.copyFile(source, temporary);
59
+ await fsp.rename(temporary, target).catch(async () => {
60
+ await fsp.rename(temporary, target);
61
+ });
62
+ if (Number.isFinite(mtimeMs)) await fsp.utimes(target, mtimeMs / 1000, mtimeMs / 1000).catch(() => {});
63
+ }
64
+
65
+ /**
66
+ * Fill missing objects on both sides.
67
+ * @returns counters plus how many objects existed on each side.
68
+ */
69
+ export async function syncAttachments(deps) {
70
+ const { localRoot, sharedRoot, apply = true } = deps;
71
+ const local = await indexAttachments(localRoot);
72
+ const shared = await indexAttachments(sharedRoot);
73
+
74
+ let pushed = 0;
75
+ let pulled = 0;
76
+ let skipped = 0;
77
+ const failed = [];
78
+
79
+ for (const [rel, entry] of local) {
80
+ if (shared.has(rel)) {
81
+ skipped += 1;
82
+ continue;
83
+ }
84
+ try {
85
+ if (apply) await copyObject(entry.file, path.join(sharedRoot, ...rel.split('/')), entry.mtime);
86
+ pushed += 1;
87
+ } catch (error) {
88
+ failed.push({ path: rel, error: String(error?.message ?? error) });
89
+ }
90
+ }
91
+ for (const [rel, entry] of shared) {
92
+ if (local.has(rel)) continue;
93
+ try {
94
+ if (apply) await copyObject(entry.file, path.join(localRoot, ...rel.split('/')), entry.mtime);
95
+ pulled += 1;
96
+ } catch (error) {
97
+ failed.push({ path: rel, error: String(error?.message ?? error) });
98
+ }
99
+ }
100
+
101
+ return { pushed, pulled, skipped, failed, localCount: local.size, sharedCount: shared.size };
102
+ }
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Configuration file sync for the pure-JS engine.
3
+ *
4
+ * The synced set is deliberately small — `profiles/<p>/cordis.patch.yml`,
5
+ * `skills/`, `AGENTS.md`, `.credentials.yaml` — because everything else is either
6
+ * machine-specific or rewritten by the app at startup. Per file the newer side
7
+ * wins; a pulled text file has foreign home paths rewritten to this user, and a
8
+ * `.json` payload is parsed before it is kept (the app may be mid-write).
9
+ */
10
+ import { promises as fsp } from 'node:fs';
11
+ import path from 'node:path';
12
+ import { createHash, randomUUID } from 'node:crypto';
13
+
14
+ export function configItems(profile = 'desktop') {
15
+ return [
16
+ `profiles/${profile}/cordis.patch.yml`,
17
+ 'skills',
18
+ 'AGENTS.md',
19
+ '.credentials.yaml',
20
+ ];
21
+ }
22
+
23
+ async function readDirSafe(dir) {
24
+ try {
25
+ return await fsp.readdir(dir, { withFileTypes: true });
26
+ } catch {
27
+ return [];
28
+ }
29
+ }
30
+
31
+ /** Relative path -> { file, mtime } for one config item. */
32
+ export async function indexConfigItem(base, relPath) {
33
+ const map = new Map();
34
+ const root = path.join(base, ...relPath.split('/'));
35
+ let stat;
36
+ try { stat = await fsp.stat(root); } catch { return map; }
37
+ if (stat.isFile()) {
38
+ map.set(relPath, { file: root, mtime: stat.mtimeMs, size: stat.size });
39
+ return map;
40
+ }
41
+ async function walk(dir, rel) {
42
+ for (const entry of await readDirSafe(dir)) {
43
+ const childRel = `${rel}/${entry.name}`;
44
+ const full = path.join(dir, entry.name);
45
+ if (entry.isDirectory()) {
46
+ await walk(full, childRel);
47
+ continue;
48
+ }
49
+ try {
50
+ const info = await fsp.stat(full);
51
+ map.set(childRel, { file: full, mtime: info.mtimeMs, size: info.size });
52
+ } catch {
53
+ // A file that vanished mid-scan is simply absent.
54
+ }
55
+ }
56
+ }
57
+ await walk(root, relPath);
58
+ return map;
59
+ }
60
+
61
+ /** Index every synced config item. */
62
+ export async function indexConfig(base, profile = 'desktop') {
63
+ const map = new Map();
64
+ for (const item of configItems(profile)) {
65
+ for (const [rel, entry] of await indexConfigItem(base, item)) map.set(rel, entry);
66
+ }
67
+ return map;
68
+ }
69
+
70
+ /**
71
+ * Replace another user's home directory with this machine's user.
72
+ * Handles both separators, since config files are hand-edited.
73
+ */
74
+ export function rewriteUserPath(text, currentUser) {
75
+ if (typeof text !== 'string' || currentUser === '') return text;
76
+ return text.replace(/([A-Za-z]:[\\/]Users[\\/])([^\\/\s"'`:]+)/gu, (match, prefix, user) => (
77
+ user.toLowerCase() === currentUser.toLowerCase() ? match : `${prefix}${currentUser}`
78
+ ));
79
+ }
80
+
81
+ async function copyFile(source, target, mtimeMs) {
82
+ await fsp.mkdir(path.dirname(target), { recursive: true });
83
+ const temporary = `${target}.${randomUUID()}.tmp`;
84
+ await fsp.copyFile(source, temporary);
85
+ await fsp.rename(temporary, target);
86
+ if (Number.isFinite(mtimeMs)) await fsp.utimes(target, mtimeMs / 1000, mtimeMs / 1000).catch(() => {});
87
+ }
88
+
89
+ // WebDAV keeps timestamps to the second, so anything inside one second is the
90
+ // same revision; comparing raw milliseconds only produces copies.
91
+ const MTIME_TOLERANCE_MS = 1000;
92
+
93
+ /** Only these extensions get the user-path rewrite; everything else is copied byte for byte. */
94
+ const TEXT_EXTENSIONS = new Set([
95
+ '.md', '.markdown', '.txt', '.yml', '.yaml', '.json', '.jsonl', '.toml', '.ini', '.cfg',
96
+ '.ps1', '.psm1', '.sh', '.bat', '.cmd', '.py', '.js', '.mjs', '.cjs', '.ts', '.html', '.css', '.xml',
97
+ ]);
98
+
99
+ function isTextConfig(rel) {
100
+ return TEXT_EXTENSIONS.has(path.extname(rel).toLowerCase());
101
+ }
102
+
103
+ async function sameContent(a, b, sizeA, sizeB) {
104
+ if (Number.isFinite(sizeA) && Number.isFinite(sizeB) && sizeA !== sizeB) return false;
105
+ try {
106
+ const [left, right] = await Promise.all([fsp.readFile(a), fsp.readFile(b)]);
107
+ return createHash('sha256').update(left).digest('hex') === createHash('sha256').update(right).digest('hex');
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+
113
+ async function isValidJson(file) {
114
+ try {
115
+ JSON.parse(await fsp.readFile(file, 'utf8'));
116
+ return true;
117
+ } catch {
118
+ return false;
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Sync the config set in both directions.
124
+ * @returns counters plus the relative paths that were rejected as invalid JSON.
125
+ */
126
+ export async function syncConfigFiles(deps) {
127
+ const { localBase, sharedBase, profile = 'desktop', currentUser = '', stagingDir = '' } = deps;
128
+ const local = await indexConfig(localBase, profile);
129
+ const shared = await indexConfig(sharedBase, profile);
130
+
131
+ let copied = 0;
132
+ let skipped = 0;
133
+ const invalid = [];
134
+ const details = [];
135
+
136
+ const push = async (rel, entry, other) => {
137
+ const target = path.join(sharedBase, ...rel.split('/'));
138
+ await copyFile(entry.file, target, entry.mtime);
139
+ if (rel.endsWith('.json') && !(await isValidJson(target))) {
140
+ // The app may be mid-write; never keep a half-written document.
141
+ await fsp.rm(target, { force: true }).catch(() => {});
142
+ invalid.push(rel);
143
+ return;
144
+ }
145
+ details.push({ action: 'push', rel, deltaMs: other === undefined ? null : Math.round(entry.mtime - other.mtime) });
146
+ copied += 1;
147
+ };
148
+
149
+ /** The app rewrites its own patch file, so a live write is lost; stage it instead. */
150
+ const isProfilePatch = (rel) => rel === `profiles/${profile}/cordis.patch.yml`;
151
+
152
+ const pull = async (rel, entry, other) => {
153
+ if (isProfilePatch(rel) && stagingDir !== '') {
154
+ const staged = path.join(stagingDir, ...rel.split('/'));
155
+ await fsp.mkdir(path.dirname(staged), { recursive: true });
156
+ await fsp.copyFile(entry.file, staged);
157
+ if (Number.isFinite(entry.mtime)) await fsp.utimes(staged, entry.mtime / 1000, entry.mtime / 1000).catch(() => {});
158
+ details.push({ action: 'staged', rel, deltaMs: other === undefined ? null : Math.round(entry.mtime - other.mtime) });
159
+ copied += 1;
160
+ return;
161
+ }
162
+ const target = path.join(localBase, ...rel.split('/'));
163
+ await copyFile(entry.file, target, entry.mtime);
164
+ if (rel.endsWith('.json') === false && isTextConfig(rel)) {
165
+ const text = await fsp.readFile(target, 'utf8').catch(() => '');
166
+ const rewritten = rewriteUserPath(text, currentUser);
167
+ if (rewritten !== text) {
168
+ await fsp.writeFile(target, rewritten, 'utf8');
169
+ // Rewriting the body resets mtime to "now"; restore the source stamp or
170
+ // the next run would push the file straight back.
171
+ if (Number.isFinite(entry.mtime)) await fsp.utimes(target, entry.mtime / 1000, entry.mtime / 1000).catch(() => {});
172
+ }
173
+ }
174
+ if (rel.endsWith('.json') && !(await isValidJson(target))) {
175
+ // The app may be mid-write; never keep a half-written document.
176
+ await fsp.rm(target, { force: true }).catch(() => {});
177
+ invalid.push(rel);
178
+ return;
179
+ }
180
+ details.push({ action: 'pull', rel, deltaMs: other === undefined ? null : Math.round(entry.mtime - other.mtime) });
181
+ copied += 1;
182
+ };
183
+
184
+ const align = async (a, b, newerMtime) => {
185
+ await fsp.utimes(a, newerMtime / 1000, newerMtime / 1000).catch(() => {});
186
+ await fsp.utimes(b, newerMtime / 1000, newerMtime / 1000).catch(() => {});
187
+ };
188
+
189
+ for (const [rel, entry] of local) {
190
+ const other = shared.get(rel);
191
+ if (other === undefined) {
192
+ await push(rel, entry, other);
193
+ continue;
194
+ }
195
+ const changed = entry.mtime > other.mtime + MTIME_TOLERANCE_MS || other.mtime > entry.mtime + MTIME_TOLERANCE_MS;
196
+ if (!changed) {
197
+ skipped += 1;
198
+ continue;
199
+ }
200
+ if (await sameContent(entry.file, other.file, entry.size, other.size)) {
201
+ // Same bytes, different stamps: keep the newer one and stop reporting it.
202
+ await align(entry.file, other.file, Math.max(entry.mtime, other.mtime));
203
+ skipped += 1;
204
+ continue;
205
+ }
206
+ // `entry` is this machine's copy, `other` is the share: a pull must copy the
207
+ // share's file, otherwise the "download" writes the local copy to itself and
208
+ // the pair never converges.
209
+ if (entry.mtime > other.mtime) await push(rel, entry, other);
210
+ else await pull(rel, other, entry);
211
+ }
212
+ for (const [rel, entry] of shared) {
213
+ if (local.has(rel)) continue;
214
+ await pull(rel, entry, undefined);
215
+ }
216
+
217
+ return { copied, skipped, invalid, details };
218
+ }