@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.
package/.dockerignore CHANGED
@@ -10,3 +10,5 @@
10
10
  !THIRD_PARTY_NOTICES.md
11
11
  !docs/rclone-LICENSE.txt
12
12
  !patches/**
13
+
14
+ !pnpm-workspace.yaml
package/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.0-beta.18
4
+
5
+ - Reuse unchanged file digests in the resident sync worker: inventory scans skip rereading files whose device, inode, size, mtime and ctime are unchanged, and the text mirror rewrites only changed files and skips fetch, push and verification when the remote head already matches. Idle sync cycles no longer hash every original twice per minute.
6
+ - Add explicit pull-only Git sync for read-only repository keys: fetch, verify and fast-forward, followed by the existing indexing path, without staging, committing or pushing.
7
+ - Preserve and refuse local changes and non-fast-forward history. Existing Git bindings can switch with revision-guarded sync policy; two-way sync is unchanged.
8
+ - Reconcile existing checkout tracking refs with native Git's fetch/push updates, retaining the revision guard for unexpected changes.
9
+ - Includes the beta.17 scope below, which was never published to npm.
10
+
11
+ ## 0.1.0-beta.17
12
+
13
+ - Add guarded in-Library gzip and scoped literal section/text updates, preserving originals, revision guards, operation receipts and the single writer.
14
+ - Retain the beta.16 Dockerfile and shared embedding implementation so existing shared-worker deployments remain compatible. The container build-policy upgrade remains separate.
15
+ - Add a representative manifest example for tool discovery; state and deployment schemas remain unchanged.
16
+ - Requires Ez core 0.1.0-beta.50 or newer for the manifest example.
17
+ Older cores refuse the update and retain the installed version.
18
+
19
+ ## 0.1.0-beta.16
20
+
21
+ - Preserve atomic Library intake when originals use a separate filesystem mount.
22
+ - Read large originals through revision-checked, binary-safe bounded ranges with
23
+ source and chunk hashes, contiguous offsets and EOF metadata.
24
+ - Existing raw reads, guarded writes, data schema and deployment layout remain
25
+ compatible.
26
+
3
27
  ## 0.1.0-beta.15
4
28
 
5
29
  - Declare the full Library command's external-content, outbound, record-change
package/CONTRIBUTING.md CHANGED
@@ -25,7 +25,7 @@ repository. Public docs describe shipped behavior and explicit limitations.
25
25
  2. Install Node 22+ and pnpm 10.30.3. Run `pnpm install --frozen-lockfile`.
26
26
  3. Change the code, user instructions and focused tests together. Authority,
27
27
  paths, credentials, cancellation and uncertain writes need negative tests.
28
- 4. Run `pnpm verify`, `npm run release:check` and `git diff --check`.
28
+ 4. Run `pnpm verify`, `pnpm run release:check` and `git diff --check`.
29
29
  Packaging/runtime changes also need the Docker checks in docs/releasing.md.
30
30
  5. Open a PR explaining the problem, resulting behavior, verification and limits.
31
31
  Include a short sanitized reproduction. State which tests were not run.
package/Dockerfile CHANGED
@@ -1,6 +1,6 @@
1
1
  FROM rclone/rclone:1.74.2@sha256:9ce0d49b611d3781233e25334e9e23d7af01e5546da7087f90d55f034ef13637 AS sync-engine
2
2
 
3
- FROM node:22.22.0-bookworm-slim@sha256:dd9d21971ec4395903fa6143c2b9267d048ae01ca6d3ea96f16cb30df6187d94 AS test
3
+ FROM node:22.23.4-bookworm-slim@sha256:de170b39439eb0e5a3444ad7d60b015614a381e10fecae2e30ec9e735122f38d AS test
4
4
  RUN apt-get update && apt-get install -y --no-install-recommends git && rm -rf /var/lib/apt/lists/*
5
5
  COPY --from=sync-engine /usr/local/bin/rclone /usr/local/bin/rclone
6
6
  WORKDIR /app
@@ -11,7 +11,7 @@ COPY scripts/publish-settings.mjs ./scripts/publish-settings.mjs
11
11
  COPY test ./test
12
12
  RUN node --test test/*.test.mjs
13
13
 
14
- FROM node:22.22.0-bookworm-slim@sha256:dd9d21971ec4395903fa6143c2b9267d048ae01ca6d3ea96f16cb30df6187d94 AS runtime
14
+ FROM node:22.23.4-bookworm-slim@sha256:de170b39439eb0e5a3444ad7d60b015614a381e10fecae2e30ec9e735122f38d AS runtime
15
15
  RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates poppler-utils python3 make g++ cmake git openssh-client && rm -rf /var/lib/apt/lists/*
16
16
  RUN corepack enable && corepack prepare pnpm@10.30.3 --activate
17
17
  COPY --from=sync-engine /usr/local/bin/rclone /usr/local/bin/rclone
package/README.md CHANGED
@@ -4,7 +4,10 @@ A separate Dockerized plugin for an agent's files and QMD search. Preserve origi
4
4
 
5
5
  **Unreleased beta.** QMD supplies search; native rclone bisync supplies explicitly enabled folder synchronization. Existing-folder adoption, automatic indexing and guarded organization are implemented. Native Drive/Dropbox connections require separate authorization and remote QA. GitHub-only sync uses native Git and a repository-specific deploy key registered through the existing GitHub plugin. Hybrid remains an agent-owned persistence policy, not an automatic sync backend. OCR and versioned cloud backup/restore are not supplied. No relay changes are required.
6
6
 
7
- See [existing-folder setup and sync policy](docs/folder-sync.md) and [GitHub-only two-way sync](docs/github-sync.md).
7
+ See [existing-folder setup and sync policy](docs/folder-sync.md) and [GitHub two-way or pull-only sync](docs/github-sync.md).
8
+
9
+ Requires Ez core 0.1.0-beta.50 or newer for the manifest example.
10
+ Older cores refuse the update and retain the installed version.
8
11
 
9
12
  ## Multiple libraries
10
13
 
@@ -67,6 +70,44 @@ ez library qmd get qmd://library/notes/travel.md
67
70
 
68
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.
69
72
 
73
+ For files larger than the executor's output allowance, first read metadata,
74
+ then use `get --path RELATIVE --offset 0 --length 524288 --expected SHA256`.
75
+ Range reads return JSON with base64 `content`, actual `length`, `chunkSha256`,
76
+ full source `bytes` and `sha256`, `nextOffset`, and `eof`. Decode each range,
77
+ verify its digest and contiguous offset, and continue at `nextOffset` until
78
+ `eof`; verify the assembled source size and digest. Every range hashes the
79
+ same open file it reads and rejects a changed source before emitting content.
80
+ Lengths are 1–524288 bytes; an offset at EOF returns an empty final range.
81
+ Range flags require all three values and cannot combine with `--raw`.
82
+
83
+ For a shared text file, `replace --path RELATIVE --key KEY` takes a JSON object
84
+ with exactly `before` and `after` strings on stdin. Supply the complete unique
85
+ block you own, including its identity and boundaries. Library reads current
86
+ bytes under its existing writer lock, requires exactly one literal `before`
87
+ match, and atomically replaces only that match. Other blocks, line endings and
88
+ Unicode bytes remain untouched. An absent/ambiguous match is a conflict, never
89
+ a fuzzy merge. Input is capped at 256 KiB and the UTF-8 file at 8 MiB; empty,
90
+ identical or ambiguous resulting blocks are rejected.
91
+
92
+ The existing history and operation receipt preserve recovery. Same-key replay
93
+ recognizes a unique `after` block even if unrelated text changed later. A
94
+ `stored` replacement receipt proves that block is present, not that the whole
95
+ file remains at its original post-write hash; the response includes the current
96
+ whole-file hash. Re-read a changed owning block rather than replaying stale
97
+ content with a fresh key. This operation adds no caller permissions, lock
98
+ override, automatic retry, append behavior or remote-sync process.
99
+
100
+ When a file is already in Library, `gzip --path SOURCE --to DEST.gz
101
+ --expected SOURCE_SHA256 --key KEY` compresses it inside the existing writer
102
+ lock. Only paths and the expected source hash cross the transport; archive
103
+ bytes do not travel through stdin. The source is retained, the destination must
104
+ be new, and existing operation receipts provide replay and interrupted-write
105
+ reconciliation. The receipt binds the source path/size/hash and gzip encoding to
106
+ the stored archive size/hash. Compression is level 9 with no current timestamp.
107
+ Both source and output retain the 512 MiB limit. This command does not update a
108
+ domain archive index, remove evidence or synchronize it remotely; those remain
109
+ explicit owning-workflow steps after verified readback.
110
+
70
111
  Semantic embeddings are **off by default**. Enable them explicitly through the owning agent's host manager:
71
112
 
72
113
  ```sh
@@ -88,7 +129,7 @@ Only embedding/tokenizer inference is shared. Use structured `vec:` queries with
88
129
 
89
130
  Drive and GitHub persistence keep ordinary files at their original relative paths: PDFs, Markdown and zero-byte files can be browsed directly. No archive or base64 bundle substitutes for the current tree. GitHub does not represent empty directories. Provider revision history remains separate from the visible current files.
90
131
 
91
- For an adopted folder, the resident service runs native bisync and indexes changes. The default interval is 60 seconds after each completed cycle, so transfers and embedding add latency. For legacy provider-only settings, uploads or Git commits/pushes remain agent-owned after each save batch. Never run both writers against the same destination.
132
+ For an adopted folder, the resident service runs native bisync and indexes changes. The default interval is 60 seconds after each completed cycle, so transfers and embedding add latency. Where a native binding exists, it is the only writer for that destination. Never run a second manual writer against a bound destination.
92
133
 
93
134
  ## Backup after each save
94
135
 
@@ -102,6 +143,8 @@ When the owner asks to enable Drive backup and sync, the onboarded agent copies
102
143
 
103
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`.
104
145
 
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
+
105
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.
106
149
 
107
150
  ## State, lifecycle and limits
@@ -117,10 +160,13 @@ An interrupted command may leave `/state/.writer-lock`, or QMD's own embed lock
117
160
  ```sh
118
161
  pnpm install --frozen-lockfile
119
162
  pnpm verify
120
- npm run release:check
163
+ pnpm run release:check
121
164
  docker build --target test -t ez-library-tests .
122
165
  docker build --target runtime -t ez-library:local .
123
166
  EZ_LIBRARY_IMAGE=ez-library:local node docker/smoke.mjs
124
167
  ```
125
168
 
126
169
  CI uses synthetic files only. Real account transfer, clean-host/reboot acceptance and cloud restore must be verified separately before claiming those capabilities. See [CONTRIBUTING.md](CONTRIBUTING.md), [SECURITY.md](SECURITY.md) and [QMD upstream](https://github.com/tobi/qmd).
170
+
171
+ Local Library subcommands accept `--help` without reading configuration or
172
+ consuming stdin. Native `qmd`, `git` and `rclone` retain their own help flags.
@@ -36,6 +36,17 @@ try {
36
36
  const put = await parse(['library', 'put', '--path', 'notes/registry.md', '--expected', 'new', '--key', 'registry-1'], note);
37
37
  assert.equal(put.data.state, 'stored');
38
38
  assert.equal(await call(['library', 'get', '--path', 'notes/registry.md', '--raw']), note);
39
+ const large = Buffer.alloc(1024 * 1024 + 17, 0xff);
40
+ const largePut = await parse(['library', 'put', '--path', 'media/large.bin', '--expected', 'new', '--key', 'range-1'], large);
41
+ const decoded = []; let offset = 0;
42
+ while (offset < large.length) {
43
+ const range = (await parse(['library', 'get', '--path', 'media/large.bin', '--offset', String(offset), '--length', '524288', '--expected', largePut.data.sha256])).data;
44
+ assert.equal(range.offset, offset); assert.equal(range.sha256, largePut.data.sha256);
45
+ decoded.push(Buffer.from(range.content, 'base64')); offset = range.nextOffset;
46
+ assert.equal(range.eof, offset === large.length);
47
+ }
48
+ assert.deepEqual(Buffer.concat(decoded), large);
49
+ await assert.rejects(call(['library', 'get', '--path', 'media/large.bin', '--offset', '0', '--length', '1', '--expected', '0'.repeat(64)]), /CONFLICT/);
39
50
  assert.equal(await call(['library-file', '--library', 'default', '--', 'notes/registry.md']), note);
40
51
  await assert.rejects(call(['library-file', 'put', '--path', 'forbidden.md']), /Supply file/);
41
52
  await assert.rejects(call(['library-file', '--library', 'default', '--', '../settings.json']), /relative path/);
package/docker/smoke.mjs CHANGED
@@ -5,16 +5,21 @@ import { randomUUID, createHash } from 'node:crypto';
5
5
 
6
6
  const image = process.env.EZ_LIBRARY_IMAGE || 'ez-library:local';
7
7
  const volume = 'ez-library-qa-' + randomUUID();
8
+ const filesVolume = volume + '-files';
8
9
  const docker = (args, input) => execFileSync('docker', args, { input, encoding: 'utf8', maxBuffer: 8 * 1024 * 1024, timeout: 180000 });
9
10
  const ipc = process.env.EZ_LIBRARY_EMBED_IPC;
10
11
  const lastCpu = Math.max(0, Math.min(4, Number(docker(['info', '--format', '{{.NCPU}}']).trim())) - 1);
11
12
  const call = (args, input) => docker(['run', '--rm', '--network', 'none', '--cap-drop', 'ALL', '--security-opt', 'no-new-privileges',
12
- '--cpuset-cpus', `0-${lastCpu}`, '--memory', '4g', '-i', '-v', volume + ':/state',
13
+ '--cpuset-cpus', `0-${lastCpu}`, '--memory', '4g', '-i', '-v', volume + ':/state', '-v', filesVolume + ':/state/files',
13
14
  ...(ipc ? ['-v', ipc + ':/inference:ro', '-e', 'EZ_LIBRARY_EMBED_SOCKET=/inference/worker.sock'] : []),
14
15
  image, 'node', '/app/bin/ez-library.mjs', ...args], input);
15
16
  const parsed = (args, input) => JSON.parse(call(args, input)).data;
16
17
  try {
17
18
  docker(['volume', 'create', volume]);
19
+ docker(['volume', 'create', filesVolume]);
20
+ // Real separate mount boundaries reproduce the former EXDEV rename failure.
21
+ docker(['run', '--rm', '--network', 'none', '--user', '0:0', '-v', volume + ':/state', '-v', filesVolume + ':/state/files',
22
+ image, 'node', '-e', `const fs=require('node:fs');fs.mkdirSync('/state/tmp',{recursive:true});for(const p of ['/state/tmp','/state/files']){fs.chownSync(p,1000,1000);fs.chmodSync(p,0o700);}fs.writeFileSync('/state/tmp/probe','synthetic');try{fs.renameSync('/state/tmp/probe','/state/files/.probe');throw Error('Fixture must reject cross-mount rename');}catch(e){if(e.code!=='EXDEV')throw e;}finally{fs.rmSync('/state/tmp/probe',{force:true});fs.rmSync('/state/files/.probe',{force:true});}`]);
18
23
  assert.match(call(['--help']), /Local library/);
19
24
  assert.equal(parsed(['doctor']).configured, false);
20
25
  parsed(['configure', '--expected', 'new', '--key', 'settings'], JSON.stringify({ schemaVersion: 1, storage: { mode: 'local' }, backup: { mode: 'off' } }));
@@ -69,5 +74,5 @@ try {
69
74
  }
70
75
  assert.equal(call(['get', '--library', 'default', '--path', 'notes/travel.md', '--raw']), note);
71
76
  assert.match(call(['get', '--library', 'work', '--path', 'notes/travel.md', '--raw']), /approval policy/);
72
- console.log(JSON.stringify({ ok: true, checks: ['help-without-state', 'configuration', 'intake-readback', 'idempotency', 'restart-persistence', 'attachment-bytes', 'pdf-extraction-and-retrieval', 'native-qmd-keyword', 'named-library-isolation-and-search', ...(ipc ? ['shared-qmd-semantic'] : [])] }));
73
- } finally { docker(['volume', 'rm', volume]); }
77
+ console.log(JSON.stringify({ ok: true, checks: ['cross-mount-atomic-put', 'help-without-state', 'configuration', 'intake-readback', 'idempotency', 'restart-persistence', 'attachment-bytes', 'pdf-extraction-and-retrieval', 'native-qmd-keyword', 'named-library-isolation-and-search', ...(ipc ? ['shared-qmd-semantic'] : [])] }));
78
+ } finally { docker(['volume', 'rm', volume, filesVolume]); }
@@ -1,12 +1,20 @@
1
1
  # GitHub-only working Library
2
2
 
3
- Native Git handles fetch, merge, commit and push. The same resident Library
3
+ Native Git handles fetch, merge, commit and push in the default two-way mode. Pull-only mode fetches and fast-forwards without committing or pushing. The same resident Library
4
4
  supervisor refreshes PDF extraction, QMD search and embeddings after each
5
5
  successful cycle. The default interval is 60 seconds after the previous cycle
6
6
  finishes; use `sync-policy` to change it or pause. Local commits survive network
7
7
  failures. A push is verified by reading the remote branch commit, and concurrent
8
8
  remote advancement is reported as uncertain for reconciliation next cycle.
9
9
 
10
+ ## Pull-only repositories
11
+
12
+ Use a read-only GitHub deploy key and `git-adopt --repository OWNER/REPO --branch main --mode pull-only` when another workspace owns the source. The existing supervisor fetches and fast-forwards, then refreshes extraction and QMD indexing. It never stages, commits or pushes in this mode, even with a write-capable key.
13
+
14
+ For an existing Git binding, read `sync-status` and use `sync-policy --expected REVISION --mode pull-only`. `paused` stops synchronization; `two-way` keeps the original bidirectional behavior. Pull-only is available only for Git bindings, including mounted existing checkouts.
15
+
16
+ Local edits, staged work, untracked files, local commits or rewritten/divergent remote history stop the cycle with a conflict and preserve the working tree. Ignored local files remain local; an incoming tracked file cannot overwrite one. Extra local originals prevent pull-only adoption. Reconcile through native Git before resuming; no hard reset or automatic conflict winner is supplied. A successful receipt verifies the remote branch commit. Network and authentication failures remain errors.
17
+
10
18
  On a constrained host, set the Library service environment `EZ_LIBRARY_EMBED=0`
11
19
  to keep automatic Git transfer, extraction and full-text indexing without running
12
20
  embeddings under the writer lock. Status retains `embedded: false`; semantic
@@ -24,7 +32,7 @@ policy, even when original files have not changed.
24
32
  `/state/sync/keys` and returns only the public key. GitHub SSH host keys come
25
33
  from its public HTTPS metadata endpoint and strict SSH checking stays enabled.
26
34
  3. Use the existing GitHub plugin's native `gh api` to list repository deploy
27
- keys, reconcile any matching public key, and register it with write access
35
+ keys, reconcile any matching public key, and register it with write access for two-way sync or read-only access for pull-only sync
28
36
  if missing. The endpoint is `repos/OWNER/REPO/keys`; submit JSON on stdin using
29
37
  `ez github gh api ... --method POST --input -`:
30
38
 
@@ -32,7 +40,7 @@ policy, even when original files have not changed.
32
40
  {"title":"Ez Library","key":"PUBLIC_KEY_FROM_GIT_KEY","read_only":false}
33
41
  ```
34
42
 
35
- Read back the matching key and its write setting after registration. If a
43
+ For pull-only sync set `read_only` to `true`. Read back the matching key and its permission after registration. If a
36
44
  registration response is uncertain, inspect the key list before retrying.
37
45
  Only the public key crosses plugins. OAuth tokens remain in GitHub's profile;
38
46
  the private SSH key remains in Library. No GCP project or new user login is
@@ -43,7 +51,7 @@ policy, even when original files have not changed.
43
51
  5. `ez library git-adopt --repository OWNER/REPO --branch main` imports the
44
52
  branch and enables sync. Existing local files with matching paths must have
45
53
  identical bytes; conflicts stop adoption. Extra local files become pending
46
- additions, so select GitHub-only only when their upload is intended.
54
+ additions in two-way mode, so select that mode only when their upload is intended. Pull-only adoption refuses extra local originals.
47
55
  6. Run `sync-run`, check `sync-status`, query actual content, and verify the
48
56
  remote commit/files through the GitHub plugin before saying sync is live.
49
57
 
@@ -25,7 +25,7 @@ On CPU-only hosts with large vaults or very large extracted documents, choose `"
25
25
 
26
26
  The agent interprets Hybrid as selected extensions below the ceiling going to the chosen private GitHub repository; images, audio, video and remaining attachments go to the selected Drive folder. First verify access, account and destination identity using that provider's tools. Persisting to GitHub includes push and remote commit readback, not only a local commit. A Drive connection through Composio provides individual upload/update/download/change tools, not automatic folder synchronization. A Gmail connection is not proof of Drive access. Never copy provider credentials into a different transfer utility.
27
27
 
28
- Maintain a portable manifest alongside authored notes when persisting: logical relative path, content hash, size, destination and remote object ID/revision (or Git commit and path). Export current bytes using `get --raw`, verify the provider result against those bytes, and record provenance as evidence. Library does not attest externally supplied receipts. Git and Drive cannot be committed atomically together: report partial persistence honestly, read back uncertain operations, and use provider idempotency/reconciliation to avoid duplicate uploads. No blind retries or default remote deletions. QMD indexes and model downloads do not belong in publication.
28
+ Report partial persistence honestly: Git and Drive cannot be committed atomically together. Read back uncertain operations through the native binding where one exists, else through the provider tools that performed the transfer, and use provider idempotency/reconciliation to avoid duplicate uploads. No blind retries or default remote deletions. QMD indexes and model downloads do not belong in publication.
29
29
 
30
30
  Hybrid distributes files across providers; it does not duplicate each file. Independently configure backup intent as either `{"mode":"off"}` or `{"mode":"external","connection":"backup-tool-profile","destination":"selected-backup-destination"}`. An existing tool must actually create versioned backups and demonstrate restore; these settings install or schedule nothing. Recover both storage destinations into a clean directory, reconstruct relative paths/attachment links, and compare content hashes before claiming full recovery.
31
31
 
@@ -33,7 +33,7 @@ Hybrid distributes files across providers; it does not duplicate each file. Inde
33
33
 
34
34
  Remote persistence defaults to ordinary files at matching relative paths, not an archive, base64 container or encrypted bundle. Preserve zero-byte files. Drive folders are real folders; GitHub stores ordinary files and history, but Git does not track empty directories. Preserve any previous archive separately during migration rather than treating it as the live tree.
35
35
 
36
- Use recorded Drive IDs for in-place updates and commit/push GitHub save batches. Cloud edits that diverge from the last verified content are conflicts, not permission to overwrite. A verified two-way import/delete policy is separate from the default Library-to-provider mirror. Native Composio file staging can supply binary references to its Drive upload/update tools without exposing credentials.
36
+ Where a native binding exists it owns in-place updates and GitHub save batches; verify through `sync-status` and remote readback rather than settings alone. Cloud edits that diverge from the last verified content are conflicts, not permission to overwrite. A verified two-way import/delete policy is separate from the default Library-to-provider mirror. Native Composio file staging can supply binary references to its Drive upload/update tools without exposing credentials.
37
37
 
38
38
  Cadence is immediately after each completed agent save batch. This agent workflow is not an autonomous watcher, and no bounded latency or offline recovery guarantee is claimed. For unattended continuous/bidirectional synchronization, use an established engine such as rclone or an appropriate provider client with a separately verified binding and conflict policy. Composio and Git operations alone do not provide that service. Do not emulate it with a scheduled LLM loop.
39
39
 
@@ -41,7 +41,7 @@ Cadence is immediately after each completed agent save batch. This agent workflo
41
41
 
42
42
  An owner request to enable provider backup and sync authorizes an initial copy now and backup of subsequent agent saves within their intake/update tasks. Keep primary storage unchanged. The agent creates/reuses the requested private destination, verifies it, configures external backup and records the after-save policy in workspace tool instructions. No invented daily schedule or delay; a requested reconciliation schedule is additional protection.
43
43
 
44
- For each changed original or derived note, preserve remote versions and relative paths, verify provider readback, and checkpoint hashes and remote IDs in the portable manifest. Skip verified unchanged content. Failed transfers stay pending with local originals preserved; report the gap rather than “synced.” This is agent-owned execution, not a background filesystem watcher. Writes outside this intake require explicit reconciliation. Connection alone activates neither behavior.
44
+ For each changed original or derived note, preserve remote versions and relative paths and verify provider readback (through the native binding where one exists). Skip verified unchanged content. Failed transfers stay pending with local originals preserved; report the gap rather than “synced.” This is agent-owned execution, not a background filesystem watcher. Writes outside this intake require explicit reconciliation. Connection alone activates neither behavior.
45
45
 
46
46
  References:
47
47
  - https://docs.composio.dev/toolkits/googledrive
package/docs/releasing.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Use CONTRIBUTING.md for every change. The source repository is public and registered in the Ez catalog; the first public npm candidate is 0.1.0-beta.10. Publication requires the reviewed release preparation PR and maintainer authorization. Keep manifest and package versions equal. Versions are immutable once published.
4
4
 
5
- 1. Run `pnpm install --frozen-lockfile`, `pnpm verify`, `npm run release:check`, and `git diff --check`. The release check also verifies that `package.json` is not private, requests public npm access on the `latest` tag, matches the repository identity, and agrees with the pinned trusted-publisher caller. The generated caller is checked against its complete reviewed contract (ignoring blank lines, standalone comments, trailing whitespace and line endings); regenerate and review contract updates together, including changes to permissions, inputs or required checks. It does not prove npm package existence, npm trust enrollment, or registry delivery; read those back separately. Review dependency audit results and licenses without automatic fixes. After lockfile changes, copy `pnpm-lock.yaml` to `docker/pnpm-lock.yaml`.
5
+ 1. Run `pnpm install --frozen-lockfile`, `pnpm verify`, `pnpm run release:check`, and `git diff --check`. The release check also verifies that `package.json` is not private, requests public npm access on the `latest` tag, matches the repository identity, and agrees with the pinned trusted-publisher caller. The generated caller is checked against its complete reviewed contract (ignoring blank lines, standalone comments, trailing whitespace and line endings); regenerate and review contract updates together, including changes to permissions, inputs or required checks. It does not prove npm package existence, npm trust enrollment, or registry delivery; read those back separately. Review dependency audit results and licenses without automatic fixes. After lockfile changes, copy `pnpm-lock.yaml` to `docker/pnpm-lock.yaml`.
6
6
  2. Run `npm pack --ignore-scripts --pack-destination /absolute/temporary-directory`, inspect its file list, hash it, and extract into an empty directory. Rebuild Docker `test` and `runtime` targets from that extracted package. Restore `docker/pnpm-lock.yaml` to the extracted root for a frozen pnpm installation. Check CLI help without state.
7
7
  3. Run `EZ_LIBRARY_IMAGE=ez-library:local node docker/smoke.mjs`. For installer/descriptor changes also run `EZ_MANAGER_MODULE=/absolute/released-ez/src/plugins/manager.mjs node docker/manager-smoke.mjs`. Also run `EZ_MANAGER_MODULE=/absolute/released-ez/src/plugins/manager.mjs node docker/shared-smoke.mjs` for the shared worker and real semantic retrieval. The latter is an explicit integration input, not a runtime dependency on a sibling repository. Use separate state and synthetic data. Verify install is inert, registered dispatch, restart persistence and data-preserving uninstall.
8
8
  For folder-sync changes also run `EZ_LIBRARY_IMAGE=ez-library:local node docker/sync-smoke.mjs`; it uses separate volumes and synthetic files with networking disabled. Native cloud authorization and provider readback remain separate required evidence for a live cloud binding.
package/ez-plugin.json CHANGED
@@ -1,8 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "id": "library",
4
- "version": "0.1.0-beta.15",
4
+ "version": "0.1.0-beta.18",
5
5
  "description": "Dockerized agent library files, QMD retrieval and explicit persistence settings",
6
+ "example": "library search 'quarterly budget' --all --limit 5",
6
7
  "commands": {
7
8
  "library": {
8
9
  "executable": "bin/ez-library.mjs",
package/package.json CHANGED
@@ -1,7 +1,10 @@
1
1
  {
2
2
  "name": "@jc_stack/ez-library",
3
- "version": "0.1.0-beta.15",
4
- "publishConfig": { "access": "public", "tag": "latest" },
3
+ "version": "0.1.0-beta.18",
4
+ "publishConfig": {
5
+ "access": "public",
6
+ "tag": "latest"
7
+ },
5
8
  "description": "Dockerized agent library files, QMD retrieval and explicit persistence settings",
6
9
  "type": "module",
7
10
  "license": "MIT",
@@ -32,7 +35,8 @@
32
35
  "LICENSE",
33
36
  "THIRD_PARTY_NOTICES.md",
34
37
  "CHANGELOG.md",
35
- "patches"
38
+ "patches",
39
+ "pnpm-workspace.yaml"
36
40
  ],
37
41
  "scripts": {
38
42
  "test": "node --test test/*.test.mjs",
@@ -0,0 +1,7 @@
1
+ # Hold third-party updates for seven days; reviewed first-party releases are exempt.
2
+ minimumReleaseAge: 10080
3
+ minimumReleaseAgeExclude:
4
+ - "@jc_stack/*"
5
+ - "@aifit/*"
6
+ trustPolicy: no-downgrade
7
+ blockExoticSubdeps: true
@@ -53,6 +53,41 @@ Refresh the appropriate QMD collection after saving derived text (`qmd update`);
53
53
 
54
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.
55
55
 
56
+ If exact raw output exceeds the executor allowance, read metadata, then call
57
+ `get --path ... --offset 0 --length 524288 --expected SHA256`. Each response
58
+ contains base64 `content`, actual `length`, `chunkSha256`, source `bytes` and
59
+ `sha256`, `nextOffset`, and `eof`. Verify each decoded chunk and contiguous
60
+ offset; continue at `nextOffset` to EOF, then verify the assembled size/hash.
61
+ All three range flags are required; do not combine them with `--raw`.
62
+ A changed source returns a conflict before emitting content. Re-read metadata
63
+ and restart assembly rather than combining different revisions.
64
+
65
+ When updating your existing block in a shared text record, prefer installed
66
+ `replace --path RELATIVE --key KEY` with JSON `{ "before": "exact old block",
67
+ "after": "complete new block" }` on stdin. Include the block identity and
68
+ boundaries so both are unique. It preserves current unrelated bytes under the
69
+ Library writer lock and fails on a missing or ambiguous old block. This is
70
+ literal replacement, not Markdown interpretation or an ownership grant. Use
71
+ `put` for creation; do not use a tiny repeated phrase as a block identity.
72
+ Input is limited to 256 KiB, valid UTF-8 files to 8 MiB, and both strings must
73
+ be nonempty and different. BUSY requires waiting for the existing writer;
74
+ CONFLICT requires re-reading your own block, not forcing a whole-file rewrite.
75
+ `operation --key KEY` reconciles scoped replacement after interruption: `stored`
76
+ means the unique replacement remains present, while its reported whole-file
77
+ hash may include newer unrelated edits. Retain normal canonical/remote proof.
78
+
79
+ For lossless compression of an existing canonical file, inspect installed
80
+ `gzip --help`, then use `gzip --path SOURCE --to DEST.gz --expected SOURCE_SHA256
81
+ --key KEY`. This avoids transferring a large archive through broker stdin.
82
+ It holds the existing Library writer lock, verifies the complete source hash,
83
+ keeps the original and creates only a new destination. Read back the returned
84
+ archive metadata and `operation --key KEY`; a replay requires the same source,
85
+ destination and key. A changed source or occupied destination fails closed.
86
+ The receipt includes the original source size/hash and compression settings.
87
+ Domain indexes and guarded removal remain with the owning procedure; never
88
+ remove the original before its required archive/index/remote proof. Compression
89
+ alone does not prove indexing, remote sync or completion of the domain work.
90
+
56
91
  Configure the local mode first unless the user already chose a provider. `settings` returns its revision; `configure` reads validated JSON on stdin and requires `--expected new` or that revision and a stable `--key`. The schema and provider choices are in [persistence](../../docs/persistence.md). Handle available technical setup autonomously within the user's authorized task; ask only for missing destination decisions or unavoidable provider consent.
57
92
 
58
93
  Native QMD commands are under `ez library qmd`. Add `/state/files` as an explicitly named collection with a Markdown/TXT mask. Search returns indexed snapshots; verify selected sources with Library readback before current factual claims or edits. Collection names are not permissions: every caller of this plugin can read its whole private volume. Do not combine another agent's private files with this index by implication.
@@ -100,35 +135,21 @@ Use `move` and `remove` with current hashes and operation keys to organize files
100
135
 
101
136
  This release handles existing Drive/Dropbox folders with native profiles, or a local folder already accessible to the plugin runtime. Split two-way Hybrid routing, Google-native document editing and OCR are not implemented; do not advertise them as enabled.
102
137
 
103
- ## GitHub-only two-way sync
138
+ ## GitHub sync
104
139
 
105
140
  Read [GitHub setup](../../docs/github-sync.md). Reuse the connected GitHub plugin for repository identity/access and native deploy-key registration. Library generates the key; only its public part goes to GitHub. Do not copy OAuth tokens or another plugin's profile, ask for an unnecessary new login, or claim that GitHub settings alone activate syncing.
106
141
 
107
142
  `git-adopt --repository OWNER/REPO --branch BRANCH` imports an existing committed branch and activates native Git sync and QMD refresh. Verify repository privacy, exact branch, original hashes and a real remote commit before claiming success. Current Drive/Hybrid routing blocks GitHub-only adoption; do not change it without the owner's intent to switch storage modes. Once Git is bound, stop manual commit/push mirroring to the same destination.
108
143
 
144
+ For a source owned elsewhere, use a read-only deploy key and `git-adopt --mode pull-only`. Existing Git bindings switch with `sync-policy --expected REVISION --mode pull-only`. The resident worker fetches and fast-forwards without staging, committing or pushing. Local changes or non-fast-forward history remain preserved conflicts; do not reset them to force a green status. `two-way` retains bidirectional sync. Folder bindings do not support pull-only mode.
145
+
109
146
  Native merge conflicts stop syncing and indexing. Use `git status`, `git show :2:PATH` and `git show :3:PATH` to inspect retained versions. Apply an owner-approved resolution through guarded `put`, explicitly stage resolved paths with `git add -- PATH`, then run `sync-run`. Never stage unresolved conflict markers automatically, force-push, or reset away pending local commits. A failed push stays pending for the next cycle; it is not a verified remote save.
110
147
 
111
148
  Use the provider's deploy-key list to find the matching public key when revocation is requested. Uninstall preserves Library state; it does not revoke the repository key. GitHub repository administration is needed for this setup. Large media at or above 100 MiB, Git LFS content, symlinks and submodules are not supported by this backend.
112
149
 
113
- ## Remote persistence (legacy, no folder binding)
114
-
115
- The owner-facing default is a live, browsable mirror, even when called “backup.” Use ordinary files and folders in Drive and ordinary committed files at matching paths in GitHub. PDFs remain PDFs; searchable companions remain separate notes. Provider revision history is distinct from the current visible tree. Git tracks zero-byte files but not empty directories; do not promise exact empty-folder parity or add placeholder files without making that limitation clear.
116
-
117
- With Drive use the existing provider tools for native binary upload and update the recorded file ID on change. With GitHub write the working tree and commit/push each completed save batch; a local commit alone is not mirrored. For the native Composio connection, discover file staging and binary update actions from its installed skill/schemas. Keep transport credentials in that provider. Preserve remote edits when they differ from the last verified hash; resolve the conflict before overwriting. Do not propagate remote deletions or claim two-way synchronization without an explicit policy and a verified import/conflict path.
118
-
119
- Run remote persistence immediately after each agent save batch, not once per day. This is near-immediate agent-owned execution, not a continuously running filesystem sync service or a guaranteed maximum delay. A failed upload means the cloud copy is stale; retain a durable pending record and report it. If the owner requires unattended continuous or bidirectional sync, prefer a proven engine such as rclone with its own authorized backend, or a provider desktop client on a supported host. Verify the actual binding and conflict behavior before claiming it runs. Composio tools and Git alone do not watch local files; do not invent a daemon in the relay or silently add scheduled LLM polling.
120
-
121
- “Enable backup in Drive, create a folder, and sync” means back up the existing Library now and keep subsequent agent saves backed up as part of each intake/update task. Retain local primary storage unless the owner asks to move it. Create the requested private folder, or reconcile and reuse one already created for this request; save its verified account and destination in settings. Do not substitute a daily cadence or invent a time. Schedule reconciliation only when the owner requests it; it supplements, not replaces, saving changes to the backup destination.
122
-
123
- With external backup enabled, every agent-authored Library save includes copying the new/changed original and derived text through the configured provider. Reuse unchanged content by verified hash, preserve prior versions and relative paths, and checkpoint remote IDs/revisions and hashes in a portable manifest. Read back the upload before saying “mirrored.” If a transfer fails, preserve the local save, retain a durable pending entry for reconciliation, and tell the owner which copy remains pending. The default remote copy is a browsable tree of ordinary files with the same relative paths and bytes, including zero-byte files. Do not wrap files in ZIP, base64 JSON, encryption, or a single archive to work around missing upload support. Stage binary bytes through the provider's native upload mechanism; if it is missing, report that gap and keep the file pending. Do not recursively back up temporary exports or the backup ledger itself.
124
-
125
- During setup, record the destination and after-save policy in the owning workspace's tool instructions so future sessions apply it. Explicit backup-off, destination changes, exclusions, and cadence choices override defaults. Agent guidance is not a filesystem watcher: files written outside Library intake are not automatically detected. Composio executes individual operations; a connected account, saved setting or queued task is not proof of ongoing sync.
126
-
127
- Read settings, then use the selected existing provider tools. Reuse an authorized Drive connection through Composio when available; discover its actual operations in the current runtime. For a missing connection, the provider tool owns OAuth: deliver its authorization link/QR, resume after consent and verify the actual account and folder. GitHub similarly requires verification of the chosen account, private repository and remote commit. Do not copy authentication state between tools or infer Drive authorization from Gmail.
128
-
129
- Apply the user's explicit format/size policy. Keep credential records and agent profiles out of ordinary publication. Store source links and remote IDs/revisions in a portable manifest that can reconstruct attachment paths. The provider tools own transport, idempotency and receipts. Library settings alone do not prove sync or backup. If a transfer is uncertain, inspect the provider and retry only a known missing action; report partial persistence rather than claiming all files are saved.
150
+ ## Remote persistence (native bindings only)
130
151
 
131
- Backup is independent from split storage. Only call it verified after a versioned restore reproduces the original hashes and links. Automatic sync is supplied only for an explicitly adopted native folder binding. OCR and versioned remote backup are not supplied by this package. Reuse available tools; do not invent a relay pipeline to supply them.
152
+ There is one supported path per bound destination: an adopted folder binding ([folder sync](../../docs/folder-sync.md)) for Drive/Dropbox via native rclone bisync, or a Git binding ([GitHub setup](../../docs/github-sync.md)) for GitHub via native Git. Where a binding exists it is the only writer — do not hand-upload to that same destination, keep a separate mirror manifest, or claim sync from settings alone. Hybrid split routing has no automatic binding: it remains agent-owned execution through provider tools per [persistence policy](../../docs/persistence.md). A failed transfer stays pending for the next cycle; it is not a verified remote save. OCR and versioned remote backup are not supplied by this package.
132
153
 
133
154
  For an existing Git checkout mounted at `files`, use `git-adopt
134
155
  --existing-checkout` only with an explicit writable mount and matching branch
package/src/cli.mjs CHANGED
@@ -6,7 +6,7 @@ import { spawn } from 'node:child_process';
6
6
  import { Readable } from 'node:stream';
7
7
  import { pipeline } from 'node:stream/promises';
8
8
  import { constants } from 'node:fs';
9
- import { fail, rootDir, locked, settings, validateSettings, put, operation, organize, list, safePath, digest, jsonBytes, defaults } from './store.mjs';
9
+ import { fail, rootDir, locked, settings, validateSettings, put, operation, organize, list, safePath, digest, readRange, jsonBytes, defaults, replaceText, MAX_REPLACE_BYTES } from './store.mjs';
10
10
  import { syncPlan, syncAdopt, syncPolicy, syncRun, syncStatus } from './sync.mjs';
11
11
  import { rclone, environment } from './native.mjs';
12
12
  import { indexStatus } from './indexer.mjs';
@@ -14,6 +14,7 @@ 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
16
  import { gitKey, gitAdopt, git } from './git-sync.mjs';
17
+ import { gzipFile } from './compress.mjs';
17
18
 
18
19
  const version = JSON.parse(await fs.readFile(new URL('../package.json', import.meta.url))).version;
19
20
  const emit = data => process.stdout.write(JSON.stringify({ ok: true, data }) + '\n');
@@ -29,7 +30,13 @@ Local library files, QMD retrieval, and persistence settings.
29
30
  settings Show settings and revision hash
30
31
  configure --expected HASH|new --key KEY < settings.json
31
32
  put --path RELATIVE --expected HASH|new --key KEY < file
33
+ replace --path RELATIVE --key KEY < replacement.json
34
+ Exact unique before/after text; preserve other bytes
35
+ gzip --path SOURCE --to DEST.gz --expected SOURCE_HASH --key KEY
36
+ Compress inside Library; retain original
32
37
  get --path RELATIVE [--raw] Metadata/hash, or exact binary stdout
38
+ get --path RELATIVE --offset BYTE --length BYTES --expected SHA256
39
+ Bounded base64 JSON, at most 524288 bytes
33
40
  file --library NAME -- RELATIVE Original file bytes for channel delivery (20 MiB)
34
41
  pdf-text --path RELATIVE Poppler text to stdout, page breaks retained
35
42
  list [--prefix TEXT] [--limit 100]
@@ -42,12 +49,12 @@ Local library files, QMD retrieval, and persistence settings.
42
49
  sync-adopt --remote REMOTE:PATH Import matching originals; enable two-way sync
43
50
  sync-status Binding, last sync, extraction and embedding status
44
51
  sync-run Reconcile now and refresh the index
45
- sync-policy --expected HASH --mode paused|two-way [--interval 60]
52
+ sync-policy --expected HASH --mode paused|two-way|pull-only [--interval 60]
46
53
  git-mirror-adopt --repository OWNER/REPO [--branch main] [--extensions .md,.txt] [--exclude-directories private,archive] [--expected-remote SHA]
47
54
  git-mirror-status Text-only GitHub history destination and revision
48
55
  git-mirror-policy --expected HASH --mode paused|one-way
49
56
  git-key --repository OWNER/REPO Create a repository key; return public key only
50
- git-adopt --repository OWNER/REPO [--branch main] Import and enable native Git sync [--existing-checkout]
57
+ git-adopt --repository OWNER/REPO [--branch main] [--mode two-way|pull-only] Import and enable Git sync [--existing-checkout]
51
58
  git ... Native Git in the bound Library working tree
52
59
 
53
60
  Local commands emit JSON (--json is also accepted); get --raw and qmd preserve
@@ -96,6 +103,9 @@ export async function main(argv = process.argv.slice(2)) {
96
103
  if (!argv.length || argv[0] === '--help' || argv[0] === 'help') { process.stdout.write(help); return; }
97
104
  if (argv[0] === '--version') { process.stdout.write(version + '\n'); return; }
98
105
  const [command, ...args] = argv;
106
+ // Local help must not select a library, read state or consume write stdin.
107
+ // Native provider flags remain untouched.
108
+ if (!['qmd', 'git', 'rclone'].includes(command) && args.includes('--help')) { process.stdout.write(help); return; }
99
109
  const base = process.env.EZ_LIBRARY_STATE || '/state';
100
110
  if (command === 'sources') {
101
111
  parseArgs({ args, options: { json: { type: 'boolean' } }, strict: true });
@@ -167,12 +177,12 @@ export async function main(argv = process.argv.slice(2)) {
167
177
  return (await rclone(root, rest, { inherit: true })).code;
168
178
  }); return;
169
179
  }
170
- const allowed = { doctor: [], settings: [], configure: ['expected', 'key'], put: ['path', 'expected', 'key'],
171
- get: ['path', 'raw'], 'pdf-text': ['path'], list: ['prefix', 'limit'], operation: ['key'],
180
+ const allowed = { doctor: [], settings: [], configure: ['expected', 'key'], put: ['path', 'expected', 'key'], replace: ['path', 'key'],
181
+ get: ['path', 'raw', 'offset', 'length', 'expected'], 'pdf-text': ['path'], list: ['prefix', 'limit'], operation: ['key'],
172
182
  'sync-plan': ['remote'], 'sync-adopt': ['remote'], 'sync-status': [], 'sync-run': [],
173
- move: ['path', 'to', 'expected', 'key'], remove: ['path', 'expected', 'key'],
183
+ move: ['path', 'to', 'expected', 'key'], remove: ['path', 'expected', 'key'], gzip: ['path', 'to', 'expected', 'key'],
174
184
  'git-mirror-adopt': ['repository', 'branch', 'extensions', 'exclude-directories', 'expected-remote'], 'git-mirror-status': [], 'git-mirror-policy': ['expected', 'mode'],
175
- 'git-key': ['repository'], 'git-adopt': ['repository', 'branch', 'existing-checkout'],
185
+ 'git-key': ['repository'], 'git-adopt': ['repository', 'branch', 'existing-checkout', 'mode'],
176
186
  'sync-policy': ['expected', 'mode', 'interval'] }[command];
177
187
  if (!allowed) fail('INVALID', 'Unknown command; use --help');
178
188
  const { values: opts } = parseArgs({ args: rest, options: Object.fromEntries([...allowed, 'json'].map(k => [k, { type: ['json', 'raw', 'existing-checkout'].includes(k) ? 'boolean' : 'string' }])), strict: true });
@@ -181,7 +191,7 @@ export async function main(argv = process.argv.slice(2)) {
181
191
  if (command === 'git-mirror-status') { emit(await mirrorStatus(root)); return; }
182
192
  if (command === 'git-mirror-policy') { emit(await mirrorPolicy(root, opts.expected, opts.mode)); return; }
183
193
  if (command === 'git-key') { emit(await gitKey(root, opts.repository)); return; }
184
- if (command === 'git-adopt') { emit(await gitAdopt(root, opts.repository, opts.branch, base, opts['existing-checkout'])); return; }
194
+ if (command === 'git-adopt') { emit(await gitAdopt(root, opts.repository, opts.branch, base, opts['existing-checkout'], opts.mode)); return; }
185
195
  if (command === 'sync-adopt') { emit(await syncAdopt(root, opts.remote, base)); return; }
186
196
  if (command === 'sync-status') { emit(await syncStatus(root)); return; }
187
197
  if (command === 'sync-run') { emit(await syncRun(root, base)); return; }
@@ -198,6 +208,18 @@ export async function main(argv = process.argv.slice(2)) {
198
208
  if (!opts.path) fail('INVALID', 'Supply --path');
199
209
  emit(await put(root, opts.path, process.stdin, { key: opts.key, expected: opts.expected })); return;
200
210
  }
211
+ if (command === 'gzip') { emit(await gzipFile(root, opts)); return; }
212
+ if (command === 'replace') {
213
+ const chunks = []; let bytes = 0;
214
+ for await (const chunk of process.stdin) {
215
+ bytes += chunk.length;
216
+ if (bytes > MAX_REPLACE_BYTES) fail('TOO_LARGE', 'Replacement input exceeds 256 KiB');
217
+ chunks.push(chunk);
218
+ }
219
+ const data = Buffer.concat(chunks), text = data.toString('utf8');
220
+ if (!Buffer.from(text).equals(data)) fail('INVALID', 'Replacement input must be UTF-8');
221
+ emit(await replaceText(root, opts.path, JSON.parse(text), { key: opts.key })); return;
222
+ }
201
223
  if (command === 'doctor') {
202
224
  let configured = false; let value = { settings: defaults(), sha256: null };
203
225
  try { await rootDir(root); value = await settings(root); configured = value.sha256 !== null; }
@@ -231,7 +253,10 @@ export async function main(argv = process.argv.slice(2)) {
231
253
  if (command === 'get') {
232
254
  if (!opts.path) fail('INVALID', 'Supply --path');
233
255
  const file = await safePath(root, 'files/' + opts.path);
234
- if (opts.raw) {
256
+ if (opts.offset !== undefined || opts.length !== undefined || opts.expected !== undefined) {
257
+ if (opts.raw) fail('INVALID', 'Range reads emit base64 JSON; omit --raw');
258
+ emit({ path: opts.path, ...await readRange(file, opts) });
259
+ } else if (opts.raw) {
235
260
  const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
236
261
  try {
237
262
  if (!(await handle.stat()).isFile()) fail('UNSAFE_PATH', 'Expected a regular file');
@@ -0,0 +1,47 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { createHash } from 'node:crypto';
4
+ import { Readable, Transform } from 'node:stream';
5
+ import { pipeline } from 'node:stream/promises';
6
+ import { createGzip } from 'node:zlib';
7
+ import { fail, LibraryError, MAX_FILE_BYTES, put, safePath } from './store.mjs';
8
+
9
+ // Transform an existing Library file inside the existing writer transaction.
10
+ // No bulk stdin, external path, subprocess, second writer or source deletion.
11
+ export async function gzipFile(root, { path, to, expected, key }) {
12
+ if (!path || !to || path === to || !to.endsWith('.gz')) fail('INVALID', 'Supply distinct --path and --to ending in .gz');
13
+ if (!/^[a-f0-9]{64}$/.test(expected || '')) fail('INVALID', 'Supply the current source SHA-256');
14
+ if (path === 'LIBRARY_SYNC_ACCESS') fail('INVALID', 'The sync access marker is reserved');
15
+ const source = { path, sha256: expected, encoding: 'gzip', level: 9 };
16
+ async function* compressed() {
17
+ // put starts consuming only after it holds the Library writer lock.
18
+ const file = await safePath(root, 'files/' + path);
19
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
20
+ try {
21
+ const stat = await handle.stat();
22
+ if (!stat.isFile()) fail('UNSAFE_PATH', 'Expected a regular file');
23
+ if (stat.size > MAX_FILE_BYTES) fail('TOO_LARGE', 'Source exceeds the Library file limit');
24
+ let bytes = 0;
25
+ const sha = createHash('sha256');
26
+ const verify = new Transform({
27
+ transform(chunk, encoding, callback) {
28
+ bytes += chunk.length;
29
+ if (bytes > MAX_FILE_BYTES) return callback(new LibraryError('TOO_LARGE', 'Source exceeds the Library file limit'));
30
+ sha.update(chunk); callback(null, chunk);
31
+ },
32
+ flush(callback) {
33
+ if (sha.digest('hex') !== expected) return callback(new LibraryError('CONFLICT', 'Source changed; re-read its metadata before compression'));
34
+ source.bytes = bytes;
35
+ callback();
36
+ },
37
+ });
38
+ const gzip = createGzip({ level: 9 });
39
+ let failure;
40
+ const pumping = pipeline(handle.createReadStream({ autoClose: false }), verify, gzip).catch(error => { failure = error; });
41
+ try { for await (const chunk of gzip) yield chunk; }
42
+ finally { gzip.destroy(); await pumping; }
43
+ if (failure) throw failure;
44
+ } finally { await handle.close(); }
45
+ }
46
+ return put(root, to, Readable.from(compressed()), { key, expected: 'new', source });
47
+ }