@jc_stack/ez-library 0.1.0-beta.16 → 0.1.0-beta.19
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 +2 -0
- package/CHANGELOG.md +21 -0
- package/CONTRIBUTING.md +1 -1
- package/Dockerfile +2 -2
- package/README.md +37 -3
- package/docs/github-sync.md +12 -4
- package/docs/releasing.md +1 -1
- package/ez-plugin.json +2 -1
- package/package.json +3 -2
- package/pnpm-workspace.yaml +7 -0
- package/skills/library/SKILL.md +29 -1
- package/src/cli.mjs +27 -7
- package/src/compress.mjs +47 -0
- package/src/git-mirror.mjs +15 -7
- package/src/git-sync.mjs +46 -19
- package/src/indexer.mjs +3 -3
- package/src/store.mjs +141 -13
- package/src/sync-worker.mjs +4 -3
- package/src/sync.mjs +5 -3
- package/test/compress.test.mjs +80 -0
- package/test/git-mirror.test.mjs +15 -0
- package/test/git-sync.test.mjs +82 -0
- package/test/indexer.test.mjs +16 -0
- package/test/library.test.mjs +31 -1
- package/test/replace.test.mjs +90 -0
- package/test/sync.test.mjs +12 -0
package/.dockerignore
CHANGED
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,26 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.0-beta.19
|
|
4
|
+
|
|
5
|
+
- Writers wait up to 60 seconds for a live holder of the Library writer lock (named in its `owner` file) instead of failing `BUSY` at once, so concurrent agent writes and the resident sync no longer fail on a brief overlap. A lock without an owner still fails closed after a one-second grace; a lock held by the same process fails at once; the resident worker stops waiting when told to stop.
|
|
6
|
+
- Requires Ez core 0.1.0-beta.50 or newer (unchanged).
|
|
7
|
+
|
|
8
|
+
## 0.1.0-beta.18
|
|
9
|
+
|
|
10
|
+
- 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.
|
|
11
|
+
- 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.
|
|
12
|
+
- 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.
|
|
13
|
+
- Reconcile existing checkout tracking refs with native Git's fetch/push updates, retaining the revision guard for unexpected changes.
|
|
14
|
+
- Includes the beta.17 scope below, which was never published to npm.
|
|
15
|
+
|
|
16
|
+
## 0.1.0-beta.17
|
|
17
|
+
|
|
18
|
+
- Add guarded in-Library gzip and scoped literal section/text updates, preserving originals, revision guards, operation receipts and the single writer.
|
|
19
|
+
- Retain the beta.16 Dockerfile and shared embedding implementation so existing shared-worker deployments remain compatible. The container build-policy upgrade remains separate.
|
|
20
|
+
- Add a representative manifest example for tool discovery; state and deployment schemas remain unchanged.
|
|
21
|
+
- Requires Ez core 0.1.0-beta.50 or newer for the manifest example.
|
|
22
|
+
Older cores refuse the update and retain the installed version.
|
|
23
|
+
|
|
3
24
|
## 0.1.0-beta.16
|
|
4
25
|
|
|
5
26
|
- 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`, `
|
|
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.
|
|
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.
|
|
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
|
|
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
|
|
@@ -122,17 +153,20 @@ The named `data` volume contains `/state/files`, `settings.json`, `operations`,
|
|
|
122
153
|
|
|
123
154
|
Stop the plugin before an operator takes a volume snapshot using an existing backup tool. Preserve originals, settings, receipts and history together. QMD indexes/models are rebuildable. Uninstall removes the deployment and registry binding but preserves volumes. Account revocation is a separate action in the provider's plugin/account. See [release and rollback practices](docs/releasing.md).
|
|
124
155
|
|
|
125
|
-
An interrupted command may leave `/state/.writer-lock`, or QMD's own embed lock below `/state/qmd/cache/qmd`. Confirm no Library client/embedding command is active before removing only the stale lock. Never delete the index or originals as a lock workaround. Run `operation` to reconcile an interrupted file write. Concurrent writes directly to `/state/files` are unsupported. Edit the mapped external folder instead, or use guarded Library commands.
|
|
156
|
+
Library writers take `/state/.writer-lock` in turn: a command waits up to 60 seconds for a live writer (named in the lock's `owner` file) before returning `BUSY`, and a lock without an owner returns `BUSY` after a one-second grace. An interrupted command may leave `/state/.writer-lock`, or QMD's own embed lock below `/state/qmd/cache/qmd`. Confirm no Library client/embedding command is active before removing only the stale lock. Never delete the index or originals as a lock workaround. Run `operation` to reconcile an interrupted file write. Concurrent writes directly to `/state/files` are unsupported. Edit the mapped external folder instead, or use guarded Library commands.
|
|
126
157
|
|
|
127
158
|
## Development
|
|
128
159
|
|
|
129
160
|
```sh
|
|
130
161
|
pnpm install --frozen-lockfile
|
|
131
162
|
pnpm verify
|
|
132
|
-
|
|
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.
|
package/docs/github-sync.md
CHANGED
|
@@ -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
|
|
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
|
|
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`, `
|
|
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.
|
|
4
|
+
"version": "0.1.0-beta.19",
|
|
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.
|
|
3
|
+
"version": "0.1.0-beta.19",
|
|
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",
|
package/skills/library/SKILL.md
CHANGED
|
@@ -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
|
|
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
|
|
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; }
|
package/src/compress.mjs
ADDED
|
@@ -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
|
+
}
|
package/src/git-mirror.mjs
CHANGED
|
@@ -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
|
-
|
|
139
|
-
|
|
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
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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
|
-
|
|
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)
|
|
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
|
}
|