@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
@@ -0,0 +1,132 @@
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, spawnSync, spawn } from 'node:child_process';
7
+ import { Readable } from 'node:stream';
8
+ import { addLibrary, catalog, selectLibrary, sources, searchLibraries } from '../src/libraries.mjs';
9
+ import { locked, put } from '../src/store.mjs';
10
+ import { gitAdopt, gitTransfer } from '../src/git-sync.mjs';
11
+ const cli = new URL('../bin/ez-library.mjs', import.meta.url);
12
+ async function setup(t) {
13
+ const base = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), 'library-named-')));
14
+ t.after(() => fs.rm(base, { recursive: true, force: true }));
15
+ return path.join(base, 'state');
16
+ }
17
+ const invoke = (root, args, input) => spawnSync(process.execPath, [cli.pathname, ...args], { env: { ...process.env, EZ_LIBRARY_STATE: root }, encoding: 'utf8', input });
18
+
19
+ test('legacy state stays in place; named files and operation receipts are isolated', async t => {
20
+ const base = await setup(t);
21
+ assert.equal((await selectLibrary(base)).root, base);
22
+ assert.equal((await sources(base)).libraries.length, 1);
23
+ const args = ['put', '--path', 'same.md', '--expected', 'new', '--key', 'same'];
24
+ assert.equal(invoke(base, args, 'legacy').status, 0);
25
+ const before = (await catalog(base)).revision;
26
+ await addLibrary(base, 'work', 'Work documentation');
27
+ assert.notEqual((await catalog(base)).revision, before);
28
+ assert.equal((await addLibrary(base, 'work', 'Work documentation')).existing, true);
29
+ assert.equal(invoke(base, args, 'ambiguous').status, 2);
30
+ assert.equal(invoke(base, [...args, '--library', 'work'], 'work').status, 0);
31
+ assert.equal(invoke(base, ['get', '--library', 'default', '--path', 'same.md', '--raw']).stdout, 'legacy');
32
+ assert.equal(invoke(base, ['get', '--library=work', '--path', 'same.md', '--raw']).stdout, 'work');
33
+ for (const name of ['default', 'work']) assert.equal(JSON.parse(invoke(base, ['operation', '--library', name, '--key', 'same']).stdout).data.state, 'stored');
34
+ for (const args of [['qmd', 'search', 'x'], ['git', 'status'], ['rclone', 'listremotes'], ['get', '--path', 'same.md'], ['put', '--library', 'missing']]) assert.equal(invoke(base, args).status, 2);
35
+ assert.equal((await sources(base)).selectionRequired, true);
36
+ });
37
+
38
+ test('invalid names, catalog corruption and intermediate symlinks fail closed', async t => {
39
+ const base = await setup(t);
40
+ for (const name of ['../escape', '/tmp/escape', 'a/b', '.hidden', 'default', 'UPPER']) await assert.rejects(addLibrary(base, name, 'Notes'));
41
+ await addLibrary(base, 'work', 'Work');
42
+ await assert.rejects(addLibrary(base, 'work', 'Different'), { code: 'CONFLICT' });
43
+ await fs.rename(path.join(base, 'libraries'), path.join(base, 'saved'));
44
+ await fs.symlink(path.join(base, 'saved'), path.join(base, 'libraries'));
45
+ await assert.rejects(selectLibrary(base, 'work'), { code: 'UNSAFE_PATH' });
46
+ await assert.rejects(addLibrary(base, 'extra', 'Extra'), { code: 'UNSAFE_PATH' });
47
+ await fs.writeFile(path.join(base, 'libraries.json'), '{}');
48
+ await assert.rejects(selectLibrary(base, 'default'), { code: 'INVALID' });
49
+ });
50
+
51
+ test('search preserves QMD matches and source names, reporting partial errors', async t => {
52
+ const base = await setup(t);
53
+ await addLibrary(base, 'work', 'Work');
54
+ const query = 'literal $(echo no)';
55
+ const response = await searchLibraries(base, { all: true, query }, async (root, args) => {
56
+ assert.deepEqual(args, ['search', query, '--json', '-n', '5']);
57
+ return { code: 0, stdout: JSON.stringify([{ file: 'qmd://library/same.md', score: 0.8 }]) };
58
+ });
59
+ assert.equal(response.complete, true);
60
+ assert.deepEqual(response.libraries.map(x => x.results[0].library), ['default', 'work']);
61
+ const partial = await searchLibraries(base, { all: true, query }, async root => {
62
+ if (root !== base) throw Error('index unavailable');
63
+ return { code: 0, stdout: '[]' };
64
+ });
65
+ assert.equal(partial.complete, false);
66
+ assert.match(partial.libraries[1].error.message, /index unavailable/);
67
+ await assert.rejects(searchLibraries(base, { query }));
68
+ await assert.rejects(searchLibraries(base, { query, all: true, name: 'work' }));
69
+ });
70
+
71
+ test('two native Git repositories with identical paths transfer independently', async t => {
72
+ const base = await setup(t);
73
+ 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: path.dirname(base), GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_ALLOW_PROTOCOL: 'file' } });
74
+ await addLibrary(base, 'work', 'Work');
75
+ for (const name of ['default', 'work']) {
76
+ const remote = path.join(path.dirname(base), name + '.git');
77
+ const checkout = path.join(path.dirname(base), name + '-checkout');
78
+ git(['init', '--bare', '--initial-branch=main', remote]);
79
+ git(['clone', remote, checkout]);
80
+ await fs.writeFile(path.join(checkout, 'same.md'), name);
81
+ git(['-C', checkout, 'add', '.']); git(['-C', checkout, 'commit', '-m', 'Seed']); git(['-C', checkout, 'push']);
82
+ const { root } = await selectLibrary(base, name);
83
+ const { config } = await gitAdopt(root, remote);
84
+ await put(root, 'added.md', Readable.from([name]), { expected: 'new', key: 'same-key' });
85
+ const result = await locked(root, () => gitTransfer(root, config));
86
+ assert.equal(result.remoteVerified, true);
87
+ assert.equal(git(['--git-dir', remote, 'show', 'main:added.md']), name);
88
+ assert.equal(await fs.readFile(path.join(root, 'files/same.md'), 'utf8'), name);
89
+ }
90
+ assert.equal((await sources(base)).libraries.every(x => x.sync.config.backend === 'git'), true);
91
+ });
92
+
93
+ test('named folder sync rejects siblings and private state within the global volume', async t => {
94
+ const base = await setup(t);
95
+ await addLibrary(base, 'work', 'Work');
96
+ await addLibrary(base, 'personal', 'Personal');
97
+ await fs.mkdir(path.join(base, 'libraries/personal/sync'));
98
+ for (const remote of [path.join(base, 'files'), path.join(base, 'libraries/personal/files'), path.join(base, 'libraries/personal/sync')]) {
99
+ for (const command of ['sync-plan', 'sync-adopt']) {
100
+ const result = invoke(base, [command, '--library', 'work', '--remote', remote]);
101
+ assert.equal(result.status, 2, result.stderr);
102
+ assert.match(result.stderr, /outside Library state/);
103
+ }
104
+ }
105
+ // A previously written binding cannot bypass the same boundary on a cycle.
106
+ const { root } = await selectLibrary(base, 'work');
107
+ await fs.writeFile(path.join(root, 'sync/config.json'), JSON.stringify({ schemaVersion: 1, remote: path.join(base, 'files'), identity: 'old', mode: 'two-way', intervalSeconds: 60 }));
108
+ const result = invoke(base, ['sync-run', '--library', 'work']);
109
+ assert.equal(result.status, 2, result.stderr);
110
+ });
111
+
112
+
113
+ test('resident supervisor attempts both bindings despite an individual failure', async t => {
114
+ const base = await setup(t);
115
+ await addLibrary(base, 'work', 'Work');
116
+ for (const name of ['default', 'work']) {
117
+ const { root } = await selectLibrary(base, name);
118
+ await fs.mkdir(path.join(root, 'sync'), { recursive: true });
119
+ await fs.writeFile(path.join(root, 'sync/config.json'), JSON.stringify({ schemaVersion: 1, remote: path.join(base, 'files'), identity: 'old', mode: 'two-way', intervalSeconds: 60 }));
120
+ }
121
+ const child = spawn(process.execPath, [new URL('../src/sync-worker.mjs', import.meta.url).pathname], { env: { ...process.env, EZ_LIBRARY_STATE: base }, stdio: ['ignore', 'ignore', 'pipe'] });
122
+ const closed = new Promise(resolve => child.once('close', resolve));
123
+ t.after(async () => { child.kill('SIGTERM'); await closed; });
124
+ await new Promise((resolve, reject) => {
125
+ let stderr = '';
126
+ const timeout = setTimeout(() => reject(Error('Supervisor did not visit both libraries: ' + stderr)), 5000);
127
+ child.stderr.on('data', chunk => {
128
+ stderr += chunk;
129
+ if (stderr.includes('"library":"default"') && stderr.includes('"library":"work"')) { clearTimeout(timeout); resolve(); }
130
+ });
131
+ });
132
+ });
@@ -0,0 +1,163 @@
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, operation, settings, defaults, validateSettings, list, digest, hash } from '../src/store.mjs';
9
+ import { qmdEnvironment } from '../src/cli.mjs';
10
+
11
+ const cli = new URL('../bin/ez-library.mjs', import.meta.url).pathname;
12
+ async function fixture(t) {
13
+ const root = await fs.mkdtemp(path.join(tmpdir(), 'ez-library-test-'));
14
+ t.after(() => fs.rm(root, { recursive: true, force: true })); return root;
15
+ }
16
+ const input = value => Readable.from([Buffer.from(value)]);
17
+ const save = (root, value, options = {}) => put(root, 'notes/test.md', input(value), { key: 'test:1', expected: 'new', ...options });
18
+ const code = expected => error => error.code === expected;
19
+
20
+ test('intake preserves binary bytes, private modes, literal paths and replay across process state', async t => {
21
+ const root = await fixture(t); const data = Buffer.from([0, 255, 10, 34, 128]);
22
+ const relative = 'media/literal $(no-execution) file.pdf';
23
+ const r = await put(root, relative, input(data), { key: 'binary:1', expected: 'new' });
24
+ assert.equal(r.state, 'stored'); assert.equal(r.sha256, hash(data));
25
+ assert.deepEqual(await fs.readFile(path.join(root, 'files', relative)), data);
26
+ assert.equal((await fs.stat(path.join(root, 'files', relative))).mode & 0o777, 0o600);
27
+ assert.equal((await put(root, relative, input(data), { key: 'binary:1', expected: 'new' })).replay, true);
28
+ const read = spawnSync(process.execPath, [cli, 'get', '--path', relative, '--raw'], { env: { ...process.env, EZ_LIBRARY_STATE: root } });
29
+ assert.equal(read.status, 0); assert.deepEqual(read.stdout, data);
30
+ });
31
+
32
+ test('replacement requires current revision; preserves history; stale replay never overwrites new content', async t => {
33
+ const root = await fixture(t); const first = await save(root, 'original');
34
+ await assert.rejects(save(root, 'bad', { key: 'second' }), code('CONFLICT'));
35
+ const second = await save(root, 'revised', { key: 'second', expected: first.sha256 });
36
+ assert.equal(await fs.readFile(path.join(root, 'history', first.sha256), 'utf8'), 'original');
37
+ await assert.rejects(save(root, 'original'), code('CONFLICT'));
38
+ assert.equal((await operation(root, 'test:1')).state, 'changed');
39
+ assert.equal((await operation(root, 'second')).state, 'stored');
40
+ assert.equal((await digest(path.join(root, 'files/notes/test.md'))).sha256, second.sha256);
41
+ });
42
+
43
+ test('operation keys bind content, target and revision', async t => {
44
+ const root = await fixture(t); await save(root, 'first');
45
+ await assert.rejects(save(root, 'different'), code('KEY_REUSED'));
46
+ await assert.rejects(put(root, 'other.md', input('first'), { key: 'test:1', expected: 'new' }), code('KEY_REUSED'));
47
+ });
48
+
49
+ test('receipt can reconcile a missing installation and recover with matching input', async t => {
50
+ const root = await fixture(t); await save(root, 'bytes');
51
+ await fs.unlink(path.join(root, 'files/notes/test.md'));
52
+ assert.equal((await operation(root, 'test:1')).state, 'missing');
53
+ assert.equal((await save(root, 'bytes')).state, 'stored');
54
+ });
55
+
56
+ test('bounds and interrupted input leave no partial target or active lock', async t => {
57
+ const root = await fixture(t);
58
+ await assert.rejects(save(root, 'too big', { maxBytes: 2 }), code('TOO_LARGE'));
59
+ const broken = Readable.from((async function* () { yield 'part'; throw Error('interrupted'); })());
60
+ await assert.rejects(put(root, 'partial.md', broken, { key: 'broken', expected: 'new' }), /interrupted/);
61
+ assert.deepEqual(await fs.readdir(path.join(root, 'tmp')), []);
62
+ await assert.rejects(fs.stat(path.join(root, 'files/partial.md')), code('ENOENT'));
63
+ await assert.rejects(fs.stat(path.join(root, '.writer-lock')), code('ENOENT'));
64
+ });
65
+
66
+ test('traversal, hidden files and symlink ancestors are rejected', async t => {
67
+ const root = await fixture(t); await save(root, 'safe');
68
+ for (const rel of ['../escape', '/etc/file', '.env', 'a/../b', 'a\\b', 'a//b']) {
69
+ await assert.rejects(put(root, rel, input('x'), { key: 'path', expected: 'new' }), code('UNSAFE_PATH'));
70
+ }
71
+ const outside = await fixture(t);
72
+ await fs.symlink(outside, path.join(root, 'files/link'));
73
+ await assert.rejects(put(root, 'link/escape', input('x'), { key: 'link', expected: 'new' }), code('UNSAFE_PATH'));
74
+ assert.deepEqual(await fs.readdir(outside), []);
75
+ await assert.rejects(list(root), code('UNSAFE_PATH'));
76
+ });
77
+
78
+ test('symlinked operation/history records do not follow outside targets', async t => {
79
+ const root = await fixture(t); const first = await save(root, 'original');
80
+ const outside = path.join(await fixture(t), 'outside'); await fs.writeFile(outside, 'untouched', { mode: 0o644 });
81
+ await fs.symlink(outside, path.join(root, 'history', first.sha256));
82
+ await assert.rejects(save(root, 'replacement', { key: 'next', expected: first.sha256 }), code('UNSAFE_PATH'));
83
+ assert.equal((await fs.stat(outside)).mode & 0o777, 0o644);
84
+ const record = path.join(root, 'operations', hash('test:1') + '.json');
85
+ await fs.unlink(record); await fs.symlink(outside, record);
86
+ await assert.rejects(operation(root, 'test:1'), code('UNSAFE_PATH'));
87
+ assert.equal(await fs.readFile(outside, 'utf8'), 'untouched');
88
+ });
89
+
90
+ test('writer lock is fail-closed, including stale-looking locks', async t => {
91
+ const root = await fixture(t); await fs.mkdir(path.join(root, '.writer-lock'));
92
+ await assert.rejects(save(root, 'blocked'), code('BUSY'));
93
+ assert((await fs.stat(path.join(root, '.writer-lock'))).isDirectory());
94
+ });
95
+
96
+ test('list honors prefix and a bounded result size', async t => {
97
+ const root = await fixture(t); await save(root, 'a');
98
+ await put(root, 'notes/second.md', input('b'), { key: 'b', expected: 'new' });
99
+ assert.equal((await list(root, 'notes/', 1)).truncated, true);
100
+ assert.equal((await list(root, 'other/', 1)).files.length, 0);
101
+ await assert.rejects(list(root, '', 1001), code('INVALID'));
102
+ });
103
+
104
+ test('all persistence modes are explicit policy; invalid destinations and credentials fail', () => {
105
+ const github = { connection: 'github-personal', repository: 'example/library', branch: 'main' };
106
+ const drive = { connection: 'drive-personal', folderId: 'folder-123' };
107
+ for (const storage of [{ mode: 'local' }, { mode: 'github', github }, { mode: 'drive', drive },
108
+ { mode: 'hybrid', github, drive, githubExtensions: ['.md', '.pdf'], maxGithubBytes: 10485760 }]) {
109
+ assert.equal(validateSettings({ schemaVersion: 1, storage, backup: { mode: 'off' } }).storage.mode, storage.mode);
110
+ }
111
+ for (const storage of [{ mode: 'hybrid', github }, { mode: 'drive' }, { mode: 'local', token: 'secret' },
112
+ { mode: 'hybrid', github, drive, githubExtensions: ['*'], maxGithubBytes: 1 },
113
+ { mode: 'hybrid', github, drive, githubExtensions: ['.pdf'], maxGithubBytes: 104857600 }]) {
114
+ assert.throws(() => validateSettings({ schemaVersion: 1, storage, backup: { mode: 'off' } }), code('INVALID'));
115
+ }
116
+ });
117
+
118
+ test('indexing policy is explicit and legacy settings remain valid', () => {
119
+ for (const mode of ['keyword', 'semantic']) {
120
+ assert.equal(validateSettings({ ...defaults(), indexing: { mode } }).indexing.mode, mode);
121
+ }
122
+ for (const indexing of [{ mode: 'automatic' }, { mode: 'keyword', fallback: 'semantic' }, {}]) {
123
+ assert.throws(() => validateSettings({ ...defaults(), indexing }), code('INVALID'));
124
+ }
125
+ assert.deepEqual(validateSettings(defaults()), defaults());
126
+ });
127
+
128
+ test('configuration survives restart and doctor never equates settings with cloud verification', async t => {
129
+ const root = await fixture(t);
130
+ const config = { ...defaults(), storage: { mode: 'drive', drive: { connection: 'account', folderId: 'folder' } } };
131
+ const run = spawnSync(process.execPath, [cli, 'configure', '--expected', 'new', '--key', 'settings:1'], {
132
+ env: { ...process.env, EZ_LIBRARY_STATE: root }, input: JSON.stringify(config), encoding: 'utf8'
133
+ });
134
+ assert.equal(run.status, 0, run.stderr); assert.deepEqual((await settings(root)).settings, config);
135
+ const doctor = spawnSync(process.execPath, [cli, 'doctor'], { env: { ...process.env, EZ_LIBRARY_STATE: root }, encoding: 'utf8' });
136
+ assert.equal(doctor.status, 0); assert.equal(JSON.parse(doctor.stdout).data.cloudPersistence, 'configured-not-verified');
137
+ });
138
+
139
+ test('help and doctor work without configuration; subprocess environment excludes secrets', async t => {
140
+ const root = path.join(await fixture(t), 'absent');
141
+ for (const args of [['--help'], ['doctor'], ['settings']]) {
142
+ const run = spawnSync(process.execPath, [cli, ...args], { env: { ...process.env, EZ_LIBRARY_STATE: root }, encoding: 'utf8' });
143
+ assert.equal(run.status, 0, run.stderr);
144
+ }
145
+ await assert.rejects(fs.stat(root), code('ENOENT'));
146
+ process.env.TELEGRAM_BOT_TOKEN = 'synthetic-test-token';
147
+ process.env.NODE_OPTIONS = '--trace-warnings';
148
+ const env = qmdEnvironment('/state');
149
+ assert.equal(env.TELEGRAM_BOT_TOKEN, undefined); assert.equal(env.NODE_OPTIONS, undefined);
150
+ delete process.env.TELEGRAM_BOT_TOKEN; delete process.env.NODE_OPTIONS;
151
+ });
152
+
153
+
154
+ test('PDF extraction rejects traversal, symlinks, directories and missing paths before launching Poppler', async t => {
155
+ const root = await fixture(t); await save(root, 'safe');
156
+ await fs.symlink('/etc/passwd', path.join(root, 'files/link.pdf'));
157
+ for (const relative of ['../settings.json', 'link.pdf', 'notes']) {
158
+ const result = spawnSync(process.execPath, [cli, 'pdf-text', '--path', relative], { env: { ...process.env, EZ_LIBRARY_STATE: root }, encoding: 'utf8' });
159
+ assert.equal(result.status, 2); assert.match(result.stderr, /UNSAFE_PATH/); assert.equal(result.stdout, '');
160
+ }
161
+ const result = spawnSync(process.execPath, [cli, 'pdf-text'], { env: { ...process.env, EZ_LIBRARY_STATE: root }, encoding: 'utf8' });
162
+ assert.equal(result.status, 2); assert.match(result.stderr, /Supply --path/);
163
+ });
@@ -0,0 +1,101 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {readFileSync} from 'node:fs';
4
+ import {verifyPublishingSettings} from '../scripts/publish-settings.mjs';
5
+
6
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
7
+ const workflow = `# Generated by scripts/generate-publish-caller.mjs; review changes before merging.
8
+ name: Publish verified npm beta
9
+ on:
10
+ workflow_dispatch:
11
+ inputs:
12
+ release-id:
13
+ description: 'Numeric ID of the staged draft prerelease'
14
+ required: true
15
+ type: string
16
+ version:
17
+ description: 'Reviewed beta version staged as draft release vVERSION'
18
+ required: true
19
+ type: string
20
+ source-sha:
21
+ description: 'Full tested commit SHA; must be current main'
22
+ required: true
23
+ type: string
24
+ artifact-sha256:
25
+ description: 'SHA-256 of the exact independently verified candidate.tgz'
26
+ required: true
27
+ type: string
28
+ permissions: {}
29
+ jobs:
30
+ publish:
31
+ if: github.repository == 'jdorado/ez-library' && github.ref == 'refs/heads/main'
32
+ permissions:
33
+ contents: write
34
+ checks: read
35
+ actions: read
36
+ pull-requests: read
37
+ id-token: write
38
+ uses: jdorado/ez-agents/.github/workflows/npm-beta-shared.yml@fed05b9c88a5d96a801436a36983254758f03389
39
+ with:
40
+ package: '@jc_stack/ez-library'
41
+ publisher-sha: 'fed05b9c88a5d96a801436a36983254758f03389'
42
+ required-checks: '["verify (22)","verify (24)","docker"]'
43
+ release-id: \${{ inputs.release-id }}
44
+ version: \${{ inputs.version }}
45
+ source-sha: \${{ inputs.source-sha }}
46
+ artifact-sha256: \${{ inputs.artifact-sha256 }}
47
+ `;
48
+
49
+ test('publishing settings match the public trusted-publisher workflow', () => {
50
+ const settings = verifyPublishingSettings(pkg, workflow);
51
+ assert.equal(settings.package.private, false);
52
+ assert.equal(settings.package.access, 'public');
53
+ assert.equal(settings.package.tag, 'latest');
54
+ assert.equal(settings.workflow.package, pkg.name);
55
+ });
56
+
57
+ test('publishing settings reject private packages', () => {
58
+ assert.throws(
59
+ () => verifyPublishingSettings({...pkg, private: true}, workflow),
60
+ /must not set private:true/,
61
+ );
62
+ });
63
+
64
+ test('publishing settings reject non-public npm access', () => {
65
+ assert.throws(
66
+ () => verifyPublishingSettings({...pkg, publishConfig: {...pkg.publishConfig, access: 'restricted'}}, workflow),
67
+ /publishConfig\.access must be public/,
68
+ );
69
+ });
70
+
71
+ for (const [name, change] of [
72
+ ['commented repository guard', text => text.replace(' if:', ' # if:')],
73
+ ['weakened repository guard', text => text.replace("github.ref == 'refs/heads/main'", "github.ref == 'refs/heads/main' || true")],
74
+ ['commented workflow pin', text => text.replace(' uses:', ' # uses:')],
75
+ ['missing OIDC permission', text => text.replace(' id-token: write', '')],
76
+ ['OIDC permission under inputs', text => text.replace(' id-token: write\n', '').replace(' with:', ' with:\n id-token: write')],
77
+ ['duplicate job guard', text => text.replace(' permissions:', ' if: true\n permissions:')],
78
+ ['missing artifact input', text => text.split('\n').filter(line => !line.includes('artifact-sha256:')).join('\n')],
79
+ ['unpinned shared workflow', text => text.replace(/npm-beta-shared.yml@[a-f0-9]{40}/, 'npm-beta-shared.yml@main')],
80
+ ['mismatched publisher pin', text => text.replace(/publisher-sha: '[a-f0-9]{40}'/, "publisher-sha: '" + 'a'.repeat(40) + "'")],
81
+ ['wrong package input', text => text.replace("package: '@jc_stack/ez-library'", "package: '@jc_stack/other'")],
82
+ ]) {
83
+ test('publishing settings reject ' + name, () => {
84
+ assert.throws(() => verifyPublishingSettings(pkg, change(workflow)));
85
+ });
86
+ }
87
+
88
+ test('generated caller accepts comments, blank lines, CRLF and matching pin updates', () => {
89
+ const changed = workflow.replaceAll('fed05b9c88a5d96a801436a36983254758f03389', 'a'.repeat(40));
90
+ const settings = verifyPublishingSettings(pkg, '# uses: jdorado/ez-agents/.github/workflows/npm-beta-shared.yml@' + 'b'.repeat(40) + '\n\n' + changed.replaceAll('\n', ' \r\n'));
91
+ assert.equal(settings.workflow.publisherSha, 'a'.repeat(40));
92
+ });
93
+
94
+ for (const [name, changed] of [
95
+ ['wrong tag', {...pkg, publishConfig: {...pkg.publishConfig, tag: 'beta'}}],
96
+ ['wrong repository', {...pkg, repository: {url: 'git+https://github.com/other/ez-library.git'}}],
97
+ ]) {
98
+ test('publishing settings reject ' + name, () => {
99
+ assert.throws(() => verifyPublishingSettings(changed, workflow));
100
+ });
101
+ }
@@ -0,0 +1,120 @@
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 { existsSync } from 'node:fs';
8
+ import { execFileSync } from 'node:child_process';
9
+ import { put, organize, operation, hash } from '../src/store.mjs';
10
+ import { syncAdopt, syncPlan, syncRun, syncStatus, syncPolicy } from '../src/sync.mjs';
11
+ import { environment } from '../src/native.mjs';
12
+
13
+ async function fixture(t) {
14
+ const base = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), 'library-sync-')));
15
+ t.after(() => fs.rm(base, { recursive: true, force: true }));
16
+ const root = path.join(base, 'state'), remote = path.join(base, 'external');
17
+ await fs.mkdir(remote); return { base, root, remote };
18
+ }
19
+ const save = (root, name, text) => put(root, name, Readable.from([text]), { key: hash(name), expected: 'new' });
20
+ const nativeAvailable = existsSync('/usr/local/bin/rclone');
21
+
22
+ test('provider folder identity resolves real parent entries and rejects missing or ambiguous ancestors', async t => {
23
+ const { root } = await fixture(t);
24
+ execFileSync(process.execPath, ['--experimental-test-module-mocks', '--input-type=module', '-e', `
25
+ import { mock } from 'node:test';
26
+ import assert from 'node:assert/strict';
27
+ const native = await import('./src/native.mjs');
28
+ let mode = 'valid';
29
+ const visited = [];
30
+ mock.module('./src/native.mjs', { namedExports: { ...native, rclone: async (_, args) => {
31
+ if (args[0] === 'config') return { code: 0, stdout: JSON.stringify({ cloud: { type: 'drive' } }) };
32
+ if (args.includes('--recursive')) return { code: 0, stdout: '[]' };
33
+ assert(args.includes('--dirs-only'));
34
+ visited.push(args[1]);
35
+ const ancestor = args[1] === 'cloud:';
36
+ const entry = { IsDir: true, Path: ancestor ? 'personal' : 'notes', ID: ancestor ? 'parent-id' : 'vault-id' };
37
+ let entries = [entry];
38
+ if (mode === 'missing' && !ancestor) entries = [];
39
+ if (mode === 'duplicate' && ancestor) entries.push({ ...entry, ID: 'other-parent' });
40
+ if (mode === 'no-id' && !ancestor) delete entry.ID;
41
+ return { code: 0, stdout: JSON.stringify(entries) };
42
+ } } });
43
+ const { syncPlan } = await import('./src/sync.mjs');
44
+ assert.equal((await syncPlan(${JSON.stringify(root)}, 'cloud:personal/notes')).identity, 'drive:vault-id');
45
+ assert.deepEqual(visited, ['cloud:', 'cloud:personal']);
46
+ for (mode of ['missing', 'duplicate', 'no-id']) {
47
+ await assert.rejects(syncPlan(${JSON.stringify(root)}, 'cloud:personal/notes'), { code: 'CONFLICT' });
48
+ }
49
+ `], { cwd: new URL('..', import.meta.url), stdio: 'pipe' });
50
+ });
51
+
52
+ test('organization preserves bytes/history and refuses stale or occupied paths', async t => {
53
+ const { root } = await fixture(t);
54
+ const original = await save(root, 'inbox/a.md', 'An original note');
55
+ const request = { path: 'inbox/a.md', to: 'organized/a.md', expected: original.sha256, key: 'move-a' };
56
+ assert.equal((await organize(root, request)).state, 'moved');
57
+ assert.equal((await organize(root, request)).replay, true);
58
+ assert.equal((await operation(root, 'move-a')).state, 'moved');
59
+ await save(root, 'occupied.md', 'Do not replace');
60
+ await assert.rejects(organize(root, { ...request, path: request.to, to: 'occupied.md', key: 'occupied' }), { code: 'CONFLICT' });
61
+ await assert.rejects(organize(root, { path: request.to, expected: hash('stale'), key: 'stale' }), { code: 'CONFLICT' });
62
+ const remove = { path: request.to, expected: original.sha256, key: 'remove-a' };
63
+ assert.equal((await organize(root, remove)).state, 'removed');
64
+ assert.equal((await organize(root, remove)).replay, true);
65
+ assert.equal(await fs.readFile(path.join(root, 'history', original.sha256), 'utf8'), 'An original note');
66
+ });
67
+
68
+ test('sync is inert without binding; policy revisions and remote paths are guarded', async t => {
69
+ const { root } = await fixture(t);
70
+ assert.equal((await syncStatus(root)).config, null);
71
+ assert.equal((await syncRun(root)).state, 'unconfigured');
72
+ for (const remote of ['drive:', ':drive,token=secret:path', 'drive:../escape', root]) {
73
+ await assert.rejects(syncPlan(root, remote));
74
+ }
75
+ await assert.rejects(syncPolicy(root, { mode: 'two-way', expected: 'old' }), { code: 'CONFLICT' });
76
+ assert.equal(environment(root).TELEGRAM_BOT_TOKEN, undefined);
77
+ assert.equal(environment(root).NODE_OPTIONS, undefined);
78
+ assert.equal(environment(root).RCLONE_CONFIG, path.join(root, 'sync/rclone.conf'));
79
+ });
80
+
81
+ test('native adoption preserves a populated folder, empty files and directories; conflicts stop adoption', { skip: !nativeAvailable }, async t => {
82
+ const { root, remote } = await fixture(t);
83
+ await fs.mkdir(path.join(remote, 'empty-dir'));
84
+ await fs.writeFile(path.join(remote, 'existing.md'), 'Existing remote note');
85
+ await fs.writeFile(path.join(remote, 'empty.txt'), '');
86
+ await fs.writeFile(path.join(remote, '.private'), 'excluded');
87
+ const plan = await syncPlan(root, remote);
88
+ assert.equal(plan.remoteFiles, 2); assert.equal(plan.ready, true);
89
+ const adopted = await syncAdopt(root, remote);
90
+ assert.equal(adopted.config.mode, 'two-way');
91
+ assert.equal(await fs.readFile(path.join(root, 'files/existing.md'), 'utf8'), 'Existing remote note');
92
+ assert.equal((await fs.stat(path.join(root, 'files/empty.txt'))).size, 0);
93
+ assert((await fs.stat(path.join(root, 'files/empty-dir'))).isDirectory());
94
+ assert(!existsSync(path.join(root, 'files/.private')));
95
+ await assert.rejects(syncAdopt(root, remote), { code: 'CONFLICT' });
96
+ const paused = await syncPolicy(root, { expected: adopted.revision, mode: 'paused', intervalSeconds: 30 });
97
+ assert.equal(paused.config.mode, 'paused');
98
+ assert.equal((await syncRun(root)).state, 'paused');
99
+ await assert.rejects(syncPolicy(root, { expected: adopted.revision, mode: 'two-way' }), { code: 'CONFLICT' });
100
+
101
+ const other = await fixture(t);
102
+ await fs.writeFile(path.join(other.remote, 'same.md'), 'remote');
103
+ await save(other.root, 'same.md', 'local');
104
+ assert.equal((await syncPlan(other.root, other.remote)).ready, false);
105
+ await assert.rejects(syncAdopt(other.root, other.remote), { code: 'CONFLICT' });
106
+ assert.equal(await fs.readFile(path.join(other.root, 'files/same.md'), 'utf8'), 'local');
107
+ assert.equal(await fs.readFile(path.join(other.remote, 'same.md'), 'utf8'), 'remote');
108
+ });
109
+
110
+ test('a deleted or replaced mapped root blocks transfers without recreating it', { skip: !nativeAvailable }, async t => {
111
+ const { root, remote } = await fixture(t);
112
+ await fs.writeFile(path.join(remote, 'kept.md'), 'Preserve me');
113
+ await syncAdopt(root, remote);
114
+ await fs.rename(remote, remote + '-deleted');
115
+ await assert.rejects(syncRun(root));
116
+ assert(!existsSync(remote));
117
+ await fs.mkdir(remote);
118
+ await assert.rejects(syncRun(root), { code: 'CONFLICT' });
119
+ assert.equal(await fs.readFile(path.join(root, 'files/kept.md'), 'utf8'), 'Preserve me');
120
+ });