@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.
- package/.dockerignore +12 -0
- package/.github/workflows/publish-beta.yml +40 -0
- package/CHANGELOG.md +57 -0
- package/CONTRIBUTING.md +89 -0
- package/Dockerfile +38 -0
- package/LICENSE +21 -0
- package/README.md +119 -0
- package/SECURITY.md +13 -0
- package/THIRD_PARTY_NOTICES.md +9 -0
- package/bin/ez-library.mjs +3 -0
- package/docker/fulltext-smoke.mjs +19 -0
- package/docker/github-smoke.mjs +114 -0
- package/docker/manager-smoke.mjs +53 -0
- package/docker/pnpm-lock.yaml +1443 -0
- package/docker/shared-smoke.mjs +81 -0
- package/docker/smoke.mjs +73 -0
- package/docker/sync-smoke.mjs +98 -0
- package/docker/text-mirror-smoke.mjs +42 -0
- package/docs/folder-sync.md +100 -0
- package/docs/github-sync.md +105 -0
- package/docs/named-libraries.md +75 -0
- package/docs/persistence.md +48 -0
- package/docs/rclone-LICENSE.txt +19 -0
- package/docs/releasing.md +74 -0
- package/docs/shared-embeddings.md +15 -0
- package/docs/text-mirror.md +54 -0
- package/ez-deployment.json +53 -0
- package/ez-plugin.json +15 -0
- package/package.json +69 -0
- package/patches/@tobilu__qmd@2.8.3.patch +60 -0
- package/scripts/publish-settings.mjs +101 -0
- package/scripts/release-check.mjs +16 -0
- package/skills/library/SKILL.md +104 -0
- package/src/cli.mjs +227 -0
- package/src/embedding-client.mjs +50 -0
- package/src/embedding-worker.mjs +59 -0
- package/src/git-mirror.mjs +121 -0
- package/src/git-sync.mjs +140 -0
- package/src/indexer.mjs +83 -0
- package/src/libraries.mjs +81 -0
- package/src/native.mjs +47 -0
- package/src/store.mjs +214 -0
- package/src/sync-worker.mjs +43 -0
- package/src/sync.mjs +172 -0
- package/test/embeddings.test.mjs +30 -0
- package/test/git-mirror.test.mjs +121 -0
- package/test/git-sync.test.mjs +135 -0
- package/test/indexer.test.mjs +73 -0
- package/test/libraries.test.mjs +132 -0
- package/test/library.test.mjs +163 -0
- package/test/publish-settings.test.mjs +101 -0
- package/test/sync.test.mjs +120 -0
package/src/git-sync.mjs
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { atomic, fail, hash, jsonBytes, locked, safePath, settings } from './store.mjs';
|
|
4
|
+
import { native, succeeded } from './native.mjs';
|
|
5
|
+
import { inventory } from './indexer.mjs';
|
|
6
|
+
|
|
7
|
+
const quote = s => "'" + s.replaceAll("'", "'\\''") + "'";
|
|
8
|
+
const privateDir = (root, repo) => path.join(root, 'sync/keys', hash(repo));
|
|
9
|
+
export function repositoryURL(repository) {
|
|
10
|
+
if (typeof repository === 'string' && /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository) && !repository.split('/').some(x => x.startsWith('.'))) return `git@github.com:${repository}.git`;
|
|
11
|
+
if (typeof repository === 'string' && path.isAbsolute(repository) && !/[\x00-\x1f]/.test(repository)) return repository;
|
|
12
|
+
fail('INVALID', 'Use owner/repository or an explicitly selected local bare repository');
|
|
13
|
+
}
|
|
14
|
+
export async function gitKey(root, repository) {
|
|
15
|
+
if (path.isAbsolute(repositoryURL(repository))) fail('INVALID', 'Local Git needs no deploy key');
|
|
16
|
+
return locked(root, async root => {
|
|
17
|
+
const dir = privateDir(root, repository);
|
|
18
|
+
await safePath(root, path.relative(root, dir) + '/key', true);
|
|
19
|
+
const key = path.join(dir, 'key');
|
|
20
|
+
try { await fs.access(key); }
|
|
21
|
+
catch (e) {
|
|
22
|
+
if (e.code !== 'ENOENT') throw e;
|
|
23
|
+
succeeded(await native(root, '/usr/bin/ssh-keygen', ['-t', 'ed25519', '-N', '', '-C', 'Ez Library repository sync', '-f', key]), 'Generate repository key');
|
|
24
|
+
}
|
|
25
|
+
// Public trust material is fetched over authenticated HTTPS, never TOFU.
|
|
26
|
+
const response = await fetch('https://api.github.com/meta', { redirect: 'error', signal: AbortSignal.timeout(15000), headers: { 'User-Agent': 'ez-library' } });
|
|
27
|
+
if (!response.ok) fail('UNAVAILABLE', 'Cannot verify GitHub SSH host keys');
|
|
28
|
+
const { ssh_keys: keys } = await response.json();
|
|
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
|
+
await atomic(path.join(dir, 'known_hosts'), keys.map(k => 'github.com ' + k).join('\n') + '\n');
|
|
31
|
+
return { repository, publicKey: (await fs.readFile(key + '.pub', 'utf8')).trim(), registration: 'Register this public key with write access through the connected GitHub plugin. Private key stays in Library.' };
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function git(root, config, args, options = {}) {
|
|
36
|
+
const dir = privateDir(root, config.repository);
|
|
37
|
+
const workTree = path.join(root, config.textMirror ? 'sync/text-mirror/files' : 'files');
|
|
38
|
+
const gitDir = path.join(root, config.textMirror ? 'sync/text-mirror/git' : 'sync/git');
|
|
39
|
+
return native(root, '/usr/bin/git', ['-C', workTree, '--git-dir=' + gitDir, '--work-tree=' + workTree,
|
|
40
|
+
'-c', 'core.hooksPath=/dev/null', '-c', 'core.autocrlf=false', '-c', 'core.filemode=false',
|
|
41
|
+
'-c', 'user.name=Ez Library', '-c', 'user.email=library@localhost', ...args], {
|
|
42
|
+
...options, env: { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_TERMINAL_PROMPT: '0',
|
|
43
|
+
GIT_ALLOW_PROTOCOL: path.isAbsolute(config.repository) ? 'file' : 'ssh',
|
|
44
|
+
GIT_SSH_COMMAND: ['/usr/bin/ssh', '-F', '/dev/null', '-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'IdentitiesOnly=yes',
|
|
45
|
+
'-o', 'StrictHostKeyChecking=yes', '-o', 'UserKnownHostsFile=' + path.join(dir, 'known_hosts'), '-i', path.join(dir, 'key')].map(quote).join(' ') } });
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function tree(root, config, ref) {
|
|
49
|
+
const output = succeeded(await git(root, config, ['ls-tree', '-rz', '--full-tree', ref]), 'Read repository tree');
|
|
50
|
+
const entries = [];
|
|
51
|
+
for (const record of output.split('\0').filter(Boolean)) {
|
|
52
|
+
const match = /^(100644|100755) blob ([a-f0-9]+)\t([\s\S]+)$/.exec(record);
|
|
53
|
+
if (!match) fail('UNSAFE_PATH', 'Git sync does not support symlinks or submodules');
|
|
54
|
+
const name = match[3];
|
|
55
|
+
// Git metadata paths may exist in the repository, but are never executable
|
|
56
|
+
// workspace policy. Reject traversal/control paths and Git's own directory.
|
|
57
|
+
if (/[\x00-\x1f\\]/.test(name) || name.split('/').some(x => !x || x === '.' || x === '..' || x.toLowerCase() === '.git')) fail('UNSAFE_PATH', 'Unsafe repository path');
|
|
58
|
+
entries.push({ path: name, oid: match[2] });
|
|
59
|
+
}
|
|
60
|
+
return entries;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function checkPolicy(root, repository, branch) {
|
|
64
|
+
const storage = (await settings(root)).settings.storage;
|
|
65
|
+
if (['hybrid', 'drive'].includes(storage.mode)) fail('CONFLICT', 'GitHub-only sync cannot override Drive/Hybrid policy; review and change storage policy before adopting');
|
|
66
|
+
if (storage.mode === 'github' && (storage.github.repository !== repository || storage.github.branch !== branch)) fail('CONFLICT', 'Git binding must match configured repository and branch');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export async function gitAdopt(root, repository, branch = 'main', stateRoot = root) {
|
|
70
|
+
const remote = repositoryURL(repository);
|
|
71
|
+
return locked(root, async root => {
|
|
72
|
+
await checkPolicy(root, repository, branch);
|
|
73
|
+
if (path.isAbsolute(remote)) {
|
|
74
|
+
const real = await fs.realpath(remote), base = await fs.realpath(stateRoot);
|
|
75
|
+
if (real !== remote || real === base || real.startsWith(base + '/') || base.startsWith(real + '/')) fail('UNSAFE_PATH', 'Git source must be outside Library state');
|
|
76
|
+
}
|
|
77
|
+
await fs.mkdir(path.join(root, 'sync'), { recursive: true, mode: 0o700 });
|
|
78
|
+
const binding = await safePath(root, 'sync/config.json');
|
|
79
|
+
try { await fs.access(binding); fail('CONFLICT', 'A sync binding already exists'); } catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
80
|
+
// Local state can be preserved in-place only when the remote has the same
|
|
81
|
+
// bytes at every existing path. Extra local files stay as pending additions.
|
|
82
|
+
const local = await inventory(path.join(root, 'files'), '', { includeHidden: true });
|
|
83
|
+
const config = { schemaVersion: 1, backend: 'git', repository, branch, mode: 'paused', intervalSeconds: 60 };
|
|
84
|
+
succeeded(await git(root, config, ['check-ref-format', '--branch', branch]), 'Validate branch');
|
|
85
|
+
const repoDir = await safePath(root, 'sync/git/probe', true);
|
|
86
|
+
await fs.mkdir(path.dirname(repoDir), { recursive: true, mode: 0o700 });
|
|
87
|
+
succeeded(await native(root, '/usr/bin/git', ['init', '--bare', path.join(root, 'sync/git')], { env: { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' } }), 'Initialize Git');
|
|
88
|
+
succeeded(await git(root, config, ['config', 'core.bare', 'false']), 'Configure Git');
|
|
89
|
+
succeeded(await git(root, config, ['remote', 'add', 'origin', remote]), 'Set Git remote');
|
|
90
|
+
// A failed setup leaves the prepared binding paused, never silently rebound.
|
|
91
|
+
await atomic(binding, jsonBytes(config));
|
|
92
|
+
succeeded(await git(root, config, ['fetch', '--no-tags', 'origin', 'refs/heads/' + branch]), 'Fetch existing branch');
|
|
93
|
+
const entries = await tree(root, config, 'FETCH_HEAD');
|
|
94
|
+
const existing = new Map(local.map(f => [f.path, f]));
|
|
95
|
+
for (const entry of entries) {
|
|
96
|
+
if (!existing.has(entry.path)) continue;
|
|
97
|
+
const oid = succeeded(await git(root, config, ['hash-object', '--no-filters', '--', path.join(root, 'files', entry.path)]), 'Check local original').trim();
|
|
98
|
+
if (oid !== entry.oid) fail('CONFLICT', 'Existing local original differs from Git: ' + entry.path);
|
|
99
|
+
}
|
|
100
|
+
succeeded(await git(root, config, ['symbolic-ref', 'HEAD', 'refs/heads/' + branch]), 'Select branch');
|
|
101
|
+
succeeded(await git(root, config, ['reset', '--mixed', 'FETCH_HEAD']), 'Initialize native index');
|
|
102
|
+
const missing = entries.filter(e => !existing.has(e.path)).map(e => e.path + '\0').join('');
|
|
103
|
+
if (missing) succeeded(await git(root, config, ['checkout-index', '-z', '--stdin'], { input: missing }), 'Import tracked files');
|
|
104
|
+
config.mode = 'two-way';
|
|
105
|
+
await atomic(binding, jsonBytes(config));
|
|
106
|
+
return { config, imported: entries.length, indexing: 'pending' };
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export async function gitTransfer(root, config) {
|
|
111
|
+
await checkPolicy(root, config.repository, config.branch);
|
|
112
|
+
const actualRemote = succeeded(await git(root, config, ['remote', 'get-url', 'origin']), 'Check bound remote').trim();
|
|
113
|
+
if (actualRemote !== repositoryURL(config.repository)) fail('CONFLICT', 'Git remote no longer matches the Library binding');
|
|
114
|
+
const conflict = succeeded(await git(root, config, ['ls-files', '--unmerged']), 'Inspect merge state');
|
|
115
|
+
if (conflict) fail('CONFLICT', 'Git merge unresolved; use native git status/show/add to resolve both retained versions before syncing');
|
|
116
|
+
const files = await inventory(path.join(root, 'files'), '', { includeHidden: true });
|
|
117
|
+
if (files.some(f => f.bytes >= 100 * 1024 * 1024)) fail('TOO_LARGE', 'GitHub ordinary files must be below 100 MiB; select another storage mode for larger media');
|
|
118
|
+
succeeded(await git(root, config, ['add', '--all', '--', '.']), 'Stage Library changes');
|
|
119
|
+
const stagedTree = succeeded(await git(root, config, ['write-tree']), 'Read staged tree').trim();
|
|
120
|
+
await tree(root, config, stagedTree);
|
|
121
|
+
const ignored = succeeded(await git(root, config, ['ls-files', '--others', '--ignored', '--exclude-standard', '-z']), 'Inspect ignored files').split('\0').filter(Boolean);
|
|
122
|
+
if (ignored.some(name => files.some(file => file.path === name))) fail('CONFLICT', 'Library files are excluded by repository ignore rules; reconcile the rules before claiming synchronization');
|
|
123
|
+
const diff = await git(root, config, ['diff', '--cached', '--quiet']);
|
|
124
|
+
if (![0, 1].includes(diff.code)) succeeded(diff, 'Inspect staged changes');
|
|
125
|
+
const merging = await git(root, config, ['rev-parse', '--verify', 'MERGE_HEAD']);
|
|
126
|
+
if (diff.code === 1 || merging.code === 0) succeeded(await git(root, config, ['commit', '--no-gpg-sign', '-m', 'Sync Library changes']), 'Commit Library changes');
|
|
127
|
+
succeeded(await git(root, config, ['fetch', '--no-tags', 'origin', 'refs/heads/' + config.branch]), 'Fetch remote changes');
|
|
128
|
+
await tree(root, config, 'FETCH_HEAD');
|
|
129
|
+
const head = succeeded(await git(root, config, ['rev-parse', 'HEAD']), 'Read local commit').trim();
|
|
130
|
+
const merge = await git(root, config, ['merge', '--no-edit', '--no-gpg-sign', 'FETCH_HEAD']);
|
|
131
|
+
if (merge.code !== 0) {
|
|
132
|
+
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');
|
|
133
|
+
succeeded(merge, 'Merge remote changes');
|
|
134
|
+
}
|
|
135
|
+
const commit = succeeded(await git(root, config, ['rev-parse', 'HEAD']), 'Read synchronized commit').trim();
|
|
136
|
+
succeeded(await git(root, config, ['push', 'origin', 'HEAD:refs/heads/' + config.branch]), 'Push Library changes');
|
|
137
|
+
const remote = succeeded(await git(root, config, ['ls-remote', '--exit-code', 'origin', 'refs/heads/' + config.branch]), 'Verify remote commit').trim().split(/\s+/)[0];
|
|
138
|
+
if (remote !== commit) fail('UNCERTAIN', 'Remote advanced during verification; fetch/reconcile on the next cycle');
|
|
139
|
+
return { commit, previousCommit: head, remoteVerified: true };
|
|
140
|
+
}
|
package/src/indexer.mjs
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { atomic, digest, hash, jsonBytes, safePath, settings } from './store.mjs';
|
|
4
|
+
import { native, qmd, succeeded } from './native.mjs';
|
|
5
|
+
|
|
6
|
+
export async function inventory(directory, relative = '', { includeHidden = false } = {}) {
|
|
7
|
+
const result = [];
|
|
8
|
+
for (const item of (await fs.readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
9
|
+
if (!includeHidden && item.name.startsWith('.')) continue;
|
|
10
|
+
const name = relative + item.name, file = path.join(directory, item.name);
|
|
11
|
+
if (item.isDirectory()) result.push(...await inventory(file, name + '/', { includeHidden }));
|
|
12
|
+
else if (item.isFile()) result.push({ path: name, ...(await digest(file)) });
|
|
13
|
+
else throw Error('Unsupported symlink or special file in Library');
|
|
14
|
+
}
|
|
15
|
+
return result;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Derived text is a rebuildable cache, outside the mirrored originals. Never
|
|
19
|
+
// overwrite an owner's note to regenerate PDF extraction.
|
|
20
|
+
export async function refreshIndex(root) {
|
|
21
|
+
const configured = await settings(root);
|
|
22
|
+
const embed = process.env.EZ_LIBRARY_EMBED !== '0' && configured.settings.indexing?.mode !== 'keyword';
|
|
23
|
+
const cache = path.join(root, 'index-text');
|
|
24
|
+
await fs.mkdir(cache, { recursive: true, mode: 0o700 });
|
|
25
|
+
if ((await fs.lstat(cache)).isSymbolicLink()) throw Error('Extraction cache cannot be a symlink');
|
|
26
|
+
const files = await inventory(path.join(root, 'files'));
|
|
27
|
+
const fingerprint = hash(jsonBytes(files));
|
|
28
|
+
await fs.mkdir(path.join(root, 'sync'), { recursive: true, mode: 0o700 });
|
|
29
|
+
const ledgerFile = path.join(root, 'sync/index.json');
|
|
30
|
+
const before = await fs.readFile(ledgerFile, 'utf8').then(JSON.parse).catch(e => { if (e.code === 'ENOENT') return {}; throw e; });
|
|
31
|
+
const semantic = embed && Boolean(process.env.EZ_LIBRARY_EMBED_SOCKET);
|
|
32
|
+
if (before.fingerprint === fingerprint) {
|
|
33
|
+
if (semantic && before.embedded) return before;
|
|
34
|
+
if (!semantic) {
|
|
35
|
+
if (!before.embedded && before.embeddingState === 'off') return before;
|
|
36
|
+
const indexed = { ...before, embedded: false, embeddingState: 'off' };
|
|
37
|
+
await atomic(ledgerFile, jsonBytes(indexed));
|
|
38
|
+
return indexed;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const extracted = {}, pending = [];
|
|
42
|
+
for (const file of files.filter(f => /\.pdf$/i.test(f.path))) {
|
|
43
|
+
const target = await safePath(root, 'index-text/' + file.path + '.md', true);
|
|
44
|
+
if (before.extracted?.[file.path] !== file.sha256) {
|
|
45
|
+
const source = await safePath(root, 'files/' + file.path);
|
|
46
|
+
const result = await native(root, '/usr/bin/pdftotext', ['-layout', '-enc', 'UTF-8', source, '-']);
|
|
47
|
+
if (result.code !== 0 || !result.stdout.trim()) {
|
|
48
|
+
pending.push({ path: file.path, reason: result.code ? 'pdf-extraction-failed' : 'ocr-required' });
|
|
49
|
+
await fs.rm(target, { force: true }); continue;
|
|
50
|
+
}
|
|
51
|
+
const pages = result.stdout.split('\f').map((text, i) => `## Page ${i + 1}\n\n${text.trim()}\n`).join('\n');
|
|
52
|
+
await atomic(target, `# ${file.path}\n\nOriginal Library path: ${JSON.stringify(file.path)}\nSHA-256: ${file.sha256}\n\n${pages}`);
|
|
53
|
+
}
|
|
54
|
+
extracted[file.path] = file.sha256;
|
|
55
|
+
}
|
|
56
|
+
for (const old of Object.keys(before.extracted || {})) {
|
|
57
|
+
if (!extracted[old]) await fs.rm(await safePath(root, 'index-text/' + old + '.md'), { force: true });
|
|
58
|
+
}
|
|
59
|
+
const listed = succeeded(await qmd(root, ['collection', 'list']), 'QMD collection list');
|
|
60
|
+
for (const [name, dir, mask] of [['library', 'files', '**/*.{md,txt}'], ['library-pdf', 'index-text', '**/*.md']]) {
|
|
61
|
+
if (!listed.includes(`qmd://${name}/`)) succeeded(await qmd(root, ['collection', 'add', path.join(root, dir), '--name', name, '--mask', mask]), 'QMD collection add');
|
|
62
|
+
}
|
|
63
|
+
succeeded(await qmd(root, ['update']), 'QMD update');
|
|
64
|
+
const conflicts = files.filter(f => /\.conflict-(local|remote)/.test(f.path)).map(f => f.path);
|
|
65
|
+
const indexed = { fingerprint, extracted, pending, conflicts, indexedAt: new Date().toISOString(), embedded: false, embeddingState: semantic ? 'indexing' : 'off' };
|
|
66
|
+
await atomic(ledgerFile, jsonBytes(indexed));
|
|
67
|
+
if (!semantic) return indexed;
|
|
68
|
+
try { succeeded(await qmd(root, ['embed', '--no-gpu', '--max-docs-per-batch', '8']), 'QMD embed'); }
|
|
69
|
+
catch (error) { indexed.embeddingState = 'unavailable'; await atomic(ledgerFile, jsonBytes(indexed)); throw error; }
|
|
70
|
+
indexed.embedded = true;
|
|
71
|
+
indexed.embeddingState = 'ready';
|
|
72
|
+
await atomic(ledgerFile, jsonBytes(indexed));
|
|
73
|
+
return indexed;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function indexStatus(root) {
|
|
77
|
+
const before = await fs.readFile(path.join(root, 'sync/index.json'), 'utf8').then(JSON.parse).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
|
|
78
|
+
const configured = await settings(root);
|
|
79
|
+
if (process.env.EZ_LIBRARY_EMBED === '0' || !process.env.EZ_LIBRARY_EMBED_SOCKET || configured.settings.indexing?.mode === 'keyword') return { state: 'off', indexedAt: before?.indexedAt || null };
|
|
80
|
+
if (!before) return { state: 'pending', indexedAt: null };
|
|
81
|
+
const fingerprint = hash(jsonBytes(await inventory(path.join(root, 'files'))));
|
|
82
|
+
return { state: fingerprint === before.fingerprint ? before.embeddingState : 'pending', indexedAt: before.indexedAt };
|
|
83
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { atomic, fail, hash, initialize, jsonBytes, locked, rootDir, safePath, settings } from './store.mjs';
|
|
4
|
+
import { syncStatus } from './sync.mjs';
|
|
5
|
+
import { qmd, succeeded } from './native.mjs';
|
|
6
|
+
|
|
7
|
+
const initial = { schemaVersion: 1, libraries: [{ name: 'default', description: 'Original library' }] };
|
|
8
|
+
const validName = name => typeof name === 'string' && /^[a-z][a-z0-9-]{0,47}$/.test(name);
|
|
9
|
+
export async function catalog(base) {
|
|
10
|
+
let value = initial;
|
|
11
|
+
try {
|
|
12
|
+
await rootDir(base);
|
|
13
|
+
value = JSON.parse(await fs.readFile(await safePath(base, 'libraries.json'), 'utf8'));
|
|
14
|
+
} catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
15
|
+
if (value.schemaVersion !== 1 || !Array.isArray(value.libraries) || !value.libraries.length ||
|
|
16
|
+
value.libraries[0]?.name !== 'default' || new Set(value.libraries.map(x => x.name)).size !== value.libraries.length ||
|
|
17
|
+
value.libraries.some(x => !validName(x.name) || typeof x.description !== 'string' || !x.description.trim() || x.description.length > 512)) {
|
|
18
|
+
fail('INVALID', 'Invalid library catalog; preserve state and inspect libraries.json');
|
|
19
|
+
}
|
|
20
|
+
return { ...value, revision: hash(jsonBytes(value)) };
|
|
21
|
+
}
|
|
22
|
+
export async function libraryRoot(base, name) {
|
|
23
|
+
if (!validName(name)) fail('INVALID', 'Use a library name from sources');
|
|
24
|
+
if (name === 'default') return base;
|
|
25
|
+
// Check every intermediate component before allowing initialize() to create it.
|
|
26
|
+
await safePath(base, `libraries/${name}/settings.json`);
|
|
27
|
+
return path.join(base, 'libraries', name);
|
|
28
|
+
}
|
|
29
|
+
export async function selectLibrary(base, name) {
|
|
30
|
+
const current = await catalog(base);
|
|
31
|
+
if (!name && current.libraries.length !== 1) fail('INVALID', 'Multiple libraries: supply --library NAME; use sources to choose');
|
|
32
|
+
name ||= current.libraries[0].name;
|
|
33
|
+
if (!current.libraries.some(x => x.name === name)) fail('INVALID', 'Unknown library; use sources or source-add');
|
|
34
|
+
return { name, root: await libraryRoot(base, name) };
|
|
35
|
+
}
|
|
36
|
+
export async function addLibrary(base, name, description) {
|
|
37
|
+
if (!validName(name) || name === 'default' || typeof description !== 'string' || !description.trim() || description.length > 512 || /[\x00-\x1f\x7f]/.test(description)) {
|
|
38
|
+
fail('INVALID', 'Supply a new lowercase library name and a one-line description (1–512 characters)');
|
|
39
|
+
}
|
|
40
|
+
return locked(base, async base => {
|
|
41
|
+
const current = await catalog(base);
|
|
42
|
+
const existing = current.libraries.find(x => x.name === name);
|
|
43
|
+
if (existing) {
|
|
44
|
+
if (existing.description !== description) fail('CONFLICT', 'Library already exists with another description');
|
|
45
|
+
return { name, revision: current.revision, existing: true };
|
|
46
|
+
}
|
|
47
|
+
await initialize(await libraryRoot(base, name));
|
|
48
|
+
const value = { schemaVersion: 1, libraries: [...current.libraries, { name, description }] };
|
|
49
|
+
await atomic(await safePath(base, 'libraries.json'), jsonBytes(value));
|
|
50
|
+
return { name, revision: hash(jsonBytes(value)), instruction: 'Refresh the workspace TOOLS.md library names and purposes from sources before routing subsequent saves.' };
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
export async function sources(base) {
|
|
54
|
+
const current = await catalog(base);
|
|
55
|
+
const libraries = [];
|
|
56
|
+
for (const entry of current.libraries) {
|
|
57
|
+
const root = await libraryRoot(base, entry.name);
|
|
58
|
+
const policy = await settings(root);
|
|
59
|
+
const sync = await syncStatus(root);
|
|
60
|
+
libraries.push({ ...entry, root, storage: policy.settings.storage, sync });
|
|
61
|
+
}
|
|
62
|
+
return { revision: current.revision, selectionRequired: libraries.length > 1, libraries };
|
|
63
|
+
}
|
|
64
|
+
export async function searchLibraries(base, { name, all, query, limit = 5 }, search = qmd) {
|
|
65
|
+
if (typeof query !== 'string' || !query.trim() || !Number.isInteger(limit) || limit < 1 || limit > 100 || (all && name)) fail('INVALID', 'Supply a query, limit 1–100, and either --all or --library NAME');
|
|
66
|
+
const entries = all ? (await catalog(base)).libraries : [{ name: (await selectLibrary(base, name)).name }];
|
|
67
|
+
const libraries = [];
|
|
68
|
+
for (const entry of entries) {
|
|
69
|
+
try {
|
|
70
|
+
const root = await libraryRoot(base, entry.name);
|
|
71
|
+
const results = await locked(root, async () => {
|
|
72
|
+
const output = succeeded(await search(root, ['search', query, '--json', '-n', String(limit)]), 'QMD search');
|
|
73
|
+
const matches = JSON.parse(output);
|
|
74
|
+
if (!Array.isArray(matches)) fail('UNAVAILABLE', 'QMD search did not return an array');
|
|
75
|
+
return matches.map(match => ({ ...match, library: entry.name }));
|
|
76
|
+
});
|
|
77
|
+
libraries.push({ library: entry.name, results });
|
|
78
|
+
} catch (error) { libraries.push({ library: entry.name, error: { code: error.code || 'UNAVAILABLE', message: error.message } }); }
|
|
79
|
+
}
|
|
80
|
+
return { complete: libraries.every(x => !x.error), limitPerLibrary: limit, libraries };
|
|
81
|
+
}
|
package/src/native.mjs
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { fail } from './store.mjs';
|
|
5
|
+
|
|
6
|
+
export function environment(root) {
|
|
7
|
+
return { PATH: '/usr/local/bin:/usr/bin:/bin', HOME: path.join(root, 'qmd'),
|
|
8
|
+
XDG_CONFIG_HOME: path.join(root, 'qmd/config'), XDG_CACHE_HOME: path.join(root, 'qmd/cache'),
|
|
9
|
+
QMD_CONFIG_DIR: path.join(root, 'qmd/config/qmd'), QMD_EMBED_MODULE: new URL('./embedding-client.mjs', import.meta.url).href,
|
|
10
|
+
...(process.env.EZ_LIBRARY_EMBED_SOCKET ? { EZ_LIBRARY_EMBED_SOCKET: process.env.EZ_LIBRARY_EMBED_SOCKET } : {}), LANG: 'C.UTF-8',
|
|
11
|
+
RCLONE_CONFIG: path.join(root, 'sync/rclone.conf') };
|
|
12
|
+
}
|
|
13
|
+
export function native(root, executable, args, { inherit = false, env = {}, input } = {}) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
const child = spawn(executable, args, { cwd: root, env: { ...environment(root), ...env }, stdio: inherit ? 'inherit' : [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'] });
|
|
16
|
+
if (!inherit && input !== undefined) { child.stdin.on('error', () => {}); child.stdin.end(input); }
|
|
17
|
+
let out = '', err = '', bytes = 0;
|
|
18
|
+
const collect = (chunk, stderr) => {
|
|
19
|
+
bytes += chunk.length;
|
|
20
|
+
if (bytes > 32 * 1024 * 1024) { child.kill('SIGTERM'); return; }
|
|
21
|
+
if (stderr) err += chunk; else out += chunk;
|
|
22
|
+
};
|
|
23
|
+
child.stdout?.on('data', x => collect(x, false)); child.stderr?.on('data', x => collect(x, true));
|
|
24
|
+
const terminate = () => child.kill('SIGTERM');
|
|
25
|
+
const interrupt = () => child.kill('SIGINT');
|
|
26
|
+
process.once('SIGTERM', terminate); process.once('SIGINT', interrupt);
|
|
27
|
+
const cleanup = () => { process.removeListener('SIGTERM', terminate); process.removeListener('SIGINT', interrupt); };
|
|
28
|
+
child.once('error', e => { cleanup(); reject(e); });
|
|
29
|
+
child.once('close', code => {
|
|
30
|
+
cleanup();
|
|
31
|
+
if (bytes > 32 * 1024 * 1024) reject(Error('Native output exceeded 32 MiB'));
|
|
32
|
+
else resolve({ code: code ?? 130, stdout: out, stderr: err });
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
export async function rclone(root, args, options) {
|
|
37
|
+
return native(root, '/usr/local/bin/rclone', args, options);
|
|
38
|
+
}
|
|
39
|
+
export async function qmd(root, args) {
|
|
40
|
+
if (args.includes('pull')) throw Error('Library does not download per-agent models; enable shared embeddings through Ez');
|
|
41
|
+
const cli = fileURLToPath(new URL('./cli/qmd.js', import.meta.resolve('@tobilu/qmd')));
|
|
42
|
+
return native(root, process.execPath, [cli, ...args]);
|
|
43
|
+
}
|
|
44
|
+
export function succeeded(result, label) {
|
|
45
|
+
if (result.code !== 0) fail('UNAVAILABLE', `${label} exited ${result.code}: ${result.stderr.slice(-4000)}`);
|
|
46
|
+
return result.stdout;
|
|
47
|
+
}
|
package/src/store.mjs
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
import * as fs from 'node:fs/promises';
|
|
2
|
+
import { createReadStream, createWriteStream, constants } from 'node:fs';
|
|
3
|
+
import { pipeline } from 'node:stream/promises';
|
|
4
|
+
import { Transform } from 'node:stream';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
7
|
+
|
|
8
|
+
export class LibraryError extends Error {
|
|
9
|
+
constructor(code, message) { super(message); this.code = code; }
|
|
10
|
+
}
|
|
11
|
+
export const fail = (code, message) => { throw new LibraryError(code, message); };
|
|
12
|
+
export const hash = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
13
|
+
export const MAX_FILE_BYTES = 512 * 1024 * 1024;
|
|
14
|
+
export const defaults = () => ({ schemaVersion: 1, storage: { mode: 'local' }, backup: { mode: 'off' } });
|
|
15
|
+
|
|
16
|
+
function keys(value, allowed) {
|
|
17
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(k => !allowed.includes(k))) fail('INVALID', 'Unknown or invalid settings fields');
|
|
18
|
+
}
|
|
19
|
+
function ref(value) {
|
|
20
|
+
if (typeof value !== 'string' || !/^[A-Za-z0-9_.:@/-]{1,160}$/.test(value)) fail('INVALID', 'Expected an opaque connection or destination reference, not credentials');
|
|
21
|
+
}
|
|
22
|
+
export function validateSettings(s) {
|
|
23
|
+
keys(s, ['schemaVersion', 'storage', 'backup', 'indexing']);
|
|
24
|
+
if (s.schemaVersion !== 1) fail('INVALID', 'Unsupported settings schema');
|
|
25
|
+
keys(s.storage, ['mode', 'github', 'drive', 'githubExtensions', 'maxGithubBytes']);
|
|
26
|
+
const { mode, github, drive, githubExtensions, maxGithubBytes } = s.storage;
|
|
27
|
+
if (!['local', 'github', 'drive', 'hybrid'].includes(mode)) fail('INVALID', 'Unknown storage mode');
|
|
28
|
+
if (github !== undefined) {
|
|
29
|
+
keys(github, ['connection', 'repository', 'branch']); ref(github.connection); ref(github.branch);
|
|
30
|
+
if (typeof github.repository !== 'string' || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(github.repository)) fail('INVALID', 'Expected owner/repository');
|
|
31
|
+
}
|
|
32
|
+
if (drive !== undefined) { keys(drive, ['connection', 'folderId']); ref(drive.connection); ref(drive.folderId); }
|
|
33
|
+
if (['github', 'hybrid'].includes(mode) && !github) fail('INVALID', 'GitHub mode requires an explicit connection, repository and branch');
|
|
34
|
+
if (['drive', 'hybrid'].includes(mode) && !drive) fail('INVALID', 'Drive mode requires an explicit connection and folder ID');
|
|
35
|
+
if ((mode === 'local' && (github || drive)) || (mode === 'github' && drive) || (mode === 'drive' && github)) fail('INVALID', 'Destination does not match storage mode');
|
|
36
|
+
if (mode === 'hybrid') {
|
|
37
|
+
if (!Array.isArray(githubExtensions) || !githubExtensions.length || githubExtensions.some(x => typeof x !== 'string' || !/^\.[a-z0-9]{1,12}$/.test(x))) fail('INVALID', 'Hybrid mode requires explicit lowercase GitHub extensions');
|
|
38
|
+
if (!Number.isSafeInteger(maxGithubBytes) || maxGithubBytes < 1 || maxGithubBytes >= 100 * 1024 * 1024) fail('INVALID', 'Hybrid GitHub ceiling must be below 100 MiB');
|
|
39
|
+
} else if (githubExtensions !== undefined || maxGithubBytes !== undefined) fail('INVALID', 'Routing fields require hybrid mode');
|
|
40
|
+
keys(s.backup, ['mode', 'connection', 'destination']);
|
|
41
|
+
if (!['off', 'external'].includes(s.backup.mode)) fail('INVALID', 'Backup is off or an explicit external tool destination');
|
|
42
|
+
if (s.backup.mode === 'external') { ref(s.backup.connection); ref(s.backup.destination); }
|
|
43
|
+
else if (s.backup.connection !== undefined || s.backup.destination !== undefined) fail('INVALID', 'Disabled backup cannot specify a destination');
|
|
44
|
+
if (s.indexing !== undefined) {
|
|
45
|
+
keys(s.indexing, ['mode']);
|
|
46
|
+
if (!['keyword', 'semantic'].includes(s.indexing.mode)) fail('INVALID', 'Indexing mode must be keyword or semantic');
|
|
47
|
+
}
|
|
48
|
+
return s;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function rootDir(root, create = false) {
|
|
52
|
+
if (!path.isAbsolute(root)) fail('INVALID', 'State directory must be absolute');
|
|
53
|
+
if (create) await fs.mkdir(root, { recursive: true, mode: 0o700 });
|
|
54
|
+
const stat = await fs.lstat(root);
|
|
55
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) fail('UNSAFE_PATH', 'State must be a real private directory');
|
|
56
|
+
return fs.realpath(root);
|
|
57
|
+
}
|
|
58
|
+
export async function safePath(root, relative, makeParents = false) {
|
|
59
|
+
if (typeof relative !== 'string' || !relative || relative.length > 1024 || /[\\\x00-\x1f\x7f]/.test(relative) || relative.split('/').some(p => !p || p.startsWith('.'))) fail('UNSAFE_PATH', 'Use a relative path without hidden, empty or parent components');
|
|
60
|
+
const parts = relative.split('/');
|
|
61
|
+
let target = root;
|
|
62
|
+
for (let i = 0; i < parts.length; i++) {
|
|
63
|
+
target = path.join(target, parts[i]);
|
|
64
|
+
if (makeParents && i < parts.length - 1) await fs.mkdir(target, { mode: 0o700 }).catch(e => { if (e.code !== 'EEXIST') throw e; });
|
|
65
|
+
const st = await fs.lstat(target).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
|
|
66
|
+
if (st && (st.isSymbolicLink() || (i < parts.length - 1 ? !st.isDirectory() : !st.isFile()))) fail('UNSAFE_PATH', 'Symlinks and special files are unsupported');
|
|
67
|
+
}
|
|
68
|
+
return target;
|
|
69
|
+
}
|
|
70
|
+
export async function initialize(root) {
|
|
71
|
+
root = await rootDir(root, true);
|
|
72
|
+
for (const name of ['files', 'operations', 'history', 'tmp', 'qmd']) {
|
|
73
|
+
const dir = path.join(root, name);
|
|
74
|
+
await fs.mkdir(dir, { mode: 0o700 }).catch(e => { if (e.code !== 'EEXIST') throw e; });
|
|
75
|
+
const st = await fs.lstat(dir);
|
|
76
|
+
if (!st.isDirectory() || st.isSymbolicLink()) fail('UNSAFE_PATH', 'Private state directories cannot be symlinks');
|
|
77
|
+
}
|
|
78
|
+
return root;
|
|
79
|
+
}
|
|
80
|
+
export async function locked(root, fn) {
|
|
81
|
+
root = await rootDir(root, true);
|
|
82
|
+
const lock = path.join(root, '.writer-lock');
|
|
83
|
+
await fs.mkdir(lock, { mode: 0o700 }).catch(e => {
|
|
84
|
+
if (e.code === 'EEXIST') fail('BUSY', 'Writer lock exists; confirm no command is active before recovering an interrupted operation');
|
|
85
|
+
throw e;
|
|
86
|
+
});
|
|
87
|
+
try { return await fn(await initialize(root)); }
|
|
88
|
+
finally { await fs.rmdir(lock); }
|
|
89
|
+
}
|
|
90
|
+
export async function digest(file) {
|
|
91
|
+
const handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
92
|
+
try {
|
|
93
|
+
const st = await handle.stat();
|
|
94
|
+
if (!st.isFile()) fail('UNSAFE_PATH', 'Expected a regular file');
|
|
95
|
+
const sha = createHash('sha256'); let bytes = 0;
|
|
96
|
+
for await (const chunk of handle.createReadStream({ autoClose: false })) { sha.update(chunk); bytes += chunk.length; }
|
|
97
|
+
return { bytes, sha256: sha.digest('hex') };
|
|
98
|
+
} finally { await handle.close(); }
|
|
99
|
+
}
|
|
100
|
+
async function current(file) { return digest(file).catch(e => { if (e.code === 'ENOENT') return null; throw e; }); }
|
|
101
|
+
export async function atomic(file, data) {
|
|
102
|
+
const temp = `${file}.${randomUUID()}.tmp`;
|
|
103
|
+
try { await fs.writeFile(temp, data, { mode: 0o600, flag: 'wx' }); await fs.rename(temp, file); }
|
|
104
|
+
finally { await fs.rm(temp, { force: true }); }
|
|
105
|
+
}
|
|
106
|
+
const jsonBytes = value => Buffer.from(JSON.stringify(value, null, 2) + '\n');
|
|
107
|
+
function operationPath(root, key) {
|
|
108
|
+
if (typeof key !== 'string' || !/^[A-Za-z0-9:_-]{1,128}$/.test(key)) fail('INVALID', 'Supply a stable --key using letters, digits, colon, underscore or hyphen');
|
|
109
|
+
return path.join(root, 'operations', hash(key) + '.json');
|
|
110
|
+
}
|
|
111
|
+
export async function settings(root) {
|
|
112
|
+
const target = await safePath(root, 'settings.json');
|
|
113
|
+
const data = await fs.readFile(target).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
|
|
114
|
+
return { settings: data ? validateSettings(JSON.parse(data)) : defaults(), sha256: data ? hash(data) : null };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// Receipts record intent before installation. Readback determines stored/changed/missing,
|
|
118
|
+
// including after interruption between the atomic receipt and file renames.
|
|
119
|
+
export async function put(root, relative, input, { key, expected, kind = 'file', maxBytes = MAX_FILE_BYTES } = {}) {
|
|
120
|
+
if (expected !== 'new' && !/^[a-f0-9]{64}$/.test(expected || '')) fail('INVALID', 'Supply --expected new or the current SHA-256');
|
|
121
|
+
if (!['file', 'settings'].includes(kind)) fail('INVALID', 'Unknown write kind');
|
|
122
|
+
return locked(root, async root => {
|
|
123
|
+
const receiptFile = operationPath(root, key);
|
|
124
|
+
await safePath(root, path.relative(root, receiptFile));
|
|
125
|
+
if (kind === 'file' && (typeof relative !== 'string' || !relative)) fail('INVALID', 'Supply a relative file path');
|
|
126
|
+
const target = await safePath(root, kind === 'settings' ? 'settings.json' : 'files/' + relative, true);
|
|
127
|
+
const temp = path.join(root, 'tmp', randomUUID());
|
|
128
|
+
let bytes = 0; const sha = createHash('sha256');
|
|
129
|
+
try {
|
|
130
|
+
await pipeline(input, new Transform({ transform(chunk, encoding, cb) {
|
|
131
|
+
bytes += chunk.length;
|
|
132
|
+
if (bytes > maxBytes) return cb(new LibraryError('TOO_LARGE', `Input exceeds ${maxBytes} bytes`));
|
|
133
|
+
sha.update(chunk); cb(null, chunk);
|
|
134
|
+
} }), createWriteStream(temp, { flags: 'wx', mode: 0o600 }));
|
|
135
|
+
const request = { kind, path: kind === 'settings' ? 'settings.json' : relative, bytes, sha256: sha.digest('hex'), expected };
|
|
136
|
+
const oldReceipt = await fs.readFile(receiptFile, 'utf8').then(JSON.parse).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
|
|
137
|
+
if (oldReceipt && JSON.stringify(oldReceipt) !== JSON.stringify(request)) fail('KEY_REUSED', 'Operation key was already used with different content or preconditions');
|
|
138
|
+
const before = await current(target);
|
|
139
|
+
if (oldReceipt && before?.sha256 === request.sha256) return { ...request, state: 'stored', replay: true };
|
|
140
|
+
if (expected === 'new' ? before !== null : before?.sha256 !== expected) fail('CONFLICT', 'File changed; re-read before replacing');
|
|
141
|
+
if (before) {
|
|
142
|
+
const history = await safePath(root, 'history/' + before.sha256);
|
|
143
|
+
await fs.copyFile(target, history, constants.COPYFILE_EXCL).catch(e => { if (e.code !== 'EEXIST') throw e; });
|
|
144
|
+
await fs.chmod(history, 0o600);
|
|
145
|
+
}
|
|
146
|
+
await atomic(receiptFile, jsonBytes(request));
|
|
147
|
+
await fs.rename(temp, target);
|
|
148
|
+
const after = await digest(target);
|
|
149
|
+
if (after.sha256 !== request.sha256) fail('UNCERTAIN', 'Write readback differs; inspect operation before retry');
|
|
150
|
+
return { ...request, state: 'stored', replay: false };
|
|
151
|
+
} finally { await fs.rm(temp, { force: true }); }
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
export async function operation(root, key) {
|
|
155
|
+
const receiptFile = await safePath(root, path.relative(root, operationPath(root, key)));
|
|
156
|
+
const receipt = JSON.parse(await fs.readFile(receiptFile, 'utf8'));
|
|
157
|
+
if (['move', 'remove'].includes(receipt.kind)) {
|
|
158
|
+
const source = await current(await safePath(root, 'files/' + receipt.path));
|
|
159
|
+
const target = receipt.to ? await current(await safePath(root, 'files/' + receipt.to)) : null;
|
|
160
|
+
return { ...receipt, state: source ? 'source-present' : receipt.kind === 'remove' ? 'removed' : target?.sha256 === receipt.expected ? 'moved' : 'changed' };
|
|
161
|
+
}
|
|
162
|
+
if (!['file', 'settings'].includes(receipt.kind)) fail('INVALID', 'Invalid operation receipt');
|
|
163
|
+
const file = await safePath(root, receipt.kind === 'settings' ? 'settings.json' : 'files/' + receipt.path);
|
|
164
|
+
const now = await current(file);
|
|
165
|
+
return { ...receipt, state: !now ? 'missing' : now.sha256 === receipt.sha256 ? 'stored' : 'changed' };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export async function organize(root, { path: relative, to, expected, key }) {
|
|
169
|
+
if (!/^[a-f0-9]{64}$/.test(expected || '')) fail('INVALID', 'Supply the current source SHA-256');
|
|
170
|
+
if (relative === 'LIBRARY_SYNC_ACCESS' || to === 'LIBRARY_SYNC_ACCESS') fail('INVALID', 'The sync access marker is reserved');
|
|
171
|
+
return locked(root, async root => {
|
|
172
|
+
const source = await safePath(root, 'files/' + relative);
|
|
173
|
+
const target = to === undefined ? null : await safePath(root, 'files/' + to, true);
|
|
174
|
+
if (target === source) fail('INVALID', 'Source and destination must differ');
|
|
175
|
+
const receipt = { kind: target ? 'move' : 'remove', path: relative, ...(target ? { to } : {}), expected };
|
|
176
|
+
const file = await safePath(root, path.relative(root, operationPath(root, key)));
|
|
177
|
+
const old = await fs.readFile(file, 'utf8').then(JSON.parse).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
|
|
178
|
+
if (old && JSON.stringify(old) !== JSON.stringify(receipt)) fail('KEY_REUSED', 'Operation key belongs to a different request');
|
|
179
|
+
if (old) {
|
|
180
|
+
const observed = await operation(root, key);
|
|
181
|
+
if (['moved', 'removed'].includes(observed.state)) return { ...observed, replay: true };
|
|
182
|
+
}
|
|
183
|
+
const before = await current(source);
|
|
184
|
+
if (before?.sha256 !== expected || (target && await current(target))) fail('CONFLICT', 'Source changed or destination exists; read both paths before organizing');
|
|
185
|
+
const history = await safePath(root, 'history/' + expected);
|
|
186
|
+
await fs.copyFile(source, history, constants.COPYFILE_EXCL).catch(e => { if (e.code !== 'EEXIST') throw e; });
|
|
187
|
+
await fs.chmod(history, 0o600);
|
|
188
|
+
await atomic(file, jsonBytes(receipt));
|
|
189
|
+
if (target) await fs.rename(source, target); else await fs.unlink(source);
|
|
190
|
+
return { ...await operation(root, key), replay: false };
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
export async function list(root, prefix = '', limit = 100) {
|
|
194
|
+
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 1000) fail('INVALID', 'Limit must be 1..1000');
|
|
195
|
+
if (prefix && (prefix.startsWith('/') || prefix.includes('..') || /[\\\x00-\x1f]/.test(prefix))) fail('UNSAFE_PATH', 'Invalid prefix');
|
|
196
|
+
const files = []; let truncated = false;
|
|
197
|
+
async function visit(dir, relative = '') {
|
|
198
|
+
for (const item of (await fs.readdir(dir, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
199
|
+
if (item.name.startsWith('.')) continue;
|
|
200
|
+
if (item.isSymbolicLink()) fail('UNSAFE_PATH', 'Symlink found in library');
|
|
201
|
+
const rel = relative ? relative + '/' + item.name : item.name;
|
|
202
|
+
if (item.isDirectory() && (rel.startsWith(prefix) || prefix.startsWith(rel + '/'))) await visit(path.join(dir, item.name), rel);
|
|
203
|
+
else if (item.isFile() && rel.startsWith(prefix)) {
|
|
204
|
+
if (files.length === limit) { truncated = true; return; }
|
|
205
|
+
const st = await fs.stat(path.join(dir, item.name)); files.push({ path: rel, bytes: st.size });
|
|
206
|
+
}
|
|
207
|
+
if (truncated) return;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
const directory = path.join(await rootDir(root), 'files');
|
|
211
|
+
if ((await fs.lstat(directory)).isSymbolicLink()) fail('UNSAFE_PATH', 'Library root cannot be a symlink');
|
|
212
|
+
await visit(directory); return { files, truncated };
|
|
213
|
+
}
|
|
214
|
+
export { createReadStream, jsonBytes };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { setTimeout } from 'node:timers/promises';
|
|
2
|
+
import { syncRun, syncStatus } from './sync.mjs';
|
|
3
|
+
import { locked } from './store.mjs';
|
|
4
|
+
import { refreshIndex } from './indexer.mjs';
|
|
5
|
+
import { embeddingStatus } from './embedding-client.mjs';
|
|
6
|
+
import { catalog, libraryRoot } from './libraries.mjs';
|
|
7
|
+
|
|
8
|
+
// One resident supervisor, no LLM polling or provider transport implementation.
|
|
9
|
+
// Native bisync owns deltas, conflicts, receipts, and recovery. The same Library
|
|
10
|
+
// writer lock serializes CLI writes, transfers, and QMD refresh.
|
|
11
|
+
const root = process.env.EZ_LIBRARY_STATE || '/state';
|
|
12
|
+
let stopping = false;
|
|
13
|
+
const controller = new AbortController();
|
|
14
|
+
process.on('SIGTERM', () => { stopping = true; controller.abort(); });
|
|
15
|
+
process.on('SIGINT', () => { stopping = true; controller.abort(); });
|
|
16
|
+
const due = new Map();
|
|
17
|
+
while (!stopping) {
|
|
18
|
+
let interval = 60;
|
|
19
|
+
try {
|
|
20
|
+
for (const { name } of (await catalog(root)).libraries) {
|
|
21
|
+
if (stopping) break;
|
|
22
|
+
try {
|
|
23
|
+
const selected = await libraryRoot(root, name);
|
|
24
|
+
const { config } = await syncStatus(selected);
|
|
25
|
+
if (config?.mode !== 'two-way') {
|
|
26
|
+
due.delete(name);
|
|
27
|
+
if ((await embeddingStatus()).state === 'ready') await locked(selected, refreshIndex);
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if ((due.get(name) || 0) <= Date.now()) {
|
|
31
|
+
try { await syncRun(selected, root); }
|
|
32
|
+
finally { due.set(name, Date.now() + config.intervalSeconds * 1000); }
|
|
33
|
+
}
|
|
34
|
+
interval = Math.min(interval, Math.max(1, ((due.get(name) || 0) - Date.now()) / 1000));
|
|
35
|
+
} catch (error) {
|
|
36
|
+
process.stderr.write(JSON.stringify({ event: 'library-sync', library: name, code: error.code || 'UNAVAILABLE', message: error.message }) + '\n');
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
} catch (error) {
|
|
40
|
+
process.stderr.write(JSON.stringify({ event: 'library-sync', code: error.code || 'UNAVAILABLE', message: error.message }) + '\n');
|
|
41
|
+
}
|
|
42
|
+
if (!stopping) await setTimeout(interval * 1000, undefined, { signal: controller.signal }).catch(() => {});
|
|
43
|
+
}
|