@jc_stack/ez-library 0.1.0-beta.12

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.
Files changed (52) hide show
  1. package/.dockerignore +12 -0
  2. package/.github/workflows/publish-beta.yml +40 -0
  3. package/CHANGELOG.md +57 -0
  4. package/CONTRIBUTING.md +89 -0
  5. package/Dockerfile +38 -0
  6. package/LICENSE +21 -0
  7. package/README.md +119 -0
  8. package/SECURITY.md +13 -0
  9. package/THIRD_PARTY_NOTICES.md +9 -0
  10. package/bin/ez-library.mjs +3 -0
  11. package/docker/fulltext-smoke.mjs +19 -0
  12. package/docker/github-smoke.mjs +114 -0
  13. package/docker/manager-smoke.mjs +53 -0
  14. package/docker/pnpm-lock.yaml +1443 -0
  15. package/docker/shared-smoke.mjs +81 -0
  16. package/docker/smoke.mjs +73 -0
  17. package/docker/sync-smoke.mjs +98 -0
  18. package/docker/text-mirror-smoke.mjs +42 -0
  19. package/docs/folder-sync.md +100 -0
  20. package/docs/github-sync.md +105 -0
  21. package/docs/named-libraries.md +75 -0
  22. package/docs/persistence.md +48 -0
  23. package/docs/rclone-LICENSE.txt +19 -0
  24. package/docs/releasing.md +74 -0
  25. package/docs/shared-embeddings.md +15 -0
  26. package/docs/text-mirror.md +54 -0
  27. package/ez-deployment.json +53 -0
  28. package/ez-plugin.json +15 -0
  29. package/package.json +69 -0
  30. package/patches/@tobilu__qmd@2.8.3.patch +60 -0
  31. package/scripts/publish-settings.mjs +101 -0
  32. package/scripts/release-check.mjs +16 -0
  33. package/skills/library/SKILL.md +104 -0
  34. package/src/cli.mjs +227 -0
  35. package/src/embedding-client.mjs +50 -0
  36. package/src/embedding-worker.mjs +59 -0
  37. package/src/git-mirror.mjs +121 -0
  38. package/src/git-sync.mjs +140 -0
  39. package/src/indexer.mjs +83 -0
  40. package/src/libraries.mjs +81 -0
  41. package/src/native.mjs +47 -0
  42. package/src/store.mjs +214 -0
  43. package/src/sync-worker.mjs +43 -0
  44. package/src/sync.mjs +172 -0
  45. package/test/embeddings.test.mjs +30 -0
  46. package/test/git-mirror.test.mjs +121 -0
  47. package/test/git-sync.test.mjs +135 -0
  48. package/test/indexer.test.mjs +73 -0
  49. package/test/libraries.test.mjs +132 -0
  50. package/test/library.test.mjs +163 -0
  51. package/test/publish-settings.test.mjs +101 -0
  52. package/test/sync.test.mjs +120 -0
package/src/sync.mjs ADDED
@@ -0,0 +1,172 @@
1
+ import * as fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { atomic, fail, hash, jsonBytes, locked, safePath } from './store.mjs';
4
+ import { inventory, refreshIndex } from './indexer.mjs';
5
+ import { rclone, succeeded } from './native.mjs';
6
+ import { mirrorTransfer, mirrorStatus } from './git-mirror.mjs';
7
+ import { gitTransfer } from './git-sync.mjs';
8
+
9
+ const marker = 'LIBRARY_SYNC_ACCESS';
10
+ const filters = '- .*\n- .*/**\n';
11
+ const common = ['--drive-skip-gdocs', '--drive-skip-shortcuts', '--retries', '1', '--contimeout', '15s', '--timeout', '60s'];
12
+ const readJSON = async file => {
13
+ const root = path.dirname(path.dirname(file));
14
+ await safePath(root, path.relative(root, file));
15
+ return fs.readFile(file, 'utf8').then(JSON.parse).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
16
+ };
17
+ const location = root => path.join(root, 'sync/config.json');
18
+
19
+ async function prepare(root) {
20
+ for (const dir of ['sync', 'sync/bisync', 'sync/history']) {
21
+ await fs.mkdir(path.join(root, dir), { recursive: true, mode: 0o700 });
22
+ if ((await fs.lstat(path.join(root, dir))).isSymbolicLink()) fail('UNSAFE_PATH', 'Sync directories cannot be symlinks');
23
+ }
24
+ const file = path.join(root, 'sync/filters');
25
+ try { await fs.writeFile(file, filters, { flag: 'wx', mode: 0o600 }); }
26
+ catch (e) { if (e.code !== 'EEXIST') throw e; }
27
+ }
28
+
29
+ async function remoteIdentity(root, remote, stateRoot = root) {
30
+ if (typeof remote !== 'string' || !remote || /[\x00-\x1f\\]/.test(remote)) fail('INVALID', 'Supply a native rclone remote:path or absolute folder');
31
+ if (path.isAbsolute(remote)) {
32
+ const real = await fs.realpath(remote);
33
+ stateRoot = await fs.realpath(stateRoot);
34
+ if (real !== remote || real === stateRoot || real.startsWith(stateRoot + '/') || stateRoot.startsWith(real + '/')) fail('UNSAFE_PATH', 'Sync folder must be real and outside Library state');
35
+ const stat = await fs.lstat(real);
36
+ if (!stat.isDirectory()) fail('UNSAFE_PATH', 'Expected an existing folder');
37
+ return `local:${stat.dev}:${stat.ino}`;
38
+ }
39
+ if (!/^[A-Za-z][A-Za-z0-9_-]*:[^:]+$/.test(remote) || remote.split(':')[1].split('/').some(p => !p || p.startsWith('.'))) fail('INVALID', 'Use a named remote and a non-hidden folder path, without inline options');
40
+ const name = remote.split(':')[0];
41
+ // Inspect native configuration in memory only. Do not expose tokens, accept
42
+ // aliases, or resolve a Drive root ID that could hide a trashed ancestor.
43
+ const profile = JSON.parse(succeeded(await rclone(root, ['config', 'dump']), 'Native connection inspection'))[name];
44
+ if (!profile || !['drive', 'dropbox'].includes(profile.type)) fail('INVALID', 'This binding supports native Drive or Dropbox profiles');
45
+ if (profile.root_folder_id || profile.trashed_only === 'true' || profile.team_drive) fail('INVALID', 'Use an account-root profile and the visible folder path; rooted/shared-drive profiles require separate validation');
46
+ // A backend-root stat can be synthetic and omit its ID (notably Drive).
47
+ // Resolve every component from its parent, also rejecting ambiguous ancestors.
48
+ let parent = name + ':', stat;
49
+ for (const part of remote.slice(parent.length).split('/')) {
50
+ const entries = JSON.parse(succeeded(await rclone(root, ['lsjson', parent, '--dirs-only', ...common]), 'Folder identity'));
51
+ const matches = entries.filter(entry => entry.IsDir && entry.Path === part);
52
+ if (matches.length !== 1 || !matches[0].ID) fail('CONFLICT', 'Mapped folder is missing, ambiguous, or has no provider identity');
53
+ stat = matches[0];
54
+ parent += (parent.endsWith(':') ? '' : '/') + part;
55
+ }
56
+ return `${profile.type}:${stat.ID}`;
57
+ }
58
+
59
+ async function inspect(root, remote, stateRoot) {
60
+ const identity = await remoteIdentity(root, remote, stateRoot);
61
+ const entries = JSON.parse(succeeded(await rclone(root, ['lsjson', remote, '--recursive', '--hash', '--exclude', '.*', '--exclude', '.*/**', ...common]), 'Folder inventory'));
62
+ const seen = new Set();
63
+ for (const file of entries) {
64
+ await safePath(root, 'files/' + file.Path + (file.IsDir ? '/path-check' : ''));
65
+ if (seen.has(file.Path)) fail('CONFLICT', 'Duplicate provider paths must be resolved before adoption');
66
+ seen.add(file.Path);
67
+ }
68
+ return { remote, identity, files: entries.filter(file => !file.IsDir) };
69
+ }
70
+
71
+ export async function syncStatus(root) {
72
+ const config = await readJSON(location(root));
73
+ return { config, revision: config ? hash(jsonBytes(config)) : null,
74
+ status: await readJSON(path.join(root, 'sync/status.json')),
75
+ textMirror: await mirrorStatus(root),
76
+ index: await readJSON(path.join(root, 'sync/index.json')) };
77
+ }
78
+
79
+ export async function syncPlan(root, remote, stateRoot = root) {
80
+ return locked(root, async root => {
81
+ await prepare(root);
82
+ const plan = await inspect(root, remote, stateRoot);
83
+ const local = await inventory(path.join(root, 'files'));
84
+ const check = local.length ? await rclone(root, ['check', path.join(root, 'files'), remote, '--one-way', '--download', '--exclude', marker, ...common]) : { code: 0 };
85
+ return { remote, identity: plan.identity, remoteFiles: plan.files.length, localFiles: local.length,
86
+ localMatchesRemote: check.code === 0, policy: 'two-way', intervalSeconds: 60,
87
+ excluded: ['hidden files/directories', 'Google-native documents', 'Drive shortcuts'],
88
+ ready: check.code === 0, note: 'Adoption requires every existing local file to match the selected folder. Conflicts stop adoption.' };
89
+ });
90
+ }
91
+
92
+ function bisyncArgs(root, config, initial = false) {
93
+ return ['bisync', path.join(root, 'files'), config.remote,
94
+ '--workdir', path.join(root, 'sync/bisync'), '--filters-file', path.join(root, 'sync/filters'),
95
+ '--check-access', '--check-filename', marker, '--compare', 'size,modtime,checksum',
96
+ '--conflict-resolve', 'none', '--conflict-loser', 'num', '--conflict-suffix', 'conflict-local,conflict-remote',
97
+ '--create-empty-src-dirs', '--resilient', '--recover', '--max-delete', '50',
98
+ '--backup-dir1', path.join(root, 'sync/history', new Date().toISOString().replaceAll(':', '-')),
99
+ ...(initial ? ['--resync-mode', 'path2'] : []), ...common];
100
+ }
101
+
102
+ export async function syncAdopt(root, remote, stateRoot = root) {
103
+ return locked(root, async root => {
104
+ await prepare(root);
105
+ if (await readJSON(location(root))) fail('CONFLICT', 'A folder is already bound; inspect sync-status rather than replacing it');
106
+ const plan = await inspect(root, remote, stateRoot);
107
+ const files = path.join(root, 'files');
108
+ if ((await inventory(files)).some(f => f.path !== marker)) {
109
+ const check = await rclone(root, ['check', files, remote, '--one-way', '--download', '--exclude', marker, ...common]);
110
+ if (check.code !== 0) fail('CONFLICT', 'Existing local files differ from the folder. Preserve and reconcile them before adopting');
111
+ }
112
+ // Import first, with no replacement of local originals. Initial bisync is
113
+ // allowed only here; the recurring worker never resets its baseline.
114
+ succeeded(await rclone(root, ['copy', remote, files, '--ignore-existing', '--create-empty-src-dirs', '--exclude', '.*', '--exclude', '.*/**', ...common]), 'Initial folder import');
115
+ succeeded(await rclone(root, ['check', remote, files, '--one-way', '--download', '--exclude', '.*', '--exclude', '.*/**', ...common]), 'Imported byte verification');
116
+ if (await remoteIdentity(root, remote, stateRoot) !== plan.identity) fail('CONFLICT', 'Folder identity changed during adoption');
117
+ if (!plan.files.some(f => f.Path === marker)) {
118
+ await fs.writeFile(path.join(files, marker), 'Library sync access marker. Removing this file pauses synchronization.\n', { mode: 0o600, flag: 'wx' });
119
+ succeeded(await rclone(root, ['copyto', path.join(files, marker), remote + '/' + marker, '--immutable', ...common]), 'Sync access marker');
120
+ }
121
+ const config = { schemaVersion: 1, remote, identity: plan.identity, mode: 'paused', intervalSeconds: 60 };
122
+ // Persist the binding before the first remote mutation by bisync. An
123
+ // interrupted adoption stays paused and needs deliberate recovery.
124
+ await atomic(location(root), jsonBytes(config));
125
+ succeeded(await rclone(root, [...bisyncArgs(root, config, true), '--dry-run']), 'Initial sync preview');
126
+ succeeded(await rclone(root, bisyncArgs(root, config, true)), 'Initial sync');
127
+ config.mode = 'two-way';
128
+ await atomic(location(root), jsonBytes(config));
129
+ await atomic(path.join(root, 'sync/status.json'), jsonBytes({ state: 'synced', syncedAt: new Date().toISOString(), indexing: 'pending' }));
130
+ return { ...await syncStatus(root), imported: plan.files.length };
131
+ });
132
+ }
133
+
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');
136
+ return locked(root, async root => {
137
+ const current = await syncStatus(root);
138
+ if (!current.config || current.revision !== expected) fail('CONFLICT', 'Read the current sync revision before changing policy');
139
+ await atomic(location(root), jsonBytes({ ...current.config, mode, intervalSeconds }));
140
+ return syncStatus(root);
141
+ });
142
+ }
143
+
144
+ export async function syncRun(root, stateRoot = root) {
145
+ return locked(root, async root => {
146
+ await prepare(root);
147
+ const config = await readJSON(location(root));
148
+ if (!config || config.mode === 'paused') return { state: config ? 'paused' : 'unconfigured' };
149
+ let status = { state: 'syncing', startedAt: new Date().toISOString() };
150
+ await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
151
+ try {
152
+ if (config.backend === 'git') status.git = await gitTransfer(root, config);
153
+ else {
154
+ if (await remoteIdentity(root, config.remote, stateRoot) !== config.identity) fail('CONFLICT', 'Mapped folder disappeared or changed identity; no automatic recreation');
155
+ succeeded(await rclone(root, bisyncArgs(root, config)), 'Native bisync');
156
+ }
157
+ status = { ...status, state: 'indexing', syncedAt: new Date().toISOString() };
158
+ await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
159
+ try { status.textMirror = await mirrorTransfer(root); }
160
+ catch (error) { status.textMirror = { state: 'pending', error: { code: error.code || 'UNAVAILABLE', message: error.message } }; }
161
+ const index = await refreshIndex(root);
162
+ status = { ...status, state: index.conflicts?.length ? 'synced-with-conflicts' : index.pending.length ? 'indexed-with-pending-extraction' : 'synced-and-indexed', indexedAt: index.indexedAt, embedded: index.embedded };
163
+ } catch (error) {
164
+ status = { ...status, state: status.syncedAt ? 'index-pending' : 'sync-error', error: { code: error.code || 'UNAVAILABLE', message: error.message } };
165
+ await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
166
+ throw error;
167
+ }
168
+ await atomic(path.join(root, 'sync/status.json'), jsonBytes(status));
169
+ if (status.textMirror?.state === 'pending') fail('UNAVAILABLE', 'Folder synced; GitHub text mirror pending: ' + status.textMirror.error.message);
170
+ return status;
171
+ });
172
+ }
@@ -0,0 +1,30 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import * as fs from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { serve, validateCall } from '../src/embedding-worker.mjs';
7
+ import { request, protocol, model, invoke, embeddingStatus } from '../src/embedding-client.mjs';
8
+
9
+ test('default off never invokes a model or downloads; unavailable has no local fallback', async () => {
10
+ assert.equal((await embeddingStatus()).state, 'off');
11
+ await assert.rejects(invoke('embed', model, ['text', {}]), /off/);
12
+ await assert.rejects(request({ method: 'health', args: [] }, '/nonexistent/worker.sock'));
13
+ await assert.rejects(invoke('embed', 'foreign', ['text', {}]), /mismatch/);
14
+ });
15
+ test('worker exposes only bounded embedding and tokenizer operations', () => {
16
+ for (const v of [ { method: 'dispose', args: [] }, { method: 'embed', args: ['text', { model: 'foreign' }] }, { method: 'embedBatch', args: [Array(33).fill('x'), {}] }, { method: 'tokenize', args: ['x'.repeat(300000)] }, { method: 'detokenize', args: [[-1]] } ]) {
17
+ assert.throws(() => validateCall({ protocol, model, ...v }));
18
+ }
19
+ assert.throws(() => validateCall({ protocol: 'wrong', model, method: 'health', args: [] }));
20
+ });
21
+ test('two clients share serialized inference without shared documents or model mutation', async t => {
22
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'ez-emb-')), socket = path.join(root, 'worker.sock');
23
+ let active = 0, max = 0, calls = 0;
24
+ const server = await serve({ embed: async text => { active++; calls++; max = Math.max(max, active); await new Promise(r => setTimeout(r, 10)); active--; return { embedding: [text.length], model }; } }, socket);
25
+ t.after(async () => { await new Promise(r => server.close(r)); await fs.rm(root, { recursive: true, force: true }); });
26
+ await Promise.all(['one', 'two'].map(text => request({ method: 'embed', args: [text, {}] }, socket)));
27
+ assert.equal(calls, 2); assert.equal(max, 1);
28
+ assert.equal((await request({ method: 'health', args: [] }, socket)).dimensions, 768);
29
+ await assert.rejects(request({ method: 'dispose', args: [] }, socket));
30
+ });
@@ -0,0 +1,121 @@
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 { execFileSync } from 'node:child_process';
7
+ import { Readable } from 'node:stream';
8
+ import { mirrorAdopt, mirrorTransfer, mirrorStatus, mirrorPolicy } from '../src/git-mirror.mjs';
9
+ import { initialize, locked, put, organize } from '../src/store.mjs';
10
+
11
+ async function fixture(t) {
12
+ const base = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), 'library-mirror-')));
13
+ t.after(() => fs.rm(base, { recursive: true, force: true }));
14
+ const root = await initialize(path.join(base, 'state')), remote = path.join(base, 'remote.git');
15
+ const git = args => execFileSync('/usr/bin/git', ['-c', 'user.name=QA', '-c', 'user.email=qa@example.invalid', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: { PATH: '/usr/bin:/bin', HOME: base, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_ALLOW_PROTOCOL: 'file' } });
16
+ git(['init', '--bare', '--initial-branch=main', remote]);
17
+ await fs.mkdir(path.join(root, 'sync'));
18
+ await fs.writeFile(path.join(root, 'sync/config.json'), JSON.stringify({ schemaVersion: 1, mode: 'two-way', remote: '/external' }));
19
+ return { root, remote, base, git, cycle: () => locked(root, () => mirrorTransfer(root)) };
20
+ }
21
+ test('text mirror versions notes and renames while excluding attachment bytes and hidden settings', async t => {
22
+ const { root, remote, git, cycle } = await fixture(t);
23
+ const note = await put(root, 'notes/a.md', Readable.from(['# Original\n![](../_attachments/image.png)']), { expected: 'new', key: 'note' });
24
+ await put(root, '_attachments/image.png', Readable.from(['synthetic image']), { expected: 'new', key: 'image' });
25
+ await fs.mkdir(path.join(root, 'files/.obsidian'));
26
+ await fs.writeFile(path.join(root, 'files/.obsidian/settings.md'), 'private settings');
27
+ await mirrorAdopt(root, remote);
28
+ const first = await cycle();
29
+ assert.equal(first.remoteVerified, true);
30
+ assert.equal(git(['--git-dir', remote, 'ls-tree', '-r', '--name-only', 'main']).trim(), 'notes/a.md');
31
+ assert.equal((await cycle()).commit, first.commit);
32
+ await organize(root, { path: 'notes/a.md', to: 'organized/a.md', expected: note.sha256, key: 'move' });
33
+ const second = await cycle(); assert.notEqual(second.commit, first.commit);
34
+ assert.match(git(['--git-dir', remote, 'show', 'main:organized/a.md']), /Original/);
35
+ assert.match(git(['--git-dir', remote, 'show', first.commit + ':notes/a.md']), /Original/);
36
+ assert.equal(await fs.readFile(path.join(root, 'files/_attachments/image.png'), 'utf8'), 'synthetic image');
37
+ const current = await mirrorStatus(root);
38
+ await mirrorPolicy(root, current.revision, 'paused');
39
+ assert.equal((await cycle()).state, 'paused');
40
+ });
41
+ test('outside GitHub edits stop mirroring without changing Drive originals or dropping remote history', async t => {
42
+ const { root, remote, base, git, cycle } = await fixture(t);
43
+ await put(root, 'note.md', Readable.from(['original']), { expected: 'new', key: 'note' });
44
+ await mirrorAdopt(root, remote); await cycle();
45
+ const checkout = path.join(base, 'external'); git(['clone', remote, checkout]);
46
+ await fs.writeFile(path.join(checkout, 'note.md'), 'external edit');
47
+ git(['-C', checkout, 'add', '.']); git(['-C', checkout, 'commit', '-m', 'external']); git(['-C', checkout, 'push']);
48
+ await assert.rejects(cycle(), { code: 'CONFLICT' });
49
+ assert.equal(await fs.readFile(path.join(root, 'files/note.md'), 'utf8'), 'original');
50
+ assert.equal(git(['--git-dir', remote, 'show', 'main:note.md']), 'external edit');
51
+ });
52
+ test('deleted mirror branches are not recreated and populated destinations are not adopted', async t => {
53
+ const { root, remote, git, cycle } = await fixture(t);
54
+ await mirrorAdopt(root, remote); await cycle();
55
+ git(['--git-dir', remote, 'update-ref', '-d', 'refs/heads/main']);
56
+ await assert.rejects(cycle(), { code: 'CONFLICT' });
57
+ await assert.rejects(mirrorAdopt(root, remote), { code: 'CONFLICT' });
58
+ });
59
+
60
+ test('failed adoption resumes exact partial setup after remote branch is corrected', async t => {
61
+ const { root, remote, base, git, cycle } = await fixture(t);
62
+ const checkout = path.join(base, 'seed'); git(['clone', remote, checkout]);
63
+ await fs.writeFile(path.join(checkout, 'existing.md'), 'existing');
64
+ git(['-C', checkout, 'add', '.']); git(['-C', checkout, 'commit', '-m', 'seed']); git(['-C', checkout, 'push']);
65
+ await assert.rejects(mirrorAdopt(root, remote, 'main', undefined, root, 'private'), { code: 'CONFLICT' });
66
+ assert.equal((await mirrorStatus(root)).config, null);
67
+ await assert.rejects(mirrorAdopt(root, remote, 'library-history', undefined, root, 'other'), error => {
68
+ assert.equal(error.code, 'CONFLICT');
69
+ assert.match(error.message, /different excluded directories/);
70
+ return true;
71
+ });
72
+ // Select an empty branch on the same repository; preserve its existing main.
73
+ await mirrorAdopt(root, remote, 'library-history', undefined, root, 'private');
74
+ assert.equal((await cycle()).remoteVerified, true);
75
+ assert.equal(git(['--git-dir', remote, 'show', 'main:existing.md']), 'existing');
76
+ });
77
+
78
+ test('text mirror excludes configured directory subtrees without matching similar prefixes', async t => {
79
+ const { root, remote, git, cycle } = await fixture(t);
80
+ await put(root, 'private/note.md', Readable.from(['excluded']), { expected: 'new', key: 'excluded' });
81
+ await put(root, 'private/deeper/note.txt', Readable.from(['also excluded']), { expected: 'new', key: 'deeper' });
82
+ await put(root, 'private-notes/note.md', Readable.from(['retained']), { expected: 'new', key: 'retained' });
83
+ await mirrorAdopt(root, remote, 'main', '.md,.txt', root, 'private');
84
+ assert.deepEqual((await mirrorStatus(root)).config.excludeDirectories, ['private']);
85
+ await cycle();
86
+ assert.equal(git(['--git-dir', remote, 'ls-tree', '-r', '--name-only', 'main']).trim(), 'private-notes/note.md');
87
+ assert.equal(await fs.readFile(path.join(root, 'files/private/note.md'), 'utf8'), 'excluded');
88
+ });
89
+
90
+ test('text mirror rejects unsafe excluded directory prefixes and accepts legacy config without exclusions', async t => {
91
+ const { root, remote, cycle } = await fixture(t);
92
+ await assert.rejects(mirrorAdopt(root, remote, 'main', undefined, root, '../private'), { code: 'INVALID' });
93
+ await mirrorAdopt(root, remote);
94
+ const configPath = path.join(root, 'sync/text-mirror.json');
95
+ const config = JSON.parse(await fs.readFile(configPath, 'utf8'));
96
+ delete config.excludeDirectories;
97
+ await fs.writeFile(configPath, JSON.stringify(config));
98
+ assert.equal((await mirrorStatus(root)).config.excludeDirectories, undefined);
99
+ assert.equal((await cycle()).remoteVerified, true);
100
+ });
101
+
102
+
103
+ test('text mirror handles directory and file replacements and retries with empty projection directories', async t => {
104
+ const { root, remote, git, cycle } = await fixture(t);
105
+ const originals = path.join(root, 'files');
106
+ await fs.mkdir(path.join(originals, 'topic.md/deep'), { recursive: true });
107
+ await fs.writeFile(path.join(originals, 'topic.md/deep/a.txt'), 'nested');
108
+ await mirrorAdopt(root, remote); const first = await cycle();
109
+ await fs.rm(path.join(originals, 'topic.md'), { recursive: true });
110
+ await fs.writeFile(path.join(originals, 'topic.md'), 'replacement');
111
+ // Empty directories may survive an interrupted previous projection pass.
112
+ await fs.mkdir(path.join(root, 'sync/text-mirror/files/topic.md/empty/deeper'), { recursive: true });
113
+ assert.equal((await cycle()).remoteVerified, true);
114
+ assert.equal(git(['--git-dir', remote, 'show', 'main:topic.md']), 'replacement');
115
+ assert.equal(git(['--git-dir', remote, 'show', first.commit + ':topic.md/deep/a.txt']), 'nested');
116
+ await fs.unlink(path.join(originals, 'topic.md'));
117
+ await fs.mkdir(path.join(originals, 'topic.md'));
118
+ await fs.writeFile(path.join(originals, 'topic.md/b.txt'), 'restored folder');
119
+ assert.equal((await cycle()).remoteVerified, true);
120
+ assert.equal(git(['--git-dir', remote, 'show', 'main:topic.md/b.txt']), 'restored folder');
121
+ });
@@ -0,0 +1,135 @@
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 { execFileSync } from 'node:child_process';
7
+ import { Readable } from 'node:stream';
8
+ import { gitAdopt, gitTransfer, git, repositoryURL } from '../src/git-sync.mjs';
9
+ import { locked, put, digest, organize, jsonBytes } from '../src/store.mjs';
10
+
11
+ async function setup(t) {
12
+ const base = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), 'library-git-')));
13
+ t.after(() => fs.rm(base, { recursive: true, force: true }));
14
+ const remote = path.join(base, 'remote.git'), external = path.join(base, 'external'), root = path.join(base, 'state');
15
+ function outside(args) {
16
+ return execFileSync('/usr/bin/git', ['-c', 'core.hooksPath=/dev/null', '-c', 'user.name=QA', '-c', 'user.email=qa@example.invalid', ...args], {
17
+ encoding: 'utf8', env: { PATH: '/usr/bin:/bin', HOME: base, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_ALLOW_PROTOCOL: 'file' }, stdio: ['ignore', 'pipe', 'pipe'] });
18
+ }
19
+ outside(['init', '--bare', '--initial-branch=main', remote]); outside(['clone', remote, external]);
20
+ for (let i=0;i<3;i++) await fs.writeFile(path.join(external, `note${i}.md`), `# Note ${i}\nOriginal telescope instructions.\n`);
21
+ await fs.writeFile(path.join(external, 'empty.txt'), '');
22
+ const publish = () => { outside(['-C', external, 'add', '-A']); outside(['-C', external, 'commit', '-m', 'External revision']); outside(['-C', external, 'push', 'origin', 'main']); };
23
+ publish();
24
+ return { base, root, remote, external, outside, publish };
25
+ }
26
+ const cycle = (root, config) => locked(root, () => gitTransfer(root, config));
27
+
28
+ test('native Git adopts originals, imports external changes, exports agent changes and verifies commit', async t => {
29
+ const { root, remote, external, outside, publish } = await setup(t);
30
+ const { config } = await gitAdopt(root, remote);
31
+ assert.equal((await fs.stat(path.join(root, 'files/empty.txt'))).size, 0);
32
+ await fs.writeFile(path.join(external, 'incoming.md'), '# Incoming\nCobalt otters.'); publish();
33
+ await cycle(root, config);
34
+ assert.match(await fs.readFile(path.join(root, 'files/incoming.md'), 'utf8'), /Cobalt/);
35
+ const saved = await put(root, 'agent.md', Readable.from(['# Agent\nSaffron notebook.']), { expected: 'new', key: 'agent' });
36
+ const result = await cycle(root, config);
37
+ assert.equal(result.remoteVerified, true);
38
+ assert.equal(outside(['--git-dir', remote, 'rev-parse', 'main']).trim(), result.commit);
39
+ assert.match(outside(['--git-dir', remote, 'show', 'main:agent.md']), /Saffron/);
40
+ await organize(root, { path: 'agent.md', to: 'organized/agent.md', expected: saved.sha256, key: 'move' });
41
+ await cycle(root, config);
42
+ assert.match(outside(['--git-dir', remote, 'show', 'main:organized/agent.md']), /Saffron/);
43
+ outside(['-C', external, 'pull', '--ff-only']);
44
+ await fs.unlink(path.join(external, 'note1.md')); await fs.rename(path.join(external, 'note2.md'), path.join(external, 'renamed.md')); publish();
45
+ await cycle(root, config);
46
+ await assert.rejects(fs.stat(path.join(root, 'files/note1.md')), { code: 'ENOENT' });
47
+ assert.match(await fs.readFile(path.join(root, 'files/renamed.md'), 'utf8'), /Note 2/);
48
+ });
49
+
50
+ test('simultaneous changes retain native merge stages and pause until explicit resolution', async t => {
51
+ const { root, remote, external, publish, outside } = await setup(t);
52
+ const { config } = await gitAdopt(root, remote);
53
+ await fs.writeFile(path.join(external, 'note0.md'), 'REMOTE revision\n'); publish();
54
+ const original = await digest(path.join(root, 'files/note0.md'));
55
+ await put(root, 'note0.md', Readable.from(['LOCAL revision\n']), { expected: original.sha256, key: 'local' });
56
+ await assert.rejects(cycle(root, config), { code: 'CONFLICT' });
57
+ assert.match((await git(root, config, ['show', ':2:note0.md'])).stdout, /LOCAL/);
58
+ assert.match((await git(root, config, ['show', ':3:note0.md'])).stdout, /REMOTE/);
59
+ await assert.rejects(cycle(root, config), { code: 'CONFLICT' });
60
+ await fs.writeFile(path.join(root, 'files/note0.md'), 'Reviewed resolution\n');
61
+ assert.equal((await git(root, config, ['add', '--', 'note0.md'])).code, 0);
62
+ await cycle(root, config);
63
+ assert.match(outside(['--git-dir', remote, 'show', 'main:note0.md']), /Reviewed resolution/);
64
+ });
65
+
66
+ test('missing remote retains local commits for retry, and symlink changes cannot enter the Library', async t => {
67
+ const { root, remote, external, publish } = await setup(t);
68
+ const { config } = await gitAdopt(root, remote);
69
+ await fs.rename(remote, remote + '-offline');
70
+ await put(root, 'pending.md', Readable.from(['Pending survives']), { expected: 'new', key: 'pending' });
71
+ await assert.rejects(cycle(root, config));
72
+ assert.match((await git(root, config, ['show', 'HEAD:pending.md'])).stdout, /Pending/);
73
+ await fs.rename(remote + '-offline', remote);
74
+ await fs.symlink('/etc/passwd', path.join(external, 'unsafe')); publish();
75
+ await assert.rejects(cycle(root, config), { code: 'UNSAFE_PATH' });
76
+ await assert.rejects(fs.lstat(path.join(root, 'files/unsafe')), { code: 'ENOENT' });
77
+ });
78
+
79
+ test('adoption preserves mismatching local files and ignore rules cannot hide unsynced originals', async t => {
80
+ const first = await setup(t);
81
+ await put(first.root, 'note0.md', Readable.from(['Keep local']), { expected: 'new', key: 'local' });
82
+ await assert.rejects(gitAdopt(first.root, first.remote), { code: 'CONFLICT' });
83
+ assert.equal(await fs.readFile(path.join(first.root, 'files/note0.md'), 'utf8'), 'Keep local');
84
+ const second = await setup(t);
85
+ await fs.writeFile(path.join(second.external, '.gitignore'), '*.pdf\n'); second.publish();
86
+ const { config } = await gitAdopt(second.root, second.remote);
87
+ await put(second.root, 'original.pdf', Readable.from(['PDF fixture']), { expected: 'new', key: 'pdf' });
88
+ await assert.rejects(cycle(second.root, config), { code: 'CONFLICT' });
89
+ for (const invalid of ['https://token@github.com/owner/repo', 'owner/../repo', '-option', 'owner/.git']) assert.throws(() => repositoryURL(invalid), { code: 'INVALID' });
90
+ });
91
+
92
+ test('changed Hybrid policy or bound remote stops Git before any upload', async t => {
93
+ const { root, remote, outside } = await setup(t);
94
+ const { config } = await gitAdopt(root, remote);
95
+ const old = outside(['--git-dir', remote, 'rev-parse', 'main']).trim();
96
+ await put(root, 'pending.md', Readable.from(['Do not publish under a changed policy']), { expected: 'new', key: 'pending' });
97
+ await put(root, 'settings.json', Readable.from([jsonBytes({ schemaVersion: 1, storage: { mode: 'drive', drive: { connection: 'example', folderId: 'example' } }, backup: { mode: 'off' } })]), { kind: 'settings', expected: 'new', key: 'settings' });
98
+ await assert.rejects(cycle(root, config), { code: 'CONFLICT' });
99
+ assert.equal(outside(['--git-dir', remote, 'rev-parse', 'main']).trim(), old);
100
+ await fs.unlink(path.join(root, 'settings.json'));
101
+ await git(root, config, ['remote', 'set-url', 'origin', remote + '-different']);
102
+ await assert.rejects(cycle(root, config), { code: 'CONFLICT' });
103
+ });
104
+
105
+ test('hidden originals obey Git safety and size checks before any push', async t => {
106
+ const { root, remote, outside } = await setup(t);
107
+ const { config } = await gitAdopt(root, remote);
108
+ const original = outside(['--git-dir', remote, 'rev-parse', 'main']).trim();
109
+ const hidden = path.join(root, 'files/.hidden');
110
+ await fs.mkdir(hidden);
111
+ await fs.symlink('/etc/passwd', path.join(hidden, 'link'));
112
+ await assert.rejects(cycle(root, config), /Unsupported symlink/);
113
+ assert.equal(outside(['--git-dir', remote, 'rev-parse', 'main']).trim(), original);
114
+ await fs.unlink(path.join(hidden, 'link'));
115
+ const large = await fs.open(path.join(hidden, 'large.bin'), 'w');
116
+ await large.truncate(100 * 1024 * 1024); await large.close();
117
+ await assert.rejects(cycle(root, config), { code: 'TOO_LARGE' });
118
+ assert.equal(outside(['--git-dir', remote, 'rev-parse', 'main']).trim(), original);
119
+ });
120
+
121
+
122
+ test('named Git adoption rejects default and sibling private state including symlink aliases', async t => {
123
+ const { base, root, remote } = await setup(t);
124
+ const selected = path.join(root, 'libraries/work');
125
+ for (const relative of ['sync/git', 'libraries/personal/sync/git']) {
126
+ const privateRepo = path.join(root, relative);
127
+ await fs.mkdir(privateRepo, { recursive: true });
128
+ await assert.rejects(gitAdopt(selected, privateRepo, 'main', root), { code: 'UNSAFE_PATH' });
129
+ }
130
+ const alias = path.join(base, 'alias');
131
+ await fs.symlink(path.join(root, 'sync/git'), alias);
132
+ await assert.rejects(gitAdopt(selected, alias, 'main', root), { code: 'UNSAFE_PATH' });
133
+ await assert.rejects(fs.stat(path.join(selected, 'sync/config.json')), { code: 'ENOENT' });
134
+ assert.equal((await gitAdopt(selected, remote, 'main', root)).config.repository, remote);
135
+ });
@@ -0,0 +1,73 @@
1
+ import { test } from 'node:test';
2
+ import { execFileSync } from 'node:child_process';
3
+
4
+ test('per-library indexing policy controls native QMD embedding with explicit shared-worker enablement', () => {
5
+ execFileSync(process.execPath, ['--experimental-test-module-mocks', '--input-type=module', '-e', `
6
+ import { mock } from 'node:test';
7
+ import assert from 'node:assert/strict';
8
+ import * as fs from 'node:fs/promises';
9
+ import path from 'node:path';
10
+ import { tmpdir } from 'node:os';
11
+ const native = await import('./src/native.mjs');
12
+ const calls = [];
13
+ mock.module('./src/native.mjs', { namedExports: { ...native,
14
+ qmd: async (_, args) => { calls.push(args); return { code: 0, stdout: args[0] === 'collection' && args[1] === 'list' ? '' : '', stderr: '' }; }
15
+ } });
16
+ const { refreshIndex, indexStatus } = await import('./src/indexer.mjs');
17
+ process.env.EZ_LIBRARY_EMBED_SOCKET = '/synthetic/worker.sock';
18
+ const base = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), 'library-index-policy-')));
19
+ try {
20
+ async function run(name, indexing, globalEmbed = true) {
21
+ const root = path.join(base, name);
22
+ await fs.mkdir(path.join(root, 'files'), { recursive: true });
23
+ await fs.mkdir(path.join(root, 'sync'));
24
+ await fs.writeFile(path.join(root, 'files', 'note.md'), name);
25
+ if (indexing) await fs.writeFile(path.join(root, 'settings.json'), JSON.stringify({ schemaVersion: 1, storage: { mode: 'local' }, backup: { mode: 'off' }, indexing }));
26
+ if (globalEmbed) delete process.env.EZ_LIBRARY_EMBED; else process.env.EZ_LIBRARY_EMBED = '0';
27
+ const start = calls.length;
28
+ const result = await refreshIndex(root);
29
+ return { result, calls: calls.slice(start) };
30
+ }
31
+ const keyword = await run('keyword', { mode: 'keyword' });
32
+ assert.equal(keyword.result.embedded, false);
33
+ assert.equal(keyword.calls.some(args => args[0] === 'embed'), false);
34
+ assert(keyword.calls.some(args => args[0] === 'update'));
35
+
36
+ const semantic = await run('semantic', { mode: 'semantic' });
37
+ assert.equal(semantic.result.embedded, true);
38
+ assert(semantic.calls.some(args => args[0] === 'embed'));
39
+
40
+ const semanticRoot = path.join(base, 'semantic');
41
+ await fs.writeFile(path.join(semanticRoot, 'settings.json'), JSON.stringify({ schemaVersion: 1, storage: { mode: 'local' }, backup: { mode: 'off' }, indexing: { mode: 'keyword' } }));
42
+ assert.equal((await indexStatus(semanticRoot)).state, 'off');
43
+ let start = calls.length;
44
+ const changedToKeyword = await refreshIndex(semanticRoot);
45
+ assert.equal(changedToKeyword.embedded, false);
46
+ assert.deepEqual(calls.slice(start), []);
47
+ assert.equal(JSON.parse(await fs.readFile(path.join(semanticRoot, 'sync/index.json'))).embedded, false);
48
+
49
+ start = calls.length;
50
+ assert.equal((await refreshIndex(semanticRoot)).embedded, false);
51
+ assert.deepEqual(calls.slice(start), []);
52
+
53
+ await fs.writeFile(path.join(semanticRoot, 'settings.json'), JSON.stringify({ schemaVersion: 1, storage: { mode: 'local' }, backup: { mode: 'off' }, indexing: { mode: 'semantic' } }));
54
+ start = calls.length;
55
+ assert.equal((await refreshIndex(semanticRoot)).embedded, true);
56
+ assert(calls.slice(start).some(args => args[0] === 'embed'));
57
+
58
+ const legacy = await run('legacy');
59
+ assert.equal(legacy.result.embedded, true);
60
+ assert(legacy.calls.some(args => args[0] === 'embed'));
61
+
62
+ delete process.env.EZ_LIBRARY_EMBED_SOCKET;
63
+ assert.equal((await indexStatus(semanticRoot)).state, 'off');
64
+ const defaultOff = await run('default-off');
65
+ assert.equal(defaultOff.result.embedded, false);
66
+ assert.equal(defaultOff.calls.some(args => args[0] === 'embed'), false);
67
+ process.env.EZ_LIBRARY_EMBED_SOCKET = '/synthetic/worker.sock';
68
+ const globallyDisabled = await run('global-off', { mode: 'semantic' }, false);
69
+ assert.equal(globallyDisabled.result.embedded, false);
70
+ assert.equal(globallyDisabled.calls.some(args => args[0] === 'embed'), false);
71
+ } finally { await fs.rm(base, { recursive: true, force: true }); }
72
+ `], { cwd: new URL('..', import.meta.url), stdio: 'pipe' });
73
+ });