@xsok/dsh-enhanced 0.0.0-stage → 0.2.2-4
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.
- package/CHANGELOG.md +25 -0
- package/LICENSE +21 -0
- package/README.md +163 -2
- package/client.js +2876 -0
- package/cordis.patch.yml +4 -0
- package/host/engine/archive.js +134 -0
- package/host/engine/atomic.js +27 -0
- package/host/engine/attachments.js +102 -0
- package/host/engine/config.js +214 -0
- package/host/engine/index.js +323 -0
- package/host/engine/ledger.js +108 -0
- package/host/engine/paths.js +81 -0
- package/host/engine/pluginlist.js +81 -0
- package/host/engine/projcache.js +165 -0
- package/host/engine/prune.js +187 -0
- package/host/engine/scan.js +177 -0
- package/host/engine/session.js +138 -0
- package/host/engine/sessions.js +346 -0
- package/host/engine/workspace.js +223 -0
- package/host/engine/zstd.js +91 -0
- package/host/envcheck.js +288 -0
- package/host/mirror.js +502 -0
- package/host/move.js +196 -0
- package/host/overwrite.js +305 -0
- package/host/restart.js +158 -0
- package/host/schedule.js +296 -0
- package/host/search.js +182 -0
- package/host/sync.js +593 -0
- package/host/trash.js +738 -0
- package/host/trashsync.js +204 -0
- package/host/webdav.js +429 -0
- package/icon.svg +1 -0
- package/index.js +313 -0
- package/locale/en.json +68 -0
- package/locale/zh.json +68 -0
- package/package.json +71 -4
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
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
|
+
/**
|
|
93
|
+
* Keep only events that still matter: an `archived` event states current intent
|
|
94
|
+
* for every machine, while an `active` event stops mattering once no document
|
|
95
|
+
* lists that session as archived. Without this the table grows forever.
|
|
96
|
+
*/
|
|
97
|
+
export function pruneArchiveEvents(events, keepIds) {
|
|
98
|
+
const kept = {};
|
|
99
|
+
let removed = 0;
|
|
100
|
+
for (const [id, event] of Object.entries(events)) {
|
|
101
|
+
if (event?.state === 'archived' || keepIds.has(id)) kept[id] = event;
|
|
102
|
+
else removed += 1;
|
|
103
|
+
}
|
|
104
|
+
return { events: kept, removed };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Drop ids whose latest event says `active`. */
|
|
108
|
+
export function applyArchiveEvents(archived, events) {
|
|
109
|
+
const kept = [];
|
|
110
|
+
const released = [];
|
|
111
|
+
for (const id of archived) {
|
|
112
|
+
const event = events[id];
|
|
113
|
+
if (event !== undefined && event.state === 'active') released.push(id);
|
|
114
|
+
else kept.push(id);
|
|
115
|
+
}
|
|
116
|
+
return { kept, released };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Run the archive half of a sync.
|
|
121
|
+
* @returns the effective archived list plus what changed.
|
|
122
|
+
*/
|
|
123
|
+
export async function syncArchiveState(deps) {
|
|
124
|
+
const { stateDir, machineId, apply = true } = deps;
|
|
125
|
+
const localArchived = deps.localArchived instanceof Set ? deps.localArchived : new Set(deps.localArchived ?? []);
|
|
126
|
+
const previous = await readArchiveSnapshot(stateDir, machineId);
|
|
127
|
+
const existing = await readArchiveEvents(stateDir);
|
|
128
|
+
const incoming = diffArchiveEvents(localArchived, previous, machineId);
|
|
129
|
+
const merged = mergeArchiveEvents(existing, incoming);
|
|
130
|
+
if (apply && Object.keys(incoming).length > 0) await writeArchiveEvents(stateDir, merged);
|
|
131
|
+
const { kept, released } = applyArchiveEvents(localArchived, merged);
|
|
132
|
+
if (apply) await writeArchiveSnapshot(stateDir, machineId, kept);
|
|
133
|
+
return { archived: kept, released, emitted: incoming, events: merged };
|
|
134
|
+
}
|
|
@@ -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,214 @@
|
|
|
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
|
+
details.push({ action: 'staged', rel, deltaMs: other === undefined ? null : Math.round(entry.mtime - other.mtime) });
|
|
158
|
+
copied += 1;
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const target = path.join(localBase, ...rel.split('/'));
|
|
162
|
+
await copyFile(entry.file, target, entry.mtime);
|
|
163
|
+
if (rel.endsWith('.json') === false && isTextConfig(rel)) {
|
|
164
|
+
const text = await fsp.readFile(target, 'utf8').catch(() => '');
|
|
165
|
+
const rewritten = rewriteUserPath(text, currentUser);
|
|
166
|
+
if (rewritten !== text) {
|
|
167
|
+
await fsp.writeFile(target, rewritten, 'utf8');
|
|
168
|
+
// Rewriting the body resets mtime to "now"; restore the source stamp or
|
|
169
|
+
// the next run would push the file straight back.
|
|
170
|
+
if (Number.isFinite(entry.mtime)) await fsp.utimes(target, entry.mtime / 1000, entry.mtime / 1000).catch(() => {});
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (rel.endsWith('.json') && !(await isValidJson(target))) {
|
|
174
|
+
// The app may be mid-write; never keep a half-written document.
|
|
175
|
+
await fsp.rm(target, { force: true }).catch(() => {});
|
|
176
|
+
invalid.push(rel);
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
details.push({ action: 'pull', rel, deltaMs: other === undefined ? null : Math.round(entry.mtime - other.mtime) });
|
|
180
|
+
copied += 1;
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
const align = async (a, b, newerMtime) => {
|
|
184
|
+
await fsp.utimes(a, newerMtime / 1000, newerMtime / 1000).catch(() => {});
|
|
185
|
+
await fsp.utimes(b, newerMtime / 1000, newerMtime / 1000).catch(() => {});
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
for (const [rel, entry] of local) {
|
|
189
|
+
const other = shared.get(rel);
|
|
190
|
+
if (other === undefined) {
|
|
191
|
+
await push(rel, entry, other);
|
|
192
|
+
continue;
|
|
193
|
+
}
|
|
194
|
+
const changed = entry.mtime > other.mtime + MTIME_TOLERANCE_MS || other.mtime > entry.mtime + MTIME_TOLERANCE_MS;
|
|
195
|
+
if (!changed) {
|
|
196
|
+
skipped += 1;
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (await sameContent(entry.file, other.file, entry.size, other.size)) {
|
|
200
|
+
// Same bytes, different stamps: keep the newer one and stop reporting it.
|
|
201
|
+
await align(entry.file, other.file, Math.max(entry.mtime, other.mtime));
|
|
202
|
+
skipped += 1;
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
205
|
+
if (entry.mtime > other.mtime) await push(rel, entry, other);
|
|
206
|
+
else await pull(rel, entry, other);
|
|
207
|
+
}
|
|
208
|
+
for (const [rel, entry] of shared) {
|
|
209
|
+
if (local.has(rel)) continue;
|
|
210
|
+
await pull(rel, entry, undefined);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return { copied, skipped, invalid, details };
|
|
214
|
+
}
|