@jc_stack/ez-library 0.1.0-beta.16 → 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,21 @@
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
+
3
19
  ## 0.1.0-beta.16
4
20
 
5
21
  - Preserve atomic Library intake when originals use a separate filesystem mount.
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
 
@@ -77,6 +80,34 @@ same open file it reads and rejects a changed source before emitting content.
77
80
  Lengths are 1–524288 bytes; an offset at EOF returns an empty final range.
78
81
  Range flags require all three values and cannot combine with `--raw`.
79
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
+
80
111
  Semantic embeddings are **off by default**. Enable them explicitly through the owning agent's host manager:
81
112
 
82
113
  ```sh
@@ -129,10 +160,13 @@ An interrupted command may leave `/state/.writer-lock`, or QMD's own embed lock
129
160
  ```sh
130
161
  pnpm install --frozen-lockfile
131
162
  pnpm verify
132
- npm run release:check
163
+ pnpm run release:check
133
164
  docker build --target test -t ez-library-tests .
134
165
  docker build --target runtime -t ez-library:local .
135
166
  EZ_LIBRARY_IMAGE=ez-library:local node docker/smoke.mjs
136
167
  ```
137
168
 
138
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.
@@ -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
 
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.16",
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,6 +1,6 @@
1
1
  {
2
2
  "name": "@jc_stack/ez-library",
3
- "version": "0.1.0-beta.16",
3
+ "version": "0.1.0-beta.18",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "tag": "latest"
@@ -35,7 +35,8 @@
35
35
  "LICENSE",
36
36
  "THIRD_PARTY_NOTICES.md",
37
37
  "CHANGELOG.md",
38
- "patches"
38
+ "patches",
39
+ "pnpm-workspace.yaml"
39
40
  ],
40
41
  "scripts": {
41
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
@@ -62,6 +62,32 @@ All three range flags are required; do not combine them with `--raw`.
62
62
  A changed source returns a conflict before emitting content. Re-read metadata
63
63
  and restart assembly rather than combining different revisions.
64
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
+
65
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.
66
92
 
67
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.
@@ -109,12 +135,14 @@ Use `move` and `remove` with current hashes and operation keys to organize files
109
135
 
110
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.
111
137
 
112
- ## GitHub-only two-way sync
138
+ ## GitHub sync
113
139
 
114
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.
115
141
 
116
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.
117
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
+
118
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.
119
147
 
120
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.
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, readRange, 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,6 +30,10 @@ 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
33
38
  get --path RELATIVE --offset BYTE --length BYTES --expected SHA256
34
39
  Bounded base64 JSON, at most 524288 bytes
@@ -44,12 +49,12 @@ Local library files, QMD retrieval, and persistence settings.
44
49
  sync-adopt --remote REMOTE:PATH Import matching originals; enable two-way sync
45
50
  sync-status Binding, last sync, extraction and embedding status
46
51
  sync-run Reconcile now and refresh the index
47
- sync-policy --expected HASH --mode paused|two-way [--interval 60]
52
+ sync-policy --expected HASH --mode paused|two-way|pull-only [--interval 60]
48
53
  git-mirror-adopt --repository OWNER/REPO [--branch main] [--extensions .md,.txt] [--exclude-directories private,archive] [--expected-remote SHA]
49
54
  git-mirror-status Text-only GitHub history destination and revision
50
55
  git-mirror-policy --expected HASH --mode paused|one-way
51
56
  git-key --repository OWNER/REPO Create a repository key; return public key only
52
- 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]
53
58
  git ... Native Git in the bound Library working tree
54
59
 
55
60
  Local commands emit JSON (--json is also accepted); get --raw and qmd preserve
@@ -98,6 +103,9 @@ export async function main(argv = process.argv.slice(2)) {
98
103
  if (!argv.length || argv[0] === '--help' || argv[0] === 'help') { process.stdout.write(help); return; }
99
104
  if (argv[0] === '--version') { process.stdout.write(version + '\n'); return; }
100
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; }
101
109
  const base = process.env.EZ_LIBRARY_STATE || '/state';
102
110
  if (command === 'sources') {
103
111
  parseArgs({ args, options: { json: { type: 'boolean' } }, strict: true });
@@ -169,12 +177,12 @@ export async function main(argv = process.argv.slice(2)) {
169
177
  return (await rclone(root, rest, { inherit: true })).code;
170
178
  }); return;
171
179
  }
172
- const allowed = { doctor: [], settings: [], configure: ['expected', 'key'], put: ['path', 'expected', 'key'],
180
+ const allowed = { doctor: [], settings: [], configure: ['expected', 'key'], put: ['path', 'expected', 'key'], replace: ['path', 'key'],
173
181
  get: ['path', 'raw', 'offset', 'length', 'expected'], 'pdf-text': ['path'], list: ['prefix', 'limit'], operation: ['key'],
174
182
  'sync-plan': ['remote'], 'sync-adopt': ['remote'], 'sync-status': [], 'sync-run': [],
175
- move: ['path', 'to', 'expected', 'key'], remove: ['path', 'expected', 'key'],
183
+ move: ['path', 'to', 'expected', 'key'], remove: ['path', 'expected', 'key'], gzip: ['path', 'to', 'expected', 'key'],
176
184
  'git-mirror-adopt': ['repository', 'branch', 'extensions', 'exclude-directories', 'expected-remote'], 'git-mirror-status': [], 'git-mirror-policy': ['expected', 'mode'],
177
- 'git-key': ['repository'], 'git-adopt': ['repository', 'branch', 'existing-checkout'],
185
+ 'git-key': ['repository'], 'git-adopt': ['repository', 'branch', 'existing-checkout', 'mode'],
178
186
  'sync-policy': ['expected', 'mode', 'interval'] }[command];
179
187
  if (!allowed) fail('INVALID', 'Unknown command; use --help');
180
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 });
@@ -183,7 +191,7 @@ export async function main(argv = process.argv.slice(2)) {
183
191
  if (command === 'git-mirror-status') { emit(await mirrorStatus(root)); return; }
184
192
  if (command === 'git-mirror-policy') { emit(await mirrorPolicy(root, opts.expected, opts.mode)); return; }
185
193
  if (command === 'git-key') { emit(await gitKey(root, opts.repository)); return; }
186
- 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; }
187
195
  if (command === 'sync-adopt') { emit(await syncAdopt(root, opts.remote, base)); return; }
188
196
  if (command === 'sync-status') { emit(await syncStatus(root)); return; }
189
197
  if (command === 'sync-run') { emit(await syncRun(root, base)); return; }
@@ -200,6 +208,18 @@ export async function main(argv = process.argv.slice(2)) {
200
208
  if (!opts.path) fail('INVALID', 'Supply --path');
201
209
  emit(await put(root, opts.path, process.stdin, { key: opts.key, expected: opts.expected })); return;
202
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
+ }
203
223
  if (command === 'doctor') {
204
224
  let configured = false; let value = { settings: defaults(), sha256: null };
205
225
  try { await rootDir(root); value = await settings(root); configured = value.sha256 !== null; }
@@ -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
+ }
@@ -135,17 +135,22 @@ export async function mirrorTransfer(root) {
135
135
  if (remote) {
136
136
  if (config.lastCommit && remote !== config.lastCommit && remote !== local.stdout.trim()) fail('CONFLICT', 'Mirror branch was changed externally');
137
137
  if (local.code !== 0) fail('CONFLICT', 'Mirror remote changed before first commit');
138
- succeeded(await run(['fetch', '--no-tags', 'origin', 'refs/heads/' + config.branch]), 'Fetch mirror head');
139
- if ((await run(['merge-base', '--is-ancestor', 'FETCH_HEAD', 'HEAD'])).code !== 0) fail('CONFLICT', 'GitHub mirror was edited externally; preserve and reconcile it before resuming');
138
+ if (remote !== local.stdout.trim()) {
139
+ succeeded(await run(['fetch', '--no-tags', 'origin', 'refs/heads/' + config.branch]), 'Fetch mirror head');
140
+ if ((await run(['merge-base', '--is-ancestor', 'FETCH_HEAD', 'HEAD'])).code !== 0) fail('CONFLICT', 'GitHub mirror was edited externally; preserve and reconcile it before resuming');
141
+ }
140
142
  } else if (config.lastCommit) fail('CONFLICT', 'Mirror branch disappeared; no automatic recreation');
141
143
  if (selected.some(x => x.bytes >= 100 * 1024 * 1024)) fail('TOO_LARGE', 'Text mirror file exceeds GitHub ordinary-file limit');
142
144
  const target = path.join(root, 'sync/text-mirror/files');
143
- const selectedPaths = new Set(selected.map(x => x.destination));
145
+ const selectedPaths = new Set(selected.map(x => x.destination)), projected = new Map();
144
146
  for (const old of await inventory(target)) {
145
147
  if (!selectedPaths.has(old.path.normalize('NFC'))) await fs.unlink(await safePath(root, 'sync/text-mirror/files/' + old.path));
148
+ else projected.set(old.path, old.sha256);
146
149
  }
147
150
  await pruneEmptyDirectories(target);
151
+ // Rewrite only changed bytes so Git's stat cache stays valid for unchanged notes.
148
152
  for (const item of selected) {
153
+ if (projected.get(item.destination) === item.sha256) continue;
149
154
  const destination = await safePath(root, 'sync/text-mirror/files/' + item.destination, true);
150
155
  await fs.copyFile(await safePath(root, 'files/' + item.path), destination);
151
156
  }
@@ -156,9 +161,12 @@ export async function mirrorTransfer(root) {
156
161
  if (![0, 1].includes(diff.code)) succeeded(diff, 'Inspect mirror changes');
157
162
  if (diff.code === 1 || local.code !== 0) succeeded(await run(['commit', '--allow-empty', '--no-gpg-sign', '-m', 'Version Library text changes']), 'Commit text mirror');
158
163
  const commit = succeeded(await run(['rev-parse', 'HEAD']), 'Read mirror commit').trim();
159
- succeeded(await run(['push', 'origin', 'HEAD:refs/heads/' + config.branch]), 'Push text mirror');
160
- const verified = succeeded(await run(['ls-remote', 'origin', 'refs/heads/' + config.branch]), 'Verify text mirror').trim().split(/\s+/)[0];
161
- if (verified !== commit) fail('UNCERTAIN', 'Mirror advanced during verification');
162
- await atomic(file(root), jsonBytes({ ...config, lastCommit: commit }));
164
+ // The remote head read above already proves an unchanged projection.
165
+ if (remote !== commit) {
166
+ succeeded(await run(['push', 'origin', 'HEAD:refs/heads/' + config.branch]), 'Push text mirror');
167
+ const verified = succeeded(await run(['ls-remote', 'origin', 'refs/heads/' + config.branch]), 'Verify text mirror').trim().split(/\s+/)[0];
168
+ if (verified !== commit) fail('UNCERTAIN', 'Mirror advanced during verification');
169
+ }
170
+ if (config.lastCommit !== commit) await atomic(file(root), jsonBytes({ ...config, lastCommit: commit }));
163
171
  return { state: 'mirrored', repository: config.repository, branch: config.branch, commit, files: selected.length, remoteVerified: true };
164
172
  }
package/src/git-sync.mjs CHANGED
@@ -28,7 +28,7 @@ export async function gitKey(root, repository) {
28
28
  const { ssh_keys: keys } = await response.json();
29
29
  if (!Array.isArray(keys) || !keys.length || keys.some(k => !/^(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp256) [A-Za-z0-9+/=]+$/.test(k))) fail('UNAVAILABLE', 'Unexpected GitHub host-key response');
30
30
  await atomic(path.join(dir, 'known_hosts'), keys.map(k => 'github.com ' + k).join('\n') + '\n');
31
- return { repository, publicKey: (await fs.readFile(key + '.pub', 'utf8')).trim(), registration: 'Register this public key with write access through the connected GitHub plugin. Private key stays in Library.' };
31
+ return { repository, publicKey: (await fs.readFile(key + '.pub', 'utf8')).trim(), registration: 'Register this public key through the connected GitHub plugin: read-only for pull-only sync, write access for two-way sync. Private key stays in Library.' };
32
32
  });
33
33
  }
34
34
 
@@ -85,7 +85,13 @@ async function existingCheckout(root, config) {
85
85
  return origin;
86
86
  }
87
87
 
88
- export async function gitAdopt(root, repository, branch = 'main', stateRoot = root, reuseCheckout = false) {
88
+ async function cleanPullTree(root, config) {
89
+ const changes = succeeded(await git(root, config, ['status', '--porcelain=v1', '--untracked-files=all']), 'Inspect pull-only working tree');
90
+ if (changes) fail('CONFLICT', 'Pull-only library has local changes; preserve and reconcile them before syncing');
91
+ }
92
+
93
+ export async function gitAdopt(root, repository, branch = 'main', stateRoot = root, reuseCheckout = false, mode = 'two-way') {
94
+ if (!['two-way', 'pull-only'].includes(mode)) fail('INVALID', 'Use two-way or pull-only Git sync');
89
95
  const remote = repositoryURL(repository);
90
96
  return locked(root, async root => {
91
97
  await checkPolicy(root, repository, branch);
@@ -105,7 +111,8 @@ export async function gitAdopt(root, repository, branch = 'main', stateRoot = ro
105
111
  // No checkout, reset, commit or push during adoption. Native history and
106
112
  // eligible unstaged edits remain owned by the existing checkout.
107
113
  succeeded(await git(root, config, ['merge-base', 'HEAD', 'FETCH_HEAD']), 'Verify shared history');
108
- config.mode = 'two-way';
114
+ if (mode === 'pull-only') await cleanPullTree(root, config);
115
+ config.mode = mode;
109
116
  await atomic(binding, jsonBytes(config));
110
117
  return { config, imported: 0, indexing: 'pending' };
111
118
  }
@@ -134,45 +141,65 @@ export async function gitAdopt(root, repository, branch = 'main', stateRoot = ro
134
141
  succeeded(await git(root, config, ['reset', '--mixed', 'FETCH_HEAD']), 'Initialize native index');
135
142
  const missing = entries.filter(e => !existing.has(e.path)).map(e => e.path + '\0').join('');
136
143
  if (missing) succeeded(await git(root, config, ['checkout-index', '-z', '--stdin'], { input: missing }), 'Import tracked files');
137
- config.mode = 'two-way';
144
+ if (mode === 'pull-only') await cleanPullTree(root, config);
145
+ config.mode = mode;
138
146
  await atomic(binding, jsonBytes(config));
139
147
  return { config, imported: entries.length, indexing: 'pending' };
140
148
  });
141
149
  }
142
150
 
143
151
  export async function gitTransfer(root, config) {
152
+ if (!['two-way', 'pull-only'].includes(config.mode)) fail('INVALID', 'Use two-way or pull-only Git sync');
153
+ const pullOnly = config.mode === 'pull-only';
144
154
  await checkPolicy(root, config.repository, config.branch);
145
155
  if (config.existingCheckout) await existingCheckout(root, config);
146
156
  const actualRemote = succeeded(await git(root, config, ['remote', 'get-url', 'origin']), 'Check bound remote').trim();
147
157
  if (actualRemote !== (config.checkoutOrigin || repositoryURL(config.repository))) fail('CONFLICT', 'Git remote no longer matches the Library binding');
148
158
  const conflict = succeeded(await git(root, config, ['ls-files', '--unmerged']), 'Inspect merge state');
149
159
  if (conflict) fail('CONFLICT', 'Git merge unresolved; use native git status/show/add to resolve both retained versions before syncing');
150
- const files = config.existingCheckout ? await gitInventory(root) : await inventory(path.join(root, 'files'), '', { includeHidden: true });
151
- const ignored = new Set(succeeded(await git(root, config, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z']), 'Inspect ignored files').split('\0').filter(Boolean));
152
- if (files.some(f => !ignored.has(f.path) && f.bytes >= 100 * 1024 * 1024)) fail('TOO_LARGE', 'GitHub ordinary files must be below 100 MiB; select another storage mode for larger media');
153
- succeeded(await git(root, config, ['add', '--all', '--', '.']), 'Stage Library changes');
154
- const stagedTree = succeeded(await git(root, config, ['write-tree']), 'Read staged tree').trim();
155
- await tree(root, config, stagedTree);
156
- const diff = await git(root, config, ['diff', '--cached', '--quiet']);
157
- if (![0, 1].includes(diff.code)) succeeded(diff, 'Inspect staged changes');
158
- const merging = await git(root, config, ['rev-parse', '--verify', 'MERGE_HEAD']);
159
- if (diff.code === 1 || merging.code === 0) succeeded(await git(root, config, ['commit', '--no-gpg-sign', '-m', 'Sync Library changes']), 'Commit Library changes');
160
+ if (pullOnly) await cleanPullTree(root, config);
161
+ else {
162
+ const files = config.existingCheckout ? await gitInventory(root) : await inventory(path.join(root, 'files'), '', { includeHidden: true });
163
+ const ignored = new Set(succeeded(await git(root, config, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z']), 'Inspect ignored files').split('\0').filter(Boolean));
164
+ if (files.some(f => !ignored.has(f.path) && f.bytes >= 100 * 1024 * 1024)) fail('TOO_LARGE', 'GitHub ordinary files must be below 100 MiB; select another storage mode for larger media');
165
+ succeeded(await git(root, config, ['add', '--all', '--', '.']), 'Stage Library changes');
166
+ const stagedTree = succeeded(await git(root, config, ['write-tree']), 'Read staged tree').trim();
167
+ await tree(root, config, stagedTree);
168
+ const diff = await git(root, config, ['diff', '--cached', '--quiet']);
169
+ if (![0, 1].includes(diff.code)) succeeded(diff, 'Inspect staged changes');
170
+ const merging = await git(root, config, ['rev-parse', '--verify', 'MERGE_HEAD']);
171
+ if (diff.code === 1 || merging.code === 0) succeeded(await git(root, config, ['commit', '--no-gpg-sign', '-m', 'Sync Library changes']), 'Commit Library changes');
172
+ }
160
173
  const transport = config.existingCheckout ? repositoryURL(config.repository) : 'origin';
161
174
  const trackingRef = 'refs/remotes/origin/' + config.branch;
162
- const previousTracking = config.existingCheckout ? await git(root, config, ['rev-parse', '--verify', '--quiet', trackingRef]) : null;
163
- if (previousTracking && ![0, 1].includes(previousTracking.code)) succeeded(previousTracking, 'Read origin revision');
164
175
  succeeded(await git(root, config, ['fetch', '--no-tags', transport, 'refs/heads/' + config.branch]), 'Fetch remote changes');
165
176
  await tree(root, config, 'FETCH_HEAD');
177
+ // Native fetch may itself update origin's tracking ref, including when its
178
+ // URL was supplied directly. Compare-and-swap against that post-fetch value.
179
+ const previousTracking = config.existingCheckout ? await git(root, config, ['rev-parse', '--verify', '--quiet', trackingRef]) : null;
180
+ if (previousTracking && ![0, 1].includes(previousTracking.code)) succeeded(previousTracking, 'Read origin revision');
166
181
  const head = succeeded(await git(root, config, ['rev-parse', 'HEAD']), 'Read local commit').trim();
167
- const merge = await git(root, config, ['merge', '--no-overwrite-ignore', '--no-edit', '--no-gpg-sign', 'FETCH_HEAD']);
182
+ if (pullOnly) {
183
+ const ancestor = await git(root, config, ['merge-base', '--is-ancestor', 'HEAD', 'FETCH_HEAD']);
184
+ if (ancestor.code === 1) fail('CONFLICT', 'Pull-only library has local commits or rewritten remote history; reconcile before syncing');
185
+ succeeded(ancestor, 'Check pull-only fast-forward');
186
+ }
187
+ const merge = await git(root, config, ['merge', '--no-overwrite-ignore', ...(pullOnly ? ['--ff-only'] : ['--no-edit', '--no-gpg-sign']), 'FETCH_HEAD']);
168
188
  if (merge.code !== 0) {
169
189
  if (succeeded(await git(root, config, ['ls-files', '--unmerged']), 'Inspect conflicts')) fail('CONFLICT', 'Both revisions retained in Git merge stages. Resolve the merge before sync/indexing resumes');
170
190
  succeeded(merge, 'Merge remote changes');
171
191
  }
172
192
  const commit = succeeded(await git(root, config, ['rev-parse', 'HEAD']), 'Read synchronized commit').trim();
173
- succeeded(await git(root, config, ['push', transport, 'HEAD:refs/heads/' + config.branch]), 'Push Library changes');
193
+ if (!pullOnly) succeeded(await git(root, config, ['push', transport, 'HEAD:refs/heads/' + config.branch]), 'Push Library changes');
174
194
  const remote = succeeded(await git(root, config, ['ls-remote', '--exit-code', transport, 'refs/heads/' + config.branch]), 'Verify remote commit').trim().split(/\s+/)[0];
175
195
  if (remote !== commit) fail('UNCERTAIN', 'Remote advanced during verification; fetch/reconcile on the next cycle');
176
- if (config.existingCheckout) succeeded(await git(root, config, ['update-ref', trackingRef, commit, previousTracking.code === 0 ? previousTracking.stdout.trim() : '0'.repeat(40)]), 'Record verified origin revision');
196
+ if (config.existingCheckout) {
197
+ // Push can also record the verified tracking value itself. Keep the guard
198
+ // for other changes, but do not reject a ref already at the desired commit.
199
+ const tracking = await git(root, config, ['rev-parse', '--verify', '--quiet', trackingRef]);
200
+ if (![0, 1].includes(tracking.code)) succeeded(tracking, 'Read verified origin revision');
201
+ if (tracking.code !== 0 || tracking.stdout.trim() !== commit)
202
+ succeeded(await git(root, config, ['update-ref', trackingRef, commit, previousTracking.code === 0 ? previousTracking.stdout.trim() : '0'.repeat(40)]), 'Record verified origin revision');
203
+ }
177
204
  return { commit, previousCommit: head, remoteVerified: true };
178
205
  }
package/src/indexer.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as fs from 'node:fs/promises';
2
2
  import path from 'node:path';
3
- import { atomic, digest, hash, jsonBytes, safePath, settings } from './store.mjs';
3
+ import { atomic, hash, jsonBytes, safePath, scanDigest, settings } from './store.mjs';
4
4
  import { native, qmd, succeeded } from './native.mjs';
5
5
 
6
6
  export async function inventory(directory, relative = '', { includeHidden = false } = {}) {
@@ -9,7 +9,7 @@ export async function inventory(directory, relative = '', { includeHidden = fals
9
9
  if (!includeHidden && item.name.startsWith('.')) continue;
10
10
  const name = relative + item.name, file = path.join(directory, item.name);
11
11
  if (item.isDirectory()) result.push(...await inventory(file, name + '/', { includeHidden }));
12
- else if (item.isFile()) result.push({ path: name, ...(await digest(file)) });
12
+ else if (item.isFile()) result.push({ path: name, ...(await scanDigest(file)) });
13
13
  else throw Error('Unsupported symlink or special file in Library');
14
14
  }
15
15
  return result;
@@ -33,7 +33,7 @@ export async function gitInventory(root) {
33
33
  if (!stat) { absent = true; break; }
34
34
  if (stat.isSymbolicLink() || !(i === parts.length - 1 ? stat.isFile() : stat.isDirectory())) throw Error('Unsupported symlink or special file in Library');
35
35
  }
36
- if (!absent) files.push({ path: name, ...(await digest(file)) });
36
+ if (!absent) files.push({ path: name, ...(await scanDigest(file)) });
37
37
  }
38
38
  return files.sort((a, b) => a.path.localeCompare(b.path));
39
39
  }
package/src/store.mjs CHANGED
@@ -12,6 +12,8 @@ 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
14
  export const MAX_READ_BYTES = 512 * 1024;
15
+ export const MAX_REPLACE_BYTES = 256 * 1024;
16
+ const MAX_TEXT_BYTES = 8 * 1024 * 1024;
15
17
  export const defaults = () => ({ schemaVersion: 1, storage: { mode: 'local' }, backup: { mode: 'off' } });
16
18
 
17
19
  function keys(value, allowed) {
@@ -88,16 +90,37 @@ export async function locked(root, fn) {
88
90
  try { return await fn(await initialize(root)); }
89
91
  finally { await fs.rmdir(lock); }
90
92
  }
91
- export async function digest(file) {
93
+ async function opened(file, read) {
92
94
  const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
93
95
  try {
94
- const st = await handle.stat();
96
+ const st = await handle.stat({ bigint: true });
95
97
  if (!st.isFile()) fail('UNSAFE_PATH', 'Expected a regular file');
96
- const sha = createHash('sha256'); let bytes = 0;
97
- for await (const chunk of handle.createReadStream({ autoClose: false })) { sha.update(chunk); bytes += chunk.length; }
98
- return { bytes, sha256: sha.digest('hex') };
98
+ return await read(handle, st);
99
99
  } finally { await handle.close(); }
100
100
  }
101
+ async function contentDigest(handle) {
102
+ const sha = createHash('sha256'); let bytes = 0;
103
+ for await (const chunk of handle.createReadStream({ autoClose: false })) { sha.update(chunk); bytes += chunk.length; }
104
+ return { bytes, sha256: sha.digest('hex') };
105
+ }
106
+ export const digest = file => opened(file, contentDigest);
107
+
108
+ // The resident worker inventories unchanged originals every cycle. Within one
109
+ // process, reuse a digest only while device, inode, size, mtime and ctime are
110
+ // identical, and never for files changed within the last two seconds.
111
+ const scanned = new Map();
112
+ export const scanDigest = file => opened(file, async (handle, st) => {
113
+ const key = `${st.dev}:${st.ino}:${st.size}:${st.mtimeNs}:${st.ctimeNs}`;
114
+ const known = scanned.get(file);
115
+ if (known?.key === key) return { ...known.value };
116
+ const value = await contentDigest(handle);
117
+ const changed = st.mtimeNs > st.ctimeNs ? st.mtimeNs : st.ctimeNs;
118
+ if (BigInt(Date.now()) * 1000000n - changed > 2000000000n) {
119
+ if (scanned.size >= 100000) scanned.clear();
120
+ scanned.set(file, { key, value });
121
+ }
122
+ return { ...value };
123
+ });
101
124
  export async function readRange(file, { offset, length, expected }) {
102
125
  if (!/^(0|[1-9][0-9]*)$/.test(offset ?? '') || !/^[1-9][0-9]*$/.test(length ?? '') ||
103
126
  !Number.isSafeInteger(Number(offset)) || !Number.isSafeInteger(Number(length)) ||
@@ -144,7 +167,7 @@ export async function settings(root) {
144
167
 
145
168
  // Receipts record intent before installation. Readback determines stored/changed/missing,
146
169
  // including after interruption between the atomic receipt and file renames.
147
- export async function put(root, relative, input, { key, expected, kind = 'file', maxBytes = MAX_FILE_BYTES } = {}) {
170
+ export async function put(root, relative, input, { key, expected, kind = 'file', maxBytes = MAX_FILE_BYTES, source } = {}) {
148
171
  if (expected !== 'new' && !/^[a-f0-9]{64}$/.test(expected || '')) fail('INVALID', 'Supply --expected new or the current SHA-256');
149
172
  if (!['file', 'settings'].includes(kind)) fail('INVALID', 'Unknown write kind');
150
173
  return locked(root, async root => {
@@ -161,7 +184,8 @@ export async function put(root, relative, input, { key, expected, kind = 'file',
161
184
  if (bytes > maxBytes) return cb(new LibraryError('TOO_LARGE', `Input exceeds ${maxBytes} bytes`));
162
185
  sha.update(chunk); cb(null, chunk);
163
186
  } }), createWriteStream(temp, { flags: 'wx', mode: 0o600 }));
164
- const request = { kind, path: kind === 'settings' ? 'settings.json' : relative, bytes, sha256: sha.digest('hex'), expected };
187
+ const request = { kind, path: kind === 'settings' ? 'settings.json' : relative, bytes, sha256: sha.digest('hex'), expected,
188
+ ...(source ? { source } : {}) };
165
189
  const oldReceipt = await fs.readFile(receiptFile, 'utf8').then(JSON.parse).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
166
190
  if (oldReceipt && JSON.stringify(oldReceipt) !== JSON.stringify(request)) fail('KEY_REUSED', 'Operation key was already used with different content or preconditions');
167
191
  const before = await current(target);
@@ -183,6 +207,7 @@ export async function put(root, relative, input, { key, expected, kind = 'file',
183
207
  export async function operation(root, key) {
184
208
  const receiptFile = await safePath(root, path.relative(root, operationPath(root, key)));
185
209
  const receipt = JSON.parse(await fs.readFile(receiptFile, 'utf8'));
210
+ if (receipt.kind === 'replace') return replacementView(root, receipt);
186
211
  if (['move', 'remove'].includes(receipt.kind)) {
187
212
  const source = await current(await safePath(root, 'files/' + receipt.path));
188
213
  const target = receipt.to ? await current(await safePath(root, 'files/' + receipt.to)) : null;
@@ -194,6 +219,81 @@ export async function operation(root, key) {
194
219
  return { ...receipt, state: !now ? 'missing' : now.sha256 === receipt.sha256 ? 'stored' : 'changed' };
195
220
  }
196
221
 
222
+ const uniquePosition = (text, part) => {
223
+ const at = text.indexOf(part);
224
+ return at >= 0 && text.indexOf(part, at + 1) < 0 ? at : -1;
225
+ };
226
+ function validateReplacement(value) {
227
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
228
+ Object.keys(value).some(key => !['before', 'after'].includes(key)) ||
229
+ typeof value.before !== 'string' || !value.before || typeof value.after !== 'string' ||
230
+ !value.after || value.before === value.after ||
231
+ Buffer.byteLength(JSON.stringify(value)) > MAX_REPLACE_BYTES) {
232
+ fail('INVALID', 'Supply distinct nonempty before/after strings in at most 256 KiB of JSON');
233
+ }
234
+ for (const text of [value.before, value.after]) {
235
+ if (Buffer.from(text).toString('utf8') !== text) fail('INVALID', 'Replacement must be valid UTF-8 text');
236
+ }
237
+ }
238
+ async function readText(file) {
239
+ const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
240
+ try {
241
+ const stat = await handle.stat();
242
+ if (!stat.isFile()) fail('UNSAFE_PATH', 'Expected a regular text file');
243
+ if (stat.size > MAX_TEXT_BYTES) fail('TOO_LARGE', 'Text replacement is limited to 8 MiB files');
244
+ const chunks = []; let bytes = 0;
245
+ for await (const chunk of handle.createReadStream({ autoClose: false })) {
246
+ bytes += chunk.length;
247
+ if (bytes > MAX_TEXT_BYTES) fail('TOO_LARGE', 'Text replacement is limited to 8 MiB files');
248
+ chunks.push(chunk);
249
+ }
250
+ const data = Buffer.concat(chunks), text = data.toString('utf8');
251
+ if (!Buffer.from(text).equals(data)) fail('INVALID', 'Text replacement requires valid UTF-8');
252
+ return { text, bytes, sha256: hash(data) };
253
+ } finally { await handle.close(); }
254
+ }
255
+ async function replacementView(root, receipt) {
256
+ validateReplacement({ before: receipt.before, after: receipt.after });
257
+ const file = await safePath(root, 'files/' + receipt.path);
258
+ const now = await readText(file).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
259
+ return { kind: 'replace', path: receipt.path, beforeSha256: hash(receipt.before), afterSha256: hash(receipt.after),
260
+ state: !now ? 'missing' : uniquePosition(now.text, receipt.after) >= 0 ? 'stored' : 'changed',
261
+ ...(now ? { bytes: now.bytes, sha256: now.sha256 } : {}) };
262
+ }
263
+
264
+ // Exact literal replacement is a scoped compare-and-swap, not a Markdown merge.
265
+ // The caller supplies its complete unique block. Unrelated bytes are read under
266
+ // the existing writer lock and retained, including other callers' recent edits.
267
+ export async function replaceText(root, relative, replacement, { key } = {}) {
268
+ validateReplacement(replacement);
269
+ if (!relative || relative === 'LIBRARY_SYNC_ACCESS') fail('INVALID', 'Supply a non-reserved file path');
270
+ return locked(root, async root => {
271
+ const target = await safePath(root, 'files/' + relative);
272
+ const receiptFile = await safePath(root, path.relative(root, operationPath(root, key)));
273
+ const request = { kind: 'replace', path: relative, before: replacement.before, after: replacement.after };
274
+ const old = await fs.readFile(receiptFile, 'utf8').then(JSON.parse).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
275
+ if (old && JSON.stringify(old) !== JSON.stringify(request)) fail('KEY_REUSED', 'Operation key belongs to a different replacement');
276
+ if (old) {
277
+ const observed = await replacementView(root, old);
278
+ if (observed.state === 'stored') return { ...observed, replay: true };
279
+ }
280
+ const before = await readText(target);
281
+ const at = uniquePosition(before.text, replacement.before);
282
+ if (at < 0) fail('CONFLICT', 'Expected text is absent or ambiguous; re-read the owning block');
283
+ const next = before.text.slice(0, at) + replacement.after + before.text.slice(at + replacement.before.length);
284
+ if (Buffer.byteLength(next) > MAX_TEXT_BYTES) fail('TOO_LARGE', 'Replacement exceeds the 8 MiB text limit');
285
+ if (uniquePosition(next, replacement.after) < 0) fail('CONFLICT', 'Resulting text is ambiguous; use a larger unique block');
286
+ const history = await safePath(root, 'history/' + before.sha256);
287
+ await fs.copyFile(target, history, constants.COPYFILE_EXCL).catch(error => { if (error.code !== 'EEXIST') throw error; });
288
+ await fs.chmod(history, 0o600);
289
+ await atomic(receiptFile, jsonBytes(request));
290
+ await atomic(target, next);
291
+ const after = await replacementView(root, request);
292
+ if (after.state !== 'stored' || after.sha256 !== hash(next)) fail('UNCERTAIN', 'Replacement readback differs; inspect operation before retry');
293
+ return { ...after, replay: false };
294
+ });
295
+ }
296
+
197
297
  export async function organize(root, { path: relative, to, expected, key }) {
198
298
  if (!/^[a-f0-9]{64}$/.test(expected || '')) fail('INVALID', 'Supply the current source SHA-256');
199
299
  if (relative === 'LIBRARY_SYNC_ACCESS' || to === 'LIBRARY_SYNC_ACCESS') fail('INVALID', 'The sync access marker is reserved');
@@ -24,7 +24,8 @@ while (!stopping) {
24
24
  const selected = await libraryRoot(root, name);
25
25
  const { config } = await syncStatus(selected);
26
26
  const mirror = (await mirrorStatus(selected)).config;
27
- if (config?.mode !== 'two-way' && (config || mirror?.mode !== 'one-way')) {
27
+ const enabled = config?.mode === 'two-way' || (config?.backend === 'git' && config.mode === 'pull-only');
28
+ if (!enabled && (config || mirror?.mode !== 'one-way')) {
28
29
  due.delete(name);
29
30
  if ((await embeddingStatus()).state === 'ready') await locked(selected, refreshIndex);
30
31
  continue;
package/src/sync.mjs CHANGED
@@ -132,10 +132,11 @@ export async function syncAdopt(root, remote, stateRoot = root) {
132
132
  }
133
133
 
134
134
  export async function syncPolicy(root, { expected, mode, intervalSeconds = 60 }) {
135
- if (!['paused', 'two-way'].includes(mode) || !Number.isInteger(intervalSeconds) || intervalSeconds < 30 || intervalSeconds > 3600) fail('INVALID', 'Use paused or two-way, and an interval from 30 to 3600 seconds');
135
+ if (!['paused', 'two-way', 'pull-only'].includes(mode) || !Number.isInteger(intervalSeconds) || intervalSeconds < 30 || intervalSeconds > 3600) fail('INVALID', 'Use paused, two-way or pull-only, and an interval from 30 to 3600 seconds');
136
136
  return locked(root, async root => {
137
137
  const current = await syncStatus(root);
138
138
  if (!current.config || current.revision !== expected) fail('CONFLICT', 'Read the current sync revision before changing policy');
139
+ if (mode === 'pull-only' && current.config.backend !== 'git') fail('INVALID', 'Pull-only sync requires a Git library');
139
140
  await atomic(location(root), jsonBytes({ ...current.config, mode, intervalSeconds }));
140
141
  return syncStatus(root);
141
142
  });
@@ -153,6 +154,7 @@ export async function syncRun(root, stateRoot = root) {
153
154
  try {
154
155
  if (config?.backend === 'git') status.git = await gitTransfer(root, config);
155
156
  else if (config) {
157
+ if (config.mode !== 'two-way') fail('INVALID', 'Folder sync requires two-way mode');
156
158
  if (await remoteIdentity(root, config.remote, stateRoot) !== config.identity) fail('CONFLICT', 'Mapped folder disappeared or changed identity; no automatic recreation');
157
159
  succeeded(await rclone(root, bisyncArgs(root, config)), 'Native bisync');
158
160
  }
@@ -0,0 +1,80 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import * as fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { randomBytes } from 'node:crypto';
7
+ import { Readable } from 'node:stream';
8
+ import { gunzipSync } from 'node:zlib';
9
+ import { spawnSync } from 'node:child_process';
10
+ import { gzipFile } from '../src/compress.mjs';
11
+ import { put, hash, operation, MAX_FILE_BYTES } from '../src/store.mjs';
12
+
13
+ async function fixture(t, data = Buffer.from('frozen evidence')) {
14
+ const root = await fs.mkdtemp(path.join(tmpdir(), 'library-gzip-'));
15
+ t.after(() => fs.rm(root, { recursive: true, force: true }));
16
+ await put(root, 'data/source.json', Readable.from([data]), { expected: 'new', key: 'source' });
17
+ return { root, data, request: { path: 'data/source.json', to: 'archive/source.json.gz', expected: hash(data), key: 'compress' } };
18
+ }
19
+
20
+ test('gzip keeps large binary data inside Library and records source/target proof', async t => {
21
+ const { root, data, request } = await fixture(t, randomBytes(2 * 1024 * 1024));
22
+ const result = await gzipFile(root, request);
23
+ const archive = await fs.readFile(path.join(root, 'files', request.to));
24
+ assert(archive.length > 1024 * 1024);
25
+ assert.deepEqual(gunzipSync(archive), data);
26
+ assert.equal(result.sha256, hash(archive));
27
+ assert.equal(result.source.sha256, hash(data));
28
+ assert.equal(result.source.bytes, data.length);
29
+ assert.equal(result.state, 'stored');
30
+ assert.equal((await fs.stat(path.join(root, 'files', request.to))).mode & 0o777, 0o600);
31
+ assert.deepEqual(await fs.readFile(path.join(root, 'files', request.path)), data);
32
+ assert.equal((await operation(root, request.key)).state, 'stored');
33
+ assert.equal((await gzipFile(root, request)).replay, true);
34
+ // Reconcile interruption after receipt installation, before destination rename.
35
+ await fs.unlink(path.join(root, 'files', request.to));
36
+ assert.equal((await operation(root, request.key)).state, 'missing');
37
+ assert.equal((await gzipFile(root, request)).state, 'stored');
38
+ assert.deepEqual(await fs.readFile(path.join(root, 'files', request.to)), archive);
39
+ });
40
+
41
+ test('gzip fails closed on stale source, occupied target, reused key and writer contention', async t => {
42
+ const { root, request } = await fixture(t);
43
+ await assert.rejects(gzipFile(root, { ...request, expected: '0'.repeat(64) }), { code: 'CONFLICT' });
44
+ await assert.rejects(fs.stat(path.join(root, 'files', request.to)), { code: 'ENOENT' });
45
+ await assert.rejects(operation(root, request.key), { code: 'ENOENT' });
46
+ await gzipFile(root, request);
47
+ await assert.rejects(gzipFile(root, { ...request, key: 'new-key' }), { code: 'CONFLICT' });
48
+ await assert.rejects(gzipFile(root, { ...request, to: 'another.gz' }), { code: 'KEY_REUSED' });
49
+ await fs.mkdir(path.join(root, '.writer-lock'));
50
+ await assert.rejects(gzipFile(root, request), { code: 'BUSY' });
51
+ await fs.rmdir(path.join(root, '.writer-lock'));
52
+ await fs.writeFile(path.join(root, 'files', request.path), 'changed');
53
+ await assert.rejects(gzipFile(root, request), { code: 'CONFLICT' });
54
+ });
55
+
56
+ test('gzip rejects traversal, symlinks, oversized sources and ambiguous destinations', async t => {
57
+ const { root, request } = await fixture(t);
58
+ for (const invalid of [{ expected: 'new' }, { to: request.path }, { to: 'no-gzip' }, { path: '' }]) {
59
+ await assert.rejects(gzipFile(root, { ...request, ...invalid }), { code: 'INVALID' });
60
+ }
61
+ await assert.rejects(gzipFile(root, { ...request, path: '../outside' }), { code: 'UNSAFE_PATH' });
62
+ await assert.rejects(gzipFile(root, { ...request, to: '../outside.gz' }), { code: 'UNSAFE_PATH' });
63
+ await fs.symlink(path.join(root, 'files', request.path), path.join(root, 'files', 'link'));
64
+ await assert.rejects(gzipFile(root, { ...request, path: 'link' }), { code: 'UNSAFE_PATH' });
65
+ await fs.symlink(path.join(root, 'files', request.path), path.join(root, 'files', 'link.gz'));
66
+ await assert.rejects(gzipFile(root, { ...request, to: 'link.gz' }), { code: 'UNSAFE_PATH' });
67
+ await fs.truncate(path.join(root, 'files', request.path), MAX_FILE_BYTES + 1);
68
+ await assert.rejects(gzipFile(root, request), { code: 'TOO_LARGE' });
69
+ });
70
+
71
+ test('gzip CLI needs no payload stdin and local help needs no state', async t => {
72
+ const { root, request, data } = await fixture(t);
73
+ const cli = new URL('../bin/ez-library.mjs', import.meta.url).pathname;
74
+ const run = spawnSync(process.execPath, [cli, 'gzip', '--path', request.path, '--to', request.to,
75
+ '--expected', request.expected, '--key', request.key], { env: { ...process.env, EZ_LIBRARY_STATE: root }, encoding: 'utf8' });
76
+ assert.equal(run.status, 0, run.stderr);
77
+ assert.equal(JSON.parse(run.stdout).data.source.sha256, hash(data));
78
+ const help = spawnSync(process.execPath, [cli, 'gzip', '--help'], { env: { ...process.env, EZ_LIBRARY_STATE: '/does-not-exist' }, encoding: 'utf8' });
79
+ assert.equal(help.status, 0); assert.match(help.stdout, /gzip --path/);
80
+ });
@@ -38,6 +38,21 @@ test('text mirror versions notes and renames while excluding attachment bytes an
38
38
  await mirrorPolicy(root, current.revision, 'paused');
39
39
  assert.equal((await cycle()).state, 'paused');
40
40
  });
41
+ test('unchanged mirror cycles keep projection files and remote head untouched', async t => {
42
+ const { root, remote, git, cycle } = await fixture(t);
43
+ await put(root, 'note.md', Readable.from(['original']), { expected: 'new', key: 'note' });
44
+ await mirrorAdopt(root, remote);
45
+ const first = await cycle(), projected = path.join(root, 'sync/text-mirror/files/note.md');
46
+ const before = await fs.stat(projected);
47
+ assert.equal((await cycle()).commit, first.commit);
48
+ const after = await fs.stat(projected);
49
+ assert.deepEqual([after.ino, after.mtimeMs], [before.ino, before.mtimeMs]);
50
+ assert.equal(git(['--git-dir', remote, 'rev-parse', 'main']).trim(), first.commit);
51
+ await fs.writeFile(path.join(root, 'files/note.md'), 'edited');
52
+ const second = await cycle();
53
+ assert.notEqual(second.commit, first.commit);
54
+ assert.equal(git(['--git-dir', remote, 'show', 'main:note.md']), 'edited');
55
+ });
41
56
  test('outside GitHub edits stop mirroring without changing Drive originals or dropping remote history', async t => {
42
57
  const { root, remote, base, git, cycle } = await fixture(t);
43
58
  await put(root, 'note.md', Readable.from(['original']), { expected: 'new', key: 'note' });
@@ -7,6 +7,7 @@ import { execFileSync } from 'node:child_process';
7
7
  import { Readable } from 'node:stream';
8
8
  import { gitAdopt, gitTransfer, git, repositoryURL } from '../src/git-sync.mjs';
9
9
  import { locked, put, digest, organize, jsonBytes } from '../src/store.mjs';
10
+ import { syncPolicy, syncStatus } from '../src/sync.mjs';
10
11
 
11
12
  async function setup(t) {
12
13
  const base = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), 'library-git-')));
@@ -25,6 +26,87 @@ async function setup(t) {
25
26
  }
26
27
  const cycle = (root, config) => locked(root, () => gitTransfer(root, config));
27
28
 
29
+ test('pull-only imports additions, renames and deletions without a push or local commit', async t => {
30
+ const { root, remote, external, outside, publish } = await setup(t);
31
+ const { config } = await gitAdopt(root, remote, 'main', root, false, 'pull-only');
32
+ // Any push, even one with no changed refs, would fail against this URL.
33
+ await git(root, config, ['remote', 'set-url', '--push', 'origin', remote + '-forbidden']);
34
+ await fs.writeFile(path.join(external, 'incoming.md'), 'Remote-only violet telescope');
35
+ await fs.rename(path.join(external, 'note0.md'), path.join(external, 'renamed.md'));
36
+ await fs.unlink(path.join(external, 'note1.md')); publish();
37
+ const expected = outside(['--git-dir', remote, 'rev-parse', 'main']).trim();
38
+ const result = await cycle(root, config);
39
+ assert.equal(result.commit, expected);
40
+ assert.equal(result.remoteVerified, true);
41
+ assert.match(await fs.readFile(path.join(root, 'files/incoming.md'), 'utf8'), /violet/);
42
+ assert.match(await fs.readFile(path.join(root, 'files/renamed.md'), 'utf8'), /Note 0/);
43
+ await assert.rejects(fs.stat(path.join(root, 'files/note1.md')), { code: 'ENOENT' });
44
+ assert.equal((await cycle(root, config)).commit, expected);
45
+ assert.equal(outside(['--git-dir', remote, 'rev-parse', 'main']).trim(), expected);
46
+ });
47
+
48
+ test('pull-only preserves local edits, staged work and untracked files without committing them', async t => {
49
+ for (const kind of ['edited', 'staged', 'untracked']) {
50
+ const { root, remote, outside } = await setup(t);
51
+ const { config } = await gitAdopt(root, remote, 'main', root, false, 'pull-only');
52
+ const original = outside(['--git-dir', remote, 'rev-parse', 'main']).trim();
53
+ const name = kind === 'untracked' ? 'local.md' : 'note0.md';
54
+ await fs.writeFile(path.join(root, 'files', name), 'Preserve local ' + kind);
55
+ if (kind === 'staged') await git(root, config, ['add', '--', name]);
56
+ await assert.rejects(cycle(root, config), { code: 'CONFLICT' });
57
+ assert.equal(await fs.readFile(path.join(root, 'files', name), 'utf8'), 'Preserve local ' + kind);
58
+ assert.equal((await git(root, config, ['rev-parse', 'HEAD'])).stdout.trim(), original);
59
+ assert.equal(outside(['--git-dir', remote, 'rev-parse', 'main']).trim(), original);
60
+ if (kind === 'staged') assert.match((await git(root, config, ['show', ':' + name])).stdout, /Preserve local staged/);
61
+ }
62
+ });
63
+
64
+ test('pull-only rejects ahead and divergent local history without resetting or merging', async t => {
65
+ for (const diverged of [false, true]) {
66
+ const { root, remote, external, outside, publish } = await setup(t);
67
+ const { config } = await gitAdopt(root, remote, 'main', root, false, 'pull-only');
68
+ await fs.writeFile(path.join(root, 'files/local.md'), 'Preserve local commit');
69
+ await git(root, config, ['add', '--', 'local.md']);
70
+ await git(root, config, ['commit', '-m', 'Local work']);
71
+ const head = (await git(root, config, ['rev-parse', 'HEAD'])).stdout.trim();
72
+ if (diverged) { await fs.writeFile(path.join(external, 'remote.md'), 'External work'); publish(); }
73
+ const remoteHead = outside(['--git-dir', remote, 'rev-parse', 'main']).trim();
74
+ await assert.rejects(cycle(root, config), { code: 'CONFLICT' });
75
+ assert.equal((await git(root, config, ['rev-parse', 'HEAD'])).stdout.trim(), head);
76
+ assert.equal(outside(['--git-dir', remote, 'rev-parse', 'main']).trim(), remoteHead);
77
+ assert.equal((await git(root, config, ['rev-parse', '--verify', 'MERGE_HEAD'])).code, 128);
78
+ }
79
+ });
80
+
81
+ test('an existing two-way Git binding can switch to revision-guarded pull-only sync', async t => {
82
+ const { root, remote } = await setup(t);
83
+ await gitAdopt(root, remote);
84
+ const before = await syncStatus(root);
85
+ const after = await syncPolicy(root, { expected: before.revision, mode: 'pull-only', intervalSeconds: 30 });
86
+ assert.equal(after.config.mode, 'pull-only');
87
+ await cycle(root, after.config);
88
+ await assert.rejects(syncPolicy(root, { expected: before.revision, mode: 'two-way' }), { code: 'CONFLICT' });
89
+ });
90
+
91
+ test('pull-only adoption preserves and refuses extra local originals', async t => {
92
+ const { root, remote } = await setup(t);
93
+ await put(root, 'local.md', Readable.from(['Keep this original']), { expected: 'new', key: 'local' });
94
+ await assert.rejects(gitAdopt(root, remote, 'main', root, false, 'pull-only'), { code: 'CONFLICT' });
95
+ assert.equal(await fs.readFile(path.join(root, 'files/local.md'), 'utf8'), 'Keep this original');
96
+ assert.equal((await syncStatus(root)).config.mode, 'paused');
97
+ });
98
+
99
+ test('pull-only advances an explicitly adopted existing checkout without creating commits', async t => {
100
+ const { root, remote, external, outside, publish } = await setup(t);
101
+ await fs.mkdir(root); outside(['clone', remote, path.join(root, 'files')]);
102
+ const { config } = await gitAdopt(root, remote, 'main', root, true, 'pull-only');
103
+ await fs.writeFile(path.join(external, 'incoming.md'), 'External checkout update'); publish();
104
+ const expected = outside(['--git-dir', remote, 'rev-parse', 'main']).trim();
105
+ assert.equal((await cycle(root, config)).commit, expected);
106
+ assert.equal(outside(['-C', path.join(root, 'files'), 'rev-parse', 'HEAD']).trim(), expected);
107
+ assert.equal(outside(['-C', path.join(root, 'files'), 'rev-parse', 'origin/main']).trim(), expected);
108
+ });
109
+
28
110
  test('native Git adopts originals, imports external changes, exports agent changes and verifies commit', async t => {
29
111
  const { root, remote, external, outside, publish } = await setup(t);
30
112
  const { config } = await gitAdopt(root, remote);
@@ -71,3 +71,19 @@ test('per-library indexing policy controls native QMD embedding with explicit sh
71
71
  } finally { await fs.rm(base, { recursive: true, force: true }); }
72
72
  `], { cwd: new URL('..', import.meta.url), stdio: 'pipe' });
73
73
  });
74
+
75
+ test('scan digests are reused per process but never hide same-size rewrites with a restored mtime', async t => {
76
+ const fs = await import('node:fs/promises'), path = (await import('node:path')).default, { tmpdir } = await import('node:os');
77
+ const { setTimeout } = await import('node:timers/promises'), assert = (await import('node:assert/strict')).default;
78
+ const { scanDigest, hash } = await import('../src/store.mjs');
79
+ const base = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), 'library-scan-')));
80
+ t.after(() => fs.rm(base, { recursive: true, force: true }));
81
+ const file = path.join(base, 'note.md');
82
+ await fs.writeFile(file, 'first');
83
+ const { mtime } = await fs.stat(file);
84
+ await setTimeout(2100);
85
+ assert.deepEqual(await scanDigest(file), { bytes: 5, sha256: hash('first') });
86
+ assert.deepEqual(await scanDigest(file), { bytes: 5, sha256: hash('first') });
87
+ await fs.writeFile(file, 'other'); await fs.utimes(file, mtime, mtime);
88
+ assert.deepEqual(await scanDigest(file), { bytes: 5, sha256: hash('other') });
89
+ });
@@ -212,3 +212,12 @@ test('PDF extraction rejects traversal, symlinks, directories and missing paths
212
212
  const result = spawnSync(process.execPath, [cli, 'pdf-text'], { env: { ...process.env, EZ_LIBRARY_STATE: root }, encoding: 'utf8' });
213
213
  assert.equal(result.status, 2); assert.match(result.stderr, /Supply --path/);
214
214
  });
215
+
216
+ test('local subcommand help succeeds before configuration or write intake',async t=>{
217
+ const root=await fixture(t);
218
+ for(const command of ['put','get','sources','sync-run']) {
219
+ const result=spawnSync(process.execPath,[cli,command,'--library','absent','--help'],{env:{...process.env,EZ_LIBRARY_STATE:root},input:'must not write',encoding:'utf8'});
220
+ assert.equal(result.status,0,result.stderr);assert.match(result.stdout,/put --path/);
221
+ }
222
+ assert.deepEqual(await fs.readdir(root),[]);
223
+ });
@@ -0,0 +1,90 @@
1
+ import { test } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import * as fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { Readable } from 'node:stream';
7
+ import { spawnSync } from 'node:child_process';
8
+ import { put, replaceText, operation, hash, MAX_REPLACE_BYTES } from '../src/store.mjs';
9
+
10
+ const initial = '# Day\r\n\r\n## A\r\nstarted 🛰\r\n\r\n## B\r\nstarted\r\n';
11
+ const a = { before: '## A\r\nstarted 🛰\r\n', after: '## A\r\ncompleted 🛰\r\n' };
12
+ const b = { before: '## B\r\nstarted\r\n', after: '## B\r\ncompleted\r\n' };
13
+ async function fixture(t, data = initial) {
14
+ const root = await fs.mkdtemp(path.join(tmpdir(), 'library-replace-'));
15
+ t.after(() => fs.rm(root, { recursive: true, force: true }));
16
+ await put(root, 'runs/day.md', Readable.from([Buffer.from(data)]), { expected: 'new', key: 'initial' });
17
+ return root;
18
+ }
19
+ const read = root => fs.readFile(path.join(root, 'files/runs/day.md'), 'utf8');
20
+
21
+ test('scoped replacements preserve interleaved writers, exact bytes and replay', async t => {
22
+ const root = await fixture(t);
23
+ const first = await replaceText(root, 'runs/day.md', a, { key: 'a' });
24
+ await replaceText(root, 'runs/day.md', b, { key: 'b' });
25
+ const expected = initial.replace(a.before, a.after).replace(b.before, b.after);
26
+ assert.equal(await read(root), expected);
27
+ assert.equal((await operation(root, 'a')).state, 'stored');
28
+ assert.notEqual((await operation(root, 'a')).sha256, first.sha256);
29
+ assert.equal((await replaceText(root, 'runs/day.md', a, { key: 'a' })).replay, true);
30
+ assert.equal(await read(root), expected);
31
+ assert.equal(await fs.readFile(path.join(root, 'history', hash(initial)), 'utf8'), initial);
32
+ assert.equal((await fs.stat(path.join(root, 'files/runs/day.md'))).mode & 0o777, 0o600);
33
+ assert.equal('before' in await operation(root, 'a'), false);
34
+ // A changed owning block does not become a stale overwrite on replay.
35
+ await replaceText(root, 'runs/day.md', { before: a.after, after: a.after + 'new progress\r\n' }, { key: 'a2' });
36
+ assert.equal((await operation(root, 'a')).state, 'stored'); // old completed text remains present
37
+ });
38
+
39
+ test('same-block conflict, ambiguity and reused keys do not rewrite a file', async t => {
40
+ const root = await fixture(t);
41
+ await replaceText(root, 'runs/day.md', a, { key: 'a' });
42
+ await assert.rejects(replaceText(root, 'runs/day.md', { ...a, after: 'different' }, { key: 'other' }), { code: 'CONFLICT' });
43
+ await assert.rejects(replaceText(root, 'runs/day.md', b, { key: 'a' }), { code: 'KEY_REUSED' });
44
+ const before = await read(root);
45
+ await assert.rejects(replaceText(root, 'runs/day.md', { before: '## ', after: 'new' }, { key: 'ambiguous' }), { code: 'CONFLICT' });
46
+ await assert.rejects(replaceText(root, 'runs/day.md', { before: b.before, after: a.after }, { key: 'duplicate-after' }), { code: 'CONFLICT' });
47
+ assert.equal(await read(root), before);
48
+ await assert.rejects(operation(root, 'ambiguous'), { code: 'ENOENT' });
49
+ });
50
+
51
+ test('interrupted receipt reconciles against current unrelated edits', async t => {
52
+ const root = await fixture(t);
53
+ await replaceText(root, 'runs/day.md', a, { key: 'a' });
54
+ // Model a durable intent with its destination not yet installed.
55
+ await fs.writeFile(path.join(root, 'files/runs/day.md'), initial.replace(b.before, b.after));
56
+ assert.equal((await operation(root, 'a')).state, 'changed');
57
+ const result = await replaceText(root, 'runs/day.md', a, { key: 'a' });
58
+ assert.equal(result.state, 'stored');
59
+ assert.equal(await read(root), initial.replace(a.before, a.after).replace(b.before, b.after));
60
+ });
61
+
62
+ test('replacement rejects unsafe input, source, contention and size', async t => {
63
+ const root = await fixture(t);
64
+ for (const value of [null, { before: '', after: 'a' }, { before: 'a', after: '' }, { before: 'a', after: 'a' },
65
+ { ...a, extra: true }, { before: '\ud800', after: 'x' }, { before: 'x', after: 'y'.repeat(MAX_REPLACE_BYTES) }]) {
66
+ await assert.rejects(replaceText(root, 'runs/day.md', value, { key: 'bad' }), { code: 'INVALID' });
67
+ }
68
+ await assert.rejects(replaceText(root, '../outside', a, { key: 'bad' }), { code: 'UNSAFE_PATH' });
69
+ await fs.symlink(path.join(root, 'files/runs/day.md'), path.join(root, 'files/link'));
70
+ await assert.rejects(replaceText(root, 'link', a, { key: 'bad' }), { code: 'UNSAFE_PATH' });
71
+ await fs.mkdir(path.join(root, '.writer-lock'));
72
+ await assert.rejects(replaceText(root, 'runs/day.md', a, { key: 'bad' }), { code: 'BUSY' });
73
+ await fs.rmdir(path.join(root, '.writer-lock'));
74
+ await fs.writeFile(path.join(root, 'files/runs/day.md'), Buffer.from([255]));
75
+ await assert.rejects(replaceText(root, 'runs/day.md', a, { key: 'bad' }), { code: 'INVALID' });
76
+ await fs.truncate(path.join(root, 'files/runs/day.md'), 8 * 1024 * 1024 + 1);
77
+ await assert.rejects(replaceText(root, 'runs/day.md', a, { key: 'bad' }), { code: 'TOO_LARGE' });
78
+ });
79
+
80
+ test('replace CLI uses bounded JSON, not shell or regex interpretation', async t => {
81
+ const root = await fixture(t);
82
+ const cli = new URL('../bin/ez-library.mjs', import.meta.url).pathname;
83
+ const run = input => spawnSync(process.execPath, [cli, 'replace', '--path', 'runs/day.md', '--key', 'cli'],
84
+ { input, env: { ...process.env, EZ_LIBRARY_STATE: root }, encoding: 'utf8' });
85
+ const result = run(JSON.stringify(a));
86
+ assert.equal(result.status, 0, result.stderr); assert.equal(JSON.parse(result.stdout).data.state, 'stored');
87
+ assert.equal(run('{').status, 2);
88
+ assert.equal(run(Buffer.from([255])).status, 2);
89
+ assert.equal(run(' '.repeat(MAX_REPLACE_BYTES + 1)).status, 2);
90
+ });
@@ -78,6 +78,18 @@ test('sync is inert without binding; policy revisions and remote paths are guard
78
78
  assert.equal(environment(root).RCLONE_CONFIG, path.join(root, 'sync/rclone.conf'));
79
79
  });
80
80
 
81
+ test('pull-only cannot enable two-way transfers on a non-Git folder binding', async t => {
82
+ const { root, remote } = await fixture(t);
83
+ await fs.mkdir(path.join(root, 'sync'), { recursive: true });
84
+ await fs.writeFile(path.join(root, 'sync/config.json'), JSON.stringify({ schemaVersion: 1, remote, mode: 'two-way', intervalSeconds: 60 }));
85
+ const before = await syncStatus(root);
86
+ await assert.rejects(syncPolicy(root, { expected: before.revision, mode: 'pull-only' }), { code: 'INVALID' });
87
+ assert.equal((await syncStatus(root)).config.mode, 'two-way');
88
+ await fs.writeFile(path.join(root, 'sync/config.json'), JSON.stringify({ ...before.config, mode: 'pull-only' }));
89
+ await assert.rejects(syncRun(root), { code: 'INVALID' });
90
+ assert.equal((await syncStatus(root)).status.state, 'sync-error');
91
+ });
92
+
81
93
  test('native adoption preserves a populated folder, empty files and directories; conflicts stop adoption', { skip: !nativeAvailable }, async t => {
82
94
  const { root, remote } = await fixture(t);
83
95
  await fs.mkdir(path.join(remote, 'empty-dir'));