@jc_stack/ez-library 0.1.0-beta.15 → 0.1.0-beta.18

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.
@@ -135,17 +135,22 @@ export async function mirrorTransfer(root) {
135
135
  if (remote) {
136
136
  if (config.lastCommit && remote !== config.lastCommit && remote !== local.stdout.trim()) fail('CONFLICT', 'Mirror branch was changed externally');
137
137
  if (local.code !== 0) fail('CONFLICT', 'Mirror remote changed before first commit');
138
- succeeded(await run(['fetch', '--no-tags', 'origin', 'refs/heads/' + config.branch]), 'Fetch mirror head');
139
- if ((await run(['merge-base', '--is-ancestor', 'FETCH_HEAD', 'HEAD'])).code !== 0) fail('CONFLICT', 'GitHub mirror was edited externally; preserve and reconcile it before resuming');
138
+ if (remote !== local.stdout.trim()) {
139
+ succeeded(await run(['fetch', '--no-tags', 'origin', 'refs/heads/' + config.branch]), 'Fetch mirror head');
140
+ if ((await run(['merge-base', '--is-ancestor', 'FETCH_HEAD', 'HEAD'])).code !== 0) fail('CONFLICT', 'GitHub mirror was edited externally; preserve and reconcile it before resuming');
141
+ }
140
142
  } else if (config.lastCommit) fail('CONFLICT', 'Mirror branch disappeared; no automatic recreation');
141
143
  if (selected.some(x => x.bytes >= 100 * 1024 * 1024)) fail('TOO_LARGE', 'Text mirror file exceeds GitHub ordinary-file limit');
142
144
  const target = path.join(root, 'sync/text-mirror/files');
143
- const selectedPaths = new Set(selected.map(x => x.destination));
145
+ const selectedPaths = new Set(selected.map(x => x.destination)), projected = new Map();
144
146
  for (const old of await inventory(target)) {
145
147
  if (!selectedPaths.has(old.path.normalize('NFC'))) await fs.unlink(await safePath(root, 'sync/text-mirror/files/' + old.path));
148
+ else projected.set(old.path, old.sha256);
146
149
  }
147
150
  await pruneEmptyDirectories(target);
151
+ // Rewrite only changed bytes so Git's stat cache stays valid for unchanged notes.
148
152
  for (const item of selected) {
153
+ if (projected.get(item.destination) === item.sha256) continue;
149
154
  const destination = await safePath(root, 'sync/text-mirror/files/' + item.destination, true);
150
155
  await fs.copyFile(await safePath(root, 'files/' + item.path), destination);
151
156
  }
@@ -156,9 +161,12 @@ export async function mirrorTransfer(root) {
156
161
  if (![0, 1].includes(diff.code)) succeeded(diff, 'Inspect mirror changes');
157
162
  if (diff.code === 1 || local.code !== 0) succeeded(await run(['commit', '--allow-empty', '--no-gpg-sign', '-m', 'Version Library text changes']), 'Commit text mirror');
158
163
  const commit = succeeded(await run(['rev-parse', 'HEAD']), 'Read mirror commit').trim();
159
- succeeded(await run(['push', 'origin', 'HEAD:refs/heads/' + config.branch]), 'Push text mirror');
160
- const verified = succeeded(await run(['ls-remote', 'origin', 'refs/heads/' + config.branch]), 'Verify text mirror').trim().split(/\s+/)[0];
161
- if (verified !== commit) fail('UNCERTAIN', 'Mirror advanced during verification');
162
- await atomic(file(root), jsonBytes({ ...config, lastCommit: commit }));
164
+ // The remote head read above already proves an unchanged projection.
165
+ if (remote !== commit) {
166
+ succeeded(await run(['push', 'origin', 'HEAD:refs/heads/' + config.branch]), 'Push text mirror');
167
+ const verified = succeeded(await run(['ls-remote', 'origin', 'refs/heads/' + config.branch]), 'Verify text mirror').trim().split(/\s+/)[0];
168
+ if (verified !== commit) fail('UNCERTAIN', 'Mirror advanced during verification');
169
+ }
170
+ if (config.lastCommit !== commit) await atomic(file(root), jsonBytes({ ...config, lastCommit: commit }));
163
171
  return { state: 'mirrored', repository: config.repository, branch: config.branch, commit, files: selected.length, remoteVerified: true };
164
172
  }
package/src/git-sync.mjs CHANGED
@@ -28,7 +28,7 @@ export async function gitKey(root, repository) {
28
28
  const { ssh_keys: keys } = await response.json();
29
29
  if (!Array.isArray(keys) || !keys.length || keys.some(k => !/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp256) [A-Za-z0-9+/=]+$/.test(k))) fail('UNAVAILABLE', 'Unexpected GitHub host-key response');
30
30
  await atomic(path.join(dir, 'known_hosts'), keys.map(k => 'github.com ' + k).join('\n') + '\n');
31
- return { repository, publicKey: (await fs.readFile(key + '.pub', 'utf8')).trim(), registration: 'Register this public key with write access through the connected GitHub plugin. Private key stays in Library.' };
31
+ return { repository, publicKey: (await fs.readFile(key + '.pub', 'utf8')).trim(), registration: 'Register this public key through the connected GitHub plugin: read-only for pull-only sync, write access for two-way sync. Private key stays in Library.' };
32
32
  });
33
33
  }
34
34
 
@@ -85,7 +85,13 @@ async function existingCheckout(root, config) {
85
85
  return origin;
86
86
  }
87
87
 
88
- export async function gitAdopt(root, repository, branch = 'main', stateRoot = root, reuseCheckout = false) {
88
+ async function cleanPullTree(root, config) {
89
+ const changes = succeeded(await git(root, config, ['status', '--porcelain=v1', '--untracked-files=all']), 'Inspect pull-only working tree');
90
+ if (changes) fail('CONFLICT', 'Pull-only library has local changes; preserve and reconcile them before syncing');
91
+ }
92
+
93
+ export async function gitAdopt(root, repository, branch = 'main', stateRoot = root, reuseCheckout = false, mode = 'two-way') {
94
+ if (!['two-way', 'pull-only'].includes(mode)) fail('INVALID', 'Use two-way or pull-only Git sync');
89
95
  const remote = repositoryURL(repository);
90
96
  return locked(root, async root => {
91
97
  await checkPolicy(root, repository, branch);
@@ -105,7 +111,8 @@ export async function gitAdopt(root, repository, branch = 'main', stateRoot = ro
105
111
  // No checkout, reset, commit or push during adoption. Native history and
106
112
  // eligible unstaged edits remain owned by the existing checkout.
107
113
  succeeded(await git(root, config, ['merge-base', 'HEAD', 'FETCH_HEAD']), 'Verify shared history');
108
- config.mode = 'two-way';
114
+ if (mode === 'pull-only') await cleanPullTree(root, config);
115
+ config.mode = mode;
109
116
  await atomic(binding, jsonBytes(config));
110
117
  return { config, imported: 0, indexing: 'pending' };
111
118
  }
@@ -134,45 +141,65 @@ export async function gitAdopt(root, repository, branch = 'main', stateRoot = ro
134
141
  succeeded(await git(root, config, ['reset', '--mixed', 'FETCH_HEAD']), 'Initialize native index');
135
142
  const missing = entries.filter(e => !existing.has(e.path)).map(e => e.path + '\0').join('');
136
143
  if (missing) succeeded(await git(root, config, ['checkout-index', '-z', '--stdin'], { input: missing }), 'Import tracked files');
137
- config.mode = 'two-way';
144
+ if (mode === 'pull-only') await cleanPullTree(root, config);
145
+ config.mode = mode;
138
146
  await atomic(binding, jsonBytes(config));
139
147
  return { config, imported: entries.length, indexing: 'pending' };
140
148
  });
141
149
  }
142
150
 
143
151
  export async function gitTransfer(root, config) {
152
+ if (!['two-way', 'pull-only'].includes(config.mode)) fail('INVALID', 'Use two-way or pull-only Git sync');
153
+ const pullOnly = config.mode === 'pull-only';
144
154
  await checkPolicy(root, config.repository, config.branch);
145
155
  if (config.existingCheckout) await existingCheckout(root, config);
146
156
  const actualRemote = succeeded(await git(root, config, ['remote', 'get-url', 'origin']), 'Check bound remote').trim();
147
157
  if (actualRemote !== (config.checkoutOrigin || repositoryURL(config.repository))) fail('CONFLICT', 'Git remote no longer matches the Library binding');
148
158
  const conflict = succeeded(await git(root, config, ['ls-files', '--unmerged']), 'Inspect merge state');
149
159
  if (conflict) fail('CONFLICT', 'Git merge unresolved; use native git status/show/add to resolve both retained versions before syncing');
150
- const files = config.existingCheckout ? await gitInventory(root) : await inventory(path.join(root, 'files'), '', { includeHidden: true });
151
- const ignored = new Set(succeeded(await git(root, config, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z']), 'Inspect ignored files').split('\0').filter(Boolean));
152
- if (files.some(f => !ignored.has(f.path) && f.bytes >= 100 * 1024 * 1024)) fail('TOO_LARGE', 'GitHub ordinary files must be below 100 MiB; select another storage mode for larger media');
153
- succeeded(await git(root, config, ['add', '--all', '--', '.']), 'Stage Library changes');
154
- const stagedTree = succeeded(await git(root, config, ['write-tree']), 'Read staged tree').trim();
155
- await tree(root, config, stagedTree);
156
- const diff = await git(root, config, ['diff', '--cached', '--quiet']);
157
- if (![0, 1].includes(diff.code)) succeeded(diff, 'Inspect staged changes');
158
- const merging = await git(root, config, ['rev-parse', '--verify', 'MERGE_HEAD']);
159
- if (diff.code === 1 || merging.code === 0) succeeded(await git(root, config, ['commit', '--no-gpg-sign', '-m', 'Sync Library changes']), 'Commit Library changes');
160
+ if (pullOnly) await cleanPullTree(root, config);
161
+ else {
162
+ const files = config.existingCheckout ? await gitInventory(root) : await inventory(path.join(root, 'files'), '', { includeHidden: true });
163
+ const ignored = new Set(succeeded(await git(root, config, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z']), 'Inspect ignored files').split('\0').filter(Boolean));
164
+ if (files.some(f => !ignored.has(f.path) && f.bytes >= 100 * 1024 * 1024)) fail('TOO_LARGE', 'GitHub ordinary files must be below 100 MiB; select another storage mode for larger media');
165
+ succeeded(await git(root, config, ['add', '--all', '--', '.']), 'Stage Library changes');
166
+ const stagedTree = succeeded(await git(root, config, ['write-tree']), 'Read staged tree').trim();
167
+ await tree(root, config, stagedTree);
168
+ const diff = await git(root, config, ['diff', '--cached', '--quiet']);
169
+ if (![0, 1].includes(diff.code)) succeeded(diff, 'Inspect staged changes');
170
+ const merging = await git(root, config, ['rev-parse', '--verify', 'MERGE_HEAD']);
171
+ if (diff.code === 1 || merging.code === 0) succeeded(await git(root, config, ['commit', '--no-gpg-sign', '-m', 'Sync Library changes']), 'Commit Library changes');
172
+ }
160
173
  const transport = config.existingCheckout ? repositoryURL(config.repository) : 'origin';
161
174
  const trackingRef = 'refs/remotes/origin/' + config.branch;
162
- const previousTracking = config.existingCheckout ? await git(root, config, ['rev-parse', '--verify', '--quiet', trackingRef]) : null;
163
- if (previousTracking && ![0, 1].includes(previousTracking.code)) succeeded(previousTracking, 'Read origin revision');
164
175
  succeeded(await git(root, config, ['fetch', '--no-tags', transport, 'refs/heads/' + config.branch]), 'Fetch remote changes');
165
176
  await tree(root, config, 'FETCH_HEAD');
177
+ // Native fetch may itself update origin's tracking ref, including when its
178
+ // URL was supplied directly. Compare-and-swap against that post-fetch value.
179
+ const previousTracking = config.existingCheckout ? await git(root, config, ['rev-parse', '--verify', '--quiet', trackingRef]) : null;
180
+ if (previousTracking && ![0, 1].includes(previousTracking.code)) succeeded(previousTracking, 'Read origin revision');
166
181
  const head = succeeded(await git(root, config, ['rev-parse', 'HEAD']), 'Read local commit').trim();
167
- const merge = await git(root, config, ['merge', '--no-overwrite-ignore', '--no-edit', '--no-gpg-sign', 'FETCH_HEAD']);
182
+ if (pullOnly) {
183
+ const ancestor = await git(root, config, ['merge-base', '--is-ancestor', 'HEAD', 'FETCH_HEAD']);
184
+ if (ancestor.code === 1) fail('CONFLICT', 'Pull-only library has local commits or rewritten remote history; reconcile before syncing');
185
+ succeeded(ancestor, 'Check pull-only fast-forward');
186
+ }
187
+ const merge = await git(root, config, ['merge', '--no-overwrite-ignore', ...(pullOnly ? ['--ff-only'] : ['--no-edit', '--no-gpg-sign']), 'FETCH_HEAD']);
168
188
  if (merge.code !== 0) {
169
189
  if (succeeded(await git(root, config, ['ls-files', '--unmerged']), 'Inspect conflicts')) fail('CONFLICT', 'Both revisions retained in Git merge stages. Resolve the merge before sync/indexing resumes');
170
190
  succeeded(merge, 'Merge remote changes');
171
191
  }
172
192
  const commit = succeeded(await git(root, config, ['rev-parse', 'HEAD']), 'Read synchronized commit').trim();
173
- succeeded(await git(root, config, ['push', transport, 'HEAD:refs/heads/' + config.branch]), 'Push Library changes');
193
+ if (!pullOnly) succeeded(await git(root, config, ['push', transport, 'HEAD:refs/heads/' + config.branch]), 'Push Library changes');
174
194
  const remote = succeeded(await git(root, config, ['ls-remote', '--exit-code', transport, 'refs/heads/' + config.branch]), 'Verify remote commit').trim().split(/\s+/)[0];
175
195
  if (remote !== commit) fail('UNCERTAIN', 'Remote advanced during verification; fetch/reconcile on the next cycle');
176
- if (config.existingCheckout) succeeded(await git(root, config, ['update-ref', trackingRef, commit, previousTracking.code === 0 ? previousTracking.stdout.trim() : '0'.repeat(40)]), 'Record verified origin revision');
196
+ if (config.existingCheckout) {
197
+ // Push can also record the verified tracking value itself. Keep the guard
198
+ // for other changes, but do not reject a ref already at the desired commit.
199
+ const tracking = await git(root, config, ['rev-parse', '--verify', '--quiet', trackingRef]);
200
+ if (![0, 1].includes(tracking.code)) succeeded(tracking, 'Read verified origin revision');
201
+ if (tracking.code !== 0 || tracking.stdout.trim() !== commit)
202
+ succeeded(await git(root, config, ['update-ref', trackingRef, commit, previousTracking.code === 0 ? previousTracking.stdout.trim() : '0'.repeat(40)]), 'Record verified origin revision');
203
+ }
177
204
  return { commit, previousCommit: head, remoteVerified: true };
178
205
  }
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
@@ -11,6 +11,9 @@ export class LibraryError extends Error {
11
11
  export const fail = (code, message) => { throw new LibraryError(code, message); };
12
12
  export const hash = bytes => createHash('sha256').update(bytes).digest('hex');
13
13
  export const MAX_FILE_BYTES = 512 * 1024 * 1024;
14
+ export const MAX_READ_BYTES = 512 * 1024;
15
+ export const MAX_REPLACE_BYTES = 256 * 1024;
16
+ const MAX_TEXT_BYTES = 8 * 1024 * 1024;
14
17
  export const defaults = () => ({ schemaVersion: 1, storage: { mode: 'local' }, backup: { mode: 'off' } });
15
18
 
16
19
  function keys(value, allowed) {
@@ -87,14 +90,62 @@ export async function locked(root, fn) {
87
90
  try { return await fn(await initialize(root)); }
88
91
  finally { await fs.rmdir(lock); }
89
92
  }
90
- export async function digest(file) {
93
+ async function opened(file, read) {
91
94
  const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
92
95
  try {
93
- const st = await handle.stat();
96
+ const st = await handle.stat({ bigint: true });
94
97
  if (!st.isFile()) fail('UNSAFE_PATH', 'Expected a regular file');
95
- const sha = createHash('sha256'); let bytes = 0;
96
- for await (const chunk of handle.createReadStream({ autoClose: false })) { sha.update(chunk); bytes += chunk.length; }
97
- return { bytes, sha256: sha.digest('hex') };
98
+ return await read(handle, st);
99
+ } finally { await handle.close(); }
100
+ }
101
+ async function contentDigest(handle) {
102
+ const sha = createHash('sha256'); let bytes = 0;
103
+ for await (const chunk of handle.createReadStream({ autoClose: false })) { sha.update(chunk); bytes += chunk.length; }
104
+ return { bytes, sha256: sha.digest('hex') };
105
+ }
106
+ export const digest = file => opened(file, contentDigest);
107
+
108
+ // The resident worker inventories unchanged originals every cycle. Within one
109
+ // process, reuse a digest only while device, inode, size, mtime and ctime are
110
+ // identical, and never for files changed within the last two seconds.
111
+ const scanned = new Map();
112
+ export const scanDigest = file => opened(file, async (handle, st) => {
113
+ const key = `${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`;
114
+ const known = scanned.get(file);
115
+ if (known?.key === key) return { ...known.value };
116
+ const value = await contentDigest(handle);
117
+ const changed = st.mtimeNs > st.ctimeNs ? st.mtimeNs : st.ctimeNs;
118
+ if (BigInt(Date.now()) * 1000000n - changed > 2000000000n) {
119
+ if (scanned.size >= 100000) scanned.clear();
120
+ scanned.set(file, { key, value });
121
+ }
122
+ return { ...value };
123
+ });
124
+ export async function readRange(file, { offset, length, expected }) {
125
+ if (!/^(0|[1-9][0-9]*)$/.test(offset ?? '') || !/^[1-9][0-9]*$/.test(length ?? '') ||
126
+ !Number.isSafeInteger(Number(offset)) || !Number.isSafeInteger(Number(length)) ||
127
+ Number(length) > MAX_READ_BYTES || !/^[a-f0-9]{64}$/.test(expected ?? '')) {
128
+ fail('INVALID', 'Ranges require --offset BYTE, --length 1..524288 and --expected SHA256');
129
+ }
130
+ offset = Number(offset); length = Number(length);
131
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
132
+ try {
133
+ if (!(await handle.stat()).isFile()) fail('UNSAFE_PATH', 'Expected a regular file');
134
+ const sha = createHash('sha256'), chunks = []; let bytes = 0;
135
+ // Hash and collect from one descriptor/pass: an atomic replacement cannot
136
+ // make the returned range belong to a different source revision.
137
+ for await (const chunk of handle.createReadStream({ autoClose: false })) {
138
+ sha.update(chunk);
139
+ const start = Math.max(0, offset - bytes), end = Math.min(chunk.length, offset + length - bytes);
140
+ if (end > start) chunks.push(chunk.subarray(start, end));
141
+ bytes += chunk.length;
142
+ }
143
+ const sha256 = sha.digest('hex');
144
+ if (sha256 !== expected) fail('CONFLICT', 'File changed; re-read metadata before requesting ranges');
145
+ if (offset > bytes) fail('INVALID', 'Offset exceeds file size');
146
+ const data = Buffer.concat(chunks), nextOffset = offset + data.length;
147
+ return { bytes, sha256, offset, length: data.length, chunkSha256: hash(data), encoding: 'base64',
148
+ content: data.toString('base64'), nextOffset, eof: nextOffset === bytes };
98
149
  } finally { await handle.close(); }
99
150
  }
100
151
  async function current(file) { return digest(file).catch(e => { if (e.code === 'ENOENT') return null; throw e; }); }
@@ -116,7 +167,7 @@ export async function settings(root) {
116
167
 
117
168
  // Receipts record intent before installation. Readback determines stored/changed/missing,
118
169
  // including after interruption between the atomic receipt and file renames.
119
- export async function put(root, relative, input, { key, expected, kind = 'file', maxBytes = MAX_FILE_BYTES } = {}) {
170
+ export async function put(root, relative, input, { key, expected, kind = 'file', maxBytes = MAX_FILE_BYTES, source } = {}) {
120
171
  if (expected !== 'new' && !/^[a-f0-9]{64}$/.test(expected || '')) fail('INVALID', 'Supply --expected new or the current SHA-256');
121
172
  if (!['file', 'settings'].includes(kind)) fail('INVALID', 'Unknown write kind');
122
173
  return locked(root, async root => {
@@ -124,7 +175,8 @@ export async function put(root, relative, input, { key, expected, kind = 'file',
124
175
  await safePath(root, path.relative(root, receiptFile));
125
176
  if (kind === 'file' && (typeof relative !== 'string' || !relative)) fail('INVALID', 'Supply a relative file path');
126
177
  const target = await safePath(root, kind === 'settings' ? 'settings.json' : 'files/' + relative, true);
127
- const temp = path.join(root, 'tmp', randomUUID());
178
+ // files may be a separate bind mount: stage on the destination filesystem.
179
+ const temp = path.join(path.dirname(target), '.ez-library-put-' + randomUUID() + '.tmp');
128
180
  let bytes = 0; const sha = createHash('sha256');
129
181
  try {
130
182
  await pipeline(input, new Transform({ transform(chunk, encoding, cb) {
@@ -132,7 +184,8 @@ export async function put(root, relative, input, { key, expected, kind = 'file',
132
184
  if (bytes > maxBytes) return cb(new LibraryError('TOO_LARGE', `Input exceeds ${maxBytes} bytes`));
133
185
  sha.update(chunk); cb(null, chunk);
134
186
  } }), createWriteStream(temp, { flags: 'wx', mode: 0o600 }));
135
- const request = { kind, path: kind === 'settings' ? 'settings.json' : relative, bytes, sha256: sha.digest('hex'), expected };
187
+ const request = { kind, path: kind === 'settings' ? 'settings.json' : relative, bytes, sha256: sha.digest('hex'), expected,
188
+ ...(source ? { source } : {}) };
136
189
  const oldReceipt = await fs.readFile(receiptFile, 'utf8').then(JSON.parse).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
137
190
  if (oldReceipt && JSON.stringify(oldReceipt) !== JSON.stringify(request)) fail('KEY_REUSED', 'Operation key was already used with different content or preconditions');
138
191
  const before = await current(target);
@@ -154,6 +207,7 @@ export async function put(root, relative, input, { key, expected, kind = 'file',
154
207
  export async function operation(root, key) {
155
208
  const receiptFile = await safePath(root, path.relative(root, operationPath(root, key)));
156
209
  const receipt = JSON.parse(await fs.readFile(receiptFile, 'utf8'));
210
+ if (receipt.kind === 'replace') return replacementView(root, receipt);
157
211
  if (['move', 'remove'].includes(receipt.kind)) {
158
212
  const source = await current(await safePath(root, 'files/' + receipt.path));
159
213
  const target = receipt.to ? await current(await safePath(root, 'files/' + receipt.to)) : null;
@@ -165,6 +219,81 @@ export async function operation(root, key) {
165
219
  return { ...receipt, state: !now ? 'missing' : now.sha256 === receipt.sha256 ? 'stored' : 'changed' };
166
220
  }
167
221
 
222
+ const uniquePosition = (text, part) => {
223
+ const at = text.indexOf(part);
224
+ return at >= 0 && text.indexOf(part, at + 1) < 0 ? at : -1;
225
+ };
226
+ function validateReplacement(value) {
227
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
228
+ Object.keys(value).some(key => !['before', 'after'].includes(key)) ||
229
+ typeof value.before !== 'string' || !value.before || typeof value.after !== 'string' ||
230
+ !value.after || value.before === value.after ||
231
+ Buffer.byteLength(JSON.stringify(value)) > MAX_REPLACE_BYTES) {
232
+ fail('INVALID', 'Supply distinct nonempty before/after strings in at most 256 KiB of JSON');
233
+ }
234
+ for (const text of [value.before, value.after]) {
235
+ if (Buffer.from(text).toString('utf8') !== text) fail('INVALID', 'Replacement must be valid UTF-8 text');
236
+ }
237
+ }
238
+ async function readText(file) {
239
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
240
+ try {
241
+ const stat = await handle.stat();
242
+ if (!stat.isFile()) fail('UNSAFE_PATH', 'Expected a regular text file');
243
+ if (stat.size > MAX_TEXT_BYTES) fail('TOO_LARGE', 'Text replacement is limited to 8 MiB files');
244
+ const chunks = []; let bytes = 0;
245
+ for await (const chunk of handle.createReadStream({ autoClose: false })) {
246
+ bytes += chunk.length;
247
+ if (bytes > MAX_TEXT_BYTES) fail('TOO_LARGE', 'Text replacement is limited to 8 MiB files');
248
+ chunks.push(chunk);
249
+ }
250
+ const data = Buffer.concat(chunks), text = data.toString('utf8');
251
+ if (!Buffer.from(text).equals(data)) fail('INVALID', 'Text replacement requires valid UTF-8');
252
+ return { text, bytes, sha256: hash(data) };
253
+ } finally { await handle.close(); }
254
+ }
255
+ async function replacementView(root, receipt) {
256
+ validateReplacement({ before: receipt.before, after: receipt.after });
257
+ const file = await safePath(root, 'files/' + receipt.path);
258
+ const now = await readText(file).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
259
+ return { kind: 'replace', path: receipt.path, beforeSha256: hash(receipt.before), afterSha256: hash(receipt.after),
260
+ state: !now ? 'missing' : uniquePosition(now.text, receipt.after) >= 0 ? 'stored' : 'changed',
261
+ ...(now ? { bytes: now.bytes, sha256: now.sha256 } : {}) };
262
+ }
263
+
264
+ // Exact literal replacement is a scoped compare-and-swap, not a Markdown merge.
265
+ // The caller supplies its complete unique block. Unrelated bytes are read under
266
+ // the existing writer lock and retained, including other callers' recent edits.
267
+ export async function replaceText(root, relative, replacement, { key } = {}) {
268
+ validateReplacement(replacement);
269
+ if (!relative || relative === 'LIBRARY_SYNC_ACCESS') fail('INVALID', 'Supply a non-reserved file path');
270
+ return locked(root, async root => {
271
+ const target = await safePath(root, 'files/' + relative);
272
+ const receiptFile = await safePath(root, path.relative(root, operationPath(root, key)));
273
+ const request = { kind: 'replace', path: relative, before: replacement.before, after: replacement.after };
274
+ const old = await fs.readFile(receiptFile, 'utf8').then(JSON.parse).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
275
+ if (old && JSON.stringify(old) !== JSON.stringify(request)) fail('KEY_REUSED', 'Operation key belongs to a different replacement');
276
+ if (old) {
277
+ const observed = await replacementView(root, old);
278
+ if (observed.state === 'stored') return { ...observed, replay: true };
279
+ }
280
+ const before = await readText(target);
281
+ const at = uniquePosition(before.text, replacement.before);
282
+ if (at < 0) fail('CONFLICT', 'Expected text is absent or ambiguous; re-read the owning block');
283
+ const next = before.text.slice(0, at) + replacement.after + before.text.slice(at + replacement.before.length);
284
+ if (Buffer.byteLength(next) > MAX_TEXT_BYTES) fail('TOO_LARGE', 'Replacement exceeds the 8 MiB text limit');
285
+ if (uniquePosition(next, replacement.after) < 0) fail('CONFLICT', 'Resulting text is ambiguous; use a larger unique block');
286
+ const history = await safePath(root, 'history/' + before.sha256);
287
+ await fs.copyFile(target, history, constants.COPYFILE_EXCL).catch(error => { if (error.code !== 'EEXIST') throw error; });
288
+ await fs.chmod(history, 0o600);
289
+ await atomic(receiptFile, jsonBytes(request));
290
+ await atomic(target, next);
291
+ const after = await replacementView(root, request);
292
+ if (after.state !== 'stored' || after.sha256 !== hash(next)) fail('UNCERTAIN', 'Replacement readback differs; inspect operation before retry');
293
+ return { ...after, replay: false };
294
+ });
295
+ }
296
+
168
297
  export async function organize(root, { path: relative, to, expected, key }) {
169
298
  if (!/^[a-f0-9]{64}$/.test(expected || '')) fail('INVALID', 'Supply the current source SHA-256');
170
299
  if (relative === 'LIBRARY_SYNC_ACCESS' || to === 'LIBRARY_SYNC_ACCESS') fail('INVALID', 'The sync access marker is reserved');
@@ -24,7 +24,8 @@ 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
30
  if ((await embeddingStatus()).state === 'ready') await locked(selected, refreshIndex);
30
31
  continue;
package/src/sync.mjs CHANGED
@@ -132,10 +132,11 @@ 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
  });
@@ -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
  }
@@ -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);