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

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,19 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.0-beta.16
4
+
5
+ - Preserve atomic Library intake when originals use a separate filesystem mount.
6
+ - Read large originals through revision-checked, binary-safe bounded ranges with
7
+ source and chunk hashes, contiguous offsets and EOF metadata.
8
+ - Existing raw reads, guarded writes, data schema and deployment layout remain
9
+ compatible.
10
+
11
+ ## 0.1.0-beta.15
12
+
13
+ - Declare the full Library command's external-content, outbound, record-change
14
+ and review exposure contract, and validate command exposure metadata during
15
+ release checks.
16
+
3
17
  ## 0.1.0-beta.14
4
18
 
5
19
  - Sync existing Git checkouts and normalize text-mirror destinations without
package/README.md CHANGED
@@ -67,6 +67,16 @@ ez library qmd get qmd://library/notes/travel.md
67
67
 
68
68
  `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
69
 
70
+ For files larger than the executor's output allowance, first read metadata,
71
+ then use `get --path RELATIVE --offset 0 --length 524288 --expected SHA256`.
72
+ Range reads return JSON with base64 `content`, actual `length`, `chunkSha256`,
73
+ full source `bytes` and `sha256`, `nextOffset`, and `eof`. Decode each range,
74
+ verify its digest and contiguous offset, and continue at `nextOffset` until
75
+ `eof`; verify the assembled source size and digest. Every range hashes the
76
+ same open file it reads and rejects a changed source before emitting content.
77
+ Lengths are 1–524288 bytes; an offset at EOF returns an empty final range.
78
+ Range flags require all three values and cannot combine with `--raw`.
79
+
70
80
  Semantic embeddings are **off by default**. Enable them explicitly through the owning agent's host manager:
71
81
 
72
82
  ```sh
@@ -88,7 +98,7 @@ Only embedding/tokenizer inference is shared. Use structured `vec:` queries with
88
98
 
89
99
  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
100
 
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.
101
+ 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
102
 
93
103
  ## Backup after each save
94
104
 
@@ -102,6 +112,8 @@ When the owner asks to enable Drive backup and sync, the onboarded agent copies
102
112
 
103
113
  `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
114
 
115
+ 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.
116
+
105
117
  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
118
 
107
119
  ## State, lifecycle and limits
@@ -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]); }
@@ -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/ez-plugin.json CHANGED
@@ -1,12 +1,18 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "id": "library",
4
- "version": "0.1.0-beta.14",
4
+ "version": "0.1.0-beta.16",
5
5
  "description": "Dockerized agent library files, QMD retrieval and explicit persistence settings",
6
6
  "commands": {
7
7
  "library": {
8
8
  "executable": "bin/ez-library.mjs",
9
- "args": []
9
+ "args": [],
10
+ "exposure": {
11
+ "receivesExternalContent": true,
12
+ "sendsExternally": true,
13
+ "changesRecords": true,
14
+ "requiresReview": true
15
+ }
10
16
  },
11
17
  "library-file": {
12
18
  "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.14",
4
- "publishConfig": { "access": "public", "tag": "latest" },
3
+ "version": "0.1.0-beta.16",
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",
@@ -6,11 +6,22 @@ import {verifyPublishingSettings} from './publish-settings.mjs';
6
6
  assert.equal(readFileSync('docker/pnpm-lock.yaml','utf8'),readFileSync('pnpm-lock.yaml','utf8'),'Refresh docker/pnpm-lock.yaml after dependency changes');
7
7
  const p=JSON.parse(readFileSync('package.json','utf8'));
8
8
  const publishSettings=verifyPublishingSettings(p,readFileSync('.github/workflows/publish-beta.yml','utf8'));
9
+ const manifest=JSON.parse(readFileSync('ez-plugin.json','utf8'));
10
+ const exposureFields=['receivesExternalContent','sendsExternally','changesRecords','requiresReview'].sort();
11
+ const expectedExposure={receivesExternalContent:true,sendsExternally:true,changesRecords:true,requiresReview:true};
12
+ const readOnlyExposure={receivesExternalContent:true,sendsExternally:false,changesRecords:false,requiresReview:false};
13
+ assert.equal(manifest.version,p.version,'package and Ez manifest versions differ');
14
+ for(const [alias,command] of Object.entries(manifest.commands||{})) {
15
+ assert.deepEqual(Object.keys(command.exposure||{}).sort(),exposureFields,`Command ${alias} must declare every exposure field`);
16
+ for(const field of exposureFields) assert.equal(typeof command.exposure[field],'boolean',`Command ${alias} exposure.${field} must be boolean`);
17
+ }
18
+ assert.deepEqual(manifest.commands.library?.exposure,expectedExposure,'library exposure must conservatively describe its broad read/write/sync surface');
19
+ for(const alias of ['library-file','library-query']) assert.deepEqual(manifest.commands[alias]?.exposure,readOnlyExposure,`${alias} must remain read-only`);
9
20
  const [pack]=JSON.parse(execFileSync('npm',['pack','--dry-run','--ignore-scripts','--json'],{encoding:'utf8'}));
10
21
  const names=pack.files.map(f=>f.path);
11
22
  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}`);
12
23
  for(const name of names) assert(!/^agent\//.test(name) && !/(^|\/)(node_modules|\.git|\.private|todo\.md|principles\.md|backlog\.md|sprints\.md)(\/|$)|(^|\/)\.env$|\.(tgz|log)$|(^|\/)(qa|plugin-manager-qa|spec-benchmark)\.md$/.test(name),`Private/internal package entry: ${name}`);
13
24
  for(const entry of p.files) assert(names.some(name=>name===entry || name.startsWith(entry+'/')),`Declared package entry missing: ${entry}`);
14
25
  for(const bin of Object.values(p.bin||{})) assert(names.includes(bin),`Missing binary ${bin}`);
15
- if(names.includes('ez-plugin.json')) assert.equal(JSON.parse(readFileSync('ez-plugin.json')).version,p.version);
26
+ if(names.includes('ez-plugin.json')) assert.equal(manifest.version,p.version);
16
27
  console.log(JSON.stringify({...publishSettings,files:names,unpackedSize:pack.unpackedSize},null,2));
@@ -53,6 +53,15 @@ 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
+
56
65
  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
66
 
58
67
  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.
@@ -110,25 +119,9 @@ Native merge conflicts stop syncing and indexing. Use `git status`, `git show :2
110
119
 
111
120
  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
121
 
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.
122
+ ## Remote persistence (native bindings only)
130
123
 
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.
124
+ 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
125
 
133
126
  For an existing Git checkout mounted at `files`, use `git-adopt
134
127
  --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 } 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';
@@ -30,6 +30,8 @@ Local library files, QMD retrieval, and persistence settings.
30
30
  configure --expected HASH|new --key KEY < settings.json
31
31
  put --path RELATIVE --expected HASH|new --key KEY < file
32
32
  get --path RELATIVE [--raw] Metadata/hash, or exact binary stdout
33
+ get --path RELATIVE --offset BYTE --length BYTES --expected SHA256
34
+ Bounded base64 JSON, at most 524288 bytes
33
35
  file --library NAME -- RELATIVE Original file bytes for channel delivery (20 MiB)
34
36
  pdf-text --path RELATIVE Poppler text to stdout, page breaks retained
35
37
  list [--prefix TEXT] [--limit 100]
@@ -168,7 +170,7 @@ export async function main(argv = process.argv.slice(2)) {
168
170
  }); return;
169
171
  }
170
172
  const allowed = { doctor: [], settings: [], configure: ['expected', 'key'], put: ['path', 'expected', 'key'],
171
- get: ['path', 'raw'], 'pdf-text': ['path'], list: ['prefix', 'limit'], operation: ['key'],
173
+ get: ['path', 'raw', 'offset', 'length', 'expected'], 'pdf-text': ['path'], list: ['prefix', 'limit'], operation: ['key'],
172
174
  'sync-plan': ['remote'], 'sync-adopt': ['remote'], 'sync-status': [], 'sync-run': [],
173
175
  move: ['path', 'to', 'expected', 'key'], remove: ['path', 'expected', 'key'],
174
176
  'git-mirror-adopt': ['repository', 'branch', 'extensions', 'exclude-directories', 'expected-remote'], 'git-mirror-status': [], 'git-mirror-policy': ['expected', 'mode'],
@@ -231,7 +233,10 @@ export async function main(argv = process.argv.slice(2)) {
231
233
  if (command === 'get') {
232
234
  if (!opts.path) fail('INVALID', 'Supply --path');
233
235
  const file = await safePath(root, 'files/' + opts.path);
234
- if (opts.raw) {
236
+ if (opts.offset !== undefined || opts.length !== undefined || opts.expected !== undefined) {
237
+ if (opts.raw) fail('INVALID', 'Range reads emit base64 JSON; omit --raw');
238
+ emit({ path: opts.path, ...await readRange(file, opts) });
239
+ } else if (opts.raw) {
235
240
  const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
236
241
  try {
237
242
  if (!(await handle.stat()).isFile()) fail('UNSAFE_PATH', 'Expected a regular file');
package/src/store.mjs CHANGED
@@ -11,6 +11,7 @@ export class LibraryError extends Error {
11
11
  export const fail = (code, message) => { throw new LibraryError(code, message); };
12
12
  export const hash = bytes => createHash('sha256').update(bytes).digest('hex');
13
13
  export const MAX_FILE_BYTES = 512 * 1024 * 1024;
14
+ export const MAX_READ_BYTES = 512 * 1024;
14
15
  export const defaults = () => ({ schemaVersion: 1, storage: { mode: 'local' }, backup: { mode: 'off' } });
15
16
 
16
17
  function keys(value, allowed) {
@@ -97,6 +98,33 @@ export async function digest(file) {
97
98
  return { bytes, sha256: sha.digest('hex') };
98
99
  } finally { await handle.close(); }
99
100
  }
101
+ export async function readRange(file, { offset, length, expected }) {
102
+ if (!/^(0|[1-9][0-9]*)$/.test(offset ?? '') || !/^[1-9][0-9]*$/.test(length ?? '') ||
103
+ !Number.isSafeInteger(Number(offset)) || !Number.isSafeInteger(Number(length)) ||
104
+ Number(length) > MAX_READ_BYTES || !/^[a-f0-9]{64}$/.test(expected ?? '')) {
105
+ fail('INVALID', 'Ranges require --offset BYTE, --length 1..524288 and --expected SHA256');
106
+ }
107
+ offset = Number(offset); length = Number(length);
108
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
109
+ try {
110
+ if (!(await handle.stat()).isFile()) fail('UNSAFE_PATH', 'Expected a regular file');
111
+ const sha = createHash('sha256'), chunks = []; let bytes = 0;
112
+ // Hash and collect from one descriptor/pass: an atomic replacement cannot
113
+ // make the returned range belong to a different source revision.
114
+ for await (const chunk of handle.createReadStream({ autoClose: false })) {
115
+ sha.update(chunk);
116
+ const start = Math.max(0, offset - bytes), end = Math.min(chunk.length, offset + length - bytes);
117
+ if (end > start) chunks.push(chunk.subarray(start, end));
118
+ bytes += chunk.length;
119
+ }
120
+ const sha256 = sha.digest('hex');
121
+ if (sha256 !== expected) fail('CONFLICT', 'File changed; re-read metadata before requesting ranges');
122
+ if (offset > bytes) fail('INVALID', 'Offset exceeds file size');
123
+ const data = Buffer.concat(chunks), nextOffset = offset + data.length;
124
+ return { bytes, sha256, offset, length: data.length, chunkSha256: hash(data), encoding: 'base64',
125
+ content: data.toString('base64'), nextOffset, eof: nextOffset === bytes };
126
+ } finally { await handle.close(); }
127
+ }
100
128
  async function current(file) { return digest(file).catch(e => { if (e.code === 'ENOENT') return null; throw e; }); }
101
129
  export async function atomic(file, data) {
102
130
  const temp = `${file}.${randomUUID()}.tmp`;
@@ -124,7 +152,8 @@ export async function put(root, relative, input, { key, expected, kind = 'file',
124
152
  await safePath(root, path.relative(root, receiptFile));
125
153
  if (kind === 'file' && (typeof relative !== 'string' || !relative)) fail('INVALID', 'Supply a relative file path');
126
154
  const target = await safePath(root, kind === 'settings' ? 'settings.json' : 'files/' + relative, true);
127
- const temp = path.join(root, 'tmp', randomUUID());
155
+ // files may be a separate bind mount: stage on the destination filesystem.
156
+ const temp = path.join(path.dirname(target), '.ez-library-put-' + randomUUID() + '.tmp');
128
157
  let bytes = 0; const sha = createHash('sha256');
129
158
  try {
130
159
  await pipeline(input, new Transform({ transform(chunk, encoding, cb) {
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import { tmpdir } from 'node:os';
6
6
  import { Readable } from 'node:stream';
7
7
  import { spawnSync } from 'node:child_process';
8
- import { put, operation, settings, defaults, validateSettings, list, digest, hash } from '../src/store.mjs';
8
+ import { put, operation, settings, defaults, validateSettings, list, digest, readRange, MAX_READ_BYTES, hash } from '../src/store.mjs';
9
9
  import { qmdEnvironment } from '../src/cli.mjs';
10
10
 
11
11
  const cli = new URL('../bin/ez-library.mjs', import.meta.url).pathname;
@@ -29,6 +29,55 @@ test('intake preserves binary bytes, private modes, literal paths and replay acr
29
29
  assert.equal(read.status, 0); assert.deepEqual(read.stdout, data);
30
30
  });
31
31
 
32
+ test('bounded reads reconstruct large binary sources with contiguous hashes and EOF', async t => {
33
+ const root = await fixture(t), data = Buffer.alloc(MAX_READ_BYTES * 2 + 137);
34
+ for (let i = 0; i < data.length; i++) data[i] = i % 256;
35
+ const stored = await save(root, data), file = path.join(root, 'files/notes/test.md');
36
+ const chunks = []; let offset = 0;
37
+ do {
38
+ const range = await readRange(file, { offset: String(offset), length: String(MAX_READ_BYTES), expected: stored.sha256 });
39
+ const chunk = Buffer.from(range.content, range.encoding);
40
+ assert.equal(range.offset, offset); assert.equal(range.length, chunk.length);
41
+ assert.equal(range.bytes, data.length); assert.equal(range.sha256, stored.sha256);
42
+ assert.equal(range.chunkSha256, hash(chunk)); assert.equal(range.nextOffset, offset + chunk.length);
43
+ assert(Buffer.byteLength(JSON.stringify(range)) < 1024 * 1024);
44
+ chunks.push(chunk); offset = range.nextOffset;
45
+ if (range.eof) break;
46
+ } while (true);
47
+ assert.deepEqual(Buffer.concat(chunks), data);
48
+ assert.equal(hash(Buffer.concat(chunks)), stored.sha256);
49
+ const eof = await readRange(file, { offset: String(data.length), length: '1', expected: stored.sha256 });
50
+ assert.equal(eof.content, ''); assert.equal(eof.eof, true); assert.equal(eof.length, 0);
51
+ });
52
+
53
+ test('range contract rejects stale hashes and invalid bounds before emitting bytes', async t => {
54
+ const root = await fixture(t), stored = await save(root, 'one 🛰 two'), file = path.join(root, 'files/notes/test.md');
55
+ const valid = { offset: '0', length: '5', expected: stored.sha256 };
56
+ for (const invalid of [{ offset: undefined }, { length: undefined }, { expected: undefined }, { length: '0' },
57
+ { offset: '-1' }, { offset: '1.5' }, { offset: '9007199254740992' }, { length: String(MAX_READ_BYTES + 1) },
58
+ { offset: '999' }, { expected: 'new' }]) {
59
+ await assert.rejects(readRange(file, { ...valid, ...invalid }), code('INVALID'));
60
+ }
61
+ await fs.writeFile(file, 'changed');
62
+ await assert.rejects(readRange(file, valid), code('CONFLICT'));
63
+ const read = spawnSync(process.execPath, [cli, 'get', '--path', 'notes/test.md', '--offset', '0', '--length', '5', '--expected', stored.sha256],
64
+ { env: { ...process.env, EZ_LIBRARY_STATE: root }, encoding: 'utf8' });
65
+ assert.equal(read.status, 3); assert.equal(read.stdout, ''); assert.match(read.stderr, /CONFLICT/);
66
+ });
67
+
68
+ test('range CLI returns binary-safe JSON and preserves path and raw boundaries', async t => {
69
+ const root = await fixture(t), data = Buffer.from([0, 255, 10, 128, 1]), stored = await save(root, data);
70
+ const args = ['get', '--path', 'notes/test.md', '--offset', '1', '--length', '3', '--expected', stored.sha256];
71
+ const invoke = argv => spawnSync(process.execPath, [cli, ...argv], { env: { ...process.env, EZ_LIBRARY_STATE: root }, encoding: 'utf8' });
72
+ const read = invoke(args); assert.equal(read.status, 0);
73
+ const range = JSON.parse(read.stdout).data;
74
+ assert.equal(range.path, 'notes/test.md'); assert.deepEqual(Buffer.from(range.content, 'base64'), data.subarray(1, 4));
75
+ assert.equal(invoke([...args, '--raw']).status, 2);
76
+ assert.equal(invoke(['get', '--path', '../escape', '--offset', '0', '--length', '1', '--expected', stored.sha256]).status, 2);
77
+ await fs.symlink(path.join(root, 'files/notes/test.md'), path.join(root, 'files/link'));
78
+ assert.equal(invoke(['get', '--path', 'link', '--offset', '0', '--length', '1', '--expected', stored.sha256]).status, 2);
79
+ });
80
+
32
81
  test('replacement requires current revision; preserves history; stale replay never overwrites new content', async t => {
33
82
  const root = await fixture(t); const first = await save(root, 'original');
34
83
  await assert.rejects(save(root, 'bad', { key: 'second' }), code('CONFLICT'));
@@ -59,6 +108,8 @@ test('bounds and interrupted input leave no partial target or active lock', asyn
59
108
  const broken = Readable.from((async function* () { yield 'part'; throw Error('interrupted'); })());
60
109
  await assert.rejects(put(root, 'partial.md', broken, { key: 'broken', expected: 'new' }), /interrupted/);
61
110
  assert.deepEqual(await fs.readdir(path.join(root, 'tmp')), []);
111
+ assert.deepEqual(await fs.readdir(path.join(root, 'files')), ['notes']);
112
+ assert.deepEqual(await fs.readdir(path.join(root, 'files/notes')), []);
62
113
  await assert.rejects(fs.stat(path.join(root, 'files/partial.md')), code('ENOENT'));
63
114
  await assert.rejects(fs.stat(path.join(root, '.writer-lock')), code('ENOENT'));
64
115
  });