@jc_stack/ez-library 0.1.0-beta.21 → 0.1.0-beta.23

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 CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.0-beta.23
4
+
5
+ - `put` and `replace` that wait out the writer lock (60 seconds, including a running sync) now fail `BUSY` as JSON on stdout with `written: false` and, while a live writer or sync holds the lock, `retryAfterSeconds`, exit 3. Nothing was written and the same `--key` can be retried. Other commands keep errors on stderr.
6
+ - `operation --key` on a Git-bound Library adds `git: { state, commit }`: `pushed` with the last remote commit that changed the path (a removal is `pushed` without a commit once the path is absent at the remote tip), `pending`, or `unknown`. Paths are read literally. It reads local Git only; no network call.
7
+ - Tests: a non-ASCII character (en dash, accents, emoji) survives `put` byte for byte, including when split across stream chunks and pipe buffers.
8
+
9
+ ## 0.1.0-beta.22
10
+
11
+ - Files and directories the Library creates under `files/` (`put`, `gzip`, `replace`, `organize` destinations) are now group read/write (`0660`/`0770`) instead of `0600`/`0700`. On a host where the content directory carries a default ACL for another account (the Stocks VM grants the agent's executor `ezrelay` this way), a `0600` file or `0700` directory made the ACL mask empty, so the executor got `Permission denied` on every new or rewritten file until the ACL was repaired by hand. Others still get nothing; receipts, history, locks and other state stay `0600`/`0700`.
12
+
3
13
  ## 0.1.0-beta.21
4
14
 
5
15
  - Git sync can no longer hang forever holding the writer lock. The SSH command adds `ServerAliveInterval=15` and `ServerAliveCountMax=4`, and every remote-touching Git call (fetch, push, ls-remote, in sync, text mirror and adoption) is bounded at 5 minutes: on expiry the child is stopped (SIGTERM, then SIGKILL after 5 seconds) and the cycle fails `UNAVAILABLE`, so the lock is released and the next interval retries. Before this, a connection that stalled after connect left `sync-status` at `syncing` and every writer `BUSY` until the service was restarted (#53).
package/README.md CHANGED
@@ -141,11 +141,11 @@ When the owner asks to enable Drive backup and sync, the onboarded agent copies
141
141
 
142
142
  ## File writes and recovery
143
143
 
144
- `put --expected new` creates a file. Replacements require the current SHA-256 from `get`, a new operation key, and new bytes on stdin. A matching retry returns the recorded outcome only if current bytes still match. Reusing a key with different content or preconditions fails. `operation --key KEY` reports `stored`, `changed`, or `missing` from actual bytes, including after interruption. Previous content is retained in `/state/history/<sha256>`; an operator can export it from the private volume and restore through a new guarded `put`.
144
+ `put --expected new` creates a file. Replacements require the current SHA-256 from `get`, a new operation key, and new bytes on stdin. A matching retry returns the recorded outcome only if current bytes still match. Reusing a key with different content or preconditions fails. `operation --key KEY` reports `stored`, `changed`, or `missing` from actual bytes, including after interruption. On a Git-bound Library it also returns `git: { state, commit }` for the write's path: `pushed` with the last remote commit that changed it (the same bytes are on the remote branch as of the last fetch or push; a removal is `pushed`, with no commit, once the path is absent at the remote tip), `pending` (not on the remote yet, so the next sync cycle carries it; pull-only and ignored files stay pending), or `unknown` (local Git could not be read). It reads local Git only and never calls the network, so `put` never waits on a sync. Verify against the provider with the returned commit when proof beyond the last sync is needed. Previous content is retained in `/state/history/<sha256>`; an operator can export it from the private volume and restore through a new guarded `put`.
145
145
 
146
146
  Intake stages a private hidden temporary file beside its destination and atomically renames it under the Library writer lock, including when `/state/files` is a separate mount. No storage migration is needed.
147
147
 
148
- Maximum intake is 512 MiB per file. Hidden paths, traversal, symlinks and special files are unsupported. `move --path SOURCE --to DEST --expected HASH --key KEY` and `remove --path SOURCE --expected HASH --key KEY` preserve recovery bytes and reject stale revisions. Their operation receipts live in the plugin volume, so child tasks do not need to edit a parent workspace manifest. `list --prefix notes/ --limit 100` is bounded and reports truncation; it is not a full backup manifest. All local commands emit JSON except `get --raw`; errors use stderr. Exit codes: 2 invalid input, 3 conflict/busy, 4 unavailable/uncertain. QMD preserves its native codes.
148
+ Maximum intake is 512 MiB per file; the plugin applies no smaller limit to `put`. A caller that reaches the plugin through a transport with its own stdin or output cap (Ez's plugin broker caps stdin and stdout at 1 MiB per call) is bounded by that cap, not by this plugin. Hidden paths, traversal, symlinks and special files are unsupported. `move --path SOURCE --to DEST --expected HASH --key KEY` and `remove --path SOURCE --expected HASH --key KEY` preserve recovery bytes and reject stale revisions. Their operation receipts live in the plugin volume, so child tasks do not need to edit a parent workspace manifest. `list --prefix notes/ --limit 100` is bounded and reports truncation; it is not a full backup manifest. All local commands emit JSON except `get --raw`; errors use stderr, except `BUSY` from `put` and `replace`, which is JSON on stdout (below). `CONFLICT` stays on stderr with the same exit code 3, so a caller that sees exit 3 reads stdout for `BUSY` and stderr for `CONFLICT`. Exit codes: 2 invalid input, 3 conflict/busy, 4 unavailable/uncertain. QMD preserves its native codes.
149
149
 
150
150
  ## State, lifecycle and limits
151
151
 
@@ -153,7 +153,7 @@ The named `data` volume contains `/state/files`, `settings.json`, `operations`,
153
153
 
154
154
  Stop the plugin before an operator takes a volume snapshot using an existing backup tool. Preserve originals, settings, receipts and history together. QMD indexes/models are rebuildable. Uninstall removes the deployment and registry binding but preserves volumes. Account revocation is a separate action in the provider's plugin/account. See [release and rollback practices](docs/releasing.md).
155
155
 
156
- Library writers take `/state/.writer-lock` in turn: a command waits up to 60 seconds for a live writer (named in the lock's `owner` file) before returning `BUSY`, and a lock without an owner returns `BUSY` after a one-second grace. An interrupted command may leave `/state/.writer-lock`, or QMD's own embed lock below `/state/qmd/cache/qmd`. Confirm no Library client/embedding command is active before removing only the stale lock. Never delete the index or originals as a lock workaround. Run `operation` to reconcile an interrupted file write. Concurrent writes directly to `/state/files` are unsupported. Edit the mapped external folder instead, or use guarded Library commands.
156
+ Library writers take `/state/.writer-lock` in turn: a command waits up to 60 seconds for a live writer (named in the lock's `owner` file; a running sync holds the same lock) before returning `BUSY`, and a lock without an owner returns `BUSY` after a one-second grace. For `put` and `replace`, `BUSY` is JSON on stdout (exit 3), not stderr: `{"ok":false,"error":{"code":"BUSY","message":...,"written":false,"retryAfterSeconds":30}}`. `retryAfterSeconds` appears only while a live writer or sync holds the lock; a lock with no owner or a stuck reclaim omits it and the message says the lock needs attention. The lock is taken before the receipt, so nothing was written and the same `--key` can be retried. There is no queue and no background retry. An interrupted command may leave `/state/.writer-lock`, or QMD's own embed lock below `/state/qmd/cache/qmd`. Confirm no Library client/embedding command is active before removing only the stale lock. Never delete the index or originals as a lock workaround. Run `operation` to reconcile an interrupted file write. Concurrent writes directly to `/state/files` are unsupported. Edit the mapped external folder instead, or use guarded Library commands.
157
157
 
158
158
  ## Development
159
159
 
package/ez-plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "id": "library",
4
- "version": "0.1.0-beta.21",
4
+ "version": "0.1.0-beta.23",
5
5
  "description": "Dockerized agent library files, QMD retrieval and explicit persistence settings",
6
6
  "example": "library search 'quarterly budget' --all --limit 5",
7
7
  "commands": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jc_stack/ez-library",
3
- "version": "0.1.0-beta.21",
3
+ "version": "0.1.0-beta.23",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "latest"
@@ -51,7 +51,7 @@ Refresh the appropriate QMD collection after saving derived text (`qmd update`);
51
51
 
52
52
  ## Onboarding and retrieval
53
53
 
54
- Choose the smallest authorized collection. Input files enter through stdin (`put --path notes/example.md --expected new --key stable-key < source.md`); no host workspace is mounted. Use `get --path ...` for current hashes and `get --raw` for exact bytes. Choose operation keys per logical write and retain them until its outcome is known. Updates require the latest hash; a conflict means re-read and reconsider the update, not force overwrite. `operation --key ...` reconciles current bytes after interruption.
54
+ Choose the smallest authorized collection. Input files enter through stdin (`put --path notes/example.md --expected new --key stable-key < source.md`); no host workspace is mounted. Use `get --path ...` for current hashes and `get --raw` for exact bytes. Choose operation keys per logical write and retain them until its outcome is known. Updates require the latest hash; a conflict means re-read and reconsider the update, not force overwrite. `operation --key ...` reconciles current bytes after interruption; on a Git-bound Library it also says whether the remote has the write (`git.state` `pushed` with `git.commit`, or `pending` until the next sync). A `put` or `replace` that waited 60 seconds for the writer lock fails with JSON on stdout (`BUSY`, `written: false`, and `retryAfterSeconds` while a live writer or sync holds the lock); nothing was written and the same key can be retried.
55
55
 
56
56
  If exact raw output exceeds the executor allowance, read metadata, then call
57
57
  `get --path ... --offset 0 --length 524288 --expected SHA256`. Each response
package/src/cli.mjs CHANGED
@@ -7,16 +7,17 @@ import { Readable } from 'node:stream';
7
7
  import { pipeline } from 'node:stream/promises';
8
8
  import { constants } from 'node:fs';
9
9
  import { fail, rootDir, locked, settings, validateSettings, put, operation, organize, list, safePath, digest, readRange, jsonBytes, defaults, replaceText, MAX_REPLACE_BYTES } from './store.mjs';
10
- import { syncPlan, syncAdopt, syncPolicy, syncRun, syncStatus } from './sync.mjs';
10
+ import { syncConfig, syncPlan, syncAdopt, syncPolicy, syncRun, syncStatus } from './sync.mjs';
11
11
  import { rclone, environment } from './native.mjs';
12
12
  import { indexStatus } from './indexer.mjs';
13
13
  import { embeddingStatus } from './embedding-client.mjs';
14
14
  import { addLibrary, selectLibrary, sources, searchLibraries } from './libraries.mjs';
15
15
  import { mirrorAdopt, mirrorStatus, mirrorPolicy } from './git-mirror.mjs';
16
- import { gitKey, gitAdopt, git } from './git-sync.mjs';
16
+ import { gitKey, gitAdopt, git, remoteReceipt } from './git-sync.mjs';
17
17
  import { gzipFile } from './compress.mjs';
18
18
 
19
19
  const version = JSON.parse(await fs.readFile(new URL('../package.json', import.meta.url))).version;
20
+ const RETRY_AFTER_SECONDS = 30;
20
21
  const emit = data => process.stdout.write(JSON.stringify({ ok: true, data }) + '\n');
21
22
  const help = `ez-library ${version}
22
23
  Local library files, QMD retrieval, and persistence settings.
@@ -30,8 +31,10 @@ Local library files, QMD retrieval, and persistence settings.
30
31
  settings Show settings and revision hash
31
32
  configure --expected HASH|new --key KEY < settings.json
32
33
  put --path RELATIVE --expected HASH|new --key KEY < file
34
+ Waits up to 60 s for the writer lock (or a running sync).
35
+ BUSY: JSON on stdout, written:false (retryAfterSeconds while a live writer holds it); the same --key may be retried
33
36
  replace --path RELATIVE --key KEY < replacement.json
34
- Exact unique before/after text; preserve other bytes
37
+ Exact unique before/after text; preserve other bytes; same lock wait and BUSY as put
35
38
  gzip --path SOURCE --to DEST.gz --expected SOURCE_HASH --key KEY
36
39
  Compress inside Library; retain original
37
40
  get --path RELATIVE [--raw] Metadata/hash, or exact binary stdout
@@ -40,7 +43,8 @@ Local library files, QMD retrieval, and persistence settings.
40
43
  file --library NAME -- RELATIVE Original file bytes for channel delivery (20 MiB)
41
44
  pdf-text --path RELATIVE Poppler text to stdout, page breaks retained
42
45
  list [--prefix TEXT] [--limit 100]
43
- operation --key KEY Recover write outcome from current bytes
46
+ operation --key KEY Recover write outcome from current bytes; on a Git-bound
47
+ Library adds git:{state pushed|pending|unknown, commit}
44
48
  move --path SOURCE --to DEST --expected HASH --key KEY
45
49
  remove --path SOURCE --expected HASH --key KEY Retain recoverable original
46
50
  qmd ... Native QMD CLI with private index/cache
@@ -99,10 +103,11 @@ async function readSettingsInput() {
99
103
  return validateSettings(parsed);
100
104
  }
101
105
  export async function main(argv = process.argv.slice(2)) {
106
+ const command = argv[0];
102
107
  try {
103
108
  if (!argv.length || argv[0] === '--help' || argv[0] === 'help') { process.stdout.write(help); return; }
104
109
  if (argv[0] === '--version') { process.stdout.write(version + '\n'); return; }
105
- const [command, ...args] = argv;
110
+ const args = argv.slice(1);
106
111
  // Local help must not select a library, read state or consume write stdin.
107
112
  // Native provider flags remain untouched.
108
113
  if (!['qmd', 'git', 'rclone'].includes(command) && args.includes('--help')) { process.stdout.write(help); return; }
@@ -237,7 +242,11 @@ export async function main(argv = process.argv.slice(2)) {
237
242
  return;
238
243
  }
239
244
  await rootDir(root);
240
- if (command === 'operation') { emit(await operation(root, opts.key)); return; }
245
+ if (command === 'operation') {
246
+ const view = await operation(root, opts.key), config = await syncConfig(root);
247
+ const receipt = config?.backend === 'git' ? await remoteReceipt(root, config, view) : null;
248
+ emit(receipt ? { ...view, git: receipt } : view); return;
249
+ }
241
250
  if (command === 'list') { emit(await list(root, opts.prefix, opts.limit === undefined ? 100 : Number(opts.limit))); return; }
242
251
  if (command === 'pdf-text') {
243
252
  if (!opts.path) fail('INVALID', 'Supply --path');
@@ -268,6 +277,9 @@ export async function main(argv = process.argv.slice(2)) {
268
277
  const code = error.code || (error instanceof SyntaxError ? 'INVALID' : 'UNAVAILABLE');
269
278
  const invalid = ['INVALID', 'UNSAFE_PATH', 'TOO_LARGE', 'KEY_REUSED'].includes(code) || code.startsWith('ERR_PARSE_ARGS');
270
279
  process.exitCode = invalid ? 2 : ['CONFLICT', 'BUSY'].includes(code) ? 3 : 4;
271
- process.stderr.write(JSON.stringify({ ok: false, error: { code, message: error.message } }) + '\n');
280
+ // A write that waited out the lock reports on stdout, in the same shape as a result, and says nothing was written.
281
+ const busyWrite = code === 'BUSY' && ['put', 'replace'].includes(command);
282
+ const body = { code, message: error.message, ...(busyWrite ? { written: false, ...(error.retryable ? { retryAfterSeconds: RETRY_AFTER_SECONDS } : {}) } : {}) };
283
+ (busyWrite ? process.stdout : process.stderr).write(JSON.stringify({ ok: false, error: body }) + '\n');
272
284
  }
273
285
  }
package/src/git-sync.mjs CHANGED
@@ -152,6 +152,28 @@ export async function gitAdopt(root, repository, branch = 'main', stateRoot = ro
152
152
  });
153
153
  }
154
154
 
155
+ // Whether the remote, as of the last fetch or push, holds what a write receipt names: the
156
+ // file's bytes, or for a removal its absence at the remote tip. Reads local Git only (paths are
157
+ // literal, never pathspec patterns) and never touches the network. For a present file `commit` is
158
+ // the last remote commit that changed the path; a removal has none. pull-only and ignored files stay pending.
159
+ export async function remoteReceipt(root, config, view) {
160
+ const present = ['stored', 'moved'].includes(view.state);
161
+ if (view.kind === 'settings' || !(present || view.state === 'removed')) return null;
162
+ const name = view.kind === 'move' ? view.to : view.path;
163
+ const read = async args => { const r = await git(root, config, ['--literal-pathspecs', ...args]); return r.code === 0 ? r.stdout.trim() : null; };
164
+ const tip = await read(['rev-parse', '--verify', '--quiet', 'refs/remotes/origin/' + config.branch]);
165
+ if (!tip) return { state: 'pending', commit: null };
166
+ const entry = await read(['ls-tree', tip, '--', name]);
167
+ if (entry === null) return { state: 'unknown', commit: null };
168
+ const remote = /^\d+ blob ([a-f0-9]+)\t/.exec(entry)?.[1] ?? null;
169
+ if (!present) return { state: remote === null ? 'pushed' : 'pending', commit: null };
170
+ const local = await read(['hash-object', '--no-filters', '--', path.join(root, 'files', name)]);
171
+ if (local === null) return { state: 'unknown', commit: null };
172
+ if (remote !== local) return { state: 'pending', commit: null };
173
+ const commit = await read(['log', '-n', '1', '--format=%H', tip, '--', name]);
174
+ return commit ? { state: 'pushed', commit } : { state: 'unknown', commit: null };
175
+ }
176
+
155
177
  export async function gitTransfer(root, config, step = async () => {}) {
156
178
  if (!['two-way', 'pull-only'].includes(config.mode)) fail('INVALID', 'Use two-way or pull-only Git sync');
157
179
  const pullOnly = config.mode === 'pull-only';
package/src/store.mjs CHANGED
@@ -16,6 +16,10 @@ export const MAX_FILE_BYTES = 512 * 1024 * 1024;
16
16
  export const MAX_READ_BYTES = 512 * 1024;
17
17
  export const MAX_REPLACE_BYTES = 256 * 1024;
18
18
  const MAX_TEXT_BYTES = 8 * 1024 * 1024;
19
+ // Library content (files/) is read and edited by the agent's executor, which is not the Library's user:
20
+ // owner and group read/write, nothing for others. Under a default ACL the group bits become the ACL mask,
21
+ // so 0600 (or 0700 for a directory) would silently mask every named-user entry to no access. State stays 0600/0700.
22
+ export const CONTENT_MODE = 0o660, CONTENT_DIR_MODE = 0o770;
19
23
  export const defaults = () => ({ schemaVersion: 1, storage: { mode: 'local' }, backup: { mode: 'off' } });
20
24
 
21
25
  function keys(value, allowed) {
@@ -60,13 +64,14 @@ export async function rootDir(root, create = false) {
60
64
  if (!stat.isDirectory() || stat.isSymbolicLink()) fail('UNSAFE_PATH', 'State must be a real private directory');
61
65
  return fs.realpath(root);
62
66
  }
67
+ // makeParents creates private parents; a number sets their mode instead (content directories).
63
68
  export async function safePath(root, relative, makeParents = false) {
64
69
  if (typeof relative !== 'string' || !relative || relative.length > 1024 || /[\\\x00-\x1f\x7f]/.test(relative) || relative.split('/').some(p => !p || p.startsWith('.'))) fail('UNSAFE_PATH', 'Use a relative path without hidden, empty or parent components');
65
70
  const parts = relative.split('/');
66
71
  let target = root;
67
72
  for (let i = 0; i < parts.length; i++) {
68
73
  target = path.join(target, parts[i]);
69
- if (makeParents && i < parts.length - 1) await fs.mkdir(target, { mode: 0o700 }).catch(e => { if (e.code !== 'EEXIST') throw e; });
74
+ if (makeParents && i < parts.length - 1) await fs.mkdir(target, { mode: typeof makeParents === 'number' ? makeParents : 0o700 }).catch(e => { if (e.code !== 'EEXIST') throw e; });
70
75
  const st = await fs.lstat(target).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
71
76
  if (st && (st.isSymbolicLink() || (i < parts.length - 1 ? !st.isDirectory() : !st.isFile()))) fail('UNSAFE_PATH', 'Symlinks and special files are unsupported');
72
77
  }
@@ -132,9 +137,15 @@ async function acquire(lock, signal) {
132
137
  }
133
138
  ownerless = owner ? null : ownerless ?? Date.now();
134
139
  if (ownerless !== null && Date.now() - ownerless >= OWNERLESS_GRACE_MS)
135
- fail('BUSY', 'Writer lock exists without an owner; confirm no command is active before recovering an interrupted operation');
136
- if (Date.now() - started >= LOCK_WAIT_MS)
137
- fail('BUSY', `Writer lock held by pid ${owner?.pid} on ${owner?.host} since ${owner?.at}; confirm it is active before recovering an interrupted operation${await fs.stat(`${lock}.reclaim`).then(() => ` (an interrupted reclaim also left ${lock}.reclaim)`, () => '')}`);
140
+ fail('BUSY', 'Writer lock needs attention: it exists without an owner; confirm no command is active before recovering an interrupted operation');
141
+ if (Date.now() - started >= LOCK_WAIT_MS) {
142
+ // Retrying can help only while a live writer or sync holds the lock.
143
+ const stuck = await fs.stat(`${lock}.reclaim`).then(() => true, () => false);
144
+ const live = Boolean(owner) && !stuck && (owner.host !== hostname() || alive(owner.pid));
145
+ const error = new LibraryError('BUSY', `Writer lock ${live ? 'held' : 'needs attention: held'} by pid ${owner?.pid} on ${owner?.host} since ${owner?.at}; confirm it is active before recovering an interrupted operation${stuck ? ` (an interrupted reclaim also left ${lock}.reclaim)` : ''}`);
146
+ error.retryable = live;
147
+ throw error;
148
+ }
138
149
  await sleep(100 + Math.random() * 150, undefined, { signal });
139
150
  }
140
151
  }
@@ -204,9 +215,9 @@ export async function readRange(file, { offset, length, expected }) {
204
215
  } finally { await handle.close(); }
205
216
  }
206
217
  async function current(file) { return digest(file).catch(e => { if (e.code === 'ENOENT') return null; throw e; }); }
207
- export async function atomic(file, data) {
218
+ export async function atomic(file, data, mode = 0o600) {
208
219
  const temp = `${file}.${randomUUID()}.tmp`;
209
- try { await fs.writeFile(temp, data, { mode: 0o600, flag: 'wx' }); await fs.rename(temp, file); }
220
+ try { await fs.writeFile(temp, data, { mode, flag: 'wx' }); await fs.rename(temp, file); }
210
221
  finally { await fs.rm(temp, { force: true }); }
211
222
  }
212
223
  const jsonBytes = value => Buffer.from(JSON.stringify(value, null, 2) + '\n');
@@ -229,7 +240,7 @@ export async function put(root, relative, input, { key, expected, kind = 'file',
229
240
  const receiptFile = operationPath(root, key);
230
241
  await safePath(root, path.relative(root, receiptFile));
231
242
  if (kind === 'file' && (typeof relative !== 'string' || !relative)) fail('INVALID', 'Supply a relative file path');
232
- const target = await safePath(root, kind === 'settings' ? 'settings.json' : 'files/' + relative, true);
243
+ const target = await safePath(root, kind === 'settings' ? 'settings.json' : 'files/' + relative, CONTENT_DIR_MODE);
233
244
  // files may be a separate bind mount: stage on the destination filesystem.
234
245
  const temp = path.join(path.dirname(target), '.ez-library-put-' + randomUUID() + '.tmp');
235
246
  let bytes = 0; const sha = createHash('sha256');
@@ -238,7 +249,7 @@ export async function put(root, relative, input, { key, expected, kind = 'file',
238
249
  bytes += chunk.length;
239
250
  if (bytes > maxBytes) return cb(new LibraryError('TOO_LARGE', `Input exceeds ${maxBytes} bytes`));
240
251
  sha.update(chunk); cb(null, chunk);
241
- } }), createWriteStream(temp, { flags: 'wx', mode: 0o600 }));
252
+ } }), createWriteStream(temp, { flags: 'wx', mode: kind === 'file' ? CONTENT_MODE : 0o600 }));
242
253
  const request = { kind, path: kind === 'settings' ? 'settings.json' : relative, bytes, sha256: sha.digest('hex'), expected,
243
254
  ...(source ? { source } : {}) };
244
255
  const oldReceipt = await fs.readFile(receiptFile, 'utf8').then(JSON.parse).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
@@ -342,7 +353,7 @@ export async function replaceText(root, relative, replacement, { key } = {}) {
342
353
  await fs.copyFile(target, history, constants.COPYFILE_EXCL).catch(error => { if (error.code !== 'EEXIST') throw error; });
343
354
  await fs.chmod(history, 0o600);
344
355
  await atomic(receiptFile, jsonBytes(request));
345
- await atomic(target, next);
356
+ await atomic(target, next, CONTENT_MODE);
346
357
  const after = await replacementView(root, request);
347
358
  if (after.state !== 'stored' || after.sha256 !== hash(next)) fail('UNCERTAIN', 'Replacement readback differs; inspect operation before retry');
348
359
  return { ...after, replay: false };
@@ -354,7 +365,7 @@ export async function organize(root, { path: relative, to, expected, key }) {
354
365
  if (relative === 'LIBRARY_SYNC_ACCESS' || to === 'LIBRARY_SYNC_ACCESS') fail('INVALID', 'The sync access marker is reserved');
355
366
  return locked(root, async root => {
356
367
  const source = await safePath(root, 'files/' + relative);
357
- const target = to === undefined ? null : await safePath(root, 'files/' + to, true);
368
+ const target = to === undefined ? null : await safePath(root, 'files/' + to, CONTENT_DIR_MODE);
358
369
  if (target === source) fail('INVALID', 'Source and destination must differ');
359
370
  const receipt = { kind: target ? 'move' : 'remove', path: relative, ...(target ? { to } : {}), expected };
360
371
  const file = await safePath(root, path.relative(root, operationPath(root, key)));
package/src/sync.mjs CHANGED
@@ -68,6 +68,8 @@ async function inspect(root, remote, stateRoot) {
68
68
  return { remote, identity, files: entries.filter(file => !file.IsDir) };
69
69
  }
70
70
 
71
+ export const syncConfig = root => readJSON(location(root));
72
+
71
73
  export async function syncStatus(root) {
72
74
  const config = await readJSON(location(root));
73
75
  return { config, revision: config ? hash(jsonBytes(config)) : null,
@@ -27,7 +27,7 @@ test('gzip keeps large binary data inside Library and records source/target proo
27
27
  assert.equal(result.source.sha256, hash(data));
28
28
  assert.equal(result.source.bytes, data.length);
29
29
  assert.equal(result.state, 'stored');
30
- assert.equal((await fs.stat(path.join(root, 'files', request.to))).mode & 0o777, 0o600);
30
+ assert.equal((await fs.stat(path.join(root, 'files', request.to))).mode & 0o047, 0o040); // group-readable, nothing for others
31
31
  assert.deepEqual(await fs.readFile(path.join(root, 'files', request.path)), data);
32
32
  assert.equal((await operation(root, request.key)).state, 'stored');
33
33
  assert.equal((await gzipFile(root, request)).replay, true);
@@ -5,8 +5,8 @@ import path from 'node:path';
5
5
  import { tmpdir } from 'node:os';
6
6
  import { execFileSync } from 'node:child_process';
7
7
  import { Readable } from 'node:stream';
8
- import { gitAdopt, gitTransfer, git, repositoryURL } from '../src/git-sync.mjs';
9
- import { locked, put, digest, organize, jsonBytes } from '../src/store.mjs';
8
+ import { gitAdopt, gitTransfer, git, repositoryURL, remoteReceipt } from '../src/git-sync.mjs';
9
+ import { locked, put, digest, organize, jsonBytes, operation } from '../src/store.mjs';
10
10
  import { syncPolicy, syncRun, syncStatus } from '../src/sync.mjs';
11
11
 
12
12
  async function setup(t) {
@@ -338,3 +338,84 @@ test('a bounded call that exits in time settles even while a grandchild still ho
338
338
  const result = await native(root, '/bin/sh', ['-c', 'sleep 2 & exit 0'], { timeout: 500 });
339
339
  assert.equal(result.code, 0);
340
340
  });
341
+
342
+ test('a read by key says whether the remote holds the write and names the commit, with no network call', async t => {
343
+ const { root, remote, outside } = await setup(t);
344
+ const { config } = await gitAdopt(root, remote);
345
+ const saved = await put(root, 'agent.md', Readable.from(['# Agent\nSaffron notebook.']), { expected: 'new', key: 'receipt:put' });
346
+ const receipt = async key => remoteReceipt(root, config, await operation(root, key));
347
+ assert.deepEqual(await receipt('receipt:put'), { state: 'pending', commit: null });
348
+ // Break the remote: a read by key must still answer from local Git.
349
+ const url = (await git(root, config, ['remote', 'get-url', 'origin'])).stdout.trim();
350
+ await git(root, config, ['remote', 'set-url', 'origin', remote + '-gone']);
351
+ assert.deepEqual(await receipt('receipt:put'), { state: 'pending', commit: null });
352
+ await git(root, config, ['remote', 'set-url', 'origin', url]);
353
+ const result = await cycle(root, config);
354
+ const pushed = await receipt('receipt:put');
355
+ assert.equal(pushed.state, 'pushed');
356
+ assert.equal(pushed.commit, outside(['--git-dir', remote, 'log', '-n', '1', '--format=%H', 'main', '--', 'agent.md']).trim());
357
+ assert.equal(pushed.commit, result.commit);
358
+ // A newer local version is pending again, and a move or remove follows its own destination.
359
+ const next = await put(root, 'agent.md', Readable.from(['# Agent\nSecond.']), { expected: saved.sha256, key: 'receipt:edit' });
360
+ assert.equal((await receipt('receipt:edit')).state, 'pending');
361
+ await cycle(root, config);
362
+ assert.equal((await receipt('receipt:edit')).state, 'pushed');
363
+ await organize(root, { path: 'agent.md', to: 'moved/agent.md', expected: next.sha256, key: 'receipt:move' });
364
+ assert.equal((await receipt('receipt:move')).state, 'pending');
365
+ await cycle(root, config);
366
+ assert.equal((await receipt('receipt:move')).state, 'pushed');
367
+ await organize(root, { path: 'moved/agent.md', expected: next.sha256, key: 'receipt:remove' });
368
+ assert.equal((await receipt('receipt:remove')).state, 'pending');
369
+ await cycle(root, config);
370
+ assert.deepEqual(await receipt('receipt:remove'), { state: 'pushed', commit: null });
371
+ // A deletion made before this write is not this write's: only absence at the tip counts, and it has no commit.
372
+ await put(root, 'again.md', Readable.from(['x']), { expected: 'new', key: 'receipt:again' });
373
+ await cycle(root, config);
374
+ const again = await digest(path.join(root, 'files/again.md'));
375
+ await organize(root, { path: 'again.md', expected: again.sha256, key: 'receipt:again-remove' });
376
+ assert.deepEqual(await receipt('receipt:again-remove'), { state: 'pending', commit: null });
377
+ });
378
+
379
+ test('receipt paths are literal names, never pathspec patterns', async t => {
380
+ const { root, remote, outside } = await setup(t);
381
+ const { config } = await gitAdopt(root, remote);
382
+ const same = await fs.readFile(path.join(root, 'files/note0.md'));
383
+ const receipt = async key => remoteReceipt(root, config, await operation(root, key));
384
+ // Same bytes as the remote's note0.md, under names that a pathspec would resolve to it.
385
+ for (const [i, name] of [':note0.md', 'note[0].md', 'note?.md', '*.md'].entries()) {
386
+ await put(root, name, Readable.from([same]), { expected: 'new', key: `literal:${i}` });
387
+ assert.deepEqual(await receipt(`literal:${i}`), { state: 'pending', commit: null }, name);
388
+ }
389
+ await cycle(root, config);
390
+ for (const [i, name] of [':note0.md', 'note[0].md', 'note?.md', '*.md'].entries()) {
391
+ const done = await receipt(`literal:${i}`);
392
+ assert.equal(done.state, 'pushed', name);
393
+ assert.equal(done.commit, outside(['--literal-pathspecs', '--git-dir', remote, 'log', '-n', '1', '--format=%H', 'main', '--', name]).trim(), name);
394
+ }
395
+ });
396
+
397
+ test('operation --key does not depend on the sync status or text mirror files', async t => {
398
+ const { root, remote } = await setup(t);
399
+ const cli = new URL('../bin/ez-library.mjs', import.meta.url).pathname;
400
+ await gitAdopt(root, remote);
401
+ await put(root, 'a.md', Readable.from(['a']), { expected: 'new', key: 'k' });
402
+ await fs.writeFile(path.join(root, 'sync/text-mirror.json'), '{ not json');
403
+ await fs.writeFile(path.join(root, 'sync/status.json'), '{ not json');
404
+ const out = JSON.parse(execFileSync(process.execPath, [cli, 'operation', '--key', 'k'], { encoding: 'utf8', env: { ...process.env, EZ_LIBRARY_STATE: root } })).data;
405
+ assert.equal(out.state, 'stored'); assert.equal(out.git.state, 'pending');
406
+ });
407
+
408
+ test('operation --key adds the Git receipt only on a Git-bound Library', async t => {
409
+ const { base, root, remote } = await setup(t);
410
+ const cli = new URL('../bin/ez-library.mjs', import.meta.url).pathname;
411
+ const read = (state, key) => JSON.parse(execFileSync(process.execPath, [cli, 'operation', '--key', key], { encoding: 'utf8', env: { ...process.env, EZ_LIBRARY_STATE: state } })).data;
412
+ const plain = path.join(base, 'plain');
413
+ await put(plain, 'a.md', Readable.from(['a']), { expected: 'new', key: 'k' });
414
+ assert.equal(read(plain, 'k').git, undefined);
415
+ const { config } = await gitAdopt(root, remote);
416
+ await put(root, 'a.md', Readable.from(['a']), { expected: 'new', key: 'k' });
417
+ assert.equal(read(root, 'k').git.state, 'pending');
418
+ await cycle(root, config);
419
+ const after = read(root, 'k');
420
+ assert.equal(after.state, 'stored'); assert.equal(after.git.state, 'pushed'); assert.match(after.git.commit, /^[a-f0-9]{40}$/);
421
+ });
@@ -23,7 +23,7 @@ test('intake preserves binary bytes, private modes, literal paths and replay acr
23
23
  const r = await put(root, relative, input(data), { key: 'binary:1', expected: 'new' });
24
24
  assert.equal(r.state, 'stored'); assert.equal(r.sha256, hash(data));
25
25
  assert.deepEqual(await fs.readFile(path.join(root, 'files', relative)), data);
26
- assert.equal((await fs.stat(path.join(root, 'files', relative))).mode & 0o777, 0o600);
26
+ assert.equal((await fs.stat(path.join(root, 'files', relative))).mode & 0o047, 0o040); // group-readable, nothing for others
27
27
  assert.equal((await put(root, relative, input(data), { key: 'binary:1', expected: 'new' })).replay, true);
28
28
  const read = spawnSync(process.execPath, [cli, 'get', '--path', relative, '--raw'], { env: { ...process.env, EZ_LIBRARY_STATE: root } });
29
29
  assert.equal(read.status, 0); assert.deepEqual(read.stdout, data);
@@ -283,3 +283,46 @@ test('local subcommand help succeeds before configuration or write intake',async
283
283
  }
284
284
  assert.deepEqual(await fs.readdir(root),[]);
285
285
  });
286
+
287
+ const run = (root, args, stdin) => spawnSync(process.execPath, [cli, ...args], { input: stdin, env: { ...process.env, EZ_LIBRARY_STATE: root } });
288
+
289
+ test('non-ASCII text survives put byte for byte, including a character split across stream chunks and pipe buffers', async t => {
290
+ const root = await fixture(t), dash = Buffer.from('–');
291
+ assert.deepEqual([...dash], [0xe2, 0x80, 0x93]);
292
+ // Split the en dash across chunks at each byte boundary, then straddle the 64 KiB pipe buffer through the CLI.
293
+ const text = Buffer.from('range 1–2 – café 😀\n');
294
+ for (const cut of [1, 2, 3, 4, text.length - 1]) {
295
+ await put(root, `split/${cut}.md`, Readable.from([text.subarray(0, cut), text.subarray(cut)]), { key: `split:${cut}`, expected: 'new' });
296
+ assert.deepEqual(await fs.readFile(path.join(root, 'files/split', `${cut}.md`)), text);
297
+ }
298
+ for (const at of [65535, 65536, 65537, 131071]) {
299
+ const body = Buffer.concat([Buffer.alloc(at, 97), dash, Buffer.alloc(70000, 98)]);
300
+ const stored = run(root, ['put', '--path', `big/${at}.md`, '--expected', 'new', '--key', `cli:${at}`], body);
301
+ assert.equal(stored.status, 0, stored.stderr);
302
+ assert.deepEqual(await fs.readFile(path.join(root, 'files/big', `${at}.md`)), body);
303
+ const read = run(root, ['get', '--path', `big/${at}.md`, '--raw']);
304
+ assert.deepEqual(read.stdout, body); assert(!body.includes(Buffer.from('�')));
305
+ }
306
+ });
307
+
308
+ test('put and replace that cannot get the writer lock say so as JSON on stdout, wrote nothing, and the same key succeeds later', async t => {
309
+ const root = await fixture(t), lock = path.join(root, '.writer-lock');
310
+ await fs.mkdir(lock);
311
+ const blocked = run(root, ['put', '--path', 'a.md', '--expected', 'new', '--key', 'busy:1'], 'data');
312
+ assert.equal(blocked.status, 3); assert.equal(blocked.stderr.length, 0);
313
+ const body = JSON.parse(blocked.stdout);
314
+ assert.equal(body.ok, false); assert.equal(body.error.code, 'BUSY');
315
+ // A lock with no owner cannot clear by waiting: no retry hint, and the message says it needs attention.
316
+ assert.equal(body.error.written, false); assert.equal('retryAfterSeconds' in body.error, false);
317
+ assert.match(body.error.message, /needs attention/);
318
+ await assert.rejects(fs.stat(path.join(root, 'files/a.md')), code('ENOENT'));
319
+ assert.deepEqual(await fs.readdir(path.join(root, 'operations')).catch(() => []), []);
320
+ const replace = run(root, ['replace', '--path', 'a.md', '--key', 'busy:2'], JSON.stringify({ before: 'x', after: 'y' }));
321
+ assert.equal(replace.status, 3); assert.equal(JSON.parse(replace.stdout).error.written, false);
322
+ // Other commands keep their stderr contract.
323
+ const other = run(root, ['move', '--path', 'a.md', '--to', 'b.md', '--expected', 'a'.repeat(64), '--key', 'busy:3']);
324
+ assert.equal(other.stdout.length, 0); assert.equal(JSON.parse(other.stderr).error.code, 'BUSY');
325
+ await fs.rmdir(lock);
326
+ const retried = run(root, ['put', '--path', 'a.md', '--expected', 'new', '--key', 'busy:1'], 'data');
327
+ assert.equal(retried.status, 0, retried.stderr); assert.equal(JSON.parse(retried.stdout).data.state, 'stored');
328
+ });
@@ -29,7 +29,7 @@ test('scoped replacements preserve interleaved writers, exact bytes and replay',
29
29
  assert.equal((await replaceText(root, 'runs/day.md', a, { key: 'a' })).replay, true);
30
30
  assert.equal(await read(root), expected);
31
31
  assert.equal(await fs.readFile(path.join(root, 'history', hash(initial)), 'utf8'), initial);
32
- assert.equal((await fs.stat(path.join(root, 'files/runs/day.md'))).mode & 0o777, 0o600);
32
+ assert.equal((await fs.stat(path.join(root, 'files/runs/day.md'))).mode & 0o047, 0o040); // group-readable, nothing for others
33
33
  assert.equal('before' in await operation(root, 'a'), false);
34
34
  // A changed owning block does not become a stale overwrite on replay.
35
35
  await replaceText(root, 'runs/day.md', { before: a.after, after: a.after + 'new progress\r\n' }, { key: 'a2' });
@@ -88,3 +88,20 @@ test('replace CLI uses bounded JSON, not shell or regex interpretation', async t
88
88
  assert.equal(run(Buffer.from([255])).status, 2);
89
89
  assert.equal(run(' '.repeat(MAX_REPLACE_BYTES + 1)).status, 2);
90
90
  });
91
+
92
+ test('content files and directories are group read/write for the executor; state stays private', async t => {
93
+ // A default ACL on the content directory turns the group bits into its mask, so a 0600 file hides every
94
+ // named-user ACL entry (the agent's executor) from its own workspace. Keep the creation mode, whatever the umask.
95
+ const previous = process.umask(0); t.after(() => process.umask(previous));
96
+ const root = await fixture(t);
97
+ const mode = file => fs.stat(path.join(root, file)).then(s => s.mode & 0o777);
98
+ assert.equal(await mode('files/runs/day.md'), 0o660);
99
+ assert.equal(await mode('files/runs'), 0o770);
100
+ await replaceText(root, 'runs/day.md', a, { key: 'mode-a' });
101
+ assert.equal(await mode('files/runs/day.md'), 0o660);
102
+ await replaceText(root, 'runs/day.md', b, { key: 'mode-b' });
103
+ const stateFiles = [...await fs.readdir(path.join(root, 'history')).then(n => n.map(x => 'history/' + x)),
104
+ ...await fs.readdir(path.join(root, 'operations')).then(n => n.map(x => 'operations/' + x))];
105
+ assert.ok(stateFiles.length >= 3);
106
+ for (const file of stateFiles) assert.equal(await mode(file), 0o600, file);
107
+ });