@jc_stack/ez-library 0.1.0-beta.22 → 0.1.0-beta.24

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.24
4
+
5
+ - `put --from-file ABSOLUTE_PATH` writes a file above the host's 1 MiB stdin cap: the service now declares `workspace: true` (read-only agent workspace) and the plugin streams the file from there. The path must be absolute and resolve to a regular file inside the workspace root named by `EZ_AGENT_WORKSPACE`; a relative or outside path, a directory, an unreadable file, a symlink leaving the workspace, or a host that does not set the variable fail with exit 2 before anything is written. The file is the only source and stdin is ignored (never read). The check applies to the open handle: the kernel's path for it (`/proc/self/fd/N`) must be a regular file inside the workspace, so a directory swapped for a symlink meanwhile is refused; where `/proc/self/fd` does not exist (not Linux) the flag is refused and stdin remains. `--expected`, `--key`, the writer lock, the receipt and the 512 MiB limit are unchanged. Reads of large files use `get --offset/--length`; the 1 MiB limit applies to stdin and command output. Requires a core that sets `EZ_AGENT_WORKSPACE` (jdorado/ez-agents#390); the service now mounts the workspace, so installing needs the manager's normal activation. Closes #58.
6
+
7
+ ## 0.1.0-beta.23
8
+
9
+ - `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.
10
+ - `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.
11
+ - Tests: a non-ASCII character (en dash, accents, emoji) survives `put` byte for byte, including when split across stream chunks and pipe buffers.
12
+
3
13
  ## 0.1.0-beta.22
4
14
 
5
15
  - 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`.
package/README.md CHANGED
@@ -68,7 +68,7 @@ ez library qmd search 'passport' -c library --json -n 5
68
68
  ez library qmd get qmd://library/notes/travel.md
69
69
  ```
70
70
 
71
- `get` returns the content hash and size; `get --raw` emits exact bytes, including binary attachments. Files enter on stdin, so the plugin does not mount the agent workspace or infer host file access. Readback proves local storage only. Each agent's registry provides a separate data volume; never share it across identities merely to share search.
71
+ `get` returns the content hash and size; `get --raw` emits exact bytes, including binary attachments. Files enter on stdin, or, above the host's 1 MiB stdin cap, by `put --from-file ABSOLUTE_PATH`: the service mounts the agent workspace read-only (`workspace: true`) and the plugin reads the file there, only inside the workspace root the host names in `EZ_AGENT_WORKSPACE`. Readback proves local storage only. Each agent's registry provides a separate data volume; never share it across identities merely to share search.
72
72
 
73
73
  For files larger than the executor's output allowance, first read metadata,
74
74
  then use `get --path RELATIVE --offset 0 --length 524288 --expected SHA256`.
@@ -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`. Ez's plugin broker caps stdin and command output at 1 MiB each per call, so stdin carries at most 1 MiB. Write a larger file with `put --path RELATIVE --expected new --key KEY --from-file /absolute/workspace/path` (the file is the only source and stdin is ignored; everything else about `put` is unchanged), and read it back with `get --offset/--length`. A `--from-file` path must be absolute, resolve to a regular file inside the workspace root (symlinks that leave it are refused) and the host must provide `EZ_AGENT_WORKSPACE`; otherwise the call fails before anything is written. An installer must declare the service's workspace mount, which core applies on install. 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
 
@@ -6,6 +6,7 @@
6
6
  "volumes": {
7
7
  "data": "/state"
8
8
  },
9
+ "workspace": true,
9
10
  "healthcheck": [
10
11
  "node",
11
12
  "/app/bin/ez-library.mjs",
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.22",
4
+ "version": "0.1.0-beta.24",
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.22",
3
+ "version": "0.1.0-beta.24",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "latest"
@@ -17,6 +17,8 @@ for(const [alias,command] of Object.entries(manifest.commands||{})) {
17
17
  }
18
18
  assert.deepEqual(manifest.commands.library?.exposure,expectedExposure,'library exposure must conservatively describe its broad read/write/sync surface');
19
19
  for(const alias of ['library-file','library-query']) assert.deepEqual(manifest.commands[alias]?.exposure,readOnlyExposure,`${alias} must remain read-only`);
20
+ const deployment=JSON.parse(readFileSync('ez-deployment.json','utf8'));
21
+ assert.equal(deployment.services.library?.workspace,true,'The library service must mount the agent workspace read-only for put --from-file');
20
22
  const [pack]=JSON.parse(execFileSync('npm',['pack','--dry-run','--ignore-scripts','--json'],{encoding:'utf8'}));
21
23
  const names=pack.files.map(f=>f.path);
22
24
  for(const required of ['LICENSE','README.md','SECURITY.md','CONTRIBUTING.md','CHANGELOG.md','THIRD_PARTY_NOTICES.md','Dockerfile','.dockerignore','docker/pnpm-lock.yaml']) assert(names.includes(required),`Missing ${required}`);
@@ -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`) up to the host's 1 MiB stdin cap. For a larger file, give its absolute path in the read-only agent workspace: `put --path big/example.pdf --expected new --key stable-key --from-file /absolute/workspace/example.pdf` (the file is the only source and stdin is ignored; refused before any write if the path is relative, outside the workspace, not a regular file, or the host does not provide the workspace root). Read large files back with `get --offset/--length`; stdin and command output are both capped at 1 MiB. 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,15 @@ 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
+ put --path RELATIVE --expected HASH|new --key KEY --from-file ABSOLUTE_WORKSPACE_PATH
35
+ Same write from a file in the agent workspace (read-only mount),
36
+ for files above the host's 1 MiB stdin cap. The file is the only
37
+ source; stdin is ignored. A relative or outside path, a directory
38
+ or a symlink out of the workspace is refused before any write
39
+ Waits up to 60 s for the writer lock (or a running sync).
40
+ BUSY: JSON on stdout, written:false (retryAfterSeconds while a live writer holds it); the same --key may be retried
33
41
  replace --path RELATIVE --key KEY < replacement.json
34
- Exact unique before/after text; preserve other bytes
42
+ Exact unique before/after text; preserve other bytes; same lock wait and BUSY as put
35
43
  gzip --path SOURCE --to DEST.gz --expected SOURCE_HASH --key KEY
36
44
  Compress inside Library; retain original
37
45
  get --path RELATIVE [--raw] Metadata/hash, or exact binary stdout
@@ -40,7 +48,8 @@ Local library files, QMD retrieval, and persistence settings.
40
48
  file --library NAME -- RELATIVE Original file bytes for channel delivery (20 MiB)
41
49
  pdf-text --path RELATIVE Poppler text to stdout, page breaks retained
42
50
  list [--prefix TEXT] [--limit 100]
43
- operation --key KEY Recover write outcome from current bytes
51
+ operation --key KEY Recover write outcome from current bytes; on a Git-bound
52
+ Library adds git:{state pushed|pending|unknown, commit}
44
53
  move --path SOURCE --to DEST --expected HASH --key KEY
45
54
  remove --path SOURCE --expected HASH --key KEY Retain recoverable original
46
55
  qmd ... Native QMD CLI with private index/cache
@@ -58,7 +67,8 @@ Local library files, QMD retrieval, and persistence settings.
58
67
  git ... Native Git in the bound Library working tree
59
68
 
60
69
  Local commands emit JSON (--json is also accepted); get --raw and qmd preserve
61
- native output. Files are limited to 512 MiB. Existing files require their current
70
+ native output. Files are limited to 512 MiB. The host caps stdin and command output
71
+ at 1 MiB each: write larger files with put --from-file; read them with get --offset/--length. Existing files require their current
62
72
  SHA-256. Stable operation keys cannot be reused for different writes.
63
73
  State: EZ_LIBRARY_STATE (absolute), default /state. Production uses the agent's
64
74
  registered Docker plugin. Credentials belong to provider tools, never settings.
@@ -98,11 +108,45 @@ async function readSettingsInput() {
98
108
  catch { fail('INVALID', 'Settings must be valid JSON'); }
99
109
  return validateSettings(parsed);
100
110
  }
111
+ // A file larger than the host's 1 MiB stdin cap arrives by its path in the read-only workspace mount.
112
+ // Core names that workspace in EZ_AGENT_WORKSPACE; the root is never guessed. Stdin is not read.
113
+ // The check applies to the open handle, not to a name: after the open the kernel's own path for that
114
+ // descriptor (/proc/self/fd/N) must be a regular file inside the workspace, so no later rename or symlink
115
+ // swap can change the answer. The runtime is a Linux container; without /proc/self/fd the flag is refused.
116
+ // `hooks` lets a test change the tree between the steps or move the probe; the CLI passes none.
117
+ const inside = (root, file) => file.startsWith(root + path.sep);
118
+ async function workspaceFile(from, hooks = {}) {
119
+ const workspace = process.env.EZ_AGENT_WORKSPACE, procFd = hooks.procFd ?? '/proc/self/fd';
120
+ if (!workspace) fail('INVALID', '--from-file needs the host to provide the workspace root (EZ_AGENT_WORKSPACE), which this host does not; send the file on stdin (at most 1 MiB through the host) or upgrade the host');
121
+ if (!path.isAbsolute(from)) fail('INVALID', '--from-file must be an absolute path inside the workspace');
122
+ if (!await fs.stat(procFd).then(stat => stat.isDirectory(), () => false)) fail('INVALID', '--from-file needs /proc/self/fd, which exists only on Linux (the plugin runs in a Linux container); send the file on stdin instead');
123
+ const unreadable = () => fail('INVALID', '--from-file cannot be read inside the workspace');
124
+ let root, real;
125
+ try { root = await fs.realpath(workspace); real = await fs.realpath(from); } catch { unreadable(); }
126
+ if (!inside(root, real)) fail('UNSAFE_PATH', '--from-file must stay inside the workspace');
127
+ await hooks.beforeOpen?.();
128
+ let handle;
129
+ try { handle = await fs.open(real, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } catch { unreadable(); }
130
+ try {
131
+ await hooks.afterOpen?.();
132
+ let opened;
133
+ try { opened = await fs.realpath(`${procFd}/${handle.fd}`); } catch { unreadable(); }
134
+ if (!inside(root, opened)) fail('UNSAFE_PATH', '--from-file must stay inside the workspace');
135
+ if (!(await handle.stat()).isFile()) fail('UNSAFE_PATH', '--from-file must be a regular file');
136
+ return handle;
137
+ } catch (error) { await handle.close(); throw error; }
138
+ }
139
+ export async function putFromFile(root, relative, from, options, hooks) {
140
+ const source = await workspaceFile(from, hooks);
141
+ try { return await put(root, relative, source.createReadStream({ autoClose: false }), options); }
142
+ finally { await source.close(); }
143
+ }
101
144
  export async function main(argv = process.argv.slice(2)) {
145
+ const command = argv[0];
102
146
  try {
103
147
  if (!argv.length || argv[0] === '--help' || argv[0] === 'help') { process.stdout.write(help); return; }
104
148
  if (argv[0] === '--version') { process.stdout.write(version + '\n'); return; }
105
- const [command, ...args] = argv;
149
+ const args = argv.slice(1);
106
150
  // Local help must not select a library, read state or consume write stdin.
107
151
  // Native provider flags remain untouched.
108
152
  if (!['qmd', 'git', 'rclone'].includes(command) && args.includes('--help')) { process.stdout.write(help); return; }
@@ -177,7 +221,7 @@ export async function main(argv = process.argv.slice(2)) {
177
221
  return (await rclone(root, rest, { inherit: true })).code;
178
222
  }); return;
179
223
  }
180
- const allowed = { doctor: [], settings: [], configure: ['expected', 'key'], put: ['path', 'expected', 'key'], replace: ['path', 'key'],
224
+ const allowed = { doctor: [], settings: [], configure: ['expected', 'key'], put: ['path', 'expected', 'key', 'from-file'], replace: ['path', 'key'],
181
225
  get: ['path', 'raw', 'offset', 'length', 'expected'], 'pdf-text': ['path'], list: ['prefix', 'limit'], operation: ['key'],
182
226
  'sync-plan': ['remote'], 'sync-adopt': ['remote'], 'sync-status': [], 'sync-run': [],
183
227
  move: ['path', 'to', 'expected', 'key'], remove: ['path', 'expected', 'key'], gzip: ['path', 'to', 'expected', 'key'],
@@ -206,7 +250,8 @@ export async function main(argv = process.argv.slice(2)) {
206
250
  }
207
251
  if (command === 'put') {
208
252
  if (!opts.path) fail('INVALID', 'Supply --path');
209
- emit(await put(root, opts.path, process.stdin, { key: opts.key, expected: opts.expected })); return;
253
+ if (opts['from-file'] === undefined) { emit(await put(root, opts.path, process.stdin, { key: opts.key, expected: opts.expected })); return; }
254
+ emit(await putFromFile(root, opts.path, opts['from-file'], { key: opts.key, expected: opts.expected })); return;
210
255
  }
211
256
  if (command === 'gzip') { emit(await gzipFile(root, opts)); return; }
212
257
  if (command === 'replace') {
@@ -237,7 +282,11 @@ export async function main(argv = process.argv.slice(2)) {
237
282
  return;
238
283
  }
239
284
  await rootDir(root);
240
- if (command === 'operation') { emit(await operation(root, opts.key)); return; }
285
+ if (command === 'operation') {
286
+ const view = await operation(root, opts.key), config = await syncConfig(root);
287
+ const receipt = config?.backend === 'git' ? await remoteReceipt(root, config, view) : null;
288
+ emit(receipt ? { ...view, git: receipt } : view); return;
289
+ }
241
290
  if (command === 'list') { emit(await list(root, opts.prefix, opts.limit === undefined ? 100 : Number(opts.limit))); return; }
242
291
  if (command === 'pdf-text') {
243
292
  if (!opts.path) fail('INVALID', 'Supply --path');
@@ -268,6 +317,9 @@ export async function main(argv = process.argv.slice(2)) {
268
317
  const code = error.code || (error instanceof SyntaxError ? 'INVALID' : 'UNAVAILABLE');
269
318
  const invalid = ['INVALID', 'UNSAFE_PATH', 'TOO_LARGE', 'KEY_REUSED'].includes(code) || code.startsWith('ERR_PARSE_ARGS');
270
319
  process.exitCode = invalid ? 2 : ['CONFLICT', 'BUSY'].includes(code) ? 3 : 4;
271
- process.stderr.write(JSON.stringify({ ok: false, error: { code, message: error.message } }) + '\n');
320
+ // A write that waited out the lock reports on stdout, in the same shape as a result, and says nothing was written.
321
+ const busyWrite = code === 'BUSY' && ['put', 'replace'].includes(command);
322
+ const body = { code, message: error.message, ...(busyWrite ? { written: false, ...(error.retryable ? { retryAfterSeconds: RETRY_AFTER_SECONDS } : {}) } : {}) };
323
+ (busyWrite ? process.stdout : process.stderr).write(JSON.stringify({ ok: false, error: body }) + '\n');
272
324
  }
273
325
  }
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
@@ -137,9 +137,15 @@ async function acquire(lock, signal) {
137
137
  }
138
138
  ownerless = owner ? null : ownerless ?? Date.now();
139
139
  if (ownerless !== null && Date.now() - ownerless >= OWNERLESS_GRACE_MS)
140
- fail('BUSY', 'Writer lock exists without an owner; confirm no command is active before recovering an interrupted operation');
141
- if (Date.now() - started >= LOCK_WAIT_MS)
142
- 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
+ }
143
149
  await sleep(100 + Math.random() * 150, undefined, { signal });
144
150
  }
145
151
  }
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,
@@ -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
+ });
@@ -6,7 +6,9 @@ import { tmpdir } from 'node:os';
6
6
  import { Readable } from 'node:stream';
7
7
  import { spawnSync } from 'node:child_process';
8
8
  import { locked, put, operation, settings, defaults, validateSettings, list, digest, readRange, MAX_READ_BYTES, hash } from '../src/store.mjs';
9
- import { qmdEnvironment } from '../src/cli.mjs';
9
+ import { qmdEnvironment, putFromFile } from '../src/cli.mjs';
10
+ import { spawn } from 'node:child_process';
11
+ import { existsSync } from 'node:fs';
10
12
 
11
13
  const cli = new URL('../bin/ez-library.mjs', import.meta.url).pathname;
12
14
  async function fixture(t) {
@@ -283,3 +285,120 @@ test('local subcommand help succeeds before configuration or write intake',async
283
285
  }
284
286
  assert.deepEqual(await fs.readdir(root),[]);
285
287
  });
288
+
289
+ const run = (root, args, stdin) => spawnSync(process.execPath, [cli, ...args], { input: stdin, env: { ...process.env, EZ_LIBRARY_STATE: root } });
290
+
291
+ test('non-ASCII text survives put byte for byte, including a character split across stream chunks and pipe buffers', async t => {
292
+ const root = await fixture(t), dash = Buffer.from('–');
293
+ assert.deepEqual([...dash], [0xe2, 0x80, 0x93]);
294
+ // Split the en dash across chunks at each byte boundary, then straddle the 64 KiB pipe buffer through the CLI.
295
+ const text = Buffer.from('range 1–2 – café 😀\n');
296
+ for (const cut of [1, 2, 3, 4, text.length - 1]) {
297
+ await put(root, `split/${cut}.md`, Readable.from([text.subarray(0, cut), text.subarray(cut)]), { key: `split:${cut}`, expected: 'new' });
298
+ assert.deepEqual(await fs.readFile(path.join(root, 'files/split', `${cut}.md`)), text);
299
+ }
300
+ for (const at of [65535, 65536, 65537, 131071]) {
301
+ const body = Buffer.concat([Buffer.alloc(at, 97), dash, Buffer.alloc(70000, 98)]);
302
+ const stored = run(root, ['put', '--path', `big/${at}.md`, '--expected', 'new', '--key', `cli:${at}`], body);
303
+ assert.equal(stored.status, 0, stored.stderr);
304
+ assert.deepEqual(await fs.readFile(path.join(root, 'files/big', `${at}.md`)), body);
305
+ const read = run(root, ['get', '--path', `big/${at}.md`, '--raw']);
306
+ assert.deepEqual(read.stdout, body); assert(!body.includes(Buffer.from('�')));
307
+ }
308
+ });
309
+
310
+ 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 => {
311
+ const root = await fixture(t), lock = path.join(root, '.writer-lock');
312
+ await fs.mkdir(lock);
313
+ const blocked = run(root, ['put', '--path', 'a.md', '--expected', 'new', '--key', 'busy:1'], 'data');
314
+ assert.equal(blocked.status, 3); assert.equal(blocked.stderr.length, 0);
315
+ const body = JSON.parse(blocked.stdout);
316
+ assert.equal(body.ok, false); assert.equal(body.error.code, 'BUSY');
317
+ // A lock with no owner cannot clear by waiting: no retry hint, and the message says it needs attention.
318
+ assert.equal(body.error.written, false); assert.equal('retryAfterSeconds' in body.error, false);
319
+ assert.match(body.error.message, /needs attention/);
320
+ await assert.rejects(fs.stat(path.join(root, 'files/a.md')), code('ENOENT'));
321
+ assert.deepEqual(await fs.readdir(path.join(root, 'operations')).catch(() => []), []);
322
+ const replace = run(root, ['replace', '--path', 'a.md', '--key', 'busy:2'], JSON.stringify({ before: 'x', after: 'y' }));
323
+ assert.equal(replace.status, 3); assert.equal(JSON.parse(replace.stdout).error.written, false);
324
+ // Other commands keep their stderr contract.
325
+ const other = run(root, ['move', '--path', 'a.md', '--to', 'b.md', '--expected', 'a'.repeat(64), '--key', 'busy:3']);
326
+ assert.equal(other.stdout.length, 0); assert.equal(JSON.parse(other.stderr).error.code, 'BUSY');
327
+ await fs.rmdir(lock);
328
+ const retried = run(root, ['put', '--path', 'a.md', '--expected', 'new', '--key', 'busy:1'], 'data');
329
+ assert.equal(retried.status, 0, retried.stderr); assert.equal(JSON.parse(retried.stdout).data.state, 'stored');
330
+ });
331
+
332
+ const linux = existsSync('/proc/self/fd') ? {} : { skip: '--from-file needs /proc/self/fd (Linux); the plugin runs in a Linux container' };
333
+ test('put --from-file streams a workspace file above 1 MiB and refuses unsafe sources before writing', linux, async t => {
334
+ const root = await fixture(t), workspace = await fs.realpath(await fixture(t)), outside = await fs.realpath(await fixture(t));
335
+ const env = { ...process.env, EZ_LIBRARY_STATE: root, EZ_AGENT_WORKSPACE: workspace };
336
+ const invoke = (args, { stdin, environment = env } = {}) => spawnSync(process.execPath, [cli, 'put', '--expected', 'new', ...args], { input: stdin, env: environment, encoding: 'utf8' });
337
+ const data = Buffer.alloc(3 * 1024 * 1024 + 11); for (let i = 0; i < data.length; i++) data[i] = (i * 31) % 251;
338
+ const big = path.join(workspace, 'big.bin'); await fs.writeFile(big, data);
339
+ const ok = invoke(['--path', 'big/a.bin', '--key', 'ff:1', '--from-file', big]);
340
+ assert.equal(ok.status, 0, ok.stderr); const receipt = JSON.parse(ok.stdout).data;
341
+ assert.equal(receipt.state, 'stored'); assert.equal(receipt.bytes, data.length); assert.equal(receipt.sha256, hash(data));
342
+ assert.deepEqual(await fs.readFile(path.join(root, 'files/big/a.bin')), data);
343
+ assert.equal((await digest(path.join(root, 'files/big/a.bin'))).sha256, hash(data));
344
+ const link = path.join(workspace, 'leaves'); await fs.symlink(outside, link);
345
+ await fs.writeFile(path.join(outside, 'secret'), 'x'); await fs.symlink(path.join(outside, 'secret'), path.join(workspace, 'out-link'));
346
+ await fs.mkdir(path.join(workspace, 'dir')); await fs.writeFile(path.join(workspace, 'locked'), 'x'); await fs.chmod(path.join(workspace, 'locked'), 0);
347
+ const refusals = {
348
+ relative: [['--from-file', 'big.bin']], outside: [['--from-file', path.join(outside, 'secret')]],
349
+ directory: [['--from-file', path.join(workspace, 'dir')]], 'symlink out': [['--from-file', path.join(workspace, 'out-link')]],
350
+ 'dir symlink out': [['--from-file', path.join(link, 'secret')]], missing: [['--from-file', path.join(workspace, 'absent')]],
351
+ unset: [['--from-file', big], { environment: { ...env, EZ_AGENT_WORKSPACE: '' } }],
352
+ ...(process.getuid?.() === 0 ? {} : { unreadable: [['--from-file', path.join(workspace, 'locked')]] }),
353
+ };
354
+ let n = 0;
355
+ for (const [name, [flag, options]] of Object.entries(refusals)) {
356
+ const r = invoke(['--path', `refused/${n}.bin`, '--key', `ff:r${n++}`, ...flag], options);
357
+ assert.equal(r.status, 2, `${name}: ${r.stdout}${r.stderr}`); assert.equal(JSON.parse(r.stderr).ok, false, name);
358
+ }
359
+ assert.deepEqual(await fs.readdir(path.join(root, 'files')), ['big']);
360
+ assert.match(invoke(['--path', 'x', '--key', 'ff:u', '--from-file', big], { environment: { ...env, EZ_AGENT_WORKSPACE: '' } }).stderr, /stdin/);
361
+ const viaStdin = invoke(['--path', 'small.txt', '--key', 'ff:s'], { stdin: 'hello' });
362
+ assert.equal(viaStdin.status, 0, viaStdin.stderr); assert.equal(JSON.parse(viaStdin.stdout).data.sha256, hash('hello'));
363
+ });
364
+
365
+ test('put --from-file does not read stdin and returns with an open, silent pipe', linux, async t => {
366
+ const root = await fixture(t), workspace = await fs.realpath(await fixture(t));
367
+ await fs.writeFile(path.join(workspace, 'f.txt'), 'abc');
368
+ const child = spawn(process.execPath, [cli, 'put', '--path', 'f.txt', '--expected', 'new', '--key', 'ff:p', '--from-file', path.join(workspace, 'f.txt')],
369
+ { env: { ...process.env, EZ_LIBRARY_STATE: root, EZ_AGENT_WORKSPACE: workspace }, stdio: ['pipe', 'pipe', 'pipe'] });
370
+ const timer = setTimeout(() => child.kill('SIGKILL'), 20000); let out = '';
371
+ child.stdout.on('data', d => { out += d; });
372
+ const status = await new Promise(resolve => child.on('exit', resolve)); clearTimeout(timer);
373
+ assert.equal(status, 0); assert.equal(JSON.parse(out).data.sha256, hash('abc'));
374
+ });
375
+
376
+ test('put --from-file refuses a path whose directory is swapped around the open, and stores nothing', linux, async t => {
377
+ const root = await fixture(t), workspace = await fs.realpath(await fixture(t)), outside = await fs.realpath(await fixture(t));
378
+ process.env.EZ_AGENT_WORKSPACE = workspace; t.after(() => { delete process.env.EZ_AGENT_WORKSPACE; });
379
+ await fs.mkdir(path.join(workspace, 'd')); await fs.mkdir(path.join(outside, 'd'));
380
+ const inner = path.join(workspace, 'd', 'f'); await fs.writeFile(inner, 'inside'); await fs.writeFile(path.join(outside, 'd', 'f'), 'secret');
381
+ const away = path.join(workspace, 'd.orig'), dir = path.join(workspace, 'd');
382
+ const swap = () => fs.rename(dir, away).then(() => fs.symlink(path.join(outside, 'd'), dir));
383
+ const revert = () => fs.rm(dir).then(() => fs.rename(away, dir));
384
+ const options = n => ({ key: `race:${n}`, expected: 'new' });
385
+ const into = () => fs.rm(dir).then(() => fs.mkdir(dir)).then(() => fs.writeFile(inner, 'inside'));
386
+ await assert.rejects(putFromFile(root, 'a', inner, options(1), { beforeOpen: swap }), code('UNSAFE_PATH'));
387
+ await revert();
388
+ await assert.rejects(putFromFile(root, 'b', inner, options(2), { beforeOpen: swap, afterOpen: revert }), code('UNSAFE_PATH'));
389
+ // symlink at the open, then a real directory (and again a symlink if the path were read by name once more)
390
+ await assert.rejects(putFromFile(root, 'd', inner, options(4), { beforeOpen: swap, afterOpen: into }), code('UNSAFE_PATH'));
391
+ await fs.rm(dir, { recursive: true, force: true }); await fs.rename(away, dir).catch(() => {});
392
+ assert.equal((await fs.stat(dir)).isDirectory() && !(await fs.lstat(dir)).isSymbolicLink(), true);
393
+ assert.deepEqual(await fs.readdir(path.join(root, 'files')).catch(() => []), []);
394
+ assert.equal((await putFromFile(root, 'c', inner, options(3))).sha256, hash('inside'));
395
+ });
396
+
397
+ test('put --from-file refuses cleanly where /proc/self/fd is absent', async t => {
398
+ const root = await fixture(t), workspace = await fs.realpath(await fixture(t));
399
+ process.env.EZ_AGENT_WORKSPACE = workspace; t.after(() => { delete process.env.EZ_AGENT_WORKSPACE; });
400
+ await fs.writeFile(path.join(workspace, 'f'), 'x');
401
+ await assert.rejects(putFromFile(root, 'f', path.join(workspace, 'f'), { key: 'np:1', expected: 'new' }, { procFd: path.join(workspace, 'no-proc') }),
402
+ error => error.code === 'INVALID' && /Linux/.test(error.message));
403
+ assert.deepEqual(await fs.readdir(path.join(root, 'files')).catch(() => []), []);
404
+ });