@jc_stack/ez-library 0.1.0-beta.16 → 0.1.0-beta.19

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/src/indexer.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
- import { atomic, digest, hash, jsonBytes, safePath, settings } from './store.mjs';
3
+ import { atomic, hash, jsonBytes, safePath, scanDigest, settings } from './store.mjs';
4
4
  import { native, qmd, succeeded } from './native.mjs';
5
5
 
6
6
  export async function inventory(directory, relative = '', { includeHidden = false } = {}) {
@@ -9,7 +9,7 @@ export async function inventory(directory, relative = '', { includeHidden = fals
9
9
  if (!includeHidden && item.name.startsWith('.')) continue;
10
10
  const name = relative + item.name, file = path.join(directory, item.name);
11
11
  if (item.isDirectory()) result.push(...await inventory(file, name + '/', { includeHidden }));
12
- else if (item.isFile()) result.push({ path: name, ...(await digest(file)) });
12
+ else if (item.isFile()) result.push({ path: name, ...(await scanDigest(file)) });
13
13
  else throw Error('Unsupported symlink or special file in Library');
14
14
  }
15
15
  return result;
@@ -33,7 +33,7 @@ export async function gitInventory(root) {
33
33
  if (!stat) { absent = true; break; }
34
34
  if (stat.isSymbolicLink() || !(i === parts.length - 1 ? stat.isFile() : stat.isDirectory())) throw Error('Unsupported symlink or special file in Library');
35
35
  }
36
- if (!absent) files.push({ path: name, ...(await digest(file)) });
36
+ if (!absent) files.push({ path: name, ...(await scanDigest(file)) });
37
37
  }
38
38
  return files.sort((a, b) => a.path.localeCompare(b.path));
39
39
  }
package/src/store.mjs CHANGED
@@ -3,6 +3,8 @@ import { createReadStream, createWriteStream, constants } from 'node:fs';
3
3
  import { pipeline } from 'node:stream/promises';
4
4
  import { Transform } from 'node:stream';
5
5
  import path from 'node:path';
6
+ import { hostname } from 'node:os';
7
+ import { setTimeout as sleep } from 'node:timers/promises';
6
8
  import { createHash, randomUUID } from 'node:crypto';
7
9
 
8
10
  export class LibraryError extends Error {
@@ -12,6 +14,8 @@ export const fail = (code, message) => { throw new LibraryError(code, message);
12
14
  export const hash = bytes => createHash('sha256').update(bytes).digest('hex');
13
15
  export const MAX_FILE_BYTES = 512 * 1024 * 1024;
14
16
  export const MAX_READ_BYTES = 512 * 1024;
17
+ export const MAX_REPLACE_BYTES = 256 * 1024;
18
+ const MAX_TEXT_BYTES = 8 * 1024 * 1024;
15
19
  export const defaults = () => ({ schemaVersion: 1, storage: { mode: 'local' }, backup: { mode: 'off' } });
16
20
 
17
21
  function keys(value, allowed) {
@@ -78,26 +82,73 @@ export async function initialize(root) {
78
82
  }
79
83
  return root;
80
84
  }
81
- export async function locked(root, fn) {
85
+ // A live writer records itself in the lock and others wait for it briefly. A lock
86
+ // with no owner is an interrupted operation and fails closed.
87
+ const LOCK_WAIT_MS = 60_000;
88
+ const OWNERLESS_GRACE_MS = 1_000;
89
+ async function lockOwner(lock) {
90
+ try { return JSON.parse(await fs.readFile(path.join(lock, 'owner'), 'utf8')); }
91
+ catch (e) { if (e.code === 'ENOENT' || e instanceof SyntaxError) return null; throw e; }
92
+ }
93
+ async function acquire(lock, signal) {
94
+ const started = Date.now();
95
+ let ownerless = null;
96
+ for (;;) {
97
+ signal?.throwIfAborted();
98
+ try {
99
+ await fs.mkdir(lock, { mode: 0o700 });
100
+ try { await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: process.pid, host: hostname(), at: new Date().toISOString() }), { mode: 0o600, flag: 'wx' }); }
101
+ catch (e) { await fs.rmdir(lock); throw e; }
102
+ return;
103
+ } catch (e) { if (e.code !== 'EEXIST') throw e; }
104
+ const owner = await lockOwner(lock);
105
+ if (owner?.pid === process.pid && owner?.host === hostname()) fail('BUSY', 'Writer lock is held by this process');
106
+ ownerless = owner ? null : ownerless ?? Date.now();
107
+ if (ownerless !== null && Date.now() - ownerless >= OWNERLESS_GRACE_MS)
108
+ fail('BUSY', 'Writer lock exists without an owner; confirm no command is active before recovering an interrupted operation');
109
+ if (Date.now() - started >= LOCK_WAIT_MS)
110
+ fail('BUSY', `Writer lock held by pid ${owner?.pid} on ${owner?.host} since ${owner?.at}; confirm it is active before recovering an interrupted operation`);
111
+ await sleep(100 + Math.random() * 150, undefined, { signal });
112
+ }
113
+ }
114
+ export async function locked(root, fn, { signal } = {}) {
82
115
  root = await rootDir(root, true);
83
116
  const lock = path.join(root, '.writer-lock');
84
- await fs.mkdir(lock, { mode: 0o700 }).catch(e => {
85
- if (e.code === 'EEXIST') fail('BUSY', 'Writer lock exists; confirm no command is active before recovering an interrupted operation');
86
- throw e;
87
- });
117
+ await acquire(lock, signal);
88
118
  try { return await fn(await initialize(root)); }
89
- finally { await fs.rmdir(lock); }
119
+ finally { await fs.rm(path.join(lock, 'owner'), { force: true }); await fs.rmdir(lock); }
90
120
  }
91
- export async function digest(file) {
121
+ async function opened(file, read) {
92
122
  const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
93
123
  try {
94
- const st = await handle.stat();
124
+ const st = await handle.stat({ bigint: true });
95
125
  if (!st.isFile()) fail('UNSAFE_PATH', 'Expected a regular file');
96
- const sha = createHash('sha256'); let bytes = 0;
97
- for await (const chunk of handle.createReadStream({ autoClose: false })) { sha.update(chunk); bytes += chunk.length; }
98
- return { bytes, sha256: sha.digest('hex') };
126
+ return await read(handle, st);
99
127
  } finally { await handle.close(); }
100
128
  }
129
+ async function contentDigest(handle) {
130
+ const sha = createHash('sha256'); let bytes = 0;
131
+ for await (const chunk of handle.createReadStream({ autoClose: false })) { sha.update(chunk); bytes += chunk.length; }
132
+ return { bytes, sha256: sha.digest('hex') };
133
+ }
134
+ export const digest = file => opened(file, contentDigest);
135
+
136
+ // The resident worker inventories unchanged originals every cycle. Within one
137
+ // process, reuse a digest only while device, inode, size, mtime and ctime are
138
+ // identical, and never for files changed within the last two seconds.
139
+ const scanned = new Map();
140
+ export const scanDigest = file => opened(file, async (handle, st) => {
141
+ const key = `${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`;
142
+ const known = scanned.get(file);
143
+ if (known?.key === key) return { ...known.value };
144
+ const value = await contentDigest(handle);
145
+ const changed = st.mtimeNs > st.ctimeNs ? st.mtimeNs : st.ctimeNs;
146
+ if (BigInt(Date.now()) * 1000000n - changed > 2000000000n) {
147
+ if (scanned.size >= 100000) scanned.clear();
148
+ scanned.set(file, { key, value });
149
+ }
150
+ return { ...value };
151
+ });
101
152
  export async function readRange(file, { offset, length, expected }) {
102
153
  if (!/^(0|[1-9][0-9]*)$/.test(offset ?? '') || !/^[1-9][0-9]*$/.test(length ?? '') ||
103
154
  !Number.isSafeInteger(Number(offset)) || !Number.isSafeInteger(Number(length)) ||
@@ -144,7 +195,7 @@ export async function settings(root) {
144
195
 
145
196
  // Receipts record intent before installation. Readback determines stored/changed/missing,
146
197
  // including after interruption between the atomic receipt and file renames.
147
- export async function put(root, relative, input, { key, expected, kind = 'file', maxBytes = MAX_FILE_BYTES } = {}) {
198
+ export async function put(root, relative, input, { key, expected, kind = 'file', maxBytes = MAX_FILE_BYTES, source } = {}) {
148
199
  if (expected !== 'new' && !/^[a-f0-9]{64}$/.test(expected || '')) fail('INVALID', 'Supply --expected new or the current SHA-256');
149
200
  if (!['file', 'settings'].includes(kind)) fail('INVALID', 'Unknown write kind');
150
201
  return locked(root, async root => {
@@ -161,7 +212,8 @@ export async function put(root, relative, input, { key, expected, kind = 'file',
161
212
  if (bytes > maxBytes) return cb(new LibraryError('TOO_LARGE', `Input exceeds ${maxBytes} bytes`));
162
213
  sha.update(chunk); cb(null, chunk);
163
214
  } }), createWriteStream(temp, { flags: 'wx', mode: 0o600 }));
164
- const request = { kind, path: kind === 'settings' ? 'settings.json' : relative, bytes, sha256: sha.digest('hex'), expected };
215
+ const request = { kind, path: kind === 'settings' ? 'settings.json' : relative, bytes, sha256: sha.digest('hex'), expected,
216
+ ...(source ? { source } : {}) };
165
217
  const oldReceipt = await fs.readFile(receiptFile, 'utf8').then(JSON.parse).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
166
218
  if (oldReceipt && JSON.stringify(oldReceipt) !== JSON.stringify(request)) fail('KEY_REUSED', 'Operation key was already used with different content or preconditions');
167
219
  const before = await current(target);
@@ -183,6 +235,7 @@ export async function put(root, relative, input, { key, expected, kind = 'file',
183
235
  export async function operation(root, key) {
184
236
  const receiptFile = await safePath(root, path.relative(root, operationPath(root, key)));
185
237
  const receipt = JSON.parse(await fs.readFile(receiptFile, 'utf8'));
238
+ if (receipt.kind === 'replace') return replacementView(root, receipt);
186
239
  if (['move', 'remove'].includes(receipt.kind)) {
187
240
  const source = await current(await safePath(root, 'files/' + receipt.path));
188
241
  const target = receipt.to ? await current(await safePath(root, 'files/' + receipt.to)) : null;
@@ -194,6 +247,81 @@ export async function operation(root, key) {
194
247
  return { ...receipt, state: !now ? 'missing' : now.sha256 === receipt.sha256 ? 'stored' : 'changed' };
195
248
  }
196
249
 
250
+ const uniquePosition = (text, part) => {
251
+ const at = text.indexOf(part);
252
+ return at >= 0 && text.indexOf(part, at + 1) < 0 ? at : -1;
253
+ };
254
+ function validateReplacement(value) {
255
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
256
+ Object.keys(value).some(key => !['before', 'after'].includes(key)) ||
257
+ typeof value.before !== 'string' || !value.before || typeof value.after !== 'string' ||
258
+ !value.after || value.before === value.after ||
259
+ Buffer.byteLength(JSON.stringify(value)) > MAX_REPLACE_BYTES) {
260
+ fail('INVALID', 'Supply distinct nonempty before/after strings in at most 256 KiB of JSON');
261
+ }
262
+ for (const text of [value.before, value.after]) {
263
+ if (Buffer.from(text).toString('utf8') !== text) fail('INVALID', 'Replacement must be valid UTF-8 text');
264
+ }
265
+ }
266
+ async function readText(file) {
267
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
268
+ try {
269
+ const stat = await handle.stat();
270
+ if (!stat.isFile()) fail('UNSAFE_PATH', 'Expected a regular text file');
271
+ if (stat.size > MAX_TEXT_BYTES) fail('TOO_LARGE', 'Text replacement is limited to 8 MiB files');
272
+ const chunks = []; let bytes = 0;
273
+ for await (const chunk of handle.createReadStream({ autoClose: false })) {
274
+ bytes += chunk.length;
275
+ if (bytes > MAX_TEXT_BYTES) fail('TOO_LARGE', 'Text replacement is limited to 8 MiB files');
276
+ chunks.push(chunk);
277
+ }
278
+ const data = Buffer.concat(chunks), text = data.toString('utf8');
279
+ if (!Buffer.from(text).equals(data)) fail('INVALID', 'Text replacement requires valid UTF-8');
280
+ return { text, bytes, sha256: hash(data) };
281
+ } finally { await handle.close(); }
282
+ }
283
+ async function replacementView(root, receipt) {
284
+ validateReplacement({ before: receipt.before, after: receipt.after });
285
+ const file = await safePath(root, 'files/' + receipt.path);
286
+ const now = await readText(file).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
287
+ return { kind: 'replace', path: receipt.path, beforeSha256: hash(receipt.before), afterSha256: hash(receipt.after),
288
+ state: !now ? 'missing' : uniquePosition(now.text, receipt.after) >= 0 ? 'stored' : 'changed',
289
+ ...(now ? { bytes: now.bytes, sha256: now.sha256 } : {}) };
290
+ }
291
+
292
+ // Exact literal replacement is a scoped compare-and-swap, not a Markdown merge.
293
+ // The caller supplies its complete unique block. Unrelated bytes are read under
294
+ // the existing writer lock and retained, including other callers' recent edits.
295
+ export async function replaceText(root, relative, replacement, { key } = {}) {
296
+ validateReplacement(replacement);
297
+ if (!relative || relative === 'LIBRARY_SYNC_ACCESS') fail('INVALID', 'Supply a non-reserved file path');
298
+ return locked(root, async root => {
299
+ const target = await safePath(root, 'files/' + relative);
300
+ const receiptFile = await safePath(root, path.relative(root, operationPath(root, key)));
301
+ const request = { kind: 'replace', path: relative, before: replacement.before, after: replacement.after };
302
+ const old = await fs.readFile(receiptFile, 'utf8').then(JSON.parse).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
303
+ if (old && JSON.stringify(old) !== JSON.stringify(request)) fail('KEY_REUSED', 'Operation key belongs to a different replacement');
304
+ if (old) {
305
+ const observed = await replacementView(root, old);
306
+ if (observed.state === 'stored') return { ...observed, replay: true };
307
+ }
308
+ const before = await readText(target);
309
+ const at = uniquePosition(before.text, replacement.before);
310
+ if (at < 0) fail('CONFLICT', 'Expected text is absent or ambiguous; re-read the owning block');
311
+ const next = before.text.slice(0, at) + replacement.after + before.text.slice(at + replacement.before.length);
312
+ if (Buffer.byteLength(next) > MAX_TEXT_BYTES) fail('TOO_LARGE', 'Replacement exceeds the 8 MiB text limit');
313
+ if (uniquePosition(next, replacement.after) < 0) fail('CONFLICT', 'Resulting text is ambiguous; use a larger unique block');
314
+ const history = await safePath(root, 'history/' + before.sha256);
315
+ await fs.copyFile(target, history, constants.COPYFILE_EXCL).catch(error => { if (error.code !== 'EEXIST') throw error; });
316
+ await fs.chmod(history, 0o600);
317
+ await atomic(receiptFile, jsonBytes(request));
318
+ await atomic(target, next);
319
+ const after = await replacementView(root, request);
320
+ if (after.state !== 'stored' || after.sha256 !== hash(next)) fail('UNCERTAIN', 'Replacement readback differs; inspect operation before retry');
321
+ return { ...after, replay: false };
322
+ });
323
+ }
324
+
197
325
  export async function organize(root, { path: relative, to, expected, key }) {
198
326
  if (!/^[a-f0-9]{64}$/.test(expected || '')) fail('INVALID', 'Supply the current source SHA-256');
199
327
  if (relative === 'LIBRARY_SYNC_ACCESS' || to === 'LIBRARY_SYNC_ACCESS') fail('INVALID', 'The sync access marker is reserved');
@@ -24,13 +24,14 @@ while (!stopping) {
24
24
  const selected = await libraryRoot(root, name);
25
25
  const { config } = await syncStatus(selected);
26
26
  const mirror = (await mirrorStatus(selected)).config;
27
- if (config?.mode !== 'two-way' && (config || mirror?.mode !== 'one-way')) {
27
+ const enabled = config?.mode === 'two-way' || (config?.backend === 'git' && config.mode === 'pull-only');
28
+ if (!enabled && (config || mirror?.mode !== 'one-way')) {
28
29
  due.delete(name);
29
- if ((await embeddingStatus()).state === 'ready') await locked(selected, refreshIndex);
30
+ if ((await embeddingStatus()).state === 'ready') await locked(selected, refreshIndex, { signal: controller.signal });
30
31
  continue;
31
32
  }
32
33
  if ((due.get(name) || 0) <= Date.now()) {
33
- try { await syncRun(selected, root); }
34
+ try { await syncRun(selected, root, { signal: controller.signal }); }
34
35
  finally { due.set(name, Date.now() + (config?.intervalSeconds || 60) * 1000); }
35
36
  }
36
37
  interval = Math.min(interval, Math.max(1, ((due.get(name) || 0) - Date.now()) / 1000));
package/src/sync.mjs CHANGED
@@ -132,16 +132,17 @@ export async function syncAdopt(root, remote, stateRoot = root) {
132
132
  }
133
133
 
134
134
  export async function syncPolicy(root, { expected, mode, intervalSeconds = 60 }) {
135
- if (!['paused', 'two-way'].includes(mode) || !Number.isInteger(intervalSeconds) || intervalSeconds < 30 || intervalSeconds > 3600) fail('INVALID', 'Use paused or two-way, and an interval from 30 to 3600 seconds');
135
+ if (!['paused', 'two-way', 'pull-only'].includes(mode) || !Number.isInteger(intervalSeconds) || intervalSeconds < 30 || intervalSeconds > 3600) fail('INVALID', 'Use paused, two-way or pull-only, and an interval from 30 to 3600 seconds');
136
136
  return locked(root, async root => {
137
137
  const current = await syncStatus(root);
138
138
  if (!current.config || current.revision !== expected) fail('CONFLICT', 'Read the current sync revision before changing policy');
139
+ if (mode === 'pull-only' && current.config.backend !== 'git') fail('INVALID', 'Pull-only sync requires a Git library');
139
140
  await atomic(location(root), jsonBytes({ ...current.config, mode, intervalSeconds }));
140
141
  return syncStatus(root);
141
142
  });
142
143
  }
143
144
 
144
- export async function syncRun(root, stateRoot = root) {
145
+ export async function syncRun(root, stateRoot = root, { signal } = {}) {
145
146
  return locked(root, async root => {
146
147
  await prepare(root);
147
148
  const config = await readJSON(location(root));
@@ -153,6 +154,7 @@ export async function syncRun(root, stateRoot = root) {
153
154
  try {
154
155
  if (config?.backend === 'git') status.git = await gitTransfer(root, config);
155
156
  else if (config) {
157
+ if (config.mode !== 'two-way') fail('INVALID', 'Folder sync requires two-way mode');
156
158
  if (await remoteIdentity(root, config.remote, stateRoot) !== config.identity) fail('CONFLICT', 'Mapped folder disappeared or changed identity; no automatic recreation');
157
159
  succeeded(await rclone(root, bisyncArgs(root, config)), 'Native bisync');
158
160
  }
@@ -170,5 +172,5 @@ export async function syncRun(root, stateRoot = root) {
170
172
  await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
171
173
  if (status.textMirror?.state === 'pending') fail('UNAVAILABLE', 'GitHub text mirror pending: ' + status.textMirror.error.message);
172
174
  return status;
173
- });
175
+ }, { signal });
174
176
  }
@@ -0,0 +1,80 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import * as fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { randomBytes } from 'node:crypto';
7
+ import { Readable } from 'node:stream';
8
+ import { gunzipSync } from 'node:zlib';
9
+ import { spawnSync } from 'node:child_process';
10
+ import { gzipFile } from '../src/compress.mjs';
11
+ import { put, hash, operation, MAX_FILE_BYTES } from '../src/store.mjs';
12
+
13
+ async function fixture(t, data = Buffer.from('frozen evidence')) {
14
+ const root = await fs.mkdtemp(path.join(tmpdir(), 'library-gzip-'));
15
+ t.after(() => fs.rm(root, { recursive: true, force: true }));
16
+ await put(root, 'data/source.json', Readable.from([data]), { expected: 'new', key: 'source' });
17
+ return { root, data, request: { path: 'data/source.json', to: 'archive/source.json.gz', expected: hash(data), key: 'compress' } };
18
+ }
19
+
20
+ test('gzip keeps large binary data inside Library and records source/target proof', async t => {
21
+ const { root, data, request } = await fixture(t, randomBytes(2 * 1024 * 1024));
22
+ const result = await gzipFile(root, request);
23
+ const archive = await fs.readFile(path.join(root, 'files', request.to));
24
+ assert(archive.length > 1024 * 1024);
25
+ assert.deepEqual(gunzipSync(archive), data);
26
+ assert.equal(result.sha256, hash(archive));
27
+ assert.equal(result.source.sha256, hash(data));
28
+ assert.equal(result.source.bytes, data.length);
29
+ assert.equal(result.state, 'stored');
30
+ assert.equal((await fs.stat(path.join(root, 'files', request.to))).mode & 0o777, 0o600);
31
+ assert.deepEqual(await fs.readFile(path.join(root, 'files', request.path)), data);
32
+ assert.equal((await operation(root, request.key)).state, 'stored');
33
+ assert.equal((await gzipFile(root, request)).replay, true);
34
+ // Reconcile interruption after receipt installation, before destination rename.
35
+ await fs.unlink(path.join(root, 'files', request.to));
36
+ assert.equal((await operation(root, request.key)).state, 'missing');
37
+ assert.equal((await gzipFile(root, request)).state, 'stored');
38
+ assert.deepEqual(await fs.readFile(path.join(root, 'files', request.to)), archive);
39
+ });
40
+
41
+ test('gzip fails closed on stale source, occupied target, reused key and writer contention', async t => {
42
+ const { root, request } = await fixture(t);
43
+ await assert.rejects(gzipFile(root, { ...request, expected: '0'.repeat(64) }), { code: 'CONFLICT' });
44
+ await assert.rejects(fs.stat(path.join(root, 'files', request.to)), { code: 'ENOENT' });
45
+ await assert.rejects(operation(root, request.key), { code: 'ENOENT' });
46
+ await gzipFile(root, request);
47
+ await assert.rejects(gzipFile(root, { ...request, key: 'new-key' }), { code: 'CONFLICT' });
48
+ await assert.rejects(gzipFile(root, { ...request, to: 'another.gz' }), { code: 'KEY_REUSED' });
49
+ await fs.mkdir(path.join(root, '.writer-lock'));
50
+ await assert.rejects(gzipFile(root, request), { code: 'BUSY' });
51
+ await fs.rmdir(path.join(root, '.writer-lock'));
52
+ await fs.writeFile(path.join(root, 'files', request.path), 'changed');
53
+ await assert.rejects(gzipFile(root, request), { code: 'CONFLICT' });
54
+ });
55
+
56
+ test('gzip rejects traversal, symlinks, oversized sources and ambiguous destinations', async t => {
57
+ const { root, request } = await fixture(t);
58
+ for (const invalid of [{ expected: 'new' }, { to: request.path }, { to: 'no-gzip' }, { path: '' }]) {
59
+ await assert.rejects(gzipFile(root, { ...request, ...invalid }), { code: 'INVALID' });
60
+ }
61
+ await assert.rejects(gzipFile(root, { ...request, path: '../outside' }), { code: 'UNSAFE_PATH' });
62
+ await assert.rejects(gzipFile(root, { ...request, to: '../outside.gz' }), { code: 'UNSAFE_PATH' });
63
+ await fs.symlink(path.join(root, 'files', request.path), path.join(root, 'files', 'link'));
64
+ await assert.rejects(gzipFile(root, { ...request, path: 'link' }), { code: 'UNSAFE_PATH' });
65
+ await fs.symlink(path.join(root, 'files', request.path), path.join(root, 'files', 'link.gz'));
66
+ await assert.rejects(gzipFile(root, { ...request, to: 'link.gz' }), { code: 'UNSAFE_PATH' });
67
+ await fs.truncate(path.join(root, 'files', request.path), MAX_FILE_BYTES + 1);
68
+ await assert.rejects(gzipFile(root, request), { code: 'TOO_LARGE' });
69
+ });
70
+
71
+ test('gzip CLI needs no payload stdin and local help needs no state', async t => {
72
+ const { root, request, data } = await fixture(t);
73
+ const cli = new URL('../bin/ez-library.mjs', import.meta.url).pathname;
74
+ const run = spawnSync(process.execPath, [cli, 'gzip', '--path', request.path, '--to', request.to,
75
+ '--expected', request.expected, '--key', request.key], { env: { ...process.env, EZ_LIBRARY_STATE: root }, encoding: 'utf8' });
76
+ assert.equal(run.status, 0, run.stderr);
77
+ assert.equal(JSON.parse(run.stdout).data.source.sha256, hash(data));
78
+ const help = spawnSync(process.execPath, [cli, 'gzip', '--help'], { env: { ...process.env, EZ_LIBRARY_STATE: '/does-not-exist' }, encoding: 'utf8' });
79
+ assert.equal(help.status, 0); assert.match(help.stdout, /gzip --path/);
80
+ });
@@ -38,6 +38,21 @@ test('text mirror versions notes and renames while excluding attachment bytes an
38
38
  await mirrorPolicy(root, current.revision, 'paused');
39
39
  assert.equal((await cycle()).state, 'paused');
40
40
  });
41
+ test('unchanged mirror cycles keep projection files and remote head untouched', async t => {
42
+ const { root, remote, git, cycle } = await fixture(t);
43
+ await put(root, 'note.md', Readable.from(['original']), { expected: 'new', key: 'note' });
44
+ await mirrorAdopt(root, remote);
45
+ const first = await cycle(), projected = path.join(root, 'sync/text-mirror/files/note.md');
46
+ const before = await fs.stat(projected);
47
+ assert.equal((await cycle()).commit, first.commit);
48
+ const after = await fs.stat(projected);
49
+ assert.deepEqual([after.ino, after.mtimeMs], [before.ino, before.mtimeMs]);
50
+ assert.equal(git(['--git-dir', remote, 'rev-parse', 'main']).trim(), first.commit);
51
+ await fs.writeFile(path.join(root, 'files/note.md'), 'edited');
52
+ const second = await cycle();
53
+ assert.notEqual(second.commit, first.commit);
54
+ assert.equal(git(['--git-dir', remote, 'show', 'main:note.md']), 'edited');
55
+ });
41
56
  test('outside GitHub edits stop mirroring without changing Drive originals or dropping remote history', async t => {
42
57
  const { root, remote, base, git, cycle } = await fixture(t);
43
58
  await put(root, 'note.md', Readable.from(['original']), { expected: 'new', key: 'note' });
@@ -7,6 +7,7 @@ import { execFileSync } from 'node:child_process';
7
7
  import { Readable } from 'node:stream';
8
8
  import { gitAdopt, gitTransfer, git, repositoryURL } from '../src/git-sync.mjs';
9
9
  import { locked, put, digest, organize, jsonBytes } from '../src/store.mjs';
10
+ import { syncPolicy, syncStatus } from '../src/sync.mjs';
10
11
 
11
12
  async function setup(t) {
12
13
  const base = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), 'library-git-')));
@@ -25,6 +26,87 @@ async function setup(t) {
25
26
  }
26
27
  const cycle = (root, config) => locked(root, () => gitTransfer(root, config));
27
28
 
29
+ test('pull-only imports additions, renames and deletions without a push or local commit', async t => {
30
+ const { root, remote, external, outside, publish } = await setup(t);
31
+ const { config } = await gitAdopt(root, remote, 'main', root, false, 'pull-only');
32
+ // Any push, even one with no changed refs, would fail against this URL.
33
+ await git(root, config, ['remote', 'set-url', '--push', 'origin', remote + '-forbidden']);
34
+ await fs.writeFile(path.join(external, 'incoming.md'), 'Remote-only violet telescope');
35
+ await fs.rename(path.join(external, 'note0.md'), path.join(external, 'renamed.md'));
36
+ await fs.unlink(path.join(external, 'note1.md')); publish();
37
+ const expected = outside(['--git-dir', remote, 'rev-parse', 'main']).trim();
38
+ const result = await cycle(root, config);
39
+ assert.equal(result.commit, expected);
40
+ assert.equal(result.remoteVerified, true);
41
+ assert.match(await fs.readFile(path.join(root, 'files/incoming.md'), 'utf8'), /violet/);
42
+ assert.match(await fs.readFile(path.join(root, 'files/renamed.md'), 'utf8'), /Note 0/);
43
+ await assert.rejects(fs.stat(path.join(root, 'files/note1.md')), { code: 'ENOENT' });
44
+ assert.equal((await cycle(root, config)).commit, expected);
45
+ assert.equal(outside(['--git-dir', remote, 'rev-parse', 'main']).trim(), expected);
46
+ });
47
+
48
+ test('pull-only preserves local edits, staged work and untracked files without committing them', async t => {
49
+ for (const kind of ['edited', 'staged', 'untracked']) {
50
+ const { root, remote, outside } = await setup(t);
51
+ const { config } = await gitAdopt(root, remote, 'main', root, false, 'pull-only');
52
+ const original = outside(['--git-dir', remote, 'rev-parse', 'main']).trim();
53
+ const name = kind === 'untracked' ? 'local.md' : 'note0.md';
54
+ await fs.writeFile(path.join(root, 'files', name), 'Preserve local ' + kind);
55
+ if (kind === 'staged') await git(root, config, ['add', '--', name]);
56
+ await assert.rejects(cycle(root, config), { code: 'CONFLICT' });
57
+ assert.equal(await fs.readFile(path.join(root, 'files', name), 'utf8'), 'Preserve local ' + kind);
58
+ assert.equal((await git(root, config, ['rev-parse', 'HEAD'])).stdout.trim(), original);
59
+ assert.equal(outside(['--git-dir', remote, 'rev-parse', 'main']).trim(), original);
60
+ if (kind === 'staged') assert.match((await git(root, config, ['show', ':' + name])).stdout, /Preserve local staged/);
61
+ }
62
+ });
63
+
64
+ test('pull-only rejects ahead and divergent local history without resetting or merging', async t => {
65
+ for (const diverged of [false, true]) {
66
+ const { root, remote, external, outside, publish } = await setup(t);
67
+ const { config } = await gitAdopt(root, remote, 'main', root, false, 'pull-only');
68
+ await fs.writeFile(path.join(root, 'files/local.md'), 'Preserve local commit');
69
+ await git(root, config, ['add', '--', 'local.md']);
70
+ await git(root, config, ['commit', '-m', 'Local work']);
71
+ const head = (await git(root, config, ['rev-parse', 'HEAD'])).stdout.trim();
72
+ if (diverged) { await fs.writeFile(path.join(external, 'remote.md'), 'External work'); publish(); }
73
+ const remoteHead = outside(['--git-dir', remote, 'rev-parse', 'main']).trim();
74
+ await assert.rejects(cycle(root, config), { code: 'CONFLICT' });
75
+ assert.equal((await git(root, config, ['rev-parse', 'HEAD'])).stdout.trim(), head);
76
+ assert.equal(outside(['--git-dir', remote, 'rev-parse', 'main']).trim(), remoteHead);
77
+ assert.equal((await git(root, config, ['rev-parse', '--verify', 'MERGE_HEAD'])).code, 128);
78
+ }
79
+ });
80
+
81
+ test('an existing two-way Git binding can switch to revision-guarded pull-only sync', async t => {
82
+ const { root, remote } = await setup(t);
83
+ await gitAdopt(root, remote);
84
+ const before = await syncStatus(root);
85
+ const after = await syncPolicy(root, { expected: before.revision, mode: 'pull-only', intervalSeconds: 30 });
86
+ assert.equal(after.config.mode, 'pull-only');
87
+ await cycle(root, after.config);
88
+ await assert.rejects(syncPolicy(root, { expected: before.revision, mode: 'two-way' }), { code: 'CONFLICT' });
89
+ });
90
+
91
+ test('pull-only adoption preserves and refuses extra local originals', async t => {
92
+ const { root, remote } = await setup(t);
93
+ await put(root, 'local.md', Readable.from(['Keep this original']), { expected: 'new', key: 'local' });
94
+ await assert.rejects(gitAdopt(root, remote, 'main', root, false, 'pull-only'), { code: 'CONFLICT' });
95
+ assert.equal(await fs.readFile(path.join(root, 'files/local.md'), 'utf8'), 'Keep this original');
96
+ assert.equal((await syncStatus(root)).config.mode, 'paused');
97
+ });
98
+
99
+ test('pull-only advances an explicitly adopted existing checkout without creating commits', async t => {
100
+ const { root, remote, external, outside, publish } = await setup(t);
101
+ await fs.mkdir(root); outside(['clone', remote, path.join(root, 'files')]);
102
+ const { config } = await gitAdopt(root, remote, 'main', root, true, 'pull-only');
103
+ await fs.writeFile(path.join(external, 'incoming.md'), 'External checkout update'); publish();
104
+ const expected = outside(['--git-dir', remote, 'rev-parse', 'main']).trim();
105
+ assert.equal((await cycle(root, config)).commit, expected);
106
+ assert.equal(outside(['-C', path.join(root, 'files'), 'rev-parse', 'HEAD']).trim(), expected);
107
+ assert.equal(outside(['-C', path.join(root, 'files'), 'rev-parse', 'origin/main']).trim(), expected);
108
+ });
109
+
28
110
  test('native Git adopts originals, imports external changes, exports agent changes and verifies commit', async t => {
29
111
  const { root, remote, external, outside, publish } = await setup(t);
30
112
  const { config } = await gitAdopt(root, remote);
@@ -71,3 +71,19 @@ test('per-library indexing policy controls native QMD embedding with explicit sh
71
71
  } finally { await fs.rm(base, { recursive: true, force: true }); }
72
72
  `], { cwd: new URL('..', import.meta.url), stdio: 'pipe' });
73
73
  });
74
+
75
+ test('scan digests are reused per process but never hide same-size rewrites with a restored mtime', async t => {
76
+ const fs = await import('node:fs/promises'), path = (await import('node:path')).default, { tmpdir } = await import('node:os');
77
+ const { setTimeout } = await import('node:timers/promises'), assert = (await import('node:assert/strict')).default;
78
+ const { scanDigest, hash } = await import('../src/store.mjs');
79
+ const base = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), 'library-scan-')));
80
+ t.after(() => fs.rm(base, { recursive: true, force: true }));
81
+ const file = path.join(base, 'note.md');
82
+ await fs.writeFile(file, 'first');
83
+ const { mtime } = await fs.stat(file);
84
+ await setTimeout(2100);
85
+ assert.deepEqual(await scanDigest(file), { bytes: 5, sha256: hash('first') });
86
+ assert.deepEqual(await scanDigest(file), { bytes: 5, sha256: hash('first') });
87
+ await fs.writeFile(file, 'other'); await fs.utimes(file, mtime, mtime);
88
+ assert.deepEqual(await scanDigest(file), { bytes: 5, sha256: hash('other') });
89
+ });
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import { tmpdir } from 'node:os';
6
6
  import { Readable } from 'node:stream';
7
7
  import { spawnSync } from 'node:child_process';
8
- import { put, operation, settings, defaults, validateSettings, list, digest, readRange, MAX_READ_BYTES, hash } from '../src/store.mjs';
8
+ import { locked, put, operation, settings, defaults, validateSettings, list, digest, readRange, MAX_READ_BYTES, hash } from '../src/store.mjs';
9
9
  import { qmdEnvironment } from '../src/cli.mjs';
10
10
 
11
11
  const cli = new URL('../bin/ez-library.mjs', import.meta.url).pathname;
@@ -144,6 +144,27 @@ test('writer lock is fail-closed, including stale-looking locks', async t => {
144
144
  assert((await fs.stat(path.join(root, '.writer-lock'))).isDirectory());
145
145
  });
146
146
 
147
+ test('a live writer is waited for instead of failing BUSY', async t => {
148
+ const root = await fixture(t); const lock = path.join(root, '.writer-lock');
149
+ await fs.mkdir(lock);
150
+ await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: process.pid + 1, host: 'other', at: new Date().toISOString() }));
151
+ const release = new Promise(resolve => setTimeout(async () => {
152
+ await fs.rm(path.join(lock, 'owner')); await fs.rmdir(lock); resolve();
153
+ }, 600));
154
+ await save(root, 'after wait');
155
+ await release;
156
+ await assert.rejects(fs.stat(lock), code('ENOENT'));
157
+ });
158
+
159
+ test('an aborted wait gives up without taking the lock', async t => {
160
+ const root = await fixture(t); const lock = path.join(root, '.writer-lock');
161
+ await fs.mkdir(lock);
162
+ await fs.writeFile(path.join(lock, 'owner'), JSON.stringify({ pid: process.pid + 1, host: 'other', at: new Date().toISOString() }));
163
+ const controller = new AbortController(); setTimeout(() => controller.abort(), 300);
164
+ await assert.rejects(locked(root, () => assert.fail('must not run'), { signal: controller.signal }), { name: 'AbortError' });
165
+ assert.equal(JSON.parse(await fs.readFile(path.join(lock, 'owner'), 'utf8')).host, 'other');
166
+ });
167
+
147
168
  test('list honors prefix and a bounded result size', async t => {
148
169
  const root = await fixture(t); await save(root, 'a');
149
170
  await put(root, 'notes/second.md', input('b'), { key: 'b', expected: 'new' });
@@ -212,3 +233,12 @@ test('PDF extraction rejects traversal, symlinks, directories and missing paths
212
233
  const result = spawnSync(process.execPath, [cli, 'pdf-text'], { env: { ...process.env, EZ_LIBRARY_STATE: root }, encoding: 'utf8' });
213
234
  assert.equal(result.status, 2); assert.match(result.stderr, /Supply --path/);
214
235
  });
236
+
237
+ test('local subcommand help succeeds before configuration or write intake',async t=>{
238
+ const root=await fixture(t);
239
+ for(const command of ['put','get','sources','sync-run']) {
240
+ const result=spawnSync(process.execPath,[cli,command,'--library','absent','--help'],{env:{...process.env,EZ_LIBRARY_STATE:root},input:'must not write',encoding:'utf8'});
241
+ assert.equal(result.status,0,result.stderr);assert.match(result.stdout,/put --path/);
242
+ }
243
+ assert.deepEqual(await fs.readdir(root),[]);
244
+ });